Compare commits

..
Author SHA1 Message Date
Christopher Hiller 8480a85ce2 chore: publish
- appium@2.0.0-beta.58
 - @appium/base-driver@9.3.4
 - @appium/base-plugin@2.2.4
 - @appium/doctor@2.0.10
 - @appium/docutils@0.3.1
 - @appium/driver-test-support@0.4.2
 - @appium/eslint-config-appium-ts@0.3.0
 - @appium/eslint-config-appium@8.0.2
 - @appium/execute-driver-plugin@3.0.9
 - @appium/fake-driver@5.2.2
 - @appium/fake-plugin@3.1.8
 - @appium/plugin-test-support@0.3.10
 - @appium/support@3.1.8
 - @appium/test-support@3.0.10
 - @appium/typedoc-plugin-appium@0.5.2
 - @appium/types@0.10.2
 - @appium/universal-xml-plugin@1.0.7
2023-03-28 13:10:45 -07:00
renovate[bot] ad98d38efb chore(deps): update eslint-related packages to v5.57.0 2023-03-28 19:38:54 +00:00
renovate[bot] 1358425e1a chore(deps): update dependency @commitlint/cli to v17.5.1 2023-03-28 12:50:54 +00:00
renovate[bot] 43fa0d7425 chore(deps): update dependency tsd to v0.28.1 2023-03-28 10:22:58 +00:00
renovate[bot] 86eb495641 fix(driver-test-support): update definitelytyped 2023-03-28 08:00:49 +00:00
Christopher Hiller 5485f0b9cd fix(types): fix method map types
These types do not care about constraints, only the shape of the driver itself.
2023-03-27 17:07:51 -07:00
Christopher Hiller 4974403661 fix: backwards-compatible fixes for TS v5.x
These will be issues when we upgrade
2023-03-27 17:07:51 -07:00
Christopher Hiller deb631b456 fix(basedriver): convert main driver implementation to typescript
This seems to fix the bug in #18379.  There must be some sort of bug in TypeScript w/r/t `@implements` or maybe even it was not treating `@typedef` as a proper alias.  Perhaps it's user error--omitting optional type args in alias-style typedefs may end up making a new type entirely.  idk, but this was easier to deal with.

Closes #18379.
2023-03-27 17:07:51 -07:00
Christopher Hiller 238c489f3a chore(base-driver): add a failing type test 2023-03-27 17:07:51 -07:00
Christopher Hiller 3c9fa7ba73 fix(appium,types,base-driver,fake-driver,driver-test-support): normalize constraint defaults
Another handful of fixes.

- remove second "extra" parameter from `Capabilities`, `NSCapabilities` `W3CCapabilities`. we were not using it anywhere to my knowledge. it was an escape hatch anyway.
- never assign `BaseDriverCapConstraints` as the default constraints, because this is confusing as hell. instead, drivers should use the `*DriverCaps` types which automatically pulls the base constraints in. applied across several workspaces
- renamed `DeviceSettings` => `IDeviceSettings` because `DeviceSettings` is a class.
- the session ID param of `Core`'s `sessionExists()` is actually optional (per the implementation)
- allow some modicum of type narrowing at the class level around settings and values returned by `ISessionHandler`'s methods. also, not all values in the raw settings object are of the same type `T`, so fix that
- `server`, `serverHost`, `serverPort` and `serverPath` are not members of `Core` (using `AppiumDriver` as a litmus test--it interacts with `Driver` types but does not have these properties itself)
- changed a few types to interfaces where possible
- moved a lost comment
- further dumbed-down the logdef stuff
- `Driver.driverData` is _always_ defined, since `Core` makes it an empty array.
- `DriverOpts` no longer contains "partial" caps; this it not quite right as the caps are not assigned until a session is created, but there's a conflict between some props which are _both_ server args and defined in constraints.  anyway, this is what `initialOpts` is for
- fix some type disagreements in basedriver's "capabilities" module
2023-03-27 17:07:51 -07:00
Christopher Hiller e8e8252c52 chore(types): add type tests for Plugins 2023-03-27 14:23:25 -07:00
Christopher Hiller 50f1e69268 fixup 2023-03-27 14:23:25 -07:00
Christopher Hiller 0dcd5fa371 fix(base-driver,base-plugin,types): update PluginCommand and DriverCommand types
The first arg of `PluginCommand` is a `NextPluginCallback` which now returns `Promise<unknown>` instead of `Promise<void>`, which was incorrect.

We use `unknown` rather than `any` because it forces us to be explicit about the return value of `await next()` if we are to call it.

Added a type `DriverCommandToPluginCommand` which essentially converts a `DriverCommand` to a `PluginCommand`.  It's probably best used as a type guard or decorator, but it can "fill in the blanks" when overloading commands in a plugin.

