@cmflow/source-pack 0.0.0-stage → 3.20.0

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