forked from MetaMask/metamask-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
455 lines (436 loc) · 14.5 KB
/
cli.ts
File metadata and controls
455 lines (436 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/**
* @file This file contains the CLI parser for the webpack build script.
* It is responsible for parsing the command line arguments and returning a
* structured object representing the parsed arguments.
*/
import type { Options as YargsOptions } from 'yargs';
import yargs from 'yargs/yargs';
import parser from 'yargs-parser';
import type { BuildTypesConfig } from '../../lib/build-type';
import {
Browsers,
type Manifest,
type Browser,
uniqueSort,
toOrange,
} from './helpers';
import { ENVIRONMENT } from './constants';
const environmentOptions = Object.values(ENVIRONMENT);
const ENV_PREFIX = 'BUNDLE';
const addFeat = 'addFeature' as const;
const omitFeat = 'omitFeature' as const;
type YargsOptionsMap = { [key: string]: YargsOptions };
type OptionsKeys = keyof Omit<Options, typeof addFeat | typeof omitFeat>;
/**
* Some options affect the default values of other options.
*/
const prerequisites = {
env: {
alias: 'e',
array: false,
default: 'development' as const,
description: 'Enables/disables production optimizations/development hints',
choices: ['development', 'production'] as const,
group: toOrange('Build options:'),
type: 'string',
},
// `as const` makes it easier for developers to see the values of the type
// when hovering over it in their IDE. `satisfies Options` enables type
// checking, without loosing the `const` property of the values, which is
// necessary for yargs to infer the final types
} as const satisfies YargsOptionsMap;
/**
* Parses the given args from `argv` and returns whether or not the requested
* build is a production build or not.
*
* @param argv
* @param opts
* @returns `true` if this is a production build, otherwise `false`
*/
function preParse(
argv: string[],
opts: typeof prerequisites,
): { env: 'production' | 'development' } {
const options: { [k: string]: { [k: string]: unknown } } = {
configuration: {
envPrefix: ENV_PREFIX,
},
};
// convert the `opts` object into a format that `yargs-parser` can understand
for (const [arg, val] of Object.entries(opts)) {
for (const [key, valEntry] of Object.entries(val)) {
if (!options[key]) {
options[key] = {};
}
options[key][arg] = valEntry;
}
}
const { env } = parser(argv, options);
return { env };
}
/**
* Type representing the parsed arguments
*/
export type Args = ReturnType<typeof parseArgv>['args'];
export type Features = ReturnType<typeof parseArgv>['features'];
/**
* Parses an array of command line arguments into a structured format.
*
* @param argv - An array of command line arguments, excluding the program
* executable and file name. Typically used as
* `parseArgv(process.argv.slice(2))`.
* @param buildConfig - The build config.
* @param buildConfig.buildTypes - The build types.
* @param buildConfig.features - The features.
* @returns An object representing the parsed arguments.
*/
export function parseArgv(
argv: string[],
{ buildTypes, features }: BuildTypesConfig,
) {
const allBuildTypeNames = Object.keys(buildTypes);
const allFeatureNames = Object.keys(features);
// args like `production` may change our CLI defaults, so we pre-parse them
const preconditions = preParse(argv, prerequisites);
const options = getOptions(preconditions, allBuildTypeNames, allFeatureNames);
const args = getCli(options, 'yarn webpack').parseSync(argv);
// the properties `$0` and `_` are added by yargs, but we don't need them. We
// transform `add` and `omit`, so we also remove them from the config object.
const { $0, _, addFeature: add, omitFeature: omit, ...config } = args;
// set up feature flags
const active = new Set<string>();
const defaultFeaturesForBuildType = buildTypes[config.type].features ?? [];
const setActive = (f: string) => omit.includes(f) || active.add(f);
[defaultFeaturesForBuildType, add].forEach((feat) => feat.forEach(setActive));
const ignore = new Set(['$0', 'conf', 'progress', 'stats', 'watch']);
const cacheKey = Object.entries(args)
.filter(([key]) => key.length > 1 && !ignore.has(key) && !key.includes('-'))
.sort(([x], [y]) => x.localeCompare(y));
return {
// narrow the `config` type to only the options we're returning
args: config as { [key in OptionsKeys]: (typeof config)[key] },
cacheKey: JSON.stringify(cacheKey),
features: {
active,
all: new Set(allFeatureNames),
},
};
}
/**
* Gets a yargs instance for parsing CLI arguments.
*
* @param options
* @param name
*/
// TODO: Fix in https://github.com/MetaMask/metamask-extension/issues/31860
// eslint-disable-next-line @typescript-eslint/naming-convention
function getCli<T extends YargsOptionsMap = Options>(options: T, name: string) {
const cli = yargs()
// Ensure unrecognized commands/options are reported as errors.
.strict()
// disable yargs's version, as we use it ourselves
.version(false)
// use the scriptName in `--help` output
.scriptName(name)
// wrap output at a maximum of 120 characters or `process.stdout.columns`
.wrap(Math.min(120, process.stdout.columns))
// enable the `--config` command, which allows the user to specify a custom
// config file containing webpack options
.config()
.parserConfiguration({
'strip-aliased': true,
'strip-dashed': true,
})
// enable ENV parsing, which allows the user to specify webpack options via
// environment variables prefixed with `BUNDLE_`
// TODO: choose a better name than `BUNDLE` (it looks like `MM` is already being used in CI for ✨something✨)
.env(ENV_PREFIX)
// TODO: enable completion once https://github.com/yargs/yargs/pull/2422 is released.
// enable the `completion` command, which outputs a bash completion script
// .completion(
// 'completion',
// 'Enable bash/zsh completions; concat the script generated by running this command to your .bashrc or .bash_profile',
// )
.example(
'$0 --env development --browser firefox --browser chrome --zip',
'Builds the extension for development for Chrome & Firefox; generate zip files for both',
)
// TODO: enable completion once https://github.com/yargs/yargs/pull/2422 is released.
// .example(
// '$0 completion',
// `Generates a bash completion script for the \`${name}\` command`,
// )
.updateStrings({
'Options:': toOrange('Options:'),
'Examples:': toOrange('Examples:'),
})
.options(options);
return cli;
}
type Options = ReturnType<typeof getOptions>;
function getOptions(
{ env }: ReturnType<typeof preParse>,
buildTypes: string[],
allFeatures: string[],
) {
const isProduction = env === 'production';
const prodDefaultDesc = "If `env` is 'production', `true`, otherwise `false`";
return {
watch: {
alias: 'w',
array: false,
default: false,
description: 'Build then watch for files changes',
group: toOrange('Developer assistance:'),
type: 'boolean',
},
cache: {
alias: 'c',
array: false,
default: true,
description: 'Cache build for faster rebuilds',
group: toOrange('Developer assistance:'),
type: 'boolean',
},
progress: {
alias: 'p',
array: false,
default: true,
description: 'Show build progress',
group: toOrange('Developer assistance:'),
type: 'boolean',
},
devtool: {
alias: 'd',
array: false,
default: isProduction ? 'hidden-source-map' : 'source-map',
defaultDescription:
"If `env` is 'production', 'hidden-source-map', otherwise 'source-map'",
description: 'Sourcemap type to generate',
choices: ['none', 'source-map', 'hidden-source-map'] as const,
group: toOrange('Developer assistance:'),
type: 'string',
},
sentry: {
array: false,
default: isProduction,
defaultDescription: prodDefaultDesc,
description: 'Enables/disables Sentry Application Monitoring',
group: toOrange('Developer assistance:'),
type: 'boolean',
},
test: {
array: false,
default: false,
description: 'Enables/disables testing mode',
group: toOrange('Developer assistance:'),
type: 'boolean',
},
reactCompilerVerbose: {
array: false,
default: false,
description:
'Enables/disables React Compiler verbose mode and statistics',
group: toOrange('Developer assistance:'),
type: 'boolean',
},
reactCompilerDebug: {
array: false,
choices: ['all', 'critical', 'none'] as const,
default: 'none',
description:
'Sets React Compiler panic threshold that fails the build for all errors or critical errors only. If `none`, the build will not fail.',
group: toOrange('Developer assistance:'),
type: 'string',
},
...prerequisites,
zip: {
alias: 'z',
array: false,
default: false,
description: 'Generate a zip file of the build',
group: toOrange('Build options:'),
type: 'boolean',
},
minify: {
alias: 'm',
array: false,
default: isProduction,
defaultDescription: "If `env` is 'production', `true`, otherwise `false`",
description: 'Minify the output',
group: toOrange('Build options:'),
type: 'boolean',
},
browser: {
alias: 'b',
array: true,
choices: ['all', ...Browsers],
coerce: (browsers: (Browser | 'all')[]) => {
type OneOrMoreBrowsers = [Browser, ...Browser[]];
// sort browser for determinism (important for caching)
const set = new Set<Browser | 'all'>(browsers.sort());
return (set.has('all') ? [...Browsers] : [...set]) as OneOrMoreBrowsers;
},
default: 'chrome',
description: 'Browsers to build for',
group: toOrange('Build options:'),
type: 'string',
},
// TODO: Fix in https://github.com/MetaMask/metamask-extension/issues/31860
// eslint-disable-next-line @typescript-eslint/naming-convention
manifest_version: {
alias: 'v',
array: false,
choices: [2, 3] as Manifest['manifest_version'][],
default: 3 as Manifest['manifest_version'],
description: "Changes manifest.json format to the given version's schema",
group: toOrange('Build options:'),
type: 'number',
},
releaseVersion: {
alias: 'r',
array: false,
default: 0,
description:
'The (pre)release version of the extension, e.g., the `6` in `18.7.25-flask.6`.',
group: toOrange('Build options:'),
type: 'number',
},
type: {
alias: 't',
array: false,
choices: ['none', ...buildTypes],
default: 'main' as const,
description: 'Select the build type (main, beta, etc)',
group: toOrange('Build options:'),
type: 'string',
},
[addFeat]: {
alias: 'a',
array: true,
choices: allFeatures,
coerce: uniqueSort,
default: [] as typeof allFeatures,
description: 'Add features to be included in the selected build `type`',
group: toOrange('Build options:'),
type: 'string',
},
[omitFeat]: {
alias: 'o',
array: true,
choices: allFeatures,
coerce: uniqueSort,
default: [] as typeof allFeatures,
description: 'Omit features from the selected build `type`',
group: toOrange('Build options:'),
type: 'string',
},
validateEnv: {
array: false,
default: isProduction,
defaultDescription: prodDefaultDesc,
description:
'Validate environment variables against builds.yml declarations',
group: toOrange('Build options:'),
type: 'boolean',
},
lavamoat: {
alias: 'l',
array: false,
default: isProduction,
defaultDescription: prodDefaultDesc,
description: 'Apply LavaMoat to the build assets',
group: toOrange('Security:'),
type: 'boolean',
},
lavamoatDebug: {
alias: 'u',
array: false,
default: false,
description:
'Enables/disables LavaMoat debug mode (ignored if `lavamoat` is not enabled)',
group: toOrange('Security:'),
type: 'boolean',
},
generatePolicy: {
alias: 'g',
array: false,
default: false,
description: 'Generate the LavaMoat policy',
group: toOrange('Security:'),
type: 'boolean',
},
snow: {
alias: 's',
array: false,
default: isProduction,
defaultDescription: prodDefaultDesc,
description: 'Apply Snow to the build assets',
group: toOrange('Security:'),
type: 'boolean',
},
targetEnvironment: {
array: false,
choices: environmentOptions,
defaultDescription:
'Auto-detected from git context (branch name, CI environment)',
description:
'The build environment (production, staging, release-candidate, pull-request, other). ' +
'Controls Sentry project targeting and feature flag detection. ' +
'If not specified, auto-detected from git context.',
group: toOrange('Build options:'),
type: 'string',
},
dryRun: {
array: false,
default: false,
description: 'Output the config without building',
group: toOrange('Options:'),
type: 'boolean',
},
stats: {
array: false,
default: false,
description: 'Display build stats after building',
group: toOrange('Options:'),
type: 'boolean',
},
} as const satisfies YargsOptionsMap;
}
/**
* Returns a string representation of the given arguments and features.
*
* @param args - The parsed CLI arguments
* @param features - The active and available features
* @param resolvedEnvironment - The resolved MetaMask environment
*/
export function getDryRunMessage(
args: Args,
features: Features,
resolvedEnvironment: string,
) {
return `🦊 Build Config 🦊
Environment (--env): ${args.env}
Target Environment: ${resolvedEnvironment}${resolvedEnvironment === args.targetEnvironment ? '' : ' (auto-detected)'}
Minify: ${args.minify}
Watch: ${args.watch}
Cache: ${args.cache}
Progress: ${args.progress}
Zip: ${args.zip}
LavaMoat: ${args.lavamoat}
LavaMoat debug: ${args.lavamoatDebug}
Generate policy: ${args.generatePolicy}
Snow: ${args.snow}
Sentry: ${args.sentry}
React Compiler verbose: ${args.reactCompilerVerbose}
React Compiler debug: ${args.reactCompilerDebug}
Validate Env: ${args.validateEnv}
Manifest version: ${args.manifest_version}
Release version: ${args.releaseVersion}
Browsers: ${args.browser.join(', ')}
Devtool: ${args.devtool}
Build type: ${args.type}
Features: ${[...features.active].join(', ')}
Test: ${args.test}
`;
}