release-note 0.0.2 → 0.0.4

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