@baby-ui/cli 0.0.0-stage → 0.1.0

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