Also normalized some of the `TArgs`/`TReturn` stuff.
2023-03-27 14:23:25 -07:00
Christopher Hiller 75cbb11d00 chore: rename ExtensionCommand classes due to naming conflict
mainly because a "command" is a thing in drivers/plugins, and these classes refer to something else completely unrelated.  renamed to `*CliCommand` to avoid confusion.
2023-03-27 14:23:25 -07:00
Christopher Hiller 020473afc4 fix(eslint-config-appium): disable import/no-unresolved for tsd tests
`tsd` has a apparently non-standard resolution algorithm
2023-03-27 12:44:47 -07:00
Christopher Hiller 497641a00d chore: add tsd for testing types
This adds [tsd](https://npm.im/tsd) which provides a small framework around running expectations against declaration files.  This is intended to be run against hand-written declarations, but because we (apparently) cannot rely on `tsc` to output valid declaration files, we should also use it to test the generated declarations of our packages.
2023-03-27 12:44:47 -07:00
renovate[bot] bc860c733a fix(types): update dependency type-fest to v3.7.1 2023-03-27 08:31:03 +00:00
renovate[bot] d774a8428a fix(test-support): update dependency sinon to v15.0.3 2023-03-27 07:22:50 +00:00
renovate[bot] a593269f61 chore(deps): update dependency @types/node to v18.15.10 2023-03-26 08:57:05 +00:00
renovate[bot] 89fd52a602 chore(deps): update dependency @types/node to v18.15.9 2023-03-25 15:57:36 +00:00
renovate[bot] 7f061d2362 chore(docutils): update dependency mkdocs-material to v9.1.4 2023-03-25 11:08:46 +00:00
renovate[bot] 2c1e1532ad chore(deps): update dependency lerna to v6.6.1 2023-03-25 08:02:49 +00:00
Christopher Hiller 0c52b50e65 fix(appium): remove longjohn
This removes `longjohn` and replaces it with a statement which increases the stack trace limit from the default (10) to 100.

I believe setting this overrides whatever was passed to the runtime `--stack-trace-limit` option.  If someone complains, we can try a different strategy.

Closes #18357
2023-03-24 12:22:33 -07:00
renovate[bot] 6db70f4143 chore(deps): update dependency lerna to v6.6.0 2023-03-24 14:27:16 +00:00
renovate[bot] 1800530bf2 chore(deps): update definitelytyped 2023-03-24 12:45:03 +00:00
renovate[bot] 32a5ee91df chore(deps): update dependency prettier to v2.8.7 2023-03-24 10:53:51 +00:00
renovate[bot] 5c0315d3bb chore(workflows): update actions/checkout digest to 8f4b7f8 2023-03-24 08:40:56 +00:00
Erhan AlankuşandKazuaki Matsuo 12f4ec404c docs(appium): grammar fix (#18359)
Co-authored-by: Kazuaki Matsuo <fly.49.89.over@gmail.com>
2023-03-23 23:21:19 -07:00
Erhan AlankuşandKazuaki Matsuo 8aa39c117f docs(appium): update index.md (#18363)
Co-authored-by: Kazuaki Matsuo <fly.49.89.over@gmail.com>
2023-03-23 23:20:46 -07:00
Christopher Hiller 017216533b chore(ci): suppress warnings when linting
This suppresses all warnings when running ESLint in CI (since they are noisy)
2023-03-23 13:05:31 -07:00
Christopher Hiller 499bda4533 chore(types): make the lone JS file a TS file
also: remove unused imports
2023-03-23 12:15:51 -07:00
Christopher Hiller 9ef564f0be chore(types): move more utility types into util module 2023-03-23 12:15:51 -07:00
Christopher Hiller d303527c3d fix(base-driver): misc type fixes
- `PostProcessOptions` moved into `@appium/types`
- `shutdownUnexpectedly` cannot be marked `@protected` as anything used this way is inaccessible in mixins
- suppress a `@typescript-eslint` warning. this probably needs to happen in a few other files
2023-03-23 12:15:51 -07:00
Christopher Hiller 51a8f2fc34 fix(base-driver): fix timeout mixin to use proper context types 2023-03-23 12:15:51 -07:00
Christopher Hiller c56dc98d13 chore(base-driver): fix description of mixin function to refer to BaseDriver 2023-03-23 12:15:51 -07:00
Christopher Hiller 454f6a5d63 fix(support): fix a few type problems; use new HTTPHeaders type 2023-03-23 12:15:51 -07:00
Christopher Hiller 87408e529c chore(types): organize more types; remove some deprecated types
This change removes types for methods in `ExternalDriver` (or rather the interfaces that build it) that were marked `@deprecated` and  consumed by `appium-xcuitest-driver`.  I salvaged what I could from the descriptions in these docstrings, and have moved them into `appium-xcuitest-driver` (obviously not in this repo).

Also:

- created some new files to group types logically
- created a `HTTPHeaders` type
- created a type `ConfigureAppOptions` for `DriverHelpers.configureApp`, and a `PostProcessOptions` type within it.
- added a couple other types
- fixed some signatures to look more like reality
- modified the return value of `queryAppState()` to return `0|1|2|3|4` instead of `0|1|3|4` since `appium-xcuitest-driver` returns the former
- made the `LogDef` and related types even _more_ loose.  tbh these are very awkward to type properly; I cannot figure out a good way to narrowly type the `self` param to a log `getter`.
- noted which of the remaining `@deprecated` methods in `ExternalDriver` were _not_ in use by `appium-xcuitest-driver`, so I can later remove them once I've salvaged the docstrings to put into `appium-uiautomator2-driver`.
2023-03-23 12:15:51 -07:00
Christopher Hiller 24bec8ce81 chore: downgrade log message about manifest upgrade
Most users are not going to care or know what this is.
2023-03-23 11:56:05 -07:00
Christopher Hiller d9b47bc864 feat(appium): improvements to ext commands when running extension in development
This PR does a handful of things:

1. It adds a `--verbose` flag to `appium <driver|plugin> list` which just dumps a big object (via Node's `util.inspect()`), which contains the underlying manifest file data
2. It creates a new manifest schema revision where the "install type" can be `dev`. Added a migration.
3. Displays a warning if trying to uninstall an extension in dev mode
4. Displays `[installed (dev mode)]` instead of `[installed (npm)]` when running `appium <driver|plugin> list` w/o `--verbose` flag
5. Attempted to simplify the return type of `ExtensionCommand.list()`

Closes #18277
2023-03-23 11:56:05 -07:00
renovate[bot] 6912fa14f2 fix(types): update dependency type-fest to v3.7.0 2023-03-23 11:22:16 +00:00
renovate[bot] 45291f71f4 chore(deps): update dependency @commitlint/cli to v17.5.0 2023-03-23 06:48:55 +00:00
Christopher Hiller 409192d063 fix(eslint-config-appium-ts): disable brace-style rule
In certain situations in `.ts` sources, class definition lines can get very long.  Prettier will split these into multiple lines, and add a final line with `{` at position 0.  This conflicts with the `brace-style` rule in ESLint.  I am not sure why the ESLint prettier config doesn't already handle this, but I am going to guess it's because that config doesn't work on `.ts` sources.
2023-03-22 16:25:22 -07:00
Christopher Hiller 309fe4c964 chore: lint everything 2023-03-22 16:25:22 -07:00
Christopher Hiller 34891f5657 fix(base-driver,types): fix websocket-related types on AppiumServer 2023-03-22 16:25:22 -07:00
Christopher Hiller 43df77f6b6 feat(eslint-config-appium-ts)!: enable for JS sources
BREAKING CHANGE: This makes `@appium/eslint-config-appium-ts` also apply to JS sources _and_ requires a new peer dependency (`eslint-import-resolver-typescript`). The `main` file is now a `.js` file.  The module is expected to _extend_ `@appium/eslint-config-appium`, not replace it; consumers needn't extend both in their ESLint config.

In the not-too-distant past, `@typescript-eslint/parser` was unable to understand docstrings in `.js` files. Evidently this is no longer true.

I've rewritten and heavily commented the configuration explaining the intent behind everything.
2023-03-22 16:25:22 -07:00
Christopher Hiller 78c6a0b991 chore: remove jsdoc vestiges 2023-03-22 11:59:20 -07:00
Mykola Mokhnach d3e91222c8 chore(base-driver): Check if a valid Error instance is thrown (#18369) 2023-03-22 07:20:32 +01:00
renovate[bot] f2dadd8f8f chore(deps): update eslint-related packages 2023-03-21 16:58:18 +00:00
renovate[bot] ffedb6e40e chore(deps): update dependency prettier to v2.8.6 2023-03-21 13:03:08 +00:00
renovate[bot] fdcd01ba35 chore(deps): update definitelytyped 2023-03-21 09:41:25 +00:00
renovate[bot] bd3ecc3fb1 fix(support): update definitelytyped 2023-03-20 19:24:56 +00:00
renovate[bot] dbc0bf69e8 fix(docutils): update dependency typedoc to v0.23.28 2023-03-20 15:46:26 +00:00
renovate[bot] 23b1096caa chore(deps): update dependency prettier to v2.8.5 2023-03-20 10:19:01 +00:00
Daniel Mertins 8805792089 docs(appium): fix links to drivers lists (#18355) 2023-03-16 14:52:24 -04:00
renovate[bot] ef9cbe6bcc fix(docutils): update dependency typedoc to v0.23.27 2023-03-16 14:34:02 +00:00
renovate[bot] fc19705ecd chore(workflows): update actions/checkout digest to 24cb908 2023-03-16 13:12:23 +00:00
Mykola Mokhnach d4654138ee chore(base-driver): Update HTTP caching logic and align it with the standard (#18348) 2023-03-16 07:30:11 +01:00
renovate[bot] 930a45dafe chore(docutils): update dependency mkdocs-material to v9.1.3 2023-03-15 08:39:34 +00:00
renovate[bot] f1a8ce0bba fix(test-support): update dependency sinon to v15.0.2 2023-03-14 10:19:30 -07:00
renovate[bot] 287974a93a chore(deps): update eslint-related packages to v5.55.0 2023-03-14 13:29:43 +00:00
renovate[bot] 4c081c6723 chore(deps): update dependency ws to v8.13.0 2023-03-11 16:32:10 +00:00
renovate[bot] 58ae10f887 chore(deps): update dependency eslint to v8.36.0 2023-03-11 13:01:30 +00:00
renovate[bot] f673efcba5 chore(deps): update dependency lint-staged to v13.2.0 2023-03-10 20:55:04 +00:00
renovate[bot] 503da432dc chore(deps): update dependency lint-staged to v13.1.4 2023-03-10 17:03:49 +00:00
renovate[bot] 4fb7eb8643 chore(deps): update dependency @types/node to v18.15.0 2023-03-10 12:38:39 +00:00
renovate[bot] ae303c73de chore(docutils): update dependency mkdocs-material to v9.1.2 2023-03-10 09:29:53 +00:00
Christopher Hiller ad11fbf97b fix(docutils): inherit stdio in long-running processes
This change ensures when running `mkdocs` or `mike` with the `--serve` flag, the output is unbuffered and stdio is inherited from the parent process.

This will show helpful things like _the URL at which the development server is running_.
2023-03-09 10:12:53 -08:00
Christopher Hiller 9ed6711a7e chore(ci): attempt to build and preview docs
This also isolates the docs build into a workflow that only runs when changes are likely to materially affect doc gen.
2023-03-09 10:11:53 -08:00
Christopher Hiller fa0e853bd0 chore(ci): attempt to avoid running trusted code on PRs from forks 2023-03-08 15:06:19 -08:00
Christopher Hiller 872b924a97 chore: publish
- appium@2.0.0-beta.57
 - @appium/base-driver@9.3.3
 - @appium/base-plugin@2.2.3
 - @appium/doctor@2.0.9
 - @appium/docutils@0.3.0
 - @appium/driver-test-support@0.4.1
 - @appium/eslint-config-appium-ts@0.2.0
 - @appium/eslint-config-appium@8.0.1
 - @appium/execute-driver-plugin@3.0.8
 - @appium/fake-driver@5.2.1
 - @appium/fake-plugin@3.1.7
 - @appium/images-plugin@2.0.8
 - @appium/opencv@2.0.8
 - @appium/plugin-test-support@0.3.9
 - @appium/schema@0.2.6
 - @appium/support@3.1.7
 - @appium/test-support@3.0.9
 - @appium/typedoc-plugin-appium@0.5.1
 - @appium/types@0.10.1
2023-03-08 11:43:18 -08:00
Dor Blayzer 0e164ba03d docs: Fix plugins link
fix broken officially-supported plugins link
2023-03-08 11:35:32 -08:00
Christopher Hiller 2359a2ba3b fix(support): remove all logging from env module
Currently there is no way to specify a log level when running extension commands (e.g., `appium driver list`).  Further, the log level used by the support module depends on whether or not Appium set it; used outside of an Appium context, there is no way to programmatically set the log level of the support module via an external API.
To that end, I just removed the log messages, because a "proper" fix will be quite involved.  See #16970.
2023-03-08 11:34:31 -08:00
renovate[bot] 49694f50a4 fix(execute-driver-plugin): update dependency webdriverio to v7.30.2 2023-03-08 11:05:39 +00:00
renovate[bot] a2cfb832ad chore(deps): update dependency json-schema-to-typescript to v12 2023-03-07 14:27:47 -08:00
Christopher Hiller 4cfad004db feat(docutils): add --upgrade flag to init
users can run `appium-docs init --upgrade` to upgrade python deps (e.g., mkdocs, mkdocs-material)
2023-03-07 14:27:16 -08:00
Christopher Hiller b159780fd6 chore(docutils): fix start script 2023-03-07 14:27:16 -08:00
renovate[bot] e2f7dd7154 chore(deps): update dependency eslint-config-prettier to v8.7.0 2023-03-07 10:55:56 +00:00
Christopher Hiller e9dae3f6d0 fix(appium,fake-driver): expose child process when running an extension script
This change makes it so when running an extension script (e.g., `appium driver foo run some-script`), unless the `--json` flag is present, the child process will do no buffering whatsoever and will inherit `process.stdin`, `process.stdout` and `process.stderr` from Appium.

This means that extension scripts can do stuff like prompt the user for input.  It _also_ means they can do stuff like display progress bars and spinners.

If the user wants JSON data, we revert to the old behavior, which is to buffer the output and dump it once the script has completed.
2023-03-06 15:46:50 -08:00
Christopher Hiller 58b4790b1d chore: lint all the typescript 2023-03-06 15:21:58 -08:00
Christopher Hiller 63eddb670f docs(eslint-config-appium): update some stuff in README.md 2023-03-06 15:21:58 -08:00
Christopher Hiller b7d86c0d04 chore(eslint-config-appium): fix broken keywords 2023-03-06 15:21:58 -08:00
Christopher Hiller dfe02ca98c feat(eslint-config-appium-ts): create new pkg @appium/eslint-config-appium-ts
This adds a new package which consumers having TS sources can use.  This does not affect current users of `@appium/eslint-config-appium`.

Due to the nature of TS, it can be a little more bold with fixes (e.g., changing let to const). I changed the following rules from the recommended settings:

no-empty-function: Reduced to a warning. It's likely we want the functions, but perhaps they should not be empty.
no-empty-interface: Disabled; we use these to merge mixin interfaces with driver classes.
no-explicit-any: Disabled; while transitioning from an untyped codebase to a typed one, we still need to use any in places. Eventually these should all be replaced.
no-non-null-assertion: Disabled; This allows us to continue use of the ! operator, which is handy when working with untyped or loosely-typed code (especially in tests).
no-var-requires: Reduced to a warning. Occasionally we may need to use require() instead of import.
Since the configuration extends our shared config, the following rules have been disabled:

import/no-unresolved: The eslint-plugin-import module cannot resolve TS modules.
no-unused-vars: This rule conflicts with typescript-eslint's rule, so it must be disabled per the documentation.
promise/no-native: In our TS-based packages, I haven't needed Bluebird, so it doesn't make sense to require it.
require-await: TS is much more aware of the return values of functions; this is not needed to avoid ambiguity (in TS code).
2023-03-06 15:21:58 -08:00
renovate[bot] 10e6815a39 chore(docutils): update dependency mkdocs-material to v9.1.1 2023-03-06 14:01:53 -08:00
Christopher Hiller cd76622aa9 fix(typedoc-plugin-appium): replace void responses with 'null'
The main thrust of this was to resolve #18269.

Implementation-wise, we have to modify an `IntrinsicType` of which both `void` and `undefined` become.  To make it `null`, we must create a new `LiteralType` (`null` is not an "intrinsic" type; I don't know why).  I would think that TypeDoc wouldn't go around creating new `LiteralType`s every time it sees `null`, but I don't see it doing anything else. Anyway, if there is a "type cache" somewhere, I'm not sure how to get at it.

Additionally, the new reflections created for parameters and the call signature were not being "registered" properly with TypeDoc.  So this adds a `static create` to both `CommandData` and `ExecMethodData` which wraps the constructor for each, respectively, then performs the registration.  This keeps a `Context` object _out_ of `CommandData`/`ExecMethodData` instances (it would only be used once at time of instantiation anyway).

Un-memoized a couple methods in `BaseCommandData` since not necessary
2023-03-06 13:18:23 -08:00
Christopher Hiller 296cb2436c chore: add auto-labeler workflow
This will automatically label PRs. We can update it to further automatically label issues at a later time, if necessary.

I have added labels for each package.
2023-03-06 13:12:32 -08:00
renovate[bot] 01bff49297 fix(images-plugin): update dependency lru-cache to v7.18.3 2023-03-06 13:34:00 +00:00
renovate[bot] 48c331157f fix(images-plugin): update dependency lru-cache to v7.18.2 2023-03-05 12:47:18 +00:00
Kazuaki Matsuo 9f8daf385b docs(appium): update migration guide in Japanese (#18297)
* docs(appium): update migration gude in js

* Update migrating-1-to-2.md
2023-03-05 17:00:32 +09:00
renovate[bot] 7bae977ca9 chore(deps): update dependency @types/node to v18.14.6 2023-03-04 12:04:54 +00:00
renovate[bot] 4ed745a95f fix(docutils): update dependency lilconfig to v2.1.0 2023-03-04 06:38:14 +00:00
renovate[bot] 85e4bd8925 fix(support): update dependency pngjs to v7 2023-03-03 11:38:15 -08:00
Christopher Hiller cce27fcf88 chore(docutils): review updates
- Use `util.pluralize()` from `@appium/support` instead of `pluralize` directly
- Write some more docstrings
2023-03-03 11:36:00 -08:00
Christopher Hiller b30b2cfb84 feat(docutils): better path validation
This adds up-front checking of user-provided custom paths to avoid doing a bunch of work and then failing later ("fail fast")
2023-03-03 11:36:00 -08:00
Christopher Hiller 9ccbab5dc0 fix(appium,support): fs.readPackageJsonFrom() returns proper type
This function always returns a `NormalizedPackageJson`, so let's be explicit about that.
2023-03-03 11:36:00 -08:00
Christopher Hiller 760bb5b8f3 chore(appium): skip auto-install of extensions if monorepo detected 2023-03-03 10:51:52 -08:00
renovate[bot] cb14faae33 chore(deps): update dependency @types/node to v18.14.5 2023-03-03 12:08:20 +00:00
Mykola MokhnachandChristopher Hiller 2a6a13ac89 fix(support): Improve error description on image load (#18284)
Co-authored-by: Christopher Hiller <boneskull@boneskull.com>
2023-03-03 06:06:52 +01:00
Christopher Hiller 4b43af0709 chore: fix dupe in clean script 2023-03-02 15:49:33 -08:00
Christopher Hiller 504415d0cd chore: build must pass on local npm install 2023-03-02 15:49:33 -08:00
Christopher Hiller 75defa7b48 chore: add prepack script
sometimes (when?) the smoke tests can pack the workspaces before they have actually been built, which will of course cause an error. this adds a prepack script to avoid the problem

removes pack-all script, which I added for reasons
2023-03-02 15:49:33 -08:00
Christopher Hiller be86627595 fix(base-driver): use new mixin strategy
also fix a broken type in fake-driver
2023-03-02 15:47:24 -08:00
Christopher Hiller 080eb8aa1b chore(opencv): increase timeout for unit test
this can take awhile when exercising many cores
2023-03-02 15:01:13 -08:00
Christopher Hiller 1b70551055 fix(base-driver): remove needless static prop breaking the build 2023-03-02 15:01:13 -08:00
Christopher Hiller d262271b26 chore(appium): InnerDriver is actually an ExternalDriver
While `findMatchingDriver()` returns a `MatchedDriver`--which is a wrapper around `DriverClass`--the instance of `DriverClass`' constructor is a `Driver`.  But in the case of `AppiumDriver`, we know `InnerDriver` is actually an `ExternalDriver`; this is why we can assign to `server`, `serverHost`, etc.
2023-03-02 15:01:13 -08:00
Christopher Hiller 45b026de67 chore(base-plugin): better type handling in executeMethod 2023-03-02 15:01:13 -08:00
Christopher Hiller 843b797750 chore(driver-test-support): fix broken types in some e2e tests 2023-03-02 15:01:13 -08:00
Christopher Hiller b4c1403c22 fix(fake-driver): fix a broken type 2023-03-02 15:01:13 -08:00
Christopher Hiller e2aa3d3b32 fix(types): type fixes & improvements
moved method-map/execute-method-map-related stuff into its own file, and made the types more expressive.  changed some default parameters to hopefully avoid errors about conflicting constraints
2023-03-02 15:01:13 -08:00
Christopher Hiller b151e4c9bf chore: add dummy test script 2023-03-02 15:01:13 -08:00
Christopher Hiller 5684c4e286 fix(types): callback to implicitWaitForCondition accepts args 2023-03-02 15:01:13 -08:00
Christopher Hiller 189e39d03c fix(docutils): use material theme 2023-03-02 15:00:50 -08:00
renovate[bot] 694f9c6a63 chore(deps): update dependency @types/node to v18.14.4 2023-03-02 15:00:57 +00:00
Christopher Hiller f80f4cb2bc feat(docutils): allow "%s" as version number in commit msg arg 2023-03-01 16:32:00 -08:00
Mykola Mokhnach 908041c525 chore: Remove obsolete jpeg-js version override (#18278) 2023-03-01 22:43:21 +01:00
Christopher Hiller 18c0b4b230 chore(docutils): remove monkeypatching of typedoc 2023-03-01 13:19:39 -08:00
Mykola Mokhnach 4e2423d0f0 docs: Update install driver from github command 2023-03-01 20:36:02 +01:00
renovate[bot] ed1d3aae61 fix(images-plugin): update dependency lru-cache to v7.18.1 2023-03-01 17:36:54 +00:00
renovate[bot] d1d5ecef87 fix(images-plugin): update dependency lru-cache to v7.17.2 2023-03-01 12:30:17 +00:00
Kazuaki Matsuo b88f6e3e86 docs: update Copyright in LCIENSE
from JS foundation to openjs foundation
2023-02-28 13:30:25 -08:00
renovate[bot] 471a4b57e6 fix(types): update dependency type-fest to v3.6.1 2023-02-28 05:28:06 +00:00
Christopher Hiller feebf72eb4 chore(fake-driver): avoid public class field assignment
This changes the `fake-driver` implementation to use declaration merging instead of other alternatives to mixins.

History:

The original code simply assigned the mixin methods to `FakeDriver.prototype` after the `class` definition. In TS, this doesn't fly; you need to be explicit about what class members exist.

To get around this, we've tried multiple different approaches:

1. Use a "mixin pattern" as explained in the official TypeScript documentation, which involves _class factories_.  This is tedious and difficult to reason about; each mixin must be passed to the next in-line, and we must be explicit about the base class and which _previous_ mixins any given mixin expects.
2. Use public class fields (a recent addition to JS).  Basically, these do not work the way you want them to; if a subclass overrides a public field, a method in the superclass which refers to this public field _will use the field as defined in the superclass_--not the subclass. This is different than how methods and accessors work.  This inhibits use of inheritance.
3. Add a method _for each method in each mixin_ to the base class, which simply calls `Function.prototype.apply` on the mixin with the context as the base class' `this`.  This is too verbose.

There may be a better way to do this, but where we've landed is using _declaration merging_ in TypeScript.  It allows us to add (but not remove, and I'm not sure about "modify") properties to the "FakeDriver interface", which seems to be the implicit TS interface created by the `class` keyword.  Since the declaration merging syntax is not expressible in JavaScript, this requires a `.ts` file.  To avoid creating _n_ extra files, it was easier to just make the mixins `.ts` files (you may note that we can mix-and-match JS and TS in our projects at will).

The implementation of each mixin uses `Object.assign()` to put new methods on the prototype, which are previously defined in the merged declaration above.  Finally, a `satisfies` clause (which is a transient type-check; it does not change any types but it _will_ generate a compiler error) ensures the props being added to the prototype match what we've defined.

You'll also note that each method has a `this` parameter, which is not a "real" parameter--it's just an annotation for TS which tells the method what the  context is.  If we hate that, an alternative is to use `FakeDriver.prototype.method = <method>` instead of the `Object.assign` call.  This feels marginally more tedious, but I could go either way.
2023-02-27 14:15:11 -08:00
Christopher Hiller 0f196bad4a chore(types,base-driver): move/remove generics and constraints in Driver
These types were "wrong" in that it is exceedingly difficult to successfully implement `getLog()`, `getLogTypes()`, `supportLogTypes`, etc., in a third-party driver because you'd need to implement _all of it_ or _none of it_.  It's especially bad because it does this without prescribing where the logs should be stored (which is by design).  Oops.

This also moves some generics in the "find" mixins.  This may change again later, but it's unclear that any given driver must declare what a "context" is, and that there can only be one per driver.
2023-02-27 14:15:11 -08:00
renovate[bot] 431092dc87 fix(docutils): update dependency typedoc to v0.23.26 2023-02-27 20:25:05 +00:00
renovate[bot] 935c70683f chore(docutils): update dependency mkdocs-material to v9.0.15 2023-02-27 15:06:51 +00:00
renovate[bot] f8099dafa7 chore(deps): update dependency @types/node to v18.14.2 2023-02-27 10:31:03 +00:00
Kazuaki Matsuo 25c9728f07 docs: update readme (#18251)
* docs: update readme

* Update README.md
2023-02-26 17:24:49 -08:00
renovate[bot] ba6b312244 chore(deps): update dependency eslint to v8.35.0 2023-02-26 13:02:12 +00:00
renovate[bot] 188ed161e4 fix(support): update dependency jimp to v0.22.7 2023-02-25 09:50:30 +00:00
renovate[bot] 96898c87d5 fix(support): update dependency @types/glob to v8.1.0 2023-02-25 02:14:49 +00:00
202 changed files with 9534 additions and 4395 deletions
-3
View File
@@ -4,8 +4,5 @@ examples/javascript-wd
**/build/**
**/*.min.js
sample-code
**/*.d.ts
**/build-fixtures/**
**/*.ts
packages/appium/docs/**/assets/**
**/*.tsx
+8 -1
View File
@@ -1,5 +1,5 @@
{
"extends": "@appium/eslint-config-appium",
"extends": ["@appium/eslint-config-appium-ts"],
"overrides": [
{
"files": "packages/fake-driver/**/*",
@@ -26,9 +26,16 @@
"sourceType": "script"
}
},
{
"files": ["./test/setup.js", "./**/scripts/**/*.js", "./packages/*/index.js"],
"rules": {
"@typescript-eslint/no-var-requires": "off"
}
},
{
"files": "./packages/*/test/**/*.js",
"rules": {
"@typescript-eslint/no-var-requires": "off",
"no-restricted-properties": [
"error",
{
+143
View File
@@ -0,0 +1,143 @@
version: v1
labels:
- label: 'Enhancement'
sync: true
matcher:
commits: '^feat.*?:'
title: '^feat.*?:'
- label: 'Bug'
sync: true
matcher:
commits: '^fix.*?:'
title: '^fix.*?:'
- label: 'Documentation'
sync: true
matcher:
commits: '^docs.*?:'
title: '^docs.*?:'
files: ['packages/docutils/**', 'packages/appium/docs/**', '**/*.md']
- label: 'chore'
sync: true
matcher:
commits: '^chore.*?:'
title: '^chore.*?:'
- label: 'SemVer:Breaking'
sync: true
matcher:
commits: '(^(.+?)!:)|(BREAKING CHANGE:)'
- label: 'Dependencies'
sync: true
matcher:
files: ['**/package.json', '**/package-lock.json', '**/requirements.txt']
author: 'renovate'
- label: 'appium core'
sync: true
matcher:
files: ['packages/appium/**']
- label: '@appium/base-driver'
sync: true
matcher:
files: ['packages/base-driver/**']
- label: '@appium/eslint-config-appium'
sync: true
matcher:
files: ['packages/eslint-config-appium/**']
- label: '@appium/base-plugin'
sync: true
matcher:
files: ['packages/base-plugin/**']
- label: '@appium/doctor'
sync: true
matcher:
files: ['packages/doctor/**']
- label: '@appium/docutils'
sync: true
matcher:
files: ['packages/docutils/**']
- label: '@appium/driver-test-support'
sync: true
matcher:
files: ['packages/driver-test-support/**']
- label: '@appium/execute-driver-plugin'
sync: true
matcher:
files: ['packages/execute-driver-plugin/**']
- label: '@appium/fake-driver'
sync: true
matcher:
files: ['packages/fake-driver/**']
- label: '@appium/fake-plugin'
sync: true
matcher:
files: ['packages/fake-plugin/**']
- label: '@appium/images-plugin'
sync: true
matcher:
files: ['packages/images-plugin/**']
- label: '@appium/opencv'
sync: true
matcher:
files: ['packages/opencv/**']
- label: '@appium/plugin-test-support'
sync: true
matcher:
files: ['packages/plugin-test-support/**']
- label: '@appium/relaxed-caps-plugin'
sync: true
matcher:
files: ['packages/relaxed-caps-plugin/**']
- label: '@appium/schema'
sync: true
matcher:
files: ['packages/schema/**']
- label: '@appium/support'
sync: true
matcher:
files: ['packages/support/**']
- label: '@appium/test-support'
sync: true
matcher:
files: ['packages/test-support/**']
- label: '@appium/tsconfig'
sync: true
matcher:
files: ['packages/tsconfig/**']
- label: '@appium/typedoc-plugin-appium'
sync: true
matcher:
files: ['packages/typedoc-plugin-appium/**']
- label: '@appium/types'
sync: true
matcher:
files: ['packages/types/**']
- label: '@appium/universal-xml-plugin'
sync: true
matcher:
files: ['packages/universal-xml-plugin/**']
+3 -21
View File
@@ -13,7 +13,7 @@ jobs:
node-version: [14.x, 16.x, 18.x]
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3
- uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3
with:
@@ -33,33 +33,15 @@ jobs:
name: Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3
- uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # v3
- name: Install dependencies
uses: bahmutov/npm-install@1a235c31658a322a3b024444759650ee6345c26d # tag=v1
with:
useRollingCache: true
install-command: npm ci
- name: ESLint
run: npm run lint
run: npm run lint:ci
- name: Validate Renovate Config
uses: rinchsan/renovate-config-validator@1ea1e8514f6a33fdd71c40b0a5fa3512b9e7b936 # tag=v0
with:
pattern: '{.renovaterc.json,renovate/default.json}'
docs:
name: Docs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3
- name: Install dependencies (node)
uses: bahmutov/npm-install@1a235c31658a322a3b024444759650ee6345c26d # tag=v1
with:
useRollingCache: true
install-command: npm ci
- name: Install dependencies (python)
run: pip install -r packages/docutils/requirements.txt
- name: Build Docs
run: |
git config user.name 'Appium Bot'
git config user.email 'appium@appium.io'
npm run --workspace packages/appium build:docs
+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3
uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # v3
- name: Cleanup
run: |
+40
View File
@@ -0,0 +1,40 @@
name: Build Docs
on:
pull_request:
types:
- opened
- reopened
- synchronize
- closed
paths:
- './packages/appium/docs/**'
- './packages/docutils/**'
- './packages/typedoc-plugin-appium/**'
concurrency: preview-${{ github.ref }}
jobs:
docs:
name: Docs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # v3
- name: Install dependencies (node)
uses: bahmutov/npm-install@1a235c31658a322a3b024444759650ee6345c26d # tag=v1
with:
useRollingCache: true
install-command: npm ci
- name: Install dependencies (python)
run: pip install -r packages/docutils/requirements.txt
- name: Configure Git User
run: |
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
- name: Build Docs
run: npm run docs:preview
- name: Deploy Preview
if: ${{ github.repository == 'appium/appium' }}
uses: rossjrw/pr-preview-action@9dac5c4777c535516ebf819f93aeadac70f66488 # v1
with:
source-dir: ./packages/appium/docs/site
+1 -1
View File
@@ -11,7 +11,7 @@ jobs:
name: Run FOSSA Analysis
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3
- uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # v3
with:
ref: master
- name: Install dependencies
+22
View File
@@ -0,0 +1,22 @@
name: 'Labeler'
on:
pull_request:
types: [opened, synchronize]
permissions:
contents: read
issues: read # change this if/when we want to label issues
pull-requests: write
statuses: read
checks: read
jobs:
labeler:
if: ${{ github.repository == 'appium/appium' }}
name: Labeler
runs-on: ubuntu-latest
steps:
# follows semantic versioning. Lock to different version: v1, v1.5, v1.5.0 or use a commit hash.
- uses: fuxingloh/multi-labeler@6704db0bcba106d07482efabbc79d3092af74fa2 # v2
with:
github-token: ${{secrets.GITHUB_TOKEN}} # optional, default to '${{ github.token }}'
+2 -2
View File
@@ -5,10 +5,10 @@ on:
jobs:
label-check:
if: github.base_ref == 'master'
if: ${{ github.base_ref == 'master' && github.repository == 'appium/appium' }}
runs-on: ubuntu-latest
steps:
- uses: danielchabr/pr-labels-checker@e1d7e79aa0933af1728011705a30528a279874fd
- uses: danielchabr/pr-labels-checker@e1d7e79aa0933af1728011705a30528a279874fd # v3.1
with:
id: check-labels
hasNone: On Hold
-1
View File
@@ -59,7 +59,6 @@ appium.zip
*.tsbuildinfo
packages/*/LICENSE
local_appium_home
jsdoc-out
*.tgz
typedoc-docs
packages/appium/docs/*/reference
+1 -1
View File
@@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright JS Foundation and other contributors, https://js.foundation
Copyright OpenJS Foundation and other contributors, https://openjsf.org/
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
+6 -8
View File
@@ -12,8 +12,9 @@
Appium is an open-source, cross-platform test automation tool for native,
hybrid, mobile web and desktop apps. Initially created to automate iOS and Android mobile
applications Appium has grown to a full-featured platform that provides [WebDriver](https://www.w3.org/TR/webdriver/)-based automation possibilities for the whole set of different mobile and desktop platforms.
See [Drivers Maintained By The Appium Team](#drivers-maintained-by-the-appium-team)
and [Drivers Provided By Third Parties](#drivers-provided-by-third-parties) sections below for more details.
See the full list of
[officially-supported](https://appium.github.io/appium/docs/en/latest/ecosystem/#drivers) and
[third-party](https://appium.github.io/appium/docs/en/latest/ecosystem/#other-drivers) drivers for more details.
:bangbang: Major documentation revision in progress
@@ -57,7 +58,7 @@ appium driver install --source=npm appium-xcuitest-driver[@<version>]
# To install a driver from a local folder (useful for developers)
appium driver install --source=local /Users/me/sources/appium-xcuitest-driver
# To install a new driver from github (hm, maybe it's time to publish it to NPM?)
appium driver install --source=github appium/appium-xcuitest-driver
appium driver install --source=github --package=appium-xcuitest-driver appium/appium-xcuitest-driver
# To list already installed drivers
appium driver list --installed
@@ -168,7 +169,7 @@ Java/Kotlin. Appium opens up the possibility of true cross-platform native app
automation, for mobile and beyond. Finally!
If you're new to Appium or want a more comprehensive description of what this is all
about, please read our [Introduction to Appium Concepts](/docs/en/about-appium/intro.md).
about, please read our [Intro to Appium](https://appium.github.io/appium/docs/en/latest/intro/).
### Quickstart
@@ -204,10 +205,7 @@ be sure to sign up!
### Troubleshooting
We put together a [troubleshooting guide](/docs/en/writing-running-appium/other/troubleshooting.md).
Please have a look here first if you run into any problems. It contains instructions for checking
a lot of common errors and how to get in touch with the community if you're
stumped.
Please find the troubleshooting guide at the corresponding driver repository/documentation.
### License
+4732 -1085
View File
File diff suppressed because it is too large Load Diff
+28 -21
View File
@@ -30,22 +30,24 @@
"build": "tsc -b",
"build:all": "run-s build build:packages",
"build:packages": "lerna run build",
"clean": "run-s \"clean:artifacts:*\" clean:workspaces",
"clean": "run-s clean:artifacts clean:workspaces",
"clean:artifacts": "run-p \"clean:artifacts:*\"",
"clean:artifacts:distfiles": "npx rimraf \"./packages/*/build\" \"./packages/*/.tsconfig.tsbuildinfo\"",
"clean:artifacts:packages": "lerna run clean || true",
"clean:workspaces": "lerna clean -y",
"ci": "npm ci",
"dev": "run-s \"build -- --watch\"",
"docs": "npm run -w packages/appium build:docs",
"docs:preview": "npm run -w packages/appium build:docs:preview",
"doctor": "node ./packages/doctor",
"husky-install": "husky install",
"generate-docs": "npm run --workspace=packages/appium generate-docs",
"prepare": "run-p husky-install build:all || true",
"prepare": "run-p husky-install build:all",
"lint": "eslint .",
"lint:fix": "run-s \"lint -- --fix\"",
"lint:ci": "eslint --quiet .",
"lint:commit": "commitlint",
"lint:staged": "lint-staged",
"pack-all": "npm pack --workspaces --include-workspace-root",
"prepublishOnly": "run-s rebuild",
"reinstall": "run-s clean ci",
"rebuild": "run-s clean:artifacts build:all",
@@ -53,17 +55,19 @@
"sync-pkgs": "run-p sync-pkgs:*",
"sync-pkgs:appium-readme": "sync-monorepo-packages --force --no-package-json --packages=packages/appium README.md",
"sync-pkgs:common-fields": "sync-monorepo-packages --fields=author,license,bugs,homepage,engines",
"sync-pkgs:keywords": "sync-monorepo-packages --field=keywords --packages=\"packages/*\" --packages=\"!packages/eslint-config-appium\" --packages=\"!packages/types\" --packages=\"!packages/typedoc-plugin-appium\"",
"sync-pkgs:keywords": "sync-monorepo-packages --field=keywords --packages=\"packages/*\" --packages=\"!packages/eslint-config-appium\" --packages=\"!packages/types\" --packages=\"!packages/typedoc-plugin-appium\" --packages=\"!packages/eslint-config-appium-ts\" ",
"sync-pkgs:license": "sync-monorepo-packages --force --no-package-json LICENSE",
"stage-synced-pkgs": "git add -A packages/appium/README.md \"packages/*/package.json\"",
"test": "npm-run-all -p lint build -s test:unit",
"test": "run-p lint build:all && run-p test:unit test:types",
"test:ci": "run-s test:smoke test:unit test:e2e",
"test:e2e": "lerna run --concurrency=2 test:e2e",
"test:smoke": "smoker --all test:smoke",
"test:types": "lerna run test:types",
"test:unit": "lerna run test",
"typedoc": "typedoc --logLevel Verbose",
"upload": "gulp github-upload",
"preversion": "run-s rebuild sync-pkgs stage-synced-pkgs",
"preversion": "run-s sync-pkgs stage-synced-pkgs",
"prepack": "npm run rebuild",
"zip": "zip -qr ./appium.zip ./packages/appium",
"zip-and-upload": "run-s zip upload"
},
@@ -74,28 +78,31 @@
},
"devDependencies": {
"@colors/colors": "1.5.0",
"@commitlint/cli": "17.4.4",
"@commitlint/cli": "17.5.1",
"@commitlint/config-conventional": "17.4.4",
"@tsconfig/node14": "1.0.3",
"@types/chai": "4.3.4",
"@types/chai-as-promised": "7.1.5",
"@types/diff": "5.0.2",
"@types/diff": "5.0.3",
"@types/mocha": "10.0.1",
"@types/node": "18.14.1",
"@types/node": "18.15.10",
"@types/semver": "7.3.13",
"@types/sinon": "10.0.13",
"@types/sinon-chai": "3.2.9",
"@types/teen_process": "2.0.0",
"@types/ws": "8.5.4",
"@types/yargs": "17.0.22",
"@types/yargs": "17.0.24",
"@typescript-eslint/eslint-plugin": "5.57.0",
"@typescript-eslint/parser": "5.57.0",
"asyncbox": "2.9.4",
"chai": "4.3.7",
"chai-as-promised": "7.1.1",
"chai-webdriverio-async": "2.7.0",
"cpy-cli": "4.2.0",
"eslint": "8.34.0",
"eslint-config-prettier": "8.6.0",
"eslint": "8.36.0",
"eslint-config-prettier": "8.8.0",
"eslint-find-rules": "4.1.0",
"eslint-import-resolver-typescript": "3.5.3",
"eslint-plugin-import": "2.27.5",
"eslint-plugin-mocha": "10.1.0",
"eslint-plugin-promise": "6.1.1",
@@ -104,31 +111,32 @@
"get-port": "5.1.1",
"handlebars": "4.7.7",
"husky": "8.0.3",
"json-schema-to-typescript": "11.0.5",
"lerna": "6.5.1",
"lint-staged": "13.1.2",
"json-schema-to-typescript": "12.0.0",
"lerna": "6.6.1",
"lint-staged": "13.2.0",
"log-symbols": "4.1.0",
"midnight-smoker": "2.0.1",
"mjpeg-consumer": "2.0.0",
"mjpeg-server": "0.3.1",
"mocha": "10.2.0",
"npm-run-all": "4.1.5",
"prettier": "2.8.4",
"prettier": "2.8.7",
"rewiremock": "3.14.5",
"rimraf": "3.0.2",
"serve-static": "1.15.0",
"sinon": "15.0.1",
"sinon": "15.0.3",
"sinon-chai": "3.7.0",
"sync-monorepo-packages": "1.0.2",
"through2": "4.0.2",
"ts-node": "10.9.1",
"typedoc": "0.23.25",
"tsd": "0.28.1",
"typedoc": "0.23.28",
"typedoc-plugin-markdown": "3.14.0",
"typedoc-plugin-resolve-crossmodule-references": "0.3.3",
"typescript": "4.9.5",
"validate.js": "0.13.1",
"webdriverio": "7.30.1",
"ws": "8.12.1",
"webdriverio": "7.30.2",
"ws": "8.13.0",
"yaml-js": "0.3.1"
},
"engines": {
@@ -139,7 +147,6 @@
"access": "public"
},
"overrides": {
"jpeg-js": "0.4.4",
"@sidvind/better-ajv-errors": {
"ajv": "8.12.0"
},
+35
View File
@@ -3,6 +3,41 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [2.0.0-beta.58](https://github.com/appium/appium/compare/appium@2.0.0-beta.57...appium@2.0.0-beta.58) (2023-03-28)
### Bug Fixes
* **appium,types,base-driver,fake-driver,driver-test-support:** normalize constraint defaults ([3c9fa7b](https://github.com/appium/appium/commit/3c9fa7ba73b639e610e1f3d41d239a9402845b4c))
* **appium:** remove longjohn ([0c52b50](https://github.com/appium/appium/commit/0c52b50e6595a16287d0bb71960fb2e08278de6f)), closes [#18357](https://github.com/appium/appium/issues/18357)
* backwards-compatible fixes for TS v5.x ([4974403](https://github.com/appium/appium/commit/49744036619ecc239e0e6255a13d38cafd709920))
* **types:** update dependency type-fest to v3.7.0 ([6912fa1](https://github.com/appium/appium/commit/6912fa14f2a7d338f17e1bed060e959de7aba1d6))
* **types:** update dependency type-fest to v3.7.1 ([bc860c7](https://github.com/appium/appium/commit/bc860c733a73760f0c42cbfb384e04d50c376d5e))
### Features
* **appium:** improvements to ext commands when running extension in development ([d9b47bc](https://github.com/appium/appium/commit/d9b47bc86434c50382221397cf39c10e661c1ea9)), closes [#18277](https://github.com/appium/appium/issues/18277)
# [2.0.0-beta.57](https://github.com/appium/appium/compare/appium@2.0.0-beta.56...appium@2.0.0-beta.57) (2023-03-08)
### Bug Fixes
* **appium,fake-driver:** expose child process when running an extension script ([e9dae3f](https://github.com/appium/appium/commit/e9dae3f6d006dcf89b6c0b6fb491be15acfed98b))
* **appium,support:** fs.readPackageJsonFrom() returns proper type ([9ccbab5](https://github.com/appium/appium/commit/9ccbab5dc02d0019b0cad903772cda872d9fd5fb))
* **docutils:** update dependency lilconfig to v2.1.0 ([4ed745a](https://github.com/appium/appium/commit/4ed745a95ffc6a43f76003eba62019c16a4c6cf2))
* **execute-driver-plugin:** update dependency webdriverio to v7.30.2 ([49694f5](https://github.com/appium/appium/commit/49694f50a4680138cc92aba1eee294c927d712cf))
* **types:** update dependency type-fest to v3.6.1 ([471a4b5](https://github.com/appium/appium/commit/471a4b57e622ff077d59f577a78341268700c48d))
# [2.0.0-beta.56](https://github.com/appium/appium/compare/appium@2.0.0-beta.55...appium@2.0.0-beta.56) (2023-02-24)
+6 -8
View File
@@ -12,8 +12,9 @@
Appium is an open-source, cross-platform test automation tool for native,
hybrid, mobile web and desktop apps. Initially created to automate iOS and Android mobile
applications Appium has grown to a full-featured platform that provides [WebDriver](https://www.w3.org/TR/webdriver/)-based automation possibilities for the whole set of different mobile and desktop platforms.
See [Drivers Maintained By The Appium Team](#drivers-maintained-by-the-appium-team)
and [Drivers Provided By Third Parties](#drivers-provided-by-third-parties) sections below for more details.
See the full list of
[officially-supported](https://appium.github.io/appium/docs/en/latest/ecosystem/#drivers) and
[third-party](https://appium.github.io/appium/docs/en/latest/ecosystem/#other-drivers) drivers for more details.
:bangbang: Major documentation revision in progress
@@ -57,7 +58,7 @@ appium driver install --source=npm appium-xcuitest-driver[@<version>]
# To install a driver from a local folder (useful for developers)
appium driver install --source=local /Users/me/sources/appium-xcuitest-driver
# To install a new driver from github (hm, maybe it's time to publish it to NPM?)
appium driver install --source=github appium/appium-xcuitest-driver
appium driver install --source=github --package=appium-xcuitest-driver appium/appium-xcuitest-driver
# To list already installed drivers
appium driver list --installed
@@ -168,7 +169,7 @@ Java/Kotlin. Appium opens up the possibility of true cross-platform native app
automation, for mobile and beyond. Finally!
If you're new to Appium or want a more comprehensive description of what this is all
about, please read our [Introduction to Appium Concepts](/docs/en/about-appium/intro.md).
about, please read our [Intro to Appium](https://appium.github.io/appium/docs/en/latest/intro/).
### Quickstart
@@ -204,10 +205,7 @@ be sure to sign up!
### Troubleshooting
We put together a [troubleshooting guide](/docs/en/writing-running-appium/other/troubleshooting.md).
Please have a look here first if you run into any problems. It contains instructions for checking
a lot of common errors and how to get in touch with the community if you're
stumped.
Please find the troubleshooting guide at the corresponding driver repository/documentation.
### License
+1 -1
View File
@@ -54,7 +54,7 @@ These drivers are not maintained by the Appium team and can be used to target ad
## Clients
You need a clients to write and run Appium scripts. To learn more about clients, read our [Client
You need clients to write and run Appium scripts. To learn more about clients, read our [Client
Intro](../intro/clients.md). Here is the list of known Appium clients. You'll want to become very
familiar with your client documentation (as well as the documentation of any Selenium client that
the Appium client depends on) since that is what you will use as your primary interface to Appium.
+1 -1
View File
@@ -20,7 +20,7 @@ JavaScript, Python, and Java, though [Appium clients](../ecosystem/index.md#clie
Before getting started, make sure your system satisfies the
[requirements](../intro/requirements.md) for running the Appium server. Additional requirements
will be discussed in conjunction with installing the UiAutomator2 driver. The guide also assumes
you're basic command line proficiency on your platform, for example being able to run commands, set
you have basic command line proficiency on your platform, for example being able to run commands, set
and persist environment variables, etc...
Now you're ready to get started! So head on over to [Installing Appium](./install.md).
@@ -1,3 +1,6 @@
<!---Current latest commit hash in the original English documentation is e4dfa52 --->
---
title: Appium 1.xからAppium 2.xへ移行する
---
@@ -39,15 +42,39 @@ Together these do introduce a few breaking changes to how Appium is installed, h
## 破壊的変更
<!---
Have a look at the [Appium 2.0 release notes](https://github.com/appium/appium/releases) for the most comprehensive lists of changes. Here we call out the breaking changes and what you need to do to account for them.
Here we call out the breaking changes and what you need to do to account for them.
--->
リリース毎の変更一覧に関しては[Appium 2.0リリースノート](https://github.com/appium/appium/releases)を確認してください。ここでは破壊的変更と何をする必要があるのかを示します。
以下では破壊的変更と、何をする必要があるのかを示します。
<!---
### :bangbang: Installing drivers during setup
--->
### :bangbang: 初期設定のbase path
<!---
With Appium 1.x, the server would accept commands by default on `http://localhost:4723/wd/hub`. The
`/wd/hub` base path was a legacy convention from the days of migrating from Selenium 1 to Selenium
2, and is no longer relevant. As such the default base path for the server is now `/`. If you want
to retain the old behaviour, you can set the base path via a command line argument as follows:
--->
Appium 1.xでは、AppiumサーバーのURLは`http://localhost:4723/wd/hub`でした。この`/wd/hub`であるbase pathはSelenium 1からSelenium 2へ移行した時の名残であり、今となっては何ら意味を持ちません。そのため、初期設定のbase pathは`/`となります。もしあたなが以前の挙動を保持したいのであれば、以下の通りにAppiumサーバを起動してください。
```
appium --base-path=/wd/hub
```
<!---
You can also set server arguments as [Config file](./config.md) properties.
--->
この設定は[Config file](./config.md)からでも可能です。
### :bangbang: ドライバーのインストール
<!---
@@ -72,10 +99,10 @@ npm install --global appium --drivers=xcuitest,uiautomator2
```
<!---
This will install Appium and the two drivers for you in one go.
This will install Appium and the two drivers for you in one go. Please uninstall any existing Appium 1.x npm packages (with `npm uninstall -g appium`) if you get an installation or startup error.
--->
これはAppiumと2つのドライバーを一つのコマンドでインストールします。
これはAppiumと2つのドライバーを一つのコマンドでインストールします。もしセットアップで何らかの問題が発生した場合、既存のAppium 1.xを`npm uninstall -g appium`で削除してみてください。
### :bangbang: Drivers installation path
@@ -224,6 +251,17 @@ In summary, if you are using a JSON Appium config file, you can simply cut-and-p
The old iOS and Android (UiAutomator 1) drivers and related tools (e.g., `authorize-ios`) have been removed. They haven't been relevant for many years anyway.
### :bangbang: Server can no longer be started with `--port 0`
In Appium 1.x, it was possible to specify `--port 0` during server startup. This had the effect of
starting Appium on a random free port. In Appium 2.0, port values must be `1` or higher. The random
port assignment was never an intentional feature of Appium 1.x, but a consequence of how Node's
HTTP servers work and the fact that there was no port input validation in Appium 1.x. If you want
to find a random free port to start Appium on, you must now take care of this on your own prior to
starting Appium. Starting Appium on an explicit and known port is the correct practice moving
forward.
### :warning: Internal packages renamed
Some Appium-internal NPM packages have been renamed (for example, `appium-base-driver` is now `@appium/base-driver`). This is not a breaking change for Appium users, only for people who have built software that directly incorporates Appium's code.
+20 -12
View File
@@ -10,7 +10,7 @@
/* eslint-disable promise/prefer-await-to-callbacks */
/* eslint-disable promise/prefer-await-to-then */
const {buildReferenceDocs, deploy, updateNav} = require('@appium/docutils');
const {buildReferenceDocs, deploy, updateNav, buildSite} = require('@appium/docutils');
const {
log,
LANGS,
@@ -28,6 +28,7 @@ const {version} = require('../../package.json');
const branch = process.env.APPIUM_DOCS_BRANCH ?? DOCS_BRANCH;
const basePrefix = process.env.APPIUM_DOCS_PREFIX ?? DOCS_PREFIX;
const remote = process.env.APPIUM_DOCS_REMOTE ?? DOCS_REMOTE;
const preview = Boolean(process.env.APPIUM_DOCS_PREVIEW);
const push = Boolean(process.env.APPIUM_DOCS_PUBLISH);
const rebase = push;
@@ -51,17 +52,24 @@ async function main() {
for (const lang of LANGS) {
log.info(`Building docs for language '${lang}' and version ${majMinVer}`);
const configFile = path.join(DOCS_DIR, `mkdocs-${lang}.yml`);
await deploy({
mkdocsYml: configFile,
branch,
prefix: path.join(basePrefix, lang),
remote,
deployVersion: majMinVer,
push,
alias: LATEST_ALIAS,
rebase,
message: `docs(appium): auto-build docs for appium@${majMinVer}, language ${lang}`,
});
if (preview) {
await buildSite({
mkdocsYml: configFile,
siteDir: path.join('site', lang),
});
} else {
await deploy({
mkdocsYml: configFile,
branch,
prefix: path.join(basePrefix, lang),
remote,
deployVersion: majMinVer,
push,
alias: LATEST_ALIAS,
rebase,
message: `docs(appium): auto-build docs for appium@${majMinVer}, language ${lang}`,
});
}
log.info(`Docs built`);
}
}
-10
View File
@@ -1,10 +0,0 @@
const {baseConfig} = require('@appium/docutils');
const lang = process.env.APPIUM_DOCS_LANG || 'en';
const config = {...baseConfig};
config.opts.source.include = [];
config.opts.tutorials = `./docs/${lang}`;
config.opts.readme = `${config.opts.tutorials}/README.md`;
module.exports = config;
+43 -32
View File
@@ -28,15 +28,12 @@ const desiredCapabilityConstraints = /** @type {const} */ ({
isString: true,
},
});
/**
* @typedef {typeof desiredCapabilityConstraints} AppiumDriverConstraints
*/
const sessionsListGuard = new AsyncLock();
const pendingDriversGuard = new AsyncLock();
/**
* @implements {SessionHandler}
* @extends {DriverCore<AppiumDriverConstraints>}
*/
class AppiumDriver extends DriverCore {
/**
@@ -92,11 +89,11 @@ class AppiumDriver extends DriverCore {
*/
desiredCapConstraints;
/** @type {DriverOpts} */
/** @type {import('@appium/types').DriverOpts<AppiumDriverConstraints>} */
args;
/**
* @param {DriverOpts} opts
* @param {import('@appium/types').DriverOpts<AppiumDriverConstraints>} opts
*/
constructor(opts) {
// It is necessary to set `--tmp` here since it should be set to
@@ -163,11 +160,10 @@ class AppiumDriver extends DriverCore {
};
}
// eslint-disable-next-line require-await
async getSessions() {
return _.toPairs(this.sessions).map(([id, driver]) => ({
id,
capabilities: driver.caps,
capabilities: /** @type {import('@appium/types').DriverCaps} */ (driver.caps),
}));
}
@@ -224,12 +220,12 @@ class AppiumDriver extends DriverCore {
/**
* Create a new session
* @param {W3CCapabilities<AppiumDriverConstraints>} jsonwpCaps JSONWP formatted desired capabilities
* @param {W3CCapabilities<AppiumDriverConstraints>} reqCaps Required capabilities (JSONWP standard)
* @param {W3CCapabilities<AppiumDriverConstraints>} w3cCapabilities W3C capabilities
* @param {DriverData[]} [driverData]
* @param {W3CAppiumDriverCaps} jsonwpCaps JSONWP formatted desired capabilities
* @param {W3CAppiumDriverCaps} [reqCaps] Required capabilities (JSONWP standard)
* @param {W3CAppiumDriverCaps} [w3cCapabilities] W3C capabilities
* @returns {Promise<SessionHandlerCreateResult>}
*/
async createSession(jsonwpCaps, reqCaps, w3cCapabilities, driverData) {
async createSession(jsonwpCaps, reqCaps, w3cCapabilities) {
const defaultCapabilities = _.cloneDeep(this.args.defaultCapabilities);
const defaultSettings = pullSettings(defaultCapabilities);
jsonwpCaps = _.cloneDeep(jsonwpCaps);
@@ -247,13 +243,14 @@ class AppiumDriver extends DriverCore {
Object.assign(w3cSettings, pullSettings(firstMatchEntry));
}
/** @type {string|undefined} */
let protocol;
let innerSessionId, dCaps;
try {
// Parse the caps into a format that the InnerDriver will accept
const parsedCaps = parseCapsForInnerDriver(
jsonwpCaps,
promoteAppiumOptions(w3cCapabilities),
promoteAppiumOptions(/** @type {W3CAppiumDriverCaps} */ (w3cCapabilities)),
this.desiredCapConstraints,
defaultCapabilities ? promoteAppiumOptionsForObject(defaultCapabilities) : undefined
);
@@ -289,7 +286,7 @@ class AppiumDriver extends DriverCore {
*/
let otherPendingDriversData = [];
const driverInstance = new InnerDriver(this.args, true);
const driverInstance = /** @type {ExternalDriver} */ (new InnerDriver(this.args, true));
// We want to assign security values directly on the driver. The driver
// should not read security values from `this.opts` because those values
@@ -399,7 +396,7 @@ class AppiumDriver extends DriverCore {
/**
*
* @param {Driver} driver
* @param {ExternalDriver} driver
* @param {string} innerSessionId
*/
attachUnexpectedShutdownHandler(driver, innerSessionId) {
@@ -442,10 +439,11 @@ class AppiumDriver extends DriverCore {
/**
*
* @param {DriverClass} InnerDriver
* @param {((...args: any[]) => any)|(new(...args: any[]) => any)} InnerDriver
* @returns {Promise<DriverData[]>}}
* @privateRemarks The _intent_ is that `InnerDriver` is the class of a driver, but it only really
* needs to be a function or constructor.
*/
// eslint-disable-next-line require-await
async curSessionDataForDriver(InnerDriver) {
const data = _.compact(
_.values(this.sessions)
@@ -588,7 +586,7 @@ class AppiumDriver extends DriverCore {
*
* @param {string} cmd
* @param {...any} args
* @returns {Promise<{value: any, error?: Error, protocol: string} | import('type-fest').AsyncReturnType<Driver['executeCommand']>>}
* @returns {Promise<{value: any, error?: Error, protocol: string} | import('type-fest').AsyncReturnType<ExternalDriver['executeCommand']>>}
*/
async executeCommand(cmd, ...args) {
// We have basically three cases for how to handle commands:
@@ -618,6 +616,7 @@ class AppiumDriver extends DriverCore {
let dstSession = null;
let protocol = null;
/** @type {this | ExternalDriver} */
// eslint-disable-next-line @typescript-eslint/no-this-alias
let driver = this;
if (isSessionCmd) {
sessionId = _.last(args);
@@ -840,21 +839,38 @@ export class NoDriverProxyCommandError extends Error {
export {AppiumDriver};
/**
* @typedef {import('@appium/types').ExternalDriver} ExternalDriver
* @typedef {import('@appium/types').Driver} Driver
* @typedef {import('@appium/types').DriverClass} DriverClass
* @typedef {import('@appium/types').DriverData} DriverData
* @typedef {import('@appium/types').ServerArgs} DriverOpts
* @typedef {import('@appium/types').Constraints} Constraints
* @typedef {import('@appium/types').AppiumServer} AppiumServer
* @typedef {import('@appium/types').ExtensionType} ExtensionType
* @typedef {import('./extension/driver-config').DriverConfig} DriverConfig
* @typedef {import('@appium/types').Plugin} Plugin
* @typedef {import('@appium/types').PluginClass} PluginClass
* @typedef {import('@appium/types').PluginType} PluginType
* @typedef {import('@appium/types').DriverType} DriverType
* @typedef {import('@appium/types').StringRecord} StringRecord
* @typedef {import('@appium/types').SessionHandler<SessionHandlerResult<any[]>,SessionHandlerResult<void>>} SessionHandler
* @typedef {import('@appium/types').ExternalDriver} ExternalDriver
* @typedef {import('@appium/types').PluginClass} PluginClass
* @typedef {import('@appium/types').Plugin} Plugin
* @typedef {import('@appium/types').DriverClass<import('@appium/types').Driver>} DriverClass
*/
/**
* @typedef {import('@appium/types').ISessionHandler<AppiumDriverConstraints,
* SessionHandlerCreateResult, SessionHandlerDeleteResult>} AppiumSessionHandler
*/
/**
* @typedef {SessionHandlerResult<[innerSessionId: string, caps:
* import('@appium/types').DriverCaps<Constraints>, protocol: string|undefined]>} SessionHandlerCreateResult
*/
/**
* @template {Constraints} C
* @typedef {import('@appium/types').Core<C>} Core
*/
/**
* @typedef {SessionHandlerResult<void>} SessionHandlerDeleteResult
*/
/**
@@ -868,11 +884,6 @@ export {AppiumDriver};
*/
/**
* @template {Constraints} C
* @typedef {import('@appium/types').W3CCapabilities<C>} W3CCapabilities
*/
/**
* @template {Constraints} C
* @typedef {import('@appium/types').Capabilities<C>} Capabilities
* @typedef {typeof desiredCapabilityConstraints} AppiumDriverConstraints
* @typedef {import('@appium/types').W3CDriverCaps<AppiumDriverConstraints>} W3CAppiumDriverCaps
*/
+10
View File
@@ -84,6 +84,16 @@ function makeListArgs(type) {
dest: 'showUpdates',
},
],
[
['--verbose'],
{
required: false,
default: false,
action: 'store_true',
help: 'Show more information about each extension',
dest: 'verbose',
},
],
]);
}
+13 -8
View File
@@ -1,15 +1,15 @@
import _ from 'lodash';
import ExtensionCommand from './extension-command';
import ExtensionCliCommand from './extension-command';
import {KNOWN_DRIVERS} from '../constants';
import '@colors/colors';
const REQ_DRIVER_FIELDS = ['driverName', 'automationName', 'platformNames', 'mainClass'];
/**
* @extends {ExtensionCommand<DriverType>}
* @extends {ExtensionCliCommand<DriverType>}
*/
export default class DriverCommand extends ExtensionCommand {
export default class DriverCliCommand extends ExtensionCliCommand {
/**
* @param {import('./extension-command').ExtensionCommandOptions<DriverType>} opts
*/
@@ -58,7 +58,12 @@ export default class DriverCommand extends ExtensionCommand {
* @return {Promise<import('./extension-command').RunOutput>}
*/
async run({driver, scriptName, extraArgs}) {
return await super._run({installSpec: driver, scriptName, extraArgs});
return await super._run({
installSpec: driver,
scriptName,
extraArgs,
bufferOutput: this.isJsonOutput,
});
}
/**
@@ -115,7 +120,7 @@ export default class DriverCommand extends ExtensionCommand {
*/
/**
* Options for {@linkcode DriverCommand.install}
* Options for {@linkcode DriverCliCommand.install}
* @typedef DriverInstallOpts
* @property {string} driver - the name or spec of a driver to install
* @property {InstallType} installType - how to install this driver. One of the INSTALL_TYPES
@@ -127,20 +132,20 @@ export default class DriverCommand extends ExtensionCommand {
*/
/**
* Options for {@linkcode DriverCommand.uninstall}
* Options for {@linkcode DriverCliCommand.uninstall}
* @typedef DriverUninstallOpts
* @property {string} driver - the name or spec of a driver to uninstall
*/
/**
* Options for {@linkcode DriverCommand.update}
* Options for {@linkcode DriverCliCommand.update}
* @typedef DriverUpdateOpts
* @property {string} driver - the name of the driver to update
* @property {boolean} unsafe - if true, will perform unsafe updates past major revision boundaries
*/
/**
* Options for {@linkcode DriverCommand.run}.
* Options for {@linkcode DriverCliCommand.run}.
* @typedef DriverRunOptions
* @property {string} driver - name of the driver to run a script from
* @property {string} scriptName - name of the script to run
+146 -75
View File
@@ -4,14 +4,17 @@ import _ from 'lodash';
import path from 'path';
import {npm, util, env, console} from '@appium/support';
import {spinWith, RingBuffer} from './utils';
import {SubProcess} from 'teen_process';
import {
INSTALL_TYPE_NPM,
INSTALL_TYPE_GIT,
INSTALL_TYPE_GITHUB,
INSTALL_TYPE_LOCAL,
INSTALL_TYPE_DEV,
} from '../extension/extension-config';
import {SubProcess} from 'teen_process';
import {packageDidChange} from '../extension/package-changed';
import {spawn} from 'child_process';
import {inspect} from 'node:util';
const UPDATE_ALL = 'installed';
@@ -31,7 +34,7 @@ function receiptToManifest(receipt) {
/**
* @template {ExtensionType} ExtType
*/
class ExtensionCommand {
class ExtensionCliCommand {
/**
* This is the `DriverConfig` or `PluginConfig`, depending on `ExtType`.
* @type {ExtensionConfig<ExtType>}
@@ -98,41 +101,40 @@ class ExtensionCommand {
/**
* List extensions
*
* @template {ExtensionType} ExtType
* @param {ListOptions} opts
* @return {Promise<ExtensionListData>} map of extension names to extension data
* @return {Promise<ExtensionList<ExtType>>} map of extension names to extension data
*/
async list({showInstalled, showUpdates}) {
const lsMsg = `Listing ${showInstalled ? 'installed' : 'available'} ${this.type}s`;
async list({showInstalled, showUpdates, verbose = false}) {
let lsMsg = `Listing ${showInstalled ? 'installed' : 'available'} ${this.type}s`;
if (verbose) {
lsMsg += ' (verbose mode)';
}
const installedNames = Object.keys(this.config.installedExtensions);
const knownNames = Object.keys(this.knownExtensions);
const exts = [...installedNames, ...knownNames].reduce(
(acc, name) => {
if (!acc[name]) {
if (installedNames.includes(name)) {
acc[name] = {
...this.config.installedExtensions[name],
installed: true,
};
} else if (!showInstalled) {
acc[name] = {pkgName: this.knownExtensions[name], installed: false};
}
const listData = [...installedNames, ...knownNames].reduce((acc, name) => {
if (!acc[name]) {
if (installedNames.includes(name)) {
acc[name] = {
.../** @type {Partial<ExtManifest<ExtType>>} */ (this.config.installedExtensions[name]),
installed: true,
};
} else if (!showInstalled) {
acc[name] = /** @type {ExtensionListData<ExtType>} */ ({
pkgName: this.knownExtensions[name],
installed: false,
});
}
return acc;
},
/**
* This accumulator contains either {@linkcode UninstalledExtensionLIstData} _or_
* {@linkcode InstalledExtensionListData} without upgrade information (which is added by the below code block)
* @type {Record<string,Partial<InstalledExtensionListData>|UninstalledExtensionListData>}
*/ ({})
);
}
return acc;
}, /** @type {ExtensionList<ExtType>} */ ({}));
// if we want to show whether updates are available, put that behind a spinner
await spinWith(this.isJsonOutput, lsMsg, async () => {
if (!showUpdates) {
return;
}
for (const [ext, data] of _.toPairs(exts)) {
for (const [ext, data] of _.toPairs(listData)) {
if (!data.installed || data.installType !== INSTALL_TYPE_NPM) {
// don't need to check for updates on exts that aren't installed
// also don't need to check for updates on non-npm exts
@@ -149,7 +151,12 @@ class ExtensionCommand {
}
});
const listData = /** @type {ExtensionListData} */ (exts);
/**
* Type guard to narrow "installed" extensions, which have more data
* @param {any} data
* @returns {data is InstalledExtensionListData<ExtType>}
*/
const extIsInstalled = (data) => Boolean(data.installed);
// if we're just getting the data, short circuit return here since we don't need to do any
// formatting logic
@@ -157,12 +164,16 @@ class ExtensionCommand {
return listData;
}
if (verbose) {
this.log.log(inspect(listData, {colors: true, depth: null}));
return listData;
}
for (const [name, data] of _.toPairs(listData)) {
let installTxt = ' [not installed]'.grey;
let updateTxt = '';
let upToDateTxt = '';
let unsafeUpdateTxt = '';
if (data.installed) {
if (extIsInstalled(data)) {
const {
installType,
installSpec,
@@ -181,8 +192,11 @@ class ExtensionCommand {
case INSTALL_TYPE_LOCAL:
typeTxt = `(linked from ${installSpec})`.magenta;
break;
case INSTALL_TYPE_DEV:
typeTxt = '(dev mode)';
break;
default:
typeTxt = '(NPM)';
typeTxt = '(npm)';
}
installTxt = `@${version.yellow} ${('[installed ' + typeTxt + ']').green}`;
@@ -512,7 +526,12 @@ class ExtensionCommand {
`Can't uninstall ${this.type} '${installSpec}'; it is not installed`
);
}
const pkgName = this.config.installedExtensions[installSpec].pkgName;
const extRecord = this.config.installedExtensions[installSpec];
if (extRecord.installType === INSTALL_TYPE_DEV) {
this.log.warn(`Cannot uninstall ${this.type} "${installSpec}" because it is in development!`);
return this.config.installedExtensions;
}
const pkgName = extRecord.pkgName;
await npm.uninstallPackage(this.config.appiumHome, pkgName);
await this.config.removeExtension(installSpec);
this.log.ok(`Successfully uninstalled ${this.type} '${installSpec}'`.green);
@@ -660,17 +679,34 @@ class ExtensionCommand {
}
/**
* Runs a script cached inside the "scripts" field under "appium"
* inside of the driver/plugins "package.json" file. Will throw
* an error if the driver/plugin does not contain a "scripts" field
* underneath the "appium" field in its package.json, if the
* "scripts" field is not a plain object, or if the scriptName is
* not found within "scripts" object.
* Just wraps {@linkcode child_process.spawn} with some default options
*
* @param {string} cwd - CWD
* @param {string} script - Path to script
* @param {string[]} args - Extra args for script
* @param {import('child_process').SpawnOptions} opts - Options
* @returns {import('node:child_process').ChildProcess}
*/
_runUnbuffered(cwd, script, args = [], opts = {}) {
return spawn(process.execPath, [script, ...args], {
cwd,
stdio: 'inherit',
...opts,
});
}
/**
* Runs a script cached inside the `scripts` field under `appium`
* inside of the extension's `package.json` file. Will throw
* an error if the driver/plugin does not contain a `scripts` field
* underneath the `appium` field in its `package.json`, if the
* `scripts` field is not a plain object, or if the `scriptName` is
* not found within `scripts` object.
*
* @param {RunOptions} opts
* @return {Promise<RunOutput>}
*/
async _run({installSpec, scriptName, extraArgs = []}) {
async _run({installSpec, scriptName, extraArgs = [], bufferOutput = false}) {
if (!this.config.isInstalled(installSpec)) {
throw this._createFatalError(`The ${this.type} "${installSpec}" is not installed`);
}
@@ -699,35 +735,65 @@ class ExtensionCommand {
);
}
const runner = new SubProcess(process.execPath, [extScripts[scriptName], ...extraArgs], {
cwd: this.config.getInstallPath(installSpec),
});
if (bufferOutput) {
const runner = new SubProcess(process.execPath, [extScripts[scriptName], ...extraArgs], {
cwd: this.config.getInstallPath(installSpec),
});
const output = new RingBuffer(50);
const output = new RingBuffer(50);
runner.on('stream-line', (line) => {
output.enqueue(line);
this.log.log(line);
});
runner.on('stream-line', (line) => {
output.enqueue(line);
this.log.log(line);
});
await runner.start(0);
await runner.start(0);
try {
await runner.join();
this.log.ok(`${scriptName} successfully ran`.green);
return {output: output.getBuff()};
} catch (err) {
this.log.error(`Encountered an error when running '${scriptName}': ${err.message}`.red);
return {error: err.message, output: output.getBuff()};
}
}
try {
await runner.join();
await new B((resolve, reject) => {
this._runUnbuffered(
this.config.getInstallPath(installSpec),
extScripts[scriptName],
extraArgs
)
.on('error', (err) => {
// generally this is of the "I can't find the script" variety.
// this is a developer bug: the extension is pointing to a script that is not where the
// developer said it would be (in `appium.scripts` of the extension's `package.json`)
reject(err);
})
.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`Script "${scriptName}" exited with code ${code}`));
}
});
});
this.log.ok(`${scriptName} successfully ran`.green);
return {output: output.getBuff()};
return {};
} catch (err) {
this.log.error(`Encountered an error when running '${scriptName}': ${err.message}`.red);
return {error: err.message, output: output.getBuff()};
return {error: err.message};
}
}
}
export default ExtensionCommand;
export {ExtensionCommand};
export default ExtensionCliCommand;
export {ExtensionCliCommand as ExtensionCommand};
/**
* Options for the {@linkcode ExtensionCommand} constructor
* Options for the {@linkcode ExtensionCliCommand} constructor
* @template {ExtensionType} ExtType
* @typedef ExtensionCommandOptions
* @property {ExtensionConfig<ExtType>} config - the `DriverConfig` or `PluginConfig` instance used for this command
@@ -735,14 +801,15 @@ export {ExtensionCommand};
*/
/**
* Extra stuff about extensions; used indirectly by {@linkcode ExtensionCommand.list}.
* Extra stuff about extensions; used indirectly by {@linkcode ExtensionCliCommand.list}.
*
* @typedef ExtensionMetadata
* @typedef ExtensionListMetadata
* @property {boolean} installed - If `true`, the extension is installed
* @property {string?} updateVersion - If the extension is installed, the version it can be updated to
* @property {string?} unsafeUpdateVersion - Same as above, but a major version bump
* @property {boolean} upToDate - If the extension is installed and the latest
* @property {string?} updateError - Update check error message (if present)
* @property {string|null} updateVersion - If the extension is installed, the version it can be updated to
* @property {string|null} unsafeUpdateVersion - Same as above, but a major version bump
* @property {string} [updateError] - Update check error message (if present)
* @property {boolean} [devMode] - If Appium is run from an extension's working copy
*/
/**
@@ -782,72 +849,75 @@ export {ExtensionCommand};
*/
/**
* Possible return value for {@linkcode ExtensionCommand.list}
* @typedef {Partial<InstalledExtensionListData> & {pkgName: string, installed: false}} UninstalledExtensionListData
* Possible return value for {@linkcode ExtensionCliCommand.list}
* @template {ExtensionType} ExtType
* @typedef {Partial<ExtManifest<ExtType>> & Partial<ExtensionListMetadata>} ExtensionListData
*/
/**
* Possible return value for {@linkcode ExtensionCommand.list}
* @typedef {import('appium/types').InternalMetadata & ExtensionMetadata} InstalledExtensionListData
* @template {ExtensionType} ExtType
* @typedef {ExtManifest<ExtType> & ExtensionListMetadata} InstalledExtensionListData
*/
/**
* Return value of {@linkcode ExtensionCommand.list}.
* @typedef {Record<string,InstalledExtensionListData|UninstalledExtensionListData>} ExtensionListData
* Return value of {@linkcode ExtensionCliCommand.list}.
* @template {ExtensionType} ExtType
* @typedef {Record<string,ExtensionListData<ExtType>>} ExtensionList
*/
/**
* Options for {@linkcode ExtensionCommand._run}.
* Options for {@linkcode ExtensionCliCommand._run}.
* @typedef RunOptions
* @property {string} installSpec - name of the extension to run a script from
* @property {string} scriptName - name of the script to run
* @property {string[]} [extraArgs] - arguments to pass to the script
* @property {boolean} [bufferOutput] - if true, will buffer the output of the script and return it
*/
/**
* Return value of {@linkcode ExtensionCommand._run}
* Return value of {@linkcode ExtensionCliCommand._run}
*
* @typedef RunOutput
* @property {string} [error] - error message if script ran unsuccessfully, otherwise undefined
* @property {string[]} output - script output
* @property {string[]} [output] - script output if `bufferOutput` was `true` in {@linkcode RunOptions}
*/
/**
* Options for {@linkcode ExtensionCommand._update}.
* Options for {@linkcode ExtensionCliCommand._update}.
* @typedef ExtensionUpdateOpts
* @property {string} installSpec - the name of the extension to update
* @property {boolean} unsafe - if true, will perform unsafe updates past major revision boundaries
*/
/**
* Return value of {@linkcode ExtensionCommand._update}.
* Return value of {@linkcode ExtensionCliCommand._update}.
* @typedef ExtensionUpdateResult
* @property {Record<string,Error>} errors - map of ext names to error objects
* @property {Record<string,UpdateReport>} updates - map of ext names to {@linkcode UpdateReport}s
*/
/**
* Part of result of {@linkcode ExtensionCommand._update}.
* Part of result of {@linkcode ExtensionCliCommand._update}.
* @typedef UpdateReport
* @property {string} from - version the extension was updated from
* @property {string} to - version the extension was updated to
*/
/**
* Options for {@linkcode ExtensionCommand._uninstall}.
* Options for {@linkcode ExtensionCliCommand._uninstall}.
* @typedef UninstallOpts
* @property {string} installSpec - the name or spec of an extension to uninstall
*/
/**
* Used by {@linkcode ExtensionCommand.getPostInstallText}
* Used by {@linkcode ExtensionCliCommand.getPostInstallText}
* @typedef ExtensionArgs
* @property {string} extName - the name of an extension
* @property {object} extData - the data for an installed extension
*/
/**
* Options for {@linkcode ExtensionCommand.installViaNpm}
* Options for {@linkcode ExtensionCliCommand.installViaNpm}
* @typedef InstallViaNpmArgs
* @property {string} installSpec - the name or spec of an extension to install
* @property {string} pkgName - the NPM package name of the extension
@@ -856,7 +926,7 @@ export {ExtensionCommand};
*/
/**
* Object returned by {@linkcode ExtensionCommand.checkForExtensionUpdate}
* Object returned by {@linkcode ExtensionCliCommand.checkForExtensionUpdate}
* @typedef PossibleUpdates
* @property {string} current - current version
* @property {string?} safeUpdate - version we can safely update to if it exists, or null
@@ -864,7 +934,7 @@ export {ExtensionCommand};
*/
/**
* Options for {@linkcode ExtensionCommand._install}
* Options for {@linkcode ExtensionCliCommand._install}
* @typedef InstallOpts
* @property {string} installSpec - the name or spec of an extension to install
* @property {InstallType} installType - how to install this extension. One of the INSTALL_TYPES
@@ -880,10 +950,11 @@ export {ExtensionCommand};
* @typedef ListOptions
* @property {boolean} showInstalled - whether should show only installed extensions
* @property {boolean} showUpdates - whether should show available updates
* @property {boolean} [verbose] - whether to show additional data from the extension
*/
/**
* Opts for {@linkcode ExtensionCommand.getInstallationReceipt}
* Opts for {@linkcode ExtensionCliCommand.getInstallationReceipt}
* @template {ExtensionType} ExtType
* @typedef GetInstallationReceiptOpts
* @property {string} installPath
+5 -5
View File
@@ -1,14 +1,14 @@
/* eslint-disable no-console */
import {DRIVER_TYPE, PLUGIN_TYPE} from '../constants';
import {isExtensionCommandArgs} from '../utils';
import DriverCommand from './driver-command';
import PluginCommand from './plugin-command';
import DriverCliCommand from './driver-command';
import PluginCliCommand from './plugin-command';
import {errAndQuit, JSON_SPACES} from './utils';
export const commandClasses = Object.freeze(
/** @type {const} */ ({
[DRIVER_TYPE]: DriverCommand,
[PLUGIN_TYPE]: PluginCommand,
[DRIVER_TYPE]: DriverCliCommand,
[PLUGIN_TYPE]: PluginCliCommand,
})
);
@@ -59,7 +59,7 @@ export {runExtensionCommand};
/**
* @template {ExtensionType} ExtType
* @typedef {ExtType extends DriverType ? Class<DriverCommand> : ExtType extends PluginType ? Class<PluginCommand> : never} ExtCommand
* @typedef {ExtType extends DriverType ? Class<DriverCliCommand> : ExtType extends PluginType ? Class<PluginCliCommand> : never} ExtCommand
*/
/**
+13 -8
View File
@@ -1,13 +1,13 @@
import _ from 'lodash';
import ExtensionCommand from './extension-command';
import ExtensionCliCommand from './extension-command';
import {KNOWN_PLUGINS} from '../constants';
const REQ_PLUGIN_FIELDS = ['pluginName', 'mainClass'];
/**
* @extends {ExtensionCommand<PluginType>}
* @extends {ExtensionCliCommand<PluginType>}
*/
export default class PluginCommand extends ExtensionCommand {
export default class PluginCliCommand extends ExtensionCliCommand {
/**
*
* @param {import('./extension-command').ExtensionCommandOptions<PluginType>} opts
@@ -57,7 +57,12 @@ export default class PluginCommand extends ExtensionCommand {
* @returns {Promise<import('./extension-command').RunOutput>}
*/
async run({plugin, scriptName, extraArgs}) {
return await super._run({installSpec: plugin, scriptName, extraArgs});
return await super._run({
installSpec: plugin,
scriptName,
extraArgs,
bufferOutput: this.isJsonOutput,
});
}
/**
@@ -105,7 +110,7 @@ export default class PluginCommand extends ExtensionCommand {
*/
/**
* Options for {@linkcode PluginCommand.install}
* Options for {@linkcode PluginCliCommand.install}
* @typedef PluginInstallOpts
* @property {string} plugin - the name or spec of a plugin to install
* @property {InstallType} installType - how to install this plugin. One of the INSTALL_TYPES
@@ -117,20 +122,20 @@ export default class PluginCommand extends ExtensionCommand {
*/
/**
* Options for {@linkcode PluginCommand.uninstall}
* Options for {@linkcode PluginCliCommand.uninstall}
* @typedef PluginUninstallOpts
* @property {string} plugin - the name or spec of a plugin to uninstall
*/
/**
* Options for {@linkcode PluginCommand.update}
* Options for {@linkcode PluginCliCommand.update}
* @typedef PluginUpdateOpts
* @property {string} plugin - the name of the plugin to update
* @property {boolean} unsafe - if true, will perform unsafe updates past major revision boundaries
*/
/**
* Options for {@linkcode PluginCommand.run}.
* Options for {@linkcode PluginCliCommand.run}.
* @typedef PluginRunOptions
* @property {string} plugin - name of the plugin to run a script from
* @property {string} scriptName - name of the script to run
+3 -2
View File
@@ -10,8 +10,9 @@ import {getDefaultsForSchema, getAllArgSpecs} from './schema/schema';
const npmPackage = fs.readPackageJsonFrom(__dirname);
const APPIUM_VER = npmPackage.version;
const MIN_NODE_VERSION = npmPackage.engines.node;
const MIN_NPM_VERSION = npmPackage.engines.npm;
const ENGINES = /** @type {Record<string,string>} */ (npmPackage.engines);
const MIN_NODE_VERSION = ENGINES.node;
const MIN_NPM_VERSION = ENGINES.npm;
const GIT_META_ROOT = '.git';
const GIT_BINARY = `git${system.isWindows() ? '.exe' : ''}`;
+9 -1
View File
@@ -68,4 +68,12 @@ export const EXT_SUBCOMMAND_RUN = 'run';
/**
* Current revision of the manifest (`extensions.yaml`) schema
*/
export const CURRENT_SCHEMA_REV = 3;
export const CURRENT_SCHEMA_REV = 4;
/**
* The default number of stack frames to show in a "long" stack trace, when enabled via `--long-stacktrace`
* @remarks This value may be increased in the future.
* @privateRemarks A value like `Infinity` may provide to have deleterious effects on
* memory usage, perf, and/or log output, and higher limits may be difficult to scan.
*/
export const LONG_STACKTRACE_LIMIT = 100;
@@ -212,28 +212,29 @@ export class DriverConfig extends ExtensionConfig {
}
/**
* @template T
* @template {ExtensionType} T
* @typedef {import('appium/types').ExtMetadata<T>} ExtMetadata
*/
/**
* @template T
* @template {ExtensionType} T
* @typedef {import('appium/types').ExtManifest<T>} ExtManifest
*/
/**
* @typedef {import('@appium/types').ExtensionType} ExtensionType
* @typedef {import('appium/types').ManifestData} ManifestData
* @typedef {import('@appium/types').DriverType} DriverType
* @typedef {import('./manifest').Manifest} Manifest
*/
/**
* @template T
* @template {ExtensionType} T
* @typedef {import('appium/types').ExtRecord<T>} ExtRecord
*/
/**
* @template T
* @template {ExtensionType} T
* @typedef {import('appium/types').ExtName<T>} ExtName
*/
@@ -244,7 +245,3 @@ export class DriverConfig extends ExtensionConfig {
* @property {string} version
* @property {string} driverName
*/
/**
* @typedef {import('@appium/types').Capabilities} Capabilities
*/
@@ -1,9 +1,9 @@
import _ from 'lodash';
import {util} from '@appium/support';
import B from 'bluebird';
import _ from 'lodash';
import path from 'path';
import resolveFrom from 'resolve-from';
import {satisfies} from 'semver';
import {util} from '@appium/support';
import {commandClasses} from '../cli/extension';
import {APPIUM_VER} from '../config';
import log from '../logger';
@@ -13,17 +13,41 @@ import {
registerSchema,
} from '../schema/schema';
const INSTALL_TYPE_NPM = 'npm';
const INSTALL_TYPE_LOCAL = 'local';
const INSTALL_TYPE_GITHUB = 'github';
const INSTALL_TYPE_GIT = 'git';
/**
* "npm" install type
* Used when extension was installed by npm package name
* @remarks _All_ extensions are installed _by_ `npm`, but only this one means the package name was
* used to specify it
*/
export const INSTALL_TYPE_NPM = 'npm';
/**
* "local" install type
* Used when extension was installed from a local path
*/
export const INSTALL_TYPE_LOCAL = 'local';
/**
* "github" install type
* Used when extension was installed via GitHub URL
*/
export const INSTALL_TYPE_GITHUB = 'github';
/**
* "git" install type
* Used when extensions was installed via Git URL
*/
export const INSTALL_TYPE_GIT = 'git';
/**
* "dev" install type
* Used when automatically detected as a working copy
*/
export const INSTALL_TYPE_DEV = 'dev';
/** @type {Set<InstallType>} */
const INSTALL_TYPES = new Set([
export const INSTALL_TYPES = new Set([
INSTALL_TYPE_GIT,
INSTALL_TYPE_GITHUB,
INSTALL_TYPE_LOCAL,
INSTALL_TYPE_NPM,
INSTALL_TYPE_DEV,
]);
/**
@@ -54,7 +78,7 @@ export class ExtensionConfig {
manifest;
/**
* @type {ExtensionListData|undefined}
* @type {import('../cli/extension-command').ExtensionList<ExtType>|undefined}
*/
#listDataCache;
@@ -239,7 +263,7 @@ export class ExtensionConfig {
* This is an expensive operation, so the result is cached. Currently, there is no
* use case for invalidating the cache.
* @protected
* @returns {Promise<ExtensionListData>}
* @returns {Promise<import('../cli/extension-command').ExtensionList<ExtType>>}
*/
async getListData() {
if (this.#listDataCache) {
@@ -300,7 +324,10 @@ export class ExtensionConfig {
if (_.isString(appiumVersion) && !satisfies(APPIUM_VER, appiumVersion)) {
const listData = await this.getListData();
const extListData = /** @type {InstalledExtensionListData} */ (listData[extName]);
const extListData =
/** @type {import('../cli/extension-command').ExtensionListData<ExtType>} */ (
listData[extName]
);
if (extListData?.installed) {
const {updateVersion, upToDate} = extListData;
if (!upToDate) {
@@ -319,7 +346,10 @@ export class ExtensionConfig {
}
} else if (!_.isString(appiumVersion)) {
const listData = await this.getListData();
const extListData = /** @type {InstalledExtensionListData} */ (listData[extName]);
const extListData =
/** @type {import('../cli/extension-command').InstalledExtensionListData<ExtType>} */ (
listData[extName]
);
if (!extListData?.upToDate && extListData?.updateVersion) {
warnings.push(
createPeerWarning(
@@ -544,6 +574,7 @@ export class ExtensionConfig {
delete require.cache[reqResolved];
}
log.debug(`Requiring ${this.extensionType} at ${reqPath}`);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const MainClass = require(reqPath)[mainClass];
if (!MainClass) {
throw new ReferenceError(
@@ -619,8 +650,6 @@ export class ExtensionConfig {
}
}
export {INSTALL_TYPE_NPM, INSTALL_TYPE_GIT, INSTALL_TYPE_LOCAL, INSTALL_TYPE_GITHUB, INSTALL_TYPES};
/**
* An issue with the {@linkcode ExtManifest} for a particular extension.
*
@@ -640,8 +669,6 @@ export {INSTALL_TYPE_NPM, INSTALL_TYPE_GIT, INSTALL_TYPE_LOCAL, INSTALL_TYPE_GIT
/**
* @typedef {import('@appium/types').ExtensionType} ExtensionType
* @typedef {import('./manifest').Manifest} Manifest
* @typedef {import('../cli/extension-command').ExtensionListData} ExtensionListData
* @typedef {import('../cli/extension-command').InstalledExtensionListData} InstalledExtensionListData
* @typedef {import('appium/types').InstallType} InstallType
*/
@@ -1,4 +1,4 @@
import {DRIVER_TYPE, PLUGIN_TYPE} from '../constants';
import {CURRENT_SCHEMA_REV, DRIVER_TYPE, PLUGIN_TYPE} from '../constants';
import log from '../logger';
/**
@@ -12,6 +12,11 @@ import log from '../logger';
*/
const SCHEMA_REV_3 = 3;
/**
* Constant for v4 of the schema rev.
*/
const SCHEMA_REV_4 = 4;
/**
* Collection of functions to migrate from one version to another.
*
@@ -20,7 +25,7 @@ const SCHEMA_REV_3 = 3;
* itself will happen within {@linkcode Manifest.syncWithInstalledExtensions}; the extensions
* will be checked and the manifest file updated per the state of the filesystem.
*
* @type {{[P in keyof ManifestDataVersions]?: Migration}}
* @type { {[P in keyof ManifestDataVersions]?: Migration} }
*/
const Migrations = {
/**
@@ -32,19 +37,32 @@ const Migrations = {
* @type {Migration}
*/
[SCHEMA_REV_3]: (manifest) => {
let shouldSync = false;
/** @type {Array<ExtManifest<PluginType>|ExtManifest<DriverType>>} */
const allExtData = [
...Object.values(manifest.getExtensionData(DRIVER_TYPE)),
...Object.values(manifest.getExtensionData(PLUGIN_TYPE)),
];
for (const metadata of allExtData) {
if (!('installPath' in metadata)) {
shouldSync = true;
break;
}
return allExtData.some((metadata) => !('installPath' in metadata));
},
/**
* Updates installed extensions to use `InstallType` of `dev` if appropriate.
*
* Previously, these types of extensions (automatically discovered) would use the default `InstallType` of `npm`, so we need
* to refresh any with this install type.
*
* This should only happen once; we do not want to re-check everything with `npm` install type
* every time.
* @type {Migration}
*/
[SCHEMA_REV_4]: (manifest) => {
if (manifest.schemaRev < SCHEMA_REV_4) {
const allExtData = [
...Object.values(manifest.getExtensionData(DRIVER_TYPE)),
...Object.values(manifest.getExtensionData(PLUGIN_TYPE)),
];
return allExtData.some((metadata) => metadata.installType === 'npm');
}
return shouldSync;
return false;
},
};
@@ -61,7 +79,7 @@ const Migrations = {
* @returns {boolean} Whether the data was modified
*/
function setSchemaRev(manifest, version) {
if (manifest.schemaRev ?? 0 < version) {
if ((manifest.schemaRev ?? 0) < version) {
manifest.setSchemaRev(version);
return true;
}
@@ -78,15 +96,13 @@ function setSchemaRev(manifest, version) {
*/
export async function migrate(manifest) {
let didChange = false;
for await (const [v, migration] of Object.entries(Migrations)) {
const version = /** @type {keyof ManifestDataVersions} */ (Number(v));
for await (const migration of Object.values(Migrations)) {
didChange = (await migration(manifest)) || didChange;
didChange = setSchemaRev(manifest, version) || didChange;
}
didChange = setSchemaRev(manifest, CURRENT_SCHEMA_REV) || didChange;
if (didChange) {
// this is not _technically_ true, since we don't actually write the file here.
log.info(`Upgraded extension manifest to schema v${manifest.schemaRev}`);
log.debug(`Upgraded extension manifest to schema v${manifest.schemaRev}`);
}
return didChange;
+26 -19
View File
@@ -10,7 +10,7 @@ import path from 'path';
import YAML from 'yaml';
import {CURRENT_SCHEMA_REV, DRIVER_TYPE, PLUGIN_TYPE} from '../constants';
import log from '../logger';
import {INSTALL_TYPE_NPM} from './extension-config';
import {INSTALL_TYPE_NPM, INSTALL_TYPE_DEV} from './extension-config';
import {packageDidChange} from './package-changed';
import {migrate} from './manifest-migrations';
@@ -148,27 +148,33 @@ export class Manifest {
* Returns a new or existing {@link Manifest} instance, based on the value of `appiumHome`.
*
* Maintains one instance per value of `appiumHome`.
* @param {string} appiumHome - Path to `APPIUM_HOME`
* @returns {Manifest}
*/
static getInstance = _.memoize(function _getInstance(appiumHome) {
return new Manifest(appiumHome);
});
static getInstance = _.memoize(
/**
* @param {string} appiumHome - Path to `APPIUM_HOME`
* @returns {Manifest}
*/
function _getInstance(appiumHome) {
return new Manifest(appiumHome);
}
);
/**
* Searches `APPIUM_HOME` for installed extensions and adds them to the manifest.
* @param {boolean} hasAppiumDependency - This affects whether or not the "dev" `InstallType` is used
* @returns {Promise<boolean>} `true` if any extensions were added, `false` otherwise.
*/
async syncWithInstalledExtensions() {
async syncWithInstalledExtensions(hasAppiumDependency = false) {
// this could be parallelized, but we can't use fs.walk as an async iterator
let didChange = false;
/**
* Listener for the `match` event of a `glob` instance
* @param {string} filepath - Path to a `package.json`
* @param {boolean} [devType] - If `true`, this is an extension in "dev mode"
* @returns {Promise<void>}
*/
const onMatch = async (filepath) => {
const onMatch = async (filepath, devType = false) => {
try {
const pkg = JSON.parse(await fs.readFile(filepath, 'utf8'));
if (isExtension(pkg)) {
@@ -188,7 +194,8 @@ export class Manifest {
) {
log.info(`Discovered installed ${extType} "${name}"`);
}
const changed = this.addExtensionFromPackage(pkg, filepath);
const installType = devType && hasAppiumDependency ? INSTALL_TYPE_DEV : INSTALL_TYPE_NPM;
const changed = this.addExtensionFromPackage(pkg, filepath, installType);
didChange = didChange || changed;
}
} catch {}
@@ -199,8 +206,9 @@ export class Manifest {
* @type {Promise<void>[]}
*/
const queue = [
// look at `package.json` in `APPIUM_HOME` only
onMatch(path.join(this.#appiumHome, 'package.json')),
// look at `package.json` in `APPIUM_HOME` only.
// this causes extensions in "dev mode" to be automatically found
onMatch(path.join(this.#appiumHome, 'package.json'), true),
];
// add dependencies to the queue
@@ -252,9 +260,10 @@ export class Manifest {
* @template {ExtensionType} ExtType
* @param {ExtPackageJson<ExtType>} pkgJson
* @param {string} pkgPath
* @param {typeof INSTALL_TYPE_NPM | typeof INSTALL_TYPE_DEV} [installType]
* @returns {boolean} - `true` if this method did anything.
*/
addExtensionFromPackage(pkgJson, pkgPath) {
addExtensionFromPackage(pkgJson, pkgPath, installType = INSTALL_TYPE_NPM) {
const extensionPath = path.dirname(pkgPath);
/**
@@ -264,7 +273,7 @@ export class Manifest {
pkgName: pkgJson.name,
version: pkgJson.version,
appiumVersion: pkgJson.peerDependencies?.appium,
installType: INSTALL_TYPE_NPM,
installType,
installSpec: `${pkgJson.name}@${pkgJson.version}`,
installPath: extensionPath,
};
@@ -434,6 +443,8 @@ export class Manifest {
shouldWrite = await migrate(this);
}
const hasAppiumDependency = await env.hasAppiumDependency(this.appiumHome);
/**
* we still may want to sync with installed extensions even if we have a
* new file. right now this is limited to the following cases:
@@ -445,13 +456,9 @@ export class Manifest {
* It may also make sense to sync with the extensions in an arbitrary
* `APPIUM_HOME`, but we don't do that here.
*/
if (
shouldWrite ||
((await env.hasAppiumDependency(this.appiumHome)) &&
(await packageDidChange(this.appiumHome)))
) {
if (shouldWrite || (hasAppiumDependency && (await packageDidChange(this.appiumHome)))) {
log.debug('Discovering newly installed extensions...');
shouldWrite = (await this.syncWithInstalledExtensions()) || shouldWrite;
shouldWrite = (await this.syncWithInstalledExtensions(hasAppiumDependency)) || shouldWrite;
}
if (shouldWrite) {
+7 -4
View File
@@ -2,7 +2,6 @@
import {init as logsinkInit} from './logsink'; // this import needs to come first since it sets up global npmlog
import logger from './logger'; // logger needs to remain second
// @ts-ignore
import {routeConfiguringFunction as makeRouter, server as baseServer} from '@appium/base-driver';
import {logger as logFactory, util, env} from '@appium/support';
import {asyncify} from 'asyncbox';
@@ -23,7 +22,7 @@ import {
} from './config';
import {readConfigFile} from './config-file';
import {loadExtensions, getActivePlugins, getActiveDrivers} from './extension';
import {SERVER_SUBCOMMAND} from './constants';
import {SERVER_SUBCOMMAND, LONG_STACKTRACE_LIMIT} from './constants';
import registerNode from './grid-register';
import {getDefaultsForSchema, validate} from './schema/schema';
import {
@@ -47,7 +46,7 @@ async function preflightChecks(args, throwInsteadOfExit = false) {
checkNodeOk();
await checkNpmOk();
if (args.longStacktrace) {
require('longjohn').async_trace_limit = -1;
Error.stackTraceLimit = LONG_STACKTRACE_LIMIT;
}
if (args.showBuildInfo) {
await showBuildInfo();
@@ -245,7 +244,11 @@ async function init(args) {
}
}
const appiumDriver = new AppiumDriver(serverArgs);
const appiumDriver = new AppiumDriver(
/** @type {import('@appium/types').DriverOpts<import('./appium').AppiumDriverConstraints>} */ (
serverArgs
)
);
// set the config on the umbrella driver so it can match drivers to caps
appiumDriver.driverConfig = driverConfig;
await preflightChecks(serverArgs, throwInsteadOfExit);
+1 -1
View File
@@ -224,7 +224,7 @@ export function toParserArgs() {
}
/**
* @template T
* @template {string|number} T
* @typedef {import('ajv/dist/types').FormatValidator<T>} FormatValidator<T>
*/
+8 -10
View File
@@ -223,7 +223,8 @@ function adjustNodePath() {
// ! statements in client modules. It uses a private API though,
// ! so it could break (maybe, eventually).
// See https://gist.github.com/branneman/8048520#7-the-hack
// @ts-ignore
// @ts-ignore see above comment
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('module').Module._initPaths();
return true;
} catch (e) {
@@ -368,21 +369,18 @@ export {
*/
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @template {StringRecord|void} [Extra=void]
* @typedef {import('@appium/types').Capabilities<C, Extra>} Capabilities
* @template {Constraints} C
* @typedef {import('@appium/types').Capabilities<C>} Capabilities
*/
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @template {StringRecord|void} [Extra=void]
* @typedef {import('@appium/types').W3CCapabilities<C, Extra>} W3CCapabilities
* @template {Constraints} C
* @typedef {import('@appium/types').W3CCapabilities<C>} W3CCapabilities
*/
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @template {StringRecord|void} [Extra=void]
* @typedef {import('@appium/types').NSCapabilities<C, Extra>} NSCapabilities
* @template {Constraints} C
* @typedef {import('@appium/types').NSCapabilities<C>} NSCapabilities
*/
/**
+10 -10
View File
@@ -1,6 +1,6 @@
{
"name": "appium",
"version": "2.0.0-beta.56",
"version": "2.0.0-beta.58",
"description": "Automation for Apps.",
"keywords": [
"automation",
@@ -44,6 +44,7 @@
],
"scripts": {
"build:docs": "node docs/scripts/build-docs.js",
"build:docs:preview": "cross-env APPIUM_DOCS_PREVIEW=1 npm run build:docs",
"build:docs:assets": "node docs/scripts/copy-assets.js",
"build:docs:cli": "node docs/scripts/gen-cli-args-docs.js",
"build:docs:reference": "node docs/scripts/build-reference.js",
@@ -59,12 +60,12 @@
"test:unit": "mocha \"./test/unit/**/*.spec.js\""
},
"dependencies": {
"@appium/base-driver": "^9.3.2",
"@appium/base-plugin": "^2.2.2",
"@appium/docutils": "^0.2.2",
"@appium/schema": "^0.2.5",
"@appium/support": "^3.1.6",
"@appium/types": "^0.10.0",
"@appium/base-driver": "^9.3.4",
"@appium/base-plugin": "^2.2.4",
"@appium/docutils": "^0.3.1",
"@appium/schema": "^0.2.6",
"@appium/support": "^3.1.8",
"@appium/types": "^0.10.2",
"@sidvind/better-ajv-errors": "2.1.0",
"@types/argparse": "2.0.10",
"@types/bluebird": "3.5.38",
@@ -82,9 +83,8 @@
"cross-env": "7.0.3",
"find-up": "5.0.0",
"glob": "8.1.0",
"lilconfig": "2.0.6",
"lilconfig": "2.1.0",
"lodash": "4.17.21",
"longjohn": "0.2.12",
"npmlog": "7.0.1",
"ora": "5.4.1",
"package-changed": "2.0.0",
@@ -92,7 +92,7 @@
"semver": "7.3.8",
"source-map-support": "0.5.21",
"teen_process": "2.0.2",
"type-fest": "3.6.0",
"type-fest": "3.7.1",
"winston": "3.8.2",
"wrap-ansi": "7.0.0",
"yaml": "2.2.1"
@@ -1,5 +1,5 @@
{
"devDependencies": {
"webdriverio": "7.30.1"
"webdriverio": "7.30.2"
}
}
@@ -22,6 +22,8 @@
*/
const B = require('bluebird');
const path = require('node:path');
const {realpath} = require('node:fs/promises');
B.config({
cancellation: true,
@@ -55,11 +57,32 @@ function log(message) {
console.error(wrap(`[Appium] ${message}`));
}
/**
* This is a naive attempt at determining whether or not we are in a dev environment; in other
* words, is `postinstall` being run from within the `appium` monorepo?
*
* When we're in the monorepo, `npm_config_local_prefix` will be set to the root of the monorepo root
* dir when running this lifecycle script from an `npm install` in the monorepo root.
*
* `realpath` is necessary due to macOS omitting `/private` from paths
*/
async function isDevEnvironment() {
return (
process.env.npm_config_local_prefix &&
path.join(process.env.npm_config_local_prefix, 'packages', 'appium') ===
(await realpath(path.join(__dirname, '..')))
);
}
/**
* Setup / check environment if we should do anything here
* @returns {Promise<boolean>} `true` if Appium is built and ready to go
*/
async function init() {
if (await isDevEnvironment()) {
log('Dev environment likely; skipping automatic installation of extensions');
return false;
}
try {
({env, util, logger} = require('@appium/support'));
// @ts-ignore
@@ -63,7 +63,7 @@ describe('Plugin CLI', function () {
* @typedef {import('appium/types').ManifestData} ManifestData
* @typedef {import('@appium/types').DriverType} DriverType
* @typedef {import('@appium/types').PluginType} PluginType
* @typedef {import('appium/lib/cli/extension-command').ExtensionListData} ExtensionListData
* @typedef {import('appium/lib/cli/extension-command').ExtensionList} ExtensionListData
* @typedef {import('./e2e-helpers').CliArgs} CliArgs
* @typedef {import('appium/types').CliExtensionSubcommand} CliExtensionSubcommand
*/
+1 -1
View File
@@ -182,7 +182,7 @@ export function formatAppiumArgErrorOutput(stderr) {
/**
* @typedef {import('@appium/types').ExtensionType} ExtensionType
* @typedef {import('appium/lib/cli/extension-command').ExtensionListData} ExtensionListData
* @typedef {import('appium/lib/cli/extension-command').ExtensionList} ExtensionListData
* @typedef {import('teen_process').ExecError} ExecError
* @typedef {import('teen_process').TeenProcessExecOptions} TeenProcessExecOptions
* @typedef {import('teen_process').TeenProcessExecResult<string>} TeenProcessExecResult
@@ -99,7 +99,7 @@ describe('manifest handling', function () {
});
it('should update the manifest file to the latest schema revision', function () {
expect(manifest.schemaRev).to.equal(3);
expect(manifest.schemaRev).to.equal(CURRENT_SCHEMA_REV);
});
});
});
@@ -0,0 +1,64 @@
// @ts-check
import {DriverConfig} from '../../../lib/extension/driver-config';
import {ExtensionCommand} from '../../../lib/cli/extension-command';
import sinon from 'sinon';
import {FAKE_DRIVER_DIR} from '../../helpers';
import {Manifest} from '../../../lib/extension/manifest';
const {expect} = chai;
/**
* Relative path from actual `package.json` of `FakeDriver` for the `fake-stdin` script
*/
const FAKE_STDIN_SCRIPT = require(`${FAKE_DRIVER_DIR}/package.json`).appium.scripts['fake-stdin'];
describe('ExtensionCommand', function () {
describe('method', function () {
/** @type {ExtensionCommand} */
let ec;
/** @type {sinon.SinonSandbox} */
let sandbox;
beforeEach(function () {
sandbox = sinon.createSandbox();
const driverConfig = DriverConfig.create(sandbox.createStubInstance(Manifest));
ec = new ExtensionCommand({config: driverConfig, json: false});
});
afterEach(function () {
sandbox.restore();
});
describe('_runUnbuffered()', function () {
// this test is low value and mostly just asserts that `child_process.spawn()` works.
// the problem is that because `_run()` returns a `Promise`, a caller cannot reach the
// underlying `ChildProcess` instance.
// something like `execa` could work around this because it returns a frankenstein of a
// `Promise` + `ChildProcess`, but I didn't want to add the dep.
it('should respond to stdin', function (done) {
// we have to fake writing to STDIN because this is an automated test, after all.
const proc = ec
._runUnbuffered(FAKE_DRIVER_DIR, FAKE_STDIN_SCRIPT, [], {
stdio: ['pipe', 'inherit', 'inherit'],
})
.once('exit', (code) => {
try {
expect(code).to.equal(0);
done();
} catch (err) {
done(err);
}
});
setTimeout(() => {
// TS does not understand that `proc.stdin` is not `null`, because it is only a `Writable`
// if STDIN is piped from the parent.
const stdin = /** @type {import('node:stream').Writable} */ (proc.stdin);
stdin.write('\n');
stdin.end();
}, 200);
});
});
});
});
@@ -0,0 +1,91 @@
import {Manifest} from '../../../lib/extension/manifest';
import {migrate} from '../../../lib/extension/manifest-migrations';
import {DRIVER_TYPE} from '../../../lib/constants';
const {expect} = chai;
describe('manifest-migrations', function () {
describe('when no installPath property present in manifest', function () {
it('should trigger refresh', async function () {
const manifest = Manifest.getInstance(process.cwd());
// do not explicitly set the schema rev lower here, since that will trigger
manifest.setExtension(
DRIVER_TYPE,
'derp',
// @ts-expect-error - old manifest version
{
version: '1.0.0',
automationName: 'Derp',
mainClass: 'SomeClass',
pkgName: 'derp',
platformNames: ['dogs', 'cats'],
installSpec: 'derp',
installType: 'local',
appiumVersion: '2.0.0',
}
);
await expect(migrate(manifest)).to.eventually.be.true;
});
});
describe('when installPath property present in manifest', function () {
it('should not trigger refresh', async function () {
const manifest = Manifest.getInstance(process.cwd());
// do not explicitly set the schema rev lower here, since that will trigger
manifest.setExtension(DRIVER_TYPE, 'derp', {
version: '1.0.0',
automationName: 'Derp',
mainClass: 'SomeClass',
pkgName: 'derp',
platformNames: ['dogs', 'cats'],
installPath: '/path/to/thing',
installType: 'local',
installSpec: 'derp',
appiumVersion: '2.0.0',
});
await expect(migrate(manifest)).to.eventually.be.false;
});
});
describe('when an installType is "npm" and the rev is old', function () {
it('should trigger refresh', async function () {
const manifest = Manifest.getInstance(process.cwd());
manifest.setSchemaRev(3); // this will trigger a refresh, but there's no way to tell _why_, which may be bad. YAGNI?
manifest.setExtension(DRIVER_TYPE, 'derp', {
version: '1.0.0',
automationName: 'Derp',
mainClass: 'SomeClass',
pkgName: 'derp',
platformNames: ['dogs', 'cats'],
installType: 'npm',
installPath: '/path/to/thing',
installSpec: 'derp',
appiumVersion: '2.0.0',
});
await expect(migrate(manifest)).to.eventually.be.true;
});
});
describe('when no installType is "npm"', function () {
it('should not trigger refresh', async function () {
const manifest = Manifest.getInstance(process.cwd());
// do not explicitly set the schema rev lower here, since that will trigger
manifest.setExtension(DRIVER_TYPE, 'derp', {
version: '1.0.0',
automationName: 'Derp',
mainClass: 'SomeClass',
pkgName: 'derp',
platformNames: ['dogs', 'cats'],
installType: 'local',
installPath: '/path/to/thing',
installSpec: 'derp',
appiumVersion: '2.0.0',
});
await expect(migrate(manifest)).to.eventually.be.false;
});
});
});
@@ -40,7 +40,10 @@ describe('Manifest', function () {
let overrides;
({MockPackageChanged, MockAppiumSupport, MockGlob, overrides, sandbox} = initMocks());
MockAppiumSupport.fs.readFile.resolves(yamlFixture);
({Manifest} = rewiremock.proxy(() => require('../../../lib/extension/manifest'), overrides));
({Manifest} = rewiremock.proxy(() => require('../../../lib/extension/manifest'), {
...overrides,
'../../../lib/extension/manifest-migrations.js': {migrate: sandbox.stub().resolves()},
}));
Manifest.getInstance.cache = new Map();
});
+4 -3
View File
@@ -5,17 +5,18 @@
import * as ManifestV2 from './base';
import * as ManifestV3 from './v3';
import * as ManifestV4 from './v4';
// add `import * as ManifestV<new-version> from './v<new-version>';` above
export * from './v3';
export * from './v4';
// replace above line with `export * from './v<new-version>';`
export {ManifestV2, ManifestV3};
export {ManifestV2, ManifestV3, ManifestV4};
export interface ManifestDataVersions {
2: ManifestV2.ManifestData;
3: ManifestV3.ManifestData;
4: ManifestV4.ManifestData;
}
// append to this interface your new version of `ManifestData`
+161
View File
@@ -0,0 +1,161 @@
import {DriverType, ExtensionType, PluginType} from '@appium/types';
import {SchemaObject} from 'ajv';
import {PackageJson, SetRequired} from 'type-fest';
/**
* One of the possible extension installation stratgies
*/
export type InstallType = 'npm' | 'git' | 'local' | 'github' | 'dev';
export interface InternalMetadata {
/**
* Package name of extension
*
* `name` from its `package.json`
*/
pkgName: string;
/**
* Version of extension
*
* `version` from its `package.json`
*/
version: string;
/**
* The method in which the user installed the extension (the `source` CLI arg)
*/
installType: InstallType;
/**
* Whatever the user typed as the extension to install. May be derived from `package.json`
*/
installSpec: string;
/**
* Maximum version of Appium that this extension is compatible with.
*
* If `undefined`, we'll try anyway.
*/
appiumVersion?: string;
/**
* Path to the extension's root directory
*/
installPath: string;
}
/**
* Shape of the `appium.schema` property in an extension's `package.json` (if it exists)
*/
export type ExtSchemaMetadata = string | (SchemaObject & {[key: number]: never});
/**
* Manifest data shared by all extensions, as contained in `package.json`
*/
export interface CommonExtMetadata {
/**
* The main class of the extension.
*
* The extension must export this class by name.
*/
mainClass: string;
/**
* Lookup table of scripts to run via `appium <driver|plugin> run <script>` keyed by name.
*/
scripts?: Record<string, string>;
/**
* Schema describing configuration options (and CLI args) for the extension.
*
* Can also just be a path (relative to the extension root) to an external JSON schema file.
*/
schema?: ExtSchemaMetadata;
}
/**
* Driver-specific manifest data as stored in a driver's `package.json`
*/
export interface DriverMetadata {
/**
* Automation name of the driver
*/
automationName: string;
/**
* Platforms the driver supports
*/
platformNames: string[];
/**
* Short name of the driver (displayed in `appium list`, etc.)
*/
driverName: string;
}
/**
* Plugin-specific manifest data as stored in a plugin's `package.json`
*/
export interface PluginMetadata {
/**
* Short name of the plugin (displayed in `appium list`, etc.)
*/
pluginName: string;
}
/**
* Generic extension metadata as stored in the `appium` prop of an extension's `package.json`.
*/
export type ExtMetadata<ExtType extends ExtensionType> = (ExtType extends DriverType
? DriverMetadata
: ExtType extends PluginType
? PluginMetadata
: never) &
CommonExtMetadata;
/**
* Combination of external + internal extension data with `driverName`/`pluginName` removed (it becomes a key in an {@linkcode ExtRecord} object).
* Part of `extensions.yaml`.
*/
export type ExtManifest<ExtType extends ExtensionType> = Omit<
ExtMetadata<ExtType>,
'driverName' | 'pluginName'
> &
InternalMetadata;
/**
* Lookup of extension name to {@linkcode ExtManifest}.
* @see {ManifestData}
*/
export type ExtRecord<ExtType extends ExtensionType> = Record<string, ExtManifest<ExtType>>;
/**
* The shape of the `extensions.yaml` file
*/
export interface ManifestData {
drivers: ExtRecord<DriverType>;
plugins: ExtRecord<PluginType>;
schemaRev: number;
}
/**
* The name of an installed extension, as it appears in `extensions.yaml`
* (as a property name under `drivers` or `plugins`)
*/
export type ExtName<ExtType extends ExtensionType> = keyof ExtRecord<ExtType>;
/**
* A `package.json` containing extension metadata.
* Must have the following properties:
* - `name`: the name of the extension
* - `version`: the version of the extension
* - `appium`: the metadata for the extension
* - `peerDependencies.appium`: the maximum compatible version of Appium
*/
export type ExtPackageJson<ExtType extends ExtensionType> = SetRequired<
PackageJson,
'name' | 'version'
> & {
appium: ExtMetadata<ExtType>;
peerDependencies: {appium: string; [key: string]: string};
};
/**
* A transient format between installation and insertion of extension metadata into the manifest.
*/
export type ExtInstallReceipt<ExtType extends ExtensionType> = ExtMetadata<ExtType> &
InternalMetadata;
+36
View File
@@ -3,6 +3,42 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [9.3.4](https://github.com/appium/appium/compare/@appium/base-driver@9.3.3...@appium/base-driver@9.3.4) (2023-03-28)
### Bug Fixes
* **appium,types,base-driver,fake-driver,driver-test-support:** normalize constraint defaults ([3c9fa7b](https://github.com/appium/appium/commit/3c9fa7ba73b639e610e1f3d41d239a9402845b4c))
* backwards-compatible fixes for TS v5.x ([4974403](https://github.com/appium/appium/commit/49744036619ecc239e0e6255a13d38cafd709920))
* **base-driver,base-plugin,types:** update PluginCommand and DriverCommand types ([0dcd5fa](https://github.com/appium/appium/commit/0dcd5fa371af523c6527e55de4cff6cd472fde22))
* **base-driver,types:** fix websocket-related types on AppiumServer ([34891f5](https://github.com/appium/appium/commit/34891f56572f18dd740558b2348d8818680dc709))
* **base-driver:** fix timeout mixin to use proper context types ([51a8f2f](https://github.com/appium/appium/commit/51a8f2fc347f0b4e222ca2e8dc92fa4bdf44d1e3))
* **base-driver:** misc type fixes ([d303527](https://github.com/appium/appium/commit/d303527c3da4f657a28b97a2d82eb1a709c6b9bc))
* **basedriver:** convert main driver implementation to typescript ([deb631b](https://github.com/appium/appium/commit/deb631b4562a0f99e4061c89a7ad21b0621f8a47)), closes [#18379](https://github.com/appium/appium/issues/18379) [#18379](https://github.com/appium/appium/issues/18379)
* **types:** update dependency type-fest to v3.7.0 ([6912fa1](https://github.com/appium/appium/commit/6912fa14f2a7d338f17e1bed060e959de7aba1d6))
* **types:** update dependency type-fest to v3.7.1 ([bc860c7](https://github.com/appium/appium/commit/bc860c733a73760f0c42cbfb384e04d50c376d5e))
## [9.3.3](https://github.com/appium/appium/compare/@appium/base-driver@9.3.2...@appium/base-driver@9.3.3) (2023-03-08)
### Bug Fixes
* **base-driver:** remove needless static prop breaking the build ([1b70551](https://github.com/appium/appium/commit/1b70551055444cad97144e539da7be872b9f70f8))
* **base-driver:** use new mixin strategy ([be86627](https://github.com/appium/appium/commit/be8662759586bb3c24c7635b60ed8c574f5e2fd4))
* **images-plugin:** update dependency lru-cache to v7.17.2 ([d1d5ece](https://github.com/appium/appium/commit/d1d5ecef87e70afea6d9d59f69cae465460e930b))
* **images-plugin:** update dependency lru-cache to v7.18.1 ([ed1d3aa](https://github.com/appium/appium/commit/ed1d3aae61539bc136b3f266911331387397b88a))
* **images-plugin:** update dependency lru-cache to v7.18.2 ([48c3311](https://github.com/appium/appium/commit/48c331157f74b238a3fc8dc92775d0af3f9f3134))
* **images-plugin:** update dependency lru-cache to v7.18.3 ([01bff49](https://github.com/appium/appium/commit/01bff49297ca5a1c92259f1f8f11f5944ef15e4d))
* **types:** update dependency type-fest to v3.6.1 ([471a4b5](https://github.com/appium/appium/commit/471a4b57e622ff077d59f577a78341268700c48d))
## [9.3.2](https://github.com/appium/appium/compare/@appium/base-driver@9.3.1...@appium/base-driver@9.3.2) (2023-02-24)
@@ -11,19 +11,24 @@ const PREFIXED_APPIUM_OPTS_CAP = `${APPIUM_VENDOR_PREFIX}options`;
/**
* Takes primary caps object and merges it into a secondary caps object.
* @template {Constraints} [T={}]
* @template {Constraints} [U={}]
* @param {Capabilities<T>} [primary]
* @param {Capabilities<U>} [secondary]
* @returns {Merge<Capabilities<T>, Capabilities<U>>}
* @template {Constraints} T
* @template {Constraints} U
* @template {Capabilities<T>} Primary
* @template {Capabilities<U>} Secondary
* @param {Primary} [primary]
* @param {Secondary} [secondary]
* @returns {MergeExclusive<Primary, Secondary>}
* @see https://www.w3.org/TR/webdriver/#dfn-merging-capabilities)
*/
function mergeCaps(primary = {}, secondary = {}) {
let result = /** @type {Merge<Capabilities<T>, Capabilities<U>>} */ ({
function mergeCaps(
primary = /** @type {Primary} */ ({}),
secondary = /** @type {Secondary} */ ({})
) {
let result = /** @type {MergeExclusive<Primary, Secondary>} */ ({
...primary,
});
for (let [name, value] of /** @type {[keyof typeof secondary, any]} */ (_.toPairs(secondary))) {
for (let [name, value] of Object.entries(secondary)) {
// Overwriting is not allowed. Primary and secondary must have different properties (w3c rule 4.4)
if (!_.isUndefined(primary[name])) {
throw new errors.InvalidArgumentError(
@@ -38,9 +43,9 @@ function mergeCaps(primary = {}, secondary = {}) {
return result;
}
// Validates caps against a set of constraints
/**
* @template {Constraints} [C={}]
* Validates caps against a set of constraints
* @template {Constraints} C
* @param {Capabilities<C>} caps
* @param {C} [constraints]
* @param {ValidateCapsOpts} [opts]
@@ -121,11 +126,11 @@ function isStandardCap(cap) {
/**
* If the 'appium:' prefix was provided and it's a valid capability, strip out the prefix
* @template {Constraints} [C={}]
* @param {import('@appium/types').NSCapabilities<C>} caps
* @template {Constraints} C
* @param {NSCapabilities<C>} caps
* @see https://www.w3.org/TR/webdriver/#dfn-extension-capabilities
* @internal
* @returns {import('@appium/types').Capabilities<C>}
* @returns {Capabilities<C>}
*/
function stripAppiumPrefixes(caps) {
// split into prefixed and non-prefixed.
@@ -135,14 +140,12 @@ function stripAppiumPrefixes(caps) {
);
// initialize this with the k/v pairs of the non-prefixed caps
let strippedCaps = /** @type {import('@appium/types').Capabilities<C>} */ (
_.pick(caps, nonPrefixedCaps)
);
let strippedCaps = /** @type {Capabilities<C>} */ (_.pick(caps, nonPrefixedCaps));
const badPrefixedCaps = [];
// Strip out the 'appium:' prefix
for (let prefixedCap of prefixedCaps) {
const strippedCapName = /** @type {StringKeyOf<import('@appium/types').Capabilities<C>>} */ (
const strippedCapName = /** @type {StringKeyOf<Capabilities<C>>} */ (
prefixedCap.substring(APPIUM_VENDOR_PREFIX.length)
);
@@ -175,8 +178,8 @@ function stripAppiumPrefixes(caps) {
/**
* Get an array of all the unprefixed caps that are being used in 'alwaysMatch' and all of the 'firstMatch' object
* @template {Constraints} [C={}]
* @param {import('@appium/types').W3CCapabilities<C>} caps A capabilities object
* @template {Constraints} C
* @param {W3CCapabilities<C>} caps A capabilities object
*/
function findNonPrefixedCaps({alwaysMatch = {}, firstMatch = []}) {
return _.chain([alwaysMatch, ...firstMatch])
@@ -191,13 +194,25 @@ function findNonPrefixedCaps({alwaysMatch = {}, firstMatch = []}) {
.value();
}
/**
* Returned by {@linkcode parseCaps}
* @template {Constraints} C
* @typedef ParsedCaps
* @property {NSCapabilities<C>[]} allFirstMatchCaps
* @property {Capabilities<C>[]} validatedFirstMatchCaps
* @property {NSCapabilities<C>} requiredCaps
* @property {Capabilities<C>|null} matchedCaps
* @property {string[]} validationErrors
*/
/**
* Parse capabilities
* @template {Constraints} [C={}]
* @param {import('@appium/types').W3CCapabilities<C>} caps
* @template {Constraints} C
* @param {W3CCapabilities<C>} caps
* @param {C} [constraints]
* @param {boolean} [shouldValidateCaps]
* @see https://www.w3.org/TR/webdriver/#processing-capabilities
* @returns {ParsedCaps<C>}
*/
function parseCaps(caps, constraints = /** @type {C} */ ({}), shouldValidateCaps = true) {
// If capabilities request is not an object, return error (#1.1)
@@ -210,8 +225,8 @@ function parseCaps(caps, constraints = /** @type {C} */ ({}), shouldValidateCaps
// Let 'requiredCaps' be property named 'alwaysMatch' from capabilities request (#2)
// and 'allFirstMatchCaps' be property named 'firstMatch' from capabilities request (#3)
let {
alwaysMatch: requiredCaps = {}, // If 'requiredCaps' is undefined, set it to an empty JSON object (#2.1)
firstMatch: allFirstMatchCaps = [{}], // If 'firstMatch' is undefined set it to a singleton list with one empty object (#3.1)
alwaysMatch: requiredCaps = /** @type {NSCapabilities<C>} */ ({}), // If 'requiredCaps' is undefined, set it to an empty JSON object (#2.1)
firstMatch: allFirstMatchCaps = /** @type {NSCapabilities<C>[]} */ ([{}]), // If 'firstMatch' is undefined set it to a singleton list with one empty object (#3.1)
} = caps;
// Reject 'firstMatch' argument if it's not an array (#3.2)
@@ -241,6 +256,7 @@ function parseCaps(caps, constraints = /** @type {C} */ ({}), shouldValidateCaps
// Strip out the 'appium:' prefix from all
let strippedRequiredCaps = stripAppiumPrefixes(requiredCaps);
/** @type {Capabilities<C>[]} */
let strippedAllFirstMatchCaps = allFirstMatchCaps.map(stripAppiumPrefixes);
// Validate the requiredCaps. But don't validate 'presence' because if that constraint fails on 'alwaysMatch' it could still pass on one of the 'firstMatch' keys
@@ -259,24 +275,23 @@ function parseCaps(caps, constraints = /** @type {C} */ ({}), shouldValidateCaps
/** @type {string[]} */
let validationErrors = [];
let validatedFirstMatchCaps = _.compact(
strippedAllFirstMatchCaps.map(
/**
* @param {import('@appium/types').Capabilities<C>} firstMatchCaps
*/
(firstMatchCaps) => {
try {
// Validate firstMatch caps
return shouldValidateCaps
? validateCaps(firstMatchCaps, filteredConstraints)
: firstMatchCaps;
} catch (e) {
validationErrors.push(e.message);
}
strippedAllFirstMatchCaps.map((firstMatchCaps) => {
try {
// Validate firstMatch caps
return shouldValidateCaps
? validateCaps(firstMatchCaps, filteredConstraints)
: firstMatchCaps;
} catch (e) {
validationErrors.push(e.message);
}
)
})
);
// Try to merge requiredCaps with first match capabilities, break once it finds its first match (see spec #6)
/**
* Try to merge requiredCaps with first match capabilities, break once it finds its first match
* (see spec #6)
* @type {ParsedCaps<C>['matchedCaps']}
*/
let matchedCaps = null;
for (let firstMatchCaps of validatedFirstMatchCaps) {
try {
@@ -300,13 +315,14 @@ function parseCaps(caps, constraints = /** @type {C} */ ({}), shouldValidateCaps
};
}
// Calls parseCaps and just returns the matchedCaps variable
/**
* Calls parseCaps and just returns the matchedCaps variable
* @template {Constraints} C
* @param {import('@appium/types').W3CCapabilities<C>} w3cCaps
* @template {W3CCapabilities<C>} W3CCaps
* @param {W3CCaps} w3cCaps
* @param {C} [constraints]
* @param {boolean} [shouldValidateCaps]
* @returns {import('@appium/types').Capabilities<C>}
* @returns {Capabilities<C>}
*/
function processCapabilities(
w3cCaps,
@@ -400,8 +416,8 @@ function promoteAppiumOptionsForObject(obj) {
* capability and promoted it to the top level.
*
* @template {Constraints} C
* @param {import('@appium/types').W3CCapabilities<C>} originalCaps
* @return {import('@appium/types').W3CCapabilities<C>} the capabilities with 'options' promoted if necessary
* @param {W3CCapabilities<C>} originalCaps
* @return {W3CCapabilities<C>} the capabilities with 'options' promoted if necessary
*/
function promoteAppiumOptions(originalCaps) {
const result = {};
@@ -451,28 +467,26 @@ export {
*/
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @template {StringRecord|void} [Extra=void]
* @typedef {import('@appium/types').NSCapabilities<C, Extra>} NSCapabilities
* @template {Constraints} C
* @typedef {import('@appium/types').NSCapabilities<C>} NSCapabilities
*/
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @template {StringRecord|void} [Extra=void]
* @typedef {import('@appium/types').Capabilities<C, Extra>} Capabilities
* @template {Constraints} C
* @typedef {import('@appium/types').Capabilities<C>} Capabilities
*/
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @template {StringRecord|void} [Extra=void]
* @typedef {import('@appium/types').W3CCapabilities<C, Extra>} W3CCapabilities
* @template {Constraints} C
* @typedef {import('@appium/types').W3CCapabilities<C>} W3CCapabilities
*/
/**
* @template T,U
* @typedef {import('type-fest').Merge<T,U>} Merge
*/
/**
* @template T
* @typedef {import('type-fest').StringKeyOf<T>} StringKeyOf
*/
/**
* @template T,U
* @typedef {import('type-fest').MergeExclusive<T, U>} MergeExclusive<T,U>
*/
@@ -1,63 +0,0 @@
/* eslint-disable require-await */
// @ts-check
import _ from 'lodash';
/**
* @template {Constraints} C
* @param {import('./timeout').TimeoutBase<C>} Base
* @returns {EventBase<C>}
*/
export function EventMixin(Base) {
/**
* @implements {IEventCommands}
*/
class EventCommands extends Base {
/**
* Log a user-defined event in the event log.
*
* @param {string} vendor - a vendor prefix for the user, to ensure namespace
* separation
* @param {string} event - the event name
*/
async logCustomEvent(vendor, event) {
this.logEvent(`${vendor}:${event}`);
}
/**
* Get the event log
* @param {string|string[]} [type] - the event type to filter with.
* It returns all events if the type is not provided or empty string/array.
* @returns {Promise<import('@appium/types').EventHistory|Record<string,number>>} - the event history log object
*/
async getLogEvents(type) {
if (_.isEmpty(type)) {
return this.eventHistory;
}
const typeList = _.castArray(type);
return _.reduce(
this.eventHistory,
(acc, eventTimes, eventType) => {
if (typeList.includes(eventType)) {
acc[eventType] = eventTimes;
}
return acc;
},
{}
);
}
}
return EventCommands;
}
/**
* @typedef {import('@appium/types').Constraints} Constraints
* @typedef {import('@appium/types').IEventCommands} IEventCommands
*/
/**
* @template {Constraints} C
* @typedef {import('../driver').BaseDriverBase<C, import('@appium/types').ITimeoutCommands & IEventCommands>} EventBase
*/
@@ -0,0 +1,49 @@
import {Constraints, IEventCommands} from '@appium/types';
import _ from 'lodash';
import {BaseDriver} from '../driver';
import {mixin} from './mixin';
declare module '../driver' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface BaseDriver<C extends Constraints> extends IEventCommands {}
}
const EventCommands: IEventCommands = {
/**
* Log a user-defined event in the event log.
*
* @param vendor - a vendor prefix for the user, to ensure namespace
* separation
* @param event - the event name
*/
async logCustomEvent<C extends Constraints>(this: BaseDriver<C>, vendor: string, event: string) {
this.logEvent(`${vendor}:${event}`);
},
/**
* Get the event log
* @param type - the event type to filter with.
* It returns all events if the type is not provided or empty string/array.
* @returns the event history log object
*/
async getLogEvents<C extends Constraints>(this: BaseDriver<C>, type: string | string[]) {
if (_.isEmpty(type)) {
return this.eventHistory;
}
const typeList = _.castArray(type);
return _.reduce(
this.eventHistory,
(acc, eventTimes, eventType) => {
if (typeList.includes(eventType)) {
acc[eventType] = eventTimes;
}
return acc;
},
{}
);
},
};
mixin(EventCommands);
@@ -1,45 +0,0 @@
import _ from 'lodash';
import {errors, validateExecuteMethodParams} from '../../protocol';
/**
* @template {Constraints} C
* @param {import('./session').SessionBase<C>} Base
* @returns {ExecuteBase<C>}
*/
export function ExecuteMixin(Base) {
/**
* @implements {IExecuteCommands}
*/
class ExecuteCommands extends Base {
/**
* @param {string} script
* @param {[Record<string, any>]|[]} protoArgs
*/
async executeMethod(script, protoArgs) {
const Driver = /** @type {DriverClass} */ (this.constructor);
const commandMetadata = {...Driver.executeMethodMap?.[script]};
if (!commandMetadata.command) {
const availableScripts = _.keys(Driver.executeMethodMap);
throw new errors.UnsupportedOperationError(
`Unsupported execute method '${script}'. Available methods ` +
`are: ${availableScripts.join(', ')}`
);
}
const args = validateExecuteMethodParams(protoArgs, commandMetadata.params);
return await this[commandMetadata.command](...args);
}
}
return ExecuteCommands;
}
/**
* @typedef {import('@appium/types').IExecuteCommands} IExecuteCommands
* @typedef {import('@appium/types').Driver} Driver
* @typedef {import('@appium/types').DriverClass} DriverClass
* @typedef {import('@appium/types').Constraints} Constraints
*/
/**
* @template {Constraints} C
* @typedef {import('../driver').BaseDriverBase<C, import('@appium/types').ITimeoutCommands & import('@appium/types').IEventCommands & import('@appium/types').IFindCommands & import('@appium/types').ILogCommands<C> & import('@appium/types').ISettingsCommands & import('@appium/types').ISessionCommands & IExecuteCommands>} ExecuteBase
*/
@@ -0,0 +1,40 @@
import _ from 'lodash';
import {errors, validateExecuteMethodParams} from '../../protocol';
import {
Constraints,
Driver,
DriverClass,
DriverCommand,
IExecuteCommands,
StringRecord,
} from '@appium/types';
import {mixin} from './mixin';
import {BaseDriver} from '../driver';
declare module '../driver' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface BaseDriver<C extends Constraints> extends IExecuteCommands {}
}
const ExecuteCommands: IExecuteCommands = {
async executeMethod<C extends Constraints>(
this: BaseDriver<C>,
script: string,
protoArgs: readonly [StringRecord<unknown>] | readonly unknown[]
) {
const Driver = this.constructor as DriverClass<Driver<C>>;
const commandMetadata = {...Driver.executeMethodMap?.[script]};
if (!commandMetadata.command) {
const availableScripts = _.keys(Driver.executeMethodMap);
throw new errors.UnsupportedOperationError(
`Unsupported execute method '${script}'. Available methods ` +
`are: ${availableScripts.join(', ')}`
);
}
const args = validateExecuteMethodParams(protoArgs, commandMetadata.params);
const command = this[commandMetadata.command] as DriverCommand;
return await command.call(this, ...args);
},
};
mixin(ExecuteCommands);
@@ -1,108 +0,0 @@
/* eslint-disable no-unused-vars */
/* eslint-disable require-await */
// @ts-check
import {errors} from '../../protocol';
/**
* @template {Constraints} C
* @param {import('./event').EventBase<C>} Base
* @returns {FindBase<C>}
*/
export function FindMixin(Base) {
/**
* @implements {IFindCommands}
*/
class FindCommands extends Base {
/**
*
* @returns {Promise<Element>}
*/
async findElement(strategy, selector) {
return await this.findElOrElsWithProcessing(strategy, selector, false);
}
/**
*
* @returns {Promise<Element[]>}
*/
async findElements(strategy, selector) {
return await this.findElOrElsWithProcessing(strategy, selector, true);
}
/**
*
* @returns {Promise<Element>}
*/
async findElementFromElement(strategy, selector, elementId) {
return await this.findElOrElsWithProcessing(strategy, selector, false, elementId);
}
/**
*
* @returns {Promise<Element[]>}
*/
async findElementsFromElement(strategy, selector, elementId) {
return await this.findElOrElsWithProcessing(strategy, selector, true, elementId);
}
/**
* Returns an object which adheres to the way the JSON Wire Protocol represents elements:
*
* Override this for your own driver!
* @template {boolean} Mult
* @template [Ctx=any]
* @param {string} strategy
* @param {string} selector
* @param {Mult} mult
* @param {Ctx} [context]
* @returns {Promise<Mult extends true ? Element[] : Element>}
*/
async findElOrEls(strategy, selector, mult, context) {
throw new errors.NotImplementedError('Not implemented yet for find.');
}
/**
* @returns {Promise<string>}
*/
async getPageSource() {
throw new errors.NotImplementedError('Not implemented yet for find.');
}
/**
* @template {boolean} Mult
* @template [Ctx=any]
* @param {string} strategy
* @param {string} selector
* @param {Mult} mult
* @param {Ctx} [context]
* @returns {Promise<Mult extends true ? Element[] : Element>}
*/
async findElOrElsWithProcessing(strategy, selector, mult, context) {
this.validateLocatorStrategy(strategy);
try {
return await this.findElOrEls(strategy, selector, mult, context);
} catch (err) {
if (this.opts.printPageSourceOnFindFailure) {
const src = await this.getPageSource();
this.log.debug(`Error finding element${mult ? 's' : ''}: ${err.message}`);
this.log.debug(`Page source requested through 'printPageSourceOnFindFailure':`);
this.log.debug(src);
}
// still want the error to occur
throw err;
}
}
}
return FindCommands;
}
/**
* @typedef {import('@appium/types').Element} Element
* @typedef {import('@appium/types').Constraints} Constraints
* @typedef {import('@appium/types').IFindCommands} IFindCommands
* @typedef {import('@appium/types').ITimeoutCommands} ITimeoutCommands
* @typedef {import('@appium/types').IEventCommands} IEventCommands
*/
/**
* @template {Constraints} C
* @typedef {import('../driver').BaseDriverBase<C, ITimeoutCommands & IEventCommands & IFindCommands>} FindBase
*/
@@ -0,0 +1,80 @@
import {Constraints, IFindCommands} from '@appium/types';
import {errors} from '../../protocol';
import {BaseDriver} from '../driver';
import {mixin} from './mixin';
declare module '../driver' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface BaseDriver<C extends Constraints> extends IFindCommands {}
}
const FindCommands: IFindCommands = {
async findElement<C extends Constraints>(this: BaseDriver<C>, strategy, selector) {
return await this.findElOrElsWithProcessing(strategy, selector, false);
},
async findElements<C extends Constraints>(this: BaseDriver<C>, strategy, selector) {
return await this.findElOrElsWithProcessing(strategy, selector, true);
},
async findElementFromElement<C extends Constraints>(
this: BaseDriver<C>,
strategy: string,
selector: string,
elementId: string
) {
return await this.findElOrElsWithProcessing(strategy, selector, false, elementId);
},
async findElementsFromElement<C extends Constraints>(
this: BaseDriver<C>,
strategy: string,
selector: string,
elementId: string
) {
return await this.findElOrElsWithProcessing(strategy, selector, true, elementId);
},
/**
* Returns an object which adheres to the way the JSON Wire Protocol represents elements:
*
* Override this for your own driver!
*/
async findElOrEls<C extends Constraints, Mult extends boolean, Ctx = any>(
this: BaseDriver<C>,
strategy: string,
selector: string,
mult: Mult,
context: Ctx
) {
throw new errors.NotImplementedError('Not implemented yet for find.');
},
async getPageSource<C extends Constraints>(this: BaseDriver<C>) {
throw new errors.NotImplementedError('Not implemented yet for find.');
},
async findElOrElsWithProcessing<C extends Constraints, Mult extends boolean, Ctx = any>(
this: BaseDriver<C>,
strategy: string,
selector: string,
mult: Mult,
context?: Ctx
) {
this.validateLocatorStrategy(strategy);
try {
return await this.findElOrEls(strategy, selector, mult, context);
} catch (err) {
if (this.opts.printPageSourceOnFindFailure) {
const src = await this.getPageSource();
this.log.debug(`Error finding element${mult ? 's' : ''}: ${err.message}`);
this.log.debug(`Page source requested through 'printPageSourceOnFindFailure':`);
this.log.debug(src);
}
// still want the error to occur
throw err;
}
},
};
mixin(FindCommands);
@@ -1,35 +0,0 @@
// @ts-check
import _ from 'lodash';
import {EventMixin} from './event';
import {FindMixin} from './find';
import {LogMixin} from './log';
import {SessionMixin} from './session';
import {SettingsMixin} from './settings';
import {TimeoutMixin} from './timeout';
import {ExecuteMixin} from './execute';
/**
* Applies all the mixins to the `BaseDriverBase` class; returns a `BaseDriver` class definition.
* Each mixin is applied in the order it is listed here, and each type is a union with the previous.
*
* @template {Constraints} C
* @param {BaseDriverBase<C>} Base
*/
export const createBaseDriverClass = _.flow(
TimeoutMixin,
EventMixin,
FindMixin,
LogMixin,
SettingsMixin,
SessionMixin,
ExecuteMixin
);
/**
* @template {Constraints} C
* @typedef {import('../driver').BaseDriverBase<C>} BaseDriverBase
*/
/**
* @typedef {import('@appium/types').Constraints} Constraints
*/
@@ -0,0 +1,7 @@
import './event';
import './find';
import './log';
import './session';
import './settings';
import './timeout';
import './execute';
@@ -1,64 +0,0 @@
/* eslint-disable require-await */
// @ts-check
import _ from 'lodash';
/**
* @template {Constraints} C
* @param {import('./find').FindBase<C>} Base
* @returns {LogBase<C>}
*/
export function LogMixin(Base) {
/**
* @implements {ILogCommands<C>}
*/
class LogCommands extends Base {
/** @type {Readonly<import('@appium/types').LogDefRecord<C>>} */
supportedLogTypes;
constructor(...args) {
super(...args);
this.supportedLogTypes ??= {};
}
async getLogTypes() {
this.log.debug('Retrieving supported log types');
return Object.keys(this.supportedLogTypes);
}
/**
* @this {import('@appium/types').Driver<C>}
* @param {keyof typeof this.supportedLogTypes} logType
* @returns {Promise<import('type-fest').AsyncReturnType<typeof this.supportedLogTypes[keyof typeof this.supportedLogTypes]['getter']>>}
*/
async getLog(logType) {
this.log.debug(`Retrieving '${String(logType)}' logs`);
if (!(logType in this.supportedLogTypes)) {
const logsTypesWithDescriptions = _.mapValues(this.supportedLogTypes, 'description');
throw new Error(
`Unsupported log type '${String(logType)}'. ` +
`Supported types: ${JSON.stringify(logsTypesWithDescriptions)}`
);
}
return await this.supportedLogTypes[logType].getter(this);
}
}
return LogCommands;
}
/**
* @typedef {import('@appium/types').Constraints} Constraints
* @typedef {import('@appium/types').StringRecord} StringRecord
*/
/**
* @template {Constraints} C
* @typedef {import('@appium/types').ILogCommands<C>} ILogCommands
*/
/**
* @template {Constraints} C
* @typedef {import('../driver').BaseDriverBase<C, import('@appium/types').ITimeoutCommands & import('@appium/types').IEventCommands & import('@appium/types').IFindCommands & ILogCommands<C>>} LogBase
*/
@@ -0,0 +1,34 @@
import {Constraints, Driver, ILogCommands, LogDefRecord} from '@appium/types';
import _ from 'lodash';
import {BaseDriver} from '../driver';
import {mixin} from './mixin';
declare module '../driver' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface BaseDriver<C extends Constraints> extends ILogCommands {}
}
const LogCommands: ILogCommands = {
supportedLogTypes: <LogDefRecord>{},
async getLogTypes<C extends Constraints>(this: BaseDriver<C>) {
this.log.debug('Retrieving supported log types');
return Object.keys(this.supportedLogTypes);
},
async getLog<C extends Constraints>(this: Driver<C>, logType: string) {
this.log.debug(`Retrieving '${String(logType)}' logs`);
if (!(logType in this.supportedLogTypes)) {
const logsTypesWithDescriptions = _.mapValues(this.supportedLogTypes, 'description');
throw new Error(
`Unsupported log type '${String(logType)}'. ` +
`Supported types: ${JSON.stringify(logsTypesWithDescriptions)}`
);
}
return await this.supportedLogTypes[logType].getter(this);
},
};
mixin(LogCommands);
@@ -0,0 +1,15 @@
import {Constraints} from '@appium/types';
import {BaseDriver} from '../driver';
/**
* This function assigns a mixin `T` to the `BaseDriver` class' prototype.
* While each mixin has its own interface which is (in isolation) unrelated to `BaseDriver`, the constraint
* on this generic type `T` is that it must be a partial of `BaseDriver`'s interface. This enforces
* that it does not conflict with the existing interface of `BaseDriver`. In that way, you can
* think of it as a type guard.
* @param mixin Mixin implementation
*/
export function mixin<C extends Constraints, T extends Partial<BaseDriver<C>>>(mixin: T): void {
// eslint-disable-next-line no-restricted-syntax
Object.assign(BaseDriver.prototype, mixin);
}
@@ -1,57 +0,0 @@
/* eslint-disable no-unused-vars */
/* eslint-disable require-await */
// @ts-check
import _ from 'lodash';
/**
* @template {Constraints} C
* @param {import('./settings').SettingsBase<C>} Base
* @returns {SessionBase<C>}
*/
export function SessionMixin(Base) {
/**
* @implements {ISessionCommands}
*/
class SessionCommands extends Base {
/**
* @returns {Promise<MultiSessionData[]>}
*/
async getSessions() {
let ret = [];
if (this.sessionId) {
ret.push({
id: this.sessionId,
capabilities: this.caps,
});
}
return ret;
}
/**
* Returns capabilities for the session and event history (if applicable)
* @returns {Promise<SingularSessionData>}
*/
async getSession() {
if (this.caps.eventTimings) {
return {...this.caps, events: this.eventHistory};
}
return this.caps;
}
}
return SessionCommands;
}
/**
* @typedef {import('@appium/types').ISessionCommands} ISessionCommands
* @typedef {import('@appium/types').SingularSessionData} SingularSessionData
* @typedef {import('@appium/types').MultiSessionData} MultiSessionData
* @typedef {import('@appium/types').Constraints} Constraints
*/
/**
* @template {Constraints} C
* @typedef {import('../driver').BaseDriverBase<C, import('@appium/types').ITimeoutCommands & import('@appium/types').IEventCommands & import('@appium/types').IFindCommands & import('@appium/types').ILogCommands<C> & import('@appium/types').ISettingsCommands & ISessionCommands>} SessionBase
*/
@@ -0,0 +1,36 @@
import {Constraints, ISessionCommands, MultiSessionData, SingularSessionData} from '@appium/types';
import {BaseDriver} from '../driver';
import {mixin} from './mixin';
declare module '../driver' {
interface BaseDriver<
// eslint-disable-next-line @typescript-eslint/no-unused-vars
C extends Constraints
> extends ISessionCommands {}
}
const SessionCommands: ISessionCommands = {
async getSessions<C extends Constraints>(this: BaseDriver<C>) {
const ret: MultiSessionData<C>[] = [];
if (this.sessionId) {
ret.push({
id: this.sessionId,
capabilities: this.caps,
});
}
return ret;
},
/**
* Returns capabilities for the session and event history (if applicable)
*/
async getSession<C extends Constraints>(this: BaseDriver<C>) {
return <SingularSessionData<C>>(
(this.caps.eventTimings ? {...this.caps, events: this.eventHistory} : this.caps)
);
},
};
mixin(SessionCommands);
@@ -1,38 +0,0 @@
// @ts-check
/**
* @template {Constraints} C
* @param {import('./log').LogBase<C>} Base
* @returns {SettingsBase<C>}
*/
export function SettingsMixin(Base) {
/**
* @implements {ISettingsCommands}
*/
class SettingsCommands extends Base {
async updateSettings(newSettings) {
if (!this.settings) {
this.log.errorAndThrow('Cannot update settings; settings object not found');
}
return await this.settings.update(newSettings);
}
async getSettings() {
if (!this.settings) {
this.log.errorAndThrow('Cannot get settings; settings object not found');
}
return await this.settings.getSettings();
}
}
return SettingsCommands;
}
/**
* @typedef {import('@appium/types').Constraints} Constraints
* @typedef {import('@appium/types').ISettingsCommands} ISettingsCommands
*/
/**
* @template {Constraints} C
* @typedef {import('../driver').BaseDriverBase<C, import('@appium/types').ITimeoutCommands & import('@appium/types').IEventCommands & import('@appium/types').IFindCommands & import('@appium/types').ILogCommands<C> & ISettingsCommands>} SettingsBase
*/
@@ -0,0 +1,26 @@
import {BaseDriver} from '../driver';
import {Constraints, ISettingsCommands, StringRecord} from '@appium/types';
import {mixin} from './mixin';
declare module '../driver' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface BaseDriver<C extends Constraints> extends ISettingsCommands {}
}
const SettingsCommands: ISettingsCommands = {
async updateSettings<C extends Constraints>(this: BaseDriver<C>, newSettings: StringRecord) {
if (!this.settings) {
this.log.errorAndThrow('Cannot update settings; settings object not found');
}
return await this.settings.update(newSettings);
},
async getSettings<C extends Constraints>(this: BaseDriver<C>) {
if (!this.settings) {
this.log.errorAndThrow('Cannot get settings; settings object not found');
}
return this.settings.getSettings();
},
};
mixin(SettingsCommands);
@@ -1,168 +0,0 @@
// @ts-check
/* eslint-disable no-unused-vars */
/* eslint-disable require-await */
import {waitForCondition} from 'asyncbox';
import _ from 'lodash';
import {util} from '@appium/support';
import {errors} from '../../protocol';
const MIN_TIMEOUT = 0;
/**
* @template {Constraints} C
* @param {import('../driver').BaseDriverBase<C>} Base
* @returns {TimeoutBase<C>}
*/
export function TimeoutMixin(Base) {
/**
* @implements {ITimeoutCommands}
*/
class TimeoutCommands extends Base {
async timeouts(type, ms, script, pageLoad, implicit) {
if (util.hasValue(type) && util.hasValue(ms)) {
this.log.debug(`MJSONWP timeout arguments: ${JSON.stringify({type, ms})}}`);
switch (type) {
case 'command':
await this.newCommandTimeout(ms);
return;
case 'implicit':
await this.implicitWaitMJSONWP(ms);
return;
case 'page load':
await this.pageLoadTimeoutMJSONWP(ms);
return;
case 'script':
await this.scriptTimeoutMJSONWP(ms);
return;
default:
throw new Error(`'${type}' type is not supported for MJSONWP timeout`);
}
}
// Otherwise assume it is W3C protocol
this.log.debug(
`W3C timeout argument: ${JSON.stringify({
script,
pageLoad,
implicit,
})}}`
);
if (util.hasValue(script)) {
await this.scriptTimeoutW3C(script);
}
if (util.hasValue(pageLoad)) {
await this.pageLoadTimeoutW3C(pageLoad);
}
if (util.hasValue(implicit)) {
await this.implicitWaitW3C(implicit);
}
}
async getTimeouts() {
return {
command: this.newCommandTimeoutMs,
implicit: this.implicitWaitMs,
};
}
// implicit
async implicitWaitW3C(ms) {
await this.implicitWait(ms);
}
async implicitWaitMJSONWP(ms) {
await this.implicitWait(ms);
}
async implicitWait(ms) {
await this.setImplicitWait(this.parseTimeoutArgument(ms));
}
// pageLoad
async pageLoadTimeoutW3C(ms) {
throw new errors.NotImplementedError('Not implemented yet for pageLoad.');
}
async pageLoadTimeoutMJSONWP(ms) {
throw new errors.NotImplementedError('Not implemented yet for pageLoad.');
}
// script
async scriptTimeoutW3C(ms) {
throw new errors.NotImplementedError('Not implemented yet for script.');
}
async scriptTimeoutMJSONWP(ms) {
throw new errors.NotImplementedError('Not implemented yet for script.');
}
// command
async newCommandTimeout(ms) {
this.setNewCommandTimeout(this.parseTimeoutArgument(ms));
}
setImplicitWait(ms) {
// eslint-disable-line require-await
this.implicitWaitMs = ms;
this.log.debug(`Set implicit wait to ${ms}ms`);
if (this.managedDrivers && this.managedDrivers.length) {
this.log.debug('Setting implicit wait on managed drivers');
for (let driver of this.managedDrivers) {
if (_.isFunction(driver.setImplicitWait)) {
driver.setImplicitWait(ms);
}
}
}
}
setNewCommandTimeout(ms) {
this.newCommandTimeoutMs = ms;
this.log.debug(`Set new command timeout to ${ms}ms`);
if (this.managedDrivers && this.managedDrivers.length) {
this.log.debug('Setting new command timeout on managed drivers');
for (let driver of this.managedDrivers) {
if (_.isFunction(driver.setNewCommandTimeout)) {
driver.setNewCommandTimeout(ms);
}
}
}
}
async implicitWaitForCondition(condFn) {
this.log.debug(`Waiting up to ${this.implicitWaitMs} ms for condition`);
let wrappedCondFn = async (...args) => {
// reset command timeout
await this.clearNewCommandTimeout();
return await condFn(...args);
};
return await waitForCondition(wrappedCondFn, {
waitMs: this.implicitWaitMs,
intervalMs: 500,
logger: this.log,
});
}
parseTimeoutArgument(ms) {
let duration = parseInt(ms, 10);
if (_.isNaN(duration) || duration < MIN_TIMEOUT) {
throw new errors.UnknownError(`Invalid timeout value '${ms}'`);
}
return duration;
}
}
return TimeoutCommands;
}
/**
* @typedef {import('@appium/types').ITimeoutCommands} ITimeoutCommands
* @typedef {import('@appium/types').Constraints} Constraints
*/
/**
* @template {Constraints} C
* @typedef {import('../driver').BaseDriverBase<C, ITimeoutCommands>} TimeoutBase
*/
@@ -0,0 +1,155 @@
import {waitForCondition} from 'asyncbox';
import _ from 'lodash';
import {util} from '@appium/support';
import {errors} from '../../protocol';
import {BaseDriver} from '../driver';
import {Constraints, ITimeoutCommands} from '@appium/types';
import {mixin} from './mixin';
declare module '../driver' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface BaseDriver<C extends Constraints> extends ITimeoutCommands {}
}
const MIN_TIMEOUT = 0;
const TimeoutCommands: ITimeoutCommands = {
async timeouts<C extends Constraints>(this: BaseDriver<C>, type, ms, script, pageLoad, implicit) {
if (util.hasValue(type) && util.hasValue(ms)) {
this.log.debug(`MJSONWP timeout arguments: ${JSON.stringify({type, ms})}}`);
switch (type) {
case 'command':
await this.newCommandTimeout(ms);
return;
case 'implicit':
await this.implicitWaitMJSONWP(ms);
return;
case 'page load':
await this.pageLoadTimeoutMJSONWP(ms);
return;
case 'script':
await this.scriptTimeoutMJSONWP(ms);
return;
default:
throw new Error(`'${type}' type is not supported for MJSONWP timeout`);
}
}
// Otherwise assume it is W3C protocol
this.log.debug(
`W3C timeout argument: ${JSON.stringify({
script,
pageLoad,
implicit,
})}}`
);
if (util.hasValue(script)) {
await this.scriptTimeoutW3C(script);
}
if (util.hasValue(pageLoad)) {
await this.pageLoadTimeoutW3C(pageLoad);
}
if (util.hasValue(implicit)) {
await this.implicitWaitW3C(implicit);
}
},
async getTimeouts() {
return {
command: this.newCommandTimeoutMs,
implicit: this.implicitWaitMs,
};
},
// implicit
async implicitWaitW3C<C extends Constraints>(this: BaseDriver<C>, ms) {
await this.implicitWait(ms);
},
async implicitWaitMJSONWP<C extends Constraints>(this: BaseDriver<C>, ms) {
await this.implicitWait(ms);
},
async implicitWait<C extends Constraints>(this: BaseDriver<C>, ms) {
this.setImplicitWait(this.parseTimeoutArgument(ms));
},
// pageLoad
async pageLoadTimeoutW3C<C extends Constraints>(this: BaseDriver<C>, ms) {
throw new errors.NotImplementedError('Not implemented yet for pageLoad.');
},
async pageLoadTimeoutMJSONWP<C extends Constraints>(this: BaseDriver<C>, ms) {
throw new errors.NotImplementedError('Not implemented yet for pageLoad.');
},
// script
async scriptTimeoutW3C<C extends Constraints>(this: BaseDriver<C>, ms) {
throw new errors.NotImplementedError('Not implemented yet for script.');
},
async scriptTimeoutMJSONWP<C extends Constraints>(this: BaseDriver<C>, ms) {
throw new errors.NotImplementedError('Not implemented yet for script.');
},
// command
async newCommandTimeout<C extends Constraints>(this: BaseDriver<C>, ms) {
this.setNewCommandTimeout(this.parseTimeoutArgument(ms));
},
setImplicitWait<C extends Constraints>(this: BaseDriver<C>, ms: number) {
// eslint-disable-line require-await
this.implicitWaitMs = ms;
this.log.debug(`Set implicit wait to ${ms}ms`);
if (this.managedDrivers && this.managedDrivers.length) {
this.log.debug('Setting implicit wait on managed drivers');
for (const driver of this.managedDrivers) {
if (_.isFunction(driver.setImplicitWait)) {
driver.setImplicitWait(ms);
}
}
}
},
setNewCommandTimeout<C extends Constraints>(this: BaseDriver<C>, ms: number) {
this.newCommandTimeoutMs = ms;
this.log.debug(`Set new command timeout to ${ms}ms`);
if (this.managedDrivers && this.managedDrivers.length) {
this.log.debug('Setting new command timeout on managed drivers');
for (const driver of this.managedDrivers) {
if (_.isFunction(driver.setNewCommandTimeout)) {
driver.setNewCommandTimeout(ms);
}
}
}
},
async implicitWaitForCondition<C extends Constraints>(
this: BaseDriver<C>,
condFn: (...args: any[]) => Promise<any>
) {
this.log.debug(`Waiting up to ${this.implicitWaitMs} ms for condition`);
const wrappedCondFn = async (...args: any[]) => {
// reset command timeout
await this.clearNewCommandTimeout();
return await condFn(...args);
};
return await waitForCondition(wrappedCondFn, {
waitMs: this.implicitWaitMs,
intervalMs: 500,
logger: this.log,
});
},
parseTimeoutArgument<C extends Constraints>(this: BaseDriver<C>, ms: number | string) {
const duration = parseInt(String(ms), 10);
if (_.isNaN(duration) || duration < MIN_TIMEOUT) {
throw new errors.UnknownError(`Invalid timeout value '${ms}'`);
}
return duration;
},
};
mixin(TimeoutCommands);
+11 -28
View File
@@ -1,7 +1,7 @@
/* eslint-disable no-unused-vars */
/* eslint-disable require-await */
import {fs, logger} from '@appium/support';
import {logger} from '@appium/support';
import AsyncLock from 'async-lock';
import {EventEmitter} from 'events';
import _ from 'lodash';
@@ -9,18 +9,16 @@ import os from 'os';
import {DEFAULT_BASE_PATH, PROTOCOLS} from '../constants';
import {errors} from '../protocol';
import DeviceSettings from './device-settings';
import helpers from './helpers';
// for compat with running tests transpiled and in-place
const {version: BASEDRIVER_VER} = fs.readPackageJsonFrom(__dirname);
import helpers, {BASEDRIVER_VER} from './helpers';
const NEW_COMMAND_TIMEOUT_MS = 60 * 1000;
const ON_UNEXPECTED_SHUTDOWN_EVENT = 'onUnexpectedShutdown';
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @implements {Core<C>}
* @template {Constraints} C
* @template {StringRecord} [Settings=StringRecord]
* @implements {Core<C, Settings>}
*/
class DriverCore {
/**
@@ -29,9 +27,6 @@ class DriverCore {
*/
static baseVersion = BASEDRIVER_VER;
/** @type {import('@appium/types').ExecuteMethodMap<DriverCore>} */
static executeMethodMap = {};
/**
* @type {string?}
*/
@@ -43,7 +38,7 @@ class DriverCore {
opts;
/**
* @type {ServerArgs}
* @type {import('@appium/types').DriverOpts<C>}
*/
initialOpts;
@@ -101,7 +96,6 @@ class DriverCore {
_log;
/**
* @protected
* @type {boolean}
*/
shutdownUnexpectedly;
@@ -122,7 +116,7 @@ class DriverCore {
* we set it to an empty DeviceSettings instance here to make sure that the
* default settings are applied even if an extending driver doesn't utilize
* the settings functionality itself
* @type {DeviceSettings}
* @type {DeviceSettings<Settings>}
*/
settings;
@@ -187,11 +181,9 @@ class DriverCore {
* specific driver sessions. This data can be later used to adjust
* properties for driver instances running in parallel.
* Override it in inherited driver classes if necessary.
*
* @return {Record<string,unknown>} Driver properties mapping
*/
get driverData() {
return {};
return /** @type {import('@appium/types').DriverData} */ ({});
}
/**
@@ -263,7 +255,7 @@ class DriverCore {
* @returns {Core<C> | null}
*/
driverForSession(sessionId) {
return this;
return /** @type {Core<C> | null} */ (this);
}
isMjsonwpProtocol() {
@@ -451,19 +443,10 @@ export {DriverCore};
* @typedef {import('@appium/types').BaseDriverCapConstraints} BaseDriverCapConstraints
*/
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @template {StringRecord|void} [Extra=void]
* @typedef {import('@appium/types').Capabilities<C, Extra>} Capabilities
*/
/**
* @template {StringRecord} [T={}]
* @typedef {import('@appium/types').W3CCapabilities<T>} W3CCapabilities
*/
/**
* @template {Constraints} C
* @typedef {import('@appium/types').Core<C>} Core
* @template {StringRecord} [S=StringRecord]
* @typedef {import('@appium/types').Core<C, S>} Core
*/
/**
@@ -9,13 +9,13 @@ import {errors} from '../protocol/errors';
export const MAX_SETTINGS_SIZE = 20 * 1024 * 1024; // 20 MB
/**
* @template T
* @template {import('@appium/types').StringRecord} T
* @implements {IDeviceSettings<T>}
*/
class DeviceSettings {
export class DeviceSettings {
/**
* @protected
* @type {Record<string,T>}
* @type {T}
*/
_settings;
@@ -27,17 +27,17 @@ class DeviceSettings {
/**
* Creates a _shallow copy_ of the `defaultSettings` parameter!
* @param {Record<string,T>} [defaultSettings]
* @param {T} [defaultSettings]
* @param {import('@appium/types').SettingsUpdateListener<T>} [onSettingsUpdate]
*/
constructor(defaultSettings = {}, onSettingsUpdate = async () => {}) {
constructor(defaultSettings = /** @type {T} */ ({}), onSettingsUpdate = async () => {}) {
this._settings = {...defaultSettings};
this._onSettingsUpdate = onSettingsUpdate;
}
/**
* calls updateSettings from implementing driver every time a setting is changed.
* @param {Record<string,T>} newSettings
* @param {T} newSettings
*/
async update(newSettings) {
if (!_.isPlainObject(newSettings)) {
@@ -54,8 +54,7 @@ class DeviceSettings {
);
}
const props = /** @type {(keyof T & string)[]} */ (_.keys(newSettings));
for (const prop of props) {
for (const prop in newSettings) {
if (!_.isUndefined(this._settings[prop])) {
if (this._settings[prop] === newSettings[prop]) {
log.debug(`The value of '${prop}' setting did not change. Skipping the update for it`);
@@ -73,9 +72,8 @@ class DeviceSettings {
}
export default DeviceSettings;
export {DeviceSettings};
/**
* @template T
* @typedef {import('@appium/types').DeviceSettings<T>} IDeviceSettings
* @template {import('@appium/types').StringRecord} [T=import('@appium/types').StringRecord]
* @typedef {import('@appium/types').IDeviceSettings<T>} IDeviceSettings
*/
@@ -1,6 +1,3 @@
/* eslint-disable require-await */
/* eslint-disable no-unused-vars */
import {validateCaps, processCapabilities} from './capabilities';
import {DriverCore} from './core';
import {util} from '@appium/support';
@@ -8,9 +5,22 @@ import B from 'bluebird';
import _ from 'lodash';
import {fixCaps, isW3cCaps} from '../helpers/capabilities';
import {DELETE_SESSION_COMMAND, determineProtocol, errors} from '../protocol';
import {createBaseDriverClass} from './commands';
import helpers from './helpers';
import {BASE_DESIRED_CAP_CONSTRAINTS} from '@appium/types';
import {
AppiumServer,
BaseDriverCapConstraints,
BASE_DESIRED_CAP_CONSTRAINTS,
Capabilities,
Constraints,
DefaultCreateSessionResult,
Driver,
DriverCaps,
DriverData,
DriverOpts,
ServerArgs,
StringRecord,
W3CDriverCaps,
} from '@appium/types';
const EVENT_SESSION_INIT = 'newSessionRequested';
const EVENT_SESSION_START = 'newSessionStarted';
@@ -18,55 +28,31 @@ const EVENT_SESSION_QUIT_START = 'quitSessionRequested';
const EVENT_SESSION_QUIT_DONE = 'quitSessionFinished';
const ON_UNEXPECTED_SHUTDOWN_EVENT = 'onUnexpectedShutdown';
/**
* @implements {SessionHandler<C>}
* @template {Constraints} C
* @template {StringRecord} [CArgs=StringRecord]
* @extends {DriverCore<C>}
*/
export class BaseDriverCore extends DriverCore {
/**
* @type {CArgs & ServerArgs}
*/
cliArgs;
export class BaseDriver<
C extends Constraints,
CArgs extends StringRecord = StringRecord,
Settings extends StringRecord = StringRecord
>
extends DriverCore<C, Settings>
implements Driver<C, CArgs>
{
cliArgs: CArgs & ServerArgs;
/**
* @type {Capabilities<C>}
*/
caps;
caps: DriverCaps<C>;
originalCaps: W3CDriverCaps<C>;
desiredCapConstraints: C;
opts: DriverOpts<C>;
server?: AppiumServer;
serverHost?: string;
serverPort?: number;
serverPath?: string;
/**
* @type {W3CCapabilities<C>}
*/
originalCaps;
/**
* @type {C}
*/
desiredCapConstraints;
/**
* @type {DriverOpts<C> & DriverOpts<BaseDriverCapConstraints>}
*/
opts;
/**
*
* @param {DriverOpts<C>} opts
* @param {boolean} shouldValidateCaps
*/
constructor(opts = /** @type {DriverOpts<C>} */ ({}), shouldValidateCaps = true) {
constructor(opts: DriverOpts<C>, shouldValidateCaps = true) {
super(opts, shouldValidateCaps);
/**
* This must be assigned here because the declaration of {@linkcode BaseDriverCore.opts} above
* blows away {@linkcode DriverCore.opts}.
*/
this.opts = opts;
this.caps = {} as DriverCaps<C>;
this.caps = {};
this.cliArgs = /** @type {CArgs & ServerArgs} */ ({});
this.cliArgs = {} as CArgs & ServerArgs;
}
/**
@@ -75,25 +61,20 @@ export class BaseDriverCore extends DriverCore {
* Subclasses _shouldn't_ need to use this. If you need to use this, please create
* an issue:
* @see https://github.com/appium/appium/issues/new
* @type {Readonly<BaseDriverCapConstraints & C>}
* @protected
*/
get _desiredCapConstraints() {
protected get _desiredCapConstraints(): Readonly<BaseDriverCapConstraints & C> {
return Object.freeze(_.merge({}, BASE_DESIRED_CAP_CONSTRAINTS, this.desiredCapConstraints));
}
// This is the main command handler for the driver. It wraps command
// execution with timeout logic, checking that we have a valid session,
// and ensuring that we execute commands one at a time. This method is called
// by MJSONWP's express router.
/**
* @param {string} cmd
* @param {...any} args
* @returns {Promise<any>}
* This is the main command handler for the driver. It wraps command
* execution with timeout logic, checking that we have a valid session,
* and ensuring that we execute commands one at a time. This method is called
* by MJSONWP's express router.
*/
async executeCommand(cmd, ...args) {
async executeCommand<T = unknown>(cmd: string, ...args: any[]): Promise<T> {
// get start time for this command, and log in special cases
let startTime = Date.now();
const startTime = Date.now();
if (cmd === 'createSession') {
// If creating a session determine if W3C or MJSONWP protocol was requested and remember the choice
@@ -161,12 +142,8 @@ export class BaseDriverCore extends DriverCore {
return res;
}
/**
*
* @param {Error|import('../protocol/errors').NoSuchDriverError} err
*/
async startUnexpectedShutdown(
err = new errors.NoSuchDriverError('The driver was unexpectedly shut down!')
err: Error = new errors.NoSuchDriverError('The driver was unexpectedly shut down!')
) {
this.eventEmitter.emit(ON_UNEXPECTED_SHUTDOWN_EVENT, err); // allow others to listen for this
this.shutdownUnexpectedly = true;
@@ -200,14 +177,7 @@ export class BaseDriverCore extends DriverCore {
}, this.newCommandTimeoutMs);
}
/**
*
* @param {import('@appium/types').AppiumServer} server
* @param {string} host
* @param {number} port
* @param {string} path
*/
assignServer(server, host, port, path) {
assignServer(server: AppiumServer, host: string, port: number, path: string) {
this.server = server;
this.serverHost = host;
this.serverPort = port;
@@ -223,8 +193,8 @@ export class BaseDriverCore extends DriverCore {
this.log.debug('Running generic full reset');
// preserving state
let currentConfig = {};
for (let property of [
const currentConfig = {};
for (const property of [
'implicitWaitMs',
'newCommandTimeoutMs',
'sessionId',
@@ -233,9 +203,6 @@ export class BaseDriverCore extends DriverCore {
currentConfig[property] = this[property];
}
// We also need to preserve the unexpected shutdown, and make sure it is not cancelled during reset.
this.resetOnUnexpectedShutdown = () => {};
try {
if (this.sessionId !== null) {
await this.deleteSession(this.sessionId);
@@ -244,7 +211,7 @@ export class BaseDriverCore extends DriverCore {
await this.createSession(this.originalCaps);
} finally {
// always restore state.
for (let [key, value] of _.toPairs(currentConfig)) {
for (const [key, value] of _.toPairs(currentConfig)) {
this[key] = value;
}
}
@@ -257,13 +224,14 @@ export class BaseDriverCore extends DriverCore {
* Appium 2 has dropped the support of these, so now we only accept capability
* objects in W3C format and thus allow any of the three arguments to represent
* the latter.
* @param {W3CCapabilities<C>} w3cCapabilities1
* @param {W3CCapabilities<C>} [w3cCapabilities2]
* @param {W3CCapabilities<C>} [w3cCapabilities]
* @param {DriverData[]} [driverData]
* @returns {Promise<[string,Capabilities<C>]>}
*/
async createSession(w3cCapabilities1, w3cCapabilities2, w3cCapabilities, driverData) {
async createSession(
w3cCapabilities1: W3CDriverCaps<C>,
w3cCapabilities2?: W3CDriverCaps<C>,
w3cCapabilities?: W3CDriverCaps<C>,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
driverData?: DriverData[]
): Promise<DefaultCreateSessionResult<C>> {
if (this.sessionId !== null) {
throw new errors.SessionNotCreatedError(
'Cannot create a new session while one is in progress'
@@ -289,15 +257,14 @@ export class BaseDriverCore extends DriverCore {
`Creating session with W3C capabilities: ${JSON.stringify(originalCaps, null, 2)}`
);
/** @type {Capabilities<C>} */
let caps;
let caps: DriverCaps<C>;
try {
caps = processCapabilities(
originalCaps,
this._desiredCapConstraints,
this.shouldValidateCaps
);
caps = fixCaps(caps, this._desiredCapConstraints, this.log);
) as DriverCaps<C>;
caps = fixCaps(caps, this._desiredCapConstraints, this.log) as DriverCaps<C>;
} catch (e) {
throw new errors.SessionNotCreatedError(e.message);
}
@@ -334,7 +301,7 @@ export class BaseDriverCore extends DriverCore {
}
if (!_.isUndefined(this.caps.newCommandTimeout)) {
this.newCommandTimeoutMs = /** @type {number} */ (this.caps.newCommandTimeout) * 1000;
this.newCommandTimeoutMs = (this.caps.newCommandTimeout as number) * 1000;
}
this._log.prefix = helpers.generateDriverLogPrefix(this, this.sessionId);
@@ -344,32 +311,23 @@ export class BaseDriverCore extends DriverCore {
return [this.sessionId, caps];
}
/**
*
* @param {string} [sessionId]
* @param {DriverData[]} [driverData]
* @returns {Promise<void>}
*/
async deleteSession(sessionId, driverData) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async deleteSession(sessionId?: string | null) {
await this.clearNewCommandTimeout();
if (this.isCommandsQueueEnabled && this.commandsQueueGuard.isBusy()) {
// simple hack to release pending commands if they exist
// @ts-ignore
for (const key of _.keys(this.commandsQueueGuard.queues)) {
// @ts-ignore
this.commandsQueueGuard.queues[key] = [];
// @ts-expect-error private API
const queues = this.commandsQueueGuard.queues;
for (const key of _.keys(queues)) {
queues[key] = [];
}
}
this.sessionId = null;
this._log.prefix = helpers.generateDriverLogPrefix(this);
}
/**
*
* @param {Capabilities<C>} caps
*/
logExtraCaps(caps) {
let extraCaps = _.difference(_.keys(caps), _.keys(this._desiredCapConstraints));
logExtraCaps(caps: Capabilities<C>) {
const extraCaps = _.difference(_.keys(caps), _.keys(this._desiredCapConstraints));
if (extraCaps.length) {
this.log.warn(
`The following capabilities were provided, but are not ` + `recognized by Appium:`
@@ -380,12 +338,7 @@ export class BaseDriverCore extends DriverCore {
}
}
/**
*
* @param {Capabilities<C>} caps
* @returns {boolean}
*/
validateDesiredCaps(caps) {
validateDesiredCaps(caps: any): caps is DriverCaps<C> {
if (!this.shouldValidateCaps) {
return true;
}
@@ -407,68 +360,6 @@ export class BaseDriverCore extends DriverCore {
}
}
/**
* This ensures that all of the mixins correctly implement the interface described in {@linkcode Driver}.
* @template {Constraints} [C={}]
* @implements {Driver<C>}
*/
export class BaseDriver extends createBaseDriverClass(BaseDriverCore) {}
export * from './commands';
export default BaseDriver;
/**
* @typedef {import('@appium/types').HTTPMethod} HTTPMethod
* @typedef {import('@appium/types').DriverData} DriverData
* @typedef {import('@appium/types').Constraints} Constraints
* @typedef {import('@appium/types').Constraint} Constraint
* @typedef {import('@appium/types').StringRecord} StringRecord
* @typedef {import('@appium/types').BaseDriverCapConstraints} BaseDriverCapConstraints
* @typedef {import('@appium/types').ServerArgs} ServerArgs
*/
/**
* @callback UpdateServerCallback
* @param {import('express').Express} app - Express app
* @param {import('@appium/types').AppiumServer} httpServer - HTTP server
* @returns {import('type-fest').Promisable<void>}
*/
/**
* This is used to extend {@linkcode BaseDriverCore} by the mixins and also external drivers.
* @template {Constraints} C
* @template [Proto={}]
* @template [Static={}]
* @typedef {import('@appium/types').Class<BaseDriverCore<C> & Proto,import('@appium/types').DriverStatic & Static>} BaseDriverBase
*/
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @typedef {import('@appium/types').SessionHandler<[string, object],void, C>} SessionHandler
*/
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @template {StringRecord|void} [Extra=void]
* @typedef {import('@appium/types').Capabilities<C, Extra>} Capabilities
*/
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @template {StringRecord|void} [Extra=void]
* @typedef {import('@appium/types').W3CCapabilities<C, Extra>} W3CCapabilities
*/
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @template {StringRecord} [CArgs=StringRecord]
* @typedef {import('@appium/types').Driver<C, CArgs>} Driver
*/
/**
* @template {Constraints} C
* @typedef {import('@appium/types').ExternalDriver<C>} ExternalDriver
*/
/**
* @template {Constraints} C
* @typedef {import('@appium/types').DriverOpts<C>} DriverOpts
*/
+216 -214
View File
@@ -2,16 +2,24 @@ import _ from 'lodash';
import path from 'path';
import url from 'url';
import logger from './logger';
import {tempDir, fs, util, zip, net, timing, node} from '@appium/support';
import {tempDir, fs, util, zip, timing, node} from '@appium/support';
import LRU from 'lru-cache';
import AsyncLock from 'async-lock';
import axios from 'axios';
import B from 'bluebird';
// for compat with running tests transpiled and in-place
const {version: BASEDRIVER_VER} = fs.readPackageJsonFrom(__dirname);
const IPA_EXT = '.ipa';
const ZIP_EXTS = ['.zip', IPA_EXT];
const ZIP_EXTS = new Set(['.zip', IPA_EXT]);
const ZIP_MIME_TYPES = ['application/zip', 'application/x-zip-compressed', 'multipart/x-zip'];
const CACHED_APPS_MAX_AGE = 1000 * 60 * 60 * 24; // ms
const MAX_CACHED_APPS = 1024;
const HTTP_STATUS_NOT_MODIFIED = 304;
const DEFAULT_REQ_HEADERS = Object.freeze({
'user-agent': `Appium (BaseDriver v${BASEDRIVER_VER})`,
});
const AVG_DOWNLOAD_SPEED_MEASUREMENT_THRESHOLD_SEC = 2;
const APPLICATIONS_CACHE = new LRU({
max: MAX_CACHED_APPS,
ttl: CACHED_APPS_MAX_AGE, // expire after 24 hours
@@ -52,77 +60,6 @@ process.on('exit', () => {
}
});
/**
*
* @param {string} url
* @returns {Promise<import('axios').AxiosResponse['headers']>}
*/
async function retrieveHeaders(url) {
try {
return (
await axios({
url,
method: 'HEAD',
timeout: 5000,
})
).headers;
} catch (e) {
logger.info(`Cannot send HEAD request to '${url}'. Original error: ${e.message}`);
}
return {};
}
function getCachedApplicationPath(link, currentAppProps = {}, cachedAppInfo = {}) {
const refresh = () => {
logger.debug(`A fresh copy of the application is going to be downloaded from ${link}`);
return null;
};
if (!_.isPlainObject(cachedAppInfo) || !_.isPlainObject(currentAppProps)) {
// if an invalid arg is passed then assume cache miss
return refresh();
}
const {
lastModified: currentModified,
immutable: currentImmutable,
// maxAge is in seconds
maxAge: currentMaxAge,
} = currentAppProps;
const {
// Date instance
lastModified,
// boolean
immutable,
// Unix time in milliseconds
timestamp,
fullPath,
} = cachedAppInfo;
if (lastModified && currentModified) {
if (currentModified.getTime() <= lastModified.getTime()) {
logger.debug(`The application at ${link} has not been modified since ${lastModified}`);
return fullPath;
}
logger.debug(`The application at ${link} has been modified since ${lastModified}`);
return refresh();
}
if (immutable && currentImmutable) {
logger.debug(`The application at ${link} is immutable`);
return fullPath;
}
if (currentMaxAge && timestamp) {
const msLeft = timestamp + currentMaxAge * 1000 - Date.now();
if (msLeft > 0) {
logger.debug(
`The cached application '${path.basename(fullPath)}' will expire in ${msLeft / 1000}s`
);
return fullPath;
}
logger.debug(`The cached application '${path.basename(fullPath)}' has expired`);
}
return refresh();
}
function verifyAppExtension(app, supportedAppExtensions) {
if (supportedAppExtensions.map(_.toLower).includes(_.toLower(path.extname(app)))) {
return app;
@@ -160,56 +97,14 @@ async function isAppIntegrityOk(currentPath, expectedIntegrity = {}) {
}
/**
* @typedef PostProcessOptions
* @property {?Object} cachedAppInfo The information about the previously cached app instance (if exists):
* - packageHash: SHA1 hash of the package if it is a file and not a folder
* - lastModified: Optional Date instance, the value of file's `Last-Modified` header
* - immutable: Optional boolean value. Contains true if the file has an `immutable` mark
* in `Cache-control` header
* - maxAge: Optional integer representation of `maxAge` parameter in `Cache-control` header
* - timestamp: The timestamp this item has been added to the cache (measured in Unix epoch
* milliseconds)
* - integrity: An object containing either `file` property with SHA1 hash of the file
* or `folder` property with total amount of cached files and subfolders
* - fullPath: the full path to the cached app
* @property {boolean} isUrl Whether the app has been downloaded from a remote URL
* @property {?Object} headers Optional headers object. Only present if `isUrl` is true and if the server
* responds to HEAD requests. All header names are normalized to lowercase.
* @property {string} appPath A string containing full path to the preprocessed application package (either
* downloaded or a local one)
*/
/**
* @typedef PostProcessResult
* @property {string} appPath The full past to the post-processed application package on the
* local file system (might be a file or a folder path)
*/
/**
* @typedef ConfigureAppOptions
* @property {(obj: PostProcessOptions) => (Promise<PostProcessResult|undefined>|PostProcessResult|undefined)} [onPostProcess]
* Optional function, which should be applied
* to the application after it is downloaded/preprocessed. This function may be async
* and is expected to accept single object parameter.
* The function is expected to either return a falsy value, which means the app must not be
* cached and a fresh copy of it is downloaded each time. If this function returns an object
* containing `appPath` property then the integrity of it will be verified and stored into
* the cache.
* @property {string[]} supportedExtensions List of supported application extensions (
* including starting dots). This property is mandatory and must not be empty.
*/
/**
* Prepares an app to be used in an automated test. The app gets cached automatically
* if it is an archive or if it is downloaded from an URL.
* If the downloaded app has `.zip` extension, this method will unzip it.
* The unzip does not work when `onPostProcess` is provided.
*
* @param {string} app Either a full path to the app or a remote URL
* @param {string|string[]|ConfigureAppOptions} options
* @returns The full path to the resulting application bundle
* @param {string} app
* @param {string|string[]|import('@appium/types').ConfigureAppOptions} options
*/
async function configureApp(app, options = /** @type {ConfigureAppOptions} */ ({})) {
async function configureApp(
app,
options = /** @type {import('@appium/types').ConfigureAppOptions} */ ({})
) {
if (!_.isString(app)) {
// immediately shortcircuit if not given an app
return;
@@ -233,13 +128,14 @@ async function configureApp(app, options = /** @type {ConfigureAppOptions} */ ({
let newApp = app;
let shouldUnzipApp = false;
let packageHash = null;
/** @type {import('axios').AxiosResponse['headers']?} */
let headers = null;
/** @type {import('axios').AxiosResponse['headers']|undefined} */
let headers = undefined;
/** @type {RemoteAppProps} */
const remoteAppProps = {
lastModified: null,
immutable: false,
maxAge: null,
etag: null,
};
const {protocol, pathname} = url.parse(newApp);
const isUrl = protocol === null ? false : ['http:', 'https:'].includes(protocol);
@@ -250,94 +146,121 @@ async function configureApp(app, options = /** @type {ConfigureAppOptions} */ ({
if (isUrl) {
// Use the app from remote URL
logger.info(`Using downloadable app '${newApp}'`);
headers = await retrieveHeaders(newApp);
if (!_.isEmpty(headers)) {
if (headers['last-modified']) {
remoteAppProps.lastModified = new Date(headers['last-modified']);
}
logger.debug(`Last-Modified: ${headers['last-modified']}`);
if (headers['cache-control']) {
remoteAppProps.immutable = /\bimmutable\b/i.test(headers['cache-control']);
const maxAgeMatch = /\bmax-age=(\d+)\b/i.exec(headers['cache-control']);
if (maxAgeMatch) {
remoteAppProps.maxAge = parseInt(maxAgeMatch[1], 10);
}
}
logger.debug(`Cache-Control: ${headers['cache-control']}`);
}
const cachedPath = getCachedApplicationPath(app, remoteAppProps, cachedAppInfo);
if (cachedPath) {
if (await isAppIntegrityOk(cachedPath, cachedAppInfo?.integrity)) {
logger.info(`Reusing previously downloaded application at '${cachedPath}'`);
return verifyAppExtension(cachedPath, supportedAppExtensions);
}
logger.info(
`The application at '${cachedPath}' does not exist anymore ` +
`or its integrity has been damaged. Deleting it from the internal cache`
);
APPLICATIONS_CACHE.delete(app);
const reqHeaders = {
...DEFAULT_REQ_HEADERS,
};
if (cachedAppInfo?.etag) {
reqHeaders['if-none-match'] = remoteAppProps.etag;
} else if (cachedAppInfo?.lastModified) {
reqHeaders['if-modified-since'] = remoteAppProps.lastModified?.toString();
}
let fileName = null;
const basename = fs.sanitizeName(path.basename(decodeURIComponent(pathname ?? '')), {
replacement: SANITIZE_REPLACEMENT,
});
const extname = path.extname(basename);
// to determine if we need to unzip the app, we have a number of places
// to look: content type, content disposition, or the file extension
if (ZIP_EXTS.includes(extname)) {
fileName = basename;
shouldUnzipApp = true;
}
if (headers['content-type']) {
const ct = headers['content-type'];
logger.debug(`Content-Type: ${ct}`);
// the filetype may not be obvious for certain urls, so check the mime type too
if (
ZIP_MIME_TYPES.some((mimeType) =>
new RegExp(`\\b${_.escapeRegExp(mimeType)}\\b`).test(ct)
)
) {
if (!fileName) {
fileName = `${DEFAULT_BASENAME}.zip`;
let {headers, stream, status} = await queryAppLink(newApp, reqHeaders);
try {
if (!_.isEmpty(headers)) {
logger.debug(`Etag: ${remoteAppProps?.etag} -> ${headers.etag}`);
if (headers.etag) {
remoteAppProps.etag = headers.etag;
}
logger.debug(
`Last-Modified: ${remoteAppProps?.['last-modified']} -> ${headers['last-modified']}`
);
if (headers['last-modified']) {
remoteAppProps.lastModified = new Date(headers['last-modified']);
}
logger.debug(
`Cache-Control: ${remoteAppProps?.['cache-control']} -> ${headers['cache-control']}`
);
if (headers['cache-control']) {
remoteAppProps.immutable = /\bimmutable\b/i.test(headers['cache-control']);
const maxAgeMatch = /\bmax-age=(\d+)\b/i.exec(headers['cache-control']);
if (maxAgeMatch) {
remoteAppProps.maxAge = parseInt(maxAgeMatch[1], 10);
}
}
}
if (cachedAppInfo && status === HTTP_STATUS_NOT_MODIFIED) {
if (await isAppIntegrityOk(cachedAppInfo.fullPath, cachedAppInfo.integrity)) {
logger.info(`Reusing previously downloaded application at '${cachedAppInfo.fullPath}'`);
return verifyAppExtension(cachedAppInfo.fullPath, supportedAppExtensions);
}
logger.info(
`The application at '${cachedAppInfo.fullPath}' does not exist anymore ` +
`or its integrity has been damaged. Deleting it from the internal cache`
);
APPLICATIONS_CACHE.delete(app);
if (!stream.closed) {
stream.destroy();
}
({stream, headers, status} = await queryAppLink(newApp, {...DEFAULT_REQ_HEADERS}));
}
let fileName = null;
const basename = fs.sanitizeName(path.basename(decodeURIComponent(pathname ?? '')), {
replacement: SANITIZE_REPLACEMENT,
});
const extname = path.extname(basename);
// to determine if we need to unzip the app, we have a number of places
// to look: content type, content disposition, or the file extension
if (ZIP_EXTS.has(extname)) {
fileName = basename;
shouldUnzipApp = true;
}
}
if (headers['content-disposition'] && /^attachment/i.test(headers['content-disposition'])) {
logger.debug(`Content-Disposition: ${headers['content-disposition']}`);
const match = /filename="([^"]+)/i.exec(headers['content-disposition']);
if (match) {
fileName = fs.sanitizeName(match[1], {
replacement: SANITIZE_REPLACEMENT,
});
shouldUnzipApp = shouldUnzipApp || ZIP_EXTS.includes(path.extname(fileName));
if (headers['content-type']) {
const ct = headers['content-type'];
logger.debug(`Content-Type: ${ct}`);
// the filetype may not be obvious for certain urls, so check the mime type too
if (
ZIP_MIME_TYPES.some((mimeType) =>
new RegExp(`\\b${_.escapeRegExp(mimeType)}\\b`).test(ct)
)
) {
if (!fileName) {
fileName = `${DEFAULT_BASENAME}.zip`;
}
shouldUnzipApp = true;
}
}
if (headers['content-disposition'] && /^attachment/i.test(headers['content-disposition'])) {
logger.debug(`Content-Disposition: ${headers['content-disposition']}`);
const match = /filename="([^"]+)/i.exec(headers['content-disposition']);
if (match) {
fileName = fs.sanitizeName(match[1], {
replacement: SANITIZE_REPLACEMENT,
});
shouldUnzipApp = shouldUnzipApp || ZIP_EXTS.has(path.extname(fileName));
}
}
if (!fileName) {
// assign the default file name and the extension if none has been detected
const resultingName = basename
? basename.substring(0, basename.length - extname.length)
: DEFAULT_BASENAME;
let resultingExt = extname;
if (!supportedAppExtensions.includes(resultingExt)) {
logger.info(
`The current file extension '${resultingExt}' is not supported. ` +
`Defaulting to '${_.first(supportedAppExtensions)}'`
);
resultingExt = /** @type {string} */ (_.first(supportedAppExtensions));
}
fileName = `${resultingName}${resultingExt}`;
}
const targetPath = await tempDir.path({
prefix: fileName,
suffix: '',
});
newApp = await fetchApp(stream, targetPath);
} finally {
if (!stream.closed) {
stream.destroy();
}
}
if (!fileName) {
// assign the default file name and the extension if none has been detected
const resultingName = basename
? basename.substring(0, basename.length - extname.length)
: DEFAULT_BASENAME;
let resultingExt = extname;
if (!supportedAppExtensions.includes(resultingExt)) {
logger.info(
`The current file extension '${resultingExt}' is not supported. ` +
`Defaulting to '${_.first(supportedAppExtensions)}'`
);
resultingExt = /** @type {string} */ (_.first(supportedAppExtensions));
}
fileName = `${resultingName}${resultingExt}`;
}
const targetPath = await tempDir.path({
prefix: fileName,
suffix: '',
});
newApp = await downloadApp(newApp, targetPath);
} else if (await fs.exists(newApp)) {
// Use the local app
logger.info(`Using local app '${newApp}'`);
shouldUnzipApp = ZIP_EXTS.includes(path.extname(newApp));
shouldUnzipApp = ZIP_EXTS.has(path.extname(newApp));
} else {
let errorMessage = `The application at '${newApp}' does not exist or is not accessible`;
// protocol value for 'C:\\temp' is 'c:', so we check the length as well
@@ -411,12 +334,14 @@ async function configureApp(app, options = /** @type {ConfigureAppOptions} */ ({
};
if (_.isFunction(onPostProcess)) {
const result = await onPostProcess({
cachedAppInfo: _.clone(cachedAppInfo),
isUrl,
headers: _.clone(headers),
appPath: newApp,
});
const result = await onPostProcess(
/** @type {import('@appium/types').PostProcessOptions<import('axios').AxiosResponseHeaders>} */ ({
cachedAppInfo: _.clone(cachedAppInfo),
isUrl,
headers: _.clone(headers),
appPath: newApp,
})
);
return !result?.appPath || app === result?.appPath || !(await fs.exists(result?.appPath))
? newApp
: await storeAppInCache(result.appPath);
@@ -429,16 +354,78 @@ async function configureApp(app, options = /** @type {ConfigureAppOptions} */ ({
});
}
async function downloadApp(app, targetPath) {
const {href} = url.parse(app);
/**
* Sends a HTTP GET query to fetch the app with caching enabled.
* Follows https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching
*
* @param {string} appLink The URL to download an app from
* @param {import('axios').RawAxiosRequestHeaders} reqHeaders Additional HTTP request headers
* @returns {Promise<RemoteAppData>}
*/
async function queryAppLink(appLink, reqHeaders) {
const {href} = url.parse(appLink);
/**
* @type {import('axios').RawAxiosRequestConfig}
*/
const requestOpts = {
url: href,
responseType: 'stream',
timeout: APP_DOWNLOAD_TIMEOUT_MS,
validateStatus: (status) =>
(status >= 200 && status < 300) || status === HTTP_STATUS_NOT_MODIFIED,
headers: reqHeaders,
};
try {
await net.downloadFile(href, targetPath, {
timeout: APP_DOWNLOAD_TIMEOUT_MS,
const {data: stream, headers, status} = await axios(requestOpts);
return {
stream,
headers,
status,
};
} catch (err) {
throw new Error(`Cannot download the app from ${href}: ${err.message}`);
}
}
/**
* Retrieves app payload from the given stream. Also meters the download performance.
*
* @param {import('stream').Readable} srcStream The incoming stream
* @param {string} dstPath The target file path to be written
* @returns {Promise<string>} The same dstPath
* @throws {Error} If there was a failure while downloading the file
*/
async function fetchApp(srcStream, dstPath) {
const timer = new timing.Timer().start();
try {
const writer = fs.createWriteStream(dstPath);
srcStream.pipe(writer);
await new B((resolve, reject) => {
srcStream.once('error', reject);
writer.once('finish', resolve);
writer.once('error', (e) => {
srcStream.unpipe(writer);
reject(e);
});
});
} catch (err) {
throw new Error(`Unable to download the app: ${err.message}`);
throw new Error(`Cannot fetch the application: ${err.message}`);
}
return targetPath;
const secondsElapsed = timer.getDuration().asSeconds;
const {size} = await fs.stat(dstPath);
logger.debug(
`The application (${util.toReadableSizeString(size)}) ` +
`has been downloaded to '${dstPath}' in ${secondsElapsed.toFixed(3)}s`
);
// it does not make much sense to approximate the speed for short downloads
if (secondsElapsed >= AVG_DOWNLOAD_SPEED_MEASUREMENT_THRESHOLD_SEC) {
const bytesPerSec = Math.floor(size / secondsElapsed);
logger.debug(`Approximate download speed: ${util.toReadableSizeString(bytesPerSec)}/s`);
}
return dstPath;
}
/**
@@ -606,11 +593,26 @@ export default {
parseCapsArray,
generateDriverLogPrefix,
};
export {configureApp, isPackageOrBundle, duplicateKeys, parseCapsArray, generateDriverLogPrefix};
export {
configureApp,
isPackageOrBundle,
duplicateKeys,
parseCapsArray,
generateDriverLogPrefix,
BASEDRIVER_VER,
};
/**
* @typedef RemoteAppProps
* @property {Date?} lastModified
* @property {boolean} immutable
* @property {number?} maxAge
* @property {string?} etag
*/
/**
* @typedef RemoteAppData Properties of the remote application (e.g. GET HTTP response) to be downloaded.
* @property {number} status The HTTP status of the response
* @property {import('stream').Readable} stream The HTTP response body represented as readable stream
* @property {import('axios').RawAxiosResponseHeaders | import('axios').AxiosResponseHeaders} headers HTTP response headers
*/
+4 -2
View File
@@ -151,8 +151,10 @@ function configureHttp({httpServer, reject, keepAliveTimeout}) {
notifier: new EventEmitter(),
closed: false,
};
// TS does not love monkeypatching.
const appiumServer = /** @type {AppiumServer} */ (/** @type {unknown} */ (httpServer));
/**
* @type {AppiumServer}
*/
const appiumServer = /** @type {any} */ (httpServer);
appiumServer.addWebSocketHandler = addWebSocketHandler;
appiumServer.removeWebSocketHandler = removeWebSocketHandler;
appiumServer.removeAllWebSocketHandlers = removeAllWebSocketHandlers;
+10 -39
View File
@@ -6,33 +6,21 @@ import B from 'bluebird';
const DEFAULT_WS_PATHNAME_PREFIX = '/ws';
/**
* Adds websocket handler to express server instance.
* It is expected this function is called in Express
* server instance context.
*
* @this {AppiumServer} - An instance of express HTTP server.
* @param {string} handlerPathname - Web socket endpoint path starting with
* a single slash character. It is recommended to always add
* DEFAULT_WS_PATHNAME_PREFIX to all web socket pathnames.
* @param {import('ws').Server} handlerServer - WebSocket server instance. See
* https://github.com/websockets/ws/pull/885 for more details
* on how to configure the handler properly.
* @returns {Promise<void>}
* @this {AppiumServer}
* @type {AppiumServer['addWebSocketHandler']}
*/
async function addWebSocketHandler(handlerPathname, handlerServer) {
const server = /** @type {AppiumServer} */ (this);
if (_.isUndefined(this.webSocketsMapping)) {
server.webSocketsMapping = {};
this.webSocketsMapping = {};
// https://github.com/websockets/ws/pull/885
server.on('upgrade', (request, socket, head) => {
this.on('upgrade', (request, socket, head) => {
let currentPathname;
try {
// @ts-expect-error
currentPathname = new URL(request.url).pathname;
currentPathname = new URL(/** @type {string} */ (request.url)).pathname;
} catch {
currentPathname = request.url;
}
for (const [pathname, wsServer] of _.toPairs(server.webSocketsMapping)) {
for (const [pathname, wsServer] of _.toPairs(this.webSocketsMapping)) {
if (currentPathname === pathname) {
wsServer.handleUpgrade(request, socket, head, (ws) => {
wsServer.emit('connection', ws, request);
@@ -47,17 +35,9 @@ async function addWebSocketHandler(handlerPathname, handlerServer) {
}
/**
* Returns web socket handlers registered for the given server
* instance.
* It is expected this function is called in Express
* server instance context.
*
* @this {AppiumServer}
* @param {string?} [keysFilter] - Only include pathnames with given
* `keysFilter` value if set. All pairs will be included by default.
* @returns {Promise<Record<string, import('ws').Server>>} pathnames to websocket server instances mapping matching the search criteria or an empty object otherwise.
* @type {AppiumServer['getWebSocketHandlers']}
*/
// eslint-disable-next-line require-await
async function getWebSocketHandlers(keysFilter = null) {
if (_.isEmpty(this.webSocketsMapping)) {
return {};
@@ -72,16 +52,9 @@ async function getWebSocketHandlers(keysFilter = null) {
}
/**
* Removes existing websocket handler from express server instance.
* The call is ignored if the given `handlerPathname` handler
* is not present in the handlers list.
* It is expected this function is called in Express
* server instance context.
* @this {AppiumServer}
* @param {string} handlerPathname - Websocket endpoint path.
* @returns {Promise<boolean>} true if the handlerPathname was found and deleted
* @type {AppiumServer['removeWebSocketHandler']}
*/
// eslint-disable-next-line require-await
async function removeWebSocketHandler(handlerPathname) {
const wsServer = this.webSocketsMapping?.[handlerPathname];
if (!wsServer) {
@@ -103,11 +76,9 @@ async function removeWebSocketHandler(handlerPathname) {
}
/**
* Removes all existing websocket handler from express server instance.
* It is expected this function is called in Express
* server instance context.
*
* @this {AppiumServer}
* @returns {Promise<boolean>} true if at least one handler has been deleted
* @type {AppiumServer['removeAllWebSocketHandlers']}
*/
async function removeAllWebSocketHandlers() {
if (_.isEmpty(this.webSocketsMapping)) {
@@ -83,7 +83,6 @@ export {isW3cCaps, fixCaps};
*/
/**
* @template {Constraints} [C=BaseDriverCapConstraints]
* @template {StringRecord|void} [Extra=void]
* @typedef {import('@appium/types').Capabilities<C, Extra>} Capabilities
* @template {Constraints} C
* @typedef {import('@appium/types').Capabilities<C>} Capabilities
*/
+11 -2
View File
@@ -277,7 +277,7 @@ function routeConfiguringFunction(driver) {
`${basePath}${path}`,
spec,
driver,
isSessionCommand(spec.command)
isSessionCommand(/** @type {import('@appium/types').DriverMethodDef} */ (spec).command)
);
}
}
@@ -454,7 +454,16 @@ function buildHandler(app, method, path, spec, driver, isSessCmd) {
} catch (err) {
// if anything goes wrong, figure out what our response should be
// based on the type of error that we encountered
let actualErr = err;
let actualErr;
if (err instanceof Error || (_.has(err, 'stack') && _.has(err, 'message'))) {
actualErr = err;
} else {
getLogger(driver, req.params.sessionId || newSessionId).warn(
'The thrown error object does not seem to be a valid instance of the Error class. This ' +
'might be a genuine bug of a driver or a plugin.'
);
actualErr = new Error(`${err ?? 'unknown'}`);
}
currentProtocol =
currentProtocol || extractProtocol(driver, req.params.sessionId || newSessionId);
+12 -13
View File
@@ -18,6 +18,7 @@ const SET_ALERT_TEXT_PAYLOAD_PARAMS = {
* define the routes, mapping of HTTP methods to particular driver commands, and
* any parameters that are expected in a request parameters can be `required` or
* `optional`
* @satisfies {import('@appium/types').MethodMap<import('../basedriver/driver').BaseDriver>}
*/
const METHOD_MAP = /** @type {const} */ ({
'/status': {
@@ -129,7 +130,11 @@ const METHOD_MAP = /** @type {const} */ ({
POST: {command: 'deactivateIMEEngine', deprecated: true},
},
'/session/:sessionId/ime/activate': {
POST: {command: 'activateIMEEngine', payloadParams: {required: ['engine']}, deprecated: true},
POST: {
command: 'activateIMEEngine',
payloadParams: {required: ['engine']},
deprecated: true,
},
},
'/session/:sessionId/frame': {
POST: {command: 'setFrame', payloadParams: {required: ['id']}},
@@ -356,7 +361,11 @@ const METHOD_MAP = /** @type {const} */ ({
DELETE: {command: 'releaseActions'},
},
'/session/:sessionId/touch/longclick': {
POST: {command: 'touchLongClick', payloadParams: {required: ['elements']}, deprecated: true},
POST: {
command: 'touchLongClick',
payloadParams: {required: ['elements']},
deprecated: true,
},
},
'/session/:sessionId/touch/flick': {
POST: {
@@ -922,7 +931,7 @@ const METHOD_MAP = /** @type {const} */ ({
let ALL_COMMANDS = [];
for (let v of _.values(METHOD_MAP)) {
for (let m of _.values(v)) {
if (m.command) {
if ('command' in m && m.command) {
ALL_COMMANDS.push(m.command);
}
}
@@ -1006,13 +1015,3 @@ function routeToCommandName(endpoint, method, basePath = DEFAULT_BASE_PATH) {
const NO_SESSION_ID_COMMANDS = ['createSession', 'getStatus', 'getSessions'];
export {METHOD_MAP, ALL_COMMANDS, NO_SESSION_ID_COMMANDS, routeToCommandName};
/**
* This checks compat with the `MethodMap` interface.
* @ignore
*/
// eslint-disable-next-line no-unused-vars
const _validMethodMap =
/** @type {import('@appium/types').MethodMap<import('@appium/types').ExternalDriver<import('@appium/types').BaseDriverCapConstraints>>} */ (
METHOD_MAP
);
+10 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/base-driver",
"version": "9.3.2",
"version": "9.3.4",
"description": "Base driver class for Appium drivers",
"keywords": [
"automation",
@@ -40,11 +40,12 @@
"test": "npm run test:unit",
"test:e2e": "mocha -p --timeout 20s --slow 10s \"./test/e2e/**/*.spec.js\"",
"test:smoke": "node ./index.js",
"test:unit": "mocha \"./test/unit/**/*.spec.js\""
"test:unit": "mocha \"./test/unit/**/*.spec.js\"",
"test:types": "tsd"
},
"dependencies": {
"@appium/support": "^3.1.6",
"@appium/types": "^0.10.0",
"@appium/support": "^3.1.8",
"@appium/types": "^0.10.2",
"@colors/colors": "1.5.0",
"@types/async-lock": "1.4.0",
"@types/bluebird": "3.5.38",
@@ -60,12 +61,12 @@
"express": "4.18.2",
"http-status-codes": "2.2.0",
"lodash": "4.17.21",
"lru-cache": "7.17.0",
"lru-cache": "7.18.3",
"method-override": "3.0.0",
"morgan": "1.10.0",
"serve-favicon": "2.5.0",
"source-map-support": "0.5.21",
"type-fest": "3.6.0",
"type-fest": "3.7.1",
"validate.js": "0.13.1"
},
"engines": {
@@ -78,5 +79,8 @@
"gitHead": "84b211330dc84849af9cc1f3a5c5ad32e15b2e72",
"typedoc": {
"entryPoint": "./lib/index.js"
},
"tsd": {
"directory": "test/types"
}
}
@@ -0,0 +1,11 @@
import {expectAssignable} from 'tsd';
// NOTE: this pulls in the distfiles
import {BaseDriver} from '.../../..';
import {BaseDriverCapConstraints, ExternalDriver, Driver, DriverOpts} from '@appium/types';
expectAssignable<Driver<BaseDriverCapConstraints>>(
new BaseDriver({} as DriverOpts<BaseDriverCapConstraints>)
);
expectAssignable<ExternalDriver<BaseDriverCapConstraints>>(
new BaseDriver({} as DriverOpts<BaseDriverCapConstraints>)
);
@@ -1,7 +1,7 @@
// @ts-check
import {LogMixin} from '../../../../lib/basedriver/commands/log';
import {createSandbox} from 'sinon';
import _ from 'lodash';
import BaseDriver from '../../../../lib';
const expect = chai.expect;
@@ -20,25 +20,15 @@ const SUPPORTED_LOG_TYPES = {
describe('log commands -', function () {
let sandbox;
/** @type {ReturnType<typeof LogMixin>} */
let LogCommands;
let logCommands;
let driver;
beforeEach(function () {
sandbox = createSandbox();
// @ts-expect-error
LogCommands = LogMixin(
class {
get log() {
return this._log;
}
}
);
logCommands = new LogCommands();
driver = new BaseDriver();
// reset the supported log types
logCommands.supportedLogTypes = {};
logCommands._log = /** @type {import('@appium/types').AppiumLogger} */ ({
driver.supportedLogTypes = {};
driver._log = /** @type {import('@appium/types').AppiumLogger} */ ({
debug: _.noop,
});
});
@@ -49,11 +39,11 @@ describe('log commands -', function () {
describe('getLogTypes', function () {
it('should return empty array when no supported log types', async function () {
(await logCommands.getLogTypes()).should.eql([]);
(await driver.getLogTypes()).should.eql([]);
});
it('should return keys to log type object', async function () {
logCommands.supportedLogTypes = SUPPORTED_LOG_TYPES;
(await logCommands.getLogTypes()).should.eql(['one', 'two']);
driver.supportedLogTypes = SUPPORTED_LOG_TYPES;
(await driver.getLogTypes()).should.eql(['one', 'two']);
});
});
describe('getLog', function () {
@@ -66,15 +56,15 @@ describe('log commands -', function () {
two = sandbox.spy(SUPPORTED_LOG_TYPES.two, 'getter');
});
it('should throw error if log type not supported', async function () {
await logCommands.getLog('one').should.eventually.be.rejected;
await driver.getLog('one').should.eventually.be.rejected;
one.called.should.be.false;
two.called.should.be.false;
});
it('should throw an error with available log types if log type not supported', async function () {
logCommands.supportedLogTypes = SUPPORTED_LOG_TYPES;
driver.supportedLogTypes = SUPPORTED_LOG_TYPES;
let err;
try {
await logCommands.getLog('three');
await driver.getLog('three');
} catch (_err) {
err = _err;
}
@@ -86,8 +76,8 @@ describe('log commands -', function () {
two.called.should.be.false;
});
it('should call getter on appropriate log when found', async function () {
logCommands.supportedLogTypes = SUPPORTED_LOG_TYPES;
let logs = await logCommands.getLog('one');
driver.supportedLogTypes = SUPPORTED_LOG_TYPES;
let logs = await driver.getLog('one');
logs.should.eql(FIRST_LOGS);
one.called.should.be.true;
two.called.should.be.false;
+19
View File
@@ -3,6 +3,25 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [2.2.4](https://github.com/appium/appium/compare/@appium/base-plugin@2.2.3...@appium/base-plugin@2.2.4) (2023-03-28)
### Bug Fixes
* **base-driver,base-plugin,types:** update PluginCommand and DriverCommand types ([0dcd5fa](https://github.com/appium/appium/commit/0dcd5fa371af523c6527e55de4cff6cd472fde22))
## [2.2.3](https://github.com/appium/appium/compare/@appium/base-plugin@2.2.2...@appium/base-plugin@2.2.3) (2023-03-08)
**Note:** Version bump only for package @appium/base-plugin
## [2.2.2](https://github.com/appium/appium/compare/@appium/base-plugin@2.2.1...@appium/base-plugin@2.2.2) (2023-02-24)
**Note:** Version bump only for package @appium/base-plugin
+15 -11
View File
@@ -56,26 +56,26 @@ class BasePlugin {
* `next` and `driver` objects since naturally we'd want to make sure to trigger the driver's own
* `executeMethod` call if an execute method is not found on the plugin itself.
*
* @template {Driver} D
* @template {Constraints} C
* @param {NextPluginCallback} next
* @param {D} driver
* @param {Driver<C>} driver
* @param {string} script
* @param {[Record<string, any>]|[]} protoArgs
* @this {Plugin}
* @param {readonly [import('@appium/types').StringRecord<unknown>] | readonly any[]} protoArgs
*/
async executeMethod(next, driver, script, protoArgs) {
const Plugin = /** @type {PluginClass} */ (this.constructor);
const Plugin = /** @type {import('@appium/types').PluginClass<Plugin>} */ (this.constructor);
const commandMetadata = {...Plugin.executeMethodMap?.[script]};
/** @type {import('@appium/types').PluginCommand<D>|undefined} */
let command;
if (!commandMetadata.command || !(command = this[commandMetadata.command])) {
if (!commandMetadata.command || !(commandMetadata.command in this)) {
this.logger.info(
`Plugin did not know how to handle method '${script}'. Passing control to next`
);
return await next();
}
const command = /** @type {import('@appium/types').PluginCommand<Driver<C>>} */ (
this[commandMetadata.command]
);
const args = validateExecuteMethodParams(protoArgs, commandMetadata.params);
return await command.call(this, next, driver, ...args);
}
@@ -87,6 +87,10 @@ export {BasePlugin};
/**
* @typedef {import('@appium/types').Plugin} Plugin
* @typedef {import('@appium/types').NextPluginCallback} NextPluginCallback
* @typedef {import('@appium/types').Driver} Driver
* @typedef {import('@appium/types').PluginClass} PluginClass
* @typedef {import('@appium/types').Constraints} Constraints
*/
/**
* @template {Constraints} C
* @typedef {import('@appium/types').Driver<C>} Driver
*/
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/base-plugin",
"version": "2.2.2",
"version": "2.2.4",
"description": "The base plugin used to create Appium 2.0 plugins",
"keywords": [
"automation",
@@ -40,8 +40,8 @@
"test:unit": "mocha \"./test/unit/**/*.spec.js\""
},
"dependencies": {
"@appium/base-driver": "^9.3.2",
"@appium/support": "^3.1.6"
"@appium/base-driver": "^9.3.4",
"@appium/support": "^3.1.8"
},
"engines": {
"node": "^14.17.0 || ^16.13.0 || >=18.0.0",
+16
View File
@@ -3,6 +3,22 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [2.0.10](https://github.com/appium/appium/compare/@appium/doctor@2.0.9...@appium/doctor@2.0.10) (2023-03-28)
**Note:** Version bump only for package @appium/doctor
## [2.0.9](https://github.com/appium/appium/compare/@appium/doctor@2.0.8...@appium/doctor@2.0.9) (2023-03-08)
**Note:** Version bump only for package @appium/doctor
## [2.0.8](https://github.com/appium/appium/compare/@appium/doctor@2.0.7...@appium/doctor@2.0.8) (2023-02-24)
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@appium/doctor",
"version": "2.0.8",
"version": "2.0.10",
"description": "Test environment for fitness to run Appium",
"keywords": [
"automation",
@@ -44,7 +44,7 @@
"test:unit": "mocha \"./test/unit/**/*.spec.js\""
},
"dependencies": {
"@appium/support": "^3.1.6",
"@appium/support": "^3.1.8",
"@colors/colors": "1.5.0",
"@types/bluebird": "3.5.38",
"@types/teen_process": "2.0.0",
+37
View File
@@ -3,6 +3,43 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [0.3.1](https://github.com/appium/appium/compare/@appium/docutils@0.3.0...@appium/docutils@0.3.1) (2023-03-28)
### Bug Fixes
* backwards-compatible fixes for TS v5.x ([4974403](https://github.com/appium/appium/commit/49744036619ecc239e0e6255a13d38cafd709920))
* **docutils:** inherit stdio in long-running processes ([ad11fbf](https://github.com/appium/appium/commit/ad11fbf97b57a0c4302d37146660e87c564a5404))
* **docutils:** update dependency typedoc to v0.23.27 ([ef9cbe6](https://github.com/appium/appium/commit/ef9cbe6bcc27a3633eda01cd7c08a4466e304630))
* **docutils:** update dependency typedoc to v0.23.28 ([dbc0bf6](https://github.com/appium/appium/commit/dbc0bf69e855744ed69ff3b75a9981b313579fa2))
* **types:** update dependency type-fest to v3.7.0 ([6912fa1](https://github.com/appium/appium/commit/6912fa14f2a7d338f17e1bed060e959de7aba1d6))
* **types:** update dependency type-fest to v3.7.1 ([bc860c7](https://github.com/appium/appium/commit/bc860c733a73760f0c42cbfb384e04d50c376d5e))
# [0.3.0](https://github.com/appium/appium/compare/@appium/docutils@0.2.2...@appium/docutils@0.3.0) (2023-03-08)
### Bug Fixes
* **docutils:** update dependency lilconfig to v2.1.0 ([4ed745a](https://github.com/appium/appium/commit/4ed745a95ffc6a43f76003eba62019c16a4c6cf2))
* **docutils:** update dependency typedoc to v0.23.26 ([431092d](https://github.com/appium/appium/commit/431092dc87c3146bfd3cd274ae5c279b7582ff55))
* **docutils:** use material theme ([189e39d](https://github.com/appium/appium/commit/189e39d03c16551272d6c489aedc0d9fbb08a3a9))
* **types:** update dependency type-fest to v3.6.1 ([471a4b5](https://github.com/appium/appium/commit/471a4b57e622ff077d59f577a78341268700c48d))
### Features
* **docutils:** add --upgrade flag to init ([4cfad00](https://github.com/appium/appium/commit/4cfad004dbdff4ae04ed7c87f23a3c9e913e4d4e))
* **docutils:** allow "%s" as version number in commit msg arg ([f80f4cb](https://github.com/appium/appium/commit/f80f4cb2bca40347913a6ce39e3de58b485492a8))
* **docutils:** better path validation ([b30b2cf](https://github.com/appium/appium/commit/b30b2cfb84b0f208d932d60082847d0d7323e108))
## [0.2.2](https://github.com/appium/appium/compare/@appium/docutils@0.2.1...@appium/docutils@0.2.2) (2023-02-24)
+11 -8
View File
@@ -5,8 +5,8 @@
*/
import _ from 'lodash';
import {exec, SubProcess, TeenProcessExecOptions} from 'teen_process';
import path from 'node:path';
import {exec, TeenProcessExecOptions} from 'teen_process';
import {
DEFAULT_DEPLOY_BRANCH,
DEFAULT_DEPLOY_REMOTE,
@@ -18,7 +18,7 @@ import {
import {DocutilsError} from '../error';
import {findMkDocsYml, readPackageJson, whichMike} from '../fs';
import logger from '../logger';
import {argify, stopwatch, TeenProcessSubprocessStartOpts} from '../util';
import {argify, spawnBackgroundProcess, SpawnBackgroundProcessOpts, stopwatch} from '../util';
const log = logger.withTag('builder:deploy');
@@ -30,14 +30,12 @@ const log = logger.withTag('builder:deploy');
*/
async function doServe(
args: string[] = [],
{startDetector, detach, timeoutMs}: TeenProcessSubprocessStartOpts = {},
opts: SpawnBackgroundProcessOpts = {},
mikePath?: string
) {
mikePath = mikePath ?? (await whichMike());
const finalArgs = ['serve', ...args];
log.debug('Launching %s with args: %O', mikePath, finalArgs);
const proc = new SubProcess(mikePath, finalArgs);
return await proc.start(startDetector, detach, timeoutMs);
return spawnBackgroundProcess(mikePath, finalArgs, opts);
}
/**
@@ -99,6 +97,10 @@ export async function deploy({
);
}
version = version ?? (await findDeployVersion(packageJsonPath, cwd));
// substitute %s in message with version
message = message?.replace('%s', version);
const mikeOpts = {
'config-file': mkDocsYmlPath,
push,
@@ -118,6 +120,7 @@ export async function deploy({
if (alias) {
mikeArgs.push(alias);
}
stop(); // discard
// unsure about how SIGHUP is handled here
await doServe(mikeArgs, serveOpts);
} else {
@@ -217,7 +220,7 @@ export interface DeployOpts {
execOpts?: TeenProcessExecOptions;
/**
* Extra options for {@linkcode teen_process.Subprocess.start}
* Extra options for {@linkcode spawnBackgroundProcess}
*/
serveOpts?: TeenProcessSubprocessStartOpts;
serveOpts?: SpawnBackgroundProcessOpts;
}
+5
View File
@@ -1,3 +1,8 @@
/**
* Exports APIs used by build-related commands
* @module
*/
export * from './deploy';
export * from './site';
export * from './reference';
+2 -3
View File
@@ -197,7 +197,7 @@ async function getNavItemsForDir(
const rootHeaderKeypath = getRootHeaderKeypath(navHeaderItems, navHeader);
for (const fileOrUrl of referenceOutputFilepaths) {
let offset = navHeaderItems.findIndex((item) => item.fileOrUrl === fileOrUrl);
const offset = navHeaderItems.findIndex((item) => item.fileOrUrl === fileOrUrl);
const newOffset = offset >= 0 ? offset : navHeaderItems.length;
const data = navHeaderItems[offset];
log.warn(rootHeaderKeypath, newOffset, data);
@@ -214,7 +214,7 @@ async function getNavItemsForDir(
}
} else {
log.debug('No items found in header %s', navHeader);
let navOffset = nav.length;
const navOffset = nav.length;
for (const [idx, newRefFilepath] of referenceOutputFilepaths.entries()) {
newNavHeaderItems.push({
keypath: `${navOffset}.${navHeader}.${idx}`,
@@ -254,7 +254,6 @@ export async function updateNav({
mkdocsYml: mkDocsYmlPath,
typedocJson: typeDocJsonPath,
all = false,
dryRun = false,
}: UpdateNavOpts = {}) {
// we need `mkdocs.yml` to update
// and we need `typedoc.json` to know where to look for the command docs
+2 -22
View File
@@ -5,7 +5,6 @@
*/
import {fs} from '@appium/support';
import glob from 'glob';
import _ from 'lodash';
import path from 'node:path';
import {Application, ArgumentsReader, TypeDocOptions, TypeDocReader} from 'typedoc';
@@ -16,28 +15,12 @@ import {
NAME_TYPEDOC_JSON,
} from '../constants';
import {DocutilsError} from '../error';
import {findPkgDir, findTypeDocJsonPath, readTypedocJson} from '../fs';
import {findTypeDocJsonPath, readTypedocJson} from '../fs';
import logger from '../logger';
import {argify, relative, stopwatch} from '../util';
const log = logger.withTag('builder:reference');
/**
* Replaces TypeDoc's homebrew "glob" implementation with a real one
*
* This cannot be done via `require('typedoc')` or `import` due to the file being excluded
* from the export map in its `package.json`.
* @see https://github.com/TypeStrong/typedoc/issues/2151
*/
const monkeyPatchTypedoc = _.once(async () => {
const typedocDir = await findPkgDir(require.resolve('typedoc'));
if (!typedocDir) {
throw new DocutilsError('Could not find TypeDoc package directory; is it installed?');
}
const tdFs = require(path.join(typedocDir, 'dist', 'lib', 'utils', 'fs.js'));
tdFs.glob = glob.sync;
});
/**
* Executes TypeDoc _in the current process_
*
@@ -48,9 +31,6 @@ const monkeyPatchTypedoc = _.once(async () => {
* @param opts - TypeDoc options
*/
export async function runTypedoc(typeDocJsonPath: string, opts: Record<string, string>) {
await monkeyPatchTypedoc();
log.debug('Monkeypatched TypeDoc');
const args = argify(opts);
log.debug('TypeDoc args:', args);
const app = new Application();
@@ -179,7 +159,7 @@ export async function buildReferenceDocs({
try {
await runTypedoc(typeDocJsonPath, extraTypedocOpts);
let finalOut = (typeDocJson.out ?? out) as string;
const finalOut = (typeDocJson.out ?? out) as string;
log.success(
'Reference docs built at %s (%dms)',
path.isAbsolute(finalOut) ? relativePath(finalOut) : finalOut,
+11 -10
View File
@@ -5,13 +5,14 @@
* @module
*/
import {spawn, SpawnOptions} from 'node:child_process';
import path from 'node:path';
import {exec, SubProcess, TeenProcessExecOptions} from 'teen_process';
import {NAME_BIN, NAME_MKDOCS, NAME_MKDOCS_YML} from '../constants';
import {exec, TeenProcessExecOptions} from 'teen_process';
import {NAME_BIN, NAME_MKDOCS, NAME_MKDOCS_YML, NAME_THEME} from '../constants';
import {DocutilsError} from '../error';
import {findMkDocsYml, readMkDocsYml, whichMkDocs} from '../fs';
import logger from '../logger';
import {relative, stopwatch, TeenProcessSubprocessStartOpts} from '../util';
import {relative, spawnBackgroundProcess, SpawnBackgroundProcessOpts, stopwatch} from '../util';
const log = logger.withTag('mkdocs');
@@ -23,14 +24,14 @@ const log = logger.withTag('mkdocs');
*/
async function doServe(
args: string[] = [],
{startDetector, detach, timeoutMs}: TeenProcessSubprocessStartOpts = {},
opts: SpawnBackgroundProcessOpts = {},
mkDocsPath?: string
) {
mkDocsPath = mkDocsPath ?? (await whichMkDocs());
const finalArgs = ['serve', ...args];
log.debug('Launching %s with args: %O', mkDocsPath, finalArgs);
const proc = new SubProcess(mkDocsPath, finalArgs);
return await proc.start(startDetector, detach, timeoutMs);
log.debug('Launching %s with args: %s', mkDocsPath, finalArgs);
return spawnBackgroundProcess(mkDocsPath, finalArgs, opts);
}
/**
@@ -57,7 +58,7 @@ async function doBuild(
export async function buildSite({
mkdocsYml: mkDocsYmlPath,
siteDir,
theme = NAME_MKDOCS,
theme = NAME_THEME,
cwd = process.cwd(),
serve = false,
serveOpts,
@@ -137,7 +138,7 @@ export interface BuildMkDocsOpts {
execOpts?: TeenProcessExecOptions;
/**
* Extra options for {@linkcode teen_process.Subprocess.start}
* Extra options for {@linkcode spawnBackgroundProcess}
*/
serveOpts?: TeenProcessSubprocessStartOpts;
serveOpts?: SpawnBackgroundProcessOpts;
}
+87
View File
@@ -0,0 +1,87 @@
/**
* Provides functions to validate user-provided options as part of Yargs' post-parsing "check" phase
* @module
*/
import {fs, util} from '@appium/support';
import _ from 'lodash';
import type {Options} from 'yargs';
import logger from '../logger';
const log = logger.withTag('check');
/**
* Given a list of objects with `id` and `path` props, filters out the ones that do not exist
* @param paths Filepaths
* @returns Missing files
*/
async function filterMissing(paths: MissingFileData[]): Promise<MissingFileData[]> {
const exists = await Promise.all(
paths.map(async ({id, path}) => ({id, path, exists: await fs.exists(path)}))
);
const results = _.reject(exists, 'exists');
return _.map(results, (result) => _.omit(result, 'exists'));
}
/**
* Data structure describing a missing file; returned by {@linkcode filterMissing}
*/
interface MissingFileData {
/**
* Arbitrary identifier; intent was to map to an option name
*/
id: string;
/**
* Normalized filepath
*/
path: string;
}
/**
* Takes user-provided paths and checks for existence.
*
* Filters options to consider based on group name only.
*
* Meant to be used as a "fail-fast" strategy on the CLI, so we don't go all the way through some
* expensive behavior before realizing we're missing a path.
* @param opts Options object for a yargs command
* @param group Group name to filter on
* @param argv User-provided args
* @returns `true` if all paths exist or otherwise an error message
*/
export async function checkMissingPaths<T extends Record<string, Options>>(
opts: T,
group: string,
argv: Record<string, unknown>
): Promise<true | string> {
const argsToCheck = _.keys(
_.pickBy(opts, (opt: Options, id: string) => opt?.group === group && id in argv) as Partial<T>
);
// yargs is pretty loose about allowing CLI args multiple times, and the value could potentially
// be a `string[]` instead of `string`; we don't want to allow more than one path per arg.
if (!argsToCheck.every((id) => _.isString(argv[id]))) {
return 'Paths may only be provided once each';
}
const pathsToCheck: MissingFileData[] = _.map(argsToCheck, (id) => ({
id,
path: String(argv[id]), // this must be a string per the above check
}));
log.debug(
'Checking for existence of %s: %s',
util.pluralize('path', pathsToCheck.length),
_.map(pathsToCheck, 'path')
);
const missingPaths = await filterMissing(pathsToCheck);
if (missingPaths.length) {
return missingPaths
.map(({id, path}) => `Path specified using --${_.kebabCase(id)} (${path}) does not exist`)
.join('\n');
}
return true;
}
+61 -43
View File
@@ -1,53 +1,64 @@
import {CommandModule, InferredOptionTypes, Options} from 'yargs';
/**
* Yargs command module for the `build` command.
* @module
*/
import path from 'node:path';
import type {CommandModule, InferredOptionTypes, Options} from 'yargs';
import {buildReferenceDocs, buildSite, deploy, updateNav} from '../../builder';
import {NAME_BIN} from '../../constants';
import logger from '../../logger';
import {stopwatch} from '../../util';
import {checkMissingPaths} from '../check';
const log = logger.withTag('build');
const NAME_GROUP_BUILD = 'Build Options:';
const NAME_GROUP_DEPLOY = 'Deployment Options:';
const NAME_GROUP_SERVE = 'Serve Options:';
const NAME_GROUP_BUILD_PATHS = 'Paths:';
enum BuildCommandGroup {
Build = 'Build Config:',
Deploy = 'Deployment Config:',
Serve = 'Dev Server Config:',
BuildPaths = 'Custom Paths:',
}
const opts = Object.freeze({
const opts = {
reference: {
describe: 'Run TypeDoc command API reference build (Markdown)',
group: NAME_GROUP_BUILD,
group: BuildCommandGroup.Build,
type: 'boolean',
default: true,
},
site: {
describe: 'Run MkDocs build (HTML)',
group: NAME_GROUP_BUILD,
group: BuildCommandGroup.Build,
type: 'boolean',
default: true,
},
'site-dir': {
alias: 'd',
describe: 'HTML output directory',
group: NAME_GROUP_BUILD_PATHS,
group: BuildCommandGroup.Build,
nargs: 1,
requiresArg: true,
type: 'string',
normalize: true,
coerce: path.resolve,
implies: 'site',
defaultDescription: '(from mkdocs.yml)',
},
'package-json': {
defaultDescription: './package.json',
describe: 'Path to package.json',
group: NAME_GROUP_BUILD_PATHS,
group: BuildCommandGroup.BuildPaths,
nargs: 1,
normalize: true,
coerce: path.resolve,
requiresArg: true,
type: 'string',
},
title: {
defaultDescription: '(extension package name)',
describe: 'Title of the API reference',
group: NAME_GROUP_BUILD,
group: BuildCommandGroup.Build,
nargs: 1,
requiresArg: true,
type: 'string',
@@ -55,45 +66,48 @@ const opts = Object.freeze({
'tsconfig-json': {
defaultDescription: './tsconfig.json',
describe: 'Path to tsconfig.json',
group: NAME_GROUP_BUILD_PATHS,
group: BuildCommandGroup.BuildPaths,
nargs: 1,
normalize: true,
requiresArg: true,
coerce: path.resolve,
type: 'string',
},
'mkdocs-yml': {
defaultDescription: './mkdocs.yml',
description: 'Path to mkdocs.yml',
group: NAME_GROUP_BUILD_PATHS,
group: BuildCommandGroup.BuildPaths,
nargs: 1,
normalize: true,
requiresArg: true,
coerce: path.resolve,
type: 'string',
},
'typedoc-json': {
defaultDescription: './typedoc.json',
describe: 'Path to typedoc.json',
group: NAME_GROUP_BUILD_PATHS,
group: BuildCommandGroup.BuildPaths,
nargs: 1,
normalize: true,
requiresArg: true,
coerce: path.resolve,
type: 'string',
},
all: {
describe: 'Output all reference docs (not just Appium comands)',
group: NAME_GROUP_BUILD,
group: BuildCommandGroup.Build,
implies: 'site',
type: 'boolean',
},
deploy: {
describe: 'Commit HTML output',
group: NAME_GROUP_DEPLOY,
describe: 'Commit HTML output to a branch using mike',
group: BuildCommandGroup.Deploy,
type: 'boolean',
implies: 'site',
},
push: {
describe: 'Push after deploy',
group: NAME_GROUP_DEPLOY,
group: BuildCommandGroup.Deploy,
type: 'boolean',
implies: 'deploy',
},
@@ -101,7 +115,7 @@ const opts = Object.freeze({
alias: 'b',
describe: 'Branch to commit to',
implies: 'deploy',
group: NAME_GROUP_DEPLOY,
group: BuildCommandGroup.Deploy,
type: 'string',
requiresArg: true,
nargs: 1,
@@ -111,7 +125,7 @@ const opts = Object.freeze({
alias: 'r',
describe: 'Remote to push to',
implies: ['deploy', 'push'],
group: NAME_GROUP_DEPLOY,
group: BuildCommandGroup.Deploy,
type: 'string',
requiresArg: true,
nargs: 1,
@@ -120,16 +134,16 @@ const opts = Object.freeze({
prefix: {
describe: 'Subdirectory within <branch> to commit to',
implies: ['deploy', 'branch'],
group: NAME_GROUP_DEPLOY,
group: BuildCommandGroup.Deploy,
type: 'string',
nargs: 1,
requiresArg: true,
},
message: {
alias: 'm',
describe: 'Commit message',
describe: 'Commit message. Use "%s" for version placeholder',
implies: 'deploy',
group: NAME_GROUP_DEPLOY,
group: BuildCommandGroup.Deploy,
type: 'string',
nargs: 1,
requiresArg: true,
@@ -137,7 +151,7 @@ const opts = Object.freeze({
'deploy-version': {
describe: 'Version (directory) to deploy build to',
implies: 'deploy',
group: NAME_GROUP_DEPLOY,
group: BuildCommandGroup.Deploy,
type: 'string',
nargs: 1,
requiresArg: true,
@@ -146,7 +160,7 @@ const opts = Object.freeze({
alias: {
describe: 'Alias for the build (e.g., "latest"); triggers alias update',
implies: 'deploy',
group: NAME_GROUP_DEPLOY,
group: BuildCommandGroup.Deploy,
type: 'string',
nargs: 1,
requiresArg: true,
@@ -155,18 +169,18 @@ const opts = Object.freeze({
rebase: {
describe: 'Rebase <branch> with remote before deploy',
implies: ['deploy', 'branch', 'remote'],
group: NAME_GROUP_DEPLOY,
group: BuildCommandGroup.Deploy,
type: 'boolean',
},
serve: {
describe: 'Start development server',
group: NAME_GROUP_SERVE,
group: BuildCommandGroup.Serve,
type: 'boolean',
},
port: {
alias: 'p',
describe: 'Development server port',
group: NAME_GROUP_SERVE,
group: BuildCommandGroup.Serve,
type: 'number',
defaultDescription: '8000',
implies: 'serve',
@@ -176,31 +190,35 @@ const opts = Object.freeze({
host: {
alias: 'h',
describe: 'Development server host',
group: NAME_GROUP_SERVE,
group: BuildCommandGroup.Serve,
type: 'string',
nargs: 1,
requiresArg: true,
implies: 'serve',
defaultDescription: 'localhost',
},
}) satisfies Record<string, Options>;
} as const satisfies Record<string, Options>;
type BuildOptions = InferredOptionTypes<typeof opts>;
export default {
command: 'build',
describe: 'Build Appium extension documentation',
builder: (yargs) =>
yargs.options(opts).check((argv) => {
// either this method doesn't provide camel-cased props, or the types are wrong.
if (argv.deploy === true && argv['site-dir']) {
log.error(
`--site-dir is unsupported when running "${NAME_BIN} deploy"; use --prefix if needd, but remember that the default behavior is to deploy to the root of the branch (${argv.branch}) instead of a subdirectory`
);
return false;
}
return true;
}),
describe: 'Build Appium extension documentation using TypeDoc & MkDocs',
builder(yargs) {
return yargs
.options(opts)
.check(async (argv) => {
// either this method doesn't provide camel-cased props, or the types are wrong.
if (argv.deploy === true && argv['site-dir']) {
return `--site-dir is unsupported when running "${NAME_BIN} deploy"; use --prefix if needed, but remember that the default behavior is to deploy to the root of the branch (${argv.branch}) instead of a subdirectory`;
}
return await checkMissingPaths(opts, BuildCommandGroup.BuildPaths, argv);
})
.epilog(
'For help with further configuration, see:\n - MkDocs: https://www.mkdocs.org\n - TypeDoc: https://typedoc.org\n - Mike: https://github.com/jimporter/mike'
);
},
async handler(args) {
const stop = stopwatch('build');
log.debug('Build command called with args: %O', args);
@@ -223,4 +241,4 @@ export default {
}
log.success('Done! (total: %dms)', stop());
},
} as CommandModule<{}, BuildOptions>;
} as CommandModule<object, BuildOptions>;
@@ -1,3 +1,8 @@
/**
* Exports all command modules
* @module
*/
export {default as init} from './init';
export {default as validate} from './validate';
export {default as build} from './build';
+54 -29
View File
@@ -1,19 +1,32 @@
/**
* Yargs command module for the `init` command.
* @module
*/
import _ from 'lodash';
import {CommandModule, InferredOptionTypes, Options} from 'yargs';
import type {CommandModule, InferredOptionTypes, Options} from 'yargs';
import {init} from '../../init';
import logger from '../../logger';
import {stopwatch} from '../../util';
import {checkMissingPaths} from '../check';
const log = logger.withTag('init');
const NAME_GROUP_INIT_MKDOCS = 'MkDocs Config:';
const NAME_GROUP_INIT_PATHS = 'Paths:';
const NAME_GROUP_INIT_BEHAVIOR = 'Initialization Behavior:';
enum InitCommandGroup {
MkDocs = 'MkDocs Config:',
Paths = 'Custom Paths:',
Behavior = 'Initialization Behavior:',
}
const opts = Object.freeze({
/**
* Note the groups here; _some_ opts are paths and would usually be checked via
* {@linkcode checkMissingPaths}, but in this case we do not care if the path exists or not, because
* we may create it.
*/
const opts = {
copyright: {
description: 'Copyright notice',
group: NAME_GROUP_INIT_MKDOCS,
group: InitCommandGroup.MkDocs,
nargs: 1,
requiresArg: true,
type: 'string',
@@ -22,19 +35,19 @@ const opts = Object.freeze({
default: '.',
defaultDescription: '(current directory)',
description: 'Directory of package',
group: NAME_GROUP_INIT_PATHS,
group: InitCommandGroup.Paths,
normalize: true,
type: 'string',
},
'dry-run': {
describe: 'Do not write any files; show what would be done',
group: NAME_GROUP_INIT_BEHAVIOR,
group: InitCommandGroup.Behavior,
type: 'boolean',
},
force: {
alias: 'f',
describe: 'Overwrite existing configurations',
group: NAME_GROUP_INIT_BEHAVIOR,
group: InitCommandGroup.Behavior,
type: 'boolean',
},
include: {
@@ -43,19 +56,20 @@ const opts = Object.freeze({
coerce: (value: string | string[]) => _.castArray(value),
description: 'Files to include in compilation (globs OK)',
nargs: 1,
group: InitCommandGroup.MkDocs,
requiresArg: true,
type: 'string',
},
mkdocs: {
default: true,
description: 'Create mkdocs.yml if needed',
group: NAME_GROUP_INIT_BEHAVIOR,
group: InitCommandGroup.Behavior,
type: 'boolean',
},
'mkdocs-yml': {
defaultDescription: './mkdocs.yml',
description: 'Path to mkdocs.yml',
group: NAME_GROUP_INIT_PATHS,
description: 'Path to new or existing mkdocs.yml',
group: InitCommandGroup.MkDocs,
nargs: 1,
normalize: true,
requiresArg: true,
@@ -63,8 +77,8 @@ const opts = Object.freeze({
},
'package-json': {
defaultDescription: './package.json',
describe: 'Path to package.json',
group: NAME_GROUP_INIT_PATHS,
describe: 'Path to existing package.json',
group: InitCommandGroup.Paths,
nargs: 1,
normalize: true,
requiresArg: true,
@@ -73,13 +87,13 @@ const opts = Object.freeze({
python: {
default: true,
description: 'Install Python dependencies if needed',
group: NAME_GROUP_INIT_BEHAVIOR,
group: InitCommandGroup.Behavior,
type: 'boolean',
},
'python-path': {
defaultDescription: '(derived from shell)',
description: 'Path to python 3 executable',
group: NAME_GROUP_INIT_PATHS,
group: InitCommandGroup.Paths,
nargs: 1,
normalize: true,
requiresArg: true,
@@ -88,7 +102,7 @@ const opts = Object.freeze({
'repo-name': {
defaultDescription: '(derived from --repo-url)',
description: 'Name of extension repository',
group: NAME_GROUP_INIT_MKDOCS,
group: InitCommandGroup.MkDocs,
nargs: 1,
requiresArg: true,
type: 'string',
@@ -96,7 +110,7 @@ const opts = Object.freeze({
'repo-url': {
defaultDescription: '(from package.json)',
description: 'URL of extension repository',
group: NAME_GROUP_INIT_MKDOCS,
group: InitCommandGroup.MkDocs,
nargs: 1,
requiresArg: true,
type: 'string',
@@ -104,7 +118,7 @@ const opts = Object.freeze({
'site-description': {
defaultDescription: '(from package.json)',
description: 'Site description',
group: NAME_GROUP_INIT_MKDOCS,
group: InitCommandGroup.MkDocs,
nargs: 1,
requiresArg: true,
type: 'string',
@@ -112,15 +126,15 @@ const opts = Object.freeze({
'site-name': {
defaultDescription: '(extension package name)',
description: 'Name of site',
group: NAME_GROUP_INIT_MKDOCS,
group: InitCommandGroup.MkDocs,
nargs: 1,
requiresArg: true,
type: 'string',
},
'tsconfig-json': {
defaultDescription: './tsconfig.json',
describe: 'Path to tsconfig.json',
group: NAME_GROUP_INIT_PATHS,
describe: 'Path to new or existing tsconfig.json',
group: InitCommandGroup.Behavior,
nargs: 1,
normalize: true,
requiresArg: true,
@@ -129,13 +143,13 @@ const opts = Object.freeze({
typedoc: {
default: true,
description: 'Create typedoc.json if needed',
group: NAME_GROUP_INIT_BEHAVIOR,
group: InitCommandGroup.Behavior,
type: 'boolean',
},
'typedoc-json': {
defaultDescription: './typedoc.json',
describe: 'Path to typedoc.json',
group: NAME_GROUP_INIT_PATHS,
describe: 'Path to new or existing typedoc.json',
group: InitCommandGroup.Behavior,
nargs: 1,
normalize: true,
requiresArg: true,
@@ -144,20 +158,31 @@ const opts = Object.freeze({
typescript: {
default: true,
description: 'Create tsconfig.json if needed',
group: NAME_GROUP_INIT_BEHAVIOR,
group: InitCommandGroup.Behavior,
type: 'boolean',
},
}) satisfies Record<string, Options>;
upgrade: {
alias: 'up',
describe: 'Only upgrade Python dependencies if out-of-date',
group: InitCommandGroup.Behavior,
type: 'boolean',
conflicts: 'force',
},
} as const satisfies Record<string, Options>;
type InitOptions = InferredOptionTypes<typeof opts>;
export default {
command: 'init',
describe: 'Initialize package for doc generation',
builder: opts,
builder(yargs) {
return yargs
.options(opts)
.check(async (argv) => checkMissingPaths(opts, InitCommandGroup.Paths, argv));
},
async handler(args) {
const done = stopwatch('init');
await init({...args, overwrite: args.force, cwd: args.dir});
log.success('Done (%dms)', done());
},
} as CommandModule<{}, InitOptions>;
} as CommandModule<object, InitOptions>;
+33 -25
View File
@@ -1,25 +1,33 @@
import pluralize from 'pluralize';
import {CommandModule, InferredOptionTypes, Options} from 'yargs';
/**
* Yargs command module for the `validate` command.
* @module
*/
import {util} from '@appium/support';
import type {CommandModule, InferredOptionTypes, Options} from 'yargs';
import {DocutilsError} from '../../error';
import {DocutilsValidator, ValidationKind} from '../../validate';
import logger from '../../logger';
import {checkMissingPaths} from '../check';
const log = logger.withTag('validate');
const NAME_GROUP_VALIDATE = 'Validation Behavior:';
const NAME_GROUP_VALIDATE_PATHS = 'Paths:';
enum ValidateCommandGroup {
Behavior = 'Validation Behavior:',
Paths = 'Custom Paths:',
}
const opts = Object.freeze({
const opts = {
mkdocs: {
default: true,
description: 'Validate MkDocs environment',
group: NAME_GROUP_VALIDATE,
group: ValidateCommandGroup.Behavior,
type: 'boolean',
},
'mkdocs-yml': {
defaultDescription: './mkdocs.yml',
description: 'Path to mkdocs.yml',
group: NAME_GROUP_VALIDATE_PATHS,
group: ValidateCommandGroup.Paths,
nargs: 1,
normalize: true,
requiresArg: true,
@@ -28,7 +36,7 @@ const opts = Object.freeze({
'npm-path': {
defaultDescription: '(derived from shell)',
description: 'Path to npm executable',
group: NAME_GROUP_VALIDATE_PATHS,
group: ValidateCommandGroup.Paths,
nargs: 1,
normalize: true,
requiresArg: true,
@@ -37,13 +45,13 @@ const opts = Object.freeze({
python: {
default: true,
description: 'Validate Python 3 environment',
group: NAME_GROUP_VALIDATE,
group: ValidateCommandGroup.Behavior,
type: 'boolean',
},
'python-path': {
defaultDescription: '(derived from shell)',
description: 'Path to python 3 executable',
group: NAME_GROUP_VALIDATE_PATHS,
group: ValidateCommandGroup.Paths,
nargs: 1,
normalize: true,
requiresArg: true,
@@ -52,7 +60,7 @@ const opts = Object.freeze({
'tsconfig-json': {
defaultDescription: './tsconfig.json',
describe: 'Path to tsconfig.json',
group: NAME_GROUP_VALIDATE_PATHS,
group: ValidateCommandGroup.Paths,
nargs: 1,
normalize: true,
requiresArg: true,
@@ -61,13 +69,13 @@ const opts = Object.freeze({
typedoc: {
default: true,
description: 'Validate TypoDoc environment',
group: NAME_GROUP_VALIDATE,
group: ValidateCommandGroup.Behavior,
type: 'boolean',
},
'typedoc-json': {
defaultDescription: './typedoc.json',
describe: 'Path to typedoc.json',
group: NAME_GROUP_VALIDATE_PATHS,
group: ValidateCommandGroup.Paths,
nargs: 1,
normalize: true,
requiresArg: true,
@@ -76,25 +84,25 @@ const opts = Object.freeze({
typescript: {
default: true,
description: 'Validate TypeScript environment',
group: NAME_GROUP_VALIDATE,
group: ValidateCommandGroup.Behavior,
type: 'boolean',
},
}) satisfies Record<string, Options>;
} as const satisfies Record<string, Options>;
type ValidateOptions = InferredOptionTypes<typeof opts>;
export default {
command: 'validate',
describe: 'Validate Environment',
builder: opts,
builder(yargs) {
return yargs.options(opts).check(async (argv) => {
if (!argv.python && !argv.typedoc && !argv.typescript && !argv.mkdocs) {
return 'No validation targets specified; one or more of --python, --typescript, --typedoc or --mkdocs must be provided';
}
return checkMissingPaths(opts, ValidateCommandGroup.Paths, argv);
});
},
async handler(args) {
if (!args.python && !args.typedoc && !args.typescript && !args.mkdocs) {
// specifically not a DocutilsError
throw new Error(
'No validation targets specified; one or more of --python, --typescript, --typedoc or --mkdocs must be provided'
);
}
let errorCount = 0;
const validator = new DocutilsValidator(args)
.once(DocutilsValidator.BEGIN, (kinds: ValidationKind[]) => {
@@ -114,8 +122,8 @@ export default {
if (errorCount) {
throw new DocutilsError(
`Validation failed with ${errorCount} ${pluralize('error', errorCount)}`
`Validation failed with ${errorCount} ${util.pluralize('error', errorCount)}`
);
}
},
} as CommandModule<{}, ValidateOptions>;
} as CommandModule<object, ValidateOptions>;
+23 -4
View File
@@ -1,4 +1,11 @@
#!/usr/bin/env node
/* eslint-disable no-console */
/**
* Main CLI entry point for `@appium/docutils`
* @module
*/
import logger from '../logger';
import _ from 'lodash';
@@ -8,6 +15,10 @@ import {DEFAULT_LOG_LEVEL, LogLevelMap, NAME_BIN} from '../constants';
import {DocutilsError} from '../error';
import {build, init, validate} from './command';
import {findConfig} from './config';
import {fs} from '@appium/support';
import {sync as readPkg} from 'read-pkg';
const pkg = readPkg({cwd: fs.findRoot(__dirname)});
const log = logger.withTag('cli');
export async function main(argv = hideBin(process.argv)) {
@@ -45,7 +56,7 @@ export async function main(argv = hideBin(process.argv)) {
describe: 'Disable config file discovery',
},
})
.middleware(
.middleware([
/**
* Configures logging; `--verbose` implies `--log-level=debug`
*/
@@ -55,8 +66,15 @@ export async function main(argv = hideBin(process.argv)) {
log.debug('Debug logging enabled via --verbose');
}
log.level = LogLevelMap[argv.logLevel];
}
)
},
/**
* Writes a startup message, if logging is enabled
*/
async () => {
log.info(`${pkg.name} @ v${pkg.version} (Node.js ${process.version})`);
},
])
.epilog(`Please report bugs at ${pkg.bugs?.url}`)
.fail(
/**
* Custom failure handler so we can log nicely.
@@ -67,6 +85,7 @@ export async function main(argv = hideBin(process.argv)) {
log.error(error.message);
} else {
y.showHelp();
console.log();
log.error(msg ?? error.message);
}
y.exit(1, error);
@@ -81,7 +100,7 @@ export async function main(argv = hideBin(process.argv)) {
}
if (require.main === module) {
// eslint-disable-next-line promise/prefer-await-to-then
// eslint-disable-next-line promise/prefer-await-to-then, promise/prefer-await-to-callbacks
main().catch((err) => {
log.error('Caught otherwise-unhandled rejection (this is probably a bug):', err);
});
+5
View File
@@ -86,6 +86,11 @@ export const NAME_ERR_ENOENT = 'ENOENT';
*/
export const NAME_ERR_EEXIST = 'EEXIST';
/**
* Name of the default theme
*/
export const NAME_THEME = 'material';
/**
* Default log level
*/
+6
View File
@@ -1 +1,7 @@
/**
* A custom error class. This exists so we can use `instanceof` to differentiate between "expected"
* exceptions and unexpected ones.
* @module
*/
export class DocutilsError extends Error {}
+6 -3
View File
@@ -127,7 +127,10 @@ async function _readPkgJson(
cwd: string,
normalize: true
): Promise<{pkgPath: string; pkg: NormalizedPackageJson}>;
async function _readPkgJson(cwd: string): Promise<{pkgPath: string; pkg: PackageJson}>;
async function _readPkgJson(
cwd: string,
normalize?: false
): Promise<{pkgPath: string; pkg: PackageJson}>;
async function _readPkgJson(
cwd: string,
normalize?: boolean
@@ -236,14 +239,14 @@ export const whichMike = _.partial(cachedWhich, NAME_MIKE);
*/
export const readMkDocsYml = _.memoize(
async (filepath: string, cwd = process.cwd()): Promise<MkDocsYml> => {
let mkDocsYml = <MkDocsYml>await readYaml(filepath);
let mkDocsYml = (await readYaml(filepath)) as MkDocsYml;
if (mkDocsYml.site_dir) {
mkDocsYml.site_dir = path.resolve(cwd, path.dirname(filepath), mkDocsYml.site_dir);
}
if (mkDocsYml.INHERIT) {
let inheritPath: string | undefined = path.resolve(path.dirname(filepath), mkDocsYml.INHERIT);
while (inheritPath) {
const inheritYml = <MkDocsYml>await readYaml(inheritPath);
const inheritYml = (await readYaml(inheritPath)) as MkDocsYml;
if (inheritYml.site_dir) {
inheritYml.site_dir = path.resolve(path.dirname(inheritPath), inheritYml.site_dir);
log.debug('Resolved site_dir to %s', inheritYml.site_dir);
+5
View File
@@ -1,3 +1,8 @@
/**
* Main entry point
* @module
*/
export * from './mike';
export * from './builder';
export * from './validate';
+23 -6
View File
@@ -126,7 +126,9 @@ export const initMkDocs = createScaffoldTask<InitMkDocsOptions, MkDocsYml>(
if (repoUrl && !repoName) {
let {pathname} = new URL(repoUrl);
pathname = pathname.slice(1);
let [owner, repo] = pathname.split('/');
const pathparts = pathname.split('/');
const owner = pathparts[0];
let repo = pathparts[1];
repo = repo.replace(/\.git$/, '');
repoName = [owner, repo].join('/');
if (repoName) {
@@ -158,8 +160,12 @@ export const initMkDocs = createScaffoldTask<InitMkDocsOptions, MkDocsYml>(
export async function initPython({
pythonPath = NAME_PYTHON,
dryRun = false,
upgrade = false,
}: InitPythonOptions = {}): Promise<void> {
const args = ['-m', 'pip', 'install', '-r', REQUIREMENTS_TXT_PATH];
if (upgrade) {
args.push('--upgrade');
}
if (dryRun) {
dryRunLog.info('Would execute command: %s %s', pythonPath, args.join(' '));
} else {
@@ -214,6 +220,7 @@ export async function init({
dryRun,
cwd,
pythonPath,
upgrade,
typedocJson: typeDocJsonPath,
}: InitOptions = {}): Promise<void> {
if (!typescript && typedoc) {
@@ -222,7 +229,7 @@ export async function init({
);
}
if (typescript) {
if (typescript && !upgrade) {
await initTsConfigJson({
dest: tsconfigJsonPath,
packageJson: packageJsonPath,
@@ -233,7 +240,7 @@ export async function init({
});
}
if (typedoc) {
if (typedoc && !upgrade) {
await initTypeDocJson({
dest: typeDocJsonPath,
packageJson: packageJsonPath,
@@ -244,10 +251,10 @@ export async function init({
}
if (python) {
await initPython({pythonPath, dryRun});
await initPython({pythonPath, dryRun, upgrade});
}
if (mkdocs) {
if (mkdocs && !upgrade) {
await initMkDocs({
dest: mkdocsYmlPath,
cwd,
@@ -262,7 +269,7 @@ export async function init({
}
}
export interface InitTypeDocOptions extends ScaffoldTaskOptions {}
export type InitTypeDocOptions = ScaffoldTaskOptions;
export interface InitTsConfigOptions extends ScaffoldTaskOptions {
/**
* List of source files (globs supported); typically `src` or `lib`
@@ -274,6 +281,11 @@ export interface InitPythonOptions extends ScaffoldTaskOptions {
* Path to `python` (v3.x) executable
*/
pythonPath?: string;
/**
* If true, upgrade only
*/
upgrade?: boolean;
}
/**
@@ -315,5 +327,10 @@ export type InitOptions = Simplify<
* Path to new or existing `mkdocs.yml` file
*/
mkdocsYml?: string;
/**
* If `true`, upgrade only
*/
upgrade?: boolean;
}
>;

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