@buildepicshit/cli 0.0.1

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