zotero-plugin 3.3.2 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/release.js +4084 -209
  2. package/package.json +3 -2
package/bin/release.js CHANGED
@@ -128,15 +128,15 @@
128
128
  }
129
129
  return obj;
130
130
  }
131
- function _parseVault(options) {
132
- const vaultPath = _vaultPath(options);
131
+ function _parseVault(options2) {
132
+ const vaultPath = _vaultPath(options2);
133
133
  const result = DotenvModule.configDotenv({ path: vaultPath });
134
134
  if (!result.parsed) {
135
135
  const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
136
136
  err.code = "MISSING_DATA";
137
137
  throw err;
138
138
  }
139
- const keys = _dotenvKey(options).split(",");
139
+ const keys = _dotenvKey(options2).split(",");
140
140
  const length = keys.length;
141
141
  let decrypted;
142
142
  for (let i = 0; i < length; i++) {
@@ -162,9 +162,9 @@
162
162
  function _debug(message) {
163
163
  console.log(`[dotenv@${version2}][DEBUG] ${message}`);
164
164
  }
165
- function _dotenvKey(options) {
166
- if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
167
- return options.DOTENV_KEY;
165
+ function _dotenvKey(options2) {
166
+ if (options2 && options2.DOTENV_KEY && options2.DOTENV_KEY.length > 0) {
167
+ return options2.DOTENV_KEY;
168
168
  }
169
169
  if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
170
170
  return process.env.DOTENV_KEY;
@@ -204,17 +204,17 @@
204
204
  }
205
205
  return { ciphertext, key };
206
206
  }
207
- function _vaultPath(options) {
207
+ function _vaultPath(options2) {
208
208
  let possibleVaultPath = null;
209
- if (options && options.path && options.path.length > 0) {
210
- if (Array.isArray(options.path)) {
211
- for (const filepath of options.path) {
209
+ if (options2 && options2.path && options2.path.length > 0) {
210
+ if (Array.isArray(options2.path)) {
211
+ for (const filepath of options2.path) {
212
212
  if (fs3.existsSync(filepath)) {
213
213
  possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
214
214
  }
215
215
  }
216
216
  } else {
217
- possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
217
+ possibleVaultPath = options2.path.endsWith(".vault") ? options2.path : `${options2.path}.vault`;
218
218
  }
219
219
  } else {
220
220
  possibleVaultPath = path3.resolve(process.cwd(), ".env.vault");
@@ -227,34 +227,34 @@
227
227
  function _resolveHome(envPath) {
228
228
  return envPath[0] === "~" ? path3.join(os2.homedir(), envPath.slice(1)) : envPath;
229
229
  }
230
- function _configVault(options) {
230
+ function _configVault(options2) {
231
231
  _log("Loading env from encrypted .env.vault");
232
- const parsed = DotenvModule._parseVault(options);
232
+ const parsed = DotenvModule._parseVault(options2);
233
233
  let processEnv = process.env;
234
- if (options && options.processEnv != null) {
235
- processEnv = options.processEnv;
234
+ if (options2 && options2.processEnv != null) {
235
+ processEnv = options2.processEnv;
236
236
  }
237
- DotenvModule.populate(processEnv, parsed, options);
237
+ DotenvModule.populate(processEnv, parsed, options2);
238
238
  return { parsed };
239
239
  }
240
- function configDotenv(options) {
240
+ function configDotenv(options2) {
241
241
  const dotenvPath = path3.resolve(process.cwd(), ".env");
242
242
  let encoding = "utf8";
243
- const debug = Boolean(options && options.debug);
244
- if (options && options.encoding) {
245
- encoding = options.encoding;
243
+ const debug = Boolean(options2 && options2.debug);
244
+ if (options2 && options2.encoding) {
245
+ encoding = options2.encoding;
246
246
  } else {
247
247
  if (debug) {
248
248
  _debug("No encoding is specified. UTF-8 is used by default");
249
249
  }
250
250
  }
251
251
  let optionPaths = [dotenvPath];
252
- if (options && options.path) {
253
- if (!Array.isArray(options.path)) {
254
- optionPaths = [_resolveHome(options.path)];
252
+ if (options2 && options2.path) {
253
+ if (!Array.isArray(options2.path)) {
254
+ optionPaths = [_resolveHome(options2.path)];
255
255
  } else {
256
256
  optionPaths = [];
257
- for (const filepath of options.path) {
257
+ for (const filepath of options2.path) {
258
258
  optionPaths.push(_resolveHome(filepath));
259
259
  }
260
260
  }
@@ -264,7 +264,7 @@
264
264
  for (const path4 of optionPaths) {
265
265
  try {
266
266
  const parsed = DotenvModule.parse(fs3.readFileSync(path4, { encoding }));
267
- DotenvModule.populate(parsedAll, parsed, options);
267
+ DotenvModule.populate(parsedAll, parsed, options2);
268
268
  } catch (e) {
269
269
  if (debug) {
270
270
  _debug(`Failed to load ${path4} ${e.message}`);
@@ -273,26 +273,26 @@
273
273
  }
274
274
  }
275
275
  let processEnv = process.env;
276
- if (options && options.processEnv != null) {
277
- processEnv = options.processEnv;
276
+ if (options2 && options2.processEnv != null) {
277
+ processEnv = options2.processEnv;
278
278
  }
279
- DotenvModule.populate(processEnv, parsedAll, options);
279
+ DotenvModule.populate(processEnv, parsedAll, options2);
280
280
  if (lastError) {
281
281
  return { parsed: parsedAll, error: lastError };
282
282
  } else {
283
283
  return { parsed: parsedAll };
284
284
  }
285
285
  }
286
- function config(options) {
287
- if (_dotenvKey(options).length === 0) {
288
- return DotenvModule.configDotenv(options);
286
+ function config(options2) {
287
+ if (_dotenvKey(options2).length === 0) {
288
+ return DotenvModule.configDotenv(options2);
289
289
  }
290
- const vaultPath = _vaultPath(options);
290
+ const vaultPath = _vaultPath(options2);
291
291
  if (!vaultPath) {
292
292
  _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
293
- return DotenvModule.configDotenv(options);
293
+ return DotenvModule.configDotenv(options2);
294
294
  }
295
- return DotenvModule._configVault(options);
295
+ return DotenvModule._configVault(options2);
296
296
  }
297
297
  function decrypt(encrypted, keyStr) {
298
298
  const key = Buffer.from(keyStr.slice(-64), "hex");
@@ -321,9 +321,9 @@
321
321
  }
322
322
  }
323
323
  }
324
- function populate(processEnv, parsed, options = {}) {
325
- const debug = Boolean(options && options.debug);
326
- const override = Boolean(options && options.override);
324
+ function populate(processEnv, parsed, options2 = {}) {
325
+ const debug = Boolean(options2 && options2.debug);
326
+ const override = Boolean(options2 && options2.override);
327
327
  if (typeof parsed !== "object") {
328
328
  const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
329
329
  err.code = "OBJECT_REQUIRED";
@@ -369,23 +369,23 @@
369
369
  // node_modules/dotenv/lib/env-options.js
370
370
  var require_env_options = __commonJS({
371
371
  "node_modules/dotenv/lib/env-options.js"(exports, module) {
372
- var options = {};
372
+ var options2 = {};
373
373
  if (process.env.DOTENV_CONFIG_ENCODING != null) {
374
- options.encoding = process.env.DOTENV_CONFIG_ENCODING;
374
+ options2.encoding = process.env.DOTENV_CONFIG_ENCODING;
375
375
  }
376
376
  if (process.env.DOTENV_CONFIG_PATH != null) {
377
- options.path = process.env.DOTENV_CONFIG_PATH;
377
+ options2.path = process.env.DOTENV_CONFIG_PATH;
378
378
  }
379
379
  if (process.env.DOTENV_CONFIG_DEBUG != null) {
380
- options.debug = process.env.DOTENV_CONFIG_DEBUG;
380
+ options2.debug = process.env.DOTENV_CONFIG_DEBUG;
381
381
  }
382
382
  if (process.env.DOTENV_CONFIG_OVERRIDE != null) {
383
- options.override = process.env.DOTENV_CONFIG_OVERRIDE;
383
+ options2.override = process.env.DOTENV_CONFIG_OVERRIDE;
384
384
  }
385
385
  if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) {
386
- options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY;
386
+ options2.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY;
387
387
  }
388
- module.exports = options;
388
+ module.exports = options2;
389
389
  }
390
390
  });
391
391
 
@@ -405,6 +405,3284 @@
405
405
  }
406
406
  });
407
407
 
408
+ // node_modules/commander/lib/error.js
409
+ var require_error = __commonJS({
410
+ "node_modules/commander/lib/error.js"(exports) {
411
+ var CommanderError2 = class extends Error {
412
+ /**
413
+ * Constructs the CommanderError class
414
+ * @param {number} exitCode suggested exit code which could be used with process.exit
415
+ * @param {string} code an id string representing the error
416
+ * @param {string} message human-readable description of the error
417
+ */
418
+ constructor(exitCode, code, message) {
419
+ super(message);
420
+ Error.captureStackTrace(this, this.constructor);
421
+ this.name = this.constructor.name;
422
+ this.code = code;
423
+ this.exitCode = exitCode;
424
+ this.nestedError = void 0;
425
+ }
426
+ };
427
+ var InvalidArgumentError2 = class extends CommanderError2 {
428
+ /**
429
+ * Constructs the InvalidArgumentError class
430
+ * @param {string} [message] explanation of why argument is invalid
431
+ */
432
+ constructor(message) {
433
+ super(1, "commander.invalidArgument", message);
434
+ Error.captureStackTrace(this, this.constructor);
435
+ this.name = this.constructor.name;
436
+ }
437
+ };
438
+ exports.CommanderError = CommanderError2;
439
+ exports.InvalidArgumentError = InvalidArgumentError2;
440
+ }
441
+ });
442
+
443
+ // node_modules/commander/lib/argument.js
444
+ var require_argument = __commonJS({
445
+ "node_modules/commander/lib/argument.js"(exports) {
446
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
447
+ var Argument2 = class {
448
+ /**
449
+ * Initialize a new command argument with the given name and description.
450
+ * The default is that the argument is required, and you can explicitly
451
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
452
+ *
453
+ * @param {string} name
454
+ * @param {string} [description]
455
+ */
456
+ constructor(name, description) {
457
+ this.description = description || "";
458
+ this.variadic = false;
459
+ this.parseArg = void 0;
460
+ this.defaultValue = void 0;
461
+ this.defaultValueDescription = void 0;
462
+ this.argChoices = void 0;
463
+ switch (name[0]) {
464
+ case "<":
465
+ this.required = true;
466
+ this._name = name.slice(1, -1);
467
+ break;
468
+ case "[":
469
+ this.required = false;
470
+ this._name = name.slice(1, -1);
471
+ break;
472
+ default:
473
+ this.required = true;
474
+ this._name = name;
475
+ break;
476
+ }
477
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
478
+ this.variadic = true;
479
+ this._name = this._name.slice(0, -3);
480
+ }
481
+ }
482
+ /**
483
+ * Return argument name.
484
+ *
485
+ * @return {string}
486
+ */
487
+ name() {
488
+ return this._name;
489
+ }
490
+ /**
491
+ * @package
492
+ */
493
+ _concatValue(value, previous) {
494
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
495
+ return [value];
496
+ }
497
+ return previous.concat(value);
498
+ }
499
+ /**
500
+ * Set the default value, and optionally supply the description to be displayed in the help.
501
+ *
502
+ * @param {*} value
503
+ * @param {string} [description]
504
+ * @return {Argument}
505
+ */
506
+ default(value, description) {
507
+ this.defaultValue = value;
508
+ this.defaultValueDescription = description;
509
+ return this;
510
+ }
511
+ /**
512
+ * Set the custom handler for processing CLI command arguments into argument values.
513
+ *
514
+ * @param {Function} [fn]
515
+ * @return {Argument}
516
+ */
517
+ argParser(fn) {
518
+ this.parseArg = fn;
519
+ return this;
520
+ }
521
+ /**
522
+ * Only allow argument value to be one of choices.
523
+ *
524
+ * @param {string[]} values
525
+ * @return {Argument}
526
+ */
527
+ choices(values) {
528
+ this.argChoices = values.slice();
529
+ this.parseArg = (arg, previous) => {
530
+ if (!this.argChoices.includes(arg)) {
531
+ throw new InvalidArgumentError2(
532
+ `Allowed choices are ${this.argChoices.join(", ")}.`
533
+ );
534
+ }
535
+ if (this.variadic) {
536
+ return this._concatValue(arg, previous);
537
+ }
538
+ return arg;
539
+ };
540
+ return this;
541
+ }
542
+ /**
543
+ * Make argument required.
544
+ *
545
+ * @returns {Argument}
546
+ */
547
+ argRequired() {
548
+ this.required = true;
549
+ return this;
550
+ }
551
+ /**
552
+ * Make argument optional.
553
+ *
554
+ * @returns {Argument}
555
+ */
556
+ argOptional() {
557
+ this.required = false;
558
+ return this;
559
+ }
560
+ };
561
+ function humanReadableArgName(arg) {
562
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
563
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
564
+ }
565
+ exports.Argument = Argument2;
566
+ exports.humanReadableArgName = humanReadableArgName;
567
+ }
568
+ });
569
+
570
+ // node_modules/commander/lib/help.js
571
+ var require_help = __commonJS({
572
+ "node_modules/commander/lib/help.js"(exports) {
573
+ var { humanReadableArgName } = require_argument();
574
+ var Help2 = class {
575
+ constructor() {
576
+ this.helpWidth = void 0;
577
+ this.minWidthToWrap = 40;
578
+ this.sortSubcommands = false;
579
+ this.sortOptions = false;
580
+ this.showGlobalOptions = false;
581
+ }
582
+ /**
583
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
584
+ * and just before calling `formatHelp()`.
585
+ *
586
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
587
+ *
588
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
589
+ */
590
+ prepareContext(contextOptions) {
591
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
592
+ }
593
+ /**
594
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
595
+ *
596
+ * @param {Command} cmd
597
+ * @returns {Command[]}
598
+ */
599
+ visibleCommands(cmd) {
600
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
601
+ const helpCommand = cmd._getHelpCommand();
602
+ if (helpCommand && !helpCommand._hidden) {
603
+ visibleCommands.push(helpCommand);
604
+ }
605
+ if (this.sortSubcommands) {
606
+ visibleCommands.sort((a, b) => {
607
+ return a.name().localeCompare(b.name());
608
+ });
609
+ }
610
+ return visibleCommands;
611
+ }
612
+ /**
613
+ * Compare options for sort.
614
+ *
615
+ * @param {Option} a
616
+ * @param {Option} b
617
+ * @returns {number}
618
+ */
619
+ compareOptions(a, b) {
620
+ const getSortKey = (option) => {
621
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
622
+ };
623
+ return getSortKey(a).localeCompare(getSortKey(b));
624
+ }
625
+ /**
626
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
627
+ *
628
+ * @param {Command} cmd
629
+ * @returns {Option[]}
630
+ */
631
+ visibleOptions(cmd) {
632
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
633
+ const helpOption = cmd._getHelpOption();
634
+ if (helpOption && !helpOption.hidden) {
635
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
636
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
637
+ if (!removeShort && !removeLong) {
638
+ visibleOptions.push(helpOption);
639
+ } else if (helpOption.long && !removeLong) {
640
+ visibleOptions.push(
641
+ cmd.createOption(helpOption.long, helpOption.description)
642
+ );
643
+ } else if (helpOption.short && !removeShort) {
644
+ visibleOptions.push(
645
+ cmd.createOption(helpOption.short, helpOption.description)
646
+ );
647
+ }
648
+ }
649
+ if (this.sortOptions) {
650
+ visibleOptions.sort(this.compareOptions);
651
+ }
652
+ return visibleOptions;
653
+ }
654
+ /**
655
+ * Get an array of the visible global options. (Not including help.)
656
+ *
657
+ * @param {Command} cmd
658
+ * @returns {Option[]}
659
+ */
660
+ visibleGlobalOptions(cmd) {
661
+ if (!this.showGlobalOptions) return [];
662
+ const globalOptions = [];
663
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
664
+ const visibleOptions = ancestorCmd.options.filter(
665
+ (option) => !option.hidden
666
+ );
667
+ globalOptions.push(...visibleOptions);
668
+ }
669
+ if (this.sortOptions) {
670
+ globalOptions.sort(this.compareOptions);
671
+ }
672
+ return globalOptions;
673
+ }
674
+ /**
675
+ * Get an array of the arguments if any have a description.
676
+ *
677
+ * @param {Command} cmd
678
+ * @returns {Argument[]}
679
+ */
680
+ visibleArguments(cmd) {
681
+ if (cmd._argsDescription) {
682
+ cmd.registeredArguments.forEach((argument) => {
683
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
684
+ });
685
+ }
686
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
687
+ return cmd.registeredArguments;
688
+ }
689
+ return [];
690
+ }
691
+ /**
692
+ * Get the command term to show in the list of subcommands.
693
+ *
694
+ * @param {Command} cmd
695
+ * @returns {string}
696
+ */
697
+ subcommandTerm(cmd) {
698
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
699
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
700
+ (args ? " " + args : "");
701
+ }
702
+ /**
703
+ * Get the option term to show in the list of options.
704
+ *
705
+ * @param {Option} option
706
+ * @returns {string}
707
+ */
708
+ optionTerm(option) {
709
+ return option.flags;
710
+ }
711
+ /**
712
+ * Get the argument term to show in the list of arguments.
713
+ *
714
+ * @param {Argument} argument
715
+ * @returns {string}
716
+ */
717
+ argumentTerm(argument) {
718
+ return argument.name();
719
+ }
720
+ /**
721
+ * Get the longest command term length.
722
+ *
723
+ * @param {Command} cmd
724
+ * @param {Help} helper
725
+ * @returns {number}
726
+ */
727
+ longestSubcommandTermLength(cmd, helper) {
728
+ return helper.visibleCommands(cmd).reduce((max, command) => {
729
+ return Math.max(
730
+ max,
731
+ this.displayWidth(
732
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
733
+ )
734
+ );
735
+ }, 0);
736
+ }
737
+ /**
738
+ * Get the longest option term length.
739
+ *
740
+ * @param {Command} cmd
741
+ * @param {Help} helper
742
+ * @returns {number}
743
+ */
744
+ longestOptionTermLength(cmd, helper) {
745
+ return helper.visibleOptions(cmd).reduce((max, option) => {
746
+ return Math.max(
747
+ max,
748
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
749
+ );
750
+ }, 0);
751
+ }
752
+ /**
753
+ * Get the longest global option term length.
754
+ *
755
+ * @param {Command} cmd
756
+ * @param {Help} helper
757
+ * @returns {number}
758
+ */
759
+ longestGlobalOptionTermLength(cmd, helper) {
760
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
761
+ return Math.max(
762
+ max,
763
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
764
+ );
765
+ }, 0);
766
+ }
767
+ /**
768
+ * Get the longest argument term length.
769
+ *
770
+ * @param {Command} cmd
771
+ * @param {Help} helper
772
+ * @returns {number}
773
+ */
774
+ longestArgumentTermLength(cmd, helper) {
775
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
776
+ return Math.max(
777
+ max,
778
+ this.displayWidth(
779
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
780
+ )
781
+ );
782
+ }, 0);
783
+ }
784
+ /**
785
+ * Get the command usage to be displayed at the top of the built-in help.
786
+ *
787
+ * @param {Command} cmd
788
+ * @returns {string}
789
+ */
790
+ commandUsage(cmd) {
791
+ let cmdName = cmd._name;
792
+ if (cmd._aliases[0]) {
793
+ cmdName = cmdName + "|" + cmd._aliases[0];
794
+ }
795
+ let ancestorCmdNames = "";
796
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
797
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
798
+ }
799
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
800
+ }
801
+ /**
802
+ * Get the description for the command.
803
+ *
804
+ * @param {Command} cmd
805
+ * @returns {string}
806
+ */
807
+ commandDescription(cmd) {
808
+ return cmd.description();
809
+ }
810
+ /**
811
+ * Get the subcommand summary to show in the list of subcommands.
812
+ * (Fallback to description for backwards compatibility.)
813
+ *
814
+ * @param {Command} cmd
815
+ * @returns {string}
816
+ */
817
+ subcommandDescription(cmd) {
818
+ return cmd.summary() || cmd.description();
819
+ }
820
+ /**
821
+ * Get the option description to show in the list of options.
822
+ *
823
+ * @param {Option} option
824
+ * @return {string}
825
+ */
826
+ optionDescription(option) {
827
+ const extraInfo = [];
828
+ if (option.argChoices) {
829
+ extraInfo.push(
830
+ // use stringify to match the display of the default value
831
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
832
+ );
833
+ }
834
+ if (option.defaultValue !== void 0) {
835
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
836
+ if (showDefault) {
837
+ extraInfo.push(
838
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
839
+ );
840
+ }
841
+ }
842
+ if (option.presetArg !== void 0 && option.optional) {
843
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
844
+ }
845
+ if (option.envVar !== void 0) {
846
+ extraInfo.push(`env: ${option.envVar}`);
847
+ }
848
+ if (extraInfo.length > 0) {
849
+ return `${option.description} (${extraInfo.join(", ")})`;
850
+ }
851
+ return option.description;
852
+ }
853
+ /**
854
+ * Get the argument description to show in the list of arguments.
855
+ *
856
+ * @param {Argument} argument
857
+ * @return {string}
858
+ */
859
+ argumentDescription(argument) {
860
+ const extraInfo = [];
861
+ if (argument.argChoices) {
862
+ extraInfo.push(
863
+ // use stringify to match the display of the default value
864
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
865
+ );
866
+ }
867
+ if (argument.defaultValue !== void 0) {
868
+ extraInfo.push(
869
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
870
+ );
871
+ }
872
+ if (extraInfo.length > 0) {
873
+ const extraDescription = `(${extraInfo.join(", ")})`;
874
+ if (argument.description) {
875
+ return `${argument.description} ${extraDescription}`;
876
+ }
877
+ return extraDescription;
878
+ }
879
+ return argument.description;
880
+ }
881
+ /**
882
+ * Generate the built-in help text.
883
+ *
884
+ * @param {Command} cmd
885
+ * @param {Help} helper
886
+ * @returns {string}
887
+ */
888
+ formatHelp(cmd, helper) {
889
+ const termWidth = helper.padWidth(cmd, helper);
890
+ const helpWidth = helper.helpWidth ?? 80;
891
+ function callFormatItem(term, description) {
892
+ return helper.formatItem(term, termWidth, description, helper);
893
+ }
894
+ let output = [
895
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
896
+ ""
897
+ ];
898
+ const commandDescription = helper.commandDescription(cmd);
899
+ if (commandDescription.length > 0) {
900
+ output = output.concat([
901
+ helper.boxWrap(
902
+ helper.styleCommandDescription(commandDescription),
903
+ helpWidth
904
+ ),
905
+ ""
906
+ ]);
907
+ }
908
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
909
+ return callFormatItem(
910
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
911
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
912
+ );
913
+ });
914
+ if (argumentList.length > 0) {
915
+ output = output.concat([
916
+ helper.styleTitle("Arguments:"),
917
+ ...argumentList,
918
+ ""
919
+ ]);
920
+ }
921
+ const optionList = helper.visibleOptions(cmd).map((option) => {
922
+ return callFormatItem(
923
+ helper.styleOptionTerm(helper.optionTerm(option)),
924
+ helper.styleOptionDescription(helper.optionDescription(option))
925
+ );
926
+ });
927
+ if (optionList.length > 0) {
928
+ output = output.concat([
929
+ helper.styleTitle("Options:"),
930
+ ...optionList,
931
+ ""
932
+ ]);
933
+ }
934
+ if (helper.showGlobalOptions) {
935
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
936
+ return callFormatItem(
937
+ helper.styleOptionTerm(helper.optionTerm(option)),
938
+ helper.styleOptionDescription(helper.optionDescription(option))
939
+ );
940
+ });
941
+ if (globalOptionList.length > 0) {
942
+ output = output.concat([
943
+ helper.styleTitle("Global Options:"),
944
+ ...globalOptionList,
945
+ ""
946
+ ]);
947
+ }
948
+ }
949
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
950
+ return callFormatItem(
951
+ helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)),
952
+ helper.styleSubcommandDescription(helper.subcommandDescription(cmd2))
953
+ );
954
+ });
955
+ if (commandList.length > 0) {
956
+ output = output.concat([
957
+ helper.styleTitle("Commands:"),
958
+ ...commandList,
959
+ ""
960
+ ]);
961
+ }
962
+ return output.join("\n");
963
+ }
964
+ /**
965
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
966
+ *
967
+ * @param {string} str
968
+ * @returns {number}
969
+ */
970
+ displayWidth(str) {
971
+ return stripColor(str).length;
972
+ }
973
+ /**
974
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
975
+ *
976
+ * @param {string} str
977
+ * @returns {string}
978
+ */
979
+ styleTitle(str) {
980
+ return str;
981
+ }
982
+ styleUsage(str) {
983
+ return str.split(" ").map((word) => {
984
+ if (word === "[options]") return this.styleOptionText(word);
985
+ if (word === "[command]") return this.styleSubcommandText(word);
986
+ if (word[0] === "[" || word[0] === "<")
987
+ return this.styleArgumentText(word);
988
+ return this.styleCommandText(word);
989
+ }).join(" ");
990
+ }
991
+ styleCommandDescription(str) {
992
+ return this.styleDescriptionText(str);
993
+ }
994
+ styleOptionDescription(str) {
995
+ return this.styleDescriptionText(str);
996
+ }
997
+ styleSubcommandDescription(str) {
998
+ return this.styleDescriptionText(str);
999
+ }
1000
+ styleArgumentDescription(str) {
1001
+ return this.styleDescriptionText(str);
1002
+ }
1003
+ styleDescriptionText(str) {
1004
+ return str;
1005
+ }
1006
+ styleOptionTerm(str) {
1007
+ return this.styleOptionText(str);
1008
+ }
1009
+ styleSubcommandTerm(str) {
1010
+ return str.split(" ").map((word) => {
1011
+ if (word === "[options]") return this.styleOptionText(word);
1012
+ if (word[0] === "[" || word[0] === "<")
1013
+ return this.styleArgumentText(word);
1014
+ return this.styleSubcommandText(word);
1015
+ }).join(" ");
1016
+ }
1017
+ styleArgumentTerm(str) {
1018
+ return this.styleArgumentText(str);
1019
+ }
1020
+ styleOptionText(str) {
1021
+ return str;
1022
+ }
1023
+ styleArgumentText(str) {
1024
+ return str;
1025
+ }
1026
+ styleSubcommandText(str) {
1027
+ return str;
1028
+ }
1029
+ styleCommandText(str) {
1030
+ return str;
1031
+ }
1032
+ /**
1033
+ * Calculate the pad width from the maximum term length.
1034
+ *
1035
+ * @param {Command} cmd
1036
+ * @param {Help} helper
1037
+ * @returns {number}
1038
+ */
1039
+ padWidth(cmd, helper) {
1040
+ return Math.max(
1041
+ helper.longestOptionTermLength(cmd, helper),
1042
+ helper.longestGlobalOptionTermLength(cmd, helper),
1043
+ helper.longestSubcommandTermLength(cmd, helper),
1044
+ helper.longestArgumentTermLength(cmd, helper)
1045
+ );
1046
+ }
1047
+ /**
1048
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
1049
+ *
1050
+ * @param {string} str
1051
+ * @returns {boolean}
1052
+ */
1053
+ preformatted(str) {
1054
+ return /\n[^\S\r\n]/.test(str);
1055
+ }
1056
+ /**
1057
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
1058
+ *
1059
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
1060
+ * TTT DDD DDDD
1061
+ * DD DDD
1062
+ *
1063
+ * @param {string} term
1064
+ * @param {number} termWidth
1065
+ * @param {string} description
1066
+ * @param {Help} helper
1067
+ * @returns {string}
1068
+ */
1069
+ formatItem(term, termWidth, description, helper) {
1070
+ const itemIndent = 2;
1071
+ const itemIndentStr = " ".repeat(itemIndent);
1072
+ if (!description) return itemIndentStr + term;
1073
+ const paddedTerm = term.padEnd(
1074
+ termWidth + term.length - helper.displayWidth(term)
1075
+ );
1076
+ const spacerWidth = 2;
1077
+ const helpWidth = this.helpWidth ?? 80;
1078
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
1079
+ let formattedDescription;
1080
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
1081
+ formattedDescription = description;
1082
+ } else {
1083
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
1084
+ formattedDescription = wrappedDescription.replace(
1085
+ /\n/g,
1086
+ "\n" + " ".repeat(termWidth + spacerWidth)
1087
+ );
1088
+ }
1089
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
1090
+ ${itemIndentStr}`);
1091
+ }
1092
+ /**
1093
+ * Wrap a string at whitespace, preserving existing line breaks.
1094
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
1095
+ *
1096
+ * @param {string} str
1097
+ * @param {number} width
1098
+ * @returns {string}
1099
+ */
1100
+ boxWrap(str, width) {
1101
+ if (width < this.minWidthToWrap) return str;
1102
+ const rawLines = str.split(/\r\n|\n/);
1103
+ const chunkPattern = /[\s]*[^\s]+/g;
1104
+ const wrappedLines = [];
1105
+ rawLines.forEach((line) => {
1106
+ const chunks = line.match(chunkPattern);
1107
+ if (chunks === null) {
1108
+ wrappedLines.push("");
1109
+ return;
1110
+ }
1111
+ let sumChunks = [chunks.shift()];
1112
+ let sumWidth = this.displayWidth(sumChunks[0]);
1113
+ chunks.forEach((chunk) => {
1114
+ const visibleWidth = this.displayWidth(chunk);
1115
+ if (sumWidth + visibleWidth <= width) {
1116
+ sumChunks.push(chunk);
1117
+ sumWidth += visibleWidth;
1118
+ return;
1119
+ }
1120
+ wrappedLines.push(sumChunks.join(""));
1121
+ const nextChunk = chunk.trimStart();
1122
+ sumChunks = [nextChunk];
1123
+ sumWidth = this.displayWidth(nextChunk);
1124
+ });
1125
+ wrappedLines.push(sumChunks.join(""));
1126
+ });
1127
+ return wrappedLines.join("\n");
1128
+ }
1129
+ };
1130
+ function stripColor(str) {
1131
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
1132
+ return str.replace(sgrPattern, "");
1133
+ }
1134
+ exports.Help = Help2;
1135
+ exports.stripColor = stripColor;
1136
+ }
1137
+ });
1138
+
1139
+ // node_modules/commander/lib/option.js
1140
+ var require_option = __commonJS({
1141
+ "node_modules/commander/lib/option.js"(exports) {
1142
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
1143
+ var Option2 = class {
1144
+ /**
1145
+ * Initialize a new `Option` with the given `flags` and `description`.
1146
+ *
1147
+ * @param {string} flags
1148
+ * @param {string} [description]
1149
+ */
1150
+ constructor(flags, description) {
1151
+ this.flags = flags;
1152
+ this.description = description || "";
1153
+ this.required = flags.includes("<");
1154
+ this.optional = flags.includes("[");
1155
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
1156
+ this.mandatory = false;
1157
+ const optionFlags = splitOptionFlags(flags);
1158
+ this.short = optionFlags.shortFlag;
1159
+ this.long = optionFlags.longFlag;
1160
+ this.negate = false;
1161
+ if (this.long) {
1162
+ this.negate = this.long.startsWith("--no-");
1163
+ }
1164
+ this.defaultValue = void 0;
1165
+ this.defaultValueDescription = void 0;
1166
+ this.presetArg = void 0;
1167
+ this.envVar = void 0;
1168
+ this.parseArg = void 0;
1169
+ this.hidden = false;
1170
+ this.argChoices = void 0;
1171
+ this.conflictsWith = [];
1172
+ this.implied = void 0;
1173
+ }
1174
+ /**
1175
+ * Set the default value, and optionally supply the description to be displayed in the help.
1176
+ *
1177
+ * @param {*} value
1178
+ * @param {string} [description]
1179
+ * @return {Option}
1180
+ */
1181
+ default(value, description) {
1182
+ this.defaultValue = value;
1183
+ this.defaultValueDescription = description;
1184
+ return this;
1185
+ }
1186
+ /**
1187
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
1188
+ * The custom processing (parseArg) is called.
1189
+ *
1190
+ * @example
1191
+ * new Option('--color').default('GREYSCALE').preset('RGB');
1192
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
1193
+ *
1194
+ * @param {*} arg
1195
+ * @return {Option}
1196
+ */
1197
+ preset(arg) {
1198
+ this.presetArg = arg;
1199
+ return this;
1200
+ }
1201
+ /**
1202
+ * Add option name(s) that conflict with this option.
1203
+ * An error will be displayed if conflicting options are found during parsing.
1204
+ *
1205
+ * @example
1206
+ * new Option('--rgb').conflicts('cmyk');
1207
+ * new Option('--js').conflicts(['ts', 'jsx']);
1208
+ *
1209
+ * @param {(string | string[])} names
1210
+ * @return {Option}
1211
+ */
1212
+ conflicts(names) {
1213
+ this.conflictsWith = this.conflictsWith.concat(names);
1214
+ return this;
1215
+ }
1216
+ /**
1217
+ * Specify implied option values for when this option is set and the implied options are not.
1218
+ *
1219
+ * The custom processing (parseArg) is not called on the implied values.
1220
+ *
1221
+ * @example
1222
+ * program
1223
+ * .addOption(new Option('--log', 'write logging information to file'))
1224
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
1225
+ *
1226
+ * @param {object} impliedOptionValues
1227
+ * @return {Option}
1228
+ */
1229
+ implies(impliedOptionValues) {
1230
+ let newImplied = impliedOptionValues;
1231
+ if (typeof impliedOptionValues === "string") {
1232
+ newImplied = { [impliedOptionValues]: true };
1233
+ }
1234
+ this.implied = Object.assign(this.implied || {}, newImplied);
1235
+ return this;
1236
+ }
1237
+ /**
1238
+ * Set environment variable to check for option value.
1239
+ *
1240
+ * An environment variable is only used if when processed the current option value is
1241
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
1242
+ *
1243
+ * @param {string} name
1244
+ * @return {Option}
1245
+ */
1246
+ env(name) {
1247
+ this.envVar = name;
1248
+ return this;
1249
+ }
1250
+ /**
1251
+ * Set the custom handler for processing CLI option arguments into option values.
1252
+ *
1253
+ * @param {Function} [fn]
1254
+ * @return {Option}
1255
+ */
1256
+ argParser(fn) {
1257
+ this.parseArg = fn;
1258
+ return this;
1259
+ }
1260
+ /**
1261
+ * Whether the option is mandatory and must have a value after parsing.
1262
+ *
1263
+ * @param {boolean} [mandatory=true]
1264
+ * @return {Option}
1265
+ */
1266
+ makeOptionMandatory(mandatory = true) {
1267
+ this.mandatory = !!mandatory;
1268
+ return this;
1269
+ }
1270
+ /**
1271
+ * Hide option in help.
1272
+ *
1273
+ * @param {boolean} [hide=true]
1274
+ * @return {Option}
1275
+ */
1276
+ hideHelp(hide = true) {
1277
+ this.hidden = !!hide;
1278
+ return this;
1279
+ }
1280
+ /**
1281
+ * @package
1282
+ */
1283
+ _concatValue(value, previous) {
1284
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
1285
+ return [value];
1286
+ }
1287
+ return previous.concat(value);
1288
+ }
1289
+ /**
1290
+ * Only allow option value to be one of choices.
1291
+ *
1292
+ * @param {string[]} values
1293
+ * @return {Option}
1294
+ */
1295
+ choices(values) {
1296
+ this.argChoices = values.slice();
1297
+ this.parseArg = (arg, previous) => {
1298
+ if (!this.argChoices.includes(arg)) {
1299
+ throw new InvalidArgumentError2(
1300
+ `Allowed choices are ${this.argChoices.join(", ")}.`
1301
+ );
1302
+ }
1303
+ if (this.variadic) {
1304
+ return this._concatValue(arg, previous);
1305
+ }
1306
+ return arg;
1307
+ };
1308
+ return this;
1309
+ }
1310
+ /**
1311
+ * Return option name.
1312
+ *
1313
+ * @return {string}
1314
+ */
1315
+ name() {
1316
+ if (this.long) {
1317
+ return this.long.replace(/^--/, "");
1318
+ }
1319
+ return this.short.replace(/^-/, "");
1320
+ }
1321
+ /**
1322
+ * Return option name, in a camelcase format that can be used
1323
+ * as an object attribute key.
1324
+ *
1325
+ * @return {string}
1326
+ */
1327
+ attributeName() {
1328
+ if (this.negate) {
1329
+ return camelcase(this.name().replace(/^no-/, ""));
1330
+ }
1331
+ return camelcase(this.name());
1332
+ }
1333
+ /**
1334
+ * Check if `arg` matches the short or long flag.
1335
+ *
1336
+ * @param {string} arg
1337
+ * @return {boolean}
1338
+ * @package
1339
+ */
1340
+ is(arg) {
1341
+ return this.short === arg || this.long === arg;
1342
+ }
1343
+ /**
1344
+ * Return whether a boolean option.
1345
+ *
1346
+ * Options are one of boolean, negated, required argument, or optional argument.
1347
+ *
1348
+ * @return {boolean}
1349
+ * @package
1350
+ */
1351
+ isBoolean() {
1352
+ return !this.required && !this.optional && !this.negate;
1353
+ }
1354
+ };
1355
+ var DualOptions = class {
1356
+ /**
1357
+ * @param {Option[]} options
1358
+ */
1359
+ constructor(options2) {
1360
+ this.positiveOptions = /* @__PURE__ */ new Map();
1361
+ this.negativeOptions = /* @__PURE__ */ new Map();
1362
+ this.dualOptions = /* @__PURE__ */ new Set();
1363
+ options2.forEach((option) => {
1364
+ if (option.negate) {
1365
+ this.negativeOptions.set(option.attributeName(), option);
1366
+ } else {
1367
+ this.positiveOptions.set(option.attributeName(), option);
1368
+ }
1369
+ });
1370
+ this.negativeOptions.forEach((value, key) => {
1371
+ if (this.positiveOptions.has(key)) {
1372
+ this.dualOptions.add(key);
1373
+ }
1374
+ });
1375
+ }
1376
+ /**
1377
+ * Did the value come from the option, and not from possible matching dual option?
1378
+ *
1379
+ * @param {*} value
1380
+ * @param {Option} option
1381
+ * @returns {boolean}
1382
+ */
1383
+ valueFromOption(value, option) {
1384
+ const optionKey = option.attributeName();
1385
+ if (!this.dualOptions.has(optionKey)) return true;
1386
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1387
+ const negativeValue = preset !== void 0 ? preset : false;
1388
+ return option.negate === (negativeValue === value);
1389
+ }
1390
+ };
1391
+ function camelcase(str) {
1392
+ return str.split("-").reduce((str2, word) => {
1393
+ return str2 + word[0].toUpperCase() + word.slice(1);
1394
+ });
1395
+ }
1396
+ function splitOptionFlags(flags) {
1397
+ let shortFlag;
1398
+ let longFlag;
1399
+ const shortFlagExp = /^-[^-]$/;
1400
+ const longFlagExp = /^--[^-]/;
1401
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1402
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1403
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1404
+ if (/^-[^-][^-]/.test(flagParts[0]))
1405
+ throw new Error(
1406
+ `invalid Option flags, short option is dash and single character: '${flags}'`
1407
+ );
1408
+ if (shortFlag && shortFlagExp.test(flagParts[0]))
1409
+ throw new Error(
1410
+ `invalid Option flags, more than one short flag: '${flags}'`
1411
+ );
1412
+ if (longFlag && longFlagExp.test(flagParts[0]))
1413
+ throw new Error(
1414
+ `invalid Option flags, more than one long flag: '${flags}'`
1415
+ );
1416
+ if (!(shortFlag || longFlag) || flagParts[0].startsWith("-"))
1417
+ throw new Error(`invalid Option flags: '${flags}'`);
1418
+ return { shortFlag, longFlag };
1419
+ }
1420
+ exports.Option = Option2;
1421
+ exports.DualOptions = DualOptions;
1422
+ }
1423
+ });
1424
+
1425
+ // node_modules/commander/lib/suggestSimilar.js
1426
+ var require_suggestSimilar = __commonJS({
1427
+ "node_modules/commander/lib/suggestSimilar.js"(exports) {
1428
+ var maxDistance = 3;
1429
+ function editDistance(a, b) {
1430
+ if (Math.abs(a.length - b.length) > maxDistance)
1431
+ return Math.max(a.length, b.length);
1432
+ const d = [];
1433
+ for (let i = 0; i <= a.length; i++) {
1434
+ d[i] = [i];
1435
+ }
1436
+ for (let j = 0; j <= b.length; j++) {
1437
+ d[0][j] = j;
1438
+ }
1439
+ for (let j = 1; j <= b.length; j++) {
1440
+ for (let i = 1; i <= a.length; i++) {
1441
+ let cost = 1;
1442
+ if (a[i - 1] === b[j - 1]) {
1443
+ cost = 0;
1444
+ } else {
1445
+ cost = 1;
1446
+ }
1447
+ d[i][j] = Math.min(
1448
+ d[i - 1][j] + 1,
1449
+ // deletion
1450
+ d[i][j - 1] + 1,
1451
+ // insertion
1452
+ d[i - 1][j - 1] + cost
1453
+ // substitution
1454
+ );
1455
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1456
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1457
+ }
1458
+ }
1459
+ }
1460
+ return d[a.length][b.length];
1461
+ }
1462
+ function suggestSimilar(word, candidates) {
1463
+ if (!candidates || candidates.length === 0) return "";
1464
+ candidates = Array.from(new Set(candidates));
1465
+ const searchingOptions = word.startsWith("--");
1466
+ if (searchingOptions) {
1467
+ word = word.slice(2);
1468
+ candidates = candidates.map((candidate) => candidate.slice(2));
1469
+ }
1470
+ let similar = [];
1471
+ let bestDistance = maxDistance;
1472
+ const minSimilarity = 0.4;
1473
+ candidates.forEach((candidate) => {
1474
+ if (candidate.length <= 1) return;
1475
+ const distance = editDistance(word, candidate);
1476
+ const length = Math.max(word.length, candidate.length);
1477
+ const similarity = (length - distance) / length;
1478
+ if (similarity > minSimilarity) {
1479
+ if (distance < bestDistance) {
1480
+ bestDistance = distance;
1481
+ similar = [candidate];
1482
+ } else if (distance === bestDistance) {
1483
+ similar.push(candidate);
1484
+ }
1485
+ }
1486
+ });
1487
+ similar.sort((a, b) => a.localeCompare(b));
1488
+ if (searchingOptions) {
1489
+ similar = similar.map((candidate) => `--${candidate}`);
1490
+ }
1491
+ if (similar.length > 1) {
1492
+ return `
1493
+ (Did you mean one of ${similar.join(", ")}?)`;
1494
+ }
1495
+ if (similar.length === 1) {
1496
+ return `
1497
+ (Did you mean ${similar[0]}?)`;
1498
+ }
1499
+ return "";
1500
+ }
1501
+ exports.suggestSimilar = suggestSimilar;
1502
+ }
1503
+ });
1504
+
1505
+ // node_modules/commander/lib/command.js
1506
+ var require_command = __commonJS({
1507
+ "node_modules/commander/lib/command.js"(exports) {
1508
+ var EventEmitter = __require("node:events").EventEmitter;
1509
+ var childProcess = __require("node:child_process");
1510
+ var path3 = __require("node:path");
1511
+ var fs3 = __require("node:fs");
1512
+ var process2 = __require("node:process");
1513
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
1514
+ var { CommanderError: CommanderError2 } = require_error();
1515
+ var { Help: Help2, stripColor } = require_help();
1516
+ var { Option: Option2, DualOptions } = require_option();
1517
+ var { suggestSimilar } = require_suggestSimilar();
1518
+ var Command2 = class _Command extends EventEmitter {
1519
+ /**
1520
+ * Initialize a new `Command`.
1521
+ *
1522
+ * @param {string} [name]
1523
+ */
1524
+ constructor(name) {
1525
+ super();
1526
+ this.commands = [];
1527
+ this.options = [];
1528
+ this.parent = null;
1529
+ this._allowUnknownOption = false;
1530
+ this._allowExcessArguments = false;
1531
+ this.registeredArguments = [];
1532
+ this._args = this.registeredArguments;
1533
+ this.args = [];
1534
+ this.rawArgs = [];
1535
+ this.processedArgs = [];
1536
+ this._scriptPath = null;
1537
+ this._name = name || "";
1538
+ this._optionValues = {};
1539
+ this._optionValueSources = {};
1540
+ this._storeOptionsAsProperties = false;
1541
+ this._actionHandler = null;
1542
+ this._executableHandler = false;
1543
+ this._executableFile = null;
1544
+ this._executableDir = null;
1545
+ this._defaultCommandName = null;
1546
+ this._exitCallback = null;
1547
+ this._aliases = [];
1548
+ this._combineFlagAndOptionalValue = true;
1549
+ this._description = "";
1550
+ this._summary = "";
1551
+ this._argsDescription = void 0;
1552
+ this._enablePositionalOptions = false;
1553
+ this._passThroughOptions = false;
1554
+ this._lifeCycleHooks = {};
1555
+ this._showHelpAfterError = false;
1556
+ this._showSuggestionAfterError = true;
1557
+ this._savedState = null;
1558
+ this._outputConfiguration = {
1559
+ writeOut: (str) => process2.stdout.write(str),
1560
+ writeErr: (str) => process2.stderr.write(str),
1561
+ outputError: (str, write) => write(str),
1562
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1563
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1564
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1565
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1566
+ stripColor: (str) => stripColor(str)
1567
+ };
1568
+ this._hidden = false;
1569
+ this._helpOption = void 0;
1570
+ this._addImplicitHelpCommand = void 0;
1571
+ this._helpCommand = void 0;
1572
+ this._helpConfiguration = {};
1573
+ }
1574
+ /**
1575
+ * Copy settings that are useful to have in common across root command and subcommands.
1576
+ *
1577
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1578
+ *
1579
+ * @param {Command} sourceCommand
1580
+ * @return {Command} `this` command for chaining
1581
+ */
1582
+ copyInheritedSettings(sourceCommand) {
1583
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1584
+ this._helpOption = sourceCommand._helpOption;
1585
+ this._helpCommand = sourceCommand._helpCommand;
1586
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1587
+ this._exitCallback = sourceCommand._exitCallback;
1588
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1589
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1590
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1591
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1592
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1593
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1594
+ return this;
1595
+ }
1596
+ /**
1597
+ * @returns {Command[]}
1598
+ * @private
1599
+ */
1600
+ _getCommandAndAncestors() {
1601
+ const result = [];
1602
+ for (let command = this; command; command = command.parent) {
1603
+ result.push(command);
1604
+ }
1605
+ return result;
1606
+ }
1607
+ /**
1608
+ * Define a command.
1609
+ *
1610
+ * There are two styles of command: pay attention to where to put the description.
1611
+ *
1612
+ * @example
1613
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1614
+ * program
1615
+ * .command('clone <source> [destination]')
1616
+ * .description('clone a repository into a newly created directory')
1617
+ * .action((source, destination) => {
1618
+ * console.log('clone command called');
1619
+ * });
1620
+ *
1621
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1622
+ * program
1623
+ * .command('start <service>', 'start named service')
1624
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1625
+ *
1626
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1627
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1628
+ * @param {object} [execOpts] - configuration options (for executable)
1629
+ * @return {Command} returns new command for action handler, or `this` for executable command
1630
+ */
1631
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1632
+ let desc = actionOptsOrExecDesc;
1633
+ let opts = execOpts;
1634
+ if (typeof desc === "object" && desc !== null) {
1635
+ opts = desc;
1636
+ desc = null;
1637
+ }
1638
+ opts = opts || {};
1639
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1640
+ const cmd = this.createCommand(name);
1641
+ if (desc) {
1642
+ cmd.description(desc);
1643
+ cmd._executableHandler = true;
1644
+ }
1645
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1646
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1647
+ cmd._executableFile = opts.executableFile || null;
1648
+ if (args) cmd.arguments(args);
1649
+ this._registerCommand(cmd);
1650
+ cmd.parent = this;
1651
+ cmd.copyInheritedSettings(this);
1652
+ if (desc) return this;
1653
+ return cmd;
1654
+ }
1655
+ /**
1656
+ * Factory routine to create a new unattached command.
1657
+ *
1658
+ * See .command() for creating an attached subcommand, which uses this routine to
1659
+ * create the command. You can override createCommand to customise subcommands.
1660
+ *
1661
+ * @param {string} [name]
1662
+ * @return {Command} new command
1663
+ */
1664
+ createCommand(name) {
1665
+ return new _Command(name);
1666
+ }
1667
+ /**
1668
+ * You can customise the help with a subclass of Help by overriding createHelp,
1669
+ * or by overriding Help properties using configureHelp().
1670
+ *
1671
+ * @return {Help}
1672
+ */
1673
+ createHelp() {
1674
+ return Object.assign(new Help2(), this.configureHelp());
1675
+ }
1676
+ /**
1677
+ * You can customise the help by overriding Help properties using configureHelp(),
1678
+ * or with a subclass of Help by overriding createHelp().
1679
+ *
1680
+ * @param {object} [configuration] - configuration options
1681
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1682
+ */
1683
+ configureHelp(configuration) {
1684
+ if (configuration === void 0) return this._helpConfiguration;
1685
+ this._helpConfiguration = configuration;
1686
+ return this;
1687
+ }
1688
+ /**
1689
+ * The default output goes to stdout and stderr. You can customise this for special
1690
+ * applications. You can also customise the display of errors by overriding outputError.
1691
+ *
1692
+ * The configuration properties are all functions:
1693
+ *
1694
+ * // change how output being written, defaults to stdout and stderr
1695
+ * writeOut(str)
1696
+ * writeErr(str)
1697
+ * // change how output being written for errors, defaults to writeErr
1698
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1699
+ * // specify width for wrapping help
1700
+ * getOutHelpWidth()
1701
+ * getErrHelpWidth()
1702
+ * // color support, currently only used with Help
1703
+ * getOutHasColors()
1704
+ * getErrHasColors()
1705
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1706
+ *
1707
+ * @param {object} [configuration] - configuration options
1708
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1709
+ */
1710
+ configureOutput(configuration) {
1711
+ if (configuration === void 0) return this._outputConfiguration;
1712
+ Object.assign(this._outputConfiguration, configuration);
1713
+ return this;
1714
+ }
1715
+ /**
1716
+ * Display the help or a custom message after an error occurs.
1717
+ *
1718
+ * @param {(boolean|string)} [displayHelp]
1719
+ * @return {Command} `this` command for chaining
1720
+ */
1721
+ showHelpAfterError(displayHelp = true) {
1722
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1723
+ this._showHelpAfterError = displayHelp;
1724
+ return this;
1725
+ }
1726
+ /**
1727
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1728
+ *
1729
+ * @param {boolean} [displaySuggestion]
1730
+ * @return {Command} `this` command for chaining
1731
+ */
1732
+ showSuggestionAfterError(displaySuggestion = true) {
1733
+ this._showSuggestionAfterError = !!displaySuggestion;
1734
+ return this;
1735
+ }
1736
+ /**
1737
+ * Add a prepared subcommand.
1738
+ *
1739
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1740
+ *
1741
+ * @param {Command} cmd - new subcommand
1742
+ * @param {object} [opts] - configuration options
1743
+ * @return {Command} `this` command for chaining
1744
+ */
1745
+ addCommand(cmd, opts) {
1746
+ if (!cmd._name) {
1747
+ throw new Error(`Command passed to .addCommand() must have a name
1748
+ - specify the name in Command constructor or using .name()`);
1749
+ }
1750
+ opts = opts || {};
1751
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1752
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1753
+ this._registerCommand(cmd);
1754
+ cmd.parent = this;
1755
+ cmd._checkForBrokenPassThrough();
1756
+ return this;
1757
+ }
1758
+ /**
1759
+ * Factory routine to create a new unattached argument.
1760
+ *
1761
+ * See .argument() for creating an attached argument, which uses this routine to
1762
+ * create the argument. You can override createArgument to return a custom argument.
1763
+ *
1764
+ * @param {string} name
1765
+ * @param {string} [description]
1766
+ * @return {Argument} new argument
1767
+ */
1768
+ createArgument(name, description) {
1769
+ return new Argument2(name, description);
1770
+ }
1771
+ /**
1772
+ * Define argument syntax for command.
1773
+ *
1774
+ * The default is that the argument is required, and you can explicitly
1775
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1776
+ *
1777
+ * @example
1778
+ * program.argument('<input-file>');
1779
+ * program.argument('[output-file]');
1780
+ *
1781
+ * @param {string} name
1782
+ * @param {string} [description]
1783
+ * @param {(Function|*)} [fn] - custom argument processing function
1784
+ * @param {*} [defaultValue]
1785
+ * @return {Command} `this` command for chaining
1786
+ */
1787
+ argument(name, description, fn, defaultValue) {
1788
+ const argument = this.createArgument(name, description);
1789
+ if (typeof fn === "function") {
1790
+ argument.default(defaultValue).argParser(fn);
1791
+ } else {
1792
+ argument.default(fn);
1793
+ }
1794
+ this.addArgument(argument);
1795
+ return this;
1796
+ }
1797
+ /**
1798
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1799
+ *
1800
+ * See also .argument().
1801
+ *
1802
+ * @example
1803
+ * program.arguments('<cmd> [env]');
1804
+ *
1805
+ * @param {string} names
1806
+ * @return {Command} `this` command for chaining
1807
+ */
1808
+ arguments(names) {
1809
+ names.trim().split(/ +/).forEach((detail) => {
1810
+ this.argument(detail);
1811
+ });
1812
+ return this;
1813
+ }
1814
+ /**
1815
+ * Define argument syntax for command, adding a prepared argument.
1816
+ *
1817
+ * @param {Argument} argument
1818
+ * @return {Command} `this` command for chaining
1819
+ */
1820
+ addArgument(argument) {
1821
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1822
+ if (previousArgument && previousArgument.variadic) {
1823
+ throw new Error(
1824
+ `only the last argument can be variadic '${previousArgument.name()}'`
1825
+ );
1826
+ }
1827
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1828
+ throw new Error(
1829
+ `a default value for a required argument is never used: '${argument.name()}'`
1830
+ );
1831
+ }
1832
+ this.registeredArguments.push(argument);
1833
+ return this;
1834
+ }
1835
+ /**
1836
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1837
+ *
1838
+ * @example
1839
+ * program.helpCommand('help [cmd]');
1840
+ * program.helpCommand('help [cmd]', 'show help');
1841
+ * program.helpCommand(false); // suppress default help command
1842
+ * program.helpCommand(true); // add help command even if no subcommands
1843
+ *
1844
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1845
+ * @param {string} [description] - custom description
1846
+ * @return {Command} `this` command for chaining
1847
+ */
1848
+ helpCommand(enableOrNameAndArgs, description) {
1849
+ if (typeof enableOrNameAndArgs === "boolean") {
1850
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1851
+ return this;
1852
+ }
1853
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1854
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1855
+ const helpDescription = description ?? "display help for command";
1856
+ const helpCommand = this.createCommand(helpName);
1857
+ helpCommand.helpOption(false);
1858
+ if (helpArgs) helpCommand.arguments(helpArgs);
1859
+ if (helpDescription) helpCommand.description(helpDescription);
1860
+ this._addImplicitHelpCommand = true;
1861
+ this._helpCommand = helpCommand;
1862
+ return this;
1863
+ }
1864
+ /**
1865
+ * Add prepared custom help command.
1866
+ *
1867
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1868
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1869
+ * @return {Command} `this` command for chaining
1870
+ */
1871
+ addHelpCommand(helpCommand, deprecatedDescription) {
1872
+ if (typeof helpCommand !== "object") {
1873
+ this.helpCommand(helpCommand, deprecatedDescription);
1874
+ return this;
1875
+ }
1876
+ this._addImplicitHelpCommand = true;
1877
+ this._helpCommand = helpCommand;
1878
+ return this;
1879
+ }
1880
+ /**
1881
+ * Lazy create help command.
1882
+ *
1883
+ * @return {(Command|null)}
1884
+ * @package
1885
+ */
1886
+ _getHelpCommand() {
1887
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1888
+ if (hasImplicitHelpCommand) {
1889
+ if (this._helpCommand === void 0) {
1890
+ this.helpCommand(void 0, void 0);
1891
+ }
1892
+ return this._helpCommand;
1893
+ }
1894
+ return null;
1895
+ }
1896
+ /**
1897
+ * Add hook for life cycle event.
1898
+ *
1899
+ * @param {string} event
1900
+ * @param {Function} listener
1901
+ * @return {Command} `this` command for chaining
1902
+ */
1903
+ hook(event, listener) {
1904
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1905
+ if (!allowedValues.includes(event)) {
1906
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1907
+ Expecting one of '${allowedValues.join("', '")}'`);
1908
+ }
1909
+ if (this._lifeCycleHooks[event]) {
1910
+ this._lifeCycleHooks[event].push(listener);
1911
+ } else {
1912
+ this._lifeCycleHooks[event] = [listener];
1913
+ }
1914
+ return this;
1915
+ }
1916
+ /**
1917
+ * Register callback to use as replacement for calling process.exit.
1918
+ *
1919
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1920
+ * @return {Command} `this` command for chaining
1921
+ */
1922
+ exitOverride(fn) {
1923
+ if (fn) {
1924
+ this._exitCallback = fn;
1925
+ } else {
1926
+ this._exitCallback = (err) => {
1927
+ if (err.code !== "commander.executeSubCommandAsync") {
1928
+ throw err;
1929
+ } else {
1930
+ }
1931
+ };
1932
+ }
1933
+ return this;
1934
+ }
1935
+ /**
1936
+ * Call process.exit, and _exitCallback if defined.
1937
+ *
1938
+ * @param {number} exitCode exit code for using with process.exit
1939
+ * @param {string} code an id string representing the error
1940
+ * @param {string} message human-readable description of the error
1941
+ * @return never
1942
+ * @private
1943
+ */
1944
+ _exit(exitCode, code, message) {
1945
+ if (this._exitCallback) {
1946
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1947
+ }
1948
+ process2.exit(exitCode);
1949
+ }
1950
+ /**
1951
+ * Register callback `fn` for the command.
1952
+ *
1953
+ * @example
1954
+ * program
1955
+ * .command('serve')
1956
+ * .description('start service')
1957
+ * .action(function() {
1958
+ * // do work here
1959
+ * });
1960
+ *
1961
+ * @param {Function} fn
1962
+ * @return {Command} `this` command for chaining
1963
+ */
1964
+ action(fn) {
1965
+ const listener = (args) => {
1966
+ const expectedArgsCount = this.registeredArguments.length;
1967
+ const actionArgs = args.slice(0, expectedArgsCount);
1968
+ if (this._storeOptionsAsProperties) {
1969
+ actionArgs[expectedArgsCount] = this;
1970
+ } else {
1971
+ actionArgs[expectedArgsCount] = this.opts();
1972
+ }
1973
+ actionArgs.push(this);
1974
+ return fn.apply(this, actionArgs);
1975
+ };
1976
+ this._actionHandler = listener;
1977
+ return this;
1978
+ }
1979
+ /**
1980
+ * Factory routine to create a new unattached option.
1981
+ *
1982
+ * See .option() for creating an attached option, which uses this routine to
1983
+ * create the option. You can override createOption to return a custom option.
1984
+ *
1985
+ * @param {string} flags
1986
+ * @param {string} [description]
1987
+ * @return {Option} new option
1988
+ */
1989
+ createOption(flags, description) {
1990
+ return new Option2(flags, description);
1991
+ }
1992
+ /**
1993
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1994
+ *
1995
+ * @param {(Option | Argument)} target
1996
+ * @param {string} value
1997
+ * @param {*} previous
1998
+ * @param {string} invalidArgumentMessage
1999
+ * @private
2000
+ */
2001
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
2002
+ try {
2003
+ return target.parseArg(value, previous);
2004
+ } catch (err) {
2005
+ if (err.code === "commander.invalidArgument") {
2006
+ const message = `${invalidArgumentMessage} ${err.message}`;
2007
+ this.error(message, { exitCode: err.exitCode, code: err.code });
2008
+ }
2009
+ throw err;
2010
+ }
2011
+ }
2012
+ /**
2013
+ * Check for option flag conflicts.
2014
+ * Register option if no conflicts found, or throw on conflict.
2015
+ *
2016
+ * @param {Option} option
2017
+ * @private
2018
+ */
2019
+ _registerOption(option) {
2020
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
2021
+ if (matchingOption) {
2022
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
2023
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
2024
+ - already used by option '${matchingOption.flags}'`);
2025
+ }
2026
+ this.options.push(option);
2027
+ }
2028
+ /**
2029
+ * Check for command name and alias conflicts with existing commands.
2030
+ * Register command if no conflicts found, or throw on conflict.
2031
+ *
2032
+ * @param {Command} command
2033
+ * @private
2034
+ */
2035
+ _registerCommand(command) {
2036
+ const knownBy = (cmd) => {
2037
+ return [cmd.name()].concat(cmd.aliases());
2038
+ };
2039
+ const alreadyUsed = knownBy(command).find(
2040
+ (name) => this._findCommand(name)
2041
+ );
2042
+ if (alreadyUsed) {
2043
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
2044
+ const newCmd = knownBy(command).join("|");
2045
+ throw new Error(
2046
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
2047
+ );
2048
+ }
2049
+ this.commands.push(command);
2050
+ }
2051
+ /**
2052
+ * Add an option.
2053
+ *
2054
+ * @param {Option} option
2055
+ * @return {Command} `this` command for chaining
2056
+ */
2057
+ addOption(option) {
2058
+ this._registerOption(option);
2059
+ const oname = option.name();
2060
+ const name = option.attributeName();
2061
+ if (option.negate) {
2062
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
2063
+ if (!this._findOption(positiveLongFlag)) {
2064
+ this.setOptionValueWithSource(
2065
+ name,
2066
+ option.defaultValue === void 0 ? true : option.defaultValue,
2067
+ "default"
2068
+ );
2069
+ }
2070
+ } else if (option.defaultValue !== void 0) {
2071
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
2072
+ }
2073
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
2074
+ if (val == null && option.presetArg !== void 0) {
2075
+ val = option.presetArg;
2076
+ }
2077
+ const oldValue = this.getOptionValue(name);
2078
+ if (val !== null && option.parseArg) {
2079
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
2080
+ } else if (val !== null && option.variadic) {
2081
+ val = option._concatValue(val, oldValue);
2082
+ }
2083
+ if (val == null) {
2084
+ if (option.negate) {
2085
+ val = false;
2086
+ } else if (option.isBoolean() || option.optional) {
2087
+ val = true;
2088
+ } else {
2089
+ val = "";
2090
+ }
2091
+ }
2092
+ this.setOptionValueWithSource(name, val, valueSource);
2093
+ };
2094
+ this.on("option:" + oname, (val) => {
2095
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
2096
+ handleOptionValue(val, invalidValueMessage, "cli");
2097
+ });
2098
+ if (option.envVar) {
2099
+ this.on("optionEnv:" + oname, (val) => {
2100
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
2101
+ handleOptionValue(val, invalidValueMessage, "env");
2102
+ });
2103
+ }
2104
+ return this;
2105
+ }
2106
+ /**
2107
+ * Internal implementation shared by .option() and .requiredOption()
2108
+ *
2109
+ * @return {Command} `this` command for chaining
2110
+ * @private
2111
+ */
2112
+ _optionEx(config, flags, description, fn, defaultValue) {
2113
+ if (typeof flags === "object" && flags instanceof Option2) {
2114
+ throw new Error(
2115
+ "To add an Option object use addOption() instead of option() or requiredOption()"
2116
+ );
2117
+ }
2118
+ const option = this.createOption(flags, description);
2119
+ option.makeOptionMandatory(!!config.mandatory);
2120
+ if (typeof fn === "function") {
2121
+ option.default(defaultValue).argParser(fn);
2122
+ } else if (fn instanceof RegExp) {
2123
+ const regex = fn;
2124
+ fn = (val, def) => {
2125
+ const m = regex.exec(val);
2126
+ return m ? m[0] : def;
2127
+ };
2128
+ option.default(defaultValue).argParser(fn);
2129
+ } else {
2130
+ option.default(fn);
2131
+ }
2132
+ return this.addOption(option);
2133
+ }
2134
+ /**
2135
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
2136
+ *
2137
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
2138
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
2139
+ *
2140
+ * See the README for more details, and see also addOption() and requiredOption().
2141
+ *
2142
+ * @example
2143
+ * program
2144
+ * .option('-p, --pepper', 'add pepper')
2145
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
2146
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
2147
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
2148
+ *
2149
+ * @param {string} flags
2150
+ * @param {string} [description]
2151
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
2152
+ * @param {*} [defaultValue]
2153
+ * @return {Command} `this` command for chaining
2154
+ */
2155
+ option(flags, description, parseArg, defaultValue) {
2156
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
2157
+ }
2158
+ /**
2159
+ * Add a required option which must have a value after parsing. This usually means
2160
+ * the option must be specified on the command line. (Otherwise the same as .option().)
2161
+ *
2162
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
2163
+ *
2164
+ * @param {string} flags
2165
+ * @param {string} [description]
2166
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
2167
+ * @param {*} [defaultValue]
2168
+ * @return {Command} `this` command for chaining
2169
+ */
2170
+ requiredOption(flags, description, parseArg, defaultValue) {
2171
+ return this._optionEx(
2172
+ { mandatory: true },
2173
+ flags,
2174
+ description,
2175
+ parseArg,
2176
+ defaultValue
2177
+ );
2178
+ }
2179
+ /**
2180
+ * Alter parsing of short flags with optional values.
2181
+ *
2182
+ * @example
2183
+ * // for `.option('-f,--flag [value]'):
2184
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
2185
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
2186
+ *
2187
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
2188
+ * @return {Command} `this` command for chaining
2189
+ */
2190
+ combineFlagAndOptionalValue(combine = true) {
2191
+ this._combineFlagAndOptionalValue = !!combine;
2192
+ return this;
2193
+ }
2194
+ /**
2195
+ * Allow unknown options on the command line.
2196
+ *
2197
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
2198
+ * @return {Command} `this` command for chaining
2199
+ */
2200
+ allowUnknownOption(allowUnknown = true) {
2201
+ this._allowUnknownOption = !!allowUnknown;
2202
+ return this;
2203
+ }
2204
+ /**
2205
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
2206
+ *
2207
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
2208
+ * @return {Command} `this` command for chaining
2209
+ */
2210
+ allowExcessArguments(allowExcess = true) {
2211
+ this._allowExcessArguments = !!allowExcess;
2212
+ return this;
2213
+ }
2214
+ /**
2215
+ * Enable positional options. Positional means global options are specified before subcommands which lets
2216
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
2217
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
2218
+ *
2219
+ * @param {boolean} [positional]
2220
+ * @return {Command} `this` command for chaining
2221
+ */
2222
+ enablePositionalOptions(positional = true) {
2223
+ this._enablePositionalOptions = !!positional;
2224
+ return this;
2225
+ }
2226
+ /**
2227
+ * Pass through options that come after command-arguments rather than treat them as command-options,
2228
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
2229
+ * positional options to have been enabled on the program (parent commands).
2230
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
2231
+ *
2232
+ * @param {boolean} [passThrough] for unknown options.
2233
+ * @return {Command} `this` command for chaining
2234
+ */
2235
+ passThroughOptions(passThrough = true) {
2236
+ this._passThroughOptions = !!passThrough;
2237
+ this._checkForBrokenPassThrough();
2238
+ return this;
2239
+ }
2240
+ /**
2241
+ * @private
2242
+ */
2243
+ _checkForBrokenPassThrough() {
2244
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
2245
+ throw new Error(
2246
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
2247
+ );
2248
+ }
2249
+ }
2250
+ /**
2251
+ * Whether to store option values as properties on command object,
2252
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
2253
+ *
2254
+ * @param {boolean} [storeAsProperties=true]
2255
+ * @return {Command} `this` command for chaining
2256
+ */
2257
+ storeOptionsAsProperties(storeAsProperties = true) {
2258
+ if (this.options.length) {
2259
+ throw new Error("call .storeOptionsAsProperties() before adding options");
2260
+ }
2261
+ if (Object.keys(this._optionValues).length) {
2262
+ throw new Error(
2263
+ "call .storeOptionsAsProperties() before setting option values"
2264
+ );
2265
+ }
2266
+ this._storeOptionsAsProperties = !!storeAsProperties;
2267
+ return this;
2268
+ }
2269
+ /**
2270
+ * Retrieve option value.
2271
+ *
2272
+ * @param {string} key
2273
+ * @return {object} value
2274
+ */
2275
+ getOptionValue(key) {
2276
+ if (this._storeOptionsAsProperties) {
2277
+ return this[key];
2278
+ }
2279
+ return this._optionValues[key];
2280
+ }
2281
+ /**
2282
+ * Store option value.
2283
+ *
2284
+ * @param {string} key
2285
+ * @param {object} value
2286
+ * @return {Command} `this` command for chaining
2287
+ */
2288
+ setOptionValue(key, value) {
2289
+ return this.setOptionValueWithSource(key, value, void 0);
2290
+ }
2291
+ /**
2292
+ * Store option value and where the value came from.
2293
+ *
2294
+ * @param {string} key
2295
+ * @param {object} value
2296
+ * @param {string} source - expected values are default/config/env/cli/implied
2297
+ * @return {Command} `this` command for chaining
2298
+ */
2299
+ setOptionValueWithSource(key, value, source) {
2300
+ if (this._storeOptionsAsProperties) {
2301
+ this[key] = value;
2302
+ } else {
2303
+ this._optionValues[key] = value;
2304
+ }
2305
+ this._optionValueSources[key] = source;
2306
+ return this;
2307
+ }
2308
+ /**
2309
+ * Get source of option value.
2310
+ * Expected values are default | config | env | cli | implied
2311
+ *
2312
+ * @param {string} key
2313
+ * @return {string}
2314
+ */
2315
+ getOptionValueSource(key) {
2316
+ return this._optionValueSources[key];
2317
+ }
2318
+ /**
2319
+ * Get source of option value. See also .optsWithGlobals().
2320
+ * Expected values are default | config | env | cli | implied
2321
+ *
2322
+ * @param {string} key
2323
+ * @return {string}
2324
+ */
2325
+ getOptionValueSourceWithGlobals(key) {
2326
+ let source;
2327
+ this._getCommandAndAncestors().forEach((cmd) => {
2328
+ if (cmd.getOptionValueSource(key) !== void 0) {
2329
+ source = cmd.getOptionValueSource(key);
2330
+ }
2331
+ });
2332
+ return source;
2333
+ }
2334
+ /**
2335
+ * Get user arguments from implied or explicit arguments.
2336
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2337
+ *
2338
+ * @private
2339
+ */
2340
+ _prepareUserArgs(argv, parseOptions) {
2341
+ if (argv !== void 0 && !Array.isArray(argv)) {
2342
+ throw new Error("first parameter to parse must be array or undefined");
2343
+ }
2344
+ parseOptions = parseOptions || {};
2345
+ if (argv === void 0 && parseOptions.from === void 0) {
2346
+ if (process2.versions?.electron) {
2347
+ parseOptions.from = "electron";
2348
+ }
2349
+ const execArgv = process2.execArgv ?? [];
2350
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
2351
+ parseOptions.from = "eval";
2352
+ }
2353
+ }
2354
+ if (argv === void 0) {
2355
+ argv = process2.argv;
2356
+ }
2357
+ this.rawArgs = argv.slice();
2358
+ let userArgs;
2359
+ switch (parseOptions.from) {
2360
+ case void 0:
2361
+ case "node":
2362
+ this._scriptPath = argv[1];
2363
+ userArgs = argv.slice(2);
2364
+ break;
2365
+ case "electron":
2366
+ if (process2.defaultApp) {
2367
+ this._scriptPath = argv[1];
2368
+ userArgs = argv.slice(2);
2369
+ } else {
2370
+ userArgs = argv.slice(1);
2371
+ }
2372
+ break;
2373
+ case "user":
2374
+ userArgs = argv.slice(0);
2375
+ break;
2376
+ case "eval":
2377
+ userArgs = argv.slice(1);
2378
+ break;
2379
+ default:
2380
+ throw new Error(
2381
+ `unexpected parse option { from: '${parseOptions.from}' }`
2382
+ );
2383
+ }
2384
+ if (!this._name && this._scriptPath)
2385
+ this.nameFromFilename(this._scriptPath);
2386
+ this._name = this._name || "program";
2387
+ return userArgs;
2388
+ }
2389
+ /**
2390
+ * Parse `argv`, setting options and invoking commands when defined.
2391
+ *
2392
+ * Use parseAsync instead of parse if any of your action handlers are async.
2393
+ *
2394
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2395
+ *
2396
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2397
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2398
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2399
+ * - `'user'`: just user arguments
2400
+ *
2401
+ * @example
2402
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2403
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2404
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2405
+ *
2406
+ * @param {string[]} [argv] - optional, defaults to process.argv
2407
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2408
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2409
+ * @return {Command} `this` command for chaining
2410
+ */
2411
+ parse(argv, parseOptions) {
2412
+ this._prepareForParse();
2413
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2414
+ this._parseCommand([], userArgs);
2415
+ return this;
2416
+ }
2417
+ /**
2418
+ * Parse `argv`, setting options and invoking commands when defined.
2419
+ *
2420
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2421
+ *
2422
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2423
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2424
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2425
+ * - `'user'`: just user arguments
2426
+ *
2427
+ * @example
2428
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2429
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2430
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2431
+ *
2432
+ * @param {string[]} [argv]
2433
+ * @param {object} [parseOptions]
2434
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2435
+ * @return {Promise}
2436
+ */
2437
+ async parseAsync(argv, parseOptions) {
2438
+ this._prepareForParse();
2439
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2440
+ await this._parseCommand([], userArgs);
2441
+ return this;
2442
+ }
2443
+ _prepareForParse() {
2444
+ if (this._savedState === null) {
2445
+ this.saveStateBeforeParse();
2446
+ } else {
2447
+ this.restoreStateBeforeParse();
2448
+ }
2449
+ }
2450
+ /**
2451
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2452
+ * Not usually called directly, but available for subclasses to save their custom state.
2453
+ *
2454
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2455
+ */
2456
+ saveStateBeforeParse() {
2457
+ this._savedState = {
2458
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2459
+ _name: this._name,
2460
+ // option values before parse have default values (including false for negated options)
2461
+ // shallow clones
2462
+ _optionValues: { ...this._optionValues },
2463
+ _optionValueSources: { ...this._optionValueSources }
2464
+ };
2465
+ }
2466
+ /**
2467
+ * Restore state before parse for calls after the first.
2468
+ * Not usually called directly, but available for subclasses to save their custom state.
2469
+ *
2470
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2471
+ */
2472
+ restoreStateBeforeParse() {
2473
+ if (this._storeOptionsAsProperties)
2474
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2475
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2476
+ this._name = this._savedState._name;
2477
+ this._scriptPath = null;
2478
+ this.rawArgs = [];
2479
+ this._optionValues = { ...this._savedState._optionValues };
2480
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2481
+ this.args = [];
2482
+ this.processedArgs = [];
2483
+ }
2484
+ /**
2485
+ * Throw if expected executable is missing. Add lots of help for author.
2486
+ *
2487
+ * @param {string} executableFile
2488
+ * @param {string} executableDir
2489
+ * @param {string} subcommandName
2490
+ */
2491
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2492
+ if (fs3.existsSync(executableFile)) return;
2493
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
2494
+ const executableMissing = `'${executableFile}' does not exist
2495
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2496
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2497
+ - ${executableDirMessage}`;
2498
+ throw new Error(executableMissing);
2499
+ }
2500
+ /**
2501
+ * Execute a sub-command executable.
2502
+ *
2503
+ * @private
2504
+ */
2505
+ _executeSubCommand(subcommand, args) {
2506
+ args = args.slice();
2507
+ let launchWithNode = false;
2508
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2509
+ function findFile(baseDir, baseName) {
2510
+ const localBin = path3.resolve(baseDir, baseName);
2511
+ if (fs3.existsSync(localBin)) return localBin;
2512
+ if (sourceExt.includes(path3.extname(baseName))) return void 0;
2513
+ const foundExt = sourceExt.find(
2514
+ (ext) => fs3.existsSync(`${localBin}${ext}`)
2515
+ );
2516
+ if (foundExt) return `${localBin}${foundExt}`;
2517
+ return void 0;
2518
+ }
2519
+ this._checkForMissingMandatoryOptions();
2520
+ this._checkForConflictingOptions();
2521
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2522
+ let executableDir = this._executableDir || "";
2523
+ if (this._scriptPath) {
2524
+ let resolvedScriptPath;
2525
+ try {
2526
+ resolvedScriptPath = fs3.realpathSync(this._scriptPath);
2527
+ } catch {
2528
+ resolvedScriptPath = this._scriptPath;
2529
+ }
2530
+ executableDir = path3.resolve(
2531
+ path3.dirname(resolvedScriptPath),
2532
+ executableDir
2533
+ );
2534
+ }
2535
+ if (executableDir) {
2536
+ let localFile = findFile(executableDir, executableFile);
2537
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2538
+ const legacyName = path3.basename(
2539
+ this._scriptPath,
2540
+ path3.extname(this._scriptPath)
2541
+ );
2542
+ if (legacyName !== this._name) {
2543
+ localFile = findFile(
2544
+ executableDir,
2545
+ `${legacyName}-${subcommand._name}`
2546
+ );
2547
+ }
2548
+ }
2549
+ executableFile = localFile || executableFile;
2550
+ }
2551
+ launchWithNode = sourceExt.includes(path3.extname(executableFile));
2552
+ let proc;
2553
+ if (process2.platform !== "win32") {
2554
+ if (launchWithNode) {
2555
+ args.unshift(executableFile);
2556
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2557
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2558
+ } else {
2559
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2560
+ }
2561
+ } else {
2562
+ this._checkForMissingExecutable(
2563
+ executableFile,
2564
+ executableDir,
2565
+ subcommand._name
2566
+ );
2567
+ args.unshift(executableFile);
2568
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2569
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2570
+ }
2571
+ if (!proc.killed) {
2572
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2573
+ signals.forEach((signal) => {
2574
+ process2.on(signal, () => {
2575
+ if (proc.killed === false && proc.exitCode === null) {
2576
+ proc.kill(signal);
2577
+ }
2578
+ });
2579
+ });
2580
+ }
2581
+ const exitCallback = this._exitCallback;
2582
+ proc.on("close", (code) => {
2583
+ code = code ?? 1;
2584
+ if (!exitCallback) {
2585
+ process2.exit(code);
2586
+ } else {
2587
+ exitCallback(
2588
+ new CommanderError2(
2589
+ code,
2590
+ "commander.executeSubCommandAsync",
2591
+ "(close)"
2592
+ )
2593
+ );
2594
+ }
2595
+ });
2596
+ proc.on("error", (err) => {
2597
+ if (err.code === "ENOENT") {
2598
+ this._checkForMissingExecutable(
2599
+ executableFile,
2600
+ executableDir,
2601
+ subcommand._name
2602
+ );
2603
+ } else if (err.code === "EACCES") {
2604
+ throw new Error(`'${executableFile}' not executable`);
2605
+ }
2606
+ if (!exitCallback) {
2607
+ process2.exit(1);
2608
+ } else {
2609
+ const wrappedError = new CommanderError2(
2610
+ 1,
2611
+ "commander.executeSubCommandAsync",
2612
+ "(error)"
2613
+ );
2614
+ wrappedError.nestedError = err;
2615
+ exitCallback(wrappedError);
2616
+ }
2617
+ });
2618
+ this.runningCommand = proc;
2619
+ }
2620
+ /**
2621
+ * @private
2622
+ */
2623
+ _dispatchSubcommand(commandName, operands, unknown) {
2624
+ const subCommand = this._findCommand(commandName);
2625
+ if (!subCommand) this.help({ error: true });
2626
+ subCommand._prepareForParse();
2627
+ let promiseChain;
2628
+ promiseChain = this._chainOrCallSubCommandHook(
2629
+ promiseChain,
2630
+ subCommand,
2631
+ "preSubcommand"
2632
+ );
2633
+ promiseChain = this._chainOrCall(promiseChain, () => {
2634
+ if (subCommand._executableHandler) {
2635
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2636
+ } else {
2637
+ return subCommand._parseCommand(operands, unknown);
2638
+ }
2639
+ });
2640
+ return promiseChain;
2641
+ }
2642
+ /**
2643
+ * Invoke help directly if possible, or dispatch if necessary.
2644
+ * e.g. help foo
2645
+ *
2646
+ * @private
2647
+ */
2648
+ _dispatchHelpCommand(subcommandName) {
2649
+ if (!subcommandName) {
2650
+ this.help();
2651
+ }
2652
+ const subCommand = this._findCommand(subcommandName);
2653
+ if (subCommand && !subCommand._executableHandler) {
2654
+ subCommand.help();
2655
+ }
2656
+ return this._dispatchSubcommand(
2657
+ subcommandName,
2658
+ [],
2659
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2660
+ );
2661
+ }
2662
+ /**
2663
+ * Check this.args against expected this.registeredArguments.
2664
+ *
2665
+ * @private
2666
+ */
2667
+ _checkNumberOfArguments() {
2668
+ this.registeredArguments.forEach((arg, i) => {
2669
+ if (arg.required && this.args[i] == null) {
2670
+ this.missingArgument(arg.name());
2671
+ }
2672
+ });
2673
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2674
+ return;
2675
+ }
2676
+ if (this.args.length > this.registeredArguments.length) {
2677
+ this._excessArguments(this.args);
2678
+ }
2679
+ }
2680
+ /**
2681
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2682
+ *
2683
+ * @private
2684
+ */
2685
+ _processArguments() {
2686
+ const myParseArg = (argument, value, previous) => {
2687
+ let parsedValue = value;
2688
+ if (value !== null && argument.parseArg) {
2689
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2690
+ parsedValue = this._callParseArg(
2691
+ argument,
2692
+ value,
2693
+ previous,
2694
+ invalidValueMessage
2695
+ );
2696
+ }
2697
+ return parsedValue;
2698
+ };
2699
+ this._checkNumberOfArguments();
2700
+ const processedArgs = [];
2701
+ this.registeredArguments.forEach((declaredArg, index) => {
2702
+ let value = declaredArg.defaultValue;
2703
+ if (declaredArg.variadic) {
2704
+ if (index < this.args.length) {
2705
+ value = this.args.slice(index);
2706
+ if (declaredArg.parseArg) {
2707
+ value = value.reduce((processed, v) => {
2708
+ return myParseArg(declaredArg, v, processed);
2709
+ }, declaredArg.defaultValue);
2710
+ }
2711
+ } else if (value === void 0) {
2712
+ value = [];
2713
+ }
2714
+ } else if (index < this.args.length) {
2715
+ value = this.args[index];
2716
+ if (declaredArg.parseArg) {
2717
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2718
+ }
2719
+ }
2720
+ processedArgs[index] = value;
2721
+ });
2722
+ this.processedArgs = processedArgs;
2723
+ }
2724
+ /**
2725
+ * Once we have a promise we chain, but call synchronously until then.
2726
+ *
2727
+ * @param {(Promise|undefined)} promise
2728
+ * @param {Function} fn
2729
+ * @return {(Promise|undefined)}
2730
+ * @private
2731
+ */
2732
+ _chainOrCall(promise, fn) {
2733
+ if (promise && promise.then && typeof promise.then === "function") {
2734
+ return promise.then(() => fn());
2735
+ }
2736
+ return fn();
2737
+ }
2738
+ /**
2739
+ *
2740
+ * @param {(Promise|undefined)} promise
2741
+ * @param {string} event
2742
+ * @return {(Promise|undefined)}
2743
+ * @private
2744
+ */
2745
+ _chainOrCallHooks(promise, event) {
2746
+ let result = promise;
2747
+ const hooks = [];
2748
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2749
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2750
+ hooks.push({ hookedCommand, callback });
2751
+ });
2752
+ });
2753
+ if (event === "postAction") {
2754
+ hooks.reverse();
2755
+ }
2756
+ hooks.forEach((hookDetail) => {
2757
+ result = this._chainOrCall(result, () => {
2758
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2759
+ });
2760
+ });
2761
+ return result;
2762
+ }
2763
+ /**
2764
+ *
2765
+ * @param {(Promise|undefined)} promise
2766
+ * @param {Command} subCommand
2767
+ * @param {string} event
2768
+ * @return {(Promise|undefined)}
2769
+ * @private
2770
+ */
2771
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2772
+ let result = promise;
2773
+ if (this._lifeCycleHooks[event] !== void 0) {
2774
+ this._lifeCycleHooks[event].forEach((hook2) => {
2775
+ result = this._chainOrCall(result, () => {
2776
+ return hook2(this, subCommand);
2777
+ });
2778
+ });
2779
+ }
2780
+ return result;
2781
+ }
2782
+ /**
2783
+ * Process arguments in context of this command.
2784
+ * Returns action result, in case it is a promise.
2785
+ *
2786
+ * @private
2787
+ */
2788
+ _parseCommand(operands, unknown) {
2789
+ const parsed = this.parseOptions(unknown);
2790
+ this._parseOptionsEnv();
2791
+ this._parseOptionsImplied();
2792
+ operands = operands.concat(parsed.operands);
2793
+ unknown = parsed.unknown;
2794
+ this.args = operands.concat(unknown);
2795
+ if (operands && this._findCommand(operands[0])) {
2796
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2797
+ }
2798
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2799
+ return this._dispatchHelpCommand(operands[1]);
2800
+ }
2801
+ if (this._defaultCommandName) {
2802
+ this._outputHelpIfRequested(unknown);
2803
+ return this._dispatchSubcommand(
2804
+ this._defaultCommandName,
2805
+ operands,
2806
+ unknown
2807
+ );
2808
+ }
2809
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2810
+ this.help({ error: true });
2811
+ }
2812
+ this._outputHelpIfRequested(parsed.unknown);
2813
+ this._checkForMissingMandatoryOptions();
2814
+ this._checkForConflictingOptions();
2815
+ const checkForUnknownOptions = () => {
2816
+ if (parsed.unknown.length > 0) {
2817
+ this.unknownOption(parsed.unknown[0]);
2818
+ }
2819
+ };
2820
+ const commandEvent = `command:${this.name()}`;
2821
+ if (this._actionHandler) {
2822
+ checkForUnknownOptions();
2823
+ this._processArguments();
2824
+ let promiseChain;
2825
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2826
+ promiseChain = this._chainOrCall(
2827
+ promiseChain,
2828
+ () => this._actionHandler(this.processedArgs)
2829
+ );
2830
+ if (this.parent) {
2831
+ promiseChain = this._chainOrCall(promiseChain, () => {
2832
+ this.parent.emit(commandEvent, operands, unknown);
2833
+ });
2834
+ }
2835
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2836
+ return promiseChain;
2837
+ }
2838
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2839
+ checkForUnknownOptions();
2840
+ this._processArguments();
2841
+ this.parent.emit(commandEvent, operands, unknown);
2842
+ } else if (operands.length) {
2843
+ if (this._findCommand("*")) {
2844
+ return this._dispatchSubcommand("*", operands, unknown);
2845
+ }
2846
+ if (this.listenerCount("command:*")) {
2847
+ this.emit("command:*", operands, unknown);
2848
+ } else if (this.commands.length) {
2849
+ this.unknownCommand();
2850
+ } else {
2851
+ checkForUnknownOptions();
2852
+ this._processArguments();
2853
+ }
2854
+ } else if (this.commands.length) {
2855
+ checkForUnknownOptions();
2856
+ this.help({ error: true });
2857
+ } else {
2858
+ checkForUnknownOptions();
2859
+ this._processArguments();
2860
+ }
2861
+ }
2862
+ /**
2863
+ * Find matching command.
2864
+ *
2865
+ * @private
2866
+ * @return {Command | undefined}
2867
+ */
2868
+ _findCommand(name) {
2869
+ if (!name) return void 0;
2870
+ return this.commands.find(
2871
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2872
+ );
2873
+ }
2874
+ /**
2875
+ * Return an option matching `arg` if any.
2876
+ *
2877
+ * @param {string} arg
2878
+ * @return {Option}
2879
+ * @package
2880
+ */
2881
+ _findOption(arg) {
2882
+ return this.options.find((option) => option.is(arg));
2883
+ }
2884
+ /**
2885
+ * Display an error message if a mandatory option does not have a value.
2886
+ * Called after checking for help flags in leaf subcommand.
2887
+ *
2888
+ * @private
2889
+ */
2890
+ _checkForMissingMandatoryOptions() {
2891
+ this._getCommandAndAncestors().forEach((cmd) => {
2892
+ cmd.options.forEach((anOption) => {
2893
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2894
+ cmd.missingMandatoryOptionValue(anOption);
2895
+ }
2896
+ });
2897
+ });
2898
+ }
2899
+ /**
2900
+ * Display an error message if conflicting options are used together in this.
2901
+ *
2902
+ * @private
2903
+ */
2904
+ _checkForConflictingLocalOptions() {
2905
+ const definedNonDefaultOptions = this.options.filter((option) => {
2906
+ const optionKey = option.attributeName();
2907
+ if (this.getOptionValue(optionKey) === void 0) {
2908
+ return false;
2909
+ }
2910
+ return this.getOptionValueSource(optionKey) !== "default";
2911
+ });
2912
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2913
+ (option) => option.conflictsWith.length > 0
2914
+ );
2915
+ optionsWithConflicting.forEach((option) => {
2916
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2917
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2918
+ );
2919
+ if (conflictingAndDefined) {
2920
+ this._conflictingOption(option, conflictingAndDefined);
2921
+ }
2922
+ });
2923
+ }
2924
+ /**
2925
+ * Display an error message if conflicting options are used together.
2926
+ * Called after checking for help flags in leaf subcommand.
2927
+ *
2928
+ * @private
2929
+ */
2930
+ _checkForConflictingOptions() {
2931
+ this._getCommandAndAncestors().forEach((cmd) => {
2932
+ cmd._checkForConflictingLocalOptions();
2933
+ });
2934
+ }
2935
+ /**
2936
+ * Parse options from `argv` removing known options,
2937
+ * and return argv split into operands and unknown arguments.
2938
+ *
2939
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2940
+ *
2941
+ * Examples:
2942
+ *
2943
+ * argv => operands, unknown
2944
+ * --known kkk op => [op], []
2945
+ * op --known kkk => [op], []
2946
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2947
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2948
+ *
2949
+ * @param {string[]} argv
2950
+ * @return {{operands: string[], unknown: string[]}}
2951
+ */
2952
+ parseOptions(argv) {
2953
+ const operands = [];
2954
+ const unknown = [];
2955
+ let dest = operands;
2956
+ const args = argv.slice();
2957
+ function maybeOption(arg) {
2958
+ return arg.length > 1 && arg[0] === "-";
2959
+ }
2960
+ let activeVariadicOption = null;
2961
+ while (args.length) {
2962
+ const arg = args.shift();
2963
+ if (arg === "--") {
2964
+ if (dest === unknown) dest.push(arg);
2965
+ dest.push(...args);
2966
+ break;
2967
+ }
2968
+ if (activeVariadicOption && !maybeOption(arg)) {
2969
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2970
+ continue;
2971
+ }
2972
+ activeVariadicOption = null;
2973
+ if (maybeOption(arg)) {
2974
+ const option = this._findOption(arg);
2975
+ if (option) {
2976
+ if (option.required) {
2977
+ const value = args.shift();
2978
+ if (value === void 0) this.optionMissingArgument(option);
2979
+ this.emit(`option:${option.name()}`, value);
2980
+ } else if (option.optional) {
2981
+ let value = null;
2982
+ if (args.length > 0 && !maybeOption(args[0])) {
2983
+ value = args.shift();
2984
+ }
2985
+ this.emit(`option:${option.name()}`, value);
2986
+ } else {
2987
+ this.emit(`option:${option.name()}`);
2988
+ }
2989
+ activeVariadicOption = option.variadic ? option : null;
2990
+ continue;
2991
+ }
2992
+ }
2993
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2994
+ const option = this._findOption(`-${arg[1]}`);
2995
+ if (option) {
2996
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2997
+ this.emit(`option:${option.name()}`, arg.slice(2));
2998
+ } else {
2999
+ this.emit(`option:${option.name()}`);
3000
+ args.unshift(`-${arg.slice(2)}`);
3001
+ }
3002
+ continue;
3003
+ }
3004
+ }
3005
+ if (/^--[^=]+=/.test(arg)) {
3006
+ const index = arg.indexOf("=");
3007
+ const option = this._findOption(arg.slice(0, index));
3008
+ if (option && (option.required || option.optional)) {
3009
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
3010
+ continue;
3011
+ }
3012
+ }
3013
+ if (maybeOption(arg)) {
3014
+ dest = unknown;
3015
+ }
3016
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
3017
+ if (this._findCommand(arg)) {
3018
+ operands.push(arg);
3019
+ if (args.length > 0) unknown.push(...args);
3020
+ break;
3021
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
3022
+ operands.push(arg);
3023
+ if (args.length > 0) operands.push(...args);
3024
+ break;
3025
+ } else if (this._defaultCommandName) {
3026
+ unknown.push(arg);
3027
+ if (args.length > 0) unknown.push(...args);
3028
+ break;
3029
+ }
3030
+ }
3031
+ if (this._passThroughOptions) {
3032
+ dest.push(arg);
3033
+ if (args.length > 0) dest.push(...args);
3034
+ break;
3035
+ }
3036
+ dest.push(arg);
3037
+ }
3038
+ return { operands, unknown };
3039
+ }
3040
+ /**
3041
+ * Return an object containing local option values as key-value pairs.
3042
+ *
3043
+ * @return {object}
3044
+ */
3045
+ opts() {
3046
+ if (this._storeOptionsAsProperties) {
3047
+ const result = {};
3048
+ const len = this.options.length;
3049
+ for (let i = 0; i < len; i++) {
3050
+ const key = this.options[i].attributeName();
3051
+ result[key] = key === this._versionOptionName ? this._version : this[key];
3052
+ }
3053
+ return result;
3054
+ }
3055
+ return this._optionValues;
3056
+ }
3057
+ /**
3058
+ * Return an object containing merged local and global option values as key-value pairs.
3059
+ *
3060
+ * @return {object}
3061
+ */
3062
+ optsWithGlobals() {
3063
+ return this._getCommandAndAncestors().reduce(
3064
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
3065
+ {}
3066
+ );
3067
+ }
3068
+ /**
3069
+ * Display error message and exit (or call exitOverride).
3070
+ *
3071
+ * @param {string} message
3072
+ * @param {object} [errorOptions]
3073
+ * @param {string} [errorOptions.code] - an id string representing the error
3074
+ * @param {number} [errorOptions.exitCode] - used with process.exit
3075
+ */
3076
+ error(message, errorOptions) {
3077
+ this._outputConfiguration.outputError(
3078
+ `${message}
3079
+ `,
3080
+ this._outputConfiguration.writeErr
3081
+ );
3082
+ if (typeof this._showHelpAfterError === "string") {
3083
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
3084
+ `);
3085
+ } else if (this._showHelpAfterError) {
3086
+ this._outputConfiguration.writeErr("\n");
3087
+ this.outputHelp({ error: true });
3088
+ }
3089
+ const config = errorOptions || {};
3090
+ const exitCode = config.exitCode || 1;
3091
+ const code = config.code || "commander.error";
3092
+ this._exit(exitCode, code, message);
3093
+ }
3094
+ /**
3095
+ * Apply any option related environment variables, if option does
3096
+ * not have a value from cli or client code.
3097
+ *
3098
+ * @private
3099
+ */
3100
+ _parseOptionsEnv() {
3101
+ this.options.forEach((option) => {
3102
+ if (option.envVar && option.envVar in process2.env) {
3103
+ const optionKey = option.attributeName();
3104
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
3105
+ this.getOptionValueSource(optionKey)
3106
+ )) {
3107
+ if (option.required || option.optional) {
3108
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
3109
+ } else {
3110
+ this.emit(`optionEnv:${option.name()}`);
3111
+ }
3112
+ }
3113
+ }
3114
+ });
3115
+ }
3116
+ /**
3117
+ * Apply any implied option values, if option is undefined or default value.
3118
+ *
3119
+ * @private
3120
+ */
3121
+ _parseOptionsImplied() {
3122
+ const dualHelper = new DualOptions(this.options);
3123
+ const hasCustomOptionValue = (optionKey) => {
3124
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
3125
+ };
3126
+ this.options.filter(
3127
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
3128
+ this.getOptionValue(option.attributeName()),
3129
+ option
3130
+ )
3131
+ ).forEach((option) => {
3132
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
3133
+ this.setOptionValueWithSource(
3134
+ impliedKey,
3135
+ option.implied[impliedKey],
3136
+ "implied"
3137
+ );
3138
+ });
3139
+ });
3140
+ }
3141
+ /**
3142
+ * Argument `name` is missing.
3143
+ *
3144
+ * @param {string} name
3145
+ * @private
3146
+ */
3147
+ missingArgument(name) {
3148
+ const message = `error: missing required argument '${name}'`;
3149
+ this.error(message, { code: "commander.missingArgument" });
3150
+ }
3151
+ /**
3152
+ * `Option` is missing an argument.
3153
+ *
3154
+ * @param {Option} option
3155
+ * @private
3156
+ */
3157
+ optionMissingArgument(option) {
3158
+ const message = `error: option '${option.flags}' argument missing`;
3159
+ this.error(message, { code: "commander.optionMissingArgument" });
3160
+ }
3161
+ /**
3162
+ * `Option` does not have a value, and is a mandatory option.
3163
+ *
3164
+ * @param {Option} option
3165
+ * @private
3166
+ */
3167
+ missingMandatoryOptionValue(option) {
3168
+ const message = `error: required option '${option.flags}' not specified`;
3169
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
3170
+ }
3171
+ /**
3172
+ * `Option` conflicts with another option.
3173
+ *
3174
+ * @param {Option} option
3175
+ * @param {Option} conflictingOption
3176
+ * @private
3177
+ */
3178
+ _conflictingOption(option, conflictingOption) {
3179
+ const findBestOptionFromValue = (option2) => {
3180
+ const optionKey = option2.attributeName();
3181
+ const optionValue = this.getOptionValue(optionKey);
3182
+ const negativeOption = this.options.find(
3183
+ (target) => target.negate && optionKey === target.attributeName()
3184
+ );
3185
+ const positiveOption = this.options.find(
3186
+ (target) => !target.negate && optionKey === target.attributeName()
3187
+ );
3188
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
3189
+ return negativeOption;
3190
+ }
3191
+ return positiveOption || option2;
3192
+ };
3193
+ const getErrorMessage = (option2) => {
3194
+ const bestOption = findBestOptionFromValue(option2);
3195
+ const optionKey = bestOption.attributeName();
3196
+ const source = this.getOptionValueSource(optionKey);
3197
+ if (source === "env") {
3198
+ return `environment variable '${bestOption.envVar}'`;
3199
+ }
3200
+ return `option '${bestOption.flags}'`;
3201
+ };
3202
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
3203
+ this.error(message, { code: "commander.conflictingOption" });
3204
+ }
3205
+ /**
3206
+ * Unknown option `flag`.
3207
+ *
3208
+ * @param {string} flag
3209
+ * @private
3210
+ */
3211
+ unknownOption(flag) {
3212
+ if (this._allowUnknownOption) return;
3213
+ let suggestion = "";
3214
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
3215
+ let candidateFlags = [];
3216
+ let command = this;
3217
+ do {
3218
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
3219
+ candidateFlags = candidateFlags.concat(moreFlags);
3220
+ command = command.parent;
3221
+ } while (command && !command._enablePositionalOptions);
3222
+ suggestion = suggestSimilar(flag, candidateFlags);
3223
+ }
3224
+ const message = `error: unknown option '${flag}'${suggestion}`;
3225
+ this.error(message, { code: "commander.unknownOption" });
3226
+ }
3227
+ /**
3228
+ * Excess arguments, more than expected.
3229
+ *
3230
+ * @param {string[]} receivedArgs
3231
+ * @private
3232
+ */
3233
+ _excessArguments(receivedArgs) {
3234
+ if (this._allowExcessArguments) return;
3235
+ const expected = this.registeredArguments.length;
3236
+ const s = expected === 1 ? "" : "s";
3237
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
3238
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
3239
+ this.error(message, { code: "commander.excessArguments" });
3240
+ }
3241
+ /**
3242
+ * Unknown command.
3243
+ *
3244
+ * @private
3245
+ */
3246
+ unknownCommand() {
3247
+ const unknownName = this.args[0];
3248
+ let suggestion = "";
3249
+ if (this._showSuggestionAfterError) {
3250
+ const candidateNames = [];
3251
+ this.createHelp().visibleCommands(this).forEach((command) => {
3252
+ candidateNames.push(command.name());
3253
+ if (command.alias()) candidateNames.push(command.alias());
3254
+ });
3255
+ suggestion = suggestSimilar(unknownName, candidateNames);
3256
+ }
3257
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
3258
+ this.error(message, { code: "commander.unknownCommand" });
3259
+ }
3260
+ /**
3261
+ * Get or set the program version.
3262
+ *
3263
+ * This method auto-registers the "-V, --version" option which will print the version number.
3264
+ *
3265
+ * You can optionally supply the flags and description to override the defaults.
3266
+ *
3267
+ * @param {string} [str]
3268
+ * @param {string} [flags]
3269
+ * @param {string} [description]
3270
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
3271
+ */
3272
+ version(str, flags, description) {
3273
+ if (str === void 0) return this._version;
3274
+ this._version = str;
3275
+ flags = flags || "-V, --version";
3276
+ description = description || "output the version number";
3277
+ const versionOption = this.createOption(flags, description);
3278
+ this._versionOptionName = versionOption.attributeName();
3279
+ this._registerOption(versionOption);
3280
+ this.on("option:" + versionOption.name(), () => {
3281
+ this._outputConfiguration.writeOut(`${str}
3282
+ `);
3283
+ this._exit(0, "commander.version", str);
3284
+ });
3285
+ return this;
3286
+ }
3287
+ /**
3288
+ * Set the description.
3289
+ *
3290
+ * @param {string} [str]
3291
+ * @param {object} [argsDescription]
3292
+ * @return {(string|Command)}
3293
+ */
3294
+ description(str, argsDescription) {
3295
+ if (str === void 0 && argsDescription === void 0)
3296
+ return this._description;
3297
+ this._description = str;
3298
+ if (argsDescription) {
3299
+ this._argsDescription = argsDescription;
3300
+ }
3301
+ return this;
3302
+ }
3303
+ /**
3304
+ * Set the summary. Used when listed as subcommand of parent.
3305
+ *
3306
+ * @param {string} [str]
3307
+ * @return {(string|Command)}
3308
+ */
3309
+ summary(str) {
3310
+ if (str === void 0) return this._summary;
3311
+ this._summary = str;
3312
+ return this;
3313
+ }
3314
+ /**
3315
+ * Set an alias for the command.
3316
+ *
3317
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3318
+ *
3319
+ * @param {string} [alias]
3320
+ * @return {(string|Command)}
3321
+ */
3322
+ alias(alias) {
3323
+ if (alias === void 0) return this._aliases[0];
3324
+ let command = this;
3325
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
3326
+ command = this.commands[this.commands.length - 1];
3327
+ }
3328
+ if (alias === command._name)
3329
+ throw new Error("Command alias can't be the same as its name");
3330
+ const matchingCommand = this.parent?._findCommand(alias);
3331
+ if (matchingCommand) {
3332
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
3333
+ throw new Error(
3334
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
3335
+ );
3336
+ }
3337
+ command._aliases.push(alias);
3338
+ return this;
3339
+ }
3340
+ /**
3341
+ * Set aliases for the command.
3342
+ *
3343
+ * Only the first alias is shown in the auto-generated help.
3344
+ *
3345
+ * @param {string[]} [aliases]
3346
+ * @return {(string[]|Command)}
3347
+ */
3348
+ aliases(aliases) {
3349
+ if (aliases === void 0) return this._aliases;
3350
+ aliases.forEach((alias) => this.alias(alias));
3351
+ return this;
3352
+ }
3353
+ /**
3354
+ * Set / get the command usage `str`.
3355
+ *
3356
+ * @param {string} [str]
3357
+ * @return {(string|Command)}
3358
+ */
3359
+ usage(str) {
3360
+ if (str === void 0) {
3361
+ if (this._usage) return this._usage;
3362
+ const args = this.registeredArguments.map((arg) => {
3363
+ return humanReadableArgName(arg);
3364
+ });
3365
+ return [].concat(
3366
+ this.options.length || this._helpOption !== null ? "[options]" : [],
3367
+ this.commands.length ? "[command]" : [],
3368
+ this.registeredArguments.length ? args : []
3369
+ ).join(" ");
3370
+ }
3371
+ this._usage = str;
3372
+ return this;
3373
+ }
3374
+ /**
3375
+ * Get or set the name of the command.
3376
+ *
3377
+ * @param {string} [str]
3378
+ * @return {(string|Command)}
3379
+ */
3380
+ name(str) {
3381
+ if (str === void 0) return this._name;
3382
+ this._name = str;
3383
+ return this;
3384
+ }
3385
+ /**
3386
+ * Set the name of the command from script filename, such as process.argv[1],
3387
+ * or require.main.filename, or __filename.
3388
+ *
3389
+ * (Used internally and public although not documented in README.)
3390
+ *
3391
+ * @example
3392
+ * program.nameFromFilename(require.main.filename);
3393
+ *
3394
+ * @param {string} filename
3395
+ * @return {Command}
3396
+ */
3397
+ nameFromFilename(filename) {
3398
+ this._name = path3.basename(filename, path3.extname(filename));
3399
+ return this;
3400
+ }
3401
+ /**
3402
+ * Get or set the directory for searching for executable subcommands of this command.
3403
+ *
3404
+ * @example
3405
+ * program.executableDir(__dirname);
3406
+ * // or
3407
+ * program.executableDir('subcommands');
3408
+ *
3409
+ * @param {string} [path]
3410
+ * @return {(string|null|Command)}
3411
+ */
3412
+ executableDir(path4) {
3413
+ if (path4 === void 0) return this._executableDir;
3414
+ this._executableDir = path4;
3415
+ return this;
3416
+ }
3417
+ /**
3418
+ * Return program help documentation.
3419
+ *
3420
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3421
+ * @return {string}
3422
+ */
3423
+ helpInformation(contextOptions) {
3424
+ const helper = this.createHelp();
3425
+ const context = this._getOutputContext(contextOptions);
3426
+ helper.prepareContext({
3427
+ error: context.error,
3428
+ helpWidth: context.helpWidth,
3429
+ outputHasColors: context.hasColors
3430
+ });
3431
+ const text = helper.formatHelp(this, helper);
3432
+ if (context.hasColors) return text;
3433
+ return this._outputConfiguration.stripColor(text);
3434
+ }
3435
+ /**
3436
+ * @typedef HelpContext
3437
+ * @type {object}
3438
+ * @property {boolean} error
3439
+ * @property {number} helpWidth
3440
+ * @property {boolean} hasColors
3441
+ * @property {function} write - includes stripColor if needed
3442
+ *
3443
+ * @returns {HelpContext}
3444
+ * @private
3445
+ */
3446
+ _getOutputContext(contextOptions) {
3447
+ contextOptions = contextOptions || {};
3448
+ const error = !!contextOptions.error;
3449
+ let baseWrite;
3450
+ let hasColors;
3451
+ let helpWidth;
3452
+ if (error) {
3453
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3454
+ hasColors = this._outputConfiguration.getErrHasColors();
3455
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3456
+ } else {
3457
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3458
+ hasColors = this._outputConfiguration.getOutHasColors();
3459
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3460
+ }
3461
+ const write = (str) => {
3462
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3463
+ return baseWrite(str);
3464
+ };
3465
+ return { error, write, hasColors, helpWidth };
3466
+ }
3467
+ /**
3468
+ * Output help information for this command.
3469
+ *
3470
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3471
+ *
3472
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3473
+ */
3474
+ outputHelp(contextOptions) {
3475
+ let deprecatedCallback;
3476
+ if (typeof contextOptions === "function") {
3477
+ deprecatedCallback = contextOptions;
3478
+ contextOptions = void 0;
3479
+ }
3480
+ const outputContext = this._getOutputContext(contextOptions);
3481
+ const eventContext = {
3482
+ error: outputContext.error,
3483
+ write: outputContext.write,
3484
+ command: this
3485
+ };
3486
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3487
+ this.emit("beforeHelp", eventContext);
3488
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3489
+ if (deprecatedCallback) {
3490
+ helpInformation = deprecatedCallback(helpInformation);
3491
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3492
+ throw new Error("outputHelp callback must return a string or a Buffer");
3493
+ }
3494
+ }
3495
+ outputContext.write(helpInformation);
3496
+ if (this._getHelpOption()?.long) {
3497
+ this.emit(this._getHelpOption().long);
3498
+ }
3499
+ this.emit("afterHelp", eventContext);
3500
+ this._getCommandAndAncestors().forEach(
3501
+ (command) => command.emit("afterAllHelp", eventContext)
3502
+ );
3503
+ }
3504
+ /**
3505
+ * You can pass in flags and a description to customise the built-in help option.
3506
+ * Pass in false to disable the built-in help option.
3507
+ *
3508
+ * @example
3509
+ * program.helpOption('-?, --help' 'show help'); // customise
3510
+ * program.helpOption(false); // disable
3511
+ *
3512
+ * @param {(string | boolean)} flags
3513
+ * @param {string} [description]
3514
+ * @return {Command} `this` command for chaining
3515
+ */
3516
+ helpOption(flags, description) {
3517
+ if (typeof flags === "boolean") {
3518
+ if (flags) {
3519
+ this._helpOption = this._helpOption ?? void 0;
3520
+ } else {
3521
+ this._helpOption = null;
3522
+ }
3523
+ return this;
3524
+ }
3525
+ flags = flags ?? "-h, --help";
3526
+ description = description ?? "display help for command";
3527
+ this._helpOption = this.createOption(flags, description);
3528
+ return this;
3529
+ }
3530
+ /**
3531
+ * Lazy create help option.
3532
+ * Returns null if has been disabled with .helpOption(false).
3533
+ *
3534
+ * @returns {(Option | null)} the help option
3535
+ * @package
3536
+ */
3537
+ _getHelpOption() {
3538
+ if (this._helpOption === void 0) {
3539
+ this.helpOption(void 0, void 0);
3540
+ }
3541
+ return this._helpOption;
3542
+ }
3543
+ /**
3544
+ * Supply your own option to use for the built-in help option.
3545
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3546
+ *
3547
+ * @param {Option} option
3548
+ * @return {Command} `this` command for chaining
3549
+ */
3550
+ addHelpOption(option) {
3551
+ this._helpOption = option;
3552
+ return this;
3553
+ }
3554
+ /**
3555
+ * Output help information and exit.
3556
+ *
3557
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3558
+ *
3559
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3560
+ */
3561
+ help(contextOptions) {
3562
+ this.outputHelp(contextOptions);
3563
+ let exitCode = Number(process2.exitCode ?? 0);
3564
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3565
+ exitCode = 1;
3566
+ }
3567
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3568
+ }
3569
+ /**
3570
+ * // Do a little typing to coordinate emit and listener for the help text events.
3571
+ * @typedef HelpTextEventContext
3572
+ * @type {object}
3573
+ * @property {boolean} error
3574
+ * @property {Command} command
3575
+ * @property {function} write
3576
+ */
3577
+ /**
3578
+ * Add additional text to be displayed with the built-in help.
3579
+ *
3580
+ * Position is 'before' or 'after' to affect just this command,
3581
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3582
+ *
3583
+ * @param {string} position - before or after built-in help
3584
+ * @param {(string | Function)} text - string to add, or a function returning a string
3585
+ * @return {Command} `this` command for chaining
3586
+ */
3587
+ addHelpText(position, text) {
3588
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3589
+ if (!allowedValues.includes(position)) {
3590
+ throw new Error(`Unexpected value for position to addHelpText.
3591
+ Expecting one of '${allowedValues.join("', '")}'`);
3592
+ }
3593
+ const helpEvent = `${position}Help`;
3594
+ this.on(helpEvent, (context) => {
3595
+ let helpStr;
3596
+ if (typeof text === "function") {
3597
+ helpStr = text({ error: context.error, command: context.command });
3598
+ } else {
3599
+ helpStr = text;
3600
+ }
3601
+ if (helpStr) {
3602
+ context.write(`${helpStr}
3603
+ `);
3604
+ }
3605
+ });
3606
+ return this;
3607
+ }
3608
+ /**
3609
+ * Output help information if help flags specified
3610
+ *
3611
+ * @param {Array} args - array of options to search for help flags
3612
+ * @private
3613
+ */
3614
+ _outputHelpIfRequested(args) {
3615
+ const helpOption = this._getHelpOption();
3616
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3617
+ if (helpRequested) {
3618
+ this.outputHelp();
3619
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3620
+ }
3621
+ }
3622
+ };
3623
+ function incrementNodeInspectorPort(args) {
3624
+ return args.map((arg) => {
3625
+ if (!arg.startsWith("--inspect")) {
3626
+ return arg;
3627
+ }
3628
+ let debugOption;
3629
+ let debugHost = "127.0.0.1";
3630
+ let debugPort = "9229";
3631
+ let match;
3632
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3633
+ debugOption = match[1];
3634
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3635
+ debugOption = match[1];
3636
+ if (/^\d+$/.test(match[3])) {
3637
+ debugPort = match[3];
3638
+ } else {
3639
+ debugHost = match[3];
3640
+ }
3641
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3642
+ debugOption = match[1];
3643
+ debugHost = match[3];
3644
+ debugPort = match[4];
3645
+ }
3646
+ if (debugOption && debugPort !== "0") {
3647
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3648
+ }
3649
+ return arg;
3650
+ });
3651
+ }
3652
+ function useColor() {
3653
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3654
+ return false;
3655
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3656
+ return true;
3657
+ return void 0;
3658
+ }
3659
+ exports.Command = Command2;
3660
+ exports.useColor = useColor;
3661
+ }
3662
+ });
3663
+
3664
+ // node_modules/commander/index.js
3665
+ var require_commander = __commonJS({
3666
+ "node_modules/commander/index.js"(exports) {
3667
+ var { Argument: Argument2 } = require_argument();
3668
+ var { Command: Command2 } = require_command();
3669
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3670
+ var { Help: Help2 } = require_help();
3671
+ var { Option: Option2 } = require_option();
3672
+ exports.program = new Command2();
3673
+ exports.createCommand = (name) => new Command2(name);
3674
+ exports.createOption = (flags, description) => new Option2(flags, description);
3675
+ exports.createArgument = (name, description) => new Argument2(name, description);
3676
+ exports.Command = Command2;
3677
+ exports.Option = Option2;
3678
+ exports.Argument = Argument2;
3679
+ exports.Help = Help2;
3680
+ exports.CommanderError = CommanderError2;
3681
+ exports.InvalidArgumentError = InvalidArgumentError2;
3682
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3683
+ }
3684
+ });
3685
+
408
3686
  // node_modules/moment/moment.js
409
3687
  var require_moment = __commonJS({
410
3688
  "node_modules/moment/moment.js"(exports, module) {
@@ -4405,6 +7683,576 @@
4405
7683
  }
4406
7684
  });
4407
7685
 
7686
+ // node_modules/uri-templates/uri-templates.js
7687
+ var require_uri_templates = __commonJS({
7688
+ "node_modules/uri-templates/uri-templates.js"(exports, module) {
7689
+ (function(global, factory) {
7690
+ if (typeof define === "function" && define.amd) {
7691
+ define("uri-templates", [], factory);
7692
+ } else if (typeof module !== "undefined" && module.exports) {
7693
+ module.exports = factory();
7694
+ } else {
7695
+ global.UriTemplate = factory();
7696
+ }
7697
+ })(exports, function() {
7698
+ var uriTemplateGlobalModifiers = {
7699
+ "+": true,
7700
+ "#": true,
7701
+ ".": true,
7702
+ "/": true,
7703
+ ";": true,
7704
+ "?": true,
7705
+ "&": true
7706
+ };
7707
+ var uriTemplateSuffices = {
7708
+ "*": true
7709
+ };
7710
+ var urlEscapedChars = /[:/&?#]/;
7711
+ function notReallyPercentEncode(string) {
7712
+ return encodeURI(string).replace(/%25[0-9][0-9]/g, function(doubleEncoded) {
7713
+ return "%" + doubleEncoded.substring(3);
7714
+ });
7715
+ }
7716
+ function isPercentEncoded(string) {
7717
+ string = string.replace(/%../g, "");
7718
+ return encodeURIComponent(string) === string;
7719
+ }
7720
+ function uriTemplateSubstitution(spec) {
7721
+ var modifier = "";
7722
+ if (uriTemplateGlobalModifiers[spec.charAt(0)]) {
7723
+ modifier = spec.charAt(0);
7724
+ spec = spec.substring(1);
7725
+ }
7726
+ var separator = "";
7727
+ var prefix = "";
7728
+ var shouldEscape = true;
7729
+ var showVariables = false;
7730
+ var trimEmptyString = false;
7731
+ if (modifier == "+") {
7732
+ shouldEscape = false;
7733
+ } else if (modifier == ".") {
7734
+ prefix = ".";
7735
+ separator = ".";
7736
+ } else if (modifier == "/") {
7737
+ prefix = "/";
7738
+ separator = "/";
7739
+ } else if (modifier == "#") {
7740
+ prefix = "#";
7741
+ shouldEscape = false;
7742
+ } else if (modifier == ";") {
7743
+ prefix = ";";
7744
+ separator = ";", showVariables = true;
7745
+ trimEmptyString = true;
7746
+ } else if (modifier == "?") {
7747
+ prefix = "?";
7748
+ separator = "&", showVariables = true;
7749
+ } else if (modifier == "&") {
7750
+ prefix = "&";
7751
+ separator = "&", showVariables = true;
7752
+ }
7753
+ var varNames = [];
7754
+ var varList = spec.split(",");
7755
+ var varSpecs = [];
7756
+ var varSpecMap = {};
7757
+ for (var i = 0; i < varList.length; i++) {
7758
+ var varName = varList[i];
7759
+ var truncate = null;
7760
+ if (varName.indexOf(":") != -1) {
7761
+ var parts = varName.split(":");
7762
+ varName = parts[0];
7763
+ truncate = parseInt(parts[1]);
7764
+ }
7765
+ var suffices = {};
7766
+ while (uriTemplateSuffices[varName.charAt(varName.length - 1)]) {
7767
+ suffices[varName.charAt(varName.length - 1)] = true;
7768
+ varName = varName.substring(0, varName.length - 1);
7769
+ }
7770
+ var varSpec = {
7771
+ truncate,
7772
+ name: varName,
7773
+ suffices
7774
+ };
7775
+ varSpecs.push(varSpec);
7776
+ varSpecMap[varName] = varSpec;
7777
+ varNames.push(varName);
7778
+ }
7779
+ var subFunction = function(valueFunction) {
7780
+ var result = "";
7781
+ var startIndex = 0;
7782
+ for (var i2 = 0; i2 < varSpecs.length; i2++) {
7783
+ var varSpec2 = varSpecs[i2];
7784
+ var value = valueFunction(varSpec2.name);
7785
+ if (value == null || Array.isArray(value) && value.length == 0 || typeof value == "object" && Object.keys(value).length == 0) {
7786
+ startIndex++;
7787
+ continue;
7788
+ }
7789
+ if (i2 == startIndex) {
7790
+ result += prefix;
7791
+ } else {
7792
+ result += separator || ",";
7793
+ }
7794
+ if (Array.isArray(value)) {
7795
+ if (showVariables) {
7796
+ result += varSpec2.name + "=";
7797
+ }
7798
+ for (var j = 0; j < value.length; j++) {
7799
+ if (j > 0) {
7800
+ result += varSpec2.suffices["*"] ? separator || "," : ",";
7801
+ if (varSpec2.suffices["*"] && showVariables) {
7802
+ result += varSpec2.name + "=";
7803
+ }
7804
+ }
7805
+ result += shouldEscape ? encodeURIComponent(value[j]).replace(/!/g, "%21") : notReallyPercentEncode(value[j]);
7806
+ }
7807
+ } else if (typeof value == "object") {
7808
+ if (showVariables && !varSpec2.suffices["*"]) {
7809
+ result += varSpec2.name + "=";
7810
+ }
7811
+ var first = true;
7812
+ for (var key in value) {
7813
+ if (!first) {
7814
+ result += varSpec2.suffices["*"] ? separator || "," : ",";
7815
+ }
7816
+ first = false;
7817
+ result += shouldEscape ? encodeURIComponent(key).replace(/!/g, "%21") : notReallyPercentEncode(key);
7818
+ result += varSpec2.suffices["*"] ? "=" : ",";
7819
+ result += shouldEscape ? encodeURIComponent(value[key]).replace(/!/g, "%21") : notReallyPercentEncode(value[key]);
7820
+ }
7821
+ } else {
7822
+ if (showVariables) {
7823
+ result += varSpec2.name;
7824
+ if (!trimEmptyString || value != "") {
7825
+ result += "=";
7826
+ }
7827
+ }
7828
+ if (varSpec2.truncate != null) {
7829
+ value = value.substring(0, varSpec2.truncate);
7830
+ }
7831
+ result += shouldEscape ? encodeURIComponent(value).replace(/!/g, "%21") : notReallyPercentEncode(value);
7832
+ }
7833
+ }
7834
+ return result;
7835
+ };
7836
+ var guessFunction = function(stringValue, resultObj, strict) {
7837
+ if (prefix) {
7838
+ stringValue = stringValue.substring(prefix.length);
7839
+ }
7840
+ if (varSpecs.length == 1 && varSpecs[0].suffices["*"]) {
7841
+ var varSpec2 = varSpecs[0];
7842
+ var varName2 = varSpec2.name;
7843
+ var arrayValue = varSpec2.suffices["*"] ? stringValue.split(separator || ",") : [stringValue];
7844
+ var hasEquals = shouldEscape && stringValue.indexOf("=") != -1;
7845
+ for (var i2 = 1; i2 < arrayValue.length; i2++) {
7846
+ var stringValue = arrayValue[i2];
7847
+ if (hasEquals && stringValue.indexOf("=") == -1) {
7848
+ arrayValue[i2 - 1] += (separator || ",") + stringValue;
7849
+ arrayValue.splice(i2, 1);
7850
+ i2--;
7851
+ }
7852
+ }
7853
+ for (var i2 = 0; i2 < arrayValue.length; i2++) {
7854
+ var stringValue = arrayValue[i2];
7855
+ if (shouldEscape && stringValue.indexOf("=") != -1) {
7856
+ hasEquals = true;
7857
+ }
7858
+ var innerArrayValue = stringValue.split(",");
7859
+ if (innerArrayValue.length == 1) {
7860
+ arrayValue[i2] = innerArrayValue[0];
7861
+ } else {
7862
+ arrayValue[i2] = innerArrayValue;
7863
+ }
7864
+ }
7865
+ if (showVariables || hasEquals) {
7866
+ var objectValue = resultObj[varName2] || {};
7867
+ for (var j = 0; j < arrayValue.length; j++) {
7868
+ var innerValue = stringValue;
7869
+ if (showVariables && !innerValue) {
7870
+ continue;
7871
+ }
7872
+ if (typeof arrayValue[j] == "string") {
7873
+ var stringValue = arrayValue[j];
7874
+ var innerVarName = stringValue.split("=", 1)[0];
7875
+ var stringValue = stringValue.substring(innerVarName.length + 1);
7876
+ if (shouldEscape) {
7877
+ if (strict && !isPercentEncoded(stringValue)) {
7878
+ return;
7879
+ }
7880
+ stringValue = decodeURIComponent(stringValue);
7881
+ }
7882
+ innerValue = stringValue;
7883
+ } else {
7884
+ var stringValue = arrayValue[j][0];
7885
+ var innerVarName = stringValue.split("=", 1)[0];
7886
+ var stringValue = stringValue.substring(innerVarName.length + 1);
7887
+ if (shouldEscape) {
7888
+ if (strict && !isPercentEncoded(stringValue)) {
7889
+ return;
7890
+ }
7891
+ stringValue = decodeURIComponent(stringValue);
7892
+ }
7893
+ arrayValue[j][0] = stringValue;
7894
+ innerValue = arrayValue[j];
7895
+ }
7896
+ if (shouldEscape) {
7897
+ if (strict && !isPercentEncoded(innerVarName)) {
7898
+ return;
7899
+ }
7900
+ innerVarName = decodeURIComponent(innerVarName);
7901
+ }
7902
+ if (objectValue[innerVarName] !== void 0) {
7903
+ if (Array.isArray(objectValue[innerVarName])) {
7904
+ objectValue[innerVarName].push(innerValue);
7905
+ } else {
7906
+ objectValue[innerVarName] = [objectValue[innerVarName], innerValue];
7907
+ }
7908
+ } else {
7909
+ objectValue[innerVarName] = innerValue;
7910
+ }
7911
+ }
7912
+ if (Object.keys(objectValue).length == 1 && objectValue[varName2] !== void 0) {
7913
+ resultObj[varName2] = objectValue[varName2];
7914
+ } else {
7915
+ resultObj[varName2] = objectValue;
7916
+ }
7917
+ } else {
7918
+ if (shouldEscape) {
7919
+ for (var j = 0; j < arrayValue.length; j++) {
7920
+ var innerArrayValue = arrayValue[j];
7921
+ if (Array.isArray(innerArrayValue)) {
7922
+ for (var k = 0; k < innerArrayValue.length; k++) {
7923
+ if (strict && !isPercentEncoded(innerArrayValue[k])) {
7924
+ return;
7925
+ }
7926
+ innerArrayValue[k] = decodeURIComponent(innerArrayValue[k]);
7927
+ }
7928
+ } else {
7929
+ if (strict && !isPercentEncoded(innerArrayValue)) {
7930
+ return;
7931
+ }
7932
+ arrayValue[j] = decodeURIComponent(innerArrayValue);
7933
+ }
7934
+ }
7935
+ }
7936
+ if (resultObj[varName2] !== void 0) {
7937
+ if (Array.isArray(resultObj[varName2])) {
7938
+ resultObj[varName2] = resultObj[varName2].concat(arrayValue);
7939
+ } else {
7940
+ resultObj[varName2] = [resultObj[varName2]].concat(arrayValue);
7941
+ }
7942
+ } else {
7943
+ if (arrayValue.length == 1 && !varSpec2.suffices["*"]) {
7944
+ resultObj[varName2] = arrayValue[0];
7945
+ } else {
7946
+ resultObj[varName2] = arrayValue;
7947
+ }
7948
+ }
7949
+ }
7950
+ } else {
7951
+ var arrayValue = varSpecs.length == 1 ? [stringValue] : stringValue.split(separator || ",");
7952
+ var specIndexMap = {};
7953
+ for (var i2 = 0; i2 < arrayValue.length; i2++) {
7954
+ var firstStarred = 0;
7955
+ for (; firstStarred < varSpecs.length - 1 && firstStarred < i2; firstStarred++) {
7956
+ if (varSpecs[firstStarred].suffices["*"]) {
7957
+ break;
7958
+ }
7959
+ }
7960
+ if (firstStarred == i2) {
7961
+ specIndexMap[i2] = i2;
7962
+ continue;
7963
+ } else {
7964
+ for (var lastStarred = varSpecs.length - 1; lastStarred > 0 && varSpecs.length - lastStarred < arrayValue.length - i2; lastStarred--) {
7965
+ if (varSpecs[lastStarred].suffices["*"]) {
7966
+ break;
7967
+ }
7968
+ }
7969
+ if (varSpecs.length - lastStarred == arrayValue.length - i2) {
7970
+ specIndexMap[i2] = lastStarred;
7971
+ continue;
7972
+ }
7973
+ }
7974
+ specIndexMap[i2] = firstStarred;
7975
+ }
7976
+ for (var i2 = 0; i2 < arrayValue.length; i2++) {
7977
+ var stringValue = arrayValue[i2];
7978
+ if (!stringValue && showVariables) {
7979
+ continue;
7980
+ }
7981
+ var innerArrayValue = stringValue.split(",");
7982
+ var hasEquals = false;
7983
+ if (showVariables) {
7984
+ var stringValue = innerArrayValue[0];
7985
+ var varName2 = stringValue.split("=", 1)[0];
7986
+ var stringValue = stringValue.substring(varName2.length + 1);
7987
+ innerArrayValue[0] = stringValue;
7988
+ var varSpec2 = varSpecMap[varName2] || varSpecs[0];
7989
+ } else {
7990
+ var varSpec2 = varSpecs[specIndexMap[i2]];
7991
+ var varName2 = varSpec2.name;
7992
+ }
7993
+ for (var j = 0; j < innerArrayValue.length; j++) {
7994
+ if (shouldEscape) {
7995
+ if (strict && !isPercentEncoded(innerArrayValue[j])) {
7996
+ return;
7997
+ }
7998
+ innerArrayValue[j] = decodeURIComponent(innerArrayValue[j]);
7999
+ }
8000
+ }
8001
+ if ((showVariables || varSpec2.suffices["*"]) && resultObj[varName2] !== void 0) {
8002
+ if (Array.isArray(resultObj[varName2])) {
8003
+ resultObj[varName2] = resultObj[varName2].concat(innerArrayValue);
8004
+ } else {
8005
+ resultObj[varName2] = [resultObj[varName2]].concat(innerArrayValue);
8006
+ }
8007
+ } else {
8008
+ if (innerArrayValue.length == 1 && !varSpec2.suffices["*"]) {
8009
+ resultObj[varName2] = innerArrayValue[0];
8010
+ } else {
8011
+ resultObj[varName2] = innerArrayValue;
8012
+ }
8013
+ }
8014
+ }
8015
+ }
8016
+ return 1;
8017
+ };
8018
+ return {
8019
+ varNames,
8020
+ prefix,
8021
+ substitution: subFunction,
8022
+ unSubstitution: guessFunction
8023
+ };
8024
+ }
8025
+ function UriTemplate(template) {
8026
+ if (!(this instanceof UriTemplate)) {
8027
+ return new UriTemplate(template);
8028
+ }
8029
+ var parts = template.split("{");
8030
+ var textParts = [parts.shift()];
8031
+ var prefixes = [];
8032
+ var substitutions = [];
8033
+ var unSubstitutions = [];
8034
+ var varNames = [];
8035
+ while (parts.length > 0) {
8036
+ var part = parts.shift();
8037
+ var spec = part.split("}")[0];
8038
+ var remainder = part.substring(spec.length + 1);
8039
+ var funcs = uriTemplateSubstitution(spec);
8040
+ substitutions.push(funcs.substitution);
8041
+ unSubstitutions.push(funcs.unSubstitution);
8042
+ prefixes.push(funcs.prefix);
8043
+ textParts.push(remainder);
8044
+ varNames = varNames.concat(funcs.varNames);
8045
+ }
8046
+ this.fill = function(valueFunction) {
8047
+ if (valueFunction && typeof valueFunction !== "function") {
8048
+ var value = valueFunction;
8049
+ valueFunction = function(varName) {
8050
+ return value[varName];
8051
+ };
8052
+ }
8053
+ var result = textParts[0];
8054
+ for (var i = 0; i < substitutions.length; i++) {
8055
+ var substitution = substitutions[i];
8056
+ result += substitution(valueFunction);
8057
+ result += textParts[i + 1];
8058
+ }
8059
+ return result;
8060
+ };
8061
+ this.fromUri = function(substituted, options2) {
8062
+ options2 = options2 || {};
8063
+ var result = {};
8064
+ for (var i = 0; i < textParts.length; i++) {
8065
+ var part2 = textParts[i];
8066
+ if (substituted.substring(0, part2.length) !== part2) {
8067
+ return;
8068
+ }
8069
+ substituted = substituted.substring(part2.length);
8070
+ if (i >= textParts.length - 1) {
8071
+ if (substituted == "") {
8072
+ break;
8073
+ } else {
8074
+ return;
8075
+ }
8076
+ }
8077
+ var prefix = prefixes[i];
8078
+ if (prefix && substituted.substring(0, prefix.length) !== prefix) {
8079
+ continue;
8080
+ }
8081
+ var nextPart = textParts[i + 1];
8082
+ var offset = i;
8083
+ while (true) {
8084
+ if (offset == textParts.length - 2) {
8085
+ var endPart = substituted.substring(substituted.length - nextPart.length);
8086
+ if (endPart !== nextPart) {
8087
+ return;
8088
+ }
8089
+ var stringValue = substituted.substring(0, substituted.length - nextPart.length);
8090
+ substituted = endPart;
8091
+ } else if (nextPart) {
8092
+ var nextPartPos = substituted.indexOf(nextPart);
8093
+ var stringValue = substituted.substring(0, nextPartPos);
8094
+ substituted = substituted.substring(nextPartPos);
8095
+ } else if (prefixes[offset + 1]) {
8096
+ var nextPartPos = substituted.indexOf(prefixes[offset + 1]);
8097
+ if (nextPartPos === -1) nextPartPos = substituted.length;
8098
+ var stringValue = substituted.substring(0, nextPartPos);
8099
+ substituted = substituted.substring(nextPartPos);
8100
+ } else if (textParts.length > offset + 2) {
8101
+ offset++;
8102
+ nextPart = textParts[offset + 1];
8103
+ continue;
8104
+ } else {
8105
+ var stringValue = substituted;
8106
+ substituted = "";
8107
+ }
8108
+ break;
8109
+ }
8110
+ if (!unSubstitutions[i](stringValue, result, options2.strict)) {
8111
+ return;
8112
+ }
8113
+ }
8114
+ return result;
8115
+ };
8116
+ this.varNames = varNames;
8117
+ this.template = template;
8118
+ }
8119
+ UriTemplate.prototype = {
8120
+ toString: function() {
8121
+ return this.template;
8122
+ },
8123
+ fillFromObject: function(obj) {
8124
+ return this.fill(obj);
8125
+ },
8126
+ test: function(uri, options2) {
8127
+ return !!this.fromUri(uri, options2);
8128
+ }
8129
+ };
8130
+ return UriTemplate;
8131
+ });
8132
+ }
8133
+ });
8134
+
8135
+ // package.json
8136
+ var require_package2 = __commonJS({
8137
+ "package.json"(exports, module) {
8138
+ module.exports = {
8139
+ name: "zotero-plugin",
8140
+ version: "4.0.0",
8141
+ description: "Zotero plugin builder",
8142
+ homepage: "https://github.com/retorquere/zotero-plugin/wiki",
8143
+ bin: {
8144
+ "zotero-plugin-release": "bin/release.js",
8145
+ "zotero-plugin-zipup": "bin/zipup.js",
8146
+ "zotero-plugin-link": "bin/link.js",
8147
+ "issue-branches": "bin/branches.js",
8148
+ "zotero-start": "bin/start.py",
8149
+ "fetch-zotero-log": "bin/fetch-zotero-log.py"
8150
+ },
8151
+ author: {
8152
+ name: "Emiliano Heyns",
8153
+ email: "Emiliano.Heyns@iris-advies.com"
8154
+ },
8155
+ scripts: {
8156
+ preversion: "npm test",
8157
+ postversion: "git push --follow-tags",
8158
+ test: "dprint fmt *.ts */*.ts && dprint check *.ts */*.ts && npm run build",
8159
+ build: "tsc && ./bundle.mjs && chmod +x bin/*.js",
8160
+ pack: "npm test && npm pack",
8161
+ prepublishOnly: "npm install && npm run build",
8162
+ ncu: "ncu -u && npm i && git add package.json package-lock.json && git commit -m ncu"
8163
+ },
8164
+ directories: {
8165
+ test: "test"
8166
+ },
8167
+ dependencies: {
8168
+ "@octokit/rest": "^21.0.2",
8169
+ "@rgrove/parse-xml": "^4.2.0",
8170
+ "@types/node": "^22.10.4",
8171
+ "@xmldom/xmldom": "^0.9.6",
8172
+ ajv: "^8.17.1",
8173
+ "ajv-keywords": "^5.1.0",
8174
+ archiver: "^7.0.1",
8175
+ clp: "^4.0.12",
8176
+ commander: "^13.0.0",
8177
+ dotenv: "^16.4.7",
8178
+ dprint: "^0.48.0",
8179
+ ejs: "^3.1.10",
8180
+ "fs-extra": "^11.2.0",
8181
+ glob: "^11.0.0",
8182
+ jsesc: "^3.1.0",
8183
+ lodash: "^4.17.21",
8184
+ moment: "^2.30.1",
8185
+ peggy: "^4.2.0",
8186
+ "properties-reader": "^2.3.0",
8187
+ pug: "^3.0.3",
8188
+ rimraf: "^6.0.1",
8189
+ "shell-quote": "^1.8.2",
8190
+ shelljs: "^0.8.5",
8191
+ "string-to-arraybuffer": "^1.0.2",
8192
+ "ts-node": "^10.9.2",
8193
+ tslib: "^2.8.1",
8194
+ typescript: "^5.7.2",
8195
+ "uri-templates": "^0.2.0",
8196
+ uzip: "^0.20201231.0",
8197
+ "xml-parser": "^1.2.1",
8198
+ xpath: "^0.0.34"
8199
+ },
8200
+ repository: {
8201
+ type: "git",
8202
+ url: "git+https://github.com/retorquere/zotero-plugin.git"
8203
+ },
8204
+ license: "ISC",
8205
+ files: [
8206
+ "bin/branches.d.ts",
8207
+ "bin/branches.js",
8208
+ "bin/link.d.ts",
8209
+ "bin/link.js",
8210
+ "bin/release.d.ts",
8211
+ "bin/release.js",
8212
+ "bin/zipup.d.ts",
8213
+ "bin/zipup.js",
8214
+ "bin/start.py",
8215
+ "bin/fetch-zotero-log.py",
8216
+ "continuous-integration.d.ts",
8217
+ "continuous-integration.js",
8218
+ "copy-assets.d.ts",
8219
+ "copy-assets.js",
8220
+ "error-report.pug",
8221
+ "install.rdf.pug",
8222
+ "loader/json.d.ts",
8223
+ "loader/json.js",
8224
+ "loader/peggy.d.ts",
8225
+ "loader/peggy.js",
8226
+ "loader/trace.d.ts",
8227
+ "loader/wrap.d.ts",
8228
+ "loader/wrap.js",
8229
+ "make-dirs.d.ts",
8230
+ "make-dirs.js",
8231
+ "package.json",
8232
+ "rdf.d.ts",
8233
+ "rdf.js",
8234
+ "root.d.ts",
8235
+ "root.js",
8236
+ "update.rdf.pug",
8237
+ "version.d.ts",
8238
+ "version.js",
8239
+ "debug-log.js",
8240
+ "debug-log.d.ts",
8241
+ "create-element.js",
8242
+ "create-element.d.ts",
8243
+ "logger.js",
8244
+ "logger.d.ts"
8245
+ ],
8246
+ bugs: {
8247
+ url: "https://github.com/retorquere/zotero-plugin/issues"
8248
+ },
8249
+ devDependencies: {
8250
+ esbuild: "^0.24.2"
8251
+ }
8252
+ };
8253
+ }
8254
+ });
8255
+
4408
8256
  // node_modules/dotenv/config.js
4409
8257
  (function() {
4410
8258
  require_main().config(
@@ -4418,9 +8266,81 @@
4418
8266
 
4419
8267
  // bin/release.ts
4420
8268
  var import_child_process = __require("child_process");
8269
+
8270
+ // node_modules/commander/esm.mjs
8271
+ var import_index = __toESM(require_commander(), 1);
8272
+ var {
8273
+ program,
8274
+ createCommand,
8275
+ createArgument,
8276
+ createOption,
8277
+ CommanderError,
8278
+ InvalidArgumentError,
8279
+ InvalidOptionArgumentError,
8280
+ // deprecated old name
8281
+ Command,
8282
+ Argument,
8283
+ Option,
8284
+ Help
8285
+ } = import_index.default;
8286
+
8287
+ // bin/release.ts
4421
8288
  var fs2 = __toESM(__require("fs"));
4422
8289
  var import_moment = __toESM(require_moment());
4423
8290
  var path2 = __toESM(__require("path"));
8291
+ var import_uri_templates = __toESM(require_uri_templates());
8292
+
8293
+ // continuous-integration.ts
8294
+ var child_process = __toESM(__require("child_process"));
8295
+ var ContinuousIntegrationSingleton = class {
8296
+ constructor() {
8297
+ this.service = "";
8298
+ this.tag = "";
8299
+ this.commit_message = "";
8300
+ this.branch = "";
8301
+ this.pull_request = false;
8302
+ this.issue = "";
8303
+ for (const [id, name] of Object.entries({ CIRCLECI: "Circle", TRAVIS: "Travis", SEMAPHORE: "Semaphore", GITHUB_ACTIONS: "GitHub" })) {
8304
+ if (process.env[id] === "true") this.service = name;
8305
+ }
8306
+ switch (this.service) {
8307
+ case "Circle":
8308
+ this.build_number = this.parseInt(process.env.CIRCLE_BUILD_NUM);
8309
+ try {
8310
+ this.tag = child_process.execSync(`git describe --exact-match ${process.env.CIRCLE_SHA1}`, { stdio: "pipe" }).toString().trim();
8311
+ } catch (err) {
8312
+ this.tag = null;
8313
+ }
8314
+ this.commit_message = child_process.execSync(`git log --format=%B -n 1 ${process.env.CIRCLE_SHA1}`).toString().trim();
8315
+ this.branch = process.env.CIRCLE_BRANCH;
8316
+ this.pull_request = !!process.env.CIRCLE_PULL_REQUEST;
8317
+ break;
8318
+ case "GitHub":
8319
+ this.build_number = this.parseInt(process.env.GITHUB_RUN_NUMBER);
8320
+ this.commit_message = child_process.execSync(`git log --format=%B -n 1 ${process.env.GITHUB_SHA}`).toString().trim();
8321
+ this.pull_request = process.env.GITHUB_EVENT_NAME.startsWith("pull-request");
8322
+ if (process.env.GITHUB_HEAD_REF) {
8323
+ this.branch = process.env.GITHUB_HEAD_REF.split("/").pop();
8324
+ } else if (process.env.GITHUB_REF.startsWith("refs/tags/")) {
8325
+ this.tag = process.env.GITHUB_REF.split("/").pop();
8326
+ } else if (process.env.GITHUB_REF.startsWith("refs/heads/")) {
8327
+ this.branch = process.env.GITHUB_REF.split("/").pop();
8328
+ }
8329
+ this.branch = this.branch || "";
8330
+ this.issue = this.branch.match(/^gh-([0-9]+)$/)?.[1] || "";
8331
+ break;
8332
+ default:
8333
+ if (process.env.CI === "true") throw new Error(`Unexpected CI service ${this.service}`);
8334
+ }
8335
+ }
8336
+ parseInt(n) {
8337
+ if (typeof n === "number") return n;
8338
+ const int = parseInt(n);
8339
+ if (isNaN(int)) throw new Error(`${n} is not an integer`);
8340
+ return int;
8341
+ }
8342
+ };
8343
+ var ContinuousIntegration = new ContinuousIntegrationSingleton();
4424
8344
 
4425
8345
  // node_modules/@octokit/rest/node_modules/universal-user-agent/index.js
4426
8346
  function getUserAgent() {
@@ -4434,24 +8354,24 @@
4434
8354
  }
4435
8355
 
4436
8356
  // node_modules/@octokit/rest/node_modules/before-after-hook/lib/register.js
4437
- function register(state, name, method, options) {
8357
+ function register(state, name, method, options2) {
4438
8358
  if (typeof method !== "function") {
4439
8359
  throw new Error("method for before hook must be a function");
4440
8360
  }
4441
- if (!options) {
4442
- options = {};
8361
+ if (!options2) {
8362
+ options2 = {};
4443
8363
  }
4444
8364
  if (Array.isArray(name)) {
4445
8365
  return name.reverse().reduce((callback, name2) => {
4446
- return register.bind(null, state, name2, callback, options);
8366
+ return register.bind(null, state, name2, callback, options2);
4447
8367
  }, method)();
4448
8368
  }
4449
8369
  return Promise.resolve().then(() => {
4450
8370
  if (!state.registry[name]) {
4451
- return method(options);
8371
+ return method(options2);
4452
8372
  }
4453
8373
  return state.registry[name].reduce((method2, registered) => {
4454
- return registered.hook.bind(null, method2, options);
8374
+ return registered.hook.bind(null, method2, options2);
4455
8375
  }, method)();
4456
8376
  });
4457
8377
  }
@@ -4463,25 +8383,25 @@
4463
8383
  state.registry[name] = [];
4464
8384
  }
4465
8385
  if (kind === "before") {
4466
- hook2 = (method, options) => {
4467
- return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options));
8386
+ hook2 = (method, options2) => {
8387
+ return Promise.resolve().then(orig.bind(null, options2)).then(method.bind(null, options2));
4468
8388
  };
4469
8389
  }
4470
8390
  if (kind === "after") {
4471
- hook2 = (method, options) => {
8391
+ hook2 = (method, options2) => {
4472
8392
  let result;
4473
- return Promise.resolve().then(method.bind(null, options)).then((result_) => {
8393
+ return Promise.resolve().then(method.bind(null, options2)).then((result_) => {
4474
8394
  result = result_;
4475
- return orig(result, options);
8395
+ return orig(result, options2);
4476
8396
  }).then(() => {
4477
8397
  return result;
4478
8398
  });
4479
8399
  };
4480
8400
  }
4481
8401
  if (kind === "error") {
4482
- hook2 = (method, options) => {
4483
- return Promise.resolve().then(method.bind(null, options)).catch((error) => {
4484
- return orig(error, options);
8402
+ hook2 = (method, options2) => {
8403
+ return Promise.resolve().then(method.bind(null, options2)).catch((error) => {
8404
+ return orig(error, options2);
4485
8405
  });
4486
8406
  };
4487
8407
  }
@@ -4573,16 +8493,16 @@
4573
8493
  const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
4574
8494
  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
4575
8495
  }
4576
- function mergeDeep(defaults, options) {
8496
+ function mergeDeep(defaults, options2) {
4577
8497
  const result = Object.assign({}, defaults);
4578
- Object.keys(options).forEach((key) => {
4579
- if (isPlainObject(options[key])) {
8498
+ Object.keys(options2).forEach((key) => {
8499
+ if (isPlainObject(options2[key])) {
4580
8500
  if (!(key in defaults))
4581
- Object.assign(result, { [key]: options[key] });
8501
+ Object.assign(result, { [key]: options2[key] });
4582
8502
  else
4583
- result[key] = mergeDeep(defaults[key], options[key]);
8503
+ result[key] = mergeDeep(defaults[key], options2[key]);
4584
8504
  } else {
4585
- Object.assign(result, { [key]: options[key] });
8505
+ Object.assign(result, { [key]: options2[key] });
4586
8506
  }
4587
8507
  });
4588
8508
  return result;
@@ -4595,18 +8515,18 @@
4595
8515
  }
4596
8516
  return obj;
4597
8517
  }
4598
- function merge(defaults, route, options) {
8518
+ function merge(defaults, route, options2) {
4599
8519
  if (typeof route === "string") {
4600
8520
  let [method, url] = route.split(" ");
4601
- options = Object.assign(url ? { method, url } : { url: method }, options);
8521
+ options2 = Object.assign(url ? { method, url } : { url: method }, options2);
4602
8522
  } else {
4603
- options = Object.assign({}, route);
8523
+ options2 = Object.assign({}, route);
4604
8524
  }
4605
- options.headers = lowercaseKeys(options.headers);
4606
- removeUndefinedProperties(options);
4607
- removeUndefinedProperties(options.headers);
4608
- const mergedOptions = mergeDeep(defaults || {}, options);
4609
- if (options.url === "/graphql") {
8525
+ options2.headers = lowercaseKeys(options2.headers);
8526
+ removeUndefinedProperties(options2);
8527
+ removeUndefinedProperties(options2.headers);
8528
+ const mergedOptions = mergeDeep(defaults || {}, options2);
8529
+ if (options2.url === "/graphql") {
4610
8530
  if (defaults && defaults.mediaType.previews?.length) {
4611
8531
  mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(
4612
8532
  (preview) => !mergedOptions.mediaType.previews.includes(preview)
@@ -4779,12 +8699,12 @@
4779
8699
  return template.replace(/\/$/, "");
4780
8700
  }
4781
8701
  }
4782
- function parse(options) {
4783
- let method = options.method.toUpperCase();
4784
- let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
4785
- let headers = Object.assign({}, options.headers);
8702
+ function parse(options2) {
8703
+ let method = options2.method.toUpperCase();
8704
+ let url = (options2.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
8705
+ let headers = Object.assign({}, options2.headers);
4786
8706
  let body;
4787
- let parameters = omit(options, [
8707
+ let parameters = omit(options2, [
4788
8708
  "method",
4789
8709
  "baseUrl",
4790
8710
  "url",
@@ -4795,25 +8715,25 @@
4795
8715
  const urlVariableNames = extractUrlVariableNames(url);
4796
8716
  url = parseUrl(url).expand(parameters);
4797
8717
  if (!/^http/.test(url)) {
4798
- url = options.baseUrl + url;
8718
+ url = options2.baseUrl + url;
4799
8719
  }
4800
- const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl");
8720
+ const omittedParameters = Object.keys(options2).filter((option) => urlVariableNames.includes(option)).concat("baseUrl");
4801
8721
  const remainingParameters = omit(parameters, omittedParameters);
4802
8722
  const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
4803
8723
  if (!isBinaryRequest) {
4804
- if (options.mediaType.format) {
8724
+ if (options2.mediaType.format) {
4805
8725
  headers.accept = headers.accept.split(/,/).map(
4806
8726
  (format) => format.replace(
4807
8727
  /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,
4808
- `application/vnd$1$2.${options.mediaType.format}`
8728
+ `application/vnd$1$2.${options2.mediaType.format}`
4809
8729
  )
4810
8730
  ).join(",");
4811
8731
  }
4812
8732
  if (url.endsWith("/graphql")) {
4813
- if (options.mediaType.previews?.length) {
8733
+ if (options2.mediaType.previews?.length) {
4814
8734
  const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
4815
- headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {
4816
- const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
8735
+ headers.accept = previewsFromAcceptHeader.concat(options2.mediaType.previews).map((preview) => {
8736
+ const format = options2.mediaType.format ? `.${options2.mediaType.format}` : "+json";
4817
8737
  return `application/vnd.github.${preview}-preview${format}`;
4818
8738
  }).join(",");
4819
8739
  }
@@ -4839,11 +8759,11 @@
4839
8759
  return Object.assign(
4840
8760
  { method, url, headers },
4841
8761
  typeof body !== "undefined" ? { body } : null,
4842
- options.request ? { request: options.request } : null
8762
+ options2.request ? { request: options2.request } : null
4843
8763
  );
4844
8764
  }
4845
- function endpointWithDefaults(defaults, route, options) {
4846
- return parse(merge(defaults, route, options));
8765
+ function endpointWithDefaults(defaults, route, options2) {
8766
+ return parse(merge(defaults, route, options2));
4847
8767
  }
4848
8768
  function withDefaults(oldDefaults, newDefaults) {
4849
8769
  const DEFAULTS2 = merge(oldDefaults, newDefaults);
@@ -4872,20 +8792,20 @@
4872
8792
  * Response object if a response was received
4873
8793
  */
4874
8794
  response;
4875
- constructor(message, statusCode, options) {
8795
+ constructor(message, statusCode, options2) {
4876
8796
  super(message);
4877
8797
  this.name = "HttpError";
4878
8798
  this.status = Number.parseInt(statusCode);
4879
8799
  if (Number.isNaN(this.status)) {
4880
8800
  this.status = 0;
4881
8801
  }
4882
- if ("response" in options) {
4883
- this.response = options.response;
8802
+ if ("response" in options2) {
8803
+ this.response = options2.response;
4884
8804
  }
4885
- const requestCopy = Object.assign({}, options.request);
4886
- if (options.request.headers.authorization) {
4887
- requestCopy.headers = Object.assign({}, options.request.headers, {
4888
- authorization: options.request.headers.authorization.replace(
8805
+ const requestCopy = Object.assign({}, options2.request);
8806
+ if (options2.request.headers.authorization) {
8807
+ requestCopy.headers = Object.assign({}, options2.request.headers, {
8808
+ authorization: options2.request.headers.authorization.replace(
4889
8809
  / .*$/,
4890
8810
  " [REDACTED]"
4891
8811
  )
@@ -5090,14 +9010,14 @@
5090
9010
  ];
5091
9011
  var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
5092
9012
  var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
5093
- function graphql(request2, query, options) {
5094
- if (options) {
5095
- if (typeof query === "string" && "query" in options) {
9013
+ function graphql(request2, query, options2) {
9014
+ if (options2) {
9015
+ if (typeof query === "string" && "query" in options2) {
5096
9016
  return Promise.reject(
5097
9017
  new Error(`[@octokit/graphql] "query" cannot be used as variable name`)
5098
9018
  );
5099
9019
  }
5100
- for (const key in options) {
9020
+ for (const key in options2) {
5101
9021
  if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key))
5102
9022
  continue;
5103
9023
  return Promise.reject(
@@ -5107,7 +9027,7 @@
5107
9027
  );
5108
9028
  }
5109
9029
  }
5110
- const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
9030
+ const parsedOptions = typeof query === "string" ? Object.assign({ query }, options2) : query;
5111
9031
  const requestOptions = Object.keys(
5112
9032
  parsedOptions
5113
9033
  ).reduce((result, key) => {
@@ -5142,8 +9062,8 @@
5142
9062
  }
5143
9063
  function withDefaults3(request2, newDefaults) {
5144
9064
  const newRequest = request2.defaults(newDefaults);
5145
- const newApi = (query, options) => {
5146
- return graphql(newRequest, query, options);
9065
+ const newApi = (query, options2) => {
9066
+ return graphql(newRequest, query, options2);
5147
9067
  };
5148
9068
  return Object.assign(newApi, {
5149
9069
  defaults: withDefaults3.bind(null, newRequest),
@@ -5222,18 +9142,18 @@
5222
9142
  static defaults(defaults) {
5223
9143
  const OctokitWithDefaults = class extends this {
5224
9144
  constructor(...args) {
5225
- const options = args[0] || {};
9145
+ const options2 = args[0] || {};
5226
9146
  if (typeof defaults === "function") {
5227
- super(defaults(options));
9147
+ super(defaults(options2));
5228
9148
  return;
5229
9149
  }
5230
9150
  super(
5231
9151
  Object.assign(
5232
9152
  {},
5233
9153
  defaults,
5234
- options,
5235
- options.userAgent && defaults.userAgent ? {
5236
- userAgent: `${options.userAgent} ${defaults.userAgent}`
9154
+ options2,
9155
+ options2.userAgent && defaults.userAgent ? {
9156
+ userAgent: `${options2.userAgent} ${defaults.userAgent}`
5237
9157
  } : null
5238
9158
  )
5239
9159
  );
@@ -5257,12 +9177,12 @@
5257
9177
  };
5258
9178
  return NewOctokit;
5259
9179
  }
5260
- constructor(options = {}) {
9180
+ constructor(options2 = {}) {
5261
9181
  const hook2 = new before_after_hook_default.Collection();
5262
9182
  const requestDefaults = {
5263
9183
  baseUrl: request.endpoint.DEFAULTS.baseUrl,
5264
9184
  headers: {},
5265
- request: Object.assign({}, options.request, {
9185
+ request: Object.assign({}, options2.request, {
5266
9186
  // @ts-ignore internal usage only, no need to type
5267
9187
  hook: hook2.bind(null, "request")
5268
9188
  }),
@@ -5271,15 +9191,15 @@
5271
9191
  format: ""
5272
9192
  }
5273
9193
  };
5274
- requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail;
5275
- if (options.baseUrl) {
5276
- requestDefaults.baseUrl = options.baseUrl;
9194
+ requestDefaults.headers["user-agent"] = options2.userAgent ? `${options2.userAgent} ${userAgentTrail}` : userAgentTrail;
9195
+ if (options2.baseUrl) {
9196
+ requestDefaults.baseUrl = options2.baseUrl;
5277
9197
  }
5278
- if (options.previews) {
5279
- requestDefaults.mediaType.previews = options.previews;
9198
+ if (options2.previews) {
9199
+ requestDefaults.mediaType.previews = options2.previews;
5280
9200
  }
5281
- if (options.timeZone) {
5282
- requestDefaults.headers["time-zone"] = options.timeZone;
9201
+ if (options2.timeZone) {
9202
+ requestDefaults.headers["time-zone"] = options2.timeZone;
5283
9203
  }
5284
9204
  this.request = request.defaults(requestDefaults);
5285
9205
  this.graphql = withCustomRequest(this.request).defaults(requestDefaults);
@@ -5290,21 +9210,21 @@
5290
9210
  warn: consoleWarn,
5291
9211
  error: consoleError
5292
9212
  },
5293
- options.log
9213
+ options2.log
5294
9214
  );
5295
9215
  this.hook = hook2;
5296
- if (!options.authStrategy) {
5297
- if (!options.auth) {
9216
+ if (!options2.authStrategy) {
9217
+ if (!options2.auth) {
5298
9218
  this.auth = async () => ({
5299
9219
  type: "unauthenticated"
5300
9220
  });
5301
9221
  } else {
5302
- const auth2 = createTokenAuth(options.auth);
9222
+ const auth2 = createTokenAuth(options2.auth);
5303
9223
  hook2.wrap("request", auth2.hook);
5304
9224
  this.auth = auth2;
5305
9225
  }
5306
9226
  } else {
5307
- const { authStrategy, ...otherOptions } = options;
9227
+ const { authStrategy, ...otherOptions } = options2;
5308
9228
  const auth2 = authStrategy(
5309
9229
  Object.assign(
5310
9230
  {
@@ -5318,7 +9238,7 @@
5318
9238
  octokit: this,
5319
9239
  octokitOptions: otherOptions
5320
9240
  },
5321
- options.auth
9241
+ options2.auth
5322
9242
  )
5323
9243
  );
5324
9244
  hook2.wrap("request", auth2.hook);
@@ -5326,7 +9246,7 @@
5326
9246
  }
5327
9247
  const classConstructor = this.constructor;
5328
9248
  for (let i = 0; i < classConstructor.plugins.length; ++i) {
5329
- Object.assign(this, classConstructor.plugins[i](this, options));
9249
+ Object.assign(this, classConstructor.plugins[i](this, options2));
5330
9250
  }
5331
9251
  }
5332
9252
  // assigned during constructor
@@ -5343,12 +9263,12 @@
5343
9263
 
5344
9264
  // node_modules/@octokit/rest/node_modules/@octokit/plugin-request-log/dist-src/index.js
5345
9265
  function requestLog(octokit2) {
5346
- octokit2.hook.wrap("request", (request2, options) => {
5347
- octokit2.log.debug("request", options);
9266
+ octokit2.hook.wrap("request", (request2, options2) => {
9267
+ octokit2.log.debug("request", options2);
5348
9268
  const start = Date.now();
5349
- const requestOptions = octokit2.request.endpoint.parse(options);
5350
- const path3 = requestOptions.url.replace(options.baseUrl, "");
5351
- return request2(options).then((response) => {
9269
+ const requestOptions = octokit2.request.endpoint.parse(options2);
9270
+ const path3 = requestOptions.url.replace(options2.baseUrl, "");
9271
+ return request2(options2).then((response) => {
5352
9272
  const requestId = response.headers["x-github-request-id"];
5353
9273
  octokit2.log.info(
5354
9274
  `${requestOptions.method} ${path3} - ${response.status} with id ${requestId} in ${Date.now() - start}ms`
@@ -5396,11 +9316,11 @@
5396
9316
  return response;
5397
9317
  }
5398
9318
  function iterator(octokit2, route, parameters) {
5399
- const options = typeof route === "function" ? route.endpoint(parameters) : octokit2.request.endpoint(route, parameters);
9319
+ const options2 = typeof route === "function" ? route.endpoint(parameters) : octokit2.request.endpoint(route, parameters);
5400
9320
  const requestMethod = typeof route === "function" ? route : octokit2.request;
5401
- const method = options.method;
5402
- const headers = options.headers;
5403
- let url = options.url;
9321
+ const method = options2.method;
9322
+ const headers = options2.headers;
9323
+ let url = options2.url;
5404
9324
  return {
5405
9325
  [Symbol.asyncIterator]: () => ({
5406
9326
  async next() {
@@ -7495,13 +11415,13 @@
7495
11415
  function decorate(octokit2, scope, methodName, defaults, decorations) {
7496
11416
  const requestWithDefaults = octokit2.request.defaults(defaults);
7497
11417
  function withDecorations(...args) {
7498
- let options = requestWithDefaults.endpoint.merge(...args);
11418
+ let options2 = requestWithDefaults.endpoint.merge(...args);
7499
11419
  if (decorations.mapToData) {
7500
- options = Object.assign({}, options, {
7501
- data: options[decorations.mapToData],
11420
+ options2 = Object.assign({}, options2, {
11421
+ data: options2[decorations.mapToData],
7502
11422
  [decorations.mapToData]: void 0
7503
11423
  });
7504
- return requestWithDefaults(options);
11424
+ return requestWithDefaults(options2);
7505
11425
  }
7506
11426
  if (decorations.renamed) {
7507
11427
  const [newScope, newMethodName] = decorations.renamed;
@@ -7513,21 +11433,21 @@
7513
11433
  octokit2.log.warn(decorations.deprecated);
7514
11434
  }
7515
11435
  if (decorations.renamedParameters) {
7516
- const options2 = requestWithDefaults.endpoint.merge(...args);
11436
+ const options22 = requestWithDefaults.endpoint.merge(...args);
7517
11437
  for (const [name, alias] of Object.entries(
7518
11438
  decorations.renamedParameters
7519
11439
  )) {
7520
- if (name in options2) {
11440
+ if (name in options22) {
7521
11441
  octokit2.log.warn(
7522
11442
  `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`
7523
11443
  );
7524
- if (!(alias in options2)) {
7525
- options2[alias] = options2[name];
11444
+ if (!(alias in options22)) {
11445
+ options22[alias] = options22[name];
7526
11446
  }
7527
- delete options2[name];
11447
+ delete options22[name];
7528
11448
  }
7529
11449
  }
7530
- return requestWithDefaults(options2);
11450
+ return requestWithDefaults(options22);
7531
11451
  }
7532
11452
  return requestWithDefaults(...args);
7533
11453
  }
@@ -7559,58 +11479,6 @@
7559
11479
  }
7560
11480
  );
7561
11481
 
7562
- // continuous-integration.ts
7563
- var child_process = __toESM(__require("child_process"));
7564
- var ContinuousIntegrationSingleton = class {
7565
- constructor() {
7566
- this.service = "";
7567
- this.tag = "";
7568
- this.commit_message = "";
7569
- this.branch = "";
7570
- this.pull_request = false;
7571
- this.issue = "";
7572
- for (const [id, name] of Object.entries({ CIRCLECI: "Circle", TRAVIS: "Travis", SEMAPHORE: "Semaphore", GITHUB_ACTIONS: "GitHub" })) {
7573
- if (process.env[id] === "true") this.service = name;
7574
- }
7575
- switch (this.service) {
7576
- case "Circle":
7577
- this.build_number = this.parseInt(process.env.CIRCLE_BUILD_NUM);
7578
- try {
7579
- this.tag = child_process.execSync(`git describe --exact-match ${process.env.CIRCLE_SHA1}`, { stdio: "pipe" }).toString().trim();
7580
- } catch (err) {
7581
- this.tag = null;
7582
- }
7583
- this.commit_message = child_process.execSync(`git log --format=%B -n 1 ${process.env.CIRCLE_SHA1}`).toString().trim();
7584
- this.branch = process.env.CIRCLE_BRANCH;
7585
- this.pull_request = !!process.env.CIRCLE_PULL_REQUEST;
7586
- break;
7587
- case "GitHub":
7588
- this.build_number = this.parseInt(process.env.GITHUB_RUN_NUMBER);
7589
- this.commit_message = child_process.execSync(`git log --format=%B -n 1 ${process.env.GITHUB_SHA}`).toString().trim();
7590
- this.pull_request = process.env.GITHUB_EVENT_NAME.startsWith("pull-request");
7591
- if (process.env.GITHUB_HEAD_REF) {
7592
- this.branch = process.env.GITHUB_HEAD_REF.split("/").pop();
7593
- } else if (process.env.GITHUB_REF.startsWith("refs/tags/")) {
7594
- this.tag = process.env.GITHUB_REF.split("/").pop();
7595
- } else if (process.env.GITHUB_REF.startsWith("refs/heads/")) {
7596
- this.branch = process.env.GITHUB_REF.split("/").pop();
7597
- }
7598
- this.branch = this.branch || "";
7599
- this.issue = this.branch.match(/^gh-([0-9]+)$/)?.[1] || "";
7600
- break;
7601
- default:
7602
- if (process.env.CI === "true") throw new Error(`Unexpected CI service ${this.service}`);
7603
- }
7604
- }
7605
- parseInt(n) {
7606
- if (typeof n === "number") return n;
7607
- const int = parseInt(n);
7608
- if (isNaN(int)) throw new Error(`${n} is not an integer`);
7609
- return int;
7610
- }
7611
- };
7612
- var ContinuousIntegration = new ContinuousIntegrationSingleton();
7613
-
7614
11482
  // root.ts
7615
11483
  var root_default = process.cwd();
7616
11484
 
@@ -7641,28 +11509,30 @@
7641
11509
  process.on("unhandledRejection", (up) => {
7642
11510
  throw up;
7643
11511
  });
11512
+ program.version(require_package2().version).option("-r, --release-message <value>", "add message to github release").option("-x, --xpi", "xpi filename template", "{name}-{version}.xpi").option("-d, --dry-run", "dry run", !ContinuousIntegration.service).option("-p, --pre-release", "release is a pre-release").parse(process.argv);
11513
+ var options = program.opts();
11514
+ if (options.releaseMessage?.startsWith("@")) options.releaseMessage = fs2.readFileSync(options.releaseMessage.substring(1), "utf-8");
7644
11515
  var octokit = new Octokit2({ auth: `token ${process.env.GITHUB_TOKEN}` });
7645
11516
  var pkg = __require(path2.join(root_default, "package.json"));
7646
11517
  var [, owner, repo] = pkg.repository.url.match(/:\/\/github.com\/([^/]+)\/([^.]+)\.git$/);
7647
- var xpi = `${pkg.name}-${version_default}.xpi`;
7648
- var PRERELEASE = false;
11518
+ var xpi = (0, import_uri_templates.default)(options.xpi).fill({ ...pkg, version: version_default });
7649
11519
  var EXPIRE_BUILDS = (0, import_moment.default)().subtract(7, "days").toDate().toISOString();
7650
11520
  function bail(msg, status = 1) {
7651
11521
  console.log(msg);
7652
11522
  process.exit(status);
7653
11523
  }
7654
- var dryRun = !ContinuousIntegration.service;
7655
- if (dryRun) {
11524
+ if (options.dryRun) {
7656
11525
  console.log("Not running on CI service, switching to dry-run mode");
7657
11526
  ContinuousIntegration.branch = (0, import_child_process.execSync)("git rev-parse --abbrev-ref HEAD", { encoding: "utf8" }).trim();
7658
11527
  }
7659
11528
  function report(msg) {
7660
- console.log(`${dryRun ? "dry-run: " : ""}${msg}`);
11529
+ console.log(`${options.dryRun ? "dry-run: " : ""}${msg}`);
7661
11530
  }
7662
11531
  if (ContinuousIntegration.pull_request) bail("Not releasing pull requests", 0);
7663
11532
  if (ContinuousIntegration.tag) {
7664
11533
  if (`v${pkg.version}` !== ContinuousIntegration.tag) bail(`Building tag ${ContinuousIntegration.tag}, but package version is ${pkg.version}`);
7665
- if (ContinuousIntegration.branch && ContinuousIntegration.branch !== "master" && ContinuousIntegration.branch !== "main") bail(`Building tag ${ContinuousIntegration.tag}, but branch is ${ContinuousIntegration.branch}`);
11534
+ const releaseBranches = ["main", "master"].concat(pkg.xpi.releaseBranches || []);
11535
+ if (ContinuousIntegration.branch && !releaseBranches.includes(ContinuousIntegration.branch)) bail(`Building tag ${ContinuousIntegration.tag}, but branch is ${ContinuousIntegration.branch}`);
7666
11536
  }
7667
11537
  var tags = /* @__PURE__ */ new Set();
7668
11538
  for (let regex = /(?:^|\s)(?:#)([a-zA-Z\d]+)/gm, tag; tag = regex.exec(ContinuousIntegration.commit_message); ) {
@@ -7678,7 +11548,7 @@
7678
11548
  let build;
7679
11549
  let reason = "";
7680
11550
  if (ContinuousIntegration.tag) {
7681
- build = `${PRERELEASE ? "pre-" : ""}release ${ContinuousIntegration.tag}`;
11551
+ build = `${options.preRelease ? "pre-" : ""}release ${ContinuousIntegration.tag}`;
7682
11552
  } else {
7683
11553
  build = `test build ${version_default}`;
7684
11554
  }
@@ -7691,7 +11561,7 @@ This update may name other issues, but the build just dropped here is for you; i
7691
11561
  }
7692
11562
  const body = `:robot: this is your friendly neighborhood build bot announcing ${link}${reason}`;
7693
11563
  report(body);
7694
- if (dryRun) return;
11564
+ if (options.dryRun) return;
7695
11565
  try {
7696
11566
  const locked = (await octokit.issues.get({ owner, repo, issue_number })).data.locked;
7697
11567
  if (locked) await octokit.issues.unlock({ owner, repo, issue_number });
@@ -7705,7 +11575,7 @@ This update may name other issues, but the build just dropped here is for you; i
7705
11575
  }
7706
11576
  async function uploadAsset(release, asset, contentType) {
7707
11577
  report(`uploading ${path2.basename(asset)} to ${release.data.tag_name}`);
7708
- if (dryRun) return;
11578
+ if (options.dryRun) return;
7709
11579
  const name = path2.basename(asset);
7710
11580
  const exists = (await octokit.repos.listReleaseAssets({ owner, repo, release_id: release.data.id })).data.find((a) => a.name === name);
7711
11581
  if (exists) {
@@ -7748,14 +11618,19 @@ This update may name other issues, but the build just dropped here is for you; i
7748
11618
  async function update_rdf(releases_tag) {
7749
11619
  const release = await getRelease(releases_tag, false);
7750
11620
  const assets = (await octokit.repos.listReleaseAssets({ owner, repo, release_id: release.data.id })).data;
11621
+ const updates = {
11622
+ "update.rdf": !pkg.xpi.update || pkg.xpi.update.rdf ? "application/rdf+xml" : "",
11623
+ "updates.json": !pkg.xpi.update || pkg.xpi.update.json ? "application/json" : ""
11624
+ };
7751
11625
  for (const asset of assets) {
7752
- if (asset.name === "update.rdf" || asset.name === "updates.json") {
11626
+ if (asset.name in updates && updates[asset.name]) {
7753
11627
  report(`removing ${asset.name} from ${release.data.tag_name}`);
7754
- if (!dryRun) await octokit.repos.deleteReleaseAsset({ owner, repo, asset_id: asset.id });
11628
+ if (!options.dryRun) await octokit.repos.deleteReleaseAsset({ owner, repo, asset_id: asset.id });
7755
11629
  }
7756
11630
  }
7757
- await uploadAsset(release, path2.join(root_default, "gen/update.rdf"), "application/rdf+xml");
7758
- await uploadAsset(release, path2.join(root_default, "gen/updates.json"), "application/json");
11631
+ for (const [pointer, mimetype] of Object.entries(updates)) {
11632
+ if (mimetype) await uploadAsset(release, path2.join(root_default, `gen/${pointer}`), mimetype);
11633
+ }
7759
11634
  }
7760
11635
  async function main() {
7761
11636
  if (process.env.NIGHTLY === "true") return;
@@ -7772,8 +11647,8 @@ This update may name other issues, but the build just dropped here is for you; i
7772
11647
  } catch (err) {
7773
11648
  }
7774
11649
  report(`uploading ${xpi} to new release ${ContinuousIntegration.tag}`);
7775
- if (!dryRun) {
7776
- release = await octokit.repos.createRelease({ owner, repo, tag_name: ContinuousIntegration.tag, prerelease: !!PRERELEASE, body: process.argv[2] || "" });
11650
+ if (!options.dryRun) {
11651
+ release = await octokit.repos.createRelease({ owner, repo, tag_name: ContinuousIntegration.tag, prerelease: !!options.preRelease, body: options.releaseMessage || "" });
7777
11652
  await uploadAsset(release, path2.join(root_default, `xpi/${xpi}`), "application/vnd.zotero.plugin");
7778
11653
  }
7779
11654
  await update_rdf(pkg.xpi.releaseURL.split("/").filter((name) => name).reverse()[0]);
@@ -7782,7 +11657,7 @@ This update may name other issues, but the build just dropped here is for you; i
7782
11657
  for (const asset of release.data.assets || []) {
7783
11658
  if (asset.name.endsWith(".xpi") && asset.created_at < EXPIRE_BUILDS) {
7784
11659
  report(`deleting ${asset.name}`);
7785
- if (!dryRun) await octokit.repos.deleteReleaseAsset({ owner, repo, asset_id: asset.id });
11660
+ if (!options.dryRun) await octokit.repos.deleteReleaseAsset({ owner, repo, asset_id: asset.id });
7786
11661
  }
7787
11662
  }
7788
11663
  await uploadAsset(release, path2.join(root_default, `xpi/${xpi}`), "application/vnd.zotero.plugin");