appium 2.0.0-beta.3 → 2.0.0-beta.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.md +10 -11
  2. package/build/lib/appium.d.ts +215 -0
  3. package/build/lib/appium.d.ts.map +1 -0
  4. package/build/lib/appium.js +241 -132
  5. package/build/lib/cli/args.d.ts +20 -0
  6. package/build/lib/cli/args.d.ts.map +1 -0
  7. package/build/lib/cli/args.js +96 -282
  8. package/build/lib/cli/driver-command.d.ts +36 -0
  9. package/build/lib/cli/driver-command.d.ts.map +1 -0
  10. package/build/lib/cli/driver-command.js +19 -12
  11. package/build/lib/cli/extension-command.d.ts +345 -0
  12. package/build/lib/cli/extension-command.d.ts.map +1 -0
  13. package/build/lib/cli/extension-command.js +171 -96
  14. package/build/lib/cli/extension.d.ts +14 -0
  15. package/build/lib/cli/extension.d.ts.map +1 -0
  16. package/build/lib/cli/extension.js +31 -16
  17. package/build/lib/cli/parser.d.ts +80 -0
  18. package/build/lib/cli/parser.d.ts.map +1 -0
  19. package/build/lib/cli/parser.js +152 -95
  20. package/build/lib/cli/plugin-command.d.ts +39 -0
  21. package/build/lib/cli/plugin-command.d.ts.map +1 -0
  22. package/build/lib/cli/plugin-command.js +18 -13
  23. package/build/lib/cli/utils.d.ts +29 -0
  24. package/build/lib/cli/utils.d.ts.map +1 -0
  25. package/build/lib/cli/utils.js +27 -3
  26. package/build/lib/config-file.d.ts +100 -0
  27. package/build/lib/config-file.d.ts.map +1 -0
  28. package/build/lib/config-file.js +136 -0
  29. package/build/lib/config.d.ts +41 -0
  30. package/build/lib/config.d.ts.map +1 -0
  31. package/build/lib/config.js +92 -67
  32. package/build/lib/constants.d.ts +48 -0
  33. package/build/lib/constants.d.ts.map +1 -0
  34. package/build/lib/constants.js +60 -0
  35. package/build/lib/extension/driver-config.d.ts +84 -0
  36. package/build/lib/extension/driver-config.d.ts.map +1 -0
  37. package/build/lib/extension/driver-config.js +190 -0
  38. package/build/lib/extension/extension-config.d.ts +170 -0
  39. package/build/lib/extension/extension-config.d.ts.map +1 -0
  40. package/build/lib/extension/extension-config.js +297 -0
  41. package/build/lib/extension/index.d.ts +39 -0
  42. package/build/lib/extension/index.d.ts.map +1 -0
  43. package/build/lib/extension/index.js +77 -0
  44. package/build/lib/extension/manifest.d.ts +174 -0
  45. package/build/lib/extension/manifest.d.ts.map +1 -0
  46. package/build/lib/extension/manifest.js +246 -0
  47. package/build/lib/extension/package-changed.d.ts +11 -0
  48. package/build/lib/extension/package-changed.d.ts.map +1 -0
  49. package/build/lib/extension/package-changed.js +68 -0
  50. package/build/lib/extension/plugin-config.d.ts +62 -0
  51. package/build/lib/extension/plugin-config.d.ts.map +1 -0
  52. package/build/lib/extension/plugin-config.js +87 -0
  53. package/build/lib/grid-register.d.ts +10 -0
  54. package/build/lib/grid-register.d.ts.map +1 -0
  55. package/build/lib/grid-register.js +21 -25
  56. package/build/lib/logger.d.ts +3 -0
  57. package/build/lib/logger.d.ts.map +1 -0
  58. package/build/lib/logger.js +4 -6
  59. package/build/lib/logsink.d.ts +4 -0
  60. package/build/lib/logsink.d.ts.map +1 -0
  61. package/build/lib/logsink.js +12 -16
  62. package/build/lib/main.d.ts +54 -0
  63. package/build/lib/main.d.ts.map +1 -0
  64. package/build/lib/main.js +189 -90
  65. package/build/lib/schema/arg-spec.d.ts +143 -0
  66. package/build/lib/schema/arg-spec.d.ts.map +1 -0
  67. package/build/lib/schema/arg-spec.js +119 -0
  68. package/build/lib/schema/cli-args.d.ts +19 -0
  69. package/build/lib/schema/cli-args.d.ts.map +1 -0
  70. package/build/lib/schema/cli-args.js +180 -0
  71. package/build/lib/schema/cli-transformers.d.ts +5 -0
  72. package/build/lib/schema/cli-transformers.d.ts.map +1 -0
  73. package/build/lib/schema/cli-transformers.js +74 -0
  74. package/build/lib/schema/index.d.ts +3 -0
  75. package/build/lib/schema/index.d.ts.map +1 -0
  76. package/build/lib/schema/index.js +34 -0
  77. package/build/lib/schema/keywords.d.ts +24 -0
  78. package/build/lib/schema/keywords.d.ts.map +1 -0
  79. package/build/lib/schema/keywords.js +70 -0
  80. package/build/lib/schema/schema.d.ts +259 -0
  81. package/build/lib/schema/schema.d.ts.map +1 -0
  82. package/build/lib/schema/schema.js +452 -0
  83. package/build/lib/utils.d.ts +66 -0
  84. package/build/lib/utils.d.ts.map +1 -0
  85. package/build/lib/utils.js +35 -139
  86. package/build/tsconfig.tsbuildinfo +1 -0
  87. package/build/types/appium-manifest.d.ts +40 -0
  88. package/build/types/appium-manifest.d.ts.map +1 -0
  89. package/build/types/cli.d.ts +112 -0
  90. package/build/types/cli.d.ts.map +1 -0
  91. package/build/types/extension.d.ts +43 -0
  92. package/build/types/extension.d.ts.map +1 -0
  93. package/build/types/external-manifest.d.ts +47 -0
  94. package/build/types/external-manifest.d.ts.map +1 -0
  95. package/build/types/index.d.ts +15 -0
  96. package/build/types/index.d.ts.map +1 -0
  97. package/index.js +11 -0
  98. package/lib/appium-config.schema.json +278 -0
  99. package/lib/appium.js +402 -155
  100. package/lib/cli/args.js +174 -377
  101. package/lib/cli/driver-command.js +22 -7
  102. package/lib/cli/extension-command.js +372 -177
  103. package/lib/cli/extension.js +32 -10
  104. package/lib/cli/parser.js +253 -83
  105. package/lib/cli/plugin-command.js +19 -6
  106. package/lib/cli/utils.js +22 -2
  107. package/lib/config-file.js +223 -0
  108. package/lib/config.js +170 -69
  109. package/lib/constants.js +78 -0
  110. package/lib/extension/driver-config.js +249 -0
  111. package/lib/extension/extension-config.js +458 -0
  112. package/lib/extension/index.js +102 -0
  113. package/lib/extension/manifest.js +484 -0
  114. package/lib/extension/package-changed.js +63 -0
  115. package/lib/extension/plugin-config.js +113 -0
  116. package/lib/grid-register.js +25 -22
  117. package/lib/logger.js +1 -1
  118. package/lib/logsink.js +14 -7
  119. package/lib/main.js +255 -90
  120. package/lib/schema/arg-spec.js +232 -0
  121. package/lib/schema/cli-args.js +261 -0
  122. package/lib/schema/cli-transformers.js +122 -0
  123. package/lib/schema/index.js +2 -0
  124. package/lib/schema/keywords.js +134 -0
  125. package/lib/schema/schema.js +734 -0
  126. package/lib/utils.js +85 -129
  127. package/package.json +68 -85
  128. package/scripts/postinstall.js +71 -0
  129. package/types/appium-manifest.ts +61 -0
  130. package/types/cli.ts +153 -0
  131. package/types/extension.ts +56 -0
  132. package/types/external-manifest.ts +58 -0
  133. package/types/index.ts +14 -0
  134. package/CHANGELOG.md +0 -3515
  135. package/bin/ios-webkit-debug-proxy-launcher.js +0 -71
  136. package/build/lib/cli/npm.js +0 -206
  137. package/build/lib/cli/parser-helpers.js +0 -82
  138. package/build/lib/driver-config.js +0 -77
  139. package/build/lib/drivers.js +0 -96
  140. package/build/lib/extension-config.js +0 -251
  141. package/build/lib/plugin-config.js +0 -59
  142. package/build/lib/plugins.js +0 -14
  143. package/lib/cli/npm.js +0 -183
  144. package/lib/cli/parser-helpers.js +0 -79
  145. package/lib/driver-config.js +0 -46
  146. package/lib/drivers.js +0 -81
  147. package/lib/extension-config.js +0 -208
  148. package/lib/plugin-config.js +0 -34
  149. package/lib/plugins.js +0 -10
