release-note 0.0.2 → 0.0.4

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