@hasna/coders 0.0.1

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