mirror of
https://github.com/appium/appium.git
synced 2026-11-17 16:15:21 +08:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31bc9f1f8c | ||
|
|
091fd320b9 | ||
|
|
d27977d33c | ||
|
|
b2ce3a0f80 | ||
|
|
9f7743443c | ||
|
|
2109f8ca84 | ||
|
|
d8a87be02a | ||
|
|
67a1abfea9 | ||
|
|
0b85f158e1 | ||
|
|
b3ee58d357 | ||
|
|
6351d119f7 | ||
|
|
6081d41388 |
Generated
+34
-57
@@ -31,7 +31,7 @@
|
||||
"@types/semver": "7.8.0",
|
||||
"@types/serve-favicon": "2.5.7",
|
||||
"@types/shell-quote": "1.7.5",
|
||||
"@types/sinon": "22.0.0",
|
||||
"@types/sinon": "22.0.2",
|
||||
"@types/which": "3.0.4",
|
||||
"@types/ws": "8.18.2",
|
||||
"@types/yargs": "17.0.35",
|
||||
@@ -5057,22 +5057,15 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/sinon": {
|
||||
"version": "22.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/sinon/-/sinon-22.0.0.tgz",
|
||||
"integrity": "sha512-TDbVpbccc2HfiqHR09Argj3mHV1KMW7sCCKj52fsl8lbRLkEn7fB1966EWhOKWUBcqfBueZuPoA7/OK1CKiy3g==",
|
||||
"version": "22.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/sinon/-/sinon-22.0.2.tgz",
|
||||
"integrity": "sha512-2qLRFlluKkn6mci189eKhlOsHcdFpsn/9+29S4VmwKCpfb+vseKrZSSOSy5259yzIpP/y4gLfqQfIIR/lZn4Ng==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/sinonjs__fake-timers": "*"
|
||||
"@sinonjs/fake-timers": "^15.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/sinonjs__fake-timers": {
|
||||
"version": "15.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/sinonjs__fake-timers/-/sinonjs__fake-timers-15.0.1.tgz",
|
||||
"integrity": "sha512-Ko2tjWJq8oozHzHV+reuvS5KYIRAokHnGbDwGh/J64LntgpbuylF74ipEL24HCyRjf9FOlBiBHWBR1RlVKsI1w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/triple-beam": {
|
||||
"version": "1.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz",
|
||||
@@ -6783,22 +6776,6 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser/node_modules/qs": {
|
||||
"version": "6.16.1",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.1.tgz",
|
||||
"integrity": "sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"es-define-property": "^1.0.1",
|
||||
"side-channel": "^1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/boolbase": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
|
||||
@@ -10552,9 +10529,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/fast-xml-parser": {
|
||||
"version": "5.11.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.11.2.tgz",
|
||||
"integrity": "sha512-R9iDuNrQYeQut46cn2r2wHKn4HYzVDvDm5J1wW+koZewykv0yuO2HChTYeZtrULyHIDM9cj9TUXloCsueCQUog==",
|
||||
"version": "5.12.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.12.0.tgz",
|
||||
"integrity": "sha512-/pXxRBtwxY9w8z7YbgsvIPPcPvFDsTbIkWwTQJhzNJPokj+TbN6ftmcv4j/pEQDvOCNnKGDzuk5Bo2oogIOiFg==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -10563,11 +10540,11 @@
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@nodable/entities": "^3.0.1",
|
||||
"fast-xml-builder": "^1.2.0",
|
||||
"is-unsafe": "^2.0.0",
|
||||
"@nodable/entities": "^3.1.0",
|
||||
"fast-xml-builder": "^1.3.1",
|
||||
"is-unsafe": "^2.0.3",
|
||||
"path-expression-matcher": "^1.6.2",
|
||||
"strnum": "^2.4.2",
|
||||
"strnum": "^2.5.1",
|
||||
"xml-naming": "^0.3.0"
|
||||
},
|
||||
"bin": {
|
||||
@@ -12076,9 +12053,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/is-unsafe": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/is-unsafe/-/is-unsafe-2.0.2.tgz",
|
||||
"integrity": "sha512-HgbIHPBH0KHHCcjLfGsCvhtPTVxjaAZlXjwdz7/GQC40SjSe4sfQsar8J5VFo8JOSbarkpV0OLG95bbaNd9aAQ==",
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/is-unsafe/-/is-unsafe-2.0.3.tgz",
|
||||
"integrity": "sha512-ZBllczCCO267vgdFb6Tq3pv+LhHaCiGMdr+ZsuL+OopruAg7S+3ZDs1vD0RPC0uSrkjzbraxaGjtX1YBxjPeFQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -17608,9 +17585,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.16.0",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",
|
||||
"integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==",
|
||||
"version": "6.17.0",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.17.0.tgz",
|
||||
"integrity": "sha512-5LK5BZ2XDHMvcUJaf0CQ5HL3aVgKbpklvByC7qLSxYkfE8COEEbJg5xCHWCTqzqi0Gs4Jn5Mv5v3R38W6edscA==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"es-define-property": "^1.0.1",
|
||||
@@ -19784,9 +19761,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/strnum": {
|
||||
"version": "2.4.2",
|
||||
"resolved": "https://registry.npmjs.org/strnum/-/strnum-2.4.2.tgz",
|
||||
"integrity": "sha512-rDG3Ah4TV0k1hWvLSzkZtMmLN9+eS+h3knq4MP6A42Y3Yh5qGNnOUs1jJkoSr8FG5dsL28c7KgkIBzSEykqtuw==",
|
||||
"version": "2.5.1",
|
||||
"resolved": "https://registry.npmjs.org/strnum/-/strnum-2.5.1.tgz",
|
||||
"integrity": "sha512-UM4nTLWzQiDBseVxUGxN0wJzIk0UU89Qi7pKXz9qISo+lhviJikTuikBsK/oFRlpvYHvSdz0TVoLyQ+sEpYwxA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -21662,13 +21639,13 @@
|
||||
}
|
||||
},
|
||||
"packages/appium": {
|
||||
"version": "3.9.0",
|
||||
"version": "3.9.1",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@appium/base-driver": "10.8.2",
|
||||
"@appium/base-plugin": "3.3.6",
|
||||
"@appium/docutils": "3.0.2",
|
||||
"@appium/base-driver": "10.8.3",
|
||||
"@appium/base-plugin": "3.3.7",
|
||||
"@appium/docutils": "3.0.3",
|
||||
"@appium/logger": "2.0.12",
|
||||
"@appium/schema": "1.3.0",
|
||||
"@appium/support": "7.2.9",
|
||||
@@ -21730,7 +21707,7 @@
|
||||
},
|
||||
"packages/base-driver": {
|
||||
"name": "@appium/base-driver",
|
||||
"version": "10.8.2",
|
||||
"version": "10.8.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@appium/support": "7.2.9",
|
||||
@@ -21759,10 +21736,10 @@
|
||||
},
|
||||
"packages/base-plugin": {
|
||||
"name": "@appium/base-plugin",
|
||||
"version": "3.3.6",
|
||||
"version": "3.3.7",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@appium/base-driver": "10.8.2",
|
||||
"@appium/base-driver": "10.8.3",
|
||||
"@appium/support": "7.2.9",
|
||||
"@appium/types": "1.7.2"
|
||||
},
|
||||
@@ -21773,7 +21750,7 @@
|
||||
},
|
||||
"packages/docutils": {
|
||||
"name": "@appium/docutils",
|
||||
"version": "3.0.2",
|
||||
"version": "3.0.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@appium/support": "7.2.9",
|
||||
@@ -21948,7 +21925,7 @@
|
||||
},
|
||||
"packages/execute-driver-plugin": {
|
||||
"name": "@appium/execute-driver-plugin",
|
||||
"version": "7.0.2",
|
||||
"version": "7.0.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@appium/support": "7.2.9",
|
||||
@@ -21984,10 +21961,10 @@
|
||||
},
|
||||
"packages/fake-plugin": {
|
||||
"name": "@appium/fake-plugin",
|
||||
"version": "4.4.2",
|
||||
"version": "4.4.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@appium/base-plugin": "3.3.6",
|
||||
"@appium/base-plugin": "3.3.7",
|
||||
"@appium/support": "7.2.9",
|
||||
"asyncbox": "6.5.0"
|
||||
},
|
||||
@@ -22267,12 +22244,12 @@
|
||||
},
|
||||
"packages/universal-xml-plugin": {
|
||||
"name": "@appium/universal-xml-plugin",
|
||||
"version": "3.0.2",
|
||||
"version": "3.0.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@appium/support": "7.2.9",
|
||||
"@xmldom/xmldom": "0.9.12",
|
||||
"fast-xml-parser": "5.11.2",
|
||||
"fast-xml-parser": "5.12.0",
|
||||
"xpath": "0.0.35"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
+1
-1
@@ -100,7 +100,7 @@
|
||||
"@types/semver": "7.8.0",
|
||||
"@types/serve-favicon": "2.5.7",
|
||||
"@types/shell-quote": "1.7.5",
|
||||
"@types/sinon": "22.0.0",
|
||||
"@types/sinon": "22.0.2",
|
||||
"@types/which": "3.0.4",
|
||||
"@types/ws": "8.18.2",
|
||||
"@types/yargs": "17.0.35",
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## [3.9.1](https://github.com/appium/appium/compare/appium@3.9.0...appium@3.9.1) (2026-11-14)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **execute-driver-plugin:** wrap non-configurable property descriptors via shadow target ([#23126](https://github.com/appium/appium/issues/23126)) ([b2ce3a0](https://github.com/appium/appium/commit/b2ce3a0f8074506a7b3eff2df15e0ac37999999a))
|
||||
|
||||
|
||||
## [3.9.0](https://github.com/appium/appium/compare/appium@3.8.0...appium@3.9.0) (2026-10-27)
|
||||
|
||||
### Features
|
||||
|
||||
@@ -46,7 +46,7 @@ contributors!
|
||||
## Gold Sponsors
|
||||
|
||||
<div class="sponsor-section">
|
||||
<a href="https://jetify.com/" target="_blank"><img src="https://images.opencollective.com/jetify/415824c/avatar/64.png" alt="Jetify" /></a>
|
||||
<a href="https://device.io/" target="_blank"><img src="https://images.opencollective.com/device-io/cc7e949/avatar/64.png" alt="Device.io" /></a>
|
||||
</div>
|
||||
|
||||
[Become a Gold Sponsor](https://opencollective.com/appium/contribute/gold-sponsor-72877/checkout?interval=month&amount=500&contributeAs=me)
|
||||
|
||||
@@ -140,3 +140,17 @@ Supported by: `@domovou69`
|
||||
```sh title="Install This Tool"
|
||||
npm install -g xpath-to-class-chain
|
||||
```
|
||||
|
||||
### [XPath to UiSelector](https://github.com/domovou69/xpath-to-uiselector)
|
||||
|
||||
XPath to UiSelector is a command-line tool for migrating Android XPath locators in test code to
|
||||
`-android uiautomator` selectors. It converts the XPaths that have an exact `UiSelector`
|
||||
equivalent, converts with a warning those that only have a close one (such as `//A//B`), and skips
|
||||
the rest with a reason. The strategy call is rewritten together with the string, for example
|
||||
`AppiumBy.xpath` becomes `AppiumBy.androidUIAutomator`.
|
||||
|
||||
Supported by: `@domovou69`
|
||||
|
||||
```sh title="Install This Tool"
|
||||
npm install -g xpath-to-uiselector
|
||||
```
|
||||
|
||||
@@ -45,7 +45,7 @@ contributors!
|
||||
|
||||
## Gold Sponsors
|
||||
|
||||
<div class="sponsor-section"><a href="https://jetify.com/" target="_blank"><img src="https://images.opencollective.com/jetify/415824c/avatar/64.png" alt="Jetify" /></a>
|
||||
<div class="sponsor-section"><a href="https://device.io/" target="_blank"><img src="https://images.opencollective.com/device-io/cc7e949/avatar/64.png" alt="Device.io" /></a>
|
||||
</div>
|
||||
|
||||
[Become a Gold Sponsor](https://opencollective.com/appium/contribute/gold-sponsor-72877/checkout?interval=month&amount=500&contributeAs=me)
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 37 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 49 KiB |
@@ -1,62 +1,39 @@
|
||||
---
|
||||
title: Building Drivers
|
||||
title: 开发驱动
|
||||
---
|
||||
|
||||
Appium wants to make it easy for anyone to develop their own automation drivers as part of the
|
||||
Appium ecosystem. This guide will explain what's involved and how you can accomplish various driver
|
||||
development tasks using the tools Appium provides. This guide assumes you (1) are a competent user of
|
||||
Appium, (2) are a competent Node.js developer, and (3) that you have read and understood the
|
||||
[Driver Intro](../intro/drivers.md).
|
||||
Appium 希望让任何人都能在 Appium 生态系统中开发自己的自动化驱动。本指南将介绍其中涉及的工作,以及如何使用 Appium 提供的工具完成各种驱动开发任务。阅读本指南的前提是你:(1)能熟练使用 Appium,(2)是一名合格的 Node.js 开发者,(3)已经阅读并理解了[驱动介绍](../intro/drivers.md)。
|
||||
|
||||
If that describes you, great! This guide will get you started.
|
||||
如果你符合这些描述,太好了!本指南将带你入门。
|
||||
|
||||
## Before you create your driver
|
||||
## 创建驱动之前
|
||||
|
||||
Before you get to work implementing your driver, it's important to have a few things sorted out.
|
||||
For example, you need to know what your driver will do. Which platform is it trying to expose
|
||||
WebDriver automation for?
|
||||
在动手实现你的驱动之前,先把几件事理清楚很重要。例如,你需要知道你的驱动要做什么。它为哪个平台提供 WebDriver 自动化能力。
|
||||
|
||||
Appium doesn't magically give you the power to automate any platform. All it does is give you a set
|
||||
of convenient tools for implementing the WebDriver Protocol. So if you want to create, for example,
|
||||
a driver for a new app platform, you'll need to know how to automate apps on that platform _without Appium_.
|
||||
Appium 并不会凭空赋予你自动化任何平台的能力。它所做的只是提供一套便捷的工具,帮你实现 WebDriver 协议。所以,如果你想为一个新的应用平台创建驱动,你需要先知道如何_不借助Appium_在该平台上自动化应用。
|
||||
|
||||
This usually means that you need to be very familiar with app development for a given platform. And
|
||||
it usually means that you will rely on tools or SDKs provided by the platform vendor.
|
||||
这通常意味着你必须非常熟悉某个平台的应用开发,而且往往要依赖该平台厂商提供的工具或 SDK。
|
||||
|
||||
Basically, if you can't answer the question **"how would I launch, remotely trigger behaviours, and
|
||||
read state from an app on this platform?" then you're not quite ready to write an Appium driver**.
|
||||
Make sure you do the research to feel comfortable that there _is_ a path forward. Once there is,
|
||||
coding it up and making it available as an Appium driver should be the easy part!
|
||||
如果你无法回答这个问题——**"我该如何在这个平台上启动应用、远程触发应用行为并读取应用状态?"——那么你还不太适合开始编写 Appium 驱动**。请先做好调研,确认确实_有_可行的路径再继续。一旦路径清晰,把它编码实现并做成一个 Appium 驱动就简单多了!
|
||||
|
||||
## Other drivers to reference
|
||||
## 可供参考的其他驱动
|
||||
|
||||
One of the greatest things about building an Appium driver is that there are already a number of
|
||||
open source Appium drivers which you can look at for reference. There is
|
||||
a [fake-driver](https://github.com/appium/appium/tree/master/packages/fake-driver) sample driver which
|
||||
does basically nothing other than showcase some of the things described in this guide.
|
||||
构建 Appium 驱动最棒的一点是:已经有许多开源的 Appium 驱动可供参考。其中有一个fake-driver](https://github.com/appium/appium/tree/master/packages/fake-driver) 示例驱动,它几乎不
|
||||
做任何实际事情,只用来演示本指南中提到的若干要点。
|
||||
|
||||
And of course, all of Appium's official drivers are open source and available in repositories at
|
||||
the project's GitHub organization. So if you ever find yourself asking, "how does a driver do X?",
|
||||
read the code for these drivers! Also don't be afraid to ask questions of the Appium developers if
|
||||
you get stuck; we're always happy to help make sure the driver development experience is a good
|
||||
one!
|
||||
当然,Appium 的所有官方驱动都是开源的,可以在项目的 GitHub 组织的仓库中找到。所以如果你正在思考"驱动是怎么实现 X 的?",去读这些驱动的源码吧!如果你在开发中遇到卡壳的地方,也尽管向 Appium 开发者们提问,我们总是乐于提供帮助,确保你的驱动开发体验顺畅!
|
||||
|
||||
## Basic requirements for Appium drivers
|
||||
## Appium 驱动的基本要求
|
||||
|
||||
These are the things your driver _must_ do (or be), if you want it to be a valid Appium driver.
|
||||
如果你想让某个东西成为一个合法的 Appium 驱动,以下是它_必须_做到(或满足)的事情。
|
||||
|
||||
### Node.js package with Appium extension metadata
|
||||
### 带 Appium 扩展元数据的 Node.js 包
|
||||
|
||||
All Appium drivers are fundamentally Node.js packages, and therefore must have a valid
|
||||
`package.json`. Your driver is not _limited_ to Node.js, but it must provide an adapter written in Node.js so it can be loaded by Appium.
|
||||
所有 Appium 驱动本质上都是 Node.js 包,因此必须有一个合法的 `package.json`。你的驱动并不_局限_于用 Node.js 编写,但它必须提供一个用 Node.js 编写的适配器,以便 Appium 能够加载它。
|
||||
|
||||
Your `package.json` must include `appium` as a `peerDependency`. The requirements for the
|
||||
dependency versions should be as loose as possible (unless you happen to know your driver will only
|
||||
work with certain versions of Appium). For Appium 2, for example, this would look something like
|
||||
`^2.0.0`, declaring that your driver works with any version of Appium that starts with 2.x.
|
||||
你的 `package.json` 必须将 `appium` 声明为 `peerDependency`。对依赖版本的要求应尽量宽松(除非你明确知道你的驱动只能与某些特定版本的 Appium 配合工作)。以 Appium 2 为例,写成`^2.0.0` 即可,表示你的驱动兼容所有 2.x 版本的 Appium。
|
||||
|
||||
Your `package.json` must contain an `appium` field, like this (we call this the 'Appium extension
|
||||
metadata'):
|
||||
你的 `package.json` 必须包含一个 `appium` 字段,如下所示(我们称之为"Appium 扩展元数据"):
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -73,26 +50,16 @@ metadata'):
|
||||
}
|
||||
```
|
||||
|
||||
The required subfields are:
|
||||
必需的子字段如下:
|
||||
|
||||
- `driverName`: this should be a short name for your driver.
|
||||
- `automationName`: this should be the string users will use for their `appium:automationName`
|
||||
capability to tell Appium to use _your_ driver.
|
||||
- `platformNames`: this is an array of one or more platform names considered valid for your driver.
|
||||
When a user sends in the `platformName` capability to start a session, it must be included in
|
||||
this list for your driver to handle the session. These names should generally include the
|
||||
operating systems your driver is targeting - for example, a driver targeting iOS would include
|
||||
`iOS`, while a driver targeting the Chrome browser on Windows would include `Windows`.
|
||||
- `mainClass`: this is a named export (in CommonJS style) from your `main` field. It must be a
|
||||
class which extends Appium's `BaseDriver` (see below).
|
||||
- `driverName`:你的驱动的简短名称。
|
||||
- `automationName`:用户在 `appium:automationName` 能力中填写的字符串,用于让 Appium 使用_你的_驱动。
|
||||
- `platformNames`:一个数组,包含你的驱动认为合法的一个或多个平台名称。当用户发起会话并传入 `platformName` 能力时,该值必须在此列表中,你的驱动才会处理该会话。这些名称通常应包含你的驱动所面向的操作系统——例如,面向 iOS 的驱动应包含 `iOS`,而面向 Windows 上 Chrome 浏览器的驱动应包含 `Windows`。
|
||||
- `mainClass`:从 `main` 字段具名导出(CommonJS 风格)的类。它必须是继承自 Appium 的 `BaseDriver` 的类(见下文)。
|
||||
|
||||
### Extend Appium's `BaseDriver` class
|
||||
### 继承 Appium 的 `BaseDriver` 类
|
||||
|
||||
Ultimately, your driver is much easier to write because most of the hard work of implementing the
|
||||
WebDriver protocol and handling certain common logic is taken care of already by Appium. This is
|
||||
all encoded up as a class which Appium exports for you to use, called `BaseDriver`. It is exported
|
||||
from `appium/driver`, so you can use one of these styles to import it and create your _own_ class
|
||||
that extends it:
|
||||
归根结底,你的驱动之所以好写,是因为实现 WebDriver 协议以及处理某些通用逻辑的繁重工作已经由 Appium 代劳了。这一切都封装在一个 Appium 导出的类中,名为 `BaseDriver`。它从 `appium/driver` 导出,你可以用下面任一方式导入它,并创建继承它的_你自己的_类:
|
||||
|
||||
```js
|
||||
import {BaseDriver} from 'appium/driver';
|
||||
@@ -102,32 +69,25 @@ export class MyDriver extends BaseDriver {
|
||||
}
|
||||
```
|
||||
|
||||
### Make your driver available
|
||||
### 让你的驱动可用
|
||||
|
||||
That's basically it! With a Node.js package exporting a driver class and with correct Appium
|
||||
extension metadata, you've got yourself an Appium driver! Now it doesn't _do_ anything, but you can
|
||||
load it up in Appium, start and stop sessions with it, etc...
|
||||
基本就是这样!一个导出驱动类的 Node.js 包,再加上正确的 Appium 扩展元数据,你就拥有了一个Appium 驱动!虽然它还什么都不_做_,但你已经可以在 Appium 中加载它、用它启动和停止会话了……
|
||||
|
||||
To make it available to users, you could publish it via NPM. When you do so, your driver will be
|
||||
installable via the Appium CLI:
|
||||
要让其他用户能用你的驱动,你可以通过 NPM 发布它。发布之后,用户就可以通过 Appium CLI 安装它:
|
||||
|
||||
```
|
||||
appium driver install --source=npm <driver-package-on-npm>
|
||||
```
|
||||
|
||||
It's a good idea to test your driver first, of course. One way to see how it works within Appium is
|
||||
to install it locally first:
|
||||
当然,最好先测试你的驱动。观察它在 Appium 中如何工作,一种方式是以本地方式安装它:
|
||||
|
||||
```
|
||||
appium driver install --source=local /path/to/your/driver
|
||||
```
|
||||
|
||||
### Developing your driver
|
||||
### 驱动的开发流程
|
||||
|
||||
How you develop your driver is up to you. It is convenient, however, to run it from within Appium
|
||||
without having to do lots of publishing and installing. The most straightforward way to do this is
|
||||
to include the most recent version of Appium as a `devDependency`, and then also your own driver,
|
||||
like this:
|
||||
如何开发你的驱动完全由你决定。不过,如何能在 Appium 中直接运行驱动,免去反复发布和安装呢?最直接的做法是把最新版本的 Appium 作为 `devDependency`,同时把你的驱动也作为依赖引入,例如:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -140,37 +100,27 @@ like this:
|
||||
}
|
||||
```
|
||||
|
||||
Now, you can run Appium locally (`npm exec appium` or `npx appium`), and because your driver is
|
||||
listed as a dependency alongside it, it will be automatically "installed" and available. You can
|
||||
design your e2e tests this way, or if you're writing them in Node.js, you can simply import
|
||||
Appium's start server methods to handle starting and stopping the Appium server in Node. (TODO:
|
||||
reference an implementation of this in one of the open source drivers when ready).
|
||||
这样,你就可以在本地运行 Appium(`npm exec appium` 或 `npx appium`),并且由于你的驱动与它并列列为依赖,它会被自动"安装"并可用。你可以按这种方式设计你的 e2e 测试;如果用 Node.js 编写测试,你还可以直接导入 Appium 的启动服务方法,在 Node 中启停 Appium 服务器。 (TODO:待相关实现就绪后,在此引用某个开源驱动的实现。)
|
||||
|
||||
Another way to do local development with an existing Appium server install is to simply install
|
||||
your driver locally:
|
||||
在 Appium 服务器上安装并进行本地开发的另一种方式是直接把驱动以本地源安装:
|
||||
|
||||
```
|
||||
appium driver install --source=local /path/to/your/driver/dev/dir
|
||||
```
|
||||
|
||||
### Refreshing your driver during development
|
||||
### 开发过程中刷新驱动
|
||||
|
||||
When the Appium server starts, it loads your driver into memory. Changes to your driver code will
|
||||
not take effect until the next time the Appium server starts. Simply starting a new session is not
|
||||
sufficient to cause your driver's code to be reloaded.
|
||||
Appium 服务器启动时会将你的驱动加载进内存。驱动代码的修改要到下一次 Appium 服务器启动时才会生效。启动一个新会话并不会以让驱动代码重新加载。
|
||||
|
||||
However, you can set the `APPIUM_RELOAD_EXTENSIONS` environment variable to `1` to request that
|
||||
Appium clear its module cache and reload extensions whenever a new session is requested. This may
|
||||
obviate the need to restart the server when you make code changes to your driver.
|
||||
不过,你可以把环境变量 `APPIUM_RELOAD_EXTENSIONS` 设为 `1`,要求 Appium 在每次收到新会话请求时清除模块缓存并重新加载扩展。这样在修改驱动代码后,也许就不必重启服务器了。
|
||||
|
||||
## Standard driver implementation ideas
|
||||
## 驱动实现的标准思路
|
||||
|
||||
These are things you will probably find yourself wanting to do when creating a driver.
|
||||
以下是创建驱动时你多半会想做的事情。
|
||||
|
||||
### Set up state in a constructor
|
||||
### 在构造函数中初始化状态
|
||||
|
||||
If you define your own constructor, you'll need to call `super` to make sure all the standard state
|
||||
is set up correctly:
|
||||
如果你定义了自己的构造函数,需要调用 `super`,确保所有标准状态被正确初始化:
|
||||
|
||||
```js
|
||||
constructor(...args) {
|
||||
@@ -179,22 +129,15 @@ constructor(...args) {
|
||||
}
|
||||
```
|
||||
|
||||
The `args` parameter here is the object containing all the CLI args used to start the Appium
|
||||
server.
|
||||
这里的 `args` 参数是包含启动 Appium 服务器所用的全部 CLI 参数的对象。
|
||||
|
||||
### Define and validate accepted capabilities
|
||||
### 定义并校验支持的能力
|
||||
|
||||
You can define your own capabilities and basic validation for them. Users will always be able to
|
||||
send in capabilities that you don't define, but if they send in capabilities you have explicitly
|
||||
defined, then Appium will validate that they are of the correct type (and will check for the
|
||||
presence of required capabilities).
|
||||
你可以定义自己的能力并为它们配置基本校验。用户可能调用你未定义的能力;但对于你已明确定义的能力,Appium 会校验其类型是否正确(并检查必填能力是否存在)。
|
||||
|
||||
If you want to turn capability validation off entirely, set `this.shouldValidateCaps` to `false` in
|
||||
your constructor.
|
||||
如果你想关闭校验,只需在构造函数中把 `this.shouldValidateCaps` 设为 `false`。
|
||||
|
||||
To give Appium your validation constraints, set `this.desiredCapConstraints` to a validation object
|
||||
in your constructor. Validation objects can be somewhat complex. Here's an example from the
|
||||
UiAutomator2 driver:
|
||||
要把校验约束提供给 Appium,需要在构造函数中把 `this.desiredCapConstraints` 设为一个校验对象。校验对象可以写得很复杂。下面是 UiAutomator2 驱动的一个例子:
|
||||
|
||||
```js
|
||||
{
|
||||
@@ -214,13 +157,9 @@ UiAutomator2 driver:
|
||||
}
|
||||
```
|
||||
|
||||
### Start a session and read capabilities
|
||||
### 启动会话并读取能力
|
||||
|
||||
Appium's `BaseDriver` already implements the `createSession` command, so you don't have to. However
|
||||
it's very common to need to perform your own startup actions (launching an app, running some
|
||||
platform code, or doing different things based on capabilities you have defined for your driver).
|
||||
So you'll probably end up overriding `createSession`. You can do so by defining the method in your
|
||||
driver:
|
||||
Appium 的 `BaseDriver` 已经实现了 `createSession` 命令,所以你不实现它也可以。但驱动通常需要执行自己的启动动作(启动应用、运行某些平台代码、或根据你为驱动定义的能力做不同的事情)。因此你很可能会去重写 `createSession`。你可以在驱动中定义该方法来实现:
|
||||
|
||||
```js
|
||||
async createSession(w3cCaps) {
|
||||
@@ -230,29 +169,19 @@ async createSession(w3cCaps) {
|
||||
}
|
||||
```
|
||||
|
||||
!!! warning "Deprecated"
|
||||
!!! 警告 “已废弃”
|
||||
|
||||
```
|
||||
Older drivers may still define `createSession` with up to four parameters, e.g.
|
||||
`createSession(jwpCaps, reqCaps, w3cCaps, otherDriverData)`. This shape is a holdover from the
|
||||
retired JSON Wire Protocol, which required desired and required caps as the first two
|
||||
arguments; only the first W3C-shaped argument was ever used. The `otherDriverData` parameter is
|
||||
likewise deprecated in favor of [IPC](#send-messages-to-plugins-running-on-the-same-session) for
|
||||
coordinating with other concurrently-running sessions. New drivers should use the single-argument
|
||||
form shown above.
|
||||
较老的驱动可能仍以最多四个参数定义 createSession,例如createSession(jwpCaps, reqCaps, w3cCaps, otherDriverData)。这种形式是已退役的 JSON Wire Protocol 的遗留产物——它要求前两个参数是期望能力和必须能力,而实际上只有第一个W3C 形式的参数被使用过。otherDriverData 参数同样已被废弃,与其他并行运行会话的协调请改用IPC(见下文"向同一会话中的插件发送消息")。新驱动应使用上面所示的单参数形式。
|
||||
```
|
||||
|
||||
You'll want to make sure to call `super.createSession` in order to get the session ID as well as
|
||||
the processed capabilities (note that capabilities are also set on `this.caps`; modifying `caps`
|
||||
locally here would have no effect other than changing what the user sees in the create session
|
||||
response).
|
||||
你要确保调用 `super.createSession`,以拿到会话 ID 以及处理过的能力(注意:能力同时也被设置在`this.caps` 上;此处仅修改局部变量 `caps`,这只改变用户在创建会话响应中看到的内容,没有其他效果)。
|
||||
|
||||
So that's it! You can fill out the middle section with whatever startup logic your driver requires.
|
||||
就是这样!中间的空白部分由你的驱动所需的启动逻辑来填充。
|
||||
|
||||
### End a session
|
||||
### 结束会话
|
||||
|
||||
If your driver requires any cleanup or shutdown logic, it's best to do it as part of overriding the
|
||||
implementation of `deleteSession`:
|
||||
如果你的驱动需要清理或关闭逻辑,最好的方式是重写 `deleteSession` 实现:
|
||||
|
||||
```js
|
||||
async deleteSession() {
|
||||
@@ -262,33 +191,21 @@ async deleteSession() {
|
||||
}
|
||||
```
|
||||
|
||||
It's very important not to throw any errors here if possible so that all parts of session cleanup
|
||||
can succeed!
|
||||
非常重要的一点是:尽可能不要在这里抛出错误,这样才能让会话清理的每个环节都成功执行!
|
||||
|
||||
### Access capabilities and CLI args
|
||||
### 访问能力与 CLI 参数
|
||||
|
||||
You'll often want to read parameters the user has set for the session, whether as CLI args or as
|
||||
capabilities. The easiest way to do this is to access `this.opts`, which is a merge of all options,
|
||||
from the CLI or from capabilities. So for example to access the `appium:app` capability, you could
|
||||
simply get the value of `this.opts.app`.
|
||||
你可能需要读取用户为会话设置的参数,无论它们是 CLI 参数还是能力。最简单的方式是访问 `this.opts`,它合并了来自 CLI 和能力的全部选项。例如要访问 `appium:app` 能力,直接读取 `this.opts.app` 即可。
|
||||
|
||||
If you care about knowing whether something was sent in as a CLI arg _or_ a capability, you can
|
||||
access the `this.cliArgs` and `this.caps` objects explicitly.
|
||||
如果你想知道某个值究竟是以 CLI 参数_还是_能力传入的,可以显式访问 `this.cliArgs` 和 `this.caps` 对象。
|
||||
|
||||
In all cases, the `appium:` capability prefix will have been stripped away by the time you are
|
||||
accessing values here, for convenience.
|
||||
在所有情况下,为方便起见,当你读取这些值时,`appium:` 能力前缀都已经被剥离掉了。
|
||||
|
||||
### Implement WebDriver classic commands
|
||||
### 实现 WebDriver classic 命令
|
||||
|
||||
You handle WebDriver commands by implementing functions in your driver class. Each member of the
|
||||
WebDriver Protocol, plus the various Appium extensions, has a corresponding function that you
|
||||
implement if you want to support that command in your driver. The best way to see which commands
|
||||
Appium supports and which method you need to implement for each command is to look at Appium's
|
||||
[routes/](https://github.com/appium/appium/tree/master/packages/base-driver/lib/protocol/routes).
|
||||
Each route object in this directory's files tells you the command name as well as the parameters you'd expect to
|
||||
receive for that command.
|
||||
你通过在驱动类中实现函数来处理 WebDriver 命令。 WebDriver 协议的每一个成员,以及 Appium 的各种扩展,都对应一个函数——如果你想支持该命令,就实现它。要了解 Appium 支持哪些命令、每个命令需要实现哪个方法,最好的办法是查看 Appium 的 [routes/](https://github.com/appium/appium/blob/master/packages/base-driver/lib/protocol/routes.js)。该文件中的每个路由对象都会告诉你命令名称以及该命令预期接收的参数。
|
||||
|
||||
Let's take this block for example:
|
||||
比如下面这段:
|
||||
|
||||
```js
|
||||
'/session/:sessionId/url': {
|
||||
@@ -297,10 +214,7 @@ Let's take this block for example:
|
||||
}
|
||||
```
|
||||
|
||||
Here we see that the route `/session/:sessionId/url` is mapped to two commands, one for a `GET`
|
||||
request and one for a `POST` request. If we want to allow our driver to change the "url" (or
|
||||
whatever that might mean for our driver), we can therefore implement the `setUrl` command, knowing
|
||||
it will take the `url` parameter:
|
||||
可以看到路由 `/session/:sessionId/url` 映射到两个命令,一个对应 `GET` 请求,一个对应 `POST` 请求。如果我们想让驱动能够改变 "url",就可以实现 `setUrl` 命令,并知道它会接收 `url` 参数:
|
||||
|
||||
```js
|
||||
async setUrl(url) {
|
||||
@@ -308,37 +222,23 @@ async setUrl(url) {
|
||||
}
|
||||
```
|
||||
|
||||
A few notes:
|
||||
几点说明:
|
||||
|
||||
- all command methods should be `async` functions or otherwise return a `Promise`
|
||||
- you don't need to worry about protocol encoding/decoding. You will get JS objects as params, and
|
||||
can return JSON-serializable objects in response. Appium will take care of wrapping it up in the
|
||||
WebDriver protocol response format, turning it into JSON, etc...
|
||||
- all session-based commands receive the `sessionId` parameter as the last parameter
|
||||
- all element-based commands receive the `elementId` parameter as the second-to-last parameter
|
||||
- if your driver doesn't implement a command, users can still try to access the command, and will
|
||||
get a `501 Not Yet Implemented` response error.
|
||||
- 所有命令方法都应当是 `async` 函数,或者以其他方式返回 `Promise`
|
||||
- 你不必关心协议的编解码。参数会以 JS 对象形式传入,你只需返回可 JSON 序列化的对象即可。 Appium 会自动把它们包装成 WebDriver 协议响应格式、转成 JSON 等等……
|
||||
- 所有基于会话的命令都会把 `sessionId` 参数作为最后一个参数传入
|
||||
- 所有基于元素的命令都会把 `elementId` 参数作为倒数第二个参数传入
|
||||
- 如果你的驱动没有实现某个命令,用户仍然可以尝试调用,但会收到 `501 Not Yet Implemented` 错误响应。
|
||||
|
||||
### Implement WebDriver BiDi commands
|
||||
### 实现 WebDriver BiDi 命令
|
||||
|
||||
[WebDriver BiDi](https://w3c.github.io/webdriver-bidi) is a newer version of the WebDriver spec
|
||||
which is implemented over Websockets instead of HTTP. As an Appium driver author you can take
|
||||
advantage of Appium's BiDi support without having to know anything about the BiDi protocol or
|
||||
Websockets. Implementing handlers for BiDi commands works just the same as implementing handlers
|
||||
for WebDriver classic commands (described in the previous section). You simply define a method on
|
||||
your driver of the appropriate name, and it will be called when the BiDi command is requested by
|
||||
the client. To see which specific names you should use for BiDi commands, have a look at
|
||||
[bidi-commands.ts](https://github.com/appium/appium/blob/master/packages/base-driver/lib/protocol/bidi-commands.ts)
|
||||
[WebDriver BiDi](https://w3c.github.io/webdriver-bidi) 是 WebDriver 规范的新版本,基于 Websocket 而非 HTTP 实现。作为 Appium 驱动作者,你可以直接利用 Appium 的 BiDi 支持,而无需了解 BiDi 协议或 Websocket 的任何细节。实现 BiDi 命令的处理方法与实现 WebDriver 经典命令的处理方法完全一样(见上一节)。你只需在驱动上定义名称对应的方法,当客户端请求该 BiDi 命令时它就会被调用。要查看 BiDi 命令应使用的具体名称,请参考 [bidi-commands.ts](https://github.com/appium/appium/blob/master/packages/base-driver/lib/protocol/bidi-commands.ts)。
|
||||
|
||||
You are not limited to BiDi commands that are defined in the official BiDi specification. If you
|
||||
wish to define new commands, you may do so; you just need to tell Appium about them! See
|
||||
[below](#extend-the-existing-protocol-with-new-commands) for more information.
|
||||
你不必局限于官方 BiDi 规范中已定义的命令。如果你想定义新命令,也完全可以——只需要把这些新命令告知 Appium!详情请见下文 [用新的命令扩展现有协议](#用新的命令扩展现有协议)。
|
||||
|
||||
### Implement element finding
|
||||
### 实现元素查找
|
||||
|
||||
Element finding is a special command implementation case. You don't actually want to override
|
||||
`findElement` or `findElements`, even though those are what are listed in `routes.js`. Appium does
|
||||
a lot of work for you if instead you implement this function:
|
||||
元素查找是一种特殊的命令实现情形。尽管 `routes.js` 中列出的命令是 `findElement` 和 `findElements`,但实际上你不应该重写它们。如果你改为实现下面这个函数,Appium 会替你完成大量工作:
|
||||
|
||||
```js
|
||||
async findElOrEls(strategy, selector, mult, context) {
|
||||
@@ -346,55 +246,43 @@ async findElOrEls(strategy, selector, mult, context) {
|
||||
}
|
||||
```
|
||||
|
||||
Here's what gets passed in:
|
||||
传入的参数含义如下:
|
||||
|
||||
- `strategy` - a string, the locator strategy being used
|
||||
- `selector` - a string, the selector
|
||||
- `mult` - boolean, whether the user has requested one element or all elements matching the
|
||||
selector
|
||||
- `context` - (optional) if defined, will be a W3C Element (i.e., a JS object with the W3C element
|
||||
identifier as the key and the element ID as the value)
|
||||
- `strategy`——字符串,正在使用的定位策略
|
||||
- `selector`——字符串,选择器
|
||||
- `mult`——布尔值,表示用户是要查找单个元素还是匹配该选择器的所有元素
|
||||
- `context`——(可选)若有值,则是一个 W3C Element(即以 W3C 元素标识符为键、元素 ID 为值的 JS 对象)
|
||||
|
||||
And you need to return one of the following:
|
||||
你需要返回以下二者之一:
|
||||
|
||||
- a single W3C element (an object as described above)
|
||||
- an array of W3C elements
|
||||
- 单个 W3C 元素(即上面描述的对象)
|
||||
- W3C 元素数组
|
||||
|
||||
Note that you can import that W3C web element identifier from `appium/support`:
|
||||
注意,你可以从 `appium/support` 导入 W3C web 元素标识符:
|
||||
|
||||
```js
|
||||
import {util} from 'appium/support';
|
||||
const { W3C_WEB_ELEMENT_IDENTIFIER } = util;
|
||||
```
|
||||
|
||||
What you do with elements is up to you! Usually you end up keeping a cache map of IDs to actual
|
||||
element "objects" or whatever the equivalent is for your platform.
|
||||
拿到元素之后怎么用完全由你决定!通常你会维护一个从 ID 到真实元素"对象"(或你平台上等价事物)的映射。
|
||||
|
||||
### Define valid locator strategies
|
||||
### 定义合法的定位策略
|
||||
|
||||
Your driver might only support a subset of the standard WebDriver locator strategies, or it might
|
||||
add its own custom locator strategies. To tell Appium which strategies are considered valid for
|
||||
your driver, create an array of strategies and assign it to `this.locatorStrategies`:
|
||||
你的驱动可能只支持标准 WebDriver 定位策略的一个子集,也可能添加自己的自定义定位策略。如何告诉 Appium 你的驱动支持哪些策略呢?你需要创建一个策略数组并赋给 `this.locatorStrategies`:
|
||||
|
||||
```js
|
||||
this.locatorStrategies = ['xpath', 'custom-strategy'];
|
||||
```
|
||||
|
||||
Appium will throw an error if the user attempts to use any strategies other than the allowed ones,
|
||||
which enables you to keep your element finding code clean and deal with only the strategies you
|
||||
know about.
|
||||
如果用户尝试使用允许范围之外的策略,Appium 会抛出错误,这能让你把元素查找代码保持干净,只处理你支持的策略。
|
||||
|
||||
By default, the list of valid strategies is empty, so if your driver isn't simply proxying to
|
||||
another WebDriver endpoint, you'll need to define some. The protocol-standard locator strategies
|
||||
are defined [here](https://www.w3.org/TR/webdriver/#locator-strategies).
|
||||
默认情况下,合法策略列表为空。所以如果你的驱动不是简单地代理到另一个 WebDriver 端点,你就需要
|
||||
定义一些策略。协议标准的定位策略定义在[这里](https://www.w3.org/TR/webdriver/#locator-strategies)。
|
||||
|
||||
### Throw WebDriver-specific errors
|
||||
### 抛出 WebDriver 错误
|
||||
|
||||
The WebDriver spec defines a set of error
|
||||
codes to accompany command responses if an
|
||||
error occurred. Appium has created error classes for each of these codes, so you can throw the
|
||||
appropriate error from inside a command, and it will do the right thing in terms of the protocol
|
||||
response to the user. To get access to these error classes, import them from `appium/driver`:
|
||||
WebDriver 规范定义了一组[错误码](https://github.com/jlipps/simple-wd-spec#error-codes),用于在命令发生错误时伴随响应返回。 Appium 为每个错误码都创建了对应的错误类,因此你可以在命令内部抛出相应的错误,Appium 会按照协议规范把它正确地响应给用户。要获得这些错误类,从 `appium/driver` 导入即可:
|
||||
|
||||
```
|
||||
import {errors} from 'appium/driver';
|
||||
@@ -402,42 +290,34 @@ import {errors} from 'appium/driver';
|
||||
throw new errors.NoSuchElementError();
|
||||
```
|
||||
|
||||
### Log messages to the Appium log
|
||||
### 向 Appium 日志写消息
|
||||
|
||||
You can always use `console.log`, of course, but Appium provides a nice logger for you as
|
||||
`this.log` (it has `.info`, `.debug`, `.log`, `.warn`, `.error` methods on it for differing log
|
||||
levels). If you want to create an Appium logger outside of a driver context (say in a script or
|
||||
helper file), you can always construct your own too:
|
||||
你当然可以随时用 `console.log`,但 Appium 为你提供了一个更贴心的日志器 `this.log`(它有 `.info`、`.debug`、`.log`、`.warn`、`.error` 等不同日志级别的方法)。如果你想在驱动上下文之外(比如脚本或辅助文件中)创建 Appium 日志器,也可以自行构造:
|
||||
|
||||
```js
|
||||
import {logging} from 'appium/support';
|
||||
const log = logging.getLogger('MyDriver');
|
||||
```
|
||||
|
||||
## Further possibilities for Appium drivers
|
||||
## Appium 驱动的进阶能力
|
||||
|
||||
These are things your driver _can_ do to take advantage of extra driver features or do its job more
|
||||
conveniently.
|
||||
以下是你的驱动_可以_做的事情,以利用更多驱动特性或更便捷地完成工作。
|
||||
|
||||
### Add a schema for custom command line arguments
|
||||
### 为自定义命令行参数添加 schema
|
||||
|
||||
You can add custom CLI args if you want your driver to receive data from the command line when the
|
||||
Appium server is started (for example, ports that a server administrator should set that should not
|
||||
be passed in as capabilities.
|
||||
如果你希望驱动在 Appium 服务器启动时从命令行接收数据,就可以添加自定义 CLI 参数(例如由服务器管理员设定的端口,这类参数不适合通过能力传入)。
|
||||
|
||||
To define CLI arguments (or configuration properties) for the Appium server, your extension must provide a _schema_. In
|
||||
the `appium` property of your extension's `package.json`, add a `schema` property. This will either
|
||||
a) be a schema itself, or b) be a path to a schema file.
|
||||
要为 Appium 服务器定义 CLI 参数(或配置属性),你的驱动必须提供一个 _schema_。在驱动 `package.json` 的 `appium` 属性下添加一个 `schema` 属性。它可以本身就是 schema,也可以指向 schema 文件的路径。
|
||||
|
||||
The rules for these schemas:
|
||||
schema 的规则如下:
|
||||
|
||||
- Schemas must conform to [JSON Schema Draft-07](https://ajv.js.org/json-schema.html#draft-07).
|
||||
- If the `schema` property is a path to a schema file, the file must be in JSON or JS (CommonJS) format.
|
||||
- Custom `$id` values are unsupported. To use `$ref`, provide a value relative to the schema root, e.g., `/properties/foo`.
|
||||
- Known values of the `format` keyword are likely supported, but various other keywords may be unsupported. If you find a keyword that is unsupported which you need to use, please [ask for support](https://github.com/appium/appium/issues/new) or send a PR!
|
||||
- The schema must be of type `object` (`{"type": "object"}`), containing the arguments in a `properties` keyword. Nested properties are unsupported.
|
||||
- Schema 必须符合 [JSON Schema Draft-07](https://ajv.js.org/json-schema.html#draft-07)。
|
||||
- 如果 `schema` 属性是 schema 文件的路径,该文件必须是 JSON 或 JS(CommonJS)格式。
|
||||
- 不支持自定义 `$id` 值。要使用 `$ref`,请提供相对于 schema 根的值,例如 `/properties/foo`。
|
||||
- `format` 关键字的已知取值一般是受支持的,但其他一些关键字可能不受支持。如果你需要用到的某个关键字不受支持,请[提出支持请求](https://github.com/appium/appium/issues/new)或提交 PR!
|
||||
- Schema 的类型必须是 `object`(`{"type": "object"}`),参数放在 `properties` 关键字中。不支持嵌套属性。
|
||||
|
||||
Example:
|
||||
示例:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -458,10 +338,8 @@ Example:
|
||||
}
|
||||
```
|
||||
|
||||
The above schema defines two properties which can be set via CLI argument or configuration file. If
|
||||
this extension is a _driver_ and its name is "horace", the CLI args would be
|
||||
`--driver-horace-test-web-server-port` and `--driver-horace-test-web-server-host`, respectively.
|
||||
Alternatively, a user could provide a configuration file containing:
|
||||
上面的 schema 定义了两个可通过 CLI 参数或配置文件设置的属性。如果这个扩展是一个_驱动_且名字为 "horace",那么对应的 CLI 参数分别是 `--driver-horace-test-web-server-port` 和
|
||||
`--driver-horace-test-web-server-host`。用户也可以提供如下内容的配置文件:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -476,7 +354,7 @@ Alternatively, a user could provide a configuration file containing:
|
||||
}
|
||||
```
|
||||
|
||||
### Add driver scripts
|
||||
### 添加驱动脚本
|
||||
|
||||
Sometimes you might want users of your driver to be able to run scripts outside the context of
|
||||
a session (for example, to run a script that pre-builds aspects of your driver). To support this,
|
||||
|
||||
@@ -140,3 +140,17 @@ Supported by: `@domovou69`
|
||||
```sh title="Install This Tool"
|
||||
npm install -g xpath-to-class-chain
|
||||
```
|
||||
|
||||
### [XPath to UiSelector](https://github.com/domovou69/xpath-to-uiselector)
|
||||
|
||||
XPath to UiSelector is a command-line tool for migrating Android XPath locators in test code to
|
||||
`-android uiautomator` selectors. It converts the XPaths that have an exact `UiSelector`
|
||||
equivalent, converts with a warning those that only have a close one (such as `//A//B`), and skips
|
||||
the rest with a reason. The strategy call is rewritten together with the string, for example
|
||||
`AppiumBy.xpath` becomes `AppiumBy.androidUIAutomator`.
|
||||
|
||||
Supported by: `@domovou69`
|
||||
|
||||
```sh title="Install This Tool"
|
||||
npm install -g xpath-to-uiselector
|
||||
```
|
||||
|
||||
@@ -45,7 +45,7 @@ contributors!
|
||||
|
||||
## Gold Sponsors
|
||||
|
||||
<div class="sponsor-section"><a href="https://jetify.com/" target="_blank"><img src="https://images.opencollective.com/jetify/415824c/avatar/64.png" alt="Jetify" /></a>
|
||||
<div class="sponsor-section"><a href="https://device.io/" target="_blank"><img src="https://images.opencollective.com/device-io/cc7e949/avatar/64.png" alt="Device.io" /></a>
|
||||
</div>
|
||||
|
||||
[Become a Gold Sponsor](https://opencollective.com/appium/contribute/gold-sponsor-72877/checkout?interval=month&amount=500&contributeAs=me)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "appium",
|
||||
"version": "3.9.0",
|
||||
"version": "3.9.1",
|
||||
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
|
||||
"description": "Automation for Apps.",
|
||||
"keywords": [
|
||||
@@ -66,9 +66,9 @@
|
||||
"test:unit": "node --test --enable-source-maps --test-timeout=5000 \"./build/test/unit/**/*.spec.js\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@appium/base-driver": "10.8.2",
|
||||
"@appium/base-plugin": "3.3.6",
|
||||
"@appium/docutils": "3.0.2",
|
||||
"@appium/base-driver": "10.8.3",
|
||||
"@appium/base-plugin": "3.3.7",
|
||||
"@appium/docutils": "3.0.3",
|
||||
"@appium/logger": "2.0.12",
|
||||
"@appium/schema": "1.3.0",
|
||||
"@appium/support": "7.2.9",
|
||||
|
||||
@@ -5,7 +5,7 @@ import {describe, it, before, after, beforeEach, type TestContext} from 'node:te
|
||||
import {fs, system, tempDir, util} from '@appium/support';
|
||||
import type {DriverType} from '@appium/types';
|
||||
import type {ExtRecord} from 'appium/types';
|
||||
import {prerelease} from 'semver';
|
||||
import {prerelease, satisfies} from 'semver';
|
||||
import {exec} from 'teen_process';
|
||||
|
||||
import {
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
EXT_SUBCOMMAND_UNINSTALL as UNINSTALL,
|
||||
KNOWN_DRIVERS,
|
||||
} from '../../lib/constants';
|
||||
import {omitKeys, resolveFrom} from '../../lib/utils';
|
||||
import {npmPackage, omitKeys, resolveFrom} from '../../lib/utils';
|
||||
import {FAKE_DRIVER_DIR, resolveFixture} from '../helpers';
|
||||
import {installLocalExtension, runAppiumJson, runAppiumRaw} from './e2e-helpers';
|
||||
|
||||
@@ -162,10 +162,20 @@ describe('Driver CLI', {timeout: 90000}, function () {
|
||||
});
|
||||
|
||||
it('should install a driver from the list of known drivers', async function () {
|
||||
const rawPeerReq = (
|
||||
await exec('npm', ['view', 'appium-uiautomator2-driver', 'peerDependencies.appium', '--json'], {
|
||||
encoding: 'utf-8',
|
||||
})
|
||||
).stdout.trim();
|
||||
const latestPeerReq = rawPeerReq ? (JSON.parse(rawPeerReq) as string) : undefined;
|
||||
const ret = await runInstall(['uiautomator2']);
|
||||
const expectedInstallSpec =
|
||||
!latestPeerReq || satisfies(npmPackage.version, latestPeerReq, {includePrerelease: true})
|
||||
? 'uiautomator2'
|
||||
: `uiautomator2@${ret.uiautomator2.version}`;
|
||||
assert.strictEqual(ret.uiautomator2.pkgName, 'appium-uiautomator2-driver');
|
||||
assert.strictEqual(ret.uiautomator2.installType, 'npm');
|
||||
assert.strictEqual(ret.uiautomator2.installSpec, 'uiautomator2');
|
||||
assert.strictEqual(ret.uiautomator2.installSpec, expectedInstallSpec);
|
||||
const list = await runList(['--installed']);
|
||||
const rest = omitKeys(list.uiautomator2 ?? {}, ['installed', 'repositoryUrl']);
|
||||
assertDeepInclude(rest, {
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## [10.8.3](https://github.com/appium/appium/compare/@appium/base-driver@10.8.2...@appium/base-driver@10.8.3) (2026-11-14)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **base-driver:** avoid catastrophic backtracking in isPackageOrBundle ([#23161](https://github.com/appium/appium/issues/23161)) ([091fd32](https://github.com/appium/appium/commit/091fd320b992e4987f9df08f8a5e86b2c23d9fb6))
|
||||
|
||||
|
||||
## [10.8.2](https://github.com/appium/appium/compare/@appium/base-driver@10.8.1...@appium/base-driver@10.8.2) (2026-10-27)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
@@ -297,7 +297,7 @@ export async function configureApp(
|
||||
* @returns `true` if the value matches a dot-separated identifier pattern.
|
||||
*/
|
||||
export function isPackageOrBundle(app: string): boolean {
|
||||
return /^([a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+)+$/.test(app);
|
||||
return /^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)+$/.test(app);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@appium/base-driver",
|
||||
"version": "10.8.2",
|
||||
"version": "10.8.3",
|
||||
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
|
||||
"description": "Base driver class for Appium drivers",
|
||||
"keywords": [
|
||||
|
||||
@@ -12,11 +12,18 @@ describe('helpers', function () {
|
||||
describe('#isPackageOrBundle', function () {
|
||||
it('should accept packages and bundles', function () {
|
||||
assert.strictEqual(isPackageOrBundle('io.appium.testapp'), true);
|
||||
assert.strictEqual(isPackageOrBundle('a.b.c'), true);
|
||||
});
|
||||
it('should not accept non-packages or non-bundles', function () {
|
||||
assert.strictEqual(isPackageOrBundle('foo'), false);
|
||||
assert.strictEqual(isPackageOrBundle('/path/to/an.app'), false);
|
||||
assert.strictEqual(isPackageOrBundle('/path/to/an.apk'), false);
|
||||
assert.strictEqual(isPackageOrBundle('a..b'), false);
|
||||
});
|
||||
it('should not backtrack catastrophically on crafted input', function () {
|
||||
const start = Date.now();
|
||||
assert.strictEqual(isPackageOrBundle(`${'aaaa.'.repeat(50)}!`), false);
|
||||
assert.ok(Date.now() - start < 100);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -3,6 +3,14 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## [3.3.7](https://github.com/appium/appium/compare/@appium/base-plugin@3.3.6...@appium/base-plugin@3.3.7) (2026-11-14)
|
||||
|
||||
**Note:** Version bump only for package @appium/base-plugin
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## [3.3.6](https://github.com/appium/appium/compare/@appium/base-plugin@3.3.5...@appium/base-plugin@3.3.6) (2026-10-27)
|
||||
|
||||
**Note:** Version bump only for package @appium/base-plugin
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@appium/base-plugin",
|
||||
"version": "3.3.6",
|
||||
"version": "3.3.7",
|
||||
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
|
||||
"description": "The base plugin used to create Appium plugins",
|
||||
"keywords": [
|
||||
@@ -44,7 +44,7 @@
|
||||
"test:unit": "node --test --enable-source-maps \"./build/test/unit/**/*.spec.js\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@appium/base-driver": "10.8.2",
|
||||
"@appium/base-driver": "10.8.3",
|
||||
"@appium/support": "7.2.9",
|
||||
"@appium/types": "1.7.2"
|
||||
},
|
||||
|
||||
@@ -3,6 +3,14 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## [3.0.3](https://github.com/appium/appium/compare/@appium/docutils@3.0.2...@appium/docutils@3.0.3) (2026-11-14)
|
||||
|
||||
**Note:** Version bump only for package @appium/docutils
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## [3.0.2](https://github.com/appium/appium/compare/@appium/docutils@3.0.1...@appium/docutils@3.0.2) (2026-10-27)
|
||||
|
||||
**Note:** Version bump only for package @appium/docutils
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@appium/docutils",
|
||||
"version": "3.0.2",
|
||||
"version": "3.0.3",
|
||||
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
|
||||
"description": "Documentation generation utilities for Appium and related projects",
|
||||
"keywords": [
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
mkdocs==1.6.1
|
||||
mkdocs-git-revision-date-localized-plugin==1.6.1
|
||||
mkdocs-git-revision-date-localized-plugin==1.6.2
|
||||
mkdocs-material==9.8.0
|
||||
mkdocs-redirects==1.2.3
|
||||
mike==2.2.0
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## [7.0.3](https://github.com/appium/appium/compare/@appium/execute-driver-plugin@7.0.2...@appium/execute-driver-plugin@7.0.3) (2026-11-14)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **execute-driver-plugin:** wrap non-configurable property descriptors via shadow target ([#23126](https://github.com/appium/appium/issues/23126)) ([b2ce3a0](https://github.com/appium/appium/commit/b2ce3a0f8074506a7b3eff2df15e0ac37999999a))
|
||||
|
||||
|
||||
## [7.0.2](https://github.com/appium/appium/compare/@appium/execute-driver-plugin@7.0.1...@appium/execute-driver-plugin@7.0.2) (2026-10-27)
|
||||
|
||||
**Note:** Version bump only for package @appium/execute-driver-plugin
|
||||
|
||||
@@ -1,48 +1,12 @@
|
||||
/**
|
||||
* @fileoverview Bridges host-realm (child process) objects into Node's `vm.runInNewContext` without
|
||||
* leaking main-realm prototype metadata that untrusted script could use to obtain the real
|
||||
* `Function` constructor and escape the VM (RCE on the Appium host).
|
||||
*
|
||||
* ## Why this exists
|
||||
*
|
||||
* `vm` isolates *globals* and bytecode, but any **host object** you inject still carries the
|
||||
* **main V8 realm's** prototypes.
|
||||
*
|
||||
* ## Strategy (high level)
|
||||
*
|
||||
* 1. **Deep `Proxy`**: Every host object/function exposed to the script is wrapped. Property
|
||||
* reads (`get`), call results (`apply` / `construct`), and—where allowed—descriptor reflection
|
||||
* (`getOwnPropertyDescriptor`) funnel return values through `wrapIfNeeded`, which recursively
|
||||
* wraps objects and functions so nested references never surface as raw host callables.
|
||||
*
|
||||
* 2. **Prototype-adjacent keys**: `constructor` and `__proto__` are not read from the target;
|
||||
* the `get` trap returns a frozen null-prototype sentinel, `getPrototypeOf` always reports that
|
||||
* sentinel (not the real prototype chain), `has` hides those keys, and `setPrototypeOf` is
|
||||
* rejected—closing the usual `…constructor.constructor` chains.
|
||||
*
|
||||
* 3. **Identity**: `targetToProxy` is a `WeakMap` from each host object/function to its single
|
||||
* proxy, so repeated reads (e.g. `driver.m === driver.m`) stay stable and cycles do not recurse
|
||||
* forever. `proxyToTarget` reverses the mapping so `Reflect.get`/`apply` can unwrap `this` and
|
||||
* pass the real host receiver to accessors and methods that expect it.
|
||||
*
|
||||
* 4. **Promises**: A `Proxy` around a native `Promise` breaks V8's internal `then` branding
|
||||
* (WebdriverIO breaks). Host promises are therefore surfaced as a **null-prototype thenable**
|
||||
* that forwards to the real promise and runs `wrapIfNeeded` on fulfilled/rejected values before
|
||||
* VM continuations run. One thenable object per promise lives in `promiseToThenableHost`.
|
||||
*
|
||||
* 5. **Descriptors**: For **configurable** own properties only, `getOwnPropertyDescriptor` returns
|
||||
* descriptors whose `value` / `get` / `set` are wrapped—so descriptor-based extraction of a
|
||||
* method still yields a sandbox proxy. **Non-configurable** properties must return the real
|
||||
* descriptor unchanged (ECMAScript Proxy invariants); those paths can still expose raw host
|
||||
* callables until the script uses normal property access, which remains wrapped.
|
||||
*
|
||||
* 6. **`defineProperty`**: Incoming descriptors from the VM may reference our proxies; fields are
|
||||
* unwrapped before `Reflect.defineProperty` so the host object receives real functions/objects.
|
||||
*
|
||||
* This is defense in depth: Node documents that `vm` is not a full security boundary. Treat
|
||||
* `--allow-insecure=…:execute_driver_script` as highly privileged regardless of this module.
|
||||
* @fileoverview Deep-proxy bridge for host objects exposed to `vm.runInNewContext`.
|
||||
* Wraps nested return values, descriptors (via structural shadow targets), Promises,
|
||||
* and VM callback boundaries while hiding `constructor` and `__proto__` prototype chains.
|
||||
* Node's `vm` is not a full security boundary; keep `execute_driver_script` behind `--allow-insecure`.
|
||||
*/
|
||||
|
||||
import {types} from 'node:util';
|
||||
|
||||
/**
|
||||
* Null-prototype object returned for prototype-adjacent property lookups on
|
||||
* proxied host values. It must not inherit `Object.prototype` (which would
|
||||
@@ -64,12 +28,19 @@ const targetToProxy = new WeakMap<HostTarget, object>();
|
||||
/** Deep proxy → underlying host target (unwrap `this` / receivers / defineProperty). */
|
||||
const proxyToTarget = new WeakMap<object, HostTarget>();
|
||||
|
||||
/**
|
||||
* Host `Promise` → null-prototype thenable facade (one per promise; then wrapped by `wrapDeep`).
|
||||
* Native promises cannot be proxied without breaking `Promise.prototype.then` receiver checks.
|
||||
*/
|
||||
/** Proxy shadow target → underlying host target for the shared `DEEP_HANDLER`. */
|
||||
const shadowToHost = new WeakMap<HostTarget, HostTarget>();
|
||||
|
||||
const vmFnToHostWrapper = new WeakMap<HostCallable, HostCallable>();
|
||||
const vmObjects = new WeakSet<HostTarget>();
|
||||
const promiseToThenableHost = new WeakMap<Promise<unknown>, object>();
|
||||
|
||||
const CONSTRUCTOR_TEST_TARGET = new Proxy(function () {}, {
|
||||
construct() {
|
||||
return {};
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Entry point: wrap a host object or function for use as a global in `vm.runInNewContext`.
|
||||
*
|
||||
@@ -83,24 +54,197 @@ export function wrapHostBindingForVmContext<T extends HostTarget>(hostValue: T):
|
||||
return wrapDeep(hostValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns Whether `value` is a proxy created by this module (`proxyToTarget` has an entry).
|
||||
* Includes both object proxies and function proxies.
|
||||
*/
|
||||
function isOurProxy(value: unknown): value is HostTarget {
|
||||
return value !== null && (typeof value === 'object' || typeof value === 'function') && proxyToTarget.has(value);
|
||||
}
|
||||
|
||||
function isVmRealmValue(value: unknown): boolean {
|
||||
return value !== null && (typeof value === 'object' || typeof value === 'function') && vmObjects.has(value);
|
||||
}
|
||||
|
||||
function isVmObjectPrototype(proto: object): boolean {
|
||||
if (proto === Object.prototype || proto === SAFE_LOOKUP_TARGET) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
if (Reflect.getPrototypeOf(proto) !== null) {
|
||||
return false;
|
||||
}
|
||||
const ctorDesc = Reflect.getOwnPropertyDescriptor(proto, 'constructor');
|
||||
const ctor = ctorDesc && 'value' in ctorDesc ? ctorDesc.value : undefined;
|
||||
if (typeof ctor !== 'function' || isOurProxy(ctor)) {
|
||||
return false;
|
||||
}
|
||||
const fnProto = Reflect.getPrototypeOf(ctor);
|
||||
return fnProto !== null && fnProto !== Function.prototype && Reflect.getPrototypeOf(fnProto) === proto;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function hasVmRealmPrototype(value: object): boolean {
|
||||
let current: object | null = value;
|
||||
for (let depth = 0; current !== null && depth < 64; depth++) {
|
||||
if (current === Object.prototype || current === Function.prototype || current === Error.prototype) {
|
||||
return false;
|
||||
}
|
||||
if (current === SAFE_LOOKUP_TARGET || shadowToHost.has(current)) {
|
||||
return false;
|
||||
}
|
||||
if (isOurProxy(current)) {
|
||||
return depth > 0;
|
||||
}
|
||||
if (isVmObjectPrototype(current)) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
current = Reflect.getPrototypeOf(current);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function recordVmValue(value: unknown): void {
|
||||
if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
value === SAFE_LOOKUP_TARGET ||
|
||||
isOurProxy(value) ||
|
||||
targetToProxy.has(value) ||
|
||||
shadowToHost.has(value) ||
|
||||
promiseToThenableHost.has(value as Promise<unknown>) ||
|
||||
!hasVmRealmPrototype(value)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
vmObjects.add(value);
|
||||
}
|
||||
|
||||
function wrapErrorForVm(err: unknown): unknown {
|
||||
if (isOurProxy(err) || isVmRealmValue(err)) {
|
||||
return err;
|
||||
}
|
||||
try {
|
||||
return wrapIfNeeded(err);
|
||||
} catch {
|
||||
return FALLBACK_WRAPPED_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
function copyFunctionMetadata(vmFn: HostCallable, wrapped: HostCallable, includePrototype: boolean): void {
|
||||
for (const key of ['length', 'name'] as const) {
|
||||
const desc = Reflect.getOwnPropertyDescriptor(vmFn, key);
|
||||
if (desc) {
|
||||
Reflect.defineProperty(wrapped, key, mapDescriptorForHost(desc));
|
||||
}
|
||||
}
|
||||
if (includePrototype) {
|
||||
const protoDesc = Reflect.getOwnPropertyDescriptor(vmFn, 'prototype');
|
||||
if (protoDesc && 'value' in protoDesc) {
|
||||
Reflect.defineProperty(wrapped, 'prototype', {
|
||||
value: unwrapIfProxy(protoDesc.value),
|
||||
writable: Boolean(protoDesc.writable),
|
||||
});
|
||||
}
|
||||
}
|
||||
Object.defineProperty(wrapped, 'toString', {
|
||||
value: () => Function.prototype.toString.call(vmFn),
|
||||
configurable: true,
|
||||
writable: true,
|
||||
});
|
||||
}
|
||||
|
||||
function runVmCallback(
|
||||
thisArg: unknown,
|
||||
args: unknown[],
|
||||
op: (safeThis: unknown, safeArgs: unknown[]) => unknown,
|
||||
awaitResult = false,
|
||||
): unknown {
|
||||
const safeThis = wrapIfNeeded(thisArg);
|
||||
const safeArgs = args.map((arg) => wrapIfNeeded(arg));
|
||||
try {
|
||||
const raw = op(safeThis, safeArgs);
|
||||
return awaitResult
|
||||
? Promise.resolve(raw)
|
||||
.then((val) => unwrapIfProxy(val))
|
||||
.catch((err: unknown) => {
|
||||
recordVmValue(err);
|
||||
throw wrapErrorForVm(err);
|
||||
})
|
||||
: unwrapIfProxy(raw);
|
||||
} catch (err) {
|
||||
recordVmValue(err);
|
||||
throw wrapErrorForVm(err);
|
||||
}
|
||||
}
|
||||
|
||||
function wrapVmFunctionForHost(vmFn: HostCallable): HostCallable {
|
||||
const cached = vmFnToHostWrapper.get(vmFn);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
recordVmValue(vmFn);
|
||||
|
||||
const applyVm = (safeThis: unknown, safeArgs: unknown[]): unknown => Reflect.apply(vmFn, safeThis, safeArgs);
|
||||
const constructible = isConstructibleFunction(vmFn);
|
||||
let wrapped: HostCallable;
|
||||
if (types.isAsyncFunction(vmFn)) {
|
||||
wrapped = async function (this: unknown, ...args: unknown[]): Promise<unknown> {
|
||||
return await (runVmCallback(this, args, applyVm, true) as Promise<unknown>);
|
||||
};
|
||||
} else if (constructible) {
|
||||
wrapped = function (this: unknown, ...args: unknown[]): unknown {
|
||||
if (new.target) {
|
||||
const actualNewTarget =
|
||||
new.target === wrapped ? (vmFn as unknown as HostConstructor) : (wrapIfNeeded(new.target) as HostConstructor);
|
||||
return runVmCallback(undefined, args, (_this, safeArgs) =>
|
||||
Reflect.construct(vmFn as unknown as HostConstructor, safeArgs, actualNewTarget),
|
||||
);
|
||||
}
|
||||
return runVmCallback(this, args, applyVm);
|
||||
};
|
||||
} else {
|
||||
wrapped = {
|
||||
callVm(this: unknown, ...args: unknown[]): unknown {
|
||||
return runVmCallback(this, args, applyVm);
|
||||
},
|
||||
}.callVm;
|
||||
}
|
||||
|
||||
copyFunctionMetadata(vmFn, wrapped, constructible);
|
||||
vmFnToHostWrapper.set(vmFn, wrapped);
|
||||
targetToProxy.set(wrapped, vmFn);
|
||||
proxyToTarget.set(wrapped, vmFn);
|
||||
return wrapped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a value that may be our deep proxy back to the underlying host target for host APIs.
|
||||
*
|
||||
* @param value - Possibly a proxy from this module, or any other value.
|
||||
* @returns The host target if `value` is our proxy; otherwise `value` unchanged.
|
||||
* Maps a value crossing from the VM into the host:
|
||||
* - Unwraps proxies created by this module back to their underlying host target.
|
||||
* - Wraps VM-realm functions so host callers cannot hand raw host `this`/arguments back to them.
|
||||
* - Tracks VM-originated objects in `vmObjects` so they round-trip back to the VM unchanged.
|
||||
*/
|
||||
function unwrapIfProxy<T>(value: T): T {
|
||||
if (isOurProxy(value)) {
|
||||
return proxyToTarget.get(value) as T;
|
||||
const target = proxyToTarget.get(value) as T;
|
||||
if (
|
||||
typeof target === 'function' &&
|
||||
vmFnToHostWrapper.get(target as unknown as HostCallable) === (value as unknown)
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
if (typeof value === 'function') {
|
||||
if (targetToProxy.has(value)) {
|
||||
return value;
|
||||
}
|
||||
return wrapVmFunctionForHost(value as unknown as HostCallable) as unknown as T;
|
||||
}
|
||||
recordVmValue(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
@@ -114,6 +258,18 @@ function isNativePromise(value: object): value is Promise<unknown> {
|
||||
return value instanceof Promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a trap operation and ensures any thrown host-realm error is wrapped via
|
||||
* {@link wrapIfNeeded} before crossing into the VM catch block.
|
||||
*/
|
||||
function runTrapSafely<T>(fn: () => T): T {
|
||||
try {
|
||||
return fn();
|
||||
} catch (err) {
|
||||
throw wrapErrorForVm(err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a host Promise by exposing a null-prototype thenable that delegates to `p` and ensures
|
||||
* fulfillment/rejection values are passed through {@link wrapIfNeeded} before VM callbacks run.
|
||||
@@ -126,7 +282,7 @@ function wrapPromiseAsThenable(p: Promise<unknown>): unknown {
|
||||
const hostObj: object =
|
||||
cached ??
|
||||
(() => {
|
||||
/* eslint-disable promise/prefer-await-to-then -- thenable facade over a host Promise */
|
||||
/* eslint-disable unicorn/no-thenable,promise/prefer-await-to-then -- thenable facade over a host Promise */
|
||||
const o = Object.assign(Object.create(null), {
|
||||
then(onFulfilled?: unknown, onRejected?: unknown) {
|
||||
const adaptFulfill =
|
||||
@@ -152,7 +308,7 @@ function wrapPromiseAsThenable(p: Promise<unknown>): unknown {
|
||||
return wrapIfNeeded(p.finally(onFinally as () => void | PromiseLike<void> | undefined));
|
||||
},
|
||||
});
|
||||
/* eslint-enable promise/prefer-await-to-then */
|
||||
/* eslint-enable unicorn/no-thenable,promise/prefer-await-to-then */
|
||||
promiseToThenableHost.set(p, o);
|
||||
return o;
|
||||
})();
|
||||
@@ -160,34 +316,148 @@ function wrapPromiseAsThenable(p: Promise<unknown>): unknown {
|
||||
}
|
||||
|
||||
/**
|
||||
* Clones a **configurable** property descriptor so `value` / `get` / `set` are wrapped for the VM.
|
||||
* Tests whether a callable has an internal `[[Construct]]` slot without throwing on common
|
||||
* non-constructible callables (async functions, generators, arrow functions, concise methods).
|
||||
*/
|
||||
function isConstructibleFunction(fn: HostCallable): boolean {
|
||||
if (types.isAsyncFunction(fn) || types.isGeneratorFunction(fn)) {
|
||||
return false;
|
||||
}
|
||||
if ((fn as unknown) === Proxy || Reflect.getOwnPropertyDescriptor(fn, 'prototype') !== undefined) {
|
||||
return true;
|
||||
}
|
||||
const nameDesc = Reflect.getOwnPropertyDescriptor(fn, 'name');
|
||||
const fnName = nameDesc && 'value' in nameDesc ? nameDesc.value : undefined;
|
||||
if (!types.isProxy(fn) && typeof fnName === 'string' && !fnName.startsWith('bound ')) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Reflect.construct(CONSTRUCTOR_TEST_TARGET, [], fn);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a clean shadow target matching the structural kind of `hostTarget` (function, array,
|
||||
* or plain object) so V8 Proxy invariants are checked against the shadow target while keeping
|
||||
* its prototype aligned with `SAFE_LOOKUP_TARGET`.
|
||||
*
|
||||
* @param d - Descriptor from `Reflect.getOwnPropertyDescriptor` on the host target.
|
||||
* @returns A new descriptor safe to return from the proxy `getOwnPropertyDescriptor` trap.
|
||||
* For constructible functions, uses a bound function `(function () {}).bind(null)` so the shadow
|
||||
* target has `[[Construct]]` without a fabricated non-configurable own `.prototype` property.
|
||||
*/
|
||||
function createShadowTarget(hostTarget: HostTarget): HostTarget {
|
||||
let shadow: HostTarget;
|
||||
if (typeof hostTarget === 'function') {
|
||||
shadow = isConstructibleFunction(hostTarget as HostCallable) ? function () {}.bind(null) : () => {};
|
||||
} else if (Array.isArray(hostTarget)) {
|
||||
shadow = [];
|
||||
} else {
|
||||
shadow = {};
|
||||
}
|
||||
Reflect.setPrototypeOf(shadow, SAFE_LOOKUP_TARGET);
|
||||
return shadow;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clones a host property descriptor so `value` / `get` / `set` are wrapped for the VM while
|
||||
* preserving the host descriptor's real `configurable`, `enumerable`, and `writable` flags.
|
||||
*/
|
||||
function mapDescriptorForSandbox(descriptor: PropertyDescriptor): PropertyDescriptor {
|
||||
if ('value' in descriptor) {
|
||||
return {
|
||||
configurable: descriptor.configurable,
|
||||
enumerable: descriptor.enumerable,
|
||||
writable: descriptor.writable,
|
||||
configurable: Boolean(descriptor.configurable),
|
||||
enumerable: Boolean(descriptor.enumerable),
|
||||
writable: Boolean(descriptor.writable),
|
||||
value: wrapIfNeeded(descriptor.value),
|
||||
};
|
||||
}
|
||||
return {
|
||||
configurable: descriptor.configurable,
|
||||
enumerable: descriptor.enumerable,
|
||||
configurable: Boolean(descriptor.configurable),
|
||||
enumerable: Boolean(descriptor.enumerable),
|
||||
get: descriptor.get ? (wrapIfNeeded(descriptor.get) as () => unknown) : undefined,
|
||||
set: descriptor.set ? (wrapIfNeeded(descriptor.set) as (v: unknown) => void) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronizes a single property from `hostTarget` onto `shadowTarget` when required by V8
|
||||
* Proxy invariants (e.g. non-configurable properties, array `length`, or non-extensible targets).
|
||||
*/
|
||||
function syncShadowProperty(
|
||||
shadowTarget: HostTarget,
|
||||
hostTarget: HostTarget,
|
||||
prop: string | symbol,
|
||||
): PropertyDescriptor | undefined {
|
||||
const hostDesc = Reflect.getOwnPropertyDescriptor(hostTarget, prop);
|
||||
if (!hostDesc) {
|
||||
const shadowDesc = Reflect.getOwnPropertyDescriptor(shadowTarget, prop);
|
||||
if (shadowDesc?.configurable) {
|
||||
Reflect.deleteProperty(shadowTarget, prop);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
const wrappedDesc = mapDescriptorForSandbox(hostDesc);
|
||||
const shadowDesc = Reflect.getOwnPropertyDescriptor(shadowTarget, prop);
|
||||
if (!wrappedDesc.configurable || shadowDesc !== undefined || !Reflect.isExtensible(shadowTarget)) {
|
||||
Reflect.defineProperty(shadowTarget, prop, wrappedDesc);
|
||||
}
|
||||
return wrappedDesc;
|
||||
}
|
||||
|
||||
function pruneShadowKeys(shadowTarget: HostTarget, hostKeySet: ReadonlySet<string | symbol>): Array<string | symbol> {
|
||||
const retainedNonConfigurable: Array<string | symbol> = [];
|
||||
for (const shadowKey of Reflect.ownKeys(shadowTarget)) {
|
||||
if (!hostKeySet.has(shadowKey)) {
|
||||
const shadowDesc = Reflect.getOwnPropertyDescriptor(shadowTarget, shadowKey);
|
||||
if (shadowDesc?.configurable) {
|
||||
Reflect.deleteProperty(shadowTarget, shadowKey);
|
||||
} else if (shadowDesc) {
|
||||
retainedNonConfigurable.push(shadowKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
return retainedNonConfigurable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronizes all own properties and non-extensibility from `hostTarget` onto `shadowTarget`.
|
||||
* Returns early once `shadowTarget` is already frozen, or sealed while `hostTarget` is not frozen.
|
||||
*/
|
||||
function syncShadowExtensibility(shadowTarget: HostTarget, hostTarget: HostTarget): void {
|
||||
if (Object.isFrozen(shadowTarget) || (Object.isSealed(shadowTarget) && !Object.isFrozen(hostTarget))) {
|
||||
return;
|
||||
}
|
||||
const hostKeys = Reflect.ownKeys(hostTarget).filter((key) => !isBlockedPrototypeKey(key));
|
||||
const hostKeySet = new Set<string | symbol>(hostKeys);
|
||||
pruneShadowKeys(shadowTarget, hostKeySet);
|
||||
for (const key of hostKeys) {
|
||||
const hostDesc = Reflect.getOwnPropertyDescriptor(hostTarget, key);
|
||||
if (hostDesc) {
|
||||
Reflect.defineProperty(shadowTarget, key, mapDescriptorForSandbox(hostDesc));
|
||||
}
|
||||
}
|
||||
if (!Reflect.isExtensible(hostTarget)) {
|
||||
Reflect.preventExtensions(shadowTarget);
|
||||
}
|
||||
}
|
||||
|
||||
function findPropertyDescriptor(target: object, prop: string | symbol): PropertyDescriptor | undefined {
|
||||
let current: object | null = target;
|
||||
while (current !== null) {
|
||||
const desc = Reflect.getOwnPropertyDescriptor(current, prop);
|
||||
if (desc) {
|
||||
return desc;
|
||||
}
|
||||
current = Reflect.getPrototypeOf(current);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares a property descriptor coming **from** the VM so `Reflect.defineProperty` on the host
|
||||
* receives real targets, not our proxy objects.
|
||||
*
|
||||
* @param descriptor - Descriptor passed into the proxy `defineProperty` trap.
|
||||
* @returns Descriptor with `value` / `get` / `set` unwrapped where they were our proxies.
|
||||
*/
|
||||
function mapDescriptorForHost(descriptor: PropertyDescriptor): PropertyDescriptor {
|
||||
const mapped: PropertyDescriptor = {};
|
||||
@@ -213,109 +483,210 @@ function mapDescriptorForHost(descriptor: PropertyDescriptor): PropertyDescripto
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwraps the proxy when used as the `receiver` for `Reflect.get`, so host getters see real `this`.
|
||||
* Unwraps the proxy when used as the `receiver` for `Reflect.get` / `Reflect.set`, preserving
|
||||
* VM subclass/object receivers without wrapping them as callback functions.
|
||||
*/
|
||||
function reflectReceiver(receiver: unknown): unknown {
|
||||
return unwrapIfProxy(receiver);
|
||||
if (isOurProxy(receiver)) {
|
||||
return proxyToTarget.get(receiver);
|
||||
}
|
||||
recordVmValue(receiver);
|
||||
return receiver;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwraps constructor references passed to `Reflect.construct`.
|
||||
*
|
||||
* @param newTarget - Constructor received by the proxy `construct` trap.
|
||||
* @returns Host constructor with this module's proxy removed when applicable.
|
||||
* Preserves VM-defined subclass constructors (`newTarget`) instead of wrapping them as callbacks.
|
||||
*/
|
||||
function unwrapConstructor(newTarget: HostCallable): HostConstructor {
|
||||
return unwrapIfProxy(newTarget) as unknown as HostConstructor;
|
||||
if (isOurProxy(newTarget)) {
|
||||
return proxyToTarget.get(newTarget) as HostConstructor;
|
||||
}
|
||||
recordVmValue(newTarget);
|
||||
return newTarget as unknown as HostConstructor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwraps each argument before forwarding calls into host functions so VM-facing proxies
|
||||
* round-trip back to their original host targets.
|
||||
*
|
||||
* @param argList - Arguments received by the proxy `apply` trap.
|
||||
* @returns Arguments with this module's proxies replaced by underlying host targets.
|
||||
* round-trip back to their original host targets and VM callbacks are wrapped for host calls.
|
||||
*/
|
||||
function unwrapArgList(argList: readonly unknown[]): unknown[] {
|
||||
return argList.map((arg) => unwrapIfProxy(arg));
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the shared `ProxyHandler` used for every deep wrap (objects and functions).
|
||||
*
|
||||
* Traps implement the file-level strategy: hide prototype edges, wrap outgoing values, unwrap
|
||||
* incoming `this` / descriptors where required by invariants.
|
||||
* Looks up the real host target for a proxy's shadow target.
|
||||
*/
|
||||
function createDeepHandler(): ProxyHandler<HostTarget> {
|
||||
return {
|
||||
apply(proxyTarget: HostTarget, thisArg: unknown, argArray: unknown[]): unknown {
|
||||
const hostFn = proxyTarget as HostCallable;
|
||||
function resolveHostTarget(shadowTarget: HostTarget): HostTarget {
|
||||
return shadowToHost.get(shadowTarget) ?? shadowTarget;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared `ProxyHandler` for all wrapped host objects and functions.
|
||||
* Resolves `hostTarget` from `shadowTarget` via `shadowToHost`.
|
||||
*/
|
||||
const DEEP_HANDLER: ProxyHandler<HostTarget> = {
|
||||
apply(shadowTarget: HostTarget, thisArg: unknown, argArray: unknown[]): unknown {
|
||||
return runTrapSafely(() => {
|
||||
const hostFn = resolveHostTarget(shadowTarget) as HostCallable;
|
||||
const hostThis = unwrapIfProxy(thisArg);
|
||||
const hostArgs = unwrapArgList(argArray);
|
||||
const result = Reflect.apply(hostFn, hostThis, hostArgs);
|
||||
return wrapIfNeeded(result);
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
construct(proxyTarget: HostTarget, argArray: unknown[], newTarget: unknown): object {
|
||||
const hostCtor = proxyTarget as HostConstructor;
|
||||
construct(shadowTarget: HostTarget, argArray: unknown[], newTarget: unknown): object {
|
||||
return runTrapSafely(() => {
|
||||
const hostCtor = resolveHostTarget(shadowTarget) as HostConstructor;
|
||||
const hostArgs = unwrapArgList(argArray);
|
||||
const hostNewTarget = unwrapConstructor(newTarget as HostCallable);
|
||||
const result = Reflect.construct(hostCtor, hostArgs, hostNewTarget);
|
||||
return wrapIfNeeded(result) as object;
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
defineProperty(target: HostTarget, prop: string | symbol, descriptor: PropertyDescriptor): boolean {
|
||||
return Reflect.defineProperty(target, prop, mapDescriptorForHost(descriptor));
|
||||
},
|
||||
|
||||
get(target: HostTarget, prop: string | symbol, receiver: unknown): unknown {
|
||||
if (isBlockedPrototypeKey(prop)) {
|
||||
return SAFE_LOOKUP_TARGET;
|
||||
}
|
||||
const value = Reflect.get(target, prop, reflectReceiver(receiver));
|
||||
return wrapIfNeeded(value);
|
||||
},
|
||||
|
||||
getOwnPropertyDescriptor(target: HostTarget, prop: string | symbol): PropertyDescriptor | undefined {
|
||||
if (isBlockedPrototypeKey(prop)) {
|
||||
return {
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
value: SAFE_LOOKUP_TARGET,
|
||||
writable: false,
|
||||
};
|
||||
}
|
||||
const descriptor = Reflect.getOwnPropertyDescriptor(target, prop);
|
||||
if (!descriptor) {
|
||||
return undefined;
|
||||
}
|
||||
// Non-configurable properties must keep a descriptor compatible with the target
|
||||
// (SameValue rules for getters / values); wrapping would violate Proxy invariants.
|
||||
if (!descriptor.configurable) {
|
||||
return descriptor;
|
||||
}
|
||||
return mapDescriptorForSandbox(descriptor);
|
||||
},
|
||||
|
||||
getPrototypeOf(target: HostTarget): object | null {
|
||||
void target;
|
||||
return SAFE_LOOKUP_TARGET;
|
||||
},
|
||||
|
||||
has(target: HostTarget, prop: string | symbol): boolean {
|
||||
defineProperty(shadowTarget: HostTarget, prop: string | symbol, descriptor: PropertyDescriptor): boolean {
|
||||
return runTrapSafely(() => {
|
||||
if (isBlockedPrototypeKey(prop)) {
|
||||
return false;
|
||||
}
|
||||
return Reflect.has(target, prop);
|
||||
},
|
||||
const hostTarget = resolveHostTarget(shadowTarget);
|
||||
const defined = Reflect.defineProperty(hostTarget, prop, mapDescriptorForHost(descriptor));
|
||||
if (defined) {
|
||||
syncShadowProperty(shadowTarget, hostTarget, prop);
|
||||
}
|
||||
return defined;
|
||||
});
|
||||
},
|
||||
|
||||
setPrototypeOf(target: HostTarget, prototype: object | null): boolean {
|
||||
void target;
|
||||
void prototype;
|
||||
return false;
|
||||
},
|
||||
};
|
||||
}
|
||||
deleteProperty(shadowTarget: HostTarget, prop: string | symbol): boolean {
|
||||
return runTrapSafely(() => {
|
||||
if (isBlockedPrototypeKey(prop)) {
|
||||
return false;
|
||||
}
|
||||
const hostTarget = resolveHostTarget(shadowTarget);
|
||||
const deleted = Reflect.deleteProperty(hostTarget, prop);
|
||||
if (deleted) {
|
||||
Reflect.deleteProperty(shadowTarget, prop);
|
||||
}
|
||||
return deleted;
|
||||
});
|
||||
},
|
||||
|
||||
get(shadowTarget: HostTarget, prop: string | symbol, receiver: unknown): unknown {
|
||||
return runTrapSafely(() => {
|
||||
if (isBlockedPrototypeKey(prop)) {
|
||||
return SAFE_LOOKUP_TARGET;
|
||||
}
|
||||
const hostTarget = resolveHostTarget(shadowTarget);
|
||||
const value = Reflect.get(hostTarget, prop, reflectReceiver(receiver));
|
||||
const wrapped = wrapIfNeeded(value);
|
||||
const hostDesc = Reflect.getOwnPropertyDescriptor(hostTarget, prop);
|
||||
if (hostDesc && !hostDesc.configurable) {
|
||||
syncShadowProperty(shadowTarget, hostTarget, prop);
|
||||
}
|
||||
return wrapped;
|
||||
});
|
||||
},
|
||||
|
||||
getOwnPropertyDescriptor(shadowTarget: HostTarget, prop: string | symbol): PropertyDescriptor | undefined {
|
||||
return runTrapSafely(() => {
|
||||
if (isBlockedPrototypeKey(prop)) {
|
||||
return undefined;
|
||||
}
|
||||
const hostTarget = resolveHostTarget(shadowTarget);
|
||||
if (!Reflect.isExtensible(hostTarget)) {
|
||||
syncShadowExtensibility(shadowTarget, hostTarget);
|
||||
}
|
||||
return syncShadowProperty(shadowTarget, hostTarget, prop);
|
||||
});
|
||||
},
|
||||
|
||||
getPrototypeOf(_shadowTarget: HostTarget): object | null {
|
||||
return SAFE_LOOKUP_TARGET;
|
||||
},
|
||||
|
||||
has(shadowTarget: HostTarget, prop: string | symbol): boolean {
|
||||
return runTrapSafely(() => {
|
||||
if (isBlockedPrototypeKey(prop)) {
|
||||
return false;
|
||||
}
|
||||
const hostTarget = resolveHostTarget(shadowTarget);
|
||||
const exists = Reflect.has(hostTarget, prop);
|
||||
if (!exists) {
|
||||
syncShadowProperty(shadowTarget, hostTarget, prop);
|
||||
}
|
||||
return exists;
|
||||
});
|
||||
},
|
||||
|
||||
isExtensible(shadowTarget: HostTarget): boolean {
|
||||
return runTrapSafely(() => {
|
||||
const hostTarget = resolveHostTarget(shadowTarget);
|
||||
if (!Reflect.isExtensible(hostTarget)) {
|
||||
syncShadowExtensibility(shadowTarget, hostTarget);
|
||||
}
|
||||
return Reflect.isExtensible(shadowTarget);
|
||||
});
|
||||
},
|
||||
|
||||
ownKeys(shadowTarget: HostTarget): Array<string | symbol> {
|
||||
return runTrapSafely(() => {
|
||||
const hostTarget = resolveHostTarget(shadowTarget);
|
||||
if (!Reflect.isExtensible(hostTarget)) {
|
||||
syncShadowExtensibility(shadowTarget, hostTarget);
|
||||
} else if (Array.isArray(hostTarget)) {
|
||||
syncShadowProperty(shadowTarget, hostTarget, 'length');
|
||||
}
|
||||
const hostKeys = Reflect.ownKeys(hostTarget).filter((key) => !isBlockedPrototypeKey(key));
|
||||
const hostKeySet = new Set<string | symbol>(hostKeys);
|
||||
hostKeys.push(...pruneShadowKeys(shadowTarget, hostKeySet));
|
||||
return hostKeys;
|
||||
});
|
||||
},
|
||||
|
||||
preventExtensions(shadowTarget: HostTarget): boolean {
|
||||
return runTrapSafely(() => {
|
||||
const hostTarget = resolveHostTarget(shadowTarget);
|
||||
if (!Reflect.preventExtensions(hostTarget)) {
|
||||
return false;
|
||||
}
|
||||
syncShadowExtensibility(shadowTarget, hostTarget);
|
||||
return true;
|
||||
});
|
||||
},
|
||||
|
||||
set(shadowTarget: HostTarget, prop: string | symbol, value: unknown, receiver: unknown): boolean {
|
||||
return runTrapSafely(() => {
|
||||
if (isBlockedPrototypeKey(prop)) {
|
||||
return false;
|
||||
}
|
||||
const hostTarget = resolveHostTarget(shadowTarget);
|
||||
const actualReceiver = reflectReceiver(receiver);
|
||||
const desc = findPropertyDescriptor(hostTarget, prop);
|
||||
const invokesHostSetter = Boolean(desc && 'set' in desc && typeof desc.set === 'function');
|
||||
const writesToHost = actualReceiver === hostTarget || isOurProxy(receiver) || invokesHostSetter;
|
||||
const valueToSet = writesToHost ? unwrapIfProxy(value) : value;
|
||||
if (!writesToHost) {
|
||||
recordVmValue(value);
|
||||
}
|
||||
const updated = Reflect.set(hostTarget, prop, valueToSet, actualReceiver);
|
||||
if (
|
||||
updated &&
|
||||
actualReceiver === hostTarget &&
|
||||
Reflect.getOwnPropertyDescriptor(shadowTarget, prop) !== undefined
|
||||
) {
|
||||
syncShadowProperty(shadowTarget, hostTarget, prop);
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
},
|
||||
|
||||
setPrototypeOf(_shadowTarget: HostTarget, _prototype: object | null): boolean {
|
||||
return false;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the one deep proxy for this host target, creating and caching it on first use.
|
||||
@@ -328,31 +699,35 @@ function wrapDeep<T extends HostTarget>(hostValue: T): T {
|
||||
if (typeof hostValue !== 'object' && typeof hostValue !== 'function') {
|
||||
return hostValue;
|
||||
}
|
||||
if (isOurProxy(hostValue)) {
|
||||
return hostValue as T;
|
||||
}
|
||||
const cached = targetToProxy.get(hostValue);
|
||||
if (cached) {
|
||||
return cached as T;
|
||||
}
|
||||
const handler = createDeepHandler();
|
||||
const proxy = new Proxy(hostValue, handler);
|
||||
if (isOurProxy(hostValue) || isVmRealmValue(hostValue)) {
|
||||
return hostValue as T;
|
||||
}
|
||||
const shadowTarget = createShadowTarget(hostValue);
|
||||
shadowToHost.set(shadowTarget, hostValue);
|
||||
const proxy = new Proxy(shadowTarget, DEEP_HANDLER);
|
||||
targetToProxy.set(hostValue, proxy);
|
||||
proxyToTarget.set(proxy, hostValue);
|
||||
return proxy as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively wraps objects and functions; leaves primitives unchanged; routes Promises to the
|
||||
* thenable facade.
|
||||
* Recursively wraps objects and functions; leaves primitives and VM-originated values unchanged;
|
||||
* routes host Promises to the thenable facade.
|
||||
*
|
||||
* @param value - Result of a `get` / `apply` / descriptor field, or any nested host value.
|
||||
* @returns Wrapped proxy, thenable-wrapped promise pipeline, or the original primitive.
|
||||
* @returns Wrapped proxy, thenable-wrapped promise pipeline, or the original primitive/VM value.
|
||||
*/
|
||||
function wrapIfNeeded(value: unknown): unknown {
|
||||
if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {
|
||||
return value;
|
||||
}
|
||||
if (isVmRealmValue(value)) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'function') {
|
||||
return wrapDeep(value as HostCallable);
|
||||
}
|
||||
@@ -361,3 +736,16 @@ function wrapIfNeeded(value: unknown): unknown {
|
||||
}
|
||||
return wrapDeep(value as HostTarget);
|
||||
}
|
||||
|
||||
function createFrozenFallbackError(): RangeError {
|
||||
const err = new RangeError('Maximum call stack size exceeded');
|
||||
Object.defineProperty(err, 'stack', {
|
||||
value: err.stack,
|
||||
writable: false,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
});
|
||||
return Object.freeze(err);
|
||||
}
|
||||
|
||||
const FALLBACK_WRAPPED_ERROR: object = wrapDeep(createFrozenFallbackError());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@appium/execute-driver-plugin",
|
||||
"version": "7.0.2",
|
||||
"version": "7.0.3",
|
||||
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
|
||||
"description": "Plugin for batching and executing Appium driver commands",
|
||||
"keywords": [
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {describe, it} from 'node:test';
|
||||
import {types} from 'node:util';
|
||||
import vm from 'node:vm';
|
||||
|
||||
import {wrapHostBindingForVmContext} from '../../lib/vm-host-binding.js';
|
||||
@@ -64,15 +65,20 @@ describe('wrapHostBindingForVmContext', function () {
|
||||
);
|
||||
});
|
||||
|
||||
it('should still allow setTimeout to schedule callbacks', async function () {
|
||||
it('should still allow setTimeout to schedule callbacks and wrap timer this receiver', async function () {
|
||||
const st = wrapHostBindingForVmContext(setTimeout);
|
||||
const ct = wrapHostBindingForVmContext(clearTimeout);
|
||||
const waited = vm.runInNewContext(
|
||||
`new Promise((resolve) => setTimeout(() => resolve(true), 10))`,
|
||||
`new Promise((resolve) => setTimeout(function () {
|
||||
const escaped = typeof this?.constructor?.constructor === 'function'
|
||||
? this.constructor.constructor('return typeof process')()
|
||||
: 'blocked';
|
||||
resolve(escaped);
|
||||
}, 10))`,
|
||||
{setTimeout: st, clearTimeout: ct},
|
||||
{timeout: 500},
|
||||
) as Promise<boolean>;
|
||||
assert.strictEqual(await waited, true);
|
||||
) as Promise<string>;
|
||||
assert.strictEqual(await waited, 'blocked');
|
||||
});
|
||||
|
||||
it('should block constructor chaining on console method functions', function () {
|
||||
@@ -159,7 +165,7 @@ describe('wrapHostBindingForVmContext', function () {
|
||||
);
|
||||
});
|
||||
|
||||
it('should wrap descriptor values from getOwnPropertyDescriptor', function () {
|
||||
it('should wrap descriptor values from getOwnPropertyDescriptor and preserve attributes', function () {
|
||||
const host = Object.create(null);
|
||||
Object.defineProperty(host, 'm', {
|
||||
value: () => {},
|
||||
@@ -168,18 +174,418 @@ describe('wrapHostBindingForVmContext', function () {
|
||||
configurable: true,
|
||||
});
|
||||
const d = wrapHostBindingForVmContext(host);
|
||||
assert.throws(() =>
|
||||
const check = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`const desc = Object.getOwnPropertyDescriptor(d, 'm');
|
||||
if (!desc || !('value' in desc)) {
|
||||
throw new Error('expected data descriptor with value from getOwnPropertyDescriptor');
|
||||
}
|
||||
const func = desc.value.constructor.constructor;
|
||||
func('return typeof process')()`,
|
||||
JSON.stringify({
|
||||
hasValue: Boolean(desc && typeof desc.value === 'function'),
|
||||
configurable: desc?.configurable,
|
||||
enumerable: desc?.enumerable,
|
||||
writable: desc?.writable,
|
||||
ctorType: typeof desc?.value?.constructor?.constructor,
|
||||
})`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
),
|
||||
) as string,
|
||||
);
|
||||
assert.deepEqual(check, {
|
||||
hasValue: true,
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
ctorType: 'undefined',
|
||||
});
|
||||
});
|
||||
|
||||
it('should wrap non-configurable data descriptors (e.g. driver.commandList) while preserving descriptor flags', function () {
|
||||
const host = Object.create(Object.prototype);
|
||||
Object.defineProperty(host, 'commandList', {
|
||||
value: ['status', 'findElement'],
|
||||
writable: false,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
});
|
||||
const d = wrapHostBindingForVmContext(host);
|
||||
|
||||
const check = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`const desc = Object.getOwnPropertyDescriptor(d, 'commandList');
|
||||
JSON.stringify({
|
||||
items: Array.from(d.commandList),
|
||||
isArray: Array.isArray(d.commandList),
|
||||
configurable: desc?.configurable,
|
||||
enumerable: desc?.enumerable,
|
||||
writable: desc?.writable,
|
||||
ctorType: typeof desc?.value?.constructor?.constructor,
|
||||
})`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
) as string,
|
||||
);
|
||||
assert.deepEqual(check, {
|
||||
items: ['status', 'findElement'],
|
||||
isArray: true,
|
||||
configurable: false,
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
ctorType: 'undefined',
|
||||
});
|
||||
});
|
||||
|
||||
it('should wrap non-configurable accessor descriptors from getOwnPropertyDescriptor while preserving flags', function () {
|
||||
const host = Object.create(Object.prototype);
|
||||
Object.defineProperty(host, 'roGetter', {
|
||||
get: () => ({nested: true}),
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
});
|
||||
const d = wrapHostBindingForVmContext(host);
|
||||
|
||||
const check = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`const desc = Object.getOwnPropertyDescriptor(d, 'roGetter');
|
||||
JSON.stringify({
|
||||
hasGetter: typeof desc?.get === 'function',
|
||||
configurable: desc?.configurable,
|
||||
enumerable: desc?.enumerable,
|
||||
ctorType: typeof desc?.get?.constructor?.constructor,
|
||||
valueCtorType: typeof desc?.get?.()?.constructor?.constructor,
|
||||
})`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
) as string,
|
||||
);
|
||||
assert.deepEqual(check, {
|
||||
hasGetter: true,
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
ctorType: 'undefined',
|
||||
valueCtorType: 'undefined',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle defineProperty with non-configurable data, accessor, partial, and array length descriptors', function () {
|
||||
const host: Record<string, unknown> = {
|
||||
a: 1,
|
||||
b: 2,
|
||||
arr: [10, 20, 30],
|
||||
f: Object.freeze(function frozenFn() {}),
|
||||
};
|
||||
Object.defineProperty(host, 'commandList', {
|
||||
value: 'fixed',
|
||||
writable: false,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
});
|
||||
const d = wrapHostBindingForVmContext(host);
|
||||
|
||||
const result = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`Object.defineProperty(d, 'x', {value: 1, writable: false, configurable: false});
|
||||
const vmObj = {nested: 7};
|
||||
const definedObj = Reflect.defineProperty(d, 'objProp', {
|
||||
value: vmObj,
|
||||
writable: false,
|
||||
configurable: false,
|
||||
});
|
||||
const objPropDesc = Object.getOwnPropertyDescriptor(d, 'objProp');
|
||||
let getterVal = 42;
|
||||
Object.defineProperty(d, 'acc', {get: () => getterVal, enumerable: true, configurable: false});
|
||||
Object.defineProperty(d, 'a', {configurable: false});
|
||||
Object.defineProperty(d, 'commandList', {value: 'fixed'});
|
||||
Object.defineProperty(d.f, 'prototype', {writable: false});
|
||||
Object.defineProperty(d.arr, 'length', {writable: false, configurable: false});
|
||||
JSON.stringify({
|
||||
xDesc: Object.getOwnPropertyDescriptor(d, 'x'),
|
||||
definedObj,
|
||||
objSameAsRead: d.objProp === vmObj,
|
||||
objSameAsDesc: objPropDesc?.value === vmObj,
|
||||
objDescFlags: {
|
||||
writable: objPropDesc?.writable,
|
||||
enumerable: objPropDesc?.enumerable,
|
||||
configurable: objPropDesc?.configurable,
|
||||
},
|
||||
accVal: d.acc,
|
||||
aDesc: Object.getOwnPropertyDescriptor(d, 'a'),
|
||||
keys: Object.keys(d),
|
||||
json: JSON.stringify({a: d.a, b: d.b}),
|
||||
arrLenDesc: Object.getOwnPropertyDescriptor(d.arr, 'length'),
|
||||
})`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
) as string,
|
||||
);
|
||||
|
||||
assert.deepEqual(result.xDesc, {
|
||||
value: 1,
|
||||
writable: false,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
});
|
||||
assert.strictEqual(result.definedObj, true);
|
||||
assert.strictEqual(result.objSameAsRead, true);
|
||||
assert.strictEqual(result.objSameAsDesc, true);
|
||||
assert.deepEqual(result.objDescFlags, {
|
||||
writable: false,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
});
|
||||
assert.strictEqual(result.accVal, 42);
|
||||
assert.deepEqual(result.aDesc, {
|
||||
value: 1,
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
});
|
||||
assert.deepEqual(result.keys, ['a', 'b', 'arr', 'f', 'acc']);
|
||||
assert.strictEqual(result.json, '{"a":1,"b":2}');
|
||||
assert.deepEqual(result.arrLenDesc, {
|
||||
value: 3,
|
||||
writable: false,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('should support Object.freeze, Object.seal, Object.preventExtensions, and extensibility checks', function () {
|
||||
const host = {
|
||||
obj: {a: 1, b: 2},
|
||||
sealed: {x: 10},
|
||||
ext: {y: 20},
|
||||
removable: {
|
||||
x: 1 as number | undefined,
|
||||
remove() {
|
||||
delete this.x;
|
||||
},
|
||||
},
|
||||
arr: [1, 2],
|
||||
frozenArr: Object.freeze([3, 4]),
|
||||
};
|
||||
const d = wrapHostBindingForVmContext(host);
|
||||
|
||||
const result = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`Object.freeze(d.obj);
|
||||
Object.seal(d.sealed);
|
||||
Object.preventExtensions(d.ext);
|
||||
Object.preventExtensions(d.removable);
|
||||
d.removable.remove();
|
||||
Object.freeze(d.arr);
|
||||
JSON.stringify({
|
||||
objFrozen: Object.isFrozen(d.obj),
|
||||
objExtensible: Object.isExtensible(d.obj),
|
||||
objKeys: Object.keys(d.obj),
|
||||
sealedIsSealed: Object.isSealed(d.sealed),
|
||||
extIsExtensible: Object.isExtensible(d.ext),
|
||||
extKeys: Object.keys(d.ext),
|
||||
extDesc: Object.getOwnPropertyDescriptor(d.ext, 'y'),
|
||||
extProto: Object.getPrototypeOf(d.ext) !== null,
|
||||
removableHasX: 'x' in d.removable,
|
||||
arrFrozen: Object.isFrozen(d.arr),
|
||||
frozenArrFrozen: Object.isFrozen(d.frozenArr),
|
||||
frozenArrExtensible: Object.isExtensible(d.frozenArr),
|
||||
frozenArrLenDesc: Object.getOwnPropertyDescriptor(d.frozenArr, 'length'),
|
||||
})`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
) as string,
|
||||
);
|
||||
|
||||
assert.deepEqual(result, {
|
||||
objFrozen: true,
|
||||
objExtensible: false,
|
||||
objKeys: ['a', 'b'],
|
||||
sealedIsSealed: true,
|
||||
extIsExtensible: false,
|
||||
extKeys: ['y'],
|
||||
extDesc: {value: 20, writable: true, enumerable: true, configurable: true},
|
||||
extProto: true,
|
||||
removableHasX: false,
|
||||
arrFrozen: true,
|
||||
frozenArrFrozen: true,
|
||||
frozenArrExtensible: false,
|
||||
frozenArrLenDesc: {value: 2, writable: false, enumerable: false, configurable: false},
|
||||
});
|
||||
});
|
||||
|
||||
it('should support bound constructors and native Proxy without fabricating own prototype', function () {
|
||||
class Foo {
|
||||
public v: unknown;
|
||||
constructor(v: unknown) {
|
||||
this.v = v;
|
||||
}
|
||||
}
|
||||
const BoundFoo = Foo.bind(null);
|
||||
const noOwnProto = Object.assign(() => 1, {});
|
||||
Object.setPrototypeOf(noOwnProto, {prototype: {inherited: true}});
|
||||
|
||||
const host = {
|
||||
BoundFoo,
|
||||
P: Proxy,
|
||||
w: noOwnProto,
|
||||
};
|
||||
const d = wrapHostBindingForVmContext(host);
|
||||
|
||||
const result = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`const inst = new d.BoundFoo('ok');
|
||||
const proxied = new d.P({k: 9}, {});
|
||||
JSON.stringify({
|
||||
instV: inst.v,
|
||||
proxiedK: proxied.k,
|
||||
boundHasOwnProto: Object.prototype.hasOwnProperty.call(d.BoundFoo, 'prototype'),
|
||||
wOwnProtoDesc: Object.getOwnPropertyDescriptor(d.w, 'prototype'),
|
||||
wOwnKeysHasProto: Reflect.ownKeys(d.w).includes('prototype'),
|
||||
deleteWProto: delete d.w.prototype,
|
||||
})`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
) as string,
|
||||
);
|
||||
|
||||
assert.deepEqual(result, {
|
||||
instV: 'ok',
|
||||
proxiedK: 9,
|
||||
boundHasOwnProto: false,
|
||||
wOwnKeysHasProto: false,
|
||||
deleteWProto: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('should wrap host exceptions thrown from construct, get, set, apply, and deleteProperty traps', function () {
|
||||
const host: Record<string, unknown> = {
|
||||
*g() {
|
||||
yield 1;
|
||||
},
|
||||
throwFn() {
|
||||
throw new TypeError('boom');
|
||||
},
|
||||
};
|
||||
Object.defineProperty(host, 'badProp', {
|
||||
get() {
|
||||
throw new Error('getter boom');
|
||||
},
|
||||
set() {
|
||||
throw new Error('setter boom');
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
const d = wrapHostBindingForVmContext(host);
|
||||
|
||||
const results = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`const checks = [];
|
||||
for (const fn of [
|
||||
() => new d.g(),
|
||||
() => d.throwFn(),
|
||||
() => d.badProp,
|
||||
() => { d.badProp = 1; },
|
||||
]) {
|
||||
try {
|
||||
fn();
|
||||
checks.push('did-not-throw');
|
||||
} catch (e) {
|
||||
const processType = typeof e?.constructor?.constructor === 'function'
|
||||
? e.constructor.constructor('return typeof process')()
|
||||
: 'undefined';
|
||||
checks.push(processType);
|
||||
}
|
||||
}
|
||||
JSON.stringify(checks)`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
) as string,
|
||||
);
|
||||
|
||||
assert.deepEqual(results, ['undefined', 'undefined', 'undefined', 'undefined']);
|
||||
});
|
||||
|
||||
it('should wrap arguments passed to VM callbacks from host methods (e.g. Array.prototype.forEach)', function () {
|
||||
const host = {
|
||||
arr: [{secret: 'a'}, {secret: 'b'}],
|
||||
};
|
||||
const d = wrapHostBindingForVmContext(host);
|
||||
|
||||
const check = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`const results = [];
|
||||
d.arr.forEach(function (item) {
|
||||
const escaped = typeof item?.constructor?.constructor === 'function'
|
||||
? item.constructor.constructor('return typeof process')()
|
||||
: 'blocked';
|
||||
results.push(escaped);
|
||||
});
|
||||
JSON.stringify(results)`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
) as string,
|
||||
);
|
||||
|
||||
assert.deepEqual(check, ['blocked', 'blocked']);
|
||||
});
|
||||
|
||||
it('should preserve function source for WebdriverIO driver.execute script serialization', function () {
|
||||
const host = {
|
||||
execute(script: string | ((...args: unknown[]) => unknown), ...args: unknown[]) {
|
||||
const serialized = typeof script === 'function' ? `return (${script}).apply(null, arguments)` : script;
|
||||
return vm.runInNewContext(`(function () { ${serialized} }).apply(null, args)`, {args});
|
||||
},
|
||||
};
|
||||
const d = wrapHostBindingForVmContext(host);
|
||||
|
||||
const value = vm.runInNewContext(`d.execute(() => 42)`, {d}, {timeout: 500});
|
||||
assert.strictEqual(value, 42);
|
||||
});
|
||||
|
||||
it('should refuse set, deleteProperty, and defineProperty on constructor and __proto__', function () {
|
||||
const host: Record<string, unknown> = {a: 1};
|
||||
const d = wrapHostBindingForVmContext(host);
|
||||
|
||||
const result = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`JSON.stringify({
|
||||
setCtor: Reflect.set(d, 'constructor', 123),
|
||||
setProto: Reflect.set(d, '__proto__', {}),
|
||||
delCtor: Reflect.deleteProperty(d, 'constructor'),
|
||||
delProto: Reflect.deleteProperty(d, '__proto__'),
|
||||
defCtor: Reflect.defineProperty(d, 'constructor', {value: 1}),
|
||||
defProto: Reflect.defineProperty(d, '__proto__', {value: 1}),
|
||||
hasCtor: 'constructor' in d,
|
||||
hasProto: '__proto__' in d,
|
||||
ownDescriptorCtor: Object.getOwnPropertyDescriptor(d, 'constructor') ?? null,
|
||||
})`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
) as string,
|
||||
);
|
||||
|
||||
assert.deepEqual(result, {
|
||||
setCtor: false,
|
||||
setProto: false,
|
||||
delCtor: false,
|
||||
delProto: false,
|
||||
defCtor: false,
|
||||
defProto: false,
|
||||
hasCtor: false,
|
||||
hasProto: false,
|
||||
ownDescriptorCtor: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('should forward property writes, unwrap proxied values on set, deletes, and key enumeration to the host target', function () {
|
||||
const original = {tag: 'inner'};
|
||||
const host: Record<string, unknown> = {a: 1, b: 2, orig: original};
|
||||
const d = wrapHostBindingForVmContext(host);
|
||||
const keys = vm.runInNewContext(
|
||||
`d.c = d.orig;
|
||||
delete d.a;
|
||||
Object.keys(d);`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
);
|
||||
assert.deepEqual(Array.from(keys as string[]), ['b', 'orig', 'c']);
|
||||
assert.strictEqual(host.a, undefined);
|
||||
assert.strictEqual(host.c, original);
|
||||
});
|
||||
|
||||
it('should preserve identity for repeated reads of the same nested method', function () {
|
||||
@@ -237,6 +643,115 @@ describe('wrapHostBindingForVmContext', function () {
|
||||
assert.strictEqual(ctorArgRoundTripsAsOriginal, true);
|
||||
});
|
||||
|
||||
it('should preserve VM subclass constructors passed as newTarget when extending a wrapped host constructor', function () {
|
||||
const Box = function (this: {v: unknown}, v: unknown) {
|
||||
this.v = v;
|
||||
} as unknown as new (v: unknown) => {v: unknown};
|
||||
const d = wrapHostBindingForVmContext({Box});
|
||||
const result = vm.runInNewContext(
|
||||
`class Sub extends d.Box {
|
||||
twice() {
|
||||
return this.v * 2;
|
||||
}
|
||||
}
|
||||
new Sub(21).twice();`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
);
|
||||
assert.strictEqual(result, 42);
|
||||
});
|
||||
|
||||
it('should preserve VM-originated error identity and instanceof when thrown through a host trap', function () {
|
||||
const d = wrapHostBindingForVmContext({arr: [1]});
|
||||
const ok = vm.runInNewContext(
|
||||
`class MyError extends Error {}
|
||||
const original = new MyError('x');
|
||||
let caught;
|
||||
try {
|
||||
d.arr.forEach(() => {
|
||||
throw original;
|
||||
});
|
||||
} catch (e) {
|
||||
caught = e;
|
||||
}
|
||||
caught === original && caught instanceof MyError;`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
);
|
||||
assert.strictEqual(ok, true);
|
||||
});
|
||||
|
||||
it('should preserve constructibility, async branding, name, length, static receiver, and wrapper identity for VM callables', async function () {
|
||||
let seenWrapper1: unknown;
|
||||
let seenWrapper2: unknown;
|
||||
const host = {
|
||||
Base: class Base {
|
||||
static get who() {
|
||||
return this;
|
||||
}
|
||||
},
|
||||
instantiate(Ctor: new (v: number) => {val: number}, v: number) {
|
||||
return new Ctor(v);
|
||||
},
|
||||
inspectAsync(fn: (...args: unknown[]) => unknown) {
|
||||
return {
|
||||
isAsync: types.isAsyncFunction(fn),
|
||||
name: fn.name,
|
||||
length: fn.length,
|
||||
};
|
||||
},
|
||||
rememberFirst(fn: unknown) {
|
||||
seenWrapper1 = fn;
|
||||
return fn;
|
||||
},
|
||||
rememberSecond(fn: unknown) {
|
||||
seenWrapper2 = fn;
|
||||
},
|
||||
};
|
||||
const d = wrapHostBindingForVmContext(host);
|
||||
|
||||
const res = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`class Foo {
|
||||
constructor(v) {
|
||||
this.val = v * 3;
|
||||
}
|
||||
}
|
||||
class Sub extends d.Base {}
|
||||
async function myTask(a, b) {
|
||||
return a + b;
|
||||
}
|
||||
const cb = function onEvent(x) { return x; };
|
||||
const echoed = d.rememberFirst(cb);
|
||||
d.rememberSecond(echoed);
|
||||
const inst = d.instantiate(Foo, 7);
|
||||
const meta = d.inspectAsync(myTask);
|
||||
JSON.stringify({
|
||||
isFoo: inst instanceof Foo,
|
||||
val: inst.val,
|
||||
subReceiverMatches: Sub.who === Sub,
|
||||
echoedMatchesCb: echoed === cb,
|
||||
meta,
|
||||
});`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
) as string,
|
||||
);
|
||||
|
||||
assert.deepEqual(res, {
|
||||
isFoo: true,
|
||||
val: 21,
|
||||
subReceiverMatches: true,
|
||||
echoedMatchesCb: true,
|
||||
meta: {
|
||||
isAsync: true,
|
||||
name: 'myTask',
|
||||
length: 2,
|
||||
},
|
||||
});
|
||||
assert.strictEqual(seenWrapper1, seenWrapper2);
|
||||
});
|
||||
|
||||
it('should not double-wrap function proxies', function () {
|
||||
const fn = function hostFn() {
|
||||
return 1;
|
||||
@@ -270,4 +785,291 @@ describe('wrapHostBindingForVmContext', function () {
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('should keep VM functions on VM receivers, resync preventExtensions deletions, and wrap null-proto chains', function () {
|
||||
const nonExtHost: Record<string, unknown> = Object.preventExtensions({a: 1, b: 2});
|
||||
const nullProtoBase = Object.create(null);
|
||||
nullProtoBase.fn = function () {
|
||||
return 'from-null-proto';
|
||||
};
|
||||
const nullProtoChild = Object.create(nullProtoBase);
|
||||
const hostNullWithFn = Object.assign(Object.create(null), {
|
||||
fn() {
|
||||
return 'host-null-fn';
|
||||
},
|
||||
});
|
||||
class HostFoo {}
|
||||
const hostReceiver = {tag: 'host-this'};
|
||||
const d = wrapHostBindingForVmContext({
|
||||
x: 1,
|
||||
obj: {x: 1},
|
||||
Foo: HostFoo,
|
||||
nonExtHost,
|
||||
nullProtoChild,
|
||||
echo(v: unknown) {
|
||||
return v;
|
||||
},
|
||||
getHostNullWithFn() {
|
||||
return hostNullWithFn;
|
||||
},
|
||||
runWithHostThis(cb: (this: unknown) => unknown) {
|
||||
return cb.call(hostReceiver);
|
||||
},
|
||||
deleteHostA() {
|
||||
delete nonExtHost.a;
|
||||
},
|
||||
});
|
||||
d.echo(hostNullWithFn);
|
||||
|
||||
const res = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`const o = Object.create(d);
|
||||
const fn = function () {};
|
||||
o.cb = fn;
|
||||
const nullReceiver = Object.create(null);
|
||||
Reflect.set(d.obj, 'x', fn, nullReceiver);
|
||||
class X extends d.Foo {}
|
||||
const x = new X();
|
||||
x.cb = fn;
|
||||
const forgedFn = function () {
|
||||
return typeof this?.constructor?.constructor === 'function'
|
||||
? this.constructor.constructor('return typeof process')()
|
||||
: 'blocked';
|
||||
};
|
||||
Object.setPrototypeOf(forgedFn, Object.getPrototypeOf(d));
|
||||
const nonStringNameFn = () => 'ran';
|
||||
Object.defineProperty(nonStringNameFn, 'name', {value: 5});
|
||||
const keysBefore = Object.keys(d.nonExtHost);
|
||||
d.deleteHostA();
|
||||
const keysAfter = Object.keys(d.nonExtHost);
|
||||
const leakedNull = d.getHostNullWithFn();
|
||||
const leakedNullEscape =
|
||||
typeof leakedNull.fn?.constructor?.constructor === 'function'
|
||||
? leakedNull.fn.constructor.constructor('return typeof process')()
|
||||
: 'blocked';
|
||||
JSON.stringify({
|
||||
oCbSame: o.cb === fn,
|
||||
oCbProcessType: o.cb.constructor.constructor('return typeof process')(),
|
||||
nullReceiverSame: nullReceiver.x === fn,
|
||||
nullReceiverProcessType: nullReceiver.x.constructor.constructor('return typeof process')(),
|
||||
xCbSame: x.cb === fn,
|
||||
xCbProcessType: x.cb.constructor.constructor('return typeof process')(),
|
||||
forgedFnThisCheck: d.runWithHostThis(forgedFn),
|
||||
nonStringNameResult: d.runWithHostThis(nonStringNameFn),
|
||||
keysBefore,
|
||||
keysAfter,
|
||||
nullProtoFnVal: d.nullProtoChild.fn(),
|
||||
nullProtoFnCtorProto: Object.getPrototypeOf(d.nullProtoChild.fn.constructor),
|
||||
leakedNullFnVal: leakedNull.fn(),
|
||||
leakedNullEscape,
|
||||
})`,
|
||||
{d},
|
||||
{timeout: 500},
|
||||
) as string,
|
||||
);
|
||||
|
||||
assert.deepEqual(res, {
|
||||
oCbSame: true,
|
||||
oCbProcessType: 'undefined',
|
||||
nullReceiverSame: true,
|
||||
nullReceiverProcessType: 'undefined',
|
||||
xCbSame: true,
|
||||
xCbProcessType: 'undefined',
|
||||
forgedFnThisCheck: 'blocked',
|
||||
nonStringNameResult: 'ran',
|
||||
keysBefore: ['a', 'b'],
|
||||
keysAfter: ['b'],
|
||||
nullProtoFnVal: 'from-null-proto',
|
||||
nullProtoFnCtorProto: null,
|
||||
leakedNullFnVal: 'host-null-fn',
|
||||
leakedNullEscape: 'blocked',
|
||||
});
|
||||
});
|
||||
|
||||
it('should wrap host RangeError on stack overflow across call, construct, and async VM wrappers and wrap host newTarget', async function () {
|
||||
class HostSub {}
|
||||
const d = wrapHostBindingForVmContext({
|
||||
now(cb: () => unknown) {
|
||||
return cb();
|
||||
},
|
||||
constructNow(Ctor: new () => object) {
|
||||
return new Ctor();
|
||||
},
|
||||
constructWithHostNewTarget(Ctor: new () => object) {
|
||||
return Reflect.construct(Ctor, [], HostSub);
|
||||
},
|
||||
});
|
||||
|
||||
const res = JSON.parse(
|
||||
(await vm.runInNewContext(
|
||||
`(async () => {
|
||||
let callErr;
|
||||
function goCall(n) {
|
||||
try {
|
||||
return d.now(function () {
|
||||
return goCall(n + 1);
|
||||
});
|
||||
} catch (e) {
|
||||
callErr = e;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
try {
|
||||
goCall(0);
|
||||
} catch {}
|
||||
|
||||
let ctorErr;
|
||||
function goCtor(n) {
|
||||
try {
|
||||
return d.constructNow(function () {
|
||||
return goCtor(n + 1);
|
||||
});
|
||||
} catch (e) {
|
||||
ctorErr = e;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
try {
|
||||
goCtor(0);
|
||||
} catch {}
|
||||
|
||||
let asyncErr;
|
||||
try {
|
||||
await d.now(async function () {
|
||||
function syncLoop(n) {
|
||||
return d.now(() => syncLoop(n + 1));
|
||||
}
|
||||
return syncLoop(0);
|
||||
});
|
||||
} catch (e) {
|
||||
asyncErr = e;
|
||||
}
|
||||
|
||||
let seenNewTarget;
|
||||
d.constructWithHostNewTarget(function () {
|
||||
seenNewTarget = new.target;
|
||||
});
|
||||
|
||||
const isRangeErr = (val) => Boolean(val && typeof val === 'object' && val.name === 'RangeError');
|
||||
const checkEscape = (val) => {
|
||||
if (val === undefined || val === null) {
|
||||
return 'missing';
|
||||
}
|
||||
return typeof val.constructor?.constructor === 'function'
|
||||
? val.constructor.constructor('return typeof process')()
|
||||
: 'blocked';
|
||||
};
|
||||
|
||||
return JSON.stringify({
|
||||
callIsError: isRangeErr(callErr),
|
||||
ctorIsError: isRangeErr(ctorErr),
|
||||
asyncIsError: isRangeErr(asyncErr),
|
||||
newTargetIsFn: typeof seenNewTarget === 'function',
|
||||
callCheck: checkEscape(callErr),
|
||||
ctorCheck: checkEscape(ctorErr),
|
||||
asyncCheck: checkEscape(asyncErr),
|
||||
newTargetCheck: checkEscape(seenNewTarget),
|
||||
});
|
||||
})()`,
|
||||
{d},
|
||||
{timeout: 2000},
|
||||
)) as string,
|
||||
);
|
||||
|
||||
assert.deepEqual(res, {
|
||||
callIsError: true,
|
||||
ctorIsError: true,
|
||||
asyncIsError: true,
|
||||
newTargetIsFn: true,
|
||||
callCheck: 'blocked',
|
||||
ctorCheck: 'blocked',
|
||||
asyncCheck: 'blocked',
|
||||
newTargetCheck: 'blocked',
|
||||
});
|
||||
});
|
||||
|
||||
it('should keep the fallback RangeError immutable across VM mutations and freezes', function () {
|
||||
const poisonedError = new Proxy(
|
||||
{},
|
||||
{
|
||||
getPrototypeOf() {
|
||||
throw new Error('unwrappable');
|
||||
},
|
||||
},
|
||||
);
|
||||
const d = wrapHostBindingForVmContext({
|
||||
triggerFallback() {
|
||||
throw poisonedError;
|
||||
},
|
||||
});
|
||||
|
||||
const first = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`(() => {
|
||||
let err;
|
||||
try {
|
||||
d.triggerFallback();
|
||||
} catch (e) {
|
||||
err = e;
|
||||
}
|
||||
const initialStackLine = String(err.stack).split('\\n')[0];
|
||||
err.message = 'mutated';
|
||||
err.stack = 'mutated-stack';
|
||||
err.foo = 1;
|
||||
let strictSetThrew = false;
|
||||
try {
|
||||
(() => { 'use strict'; err.message = 'strict-mutated'; })();
|
||||
} catch (e) {
|
||||
strictSetThrew = e instanceof TypeError;
|
||||
}
|
||||
const defMutate = Reflect.defineProperty(err, 'message', {value: 'x'});
|
||||
const defNew = Reflect.defineProperty(err, 'foo', {value: 1});
|
||||
const defNoop = Reflect.defineProperty(err, 'message', {});
|
||||
const prevented = Object.preventExtensions(err) === err;
|
||||
const frozen = Object.freeze(err) === err;
|
||||
return JSON.stringify({
|
||||
initialStackLine,
|
||||
strictSetThrew,
|
||||
defMutate,
|
||||
defNew,
|
||||
defNoop,
|
||||
prevented,
|
||||
frozen,
|
||||
isFrozen: Object.isFrozen(err),
|
||||
});
|
||||
})()`,
|
||||
{d},
|
||||
) as string,
|
||||
);
|
||||
|
||||
const second = JSON.parse(
|
||||
vm.runInNewContext(
|
||||
`(() => {
|
||||
try {
|
||||
d.triggerFallback();
|
||||
} catch (e) {
|
||||
return JSON.stringify({
|
||||
message: e.message,
|
||||
stackLine: String(e.stack).split('\\n')[0],
|
||||
hasFoo: 'foo' in e,
|
||||
});
|
||||
}
|
||||
})()`,
|
||||
{d},
|
||||
) as string,
|
||||
);
|
||||
|
||||
assert.equal(first.strictSetThrew, true);
|
||||
assert.equal(first.defMutate, false);
|
||||
assert.equal(first.defNew, false);
|
||||
assert.equal(first.defNoop, true);
|
||||
assert.equal(first.prevented, true);
|
||||
assert.equal(first.frozen, true);
|
||||
assert.equal(first.isFrozen, true);
|
||||
assert.deepEqual(second, {
|
||||
message: 'Maximum call stack size exceeded',
|
||||
stackLine: first.initialStackLine,
|
||||
hasFoo: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,14 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## [4.4.3](https://github.com/appium/appium/compare/@appium/fake-plugin@4.4.2...@appium/fake-plugin@4.4.3) (2026-11-14)
|
||||
|
||||
**Note:** Version bump only for package @appium/fake-plugin
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## [4.4.2](https://github.com/appium/appium/compare/@appium/fake-plugin@4.4.1...@appium/fake-plugin@4.4.2) (2026-10-27)
|
||||
|
||||
**Note:** Version bump only for package @appium/fake-plugin
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@appium/fake-plugin",
|
||||
"version": "4.4.2",
|
||||
"version": "4.4.3",
|
||||
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
|
||||
"description": "A fake Appium plugin",
|
||||
"keywords": [
|
||||
@@ -43,7 +43,7 @@
|
||||
"test:unit": "node --test --enable-source-maps --test-timeout=5000 \"./build/test/unit/**/*.spec.js\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@appium/base-plugin": "3.3.6",
|
||||
"@appium/base-plugin": "3.3.7",
|
||||
"@appium/support": "7.2.9",
|
||||
"asyncbox": "6.5.0"
|
||||
},
|
||||
|
||||
@@ -3,6 +3,14 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## [3.0.3](https://github.com/appium/appium/compare/@appium/universal-xml-plugin@3.0.2...@appium/universal-xml-plugin@3.0.3) (2026-11-14)
|
||||
|
||||
**Note:** Version bump only for package @appium/universal-xml-plugin
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## [3.0.2](https://github.com/appium/appium/compare/@appium/universal-xml-plugin@3.0.1...@appium/universal-xml-plugin@3.0.2) (2026-10-27)
|
||||
|
||||
**Note:** Version bump only for package @appium/universal-xml-plugin
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@appium/universal-xml-plugin",
|
||||
"version": "3.0.2",
|
||||
"version": "3.0.3",
|
||||
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
|
||||
"description": "Appium plugin for making XML source and XPath queries the same across iOS and Android",
|
||||
"keywords": [
|
||||
@@ -50,7 +50,7 @@
|
||||
"dependencies": {
|
||||
"@appium/support": "7.2.9",
|
||||
"@xmldom/xmldom": "0.9.12",
|
||||
"fast-xml-parser": "5.11.2",
|
||||
"fast-xml-parser": "5.12.0",
|
||||
"xpath": "0.0.35"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
Reference in New Issue
Block a user