appium 2.0.0-beta.4 → 2.0.0-beta.40

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 (151) hide show
  1. package/README.md +10 -11
  2. package/build/lib/appium.d.ts +204 -0
  3. package/build/lib/appium.d.ts.map +1 -0
  4. package/build/lib/appium.js +257 -131
  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 +25 -18
  11. package/build/lib/cli/extension-command.d.ts +372 -0
  12. package/build/lib/cli/extension-command.d.ts.map +1 -0
  13. package/build/lib/cli/extension-command.js +286 -156
  14. package/build/lib/cli/extension.d.ts +18 -0
  15. package/build/lib/cli/extension.d.ts.map +1 -0
  16. package/build/lib/cli/extension.js +30 -17
  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 +33 -0
  21. package/build/lib/cli/plugin-command.d.ts.map +1 -0
  22. package/build/lib/cli/plugin-command.js +24 -19
  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 +81 -0
  36. package/build/lib/extension/driver-config.d.ts.map +1 -0
  37. package/build/lib/extension/driver-config.js +177 -0
  38. package/build/lib/extension/extension-config.d.ts +242 -0
  39. package/build/lib/extension/extension-config.d.ts.map +1 -0
  40. package/build/lib/extension/extension-config.js +436 -0
  41. package/build/lib/extension/index.d.ts +48 -0
  42. package/build/lib/extension/index.d.ts.map +1 -0
  43. package/build/lib/extension/index.js +74 -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 +256 -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 +57 -0
  51. package/build/lib/extension/plugin-config.d.ts.map +1 -0
  52. package/build/lib/extension/plugin-config.js +78 -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 +14 -17
  62. package/build/lib/main.d.ts +55 -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 +59 -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-manifest.d.ts +55 -0
  92. package/build/types/extension-manifest.d.ts.map +1 -0
  93. package/build/types/index.d.ts +16 -0
  94. package/build/types/index.d.ts.map +1 -0
  95. package/driver.d.ts +1 -0
  96. package/driver.js +14 -0
  97. package/index.js +11 -0
  98. package/lib/appium.js +517 -186
  99. package/lib/cli/args.js +269 -422
  100. package/lib/cli/driver-command.js +58 -23
  101. package/lib/cli/extension-command.js +612 -260
  102. package/lib/cli/extension.js +34 -16
  103. package/lib/cli/parser.js +241 -83
  104. package/lib/cli/plugin-command.js +48 -20
  105. package/lib/cli/utils.js +24 -10
  106. package/lib/config-file.js +219 -0
  107. package/lib/config.js +210 -91
  108. package/lib/constants.js +69 -0
  109. package/lib/extension/driver-config.js +249 -0
  110. package/lib/extension/extension-config.js +679 -0
  111. package/lib/extension/index.js +116 -0
  112. package/lib/extension/manifest.js +475 -0
  113. package/lib/extension/package-changed.js +64 -0
  114. package/lib/extension/plugin-config.js +113 -0
  115. package/lib/grid-register.js +49 -35
  116. package/lib/logger.js +1 -2
  117. package/lib/logsink.js +38 -33
  118. package/lib/main.js +303 -100
  119. package/lib/schema/arg-spec.js +229 -0
  120. package/lib/schema/cli-args.js +238 -0
  121. package/lib/schema/cli-transformers.js +115 -0
  122. package/lib/schema/index.js +2 -0
  123. package/lib/schema/keywords.js +136 -0
  124. package/lib/schema/schema.js +717 -0
  125. package/lib/utils.js +121 -140
  126. package/package.json +75 -85
  127. package/plugin.d.ts +1 -0
  128. package/plugin.js +13 -0
  129. package/scripts/autoinstall-extensions.js +177 -0
  130. package/support.d.ts +1 -0
  131. package/support.js +13 -0
  132. package/types/appium-manifest.ts +73 -0
  133. package/types/cli.ts +146 -0
  134. package/types/extension-manifest.ts +64 -0
  135. package/types/index.ts +21 -0
  136. package/CHANGELOG.md +0 -3515
  137. package/bin/ios-webkit-debug-proxy-launcher.js +0 -71
  138. package/build/lib/cli/npm.js +0 -206
  139. package/build/lib/cli/parser-helpers.js +0 -82
  140. package/build/lib/driver-config.js +0 -77
  141. package/build/lib/drivers.js +0 -96
  142. package/build/lib/extension-config.js +0 -253
  143. package/build/lib/plugin-config.js +0 -59
  144. package/build/lib/plugins.js +0 -14
  145. package/lib/cli/npm.js +0 -183
  146. package/lib/cli/parser-helpers.js +0 -79
  147. package/lib/driver-config.js +0 -46
  148. package/lib/drivers.js +0 -81
  149. package/lib/extension-config.js +0 -209
  150. package/lib/plugin-config.js +0 -34
  151. package/lib/plugins.js +0 -10
