@skapxd/eslint-opinionated 0.1.0

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