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