@alcyone-labs/arg-parser 2.7.1 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -9,7 +9,7 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
9
9
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
10
10
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
11
11
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
12
- var __flags, _throwForDuplicateFlags, _appName, _appCommandName, _subCommandName, _parameters, _handler, _throwForDuplicateFlags2, _description, _handleErrors, _autoExit, _parentParser, _lastParseResult, _inheritParentFlags, _subCommands, _flagManager, _dxtGenerator, _configurationManager, _fuzzyMode, _mcpResourcesManager, _mcpPromptsManager, _mcpNotificationsManager, _ArgParserBase_instances, _identifyCommandChainAndParsers_fn, _handleGlobalChecks_fn, _validateMandatoryFlags_fn, _applyDefaultValues_fn, _prepareAndExecuteHandler_fn, parseFlags_fn, _enableFuzzyMode_fn, displayErrorAndExit_fn, _printRecursiveToConsole_fn, _buildRecursiveString_fn, _buildRecursiveJson_fn, _handleSaveToEnvFlag_fn, _handleBuildDxtFlag_fn, _handleMcpServeFlag_fn, _resolveLoggerConfigForServe_fn, _getMcpServerConfiguration_fn, _startUnifiedMcpServer_fn, _findAllMcpSubCommands_fn, _parseMcpTransportOptions_fn, _ArgParser_instances, _resolveLoggerConfig_fn, registerToolAsSubCommand_fn, _startSingleTransport_fn, processAsyncHandlerPromise_fn, _hasDate, _hasTime, _offset;
12
+ var __flags, _throwForDuplicateFlags, _appName, _appCommandName, _subCommandName, _parameters, _handler, _throwForDuplicateFlags2, _description, _handleErrors, _autoExit, _parentParser, _lastParseResult, _inheritParentFlags, _subCommands, _flagManager, _dxtGenerator, _configurationManager, _fuzzyMode, _dynamicFlagNames, _mcpResourcesManager, _mcpPromptsManager, _mcpNotificationsManager, _ArgParserBase_instances, registerDynamicFlags_fn, resetDynamicFlagsRecursive_fn, _preloadDynamicFlagsForHelp_fn, _identifyCommandChainAndParsers_fn, _handleGlobalChecks_fn, _validateMandatoryFlags_fn, _applyDefaultValues_fn, _prepareAndExecuteHandler_fn, parseFlags_fn, _enableFuzzyMode_fn, displayErrorAndExit_fn, _printRecursiveToConsole_fn, _buildRecursiveString_fn, _buildRecursiveJson_fn, _handleSaveToEnvFlag_fn, _handleBuildDxtFlag_fn, _handleMcpServeFlag_fn, _resolveLoggerConfigForServe_fn, _getMcpServerConfiguration_fn, _startUnifiedMcpServer_fn, _findAllMcpSubCommands_fn, _parseMcpTransportOptions_fn, _ArgParser_instances, _resolveLoggerConfig_fn, registerToolAsSubCommand_fn, _startSingleTransport_fn, processAsyncHandlerPromise_fn, _hasDate, _hasTime, _offset;
13
13
  import * as fs from "node:fs";
14
14
  import * as path from "node:path";
15
15
  import { fileURLToPath } from "node:url";
@@ -1036,13 +1036,17 @@ class ConfigurationManager {
1036
1036
  }
1037
1037
  }
