@capytale/activity.js 3.0.7 → 3.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cactjs.js CHANGED
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- var require$$0 = require('events');
5
- var require$$1 = require('child_process');
6
- var require$$2 = require('path');
7
- var fs$1 = require('fs');
8
- var require$$4 = require('process');
4
+ var require$$0 = require('node:events');
5
+ var require$$1 = require('node:child_process');
6
+ var require$$2 = require('node:path');
7
+ var require$$3 = require('node:fs');
8
+ var require$$4 = require('node:process');
9
9
  var crypto = require('crypto');
10
+ var fs$1 = require('fs');
11
+ var path$1 = require('path');
10
12
 
11
13
  var commander = {};
12
14
 
@@ -16,7 +18,6 @@ var error = {};
16
18
 
17
19
  /**
18
20
  * CommanderError class
19
- * @class
20
21
  */
21
22
 
22
23
  let CommanderError$3 = class CommanderError extends Error {
@@ -25,7 +26,6 @@ let CommanderError$3 = class CommanderError extends Error {
25
26
  * @param {number} exitCode suggested exit code which could be used with process.exit
26
27
  * @param {string} code an id string representing the error
27
28
  * @param {string} message human-readable description of the error
28
- * @constructor
29
29
  */
30
30
  constructor(exitCode, code, message) {
31
31
  super(message);
@@ -40,13 +40,11 @@ let CommanderError$3 = class CommanderError extends Error {
40
40
 
41
41
  /**
42
42
  * InvalidArgumentError class
43
- * @class
44
43
  */
45
44
  let InvalidArgumentError$4 = class InvalidArgumentError extends CommanderError$3 {
46
45
  /**
47
46
  * Constructs the InvalidArgumentError class
48
47
  * @param {string} [message] explanation of why argument is invalid
49
- * @constructor
50
48
  */
51
49
  constructor(message) {
52
50
  super(1, 'commander.invalidArgument', message);
@@ -111,7 +109,7 @@ let Argument$3 = class Argument {
111
109
  }
112
110
 
113
111
  /**
114
- * @package internal use only
112
+ * @package
115
113
  */
116
114
 
117
115
  _concatValue(value, previous) {
@@ -159,7 +157,9 @@ let Argument$3 = class Argument {
159
157
  this.argChoices = values.slice();
160
158
  this.parseArg = (arg, previous) => {
161
159
  if (!this.argChoices.includes(arg)) {
162
- throw new InvalidArgumentError$3(`Allowed choices are ${this.argChoices.join(', ')}.`);
160
+ throw new InvalidArgumentError$3(
161
+ `Allowed choices are ${this.argChoices.join(', ')}.`,
162
+ );
163
163
  }
164
164
  if (this.variadic) {
165
165
  return this._concatValue(arg, previous);
@@ -171,6 +171,8 @@ let Argument$3 = class Argument {
171
171
 
172
172
  /**
173
173
  * Make argument required.
174
+ *
175
+ * @returns {Argument}
174
176
  */
175
177
  argRequired() {
176
178
  this.required = true;
@@ -179,6 +181,8 @@ let Argument$3 = class Argument {
179
181
 
180
182
  /**
181
183
  * Make argument optional.
184
+ *
185
+ * @returns {Argument}
182
186
  */
183
187
  argOptional() {
184
188
  this.required = false;
@@ -197,9 +201,7 @@ let Argument$3 = class Argument {
197
201
  function humanReadableArgName$2(arg) {
198
202
  const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
199
203
 
200
- return arg.required
201
- ? '<' + nameOutput + '>'
202
- : '[' + nameOutput + ']';
204
+ return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
203
205
  }
204
206
 
205
207
  argument.Argument = Argument$3;
@@ -236,14 +238,14 @@ let Help$3 = class Help {
236
238
  */
237
239
 
238
240
  visibleCommands(cmd) {
239
- const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden);
241
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
240
242
  const helpCommand = cmd._getHelpCommand();
241
243
  if (helpCommand && !helpCommand._hidden) {
242
244
  visibleCommands.push(helpCommand);
243
245
  }
244
246
  if (this.sortSubcommands) {
245
247
  visibleCommands.sort((a, b) => {
246
- // @ts-ignore: overloaded return type
248
+ // @ts-ignore: because overloaded return type
247
249
  return a.name().localeCompare(b.name());
248
250
  });
249
251
  }
@@ -255,12 +257,14 @@ let Help$3 = class Help {
255
257
  *
256
258
  * @param {Option} a
257
259
  * @param {Option} b
258
- * @returns number
260
+ * @returns {number}
259
261
  */
260
262
  compareOptions(a, b) {
261
263
  const getSortKey = (option) => {
262
264
  // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
263
- return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, '');
265
+ return option.short
266
+ ? option.short.replace(/^-/, '')
267
+ : option.long.replace(/^--/, '');
264
268
  };
265
269
  return getSortKey(a).localeCompare(getSortKey(b));
266
270
  }
@@ -283,9 +287,13 @@ let Help$3 = class Help {
283
287
  if (!removeShort && !removeLong) {
284
288
  visibleOptions.push(helpOption); // no changes needed
285
289
  } else if (helpOption.long && !removeLong) {
286
- visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
290
+ visibleOptions.push(
291
+ cmd.createOption(helpOption.long, helpOption.description),
292
+ );
287
293
  } else if (helpOption.short && !removeShort) {
288
- visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
294
+ visibleOptions.push(
295
+ cmd.createOption(helpOption.short, helpOption.description),
296
+ );
289
297
  }
290
298
  }
291
299
  if (this.sortOptions) {
@@ -305,8 +313,14 @@ let Help$3 = class Help {
305
313
  if (!this.showGlobalOptions) return [];
306
314
 
307
315
  const globalOptions = [];
308
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
309
- const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
316
+ for (
317
+ let ancestorCmd = cmd.parent;
318
+ ancestorCmd;
319
+ ancestorCmd = ancestorCmd.parent
320
+ ) {
321
+ const visibleOptions = ancestorCmd.options.filter(
322
+ (option) => !option.hidden,
323
+ );
310
324
  globalOptions.push(...visibleOptions);
311
325
  }
312
326
  if (this.sortOptions) {
@@ -325,13 +339,14 @@ let Help$3 = class Help {
325
339
  visibleArguments(cmd) {
326
340
  // Side effect! Apply the legacy descriptions before the arguments are displayed.
327
341
  if (cmd._argsDescription) {
328
- cmd.registeredArguments.forEach(argument => {
329
- argument.description = argument.description || cmd._argsDescription[argument.name()] || '';
342
+ cmd.registeredArguments.forEach((argument) => {
343
+ argument.description =
344
+ argument.description || cmd._argsDescription[argument.name()] || '';
330
345
  });
331
346
  }
332
347
 
333
348
  // If there are any arguments with a description then return all the arguments.
334
- if (cmd.registeredArguments.find(argument => argument.description)) {
349
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
335
350
  return cmd.registeredArguments;
336
351
  }
337
352
  return [];
@@ -346,11 +361,15 @@ let Help$3 = class Help {
346
361
 
347
362
  subcommandTerm(cmd) {
348
363
  // Legacy. Ignores custom usage string, and nested commands.
349
- const args = cmd.registeredArguments.map(arg => humanReadableArgName$1(arg)).join(' ');
350
- return cmd._name +
364
+ const args = cmd.registeredArguments
365
+ .map((arg) => humanReadableArgName$1(arg))
366
+ .join(' ');
367
+ return (
368
+ cmd._name +
351
369
  (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
352
370
  (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
353
- (args ? ' ' + args : '');
371
+ (args ? ' ' + args : '')
372
+ );
354
373
  }
355
374
 
356
375
  /**
@@ -445,7 +464,11 @@ let Help$3 = class Help {
445
464
  cmdName = cmdName + '|' + cmd._aliases[0];
446
465
  }
447
466
  let ancestorCmdNames = '';
448
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
467
+ for (
468
+ let ancestorCmd = cmd.parent;
469
+ ancestorCmd;
470
+ ancestorCmd = ancestorCmd.parent
471
+ ) {
449
472
  ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;
450
473
  }
451
474
  return ancestorCmdNames + cmdName + ' ' + cmd.usage();
@@ -459,7 +482,7 @@ let Help$3 = class Help {
459
482
  */
460
483
 
461
484
  commandDescription(cmd) {
462
- // @ts-ignore: overloaded return type
485
+ // @ts-ignore: because overloaded return type
463
486
  return cmd.description();
464
487
  }
465
488
 
@@ -472,7 +495,7 @@ let Help$3 = class Help {
472
495
  */
473
496
 
474
497
  subcommandDescription(cmd) {
475
- // @ts-ignore: overloaded return type
498
+ // @ts-ignore: because overloaded return type
476
499
  return cmd.summary() || cmd.description();
477
500
  }
478
501
 
@@ -489,15 +512,20 @@ let Help$3 = class Help {
489
512
  if (option.argChoices) {
490
513
  extraInfo.push(
491
514
  // use stringify to match the display of the default value
492
- `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);
515
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
516
+ );
493
517
  }
494
518
  if (option.defaultValue !== undefined) {
495
519
  // default for boolean and negated more for programmer than end user,
496
520
  // but show true/false for boolean option as may be for hand-rolled env or config processing.
497
- const showDefault = option.required || option.optional ||
521
+ const showDefault =
522
+ option.required ||
523
+ option.optional ||
498
524
  (option.isBoolean() && typeof option.defaultValue === 'boolean');
499
525
  if (showDefault) {
500
- extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
526
+ extraInfo.push(
527
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,
528
+ );
501
529
  }
502
530
  }
503
531
  // preset for boolean and negated are more for programmer than end user
@@ -526,10 +554,13 @@ let Help$3 = class Help {
526
554
  if (argument.argChoices) {
527
555
  extraInfo.push(
528
556
  // use stringify to match the display of the default value
529
- `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);
557
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
558
+ );
530
559
  }
531
560
  if (argument.defaultValue !== undefined) {
532
- extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
561
+ extraInfo.push(
562
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,
563
+ );
533
564
  }
534
565
  if (extraInfo.length > 0) {
535
566
  const extraDescripton = `(${extraInfo.join(', ')})`;
@@ -557,7 +588,11 @@ let Help$3 = class Help {
557
588
  function formatItem(term, description) {
558
589
  if (description) {
559
590
  const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
560
- return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
591
+ return helper.wrap(
592
+ fullText,
593
+ helpWidth - itemIndentWidth,
594
+ termWidth + itemSeparatorWidth,
595
+ );
561
596
  }
562
597
  return term;
563
598
  }
@@ -571,12 +606,18 @@ let Help$3 = class Help {
571
606
  // Description
572
607
  const commandDescription = helper.commandDescription(cmd);
573
608
  if (commandDescription.length > 0) {
574
- output = output.concat([helper.wrap(commandDescription, helpWidth, 0), '']);
609
+ output = output.concat([
610
+ helper.wrap(commandDescription, helpWidth, 0),
611
+ '',
612
+ ]);
575
613
  }
576
614
 
577
615
  // Arguments
578
616
  const argumentList = helper.visibleArguments(cmd).map((argument) => {
579
- return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
617
+ return formatItem(
618
+ helper.argumentTerm(argument),
619
+ helper.argumentDescription(argument),
620
+ );
580
621
  });
581
622
  if (argumentList.length > 0) {
582
623
  output = output.concat(['Arguments:', formatList(argumentList), '']);
@@ -584,24 +625,39 @@ let Help$3 = class Help {
584
625
 
585
626
  // Options
586
627
  const optionList = helper.visibleOptions(cmd).map((option) => {
587
- return formatItem(helper.optionTerm(option), helper.optionDescription(option));
628
+ return formatItem(
629
+ helper.optionTerm(option),
630
+ helper.optionDescription(option),
631
+ );
588
632
  });
589
633
  if (optionList.length > 0) {
590
634
  output = output.concat(['Options:', formatList(optionList), '']);
591
635
  }
592
636
 
593
637
  if (this.showGlobalOptions) {
594
- const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
595
- return formatItem(helper.optionTerm(option), helper.optionDescription(option));
596
- });
638
+ const globalOptionList = helper
639
+ .visibleGlobalOptions(cmd)
640
+ .map((option) => {
641
+ return formatItem(
642
+ helper.optionTerm(option),
643
+ helper.optionDescription(option),
644
+ );
645
+ });
597
646
  if (globalOptionList.length > 0) {
598
- output = output.concat(['Global Options:', formatList(globalOptionList), '']);
647
+ output = output.concat([
648
+ 'Global Options:',
649
+ formatList(globalOptionList),
650
+ '',
651
+ ]);
599
652
  }
600
653
  }
601
654
 
602
655
  // Commands
603
656
  const commandList = helper.visibleCommands(cmd).map((cmd) => {
604
- return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));
657
+ return formatItem(
658
+ helper.subcommandTerm(cmd),
659
+ helper.subcommandDescription(cmd),
660
+ );
605
661
  });
606
662
  if (commandList.length > 0) {
607
663
  output = output.concat(['Commands:', formatList(commandList), '']);
@@ -623,7 +679,7 @@ let Help$3 = class Help {
623
679
  helper.longestOptionTermLength(cmd, helper),
624
680
  helper.longestGlobalOptionTermLength(cmd, helper),
625
681
  helper.longestSubcommandTermLength(cmd, helper),
626
- helper.longestArgumentTermLength(cmd, helper)
682
+ helper.longestArgumentTermLength(cmd, helper),
627
683
  );
628
684
  }
629
685
 
@@ -641,7 +697,8 @@ let Help$3 = class Help {
641
697
 
642
698
  wrap(str, width, indent, minColumnWidth = 40) {
643
699
  // Full \s characters, minus the linefeeds.
644
- const indents = ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff';
700
+ const indents =
701
+ ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff';
645
702
  // Detect manually wrapped and indented strings by searching for line break followed by spaces.
646
703
  const manualIndent = new RegExp(`[\\n][${indents}]+`);
647
704
  if (str.match(manualIndent)) return str;
@@ -656,12 +713,20 @@ let Help$3 = class Help {
656
713
  const breaks = `\\s${zeroWidthSpace}`;
657
714
  // Match line end (so empty lines don't collapse),
658
715
  // or as much text as will fit in column, or excess text up to first break.
659
- const regex = new RegExp(`\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, 'g');
716
+ const regex = new RegExp(
717
+ `\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
718
+ 'g',
719
+ );
660
720
  const lines = columnText.match(regex) || [];
661
- return leadingStr + lines.map((line, i) => {
662
- if (line === '\n') return ''; // preserve empty lines
663
- return ((i > 0) ? indentString : '') + line.trimEnd();
664
- }).join('\n');
721
+ return (
722
+ leadingStr +
723
+ lines
724
+ .map((line, i) => {
725
+ if (line === '\n') return ''; // preserve empty lines
726
+ return (i > 0 ? indentString : '') + line.trimEnd();
727
+ })
728
+ .join('\n')
729
+ );
665
730
  }
666
731
  };
667
732
 
@@ -764,7 +829,7 @@ let Option$3 = class Option {
764
829
  * .addOption(new Option('--log', 'write logging information to file'))
765
830
  * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
766
831
  *
767
- * @param {Object} impliedOptionValues
832
+ * @param {object} impliedOptionValues
768
833
  * @return {Option}
769
834
  */
770
835
  implies(impliedOptionValues) {
@@ -829,7 +894,7 @@ let Option$3 = class Option {
829
894
  }
830
895
 
831
896
  /**
832
- * @package internal use only
897
+ * @package
833
898
  */
834
899
 
835
900
  _concatValue(value, previous) {
@@ -851,7 +916,9 @@ let Option$3 = class Option {
851
916
  this.argChoices = values.slice();
852
917
  this.parseArg = (arg, previous) => {
853
918
  if (!this.argChoices.includes(arg)) {
854
- throw new InvalidArgumentError$2(`Allowed choices are ${this.argChoices.join(', ')}.`);
919
+ throw new InvalidArgumentError$2(
920
+ `Allowed choices are ${this.argChoices.join(', ')}.`,
921
+ );
855
922
  }
856
923
  if (this.variadic) {
857
924
  return this._concatValue(arg, previous);
@@ -890,7 +957,7 @@ let Option$3 = class Option {
890
957
  *
891
958
  * @param {string} arg
892
959
  * @return {boolean}
893
- * @package internal use only
960
+ * @package
894
961
  */
895
962
 
896
963
  is(arg) {
@@ -903,7 +970,7 @@ let Option$3 = class Option {
903
970
  * Options are one of boolean, negated, required argument, or optional argument.
904
971
  *
905
972
  * @return {boolean}
906
- * @package internal use only
973
+ * @package
907
974
  */
908
975
 
909
976
  isBoolean() {
@@ -926,7 +993,7 @@ let DualOptions$1 = class DualOptions {
926
993
  this.positiveOptions = new Map();
927
994
  this.negativeOptions = new Map();
928
995
  this.dualOptions = new Set();
929
- options.forEach(option => {
996
+ options.forEach((option) => {
930
997
  if (option.negate) {
931
998
  this.negativeOptions.set(option.attributeName(), option);
932
999
  } else {
@@ -953,7 +1020,7 @@ let DualOptions$1 = class DualOptions {
953
1020
 
954
1021
  // Use the value to deduce if (probably) came from the option.
955
1022
  const preset = this.negativeOptions.get(optionKey).presetArg;
956
- const negativeValue = (preset !== undefined) ? preset : false;
1023
+ const negativeValue = preset !== undefined ? preset : false;
957
1024
  return option.negate === (negativeValue === value);
958
1025
  }
959
1026
  };
@@ -984,7 +1051,8 @@ function splitOptionFlags(flags) {
984
1051
  // Use original very loose parsing to maintain backwards compatibility for now,
985
1052
  // which allowed for example unintended `-sw, --short-word` [sic].
986
1053
  const flagParts = flags.split(/[ |,]+/);
987
- if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
1054
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
1055
+ shortFlag = flagParts.shift();
988
1056
  longFlag = flagParts.shift();
989
1057
  // Add support for lone short flag without significantly changing parsing!
990
1058
  if (!shortFlag && /^-[^-]$/.test(longFlag)) {
@@ -1007,7 +1075,8 @@ function editDistance(a, b) {
1007
1075
  // (Simple implementation.)
1008
1076
 
1009
1077
  // Quick early exit, return worst case.
1010
- if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
1078
+ if (Math.abs(a.length - b.length) > maxDistance)
1079
+ return Math.max(a.length, b.length);
1011
1080
 
1012
1081
  // distance between prefix substrings of a and b
1013
1082
  const d = [];
@@ -1033,7 +1102,7 @@ function editDistance(a, b) {
1033
1102
  d[i][j] = Math.min(
1034
1103
  d[i - 1][j] + 1, // deletion
1035
1104
  d[i][j - 1] + 1, // insertion
1036
- d[i - 1][j - 1] + cost // substitution
1105
+ d[i - 1][j - 1] + cost, // substitution
1037
1106
  );
1038
1107
  // transposition
1039
1108
  if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
@@ -1061,7 +1130,7 @@ function suggestSimilar$1(word, candidates) {
1061
1130
  const searchingOptions = word.startsWith('--');
1062
1131
  if (searchingOptions) {
1063
1132
  word = word.slice(2);
1064
- candidates = candidates.map(candidate => candidate.slice(2));
1133
+ candidates = candidates.map((candidate) => candidate.slice(2));
1065
1134
  }
1066
1135
 
1067
1136
  let similar = [];
@@ -1086,7 +1155,7 @@ function suggestSimilar$1(word, candidates) {
1086
1155
 
1087
1156
  similar.sort((a, b) => a.localeCompare(b));
1088
1157
  if (searchingOptions) {
1089
- similar = similar.map(candidate => `--${candidate}`);
1158
+ similar = similar.map((candidate) => `--${candidate}`);
1090
1159
  }
1091
1160
 
1092
1161
  if (similar.length > 1) {
@@ -1103,7 +1172,7 @@ suggestSimilar$2.suggestSimilar = suggestSimilar$1;
1103
1172
  const EventEmitter = require$$0.EventEmitter;
1104
1173
  const childProcess = require$$1;
1105
1174
  const path = require$$2;
1106
- const fs = fs$1;
1175
+ const fs = require$$3;
1107
1176
  const process$1 = require$$4;
1108
1177
 
1109
1178
  const { Argument: Argument$2, humanReadableArgName } = argument;
@@ -1162,9 +1231,11 @@ let Command$2 = class Command extends EventEmitter {
1162
1231
  this._outputConfiguration = {
1163
1232
  writeOut: (str) => process$1.stdout.write(str),
1164
1233
  writeErr: (str) => process$1.stderr.write(str),
1165
- getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : undefined,
1166
- getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : undefined,
1167
- outputError: (str, write) => write(str)
1234
+ getOutHelpWidth: () =>
1235
+ process$1.stdout.isTTY ? process$1.stdout.columns : undefined,
1236
+ getErrHelpWidth: () =>
1237
+ process$1.stderr.isTTY ? process$1.stderr.columns : undefined,
1238
+ outputError: (str, write) => write(str),
1168
1239
  };
1169
1240
 
1170
1241
  this._hidden = false;
@@ -1191,7 +1262,8 @@ let Command$2 = class Command extends EventEmitter {
1191
1262
  this._helpConfiguration = sourceCommand._helpConfiguration;
1192
1263
  this._exitCallback = sourceCommand._exitCallback;
1193
1264
  this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1194
- this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1265
+ this._combineFlagAndOptionalValue =
1266
+ sourceCommand._combineFlagAndOptionalValue;
1195
1267
  this._allowExcessArguments = sourceCommand._allowExcessArguments;
1196
1268
  this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1197
1269
  this._showHelpAfterError = sourceCommand._showHelpAfterError;
@@ -1207,6 +1279,7 @@ let Command$2 = class Command extends EventEmitter {
1207
1279
 
1208
1280
  _getCommandAndAncestors() {
1209
1281
  const result = [];
1282
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
1210
1283
  for (let command = this; command; command = command.parent) {
1211
1284
  result.push(command);
1212
1285
  }
@@ -1233,8 +1306,8 @@ let Command$2 = class Command extends EventEmitter {
1233
1306
  * .command('stop [service]', 'stop named service, or all if no name supplied');
1234
1307
  *
1235
1308
  * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1236
- * @param {(Object|string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1237
- * @param {Object} [execOpts] - configuration options (for executable)
1309
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1310
+ * @param {object} [execOpts] - configuration options (for executable)
1238
1311
  * @return {Command} returns new command for action handler, or `this` for executable command
1239
1312
  */
1240
1313
 
@@ -1294,8 +1367,8 @@ let Command$2 = class Command extends EventEmitter {
1294
1367
  * You can customise the help by overriding Help properties using configureHelp(),
1295
1368
  * or with a subclass of Help by overriding createHelp().
1296
1369
  *
1297
- * @param {Object} [configuration] - configuration options
1298
- * @return {(Command|Object)} `this` command for chaining, or stored configuration
1370
+ * @param {object} [configuration] - configuration options
1371
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1299
1372
  */
1300
1373
 
1301
1374
  configureHelp(configuration) {
@@ -1320,8 +1393,8 @@ let Command$2 = class Command extends EventEmitter {
1320
1393
  * // functions based on what is being written out
1321
1394
  * outputError(str, write) // used for displaying errors, and not used for displaying help
1322
1395
  *
1323
- * @param {Object} [configuration] - configuration options
1324
- * @return {(Command|Object)} `this` command for chaining, or stored configuration
1396
+ * @param {object} [configuration] - configuration options
1397
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1325
1398
  */
1326
1399
 
1327
1400
  configureOutput(configuration) {
@@ -1360,7 +1433,7 @@ let Command$2 = class Command extends EventEmitter {
1360
1433
  * See .command() for creating an attached subcommand which inherits settings from its parent.
1361
1434
  *
1362
1435
  * @param {Command} cmd - new subcommand
1363
- * @param {Object} [opts] - configuration options
1436
+ * @param {object} [opts] - configuration options
1364
1437
  * @return {Command} `this` command for chaining
1365
1438
  */
1366
1439
 
@@ -1436,9 +1509,12 @@ let Command$2 = class Command extends EventEmitter {
1436
1509
  */
1437
1510
 
1438
1511
  arguments(names) {
1439
- names.trim().split(/ +/).forEach((detail) => {
1440
- this.argument(detail);
1441
- });
1512
+ names
1513
+ .trim()
1514
+ .split(/ +/)
1515
+ .forEach((detail) => {
1516
+ this.argument(detail);
1517
+ });
1442
1518
  return this;
1443
1519
  }
1444
1520
 
@@ -1451,10 +1527,18 @@ let Command$2 = class Command extends EventEmitter {
1451
1527
  addArgument(argument) {
1452
1528
  const previousArgument = this.registeredArguments.slice(-1)[0];
1453
1529
  if (previousArgument && previousArgument.variadic) {
1454
- throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1530
+ throw new Error(
1531
+ `only the last argument can be variadic '${previousArgument.name()}'`,
1532
+ );
1455
1533
  }
1456
- if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
1457
- throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1534
+ if (
1535
+ argument.required &&
1536
+ argument.defaultValue !== undefined &&
1537
+ argument.parseArg === undefined
1538
+ ) {
1539
+ throw new Error(
1540
+ `a default value for a required argument is never used: '${argument.name()}'`,
1541
+ );
1458
1542
  }
1459
1543
  this.registeredArguments.push(argument);
1460
1544
  return this;
@@ -1463,6 +1547,7 @@ let Command$2 = class Command extends EventEmitter {
1463
1547
  /**
1464
1548
  * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1465
1549
  *
1550
+ * @example
1466
1551
  * program.helpCommand('help [cmd]');
1467
1552
  * program.helpCommand('help [cmd]', 'show help');
1468
1553
  * program.helpCommand(false); // suppress default help command
@@ -1521,8 +1606,11 @@ let Command$2 = class Command extends EventEmitter {
1521
1606
  * @package
1522
1607
  */
1523
1608
  _getHelpCommand() {
1524
- const hasImplicitHelpCommand = this._addImplicitHelpCommand ??
1525
- (this.commands.length && !this._actionHandler && !this._findCommand('help'));
1609
+ const hasImplicitHelpCommand =
1610
+ this._addImplicitHelpCommand ??
1611
+ (this.commands.length &&
1612
+ !this._actionHandler &&
1613
+ !this._findCommand('help'));
1526
1614
 
1527
1615
  if (hasImplicitHelpCommand) {
1528
1616
  if (this._helpCommand === undefined) {
@@ -1668,14 +1756,18 @@ Expecting one of '${allowedValues.join("', '")}'`);
1668
1756
  * Register option if no conflicts found, or throw on conflict.
1669
1757
  *
1670
1758
  * @param {Option} option
1671
- * @api private
1759
+ * @private
1672
1760
  */
1673
1761
 
1674
1762
  _registerOption(option) {
1675
- const matchingOption = (option.short && this._findOption(option.short)) ||
1763
+ const matchingOption =
1764
+ (option.short && this._findOption(option.short)) ||
1676
1765
  (option.long && this._findOption(option.long));
1677
1766
  if (matchingOption) {
1678
- const matchingFlag = (option.long && this._findOption(option.long)) ? option.long : option.short;
1767
+ const matchingFlag =
1768
+ option.long && this._findOption(option.long)
1769
+ ? option.long
1770
+ : option.short;
1679
1771
  throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1680
1772
  - already used by option '${matchingOption.flags}'`);
1681
1773
  }
@@ -1688,7 +1780,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1688
1780
  * Register command if no conflicts found, or throw on conflict.
1689
1781
  *
1690
1782
  * @param {Command} command
1691
- * @api private
1783
+ * @private
1692
1784
  */
1693
1785
 
1694
1786
  _registerCommand(command) {
@@ -1696,11 +1788,15 @@ Expecting one of '${allowedValues.join("', '")}'`);
1696
1788
  return [cmd.name()].concat(cmd.aliases());
1697
1789
  };
1698
1790
 
1699
- const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1791
+ const alreadyUsed = knownBy(command).find((name) =>
1792
+ this._findCommand(name),
1793
+ );
1700
1794
  if (alreadyUsed) {
1701
1795
  const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
1702
1796
  const newCmd = knownBy(command).join('|');
1703
- throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1797
+ throw new Error(
1798
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`,
1799
+ );
1704
1800
  }
1705
1801
 
1706
1802
  this.commands.push(command);
@@ -1723,7 +1819,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
1723
1819
  // --no-foo is special and defaults foo to true, unless a --foo option is already defined
1724
1820
  const positiveLongFlag = option.long.replace(/^--no-/, '--');
1725
1821
  if (!this._findOption(positiveLongFlag)) {
1726
- this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');
1822
+ this.setOptionValueWithSource(
1823
+ name,
1824
+ option.defaultValue === undefined ? true : option.defaultValue,
1825
+ 'default',
1826
+ );
1727
1827
  }
1728
1828
  } else if (option.defaultValue !== undefined) {
1729
1829
  this.setOptionValueWithSource(name, option.defaultValue, 'default');
@@ -1776,11 +1876,14 @@ Expecting one of '${allowedValues.join("', '")}'`);
1776
1876
  /**
1777
1877
  * Internal implementation shared by .option() and .requiredOption()
1778
1878
  *
1879
+ * @return {Command} `this` command for chaining
1779
1880
  * @private
1780
1881
  */
1781
1882
  _optionEx(config, flags, description, fn, defaultValue) {
1782
1883
  if (typeof flags === 'object' && flags instanceof Option$2) {
1783
- throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');
1884
+ throw new Error(
1885
+ 'To add an Option object use addOption() instead of option() or requiredOption()',
1886
+ );
1784
1887
  }
1785
1888
  const option = this.createOption(flags, description);
1786
1889
  option.makeOptionMandatory(!!config.mandatory);
@@ -1828,20 +1931,26 @@ Expecting one of '${allowedValues.join("', '")}'`);
1828
1931
  }
1829
1932
 
1830
1933
  /**
1831
- * Add a required option which must have a value after parsing. This usually means
1832
- * the option must be specified on the command line. (Otherwise the same as .option().)
1833
- *
1834
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1835
- *
1836
- * @param {string} flags
1837
- * @param {string} [description]
1838
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1839
- * @param {*} [defaultValue]
1840
- * @return {Command} `this` command for chaining
1841
- */
1934
+ * Add a required option which must have a value after parsing. This usually means
1935
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1936
+ *
1937
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1938
+ *
1939
+ * @param {string} flags
1940
+ * @param {string} [description]
1941
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1942
+ * @param {*} [defaultValue]
1943
+ * @return {Command} `this` command for chaining
1944
+ */
1842
1945
 
1843
1946
  requiredOption(flags, description, parseArg, defaultValue) {
1844
- return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1947
+ return this._optionEx(
1948
+ { mandatory: true },
1949
+ flags,
1950
+ description,
1951
+ parseArg,
1952
+ defaultValue,
1953
+ );
1845
1954
  }
1846
1955
 
1847
1956
  /**
@@ -1852,7 +1961,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
1852
1961
  * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1853
1962
  * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1854
1963
  *
1855
- * @param {boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
1964
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1965
+ * @return {Command} `this` command for chaining
1856
1966
  */
1857
1967
  combineFlagAndOptionalValue(combine = true) {
1858
1968
  this._combineFlagAndOptionalValue = !!combine;
@@ -1862,8 +1972,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
1862
1972
  /**
1863
1973
  * Allow unknown options on the command line.
1864
1974
  *
1865
- * @param {boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
1866
- * for unknown options.
1975
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1976
+ * @return {Command} `this` command for chaining
1867
1977
  */
1868
1978
  allowUnknownOption(allowUnknown = true) {
1869
1979
  this._allowUnknownOption = !!allowUnknown;
@@ -1873,8 +1983,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
1873
1983
  /**
1874
1984
  * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1875
1985
  *
1876
- * @param {boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
1877
- * for excess arguments.
1986
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1987
+ * @return {Command} `this` command for chaining
1878
1988
  */
1879
1989
  allowExcessArguments(allowExcess = true) {
1880
1990
  this._allowExcessArguments = !!allowExcess;
@@ -1886,7 +1996,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
1886
1996
  * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1887
1997
  * The default behaviour is non-positional and global options may appear anywhere on the command line.
1888
1998
  *
1889
- * @param {boolean} [positional=true]
1999
+ * @param {boolean} [positional]
2000
+ * @return {Command} `this` command for chaining
1890
2001
  */
1891
2002
  enablePositionalOptions(positional = true) {
1892
2003
  this._enablePositionalOptions = !!positional;
@@ -1899,8 +2010,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
1899
2010
  * positional options to have been enabled on the program (parent commands).
1900
2011
  * The default behaviour is non-positional and options may appear before or after command-arguments.
1901
2012
  *
1902
- * @param {boolean} [passThrough=true]
1903
- * for unknown options.
2013
+ * @param {boolean} [passThrough] for unknown options.
2014
+ * @return {Command} `this` command for chaining
1904
2015
  */
1905
2016
  passThroughOptions(passThrough = true) {
1906
2017
  this._passThroughOptions = !!passThrough;
@@ -1913,25 +2024,33 @@ Expecting one of '${allowedValues.join("', '")}'`);
1913
2024
  */
1914
2025
 
1915
2026
  _checkForBrokenPassThrough() {
1916
- if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1917
- throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
2027
+ if (
2028
+ this.parent &&
2029
+ this._passThroughOptions &&
2030
+ !this.parent._enablePositionalOptions
2031
+ ) {
2032
+ throw new Error(
2033
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,
2034
+ );
1918
2035
  }
1919
2036
  }
1920
2037
 
1921
2038
  /**
1922
- * Whether to store option values as properties on command object,
1923
- * or store separately (specify false). In both cases the option values can be accessed using .opts().
1924
- *
1925
- * @param {boolean} [storeAsProperties=true]
1926
- * @return {Command} `this` command for chaining
1927
- */
2039
+ * Whether to store option values as properties on command object,
2040
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
2041
+ *
2042
+ * @param {boolean} [storeAsProperties=true]
2043
+ * @return {Command} `this` command for chaining
2044
+ */
1928
2045
 
1929
2046
  storeOptionsAsProperties(storeAsProperties = true) {
1930
2047
  if (this.options.length) {
1931
2048
  throw new Error('call .storeOptionsAsProperties() before adding options');
1932
2049
  }
1933
2050
  if (Object.keys(this._optionValues).length) {
1934
- throw new Error('call .storeOptionsAsProperties() before setting option values');
2051
+ throw new Error(
2052
+ 'call .storeOptionsAsProperties() before setting option values',
2053
+ );
1935
2054
  }
1936
2055
  this._storeOptionsAsProperties = !!storeAsProperties;
1937
2056
  return this;
@@ -1941,7 +2060,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1941
2060
  * Retrieve option value.
1942
2061
  *
1943
2062
  * @param {string} key
1944
- * @return {Object} value
2063
+ * @return {object} value
1945
2064
  */
1946
2065
 
1947
2066
  getOptionValue(key) {
@@ -1955,7 +2074,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1955
2074
  * Store option value.
1956
2075
  *
1957
2076
  * @param {string} key
1958
- * @param {Object} value
2077
+ * @param {object} value
1959
2078
  * @return {Command} `this` command for chaining
1960
2079
  */
1961
2080
 
@@ -1964,13 +2083,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
1964
2083
  }
1965
2084
 
1966
2085
  /**
1967
- * Store option value and where the value came from.
1968
- *
1969
- * @param {string} key
1970
- * @param {Object} value
1971
- * @param {string} source - expected values are default/config/env/cli/implied
1972
- * @return {Command} `this` command for chaining
1973
- */
2086
+ * Store option value and where the value came from.
2087
+ *
2088
+ * @param {string} key
2089
+ * @param {object} value
2090
+ * @param {string} source - expected values are default/config/env/cli/implied
2091
+ * @return {Command} `this` command for chaining
2092
+ */
1974
2093
 
1975
2094
  setOptionValueWithSource(key, value, source) {
1976
2095
  if (this._storeOptionsAsProperties) {
@@ -1983,24 +2102,24 @@ Expecting one of '${allowedValues.join("', '")}'`);
1983
2102
  }
1984
2103
 
1985
2104
  /**
1986
- * Get source of option value.
1987
- * Expected values are default | config | env | cli | implied
1988
- *
1989
- * @param {string} key
1990
- * @return {string}
1991
- */
2105
+ * Get source of option value.
2106
+ * Expected values are default | config | env | cli | implied
2107
+ *
2108
+ * @param {string} key
2109
+ * @return {string}
2110
+ */
1992
2111
 
1993
2112
  getOptionValueSource(key) {
1994
2113
  return this._optionValueSources[key];
1995
2114
  }
1996
2115
 
1997
2116
  /**
1998
- * Get source of option value. See also .optsWithGlobals().
1999
- * Expected values are default | config | env | cli | implied
2000
- *
2001
- * @param {string} key
2002
- * @return {string}
2003
- */
2117
+ * Get source of option value. See also .optsWithGlobals().
2118
+ * Expected values are default | config | env | cli | implied
2119
+ *
2120
+ * @param {string} key
2121
+ * @return {string}
2122
+ */
2004
2123
 
2005
2124
  getOptionValueSourceWithGlobals(key) {
2006
2125
  // global overwrites local, like optsWithGlobals
@@ -2026,17 +2145,30 @@ Expecting one of '${allowedValues.join("', '")}'`);
2026
2145
  }
2027
2146
  parseOptions = parseOptions || {};
2028
2147
 
2029
- // Default to using process.argv
2030
- if (argv === undefined) {
2031
- argv = process$1.argv;
2032
- // @ts-ignore: unknown property
2033
- if (process$1.versions && process$1.versions.electron) {
2148
+ // auto-detect argument conventions if nothing supplied
2149
+ if (argv === undefined && parseOptions.from === undefined) {
2150
+ if (process$1.versions?.electron) {
2034
2151
  parseOptions.from = 'electron';
2035
2152
  }
2153
+ // check node specific options for scenarios where user CLI args follow executable without scriptname
2154
+ const execArgv = process$1.execArgv ?? [];
2155
+ if (
2156
+ execArgv.includes('-e') ||
2157
+ execArgv.includes('--eval') ||
2158
+ execArgv.includes('-p') ||
2159
+ execArgv.includes('--print')
2160
+ ) {
2161
+ parseOptions.from = 'eval'; // internal usage, not documented
2162
+ }
2163
+ }
2164
+
2165
+ // default to using process.argv
2166
+ if (argv === undefined) {
2167
+ argv = process$1.argv;
2036
2168
  }
2037
2169
  this.rawArgs = argv.slice();
2038
2170
 
2039
- // make it a little easier for callers by supporting various argv conventions
2171
+ // extract the user args and scriptPath
2040
2172
  let userArgs;
2041
2173
  switch (parseOptions.from) {
2042
2174
  case undefined:
@@ -2045,7 +2177,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2045
2177
  userArgs = argv.slice(2);
2046
2178
  break;
2047
2179
  case 'electron':
2048
- // @ts-ignore: unknown property
2180
+ // @ts-ignore: because defaultApp is an unknown property
2049
2181
  if (process$1.defaultApp) {
2050
2182
  this._scriptPath = argv[1];
2051
2183
  userArgs = argv.slice(2);
@@ -2056,12 +2188,18 @@ Expecting one of '${allowedValues.join("', '")}'`);
2056
2188
  case 'user':
2057
2189
  userArgs = argv.slice(0);
2058
2190
  break;
2191
+ case 'eval':
2192
+ userArgs = argv.slice(1);
2193
+ break;
2059
2194
  default:
2060
- throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
2195
+ throw new Error(
2196
+ `unexpected parse option { from: '${parseOptions.from}' }`,
2197
+ );
2061
2198
  }
2062
2199
 
2063
2200
  // Find default name for program from arguments.
2064
- if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
2201
+ if (!this._name && this._scriptPath)
2202
+ this.nameFromFilename(this._scriptPath);
2065
2203
  this._name = this._name || 'program';
2066
2204
 
2067
2205
  return userArgs;
@@ -2070,16 +2208,22 @@ Expecting one of '${allowedValues.join("', '")}'`);
2070
2208
  /**
2071
2209
  * Parse `argv`, setting options and invoking commands when defined.
2072
2210
  *
2073
- * The default expectation is that the arguments are from node and have the application as argv[0]
2074
- * and the script being run in argv[1], with user parameters after that.
2211
+ * Use parseAsync instead of parse if any of your action handlers are async.
2212
+ *
2213
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2214
+ *
2215
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2216
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2217
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2218
+ * - `'user'`: just user arguments
2075
2219
  *
2076
2220
  * @example
2077
- * program.parse(process.argv);
2078
- * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
2221
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2222
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2079
2223
  * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2080
2224
  *
2081
2225
  * @param {string[]} [argv] - optional, defaults to process.argv
2082
- * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
2226
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2083
2227
  * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2084
2228
  * @return {Command} `this` command for chaining
2085
2229
  */
@@ -2094,18 +2238,20 @@ Expecting one of '${allowedValues.join("', '")}'`);
2094
2238
  /**
2095
2239
  * Parse `argv`, setting options and invoking commands when defined.
2096
2240
  *
2097
- * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
2241
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2098
2242
  *
2099
- * The default expectation is that the arguments are from node and have the application as argv[0]
2100
- * and the script being run in argv[1], with user parameters after that.
2243
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2244
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2245
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2246
+ * - `'user'`: just user arguments
2101
2247
  *
2102
2248
  * @example
2103
- * await program.parseAsync(process.argv);
2104
- * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
2249
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2250
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2105
2251
  * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2106
2252
  *
2107
2253
  * @param {string[]} [argv]
2108
- * @param {Object} [parseOptions]
2254
+ * @param {object} [parseOptions]
2109
2255
  * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2110
2256
  * @return {Promise}
2111
2257
  */
@@ -2137,7 +2283,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
2137
2283
  if (sourceExt.includes(path.extname(baseName))) return undefined;
2138
2284
 
2139
2285
  // Try all the extensions.
2140
- const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));
2286
+ const foundExt = sourceExt.find((ext) =>
2287
+ fs.existsSync(`${localBin}${ext}`),
2288
+ );
2141
2289
  if (foundExt) return `${localBin}${foundExt}`;
2142
2290
 
2143
2291
  return undefined;
@@ -2148,7 +2296,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2148
2296
  this._checkForConflictingOptions();
2149
2297
 
2150
2298
  // executableFile and executableDir might be full path, or just a name
2151
- let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2299
+ let executableFile =
2300
+ subcommand._executableFile || `${this._name}-${subcommand._name}`;
2152
2301
  let executableDir = this._executableDir || '';
2153
2302
  if (this._scriptPath) {
2154
2303
  let resolvedScriptPath; // resolve possible symlink for installed npm binary
@@ -2157,7 +2306,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
2157
2306
  } catch (err) {
2158
2307
  resolvedScriptPath = this._scriptPath;
2159
2308
  }
2160
- executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
2309
+ executableDir = path.resolve(
2310
+ path.dirname(resolvedScriptPath),
2311
+ executableDir,
2312
+ );
2161
2313
  }
2162
2314
 
2163
2315
  // Look for a local file in preference to a command in PATH.
@@ -2166,9 +2318,15 @@ Expecting one of '${allowedValues.join("', '")}'`);
2166
2318
 
2167
2319
  // Legacy search using prefix of script name instead of command name
2168
2320
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
2169
- const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
2321
+ const legacyName = path.basename(
2322
+ this._scriptPath,
2323
+ path.extname(this._scriptPath),
2324
+ );
2170
2325
  if (legacyName !== this._name) {
2171
- localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
2326
+ localFile = findFile(
2327
+ executableDir,
2328
+ `${legacyName}-${subcommand._name}`,
2329
+ );
2172
2330
  }
2173
2331
  }
2174
2332
  executableFile = localFile || executableFile;
@@ -2194,12 +2352,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
2194
2352
  proc = childProcess.spawn(process$1.execPath, args, { stdio: 'inherit' });
2195
2353
  }
2196
2354
 
2197
- if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn
2355
+ if (!proc.killed) {
2356
+ // testing mainly to avoid leak warnings during unit tests with mocked spawn
2198
2357
  const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
2199
2358
  signals.forEach((signal) => {
2200
- // @ts-ignore
2201
2359
  process$1.on(signal, () => {
2202
2360
  if (proc.killed === false && proc.exitCode === null) {
2361
+ // @ts-ignore because signals not typed to known strings
2203
2362
  proc.kill(signal);
2204
2363
  }
2205
2364
  });
@@ -2208,16 +2367,22 @@ Expecting one of '${allowedValues.join("', '")}'`);
2208
2367
 
2209
2368
  // By default terminate process when spawned process terminates.
2210
2369
  const exitCallback = this._exitCallback;
2211
- proc.on('close', (code, _signal) => {
2370
+ proc.on('close', (code) => {
2212
2371
  code = code ?? 1; // code is null if spawned process terminated due to a signal
2213
2372
  if (!exitCallback) {
2214
2373
  process$1.exit(code);
2215
2374
  } else {
2216
- exitCallback(new CommanderError$2(code, 'commander.executeSubCommandAsync', '(close)'));
2375
+ exitCallback(
2376
+ new CommanderError$2(
2377
+ code,
2378
+ 'commander.executeSubCommandAsync',
2379
+ '(close)',
2380
+ ),
2381
+ );
2217
2382
  }
2218
2383
  });
2219
2384
  proc.on('error', (err) => {
2220
- // @ts-ignore
2385
+ // @ts-ignore: because err.code is an unknown property
2221
2386
  if (err.code === 'ENOENT') {
2222
2387
  const executableDirMessage = executableDir
2223
2388
  ? `searched for local subcommand relative to directory '${executableDir}'`
@@ -2227,14 +2392,18 @@ Expecting one of '${allowedValues.join("', '")}'`);
2227
2392
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2228
2393
  - ${executableDirMessage}`;
2229
2394
  throw new Error(executableMissing);
2230
- // @ts-ignore
2395
+ // @ts-ignore: because err.code is an unknown property
2231
2396
  } else if (err.code === 'EACCES') {
2232
2397
  throw new Error(`'${executableFile}' not executable`);
2233
2398
  }
2234
2399
  if (!exitCallback) {
2235
2400
  process$1.exit(1);
2236
2401
  } else {
2237
- const wrappedError = new CommanderError$2(1, 'commander.executeSubCommandAsync', '(error)');
2402
+ const wrappedError = new CommanderError$2(
2403
+ 1,
2404
+ 'commander.executeSubCommandAsync',
2405
+ '(error)',
2406
+ );
2238
2407
  wrappedError.nestedError = err;
2239
2408
  exitCallback(wrappedError);
2240
2409
  }
@@ -2253,7 +2422,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
2253
2422
  if (!subCommand) this.help({ error: true });
2254
2423
 
2255
2424
  let promiseChain;
2256
- promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');
2425
+ promiseChain = this._chainOrCallSubCommandHook(
2426
+ promiseChain,
2427
+ subCommand,
2428
+ 'preSubcommand',
2429
+ );
2257
2430
  promiseChain = this._chainOrCall(promiseChain, () => {
2258
2431
  if (subCommand._executableHandler) {
2259
2432
  this._executeSubCommand(subCommand, operands.concat(unknown));
@@ -2281,9 +2454,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
2281
2454
  }
2282
2455
 
2283
2456
  // Fallback to parsing the help flag to invoke the help.
2284
- return this._dispatchSubcommand(subcommandName, [], [
2285
- this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'
2286
- ]);
2457
+ return this._dispatchSubcommand(
2458
+ subcommandName,
2459
+ [],
2460
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],
2461
+ );
2287
2462
  }
2288
2463
 
2289
2464
  /**
@@ -2300,7 +2475,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
2300
2475
  }
2301
2476
  });
2302
2477
  // too many
2303
- if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2478
+ if (
2479
+ this.registeredArguments.length > 0 &&
2480
+ this.registeredArguments[this.registeredArguments.length - 1].variadic
2481
+ ) {
2304
2482
  return;
2305
2483
  }
2306
2484
  if (this.args.length > this.registeredArguments.length) {
@@ -2320,7 +2498,12 @@ Expecting one of '${allowedValues.join("', '")}'`);
2320
2498
  let parsedValue = value;
2321
2499
  if (value !== null && argument.parseArg) {
2322
2500
  const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2323
- parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2501
+ parsedValue = this._callParseArg(
2502
+ argument,
2503
+ value,
2504
+ previous,
2505
+ invalidValueMessage,
2506
+ );
2324
2507
  }
2325
2508
  return parsedValue;
2326
2509
  };
@@ -2385,8 +2568,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2385
2568
  const hooks = [];
2386
2569
  this._getCommandAndAncestors()
2387
2570
  .reverse()
2388
- .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)
2389
- .forEach(hookedCommand => {
2571
+ .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)
2572
+ .forEach((hookedCommand) => {
2390
2573
  hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2391
2574
  hooks.push({ hookedCommand, callback });
2392
2575
  });
@@ -2442,14 +2625,26 @@ Expecting one of '${allowedValues.join("', '")}'`);
2442
2625
  if (operands && this._findCommand(operands[0])) {
2443
2626
  return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2444
2627
  }
2445
- if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2628
+ if (
2629
+ this._getHelpCommand() &&
2630
+ operands[0] === this._getHelpCommand().name()
2631
+ ) {
2446
2632
  return this._dispatchHelpCommand(operands[1]);
2447
2633
  }
2448
2634
  if (this._defaultCommandName) {
2449
2635
  this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command
2450
- return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2636
+ return this._dispatchSubcommand(
2637
+ this._defaultCommandName,
2638
+ operands,
2639
+ unknown,
2640
+ );
2451
2641
  }
2452
- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2642
+ if (
2643
+ this.commands.length &&
2644
+ this.args.length === 0 &&
2645
+ !this._actionHandler &&
2646
+ !this._defaultCommandName
2647
+ ) {
2453
2648
  // probably missing subcommand and no handler, user needs help (and exit)
2454
2649
  this.help({ error: true });
2455
2650
  }
@@ -2472,7 +2667,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
2472
2667
 
2473
2668
  let promiseChain;
2474
2669
  promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
2475
- promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2670
+ promiseChain = this._chainOrCall(promiseChain, () =>
2671
+ this._actionHandler(this.processedArgs),
2672
+ );
2476
2673
  if (this.parent) {
2477
2674
  promiseChain = this._chainOrCall(promiseChain, () => {
2478
2675
  this.parent.emit(commandEvent, operands, unknown); // legacy
@@ -2486,7 +2683,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2486
2683
  this._processArguments();
2487
2684
  this.parent.emit(commandEvent, operands, unknown); // legacy
2488
2685
  } else if (operands.length) {
2489
- if (this._findCommand('*')) { // legacy default command
2686
+ if (this._findCommand('*')) {
2687
+ // legacy default command
2490
2688
  return this._dispatchSubcommand('*', operands, unknown);
2491
2689
  }
2492
2690
  if (this.listenerCount('command:*')) {
@@ -2513,10 +2711,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
2513
2711
  * Find matching command.
2514
2712
  *
2515
2713
  * @private
2714
+ * @return {Command | undefined}
2516
2715
  */
2517
2716
  _findCommand(name) {
2518
2717
  if (!name) return undefined;
2519
- return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));
2718
+ return this.commands.find(
2719
+ (cmd) => cmd._name === name || cmd._aliases.includes(name),
2720
+ );
2520
2721
  }
2521
2722
 
2522
2723
  /**
@@ -2524,11 +2725,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
2524
2725
  *
2525
2726
  * @param {string} arg
2526
2727
  * @return {Option}
2527
- * @package internal use only
2728
+ * @package
2528
2729
  */
2529
2730
 
2530
2731
  _findOption(arg) {
2531
- return this.options.find(option => option.is(arg));
2732
+ return this.options.find((option) => option.is(arg));
2532
2733
  }
2533
2734
 
2534
2735
  /**
@@ -2542,7 +2743,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
2542
2743
  // Walk up hierarchy so can call in subcommand after checking for displaying help.
2543
2744
  this._getCommandAndAncestors().forEach((cmd) => {
2544
2745
  cmd.options.forEach((anOption) => {
2545
- if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {
2746
+ if (
2747
+ anOption.mandatory &&
2748
+ cmd.getOptionValue(anOption.attributeName()) === undefined
2749
+ ) {
2546
2750
  cmd.missingMandatoryOptionValue(anOption);
2547
2751
  }
2548
2752
  });
@@ -2555,23 +2759,21 @@ Expecting one of '${allowedValues.join("', '")}'`);
2555
2759
  * @private
2556
2760
  */
2557
2761
  _checkForConflictingLocalOptions() {
2558
- const definedNonDefaultOptions = this.options.filter(
2559
- (option) => {
2560
- const optionKey = option.attributeName();
2561
- if (this.getOptionValue(optionKey) === undefined) {
2562
- return false;
2563
- }
2564
- return this.getOptionValueSource(optionKey) !== 'default';
2762
+ const definedNonDefaultOptions = this.options.filter((option) => {
2763
+ const optionKey = option.attributeName();
2764
+ if (this.getOptionValue(optionKey) === undefined) {
2765
+ return false;
2565
2766
  }
2566
- );
2767
+ return this.getOptionValueSource(optionKey) !== 'default';
2768
+ });
2567
2769
 
2568
2770
  const optionsWithConflicting = definedNonDefaultOptions.filter(
2569
- (option) => option.conflictsWith.length > 0
2771
+ (option) => option.conflictsWith.length > 0,
2570
2772
  );
2571
2773
 
2572
2774
  optionsWithConflicting.forEach((option) => {
2573
2775
  const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>
2574
- option.conflictsWith.includes(defined.attributeName())
2776
+ option.conflictsWith.includes(defined.attributeName()),
2575
2777
  );
2576
2778
  if (conflictingAndDefined) {
2577
2779
  this._conflictingOption(option, conflictingAndDefined);
@@ -2651,7 +2853,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2651
2853
  value = args.shift();
2652
2854
  }
2653
2855
  this.emit(`option:${option.name()}`, value);
2654
- } else { // boolean flag
2856
+ } else {
2857
+ // boolean flag
2655
2858
  this.emit(`option:${option.name()}`);
2656
2859
  }
2657
2860
  activeVariadicOption = option.variadic ? option : null;
@@ -2663,7 +2866,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
2663
2866
  if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
2664
2867
  const option = this._findOption(`-${arg[1]}`);
2665
2868
  if (option) {
2666
- if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {
2869
+ if (
2870
+ option.required ||
2871
+ (option.optional && this._combineFlagAndOptionalValue)
2872
+ ) {
2667
2873
  // option with value following in same argument
2668
2874
  this.emit(`option:${option.name()}`, arg.slice(2));
2669
2875
  } else {
@@ -2694,12 +2900,19 @@ Expecting one of '${allowedValues.join("', '")}'`);
2694
2900
  }
2695
2901
 
2696
2902
  // If using positionalOptions, stop processing our options at subcommand.
2697
- if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2903
+ if (
2904
+ (this._enablePositionalOptions || this._passThroughOptions) &&
2905
+ operands.length === 0 &&
2906
+ unknown.length === 0
2907
+ ) {
2698
2908
  if (this._findCommand(arg)) {
2699
2909
  operands.push(arg);
2700
2910
  if (args.length > 0) unknown.push(...args);
2701
2911
  break;
2702
- } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2912
+ } else if (
2913
+ this._getHelpCommand() &&
2914
+ arg === this._getHelpCommand().name()
2915
+ ) {
2703
2916
  operands.push(arg);
2704
2917
  if (args.length > 0) operands.push(...args);
2705
2918
  break;
@@ -2727,7 +2940,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2727
2940
  /**
2728
2941
  * Return an object containing local option values as key-value pairs.
2729
2942
  *
2730
- * @return {Object}
2943
+ * @return {object}
2731
2944
  */
2732
2945
  opts() {
2733
2946
  if (this._storeOptionsAsProperties) {
@@ -2737,7 +2950,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2737
2950
 
2738
2951
  for (let i = 0; i < len; i++) {
2739
2952
  const key = this.options[i].attributeName();
2740
- result[key] = key === this._versionOptionName ? this._version : this[key];
2953
+ result[key] =
2954
+ key === this._versionOptionName ? this._version : this[key];
2741
2955
  }
2742
2956
  return result;
2743
2957
  }
@@ -2748,13 +2962,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
2748
2962
  /**
2749
2963
  * Return an object containing merged local and global option values as key-value pairs.
2750
2964
  *
2751
- * @return {Object}
2965
+ * @return {object}
2752
2966
  */
2753
2967
  optsWithGlobals() {
2754
2968
  // globals overwrite locals
2755
2969
  return this._getCommandAndAncestors().reduce(
2756
2970
  (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2757
- {}
2971
+ {},
2758
2972
  );
2759
2973
  }
2760
2974
 
@@ -2762,13 +2976,16 @@ Expecting one of '${allowedValues.join("', '")}'`);
2762
2976
  * Display error message and exit (or call exitOverride).
2763
2977
  *
2764
2978
  * @param {string} message
2765
- * @param {Object} [errorOptions]
2979
+ * @param {object} [errorOptions]
2766
2980
  * @param {string} [errorOptions.code] - an id string representing the error
2767
2981
  * @param {number} [errorOptions.exitCode] - used with process.exit
2768
2982
  */
2769
2983
  error(message, errorOptions) {
2770
2984
  // output handling
2771
- this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2985
+ this._outputConfiguration.outputError(
2986
+ `${message}\n`,
2987
+ this._outputConfiguration.writeErr,
2988
+ );
2772
2989
  if (typeof this._showHelpAfterError === 'string') {
2773
2990
  this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2774
2991
  } else if (this._showHelpAfterError) {
@@ -2794,11 +3011,18 @@ Expecting one of '${allowedValues.join("', '")}'`);
2794
3011
  if (option.envVar && option.envVar in process$1.env) {
2795
3012
  const optionKey = option.attributeName();
2796
3013
  // Priority check. Do not overwrite cli or options from unknown source (client-code).
2797
- if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {
2798
- if (option.required || option.optional) { // option can take a value
3014
+ if (
3015
+ this.getOptionValue(optionKey) === undefined ||
3016
+ ['default', 'config', 'env'].includes(
3017
+ this.getOptionValueSource(optionKey),
3018
+ )
3019
+ ) {
3020
+ if (option.required || option.optional) {
3021
+ // option can take a value
2799
3022
  // keep very simple, optional always takes value
2800
3023
  this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
2801
- } else { // boolean
3024
+ } else {
3025
+ // boolean
2802
3026
  // keep very simple, only care that envVar defined and not the value
2803
3027
  this.emit(`optionEnv:${option.name()}`);
2804
3028
  }
@@ -2815,17 +3039,30 @@ Expecting one of '${allowedValues.join("', '")}'`);
2815
3039
  _parseOptionsImplied() {
2816
3040
  const dualHelper = new DualOptions(this.options);
2817
3041
  const hasCustomOptionValue = (optionKey) => {
2818
- return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));
3042
+ return (
3043
+ this.getOptionValue(optionKey) !== undefined &&
3044
+ !['default', 'implied'].includes(this.getOptionValueSource(optionKey))
3045
+ );
2819
3046
  };
2820
3047
  this.options
2821
- .filter(option => (option.implied !== undefined) &&
2822
- hasCustomOptionValue(option.attributeName()) &&
2823
- dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))
3048
+ .filter(
3049
+ (option) =>
3050
+ option.implied !== undefined &&
3051
+ hasCustomOptionValue(option.attributeName()) &&
3052
+ dualHelper.valueFromOption(
3053
+ this.getOptionValue(option.attributeName()),
3054
+ option,
3055
+ ),
3056
+ )
2824
3057
  .forEach((option) => {
2825
3058
  Object.keys(option.implied)
2826
- .filter(impliedKey => !hasCustomOptionValue(impliedKey))
2827
- .forEach(impliedKey => {
2828
- this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');
3059
+ .filter((impliedKey) => !hasCustomOptionValue(impliedKey))
3060
+ .forEach((impliedKey) => {
3061
+ this.setOptionValueWithSource(
3062
+ impliedKey,
3063
+ option.implied[impliedKey],
3064
+ 'implied',
3065
+ );
2829
3066
  });
2830
3067
  });
2831
3068
  }
@@ -2879,12 +3116,18 @@ Expecting one of '${allowedValues.join("', '")}'`);
2879
3116
  const findBestOptionFromValue = (option) => {
2880
3117
  const optionKey = option.attributeName();
2881
3118
  const optionValue = this.getOptionValue(optionKey);
2882
- const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());
2883
- const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());
2884
- if (negativeOption && (
2885
- (negativeOption.presetArg === undefined && optionValue === false) ||
2886
- (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)
2887
- )) {
3119
+ const negativeOption = this.options.find(
3120
+ (target) => target.negate && optionKey === target.attributeName(),
3121
+ );
3122
+ const positiveOption = this.options.find(
3123
+ (target) => !target.negate && optionKey === target.attributeName(),
3124
+ );
3125
+ if (
3126
+ negativeOption &&
3127
+ ((negativeOption.presetArg === undefined && optionValue === false) ||
3128
+ (negativeOption.presetArg !== undefined &&
3129
+ optionValue === negativeOption.presetArg))
3130
+ ) {
2888
3131
  return negativeOption;
2889
3132
  }
2890
3133
  return positiveOption || option;
@@ -2918,11 +3161,14 @@ Expecting one of '${allowedValues.join("', '")}'`);
2918
3161
  if (flag.startsWith('--') && this._showSuggestionAfterError) {
2919
3162
  // Looping to pick up the global options too
2920
3163
  let candidateFlags = [];
3164
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
2921
3165
  let command = this;
2922
3166
  do {
2923
- const moreFlags = command.createHelp().visibleOptions(command)
2924
- .filter(option => option.long)
2925
- .map(option => option.long);
3167
+ const moreFlags = command
3168
+ .createHelp()
3169
+ .visibleOptions(command)
3170
+ .filter((option) => option.long)
3171
+ .map((option) => option.long);
2926
3172
  candidateFlags = candidateFlags.concat(moreFlags);
2927
3173
  command = command.parent;
2928
3174
  } while (command && !command._enablePositionalOptions);
@@ -2944,7 +3190,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2944
3190
  if (this._allowExcessArguments) return;
2945
3191
 
2946
3192
  const expected = this.registeredArguments.length;
2947
- const s = (expected === 1) ? '' : 's';
3193
+ const s = expected === 1 ? '' : 's';
2948
3194
  const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
2949
3195
  const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2950
3196
  this.error(message, { code: 'commander.excessArguments' });
@@ -2962,11 +3208,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
2962
3208
 
2963
3209
  if (this._showSuggestionAfterError) {
2964
3210
  const candidateNames = [];
2965
- this.createHelp().visibleCommands(this).forEach((command) => {
2966
- candidateNames.push(command.name());
2967
- // just visible alias
2968
- if (command.alias()) candidateNames.push(command.alias());
2969
- });
3211
+ this.createHelp()
3212
+ .visibleCommands(this)
3213
+ .forEach((command) => {
3214
+ candidateNames.push(command.name());
3215
+ // just visible alias
3216
+ if (command.alias()) candidateNames.push(command.alias());
3217
+ });
2970
3218
  suggestion = suggestSimilar(unknownName, candidateNames);
2971
3219
  }
2972
3220
 
@@ -3007,11 +3255,12 @@ Expecting one of '${allowedValues.join("', '")}'`);
3007
3255
  * Set the description.
3008
3256
  *
3009
3257
  * @param {string} [str]
3010
- * @param {Object} [argsDescription]
3258
+ * @param {object} [argsDescription]
3011
3259
  * @return {(string|Command)}
3012
3260
  */
3013
3261
  description(str, argsDescription) {
3014
- if (str === undefined && argsDescription === undefined) return this._description;
3262
+ if (str === undefined && argsDescription === undefined)
3263
+ return this._description;
3015
3264
  this._description = str;
3016
3265
  if (argsDescription) {
3017
3266
  this._argsDescription = argsDescription;
@@ -3044,18 +3293,27 @@ Expecting one of '${allowedValues.join("', '")}'`);
3044
3293
  if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
3045
3294
 
3046
3295
  /** @type {Command} */
3296
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
3047
3297
  let command = this;
3048
- if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
3298
+ if (
3299
+ this.commands.length !== 0 &&
3300
+ this.commands[this.commands.length - 1]._executableHandler
3301
+ ) {
3049
3302
  // assume adding alias for last added executable subcommand, rather than this
3050
3303
  command = this.commands[this.commands.length - 1];
3051
3304
  }
3052
3305
 
3053
- if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
3306
+ if (alias === command._name)
3307
+ throw new Error("Command alias can't be the same as its name");
3054
3308
  const matchingCommand = this.parent?._findCommand(alias);
3055
3309
  if (matchingCommand) {
3056
3310
  // c.f. _registerCommand
3057
- const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join('|');
3058
- throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
3311
+ const existingCmd = [matchingCommand.name()]
3312
+ .concat(matchingCommand.aliases())
3313
+ .join('|');
3314
+ throw new Error(
3315
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,
3316
+ );
3059
3317
  }
3060
3318
 
3061
3319
  command._aliases.push(alias);
@@ -3093,11 +3351,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
3093
3351
  const args = this.registeredArguments.map((arg) => {
3094
3352
  return humanReadableArgName(arg);
3095
3353
  });
3096
- return [].concat(
3097
- (this.options.length || (this._helpOption !== null) ? '[options]' : []),
3098
- (this.commands.length ? '[command]' : []),
3099
- (this.registeredArguments.length ? args : [])
3100
- ).join(' ');
3354
+ return []
3355
+ .concat(
3356
+ this.options.length || this._helpOption !== null ? '[options]' : [],
3357
+ this.commands.length ? '[command]' : [],
3358
+ this.registeredArguments.length ? args : [],
3359
+ )
3360
+ .join(' ');
3101
3361
  }
3102
3362
 
3103
3363
  this._usage = str;
@@ -3164,7 +3424,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
3164
3424
  helpInformation(contextOptions) {
3165
3425
  const helper = this.createHelp();
3166
3426
  if (helper.helpWidth === undefined) {
3167
- helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
3427
+ helper.helpWidth =
3428
+ contextOptions && contextOptions.error
3429
+ ? this._outputConfiguration.getErrHelpWidth()
3430
+ : this._outputConfiguration.getOutHelpWidth();
3168
3431
  }
3169
3432
  return helper.formatHelp(this, helper);
3170
3433
  }
@@ -3203,13 +3466,18 @@ Expecting one of '${allowedValues.join("', '")}'`);
3203
3466
  }
3204
3467
  const context = this._getHelpContext(contextOptions);
3205
3468
 
3206
- this._getCommandAndAncestors().reverse().forEach(command => command.emit('beforeAllHelp', context));
3469
+ this._getCommandAndAncestors()
3470
+ .reverse()
3471
+ .forEach((command) => command.emit('beforeAllHelp', context));
3207
3472
  this.emit('beforeHelp', context);
3208
3473
 
3209
3474
  let helpInformation = this.helpInformation(context);
3210
3475
  if (deprecatedCallback) {
3211
3476
  helpInformation = deprecatedCallback(helpInformation);
3212
- if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {
3477
+ if (
3478
+ typeof helpInformation !== 'string' &&
3479
+ !Buffer.isBuffer(helpInformation)
3480
+ ) {
3213
3481
  throw new Error('outputHelp callback must return a string or a Buffer');
3214
3482
  }
3215
3483
  }
@@ -3219,7 +3487,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
3219
3487
  this.emit(this._getHelpOption().long); // deprecated
3220
3488
  }
3221
3489
  this.emit('afterHelp', context);
3222
- this._getCommandAndAncestors().forEach(command => command.emit('afterAllHelp', context));
3490
+ this._getCommandAndAncestors().forEach((command) =>
3491
+ command.emit('afterAllHelp', context),
3492
+ );
3223
3493
  }
3224
3494
 
3225
3495
  /**
@@ -3259,7 +3529,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
3259
3529
  * Returns null if has been disabled with .helpOption(false).
3260
3530
  *
3261
3531
  * @returns {(Option | null)} the help option
3262
- * @package internal use only
3532
+ * @package
3263
3533
  */
3264
3534
  _getHelpOption() {
3265
3535
  // Lazy create help option on demand.
@@ -3292,7 +3562,12 @@ Expecting one of '${allowedValues.join("', '")}'`);
3292
3562
  help(contextOptions) {
3293
3563
  this.outputHelp(contextOptions);
3294
3564
  let exitCode = process$1.exitCode || 0;
3295
- if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {
3565
+ if (
3566
+ exitCode === 0 &&
3567
+ contextOptions &&
3568
+ typeof contextOptions !== 'function' &&
3569
+ contextOptions.error
3570
+ ) {
3296
3571
  exitCode = 1;
3297
3572
  }
3298
3573
  // message: do not have all displayed text available so only passing placeholder.
@@ -3340,7 +3615,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
3340
3615
 
3341
3616
  _outputHelpIfRequested(args) {
3342
3617
  const helpOption = this._getHelpOption();
3343
- const helpRequested = helpOption && args.find(arg => helpOption.is(arg));
3618
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3344
3619
  if (helpRequested) {
3345
3620
  this.outputHelp();
3346
3621
  // (Do not have all displayed text available so only passing placeholder.)
@@ -3373,7 +3648,9 @@ function incrementNodeInspectorPort(args) {
3373
3648
  if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3374
3649
  // e.g. --inspect
3375
3650
  debugOption = match[1];
3376
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3651
+ } else if (
3652
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null
3653
+ ) {
3377
3654
  debugOption = match[1];
3378
3655
  if (/^\d+$/.test(match[3])) {
3379
3656
  // e.g. --inspect=1234
@@ -3382,7 +3659,9 @@ function incrementNodeInspectorPort(args) {
3382
3659
  // e.g. --inspect=localhost
3383
3660
  debugHost = match[3];
3384
3661
  }
3385
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3662
+ } else if (
3663
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null
3664
+ ) {
3386
3665
  // e.g. --inspect=localhost:1234
3387
3666
  debugOption = match[1];
3388
3667
  debugHost = match[3];
@@ -3435,7 +3714,7 @@ const {
3435
3714
  Command,
3436
3715
  Argument,
3437
3716
  Option,
3438
- Help
3717
+ Help,
3439
3718
  } = commander;
3440
3719
 
3441
3720
  function genKey(b) {
@@ -3516,8 +3795,8 @@ function addKey(file, key, value) {
3516
3795
  else {
3517
3796
  content = line + '\n';
3518
3797
  }
3519
- if (!fs$1.existsSync(require$$2.dirname(file)))
3520
- fs$1.mkdirSync(require$$2.dirname(file), { recursive: true });
3798
+ if (!fs$1.existsSync(path$1.dirname(file)))
3799
+ fs$1.mkdirSync(path$1.dirname(file), { recursive: true });
3521
3800
  fs$1.writeFileSync(file, content);
3522
3801
  }
3523
3802
 
@@ -3531,8 +3810,8 @@ function createPhpFile(file, key) {
3531
3810
  const content = `<?php
3532
3811
  // clef de signature
3533
3812
  return "${key}";`;
3534
- if (!fs$1.existsSync(require$$2.dirname(file)))
3535
- fs$1.mkdirSync(require$$2.dirname(file), { recursive: true });
3813
+ if (!fs$1.existsSync(path$1.dirname(file)))
3814
+ fs$1.mkdirSync(path$1.dirname(file), { recursive: true });
3536
3815
  fs$1.writeFileSync(file, content);
3537
3816
  }
3538
3817
 
@@ -3549,7 +3828,7 @@ program
3549
3828
  .option('-v, --var <var>', 'Nom de la variable à ajouter', 'CAPY_SIGN_KEY')
3550
3829
  .action((options) => {
3551
3830
  const key = genKey();
3552
- const file = require$$2.resolve(process.cwd(), options.envFile);
3831
+ const file = path$1.resolve(process.cwd(), options.envFile);
3553
3832
  console.log('Génération de clé d\'API', key.hex);
3554
3833
  console.log('Ajout dans le fichier', file);
3555
3834
  addKey(file, options.var, key.hex);
@@ -3562,7 +3841,7 @@ program
3562
3841
  .option('-v, --var <var>', 'Nom de la variable à lire', 'CAPY_SIGN_KEY')
3563
3842
  .option('-o, --output-file <file>', 'Fichier php à écrire', 'dist/key.php')
3564
3843
  .action((options) => {
3565
- const file = require$$2.resolve(process.cwd(), options.envFile);
3844
+ const file = path$1.resolve(process.cwd(), options.envFile);
3566
3845
  const b = extractKey(file, options.var);
3567
3846
  if (b == null) {
3568
3847
  console.error('Impossible de lire la clé');
@@ -3570,7 +3849,7 @@ program
3570
3849
  }
3571
3850
  const key = genKey(b);
3572
3851
  console.log('Lecture de la clé d\'API', key.hex);
3573
- const outFile = require$$2.resolve(process.cwd(), options.outputFile);
3852
+ const outFile = path$1.resolve(process.cwd(), options.outputFile);
3574
3853
  console.log('Ecriture dans le fichier', outFile);
3575
3854
  createPhpFile(outFile, key.phpString);
3576
3855
  });