@rslib/core 0.0.0

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.
@@ -0,0 +1,3805 @@
1
+ /******/ (() => { // webpackBootstrap
2
+ /******/ var __webpack_modules__ = ({
3
+
4
+ /***/ 718:
5
+ /***/ ((module) => {
6
+
7
+ "use strict";
8
+ module.exports = require("node:child_process");
9
+
10
+ /***/ }),
11
+
12
+ /***/ 673:
13
+ /***/ ((module) => {
14
+
15
+ "use strict";
16
+ module.exports = require("node:events");
17
+
18
+ /***/ }),
19
+
20
+ /***/ 561:
21
+ /***/ ((module) => {
22
+
23
+ "use strict";
24
+ module.exports = require("node:fs");
25
+
26
+ /***/ }),
27
+
28
+ /***/ 411:
29
+ /***/ ((module) => {
30
+
31
+ "use strict";
32
+ module.exports = require("node:path");
33
+
34
+ /***/ }),
35
+
36
+ /***/ 742:
37
+ /***/ ((module) => {
38
+
39
+ "use strict";
40
+ module.exports = require("node:process");
41
+
42
+ /***/ }),
43
+
44
+ /***/ 654:
45
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
46
+
47
+ const { InvalidArgumentError } = __nccwpck_require__(829);
48
+
49
+ class Argument {
50
+ /**
51
+ * Initialize a new command argument with the given name and description.
52
+ * The default is that the argument is required, and you can explicitly
53
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
54
+ *
55
+ * @param {string} name
56
+ * @param {string} [description]
57
+ */
58
+
59
+ constructor(name, description) {
60
+ this.description = description || '';
61
+ this.variadic = false;
62
+ this.parseArg = undefined;
63
+ this.defaultValue = undefined;
64
+ this.defaultValueDescription = undefined;
65
+ this.argChoices = undefined;
66
+
67
+ switch (name[0]) {
68
+ case '<': // e.g. <required>
69
+ this.required = true;
70
+ this._name = name.slice(1, -1);
71
+ break;
72
+ case '[': // e.g. [optional]
73
+ this.required = false;
74
+ this._name = name.slice(1, -1);
75
+ break;
76
+ default:
77
+ this.required = true;
78
+ this._name = name;
79
+ break;
80
+ }
81
+
82
+ if (this._name.length > 3 && this._name.slice(-3) === '...') {
83
+ this.variadic = true;
84
+ this._name = this._name.slice(0, -3);
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Return argument name.
90
+ *
91
+ * @return {string}
92
+ */
93
+
94
+ name() {
95
+ return this._name;
96
+ }
97
+
98
+ /**
99
+ * @package
100
+ */
101
+
102
+ _concatValue(value, previous) {
103
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
104
+ return [value];
105
+ }
106
+
107
+ return previous.concat(value);
108
+ }
109
+
110
+ /**
111
+ * Set the default value, and optionally supply the description to be displayed in the help.
112
+ *
113
+ * @param {*} value
114
+ * @param {string} [description]
115
+ * @return {Argument}
116
+ */
117
+
118
+ default(value, description) {
119
+ this.defaultValue = value;
120
+ this.defaultValueDescription = description;
121
+ return this;
122
+ }
123
+
124
+ /**
125
+ * Set the custom handler for processing CLI command arguments into argument values.
126
+ *
127
+ * @param {Function} [fn]
128
+ * @return {Argument}
129
+ */
130
+
131
+ argParser(fn) {
132
+ this.parseArg = fn;
133
+ return this;
134
+ }
135
+
136
+ /**
137
+ * Only allow argument value to be one of choices.
138
+ *
139
+ * @param {string[]} values
140
+ * @return {Argument}
141
+ */
142
+
143
+ choices(values) {
144
+ this.argChoices = values.slice();
145
+ this.parseArg = (arg, previous) => {
146
+ if (!this.argChoices.includes(arg)) {
147
+ throw new InvalidArgumentError(
148
+ `Allowed choices are ${this.argChoices.join(', ')}.`,
149
+ );
150
+ }
151
+ if (this.variadic) {
152
+ return this._concatValue(arg, previous);
153
+ }
154
+ return arg;
155
+ };
156
+ return this;
157
+ }
158
+
159
+ /**
160
+ * Make argument required.
161
+ *
162
+ * @returns {Argument}
163
+ */
164
+ argRequired() {
165
+ this.required = true;
166
+ return this;
167
+ }
168
+
169
+ /**
170
+ * Make argument optional.
171
+ *
172
+ * @returns {Argument}
173
+ */
174
+ argOptional() {
175
+ this.required = false;
176
+ return this;
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Takes an argument and returns its human readable equivalent for help usage.
182
+ *
183
+ * @param {Argument} arg
184
+ * @return {string}
185
+ * @private
186
+ */
187
+
188
+ function humanReadableArgName(arg) {
189
+ const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
190
+
191
+ return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
192
+ }
193
+
194
+ exports.Argument = Argument;
195
+ exports.humanReadableArgName = humanReadableArgName;
196
+
197
+
198
+ /***/ }),
199
+
200
+ /***/ 955:
201
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
202
+
203
+ const EventEmitter = (__nccwpck_require__(673).EventEmitter);
204
+ const childProcess = __nccwpck_require__(718);
205
+ const path = __nccwpck_require__(411);
206
+ const fs = __nccwpck_require__(561);
207
+ const process = __nccwpck_require__(742);
208
+
209
+ const { Argument, humanReadableArgName } = __nccwpck_require__(654);
210
+ const { CommanderError } = __nccwpck_require__(829);
211
+ const { Help } = __nccwpck_require__(567);
212
+ const { Option, DualOptions } = __nccwpck_require__(230);
213
+ const { suggestSimilar } = __nccwpck_require__(241);
214
+
215
+ class Command extends EventEmitter {
216
+ /**
217
+ * Initialize a new `Command`.
218
+ *
219
+ * @param {string} [name]
220
+ */
221
+
222
+ constructor(name) {
223
+ super();
224
+ /** @type {Command[]} */
225
+ this.commands = [];
226
+ /** @type {Option[]} */
227
+ this.options = [];
228
+ this.parent = null;
229
+ this._allowUnknownOption = false;
230
+ this._allowExcessArguments = true;
231
+ /** @type {Argument[]} */
232
+ this.registeredArguments = [];
233
+ this._args = this.registeredArguments; // deprecated old name
234
+ /** @type {string[]} */
235
+ this.args = []; // cli args with options removed
236
+ this.rawArgs = [];
237
+ this.processedArgs = []; // like .args but after custom processing and collecting variadic
238
+ this._scriptPath = null;
239
+ this._name = name || '';
240
+ this._optionValues = {};
241
+ this._optionValueSources = {}; // default, env, cli etc
242
+ this._storeOptionsAsProperties = false;
243
+ this._actionHandler = null;
244
+ this._executableHandler = false;
245
+ this._executableFile = null; // custom name for executable
246
+ this._executableDir = null; // custom search directory for subcommands
247
+ this._defaultCommandName = null;
248
+ this._exitCallback = null;
249
+ this._aliases = [];
250
+ this._combineFlagAndOptionalValue = true;
251
+ this._description = '';
252
+ this._summary = '';
253
+ this._argsDescription = undefined; // legacy
254
+ this._enablePositionalOptions = false;
255
+ this._passThroughOptions = false;
256
+ this._lifeCycleHooks = {}; // a hash of arrays
257
+ /** @type {(boolean | string)} */
258
+ this._showHelpAfterError = false;
259
+ this._showSuggestionAfterError = true;
260
+
261
+ // see .configureOutput() for docs
262
+ this._outputConfiguration = {
263
+ writeOut: (str) => process.stdout.write(str),
264
+ writeErr: (str) => process.stderr.write(str),
265
+ getOutHelpWidth: () =>
266
+ process.stdout.isTTY ? process.stdout.columns : undefined,
267
+ getErrHelpWidth: () =>
268
+ process.stderr.isTTY ? process.stderr.columns : undefined,
269
+ outputError: (str, write) => write(str),
270
+ };
271
+
272
+ this._hidden = false;
273
+ /** @type {(Option | null | undefined)} */
274
+ this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.
275
+ this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited
276
+ /** @type {Command} */
277
+ this._helpCommand = undefined; // lazy initialised, inherited
278
+ this._helpConfiguration = {};
279
+ }
280
+
281
+ /**
282
+ * Copy settings that are useful to have in common across root command and subcommands.
283
+ *
284
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
285
+ *
286
+ * @param {Command} sourceCommand
287
+ * @return {Command} `this` command for chaining
288
+ */
289
+ copyInheritedSettings(sourceCommand) {
290
+ this._outputConfiguration = sourceCommand._outputConfiguration;
291
+ this._helpOption = sourceCommand._helpOption;
292
+ this._helpCommand = sourceCommand._helpCommand;
293
+ this._helpConfiguration = sourceCommand._helpConfiguration;
294
+ this._exitCallback = sourceCommand._exitCallback;
295
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
296
+ this._combineFlagAndOptionalValue =
297
+ sourceCommand._combineFlagAndOptionalValue;
298
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
299
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
300
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
301
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
302
+
303
+ return this;
304
+ }
305
+
306
+ /**
307
+ * @returns {Command[]}
308
+ * @private
309
+ */
310
+
311
+ _getCommandAndAncestors() {
312
+ const result = [];
313
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
314
+ for (let command = this; command; command = command.parent) {
315
+ result.push(command);
316
+ }
317
+ return result;
318
+ }
319
+
320
+ /**
321
+ * Define a command.
322
+ *
323
+ * There are two styles of command: pay attention to where to put the description.
324
+ *
325
+ * @example
326
+ * // Command implemented using action handler (description is supplied separately to `.command`)
327
+ * program
328
+ * .command('clone <source> [destination]')
329
+ * .description('clone a repository into a newly created directory')
330
+ * .action((source, destination) => {
331
+ * console.log('clone command called');
332
+ * });
333
+ *
334
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
335
+ * program
336
+ * .command('start <service>', 'start named service')
337
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
338
+ *
339
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
340
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
341
+ * @param {object} [execOpts] - configuration options (for executable)
342
+ * @return {Command} returns new command for action handler, or `this` for executable command
343
+ */
344
+
345
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
346
+ let desc = actionOptsOrExecDesc;
347
+ let opts = execOpts;
348
+ if (typeof desc === 'object' && desc !== null) {
349
+ opts = desc;
350
+ desc = null;
351
+ }
352
+ opts = opts || {};
353
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
354
+
355
+ const cmd = this.createCommand(name);
356
+ if (desc) {
357
+ cmd.description(desc);
358
+ cmd._executableHandler = true;
359
+ }
360
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
361
+ cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
362
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
363
+ if (args) cmd.arguments(args);
364
+ this._registerCommand(cmd);
365
+ cmd.parent = this;
366
+ cmd.copyInheritedSettings(this);
367
+
368
+ if (desc) return this;
369
+ return cmd;
370
+ }
371
+
372
+ /**
373
+ * Factory routine to create a new unattached command.
374
+ *
375
+ * See .command() for creating an attached subcommand, which uses this routine to
376
+ * create the command. You can override createCommand to customise subcommands.
377
+ *
378
+ * @param {string} [name]
379
+ * @return {Command} new command
380
+ */
381
+
382
+ createCommand(name) {
383
+ return new Command(name);
384
+ }
385
+
386
+ /**
387
+ * You can customise the help with a subclass of Help by overriding createHelp,
388
+ * or by overriding Help properties using configureHelp().
389
+ *
390
+ * @return {Help}
391
+ */
392
+
393
+ createHelp() {
394
+ return Object.assign(new Help(), this.configureHelp());
395
+ }
396
+
397
+ /**
398
+ * You can customise the help by overriding Help properties using configureHelp(),
399
+ * or with a subclass of Help by overriding createHelp().
400
+ *
401
+ * @param {object} [configuration] - configuration options
402
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
403
+ */
404
+
405
+ configureHelp(configuration) {
406
+ if (configuration === undefined) return this._helpConfiguration;
407
+
408
+ this._helpConfiguration = configuration;
409
+ return this;
410
+ }
411
+
412
+ /**
413
+ * The default output goes to stdout and stderr. You can customise this for special
414
+ * applications. You can also customise the display of errors by overriding outputError.
415
+ *
416
+ * The configuration properties are all functions:
417
+ *
418
+ * // functions to change where being written, stdout and stderr
419
+ * writeOut(str)
420
+ * writeErr(str)
421
+ * // matching functions to specify width for wrapping help
422
+ * getOutHelpWidth()
423
+ * getErrHelpWidth()
424
+ * // functions based on what is being written out
425
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
426
+ *
427
+ * @param {object} [configuration] - configuration options
428
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
429
+ */
430
+
431
+ configureOutput(configuration) {
432
+ if (configuration === undefined) return this._outputConfiguration;
433
+
434
+ Object.assign(this._outputConfiguration, configuration);
435
+ return this;
436
+ }
437
+
438
+ /**
439
+ * Display the help or a custom message after an error occurs.
440
+ *
441
+ * @param {(boolean|string)} [displayHelp]
442
+ * @return {Command} `this` command for chaining
443
+ */
444
+ showHelpAfterError(displayHelp = true) {
445
+ if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
446
+ this._showHelpAfterError = displayHelp;
447
+ return this;
448
+ }
449
+
450
+ /**
451
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
452
+ *
453
+ * @param {boolean} [displaySuggestion]
454
+ * @return {Command} `this` command for chaining
455
+ */
456
+ showSuggestionAfterError(displaySuggestion = true) {
457
+ this._showSuggestionAfterError = !!displaySuggestion;
458
+ return this;
459
+ }
460
+
461
+ /**
462
+ * Add a prepared subcommand.
463
+ *
464
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
465
+ *
466
+ * @param {Command} cmd - new subcommand
467
+ * @param {object} [opts] - configuration options
468
+ * @return {Command} `this` command for chaining
469
+ */
470
+
471
+ addCommand(cmd, opts) {
472
+ if (!cmd._name) {
473
+ throw new Error(`Command passed to .addCommand() must have a name
474
+ - specify the name in Command constructor or using .name()`);
475
+ }
476
+
477
+ opts = opts || {};
478
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
479
+ if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
480
+
481
+ this._registerCommand(cmd);
482
+ cmd.parent = this;
483
+ cmd._checkForBrokenPassThrough();
484
+
485
+ return this;
486
+ }
487
+
488
+ /**
489
+ * Factory routine to create a new unattached argument.
490
+ *
491
+ * See .argument() for creating an attached argument, which uses this routine to
492
+ * create the argument. You can override createArgument to return a custom argument.
493
+ *
494
+ * @param {string} name
495
+ * @param {string} [description]
496
+ * @return {Argument} new argument
497
+ */
498
+
499
+ createArgument(name, description) {
500
+ return new Argument(name, description);
501
+ }
502
+
503
+ /**
504
+ * Define argument syntax for command.
505
+ *
506
+ * The default is that the argument is required, and you can explicitly
507
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
508
+ *
509
+ * @example
510
+ * program.argument('<input-file>');
511
+ * program.argument('[output-file]');
512
+ *
513
+ * @param {string} name
514
+ * @param {string} [description]
515
+ * @param {(Function|*)} [fn] - custom argument processing function
516
+ * @param {*} [defaultValue]
517
+ * @return {Command} `this` command for chaining
518
+ */
519
+ argument(name, description, fn, defaultValue) {
520
+ const argument = this.createArgument(name, description);
521
+ if (typeof fn === 'function') {
522
+ argument.default(defaultValue).argParser(fn);
523
+ } else {
524
+ argument.default(fn);
525
+ }
526
+ this.addArgument(argument);
527
+ return this;
528
+ }
529
+
530
+ /**
531
+ * Define argument syntax for command, adding multiple at once (without descriptions).
532
+ *
533
+ * See also .argument().
534
+ *
535
+ * @example
536
+ * program.arguments('<cmd> [env]');
537
+ *
538
+ * @param {string} names
539
+ * @return {Command} `this` command for chaining
540
+ */
541
+
542
+ arguments(names) {
543
+ names
544
+ .trim()
545
+ .split(/ +/)
546
+ .forEach((detail) => {
547
+ this.argument(detail);
548
+ });
549
+ return this;
550
+ }
551
+
552
+ /**
553
+ * Define argument syntax for command, adding a prepared argument.
554
+ *
555
+ * @param {Argument} argument
556
+ * @return {Command} `this` command for chaining
557
+ */
558
+ addArgument(argument) {
559
+ const previousArgument = this.registeredArguments.slice(-1)[0];
560
+ if (previousArgument && previousArgument.variadic) {
561
+ throw new Error(
562
+ `only the last argument can be variadic '${previousArgument.name()}'`,
563
+ );
564
+ }
565
+ if (
566
+ argument.required &&
567
+ argument.defaultValue !== undefined &&
568
+ argument.parseArg === undefined
569
+ ) {
570
+ throw new Error(
571
+ `a default value for a required argument is never used: '${argument.name()}'`,
572
+ );
573
+ }
574
+ this.registeredArguments.push(argument);
575
+ return this;
576
+ }
577
+
578
+ /**
579
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
580
+ *
581
+ * @example
582
+ * program.helpCommand('help [cmd]');
583
+ * program.helpCommand('help [cmd]', 'show help');
584
+ * program.helpCommand(false); // suppress default help command
585
+ * program.helpCommand(true); // add help command even if no subcommands
586
+ *
587
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
588
+ * @param {string} [description] - custom description
589
+ * @return {Command} `this` command for chaining
590
+ */
591
+
592
+ helpCommand(enableOrNameAndArgs, description) {
593
+ if (typeof enableOrNameAndArgs === 'boolean') {
594
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
595
+ return this;
596
+ }
597
+
598
+ enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';
599
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
600
+ const helpDescription = description ?? 'display help for command';
601
+
602
+ const helpCommand = this.createCommand(helpName);
603
+ helpCommand.helpOption(false);
604
+ if (helpArgs) helpCommand.arguments(helpArgs);
605
+ if (helpDescription) helpCommand.description(helpDescription);
606
+
607
+ this._addImplicitHelpCommand = true;
608
+ this._helpCommand = helpCommand;
609
+
610
+ return this;
611
+ }
612
+
613
+ /**
614
+ * Add prepared custom help command.
615
+ *
616
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
617
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
618
+ * @return {Command} `this` command for chaining
619
+ */
620
+ addHelpCommand(helpCommand, deprecatedDescription) {
621
+ // If not passed an object, call through to helpCommand for backwards compatibility,
622
+ // as addHelpCommand was originally used like helpCommand is now.
623
+ if (typeof helpCommand !== 'object') {
624
+ this.helpCommand(helpCommand, deprecatedDescription);
625
+ return this;
626
+ }
627
+
628
+ this._addImplicitHelpCommand = true;
629
+ this._helpCommand = helpCommand;
630
+ return this;
631
+ }
632
+
633
+ /**
634
+ * Lazy create help command.
635
+ *
636
+ * @return {(Command|null)}
637
+ * @package
638
+ */
639
+ _getHelpCommand() {
640
+ const hasImplicitHelpCommand =
641
+ this._addImplicitHelpCommand ??
642
+ (this.commands.length &&
643
+ !this._actionHandler &&
644
+ !this._findCommand('help'));
645
+
646
+ if (hasImplicitHelpCommand) {
647
+ if (this._helpCommand === undefined) {
648
+ this.helpCommand(undefined, undefined); // use default name and description
649
+ }
650
+ return this._helpCommand;
651
+ }
652
+ return null;
653
+ }
654
+
655
+ /**
656
+ * Add hook for life cycle event.
657
+ *
658
+ * @param {string} event
659
+ * @param {Function} listener
660
+ * @return {Command} `this` command for chaining
661
+ */
662
+
663
+ hook(event, listener) {
664
+ const allowedValues = ['preSubcommand', 'preAction', 'postAction'];
665
+ if (!allowedValues.includes(event)) {
666
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
667
+ Expecting one of '${allowedValues.join("', '")}'`);
668
+ }
669
+ if (this._lifeCycleHooks[event]) {
670
+ this._lifeCycleHooks[event].push(listener);
671
+ } else {
672
+ this._lifeCycleHooks[event] = [listener];
673
+ }
674
+ return this;
675
+ }
676
+
677
+ /**
678
+ * Register callback to use as replacement for calling process.exit.
679
+ *
680
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
681
+ * @return {Command} `this` command for chaining
682
+ */
683
+
684
+ exitOverride(fn) {
685
+ if (fn) {
686
+ this._exitCallback = fn;
687
+ } else {
688
+ this._exitCallback = (err) => {
689
+ if (err.code !== 'commander.executeSubCommandAsync') {
690
+ throw err;
691
+ } else {
692
+ // Async callback from spawn events, not useful to throw.
693
+ }
694
+ };
695
+ }
696
+ return this;
697
+ }
698
+
699
+ /**
700
+ * Call process.exit, and _exitCallback if defined.
701
+ *
702
+ * @param {number} exitCode exit code for using with process.exit
703
+ * @param {string} code an id string representing the error
704
+ * @param {string} message human-readable description of the error
705
+ * @return never
706
+ * @private
707
+ */
708
+
709
+ _exit(exitCode, code, message) {
710
+ if (this._exitCallback) {
711
+ this._exitCallback(new CommanderError(exitCode, code, message));
712
+ // Expecting this line is not reached.
713
+ }
714
+ process.exit(exitCode);
715
+ }
716
+
717
+ /**
718
+ * Register callback `fn` for the command.
719
+ *
720
+ * @example
721
+ * program
722
+ * .command('serve')
723
+ * .description('start service')
724
+ * .action(function() {
725
+ * // do work here
726
+ * });
727
+ *
728
+ * @param {Function} fn
729
+ * @return {Command} `this` command for chaining
730
+ */
731
+
732
+ action(fn) {
733
+ const listener = (args) => {
734
+ // The .action callback takes an extra parameter which is the command or options.
735
+ const expectedArgsCount = this.registeredArguments.length;
736
+ const actionArgs = args.slice(0, expectedArgsCount);
737
+ if (this._storeOptionsAsProperties) {
738
+ actionArgs[expectedArgsCount] = this; // backwards compatible "options"
739
+ } else {
740
+ actionArgs[expectedArgsCount] = this.opts();
741
+ }
742
+ actionArgs.push(this);
743
+
744
+ return fn.apply(this, actionArgs);
745
+ };
746
+ this._actionHandler = listener;
747
+ return this;
748
+ }
749
+
750
+ /**
751
+ * Factory routine to create a new unattached option.
752
+ *
753
+ * See .option() for creating an attached option, which uses this routine to
754
+ * create the option. You can override createOption to return a custom option.
755
+ *
756
+ * @param {string} flags
757
+ * @param {string} [description]
758
+ * @return {Option} new option
759
+ */
760
+
761
+ createOption(flags, description) {
762
+ return new Option(flags, description);
763
+ }
764
+
765
+ /**
766
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
767
+ *
768
+ * @param {(Option | Argument)} target
769
+ * @param {string} value
770
+ * @param {*} previous
771
+ * @param {string} invalidArgumentMessage
772
+ * @private
773
+ */
774
+
775
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
776
+ try {
777
+ return target.parseArg(value, previous);
778
+ } catch (err) {
779
+ if (err.code === 'commander.invalidArgument') {
780
+ const message = `${invalidArgumentMessage} ${err.message}`;
781
+ this.error(message, { exitCode: err.exitCode, code: err.code });
782
+ }
783
+ throw err;
784
+ }
785
+ }
786
+
787
+ /**
788
+ * Check for option flag conflicts.
789
+ * Register option if no conflicts found, or throw on conflict.
790
+ *
791
+ * @param {Option} option
792
+ * @private
793
+ */
794
+
795
+ _registerOption(option) {
796
+ const matchingOption =
797
+ (option.short && this._findOption(option.short)) ||
798
+ (option.long && this._findOption(option.long));
799
+ if (matchingOption) {
800
+ const matchingFlag =
801
+ option.long && this._findOption(option.long)
802
+ ? option.long
803
+ : option.short;
804
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
805
+ - already used by option '${matchingOption.flags}'`);
806
+ }
807
+
808
+ this.options.push(option);
809
+ }
810
+
811
+ /**
812
+ * Check for command name and alias conflicts with existing commands.
813
+ * Register command if no conflicts found, or throw on conflict.
814
+ *
815
+ * @param {Command} command
816
+ * @private
817
+ */
818
+
819
+ _registerCommand(command) {
820
+ const knownBy = (cmd) => {
821
+ return [cmd.name()].concat(cmd.aliases());
822
+ };
823
+
824
+ const alreadyUsed = knownBy(command).find((name) =>
825
+ this._findCommand(name),
826
+ );
827
+ if (alreadyUsed) {
828
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
829
+ const newCmd = knownBy(command).join('|');
830
+ throw new Error(
831
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`,
832
+ );
833
+ }
834
+
835
+ this.commands.push(command);
836
+ }
837
+
838
+ /**
839
+ * Add an option.
840
+ *
841
+ * @param {Option} option
842
+ * @return {Command} `this` command for chaining
843
+ */
844
+ addOption(option) {
845
+ this._registerOption(option);
846
+
847
+ const oname = option.name();
848
+ const name = option.attributeName();
849
+
850
+ // store default value
851
+ if (option.negate) {
852
+ // --no-foo is special and defaults foo to true, unless a --foo option is already defined
853
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
854
+ if (!this._findOption(positiveLongFlag)) {
855
+ this.setOptionValueWithSource(
856
+ name,
857
+ option.defaultValue === undefined ? true : option.defaultValue,
858
+ 'default',
859
+ );
860
+ }
861
+ } else if (option.defaultValue !== undefined) {
862
+ this.setOptionValueWithSource(name, option.defaultValue, 'default');
863
+ }
864
+
865
+ // handler for cli and env supplied values
866
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
867
+ // val is null for optional option used without an optional-argument.
868
+ // val is undefined for boolean and negated option.
869
+ if (val == null && option.presetArg !== undefined) {
870
+ val = option.presetArg;
871
+ }
872
+
873
+ // custom processing
874
+ const oldValue = this.getOptionValue(name);
875
+ if (val !== null && option.parseArg) {
876
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
877
+ } else if (val !== null && option.variadic) {
878
+ val = option._concatValue(val, oldValue);
879
+ }
880
+
881
+ // Fill-in appropriate missing values. Long winded but easy to follow.
882
+ if (val == null) {
883
+ if (option.negate) {
884
+ val = false;
885
+ } else if (option.isBoolean() || option.optional) {
886
+ val = true;
887
+ } else {
888
+ val = ''; // not normal, parseArg might have failed or be a mock function for testing
889
+ }
890
+ }
891
+ this.setOptionValueWithSource(name, val, valueSource);
892
+ };
893
+
894
+ this.on('option:' + oname, (val) => {
895
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
896
+ handleOptionValue(val, invalidValueMessage, 'cli');
897
+ });
898
+
899
+ if (option.envVar) {
900
+ this.on('optionEnv:' + oname, (val) => {
901
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
902
+ handleOptionValue(val, invalidValueMessage, 'env');
903
+ });
904
+ }
905
+
906
+ return this;
907
+ }
908
+
909
+ /**
910
+ * Internal implementation shared by .option() and .requiredOption()
911
+ *
912
+ * @return {Command} `this` command for chaining
913
+ * @private
914
+ */
915
+ _optionEx(config, flags, description, fn, defaultValue) {
916
+ if (typeof flags === 'object' && flags instanceof Option) {
917
+ throw new Error(
918
+ 'To add an Option object use addOption() instead of option() or requiredOption()',
919
+ );
920
+ }
921
+ const option = this.createOption(flags, description);
922
+ option.makeOptionMandatory(!!config.mandatory);
923
+ if (typeof fn === 'function') {
924
+ option.default(defaultValue).argParser(fn);
925
+ } else if (fn instanceof RegExp) {
926
+ // deprecated
927
+ const regex = fn;
928
+ fn = (val, def) => {
929
+ const m = regex.exec(val);
930
+ return m ? m[0] : def;
931
+ };
932
+ option.default(defaultValue).argParser(fn);
933
+ } else {
934
+ option.default(fn);
935
+ }
936
+
937
+ return this.addOption(option);
938
+ }
939
+
940
+ /**
941
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
942
+ *
943
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
944
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
945
+ *
946
+ * See the README for more details, and see also addOption() and requiredOption().
947
+ *
948
+ * @example
949
+ * program
950
+ * .option('-p, --pepper', 'add pepper')
951
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
952
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
953
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
954
+ *
955
+ * @param {string} flags
956
+ * @param {string} [description]
957
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
958
+ * @param {*} [defaultValue]
959
+ * @return {Command} `this` command for chaining
960
+ */
961
+
962
+ option(flags, description, parseArg, defaultValue) {
963
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
964
+ }
965
+
966
+ /**
967
+ * Add a required option which must have a value after parsing. This usually means
968
+ * the option must be specified on the command line. (Otherwise the same as .option().)
969
+ *
970
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
971
+ *
972
+ * @param {string} flags
973
+ * @param {string} [description]
974
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
975
+ * @param {*} [defaultValue]
976
+ * @return {Command} `this` command for chaining
977
+ */
978
+
979
+ requiredOption(flags, description, parseArg, defaultValue) {
980
+ return this._optionEx(
981
+ { mandatory: true },
982
+ flags,
983
+ description,
984
+ parseArg,
985
+ defaultValue,
986
+ );
987
+ }
988
+
989
+ /**
990
+ * Alter parsing of short flags with optional values.
991
+ *
992
+ * @example
993
+ * // for `.option('-f,--flag [value]'):
994
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
995
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
996
+ *
997
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
998
+ * @return {Command} `this` command for chaining
999
+ */
1000
+ combineFlagAndOptionalValue(combine = true) {
1001
+ this._combineFlagAndOptionalValue = !!combine;
1002
+ return this;
1003
+ }
1004
+
1005
+ /**
1006
+ * Allow unknown options on the command line.
1007
+ *
1008
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1009
+ * @return {Command} `this` command for chaining
1010
+ */
1011
+ allowUnknownOption(allowUnknown = true) {
1012
+ this._allowUnknownOption = !!allowUnknown;
1013
+ return this;
1014
+ }
1015
+
1016
+ /**
1017
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1018
+ *
1019
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1020
+ * @return {Command} `this` command for chaining
1021
+ */
1022
+ allowExcessArguments(allowExcess = true) {
1023
+ this._allowExcessArguments = !!allowExcess;
1024
+ return this;
1025
+ }
1026
+
1027
+ /**
1028
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1029
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1030
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1031
+ *
1032
+ * @param {boolean} [positional]
1033
+ * @return {Command} `this` command for chaining
1034
+ */
1035
+ enablePositionalOptions(positional = true) {
1036
+ this._enablePositionalOptions = !!positional;
1037
+ return this;
1038
+ }
1039
+
1040
+ /**
1041
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1042
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1043
+ * positional options to have been enabled on the program (parent commands).
1044
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1045
+ *
1046
+ * @param {boolean} [passThrough] for unknown options.
1047
+ * @return {Command} `this` command for chaining
1048
+ */
1049
+ passThroughOptions(passThrough = true) {
1050
+ this._passThroughOptions = !!passThrough;
1051
+ this._checkForBrokenPassThrough();
1052
+ return this;
1053
+ }
1054
+
1055
+ /**
1056
+ * @private
1057
+ */
1058
+
1059
+ _checkForBrokenPassThrough() {
1060
+ if (
1061
+ this.parent &&
1062
+ this._passThroughOptions &&
1063
+ !this.parent._enablePositionalOptions
1064
+ ) {
1065
+ throw new Error(
1066
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,
1067
+ );
1068
+ }
1069
+ }
1070
+
1071
+ /**
1072
+ * Whether to store option values as properties on command object,
1073
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1074
+ *
1075
+ * @param {boolean} [storeAsProperties=true]
1076
+ * @return {Command} `this` command for chaining
1077
+ */
1078
+
1079
+ storeOptionsAsProperties(storeAsProperties = true) {
1080
+ if (this.options.length) {
1081
+ throw new Error('call .storeOptionsAsProperties() before adding options');
1082
+ }
1083
+ if (Object.keys(this._optionValues).length) {
1084
+ throw new Error(
1085
+ 'call .storeOptionsAsProperties() before setting option values',
1086
+ );
1087
+ }
1088
+ this._storeOptionsAsProperties = !!storeAsProperties;
1089
+ return this;
1090
+ }
1091
+
1092
+ /**
1093
+ * Retrieve option value.
1094
+ *
1095
+ * @param {string} key
1096
+ * @return {object} value
1097
+ */
1098
+
1099
+ getOptionValue(key) {
1100
+ if (this._storeOptionsAsProperties) {
1101
+ return this[key];
1102
+ }
1103
+ return this._optionValues[key];
1104
+ }
1105
+
1106
+ /**
1107
+ * Store option value.
1108
+ *
1109
+ * @param {string} key
1110
+ * @param {object} value
1111
+ * @return {Command} `this` command for chaining
1112
+ */
1113
+
1114
+ setOptionValue(key, value) {
1115
+ return this.setOptionValueWithSource(key, value, undefined);
1116
+ }
1117
+
1118
+ /**
1119
+ * Store option value and where the value came from.
1120
+ *
1121
+ * @param {string} key
1122
+ * @param {object} value
1123
+ * @param {string} source - expected values are default/config/env/cli/implied
1124
+ * @return {Command} `this` command for chaining
1125
+ */
1126
+
1127
+ setOptionValueWithSource(key, value, source) {
1128
+ if (this._storeOptionsAsProperties) {
1129
+ this[key] = value;
1130
+ } else {
1131
+ this._optionValues[key] = value;
1132
+ }
1133
+ this._optionValueSources[key] = source;
1134
+ return this;
1135
+ }
1136
+
1137
+ /**
1138
+ * Get source of option value.
1139
+ * Expected values are default | config | env | cli | implied
1140
+ *
1141
+ * @param {string} key
1142
+ * @return {string}
1143
+ */
1144
+
1145
+ getOptionValueSource(key) {
1146
+ return this._optionValueSources[key];
1147
+ }
1148
+
1149
+ /**
1150
+ * Get source of option value. See also .optsWithGlobals().
1151
+ * Expected values are default | config | env | cli | implied
1152
+ *
1153
+ * @param {string} key
1154
+ * @return {string}
1155
+ */
1156
+
1157
+ getOptionValueSourceWithGlobals(key) {
1158
+ // global overwrites local, like optsWithGlobals
1159
+ let source;
1160
+ this._getCommandAndAncestors().forEach((cmd) => {
1161
+ if (cmd.getOptionValueSource(key) !== undefined) {
1162
+ source = cmd.getOptionValueSource(key);
1163
+ }
1164
+ });
1165
+ return source;
1166
+ }
1167
+
1168
+ /**
1169
+ * Get user arguments from implied or explicit arguments.
1170
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1171
+ *
1172
+ * @private
1173
+ */
1174
+
1175
+ _prepareUserArgs(argv, parseOptions) {
1176
+ if (argv !== undefined && !Array.isArray(argv)) {
1177
+ throw new Error('first parameter to parse must be array or undefined');
1178
+ }
1179
+ parseOptions = parseOptions || {};
1180
+
1181
+ // auto-detect argument conventions if nothing supplied
1182
+ if (argv === undefined && parseOptions.from === undefined) {
1183
+ if (process.versions?.electron) {
1184
+ parseOptions.from = 'electron';
1185
+ }
1186
+ // check node specific options for scenarios where user CLI args follow executable without scriptname
1187
+ const execArgv = process.execArgv ?? [];
1188
+ if (
1189
+ execArgv.includes('-e') ||
1190
+ execArgv.includes('--eval') ||
1191
+ execArgv.includes('-p') ||
1192
+ execArgv.includes('--print')
1193
+ ) {
1194
+ parseOptions.from = 'eval'; // internal usage, not documented
1195
+ }
1196
+ }
1197
+
1198
+ // default to using process.argv
1199
+ if (argv === undefined) {
1200
+ argv = process.argv;
1201
+ }
1202
+ this.rawArgs = argv.slice();
1203
+
1204
+ // extract the user args and scriptPath
1205
+ let userArgs;
1206
+ switch (parseOptions.from) {
1207
+ case undefined:
1208
+ case 'node':
1209
+ this._scriptPath = argv[1];
1210
+ userArgs = argv.slice(2);
1211
+ break;
1212
+ case 'electron':
1213
+ // @ts-ignore: because defaultApp is an unknown property
1214
+ if (process.defaultApp) {
1215
+ this._scriptPath = argv[1];
1216
+ userArgs = argv.slice(2);
1217
+ } else {
1218
+ userArgs = argv.slice(1);
1219
+ }
1220
+ break;
1221
+ case 'user':
1222
+ userArgs = argv.slice(0);
1223
+ break;
1224
+ case 'eval':
1225
+ userArgs = argv.slice(1);
1226
+ break;
1227
+ default:
1228
+ throw new Error(
1229
+ `unexpected parse option { from: '${parseOptions.from}' }`,
1230
+ );
1231
+ }
1232
+
1233
+ // Find default name for program from arguments.
1234
+ if (!this._name && this._scriptPath)
1235
+ this.nameFromFilename(this._scriptPath);
1236
+ this._name = this._name || 'program';
1237
+
1238
+ return userArgs;
1239
+ }
1240
+
1241
+ /**
1242
+ * Parse `argv`, setting options and invoking commands when defined.
1243
+ *
1244
+ * Use parseAsync instead of parse if any of your action handlers are async.
1245
+ *
1246
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1247
+ *
1248
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1249
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1250
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1251
+ * - `'user'`: just user arguments
1252
+ *
1253
+ * @example
1254
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1255
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1256
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1257
+ *
1258
+ * @param {string[]} [argv] - optional, defaults to process.argv
1259
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1260
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1261
+ * @return {Command} `this` command for chaining
1262
+ */
1263
+
1264
+ parse(argv, parseOptions) {
1265
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1266
+ this._parseCommand([], userArgs);
1267
+
1268
+ return this;
1269
+ }
1270
+
1271
+ /**
1272
+ * Parse `argv`, setting options and invoking commands when defined.
1273
+ *
1274
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1275
+ *
1276
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1277
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1278
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1279
+ * - `'user'`: just user arguments
1280
+ *
1281
+ * @example
1282
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1283
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1284
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1285
+ *
1286
+ * @param {string[]} [argv]
1287
+ * @param {object} [parseOptions]
1288
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1289
+ * @return {Promise}
1290
+ */
1291
+
1292
+ async parseAsync(argv, parseOptions) {
1293
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1294
+ await this._parseCommand([], userArgs);
1295
+
1296
+ return this;
1297
+ }
1298
+
1299
+ /**
1300
+ * Execute a sub-command executable.
1301
+ *
1302
+ * @private
1303
+ */
1304
+
1305
+ _executeSubCommand(subcommand, args) {
1306
+ args = args.slice();
1307
+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
1308
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
1309
+
1310
+ function findFile(baseDir, baseName) {
1311
+ // Look for specified file
1312
+ const localBin = path.resolve(baseDir, baseName);
1313
+ if (fs.existsSync(localBin)) return localBin;
1314
+
1315
+ // Stop looking if candidate already has an expected extension.
1316
+ if (sourceExt.includes(path.extname(baseName))) return undefined;
1317
+
1318
+ // Try all the extensions.
1319
+ const foundExt = sourceExt.find((ext) =>
1320
+ fs.existsSync(`${localBin}${ext}`),
1321
+ );
1322
+ if (foundExt) return `${localBin}${foundExt}`;
1323
+
1324
+ return undefined;
1325
+ }
1326
+
1327
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
1328
+ this._checkForMissingMandatoryOptions();
1329
+ this._checkForConflictingOptions();
1330
+
1331
+ // executableFile and executableDir might be full path, or just a name
1332
+ let executableFile =
1333
+ subcommand._executableFile || `${this._name}-${subcommand._name}`;
1334
+ let executableDir = this._executableDir || '';
1335
+ if (this._scriptPath) {
1336
+ let resolvedScriptPath; // resolve possible symlink for installed npm binary
1337
+ try {
1338
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1339
+ } catch (err) {
1340
+ resolvedScriptPath = this._scriptPath;
1341
+ }
1342
+ executableDir = path.resolve(
1343
+ path.dirname(resolvedScriptPath),
1344
+ executableDir,
1345
+ );
1346
+ }
1347
+
1348
+ // Look for a local file in preference to a command in PATH.
1349
+ if (executableDir) {
1350
+ let localFile = findFile(executableDir, executableFile);
1351
+
1352
+ // Legacy search using prefix of script name instead of command name
1353
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1354
+ const legacyName = path.basename(
1355
+ this._scriptPath,
1356
+ path.extname(this._scriptPath),
1357
+ );
1358
+ if (legacyName !== this._name) {
1359
+ localFile = findFile(
1360
+ executableDir,
1361
+ `${legacyName}-${subcommand._name}`,
1362
+ );
1363
+ }
1364
+ }
1365
+ executableFile = localFile || executableFile;
1366
+ }
1367
+
1368
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1369
+
1370
+ let proc;
1371
+ if (process.platform !== 'win32') {
1372
+ if (launchWithNode) {
1373
+ args.unshift(executableFile);
1374
+ // add executable arguments to spawn
1375
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1376
+
1377
+ proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
1378
+ } else {
1379
+ proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });
1380
+ }
1381
+ } else {
1382
+ args.unshift(executableFile);
1383
+ // add executable arguments to spawn
1384
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1385
+ proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
1386
+ }
1387
+
1388
+ if (!proc.killed) {
1389
+ // testing mainly to avoid leak warnings during unit tests with mocked spawn
1390
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
1391
+ signals.forEach((signal) => {
1392
+ process.on(signal, () => {
1393
+ if (proc.killed === false && proc.exitCode === null) {
1394
+ // @ts-ignore because signals not typed to known strings
1395
+ proc.kill(signal);
1396
+ }
1397
+ });
1398
+ });
1399
+ }
1400
+
1401
+ // By default terminate process when spawned process terminates.
1402
+ const exitCallback = this._exitCallback;
1403
+ proc.on('close', (code) => {
1404
+ code = code ?? 1; // code is null if spawned process terminated due to a signal
1405
+ if (!exitCallback) {
1406
+ process.exit(code);
1407
+ } else {
1408
+ exitCallback(
1409
+ new CommanderError(
1410
+ code,
1411
+ 'commander.executeSubCommandAsync',
1412
+ '(close)',
1413
+ ),
1414
+ );
1415
+ }
1416
+ });
1417
+ proc.on('error', (err) => {
1418
+ // @ts-ignore: because err.code is an unknown property
1419
+ if (err.code === 'ENOENT') {
1420
+ const executableDirMessage = executableDir
1421
+ ? `searched for local subcommand relative to directory '${executableDir}'`
1422
+ : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
1423
+ const executableMissing = `'${executableFile}' does not exist
1424
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1425
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1426
+ - ${executableDirMessage}`;
1427
+ throw new Error(executableMissing);
1428
+ // @ts-ignore: because err.code is an unknown property
1429
+ } else if (err.code === 'EACCES') {
1430
+ throw new Error(`'${executableFile}' not executable`);
1431
+ }
1432
+ if (!exitCallback) {
1433
+ process.exit(1);
1434
+ } else {
1435
+ const wrappedError = new CommanderError(
1436
+ 1,
1437
+ 'commander.executeSubCommandAsync',
1438
+ '(error)',
1439
+ );
1440
+ wrappedError.nestedError = err;
1441
+ exitCallback(wrappedError);
1442
+ }
1443
+ });
1444
+
1445
+ // Store the reference to the child process
1446
+ this.runningCommand = proc;
1447
+ }
1448
+
1449
+ /**
1450
+ * @private
1451
+ */
1452
+
1453
+ _dispatchSubcommand(commandName, operands, unknown) {
1454
+ const subCommand = this._findCommand(commandName);
1455
+ if (!subCommand) this.help({ error: true });
1456
+
1457
+ let promiseChain;
1458
+ promiseChain = this._chainOrCallSubCommandHook(
1459
+ promiseChain,
1460
+ subCommand,
1461
+ 'preSubcommand',
1462
+ );
1463
+ promiseChain = this._chainOrCall(promiseChain, () => {
1464
+ if (subCommand._executableHandler) {
1465
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1466
+ } else {
1467
+ return subCommand._parseCommand(operands, unknown);
1468
+ }
1469
+ });
1470
+ return promiseChain;
1471
+ }
1472
+
1473
+ /**
1474
+ * Invoke help directly if possible, or dispatch if necessary.
1475
+ * e.g. help foo
1476
+ *
1477
+ * @private
1478
+ */
1479
+
1480
+ _dispatchHelpCommand(subcommandName) {
1481
+ if (!subcommandName) {
1482
+ this.help();
1483
+ }
1484
+ const subCommand = this._findCommand(subcommandName);
1485
+ if (subCommand && !subCommand._executableHandler) {
1486
+ subCommand.help();
1487
+ }
1488
+
1489
+ // Fallback to parsing the help flag to invoke the help.
1490
+ return this._dispatchSubcommand(
1491
+ subcommandName,
1492
+ [],
1493
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],
1494
+ );
1495
+ }
1496
+
1497
+ /**
1498
+ * Check this.args against expected this.registeredArguments.
1499
+ *
1500
+ * @private
1501
+ */
1502
+
1503
+ _checkNumberOfArguments() {
1504
+ // too few
1505
+ this.registeredArguments.forEach((arg, i) => {
1506
+ if (arg.required && this.args[i] == null) {
1507
+ this.missingArgument(arg.name());
1508
+ }
1509
+ });
1510
+ // too many
1511
+ if (
1512
+ this.registeredArguments.length > 0 &&
1513
+ this.registeredArguments[this.registeredArguments.length - 1].variadic
1514
+ ) {
1515
+ return;
1516
+ }
1517
+ if (this.args.length > this.registeredArguments.length) {
1518
+ this._excessArguments(this.args);
1519
+ }
1520
+ }
1521
+
1522
+ /**
1523
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
1524
+ *
1525
+ * @private
1526
+ */
1527
+
1528
+ _processArguments() {
1529
+ const myParseArg = (argument, value, previous) => {
1530
+ // Extra processing for nice error message on parsing failure.
1531
+ let parsedValue = value;
1532
+ if (value !== null && argument.parseArg) {
1533
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1534
+ parsedValue = this._callParseArg(
1535
+ argument,
1536
+ value,
1537
+ previous,
1538
+ invalidValueMessage,
1539
+ );
1540
+ }
1541
+ return parsedValue;
1542
+ };
1543
+
1544
+ this._checkNumberOfArguments();
1545
+
1546
+ const processedArgs = [];
1547
+ this.registeredArguments.forEach((declaredArg, index) => {
1548
+ let value = declaredArg.defaultValue;
1549
+ if (declaredArg.variadic) {
1550
+ // Collect together remaining arguments for passing together as an array.
1551
+ if (index < this.args.length) {
1552
+ value = this.args.slice(index);
1553
+ if (declaredArg.parseArg) {
1554
+ value = value.reduce((processed, v) => {
1555
+ return myParseArg(declaredArg, v, processed);
1556
+ }, declaredArg.defaultValue);
1557
+ }
1558
+ } else if (value === undefined) {
1559
+ value = [];
1560
+ }
1561
+ } else if (index < this.args.length) {
1562
+ value = this.args[index];
1563
+ if (declaredArg.parseArg) {
1564
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1565
+ }
1566
+ }
1567
+ processedArgs[index] = value;
1568
+ });
1569
+ this.processedArgs = processedArgs;
1570
+ }
1571
+
1572
+ /**
1573
+ * Once we have a promise we chain, but call synchronously until then.
1574
+ *
1575
+ * @param {(Promise|undefined)} promise
1576
+ * @param {Function} fn
1577
+ * @return {(Promise|undefined)}
1578
+ * @private
1579
+ */
1580
+
1581
+ _chainOrCall(promise, fn) {
1582
+ // thenable
1583
+ if (promise && promise.then && typeof promise.then === 'function') {
1584
+ // already have a promise, chain callback
1585
+ return promise.then(() => fn());
1586
+ }
1587
+ // callback might return a promise
1588
+ return fn();
1589
+ }
1590
+
1591
+ /**
1592
+ *
1593
+ * @param {(Promise|undefined)} promise
1594
+ * @param {string} event
1595
+ * @return {(Promise|undefined)}
1596
+ * @private
1597
+ */
1598
+
1599
+ _chainOrCallHooks(promise, event) {
1600
+ let result = promise;
1601
+ const hooks = [];
1602
+ this._getCommandAndAncestors()
1603
+ .reverse()
1604
+ .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)
1605
+ .forEach((hookedCommand) => {
1606
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1607
+ hooks.push({ hookedCommand, callback });
1608
+ });
1609
+ });
1610
+ if (event === 'postAction') {
1611
+ hooks.reverse();
1612
+ }
1613
+
1614
+ hooks.forEach((hookDetail) => {
1615
+ result = this._chainOrCall(result, () => {
1616
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1617
+ });
1618
+ });
1619
+ return result;
1620
+ }
1621
+
1622
+ /**
1623
+ *
1624
+ * @param {(Promise|undefined)} promise
1625
+ * @param {Command} subCommand
1626
+ * @param {string} event
1627
+ * @return {(Promise|undefined)}
1628
+ * @private
1629
+ */
1630
+
1631
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1632
+ let result = promise;
1633
+ if (this._lifeCycleHooks[event] !== undefined) {
1634
+ this._lifeCycleHooks[event].forEach((hook) => {
1635
+ result = this._chainOrCall(result, () => {
1636
+ return hook(this, subCommand);
1637
+ });
1638
+ });
1639
+ }
1640
+ return result;
1641
+ }
1642
+
1643
+ /**
1644
+ * Process arguments in context of this command.
1645
+ * Returns action result, in case it is a promise.
1646
+ *
1647
+ * @private
1648
+ */
1649
+
1650
+ _parseCommand(operands, unknown) {
1651
+ const parsed = this.parseOptions(unknown);
1652
+ this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env
1653
+ this._parseOptionsImplied();
1654
+ operands = operands.concat(parsed.operands);
1655
+ unknown = parsed.unknown;
1656
+ this.args = operands.concat(unknown);
1657
+
1658
+ if (operands && this._findCommand(operands[0])) {
1659
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1660
+ }
1661
+ if (
1662
+ this._getHelpCommand() &&
1663
+ operands[0] === this._getHelpCommand().name()
1664
+ ) {
1665
+ return this._dispatchHelpCommand(operands[1]);
1666
+ }
1667
+ if (this._defaultCommandName) {
1668
+ this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command
1669
+ return this._dispatchSubcommand(
1670
+ this._defaultCommandName,
1671
+ operands,
1672
+ unknown,
1673
+ );
1674
+ }
1675
+ if (
1676
+ this.commands.length &&
1677
+ this.args.length === 0 &&
1678
+ !this._actionHandler &&
1679
+ !this._defaultCommandName
1680
+ ) {
1681
+ // probably missing subcommand and no handler, user needs help (and exit)
1682
+ this.help({ error: true });
1683
+ }
1684
+
1685
+ this._outputHelpIfRequested(parsed.unknown);
1686
+ this._checkForMissingMandatoryOptions();
1687
+ this._checkForConflictingOptions();
1688
+
1689
+ // We do not always call this check to avoid masking a "better" error, like unknown command.
1690
+ const checkForUnknownOptions = () => {
1691
+ if (parsed.unknown.length > 0) {
1692
+ this.unknownOption(parsed.unknown[0]);
1693
+ }
1694
+ };
1695
+
1696
+ const commandEvent = `command:${this.name()}`;
1697
+ if (this._actionHandler) {
1698
+ checkForUnknownOptions();
1699
+ this._processArguments();
1700
+
1701
+ let promiseChain;
1702
+ promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
1703
+ promiseChain = this._chainOrCall(promiseChain, () =>
1704
+ this._actionHandler(this.processedArgs),
1705
+ );
1706
+ if (this.parent) {
1707
+ promiseChain = this._chainOrCall(promiseChain, () => {
1708
+ this.parent.emit(commandEvent, operands, unknown); // legacy
1709
+ });
1710
+ }
1711
+ promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
1712
+ return promiseChain;
1713
+ }
1714
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
1715
+ checkForUnknownOptions();
1716
+ this._processArguments();
1717
+ this.parent.emit(commandEvent, operands, unknown); // legacy
1718
+ } else if (operands.length) {
1719
+ if (this._findCommand('*')) {
1720
+ // legacy default command
1721
+ return this._dispatchSubcommand('*', operands, unknown);
1722
+ }
1723
+ if (this.listenerCount('command:*')) {
1724
+ // skip option check, emit event for possible misspelling suggestion
1725
+ this.emit('command:*', operands, unknown);
1726
+ } else if (this.commands.length) {
1727
+ this.unknownCommand();
1728
+ } else {
1729
+ checkForUnknownOptions();
1730
+ this._processArguments();
1731
+ }
1732
+ } else if (this.commands.length) {
1733
+ checkForUnknownOptions();
1734
+ // This command has subcommands and nothing hooked up at this level, so display help (and exit).
1735
+ this.help({ error: true });
1736
+ } else {
1737
+ checkForUnknownOptions();
1738
+ this._processArguments();
1739
+ // fall through for caller to handle after calling .parse()
1740
+ }
1741
+ }
1742
+
1743
+ /**
1744
+ * Find matching command.
1745
+ *
1746
+ * @private
1747
+ * @return {Command | undefined}
1748
+ */
1749
+ _findCommand(name) {
1750
+ if (!name) return undefined;
1751
+ return this.commands.find(
1752
+ (cmd) => cmd._name === name || cmd._aliases.includes(name),
1753
+ );
1754
+ }
1755
+
1756
+ /**
1757
+ * Return an option matching `arg` if any.
1758
+ *
1759
+ * @param {string} arg
1760
+ * @return {Option}
1761
+ * @package
1762
+ */
1763
+
1764
+ _findOption(arg) {
1765
+ return this.options.find((option) => option.is(arg));
1766
+ }
1767
+
1768
+ /**
1769
+ * Display an error message if a mandatory option does not have a value.
1770
+ * Called after checking for help flags in leaf subcommand.
1771
+ *
1772
+ * @private
1773
+ */
1774
+
1775
+ _checkForMissingMandatoryOptions() {
1776
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
1777
+ this._getCommandAndAncestors().forEach((cmd) => {
1778
+ cmd.options.forEach((anOption) => {
1779
+ if (
1780
+ anOption.mandatory &&
1781
+ cmd.getOptionValue(anOption.attributeName()) === undefined
1782
+ ) {
1783
+ cmd.missingMandatoryOptionValue(anOption);
1784
+ }
1785
+ });
1786
+ });
1787
+ }
1788
+
1789
+ /**
1790
+ * Display an error message if conflicting options are used together in this.
1791
+ *
1792
+ * @private
1793
+ */
1794
+ _checkForConflictingLocalOptions() {
1795
+ const definedNonDefaultOptions = this.options.filter((option) => {
1796
+ const optionKey = option.attributeName();
1797
+ if (this.getOptionValue(optionKey) === undefined) {
1798
+ return false;
1799
+ }
1800
+ return this.getOptionValueSource(optionKey) !== 'default';
1801
+ });
1802
+
1803
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
1804
+ (option) => option.conflictsWith.length > 0,
1805
+ );
1806
+
1807
+ optionsWithConflicting.forEach((option) => {
1808
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>
1809
+ option.conflictsWith.includes(defined.attributeName()),
1810
+ );
1811
+ if (conflictingAndDefined) {
1812
+ this._conflictingOption(option, conflictingAndDefined);
1813
+ }
1814
+ });
1815
+ }
1816
+
1817
+ /**
1818
+ * Display an error message if conflicting options are used together.
1819
+ * Called after checking for help flags in leaf subcommand.
1820
+ *
1821
+ * @private
1822
+ */
1823
+ _checkForConflictingOptions() {
1824
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
1825
+ this._getCommandAndAncestors().forEach((cmd) => {
1826
+ cmd._checkForConflictingLocalOptions();
1827
+ });
1828
+ }
1829
+
1830
+ /**
1831
+ * Parse options from `argv` removing known options,
1832
+ * and return argv split into operands and unknown arguments.
1833
+ *
1834
+ * Examples:
1835
+ *
1836
+ * argv => operands, unknown
1837
+ * --known kkk op => [op], []
1838
+ * op --known kkk => [op], []
1839
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
1840
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
1841
+ *
1842
+ * @param {string[]} argv
1843
+ * @return {{operands: string[], unknown: string[]}}
1844
+ */
1845
+
1846
+ parseOptions(argv) {
1847
+ const operands = []; // operands, not options or values
1848
+ const unknown = []; // first unknown option and remaining unknown args
1849
+ let dest = operands;
1850
+ const args = argv.slice();
1851
+
1852
+ function maybeOption(arg) {
1853
+ return arg.length > 1 && arg[0] === '-';
1854
+ }
1855
+
1856
+ // parse options
1857
+ let activeVariadicOption = null;
1858
+ while (args.length) {
1859
+ const arg = args.shift();
1860
+
1861
+ // literal
1862
+ if (arg === '--') {
1863
+ if (dest === unknown) dest.push(arg);
1864
+ dest.push(...args);
1865
+ break;
1866
+ }
1867
+
1868
+ if (activeVariadicOption && !maybeOption(arg)) {
1869
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1870
+ continue;
1871
+ }
1872
+ activeVariadicOption = null;
1873
+
1874
+ if (maybeOption(arg)) {
1875
+ const option = this._findOption(arg);
1876
+ // recognised option, call listener to assign value with possible custom processing
1877
+ if (option) {
1878
+ if (option.required) {
1879
+ const value = args.shift();
1880
+ if (value === undefined) this.optionMissingArgument(option);
1881
+ this.emit(`option:${option.name()}`, value);
1882
+ } else if (option.optional) {
1883
+ let value = null;
1884
+ // historical behaviour is optional value is following arg unless an option
1885
+ if (args.length > 0 && !maybeOption(args[0])) {
1886
+ value = args.shift();
1887
+ }
1888
+ this.emit(`option:${option.name()}`, value);
1889
+ } else {
1890
+ // boolean flag
1891
+ this.emit(`option:${option.name()}`);
1892
+ }
1893
+ activeVariadicOption = option.variadic ? option : null;
1894
+ continue;
1895
+ }
1896
+ }
1897
+
1898
+ // Look for combo options following single dash, eat first one if known.
1899
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
1900
+ const option = this._findOption(`-${arg[1]}`);
1901
+ if (option) {
1902
+ if (
1903
+ option.required ||
1904
+ (option.optional && this._combineFlagAndOptionalValue)
1905
+ ) {
1906
+ // option with value following in same argument
1907
+ this.emit(`option:${option.name()}`, arg.slice(2));
1908
+ } else {
1909
+ // boolean option, emit and put back remainder of arg for further processing
1910
+ this.emit(`option:${option.name()}`);
1911
+ args.unshift(`-${arg.slice(2)}`);
1912
+ }
1913
+ continue;
1914
+ }
1915
+ }
1916
+
1917
+ // Look for known long flag with value, like --foo=bar
1918
+ if (/^--[^=]+=/.test(arg)) {
1919
+ const index = arg.indexOf('=');
1920
+ const option = this._findOption(arg.slice(0, index));
1921
+ if (option && (option.required || option.optional)) {
1922
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1923
+ continue;
1924
+ }
1925
+ }
1926
+
1927
+ // Not a recognised option by this command.
1928
+ // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
1929
+
1930
+ // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
1931
+ if (maybeOption(arg)) {
1932
+ dest = unknown;
1933
+ }
1934
+
1935
+ // If using positionalOptions, stop processing our options at subcommand.
1936
+ if (
1937
+ (this._enablePositionalOptions || this._passThroughOptions) &&
1938
+ operands.length === 0 &&
1939
+ unknown.length === 0
1940
+ ) {
1941
+ if (this._findCommand(arg)) {
1942
+ operands.push(arg);
1943
+ if (args.length > 0) unknown.push(...args);
1944
+ break;
1945
+ } else if (
1946
+ this._getHelpCommand() &&
1947
+ arg === this._getHelpCommand().name()
1948
+ ) {
1949
+ operands.push(arg);
1950
+ if (args.length > 0) operands.push(...args);
1951
+ break;
1952
+ } else if (this._defaultCommandName) {
1953
+ unknown.push(arg);
1954
+ if (args.length > 0) unknown.push(...args);
1955
+ break;
1956
+ }
1957
+ }
1958
+
1959
+ // If using passThroughOptions, stop processing options at first command-argument.
1960
+ if (this._passThroughOptions) {
1961
+ dest.push(arg);
1962
+ if (args.length > 0) dest.push(...args);
1963
+ break;
1964
+ }
1965
+
1966
+ // add arg
1967
+ dest.push(arg);
1968
+ }
1969
+
1970
+ return { operands, unknown };
1971
+ }
1972
+
1973
+ /**
1974
+ * Return an object containing local option values as key-value pairs.
1975
+ *
1976
+ * @return {object}
1977
+ */
1978
+ opts() {
1979
+ if (this._storeOptionsAsProperties) {
1980
+ // Preserve original behaviour so backwards compatible when still using properties
1981
+ const result = {};
1982
+ const len = this.options.length;
1983
+
1984
+ for (let i = 0; i < len; i++) {
1985
+ const key = this.options[i].attributeName();
1986
+ result[key] =
1987
+ key === this._versionOptionName ? this._version : this[key];
1988
+ }
1989
+ return result;
1990
+ }
1991
+
1992
+ return this._optionValues;
1993
+ }
1994
+
1995
+ /**
1996
+ * Return an object containing merged local and global option values as key-value pairs.
1997
+ *
1998
+ * @return {object}
1999
+ */
2000
+ optsWithGlobals() {
2001
+ // globals overwrite locals
2002
+ return this._getCommandAndAncestors().reduce(
2003
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2004
+ {},
2005
+ );
2006
+ }
2007
+
2008
+ /**
2009
+ * Display error message and exit (or call exitOverride).
2010
+ *
2011
+ * @param {string} message
2012
+ * @param {object} [errorOptions]
2013
+ * @param {string} [errorOptions.code] - an id string representing the error
2014
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2015
+ */
2016
+ error(message, errorOptions) {
2017
+ // output handling
2018
+ this._outputConfiguration.outputError(
2019
+ `${message}\n`,
2020
+ this._outputConfiguration.writeErr,
2021
+ );
2022
+ if (typeof this._showHelpAfterError === 'string') {
2023
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2024
+ } else if (this._showHelpAfterError) {
2025
+ this._outputConfiguration.writeErr('\n');
2026
+ this.outputHelp({ error: true });
2027
+ }
2028
+
2029
+ // exit handling
2030
+ const config = errorOptions || {};
2031
+ const exitCode = config.exitCode || 1;
2032
+ const code = config.code || 'commander.error';
2033
+ this._exit(exitCode, code, message);
2034
+ }
2035
+
2036
+ /**
2037
+ * Apply any option related environment variables, if option does
2038
+ * not have a value from cli or client code.
2039
+ *
2040
+ * @private
2041
+ */
2042
+ _parseOptionsEnv() {
2043
+ this.options.forEach((option) => {
2044
+ if (option.envVar && option.envVar in process.env) {
2045
+ const optionKey = option.attributeName();
2046
+ // Priority check. Do not overwrite cli or options from unknown source (client-code).
2047
+ if (
2048
+ this.getOptionValue(optionKey) === undefined ||
2049
+ ['default', 'config', 'env'].includes(
2050
+ this.getOptionValueSource(optionKey),
2051
+ )
2052
+ ) {
2053
+ if (option.required || option.optional) {
2054
+ // option can take a value
2055
+ // keep very simple, optional always takes value
2056
+ this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
2057
+ } else {
2058
+ // boolean
2059
+ // keep very simple, only care that envVar defined and not the value
2060
+ this.emit(`optionEnv:${option.name()}`);
2061
+ }
2062
+ }
2063
+ }
2064
+ });
2065
+ }
2066
+
2067
+ /**
2068
+ * Apply any implied option values, if option is undefined or default value.
2069
+ *
2070
+ * @private
2071
+ */
2072
+ _parseOptionsImplied() {
2073
+ const dualHelper = new DualOptions(this.options);
2074
+ const hasCustomOptionValue = (optionKey) => {
2075
+ return (
2076
+ this.getOptionValue(optionKey) !== undefined &&
2077
+ !['default', 'implied'].includes(this.getOptionValueSource(optionKey))
2078
+ );
2079
+ };
2080
+ this.options
2081
+ .filter(
2082
+ (option) =>
2083
+ option.implied !== undefined &&
2084
+ hasCustomOptionValue(option.attributeName()) &&
2085
+ dualHelper.valueFromOption(
2086
+ this.getOptionValue(option.attributeName()),
2087
+ option,
2088
+ ),
2089
+ )
2090
+ .forEach((option) => {
2091
+ Object.keys(option.implied)
2092
+ .filter((impliedKey) => !hasCustomOptionValue(impliedKey))
2093
+ .forEach((impliedKey) => {
2094
+ this.setOptionValueWithSource(
2095
+ impliedKey,
2096
+ option.implied[impliedKey],
2097
+ 'implied',
2098
+ );
2099
+ });
2100
+ });
2101
+ }
2102
+
2103
+ /**
2104
+ * Argument `name` is missing.
2105
+ *
2106
+ * @param {string} name
2107
+ * @private
2108
+ */
2109
+
2110
+ missingArgument(name) {
2111
+ const message = `error: missing required argument '${name}'`;
2112
+ this.error(message, { code: 'commander.missingArgument' });
2113
+ }
2114
+
2115
+ /**
2116
+ * `Option` is missing an argument.
2117
+ *
2118
+ * @param {Option} option
2119
+ * @private
2120
+ */
2121
+
2122
+ optionMissingArgument(option) {
2123
+ const message = `error: option '${option.flags}' argument missing`;
2124
+ this.error(message, { code: 'commander.optionMissingArgument' });
2125
+ }
2126
+
2127
+ /**
2128
+ * `Option` does not have a value, and is a mandatory option.
2129
+ *
2130
+ * @param {Option} option
2131
+ * @private
2132
+ */
2133
+
2134
+ missingMandatoryOptionValue(option) {
2135
+ const message = `error: required option '${option.flags}' not specified`;
2136
+ this.error(message, { code: 'commander.missingMandatoryOptionValue' });
2137
+ }
2138
+
2139
+ /**
2140
+ * `Option` conflicts with another option.
2141
+ *
2142
+ * @param {Option} option
2143
+ * @param {Option} conflictingOption
2144
+ * @private
2145
+ */
2146
+ _conflictingOption(option, conflictingOption) {
2147
+ // The calling code does not know whether a negated option is the source of the
2148
+ // value, so do some work to take an educated guess.
2149
+ const findBestOptionFromValue = (option) => {
2150
+ const optionKey = option.attributeName();
2151
+ const optionValue = this.getOptionValue(optionKey);
2152
+ const negativeOption = this.options.find(
2153
+ (target) => target.negate && optionKey === target.attributeName(),
2154
+ );
2155
+ const positiveOption = this.options.find(
2156
+ (target) => !target.negate && optionKey === target.attributeName(),
2157
+ );
2158
+ if (
2159
+ negativeOption &&
2160
+ ((negativeOption.presetArg === undefined && optionValue === false) ||
2161
+ (negativeOption.presetArg !== undefined &&
2162
+ optionValue === negativeOption.presetArg))
2163
+ ) {
2164
+ return negativeOption;
2165
+ }
2166
+ return positiveOption || option;
2167
+ };
2168
+
2169
+ const getErrorMessage = (option) => {
2170
+ const bestOption = findBestOptionFromValue(option);
2171
+ const optionKey = bestOption.attributeName();
2172
+ const source = this.getOptionValueSource(optionKey);
2173
+ if (source === 'env') {
2174
+ return `environment variable '${bestOption.envVar}'`;
2175
+ }
2176
+ return `option '${bestOption.flags}'`;
2177
+ };
2178
+
2179
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2180
+ this.error(message, { code: 'commander.conflictingOption' });
2181
+ }
2182
+
2183
+ /**
2184
+ * Unknown option `flag`.
2185
+ *
2186
+ * @param {string} flag
2187
+ * @private
2188
+ */
2189
+
2190
+ unknownOption(flag) {
2191
+ if (this._allowUnknownOption) return;
2192
+ let suggestion = '';
2193
+
2194
+ if (flag.startsWith('--') && this._showSuggestionAfterError) {
2195
+ // Looping to pick up the global options too
2196
+ let candidateFlags = [];
2197
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
2198
+ let command = this;
2199
+ do {
2200
+ const moreFlags = command
2201
+ .createHelp()
2202
+ .visibleOptions(command)
2203
+ .filter((option) => option.long)
2204
+ .map((option) => option.long);
2205
+ candidateFlags = candidateFlags.concat(moreFlags);
2206
+ command = command.parent;
2207
+ } while (command && !command._enablePositionalOptions);
2208
+ suggestion = suggestSimilar(flag, candidateFlags);
2209
+ }
2210
+
2211
+ const message = `error: unknown option '${flag}'${suggestion}`;
2212
+ this.error(message, { code: 'commander.unknownOption' });
2213
+ }
2214
+
2215
+ /**
2216
+ * Excess arguments, more than expected.
2217
+ *
2218
+ * @param {string[]} receivedArgs
2219
+ * @private
2220
+ */
2221
+
2222
+ _excessArguments(receivedArgs) {
2223
+ if (this._allowExcessArguments) return;
2224
+
2225
+ const expected = this.registeredArguments.length;
2226
+ const s = expected === 1 ? '' : 's';
2227
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
2228
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2229
+ this.error(message, { code: 'commander.excessArguments' });
2230
+ }
2231
+
2232
+ /**
2233
+ * Unknown command.
2234
+ *
2235
+ * @private
2236
+ */
2237
+
2238
+ unknownCommand() {
2239
+ const unknownName = this.args[0];
2240
+ let suggestion = '';
2241
+
2242
+ if (this._showSuggestionAfterError) {
2243
+ const candidateNames = [];
2244
+ this.createHelp()
2245
+ .visibleCommands(this)
2246
+ .forEach((command) => {
2247
+ candidateNames.push(command.name());
2248
+ // just visible alias
2249
+ if (command.alias()) candidateNames.push(command.alias());
2250
+ });
2251
+ suggestion = suggestSimilar(unknownName, candidateNames);
2252
+ }
2253
+
2254
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2255
+ this.error(message, { code: 'commander.unknownCommand' });
2256
+ }
2257
+
2258
+ /**
2259
+ * Get or set the program version.
2260
+ *
2261
+ * This method auto-registers the "-V, --version" option which will print the version number.
2262
+ *
2263
+ * You can optionally supply the flags and description to override the defaults.
2264
+ *
2265
+ * @param {string} [str]
2266
+ * @param {string} [flags]
2267
+ * @param {string} [description]
2268
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2269
+ */
2270
+
2271
+ version(str, flags, description) {
2272
+ if (str === undefined) return this._version;
2273
+ this._version = str;
2274
+ flags = flags || '-V, --version';
2275
+ description = description || 'output the version number';
2276
+ const versionOption = this.createOption(flags, description);
2277
+ this._versionOptionName = versionOption.attributeName();
2278
+ this._registerOption(versionOption);
2279
+
2280
+ this.on('option:' + versionOption.name(), () => {
2281
+ this._outputConfiguration.writeOut(`${str}\n`);
2282
+ this._exit(0, 'commander.version', str);
2283
+ });
2284
+ return this;
2285
+ }
2286
+
2287
+ /**
2288
+ * Set the description.
2289
+ *
2290
+ * @param {string} [str]
2291
+ * @param {object} [argsDescription]
2292
+ * @return {(string|Command)}
2293
+ */
2294
+ description(str, argsDescription) {
2295
+ if (str === undefined && argsDescription === undefined)
2296
+ return this._description;
2297
+ this._description = str;
2298
+ if (argsDescription) {
2299
+ this._argsDescription = argsDescription;
2300
+ }
2301
+ return this;
2302
+ }
2303
+
2304
+ /**
2305
+ * Set the summary. Used when listed as subcommand of parent.
2306
+ *
2307
+ * @param {string} [str]
2308
+ * @return {(string|Command)}
2309
+ */
2310
+ summary(str) {
2311
+ if (str === undefined) return this._summary;
2312
+ this._summary = str;
2313
+ return this;
2314
+ }
2315
+
2316
+ /**
2317
+ * Set an alias for the command.
2318
+ *
2319
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2320
+ *
2321
+ * @param {string} [alias]
2322
+ * @return {(string|Command)}
2323
+ */
2324
+
2325
+ alias(alias) {
2326
+ if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
2327
+
2328
+ /** @type {Command} */
2329
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
2330
+ let command = this;
2331
+ if (
2332
+ this.commands.length !== 0 &&
2333
+ this.commands[this.commands.length - 1]._executableHandler
2334
+ ) {
2335
+ // assume adding alias for last added executable subcommand, rather than this
2336
+ command = this.commands[this.commands.length - 1];
2337
+ }
2338
+
2339
+ if (alias === command._name)
2340
+ throw new Error("Command alias can't be the same as its name");
2341
+ const matchingCommand = this.parent?._findCommand(alias);
2342
+ if (matchingCommand) {
2343
+ // c.f. _registerCommand
2344
+ const existingCmd = [matchingCommand.name()]
2345
+ .concat(matchingCommand.aliases())
2346
+ .join('|');
2347
+ throw new Error(
2348
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,
2349
+ );
2350
+ }
2351
+
2352
+ command._aliases.push(alias);
2353
+ return this;
2354
+ }
2355
+
2356
+ /**
2357
+ * Set aliases for the command.
2358
+ *
2359
+ * Only the first alias is shown in the auto-generated help.
2360
+ *
2361
+ * @param {string[]} [aliases]
2362
+ * @return {(string[]|Command)}
2363
+ */
2364
+
2365
+ aliases(aliases) {
2366
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
2367
+ if (aliases === undefined) return this._aliases;
2368
+
2369
+ aliases.forEach((alias) => this.alias(alias));
2370
+ return this;
2371
+ }
2372
+
2373
+ /**
2374
+ * Set / get the command usage `str`.
2375
+ *
2376
+ * @param {string} [str]
2377
+ * @return {(string|Command)}
2378
+ */
2379
+
2380
+ usage(str) {
2381
+ if (str === undefined) {
2382
+ if (this._usage) return this._usage;
2383
+
2384
+ const args = this.registeredArguments.map((arg) => {
2385
+ return humanReadableArgName(arg);
2386
+ });
2387
+ return []
2388
+ .concat(
2389
+ this.options.length || this._helpOption !== null ? '[options]' : [],
2390
+ this.commands.length ? '[command]' : [],
2391
+ this.registeredArguments.length ? args : [],
2392
+ )
2393
+ .join(' ');
2394
+ }
2395
+
2396
+ this._usage = str;
2397
+ return this;
2398
+ }
2399
+
2400
+ /**
2401
+ * Get or set the name of the command.
2402
+ *
2403
+ * @param {string} [str]
2404
+ * @return {(string|Command)}
2405
+ */
2406
+
2407
+ name(str) {
2408
+ if (str === undefined) return this._name;
2409
+ this._name = str;
2410
+ return this;
2411
+ }
2412
+
2413
+ /**
2414
+ * Set the name of the command from script filename, such as process.argv[1],
2415
+ * or require.main.filename, or __filename.
2416
+ *
2417
+ * (Used internally and public although not documented in README.)
2418
+ *
2419
+ * @example
2420
+ * program.nameFromFilename(require.main.filename);
2421
+ *
2422
+ * @param {string} filename
2423
+ * @return {Command}
2424
+ */
2425
+
2426
+ nameFromFilename(filename) {
2427
+ this._name = path.basename(filename, path.extname(filename));
2428
+
2429
+ return this;
2430
+ }
2431
+
2432
+ /**
2433
+ * Get or set the directory for searching for executable subcommands of this command.
2434
+ *
2435
+ * @example
2436
+ * program.executableDir(__dirname);
2437
+ * // or
2438
+ * program.executableDir('subcommands');
2439
+ *
2440
+ * @param {string} [path]
2441
+ * @return {(string|null|Command)}
2442
+ */
2443
+
2444
+ executableDir(path) {
2445
+ if (path === undefined) return this._executableDir;
2446
+ this._executableDir = path;
2447
+ return this;
2448
+ }
2449
+
2450
+ /**
2451
+ * Return program help documentation.
2452
+ *
2453
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2454
+ * @return {string}
2455
+ */
2456
+
2457
+ helpInformation(contextOptions) {
2458
+ const helper = this.createHelp();
2459
+ if (helper.helpWidth === undefined) {
2460
+ helper.helpWidth =
2461
+ contextOptions && contextOptions.error
2462
+ ? this._outputConfiguration.getErrHelpWidth()
2463
+ : this._outputConfiguration.getOutHelpWidth();
2464
+ }
2465
+ return helper.formatHelp(this, helper);
2466
+ }
2467
+
2468
+ /**
2469
+ * @private
2470
+ */
2471
+
2472
+ _getHelpContext(contextOptions) {
2473
+ contextOptions = contextOptions || {};
2474
+ const context = { error: !!contextOptions.error };
2475
+ let write;
2476
+ if (context.error) {
2477
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2478
+ } else {
2479
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2480
+ }
2481
+ context.write = contextOptions.write || write;
2482
+ context.command = this;
2483
+ return context;
2484
+ }
2485
+
2486
+ /**
2487
+ * Output help information for this command.
2488
+ *
2489
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2490
+ *
2491
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2492
+ */
2493
+
2494
+ outputHelp(contextOptions) {
2495
+ let deprecatedCallback;
2496
+ if (typeof contextOptions === 'function') {
2497
+ deprecatedCallback = contextOptions;
2498
+ contextOptions = undefined;
2499
+ }
2500
+ const context = this._getHelpContext(contextOptions);
2501
+
2502
+ this._getCommandAndAncestors()
2503
+ .reverse()
2504
+ .forEach((command) => command.emit('beforeAllHelp', context));
2505
+ this.emit('beforeHelp', context);
2506
+
2507
+ let helpInformation = this.helpInformation(context);
2508
+ if (deprecatedCallback) {
2509
+ helpInformation = deprecatedCallback(helpInformation);
2510
+ if (
2511
+ typeof helpInformation !== 'string' &&
2512
+ !Buffer.isBuffer(helpInformation)
2513
+ ) {
2514
+ throw new Error('outputHelp callback must return a string or a Buffer');
2515
+ }
2516
+ }
2517
+ context.write(helpInformation);
2518
+
2519
+ if (this._getHelpOption()?.long) {
2520
+ this.emit(this._getHelpOption().long); // deprecated
2521
+ }
2522
+ this.emit('afterHelp', context);
2523
+ this._getCommandAndAncestors().forEach((command) =>
2524
+ command.emit('afterAllHelp', context),
2525
+ );
2526
+ }
2527
+
2528
+ /**
2529
+ * You can pass in flags and a description to customise the built-in help option.
2530
+ * Pass in false to disable the built-in help option.
2531
+ *
2532
+ * @example
2533
+ * program.helpOption('-?, --help' 'show help'); // customise
2534
+ * program.helpOption(false); // disable
2535
+ *
2536
+ * @param {(string | boolean)} flags
2537
+ * @param {string} [description]
2538
+ * @return {Command} `this` command for chaining
2539
+ */
2540
+
2541
+ helpOption(flags, description) {
2542
+ // Support disabling built-in help option.
2543
+ if (typeof flags === 'boolean') {
2544
+ if (flags) {
2545
+ this._helpOption = this._helpOption ?? undefined; // preserve existing option
2546
+ } else {
2547
+ this._helpOption = null; // disable
2548
+ }
2549
+ return this;
2550
+ }
2551
+
2552
+ // Customise flags and description.
2553
+ flags = flags ?? '-h, --help';
2554
+ description = description ?? 'display help for command';
2555
+ this._helpOption = this.createOption(flags, description);
2556
+
2557
+ return this;
2558
+ }
2559
+
2560
+ /**
2561
+ * Lazy create help option.
2562
+ * Returns null if has been disabled with .helpOption(false).
2563
+ *
2564
+ * @returns {(Option | null)} the help option
2565
+ * @package
2566
+ */
2567
+ _getHelpOption() {
2568
+ // Lazy create help option on demand.
2569
+ if (this._helpOption === undefined) {
2570
+ this.helpOption(undefined, undefined);
2571
+ }
2572
+ return this._helpOption;
2573
+ }
2574
+
2575
+ /**
2576
+ * Supply your own option to use for the built-in help option.
2577
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2578
+ *
2579
+ * @param {Option} option
2580
+ * @return {Command} `this` command for chaining
2581
+ */
2582
+ addHelpOption(option) {
2583
+ this._helpOption = option;
2584
+ return this;
2585
+ }
2586
+
2587
+ /**
2588
+ * Output help information and exit.
2589
+ *
2590
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2591
+ *
2592
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2593
+ */
2594
+
2595
+ help(contextOptions) {
2596
+ this.outputHelp(contextOptions);
2597
+ let exitCode = process.exitCode || 0;
2598
+ if (
2599
+ exitCode === 0 &&
2600
+ contextOptions &&
2601
+ typeof contextOptions !== 'function' &&
2602
+ contextOptions.error
2603
+ ) {
2604
+ exitCode = 1;
2605
+ }
2606
+ // message: do not have all displayed text available so only passing placeholder.
2607
+ this._exit(exitCode, 'commander.help', '(outputHelp)');
2608
+ }
2609
+
2610
+ /**
2611
+ * Add additional text to be displayed with the built-in help.
2612
+ *
2613
+ * Position is 'before' or 'after' to affect just this command,
2614
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2615
+ *
2616
+ * @param {string} position - before or after built-in help
2617
+ * @param {(string | Function)} text - string to add, or a function returning a string
2618
+ * @return {Command} `this` command for chaining
2619
+ */
2620
+ addHelpText(position, text) {
2621
+ const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
2622
+ if (!allowedValues.includes(position)) {
2623
+ throw new Error(`Unexpected value for position to addHelpText.
2624
+ Expecting one of '${allowedValues.join("', '")}'`);
2625
+ }
2626
+ const helpEvent = `${position}Help`;
2627
+ this.on(helpEvent, (context) => {
2628
+ let helpStr;
2629
+ if (typeof text === 'function') {
2630
+ helpStr = text({ error: context.error, command: context.command });
2631
+ } else {
2632
+ helpStr = text;
2633
+ }
2634
+ // Ignore falsy value when nothing to output.
2635
+ if (helpStr) {
2636
+ context.write(`${helpStr}\n`);
2637
+ }
2638
+ });
2639
+ return this;
2640
+ }
2641
+
2642
+ /**
2643
+ * Output help information if help flags specified
2644
+ *
2645
+ * @param {Array} args - array of options to search for help flags
2646
+ * @private
2647
+ */
2648
+
2649
+ _outputHelpIfRequested(args) {
2650
+ const helpOption = this._getHelpOption();
2651
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2652
+ if (helpRequested) {
2653
+ this.outputHelp();
2654
+ // (Do not have all displayed text available so only passing placeholder.)
2655
+ this._exit(0, 'commander.helpDisplayed', '(outputHelp)');
2656
+ }
2657
+ }
2658
+ }
2659
+
2660
+ /**
2661
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2662
+ *
2663
+ * @param {string[]} args - array of arguments from node.execArgv
2664
+ * @returns {string[]}
2665
+ * @private
2666
+ */
2667
+
2668
+ function incrementNodeInspectorPort(args) {
2669
+ // Testing for these options:
2670
+ // --inspect[=[host:]port]
2671
+ // --inspect-brk[=[host:]port]
2672
+ // --inspect-port=[host:]port
2673
+ return args.map((arg) => {
2674
+ if (!arg.startsWith('--inspect')) {
2675
+ return arg;
2676
+ }
2677
+ let debugOption;
2678
+ let debugHost = '127.0.0.1';
2679
+ let debugPort = '9229';
2680
+ let match;
2681
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2682
+ // e.g. --inspect
2683
+ debugOption = match[1];
2684
+ } else if (
2685
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null
2686
+ ) {
2687
+ debugOption = match[1];
2688
+ if (/^\d+$/.test(match[3])) {
2689
+ // e.g. --inspect=1234
2690
+ debugPort = match[3];
2691
+ } else {
2692
+ // e.g. --inspect=localhost
2693
+ debugHost = match[3];
2694
+ }
2695
+ } else if (
2696
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null
2697
+ ) {
2698
+ // e.g. --inspect=localhost:1234
2699
+ debugOption = match[1];
2700
+ debugHost = match[3];
2701
+ debugPort = match[4];
2702
+ }
2703
+
2704
+ if (debugOption && debugPort !== '0') {
2705
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2706
+ }
2707
+ return arg;
2708
+ });
2709
+ }
2710
+
2711
+ exports.Command = Command;
2712
+
2713
+
2714
+ /***/ }),
2715
+
2716
+ /***/ 829:
2717
+ /***/ ((__unused_webpack_module, exports) => {
2718
+
2719
+ /**
2720
+ * CommanderError class
2721
+ */
2722
+ class CommanderError extends Error {
2723
+ /**
2724
+ * Constructs the CommanderError class
2725
+ * @param {number} exitCode suggested exit code which could be used with process.exit
2726
+ * @param {string} code an id string representing the error
2727
+ * @param {string} message human-readable description of the error
2728
+ */
2729
+ constructor(exitCode, code, message) {
2730
+ super(message);
2731
+ // properly capture stack trace in Node.js
2732
+ Error.captureStackTrace(this, this.constructor);
2733
+ this.name = this.constructor.name;
2734
+ this.code = code;
2735
+ this.exitCode = exitCode;
2736
+ this.nestedError = undefined;
2737
+ }
2738
+ }
2739
+
2740
+ /**
2741
+ * InvalidArgumentError class
2742
+ */
2743
+ class InvalidArgumentError extends CommanderError {
2744
+ /**
2745
+ * Constructs the InvalidArgumentError class
2746
+ * @param {string} [message] explanation of why argument is invalid
2747
+ */
2748
+ constructor(message) {
2749
+ super(1, 'commander.invalidArgument', message);
2750
+ // properly capture stack trace in Node.js
2751
+ Error.captureStackTrace(this, this.constructor);
2752
+ this.name = this.constructor.name;
2753
+ }
2754
+ }
2755
+
2756
+ exports.CommanderError = CommanderError;
2757
+ exports.InvalidArgumentError = InvalidArgumentError;
2758
+
2759
+
2760
+ /***/ }),
2761
+
2762
+ /***/ 567:
2763
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
2764
+
2765
+ const { humanReadableArgName } = __nccwpck_require__(654);
2766
+
2767
+ /**
2768
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
2769
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
2770
+ * @typedef { import("./argument.js").Argument } Argument
2771
+ * @typedef { import("./command.js").Command } Command
2772
+ * @typedef { import("./option.js").Option } Option
2773
+ */
2774
+
2775
+ // Although this is a class, methods are static in style to allow override using subclass or just functions.
2776
+ class Help {
2777
+ constructor() {
2778
+ this.helpWidth = undefined;
2779
+ this.sortSubcommands = false;
2780
+ this.sortOptions = false;
2781
+ this.showGlobalOptions = false;
2782
+ }
2783
+
2784
+ /**
2785
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
2786
+ *
2787
+ * @param {Command} cmd
2788
+ * @returns {Command[]}
2789
+ */
2790
+
2791
+ visibleCommands(cmd) {
2792
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
2793
+ const helpCommand = cmd._getHelpCommand();
2794
+ if (helpCommand && !helpCommand._hidden) {
2795
+ visibleCommands.push(helpCommand);
2796
+ }
2797
+ if (this.sortSubcommands) {
2798
+ visibleCommands.sort((a, b) => {
2799
+ // @ts-ignore: because overloaded return type
2800
+ return a.name().localeCompare(b.name());
2801
+ });
2802
+ }
2803
+ return visibleCommands;
2804
+ }
2805
+
2806
+ /**
2807
+ * Compare options for sort.
2808
+ *
2809
+ * @param {Option} a
2810
+ * @param {Option} b
2811
+ * @returns {number}
2812
+ */
2813
+ compareOptions(a, b) {
2814
+ const getSortKey = (option) => {
2815
+ // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
2816
+ return option.short
2817
+ ? option.short.replace(/^-/, '')
2818
+ : option.long.replace(/^--/, '');
2819
+ };
2820
+ return getSortKey(a).localeCompare(getSortKey(b));
2821
+ }
2822
+
2823
+ /**
2824
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
2825
+ *
2826
+ * @param {Command} cmd
2827
+ * @returns {Option[]}
2828
+ */
2829
+
2830
+ visibleOptions(cmd) {
2831
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
2832
+ // Built-in help option.
2833
+ const helpOption = cmd._getHelpOption();
2834
+ if (helpOption && !helpOption.hidden) {
2835
+ // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.
2836
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
2837
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
2838
+ if (!removeShort && !removeLong) {
2839
+ visibleOptions.push(helpOption); // no changes needed
2840
+ } else if (helpOption.long && !removeLong) {
2841
+ visibleOptions.push(
2842
+ cmd.createOption(helpOption.long, helpOption.description),
2843
+ );
2844
+ } else if (helpOption.short && !removeShort) {
2845
+ visibleOptions.push(
2846
+ cmd.createOption(helpOption.short, helpOption.description),
2847
+ );
2848
+ }
2849
+ }
2850
+ if (this.sortOptions) {
2851
+ visibleOptions.sort(this.compareOptions);
2852
+ }
2853
+ return visibleOptions;
2854
+ }
2855
+
2856
+ /**
2857
+ * Get an array of the visible global options. (Not including help.)
2858
+ *
2859
+ * @param {Command} cmd
2860
+ * @returns {Option[]}
2861
+ */
2862
+
2863
+ visibleGlobalOptions(cmd) {
2864
+ if (!this.showGlobalOptions) return [];
2865
+
2866
+ const globalOptions = [];
2867
+ for (
2868
+ let ancestorCmd = cmd.parent;
2869
+ ancestorCmd;
2870
+ ancestorCmd = ancestorCmd.parent
2871
+ ) {
2872
+ const visibleOptions = ancestorCmd.options.filter(
2873
+ (option) => !option.hidden,
2874
+ );
2875
+ globalOptions.push(...visibleOptions);
2876
+ }
2877
+ if (this.sortOptions) {
2878
+ globalOptions.sort(this.compareOptions);
2879
+ }
2880
+ return globalOptions;
2881
+ }
2882
+
2883
+ /**
2884
+ * Get an array of the arguments if any have a description.
2885
+ *
2886
+ * @param {Command} cmd
2887
+ * @returns {Argument[]}
2888
+ */
2889
+
2890
+ visibleArguments(cmd) {
2891
+ // Side effect! Apply the legacy descriptions before the arguments are displayed.
2892
+ if (cmd._argsDescription) {
2893
+ cmd.registeredArguments.forEach((argument) => {
2894
+ argument.description =
2895
+ argument.description || cmd._argsDescription[argument.name()] || '';
2896
+ });
2897
+ }
2898
+
2899
+ // If there are any arguments with a description then return all the arguments.
2900
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
2901
+ return cmd.registeredArguments;
2902
+ }
2903
+ return [];
2904
+ }
2905
+
2906
+ /**
2907
+ * Get the command term to show in the list of subcommands.
2908
+ *
2909
+ * @param {Command} cmd
2910
+ * @returns {string}
2911
+ */
2912
+
2913
+ subcommandTerm(cmd) {
2914
+ // Legacy. Ignores custom usage string, and nested commands.
2915
+ const args = cmd.registeredArguments
2916
+ .map((arg) => humanReadableArgName(arg))
2917
+ .join(' ');
2918
+ return (
2919
+ cmd._name +
2920
+ (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
2921
+ (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
2922
+ (args ? ' ' + args : '')
2923
+ );
2924
+ }
2925
+
2926
+ /**
2927
+ * Get the option term to show in the list of options.
2928
+ *
2929
+ * @param {Option} option
2930
+ * @returns {string}
2931
+ */
2932
+
2933
+ optionTerm(option) {
2934
+ return option.flags;
2935
+ }
2936
+
2937
+ /**
2938
+ * Get the argument term to show in the list of arguments.
2939
+ *
2940
+ * @param {Argument} argument
2941
+ * @returns {string}
2942
+ */
2943
+
2944
+ argumentTerm(argument) {
2945
+ return argument.name();
2946
+ }
2947
+
2948
+ /**
2949
+ * Get the longest command term length.
2950
+ *
2951
+ * @param {Command} cmd
2952
+ * @param {Help} helper
2953
+ * @returns {number}
2954
+ */
2955
+
2956
+ longestSubcommandTermLength(cmd, helper) {
2957
+ return helper.visibleCommands(cmd).reduce((max, command) => {
2958
+ return Math.max(max, helper.subcommandTerm(command).length);
2959
+ }, 0);
2960
+ }
2961
+
2962
+ /**
2963
+ * Get the longest option term length.
2964
+ *
2965
+ * @param {Command} cmd
2966
+ * @param {Help} helper
2967
+ * @returns {number}
2968
+ */
2969
+
2970
+ longestOptionTermLength(cmd, helper) {
2971
+ return helper.visibleOptions(cmd).reduce((max, option) => {
2972
+ return Math.max(max, helper.optionTerm(option).length);
2973
+ }, 0);
2974
+ }
2975
+
2976
+ /**
2977
+ * Get the longest global option term length.
2978
+ *
2979
+ * @param {Command} cmd
2980
+ * @param {Help} helper
2981
+ * @returns {number}
2982
+ */
2983
+
2984
+ longestGlobalOptionTermLength(cmd, helper) {
2985
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
2986
+ return Math.max(max, helper.optionTerm(option).length);
2987
+ }, 0);
2988
+ }
2989
+
2990
+ /**
2991
+ * Get the longest argument term length.
2992
+ *
2993
+ * @param {Command} cmd
2994
+ * @param {Help} helper
2995
+ * @returns {number}
2996
+ */
2997
+
2998
+ longestArgumentTermLength(cmd, helper) {
2999
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
3000
+ return Math.max(max, helper.argumentTerm(argument).length);
3001
+ }, 0);
3002
+ }
3003
+
3004
+ /**
3005
+ * Get the command usage to be displayed at the top of the built-in help.
3006
+ *
3007
+ * @param {Command} cmd
3008
+ * @returns {string}
3009
+ */
3010
+
3011
+ commandUsage(cmd) {
3012
+ // Usage
3013
+ let cmdName = cmd._name;
3014
+ if (cmd._aliases[0]) {
3015
+ cmdName = cmdName + '|' + cmd._aliases[0];
3016
+ }
3017
+ let ancestorCmdNames = '';
3018
+ for (
3019
+ let ancestorCmd = cmd.parent;
3020
+ ancestorCmd;
3021
+ ancestorCmd = ancestorCmd.parent
3022
+ ) {
3023
+ ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;
3024
+ }
3025
+ return ancestorCmdNames + cmdName + ' ' + cmd.usage();
3026
+ }
3027
+
3028
+ /**
3029
+ * Get the description for the command.
3030
+ *
3031
+ * @param {Command} cmd
3032
+ * @returns {string}
3033
+ */
3034
+
3035
+ commandDescription(cmd) {
3036
+ // @ts-ignore: because overloaded return type
3037
+ return cmd.description();
3038
+ }
3039
+
3040
+ /**
3041
+ * Get the subcommand summary to show in the list of subcommands.
3042
+ * (Fallback to description for backwards compatibility.)
3043
+ *
3044
+ * @param {Command} cmd
3045
+ * @returns {string}
3046
+ */
3047
+
3048
+ subcommandDescription(cmd) {
3049
+ // @ts-ignore: because overloaded return type
3050
+ return cmd.summary() || cmd.description();
3051
+ }
3052
+
3053
+ /**
3054
+ * Get the option description to show in the list of options.
3055
+ *
3056
+ * @param {Option} option
3057
+ * @return {string}
3058
+ */
3059
+
3060
+ optionDescription(option) {
3061
+ const extraInfo = [];
3062
+
3063
+ if (option.argChoices) {
3064
+ extraInfo.push(
3065
+ // use stringify to match the display of the default value
3066
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
3067
+ );
3068
+ }
3069
+ if (option.defaultValue !== undefined) {
3070
+ // default for boolean and negated more for programmer than end user,
3071
+ // but show true/false for boolean option as may be for hand-rolled env or config processing.
3072
+ const showDefault =
3073
+ option.required ||
3074
+ option.optional ||
3075
+ (option.isBoolean() && typeof option.defaultValue === 'boolean');
3076
+ if (showDefault) {
3077
+ extraInfo.push(
3078
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,
3079
+ );
3080
+ }
3081
+ }
3082
+ // preset for boolean and negated are more for programmer than end user
3083
+ if (option.presetArg !== undefined && option.optional) {
3084
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
3085
+ }
3086
+ if (option.envVar !== undefined) {
3087
+ extraInfo.push(`env: ${option.envVar}`);
3088
+ }
3089
+ if (extraInfo.length > 0) {
3090
+ return `${option.description} (${extraInfo.join(', ')})`;
3091
+ }
3092
+
3093
+ return option.description;
3094
+ }
3095
+
3096
+ /**
3097
+ * Get the argument description to show in the list of arguments.
3098
+ *
3099
+ * @param {Argument} argument
3100
+ * @return {string}
3101
+ */
3102
+
3103
+ argumentDescription(argument) {
3104
+ const extraInfo = [];
3105
+ if (argument.argChoices) {
3106
+ extraInfo.push(
3107
+ // use stringify to match the display of the default value
3108
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
3109
+ );
3110
+ }
3111
+ if (argument.defaultValue !== undefined) {
3112
+ extraInfo.push(
3113
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,
3114
+ );
3115
+ }
3116
+ if (extraInfo.length > 0) {
3117
+ const extraDescripton = `(${extraInfo.join(', ')})`;
3118
+ if (argument.description) {
3119
+ return `${argument.description} ${extraDescripton}`;
3120
+ }
3121
+ return extraDescripton;
3122
+ }
3123
+ return argument.description;
3124
+ }
3125
+
3126
+ /**
3127
+ * Generate the built-in help text.
3128
+ *
3129
+ * @param {Command} cmd
3130
+ * @param {Help} helper
3131
+ * @returns {string}
3132
+ */
3133
+
3134
+ formatHelp(cmd, helper) {
3135
+ const termWidth = helper.padWidth(cmd, helper);
3136
+ const helpWidth = helper.helpWidth || 80;
3137
+ const itemIndentWidth = 2;
3138
+ const itemSeparatorWidth = 2; // between term and description
3139
+ function formatItem(term, description) {
3140
+ if (description) {
3141
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
3142
+ return helper.wrap(
3143
+ fullText,
3144
+ helpWidth - itemIndentWidth,
3145
+ termWidth + itemSeparatorWidth,
3146
+ );
3147
+ }
3148
+ return term;
3149
+ }
3150
+ function formatList(textArray) {
3151
+ return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));
3152
+ }
3153
+
3154
+ // Usage
3155
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];
3156
+
3157
+ // Description
3158
+ const commandDescription = helper.commandDescription(cmd);
3159
+ if (commandDescription.length > 0) {
3160
+ output = output.concat([
3161
+ helper.wrap(commandDescription, helpWidth, 0),
3162
+ '',
3163
+ ]);
3164
+ }
3165
+
3166
+ // Arguments
3167
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
3168
+ return formatItem(
3169
+ helper.argumentTerm(argument),
3170
+ helper.argumentDescription(argument),
3171
+ );
3172
+ });
3173
+ if (argumentList.length > 0) {
3174
+ output = output.concat(['Arguments:', formatList(argumentList), '']);
3175
+ }
3176
+
3177
+ // Options
3178
+ const optionList = helper.visibleOptions(cmd).map((option) => {
3179
+ return formatItem(
3180
+ helper.optionTerm(option),
3181
+ helper.optionDescription(option),
3182
+ );
3183
+ });
3184
+ if (optionList.length > 0) {
3185
+ output = output.concat(['Options:', formatList(optionList), '']);
3186
+ }
3187
+
3188
+ if (this.showGlobalOptions) {
3189
+ const globalOptionList = helper
3190
+ .visibleGlobalOptions(cmd)
3191
+ .map((option) => {
3192
+ return formatItem(
3193
+ helper.optionTerm(option),
3194
+ helper.optionDescription(option),
3195
+ );
3196
+ });
3197
+ if (globalOptionList.length > 0) {
3198
+ output = output.concat([
3199
+ 'Global Options:',
3200
+ formatList(globalOptionList),
3201
+ '',
3202
+ ]);
3203
+ }
3204
+ }
3205
+
3206
+ // Commands
3207
+ const commandList = helper.visibleCommands(cmd).map((cmd) => {
3208
+ return formatItem(
3209
+ helper.subcommandTerm(cmd),
3210
+ helper.subcommandDescription(cmd),
3211
+ );
3212
+ });
3213
+ if (commandList.length > 0) {
3214
+ output = output.concat(['Commands:', formatList(commandList), '']);
3215
+ }
3216
+
3217
+ return output.join('\n');
3218
+ }
3219
+
3220
+ /**
3221
+ * Calculate the pad width from the maximum term length.
3222
+ *
3223
+ * @param {Command} cmd
3224
+ * @param {Help} helper
3225
+ * @returns {number}
3226
+ */
3227
+
3228
+ padWidth(cmd, helper) {
3229
+ return Math.max(
3230
+ helper.longestOptionTermLength(cmd, helper),
3231
+ helper.longestGlobalOptionTermLength(cmd, helper),
3232
+ helper.longestSubcommandTermLength(cmd, helper),
3233
+ helper.longestArgumentTermLength(cmd, helper),
3234
+ );
3235
+ }
3236
+
3237
+ /**
3238
+ * Wrap the given string to width characters per line, with lines after the first indented.
3239
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
3240
+ *
3241
+ * @param {string} str
3242
+ * @param {number} width
3243
+ * @param {number} indent
3244
+ * @param {number} [minColumnWidth=40]
3245
+ * @return {string}
3246
+ *
3247
+ */
3248
+
3249
+ wrap(str, width, indent, minColumnWidth = 40) {
3250
+ // Full \s characters, minus the linefeeds.
3251
+ const indents =
3252
+ ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff';
3253
+ // Detect manually wrapped and indented strings by searching for line break followed by spaces.
3254
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
3255
+ if (str.match(manualIndent)) return str;
3256
+ // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).
3257
+ const columnWidth = width - indent;
3258
+ if (columnWidth < minColumnWidth) return str;
3259
+
3260
+ const leadingStr = str.slice(0, indent);
3261
+ const columnText = str.slice(indent).replace('\r\n', '\n');
3262
+ const indentString = ' '.repeat(indent);
3263
+ const zeroWidthSpace = '\u200B';
3264
+ const breaks = `\\s${zeroWidthSpace}`;
3265
+ // Match line end (so empty lines don't collapse),
3266
+ // or as much text as will fit in column, or excess text up to first break.
3267
+ const regex = new RegExp(
3268
+ `\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
3269
+ 'g',
3270
+ );
3271
+ const lines = columnText.match(regex) || [];
3272
+ return (
3273
+ leadingStr +
3274
+ lines
3275
+ .map((line, i) => {
3276
+ if (line === '\n') return ''; // preserve empty lines
3277
+ return (i > 0 ? indentString : '') + line.trimEnd();
3278
+ })
3279
+ .join('\n')
3280
+ );
3281
+ }
3282
+ }
3283
+
3284
+ exports.Help = Help;
3285
+
3286
+
3287
+ /***/ }),
3288
+
3289
+ /***/ 230:
3290
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
3291
+
3292
+ const { InvalidArgumentError } = __nccwpck_require__(829);
3293
+
3294
+ class Option {
3295
+ /**
3296
+ * Initialize a new `Option` with the given `flags` and `description`.
3297
+ *
3298
+ * @param {string} flags
3299
+ * @param {string} [description]
3300
+ */
3301
+
3302
+ constructor(flags, description) {
3303
+ this.flags = flags;
3304
+ this.description = description || '';
3305
+
3306
+ this.required = flags.includes('<'); // A value must be supplied when the option is specified.
3307
+ this.optional = flags.includes('['); // A value is optional when the option is specified.
3308
+ // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
3309
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
3310
+ this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
3311
+ const optionFlags = splitOptionFlags(flags);
3312
+ this.short = optionFlags.shortFlag;
3313
+ this.long = optionFlags.longFlag;
3314
+ this.negate = false;
3315
+ if (this.long) {
3316
+ this.negate = this.long.startsWith('--no-');
3317
+ }
3318
+ this.defaultValue = undefined;
3319
+ this.defaultValueDescription = undefined;
3320
+ this.presetArg = undefined;
3321
+ this.envVar = undefined;
3322
+ this.parseArg = undefined;
3323
+ this.hidden = false;
3324
+ this.argChoices = undefined;
3325
+ this.conflictsWith = [];
3326
+ this.implied = undefined;
3327
+ }
3328
+
3329
+ /**
3330
+ * Set the default value, and optionally supply the description to be displayed in the help.
3331
+ *
3332
+ * @param {*} value
3333
+ * @param {string} [description]
3334
+ * @return {Option}
3335
+ */
3336
+
3337
+ default(value, description) {
3338
+ this.defaultValue = value;
3339
+ this.defaultValueDescription = description;
3340
+ return this;
3341
+ }
3342
+
3343
+ /**
3344
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
3345
+ * The custom processing (parseArg) is called.
3346
+ *
3347
+ * @example
3348
+ * new Option('--color').default('GREYSCALE').preset('RGB');
3349
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
3350
+ *
3351
+ * @param {*} arg
3352
+ * @return {Option}
3353
+ */
3354
+
3355
+ preset(arg) {
3356
+ this.presetArg = arg;
3357
+ return this;
3358
+ }
3359
+
3360
+ /**
3361
+ * Add option name(s) that conflict with this option.
3362
+ * An error will be displayed if conflicting options are found during parsing.
3363
+ *
3364
+ * @example
3365
+ * new Option('--rgb').conflicts('cmyk');
3366
+ * new Option('--js').conflicts(['ts', 'jsx']);
3367
+ *
3368
+ * @param {(string | string[])} names
3369
+ * @return {Option}
3370
+ */
3371
+
3372
+ conflicts(names) {
3373
+ this.conflictsWith = this.conflictsWith.concat(names);
3374
+ return this;
3375
+ }
3376
+
3377
+ /**
3378
+ * Specify implied option values for when this option is set and the implied options are not.
3379
+ *
3380
+ * The custom processing (parseArg) is not called on the implied values.
3381
+ *
3382
+ * @example
3383
+ * program
3384
+ * .addOption(new Option('--log', 'write logging information to file'))
3385
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
3386
+ *
3387
+ * @param {object} impliedOptionValues
3388
+ * @return {Option}
3389
+ */
3390
+ implies(impliedOptionValues) {
3391
+ let newImplied = impliedOptionValues;
3392
+ if (typeof impliedOptionValues === 'string') {
3393
+ // string is not documented, but easy mistake and we can do what user probably intended.
3394
+ newImplied = { [impliedOptionValues]: true };
3395
+ }
3396
+ this.implied = Object.assign(this.implied || {}, newImplied);
3397
+ return this;
3398
+ }
3399
+
3400
+ /**
3401
+ * Set environment variable to check for option value.
3402
+ *
3403
+ * An environment variable is only used if when processed the current option value is
3404
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
3405
+ *
3406
+ * @param {string} name
3407
+ * @return {Option}
3408
+ */
3409
+
3410
+ env(name) {
3411
+ this.envVar = name;
3412
+ return this;
3413
+ }
3414
+
3415
+ /**
3416
+ * Set the custom handler for processing CLI option arguments into option values.
3417
+ *
3418
+ * @param {Function} [fn]
3419
+ * @return {Option}
3420
+ */
3421
+
3422
+ argParser(fn) {
3423
+ this.parseArg = fn;
3424
+ return this;
3425
+ }
3426
+
3427
+ /**
3428
+ * Whether the option is mandatory and must have a value after parsing.
3429
+ *
3430
+ * @param {boolean} [mandatory=true]
3431
+ * @return {Option}
3432
+ */
3433
+
3434
+ makeOptionMandatory(mandatory = true) {
3435
+ this.mandatory = !!mandatory;
3436
+ return this;
3437
+ }
3438
+
3439
+ /**
3440
+ * Hide option in help.
3441
+ *
3442
+ * @param {boolean} [hide=true]
3443
+ * @return {Option}
3444
+ */
3445
+
3446
+ hideHelp(hide = true) {
3447
+ this.hidden = !!hide;
3448
+ return this;
3449
+ }
3450
+
3451
+ /**
3452
+ * @package
3453
+ */
3454
+
3455
+ _concatValue(value, previous) {
3456
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
3457
+ return [value];
3458
+ }
3459
+
3460
+ return previous.concat(value);
3461
+ }
3462
+
3463
+ /**
3464
+ * Only allow option value to be one of choices.
3465
+ *
3466
+ * @param {string[]} values
3467
+ * @return {Option}
3468
+ */
3469
+
3470
+ choices(values) {
3471
+ this.argChoices = values.slice();
3472
+ this.parseArg = (arg, previous) => {
3473
+ if (!this.argChoices.includes(arg)) {
3474
+ throw new InvalidArgumentError(
3475
+ `Allowed choices are ${this.argChoices.join(', ')}.`,
3476
+ );
3477
+ }
3478
+ if (this.variadic) {
3479
+ return this._concatValue(arg, previous);
3480
+ }
3481
+ return arg;
3482
+ };
3483
+ return this;
3484
+ }
3485
+
3486
+ /**
3487
+ * Return option name.
3488
+ *
3489
+ * @return {string}
3490
+ */
3491
+
3492
+ name() {
3493
+ if (this.long) {
3494
+ return this.long.replace(/^--/, '');
3495
+ }
3496
+ return this.short.replace(/^-/, '');
3497
+ }
3498
+
3499
+ /**
3500
+ * Return option name, in a camelcase format that can be used
3501
+ * as a object attribute key.
3502
+ *
3503
+ * @return {string}
3504
+ */
3505
+
3506
+ attributeName() {
3507
+ return camelcase(this.name().replace(/^no-/, ''));
3508
+ }
3509
+
3510
+ /**
3511
+ * Check if `arg` matches the short or long flag.
3512
+ *
3513
+ * @param {string} arg
3514
+ * @return {boolean}
3515
+ * @package
3516
+ */
3517
+
3518
+ is(arg) {
3519
+ return this.short === arg || this.long === arg;
3520
+ }
3521
+
3522
+ /**
3523
+ * Return whether a boolean option.
3524
+ *
3525
+ * Options are one of boolean, negated, required argument, or optional argument.
3526
+ *
3527
+ * @return {boolean}
3528
+ * @package
3529
+ */
3530
+
3531
+ isBoolean() {
3532
+ return !this.required && !this.optional && !this.negate;
3533
+ }
3534
+ }
3535
+
3536
+ /**
3537
+ * This class is to make it easier to work with dual options, without changing the existing
3538
+ * implementation. We support separate dual options for separate positive and negative options,
3539
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
3540
+ * use cases, but is tricky for others where we want separate behaviours despite
3541
+ * the single shared option value.
3542
+ */
3543
+ class DualOptions {
3544
+ /**
3545
+ * @param {Option[]} options
3546
+ */
3547
+ constructor(options) {
3548
+ this.positiveOptions = new Map();
3549
+ this.negativeOptions = new Map();
3550
+ this.dualOptions = new Set();
3551
+ options.forEach((option) => {
3552
+ if (option.negate) {
3553
+ this.negativeOptions.set(option.attributeName(), option);
3554
+ } else {
3555
+ this.positiveOptions.set(option.attributeName(), option);
3556
+ }
3557
+ });
3558
+ this.negativeOptions.forEach((value, key) => {
3559
+ if (this.positiveOptions.has(key)) {
3560
+ this.dualOptions.add(key);
3561
+ }
3562
+ });
3563
+ }
3564
+
3565
+ /**
3566
+ * Did the value come from the option, and not from possible matching dual option?
3567
+ *
3568
+ * @param {*} value
3569
+ * @param {Option} option
3570
+ * @returns {boolean}
3571
+ */
3572
+ valueFromOption(value, option) {
3573
+ const optionKey = option.attributeName();
3574
+ if (!this.dualOptions.has(optionKey)) return true;
3575
+
3576
+ // Use the value to deduce if (probably) came from the option.
3577
+ const preset = this.negativeOptions.get(optionKey).presetArg;
3578
+ const negativeValue = preset !== undefined ? preset : false;
3579
+ return option.negate === (negativeValue === value);
3580
+ }
3581
+ }
3582
+
3583
+ /**
3584
+ * Convert string from kebab-case to camelCase.
3585
+ *
3586
+ * @param {string} str
3587
+ * @return {string}
3588
+ * @private
3589
+ */
3590
+
3591
+ function camelcase(str) {
3592
+ return str.split('-').reduce((str, word) => {
3593
+ return str + word[0].toUpperCase() + word.slice(1);
3594
+ });
3595
+ }
3596
+
3597
+ /**
3598
+ * Split the short and long flag out of something like '-m,--mixed <value>'
3599
+ *
3600
+ * @private
3601
+ */
3602
+
3603
+ function splitOptionFlags(flags) {
3604
+ let shortFlag;
3605
+ let longFlag;
3606
+ // Use original very loose parsing to maintain backwards compatibility for now,
3607
+ // which allowed for example unintended `-sw, --short-word` [sic].
3608
+ const flagParts = flags.split(/[ |,]+/);
3609
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
3610
+ shortFlag = flagParts.shift();
3611
+ longFlag = flagParts.shift();
3612
+ // Add support for lone short flag without significantly changing parsing!
3613
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
3614
+ shortFlag = longFlag;
3615
+ longFlag = undefined;
3616
+ }
3617
+ return { shortFlag, longFlag };
3618
+ }
3619
+
3620
+ exports.Option = Option;
3621
+ exports.DualOptions = DualOptions;
3622
+
3623
+
3624
+ /***/ }),
3625
+
3626
+ /***/ 241:
3627
+ /***/ ((__unused_webpack_module, exports) => {
3628
+
3629
+ const maxDistance = 3;
3630
+
3631
+ function editDistance(a, b) {
3632
+ // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance
3633
+ // Calculating optimal string alignment distance, no substring is edited more than once.
3634
+ // (Simple implementation.)
3635
+
3636
+ // Quick early exit, return worst case.
3637
+ if (Math.abs(a.length - b.length) > maxDistance)
3638
+ return Math.max(a.length, b.length);
3639
+
3640
+ // distance between prefix substrings of a and b
3641
+ const d = [];
3642
+
3643
+ // pure deletions turn a into empty string
3644
+ for (let i = 0; i <= a.length; i++) {
3645
+ d[i] = [i];
3646
+ }
3647
+ // pure insertions turn empty string into b
3648
+ for (let j = 0; j <= b.length; j++) {
3649
+ d[0][j] = j;
3650
+ }
3651
+
3652
+ // fill matrix
3653
+ for (let j = 1; j <= b.length; j++) {
3654
+ for (let i = 1; i <= a.length; i++) {
3655
+ let cost = 1;
3656
+ if (a[i - 1] === b[j - 1]) {
3657
+ cost = 0;
3658
+ } else {
3659
+ cost = 1;
3660
+ }
3661
+ d[i][j] = Math.min(
3662
+ d[i - 1][j] + 1, // deletion
3663
+ d[i][j - 1] + 1, // insertion
3664
+ d[i - 1][j - 1] + cost, // substitution
3665
+ );
3666
+ // transposition
3667
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
3668
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
3669
+ }
3670
+ }
3671
+ }
3672
+
3673
+ return d[a.length][b.length];
3674
+ }
3675
+
3676
+ /**
3677
+ * Find close matches, restricted to same number of edits.
3678
+ *
3679
+ * @param {string} word
3680
+ * @param {string[]} candidates
3681
+ * @returns {string}
3682
+ */
3683
+
3684
+ function suggestSimilar(word, candidates) {
3685
+ if (!candidates || candidates.length === 0) return '';
3686
+ // remove possible duplicates
3687
+ candidates = Array.from(new Set(candidates));
3688
+
3689
+ const searchingOptions = word.startsWith('--');
3690
+ if (searchingOptions) {
3691
+ word = word.slice(2);
3692
+ candidates = candidates.map((candidate) => candidate.slice(2));
3693
+ }
3694
+
3695
+ let similar = [];
3696
+ let bestDistance = maxDistance;
3697
+ const minSimilarity = 0.4;
3698
+ candidates.forEach((candidate) => {
3699
+ if (candidate.length <= 1) return; // no one character guesses
3700
+
3701
+ const distance = editDistance(word, candidate);
3702
+ const length = Math.max(word.length, candidate.length);
3703
+ const similarity = (length - distance) / length;
3704
+ if (similarity > minSimilarity) {
3705
+ if (distance < bestDistance) {
3706
+ // better edit distance, throw away previous worse matches
3707
+ bestDistance = distance;
3708
+ similar = [candidate];
3709
+ } else if (distance === bestDistance) {
3710
+ similar.push(candidate);
3711
+ }
3712
+ }
3713
+ });
3714
+
3715
+ similar.sort((a, b) => a.localeCompare(b));
3716
+ if (searchingOptions) {
3717
+ similar = similar.map((candidate) => `--${candidate}`);
3718
+ }
3719
+
3720
+ if (similar.length > 1) {
3721
+ return `\n(Did you mean one of ${similar.join(', ')}?)`;
3722
+ }
3723
+ if (similar.length === 1) {
3724
+ return `\n(Did you mean ${similar[0]}?)`;
3725
+ }
3726
+ return '';
3727
+ }
3728
+
3729
+ exports.suggestSimilar = suggestSimilar;
3730
+
3731
+
3732
+ /***/ })
3733
+
3734
+ /******/ });
3735
+ /************************************************************************/
3736
+ /******/ // The module cache
3737
+ /******/ var __webpack_module_cache__ = {};
3738
+ /******/
3739
+ /******/ // The require function
3740
+ /******/ function __nccwpck_require__(moduleId) {
3741
+ /******/ // Check if module is in cache
3742
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
3743
+ /******/ if (cachedModule !== undefined) {
3744
+ /******/ return cachedModule.exports;
3745
+ /******/ }
3746
+ /******/ // Create a new module (and put it into the cache)
3747
+ /******/ var module = __webpack_module_cache__[moduleId] = {
3748
+ /******/ // no module.id needed
3749
+ /******/ // no module.loaded needed
3750
+ /******/ exports: {}
3751
+ /******/ };
3752
+ /******/
3753
+ /******/ // Execute the module function
3754
+ /******/ var threw = true;
3755
+ /******/ try {
3756
+ /******/ __webpack_modules__[moduleId](module, module.exports, __nccwpck_require__);
3757
+ /******/ threw = false;
3758
+ /******/ } finally {
3759
+ /******/ if(threw) delete __webpack_module_cache__[moduleId];
3760
+ /******/ }
3761
+ /******/
3762
+ /******/ // Return the exports of the module
3763
+ /******/ return module.exports;
3764
+ /******/ }
3765
+ /******/
3766
+ /************************************************************************/
3767
+ /******/ /* webpack/runtime/compat */
3768
+ /******/
3769
+ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
3770
+ /******/
3771
+ /************************************************************************/
3772
+ var __webpack_exports__ = {};
3773
+ // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
3774
+ (() => {
3775
+ var exports = __webpack_exports__;
3776
+ const { Argument } = __nccwpck_require__(654);
3777
+ const { Command } = __nccwpck_require__(955);
3778
+ const { CommanderError, InvalidArgumentError } = __nccwpck_require__(829);
3779
+ const { Help } = __nccwpck_require__(567);
3780
+ const { Option } = __nccwpck_require__(230);
3781
+
3782
+ exports.program = new Command();
3783
+
3784
+ exports.createCommand = (name) => new Command(name);
3785
+ exports.createOption = (flags, description) => new Option(flags, description);
3786
+ exports.createArgument = (name, description) => new Argument(name, description);
3787
+
3788
+ /**
3789
+ * Expose classes
3790
+ */
3791
+
3792
+ exports.Command = Command;
3793
+ exports.Option = Option;
3794
+ exports.Argument = Argument;
3795
+ exports.Help = Help;
3796
+
3797
+ exports.CommanderError = CommanderError;
3798
+ exports.InvalidArgumentError = InvalidArgumentError;
3799
+ exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated
3800
+
3801
+ })();
3802
+
3803
+ module.exports = __webpack_exports__;
3804
+ /******/ })()
3805
+ ;