@yejianfei.billy/subagent-cli 0.1.2

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