@catladder/cli 0.0.0-new-cli-80ac360a → 0.0.0-new-cli-81ed6546

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/bundles/catenv/index.js +4341 -27
  2. package/dist/bundles/cli/index.js +15872 -694
  3. package/dist/cli/src/apps/catenv/catenv.d.ts +1 -0
  4. package/dist/cli/src/apps/catenv/catenv.js +1 -1
  5. package/dist/cli/src/apps/catenv/catenv.js.map +1 -1
  6. package/dist/cli/src/apps/catenv/printVariables.js +0 -10
  7. package/dist/cli/src/apps/catenv/printVariables.js.map +1 -1
  8. package/dist/cli/src/catenv.js +13 -16
  9. package/dist/cli/src/catenv.js.map +1 -1
  10. package/dist/cli/src/commands/index.d.ts +3 -0
  11. package/dist/cli/src/commands/index.js +23 -1
  12. package/dist/cli/src/commands/index.js.map +1 -1
  13. package/dist/cli/src/commands/project/commandSecurityEvaluate.js +1 -1
  14. package/dist/cli/src/commands/project/commandSecurityEvaluate.js.map +1 -1
  15. package/dist/cli/src/commands/security/commandSecurityAuditCiJob.d.ts +27 -0
  16. package/dist/cli/src/commands/security/commandSecurityAuditCiJob.js +83 -0
  17. package/dist/cli/src/commands/security/commandSecurityAuditCiJob.js.map +1 -0
  18. package/dist/cli/src/commands/security/commandSecurityAuditCreate.d.ts +22 -0
  19. package/dist/cli/src/commands/security/commandSecurityAuditCreate.js +60 -0
  20. package/dist/cli/src/commands/security/commandSecurityAuditCreate.js.map +1 -0
  21. package/dist/cli/src/commands/security/commandSecurityAuditEvaluate.d.ts +7 -0
  22. package/dist/cli/src/commands/security/commandSecurityAuditEvaluate.js +35 -0
  23. package/dist/cli/src/commands/security/commandSecurityAuditEvaluate.js.map +1 -0
  24. package/dist/cli/src/security/auditDocument.js.map +1 -0
  25. package/dist/cli/src/security/createSecurityAuditMergeRequest.js.map +1 -0
  26. package/dist/cli/src/security/evaluateSecurityAudit.js.map +1 -0
  27. package/dist/pipeline/src/build/types.d.ts +1 -1
  28. package/dist/pipeline/src/constants.js +1 -1
  29. package/dist/pipeline/src/context/getEnvironmentVariables.d.ts +1 -1
  30. package/dist/pipeline/src/deploy/types/index.d.ts +2 -2
  31. package/dist/pipeline/src/types/config.d.ts +3 -3
  32. package/dist/tsconfig.tsbuildinfo +1 -1
  33. package/package.json +3 -6
  34. package/scripts/bundle +0 -2
  35. package/src/apps/catenv/catenv.ts +4 -2
  36. package/src/apps/catenv/printVariables.ts +0 -8
  37. package/src/catenv.ts +18 -19
  38. package/src/commands/index.ts +5 -0
  39. package/src/commands/project/commandSecurityEvaluate.ts +1 -1
  40. package/src/commands/security/commandSecurityAuditCiJob.ts +91 -0
  41. package/src/commands/security/commandSecurityAuditCreate.ts +58 -0
  42. package/src/commands/security/commandSecurityAuditEvaluate.ts +30 -0
  43. package/bin/catci +0 -3
  44. package/bin/catci-dev +0 -3
  45. package/dist/bundles/catci/index.js +0 -71714
  46. package/dist/cli/src/apps/catci/catci.d.ts +0 -1
  47. package/dist/cli/src/apps/catci/catci.js +0 -33
  48. package/dist/cli/src/apps/catci/catci.js.map +0 -1
  49. package/dist/cli/src/apps/catci/commands/security/auditDocument.js.map +0 -1
  50. package/dist/cli/src/apps/catci/commands/security/commands.d.ts +0 -2
  51. package/dist/cli/src/apps/catci/commands/security/commands.js +0 -118
  52. package/dist/cli/src/apps/catci/commands/security/commands.js.map +0 -1
  53. package/dist/cli/src/apps/catci/commands/security/createSecurityAuditMergeRequest.js.map +0 -1
  54. package/dist/cli/src/apps/catci/commands/security/evaluateSecurityAudit.js.map +0 -1
  55. package/dist/cli/src/catci.d.ts +0 -1
  56. package/dist/cli/src/catci.js +0 -7
  57. package/dist/cli/src/catci.js.map +0 -1
  58. package/src/apps/catci/catci.ts +0 -26
  59. package/src/apps/catci/commands/security/commands.ts +0 -161
  60. package/src/catci.ts +0 -3
  61. /package/dist/cli/src/{apps/catci/commands/security → security}/auditDocument.d.ts +0 -0
  62. /package/dist/cli/src/{apps/catci/commands/security → security}/auditDocument.js +0 -0
  63. /package/dist/cli/src/{apps/catci/commands/security → security}/createSecurityAuditMergeRequest.d.ts +0 -0
  64. /package/dist/cli/src/{apps/catci/commands/security → security}/createSecurityAuditMergeRequest.js +0 -0
  65. /package/dist/cli/src/{apps/catci/commands/security → security}/evaluateSecurityAudit.d.ts +0 -0
  66. /package/dist/cli/src/{apps/catci/commands/security → security}/evaluateSecurityAudit.js +0 -0
  67. /package/dist/cli/src/{apps/catci/commands/security → security}/topics.json +0 -0
  68. /package/src/{apps/catci/commands/security → security}/auditDocument.ts +0 -0
  69. /package/src/{apps/catci/commands/security → security}/createSecurityAuditMergeRequest.ts +0 -0
  70. /package/src/{apps/catci/commands/security → security}/evaluateSecurityAudit.ts +0 -0
  71. /package/src/{apps/catci/commands/security → security}/topics.json +0 -0
@@ -26,7 +26,7 @@ exports["default"] = async (choice, options) => {
26
26
  if (options === null || options === void 0 ? void 0 : options.verbose) {
27
27
  (0, verboseBanner_1.printVerboseBanner)();
28
28
  }
29
- await Promise.all([(0, pipeline_1.generatePipelineFiles)(context, (_a = config.pipelineType) !== null && _a !== void 0 ? _a : "gitlab"), (0, writeDotEnvFiles_1.writeDotEnvFiles)(context, choice), (0, writeEnvDTs_1.writeDTsFiles)(context, choice), (0, printVariables_1.printVariables)(context, choice)]);
29
+ await Promise.all([(0, pipeline_1.generatePipelineFiles)(context, (_a = config.pipelineType) !== null && _a !== void 0 ? _a : "gitlab"), (0, writeDotEnvFiles_1.writeDotEnvFiles)(context, choice), (0, writeEnvDTs_1.writeDTsFiles)(context, choice), (options === null || options === void 0 ? void 0 : options.printVariables) ? (0, printVariables_1.printVariables)(context, choice) : Promise.resolve()]);
30
30
  };
31
31
 
32
32
  /***/ }),
@@ -44,27 +44,17 @@ exports.printVariables = void 0;
44
44
  const getProjectConfig_1 = __nccwpck_require__(1);
45
45
  const utils_1 = __nccwpck_require__(1909);
46
46
  const getAllVariablesToPrint = async (config, choice) => {
47
- var _a;
48
47
  const {
49
48
  env,
50
49
  currentComponent
51
50
  } = await (0, utils_1.getCurrentComponentAndEnvFromChoice)(config, choice);
52
51
  if (currentComponent) {
53
- // don't print vars if dotenv is enabled
54
- if ((_a = config.components[currentComponent].dotEnv) !== null && _a !== void 0 ? _a : true) {
55
- return {};
56
- }
57
52
  return await (0, getProjectConfig_1.getEnvVarsResolved)(null, env, currentComponent);
58
53
  } else {
59
54
  // when in a monorep and not in a subapp, merge all env vars.
60
55
  // this is not 100% correct, but better than not exporting any vars at all
61
56
  // so we also add prefixed variants
62
57
  return await Object.keys(config.components).reduce(async (acc, componentName) => {
63
- var _a;
64
- // don't print vars if dotenv is enabled
65
- if ((_a = config.components[componentName].dotEnv) !== null && _a !== void 0 ? _a : true) {
66
- return await acc;
67
- }
68
58
  const subappvars = await (0, getProjectConfig_1.getEnvVarsResolved)(null, env, componentName);
69
59
  delete subappvars["_ALL_ENV_VAR_KEYS"];
70
60
  return {
@@ -285,24 +275,21 @@ var __importDefault = this && this.__importDefault || function (mod) {
285
275
  Object.defineProperty(exports, "__esModule", ({
286
276
  value: true
287
277
  }));
278
+ const commander_1 = __nccwpck_require__(395);
288
279
  const catenv_1 = __importDefault(__nccwpck_require__(6057));
289
280
  const parseChoice_1 = __nccwpck_require__(4272);
290
- const args = process.argv.slice(2);
291
- const helpFlags = ["--help", "-h", "help"];
292
- if (args.some(arg => helpFlags.includes(arg))) {
293
- const docLink = "https://git.panter.ch/catladder/catladder/-/blob/main/docs/1_VARS.md";
294
- console.log(`\nUsage: catenv [env|env:component] [-v|--verbose]\n\nEnv variable and catenv documentation:\n${docLink}`);
295
- process.exit(0);
296
- }
297
- const verbose = args.some(arg => arg === "-v" || arg === "--verbose");
298
- // choise arg is deprecated and will be removed in the future
299
- const choiceArg = args.find(arg => arg !== "-v" && arg !== "--verbose");
300
- (0, catenv_1.default)(choiceArg ? (0, parseChoice_1.parseChoice)(choiceArg) : null, {
301
- verbose
302
- }).then(() => {
303
- // we have to exit manually, because we have some file watches
304
- process.exit();
281
+ const packageInfos_1 = __importDefault(__nccwpck_require__(3568));
282
+ const program = new commander_1.Command();
283
+ program.name("catenv").description("Environment variable and pipeline generation via direnv").version(packageInfos_1.default.version).argument("[envComponent]", "env or env:component").option("-v, --verbose", "verbose output").action((envComponent, opts) => {
284
+ var _a;
285
+ (0, catenv_1.default)(envComponent ? (0, parseChoice_1.parseChoice)(envComponent) : null, {
286
+ verbose: (_a = opts.verbose) !== null && _a !== void 0 ? _a : false
287
+ }).then(() => {
288
+ // we have to exit manually, because we have some file watches
289
+ process.exit();
290
+ });
305
291
  });
292
+ program.parse();
306
293
 
307
294
  /***/ }),
308
295
 
@@ -558,6 +545,26 @@ exports.gitProjectInformation = gitProjectInformation;
558
545
 
559
546
  /***/ }),
560
547
 
548
+ /***/ 3568:
549
+ /***/ ((__unused_webpack_module, exports) => {
550
+
551
+ "use strict";
552
+
553
+
554
+ // we can't import the package.json directly, because the bundling process will inline it
555
+ // but the version is only set during deployement, when its already bundled
556
+ // instead we need to use require.main.path to get the path of the main module, which is actually the file in the bin
557
+ // this will point to the root package.json
558
+ var _a;
559
+ Object.defineProperty(exports, "__esModule", ({
560
+ value: true
561
+ }));
562
+ const path = ((_a = require.main) === null || _a === void 0 ? void 0 : _a.path) + "/../package.json";
563
+ const ownPkg = require(path);
564
+ exports["default"] = ownPkg;
565
+
566
+ /***/ }),
567
+
561
568
  /***/ 6172:
562
569
  /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
563
570
 
@@ -2807,7 +2814,7 @@ Object.defineProperty(exports, "__esModule", ({
2807
2814
  value: true
2808
2815
  }));
2809
2816
  exports.DOCKER_REGISTRY = exports.PIPELINE_IMAGE_TAG = void 0;
2810
- exports.PIPELINE_IMAGE_TAG = "new-cli-80ac360a" || 0;
2817
+ exports.PIPELINE_IMAGE_TAG = "new-cli-81ed6546" || 0;
2811
2818
  exports.DOCKER_REGISTRY = "git.panter.ch:5001/catladder/catladder" || 0;
2812
2819
 
2813
2820
  /***/ }),
@@ -41407,6 +41414,46 @@ module.exports = require("https");
41407
41414
 
41408
41415
  /***/ }),
41409
41416
 
41417
+ /***/ 1421:
41418
+ /***/ ((module) => {
41419
+
41420
+ "use strict";
41421
+ module.exports = require("node:child_process");
41422
+
41423
+ /***/ }),
41424
+
41425
+ /***/ 8474:
41426
+ /***/ ((module) => {
41427
+
41428
+ "use strict";
41429
+ module.exports = require("node:events");
41430
+
41431
+ /***/ }),
41432
+
41433
+ /***/ 3024:
41434
+ /***/ ((module) => {
41435
+
41436
+ "use strict";
41437
+ module.exports = require("node:fs");
41438
+
41439
+ /***/ }),
41440
+
41441
+ /***/ 6760:
41442
+ /***/ ((module) => {
41443
+
41444
+ "use strict";
41445
+ module.exports = require("node:path");
41446
+
41447
+ /***/ }),
41448
+
41449
+ /***/ 1708:
41450
+ /***/ ((module) => {
41451
+
41452
+ "use strict";
41453
+ module.exports = require("node:process");
41454
+
41455
+ /***/ }),
41456
+
41410
41457
  /***/ 857:
