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