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