@tiddlywiki/mws 0.0.14 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -12154,12 +12154,12 @@ var init_StateObject = __esm({
12154
12154
  init_streamer();
12155
12155
  init_utils2();
12156
12156
  _StateObject = class _StateObject extends StreamerState {
12157
- constructor(streamer, routePath, bodyFormat, user, commander, tiddlerCache) {
12157
+ constructor(streamer, routePath, bodyFormat, user, commander2, tiddlerCache) {
12158
12158
  super(streamer);
12159
12159
  this.routePath = routePath;
12160
12160
  this.bodyFormat = bodyFormat;
12161
12161
  this.user = user;
12162
- this.commander = commander;
12162
+ this.commander = commander2;
12163
12163
  this.tiddlerCache = tiddlerCache;
12164
12164
  this.z = z3;
12165
12165
  this.STREAM_ENDED = STREAM_ENDED;
@@ -12170,9 +12170,9 @@ var init_StateObject = __esm({
12170
12170
  this.$transaction = /* @__PURE__ */ __name(async (fn) => {
12171
12171
  return await this.engine.$transaction((prisma) => fn(prisma));
12172
12172
  }, "$transaction");
12173
- this.engine = commander.engine;
12174
- this.config = commander.siteConfig;
12175
- this.PasswordService = commander.PasswordService;
12173
+ this.engine = commander2.engine;
12174
+ this.config = commander2.siteConfig;
12175
+ this.PasswordService = commander2.PasswordService;
12176
12176
  this.readMultipartData = readMultipartData.bind(this);
12177
12177
  this.sendResponse = sendResponse.bind(void 0, this.config, this);
12178
12178
  this.pathParams = Object.fromEntries(routePath.map(
@@ -12914,13 +12914,13 @@ var init_TiddlerStore = __esm({
12914
12914
  init_esm_shims();
12915
12915
  init_utils2();
12916
12916
  _TiddlerStore = class _TiddlerStore {
12917
- constructor(commander, prisma) {
12918
- this.commander = commander;
12917
+ constructor(commander2, prisma) {
12918
+ this.commander = commander2;
12919
12919
  this.prisma = prisma;
12920
12920
  this.fieldModules = this.commander.$tw.Tiddler.fieldModules;
12921
- this.attachService = new commander.AttachmentService(commander.siteConfig, prisma);
12922
- this.storePath = commander.siteConfig.storePath;
12923
- this.config = commander.siteConfig;
12921
+ this.attachService = new commander2.AttachmentService(commander2.siteConfig, prisma);
12922
+ this.storePath = commander2.siteConfig.storePath;
12923
+ this.config = commander2.siteConfig;
12924
12924
  }
12925
12925
  /*
12926
12926
  Returns null if a bag/recipe name is valid, or a string error message if not
@@ -14096,7 +14096,7 @@ var init_bag_file_server = __esm({
14096
14096
  super(state.commander, prisma);
14097
14097
  this.state = state;
14098
14098
  }
14099
- toTiddlyWebJson(info11) {
14099
+ toTiddlyWebJson(info12) {
14100
14100
  const output = { fields: {} };
14101
14101
  const knownFields = [
14102
14102
  "bag",
@@ -14113,16 +14113,16 @@ var init_bag_file_server = __esm({
14113
14113
  "type",
14114
14114
  "uri"
14115
14115
  ];
14116
- each(info11.tiddler, (field, name) => {
14116
+ each(info12.tiddler, (field, name) => {
14117
14117
  if (knownFields.indexOf(name) !== -1) {
14118
14118
  output[name] = field;
14119
14119
  } else {
14120
14120
  output.fields[name] = field;
14121
14121
  }
14122
14122
  });
14123
- output.type = info11.tiddler.type || "text/vnd.tiddlywiki";
14124
- output.revision = `${info11.tiddler_id}`;
14125
- output.bag = info11.bag_name;
14123
+ output.type = info12.tiddler.type || "text/vnd.tiddlywiki";
14124
+ output.revision = `${info12.tiddler_id}`;
14125
+ output.bag = info12.bag_name;
14126
14126
  return output;
14127
14127
  }
14128
14128
  /** If neither bag_name nor bag_id are specified, the fallback will be sent. */
@@ -14779,7 +14779,7 @@ async function setupDevServer(enableDevServer, pathPrefix) {
14779
14779
  }, index_file), "sendIndex");
14780
14780
  if (state.url === "/") return sendIndex();
14781
14781
  return state.sendFile(200, {}, {
14782
- root: rootdir,
14782
+ root: resolve3(rootdir, "public"),
14783
14783
  reqpath: state.url,
14784
14784
  on404: /* @__PURE__ */ __name(async () => sendIndex(), "on404")
14785
14785
  });
@@ -14870,8 +14870,8 @@ var init_setupDevServer = __esm({
14870
14870
 
14871
14871
  // src/routes/cache.ts
14872
14872
  import { ok as ok4 } from "assert";
14873
- async function startupCache(commander) {
14874
- const $tw2 = commander.$tw;
14873
+ async function startupCache(commander2) {
14874
+ const $tw2 = commander2.$tw;
14875
14875
  const bootTiddlers = $tw2.loadTiddlersFromPath($tw2.boot.bootPath).flatMap((file) => file.tiddlers);
14876
14876
  const coreTiddler = $tw2.loadPluginFolder($tw2.boot.corePath);
14877
14877
  ok4(coreTiddler);
@@ -14958,20 +14958,20 @@ var init_router = __esm({
14958
14958
  }
14959
14959
  }, "zodTransformJSON");
14960
14960
  _Router = class _Router {
14961
- constructor(rootRoute2, commander, tiddlerCache) {
14961
+ constructor(rootRoute2, commander2, tiddlerCache) {
14962
14962
  this.rootRoute = rootRoute2;
14963
- this.commander = commander;
14963
+ this.commander = commander2;
14964
14964
  this.tiddlerCache = tiddlerCache;
14965
14965
  this.pathPrefix = "";
14966
14966
  this.enableBrowserCache = true;
14967
14967
  this.enableGzip = false;
14968
14968
  this.csrfDisable = false;
14969
- this.engine = commander.engine;
14970
- this.SessionManager = commander.SessionManager;
14971
- this.pathPrefix = commander.siteConfig.pathPrefix;
14969
+ this.engine = commander2.engine;
14970
+ this.SessionManager = commander2.SessionManager;
14971
+ this.pathPrefix = commander2.siteConfig.pathPrefix;
14972
14972
  }
14973
- static async makeRouter(commander, enableDevServer) {
14974
- const sendDevServer = await setupDevServer(enableDevServer, commander.siteConfig.pathPrefix);
14973
+ static async makeRouter(commander2, enableDevServer) {
14974
+ const sendDevServer = await setupDevServer(enableDevServer, commander2.siteConfig.pathPrefix);
14975
14975
  const rootRoute2 = defineRoute(ROOT_ROUTE, {
14976
14976
  method: AllowedMethods,
14977
14977
  path: /^/,
@@ -14979,10 +14979,10 @@ var init_router = __esm({
14979
14979
  }, async (state) => {
14980
14980
  state.sendDevServer = sendDevServer.bind(void 0, state);
14981
14981
  });
14982
- await commander.SessionManager.defineRoutes(rootRoute2);
14983
- await RootRoute(rootRoute2, commander.siteConfig);
14984
- const cache = await startupCache(commander);
14985
- return new _Router(rootRoute2, commander, cache);
14982
+ await commander2.SessionManager.defineRoutes(rootRoute2);
14983
+ await RootRoute(rootRoute2, commander2.siteConfig);
14984
+ const cache = await startupCache(commander2);
14985
+ return new _Router(rootRoute2, commander2, cache);
14986
14986
  }
14987
14987
  handleIncomingRequest(req, res) {
14988
14988
  const [ok8, err, streamer] = function() {
@@ -15554,10 +15554,3368 @@ var init_attachments = __esm({
15554
15554
  }
15555
15555
  });
15556
15556
 
15557
- // src/commands/mws-load-plugin-bags.ts
15558
- var mws_load_plugin_bags_exports = {};
15559
- __export(mws_load_plugin_bags_exports, {
15560
- Command: () => Command,
15557
+ // node_modules/commander/lib/error.js
15558
+ var require_error = __commonJS({
15559
+ "node_modules/commander/lib/error.js"(exports) {
15560
+ "use strict";
15561
+ init_esm_shims();
15562
+ var _CommanderError = class _CommanderError extends Error {
15563
+ /**
15564
+ * Constructs the CommanderError class
15565
+ * @param {number} exitCode suggested exit code which could be used with process.exit
15566
+ * @param {string} code an id string representing the error
15567
+ * @param {string} message human-readable description of the error
15568
+ */
15569
+ constructor(exitCode, code, message) {
15570
+ super(message);
15571
+ Error.captureStackTrace(this, this.constructor);
15572
+ this.name = this.constructor.name;
15573
+ this.code = code;
15574
+ this.exitCode = exitCode;
15575
+ this.nestedError = void 0;
15576
+ }
15577
+ };
15578
+ __name(_CommanderError, "CommanderError");
15579
+ var CommanderError2 = _CommanderError;
15580
+ var _InvalidArgumentError = class _InvalidArgumentError extends CommanderError2 {
15581
+ /**
15582
+ * Constructs the InvalidArgumentError class
15583
+ * @param {string} [message] explanation of why argument is invalid
15584
+ */
15585
+ constructor(message) {
15586
+ super(1, "commander.invalidArgument", message);
15587
+ Error.captureStackTrace(this, this.constructor);
15588
+ this.name = this.constructor.name;
15589
+ }
15590
+ };
15591
+ __name(_InvalidArgumentError, "InvalidArgumentError");
15592
+ var InvalidArgumentError2 = _InvalidArgumentError;
15593
+ exports.CommanderError = CommanderError2;
15594
+ exports.InvalidArgumentError = InvalidArgumentError2;
15595
+ }
15596
+ });
15597
+
15598
+ // node_modules/commander/lib/argument.js
15599
+ var require_argument = __commonJS({
15600
+ "node_modules/commander/lib/argument.js"(exports) {
15601
+ "use strict";
15602
+ init_esm_shims();
15603
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
15604
+ var _Argument = class _Argument {
15605
+ /**
15606
+ * Initialize a new command argument with the given name and description.
15607
+ * The default is that the argument is required, and you can explicitly
15608
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
15609
+ *
15610
+ * @param {string} name
15611
+ * @param {string} [description]
15612
+ */
15613
+ constructor(name, description) {
15614
+ this.description = description || "";
15615
+ this.variadic = false;
15616
+ this.parseArg = void 0;
15617
+ this.defaultValue = void 0;
15618
+ this.defaultValueDescription = void 0;
15619
+ this.argChoices = void 0;
15620
+ switch (name[0]) {
15621
+ case "<":
15622
+ this.required = true;
15623
+ this._name = name.slice(1, -1);
15624
+ break;
15625
+ case "[":
15626
+ this.required = false;
15627
+ this._name = name.slice(1, -1);
15628
+ break;
15629
+ default:
15630
+ this.required = true;
15631
+ this._name = name;
15632
+ break;
15633
+ }
15634
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
15635
+ this.variadic = true;
15636
+ this._name = this._name.slice(0, -3);
15637
+ }
15638
+ }
15639
+ /**
15640
+ * Return argument name.
15641
+ *
15642
+ * @return {string}
15643
+ */
15644
+ name() {
15645
+ return this._name;
15646
+ }
15647
+ /**
15648
+ * @package
15649
+ */
15650
+ _concatValue(value, previous) {
15651
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
15652
+ return [value];
15653
+ }
15654
+ return previous.concat(value);
15655
+ }
15656
+ /**
15657
+ * Set the default value, and optionally supply the description to be displayed in the help.
15658
+ *
15659
+ * @param {*} value
15660
+ * @param {string} [description]
15661
+ * @return {Argument}
15662
+ */
15663
+ default(value, description) {
15664
+ this.defaultValue = value;
15665
+ this.defaultValueDescription = description;
15666
+ return this;
15667
+ }
15668
+ /**
15669
+ * Set the custom handler for processing CLI command arguments into argument values.
15670
+ *
15671
+ * @param {Function} [fn]
15672
+ * @return {Argument}
15673
+ */
15674
+ argParser(fn) {
15675
+ this.parseArg = fn;
15676
+ return this;
15677
+ }
15678
+ /**
15679
+ * Only allow argument value to be one of choices.
15680
+ *
15681
+ * @param {string[]} values
15682
+ * @return {Argument}
15683
+ */
15684
+ choices(values) {
15685
+ this.argChoices = values.slice();
15686
+ this.parseArg = (arg, previous) => {
15687
+ if (!this.argChoices.includes(arg)) {
15688
+ throw new InvalidArgumentError2(
15689
+ `Allowed choices are ${this.argChoices.join(", ")}.`
15690
+ );
15691
+ }
15692
+ if (this.variadic) {
15693
+ return this._concatValue(arg, previous);
15694
+ }
15695
+ return arg;
15696
+ };
15697
+ return this;
15698
+ }
15699
+ /**
15700
+ * Make argument required.
15701
+ *
15702
+ * @returns {Argument}
15703
+ */
15704
+ argRequired() {
15705
+ this.required = true;
15706
+ return this;
15707
+ }
15708
+ /**
15709
+ * Make argument optional.
15710
+ *
15711
+ * @returns {Argument}
15712
+ */
15713
+ argOptional() {
15714
+ this.required = false;
15715
+ return this;
15716
+ }
15717
+ };
15718
+ __name(_Argument, "Argument");
15719
+ var Argument2 = _Argument;
15720
+ function humanReadableArgName(arg) {
15721
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
15722
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
15723
+ }
15724
+ __name(humanReadableArgName, "humanReadableArgName");
15725
+ exports.Argument = Argument2;
15726
+ exports.humanReadableArgName = humanReadableArgName;
15727
+ }
15728
+ });
15729
+
15730
+ // node_modules/commander/lib/help.js
15731
+ var require_help = __commonJS({
15732
+ "node_modules/commander/lib/help.js"(exports) {
15733
+ "use strict";
15734
+ init_esm_shims();
15735
+ var { humanReadableArgName } = require_argument();
15736
+ var _Help = class _Help {
15737
+ constructor() {
15738
+ this.helpWidth = void 0;
15739
+ this.minWidthToWrap = 40;
15740
+ this.sortSubcommands = false;
15741
+ this.sortOptions = false;
15742
+ this.showGlobalOptions = false;
15743
+ }
15744
+ /**
15745
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
15746
+ * and just before calling `formatHelp()`.
15747
+ *
15748
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
15749
+ *
15750
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
15751
+ */
15752
+ prepareContext(contextOptions) {
15753
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
15754
+ }
15755
+ /**
15756
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
15757
+ *
15758
+ * @param {Command} cmd
15759
+ * @returns {Command[]}
15760
+ */
15761
+ visibleCommands(cmd) {
15762
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
15763
+ const helpCommand = cmd._getHelpCommand();
15764
+ if (helpCommand && !helpCommand._hidden) {
15765
+ visibleCommands.push(helpCommand);
15766
+ }
15767
+ if (this.sortSubcommands) {
15768
+ visibleCommands.sort((a, b) => {
15769
+ return a.name().localeCompare(b.name());
15770
+ });
15771
+ }
15772
+ return visibleCommands;
15773
+ }
15774
+ /**
15775
+ * Compare options for sort.
15776
+ *
15777
+ * @param {Option} a
15778
+ * @param {Option} b
15779
+ * @returns {number}
15780
+ */
15781
+ compareOptions(a, b) {
15782
+ const getSortKey = /* @__PURE__ */ __name((option) => {
15783
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
15784
+ }, "getSortKey");
15785
+ return getSortKey(a).localeCompare(getSortKey(b));
15786
+ }
15787
+ /**
15788
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
15789
+ *
15790
+ * @param {Command} cmd
15791
+ * @returns {Option[]}
15792
+ */
15793
+ visibleOptions(cmd) {
15794
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
15795
+ const helpOption = cmd._getHelpOption();
15796
+ if (helpOption && !helpOption.hidden) {
15797
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
15798
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
15799
+ if (!removeShort && !removeLong) {
15800
+ visibleOptions.push(helpOption);
15801
+ } else if (helpOption.long && !removeLong) {
15802
+ visibleOptions.push(
15803
+ cmd.createOption(helpOption.long, helpOption.description)
15804
+ );
15805
+ } else if (helpOption.short && !removeShort) {
15806
+ visibleOptions.push(
15807
+ cmd.createOption(helpOption.short, helpOption.description)
15808
+ );
15809
+ }
15810
+ }
15811
+ if (this.sortOptions) {
15812
+ visibleOptions.sort(this.compareOptions);
15813
+ }
15814
+ return visibleOptions;
15815
+ }
15816
+ /**
15817
+ * Get an array of the visible global options. (Not including help.)
15818
+ *
15819
+ * @param {Command} cmd
15820
+ * @returns {Option[]}
15821
+ */
15822
+ visibleGlobalOptions(cmd) {
15823
+ if (!this.showGlobalOptions) return [];
15824
+ const globalOptions = [];
15825
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
15826
+ const visibleOptions = ancestorCmd.options.filter(
15827
+ (option) => !option.hidden
15828
+ );
15829
+ globalOptions.push(...visibleOptions);
15830
+ }
15831
+ if (this.sortOptions) {
15832
+ globalOptions.sort(this.compareOptions);
15833
+ }
15834
+ return globalOptions;
15835
+ }
15836
+ /**
15837
+ * Get an array of the arguments if any have a description.
15838
+ *
15839
+ * @param {Command} cmd
15840
+ * @returns {Argument[]}
15841
+ */
15842
+ visibleArguments(cmd) {
15843
+ if (cmd._argsDescription) {
15844
+ cmd.registeredArguments.forEach((argument) => {
15845
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
15846
+ });
15847
+ }
15848
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
15849
+ return cmd.registeredArguments;
15850
+ }
15851
+ return [];
15852
+ }
15853
+ /**
15854
+ * Get the command term to show in the list of subcommands.
15855
+ *
15856
+ * @param {Command} cmd
15857
+ * @returns {string}
15858
+ */
15859
+ subcommandTerm(cmd) {
15860
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
15861
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
15862
+ (args ? " " + args : "");
15863
+ }
15864
+ /**
15865
+ * Get the option term to show in the list of options.
15866
+ *
15867
+ * @param {Option} option
15868
+ * @returns {string}
15869
+ */
15870
+ optionTerm(option) {
15871
+ return option.flags;
15872
+ }
15873
+ /**
15874
+ * Get the argument term to show in the list of arguments.
15875
+ *
15876
+ * @param {Argument} argument
15877
+ * @returns {string}
15878
+ */
15879
+ argumentTerm(argument) {
15880
+ return argument.name();
15881
+ }
15882
+ /**
15883
+ * Get the longest command term length.
15884
+ *
15885
+ * @param {Command} cmd
15886
+ * @param {Help} helper
15887
+ * @returns {number}
15888
+ */
15889
+ longestSubcommandTermLength(cmd, helper) {
15890
+ return helper.visibleCommands(cmd).reduce((max, command) => {
15891
+ return Math.max(
15892
+ max,
15893
+ this.displayWidth(
15894
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
15895
+ )
15896
+ );
15897
+ }, 0);
15898
+ }
15899
+ /**
15900
+ * Get the longest option term length.
15901
+ *
15902
+ * @param {Command} cmd
15903
+ * @param {Help} helper
15904
+ * @returns {number}
15905
+ */
15906
+ longestOptionTermLength(cmd, helper) {
15907
+ return helper.visibleOptions(cmd).reduce((max, option) => {
15908
+ return Math.max(
15909
+ max,
15910
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
15911
+ );
15912
+ }, 0);
15913
+ }
15914
+ /**
15915
+ * Get the longest global option term length.
15916
+ *
15917
+ * @param {Command} cmd
15918
+ * @param {Help} helper
15919
+ * @returns {number}
15920
+ */
15921
+ longestGlobalOptionTermLength(cmd, helper) {
15922
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
15923
+ return Math.max(
15924
+ max,
15925
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
15926
+ );
15927
+ }, 0);
15928
+ }
15929
+ /**
15930
+ * Get the longest argument term length.
15931
+ *
15932
+ * @param {Command} cmd
15933
+ * @param {Help} helper
15934
+ * @returns {number}
15935
+ */
15936
+ longestArgumentTermLength(cmd, helper) {
15937
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
15938
+ return Math.max(
15939
+ max,
15940
+ this.displayWidth(
15941
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
15942
+ )
15943
+ );
15944
+ }, 0);
15945
+ }
15946
+ /**
15947
+ * Get the command usage to be displayed at the top of the built-in help.
15948
+ *
15949
+ * @param {Command} cmd
15950
+ * @returns {string}
15951
+ */
15952
+ commandUsage(cmd) {
15953
+ let cmdName = cmd._name;
15954
+ if (cmd._aliases[0]) {
15955
+ cmdName = cmdName + "|" + cmd._aliases[0];
15956
+ }
15957
+ let ancestorCmdNames = "";
15958
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
15959
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
15960
+ }
15961
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
15962
+ }
15963
+ /**
15964
+ * Get the description for the command.
15965
+ *
15966
+ * @param {Command} cmd
15967
+ * @returns {string}
15968
+ */
15969
+ commandDescription(cmd) {
15970
+ return cmd.description();
15971
+ }
15972
+ /**
15973
+ * Get the subcommand summary to show in the list of subcommands.
15974
+ * (Fallback to description for backwards compatibility.)
15975
+ *
15976
+ * @param {Command} cmd
15977
+ * @returns {string}
15978
+ */
15979
+ subcommandDescription(cmd) {
15980
+ return cmd.summary() || cmd.description();
15981
+ }
15982
+ /**
15983
+ * Get the option description to show in the list of options.
15984
+ *
15985
+ * @param {Option} option
15986
+ * @return {string}
15987
+ */
15988
+ optionDescription(option) {
15989
+ const extraInfo = [];
15990
+ if (option.argChoices) {
15991
+ extraInfo.push(
15992
+ // use stringify to match the display of the default value
15993
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
15994
+ );
15995
+ }
15996
+ if (option.defaultValue !== void 0) {
15997
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
15998
+ if (showDefault) {
15999
+ extraInfo.push(
16000
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
16001
+ );
16002
+ }
16003
+ }
16004
+ if (option.presetArg !== void 0 && option.optional) {
16005
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
16006
+ }
16007
+ if (option.envVar !== void 0) {
16008
+ extraInfo.push(`env: ${option.envVar}`);
16009
+ }
16010
+ if (extraInfo.length > 0) {
16011
+ return `${option.description} (${extraInfo.join(", ")})`;
16012
+ }
16013
+ return option.description;
16014
+ }
16015
+ /**
16016
+ * Get the argument description to show in the list of arguments.
16017
+ *
16018
+ * @param {Argument} argument
16019
+ * @return {string}
16020
+ */
16021
+ argumentDescription(argument) {
16022
+ const extraInfo = [];
16023
+ if (argument.argChoices) {
16024
+ extraInfo.push(
16025
+ // use stringify to match the display of the default value
16026
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
16027
+ );
16028
+ }
16029
+ if (argument.defaultValue !== void 0) {
16030
+ extraInfo.push(
16031
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
16032
+ );
16033
+ }
16034
+ if (extraInfo.length > 0) {
16035
+ const extraDescription = `(${extraInfo.join(", ")})`;
16036
+ if (argument.description) {
16037
+ return `${argument.description} ${extraDescription}`;
16038
+ }
16039
+ return extraDescription;
16040
+ }
16041
+ return argument.description;
16042
+ }
16043
+ /**
16044
+ * Generate the built-in help text.
16045
+ *
16046
+ * @param {Command} cmd
16047
+ * @param {Help} helper
16048
+ * @returns {string}
16049
+ */
16050
+ formatHelp(cmd, helper) {
16051
+ const termWidth = helper.padWidth(cmd, helper);
16052
+ const helpWidth = helper.helpWidth ?? 80;
16053
+ function callFormatItem(term, description) {
16054
+ return helper.formatItem(term, termWidth, description, helper);
16055
+ }
16056
+ __name(callFormatItem, "callFormatItem");
16057
+ let output = [
16058
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
16059
+ ""
16060
+ ];
16061
+ const commandDescription = helper.commandDescription(cmd);
16062
+ if (commandDescription.length > 0) {
16063
+ output = output.concat([
16064
+ helper.boxWrap(
16065
+ helper.styleCommandDescription(commandDescription),
16066
+ helpWidth
16067
+ ),
16068
+ ""
16069
+ ]);
16070
+ }
16071
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
16072
+ return callFormatItem(
16073
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
16074
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
16075
+ );
16076
+ });
16077
+ if (argumentList.length > 0) {
16078
+ output = output.concat([
16079
+ helper.styleTitle("Arguments:"),
16080
+ ...argumentList,
16081
+ ""
16082
+ ]);
16083
+ }
16084
+ const optionList = helper.visibleOptions(cmd).map((option) => {
16085
+ return callFormatItem(
16086
+ helper.styleOptionTerm(helper.optionTerm(option)),
16087
+ helper.styleOptionDescription(helper.optionDescription(option))
16088
+ );
16089
+ });
16090
+ if (optionList.length > 0) {
16091
+ output = output.concat([
16092
+ helper.styleTitle("Options:"),
16093
+ ...optionList,
16094
+ ""
16095
+ ]);
16096
+ }
16097
+ if (helper.showGlobalOptions) {
16098
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
16099
+ return callFormatItem(
16100
+ helper.styleOptionTerm(helper.optionTerm(option)),
16101
+ helper.styleOptionDescription(helper.optionDescription(option))
16102
+ );
16103
+ });
16104
+ if (globalOptionList.length > 0) {
16105
+ output = output.concat([
16106
+ helper.styleTitle("Global Options:"),
16107
+ ...globalOptionList,
16108
+ ""
16109
+ ]);
16110
+ }
16111
+ }
16112
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
16113
+ return callFormatItem(
16114
+ helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)),
16115
+ helper.styleSubcommandDescription(helper.subcommandDescription(cmd2))
16116
+ );
16117
+ });
16118
+ if (commandList.length > 0) {
16119
+ output = output.concat([
16120
+ helper.styleTitle("Commands:"),
16121
+ ...commandList,
16122
+ ""
16123
+ ]);
16124
+ }
16125
+ return output.join("\n");
16126
+ }
16127
+ /**
16128
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
16129
+ *
16130
+ * @param {string} str
16131
+ * @returns {number}
16132
+ */
16133
+ displayWidth(str) {
16134
+ return stripColor(str).length;
16135
+ }
16136
+ /**
16137
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
16138
+ *
16139
+ * @param {string} str
16140
+ * @returns {string}
16141
+ */
16142
+ styleTitle(str) {
16143
+ return str;
16144
+ }
16145
+ styleUsage(str) {
16146
+ return str.split(" ").map((word) => {
16147
+ if (word === "[options]") return this.styleOptionText(word);
16148
+ if (word === "[command]") return this.styleSubcommandText(word);
16149
+ if (word[0] === "[" || word[0] === "<")
16150
+ return this.styleArgumentText(word);
16151
+ return this.styleCommandText(word);
16152
+ }).join(" ");
16153
+ }
16154
+ styleCommandDescription(str) {
16155
+ return this.styleDescriptionText(str);
16156
+ }
16157
+ styleOptionDescription(str) {
16158
+ return this.styleDescriptionText(str);
16159
+ }
16160
+ styleSubcommandDescription(str) {
16161
+ return this.styleDescriptionText(str);
16162
+ }
16163
+ styleArgumentDescription(str) {
16164
+ return this.styleDescriptionText(str);
16165
+ }
16166
+ styleDescriptionText(str) {
16167
+ return str;
16168
+ }
16169
+ styleOptionTerm(str) {
16170
+ return this.styleOptionText(str);
16171
+ }
16172
+ styleSubcommandTerm(str) {
16173
+ return str.split(" ").map((word) => {
16174
+ if (word === "[options]") return this.styleOptionText(word);
16175
+ if (word[0] === "[" || word[0] === "<")
16176
+ return this.styleArgumentText(word);
16177
+ return this.styleSubcommandText(word);
16178
+ }).join(" ");
16179
+ }
16180
+ styleArgumentTerm(str) {
16181
+ return this.styleArgumentText(str);
16182
+ }
16183
+ styleOptionText(str) {
16184
+ return str;
16185
+ }
16186
+ styleArgumentText(str) {
16187
+ return str;
16188
+ }
16189
+ styleSubcommandText(str) {
16190
+ return str;
16191
+ }
16192
+ styleCommandText(str) {
16193
+ return str;
16194
+ }
16195
+ /**
16196
+ * Calculate the pad width from the maximum term length.
16197
+ *
16198
+ * @param {Command} cmd
16199
+ * @param {Help} helper
16200
+ * @returns {number}
16201
+ */
16202
+ padWidth(cmd, helper) {
16203
+ return Math.max(
16204
+ helper.longestOptionTermLength(cmd, helper),
16205
+ helper.longestGlobalOptionTermLength(cmd, helper),
16206
+ helper.longestSubcommandTermLength(cmd, helper),
16207
+ helper.longestArgumentTermLength(cmd, helper)
16208
+ );
16209
+ }
16210
+ /**
16211
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
16212
+ *
16213
+ * @param {string} str
16214
+ * @returns {boolean}
16215
+ */
16216
+ preformatted(str) {
16217
+ return /\n[^\S\r\n]/.test(str);
16218
+ }
16219
+ /**
16220
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
16221
+ *
16222
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
16223
+ * TTT DDD DDDD
16224
+ * DD DDD
16225
+ *
16226
+ * @param {string} term
16227
+ * @param {number} termWidth
16228
+ * @param {string} description
16229
+ * @param {Help} helper
16230
+ * @returns {string}
16231
+ */
16232
+ formatItem(term, termWidth, description, helper) {
16233
+ const itemIndent = 2;
16234
+ const itemIndentStr = " ".repeat(itemIndent);
16235
+ if (!description) return itemIndentStr + term;
16236
+ const paddedTerm = term.padEnd(
16237
+ termWidth + term.length - helper.displayWidth(term)
16238
+ );
16239
+ const spacerWidth = 2;
16240
+ const helpWidth = this.helpWidth ?? 80;
16241
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
16242
+ let formattedDescription;
16243
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
16244
+ formattedDescription = description;
16245
+ } else {
16246
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
16247
+ formattedDescription = wrappedDescription.replace(
16248
+ /\n/g,
16249
+ "\n" + " ".repeat(termWidth + spacerWidth)
16250
+ );
16251
+ }
16252
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
16253
+ ${itemIndentStr}`);
16254
+ }
16255
+ /**
16256
+ * Wrap a string at whitespace, preserving existing line breaks.
16257
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
16258
+ *
16259
+ * @param {string} str
16260
+ * @param {number} width
16261
+ * @returns {string}
16262
+ */
16263
+ boxWrap(str, width) {
16264
+ if (width < this.minWidthToWrap) return str;
16265
+ const rawLines = str.split(/\r\n|\n/);
16266
+ const chunkPattern = /[\s]*[^\s]+/g;
16267
+ const wrappedLines = [];
16268
+ rawLines.forEach((line) => {
16269
+ const chunks = line.match(chunkPattern);
16270
+ if (chunks === null) {
16271
+ wrappedLines.push("");
16272
+ return;
16273
+ }
16274
+ let sumChunks = [chunks.shift()];
16275
+ let sumWidth = this.displayWidth(sumChunks[0]);
16276
+ chunks.forEach((chunk) => {
16277
+ const visibleWidth = this.displayWidth(chunk);
16278
+ if (sumWidth + visibleWidth <= width) {
16279
+ sumChunks.push(chunk);
16280
+ sumWidth += visibleWidth;
16281
+ return;
16282
+ }
16283
+ wrappedLines.push(sumChunks.join(""));
16284
+ const nextChunk = chunk.trimStart();
16285
+ sumChunks = [nextChunk];
16286
+ sumWidth = this.displayWidth(nextChunk);
16287
+ });
16288
+ wrappedLines.push(sumChunks.join(""));
16289
+ });
16290
+ return wrappedLines.join("\n");
16291
+ }
16292
+ };
16293
+ __name(_Help, "Help");
16294
+ var Help2 = _Help;
16295
+ function stripColor(str) {
16296
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
16297
+ return str.replace(sgrPattern, "");
16298
+ }
16299
+ __name(stripColor, "stripColor");
16300
+ exports.Help = Help2;
16301
+ exports.stripColor = stripColor;
16302
+ }
16303
+ });
16304
+
16305
+ // node_modules/commander/lib/option.js
16306
+ var require_option = __commonJS({
16307
+ "node_modules/commander/lib/option.js"(exports) {
16308
+ "use strict";
16309
+ init_esm_shims();
16310
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
16311
+ var _Option = class _Option {
16312
+ /**
16313
+ * Initialize a new `Option` with the given `flags` and `description`.
16314
+ *
16315
+ * @param {string} flags
16316
+ * @param {string} [description]
16317
+ */
16318
+ constructor(flags, description) {
16319
+ this.flags = flags;
16320
+ this.description = description || "";
16321
+ this.required = flags.includes("<");
16322
+ this.optional = flags.includes("[");
16323
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
16324
+ this.mandatory = false;
16325
+ const optionFlags = splitOptionFlags(flags);
16326
+ this.short = optionFlags.shortFlag;
16327
+ this.long = optionFlags.longFlag;
16328
+ this.negate = false;
16329
+ if (this.long) {
16330
+ this.negate = this.long.startsWith("--no-");
16331
+ }
16332
+ this.defaultValue = void 0;
16333
+ this.defaultValueDescription = void 0;
16334
+ this.presetArg = void 0;
16335
+ this.envVar = void 0;
16336
+ this.parseArg = void 0;
16337
+ this.hidden = false;
16338
+ this.argChoices = void 0;
16339
+ this.conflictsWith = [];
16340
+ this.implied = void 0;
16341
+ }
16342
+ /**
16343
+ * Set the default value, and optionally supply the description to be displayed in the help.
16344
+ *
16345
+ * @param {*} value
16346
+ * @param {string} [description]
16347
+ * @return {Option}
16348
+ */
16349
+ default(value, description) {
16350
+ this.defaultValue = value;
16351
+ this.defaultValueDescription = description;
16352
+ return this;
16353
+ }
16354
+ /**
16355
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
16356
+ * The custom processing (parseArg) is called.
16357
+ *
16358
+ * @example
16359
+ * new Option('--color').default('GREYSCALE').preset('RGB');
16360
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
16361
+ *
16362
+ * @param {*} arg
16363
+ * @return {Option}
16364
+ */
16365
+ preset(arg) {
16366
+ this.presetArg = arg;
16367
+ return this;
16368
+ }
16369
+ /**
16370
+ * Add option name(s) that conflict with this option.
16371
+ * An error will be displayed if conflicting options are found during parsing.
16372
+ *
16373
+ * @example
16374
+ * new Option('--rgb').conflicts('cmyk');
16375
+ * new Option('--js').conflicts(['ts', 'jsx']);
16376
+ *
16377
+ * @param {(string | string[])} names
16378
+ * @return {Option}
16379
+ */
16380
+ conflicts(names) {
16381
+ this.conflictsWith = this.conflictsWith.concat(names);
16382
+ return this;
16383
+ }
16384
+ /**
16385
+ * Specify implied option values for when this option is set and the implied options are not.
16386
+ *
16387
+ * The custom processing (parseArg) is not called on the implied values.
16388
+ *
16389
+ * @example
16390
+ * program
16391
+ * .addOption(new Option('--log', 'write logging information to file'))
16392
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
16393
+ *
16394
+ * @param {object} impliedOptionValues
16395
+ * @return {Option}
16396
+ */
16397
+ implies(impliedOptionValues) {
16398
+ let newImplied = impliedOptionValues;
16399
+ if (typeof impliedOptionValues === "string") {
16400
+ newImplied = { [impliedOptionValues]: true };
16401
+ }
16402
+ this.implied = Object.assign(this.implied || {}, newImplied);
16403
+ return this;
16404
+ }
16405
+ /**
16406
+ * Set environment variable to check for option value.
16407
+ *
16408
+ * An environment variable is only used if when processed the current option value is
16409
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
16410
+ *
16411
+ * @param {string} name
16412
+ * @return {Option}
16413
+ */
16414
+ env(name) {
16415
+ this.envVar = name;
16416
+ return this;
16417
+ }
16418
+ /**
16419
+ * Set the custom handler for processing CLI option arguments into option values.
16420
+ *
16421
+ * @param {Function} [fn]
16422
+ * @return {Option}
16423
+ */
16424
+ argParser(fn) {
16425
+ this.parseArg = fn;
16426
+ return this;
16427
+ }
16428
+ /**
16429
+ * Whether the option is mandatory and must have a value after parsing.
16430
+ *
16431
+ * @param {boolean} [mandatory=true]
16432
+ * @return {Option}
16433
+ */
16434
+ makeOptionMandatory(mandatory = true) {
16435
+ this.mandatory = !!mandatory;
16436
+ return this;
16437
+ }
16438
+ /**
16439
+ * Hide option in help.
16440
+ *
16441
+ * @param {boolean} [hide=true]
16442
+ * @return {Option}
16443
+ */
16444
+ hideHelp(hide = true) {
16445
+ this.hidden = !!hide;
16446
+ return this;
16447
+ }
16448
+ /**
16449
+ * @package
16450
+ */
16451
+ _concatValue(value, previous) {
16452
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
16453
+ return [value];
16454
+ }
16455
+ return previous.concat(value);
16456
+ }
16457
+ /**
16458
+ * Only allow option value to be one of choices.
16459
+ *
16460
+ * @param {string[]} values
16461
+ * @return {Option}
16462
+ */
16463
+ choices(values) {
16464
+ this.argChoices = values.slice();
16465
+ this.parseArg = (arg, previous) => {
16466
+ if (!this.argChoices.includes(arg)) {
16467
+ throw new InvalidArgumentError2(
16468
+ `Allowed choices are ${this.argChoices.join(", ")}.`
16469
+ );
16470
+ }
16471
+ if (this.variadic) {
16472
+ return this._concatValue(arg, previous);
16473
+ }
16474
+ return arg;
16475
+ };
16476
+ return this;
16477
+ }
16478
+ /**
16479
+ * Return option name.
16480
+ *
16481
+ * @return {string}
16482
+ */
16483
+ name() {
16484
+ if (this.long) {
16485
+ return this.long.replace(/^--/, "");
16486
+ }
16487
+ return this.short.replace(/^-/, "");
16488
+ }
16489
+ /**
16490
+ * Return option name, in a camelcase format that can be used
16491
+ * as an object attribute key.
16492
+ *
16493
+ * @return {string}
16494
+ */
16495
+ attributeName() {
16496
+ if (this.negate) {
16497
+ return camelcase(this.name().replace(/^no-/, ""));
16498
+ }
16499
+ return camelcase(this.name());
16500
+ }
16501
+ /**
16502
+ * Check if `arg` matches the short or long flag.
16503
+ *
16504
+ * @param {string} arg
16505
+ * @return {boolean}
16506
+ * @package
16507
+ */
16508
+ is(arg) {
16509
+ return this.short === arg || this.long === arg;
16510
+ }
16511
+ /**
16512
+ * Return whether a boolean option.
16513
+ *
16514
+ * Options are one of boolean, negated, required argument, or optional argument.
16515
+ *
16516
+ * @return {boolean}
16517
+ * @package
16518
+ */
16519
+ isBoolean() {
16520
+ return !this.required && !this.optional && !this.negate;
16521
+ }
16522
+ };
16523
+ __name(_Option, "Option");
16524
+ var Option2 = _Option;
16525
+ var _DualOptions = class _DualOptions {
16526
+ /**
16527
+ * @param {Option[]} options
16528
+ */
16529
+ constructor(options) {
16530
+ this.positiveOptions = /* @__PURE__ */ new Map();
16531
+ this.negativeOptions = /* @__PURE__ */ new Map();
16532
+ this.dualOptions = /* @__PURE__ */ new Set();
16533
+ options.forEach((option) => {
16534
+ if (option.negate) {
16535
+ this.negativeOptions.set(option.attributeName(), option);
16536
+ } else {
16537
+ this.positiveOptions.set(option.attributeName(), option);
16538
+ }
16539
+ });
16540
+ this.negativeOptions.forEach((value, key) => {
16541
+ if (this.positiveOptions.has(key)) {
16542
+ this.dualOptions.add(key);
16543
+ }
16544
+ });
16545
+ }
16546
+ /**
16547
+ * Did the value come from the option, and not from possible matching dual option?
16548
+ *
16549
+ * @param {*} value
16550
+ * @param {Option} option
16551
+ * @returns {boolean}
16552
+ */
16553
+ valueFromOption(value, option) {
16554
+ const optionKey = option.attributeName();
16555
+ if (!this.dualOptions.has(optionKey)) return true;
16556
+ const preset = this.negativeOptions.get(optionKey).presetArg;
16557
+ const negativeValue = preset !== void 0 ? preset : false;
16558
+ return option.negate === (negativeValue === value);
16559
+ }
16560
+ };
16561
+ __name(_DualOptions, "DualOptions");
16562
+ var DualOptions = _DualOptions;
16563
+ function camelcase(str) {
16564
+ return str.split("-").reduce((str2, word) => {
16565
+ return str2 + word[0].toUpperCase() + word.slice(1);
16566
+ });
16567
+ }
16568
+ __name(camelcase, "camelcase");
16569
+ function splitOptionFlags(flags) {
16570
+ let shortFlag;
16571
+ let longFlag;
16572
+ const shortFlagExp = /^-[^-]$/;
16573
+ const longFlagExp = /^--[^-]/;
16574
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
16575
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
16576
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
16577
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
16578
+ shortFlag = flagParts.shift();
16579
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
16580
+ shortFlag = longFlag;
16581
+ longFlag = flagParts.shift();
16582
+ }
16583
+ if (flagParts[0].startsWith("-")) {
16584
+ const unsupportedFlag = flagParts[0];
16585
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
16586
+ if (/^-[^-][^-]/.test(unsupportedFlag))
16587
+ throw new Error(
16588
+ `${baseError}
16589
+ - a short flag is a single dash and a single character
16590
+ - either use a single dash and a single character (for a short flag)
16591
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
16592
+ );
16593
+ if (shortFlagExp.test(unsupportedFlag))
16594
+ throw new Error(`${baseError}
16595
+ - too many short flags`);
16596
+ if (longFlagExp.test(unsupportedFlag))
16597
+ throw new Error(`${baseError}
16598
+ - too many long flags`);
16599
+ throw new Error(`${baseError}
16600
+ - unrecognised flag format`);
16601
+ }
16602
+ if (shortFlag === void 0 && longFlag === void 0)
16603
+ throw new Error(
16604
+ `option creation failed due to no flags found in '${flags}'.`
16605
+ );
16606
+ return { shortFlag, longFlag };
16607
+ }
16608
+ __name(splitOptionFlags, "splitOptionFlags");
16609
+ exports.Option = Option2;
16610
+ exports.DualOptions = DualOptions;
16611
+ }
16612
+ });
16613
+
16614
+ // node_modules/commander/lib/suggestSimilar.js
16615
+ var require_suggestSimilar = __commonJS({
16616
+ "node_modules/commander/lib/suggestSimilar.js"(exports) {
16617
+ "use strict";
16618
+ init_esm_shims();
16619
+ var maxDistance = 3;
16620
+ function editDistance(a, b) {
16621
+ if (Math.abs(a.length - b.length) > maxDistance)
16622
+ return Math.max(a.length, b.length);
16623
+ const d = [];
16624
+ for (let i = 0; i <= a.length; i++) {
16625
+ d[i] = [i];
16626
+ }
16627
+ for (let j = 0; j <= b.length; j++) {
16628
+ d[0][j] = j;
16629
+ }
16630
+ for (let j = 1; j <= b.length; j++) {
16631
+ for (let i = 1; i <= a.length; i++) {
16632
+ let cost = 1;
16633
+ if (a[i - 1] === b[j - 1]) {
16634
+ cost = 0;
16635
+ } else {
16636
+ cost = 1;
16637
+ }
16638
+ d[i][j] = Math.min(
16639
+ d[i - 1][j] + 1,
16640
+ // deletion
16641
+ d[i][j - 1] + 1,
16642
+ // insertion
16643
+ d[i - 1][j - 1] + cost
16644
+ // substitution
16645
+ );
16646
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
16647
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
16648
+ }
16649
+ }
16650
+ }
16651
+ return d[a.length][b.length];
16652
+ }
16653
+ __name(editDistance, "editDistance");
16654
+ function suggestSimilar(word, candidates) {
16655
+ if (!candidates || candidates.length === 0) return "";
16656
+ candidates = Array.from(new Set(candidates));
16657
+ const searchingOptions = word.startsWith("--");
16658
+ if (searchingOptions) {
16659
+ word = word.slice(2);
16660
+ candidates = candidates.map((candidate) => candidate.slice(2));
16661
+ }
16662
+ let similar = [];
16663
+ let bestDistance = maxDistance;
16664
+ const minSimilarity = 0.4;
16665
+ candidates.forEach((candidate) => {
16666
+ if (candidate.length <= 1) return;
16667
+ const distance = editDistance(word, candidate);
16668
+ const length = Math.max(word.length, candidate.length);
16669
+ const similarity = (length - distance) / length;
16670
+ if (similarity > minSimilarity) {
16671
+ if (distance < bestDistance) {
16672
+ bestDistance = distance;
16673
+ similar = [candidate];
16674
+ } else if (distance === bestDistance) {
16675
+ similar.push(candidate);
16676
+ }
16677
+ }
16678
+ });
16679
+ similar.sort((a, b) => a.localeCompare(b));
16680
+ if (searchingOptions) {
16681
+ similar = similar.map((candidate) => `--${candidate}`);
16682
+ }
16683
+ if (similar.length > 1) {
16684
+ return `
16685
+ (Did you mean one of ${similar.join(", ")}?)`;
16686
+ }
16687
+ if (similar.length === 1) {
16688
+ return `
16689
+ (Did you mean ${similar[0]}?)`;
16690
+ }
16691
+ return "";
16692
+ }
16693
+ __name(suggestSimilar, "suggestSimilar");
16694
+ exports.suggestSimilar = suggestSimilar;
16695
+ }
16696
+ });
16697
+
16698
+ // node_modules/commander/lib/command.js
16699
+ var require_command = __commonJS({
16700
+ "node_modules/commander/lib/command.js"(exports) {
16701
+ "use strict";
16702
+ init_esm_shims();
16703
+ var EventEmitter = __require("node:events").EventEmitter;
16704
+ var childProcess = __require("node:child_process");
16705
+ var path5 = __require("node:path");
16706
+ var fs3 = __require("node:fs");
16707
+ var process2 = __require("node:process");
16708
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
16709
+ var { CommanderError: CommanderError2 } = require_error();
16710
+ var { Help: Help2, stripColor } = require_help();
16711
+ var { Option: Option2, DualOptions } = require_option();
16712
+ var { suggestSimilar } = require_suggestSimilar();
16713
+ var _Command12 = class _Command12 extends EventEmitter {
16714
+ /**
16715
+ * Initialize a new `Command`.
16716
+ *
16717
+ * @param {string} [name]
16718
+ */
16719
+ constructor(name) {
16720
+ super();
16721
+ this.commands = [];
16722
+ this.options = [];
16723
+ this.parent = null;
16724
+ this._allowUnknownOption = false;
16725
+ this._allowExcessArguments = false;
16726
+ this.registeredArguments = [];
16727
+ this._args = this.registeredArguments;
16728
+ this.args = [];
16729
+ this.rawArgs = [];
16730
+ this.processedArgs = [];
16731
+ this._scriptPath = null;
16732
+ this._name = name || "";
16733
+ this._optionValues = {};
16734
+ this._optionValueSources = {};
16735
+ this._storeOptionsAsProperties = false;
16736
+ this._actionHandler = null;
16737
+ this._executableHandler = false;
16738
+ this._executableFile = null;
16739
+ this._executableDir = null;
16740
+ this._defaultCommandName = null;
16741
+ this._exitCallback = null;
16742
+ this._aliases = [];
16743
+ this._combineFlagAndOptionalValue = true;
16744
+ this._description = "";
16745
+ this._summary = "";
16746
+ this._argsDescription = void 0;
16747
+ this._enablePositionalOptions = false;
16748
+ this._passThroughOptions = false;
16749
+ this._lifeCycleHooks = {};
16750
+ this._showHelpAfterError = false;
16751
+ this._showSuggestionAfterError = true;
16752
+ this._savedState = null;
16753
+ this._outputConfiguration = {
16754
+ writeOut: /* @__PURE__ */ __name((str) => process2.stdout.write(str), "writeOut"),
16755
+ writeErr: /* @__PURE__ */ __name((str) => process2.stderr.write(str), "writeErr"),
16756
+ outputError: /* @__PURE__ */ __name((str, write) => write(str), "outputError"),
16757
+ getOutHelpWidth: /* @__PURE__ */ __name(() => process2.stdout.isTTY ? process2.stdout.columns : void 0, "getOutHelpWidth"),
16758
+ getErrHelpWidth: /* @__PURE__ */ __name(() => process2.stderr.isTTY ? process2.stderr.columns : void 0, "getErrHelpWidth"),
16759
+ getOutHasColors: /* @__PURE__ */ __name(() => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()), "getOutHasColors"),
16760
+ getErrHasColors: /* @__PURE__ */ __name(() => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()), "getErrHasColors"),
16761
+ stripColor: /* @__PURE__ */ __name((str) => stripColor(str), "stripColor")
16762
+ };
16763
+ this._hidden = false;
16764
+ this._helpOption = void 0;
16765
+ this._addImplicitHelpCommand = void 0;
16766
+ this._helpCommand = void 0;
16767
+ this._helpConfiguration = {};
16768
+ }
16769
+ /**
16770
+ * Copy settings that are useful to have in common across root command and subcommands.
16771
+ *
16772
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
16773
+ *
16774
+ * @param {Command} sourceCommand
16775
+ * @return {Command} `this` command for chaining
16776
+ */
16777
+ copyInheritedSettings(sourceCommand) {
16778
+ this._outputConfiguration = sourceCommand._outputConfiguration;
16779
+ this._helpOption = sourceCommand._helpOption;
16780
+ this._helpCommand = sourceCommand._helpCommand;
16781
+ this._helpConfiguration = sourceCommand._helpConfiguration;
16782
+ this._exitCallback = sourceCommand._exitCallback;
16783
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
16784
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
16785
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
16786
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
16787
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
16788
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
16789
+ return this;
16790
+ }
16791
+ /**
16792
+ * @returns {Command[]}
16793
+ * @private
16794
+ */
16795
+ _getCommandAndAncestors() {
16796
+ const result = [];
16797
+ for (let command = this; command; command = command.parent) {
16798
+ result.push(command);
16799
+ }
16800
+ return result;
16801
+ }
16802
+ /**
16803
+ * Define a command.
16804
+ *
16805
+ * There are two styles of command: pay attention to where to put the description.
16806
+ *
16807
+ * @example
16808
+ * // Command implemented using action handler (description is supplied separately to `.command`)
16809
+ * program
16810
+ * .command('clone <source> [destination]')
16811
+ * .description('clone a repository into a newly created directory')
16812
+ * .action((source, destination) => {
16813
+ * console.log('clone command called');
16814
+ * });
16815
+ *
16816
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
16817
+ * program
16818
+ * .command('start <service>', 'start named service')
16819
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
16820
+ *
16821
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
16822
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
16823
+ * @param {object} [execOpts] - configuration options (for executable)
16824
+ * @return {Command} returns new command for action handler, or `this` for executable command
16825
+ */
16826
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
16827
+ let desc = actionOptsOrExecDesc;
16828
+ let opts = execOpts;
16829
+ if (typeof desc === "object" && desc !== null) {
16830
+ opts = desc;
16831
+ desc = null;
16832
+ }
16833
+ opts = opts || {};
16834
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
16835
+ const cmd = this.createCommand(name);
16836
+ if (desc) {
16837
+ cmd.description(desc);
16838
+ cmd._executableHandler = true;
16839
+ }
16840
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
16841
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
16842
+ cmd._executableFile = opts.executableFile || null;
16843
+ if (args) cmd.arguments(args);
16844
+ this._registerCommand(cmd);
16845
+ cmd.parent = this;
16846
+ cmd.copyInheritedSettings(this);
16847
+ if (desc) return this;
16848
+ return cmd;
16849
+ }
16850
+ /**
16851
+ * Factory routine to create a new unattached command.
16852
+ *
16853
+ * See .command() for creating an attached subcommand, which uses this routine to
16854
+ * create the command. You can override createCommand to customise subcommands.
16855
+ *
16856
+ * @param {string} [name]
16857
+ * @return {Command} new command
16858
+ */
16859
+ createCommand(name) {
16860
+ return new _Command12(name);
16861
+ }
16862
+ /**
16863
+ * You can customise the help with a subclass of Help by overriding createHelp,
16864
+ * or by overriding Help properties using configureHelp().
16865
+ *
16866
+ * @return {Help}
16867
+ */
16868
+ createHelp() {
16869
+ return Object.assign(new Help2(), this.configureHelp());
16870
+ }
16871
+ /**
16872
+ * You can customise the help by overriding Help properties using configureHelp(),
16873
+ * or with a subclass of Help by overriding createHelp().
16874
+ *
16875
+ * @param {object} [configuration] - configuration options
16876
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
16877
+ */
16878
+ configureHelp(configuration) {
16879
+ if (configuration === void 0) return this._helpConfiguration;
16880
+ this._helpConfiguration = configuration;
16881
+ return this;
16882
+ }
16883
+ /**
16884
+ * The default output goes to stdout and stderr. You can customise this for special
16885
+ * applications. You can also customise the display of errors by overriding outputError.
16886
+ *
16887
+ * The configuration properties are all functions:
16888
+ *
16889
+ * // change how output being written, defaults to stdout and stderr
16890
+ * writeOut(str)
16891
+ * writeErr(str)
16892
+ * // change how output being written for errors, defaults to writeErr
16893
+ * outputError(str, write) // used for displaying errors and not used for displaying help
16894
+ * // specify width for wrapping help
16895
+ * getOutHelpWidth()
16896
+ * getErrHelpWidth()
16897
+ * // color support, currently only used with Help
16898
+ * getOutHasColors()
16899
+ * getErrHasColors()
16900
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
16901
+ *
16902
+ * @param {object} [configuration] - configuration options
16903
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
16904
+ */
16905
+ configureOutput(configuration) {
16906
+ if (configuration === void 0) return this._outputConfiguration;
16907
+ Object.assign(this._outputConfiguration, configuration);
16908
+ return this;
16909
+ }
16910
+ /**
16911
+ * Display the help or a custom message after an error occurs.
16912
+ *
16913
+ * @param {(boolean|string)} [displayHelp]
16914
+ * @return {Command} `this` command for chaining
16915
+ */
16916
+ showHelpAfterError(displayHelp = true) {
16917
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
16918
+ this._showHelpAfterError = displayHelp;
16919
+ return this;
16920
+ }
16921
+ /**
16922
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
16923
+ *
16924
+ * @param {boolean} [displaySuggestion]
16925
+ * @return {Command} `this` command for chaining
16926
+ */
16927
+ showSuggestionAfterError(displaySuggestion = true) {
16928
+ this._showSuggestionAfterError = !!displaySuggestion;
16929
+ return this;
16930
+ }
16931
+ /**
16932
+ * Add a prepared subcommand.
16933
+ *
16934
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
16935
+ *
16936
+ * @param {Command} cmd - new subcommand
16937
+ * @param {object} [opts] - configuration options
16938
+ * @return {Command} `this` command for chaining
16939
+ */
16940
+ addCommand(cmd, opts) {
16941
+ if (!cmd._name) {
16942
+ throw new Error(`Command passed to .addCommand() must have a name
16943
+ - specify the name in Command constructor or using .name()`);
16944
+ }
16945
+ opts = opts || {};
16946
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
16947
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
16948
+ this._registerCommand(cmd);
16949
+ cmd.parent = this;
16950
+ cmd._checkForBrokenPassThrough();
16951
+ return this;
16952
+ }
16953
+ /**
16954
+ * Factory routine to create a new unattached argument.
16955
+ *
16956
+ * See .argument() for creating an attached argument, which uses this routine to
16957
+ * create the argument. You can override createArgument to return a custom argument.
16958
+ *
16959
+ * @param {string} name
16960
+ * @param {string} [description]
16961
+ * @return {Argument} new argument
16962
+ */
16963
+ createArgument(name, description) {
16964
+ return new Argument2(name, description);
16965
+ }
16966
+ /**
16967
+ * Define argument syntax for command.
16968
+ *
16969
+ * The default is that the argument is required, and you can explicitly
16970
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
16971
+ *
16972
+ * @example
16973
+ * program.argument('<input-file>');
16974
+ * program.argument('[output-file]');
16975
+ *
16976
+ * @param {string} name
16977
+ * @param {string} [description]
16978
+ * @param {(Function|*)} [fn] - custom argument processing function
16979
+ * @param {*} [defaultValue]
16980
+ * @return {Command} `this` command for chaining
16981
+ */
16982
+ argument(name, description, fn, defaultValue) {
16983
+ const argument = this.createArgument(name, description);
16984
+ if (typeof fn === "function") {
16985
+ argument.default(defaultValue).argParser(fn);
16986
+ } else {
16987
+ argument.default(fn);
16988
+ }
16989
+ this.addArgument(argument);
16990
+ return this;
16991
+ }
16992
+ /**
16993
+ * Define argument syntax for command, adding multiple at once (without descriptions).
16994
+ *
16995
+ * See also .argument().
16996
+ *
16997
+ * @example
16998
+ * program.arguments('<cmd> [env]');
16999
+ *
17000
+ * @param {string} names
17001
+ * @return {Command} `this` command for chaining
17002
+ */
17003
+ arguments(names) {
17004
+ names.trim().split(/ +/).forEach((detail) => {
17005
+ this.argument(detail);
17006
+ });
17007
+ return this;
17008
+ }
17009
+ /**
17010
+ * Define argument syntax for command, adding a prepared argument.
17011
+ *
17012
+ * @param {Argument} argument
17013
+ * @return {Command} `this` command for chaining
17014
+ */
17015
+ addArgument(argument) {
17016
+ const previousArgument = this.registeredArguments.slice(-1)[0];
17017
+ if (previousArgument && previousArgument.variadic) {
17018
+ throw new Error(
17019
+ `only the last argument can be variadic '${previousArgument.name()}'`
17020
+ );
17021
+ }
17022
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
17023
+ throw new Error(
17024
+ `a default value for a required argument is never used: '${argument.name()}'`
17025
+ );
17026
+ }
17027
+ this.registeredArguments.push(argument);
17028
+ return this;
17029
+ }
17030
+ /**
17031
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
17032
+ *
17033
+ * @example
17034
+ * program.helpCommand('help [cmd]');
17035
+ * program.helpCommand('help [cmd]', 'show help');
17036
+ * program.helpCommand(false); // suppress default help command
17037
+ * program.helpCommand(true); // add help command even if no subcommands
17038
+ *
17039
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
17040
+ * @param {string} [description] - custom description
17041
+ * @return {Command} `this` command for chaining
17042
+ */
17043
+ helpCommand(enableOrNameAndArgs, description) {
17044
+ if (typeof enableOrNameAndArgs === "boolean") {
17045
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
17046
+ return this;
17047
+ }
17048
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
17049
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
17050
+ const helpDescription = description ?? "display help for command";
17051
+ const helpCommand = this.createCommand(helpName);
17052
+ helpCommand.helpOption(false);
17053
+ if (helpArgs) helpCommand.arguments(helpArgs);
17054
+ if (helpDescription) helpCommand.description(helpDescription);
17055
+ this._addImplicitHelpCommand = true;
17056
+ this._helpCommand = helpCommand;
17057
+ return this;
17058
+ }
17059
+ /**
17060
+ * Add prepared custom help command.
17061
+ *
17062
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
17063
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
17064
+ * @return {Command} `this` command for chaining
17065
+ */
17066
+ addHelpCommand(helpCommand, deprecatedDescription) {
17067
+ if (typeof helpCommand !== "object") {
17068
+ this.helpCommand(helpCommand, deprecatedDescription);
17069
+ return this;
17070
+ }
17071
+ this._addImplicitHelpCommand = true;
17072
+ this._helpCommand = helpCommand;
17073
+ return this;
17074
+ }
17075
+ /**
17076
+ * Lazy create help command.
17077
+ *
17078
+ * @return {(Command|null)}
17079
+ * @package
17080
+ */
17081
+ _getHelpCommand() {
17082
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
17083
+ if (hasImplicitHelpCommand) {
17084
+ if (this._helpCommand === void 0) {
17085
+ this.helpCommand(void 0, void 0);
17086
+ }
17087
+ return this._helpCommand;
17088
+ }
17089
+ return null;
17090
+ }
17091
+ /**
17092
+ * Add hook for life cycle event.
17093
+ *
17094
+ * @param {string} event
17095
+ * @param {Function} listener
17096
+ * @return {Command} `this` command for chaining
17097
+ */
17098
+ hook(event, listener) {
17099
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
17100
+ if (!allowedValues.includes(event)) {
17101
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
17102
+ Expecting one of '${allowedValues.join("', '")}'`);
17103
+ }
17104
+ if (this._lifeCycleHooks[event]) {
17105
+ this._lifeCycleHooks[event].push(listener);
17106
+ } else {
17107
+ this._lifeCycleHooks[event] = [listener];
17108
+ }
17109
+ return this;
17110
+ }
17111
+ /**
17112
+ * Register callback to use as replacement for calling process.exit.
17113
+ *
17114
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
17115
+ * @return {Command} `this` command for chaining
17116
+ */
17117
+ exitOverride(fn) {
17118
+ if (fn) {
17119
+ this._exitCallback = fn;
17120
+ } else {
17121
+ this._exitCallback = (err) => {
17122
+ if (err.code !== "commander.executeSubCommandAsync") {
17123
+ throw err;
17124
+ } else {
17125
+ }
17126
+ };
17127
+ }
17128
+ return this;
17129
+ }
17130
+ /**
17131
+ * Call process.exit, and _exitCallback if defined.
17132
+ *
17133
+ * @param {number} exitCode exit code for using with process.exit
17134
+ * @param {string} code an id string representing the error
17135
+ * @param {string} message human-readable description of the error
17136
+ * @return never
17137
+ * @private
17138
+ */
17139
+ _exit(exitCode, code, message) {
17140
+ if (this._exitCallback) {
17141
+ this._exitCallback(new CommanderError2(exitCode, code, message));
17142
+ }
17143
+ process2.exit(exitCode);
17144
+ }
17145
+ /**
17146
+ * Register callback `fn` for the command.
17147
+ *
17148
+ * @example
17149
+ * program
17150
+ * .command('serve')
17151
+ * .description('start service')
17152
+ * .action(function() {
17153
+ * // do work here
17154
+ * });
17155
+ *
17156
+ * @param {Function} fn
17157
+ * @return {Command} `this` command for chaining
17158
+ */
17159
+ action(fn) {
17160
+ const listener = /* @__PURE__ */ __name((args) => {
17161
+ const expectedArgsCount = this.registeredArguments.length;
17162
+ const actionArgs = args.slice(0, expectedArgsCount);
17163
+ if (this._storeOptionsAsProperties) {
17164
+ actionArgs[expectedArgsCount] = this;
17165
+ } else {
17166
+ actionArgs[expectedArgsCount] = this.opts();
17167
+ }
17168
+ actionArgs.push(this);
17169
+ return fn.apply(this, actionArgs);
17170
+ }, "listener");
17171
+ this._actionHandler = listener;
17172
+ return this;
17173
+ }
17174
+ /**
17175
+ * Factory routine to create a new unattached option.
17176
+ *
17177
+ * See .option() for creating an attached option, which uses this routine to
17178
+ * create the option. You can override createOption to return a custom option.
17179
+ *
17180
+ * @param {string} flags
17181
+ * @param {string} [description]
17182
+ * @return {Option} new option
17183
+ */
17184
+ createOption(flags, description) {
17185
+ return new Option2(flags, description);
17186
+ }
17187
+ /**
17188
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
17189
+ *
17190
+ * @param {(Option | Argument)} target
17191
+ * @param {string} value
17192
+ * @param {*} previous
17193
+ * @param {string} invalidArgumentMessage
17194
+ * @private
17195
+ */
17196
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
17197
+ try {
17198
+ return target.parseArg(value, previous);
17199
+ } catch (err) {
17200
+ if (err.code === "commander.invalidArgument") {
17201
+ const message = `${invalidArgumentMessage} ${err.message}`;
17202
+ this.error(message, { exitCode: err.exitCode, code: err.code });
17203
+ }
17204
+ throw err;
17205
+ }
17206
+ }
17207
+ /**
17208
+ * Check for option flag conflicts.
17209
+ * Register option if no conflicts found, or throw on conflict.
17210
+ *
17211
+ * @param {Option} option
17212
+ * @private
17213
+ */
17214
+ _registerOption(option) {
17215
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
17216
+ if (matchingOption) {
17217
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
17218
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
17219
+ - already used by option '${matchingOption.flags}'`);
17220
+ }
17221
+ this.options.push(option);
17222
+ }
17223
+ /**
17224
+ * Check for command name and alias conflicts with existing commands.
17225
+ * Register command if no conflicts found, or throw on conflict.
17226
+ *
17227
+ * @param {Command} command
17228
+ * @private
17229
+ */
17230
+ _registerCommand(command) {
17231
+ const knownBy = /* @__PURE__ */ __name((cmd) => {
17232
+ return [cmd.name()].concat(cmd.aliases());
17233
+ }, "knownBy");
17234
+ const alreadyUsed = knownBy(command).find(
17235
+ (name) => this._findCommand(name)
17236
+ );
17237
+ if (alreadyUsed) {
17238
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
17239
+ const newCmd = knownBy(command).join("|");
17240
+ throw new Error(
17241
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
17242
+ );
17243
+ }
17244
+ this.commands.push(command);
17245
+ }
17246
+ /**
17247
+ * Add an option.
17248
+ *
17249
+ * @param {Option} option
17250
+ * @return {Command} `this` command for chaining
17251
+ */
17252
+ addOption(option) {
17253
+ this._registerOption(option);
17254
+ const oname = option.name();
17255
+ const name = option.attributeName();
17256
+ if (option.negate) {
17257
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
17258
+ if (!this._findOption(positiveLongFlag)) {
17259
+ this.setOptionValueWithSource(
17260
+ name,
17261
+ option.defaultValue === void 0 ? true : option.defaultValue,
17262
+ "default"
17263
+ );
17264
+ }
17265
+ } else if (option.defaultValue !== void 0) {
17266
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
17267
+ }
17268
+ const handleOptionValue = /* @__PURE__ */ __name((val, invalidValueMessage, valueSource) => {
17269
+ if (val == null && option.presetArg !== void 0) {
17270
+ val = option.presetArg;
17271
+ }
17272
+ const oldValue = this.getOptionValue(name);
17273
+ if (val !== null && option.parseArg) {
17274
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
17275
+ } else if (val !== null && option.variadic) {
17276
+ val = option._concatValue(val, oldValue);
17277
+ }
17278
+ if (val == null) {
17279
+ if (option.negate) {
17280
+ val = false;
17281
+ } else if (option.isBoolean() || option.optional) {
17282
+ val = true;
17283
+ } else {
17284
+ val = "";
17285
+ }
17286
+ }
17287
+ this.setOptionValueWithSource(name, val, valueSource);
17288
+ }, "handleOptionValue");
17289
+ this.on("option:" + oname, (val) => {
17290
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
17291
+ handleOptionValue(val, invalidValueMessage, "cli");
17292
+ });
17293
+ if (option.envVar) {
17294
+ this.on("optionEnv:" + oname, (val) => {
17295
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
17296
+ handleOptionValue(val, invalidValueMessage, "env");
17297
+ });
17298
+ }
17299
+ return this;
17300
+ }
17301
+ /**
17302
+ * Internal implementation shared by .option() and .requiredOption()
17303
+ *
17304
+ * @return {Command} `this` command for chaining
17305
+ * @private
17306
+ */
17307
+ _optionEx(config, flags, description, fn, defaultValue) {
17308
+ if (typeof flags === "object" && flags instanceof Option2) {
17309
+ throw new Error(
17310
+ "To add an Option object use addOption() instead of option() or requiredOption()"
17311
+ );
17312
+ }
17313
+ const option = this.createOption(flags, description);
17314
+ option.makeOptionMandatory(!!config.mandatory);
17315
+ if (typeof fn === "function") {
17316
+ option.default(defaultValue).argParser(fn);
17317
+ } else if (fn instanceof RegExp) {
17318
+ const regex = fn;
17319
+ fn = /* @__PURE__ */ __name((val, def) => {
17320
+ const m = regex.exec(val);
17321
+ return m ? m[0] : def;
17322
+ }, "fn");
17323
+ option.default(defaultValue).argParser(fn);
17324
+ } else {
17325
+ option.default(fn);
17326
+ }
17327
+ return this.addOption(option);
17328
+ }
17329
+ /**
17330
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
17331
+ *
17332
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
17333
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
17334
+ *
17335
+ * See the README for more details, and see also addOption() and requiredOption().
17336
+ *
17337
+ * @example
17338
+ * program
17339
+ * .option('-p, --pepper', 'add pepper')
17340
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
17341
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
17342
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
17343
+ *
17344
+ * @param {string} flags
17345
+ * @param {string} [description]
17346
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
17347
+ * @param {*} [defaultValue]
17348
+ * @return {Command} `this` command for chaining
17349
+ */
17350
+ option(flags, description, parseArg, defaultValue) {
17351
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
17352
+ }
17353
+ /**
17354
+ * Add a required option which must have a value after parsing. This usually means
17355
+ * the option must be specified on the command line. (Otherwise the same as .option().)
17356
+ *
17357
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
17358
+ *
17359
+ * @param {string} flags
17360
+ * @param {string} [description]
17361
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
17362
+ * @param {*} [defaultValue]
17363
+ * @return {Command} `this` command for chaining
17364
+ */
17365
+ requiredOption(flags, description, parseArg, defaultValue) {
17366
+ return this._optionEx(
17367
+ { mandatory: true },
17368
+ flags,
17369
+ description,
17370
+ parseArg,
17371
+ defaultValue
17372
+ );
17373
+ }
17374
+ /**
17375
+ * Alter parsing of short flags with optional values.
17376
+ *
17377
+ * @example
17378
+ * // for `.option('-f,--flag [value]'):
17379
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
17380
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
17381
+ *
17382
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
17383
+ * @return {Command} `this` command for chaining
17384
+ */
17385
+ combineFlagAndOptionalValue(combine = true) {
17386
+ this._combineFlagAndOptionalValue = !!combine;
17387
+ return this;
17388
+ }
17389
+ /**
17390
+ * Allow unknown options on the command line.
17391
+ *
17392
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
17393
+ * @return {Command} `this` command for chaining
17394
+ */
17395
+ allowUnknownOption(allowUnknown = true) {
17396
+ this._allowUnknownOption = !!allowUnknown;
17397
+ return this;
17398
+ }
17399
+ /**
17400
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
17401
+ *
17402
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
17403
+ * @return {Command} `this` command for chaining
17404
+ */
17405
+ allowExcessArguments(allowExcess = true) {
17406
+ this._allowExcessArguments = !!allowExcess;
17407
+ return this;
17408
+ }
17409
+ /**
17410
+ * Enable positional options. Positional means global options are specified before subcommands which lets
17411
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
17412
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
17413
+ *
17414
+ * @param {boolean} [positional]
17415
+ * @return {Command} `this` command for chaining
17416
+ */
17417
+ enablePositionalOptions(positional = true) {
17418
+ this._enablePositionalOptions = !!positional;
17419
+ return this;
17420
+ }
17421
+ /**
17422
+ * Pass through options that come after command-arguments rather than treat them as command-options,
17423
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
17424
+ * positional options to have been enabled on the program (parent commands).
17425
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
17426
+ *
17427
+ * @param {boolean} [passThrough] for unknown options.
17428
+ * @return {Command} `this` command for chaining
17429
+ */
17430
+ passThroughOptions(passThrough = true) {
17431
+ this._passThroughOptions = !!passThrough;
17432
+ this._checkForBrokenPassThrough();
17433
+ return this;
17434
+ }
17435
+ /**
17436
+ * @private
17437
+ */
17438
+ _checkForBrokenPassThrough() {
17439
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
17440
+ throw new Error(
17441
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
17442
+ );
17443
+ }
17444
+ }
17445
+ /**
17446
+ * Whether to store option values as properties on command object,
17447
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
17448
+ *
17449
+ * @param {boolean} [storeAsProperties=true]
17450
+ * @return {Command} `this` command for chaining
17451
+ */
17452
+ storeOptionsAsProperties(storeAsProperties = true) {
17453
+ if (this.options.length) {
17454
+ throw new Error("call .storeOptionsAsProperties() before adding options");
17455
+ }
17456
+ if (Object.keys(this._optionValues).length) {
17457
+ throw new Error(
17458
+ "call .storeOptionsAsProperties() before setting option values"
17459
+ );
17460
+ }
17461
+ this._storeOptionsAsProperties = !!storeAsProperties;
17462
+ return this;
17463
+ }
17464
+ /**
17465
+ * Retrieve option value.
17466
+ *
17467
+ * @param {string} key
17468
+ * @return {object} value
17469
+ */
17470
+ getOptionValue(key) {
17471
+ if (this._storeOptionsAsProperties) {
17472
+ return this[key];
17473
+ }
17474
+ return this._optionValues[key];
17475
+ }
17476
+ /**
17477
+ * Store option value.
17478
+ *
17479
+ * @param {string} key
17480
+ * @param {object} value
17481
+ * @return {Command} `this` command for chaining
17482
+ */
17483
+ setOptionValue(key, value) {
17484
+ return this.setOptionValueWithSource(key, value, void 0);
17485
+ }
17486
+ /**
17487
+ * Store option value and where the value came from.
17488
+ *
17489
+ * @param {string} key
17490
+ * @param {object} value
17491
+ * @param {string} source - expected values are default/config/env/cli/implied
17492
+ * @return {Command} `this` command for chaining
17493
+ */
17494
+ setOptionValueWithSource(key, value, source) {
17495
+ if (this._storeOptionsAsProperties) {
17496
+ this[key] = value;
17497
+ } else {
17498
+ this._optionValues[key] = value;
17499
+ }
17500
+ this._optionValueSources[key] = source;
17501
+ return this;
17502
+ }
17503
+ /**
17504
+ * Get source of option value.
17505
+ * Expected values are default | config | env | cli | implied
17506
+ *
17507
+ * @param {string} key
17508
+ * @return {string}
17509
+ */
17510
+ getOptionValueSource(key) {
17511
+ return this._optionValueSources[key];
17512
+ }
17513
+ /**
17514
+ * Get source of option value. See also .optsWithGlobals().
17515
+ * Expected values are default | config | env | cli | implied
17516
+ *
17517
+ * @param {string} key
17518
+ * @return {string}
17519
+ */
17520
+ getOptionValueSourceWithGlobals(key) {
17521
+ let source;
17522
+ this._getCommandAndAncestors().forEach((cmd) => {
17523
+ if (cmd.getOptionValueSource(key) !== void 0) {
17524
+ source = cmd.getOptionValueSource(key);
17525
+ }
17526
+ });
17527
+ return source;
17528
+ }
17529
+ /**
17530
+ * Get user arguments from implied or explicit arguments.
17531
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
17532
+ *
17533
+ * @private
17534
+ */
17535
+ _prepareUserArgs(argv, parseOptions) {
17536
+ if (argv !== void 0 && !Array.isArray(argv)) {
17537
+ throw new Error("first parameter to parse must be array or undefined");
17538
+ }
17539
+ parseOptions = parseOptions || {};
17540
+ if (argv === void 0 && parseOptions.from === void 0) {
17541
+ if (process2.versions?.electron) {
17542
+ parseOptions.from = "electron";
17543
+ }
17544
+ const execArgv = process2.execArgv ?? [];
17545
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
17546
+ parseOptions.from = "eval";
17547
+ }
17548
+ }
17549
+ if (argv === void 0) {
17550
+ argv = process2.argv;
17551
+ }
17552
+ this.rawArgs = argv.slice();
17553
+ let userArgs;
17554
+ switch (parseOptions.from) {
17555
+ case void 0:
17556
+ case "node":
17557
+ this._scriptPath = argv[1];
17558
+ userArgs = argv.slice(2);
17559
+ break;
17560
+ case "electron":
17561
+ if (process2.defaultApp) {
17562
+ this._scriptPath = argv[1];
17563
+ userArgs = argv.slice(2);
17564
+ } else {
17565
+ userArgs = argv.slice(1);
17566
+ }
17567
+ break;
17568
+ case "user":
17569
+ userArgs = argv.slice(0);
17570
+ break;
17571
+ case "eval":
17572
+ userArgs = argv.slice(1);
17573
+ break;
17574
+ default:
17575
+ throw new Error(
17576
+ `unexpected parse option { from: '${parseOptions.from}' }`
17577
+ );
17578
+ }
17579
+ if (!this._name && this._scriptPath)
17580
+ this.nameFromFilename(this._scriptPath);
17581
+ this._name = this._name || "program";
17582
+ return userArgs;
17583
+ }
17584
+ /**
17585
+ * Parse `argv`, setting options and invoking commands when defined.
17586
+ *
17587
+ * Use parseAsync instead of parse if any of your action handlers are async.
17588
+ *
17589
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
17590
+ *
17591
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
17592
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
17593
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
17594
+ * - `'user'`: just user arguments
17595
+ *
17596
+ * @example
17597
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
17598
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
17599
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
17600
+ *
17601
+ * @param {string[]} [argv] - optional, defaults to process.argv
17602
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
17603
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
17604
+ * @return {Command} `this` command for chaining
17605
+ */
17606
+ parse(argv, parseOptions) {
17607
+ this._prepareForParse();
17608
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
17609
+ this._parseCommand([], userArgs);
17610
+ return this;
17611
+ }
17612
+ /**
17613
+ * Parse `argv`, setting options and invoking commands when defined.
17614
+ *
17615
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
17616
+ *
17617
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
17618
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
17619
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
17620
+ * - `'user'`: just user arguments
17621
+ *
17622
+ * @example
17623
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
17624
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
17625
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
17626
+ *
17627
+ * @param {string[]} [argv]
17628
+ * @param {object} [parseOptions]
17629
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
17630
+ * @return {Promise}
17631
+ */
17632
+ async parseAsync(argv, parseOptions) {
17633
+ this._prepareForParse();
17634
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
17635
+ await this._parseCommand([], userArgs);
17636
+ return this;
17637
+ }
17638
+ _prepareForParse() {
17639
+ if (this._savedState === null) {
17640
+ this.saveStateBeforeParse();
17641
+ } else {
17642
+ this.restoreStateBeforeParse();
17643
+ }
17644
+ }
17645
+ /**
17646
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
17647
+ * Not usually called directly, but available for subclasses to save their custom state.
17648
+ *
17649
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
17650
+ */
17651
+ saveStateBeforeParse() {
17652
+ this._savedState = {
17653
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
17654
+ _name: this._name,
17655
+ // option values before parse have default values (including false for negated options)
17656
+ // shallow clones
17657
+ _optionValues: { ...this._optionValues },
17658
+ _optionValueSources: { ...this._optionValueSources }
17659
+ };
17660
+ }
17661
+ /**
17662
+ * Restore state before parse for calls after the first.
17663
+ * Not usually called directly, but available for subclasses to save their custom state.
17664
+ *
17665
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
17666
+ */
17667
+ restoreStateBeforeParse() {
17668
+ if (this._storeOptionsAsProperties)
17669
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
17670
+ - either make a new Command for each call to parse, or stop storing options as properties`);
17671
+ this._name = this._savedState._name;
17672
+ this._scriptPath = null;
17673
+ this.rawArgs = [];
17674
+ this._optionValues = { ...this._savedState._optionValues };
17675
+ this._optionValueSources = { ...this._savedState._optionValueSources };
17676
+ this.args = [];
17677
+ this.processedArgs = [];
17678
+ }
17679
+ /**
17680
+ * Throw if expected executable is missing. Add lots of help for author.
17681
+ *
17682
+ * @param {string} executableFile
17683
+ * @param {string} executableDir
17684
+ * @param {string} subcommandName
17685
+ */
17686
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
17687
+ if (fs3.existsSync(executableFile)) return;
17688
+ 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";
17689
+ const executableMissing = `'${executableFile}' does not exist
17690
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
17691
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17692
+ - ${executableDirMessage}`;
17693
+ throw new Error(executableMissing);
17694
+ }
17695
+ /**
17696
+ * Execute a sub-command executable.
17697
+ *
17698
+ * @private
17699
+ */
17700
+ _executeSubCommand(subcommand, args) {
17701
+ args = args.slice();
17702
+ let launchWithNode = false;
17703
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
17704
+ function findFile(baseDir, baseName) {
17705
+ const localBin = path5.resolve(baseDir, baseName);
17706
+ if (fs3.existsSync(localBin)) return localBin;
17707
+ if (sourceExt.includes(path5.extname(baseName))) return void 0;
17708
+ const foundExt = sourceExt.find(
17709
+ (ext) => fs3.existsSync(`${localBin}${ext}`)
17710
+ );
17711
+ if (foundExt) return `${localBin}${foundExt}`;
17712
+ return void 0;
17713
+ }
17714
+ __name(findFile, "findFile");
17715
+ this._checkForMissingMandatoryOptions();
17716
+ this._checkForConflictingOptions();
17717
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
17718
+ let executableDir = this._executableDir || "";
17719
+ if (this._scriptPath) {
17720
+ let resolvedScriptPath;
17721
+ try {
17722
+ resolvedScriptPath = fs3.realpathSync(this._scriptPath);
17723
+ } catch {
17724
+ resolvedScriptPath = this._scriptPath;
17725
+ }
17726
+ executableDir = path5.resolve(
17727
+ path5.dirname(resolvedScriptPath),
17728
+ executableDir
17729
+ );
17730
+ }
17731
+ if (executableDir) {
17732
+ let localFile = findFile(executableDir, executableFile);
17733
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
17734
+ const legacyName = path5.basename(
17735
+ this._scriptPath,
17736
+ path5.extname(this._scriptPath)
17737
+ );
17738
+ if (legacyName !== this._name) {
17739
+ localFile = findFile(
17740
+ executableDir,
17741
+ `${legacyName}-${subcommand._name}`
17742
+ );
17743
+ }
17744
+ }
17745
+ executableFile = localFile || executableFile;
17746
+ }
17747
+ launchWithNode = sourceExt.includes(path5.extname(executableFile));
17748
+ let proc;
17749
+ if (process2.platform !== "win32") {
17750
+ if (launchWithNode) {
17751
+ args.unshift(executableFile);
17752
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
17753
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
17754
+ } else {
17755
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
17756
+ }
17757
+ } else {
17758
+ this._checkForMissingExecutable(
17759
+ executableFile,
17760
+ executableDir,
17761
+ subcommand._name
17762
+ );
17763
+ args.unshift(executableFile);
17764
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
17765
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
17766
+ }
17767
+ if (!proc.killed) {
17768
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
17769
+ signals.forEach((signal) => {
17770
+ process2.on(signal, () => {
17771
+ if (proc.killed === false && proc.exitCode === null) {
17772
+ proc.kill(signal);
17773
+ }
17774
+ });
17775
+ });
17776
+ }
17777
+ const exitCallback = this._exitCallback;
17778
+ proc.on("close", (code) => {
17779
+ code = code ?? 1;
17780
+ if (!exitCallback) {
17781
+ process2.exit(code);
17782
+ } else {
17783
+ exitCallback(
17784
+ new CommanderError2(
17785
+ code,
17786
+ "commander.executeSubCommandAsync",
17787
+ "(close)"
17788
+ )
17789
+ );
17790
+ }
17791
+ });
17792
+ proc.on("error", (err) => {
17793
+ if (err.code === "ENOENT") {
17794
+ this._checkForMissingExecutable(
17795
+ executableFile,
17796
+ executableDir,
17797
+ subcommand._name
17798
+ );
17799
+ } else if (err.code === "EACCES") {
17800
+ throw new Error(`'${executableFile}' not executable`);
17801
+ }
17802
+ if (!exitCallback) {
17803
+ process2.exit(1);
17804
+ } else {
17805
+ const wrappedError = new CommanderError2(
17806
+ 1,
17807
+ "commander.executeSubCommandAsync",
17808
+ "(error)"
17809
+ );
17810
+ wrappedError.nestedError = err;
17811
+ exitCallback(wrappedError);
17812
+ }
17813
+ });
17814
+ this.runningCommand = proc;
17815
+ }
17816
+ /**
17817
+ * @private
17818
+ */
17819
+ _dispatchSubcommand(commandName, operands, unknown) {
17820
+ const subCommand = this._findCommand(commandName);
17821
+ if (!subCommand) this.help({ error: true });
17822
+ subCommand._prepareForParse();
17823
+ let promiseChain;
17824
+ promiseChain = this._chainOrCallSubCommandHook(
17825
+ promiseChain,
17826
+ subCommand,
17827
+ "preSubcommand"
17828
+ );
17829
+ promiseChain = this._chainOrCall(promiseChain, () => {
17830
+ if (subCommand._executableHandler) {
17831
+ this._executeSubCommand(subCommand, operands.concat(unknown));
17832
+ } else {
17833
+ return subCommand._parseCommand(operands, unknown);
17834
+ }
17835
+ });
17836
+ return promiseChain;
17837
+ }
17838
+ /**
17839
+ * Invoke help directly if possible, or dispatch if necessary.
17840
+ * e.g. help foo
17841
+ *
17842
+ * @private
17843
+ */
17844
+ _dispatchHelpCommand(subcommandName) {
17845
+ if (!subcommandName) {
17846
+ this.help();
17847
+ }
17848
+ const subCommand = this._findCommand(subcommandName);
17849
+ if (subCommand && !subCommand._executableHandler) {
17850
+ subCommand.help();
17851
+ }
17852
+ return this._dispatchSubcommand(
17853
+ subcommandName,
17854
+ [],
17855
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
17856
+ );
17857
+ }
17858
+ /**
17859
+ * Check this.args against expected this.registeredArguments.
17860
+ *
17861
+ * @private
17862
+ */
17863
+ _checkNumberOfArguments() {
17864
+ this.registeredArguments.forEach((arg, i) => {
17865
+ if (arg.required && this.args[i] == null) {
17866
+ this.missingArgument(arg.name());
17867
+ }
17868
+ });
17869
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
17870
+ return;
17871
+ }
17872
+ if (this.args.length > this.registeredArguments.length) {
17873
+ this._excessArguments(this.args);
17874
+ }
17875
+ }
17876
+ /**
17877
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
17878
+ *
17879
+ * @private
17880
+ */
17881
+ _processArguments() {
17882
+ const myParseArg = /* @__PURE__ */ __name((argument, value, previous) => {
17883
+ let parsedValue = value;
17884
+ if (value !== null && argument.parseArg) {
17885
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
17886
+ parsedValue = this._callParseArg(
17887
+ argument,
17888
+ value,
17889
+ previous,
17890
+ invalidValueMessage
17891
+ );
17892
+ }
17893
+ return parsedValue;
17894
+ }, "myParseArg");
17895
+ this._checkNumberOfArguments();
17896
+ const processedArgs = [];
17897
+ this.registeredArguments.forEach((declaredArg, index) => {
17898
+ let value = declaredArg.defaultValue;
17899
+ if (declaredArg.variadic) {
17900
+ if (index < this.args.length) {
17901
+ value = this.args.slice(index);
17902
+ if (declaredArg.parseArg) {
17903
+ value = value.reduce((processed, v) => {
17904
+ return myParseArg(declaredArg, v, processed);
17905
+ }, declaredArg.defaultValue);
17906
+ }
17907
+ } else if (value === void 0) {
17908
+ value = [];
17909
+ }
17910
+ } else if (index < this.args.length) {
17911
+ value = this.args[index];
17912
+ if (declaredArg.parseArg) {
17913
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
17914
+ }
17915
+ }
17916
+ processedArgs[index] = value;
17917
+ });
17918
+ this.processedArgs = processedArgs;
17919
+ }
17920
+ /**
17921
+ * Once we have a promise we chain, but call synchronously until then.
17922
+ *
17923
+ * @param {(Promise|undefined)} promise
17924
+ * @param {Function} fn
17925
+ * @return {(Promise|undefined)}
17926
+ * @private
17927
+ */
17928
+ _chainOrCall(promise, fn) {
17929
+ if (promise && promise.then && typeof promise.then === "function") {
17930
+ return promise.then(() => fn());
17931
+ }
17932
+ return fn();
17933
+ }
17934
+ /**
17935
+ *
17936
+ * @param {(Promise|undefined)} promise
17937
+ * @param {string} event
17938
+ * @return {(Promise|undefined)}
17939
+ * @private
17940
+ */
17941
+ _chainOrCallHooks(promise, event) {
17942
+ let result = promise;
17943
+ const hooks = [];
17944
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
17945
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
17946
+ hooks.push({ hookedCommand, callback });
17947
+ });
17948
+ });
17949
+ if (event === "postAction") {
17950
+ hooks.reverse();
17951
+ }
17952
+ hooks.forEach((hookDetail) => {
17953
+ result = this._chainOrCall(result, () => {
17954
+ return hookDetail.callback(hookDetail.hookedCommand, this);
17955
+ });
17956
+ });
17957
+ return result;
17958
+ }
17959
+ /**
17960
+ *
17961
+ * @param {(Promise|undefined)} promise
17962
+ * @param {Command} subCommand
17963
+ * @param {string} event
17964
+ * @return {(Promise|undefined)}
17965
+ * @private
17966
+ */
17967
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
17968
+ let result = promise;
17969
+ if (this._lifeCycleHooks[event] !== void 0) {
17970
+ this._lifeCycleHooks[event].forEach((hook) => {
17971
+ result = this._chainOrCall(result, () => {
17972
+ return hook(this, subCommand);
17973
+ });
17974
+ });
17975
+ }
17976
+ return result;
17977
+ }
17978
+ /**
17979
+ * Process arguments in context of this command.
17980
+ * Returns action result, in case it is a promise.
17981
+ *
17982
+ * @private
17983
+ */
17984
+ _parseCommand(operands, unknown) {
17985
+ const parsed = this.parseOptions(unknown);
17986
+ this._parseOptionsEnv();
17987
+ this._parseOptionsImplied();
17988
+ operands = operands.concat(parsed.operands);
17989
+ unknown = parsed.unknown;
17990
+ this.args = operands.concat(unknown);
17991
+ if (operands && this._findCommand(operands[0])) {
17992
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
17993
+ }
17994
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
17995
+ return this._dispatchHelpCommand(operands[1]);
17996
+ }
17997
+ if (this._defaultCommandName) {
17998
+ this._outputHelpIfRequested(unknown);
17999
+ return this._dispatchSubcommand(
18000
+ this._defaultCommandName,
18001
+ operands,
18002
+ unknown
18003
+ );
18004
+ }
18005
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
18006
+ this.help({ error: true });
18007
+ }
18008
+ this._outputHelpIfRequested(parsed.unknown);
18009
+ this._checkForMissingMandatoryOptions();
18010
+ this._checkForConflictingOptions();
18011
+ const checkForUnknownOptions = /* @__PURE__ */ __name(() => {
18012
+ if (parsed.unknown.length > 0) {
18013
+ this.unknownOption(parsed.unknown[0]);
18014
+ }
18015
+ }, "checkForUnknownOptions");
18016
+ const commandEvent = `command:${this.name()}`;
18017
+ if (this._actionHandler) {
18018
+ checkForUnknownOptions();
18019
+ this._processArguments();
18020
+ let promiseChain;
18021
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
18022
+ promiseChain = this._chainOrCall(
18023
+ promiseChain,
18024
+ () => this._actionHandler(this.processedArgs)
18025
+ );
18026
+ if (this.parent) {
18027
+ promiseChain = this._chainOrCall(promiseChain, () => {
18028
+ this.parent.emit(commandEvent, operands, unknown);
18029
+ });
18030
+ }
18031
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
18032
+ return promiseChain;
18033
+ }
18034
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
18035
+ checkForUnknownOptions();
18036
+ this._processArguments();
18037
+ this.parent.emit(commandEvent, operands, unknown);
18038
+ } else if (operands.length) {
18039
+ if (this._findCommand("*")) {
18040
+ return this._dispatchSubcommand("*", operands, unknown);
18041
+ }
18042
+ if (this.listenerCount("command:*")) {
18043
+ this.emit("command:*", operands, unknown);
18044
+ } else if (this.commands.length) {
18045
+ this.unknownCommand();
18046
+ } else {
18047
+ checkForUnknownOptions();
18048
+ this._processArguments();
18049
+ }
18050
+ } else if (this.commands.length) {
18051
+ checkForUnknownOptions();
18052
+ this.help({ error: true });
18053
+ } else {
18054
+ checkForUnknownOptions();
18055
+ this._processArguments();
18056
+ }
18057
+ }
18058
+ /**
18059
+ * Find matching command.
18060
+ *
18061
+ * @private
18062
+ * @return {Command | undefined}
18063
+ */
18064
+ _findCommand(name) {
18065
+ if (!name) return void 0;
18066
+ return this.commands.find(
18067
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
18068
+ );
18069
+ }
18070
+ /**
18071
+ * Return an option matching `arg` if any.
18072
+ *
18073
+ * @param {string} arg
18074
+ * @return {Option}
18075
+ * @package
18076
+ */
18077
+ _findOption(arg) {
18078
+ return this.options.find((option) => option.is(arg));
18079
+ }
18080
+ /**
18081
+ * Display an error message if a mandatory option does not have a value.
18082
+ * Called after checking for help flags in leaf subcommand.
18083
+ *
18084
+ * @private
18085
+ */
18086
+ _checkForMissingMandatoryOptions() {
18087
+ this._getCommandAndAncestors().forEach((cmd) => {
18088
+ cmd.options.forEach((anOption) => {
18089
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
18090
+ cmd.missingMandatoryOptionValue(anOption);
18091
+ }
18092
+ });
18093
+ });
18094
+ }
18095
+ /**
18096
+ * Display an error message if conflicting options are used together in this.
18097
+ *
18098
+ * @private
18099
+ */
18100
+ _checkForConflictingLocalOptions() {
18101
+ const definedNonDefaultOptions = this.options.filter((option) => {
18102
+ const optionKey = option.attributeName();
18103
+ if (this.getOptionValue(optionKey) === void 0) {
18104
+ return false;
18105
+ }
18106
+ return this.getOptionValueSource(optionKey) !== "default";
18107
+ });
18108
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
18109
+ (option) => option.conflictsWith.length > 0
18110
+ );
18111
+ optionsWithConflicting.forEach((option) => {
18112
+ const conflictingAndDefined = definedNonDefaultOptions.find(
18113
+ (defined) => option.conflictsWith.includes(defined.attributeName())
18114
+ );
18115
+ if (conflictingAndDefined) {
18116
+ this._conflictingOption(option, conflictingAndDefined);
18117
+ }
18118
+ });
18119
+ }
18120
+ /**
18121
+ * Display an error message if conflicting options are used together.
18122
+ * Called after checking for help flags in leaf subcommand.
18123
+ *
18124
+ * @private
18125
+ */
18126
+ _checkForConflictingOptions() {
18127
+ this._getCommandAndAncestors().forEach((cmd) => {
18128
+ cmd._checkForConflictingLocalOptions();
18129
+ });
18130
+ }
18131
+ /**
18132
+ * Parse options from `argv` removing known options,
18133
+ * and return argv split into operands and unknown arguments.
18134
+ *
18135
+ * Side effects: modifies command by storing options. Does not reset state if called again.
18136
+ *
18137
+ * Examples:
18138
+ *
18139
+ * argv => operands, unknown
18140
+ * --known kkk op => [op], []
18141
+ * op --known kkk => [op], []
18142
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
18143
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
18144
+ *
18145
+ * @param {string[]} argv
18146
+ * @return {{operands: string[], unknown: string[]}}
18147
+ */
18148
+ parseOptions(argv) {
18149
+ const operands = [];
18150
+ const unknown = [];
18151
+ let dest = operands;
18152
+ const args = argv.slice();
18153
+ function maybeOption(arg) {
18154
+ return arg.length > 1 && arg[0] === "-";
18155
+ }
18156
+ __name(maybeOption, "maybeOption");
18157
+ let activeVariadicOption = null;
18158
+ while (args.length) {
18159
+ const arg = args.shift();
18160
+ if (arg === "--") {
18161
+ if (dest === unknown) dest.push(arg);
18162
+ dest.push(...args);
18163
+ break;
18164
+ }
18165
+ if (activeVariadicOption && !maybeOption(arg)) {
18166
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
18167
+ continue;
18168
+ }
18169
+ activeVariadicOption = null;
18170
+ if (maybeOption(arg)) {
18171
+ const option = this._findOption(arg);
18172
+ if (option) {
18173
+ if (option.required) {
18174
+ const value = args.shift();
18175
+ if (value === void 0) this.optionMissingArgument(option);
18176
+ this.emit(`option:${option.name()}`, value);
18177
+ } else if (option.optional) {
18178
+ let value = null;
18179
+ if (args.length > 0 && !maybeOption(args[0])) {
18180
+ value = args.shift();
18181
+ }
18182
+ this.emit(`option:${option.name()}`, value);
18183
+ } else {
18184
+ this.emit(`option:${option.name()}`);
18185
+ }
18186
+ activeVariadicOption = option.variadic ? option : null;
18187
+ continue;
18188
+ }
18189
+ }
18190
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
18191
+ const option = this._findOption(`-${arg[1]}`);
18192
+ if (option) {
18193
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
18194
+ this.emit(`option:${option.name()}`, arg.slice(2));
18195
+ } else {
18196
+ this.emit(`option:${option.name()}`);
18197
+ args.unshift(`-${arg.slice(2)}`);
18198
+ }
18199
+ continue;
18200
+ }
18201
+ }
18202
+ if (/^--[^=]+=/.test(arg)) {
18203
+ const index = arg.indexOf("=");
18204
+ const option = this._findOption(arg.slice(0, index));
18205
+ if (option && (option.required || option.optional)) {
18206
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
18207
+ continue;
18208
+ }
18209
+ }
18210
+ if (maybeOption(arg)) {
18211
+ dest = unknown;
18212
+ }
18213
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
18214
+ if (this._findCommand(arg)) {
18215
+ operands.push(arg);
18216
+ if (args.length > 0) unknown.push(...args);
18217
+ break;
18218
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
18219
+ operands.push(arg);
18220
+ if (args.length > 0) operands.push(...args);
18221
+ break;
18222
+ } else if (this._defaultCommandName) {
18223
+ unknown.push(arg);
18224
+ if (args.length > 0) unknown.push(...args);
18225
+ break;
18226
+ }
18227
+ }
18228
+ if (this._passThroughOptions) {
18229
+ dest.push(arg);
18230
+ if (args.length > 0) dest.push(...args);
18231
+ break;
18232
+ }
18233
+ dest.push(arg);
18234
+ }
18235
+ return { operands, unknown };
18236
+ }
18237
+ /**
18238
+ * Return an object containing local option values as key-value pairs.
18239
+ *
18240
+ * @return {object}
18241
+ */
18242
+ opts() {
18243
+ if (this._storeOptionsAsProperties) {
18244
+ const result = {};
18245
+ const len = this.options.length;
18246
+ for (let i = 0; i < len; i++) {
18247
+ const key = this.options[i].attributeName();
18248
+ result[key] = key === this._versionOptionName ? this._version : this[key];
18249
+ }
18250
+ return result;
18251
+ }
18252
+ return this._optionValues;
18253
+ }
18254
+ /**
18255
+ * Return an object containing merged local and global option values as key-value pairs.
18256
+ *
18257
+ * @return {object}
18258
+ */
18259
+ optsWithGlobals() {
18260
+ return this._getCommandAndAncestors().reduce(
18261
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
18262
+ {}
18263
+ );
18264
+ }
18265
+ /**
18266
+ * Display error message and exit (or call exitOverride).
18267
+ *
18268
+ * @param {string} message
18269
+ * @param {object} [errorOptions]
18270
+ * @param {string} [errorOptions.code] - an id string representing the error
18271
+ * @param {number} [errorOptions.exitCode] - used with process.exit
18272
+ */
18273
+ error(message, errorOptions) {
18274
+ this._outputConfiguration.outputError(
18275
+ `${message}
18276
+ `,
18277
+ this._outputConfiguration.writeErr
18278
+ );
18279
+ if (typeof this._showHelpAfterError === "string") {
18280
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
18281
+ `);
18282
+ } else if (this._showHelpAfterError) {
18283
+ this._outputConfiguration.writeErr("\n");
18284
+ this.outputHelp({ error: true });
18285
+ }
18286
+ const config = errorOptions || {};
18287
+ const exitCode = config.exitCode || 1;
18288
+ const code = config.code || "commander.error";
18289
+ this._exit(exitCode, code, message);
18290
+ }
18291
+ /**
18292
+ * Apply any option related environment variables, if option does
18293
+ * not have a value from cli or client code.
18294
+ *
18295
+ * @private
18296
+ */
18297
+ _parseOptionsEnv() {
18298
+ this.options.forEach((option) => {
18299
+ if (option.envVar && option.envVar in process2.env) {
18300
+ const optionKey = option.attributeName();
18301
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
18302
+ this.getOptionValueSource(optionKey)
18303
+ )) {
18304
+ if (option.required || option.optional) {
18305
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
18306
+ } else {
18307
+ this.emit(`optionEnv:${option.name()}`);
18308
+ }
18309
+ }
18310
+ }
18311
+ });
18312
+ }
18313
+ /**
18314
+ * Apply any implied option values, if option is undefined or default value.
18315
+ *
18316
+ * @private
18317
+ */
18318
+ _parseOptionsImplied() {
18319
+ const dualHelper = new DualOptions(this.options);
18320
+ const hasCustomOptionValue = /* @__PURE__ */ __name((optionKey) => {
18321
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
18322
+ }, "hasCustomOptionValue");
18323
+ this.options.filter(
18324
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
18325
+ this.getOptionValue(option.attributeName()),
18326
+ option
18327
+ )
18328
+ ).forEach((option) => {
18329
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
18330
+ this.setOptionValueWithSource(
18331
+ impliedKey,
18332
+ option.implied[impliedKey],
18333
+ "implied"
18334
+ );
18335
+ });
18336
+ });
18337
+ }
18338
+ /**
18339
+ * Argument `name` is missing.
18340
+ *
18341
+ * @param {string} name
18342
+ * @private
18343
+ */
18344
+ missingArgument(name) {
18345
+ const message = `error: missing required argument '${name}'`;
18346
+ this.error(message, { code: "commander.missingArgument" });
18347
+ }
18348
+ /**
18349
+ * `Option` is missing an argument.
18350
+ *
18351
+ * @param {Option} option
18352
+ * @private
18353
+ */
18354
+ optionMissingArgument(option) {
18355
+ const message = `error: option '${option.flags}' argument missing`;
18356
+ this.error(message, { code: "commander.optionMissingArgument" });
18357
+ }
18358
+ /**
18359
+ * `Option` does not have a value, and is a mandatory option.
18360
+ *
18361
+ * @param {Option} option
18362
+ * @private
18363
+ */
18364
+ missingMandatoryOptionValue(option) {
18365
+ const message = `error: required option '${option.flags}' not specified`;
18366
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
18367
+ }
18368
+ /**
18369
+ * `Option` conflicts with another option.
18370
+ *
18371
+ * @param {Option} option
18372
+ * @param {Option} conflictingOption
18373
+ * @private
18374
+ */
18375
+ _conflictingOption(option, conflictingOption) {
18376
+ const findBestOptionFromValue = /* @__PURE__ */ __name((option2) => {
18377
+ const optionKey = option2.attributeName();
18378
+ const optionValue = this.getOptionValue(optionKey);
18379
+ const negativeOption = this.options.find(
18380
+ (target) => target.negate && optionKey === target.attributeName()
18381
+ );
18382
+ const positiveOption = this.options.find(
18383
+ (target) => !target.negate && optionKey === target.attributeName()
18384
+ );
18385
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
18386
+ return negativeOption;
18387
+ }
18388
+ return positiveOption || option2;
18389
+ }, "findBestOptionFromValue");
18390
+ const getErrorMessage = /* @__PURE__ */ __name((option2) => {
18391
+ const bestOption = findBestOptionFromValue(option2);
18392
+ const optionKey = bestOption.attributeName();
18393
+ const source = this.getOptionValueSource(optionKey);
18394
+ if (source === "env") {
18395
+ return `environment variable '${bestOption.envVar}'`;
18396
+ }
18397
+ return `option '${bestOption.flags}'`;
18398
+ }, "getErrorMessage");
18399
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
18400
+ this.error(message, { code: "commander.conflictingOption" });
18401
+ }
18402
+ /**
18403
+ * Unknown option `flag`.
18404
+ *
18405
+ * @param {string} flag
18406
+ * @private
18407
+ */
18408
+ unknownOption(flag) {
18409
+ if (this._allowUnknownOption) return;
18410
+ let suggestion = "";
18411
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
18412
+ let candidateFlags = [];
18413
+ let command = this;
18414
+ do {
18415
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
18416
+ candidateFlags = candidateFlags.concat(moreFlags);
18417
+ command = command.parent;
18418
+ } while (command && !command._enablePositionalOptions);
18419
+ suggestion = suggestSimilar(flag, candidateFlags);
18420
+ }
18421
+ const message = `error: unknown option '${flag}'${suggestion}`;
18422
+ this.error(message, { code: "commander.unknownOption" });
18423
+ }
18424
+ /**
18425
+ * Excess arguments, more than expected.
18426
+ *
18427
+ * @param {string[]} receivedArgs
18428
+ * @private
18429
+ */
18430
+ _excessArguments(receivedArgs) {
18431
+ if (this._allowExcessArguments) return;
18432
+ const expected = this.registeredArguments.length;
18433
+ const s = expected === 1 ? "" : "s";
18434
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
18435
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
18436
+ this.error(message, { code: "commander.excessArguments" });
18437
+ }
18438
+ /**
18439
+ * Unknown command.
18440
+ *
18441
+ * @private
18442
+ */
18443
+ unknownCommand() {
18444
+ const unknownName = this.args[0];
18445
+ let suggestion = "";
18446
+ if (this._showSuggestionAfterError) {
18447
+ const candidateNames = [];
18448
+ this.createHelp().visibleCommands(this).forEach((command) => {
18449
+ candidateNames.push(command.name());
18450
+ if (command.alias()) candidateNames.push(command.alias());
18451
+ });
18452
+ suggestion = suggestSimilar(unknownName, candidateNames);
18453
+ }
18454
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
18455
+ this.error(message, { code: "commander.unknownCommand" });
18456
+ }
18457
+ /**
18458
+ * Get or set the program version.
18459
+ *
18460
+ * This method auto-registers the "-V, --version" option which will print the version number.
18461
+ *
18462
+ * You can optionally supply the flags and description to override the defaults.
18463
+ *
18464
+ * @param {string} [str]
18465
+ * @param {string} [flags]
18466
+ * @param {string} [description]
18467
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
18468
+ */
18469
+ version(str, flags, description) {
18470
+ if (str === void 0) return this._version;
18471
+ this._version = str;
18472
+ flags = flags || "-V, --version";
18473
+ description = description || "output the version number";
18474
+ const versionOption = this.createOption(flags, description);
18475
+ this._versionOptionName = versionOption.attributeName();
18476
+ this._registerOption(versionOption);
18477
+ this.on("option:" + versionOption.name(), () => {
18478
+ this._outputConfiguration.writeOut(`${str}
18479
+ `);
18480
+ this._exit(0, "commander.version", str);
18481
+ });
18482
+ return this;
18483
+ }
18484
+ /**
18485
+ * Set the description.
18486
+ *
18487
+ * @param {string} [str]
18488
+ * @param {object} [argsDescription]
18489
+ * @return {(string|Command)}
18490
+ */
18491
+ description(str, argsDescription) {
18492
+ if (str === void 0 && argsDescription === void 0)
18493
+ return this._description;
18494
+ this._description = str;
18495
+ if (argsDescription) {
18496
+ this._argsDescription = argsDescription;
18497
+ }
18498
+ return this;
18499
+ }
18500
+ /**
18501
+ * Set the summary. Used when listed as subcommand of parent.
18502
+ *
18503
+ * @param {string} [str]
18504
+ * @return {(string|Command)}
18505
+ */
18506
+ summary(str) {
18507
+ if (str === void 0) return this._summary;
18508
+ this._summary = str;
18509
+ return this;
18510
+ }
18511
+ /**
18512
+ * Set an alias for the command.
18513
+ *
18514
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
18515
+ *
18516
+ * @param {string} [alias]
18517
+ * @return {(string|Command)}
18518
+ */
18519
+ alias(alias) {
18520
+ if (alias === void 0) return this._aliases[0];
18521
+ let command = this;
18522
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
18523
+ command = this.commands[this.commands.length - 1];
18524
+ }
18525
+ if (alias === command._name)
18526
+ throw new Error("Command alias can't be the same as its name");
18527
+ const matchingCommand = this.parent?._findCommand(alias);
18528
+ if (matchingCommand) {
18529
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
18530
+ throw new Error(
18531
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
18532
+ );
18533
+ }
18534
+ command._aliases.push(alias);
18535
+ return this;
18536
+ }
18537
+ /**
18538
+ * Set aliases for the command.
18539
+ *
18540
+ * Only the first alias is shown in the auto-generated help.
18541
+ *
18542
+ * @param {string[]} [aliases]
18543
+ * @return {(string[]|Command)}
18544
+ */
18545
+ aliases(aliases) {
18546
+ if (aliases === void 0) return this._aliases;
18547
+ aliases.forEach((alias) => this.alias(alias));
18548
+ return this;
18549
+ }
18550
+ /**
18551
+ * Set / get the command usage `str`.
18552
+ *
18553
+ * @param {string} [str]
18554
+ * @return {(string|Command)}
18555
+ */
18556
+ usage(str) {
18557
+ if (str === void 0) {
18558
+ if (this._usage) return this._usage;
18559
+ const args = this.registeredArguments.map((arg) => {
18560
+ return humanReadableArgName(arg);
18561
+ });
18562
+ return [].concat(
18563
+ this.options.length || this._helpOption !== null ? "[options]" : [],
18564
+ this.commands.length ? "[command]" : [],
18565
+ this.registeredArguments.length ? args : []
18566
+ ).join(" ");
18567
+ }
18568
+ this._usage = str;
18569
+ return this;
18570
+ }
18571
+ /**
18572
+ * Get or set the name of the command.
18573
+ *
18574
+ * @param {string} [str]
18575
+ * @return {(string|Command)}
18576
+ */
18577
+ name(str) {
18578
+ if (str === void 0) return this._name;
18579
+ this._name = str;
18580
+ return this;
18581
+ }
18582
+ /**
18583
+ * Set the name of the command from script filename, such as process.argv[1],
18584
+ * or require.main.filename, or __filename.
18585
+ *
18586
+ * (Used internally and public although not documented in README.)
18587
+ *
18588
+ * @example
18589
+ * program.nameFromFilename(require.main.filename);
18590
+ *
18591
+ * @param {string} filename
18592
+ * @return {Command}
18593
+ */
18594
+ nameFromFilename(filename) {
18595
+ this._name = path5.basename(filename, path5.extname(filename));
18596
+ return this;
18597
+ }
18598
+ /**
18599
+ * Get or set the directory for searching for executable subcommands of this command.
18600
+ *
18601
+ * @example
18602
+ * program.executableDir(__dirname);
18603
+ * // or
18604
+ * program.executableDir('subcommands');
18605
+ *
18606
+ * @param {string} [path]
18607
+ * @return {(string|null|Command)}
18608
+ */
18609
+ executableDir(path6) {
18610
+ if (path6 === void 0) return this._executableDir;
18611
+ this._executableDir = path6;
18612
+ return this;
18613
+ }
18614
+ /**
18615
+ * Return program help documentation.
18616
+ *
18617
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
18618
+ * @return {string}
18619
+ */
18620
+ helpInformation(contextOptions) {
18621
+ const helper = this.createHelp();
18622
+ const context = this._getOutputContext(contextOptions);
18623
+ helper.prepareContext({
18624
+ error: context.error,
18625
+ helpWidth: context.helpWidth,
18626
+ outputHasColors: context.hasColors
18627
+ });
18628
+ const text = helper.formatHelp(this, helper);
18629
+ if (context.hasColors) return text;
18630
+ return this._outputConfiguration.stripColor(text);
18631
+ }
18632
+ /**
18633
+ * @typedef HelpContext
18634
+ * @type {object}
18635
+ * @property {boolean} error
18636
+ * @property {number} helpWidth
18637
+ * @property {boolean} hasColors
18638
+ * @property {function} write - includes stripColor if needed
18639
+ *
18640
+ * @returns {HelpContext}
18641
+ * @private
18642
+ */
18643
+ _getOutputContext(contextOptions) {
18644
+ contextOptions = contextOptions || {};
18645
+ const error = !!contextOptions.error;
18646
+ let baseWrite;
18647
+ let hasColors;
18648
+ let helpWidth;
18649
+ if (error) {
18650
+ baseWrite = /* @__PURE__ */ __name((str) => this._outputConfiguration.writeErr(str), "baseWrite");
18651
+ hasColors = this._outputConfiguration.getErrHasColors();
18652
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
18653
+ } else {
18654
+ baseWrite = /* @__PURE__ */ __name((str) => this._outputConfiguration.writeOut(str), "baseWrite");
18655
+ hasColors = this._outputConfiguration.getOutHasColors();
18656
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
18657
+ }
18658
+ const write = /* @__PURE__ */ __name((str) => {
18659
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
18660
+ return baseWrite(str);
18661
+ }, "write");
18662
+ return { error, write, hasColors, helpWidth };
18663
+ }
18664
+ /**
18665
+ * Output help information for this command.
18666
+ *
18667
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
18668
+ *
18669
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
18670
+ */
18671
+ outputHelp(contextOptions) {
18672
+ let deprecatedCallback;
18673
+ if (typeof contextOptions === "function") {
18674
+ deprecatedCallback = contextOptions;
18675
+ contextOptions = void 0;
18676
+ }
18677
+ const outputContext = this._getOutputContext(contextOptions);
18678
+ const eventContext = {
18679
+ error: outputContext.error,
18680
+ write: outputContext.write,
18681
+ command: this
18682
+ };
18683
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
18684
+ this.emit("beforeHelp", eventContext);
18685
+ let helpInformation = this.helpInformation({ error: outputContext.error });
18686
+ if (deprecatedCallback) {
18687
+ helpInformation = deprecatedCallback(helpInformation);
18688
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
18689
+ throw new Error("outputHelp callback must return a string or a Buffer");
18690
+ }
18691
+ }
18692
+ outputContext.write(helpInformation);
18693
+ if (this._getHelpOption()?.long) {
18694
+ this.emit(this._getHelpOption().long);
18695
+ }
18696
+ this.emit("afterHelp", eventContext);
18697
+ this._getCommandAndAncestors().forEach(
18698
+ (command) => command.emit("afterAllHelp", eventContext)
18699
+ );
18700
+ }
18701
+ /**
18702
+ * You can pass in flags and a description to customise the built-in help option.
18703
+ * Pass in false to disable the built-in help option.
18704
+ *
18705
+ * @example
18706
+ * program.helpOption('-?, --help' 'show help'); // customise
18707
+ * program.helpOption(false); // disable
18708
+ *
18709
+ * @param {(string | boolean)} flags
18710
+ * @param {string} [description]
18711
+ * @return {Command} `this` command for chaining
18712
+ */
18713
+ helpOption(flags, description) {
18714
+ if (typeof flags === "boolean") {
18715
+ if (flags) {
18716
+ this._helpOption = this._helpOption ?? void 0;
18717
+ } else {
18718
+ this._helpOption = null;
18719
+ }
18720
+ return this;
18721
+ }
18722
+ flags = flags ?? "-h, --help";
18723
+ description = description ?? "display help for command";
18724
+ this._helpOption = this.createOption(flags, description);
18725
+ return this;
18726
+ }
18727
+ /**
18728
+ * Lazy create help option.
18729
+ * Returns null if has been disabled with .helpOption(false).
18730
+ *
18731
+ * @returns {(Option | null)} the help option
18732
+ * @package
18733
+ */
18734
+ _getHelpOption() {
18735
+ if (this._helpOption === void 0) {
18736
+ this.helpOption(void 0, void 0);
18737
+ }
18738
+ return this._helpOption;
18739
+ }
18740
+ /**
18741
+ * Supply your own option to use for the built-in help option.
18742
+ * This is an alternative to using helpOption() to customise the flags and description etc.
18743
+ *
18744
+ * @param {Option} option
18745
+ * @return {Command} `this` command for chaining
18746
+ */
18747
+ addHelpOption(option) {
18748
+ this._helpOption = option;
18749
+ return this;
18750
+ }
18751
+ /**
18752
+ * Output help information and exit.
18753
+ *
18754
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
18755
+ *
18756
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
18757
+ */
18758
+ help(contextOptions) {
18759
+ this.outputHelp(contextOptions);
18760
+ let exitCode = Number(process2.exitCode ?? 0);
18761
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
18762
+ exitCode = 1;
18763
+ }
18764
+ this._exit(exitCode, "commander.help", "(outputHelp)");
18765
+ }
18766
+ /**
18767
+ * // Do a little typing to coordinate emit and listener for the help text events.
18768
+ * @typedef HelpTextEventContext
18769
+ * @type {object}
18770
+ * @property {boolean} error
18771
+ * @property {Command} command
18772
+ * @property {function} write
18773
+ */
18774
+ /**
18775
+ * Add additional text to be displayed with the built-in help.
18776
+ *
18777
+ * Position is 'before' or 'after' to affect just this command,
18778
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
18779
+ *
18780
+ * @param {string} position - before or after built-in help
18781
+ * @param {(string | Function)} text - string to add, or a function returning a string
18782
+ * @return {Command} `this` command for chaining
18783
+ */
18784
+ addHelpText(position, text) {
18785
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
18786
+ if (!allowedValues.includes(position)) {
18787
+ throw new Error(`Unexpected value for position to addHelpText.
18788
+ Expecting one of '${allowedValues.join("', '")}'`);
18789
+ }
18790
+ const helpEvent = `${position}Help`;
18791
+ this.on(helpEvent, (context) => {
18792
+ let helpStr;
18793
+ if (typeof text === "function") {
18794
+ helpStr = text({ error: context.error, command: context.command });
18795
+ } else {
18796
+ helpStr = text;
18797
+ }
18798
+ if (helpStr) {
18799
+ context.write(`${helpStr}
18800
+ `);
18801
+ }
18802
+ });
18803
+ return this;
18804
+ }
18805
+ /**
18806
+ * Output help information if help flags specified
18807
+ *
18808
+ * @param {Array} args - array of options to search for help flags
18809
+ * @private
18810
+ */
18811
+ _outputHelpIfRequested(args) {
18812
+ const helpOption = this._getHelpOption();
18813
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
18814
+ if (helpRequested) {
18815
+ this.outputHelp();
18816
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
18817
+ }
18818
+ }
18819
+ };
18820
+ __name(_Command12, "Command");
18821
+ var Command13 = _Command12;
18822
+ function incrementNodeInspectorPort(args) {
18823
+ return args.map((arg) => {
18824
+ if (!arg.startsWith("--inspect")) {
18825
+ return arg;
18826
+ }
18827
+ let debugOption;
18828
+ let debugHost = "127.0.0.1";
18829
+ let debugPort = "9229";
18830
+ let match;
18831
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
18832
+ debugOption = match[1];
18833
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
18834
+ debugOption = match[1];
18835
+ if (/^\d+$/.test(match[3])) {
18836
+ debugPort = match[3];
18837
+ } else {
18838
+ debugHost = match[3];
18839
+ }
18840
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
18841
+ debugOption = match[1];
18842
+ debugHost = match[3];
18843
+ debugPort = match[4];
18844
+ }
18845
+ if (debugOption && debugPort !== "0") {
18846
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
18847
+ }
18848
+ return arg;
18849
+ });
18850
+ }
18851
+ __name(incrementNodeInspectorPort, "incrementNodeInspectorPort");
18852
+ function useColor() {
18853
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
18854
+ return false;
18855
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
18856
+ return true;
18857
+ return void 0;
18858
+ }
18859
+ __name(useColor, "useColor");
18860
+ exports.Command = Command13;
18861
+ exports.useColor = useColor;
18862
+ }
18863
+ });
18864
+
18865
+ // node_modules/commander/index.js
18866
+ var require_commander = __commonJS({
18867
+ "node_modules/commander/index.js"(exports) {
18868
+ "use strict";
18869
+ init_esm_shims();
18870
+ var { Argument: Argument2 } = require_argument();
18871
+ var { Command: Command13 } = require_command();
18872
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
18873
+ var { Help: Help2 } = require_help();
18874
+ var { Option: Option2 } = require_option();
18875
+ exports.program = new Command13();
18876
+ exports.createCommand = (name) => new Command13(name);
18877
+ exports.createOption = (flags, description) => new Option2(flags, description);
18878
+ exports.createArgument = (name, description) => new Argument2(name, description);
18879
+ exports.Command = Command13;
18880
+ exports.Option = Option2;
18881
+ exports.Argument = Argument2;
18882
+ exports.Help = Help2;
18883
+ exports.CommanderError = CommanderError2;
18884
+ exports.InvalidArgumentError = InvalidArgumentError2;
18885
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
18886
+ }
18887
+ });
18888
+
18889
+ // node_modules/commander/esm.mjs
18890
+ var import_index, program, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help;
18891
+ var init_esm = __esm({
18892
+ "node_modules/commander/esm.mjs"() {
18893
+ "use strict";
18894
+ init_esm_shims();
18895
+ import_index = __toESM(require_commander(), 1);
18896
+ ({
18897
+ program,
18898
+ createCommand,
18899
+ createArgument,
18900
+ createOption,
18901
+ CommanderError,
18902
+ InvalidArgumentError,
18903
+ InvalidOptionArgumentError,
18904
+ Command: (
18905
+ // deprecated old name
18906
+ Command
18907
+ ),
18908
+ Argument,
18909
+ Option,
18910
+ Help
18911
+ } = import_index.default);
18912
+ }
18913
+ });
18914
+
18915
+ // src/commands/load-plugin-bags.ts
18916
+ var load_plugin_bags_exports = {};
18917
+ __export(load_plugin_bags_exports, {
18918
+ Command: () => Command2,
15561
18919
  info: () => info
15562
18920
  });
