Compare commits

..
Author SHA1 Message Date
github-actions 19b5d082d5 chore: publish
- appium@4.0.2
 - @appium/archward@1.1.0
 - @appium/base-driver@11.0.2
 - @appium/base-plugin@4.0.2
 - @appium/docutils@4.0.2
 - @appium/driver-test-support@4.0.2
 - @appium/execute-driver-plugin@9.0.1
 - @appium/fake-driver@7.0.2
 - @appium/fake-plugin@5.0.2
 - @appium/http-server@1.0.2
 - @appium/images-plugin@6.0.2
 - @appium/opencv@6.0.1
 - @appium/plugin-test-support@4.0.2
 - @appium/relaxed-caps-plugin@4.0.1
 - @appium/storage-plugin@3.0.2
 - @appium/support@8.0.2
 - @appium/types@3.0.0
 - @appium/universal-xml-plugin@4.0.2
2026-11-27 07:31:35 +00:00
Mykola Mokhnach 67f151f6f3 feat(archward): add package that checks a package against its C4 model (#23225) 2026-11-27 08:27:34 +01:00
Chirag Panchal d3dc4bd9c8 docs: fix dead links to moved base-driver source files (#23229)
basedriver/helpers.ts was split into basedriver/helpers/ (configureApp is in app-cache.ts) and protocol/bidi-commands.ts became the protocol/bidi-commands/ directory.
2026-11-26 21:51:35 +02:00
feca1714c9 docs(appium): Update documentation translations (#23227)
* docs(appium): Update documentation translations

* docs: update authors (ja)

* docs: update authors (zh)

---------

Co-authored-by: mykola-mokhnach <7767781+mykola-mokhnach@users.noreply.github.com>
Co-authored-by: Edgars Eglītis <37242620+eglitise@users.noreply.github.com>
2026-11-26 12:55:22 +02:00
renovate[bot] a2caed50f6 chore(universal-xml-plugin): update dependency xpath to v0.1.0 (#23228)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-26 12:53:48 +02:00
Lê Văn Xuân Hoàn df431dd271 feat(types)!: check method map payload params against command signatures (#23158)
BREAKING CHANGE: MethodMap, DriverMethodMap, PluginMethodMap, DriverMethodDef, and PluginMethodDef now validate command names and payloadParams against driver and plugin command signatures by default. Pass MethodMap<T, false> or DriverMethodDef<T, true> / PluginMethodDef<T, true> for proxied or handle()-dispatched routes.
2026-11-25 21:10:03 +01:00
renovate[bot] c553d48b21 chore(docutils): update dependency mkdocs-git-revision-date-localized-plugin to v1.7.1 (#23226)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-25 11:09:48 +00:00
Edgars Eglītis 3f09891f6a docs: add Appium 4 blogpost (#23224) 2026-11-25 13:00:28 +02:00
Erin Krasniqi a68b15fdae fix(appium): clean up sessions when a createSession plugin fails (#23217) 2026-11-25 11:00:06 +01:00
renovate[bot] 6db045b5e7 chore(deps): update dependency npm-run-all2 to v9.1.0 (#23222)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-24 21:32:40 +01:00
github-actions[bot]andmykola-mokhnach c3f1b23d22 docs(appium): Update documentation translations (#23219)
Co-authored-by: mykola-mokhnach <7767781+mykola-mokhnach@users.noreply.github.com>
2026-11-24 15:00:54 +02:00
renovate[bot] 7d1472051a chore(deps): update dependency lerna to v10.1.3 (#23218)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-24 01:39:45 +00:00
github-actions e72b4765eb chore: publish
- appium@4.0.1
 - @appium/base-driver@11.0.1
 - @appium/base-plugin@4.0.1
 - @appium/docutils@4.0.1
 - @appium/driver-test-support@4.0.1
 - @appium/execute-driver-plugin@9.0.0
 - @appium/fake-driver@7.0.1
 - @appium/fake-plugin@5.0.1
 - @appium/http-server@1.0.1
 - @appium/images-plugin@6.0.1
 - @appium/oxc-config@2.0.1
 - @appium/plugin-test-support@4.0.1
 - @appium/storage-plugin@3.0.1
 - @appium/support@8.0.1
 - @appium/universal-xml-plugin@4.0.1
2026-11-23 18:09:34 +00:00
github-actions[bot] e862062656 docs(appium): Update documentation translations (#23216) 2026-11-22 08:54:40 +01:00
Mohamed Mostafa 43ffd5f888 fix(appium): remove a session before its driver finishes deleting it (#23215)
* fix(appium): remove a session before its driver finishes deleting it

* fix(appium): wait for sessions that are still being deleted in deleteAllSessions

* style(base-driver): collapse the settings prototype assertion onto one line
2026-11-22 11:38:48 +09:00
Mohamed Mostafa a7fbe25a0c fix(appium): give each createSession call its own plugin instances (#23214) 2026-11-21 23:20:17 +01:00
bob 3599786ecb fix(base-driver): reject prototype-polluting keys in settings updates (#23132) 2026-11-21 22:35:40 +01:00
renovate[bot] 0edc780de6 chore(workflows): update slackapi/slack-github-action action to v4.1.0 (#23213)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-21 15:01:23 +00:00
github-actions[bot]andmykola-mokhnach d16d9cb52d docs(appium): Update documentation translations (#23212)
Co-authored-by: mykola-mokhnach <7767781+mykola-mokhnach@users.noreply.github.com>
2026-11-21 12:49:08 +02:00
Edgars Eglītis 374f3de136 ci: update docs build to use v-prefixed major versions (#23211) 2026-11-20 15:55:57 +02:00
renovate[bot] d34f3c776f chore(oxc-config): update dependency oxfmt to ^0.79.0 (#23208)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-20 13:21:31 +02:00
github-actions[bot] c94ae059d2 docs(appium): Update documentation translations (#23205) 2026-11-20 10:42:31 +01:00
renovate[bot] 1a10293c99 chore(deps): update dependency lerna to v10.1.2 (#23206)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-20 10:42:09 +01:00
renovate[bot] a6eeaf2ad4 chore(docutils): update dependency mkdocs-material to v9.8.2 (#23207)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-20 10:41:56 +01:00
renovate[bot] 71390a1f66 chore(oxc-config): update dependency oxlint to ~1.94.0 (#23209)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-20 10:41:30 +01:00
Mykola Mokhnach db8a58813b fix(base-driver): bound the state of the BiDi subscriptions (#23198) 2026-11-20 08:09:12 +01:00
Mykola Mokhnach bca239835c fix(appium): release the manifest lock while a driver/plugin script runs (#23204) 2026-11-19 20:52:09 +01:00
Edgars Eglītis 25bd5bf4ea docs: remove obsolete CORS flag (#23202) 2026-11-19 17:02:32 +02:00
Edgars Eglītis 3914e063aa docs: update system requirements (#23201) 2026-11-19 15:59:58 +02:00
renovate[bot] b280f9be09 chore(oxc-config): update dependency oxfmt to ^0.78.0 (#23189)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 16:17:03 +01:00
renovate[bot] da10cfbe21 chore(oxc-config): update dependency oxlint to ~1.93.0 (#23190)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 14:55:04 +01:00
renovate[bot] 4332de0e9a chore(storage-plugin): update dependency ws to v8.23.0 (#23192)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 14:54:45 +01:00
renovate[bot] 2359d23f0c chore(storage-plugin): update dependency asyncbox to v7.1.0 (#23196)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 14:54:31 +01:00
Mykola Mokhnach 2890b29429 fix(images-plugin): match asyncbox condition-unmet errors by code (#23195) 2026-11-18 14:27:07 +01:00
Edgars Eglītis 963e4736ef chore(deps): remove obsolete overrides (#23194) 2026-11-18 12:51:35 +02:00
renovate[bot] 199685cd34 chore(appium): update dependency axios to v1.21.1 (#23188)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 11:28:56 +01:00
Edgars Eglītis dc16743660 chore(storage-plugin): bump server peer dependency (#23191) 2026-11-18 12:15:21 +02:00
renovate[bot] 5aa0c79f11 chore(universal-xml-plugin): update dependency xpath to v0.0.36 (#23187)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 11:55:31 +02:00
renovate[bot] 55ebb84f6e chore(appium): update dependency lilconfig to v3.1.5 (#23185)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 07:59:06 +01:00
renovate[bot] 363d3a5cb5 chore(appium): update dependency semver to v7.8.6 (#23186)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 07:58:51 +01:00
renovate[bot] 17e3d03be1 chore(support): update dependency @types/yauzl to v3 (#23184)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 07:42:48 +01:00
renovate[bot] 3495c46a99 chore(deps): update dependency @types/ws to v8.18.2 (#23183)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 02:29:44 +00:00
renovate[bot] 8b6482033e chore(deps): update dependency @tsconfig/node22 to v22.0.7 (#23182)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-17 14:45:46 +00:00
renovate[bot] 12afc85064 chore(docutils): update dependency mkdocs-git-revision-date-localized-plugin to v1.7.0 (#23181)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-17 12:59:02 +00:00
renovate[bot] 4f9fe05442 chore(docutils): update dependency mkdocs-material to v9.8.1 (#23179)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-17 04:42:29 +00:00
renovate[bot] 51cfc7b292 chore(workflows): update peter-evans/create-pull-request action to v8.1.3 (#23180)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 19:31:14 +00:00
github-actions[bot]andmykola-mokhnach e67a1980b0 docs(appium): Update documentation translations (#23174)
Co-authored-by: mykola-mokhnach <7767781+mykola-mokhnach@users.noreply.github.com>
2026-11-16 20:43:19 +02:00
renovate[bot] 8bd55ec338 chore(appium): update dependency argparse to v3.0.4 (#23178)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 19:26:19 +01:00
Lê Văn Xuân Hoàn aad17b1ba9 test(http-server): declare FakeDriver newMethodMap as const (#23176) 2026-11-16 09:58:12 +01:00
Mohamed Mostafa a8d646b6cc fix(support): apply case-only moves on macOS too (#23147) 2026-11-15 23:10:01 +01:00
Mykola Mokhnach 2b232adb2a feat(execute-driver-plugin)!: update webdriverio to v10 (#23170)
BREAKING CHANGE: webdriverio 10 requires Node.js ^22.23.4 || ^24.22.1 || >=26.12.1, so the plugin's minimum supported Node versions are raised accordingly.
2026-11-15 21:58:26 +01:00
Edgars Eglītis 2a6ef950f0 docs: update migration guide to remove beta references (#23173) 2026-11-15 22:12:13 +02:00
jimbob1414andClaude Opus 5.5 96bcc11ff4 docs: add BenchFleet Appium to Ecosystem tools document (#23171)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 21:18:57 +02:00
Edgars Eglītis f7ccf0fb7c docs: link to Appium 4 migration guide + update aggregate changelog (#23172) 2026-11-15 20:57:21 +02:00
Mykola Mokhnach 5e1ec327c4 chore(deps): update dependency webdriverio to v10 (#23169) 2026-11-15 15:50:36 +01:00
Mykola Mokhnach 61bfbebe3c chore(deps): update dependency @types/node to v26 (#23168) 2026-11-15 15:23:37 +01:00
renovate[bot] 6447e97999 chore(http-server): update dependency path-to-regexp to v9 (#23113)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 15:23:05 +01:00
renovate[bot] 5cf9d9bba6 chore(support): update dependency teen_process to v5 (#23167)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 15:21:29 +01:00
renovate[bot] 0f5284f1f4 chore(support): update dependency asyncbox to v7 (#23166)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-15 15:11:51 +01:00
178 changed files with 10535 additions and 3486 deletions
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
CROWDIN_PROJECT_ID: ${{ vars[matrix.project_id_var] }}
CROWDIN_TOKEN: ${{ secrets.CROWDIN_DOCS_TOKEN }}
- name: Post to Slack for ${{ matrix.project_name }}
uses: slackapi/slack-github-action@v4.0.0
uses: slackapi/slack-github-action@v4.1.0
with:
errors: true
webhook: ${{ secrets.SLACK_WEBHOOK_URL }}
@@ -29,7 +29,7 @@ jobs:
CROWDIN_PROJECT_ID: ${{ vars.CROWDIN_DOCS_PROJECT_ID }}
CROWDIN_TOKEN: ${{ secrets.CROWDIN_DOCS_TOKEN }}
- name: Create Pull Request
uses: peter-evans/create-pull-request@v8.1.1
uses: peter-evans/create-pull-request@v8.1.3
with:
token: ${{ github.token }}
commit-message: 'docs(appium): Update documentation translations'
+1 -1
View File
@@ -29,7 +29,7 @@ jobs:
# GITHUB_TOKEN is optional - if not provided, uses unauthenticated requests (rate limited)
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Post to Slack
uses: slackapi/slack-github-action@v4.0.0
uses: slackapi/slack-github-action@v4.1.0
with:
errors: true
webhook: ${{ secrets.SLACK_WEBHOOK_URL }}
+2 -1
View File
@@ -24,9 +24,9 @@ to driver/client documentation
* [base-plugin](packages/base-plugin/CHANGELOG.md)
* [docutils](packages/docutils/CHANGELOG.md)
* [driver-test-support](packages/driver-test-support/CHANGELOG.md)
* [eslint-config-appium-ts](packages/eslint-config-appium-ts/CHANGELOG.md)
* [fake-driver](packages/fake-driver/CHANGELOG.md)
* [fake-plugin](packages/fake-plugin/CHANGELOG.md)
* [http-server](packages/http-server/CHANGELOG.md)
* [logger](packages/logger/CHANGELOG.md)
* [opencv](packages/opencv/CHANGELOG.md)
* [oxc-config](packages/oxc-config/CHANGELOG.md)
@@ -42,6 +42,7 @@ to driver/client documentation
The changelog links used for these modules lead to the last version of their changelog file.
* [doctor](https://github.com/appium/appium/blob/8daf5e123ac14c8325acf504fb33eb28e1a3dd78/packages/doctor/CHANGELOG.md) ([removal PR](https://github.com/appium/appium/pull/20805))
* [eslint-config-appium](https://github.com/appium/appium/blob/4b3a8c2197a587ec5a2606b662e4e7667a7852cb/packages/eslint-config-appium/CHANGELOG.md) ([removal PR](https://github.com/appium/appium/pull/20856))
* [eslint-config-appium-ts](https://github.com/appium/appium/blob/31bc9f1f8cc99561135f4dd53c0e49637813d694/packages/eslint-config-appium-ts/CHANGELOG.md) ([removal PR](https://github.com/appium/appium/pull/22699))
* [gulp-plugins](https://github.com/appium/appium/blob/0823f0b60e40395cd1dc3b72cfa3c0092bc81302/packages/gulp-plugins/CHANGELOG.md) ([removal PR](https://github.com/appium/appium/pull/17943))
* [test-support](https://github.com/appium/appium/blob/1a46d7d61ee49c7e82a63687c5647c42ab69513d/packages/test-support/CHANGELOG.md) ([removal PR](https://github.com/appium/appium/pull/22351))
* [typedoc-plugin-appium](https://github.com/appium/appium/blob/d6204b6902074210943d7bbbf72d139b9b170a20/packages/typedoc-plugin-appium/CHANGELOG.md) ([removal PR](https://github.com/appium/appium/pull/19465))
+1
View File
@@ -43,6 +43,7 @@ programming languages, which means there is an entire ecosystem of related softw
The Appium team only provides support for the most recent version of Appium. If you wish to upgrade from
an older major Appium version, please refer to the migration guides:
* [Appium v3 to v4](https://appium.io/docs/en/latest/guides/migrating-3-to-4/)
* [Appium v2 to v3](https://appium.io/docs/en/latest/guides/migrating-2-to-3/)
* [Appium v1 to v2](https://appium.io/docs/en/latest/guides/migrating-1-to-2/)
+2797 -2210
View File
File diff suppressed because it is too large Load Diff
+10 -17
View File
@@ -81,44 +81,37 @@
},
"devDependencies": {
"@appium/oxc-config": "2.0.0-beta.0",
"@tsconfig/node22": "22.0.0",
"@tsconfig/node22": "22.0.7",
"@types/express": "5.0.6",
"@types/json-schema": "7.0.15",
"@types/lockfile": "1.0.4",
"@types/method-override": "3.0.0",
"@types/mime-types": "3.0.1",
"@types/morgan": "1.9.10",
"@types/node": "24.19.2",
"@types/node": "26.6.6",
"@types/picomatch": "4.0.3",
"@types/pluralize": "0.0.33",
"@types/semver": "7.8.0",
"@types/shell-quote": "1.7.5",
"@types/sinon": "22.0.2",
"@types/which": "3.0.4",
"@types/ws": "8.18.1",
"@types/ws": "8.18.2",
"@types/yargs": "17.0.35",
"asyncbox": "6.6.0",
"axios": "1.20.0",
"asyncbox": "7.1.0",
"axios": "1.21.1",
"conventional-changelog-conventionalcommits": "9.3.1",
"cross-env": "10.1.0",
"json-schema-to-typescript": "16.0.0",
"lerna": "10.1.1",
"npm-run-all2": "9.0.4",
"lerna": "10.1.3",
"npm-run-all2": "9.1.0",
"sinon": "22.1.0",
"teen_process": "4.2.1",
"teen_process": "5.0.1",
"tsd": "0.33.0",
"typescript": "6.0.3",
"webdriverio": "9.32.0",
"ws": "8.22.0"
"webdriverio": "10.2.0",
"ws": "8.23.0"
},
"overrides": {
"@sidvind/better-ajv-errors": {
"ajv": "8.20.0"
},
"ajv-formats": {
"ajv": "8.20.0"
},
"http-cache-semantics": "4.3.0",
"nx": {
"undici": "7.30.2"
}
+17
View File
@@ -3,6 +3,23 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [4.0.2](https://github.com/appium/appium/compare/appium@4.0.1...appium@4.0.2) (2026-11-27)
### Bug Fixes
* **appium:** clean up sessions when a createSession plugin fails ([#23217](https://github.com/appium/appium/issues/23217)) ([a68b15f](https://github.com/appium/appium/commit/a68b15fdaef667d7977dbc4c8c73daadc668c88d))
## [4.0.1](https://github.com/appium/appium/compare/appium@4.0.0...appium@4.0.1) (2026-11-23)
### Bug Fixes
* **appium:** give each createSession call its own plugin instances ([#23214](https://github.com/appium/appium/issues/23214)) ([a7fbe25](https://github.com/appium/appium/commit/a7fbe25a0c7f1c9f3e1487aaae858bb6a3e21afd))
* **appium:** release the manifest lock while a driver/plugin script runs ([#23204](https://github.com/appium/appium/issues/23204)) ([bca2398](https://github.com/appium/appium/commit/bca239835c55ef037e34ea80cbf48d9f6a5b736a))
* **appium:** remove a session before its driver finishes deleting it ([#23215](https://github.com/appium/appium/issues/23215)) ([43ffd5f](https://github.com/appium/appium/commit/43ffd5f888e9e968f75afc01f0a6de929319d104))
* **base-driver:** bound the state of the BiDi subscriptions ([#23198](https://github.com/appium/appium/issues/23198)) ([db8a588](https://github.com/appium/appium/commit/db8a58813b6e89770e7245790f2aa1cd25d8a5dd))
## [4.0.0](https://github.com/appium/appium/compare/appium@3.9.1...appium@4.0.0) (2026-11-15)
### ⚠ BREAKING CHANGES
+1
View File
@@ -43,6 +43,7 @@ programming languages, which means there is an entire ecosystem of related softw
The Appium team only provides support for the most recent version of Appium. If you wish to upgrade from
an older major Appium version, please refer to the migration guides:
* [Appium v3 to v4](https://appium.io/docs/en/latest/guides/migrating-3-to-4/)
* [Appium v2 to v3](https://appium.io/docs/en/latest/guides/migrating-2-to-3/)
* [Appium v1 to v2](https://appium.io/docs/en/latest/guides/migrating-1-to-2/)
@@ -22,3 +22,8 @@ authors:
description: 'Appium Core Maintainer'
avatar: https://avatars.githubusercontent.com/u/7767781?v=4
slug: 'mykola'
eglitise:
name: 'Edgars Eglitis'
description: 'Appium Core Maintainer'
avatar: https://avatars.githubusercontent.com/u/37242620?v=4
slug: 'eglitise'
@@ -0,0 +1,41 @@
---
authors:
- eglitise
date: 2026-11-15
---
# 🚀 Appium 4
Appium 4 is here! A major milestone in the evolution of Appium, this release aims to strengthen
Appium's compliance with the W3C WebDriver protocol, modernize the codebase, and as usual, remove
deprecated legacy functionality.
<!-- more -->
While Appium 3 was primarily a cleanup release that removed a lot of deprecated endpoints, Appium 4
has a broader scope of changes. A few legacy endpoints have still been removed, but the key focus
this time has been on various behavioral adjustments for closer alignment with the W3C WebDriver
protocol specification, as well as full removal of support for drivers/plugins who relied on the
obsolete JSONWP/MJSONWP protocols.
The key breaking changes are as follows:
- Minimum Node.js version is raised to 22.22
- All Appium packages are now ESM-only
- The Windows driver is replaced with the WinCore driver
- Some deprecated endpoints have been removed (far fewer than in Appium 3!)
- The server flag for enabling CORS has been renamed
When it comes to new features, Appium 4 adds only a few, similarly to Appium 3:
- New server flag for controlling allowed app URLs in capabilities like `appium:app`
- The `install` and `update` CLI commands now gracefully handle any incompatibilities with the
extension's declared server version range
- The universal XML plugin's translation can now be toggled mid-session
As usual, the full [Appium 4 migration guide](../../guides/migrating-3-to-4.md) describes the full
extent of the important changes included in this major release.
The Appium team is incredibly grateful to all contributors who made this release possible!
Happy testing!
@@ -314,7 +314,7 @@ Websockets. Implementing handlers for BiDi commands works just the same as imple
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)
[bidi-commands](https://github.com/appium/appium/tree/master/packages/base-driver/lib/protocol/bidi-commands)
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
@@ -164,6 +164,11 @@ constructor(...args) {
The `args` parameter here is the object containing all the CLI args used to start the Appium
server.
Appium creates a separate instance of your plugin for each session. The instance that handles
`createSession` also handles the later commands of that session, so state set in `createSession`
can be kept on `this`. If `createSession` fails, that instance is dropped. Commands that do not
belong to a session, such as `getStatus`, are handled by another instance which no session uses.
### Intercept and handle specific Appium commands
This is the most normal behavior for Appium plugins -- to modify or replace the execution of one or
@@ -105,6 +105,20 @@ Supported by: `@AppiumTestDistribution`
npm install -g appium-installer
```
### [BenchFleet Appium](https://github.com/benchfleet/benchfleet-appium)
BenchFleet Appium is a command-line tool for running existing Appium tests on real Android phones
connected to a [BenchFleet](https://benchfleet.com) Hub, a desktop app for managing many phones
(Pro or Team plan). For each phone, the Hub starts an Appium server with the UiAutomator2 driver.
The tool then runs your test command once per phone with that server's URL in `APPIUM_URL`, and
collects each phone's JUnit report. iOS and BenchFleet's cloud phones are not supported yet.
Supported by: `@benchfleet`
```sh title="Install This Tool"
npm install -g benchfleet-appium
```
### [Optics](https://github.com/mozarkai/optics-framework)
Optics is an open-source test automation framework that uses Appium to drive Android, iOS,
+1 -1
View File
@@ -15,7 +15,7 @@ bundle for each test.
## What Is Cached
Caching could be applied to application bundles generated by
[`configureApp`](https://github.com/appium/appium/blob/master/packages/base-driver/lib/basedriver/helpers.ts#L99) helper call.
[`configureApp`](https://github.com/appium/appium/blob/master/packages/base-driver/lib/basedriver/helpers/app-cache.ts#L98) helper call.
Inherited drivers can customize their caching logic by providing own `onPostProcess`
(or both `inDownload` and `onPostProcess`) property definition, but the general
rule of thumb is that we need to cache locally all application bundles need to be downloaded and/or extracted
@@ -12,13 +12,12 @@ deprecated items not limited to endpoints, and general modernizing of the codeba
## Installation
Appium 4 is currently only available as a beta release, published under the `beta` npm dist-tag.
The installation method otherwise remains the same as for Appium 3. If you want to upgrade, you
The installation method for Appium 4 remains the same as for Appium 3. If you want to upgrade, you
can simply install Appium 4 on top of your existing installation:
```bash
# optional: `appium setup reset`
npm install -g appium@beta
npm install -g appium
```
## Breaking Changes
@@ -8,7 +8,7 @@ title: System Requirements
The basic requirements for the Appium server are:
* A macOS, Linux, or Windows operating system
* [Node.js](https://nodejs.org) version in the [SemVer](https://semver.org) range `^20.19.0 || ^22.12.0 || >=24.0.0`
* [Node.js](https://nodejs.org) version in the [SemVer](https://semver.org) range `^22.22.2 || ^24.15.0 || >=26.0.0`
* LTS is recommended
* [`npm`](https://npmjs.com) version `>=10` (`npm` is usually bundled with Node.js, but can be upgraded
independently)
@@ -48,6 +48,20 @@ Subscribes to one or more BiDi events.
`{subscription: string}` — a unique subscription ID that can be passed to `session.unsubscribe`.
#### Limits
A session can have up to 100 subscriptions. Every subscription covers a combination of each of its
events and each of its contexts (an event without contexts counts as one), and all the subscriptions
together, counted one by one, can cover up to 1000 combinations. Lists in the parameters can have up
to 1000 items, and the event names, contexts and subscription IDs can be up to 256 characters long.
A request that exceeds a limit fails with an `invalid argument` error without changing the subscriptions.
Unsubscribing by event names (`events`) removes the matching contexts of those events across all the
subscriptions (an event stays active in the contexts that are not listed), but the IDs of the
subscriptions that have no events left stay valid, so they can still be passed to `session.unsubscribe`.
The oldest such ID expires only when a new subscription needs its slot at the limit of 100 subscriptions.
An unknown or expired ID fails the whole `subscriptions` request, and none of its subscriptions are removed.
### bidiUnsubscribe
```
@@ -27,7 +27,6 @@ appium
|<div style="width:15em">Argument</div>|Description|Type|<div style="width:7em">Default</div>|
|--|--|--|--|
|`--address`, `-a`|IPv4/IPv6 address or a hostname to listen on|string|`0.0.0.0`|
|`--allow-cors`|Allow web browser connections from any host|boolean|`false`|
|`--allow-insecure`|List of [insecure features](../../guides/security.md) that should be allowed in this server's sessions. Individual features can be overridden by `--deny-insecure`. Has no effect in combination with `--relaxed-security`.|array<string>|`[]`|
|`--allow-unknown-args`|Do not exit if unrecognized command-line arguments are passed to the server; ignore them instead. Useful when the Appium CLI is wrapped by external tooling that appends extra flags.|boolean|`false`|
|`--app-url-rules`|Rules that remote application URLs (e.g. in the `appium:app` capability) must satisfy before the server downloads them. See the [Restricting Remote App URLs](../../guides/security.md#restricting-remote-app-urls) guide for details. Can be a path to a JSON file or raw JSON.|object||
@@ -22,3 +22,8 @@ authors:
description: 'Appium Core Maintainer'
avatar: https://avatars.githubusercontent.com/u/7767781?v=4
slug: 'mykola'
eglitise:
name: 'Edgars Eglitis'
description: 'Appium Core Maintainer'
avatar: https://avatars.githubusercontent.com/u/37242620?v=4
slug: 'eglitise'
@@ -0,0 +1,41 @@
---
authors:
- eglitise
date: 2026-11-15
---
# 🚀 Appium 4
Appium 4 is here! A major milestone in the evolution of Appium, this release aims to strengthen
Appium's compliance with the W3C WebDriver protocol, modernize the codebase, and as usual, remove
deprecated legacy functionality.
<!-- more -->
While Appium 3 was primarily a cleanup release that removed a lot of deprecated endpoints, Appium 4
has a broader scope of changes. A few legacy endpoints have still been removed, but the key focus
this time has been on various behavioral adjustments for closer alignment with the W3C WebDriver
protocol specification, as well as full removal of support for drivers/plugins who relied on the
obsolete JSONWP/MJSONWP protocols.
The key breaking changes are as follows:
- Minimum Node.js version is raised to 22.22
- All Appium packages are now ESM-only
- The Windows driver is replaced with the WinCore driver
- Some deprecated endpoints have been removed (far fewer than in Appium 3!)
- The server flag for enabling CORS has been renamed
When it comes to new features, Appium 4 adds only a few, similarly to Appium 3:
- New server flag for controlling allowed app URLs in capabilities like `appium:app`
- The `install` and `update` CLI commands now gracefully handle any incompatibilities with the
extension's declared server version range
- The universal XML plugin's translation can now be toggled mid-session
As usual, the full [Appium 4 migration guide](../../guides/migrating-3-to-4.md) describes the full
extent of the important changes included in this major release.
The Appium team is incredibly grateful to all contributors who made this release possible!
Happy testing!
@@ -230,18 +230,6 @@ 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.
```
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
@@ -730,6 +718,12 @@ A couple notes about this system:
mode!
3. The `executeMethod` helper will reject with an error if a script name doesn't match one of the
script names defined as a command in `executeMethodMap`, or if there are missing parameters.
4. If your driver is written in TypeScript, declare the map `as const satisfies
ExecuteMethodMap<MyDriver>` (with `ExecuteMethodMap` imported from `@appium/types`). The
compiler then checks that each `command` names a method of your driver, and that the
`required`/`optional` params are consistent with that method's signature: the method must not
require a parameter which is listed as `optional` (or not listed at all), and must accept all
of the listed parameters.
One of the nice things about the Execute Method strategy is that methods implemented in this way
will be available via the classic or BiDi interfaces (since they will result in the same Appium
@@ -796,6 +790,36 @@ this.eventEmitter.emit('bidiEvent', {
Now, if the client has subscribed to the `system.cpu` event, it will be notified with the load
whenever the driver emits it.
#### Slow clients and high-rate events
Appium does not buffer events indefinitely for a client that does not read them. A connection
that keeps more than `--bidi-max-buffered-bytes` unsent for longer than `--bidi-max-buffered-ms`
is closed with the code `1013`, and connections that do not answer WebSocket pings (see
`--bidi-heartbeat-interval`) are terminated. Both only affect the offending connection.
Drivers that emit events at a high rate (e.g. media streams) can let Appium skip events for a
connection that is falling behind, instead of waiting for it to be closed. Add a `delivery` hint
to the event (it is never sent to clients; older Appium versions ignore it):
```js
this.eventEmitter.emit('bidiEvent', {
method: 'appium:media.units',
params: {track: 'video', units},
delivery: {policy: 'droppable', chain: 'video', syncPoint: startsWithKeyframe},
})
```
- `policy`: `reliable` (default) events are always sent, `droppable` ones may be skipped.
- `chain`: events of the same chain depend on each other. After one is skipped for a connection,
the following ones are skipped for it too, until an event with `syncPoint: true` (e.g. a keyframe)
arrives and the connection has caught up. Every connection resynchronizes independently.
Subscriptions are per session, not per connection, so Appium decides by the state of each
connection's buffer. To react to dropped events (e.g. to request a keyframe or lower the bitrate),
listen to `bidiBackpressure` on the same emitter. Its payload is `{method, chain?, state, dropped}`,
where `state` is `dropping` once the first connection starts skipping events (and again whenever a
sync point is skipped, so that you can request a new one) and `recovered` once the last one stops, and `dropped` is the largest number of events skipped for a single connection.
### Make itself aware of resources other concurrent drivers are using
Let's say your driver uses up some system resources, like ports. There are a few ways to make sure
@@ -803,55 +827,35 @@ that multiple simultaneous sessions don't use the same resources:
1. Have your users specify resource IDs via capabilities (`appium:driverPort` etc)
2. Just always use free resources (find a new random port for each session)
3. Have each driver express what resources it is using, then examine currently-used resources from
other drivers when a new session begins.
3. Have each running instance of your driver publish and subscribe to messages on a shared IPC
channel, so sessions can coordinate directly with one another.
!!! warning "Deprecated"
```
The `driverData`-based mechanism described below is deprecated. Prefer
[IPC](#send-messages-to-plugins-running-on-the-same-session) for coordinating resources across
concurrently-running sessions instead.
```
To support this third strategy, you can implement `get driverData` in your driver to return what
sorts of resources your driver is currently using, for example:
```js
get driverData() {
return {specialPort: 1234, specialFile: /path/to/file}
}
```
Now, when a new session is started on your driver, the `driverData` response from any other
simultaneously running drivers (of the same type) will also be included, as the last parameter of
the deprecated, multi-argument form of the `createSession` method:
```js
async createSession(jwpCaps, reqCaps, w3cCaps, driverData)
```
You can dig into this `driverData` array to see what resources other drivers are using to help
determine which ones you want to use for this particular session.
The per-session IPC channel described in Send messages to plugins running on the same
session is isolated per session, so it
can't be used for this: it doesn't let you talk to _other_ sessions of your driver. Instead,
construct and hold on to your own `AppiumIpc` instance (exported from `appium/driver.js`) at
module scope in your driver's package, for example as a memoized singleton. Since Node.js caches
modules, every instance of your driver loaded within the same Appium server process will share
that one `AppiumIpc` object, and can use it to publish and subscribe to topics across sessions —
the same way the per-session channel works, just not scoped to a single session. See
[xcuitest-driver's `session-claim-handler.ts`](https://github.com/appium/appium-xcuitest-driver/blob/master/lib/session-claim-handler.ts)
for a real example, which uses this technique to detect and resolve conflicting sessions targeting
the same device UDID.
!!! warning
```
Be careful here, since `driverData` is only passed between sessions of a single running Appium
server. There's nothing to stop a user from running multiple Appium servers and requesting your
driver simultaneously on each of them. In this case, you won't be able to ensure independence
of resources via `driverData`, so you might consider using file-based locking mechanisms or
something similar.
This only works for sessions running within the same Node.js process (i.e. the same Appium
server). It cannot coordinate sessions running on different Appium server processes; for that,
consider file-based locking or a similar out-of-process mechanism.
```
!!! warning
```
It's also important to note you will only receive `driverData` for other instances of *your*
driver. So unrelated drivers also running may still be using some system resources. In general
Appium doesn't provide any features for ensuring unrelated drivers don't interfere with one
another, so it's up to the drivers to allow users to specify resource locations or addresses to
avoid clashes.
Appium also doesn't provide any features for ensuring unrelated drivers don't interfere with
one another, so it's up to the drivers to allow users to specify resource locations or
addresses to avoid clashes.
```
### Log events to the Appium event timeline
@@ -1002,10 +1006,15 @@ export type IpcMessage<T> = {
There are some important things to keep in mind when using Appium's IPC feature:
- IPC is only available once `onIpcInit` has been called, at the end of the `createSession` flow.
It cannot be used statically or in `createSession` hooks
- In sum, IPC is only for use during a session (this is also to prevent drivers/plugins from
accessing or reading data sent on IPC channels in other sessions.)
- The `ipcSubscribe` method (and the IPC channel it subscribes to) is only available once
`onIpcInit` has been called, at the end of the `createSession` flow. It cannot be used statically
or in `createSession` hooks
- The channel that `ipcSubscribe` gives you access to is scoped to the current session, and is
shared only with the plugins active in that same session (this is also to prevent drivers/plugins
from accessing or reading data sent on IPC channels in other sessions.) To coordinate across
multiple concurrent sessions of your own driver instead, see Make itself aware of resources
other concurrent drivers are
using.
- The default max size of an IPC message is 1MB. This can be configured by the server-admin by
using the `--max-ipc-data-size` arg (value is a number in bytes).
- If a message exceeds the configured size, any call to `publish` methods will throw, so be
@@ -168,6 +168,11 @@ constructor(...args) {
The `args` parameter here is the object containing all the CLI args used to start the Appium
server.
Appium creates a separate instance of your plugin for each session. The instance that handles
`createSession` also handles the later commands of that session, so state set in `createSession`
can be kept on `this`. If `createSession` fails, that instance is dropped. Commands that do not
belong to a session, such as `getStatus`, are handled by another instance which no session uses.
### Intercept and handle specific Appium commands
This is the most normal behavior for Appium plugins -- to modify or replace the execution of one or
@@ -261,7 +266,7 @@ throw new errors.NoSuchElementError();
### Log messages to the Appium log
You can always use `console.log`, of course, but Appium provides a nice logger for you as
`this.logger` (it has `.info`, `.debug`, `.log`, `.warn`, `.error` methods on it for differing log
`this.log` (it has `.info`, `.debug`, `.warn`, `.error` methods on it for differing log
levels). If you want to create an Appium logger outside of a plugin context (say in a script or
helper file), you can always construct your own too:
@@ -482,7 +487,7 @@ capability.
You probably don't normally need to update the Appium server object (which is an
[Express](https://expressjs.com/) server having already been
[configured](https://github.com/appium/appium/blob/master/packages/base-driver/lib/express/server.ts)
[configured](https://github.com/appium/appium/blob/master/packages/http-server/lib/server.ts)
in a variety of ways). But, for example, you could add new routes to the server to support your
plugin's requirements. To update the server you must implement the `static async updateServer`
method in your class. This method takes three parameters:
@@ -42,7 +42,7 @@ In order to get some value in logs replaced by a generic mask it is necessary:
[util.format](https://nodejs.org/api/util.html#utilformatformat-args) API.
- While sending the appropriate server request, where this log line is used and should be masked,
add the custom header `X-Appium-Is-Sensitive` with its value set to `1` or `true` (case-insensitive).
add the custom header `X-Appium-Is-Sensitive` with its value set to `1`, `true` or `yes` (case-insensitive).
Without such header the above log value is not going to be masked.
This way it is possible to conditionally mask log records depending on which
request is being handled by the extension if the log expression is used in the
+18 -16
View File
@@ -71,20 +71,13 @@ appium driver install safari
appium driver install uiautomator2
```
### [Windows](https://github.com/appium/appium-windows-driver)
!!! warning
```
Only the Node.js-based driver part is maintained by the Appium team. The server part
(WinAppDriver executable) is provided by Microsoft, but has not been maintained since 2022.
```
### [WinCore](https://appium.github.io/appium-wincore-driver)
- Target: Windows applications
- Mode: Native
```sh title="Install This Driver"
appium driver install windows
appium driver install wincore
```
### [XCUITest](https://appium.github.io/appium-xcuitest-driver/)
@@ -161,13 +154,6 @@ appium driver install --source=npm @itsmeaj/appium-linux-driver
### [NovaWindows](https://github.com/AutomateThePlanet/appium-novawindows-driver)
!!! info
```
This driver is recommended as a drop-in replacement for the partially unmaintained
[Windows driver](#windows)
```
- Target: Windows applications
- Mode: Native, Hybrid
- Supported by: Community / Automate The Planet
@@ -212,6 +198,22 @@ npm install appium-tizen-driver
appium driver install --source=npm appium-tizen-tv-driver
```
### [Windows (legacy)](https://github.com/appium/appium-windows-driver)
!!! warning
```
This driver relies on WinAppDriver, which has not been maintained since 2022, and is only
compatible with Appium 1-3. Use the [WinCore](#wincore) driver with Appium 4 and newer.
```
- Target: Windows applications
- Mode: Native
```sh title="Install This Driver"
appium driver install --source=npm appium-windows-driver
```
### [You.i Engine](https://github.com/YOU-i-Labs/appium-youiengine-driver)
!!! warning
@@ -114,6 +114,20 @@ Supported by: `@AppiumTestDistribution`
npm install -g appium-installer
```
### [BenchFleet Appium](https://github.com/benchfleet/benchfleet-appium)
BenchFleet Appium is a command-line tool for running existing Appium tests on real Android phones
connected to a [BenchFleet](https://benchfleet.com) Hub, a desktop app for managing many phones
(Pro or Team plan). For each phone, the Hub starts an Appium server with the UiAutomator2 driver.
The tool then runs your test command once per phone with that server's URL in `APPIUM_URL`, and
collects each phone's JUnit report. iOS and BenchFleet's cloud phones are not supported yet.
Supported by: `@benchfleet`
```sh title="Install This Tool"
npm install -g benchfleet-appium
```
### [Optics](https://github.com/mozarkai/optics-framework)
Optics is an open-source test automation framework that uses Appium to drive Android, iOS,
+1 -1
View File
@@ -99,4 +99,4 @@ The above configuration corresponds to the `--driver-xcuitest-webkit-debug-proxy
All properties are case-sensitive and will be in
[kebab-case](https://en.wikipedia.org/wiki/Naming_convention_(programming)#Delimiter-separated_words).
For example, `callback-port` is allowed, but `callbackPort` is not.
For example, `base-path` is allowed, but `basePath` is not.
+343
View File
@@ -0,0 +1,343 @@
---
title: Automating Gestures
---
Appium supports automating complex pointer, touch, key, and wheel interactions through the
W3C WebDriver [Perform Actions](../reference/api/webdriver.md#performactions) API
([W3C Specification](https://w3c.github.io/webdriver/#actions)). Alternatively, many drivers provide
platform-native gesture [Execute Methods](./execute-methods.md) for common interactions.
In the W3C Actions API, interactions are defined by creating one or more virtual input sources
(such as `pointer` with `pointerType: "touch"`, `key`, `wheel`, or `none`) and queuing a sequence
of synchronized ticks (`pointerMove`, `pointerDown`, `pointerUp`, `pause`). See the
[Selenium Actions API documentation](https://www.selenium.dev/documentation/webdriver/actions_api/)
for a general overview of input sources and tick synchronization.
Below are examples of common single-finger and multi-touch gestures implemented using the W3C
Actions API across client languages.
## Double Tap
Performs two quick touch taps at `(x, y)` with a short pause between them:
=== "JS (WebDriverIO)"
```js
await driver
.action('pointer', {parameters: {pointerType: 'touch'}})
.move({x: 200, y: 300, duration: 0})
.down()
.up()
.pause(100)
.down()
.up()
.perform();
```
=== "Java"
```java
PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");
Sequence doubleTap = new Sequence(finger, 1)
.addAction(finger.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), 200, 300))
.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()))
.addAction(new Pause(finger, Duration.ofMillis(100)))
.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
driver.perform(Collections.singletonList(doubleTap));
```
=== "Python"
```py
actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "finger"))
actions.w3c_actions.pointer_action.move_to_location(200, 300)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pointer_up()
actions.w3c_actions.pointer_action.pause(0.1)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pointer_up()
actions.perform()
```
=== "Ruby"
```rb
f1 = driver.action.add_pointer_input(:touch, 'finger')
f1.create_pointer_move(duration: 0, x: 200, y: 300, origin: :viewport)
f1.create_pointer_down(:left)
f1.create_pointer_up(:left)
f1.create_pause(0.1)
f1.create_pointer_down(:left)
f1.create_pointer_up(:left)
driver.perform_actions([f1])
```
=== "C#"
```csharp
var finger = new PointerInputDevice(PointerKind.Touch, "finger");
var doubleTap = new ActionSequence(finger, 0);
doubleTap.AddAction(finger.CreatePointerMove(CoordinateOrigin.Viewport, 200, 300, TimeSpan.Zero));
doubleTap.AddAction(finger.CreatePointerDown(MouseButton.Touch));
doubleTap.AddAction(finger.CreatePointerUp(MouseButton.Touch));
doubleTap.AddAction(finger.CreatePause(TimeSpan.FromMilliseconds(100)));
doubleTap.AddAction(finger.CreatePointerDown(MouseButton.Touch));
doubleTap.AddAction(finger.CreatePointerUp(MouseButton.Touch));
driver.PerformActions(new List<ActionSequence> { doubleTap });
```
## Long Press
Presses and holds a touch pointer at `(x, y)` for 1000ms before releasing:
=== "JS (WebDriverIO)"
```js
await driver
.action('pointer', {parameters: {pointerType: 'touch'}})
.move({x: 200, y: 300, duration: 0})
.down()
.pause(1000)
.up()
.perform();
```
=== "Java"
```java
PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");
Sequence longPress = new Sequence(finger, 1)
.addAction(finger.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), 200, 300))
.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
.addAction(new Pause(finger, Duration.ofMillis(1000)))
.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
driver.perform(Collections.singletonList(longPress));
```
=== "Python"
```py
actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "finger"))
actions.w3c_actions.pointer_action.move_to_location(200, 300)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pause(1.0)
actions.w3c_actions.pointer_action.pointer_up()
actions.perform()
```
=== "Ruby"
```rb
f1 = driver.action.add_pointer_input(:touch, 'finger')
f1.create_pointer_move(duration: 0, x: 200, y: 300, origin: :viewport)
f1.create_pointer_down(:left)
f1.create_pause(1.0)
f1.create_pointer_up(:left)
driver.perform_actions([f1])
```
=== "C#"
```csharp
var finger = new PointerInputDevice(PointerKind.Touch, "finger");
var longPress = new ActionSequence(finger, 0);
longPress.AddAction(finger.CreatePointerMove(CoordinateOrigin.Viewport, 200, 300, TimeSpan.Zero));
longPress.AddAction(finger.CreatePointerDown(MouseButton.Touch));
longPress.AddAction(finger.CreatePause(TimeSpan.FromMilliseconds(1000)));
longPress.AddAction(finger.CreatePointerUp(MouseButton.Touch));
driver.PerformActions(new List<ActionSequence> { longPress });
```
## Drag and Drop / Swipe
Moves a touch pointer from `(200, 600)` to `(200, 200)` over 600ms:
=== "JS (WebDriverIO)"
```js
await driver
.action('pointer', {parameters: {pointerType: 'touch'}})
.move({x: 200, y: 600, duration: 0})
.down()
.pause(100)
.move({x: 200, y: 200, duration: 600})
.up()
.perform();
```
=== "Java"
```java
PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");
Sequence dragAndDrop = new Sequence(finger, 1)
.addAction(finger.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), 200, 600))
.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
.addAction(new Pause(finger, Duration.ofMillis(100)))
.addAction(finger.createPointerMove(Duration.ofMillis(600), PointerInput.Origin.viewport(), 200, 200))
.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
driver.perform(Collections.singletonList(dragAndDrop));
```
=== "Python"
```py
actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "finger"))
actions.w3c_actions.pointer_action.move_to_location(200, 600)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pause(0.1)
actions.w3c_actions.pointer_action.move_to_location(200, 200)
actions.w3c_actions.pointer_action.pointer_up()
actions.perform()
```
=== "Ruby"
```rb
f1 = driver.action.add_pointer_input(:touch, 'finger')
f1.create_pointer_move(duration: 0, x: 200, y: 600, origin: :viewport)
f1.create_pointer_down(:left)
f1.create_pause(0.1)
f1.create_pointer_move(duration: 0.6, x: 200, y: 200, origin: :viewport)
f1.create_pointer_up(:left)
driver.perform_actions([f1])
```
=== "C#"
```csharp
var finger = new PointerInputDevice(PointerKind.Touch, "finger");
var dragAndDrop = new ActionSequence(finger, 0);
dragAndDrop.AddAction(finger.CreatePointerMove(CoordinateOrigin.Viewport, 200, 600, TimeSpan.Zero));
dragAndDrop.AddAction(finger.CreatePointerDown(MouseButton.Touch));
dragAndDrop.AddAction(finger.CreatePause(TimeSpan.FromMilliseconds(100)));
dragAndDrop.AddAction(finger.CreatePointerMove(CoordinateOrigin.Viewport, 200, 200, TimeSpan.FromMilliseconds(600)));
dragAndDrop.AddAction(finger.CreatePointerUp(MouseButton.Touch));
driver.PerformActions(new List<ActionSequence> { dragAndDrop });
```
## Pinch and Zoom (Multi-Touch)
Uses two concurrent `touch` pointer sequences (`finger1` and `finger2`) moving apart to zoom in (or toward each other to pinch):
=== "JS (WebDriverIO)"
```js
await driver.performActions([
{
type: 'pointer',
id: 'finger1',
parameters: {pointerType: 'touch'},
actions: [
{type: 'pointerMove', duration: 0, x: 200, y: 400},
{type: 'pointerDown', button: 0},
{type: 'pause', duration: 100},
{type: 'pointerMove', duration: 500, x: 200, y: 200},
{type: 'pointerUp', button: 0},
],
},
{
type: 'pointer',
id: 'finger2',
parameters: {pointerType: 'touch'},
actions: [
{type: 'pointerMove', duration: 0, x: 200, y: 450},
{type: 'pointerDown', button: 0},
{type: 'pause', duration: 100},
{type: 'pointerMove', duration: 500, x: 200, y: 650},
{type: 'pointerUp', button: 0},
],
},
]);
```
=== "Java"
```java
PointerInput finger1 = new PointerInput(PointerInput.Kind.TOUCH, "finger1");
Sequence seq1 = new Sequence(finger1, 1)
.addAction(finger1.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), 200, 400))
.addAction(finger1.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
.addAction(new Pause(finger1, Duration.ofMillis(100)))
.addAction(finger1.createPointerMove(Duration.ofMillis(500), PointerInput.Origin.viewport(), 200, 200))
.addAction(finger1.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
PointerInput finger2 = new PointerInput(PointerInput.Kind.TOUCH, "finger2");
Sequence seq2 = new Sequence(finger2, 1)
.addAction(finger2.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), 200, 450))
.addAction(finger2.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
.addAction(new Pause(finger2, Duration.ofMillis(100)))
.addAction(finger2.createPointerMove(Duration.ofMillis(500), PointerInput.Origin.viewport(), 200, 650))
.addAction(finger2.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
driver.perform(Arrays.asList(seq1, seq2));
```
=== "Python"
```py
action_builder = ActionBuilder(driver)
finger1 = action_builder.add_pointer_input(interaction.POINTER_TOUCH, "finger1")
finger2 = action_builder.add_pointer_input(interaction.POINTER_TOUCH, "finger2")
finger1.create_pointer_move(duration=0, x=200, y=400)
finger1.create_pointer_down(button=MouseButton.LEFT)
finger1.create_pause(0.1)
finger1.create_pointer_move(duration=500, x=200, y=200)
finger1.create_pointer_up(button=MouseButton.LEFT)
finger2.create_pointer_move(duration=0, x=200, y=450)
finger2.create_pointer_down(button=MouseButton.LEFT)
finger2.create_pause(0.1)
finger2.create_pointer_move(duration=500, x=200, y=650)
finger2.create_pointer_up(button=MouseButton.LEFT)
action_builder.perform()
```
=== "Ruby"
```rb
f1 = driver.action.add_pointer_input(:touch, 'finger1')
f1.create_pointer_move(duration: 0, x: 200, y: 400, origin: :viewport)
f1.create_pointer_down(:left)
f1.create_pause(0.1)
f1.create_pointer_move(duration: 0.5, x: 200, y: 200, origin: :viewport)
f1.create_pointer_up(:left)
f2 = driver.action.add_pointer_input(:touch, 'finger2')
f2.create_pointer_move(duration: 0, x: 200, y: 450, origin: :viewport)
f2.create_pointer_down(:left)
f2.create_pause(0.1)
f2.create_pointer_move(duration: 0.5, x: 200, y: 650, origin: :viewport)
f2.create_pointer_up(:left)
driver.perform_actions([f1, f2])
```
=== "C#"
```csharp
var finger1 = new PointerInputDevice(PointerKind.Touch, "finger1");
var seq1 = new ActionSequence(finger1, 0);
seq1.AddAction(finger1.CreatePointerMove(CoordinateOrigin.Viewport, 200, 400, TimeSpan.Zero));
seq1.AddAction(finger1.CreatePointerDown(MouseButton.Touch));
seq1.AddAction(finger1.CreatePause(TimeSpan.FromMilliseconds(100)));
seq1.AddAction(finger1.CreatePointerMove(CoordinateOrigin.Viewport, 200, 200, TimeSpan.FromMilliseconds(500)));
seq1.AddAction(finger1.CreatePointerUp(MouseButton.Touch));
var finger2 = new PointerInputDevice(PointerKind.Touch, "finger2");
var seq2 = new ActionSequence(finger2, 0);
seq2.AddAction(finger2.CreatePointerMove(CoordinateOrigin.Viewport, 200, 450, TimeSpan.Zero));
seq2.AddAction(finger2.CreatePointerDown(MouseButton.Touch));
seq2.AddAction(finger2.CreatePause(TimeSpan.FromMilliseconds(100)));
seq2.AddAction(finger2.CreatePointerMove(CoordinateOrigin.Viewport, 200, 650, TimeSpan.FromMilliseconds(500)));
seq2.AddAction(finger2.CreatePointerUp(MouseButton.Touch));
driver.PerformActions(new List<ActionSequence> { seq1, seq2 });
```
-59
View File
@@ -117,62 +117,3 @@ hub, you'll be able to send all your Appium traffic via the single hub endpoint
And of course, you're able to link up Appium servers and nodes running on different machines in
your network to form a larger grid.
## Using Selenium Grid 3
It is possible to register your Appium server with a local [Selenium Grid 3](https://www.selenium.dev/documentation/legacy/selenium_3/grid_3/)
([setup docs](https://www.selenium.dev/documentation/legacy/grid_3/setting_up_your_own_grid/)) instance by using the
`--nodeconfig` server argument.
```bash
appium server --nodeconfig /path/to/nodeconfig.json --base-path=/wd/hub
```
In the referenced config file you have to define the `browserName`, `version` and `platform`
capabilities and based on these parameters the grid will re-direct your test to the right device.
You will also need to configure your host details and the Selenium Grid details. For a full list of
all parameters and descriptions see
[here](https://www.selenium.dev/documentation/legacy/selenium_3/grid_setup/).
Once you start the Appium server it will register with the grid, and you will see your device on
the grid console page:
`http://**\<grid-ip-address\>**:**\<grid-port\>**/grid/console`
### Example Grid Node Configuration JSON
```json
{
"capabilities":
[
{
"browserName": "<e.g._iPhone5_or_iPad4>",
"version":"<version_of_iOS_e.g._7.1>",
"maxInstances": 1,
"platform":"<platform_e.g._MAC_or_ANDROID>"
}
],
"configuration":
{
"cleanUpCycle":2000,
"timeout":30000,
"proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
"url":"http://<host_name_appium_server_or_ip-address_appium_server>:<appium_port>/wd/hub",
"host": "<host_name_appium_server_or_ip-address_appium_server>",
"port": <appium_port>,
"maxSession": 1,
"register": true,
"registerCycle": 5000,
"hubPort": <grid_port>,
"hubHost": "<Grid_host_name_or_grid_ip-address>",
"hubProtocol": "<Protocol_of_Grid_defaults_to_http>"
}
}
```
If `url`, `host`, and `port` are not given, the config will be auto updated to point to
`localhost:<appium-port>`.
If your Appium server is running on a different machine to your Selenium Grid server, make sure you
use an external name/IP address in your `host` and `url` configuration; `localhost` and `127.0.0.1`
will prevent Selenium Grid from connecting correctly.
@@ -28,12 +28,6 @@ installing it only installs the core Appium server, without any drivers.
When it comes to installing Appium 2 drivers, there are several approaches you can take:
- Add the `--drivers` flag when installing Appium, for example:
```bash
npm i -g appium --drivers=xcuitest,uiautomator2
```
- Use the [Appium Extension CLI](../reference/cli/extensions.md), for example:
```bash
@@ -221,8 +215,12 @@ and [Mobile JSON Wire Protocol](https://github.com/SeleniumHQ/mobile-spec/blob/m
(MJSONWP) were used instead.
In Appium 1, all of these protocols were supported, so that older Selenium/Appium clients could
still communicate with newer Appium servers. Appium 2 removes support for JSONWP/MJSONWP and is now
only compatible with the W3C WebDriver Protocol.
still communicate with newer Appium servers. Appium 2 removes support for JSONWP/MJSONWP (including
legacy `TouchAction` and `MultiAction` endpoints) and is now only compatible with the W3C WebDriver
Protocol. Multi-touch and pointer gestures should be performed using the W3C
[Perform Actions](../reference/api/webdriver.md#performactions) API (see the
[Automating Gestures](./gestures.md) guide) or driver-specific
[Execute Methods](./execute-methods.md).
!!! info "Actions Needed"
@@ -0,0 +1,649 @@
---
title: Migrating to Appium 4
---
This document is a guide for those who are using Appium 3 and would like to upgrade to Appium 4.
It contains a list of breaking changes (including behavioral fixes), as well as suggestions for
handling them.
Appium 3 was largely focused on cleaning up old endpoints, whereas Appium 4 includes a wider range
of changes, including closer alignment to W3C WebDriver protocol requirements, removal of
deprecated items not limited to endpoints, and general modernizing of the codebase.
## Installation
The installation method for Appium 4 remains the same as for Appium 3. If you want to upgrade, you
can simply install Appium 4 on top of your existing installation:
```bash
# optional: `appium setup reset`
npm install -g appium
```
## Breaking Changes
### Node 22.22+ Required
Appium 3 required a Node.js version in the range `^20.19.0 || ^22.12.0 || >=24.0.0`. Appium 4 drops
Node 20 and bumps the required range to `^22.22.2 || ^24.15.0 || >=26.0.0`. The minimum `npm`
version remains unchanged.
!!! info "Actions Needed"
Upgrade Node.js to `v22.22.2` or newer
### ESM-Only
Every package in the Appium monorepo (`appium` and its dependents) is now published as ESM-only,
with no CommonJS build. `require()` no longer works for these packages.
!!! info "Actions Needed"
Import Appium packages using ESM `import` syntax, or use dynamic `import()` from CommonJS code
### JSONWP/MJSONWP Internals Removed
The release of Appium 2 removed general support for the obsolete JSONWP and MJSONWP protocols,
though some Appium-related packages using JSONWP/MJSONWP under the hood could still continue to
function.
Appium 4 removes most of the remaining internal code that supported these protocols, which means
that drivers that still relied on these protocols are no longer compatible with Appium 4. Most
notably, this includes the Windows driver ([see dedicated section below](#windows-driver-replaced-by-wincore-driver)). All other official drivers rely on the W3C protocol and are not affected by this change.
Despite this, Appium 4 does retain temporary support for a select few JSONWP/MJSONWP endpoints (see
[Deprecated Endpoints Removed](#deprecated-endpoints-removed)).
For extension developers, a more detailed breakdown is available in the Developer-Facing Changes
section below.
!!! info "Actions Needed"
Migrate to drivers that support the W3C WebDriver protocol
### Windows Driver Replaced by WinCore Driver
As part of [dropping support for the deprecated JSONWP and MJSONWP protocols](#jsonwpmjsonwp-support-fully-removed),
Appium 4 is no longer compatible with the Windows driver ([`appium-windows-driver`](https://github.com/appium/appium-windows-driver)),
since the driver cannot support the standard W3C WebDriver protocol. As a result, the
`appium driver install windows` CLI command also no longer works.
Its official replacement is the WinCore driver ([`appium-wincore-driver`](https://github.com/appium/appium-wincore-driver)),
which can be installed using the new `appium driver install wincore` command. Since the WinCore
driver is also compatible with Appium 3, you can safely migrate from the Windows driver while
remaining on Appium 3 - though note that the installation shortcut is only available since Appium 4.
!!! info "Actions Needed"
If you currently use the Windows driver with Appium 3, you can migrate as follows:
1. Install `appium-wincore-driver` v3: `appium driver install --source=npm appium-wincore-driver@3`
2. Migrate your tests to use the WinCore driver
3. Uninstall the Windows driver: `appium driver uninstall windows`
4. Upgrade to Appium 4
5. Update the WinCore driver to its Appium 4 version: `appium driver update wincore --unsafe`
### Deprecated Endpoints Removed
Similarly to Appium 3, Appium 4 also removes several previously deprecated server endpoints, all of
which belong to the obsolete JSONWP/MJSONWP protocols. Compared to Appium 3, this cleanup is much
smaller (12 removed endpoints total, compared to 98 for Appium 3).
All removed endpoints are listed below, along with their replacement endpoints or driver-specific
execute methods:
- `GET /session/:sessionId`
- :octicons-arrow-right-24: [`GET /session/:sessionId/appium/capabilities`](../reference/api/appium.md#getappiumsessioncapabilities) (for capabilities)
- :octicons-arrow-right-24: [`GET /session/:sessionId/appium/events`](../reference/api/appium.md#getlogevents) (for event timings)
- `POST /session/:sessionId/ime/activate`
- :octicons-check-24: Moved to [UiAutomator2](https://appium.github.io/appium-uiautomator2-driver/)/[Espresso](https://appium.github.io/appium-espresso-driver/) drivers
- `GET /session/:sessionId/ime/activated`
- :octicons-check-24: Moved to UiAutomator2/Espresso drivers
- `GET /session/:sessionId/ime/active_engine`
- :octicons-check-24: Moved to UiAutomator2/Espresso drivers
- `GET /session/:sessionId/ime/available_engines`
- :octicons-check-24: Moved to UiAutomator2/Espresso drivers
- `POST /session/:sessionId/ime/deactivate`
- :octicons-check-24: Moved to UiAutomator2/Espresso drivers
- `GET /session/:sessionId/location`
- :octicons-check-24: Moved to [XCUITest](https://appium.github.io/appium-xcuitest-driver/) driver
- :octicons-arrow-right-24: `mobile: getGeolocation` (UiAutomator2/Espresso drivers)
- :octicons-arrow-right-24: `mobile: getSimulatedLocation` (XCUITest driver)
- `POST /session/:sessionId/location`
- :octicons-check-24: Moved to UiAutomator2/Espresso/XCUITest drivers
- :octicons-arrow-right-24: `mobile: setGeolocation` (UiAutomator2/Espresso drivers)
- :octicons-arrow-right-24: `mobile: setSimulatedLocation` (XCUITest driver)
- `GET /session/:sessionId/network_connection`
- :octicons-check-24: Moved to UiAutomator2/Espresso drivers
- :octicons-arrow-right-24: `mobile: getConnectivity` (UiAutomator2/Espresso drivers)
- `POST /session/:sessionId/network_connection`
- :octicons-check-24: Moved to UiAutomator2/Espresso drivers
- :octicons-arrow-right-24: `mobile: setConnectivity` (UiAutomator2/Espresso drivers)
- `POST /session/:sessionId/receive_async_response`
- :octicons-arrow-right-24: [`POST /session/:sessionId/execute/async`](../reference/api/webdriver.md#executeasync)
- `GET /session/:sessionId/element/:elementId`
- :octicons-no-entry-24: JSONWP protocol command stub with no direct replacement
#### Remaining Deprecations
There are 7 more deprecated endpoints that are intentionally _not_ removed in Appium 4. They are
the last remaining JSONWP/MJSONWP endpoints supported by Appium, and are listed in the
[JSONWP](../reference/api/jsonwp.md) and [MJSONWP](../reference/api/mjsonwp.md) reference pages.
These endpoints are kept due to their common usage (for context management), and their deprecation
being somewhat recent. All of them are therefore planned to be removed in the next major Appium
version, in order to give users time to migrate to their replacements.
!!! info "Actions Needed"
Check your Appium client documentation for the affected methods, and adjust your code to use
their replacements
### `--allow-cors` Flag Renamed
In Appium 3, the `--allow-cors` server argument was the only feature flag not integrated with
Appium's default [insecure feature flag mechanism](./security.md). Appium 4 removes this argument
and replaces it with the `cors` insecure feature name. This means the feature can now be controlled
using the `--allow-insecure`, `--deny-insecure` and `--relaxed-security` flags.
Similarly to the `session_discovery` feature, the `cors` feature must also be prefixed with the
wildcard (`*`) symbol.
!!! info "Actions Needed"
Replace `--allow-cors` with `--allow-insecure=*:cors` or `--relaxed-security`
### Default Log Level Set to Info
The default logging level for server logs has been changed from `debug` to `info`. Debug-level
logging is very verbose and mostly only useful for troubleshooting.
!!! info "Actions Needed"
Pass `--log-level debug` explicitly if you rely on the previous verbosity
### CLI Command Output Streams Split
In Appium 3, all non-JSON output of Appium's CLI commands (`driver`/`plugin`/`setup`, but not
`server`) was written to `stderr`. Appium 4 now writes `log`/`ok`/`info`/`warn` level messages of
these commands to `stdout`, while `error` level output remains in `stderr`.
The log output of the server itself (the `server` command) is unaffected, since it already split
streams this way.
!!! info "Actions Needed"
If you use scripts that capture non-JSON output of `driver`/`plugin`/`setup` commands, make
sure they read from the correct stream
### SPDY/HTTP2 No Longer Supported
In Appium 3, the server could be launched with SSL/TLS, which enabled support for the SPDY and
HTTP/2 protocols. This functionality relied on the unmaintained `spdy` package. Appium 4 replaces
this package with Node's native `https` module, which only supports plain HTTPS (HTTP/1.1).
!!! info "Actions Needed"
Clients relying on SPDY or HTTP/2 multiplexing against Appium's TLS listener must switch to
plain HTTPS (HTTP/1.1) or use a proxy
### Selenium Grid 3 Support Removed
Support for Selenium Grid 3 hub has been removed, along with its `--nodeconfig` server
argument/config file property. Selenium Grid 4 remains supported.
!!! info "Actions Needed"
If you relied on Grid 3 registration, use the [Selenium Grid 4 relay feature](./grid.md) instead
### Post-Install Script Removed
Appium 2 and 3 supported a postinstall hook that allowed for installation of drivers/plugins
together with the Appium server itself:
```
npm install -g appium --drivers=... --plugins=...
```
Since postinstall hooks are a supply-chain security risk, and newer versions of `npm` disable them
by default, this hook has been removed in Appium 4.
!!! info "Actions Needed"
If you install drivers/plugins using the postinstall hook, migrate to Appium's
[`install`](../reference/cli/extensions.md#install) command, or declare extensions in your
project's `package.json` file
### Event Timings Capability Removed
In Appium 3, the `appium:eventTimings` capability could be set to `true` in order to include event
timing information in the response of the `GET /session/:sessionId` endpoint. Since Appium 4
removes this endpoint (see [Deprecated Endpoints Removed](#deprecated-endpoints-removed)), the
capability became obsolete, and has also been removed.
!!! info "Actions Needed"
Remove any instances of the `appium:eventTimings` capability, and instead use the [getLogEvents](../reference/api/appium.md#getlogevents) endpoint to retrieve event timings
### Unused Server Arguments Removed
The following server arguments have had no effect for a long time and have been removed, along with
their equivalents in the configuration file:
- `--callback-address` (`-ca`)
- `--callback-port` (`-cp`)
- `--debug-log-spacing`
- `--shell`
- `--strict-caps`
- `--trace-dir`
Passing any of them on the command line now fails with an unrecognized argument error (unless
[`--allow-unknown-args`](../reference/cli/server.md) is set), and config files containing them
fail schema validation.
!!! info "Actions Needed"
Remove these arguments from startup scripts and config files
## Behavior Fixes
This is a list of smaller changes that are positioned as fixes, rather than removal of existing
functionality, and may or may not be breaking depending on your usecase. The majority of changes
are related to alignment with the W3C WebDriver specification, and should not generally require
any user action.
### Session Lifecycle
- If a successfully created session fails initialization, Appium now attempts to delete the newly
created session and removes its registration while preserving the original initialization error
([#22873](https://github.com/appium/appium/pull/22873))
- The new command idle timeout (`appium:newCommandTimeout`) now only starts after finishing the
setup of initial settings and BiDi responses, preventing a session from expiring during
initialization ([#22881](https://github.com/appium/appium/pull/22881))
- If the new command idle timeout expires and the session deletion process starts, any driver
cleanup failures are now logged, instead of becoming an unhandled rejection that can terminate
the server and unrelated sessions ([#22964](https://github.com/appium/appium/pull/22964))
- Upon session deletion, any commands still waiting in the command queue are now rejected with HTTP
`404` / `invalid session id`, instead of remaining pending indefinitely
([#22874](https://github.com/appium/appium/pull/22874))
### Capabilities
- Names of standard WebDriver capabilities must now be case-sensitive (e.g. `platformName`, not
`PlatformName`). Handling of the _values_ of these capabilities, as well as names of prefixed
capabilities (e.g. `appium:app`), remains unchanged
([#22976](https://github.com/appium/appium/pull/22976))
- Malformed capability containers and parse failures now return HTTP `400` / `invalid argument`,
instead of HTTP `500` / `session not created`
([#22977](https://github.com/appium/appium/pull/22977))
- Top-level `null` capabilities are omitted before validation and merging, avoiding false
duplicate-key errors. Nested nulls, such as `timeouts: {script: null}`, are preserved
([#22975](https://github.com/appium/appium/pull/22975))
- Session settings provided inside `appium:options` are now honored
([#22882](https://github.com/appium/appium/pull/22882))
- The standard `timeouts` capability now correctly initializes BaseDriver's timeout state using
the same value checks as the [Set Timeouts](../reference/api/webdriver.md#timeouts) endpoint.
Backend handling remains driver-specific ([#22983](https://github.com/appium/appium/pull/22983))
- Setting both `appium:noReset` and `appium:fullReset` to `true` now returns HTTP `500` /
`session not created` instead of a generic error, and no longer leaves partially initialized
session state behind ([#22861](https://github.com/appium/appium/pull/22861),
[#22870](https://github.com/appium/appium/pull/22870))
- Setting `appium:newCommandTimeout` to `null`, a blank string, or a non-finite numeric value is
now ignored (keeping the default timeout value), instead of causing the timeout to be silently
disabled ([#22815](https://github.com/appium/appium/pull/22815),
[#23103](https://github.com/appium/appium/pull/23103)). Other invalid types, such as negative
numbers or nonnumeric strings, still fail capability validation
- Percent-encoded credentials in `appium:app` URLs are now decoded once before Basic authentication,
and complete HTTP-compressed downloads are no longer rejected if the decompressed file size
differs from `Content-Length` ([#22887](https://github.com/appium/appium/pull/22887),
[#22886](https://github.com/appium/appium/pull/22886))
- Setting `firstMatch` to an empty array (`[]`) is now rejected with HTTP `400` /
`invalid argument`, instead of being silently replaced with a single empty entry
([#22860](https://github.com/appium/appium/pull/22860))
- Every `firstMatch` candidate is now validated and merged before selection. Invalid supplied values
or duplicate keys in any candidate reject the request, even if another candidate could match;
missing required driver capabilities and unsupported platforms still allow matching to continue
([#22982](https://github.com/appium/appium/pull/22982))
- Default capabilities (which can be set using `--default-capabilities`) are now applied to each
individual `firstMatch` candidate separately. Values set in `alwaysMatch` or the current
candidate still take precedence ([#22988](https://github.com/appium/appium/pull/22988)). See
[Default Capabilities](../reference/cli/server.md#default-capabilities) for an example.
- Session settings are now applied from the selected `firstMatch` candidate, instead of potentially
being overridden by later unselected candidates. Defaults and `alwaysMatch` settings are still
applied first ([#22882](https://github.com/appium/appium/pull/22882))
- Values of the standard `timeouts` capability are now also validated in `alwaysMatch` and every
`firstMatch` candidate ([#23062](https://github.com/appium/appium/pull/23062)). A malformed
timeout object or invalid standard timeout value is rejected with HTTP `400` /
`invalid argument`, even if an earlier `firstMatch` candidate could match. Top-level
`timeouts: null` is still omitted, nested null timeout values are preserved, and unknown timeout
properties are ignored for validation
### HTTP Responses
- All WebDriver HTTP responses now include the `Cache-Control: no-cache` header. Caches must
revalidate these responses before reusing them
([#22971](https://github.com/appium/appium/pull/22971))
- Any WebDriver error `data` (e.g. alert text) is now preserved in driver and proxy responses
([#22974](https://github.com/appium/appium/pull/22974))
- The body of any `POST` command now has to be a JSON object; requests where the body is empty or
set to an empty JSON array (`[]`) return HTTP `400` with `invalid argument`
([#23007](https://github.com/appium/appium/pull/23007)). A value of `{}` is still accepted,
including commands that take no parameters. Routes that set `payloadParams.wrap` may still accept
an empty array
- `GET` requests to the server root route (e.g. `GET /` for a default server base path) now return
HTTP `404` / `unknown command`, instead of Express's HTML 404 page. Extensions can still register
their own root route ([#22969](https://github.com/appium/appium/pull/22969))
- `HEAD` requests to any `GET` command URL now return HTTP `405` without executing the `GET`
command. Custom server routes and `HEAD` request handlers retain their behavior
([#22992](https://github.com/appium/appium/pull/22992))
- Driver commands rejecting with `null` or `undefined` now return HTTP `500` / `unknown error`,
instead of causing the error handler itself to fail
([#22869](https://github.com/appium/appium/pull/22869))
- `TimeoutError` and `ScriptTimeoutError` now map to HTTP `500` instead of HTTP `408`
([#22686](https://github.com/appium/appium/pull/22686))
- A `detached shadow root` error is now preserved as HTTP `404`, instead of being converted to HTTP
`500` / `unknown error` ([#22968](https://github.com/appium/appium/pull/22968))
### Specific Endpoints
- [New Session](../reference/api/webdriver.md#createsession): now raises the `session not created`
error instead of `unknown error` if no installed driver matches the requested platform/automation
combination, or the matching driver cannot be loaded or does not export its class. Validation of
missing `platformName`/`appium:automationName` is unchanged
([#22970](https://github.com/appium/appium/pull/22970))
- [Get Timeouts](../reference/api/webdriver.md#gettimeouts): now returns `script` and `pageLoad` in
addition to the existing `implicit` and Appium-specific `command` values
([#22776](https://github.com/appium/appium/pull/22776))
- [Set Timeouts](../reference/api/webdriver.md#timeouts): `script`, `pageLoad`, and `implicit` now
only accept null or integer values; strings and fractions return HTTP `400` / `invalid argument`
([#22961](https://github.com/appium/appium/pull/22961))
- Set Timeouts: `null` values now correctly disable the specified timeout
([#22961](https://github.com/appium/appium/pull/22961))
- Set Timeouts: omitting `script`, `pageLoad`, or `implicit` no longer fails: omitted fields keep their
values and `{}` succeeds without changes. Invalid updates change no values
([#22960](https://github.com/appium/appium/pull/22960),
[#22961](https://github.com/appium/appium/pull/22961))
- Set Timeouts: unknown values for the legacy `type` argument now return HTTP `400` /
`invalid argument` instead of HTTP `500` / `unknown error`
([#22987](https://github.com/appium/appium/pull/22987))
- [getLog](../reference/api/others.md#getlog): unsupported `type` values now return HTTP `400` /
`invalid argument` instead of HTTP `500` / `unknown error`
([#22986](https://github.com/appium/appium/pull/22986))
### BiDi Protocol
- Subscriptions without `contexts` now receive events carrying a context, so that module
subscriptions such as `events: ["log"]` now match events such as `log.entryAdded`. Overlapping
subscriptions deliver each event only once ([#22883](https://github.com/appium/appium/pull/22883))
- The implementation of [`session.subscribe`](../reference/api/bidi.md#bidisubscribe) (which does
not yet support `userContexts`) now rejects `userContexts` with HTTP `500` /
`unsupported operation`, instead of silently creating an unscoped subscription. Malformed
`userContexts`, or supplying both `contexts` and `userContexts`, return HTTP `400` /
`invalid argument`. Drivers implementing user-context support can override `bidiSubscribe`
([#22877](https://github.com/appium/appium/pull/22877)).
- Any `sessionId` or `id` keys inside BiDi command parameters are now validated like any other
unknown parameter, instead of being silently accepted
([#22771](https://github.com/appium/appium/pull/22771))
### [Storage Plugin](https://github.com/appium/appium/tree/master/packages/storage-plugin)
- All [endpoints](../reference/api/plugins.md#storage-plugin) and stream/events WebSocket paths now
respect custom server `--base-path` values, instead of always being mounted at the server root
([#22906](https://github.com/appium/appium/pull/22906))
- File names starting with a dot or ending with `.filepart` are now rejected
([#22863](https://github.com/appium/appium/pull/22863),
[#22959](https://github.com/appium/appium/pull/22959))
- Concurrent WebSocket uploads of the same file are now rejected
([#22962](https://github.com/appium/appium/pull/22962))
- Pending upload WebSocket routes are now preserved across retries
([#22948](https://github.com/appium/appium/pull/22948))
- Errors on upload event sockets are now logged instead of potentially terminating the server
([#22963](https://github.com/appium/appium/pull/22963))
### Other Fixes
- The `appium driver`/`appium plugin` CLI commands now lock the extension manifest while running,
preventing any concurrent CLI commands from silently clobbering each other's changes
([#22767](https://github.com/appium/appium/pull/22767))
- IPv6 literals are now correctly bracketed during URL assembly, including BiDi WebSocket URLs and
[Execute Driver Plugin](https://github.com/appium/appium/tree/master/packages/execute-driver-plugin)
connections ([#22872](https://github.com/appium/appium/pull/22872),
[#22912](https://github.com/appium/appium/pull/22912),
[#22914](https://github.com/appium/appium/pull/22914))
## Developer-Facing Changes
The following changes primarily affect developers of Appium clients, drivers, plugins, or tools
that import Appium's internal packages directly. They do not affect most Appium end users.
### Extension Development
- When installing a locally available driver/plugin using Appium's CLI `install` command with the
`--source=local` flag, Appium now installs the extension directly from the supplied local
directory, without first creating an intermediate global `npm` link
([#23086](https://github.com/appium/appium/pull/23086)). Local installs still link to the source
directory, so source changes do not require reinstalling the extension. If you use tooling that
relies on the package being linked in `npm`'s global prefix, manage that global link separately.
- Extension manifests and `extensions.yaml` are now validated with `ajv`/JSON Schema; a corrupted
`extensions.yaml` now resets to an empty manifest with a warning, instead of crashing later with a
confusing error ([#22732](https://github.com/appium/appium/pull/22732))
- `ExecuteMethodMap` type declarations now check `params` against the target method's signature at
compile time, catching mismatched required/optional execute method parameters in driver code
([#22754](https://github.com/appium/appium/pull/22754))
- When a plugin intercepts a command that would otherwise be proxied downstream, Appium no longer
validates its fields or values ([#23060](https://github.com/appium/appium/pull/23060)). This
matches direct proxying, where the downstream remote end owns these checks. Plugins that
previously relied on Appium to validate these arguments can now receive missing or invalid
values (JSON-object request-body checks still remain in place before the plugin is called). If
your plugin handles such a command without calling `next()`, validate the inputs it uses.
Pass-through plugins can still call `next()` and delegate validation to the downstream remote end.
### `@appium/base-driver`
#### JSONWP/MJSONWP Removal
As listed [in the Breaking Changes section above](#jsonwpmjsonwp-internals-removed), the internal
code responsible for JSONWP/MJSONWP protocol support has been removed
([#22681](https://github.com/appium/appium/pull/22681)). This includes the following items:
- `ProtocolError` instances no longer carry a `jsonwpCode` property, and error responses no longer
include a legacy numeric `status` code (`errorFromMJSONWPStatusCode`, aliased as `errorFromCode`,
has been removed; use `errorFromW3CJsonCode`)
- Responses no longer duplicate element references under the legacy `ELEMENT` key; only the W3C
`element-6066-11e4-a52e-4f735466cecf` key is present
- `WebDriverProxy` (formerly `JWProxy`, now removed as a name) no longer converts responses from a
downstream automation server speaking legacy MJSONWP; downstream servers must speak W3C WebDriver
- `determineProtocol`, `DriverCore#setProtocolMJSONWP()`, and `DriverCore#isMjsonwpProtocol()` have
been removed; drivers can no longer produce the legacy `{sessionId, status, value}` response shape
- `statusCodes` and `getSummaryByCode` are no longer available (the `jsonwp-status` module has been
removed)
- A command result shaped like `{protocol, value}` is no longer unwrapped. It is sent to the
client as the command value, so a script returning `{protocol: 'W3C', value: 5}` gets that object
back. A result of `{protocol, error}` whose `protocol` is `W3C` or `MJSONWP` and whose `error`
is an `Error` is still thrown
#### HTTP Server Moved to Separate Package
The HTTP/Express server code has been extracted from `@appium/base-driver` into the new
`@appium/http-server` package ([#22800](https://github.com/appium/appium/pull/22800)). The
following items are therefore no longer exported from `@appium/base-driver` or `appium/driver.js`:
- Methods: `server`, `normalizeBasePath`, `configureServer`
- Types: `ServerOpts`, `ConfigureServerOpts`, `ConfigureHttpOpts`, `StartServerOpts`
If you use these items, import them from `@appium/http-server` instead.
#### Other Changes
- The default class export has been removed
([#22741](https://github.com/appium/appium/pull/22741)). Use the named `{BaseDriver}` export
instead
- The default export of `basedriver/helpers.js` has been removed
([#22741](https://github.com/appium/appium/pull/22741)). Use named exports instead
- `BaseDriver`'s constructor no longer takes command-mixin machinery into account
([#22741](https://github.com/appium/appium/pull/22741))
- `createSession()` no longer accepts the legacy multi-argument form
(`jwpCaps, reqCaps, w3cCaps`); only the single `w3cCapabilities` argument is supported now
([#22730](https://github.com/appium/appium/pull/22730))
- The deprecated `driverData` mechanism (`Core.driverData`, the `driverData` parameter on
`createSession`/`deleteSession`, and the `DriverData` type) has been removed
([#22716](https://github.com/appium/appium/pull/22716)). Migrate to `IAppiumIpc` instead
- The `server()` and `configureServer()` methods (now exported by `@appium/http-server`) now
default to `allowCors: false` ([#22990](https://github.com/appium/appium/pull/22990))
- Both `ipc.unsubscribe(topic, subscriber)` and `subscription.unsubscribe()` now finish waiting on
async iterators and notify observers once ([#22955](https://github.com/appium/appium/pull/22955)).
An observer that throws still propagates its error to the caller, but no longer prevents waiting
iterators from finishing
- The unused `reset()` method has been removed
([#22741](https://github.com/appium/appium/pull/22741))
- The `generateDriverLogPrefix()` helper no longer supports the deprecated `sessionId` argument
([#22764](https://github.com/appium/appium/pull/22764))
- The new command idle timeout now stays suspended through HTTP/BiDi plugin chains, including work
after `next()`, and while proxied BiDi commands await a response
([#22946](https://github.com/appium/appium/pull/22946),
[#22947](https://github.com/appium/appium/pull/22947)). Custom `startNewCommandTimeout`
implementations must delegate timer creation to `super.startNewCommandTimeout()` so they respect
shared activity, while custom command execution must delegate to `super.executeCommand()` or wrap
the full command in `runWithCommandTimeout`
- The `appium:autoLaunch`, `appium:locale`, `appium:language`, `appium:autoWebview`,
`appium:orientation`, and `appium:udid` capabilities are no longer validated as part of the
standard capability constraints ([#22950](https://github.com/appium/appium/pull/22950),
[#22952](https://github.com/appium/appium/pull/22952)). If you use them, declare them in your own
driver constraints
- The built-in test fixture routes (`/welcome`, `/test/guinea-pig*`, `/produce_error`, `/crash`),
the `STATIC_DIR` export, and the `APPIUM_ENABLE_LEGACY_TEST_PAGES` environment variable have been
removed ([#22680](https://github.com/appium/appium/pull/22680)). If you relied on these fixtures,
migrate to use your own local test server
### `@appium/base-plugin`
- The default class export has been removed ([#22718](https://github.com/appium/appium/pull/22718)).
Use the named `{BasePlugin}` export instead
- `Plugin#logger` has been removed in favor of `Plugin#log`
([#22718](https://github.com/appium/appium/pull/22718))
- `Plugin#name` and `Plugin#cliArgs` are now read-only
([#22718](https://github.com/appium/appium/pull/22718))
### `@appium/logger`
- The default class export has been removed ([#22719](https://github.com/appium/appium/pull/22719)).
Use the named `{log}` export instead
- The long-disabled, no-op progress/unicode methods (`enableProgress`, `disableProgress`,
`progressEnabled`, `enableUnicode`, `disableUnicode`) have been removed
([#22719](https://github.com/appium/appium/pull/22719))
### `@appium/support`
- `env`: the module has been integrated into the `appium` package as internal helpers
([#22708](https://github.com/appium/appium/pull/22708))
- `imageUtil`: the module has been removed ([#22678](https://github.com/appium/appium/pull/22678))
- `fs`: the following exports have been removed: `readPackageJsonFrom` and `findRoot` methods,
`F_OK`/`R_OK`/`W_OK`/`X_OK` constants, `CopyFileDescriptor` and `ReadFn` types
([#22678](https://github.com/appium/appium/pull/22678))
- `fs`: `glob()` now relies on Node's `fs.promises.glob` instead of the `glob` package, with a
narrower `GlobOptions` shape ([#22735](https://github.com/appium/appium/pull/22735))
- `fs`: `mv()` now preserves symlinks inside moved directories and moves source symlinks themselves
without moving their targets' contents. Dangling source links are supported, and Windows
case-only renames update the entry's spelling
([#22880](https://github.com/appium/appium/pull/22880),
[#22954](https://github.com/appium/appium/pull/22954),
[#22958](https://github.com/appium/appium/pull/22958))
- `fs`: `walkDir()` now continues after walker errors such as `EACCES` and `ELOOP` instead of
hanging. These errors are logged and affected entries are skipped; `ENOENT` still rejects the
returned promise ([#22956](https://github.com/appium/appium/pull/22956))
- `fs`: `write()` now relies on Node's `promisify`, which resolves to an object
(`{bytesWritten, buffer}`), instead of only `bytesWritten`
([#22704](https://github.com/appium/appium/pull/22704))
- `logger`: the default export has been removed. Use the named `{log}` export instead
([#22719](https://github.com/appium/appium/pull/22719))
- `logger`: `errorAndThrow` has been removed in favor of `errorWithException`
([#22719](https://github.com/appium/appium/pull/22719))
- `net`: support for FTP-based file uploads has been removed, along with the `FtpUploadOptions` and
`NotHttpUploadOptions` types ([#22678](https://github.com/appium/appium/pull/22678))
- `net`: the new `checkPortStatus()` and `getFreePort()` helpers replace the `portscanner` package
and custom free port lookups in drivers and plugins
([#23156](https://github.com/appium/appium/pull/23156)). Unlike `portscanner`, they accept an
options object instead of positional arguments. `getFreePort()` also covers `findAPortNotInUse()`:
pass `port` (a single port or a `[startPort, endPort]` range) to probe specific ports, in which
case it throws `NoFreePortError` if all of them are busy instead of resolving with `false`
- `mjpeg`: the module has been removed ([#22678](https://github.com/appium/appium/pull/22678))
- `mkdirp`: the module has been removed ([#22678](https://github.com/appium/appium/pull/22678)).
Import `mkdirp()` from the `fs` module instead
- `node`: `requirePackage()` has been removed
([#22684](https://github.com/appium/appium/pull/22684))
- `npm`: the module has been integrated into the `appium` package as internal helpers
([#22721](https://github.com/appium/appium/pull/22721))
- `process`: the module has been removed ([#22678](https://github.com/appium/appium/pull/22678))
- `system`: `macOsxVersion()` has been removed
([#22684](https://github.com/appium/appium/pull/22684))
- `util`: the following methods have been removed: `uuidV1`, `uuidV3`, `uuidV5`, `localIp`,
`cancellableDelay`, and `multiResolve` ([#22678](https://github.com/appium/appium/pull/22678))
- `zip`: `extractAllTo()` always uses the built-in JS extractor now, so the `useSystemUnzip` option
has been removed ([#23091](https://github.com/appium/appium/pull/23091)). The extractor supports
only stored and deflate entries and verifies the CRC32 of every entry. File names that are not
flagged as UTF-8 by the archive are decoded as `utf8` by default, and the legacy `cp437` decoding
is no longer supported. Other single-byte encodings supported by Node.js can be selected via
`fileNamesEncoding`. Archives with encrypted entries or other compression methods are rejected
with `ZipStreamUnsupportedError`
### `@appium/tsconfig`
- `noImplicitOverride` is now set to `true`, which means that TypeScript drivers and plugins that
extend the config must mark every member overriding a base class member (e.g. `BaseDriver` or
`BasePlugin` methods, and `static` fields such as `newMethodMap`) with the `override` modifier
([#23143](https://github.com/appium/appium/pull/23143)). Opt-out is also possible by setting
`noImplicitOverride` to `false` in your own `tsconfig.json`.
### Client Development
- State-changing HTTP requests with an `Origin` header now return HTTP `403`, unless the CORS
insecure feature is enabled on the Appium server
([#23102](https://github.com/appium/appium/pull/23102)). Remove the `Origin` header or instruct
users to enable CORS.
## New Features
### App URL Rules
The new `--app-url-rules` server CLI flag (and its equivalent configuration file property) allows
server hosts to restrict the host/IP values allowed in capabilities like `appium:app`. Configurable
properties include allow/deny lists, HTTPS-only, credentials, and redirect limits.
Refer to [the Security guide](./security.md#restricting-remote-app-urls) for more details.
### CLI Update Command Checks Server Requirement
As a follow-up to Appium 3.9, which changed the default behavior of the Appium CLI
[`install`](../reference/cli/extensions.md#install) command to install the newest extension version
that is compatible with the current server (as opposed to throwing an error if the server
requirement of the latest extension version is incompatible), Appium 4 adjusts the
[`update`](../reference/cli/extensions.md#update) command to now implement this behavior as well.
This makes default usage of both `install` and `update` safe even when future major extension
versions raise their server requirements.
### Commands Can Bypass Queue
Driver commands (endpoints) are now allowed to bypass the default command queue, which enables the
command to execute while another long-running command is in progress.
By default, only the standard [Status](../reference/api/webdriver.md#getstatus) endpoint is exempt
from the queue, but driver developers can also customize the list of exempt commands by overriding
the `queueExemptCommands` getter.
The behavior of the idle timer (set by `appium:newCommandTimeout`) has also been adjusted to only
reset once no commands are executing.
### New Set Timeouts Parameter
The standard [Set Timeouts](../reference/api/webdriver.md#timeouts) endpoint has been extended to
additionally accept the Appium-specific `command` parameter. This aligns its handling with
[Get Timeouts](../reference/api/webdriver.md#gettimeouts), which already returned this parameter.
The parameter itself is mapped to the `appium:newCommandTimeout` capability.
The non-standard `type`/`ms` parameters, which were previously the only way to change this timeout
mid-session, have been deprecated as a result.
### Universal XML Plugin Can Be Toggled
The [Universal XML plugin](https://github.com/appium/appium/tree/master/packages/universal-xml-plugin)
now provides the [`universalXml: setEnabled` and `universalXml: isEnabled` execute methods](../reference/api/plugins.md#universal-xml-plugin),
which allow toggling the translation during a session, e.g. to retrieve the original page source.
+123
View File
@@ -37,6 +37,10 @@ sessions the feature should apply. The prefix can be either the driver's `automa
wildcard (`*`) symbol, if the feature should be applied to all drivers. The prefix and feature name
are separated using the colon character (`:`).
Use the driver's `automationName`, which may differ from its install name. An install-name-only
prefix does not enable or disable a feature. When configuring a session, Appium warns about such
entries for that driver unless the prefix is another installed driver's `automationName`.
For example, `first:foo` refers to the `foo` feature for the `first` driver, whereas `*:bar` refers
to the `bar` feature for all drivers.
@@ -87,3 +91,122 @@ Turn on multiple insecure features for specific drivers:
```bash
appium --allow-insecure=uiautomator2:adb_shell,xcuitest:get_server_logs
```
## Restricting Remote App URLs
Several drivers accept a URL instead of a local path in capabilities such as `appium:app`, in which
case the Appium server downloads the application package from that URL before starting the session.
By default, any `http:` or `https:` URL is accepted. Server hosts who want to control which URLs
their server is allowed to download from can do so with the `--app-url-rules` argument (or the
`server.app-url-rules` property in a [configuration file](./config.md)). Its value is a JSON object
(or a path to a JSON file) with any of the following properties:
| <div style="width:10em">Rule</div> | Description | Default |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `allow` | List of hostname patterns, IP addresses, or CIDR subnets. If non-empty, a hostname or its resolved address must match _at least one_ | `[]` |
| `deny` | List of hostname patterns, IP addresses, or CIDR subnets. A matching hostname or resolved address is rejected, even if an `allow` rule also matches | `[]` |
| `httpsOnly` | Only accept `https:` URLs | `false` |
| `allowCredentials` | Accept URLs containing a username and/or password (e.g. `https://user:pass@host/app.apk`) | `true` |
| `maxRedirects` | Maximum number of HTTP redirects to follow while downloading. Set to `0` to reject any redirect | `21` |
Hostnames are normalized (lowercased, converted to Punycode, trailing dot removed) before matching
and resolved on every download. Address rules apply to literal addresses and all dynamically
resolved IPv4/IPv6 addresses. The rules are also applied to every redirect, so redirects cannot be
used to escape them. If a URL violates any rule, the session is not created and a generic error
is returned. The violated rule is deliberately neither reported to the client nor written to the
server log, since server logs are often handed over to clients as well. URL schemes, ports, paths,
queries, and fragments are not matched.
Hostname patterns use the [picomatch](https://github.com/micromatch/picomatch#globbing-features)
glob syntax and are matched against the whole hostname:
| Pattern | Matches |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `artifacts.example.com` | Exactly this hostname |
| `*.example.com` | Any subdomain of `example.com` (including nested ones, like `a.b.example.com`), but not `example.com` itself |
| `*example.com` | Any hostname ending with `example.com`, including `example.com` itself |
| `apps.{staging,prod}.example.com` | `apps.staging.example.com` and `apps.prod.example.com` |
| `build-?.example.com` | `build-1.example.com`, `build-a.example.com`, etc. |
| `node[0-9].example.com` | `node0.example.com` to `node9.example.com` |
IP address rules match a single address (`192.0.2.10`, `2001:db8::1`) or a whole subnet in CIDR
notation (`10.0.0.0/8`, `2001:db8::/32`). IPv4 rules also match IPv4-mapped IPv6 addresses
(e.g. `::ffff:10.1.2.3`).
!!! note
```
These rules only apply to URLs the server downloads via the standard app configuration helper,
which is used for `appium:app` and similar capabilities by all official drivers. Drivers may
define custom capabilities with URLs that are processed differently and thus are not covered.
```
!!! note
```
If the server downloads applications through an HTTP proxy (configured via the `HTTP_PROXY`,
`HTTPS_PROXY` and `NO_PROXY` environment variables), the proxy resolves the destination host
itself, so rules containing IP addresses or subnets cannot be enforced for proxied downloads.
Such downloads are rejected; either exclude the download hosts from proxying via `NO_PROXY`
or only use hostname-based rules.
```
### Examples
Only allow HTTPS downloads from an internal artifact server, without credentials in the URL and
without following redirects:
```bash
appium --app-url-rules='{"allow": ["artifacts.example.com", "10.0.0.0/8"], "httpsOnly": true, "allowCredentials": false, "maxRedirects": 0}'
```
The same configuration as part of a config file:
```yaml
server:
app-url-rules:
allow:
- 'artifacts.example.com'
- '10.0.0.0/8'
httpsOnly: true
allowCredentials: false
maxRedirects: 0
```
Allow downloads from any subdomain of `example.com` and from two IPv6 subnets, except from the
staging environment:
```yaml
server:
app-url-rules:
allow:
- '*.example.com'
- '2001:db8:1::/48'
- '2001:db8:2::/48'
deny:
- '*.staging.example.com'
```
Allow downloads from anywhere, except from the server itself, private networks, link-local
addresses (such as cloud metadata services), and any `.internal` hostname:
```yaml
server:
app-url-rules:
deny:
- 'localhost'
- '*.internal'
- '127.0.0.0/8'
- '10.0.0.0/8'
- '172.16.0.0/12'
- '192.168.0.0/16'
- '169.254.0.0/16'
- '::1/128'
- 'fc00::/7'
- 'fe80::/10'
```
The rules in the last example are applied to the addresses each hostname resolves to, so they
cannot be bypassed via DNS. Note that the `deny` list also blocks any download from the server's
own private network, so a private artifact server must be excluded from the `deny` rules in order
to work.
+6 -7
View File
@@ -2,7 +2,7 @@
hide:
- toc
title: SSL/TLS/SPDY Support
title: SSL/TLS Support
---
Appium 2.2 introduces the option to start the Appium server with SSL/TLS support.
@@ -20,15 +20,14 @@ Both arguments must be provided and should contain paths to a valid
[X509 PEM](https://www.ssl.com/guide/pem-der-crt-and-cer-x-509-encodings-and-conversions/)
certificate and its corresponding private key.
After the server is started use the `https` protocol and a client supporting SSL/TLS or
[SPDY](https://en.wikipedia.org/wiki/SPDY) to communicate to it.
After the server is started use the `https` protocol and a client supporting SSL/TLS to
communicate to it.
### Supported Features
Once a secure server socket is established it supports the following protocols:
`['h2', 'spdy/3.1', 'spdy/3', 'spdy/2', 'http/1.1', 'http/1.0']`. See
[the SPDY node module documentation](https://www.npmjs.com/package/spdy) to get more details about
its features. All insecure client connections will be rejected by the server.
Once a secure server socket is established it uses Node.js' native
[`https`](https://nodejs.org/api/https.html) module to serve connections. All insecure client
connections will be rejected by the server.
### Self-Signed Certificates
+12 -2
View File
@@ -41,6 +41,16 @@ So, for example, the `Find Element` command corresponds to an HTTP `POST` reques
endpoint `/session/:sessionid/element` (where in this case, `:sessionid` is a placeholder for the
unique session ID generated by the server in a previous call to `Create Session`).
If the client disconnects before Appium finishes sending a `Create Session` response and the
request has no `X-Idempotency-Key`, Appium deletes the new session once driver setup completes.
Setup is not interrupted. With an accepted idempotency key, a retry that arrives before setup
finishes waits for the same session ID, or the same error if setup failed. If the original client
and all waiting retries disconnect before setup finishes, Appium deletes the new session and
discards its cached result; a later retry starts a new session. Otherwise, Appium keeps the session
and caches its response for replay while it remains in the bounded, in-memory idempotency cache.
Disconnecting after a response was sent, or during a command in an existing session, does not
automatically end that session. Use `Delete Session` when you are done.
This information is primarily useful for people developing technology that works with the WebDriver
spec. It's not particularly useful for people trying to write Appium or Selenium tests. When you
write an Appium test, you want to use a programming language you're familiar with. Luckily, there
@@ -112,8 +122,8 @@ System.Console.WriteLine(driver.PageSource);
Each of these scripts, despite being in different languages, does the same thing under the hood:
1. Call `Find Element` with a `using` parameter of `xpath` and a `value` parameter expressing the
XPath query used to find an element. (If you're confused about these terms, you might find an
introduction to Appium or Selenium useful)
XPath query used to find an element. (If you're confused about these terms, you might find an
introduction to Appium or Selenium useful)
2. Call `Click Element` with the ID of the element found in the previous call.
3. Call `Get Element Text` with the ID of the same element, and print it to the console.
4. Call `Get Page Source` to retrieve the page/app source and print it to the console.
+1 -1
View File
@@ -19,7 +19,7 @@ Appium, called `BaseDriver`. You could have something very close to a "working"
very simple lines of code:
```js
import BaseDriver from '@appium/base-driver'
import {BaseDriver} from '@appium/base-driver'
class MyNewDriver extends BaseDriver {
}
@@ -8,7 +8,7 @@ title: System Requirements
The basic requirements for the Appium server are:
- A macOS, Linux, or Windows operating system
- [Node.js](https://nodejs.org) version in the [SemVer](https://semver.org) range `^20.19.0 || ^22.12.0 || >=24.0.0`
- [Node.js](https://nodejs.org) version in the [SemVer](https://semver.org) range `^22.22.2 || ^24.15.0 || >=26.0.0`
- LTS is recommended
- [`npm`](https://npmjs.com) version `>=10` (`npm` is usually bundled with Node.js, but can be upgraded
independently)
@@ -8,15 +8,14 @@ title: Write a Test (.NET)
The [Appium .NET Client](https://github.com/appium/dotnet-client/) is
an official Appium client in C#. This driver is an extension of the Selenium C# client. It has all the functionalities of the regular driver, but add Appium-specific methods on top of this. The driver is available on the public NuGet Gallery as [Appium.WebDriver](https://www.nuget.org/packages/Appium.WebDriver/).
Now, we get inside the directory and create a new [NUnit](https://nunit.org/) project. We will also add the references to the Appium.Net driver, and other dependencies.
Now, create a new [NUnit](https://nunit.org/) project. We will also add the references to the Appium.Net driver, and other dependencies.
```bash
cd dotnet-client
dotnet new nunit --name appiumtest
cd appiumtest
# This will install the latest 5.x version
# This will install the latest version
dotnet add package Appium.WebDriver --prerelease
dotnet add package Newtonsoft.Json --version 13.0.3
```
@@ -47,7 +46,7 @@ public class Tests
driverOptions.AddAdditionalAppiumOption("appPackage", "com.android.settings");
driverOptions.AddAdditionalAppiumOption("appActivity", ".Settings");
// NoReset assumes the app com.google.android is preinstalled on the emulator
// NoReset assumes the app com.android.settings is preinstalled on the emulator
driverOptions.AddAdditionalAppiumOption("noReset", true);
_driver = new AndroidDriver(serverUri, driverOptions, TimeSpan.FromSeconds(180));
+22 -7
View File
@@ -49,6 +49,20 @@ Subscribes to one or more BiDi events.
`{subscription: string}` — a unique subscription ID that can be passed to `session.unsubscribe`.
#### Limits
A session can have up to 100 subscriptions. Every subscription covers a combination of each of its
events and each of its contexts (an event without contexts counts as one), and all the subscriptions
together, counted one by one, can cover up to 1000 combinations. Lists in the parameters can have up
to 1000 items, and the event names, contexts and subscription IDs can be up to 256 characters long.
A request that exceeds a limit fails with an `invalid argument` error without changing the subscriptions.
Unsubscribing by event names (`events`) removes the matching contexts of those events across all the
subscriptions (an event stays active in the contexts that are not listed), but the IDs of the
subscriptions that have no events left stay valid, so they can still be passed to `session.unsubscribe`.
The oldest such ID expires only when a new subscription needs its slot at the limit of 100 subscriptions.
An unknown or expired ID fails the whole `subscriptions` request, and none of its subscriptions are removed.
### bidiUnsubscribe
```
@@ -57,16 +71,17 @@ session.unsubscribe
> WebDriver BiDi documentation: [session.unsubscribe](https://w3c.github.io/webdriver-bidi/#command-session-unsubscribe)
Unsubscribes using either previously returned subscription IDs or event names.
Removing a subscription ID preserves any overlapping subscriptions.
Unsubscribes from one or more BiDi events using subscription IDs or event names. Event names can
also be scoped to contexts (legacy parameter). Removing a subscription ID preserves any overlapping
subscriptions.
#### Parameters
| Name | Description | Type | Default |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ------- |
| `subscriptions?` | Non-empty list of subscription IDs returned by `session.subscribe`. Cannot be combined with `events` or `contexts`. | string[] | |
| `contexts?` | Non-standard, only together with `events`: contexts in which to unsubscribe from the specified events. By default, the global scope is applied. | string[] | `['']` |
| `events?` | Non-empty list of event names to unsubscribe from. Required when `subscriptions` is omitted. | string[] | |
| Name | Description | Type | Default |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------ | ------- |
| `subscriptions?` | Non-empty list of subscription IDs returned by `session.subscribe`. Cannot be combined with `events` or `contexts`. | string[] | |
| `events?` | Non-empty list of event names to unsubscribe from. Required when `subscriptions` is omitted. | string[] | |
| `contexts?` | Legacy parameter: contexts in which to unsubscribe from events specified in `events`. By default, the global scope is applied. | string[] | `['']` |
All subscription IDs must be known to the current session. An unknown ID causes an `invalid argument`
error without removing any subscriptions. Subscription IDs are cleared when the session is deleted.
@@ -11,125 +11,6 @@ title: JSON Wire Protocol
The following is a list of legacy [JSON Wire Protocol (JSONWP)](https://www.selenium.dev/documentation/legacy/json_wire_protocol/)
endpoints supported in Appium.
### getSession
```
GET /session/:sessionId
```
> JSONWP documentation: [/session/:sessionId](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionid)
Retrieves the capabilities of the current session.
Appium implements a modified version of this endpoint. If the `appium:eventTimings` capability is
set to `true`, the returned result will additionally include the `events` key, whose value contains
the event history and timings.
!!! warning "Deprecated"
For retrieving capabilities, please use [`getAppiumSessionCapabilities`](./appium.md#getappiumsessioncapabilities).<br />
For retrieving event history, please use [`getLogEvents`](./appium.md#getlogevents).
#### Response
`Capabilities` - an object containing the session capabilities, and the event history (if applicable)
### availableIMEEngines
```
GET /session/:sessionId/ime/available_engines
```
> JSONWP documentation: [/session/:sessionId/ime/available_engines](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimeavailable_engines)
Retrieves all IME (input method editor) engines available on the device under test.
!!! warning "Deprecated"
In the future, this endpoint will be moved to the [UiAutomator2 and Espresso drivers](../../ecosystem/drivers.md)
#### Response
`string[]` - a list of available IME engines
### getActiveIMEEngine
```
GET /session/:sessionId/ime/active_engine
```
> JSONWP documentation: [/session/:sessionId/ime/active_engine](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimeactive_engine)
Retrieves the name of the active IME engine.
!!! warning "Deprecated"
In the future, this endpoint will be moved to the UiAutomator2 and Espresso drivers
#### Response
`string` - the name of the active IME engine
### isIMEActivated
```
GET /session/:sessionId/ime/activated
```
> JSONWP documentation: [/session/:sessionId/ime/activated](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimeactivated)
Determines if IME input is available and active.
!!! warning "Deprecated"
In the future, this endpoint will be moved to the UiAutomator2 and Espresso drivers
#### Response
`boolean` - `true` if IME is active, otherwise `false`
### deactivateIMEEngine
```
POST /session/:sessionId/ime/deactivate
```
> JSONWP documentation: [/session/:sessionId/ime/deactivate](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimedeactivate)
Deactivates the currently active IME engine.
!!! warning "Deprecated"
In the future, this endpoint will be moved to the UiAutomator2 and Espresso drivers
#### Response
`null`
### activateIMEEngine
```
POST /session/:sessionId/ime/activate
```
> JSONWP documentation: [/session/:sessionId/ime/activate](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimeactivate)
Activates an IME engine.
!!! warning "Deprecated"
In the future, this endpoint will be moved to the UiAutomator2 and Espresso drivers
#### Parameters
| Name | Description | Type |
| -------- | ---------------------------------- | ------ |
| `engine` | Name of the IME engine to activate | string |
#### Response
`null`
### getOrientation
```
@@ -171,53 +52,3 @@ Sets the orientation of the device under test.
#### Response
`null`
### getGeoLocation
```
GET /session/:sessionId/location
```
> JSONWP documentation: [/session/:sessionId/location](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidlocation)
Retrieves the current location of the device under test.
!!! warning "Deprecated"
Please use driver-specific extension methods such as `mobile: getGeoLocation` or
`mobile: getSimulatedLocation`
#### Response
`Location` - an object with the following properties:
| Name | Description | Type |
| ----------- | -------------------------------- | ------ |
| `altitude` | Altitude of the device location | number |
| `latitude` | Latitude of the device location | number |
| `longitude` | Longitude of the device location | number |
### setGeoLocation
```
POST /session/:sessionId/location
```
> JSONWP documentation: [/session/:sessionId/location](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidlocation)
Sets the current location of the device under test.
!!! warning "Deprecated"
Please use driver-specific extension methods such as `mobile: setGeoLocation` or
`mobile: setSimulatedLocation`
#### Parameters
| Name | Description | Type |
| ---------- | ------------------------------------------- | ------------------------- |
| `location` | New device latitude, longitude and altitude | [`Location`](#response_6) |
#### Response
`null`
@@ -120,53 +120,3 @@ Retrieves all available application contexts.
#### Response
`string[]` - the names of available contexts
### getNetworkConnection
```
GET /session/:sessionId/network_connection
```
> MJSONWP documentation: [Device Modes](https://github.com/SeleniumHQ/mobile-spec/blob/master/spec-draft.md#device-modes)
Retrieves the current state of network types (data, Wi-Fi, airplane mode).
!!! warning "Deprecated"
Please use driver-specific extension methods such as `mobile: getConnectivity`
#### Response
`NetworkConnectionState` - a number indicating the current network state:
| Value | Data | Wi-Fi | Airplane Mode |
| ----- | ---- | ----- | ------------- |
| `0` | OFF | OFF | OFF |
| `1` | OFF | OFF | ON |
| `2` | OFF | ON | OFF |
| `4` | ON | OFF | OFF |
| `6` | ON | ON | OFF |
### setNetworkConnection
```
POST /session/:sessionId/network_connection
```
> MJSONWP documentation: [Device Modes](https://github.com/SeleniumHQ/mobile-spec/blob/master/spec-draft.md#device-modes)
Sets the state of network types (data, Wi-Fi, airplane mode).
!!! warning "Deprecated"
Please use driver-specific extension methods such as `mobile: setConnectivity`
#### Parameters
| <div style="width:6em">Name</div> | Description | <div style="width:18em">Type</div> |
| --------------------------------- | -------------------------------------------------------------------------- | ----------------------------------------------------- |
| `parameters` | Object containing the `type` key, whose value is the desired network state | `{"type": `[`NetworkConnectionState`](#response_5)`}` |
#### Response
[`NetworkConnectionState`](#response_5) - the new network state
@@ -267,6 +267,43 @@ preserved, and only the incomplete uploads will be stopped.
## Universal XML Plugin
Translation is on by default. It can be turned off and on during a session with the
[execute methods](../../guides/execute-methods.md) below, and applies only to the current session.
### execute
```
POST /session/:sessionId/execute/sync
```
Modifies the [`execute`](./webdriver.md#execute) endpoint:
- Adds the `universalXml: setEnabled` and `universalXml: isEnabled` execute methods. Any other
script is passed on unchanged
#### universalXml: setEnabled
Turns translation on or off for the current session. While it is off, `findElement`,
`findElements` and `getPageSource` are passed on unchanged.
##### Parameters
| Name | Description | Type |
| --------- | ------------------------------------------------- | ------- |
| `enabled` | Whether node/attribute names should be translated | boolean |
##### Response
`null`
#### universalXml: isEnabled
Returns whether translation is on for the current session.
##### Response
`boolean` - `true` if translation is on
### findElement
```
@@ -26,18 +26,11 @@ POST /session
Creates a new WebDriver session.
Appium implements a modified version of this endpoint for historical reasons. While the W3C
endpoint only accepts 1 parameter, Appium's implementation allows up to 3 parameters, as this was
required by the legacy JSON Wire Protocol (JSONWP). Since Appium 2, the JSONWP format is no longer
supported, and any of the 3 parameters can be used to specify the W3C capabilities.
#### Parameters
| Name | Description | Type |
| ------------------- | ----------------------------------------------------------------------------- | --------------- |
| `w3cCapabilities1?` | Capabilities of the new session | `W3CDriverCaps` |
| `w3cCapabilities2?` | Another location for the new session capabilities (legacy) | `W3CDriverCaps` |
| `w3cCapabilities?` | Another location for the new session capabilities (legacy) | `W3CDriverCaps` |
| Name | Description | Type |
| --------------- | ------------------------------- | --------------- |
| `capabilities?` | Capabilities of the new session | `W3CDriverCaps` |
#### Response
@@ -92,14 +85,19 @@ GET /session/:sessionId/timeouts
Retrieves the timeout values of the current session.
Appium implements a modified version of this endpoint, by also returning the value of the `command`
timeout for supported drivers and contexts.
#### Response
`GetTimeoutsResult` - an object with the following properties:
| Name | Description | Type |
| ---------- | --------------------- | ------ |
| `command` | Command timeout | number |
| `implicit` | Implicit wait timeout | number |
| Name | Description | Type |
| ---------- | ---------------------- | -------------- |
| `script` | Script timeout | number or null |
| `pageLoad` | Page load timeout | number or null |
| `implicit` | Implicit wait timeout | number or null |
| `command` | Appium command timeout | number |
### timeouts
@@ -111,13 +109,17 @@ POST /session/:sessionId/timeouts
Sets the timeout values of the current session.
Appium implements a modified version of this endpoint by adding the optional `command` parameter
for supported drivers and contexts.
#### Parameters
| Name | Description | Type |
| ----------- | ---------------------------------------------------------- | ------ |
| `implicit?` | Implicit wait timeout (in milliseconds) | number |
| `pageLoad?` | Page load timeout (in milliseconds) | number |
| `script?` | Script timeout (in milliseconds) | number |
| Name | Description | Type |
| ----------- | ----------------------------------------------------------- | -------------- |
| `script?` | Script timeout (in milliseconds) | number or null |
| `implicit?` | Implicit wait timeout (in milliseconds) | number or null |
| `pageLoad?` | Page load timeout (in milliseconds) | number or null |
| `command?` | Appium command timeout (in milliseconds) | number |
#### Response
@@ -954,7 +956,7 @@ POST /session/:sessionId/actions
> WebDriver documentation: [Perform Actions](https://w3c.github.io/webdriver/#perform-actions)
Performs a sequence of [actions](https://w3c.github.io/webdriver/#actions).
Performs a sequence of [actions](https://w3c.github.io/webdriver/#actions). See the [Automating Gestures](../../guides/gestures.md) guide for multi-language examples.
#### Parameters
@@ -14,6 +14,7 @@ they can only be enabled using the wildcard (`*`) prefix:
| Feature Name | Description |
| ------------------- | ------------------------------------------------------------------------------- |
| `session_discovery` | Allows retrieving the list of active server sessions via `GET /appium/sessions` |
| `cors` | Allows web browser connections to the server from any host |
Of course, Appium drivers and plugins are free to define additional insecure features of their own.
The following features are defined by official plugins:
+74 -42
View File
@@ -24,48 +24,80 @@ appium
All of these options can also be set via a [Configuration File](../../guides/config.md). Options
set on the command line will override any options found in a configuration file.
| <div style="width:15em">Argument</div> | Description | Type | <div style="width:7em">Default</div> |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------------------------------------------------------- |
| `--address`, `-a` | IPv4/IPv6 address or a hostname to listen on | string | `0.0.0.0` |
| `--allow-cors` | Allow web browser connections from any host | boolean | `false` |
| `--allow-insecure` | List of [insecure features](../../guides/security.md) that should be allowed in this server's sessions. Individual features can be overridden by `--deny-insecure`. Has no effect in combination with `--relaxed-security`. | array<string> | `[]` |
| `--allow-unknown-args` | Do not exit if unrecognized command-line arguments are passed to the server; ignore them instead. Useful when the Appium CLI is wrapped by external tooling that appends extra flags. | boolean | `false` |
| `--base-path`, `-pa` | Base path to use as the prefix for all webdriver routes running on the server | string | `""` |
| `--callback-address`, `-ca` | Callback IP address | string | same as `--address` |
| `--callback-port`, `-cp` | Callback port | integer | `4723` |
| `--config` | Path to an [Appium configuration JSON file](../../guides/config.md) | string | |
| `--debug-log-spacing` | Add exaggerated spacing in logs to help with visual inspection | boolean | `false` |
| `--default-capabilities`, `-dc` | Capabilities that will be used for each session, unless overridden by received capabilities | object | |
| `--deny-insecure` | List of [insecure features](../../guides/security.md) that should be disabled in this server's sessions. Since all insecure features are disabled by default, this argument has no effect without either `--allow-insecure` or `--relaxed-security`, and is applied after both. | array<string> | `[]` |
| `--driver` | Driver-specific configuration. Keys should correspond to driver package names | object | |
| `--drivers-import-chunk-size` | Maximum number of drivers that can be imported in parallel on server startup | number | `3` |
| `--keep-alive-timeout`, `-ka` | Timeout (in seconds) to use as both the keep-alive timeout and the connection timeout for all client requests. Disabled if set to `0`. | integer | `600` |
| `--request-timeout` | Timeout (in seconds) for waiting to receive the entire HTTP request from the client. Disabled if set to `0`. Requests exceeding this timeout will be rejected with the code `HTTP 408`. | integer | `3600` |
| `--local-timezone` | Use local timezone for log timestamps | boolean | `false` |
| `--log`, `-g` | Path to a file where the server logs should be output. This does not affect output on the console. | string | |
| `--log-filters` | List of log filtering rules. See the [log filtering guide](../../guides/log-filters.md) for details. | array | |
| `--log-level` | The log level for the server logs. Supported values are `debug`, `info`, `warn`, or `error`. Combining two supported values using a colon (e.g. `warn:debug`) allows to set separate log levels for the console and file outputs, respectively. | string | `debug` |
| `--log-format` | The log format of the server logs. Supported values are `text`, `json`, or `pretty_json`. Setting the value to `json` disables colors. | string | `text` |
| `--log-no-colors` | Disable colors in the server log | boolean | `false` |
| `--log-timestamp` | Show timestamps in the server log | boolean | `false` |
| `--long-stacktrace` | Add long stack traces to log entries. Recommended for debugging only. | boolean | `false` |
| `--max-ipc-data-size` | Maximum byte size of IPC message objects. | integer | `1048576` (1MB) |
| `--max-ipc-topics` | Maximum number of IPC topics per session. | integer | `1000` |
| `--no-perms-check` | Skip various permission checks on the server startup | boolean | `false` |
| `--nodeconfig` | JSON configuration for registering Appium as a node with Selenium Grid 3 | object | |
| `--plugin` | Plugin-specific configuration. Keys should correspond to plugin package names | object | |
| `--plugins-import-chunk-size` | Maximum number of plugins that can be imported in parallel on server startup | number | `7` |
| `--port`, `-p` | Port to listen on | integer | `4723` |
| `--relaxed-security` | Allow all [insecure features](../../guides/security.md). Only use this if all clients are in a trusted network and could not potentially break out of the session sandbox. Specific features can be overridden by using `--deny-insecure`. | boolean | `false` |
| `--session-override` | Enable session override (clobbering) | boolean | `false` |
| `--shutdown-timeout` | Timeout (in milliseconds) for waiting on all active connections to close, when shutting down the server | number | `5000` |
| `--ssl-cert-path` | Absolute path to the `.cert` file if TLS is used. Must be provided together with `--ssl-key-path`. See the [SSL/TLS/SPDY Support guide](../../guides/tls.md) for details. | string | |
| `--ssl-key-path` | Absolute path to the `.key` file if TLS is used. Must be provided together with `--ssl-cert-path`. See the [SSL/TLS/SPDY Support guide](../../guides/tls.md) for details. | string | |
| `--strict-caps` | Prevent creation of new client sessions that use unsupported capabilities | boolean | `false` |
| `--tmp` | Absolute path to the directory used for temporary files | string | [`os.tmpdir()`](https://nodejs.org/api/os.html#ostmpdir) |
| `--use-drivers` | List of drivers to activate. By default, all installed drivers are activated. | array<string> | `[]` |
| `--use-plugins` | List of plugins to activate. By default, no plugins are activated. Set to `["all"]` to activate all installed plugins. | array<string> | `[]` |
| `--webhook`, `-G` | URL for an HTTP listener where the server logs should be output. This does not affect output on the console. A bare `host:port` is also accepted, which posts the logs to the root path over plain http; a value having neither a scheme nor a port falls back to `127.0.0.1:9003`. | string | |
| <div style="width:15em">Argument</div> | Description | Type | <div style="width:7em">Default</div> |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------------------------------------------------------- |
| `--address`, `-a` | IPv4/IPv6 address or a hostname to listen on | string | `0.0.0.0` |
| `--allow-insecure` | List of [insecure features](../../guides/security.md) that should be allowed in this server's sessions. Individual features can be overridden by `--deny-insecure`. Has no effect in combination with `--relaxed-security`. | array<string> | `[]` |
| `--allow-unknown-args` | Do not exit if unrecognized command-line arguments are passed to the server; ignore them instead. Useful when the Appium CLI is wrapped by external tooling that appends extra flags. | boolean | `false` |
| `--app-url-rules` | Rules that remote application URLs (e.g. in the `appium:app` capability) must satisfy before the server downloads them. See the [Restricting Remote App URLs](../../guides/security.md#restricting-remote-app-urls) guide for details. Can be a path to a JSON file or raw JSON. | object | |
| `--base-path`, `-pa` | Base path to use as the prefix for all webdriver routes running on the server | string | `""` |
| `--config` | Path to an [Appium configuration JSON file](../../guides/config.md) | string | |
| `--bidi-heartbeat-interval` | Interval (in seconds) between WebSocket pings sent to each [BiDi](../api/bidi.md) client. A connection that misses two consecutive pongs is terminated. Disabled if set to `0`. | integer | `15` |
| `--bidi-max-buffered-bytes` | Maximum number of bytes the server may keep buffered for a BiDi connection whose client is not reading fast enough. A connection that stays above the limit for longer than `--bidi-max-buffered-ms`, or exceeds twice the limit, is closed with the code `1013`. Disabled if set to `0`, which also turns off skipping of droppable events. | integer | `33554432` |
| `--bidi-max-buffered-ms` | Time (in milliseconds) a BiDi connection may stay above `--bidi-max-buffered-bytes` before it is closed. If set to `0`, the connection is closed as soon as the limit is exceeded. | integer | `30000` |
| `--default-capabilities`, `-dc` | Capabilities that will be used for each session, unless overridden by received capabilities. See [Default Capabilities](#default-capabilities) for how they are applied. | object | |
| `--deny-insecure` | List of [insecure features](../../guides/security.md) that should be disabled in this server's sessions. Since all insecure features are disabled by default, this argument has no effect without either `--allow-insecure` or `--relaxed-security`, and is applied after both. | array<string> | `[]` |
| `--driver` | Driver-specific configuration. Keys should correspond to driver package names | object | |
| `--drivers-import-chunk-size` | Maximum number of drivers that can be imported in parallel on server startup | number | `3` |
| `--keep-alive-timeout`, `-ka` | Timeout (in seconds) to use as both the keep-alive timeout and the connection timeout for all client requests. Disabled if set to `0`. | integer | `600` |
| `--request-timeout` | Timeout (in seconds) for waiting to receive the entire HTTP request from the client. Disabled if set to `0`. Requests exceeding this timeout will be rejected with the code `HTTP 408`. | integer | `3600` |
| `--local-timezone` | Use local timezone for log timestamps | boolean | `false` |
| `--log`, `-g` | Path to a file where the server logs should be output. This does not affect output on the console. | string | |
| `--log-filters` | List of log filtering rules. See the [log filtering guide](../../guides/log-filters.md) for details. | array | |
| `--log-level` | The log level for the server logs. Supported values are `debug`, `info`, `warn`, or `error`. Combining two supported values using a colon (e.g. `warn:debug`) allows to set separate log levels for the console and file outputs, respectively. | string | `info` |
| `--log-format` | The log format of the server logs. Supported values are `text`, `json`, or `pretty_json`. Setting the value to `json` disables colors. | string | `text` |
| `--log-no-colors` | Disable colors in the server log | boolean | `false` |
| `--log-timestamp` | Show timestamps in the server log | boolean | `false` |
| `--long-stacktrace` | Add long stack traces to log entries. Recommended for debugging only. | boolean | `false` |
| `--max-ipc-data-size` | Maximum byte size of IPC message objects. | integer | `1048576` (1MB) |
| `--max-ipc-topics` | Maximum number of IPC topics per session. | integer | `1000` |
| `--no-perms-check` | Skip various permission checks on the server startup | boolean | `false` |
| `--plugin` | Plugin-specific configuration. Keys should correspond to plugin package names | object | |
| `--plugins-import-chunk-size` | Maximum number of plugins that can be imported in parallel on server startup | number | `7` |
| `--port`, `-p` | Port to listen on | integer | `4723` |
| `--relaxed-security` | Allow all [insecure features](../../guides/security.md). Only use this if all clients are in a trusted network and could not potentially break out of the session sandbox. Specific features can be overridden by using `--deny-insecure`. | boolean | `false` |
| `--session-override` | Enable session override (clobbering) | boolean | `false` |
| `--shutdown-timeout` | Timeout (in milliseconds) for waiting on all active connections to close, when shutting down the server | number | `5000` |
| `--ssl-cert-path` | Absolute path to the `.cert` file if TLS is used. Must be provided together with `--ssl-key-path`. See the [SSL/TLS/SPDY Support guide](../../guides/tls.md) for details. | string | |
| `--ssl-key-path` | Absolute path to the `.key` file if TLS is used. Must be provided together with `--ssl-cert-path`. See the [SSL/TLS/SPDY Support guide](../../guides/tls.md) for details. | string | |
| `--tmp` | Absolute path to the directory used for temporary files | string | [`os.tmpdir()`](https://nodejs.org/api/os.html#ostmpdir) |
| `--use-drivers` | List of drivers to activate. By default, all installed drivers are activated. | array<string> | `[]` |
| `--use-plugins` | List of plugins to activate. By default, no plugins are activated. Set to `["all"]` to activate all installed plugins. | array<string> | `[]` |
| `--webhook`, `-G` | URL for an HTTP listener where the server logs should be output. This does not affect output on the console. A bare `host:port` is also accepted, which posts the logs to the root path over plain http; a value having neither a scheme nor a port falls back to `127.0.0.1:9003`. | string | |
### Default Capabilities
Capabilities set with `--default-capabilities` are added to the received capabilities before a
driver is matched. This is Appium's own defaulting behavior, not something defined by the W3C
WebDriver specification.
- A value the client sends in `alwaysMatch`, or in a given `firstMatch` candidate, takes precedence
over the server default
- Defaults fill missing keys in each `firstMatch` candidate separately. A value in one candidate
does not stop the default from being applied to another candidate
- A key sent in both `alwaysMatch` and `firstMatch` is still rejected by the usual capability
validation. Server defaults do not change that
For example, with these server defaults:
```json
{"appium:newCommandTimeout": 60}
```
and these received capabilities:
```json
{
"alwaysMatch": {"appium:deviceName": "Pixel"},
"firstMatch": [
{"platformName": "iOS", "appium:newCommandTimeout": 120},
{"platformName": "Android"}
]
}
```
the iOS candidate keeps `appium:newCommandTimeout` of `120`, and the Android candidate gets the
default `60`. The session uses the value from whichever candidate it is created with.
### Info Options
@@ -33,7 +33,7 @@ appium setup browser
Installs the following extensions for desktop application testing:
- Drivers: `mac2`[^1], `windows`[^2]
- Drivers: `mac2`[^1], `wincore`[^2]
- Plugins: `images`, `inspector`
#### Usage
@@ -29,12 +29,11 @@ Appium sessions.
These capabilities are used in the Appium server/base driver, but are optional, and may have a
default value.
| <div style="width:19em">Capability</div> | Description | Type | Default |
| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ------- |
| `webSocketUrl` | Toggle support of the WebDriver BiDi protocol | `boolean` | |
| `appium:eventTimings` (deprecated) | Toggle collection of [Event Timings](../../guides/event-timing.md). This capability is deprecated - please use the [`getLogEvents`](../api/appium.md#getlogevents) endpoint instead. | `boolean` | |
| `appium:newCommandTimeout` | Number of seconds the Appium server should wait for clients to send commands before stopping the session. A value of `0` disables the timeout. | `number` | `60` |
| `appium:printPageSourceOnFindFailure` | Toggle retrieval of the page source and its printing to the Appium log, whenever a request to find an element fails | `boolean` | |
| <div style="width:19em">Capability</div> | Description | Type | Default |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | ------- |
| `webSocketUrl` | Toggle support of the WebDriver BiDi protocol | `boolean` | |
| `appium:newCommandTimeout` | Number of seconds the Appium server should wait for clients to send commands before stopping the session. A value of `0` disables the timeout. | `number` | `60` |
| `appium:printPageSourceOnFindFailure` | Toggle retrieval of the page source and its printing to the Appium log, whenever a request to find an element fails | `boolean` | |
### Validated Capabilities
@@ -42,9 +41,9 @@ These capabilities are not directly used in the Appium server/base driver, but a
validation checks due to their relevance in other drivers. The actual handling of these
capabilities is optional and entirely driver-dependent.
| Capability | Validation |
| --------------------------------------------------- | ------------------------------------------------------------- |
| `platformVersion` | Must be `string` |
| `appium:app` | Must be `string`; empty values are ignored |
| `appium:fullReset` | Must be `boolean`; mutually exclusive with `appium:noReset` |
| `appium:noReset` | Must be `boolean`; mutually exclusive with `appium:fullReset` |
| Capability | Validation |
| ------------------------ | ------------------------------------------------------------- |
| `appium:platformVersion` | Must be `string` |
| `appium:app` | Must be `string`; empty values are ignored |
| `appium:fullReset` | Must be `boolean`; mutually exclusive with `appium:noReset` |
| `appium:noReset` | Must be `boolean`; mutually exclusive with `appium:fullReset` |
+2
View File
@@ -57,6 +57,7 @@ nav:
- reference/api/plugins.md
- ガイド:
- 移行:
- guides/migrating-3-to-4.md
- guides/migrating-2-to-3.md
- guides/migrating-1-to-2.md
- サーバ/ドライバの設定:
@@ -73,6 +74,7 @@ nav:
- guides/caps.md
- guides/settings.md
- guides/execute-methods.md
- guides/gestures.md
- guides/context.md
- guides/event-timing.md
- More Resources:
+2
View File
@@ -57,6 +57,7 @@ nav:
- reference/api/plugins.md
- 指南:
- 迁移:
- guides/migrating-3-to-4.md
- guides/migrating-2-to-3.md
- guides/migrating-1-to-2.md
- 服务器/驱动程序配置:
@@ -73,6 +74,7 @@ nav:
- guides/caps.md
- guides/settings.md
- guides/execute-methods.md
- guides/gestures.md
- guides/context.md
- guides/event-timing.md
- 更多资源:
+4 -4
View File
@@ -38,10 +38,10 @@ async function main() {
if (!semVersion) {
throw new Error(`Could not parse Appium version "${version}" as semver`);
}
const majMinVer = `${semVersion.major}.${semVersion.minor}`;
const vPrefixedMajVer = `v${semVersion.major}`;
for (const lang of LANGS) {
log.info(`Building docs for language '${lang}' and version ${majMinVer}`);
log.info(`Building docs for language '${lang}' and version ${vPrefixedMajVer}`);
const configFile = path.join(DOCS_DIR, `mkdocs-${lang}.yml`);
if (preview) {
await buildSite({
@@ -54,10 +54,10 @@ async function main() {
branch,
deployPrefix: path.join(basePrefix, lang),
remote,
deployVersion: majMinVer,
deployVersion: vPrefixedMajVer,
push,
alias: LATEST_ALIAS,
message: `docs(appium): auto-build docs for appium@${majMinVer}, language ${lang}`,
message: `docs(appium): build docs for appium@${vPrefixedMajVer}, language ${lang}`,
});
}
log.info(`Docs built`);
@@ -22,3 +22,8 @@ authors:
description: 'Appium Core Maintainer'
avatar: https://avatars.githubusercontent.com/u/7767781?v=4
slug: 'mykola'
eglitise:
name: 'Edgars Eglitis'
description: 'Appium Core Maintainer'
avatar: https://avatars.githubusercontent.com/u/37242620?v=4
slug: 'eglitise'
@@ -0,0 +1,41 @@
---
authors:
- eglitise
date: 2026-11-15
---
# 🚀 Appium 4
Appium 4 is here! A major milestone in the evolution of Appium, this release aims to strengthen
Appium's compliance with the W3C WebDriver protocol, modernize the codebase, and as usual, remove
deprecated legacy functionality.
<!-- more -->
While Appium 3 was primarily a cleanup release that removed a lot of deprecated endpoints, Appium 4
has a broader scope of changes. A few legacy endpoints have still been removed, but the key focus
this time has been on various behavioral adjustments for closer alignment with the W3C WebDriver
protocol specification, as well as full removal of support for drivers/plugins who relied on the
obsolete JSONWP/MJSONWP protocols.
The key breaking changes are as follows:
- Minimum Node.js version is raised to 22.22
- All Appium packages are now ESM-only
- The Windows driver is replaced with the WinCore driver
- Some deprecated endpoints have been removed (far fewer than in Appium 3!)
- The server flag for enabling CORS has been renamed
When it comes to new features, Appium 4 adds only a few, similarly to Appium 3:
- New server flag for controlling allowed app URLs in capabilities like `appium:app`
- The `install` and `update` CLI commands now gracefully handle any incompatibilities with the
extension's declared server version range
- The universal XML plugin's translation can now be toggled mid-session
As usual, the full [Appium 4 migration guide](../../guides/migrating-3-to-4.md) describes the full
extent of the important changes included in this major release.
The Appium team is incredibly grateful to all contributors who made this release possible!
Happy testing!
@@ -169,12 +169,6 @@ async createSession(w3cCaps) {
}
```
!!! 警告 “已废弃”
```
较老的驱动可能仍以最多四个参数定义 createSession,例如createSession(jwpCaps, reqCaps, w3cCaps, otherDriverData)。这种形式是已退役的 JSON Wire Protocol 的遗留产物——它要求前两个参数是期望能力和必须能力,而实际上只有第一个W3C 形式的参数被使用过。otherDriverData 参数同样已被废弃,与其他并行运行会话的协调请改用IPC(见下文"向同一会话中的插件发送消息")。新驱动应使用上面所示的单参数形式。
```
你要确保调用 `super.createSession`,以拿到会话 ID 以及处理过的能力(注意:能力同时也被设置在`this.caps` 上;此处仅修改局部变量 `caps`,这只改变用户在创建会话响应中看到的内容,没有其他效果)。
就是这样!中间的空白部分由你的驱动所需的启动逻辑来填充。
@@ -356,11 +350,7 @@ schema 的规则如下:
### 添加驱动脚本
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,
you can add a map of script names and JS files to the `scripts` field within your Appium extension
metadata. So let's say you've created a script in your project that lives in a `scripts` directory
in your project, named `driver-prebuild.js`. Then you could add a `scripts` field like this:
有时你可能希望驱动用户能够在会话上下文之外运行脚本(例如运行一个预先构建驱动某些部分的脚本)。为支持这一点,你可以在 Appium 扩展元数据的 `scripts` 字段中添加一个"脚本名 → JS 文件"的映射。假设你在项目的 `scripts` 目录下创建了一个名为 `driver-prebuild.js` 的脚本,那么可以像这样添加`scripts` 字段:
```json
{
@@ -370,20 +360,15 @@ in your project, named `driver-prebuild.js`. Then you could add a `scripts` fiel
}
```
Now, assuming your driver is named `mydriver`, users of your driver can run `appium driver run
mydriver prebuild`, and your script will execute.
假设你的驱动名为 `mydriver`,驱动用户就可以运行 `appium driver run mydriver prebuild`,你的脚本便会执行。
### Proxy commands to another WebDriver implementation
### 把命令代理到另一个 WebDriver 实现
A very common design architecture for Appium drivers is to have some kind of platform-specific
WebDriver implementation that the Appium driver interfaces with. For example, the Appium
UiAutomator2 driver interfaces with a special (Java-based) server running on the Android device. In
webview mode, it also interfaces with Chromedriver.
Appium 驱动一种非常常见的设计架构,是与某种平台专有的 WebDriver 实现对接。例如,Appium 的 UiAutomator2 驱动对接一个运行在 Android 设备上的特殊(基于 Java 的)服务器;在 webview 模式下,它还对接 Chromedriver。
If you find yourself in this situation, it is extremely easy to tell Appium that your driver is
just going to be proxying WebDriver commands straight to another endpoint.
如果你发现自己正处于这种情形,告诉 Appium"这个驱动只是把 WebDriver 命令直接代理转发到另一个端点"是极其简单的。
First, let Appium know that your driver _can_ proxy by implementing the `canProxy` method:
首先,实现 `canProxy` 方法,让 Appium 知道你的驱&#x52A8;_&#x53EF;&#x4EE5;_&#x4EE3;理:
```js
canProxy() {
@@ -391,8 +376,7 @@ canProxy() {
}
```
Next, tell Appium which WebDriver routes it should _not_ attempt to proxy (there often end up being
certain routes that you don't want to forward on):
接下来,告诉 Appium 哪些 WebDriver 路&#x7531;_&#x4E0D;&#x5E94;_&#x5C1D;试代理(通常总有一些路由是你不想转发出去的):
```js
getProxyAvoidList() {
@@ -402,14 +386,9 @@ getProxyAvoidList() {
}
```
The proxy avoidance list should be an array of arrays, where each inner array has an HTTP method as
its first member, and a regular expression as its second. If the regular expression matches the
route, then the route will not be proxied and instead will be handled by your driver. In this
example, we are avoiding proxying all `POST` routes that have the `appium` prefix.
禁止代理列表应是一个二维数组,每个内层数组的第一个成员是 HTTP 方法,第二个是正则表达式。如果正则表达式匹配某条路由,该路由就不会被代理,而是交由你的驱动处理。这个例子中,我们禁止代理所有带 `appium` 前缀的 `POST` 路由。
Next, we have to set up the proxying itself. The way to do this is to use a special class from
Appium called `WebDriverProxy`. You'll want to create a `WebDriverProxy` object using the details
required to connect to the remote server:
然后要设置代理本身。做法是使用 Appium 提供的特殊类 `WebDriverProxy`。你需要用连接远程服务器所需的详细信息创建 `WebDriverProxy` 对象:
```js
// import {WebDriverProxy} from 'appium/driver';
@@ -424,14 +403,9 @@ this.proxyReqRes = proxy.proxyReqRes.bind(proxy);
this.proxyCommand = proxy.command.bind(proxy);
```
Here we are creating a proxy object and assigning some of its methods to `this` under the names
`proxyReqRes` and `proxyCommand`. This is required for Appium to use the proxy, so don't forget
this step! The `WebDriverProxy` has a variety of other options which you can check out in the
source code as well.
这里我们创建了代理对象,并把它的部分方法以 `proxyReqRes` 和 `proxyCommand` 的名字挂到 `this`上。这是 Appium 使用代理的必要条件,千万别漏掉这一步! `WebDriverProxy` 还有许多其他选项,你可以在[源码](https://github.com/appium/appium/blob/master/packages/base-driver/lib/wd-proxy/proxy.ts)中查看。
Finally, we need a way to tell Appium when the proxy is active. For your driver it might always
be active, or it might only be active when in a certain context. You can define the logic as an
implementation of `proxyActive`:
最后,我们需要告诉 Appium 代理何时激活。对你的驱动来说,代理可能一直激活,也可能只在某个特定上下文中激活。你可以把这部分逻辑实现为 `proxyActive`:
```js
proxyActive() {
@@ -439,8 +413,7 @@ proxyActive() {
}
```
With those pieces in play, you won't have to reimplement anything that's already implemented by the
remote endpoint you're proxying to. Appium will take care of all the proxying for you.
有了这几块拼图,你就不必重新实现远程端点已经实现过的功能。所有的代理工作都会由 Appium 代劳。
### Proxy BiDi commands to another BiDi implementation
@@ -608,6 +581,12 @@ A couple notes about this system:
mode!
3. The `executeMethod` helper will reject with an error if a script name doesn't match one of the
script names defined as a command in `executeMethodMap`, or if there are missing parameters.
4. If your driver is written in TypeScript, declare the map `as const satisfies
ExecuteMethodMap<MyDriver>` (with `ExecuteMethodMap` imported from `@appium/types`). The
compiler then checks that each `command` names a method of your driver, and that the
`required`/`optional` params are consistent with that method's signature: the method must not
require a parameter which is listed as `optional` (or not listed at all), and must accept all
of the listed parameters.
One of the nice things about the Execute Method strategy is that methods implemented in this way
will be available via the classic or BiDi interfaces (since they will result in the same Appium
@@ -674,6 +653,36 @@ this.eventEmitter.emit('bidiEvent', {
Now, if the client has subscribed to the `system.cpu` event, it will be notified with the load
whenever the driver emits it.
#### Slow clients and high-rate events
Appium does not buffer events indefinitely for a client that does not read them. A connection
that keeps more than `--bidi-max-buffered-bytes` unsent for longer than `--bidi-max-buffered-ms`
is closed with the code `1013`, and connections that do not answer WebSocket pings (see
`--bidi-heartbeat-interval`) are terminated. Both only affect the offending connection.
Drivers that emit events at a high rate (e.g. media streams) can let Appium skip events for a
connection that is falling behind, instead of waiting for it to be closed. Add a `delivery` hint
to the event (it is never sent to clients; older Appium versions ignore it):
```js
this.eventEmitter.emit('bidiEvent', {
method: 'appium:media.units',
params: {track: 'video', units},
delivery: {policy: 'droppable', chain: 'video', syncPoint: startsWithKeyframe},
})
```
- `policy`: `reliable` (default) events are always sent, `droppable` ones may be skipped.
- `chain`: events of the same chain depend on each other. After one is skipped for a connection,
the following ones are skipped for it too, until an event with `syncPoint: true` (e.g. a keyframe)
arrives and the connection has caught up. Every connection resynchronizes independently.
Subscriptions are per session, not per connection, so Appium decides by the state of each
connection's buffer. To react to dropped events (e.g. to request a keyframe or lower the bitrate),
listen to `bidiBackpressure` on the same emitter. Its payload is `{method, chain?, state, dropped}`,
where `state` is `dropping` once the first connection starts skipping events (and again whenever a
sync point is skipped, so that you can request a new one) and `recovered` once the last one stops, and `dropped` is the largest number of events skipped for a single connection.
### Make itself aware of resources other concurrent drivers are using
Let's say your driver uses up some system resources, like ports. There are a few ways to make sure
@@ -681,55 +690,35 @@ that multiple simultaneous sessions don't use the same resources:
1. Have your users specify resource IDs via capabilities (`appium:driverPort` etc)
2. Just always use free resources (find a new random port for each session)
3. Have each driver express what resources it is using, then examine currently-used resources from
other drivers when a new session begins.
3. Have each running instance of your driver publish and subscribe to messages on a shared IPC
channel, so sessions can coordinate directly with one another.
!!! warning "Deprecated"
```
The `driverData`-based mechanism described below is deprecated. Prefer
[IPC](#send-messages-to-plugins-running-on-the-same-session) for coordinating resources across
concurrently-running sessions instead.
```
To support this third strategy, you can implement `get driverData` in your driver to return what
sorts of resources your driver is currently using, for example:
```js
get driverData() {
return {specialPort: 1234, specialFile: /path/to/file}
}
```
Now, when a new session is started on your driver, the `driverData` response from any other
simultaneously running drivers (of the same type) will also be included, as the last parameter of
the deprecated, multi-argument form of the `createSession` method:
```js
async createSession(jwpCaps, reqCaps, w3cCaps, driverData)
```
You can dig into this `driverData` array to see what resources other drivers are using to help
determine which ones you want to use for this particular session.
The per-session IPC channel described in Send messages to plugins running on the same
session is isolated per session, so it
can't be used for this: it doesn't let you talk to _other_ sessions of your driver. Instead,
construct and hold on to your own `AppiumIpc` instance (exported from `appium/driver.js`) at
module scope in your driver's package, for example as a memoized singleton. Since Node.js caches
modules, every instance of your driver loaded within the same Appium server process will share
that one `AppiumIpc` object, and can use it to publish and subscribe to topics across sessions —
the same way the per-session channel works, just not scoped to a single session. See
[xcuitest-driver's `session-claim-handler.ts`](https://github.com/appium/appium-xcuitest-driver/blob/master/lib/session-claim-handler.ts)
for a real example, which uses this technique to detect and resolve conflicting sessions targeting
the same device UDID.
!!! warning
```
Be careful here, since `driverData` is only passed between sessions of a single running Appium
server. There's nothing to stop a user from running multiple Appium servers and requesting your
driver simultaneously on each of them. In this case, you won't be able to ensure independence
of resources via `driverData`, so you might consider using file-based locking mechanisms or
something similar.
This only works for sessions running within the same Node.js process (i.e. the same Appium
server). It cannot coordinate sessions running on different Appium server processes; for that,
consider file-based locking or a similar out-of-process mechanism.
```
!!! warning
```
It's also important to note you will only receive `driverData` for other instances of *your*
driver. So unrelated drivers also running may still be using some system resources. In general
Appium doesn't provide any features for ensuring unrelated drivers don't interfere with one
another, so it's up to the drivers to allow users to specify resource locations or addresses to
avoid clashes.
Appium also doesn't provide any features for ensuring unrelated drivers don't interfere with
one another, so it's up to the drivers to allow users to specify resource locations or
addresses to avoid clashes.
```
### Log events to the Appium event timeline
@@ -880,10 +869,15 @@ export type IpcMessage<T> = {
There are some important things to keep in mind when using Appium's IPC feature:
- IPC is only available once `onIpcInit` has been called, at the end of the `createSession` flow.
It cannot be used statically or in `createSession` hooks
- In sum, IPC is only for use during a session (this is also to prevent drivers/plugins from
accessing or reading data sent on IPC channels in other sessions.)
- The `ipcSubscribe` method (and the IPC channel it subscribes to) is only available once
`onIpcInit` has been called, at the end of the `createSession` flow. It cannot be used statically
or in `createSession` hooks
- The channel that `ipcSubscribe` gives you access to is scoped to the current session, and is
shared only with the plugins active in that same session (this is also to prevent drivers/plugins
from accessing or reading data sent on IPC channels in other sessions.) To coordinate across
multiple concurrent sessions of your own driver instead, see Make itself aware of resources
other concurrent drivers are
using.
- The default max size of an IPC message is 1MB. This can be configured by the server-admin by
using the `--max-ipc-data-size` arg (value is a number in bytes).
- If a message exceeds the configured size, any call to `publish` methods will throw, so be
@@ -123,6 +123,11 @@ constructor(...args) {
这里的 `args` 参数是包含启动 Appium 服务器所用全部 CLI 参数的对象。
Appium creates a separate instance of your plugin for each session. The instance that handles
`createSession` also handles the later commands of that session, so state set in `createSession`
can be kept on `this`. If `createSession` fails, that instance is dropped. Commands that do not
belong to a session, such as `getStatus`, are handled by another instance which no session uses.
### 拦截并处理特定的 Appium 命令
这是 Appium 插件最常见的用法——修改或替换本应由当前驱动处理的一个或多个命令的执行。要覆盖默认的命令处理逻辑,你需要在类中实现与所要处理的 Appium 命令同名的 `async` 方法(和[驱动本身的实现方式](./build-drivers.md#implement-webdriver-classic-commands)完全一致)。想知道都有哪些命令名?它们定义在 Appium base driver 的
@@ -190,7 +195,9 @@ throw new errors.NoSuchElementError();
### 向 Appium 日志写消息
你当然可以随时用 `console.log`,但 Appium 为你提供了一个更贴心的日志器 `this.logger`(它有 `.info`、`.debug`、`.log`、`.warn`、`.error` 等不同日志级别的方法)。如果你想在插件上下文之外(比如脚本或辅助文件中)创建 Appium 日志器,也可以自行构造:
You can always use `console.log`, of course, but Appium provides a nice logger for you as
`this.log` (it has `.info`, `.debug`, `.warn`, `.error` methods on it for differing log
levels). 如果你想在插件上下文之外(比如脚本或辅助文件中)创建 Appium 日志器,也可以自行构造:
```js
import {logging} from 'appium/support';
@@ -354,7 +361,7 @@ async execute(next, driver, script, args) {
You probably don't normally need to update the Appium server object (which is an
[Express](https://expressjs.com/) server having already been
[configured](https://github.com/appium/appium/blob/master/packages/base-driver/lib/express/server.ts)
[configured](https://github.com/appium/appium/blob/master/packages/http-server/lib/server.ts)
in a variety of ways). 但你可以为服务器添加新的路由来支撑你的插件的需求。要更新服务器,你必须在类中实现 `static async updateServer` 方法。该方法接收三个参数:
- `expressApp`:Express app 对象
@@ -32,4 +32,6 @@ Appium server 已经提供了一种通过 [过滤](../guides/log-filters.md) 来
格式化过程会通过标准的 Node.js [util.format](https://nodejs.org/api/util.html#utilformatformat-args) API 完成。
- 在发送相应的服务器请求时,如果这个日志行被使用并且应该被掩码处理,请额外添加自定义请求头 `X-Appium-Is-Sensitive`,其值为 `1` 或 `true`(大小写不敏感)。如果没有这个请求头,上述日志值将不会被掩码处理。这样就可以根据扩展处理的具体请求来有条件地屏蔽日志记录;如果日志表达式位于公共部分,就可以在这里统一控制。
- While sending the appropriate server request, where this log line is used and should be masked,
add the custom header `X-Appium-Is-Sensitive` with its value set to `1`, `true` or `yes` (case-insensitive).
如果没有这个请求头,上述日志值将不会被掩码处理。这样就可以根据扩展处理的具体请求来有条件地屏蔽日志记录;如果日志表达式位于公共部分,就可以在这里统一控制。
+18 -16
View File
@@ -71,20 +71,13 @@ appium driver install safari
appium driver install uiautomator2
```
### [Windows](https://github.com/appium/appium-windows-driver)
!!! warning
```
Only the Node.js-based driver part is maintained by the Appium team. The server part
(WinAppDriver executable) is provided by Microsoft, but has not been maintained since 2022.
```
### [WinCore](https://appium.github.io/appium-wincore-driver)
- Target: Windows applications
- Mode: Native
```sh title="Install This Driver"
appium driver install windows
appium driver install wincore
```
### [XCUITest](https://appium.github.io/appium-xcuitest-driver/)
@@ -161,13 +154,6 @@ appium driver install --source=npm @itsmeaj/appium-linux-driver
### [NovaWindows](https://github.com/AutomateThePlanet/appium-novawindows-driver)
!!! info
```
This driver is recommended as a drop-in replacement for the partially unmaintained
[Windows driver](#windows)
```
- Target: Windows applications
- Mode: Native, Hybrid
- Supported by: Community / Automate The Planet
@@ -212,6 +198,22 @@ npm install appium-tizen-driver
appium driver install --source=npm appium-tizen-tv-driver
```
### [Windows (legacy)](https://github.com/appium/appium-windows-driver)
!!! warning
```
This driver relies on WinAppDriver, which has not been maintained since 2022, and is only
compatible with Appium 1-3. Use the [WinCore](#wincore) driver with Appium 4 and newer.
```
- Target: Windows applications
- Mode: Native
```sh title="Install This Driver"
appium driver install --source=npm appium-windows-driver
```
### [You.i Engine](https://github.com/YOU-i-Labs/appium-youiengine-driver)
!!! warning
@@ -114,6 +114,20 @@ Supported by: `@AppiumTestDistribution`
npm install -g appium-installer
```
### [BenchFleet Appium](https://github.com/benchfleet/benchfleet-appium)
BenchFleet Appium is a command-line tool for running existing Appium tests on real Android phones
connected to a [BenchFleet](https://benchfleet.com) Hub, a desktop app for managing many phones
(Pro or Team plan). For each phone, the Hub starts an Appium server with the UiAutomator2 driver.
The tool then runs your test command once per phone with that server's URL in `APPIUM_URL`, and
collects each phone's JUnit report. iOS and BenchFleet's cloud phones are not supported yet.
Supported by: `@benchfleet`
```sh title="Install This Tool"
npm install -g benchfleet-appium
```
### [Optics](https://github.com/mozarkai/optics-framework)
Optics is an open-source test automation framework that uses Appium to drive Android, iOS,
+1 -1
View File
@@ -99,4 +99,4 @@ The above configuration corresponds to the `--driver-xcuitest-webkit-debug-proxy
All properties are case-sensitive and will be in
[kebab-case](https://en.wikipedia.org/wiki/Naming_convention_(programming)#Delimiter-separated_words).
For example, `callback-port` is allowed, but `callbackPort` is not.
For example, `base-path` is allowed, but `basePath` is not.
+343
View File
@@ -0,0 +1,343 @@
---
title: Automating Gestures
---
Appium supports automating complex pointer, touch, key, and wheel interactions through the
W3C WebDriver [Perform Actions](../reference/api/webdriver.md#performactions) API
([W3C Specification](https://w3c.github.io/webdriver/#actions)). Alternatively, many drivers provide
platform-native gesture [Execute Methods](./execute-methods.md) for common interactions.
In the W3C Actions API, interactions are defined by creating one or more virtual input sources
(such as `pointer` with `pointerType: "touch"`, `key`, `wheel`, or `none`) and queuing a sequence
of synchronized ticks (`pointerMove`, `pointerDown`, `pointerUp`, `pause`). See the
[Selenium Actions API documentation](https://www.selenium.dev/documentation/webdriver/actions_api/)
for a general overview of input sources and tick synchronization.
Below are examples of common single-finger and multi-touch gestures implemented using the W3C
Actions API across client languages.
## Double Tap
Performs two quick touch taps at `(x, y)` with a short pause between them:
=== "JS (WebDriverIO)"
```js
await driver
.action('pointer', {parameters: {pointerType: 'touch'}})
.move({x: 200, y: 300, duration: 0})
.down()
.up()
.pause(100)
.down()
.up()
.perform();
```
=== "Java"
```java
PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");
Sequence doubleTap = new Sequence(finger, 1)
.addAction(finger.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), 200, 300))
.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()))
.addAction(new Pause(finger, Duration.ofMillis(100)))
.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
driver.perform(Collections.singletonList(doubleTap));
```
=== "Python"
```py
actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "finger"))
actions.w3c_actions.pointer_action.move_to_location(200, 300)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pointer_up()
actions.w3c_actions.pointer_action.pause(0.1)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pointer_up()
actions.perform()
```
=== "Ruby"
```rb
f1 = driver.action.add_pointer_input(:touch, 'finger')
f1.create_pointer_move(duration: 0, x: 200, y: 300, origin: :viewport)
f1.create_pointer_down(:left)
f1.create_pointer_up(:left)
f1.create_pause(0.1)
f1.create_pointer_down(:left)
f1.create_pointer_up(:left)
driver.perform_actions([f1])
```
=== "C#"
```csharp
var finger = new PointerInputDevice(PointerKind.Touch, "finger");
var doubleTap = new ActionSequence(finger, 0);
doubleTap.AddAction(finger.CreatePointerMove(CoordinateOrigin.Viewport, 200, 300, TimeSpan.Zero));
doubleTap.AddAction(finger.CreatePointerDown(MouseButton.Touch));
doubleTap.AddAction(finger.CreatePointerUp(MouseButton.Touch));
doubleTap.AddAction(finger.CreatePause(TimeSpan.FromMilliseconds(100)));
doubleTap.AddAction(finger.CreatePointerDown(MouseButton.Touch));
doubleTap.AddAction(finger.CreatePointerUp(MouseButton.Touch));
driver.PerformActions(new List<ActionSequence> { doubleTap });
```
## Long Press
Presses and holds a touch pointer at `(x, y)` for 1000ms before releasing:
=== "JS (WebDriverIO)"
```js
await driver
.action('pointer', {parameters: {pointerType: 'touch'}})
.move({x: 200, y: 300, duration: 0})
.down()
.pause(1000)
.up()
.perform();
```
=== "Java"
```java
PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");
Sequence longPress = new Sequence(finger, 1)
.addAction(finger.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), 200, 300))
.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
.addAction(new Pause(finger, Duration.ofMillis(1000)))
.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
driver.perform(Collections.singletonList(longPress));
```
=== "Python"
```py
actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "finger"))
actions.w3c_actions.pointer_action.move_to_location(200, 300)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pause(1.0)
actions.w3c_actions.pointer_action.pointer_up()
actions.perform()
```
=== "Ruby"
```rb
f1 = driver.action.add_pointer_input(:touch, 'finger')
f1.create_pointer_move(duration: 0, x: 200, y: 300, origin: :viewport)
f1.create_pointer_down(:left)
f1.create_pause(1.0)
f1.create_pointer_up(:left)
driver.perform_actions([f1])
```
=== "C#"
```csharp
var finger = new PointerInputDevice(PointerKind.Touch, "finger");
var longPress = new ActionSequence(finger, 0);
longPress.AddAction(finger.CreatePointerMove(CoordinateOrigin.Viewport, 200, 300, TimeSpan.Zero));
longPress.AddAction(finger.CreatePointerDown(MouseButton.Touch));
longPress.AddAction(finger.CreatePause(TimeSpan.FromMilliseconds(1000)));
longPress.AddAction(finger.CreatePointerUp(MouseButton.Touch));
driver.PerformActions(new List<ActionSequence> { longPress });
```
## Drag and Drop / Swipe
Moves a touch pointer from `(200, 600)` to `(200, 200)` over 600ms:
=== "JS (WebDriverIO)"
```js
await driver
.action('pointer', {parameters: {pointerType: 'touch'}})
.move({x: 200, y: 600, duration: 0})
.down()
.pause(100)
.move({x: 200, y: 200, duration: 600})
.up()
.perform();
```
=== "Java"
```java
PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");
Sequence dragAndDrop = new Sequence(finger, 1)
.addAction(finger.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), 200, 600))
.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
.addAction(new Pause(finger, Duration.ofMillis(100)))
.addAction(finger.createPointerMove(Duration.ofMillis(600), PointerInput.Origin.viewport(), 200, 200))
.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
driver.perform(Collections.singletonList(dragAndDrop));
```
=== "Python"
```py
actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "finger"))
actions.w3c_actions.pointer_action.move_to_location(200, 600)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.pause(0.1)
actions.w3c_actions.pointer_action.move_to_location(200, 200)
actions.w3c_actions.pointer_action.pointer_up()
actions.perform()
```
=== "Ruby"
```rb
f1 = driver.action.add_pointer_input(:touch, 'finger')
f1.create_pointer_move(duration: 0, x: 200, y: 600, origin: :viewport)
f1.create_pointer_down(:left)
f1.create_pause(0.1)
f1.create_pointer_move(duration: 0.6, x: 200, y: 200, origin: :viewport)
f1.create_pointer_up(:left)
driver.perform_actions([f1])
```
=== "C#"
```csharp
var finger = new PointerInputDevice(PointerKind.Touch, "finger");
var dragAndDrop = new ActionSequence(finger, 0);
dragAndDrop.AddAction(finger.CreatePointerMove(CoordinateOrigin.Viewport, 200, 600, TimeSpan.Zero));
dragAndDrop.AddAction(finger.CreatePointerDown(MouseButton.Touch));
dragAndDrop.AddAction(finger.CreatePause(TimeSpan.FromMilliseconds(100)));
dragAndDrop.AddAction(finger.CreatePointerMove(CoordinateOrigin.Viewport, 200, 200, TimeSpan.FromMilliseconds(600)));
dragAndDrop.AddAction(finger.CreatePointerUp(MouseButton.Touch));
driver.PerformActions(new List<ActionSequence> { dragAndDrop });
```
## Pinch and Zoom (Multi-Touch)
Uses two concurrent `touch` pointer sequences (`finger1` and `finger2`) moving apart to zoom in (or toward each other to pinch):
=== "JS (WebDriverIO)"
```js
await driver.performActions([
{
type: 'pointer',
id: 'finger1',
parameters: {pointerType: 'touch'},
actions: [
{type: 'pointerMove', duration: 0, x: 200, y: 400},
{type: 'pointerDown', button: 0},
{type: 'pause', duration: 100},
{type: 'pointerMove', duration: 500, x: 200, y: 200},
{type: 'pointerUp', button: 0},
],
},
{
type: 'pointer',
id: 'finger2',
parameters: {pointerType: 'touch'},
actions: [
{type: 'pointerMove', duration: 0, x: 200, y: 450},
{type: 'pointerDown', button: 0},
{type: 'pause', duration: 100},
{type: 'pointerMove', duration: 500, x: 200, y: 650},
{type: 'pointerUp', button: 0},
],
},
]);
```
=== "Java"
```java
PointerInput finger1 = new PointerInput(PointerInput.Kind.TOUCH, "finger1");
Sequence seq1 = new Sequence(finger1, 1)
.addAction(finger1.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), 200, 400))
.addAction(finger1.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
.addAction(new Pause(finger1, Duration.ofMillis(100)))
.addAction(finger1.createPointerMove(Duration.ofMillis(500), PointerInput.Origin.viewport(), 200, 200))
.addAction(finger1.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
PointerInput finger2 = new PointerInput(PointerInput.Kind.TOUCH, "finger2");
Sequence seq2 = new Sequence(finger2, 1)
.addAction(finger2.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), 200, 450))
.addAction(finger2.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
.addAction(new Pause(finger2, Duration.ofMillis(100)))
.addAction(finger2.createPointerMove(Duration.ofMillis(500), PointerInput.Origin.viewport(), 200, 650))
.addAction(finger2.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
driver.perform(Arrays.asList(seq1, seq2));
```
=== "Python"
```py
action_builder = ActionBuilder(driver)
finger1 = action_builder.add_pointer_input(interaction.POINTER_TOUCH, "finger1")
finger2 = action_builder.add_pointer_input(interaction.POINTER_TOUCH, "finger2")
finger1.create_pointer_move(duration=0, x=200, y=400)
finger1.create_pointer_down(button=MouseButton.LEFT)
finger1.create_pause(0.1)
finger1.create_pointer_move(duration=500, x=200, y=200)
finger1.create_pointer_up(button=MouseButton.LEFT)
finger2.create_pointer_move(duration=0, x=200, y=450)
finger2.create_pointer_down(button=MouseButton.LEFT)
finger2.create_pause(0.1)
finger2.create_pointer_move(duration=500, x=200, y=650)
finger2.create_pointer_up(button=MouseButton.LEFT)
action_builder.perform()
```
=== "Ruby"
```rb
f1 = driver.action.add_pointer_input(:touch, 'finger1')
f1.create_pointer_move(duration: 0, x: 200, y: 400, origin: :viewport)
f1.create_pointer_down(:left)
f1.create_pause(0.1)
f1.create_pointer_move(duration: 0.5, x: 200, y: 200, origin: :viewport)
f1.create_pointer_up(:left)
f2 = driver.action.add_pointer_input(:touch, 'finger2')
f2.create_pointer_move(duration: 0, x: 200, y: 450, origin: :viewport)
f2.create_pointer_down(:left)
f2.create_pause(0.1)
f2.create_pointer_move(duration: 0.5, x: 200, y: 650, origin: :viewport)
f2.create_pointer_up(:left)
driver.perform_actions([f1, f2])
```
=== "C#"
```csharp
var finger1 = new PointerInputDevice(PointerKind.Touch, "finger1");
var seq1 = new ActionSequence(finger1, 0);
seq1.AddAction(finger1.CreatePointerMove(CoordinateOrigin.Viewport, 200, 400, TimeSpan.Zero));
seq1.AddAction(finger1.CreatePointerDown(MouseButton.Touch));
seq1.AddAction(finger1.CreatePause(TimeSpan.FromMilliseconds(100)));
seq1.AddAction(finger1.CreatePointerMove(CoordinateOrigin.Viewport, 200, 200, TimeSpan.FromMilliseconds(500)));
seq1.AddAction(finger1.CreatePointerUp(MouseButton.Touch));
var finger2 = new PointerInputDevice(PointerKind.Touch, "finger2");
var seq2 = new ActionSequence(finger2, 0);
seq2.AddAction(finger2.CreatePointerMove(CoordinateOrigin.Viewport, 200, 450, TimeSpan.Zero));
seq2.AddAction(finger2.CreatePointerDown(MouseButton.Touch));
seq2.AddAction(finger2.CreatePause(TimeSpan.FromMilliseconds(100)));
seq2.AddAction(finger2.CreatePointerMove(CoordinateOrigin.Viewport, 200, 650, TimeSpan.FromMilliseconds(500)));
seq2.AddAction(finger2.CreatePointerUp(MouseButton.Touch));
driver.PerformActions(new List<ActionSequence> { seq1, seq2 });
```
-59
View File
@@ -117,62 +117,3 @@ hub, you'll be able to send all your Appium traffic via the single hub endpoint
And of course, you're able to link up Appium servers and nodes running on different machines in
your network to form a larger grid.
## Using Selenium Grid 3
It is possible to register your Appium server with a local [Selenium Grid 3](https://www.selenium.dev/documentation/legacy/selenium_3/grid_3/)
([setup docs](https://www.selenium.dev/documentation/legacy/grid_3/setting_up_your_own_grid/)) instance by using the
`--nodeconfig` server argument.
```bash
appium server --nodeconfig /path/to/nodeconfig.json --base-path=/wd/hub
```
In the referenced config file you have to define the `browserName`, `version` and `platform`
capabilities and based on these parameters the grid will re-direct your test to the right device.
You will also need to configure your host details and the Selenium Grid details. For a full list of
all parameters and descriptions see
[here](https://www.selenium.dev/documentation/legacy/selenium_3/grid_setup/).
Once you start the Appium server it will register with the grid, and you will see your device on
the grid console page:
`http://**\<grid-ip-address\>**:**\<grid-port\>**/grid/console`
### Example Grid Node Configuration JSON
```json
{
"capabilities":
[
{
"browserName": "<e.g._iPhone5_or_iPad4>",
"version":"<version_of_iOS_e.g._7.1>",
"maxInstances": 1,
"platform":"<platform_e.g._MAC_or_ANDROID>"
}
],
"configuration":
{
"cleanUpCycle":2000,
"timeout":30000,
"proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
"url":"http://<host_name_appium_server_or_ip-address_appium_server>:<appium_port>/wd/hub",
"host": "<host_name_appium_server_or_ip-address_appium_server>",
"port": <appium_port>,
"maxSession": 1,
"register": true,
"registerCycle": 5000,
"hubPort": <grid_port>,
"hubHost": "<Grid_host_name_or_grid_ip-address>",
"hubProtocol": "<Protocol_of_Grid_defaults_to_http>"
}
}
```
If `url`, `host`, and `port` are not given, the config will be auto updated to point to
`localhost:<appium-port>`.
If your Appium server is running on a different machine to your Selenium Grid server, make sure you
use an external name/IP address in your `host` and `url` configuration; `localhost` and `127.0.0.1`
will prevent Selenium Grid from connecting correctly.
@@ -31,12 +31,6 @@ installing it only installs the core Appium server, without any drivers.
When it comes to installing Appium 2 drivers, there are several approaches you can take:
- Add the `--drivers` flag when installing Appium, for example:
```bash
npm i -g appium --drivers=xcuitest,uiautomator2
```
- Use the [Appium Extension CLI](../reference/cli/extensions.md), for example:
```bash
@@ -227,8 +221,12 @@ and [Mobile JSON Wire Protocol](https://github.com/SeleniumHQ/mobile-spec/blob/m
(MJSONWP) were used instead.
In Appium 1, all of these protocols were supported, so that older Selenium/Appium clients could
still communicate with newer Appium servers. Appium 2 removes support for JSONWP/MJSONWP and is now
only compatible with the W3C WebDriver Protocol.
still communicate with newer Appium servers. Appium 2 removes support for JSONWP/MJSONWP (including
legacy `TouchAction` and `MultiAction` endpoints) and is now only compatible with the W3C WebDriver
Protocol. Multi-touch and pointer gestures should be performed using the W3C
[Perform Actions](../reference/api/webdriver.md#performactions) API (see the
[Automating Gestures](./gestures.md) guide) or driver-specific
[Execute Methods](./execute-methods.md).
!!! info "Actions Needed"
@@ -0,0 +1,649 @@
---
title: Migrating to Appium 4
---
This document is a guide for those who are using Appium 3 and would like to upgrade to Appium 4.
It contains a list of breaking changes (including behavioral fixes), as well as suggestions for
handling them.
Appium 3 was largely focused on cleaning up old endpoints, whereas Appium 4 includes a wider range
of changes, including closer alignment to W3C WebDriver protocol requirements, removal of
deprecated items not limited to endpoints, and general modernizing of the codebase.
## Installation
The installation method for Appium 4 remains the same as for Appium 3. If you want to upgrade, you
can simply install Appium 4 on top of your existing installation:
```bash
# optional: `appium setup reset`
npm install -g appium
```
## Breaking Changes
### Node 22.22+ Required
Appium 3 required a Node.js version in the range `^20.19.0 || ^22.12.0 || >=24.0.0`. Appium 4 drops
Node 20 and bumps the required range to `^22.22.2 || ^24.15.0 || >=26.0.0`. The minimum `npm`
version remains unchanged.
!!! info "Actions Needed"
Upgrade Node.js to `v22.22.2` or newer
### ESM-Only
Every package in the Appium monorepo (`appium` and its dependents) is now published as ESM-only,
with no CommonJS build. `require()` no longer works for these packages.
!!! info "Actions Needed"
Import Appium packages using ESM `import` syntax, or use dynamic `import()` from CommonJS code
### JSONWP/MJSONWP Internals Removed
The release of Appium 2 removed general support for the obsolete JSONWP and MJSONWP protocols,
though some Appium-related packages using JSONWP/MJSONWP under the hood could still continue to
function.
Appium 4 removes most of the remaining internal code that supported these protocols, which means
that drivers that still relied on these protocols are no longer compatible with Appium 4. Most
notably, this includes the Windows driver ([see dedicated section below](#windows-driver-replaced-by-wincore-driver)). All other official drivers rely on the W3C protocol and are not affected by this change.
Despite this, Appium 4 does retain temporary support for a select few JSONWP/MJSONWP endpoints (see
[Deprecated Endpoints Removed](#deprecated-endpoints-removed)).
For extension developers, a more detailed breakdown is available in the Developer-Facing Changes
section below.
!!! info "Actions Needed"
Migrate to drivers that support the W3C WebDriver protocol
### Windows Driver Replaced by WinCore Driver
As part of [dropping support for the deprecated JSONWP and MJSONWP protocols](#jsonwpmjsonwp-support-fully-removed),
Appium 4 is no longer compatible with the Windows driver ([`appium-windows-driver`](https://github.com/appium/appium-windows-driver)),
since the driver cannot support the standard W3C WebDriver protocol. As a result, the
`appium driver install windows` CLI command also no longer works.
Its official replacement is the WinCore driver ([`appium-wincore-driver`](https://github.com/appium/appium-wincore-driver)),
which can be installed using the new `appium driver install wincore` command. Since the WinCore
driver is also compatible with Appium 3, you can safely migrate from the Windows driver while
remaining on Appium 3 - though note that the installation shortcut is only available since Appium 4.
!!! info "Actions Needed"
If you currently use the Windows driver with Appium 3, you can migrate as follows:
1. Install `appium-wincore-driver` v3: `appium driver install --source=npm appium-wincore-driver@3`
2. Migrate your tests to use the WinCore driver
3. Uninstall the Windows driver: `appium driver uninstall windows`
4. Upgrade to Appium 4
5. Update the WinCore driver to its Appium 4 version: `appium driver update wincore --unsafe`
### Deprecated Endpoints Removed
Similarly to Appium 3, Appium 4 also removes several previously deprecated server endpoints, all of
which belong to the obsolete JSONWP/MJSONWP protocols. Compared to Appium 3, this cleanup is much
smaller (12 removed endpoints total, compared to 98 for Appium 3).
All removed endpoints are listed below, along with their replacement endpoints or driver-specific
execute methods:
- `GET /session/:sessionId`
- :octicons-arrow-right-24: [`GET /session/:sessionId/appium/capabilities`](../reference/api/appium.md#getappiumsessioncapabilities) (for capabilities)
- :octicons-arrow-right-24: [`GET /session/:sessionId/appium/events`](../reference/api/appium.md#getlogevents) (for event timings)
- `POST /session/:sessionId/ime/activate`
- :octicons-check-24: Moved to [UiAutomator2](https://appium.github.io/appium-uiautomator2-driver/)/[Espresso](https://appium.github.io/appium-espresso-driver/) drivers
- `GET /session/:sessionId/ime/activated`
- :octicons-check-24: Moved to UiAutomator2/Espresso drivers
- `GET /session/:sessionId/ime/active_engine`
- :octicons-check-24: Moved to UiAutomator2/Espresso drivers
- `GET /session/:sessionId/ime/available_engines`
- :octicons-check-24: Moved to UiAutomator2/Espresso drivers
- `POST /session/:sessionId/ime/deactivate`
- :octicons-check-24: Moved to UiAutomator2/Espresso drivers
- `GET /session/:sessionId/location`
- :octicons-check-24: Moved to [XCUITest](https://appium.github.io/appium-xcuitest-driver/) driver
- :octicons-arrow-right-24: `mobile: getGeolocation` (UiAutomator2/Espresso drivers)
- :octicons-arrow-right-24: `mobile: getSimulatedLocation` (XCUITest driver)
- `POST /session/:sessionId/location`
- :octicons-check-24: Moved to UiAutomator2/Espresso/XCUITest drivers
- :octicons-arrow-right-24: `mobile: setGeolocation` (UiAutomator2/Espresso drivers)
- :octicons-arrow-right-24: `mobile: setSimulatedLocation` (XCUITest driver)
- `GET /session/:sessionId/network_connection`
- :octicons-check-24: Moved to UiAutomator2/Espresso drivers
- :octicons-arrow-right-24: `mobile: getConnectivity` (UiAutomator2/Espresso drivers)
- `POST /session/:sessionId/network_connection`
- :octicons-check-24: Moved to UiAutomator2/Espresso drivers
- :octicons-arrow-right-24: `mobile: setConnectivity` (UiAutomator2/Espresso drivers)
- `POST /session/:sessionId/receive_async_response`
- :octicons-arrow-right-24: [`POST /session/:sessionId/execute/async`](../reference/api/webdriver.md#executeasync)
- `GET /session/:sessionId/element/:elementId`
- :octicons-no-entry-24: JSONWP protocol command stub with no direct replacement
#### Remaining Deprecations
There are 7 more deprecated endpoints that are intentionally _not_ removed in Appium 4. They are
the last remaining JSONWP/MJSONWP endpoints supported by Appium, and are listed in the
[JSONWP](../reference/api/jsonwp.md) and [MJSONWP](../reference/api/mjsonwp.md) reference pages.
These endpoints are kept due to their common usage (for context management), and their deprecation
being somewhat recent. All of them are therefore planned to be removed in the next major Appium
version, in order to give users time to migrate to their replacements.
!!! info "Actions Needed"
Check your Appium client documentation for the affected methods, and adjust your code to use
their replacements
### `--allow-cors` Flag Renamed
In Appium 3, the `--allow-cors` server argument was the only feature flag not integrated with
Appium's default [insecure feature flag mechanism](./security.md). Appium 4 removes this argument
and replaces it with the `cors` insecure feature name. This means the feature can now be controlled
using the `--allow-insecure`, `--deny-insecure` and `--relaxed-security` flags.
Similarly to the `session_discovery` feature, the `cors` feature must also be prefixed with the
wildcard (`*`) symbol.
!!! info "Actions Needed"
Replace `--allow-cors` with `--allow-insecure=*:cors` or `--relaxed-security`
### Default Log Level Set to Info
The default logging level for server logs has been changed from `debug` to `info`. Debug-level
logging is very verbose and mostly only useful for troubleshooting.
!!! info "Actions Needed"
Pass `--log-level debug` explicitly if you rely on the previous verbosity
### CLI Command Output Streams Split
In Appium 3, all non-JSON output of Appium's CLI commands (`driver`/`plugin`/`setup`, but not
`server`) was written to `stderr`. Appium 4 now writes `log`/`ok`/`info`/`warn` level messages of
these commands to `stdout`, while `error` level output remains in `stderr`.
The log output of the server itself (the `server` command) is unaffected, since it already split
streams this way.
!!! info "Actions Needed"
If you use scripts that capture non-JSON output of `driver`/`plugin`/`setup` commands, make
sure they read from the correct stream
### SPDY/HTTP2 No Longer Supported
In Appium 3, the server could be launched with SSL/TLS, which enabled support for the SPDY and
HTTP/2 protocols. This functionality relied on the unmaintained `spdy` package. Appium 4 replaces
this package with Node's native `https` module, which only supports plain HTTPS (HTTP/1.1).
!!! info "Actions Needed"
Clients relying on SPDY or HTTP/2 multiplexing against Appium's TLS listener must switch to
plain HTTPS (HTTP/1.1) or use a proxy
### Selenium Grid 3 Support Removed
Support for Selenium Grid 3 hub has been removed, along with its `--nodeconfig` server
argument/config file property. Selenium Grid 4 remains supported.
!!! info "Actions Needed"
If you relied on Grid 3 registration, use the [Selenium Grid 4 relay feature](./grid.md) instead
### Post-Install Script Removed
Appium 2 and 3 supported a postinstall hook that allowed for installation of drivers/plugins
together with the Appium server itself:
```
npm install -g appium --drivers=... --plugins=...
```
Since postinstall hooks are a supply-chain security risk, and newer versions of `npm` disable them
by default, this hook has been removed in Appium 4.
!!! info "Actions Needed"
If you install drivers/plugins using the postinstall hook, migrate to Appium's
[`install`](../reference/cli/extensions.md#install) command, or declare extensions in your
project's `package.json` file
### Event Timings Capability Removed
In Appium 3, the `appium:eventTimings` capability could be set to `true` in order to include event
timing information in the response of the `GET /session/:sessionId` endpoint. Since Appium 4
removes this endpoint (see [Deprecated Endpoints Removed](#deprecated-endpoints-removed)), the
capability became obsolete, and has also been removed.
!!! info "Actions Needed"
Remove any instances of the `appium:eventTimings` capability, and instead use the [getLogEvents](../reference/api/appium.md#getlogevents) endpoint to retrieve event timings
### Unused Server Arguments Removed
The following server arguments have had no effect for a long time and have been removed, along with
their equivalents in the configuration file:
- `--callback-address` (`-ca`)
- `--callback-port` (`-cp`)
- `--debug-log-spacing`
- `--shell`
- `--strict-caps`
- `--trace-dir`
Passing any of them on the command line now fails with an unrecognized argument error (unless
[`--allow-unknown-args`](../reference/cli/server.md) is set), and config files containing them
fail schema validation.
!!! info "Actions Needed"
Remove these arguments from startup scripts and config files
## Behavior Fixes
This is a list of smaller changes that are positioned as fixes, rather than removal of existing
functionality, and may or may not be breaking depending on your usecase. The majority of changes
are related to alignment with the W3C WebDriver specification, and should not generally require
any user action.
### Session Lifecycle
- If a successfully created session fails initialization, Appium now attempts to delete the newly
created session and removes its registration while preserving the original initialization error
([#22873](https://github.com/appium/appium/pull/22873))
- The new command idle timeout (`appium:newCommandTimeout`) now only starts after finishing the
setup of initial settings and BiDi responses, preventing a session from expiring during
initialization ([#22881](https://github.com/appium/appium/pull/22881))
- If the new command idle timeout expires and the session deletion process starts, any driver
cleanup failures are now logged, instead of becoming an unhandled rejection that can terminate
the server and unrelated sessions ([#22964](https://github.com/appium/appium/pull/22964))
- Upon session deletion, any commands still waiting in the command queue are now rejected with HTTP
`404` / `invalid session id`, instead of remaining pending indefinitely
([#22874](https://github.com/appium/appium/pull/22874))
### Capabilities
- Names of standard WebDriver capabilities must now be case-sensitive (e.g. `platformName`, not
`PlatformName`). Handling of the _values_ of these capabilities, as well as names of prefixed
capabilities (e.g. `appium:app`), remains unchanged
([#22976](https://github.com/appium/appium/pull/22976))
- Malformed capability containers and parse failures now return HTTP `400` / `invalid argument`,
instead of HTTP `500` / `session not created`
([#22977](https://github.com/appium/appium/pull/22977))
- Top-level `null` capabilities are omitted before validation and merging, avoiding false
duplicate-key errors. Nested nulls, such as `timeouts: {script: null}`, are preserved
([#22975](https://github.com/appium/appium/pull/22975))
- Session settings provided inside `appium:options` are now honored
([#22882](https://github.com/appium/appium/pull/22882))
- The standard `timeouts` capability now correctly initializes BaseDriver's timeout state using
the same value checks as the [Set Timeouts](../reference/api/webdriver.md#timeouts) endpoint.
Backend handling remains driver-specific ([#22983](https://github.com/appium/appium/pull/22983))
- Setting both `appium:noReset` and `appium:fullReset` to `true` now returns HTTP `500` /
`session not created` instead of a generic error, and no longer leaves partially initialized
session state behind ([#22861](https://github.com/appium/appium/pull/22861),
[#22870](https://github.com/appium/appium/pull/22870))
- Setting `appium:newCommandTimeout` to `null`, a blank string, or a non-finite numeric value is
now ignored (keeping the default timeout value), instead of causing the timeout to be silently
disabled ([#22815](https://github.com/appium/appium/pull/22815),
[#23103](https://github.com/appium/appium/pull/23103)). Other invalid types, such as negative
numbers or nonnumeric strings, still fail capability validation
- Percent-encoded credentials in `appium:app` URLs are now decoded once before Basic authentication,
and complete HTTP-compressed downloads are no longer rejected if the decompressed file size
differs from `Content-Length` ([#22887](https://github.com/appium/appium/pull/22887),
[#22886](https://github.com/appium/appium/pull/22886))
- Setting `firstMatch` to an empty array (`[]`) is now rejected with HTTP `400` /
`invalid argument`, instead of being silently replaced with a single empty entry
([#22860](https://github.com/appium/appium/pull/22860))
- Every `firstMatch` candidate is now validated and merged before selection. Invalid supplied values
or duplicate keys in any candidate reject the request, even if another candidate could match;
missing required driver capabilities and unsupported platforms still allow matching to continue
([#22982](https://github.com/appium/appium/pull/22982))
- Default capabilities (which can be set using `--default-capabilities`) are now applied to each
individual `firstMatch` candidate separately. Values set in `alwaysMatch` or the current
candidate still take precedence ([#22988](https://github.com/appium/appium/pull/22988)). See
[Default Capabilities](../reference/cli/server.md#default-capabilities) for an example.
- Session settings are now applied from the selected `firstMatch` candidate, instead of potentially
being overridden by later unselected candidates. Defaults and `alwaysMatch` settings are still
applied first ([#22882](https://github.com/appium/appium/pull/22882))
- Values of the standard `timeouts` capability are now also validated in `alwaysMatch` and every
`firstMatch` candidate ([#23062](https://github.com/appium/appium/pull/23062)). A malformed
timeout object or invalid standard timeout value is rejected with HTTP `400` /
`invalid argument`, even if an earlier `firstMatch` candidate could match. Top-level
`timeouts: null` is still omitted, nested null timeout values are preserved, and unknown timeout
properties are ignored for validation
### HTTP Responses
- All WebDriver HTTP responses now include the `Cache-Control: no-cache` header. Caches must
revalidate these responses before reusing them
([#22971](https://github.com/appium/appium/pull/22971))
- Any WebDriver error `data` (e.g. alert text) is now preserved in driver and proxy responses
([#22974](https://github.com/appium/appium/pull/22974))
- The body of any `POST` command now has to be a JSON object; requests where the body is empty or
set to an empty JSON array (`[]`) return HTTP `400` with `invalid argument`
([#23007](https://github.com/appium/appium/pull/23007)). A value of `{}` is still accepted,
including commands that take no parameters. Routes that set `payloadParams.wrap` may still accept
an empty array
- `GET` requests to the server root route (e.g. `GET /` for a default server base path) now return
HTTP `404` / `unknown command`, instead of Express's HTML 404 page. Extensions can still register
their own root route ([#22969](https://github.com/appium/appium/pull/22969))
- `HEAD` requests to any `GET` command URL now return HTTP `405` without executing the `GET`
command. Custom server routes and `HEAD` request handlers retain their behavior
([#22992](https://github.com/appium/appium/pull/22992))
- Driver commands rejecting with `null` or `undefined` now return HTTP `500` / `unknown error`,
instead of causing the error handler itself to fail
([#22869](https://github.com/appium/appium/pull/22869))
- `TimeoutError` and `ScriptTimeoutError` now map to HTTP `500` instead of HTTP `408`
([#22686](https://github.com/appium/appium/pull/22686))
- A `detached shadow root` error is now preserved as HTTP `404`, instead of being converted to HTTP
`500` / `unknown error` ([#22968](https://github.com/appium/appium/pull/22968))
### Specific Endpoints
- [New Session](../reference/api/webdriver.md#createsession): now raises the `session not created`
error instead of `unknown error` if no installed driver matches the requested platform/automation
combination, or the matching driver cannot be loaded or does not export its class. Validation of
missing `platformName`/`appium:automationName` is unchanged
([#22970](https://github.com/appium/appium/pull/22970))
- [Get Timeouts](../reference/api/webdriver.md#gettimeouts): now returns `script` and `pageLoad` in
addition to the existing `implicit` and Appium-specific `command` values
([#22776](https://github.com/appium/appium/pull/22776))
- [Set Timeouts](../reference/api/webdriver.md#timeouts): `script`, `pageLoad`, and `implicit` now
only accept null or integer values; strings and fractions return HTTP `400` / `invalid argument`
([#22961](https://github.com/appium/appium/pull/22961))
- Set Timeouts: `null` values now correctly disable the specified timeout
([#22961](https://github.com/appium/appium/pull/22961))
- Set Timeouts: omitting `script`, `pageLoad`, or `implicit` no longer fails: omitted fields keep their
values and `{}` succeeds without changes. Invalid updates change no values
([#22960](https://github.com/appium/appium/pull/22960),
[#22961](https://github.com/appium/appium/pull/22961))
- Set Timeouts: unknown values for the legacy `type` argument now return HTTP `400` /
`invalid argument` instead of HTTP `500` / `unknown error`
([#22987](https://github.com/appium/appium/pull/22987))
- [getLog](../reference/api/others.md#getlog): unsupported `type` values now return HTTP `400` /
`invalid argument` instead of HTTP `500` / `unknown error`
([#22986](https://github.com/appium/appium/pull/22986))
### BiDi Protocol
- Subscriptions without `contexts` now receive events carrying a context, so that module
subscriptions such as `events: ["log"]` now match events such as `log.entryAdded`. Overlapping
subscriptions deliver each event only once ([#22883](https://github.com/appium/appium/pull/22883))
- The implementation of [`session.subscribe`](../reference/api/bidi.md#bidisubscribe) (which does
not yet support `userContexts`) now rejects `userContexts` with HTTP `500` /
`unsupported operation`, instead of silently creating an unscoped subscription. Malformed
`userContexts`, or supplying both `contexts` and `userContexts`, return HTTP `400` /
`invalid argument`. Drivers implementing user-context support can override `bidiSubscribe`
([#22877](https://github.com/appium/appium/pull/22877)).
- Any `sessionId` or `id` keys inside BiDi command parameters are now validated like any other
unknown parameter, instead of being silently accepted
([#22771](https://github.com/appium/appium/pull/22771))
### [Storage Plugin](https://github.com/appium/appium/tree/master/packages/storage-plugin)
- All [endpoints](../reference/api/plugins.md#storage-plugin) and stream/events WebSocket paths now
respect custom server `--base-path` values, instead of always being mounted at the server root
([#22906](https://github.com/appium/appium/pull/22906))
- File names starting with a dot or ending with `.filepart` are now rejected
([#22863](https://github.com/appium/appium/pull/22863),
[#22959](https://github.com/appium/appium/pull/22959))
- Concurrent WebSocket uploads of the same file are now rejected
([#22962](https://github.com/appium/appium/pull/22962))
- Pending upload WebSocket routes are now preserved across retries
([#22948](https://github.com/appium/appium/pull/22948))
- Errors on upload event sockets are now logged instead of potentially terminating the server
([#22963](https://github.com/appium/appium/pull/22963))
### Other Fixes
- The `appium driver`/`appium plugin` CLI commands now lock the extension manifest while running,
preventing any concurrent CLI commands from silently clobbering each other's changes
([#22767](https://github.com/appium/appium/pull/22767))
- IPv6 literals are now correctly bracketed during URL assembly, including BiDi WebSocket URLs and
[Execute Driver Plugin](https://github.com/appium/appium/tree/master/packages/execute-driver-plugin)
connections ([#22872](https://github.com/appium/appium/pull/22872),
[#22912](https://github.com/appium/appium/pull/22912),
[#22914](https://github.com/appium/appium/pull/22914))
## Developer-Facing Changes
The following changes primarily affect developers of Appium clients, drivers, plugins, or tools
that import Appium's internal packages directly. They do not affect most Appium end users.
### Extension Development
- When installing a locally available driver/plugin using Appium's CLI `install` command with the
`--source=local` flag, Appium now installs the extension directly from the supplied local
directory, without first creating an intermediate global `npm` link
([#23086](https://github.com/appium/appium/pull/23086)). Local installs still link to the source
directory, so source changes do not require reinstalling the extension. If you use tooling that
relies on the package being linked in `npm`'s global prefix, manage that global link separately.
- Extension manifests and `extensions.yaml` are now validated with `ajv`/JSON Schema; a corrupted
`extensions.yaml` now resets to an empty manifest with a warning, instead of crashing later with a
confusing error ([#22732](https://github.com/appium/appium/pull/22732))
- `ExecuteMethodMap` type declarations now check `params` against the target method's signature at
compile time, catching mismatched required/optional execute method parameters in driver code
([#22754](https://github.com/appium/appium/pull/22754))
- When a plugin intercepts a command that would otherwise be proxied downstream, Appium no longer
validates its fields or values ([#23060](https://github.com/appium/appium/pull/23060)). This
matches direct proxying, where the downstream remote end owns these checks. Plugins that
previously relied on Appium to validate these arguments can now receive missing or invalid
values (JSON-object request-body checks still remain in place before the plugin is called). If
your plugin handles such a command without calling `next()`, validate the inputs it uses.
Pass-through plugins can still call `next()` and delegate validation to the downstream remote end.
### `@appium/base-driver`
#### JSONWP/MJSONWP Removal
As listed [in the Breaking Changes section above](#jsonwpmjsonwp-internals-removed), the internal
code responsible for JSONWP/MJSONWP protocol support has been removed
([#22681](https://github.com/appium/appium/pull/22681)). This includes the following items:
- `ProtocolError` instances no longer carry a `jsonwpCode` property, and error responses no longer
include a legacy numeric `status` code (`errorFromMJSONWPStatusCode`, aliased as `errorFromCode`,
has been removed; use `errorFromW3CJsonCode`)
- Responses no longer duplicate element references under the legacy `ELEMENT` key; only the W3C
`element-6066-11e4-a52e-4f735466cecf` key is present
- `WebDriverProxy` (formerly `JWProxy`, now removed as a name) no longer converts responses from a
downstream automation server speaking legacy MJSONWP; downstream servers must speak W3C WebDriver
- `determineProtocol`, `DriverCore#setProtocolMJSONWP()`, and `DriverCore#isMjsonwpProtocol()` have
been removed; drivers can no longer produce the legacy `{sessionId, status, value}` response shape
- `statusCodes` and `getSummaryByCode` are no longer available (the `jsonwp-status` module has been
removed)
- A command result shaped like `{protocol, value}` is no longer unwrapped. It is sent to the
client as the command value, so a script returning `{protocol: 'W3C', value: 5}` gets that object
back. A result of `{protocol, error}` whose `protocol` is `W3C` or `MJSONWP` and whose `error`
is an `Error` is still thrown
#### HTTP Server Moved to Separate Package
The HTTP/Express server code has been extracted from `@appium/base-driver` into the new
`@appium/http-server` package ([#22800](https://github.com/appium/appium/pull/22800)). The
following items are therefore no longer exported from `@appium/base-driver` or `appium/driver.js`:
- Methods: `server`, `normalizeBasePath`, `configureServer`
- Types: `ServerOpts`, `ConfigureServerOpts`, `ConfigureHttpOpts`, `StartServerOpts`
If you use these items, import them from `@appium/http-server` instead.
#### Other Changes
- The default class export has been removed
([#22741](https://github.com/appium/appium/pull/22741)). Use the named `{BaseDriver}` export
instead
- The default export of `basedriver/helpers.js` has been removed
([#22741](https://github.com/appium/appium/pull/22741)). Use named exports instead
- `BaseDriver`'s constructor no longer takes command-mixin machinery into account
([#22741](https://github.com/appium/appium/pull/22741))
- `createSession()` no longer accepts the legacy multi-argument form
(`jwpCaps, reqCaps, w3cCaps`); only the single `w3cCapabilities` argument is supported now
([#22730](https://github.com/appium/appium/pull/22730))
- The deprecated `driverData` mechanism (`Core.driverData`, the `driverData` parameter on
`createSession`/`deleteSession`, and the `DriverData` type) has been removed
([#22716](https://github.com/appium/appium/pull/22716)). Migrate to `IAppiumIpc` instead
- The `server()` and `configureServer()` methods (now exported by `@appium/http-server`) now
default to `allowCors: false` ([#22990](https://github.com/appium/appium/pull/22990))
- Both `ipc.unsubscribe(topic, subscriber)` and `subscription.unsubscribe()` now finish waiting on
async iterators and notify observers once ([#22955](https://github.com/appium/appium/pull/22955)).
An observer that throws still propagates its error to the caller, but no longer prevents waiting
iterators from finishing
- The unused `reset()` method has been removed
([#22741](https://github.com/appium/appium/pull/22741))
- The `generateDriverLogPrefix()` helper no longer supports the deprecated `sessionId` argument
([#22764](https://github.com/appium/appium/pull/22764))
- The new command idle timeout now stays suspended through HTTP/BiDi plugin chains, including work
after `next()`, and while proxied BiDi commands await a response
([#22946](https://github.com/appium/appium/pull/22946),
[#22947](https://github.com/appium/appium/pull/22947)). Custom `startNewCommandTimeout`
implementations must delegate timer creation to `super.startNewCommandTimeout()` so they respect
shared activity, while custom command execution must delegate to `super.executeCommand()` or wrap
the full command in `runWithCommandTimeout`
- The `appium:autoLaunch`, `appium:locale`, `appium:language`, `appium:autoWebview`,
`appium:orientation`, and `appium:udid` capabilities are no longer validated as part of the
standard capability constraints ([#22950](https://github.com/appium/appium/pull/22950),
[#22952](https://github.com/appium/appium/pull/22952)). If you use them, declare them in your own
driver constraints
- The built-in test fixture routes (`/welcome`, `/test/guinea-pig*`, `/produce_error`, `/crash`),
the `STATIC_DIR` export, and the `APPIUM_ENABLE_LEGACY_TEST_PAGES` environment variable have been
removed ([#22680](https://github.com/appium/appium/pull/22680)). If you relied on these fixtures,
migrate to use your own local test server
### `@appium/base-plugin`
- The default class export has been removed ([#22718](https://github.com/appium/appium/pull/22718)).
Use the named `{BasePlugin}` export instead
- `Plugin#logger` has been removed in favor of `Plugin#log`
([#22718](https://github.com/appium/appium/pull/22718))
- `Plugin#name` and `Plugin#cliArgs` are now read-only
([#22718](https://github.com/appium/appium/pull/22718))
### `@appium/logger`
- The default class export has been removed ([#22719](https://github.com/appium/appium/pull/22719)).
Use the named `{log}` export instead
- The long-disabled, no-op progress/unicode methods (`enableProgress`, `disableProgress`,
`progressEnabled`, `enableUnicode`, `disableUnicode`) have been removed
([#22719](https://github.com/appium/appium/pull/22719))
### `@appium/support`
- `env`: the module has been integrated into the `appium` package as internal helpers
([#22708](https://github.com/appium/appium/pull/22708))
- `imageUtil`: the module has been removed ([#22678](https://github.com/appium/appium/pull/22678))
- `fs`: the following exports have been removed: `readPackageJsonFrom` and `findRoot` methods,
`F_OK`/`R_OK`/`W_OK`/`X_OK` constants, `CopyFileDescriptor` and `ReadFn` types
([#22678](https://github.com/appium/appium/pull/22678))
- `fs`: `glob()` now relies on Node's `fs.promises.glob` instead of the `glob` package, with a
narrower `GlobOptions` shape ([#22735](https://github.com/appium/appium/pull/22735))
- `fs`: `mv()` now preserves symlinks inside moved directories and moves source symlinks themselves
without moving their targets' contents. Dangling source links are supported, and Windows
case-only renames update the entry's spelling
([#22880](https://github.com/appium/appium/pull/22880),
[#22954](https://github.com/appium/appium/pull/22954),
[#22958](https://github.com/appium/appium/pull/22958))
- `fs`: `walkDir()` now continues after walker errors such as `EACCES` and `ELOOP` instead of
hanging. These errors are logged and affected entries are skipped; `ENOENT` still rejects the
returned promise ([#22956](https://github.com/appium/appium/pull/22956))
- `fs`: `write()` now relies on Node's `promisify`, which resolves to an object
(`{bytesWritten, buffer}`), instead of only `bytesWritten`
([#22704](https://github.com/appium/appium/pull/22704))
- `logger`: the default export has been removed. Use the named `{log}` export instead
([#22719](https://github.com/appium/appium/pull/22719))
- `logger`: `errorAndThrow` has been removed in favor of `errorWithException`
([#22719](https://github.com/appium/appium/pull/22719))
- `net`: support for FTP-based file uploads has been removed, along with the `FtpUploadOptions` and
`NotHttpUploadOptions` types ([#22678](https://github.com/appium/appium/pull/22678))
- `net`: the new `checkPortStatus()` and `getFreePort()` helpers replace the `portscanner` package
and custom free port lookups in drivers and plugins
([#23156](https://github.com/appium/appium/pull/23156)). Unlike `portscanner`, they accept an
options object instead of positional arguments. `getFreePort()` also covers `findAPortNotInUse()`:
pass `port` (a single port or a `[startPort, endPort]` range) to probe specific ports, in which
case it throws `NoFreePortError` if all of them are busy instead of resolving with `false`
- `mjpeg`: the module has been removed ([#22678](https://github.com/appium/appium/pull/22678))
- `mkdirp`: the module has been removed ([#22678](https://github.com/appium/appium/pull/22678)).
Import `mkdirp()` from the `fs` module instead
- `node`: `requirePackage()` has been removed
([#22684](https://github.com/appium/appium/pull/22684))
- `npm`: the module has been integrated into the `appium` package as internal helpers
([#22721](https://github.com/appium/appium/pull/22721))
- `process`: the module has been removed ([#22678](https://github.com/appium/appium/pull/22678))
- `system`: `macOsxVersion()` has been removed
([#22684](https://github.com/appium/appium/pull/22684))
- `util`: the following methods have been removed: `uuidV1`, `uuidV3`, `uuidV5`, `localIp`,
`cancellableDelay`, and `multiResolve` ([#22678](https://github.com/appium/appium/pull/22678))
- `zip`: `extractAllTo()` always uses the built-in JS extractor now, so the `useSystemUnzip` option
has been removed ([#23091](https://github.com/appium/appium/pull/23091)). The extractor supports
only stored and deflate entries and verifies the CRC32 of every entry. File names that are not
flagged as UTF-8 by the archive are decoded as `utf8` by default, and the legacy `cp437` decoding
is no longer supported. Other single-byte encodings supported by Node.js can be selected via
`fileNamesEncoding`. Archives with encrypted entries or other compression methods are rejected
with `ZipStreamUnsupportedError`
### `@appium/tsconfig`
- `noImplicitOverride` is now set to `true`, which means that TypeScript drivers and plugins that
extend the config must mark every member overriding a base class member (e.g. `BaseDriver` or
`BasePlugin` methods, and `static` fields such as `newMethodMap`) with the `override` modifier
([#23143](https://github.com/appium/appium/pull/23143)). Opt-out is also possible by setting
`noImplicitOverride` to `false` in your own `tsconfig.json`.
### Client Development
- State-changing HTTP requests with an `Origin` header now return HTTP `403`, unless the CORS
insecure feature is enabled on the Appium server
([#23102](https://github.com/appium/appium/pull/23102)). Remove the `Origin` header or instruct
users to enable CORS.
## New Features
### App URL Rules
The new `--app-url-rules` server CLI flag (and its equivalent configuration file property) allows
server hosts to restrict the host/IP values allowed in capabilities like `appium:app`. Configurable
properties include allow/deny lists, HTTPS-only, credentials, and redirect limits.
Refer to [the Security guide](./security.md#restricting-remote-app-urls) for more details.
### CLI Update Command Checks Server Requirement
As a follow-up to Appium 3.9, which changed the default behavior of the Appium CLI
[`install`](../reference/cli/extensions.md#install) command to install the newest extension version
that is compatible with the current server (as opposed to throwing an error if the server
requirement of the latest extension version is incompatible), Appium 4 adjusts the
[`update`](../reference/cli/extensions.md#update) command to now implement this behavior as well.
This makes default usage of both `install` and `update` safe even when future major extension
versions raise their server requirements.
### Commands Can Bypass Queue
Driver commands (endpoints) are now allowed to bypass the default command queue, which enables the
command to execute while another long-running command is in progress.
By default, only the standard [Status](../reference/api/webdriver.md#getstatus) endpoint is exempt
from the queue, but driver developers can also customize the list of exempt commands by overriding
the `queueExemptCommands` getter.
The behavior of the idle timer (set by `appium:newCommandTimeout`) has also been adjusted to only
reset once no commands are executing.
### New Set Timeouts Parameter
The standard [Set Timeouts](../reference/api/webdriver.md#timeouts) endpoint has been extended to
additionally accept the Appium-specific `command` parameter. This aligns its handling with
[Get Timeouts](../reference/api/webdriver.md#gettimeouts), which already returned this parameter.
The parameter itself is mapped to the `appium:newCommandTimeout` capability.
The non-standard `type`/`ms` parameters, which were previously the only way to change this timeout
mid-session, have been deprecated as a result.
### Universal XML Plugin Can Be Toggled
The [Universal XML plugin](https://github.com/appium/appium/tree/master/packages/universal-xml-plugin)
now provides the [`universalXml: setEnabled` and `universalXml: isEnabled` execute methods](../reference/api/plugins.md#universal-xml-plugin),
which allow toggling the translation during a session, e.g. to retrieve the original page source.
+123
View File
@@ -37,6 +37,10 @@ sessions the feature should apply. The prefix can be either the driver's `automa
wildcard (`*`) symbol, if the feature should be applied to all drivers. The prefix and feature name
are separated using the colon character (`:`).
Use the driver's `automationName`, which may differ from its install name. An install-name-only
prefix does not enable or disable a feature. When configuring a session, Appium warns about such
entries for that driver unless the prefix is another installed driver's `automationName`.
For example, `first:foo` refers to the `foo` feature for the `first` driver, whereas `*:bar` refers
to the `bar` feature for all drivers.
@@ -87,3 +91,122 @@ Turn on multiple insecure features for specific drivers:
```bash
appium --allow-insecure=uiautomator2:adb_shell,xcuitest:get_server_logs
```
## Restricting Remote App URLs
Several drivers accept a URL instead of a local path in capabilities such as `appium:app`, in which
case the Appium server downloads the application package from that URL before starting the session.
By default, any `http:` or `https:` URL is accepted. Server hosts who want to control which URLs
their server is allowed to download from can do so with the `--app-url-rules` argument (or the
`server.app-url-rules` property in a [configuration file](./config.md)). Its value is a JSON object
(or a path to a JSON file) with any of the following properties:
| <div style="width:10em">Rule</div> | Description | Default |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `allow` | List of hostname patterns, IP addresses, or CIDR subnets. If non-empty, a hostname or its resolved address must match _at least one_ | `[]` |
| `deny` | List of hostname patterns, IP addresses, or CIDR subnets. A matching hostname or resolved address is rejected, even if an `allow` rule also matches | `[]` |
| `httpsOnly` | Only accept `https:` URLs | `false` |
| `allowCredentials` | Accept URLs containing a username and/or password (e.g. `https://user:pass@host/app.apk`) | `true` |
| `maxRedirects` | Maximum number of HTTP redirects to follow while downloading. Set to `0` to reject any redirect | `21` |
Hostnames are normalized (lowercased, converted to Punycode, trailing dot removed) before matching
and resolved on every download. Address rules apply to literal addresses and all dynamically
resolved IPv4/IPv6 addresses. The rules are also applied to every redirect, so redirects cannot be
used to escape them. If a URL violates any rule, the session is not created and a generic error
is returned. The violated rule is deliberately neither reported to the client nor written to the
server log, since server logs are often handed over to clients as well. URL schemes, ports, paths,
queries, and fragments are not matched.
Hostname patterns use the [picomatch](https://github.com/micromatch/picomatch#globbing-features)
glob syntax and are matched against the whole hostname:
| Pattern | Matches |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `artifacts.example.com` | Exactly this hostname |
| `*.example.com` | Any subdomain of `example.com` (including nested ones, like `a.b.example.com`), but not `example.com` itself |
| `*example.com` | Any hostname ending with `example.com`, including `example.com` itself |
| `apps.{staging,prod}.example.com` | `apps.staging.example.com` and `apps.prod.example.com` |
| `build-?.example.com` | `build-1.example.com`, `build-a.example.com`, etc. |
| `node[0-9].example.com` | `node0.example.com` to `node9.example.com` |
IP address rules match a single address (`192.0.2.10`, `2001:db8::1`) or a whole subnet in CIDR
notation (`10.0.0.0/8`, `2001:db8::/32`). IPv4 rules also match IPv4-mapped IPv6 addresses
(e.g. `::ffff:10.1.2.3`).
!!! note
```
These rules only apply to URLs the server downloads via the standard app configuration helper,
which is used for `appium:app` and similar capabilities by all official drivers. Drivers may
define custom capabilities with URLs that are processed differently and thus are not covered.
```
!!! note
```
If the server downloads applications through an HTTP proxy (configured via the `HTTP_PROXY`,
`HTTPS_PROXY` and `NO_PROXY` environment variables), the proxy resolves the destination host
itself, so rules containing IP addresses or subnets cannot be enforced for proxied downloads.
Such downloads are rejected; either exclude the download hosts from proxying via `NO_PROXY`
or only use hostname-based rules.
```
### Examples
Only allow HTTPS downloads from an internal artifact server, without credentials in the URL and
without following redirects:
```bash
appium --app-url-rules='{"allow": ["artifacts.example.com", "10.0.0.0/8"], "httpsOnly": true, "allowCredentials": false, "maxRedirects": 0}'
```
The same configuration as part of a config file:
```yaml
server:
app-url-rules:
allow:
- 'artifacts.example.com'
- '10.0.0.0/8'
httpsOnly: true
allowCredentials: false
maxRedirects: 0
```
Allow downloads from any subdomain of `example.com` and from two IPv6 subnets, except from the
staging environment:
```yaml
server:
app-url-rules:
allow:
- '*.example.com'
- '2001:db8:1::/48'
- '2001:db8:2::/48'
deny:
- '*.staging.example.com'
```
Allow downloads from anywhere, except from the server itself, private networks, link-local
addresses (such as cloud metadata services), and any `.internal` hostname:
```yaml
server:
app-url-rules:
deny:
- 'localhost'
- '*.internal'
- '127.0.0.0/8'
- '10.0.0.0/8'
- '172.16.0.0/12'
- '192.168.0.0/16'
- '169.254.0.0/16'
- '::1/128'
- 'fc00::/7'
- 'fe80::/10'
```
The rules in the last example are applied to the addresses each hostname resolves to, so they
cannot be bypassed via DNS. Note that the `deny` list also blocks any download from the server's
own private network, so a private artifact server must be excluded from the `deny` rules in order
to work.
+6 -7
View File
@@ -2,7 +2,7 @@
hide:
- toc
title: SSL/TLS/SPDY Support
title: SSL/TLS Support
---
Appium 2.2 introduces the option to start the Appium server with SSL/TLS support.
@@ -20,15 +20,14 @@ Both arguments must be provided and should contain paths to a valid
[X509 PEM](https://www.ssl.com/guide/pem-der-crt-and-cer-x-509-encodings-and-conversions/)
certificate and its corresponding private key.
After the server is started use the `https` protocol and a client supporting SSL/TLS or
[SPDY](https://en.wikipedia.org/wiki/SPDY) to communicate to it.
After the server is started use the `https` protocol and a client supporting SSL/TLS to
communicate to it.
### Supported Features
Once a secure server socket is established it supports the following protocols:
`['h2', 'spdy/3.1', 'spdy/3', 'spdy/2', 'http/1.1', 'http/1.0']`. See
[the SPDY node module documentation](https://www.npmjs.com/package/spdy) to get more details about
its features. All insecure client connections will be rejected by the server.
Once a secure server socket is established it uses Node.js' native
[`https`](https://nodejs.org/api/https.html) module to serve connections. All insecure client
connections will be rejected by the server.
### Self-Signed Certificates
+10
View File
@@ -24,6 +24,16 @@ title: Appium 客户端简介
例如,`查找元素`命令对应于发送到 HTTP 端点 `/session/:sessionid/element` 的 HTTP `POST` 请求(其中`:sessionid` 是服务器在之前 `创建会话` 调用中生成的唯一会话 ID 的占位符)。
If the client disconnects before Appium finishes sending a `Create Session` response and the
request has no `X-Idempotency-Key`, Appium deletes the new session once driver setup completes.
Setup is not interrupted. With an accepted idempotency key, a retry that arrives before setup
finishes waits for the same session ID, or the same error if setup failed. If the original client
and all waiting retries disconnect before setup finishes, Appium deletes the new session and
discards its cached result; a later retry starts a new session. Otherwise, Appium keeps the session
and caches its response for replay while it remains in the bounded, in-memory idempotency cache.
Disconnecting after a response was sent, or during a command in an existing session, does not
automatically end that session. Use `Delete Session` when you are done.
此信息主要对开发与 WebDriver 规范一起工作的技术的人有用。它对试图编写 Appium 或 Selenium 测试的人不是特别有用。当您编写 Appium 测试时,您希望使用您熟悉的编程语言。幸运的是,存在一组 [Appium 客户端库](../ecosystem/clients.md)[^1],它们负责向 Appium 服务器发起HTTP 的请求。它们为特定编程语言公开了一组“原生”命令,以便对测试作者来说,它就像您在编写 Python、JavaScript 或 Java。
以下是使用 Appium 客户端在五种不同编程语言中实现相同的 Appium 命令集的示例(注意,这不是包含所有导入的工作示例代码;请参阅每个客户端库的设置和命令参考说明):
+1 -1
View File
@@ -11,7 +11,7 @@ title: Appium 驱动程序介绍
在最基本的层面上,驱动程序只是扩展了 Appium 中包含的一个特殊类的 Node.js 类,这个类叫做 `BaseDriver`。你可以用以下非常简单的几行代码就拥有一个非常接近"可工作"的驱动程序:
```js
import BaseDriver from '@appium/base-driver'
import {BaseDriver} from '@appium/base-driver'
class MyNewDriver extends BaseDriver {
}
@@ -8,7 +8,7 @@ title: 系统要求
Appium 服务器的基本要求如下:
- macOS、Linux 或 Windows 操作系统
- [Node.js](https://nodejs.org) 版本在 [SemVer](https://semver.org) 范围 `^20.19.0 || ^22.12.0 || >=24.0.0`
- [Node.js](https://nodejs.org) version in the [SemVer](https://semver.org) range `^22.22.2 || ^24.15.0 || >=26.0.0`
- 推荐使用 LTS 版本
- [`npm`](https://npmjs.com) 版本 `>=10`(`npm` 通常与 Node.js 捆绑,但可以独立升级)
@@ -8,15 +8,14 @@ title: 编写测试 (.NET)
[Appium .NET Client](https://github.com/appium/dotnet-client/) 是
官方的 Appium C# 客户端。这个驱动程序是 Selenium C# 客户端的扩展。它具有常规驱动程序的所有功能,但在之上添加了 Appium 特定的方法。该驱动程序在公共 NuGet Gallery 上作为 [Appium.WebDriver](https://www.nuget.org/packages/Appium.WebDriver/) 提供。
现在,我们进入目录并创建一个新的 [NUnit](https://nunit.org/) 项目。我们还将添加对 Appium.Net 驱动程序和其他依赖项的引用。
Now, create a new [NUnit](https://nunit.org/) project. 我们还将添加对 Appium.Net 驱动程序和其他依赖项的引用。
```bash
cd dotnet-client
dotnet new nunit --name appiumtest
cd appiumtest
# 这将安装最新的 5.x 版本
# This will install the latest version
dotnet add package Appium.WebDriver --prerelease
dotnet add package Newtonsoft.Json --version 13.0.3
```
@@ -47,7 +46,7 @@ public class Tests
driverOptions.AddAdditionalAppiumOption("appPackage", "com.android.settings");
driverOptions.AddAdditionalAppiumOption("appActivity", ".Settings");
// NoReset assumes the app com.google.android is preinstalled on the emulator
// NoReset assumes the app com.android.settings is preinstalled on the emulator
driverOptions.AddAdditionalAppiumOption("noReset", true);
_driver = new AndroidDriver(serverUri, driverOptions, TimeSpan.FromSeconds(180));
+22 -7
View File
@@ -49,6 +49,20 @@ Subscribes to one or more BiDi events.
`{subscription: string}` — a unique subscription ID that can be passed to `session.unsubscribe`.
#### Limits
A session can have up to 100 subscriptions. Every subscription covers a combination of each of its
events and each of its contexts (an event without contexts counts as one), and all the subscriptions
together, counted one by one, can cover up to 1000 combinations. Lists in the parameters can have up
to 1000 items, and the event names, contexts and subscription IDs can be up to 256 characters long.
A request that exceeds a limit fails with an `invalid argument` error without changing the subscriptions.
Unsubscribing by event names (`events`) removes the matching contexts of those events across all the
subscriptions (an event stays active in the contexts that are not listed), but the IDs of the
subscriptions that have no events left stay valid, so they can still be passed to `session.unsubscribe`.
The oldest such ID expires only when a new subscription needs its slot at the limit of 100 subscriptions.
An unknown or expired ID fails the whole `subscriptions` request, and none of its subscriptions are removed.
### bidiUnsubscribe
```
@@ -57,16 +71,17 @@ session.unsubscribe
> WebDriver BiDi documentation: [session.unsubscribe](https://w3c.github.io/webdriver-bidi/#command-session-unsubscribe)
Unsubscribes using either previously returned subscription IDs or event names.
Removing a subscription ID preserves any overlapping subscriptions.
Unsubscribes from one or more BiDi events using subscription IDs or event names. Event names can
also be scoped to contexts (legacy parameter). Removing a subscription ID preserves any overlapping
subscriptions.
#### Parameters
| Name | Description | Type | Default |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ------- |
| `subscriptions?` | Non-empty list of subscription IDs returned by `session.subscribe`. Cannot be combined with `events` or `contexts`. | string[] | |
| `contexts?` | Non-standard, only together with `events`: contexts in which to unsubscribe from the specified events. By default, the global scope is applied. | string[] | `['']` |
| `events?` | Non-empty list of event names to unsubscribe from. Required when `subscriptions` is omitted. | string[] | |
| Name | Description | Type | Default |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------ | ------- |
| `subscriptions?` | Non-empty list of subscription IDs returned by `session.subscribe`. Cannot be combined with `events` or `contexts`. | string[] | |
| `events?` | Non-empty list of event names to unsubscribe from. Required when `subscriptions` is omitted. | string[] | |
| `contexts?` | Legacy parameter: contexts in which to unsubscribe from events specified in `events`. By default, the global scope is applied. | string[] | `['']` |
All subscription IDs must be known to the current session. An unknown ID causes an `invalid argument`
error without removing any subscriptions. Subscription IDs are cleared when the session is deleted.
@@ -11,125 +11,6 @@ title: JSON Wire Protocol
The following is a list of legacy [JSON Wire Protocol (JSONWP)](https://www.selenium.dev/documentation/legacy/json_wire_protocol/)
endpoints supported in Appium.
### getSession
```
GET /session/:sessionId
```
> JSONWP documentation: [/session/:sessionId](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionid)
Retrieves the capabilities of the current session.
Appium implements a modified version of this endpoint. If the `appium:eventTimings` capability is
set to `true`, the returned result will additionally include the `events` key, whose value contains
the event history and timings.
!!! warning "Deprecated"
For retrieving capabilities, please use [`getAppiumSessionCapabilities`](./appium.md#getappiumsessioncapabilities).<br />
For retrieving event history, please use [`getLogEvents`](./appium.md#getlogevents).
#### Response
`Capabilities` - an object containing the session capabilities, and the event history (if applicable)
### availableIMEEngines
```
GET /session/:sessionId/ime/available_engines
```
> JSONWP documentation: [/session/:sessionId/ime/available_engines](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimeavailable_engines)
Retrieves all IME (input method editor) engines available on the device under test.
!!! warning "Deprecated"
In the future, this endpoint will be moved to the [UiAutomator2 and Espresso drivers](../../ecosystem/drivers.md)
#### Response
`string[]` - a list of available IME engines
### getActiveIMEEngine
```
GET /session/:sessionId/ime/active_engine
```
> JSONWP documentation: [/session/:sessionId/ime/active_engine](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimeactive_engine)
Retrieves the name of the active IME engine.
!!! warning "Deprecated"
In the future, this endpoint will be moved to the UiAutomator2 and Espresso drivers
#### Response
`string` - the name of the active IME engine
### isIMEActivated
```
GET /session/:sessionId/ime/activated
```
> JSONWP documentation: [/session/:sessionId/ime/activated](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimeactivated)
Determines if IME input is available and active.
!!! warning "Deprecated"
In the future, this endpoint will be moved to the UiAutomator2 and Espresso drivers
#### Response
`boolean` - `true` if IME is active, otherwise `false`
### deactivateIMEEngine
```
POST /session/:sessionId/ime/deactivate
```
> JSONWP documentation: [/session/:sessionId/ime/deactivate](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimedeactivate)
Deactivates the currently active IME engine.
!!! warning "Deprecated"
In the future, this endpoint will be moved to the UiAutomator2 and Espresso drivers
#### Response
`null`
### activateIMEEngine
```
POST /session/:sessionId/ime/activate
```
> JSONWP documentation: [/session/:sessionId/ime/activate](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimeactivate)
Activates an IME engine.
!!! warning "Deprecated"
In the future, this endpoint will be moved to the UiAutomator2 and Espresso drivers
#### Parameters
| Name | Description | Type |
| -------- | ---------------------------------- | ------ |
| `engine` | Name of the IME engine to activate | string |
#### Response
`null`
### getOrientation
```
@@ -171,53 +52,3 @@ Sets the orientation of the device under test.
#### Response
`null`
### getGeoLocation
```
GET /session/:sessionId/location
```
> JSONWP documentation: [/session/:sessionId/location](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidlocation)
Retrieves the current location of the device under test.
!!! warning "Deprecated"
Please use driver-specific extension methods such as `mobile: getGeoLocation` or
`mobile: getSimulatedLocation`
#### Response
`Location` - an object with the following properties:
| Name | Description | Type |
| ----------- | -------------------------------- | ------ |
| `altitude` | Altitude of the device location | number |
| `latitude` | Latitude of the device location | number |
| `longitude` | Longitude of the device location | number |
### setGeoLocation
```
POST /session/:sessionId/location
```
> JSONWP documentation: [/session/:sessionId/location](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidlocation)
Sets the current location of the device under test.
!!! warning "Deprecated"
Please use driver-specific extension methods such as `mobile: setGeoLocation` or
`mobile: setSimulatedLocation`
#### Parameters
| Name | Description | Type |
| ---------- | ------------------------------------------- | ------------------------- |
| `location` | New device latitude, longitude and altitude | [`Location`](#response_6) |
#### Response
`null`
@@ -120,53 +120,3 @@ Retrieves all available application contexts.
#### Response
`string[]` - the names of available contexts
### getNetworkConnection
```
GET /session/:sessionId/network_connection
```
> MJSONWP documentation: [Device Modes](https://github.com/SeleniumHQ/mobile-spec/blob/master/spec-draft.md#device-modes)
Retrieves the current state of network types (data, Wi-Fi, airplane mode).
!!! warning "Deprecated"
Please use driver-specific extension methods such as `mobile: getConnectivity`
#### Response
`NetworkConnectionState` - a number indicating the current network state:
| Value | Data | Wi-Fi | Airplane Mode |
| ----- | ---- | ----- | ------------- |
| `0` | OFF | OFF | OFF |
| `1` | OFF | OFF | ON |
| `2` | OFF | ON | OFF |
| `4` | ON | OFF | OFF |
| `6` | ON | ON | OFF |
### setNetworkConnection
```
POST /session/:sessionId/network_connection
```
> MJSONWP documentation: [Device Modes](https://github.com/SeleniumHQ/mobile-spec/blob/master/spec-draft.md#device-modes)
Sets the state of network types (data, Wi-Fi, airplane mode).
!!! warning "Deprecated"
Please use driver-specific extension methods such as `mobile: setConnectivity`
#### Parameters
| <div style="width:6em">Name</div> | Description | <div style="width:18em">Type</div> |
| --------------------------------- | -------------------------------------------------------------------------- | ----------------------------------------------------- |
| `parameters` | Object containing the `type` key, whose value is the desired network state | `{"type": `[`NetworkConnectionState`](#response_5)`}` |
#### Response
[`NetworkConnectionState`](#response_5) - the new network state
@@ -267,6 +267,43 @@ preserved, and only the incomplete uploads will be stopped.
## Universal XML Plugin
Translation is on by default. It can be turned off and on during a session with the
[execute methods](../../guides/execute-methods.md) below, and applies only to the current session.
### execute
```
POST /session/:sessionId/execute/sync
```
Modifies the [`execute`](./webdriver.md#execute) endpoint:
- Adds the `universalXml: setEnabled` and `universalXml: isEnabled` execute methods. Any other
script is passed on unchanged
#### universalXml: setEnabled
Turns translation on or off for the current session. While it is off, `findElement`,
`findElements` and `getPageSource` are passed on unchanged.
##### Parameters
| Name | Description | Type |
| --------- | ------------------------------------------------- | ------- |
| `enabled` | Whether node/attribute names should be translated | boolean |
##### Response
`null`
#### universalXml: isEnabled
Returns whether translation is on for the current session.
##### Response
`boolean` - `true` if translation is on
### findElement
```
@@ -26,18 +26,11 @@ POST /session
Creates a new WebDriver session.
Appium implements a modified version of this endpoint for historical reasons. While the W3C
endpoint only accepts 1 parameter, Appium's implementation allows up to 3 parameters, as this was
required by the legacy JSON Wire Protocol (JSONWP). Since Appium 2, the JSONWP format is no longer
supported, and any of the 3 parameters can be used to specify the W3C capabilities.
#### Parameters
| Name | Description | Type |
| ------------------- | ----------------------------------------------------------------------------- | --------------- |
| `w3cCapabilities1?` | Capabilities of the new session | `W3CDriverCaps` |
| `w3cCapabilities2?` | Another location for the new session capabilities (legacy) | `W3CDriverCaps` |
| `w3cCapabilities?` | Another location for the new session capabilities (legacy) | `W3CDriverCaps` |
| Name | Description | Type |
| --------------- | ------------------------------- | --------------- |
| `capabilities?` | Capabilities of the new session | `W3CDriverCaps` |
#### Response
@@ -92,14 +85,19 @@ GET /session/:sessionId/timeouts
Retrieves the timeout values of the current session.
Appium implements a modified version of this endpoint, by also returning the value of the `command`
timeout for supported drivers and contexts.
#### Response
`GetTimeoutsResult` - an object with the following properties:
| Name | Description | Type |
| ---------- | --------------------- | ------ |
| `command` | Command timeout | number |
| `implicit` | Implicit wait timeout | number |
| Name | Description | Type |
| ---------- | ---------------------- | -------------- |
| `script` | Script timeout | number or null |
| `pageLoad` | Page load timeout | number or null |
| `implicit` | Implicit wait timeout | number or null |
| `command` | Appium command timeout | number |
### timeouts
@@ -111,13 +109,17 @@ POST /session/:sessionId/timeouts
Sets the timeout values of the current session.
Appium implements a modified version of this endpoint by adding the optional `command` parameter
for supported drivers and contexts.
#### Parameters
| Name | Description | Type |
| ----------- | ---------------------------------------------------------- | ------ |
| `implicit?` | Implicit wait timeout (in milliseconds) | number |
| `pageLoad?` | Page load timeout (in milliseconds) | number |
| `script?` | Script timeout (in milliseconds) | number |
| Name | Description | Type |
| ----------- | ----------------------------------------------------------- | -------------- |
| `script?` | Script timeout (in milliseconds) | number or null |
| `implicit?` | Implicit wait timeout (in milliseconds) | number or null |
| `pageLoad?` | Page load timeout (in milliseconds) | number or null |
| `command?` | Appium command timeout (in milliseconds) | number |
#### Response
@@ -954,7 +956,7 @@ POST /session/:sessionId/actions
> WebDriver documentation: [Perform Actions](https://w3c.github.io/webdriver/#perform-actions)
Performs a sequence of [actions](https://w3c.github.io/webdriver/#actions).
Performs a sequence of [actions](https://w3c.github.io/webdriver/#actions). See the [Automating Gestures](../../guides/gestures.md) guide for multi-language examples.
#### Parameters
@@ -14,6 +14,7 @@ they can only be enabled using the wildcard (`*`) prefix:
| Feature Name | Description |
| ------------------- | ------------------------------------------------------------------------------- |
| `session_discovery` | Allows retrieving the list of active server sessions via `GET /appium/sessions` |
| `cors` | Allows web browser connections to the server from any host |
Of course, Appium drivers and plugins are free to define additional insecure features of their own.
The following features are defined by official plugins:
+74 -42
View File
@@ -24,48 +24,80 @@ appium
All of these options can also be set via a [Configuration File](../../guides/config.md). Options
set on the command line will override any options found in a configuration file.
| <div style="width:15em">Argument</div> | Description | Type | <div style="width:7em">Default</div> |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------------------------------------------------------- |
| `--address`, `-a` | IPv4/IPv6 address or a hostname to listen on | string | `0.0.0.0` |
| `--allow-cors` | Allow web browser connections from any host | boolean | `false` |
| `--allow-insecure` | List of [insecure features](../../guides/security.md) that should be allowed in this server's sessions. Individual features can be overridden by `--deny-insecure`. Has no effect in combination with `--relaxed-security`. | array<string> | `[]` |
| `--allow-unknown-args` | Do not exit if unrecognized command-line arguments are passed to the server; ignore them instead. Useful when the Appium CLI is wrapped by external tooling that appends extra flags. | boolean | `false` |
| `--base-path`, `-pa` | Base path to use as the prefix for all webdriver routes running on the server | string | `""` |
| `--callback-address`, `-ca` | Callback IP address | string | same as `--address` |
| `--callback-port`, `-cp` | Callback port | integer | `4723` |
| `--config` | Path to an [Appium configuration JSON file](../../guides/config.md) | string | |
| `--debug-log-spacing` | Add exaggerated spacing in logs to help with visual inspection | boolean | `false` |
| `--default-capabilities`, `-dc` | Capabilities that will be used for each session, unless overridden by received capabilities | object | |
| `--deny-insecure` | List of [insecure features](../../guides/security.md) that should be disabled in this server's sessions. Since all insecure features are disabled by default, this argument has no effect without either `--allow-insecure` or `--relaxed-security`, and is applied after both. | array<string> | `[]` |
| `--driver` | Driver-specific configuration. Keys should correspond to driver package names | object | |
| `--drivers-import-chunk-size` | Maximum number of drivers that can be imported in parallel on server startup | number | `3` |
| `--keep-alive-timeout`, `-ka` | Timeout (in seconds) to use as both the keep-alive timeout and the connection timeout for all client requests. Disabled if set to `0`. | integer | `600` |
| `--request-timeout` | Timeout (in seconds) for waiting to receive the entire HTTP request from the client. Disabled if set to `0`. Requests exceeding this timeout will be rejected with the code `HTTP 408`. | integer | `3600` |
| `--local-timezone` | Use local timezone for log timestamps | boolean | `false` |
| `--log`, `-g` | Path to a file where the server logs should be output. This does not affect output on the console. | string | |
| `--log-filters` | List of log filtering rules. See the [log filtering guide](../../guides/log-filters.md) for details. | array | |
| `--log-level` | The log level for the server logs. Supported values are `debug`, `info`, `warn`, or `error`. Combining two supported values using a colon (e.g. `warn:debug`) allows to set separate log levels for the console and file outputs, respectively. | string | `debug` |
| `--log-format` | The log format of the server logs. Supported values are `text`, `json`, or `pretty_json`. Setting the value to `json` disables colors. | string | `text` |
| `--log-no-colors` | Disable colors in the server log | boolean | `false` |
| `--log-timestamp` | Show timestamps in the server log | boolean | `false` |
| `--long-stacktrace` | Add long stack traces to log entries. Recommended for debugging only. | boolean | `false` |
| `--max-ipc-data-size` | Maximum byte size of IPC message objects. | integer | `1048576` (1MB) |
| `--max-ipc-topics` | Maximum number of IPC topics per session. | integer | `1000` |
| `--no-perms-check` | Skip various permission checks on the server startup | boolean | `false` |
| `--nodeconfig` | JSON configuration for registering Appium as a node with Selenium Grid 3 | object | |
| `--plugin` | Plugin-specific configuration. Keys should correspond to plugin package names | object | |
| `--plugins-import-chunk-size` | Maximum number of plugins that can be imported in parallel on server startup | number | `7` |
| `--port`, `-p` | Port to listen on | integer | `4723` |
| `--relaxed-security` | Allow all [insecure features](../../guides/security.md). Only use this if all clients are in a trusted network and could not potentially break out of the session sandbox. Specific features can be overridden by using `--deny-insecure`. | boolean | `false` |
| `--session-override` | Enable session override (clobbering) | boolean | `false` |
| `--shutdown-timeout` | Timeout (in milliseconds) for waiting on all active connections to close, when shutting down the server | number | `5000` |
| `--ssl-cert-path` | Absolute path to the `.cert` file if TLS is used. Must be provided together with `--ssl-key-path`. See the [SSL/TLS/SPDY Support guide](../../guides/tls.md) for details. | string | |
| `--ssl-key-path` | Absolute path to the `.key` file if TLS is used. Must be provided together with `--ssl-cert-path`. See the [SSL/TLS/SPDY Support guide](../../guides/tls.md) for details. | string | |
| `--strict-caps` | Prevent creation of new client sessions that use unsupported capabilities | boolean | `false` |
| `--tmp` | Absolute path to the directory used for temporary files | string | [`os.tmpdir()`](https://nodejs.org/api/os.html#ostmpdir) |
| `--use-drivers` | List of drivers to activate. By default, all installed drivers are activated. | array<string> | `[]` |
| `--use-plugins` | List of plugins to activate. By default, no plugins are activated. Set to `["all"]` to activate all installed plugins. | array<string> | `[]` |
| `--webhook`, `-G` | URL for an HTTP listener where the server logs should be output. This does not affect output on the console. A bare `host:port` is also accepted, which posts the logs to the root path over plain http; a value having neither a scheme nor a port falls back to `127.0.0.1:9003`. | string | |
| <div style="width:15em">Argument</div> | Description | Type | <div style="width:7em">Default</div> |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------------------------------------------------------- |
| `--address`, `-a` | IPv4/IPv6 address or a hostname to listen on | string | `0.0.0.0` |
| `--allow-insecure` | List of [insecure features](../../guides/security.md) that should be allowed in this server's sessions. Individual features can be overridden by `--deny-insecure`. Has no effect in combination with `--relaxed-security`. | array<string> | `[]` |
| `--allow-unknown-args` | Do not exit if unrecognized command-line arguments are passed to the server; ignore them instead. Useful when the Appium CLI is wrapped by external tooling that appends extra flags. | boolean | `false` |
| `--app-url-rules` | Rules that remote application URLs (e.g. in the `appium:app` capability) must satisfy before the server downloads them. See the [Restricting Remote App URLs](../../guides/security.md#restricting-remote-app-urls) guide for details. Can be a path to a JSON file or raw JSON. | object | |
| `--base-path`, `-pa` | Base path to use as the prefix for all webdriver routes running on the server | string | `""` |
| `--config` | Path to an [Appium configuration JSON file](../../guides/config.md) | string | |
| `--bidi-heartbeat-interval` | Interval (in seconds) between WebSocket pings sent to each [BiDi](../api/bidi.md) client. A connection that misses two consecutive pongs is terminated. Disabled if set to `0`. | integer | `15` |
| `--bidi-max-buffered-bytes` | Maximum number of bytes the server may keep buffered for a BiDi connection whose client is not reading fast enough. A connection that stays above the limit for longer than `--bidi-max-buffered-ms`, or exceeds twice the limit, is closed with the code `1013`. Disabled if set to `0`, which also turns off skipping of droppable events. | integer | `33554432` |
| `--bidi-max-buffered-ms` | Time (in milliseconds) a BiDi connection may stay above `--bidi-max-buffered-bytes` before it is closed. If set to `0`, the connection is closed as soon as the limit is exceeded. | integer | `30000` |
| `--default-capabilities`, `-dc` | Capabilities that will be used for each session, unless overridden by received capabilities. See [Default Capabilities](#default-capabilities) for how they are applied. | object | |
| `--deny-insecure` | List of [insecure features](../../guides/security.md) that should be disabled in this server's sessions. Since all insecure features are disabled by default, this argument has no effect without either `--allow-insecure` or `--relaxed-security`, and is applied after both. | array<string> | `[]` |
| `--driver` | Driver-specific configuration. Keys should correspond to driver package names | object | |
| `--drivers-import-chunk-size` | Maximum number of drivers that can be imported in parallel on server startup | number | `3` |
| `--keep-alive-timeout`, `-ka` | Timeout (in seconds) to use as both the keep-alive timeout and the connection timeout for all client requests. Disabled if set to `0`. | integer | `600` |
| `--request-timeout` | Timeout (in seconds) for waiting to receive the entire HTTP request from the client. Disabled if set to `0`. Requests exceeding this timeout will be rejected with the code `HTTP 408`. | integer | `3600` |
| `--local-timezone` | Use local timezone for log timestamps | boolean | `false` |
| `--log`, `-g` | Path to a file where the server logs should be output. This does not affect output on the console. | string | |
| `--log-filters` | List of log filtering rules. See the [log filtering guide](../../guides/log-filters.md) for details. | array | |
| `--log-level` | The log level for the server logs. Supported values are `debug`, `info`, `warn`, or `error`. Combining two supported values using a colon (e.g. `warn:debug`) allows to set separate log levels for the console and file outputs, respectively. | string | `info` |
| `--log-format` | The log format of the server logs. Supported values are `text`, `json`, or `pretty_json`. Setting the value to `json` disables colors. | string | `text` |
| `--log-no-colors` | Disable colors in the server log | boolean | `false` |
| `--log-timestamp` | Show timestamps in the server log | boolean | `false` |
| `--long-stacktrace` | Add long stack traces to log entries. Recommended for debugging only. | boolean | `false` |
| `--max-ipc-data-size` | Maximum byte size of IPC message objects. | integer | `1048576` (1MB) |
| `--max-ipc-topics` | Maximum number of IPC topics per session. | integer | `1000` |
| `--no-perms-check` | Skip various permission checks on the server startup | boolean | `false` |
| `--plugin` | Plugin-specific configuration. Keys should correspond to plugin package names | object | |
| `--plugins-import-chunk-size` | Maximum number of plugins that can be imported in parallel on server startup | number | `7` |
| `--port`, `-p` | Port to listen on | integer | `4723` |
| `--relaxed-security` | Allow all [insecure features](../../guides/security.md). Only use this if all clients are in a trusted network and could not potentially break out of the session sandbox. Specific features can be overridden by using `--deny-insecure`. | boolean | `false` |
| `--session-override` | Enable session override (clobbering) | boolean | `false` |
| `--shutdown-timeout` | Timeout (in milliseconds) for waiting on all active connections to close, when shutting down the server | number | `5000` |
| `--ssl-cert-path` | Absolute path to the `.cert` file if TLS is used. Must be provided together with `--ssl-key-path`. See the [SSL/TLS/SPDY Support guide](../../guides/tls.md) for details. | string | |
| `--ssl-key-path` | Absolute path to the `.key` file if TLS is used. Must be provided together with `--ssl-cert-path`. See the [SSL/TLS/SPDY Support guide](../../guides/tls.md) for details. | string | |
| `--tmp` | Absolute path to the directory used for temporary files | string | [`os.tmpdir()`](https://nodejs.org/api/os.html#ostmpdir) |
| `--use-drivers` | List of drivers to activate. By default, all installed drivers are activated. | array<string> | `[]` |
| `--use-plugins` | List of plugins to activate. By default, no plugins are activated. Set to `["all"]` to activate all installed plugins. | array<string> | `[]` |
| `--webhook`, `-G` | URL for an HTTP listener where the server logs should be output. This does not affect output on the console. A bare `host:port` is also accepted, which posts the logs to the root path over plain http; a value having neither a scheme nor a port falls back to `127.0.0.1:9003`. | string | |
### Default Capabilities
Capabilities set with `--default-capabilities` are added to the received capabilities before a
driver is matched. This is Appium's own defaulting behavior, not something defined by the W3C
WebDriver specification.
- A value the client sends in `alwaysMatch`, or in a given `firstMatch` candidate, takes precedence
over the server default
- Defaults fill missing keys in each `firstMatch` candidate separately. A value in one candidate
does not stop the default from being applied to another candidate
- A key sent in both `alwaysMatch` and `firstMatch` is still rejected by the usual capability
validation. Server defaults do not change that
For example, with these server defaults:
```json
{"appium:newCommandTimeout": 60}
```
and these received capabilities:
```json
{
"alwaysMatch": {"appium:deviceName": "Pixel"},
"firstMatch": [
{"platformName": "iOS", "appium:newCommandTimeout": 120},
{"platformName": "Android"}
]
}
```
the iOS candidate keeps `appium:newCommandTimeout` of `120`, and the Android candidate gets the
default `60`. The session uses the value from whichever candidate it is created with.
### Info Options
@@ -33,7 +33,7 @@ appium setup browser
Installs the following extensions for desktop application testing:
- Drivers: `mac2`[^1], `windows`[^2]
- Drivers: `mac2`[^1], `wincore`[^2]
- Plugins: `images`, `inspector`
#### Usage
@@ -29,12 +29,11 @@ Appium sessions.
These capabilities are used in the Appium server/base driver, but are optional, and may have a
default value.
| <div style="width:19em">Capability</div> | Description | Type | Default |
| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ------- |
| `webSocketUrl` | Toggle support of the WebDriver BiDi protocol | `boolean` | |
| `appium:eventTimings` (deprecated) | Toggle collection of [Event Timings](../../guides/event-timing.md). This capability is deprecated - please use the [`getLogEvents`](../api/appium.md#getlogevents) endpoint instead. | `boolean` | |
| `appium:newCommandTimeout` | Number of seconds the Appium server should wait for clients to send commands before stopping the session. A value of `0` disables the timeout. | `number` | `60` |
| `appium:printPageSourceOnFindFailure` | Toggle retrieval of the page source and its printing to the Appium log, whenever a request to find an element fails | `boolean` | |
| <div style="width:19em">Capability</div> | Description | Type | Default |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | ------- |
| `webSocketUrl` | Toggle support of the WebDriver BiDi protocol | `boolean` | |
| `appium:newCommandTimeout` | Number of seconds the Appium server should wait for clients to send commands before stopping the session. A value of `0` disables the timeout. | `number` | `60` |
| `appium:printPageSourceOnFindFailure` | Toggle retrieval of the page source and its printing to the Appium log, whenever a request to find an element fails | `boolean` | |
### Validated Capabilities
@@ -42,9 +41,9 @@ These capabilities are not directly used in the Appium server/base driver, but a
validation checks due to their relevance in other drivers. The actual handling of these
capabilities is optional and entirely driver-dependent.
| Capability | Validation |
| --------------------------------------------------- | ------------------------------------------------------------- |
| `platformVersion` | Must be `string` |
| `appium:app` | Must be `string`; empty values are ignored |
| `appium:fullReset` | Must be `boolean`; mutually exclusive with `appium:noReset` |
| `appium:noReset` | Must be `boolean`; mutually exclusive with `appium:fullReset` |
| Capability | Validation |
| ------------------------ | ------------------------------------------------------------- |
| `appium:platformVersion` | Must be `string` |
| `appium:app` | Must be `string`; empty values are ignored |
| `appium:fullReset` | Must be `boolean`; mutually exclusive with `appium:noReset` |
| `appium:noReset` | Must be `boolean`; mutually exclusive with `appium:fullReset` |
+116 -50
View File
@@ -139,6 +139,9 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
private _isShuttingDown = false;
/** Inner driver deleteSession calls that are still running, by session id */
private readonly pendingTeardowns = new Map<string, Promise<unknown>>();
/**
* @param opts - CLI/server options (address, port, security, default capabilities, etc.)
*/
@@ -408,18 +411,7 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
await driverInstance.startNewCommandTimeout();
} catch (error: unknown) {
if (registeredSessionId) {
try {
// A failed initialization must not leave a registered session or an idle timer,
// even if the driver's own deleteSession also fails.
try {
await this.sessions[registeredSessionId]?.clearNewCommandTimeout();
} finally {
await this.deleteSession(registeredSessionId);
}
} catch (cleanupError) {
const message = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
this.log.warn(`Could not clean up failed session ${registeredSessionId}: ${message}`);
}
await this.cleanupFailedSession(registeredSessionId);
}
return markResponseEnvelope({
protocol,
@@ -477,20 +469,23 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
* driver’s `deleteSession`.
*/
async deleteSession(sessionId: string): Promise<SessionHandlerDeleteResult> {
const dstSession: ExternalDriver | undefined = this.sessions[sessionId];
try {
const dstSession: ExternalDriver | undefined = this.sessions[sessionId];
if (dstSession) {
this.cleanupBidiSockets(sessionId);
}
// this may not be correct, but if `dstSession` was falsy, the call to `deleteSession()` would
// throw anyway.
if (!dstSession) {
throw new Error('Session not found');
}
// The inner driver may take a while to clean up, and must not get any other command or a
// second deleteSession call meanwhile
delete this.sessions[sessionId];
this.cleanupBidiSockets(sessionId);
const teardown = dstSession.deleteSession(sessionId);
this.pendingTeardowns.set(sessionId, teardown);
return markResponseEnvelope({
protocol: PROTOCOLS.W3C,
value: await dstSession.deleteSession(sessionId),
value: await teardown,
});
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
@@ -503,27 +498,40 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
// regardless of whether the deleteSession completes successfully or not
// make the session unavailable, because who knows what state it might
// be in otherwise
this.log.info(`Removing session ${sessionId} from our master session list`);
this.deleteLinkedSessionObjects(sessionId);
if (dstSession) {
this.pendingTeardowns.delete(sessionId);
this.log.info(`Removing session ${sessionId} from our master session list`);
this.deleteLinkedSessionObjects(sessionId);
}
}
}
/**
* Ends every active session, either by normal `deleteSession` or by `startUnexpectedShutdown`
* when `force` is true.
* when `force` is true, and waits for the sessions that are already being deleted.
*/
async deleteAllSessions(opts: {force?: boolean; reason?: string} = {}): Promise<void> {
const sessionsCount = Object.keys(this.sessions).length;
if (0 === sessionsCount) {
// A second deleteSession or startUnexpectedShutdown call would run the driver teardown twice
const teardowns = [...this.pendingTeardowns.values()];
if (0 === sessionsCount && 0 === teardowns.length) {
this.log.debug('There are no active sessions for cleanup');
return;
}
const {force = false, reason} = opts;
this.log.debug(`Cleaning up ${util.pluralize('active session', sessionsCount, true)}`);
const cleanupPromises = force
? Object.values(this.sessions).map((drv) => drv.startUnexpectedShutdown(reason ? new Error(reason) : undefined))
: Object.keys(this.sessions).map((id) => this.deleteSession(id));
if (sessionsCount) {
this.log.debug(`Cleaning up ${util.pluralize('active session', sessionsCount, true)}`);
}
if (teardowns.length) {
this.log.debug(`Waiting for ${util.pluralize('session', teardowns.length, true)} to finish deleting`);
}
const cleanupPromises = [
...(force
? Object.values(this.sessions).map((drv) => drv.startUnexpectedShutdown(reason ? new Error(reason) : undefined))
: Object.keys(this.sessions).map((id) => this.deleteSession(id))),
...teardowns,
];
for (const cleanupPromise of cleanupPromises) {
try {
await cleanupPromise;
@@ -561,12 +569,7 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
* session (or sessionless when `sessionId` is null).
*/
pluginsToHandleCmd(cmd: string, sessionId: string | null = null): Plugin[] {
// to handle a given command, a plugin should either implement that command as a plugin
// instance method or it should implement a generic 'handle' method
return this.pluginsForSession(sessionId).filter((p) => {
const pluginMethod = (p as Plugin & Record<string, unknown>)[cmd];
return typeof pluginMethod === 'function' || typeof p.handle === 'function';
});
return this.pluginsForSession(sessionId).filter((p) => canHandleCmd(p, cmd));
}
/**
@@ -626,8 +629,12 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
}
}
// Each createSession call gets its own plugin instances, so that concurrent calls do not share them
const newSessionPlugins = cmd === CREATE_SESSION_COMMAND ? this.createPluginInstances() : undefined;
const sessionTracker = newSessionPlugins?.length ? this.createSessionTracker() : undefined;
// get any plugins which are registered as handling this command
const plugins = this.pluginsToHandleCmd(cmd, sessionId);
const candidates = newSessionPlugins ?? this.pluginsForSession(sessionId);
const plugins = candidates.filter((p) => canHandleCmd(p, cmd));
// now we define a 'cmdHandledBy' object which will keep track of which plugins have handled this
// command. we care about this because (a) multiple plugins can handle the same command, and
@@ -691,7 +698,7 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
args,
plugins,
cmdHandledBy,
next: defaultBehavior,
next: sessionTracker?.wrap(defaultBehavior) ?? defaultBehavior,
});
// clear the ambient proxy request while the plugin/default chain runs, so a plugin that
// re-enters executeCommand for a different command doesn't inherit and misuse this one
@@ -705,18 +712,20 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
this.logPluginHandlerReport(plugins, {cmd, cmdHandledBy});
// And finally, if the command was createSession, we want to migrate any plugins which were
// previously sessionless to use the new sessionId, so that plugins can share state between
// their createSession method and other instance methods
if (cmd === CREATE_SESSION_COMMAND && this.sessionlessPlugins.length && !res.error) {
const newSessionId = (res.value as unknown[])[0] as string;
this.log.info(
`Promoting ${this.sessionlessPlugins.length} sessionless plugins to be attached ` +
`to session ID ${newSessionId}`,
);
this.sessionPlugins[newSessionId] = this.sessionlessPlugins;
const promoted = this.sessionPlugins[newSessionId] as (Plugin & ExtensionCore)[];
for (const p of promoted) {
// And finally, if the command was createSession, we want to attach its plugin instances to the
// new sessionId, so that plugins can share state between their createSession method and other
// instance methods
if (newSessionPlugins?.length) {
const newSessionId =
!res.error && Array.isArray(res.value) && typeof res.value[0] === 'string' ? res.value[0] : undefined;
await sessionTracker?.settle(newSessionId);
if (!newSessionId) {
res.error ??= new Error('A createSession plugin did not return a session ID');
return res;
}
this.log.info(`Attaching ${newSessionPlugins.length} plugins to session ID ${newSessionId}`);
this.sessionPlugins[newSessionId] = newSessionPlugins;
for (const p of newSessionPlugins as (Plugin & ExtensionCore)[]) {
if (typeof p.updateLogPrefix === 'function') {
p.updateLogPrefix(`${generateDriverLogPrefix(p)} <${generateDriverLogPrefix(this.sessions[newSessionId])}>`);
}
@@ -724,7 +733,6 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
const extPlugin = p as unknown as IpcAssignable;
await extPlugin.assignIpc(this.sessionIpcs[newSessionId]);
}
this.sessionlessPlugins = [];
}
return res;
@@ -805,15 +813,17 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
/** Runs the wrapped plugin chain and merges the result into a `SessionHandlerResult` shape. */
async executeWrappedCommand(wrappedCmd: () => Promise<unknown>): Promise<SessionHandlerResult<unknown>> {
let cmdRes: unknown;
let cmdErr: unknown;
const res: SessionHandlerResult<unknown> = {};
try {
// At this point, `wrappedCmd` defines a whole sequence of plugin handlers, culminating in
// our default handler. Whatever it returns is what we're going to want to send back to the
// user.
cmdRes = await wrappedCmd();
} catch (e) {
cmdErr = e;
} catch (error) {
return markResponseEnvelope({
error: error instanceof Error ? error : new Error(String(error)),
protocol: PROTOCOLS.W3C,
});
}
// A marked envelope or a returned Error is passed through. `{protocol: 'W3C', value}` is data.
@@ -821,7 +831,6 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
Object.assign(res, cmdRes);
} else {
res.value = cmdRes;
res.error = cmdErr instanceof Error ? cmdErr : undefined;
res.protocol = PROTOCOLS.W3C;
}
return markResponseEnvelope(res);
@@ -845,11 +854,61 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
return typeof dstSession?.canProxy === 'function' && dstSession.canProxy(sessionId);
}
private async cleanupFailedSession(sessionId: string): Promise<void> {
try {
// Stop the idle timer even if the driver's deleteSession fails before clearing it.
try {
await this.sessions[sessionId]?.clearNewCommandTimeout();
} finally {
await this.deleteSession(sessionId);
}
} catch (cleanupError) {
const message = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
this.log.warn(`Could not clean up failed session ${sessionId}: ${message}`);
}
}
private deleteLinkedSessionObjects(sessionId: string): void {
delete this.sessions[sessionId];
delete this.sessionPlugins[sessionId];
delete this.sessionIpcs[sessionId];
}
private createSessionTracker() {
const createdSessionIds = new Set<string>();
let settled = false;
const cleanupIfRegistered = async (id: string) => {
if (this.sessionExists(id)) {
await this.cleanupFailedSession(id);
}
};
return {
wrap: (next: () => Promise<unknown>) => async () => {
const result = (await next()) as SessionHandlerCreateResult;
const id = result.value?.[0];
if (id) {
if (settled) {
// An unawaited next() may finish after the client has received a response.
await cleanupIfRegistered(id);
} else {
createdSessionIds.add(id);
}
}
return result;
},
settle: async (returnedId: string | undefined) => {
settled = true;
// A retry may create several sessions, but only one is returned to the client.
for (const id of createdSessionIds) {
if (id !== returnedId) {
await cleanupIfRegistered(id);
}
}
},
};
}
}
/**
@@ -869,6 +928,13 @@ export class NoDriverProxyCommandError extends Error {
}
}
// to handle a given command, a plugin should either implement that command as a plugin
// instance method or it should implement a generic 'handle' method
function canHandleCmd(plugin: Plugin, cmd: string): boolean {
const pluginMethod = (plugin as Plugin & Record<string, unknown>)[cmd];
return typeof pluginMethod === 'function' || typeof plugin.handle === 'function';
}
/** True if `cmd` should run on the umbrella driver instead of only on the session’s inner driver. */
function isAppiumDriverCommand(cmd: string): boolean {
return (
+26 -18
View File
@@ -2,7 +2,7 @@
import type {Class, DriverType, ExtensionType, PluginType} from '@appium/types';
import type {Args, CliExtensionCommand, CliExtensionSubcommand} from 'appium/types/index.js';
import {DRIVER_TYPE, PLUGIN_TYPE} from '../constants.js';
import {DRIVER_TYPE, EXT_SUBCOMMAND_RUN, PLUGIN_TYPE} from '../constants.js';
import type {ExtensionConfig} from '../extension/extension-config.js';
import {reloadManifest} from '../extension/index.js';
import {isExtensionCommandArgs} from '../schema/cli-args-guards.js';
@@ -46,24 +46,32 @@ export async function runExtensionCommand<Cmd extends CliExtensionCommand, SubCm
// Serialize this against any other `driver`/`plugin` CLI command running (in this or another
// process) against the same `APPIUM_HOME`, so concurrent commands can't race to read, mutate,
// and write the same extension manifest out from under each other.
const prepare = async () => {
// Refresh from disk while holding the lock, in case another process wrote to the manifest
// between this process's startup read and now, and revalidate so derived state (installed
// extensions, pending validation summary, duplicate-automationName tracking) is current too.
await reloadManifest(config.manifest);
const CommandClass = commandClasses[type] as ExtCommand<Cmd>;
const cmd = new CommandClass({config, json} as any);
cmd.printPendingValidationSummary();
return cmd;
};
const execute = async (cmd: Awaited<ReturnType<typeof prepare>>) => {
const jsonResult = (await cmd.execute(args)) as Record<string, unknown>;
if (json && !suppressOutput) {
console.log(JSON.stringify(jsonResult, null, JSON_SPACES));
}
return jsonResult;
};
try {
return await withManifestLock<Record<string, unknown>>(config.appiumHome, async () => {
// Refresh from disk while holding the lock, in case another process wrote to the manifest
// between this process's startup read and now, and revalidate so derived state (installed
// extensions, pending validation summary, duplicate-automationName tracking) is current too.
await reloadManifest(config.manifest);
const CommandClass = commandClasses[type] as ExtCommand<Cmd>;
const cmd = new CommandClass({config, json} as any);
cmd.printPendingValidationSummary();
const jsonResult = (await cmd.execute(args)) as Record<string, unknown>;
if (json && !suppressOutput) {
console.log(JSON.stringify(jsonResult, null, JSON_SPACES));
}
return jsonResult;
});
// `run` only reads the manifest and may be long-running (e.g. a tunnel), so it must not
// hold the lock while the script runs or it would block server startup.
if ((args as unknown as Record<string, unknown>)[`${type}Command`] === EXT_SUBCOMMAND_RUN) {
return await execute(await withManifestLock(config.appiumHome, prepare));
}
return await withManifestLock(config.appiumHome, async () => await execute(await prepare()));
} catch (err) {
// in the suppress output case, we are calling this function internally and should
// just throw instead of printing an error and ending the process
+14 -14
View File
@@ -1,6 +1,6 @@
{
"name": "appium",
"version": "4.0.0",
"version": "4.0.2",
"gitHead": "f7b20335eab4022e5cbbb627ec86866a994444f8",
"description": "Automation for Apps.",
"keywords": [
@@ -65,27 +65,27 @@
"test:unit": "node --test --experimental-test-module-mocks --test-concurrency=1 --enable-source-maps --test-timeout=5000 \"./build/test/unit/**/*.spec.js\""
},
"dependencies": {
"@appium/base-driver": "11.0.0",
"@appium/base-plugin": "4.0.0",
"@appium/docutils": "4.0.0",
"@appium/http-server": "1.0.0",
"@appium/base-driver": "11.0.2",
"@appium/base-plugin": "4.0.2",
"@appium/docutils": "4.0.2",
"@appium/http-server": "1.0.2",
"@appium/logger": "3.0.0",
"@appium/schema": "2.0.0",
"@appium/support": "8.0.0",
"@appium/types": "2.0.0",
"@appium/support": "8.0.2",
"@appium/types": "3.0.0",
"@sidvind/better-ajv-errors": "7.0.0",
"ajv": "8.20.0",
"ajv-formats": "3.0.1",
"argparse": "3.0.3",
"asyncbox": "6.6.0",
"axios": "1.20.0",
"lilconfig": "3.1.4",
"argparse": "3.0.4",
"asyncbox": "7.1.0",
"axios": "1.21.1",
"lilconfig": "3.1.5",
"lru-cache": "11.5.3",
"normalize-package-data": "9.0.0",
"semver": "7.8.5",
"teen_process": "4.2.1",
"semver": "7.8.6",
"teen_process": "5.0.1",
"winston": "3.19.0",
"ws": "8.22.0",
"ws": "8.23.0",
"yaml": "2.9.1",
"yocto-spinner": "1.2.2"
},
@@ -1,5 +1,5 @@
{
"devDependencies": {
"webdriverio": "9.32.0"
"webdriverio": "10.2.0"
}
}
@@ -528,6 +528,100 @@ describe('AppiumDriver', function () {
// cleanup, since we faked the delete session call
await (mockFakeDriver as any).object.deleteSession();
});
it('should stop routing to the session while the inner driver deletes it', async function () {
const [sessionId] = (await appium.createSession(W3C_CAPS)).value!;
let finish!: () => void;
const pending = new Promise<void>((resolve) => {
finish = resolve;
});
const originalDeleteSession = fakeDriver.deleteSession.bind(fakeDriver);
const innerDeleteSession = sandbox.stub(fakeDriver, 'deleteSession').callsFake(async (id) => {
await pending;
await originalDeleteSession(id);
});
const deletion = appium.deleteSession(sessionId);
try {
assert.strictEqual(appium.sessionExists(sessionId), false);
await assert.rejects(appium.executeCommand('getPageSource', sessionId), /does not exist/);
const {error} = await appium.deleteSession(sessionId);
assert.match(error!.message, /Session not found/);
assert.strictEqual(innerDeleteSession.callCount, 1);
} finally {
finish();
assert.strictEqual((await deletion).error, undefined);
}
});
it('should keep the session removed when the inner driver fails to delete it', async function () {
const [sessionId] = (await appium.createSession(W3C_CAPS)).value!;
sandbox.stub(fakeDriver, 'deleteSession').rejects(new Error('teardown failed'));
try {
const {error} = await appium.deleteSession(sessionId);
assert.match(error!.message, /teardown failed/);
assert.strictEqual(appium.sessionExists(sessionId), false);
await assert.rejects(appium.executeCommand('getPageSource', sessionId), /does not exist/);
} finally {
await fakeDriver.clearNewCommandTimeout();
}
});
it('should wait for a session that is being deleted before overriding it', async function () {
appium.args.sessionOverride = true;
const oldDriver = new FakeDriver();
(appium as any).sessions['old-session'] = oldDriver;
let finish!: () => void;
const pending = new Promise<void>((resolve) => {
finish = resolve;
});
const events: string[] = [];
sandbox.stub(oldDriver, 'deleteSession').callsFake(async () => {
await pending;
events.push('old session deleted');
});
mockFakeDriver
.expects('createSession')
.once()
.callsFake(async () => {
events.push('new session created');
return [SESSION_ID, {...BASE_CAPS}];
});
const deletion = appium.deleteSession('old-session');
const creation = appium.createSession(W3C_CAPS);
try {
await new Promise((resolve) => setImmediate(resolve));
assert.deepStrictEqual(events, []);
} finally {
finish();
}
assert.strictEqual((await deletion).error, undefined);
assert.strictEqual((await creation).error, undefined);
assert.deepStrictEqual(events, ['old session deleted', 'new session created']);
await appium.deleteSession(SESSION_ID);
});
it('should wait for a session that is being deleted when the server shuts down', async function () {
const [sessionId] = (await appium.createSession(W3C_CAPS)).value!;
let finish!: () => void;
const pending = new Promise<void>((resolve) => {
finish = resolve;
});
const originalDeleteSession = fakeDriver.deleteSession.bind(fakeDriver);
const innerDeleteSession = sandbox.stub(fakeDriver, 'deleteSession').callsFake(async (id) => {
await pending;
await originalDeleteSession(id);
});
const deletion = appium.deleteSession(sessionId);
let isShutDown = false;
const shutdown = appium.shutdown().then(() => {
isShutDown = true;
});
try {
await new Promise((resolve) => setImmediate(resolve));
assert.strictEqual(isShutDown, false);
} finally {
finish();
}
await shutdown;
assert.strictEqual((await deletion).error, undefined);
assert.strictEqual(innerDeleteSession.callCount, 1);
});
});
describe('executeCommand', function () {
let appium: InstanceType<typeof AppiumModule.AppiumDriver>;
@@ -710,6 +804,246 @@ describe('AppiumDriver', function () {
await fakeDriver.clearNewCommandTimeout();
}
});
it('should keep the plugin instances of concurrently created sessions apart', async function () {
const releases = new Map<string, () => void>();
let markStarted!: () => void;
const started = new Promise<void>((resolve) => {
markStarted = resolve;
});
class SessionStatePlugin extends BasePlugin {
deviceNames: string[] = [];
async createSession(next: () => Promise<unknown>, driver: unknown, caps: W3CCapabilities<Constraints>) {
const deviceName = caps.alwaysMatch?.['appium:deviceName'] as string;
this.deviceNames.push(deviceName);
await new Promise<void>((resolve) => {
releases.set(deviceName, resolve);
if (releases.size === 2) {
markStarted();
}
});
return await next();
}
}
class ProbeDriver extends BaseDriver<Constraints> {}
(appium as any).driverConfig = {
findMatchingDriver: sandbox.stub().returns({driver: ProbeDriver, version: '1.2.3', driverName: 'probe'}),
};
setPluginClassesForTest(appium, new Map<any, string>([[SessionStatePlugin, 'state']]));
const caps = (deviceName: string) => ({
alwaysMatch: {...W3C_CAPS.alwaysMatch, 'appium:deviceName': deviceName, 'appium:newCommandTimeout': 0},
firstMatch: [{}],
});
const first = appium.executeCommand('createSession', caps('first'));
const second = appium.executeCommand('createSession', caps('second'));
await started;
releases.get('second')!();
const [secondId] = (await second).value as [string];
releases.get('first')!();
const [firstId] = (await first).value as [string];
try {
for (const [sessionId, deviceName] of [
[firstId, 'first'],
[secondId, 'second'],
]) {
const [plugin] = appium.pluginsForSession(sessionId) as SessionStatePlugin[];
assert.deepStrictEqual(plugin.deviceNames, [deviceName]);
}
} finally {
await appium.deleteSession(firstId);
await appium.deleteSession(secondId);
}
});
for (const throwsError of [true, false]) {
it(`should delete a session when a plugin throws ${throwsError ? 'an Error' : 'a string'} after creating it`, async function () {
const failure = throwsError ? new Error('plugin setup failed') : 'plugin setup failed';
let createdSessionId: string | null = null;
class FailingPlugin extends BasePlugin {
async createSession(next: () => Promise<unknown>) {
await next();
createdSessionId = fakeDriver.sessionId;
throw failure;
}
}
setPluginClassesForTest(appium, new Map([[FailingPlugin, 'failing']]));
delete appium.sessions[SESSION_ID]; // Remove the placeholder from the executeCommand fixture.
const deleteSession = sandbox.spy(fakeDriver, 'deleteSession');
const caps = {
...W3C_CAPS,
alwaysMatch: {...W3C_CAPS.alwaysMatch, 'appium:newCommandTimeout': 0},
};
try {
const result = await appium.executeCommand('createSession', caps);
if (failure instanceof Error) {
assert.strictEqual(result.error, failure);
} else {
assert.strictEqual(result.error?.message, failure);
}
assert.ok(createdSessionId, 'the inner driver must create a session before the plugin fails');
assert.strictEqual(appium.sessionExists(createdSessionId), false);
assert.strictEqual(appium.sessionIpcs[createdSessionId], undefined);
assert.strictEqual(fakeDriver.sessionId, null);
assert.deepStrictEqual(deleteSession.args, [[createdSessionId]]);
} finally {
if (createdSessionId && appium.sessionExists(createdSessionId)) {
await appium.deleteSession(createdSessionId);
}
}
});
}
it('should delete a session when driver startup finishes after the plugin fails', async function () {
const failure = new Error('plugin setup failed');
const startupEntered = Promise.withResolvers<void>();
const releaseStartup = Promise.withResolvers<void>();
let pendingStartup: Promise<unknown> | undefined;
class FailingPlugin extends BasePlugin {
async createSession(next: () => Promise<unknown>) {
pendingStartup = next();
await startupEntered.promise;
throw failure;
}
}
setPluginClassesForTest(appium, new Map([[FailingPlugin, 'failing']]));
delete appium.sessions[SESSION_ID];
const createSession = fakeDriver.createSession.bind(fakeDriver);
sandbox.stub(fakeDriver, 'createSession').callsFake(async (caps) => {
startupEntered.resolve();
await releaseStartup.promise;
return await createSession(caps);
});
const deleteSession = sandbox.spy(fakeDriver, 'deleteSession');
const caps = {
...W3C_CAPS,
alwaysMatch: {...W3C_CAPS.alwaysMatch, 'appium:newCommandTimeout': 0},
};
try {
const result = await appium.executeCommand('createSession', caps);
assert.strictEqual(result.error, failure);
assert.strictEqual(deleteSession.callCount, 0);
assert.ok(pendingStartup);
releaseStartup.resolve();
const {value} = (await pendingStartup) as {value: [string]};
const [sessionId] = value;
assert.strictEqual(appium.sessionExists(sessionId), false);
assert.strictEqual(appium.sessionIpcs[sessionId], undefined);
assert.strictEqual(appium.sessionPlugins[sessionId], undefined);
assert.strictEqual(fakeDriver.sessionId, null);
assert.deepStrictEqual(deleteSession.args, [[sessionId]]);
} finally {
releaseStartup.resolve();
await pendingStartup;
if (fakeDriver.sessionId && appium.sessionExists(fakeDriver.sessionId)) {
await appium.deleteSession(fakeDriver.sessionId);
}
}
});
for (const retryFails of [true, false]) {
it(`should delete the first session when a plugin retry ${retryFails ? 'fails' : 'succeeds'}`, async function () {
class RetryingPlugin extends BasePlugin {
async createSession(next: () => Promise<unknown>) {
await next();
return await next();
}
}
const retryDriver = new FakeDriver();
const retryError = new Error('retry driver failed to start');
if (retryFails) {
sandbox.stub(retryDriver, 'createSession').rejects(retryError);
}
const driverMatch = (driver: FakeDriver) => ({
driver: function Driver() {
return driver;
},
version: '1.2.3',
driverName: 'fake',
});
(appium as any).driverConfig = {
findMatchingDriver: sandbox
.stub()
.onFirstCall()
.returns(driverMatch(fakeDriver))
.onSecondCall()
.returns(driverMatch(retryDriver)),
};
setPluginClassesForTest(appium, new Map([[RetryingPlugin, 'retrying']]));
delete appium.sessions[SESSION_ID];
const firstStartup = sandbox.spy(fakeDriver, 'createSession');
const deleteFirstSession = sandbox.spy(fakeDriver, 'deleteSession');
const deleteRetrySession = sandbox.spy(retryDriver, 'deleteSession');
const caps = {
...W3C_CAPS,
alwaysMatch: {...W3C_CAPS.alwaysMatch, 'appium:newCommandTimeout': 0},
};
try {
const result = await appium.executeCommand('createSession', caps);
const [firstId] = await firstStartup.returnValues[0];
if (retryFails) {
assert.strictEqual(result.error, retryError);
assert.deepStrictEqual(Object.keys(appium.sessions), []);
} else {
const [returnedId] = result.value as [string];
assert.strictEqual(returnedId, retryDriver.sessionId);
assert.notStrictEqual(returnedId, firstId);
assert.strictEqual(appium.sessions[returnedId], retryDriver);
assert.ok(appium.sessionIpcs[returnedId]);
assert.ok(appium.sessionPlugins[returnedId][0] instanceof RetryingPlugin);
}
assert.strictEqual(appium.sessionExists(firstId), false);
assert.strictEqual(appium.sessionIpcs[firstId], undefined);
assert.strictEqual(appium.sessionPlugins[firstId], undefined);
assert.deepStrictEqual(deleteFirstSession.args, [[firstId]]);
assert.strictEqual(deleteRetrySession.callCount, 0);
} finally {
for (const id of Object.keys(appium.sessions)) {
await appium.deleteSession(id);
}
}
});
}
it('should not reuse the plugin instances of a failed createSession', async function () {
class SessionStatePlugin extends BasePlugin {
deviceNames: string[] = [];
async createSession(next: () => Promise<unknown>, driver: unknown, caps: W3CCapabilities<Constraints>) {
this.deviceNames.push(caps.alwaysMatch?.['appium:deviceName'] as string);
return await next();
}
}
class FailingDriver extends BaseDriver<Constraints> {
override async createSession(): Promise<never> {
throw new Error('cannot start the session');
}
}
class ProbeDriver extends BaseDriver<Constraints> {}
(appium as any).driverConfig = {
findMatchingDriver: sandbox
.stub()
.onFirstCall()
.returns({driver: FailingDriver, version: '1.2.3', driverName: 'probe'})
.onSecondCall()
.returns({driver: ProbeDriver, version: '1.2.3', driverName: 'probe'}),
};
setPluginClassesForTest(appium, new Map<any, string>([[SessionStatePlugin, 'state']]));
const caps = (deviceName: string) => ({
alwaysMatch: {...W3C_CAPS.alwaysMatch, 'appium:deviceName': deviceName, 'appium:newCommandTimeout': 0},
firstMatch: [{}],
});
const failed = await appium.executeCommand('createSession', caps('failing'));
assert.match(failed.error!.message, /cannot start the session/);
const [sessionId] = (await appium.executeCommand('createSession', caps('working'))).value as [string];
try {
const [plugin] = appium.pluginsForSession(sessionId) as SessionStatePlugin[];
assert.deepStrictEqual(plugin.deviceNames, ['working']);
} finally {
await appium.deleteSession(sessionId);
}
});
});
describe('configureDriverFeatures', function () {
let appium: InstanceType<typeof AppiumModule.AppiumDriver>;
@@ -108,6 +108,25 @@ describe('runExtensionCommand', function () {
assert.strictEqual(await fs.exists(lockFile), false);
});
it('does not hold the manifest lock while a `run` command executes', async function () {
const {driverConfig} = await loadExtensions(appiumHome);
const lockFile = await resolveManifestLockfilePath(appiumHome);
let lockExistedDuringRun: boolean | undefined;
const executeMock = mock.method(FakeExtensionCommand.prototype, 'execute', async () => {
lockExistedDuringRun = existsSync(lockFile);
return {};
});
try {
await runExtensionCommand(
{subcommand: DRIVER_TYPE, driverCommand: 'run', suppressOutput: true} as any,
driverConfig,
);
} finally {
executeMock.mock.restore();
}
assert.strictEqual(lockExistedDuringRun, false);
});
it('still releases the lock when the command throws', async function () {
const {driverConfig} = await loadExtensions(appiumHome);
const lockFile = await resolveManifestLockfilePath(appiumHome);
+10
View File
@@ -0,0 +1,10 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## 1.1.0 (2026-11-27)
### Features
* **archward:** add package that checks a package against its C4 model ([#23225](https://github.com/appium/appium/issues/23225)) ([67f151f](https://github.com/appium/appium/commit/67f151f6f3520f7d86c48d1ea52fefc9a51313bb))
+159
View File
@@ -0,0 +1,159 @@
# @appium/archward
> Checks a package's source against its [C4](https://c4model.com) architecture model
## Summary
Keeps a package's architecture honest. The architecture is written once, as text, in a
[LikeC4](https://likec4.dev) model that lives next to the package. `archward` compares the actual
imports against it and fails on:
- an import between components that the model does not declare (domain leaks);
- import cycles, reported separately for runtime and type-only imports;
- source files that no component owns (or that several do);
- optionally, deep imports of scoped packages (e.g. `@appium/support/lib/fs.js`; a subpath is fine
if the installed package lists it in its `exports`, e.g. `@appium/oxc-config/oxlint`), and
imports of packages that are not declared in `package.json`.
Known violations are frozen in a baseline, so a package can adopt the check without fixing
everything first. New violations fail, and baseline entries that are fixed must be removed, so the
baseline can only shrink.
## Usage
```bash
npm install --save-dev @appium/archward
npx archward init [packageDir] # scaffold architecture/ from the current code
npx archward [packageDir...] # check (default: current directory)
npx archward --workspaces [rootDir] # check the workspace packages that have a model
npx archward --update-baseline # tolerate all current violations
npx archward --verbose # list every finding
```
`init` also takes `--source-root <dir>` and `--entry-point-scope <scope>` (repeatable); they are
saved to `config.json`.
Exit code: `0` ok, `1` violations found, `2` usage or runtime error. Relative imports that cannot be
resolved are reported as warnings, as they cannot be checked. `typescript` (5 or 6) must be
installed, as imports are resolved with the package's `tsconfig.json`.
### Getting started
`archward init` creates `architecture/` from the code as it is: one component per top-level
directory and per root file of the source root (`lib`, or `src` if `lib` holds build output; use
`--source-root` to override), allowed dependencies taken from the current imports, and a baseline
for the existing cycles. Then:
1. Edit `model.c4`: delete the dependencies that should not be allowed, merge or rename components,
add descriptions. Run `archward --update-baseline` to tolerate the violations this creates.
2. Run `archward` in CI.
3. Tell agents about the model, see [AI agents](#ai-agents) (`init` prints a ready snippet).
In a monorepo, run `init` in each package, and `archward --workspaces .` from the root.
### Files
The package being checked holds an `architecture/` directory:
| File | Purpose |
|---|---|
| `*.c4` | The LikeC4 model: components, the paths they own, and the dependencies they may have. |
| `baseline.json` | Tolerated violations. Written by `--update-baseline`; each entry may carry a `reason`. |
| `config.json` | Optional settings, see below. |
### The model
Each component declares the files it owns through `metadata.paths` (globs relative to the package,
`*` and `**` supported). Relationships between components are the **allowed** dependencies:
```
specification {
element container
element component
}
model {
app = container 'my-package' {
cli = component 'cli' {
metadata { paths 'lib/cli/**' }
}
utils = component 'utils' {
metadata { paths 'lib/utils/**' }
}
}
app.cli -> app.utils
}
```
Every file under the source root must belong to exactly one component; a file that matches no
component, or several, is an error. Components tagged `#unenforced` (declare `tag unenforced` in the
specification) still own their files, but their dependencies are not checked. Elements without
`metadata.paths` (systems, actors, ...) are for diagrams only. Preview the diagrams with `npx likec4 start architecture`.
### `architecture/config.json`
| Option | Default | Description |
|---|---|---|
| `sourceRoot` | `lib` | Directory to check, relative to the package. |
| `tsconfig` | `tsconfig.json` | Used to resolve imports. |
| `entryPointScopes` | `[]` | npm scopes (e.g. `["@appium"]`) whose packages must be declared in `package.json` and imported through their entry points only (a subpath the installed package lists in its `exports` is allowed). A `devDependency` is enough for `import type`. |
| `typeOnlyCycles` | `error` | `ignore` to stop reporting cycles that exist only through `import type`. They have no runtime effect, and patterns such as command mixins that reference their driver's type produce hundreds of them. Runtime cycles are always reported. |
| `undeclaredDependencies` | `ignore` | `error` to require every package the source imports to be declared in `package.json` (`dependencies`, `peerDependencies` or `optionalDependencies`; a `devDependency` is enough for `import type`), so nothing works only because of hoisting. Built-ins, relative and `#` imports, the package itself and tsconfig `paths` aliases are exempt. Without it, only packages in `entryPointScopes` are checked. |
Unknown options are rejected.
### Baseline
`baseline.json` lists tolerated violations: `boundaries` (`from`/`to` files), and `cycles`
(`runtime` and `typeOnly`, each a list of files). Unowned files and package-import violations cannot
be baselined; they are cheap to fix, and `--update-baseline` warns when it finds any. Treat changes to it like changes to the model:
adding an entry accepts a violation, so it deserves review.
## AI agents
The model is only a single source of truth if agents read it and keep it current. A project that
adopts `archward` must say so in its `AGENTS.md` (or equivalent), so that agents:
- read the model before adding or moving code, and put new code in the component that owns it;
- run `archward` before finishing, as CI does;
- update the model in the same change when a component, path or dependency legitimately changes,
and explain why in the PR description;
- never loosen the model or the baseline to silence a failure, and only ever remove baseline entries
as they get fixed.
A snippet to adapt (replace `packages/foo`):
```markdown
## Architecture
`packages/foo/architecture/*.c4` is the source of truth for the component boundaries of
`packages/foo`. CI runs `npx archward packages/foo`.
- Before adding or moving code, find the owning component (`metadata.paths`) and respect its
allowed dependencies. New files must be covered by a component's `paths`.
- Fix a failing check by changing the code. Do not add edges to the model or entries to
`baseline.json` to make it pass, unless the new dependency is intended; then update the `.c4`
files in the same change and explain why in the PR description.
- Remove `baseline.json` entries when you fix the violation they cover.
- Keep component descriptions and the paths they own in sync with the code.
```
Agents can also query the model directly: `npx likec4 mcp architecture` starts an MCP server for it.
## API
```ts
import {checkPackage, formatReport} from '@appium/archward';
const result = await checkPackage('path/to/package');
console.log(formatReport(result));
process.exitCode = result.ok ? 0 : 1;
```
Also exported: `updateBaseline(dir)`, `initPackage(dir, options)`, `findWorkspacePackages(rootDir)` and
`loadConfig(dir)`, plus the result types.
## License
Apache-2.0
@@ -0,0 +1,7 @@
{
"boundaries": [],
"cycles": {
"runtime": [],
"typeOnly": []
}
}
+79
View File
@@ -0,0 +1,79 @@
// Architecture of @appium/archward, checked by `archward` itself (see ../README.md).
// Each component owns the files in `metadata.paths`; each `a -> b` ALLOWS a to import b.
model {
archward = container '@appium/archward' {
api = component 'index.ts' {
description 'Public programmatic entry point; re-exports only.'
metadata { paths 'lib/index.ts' }
}
cli = component 'cli.ts' {
description 'Argument parsing, exit codes and printing for the `archward` command.'
metadata { paths 'lib/cli.ts' }
}
check = component 'check.ts' {
description 'Runs one package check: analysis, baseline comparison and baseline updates.'
metadata { paths 'lib/check.ts' }
}
analysis = component 'analysis' {
description 'Reads the model and the import graph; finds boundary, cycle and package-import violations.'
metadata { paths 'lib/analysis/**' }
}
init = component 'init' {
description 'Derives a starting model and baseline from the current code (`archward init`).'
metadata { paths 'lib/init/**' }
}
baseline = component 'baseline.ts' {
description 'Reads, writes and diffs the tolerated-violations baseline.'
metadata { paths 'lib/baseline.ts' }
}
config = component 'config.ts' {
description 'Loads and validates `architecture/config.json`.'
metadata { paths 'lib/config.ts' }
}
report = component 'report.ts' {
description 'Formats check results for humans.'
metadata { paths 'lib/report.ts' }
}
workspaces = component 'workspaces.ts' {
description 'Finds the packages of an npm workspaces monorepo.'
metadata { paths 'lib/workspaces.ts' }
}
types = component 'types.ts' {
description 'Shared types. Depends on nothing.'
metadata { paths 'lib/types.ts' }
}
util = component 'util.ts' {
description 'Small dependency-free helpers.'
metadata { paths 'lib/util.ts' }
}
}
archward.cli -> archward.check
archward.cli -> archward.init
archward.cli -> archward.report
archward.cli -> archward.workspaces
archward.api -> archward.check
archward.api -> archward.config
archward.api -> archward.init
archward.api -> archward.report
archward.api -> archward.types
archward.api -> archward.workspaces
archward.check -> archward.analysis
archward.check -> archward.baseline
archward.check -> archward.config
archward.check -> archward.types
archward.check -> archward.util
archward.init -> archward.analysis
archward.init -> archward.check
archward.init -> archward.config
archward.init -> archward.types
archward.init -> archward.util
archward.analysis -> archward.types
archward.analysis -> archward.util
archward.baseline -> archward.config
archward.baseline -> archward.types
archward.baseline -> archward.util
archward.config -> archward.types
archward.report -> archward.types
archward.workspaces -> archward.config
}
+6
View File
@@ -0,0 +1,6 @@
specification {
element container
element component
// Tag a component #unenforced to document it without checking its dependencies.
tag unenforced
}
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env node
// @ts-check
import {main} from '../build/lib/cli.js';
process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,77 @@
import type {IModule} from 'dependency-cruiser';
import type {ImportedBoundary} from '../types.js';
import {boundaryKey, byString} from '../util.js';
import type {Ownership} from './model.js';
export interface BoundaryContext {
/** Source root with a trailing slash, e.g. `lib/`. */
prefix: string;
ownership: Ownership;
/** Allowed `from -> to` component edges. */
allowed: ReadonlySet<string>;
}
export interface BoundaryResult {
/** Source files that no component owns. */
unownedFiles: string[];
/** Imports between enforced components that the model does not allow. */
boundaries: ImportedBoundary[];
/** Allowed edges that no import uses. */
unusedEdges: string[];
}
/**
* Checks which component owns each source file and whether the imports between components are
* allowed. Files of `#unenforced` components are owned, but their imports are not checked.
* @throws if a file belongs to several components
*/
export function findBoundaries(modules: readonly IModule[], context: BoundaryContext): BoundaryResult {
const {prefix, ownership, allowed} = context;
const unownedFiles = new Set<string>();
const ambiguousFiles = new Set<string>();
const boundaries = new Map<string, ImportedBoundary>();
const usedEdges = new Set<string>();
const ownerOf = (file: string): string | undefined => {
const owners = ownership.ownersOf(file);
if (owners.length > 1) {
ambiguousFiles.add(`${file} (${owners.join(', ')})`);
}
return owners[0];
};
for (const mod of modules.filter((m) => m.source.startsWith(prefix))) {
const fromComponent = ownerOf(mod.source);
if (!fromComponent) {
unownedFiles.add(mod.source);
}
for (const dep of mod.dependencies) {
const toComponent = dep.resolved.startsWith(prefix) ? ownerOf(dep.resolved) : undefined;
if (
!fromComponent ||
!toComponent ||
fromComponent === toComponent ||
!ownership.componentIds.has(fromComponent) ||
!ownership.componentIds.has(toComponent)
) {
continue;
}
const edge = `${fromComponent} -> ${toComponent}`;
usedEdges.add(edge);
if (!allowed.has(edge)) {
const boundary = {from: mod.source, to: dep.resolved, fromComponent, toComponent};
boundaries.set(boundaryKey(boundary), boundary);
}
}
}
if (ambiguousFiles.size) {
const files = [...ambiguousFiles].sort(byString).slice(0, 10);
throw new Error(
`Each file must belong to exactly one component, but these match several:\n ${files.join('\n ')}`,
);
}
return {
unownedFiles: [...unownedFiles].sort(byString),
boundaries: [...boundaries.values()].sort((a, b) => byString(boundaryKey(a), boundaryKey(b))),
unusedEdges: [...allowed].filter((edge) => !usedEdges.has(edge)).sort(byString),
};
}
+35
View File
@@ -0,0 +1,35 @@
import {byString} from '../util.js';
import type {SourceGraph} from './graph.js';
export interface ClassifiedCycles {
runtimeCycles: string[];
/** Cycles that exist only through `import type`. */
typeOnlyCycles: string[];
}
/** Whether every import in the cycle exists at runtime (none is type-only). */
export function isRuntimeCycle(files: readonly string[], runtimeEdges: ReadonlySet<string>): boolean {
return files.every((file, i) => runtimeEdges.has(`${file} -> ${files[(i + 1) % files.length]}`));
}
/**
* Splits the cycles of the two graphs into runtime and type-only ones. A cycle of the type-inclusive
* graph that is made only of runtime imports is already covered by the runtime graph.
* @param typeOnlyCycles - `ignore` leaves the type-only list empty
*/
export function classifyCycles(
withTypes: SourceGraph,
runtime: SourceGraph,
typeOnlyCycles: 'error' | 'ignore',
): ClassifiedCycles {
const runtimeEdges = new Set(
runtime.modules.flatMap((m) => m.dependencies.map((d) => `${m.source} -> ${d.resolved}`)),
);
return {
runtimeCycles: [...runtime.cycles].sort(byString),
typeOnlyCycles:
typeOnlyCycles === 'ignore'
? []
: withTypes.cycles.filter((key) => !isRuntimeCycle(key.split(' > '), runtimeEdges)).sort(byString),
};
}
+52
View File
@@ -0,0 +1,52 @@
import {readFile} from 'node:fs/promises';
import path from 'node:path';
/**
* Whether a package's `exports` field makes `subpath` (e.g. `./oxlint`) importable.
* Supports exact keys and `*` patterns; a `null` target blocks the subpath.
*/
export function isExportedSubpath(exportsField: unknown, subpath: string): boolean {
if (typeof exportsField !== 'object' || exportsField === null || Array.isArray(exportsField)) {
return false;
}
const map = exportsField as Record<string, unknown>;
if (!Object.keys(map).some((key) => key.startsWith('.'))) {
return false; // conditions only: the root entry point is the sole export
}
if (subpath in map) {
return map[subpath] !== null;
}
const pattern = Object.keys(map)
.filter((key) => {
const star = key.indexOf('*');
return (
star !== -1 &&
subpath.length >= key.length &&
subpath.startsWith(key.slice(0, star)) &&
subpath.endsWith(key.slice(star + 1))
);
})
// Node's order: the longer prefix before `*` wins, then the longer key
.sort((a, b) => b.indexOf('*') - a.indexOf('*') || b.length - a.length)[0];
return pattern !== undefined && map[pattern] !== null;
}
/**
* Reads the `exports` field of an installed package, looking up `node_modules` from `fromDir`.
* @returns `undefined` if the package is not installed or declares no `exports`
*/
export async function readInstalledExports(fromDir: string, name: string): Promise<unknown> {
for (let dir = fromDir; ; dir = path.dirname(dir)) {
try {
const pkg = JSON.parse(await readFile(path.join(dir, 'node_modules', name, 'package.json'), 'utf8')) as {
exports?: unknown;
};
return pkg.exports;
} catch {
// not installed at this level; keep looking upwards
}
if (path.dirname(dir) === dir) {
return undefined;
}
}
}
+58
View File
@@ -0,0 +1,58 @@
import path from 'node:path';
import {cruise, type ICruiseResult, type IModule} from 'dependency-cruiser';
import type {ResolvedConfig} from '../types.js';
import {byString, cycleKey} from '../util.js';
export interface SourceGraph {
modules: IModule[];
/** Canonical keys of all import cycles. */
cycles: string[];
}
/**
* Extracts the import graph of the package's source root.
* @param typeImports - also follow type-only imports (they are erased at runtime)
*/
export async function cruiseSources(config: ResolvedConfig, typeImports: boolean): Promise<SourceGraph> {
const sourcePrefix = `${config.sourceRoot.replace(/\/$/, '')}/`;
const {output} = await cruise(
[config.sourceRoot],
{
baseDir: config.packageDir,
validate: true,
// Keep external imports in the graph, but do not crawl into them: workspace siblings resolve to
// their build output through symlinks, outside node_modules and outside the source root.
doNotFollow: {path: `^(?!${escapeRegExp(sourcePrefix)})`},
tsPreCompilationDeps: typeImports,
tsConfig: {fileName: path.join(config.packageDir, config.tsconfig)},
ruleSet: {forbidden: [{name: 'no-circular', severity: 'error', from: {}, to: {circular: true}}]},
},
{extensions: ['.ts', '.tsx', '.mts', '.cts', '.js', '.mjs', '.cjs']},
);
const result = output as ICruiseResult;
const cycles = result.summary.violations.flatMap((v) => (v.cycle ? [cycleKey(v.cycle.map((c) => c.name))] : []));
return {modules: result.modules, cycles: [...new Set(cycles)]};
}
/** Runs the two passes one after the other, so they never share dependency-cruiser's process-wide state. */
export async function cruiseBoth(config: ResolvedConfig): Promise<{withTypes: SourceGraph; runtime: SourceGraph}> {
const withTypes = await cruiseSources(config, true);
const runtime = await cruiseSources(config, false);
return {withTypes, runtime};
}
/** Relative imports that could not be resolved, as `file -> specifier`; they cannot be checked. */
export function findUnresolvedImports(modules: readonly IModule[]): string[] {
const unresolved = modules.flatMap((mod) =>
mod.dependencies
.filter((dep) => dep.couldNotResolve && dep.module.startsWith('.'))
.map((dep) => `${mod.source} -> ${dep.module}`),
);
return [...new Set(unresolved)].sort(byString);
}
function escapeRegExp(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
+50
View File
@@ -0,0 +1,50 @@
import {readdir} from 'node:fs/promises';
import type {Analysis, ResolvedConfig} from '../types.js';
import {findBoundaries} from './boundaries.js';
import {classifyCycles} from './cycles.js';
import {cruiseBoth, findUnresolvedImports} from './graph.js';
import {allowedEdges, buildOwnership, exportModel} from './model.js';
import {findPackageImports, readDeclaredDependencies} from './package-imports.js';
/**
* Finds everything in the package's source that the architecture model and the package rules
* object to, before the baseline is applied.
*/
export async function analyze(config: ResolvedConfig): Promise<Analysis> {
await assertModelExists(config.modelDir);
const [model, declared, {withTypes, runtime}] = await Promise.all([
exportModel(config.modelDir),
readDeclaredDependencies(config.packageDir),
cruiseBoth(config),
]);
const ownership = buildOwnership(model);
const prefix = `${config.sourceRoot}/`;
const {unownedFiles, boundaries, unusedEdges} = findBoundaries(withTypes.modules, {
prefix,
ownership,
allowed: allowedEdges(model, ownership.componentIds),
});
return {
unownedFiles,
boundaries,
unusedEdges,
packageImports: await findPackageImports(withTypes.modules, {
packageDir: config.packageDir,
prefix,
entryPointScopes: config.entryPointScopes,
undeclaredDependencies: config.undeclaredDependencies,
declared,
runtimeModules: runtime.modules,
}),
unresolvedImports: findUnresolvedImports(withTypes.modules.filter((m) => m.source.startsWith(prefix))),
...classifyCycles(withTypes, runtime, config.typeOnlyCycles),
};
}
async function assertModelExists(modelDir: string): Promise<void> {
const files = await readdir(modelDir).catch(() => [] as string[]);
if (!files.some((f) => f.endsWith('.c4'))) {
throw new Error(`No architecture model found: expected *.c4 files in ${modelDir}`);
}
}
+102
View File
@@ -0,0 +1,102 @@
import {execFile} from 'node:child_process';
import {existsSync, readFileSync} from 'node:fs';
import {mkdtemp, readFile, rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {promisify} from 'node:util';
import picomatch from 'picomatch';
import type {ArchitectureModel} from '../types.js';
const execFileAsync = promisify(execFile);
/** Components tagged with this are documented but not checked. */
export const UNENFORCED_TAG = 'unenforced';
export interface Ownership {
/** Ids of the enforced components (those that are not `#unenforced`). */
componentIds: Set<string>;
/** Ids of all components (enforced or not) whose paths match `file` (package-relative, `/`-separated). */
ownersOf: (file: string) => string[];
}
/** Exports the LikeC4 model in `modelDir` to JSON using the bundled `likec4` CLI. */
export async function exportModel(modelDir: string): Promise<ArchitectureModel> {
const tmp = await mkdtemp(path.join(tmpdir(), 'archward-'));
try {
const out = path.join(tmp, 'model.json');
await execFileAsync(process.execPath, [await findLikec4Bin(), 'export', 'json', modelDir, '-o', out]);
return parseModel(JSON.parse(await readFile(out, 'utf8')));
} catch (err) {
const stderr = (err as {stderr?: string}).stderr?.trim();
throw new Error(`Cannot export the architecture model in ${modelDir}: ${stderr || (err as Error).message}`, {
cause: err,
});
} finally {
await rm(tmp, {recursive: true, force: true});
}
}
/** Checks that the JSON exported by `likec4` has the shape this tool reads. */
export function parseModel(json: unknown): ArchitectureModel {
const model = json as Partial<ArchitectureModel> | null;
if (!model || typeof model.elements !== 'object' || typeof model.relations !== 'object') {
throw new Error("unexpected `likec4 export json` format: expected 'elements' and 'relations' objects");
}
return model as ArchitectureModel;
}
/** Maps source files to the components that own them (via `metadata.paths` globs). */
export function buildOwnership(model: ArchitectureModel): Ownership {
const components = Object.values(model.elements).filter((e) => e.kind === 'component' && e.metadata?.paths);
const matchers = components.map((c) => ({
id: c.id,
isMatch: picomatch([c.metadata?.paths ?? []].flat(), {dot: true}),
}));
return {
componentIds: new Set(components.filter((c) => !c.tags?.includes(UNENFORCED_TAG)).map((c) => c.id)),
ownersOf: (file) => matchers.filter((m) => m.isMatch(file)).map((m) => m.id),
};
}
/** The component -> component edges the model allows, as `from -> to` keys. */
export function allowedEdges(model: ArchitectureModel, componentIds: ReadonlySet<string>): Set<string> {
const edges = new Set<string>();
for (const {source, target} of Object.values(model.relations)) {
if (componentIds.has(source.model) && componentIds.has(target.model)) {
edges.add(`${source.model} -> ${target.model}`);
}
}
return edges;
}
/** Locates the `likec4` CLI script, without relying on its `exports` map. */
async function findLikec4Bin(): Promise<string> {
const dir = findPackageDir('likec4');
const {bin} = JSON.parse(await readFile(path.join(dir, 'package.json'), 'utf8')) as {
bin?: string | Record<string, string>;
};
const rel = typeof bin === 'string' ? bin : bin?.likec4;
if (!rel) {
throw new Error(`the 'likec4' package at ${dir} declares no 'likec4' executable`);
}
return path.resolve(dir, rel);
}
/** Walks up from the package's resolved entry point to its root directory. */
function findPackageDir(name: string): string {
let dir = path.dirname(fileURLToPath(import.meta.resolve(name)));
while (
!existsSync(path.join(dir, 'package.json')) ||
JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8')).name !== name
) {
const parent = path.dirname(dir);
if (parent === dir) {
throw new Error(`cannot locate the '${name}' package`);
}
dir = parent;
}
return dir;
}
@@ -0,0 +1,149 @@
import {readFile} from 'node:fs/promises';
import {builtinModules} from 'node:module';
import path from 'node:path';
import type {IModule} from 'dependency-cruiser';
import type {ArchwardConfig} from '../types.js';
import {byString} from '../util.js';
import {isExportedSubpath, readInstalledExports} from './exports.js';
const BUILTINS = new Set(builtinModules);
export interface DeclaredDependencies {
name?: string;
/** `dependencies`, `peerDependencies` and `optionalDependencies`. */
runtime: ReadonlySet<string>;
dev: ReadonlySet<string>;
}
export interface PackageImportContext {
packageDir: string;
/** Source root with a trailing slash, e.g. `lib/`. */
prefix: string;
entryPointScopes: readonly string[];
undeclaredDependencies: NonNullable<ArchwardConfig['undeclaredDependencies']>;
declared: DeclaredDependencies;
/** The graph without type-only imports; an import missing from it is erased at runtime. */
runtimeModules: readonly IModule[];
}
export interface PackageImportFinding {
key: string;
message: string;
}
/** Reads the declared dependencies and the name of the package in `packageDir`. */
export async function readDeclaredDependencies(packageDir: string): Promise<DeclaredDependencies> {
const pkg = JSON.parse(await readFile(path.join(packageDir, 'package.json'), 'utf8')) as {
name?: string;
} & Record<string, Record<string, string> | undefined>;
const names = (fields: string[]) => new Set(fields.flatMap((field) => Object.keys(pkg[field] ?? {})));
return {
name: pkg.name,
runtime: names(['dependencies', 'peerDependencies', 'optionalDependencies']),
dev: names(['devDependencies']),
};
}
/**
* Checks the packages the source imports: deep imports of packages in `entryPointScopes` (unless
* the installed package exports the subpath), and packages missing from `package.json`.
*/
export async function findPackageImports(
modules: readonly IModule[],
context: PackageImportContext,
): Promise<PackageImportFinding[]> {
const {prefix, entryPointScopes, undeclaredDependencies, declared, runtimeModules} = context;
const runtimeImports = new Set(runtimeModules.flatMap((m) => m.dependencies.map((d) => `${m.source}\0${d.module}`)));
const exportsOf = createExportsLookup(context.packageDir);
const findings = new Map<string, string>();
for (const mod of modules.filter((m) => m.source.startsWith(prefix))) {
for (const dep of mod.dependencies) {
const spec = parseScopedSpecifier(dep.module, entryPointScopes);
if (spec?.subpath && !isExportedSubpath(await exportsOf(spec.pkg), spec.subpath)) {
findings.set(
`${mod.source} -> ${dep.module}`,
`${mod.source} deep-imports '${dep.module}'. Import from '${spec.pkg}' entry points only.`,
);
}
const external =
undeclaredDependencies === 'error'
? isLocalFile(dep)
? null
: externalPackageName(dep.module)
: (spec?.pkg ?? null);
// Unresolved imports carry no type-only marker, so type-only is "absent from the runtime graph".
const isTypeOnly = !runtimeImports.has(`${mod.source}\0${dep.module}`);
if (
external &&
external !== declared.name &&
!declared.runtime.has(external) &&
!(declared.dev.has(external) && isTypeOnly)
) {
findings.set(
`${mod.source} -> ${external}`,
`${mod.source} imports '${external}', which is not declared in package.json (devDependencies are enough for type-only imports).`,
);
}
}
}
return [...findings].map(([key, message]) => ({key, message})).sort((a, b) => byString(a.key, b.key));
}
/**
* Parses an import specifier of a package within one of the given npm scopes.
* @returns the package name, and the subpath (e.g. `./oxlint`) if the specifier reaches past the
* package's root entry point, or `null`
*/
export function parseScopedSpecifier(
specifier: string,
scopes: readonly string[],
): {pkg: string; subpath?: string} | null {
for (const scope of scopes) {
const escaped = scope.replace(/[.+^${}()|[\]\\]/g, '\\$&');
const match = new RegExp(`^(${escaped}/[^/]+)(/.*)?$`).exec(specifier);
if (match) {
return {pkg: match[1], ...(match[2] ? {subpath: `.${match[2]}`} : {})};
}
}
return null;
}
/**
* The npm package an import specifier refers to (`@scope/name` or `name`), or `null` for relative
* and absolute paths, `#` imports, `node:`/URL-style specifiers and Node.js built-in modules.
*/
export function externalPackageName(specifier: string): string | null {
if (/^[./#]/.test(specifier) || specifier.includes(':')) {
return null;
}
const parts = specifier.split('/');
const name = specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
return !name || (!specifier.startsWith('@') && BUILTINS.has(name)) ? null : name;
}
/**
* Whether an import resolved to a file of this package that is not in `node_modules`: a relative
* import, or a tsconfig `paths` alias (wherever in the package it points). Packages resolve into
* `node_modules`, or, for linked workspace packages, outside the package directory.
*/
function isLocalFile(dep: {resolved: string; couldNotResolve?: boolean}): boolean {
return (
!dep.couldNotResolve &&
!dep.resolved.startsWith('..') &&
!path.isAbsolute(dep.resolved) &&
!dep.resolved.split('/').includes('node_modules')
);
}
/** Looks up the `exports` of installed packages, reading each package at most once. */
function createExportsLookup(fromDir: string): (pkg: string) => Promise<unknown> {
const cache = new Map<string, Promise<unknown>>();
return (pkg) => {
if (!cache.has(pkg)) {
cache.set(pkg, readInstalledExports(fromDir, pkg));
}
return cache.get(pkg) as Promise<unknown>;
};
}
+58
View File
@@ -0,0 +1,58 @@
import {randomUUID} from 'node:crypto';
import {mkdir, rename, rm, writeFile} from 'node:fs/promises';
import path from 'node:path';
import {readOptionalJson} from './config.js';
import type {Analysis, Baseline, CycleEntry} from './types.js';
import {boundaryKey, byString, cycleKey} from './util.js';
/** Splits `current` keys against a baseline into new (not baselined) and stale (no longer present). */
export function diffAgainstBaseline(
currentKeys: Iterable<string>,
baselineKeys: Iterable<string>,
): {added: string[]; stale: string[]} {
const current = new Set(currentKeys);
const baseline = new Set(baselineKeys);
return {
added: [...current].filter((k) => !baseline.has(k)).sort(byString),
stale: [...baseline].filter((k) => !current.has(k)).sort(byString),
};
}
/** Reads the baseline file; a missing file is an empty baseline. */
export async function readBaseline(file: string): Promise<Baseline> {
const raw = await readOptionalJson<Partial<Baseline>>(file);
return {
boundaries: raw.boundaries ?? [],
cycles: {runtime: raw.cycles?.runtime ?? [], typeOnly: raw.cycles?.typeOnly ?? []},
};
}
/** Writes a baseline of everything in `analysis`, keeping the reasons of entries that remain. */
export async function writeBaseline(file: string, analysis: Analysis, previous: Baseline): Promise<void> {
const reasons = new Map<string, string | undefined>([
...previous.boundaries.map((b) => [boundaryKey(b), b.reason] as const),
...[...previous.cycles.runtime, ...previous.cycles.typeOnly].map((c) => [cycleKey(c.cycle), c.reason] as const),
]);
const withReason = (key: string) => (reasons.get(key) ? {reason: reasons.get(key)} : {});
const cycleEntry = (key: string): CycleEntry => ({cycle: key.split(' > '), ...withReason(key)});
const next: Baseline = {
boundaries: analysis.boundaries
.map((b) => ({from: b.from, to: b.to, ...withReason(boundaryKey(b))}))
.sort((a, b) => byString(boundaryKey(a), boundaryKey(b))),
cycles: {
runtime: analysis.runtimeCycles.map(cycleEntry),
typeOnly: analysis.typeOnlyCycles.map(cycleEntry),
},
};
await mkdir(path.dirname(file), {recursive: true});
// Write to a temp file and rename it into place, so a failure never leaves a partial baseline.
const tmp = `${file}.${randomUUID()}.tmp`;
try {
await writeFile(tmp, `${JSON.stringify(next, null, 2)}\n`);
await rename(tmp, file);
} catch (err) {
await rm(tmp, {force: true});
throw err;
}
}
+80
View File
@@ -0,0 +1,80 @@
import {analyze} from './analysis/index.js';
import {diffAgainstBaseline, readBaseline, writeBaseline} from './baseline.js';
import {loadConfig} from './config.js';
import type {Analysis, CheckResult, Finding, ImportedBoundary} from './types.js';
import {boundaryKey} from './util.js';
/**
* Checks the package in `packageDir` against its architecture model and baseline.
* @returns the findings; `ok` is false if there are any new violations or stale baseline entries
*/
export async function checkPackage(packageDir: string): Promise<CheckResult> {
const config = await loadConfig(packageDir);
const analysis = await analyze(config);
const baseline = await readBaseline(config.baselineFile);
const boundariesByKey = new Map(analysis.boundaries.map((b) => [boundaryKey(b), b]));
const findings: Finding[] = [
...analysis.unownedFiles.map((file) => ({
rule: 'unowned-file' as const,
status: 'new' as const,
key: file,
message: `${file} is not owned by any component. Add its path to a component in architecture/model.c4.`,
})),
...analysis.packageImports.map((p) => ({rule: 'package-import' as const, status: 'new' as const, ...p})),
...compare('boundary', [...boundariesByKey.keys()], baseline.boundaries.map(boundaryKey), (key) =>
describeBoundary(key, boundariesByKey),
),
...compare(
'runtime-cycle',
analysis.runtimeCycles,
baseline.cycles.runtime.map((c) => c.cycle.join(' > ')),
),
...compare(
'type-cycle',
analysis.typeOnlyCycles,
baseline.cycles.typeOnly.map((c) => c.cycle.join(' > ')),
),
];
const count = (rule: Finding['rule'], total: number) =>
total - findings.filter((f) => f.rule === rule && f.status === 'new').length;
return {
ok: findings.length === 0,
findings,
warnings: [
...analysis.unusedEdges.map((edge) => `edge '${edge}' is declared in the model but never used in the code.`),
...analysis.unresolvedImports.map((imp) => `${imp} could not be resolved, so it was not checked.`),
],
analysis,
baselined: {
boundaries: count('boundary', analysis.boundaries.length),
runtimeCycles: count('runtime-cycle', analysis.runtimeCycles.length),
typeOnlyCycles: count('type-cycle', analysis.typeOnlyCycles.length),
},
};
}
/** Rewrites the baseline to tolerate every current violation, keeping existing reasons. */
export async function updateBaseline(packageDir: string): Promise<Analysis> {
const config = await loadConfig(packageDir);
const analysis = await analyze(config);
await writeBaseline(config.baselineFile, analysis, await readBaseline(config.baselineFile));
return analysis;
}
function compare(
rule: Finding['rule'],
currentKeys: string[],
baselineKeys: string[],
describe: (key: string) => string = (key) => key,
): Finding[] {
const {added, stale} = diffAgainstBaseline(currentKeys, baselineKeys);
return [
...added.map((key) => ({rule, status: 'new' as const, key, message: describe(key)})),
...stale.map((key) => ({rule, status: 'stale' as const, key, message: key})),
];
}
function describeBoundary(key: string, boundaries: ReadonlyMap<string, ImportedBoundary>): string {
const b = boundaries.get(key);
return b ? `${key} (component '${b.fromComponent}' may not depend on '${b.toComponent}')` : key;
}
+168
View File
@@ -0,0 +1,168 @@
import path from 'node:path';
import {parseArgs} from 'node:util';
import {checkPackage, updateBaseline} from './check.js';
import {initPackage} from './init/index.js';
import {formatReport} from './report.js';
import {findWorkspacePackages} from './workspaces.js';
const USAGE = `Usage:
archward [packageDir...] [--workspaces] [--update-baseline] [--verbose]
archward init [packageDir] [--source-root <dir>] [--entry-point-scope <scope>]...
Checks each package (default: the current directory) against its architecture/*.c4.
--workspaces treat each packageDir as a monorepo root and check its workspace packages
that have an architecture/ directory
--update-baseline tolerate all current violations by rewriting architecture/baseline.json
--verbose list every finding instead of the first few per rule
init creates architecture/ for a package from its current code (components = top-level
directories and files of the source root, dependencies = current imports) and a baseline.
`;
const EXIT_OK = 0;
const EXIT_VIOLATIONS = 1;
const EXIT_ERROR = 2;
interface CliArgs {
help: boolean;
init: boolean;
workspaces: boolean;
updateBaseline: boolean;
verbose: boolean;
sourceRoot?: string;
entryPointScopes: string[];
dirs: string[];
}
/**
* Runs the CLI.
* @param argv - arguments after the program name
* @returns the process exit code: 0 ok, 1 violations found, 2 usage or runtime error
*/
export async function main(argv: string[]): Promise<number> {
let args: CliArgs;
try {
args = parseCliArgs(argv);
} catch (err) {
process.stderr.write(`${(err as Error).message}\n${USAGE}`);
return EXIT_ERROR;
}
if (args.help) {
process.stdout.write(USAGE);
return EXIT_OK;
}
try {
if (args.init) {
return await runInit(args);
}
const dirs = args.workspaces ? (await Promise.all(args.dirs.map(findWorkspacePackages))).flat() : args.dirs;
if (!dirs.length) {
throw new Error('No packages with an architecture/ directory found');
}
let exitCode = EXIT_OK;
for (const dir of dirs) {
if (dirs.length > 1) {
process.stdout.write(`== ${path.relative(process.cwd(), dir) || '.'}\n`);
}
exitCode = Math.max(exitCode, await runOne(dir, args));
}
return exitCode;
} catch (err) {
process.stderr.write(`${(err as Error).message}\n`);
return EXIT_ERROR;
}
}
function parseCliArgs(argv: string[]): CliArgs {
const {values, positionals} = parseArgs({
args: argv,
allowPositionals: true,
options: {
workspaces: {type: 'boolean'},
'update-baseline': {type: 'boolean'},
verbose: {type: 'boolean'},
'source-root': {type: 'string'},
'entry-point-scope': {type: 'string', multiple: true},
help: {type: 'boolean', short: 'h'},
},
});
const init = positionals[0] === 'init';
const dirs = (init ? positionals.slice(1) : positionals).map((d) => path.resolve(d));
if (init && dirs.length > 1) {
throw new Error(`init takes at most one package directory, got ${dirs.length}`);
}
if (init && (values.workspaces || values['update-baseline'])) {
throw new Error('init does not take --workspaces or --update-baseline');
}
if (!init && (values['source-root'] || values['entry-point-scope'])) {
throw new Error('--source-root and --entry-point-scope only apply to init');
}
return {
help: Boolean(values.help),
init,
workspaces: Boolean(values.workspaces),
updateBaseline: Boolean(values['update-baseline']),
verbose: Boolean(values.verbose),
sourceRoot: values['source-root'],
entryPointScopes: values['entry-point-scope'] ?? [],
dirs: dirs.length ? dirs : [path.resolve('.')],
};
}
async function runOne(dir: string, args: CliArgs): Promise<number> {
if (args.updateBaseline) {
return runUpdateBaseline(dir);
}
const result = await checkPackage(dir);
process.stdout.write(`${formatReport(result, {verbose: args.verbose})}\n`);
return result.ok ? EXIT_OK : EXIT_VIOLATIONS;
}
async function runUpdateBaseline(packageDir: string): Promise<number> {
const analysis = await updateBaseline(packageDir);
process.stdout.write(
`Baseline updated: ${analysis.boundaries.length} boundary imports, ` +
`${analysis.runtimeCycles.length} runtime cycles, ${analysis.typeOnlyCycles.length} type-only cycles.\n`,
);
const unbaselinable = analysis.unownedFiles.length + analysis.packageImports.length;
if (unbaselinable) {
process.stderr.write(
`warning: ${analysis.unownedFiles.length} unowned files and ${analysis.packageImports.length} package ` +
'import violations cannot be baselined and still fail the check. Fix them (see `archward`).\n',
);
}
return EXIT_OK;
}
async function runInit(args: CliArgs): Promise<number> {
const [dir] = args.dirs;
const result = await initPackage(dir, {sourceRoot: args.sourceRoot, entryPointScopes: args.entryPointScopes});
const rel = path.relative(process.cwd(), dir) || '.';
process.stdout.write(
`Created ${result.files.join(', ')} in ${rel}: ${result.components} components, ` +
`${result.edges} allowed dependencies (taken from the current imports).\n\n` +
'Next steps:\n' +
' 1. Delete the dependencies in model.c4 that should not be allowed, add descriptions.\n' +
` 2. Run \`archward ${rel} --update-baseline\` to tolerate the violations that creates.\n` +
' 3. Run `archward` in CI, and add the following to AGENTS.md:\n\n' +
`${agentsSnippet(rel)}`,
);
return EXIT_OK;
}
function agentsSnippet(packageDir: string): string {
return `## Architecture
\`${packageDir}/architecture/*.c4\` is the source of truth for the component boundaries of
\`${packageDir}\`. CI runs \`npx archward ${packageDir}\`.
- Before adding or moving code, find the owning component (\`metadata.paths\`) and respect its
allowed dependencies. New files must be covered by a component's \`paths\`.
- Fix a failing check by changing the code. Do not add edges to the model or entries to
\`baseline.json\` to make it pass, unless the new dependency is intended; then update the \`.c4\`
files in the same change and explain why in the PR description.
- Remove \`baseline.json\` entries when you fix the violation they cover.
- Keep component descriptions and the paths they own in sync with the code.
`;
}
+85
View File
@@ -0,0 +1,85 @@
import {readFile, realpath} from 'node:fs/promises';
import path from 'node:path';
import type {ArchwardConfig, ResolvedConfig} from './types.js';
export const ARCHITECTURE_DIR = 'architecture';
const CONFIG_KEYS = new Set(['sourceRoot', 'tsconfig', 'entryPointScopes', 'typeOnlyCycles', 'undeclaredDependencies']);
/**
* Resolves the settings of the package in `packageDir`, applying defaults over the optional
* `architecture/config.json`.
*/
export async function loadConfig(packageDir: string): Promise<ResolvedConfig> {
// dependency-cruiser reports real paths, so symlinked directories (e.g. macOS /tmp) must be resolved
const root = await realpath(path.resolve(packageDir));
const modelDir = path.join(root, ARCHITECTURE_DIR);
const configFile = path.join(modelDir, 'config.json');
const user = parseConfig(await readOptionalJson<ArchwardConfig>(configFile), configFile);
return {
packageDir: root,
sourceRoot: normalizeSourceRoot(user.sourceRoot ?? 'lib', configFile),
tsconfig: user.tsconfig ?? 'tsconfig.json',
entryPointScopes: user.entryPointScopes ?? [],
typeOnlyCycles: user.typeOnlyCycles ?? 'error',
undeclaredDependencies: user.undeclaredDependencies ?? 'ignore',
modelDir,
baselineFile: path.join(modelDir, 'baseline.json'),
};
}
/**
* Normalizes a source directory to the form used in the import graph: relative to the package,
* `/`-separated, without a leading `./` or trailing slash.
*/
export function normalizeSourceRoot(sourceRoot: string, origin = 'sourceRoot'): string {
const normalized = path.posix.normalize(sourceRoot.replace(/\\/g, '/')).replace(/\/+$/, '');
if (!normalized || normalized === '.' || normalized.startsWith('..') || path.posix.isAbsolute(normalized)) {
throw new Error(`${origin}: the source root must be a subdirectory of the package, got '${sourceRoot}'`);
}
return normalized;
}
/** Validates the contents of `architecture/config.json`; unknown options are rejected to catch typos. */
export function parseConfig(raw: unknown, file: string): ArchwardConfig {
const fail = (msg: string): never => {
throw new Error(`${file}: ${msg}`);
};
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
return fail('expected a JSON object');
}
const config = raw as Record<string, unknown>;
for (const key of Object.keys(config)) {
if (!CONFIG_KEYS.has(key)) {
fail(`unknown option '${key}' (known: ${[...CONFIG_KEYS].join(', ')})`);
}
}
for (const key of ['sourceRoot', 'tsconfig'] as const) {
if (config[key] !== undefined && typeof config[key] !== 'string') {
fail(`'${key}' must be a string`);
}
}
const scopes = config.entryPointScopes;
if (scopes !== undefined && !(Array.isArray(scopes) && scopes.every((s) => typeof s === 'string'))) {
fail("'entryPointScopes' must be an array of strings");
}
for (const key of ['typeOnlyCycles', 'undeclaredDependencies'] as const) {
if (config[key] !== undefined && config[key] !== 'error' && config[key] !== 'ignore') {
fail(`'${key}' must be 'error' or 'ignore'`);
}
}
return config as ArchwardConfig;
}
/** Reads and parses a JSON file, returning `{}` if it does not exist. */
export async function readOptionalJson<T extends object>(file: string): Promise<T> {
try {
return JSON.parse(await readFile(file, 'utf8')) as T;
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
return {} as T;
}
throw new Error(`Cannot read ${file}: ${(err as Error).message}`, {cause: err});
}
}
+6
View File
@@ -0,0 +1,6 @@
export {checkPackage, updateBaseline} from './check.js';
export {loadConfig} from './config.js';
export {initPackage, type InitOptions, type InitResult} from './init/index.js';
export {formatReport, type ReportOptions} from './report.js';
export {findWorkspacePackages} from './workspaces.js';
export type {Analysis, ArchwardConfig, Baseline, CheckResult, Finding, ResolvedConfig, Rule} from './types.js';

Some files were not shown because too many files have changed in this diff Show More