@@ -0,0 +1,219 @@
1
+ import betterAjvErrors from '@sidvind/better-ajv-errors';
2
+ import {lilconfig} from 'lilconfig';
3
+ import _ from 'lodash';
4
+ import yaml from 'yaml';
5
+ import {getSchema, validate} from './schema/schema';
6
+
7
+ /**
8
+ * lilconfig loader to handle `.yaml` files
9
+ * @type {import('lilconfig').LoaderSync}
10
+ */
11
+ function yamlLoader(filepath, content) {
12
+ return yaml.parse(content);
13
+ }
14
+
15
+ /**
16
+ * A cache of the raw config file (a JSON string) at a filepath.
17
+ * This is used for better error reporting.
18
+ * Note that config files needn't be JSON, but it helps if they are.
19
+ * @type {Map<string,RawJson>}
20
+ */
21
+ const rawConfig = new Map();
22
+
23
+ /**
24
+ * Custom JSON loader that caches the raw config file (for use with `better-ajv-errors`).
25
+ * If it weren't for this cache, this would be unnecessary.
26
+ * @type {import('lilconfig').LoaderSync}
27
+ */
28
+ function jsonLoader(filepath, content) {
29
+ rawConfig.set(filepath, content);
30
+ return JSON.parse(content);
31
+ }
32
+
33
+ /**
34
+ * Loads a config file from an explicit path
35
+ * @param {LilconfigAsyncSearcher} lc - lilconfig instance
36
+ * @param {string} filepath - Path to config file
37
+ * @returns {Promise<import('lilconfig').LilconfigResult>}
38
+ */
39
+ async function loadConfigFile(lc, filepath) {
40
+ try {
41
+ // removing "await" will cause any rejection to _not_ be caught in this block!
42
+ return await lc.load(filepath);
43
+ } catch (/** @type {unknown} */ err) {
44
+ if (/** @type {NodeJS.ErrnoException} */ (err).code === 'ENOENT') {
45
+ /** @type {NodeJS.ErrnoException} */ (
46
+ err
47
+ ).message = `Config file not found at user-provided path: ${filepath}`;
48
+ throw err;
49
+ } else if (err instanceof SyntaxError) {
50
+ // generally invalid JSON
51
+ err.message = `Config file at user-provided path ${filepath} is invalid:\n${err.message}`;
52
+ throw err;
53
+ }
54
+ throw err;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Searches for a config file
60
+ * @param {LilconfigAsyncSearcher} lc - lilconfig instance
61
+ * @returns {Promise<import('lilconfig').LilconfigResult>}
62
+ */
63
+ async function searchConfigFile(lc) {
64
+ return await lc.search();
65
+ }
66
+
67
+ /**
68
+ * Given an array of errors and the result of loading a config file, generate a
69
+ * helpful string for the user.
70
+ *
71
+ * - If `opts` contains a `json` property, this should be the original JSON
72
+ * _string_ of the config file. This is only applicable if the config file
73
+ * was in JSON format. If present, it will associate line numbers with errors.
74
+ * - If `errors` happens to be empty, this will throw.
75
+ * @param {import('ajv').ErrorObject[]} errors - Non-empty array of errors. Required.
76
+ * @param {ReadConfigFileResult['config']|any} [config] -
77
+ * Configuration & metadata
78
+ * @param {FormatConfigErrorsOptions} [opts]
79
+ * @throws {TypeError} If `errors` is empty
80
+ * @returns {string}
81
+ */
82
+ export function formatErrors(errors = [], config = {}, opts = {}) {
83
+ if (errors && !errors.length) {
84
+ throw new TypeError('Array of errors must be non-empty');
85
+ }
86
+ return betterAjvErrors(getSchema(opts.schemaId), config, errors, {
87
+ json: opts.json,
88
+ format: 'cli',
89
+ });
90
+ }
91
+
92
+ /**
93
+ * Given an optional path, read a config file. Validates the config file.
94
+ *
95
+ * Call {@link validate} if you already have a config object.
96
+ * @param {string} [filepath] - Path to config file, if we have one
97
+ * @param {ReadConfigFileOptions} [opts] - Options
98
+ * @public
99
+ * @returns {Promise<ReadConfigFileResult>} Contains config and filepath, if found, and any errors
100
+ */
101
+ export async function readConfigFile(filepath, opts = {}) {
102
+ const lc = lilconfig('appium', {
103
+ loaders: {
104
+ '.yaml': yamlLoader,
105
+ '.yml': yamlLoader,
106
+ '.json': jsonLoader,
107
+ noExt: jsonLoader,
108
+ },
109
+ packageProp: 'appiumConfig',
110
+ });
111
+
112
+ const result = filepath ? await loadConfigFile(lc, filepath) : await searchConfigFile(lc);
113
+
114
+ if (result?.filepath && !result?.isEmpty) {
115
+ const {pretty = true} = opts;
116
+ try {
117
+ let configResult;
118
+ const errors = validate(result.config);
119
+ if (_.isEmpty(errors)) {
120
+ configResult = {...result, errors};
121
+ } else {
122
+ const reason = formatErrors(errors, result.config, {
123
+ json: rawConfig.get(result.filepath),
124
+ pretty,
125
+ });
126
+ configResult = reason ? {...result, errors, reason} : {...result, errors};
127
+ }
128
+
129
+ // normalize (to camel case) all top-level property names of the config file
130
+ configResult.config = normalizeConfig(/** @type {AppiumConfig} */ (configResult.config));
131
+
132
+ return configResult;
133
+ } finally {
134
+ // clean up the raw config file cache, which is only kept to better report errors.
135
+ rawConfig.delete(result.filepath);
136
+ }
137
+ }
138
+ return result ?? {};
139
+ }
140
+
141
+ /**
142
+ * Convert schema property names to either a) the value of the `appiumCliDest` property, if any; or b) camel-case
143
+ * @param {AppiumConfig} config - Configuration object
144
+ * @returns {NormalizedAppiumConfig} New object with camel-cased keys (or `dest` keys).
145
+ */
146
+ export function normalizeConfig(config) {
147
+ const schema = getSchema();
148
+ /**
149
+ * @param {AppiumConfig} config
150
+ * @param {string} [section] - Keypath (lodash `_.get()` style) to section of config. If omitted, assume root Appium config schema
151
+ * @todo Rewrite as a loop
152
+ * @returns Normalized section of config
153
+ */
154
+ const normalize = (config, section) => {
155
+ const obj = _.isUndefined(section) ? config : _.get(config, section, config);
156
+
157
+ const mappedObj = _.mapKeys(
158
+ obj,
159
+ (__, prop) => schema.properties[prop]?.appiumCliDest ?? _.camelCase(prop)
160
+ );
161
+
162
+ return _.mapValues(mappedObj, (value, property) => {
163
+ const nextSection = section ? `${section}.${property}` : property;
164
+ return isSchemaTypeObject(value) ? normalize(config, nextSection) : value;
165
+ });
166
+ };
167
+
168
+ /**
169
+ * Returns `true` if the schema prop references an object, or if it's an object itself
170
+ * @param {import('ajv').SchemaObject|object} schema - Referencing schema object
171
+ */
172
+ const isSchemaTypeObject = (schema) => Boolean(schema.properties);
173
+
174
+ return normalize(config);
175
+ }
176
+
177
+ /**
178
+ * Result of calling {@link readConfigFile}.
179
+ * @typedef ReadConfigFileResult
180
+ * @property {import('ajv').ErrorObject[]} [errors] - Validation errors
181
+ * @property {string} [filepath] - The path to the config file, if found
182
+ * @property {boolean} [isEmpty] - If `true`, the config file exists but is empty
183
+ * @property {NormalizedAppiumConfig} [config] - The parsed configuration
184
+ * @property {string|import('@sidvind/better-ajv-errors').IOutputError[]} [reason] - Human-readable error messages and suggestions. If the `pretty` option is `true`, this will be a nice string to print.
185
+ */
186
+
187
+ /**
188
+ * Options for {@link readConfigFile}.
189
+ * @typedef ReadConfigFileOptions
190
+ * @property {boolean} [pretty=true] If `false`, do not use color and fancy formatting in the `reason` property of the {@link ReadConfigFileResult}. The value of `reason` is then suitable for machine-reading.
191
+ */
192
+
193
+ /**
194
+ * This is an `AsyncSearcher` which is inexplicably _not_ exported by the `lilconfig` type definition.
195
+ * @typedef {ReturnType<import('lilconfig')["lilconfig"]>} LilconfigAsyncSearcher
196
+ */
197
+
198
+ /**
199
+ * The contents of an Appium config file. Generated from schema
200
+ * @typedef {import('@appium/types').AppiumConfig} AppiumConfig
201
+ */
202
+
203
+ /**
204
+ * The contents of an Appium config file with camelcased property names (and using `appiumCliDest` value if present). Generated from {@link AppiumConfig}
205
+ * @typedef {import('@appium/types').NormalizedAppiumConfig} NormalizedAppiumConfig
206
+ */
207
+
208
+ /**
209
+ * The string should be a raw JSON string.
210
+ * @typedef {string} RawJson
211
+ */
212
+
213
+ /**
214
+ * Options for {@link formatErrors}.
215
+ * @typedef FormatConfigErrorsOptions
216
+ * @property {import('./config-file').RawJson} [json] - Raw JSON config (as string)
217
+ * @property {boolean} [pretty=true] - Whether to format errors as a CLI-friendly string
218
+ * @property {string} [schemaId] - Specific ID of a prop; otherwise entire schema
219
+ */
package/lib/config.js CHANGED
@@ -1,14 +1,15 @@
1
+ /* eslint-disable no-console */
1
2
  import _ from 'lodash';
2
- import path from 'path';
3
- import { mkdirp, fs, system } from 'appium-support';
3
+ import {system, fs} from '@appium/support';
4
4
  import axios from 'axios';
5
- import { exec } from 'teen_process';
6
- import { rootDir } from './utils';
5
+ import {exec} from 'teen_process';
7
6
  import logger from './logger';
8
7
  import semver from 'semver';
8
+ import findUp from 'find-up';
9
+ import {getDefaultsForSchema, getAllArgSpecs} from './schema/schema';
9
10
 
11
+ const npmPackage = fs.readPackageJsonFrom(__dirname);
10
12
 
11
- const npmPackage = require(path.resolve(rootDir, 'package.json'));
12
13
  const APPIUM_VER = npmPackage.version;
13
14
  const MIN_NODE_VERSION = npmPackage.engines.node;
14
15
 
@@ -16,31 +17,46 @@ const GIT_META_ROOT = '.git';
16
17
  const GIT_BINARY = `git${system.isWindows() ? '.exe' : ''}`;
17
18
  const GITHUB_API = 'https://api.github.com/repos/appium/appium';
18
19
 
20
+ /**
21
+ * @type {import('appium/types').BuildInfo}
22
+ */
19
23
  const BUILD_INFO = {
20
24
  version: APPIUM_VER,
21
25
  };
22
26
 
23
- function getNodeVersion () {
24
- return semver.coerce(process.version);
27
+ function getNodeVersion() {
28
+ return /** @type {import('semver').SemVer} */ (semver.coerce(process.version));
25
29
  }
26
30
 
27
- async function updateBuildInfo (useGithubApiFallback = false) {
31
+ async function updateBuildInfo(useGithubApiFallback = false) {
28
32
  const sha = await getGitRev(useGithubApiFallback);
29
33
  if (!sha) {
30
34
  return;
31
35
  }
32
36
  BUILD_INFO['git-sha'] = sha;
33
37
  const built = await getGitTimestamp(sha, useGithubApiFallback);
34
- if (!_.isEmpty(built)) {
38
+ if (built) {
35
39
  BUILD_INFO.built = built;
36
40
  }
37
41
  }
38
42
 
39
- async function getGitRev (useGithubApiFallback = false) {
40
- if (await fs.exists(path.resolve(rootDir, GIT_META_ROOT))) {
43
+ /**
44
+ * Finds the Git metadata dir (see `GIT_META_ROOT`)
45
+ *
46
+ * This is needed because Appium cannot assume `package.json` and `.git` are in the same
47
+ * directory. Monorepos, see?
48
+ * @returns {Promise<string|undefined>} Path to dir or `undefined` if not found
49
+ */
50
+ async function findGitRoot() {
51
+ return await findUp(GIT_META_ROOT, {cwd: rootDir, type: 'directory'});
52
+ }
53
+
54
+ async function getGitRev(useGithubApiFallback = false) {
55
+ const gitRoot = await findGitRoot();
56
+ if (gitRoot) {
41
57
  try {
42
58
  const {stdout} = await exec(GIT_BINARY, ['rev-parse', 'HEAD'], {
43
- cwd: rootDir
59
+ cwd: gitRoot,
44
60
  });
45
61
  return stdout.trim();
46
62
  } catch (ign) {}
@@ -51,11 +67,13 @@ async function getGitRev (useGithubApiFallback = false) {
51
67
  }
52
68
 
53
69
  try {
54
- const resBodyObj = (await axios.get(`${GITHUB_API}/tags`, {
55
- headers: {
56
- 'User-Agent': `Appium ${APPIUM_VER}`
57
- }
58
- })).data;
70
+ const resBodyObj = (
71
+ await axios.get(`${GITHUB_API}/tags`, {
72
+ headers: {
73
+ 'User-Agent': `Appium ${APPIUM_VER}`,
74
+ },
75
+ })
76
+ ).data;
59
77
  if (_.isArray(resBodyObj)) {
60
78
  for (const {name, commit} of resBodyObj) {
61
79
  if (name === `v${APPIUM_VER}` && commit && commit.sha) {
@@ -67,11 +85,17 @@ async function getGitRev (useGithubApiFallback = false) {
67
85
  return null;
68
86
  }
69
87
 
70
- async function getGitTimestamp (commitSha, useGithubApiFallback = false) {
71
- if (await fs.exists(path.resolve(rootDir, GIT_META_ROOT))) {
88
+ /**
89
+ * @param {string} commitSha
90
+ * @param {boolean} [useGithubApiFallback]
91
+ * @returns {Promise<string?>}
92
+ */
93
+ async function getGitTimestamp(commitSha, useGithubApiFallback = false) {
94
+ const gitRoot = await findGitRoot();
95
+ if (gitRoot) {
72
96
  try {
73
97
  const {stdout} = await exec(GIT_BINARY, ['show', '-s', '--format=%ci', commitSha], {
74
- cwd: rootDir
98
+ cwd: gitRoot,
75
99
  });
76
100
  return stdout.trim();
77
101
  } catch (ign) {}
@@ -82,11 +106,13 @@ async function getGitTimestamp (commitSha, useGithubApiFallback = false) {
82
106
  }
83
107
 
84
108
  try {
85
- const resBodyObj = (await axios.get(`${GITHUB_API}/commits/${commitSha}`, {
86
- headers: {
87
- 'User-Agent': `Appium ${APPIUM_VER}`
88
- }
89
- })).data;
109
+ const resBodyObj = (
110
+ await axios.get(`${GITHUB_API}/commits/${commitSha}`, {
111
+ headers: {
112
+ 'User-Agent': `Appium ${APPIUM_VER}`,
113
+ },
114
+ })
115
+ ).data;
90
116
  if (resBodyObj && resBodyObj.commit) {
91
117
  if (resBodyObj.commit.committer && resBodyObj.commit.committer.date) {
92
118
  return resBodyObj.commit.committer.date;
@@ -100,28 +126,28 @@ async function getGitTimestamp (commitSha, useGithubApiFallback = false) {
100
126
  }
101
127
 
102
128
  /**
103
- * @return Mutable object containing Appium build information. By default it
129
+ * Mutable object containing Appium build information. By default it
104
130
  * only contains the Appium version, but is updated with the build timestamp
105
131
  * and git commit hash asynchronously as soon as `updateBuildInfo` is called
106
132
  * and succeeds.
133
+ * @returns {import('appium/types').BuildInfo}
107
134
  */
108
- function getBuildInfo () {
135
+ function getBuildInfo() {
109
136
  return BUILD_INFO;
110
137
  }
111
138
 
112
- function checkNodeOk () {
139
+ function checkNodeOk() {
113
140
  const version = getNodeVersion();
114
141
  if (!semver.satisfies(version, MIN_NODE_VERSION)) {
115
142
  logger.errorAndThrow(`Node version must be ${MIN_NODE_VERSION}. Currently ${version.version}`);
116
143
  }
117
144
  }
118
145
 
119
- function warnNodeDeprecations () {
146
+ function warnNodeDeprecations() {
120
147
  /**
121
148
  * Uncomment this section to get node version deprecation warnings
122
149
  * Also add test cases to config-specs.js to cover the cases added
123
150
  **/
124
-
125
151
  // const version = getNodeVersion();
126
152
  // if (version.major < 8) {
127
153
  // logger.warn(`Appium support for versions of node < ${version.major} has been ` +
@@ -130,83 +156,176 @@ function warnNodeDeprecations () {
130
156
  // }
131
157
  }
132
158
 
133
- async function showConfig () {
159
+ async function showBuildInfo() {
134
160
  await updateBuildInfo(true);
135
161
  console.log(JSON.stringify(getBuildInfo())); // eslint-disable-line no-console
136
162
  }
137
163
 
138
- function getNonDefaultArgs (parser, args) {
139
- let nonDefaults = {};
140
- for (let rawArg of parser.rawArgs) {
141
- let arg = rawArg[1].dest;
142
- if (args[arg] && args[arg] !== rawArg[1].defaultValue) {
143
- nonDefaults[arg] = args[arg];
144
- }
145
- }
146
- return nonDefaults;
147
- }
164
+ /**
165
+ * Returns k/v pairs of server arguments which are _not_ the defaults.
166
+ * @param {Args} parsedArgs
167
+ * @returns {Args}
168
+ */
169
+ function getNonDefaultServerArgs(parsedArgs) {
170
+ /**
171
+ * Flattens parsed args into a single level object for comparison with
172
+ * flattened defaults across server args and extension args.
173
+ * @param {Args} args
174
+ * @returns {Record<string, { value: any, argSpec: ArgSpec }>}
175
+ */
176
+ const flatten = (args) => {
177
+ const argSpecs = getAllArgSpecs();
178
+ const flattened = _.reduce(
179
+ [...argSpecs.values()],
180
+ (acc, argSpec) => {
181
+ if (_.has(args, argSpec.dest)) {
182
+ acc[argSpec.dest] = {value: _.get(args, argSpec.dest), argSpec};
183
+ }
184
+ return acc;
185
+ },
186
+ /** @type {Record<string, { value: any, argSpec: ArgSpec }>} */ ({})
187
+ );
148
188
 
149
- function checkValidPort (port, portName) {
150
- if (port > 0 && port < 65536) return true; // eslint-disable-line curly
151
- logger.error(`Port '${portName}' must be greater than 0 and less than 65536. Currently ${port}`);
152
- return false;
153
- }
189
+ return flattened;
190
+ };
154
191
 
155
- function validateServerArgs (parser, args) {
156
- // arguments that cannot both be set
157
- let exclusives = [
158
- ['noReset', 'fullReset'],
159
- ['ipa', 'safari'],
160
- ['app', 'safari'],
161
- ['forceIphone', 'forceIpad'],
162
- ['deviceName', 'defaultDevice']
163
- ];
164
-
165
- for (let exSet of exclusives) {
166
- let numFoundInArgs = 0;
167
- for (let opt of exSet) {
168
- if (_.has(args, opt) && args[opt]) {
169
- numFoundInArgs++;
170
- }
171
- }
172
- if (numFoundInArgs > 1) {
173
- throw new Error(`You can't pass in more than one argument from the ` +
174
- `set ${JSON.stringify(exSet)}, since they are ` +
175
- `mutually exclusive`);
176
- }
177
- }
192
+ const args = flatten(parsedArgs);
178
193
 
179
- const validations = {
180
- port: checkValidPort,
181
- callbackPort: checkValidPort,
182
- bootstrapPort: checkValidPort,
183
- chromedriverPort: checkValidPort,
184
- robotPort: checkValidPort,
185
- backendRetries: (r) => r >= 0
186
- };
194
+ // hopefully these function names are descriptive enough
195
+ const typesDiffer = /** @param {string} dest */ (dest) =>
196
+ typeof args[dest].value !== typeof defaultsFromSchema[dest];
187
197
 
188
- const nonDefaultArgs = getNonDefaultArgs(parser, args);
198
+ const defaultValueIsArray = /** @param {string} dest */ (dest) =>
199
+ _.isArray(defaultsFromSchema[dest]);
189
200
 
190
- for (let [arg, validator] of _.toPairs(validations)) {
191
- if (_.has(nonDefaultArgs, arg)) {
192
- if (!validator(args[arg], arg)) {
193
- throw new Error(`Invalid argument for param ${arg}: ${args[arg]}`);
194
- }
195
- }
201
+ const argsValueIsArray = /** @param {string} dest */ (dest) => _.isArray(args[dest].value);
202
+
203
+ const arraysDiffer = /** @param {string} dest */ (dest) =>
204
+ _.gt(_.size(_.difference(args[dest].value, defaultsFromSchema[dest])), 0);
205
+
206
+ const valuesDiffer = /** @param {string} dest */ (dest) =>
207
+ args[dest].value !== defaultsFromSchema[dest];
208
+
209
+ const defaultIsDefined = /** @param {string} dest */ (dest) =>
210
+ !_.isUndefined(defaultsFromSchema[dest]);
211
+
212
+ // note that `_.overEvery` is like an "AND", and `_.overSome` is like an "OR"
213
+
214
+ const argValueNotArrayOrArraysDiffer = _.overSome([_.negate(argsValueIsArray), arraysDiffer]);
215
+
216
+ const defaultValueNotArrayAndValuesDiffer = _.overEvery([
217
+ _.negate(defaultValueIsArray),
218
+ valuesDiffer,
219
+ ]);
220
+
221
+ /**
222
+ * This used to be a hideous conditional, but it's broken up into a hideous function instead.
223
+ * hopefully this makes things a little more understandable.
224
+ * - checks if the default value is defined
225
+ * - if so, and the default is not an array:
226
+ * - ensures the types are the same
227
+ * - ensures the values are equal
228
+ * - if so, and the default is an array:
229
+ * - ensures the args value is an array
230
+ * - ensures the args values do not differ from the default values
231
+ * @type {(dest: string) => boolean}
232
+ */
233
+ const isNotDefault = _.overEvery([
234
+ defaultIsDefined,
235
+ _.overSome([
236
+ typesDiffer,
237
+ _.overEvery([defaultValueIsArray, argValueNotArrayOrArraysDiffer]),
238
+ defaultValueNotArrayAndValuesDiffer,
239
+ ]),
240
+ ]);
241
+
242
+ const defaultsFromSchema = getDefaultsForSchema(true);
243
+
244
+ return _.reduce(
245
+ _.pickBy(args, (__, key) => isNotDefault(key)),
246
+ // explodes the flattened object back into nested one
247
+ (acc, {value, argSpec}) => _.set(acc, argSpec.dest, value),
248
+ /** @type {Args} */ ({})
249
+ );
250
+ }
251
+
252
+ /**
253
+ * Compacts an object for {@link showConfig}:
254
+ * 1. Removes `subcommand` key/value
255
+ * 2. Removes `undefined` values
256
+ * 3. Removes empty objects (but not `false` values)
257
+ * Does not operate recursively.
258
+ */
259
+ const compactConfig = _.partial(
260
+ _.omitBy,
261
+ _,
262
+ (value, key) =>
263
+ key === 'subcommand' || _.isUndefined(value) || (_.isObject(value) && _.isEmpty(value))
264
+ );
265
+
266
+ /**
267
+ * Shows a breakdown of the current config after CLI params, config file loaded & defaults applied.
268
+ *
269
+ * The actual shape of `preConfigParsedArgs` and `defaults` does not matter for the purposes of this function,
270
+ * but it's intended to be called with values of type {@link ParsedArgs} and `DefaultValues<true>`, respectively.
271
+ *
272
+ * @param {Partial<ParsedArgs>} nonDefaultPreConfigParsedArgs - Parsed CLI args (or param to `init()`) before config & defaults applied
273
+ * @param {import('./config-file').ReadConfigFileResult} configResult - Result of attempting to load a config file. _Must_ be normalized
274
+ * @param {Partial<ParsedArgs>} defaults - Configuration defaults from schemas
275
+ * @param {ParsedArgs} parsedArgs - Entire parsed args object
276
+ */
277
+ function showConfig(nonDefaultPreConfigParsedArgs, configResult, defaults, parsedArgs) {
278
+ console.log('Appium Configuration\n');
279
+ console.log('from defaults:\n');
280
+ console.dir(compactConfig(defaults));
281
+ if (configResult.config) {
282
+ console.log(`\nfrom config file at ${configResult.filepath}:\n`);
283
+ console.dir(compactConfig(configResult.config));
284
+ } else {
285
+ console.log(`\n(no configuration file loaded)`);
286
+ }
287
+ if (_.isEmpty(nonDefaultPreConfigParsedArgs)) {
288
+ console.log(`\n(no CLI parameters provided)`);
289
+ } else {
290
+ console.log('\nvia CLI or function call:\n');
291
+ console.dir(compactConfig(nonDefaultPreConfigParsedArgs));
196
292
  }
293
+ console.log('\nfinal configuration:\n');
294
+ console.dir(compactConfig(parsedArgs));
197
295
  }
198
296
 
199
- async function validateTmpDir (tmpDir) {
297
+ /**
298
+ * @param {string} tmpDir
299
+ */
300
+ async function validateTmpDir(tmpDir) {
200
301
  try {
201
- await mkdirp(tmpDir);
302
+ await fs.mkdirp(tmpDir);
202
303
  } catch (e) {
203
- throw new Error(`We could not ensure that the temp dir you specified ` +
204
- `(${tmpDir}) exists. Please make sure it's writeable.`);
304
+ throw new Error(
305
+ `We could not ensure that the temp dir you specified ` +
306
+ `(${tmpDir}) exists. Please make sure it's writeable.`
307
+ );
205
308
  }
206
309
  }
207
310
 
311
+ const rootDir = fs.findRoot(__dirname);
312
+
208
313
  export {
209
- getBuildInfo, validateServerArgs, checkNodeOk, showConfig,
210
- warnNodeDeprecations, validateTmpDir, getNonDefaultArgs,
211
- getGitRev, checkValidPort, APPIUM_VER, updateBuildInfo,
314
+ getBuildInfo,
315
+ checkNodeOk,
316
+ showBuildInfo,
317
+ warnNodeDeprecations,
318
+ validateTmpDir,
319
+ getNonDefaultServerArgs,
320
+ getGitRev,
321
+ APPIUM_VER,
322
+ updateBuildInfo,
323
+ showConfig,
324
+ rootDir,
212
325
  };
326
+
327
+ /**
328
+ * @typedef {import('appium/types').ParsedArgs} ParsedArgs
329
+ * @typedef {import('appium/types').Args} Args
330
+ * @typedef {import('./schema/arg-spec').ArgSpec} ArgSpec
331
+ */
@@ -0,0 +1,69 @@
1
+ import path from 'path';
2
+
3
+ /**
4
+ * The name of the extension type for drivers
5
+ */
6
+ export const DRIVER_TYPE = 'driver';
7
+
8
+ /**
9
+ * The name of the extension type for plugins
10
+ */
11
+ export const PLUGIN_TYPE = 'plugin';
12
+
13
+ /**
14
+ * The `server` command of the `appium` CLI
15
+ */
16
+ export const SERVER_SUBCOMMAND = 'server';
17
+
18
+ /**
19
+ * The value of `--use-plugins` if _all_ plugins should be loaded
20
+ */
21
+ export const USE_ALL_PLUGINS = 'all';
22
+
23
+ // This is a map of plugin names to npm packages representing those plugins.
24
+ // The plugins in this list will be available to the CLI so users can just
25
+ // type 'appium plugin install 'name'', rather than having to specify the full
26
+ // npm package. I.e., these are the officially recognized plugins.
27
+ export const KNOWN_PLUGINS = Object.freeze(
28
+ /** @type {const} */ ({
29
+ images: '@appium/images-plugin',
30
+ 'execute-driver': '@appium/execute-driver-plugin',
31
+ 'relaxed-caps': '@appium/relaxed-caps-plugin',
32
+ })
33
+ );
34
+
35
+ // This is a map of driver names to npm packages representing those drivers.
36
+ // The drivers in this list will be available to the CLI so users can just
37
+ // type 'appium driver install 'name'', rather than having to specify the full
38
+ // npm package. I.e., these are the officially recognized drivers.
39
+ export const KNOWN_DRIVERS = Object.freeze(
40
+ /** @type {const} */ ({
41
+ uiautomator2: 'appium-uiautomator2-driver',
42
+ xcuitest: 'appium-xcuitest-driver',
43
+ youiengine: 'appium-youiengine-driver',
44
+ windows: 'appium-windows-driver',
45
+ mac: 'appium-mac-driver',
46
+ mac2: 'appium-mac2-driver',
47
+ espresso: 'appium-espresso-driver',
48
+ tizen: 'appium-tizen-driver',
49
+ flutter: 'appium-flutter-driver',
50
+ safari: 'appium-safari-driver',
51
+ gecko: 'appium-geckodriver',
52
+ })
53
+ );
54
+
55
+ /**
56
+ * Relative path to directory containing any Appium internal files
57
+ */
58
+ export const CACHE_DIR_RELATIVE_PATH = path.join('node_modules', '.cache', 'appium');
59
+
60
+ /**
61
+ * Relative path to hashfile (from `APPIUM_HOME`) of consuming project's `package.json` (if it exists)
62
+ */
63
+ export const PKG_HASHFILE_RELATIVE_PATH = path.join(CACHE_DIR_RELATIVE_PATH, 'package.hash');
64
+
65
+ export const EXT_SUBCOMMAND_LIST = 'list';
66
+ export const EXT_SUBCOMMAND_INSTALL = 'install';
67
+ export const EXT_SUBCOMMAND_UNINSTALL = 'uninstall';
68
+ export const EXT_SUBCOMMAND_UPDATE = 'update';
69
+ export const EXT_SUBCOMMAND_RUN = 'run';