15563
18921
  import { resolve as resolve5 } from "node:path";
@@ -15618,21 +18976,25 @@ async function loadPluginBags($tw2, store, engine) {
15618
18976
  });
15619
18977
  await engine.$transaction(prismaPromiseArray);
15620
18978
  }
15621
- var info, _Command, Command;
15622
- var init_mws_load_plugin_bags = __esm({
15623
- "src/commands/mws-load-plugin-bags.ts"() {
18979
+ var info, _Command, Command2;
18980
+ var init_load_plugin_bags = __esm({
18981
+ "src/commands/load-plugin-bags.ts"() {
15624
18982
  "use strict";
15625
18983
  init_esm_shims();
15626
18984
  init_TiddlerStore();
15627
18985
  init_utils2();
15628
18986
  info = {
15629
- name: "mws-load-plugin-bags",
18987
+ name: "load-plugin-bags",
18988
+ description: "Load plugin bags from the TiddlyWiki5 plugins folder",
18989
+ arguments: [
18990
+ ["path", "Path to the TiddlyWiki5 plugins folder"]
18991
+ ],
15630
18992
  synchronous: true
15631
18993
  };
15632
18994
  _Command = class _Command {
15633
- constructor(params, commander, callback) {
18995
+ constructor(params, commander2, callback) {
15634
18996
  this.params = params;
15635
- this.commander = commander;
18997
+ this.commander = commander2;
15636
18998
  this.callback = callback;
15637
18999
  }
15638
19000
  get $tw() {
@@ -15649,32 +19011,34 @@ var init_mws_load_plugin_bags = __esm({
15649
19011
  }
15650
19012
  };
15651
19013
  __name(_Command, "Command");
15652
- Command = _Command;
19014
+ Command2 = _Command;
15653
19015
  __name(loadPluginBags, "loadPluginBags");
15654
19016
  }
15655
19017
  });
15656
19018
 
15657
- // src/commands/mws-render-tiddlywiki5.ts
15658
- var mws_render_tiddlywiki5_exports = {};
15659
- __export(mws_render_tiddlywiki5_exports, {
15660
- Command: () => Command2,
19019
+ // src/commands/render-tiddlywiki5.ts
19020
+ var render_tiddlywiki5_exports = {};
19021
+ __export(render_tiddlywiki5_exports, {
19022
+ Command: () => Command3,
15661
19023
  info: () => info2
15662
19024
  });
15663
19025
  import { resolve as resolve6 } from "node:path";
15664
- var writeFileSync3, info2, _Command2, Command2;
15665
- var init_mws_render_tiddlywiki5 = __esm({
15666
- "src/commands/mws-render-tiddlywiki5.ts"() {
19026
+ var writeFileSync3, info2, _Command2, Command3;
19027
+ var init_render_tiddlywiki5 = __esm({
19028
+ "src/commands/render-tiddlywiki5.ts"() {
15667
19029
  "use strict";
15668
19030
  init_esm_shims();
15669
19031
  ({ writeFileSync: writeFileSync3 } = __require("fs"));
15670
19032
  info2 = {
15671
- name: "mws-render-tiddlywiki5",
19033
+ name: "render-tiddlywiki5",
19034
+ description: "Render the TiddlyWiki5 HTML file",
19035
+ arguments: [],
15672
19036
  synchronous: true
15673
19037
  };
15674
19038
  _Command2 = class _Command2 {
15675
- constructor(params, commander, callback) {
19039
+ constructor(params, commander2, callback) {
15676
19040
  this.params = params;
15677
- this.commander = commander;
19041
+ this.commander = commander2;
15678
19042
  this.callback = callback;
15679
19043
  }
15680
19044
  async execute() {
@@ -15698,14 +19062,14 @@ var init_mws_render_tiddlywiki5 = __esm({
15698
19062
  }
15699
19063
  };
15700
19064
  __name(_Command2, "Command");
15701
- Command2 = _Command2;
19065
+ Command3 = _Command2;
15702
19066
  }
15703
19067
  });
15704
19068
 
15705
- // src/commands/mws-load-wiki-folder.ts
15706
- var mws_load_wiki_folder_exports = {};
15707
- __export(mws_load_wiki_folder_exports, {
15708
- Command: () => Command3,
19069
+ // src/commands/load-wiki-folder.ts
19070
+ var load_wiki_folder_exports = {};
19071
+ __export(load_wiki_folder_exports, {
19072
+ Command: () => Command4,
15709
19073
  info: () => info3
15710
19074
  });
15711
19075
  import { resolve as resolve7 } from "path";
@@ -15762,20 +19126,28 @@ function loadWikiFolder({ $tw: $tw2, store, ...options }) {
15762
19126
  ...store.saveTiddlersFromPath_PrismaArray(tiddlersFromPath, options.bagName)
15763
19127
  ];
15764
19128
  }
15765
- var info3, _Command3, Command3;
15766
- var init_mws_load_wiki_folder = __esm({
15767
- "src/commands/mws-load-wiki-folder.ts"() {
19129
+ var info3, _Command3, Command4;
19130
+ var init_load_wiki_folder = __esm({
19131
+ "src/commands/load-wiki-folder.ts"() {
15768
19132
  "use strict";
15769
19133
  init_esm_shims();
15770
19134
  init_TiddlerStore();
15771
19135
  info3 = {
15772
- name: "mws-load-wiki-folder",
19136
+ name: "load-wiki-folder",
19137
+ description: "Load a TiddlyWiki folder into a bag",
19138
+ arguments: [
19139
+ ["path", "Path to the TiddlyWiki5 plugins folder"],
19140
+ ["bag-name", "Name of the bag to load tiddlers into"],
19141
+ ["bag-description", "Description of the bag"],
19142
+ ["recipe-name", "Name of the recipe to create"],
19143
+ ["recipe-description", "Description of the recipe"]
19144
+ ],
15773
19145
  synchronous: true
15774
19146
  };
15775
19147
  _Command3 = class _Command3 {
15776
- constructor(params, commander, callback) {
19148
+ constructor(params, commander2, callback) {
15777
19149
  this.params = params;
15778
- this.commander = commander;
19150
+ this.commander = commander2;
15779
19151
  this.callback = callback;
15780
19152
  }
15781
19153
  async execute() {
@@ -15796,36 +19168,40 @@ var init_mws_load_wiki_folder = __esm({
15796
19168
  }
15797
19169
  };
15798
19170
  __name(_Command3, "Command");
15799
- Command3 = _Command3;
19171
+ Command4 = _Command3;
15800
19172
  __name(makePluginBagName, "makePluginBagName");
15801
19173
  __name(loadWikiFolder, "loadWikiFolder");
15802
19174
  }
15803
19175
  });
15804
19176
 
15805
- // src/commands/mws-save-archive.ts
15806
- var mws_save_archive_exports = {};
15807
- __export(mws_save_archive_exports, {
15808
- Command: () => Command4,
19177
+ // src/commands/save-archive.ts
19178
+ var save_archive_exports = {};
19179
+ __export(save_archive_exports, {
19180
+ Command: () => Command5,
15809
19181
  info: () => info4
15810
19182
  });
15811
19183
  import { resolve as resolve8 } from "path";
15812
19184
  import * as _fsp from "fs/promises";
15813
- var fsp, info4, _Command4, Command4;
15814
- var init_mws_save_archive = __esm({
15815
- "src/commands/mws-save-archive.ts"() {
19185
+ var fsp, info4, _Command4, Command5;
19186
+ var init_save_archive = __esm({
19187
+ "src/commands/save-archive.ts"() {
15816
19188
  "use strict";
15817
19189
  init_esm_shims();
15818
19190
  init_TiddlerStore();
15819
19191
  init_utils2();
15820
19192
  fsp = createStrictAwaitProxy(_fsp);
15821
19193
  info4 = {
15822
- name: "mws-save-archive",
19194
+ name: "save-archive",
19195
+ description: "Save an archive of recipes, bags and tiddlers to a directory",
19196
+ arguments: [
19197
+ ["path", "Path to the directory to save the archive"]
19198
+ ],
15823
19199
  synchronous: true
15824
19200
  };
15825
19201
  _Command4 = class _Command4 {
15826
- constructor(params, commander, callback) {
19202
+ constructor(params, commander2, callback) {
15827
19203
  this.params = params;
15828
- this.commander = commander;
19204
+ this.commander = commander2;
15829
19205
  this.callback = callback;
15830
19206
  }
15831
19207
  get $tw() {
@@ -15904,35 +19280,39 @@ var init_mws_save_archive = __esm({
15904
19280
  }
15905
19281
  };
15906
19282
  __name(_Command4, "Command");
15907
- Command4 = _Command4;
19283
+ Command5 = _Command4;
15908
19284
  }
15909
19285
  });
15910
19286
 
15911
- // src/commands/mws-load-archive.ts
15912
- var mws_load_archive_exports = {};
15913
- __export(mws_load_archive_exports, {
15914
- Command: () => Command5,
19287
+ // src/commands/load-archive.ts
19288
+ var load_archive_exports = {};
19289
+ __export(load_archive_exports, {
19290
+ Command: () => Command6,
15915
19291
  info: () => info5
15916
19292
  });
15917
19293
  import { join as join2, resolve as resolve9 } from "path";
15918
19294
  import * as _fsp2 from "fs/promises";
15919
19295
  import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
15920
19296
  import { existsSync as existsSync3 } from "fs";
15921
- var fsp2, info5, _Command5, Command5, _Archiver, Archiver, _Archiver1, Archiver1, _Archiver2, Archiver2;
15922
- var init_mws_load_archive = __esm({
15923
- "src/commands/mws-load-archive.ts"() {
19297
+ var fsp2, info5, _Command5, Command6, _Archiver, Archiver, _Archiver1, Archiver1, _Archiver2, Archiver2;
19298
+ var init_load_archive = __esm({
19299
+ "src/commands/load-archive.ts"() {
15924
19300
  "use strict";
15925
19301
  init_esm_shims();
15926
19302
  init_utils2();
15927
19303
  fsp2 = createStrictAwaitProxy(_fsp2);
15928
19304
  info5 = {
15929
- name: "mws-load-archive",
19305
+ name: "load-archive",
19306
+ description: "Load a MWS archive into the database",
19307
+ arguments: [
19308
+ ["archivePath", "Path to the archive to load"]
19309
+ ],
15930
19310
  synchronous: true
15931
19311
  };
15932
19312
  _Command5 = class _Command5 {
15933
- constructor(params, commander, callback) {
19313
+ constructor(params, commander2, callback) {
15934
19314
  this.params = params;
15935
- this.commander = commander;
19315
+ this.commander = commander2;
15936
19316
  this.callback = callback;
15937
19317
  }
15938
19318
  async execute() {
@@ -15953,10 +19333,10 @@ var init_mws_load_archive = __esm({
15953
19333
  }
15954
19334
  };
15955
19335
  __name(_Command5, "Command");
15956
- Command5 = _Command5;
19336
+ Command6 = _Command5;
15957
19337
  _Archiver = class _Archiver {
15958
- constructor(commander) {
15959
- this.commander = commander;
19338
+ constructor(commander2) {
19339
+ this.commander = commander2;
15960
19340
  }
15961
19341
  };
15962
19342
  __name(_Archiver, "Archiver");
@@ -16153,27 +19533,29 @@ var init_mws_load_archive = __esm({
16153
19533
  }
16154
19534
  });
16155
19535
 
16156
- // src/commands/mws-init-store.ts
16157
- var mws_init_store_exports = {};
16158
- __export(mws_init_store_exports, {
16159
- Command: () => Command6,
19536
+ // src/commands/init-store.ts
19537
+ var init_store_exports = {};
19538
+ __export(init_store_exports, {
19539
+ Command: () => Command7,
16160
19540
  info: () => info6
16161
19541
  });
16162
19542
  import { resolve as resolve10 } from "node:path";
16163
- var info6, _Command6, Command6;
16164
- var init_mws_init_store = __esm({
16165
- "src/commands/mws-init-store.ts"() {
19543
+ var info6, _Command6, Command7;
19544
+ var init_init_store = __esm({
19545
+ "src/commands/init-store.ts"() {
16166
19546
  "use strict";
16167
19547
  init_esm_shims();
16168
19548
  init_utils2();
16169
19549
  info6 = {
16170
- name: "mws-init-store",
19550
+ name: "init-store",
19551
+ description: "Initialize the MWS Store",
19552
+ arguments: [],
16171
19553
  synchronous: true
16172
19554
  };
16173
19555
  _Command6 = class _Command6 {
16174
- constructor(params, commander, callback) {
19556
+ constructor(params, commander2, callback) {
16175
19557
  this.params = params;
16176
- this.commander = commander;
19558
+ this.commander = commander2;
16177
19559
  this.callback = callback;
16178
19560
  }
16179
19561
  get $tw() {
@@ -16203,26 +19585,26 @@ var init_mws_init_store = __esm({
16203
19585
  });
16204
19586
  const tweditions = resolve10(dist_require_resolve("tiddlywiki"), "../../editions");
16205
19587
  this.commander.addCommandTokens([
16206
- "--mws-load-plugin-bags",
16207
- "--mws-load-wiki-folder",
19588
+ "--load-plugin-bags",
19589
+ "--load-wiki-folder",
16208
19590
  dist_resolve("../editions/mws-docs"),
16209
19591
  "mws-docs",
16210
19592
  "MWS Documentation from https://mws.tiddlywiki.com",
16211
19593
  "mws-docs",
16212
19594
  "MWS Documentation from https://mws.tiddlywiki.com",
16213
- "--mws-load-wiki-folder",
19595
+ "--load-wiki-folder",
16214
19596
  resolve10(tweditions, "tw5.com"),
16215
19597
  "docs",
16216
19598
  "TiddlyWiki Documentation from https://tiddlywiki.com",
16217
19599
  "docs",
16218
19600
  "TiddlyWiki Documentation from https://tiddlywiki.com",
16219
- "--mws-load-wiki-folder",
19601
+ "--load-wiki-folder",
16220
19602
  resolve10(tweditions, "dev"),
16221
19603
  "dev",
16222
19604
  "TiddlyWiki Developer Documentation from https://tiddlywiki.com/dev",
16223
19605
  "dev-docs",
16224
19606
  "TiddlyWiki Developer Documentation from https://tiddlywiki.com/dev",
16225
- "--mws-load-wiki-folder",
19607
+ "--load-wiki-folder",
16226
19608
  resolve10(tweditions, "tour"),
16227
19609
  "tour",
16228
19610
  "TiddlyWiki Interactive Tour from https://tiddlywiki.com",
@@ -16234,14 +19616,14 @@ var init_mws_init_store = __esm({
16234
19616
  }
16235
19617
  };
16236
19618
  __name(_Command6, "Command");
16237
- Command6 = _Command6;
19619
+ Command7 = _Command6;
16238
19620
  }
16239
19621
  });
16240
19622
 
16241
- // src/commands/mws-listen.ts
16242
- var mws_listen_exports = {};
16243
- __export(mws_listen_exports, {
16244
- Command: () => Command7,
19623
+ // src/commands/listen.ts
19624
+ var listen_exports = {};
19625
+ __export(listen_exports, {
19626
+ Command: () => Command8,
16245
19627
  ListenerBase: () => ListenerBase,
16246
19628
  ListenerHTTP: () => ListenerHTTP,
16247
19629
  ListenerHTTPS: () => ListenerHTTPS,
@@ -16251,12 +19633,18 @@ import { ok as ok6 } from "assert";
16251
19633
  import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
16252
19634
  import { createServer } from "http";
16253
19635
  import * as http2 from "node:http2";
16254
- var _ListenerBase, ListenerBase, _ListenerHTTPS, ListenerHTTPS, _ListenerHTTP, ListenerHTTP, info7, _Command7, Command7;
16255
- var init_mws_listen = __esm({
16256
- "src/commands/mws-listen.ts"() {
19636
+ var info7, _ListenerBase, ListenerBase, _ListenerHTTPS, ListenerHTTPS, _ListenerHTTP, ListenerHTTP, _Command7, Command8;
19637
+ var init_listen = __esm({
19638
+ "src/commands/listen.ts"() {
16257
19639
  "use strict";
16258
19640
  init_esm_shims();
16259
19641
  init_router();
19642
+ info7 = {
19643
+ name: "listen",
19644
+ description: "Start the server and listen for incoming requests",
19645
+ arguments: [],
19646
+ synchronous: true
19647
+ };
16260
19648
  _ListenerBase = class _ListenerBase {
16261
19649
  constructor(server3, router, bindInfo) {
16262
19650
  this.server = server3;
@@ -16320,18 +19708,14 @@ var init_mws_listen = __esm({
16320
19708
  };
16321
19709
  __name(_ListenerHTTP, "ListenerHTTP");
16322
19710
  ListenerHTTP = _ListenerHTTP;
16323
- info7 = {
16324
- name: "mws-listen",
16325
- synchronous: true
16326
- };
16327
19711
  _Command7 = class _Command7 {
16328
- constructor(params, commander, listenConfig, onListenersCreated) {
19712
+ constructor(params, commander2, listenConfig, onListenersCreated) {
16329
19713
  this.params = params;
16330
- this.commander = commander;
19714
+ this.commander = commander2;
16331
19715
  if (this.params.length) throw `${info7.name}: No parameters allowed. Please put listener options in the config file.`;
16332
19716
  this.execute = async () => {
16333
19717
  this.commander.addCommandTokens([
16334
- "--mws-render-tiddlywiki5",
19718
+ "--render-tiddlywiki5",
16335
19719
  "--divider"
16336
19720
  ]);
16337
19721
  const router = await Router2.makeRouter(
@@ -16356,58 +19740,64 @@ var init_mws_listen = __esm({
16356
19740
  }
16357
19741
  };
16358
19742
  __name(_Command7, "Command");
16359
- Command7 = _Command7;
19743
+ Command8 = _Command7;
16360
19744
  }
16361
19745
  });
16362
19746
 
16363
19747
  // src/commands/divider.ts
16364
19748
  var divider_exports = {};
16365
19749
  __export(divider_exports, {
16366
- Command: () => Command8,
19750
+ Command: () => Command9,
16367
19751
  info: () => info8
16368
19752
  });
16369
- var info8, _Command8, Command8;
19753
+ var info8, _Command8, Command9;
16370
19754
  var init_divider = __esm({
16371
19755
  "src/commands/divider.ts"() {
16372
19756
  "use strict";
16373
19757
  init_esm_shims();
16374
19758
  info8 = {
16375
19759
  name: "divider",
16376
- synchronous: true
19760
+ description: "A no-op command to delimit param concatenation.",
19761
+ arguments: [],
19762
+ synchronous: true,
19763
+ internal: true
16377
19764
  };
16378
19765
  _Command8 = class _Command8 {
16379
- constructor(params, commander) {
19766
+ constructor(params, commander2) {
16380
19767
  this.params = params;
16381
- this.commander = commander;
19768
+ this.commander = commander2;
16382
19769
  if (this.params.length) throw `${info8.name}: No parameters allowed. This is a no-op command.`;
16383
19770
  }
16384
19771
  execute() {
16385
19772
  }
16386
19773
  };
16387
19774
  __name(_Command8, "Command");
16388
- Command8 = _Command8;
19775
+ Command9 = _Command8;
16389
19776
  }
16390
19777
  });
16391
19778
 
16392
19779
  // src/commands/tests-complete.ts
16393
19780
  var tests_complete_exports = {};
16394
19781
  __export(tests_complete_exports, {
16395
- Command: () => Command9,
19782
+ Command: () => Command10,
16396
19783
  info: () => info9
16397
19784
  });
16398
- var info9, _Command9, Command9;
19785
+ var info9, _Command9, Command10;
16399
19786
  var init_tests_complete = __esm({
16400
19787
  "src/commands/tests-complete.ts"() {
16401
19788
  "use strict";
16402
19789
  init_esm_shims();
16403
19790
  info9 = {
16404
19791
  name: "tests-complete",
16405
- synchronous: true
19792
+ description: "Tests completed successfully.",
19793
+ arguments: [],
19794
+ synchronous: true,
19795
+ internal: true
16406
19796
  };
16407
19797
  _Command9 = class _Command9 {
16408
- constructor(params, commander) {
19798
+ constructor(params, commander2) {
16409
19799
  this.params = params;
16410
- this.commander = commander;
19800
+ this.commander = commander2;
16411
19801
  }
16412
19802
  execute() {
16413
19803
  console.log("Tests completed successfully.");
@@ -16415,30 +19805,33 @@ var init_tests_complete = __esm({
16415
19805
  }
16416
19806
  };
16417
19807
  __name(_Command9, "Command");
16418
- Command9 = _Command9;
19808
+ Command10 = _Command9;
16419
19809
  }
16420
19810
  });
16421
19811
 
16422
- // src/commands/mws-client-build.ts
16423
- var mws_client_build_exports = {};
16424
- __export(mws_client_build_exports, {
16425
- Command: () => Command10,
19812
+ // src/commands/client-build.ts
19813
+ var client_build_exports = {};
19814
+ __export(client_build_exports, {
19815
+ Command: () => Command11,
16426
19816
  info: () => info10
16427
19817
  });
16428
- var info10, _Command10, Command10;
16429
- var init_mws_client_build = __esm({
16430
- "src/commands/mws-client-build.ts"() {
19818
+ var info10, _Command10, Command11;
19819
+ var init_client_build = __esm({
19820
+ "src/commands/client-build.ts"() {
16431
19821
  "use strict";
16432
19822
  init_esm_shims();
16433
19823
  init_setupDevServer();
16434
19824
  info10 = {
16435
- name: "mws-client-build",
16436
- synchronous: true
19825
+ name: "client-build",
19826
+ description: "Build the client for the TiddlyWiki5 server",
19827
+ arguments: [],
19828
+ synchronous: true,
19829
+ internal: true
16437
19830
  };
16438
19831
  _Command10 = class _Command10 {
16439
- constructor(params, commander) {
19832
+ constructor(params, commander2) {
16440
19833
  this.params = params;
16441
- this.commander = commander;
19834
+ this.commander = commander2;
16442
19835
  if (this.params.length) throw `${info10.name}: No parameters allowed. This is a no-op command.`;
16443
19836
  }
16444
19837
  async execute() {
@@ -16448,7 +19841,37 @@ var init_mws_client_build = __esm({
16448
19841
  }
16449
19842
  };
16450
19843
  __name(_Command10, "Command");
16451
- Command10 = _Command10;
19844
+ Command11 = _Command10;
19845
+ }
19846
+ });
19847
+
19848
+ // src/commands/help.ts
19849
+ var help_exports = {};
19850
+ __export(help_exports, {
19851
+ Command: () => Command12,
19852
+ info: () => info11
19853
+ });
19854
+ var info11, _Command11, Command12;
19855
+ var init_help = __esm({
19856
+ "src/commands/help.ts"() {
19857
+ "use strict";
19858
+ init_esm_shims();
19859
+ info11 = {
19860
+ name: "help",
19861
+ description: "Print this help message",
19862
+ arguments: [],
19863
+ synchronous: true
19864
+ };
19865
+ _Command11 = class _Command11 {
19866
+ constructor(params, commander2) {
19867
+ this.params = params;
19868
+ this.commander = commander2;
19869
+ }
19870
+ async execute() {
19871
+ }
19872
+ };
19873
+ __name(_Command11, "Command");
19874
+ Command12 = _Command11;
16452
19875
  }
16453
19876
  });
16454
19877
 
@@ -16458,27 +19881,29 @@ var init_commands = __esm({
16458
19881
  "src/commands/index.ts"() {
16459
19882
  "use strict";
16460
19883
  init_esm_shims();
16461
- init_mws_load_plugin_bags();
16462
- init_mws_render_tiddlywiki5();
16463
- init_mws_load_wiki_folder();
16464
- init_mws_save_archive();
16465
- init_mws_load_archive();
16466
- init_mws_init_store();
16467
- init_mws_listen();
19884
+ init_load_plugin_bags();
19885
+ init_render_tiddlywiki5();
19886
+ init_load_wiki_folder();
19887
+ init_save_archive();
19888
+ init_load_archive();
19889
+ init_init_store();
19890
+ init_listen();
16468
19891
  init_divider();
16469
19892
  init_tests_complete();
16470
- init_mws_client_build();
19893
+ init_client_build();
19894
+ init_help();
16471
19895
  commands = {
16472
- [info.name]: mws_load_plugin_bags_exports,
16473
- [info2.name]: mws_render_tiddlywiki5_exports,
16474
- [info3.name]: mws_load_wiki_folder_exports,
16475
- [info4.name]: mws_save_archive_exports,
16476
- [info5.name]: mws_load_archive_exports,
16477
- [info6.name]: mws_init_store_exports,
16478
- [info7.name]: mws_listen_exports,
19896
+ [info.name]: load_plugin_bags_exports,
19897
+ [info2.name]: render_tiddlywiki5_exports,
19898
+ [info3.name]: load_wiki_folder_exports,
19899
+ [info4.name]: save_archive_exports,
19900
+ [info5.name]: load_archive_exports,
19901
+ [info6.name]: init_store_exports,
19902
+ [info7.name]: listen_exports,
19903
+ [info11.name]: help_exports,
16479
19904
  [info8.name]: divider_exports,
16480
19905
  [info9.name]: tests_complete_exports,
16481
- [info10.name]: mws_client_build_exports
19906
+ [info10.name]: client_build_exports
16482
19907
  };
16483
19908
  }
16484
19909
  });
@@ -16497,11 +19922,9 @@ var init_sqlite_adapter = __esm({
16497
19922
  _SqliteAdapter = class _SqliteAdapter {
16498
19923
  constructor(databasePath) {
16499
19924
  this.databasePath = databasePath;
16500
- this.setupRequired = true;
16501
19925
  this.adapter = new PrismaBetterSQLite3({ url: "file:" + this.databasePath });
16502
19926
  }
16503
19927
  async init() {
16504
- this.setupRequired = false;
16505
19928
  const libsql = await this.adapter.connect();
16506
19929
  if (process.env.RUN_OLD_MWS_DB_SETUP_FOR_TESTING) {
16507
19930
  await libsql.executeScript(await readFile2(dist_resolve(
@@ -16569,7 +19992,7 @@ var init_sqlite_adapter = __esm({
16569
19992
  // src/commander.ts
16570
19993
  import * as path4 from "node:path";
16571
19994
  import { PrismaClient as PrismaClient2 } from "@prisma/client";
16572
- import { existsSync as existsSync6, mkdirSync as mkdirSync2 } from "node:fs";
19995
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync4 } from "node:fs";
16573
19996
  import { ok as ok7 } from "node:assert";
16574
19997
  var _StartupCommander, StartupCommander, _Commander, Commander;
16575
19998
  var init_commander = __esm({
@@ -16578,6 +20001,8 @@ var init_commander = __esm({
16578
20001
  init_esm_shims();
16579
20002
  init_sessions();
16580
20003
  init_attachments();
20004
+ init_utils2();
20005
+ init_esm();
16581
20006
  init_commands();
16582
20007
  init_sqlite_adapter();
16583
20008
  _StartupCommander = class _StartupCommander {
@@ -16585,6 +20010,8 @@ var init_commander = __esm({
16585
20010
  this.config = config;
16586
20011
  this.$tw = $tw2;
16587
20012
  this.PasswordService = PasswordService;
20013
+ /** Signals that database setup is required. May be set to false by any qualified setup command. */
20014
+ this.setupRequired = true;
16588
20015
  if (config.config?.pathPrefix) {
16589
20016
  ok7(config.config.pathPrefix.startsWith("/"), "pathPrefix must start with a slash");
16590
20017
  ok7(!config.config.pathPrefix.endsWith("/"), "pathPrefix must not end with a slash");
@@ -16619,6 +20046,7 @@ var init_commander = __esm({
16619
20046
  }
16620
20047
  async init() {
16621
20048
  await this.adapter.init();
20049
+ this.setupRequired = false;
16622
20050
  const users = await this.engine.users.count();
16623
20051
  if (!users) {
16624
20052
  this.setupRequired = true;
@@ -16627,13 +20055,6 @@ var init_commander = __esm({
16627
20055
  $transaction(fn, options) {
16628
20056
  return this.engine.$transaction(fn, options);
16629
20057
  }
16630
- /** Signals that database setup is required. May be set to false by any qualified setup command. */
16631
- get setupRequired() {
16632
- return this.adapter.setupRequired;
16633
- }
16634
- set setupRequired(v) {
16635
- this.adapter.setupRequired = v;
16636
- }
16637
20058
  };
16638
20059
  __name(_StartupCommander, "StartupCommander");
16639
20060
  StartupCommander = _StartupCommander;
@@ -16646,9 +20067,34 @@ var init_commander = __esm({
16646
20067
  config.listeners = [];
16647
20068
  config.onListenersCreated = void 0;
16648
20069
  this.create_mws_listen = (params) => {
16649
- return new mws_listen_exports.Command(params, this, listeners, onListenersCreated);
20070
+ console.log(listeners);
20071
+ return new listen_exports.Command(params, this, listeners, onListenersCreated);
16650
20072
  };
16651
20073
  }
20074
+ async init() {
20075
+ await super.init();
20076
+ this.program = new Command();
20077
+ const pkg = JSON.parse(readFileSync4(dist_resolve("../package.json"), "utf-8"));
20078
+ this.program.name("mws").description(pkg.description).version(pkg.version).enablePositionalOptions().passThroughOptions().showHelpAfterError();
20079
+ Object.keys(commands).forEach((key) => {
20080
+ const c = commands[key];
20081
+ if (c.info.internal) return;
20082
+ if (c.info.name === "help") return;
20083
+ const command = this.program.command(c.info.name);
20084
+ command.description(c.info.description);
20085
+ c.info.arguments.forEach(([name, description]) => {
20086
+ command.argument(name, description);
20087
+ });
20088
+ c.info.options?.forEach(([name, description]) => {
20089
+ command.option(name, description);
20090
+ });
20091
+ command.action((...args) => {
20092
+ const command2 = args.pop();
20093
+ const options = args.pop();
20094
+ this.addCommandTokens(["--" + command2.name(), ...args]);
20095
+ });
20096
+ });
20097
+ }
16652
20098
  static initCommands(moduleType) {
16653
20099
  if (moduleType) throw new Error("moduleType is not implemented");
16654
20100
  }
@@ -16664,15 +20110,34 @@ var init_commander = __esm({
16664
20110
  */
16665
20111
  execute(commandTokens) {
16666
20112
  console.log("Commander", commandTokens);
20113
+ this.setPromise();
20114
+ this.commandTokens = [];
20115
+ switch (commandTokens[0]) {
20116
+ // internal dev commands
20117
+ case "--client-build":
20118
+ this.commandTokens.push(...commandTokens);
20119
+ break;
20120
+ default:
20121
+ this.program.parse(commandTokens, { from: "user" });
20122
+ break;
20123
+ }
20124
+ this.executeNextCommand();
20125
+ return this.promise;
20126
+ }
20127
+ executeInternal(commandTokens) {
20128
+ console.log("Commander", commandTokens);
20129
+ this.setPromise();
16667
20130
  this.commandTokens = commandTokens;
20131
+ this.executeNextCommand();
20132
+ return this.promise;
20133
+ }
20134
+ setPromise() {
16668
20135
  this.promise = new Promise((resolve13, reject) => {
16669
20136
  this.callback = (err) => {
16670
20137
  if (err) this.$tw.utils.error("Error: " + err);
16671
20138
  err ? reject(err) : resolve13();
16672
20139
  };
16673
20140
  });
16674
- this.executeNextCommand();
16675
- return this.promise;
16676
20141
  }
16677
20142
  /*
16678
20143
  Execute the next command in the sequence
@@ -16699,17 +20164,17 @@ var init_commander = __esm({
16699
20164
  this.nextToken = nextCommand === -1 ? this.commandTokens.length : nextCommand;
16700
20165
  if (commandName !== divider_exports.info.name)
16701
20166
  console.log("Commander executing", commandName, params);
16702
- const paramsIfMandetory = !command.info.mandatoryParameters ? params : this.extractNamedParameters(params, command.info.mandatoryParameters);
16703
20167
  if (typeof params === "string") {
16704
20168
  this.callback(params);
16705
20169
  return;
16706
20170
  }
20171
+ console.log(params);
16707
20172
  new Promise(async (resolve13) => {
16708
- const { Command: Command11, info: info11 } = command;
20173
+ const { Command: Command13, info: info12 } = command;
16709
20174
  try {
16710
- c = info11.name === "mws-listen" ? this.create_mws_listen(paramsIfMandetory) : new Command11(paramsIfMandetory, this, info11.synchronous ? void 0 : resolve13);
20175
+ c = info12.name === listen_exports.info.name ? this.create_mws_listen(params) : new Command13(params, this, info12.synchronous ? void 0 : resolve13);
16711
20176
  err = await c.execute();
16712
- if (err || info11.synchronous) resolve13(err);
20177
+ if (err || info12.synchronous) resolve13(err);
16713
20178
  } catch (e) {
16714
20179
  resolve13(e);
16715
20180
  }
@@ -16855,21 +20320,22 @@ async function startServer(config) {
16855
20320
  const passwordMasterKey = readFileSync5(config.passwordMasterKeyFile, "utf8").trim();
16856
20321
  config.onPasswordKeyFileRead?.();
16857
20322
  config.wikiPath = resolve12(config.wikiPath);
16858
- const commander = new Commander(
20323
+ const commander2 = new Commander(
16859
20324
  config,
16860
20325
  await bootTiddlyWiki(config.wikiPath),
16861
20326
  await createPasswordService(passwordMasterKey)
16862
20327
  );
16863
- await commander.init();
20328
+ await commander2.init();
16864
20329
  const cli = process.argv.slice(2);
16865
- await commander.execute([
16866
- ...cli.length ? cli : [
16867
- "--mws-init-store",
16868
- "--mws-listen"
16869
- ]
16870
- ]);
16871
- if (commander.setupRequired) {
16872
- console.log("MWS setup required. Please run either --mws-init-store or --mws-load-archive");
20330
+ if (cli.length)
20331
+ await commander2.execute(cli);
20332
+ else
20333
+ await commander2.executeInternal([
20334
+ "--init-store",
20335
+ "--listen"
20336
+ ]);
20337
+ if (commander2.setupRequired) {
20338
+ console.log("MWS setup required. Please run either init-store or load-archive");
16873
20339
  process.exit(1);
16874
20340
  }
16875
20341
  }