41411
41458
  /***/ ((module) => {
41412
41459
 
@@ -41477,6 +41524,4273 @@ module.exports = require("util");
41477
41524
  "use strict";
41478
41525
  module.exports = require("zlib");
41479
41526
 
41527
+ /***/ }),
41528
+
41529
+ /***/ 395:
41530
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
41531
+
41532
+ const { Argument } = __nccwpck_require__(4100);
41533
+ const { Command } = __nccwpck_require__(6986);
41534
+ const { CommanderError, InvalidArgumentError } = __nccwpck_require__(9073);
41535
+ const { Help } = __nccwpck_require__(5632);
41536
+ const { Option } = __nccwpck_require__(7546);
41537
+
41538
+ exports.program = new Command();
41539
+
41540
+ exports.createCommand = (name) => new Command(name);
41541
+ exports.createOption = (flags, description) => new Option(flags, description);
41542
+ exports.createArgument = (name, description) => new Argument(name, description);
41543
+
41544
+ /**
41545
+ * Expose classes
41546
+ */
41547
+
41548
+ exports.Command = Command;
41549
+ exports.Option = Option;
41550
+ exports.Argument = Argument;
41551
+ exports.Help = Help;
41552
+
41553
+ exports.CommanderError = CommanderError;
41554
+ exports.InvalidArgumentError = InvalidArgumentError;
41555
+ exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated
41556
+
41557
+
41558
+ /***/ }),
41559
+
41560
+ /***/ 4100:
41561
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
41562
+
41563
+ const { InvalidArgumentError } = __nccwpck_require__(9073);
41564
+
41565
+ class Argument {
41566
+ /**
41567
+ * Initialize a new command argument with the given name and description.
41568
+ * The default is that the argument is required, and you can explicitly
41569
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
41570
+ *
41571
+ * @param {string} name
41572
+ * @param {string} [description]
41573
+ */
41574
+
41575
+ constructor(name, description) {
41576
+ this.description = description || '';
41577
+ this.variadic = false;
41578
+ this.parseArg = undefined;
41579
+ this.defaultValue = undefined;
41580
+ this.defaultValueDescription = undefined;
41581
+ this.argChoices = undefined;
41582
+
41583
+ switch (name[0]) {
41584
+ case '<': // e.g. <required>
41585
+ this.required = true;
41586
+ this._name = name.slice(1, -1);
41587
+ break;
41588
+ case '[': // e.g. [optional]
41589
+ this.required = false;
41590
+ this._name = name.slice(1, -1);
41591
+ break;
41592
+ default:
41593
+ this.required = true;
41594
+ this._name = name;
41595
+ break;
41596
+ }
41597
+
41598
+ if (this._name.endsWith('...')) {
41599
+ this.variadic = true;
41600
+ this._name = this._name.slice(0, -3);
41601
+ }
41602
+ }
41603
+
41604
+ /**
41605
+ * Return argument name.
41606
+ *
41607
+ * @return {string}
41608
+ */
41609
+
41610
+ name() {
41611
+ return this._name;
41612
+ }
41613
+
41614
+ /**
41615
+ * @package
41616
+ */
41617
+
41618
+ _collectValue(value, previous) {
41619
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
41620
+ return [value];
41621
+ }
41622
+
41623
+ previous.push(value);
41624
+ return previous;
41625
+ }
41626
+
41627
+ /**
41628
+ * Set the default value, and optionally supply the description to be displayed in the help.
41629
+ *
41630
+ * @param {*} value
41631
+ * @param {string} [description]
41632
+ * @return {Argument}
41633
+ */
41634
+
41635
+ default(value, description) {
41636
+ this.defaultValue = value;
41637
+ this.defaultValueDescription = description;
41638
+ return this;
41639
+ }
41640
+
41641
+ /**
41642
+ * Set the custom handler for processing CLI command arguments into argument values.
41643
+ *
41644
+ * @param {Function} [fn]
41645
+ * @return {Argument}
41646
+ */
41647
+
41648
+ argParser(fn) {
41649
+ this.parseArg = fn;
41650
+ return this;
41651
+ }
41652
+
41653
+ /**
41654
+ * Only allow argument value to be one of choices.
41655
+ *
41656
+ * @param {string[]} values
41657
+ * @return {Argument}
41658
+ */
41659
+
41660
+ choices(values) {
41661
+ this.argChoices = values.slice();
41662
+ this.parseArg = (arg, previous) => {
41663
+ if (!this.argChoices.includes(arg)) {
41664
+ throw new InvalidArgumentError(
41665
+ `Allowed choices are ${this.argChoices.join(', ')}.`,
41666
+ );
41667
+ }
41668
+ if (this.variadic) {
41669
+ return this._collectValue(arg, previous);
41670
+ }
41671
+ return arg;
41672
+ };
41673
+ return this;
41674
+ }
41675
+
41676
+ /**
41677
+ * Make argument required.
41678
+ *
41679
+ * @returns {Argument}
41680
+ */
41681
+ argRequired() {
41682
+ this.required = true;
41683
+ return this;
41684
+ }
41685
+
41686
+ /**
41687
+ * Make argument optional.
41688
+ *
41689
+ * @returns {Argument}
41690
+ */
41691
+ argOptional() {
41692
+ this.required = false;
41693
+ return this;
41694
+ }
41695
+ }
41696
+
41697
+ /**
41698
+ * Takes an argument and returns its human readable equivalent for help usage.
41699
+ *
41700
+ * @param {Argument} arg
41701
+ * @return {string}
41702
+ * @private
41703
+ */
41704
+
41705
+ function humanReadableArgName(arg) {
41706
+ const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
41707
+
41708
+ return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
41709
+ }
41710
+
41711
+ exports.Argument = Argument;
41712
+ exports.humanReadableArgName = humanReadableArgName;
41713
+
41714
+
41715
+ /***/ }),
41716
+
41717
+ /***/ 6986:
41718
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
41719
+
41720
+ const EventEmitter = (__nccwpck_require__(8474).EventEmitter);
41721
+ const childProcess = __nccwpck_require__(1421);
41722
+ const path = __nccwpck_require__(6760);
41723
+ const fs = __nccwpck_require__(3024);
41724
+ const process = __nccwpck_require__(1708);
41725
+
41726
+ const { Argument, humanReadableArgName } = __nccwpck_require__(4100);
41727
+ const { CommanderError } = __nccwpck_require__(9073);
41728
+ const { Help, stripColor } = __nccwpck_require__(5632);
41729
+ const { Option, DualOptions } = __nccwpck_require__(7546);
41730
+ const { suggestSimilar } = __nccwpck_require__(2044);
41731
+
41732
+ class Command extends EventEmitter {
41733
+ /**
41734
+ * Initialize a new `Command`.
41735
+ *
41736
+ * @param {string} [name]
41737
+ */
41738
+
41739
+ constructor(name) {
41740
+ super();
41741
+ /** @type {Command[]} */
41742
+ this.commands = [];
41743
+ /** @type {Option[]} */
41744
+ this.options = [];
41745
+ this.parent = null;
41746
+ this._allowUnknownOption = false;
41747
+ this._allowExcessArguments = false;
41748
+ /** @type {Argument[]} */
41749
+ this.registeredArguments = [];
41750
+ this._args = this.registeredArguments; // deprecated old name
41751
+ /** @type {string[]} */
41752
+ this.args = []; // cli args with options removed
41753
+ this.rawArgs = [];
41754
+ this.processedArgs = []; // like .args but after custom processing and collecting variadic
41755
+ this._scriptPath = null;
41756
+ this._name = name || '';
41757
+ this._optionValues = {};
41758
+ this._optionValueSources = {}; // default, env, cli etc
41759
+ this._storeOptionsAsProperties = false;
41760
+ this._actionHandler = null;
41761
+ this._executableHandler = false;
41762
+ this._executableFile = null; // custom name for executable
41763
+ this._executableDir = null; // custom search directory for subcommands
41764
+ this._defaultCommandName = null;
41765
+ this._exitCallback = null;
41766
+ this._aliases = [];
41767
+ this._combineFlagAndOptionalValue = true;
41768
+ this._description = '';
41769
+ this._summary = '';
41770
+ this._argsDescription = undefined; // legacy
41771
+ this._enablePositionalOptions = false;
41772
+ this._passThroughOptions = false;
41773
+ this._lifeCycleHooks = {}; // a hash of arrays
41774
+ /** @type {(boolean | string)} */
41775
+ this._showHelpAfterError = false;
41776
+ this._showSuggestionAfterError = true;
41777
+ this._savedState = null; // used in save/restoreStateBeforeParse
41778
+
41779
+ // see configureOutput() for docs
41780
+ this._outputConfiguration = {
41781
+ writeOut: (str) => process.stdout.write(str),
41782
+ writeErr: (str) => process.stderr.write(str),
41783
+ outputError: (str, write) => write(str),
41784
+ getOutHelpWidth: () =>
41785
+ process.stdout.isTTY ? process.stdout.columns : undefined,
41786
+ getErrHelpWidth: () =>
41787
+ process.stderr.isTTY ? process.stderr.columns : undefined,
41788
+ getOutHasColors: () =>
41789
+ useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),
41790
+ getErrHasColors: () =>
41791
+ useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),
41792
+ stripColor: (str) => stripColor(str),
41793
+ };
41794
+
41795
+ this._hidden = false;
41796
+ /** @type {(Option | null | undefined)} */
41797
+ this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.
41798
+ this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited
41799
+ /** @type {Command} */
41800
+ this._helpCommand = undefined; // lazy initialised, inherited
41801
+ this._helpConfiguration = {};
41802
+ /** @type {string | undefined} */
41803
+ this._helpGroupHeading = undefined; // soft initialised when added to parent
41804
+ /** @type {string | undefined} */
41805
+ this._defaultCommandGroup = undefined;
41806
+ /** @type {string | undefined} */
41807
+ this._defaultOptionGroup = undefined;
41808
+ }
41809
+
41810
+ /**
41811
+ * Copy settings that are useful to have in common across root command and subcommands.
41812
+ *
41813
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
41814
+ *
41815
+ * @param {Command} sourceCommand
41816
+ * @return {Command} `this` command for chaining
41817
+ */
41818
+ copyInheritedSettings(sourceCommand) {
41819
+ this._outputConfiguration = sourceCommand._outputConfiguration;
41820
+ this._helpOption = sourceCommand._helpOption;
41821
+ this._helpCommand = sourceCommand._helpCommand;
41822
+ this._helpConfiguration = sourceCommand._helpConfiguration;
41823
+ this._exitCallback = sourceCommand._exitCallback;
41824
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
41825
+ this._combineFlagAndOptionalValue =
41826
+ sourceCommand._combineFlagAndOptionalValue;
41827
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
41828
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
41829
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
41830
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
41831
+
41832
+ return this;
41833
+ }
41834
+
41835
+ /**
41836
+ * @returns {Command[]}
41837
+ * @private
41838
+ */
41839
+
41840
+ _getCommandAndAncestors() {
41841
+ const result = [];
41842
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
41843
+ for (let command = this; command; command = command.parent) {
41844
+ result.push(command);
41845
+ }
41846
+ return result;
41847
+ }
41848
+
41849
+ /**
41850
+ * Define a command.
41851
+ *
41852
+ * There are two styles of command: pay attention to where to put the description.
41853
+ *
41854
+ * @example
41855
+ * // Command implemented using action handler (description is supplied separately to `.command`)
41856
+ * program
41857
+ * .command('clone <source> [destination]')
41858
+ * .description('clone a repository into a newly created directory')
41859
+ * .action((source, destination) => {
41860
+ * console.log('clone command called');
41861
+ * });
41862
+ *
41863
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
41864
+ * program
41865
+ * .command('start <service>', 'start named service')
41866
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
41867
+ *
41868
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
41869
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
41870
+ * @param {object} [execOpts] - configuration options (for executable)
41871
+ * @return {Command} returns new command for action handler, or `this` for executable command
41872
+ */
41873
+
41874
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
41875
+ let desc = actionOptsOrExecDesc;
41876
+ let opts = execOpts;
41877
+ if (typeof desc === 'object' && desc !== null) {
41878
+ opts = desc;
41879
+ desc = null;
41880
+ }
41881
+ opts = opts || {};
41882
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
41883
+
41884
+ const cmd = this.createCommand(name);
41885
+ if (desc) {
41886
+ cmd.description(desc);
41887
+ cmd._executableHandler = true;
41888
+ }
41889
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
41890
+ cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
41891
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
41892
+ if (args) cmd.arguments(args);
41893
+ this._registerCommand(cmd);
41894
+ cmd.parent = this;
41895
+ cmd.copyInheritedSettings(this);
41896
+
41897
+ if (desc) return this;
41898
+ return cmd;
41899
+ }
41900
+
41901
+ /**
41902
+ * Factory routine to create a new unattached command.
41903
+ *
41904
+ * See .command() for creating an attached subcommand, which uses this routine to
41905
+ * create the command. You can override createCommand to customise subcommands.
41906
+ *
41907
+ * @param {string} [name]
41908
+ * @return {Command} new command
41909
+ */
41910
+
41911
+ createCommand(name) {
41912
+ return new Command(name);
41913
+ }
41914
+
41915
+ /**
41916
+ * You can customise the help with a subclass of Help by overriding createHelp,
41917
+ * or by overriding Help properties using configureHelp().
41918
+ *
41919
+ * @return {Help}
41920
+ */
41921
+
41922
+ createHelp() {
41923
+ return Object.assign(new Help(), this.configureHelp());
41924
+ }
41925
+
41926
+ /**
41927
+ * You can customise the help by overriding Help properties using configureHelp(),
41928
+ * or with a subclass of Help by overriding createHelp().
41929
+ *
41930
+ * @param {object} [configuration] - configuration options
41931
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
41932
+ */
41933
+
41934
+ configureHelp(configuration) {
41935
+ if (configuration === undefined) return this._helpConfiguration;
41936
+
41937
+ this._helpConfiguration = configuration;
41938
+ return this;
41939
+ }
41940
+
41941
+ /**
41942
+ * The default output goes to stdout and stderr. You can customise this for special
41943
+ * applications. You can also customise the display of errors by overriding outputError.
41944
+ *
41945
+ * The configuration properties are all functions:
41946
+ *
41947
+ * // change how output being written, defaults to stdout and stderr
41948
+ * writeOut(str)
41949
+ * writeErr(str)
41950
+ * // change how output being written for errors, defaults to writeErr
41951
+ * outputError(str, write) // used for displaying errors and not used for displaying help
41952
+ * // specify width for wrapping help
41953
+ * getOutHelpWidth()
41954
+ * getErrHelpWidth()
41955
+ * // color support, currently only used with Help
41956
+ * getOutHasColors()
41957
+ * getErrHasColors()
41958
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
41959
+ *
41960
+ * @param {object} [configuration] - configuration options
41961
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
41962
+ */
41963
+
41964
+ configureOutput(configuration) {
41965
+ if (configuration === undefined) return this._outputConfiguration;
41966
+
41967
+ this._outputConfiguration = {
41968
+ ...this._outputConfiguration,
41969
+ ...configuration,
41970
+ };
41971
+ return this;
41972
+ }
41973
+
41974
+ /**
41975
+ * Display the help or a custom message after an error occurs.
41976
+ *
41977
+ * @param {(boolean|string)} [displayHelp]
41978
+ * @return {Command} `this` command for chaining
41979
+ */
41980
+ showHelpAfterError(displayHelp = true) {
41981
+ if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
41982
+ this._showHelpAfterError = displayHelp;
41983
+ return this;
41984
+ }
41985
+
41986
+ /**
41987
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
41988
+ *
41989
+ * @param {boolean} [displaySuggestion]
41990
+ * @return {Command} `this` command for chaining
41991
+ */
41992
+ showSuggestionAfterError(displaySuggestion = true) {
41993
+ this._showSuggestionAfterError = !!displaySuggestion;
41994
+ return this;
41995
+ }
41996
+
41997
+ /**
41998
+ * Add a prepared subcommand.
41999
+ *
42000
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
42001
+ *
42002
+ * @param {Command} cmd - new subcommand
42003
+ * @param {object} [opts] - configuration options
42004
+ * @return {Command} `this` command for chaining
42005
+ */
42006
+
42007
+ addCommand(cmd, opts) {
42008
+ if (!cmd._name) {
42009
+ throw new Error(`Command passed to .addCommand() must have a name
42010
+ - specify the name in Command constructor or using .name()`);
42011
+ }
42012
+
42013
+ opts = opts || {};
42014
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
42015
+ if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
42016
+
42017
+ this._registerCommand(cmd);
42018
+ cmd.parent = this;
42019
+ cmd._checkForBrokenPassThrough();
42020
+
42021
+ return this;
42022
+ }
42023
+
42024
+ /**
42025
+ * Factory routine to create a new unattached argument.
42026
+ *
42027
+ * See .argument() for creating an attached argument, which uses this routine to
42028
+ * create the argument. You can override createArgument to return a custom argument.
42029
+ *
42030
+ * @param {string} name
42031
+ * @param {string} [description]
42032
+ * @return {Argument} new argument
42033
+ */
42034
+
42035
+ createArgument(name, description) {
42036
+ return new Argument(name, description);
42037
+ }
42038
+
42039
+ /**
42040
+ * Define argument syntax for command.
42041
+ *
42042
+ * The default is that the argument is required, and you can explicitly
42043
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
42044
+ *
42045
+ * @example
42046
+ * program.argument('<input-file>');
42047
+ * program.argument('[output-file]');
42048
+ *
42049
+ * @param {string} name
42050
+ * @param {string} [description]
42051
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
42052
+ * @param {*} [defaultValue]
42053
+ * @return {Command} `this` command for chaining
42054
+ */
42055
+ argument(name, description, parseArg, defaultValue) {
42056
+ const argument = this.createArgument(name, description);
42057
+ if (typeof parseArg === 'function') {
42058
+ argument.default(defaultValue).argParser(parseArg);
42059
+ } else {
42060
+ argument.default(parseArg);
42061
+ }
42062
+ this.addArgument(argument);
42063
+ return this;
42064
+ }
42065
+
42066
+ /**
42067
+ * Define argument syntax for command, adding multiple at once (without descriptions).
42068
+ *
42069
+ * See also .argument().
42070
+ *
42071
+ * @example
42072
+ * program.arguments('<cmd> [env]');
42073
+ *
42074
+ * @param {string} names
42075
+ * @return {Command} `this` command for chaining
42076
+ */
42077
+
42078
+ arguments(names) {
42079
+ names
42080
+ .trim()
42081
+ .split(/ +/)
42082
+ .forEach((detail) => {
42083
+ this.argument(detail);
42084
+ });
42085
+ return this;
42086
+ }
42087
+
42088
+ /**
42089
+ * Define argument syntax for command, adding a prepared argument.
42090
+ *
42091
+ * @param {Argument} argument
42092
+ * @return {Command} `this` command for chaining
42093
+ */
42094
+ addArgument(argument) {
42095
+ const previousArgument = this.registeredArguments.slice(-1)[0];
42096
+ if (previousArgument?.variadic) {
42097
+ throw new Error(
42098
+ `only the last argument can be variadic '${previousArgument.name()}'`,
42099
+ );
42100
+ }
42101
+ if (
42102
+ argument.required &&
42103
+ argument.defaultValue !== undefined &&
42104
+ argument.parseArg === undefined
42105
+ ) {
42106
+ throw new Error(
42107
+ `a default value for a required argument is never used: '${argument.name()}'`,
42108
+ );
42109
+ }
42110
+ this.registeredArguments.push(argument);
42111
+ return this;
42112
+ }
42113
+
42114
+ /**
42115
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
42116
+ *
42117
+ * @example
42118
+ * program.helpCommand('help [cmd]');
42119
+ * program.helpCommand('help [cmd]', 'show help');
42120
+ * program.helpCommand(false); // suppress default help command
42121
+ * program.helpCommand(true); // add help command even if no subcommands
42122
+ *
42123
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
42124
+ * @param {string} [description] - custom description
42125
+ * @return {Command} `this` command for chaining
42126
+ */
42127
+
42128
+ helpCommand(enableOrNameAndArgs, description) {
42129
+ if (typeof enableOrNameAndArgs === 'boolean') {
42130
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
42131
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
42132
+ // make the command to store the group
42133
+ this._initCommandGroup(this._getHelpCommand());
42134
+ }
42135
+ return this;
42136
+ }
42137
+
42138
+ const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';
42139
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
42140
+ const helpDescription = description ?? 'display help for command';
42141
+
42142
+ const helpCommand = this.createCommand(helpName);
42143
+ helpCommand.helpOption(false);
42144
+ if (helpArgs) helpCommand.arguments(helpArgs);
42145
+ if (helpDescription) helpCommand.description(helpDescription);
42146
+
42147
+ this._addImplicitHelpCommand = true;
42148
+ this._helpCommand = helpCommand;
42149
+ // init group unless lazy create
42150
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
42151
+
42152
+ return this;
42153
+ }
42154
+
42155
+ /**
42156
+ * Add prepared custom help command.
42157
+ *
42158
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
42159
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
42160
+ * @return {Command} `this` command for chaining
42161
+ */
42162
+ addHelpCommand(helpCommand, deprecatedDescription) {
42163
+ // If not passed an object, call through to helpCommand for backwards compatibility,
42164
+ // as addHelpCommand was originally used like helpCommand is now.
42165
+ if (typeof helpCommand !== 'object') {
42166
+ this.helpCommand(helpCommand, deprecatedDescription);
42167
+ return this;
42168
+ }
42169
+
42170
+ this._addImplicitHelpCommand = true;
42171
+ this._helpCommand = helpCommand;
42172
+ this._initCommandGroup(helpCommand);
42173
+ return this;
42174
+ }
42175
+
42176
+ /**
42177
+ * Lazy create help command.
42178
+ *
42179
+ * @return {(Command|null)}
42180
+ * @package
42181
+ */
42182
+ _getHelpCommand() {
42183
+ const hasImplicitHelpCommand =
42184
+ this._addImplicitHelpCommand ??
42185
+ (this.commands.length &&
42186
+ !this._actionHandler &&
42187
+ !this._findCommand('help'));
42188
+
42189
+ if (hasImplicitHelpCommand) {
42190
+ if (this._helpCommand === undefined) {
42191
+ this.helpCommand(undefined, undefined); // use default name and description
42192
+ }
42193
+ return this._helpCommand;
42194
+ }
42195
+ return null;
42196
+ }
42197
+
42198
+ /**
42199
+ * Add hook for life cycle event.
42200
+ *
42201
+ * @param {string} event
42202
+ * @param {Function} listener
42203
+ * @return {Command} `this` command for chaining
42204
+ */
42205
+
42206
+ hook(event, listener) {
42207
+ const allowedValues = ['preSubcommand', 'preAction', 'postAction'];
42208
+ if (!allowedValues.includes(event)) {
42209
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
42210
+ Expecting one of '${allowedValues.join("', '")}'`);
42211
+ }
42212
+ if (this._lifeCycleHooks[event]) {
42213
+ this._lifeCycleHooks[event].push(listener);
42214
+ } else {
42215
+ this._lifeCycleHooks[event] = [listener];
42216
+ }
42217
+ return this;
42218
+ }
42219
+
42220
+ /**
42221
+ * Register callback to use as replacement for calling process.exit.
42222
+ *
42223
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
42224
+ * @return {Command} `this` command for chaining
42225
+ */
42226
+
42227
+ exitOverride(fn) {
42228
+ if (fn) {
42229
+ this._exitCallback = fn;
42230
+ } else {
42231
+ this._exitCallback = (err) => {
42232
+ if (err.code !== 'commander.executeSubCommandAsync') {
42233
+ throw err;
42234
+ } else {
42235
+ // Async callback from spawn events, not useful to throw.
42236
+ }
42237
+ };
42238
+ }
42239
+ return this;
42240
+ }
42241
+
42242
+ /**
42243
+ * Call process.exit, and _exitCallback if defined.
42244
+ *
42245
+ * @param {number} exitCode exit code for using with process.exit
42246
+ * @param {string} code an id string representing the error
42247
+ * @param {string} message human-readable description of the error
42248
+ * @return never
42249
+ * @private
42250
+ */
42251
+
42252
+ _exit(exitCode, code, message) {
42253
+ if (this._exitCallback) {
42254
+ this._exitCallback(new CommanderError(exitCode, code, message));
42255
+ // Expecting this line is not reached.
42256
+ }
42257
+ process.exit(exitCode);
42258
+ }
42259
+
42260
+ /**
42261
+ * Register callback `fn` for the command.
42262
+ *
42263
+ * @example
42264
+ * program
42265
+ * .command('serve')
42266
+ * .description('start service')
42267
+ * .action(function() {
42268
+ * // do work here
42269
+ * });
42270
+ *
42271
+ * @param {Function} fn
42272
+ * @return {Command} `this` command for chaining
42273
+ */
42274
+
42275
+ action(fn) {
42276
+ const listener = (args) => {
42277
+ // The .action callback takes an extra parameter which is the command or options.
42278
+ const expectedArgsCount = this.registeredArguments.length;
42279
+ const actionArgs = args.slice(0, expectedArgsCount);
42280
+ if (this._storeOptionsAsProperties) {
42281
+ actionArgs[expectedArgsCount] = this; // backwards compatible "options"
42282
+ } else {
42283
+ actionArgs[expectedArgsCount] = this.opts();
42284
+ }
42285
+ actionArgs.push(this);
42286
+
42287
+ return fn.apply(this, actionArgs);
42288
+ };
42289
+ this._actionHandler = listener;
42290
+ return this;
42291
+ }
42292
+
42293
+ /**
42294
+ * Factory routine to create a new unattached option.
42295
+ *
42296
+ * See .option() for creating an attached option, which uses this routine to
42297
+ * create the option. You can override createOption to return a custom option.
42298
+ *
42299
+ * @param {string} flags
42300
+ * @param {string} [description]
42301
+ * @return {Option} new option
42302
+ */
42303
+
42304
+ createOption(flags, description) {
42305
+ return new Option(flags, description);
42306
+ }
42307
+
42308
+ /**
42309
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
42310
+ *
42311
+ * @param {(Option | Argument)} target
42312
+ * @param {string} value
42313
+ * @param {*} previous
42314
+ * @param {string} invalidArgumentMessage
42315
+ * @private
42316
+ */
42317
+
42318
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
42319
+ try {
42320
+ return target.parseArg(value, previous);
42321
+ } catch (err) {
42322
+ if (err.code === 'commander.invalidArgument') {
42323
+ const message = `${invalidArgumentMessage} ${err.message}`;
42324
+ this.error(message, { exitCode: err.exitCode, code: err.code });
42325
+ }
42326
+ throw err;
42327
+ }
42328
+ }
42329
+
42330
+ /**
42331
+ * Check for option flag conflicts.
42332
+ * Register option if no conflicts found, or throw on conflict.
42333
+ *
42334
+ * @param {Option} option
42335
+ * @private
42336
+ */
42337
+
42338
+ _registerOption(option) {
42339
+ const matchingOption =
42340
+ (option.short && this._findOption(option.short)) ||
42341
+ (option.long && this._findOption(option.long));
42342
+ if (matchingOption) {
42343
+ const matchingFlag =
42344
+ option.long && this._findOption(option.long)
42345
+ ? option.long
42346
+ : option.short;
42347
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
42348
+ - already used by option '${matchingOption.flags}'`);
42349
+ }
42350
+
42351
+ this._initOptionGroup(option);
42352
+ this.options.push(option);
42353
+ }
42354
+
42355
+ /**
42356
+ * Check for command name and alias conflicts with existing commands.
42357
+ * Register command if no conflicts found, or throw on conflict.
42358
+ *
42359
+ * @param {Command} command
42360
+ * @private
42361
+ */
42362
+
42363
+ _registerCommand(command) {
42364
+ const knownBy = (cmd) => {
42365
+ return [cmd.name()].concat(cmd.aliases());
42366
+ };
42367
+
42368
+ const alreadyUsed = knownBy(command).find((name) =>
42369
+ this._findCommand(name),
42370
+ );
42371
+ if (alreadyUsed) {
42372
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
42373
+ const newCmd = knownBy(command).join('|');
42374
+ throw new Error(
42375
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`,
42376
+ );
42377
+ }
42378
+
42379
+ this._initCommandGroup(command);
42380
+ this.commands.push(command);
42381
+ }
42382
+
42383
+ /**
42384
+ * Add an option.
42385
+ *
42386
+ * @param {Option} option
42387
+ * @return {Command} `this` command for chaining
42388
+ */
42389
+ addOption(option) {
42390
+ this._registerOption(option);
42391
+
42392
+ const oname = option.name();
42393
+ const name = option.attributeName();
42394
+
42395
+ // store default value
42396
+ if (option.negate) {
42397
+ // --no-foo is special and defaults foo to true, unless a --foo option is already defined
42398
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
42399
+ if (!this._findOption(positiveLongFlag)) {
42400
+ this.setOptionValueWithSource(
42401
+ name,
42402
+ option.defaultValue === undefined ? true : option.defaultValue,
42403
+ 'default',
42404
+ );
42405
+ }
42406
+ } else if (option.defaultValue !== undefined) {
42407
+ this.setOptionValueWithSource(name, option.defaultValue, 'default');
42408
+ }
42409
+
42410
+ // handler for cli and env supplied values
42411
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
42412
+ // val is null for optional option used without an optional-argument.
42413
+ // val is undefined for boolean and negated option.
42414
+ if (val == null && option.presetArg !== undefined) {
42415
+ val = option.presetArg;
42416
+ }
42417
+
42418
+ // custom processing
42419
+ const oldValue = this.getOptionValue(name);
42420
+ if (val !== null && option.parseArg) {
42421
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
42422
+ } else if (val !== null && option.variadic) {
42423
+ val = option._collectValue(val, oldValue);
42424
+ }
42425
+
42426
+ // Fill-in appropriate missing values. Long winded but easy to follow.
42427
+ if (val == null) {
42428
+ if (option.negate) {
42429
+ val = false;
42430
+ } else if (option.isBoolean() || option.optional) {
42431
+ val = true;
42432
+ } else {
42433
+ val = ''; // not normal, parseArg might have failed or be a mock function for testing
42434
+ }
42435
+ }
42436
+ this.setOptionValueWithSource(name, val, valueSource);
42437
+ };
42438
+
42439
+ this.on('option:' + oname, (val) => {
42440
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
42441
+ handleOptionValue(val, invalidValueMessage, 'cli');
42442
+ });
42443
+
42444
+ if (option.envVar) {
42445
+ this.on('optionEnv:' + oname, (val) => {
42446
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
42447
+ handleOptionValue(val, invalidValueMessage, 'env');
42448
+ });
42449
+ }
42450
+
42451
+ return this;
42452
+ }
42453
+
42454
+ /**
42455
+ * Internal implementation shared by .option() and .requiredOption()
42456
+ *
42457
+ * @return {Command} `this` command for chaining
42458
+ * @private
42459
+ */
42460
+ _optionEx(config, flags, description, fn, defaultValue) {
42461
+ if (typeof flags === 'object' && flags instanceof Option) {
42462
+ throw new Error(
42463
+ 'To add an Option object use addOption() instead of option() or requiredOption()',
42464
+ );
42465
+ }
42466
+ const option = this.createOption(flags, description);
42467
+ option.makeOptionMandatory(!!config.mandatory);
42468
+ if (typeof fn === 'function') {
42469
+ option.default(defaultValue).argParser(fn);
42470
+ } else if (fn instanceof RegExp) {
42471
+ // deprecated
42472
+ const regex = fn;
42473
+ fn = (val, def) => {
42474
+ const m = regex.exec(val);
42475
+ return m ? m[0] : def;
42476
+ };
42477
+ option.default(defaultValue).argParser(fn);
42478
+ } else {
42479
+ option.default(fn);
42480
+ }
42481
+
42482
+ return this.addOption(option);
42483
+ }
42484
+
42485
+ /**
42486
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
42487
+ *
42488
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
42489
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
42490
+ *
42491
+ * See the README for more details, and see also addOption() and requiredOption().
42492
+ *
42493
+ * @example
42494
+ * program
42495
+ * .option('-p, --pepper', 'add pepper')
42496
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
42497
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
42498
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
42499
+ *
42500
+ * @param {string} flags
42501
+ * @param {string} [description]
42502
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
42503
+ * @param {*} [defaultValue]
42504
+ * @return {Command} `this` command for chaining
42505
+ */
42506
+
42507
+ option(flags, description, parseArg, defaultValue) {
42508
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
42509
+ }
42510
+
42511
+ /**
42512
+ * Add a required option which must have a value after parsing. This usually means
42513
+ * the option must be specified on the command line. (Otherwise the same as .option().)
42514
+ *
42515
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
42516
+ *
42517
+ * @param {string} flags
42518
+ * @param {string} [description]
42519
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
42520
+ * @param {*} [defaultValue]
42521
+ * @return {Command} `this` command for chaining
42522
+ */
42523
+
42524
+ requiredOption(flags, description, parseArg, defaultValue) {
42525
+ return this._optionEx(
42526
+ { mandatory: true },
42527
+ flags,
42528
+ description,
42529
+ parseArg,
42530
+ defaultValue,
42531
+ );
42532
+ }
42533
+
42534
+ /**
42535
+ * Alter parsing of short flags with optional values.
42536
+ *
42537
+ * @example
42538
+ * // for `.option('-f,--flag [value]'):
42539
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
42540
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
42541
+ *
42542
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
42543
+ * @return {Command} `this` command for chaining
42544
+ */
42545
+ combineFlagAndOptionalValue(combine = true) {
42546
+ this._combineFlagAndOptionalValue = !!combine;
42547
+ return this;
42548
+ }
42549
+
42550
+ /**
42551
+ * Allow unknown options on the command line.
42552
+ *
42553
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
42554
+ * @return {Command} `this` command for chaining
42555
+ */
42556
+ allowUnknownOption(allowUnknown = true) {
42557
+ this._allowUnknownOption = !!allowUnknown;
42558
+ return this;
42559
+ }
42560
+
42561
+ /**
42562
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
42563
+ *
42564
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
42565
+ * @return {Command} `this` command for chaining
42566
+ */
42567
+ allowExcessArguments(allowExcess = true) {
42568
+ this._allowExcessArguments = !!allowExcess;
42569
+ return this;
42570
+ }
42571
+
42572
+ /**
42573
+ * Enable positional options. Positional means global options are specified before subcommands which lets
42574
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
42575
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
42576
+ *
42577
+ * @param {boolean} [positional]
42578
+ * @return {Command} `this` command for chaining
42579
+ */
42580
+ enablePositionalOptions(positional = true) {
42581
+ this._enablePositionalOptions = !!positional;
42582
+ return this;
42583
+ }
42584
+
42585
+ /**
42586
+ * Pass through options that come after command-arguments rather than treat them as command-options,
42587
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
42588
+ * positional options to have been enabled on the program (parent commands).
42589
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
42590
+ *
42591
+ * @param {boolean} [passThrough] for unknown options.
42592
+ * @return {Command} `this` command for chaining
42593
+ */
42594
+ passThroughOptions(passThrough = true) {
42595
+ this._passThroughOptions = !!passThrough;
42596
+ this._checkForBrokenPassThrough();
42597
+ return this;
42598
+ }
42599
+
42600
+ /**
42601
+ * @private
42602
+ */
42603
+
42604
+ _checkForBrokenPassThrough() {
42605
+ if (
42606
+ this.parent &&
42607
+ this._passThroughOptions &&
42608
+ !this.parent._enablePositionalOptions
42609
+ ) {
42610
+ throw new Error(
42611
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,
42612
+ );
42613
+ }
42614
+ }
42615
+
42616
+ /**
42617
+ * Whether to store option values as properties on command object,
42618
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
42619
+ *
42620
+ * @param {boolean} [storeAsProperties=true]
42621
+ * @return {Command} `this` command for chaining
42622
+ */
42623
+
42624
+ storeOptionsAsProperties(storeAsProperties = true) {
42625
+ if (this.options.length) {
42626
+ throw new Error('call .storeOptionsAsProperties() before adding options');
42627
+ }
42628
+ if (Object.keys(this._optionValues).length) {
42629
+ throw new Error(
42630
+ 'call .storeOptionsAsProperties() before setting option values',
42631
+ );
42632
+ }
42633
+ this._storeOptionsAsProperties = !!storeAsProperties;
42634
+ return this;
42635
+ }
42636
+
42637
+ /**
42638
+ * Retrieve option value.
42639
+ *
42640
+ * @param {string} key
42641
+ * @return {object} value
42642
+ */
42643
+
42644
+ getOptionValue(key) {
42645
+ if (this._storeOptionsAsProperties) {
42646
+ return this[key];
42647
+ }
42648
+ return this._optionValues[key];
42649
+ }
42650
+
42651
+ /**
42652
+ * Store option value.
42653
+ *
42654
+ * @param {string} key
42655
+ * @param {object} value
42656
+ * @return {Command} `this` command for chaining
42657
+ */
42658
+
42659
+ setOptionValue(key, value) {
42660
+ return this.setOptionValueWithSource(key, value, undefined);
42661
+ }
42662
+
42663
+ /**
42664
+ * Store option value and where the value came from.
42665
+ *
42666
+ * @param {string} key
42667
+ * @param {object} value
42668
+ * @param {string} source - expected values are default/config/env/cli/implied
42669
+ * @return {Command} `this` command for chaining
42670
+ */
42671
+
42672
+ setOptionValueWithSource(key, value, source) {
42673
+ if (this._storeOptionsAsProperties) {
42674
+ this[key] = value;
42675
+ } else {
42676
+ this._optionValues[key] = value;
42677
+ }
42678
+ this._optionValueSources[key] = source;
42679
+ return this;
42680
+ }
42681
+
42682
+ /**
42683
+ * Get source of option value.
42684
+ * Expected values are default | config | env | cli | implied
42685
+ *
42686
+ * @param {string} key
42687
+ * @return {string}
42688
+ */
42689
+
42690
+ getOptionValueSource(key) {
42691
+ return this._optionValueSources[key];
42692
+ }
42693
+
42694
+ /**
42695
+ * Get source of option value. See also .optsWithGlobals().
42696
+ * Expected values are default | config | env | cli | implied
42697
+ *
42698
+ * @param {string} key
42699
+ * @return {string}
42700
+ */
42701
+
42702
+ getOptionValueSourceWithGlobals(key) {
42703
+ // global overwrites local, like optsWithGlobals
42704
+ let source;
42705
+ this._getCommandAndAncestors().forEach((cmd) => {
42706
+ if (cmd.getOptionValueSource(key) !== undefined) {
42707
+ source = cmd.getOptionValueSource(key);
42708
+ }
42709
+ });
42710
+ return source;
42711
+ }
42712
+
42713
+ /**
42714
+ * Get user arguments from implied or explicit arguments.
42715
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
42716
+ *
42717
+ * @private
42718
+ */
42719
+
42720
+ _prepareUserArgs(argv, parseOptions) {
42721
+ if (argv !== undefined && !Array.isArray(argv)) {
42722
+ throw new Error('first parameter to parse must be array or undefined');
42723
+ }
42724
+ parseOptions = parseOptions || {};
42725
+
42726
+ // auto-detect argument conventions if nothing supplied
42727
+ if (argv === undefined && parseOptions.from === undefined) {
42728
+ if (process.versions?.electron) {
42729
+ parseOptions.from = 'electron';
42730
+ }
42731
+ // check node specific options for scenarios where user CLI args follow executable without scriptname
42732
+ const execArgv = process.execArgv ?? [];
42733
+ if (
42734
+ execArgv.includes('-e') ||
42735
+ execArgv.includes('--eval') ||
42736
+ execArgv.includes('-p') ||
42737
+ execArgv.includes('--print')
42738
+ ) {
42739
+ parseOptions.from = 'eval'; // internal usage, not documented
42740
+ }
42741
+ }
42742
+
42743
+ // default to using process.argv
42744
+ if (argv === undefined) {
42745
+ argv = process.argv;
42746
+ }
42747
+ this.rawArgs = argv.slice();
42748
+
42749
+ // extract the user args and scriptPath
42750
+ let userArgs;
42751
+ switch (parseOptions.from) {
42752
+ case undefined:
42753
+ case 'node':
42754
+ this._scriptPath = argv[1];
42755
+ userArgs = argv.slice(2);
42756
+ break;
42757
+ case 'electron':
42758
+ // @ts-ignore: because defaultApp is an unknown property
42759
+ if (process.defaultApp) {
42760
+ this._scriptPath = argv[1];
42761
+ userArgs = argv.slice(2);
42762
+ } else {
42763
+ userArgs = argv.slice(1);
42764
+ }
42765
+ break;
42766
+ case 'user':
42767
+ userArgs = argv.slice(0);
42768
+ break;
42769
+ case 'eval':
42770
+ userArgs = argv.slice(1);
42771
+ break;
42772
+ default:
42773
+ throw new Error(
42774
+ `unexpected parse option { from: '${parseOptions.from}' }`,
42775
+ );
42776
+ }
42777
+
42778
+ // Find default name for program from arguments.
42779
+ if (!this._name && this._scriptPath)
42780
+ this.nameFromFilename(this._scriptPath);
42781
+ this._name = this._name || 'program';
42782
+
42783
+ return userArgs;
42784
+ }
42785
+
42786
+ /**
42787
+ * Parse `argv`, setting options and invoking commands when defined.
42788
+ *
42789
+ * Use parseAsync instead of parse if any of your action handlers are async.
42790
+ *
42791
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
42792
+ *
42793
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
42794
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
42795
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
42796
+ * - `'user'`: just user arguments
42797
+ *
42798
+ * @example
42799
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
42800
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
42801
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
42802
+ *
42803
+ * @param {string[]} [argv] - optional, defaults to process.argv
42804
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
42805
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
42806
+ * @return {Command} `this` command for chaining
42807
+ */
42808
+
42809
+ parse(argv, parseOptions) {
42810
+ this._prepareForParse();
42811
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
42812
+ this._parseCommand([], userArgs);
42813
+
42814
+ return this;
42815
+ }
42816
+
42817
+ /**
42818
+ * Parse `argv`, setting options and invoking commands when defined.
42819
+ *
42820
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
42821
+ *
42822
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
42823
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
42824
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
42825
+ * - `'user'`: just user arguments
42826
+ *
42827
+ * @example
42828
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
42829
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
42830
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
42831
+ *
42832
+ * @param {string[]} [argv]
42833
+ * @param {object} [parseOptions]
42834
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
42835
+ * @return {Promise}
42836
+ */
42837
+
42838
+ async parseAsync(argv, parseOptions) {
42839
+ this._prepareForParse();
42840
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
42841
+ await this._parseCommand([], userArgs);
42842
+
42843
+ return this;
42844
+ }
42845
+
42846
+ _prepareForParse() {
42847
+ if (this._savedState === null) {
42848
+ this.saveStateBeforeParse();
42849
+ } else {
42850
+ this.restoreStateBeforeParse();
42851
+ }
42852
+ }
42853
+
42854
+ /**
42855
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
42856
+ * Not usually called directly, but available for subclasses to save their custom state.
42857
+ *
42858
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
42859
+ */
42860
+ saveStateBeforeParse() {
42861
+ this._savedState = {
42862
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
42863
+ _name: this._name,
42864
+ // option values before parse have default values (including false for negated options)
42865
+ // shallow clones
42866
+ _optionValues: { ...this._optionValues },
42867
+ _optionValueSources: { ...this._optionValueSources },
42868
+ };
42869
+ }
42870
+
42871
+ /**
42872
+ * Restore state before parse for calls after the first.
42873
+ * Not usually called directly, but available for subclasses to save their custom state.
42874
+ *
42875
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
42876
+ */
42877
+ restoreStateBeforeParse() {
42878
+ if (this._storeOptionsAsProperties)
42879
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
42880
+ - either make a new Command for each call to parse, or stop storing options as properties`);
42881
+
42882
+ // clear state from _prepareUserArgs
42883
+ this._name = this._savedState._name;
42884
+ this._scriptPath = null;
42885
+ this.rawArgs = [];
42886
+ // clear state from setOptionValueWithSource
42887
+ this._optionValues = { ...this._savedState._optionValues };
42888
+ this._optionValueSources = { ...this._savedState._optionValueSources };
42889
+ // clear state from _parseCommand
42890
+ this.args = [];
42891
+ // clear state from _processArguments
42892
+ this.processedArgs = [];
42893
+ }
42894
+
42895
+ /**
42896
+ * Throw if expected executable is missing. Add lots of help for author.
42897
+ *
42898
+ * @param {string} executableFile
42899
+ * @param {string} executableDir
42900
+ * @param {string} subcommandName
42901
+ */
42902
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
42903
+ if (fs.existsSync(executableFile)) return;
42904
+
42905
+ const executableDirMessage = executableDir
42906
+ ? `searched for local subcommand relative to directory '${executableDir}'`
42907
+ : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
42908
+ const executableMissing = `'${executableFile}' does not exist
42909
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
42910
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
42911
+ - ${executableDirMessage}`;
42912
+ throw new Error(executableMissing);
42913
+ }
42914
+
42915
+ /**
42916
+ * Execute a sub-command executable.
42917
+ *
42918
+ * @private
42919
+ */
42920
+
42921
+ _executeSubCommand(subcommand, args) {
42922
+ args = args.slice();
42923
+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
42924
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
42925
+
42926
+ function findFile(baseDir, baseName) {
42927
+ // Look for specified file
42928
+ const localBin = path.resolve(baseDir, baseName);
42929
+ if (fs.existsSync(localBin)) return localBin;
42930
+
42931
+ // Stop looking if candidate already has an expected extension.
42932
+ if (sourceExt.includes(path.extname(baseName))) return undefined;
42933
+
42934
+ // Try all the extensions.
42935
+ const foundExt = sourceExt.find((ext) =>
42936
+ fs.existsSync(`${localBin}${ext}`),
42937
+ );
42938
+ if (foundExt) return `${localBin}${foundExt}`;
42939
+
42940
+ return undefined;
42941
+ }
42942
+
42943
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
42944
+ this._checkForMissingMandatoryOptions();
42945
+ this._checkForConflictingOptions();
42946
+
42947
+ // executableFile and executableDir might be full path, or just a name
42948
+ let executableFile =
42949
+ subcommand._executableFile || `${this._name}-${subcommand._name}`;
42950
+ let executableDir = this._executableDir || '';
42951
+ if (this._scriptPath) {
42952
+ let resolvedScriptPath; // resolve possible symlink for installed npm binary
42953
+ try {
42954
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
42955
+ } catch {
42956
+ resolvedScriptPath = this._scriptPath;
42957
+ }
42958
+ executableDir = path.resolve(
42959
+ path.dirname(resolvedScriptPath),
42960
+ executableDir,
42961
+ );
42962
+ }
42963
+
42964
+ // Look for a local file in preference to a command in PATH.
42965
+ if (executableDir) {
42966
+ let localFile = findFile(executableDir, executableFile);
42967
+
42968
+ // Legacy search using prefix of script name instead of command name
42969
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
42970
+ const legacyName = path.basename(
42971
+ this._scriptPath,
42972
+ path.extname(this._scriptPath),
42973
+ );
42974
+ if (legacyName !== this._name) {
42975
+ localFile = findFile(
42976
+ executableDir,
42977
+ `${legacyName}-${subcommand._name}`,
42978
+ );
42979
+ }
42980
+ }
42981
+ executableFile = localFile || executableFile;
42982
+ }
42983
+
42984
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
42985
+
42986
+ let proc;
42987
+ if (process.platform !== 'win32') {
42988
+ if (launchWithNode) {
42989
+ args.unshift(executableFile);
42990
+ // add executable arguments to spawn
42991
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
42992
+
42993
+ proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
42994
+ } else {
42995
+ proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });
42996
+ }
42997
+ } else {
42998
+ this._checkForMissingExecutable(
42999
+ executableFile,
43000
+ executableDir,
43001
+ subcommand._name,
43002
+ );
43003
+ args.unshift(executableFile);
43004
+ // add executable arguments to spawn
43005
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
43006
+ proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
43007
+ }
43008
+
43009
+ if (!proc.killed) {
43010
+ // testing mainly to avoid leak warnings during unit tests with mocked spawn
43011
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
43012
+ signals.forEach((signal) => {
43013
+ process.on(signal, () => {
43014
+ if (proc.killed === false && proc.exitCode === null) {
43015
+ // @ts-ignore because signals not typed to known strings
43016
+ proc.kill(signal);
43017
+ }
43018
+ });
43019
+ });
43020
+ }
43021
+
43022
+ // By default terminate process when spawned process terminates.
43023
+ const exitCallback = this._exitCallback;
43024
+ proc.on('close', (code) => {
43025
+ code = code ?? 1; // code is null if spawned process terminated due to a signal
43026
+ if (!exitCallback) {
43027
+ process.exit(code);
43028
+ } else {
43029
+ exitCallback(
43030
+ new CommanderError(
43031
+ code,
43032
+ 'commander.executeSubCommandAsync',
43033
+ '(close)',
43034
+ ),
43035
+ );
43036
+ }
43037
+ });
43038
+ proc.on('error', (err) => {
43039
+ // @ts-ignore: because err.code is an unknown property
43040
+ if (err.code === 'ENOENT') {
43041
+ this._checkForMissingExecutable(
43042
+ executableFile,
43043
+ executableDir,
43044
+ subcommand._name,
43045
+ );
43046
+ // @ts-ignore: because err.code is an unknown property
43047
+ } else if (err.code === 'EACCES') {
43048
+ throw new Error(`'${executableFile}' not executable`);
43049
+ }
43050
+ if (!exitCallback) {
43051
+ process.exit(1);
43052
+ } else {
43053
+ const wrappedError = new CommanderError(
43054
+ 1,
43055
+ 'commander.executeSubCommandAsync',
43056
+ '(error)',
43057
+ );
43058
+ wrappedError.nestedError = err;
43059
+ exitCallback(wrappedError);
43060
+ }
43061
+ });
43062
+
43063
+ // Store the reference to the child process
43064
+ this.runningCommand = proc;
43065
+ }
43066
+
43067
+ /**
43068
+ * @private
43069
+ */
43070
+
43071
+ _dispatchSubcommand(commandName, operands, unknown) {
43072
+ const subCommand = this._findCommand(commandName);
43073
+ if (!subCommand) this.help({ error: true });
43074
+
43075
+ subCommand._prepareForParse();
43076
+ let promiseChain;
43077
+ promiseChain = this._chainOrCallSubCommandHook(
43078
+ promiseChain,
43079
+ subCommand,
43080
+ 'preSubcommand',
43081
+ );
43082
+ promiseChain = this._chainOrCall(promiseChain, () => {
43083
+ if (subCommand._executableHandler) {
43084
+ this._executeSubCommand(subCommand, operands.concat(unknown));
43085
+ } else {
43086
+ return subCommand._parseCommand(operands, unknown);
43087
+ }
43088
+ });
43089
+ return promiseChain;
43090
+ }
43091
+
43092
+ /**
43093
+ * Invoke help directly if possible, or dispatch if necessary.
43094
+ * e.g. help foo
43095
+ *
43096
+ * @private
43097
+ */
43098
+
43099
+ _dispatchHelpCommand(subcommandName) {
43100
+ if (!subcommandName) {
43101
+ this.help();
43102
+ }
43103
+ const subCommand = this._findCommand(subcommandName);
43104
+ if (subCommand && !subCommand._executableHandler) {
43105
+ subCommand.help();
43106
+ }
43107
+
43108
+ // Fallback to parsing the help flag to invoke the help.
43109
+ return this._dispatchSubcommand(
43110
+ subcommandName,
43111
+ [],
43112
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],
43113
+ );
43114
+ }
43115
+
43116
+ /**
43117
+ * Check this.args against expected this.registeredArguments.
43118
+ *
43119
+ * @private
43120
+ */
43121
+
43122
+ _checkNumberOfArguments() {
43123
+ // too few
43124
+ this.registeredArguments.forEach((arg, i) => {
43125
+ if (arg.required && this.args[i] == null) {
43126
+ this.missingArgument(arg.name());
43127
+ }
43128
+ });
43129
+ // too many
43130
+ if (
43131
+ this.registeredArguments.length > 0 &&
43132
+ this.registeredArguments[this.registeredArguments.length - 1].variadic
43133
+ ) {
43134
+ return;
43135
+ }
43136
+ if (this.args.length > this.registeredArguments.length) {
43137
+ this._excessArguments(this.args);
43138
+ }
43139
+ }
43140
+
43141
+ /**
43142
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
43143
+ *
43144
+ * @private
43145
+ */
43146
+
43147
+ _processArguments() {
43148
+ const myParseArg = (argument, value, previous) => {
43149
+ // Extra processing for nice error message on parsing failure.
43150
+ let parsedValue = value;
43151
+ if (value !== null && argument.parseArg) {
43152
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
43153
+ parsedValue = this._callParseArg(
43154
+ argument,
43155
+ value,
43156
+ previous,
43157
+ invalidValueMessage,
43158
+ );
43159
+ }
43160
+ return parsedValue;
43161
+ };
43162
+
43163
+ this._checkNumberOfArguments();
43164
+
43165
+ const processedArgs = [];
43166
+ this.registeredArguments.forEach((declaredArg, index) => {
43167
+ let value = declaredArg.defaultValue;
43168
+ if (declaredArg.variadic) {
43169
+ // Collect together remaining arguments for passing together as an array.
43170
+ if (index < this.args.length) {
43171
+ value = this.args.slice(index);
43172
+ if (declaredArg.parseArg) {
43173
+ value = value.reduce((processed, v) => {
43174
+ return myParseArg(declaredArg, v, processed);
43175
+ }, declaredArg.defaultValue);
43176
+ }
43177
+ } else if (value === undefined) {
43178
+ value = [];
43179
+ }
43180
+ } else if (index < this.args.length) {
43181
+ value = this.args[index];
43182
+ if (declaredArg.parseArg) {
43183
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
43184
+ }
43185
+ }
43186
+ processedArgs[index] = value;
43187
+ });
43188
+ this.processedArgs = processedArgs;
43189
+ }
43190
+
43191
+ /**
43192
+ * Once we have a promise we chain, but call synchronously until then.
43193
+ *
43194
+ * @param {(Promise|undefined)} promise
43195
+ * @param {Function} fn
43196
+ * @return {(Promise|undefined)}
43197
+ * @private
43198
+ */
43199
+
43200
+ _chainOrCall(promise, fn) {
43201
+ // thenable
43202
+ if (promise?.then && typeof promise.then === 'function') {
43203
+ // already have a promise, chain callback
43204
+ return promise.then(() => fn());
43205
+ }
43206
+ // callback might return a promise
43207
+ return fn();
43208
+ }
43209
+
43210
+ /**
43211
+ *
43212
+ * @param {(Promise|undefined)} promise
43213
+ * @param {string} event
43214
+ * @return {(Promise|undefined)}
43215
+ * @private
43216
+ */
43217
+
43218
+ _chainOrCallHooks(promise, event) {
43219
+ let result = promise;
43220
+ const hooks = [];
43221
+ this._getCommandAndAncestors()
43222
+ .reverse()
43223
+ .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)
43224
+ .forEach((hookedCommand) => {
43225
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
43226
+ hooks.push({ hookedCommand, callback });
43227
+ });
43228
+ });
43229
+ if (event === 'postAction') {
43230
+ hooks.reverse();
43231
+ }
43232
+
43233
+ hooks.forEach((hookDetail) => {
43234
+ result = this._chainOrCall(result, () => {
43235
+ return hookDetail.callback(hookDetail.hookedCommand, this);
43236
+ });
43237
+ });
43238
+ return result;
43239
+ }
43240
+
43241
+ /**
43242
+ *
43243
+ * @param {(Promise|undefined)} promise
43244
+ * @param {Command} subCommand
43245
+ * @param {string} event
43246
+ * @return {(Promise|undefined)}
43247
+ * @private
43248
+ */
43249
+
43250
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
43251
+ let result = promise;
43252
+ if (this._lifeCycleHooks[event] !== undefined) {
43253
+ this._lifeCycleHooks[event].forEach((hook) => {
43254
+ result = this._chainOrCall(result, () => {
43255
+ return hook(this, subCommand);
43256
+ });
43257
+ });
43258
+ }
43259
+ return result;
43260
+ }
43261
+
43262
+ /**
43263
+ * Process arguments in context of this command.
43264
+ * Returns action result, in case it is a promise.
43265
+ *
43266
+ * @private
43267
+ */
43268
+
43269
+ _parseCommand(operands, unknown) {
43270
+ const parsed = this.parseOptions(unknown);
43271
+ this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env
43272
+ this._parseOptionsImplied();
43273
+ operands = operands.concat(parsed.operands);
43274
+ unknown = parsed.unknown;
43275
+ this.args = operands.concat(unknown);
43276
+
43277
+ if (operands && this._findCommand(operands[0])) {
43278
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
43279
+ }
43280
+ if (
43281
+ this._getHelpCommand() &&
43282
+ operands[0] === this._getHelpCommand().name()
43283
+ ) {
43284
+ return this._dispatchHelpCommand(operands[1]);
43285
+ }
43286
+ if (this._defaultCommandName) {
43287
+ this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command
43288
+ return this._dispatchSubcommand(
43289
+ this._defaultCommandName,
43290
+ operands,
43291
+ unknown,
43292
+ );
43293
+ }
43294
+ if (
43295
+ this.commands.length &&
43296
+ this.args.length === 0 &&
43297
+ !this._actionHandler &&
43298
+ !this._defaultCommandName
43299
+ ) {
43300
+ // probably missing subcommand and no handler, user needs help (and exit)
43301
+ this.help({ error: true });
43302
+ }
43303
+
43304
+ this._outputHelpIfRequested(parsed.unknown);
43305
+ this._checkForMissingMandatoryOptions();
43306
+ this._checkForConflictingOptions();
43307
+
43308
+ // We do not always call this check to avoid masking a "better" error, like unknown command.
43309
+ const checkForUnknownOptions = () => {
43310
+ if (parsed.unknown.length > 0) {
43311
+ this.unknownOption(parsed.unknown[0]);
43312
+ }
43313
+ };
43314
+
43315
+ const commandEvent = `command:${this.name()}`;
43316
+ if (this._actionHandler) {
43317
+ checkForUnknownOptions();
43318
+ this._processArguments();
43319
+
43320
+ let promiseChain;
43321
+ promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
43322
+ promiseChain = this._chainOrCall(promiseChain, () =>
43323
+ this._actionHandler(this.processedArgs),
43324
+ );
43325
+ if (this.parent) {
43326
+ promiseChain = this._chainOrCall(promiseChain, () => {
43327
+ this.parent.emit(commandEvent, operands, unknown); // legacy
43328
+ });
43329
+ }
43330
+ promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
43331
+ return promiseChain;
43332
+ }
43333
+ if (this.parent?.listenerCount(commandEvent)) {
43334
+ checkForUnknownOptions();
43335
+ this._processArguments();
43336
+ this.parent.emit(commandEvent, operands, unknown); // legacy
43337
+ } else if (operands.length) {
43338
+ if (this._findCommand('*')) {
43339
+ // legacy default command
43340
+ return this._dispatchSubcommand('*', operands, unknown);
43341
+ }
43342
+ if (this.listenerCount('command:*')) {
43343
+ // skip option check, emit event for possible misspelling suggestion
43344
+ this.emit('command:*', operands, unknown);
43345
+ } else if (this.commands.length) {
43346
+ this.unknownCommand();
43347
+ } else {
43348
+ checkForUnknownOptions();
43349
+ this._processArguments();
43350
+ }
43351
+ } else if (this.commands.length) {
43352
+ checkForUnknownOptions();
43353
+ // This command has subcommands and nothing hooked up at this level, so display help (and exit).
43354
+ this.help({ error: true });
43355
+ } else {
43356
+ checkForUnknownOptions();
43357
+ this._processArguments();
43358
+ // fall through for caller to handle after calling .parse()
43359
+ }
43360
+ }
43361
+
43362
+ /**
43363
+ * Find matching command.
43364
+ *
43365
+ * @private
43366
+ * @return {Command | undefined}
43367
+ */
43368
+ _findCommand(name) {
43369
+ if (!name) return undefined;
43370
+ return this.commands.find(
43371
+ (cmd) => cmd._name === name || cmd._aliases.includes(name),
43372
+ );
43373
+ }
43374
+
43375
+ /**
43376
+ * Return an option matching `arg` if any.
43377
+ *
43378
+ * @param {string} arg
43379
+ * @return {Option}
43380
+ * @package
43381
+ */
43382
+
43383
+ _findOption(arg) {
43384
+ return this.options.find((option) => option.is(arg));
43385
+ }
43386
+
43387
+ /**
43388
+ * Display an error message if a mandatory option does not have a value.
43389
+ * Called after checking for help flags in leaf subcommand.
43390
+ *
43391
+ * @private
43392
+ */
43393
+
43394
+ _checkForMissingMandatoryOptions() {
43395
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
43396
+ this._getCommandAndAncestors().forEach((cmd) => {
43397
+ cmd.options.forEach((anOption) => {
43398
+ if (
43399
+ anOption.mandatory &&
43400
+ cmd.getOptionValue(anOption.attributeName()) === undefined
43401
+ ) {
43402
+ cmd.missingMandatoryOptionValue(anOption);
43403
+ }
43404
+ });
43405
+ });
43406
+ }
43407
+
43408
+ /**
43409
+ * Display an error message if conflicting options are used together in this.
43410
+ *
43411
+ * @private
43412
+ */
43413
+ _checkForConflictingLocalOptions() {
43414
+ const definedNonDefaultOptions = this.options.filter((option) => {
43415
+ const optionKey = option.attributeName();
43416
+ if (this.getOptionValue(optionKey) === undefined) {
43417
+ return false;
43418
+ }
43419
+ return this.getOptionValueSource(optionKey) !== 'default';
43420
+ });
43421
+
43422
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
43423
+ (option) => option.conflictsWith.length > 0,
43424
+ );
43425
+
43426
+ optionsWithConflicting.forEach((option) => {
43427
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>
43428
+ option.conflictsWith.includes(defined.attributeName()),
43429
+ );
43430
+ if (conflictingAndDefined) {
43431
+ this._conflictingOption(option, conflictingAndDefined);
43432
+ }
43433
+ });
43434
+ }
43435
+
43436
+ /**
43437
+ * Display an error message if conflicting options are used together.
43438
+ * Called after checking for help flags in leaf subcommand.
43439
+ *
43440
+ * @private
43441
+ */
43442
+ _checkForConflictingOptions() {
43443
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
43444
+ this._getCommandAndAncestors().forEach((cmd) => {
43445
+ cmd._checkForConflictingLocalOptions();
43446
+ });
43447
+ }
43448
+
43449
+ /**
43450
+ * Parse options from `argv` removing known options,
43451
+ * and return argv split into operands and unknown arguments.
43452
+ *
43453
+ * Side effects: modifies command by storing options. Does not reset state if called again.
43454
+ *
43455
+ * Examples:
43456
+ *
43457
+ * argv => operands, unknown
43458
+ * --known kkk op => [op], []
43459
+ * op --known kkk => [op], []
43460
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
43461
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
43462
+ *
43463
+ * @param {string[]} args
43464
+ * @return {{operands: string[], unknown: string[]}}
43465
+ */
43466
+
43467
+ parseOptions(args) {
43468
+ const operands = []; // operands, not options or values
43469
+ const unknown = []; // first unknown option and remaining unknown args
43470
+ let dest = operands;
43471
+
43472
+ function maybeOption(arg) {
43473
+ return arg.length > 1 && arg[0] === '-';
43474
+ }
43475
+
43476
+ const negativeNumberArg = (arg) => {
43477
+ // return false if not a negative number
43478
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
43479
+ // negative number is ok unless digit used as an option in command hierarchy
43480
+ return !this._getCommandAndAncestors().some((cmd) =>
43481
+ cmd.options
43482
+ .map((opt) => opt.short)
43483
+ .some((short) => /^-\d$/.test(short)),
43484
+ );
43485
+ };
43486
+
43487
+ // parse options
43488
+ let activeVariadicOption = null;
43489
+ let activeGroup = null; // working through group of short options, like -abc
43490
+ let i = 0;
43491
+ while (i < args.length || activeGroup) {
43492
+ const arg = activeGroup ?? args[i++];
43493
+ activeGroup = null;
43494
+
43495
+ // literal
43496
+ if (arg === '--') {
43497
+ if (dest === unknown) dest.push(arg);
43498
+ dest.push(...args.slice(i));
43499
+ break;
43500
+ }
43501
+
43502
+ if (
43503
+ activeVariadicOption &&
43504
+ (!maybeOption(arg) || negativeNumberArg(arg))
43505
+ ) {
43506
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
43507
+ continue;
43508
+ }
43509
+ activeVariadicOption = null;
43510
+
43511
+ if (maybeOption(arg)) {
43512
+ const option = this._findOption(arg);
43513
+ // recognised option, call listener to assign value with possible custom processing
43514
+ if (option) {
43515
+ if (option.required) {
43516
+ const value = args[i++];
43517
+ if (value === undefined) this.optionMissingArgument(option);
43518
+ this.emit(`option:${option.name()}`, value);
43519
+ } else if (option.optional) {
43520
+ let value = null;
43521
+ // historical behaviour is optional value is following arg unless an option
43522
+ if (
43523
+ i < args.length &&
43524
+ (!maybeOption(args[i]) || negativeNumberArg(args[i]))
43525
+ ) {
43526
+ value = args[i++];
43527
+ }
43528
+ this.emit(`option:${option.name()}`, value);
43529
+ } else {
43530
+ // boolean flag
43531
+ this.emit(`option:${option.name()}`);
43532
+ }
43533
+ activeVariadicOption = option.variadic ? option : null;
43534
+ continue;
43535
+ }
43536
+ }
43537
+
43538
+ // Look for combo options following single dash, eat first one if known.
43539
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
43540
+ const option = this._findOption(`-${arg[1]}`);
43541
+ if (option) {
43542
+ if (
43543
+ option.required ||
43544
+ (option.optional && this._combineFlagAndOptionalValue)
43545
+ ) {
43546
+ // option with value following in same argument
43547
+ this.emit(`option:${option.name()}`, arg.slice(2));
43548
+ } else {
43549
+ // boolean option
43550
+ this.emit(`option:${option.name()}`);
43551
+ // remove the processed option and keep processing group
43552
+ activeGroup = `-${arg.slice(2)}`;
43553
+ }
43554
+ continue;
43555
+ }
43556
+ }
43557
+
43558
+ // Look for known long flag with value, like --foo=bar
43559
+ if (/^--[^=]+=/.test(arg)) {
43560
+ const index = arg.indexOf('=');
43561
+ const option = this._findOption(arg.slice(0, index));
43562
+ if (option && (option.required || option.optional)) {
43563
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
43564
+ continue;
43565
+ }
43566
+ }
43567
+
43568
+ // Not a recognised option by this command.
43569
+ // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
43570
+
43571
+ // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
43572
+ // A negative number in a leaf command is not an unknown option.
43573
+ if (
43574
+ dest === operands &&
43575
+ maybeOption(arg) &&
43576
+ !(this.commands.length === 0 && negativeNumberArg(arg))
43577
+ ) {
43578
+ dest = unknown;
43579
+ }
43580
+
43581
+ // If using positionalOptions, stop processing our options at subcommand.
43582
+ if (
43583
+ (this._enablePositionalOptions || this._passThroughOptions) &&
43584
+ operands.length === 0 &&
43585
+ unknown.length === 0
43586
+ ) {
43587
+ if (this._findCommand(arg)) {
43588
+ operands.push(arg);
43589
+ unknown.push(...args.slice(i));
43590
+ break;
43591
+ } else if (
43592
+ this._getHelpCommand() &&
43593
+ arg === this._getHelpCommand().name()
43594
+ ) {
43595
+ operands.push(arg, ...args.slice(i));
43596
+ break;
43597
+ } else if (this._defaultCommandName) {
43598
+ unknown.push(arg, ...args.slice(i));
43599
+ break;
43600
+ }
43601
+ }
43602
+
43603
+ // If using passThroughOptions, stop processing options at first command-argument.
43604
+ if (this._passThroughOptions) {
43605
+ dest.push(arg, ...args.slice(i));
43606
+ break;
43607
+ }
43608
+
43609
+ // add arg
43610
+ dest.push(arg);
43611
+ }
43612
+
43613
+ return { operands, unknown };
43614
+ }
43615
+
43616
+ /**
43617
+ * Return an object containing local option values as key-value pairs.
43618
+ *
43619
+ * @return {object}
43620
+ */
43621
+ opts() {
43622
+ if (this._storeOptionsAsProperties) {
43623
+ // Preserve original behaviour so backwards compatible when still using properties
43624
+ const result = {};
43625
+ const len = this.options.length;
43626
+
43627
+ for (let i = 0; i < len; i++) {
43628
+ const key = this.options[i].attributeName();
43629
+ result[key] =
43630
+ key === this._versionOptionName ? this._version : this[key];
43631
+ }
43632
+ return result;
43633
+ }
43634
+
43635
+ return this._optionValues;
43636
+ }
43637
+
43638
+ /**
43639
+ * Return an object containing merged local and global option values as key-value pairs.
43640
+ *
43641
+ * @return {object}
43642
+ */
43643
+ optsWithGlobals() {
43644
+ // globals overwrite locals
43645
+ return this._getCommandAndAncestors().reduce(
43646
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
43647
+ {},
43648
+ );
43649
+ }
43650
+
43651
+ /**
43652
+ * Display error message and exit (or call exitOverride).
43653
+ *
43654
+ * @param {string} message
43655
+ * @param {object} [errorOptions]
43656
+ * @param {string} [errorOptions.code] - an id string representing the error
43657
+ * @param {number} [errorOptions.exitCode] - used with process.exit
43658
+ */
43659
+ error(message, errorOptions) {
43660
+ // output handling
43661
+ this._outputConfiguration.outputError(
43662
+ `${message}\n`,
43663
+ this._outputConfiguration.writeErr,
43664
+ );
43665
+ if (typeof this._showHelpAfterError === 'string') {
43666
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
43667
+ } else if (this._showHelpAfterError) {
43668
+ this._outputConfiguration.writeErr('\n');
43669
+ this.outputHelp({ error: true });
43670
+ }
43671
+
43672
+ // exit handling
43673
+ const config = errorOptions || {};
43674
+ const exitCode = config.exitCode || 1;
43675
+ const code = config.code || 'commander.error';
43676
+ this._exit(exitCode, code, message);
43677
+ }
43678
+
43679
+ /**
43680
+ * Apply any option related environment variables, if option does
43681
+ * not have a value from cli or client code.
43682
+ *
43683
+ * @private
43684
+ */
43685
+ _parseOptionsEnv() {
43686
+ this.options.forEach((option) => {
43687
+ if (option.envVar && option.envVar in process.env) {
43688
+ const optionKey = option.attributeName();
43689
+ // Priority check. Do not overwrite cli or options from unknown source (client-code).
43690
+ if (
43691
+ this.getOptionValue(optionKey) === undefined ||
43692
+ ['default', 'config', 'env'].includes(
43693
+ this.getOptionValueSource(optionKey),
43694
+ )
43695
+ ) {
43696
+ if (option.required || option.optional) {
43697
+ // option can take a value
43698
+ // keep very simple, optional always takes value
43699
+ this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
43700
+ } else {
43701
+ // boolean
43702
+ // keep very simple, only care that envVar defined and not the value
43703
+ this.emit(`optionEnv:${option.name()}`);
43704
+ }
43705
+ }
43706
+ }
43707
+ });
43708
+ }
43709
+
43710
+ /**
43711
+ * Apply any implied option values, if option is undefined or default value.
43712
+ *
43713
+ * @private
43714
+ */
43715
+ _parseOptionsImplied() {
43716
+ const dualHelper = new DualOptions(this.options);
43717
+ const hasCustomOptionValue = (optionKey) => {
43718
+ return (
43719
+ this.getOptionValue(optionKey) !== undefined &&
43720
+ !['default', 'implied'].includes(this.getOptionValueSource(optionKey))
43721
+ );
43722
+ };
43723
+ this.options
43724
+ .filter(
43725
+ (option) =>
43726
+ option.implied !== undefined &&
43727
+ hasCustomOptionValue(option.attributeName()) &&
43728
+ dualHelper.valueFromOption(
43729
+ this.getOptionValue(option.attributeName()),
43730
+ option,
43731
+ ),
43732
+ )
43733
+ .forEach((option) => {
43734
+ Object.keys(option.implied)
43735
+ .filter((impliedKey) => !hasCustomOptionValue(impliedKey))
43736
+ .forEach((impliedKey) => {
43737
+ this.setOptionValueWithSource(
43738
+ impliedKey,
43739
+ option.implied[impliedKey],
43740
+ 'implied',
43741
+ );
43742
+ });
43743
+ });
43744
+ }
43745
+
43746
+ /**
43747
+ * Argument `name` is missing.
43748
+ *
43749
+ * @param {string} name
43750
+ * @private
43751
+ */
43752
+
43753
+ missingArgument(name) {
43754
+ const message = `error: missing required argument '${name}'`;
43755
+ this.error(message, { code: 'commander.missingArgument' });
43756
+ }
43757
+
43758
+ /**
43759
+ * `Option` is missing an argument.
43760
+ *
43761
+ * @param {Option} option
43762
+ * @private
43763
+ */
43764
+
43765
+ optionMissingArgument(option) {
43766
+ const message = `error: option '${option.flags}' argument missing`;
43767
+ this.error(message, { code: 'commander.optionMissingArgument' });
43768
+ }
43769
+
43770
+ /**
43771
+ * `Option` does not have a value, and is a mandatory option.
43772
+ *
43773
+ * @param {Option} option
43774
+ * @private
43775
+ */
43776
+
43777
+ missingMandatoryOptionValue(option) {
43778
+ const message = `error: required option '${option.flags}' not specified`;
43779
+ this.error(message, { code: 'commander.missingMandatoryOptionValue' });
43780
+ }
43781
+
43782
+ /**
43783
+ * `Option` conflicts with another option.
43784
+ *
43785
+ * @param {Option} option
43786
+ * @param {Option} conflictingOption
43787
+ * @private
43788
+ */
43789
+ _conflictingOption(option, conflictingOption) {
43790
+ // The calling code does not know whether a negated option is the source of the
43791
+ // value, so do some work to take an educated guess.
43792
+ const findBestOptionFromValue = (option) => {
43793
+ const optionKey = option.attributeName();
43794
+ const optionValue = this.getOptionValue(optionKey);
43795
+ const negativeOption = this.options.find(
43796
+ (target) => target.negate && optionKey === target.attributeName(),
43797
+ );
43798
+ const positiveOption = this.options.find(
43799
+ (target) => !target.negate && optionKey === target.attributeName(),
43800
+ );
43801
+ if (
43802
+ negativeOption &&
43803
+ ((negativeOption.presetArg === undefined && optionValue === false) ||
43804
+ (negativeOption.presetArg !== undefined &&
43805
+ optionValue === negativeOption.presetArg))
43806
+ ) {
43807
+ return negativeOption;
43808
+ }
43809
+ return positiveOption || option;
43810
+ };
43811
+
43812
+ const getErrorMessage = (option) => {
43813
+ const bestOption = findBestOptionFromValue(option);
43814
+ const optionKey = bestOption.attributeName();
43815
+ const source = this.getOptionValueSource(optionKey);
43816
+ if (source === 'env') {
43817
+ return `environment variable '${bestOption.envVar}'`;
43818
+ }
43819
+ return `option '${bestOption.flags}'`;
43820
+ };
43821
+
43822
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
43823
+ this.error(message, { code: 'commander.conflictingOption' });
43824
+ }
43825
+
43826
+ /**
43827
+ * Unknown option `flag`.
43828
+ *
43829
+ * @param {string} flag
43830
+ * @private
43831
+ */
43832
+
43833
+ unknownOption(flag) {
43834
+ if (this._allowUnknownOption) return;
43835
+ let suggestion = '';
43836
+
43837
+ if (flag.startsWith('--') && this._showSuggestionAfterError) {
43838
+ // Looping to pick up the global options too
43839
+ let candidateFlags = [];
43840
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
43841
+ let command = this;
43842
+ do {
43843
+ const moreFlags = command
43844
+ .createHelp()
43845
+ .visibleOptions(command)
43846
+ .filter((option) => option.long)
43847
+ .map((option) => option.long);
43848
+ candidateFlags = candidateFlags.concat(moreFlags);
43849
+ command = command.parent;
43850
+ } while (command && !command._enablePositionalOptions);
43851
+ suggestion = suggestSimilar(flag, candidateFlags);
43852
+ }
43853
+
43854
+ const message = `error: unknown option '${flag}'${suggestion}`;
43855
+ this.error(message, { code: 'commander.unknownOption' });
43856
+ }
43857
+
43858
+ /**
43859
+ * Excess arguments, more than expected.
43860
+ *
43861
+ * @param {string[]} receivedArgs
43862
+ * @private
43863
+ */
43864
+
43865
+ _excessArguments(receivedArgs) {
43866
+ if (this._allowExcessArguments) return;
43867
+
43868
+ const expected = this.registeredArguments.length;
43869
+ const s = expected === 1 ? '' : 's';
43870
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
43871
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
43872
+ this.error(message, { code: 'commander.excessArguments' });
43873
+ }
43874
+
43875
+ /**
43876
+ * Unknown command.
43877
+ *
43878
+ * @private
43879
+ */
43880
+
43881
+ unknownCommand() {
43882
+ const unknownName = this.args[0];
43883
+ let suggestion = '';
43884
+
43885
+ if (this._showSuggestionAfterError) {
43886
+ const candidateNames = [];
43887
+ this.createHelp()
43888
+ .visibleCommands(this)
43889
+ .forEach((command) => {
43890
+ candidateNames.push(command.name());
43891
+ // just visible alias
43892
+ if (command.alias()) candidateNames.push(command.alias());
43893
+ });
43894
+ suggestion = suggestSimilar(unknownName, candidateNames);
43895
+ }
43896
+
43897
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
43898
+ this.error(message, { code: 'commander.unknownCommand' });
43899
+ }
43900
+
43901
+ /**
43902
+ * Get or set the program version.
43903
+ *
43904
+ * This method auto-registers the "-V, --version" option which will print the version number.
43905
+ *
43906
+ * You can optionally supply the flags and description to override the defaults.
43907
+ *
43908
+ * @param {string} [str]
43909
+ * @param {string} [flags]
43910
+ * @param {string} [description]
43911
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
43912
+ */
43913
+
43914
+ version(str, flags, description) {
43915
+ if (str === undefined) return this._version;
43916
+ this._version = str;
43917
+ flags = flags || '-V, --version';
43918
+ description = description || 'output the version number';
43919
+ const versionOption = this.createOption(flags, description);
43920
+ this._versionOptionName = versionOption.attributeName();
43921
+ this._registerOption(versionOption);
43922
+
43923
+ this.on('option:' + versionOption.name(), () => {
43924
+ this._outputConfiguration.writeOut(`${str}\n`);
43925
+ this._exit(0, 'commander.version', str);
43926
+ });
43927
+ return this;
43928
+ }
43929
+
43930
+ /**
43931
+ * Set the description.
43932
+ *
43933
+ * @param {string} [str]
43934
+ * @param {object} [argsDescription]
43935
+ * @return {(string|Command)}
43936
+ */
43937
+ description(str, argsDescription) {
43938
+ if (str === undefined && argsDescription === undefined)
43939
+ return this._description;
43940
+ this._description = str;
43941
+ if (argsDescription) {
43942
+ this._argsDescription = argsDescription;
43943
+ }
43944
+ return this;
43945
+ }
43946
+
43947
+ /**
43948
+ * Set the summary. Used when listed as subcommand of parent.
43949
+ *
43950
+ * @param {string} [str]
43951
+ * @return {(string|Command)}
43952
+ */
43953
+ summary(str) {
43954
+ if (str === undefined) return this._summary;
43955
+ this._summary = str;
43956
+ return this;
43957
+ }
43958
+
43959
+ /**
43960
+ * Set an alias for the command.
43961
+ *
43962
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
43963
+ *
43964
+ * @param {string} [alias]
43965
+ * @return {(string|Command)}
43966
+ */
43967
+
43968
+ alias(alias) {
43969
+ if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
43970
+
43971
+ /** @type {Command} */
43972
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
43973
+ let command = this;
43974
+ if (
43975
+ this.commands.length !== 0 &&
43976
+ this.commands[this.commands.length - 1]._executableHandler
43977
+ ) {
43978
+ // assume adding alias for last added executable subcommand, rather than this
43979
+ command = this.commands[this.commands.length - 1];
43980
+ }
43981
+
43982
+ if (alias === command._name)
43983
+ throw new Error("Command alias can't be the same as its name");
43984
+ const matchingCommand = this.parent?._findCommand(alias);
43985
+ if (matchingCommand) {
43986
+ // c.f. _registerCommand
43987
+ const existingCmd = [matchingCommand.name()]
43988
+ .concat(matchingCommand.aliases())
43989
+ .join('|');
43990
+ throw new Error(
43991
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,
43992
+ );
43993
+ }
43994
+
43995
+ command._aliases.push(alias);
43996
+ return this;
43997
+ }
43998
+
43999
+ /**
44000
+ * Set aliases for the command.
44001
+ *
44002
+ * Only the first alias is shown in the auto-generated help.
44003
+ *
44004
+ * @param {string[]} [aliases]
44005
+ * @return {(string[]|Command)}
44006
+ */
44007
+
44008
+ aliases(aliases) {
44009
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
44010
+ if (aliases === undefined) return this._aliases;
44011
+
44012
+ aliases.forEach((alias) => this.alias(alias));
44013
+ return this;
44014
+ }
44015
+
44016
+ /**
44017
+ * Set / get the command usage `str`.
44018
+ *
44019
+ * @param {string} [str]
44020
+ * @return {(string|Command)}
44021
+ */
44022
+
44023
+ usage(str) {
44024
+ if (str === undefined) {
44025
+ if (this._usage) return this._usage;
44026
+
44027
+ const args = this.registeredArguments.map((arg) => {
44028
+ return humanReadableArgName(arg);
44029
+ });
44030
+ return []
44031
+ .concat(
44032
+ this.options.length || this._helpOption !== null ? '[options]' : [],
44033
+ this.commands.length ? '[command]' : [],
44034
+ this.registeredArguments.length ? args : [],
44035
+ )
44036
+ .join(' ');
44037
+ }
44038
+
44039
+ this._usage = str;
44040
+ return this;
44041
+ }
44042
+
44043
+ /**
44044
+ * Get or set the name of the command.
44045
+ *
44046
+ * @param {string} [str]
44047
+ * @return {(string|Command)}
44048
+ */
44049
+
44050
+ name(str) {
44051
+ if (str === undefined) return this._name;
44052
+ this._name = str;
44053
+ return this;
44054
+ }
44055
+
44056
+ /**
44057
+ * Set/get the help group heading for this subcommand in parent command's help.
44058
+ *
44059
+ * @param {string} [heading]
44060
+ * @return {Command | string}
44061
+ */
44062
+
44063
+ helpGroup(heading) {
44064
+ if (heading === undefined) return this._helpGroupHeading ?? '';
44065
+ this._helpGroupHeading = heading;
44066
+ return this;
44067
+ }
44068
+
44069
+ /**
44070
+ * Set/get the default help group heading for subcommands added to this command.
44071
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
44072
+ *
44073
+ * @example
44074
+ * program.commandsGroup('Development Commands:);
44075
+ * program.command('watch')...
44076
+ * program.command('lint')...
44077
+ * ...
44078
+ *
44079
+ * @param {string} [heading]
44080
+ * @returns {Command | string}
44081
+ */
44082
+ commandsGroup(heading) {
44083
+ if (heading === undefined) return this._defaultCommandGroup ?? '';
44084
+ this._defaultCommandGroup = heading;
44085
+ return this;
44086
+ }
44087
+
44088
+ /**
44089
+ * Set/get the default help group heading for options added to this command.
44090
+ * (This does not override a group set directly on the option using .helpGroup().)
44091
+ *
44092
+ * @example
44093
+ * program
44094
+ * .optionsGroup('Development Options:')
44095
+ * .option('-d, --debug', 'output extra debugging')
44096
+ * .option('-p, --profile', 'output profiling information')
44097
+ *
44098
+ * @param {string} [heading]
44099
+ * @returns {Command | string}
44100
+ */
44101
+ optionsGroup(heading) {
44102
+ if (heading === undefined) return this._defaultOptionGroup ?? '';
44103
+ this._defaultOptionGroup = heading;
44104
+ return this;
44105
+ }
44106
+
44107
+ /**
44108
+ * @param {Option} option
44109
+ * @private
44110
+ */
44111
+ _initOptionGroup(option) {
44112
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
44113
+ option.helpGroup(this._defaultOptionGroup);
44114
+ }
44115
+
44116
+ /**
44117
+ * @param {Command} cmd
44118
+ * @private
44119
+ */
44120
+ _initCommandGroup(cmd) {
44121
+ if (this._defaultCommandGroup && !cmd.helpGroup())
44122
+ cmd.helpGroup(this._defaultCommandGroup);
44123
+ }
44124
+
44125
+ /**
44126
+ * Set the name of the command from script filename, such as process.argv[1],
44127
+ * or require.main.filename, or __filename.
44128
+ *
44129
+ * (Used internally and public although not documented in README.)
44130
+ *
44131
+ * @example
44132
+ * program.nameFromFilename(require.main.filename);
44133
+ *
44134
+ * @param {string} filename
44135
+ * @return {Command}
44136
+ */
44137
+
44138
+ nameFromFilename(filename) {
44139
+ this._name = path.basename(filename, path.extname(filename));
44140
+
44141
+ return this;
44142
+ }
44143
+
44144
+ /**
44145
+ * Get or set the directory for searching for executable subcommands of this command.
44146
+ *
44147
+ * @example
44148
+ * program.executableDir(__dirname);
44149
+ * // or
44150
+ * program.executableDir('subcommands');
44151
+ *
44152
+ * @param {string} [path]
44153
+ * @return {(string|null|Command)}
44154
+ */
44155
+
44156
+ executableDir(path) {
44157
+ if (path === undefined) return this._executableDir;
44158
+ this._executableDir = path;
44159
+ return this;
44160
+ }
44161
+
44162
+ /**
44163
+ * Return program help documentation.
44164
+ *
44165
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
44166
+ * @return {string}
44167
+ */
44168
+
44169
+ helpInformation(contextOptions) {
44170
+ const helper = this.createHelp();
44171
+ const context = this._getOutputContext(contextOptions);
44172
+ helper.prepareContext({
44173
+ error: context.error,
44174
+ helpWidth: context.helpWidth,
44175
+ outputHasColors: context.hasColors,
44176
+ });
44177
+ const text = helper.formatHelp(this, helper);
44178
+ if (context.hasColors) return text;
44179
+ return this._outputConfiguration.stripColor(text);
44180
+ }
44181
+
44182
+ /**
44183
+ * @typedef HelpContext
44184
+ * @type {object}
44185
+ * @property {boolean} error
44186
+ * @property {number} helpWidth
44187
+ * @property {boolean} hasColors
44188
+ * @property {function} write - includes stripColor if needed
44189
+ *
44190
+ * @returns {HelpContext}
44191
+ * @private
44192
+ */
44193
+
44194
+ _getOutputContext(contextOptions) {
44195
+ contextOptions = contextOptions || {};
44196
+ const error = !!contextOptions.error;
44197
+ let baseWrite;
44198
+ let hasColors;
44199
+ let helpWidth;
44200
+ if (error) {
44201
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
44202
+ hasColors = this._outputConfiguration.getErrHasColors();
44203
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
44204
+ } else {
44205
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
44206
+ hasColors = this._outputConfiguration.getOutHasColors();
44207
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
44208
+ }
44209
+ const write = (str) => {
44210
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
44211
+ return baseWrite(str);
44212
+ };
44213
+ return { error, write, hasColors, helpWidth };
44214
+ }
44215
+
44216
+ /**
44217
+ * Output help information for this command.
44218
+ *
44219
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
44220
+ *
44221
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
44222
+ */
44223
+
44224
+ outputHelp(contextOptions) {
44225
+ let deprecatedCallback;
44226
+ if (typeof contextOptions === 'function') {
44227
+ deprecatedCallback = contextOptions;
44228
+ contextOptions = undefined;
44229
+ }
44230
+
44231
+ const outputContext = this._getOutputContext(contextOptions);
44232
+ /** @type {HelpTextEventContext} */
44233
+ const eventContext = {
44234
+ error: outputContext.error,
44235
+ write: outputContext.write,
44236
+ command: this,
44237
+ };
44238
+
44239
+ this._getCommandAndAncestors()
44240
+ .reverse()
44241
+ .forEach((command) => command.emit('beforeAllHelp', eventContext));
44242
+ this.emit('beforeHelp', eventContext);
44243
+
44244
+ let helpInformation = this.helpInformation({ error: outputContext.error });
44245
+ if (deprecatedCallback) {
44246
+ helpInformation = deprecatedCallback(helpInformation);
44247
+ if (
44248
+ typeof helpInformation !== 'string' &&
44249
+ !Buffer.isBuffer(helpInformation)
44250
+ ) {
44251
+ throw new Error('outputHelp callback must return a string or a Buffer');
44252
+ }
44253
+ }
44254
+ outputContext.write(helpInformation);
44255
+
44256
+ if (this._getHelpOption()?.long) {
44257
+ this.emit(this._getHelpOption().long); // deprecated
44258
+ }
44259
+ this.emit('afterHelp', eventContext);
44260
+ this._getCommandAndAncestors().forEach((command) =>
44261
+ command.emit('afterAllHelp', eventContext),
44262
+ );
44263
+ }
44264
+
44265
+ /**
44266
+ * You can pass in flags and a description to customise the built-in help option.
44267
+ * Pass in false to disable the built-in help option.
44268
+ *
44269
+ * @example
44270
+ * program.helpOption('-?, --help' 'show help'); // customise
44271
+ * program.helpOption(false); // disable
44272
+ *
44273
+ * @param {(string | boolean)} flags
44274
+ * @param {string} [description]
44275
+ * @return {Command} `this` command for chaining
44276
+ */
44277
+
44278
+ helpOption(flags, description) {
44279
+ // Support enabling/disabling built-in help option.
44280
+ if (typeof flags === 'boolean') {
44281
+ if (flags) {
44282
+ if (this._helpOption === null) this._helpOption = undefined; // reenable
44283
+ if (this._defaultOptionGroup) {
44284
+ // make the option to store the group
44285
+ this._initOptionGroup(this._getHelpOption());
44286
+ }
44287
+ } else {
44288
+ this._helpOption = null; // disable
44289
+ }
44290
+ return this;
44291
+ }
44292
+
44293
+ // Customise flags and description.
44294
+ this._helpOption = this.createOption(
44295
+ flags ?? '-h, --help',
44296
+ description ?? 'display help for command',
44297
+ );
44298
+ // init group unless lazy create
44299
+ if (flags || description) this._initOptionGroup(this._helpOption);
44300
+
44301
+ return this;
44302
+ }
44303
+
44304
+ /**
44305
+ * Lazy create help option.
44306
+ * Returns null if has been disabled with .helpOption(false).
44307
+ *
44308
+ * @returns {(Option | null)} the help option
44309
+ * @package
44310
+ */
44311
+ _getHelpOption() {
44312
+ // Lazy create help option on demand.
44313
+ if (this._helpOption === undefined) {
44314
+ this.helpOption(undefined, undefined);
44315
+ }
44316
+ return this._helpOption;
44317
+ }
44318
+
44319
+ /**
44320
+ * Supply your own option to use for the built-in help option.
44321
+ * This is an alternative to using helpOption() to customise the flags and description etc.
44322
+ *
44323
+ * @param {Option} option
44324
+ * @return {Command} `this` command for chaining
44325
+ */
44326
+ addHelpOption(option) {
44327
+ this._helpOption = option;
44328
+ this._initOptionGroup(option);
44329
+ return this;
44330
+ }
44331
+
44332
+ /**
44333
+ * Output help information and exit.
44334
+ *
44335
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
44336
+ *
44337
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
44338
+ */
44339
+
44340
+ help(contextOptions) {
44341
+ this.outputHelp(contextOptions);
44342
+ let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number
44343
+ if (
44344
+ exitCode === 0 &&
44345
+ contextOptions &&
44346
+ typeof contextOptions !== 'function' &&
44347
+ contextOptions.error
44348
+ ) {
44349
+ exitCode = 1;
44350
+ }
44351
+ // message: do not have all displayed text available so only passing placeholder.
44352
+ this._exit(exitCode, 'commander.help', '(outputHelp)');
44353
+ }
44354
+
44355
+ /**
44356
+ * // Do a little typing to coordinate emit and listener for the help text events.
44357
+ * @typedef HelpTextEventContext
44358
+ * @type {object}
44359
+ * @property {boolean} error
44360
+ * @property {Command} command
44361
+ * @property {function} write
44362
+ */
44363
+
44364
+ /**
44365
+ * Add additional text to be displayed with the built-in help.
44366
+ *
44367
+ * Position is 'before' or 'after' to affect just this command,
44368
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
44369
+ *
44370
+ * @param {string} position - before or after built-in help
44371
+ * @param {(string | Function)} text - string to add, or a function returning a string
44372
+ * @return {Command} `this` command for chaining
44373
+ */
44374
+
44375
+ addHelpText(position, text) {
44376
+ const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
44377
+ if (!allowedValues.includes(position)) {
44378
+ throw new Error(`Unexpected value for position to addHelpText.
44379
+ Expecting one of '${allowedValues.join("', '")}'`);
44380
+ }
44381
+
44382
+ const helpEvent = `${position}Help`;
44383
+ this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {
44384
+ let helpStr;
44385
+ if (typeof text === 'function') {
44386
+ helpStr = text({ error: context.error, command: context.command });
44387
+ } else {
44388
+ helpStr = text;
44389
+ }
44390
+ // Ignore falsy value when nothing to output.
44391
+ if (helpStr) {
44392
+ context.write(`${helpStr}\n`);
44393
+ }
44394
+ });
44395
+ return this;
44396
+ }
44397
+
44398
+ /**
44399
+ * Output help information if help flags specified
44400
+ *
44401
+ * @param {Array} args - array of options to search for help flags
44402
+ * @private
44403
+ */
44404
+
44405
+ _outputHelpIfRequested(args) {
44406
+ const helpOption = this._getHelpOption();
44407
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
44408
+ if (helpRequested) {
44409
+ this.outputHelp();
44410
+ // (Do not have all displayed text available so only passing placeholder.)
44411
+ this._exit(0, 'commander.helpDisplayed', '(outputHelp)');
44412
+ }
44413
+ }
44414
+ }
44415
+
44416
+ /**
44417
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
44418
+ *
44419
+ * @param {string[]} args - array of arguments from node.execArgv
44420
+ * @returns {string[]}
44421
+ * @private
44422
+ */
44423
+
44424
+ function incrementNodeInspectorPort(args) {
44425
+ // Testing for these options:
44426
+ // --inspect[=[host:]port]
44427
+ // --inspect-brk[=[host:]port]
44428
+ // --inspect-port=[host:]port
44429
+ return args.map((arg) => {
44430
+ if (!arg.startsWith('--inspect')) {
44431
+ return arg;
44432
+ }
44433
+ let debugOption;
44434
+ let debugHost = '127.0.0.1';
44435
+ let debugPort = '9229';
44436
+ let match;
44437
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
44438
+ // e.g. --inspect
44439
+ debugOption = match[1];
44440
+ } else if (
44441
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null
44442
+ ) {
44443
+ debugOption = match[1];
44444
+ if (/^\d+$/.test(match[3])) {
44445
+ // e.g. --inspect=1234
44446
+ debugPort = match[3];
44447
+ } else {
44448
+ // e.g. --inspect=localhost
44449
+ debugHost = match[3];
44450
+ }
44451
+ } else if (
44452
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null
44453
+ ) {
44454
+ // e.g. --inspect=localhost:1234
44455
+ debugOption = match[1];
44456
+ debugHost = match[3];
44457
+ debugPort = match[4];
44458
+ }
44459
+
44460
+ if (debugOption && debugPort !== '0') {
44461
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
44462
+ }
44463
+ return arg;
44464
+ });
44465
+ }
44466
+
44467
+ /**
44468
+ * @returns {boolean | undefined}
44469
+ * @package
44470
+ */
44471
+ function useColor() {
44472
+ // Test for common conventions.
44473
+ // NB: the observed behaviour is in combination with how author adds color! For example:
44474
+ // - we do not test NODE_DISABLE_COLORS, but util:styletext does
44475
+ // - we do test NO_COLOR, but Chalk does not
44476
+ //
44477
+ // References:
44478
+ // https://no-color.org
44479
+ // https://bixense.com/clicolors/
44480
+ // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109
44481
+ // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33
44482
+ // (https://force-color.org recent web page from 2023, does not match major javascript implementations)
44483
+
44484
+ if (
44485
+ process.env.NO_COLOR ||
44486
+ process.env.FORCE_COLOR === '0' ||
44487
+ process.env.FORCE_COLOR === 'false'
44488
+ )
44489
+ return false;
44490
+ if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)
44491
+ return true;
44492
+ return undefined;
44493
+ }
44494
+
44495
+ exports.Command = Command;
44496
+ exports.useColor = useColor; // exporting for tests
44497
+
44498
+
44499
+ /***/ }),
44500
+
44501
+ /***/ 9073:
44502
+ /***/ ((__unused_webpack_module, exports) => {
44503
+
44504
+ /**
44505
+ * CommanderError class
44506
+ */
44507
+ class CommanderError extends Error {
44508
+ /**
44509
+ * Constructs the CommanderError class
44510
+ * @param {number} exitCode suggested exit code which could be used with process.exit
44511
+ * @param {string} code an id string representing the error
44512
+ * @param {string} message human-readable description of the error
44513
+ */
44514
+ constructor(exitCode, code, message) {
44515
+ super(message);
44516
+ // properly capture stack trace in Node.js
44517
+ Error.captureStackTrace(this, this.constructor);
44518
+ this.name = this.constructor.name;
44519
+ this.code = code;
44520
+ this.exitCode = exitCode;
44521
+ this.nestedError = undefined;
44522
+ }
44523
+ }
44524
+
44525
+ /**
44526
+ * InvalidArgumentError class
44527
+ */
44528
+ class InvalidArgumentError extends CommanderError {
44529
+ /**
44530
+ * Constructs the InvalidArgumentError class
44531
+ * @param {string} [message] explanation of why argument is invalid
44532
+ */
44533
+ constructor(message) {
44534
+ super(1, 'commander.invalidArgument', message);
44535
+ // properly capture stack trace in Node.js
44536
+ Error.captureStackTrace(this, this.constructor);
44537
+ this.name = this.constructor.name;
44538
+ }
44539
+ }
44540
+
44541
+ exports.CommanderError = CommanderError;
44542
+ exports.InvalidArgumentError = InvalidArgumentError;
44543
+
44544
+
44545
+ /***/ }),
44546
+
44547
+ /***/ 5632:
44548
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
44549
+
44550
+ const { humanReadableArgName } = __nccwpck_require__(4100);
44551
+
44552
+ /**
44553
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
44554
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
44555
+ * @typedef { import("./argument.js").Argument } Argument
44556
+ * @typedef { import("./command.js").Command } Command
44557
+ * @typedef { import("./option.js").Option } Option
44558
+ */
44559
+
44560
+ // Although this is a class, methods are static in style to allow override using subclass or just functions.
44561
+ class Help {
44562
+ constructor() {
44563
+ this.helpWidth = undefined;
44564
+ this.minWidthToWrap = 40;
44565
+ this.sortSubcommands = false;
44566
+ this.sortOptions = false;
44567
+ this.showGlobalOptions = false;
44568
+ }
44569
+
44570
+ /**
44571
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
44572
+ * and just before calling `formatHelp()`.
44573
+ *
44574
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
44575
+ *
44576
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
44577
+ */
44578
+ prepareContext(contextOptions) {
44579
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
44580
+ }
44581
+
44582
+ /**
44583
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
44584
+ *
44585
+ * @param {Command} cmd
44586
+ * @returns {Command[]}
44587
+ */
44588
+
44589
+ visibleCommands(cmd) {
44590
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
44591
+ const helpCommand = cmd._getHelpCommand();
44592
+ if (helpCommand && !helpCommand._hidden) {
44593
+ visibleCommands.push(helpCommand);
44594
+ }
44595
+ if (this.sortSubcommands) {
44596
+ visibleCommands.sort((a, b) => {
44597
+ // @ts-ignore: because overloaded return type
44598
+ return a.name().localeCompare(b.name());
44599
+ });
44600
+ }
44601
+ return visibleCommands;
44602
+ }
44603
+
44604
+ /**
44605
+ * Compare options for sort.
44606
+ *
44607
+ * @param {Option} a
44608
+ * @param {Option} b
44609
+ * @returns {number}
44610
+ */
44611
+ compareOptions(a, b) {
44612
+ const getSortKey = (option) => {
44613
+ // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
44614
+ return option.short
44615
+ ? option.short.replace(/^-/, '')
44616
+ : option.long.replace(/^--/, '');
44617
+ };
44618
+ return getSortKey(a).localeCompare(getSortKey(b));
44619
+ }
44620
+
44621
+ /**
44622
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
44623
+ *
44624
+ * @param {Command} cmd
44625
+ * @returns {Option[]}
44626
+ */
44627
+
44628
+ visibleOptions(cmd) {
44629
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
44630
+ // Built-in help option.
44631
+ const helpOption = cmd._getHelpOption();
44632
+ if (helpOption && !helpOption.hidden) {
44633
+ // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.
44634
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
44635
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
44636
+ if (!removeShort && !removeLong) {
44637
+ visibleOptions.push(helpOption); // no changes needed
44638
+ } else if (helpOption.long && !removeLong) {
44639
+ visibleOptions.push(
44640
+ cmd.createOption(helpOption.long, helpOption.description),
44641
+ );
44642
+ } else if (helpOption.short && !removeShort) {
44643
+ visibleOptions.push(
44644
+ cmd.createOption(helpOption.short, helpOption.description),
44645
+ );
44646
+ }
44647
+ }
44648
+ if (this.sortOptions) {
44649
+ visibleOptions.sort(this.compareOptions);
44650
+ }
44651
+ return visibleOptions;
44652
+ }
44653
+
44654
+ /**
44655
+ * Get an array of the visible global options. (Not including help.)
44656
+ *
44657
+ * @param {Command} cmd
44658
+ * @returns {Option[]}
44659
+ */
44660
+
44661
+ visibleGlobalOptions(cmd) {
44662
+ if (!this.showGlobalOptions) return [];
44663
+
44664
+ const globalOptions = [];
44665
+ for (
44666
+ let ancestorCmd = cmd.parent;
44667
+ ancestorCmd;
44668
+ ancestorCmd = ancestorCmd.parent
44669
+ ) {
44670
+ const visibleOptions = ancestorCmd.options.filter(
44671
+ (option) => !option.hidden,
44672
+ );
44673
+ globalOptions.push(...visibleOptions);
44674
+ }
44675
+ if (this.sortOptions) {
44676
+ globalOptions.sort(this.compareOptions);
44677
+ }
44678
+ return globalOptions;
44679
+ }
44680
+
44681
+ /**
44682
+ * Get an array of the arguments if any have a description.
44683
+ *
44684
+ * @param {Command} cmd
44685
+ * @returns {Argument[]}
44686
+ */
44687
+
44688
+ visibleArguments(cmd) {
44689
+ // Side effect! Apply the legacy descriptions before the arguments are displayed.
44690
+ if (cmd._argsDescription) {
44691
+ cmd.registeredArguments.forEach((argument) => {
44692
+ argument.description =
44693
+ argument.description || cmd._argsDescription[argument.name()] || '';
44694
+ });
44695
+ }
44696
+
44697
+ // If there are any arguments with a description then return all the arguments.
44698
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
44699
+ return cmd.registeredArguments;
44700
+ }
44701
+ return [];
44702
+ }
44703
+
44704
+ /**
44705
+ * Get the command term to show in the list of subcommands.
44706
+ *
44707
+ * @param {Command} cmd
44708
+ * @returns {string}
44709
+ */
44710
+
44711
+ subcommandTerm(cmd) {
44712
+ // Legacy. Ignores custom usage string, and nested commands.
44713
+ const args = cmd.registeredArguments
44714
+ .map((arg) => humanReadableArgName(arg))
44715
+ .join(' ');
44716
+ return (
44717
+ cmd._name +
44718
+ (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
44719
+ (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
44720
+ (args ? ' ' + args : '')
44721
+ );
44722
+ }
44723
+
44724
+ /**
44725
+ * Get the option term to show in the list of options.
44726
+ *
44727
+ * @param {Option} option
44728
+ * @returns {string}
44729
+ */
44730
+
44731
+ optionTerm(option) {
44732
+ return option.flags;
44733
+ }
44734
+
44735
+ /**
44736
+ * Get the argument term to show in the list of arguments.
44737
+ *
44738
+ * @param {Argument} argument
44739
+ * @returns {string}
44740
+ */
44741
+
44742
+ argumentTerm(argument) {
44743
+ return argument.name();
44744
+ }
44745
+
44746
+ /**
44747
+ * Get the longest command term length.
44748
+ *
44749
+ * @param {Command} cmd
44750
+ * @param {Help} helper
44751
+ * @returns {number}
44752
+ */
44753
+
44754
+ longestSubcommandTermLength(cmd, helper) {
44755
+ return helper.visibleCommands(cmd).reduce((max, command) => {
44756
+ return Math.max(
44757
+ max,
44758
+ this.displayWidth(
44759
+ helper.styleSubcommandTerm(helper.subcommandTerm(command)),
44760
+ ),
44761
+ );
44762
+ }, 0);
44763
+ }
44764
+
44765
+ /**
44766
+ * Get the longest option term length.
44767
+ *
44768
+ * @param {Command} cmd
44769
+ * @param {Help} helper
44770
+ * @returns {number}
44771
+ */
44772
+
44773
+ longestOptionTermLength(cmd, helper) {
44774
+ return helper.visibleOptions(cmd).reduce((max, option) => {
44775
+ return Math.max(
44776
+ max,
44777
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),
44778
+ );
44779
+ }, 0);
44780
+ }
44781
+
44782
+ /**
44783
+ * Get the longest global option term length.
44784
+ *
44785
+ * @param {Command} cmd
44786
+ * @param {Help} helper
44787
+ * @returns {number}
44788
+ */
44789
+
44790
+ longestGlobalOptionTermLength(cmd, helper) {
44791
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
44792
+ return Math.max(
44793
+ max,
44794
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),
44795
+ );
44796
+ }, 0);
44797
+ }
44798
+
44799
+ /**
44800
+ * Get the longest argument term length.
44801
+ *
44802
+ * @param {Command} cmd
44803
+ * @param {Help} helper
44804
+ * @returns {number}
44805
+ */
44806
+
44807
+ longestArgumentTermLength(cmd, helper) {
44808
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
44809
+ return Math.max(
44810
+ max,
44811
+ this.displayWidth(
44812
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
44813
+ ),
44814
+ );
44815
+ }, 0);
44816
+ }
44817
+
44818
+ /**
44819
+ * Get the command usage to be displayed at the top of the built-in help.
44820
+ *
44821
+ * @param {Command} cmd
44822
+ * @returns {string}
44823
+ */
44824
+
44825
+ commandUsage(cmd) {
44826
+ // Usage
44827
+ let cmdName = cmd._name;
44828
+ if (cmd._aliases[0]) {
44829
+ cmdName = cmdName + '|' + cmd._aliases[0];
44830
+ }
44831
+ let ancestorCmdNames = '';
44832
+ for (
44833
+ let ancestorCmd = cmd.parent;
44834
+ ancestorCmd;
44835
+ ancestorCmd = ancestorCmd.parent
44836
+ ) {
44837
+ ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;
44838
+ }
44839
+ return ancestorCmdNames + cmdName + ' ' + cmd.usage();
44840
+ }
44841
+
44842
+ /**
44843
+ * Get the description for the command.
44844
+ *
44845
+ * @param {Command} cmd
44846
+ * @returns {string}
44847
+ */
44848
+
44849
+ commandDescription(cmd) {
44850
+ // @ts-ignore: because overloaded return type
44851
+ return cmd.description();
44852
+ }
44853
+
44854
+ /**
44855
+ * Get the subcommand summary to show in the list of subcommands.
44856
+ * (Fallback to description for backwards compatibility.)
44857
+ *
44858
+ * @param {Command} cmd
44859
+ * @returns {string}
44860
+ */
44861
+
44862
+ subcommandDescription(cmd) {
44863
+ // @ts-ignore: because overloaded return type
44864
+ return cmd.summary() || cmd.description();
44865
+ }
44866
+
44867
+ /**
44868
+ * Get the option description to show in the list of options.
44869
+ *
44870
+ * @param {Option} option
44871
+ * @return {string}
44872
+ */
44873
+
44874
+ optionDescription(option) {
44875
+ const extraInfo = [];
44876
+
44877
+ if (option.argChoices) {
44878
+ extraInfo.push(
44879
+ // use stringify to match the display of the default value
44880
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
44881
+ );
44882
+ }
44883
+ if (option.defaultValue !== undefined) {
44884
+ // default for boolean and negated more for programmer than end user,
44885
+ // but show true/false for boolean option as may be for hand-rolled env or config processing.
44886
+ const showDefault =
44887
+ option.required ||
44888
+ option.optional ||
44889
+ (option.isBoolean() && typeof option.defaultValue === 'boolean');
44890
+ if (showDefault) {
44891
+ extraInfo.push(
44892
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,
44893
+ );
44894
+ }
44895
+ }
44896
+ // preset for boolean and negated are more for programmer than end user
44897
+ if (option.presetArg !== undefined && option.optional) {
44898
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
44899
+ }
44900
+ if (option.envVar !== undefined) {
44901
+ extraInfo.push(`env: ${option.envVar}`);
44902
+ }
44903
+ if (extraInfo.length > 0) {
44904
+ const extraDescription = `(${extraInfo.join(', ')})`;
44905
+ if (option.description) {
44906
+ return `${option.description} ${extraDescription}`;
44907
+ }
44908
+ return extraDescription;
44909
+ }
44910
+
44911
+ return option.description;
44912
+ }
44913
+
44914
+ /**
44915
+ * Get the argument description to show in the list of arguments.
44916
+ *
44917
+ * @param {Argument} argument
44918
+ * @return {string}
44919
+ */
44920
+
44921
+ argumentDescription(argument) {
44922
+ const extraInfo = [];
44923
+ if (argument.argChoices) {
44924
+ extraInfo.push(
44925
+ // use stringify to match the display of the default value
44926
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
44927
+ );
44928
+ }
44929
+ if (argument.defaultValue !== undefined) {
44930
+ extraInfo.push(
44931
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,
44932
+ );
44933
+ }
44934
+ if (extraInfo.length > 0) {
44935
+ const extraDescription = `(${extraInfo.join(', ')})`;
44936
+ if (argument.description) {
44937
+ return `${argument.description} ${extraDescription}`;
44938
+ }
44939
+ return extraDescription;
44940
+ }
44941
+ return argument.description;
44942
+ }
44943
+
44944
+ /**
44945
+ * Format a list of items, given a heading and an array of formatted items.
44946
+ *
44947
+ * @param {string} heading
44948
+ * @param {string[]} items
44949
+ * @param {Help} helper
44950
+ * @returns string[]
44951
+ */
44952
+ formatItemList(heading, items, helper) {
44953
+ if (items.length === 0) return [];
44954
+
44955
+ return [helper.styleTitle(heading), ...items, ''];
44956
+ }
44957
+
44958
+ /**
44959
+ * Group items by their help group heading.
44960
+ *
44961
+ * @param {Command[] | Option[]} unsortedItems
44962
+ * @param {Command[] | Option[]} visibleItems
44963
+ * @param {Function} getGroup
44964
+ * @returns {Map<string, Command[] | Option[]>}
44965
+ */
44966
+ groupItems(unsortedItems, visibleItems, getGroup) {
44967
+ const result = new Map();
44968
+ // Add groups in order of appearance in unsortedItems.
44969
+ unsortedItems.forEach((item) => {
44970
+ const group = getGroup(item);
44971
+ if (!result.has(group)) result.set(group, []);
44972
+ });
44973
+ // Add items in order of appearance in visibleItems.
44974
+ visibleItems.forEach((item) => {
44975
+ const group = getGroup(item);
44976
+ if (!result.has(group)) {
44977
+ result.set(group, []);
44978
+ }
44979
+ result.get(group).push(item);
44980
+ });
44981
+ return result;
44982
+ }
44983
+
44984
+ /**
44985
+ * Generate the built-in help text.
44986
+ *
44987
+ * @param {Command} cmd
44988
+ * @param {Help} helper
44989
+ * @returns {string}
44990
+ */
44991
+
44992
+ formatHelp(cmd, helper) {
44993
+ const termWidth = helper.padWidth(cmd, helper);
44994
+ const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called
44995
+
44996
+ function callFormatItem(term, description) {
44997
+ return helper.formatItem(term, termWidth, description, helper);
44998
+ }
44999
+
45000
+ // Usage
45001
+ let output = [
45002
+ `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,
45003
+ '',
45004
+ ];
45005
+
45006
+ // Description
45007
+ const commandDescription = helper.commandDescription(cmd);
45008
+ if (commandDescription.length > 0) {
45009
+ output = output.concat([
45010
+ helper.boxWrap(
45011
+ helper.styleCommandDescription(commandDescription),
45012
+ helpWidth,
45013
+ ),
45014
+ '',
45015
+ ]);
45016
+ }
45017
+
45018
+ // Arguments
45019
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
45020
+ return callFormatItem(
45021
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
45022
+ helper.styleArgumentDescription(helper.argumentDescription(argument)),
45023
+ );
45024
+ });
45025
+ output = output.concat(
45026
+ this.formatItemList('Arguments:', argumentList, helper),
45027
+ );
45028
+
45029
+ // Options
45030
+ const optionGroups = this.groupItems(
45031
+ cmd.options,
45032
+ helper.visibleOptions(cmd),
45033
+ (option) => option.helpGroupHeading ?? 'Options:',
45034
+ );
45035
+ optionGroups.forEach((options, group) => {
45036
+ const optionList = options.map((option) => {
45037
+ return callFormatItem(
45038
+ helper.styleOptionTerm(helper.optionTerm(option)),
45039
+ helper.styleOptionDescription(helper.optionDescription(option)),
45040
+ );
45041
+ });
45042
+ output = output.concat(this.formatItemList(group, optionList, helper));
45043
+ });
45044
+
45045
+ if (helper.showGlobalOptions) {
45046
+ const globalOptionList = helper
45047
+ .visibleGlobalOptions(cmd)
45048
+ .map((option) => {
45049
+ return callFormatItem(
45050
+ helper.styleOptionTerm(helper.optionTerm(option)),
45051
+ helper.styleOptionDescription(helper.optionDescription(option)),
45052
+ );
45053
+ });
45054
+ output = output.concat(
45055
+ this.formatItemList('Global Options:', globalOptionList, helper),
45056
+ );
45057
+ }
45058
+
45059
+ // Commands
45060
+ const commandGroups = this.groupItems(
45061
+ cmd.commands,
45062
+ helper.visibleCommands(cmd),
45063
+ (sub) => sub.helpGroup() || 'Commands:',
45064
+ );
45065
+ commandGroups.forEach((commands, group) => {
45066
+ const commandList = commands.map((sub) => {
45067
+ return callFormatItem(
45068
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
45069
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub)),
45070
+ );
45071
+ });
45072
+ output = output.concat(this.formatItemList(group, commandList, helper));
45073
+ });
45074
+
45075
+ return output.join('\n');
45076
+ }
45077
+
45078
+ /**
45079
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
45080
+ *
45081
+ * @param {string} str
45082
+ * @returns {number}
45083
+ */
45084
+ displayWidth(str) {
45085
+ return stripColor(str).length;
45086
+ }
45087
+
45088
+ /**
45089
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
45090
+ *
45091
+ * @param {string} str
45092
+ * @returns {string}
45093
+ */
45094
+ styleTitle(str) {
45095
+ return str;
45096
+ }
45097
+
45098
+ styleUsage(str) {
45099
+ // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:
45100
+ // command subcommand [options] [command] <foo> [bar]
45101
+ return str
45102
+ .split(' ')
45103
+ .map((word) => {
45104
+ if (word === '[options]') return this.styleOptionText(word);
45105
+ if (word === '[command]') return this.styleSubcommandText(word);
45106
+ if (word[0] === '[' || word[0] === '<')
45107
+ return this.styleArgumentText(word);
45108
+ return this.styleCommandText(word); // Restrict to initial words?
45109
+ })
45110
+ .join(' ');
45111
+ }
45112
+ styleCommandDescription(str) {
45113
+ return this.styleDescriptionText(str);
45114
+ }
45115
+ styleOptionDescription(str) {
45116
+ return this.styleDescriptionText(str);
45117
+ }
45118
+ styleSubcommandDescription(str) {
45119
+ return this.styleDescriptionText(str);
45120
+ }
45121
+ styleArgumentDescription(str) {
45122
+ return this.styleDescriptionText(str);
45123
+ }
45124
+ styleDescriptionText(str) {
45125
+ return str;
45126
+ }
45127
+ styleOptionTerm(str) {
45128
+ return this.styleOptionText(str);
45129
+ }
45130
+ styleSubcommandTerm(str) {
45131
+ // This is very like usage with lots of parts! Assume default string which is formed like:
45132
+ // subcommand [options] <foo> [bar]
45133
+ return str
45134
+ .split(' ')
45135
+ .map((word) => {
45136
+ if (word === '[options]') return this.styleOptionText(word);
45137
+ if (word[0] === '[' || word[0] === '<')
45138
+ return this.styleArgumentText(word);
45139
+ return this.styleSubcommandText(word); // Restrict to initial words?
45140
+ })
45141
+ .join(' ');
45142
+ }
45143
+ styleArgumentTerm(str) {
45144
+ return this.styleArgumentText(str);
45145
+ }
45146
+ styleOptionText(str) {
45147
+ return str;
45148
+ }
45149
+ styleArgumentText(str) {
45150
+ return str;
45151
+ }
45152
+ styleSubcommandText(str) {
45153
+ return str;
45154
+ }
45155
+ styleCommandText(str) {
45156
+ return str;
45157
+ }
45158
+
45159
+ /**
45160
+ * Calculate the pad width from the maximum term length.
45161
+ *
45162
+ * @param {Command} cmd
45163
+ * @param {Help} helper
45164
+ * @returns {number}
45165
+ */
45166
+
45167
+ padWidth(cmd, helper) {
45168
+ return Math.max(
45169
+ helper.longestOptionTermLength(cmd, helper),
45170
+ helper.longestGlobalOptionTermLength(cmd, helper),
45171
+ helper.longestSubcommandTermLength(cmd, helper),
45172
+ helper.longestArgumentTermLength(cmd, helper),
45173
+ );
45174
+ }
45175
+
45176
+ /**
45177
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
45178
+ *
45179
+ * @param {string} str
45180
+ * @returns {boolean}
45181
+ */
45182
+ preformatted(str) {
45183
+ return /\n[^\S\r\n]/.test(str);
45184
+ }
45185
+
45186
+ /**
45187
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
45188
+ *
45189
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
45190
+ * TTT DDD DDDD
45191
+ * DD DDD
45192
+ *
45193
+ * @param {string} term
45194
+ * @param {number} termWidth
45195
+ * @param {string} description
45196
+ * @param {Help} helper
45197
+ * @returns {string}
45198
+ */
45199
+ formatItem(term, termWidth, description, helper) {
45200
+ const itemIndent = 2;
45201
+ const itemIndentStr = ' '.repeat(itemIndent);
45202
+ if (!description) return itemIndentStr + term;
45203
+
45204
+ // Pad the term out to a consistent width, so descriptions are aligned.
45205
+ const paddedTerm = term.padEnd(
45206
+ termWidth + term.length - helper.displayWidth(term),
45207
+ );
45208
+
45209
+ // Format the description.
45210
+ const spacerWidth = 2; // between term and description
45211
+ const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called
45212
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
45213
+ let formattedDescription;
45214
+ if (
45215
+ remainingWidth < this.minWidthToWrap ||
45216
+ helper.preformatted(description)
45217
+ ) {
45218
+ formattedDescription = description;
45219
+ } else {
45220
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
45221
+ formattedDescription = wrappedDescription.replace(
45222
+ /\n/g,
45223
+ '\n' + ' '.repeat(termWidth + spacerWidth),
45224
+ );
45225
+ }
45226
+
45227
+ // Construct and overall indent.
45228
+ return (
45229
+ itemIndentStr +
45230
+ paddedTerm +
45231
+ ' '.repeat(spacerWidth) +
45232
+ formattedDescription.replace(/\n/g, `\n${itemIndentStr}`)
45233
+ );
45234
+ }
45235
+
45236
+ /**
45237
+ * Wrap a string at whitespace, preserving existing line breaks.
45238
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
45239
+ *
45240
+ * @param {string} str
45241
+ * @param {number} width
45242
+ * @returns {string}
45243
+ */
45244
+ boxWrap(str, width) {
45245
+ if (width < this.minWidthToWrap) return str;
45246
+
45247
+ const rawLines = str.split(/\r\n|\n/);
45248
+ // split up text by whitespace
45249
+ const chunkPattern = /[\s]*[^\s]+/g;
45250
+ const wrappedLines = [];
45251
+ rawLines.forEach((line) => {
45252
+ const chunks = line.match(chunkPattern);
45253
+ if (chunks === null) {
45254
+ wrappedLines.push('');
45255
+ return;
45256
+ }
45257
+
45258
+ let sumChunks = [chunks.shift()];
45259
+ let sumWidth = this.displayWidth(sumChunks[0]);
45260
+ chunks.forEach((chunk) => {
45261
+ const visibleWidth = this.displayWidth(chunk);
45262
+ // Accumulate chunks while they fit into width.
45263
+ if (sumWidth + visibleWidth <= width) {
45264
+ sumChunks.push(chunk);
45265
+ sumWidth += visibleWidth;
45266
+ return;
45267
+ }
45268
+ wrappedLines.push(sumChunks.join(''));
45269
+
45270
+ const nextChunk = chunk.trimStart(); // trim space at line break
45271
+ sumChunks = [nextChunk];
45272
+ sumWidth = this.displayWidth(nextChunk);
45273
+ });
45274
+ wrappedLines.push(sumChunks.join(''));
45275
+ });
45276
+
45277
+ return wrappedLines.join('\n');
45278
+ }
45279
+ }
45280
+
45281
+ /**
45282
+ * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
45283
+ *
45284
+ * @param {string} str
45285
+ * @returns {string}
45286
+ * @package
45287
+ */
45288
+
45289
+ function stripColor(str) {
45290
+ // eslint-disable-next-line no-control-regex
45291
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
45292
+ return str.replace(sgrPattern, '');
45293
+ }
45294
+
45295
+ exports.Help = Help;
45296
+ exports.stripColor = stripColor;
45297
+
45298
+
45299
+ /***/ }),
45300
+
45301
+ /***/ 7546:
45302
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
45303
+
45304
+ const { InvalidArgumentError } = __nccwpck_require__(9073);
45305
+
45306
+ class Option {
45307
+ /**
45308
+ * Initialize a new `Option` with the given `flags` and `description`.
45309
+ *
45310
+ * @param {string} flags
45311
+ * @param {string} [description]
45312
+ */
45313
+
45314
+ constructor(flags, description) {
45315
+ this.flags = flags;
45316
+ this.description = description || '';
45317
+
45318
+ this.required = flags.includes('<'); // A value must be supplied when the option is specified.
45319
+ this.optional = flags.includes('['); // A value is optional when the option is specified.
45320
+ // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
45321
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
45322
+ this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
45323
+ const optionFlags = splitOptionFlags(flags);
45324
+ this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).
45325
+ this.long = optionFlags.longFlag;
45326
+ this.negate = false;
45327
+ if (this.long) {
45328
+ this.negate = this.long.startsWith('--no-');
45329
+ }
45330
+ this.defaultValue = undefined;
45331
+ this.defaultValueDescription = undefined;
45332
+ this.presetArg = undefined;
45333
+ this.envVar = undefined;
45334
+ this.parseArg = undefined;
45335
+ this.hidden = false;
45336
+ this.argChoices = undefined;
45337
+ this.conflictsWith = [];
45338
+ this.implied = undefined;
45339
+ this.helpGroupHeading = undefined; // soft initialised when option added to command
45340
+ }
45341
+
45342
+ /**
45343
+ * Set the default value, and optionally supply the description to be displayed in the help.
45344
+ *
45345
+ * @param {*} value
45346
+ * @param {string} [description]
45347
+ * @return {Option}
45348
+ */
45349
+
45350
+ default(value, description) {
45351
+ this.defaultValue = value;
45352
+ this.defaultValueDescription = description;
45353
+ return this;
45354
+ }
45355
+
45356
+ /**
45357
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
45358
+ * The custom processing (parseArg) is called.
45359
+ *
45360
+ * @example
45361
+ * new Option('--color').default('GREYSCALE').preset('RGB');
45362
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
45363
+ *
45364
+ * @param {*} arg
45365
+ * @return {Option}
45366
+ */
45367
+
45368
+ preset(arg) {
45369
+ this.presetArg = arg;
45370
+ return this;
45371
+ }
45372
+
45373
+ /**
45374
+ * Add option name(s) that conflict with this option.
45375
+ * An error will be displayed if conflicting options are found during parsing.
45376
+ *
45377
+ * @example
45378
+ * new Option('--rgb').conflicts('cmyk');
45379
+ * new Option('--js').conflicts(['ts', 'jsx']);
45380
+ *
45381
+ * @param {(string | string[])} names
45382
+ * @return {Option}
45383
+ */
45384
+
45385
+ conflicts(names) {
45386
+ this.conflictsWith = this.conflictsWith.concat(names);
45387
+ return this;
45388
+ }
45389
+
45390
+ /**
45391
+ * Specify implied option values for when this option is set and the implied options are not.
45392
+ *
45393
+ * The custom processing (parseArg) is not called on the implied values.
45394
+ *
45395
+ * @example
45396
+ * program
45397
+ * .addOption(new Option('--log', 'write logging information to file'))
45398
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
45399
+ *
45400
+ * @param {object} impliedOptionValues
45401
+ * @return {Option}
45402
+ */
45403
+ implies(impliedOptionValues) {
45404
+ let newImplied = impliedOptionValues;
45405
+ if (typeof impliedOptionValues === 'string') {
45406
+ // string is not documented, but easy mistake and we can do what user probably intended.
45407
+ newImplied = { [impliedOptionValues]: true };
45408
+ }
45409
+ this.implied = Object.assign(this.implied || {}, newImplied);
45410
+ return this;
45411
+ }
45412
+
45413
+ /**
45414
+ * Set environment variable to check for option value.
45415
+ *
45416
+ * An environment variable is only used if when processed the current option value is
45417
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
45418
+ *
45419
+ * @param {string} name
45420
+ * @return {Option}
45421
+ */
45422
+
45423
+ env(name) {
45424
+ this.envVar = name;
45425
+ return this;
45426
+ }
45427
+
45428
+ /**
45429
+ * Set the custom handler for processing CLI option arguments into option values.
45430
+ *
45431
+ * @param {Function} [fn]
45432
+ * @return {Option}
45433
+ */
45434
+
45435
+ argParser(fn) {
45436
+ this.parseArg = fn;
45437
+ return this;
45438
+ }
45439
+
45440
+ /**
45441
+ * Whether the option is mandatory and must have a value after parsing.
45442
+ *
45443
+ * @param {boolean} [mandatory=true]
45444
+ * @return {Option}
45445
+ */
45446
+
45447
+ makeOptionMandatory(mandatory = true) {
45448
+ this.mandatory = !!mandatory;
45449
+ return this;
45450
+ }
45451
+
45452
+ /**
45453
+ * Hide option in help.
45454
+ *
45455
+ * @param {boolean} [hide=true]
45456
+ * @return {Option}
45457
+ */
45458
+
45459
+ hideHelp(hide = true) {
45460
+ this.hidden = !!hide;
45461
+ return this;
45462
+ }
45463
+
45464
+ /**
45465
+ * @package
45466
+ */
45467
+
45468
+ _collectValue(value, previous) {
45469
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
45470
+ return [value];
45471
+ }
45472
+
45473
+ previous.push(value);
45474
+ return previous;
45475
+ }
45476
+
45477
+ /**
45478
+ * Only allow option value to be one of choices.
45479
+ *
45480
+ * @param {string[]} values
45481
+ * @return {Option}
45482
+ */
45483
+
45484
+ choices(values) {
45485
+ this.argChoices = values.slice();
45486
+ this.parseArg = (arg, previous) => {
45487
+ if (!this.argChoices.includes(arg)) {
45488
+ throw new InvalidArgumentError(
45489
+ `Allowed choices are ${this.argChoices.join(', ')}.`,
45490
+ );
45491
+ }
45492
+ if (this.variadic) {
45493
+ return this._collectValue(arg, previous);
45494
+ }
45495
+ return arg;
45496
+ };
45497
+ return this;
45498
+ }
45499
+
45500
+ /**
45501
+ * Return option name.
45502
+ *
45503
+ * @return {string}
45504
+ */
45505
+
45506
+ name() {
45507
+ if (this.long) {
45508
+ return this.long.replace(/^--/, '');
45509
+ }
45510
+ return this.short.replace(/^-/, '');
45511
+ }
45512
+
45513
+ /**
45514
+ * Return option name, in a camelcase format that can be used
45515
+ * as an object attribute key.
45516
+ *
45517
+ * @return {string}
45518
+ */
45519
+
45520
+ attributeName() {
45521
+ if (this.negate) {
45522
+ return camelcase(this.name().replace(/^no-/, ''));
45523
+ }
45524
+ return camelcase(this.name());
45525
+ }
45526
+
45527
+ /**
45528
+ * Set the help group heading.
45529
+ *
45530
+ * @param {string} heading
45531
+ * @return {Option}
45532
+ */
45533
+ helpGroup(heading) {
45534
+ this.helpGroupHeading = heading;
45535
+ return this;
45536
+ }
45537
+
45538
+ /**
45539
+ * Check if `arg` matches the short or long flag.
45540
+ *
45541
+ * @param {string} arg
45542
+ * @return {boolean}
45543
+ * @package
45544
+ */
45545
+
45546
+ is(arg) {
45547
+ return this.short === arg || this.long === arg;
45548
+ }
45549
+
45550
+ /**
45551
+ * Return whether a boolean option.
45552
+ *
45553
+ * Options are one of boolean, negated, required argument, or optional argument.
45554
+ *
45555
+ * @return {boolean}
45556
+ * @package
45557
+ */
45558
+
45559
+ isBoolean() {
45560
+ return !this.required && !this.optional && !this.negate;
45561
+ }
45562
+ }
45563
+
45564
+ /**
45565
+ * This class is to make it easier to work with dual options, without changing the existing
45566
+ * implementation. We support separate dual options for separate positive and negative options,
45567
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
45568
+ * use cases, but is tricky for others where we want separate behaviours despite
45569
+ * the single shared option value.
45570
+ */
45571
+ class DualOptions {
45572
+ /**
45573
+ * @param {Option[]} options
45574
+ */
45575
+ constructor(options) {
45576
+ this.positiveOptions = new Map();
45577
+ this.negativeOptions = new Map();
45578
+ this.dualOptions = new Set();
45579
+ options.forEach((option) => {
45580
+ if (option.negate) {
45581
+ this.negativeOptions.set(option.attributeName(), option);
45582
+ } else {
45583
+ this.positiveOptions.set(option.attributeName(), option);
45584
+ }
45585
+ });
45586
+ this.negativeOptions.forEach((value, key) => {
45587
+ if (this.positiveOptions.has(key)) {
45588
+ this.dualOptions.add(key);
45589
+ }
45590
+ });
45591
+ }
45592
+
45593
+ /**
45594
+ * Did the value come from the option, and not from possible matching dual option?
45595
+ *
45596
+ * @param {*} value
45597
+ * @param {Option} option
45598
+ * @returns {boolean}
45599
+ */
45600
+ valueFromOption(value, option) {
45601
+ const optionKey = option.attributeName();
45602
+ if (!this.dualOptions.has(optionKey)) return true;
45603
+
45604
+ // Use the value to deduce if (probably) came from the option.
45605
+ const preset = this.negativeOptions.get(optionKey).presetArg;
45606
+ const negativeValue = preset !== undefined ? preset : false;
45607
+ return option.negate === (negativeValue === value);
45608
+ }
45609
+ }
45610
+
45611
+ /**
45612
+ * Convert string from kebab-case to camelCase.
45613
+ *
45614
+ * @param {string} str
45615
+ * @return {string}
45616
+ * @private
45617
+ */
45618
+
45619
+ function camelcase(str) {
45620
+ return str.split('-').reduce((str, word) => {
45621
+ return str + word[0].toUpperCase() + word.slice(1);
45622
+ });
45623
+ }
45624
+
45625
+ /**
45626
+ * Split the short and long flag out of something like '-m,--mixed <value>'
45627
+ *
45628
+ * @private
45629
+ */
45630
+
45631
+ function splitOptionFlags(flags) {
45632
+ let shortFlag;
45633
+ let longFlag;
45634
+ // short flag, single dash and single character
45635
+ const shortFlagExp = /^-[^-]$/;
45636
+ // long flag, double dash and at least one character
45637
+ const longFlagExp = /^--[^-]/;
45638
+
45639
+ const flagParts = flags.split(/[ |,]+/).concat('guard');
45640
+ // Normal is short and/or long.
45641
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
45642
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
45643
+ // Long then short. Rarely used but fine.
45644
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
45645
+ shortFlag = flagParts.shift();
45646
+ // Allow two long flags, like '--ws, --workspace'
45647
+ // This is the supported way to have a shortish option flag.
45648
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
45649
+ shortFlag = longFlag;
45650
+ longFlag = flagParts.shift();
45651
+ }
45652
+
45653
+ // Check for unprocessed flag. Fail noisily rather than silently ignore.
45654
+ if (flagParts[0].startsWith('-')) {
45655
+ const unsupportedFlag = flagParts[0];
45656
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
45657
+ if (/^-[^-][^-]/.test(unsupportedFlag))
45658
+ throw new Error(
45659
+ `${baseError}
45660
+ - a short flag is a single dash and a single character
45661
+ - either use a single dash and a single character (for a short flag)
45662
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,
45663
+ );
45664
+ if (shortFlagExp.test(unsupportedFlag))
45665
+ throw new Error(`${baseError}
45666
+ - too many short flags`);
45667
+ if (longFlagExp.test(unsupportedFlag))
45668
+ throw new Error(`${baseError}
45669
+ - too many long flags`);
45670
+
45671
+ throw new Error(`${baseError}
45672
+ - unrecognised flag format`);
45673
+ }
45674
+ if (shortFlag === undefined && longFlag === undefined)
45675
+ throw new Error(
45676
+ `option creation failed due to no flags found in '${flags}'.`,
45677
+ );
45678
+
45679
+ return { shortFlag, longFlag };
45680
+ }
45681
+
45682
+ exports.Option = Option;
45683
+ exports.DualOptions = DualOptions;
45684
+
45685
+
45686
+ /***/ }),
45687
+
45688
+ /***/ 2044:
45689
+ /***/ ((__unused_webpack_module, exports) => {
45690
+
45691
+ const maxDistance = 3;
45692
+
45693
+ function editDistance(a, b) {
45694
+ // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance
45695
+ // Calculating optimal string alignment distance, no substring is edited more than once.
45696
+ // (Simple implementation.)
45697
+
45698
+ // Quick early exit, return worst case.
45699
+ if (Math.abs(a.length - b.length) > maxDistance)
45700
+ return Math.max(a.length, b.length);
45701
+
45702
+ // distance between prefix substrings of a and b
45703
+ const d = [];
45704
+
45705
+ // pure deletions turn a into empty string
45706
+ for (let i = 0; i <= a.length; i++) {
45707
+ d[i] = [i];
45708
+ }
45709
+ // pure insertions turn empty string into b
45710
+ for (let j = 0; j <= b.length; j++) {
45711
+ d[0][j] = j;
45712
+ }
45713
+
45714
+ // fill matrix
45715
+ for (let j = 1; j <= b.length; j++) {
45716
+ for (let i = 1; i <= a.length; i++) {
45717
+ let cost = 1;
45718
+ if (a[i - 1] === b[j - 1]) {
45719
+ cost = 0;
45720
+ } else {
45721
+ cost = 1;
45722
+ }
45723
+ d[i][j] = Math.min(
45724
+ d[i - 1][j] + 1, // deletion
45725
+ d[i][j - 1] + 1, // insertion
45726
+ d[i - 1][j - 1] + cost, // substitution
45727
+ );
45728
+ // transposition
45729
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
45730
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
45731
+ }
45732
+ }
45733
+ }
45734
+
45735
+ return d[a.length][b.length];
45736
+ }
45737
+
45738
+ /**
45739
+ * Find close matches, restricted to same number of edits.
45740
+ *
45741
+ * @param {string} word
45742
+ * @param {string[]} candidates
45743
+ * @returns {string}
45744
+ */
45745
+
45746
+ function suggestSimilar(word, candidates) {
45747
+ if (!candidates || candidates.length === 0) return '';
45748
+ // remove possible duplicates
45749
+ candidates = Array.from(new Set(candidates));
45750
+
45751
+ const searchingOptions = word.startsWith('--');
45752
+ if (searchingOptions) {
45753
+ word = word.slice(2);
45754
+ candidates = candidates.map((candidate) => candidate.slice(2));
45755
+ }
45756
+
45757
+ let similar = [];
45758
+ let bestDistance = maxDistance;
45759
+ const minSimilarity = 0.4;
45760
+ candidates.forEach((candidate) => {
45761
+ if (candidate.length <= 1) return; // no one character guesses
45762
+
45763
+ const distance = editDistance(word, candidate);
45764
+ const length = Math.max(word.length, candidate.length);
45765
+ const similarity = (length - distance) / length;
45766
+ if (similarity > minSimilarity) {
45767
+ if (distance < bestDistance) {
45768
+ // better edit distance, throw away previous worse matches
45769
+ bestDistance = distance;
45770
+ similar = [candidate];
45771
+ } else if (distance === bestDistance) {
45772
+ similar.push(candidate);
45773
+ }
45774
+ }
45775
+ });
45776
+
45777
+ similar.sort((a, b) => a.localeCompare(b));
45778
+ if (searchingOptions) {
45779
+ similar = similar.map((candidate) => `--${candidate}`);
45780
+ }
45781
+
45782
+ if (similar.length > 1) {
45783
+ return `\n(Did you mean one of ${similar.join(', ')}?)`;
45784
+ }
45785
+ if (similar.length === 1) {
45786
+ return `\n(Did you mean ${similar[0]}?)`;
45787
+ }
45788
+ return '';
45789
+ }
45790
+
45791
+ exports.suggestSimilar = suggestSimilar;
45792
+
45793
+
41480
45794
  /***/ }),
41481
45795
 
41482
45796
  /***/ 3728: