create-storybook 9.2.0-alpha.3 → 10.0.0-beta.1

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