yargs 17.0.0-candidate.7 → 17.0.1

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.
package/build/index.cjs CHANGED
@@ -1,3154 +1 @@
1
- 'use strict';
2
-
3
- var assert = require('assert');
4
-
5
- class YError extends Error {
6
- constructor(msg) {
7
- super(msg || 'yargs error');
8
- this.name = 'YError';
9
- Error.captureStackTrace(this, YError);
10
- }
11
- }
12
-
13
- let previouslyVisitedConfigs = [];
14
- let shim;
15
- function applyExtends(config, cwd, mergeExtends, _shim) {
16
- shim = _shim;
17
- let defaultConfig = {};
18
- if (Object.prototype.hasOwnProperty.call(config, 'extends')) {
19
- if (typeof config.extends !== 'string')
20
- return defaultConfig;
21
- const isPath = /\.json|\..*rc$/.test(config.extends);
22
- let pathToDefault = null;
23
- if (!isPath) {
24
- try {
25
- pathToDefault = require.resolve(config.extends);
26
- }
27
- catch (_err) {
28
- return config;
29
- }
30
- }
31
- else {
32
- pathToDefault = getPathToDefaultConfig(cwd, config.extends);
33
- }
34
- checkForCircularExtends(pathToDefault);
35
- previouslyVisitedConfigs.push(pathToDefault);
36
- defaultConfig = isPath
37
- ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8'))
38
- : require(config.extends);
39
- delete config.extends;
40
- defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim);
41
- }
42
- previouslyVisitedConfigs = [];
43
- return mergeExtends
44
- ? mergeDeep(defaultConfig, config)
45
- : Object.assign({}, defaultConfig, config);
46
- }
47
- function checkForCircularExtends(cfgPath) {
48
- if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
49
- throw new YError(`Circular extended configurations: '${cfgPath}'.`);
50
- }
51
- }
52
- function getPathToDefaultConfig(cwd, pathToExtend) {
53
- return shim.path.resolve(cwd, pathToExtend);
54
- }
55
- function mergeDeep(config1, config2) {
56
- const target = {};
57
- function isObject(obj) {
58
- return obj && typeof obj === 'object' && !Array.isArray(obj);
59
- }
60
- Object.assign(target, config1);
61
- for (const key of Object.keys(config2)) {
62
- if (isObject(config2[key]) && isObject(target[key])) {
63
- target[key] = mergeDeep(config1[key], config2[key]);
64
- }
65
- else {
66
- target[key] = config2[key];
67
- }
68
- }
69
- return target;
70
- }
71
-
72
- function parseCommand(cmd) {
73
- const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ');
74
- const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
75
- const bregex = /\.*[\][<>]/g;
76
- const firstCommand = splitCommand.shift();
77
- if (!firstCommand)
78
- throw new Error(`No command found in: ${cmd}`);
79
- const parsedCommand = {
80
- cmd: firstCommand.replace(bregex, ''),
81
- demanded: [],
82
- optional: [],
83
- };
84
- splitCommand.forEach((cmd, i) => {
85
- let variadic = false;
86
- cmd = cmd.replace(/\s/g, '');
87
- if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1)
88
- variadic = true;
89
- if (/^\[/.test(cmd)) {
90
- parsedCommand.optional.push({
91
- cmd: cmd.replace(bregex, '').split('|'),
92
- variadic,
93
- });
94
- }
95
- else {
96
- parsedCommand.demanded.push({
97
- cmd: cmd.replace(bregex, '').split('|'),
98
- variadic,
99
- });
100
- }
101
- });
102
- return parsedCommand;
103
- }
104
-
105
- const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
106
- function argsert(arg1, arg2, arg3) {
107
- function parseArgs() {
108
- return typeof arg1 === 'object'
109
- ? [{ demanded: [], optional: [] }, arg1, arg2]
110
- : [
111
- parseCommand(`cmd ${arg1}`),
112
- arg2,
113
- arg3,
114
- ];
115
- }
116
- try {
117
- let position = 0;
118
- const [parsed, callerArguments, _length] = parseArgs();
119
- const args = [].slice.call(callerArguments);
120
- while (args.length && args[args.length - 1] === undefined)
121
- args.pop();
122
- const length = _length || args.length;
123
- if (length < parsed.demanded.length) {
124
- throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
125
- }
126
- const totalCommands = parsed.demanded.length + parsed.optional.length;
127
- if (length > totalCommands) {
128
- throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
129
- }
130
- parsed.demanded.forEach(demanded => {
131
- const arg = args.shift();
132
- const observedType = guessType(arg);
133
- const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*');
134
- if (matchingTypes.length === 0)
135
- argumentTypeError(observedType, demanded.cmd, position);
136
- position += 1;
137
- });
138
- parsed.optional.forEach(optional => {
139
- if (args.length === 0)
140
- return;
141
- const arg = args.shift();
142
- const observedType = guessType(arg);
143
- const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*');
144
- if (matchingTypes.length === 0)
145
- argumentTypeError(observedType, optional.cmd, position);
146
- position += 1;
147
- });
148
- }
149
- catch (err) {
150
- console.warn(err.stack);
151
- }
152
- }
153
- function guessType(arg) {
154
- if (Array.isArray(arg)) {
155
- return 'array';
156
- }
157
- else if (arg === null) {
158
- return 'null';
159
- }
160
- return typeof arg;
161
- }
162
- function argumentTypeError(observedType, allowedTypes, position) {
163
- throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`);
164
- }
165
-
166
- function isPromise(maybePromise) {
167
- return (!!maybePromise &&
168
- !!maybePromise.then &&
169
- typeof maybePromise.then === 'function');
170
- }
171
-
172
- function assertNotStrictEqual(actual, expected, shim, message) {
173
- shim.assert.notStrictEqual(actual, expected, message);
174
- }
175
- function assertSingleKey(actual, shim) {
176
- shim.assert.strictEqual(typeof actual, 'string');
177
- }
178
- function objectKeys(object) {
179
- return Object.keys(object);
180
- }
181
-
182
- function objFilter(original = {}, filter = () => true) {
183
- const obj = {};
184
- objectKeys(original).forEach(key => {
185
- if (filter(key, original[key])) {
186
- obj[key] = original[key];
187
- }
188
- });
189
- return obj;
190
- }
191
-
192
- function getProcessArgvBinIndex() {
193
- if (isBundledElectronApp())
194
- return 0;
195
- return 1;
196
- }
197
- function isBundledElectronApp() {
198
- return isElectronApp() && !process.defaultApp;
199
- }
200
- function isElectronApp() {
201
- return !!process.versions.electron;
202
- }
203
- function hideBin(argv) {
204
- return argv.slice(getProcessArgvBinIndex() + 1);
205
- }
206
- function getProcessArgvBin() {
207
- return process.argv[getProcessArgvBinIndex()];
208
- }
209
-
210
- var processArgv = /*#__PURE__*/Object.freeze({
211
- __proto__: null,
212
- hideBin: hideBin,
213
- getProcessArgvBin: getProcessArgvBin
214
- });
215
-
216
- class GlobalMiddleware {
217
- constructor(yargs) {
218
- this.globalMiddleware = [];
219
- this.frozens = [];
220
- this.yargs = yargs;
221
- }
222
- addMiddleware(callback, applyBeforeValidation, global = true) {
223
- argsert('<array|function> [boolean] [boolean]', [callback, applyBeforeValidation, global], arguments.length);
224
- if (Array.isArray(callback)) {
225
- for (let i = 0; i < callback.length; i++) {
226
- if (typeof callback[i] !== 'function') {
227
- throw Error('middleware must be a function');
228
- }
229
- const m = callback[i];
230
- m.applyBeforeValidation = applyBeforeValidation;
231
- m.global = global;
232
- }
233
- Array.prototype.push.apply(this.globalMiddleware, callback);
234
- }
235
- else if (typeof callback === 'function') {
236
- const m = callback;
237
- m.applyBeforeValidation = applyBeforeValidation;
238
- m.global = global;
239
- this.globalMiddleware.push(callback);
240
- }
241
- return this.yargs;
242
- }
243
- addCoerceMiddleware(callback, option) {
244
- const aliases = this.yargs.getAliases();
245
- this.globalMiddleware = this.globalMiddleware.filter(m => {
246
- const toCheck = [...(aliases[option] ? aliases[option] : []), option];
247
- if (!m.option)
248
- return true;
249
- else
250
- return !toCheck.includes(m.option);
251
- });
252
- callback.option = option;
253
- return this.addMiddleware(callback, true, true);
254
- }
255
- getMiddleware() {
256
- return this.globalMiddleware;
257
- }
258
- freeze() {
259
- this.frozens.push([...this.globalMiddleware]);
260
- }
261
- unfreeze() {
262
- const frozen = this.frozens.pop();
263
- if (frozen !== undefined)
264
- this.globalMiddleware = frozen;
265
- }
266
- reset() {
267
- this.globalMiddleware = this.globalMiddleware.filter(m => m.global);
268
- }
269
- }
270
- function commandMiddlewareFactory(commandMiddleware) {
271
- if (!commandMiddleware)
272
- return [];
273
- return commandMiddleware.map(middleware => {
274
- middleware.applyBeforeValidation = false;
275
- return middleware;
276
- });
277
- }
278
- function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
279
- return middlewares.reduce((acc, middleware) => {
280
- if (middleware.applyBeforeValidation !== beforeValidation) {
281
- return acc;
282
- }
283
- if (isPromise(acc)) {
284
- return acc
285
- .then(initialObj => Promise.all([
286
- initialObj,
287
- middleware(initialObj, yargs),
288
- ]))
289
- .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
290
- }
291
- else {
292
- const result = middleware(acc, yargs);
293
- return isPromise(result)
294
- ? result.then(middlewareObj => Object.assign(acc, middlewareObj))
295
- : Object.assign(acc, result);
296
- }
297
- }, argv);
298
- }
299
-
300
- function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => {
301
- throw err;
302
- }) {
303
- try {
304
- const result = isFunction(getResult) ? getResult() : getResult;
305
- if (isPromise(result)) {
306
- return result.then((result) => {
307
- return resultHandler(result);
308
- });
309
- }
310
- else {
311
- return resultHandler(result);
312
- }
313
- }
314
- catch (err) {
315
- return errorHandler(err);
316
- }
317
- }
318
- function isFunction(arg) {
319
- return typeof arg === 'function';
320
- }
321
-
322
- function whichModule(exported) {
323
- if (typeof require === 'undefined')
324
- return null;
325
- for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) {
326
- mod = require.cache[files[i]];
327
- if (mod.exports === exported)
328
- return mod;
329
- }
330
- return null;
331
- }
332
-
333
- const DEFAULT_MARKER = /(^\*)|(^\$0)/;
334
- class CommandInstance {
335
- constructor(usage, validation, globalMiddleware, shim) {
336
- this.requireCache = new Set();
337
- this.handlers = {};
338
- this.aliasMap = {};
339
- this.frozens = [];
340
- this.shim = shim;
341
- this.usage = usage;
342
- this.globalMiddleware = globalMiddleware;
343
- this.validation = validation;
344
- }
345
- addDirectory(dir, req, callerFile, opts) {
346
- opts = opts || {};
347
- if (typeof opts.recurse !== 'boolean')
348
- opts.recurse = false;
349
- if (!Array.isArray(opts.extensions))
350
- opts.extensions = ['js'];
351
- const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o;
352
- opts.visit = (obj, joined, filename) => {
353
- const visited = parentVisit(obj, joined, filename);
354
- if (visited) {
355
- if (this.requireCache.has(joined))
356
- return visited;
357
- else
358
- this.requireCache.add(joined);
359
- this.addHandler(visited);
360
- }
361
- return visited;
362
- };
363
- this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts);
364
- }
365
- addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) {
366
- let aliases = [];
367
- const middlewares = commandMiddlewareFactory(commandMiddleware);
368
- handler = handler || (() => { });
369
- if (Array.isArray(cmd)) {
370
- if (isCommandAndAliases(cmd)) {
371
- [cmd, ...aliases] = cmd;
372
- }
373
- else {
374
- for (const command of cmd) {
375
- this.addHandler(command);
376
- }
377
- }
378
- }
379
- else if (isCommandHandlerDefinition(cmd)) {
380
- let command = Array.isArray(cmd.command) || typeof cmd.command === 'string'
381
- ? cmd.command
382
- : this.moduleName(cmd);
383
- if (cmd.aliases)
384
- command = [].concat(command).concat(cmd.aliases);
385
- this.addHandler(command, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
386
- return;
387
- }
388
- else if (isCommandBuilderDefinition(builder)) {
389
- this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
390
- return;
391
- }
392
- if (typeof cmd === 'string') {
393
- const parsedCommand = parseCommand(cmd);
394
- aliases = aliases.map(alias => parseCommand(alias).cmd);
395
- let isDefault = false;
396
- const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => {
397
- if (DEFAULT_MARKER.test(c)) {
398
- isDefault = true;
399
- return false;
400
- }
401
- return true;
402
- });
403
- if (parsedAliases.length === 0 && isDefault)
404
- parsedAliases.push('$0');
405
- if (isDefault) {
406
- parsedCommand.cmd = parsedAliases[0];
407
- aliases = parsedAliases.slice(1);
408
- cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
409
- }
410
- aliases.forEach(alias => {
411
- this.aliasMap[alias] = parsedCommand.cmd;
412
- });
413
- if (description !== false) {
414
- this.usage.command(cmd, description, isDefault, aliases, deprecated);
415
- }
416
- this.handlers[parsedCommand.cmd] = {
417
- original: cmd,
418
- description,
419
- handler,
420
- builder: builder || {},
421
- middlewares,
422
- deprecated,
423
- demanded: parsedCommand.demanded,
424
- optional: parsedCommand.optional,
425
- };
426
- if (isDefault)
427
- this.defaultCommand = this.handlers[parsedCommand.cmd];
428
- }
429
- }
430
- getCommandHandlers() {
431
- return this.handlers;
432
- }
433
- getCommands() {
434
- return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
435
- }
436
- hasDefaultCommand() {
437
- return !!this.defaultCommand;
438
- }
439
- runCommand(command, yargs, parsed, commandIndex, helpOnly) {
440
- const commandHandler = this.handlers[command] ||
441
- this.handlers[this.aliasMap[command]] ||
442
- this.defaultCommand;
443
- const currentContext = yargs.getContext();
444
- const parentCommands = currentContext.commands.slice();
445
- if (command) {
446
- currentContext.commands.push(command);
447
- currentContext.fullCommands.push(commandHandler.original);
448
- }
449
- const builderResult = this.applyBuilderUpdateUsageAndParse(command, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly);
450
- if (isPromise(builderResult)) {
451
- return builderResult.then(result => {
452
- return this.applyMiddlewareAndGetResult(command, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs);
453
- });
454
- }
455
- else {
456
- return this.applyMiddlewareAndGetResult(command, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs);
457
- }
458
- }
459
- applyBuilderUpdateUsageAndParse(command, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly) {
460
- const builder = commandHandler.builder;
461
- let innerYargs = yargs;
462
- if (isCommandBuilderCallback(builder)) {
463
- const builderOutput = builder(yargs.reset(aliases));
464
- if (isPromise(builderOutput)) {
465
- return builderOutput.then(output => {
466
- innerYargs = isYargsInstance(output) ? output : yargs;
467
- return this.parseAndUpdateUsage(command, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
468
- });
469
- }
470
- }
471
- else if (isCommandBuilderOptionDefinitions(builder)) {
472
- innerYargs = yargs.reset(aliases);
473
- Object.keys(commandHandler.builder).forEach(key => {
474
- innerYargs.option(key, builder[key]);
475
- });
476
- }
477
- return this.parseAndUpdateUsage(command, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
478
- }
479
- parseAndUpdateUsage(command, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) {
480
- if (!command)
481
- innerYargs.getUsageInstance().unfreeze();
482
- if (this.shouldUpdateUsage(innerYargs)) {
483
- innerYargs
484
- .getUsageInstance()
485
- .usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
486
- }
487
- const innerArgv = innerYargs._parseArgs(null, undefined, true, commandIndex, helpOnly);
488
- return {
489
- aliases: innerYargs.parsed.aliases,
490
- innerArgv: innerArgv,
491
- };
492
- }
493
- shouldUpdateUsage(yargs) {
494
- return (!yargs.getUsageInstance().getUsageDisabled() &&
495
- yargs.getUsageInstance().getUsage().length === 0);
496
- }
497
- usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
498
- const c = DEFAULT_MARKER.test(commandHandler.original)
499
- ? commandHandler.original.replace(DEFAULT_MARKER, '').trim()
500
- : commandHandler.original;
501
- const pc = parentCommands.filter(c => {
502
- return !DEFAULT_MARKER.test(c);
503
- });
504
- pc.push(c);
505
- return `$0 ${pc.join(' ')}`;
506
- }
507
- applyMiddlewareAndGetResult(command, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) {
508
- let positionalMap = {};
509
- if (!yargs._hasOutput()) {
510
- positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs);
511
- }
512
- if (helpOnly)
513
- return innerArgv;
514
- const middlewares = this.globalMiddleware
515
- .getMiddleware()
516
- .slice(0)
517
- .concat(commandHandler.middlewares);
518
- innerArgv = applyMiddleware(innerArgv, yargs, middlewares, true);
519
- if (!yargs._hasOutput()) {
520
- const validation = yargs._runValidation(aliases, positionalMap, yargs.parsed.error, !command);
521
- innerArgv = maybeAsyncResult(innerArgv, result => {
522
- validation(result);
523
- return result;
524
- });
525
- }
526
- if (commandHandler.handler && !yargs._hasOutput()) {
527
- yargs._setHasOutput();
528
- const populateDoubleDash = !!yargs.getOptions().configuration['populate--'];
529
- yargs._postProcess(innerArgv, populateDoubleDash, false, false);
530
- innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
531
- innerArgv = maybeAsyncResult(innerArgv, result => {
532
- const handlerResult = commandHandler.handler(result);
533
- if (isPromise(handlerResult)) {
534
- return handlerResult.then(() => result);
535
- }
536
- else {
537
- return result;
538
- }
539
- });
540
- yargs.getUsageInstance().cacheHelpMessage();
541
- if (isPromise(innerArgv) && !yargs._hasParseCallback()) {
542
- innerArgv.catch(error => {
543
- try {
544
- yargs.getUsageInstance().fail(null, error);
545
- }
546
- catch (_err) {
547
- }
548
- });
549
- }
550
- }
551
- if (command) {
552
- currentContext.commands.pop();
553
- currentContext.fullCommands.pop();
554
- }
555
- return innerArgv;
556
- }
557
- populatePositionals(commandHandler, argv, context, yargs) {
558
- argv._ = argv._.slice(context.commands.length);
559
- const demanded = commandHandler.demanded.slice(0);
560
- const optional = commandHandler.optional.slice(0);
561
- const positionalMap = {};
562
- this.validation.positionalCount(demanded.length, argv._.length);
563
- while (demanded.length) {
564
- const demand = demanded.shift();
565
- this.populatePositional(demand, argv, positionalMap);
566
- }
567
- while (optional.length) {
568
- const maybe = optional.shift();
569
- this.populatePositional(maybe, argv, positionalMap);
570
- }
571
- argv._ = context.commands.concat(argv._.map(a => '' + a));
572
- this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs);
573
- return positionalMap;
574
- }
575
- populatePositional(positional, argv, positionalMap) {
576
- const cmd = positional.cmd[0];
577
- if (positional.variadic) {
578
- positionalMap[cmd] = argv._.splice(0).map(String);
579
- }
580
- else {
581
- if (argv._.length)
582
- positionalMap[cmd] = [String(argv._.shift())];
583
- }
584
- }
585
- cmdToParseOptions(cmdString) {
586
- const parseOptions = {
587
- array: [],
588
- default: {},
589
- alias: {},
590
- demand: {},
591
- };
592
- const parsed = parseCommand(cmdString);
593
- parsed.demanded.forEach(d => {
594
- const [cmd, ...aliases] = d.cmd;
595
- if (d.variadic) {
596
- parseOptions.array.push(cmd);
597
- parseOptions.default[cmd] = [];
598
- }
599
- parseOptions.alias[cmd] = aliases;
600
- parseOptions.demand[cmd] = true;
601
- });
602
- parsed.optional.forEach(o => {
603
- const [cmd, ...aliases] = o.cmd;
604
- if (o.variadic) {
605
- parseOptions.array.push(cmd);
606
- parseOptions.default[cmd] = [];
607
- }
608
- parseOptions.alias[cmd] = aliases;
609
- });
610
- return parseOptions;
611
- }
612
- postProcessPositionals(argv, positionalMap, parseOptions, yargs) {
613
- const options = Object.assign({}, yargs.getOptions());
614
- options.default = Object.assign(parseOptions.default, options.default);
615
- for (const key of Object.keys(parseOptions.alias)) {
616
- options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]);
617
- }
618
- options.array = options.array.concat(parseOptions.array);
619
- options.config = {};
620
- const unparsed = [];
621
- Object.keys(positionalMap).forEach(key => {
622
- positionalMap[key].map(value => {
623
- if (options.configuration['unknown-options-as-args'])
624
- options.key[key] = true;
625
- unparsed.push(`--${key}`);
626
- unparsed.push(value);
627
- });
628
- });
629
- if (!unparsed.length)
630
- return;
631
- const config = Object.assign({}, options.configuration, {
632
- 'populate--': false,
633
- });
634
- const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, {
635
- configuration: config,
636
- }));
637
- if (parsed.error) {
638
- yargs.getUsageInstance().fail(parsed.error.message, parsed.error);
639
- }
640
- else {
641
- const positionalKeys = Object.keys(positionalMap);
642
- Object.keys(positionalMap).forEach(key => {
643
- positionalKeys.push(...parsed.aliases[key]);
644
- });
645
- Object.keys(parsed.argv).forEach(key => {
646
- if (positionalKeys.indexOf(key) !== -1) {
647
- if (!positionalMap[key])
648
- positionalMap[key] = parsed.argv[key];
649
- argv[key] = parsed.argv[key];
650
- }
651
- });
652
- }
653
- }
654
- runDefaultBuilderOn(yargs) {
655
- assertNotStrictEqual(this.defaultCommand, undefined, this.shim);
656
- if (this.shouldUpdateUsage(yargs)) {
657
- const commandString = DEFAULT_MARKER.test(this.defaultCommand.original)
658
- ? this.defaultCommand.original
659
- : this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ');
660
- yargs
661
- .getUsageInstance()
662
- .usage(commandString, this.defaultCommand.description);
663
- }
664
- const builder = this.defaultCommand.builder;
665
- if (isCommandBuilderCallback(builder)) {
666
- builder(yargs);
667
- }
668
- else if (!isCommandBuilderDefinition(builder)) {
669
- Object.keys(builder).forEach(key => {
670
- yargs.option(key, builder[key]);
671
- });
672
- }
673
- }
674
- moduleName(obj) {
675
- const mod = whichModule(obj);
676
- if (!mod)
677
- throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`);
678
- return this.commandFromFilename(mod.filename);
679
- }
680
- commandFromFilename(filename) {
681
- return this.shim.path.basename(filename, this.shim.path.extname(filename));
682
- }
683
- extractDesc({ describe, description, desc }) {
684
- for (const test of [describe, description, desc]) {
685
- if (typeof test === 'string' || test === false)
686
- return test;
687
- assertNotStrictEqual(test, true, this.shim);
688
- }
689
- return false;
690
- }
691
- freeze() {
692
- this.frozens.push({
693
- handlers: this.handlers,
694
- aliasMap: this.aliasMap,
695
- defaultCommand: this.defaultCommand,
696
- });
697
- }
698
- unfreeze() {
699
- const frozen = this.frozens.pop();
700
- assertNotStrictEqual(frozen, undefined, this.shim);
701
- ({
702
- handlers: this.handlers,
703
- aliasMap: this.aliasMap,
704
- defaultCommand: this.defaultCommand,
705
- } = frozen);
706
- }
707
- reset() {
708
- this.handlers = {};
709
- this.aliasMap = {};
710
- this.defaultCommand = undefined;
711
- this.requireCache = new Set();
712
- return this;
713
- }
714
- }
715
- function command(usage, validation, globalMiddleware, shim) {
716
- return new CommandInstance(usage, validation, globalMiddleware, shim);
717
- }
718
- function isCommandBuilderDefinition(builder) {
719
- return (typeof builder === 'object' &&
720
- !!builder.builder &&
721
- typeof builder.handler === 'function');
722
- }
723
- function isCommandAndAliases(cmd) {
724
- if (cmd.every(c => typeof c === 'string')) {
725
- return true;
726
- }
727
- else {
728
- return false;
729
- }
730
- }
731
- function isCommandBuilderCallback(builder) {
732
- return typeof builder === 'function';
733
- }
734
- function isCommandBuilderOptionDefinitions(builder) {
735
- return typeof builder === 'object';
736
- }
737
- function isCommandHandlerDefinition(cmd) {
738
- return typeof cmd === 'object' && !Array.isArray(cmd);
739
- }
740
-
741
- function setBlocking(blocking) {
742
- if (typeof process === 'undefined')
743
- return;
744
- [process.stdout, process.stderr].forEach(_stream => {
745
- const stream = _stream;
746
- if (stream._handle &&
747
- stream.isTTY &&
748
- typeof stream._handle.setBlocking === 'function') {
749
- stream._handle.setBlocking(blocking);
750
- }
751
- });
752
- }
753
-
754
- function isBoolean(fail) {
755
- return typeof fail === 'boolean';
756
- }
757
- function usage(yargs, y18n, shim) {
758
- const __ = y18n.__;
759
- const self = {};
760
- const fails = [];
761
- self.failFn = function failFn(f) {
762
- fails.push(f);
763
- };
764
- let failMessage = null;
765
- let showHelpOnFail = true;
766
- self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) {
767
- function parseFunctionArgs() {
768
- return typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2];
769
- }
770
- const [enabled, message] = parseFunctionArgs();
771
- failMessage = message;
772
- showHelpOnFail = enabled;
773
- return self;
774
- };
775
- let failureOutput = false;
776
- self.fail = function fail(msg, err) {
777
- const logger = yargs._getLoggerInstance();
778
- if (fails.length) {
779
- for (let i = fails.length - 1; i >= 0; --i) {
780
- const fail = fails[i];
781
- if (isBoolean(fail)) {
782
- if (err)
783
- throw err;
784
- else if (msg)
785
- throw Error(msg);
786
- }
787
- else {
788
- fail(msg, err, self);
789
- }
790
- }
791
- }
792
- else {
793
- if (yargs.getExitProcess())
794
- setBlocking(true);
795
- if (!failureOutput) {
796
- failureOutput = true;
797
- if (showHelpOnFail) {
798
- yargs.showHelp('error');
799
- logger.error();
800
- }
801
- if (msg || err)
802
- logger.error(msg || err);
803
- if (failMessage) {
804
- if (msg || err)
805
- logger.error('');
806
- logger.error(failMessage);
807
- }
808
- }
809
- err = err || new YError(msg);
810
- if (yargs.getExitProcess()) {
811
- return yargs.exit(1);
812
- }
813
- else if (yargs._hasParseCallback()) {
814
- return yargs.exit(1, err);
815
- }
816
- else {
817
- throw err;
818
- }
819
- }
820
- };
821
- let usages = [];
822
- let usageDisabled = false;
823
- self.usage = (msg, description) => {
824
- if (msg === null) {
825
- usageDisabled = true;
826
- usages = [];
827
- return self;
828
- }
829
- usageDisabled = false;
830
- usages.push([msg, description || '']);
831
- return self;
832
- };
833
- self.getUsage = () => {
834
- return usages;
835
- };
836
- self.getUsageDisabled = () => {
837
- return usageDisabled;
838
- };
839
- self.getPositionalGroupName = () => {
840
- return __('Positionals:');
841
- };
842
- let examples = [];
843
- self.example = (cmd, description) => {
844
- examples.push([cmd, description || '']);
845
- };
846
- let commands = [];
847
- self.command = function command(cmd, description, isDefault, aliases, deprecated = false) {
848
- if (isDefault) {
849
- commands = commands.map(cmdArray => {
850
- cmdArray[2] = false;
851
- return cmdArray;
852
- });
853
- }
854
- commands.push([cmd, description || '', isDefault, aliases, deprecated]);
855
- };
856
- self.getCommands = () => commands;
857
- let descriptions = {};
858
- self.describe = function describe(keyOrKeys, desc) {
859
- if (Array.isArray(keyOrKeys)) {
860
- keyOrKeys.forEach(k => {
861
- self.describe(k, desc);
862
- });
863
- }
864
- else if (typeof keyOrKeys === 'object') {
865
- Object.keys(keyOrKeys).forEach(k => {
866
- self.describe(k, keyOrKeys[k]);
867
- });
868
- }
869
- else {
870
- descriptions[keyOrKeys] = desc;
871
- }
872
- };
873
- self.getDescriptions = () => descriptions;
874
- let epilogs = [];
875
- self.epilog = msg => {
876
- epilogs.push(msg);
877
- };
878
- let wrapSet = false;
879
- let wrap;
880
- self.wrap = cols => {
881
- wrapSet = true;
882
- wrap = cols;
883
- };
884
- function getWrap() {
885
- if (!wrapSet) {
886
- wrap = windowWidth();
887
- wrapSet = true;
888
- }
889
- return wrap;
890
- }
891
- const deferY18nLookupPrefix = '__yargsString__:';
892
- self.deferY18nLookup = str => deferY18nLookupPrefix + str;
893
- self.help = function help() {
894
- if (cachedHelpMessage)
895
- return cachedHelpMessage;
896
- normalizeAliases();
897
- const base$0 = yargs.customScriptName
898
- ? yargs.$0
899
- : shim.path.basename(yargs.$0);
900
- const demandedOptions = yargs.getDemandedOptions();
901
- const demandedCommands = yargs.getDemandedCommands();
902
- const deprecatedOptions = yargs.getDeprecatedOptions();
903
- const groups = yargs.getGroups();
904
- const options = yargs.getOptions();
905
- let keys = [];
906
- keys = keys.concat(Object.keys(descriptions));
907
- keys = keys.concat(Object.keys(demandedOptions));
908
- keys = keys.concat(Object.keys(demandedCommands));
909
- keys = keys.concat(Object.keys(options.default));
910
- keys = keys.filter(filterHiddenOptions);
911
- keys = Object.keys(keys.reduce((acc, key) => {
912
- if (key !== '_')
913
- acc[key] = true;
914
- return acc;
915
- }, {}));
916
- const theWrap = getWrap();
917
- const ui = shim.cliui({
918
- width: theWrap,
919
- wrap: !!theWrap,
920
- });
921
- if (!usageDisabled) {
922
- if (usages.length) {
923
- usages.forEach(usage => {
924
- ui.div(`${usage[0].replace(/\$0/g, base$0)}`);
925
- if (usage[1]) {
926
- ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] });
927
- }
928
- });
929
- ui.div();
930
- }
931
- else if (commands.length) {
932
- let u = null;
933
- if (demandedCommands._) {
934
- u = `${base$0} <${__('command')}>\n`;
935
- }
936
- else {
937
- u = `${base$0} [${__('command')}]\n`;
938
- }
939
- ui.div(`${u}`);
940
- }
941
- }
942
- if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) {
943
- ui.div(__('Commands:'));
944
- const context = yargs.getContext();
945
- const parentCommands = context.commands.length
946
- ? `${context.commands.join(' ')} `
947
- : '';
948
- if (yargs.getParserConfiguration()['sort-commands'] === true) {
949
- commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
950
- }
951
- commands.forEach(command => {
952
- const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}`;
953
- ui.span({
954
- text: commandString,
955
- padding: [0, 2, 0, 2],
956
- width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4,
957
- }, { text: command[1] });
958
- const hints = [];
959
- if (command[2])
960
- hints.push(`[${__('default')}]`);
961
- if (command[3] && command[3].length) {
962
- hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`);
963
- }
964
- if (command[4]) {
965
- if (typeof command[4] === 'string') {
966
- hints.push(`[${__('deprecated: %s', command[4])}]`);
967
- }
968
- else {
969
- hints.push(`[${__('deprecated')}]`);
970
- }
971
- }
972
- if (hints.length) {
973
- ui.div({
974
- text: hints.join(' '),
975
- padding: [0, 0, 0, 2],
976
- align: 'right',
977
- });
978
- }
979
- else {
980
- ui.div();
981
- }
982
- });
983
- ui.div();
984
- }
985
- const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
986
- keys = keys.filter(key => !yargs.parsed.newAliases[key] &&
987
- aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1));
988
- const defaultGroup = __('Options:');
989
- if (!groups[defaultGroup])
990
- groups[defaultGroup] = [];
991
- addUngroupedKeys(keys, options.alias, groups, defaultGroup);
992
- const isLongSwitch = (sw) => /^--/.test(getText(sw));
993
- const displayedGroups = Object.keys(groups)
994
- .filter(groupName => groups[groupName].length > 0)
995
- .map(groupName => {
996
- const normalizedKeys = groups[groupName]
997
- .filter(filterHiddenOptions)
998
- .map(key => {
999
- if (~aliasKeys.indexOf(key))
1000
- return key;
1001
- for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
1002
- if (~(options.alias[aliasKey] || []).indexOf(key))
1003
- return aliasKey;
1004
- }
1005
- return key;
1006
- });
1007
- return { groupName, normalizedKeys };
1008
- })
1009
- .filter(({ normalizedKeys }) => normalizedKeys.length > 0)
1010
- .map(({ groupName, normalizedKeys }) => {
1011
- const switches = normalizedKeys.reduce((acc, key) => {
1012
- acc[key] = [key]
1013
- .concat(options.alias[key] || [])
1014
- .map(sw => {
1015
- if (groupName === self.getPositionalGroupName())
1016
- return sw;
1017
- else {
1018
- return ((/^[0-9]$/.test(sw)
1019
- ? ~options.boolean.indexOf(key)
1020
- ? '-'
1021
- : '--'
1022
- : sw.length > 1
1023
- ? '--'
1024
- : '-') + sw);
1025
- }
1026
- })
1027
- .sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2)
1028
- ? 0
1029
- : isLongSwitch(sw1)
1030
- ? 1
1031
- : -1)
1032
- .join(', ');
1033
- return acc;
1034
- }, {});
1035
- return { groupName, normalizedKeys, switches };
1036
- });
1037
- const shortSwitchesUsed = displayedGroups
1038
- .filter(({ groupName }) => groupName !== self.getPositionalGroupName())
1039
- .some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key])));
1040
- if (shortSwitchesUsed) {
1041
- displayedGroups
1042
- .filter(({ groupName }) => groupName !== self.getPositionalGroupName())
1043
- .forEach(({ normalizedKeys, switches }) => {
1044
- normalizedKeys.forEach(key => {
1045
- if (isLongSwitch(switches[key])) {
1046
- switches[key] = addIndentation(switches[key], '-x, '.length);
1047
- }
1048
- });
1049
- });
1050
- }
1051
- displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
1052
- ui.div(groupName);
1053
- normalizedKeys.forEach(key => {
1054
- const kswitch = switches[key];
1055
- let desc = descriptions[key] || '';
1056
- let type = null;
1057
- if (~desc.lastIndexOf(deferY18nLookupPrefix))
1058
- desc = __(desc.substring(deferY18nLookupPrefix.length));
1059
- if (~options.boolean.indexOf(key))
1060
- type = `[${__('boolean')}]`;
1061
- if (~options.count.indexOf(key))
1062
- type = `[${__('count')}]`;
1063
- if (~options.string.indexOf(key))
1064
- type = `[${__('string')}]`;
1065
- if (~options.normalize.indexOf(key))
1066
- type = `[${__('string')}]`;
1067
- if (~options.array.indexOf(key))
1068
- type = `[${__('array')}]`;
1069
- if (~options.number.indexOf(key))
1070
- type = `[${__('number')}]`;
1071
- const deprecatedExtra = (deprecated) => typeof deprecated === 'string'
1072
- ? `[${__('deprecated: %s', deprecated)}]`
1073
- : `[${__('deprecated')}]`;
1074
- const extra = [
1075
- key in deprecatedOptions
1076
- ? deprecatedExtra(deprecatedOptions[key])
1077
- : null,
1078
- type,
1079
- key in demandedOptions ? `[${__('required')}]` : null,
1080
- options.choices && options.choices[key]
1081
- ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]`
1082
- : null,
1083
- defaultString(options.default[key], options.defaultDescription[key]),
1084
- ]
1085
- .filter(Boolean)
1086
- .join(' ');
1087
- ui.span({
1088
- text: getText(kswitch),
1089
- padding: [0, 2, 0, 2 + getIndentation(kswitch)],
1090
- width: maxWidth(switches, theWrap) + 4,
1091
- }, desc);
1092
- if (extra)
1093
- ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' });
1094
- else
1095
- ui.div();
1096
- });
1097
- ui.div();
1098
- });
1099
- if (examples.length) {
1100
- ui.div(__('Examples:'));
1101
- examples.forEach(example => {
1102
- example[0] = example[0].replace(/\$0/g, base$0);
1103
- });
1104
- examples.forEach(example => {
1105
- if (example[1] === '') {
1106
- ui.div({
1107
- text: example[0],
1108
- padding: [0, 2, 0, 2],
1109
- });
1110
- }
1111
- else {
1112
- ui.div({
1113
- text: example[0],
1114
- padding: [0, 2, 0, 2],
1115
- width: maxWidth(examples, theWrap) + 4,
1116
- }, {
1117
- text: example[1],
1118
- });
1119
- }
1120
- });
1121
- ui.div();
1122
- }
1123
- if (epilogs.length > 0) {
1124
- const e = epilogs
1125
- .map(epilog => epilog.replace(/\$0/g, base$0))
1126
- .join('\n');
1127
- ui.div(`${e}\n`);
1128
- }
1129
- return ui.toString().replace(/\s*$/, '');
1130
- };
1131
- function maxWidth(table, theWrap, modifier) {
1132
- let width = 0;
1133
- if (!Array.isArray(table)) {
1134
- table = Object.values(table).map(v => [v]);
1135
- }
1136
- table.forEach(v => {
1137
- width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width);
1138
- });
1139
- if (theWrap)
1140
- width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
1141
- return width;
1142
- }
1143
- function normalizeAliases() {
1144
- const demandedOptions = yargs.getDemandedOptions();
1145
- const options = yargs.getOptions();
1146
- (Object.keys(options.alias) || []).forEach(key => {
1147
- options.alias[key].forEach(alias => {
1148
- if (descriptions[alias])
1149
- self.describe(key, descriptions[alias]);
1150
- if (alias in demandedOptions)
1151
- yargs.demandOption(key, demandedOptions[alias]);
1152
- if (~options.boolean.indexOf(alias))
1153
- yargs.boolean(key);
1154
- if (~options.count.indexOf(alias))
1155
- yargs.count(key);
1156
- if (~options.string.indexOf(alias))
1157
- yargs.string(key);
1158
- if (~options.normalize.indexOf(alias))
1159
- yargs.normalize(key);
1160
- if (~options.array.indexOf(alias))
1161
- yargs.array(key);
1162
- if (~options.number.indexOf(alias))
1163
- yargs.number(key);
1164
- });
1165
- });
1166
- }
1167
- let cachedHelpMessage;
1168
- self.cacheHelpMessage = function () {
1169
- cachedHelpMessage = this.help();
1170
- };
1171
- self.clearCachedHelpMessage = function () {
1172
- cachedHelpMessage = undefined;
1173
- };
1174
- self.hasCachedHelpMessage = function () {
1175
- return !!cachedHelpMessage;
1176
- };
1177
- function addUngroupedKeys(keys, aliases, groups, defaultGroup) {
1178
- let groupedKeys = [];
1179
- let toCheck = null;
1180
- Object.keys(groups).forEach(group => {
1181
- groupedKeys = groupedKeys.concat(groups[group]);
1182
- });
1183
- keys.forEach(key => {
1184
- toCheck = [key].concat(aliases[key]);
1185
- if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
1186
- groups[defaultGroup].push(key);
1187
- }
1188
- });
1189
- return groupedKeys;
1190
- }
1191
- function filterHiddenOptions(key) {
1192
- return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 ||
1193
- yargs.parsed.argv[yargs.getOptions().showHiddenOpt]);
1194
- }
1195
- self.showHelp = (level) => {
1196
- const logger = yargs._getLoggerInstance();
1197
- if (!level)
1198
- level = 'error';
1199
- const emit = typeof level === 'function' ? level : logger[level];
1200
- emit(self.help());
1201
- };
1202
- self.functionDescription = fn => {
1203
- const description = fn.name
1204
- ? shim.Parser.decamelize(fn.name, '-')
1205
- : __('generated-value');
1206
- return ['(', description, ')'].join('');
1207
- };
1208
- self.stringifiedValues = function stringifiedValues(values, separator) {
1209
- let string = '';
1210
- const sep = separator || ', ';
1211
- const array = [].concat(values);
1212
- if (!values || !array.length)
1213
- return string;
1214
- array.forEach(value => {
1215
- if (string.length)
1216
- string += sep;
1217
- string += JSON.stringify(value);
1218
- });
1219
- return string;
1220
- };
1221
- function defaultString(value, defaultDescription) {
1222
- let string = `[${__('default:')} `;
1223
- if (value === undefined && !defaultDescription)
1224
- return null;
1225
- if (defaultDescription) {
1226
- string += defaultDescription;
1227
- }
1228
- else {
1229
- switch (typeof value) {
1230
- case 'string':
1231
- string += `"${value}"`;
1232
- break;
1233
- case 'object':
1234
- string += JSON.stringify(value);
1235
- break;
1236
- default:
1237
- string += value;
1238
- }
1239
- }
1240
- return `${string}]`;
1241
- }
1242
- function windowWidth() {
1243
- const maxWidth = 80;
1244
- if (shim.process.stdColumns) {
1245
- return Math.min(maxWidth, shim.process.stdColumns);
1246
- }
1247
- else {
1248
- return maxWidth;
1249
- }
1250
- }
1251
- let version = null;
1252
- self.version = ver => {
1253
- version = ver;
1254
- };
1255
- self.showVersion = level => {
1256
- const logger = yargs._getLoggerInstance();
1257
- if (!level)
1258
- level = 'error';
1259
- const emit = typeof level === 'function' ? level : logger[level];
1260
- emit(version);
1261
- };
1262
- self.reset = function reset(localLookup) {
1263
- failMessage = null;
1264
- failureOutput = false;
1265
- usages = [];
1266
- usageDisabled = false;
1267
- epilogs = [];
1268
- examples = [];
1269
- commands = [];
1270
- descriptions = objFilter(descriptions, k => !localLookup[k]);
1271
- return self;
1272
- };
1273
- const frozens = [];
1274
- self.freeze = function freeze() {
1275
- frozens.push({
1276
- failMessage,
1277
- failureOutput,
1278
- usages,
1279
- usageDisabled,
1280
- epilogs,
1281
- examples,
1282
- commands,
1283
- descriptions,
1284
- });
1285
- };
1286
- self.unfreeze = function unfreeze() {
1287
- const frozen = frozens.pop();
1288
- if (!frozen)
1289
- return;
1290
- ({
1291
- failMessage,
1292
- failureOutput,
1293
- usages,
1294
- usageDisabled,
1295
- epilogs,
1296
- examples,
1297
- commands,
1298
- descriptions,
1299
- } = frozen);
1300
- };
1301
- return self;
1302
- }
1303
- function isIndentedText(text) {
1304
- return typeof text === 'object';
1305
- }
1306
- function addIndentation(text, indent) {
1307
- return isIndentedText(text)
1308
- ? { text: text.text, indentation: text.indentation + indent }
1309
- : { text, indentation: indent };
1310
- }
1311
- function getIndentation(text) {
1312
- return isIndentedText(text) ? text.indentation : 0;
1313
- }
1314
- function getText(text) {
1315
- return isIndentedText(text) ? text.text : text;
1316
- }
1317
-
1318
- const completionShTemplate = `###-begin-{{app_name}}-completions-###
1319
- #
1320
- # yargs command completion script
1321
- #
1322
- # Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
1323
- # or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
1324
- #
1325
- _yargs_completions()
1326
- {
1327
- local cur_word args type_list
1328
-
1329
- cur_word="\${COMP_WORDS[COMP_CWORD]}"
1330
- args=("\${COMP_WORDS[@]}")
1331
-
1332
- # ask yargs to generate completions.
1333
- type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")
1334
-
1335
- COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )
1336
-
1337
- # if no match was found, fall back to filename completion
1338
- if [ \${#COMPREPLY[@]} -eq 0 ]; then
1339
- COMPREPLY=()
1340
- fi
1341
-
1342
- return 0
1343
- }
1344
- complete -o default -F _yargs_completions {{app_name}}
1345
- ###-end-{{app_name}}-completions-###
1346
- `;
1347
- const completionZshTemplate = `#compdef {{app_name}}
1348
- ###-begin-{{app_name}}-completions-###
1349
- #
1350
- # yargs command completion script
1351
- #
1352
- # Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
1353
- # or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX.
1354
- #
1355
- _{{app_name}}_yargs_completions()
1356
- {
1357
- local reply
1358
- local si=$IFS
1359
- IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
1360
- IFS=$si
1361
- _describe 'values' reply
1362
- }
1363
- compdef _{{app_name}}_yargs_completions {{app_name}}
1364
- ###-end-{{app_name}}-completions-###
1365
- `;
1366
-
1367
- class Completion {
1368
- constructor(yargs, usage, command, shim) {
1369
- var _a, _b, _c;
1370
- this.yargs = yargs;
1371
- this.usage = usage;
1372
- this.command = command;
1373
- this.shim = shim;
1374
- this.completionKey = 'get-yargs-completions';
1375
- this.aliases = null;
1376
- this.customCompletionFunction = null;
1377
- this.zshShell = (_c = (((_a = this.shim.getEnv('SHELL')) === null || _a === void 0 ? void 0 : _a.includes('zsh')) || ((_b = this.shim.getEnv('ZSH_NAME')) === null || _b === void 0 ? void 0 : _b.includes('zsh')))) !== null && _c !== void 0 ? _c : false;
1378
- }
1379
- defaultCompletion(args, argv, current, done) {
1380
- const handlers = this.command.getCommandHandlers();
1381
- for (let i = 0, ii = args.length; i < ii; ++i) {
1382
- if (handlers[args[i]] && handlers[args[i]].builder) {
1383
- const builder = handlers[args[i]].builder;
1384
- if (isCommandBuilderCallback(builder)) {
1385
- const y = this.yargs.reset();
1386
- builder(y);
1387
- return y.argv;
1388
- }
1389
- }
1390
- }
1391
- const completions = [];
1392
- this.commandCompletions(completions, args, current);
1393
- this.optionCompletions(completions, args, argv, current);
1394
- done(null, completions);
1395
- }
1396
- commandCompletions(completions, args, current) {
1397
- const parentCommands = this.yargs.getContext().commands;
1398
- if (!current.match(/^-/) &&
1399
- parentCommands[parentCommands.length - 1] !== current) {
1400
- this.usage.getCommands().forEach(usageCommand => {
1401
- const commandName = parseCommand(usageCommand[0]).cmd;
1402
- if (args.indexOf(commandName) === -1) {
1403
- if (!this.zshShell) {
1404
- completions.push(commandName);
1405
- }
1406
- else {
1407
- const desc = usageCommand[1] || '';
1408
- completions.push(commandName.replace(/:/g, '\\:') + ':' + desc);
1409
- }
1410
- }
1411
- });
1412
- }
1413
- }
1414
- optionCompletions(completions, args, argv, current) {
1415
- if (current.match(/^-/) || (current === '' && completions.length === 0)) {
1416
- const options = this.yargs.getOptions();
1417
- const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
1418
- Object.keys(options.key).forEach(key => {
1419
- const negable = !!options.configuration['boolean-negation'] &&
1420
- options.boolean.includes(key);
1421
- const isPositionalKey = positionalKeys.includes(key);
1422
- if (!isPositionalKey &&
1423
- !this.argsContainKey(args, argv, key, negable)) {
1424
- this.completeOptionKey(key, completions, current);
1425
- if (negable && !!options.default[key])
1426
- this.completeOptionKey(`no-${key}`, completions, current);
1427
- }
1428
- });
1429
- }
1430
- }
1431
- argsContainKey(args, argv, key, negable) {
1432
- if (args.indexOf(`--${key}`) !== -1)
1433
- return true;
1434
- if (negable && args.indexOf(`--no-${key}`) !== -1)
1435
- return true;
1436
- if (this.aliases) {
1437
- for (const alias of this.aliases[key]) {
1438
- if (argv[alias] !== undefined)
1439
- return true;
1440
- }
1441
- }
1442
- return false;
1443
- }
1444
- completeOptionKey(key, completions, current) {
1445
- const descs = this.usage.getDescriptions();
1446
- const startsByTwoDashes = (s) => /^--/.test(s);
1447
- const isShortOption = (s) => /^[^0-9]$/.test(s);
1448
- const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
1449
- if (!this.zshShell) {
1450
- completions.push(dashes + key);
1451
- }
1452
- else {
1453
- const desc = descs[key] || '';
1454
- completions.push(dashes +
1455
- `${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`);
1456
- }
1457
- }
1458
- customCompletion(args, argv, current, done) {
1459
- assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
1460
- if (isSyncCompletionFunction(this.customCompletionFunction)) {
1461
- const result = this.customCompletionFunction(current, argv);
1462
- if (isPromise(result)) {
1463
- return result
1464
- .then(list => {
1465
- this.shim.process.nextTick(() => {
1466
- done(null, list);
1467
- });
1468
- })
1469
- .catch(err => {
1470
- this.shim.process.nextTick(() => {
1471
- done(err, undefined);
1472
- });
1473
- });
1474
- }
1475
- return done(null, result);
1476
- }
1477
- else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
1478
- return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => {
1479
- done(null, completions);
1480
- });
1481
- }
1482
- else {
1483
- return this.customCompletionFunction(current, argv, completions => {
1484
- done(null, completions);
1485
- });
1486
- }
1487
- }
1488
- getCompletion(args, done) {
1489
- const current = args.length ? args[args.length - 1] : '';
1490
- const argv = this.yargs.parse(args, true);
1491
- const completionFunction = this.customCompletionFunction
1492
- ? (argv) => this.customCompletion(args, argv, current, done)
1493
- : (argv) => this.defaultCompletion(args, argv, current, done);
1494
- return isPromise(argv)
1495
- ? argv.then(completionFunction)
1496
- : completionFunction(argv);
1497
- }
1498
- generateCompletionScript($0, cmd) {
1499
- let script = this.zshShell
1500
- ? completionZshTemplate
1501
- : completionShTemplate;
1502
- const name = this.shim.path.basename($0);
1503
- if ($0.match(/\.js$/))
1504
- $0 = `./${$0}`;
1505
- script = script.replace(/{{app_name}}/g, name);
1506
- script = script.replace(/{{completion_command}}/g, cmd);
1507
- return script.replace(/{{app_path}}/g, $0);
1508
- }
1509
- registerFunction(fn) {
1510
- this.customCompletionFunction = fn;
1511
- }
1512
- setParsed(parsed) {
1513
- this.aliases = parsed.aliases;
1514
- }
1515
- }
1516
- function completion(yargs, usage, command, shim) {
1517
- return new Completion(yargs, usage, command, shim);
1518
- }
1519
- function isSyncCompletionFunction(completionFunction) {
1520
- return completionFunction.length < 3;
1521
- }
1522
- function isFallbackCompletionFunction(completionFunction) {
1523
- return completionFunction.length > 3;
1524
- }
1525
-
1526
- function levenshtein(a, b) {
1527
- if (a.length === 0)
1528
- return b.length;
1529
- if (b.length === 0)
1530
- return a.length;
1531
- const matrix = [];
1532
- let i;
1533
- for (i = 0; i <= b.length; i++) {
1534
- matrix[i] = [i];
1535
- }
1536
- let j;
1537
- for (j = 0; j <= a.length; j++) {
1538
- matrix[0][j] = j;
1539
- }
1540
- for (i = 1; i <= b.length; i++) {
1541
- for (j = 1; j <= a.length; j++) {
1542
- if (b.charAt(i - 1) === a.charAt(j - 1)) {
1543
- matrix[i][j] = matrix[i - 1][j - 1];
1544
- }
1545
- else {
1546
- matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
1547
- }
1548
- }
1549
- }
1550
- return matrix[b.length][a.length];
1551
- }
1552
-
1553
- const specialKeys = ['$0', '--', '_'];
1554
- function validation(yargs, usage, y18n, shim) {
1555
- const __ = y18n.__;
1556
- const __n = y18n.__n;
1557
- const self = {};
1558
- self.nonOptionCount = function nonOptionCount(argv) {
1559
- const demandedCommands = yargs.getDemandedCommands();
1560
- const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0);
1561
- const _s = positionalCount - yargs.getContext().commands.length;
1562
- if (demandedCommands._ &&
1563
- (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
1564
- if (_s < demandedCommands._.min) {
1565
- if (demandedCommands._.minMsg !== undefined) {
1566
- usage.fail(demandedCommands._.minMsg
1567
- ? demandedCommands._.minMsg
1568
- .replace(/\$0/g, _s.toString())
1569
- .replace(/\$1/, demandedCommands._.min.toString())
1570
- : null);
1571
- }
1572
- else {
1573
- usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString()));
1574
- }
1575
- }
1576
- else if (_s > demandedCommands._.max) {
1577
- if (demandedCommands._.maxMsg !== undefined) {
1578
- usage.fail(demandedCommands._.maxMsg
1579
- ? demandedCommands._.maxMsg
1580
- .replace(/\$0/g, _s.toString())
1581
- .replace(/\$1/, demandedCommands._.max.toString())
1582
- : null);
1583
- }
1584
- else {
1585
- usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString()));
1586
- }
1587
- }
1588
- }
1589
- };
1590
- self.positionalCount = function positionalCount(required, observed) {
1591
- if (observed < required) {
1592
- usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + ''));
1593
- }
1594
- };
1595
- self.requiredArguments = function requiredArguments(argv, demandedOptions) {
1596
- let missing = null;
1597
- for (const key of Object.keys(demandedOptions)) {
1598
- if (!Object.prototype.hasOwnProperty.call(argv, key) ||
1599
- typeof argv[key] === 'undefined') {
1600
- missing = missing || {};
1601
- missing[key] = demandedOptions[key];
1602
- }
1603
- }
1604
- if (missing) {
1605
- const customMsgs = [];
1606
- for (const key of Object.keys(missing)) {
1607
- const msg = missing[key];
1608
- if (msg && customMsgs.indexOf(msg) < 0) {
1609
- customMsgs.push(msg);
1610
- }
1611
- }
1612
- const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '';
1613
- usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg));
1614
- }
1615
- };
1616
- self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) {
1617
- const commandKeys = yargs.getCommandInstance().getCommands();
1618
- const unknown = [];
1619
- const currentContext = yargs.getContext();
1620
- Object.keys(argv).forEach(key => {
1621
- if (specialKeys.indexOf(key) === -1 &&
1622
- !Object.prototype.hasOwnProperty.call(positionalMap, key) &&
1623
- !Object.prototype.hasOwnProperty.call(yargs._getParseContext(), key) &&
1624
- !self.isValidAndSomeAliasIsNotNew(key, aliases)) {
1625
- unknown.push(key);
1626
- }
1627
- });
1628
- if (checkPositionals &&
1629
- (currentContext.commands.length > 0 ||
1630
- commandKeys.length > 0 ||
1631
- isDefaultCommand)) {
1632
- argv._.slice(currentContext.commands.length).forEach(key => {
1633
- if (commandKeys.indexOf('' + key) === -1) {
1634
- unknown.push('' + key);
1635
- }
1636
- });
1637
- }
1638
- if (unknown.length > 0) {
1639
- usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.join(', ')));
1640
- }
1641
- };
1642
- self.unknownCommands = function unknownCommands(argv) {
1643
- const commandKeys = yargs.getCommandInstance().getCommands();
1644
- const unknown = [];
1645
- const currentContext = yargs.getContext();
1646
- if (currentContext.commands.length > 0 || commandKeys.length > 0) {
1647
- argv._.slice(currentContext.commands.length).forEach(key => {
1648
- if (commandKeys.indexOf('' + key) === -1) {
1649
- unknown.push('' + key);
1650
- }
1651
- });
1652
- }
1653
- if (unknown.length > 0) {
1654
- usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', ')));
1655
- return true;
1656
- }
1657
- else {
1658
- return false;
1659
- }
1660
- };
1661
- self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) {
1662
- if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
1663
- return false;
1664
- }
1665
- const newAliases = yargs.parsed.newAliases;
1666
- for (const a of [key, ...aliases[key]]) {
1667
- if (!Object.prototype.hasOwnProperty.call(newAliases, a) ||
1668
- !newAliases[key]) {
1669
- return true;
1670
- }
1671
- }
1672
- return false;
1673
- };
1674
- self.limitedChoices = function limitedChoices(argv) {
1675
- const options = yargs.getOptions();
1676
- const invalid = {};
1677
- if (!Object.keys(options.choices).length)
1678
- return;
1679
- Object.keys(argv).forEach(key => {
1680
- if (specialKeys.indexOf(key) === -1 &&
1681
- Object.prototype.hasOwnProperty.call(options.choices, key)) {
1682
- [].concat(argv[key]).forEach(value => {
1683
- if (options.choices[key].indexOf(value) === -1 &&
1684
- value !== undefined) {
1685
- invalid[key] = (invalid[key] || []).concat(value);
1686
- }
1687
- });
1688
- }
1689
- });
1690
- const invalidKeys = Object.keys(invalid);
1691
- if (!invalidKeys.length)
1692
- return;
1693
- let msg = __('Invalid values:');
1694
- invalidKeys.forEach(key => {
1695
- msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`;
1696
- });
1697
- usage.fail(msg);
1698
- };
1699
- let implied = {};
1700
- self.implies = function implies(key, value) {
1701
- argsert('<string|object> [array|number|string]', [key, value], arguments.length);
1702
- if (typeof key === 'object') {
1703
- Object.keys(key).forEach(k => {
1704
- self.implies(k, key[k]);
1705
- });
1706
- }
1707
- else {
1708
- yargs.global(key);
1709
- if (!implied[key]) {
1710
- implied[key] = [];
1711
- }
1712
- if (Array.isArray(value)) {
1713
- value.forEach(i => self.implies(key, i));
1714
- }
1715
- else {
1716
- assertNotStrictEqual(value, undefined, shim);
1717
- implied[key].push(value);
1718
- }
1719
- }
1720
- };
1721
- self.getImplied = function getImplied() {
1722
- return implied;
1723
- };
1724
- function keyExists(argv, val) {
1725
- const num = Number(val);
1726
- val = isNaN(num) ? val : num;
1727
- if (typeof val === 'number') {
1728
- val = argv._.length >= val;
1729
- }
1730
- else if (val.match(/^--no-.+/)) {
1731
- val = val.match(/^--no-(.+)/)[1];
1732
- val = !argv[val];
1733
- }
1734
- else {
1735
- val = argv[val];
1736
- }
1737
- return val;
1738
- }
1739
- self.implications = function implications(argv) {
1740
- const implyFail = [];
1741
- Object.keys(implied).forEach(key => {
1742
- const origKey = key;
1743
- (implied[key] || []).forEach(value => {
1744
- let key = origKey;
1745
- const origValue = value;
1746
- key = keyExists(argv, key);
1747
- value = keyExists(argv, value);
1748
- if (key && !value) {
1749
- implyFail.push(` ${origKey} -> ${origValue}`);
1750
- }
1751
- });
1752
- });
1753
- if (implyFail.length) {
1754
- let msg = `${__('Implications failed:')}\n`;
1755
- implyFail.forEach(value => {
1756
- msg += value;
1757
- });
1758
- usage.fail(msg);
1759
- }
1760
- };
1761
- let conflicting = {};
1762
- self.conflicts = function conflicts(key, value) {
1763
- argsert('<string|object> [array|string]', [key, value], arguments.length);
1764
- if (typeof key === 'object') {
1765
- Object.keys(key).forEach(k => {
1766
- self.conflicts(k, key[k]);
1767
- });
1768
- }
1769
- else {
1770
- yargs.global(key);
1771
- if (!conflicting[key]) {
1772
- conflicting[key] = [];
1773
- }
1774
- if (Array.isArray(value)) {
1775
- value.forEach(i => self.conflicts(key, i));
1776
- }
1777
- else {
1778
- conflicting[key].push(value);
1779
- }
1780
- }
1781
- };
1782
- self.getConflicting = () => conflicting;
1783
- self.conflicting = function conflictingFn(argv) {
1784
- Object.keys(argv).forEach(key => {
1785
- if (conflicting[key]) {
1786
- conflicting[key].forEach(value => {
1787
- if (value && argv[key] !== undefined && argv[value] !== undefined) {
1788
- usage.fail(__('Arguments %s and %s are mutually exclusive', key, value));
1789
- }
1790
- });
1791
- }
1792
- });
1793
- };
1794
- self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
1795
- const threshold = 3;
1796
- potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
1797
- let recommended = null;
1798
- let bestDistance = Infinity;
1799
- for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
1800
- const d = levenshtein(cmd, candidate);
1801
- if (d <= threshold && d < bestDistance) {
1802
- bestDistance = d;
1803
- recommended = candidate;
1804
- }
1805
- }
1806
- if (recommended)
1807
- usage.fail(__('Did you mean %s?', recommended));
1808
- };
1809
- self.reset = function reset(localLookup) {
1810
- implied = objFilter(implied, k => !localLookup[k]);
1811
- conflicting = objFilter(conflicting, k => !localLookup[k]);
1812
- return self;
1813
- };
1814
- const frozens = [];
1815
- self.freeze = function freeze() {
1816
- frozens.push({
1817
- implied,
1818
- conflicting,
1819
- });
1820
- };
1821
- self.unfreeze = function unfreeze() {
1822
- const frozen = frozens.pop();
1823
- assertNotStrictEqual(frozen, undefined, shim);
1824
- ({ implied, conflicting } = frozen);
1825
- };
1826
- return self;
1827
- }
1828
-
1829
- let shim$1;
1830
- function YargsWithShim(_shim) {
1831
- shim$1 = _shim;
1832
- return Yargs;
1833
- }
1834
- function Yargs(processArgs = [], cwd = shim$1.process.cwd(), parentRequire) {
1835
- const self = {};
1836
- let command$1;
1837
- let completion$1 = null;
1838
- let groups = {};
1839
- let output = '';
1840
- const preservedGroups = {};
1841
- const globalMiddleware = new GlobalMiddleware(self);
1842
- let usage$1;
1843
- let validation$1;
1844
- const y18n = shim$1.y18n;
1845
- self.scriptName = function (scriptName) {
1846
- self.customScriptName = true;
1847
- self.$0 = scriptName;
1848
- return self;
1849
- };
1850
- let default$0;
1851
- if (/\b(node|iojs|electron)(\.exe)?$/.test(shim$1.process.argv()[0])) {
1852
- default$0 = shim$1.process.argv().slice(1, 2);
1853
- }
1854
- else {
1855
- default$0 = shim$1.process.argv().slice(0, 1);
1856
- }
1857
- self.$0 = default$0
1858
- .map(x => {
1859
- const b = rebase(cwd, x);
1860
- return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
1861
- })
1862
- .join(' ')
1863
- .trim();
1864
- if (shim$1.getEnv('_') && shim$1.getProcessArgvBin() === shim$1.getEnv('_')) {
1865
- self.$0 = shim$1
1866
- .getEnv('_')
1867
- .replace(`${shim$1.path.dirname(shim$1.process.execPath())}/`, '');
1868
- }
1869
- const context = { resets: -1, commands: [], fullCommands: [] };
1870
- self.getContext = () => context;
1871
- let hasOutput = false;
1872
- let exitError = null;
1873
- self.exit = (code, err) => {
1874
- hasOutput = true;
1875
- exitError = err;
1876
- if (exitProcess)
1877
- shim$1.process.exit(code);
1878
- };
1879
- let completionCommand = null;
1880
- self.completion = function (cmd, desc, fn) {
1881
- argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length);
1882
- if (typeof desc === 'function') {
1883
- fn = desc;
1884
- desc = undefined;
1885
- }
1886
- completionCommand = cmd || completionCommand || 'completion';
1887
- if (!desc && desc !== false) {
1888
- desc = 'generate completion script';
1889
- }
1890
- self.command(completionCommand, desc);
1891
- if (fn)
1892
- completion$1.registerFunction(fn);
1893
- return self;
1894
- };
1895
- let options;
1896
- self.resetOptions = self.reset = function resetOptions(aliases = {}) {
1897
- context.resets++;
1898
- options = options || {};
1899
- const tmpOptions = {};
1900
- tmpOptions.local = options.local ? options.local : [];
1901
- tmpOptions.configObjects = options.configObjects
1902
- ? options.configObjects
1903
- : [];
1904
- const localLookup = {};
1905
- tmpOptions.local.forEach(l => {
1906
- localLookup[l] = true;
1907
- (aliases[l] || []).forEach(a => {
1908
- localLookup[a] = true;
1909
- });
1910
- });
1911
- Object.assign(preservedGroups, Object.keys(groups).reduce((acc, groupName) => {
1912
- const keys = groups[groupName].filter(key => !(key in localLookup));
1913
- if (keys.length > 0) {
1914
- acc[groupName] = keys;
1915
- }
1916
- return acc;
1917
- }, {}));
1918
- groups = {};
1919
- const arrayOptions = [
1920
- 'array',
1921
- 'boolean',
1922
- 'string',
1923
- 'skipValidation',
1924
- 'count',
1925
- 'normalize',
1926
- 'number',
1927
- 'hiddenOptions',
1928
- ];
1929
- const objectOptions = [
1930
- 'narg',
1931
- 'key',
1932
- 'alias',
1933
- 'default',
1934
- 'defaultDescription',
1935
- 'config',
1936
- 'choices',
1937
- 'demandedOptions',
1938
- 'demandedCommands',
1939
- 'deprecatedOptions',
1940
- ];
1941
- arrayOptions.forEach(k => {
1942
- tmpOptions[k] = (options[k] || []).filter((k) => !localLookup[k]);
1943
- });
1944
- objectOptions.forEach((k) => {
1945
- tmpOptions[k] = objFilter(options[k], k => !localLookup[k]);
1946
- });
1947
- tmpOptions.envPrefix = options.envPrefix;
1948
- options = tmpOptions;
1949
- usage$1 = usage$1 ? usage$1.reset(localLookup) : usage(self, y18n, shim$1);
1950
- validation$1 = validation$1
1951
- ? validation$1.reset(localLookup)
1952
- : validation(self, usage$1, y18n, shim$1);
1953
- command$1 = command$1
1954
- ? command$1.reset()
1955
- : command(usage$1, validation$1, globalMiddleware, shim$1);
1956
- if (!completion$1)
1957
- completion$1 = completion(self, usage$1, command$1, shim$1);
1958
- globalMiddleware.reset();
1959
- completionCommand = null;
1960
- output = '';
1961
- exitError = null;
1962
- hasOutput = false;
1963
- self.parsed = false;
1964
- return self;
1965
- };
1966
- self.resetOptions();
1967
- const frozens = [];
1968
- function freeze() {
1969
- frozens.push({
1970
- options,
1971
- configObjects: options.configObjects.slice(0),
1972
- exitProcess,
1973
- groups,
1974
- strict,
1975
- strictCommands,
1976
- strictOptions,
1977
- completionCommand,
1978
- output,
1979
- exitError,
1980
- hasOutput,
1981
- parsed: self.parsed,
1982
- parseFn,
1983
- parseContext,
1984
- });
1985
- usage$1.freeze();
1986
- validation$1.freeze();
1987
- command$1.freeze();
1988
- globalMiddleware.freeze();
1989
- }
1990
- function unfreeze() {
1991
- const frozen = frozens.pop();
1992
- assertNotStrictEqual(frozen, undefined, shim$1);
1993
- let configObjects;
1994
- ({
1995
- options,
1996
- configObjects,
1997
- exitProcess,
1998
- groups,
1999
- output,
2000
- exitError,
2001
- hasOutput,
2002
- parsed: self.parsed,
2003
- strict,
2004
- strictCommands,
2005
- strictOptions,
2006
- completionCommand,
2007
- parseFn,
2008
- parseContext,
2009
- } = frozen);
2010
- options.configObjects = configObjects;
2011
- usage$1.unfreeze();
2012
- validation$1.unfreeze();
2013
- command$1.unfreeze();
2014
- globalMiddleware.unfreeze();
2015
- }
2016
- self.boolean = function (keys) {
2017
- argsert('<array|string>', [keys], arguments.length);
2018
- populateParserHintArray('boolean', keys);
2019
- return self;
2020
- };
2021
- self.array = function (keys) {
2022
- argsert('<array|string>', [keys], arguments.length);
2023
- populateParserHintArray('array', keys);
2024
- return self;
2025
- };
2026
- self.number = function (keys) {
2027
- argsert('<array|string>', [keys], arguments.length);
2028
- populateParserHintArray('number', keys);
2029
- return self;
2030
- };
2031
- self.normalize = function (keys) {
2032
- argsert('<array|string>', [keys], arguments.length);
2033
- populateParserHintArray('normalize', keys);
2034
- return self;
2035
- };
2036
- self.count = function (keys) {
2037
- argsert('<array|string>', [keys], arguments.length);
2038
- populateParserHintArray('count', keys);
2039
- return self;
2040
- };
2041
- self.string = function (keys) {
2042
- argsert('<array|string>', [keys], arguments.length);
2043
- populateParserHintArray('string', keys);
2044
- return self;
2045
- };
2046
- self.requiresArg = function (keys) {
2047
- argsert('<array|string|object> [number]', [keys], arguments.length);
2048
- if (typeof keys === 'string' && options.narg[keys]) {
2049
- return self;
2050
- }
2051
- else {
2052
- populateParserHintSingleValueDictionary(self.requiresArg, 'narg', keys, NaN);
2053
- }
2054
- return self;
2055
- };
2056
- self.skipValidation = function (keys) {
2057
- argsert('<array|string>', [keys], arguments.length);
2058
- populateParserHintArray('skipValidation', keys);
2059
- return self;
2060
- };
2061
- function populateParserHintArray(type, keys) {
2062
- keys = [].concat(keys);
2063
- keys.forEach(key => {
2064
- key = sanitizeKey(key);
2065
- options[type].push(key);
2066
- });
2067
- }
2068
- self.nargs = function (key, value) {
2069
- argsert('<string|object|array> [number]', [key, value], arguments.length);
2070
- populateParserHintSingleValueDictionary(self.nargs, 'narg', key, value);
2071
- return self;
2072
- };
2073
- self.choices = function (key, value) {
2074
- argsert('<object|string|array> [string|array]', [key, value], arguments.length);
2075
- populateParserHintArrayDictionary(self.choices, 'choices', key, value);
2076
- return self;
2077
- };
2078
- self.alias = function (key, value) {
2079
- argsert('<object|string|array> [string|array]', [key, value], arguments.length);
2080
- populateParserHintArrayDictionary(self.alias, 'alias', key, value);
2081
- return self;
2082
- };
2083
- self.default = self.defaults = function (key, value, defaultDescription) {
2084
- argsert('<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length);
2085
- if (defaultDescription) {
2086
- assertSingleKey(key, shim$1);
2087
- options.defaultDescription[key] = defaultDescription;
2088
- }
2089
- if (typeof value === 'function') {
2090
- assertSingleKey(key, shim$1);
2091
- if (!options.defaultDescription[key])
2092
- options.defaultDescription[key] = usage$1.functionDescription(value);
2093
- value = value.call();
2094
- }
2095
- populateParserHintSingleValueDictionary(self.default, 'default', key, value);
2096
- return self;
2097
- };
2098
- self.describe = function (key, desc) {
2099
- argsert('<object|string|array> [string]', [key, desc], arguments.length);
2100
- setKey(key, true);
2101
- usage$1.describe(key, desc);
2102
- return self;
2103
- };
2104
- function setKey(key, set) {
2105
- populateParserHintSingleValueDictionary(setKey, 'key', key, set);
2106
- return self;
2107
- }
2108
- function demandOption(keys, msg) {
2109
- argsert('<object|string|array> [string]', [keys, msg], arguments.length);
2110
- populateParserHintSingleValueDictionary(self.demandOption, 'demandedOptions', keys, msg);
2111
- return self;
2112
- }
2113
- self.demandOption = demandOption;
2114
- self.coerce = function (keys, value) {
2115
- argsert('<object|string|array> [function]', [keys, value], arguments.length);
2116
- if (Array.isArray(keys)) {
2117
- if (!value) {
2118
- throw new YError('coerce callback must be provided');
2119
- }
2120
- for (const key of keys) {
2121
- self.coerce(key, value);
2122
- }
2123
- return self;
2124
- }
2125
- else if (typeof keys === 'object') {
2126
- for (const key of Object.keys(keys)) {
2127
- self.coerce(key, keys[key]);
2128
- }
2129
- return self;
2130
- }
2131
- if (!value) {
2132
- throw new YError('coerce callback must be provided');
2133
- }
2134
- self.alias(keys, keys);
2135
- globalMiddleware.addCoerceMiddleware((argv, yargs) => {
2136
- let aliases;
2137
- return maybeAsyncResult(() => {
2138
- aliases = yargs.getAliases();
2139
- return value(argv[keys]);
2140
- }, (result) => {
2141
- argv[keys] = result;
2142
- if (aliases[keys]) {
2143
- for (const alias of aliases[keys]) {
2144
- argv[alias] = result;
2145
- }
2146
- }
2147
- return argv;
2148
- }, (err) => {
2149
- throw new YError(err.message);
2150
- });
2151
- }, keys);
2152
- return self;
2153
- };
2154
- function populateParserHintSingleValueDictionary(builder, type, key, value) {
2155
- populateParserHintDictionary(builder, type, key, value, (type, key, value) => {
2156
- options[type][key] = value;
2157
- });
2158
- }
2159
- function populateParserHintArrayDictionary(builder, type, key, value) {
2160
- populateParserHintDictionary(builder, type, key, value, (type, key, value) => {
2161
- options[type][key] = (options[type][key] || []).concat(value);
2162
- });
2163
- }
2164
- function populateParserHintDictionary(builder, type, key, value, singleKeyHandler) {
2165
- if (Array.isArray(key)) {
2166
- key.forEach(k => {
2167
- builder(k, value);
2168
- });
2169
- }
2170
- else if (((key) => typeof key === 'object')(key)) {
2171
- for (const k of objectKeys(key)) {
2172
- builder(k, key[k]);
2173
- }
2174
- }
2175
- else {
2176
- singleKeyHandler(type, sanitizeKey(key), value);
2177
- }
2178
- }
2179
- function sanitizeKey(key) {
2180
- if (key === '__proto__')
2181
- return '___proto___';
2182
- return key;
2183
- }
2184
- function deleteFromParserHintObject(optionKey) {
2185
- objectKeys(options).forEach((hintKey) => {
2186
- if (((key) => key === 'configObjects')(hintKey))
2187
- return;
2188
- const hint = options[hintKey];
2189
- if (Array.isArray(hint)) {
2190
- if (~hint.indexOf(optionKey))
2191
- hint.splice(hint.indexOf(optionKey), 1);
2192
- }
2193
- else if (typeof hint === 'object') {
2194
- delete hint[optionKey];
2195
- }
2196
- });
2197
- delete usage$1.getDescriptions()[optionKey];
2198
- }
2199
- self.config = function config(key = 'config', msg, parseFn) {
2200
- argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length);
2201
- if (typeof key === 'object' && !Array.isArray(key)) {
2202
- key = applyExtends(key, cwd, self.getParserConfiguration()['deep-merge-config'] || false, shim$1);
2203
- options.configObjects = (options.configObjects || []).concat(key);
2204
- return self;
2205
- }
2206
- if (typeof msg === 'function') {
2207
- parseFn = msg;
2208
- msg = undefined;
2209
- }
2210
- self.describe(key, msg || usage$1.deferY18nLookup('Path to JSON config file'));
2211
- (Array.isArray(key) ? key : [key]).forEach(k => {
2212
- options.config[k] = parseFn || true;
2213
- });
2214
- return self;
2215
- };
2216
- self.example = function (cmd, description) {
2217
- argsert('<string|array> [string]', [cmd, description], arguments.length);
2218
- if (Array.isArray(cmd)) {
2219
- cmd.forEach(exampleParams => self.example(...exampleParams));
2220
- }
2221
- else {
2222
- usage$1.example(cmd, description);
2223
- }
2224
- return self;
2225
- };
2226
- self.command = self.commands = function (cmd, description, builder, handler, middlewares, deprecated) {
2227
- argsert('<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length);
2228
- command$1.addHandler(cmd, description, builder, handler, middlewares, deprecated);
2229
- return self;
2230
- };
2231
- self.commandDir = function (dir, opts) {
2232
- argsert('<string> [object]', [dir, opts], arguments.length);
2233
- const req = parentRequire || shim$1.require;
2234
- command$1.addDirectory(dir, req, shim$1.getCallerFile(), opts);
2235
- return self;
2236
- };
2237
- self.demand = self.required = self.require = function demand(keys, max, msg) {
2238
- if (Array.isArray(max)) {
2239
- max.forEach(key => {
2240
- assertNotStrictEqual(msg, true, shim$1);
2241
- demandOption(key, msg);
2242
- });
2243
- max = Infinity;
2244
- }
2245
- else if (typeof max !== 'number') {
2246
- msg = max;
2247
- max = Infinity;
2248
- }
2249
- if (typeof keys === 'number') {
2250
- assertNotStrictEqual(msg, true, shim$1);
2251
- self.demandCommand(keys, max, msg, msg);
2252
- }
2253
- else if (Array.isArray(keys)) {
2254
- keys.forEach(key => {
2255
- assertNotStrictEqual(msg, true, shim$1);
2256
- demandOption(key, msg);
2257
- });
2258
- }
2259
- else {
2260
- if (typeof msg === 'string') {
2261
- demandOption(keys, msg);
2262
- }
2263
- else if (msg === true || typeof msg === 'undefined') {
2264
- demandOption(keys);
2265
- }
2266
- }
2267
- return self;
2268
- };
2269
- self.demandCommand = function demandCommand(min = 1, max, minMsg, maxMsg) {
2270
- argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length);
2271
- if (typeof max !== 'number') {
2272
- minMsg = max;
2273
- max = Infinity;
2274
- }
2275
- self.global('_', false);
2276
- options.demandedCommands._ = {
2277
- min,
2278
- max,
2279
- minMsg,
2280
- maxMsg,
2281
- };
2282
- return self;
2283
- };
2284
- self.getAliases = () => {
2285
- return self.parsed ? self.parsed.aliases : {};
2286
- };
2287
- self.getDemandedOptions = () => {
2288
- argsert([], 0);
2289
- return options.demandedOptions;
2290
- };
2291
- self.getDemandedCommands = () => {
2292
- argsert([], 0);
2293
- return options.demandedCommands;
2294
- };
2295
- self.deprecateOption = function deprecateOption(option, message) {
2296
- argsert('<string> [string|boolean]', [option, message], arguments.length);
2297
- options.deprecatedOptions[option] = message;
2298
- return self;
2299
- };
2300
- self.getDeprecatedOptions = () => {
2301
- argsert([], 0);
2302
- return options.deprecatedOptions;
2303
- };
2304
- self.implies = function (key, value) {
2305
- argsert('<string|object> [number|string|array]', [key, value], arguments.length);
2306
- validation$1.implies(key, value);
2307
- return self;
2308
- };
2309
- self.conflicts = function (key1, key2) {
2310
- argsert('<string|object> [string|array]', [key1, key2], arguments.length);
2311
- validation$1.conflicts(key1, key2);
2312
- return self;
2313
- };
2314
- self.usage = function (msg, description, builder, handler) {
2315
- argsert('<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length);
2316
- if (description !== undefined) {
2317
- assertNotStrictEqual(msg, null, shim$1);
2318
- if ((msg || '').match(/^\$0( |$)/)) {
2319
- return self.command(msg, description, builder, handler);
2320
- }
2321
- else {
2322
- throw new YError('.usage() description must start with $0 if being used as alias for .command()');
2323
- }
2324
- }
2325
- else {
2326
- usage$1.usage(msg);
2327
- return self;
2328
- }
2329
- };
2330
- self.epilogue = self.epilog = function (msg) {
2331
- argsert('<string>', [msg], arguments.length);
2332
- usage$1.epilog(msg);
2333
- return self;
2334
- };
2335
- self.fail = function (f) {
2336
- argsert('<function|boolean>', [f], arguments.length);
2337
- if (typeof f === 'boolean' && f !== false) {
2338
- throw new YError("Invalid first argument. Expected function or boolean 'false'");
2339
- }
2340
- usage$1.failFn(f);
2341
- return self;
2342
- };
2343
- self.check = function (f, global) {
2344
- argsert('<function> [boolean]', [f, global], arguments.length);
2345
- self.middleware((argv, _yargs) => {
2346
- return maybeAsyncResult(() => {
2347
- return f(argv);
2348
- }, (result) => {
2349
- if (!result) {
2350
- usage$1.fail(y18n.__('Argument check failed: %s', f.toString()));
2351
- }
2352
- else if (typeof result === 'string' || result instanceof Error) {
2353
- usage$1.fail(result.toString(), result);
2354
- }
2355
- return argv;
2356
- }, (err) => {
2357
- usage$1.fail(err.message ? err.message : err.toString(), err);
2358
- return argv;
2359
- });
2360
- }, false, global);
2361
- return self;
2362
- };
2363
- self.middleware = (callback, applyBeforeValidation, global = true) => {
2364
- return globalMiddleware.addMiddleware(callback, !!applyBeforeValidation, global);
2365
- };
2366
- self.global = function global(globals, global) {
2367
- argsert('<string|array> [boolean]', [globals, global], arguments.length);
2368
- globals = [].concat(globals);
2369
- if (global !== false) {
2370
- options.local = options.local.filter(l => globals.indexOf(l) === -1);
2371
- }
2372
- else {
2373
- globals.forEach(g => {
2374
- if (options.local.indexOf(g) === -1)
2375
- options.local.push(g);
2376
- });
2377
- }
2378
- return self;
2379
- };
2380
- self.pkgConf = function pkgConf(key, rootPath) {
2381
- argsert('<string> [string]', [key, rootPath], arguments.length);
2382
- let conf = null;
2383
- const obj = pkgUp(rootPath || cwd);
2384
- if (obj[key] && typeof obj[key] === 'object') {
2385
- conf = applyExtends(obj[key], rootPath || cwd, self.getParserConfiguration()['deep-merge-config'] || false, shim$1);
2386
- options.configObjects = (options.configObjects || []).concat(conf);
2387
- }
2388
- return self;
2389
- };
2390
- const pkgs = {};
2391
- function pkgUp(rootPath) {
2392
- const npath = rootPath || '*';
2393
- if (pkgs[npath])
2394
- return pkgs[npath];
2395
- let obj = {};
2396
- try {
2397
- let startDir = rootPath || shim$1.mainFilename;
2398
- if (!rootPath && shim$1.path.extname(startDir)) {
2399
- startDir = shim$1.path.dirname(startDir);
2400
- }
2401
- const pkgJsonPath = shim$1.findUp(startDir, (dir, names) => {
2402
- if (names.includes('package.json')) {
2403
- return 'package.json';
2404
- }
2405
- else {
2406
- return undefined;
2407
- }
2408
- });
2409
- assertNotStrictEqual(pkgJsonPath, undefined, shim$1);
2410
- obj = JSON.parse(shim$1.readFileSync(pkgJsonPath, 'utf8'));
2411
- }
2412
- catch (_noop) { }
2413
- pkgs[npath] = obj || {};
2414
- return pkgs[npath];
2415
- }
2416
- let parseFn = null;
2417
- let parseContext = null;
2418
- self.parse = function parse(args, shortCircuit, _parseFn) {
2419
- argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length);
2420
- freeze();
2421
- if (typeof args === 'undefined') {
2422
- const argv = self._parseArgs(processArgs);
2423
- const tmpParsed = self.parsed;
2424
- unfreeze();
2425
- self.parsed = tmpParsed;
2426
- return argv;
2427
- }
2428
- if (typeof shortCircuit === 'object') {
2429
- parseContext = shortCircuit;
2430
- shortCircuit = _parseFn;
2431
- }
2432
- if (typeof shortCircuit === 'function') {
2433
- parseFn = shortCircuit;
2434
- shortCircuit = false;
2435
- }
2436
- if (!shortCircuit)
2437
- processArgs = args;
2438
- if (parseFn)
2439
- exitProcess = false;
2440
- const parsed = self._parseArgs(args, !!shortCircuit);
2441
- completion$1.setParsed(self.parsed);
2442
- if (parseFn)
2443
- parseFn(exitError, parsed, output);
2444
- unfreeze();
2445
- return parsed;
2446
- };
2447
- self._getParseContext = () => parseContext || {};
2448
- self._hasParseCallback = () => !!parseFn;
2449
- self.option = self.options = function option(key, opt) {
2450
- argsert('<string|object> [object]', [key, opt], arguments.length);
2451
- if (typeof key === 'object') {
2452
- Object.keys(key).forEach(k => {
2453
- self.options(k, key[k]);
2454
- });
2455
- }
2456
- else {
2457
- if (typeof opt !== 'object') {
2458
- opt = {};
2459
- }
2460
- options.key[key] = true;
2461
- if (opt.alias)
2462
- self.alias(key, opt.alias);
2463
- const deprecate = opt.deprecate || opt.deprecated;
2464
- if (deprecate) {
2465
- self.deprecateOption(key, deprecate);
2466
- }
2467
- const demand = opt.demand || opt.required || opt.require;
2468
- if (demand) {
2469
- self.demand(key, demand);
2470
- }
2471
- if (opt.demandOption) {
2472
- self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined);
2473
- }
2474
- if (opt.conflicts) {
2475
- self.conflicts(key, opt.conflicts);
2476
- }
2477
- if ('default' in opt) {
2478
- self.default(key, opt.default);
2479
- }
2480
- if (opt.implies !== undefined) {
2481
- self.implies(key, opt.implies);
2482
- }
2483
- if (opt.nargs !== undefined) {
2484
- self.nargs(key, opt.nargs);
2485
- }
2486
- if (opt.config) {
2487
- self.config(key, opt.configParser);
2488
- }
2489
- if (opt.normalize) {
2490
- self.normalize(key);
2491
- }
2492
- if (opt.choices) {
2493
- self.choices(key, opt.choices);
2494
- }
2495
- if (opt.coerce) {
2496
- self.coerce(key, opt.coerce);
2497
- }
2498
- if (opt.group) {
2499
- self.group(key, opt.group);
2500
- }
2501
- if (opt.boolean || opt.type === 'boolean') {
2502
- self.boolean(key);
2503
- if (opt.alias)
2504
- self.boolean(opt.alias);
2505
- }
2506
- if (opt.array || opt.type === 'array') {
2507
- self.array(key);
2508
- if (opt.alias)
2509
- self.array(opt.alias);
2510
- }
2511
- if (opt.number || opt.type === 'number') {
2512
- self.number(key);
2513
- if (opt.alias)
2514
- self.number(opt.alias);
2515
- }
2516
- if (opt.string || opt.type === 'string') {
2517
- self.string(key);
2518
- if (opt.alias)
2519
- self.string(opt.alias);
2520
- }
2521
- if (opt.count || opt.type === 'count') {
2522
- self.count(key);
2523
- }
2524
- if (typeof opt.global === 'boolean') {
2525
- self.global(key, opt.global);
2526
- }
2527
- if (opt.defaultDescription) {
2528
- options.defaultDescription[key] = opt.defaultDescription;
2529
- }
2530
- if (opt.skipValidation) {
2531
- self.skipValidation(key);
2532
- }
2533
- const desc = opt.describe || opt.description || opt.desc;
2534
- self.describe(key, desc);
2535
- if (opt.hidden) {
2536
- self.hide(key);
2537
- }
2538
- if (opt.requiresArg) {
2539
- self.requiresArg(key);
2540
- }
2541
- }
2542
- return self;
2543
- };
2544
- self.getOptions = () => options;
2545
- self.positional = function (key, opts) {
2546
- argsert('<string> <object>', [key, opts], arguments.length);
2547
- if (context.resets === 0) {
2548
- throw new YError(".positional() can only be called in a command's builder function");
2549
- }
2550
- const supportedOpts = [
2551
- 'default',
2552
- 'defaultDescription',
2553
- 'implies',
2554
- 'normalize',
2555
- 'choices',
2556
- 'conflicts',
2557
- 'coerce',
2558
- 'type',
2559
- 'describe',
2560
- 'desc',
2561
- 'description',
2562
- 'alias',
2563
- ];
2564
- opts = objFilter(opts, (k, v) => {
2565
- let accept = supportedOpts.indexOf(k) !== -1;
2566
- if (k === 'type' && ['string', 'number', 'boolean'].indexOf(v) === -1)
2567
- accept = false;
2568
- return accept;
2569
- });
2570
- const fullCommand = context.fullCommands[context.fullCommands.length - 1];
2571
- const parseOptions = fullCommand
2572
- ? command$1.cmdToParseOptions(fullCommand)
2573
- : {
2574
- array: [],
2575
- alias: {},
2576
- default: {},
2577
- demand: {},
2578
- };
2579
- objectKeys(parseOptions).forEach(pk => {
2580
- const parseOption = parseOptions[pk];
2581
- if (Array.isArray(parseOption)) {
2582
- if (parseOption.indexOf(key) !== -1)
2583
- opts[pk] = true;
2584
- }
2585
- else {
2586
- if (parseOption[key] && !(pk in opts))
2587
- opts[pk] = parseOption[key];
2588
- }
2589
- });
2590
- self.group(key, usage$1.getPositionalGroupName());
2591
- return self.option(key, opts);
2592
- };
2593
- self.group = function group(opts, groupName) {
2594
- argsert('<string|array> <string>', [opts, groupName], arguments.length);
2595
- const existing = preservedGroups[groupName] || groups[groupName];
2596
- if (preservedGroups[groupName]) {
2597
- delete preservedGroups[groupName];
2598
- }
2599
- const seen = {};
2600
- groups[groupName] = (existing || []).concat(opts).filter(key => {
2601
- if (seen[key])
2602
- return false;
2603
- return (seen[key] = true);
2604
- });
2605
- return self;
2606
- };
2607
- self.getGroups = () => Object.assign({}, groups, preservedGroups);
2608
- self.env = function (prefix) {
2609
- argsert('[string|boolean]', [prefix], arguments.length);
2610
- if (prefix === false)
2611
- delete options.envPrefix;
2612
- else
2613
- options.envPrefix = prefix || '';
2614
- return self;
2615
- };
2616
- self.wrap = function (cols) {
2617
- argsert('<number|null|undefined>', [cols], arguments.length);
2618
- usage$1.wrap(cols);
2619
- return self;
2620
- };
2621
- let strict = false;
2622
- self.strict = function (enabled) {
2623
- argsert('[boolean]', [enabled], arguments.length);
2624
- strict = enabled !== false;
2625
- return self;
2626
- };
2627
- self.getStrict = () => strict;
2628
- let strictCommands = false;
2629
- self.strictCommands = function (enabled) {
2630
- argsert('[boolean]', [enabled], arguments.length);
2631
- strictCommands = enabled !== false;
2632
- return self;
2633
- };
2634
- self.getStrictCommands = () => strictCommands;
2635
- let strictOptions = false;
2636
- self.strictOptions = function (enabled) {
2637
- argsert('[boolean]', [enabled], arguments.length);
2638
- strictOptions = enabled !== false;
2639
- return self;
2640
- };
2641
- self.getStrictOptions = () => strictOptions;
2642
- let parserConfig = {};
2643
- self.parserConfiguration = function parserConfiguration(config) {
2644
- argsert('<object>', [config], arguments.length);
2645
- parserConfig = config;
2646
- return self;
2647
- };
2648
- self.getParserConfiguration = () => parserConfig;
2649
- self.getHelp = async function () {
2650
- hasOutput = true;
2651
- if (!usage$1.hasCachedHelpMessage()) {
2652
- if (!self.parsed) {
2653
- const parse = self._parseArgs(processArgs, undefined, undefined, 0, true);
2654
- if (isPromise(parse)) {
2655
- return parse.then(() => {
2656
- return usage$1.help();
2657
- });
2658
- }
2659
- }
2660
- if (command$1.hasDefaultCommand()) {
2661
- context.resets++;
2662
- command$1.runDefaultBuilderOn(self);
2663
- }
2664
- }
2665
- return usage$1.help();
2666
- };
2667
- self.showHelp = function (level) {
2668
- argsert('[string|function]', [level], arguments.length);
2669
- hasOutput = true;
2670
- if (!usage$1.hasCachedHelpMessage()) {
2671
- if (!self.parsed) {
2672
- const parse = self._parseArgs(processArgs, undefined, undefined, 0, true);
2673
- if (isPromise(parse)) {
2674
- parse.then(() => {
2675
- usage$1.showHelp(level);
2676
- });
2677
- return self;
2678
- }
2679
- }
2680
- if (command$1.hasDefaultCommand()) {
2681
- context.resets++;
2682
- command$1.runDefaultBuilderOn(self);
2683
- }
2684
- }
2685
- usage$1.showHelp(level);
2686
- return self;
2687
- };
2688
- self.showVersion = function (level) {
2689
- argsert('[string|function]', [level], arguments.length);
2690
- usage$1.showVersion(level);
2691
- return self;
2692
- };
2693
- let versionOpt = null;
2694
- self.version = function version(opt, msg, ver) {
2695
- const defaultVersionOpt = 'version';
2696
- argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length);
2697
- if (versionOpt) {
2698
- deleteFromParserHintObject(versionOpt);
2699
- usage$1.version(undefined);
2700
- versionOpt = null;
2701
- }
2702
- if (arguments.length === 0) {
2703
- ver = guessVersion();
2704
- opt = defaultVersionOpt;
2705
- }
2706
- else if (arguments.length === 1) {
2707
- if (opt === false) {
2708
- return self;
2709
- }
2710
- ver = opt;
2711
- opt = defaultVersionOpt;
2712
- }
2713
- else if (arguments.length === 2) {
2714
- ver = msg;
2715
- msg = undefined;
2716
- }
2717
- versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt;
2718
- msg = msg || usage$1.deferY18nLookup('Show version number');
2719
- usage$1.version(ver || undefined);
2720
- self.boolean(versionOpt);
2721
- self.describe(versionOpt, msg);
2722
- return self;
2723
- };
2724
- function guessVersion() {
2725
- const obj = pkgUp();
2726
- return obj.version || 'unknown';
2727
- }
2728
- let helpOpt = null;
2729
- self.addHelpOpt = self.help = function addHelpOpt(opt, msg) {
2730
- const defaultHelpOpt = 'help';
2731
- argsert('[string|boolean] [string]', [opt, msg], arguments.length);
2732
- if (helpOpt) {
2733
- deleteFromParserHintObject(helpOpt);
2734
- helpOpt = null;
2735
- }
2736
- if (arguments.length === 1) {
2737
- if (opt === false)
2738
- return self;
2739
- }
2740
- helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
2741
- self.boolean(helpOpt);
2742
- self.describe(helpOpt, msg || usage$1.deferY18nLookup('Show help'));
2743
- return self;
2744
- };
2745
- const defaultShowHiddenOpt = 'show-hidden';
2746
- options.showHiddenOpt = defaultShowHiddenOpt;
2747
- self.addShowHiddenOpt = self.showHidden = function addShowHiddenOpt(opt, msg) {
2748
- argsert('[string|boolean] [string]', [opt, msg], arguments.length);
2749
- if (arguments.length === 1) {
2750
- if (opt === false)
2751
- return self;
2752
- }
2753
- const showHiddenOpt = typeof opt === 'string' ? opt : defaultShowHiddenOpt;
2754
- self.boolean(showHiddenOpt);
2755
- self.describe(showHiddenOpt, msg || usage$1.deferY18nLookup('Show hidden options'));
2756
- options.showHiddenOpt = showHiddenOpt;
2757
- return self;
2758
- };
2759
- self.hide = function hide(key) {
2760
- argsert('<string>', [key], arguments.length);
2761
- options.hiddenOptions.push(key);
2762
- return self;
2763
- };
2764
- self.showHelpOnFail = function showHelpOnFail(enabled, message) {
2765
- argsert('[boolean|string] [string]', [enabled, message], arguments.length);
2766
- usage$1.showHelpOnFail(enabled, message);
2767
- return self;
2768
- };
2769
- let exitProcess = true;
2770
- self.exitProcess = function (enabled = true) {
2771
- argsert('[boolean]', [enabled], arguments.length);
2772
- exitProcess = enabled;
2773
- return self;
2774
- };
2775
- self.getExitProcess = () => exitProcess;
2776
- self.showCompletionScript = function ($0, cmd) {
2777
- argsert('[string] [string]', [$0, cmd], arguments.length);
2778
- $0 = $0 || self.$0;
2779
- _logger.log(completion$1.generateCompletionScript($0, cmd || completionCommand || 'completion'));
2780
- return self;
2781
- };
2782
- self.getCompletion = async function (args, done) {
2783
- argsert('<array> [function]', [args, done], arguments.length);
2784
- if (!done) {
2785
- return new Promise((resolve, reject) => {
2786
- completion$1.getCompletion(args, (err, completions) => {
2787
- if (err)
2788
- reject(err);
2789
- else
2790
- resolve(completions);
2791
- });
2792
- });
2793
- }
2794
- else {
2795
- return completion$1.getCompletion(args, done);
2796
- }
2797
- };
2798
- self.locale = function (locale) {
2799
- argsert('[string]', [locale], arguments.length);
2800
- if (!locale) {
2801
- guessLocale();
2802
- return y18n.getLocale();
2803
- }
2804
- detectLocale = false;
2805
- y18n.setLocale(locale);
2806
- return self;
2807
- };
2808
- self.updateStrings = self.updateLocale = function (obj) {
2809
- argsert('<object>', [obj], arguments.length);
2810
- detectLocale = false;
2811
- y18n.updateLocale(obj);
2812
- return self;
2813
- };
2814
- let detectLocale = true;
2815
- self.detectLocale = function (detect) {
2816
- argsert('<boolean>', [detect], arguments.length);
2817
- detectLocale = detect;
2818
- return self;
2819
- };
2820
- self.getDetectLocale = () => detectLocale;
2821
- const _logger = {
2822
- log(...args) {
2823
- if (!self._hasParseCallback())
2824
- console.log(...args);
2825
- hasOutput = true;
2826
- if (output.length)
2827
- output += '\n';
2828
- output += args.join(' ');
2829
- },
2830
- error(...args) {
2831
- if (!self._hasParseCallback())
2832
- console.error(...args);
2833
- hasOutput = true;
2834
- if (output.length)
2835
- output += '\n';
2836
- output += args.join(' ');
2837
- },
2838
- };
2839
- self._getLoggerInstance = () => _logger;
2840
- self._hasOutput = () => hasOutput;
2841
- self._setHasOutput = () => {
2842
- hasOutput = true;
2843
- };
2844
- let recommendCommands;
2845
- self.recommendCommands = function (recommend = true) {
2846
- argsert('[boolean]', [recommend], arguments.length);
2847
- recommendCommands = recommend;
2848
- return self;
2849
- };
2850
- self.getUsageInstance = () => usage$1;
2851
- self.getValidationInstance = () => validation$1;
2852
- self.getCommandInstance = () => command$1;
2853
- self.terminalWidth = () => {
2854
- argsert([], 0);
2855
- return shim$1.process.stdColumns;
2856
- };
2857
- Object.defineProperty(self, 'argv', {
2858
- get: () => {
2859
- return self.parse();
2860
- },
2861
- enumerable: true,
2862
- });
2863
- self._parseArgs = function parseArgs(args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) {
2864
- let skipValidation = !!calledFromCommand || helpOnly;
2865
- args = args || processArgs;
2866
- options.__ = y18n.__;
2867
- options.configuration = self.getParserConfiguration();
2868
- const populateDoubleDash = !!options.configuration['populate--'];
2869
- const config = Object.assign({}, options.configuration, {
2870
- 'populate--': true,
2871
- });
2872
- const parsed = shim$1.Parser.detailed(args, Object.assign({}, options, {
2873
- configuration: Object.assign({ 'parse-positional-numbers': false }, config),
2874
- }));
2875
- let argv = parsed.argv;
2876
- let argvPromise = undefined;
2877
- if (parseContext)
2878
- argv = Object.assign({}, argv, parseContext);
2879
- const aliases = parsed.aliases;
2880
- argv.$0 = self.$0;
2881
- self.parsed = parsed;
2882
- if (commandIndex === 0) {
2883
- usage$1.clearCachedHelpMessage();
2884
- }
2885
- try {
2886
- guessLocale();
2887
- if (shortCircuit) {
2888
- return self._postProcess(argv, populateDoubleDash, !!calledFromCommand, false);
2889
- }
2890
- if (helpOpt) {
2891
- const helpCmds = [helpOpt]
2892
- .concat(aliases[helpOpt] || [])
2893
- .filter(k => k.length > 1);
2894
- if (~helpCmds.indexOf('' + argv._[argv._.length - 1])) {
2895
- argv._.pop();
2896
- argv[helpOpt] = true;
2897
- }
2898
- }
2899
- const handlerKeys = command$1.getCommands();
2900
- const requestCompletions = completion$1.completionKey in argv;
2901
- const skipRecommendation = argv[helpOpt] || requestCompletions || helpOnly;
2902
- if (argv._.length) {
2903
- if (handlerKeys.length) {
2904
- let firstUnknownCommand;
2905
- for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
2906
- cmd = String(argv._[i]);
2907
- if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
2908
- const innerArgv = command$1.runCommand(cmd, self, parsed, i + 1, helpOnly);
2909
- return self._postProcess(innerArgv, populateDoubleDash, !!calledFromCommand, false);
2910
- }
2911
- else if (!firstUnknownCommand && cmd !== completionCommand) {
2912
- firstUnknownCommand = cmd;
2913
- break;
2914
- }
2915
- }
2916
- if (command$1.hasDefaultCommand() && !skipRecommendation) {
2917
- const innerArgv = command$1.runCommand(null, self, parsed, 0, helpOnly);
2918
- return self._postProcess(innerArgv, populateDoubleDash, !!calledFromCommand, false);
2919
- }
2920
- if (recommendCommands && firstUnknownCommand && !skipRecommendation) {
2921
- validation$1.recommendCommands(firstUnknownCommand, handlerKeys);
2922
- }
2923
- }
2924
- if (completionCommand &&
2925
- ~argv._.indexOf(completionCommand) &&
2926
- !requestCompletions) {
2927
- if (exitProcess)
2928
- setBlocking(true);
2929
- self.showCompletionScript();
2930
- self.exit(0);
2931
- }
2932
- }
2933
- else if (command$1.hasDefaultCommand() && !skipRecommendation) {
2934
- const innerArgv = command$1.runCommand(null, self, parsed, 0, helpOnly);
2935
- return self._postProcess(innerArgv, populateDoubleDash, !!calledFromCommand, false);
2936
- }
2937
- if (requestCompletions) {
2938
- if (exitProcess)
2939
- setBlocking(true);
2940
- args = [].concat(args);
2941
- const completionArgs = args.slice(args.indexOf(`--${completion$1.completionKey}`) + 1);
2942
- completion$1.getCompletion(completionArgs, (err, completions) => {
2943
- if (err)
2944
- throw new YError(err.message);
2945
- (completions || []).forEach(completion => {
2946
- _logger.log(completion);
2947
- });
2948
- self.exit(0);
2949
- });
2950
- return self._postProcess(argv, !populateDoubleDash, !!calledFromCommand, false);
2951
- }
2952
- if (!hasOutput) {
2953
- Object.keys(argv).forEach(key => {
2954
- if (key === helpOpt && argv[key]) {
2955
- if (exitProcess)
2956
- setBlocking(true);
2957
- skipValidation = true;
2958
- self.showHelp('log');
2959
- self.exit(0);
2960
- }
2961
- else if (key === versionOpt && argv[key]) {
2962
- if (exitProcess)
2963
- setBlocking(true);
2964
- skipValidation = true;
2965
- usage$1.showVersion('log');
2966
- self.exit(0);
2967
- }
2968
- });
2969
- }
2970
- if (!skipValidation && options.skipValidation.length > 0) {
2971
- skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true);
2972
- }
2973
- if (!skipValidation) {
2974
- if (parsed.error)
2975
- throw new YError(parsed.error.message);
2976
- if (!requestCompletions) {
2977
- const validation = self._runValidation(aliases, {}, parsed.error);
2978
- if (!calledFromCommand) {
2979
- argvPromise = applyMiddleware(argv, self, globalMiddleware.getMiddleware(), true);
2980
- }
2981
- argvPromise = validateAsync(validation, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv);
2982
- if (isPromise(argvPromise) && !calledFromCommand) {
2983
- argvPromise = argvPromise.then(() => {
2984
- return applyMiddleware(argv, self, globalMiddleware.getMiddleware(), false);
2985
- });
2986
- }
2987
- }
2988
- }
2989
- }
2990
- catch (err) {
2991
- if (err instanceof YError)
2992
- usage$1.fail(err.message, err);
2993
- else
2994
- throw err;
2995
- }
2996
- return self._postProcess(argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true);
2997
- };
2998
- function validateAsync(validation, argv) {
2999
- return maybeAsyncResult(argv, result => {
3000
- validation(result);
3001
- return result;
3002
- });
3003
- }
3004
- self._postProcess = function (argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) {
3005
- if (calledFromCommand)
3006
- return argv;
3007
- if (isPromise(argv))
3008
- return argv;
3009
- if (!populateDoubleDash) {
3010
- argv = self._copyDoubleDash(argv);
3011
- }
3012
- const parsePositionalNumbers = self.getParserConfiguration()['parse-positional-numbers'] ||
3013
- self.getParserConfiguration()['parse-positional-numbers'] === undefined;
3014
- if (parsePositionalNumbers) {
3015
- argv = self._parsePositionalNumbers(argv);
3016
- }
3017
- if (runGlobalMiddleware) {
3018
- argv = applyMiddleware(argv, self, globalMiddleware.getMiddleware(), false);
3019
- }
3020
- return argv;
3021
- };
3022
- self._copyDoubleDash = function (argv) {
3023
- if (!argv._ || !argv['--'])
3024
- return argv;
3025
- argv._.push.apply(argv._, argv['--']);
3026
- try {
3027
- delete argv['--'];
3028
- }
3029
- catch (_err) { }
3030
- return argv;
3031
- };
3032
- self._parsePositionalNumbers = function (argv) {
3033
- const args = argv['--'] ? argv['--'] : argv._;
3034
- for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
3035
- if (shim$1.Parser.looksLikeNumber(arg) &&
3036
- Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) {
3037
- args[i] = Number(arg);
3038
- }
3039
- }
3040
- return argv;
3041
- };
3042
- self._runValidation = function runValidation(aliases, positionalMap, parseErrors, isDefaultCommand = false) {
3043
- aliases = Object.assign({}, aliases);
3044
- positionalMap = Object.assign({}, positionalMap);
3045
- const demandedOptions = Object.assign({}, self.getDemandedOptions());
3046
- return (argv) => {
3047
- if (parseErrors)
3048
- throw new YError(parseErrors.message);
3049
- validation$1.nonOptionCount(argv);
3050
- validation$1.requiredArguments(argv, demandedOptions);
3051
- let failedStrictCommands = false;
3052
- if (strictCommands) {
3053
- failedStrictCommands = validation$1.unknownCommands(argv);
3054
- }
3055
- if (strict && !failedStrictCommands) {
3056
- validation$1.unknownArguments(argv, aliases, positionalMap, isDefaultCommand);
3057
- }
3058
- else if (strictOptions) {
3059
- validation$1.unknownArguments(argv, aliases, {}, false, false);
3060
- }
3061
- validation$1.limitedChoices(argv);
3062
- validation$1.implications(argv);
3063
- validation$1.conflicting(argv);
3064
- };
3065
- };
3066
- function guessLocale() {
3067
- if (!detectLocale)
3068
- return;
3069
- const locale = shim$1.getEnv('LC_ALL') ||
3070
- shim$1.getEnv('LC_MESSAGES') ||
3071
- shim$1.getEnv('LANG') ||
3072
- shim$1.getEnv('LANGUAGE') ||
3073
- 'en_US';
3074
- self.locale(locale.replace(/[.:].*/, ''));
3075
- }
3076
- self.help();
3077
- self.version();
3078
- return self;
3079
- }
3080
- const rebase = (base, dir) => shim$1.path.relative(base, dir);
3081
- function isYargsInstance(y) {
3082
- return !!y && typeof y._parseArgs === 'function';
3083
- }
3084
-
3085
- var _a, _b;
3086
- const { readFileSync } = require('fs');
3087
- const { inspect } = require('util');
3088
- const { resolve } = require('path');
3089
- const y18n = require('y18n');
3090
- const Parser = require('yargs-parser');
3091
- var cjsPlatformShim = {
3092
- assert: {
3093
- notStrictEqual: assert.notStrictEqual,
3094
- strictEqual: assert.strictEqual,
3095
- },
3096
- cliui: require('cliui'),
3097
- findUp: require('escalade/sync'),
3098
- getEnv: (key) => {
3099
- return process.env[key];
3100
- },
3101
- getCallerFile: require('get-caller-file'),
3102
- getProcessArgvBin: getProcessArgvBin,
3103
- inspect,
3104
- mainFilename: (_b = (_a = require === null || require === void 0 ? void 0 : require.main) === null || _a === void 0 ? void 0 : _a.filename) !== null && _b !== void 0 ? _b : process.cwd(),
3105
- Parser,
3106
- path: require('path'),
3107
- process: {
3108
- argv: () => process.argv,
3109
- cwd: process.cwd,
3110
- execPath: () => process.execPath,
3111
- exit: (code) => {
3112
- process.exit(code);
3113
- },
3114
- nextTick: process.nextTick,
3115
- stdColumns: typeof process.stdout.columns !== 'undefined'
3116
- ? process.stdout.columns
3117
- : null,
3118
- },
3119
- readFileSync,
3120
- require: require,
3121
- requireDirectory: require('require-directory'),
3122
- stringWidth: require('string-width'),
3123
- y18n: y18n({
3124
- directory: resolve(__dirname, '../locales'),
3125
- updateFiles: false,
3126
- }),
3127
- };
3128
-
3129
- const minNodeVersion = process && process.env && process.env.YARGS_MIN_NODE_VERSION
3130
- ? Number(process.env.YARGS_MIN_NODE_VERSION)
3131
- : 10;
3132
- if (process && process.version) {
3133
- const major = Number(process.version.match(/v([^.]+)/)[1]);
3134
- if (major < minNodeVersion) {
3135
- throw Error(`yargs supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs#supported-nodejs-versions`);
3136
- }
3137
- }
3138
- const Parser$1 = require('yargs-parser');
3139
- const Yargs$1 = YargsWithShim(cjsPlatformShim);
3140
- var cjs = {
3141
- applyExtends,
3142
- cjsPlatformShim,
3143
- Yargs: Yargs$1,
3144
- argsert,
3145
- isPromise,
3146
- objFilter,
3147
- parseCommand,
3148
- Parser: Parser$1,
3149
- processArgv,
3150
- rebase,
3151
- YError,
3152
- };
3153
-
3154
- module.exports = cjs;
1
+ "use strict";var t=require("assert");class e extends Error{constructor(t){super(t||"yargs error"),this.name="YError",Error.captureStackTrace(this,e)}}let s,n=[];function i(t,o,a,h){s=h;let l={};if(Object.prototype.hasOwnProperty.call(t,"extends")){if("string"!=typeof t.extends)return l;const r=/\.json|\..*rc$/.test(t.extends);let h=null;if(r)h=function(t,e){return s.path.resolve(t,e)}(o,t.extends);else try{h=require.resolve(t.extends)}catch(e){return t}!function(t){if(n.indexOf(t)>-1)throw new e(`Circular extended configurations: '${t}'.`)}(h),n.push(h),l=r?JSON.parse(s.readFileSync(h,"utf8")):require(t.extends),delete t.extends,l=i(l,s.path.dirname(h),a,s)}return n=[],a?r(l,t):Object.assign({},l,t)}function r(t,e){const s={};function n(t){return t&&"object"==typeof t&&!Array.isArray(t)}Object.assign(s,t);for(const i of Object.keys(e))n(e[i])&&n(s[i])?s[i]=r(t[i],e[i]):s[i]=e[i];return s}function o(t){const e=t.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),s=/\.*[\][<>]/g,n=e.shift();if(!n)throw new Error(`No command found in: ${t}`);const i={cmd:n.replace(s,""),demanded:[],optional:[]};return e.forEach(((t,n)=>{let r=!1;t=t.replace(/\s/g,""),/\.+[\]>]/.test(t)&&n===e.length-1&&(r=!0),/^\[/.test(t)?i.optional.push({cmd:t.replace(s,"").split("|"),variadic:r}):i.demanded.push({cmd:t.replace(s,"").split("|"),variadic:r})})),i}const a=["first","second","third","fourth","fifth","sixth"];function h(t,s,n){try{let i=0;const[r,a,h]="object"==typeof t?[{demanded:[],optional:[]},t,s]:[o(`cmd ${t}`),s,n],d=[].slice.call(a);for(;d.length&&void 0===d[d.length-1];)d.pop();const u=h||d.length;if(u<r.demanded.length)throw new e(`Not enough arguments provided. Expected ${r.demanded.length} but received ${d.length}.`);const p=r.demanded.length+r.optional.length;if(u>p)throw new e(`Too many arguments provided. Expected max ${p} but received ${u}.`);r.demanded.forEach((t=>{const e=l(d.shift());0===t.cmd.filter((t=>t===e||"*"===t)).length&&c(e,t.cmd,i),i+=1})),r.optional.forEach((t=>{if(0===d.length)return;const e=l(d.shift());0===t.cmd.filter((t=>t===e||"*"===t)).length&&c(e,t.cmd,i),i+=1}))}catch(t){console.warn(t.stack)}}function l(t){return Array.isArray(t)?"array":null===t?"null":typeof t}function c(t,s,n){throw new e(`Invalid ${a[n]||"manyith"} argument. Expected ${s.join(" or ")} but received ${t}.`)}function d(t){return!!t&&!!t.then&&"function"==typeof t.then}function u(t,e,s,n){s.assert.notStrictEqual(t,e,n)}function p(t,e){e.assert.strictEqual(typeof t,"string")}function g(t){return Object.keys(t)}function m(t={},e=(()=>!0)){const s={};return g(t).forEach((n=>{e(n,t[n])&&(s[n]=t[n])})),s}function f(){return process.versions.electron&&!process.defaultApp?0:1}function y(){return process.argv[f()]}var b=Object.freeze({__proto__:null,hideBin:function(t){return t.slice(f()+1)},getProcessArgvBin:y});function O(t,e,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(t):n?n.value:e.get(t)}function v(t,e,s,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(t,s):i?i.value=s:e.set(t,s),s}class w{constructor(t){this.globalMiddleware=[],this.frozens=[],this.yargs=t}addMiddleware(t,e,s=!0){if(h("<array|function> [boolean] [boolean]",[t,e,s],arguments.length),Array.isArray(t)){for(let n=0;n<t.length;n++){if("function"!=typeof t[n])throw Error("middleware must be a function");const i=t[n];i.applyBeforeValidation=e,i.global=s}Array.prototype.push.apply(this.globalMiddleware,t)}else if("function"==typeof t){const n=t;n.applyBeforeValidation=e,n.global=s,this.globalMiddleware.push(t)}return this.yargs}addCoerceMiddleware(t,e){const s=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((t=>{const n=[...s[e]||[],e];return!t.option||!n.includes(t.option)})),t.option=e,this.addMiddleware(t,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){const t=this.frozens.pop();void 0!==t&&(this.globalMiddleware=t)}reset(){this.globalMiddleware=this.globalMiddleware.filter((t=>t.global))}}function C(t,e,s,n){return s.reduce(((t,s)=>{if(s.applyBeforeValidation!==n)return t;if(d(t))return t.then((t=>Promise.all([t,s(t,e)]))).then((([t,e])=>Object.assign(t,e)));{const n=s(t,e);return d(n)?n.then((e=>Object.assign(t,e))):Object.assign(t,n)}}),t)}function j(t,e,s=(t=>{throw t})){try{const s="function"==typeof t?t():t;return d(s)?s.then((t=>e(t))):e(s)}catch(t){return s(t)}}const x=/(^\*)|(^\$0)/;class _{constructor(t,e,s,n){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=n,this.usage=t,this.globalMiddleware=s,this.validation=e}addDirectory(t,e,s,n){"boolean"!=typeof(n=n||{}).recurse&&(n.recurse=!1),Array.isArray(n.extensions)||(n.extensions=["js"]);const i="function"==typeof n.visit?n.visit:t=>t;n.visit=(t,e,s)=>{const n=i(t,e,s);if(n){if(this.requireCache.has(e))return n;this.requireCache.add(e),this.addHandler(n)}return n},this.shim.requireDirectory({require:e,filename:s},t,n)}addHandler(t,e,s,n,i,r){let a=[];const h=function(t){return t?t.map((t=>(t.applyBeforeValidation=!1,t))):[]}(i);if(n=n||(()=>{}),Array.isArray(t))if(function(t){return t.every((t=>"string"==typeof t))}(t))[t,...a]=t;else for(const e of t)this.addHandler(e);else{if(function(t){return"object"==typeof t&&!Array.isArray(t)}(t)){let e=Array.isArray(t.command)||"string"==typeof t.command?t.command:this.moduleName(t);return t.aliases&&(e=[].concat(e).concat(t.aliases)),void this.addHandler(e,this.extractDesc(t),t.builder,t.handler,t.middlewares,t.deprecated)}if(M(s))return void this.addHandler([t].concat(a),e,s.builder,s.handler,s.middlewares,s.deprecated)}if("string"==typeof t){const i=o(t);a=a.map((t=>o(t).cmd));let l=!1;const c=[i.cmd].concat(a).filter((t=>!x.test(t)||(l=!0,!1)));0===c.length&&l&&c.push("$0"),l&&(i.cmd=c[0],a=c.slice(1),t=t.replace(x,i.cmd)),a.forEach((t=>{this.aliasMap[t]=i.cmd})),!1!==e&&this.usage.command(t,e,l,a,r),this.handlers[i.cmd]={original:t,description:e,handler:n,builder:s||{},middlewares:h,deprecated:r,demanded:i.demanded,optional:i.optional},l&&(this.defaultCommand=this.handlers[i.cmd])}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(t,e,s,n,i,r){const o=this.handlers[t]||this.handlers[this.aliasMap[t]]||this.defaultCommand,a=e.getInternalMethods().getContext(),h=a.commands.slice(),l=!t;t&&(a.commands.push(t),a.fullCommands.push(o.original));const c=this.applyBuilderUpdateUsageAndParse(l,o,e,s.aliases,h,n,i,r);return d(c)?c.then((t=>this.applyMiddlewareAndGetResult(l,o,t.innerArgv,a,i,t.aliases,e))):this.applyMiddlewareAndGetResult(l,o,c.innerArgv,a,i,c.aliases,e)}applyBuilderUpdateUsageAndParse(t,e,s,n,i,r,o,a){const h=e.builder;let l=s;if(k(h)){const c=h(s.getInternalMethods().reset(n),a);if(d(c))return c.then((n=>{var a;return l=(a=n)&&"function"==typeof a.getInternalMethods?n:s,this.parseAndUpdateUsage(t,e,l,i,r,o)}))}else(function(t){return"object"==typeof t})(h)&&(l=s.getInternalMethods().reset(n),Object.keys(e.builder).forEach((t=>{l.option(t,h[t])})));return this.parseAndUpdateUsage(t,e,l,i,r,o)}parseAndUpdateUsage(t,e,s,n,i,r){t&&s.getInternalMethods().getUsageInstance().unfreeze(),this.shouldUpdateUsage(s)&&s.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(n,e),e.description);const o=s.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,i,r);return d(o)?o.then((t=>({aliases:s.parsed.aliases,innerArgv:t}))):{aliases:s.parsed.aliases,innerArgv:o}}shouldUpdateUsage(t){return!t.getInternalMethods().getUsageInstance().getUsageDisabled()&&0===t.getInternalMethods().getUsageInstance().getUsage().length}usageFromParentCommandsCommandHandler(t,e){const s=x.test(e.original)?e.original.replace(x,"").trim():e.original,n=t.filter((t=>!x.test(t)));return n.push(s),`$0 ${n.join(" ")}`}applyMiddlewareAndGetResult(t,e,s,n,i,r,o){let a={};if(i)return s;o.getInternalMethods().getHasOutput()||(a=this.populatePositionals(e,s,n,o));const h=this.globalMiddleware.getMiddleware().slice(0).concat(e.middlewares);if(s=C(s,o,h,!0),!o.getInternalMethods().getHasOutput()){const e=o.getInternalMethods().runValidation(r,a,o.parsed.error,t);s=j(s,(t=>(e(t),t)))}if(e.handler&&!o.getInternalMethods().getHasOutput()){o.getInternalMethods().setHasOutput();const n=!!o.getOptions().configuration["populate--"];o.getInternalMethods().postProcess(s,n,!1,!1),s=j(s=C(s,o,h,!1),(t=>{const s=e.handler(t);return d(s)?s.then((()=>t)):t})),t||o.getInternalMethods().getUsageInstance().cacheHelpMessage(),d(s)&&!o.getInternalMethods().hasParseCallback()&&s.catch((t=>{try{o.getInternalMethods().getUsageInstance().fail(null,t)}catch(t){}}))}return t||(n.commands.pop(),n.fullCommands.pop()),s}populatePositionals(t,e,s,n){e._=e._.slice(s.commands.length);const i=t.demanded.slice(0),r=t.optional.slice(0),o={};for(this.validation.positionalCount(i.length,e._.length);i.length;){const t=i.shift();this.populatePositional(t,e,o)}for(;r.length;){const t=r.shift();this.populatePositional(t,e,o)}return e._=s.commands.concat(e._.map((t=>""+t))),this.postProcessPositionals(e,o,this.cmdToParseOptions(t.original),n),o}populatePositional(t,e,s){const n=t.cmd[0];t.variadic?s[n]=e._.splice(0).map(String):e._.length&&(s[n]=[String(e._.shift())])}cmdToParseOptions(t){const e={array:[],default:{},alias:{},demand:{}},s=o(t);return s.demanded.forEach((t=>{const[s,...n]=t.cmd;t.variadic&&(e.array.push(s),e.default[s]=[]),e.alias[s]=n,e.demand[s]=!0})),s.optional.forEach((t=>{const[s,...n]=t.cmd;t.variadic&&(e.array.push(s),e.default[s]=[]),e.alias[s]=n})),e}postProcessPositionals(t,e,s,n){const i=Object.assign({},n.getOptions());i.default=Object.assign(s.default,i.default);for(const t of Object.keys(s.alias))i.alias[t]=(i.alias[t]||[]).concat(s.alias[t]);i.array=i.array.concat(s.array),i.config={};const r=[];if(Object.keys(e).forEach((t=>{e[t].map((e=>{i.configuration["unknown-options-as-args"]&&(i.key[t]=!0),r.push(`--${t}`),r.push(e)}))})),!r.length)return;const o=Object.assign({},i.configuration,{"populate--":!1}),a=this.shim.Parser.detailed(r,Object.assign({},i,{configuration:o}));if(a.error)n.getInternalMethods().getUsageInstance().fail(a.error.message,a.error);else{const s=Object.keys(e);Object.keys(e).forEach((t=>{s.push(...a.aliases[t])})),Object.keys(a.argv).forEach((n=>{-1!==s.indexOf(n)&&(e[n]||(e[n]=a.argv[n]),t[n]=a.argv[n])}))}}runDefaultBuilderOn(t){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(t)){const e=x.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");t.getInternalMethods().getUsageInstance().usage(e,this.defaultCommand.description)}const e=this.defaultCommand.builder;if(k(e))return e(t,!0);M(e)||Object.keys(e).forEach((s=>{t.option(s,e[s])}))}moduleName(t){const e=function(t){if("undefined"==typeof require)return null;for(let e,s=0,n=Object.keys(require.cache);s<n.length;s++)if(e=require.cache[n[s]],e.exports===t)return e;return null}(t);if(!e)throw new Error(`No command name given for module: ${this.shim.inspect(t)}`);return this.commandFromFilename(e.filename)}commandFromFilename(t){return this.shim.path.basename(t,this.shim.path.extname(t))}extractDesc({describe:t,description:e,desc:s}){for(const n of[t,e,s]){if("string"==typeof n||!1===n)return n;u(n,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){const t=this.frozens.pop();u(t,void 0,this.shim),({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=t)}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function M(t){return"object"==typeof t&&!!t.builder&&"function"==typeof t.handler}function k(t){return"function"==typeof t}function E(t){"undefined"!=typeof process&&[process.stdout,process.stderr].forEach((e=>{const s=e;s._handle&&s.isTTY&&"function"==typeof s._handle.setBlocking&&s._handle.setBlocking(t)}))}function S(t){return"boolean"==typeof t}function $(t,s){const n=s.y18n.__,i={},r=[];i.failFn=function(t){r.push(t)};let o=null,a=!0;i.showHelpOnFail=function(t=!0,e){const[s,n]="string"==typeof t?[!0,t]:[t,e];return o=n,a=s,i};let h=!1;i.fail=function(s,n){const l=t.getInternalMethods().getLoggerInstance();if(!r.length){if(t.getExitProcess()&&E(!0),h||(h=!0,a&&(t.showHelp("error"),l.error()),(s||n)&&l.error(s||n),o&&((s||n)&&l.error(""),l.error(o))),n=n||new e(s),t.getExitProcess())return t.exit(1);if(t.getInternalMethods().hasParseCallback())return t.exit(1,n);throw n}for(let t=r.length-1;t>=0;--t){const e=r[t];if(S(e)){if(n)throw n;if(s)throw Error(s)}else e(s,n,i)}};let l=[],c=!1;i.usage=(t,e)=>null===t?(c=!0,l=[],i):(c=!1,l.push([t,e||""]),i),i.getUsage=()=>l,i.getUsageDisabled=()=>c,i.getPositionalGroupName=()=>n("Positionals:");let d=[];i.example=(t,e)=>{d.push([t,e||""])};let u=[];i.command=function(t,e,s,n,i=!1){s&&(u=u.map((t=>(t[2]=!1,t)))),u.push([t,e||"",s,n,i])},i.getCommands=()=>u;let p={};i.describe=function(t,e){Array.isArray(t)?t.forEach((t=>{i.describe(t,e)})):"object"==typeof t?Object.keys(t).forEach((e=>{i.describe(e,t[e])})):p[t]=e},i.getDescriptions=()=>p;let g=[];i.epilog=t=>{g.push(t)};let f,y=!1;function b(){return y||(f=function(){const t=80;return s.process.stdColumns?Math.min(t,s.process.stdColumns):t}(),y=!0),f}i.wrap=t=>{y=!0,f=t};const O="__yargsString__:";function v(t,e,n){let i=0;return Array.isArray(t)||(t=Object.values(t).map((t=>[t]))),t.forEach((t=>{i=Math.max(s.stringWidth(n?`${n} ${I(t[0])}`:I(t[0]))+A(t[0]),i)})),e&&(i=Math.min(i,parseInt((.5*e).toString(),10))),i}let w;function C(e){return t.getOptions().hiddenOptions.indexOf(e)<0||t.parsed.argv[t.getOptions().showHiddenOpt]}function j(t,e){let s=`[${n("default:")} `;if(void 0===t&&!e)return null;if(e)s+=e;else switch(typeof t){case"string":s+=`"${t}"`;break;case"object":s+=JSON.stringify(t);break;default:s+=t}return`${s}]`}i.deferY18nLookup=t=>O+t,i.help=function(){if(w)return w;!function(){const e=t.getDemandedOptions(),s=t.getOptions();(Object.keys(s.alias)||[]).forEach((n=>{s.alias[n].forEach((r=>{p[r]&&i.describe(n,p[r]),r in e&&t.demandOption(n,e[r]),~s.boolean.indexOf(r)&&t.boolean(n),~s.count.indexOf(r)&&t.count(n),~s.string.indexOf(r)&&t.string(n),~s.normalize.indexOf(r)&&t.normalize(n),~s.array.indexOf(r)&&t.array(n),~s.number.indexOf(r)&&t.number(n)}))}))}();const e=t.customScriptName?t.$0:s.path.basename(t.$0),r=t.getDemandedOptions(),o=t.getDemandedCommands(),a=t.getDeprecatedOptions(),h=t.getGroups(),m=t.getOptions();let f=[];f=f.concat(Object.keys(p)),f=f.concat(Object.keys(r)),f=f.concat(Object.keys(o)),f=f.concat(Object.keys(m.default)),f=f.filter(C),f=Object.keys(f.reduce(((t,e)=>("_"!==e&&(t[e]=!0),t)),{}));const y=b(),x=s.cliui({width:y,wrap:!!y});if(!c)if(l.length)l.forEach((t=>{x.div(`${t[0].replace(/\$0/g,e)}`),t[1]&&x.div({text:`${t[1]}`,padding:[1,0,0,0]})})),x.div();else if(u.length){let t=null;t=o._?`${e} <${n("command")}>\n`:`${e} [${n("command")}]\n`,x.div(`${t}`)}if(u.length>1||1===u.length&&!u[0][2]){x.div(n("Commands:"));const s=t.getInternalMethods().getContext(),i=s.commands.length?`${s.commands.join(" ")} `:"";!0===t.getInternalMethods().getParserConfiguration()["sort-commands"]&&(u=u.sort(((t,e)=>t[0].localeCompare(e[0])))),u.forEach((t=>{const s=`${e} ${i}${t[0].replace(/^\$0 ?/,"")}`;x.span({text:s,padding:[0,2,0,2],width:v(u,y,`${e}${i}`)+4},{text:t[1]});const r=[];t[2]&&r.push(`[${n("default")}]`),t[3]&&t[3].length&&r.push(`[${n("aliases:")} ${t[3].join(", ")}]`),t[4]&&("string"==typeof t[4]?r.push(`[${n("deprecated: %s",t[4])}]`):r.push(`[${n("deprecated")}]`)),r.length?x.div({text:r.join(" "),padding:[0,0,0,2],align:"right"}):x.div()})),x.div()}const _=(Object.keys(m.alias)||[]).concat(Object.keys(t.parsed.newAliases)||[]);f=f.filter((e=>!t.parsed.newAliases[e]&&_.every((t=>-1===(m.alias[t]||[]).indexOf(e)))));const M=n("Options:");h[M]||(h[M]=[]),function(t,e,s,n){let i=[],r=null;Object.keys(s).forEach((t=>{i=i.concat(s[t])})),t.forEach((t=>{r=[t].concat(e[t]),r.some((t=>-1!==i.indexOf(t)))||s[n].push(t)}))}(f,m.alias,h,M);const k=t=>/^--/.test(I(t)),E=Object.keys(h).filter((t=>h[t].length>0)).map((t=>({groupName:t,normalizedKeys:h[t].filter(C).map((t=>{if(~_.indexOf(t))return t;for(let e,s=0;void 0!==(e=_[s]);s++)if(~(m.alias[e]||[]).indexOf(t))return e;return t}))}))).filter((({normalizedKeys:t})=>t.length>0)).map((({groupName:t,normalizedKeys:e})=>{const s=e.reduce(((e,s)=>(e[s]=[s].concat(m.alias[s]||[]).map((e=>t===i.getPositionalGroupName()?e:(/^[0-9]$/.test(e)?~m.boolean.indexOf(s)?"-":"--":e.length>1?"--":"-")+e)).sort(((t,e)=>k(t)===k(e)?0:k(t)?1:-1)).join(", "),e)),{});return{groupName:t,normalizedKeys:e,switches:s}}));if(E.filter((({groupName:t})=>t!==i.getPositionalGroupName())).some((({normalizedKeys:t,switches:e})=>!t.every((t=>k(e[t])))))&&E.filter((({groupName:t})=>t!==i.getPositionalGroupName())).forEach((({normalizedKeys:t,switches:e})=>{t.forEach((t=>{var s,n;k(e[t])&&(e[t]=(s=e[t],n="-x, ".length,P(s)?{text:s.text,indentation:s.indentation+n}:{text:s,indentation:n}))}))})),E.forEach((({groupName:t,normalizedKeys:e,switches:s})=>{x.div(t),e.forEach((t=>{const e=s[t];let o=p[t]||"",h=null;~o.lastIndexOf(O)&&(o=n(o.substring(O.length))),~m.boolean.indexOf(t)&&(h=`[${n("boolean")}]`),~m.count.indexOf(t)&&(h=`[${n("count")}]`),~m.string.indexOf(t)&&(h=`[${n("string")}]`),~m.normalize.indexOf(t)&&(h=`[${n("string")}]`),~m.array.indexOf(t)&&(h=`[${n("array")}]`),~m.number.indexOf(t)&&(h=`[${n("number")}]`);const l=[t in a?(c=a[t],"string"==typeof c?`[${n("deprecated: %s",c)}]`:`[${n("deprecated")}]`):null,h,t in r?`[${n("required")}]`:null,m.choices&&m.choices[t]?`[${n("choices:")} ${i.stringifiedValues(m.choices[t])}]`:null,j(m.default[t],m.defaultDescription[t])].filter(Boolean).join(" ");var c;x.span({text:I(e),padding:[0,2,0,2+A(e)],width:v(s,y)+4},o),l?x.div({text:l,padding:[0,0,0,2],align:"right"}):x.div()})),x.div()})),d.length&&(x.div(n("Examples:")),d.forEach((t=>{t[0]=t[0].replace(/\$0/g,e)})),d.forEach((t=>{""===t[1]?x.div({text:t[0],padding:[0,2,0,2]}):x.div({text:t[0],padding:[0,2,0,2],width:v(d,y)+4},{text:t[1]})})),x.div()),g.length>0){const t=g.map((t=>t.replace(/\$0/g,e))).join("\n");x.div(`${t}\n`)}return x.toString().replace(/\s*$/,"")},i.cacheHelpMessage=function(){w=this.help()},i.clearCachedHelpMessage=function(){w=void 0},i.hasCachedHelpMessage=function(){return!!w},i.showHelp=e=>{const s=t.getInternalMethods().getLoggerInstance();e||(e="error");("function"==typeof e?e:s[e])(i.help())},i.functionDescription=t=>["(",t.name?s.Parser.decamelize(t.name,"-"):n("generated-value"),")"].join(""),i.stringifiedValues=function(t,e){let s="";const n=e||", ",i=[].concat(t);return t&&i.length?(i.forEach((t=>{s.length&&(s+=n),s+=JSON.stringify(t)})),s):s};let x=null;i.version=t=>{x=t},i.showVersion=e=>{const s=t.getInternalMethods().getLoggerInstance();e||(e="error");("function"==typeof e?e:s[e])(x)},i.reset=function(t){return o=null,h=!1,l=[],c=!1,g=[],d=[],u=[],p=m(p,(e=>!t[e])),i};const _=[];return i.freeze=function(){_.push({failMessage:o,failureOutput:h,usages:l,usageDisabled:c,epilogs:g,examples:d,commands:u,descriptions:p})},i.unfreeze=function(){const t=_.pop();t&&({failMessage:o,failureOutput:h,usages:l,usageDisabled:c,epilogs:g,examples:d,commands:u,descriptions:p}=t)},i}function P(t){return"object"==typeof t}function A(t){return P(t)?t.indentation:0}function I(t){return P(t)?t.text:t}class N{constructor(t,e,s,n){var i,r,o;this.yargs=t,this.usage=e,this.command=s,this.shim=n,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.zshShell=null!==(o=(null===(i=this.shim.getEnv("SHELL"))||void 0===i?void 0:i.includes("zsh"))||(null===(r=this.shim.getEnv("ZSH_NAME"))||void 0===r?void 0:r.includes("zsh")))&&void 0!==o&&o}defaultCompletion(t,e,s,n){const i=this.command.getCommandHandlers();for(let e=0,s=t.length;e<s;++e)if(i[t[e]]&&i[t[e]].builder){const s=i[t[e]].builder;if(k(s)){const t=this.yargs.getInternalMethods().reset();return s(t,!0),t.argv}}const r=[];this.commandCompletions(r,t,s),this.optionCompletions(r,t,e,s),n(null,r)}commandCompletions(t,e,s){const n=this.yargs.getInternalMethods().getContext().commands;s.match(/^-/)||n[n.length-1]===s||this.usage.getCommands().forEach((s=>{const n=o(s[0]).cmd;if(-1===e.indexOf(n))if(this.zshShell){const e=s[1]||"";t.push(n.replace(/:/g,"\\:")+":"+e)}else t.push(n)}))}optionCompletions(t,e,s,n){if(n.match(/^-/)||""===n&&0===t.length){const i=this.yargs.getOptions(),r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(i.key).forEach((o=>{const a=!!i.configuration["boolean-negation"]&&i.boolean.includes(o);r.includes(o)||this.argsContainKey(e,s,o,a)||(this.completeOptionKey(o,t,n),a&&i.default[o]&&this.completeOptionKey(`no-${o}`,t,n))}))}}argsContainKey(t,e,s,n){if(-1!==t.indexOf(`--${s}`))return!0;if(n&&-1!==t.indexOf(`--no-${s}`))return!0;if(this.aliases)for(const t of this.aliases[s])if(void 0!==e[t])return!0;return!1}completeOptionKey(t,e,s){const n=this.usage.getDescriptions(),i=!/^--/.test(s)&&(t=>/^[^0-9]$/.test(t))(t)?"-":"--";if(this.zshShell){const s=n[t]||"";e.push(i+`${t.replace(/:/g,"\\:")}:${s.replace("__yargsString__:","")}`)}else e.push(i+t)}customCompletion(t,e,s,n){if(u(this.customCompletionFunction,null,this.shim),this.customCompletionFunction.length<3){const t=this.customCompletionFunction(s,e);return d(t)?t.then((t=>{this.shim.process.nextTick((()=>{n(null,t)}))})).catch((t=>{this.shim.process.nextTick((()=>{n(t,void 0)}))})):n(null,t)}return function(t){return t.length>3}(this.customCompletionFunction)?this.customCompletionFunction(s,e,((i=n)=>this.defaultCompletion(t,e,s,i)),(t=>{n(null,t)})):this.customCompletionFunction(s,e,(t=>{n(null,t)}))}getCompletion(t,e){const s=t.length?t[t.length-1]:"",n=this.yargs.parse(t,!0),i=this.customCompletionFunction?n=>this.customCompletion(t,n,s,e):n=>this.defaultCompletion(t,n,s,e);return d(n)?n.then(i):i(n)}generateCompletionScript(t,e){let s=this.zshShell?'#compdef {{app_name}}\n###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc\n# or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local reply\n local si=$IFS\n IFS=$\'\n\' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "${words[@]}"))\n IFS=$si\n _describe \'values\' reply\n}\ncompdef _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n':'###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc\n# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local cur_word args type_list\n\n cur_word="${COMP_WORDS[COMP_CWORD]}"\n args=("${COMP_WORDS[@]}")\n\n # ask yargs to generate completions.\n type_list=$({{app_path}} --get-yargs-completions "${args[@]}")\n\n COMPREPLY=( $(compgen -W "${type_list}" -- ${cur_word}) )\n\n # if no match was found, fall back to filename completion\n if [ ${#COMPREPLY[@]} -eq 0 ]; then\n COMPREPLY=()\n fi\n\n return 0\n}\ncomplete -o default -F _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n';const n=this.shim.path.basename(t);return t.match(/\.js$/)&&(t=`./${t}`),s=s.replace(/{{app_name}}/g,n),s=s.replace(/{{completion_command}}/g,e),s.replace(/{{app_path}}/g,t)}registerFunction(t){this.customCompletionFunction=t}setParsed(t){this.aliases=t.aliases}}function D(t,e){if(0===t.length)return e.length;if(0===e.length)return t.length;const s=[];let n,i;for(n=0;n<=e.length;n++)s[n]=[n];for(i=0;i<=t.length;i++)s[0][i]=i;for(n=1;n<=e.length;n++)for(i=1;i<=t.length;i++)e.charAt(n-1)===t.charAt(i-1)?s[n][i]=s[n-1][i-1]:s[n][i]=Math.min(s[n-1][i-1]+1,Math.min(s[n][i-1]+1,s[n-1][i]+1));return s[e.length][t.length]}const z=["$0","--","_"];var q,H,F,U,W,L,V,R,T,G,B,K,Y,J,Z,X,Q,tt,et,st,nt,it,rt,ot,at,ht,lt,ct,dt,ut,pt,gt;const mt=Symbol("copyDoubleDash"),ft=Symbol("copyDoubleDash"),yt=Symbol("deleteFromParserHintObject"),bt=Symbol("freeze"),Ot=Symbol("getDollarZero"),vt=Symbol("getParserConfiguration"),wt=Symbol("guessLocale"),Ct=Symbol("guessVersion"),jt=Symbol("parsePositionalNumbers"),xt=Symbol("pkgUp"),_t=Symbol("populateParserHintArray"),Mt=Symbol("populateParserHintSingleValueDictionary"),kt=Symbol("populateParserHintArrayDictionary"),Et=Symbol("populateParserHintDictionary"),St=Symbol("sanitizeKey"),$t=Symbol("setKey"),Pt=Symbol("unfreeze"),At=Symbol("validateAsync"),It=Symbol("getCommandInstance"),Nt=Symbol("getContext"),Dt=Symbol("getHasOutput"),zt=Symbol("getLoggerInstance"),qt=Symbol("getParseContext"),Ht=Symbol("getUsageInstance"),Ft=Symbol("getValidationInstance"),Ut=Symbol("hasParseCallback"),Wt=Symbol("postProcess"),Lt=Symbol("rebase"),Vt=Symbol("reset"),Rt=Symbol("runYargsParserAndExecuteCommands"),Tt=Symbol("runValidation"),Gt=Symbol("setHasOutput");class Bt{constructor(t=[],e,s,n){this.customScriptName=!1,this.parsed=!1,q.set(this,void 0),H.set(this,void 0),F.set(this,{commands:[],fullCommands:[]}),U.set(this,null),W.set(this,null),L.set(this,"show-hidden"),V.set(this,null),R.set(this,!0),T.set(this,!0),G.set(this,[]),B.set(this,void 0),K.set(this,{}),Y.set(this,!1),J.set(this,null),Z.set(this,void 0),X.set(this,""),Q.set(this,void 0),tt.set(this,void 0),et.set(this,{}),st.set(this,null),nt.set(this,null),it.set(this,{}),rt.set(this,{}),ot.set(this,void 0),at.set(this,!1),ht.set(this,void 0),lt.set(this,!1),ct.set(this,!1),dt.set(this,!1),ut.set(this,void 0),pt.set(this,null),gt.set(this,void 0),v(this,ht,n),v(this,ot,t),v(this,H,e),v(this,tt,s),v(this,B,new w(this)),this.$0=this[Ot](),this[Vt](),v(this,q,O(this,q)),v(this,ut,O(this,ut)),v(this,gt,O(this,gt)),v(this,Q,O(this,Q)),O(this,Q).showHiddenOpt=O(this,L),v(this,Z,this[ft]())}addHelpOpt(t,e){return h("[string|boolean] [string]",[t,e],arguments.length),O(this,J)&&(this[yt](O(this,J)),v(this,J,null)),!1===t&&void 0===e||(v(this,J,"string"==typeof t?t:"help"),this.boolean(O(this,J)),this.describe(O(this,J),e||O(this,ut).deferY18nLookup("Show help"))),this}help(t,e){return this.addHelpOpt(t,e)}addShowHiddenOpt(t,e){if(h("[string|boolean] [string]",[t,e],arguments.length),!1===t&&void 0===e)return this;const s="string"==typeof t?t:O(this,L);return this.boolean(s),this.describe(s,e||O(this,ut).deferY18nLookup("Show hidden options")),O(this,Q).showHiddenOpt=s,this}showHidden(t,e){return this.addShowHiddenOpt(t,e)}alias(t,e){return h("<object|string|array> [string|array]",[t,e],arguments.length),this[kt](this.alias.bind(this),"alias",t,e),this}array(t){return h("<array|string>",[t],arguments.length),this[_t]("array",t),this}boolean(t){return h("<array|string>",[t],arguments.length),this[_t]("boolean",t),this}check(t,e){return h("<function> [boolean]",[t,e],arguments.length),this.middleware(((e,s)=>j((()=>t(e)),(s=>(s?("string"==typeof s||s instanceof Error)&&O(this,ut).fail(s.toString(),s):O(this,ut).fail(O(this,ht).y18n.__("Argument check failed: %s",t.toString())),e)),(t=>(O(this,ut).fail(t.message?t.message:t.toString(),t),e)))),!1,e),this}choices(t,e){return h("<object|string|array> [string|array]",[t,e],arguments.length),this[kt](this.choices.bind(this),"choices",t,e),this}coerce(t,s){if(h("<object|string|array> [function]",[t,s],arguments.length),Array.isArray(t)){if(!s)throw new e("coerce callback must be provided");for(const e of t)this.coerce(e,s);return this}if("object"==typeof t){for(const e of Object.keys(t))this.coerce(e,t[e]);return this}if(!s)throw new e("coerce callback must be provided");return O(this,Q).key[t]=!0,O(this,B).addCoerceMiddleware(((n,i)=>{let r;return j((()=>(r=i.getAliases(),s(n[t]))),(e=>{if(n[t]=e,r[t])for(const s of r[t])n[s]=e;return n}),(t=>{throw new e(t.message)}))}),t),this}conflicts(t,e){return h("<string|object> [string|array]",[t,e],arguments.length),O(this,gt).conflicts(t,e),this}config(t="config",e,s){return h("[object|string] [string|function] [function]",[t,e,s],arguments.length),"object"!=typeof t||Array.isArray(t)?("function"==typeof e&&(s=e,e=void 0),this.describe(t,e||O(this,ut).deferY18nLookup("Path to JSON config file")),(Array.isArray(t)?t:[t]).forEach((t=>{O(this,Q).config[t]=s||!0})),this):(t=i(t,O(this,H),this[vt]()["deep-merge-config"]||!1,O(this,ht)),O(this,Q).configObjects=(O(this,Q).configObjects||[]).concat(t),this)}completion(t,e,s){return h("[string] [string|boolean|function] [function]",[t,e,s],arguments.length),"function"==typeof e&&(s=e,e=void 0),v(this,W,t||O(this,W)||"completion"),e||!1===e||(e="generate completion script"),this.command(O(this,W),e),s&&O(this,U).registerFunction(s),this}command(t,e,s,n,i,r){return h("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[t,e,s,n,i,r],arguments.length),O(this,q).addHandler(t,e,s,n,i,r),this}commands(t,e,s,n,i,r){return this.command(t,e,s,n,i,r)}commandDir(t,e){h("<string> [object]",[t,e],arguments.length);const s=O(this,tt)||O(this,ht).require;return O(this,q).addDirectory(t,s,O(this,ht).getCallerFile(),e),this}count(t){return h("<array|string>",[t],arguments.length),this[_t]("count",t),this}default(t,e,s){return h("<object|string|array> [*] [string]",[t,e,s],arguments.length),s&&(p(t,O(this,ht)),O(this,Q).defaultDescription[t]=s),"function"==typeof e&&(p(t,O(this,ht)),O(this,Q).defaultDescription[t]||(O(this,Q).defaultDescription[t]=O(this,ut).functionDescription(e)),e=e.call()),this[Mt](this.default.bind(this),"default",t,e),this}defaults(t,e,s){return this.default(t,e,s)}demandCommand(t=1,e,s,n){return h("[number] [number|string] [string|null|undefined] [string|null|undefined]",[t,e,s,n],arguments.length),"number"!=typeof e&&(s=e,e=1/0),this.global("_",!1),O(this,Q).demandedCommands._={min:t,max:e,minMsg:s,maxMsg:n},this}demand(t,e,s){return Array.isArray(e)?(e.forEach((t=>{u(s,!0,O(this,ht)),this.demandOption(t,s)})),e=1/0):"number"!=typeof e&&(s=e,e=1/0),"number"==typeof t?(u(s,!0,O(this,ht)),this.demandCommand(t,e,s,s)):Array.isArray(t)?t.forEach((t=>{u(s,!0,O(this,ht)),this.demandOption(t,s)})):"string"==typeof s?this.demandOption(t,s):!0!==s&&void 0!==s||this.demandOption(t),this}demandOption(t,e){return h("<object|string|array> [string]",[t,e],arguments.length),this[Mt](this.demandOption.bind(this),"demandedOptions",t,e),this}deprecateOption(t,e){return h("<string> [string|boolean]",[t,e],arguments.length),O(this,Q).deprecatedOptions[t]=e,this}describe(t,e){return h("<object|string|array> [string]",[t,e],arguments.length),this[$t](t,!0),O(this,ut).describe(t,e),this}detectLocale(t){return h("<boolean>",[t],arguments.length),v(this,R,t),this}env(t){return h("[string|boolean]",[t],arguments.length),!1===t?delete O(this,Q).envPrefix:O(this,Q).envPrefix=t||"",this}epilogue(t){return h("<string>",[t],arguments.length),O(this,ut).epilog(t),this}epilog(t){return this.epilogue(t)}example(t,e){return h("<string|array> [string]",[t,e],arguments.length),Array.isArray(t)?t.forEach((t=>this.example(...t))):O(this,ut).example(t,e),this}exit(t,e){v(this,Y,!0),v(this,V,e),O(this,T)&&O(this,ht).process.exit(t)}exitProcess(t=!0){return h("[boolean]",[t],arguments.length),v(this,T,t),this}fail(t){if(h("<function|boolean>",[t],arguments.length),"boolean"==typeof t&&!1!==t)throw new e("Invalid first argument. Expected function or boolean 'false'");return O(this,ut).failFn(t),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(t,e){return h("<array> [function]",[t,e],arguments.length),e?O(this,U).getCompletion(t,e):new Promise(((e,s)=>{O(this,U).getCompletion(t,((t,n)=>{t?s(t):e(n)}))}))}getDemandedOptions(){return h([],0),O(this,Q).demandedOptions}getDemandedCommands(){return h([],0),O(this,Q).demandedCommands}getDeprecatedOptions(){return h([],0),O(this,Q).deprecatedOptions}getDetectLocale(){return O(this,R)}getExitProcess(){return O(this,T)}getGroups(){return Object.assign({},O(this,K),O(this,rt))}getHelp(){if(v(this,Y,!0),!O(this,ut).hasCachedHelpMessage()){if(!this.parsed){const t=this[Rt](O(this,ot),void 0,void 0,0,!0);if(d(t))return t.then((()=>O(this,ut).help()))}const t=O(this,q).runDefaultBuilderOn(this);if(d(t))return t.then((()=>O(this,ut).help()))}return Promise.resolve(O(this,ut).help())}getOptions(){return O(this,Q)}getStrict(){return O(this,lt)}getStrictCommands(){return O(this,ct)}getStrictOptions(){return O(this,dt)}global(t,e){return h("<string|array> [boolean]",[t,e],arguments.length),t=[].concat(t),!1!==e?O(this,Q).local=O(this,Q).local.filter((e=>-1===t.indexOf(e))):t.forEach((t=>{-1===O(this,Q).local.indexOf(t)&&O(this,Q).local.push(t)})),this}group(t,e){h("<string|array> <string>",[t,e],arguments.length);const s=O(this,rt)[e]||O(this,K)[e];O(this,rt)[e]&&delete O(this,rt)[e];const n={};return O(this,K)[e]=(s||[]).concat(t).filter((t=>!n[t]&&(n[t]=!0))),this}hide(t){return h("<string>",[t],arguments.length),O(this,Q).hiddenOptions.push(t),this}implies(t,e){return h("<string|object> [number|string|array]",[t,e],arguments.length),O(this,gt).implies(t,e),this}locale(t){return h("[string]",[t],arguments.length),t?(v(this,R,!1),O(this,ht).y18n.setLocale(t),this):(this[wt](),O(this,ht).y18n.getLocale())}middleware(t,e,s){return O(this,B).addMiddleware(t,!!e,s)}nargs(t,e){return h("<string|object|array> [number]",[t,e],arguments.length),this[Mt](this.nargs.bind(this),"narg",t,e),this}normalize(t){return h("<array|string>",[t],arguments.length),this[_t]("normalize",t),this}number(t){return h("<array|string>",[t],arguments.length),this[_t]("number",t),this}option(t,e){if(h("<string|object> [object]",[t,e],arguments.length),"object"==typeof t)Object.keys(t).forEach((e=>{this.options(e,t[e])}));else{"object"!=typeof e&&(e={}),O(this,Q).key[t]=!0,e.alias&&this.alias(t,e.alias);const s=e.deprecate||e.deprecated;s&&this.deprecateOption(t,s);const n=e.demand||e.required||e.require;n&&this.demand(t,n),e.demandOption&&this.demandOption(t,"string"==typeof e.demandOption?e.demandOption:void 0),e.conflicts&&this.conflicts(t,e.conflicts),"default"in e&&this.default(t,e.default),void 0!==e.implies&&this.implies(t,e.implies),void 0!==e.nargs&&this.nargs(t,e.nargs),e.config&&this.config(t,e.configParser),e.normalize&&this.normalize(t),e.choices&&this.choices(t,e.choices),e.coerce&&this.coerce(t,e.coerce),e.group&&this.group(t,e.group),(e.boolean||"boolean"===e.type)&&(this.boolean(t),e.alias&&this.boolean(e.alias)),(e.array||"array"===e.type)&&(this.array(t),e.alias&&this.array(e.alias)),(e.number||"number"===e.type)&&(this.number(t),e.alias&&this.number(e.alias)),(e.string||"string"===e.type)&&(this.string(t),e.alias&&this.string(e.alias)),(e.count||"count"===e.type)&&this.count(t),"boolean"==typeof e.global&&this.global(t,e.global),e.defaultDescription&&(O(this,Q).defaultDescription[t]=e.defaultDescription),e.skipValidation&&this.skipValidation(t);const i=e.describe||e.description||e.desc;this.describe(t,i),e.hidden&&this.hide(t),e.requiresArg&&this.requiresArg(t)}return this}options(t,e){return this.option(t,e)}parse(t,e,s){h("[string|array] [function|boolean|object] [function]",[t,e,s],arguments.length),this[bt](),void 0===t&&(t=O(this,ot)),"object"==typeof e&&(v(this,nt,e),e=s),"function"==typeof e&&(v(this,st,e),e=!1),e||v(this,ot,t),O(this,st)&&v(this,T,!1);const n=this[Rt](t,!!e),i=this.parsed;return O(this,U).setParsed(this.parsed),d(n)?n.then((t=>(O(this,st)&&O(this,st).call(this,O(this,V),t,O(this,X)),t))).catch((t=>{throw O(this,st)&&O(this,st)(t,this.parsed.argv,O(this,X)),t})).finally((()=>{this[Pt](),this.parsed=i})):(O(this,st)&&O(this,st).call(this,O(this,V),n,O(this,X)),this[Pt](),this.parsed=i,n)}parseAsync(t,e,s){const n=this.parse(t,e,s);return d(n)?n:Promise.resolve(n)}parseSync(t,s,n){const i=this.parse(t,s,n);if(d(i))throw new e(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return i}parserConfiguration(t){return h("<object>",[t],arguments.length),v(this,et,t),this}pkgConf(t,e){h("<string> [string]",[t,e],arguments.length);let s=null;const n=this[xt](e||O(this,H));return n[t]&&"object"==typeof n[t]&&(s=i(n[t],e||O(this,H),this[vt]()["deep-merge-config"]||!1,O(this,ht)),O(this,Q).configObjects=(O(this,Q).configObjects||[]).concat(s)),this}positional(t,e){h("<string> <object>",[t,e],arguments.length);const s=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];e=m(e,((t,e)=>{let n=-1!==s.indexOf(t);return"type"===t&&-1===["string","number","boolean"].indexOf(e)&&(n=!1),n}));const n=O(this,F).fullCommands[O(this,F).fullCommands.length-1],i=n?O(this,q).cmdToParseOptions(n):{array:[],alias:{},default:{},demand:{}};return g(i).forEach((s=>{const n=i[s];Array.isArray(n)?-1!==n.indexOf(t)&&(e[s]=!0):n[t]&&!(s in e)&&(e[s]=n[t])})),this.group(t,O(this,ut).getPositionalGroupName()),this.option(t,e)}recommendCommands(t=!0){return h("[boolean]",[t],arguments.length),v(this,at,t),this}required(t,e,s){return this.demand(t,e,s)}require(t,e,s){return this.demand(t,e,s)}requiresArg(t){return h("<array|string|object> [number]",[t],arguments.length),"string"==typeof t&&O(this,Q).narg[t]||this[Mt](this.requiresArg.bind(this),"narg",t,NaN),this}showCompletionScript(t,e){return h("[string] [string]",[t,e],arguments.length),t=t||this.$0,O(this,Z).log(O(this,U).generateCompletionScript(t,e||O(this,W)||"completion")),this}showHelp(t){if(h("[string|function]",[t],arguments.length),v(this,Y,!0),!O(this,ut).hasCachedHelpMessage()){if(!this.parsed){const e=this[Rt](O(this,ot),void 0,void 0,0,!0);if(d(e))return e.then((()=>{O(this,ut).showHelp(t)})),this}const e=O(this,q).runDefaultBuilderOn(this);if(d(e))return e.then((()=>{O(this,ut).showHelp(t)})),this}return O(this,ut).showHelp(t),this}scriptName(t){return this.customScriptName=!0,this.$0=t,this}showHelpOnFail(t,e){return h("[boolean|string] [string]",[t,e],arguments.length),O(this,ut).showHelpOnFail(t,e),this}showVersion(t){return h("[string|function]",[t],arguments.length),O(this,ut).showVersion(t),this}skipValidation(t){return h("<array|string>",[t],arguments.length),this[_t]("skipValidation",t),this}strict(t){return h("[boolean]",[t],arguments.length),v(this,lt,!1!==t),this}strictCommands(t){return h("[boolean]",[t],arguments.length),v(this,ct,!1!==t),this}strictOptions(t){return h("[boolean]",[t],arguments.length),v(this,dt,!1!==t),this}string(t){return h("<array|string>",[t],arguments.length),this[_t]("string",t),this}terminalWidth(){return h([],0),O(this,ht).process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return h("<object>",[t],arguments.length),v(this,R,!1),O(this,ht).y18n.updateLocale(t),this}usage(t,s,n,i){if(h("<string|null|undefined> [string|boolean] [function|object] [function]",[t,s,n,i],arguments.length),void 0!==s){if(u(t,null,O(this,ht)),(t||"").match(/^\$0( |$)/))return this.command(t,s,n,i);throw new e(".usage() description must start with $0 if being used as alias for .command()")}return O(this,ut).usage(t),this}version(t,e,s){const n="version";if(h("[boolean|string] [string] [string]",[t,e,s],arguments.length),O(this,pt)&&(this[yt](O(this,pt)),O(this,ut).version(void 0),v(this,pt,null)),0===arguments.length)s=this[Ct](),t=n;else if(1===arguments.length){if(!1===t)return this;s=t,t=n}else 2===arguments.length&&(s=e,e=void 0);return v(this,pt,"string"==typeof t?t:n),e=e||O(this,ut).deferY18nLookup("Show version number"),O(this,ut).version(s||void 0),this.boolean(O(this,pt)),this.describe(O(this,pt),e),this}wrap(t){return h("<number|null|undefined>",[t],arguments.length),O(this,ut).wrap(t),this}[(q=new WeakMap,H=new WeakMap,F=new WeakMap,U=new WeakMap,W=new WeakMap,L=new WeakMap,V=new WeakMap,R=new WeakMap,T=new WeakMap,G=new WeakMap,B=new WeakMap,K=new WeakMap,Y=new WeakMap,J=new WeakMap,Z=new WeakMap,X=new WeakMap,Q=new WeakMap,tt=new WeakMap,et=new WeakMap,st=new WeakMap,nt=new WeakMap,it=new WeakMap,rt=new WeakMap,ot=new WeakMap,at=new WeakMap,ht=new WeakMap,lt=new WeakMap,ct=new WeakMap,dt=new WeakMap,ut=new WeakMap,pt=new WeakMap,gt=new WeakMap,mt)](t){if(!t._||!t["--"])return t;t._.push.apply(t._,t["--"]);try{delete t["--"]}catch(t){}return t}[ft](){return{log:(...t)=>{this[Ut]()||console.log(...t),v(this,Y,!0),O(this,X).length&&v(this,X,O(this,X)+"\n"),v(this,X,O(this,X)+t.join(" "))},error:(...t)=>{this[Ut]()||console.error(...t),v(this,Y,!0),O(this,X).length&&v(this,X,O(this,X)+"\n"),v(this,X,O(this,X)+t.join(" "))}}}[yt](t){g(O(this,Q)).forEach((e=>{if("configObjects"===e)return;const s=O(this,Q)[e];Array.isArray(s)?~s.indexOf(t)&&s.splice(s.indexOf(t),1):"object"==typeof s&&delete s[t]})),delete O(this,ut).getDescriptions()[t]}[bt](){O(this,G).push({options:O(this,Q),configObjects:O(this,Q).configObjects.slice(0),exitProcess:O(this,T),groups:O(this,K),strict:O(this,lt),strictCommands:O(this,ct),strictOptions:O(this,dt),completionCommand:O(this,W),output:O(this,X),exitError:O(this,V),hasOutput:O(this,Y),parsed:this.parsed,parseFn:O(this,st),parseContext:O(this,nt)}),O(this,ut).freeze(),O(this,gt).freeze(),O(this,q).freeze(),O(this,B).freeze()}[Ot](){let t,e="";return t=/\b(node|iojs|electron)(\.exe)?$/.test(O(this,ht).process.argv()[0])?O(this,ht).process.argv().slice(1,2):O(this,ht).process.argv().slice(0,1),e=t.map((t=>{const e=this[Lt](O(this,H),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&e.length<t.length?e:t})).join(" ").trim(),O(this,ht).getEnv("_")&&O(this,ht).getProcessArgvBin()===O(this,ht).getEnv("_")&&(e=O(this,ht).getEnv("_").replace(`${O(this,ht).path.dirname(O(this,ht).process.execPath())}/`,"")),e}[vt](){return O(this,et)}[wt](){if(!O(this,R))return;const t=O(this,ht).getEnv("LC_ALL")||O(this,ht).getEnv("LC_MESSAGES")||O(this,ht).getEnv("LANG")||O(this,ht).getEnv("LANGUAGE")||"en_US";this.locale(t.replace(/[.:].*/,""))}[Ct](){return this[xt]().version||"unknown"}[jt](t){const e=t["--"]?t["--"]:t._;for(let t,s=0;void 0!==(t=e[s]);s++)O(this,ht).Parser.looksLikeNumber(t)&&Number.isSafeInteger(Math.floor(parseFloat(`${t}`)))&&(e[s]=Number(t));return t}[xt](t){const e=t||"*";if(O(this,it)[e])return O(this,it)[e];let s={};try{let e=t||O(this,ht).mainFilename;!t&&O(this,ht).path.extname(e)&&(e=O(this,ht).path.dirname(e));const n=O(this,ht).findUp(e,((t,e)=>e.includes("package.json")?"package.json":void 0));u(n,void 0,O(this,ht)),s=JSON.parse(O(this,ht).readFileSync(n,"utf8"))}catch(t){}return O(this,it)[e]=s||{},O(this,it)[e]}[_t](t,e){(e=[].concat(e)).forEach((e=>{e=this[St](e),O(this,Q)[t].push(e)}))}[Mt](t,e,s,n){this[Et](t,e,s,n,((t,e,s)=>{O(this,Q)[t][e]=s}))}[kt](t,e,s,n){this[Et](t,e,s,n,((t,e,s)=>{O(this,Q)[t][e]=(O(this,Q)[t][e]||[]).concat(s)}))}[Et](t,e,s,n,i){if(Array.isArray(s))s.forEach((e=>{t(e,n)}));else if((t=>"object"==typeof t)(s))for(const e of g(s))t(e,s[e]);else i(e,this[St](s),n)}[St](t){return"__proto__"===t?"___proto___":t}[$t](t,e){return this[Mt](this[$t].bind(this),"key",t,e),this}[Pt](){var t,e,s,n,i,r,o,a,h,l,c,d;const p=O(this,G).pop();let g;u(p,void 0,O(this,ht)),t=this,e=this,s=this,n=this,i=this,r=this,o=this,a=this,h=this,l=this,c=this,d=this,({options:{set value(e){v(t,Q,e)}}.value,configObjects:g,exitProcess:{set value(t){v(e,T,t)}}.value,groups:{set value(t){v(s,K,t)}}.value,output:{set value(t){v(n,X,t)}}.value,exitError:{set value(t){v(i,V,t)}}.value,hasOutput:{set value(t){v(r,Y,t)}}.value,parsed:this.parsed,strict:{set value(t){v(o,lt,t)}}.value,strictCommands:{set value(t){v(a,ct,t)}}.value,strictOptions:{set value(t){v(h,dt,t)}}.value,completionCommand:{set value(t){v(l,W,t)}}.value,parseFn:{set value(t){v(c,st,t)}}.value,parseContext:{set value(t){v(d,nt,t)}}.value}=p),O(this,Q).configObjects=g,O(this,ut).unfreeze(),O(this,gt).unfreeze(),O(this,q).unfreeze(),O(this,B).unfreeze()}[At](t,e){return j(e,(e=>(t(e),e)))}getInternalMethods(){return{getCommandInstance:this[It].bind(this),getContext:this[Nt].bind(this),getHasOutput:this[Dt].bind(this),getLoggerInstance:this[zt].bind(this),getParseContext:this[qt].bind(this),getParserConfiguration:this[vt].bind(this),getUsageInstance:this[Ht].bind(this),getValidationInstance:this[Ft].bind(this),hasParseCallback:this[Ut].bind(this),postProcess:this[Wt].bind(this),reset:this[Vt].bind(this),runValidation:this[Tt].bind(this),runYargsParserAndExecuteCommands:this[Rt].bind(this),setHasOutput:this[Gt].bind(this)}}[It](){return O(this,q)}[Nt](){return O(this,F)}[Dt](){return O(this,Y)}[zt](){return O(this,Z)}[qt](){return O(this,nt)||{}}[Ht](){return O(this,ut)}[Ft](){return O(this,gt)}[Ut](){return!!O(this,st)}[Wt](t,e,s,n){if(s)return t;if(d(t))return t;e||(t=this[mt](t));return(this[vt]()["parse-positional-numbers"]||void 0===this[vt]()["parse-positional-numbers"])&&(t=this[jt](t)),n&&(t=C(t,this,O(this,B).getMiddleware(),!1)),t}[Vt](t={}){v(this,Q,O(this,Q)||{});const e={};e.local=O(this,Q).local?O(this,Q).local:[],e.configObjects=O(this,Q).configObjects?O(this,Q).configObjects:[];const s={};e.local.forEach((e=>{s[e]=!0,(t[e]||[]).forEach((t=>{s[t]=!0}))})),Object.assign(O(this,rt),Object.keys(O(this,K)).reduce(((t,e)=>{const n=O(this,K)[e].filter((t=>!(t in s)));return n.length>0&&(t[e]=n),t}),{})),v(this,K,{});return["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"].forEach((t=>{e[t]=(O(this,Q)[t]||[]).filter((t=>!s[t]))})),["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"].forEach((t=>{e[t]=m(O(this,Q)[t],(t=>!s[t]))})),e.envPrefix=O(this,Q).envPrefix,v(this,Q,e),v(this,ut,O(this,ut)?O(this,ut).reset(s):$(this,O(this,ht))),v(this,gt,O(this,gt)?O(this,gt).reset(s):function(t,e,s){const n=s.y18n.__,i=s.y18n.__n,r={nonOptionCount:function(s){const n=t.getDemandedCommands(),r=s._.length+(s["--"]?s["--"].length:0)-t.getInternalMethods().getContext().commands.length;n._&&(r<n._.min||r>n._.max)&&(r<n._.min?void 0!==n._.minMsg?e.fail(n._.minMsg?n._.minMsg.replace(/\$0/g,r.toString()).replace(/\$1/,n._.min.toString()):null):e.fail(i("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",r,r.toString(),n._.min.toString())):r>n._.max&&(void 0!==n._.maxMsg?e.fail(n._.maxMsg?n._.maxMsg.replace(/\$0/g,r.toString()).replace(/\$1/,n._.max.toString()):null):e.fail(i("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",r,r.toString(),n._.max.toString()))))},positionalCount:function(t,s){s<t&&e.fail(i("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",s,s+"",t+""))},requiredArguments:function(t,s){let n=null;for(const e of Object.keys(s))Object.prototype.hasOwnProperty.call(t,e)&&void 0!==t[e]||(n=n||{},n[e]=s[e]);if(n){const t=[];for(const e of Object.keys(n)){const s=n[e];s&&t.indexOf(s)<0&&t.push(s)}const s=t.length?`\n${t.join("\n")}`:"";e.fail(i("Missing required argument: %s","Missing required arguments: %s",Object.keys(n).length,Object.keys(n).join(", ")+s))}},unknownArguments:function(s,n,o,a,h=!0){const l=t.getInternalMethods().getCommandInstance().getCommands(),c=[],d=t.getInternalMethods().getContext();Object.keys(s).forEach((e=>{-1!==z.indexOf(e)||Object.prototype.hasOwnProperty.call(o,e)||Object.prototype.hasOwnProperty.call(t.getInternalMethods().getParseContext(),e)||r.isValidAndSomeAliasIsNotNew(e,n)||c.push(e)})),h&&(d.commands.length>0||l.length>0||a)&&s._.slice(d.commands.length).forEach((t=>{-1===l.indexOf(""+t)&&c.push(""+t)})),c.length>0&&e.fail(i("Unknown argument: %s","Unknown arguments: %s",c.length,c.join(", ")))},unknownCommands:function(s){const n=t.getInternalMethods().getCommandInstance().getCommands(),r=[],o=t.getInternalMethods().getContext();return(o.commands.length>0||n.length>0)&&s._.slice(o.commands.length).forEach((t=>{-1===n.indexOf(""+t)&&r.push(""+t)})),r.length>0&&(e.fail(i("Unknown command: %s","Unknown commands: %s",r.length,r.join(", "))),!0)},isValidAndSomeAliasIsNotNew:function(e,s){if(!Object.prototype.hasOwnProperty.call(s,e))return!1;const n=t.parsed.newAliases;return[e,...s[e]].some((t=>!Object.prototype.hasOwnProperty.call(n,t)||!n[e]))},limitedChoices:function(s){const i=t.getOptions(),r={};if(!Object.keys(i.choices).length)return;Object.keys(s).forEach((t=>{-1===z.indexOf(t)&&Object.prototype.hasOwnProperty.call(i.choices,t)&&[].concat(s[t]).forEach((e=>{-1===i.choices[t].indexOf(e)&&void 0!==e&&(r[t]=(r[t]||[]).concat(e))}))}));const o=Object.keys(r);if(!o.length)return;let a=n("Invalid values:");o.forEach((t=>{a+=`\n ${n("Argument: %s, Given: %s, Choices: %s",t,e.stringifiedValues(r[t]),e.stringifiedValues(i.choices[t]))}`})),e.fail(a)}};let o={};function a(t,e){const s=Number(e);return"number"==typeof(e=isNaN(s)?e:s)?t._.length>=e:e.match(/^--no-.+/)?!t[e=e.match(/^--no-(.+)/)[1]]:t[e]}r.implies=function(e,n){h("<string|object> [array|number|string]",[e,n],arguments.length),"object"==typeof e?Object.keys(e).forEach((t=>{r.implies(t,e[t])})):(t.global(e),o[e]||(o[e]=[]),Array.isArray(n)?n.forEach((t=>r.implies(e,t))):(u(n,void 0,s),o[e].push(n)))},r.getImplied=function(){return o},r.implications=function(t){const s=[];if(Object.keys(o).forEach((e=>{const n=e;(o[e]||[]).forEach((e=>{let i=n;const r=e;i=a(t,i),e=a(t,e),i&&!e&&s.push(` ${n} -> ${r}`)}))})),s.length){let t=`${n("Implications failed:")}\n`;s.forEach((e=>{t+=e})),e.fail(t)}};let l={};r.conflicts=function(e,s){h("<string|object> [array|string]",[e,s],arguments.length),"object"==typeof e?Object.keys(e).forEach((t=>{r.conflicts(t,e[t])})):(t.global(e),l[e]||(l[e]=[]),Array.isArray(s)?s.forEach((t=>r.conflicts(e,t))):l[e].push(s))},r.getConflicting=()=>l,r.conflicting=function(t){Object.keys(t).forEach((s=>{l[s]&&l[s].forEach((i=>{i&&void 0!==t[s]&&void 0!==t[i]&&e.fail(n("Arguments %s and %s are mutually exclusive",s,i))}))}))},r.recommendCommands=function(t,s){s=s.sort(((t,e)=>e.length-t.length));let i=null,r=1/0;for(let e,n=0;void 0!==(e=s[n]);n++){const s=D(t,e);s<=3&&s<r&&(r=s,i=e)}i&&e.fail(n("Did you mean %s?",i))},r.reset=function(t){return o=m(o,(e=>!t[e])),l=m(l,(e=>!t[e])),r};const c=[];return r.freeze=function(){c.push({implied:o,conflicting:l})},r.unfreeze=function(){const t=c.pop();u(t,void 0,s),({implied:o,conflicting:l}=t)},r}(this,O(this,ut),O(this,ht))),v(this,q,O(this,q)?O(this,q).reset():function(t,e,s,n){return new _(t,e,s,n)}(O(this,ut),O(this,gt),O(this,B),O(this,ht))),O(this,U)||v(this,U,function(t,e,s,n){return new N(t,e,s,n)}(this,O(this,ut),O(this,q),O(this,ht))),O(this,B).reset(),v(this,W,null),v(this,X,""),v(this,V,null),v(this,Y,!1),this.parsed=!1,this}[Lt](t,e){return O(this,ht).path.relative(t,e)}[Rt](t,s,n,i=0,r=!1){let o=!!n||r;t=t||O(this,ot),O(this,Q).__=O(this,ht).y18n.__,O(this,Q).configuration=this[vt]();const a=!!O(this,Q).configuration["populate--"],h=Object.assign({},O(this,Q).configuration,{"populate--":!0}),l=O(this,ht).Parser.detailed(t,Object.assign({},O(this,Q),{configuration:{"parse-positional-numbers":!1,...h}})),c=Object.assign(l.argv,O(this,nt));let u;const p=l.aliases;let g=!1,m=!1;Object.keys(c).forEach((t=>{t===O(this,J)&&c[t]?g=!0:t===O(this,pt)&&c[t]&&(m=!0)})),c.$0=this.$0,this.parsed=l,0===i&&O(this,ut).clearCachedHelpMessage();try{if(this[wt](),s)return this[Wt](c,a,!!n,!1);if(O(this,J)){~[O(this,J)].concat(p[O(this,J)]||[]).filter((t=>t.length>1)).indexOf(""+c._[c._.length-1])&&(c._.pop(),g=!0)}const h=O(this,q).getCommands(),f=O(this,U).completionKey in c,y=g||f||r;if(c._.length){if(h.length){let t;for(let e,s=i||0;void 0!==c._[s];s++){if(e=String(c._[s]),~h.indexOf(e)&&e!==O(this,W)){const t=O(this,q).runCommand(e,this,l,s+1,r,g||m||r);return this[Wt](t,a,!!n,!1)}if(!t&&e!==O(this,W)){t=e;break}}!O(this,q).hasDefaultCommand()&&O(this,at)&&t&&!y&&O(this,gt).recommendCommands(t,h)}O(this,W)&&~c._.indexOf(O(this,W))&&!f&&(O(this,T)&&E(!0),this.showCompletionScript(),this.exit(0))}if(O(this,q).hasDefaultCommand()&&!y){const t=O(this,q).runCommand(null,this,l,0,r,g||m||r);return this[Wt](t,a,!!n,!1)}if(f){O(this,T)&&E(!0);const s=(t=[].concat(t)).slice(t.indexOf(`--${O(this,U).completionKey}`)+1);return O(this,U).getCompletion(s,((t,s)=>{if(t)throw new e(t.message);(s||[]).forEach((t=>{O(this,Z).log(t)})),this.exit(0)})),this[Wt](c,!a,!!n,!1)}if(O(this,Y)||(g?(O(this,T)&&E(!0),o=!0,this.showHelp("log"),this.exit(0)):m&&(O(this,T)&&E(!0),o=!0,O(this,ut).showVersion("log"),this.exit(0))),!o&&O(this,Q).skipValidation.length>0&&(o=Object.keys(c).some((t=>O(this,Q).skipValidation.indexOf(t)>=0&&!0===c[t]))),!o){if(l.error)throw new e(l.error.message);if(!f){const t=this[Tt](p,{},l.error);n||(u=C(c,this,O(this,B).getMiddleware(),!0)),u=this[At](t,null!=u?u:c),d(u)&&!n&&(u=u.then((()=>C(c,this,O(this,B).getMiddleware(),!1))))}}}catch(t){if(!(t instanceof e))throw t;O(this,ut).fail(t.message,t)}return this[Wt](null!=u?u:c,a,!!n,!0)}[Tt](t,s,n,i){t={...t},s={...s};const r={...this.getDemandedOptions()};return o=>{if(n)throw new e(n.message);O(this,gt).nonOptionCount(o),O(this,gt).requiredArguments(o,r);let a=!1;O(this,ct)&&(a=O(this,gt).unknownCommands(o)),O(this,lt)&&!a?O(this,gt).unknownArguments(o,t,s,!!i):O(this,dt)&&O(this,gt).unknownArguments(o,t,{},!1,!1),O(this,gt).limitedChoices(o),O(this,gt).implications(o),O(this,gt).conflicting(o)}}[Gt](){v(this,Y,!0)}}var Kt,Yt;const{readFileSync:Jt}=require("fs"),{inspect:Zt}=require("util"),{resolve:Xt}=require("path"),Qt=require("y18n"),te=require("yargs-parser");var ee,se={assert:{notStrictEqual:t.notStrictEqual,strictEqual:t.strictEqual},cliui:require("cliui"),findUp:require("escalade/sync"),getEnv:t=>process.env[t],getCallerFile:require("get-caller-file"),getProcessArgvBin:y,inspect:Zt,mainFilename:null!==(Yt=null===(Kt=null===require||void 0===require?void 0:require.main)||void 0===Kt?void 0:Kt.filename)&&void 0!==Yt?Yt:process.cwd(),Parser:te,path:require("path"),process:{argv:()=>process.argv,cwd:process.cwd,execPath:()=>process.execPath,exit:t=>{process.exit(t)},nextTick:process.nextTick,stdColumns:void 0!==process.stdout.columns?process.stdout.columns:null},readFileSync:Jt,require:require,requireDirectory:require("require-directory"),stringWidth:require("string-width"),y18n:Qt({directory:Xt(__dirname,"../locales"),updateFiles:!1})};const ne=(null===(ee=null===process||void 0===process?void 0:process.env)||void 0===ee?void 0:ee.YARGS_MIN_NODE_VERSION)?Number(process.env.YARGS_MIN_NODE_VERSION):12;if(process&&process.version){if(Number(process.version.match(/v([^.]+)/)[1])<ne)throw Error(`yargs supports a minimum Node.js version of ${ne}. Read our version support policy: https://github.com/yargs/yargs#supported-nodejs-versions`)}const ie=require("yargs-parser");var re,oe={applyExtends:i,cjsPlatformShim:se,Yargs:(re=se,(t=[],e=re.process.cwd(),s)=>{const n=new Bt(t,e,s,re);return Object.defineProperty(n,"argv",{get:()=>n.parse(),enumerable:!0}),n.help(),n.version(),n}),argsert:h,isPromise:d,objFilter:m,parseCommand:o,Parser:ie,processArgv:b,YError:e};module.exports=oe;