release-note 0.0.1 → 0.0.3

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