@wix/create-new 0.0.1

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