create-gridland 0.2.0

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