appium 2.0.0-beta.5 → 2.0.0-beta.53

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 (199) hide show
  1. package/README.md +156 -63
  2. package/build/lib/appium.d.ts +226 -0
  3. package/build/lib/appium.d.ts.map +1 -0
  4. package/build/lib/appium.js +694 -439
  5. package/build/lib/appium.js.map +1 -0
  6. package/build/lib/cli/args.d.ts +17 -0
  7. package/build/lib/cli/args.d.ts.map +1 -0
  8. package/build/lib/cli/args.js +253 -319
  9. package/build/lib/cli/args.js.map +1 -0
  10. package/build/lib/cli/driver-command.d.ts +102 -0
  11. package/build/lib/cli/driver-command.d.ts.map +1 -0
  12. package/build/lib/cli/driver-command.js +126 -81
  13. package/build/lib/cli/driver-command.js.map +1 -0
  14. package/build/lib/cli/extension-command.d.ts +385 -0
  15. package/build/lib/cli/extension-command.d.ts.map +1 -0
  16. package/build/lib/cli/extension-command.js +731 -383
  17. package/build/lib/cli/extension-command.js.map +1 -0
  18. package/build/lib/cli/extension.d.ts +23 -0
  19. package/build/lib/cli/extension.d.ts.map +1 -0
  20. package/build/lib/cli/extension.js +71 -54
  21. package/build/lib/cli/extension.js.map +1 -0
  22. package/build/lib/cli/parser.d.ts +84 -0
  23. package/build/lib/cli/parser.d.ts.map +1 -0
  24. package/build/lib/cli/parser.js +240 -128
  25. package/build/lib/cli/parser.js.map +1 -0
  26. package/build/lib/cli/plugin-command.d.ts +99 -0
  27. package/build/lib/cli/plugin-command.d.ts.map +1 -0
  28. package/build/lib/cli/plugin-command.js +120 -81
  29. package/build/lib/cli/plugin-command.js.map +1 -0
  30. package/build/lib/cli/utils.d.ts +29 -0
  31. package/build/lib/cli/utils.d.ts.map +1 -0
  32. package/build/lib/cli/utils.js +72 -51
  33. package/build/lib/cli/utils.js.map +1 -0
  34. package/build/lib/config-file.d.ts +100 -0
  35. package/build/lib/config-file.d.ts.map +1 -0
  36. package/build/lib/config-file.js +207 -0
  37. package/build/lib/config-file.js.map +1 -0
  38. package/build/lib/config.d.ts +49 -0
  39. package/build/lib/config.d.ts.map +1 -0
  40. package/build/lib/config.js +265 -201
  41. package/build/lib/config.js.map +1 -0
  42. package/build/lib/constants.d.ts +49 -0
  43. package/build/lib/constants.d.ts.map +1 -0
  44. package/build/lib/constants.js +66 -0
  45. package/build/lib/constants.js.map +1 -0
  46. package/build/lib/extension/driver-config.d.ts +82 -0
  47. package/build/lib/extension/driver-config.d.ts.map +1 -0
  48. package/build/lib/extension/driver-config.js +212 -0
  49. package/build/lib/extension/driver-config.js.map +1 -0
  50. package/build/lib/extension/extension-config.d.ts +249 -0
  51. package/build/lib/extension/extension-config.d.ts.map +1 -0
  52. package/build/lib/extension/extension-config.js +581 -0
  53. package/build/lib/extension/extension-config.js.map +1 -0
  54. package/build/lib/extension/index.d.ts +48 -0
  55. package/build/lib/extension/index.d.ts.map +1 -0
  56. package/build/lib/extension/index.js +105 -0
  57. package/build/lib/extension/index.js.map +1 -0
  58. package/build/lib/extension/manifest-migrations.d.ts +27 -0
  59. package/build/lib/extension/manifest-migrations.d.ts.map +1 -0
  60. package/build/lib/extension/manifest-migrations.js +118 -0
  61. package/build/lib/extension/manifest-migrations.js.map +1 -0
  62. package/build/lib/extension/manifest.d.ts +145 -0
  63. package/build/lib/extension/manifest.d.ts.map +1 -0
  64. package/build/lib/extension/manifest.js +521 -0
  65. package/build/lib/extension/manifest.js.map +1 -0
  66. package/build/lib/extension/package-changed.d.ts +11 -0
  67. package/build/lib/extension/package-changed.d.ts.map +1 -0
  68. package/build/lib/extension/package-changed.js +62 -0
  69. package/build/lib/extension/package-changed.js.map +1 -0
  70. package/build/lib/extension/plugin-config.d.ts +56 -0
  71. package/build/lib/extension/plugin-config.d.ts.map +1 -0
  72. package/build/lib/extension/plugin-config.js +102 -0
  73. package/build/lib/extension/plugin-config.js.map +1 -0
  74. package/build/lib/grid-register.d.ts +10 -0
  75. package/build/lib/grid-register.d.ts.map +1 -0
  76. package/build/lib/grid-register.js +122 -144
  77. package/build/lib/grid-register.js.map +1 -0
  78. package/build/lib/logger.d.ts +3 -0
  79. package/build/lib/logger.d.ts.map +1 -0
  80. package/build/lib/logger.js +5 -17
  81. package/build/lib/logger.js.map +1 -0
  82. package/build/lib/logsink.d.ts +4 -0
  83. package/build/lib/logsink.d.ts.map +1 -0
  84. package/build/lib/logsink.js +190 -187
  85. package/build/lib/logsink.js.map +1 -0
  86. package/build/lib/main.d.ts +62 -0
  87. package/build/lib/main.d.ts.map +1 -0
  88. package/build/lib/main.js +348 -228
  89. package/build/lib/main.js.map +1 -0
  90. package/build/lib/schema/arg-spec.d.ts +143 -0
  91. package/build/lib/schema/arg-spec.d.ts.map +1 -0
  92. package/build/lib/schema/arg-spec.js +164 -0
  93. package/build/lib/schema/arg-spec.js.map +1 -0
  94. package/build/lib/schema/cli-args.d.ts +19 -0
  95. package/build/lib/schema/cli-args.d.ts.map +1 -0
  96. package/build/lib/schema/cli-args.js +217 -0
  97. package/build/lib/schema/cli-args.js.map +1 -0
  98. package/build/lib/schema/cli-transformers.d.ts +5 -0
  99. package/build/lib/schema/cli-transformers.d.ts.map +1 -0
  100. package/build/lib/schema/cli-transformers.js +124 -0
  101. package/build/lib/schema/cli-transformers.js.map +1 -0
  102. package/build/lib/schema/index.d.ts +3 -0
  103. package/build/lib/schema/index.d.ts.map +1 -0
  104. package/build/lib/schema/index.js +19 -0
  105. package/build/lib/schema/index.js.map +1 -0
  106. package/build/lib/schema/keywords.d.ts +24 -0
  107. package/build/lib/schema/keywords.d.ts.map +1 -0
  108. package/build/lib/schema/keywords.js +128 -0
  109. package/build/lib/schema/keywords.js.map +1 -0
  110. package/build/lib/schema/schema.d.ts +259 -0
  111. package/build/lib/schema/schema.d.ts.map +1 -0
  112. package/build/lib/schema/schema.js +615 -0
  113. package/build/lib/schema/schema.js.map +1 -0
  114. package/build/lib/utils.d.ts +121 -0
  115. package/build/lib/utils.d.ts.map +1 -0
  116. package/build/lib/utils.js +351 -273
  117. package/build/lib/utils.js.map +1 -0
  118. package/build/tsconfig.tsbuildinfo +1 -0
  119. package/build/types/cli.d.ts +134 -0
  120. package/build/types/cli.d.ts.map +1 -0
  121. package/build/types/cli.js +3 -0
  122. package/build/types/cli.js.map +1 -0
  123. package/build/types/index.d.ts +15 -0
  124. package/build/types/index.d.ts.map +1 -0
  125. package/build/types/index.js +19 -0
  126. package/build/types/index.js.map +1 -0
  127. package/build/types/manifest/base.d.ts +135 -0
  128. package/build/types/manifest/base.d.ts.map +1 -0
  129. package/build/types/manifest/base.js +3 -0
  130. package/build/types/manifest/base.js.map +1 -0
  131. package/build/types/manifest/index.d.ts +19 -0
  132. package/build/types/manifest/index.d.ts.map +1 -0
  133. package/build/types/manifest/index.js +40 -0
  134. package/build/types/manifest/index.js.map +1 -0
  135. package/build/types/manifest/v3.d.ts +139 -0
  136. package/build/types/manifest/v3.d.ts.map +1 -0
  137. package/build/types/manifest/v3.js +3 -0
  138. package/build/types/manifest/v3.js.map +1 -0
  139. package/driver.d.ts +1 -0
  140. package/driver.js +14 -0
  141. package/index.js +11 -0
  142. package/lib/appium.js +535 -186
  143. package/lib/cli/args.js +267 -422
  144. package/lib/cli/driver-command.js +126 -23
  145. package/lib/cli/extension-command.js +679 -271
  146. package/lib/cli/extension.js +48 -17
  147. package/lib/cli/parser.js +263 -83
  148. package/lib/cli/plugin-command.js +115 -20
  149. package/lib/cli/utils.js +24 -10
  150. package/lib/config-file.js +220 -0
  151. package/lib/config.js +244 -110
  152. package/lib/constants.js +71 -0
  153. package/lib/extension/driver-config.js +250 -0
  154. package/lib/extension/extension-config.js +682 -0
  155. package/lib/extension/index.js +116 -0
  156. package/lib/extension/manifest-migrations.js +120 -0
  157. package/lib/extension/manifest.js +573 -0
  158. package/lib/extension/package-changed.js +64 -0
  159. package/lib/extension/plugin-config.js +112 -0
  160. package/lib/grid-register.js +49 -35
  161. package/lib/logger.js +1 -2
  162. package/lib/logsink.js +64 -38
  163. package/lib/main.js +321 -101
  164. package/lib/schema/arg-spec.js +229 -0
  165. package/lib/schema/cli-args.js +238 -0
  166. package/lib/schema/cli-transformers.js +119 -0
  167. package/lib/schema/index.js +2 -0
  168. package/lib/schema/keywords.js +136 -0
  169. package/lib/schema/schema.js +722 -0
  170. package/lib/utils.js +291 -167
  171. package/package.json +83 -84
  172. package/plugin.d.ts +1 -0
  173. package/plugin.js +13 -0
  174. package/scripts/autoinstall-extensions.js +237 -0
  175. package/support.d.ts +1 -0
  176. package/support.js +13 -0
  177. package/tsconfig.json +25 -0
  178. package/types/cli.ts +193 -0
  179. package/types/index.ts +20 -0
  180. package/types/manifest/README.md +30 -0
  181. package/types/manifest/base.ts +158 -0
  182. package/types/manifest/index.ts +27 -0
  183. package/types/manifest/v3.ts +161 -0
  184. package/CHANGELOG.md +0 -3515
  185. package/bin/ios-webkit-debug-proxy-launcher.js +0 -71
  186. package/build/lib/cli/npm.js +0 -208
  187. package/build/lib/cli/parser-helpers.js +0 -82
  188. package/build/lib/driver-config.js +0 -77
  189. package/build/lib/drivers.js +0 -96
  190. package/build/lib/extension-config.js +0 -253
  191. package/build/lib/plugin-config.js +0 -59
  192. package/build/lib/plugins.js +0 -14
  193. package/lib/cli/npm.js +0 -184
  194. package/lib/cli/parser-helpers.js +0 -79
  195. package/lib/driver-config.js +0 -46
  196. package/lib/drivers.js +0 -81
  197. package/lib/extension-config.js +0 -209
  198. package/lib/plugin-config.js +0 -34
  199. package/lib/plugins.js +0 -10