@@ -0,0 +1,102 @@
1
+
2
+ import _ from 'lodash';
3
+ import { USE_ALL_PLUGINS } from '../constants';
4
+ import log from '../logger';
5
+ import { DriverConfig } from './driver-config';
6
+ import { Manifest } from './manifest';
7
+ import { PluginConfig } from './plugin-config';
8
+
9
+ /**
10
+ * Loads extensions and creates `ExtensionConfig` instances.
11
+ *
12
+ * - Reads the manifest file, creating if necessary
13
+ * - Using the parsed extension data, creates/gets the `ExtensionConfig` subclass instances
14
+ * - Returns these instances
15
+ *
16
+ * If `appiumHome` is needed, use `resolveAppiumHome` from the `env` module in `@appium/support`.
17
+ * @param {string} appiumHome
18
+ * @returns {Promise<ExtensionConfigs>}
19
+ */
20
+ export async function loadExtensions (appiumHome) {
21
+ const manifest = Manifest.getInstance(appiumHome);
22
+ const {drivers, plugins} = await manifest.read();
23
+ const driverConfig =
24
+ DriverConfig.getInstance(manifest) ??
25
+ DriverConfig.create(manifest, {extData: drivers});
26
+ const pluginConfig =
27
+ PluginConfig.getInstance(manifest) ??
28
+ PluginConfig.create(manifest, {extData: plugins});
29
+ return {driverConfig, pluginConfig};
30
+ }
31
+
32
+ /**
33
+ * Find any plugin name which has been installed, and which has been requested for activation by
34
+ * using the --use-plugins flag, and turn each one into its class, so we can send them as objects
35
+ * to the server init. We also want to send/assign them to the umbrella driver so it can use them
36
+ * to wrap command execution
37
+ *
38
+ * @param {import('./plugin-config').PluginConfig} pluginConfig - a plugin extension config
39
+ * @param {string[]} usePlugins
40
+ * @returns {import('../../types').PluginClass[]}
41
+ */
42
+ export function getActivePlugins (pluginConfig, usePlugins = []) {
43
+ return _.compact(
44
+ Object.keys(pluginConfig.installedExtensions)
45
+ .filter(
46
+ (pluginName) =>
47
+ _.includes(usePlugins, pluginName) ||
48
+ (usePlugins.length === 1 && usePlugins[0] === USE_ALL_PLUGINS),
49
+ )
50
+ .map((pluginName) => {
51
+ try {
52
+ log.info(`Attempting to load plugin ${pluginName}...`);
53
+ const PluginClass = pluginConfig.require(pluginName);
54
+
55
+ PluginClass.pluginName = pluginName; // store the plugin name on the class so it can be used later
56
+ return PluginClass;
57
+ } catch (err) {
58
+ log.error(
59
+ `Could not load plugin '${pluginName}', so it will not be available. Error ` +
60
+ `in loading the plugin was: ${err.message}`,
61
+ );
62
+ log.debug(err.stack);
63
+ }
64
+ }),
65
+ );
66
+ }
67
+
68
+ /**
69
+ * Find any driver name which has been installed, and turn each one into its class, so we can send
70
+ * them as objects to the server init in case they need to add methods/routes or update the server.
71
+ * If the --drivers flag was given, this method only loads the given drivers.
72
+ *
73
+ * @param {import('./driver-config').DriverConfig} driverConfig - a driver extension config
74
+ * @param {string[]} [useDrivers] - optional list of drivers to load
75
+ */
76
+ export function getActiveDrivers (driverConfig, useDrivers = []) {
77
+ return _.compact(
78
+ Object.keys(driverConfig.installedExtensions)
79
+ .filter(
80
+ (driverName) =>
81
+ _.includes(useDrivers, driverName) || useDrivers.length === 0,
82
+ )
83
+ .map((driverName) => {
84
+ try {
85
+ log.info(`Attempting to load driver ${driverName}...`);
86
+ return driverConfig.require(driverName);
87
+ } catch (err) {
88
+ log.error(
89
+ `Could not load driver '${driverName}', so it will not be available. Error ` +
90
+ `in loading the driver was: ${err.message}`,
91
+ );
92
+ log.debug(err.stack);
93
+ }
94
+ }),
95
+ );
96
+ }
97
+
98
+ /**
99
+ * @typedef ExtensionConfigs
100
+ * @property {DriverConfig} driverConfig
101
+ * @property {PluginConfig} pluginConfig
102
+ */
@@ -0,0 +1,484 @@
1
+ /**
2
+ * Module containing {@link Manifest} which handles reading & writing of extension config files.
3
+ */
4
+
5
+ import { env, fs } from '@appium/support';
6
+ import _ from 'lodash';
7
+ import path from 'path';
8
+ import YAML from 'yaml';
9
+ import { DRIVER_TYPE, PLUGIN_TYPE } from '../constants';
10
+ import log from '../logger';
11
+ import { INSTALL_TYPE_NPM } from './extension-config';
12
+ import { packageDidChange } from './package-changed';
13
+
14
+ /**
15
+ * Default depth to search in directory tree for whatever it is we're looking for.
16
+ *
17
+ * It's 4 because smaller numbers didn't work.
18
+ */
19
+ const DEFAULT_SEARCH_DEPTH = 4;
20
+
21
+ /**
22
+ * Default options for {@link findExtensions}.
23
+ * @type {Readonly<import('klaw').Options>}
24
+ */
25
+ const DEFAULT_FIND_EXTENSIONS_OPTS = Object.freeze({
26
+ depthLimit: DEFAULT_SEARCH_DEPTH,
27
+ /* istanbul ignore next */
28
+ filter: (filepath) => !path.basename(filepath).startsWith('.'),
29
+ });
30
+
31
+ /**
32
+ * Current configuration schema revision!
33
+ */
34
+ const CONFIG_SCHEMA_REV = 2;
35
+
36
+ /**
37
+ * The name of the prop (`drivers`) used in `extensions.yaml` for drivers.
38
+ * @type {`${typeof DRIVER_TYPE}s`}
39
+ */
40
+ const CONFIG_DATA_DRIVER_KEY = `${DRIVER_TYPE}s`;
41
+
42
+ /**
43
+ * The name of the prop (`plugins`) used in `extensions.yaml` for plugins.
44
+ * @type {`${typeof PLUGIN_TYPE}s`}
45
+ */
46
+ const CONFIG_DATA_PLUGIN_KEY = `${PLUGIN_TYPE}s`;
47
+
48
+ /**
49
+ * @type {Readonly<ManifestData>}
50
+ */
51
+ const INITIAL_MANIFEST_DATA = Object.freeze({
52
+ [CONFIG_DATA_DRIVER_KEY]: Object.freeze({}),
53
+ [CONFIG_DATA_PLUGIN_KEY]: Object.freeze({}),
54
+ schemaRev: CONFIG_SCHEMA_REV,
55
+ });
56
+
57
+ /**
58
+ * Given a `package.json` return `true` if it represents an Appium Extension (either a driver or plugin).
59
+ *
60
+ * The `package.json` must have an `appium` property which is an object.
61
+ * @param {any} value
62
+ * @returns {value is ExtPackageJson<ExtensionType>}
63
+ */
64
+ function isExtension (value) {
65
+ return (
66
+ _.isPlainObject(value) &&
67
+ _.isPlainObject(value.appium) &&
68
+ _.isString(value.name) &&
69
+ _.isString(value.version)
70
+ );
71
+ }
72
+ /**
73
+ * Given a `package.json`, return `true` if it represents an Appium Driver.
74
+ *
75
+ * To be considered a driver, a `package.json` must have a fields
76
+ * `appium.driverName`, `appium.automationName` and `appium.platformNames`.
77
+ * @param {any} value - Value to test
78
+ * @returns {value is ExtPackageJson<DriverType>}
79
+ */
80
+ function isDriver (value) {
81
+ return (
82
+ isExtension(value) &&
83
+ _.isString(_.get(value, 'appium.driverName')) &&
84
+ _.isString(_.get(value, 'appium.automationName')) &&
85
+ _.isArray(_.get(value, 'appium.platformNames'))
86
+ );
87
+ }
88
+
89
+ /**
90
+ * Given a `package.json`, return `true` if it represents an Appium Plugin.
91
+ *
92
+ * To be considered a plugin, a `package.json` must have an `appium.pluginName` field.
93
+ * @param {any} value - Value to test
94
+ * @returns {value is ExtPackageJson<PluginType>}
95
+ */
96
+ function isPlugin (value) {
97
+ return isExtension(value) && _.isString(_.get(value, 'appium.pluginName'));
98
+ }
99
+
100
+ /**
101
+ * Handles reading & writing of extension config files.
102
+ *
103
+ * Only one instance of this class exists per value of `APPIUM_HOME`.
104
+ */
105
+ export class Manifest {
106
+ /**
107
+ * The entire contents of a parsed YAML extension config file.
108
+ *
109
+ * Contains proxies for automatic persistence on disk
110
+ * @type {ManifestData}
111
+ * @private
112
+ */
113
+ _data;
114
+
115
+ /**
116
+ * Path to `APPIUM_HOME`.
117
+ * @private
118
+ * @type {Readonly<string>}
119
+ */
120
+ _appiumHome;
121
+
122
+ /**
123
+ * Path to `extensions.yaml`
124
+ * @type {string}
125
+ * Not set until {@link Manifest.read} is called.
126
+ */
127
+ _manifestPath;
128
+
129
+ /**
130
+ * Helps avoid writing multiple times.
131
+ *
132
+ * If this is `undefined`, calling {@link Manifest.write} will cause it to be
133
+ * set to a `Promise`. When the call to `write()` is complete, the `Promise`
134
+ * will resolve and then this value will be set to `undefined`. Concurrent calls
135
+ * made while this value is a `Promise` will return the `Promise` itself.
136
+ * @private
137
+ * @type {Promise<boolean>|undefined}
138
+ */
139
+ _writing;
140
+
141
+ /**
142
+ * Helps avoid reading multiple times.
143
+ *
144
+ * If this is `undefined`, calling {@link Manifest.read} will cause it to be
145
+ * set to a `Promise`. When the call to `read()` is complete, the `Promise`
146
+ * will resolve and then this value will be set to `undefined`. Concurrent calls
147
+ * made while this value is a `Promise` will return the `Promise` itself.
148
+ * @private
149
+ * @type {Promise<void>|undefined}
150
+ */
151
+ _reading;
152
+
153
+ /**
154
+ * Sets internal data to a fresh clone of {@link INITIAL_MANIFEST_DATA}
155
+ *
156
+ * Use {@link Manifest.getInstance} instead.
157
+ * @param {string} appiumHome
158
+ * @private
159
+ */
160
+ constructor (appiumHome) {
161
+ this._appiumHome = appiumHome;
162
+ this._data = _.cloneDeep(INITIAL_MANIFEST_DATA);
163
+ }
164
+
165
+ /**
166
+ * Returns a new or existing {@link Manifest} instance, based on the value of `appiumHome`.
167
+ *
168
+ * Maintains one instance per value of `appiumHome`.
169
+ * @param {string} appiumHome - Path to `APPIUM_HOME`
170
+ * @returns {Manifest}
171
+ */
172
+ static getInstance = _.memoize(function _getInstance (
173
+ appiumHome,
174
+ ) {
175
+ return new Manifest(appiumHome);
176
+ });
177
+
178
+ /**
179
+ * Searches `APPIUM_HOME` for installed extensions and adds them to the manifest.
180
+ * @param {SyncWithInstalledExtensionsOpts} opts
181
+ * @returns {Promise<boolean>} `true` if any extensions were added, `false` otherwise.
182
+ */
183
+ async syncWithInstalledExtensions ({depthLimit = DEFAULT_SEARCH_DEPTH} = {}) {
184
+ const walkOpts = _.defaults({depthLimit}, DEFAULT_FIND_EXTENSIONS_OPTS);
185
+ // this could be parallelized, but we can't use fs.walk as an async iterator
186
+ let didChange = false;
187
+ for await (const {stats, path: filepath} of fs.walk(
188
+ this._appiumHome,
189
+ walkOpts,
190
+ )) {
191
+ if (filepath !== this._appiumHome && stats.isDirectory()) {
192
+ try {
193
+ const pkg = await env.readPackageInDir(filepath);
194
+ if (pkg && isExtension(pkg)) {
195
+ // it's possible that this extension already exists in the manifest,
196
+ // so only update `didChange` if it's new.
197
+ const added = this.addExtensionFromPackage(
198
+ pkg,
199
+ path.join(filepath, 'package.json'),
200
+ );
201
+ didChange = didChange || added;
202
+ }
203
+ } catch {}
204
+ }
205
+ }
206
+ return didChange;
207
+ }
208
+
209
+ /**
210
+ * Returns `true` if driver with name `name` is registered.
211
+ * @param {string} name - Driver name
212
+ * @returns {boolean}
213
+ */
214
+ hasDriver (name) {
215
+ return Boolean(this._data.drivers[name]);
216
+ }
217
+
218
+ /**
219
+ * Returns `true` if plugin with name `name` is registered.
220
+ * @param {string} name - Plugin name
221
+ * @returns {boolean}
222
+ */
223
+ hasPlugin (name) {
224
+ return Boolean(this._data.plugins[name]);
225
+ }
226
+
227
+ /**
228
+ * Given a path to a `package.json`, add it as either a driver or plugin to the manifest.
229
+ *
230
+ * Will _not_ overwrite existing entries.
231
+ * @template {ExtensionType} ExtType
232
+ * @param {ExtPackageJson<ExtType>} pkgJson
233
+ * @param {string} pkgPath
234
+ * @returns {boolean} - `true` upon success, `false` if the extension is already registered.
235
+ */
236
+ addExtensionFromPackage (pkgJson, pkgPath) {
237
+ /**
238
+ * @type {InternalMetadata}
239
+ */
240
+ const internal = {
241
+ pkgName: pkgJson.name,
242
+ version: pkgJson.version,
243
+ installType: INSTALL_TYPE_NPM,
244
+ installSpec: `${pkgJson.name}@${pkgJson.version}`,
245
+ };
246
+
247
+ if (isDriver(pkgJson)) {
248
+ if (!this.hasDriver(pkgJson.appium.driverName)) {
249
+ this.addExtension(DRIVER_TYPE, pkgJson.appium.driverName, {
250
+ ..._.omit(pkgJson.appium, 'driverName'),
251
+ ...internal
252
+ });
253
+ return true;
254
+ }
255
+ return false;
256
+ } else if (isPlugin(pkgJson)) {
257
+ if (!this.hasPlugin(pkgJson.appium.pluginName)) {
258
+ this.addExtension(PLUGIN_TYPE, pkgJson.appium.pluginName, {
259
+ ..._.omit(pkgJson.appium, 'pluginName'),
260
+ ...internal,
261
+ });
262
+ return true;
263
+ }
264
+ return false;
265
+ } else {
266
+ throw new TypeError(
267
+ `The extension in ${path.dirname(
268
+ pkgPath,
269
+ )} is neither a valid driver nor a valid plugin.`,
270
+ );
271
+ }
272
+ }
273
+
274
+ /**
275
+ * Adds an extension to the manifest as was installed by the `appium` CLI. The
276
+ * `extData`, `extType`, and `extName` have already been determined.
277
+ *
278
+ * See {@link Manifest.addExtensionFromPackage} for adding an extension from an on-disk package.
279
+ * @template {ExtensionType} ExtType
280
+ * @param {ExtType} extType - `driver` or `plugin`
281
+ * @param {string} extName - Name of extension
282
+ * @param {ExtManifest<ExtType>} extData - Extension metadata
283
+ * @returns {void}
284
+ */
285
+ addExtension (extType, extName, extData) {
286
+ this._data[`${extType}s`][extName] = extData;
287
+ }
288
+
289
+ /**
290
+ * Returns the APPIUM_HOME path
291
+ */
292
+ get appiumHome () {
293
+ return this._appiumHome;
294
+ }
295
+
296
+ /**
297
+ * Returns the path to the manifest file
298
+ */
299
+ get manifestPath () {
300
+ return this._manifestPath;
301
+ }
302
+
303
+ /**
304
+ * Returns extension data for a particular type.
305
+ *
306
+ * @template {ExtensionType} ExtType
307
+ * @param {ExtType} extType
308
+ * @returns {ExtRecord<ExtType>}
309
+ */
310
+ getExtensionData (extType) {
311
+ return this._data[/** @type {string} */ (`${extType}s`)];
312
+ }
313
+
314
+ /**
315
+ * Reads manifest from disk and _overwrites_ the internal data.
316
+ *
317
+ * If the manifest does not exist on disk, an {@link INITIAL_MANIFEST_DATA "empty"} manifest file will be created.
318
+ *
319
+ * If `APPIUM_HOME` contains a `package.json` with an `appium` dependency, then a hash of the `package.json` will be taken. If this hash differs from the last hash, the contents of `APPIUM_HOME/node_modules` will be scanned for extensions that may have been installed outside of the `appium` CLI. Any found extensions will be added to the manifest file, and if so, the manifest file will be written to disk.
320
+ *
321
+ * Only one read operation should happen at a time. This is controlled via the {@link Manifest._reading} property.
322
+ * @returns {Promise<ManifestData>} The data
323
+ */
324
+ async read () {
325
+ if (this._reading) {
326
+ await this._reading;
327
+ return this._data;
328
+ }
329
+
330
+ this._reading = (async () => {
331
+ /** @type {ManifestData} */
332
+ let data;
333
+ let isNewFile = false;
334
+ await this._setManifestPath();
335
+ try {
336
+ log.debug(`Reading ${this._manifestPath}...`);
337
+ const yaml = await fs.readFile(this._manifestPath, 'utf8');
338
+ data = YAML.parse(yaml);
339
+ } catch (err) {
340
+ if (err.code === 'ENOENT') {
341
+ data = _.cloneDeep(INITIAL_MANIFEST_DATA);
342
+ isNewFile = true;
343
+ } else {
344
+ if (this._manifestPath) {
345
+ throw new Error(
346
+ `Appium had trouble loading the extension installation ` +
347
+ `cache file (${this._manifestPath}). It may be invalid YAML. Specific error: ${err.message}`,
348
+ );
349
+ } else {
350
+ throw new Error(
351
+ `Appium encountered an unknown problem. Specific error: ${err.message}`,
352
+ );
353
+ }
354
+ }
355
+ }
356
+
357
+ this._data = data;
358
+ let installedExtensionsChanged = false;
359
+ if (
360
+ await env.hasAppiumDependency(this.appiumHome) &&
361
+ (await packageDidChange(this.appiumHome))
362
+ ) {
363
+ installedExtensionsChanged = await this.syncWithInstalledExtensions();
364
+ }
365
+
366
+ if (isNewFile || installedExtensionsChanged) {
367
+ await this.write();
368
+ }
369
+ })();
370
+ try {
371
+ await this._reading;
372
+ return this._data;
373
+ } finally {
374
+ this._reading = undefined;
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Ensures {@link Manifest._manifestPath} is set.
380
+ *
381
+ * Creates the directory if necessary.
382
+ * @private
383
+ * @returns {Promise<string>}
384
+ */
385
+ async _setManifestPath () {
386
+ if (!this._manifestPath) {
387
+ this._manifestPath = await env.resolveManifestPath(this._appiumHome);
388
+
389
+ /* istanbul ignore if */
390
+ if (path.relative(this._appiumHome, this._manifestPath).startsWith('.')) {
391
+ throw new Error(
392
+ `Mismatch between location of APPIUM_HOME and manifest file. APPIUM_HOME: ${this.appiumHome}, manifest file: ${this._manifestPath}`,
393
+ );
394
+ }
395
+ }
396
+
397
+ return this._manifestPath;
398
+ }
399
+
400
+ /**
401
+ * Writes the data if it need s writing.
402
+ *
403
+ * If the `schemaRev` prop needs updating, the file will be written.
404
+ *
405
+ * @todo If this becomes too much of a bottleneck, throttle it.
406
+ * @returns {Promise<boolean>} Whether the data was written
407
+ */
408
+ async write () {
409
+ if (this._writing) {
410
+ return this._writing;
411
+ }
412
+ this._writing = (async () => {
413
+ await this._setManifestPath();
414
+ try {
415
+ await fs.mkdirp(path.dirname(this._manifestPath));
416
+ } catch (err) {
417
+ throw new Error(
418
+ `Appium could not create the directory for the manifest file: ${path.dirname(
419
+ this._manifestPath,
420
+ )}. Original error: ${err.message}`,
421
+ );
422
+ }
423
+ try {
424
+ await fs.writeFile(
425
+ this._manifestPath,
426
+ YAML.stringify(this._data),
427
+ 'utf8',
428
+ );
429
+ return true;
430
+ } catch (err) {
431
+ throw new Error(
432
+ `Appium could not write to manifest at ${this._manifestPath} using APPIUM_HOME ${this._appiumHome}. ` +
433
+ `Please ensure it is writable. Original error: ${err.message}`,
434
+ );
435
+ }
436
+ })();
437
+ try {
438
+ return await this._writing;
439
+ } finally {
440
+ this._writing = undefined;
441
+ }
442
+ }
443
+ }
444
+
445
+ /**
446
+ * Type of the string referring to a driver (typically as a key or type string)
447
+ * @typedef {import('../../types').DriverType} DriverType
448
+ */
449
+
450
+ /**
451
+ * Type of the string referring to a plugin (typically as a key or type string)
452
+ * @typedef {import('../../types').PluginType} PluginType
453
+ */
454
+
455
+ /**
456
+ * @typedef SyncWithInstalledExtensionsOpts
457
+ * @property {number} [depthLimit] - Maximum depth to recurse into subdirectories
458
+ */
459
+
460
+ /**
461
+ * @typedef {import('../../types/appium-manifest').ManifestData} ManifestData
462
+ * @typedef {import('../../types/appium-manifest').InternalMetadata} InternalMetadata
463
+ */
464
+
465
+ /**
466
+ * @template T
467
+ * @typedef {import('../../types/external-manifest').ExtPackageJson<T>} ExtPackageJson
468
+ */
469
+
470
+ /**
471
+ * @template T
472
+ * @typedef {import('../../types/appium-manifest').ExtManifest<T>} ExtManifest
473
+ */
474
+
475
+ /**
476
+ * @template T
477
+ * @typedef {import('../../types/appium-manifest').ExtRecord<T>} ExtRecord
478
+ */
479
+
480
+ /**
481
+ * Either `driver` or `plugin` rn
482
+ * @typedef {import('../../types').ExtensionType} ExtensionType
483
+ */
484
+
@@ -0,0 +1,63 @@
1
+
2
+ import { fs } from '@appium/support';
3
+ import { isPackageChanged } from 'package-changed';
4
+ import path from 'path';
5
+ import { PKG_HASHFILE_RELATIVE_PATH } from '../constants';
6
+ import log from '../logger';
7
+
8
+ /**
9
+ * Determines if extensions have changed, and updates a hash the `package.json` in `appiumHome` if so.
10
+ *
11
+ * If they have, we need to sync them with the `extensions.yaml` manifest.
12
+ *
13
+ * _Warning: this makes a blocking call to `writeFileSync`._
14
+ * @param {string} appiumHome
15
+ * @returns {Promise<boolean>} `true` if `package.json` `appiumHome` changed
16
+ */
17
+ export async function packageDidChange (appiumHome) {
18
+ const hashFilename = path.join(appiumHome, PKG_HASHFILE_RELATIVE_PATH);
19
+
20
+ // XXX: the types in `package-changed` seem to be wrong.
21
+
22
+ /** @type {boolean} */
23
+ let isChanged;
24
+ /** @type {() => void} */
25
+ let writeHash;
26
+ /** @type {string} */
27
+ let hash;
28
+ /** @type {string|undefined} */
29
+ let oldHash;
30
+
31
+ // first mkdirp the target dir.
32
+ const hashFilenameDir = path.dirname(hashFilename);
33
+ log.debug(`Creating hash file directory: ${hashFilenameDir}`);
34
+ try {
35
+ await fs.mkdirp(hashFilenameDir);
36
+ } catch (err) {
37
+ throw new Error(
38
+ `Appium could not create the directory for hash file: ${hashFilenameDir}. Original error: ${err.message}`,
39
+ );
40
+ }
41
+
42
+ try {
43
+ ({isChanged, writeHash, oldHash, hash} = await isPackageChanged({
44
+ cwd: appiumHome,
45
+ hashFilename: PKG_HASHFILE_RELATIVE_PATH,
46
+ }));
47
+ } catch {
48
+ return true;
49
+ }
50
+
51
+ if (isChanged) {
52
+ try {
53
+ writeHash();
54
+ log.debug(`Updated hash of ${appiumHome}/package.json from: ${oldHash ?? '(none)'} to: ${hash}`);
55
+ } catch (err) {
56
+ throw new Error(
57
+ `Appium could not write hash file: ${hashFilenameDir}. Original error: ${err.message}`,
58
+ );
59
+ }
60
+ }
61
+
62
+ return isChanged;
63
+ }