@bomb.sh/tab 0.0.1-pre.0

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