@@ -0,0 +1,722 @@
1
+ import Ajv from 'ajv';
2
+ import addFormats from 'ajv-formats';
3
+ import _ from 'lodash';
4
+ import path from 'path';
5
+ import {DRIVER_TYPE, PLUGIN_TYPE} from '../constants';
6
+ import {AppiumConfigJsonSchema} from '@appium/schema';
7
+ import {APPIUM_CONFIG_SCHEMA_ID, ArgSpec, SERVER_PROP_NAME} from './arg-spec';
8
+ import {keywords} from './keywords';
9
+
10
+ /**
11
+ * Key/value pairs go in... but they don't come out.
12
+ *
13
+ * @template K,V
14
+ * @extends {Map<K,V>}
15
+ */
16
+ export class RoachHotelMap extends Map {
17
+ /**
18
+ * @param {K} key
19
+ * @param {V} value
20
+ */
21
+ set(key, value) {
22
+ if (this.has(key)) {
23
+ throw new Error(`${key} is already set`);
24
+ }
25
+ return super.set(key, value);
26
+ }
27
+
28
+ /**
29
+ * @param {K} key
30
+ */
31
+ // eslint-disable-next-line no-unused-vars
32
+ delete(key) {
33
+ return false;
34
+ }
35
+
36
+ clear() {
37
+ throw new Error(`Cannot clear RoachHotelMap`);
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Extensions that an extension schema file can have.
43
+ */
44
+ export const ALLOWED_SCHEMA_EXTENSIONS = new Set(['.json', '.js', '.cjs']);
45
+
46
+ const SCHEMA_KEY = '$schema';
47
+
48
+ /**
49
+ * A wrapper around Ajv and schema-related functions.
50
+ *
51
+ * Should have been named Highlander, because _there can only be one_
52
+ */
53
+ class AppiumSchema {
54
+ /**
55
+ * A mapping of unique argument IDs to their corresponding {@link ArgSpec}s.
56
+ *
57
+ * An "argument" is a CLI argument or a config property.
58
+ *
59
+ * Used to provide easy lookups of argument metadata when converting between different representations of those arguments.
60
+ * @private
61
+ * @type {RoachHotelMap<string,ArgSpec>}
62
+ */
63
+ _argSpecs = new RoachHotelMap();
64
+
65
+ /**
66
+ * A map of extension types to extension names to schema objects.
67
+ *
68
+ * This data structure is used to ensure there are no naming conflicts. The schemas
69
+ * are stored here in memory until the instance is _finalized_.
70
+ * @private
71
+ * @type {Record<ExtensionType,Map<string,SchemaObject>>}
72
+ */
73
+ _registeredSchemas = {[DRIVER_TYPE]: new Map(), [PLUGIN_TYPE]: new Map()};
74
+
75
+ /**
76
+ * Ajv instance
77
+ *
78
+ * @private
79
+ * @type {Ajv}
80
+ */
81
+ _ajv;
82
+
83
+ /**
84
+ * Singleton instance.
85
+ * @private
86
+ * @type {AppiumSchema}
87
+ */
88
+ static _instance;
89
+
90
+ /**
91
+ * Lookup of schema IDs to finalized schemas.
92
+ *
93
+ * This does not include references, but rather the root schemas themselves.
94
+ * @private
95
+ * @type {Record<string,StrictSchemaObject>?}
96
+ */
97
+ _finalizedSchemas = null;
98
+
99
+ /**
100
+ * Initializes Ajv, adds standard formats and our custom keywords.
101
+ * @see https://npm.im/ajv-formats
102
+ * @private
103
+ */
104
+ constructor() {
105
+ this._ajv = AppiumSchema._instantiateAjv();
106
+ }
107
+
108
+ /**
109
+ * Factory function for {@link AppiumSchema} instances.
110
+ *
111
+ * Returns a singleton instance if one exists, otherwise creates a new one.
112
+ * Binds public methods to the instance.
113
+ * @returns {AppiumSchema}
114
+ */
115
+ static create() {
116
+ if (!AppiumSchema._instance) {
117
+ const instance = new AppiumSchema();
118
+ AppiumSchema._instance = instance;
119
+ _.bindAll(instance, [
120
+ 'finalize',
121
+ 'flatten',
122
+ 'getAllArgSpecs',
123
+ 'getArgSpec',
124
+ 'getDefaults',
125
+ 'getDefaultsForExtension',
126
+ 'getSchema',
127
+ 'hasArgSpec',
128
+ 'isFinalized',
129
+ 'registerSchema',
130
+ 'hasRegisteredSchema',
131
+ 'reset',
132
+ 'validate',
133
+ ]);
134
+ }
135
+
136
+ return AppiumSchema._instance;
137
+ }
138
+
139
+ /**
140
+ * Returns `true` if a schema has been registered using given extension type and name.
141
+ *
142
+ * This does not depend on whether or not the instance has been _finalized_.
143
+ * @param {ExtensionType} extType - Extension type
144
+ * @param {string} extName - Name
145
+ * @returns {boolean} If registered
146
+ */
147
+ hasRegisteredSchema(extType, extName) {
148
+ return this._registeredSchemas[extType].has(extName);
149
+ }
150
+
151
+ /**
152
+ * Return `true` if {@link AppiumSchema.finalize finalize} has been called
153
+ * successfully and {@link AppiumSchema.reset reset} has not been called since.
154
+ * @returns {boolean} If finalized
155
+ */
156
+ isFinalized() {
157
+ return Boolean(this._finalizedSchemas);
158
+ }
159
+
160
+ getAllArgSpecs() {
161
+ return this._argSpecs;
162
+ }
163
+
164
+ /**
165
+ * Call this when no more schemas will be registered.
166
+ *
167
+ * This does three things:
168
+ * 1. It combines all schemas from extensions into the Appium config schema,
169
+ * then adds the result to the `Ajv` instance.
170
+ * 2. It adds schemas for _each_ argument/property for validation purposes.
171
+ * The CLI uses these schemas to validate specific arguments.
172
+ * 3. The schemas are validated against JSON schema draft-07 (which is the
173
+ * only one supported at this time)
174
+ *
175
+ * Any method in this instance that needs to interact with the `Ajv` instance
176
+ * will throw if this method has not been called.
177
+ *
178
+ * If the instance has already been finalized, this is a no-op.
179
+ * @public
180
+ * @throws {Error} If the schema is not valid
181
+ * @returns {Readonly<Record<string,StrictSchemaObject>>} Record of schema IDs to full schema objects
182
+ */
183
+ finalize() {
184
+ if (this.isFinalized()) {
185
+ return /** @type {NonNullable<typeof this._finalizedSchemas>} */ (this._finalizedSchemas);
186
+ }
187
+
188
+ const ajv = this._ajv;
189
+
190
+ // Ajv will _mutate_ the schema, so we need to clone it.
191
+ const baseSchema = _.cloneDeep(AppiumConfigJsonSchema);
192
+
193
+ /**
194
+ *
195
+ * @param {SchemaObject} schema
196
+ * @param {ExtensionType} [extType]
197
+ * @param {string} [extName]
198
+ */
199
+ const addArgSpecs = (schema, extType, extName) => {
200
+ for (let [propName, propSchema] of Object.entries(schema)) {
201
+ const argSpec = ArgSpec.create(propName, {
202
+ dest: propSchema.appiumCliDest,
203
+ defaultValue: propSchema.default,
204
+ extType,
205
+ extName,
206
+ });
207
+ const {arg} = argSpec;
208
+ this._argSpecs.set(arg, argSpec);
209
+ }
210
+ };
211
+
212
+ addArgSpecs(_.omit(baseSchema.properties.server.properties, [DRIVER_TYPE, PLUGIN_TYPE]));
213
+
214
+ /**
215
+ * @type {Record<string,StrictSchemaObject>}
216
+ */
217
+ const finalizedSchemas = {};
218
+
219
+ const finalSchema = _.reduce(
220
+ this._registeredSchemas,
221
+ /**
222
+ * @param {typeof baseSchema} baseSchema
223
+ * @param {Map<string,SchemaObject>} extensionSchemas
224
+ * @param {ExtensionType} extType
225
+ */
226
+ (baseSchema, extensionSchemas, extType) => {
227
+ extensionSchemas.forEach((schema, extName) => {
228
+ const $ref = ArgSpec.toSchemaBaseRef(extType, extName);
229
+ schema.$id = $ref;
230
+ schema.additionalProperties = false; // this makes `schema` become a `StrictSchemaObject`
231
+ baseSchema.properties.server.properties[extType].properties[extName] = {
232
+ $ref,
233
+ $comment: extName,
234
+ };
235
+ ajv.validateSchema(schema, true);
236
+ addArgSpecs(schema.properties, extType, extName);
237
+ ajv.addSchema(schema, $ref);
238
+ finalizedSchemas[$ref] = /** @type {StrictSchemaObject} */ (schema);
239
+ });
240
+ return baseSchema;
241
+ },
242
+ baseSchema
243
+ );
244
+
245
+ ajv.addSchema(finalSchema, APPIUM_CONFIG_SCHEMA_ID);
246
+ finalizedSchemas[APPIUM_CONFIG_SCHEMA_ID] = finalSchema;
247
+ ajv.validateSchema(finalSchema, true);
248
+
249
+ this._finalizedSchemas = finalizedSchemas;
250
+ return Object.freeze(finalizedSchemas);
251
+ }
252
+
253
+ /**
254
+ * Configures and creates an Ajv instance.
255
+ * @private
256
+ * @returns {Ajv}
257
+ */
258
+ static _instantiateAjv() {
259
+ const ajv = addFormats(
260
+ new Ajv({
261
+ // without this not much validation actually happens
262
+ allErrors: true,
263
+ })
264
+ );
265
+
266
+ // add custom keywords to ajv. see schema-keywords.js
267
+ _.forEach(keywords, (keyword) => {
268
+ ajv.addKeyword(keyword);
269
+ });
270
+
271
+ return ajv;
272
+ }
273
+
274
+ /**
275
+ * Resets this instance to its original state.
276
+ *
277
+ * - Removes all added schemas from the `Ajv` instance
278
+ * - Resets the map of {@link ArgSpec ArgSpecs}
279
+ * - Resets the map of registered schemas
280
+ * - Sets the {@link AppiumSchema._finalized _finalized} flag to `false`
281
+ *
282
+ * If you need to call {@link AppiumSchema.finalize} again, you'll want to call this first.
283
+ * @returns {void}
284
+ */
285
+ reset() {
286
+ for (const schemaId of Object.keys(this._finalizedSchemas ?? {})) {
287
+ this._ajv.removeSchema(schemaId);
288
+ }
289
+ this._argSpecs = new RoachHotelMap();
290
+ this._registeredSchemas = {
291
+ [DRIVER_TYPE]: new Map(),
292
+ [PLUGIN_TYPE]: new Map(),
293
+ };
294
+ this._finalizedSchemas = null;
295
+
296
+ // Ajv seems to have an over-eager cache, so we have to dump the object entirely.
297
+ this._ajv = AppiumSchema._instantiateAjv();
298
+ }
299
+
300
+ /**
301
+ * Registers a schema from an extension.
302
+ *
303
+ * This is "fail-fast" in that the schema will immediately be validated against JSON schema draft-07 _or_ whatever the value of the schema's `$schema` prop is.
304
+ *
305
+ * Does _not_ add the schema to the `ajv` instance (this is done by {@link AppiumSchema.finalize}).
306
+ * @param {ExtensionType} extType - Extension type
307
+ * @param {string} extName - Unique extension name for `type`
308
+ * @param {SchemaObject} schema - Schema object
309
+ * @throws {SchemaNameConflictError} If the schema is an invalid
310
+ * @returns {void}
311
+ */
312
+ registerSchema(extType, extName, schema) {
313
+ if (!(extType && extName) || _.isUndefined(schema)) {
314
+ throw new TypeError('Expected extension type, extension name, and a defined schema');
315
+ }
316
+ if (!AppiumSchema.isSupportedSchemaType(schema)) {
317
+ throw new SchemaUnsupportedSchemaError(schema, extType, extName);
318
+ }
319
+ const normalizedExtName = _.kebabCase(extName);
320
+ if (this.hasRegisteredSchema(extType, normalizedExtName)) {
321
+ if (_.isEqual(this._registeredSchemas[extType].get(normalizedExtName), schema)) {
322
+ return;
323
+ }
324
+ throw new SchemaNameConflictError(extType, extName);
325
+ }
326
+ this._ajv.validateSchema(schema, true);
327
+
328
+ this._registeredSchemas[extType].set(normalizedExtName, schema);
329
+ }
330
+
331
+ /**
332
+ * Returns a {@link ArgSpec} for the given argument name.
333
+ * @param {string} name - CLI argument name
334
+ * @param {ExtensionType} [extType] - Extension type
335
+ * @param {string} [extName] - Extension name
336
+ * @returns {ArgSpec|undefined} ArgSpec or `undefined` if not found
337
+ */
338
+ getArgSpec(name, extType, extName) {
339
+ return this._argSpecs.get(ArgSpec.toArg(name, extType, extName));
340
+ }
341
+
342
+ /**
343
+ * Returns `true` if the instance knows about an argument by the given `name`.
344
+ * @param {string} name - CLI argument name
345
+ * @param {ExtensionType} [extType] - Extension type
346
+ * @param {string} [extName] - Extension name
347
+ * @returns {boolean} `true` if such an {@link ArgSpec} exists
348
+ */
349
+ hasArgSpec(name, extType, extName) {
350
+ return this._argSpecs.has(ArgSpec.toArg(name, extType, extName));
351
+ }
352
+
353
+ /**
354
+ * Returns a `Record` of argument "dest" strings to default values.
355
+ *
356
+ * The "dest" string is the property name in object returned by
357
+ * `argparse.ArgumentParser['parse_args']`.
358
+ * @template {boolean|undefined} Flattened
359
+ * @param {Flattened} [flatten=true] - If `true`, flattens the returned object
360
+ * using "keypath"-style keys of the format `<extType>.<extName>.<argName>`.
361
+ * Otherwise, returns a nested object using `extType` and `extName` as
362
+ * properties. Base arguments (server arguments) are always at the top level.
363
+ * @returns {DefaultValues<Flattened>}
364
+ */
365
+ getDefaults(flatten = /** @type {Flattened} */ (true)) {
366
+ if (!this.isFinalized()) {
367
+ throw new SchemaFinalizationError();
368
+ }
369
+
370
+ /**
371
+ * @private
372
+ * @callback DefaultReducer
373
+ * @param {DefaultValues<Flattened>} defaults
374
+ * @param {ArgSpec} argSpec
375
+ * @returns {DefaultValues<Flattened>}
376
+ */
377
+ /** @type {DefaultReducer} */
378
+ const reducer = flatten
379
+ ? (defaults, {defaultValue, dest}) => {
380
+ if (!_.isUndefined(defaultValue)) {
381
+ defaults[dest] = defaultValue;
382
+ }
383
+ return defaults;
384
+ }
385
+ : (defaults, {defaultValue, dest}) => {
386
+ if (!_.isUndefined(defaultValue)) {
387
+ _.set(defaults, dest, defaultValue);
388
+ }
389
+ return defaults;
390
+ };
391
+
392
+ /** @type {DefaultValues<Flattened>} */
393
+ const retval = {};
394
+ return [...this._argSpecs.values()].reduce(reducer, retval);
395
+ }
396
+
397
+ /**
398
+ * Returns a flattened Record of defaults for a specific extension. Keys will
399
+ * be of format `<argName>`.
400
+ * @param {ExtensionType} extType - Extension type
401
+ * @param {string} extName - Extension name
402
+ * @returns {Record<string,ArgSpecDefaultValue>}
403
+ */
404
+ getDefaultsForExtension(extType, extName) {
405
+ if (!this.isFinalized()) {
406
+ throw new SchemaFinalizationError();
407
+ }
408
+ const specs = [...this._argSpecs.values()].filter(
409
+ (spec) => spec.extType === extType && spec.extName === extName
410
+ );
411
+ return specs.reduce((defaults, {defaultValue, rawDest}) => {
412
+ if (!_.isUndefined(defaultValue)) {
413
+ defaults[rawDest] = defaultValue;
414
+ }
415
+ return defaults;
416
+ }, {});
417
+ }
418
+
419
+ /**
420
+ * Flatten schema into an array of `SchemaObject`s and associated
421
+ * {@link ArgSpec ArgSpecs}.
422
+ *
423
+ * Converts nested extension schemas to keys based on the extension type and
424
+ * name. Used when translating to `argparse` options or getting the list of
425
+ * default values (see {@link AppiumSchema.getDefaults}) for CLI or otherwise.
426
+ *
427
+ * The return value is an intermediate reprsentation used by `cli-args`
428
+ * module's `toParserArgs`, which converts the finalized schema to parameters
429
+ * used by `argparse`.
430
+ * @throws If {@link AppiumSchema.finalize} has not been called yet.
431
+ * @returns {FlattenedSchema}
432
+ */
433
+ flatten() {
434
+ const schema = this.getSchema();
435
+
436
+ /** @type { {properties: SchemaObject, prefix: string[]}[] } */
437
+ const stack = [{properties: schema.properties, prefix: []}];
438
+ /** @type {FlattenedSchema} */
439
+ const flattened = [];
440
+
441
+ // this bit is a recursive algorithm rewritten as a for loop.
442
+ // when we find something we want to traverse, we add it to `stack`
443
+ for (const {properties, prefix} of stack) {
444
+ const pairs = _.toPairs(properties);
445
+ for (const [key, value] of pairs) {
446
+ if (key === SCHEMA_KEY) {
447
+ continue;
448
+ }
449
+ const {properties, $ref} = value;
450
+ if (properties) {
451
+ stack.push({
452
+ properties,
453
+ prefix: key === SERVER_PROP_NAME ? [] : [...prefix, key],
454
+ });
455
+ } else if ($ref) {
456
+ let refSchema;
457
+ try {
458
+ refSchema = this.getSchema($ref);
459
+ } catch (err) {
460
+ // this can happen if an extension schema supplies a $ref to a non-existent schema
461
+ throw new SchemaUnknownSchemaError($ref);
462
+ }
463
+ const {normalizedExtName} = ArgSpec.extensionInfoFromRootSchemaId($ref);
464
+ if (!normalizedExtName) {
465
+ /* istanbul ignore next */
466
+ throw new ReferenceError(
467
+ `Could not determine extension name from schema ID ${$ref}. This is a bug.`
468
+ );
469
+ }
470
+ stack.push({
471
+ properties: refSchema.properties,
472
+ prefix: [...prefix, key, normalizedExtName],
473
+ });
474
+ } else if (key !== DRIVER_TYPE && key !== PLUGIN_TYPE) {
475
+ const [extType, extName] = prefix;
476
+ const argSpec = this.getArgSpec(key, /** @type {ExtensionType} */ (extType), extName);
477
+ if (!argSpec) {
478
+ /* istanbul ignore next */
479
+ throw new ReferenceError(
480
+ `Unknown argument with key ${key}, extType ${extType} and extName ${extName}. This is a bug.`
481
+ );
482
+ }
483
+ flattened.push({schema: _.cloneDeep(value), argSpec});
484
+ }
485
+ }
486
+ }
487
+
488
+ return flattened;
489
+ }
490
+
491
+ /**
492
+ * Retrieves the schema itself
493
+ * @public
494
+ * @param {string} [ref] - Schema ID
495
+ * @throws If the schema has not yet been finalized
496
+ * @returns {SchemaObject}
497
+ */
498
+ getSchema(ref = APPIUM_CONFIG_SCHEMA_ID) {
499
+ return /** @type {SchemaObject} */ (this._getValidator(ref).schema);
500
+ }
501
+
502
+ /**
503
+ * Retrieves schema validator function from Ajv
504
+ * @param {string} [id] - Schema ID
505
+ * @private
506
+ * @returns {import('ajv').ValidateFunction}
507
+ */
508
+ _getValidator(id = APPIUM_CONFIG_SCHEMA_ID) {
509
+ const validator = this._ajv.getSchema(id);
510
+ if (!validator) {
511
+ if (id === APPIUM_CONFIG_SCHEMA_ID) {
512
+ throw new SchemaFinalizationError();
513
+ } else {
514
+ throw new SchemaUnknownSchemaError(id);
515
+ }
516
+ }
517
+ return validator;
518
+ }
519
+
520
+ /**
521
+ * Given an object, validates it against the Appium config schema.
522
+ * If errors occur, the returned array will be non-empty.
523
+ * @param {any} value - The value (hopefully an object) to validate against the schema
524
+ * @param {string} [ref] - Schema ID or ref.
525
+ * @public
526
+ * @returns {import('ajv').ErrorObject[]} Array of errors, if any.
527
+ */
528
+ validate(value, ref = APPIUM_CONFIG_SCHEMA_ID) {
529
+ const validator = this._getValidator(ref);
530
+ return !validator(value) && _.isArray(validator.errors) ? [...validator.errors] : [];
531
+ }
532
+
533
+ /**
534
+ * Returns `true` if `filename`'s file extension is allowed (in {@link ALLOWED_SCHEMA_EXTENSIONS}).
535
+ * @param {string} filename
536
+ * @returns {boolean}
537
+ */
538
+ static isAllowedSchemaFileExtension(filename) {
539
+ return ALLOWED_SCHEMA_EXTENSIONS.has(path.extname(filename));
540
+ }
541
+
542
+ /**
543
+ * Returns `true` if `schema` is a plain object with a non-true `$async` property.
544
+ * @param {any} schema - Schema to check
545
+ * @returns {schema is SchemaObject}
546
+ */
547
+ static isSupportedSchemaType(schema) {
548
+ return _.isPlainObject(schema) && schema.$async !== true;
549
+ }
550
+ }
551
+
552
+ /**
553
+ * Thrown when the {@link AppiumSchema} instance has not yet been finalized, but
554
+ * the method called requires it.
555
+ */
556
+ export class SchemaFinalizationError extends Error {
557
+ /**
558
+ * @type {Readonly<string>}
559
+ */
560
+ code = 'APPIUMERR_SCHEMA_FINALIZATION';
561
+
562
+ constructor() {
563
+ super('Schema not yet finalized; `finalize()` must be called first.');
564
+ }
565
+ }
566
+
567
+ /**
568
+ * Thrown when a "unique" schema ID conflicts with an existing schema ID.
569
+ *
570
+ * This is likely going to be caused by attempting to register the same schema twice.
571
+ */
572
+ export class SchemaNameConflictError extends Error {
573
+ /**
574
+ * @type {Readonly<string>}
575
+ */
576
+ code = 'APPIUMERR_SCHEMA_NAME_CONFLICT';
577
+
578
+ /**
579
+ * @type {Readonly<{extType: ExtensionType, extName: string}>}
580
+ */
581
+ data;
582
+
583
+ /**
584
+ * @param {ExtensionType} extType
585
+ * @param {string} extName
586
+ */
587
+ constructor(extType, extName) {
588
+ super(`Name for ${extType} schema "${extName}" conflicts with an existing schema`);
589
+ this.data = {extType, extName};
590
+ }
591
+ }
592
+
593
+ /**
594
+ * Thrown when a schema ID was expected, but it doesn't exist on the {@link Ajv} instance.
595
+ */
596
+ export class SchemaUnknownSchemaError extends ReferenceError {
597
+ /**
598
+ * @type {Readonly<string>}
599
+ */
600
+ code = 'APPIUMERR_SCHEMA_UNKNOWN_SCHEMA';
601
+
602
+ /**
603
+ * @type {Readonly<{schemaId: string}>}
604
+ */
605
+ data;
606
+
607
+ /**
608
+ * @param {string} schemaId
609
+ */
610
+ constructor(schemaId) {
611
+ super(`Unknown schema: "${schemaId}"`);
612
+ this.data = {schemaId};
613
+ }
614
+ }
615
+
616
+ /**
617
+ * Thrown when a schema is provided, but it's of an unsupported type.
618
+ *
619
+ * "Valid" schemas which are unsupported include boolean schemas and async schemas
620
+ * (having a `true` `$async` property).
621
+ */
622
+ export class SchemaUnsupportedSchemaError extends TypeError {
623
+ /**
624
+ * @type {Readonly<string>}
625
+ */
626
+ code = 'APPIUMERR_SCHEMA_UNSUPPORTED_SCHEMA';
627
+
628
+ /**
629
+ * @type {Readonly<{schema: any, extType: ExtensionType, extName: string}>}
630
+ */
631
+ data;
632
+
633
+ /**
634
+ * @param {any} schema
635
+ * @param {ExtensionType} extType
636
+ * @param {string} extName
637
+ */
638
+ constructor(schema, extType, extName) {
639
+ // https://github.com/Microsoft/TypeScript/issues/8277
640
+ super(
641
+ (() => {
642
+ let msg = `Unsupported schema from ${extType} "${extName}":`;
643
+ if (_.isBoolean(schema)) {
644
+ return `${msg} schema cannot be a boolean`;
645
+ }
646
+ if (_.isPlainObject(schema)) {
647
+ if (schema.$async) {
648
+ return `${msg} schema cannot be an async schema`;
649
+ }
650
+ /* istanbul ignore next */
651
+ throw new TypeError(
652
+ `schema IS supported; this error should not be thrown (this is a bug). value of schema: ${JSON.stringify(
653
+ schema
654
+ )}`
655
+ );
656
+ }
657
+ return `${msg} schema must be a plain object without a true "$async" property`;
658
+ })()
659
+ );
660
+ this.data = {schema, extType, extName};
661
+ }
662
+ }
663
+
664
+ const appiumSchema = AppiumSchema.create();
665
+
666
+ export const {
667
+ registerSchema,
668
+ getAllArgSpecs,
669
+ getArgSpec,
670
+ hasArgSpec,
671
+ isFinalized,
672
+ finalize: finalizeSchema,
673
+ reset: resetSchema,
674
+ validate,
675
+ getSchema,
676
+ flatten: flattenSchema,
677
+ getDefaults: getDefaultsForSchema,
678
+ getDefaultsForExtension,
679
+ } = appiumSchema;
680
+ export const {isAllowedSchemaFileExtension} = AppiumSchema;
681
+
682
+ /**
683
+ * Appium only supports schemas that are plain objects; not arrays.
684
+ * @typedef {import('ajv').SchemaObject & {[key: number]: never}} SchemaObject
685
+ */
686
+
687
+ /**
688
+ * @typedef {import('@appium/types').ExtensionType} ExtensionType
689
+ */
690
+
691
+ /**
692
+ * An object having property `additionalProperties: false`
693
+ * @typedef StrictProp
694
+ * @property {false} additionalProperties
695
+ */
696
+
697
+ /**
698
+ * A {@link SchemaObject} with `additionalProperties: false`
699
+ * @typedef {SchemaObject & StrictProp} StrictSchemaObject
700
+ */
701
+
702
+ /**
703
+ * A list of schemas associated with properties and their corresponding {@link ArgSpec} objects.
704
+ *
705
+ * Intermediate data structure used when converting the entire schema down to CLI arguments.
706
+ * @typedef { {schema: SchemaObject, argSpec: ArgSpec}[] } FlattenedSchema
707
+ */
708
+
709
+ /**
710
+ * @typedef {ArgSpec['defaultValue']} ArgSpecDefaultValue
711
+ */
712
+
713
+ /**
714
+ * e.g. `{driver: {foo: 'bar'}}` where `foo` is the arg name and `bar` is the default value.
715
+ * @typedef {Record<string,Record<string,ArgSpecDefaultValue>>} NestedArgSpecDefaultValue
716
+ */
717
+
718
+ /**
719
+ * Helper type for the return value of {@link AppiumSchema.getDefaults}
720
+ * @template {boolean|undefined} Flattened
721
+ * @typedef {Record<string,Flattened extends true ? ArgSpecDefaultValue : ArgSpecDefaultValue | NestedArgSpecDefaultValue>} DefaultValues
722
+ */