1038
1038
  const zodDxtOptionsSchema = z.object({
1039
- sensitive: z.boolean().optional().describe("Whether this field should be marked as sensitive in DXT user_config"),
1039
+ sensitive: z.boolean().optional().describe(
1040
+ "Whether this field should be marked as sensitive in DXT user_config"
1041
+ ),
1040
1042
  localDefault: z.string().optional().describe("Default value specific to DXT sandbox environment"),
1041
1043
  type: z.enum(["string", "directory", "file", "boolean", "number"]).optional().describe("DXT input type - determines UI component in DXT clients"),
1042
1044
  multiple: z.boolean().optional().describe("Allow multiple values (for arrays)"),
1043
1045
  min: z.number().optional().describe("Minimum value (for number type)"),
1044
1046
  max: z.number().optional().describe("Maximum value (for number type)"),
1045
- default: z.any().optional().describe("DXT-specific default value (overrides localDefault if provided)"),
1047
+ default: z.any().optional().describe(
1048
+ "DXT-specific default value (overrides localDefault if provided)"
1049
+ ),
1046
1050
  title: z.string().optional().describe("Custom title for the user_config field")
1047
1051
  }).strict().refine(
1048
1052
  (data2) => {
@@ -1130,7 +1134,12 @@ const zodFlagSchema = z.object({
1130
1134
  env: z.union([z.string(), z.array(z.string())]).optional().describe(
1131
1135
  "Environment variables that should be set from this flag's value in DXT packages."
1132
1136
  ),
1133
- dxtOptions: zodDxtOptionsSchema.optional().describe("DXT-specific configuration options for enhanced DXT manifest generation")
1137
+ dxtOptions: zodDxtOptionsSchema.optional().describe(
1138
+ "DXT-specific configuration options for enhanced DXT manifest generation"
1139
+ ),
1140
+ dynamicRegister: z.custom((val) => typeof val === "function").optional().describe(
1141
+ "Optional callback that can register additional flags dynamically when this flag is present."
1142
+ )
1134
1143
  }).transform((obj) => {
1135
1144
  const newObj = { ...obj };
1136
1145
  if ("default" in newObj && newObj["default"] !== void 0 && !("defaultValue" in newObj)) {
@@ -3633,6 +3642,9 @@ const _FlagManager = class _FlagManager {
3633
3642
  hasFlag(name) {
3634
3643
  return __privateGet(this, __flags).has(name);
3635
3644
  }
3645
+ removeFlag(name) {
3646
+ return __privateGet(this, __flags).delete(name);
3647
+ }
3636
3648
  getFlag(name) {
3637
3649
  return __privateGet(this, __flags).get(name);
3638
3650
  }
@@ -3679,6 +3691,8 @@ const _ArgParserBase = class _ArgParserBase {
3679
3691
  __privateAdd(this, _dxtGenerator);
3680
3692
  __privateAdd(this, _configurationManager);
3681
3693
  __privateAdd(this, _fuzzyMode, false);
3694
+ // Track dynamically added flags so we can clean them between parses
3695
+ __privateAdd(this, _dynamicFlagNames, /* @__PURE__ */ new Set());
3682
3696
  // MCP-related managers
3683
3697
  __privateAdd(this, _mcpResourcesManager, new McpResourcesManager());
3684
3698
  __privateAdd(this, _mcpPromptsManager, new McpPromptsManager());
@@ -3794,10 +3808,14 @@ const _ArgParserBase = class _ArgParserBase {
3794
3808
  value = flag["type"].parse(parsedJson);
3795
3809
  } catch (error) {
3796
3810
  if (error instanceof SyntaxError) {
3797
- throw new Error(`Invalid JSON for flag '${flag["name"]}': ${error.message}`);
3811
+ throw new Error(
3812
+ `Invalid JSON for flag '${flag["name"]}': ${error.message}`
3813
+ );
3798
3814
  } else {
3799
3815
  const errorMessage = error instanceof Error ? error.message : String(error);
3800
- throw new Error(`Validation failed for flag '${flag["name"]}': ${errorMessage}`);
3816
+ throw new Error(
3817
+ `Validation failed for flag '${flag["name"]}': ${errorMessage}`
3818
+ );
3801
3819
  }
3802
3820
  }
3803
3821
  } else {
@@ -3938,9 +3956,13 @@ const _ArgParserBase = class _ArgParserBase {
3938
3956
  debug.log("ArgParserBase.parse() called with args:", processArgs);
3939
3957
  const shouldCheckAutoExecution = (options == null ? void 0 : options.importMetaUrl) && (options == null ? void 0 : options.autoExecute) !== false;
3940
3958
  if (shouldCheckAutoExecution) {
3941
- const isDirectExecution = _ArgParserBase.isExecutedDirectly(options.importMetaUrl);
3959
+ const isDirectExecution = _ArgParserBase.isExecutedDirectly(
3960
+ options.importMetaUrl
3961
+ );
3942
3962
  if (!isDirectExecution) {
3943
- debug.log("Auto-execution enabled but script is imported, skipping execution");
3963
+ debug.log(
3964
+ "Auto-execution enabled but script is imported, skipping execution"
3965
+ );
3944
3966
  return {};
3945
3967
  }
3946
3968
  }
@@ -3953,6 +3975,7 @@ const _ArgParserBase = class _ArgParserBase {
3953
3975
  );
3954
3976
  }
3955
3977
  }
3978
+ __privateMethod(this, _ArgParserBase_instances, resetDynamicFlagsRecursive_fn).call(this);
3956
3979
  const originalProcessArgs = [...processArgs];
3957
3980
  const shouldPreventExecution = typeof process !== "undefined" && (process.env["ARGPARSER_FUZZY_MODE"] === "true" || process.argv && process.argv.includes("--s-enable-fuzzy") && !processArgs.includes("--s-enable-fuzzy")) && !(options == null ? void 0 : options.skipHelpHandling);
3958
3981
  if (shouldPreventExecution) {
@@ -4206,7 +4229,9 @@ ${cyan("Flags:")}
4206
4229
  if (properties2.length <= 4) {
4207
4230
  typeDetails.push(`Properties: ${properties2.join(", ")}`);
4208
4231
  } else {
4209
- typeDetails.push(`Properties: ${properties2.slice(0, 4).join(", ")}, ... (${properties2.length} total)`);
4232
+ typeDetails.push(
4233
+ `Properties: ${properties2.slice(0, 4).join(", ")}, ... (${properties2.length} total)`
4234
+ );
4210
4235
  }
4211
4236
  }
4212
4237
  }
@@ -4388,10 +4413,62 @@ _flagManager = new WeakMap();
4388
4413
  _dxtGenerator = new WeakMap();
4389
4414
  _configurationManager = new WeakMap();
4390
4415
  _fuzzyMode = new WeakMap();
4416
+ _dynamicFlagNames = new WeakMap();
4391
4417
  _mcpResourcesManager = new WeakMap();
4392
4418
  _mcpPromptsManager = new WeakMap();
4393
4419
  _mcpNotificationsManager = new WeakMap();
4394
4420
  _ArgParserBase_instances = new WeakSet();
4421
+ // Register flags coming from dynamic loaders and track them for cleanup
4422
+ registerDynamicFlags_fn = function(flags) {
4423
+ if (!Array.isArray(flags) || flags.length === 0) return;
4424
+ for (const flag of flags) {
4425
+ const name = flag["name"];
4426
+ const existed = __privateGet(this, _flagManager).hasFlag(name);
4427
+ __privateGet(this, _flagManager).addFlag(flag);
4428
+ if (!existed) __privateGet(this, _dynamicFlagNames).add(name);
4429
+ }
4430
+ };
4431
+ // Remove dynamically registered flags on this parser and all sub-parsers
4432
+ resetDynamicFlagsRecursive_fn = function(parser = this) {
4433
+ var _a;
4434
+ for (const name of __privateGet(parser, _dynamicFlagNames)) {
4435
+ __privateGet(parser, _flagManager).removeFlag(name);
4436
+ }
4437
+ __privateGet(parser, _dynamicFlagNames).clear();
4438
+ for (const [, sub] of __privateGet(parser, _subCommands)) {
4439
+ if (sub && sub.parser instanceof _ArgParserBase) {
4440
+ __privateMethod(_a = sub.parser, _ArgParserBase_instances, resetDynamicFlagsRecursive_fn).call(_a);
4441
+ }
4442
+ }
4443
+ };
4444
+ _preloadDynamicFlagsForHelp_fn = async function(processArgs) {
4445
+ var _a;
4446
+ let currentParser = this;
4447
+ let remaining = [...processArgs];
4448
+ while (true) {
4449
+ let subIndex = -1;
4450
+ for (let i = 0; i < remaining.length; i++) {
4451
+ if (__privateGet(currentParser, _subCommands).has(remaining[i])) {
4452
+ subIndex = i;
4453
+ break;
4454
+ }
4455
+ }
4456
+ const segment = subIndex === -1 ? remaining : remaining.slice(0, subIndex);
4457
+ try {
4458
+ await __privateMethod(_a = currentParser, _ArgParserBase_instances, parseFlags_fn).call(_a, segment, {
4459
+ skipHelpHandling: true,
4460
+ dynamicHelpPreload: true
4461
+ });
4462
+ } catch {
4463
+ }
4464
+ if (subIndex === -1) break;
4465
+ const nextName = remaining[subIndex];
4466
+ const sub = __privateGet(currentParser, _subCommands).get(nextName);
4467
+ if (!sub || !(sub.parser instanceof _ArgParserBase)) break;
4468
+ currentParser = sub.parser;
4469
+ remaining = remaining.slice(subIndex + 1);
4470
+ }
4471
+ };
4395
4472
  _identifyCommandChainAndParsers_fn = function(argsToParse, currentParser, commandChainSoFar, parserChainSoFar) {
4396
4473
  let subCommandIndex = -1;
4397
4474
  let subCommandName = null;
@@ -4637,6 +4714,7 @@ _handleGlobalChecks_fn = async function(processArgs, options) {
4637
4714
  (arg) => helpOptions.includes(arg)
4638
4715
  );
4639
4716
  if (helpRequested) {
4717
+ await __privateMethod(this, _ArgParserBase_instances, _preloadDynamicFlagsForHelp_fn).call(this, processArgs);
4640
4718
  console.log(identifiedFinalParser.helpText());
4641
4719
  return this._handleExit(0, "Help displayed", "help");
4642
4720
  }
@@ -4761,8 +4839,95 @@ _prepareAndExecuteHandler_fn = function(handlerToExecute, finalArgs, skipHandler
4761
4839
  }
4762
4840
  };
4763
4841
  parseFlags_fn = async function(args, options) {
4764
- var _a, _b;
4765
- const flags = __privateGet(this, _flagManager).flags;
4842
+ var _a, _b, _c;
4843
+ let flags = __privateGet(this, _flagManager).flags;
4844
+ const dynamicCandidates = flags.filter(
4845
+ (f) => typeof f["dynamicRegister"] === "function"
4846
+ );
4847
+ if (dynamicCandidates.length > 0) {
4848
+ const loaderOutput = Object.fromEntries(
4849
+ dynamicCandidates.map((f) => [
4850
+ f["name"],
4851
+ f["allowMultiple"] ? [] : void 0
4852
+ ])
4853
+ );
4854
+ const tmpConsumed = /* @__PURE__ */ new Set();
4855
+ for (const flagToCheck of dynamicCandidates) {
4856
+ if (flagToCheck["allowLigature"] && !flagToCheck["flagOnly"]) {
4857
+ const regex = createRegExp(
4858
+ anyOf$1(
4859
+ ...flagToCheck["options"].map((option) => `${option}=`)
4860
+ ),
4861
+ oneOrMore(char).groupedAs("arg")
4862
+ );
4863
+ for (let i = 0; i < args.length; i++) {
4864
+ if (tmpConsumed.has(i)) continue;
4865
+ const matches = regex.exec(`${args[i]}`);
4866
+ if ((_a = matches == null ? void 0 : matches.groups) == null ? void 0 : _a["arg"]) {
4867
+ await this._addToOutput(
4868
+ flagToCheck,
4869
+ matches.groups["arg"],
4870
+ loaderOutput,
4871
+ options
4872
+ );
4873
+ tmpConsumed.add(i);
4874
+ if (!flagToCheck["allowMultiple"]) break;
4875
+ }
4876
+ }
4877
+ }
4878
+ }
4879
+ for (const flagToCheck of dynamicCandidates) {
4880
+ for (let index2 = 0; index2 < args.length; index2++) {
4881
+ if (tmpConsumed.has(index2)) continue;
4882
+ const value = args[index2];
4883
+ const nextIndex = index2 + 1;
4884
+ const nextValueExists = nextIndex < args.length;
4885
+ const nextValue = nextValueExists ? args[nextIndex] : void 0;
4886
+ const nextValueIsFlag = typeof nextValue === "string" && nextValue.startsWith("-");
4887
+ if (flagToCheck["options"].includes(value)) {
4888
+ tmpConsumed.add(index2);
4889
+ if (flagToCheck["flagOnly"]) {
4890
+ await this._addToOutput(flagToCheck, true, loaderOutput, options);
4891
+ } else if (nextValueExists && !nextValueIsFlag) {
4892
+ await this._addToOutput(
4893
+ flagToCheck,
4894
+ nextValue,
4895
+ loaderOutput,
4896
+ options
4897
+ );
4898
+ tmpConsumed.add(nextIndex);
4899
+ } else if (flagToCheck["type"] === Boolean) {
4900
+ await this._addToOutput(flagToCheck, true, loaderOutput, options);
4901
+ }
4902
+ if (!flagToCheck["allowMultiple"]) break;
4903
+ }
4904
+ }
4905
+ }
4906
+ for (const flagToCheck of dynamicCandidates) {
4907
+ const val = loaderOutput[flagToCheck["name"]];
4908
+ const hasValue = flagToCheck["allowMultiple"] ? Array.isArray(val) && val.length > 0 : val !== void 0;
4909
+ if (!hasValue) continue;
4910
+ const registerFlags = (newFlags) => {
4911
+ if (Array.isArray(newFlags) && newFlags.length) {
4912
+ __privateMethod(this, _ArgParserBase_instances, registerDynamicFlags_fn).call(this, newFlags);
4913
+ }
4914
+ };
4915
+ const dyn = flagToCheck["dynamicRegister"];
4916
+ if (typeof dyn === "function") {
4917
+ const maybe = dyn({
4918
+ value: val,
4919
+ argsSoFar: loaderOutput,
4920
+ parser: this,
4921
+ processArgs: args,
4922
+ forHelp: !!(options == null ? void 0 : options.dynamicHelpPreload),
4923
+ registerFlags
4924
+ });
4925
+ const awaited = maybe && typeof maybe.then === "function" ? await maybe : maybe;
4926
+ if (Array.isArray(awaited)) registerFlags(awaited);
4927
+ }
4928
+ }
4929
+ flags = __privateGet(this, _flagManager).flags;
4930
+ }
4766
4931
  const output = Object.fromEntries(
4767
4932
  flags.map((flag) => [
4768
4933
  flag["name"],
@@ -4782,10 +4947,10 @@ parseFlags_fn = async function(args, options) {
4782
4947
  if (consumedIndices.has(i)) continue;
4783
4948
  const itemToCheck = args[i];
4784
4949
  const matches = regex.exec(`${itemToCheck}`);
4785
- if ((_a = matches == null ? void 0 : matches.groups) == null ? void 0 : _a["arg"]) {
4950
+ if ((_b = matches == null ? void 0 : matches.groups) == null ? void 0 : _b["arg"]) {
4786
4951
  await this._addToOutput(
4787
4952
  flagToCheck,
4788
- (_b = matches == null ? void 0 : matches.groups) == null ? void 0 : _b["arg"],
4953
+ (_c = matches == null ? void 0 : matches.groups) == null ? void 0 : _c["arg"],
4789
4954
  output,
4790
4955
  options
4791
4956
  );