politty 0.11.1 → 0.11.3

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.
@@ -1,4 +1,5 @@
1
- import { a as toCamelCase, c as listSubCommands, d as resolveSubcommandWithAlias, f as isLazyCommand, l as resolveLazyCommand, m as resolveSubCommandMeta, n as getAllAliases, o as toKebabCase, r as getExtractedFields, s as listSubCommandNamesWithAliases, t as extractFields } from "./schema-extractor-GEuI_L0X.js";
1
+ import { a as toCamelCase, n as getAllAliases, o as toKebabCase, r as getExtractedFields, t as extractFields } from "./schema-extractor-wzJ1cGon.js";
2
+ import { a as resolveSubcommandWithAlias, c as resolveSubCommandMeta, n as listSubCommands, o as isLazyCommand, r as resolveLazyCommand, t as listSubCommandNamesWithAliases } from "./subcommand-router-CTzHPGzF.js";
2
3
  import { n as emptyLogs, r as mergeLogs, t as createLogCollector } from "./log-collector-DK32-73m.js";
3
4
  import { a as symbols, i as styles } from "./logger-DbDkjdfO.js";
4
5
  import { stripVTControlCharacters } from "node:util";
@@ -521,7 +522,8 @@ function renderBlock(block) {
521
522
  `${pipe} ${renderedHeaders.map((h, i) => styles.bold(alignText(h, colWidths[i], block.alignments[i] ?? "left"))).join(` ${pipe} `)} ${pipe}`,
522
523
  midBorder,
523
524
  ...renderedRows.map((row) => {
524
- return `${pipe} ${row.map((cell, i) => alignText(cell, colWidths[i], block.alignments[i] ?? "left")).join(` ${pipe} `)} ${pipe}`;
525
+ const cells = row.map((cell, i) => alignText(cell, colWidths[i], block.alignments[i] ?? "left"));
526
+ return `${pipe} ${cells.join(` ${pipe} `)} ${pipe}`;
525
527
  }),
526
528
  botBorder
527
529
  ].join("\n");
@@ -995,6 +997,30 @@ var DuplicateNegationError = class extends Error {
995
997
  this.name = "DuplicateNegationError";
996
998
  }
997
999
  };
1000
+ /**
1001
+ * Error thrown when a field name collides with a reserved, framework-injected
1002
+ * key on the final args object (e.g. `$source`).
1003
+ */
1004
+ var ReservedFieldNameError = class extends Error {
1005
+ constructor(message) {
1006
+ super(message);
1007
+ this.name = "ReservedFieldNameError";
1008
+ }
1009
+ };
1010
+ /**
1011
+ * Error thrown when a global field and a same-named local field have
1012
+ * different definitions (per `extractFields()`'s type bucket, whether the
1013
+ * field is positional, and enum values). Only exactly-matching definitions
1014
+ * are allowed to share a name across global/local schemas — anything else
1015
+ * is rejected at validation time rather than risking a value from one
1016
+ * schema silently flowing into the other.
1017
+ */
1018
+ var FieldTypeConflictError = class extends Error {
1019
+ constructor(message) {
1020
+ super(message);
1021
+ this.name = "FieldTypeConflictError";
1022
+ }
1023
+ };
998
1024
 
999
1025
  //#endregion
1000
1026
  //#region src/validator/command-validator.ts
@@ -1196,6 +1222,29 @@ function checkReservedAliases(extracted, commandPath) {
1196
1222
  return errors;
1197
1223
  }
1198
1224
  /**
1225
+ * Check for field names starting with `$`.
1226
+ *
1227
+ * The `$` prefix is reserved for framework-injected helpers on the final
1228
+ * args object (e.g. `$source`). It is also impractical as a real CLI flag
1229
+ * since an unquoted `$name` is expanded by the shell before it ever reaches
1230
+ * the program, so this is rejected outright rather than merely discouraged.
1231
+ *
1232
+ * Aliases can't start with `$` (schema extraction already restricts alias
1233
+ * characters to `[A-Za-z0-9-]`), and `cliName` is derived from `name` via
1234
+ * `toKebabCase`, which never strips or moves a leading `$` — so checking
1235
+ * `field.name` alone covers every way `$` could reach the final args object.
1236
+ */
1237
+ function checkReservedFieldNames(extracted, commandPath) {
1238
+ const errors = [];
1239
+ for (const field of extracted.fields) if (field.name.startsWith("$")) errors.push({
1240
+ commandPath,
1241
+ type: "reserved_field_name",
1242
+ message: `Field "${field.name}" starts with "$", which is reserved for framework-injected helpers (e.g. $source).`,
1243
+ field: field.name
1244
+ });
1245
+ return errors;
1246
+ }
1247
+ /**
1199
1248
  * Validate that no duplicate field names exist
1200
1249
  *
1201
1250
  * @param extracted - Extracted fields from schema
@@ -1262,6 +1311,28 @@ function validateReservedAliases(extracted, _hasSubCommands) {
1262
1311
  }
1263
1312
  }
1264
1313
  /**
1314
+ * Validate that no field name starts with `$`
1315
+ *
1316
+ * The `$` prefix is reserved for framework-injected helpers on the final
1317
+ * args object (e.g. `$source`), and is unusable as a real CLI flag anyway
1318
+ * since an unquoted `$name` gets shell-expanded before the program sees it.
1319
+ *
1320
+ * Checking `field.name` alone is sufficient: aliases can't start with `$`
1321
+ * (schema extraction already restricts alias characters to `[A-Za-z0-9-]`),
1322
+ * and `cliName` is derived from `name` via `toKebabCase`, which never strips
1323
+ * or moves a leading `$`. See {@link checkReservedFieldNames}.
1324
+ *
1325
+ * @param extracted - Extracted fields from schema
1326
+ * @throws {ReservedFieldNameError} If a field name starts with "$"
1327
+ */
1328
+ function validateReservedFieldNames(extracted) {
1329
+ const errors = checkReservedFieldNames(extracted, []);
1330
+ if (errors.length > 0) {
1331
+ const err = errors[0];
1332
+ throw new ReservedFieldNameError(err.message);
1333
+ }
1334
+ }
1335
+ /**
1265
1336
  * Validate that custom boolean negation names do not collide with anything
1266
1337
  *
1267
1338
  * @param extracted - Extracted fields from schema
@@ -1288,21 +1359,76 @@ function validateCaseVariantCollisions(extracted) {
1288
1359
  }
1289
1360
  }
1290
1361
  /**
1291
- * Validate that no case-variant collisions exist between two schemas
1292
- * (e.g., global args and command args).
1293
- *
1294
- * @param extractedA - Extracted fields from first schema (e.g., global args)
1295
- * @param extractedB - Extracted fields from second schema (e.g., command args)
1296
- * @throws {CaseVariantCollisionError} If cross-schema case-variant collisions are found
1362
+ * Check whether two same-named fields from different schemas (e.g. global
1363
+ * args and command args) have identical definitions. Only the facts
1364
+ * `extractFields()` already exposes are compared: the coarse type bucket,
1365
+ * whether the field is positional, and, for enum-like fields, the exact
1366
+ * set of allowed values. Anything `extractFields()` can't see (e.g. a
1367
+ * `.refine()`) is intentionally not compared — this is a coarse, cheap
1368
+ * equality check, not a full schema comparison.
1297
1369
  */
1298
- function validateCrossSchemaCollisions(extractedA, extractedB) {
1370
+ function fieldsAreIdentical(a, b) {
1371
+ if (a.type !== b.type) return false;
1372
+ if (a.positional !== b.positional) return false;
1373
+ const aEnum = a.enumValues;
1374
+ const bEnum = b.enumValues;
1375
+ if (!aEnum && !bEnum) return true;
1376
+ if (!aEnum || !bEnum) return false;
1377
+ const aSet = new Set(aEnum);
1378
+ const bSet = new Set(bEnum);
1379
+ if (aSet.size !== bSet.size) return false;
1380
+ for (const value of aSet) if (!bSet.has(value)) return false;
1381
+ return true;
1382
+ }
1383
+ /**
1384
+ * Check for cross-schema collisions between two schemas (e.g., global args
1385
+ * and command args): neither a case-variant collision (same canonical name,
1386
+ * different spelling) nor a same-named field with a different definition
1387
+ * (same spelling, but the two schemas don't agree on what values are valid).
1388
+ */
1389
+ function checkCrossSchemaCollisions(extractedA, extractedB, commandPath) {
1390
+ const errors = [];
1299
1391
  const canonicalMap = /* @__PURE__ */ new Map();
1300
- for (const field of extractedA.fields) canonicalMap.set(toCamelCase(field.name), field.name);
1392
+ for (const field of extractedA.fields) canonicalMap.set(toCamelCase(field.name), field);
1301
1393
  for (const field of extractedB.fields) {
1302
1394
  const camel = toCamelCase(field.name);
1303
1395
  const existing = canonicalMap.get(camel);
1304
- if (existing && existing !== field.name) throw new CaseVariantCollisionError(`Global field "${existing}" and command field "${field.name}" are case variants of each other and would collide.`);
1396
+ if (!existing) continue;
1397
+ if (existing.name !== field.name) {
1398
+ errors.push({
1399
+ commandPath,
1400
+ type: "case_variant_collision",
1401
+ message: `Global field "${existing.name}" and command field "${field.name}" are case variants of each other and would collide.`,
1402
+ field: field.name
1403
+ });
1404
+ continue;
1405
+ }
1406
+ if (!fieldsAreIdentical(existing, field)) errors.push({
1407
+ commandPath,
1408
+ type: "field_type_conflict",
1409
+ message: `Global field "${existing.name}" and command field "${field.name}" share the same name but have different definitions.`,
1410
+ field: field.name
1411
+ });
1305
1412
  }
1413
+ return errors;
1414
+ }
1415
+ /**
1416
+ * Validate that no cross-schema collisions exist between two schemas
1417
+ * (e.g., global args and command args): neither a case-variant collision
1418
+ * (same canonical name, different spelling) nor a same-named field with a
1419
+ * different definition (same spelling, but the two schemas don't agree on
1420
+ * what values are valid).
1421
+ *
1422
+ * @param extractedA - Extracted fields from first schema (e.g., global args)
1423
+ * @param extractedB - Extracted fields from second schema (e.g., command args)
1424
+ * @throws {CaseVariantCollisionError} If cross-schema case-variant collisions are found
1425
+ * @throws {FieldTypeConflictError} If a same-named field has a different definition on each schema
1426
+ */
1427
+ function validateCrossSchemaCollisions(extractedA, extractedB) {
1428
+ const err = checkCrossSchemaCollisions(extractedA, extractedB, [])[0];
1429
+ if (!err) return;
1430
+ if (err.type === "case_variant_collision") throw new CaseVariantCollisionError(err.message);
1431
+ throw new FieldTypeConflictError(err.message);
1306
1432
  }
1307
1433
  /**
1308
1434
  * Collect validation errors for a single command's schema (non-throwing)
@@ -1314,7 +1440,8 @@ function collectSchemaErrors(extracted, _hasSubCommands, commandPath) {
1314
1440
  ...checkDuplicateAliases(extracted, commandPath),
1315
1441
  ...checkDuplicateNegations(extracted, commandPath),
1316
1442
  ...checkPositionalConfig(extracted, commandPath),
1317
- ...checkReservedAliases(extracted, commandPath)
1443
+ ...checkReservedAliases(extracted, commandPath),
1444
+ ...checkReservedFieldNames(extracted, commandPath)
1318
1445
  ];
1319
1446
  }
1320
1447
  /**
@@ -1390,13 +1517,18 @@ async function validateCommand(command, options = {}) {
1390
1517
  const commandPath = options.commandPath ?? [command.name];
1391
1518
  const errors = [];
1392
1519
  const hasSubCommands = command.subCommands ? Object.keys(command.subCommands).length > 0 : false;
1520
+ const globalExtracted = options.globalArgs ? extractFields(options.globalArgs) : void 0;
1393
1521
  if (command.args) {
1394
1522
  const extracted = extractFields(command.args);
1395
1523
  errors.push(...collectSchemaErrors(extracted, hasSubCommands, commandPath));
1524
+ if (globalExtracted) errors.push(...checkCrossSchemaCollisions(globalExtracted, extracted, commandPath));
1396
1525
  }
1397
1526
  errors.push(...checkSubCommandAliasConflicts(command, commandPath));
1398
1527
  if (command.subCommands) for (const [name, subCmd] of Object.entries(command.subCommands)) {
1399
- const subResult = await validateCommand(await resolveLazyCommand(subCmd), { commandPath: [...commandPath, name] });
1528
+ const subResult = await validateCommand(await resolveLazyCommand(subCmd), {
1529
+ commandPath: [...commandPath, name],
1530
+ ...options.globalArgs ? { globalArgs: options.globalArgs } : {}
1531
+ });
1400
1532
  if (!subResult.valid) errors.push(...subResult.errors);
1401
1533
  }
1402
1534
  if (errors.length === 0) return { valid: true };
@@ -1977,6 +2109,7 @@ function parseArgs(argv, command, options = {}) {
1977
2109
  validateDuplicateNegations(extracted);
1978
2110
  validatePositionalConfig(extracted);
1979
2111
  validateReservedAliases(extracted, hasSubCommands);
2112
+ validateReservedFieldNames(extracted);
1980
2113
  if (options.globalExtracted) validateCrossSchemaCollisions(options.globalExtracted, extracted);
1981
2114
  }
1982
2115
  }
@@ -2028,12 +2161,14 @@ function parseArgs(argv, command, options = {}) {
2028
2161
  const parserOptions = buildParserOptions(extracted);
2029
2162
  const parsed = parseArgv(commandArgv, parserOptions);
2030
2163
  const rawArgs = mergeWithPositionals(parsed, extracted);
2164
+ const envFallbackFields = /* @__PURE__ */ new Set();
2031
2165
  for (const field of extracted.fields) if (field.env && rawArgs[field.name] === void 0) {
2032
2166
  const envNames = Array.isArray(field.env) ? field.env : [field.env];
2033
2167
  for (const envName of envNames) {
2034
2168
  const envValue = process.env[envName];
2035
2169
  if (envValue !== void 0) {
2036
2170
  rawArgs[field.name] = envValue;
2171
+ envFallbackFields.add(field.name);
2037
2172
  break;
2038
2173
  }
2039
2174
  }
@@ -2061,7 +2196,8 @@ function parseArgs(argv, command, options = {}) {
2061
2196
  unknownFlags,
2062
2197
  unknownGlobalFlags: suppressedGlobalFlags,
2063
2198
  extractedFields: extracted,
2064
- rawGlobalArgs
2199
+ rawGlobalArgs,
2200
+ envFallbackFields
2065
2201
  };
2066
2202
  }
2067
2203
  /**
@@ -2269,6 +2405,18 @@ const defaultLogger = {
2269
2405
  warn: (message) => console.warn(message)
2270
2406
  };
2271
2407
  /**
2408
+ * Attach a non-enumerable `$source` helper to the final args object so it
2409
+ * stays invisible to `Object.keys`/`JSON.stringify`/spread (those only ever
2410
+ * see real field values) while still being reachable via property access
2411
+ * (including through `createDualCaseProxy`).
2412
+ */
2413
+ function attachArgSource(target, sourceMap) {
2414
+ Object.defineProperty(target, "$source", {
2415
+ value: (name) => sourceMap.get(name) ?? sourceMap.get(toCamelCase(name)) ?? sourceMap.get(toKebabCase(name)) ?? "default",
2416
+ enumerable: false
2417
+ });
2418
+ }
2419
+ /**
2272
2420
  * Run a command with the given arguments (programmatic/test usage)
2273
2421
  *
2274
2422
  * This function parses arguments, validates them, routes to subcommands,
@@ -2682,6 +2830,8 @@ async function runCommandInternal(command, argv, options = {}) {
2682
2830
  }
2683
2831
  let validatedGlobalArgs = {};
2684
2832
  const isCompletionInvocation = command.name === "__complete";
2833
+ const cliProvidedGlobalFields = new Set(Object.keys(accumulatedGlobalArgs));
2834
+ const envFallbackGlobalFields = /* @__PURE__ */ new Set();
2685
2835
  if (options.globalArgs && options._globalExtracted && !isCompletionInvocation) {
2686
2836
  for (const field of options._globalExtracted.fields) if (field.env && accumulatedGlobalArgs[field.name] === void 0) {
2687
2837
  const envNames = Array.isArray(field.env) ? field.env : [field.env];
@@ -2689,13 +2839,14 @@ async function runCommandInternal(command, argv, options = {}) {
2689
2839
  const envValue = process.env[envName];
2690
2840
  if (envValue !== void 0) {
2691
2841
  accumulatedGlobalArgs[field.name] = envValue;
2842
+ envFallbackGlobalFields.add(field.name);
2692
2843
  break;
2693
2844
  }
2694
2845
  }
2695
2846
  }
2696
2847
  if (options.prompt) {
2697
2848
  const resolved = await options.prompt(accumulatedGlobalArgs, options._globalExtracted);
2698
- Object.assign(accumulatedGlobalArgs, resolved);
2849
+ for (const [key, value] of Object.entries(resolved)) if (value !== void 0) accumulatedGlobalArgs[key] = value;
2699
2850
  }
2700
2851
  const globalValidation = validateArgs(accumulatedGlobalArgs, options.globalArgs);
2701
2852
  if (!globalValidation.success) {
@@ -2710,6 +2861,10 @@ async function runCommandInternal(command, argv, options = {}) {
2710
2861
  validatedGlobalArgs = globalValidation.data;
2711
2862
  }
2712
2863
  if (!command.args) {
2864
+ const globalSourceMap = /* @__PURE__ */ new Map();
2865
+ for (const name of cliProvidedGlobalFields) globalSourceMap.set(name, "cli");
2866
+ for (const name of envFallbackGlobalFields) globalSourceMap.set(name, "env");
2867
+ attachArgSource(validatedGlobalArgs, globalSourceMap);
2713
2868
  const proxiedGlobalArgs = createDualCaseProxy(validatedGlobalArgs);
2714
2869
  if (options._globalExtracted && !isCompletionInvocation) await runEffects(proxiedGlobalArgs, options._globalExtracted, proxiedGlobalArgs);
2715
2870
  collector?.stop();
@@ -2721,12 +2876,25 @@ async function runCommandInternal(command, argv, options = {}) {
2721
2876
  });
2722
2877
  }
2723
2878
  let argsToValidate = parseResult.rawArgs;
2879
+ const promptResolvedFields = /* @__PURE__ */ new Set();
2724
2880
  if (options.prompt && parseResult.extractedFields) {
2725
2881
  const resolved = await options.prompt(argsToValidate, parseResult.extractedFields);
2726
- argsToValidate = {
2727
- ...argsToValidate,
2728
- ...resolved
2729
- };
2882
+ const nextArgsToValidate = { ...argsToValidate };
2883
+ for (const [key, value] of Object.entries(resolved)) if (value !== void 0) {
2884
+ nextArgsToValidate[key] = value;
2885
+ promptResolvedFields.add(key);
2886
+ }
2887
+ argsToValidate = nextArgsToValidate;
2888
+ }
2889
+ const globalPrefilledFields = /* @__PURE__ */ new Set();
2890
+ if (parseResult.extractedFields) {
2891
+ for (const field of parseResult.extractedFields.fields) if (!(Object.hasOwn(parseResult.rawArgs, field.name) || promptResolvedFields.has(field.name)) && cliProvidedGlobalFields.has(field.name) && Object.hasOwn(validatedGlobalArgs, field.name)) {
2892
+ argsToValidate = {
2893
+ ...argsToValidate,
2894
+ [field.name]: validatedGlobalArgs[field.name]
2895
+ };
2896
+ globalPrefilledFields.add(field.name);
2897
+ }
2730
2898
  }
2731
2899
  const validationResult = validateArgs(argsToValidate, command.args);
2732
2900
  if (!validationResult.success) {
@@ -2742,10 +2910,24 @@ async function runCommandInternal(command, argv, options = {}) {
2742
2910
  const proxiedGlobalArgs = createDualCaseProxy(validatedGlobalArgs);
2743
2911
  if (options._globalExtracted && !isCompletionInvocation) await runEffects(proxiedGlobalArgs, options._globalExtracted, proxiedGlobalArgs);
2744
2912
  if (parseResult.extractedFields && !isCompletionInvocation) await runEffects(proxiedCommandArgs, parseResult.extractedFields, proxiedGlobalArgs);
2745
- const mergedArgs = createDualCaseProxy({
2913
+ const mergedPlainArgs = {
2746
2914
  ...proxiedGlobalArgs,
2747
2915
  ...proxiedCommandArgs
2748
- });
2916
+ };
2917
+ const argSourceMap = /* @__PURE__ */ new Map();
2918
+ for (const name of cliProvidedGlobalFields) argSourceMap.set(name, "cli");
2919
+ for (const name of envFallbackGlobalFields) argSourceMap.set(name, "env");
2920
+ const localEnvFallbackFields = parseResult.envFallbackFields ?? /* @__PURE__ */ new Set();
2921
+ for (const field of parseResult.extractedFields?.fields ?? []) {
2922
+ if (globalPrefilledFields.has(field.name)) {
2923
+ argSourceMap.set(field.name, "cli");
2924
+ continue;
2925
+ }
2926
+ const localHasCliOrEnvValue = Object.hasOwn(parseResult.rawArgs, field.name) || localEnvFallbackFields.has(field.name);
2927
+ argSourceMap.set(field.name, localHasCliOrEnvValue ? localEnvFallbackFields.has(field.name) ? "env" : "cli" : "default");
2928
+ }
2929
+ attachArgSource(mergedPlainArgs, argSourceMap);
2930
+ const mergedArgs = createDualCaseProxy(mergedPlainArgs);
2749
2931
  collector?.stop();
2750
2932
  return await executeLifecycle(command, mergedArgs, {
2751
2933
  handleSignals: options.handleSignals,
@@ -2778,6 +2960,7 @@ function extractAndValidateGlobal(options) {
2778
2960
  validateDuplicateAliases(extracted);
2779
2961
  validateDuplicateNegations(extracted);
2780
2962
  validateReservedAliases(extracted, true);
2963
+ validateReservedFieldNames(extracted);
2781
2964
  const positionalNames = extracted.fields.filter((f) => f.positional).map((f) => f.name);
2782
2965
  if (positionalNames.length > 0) throw new Error(`Global options schema must not contain positional arguments. Found: ${positionalNames.join(", ")}`);
2783
2966
  }
@@ -2785,5 +2968,5 @@ function extractAndValidateGlobal(options) {
2785
2968
  }
2786
2969
 
2787
2970
  //#endregion
2788
- export { renderMarkdown as C, renderInline as S, DuplicateFieldError as _, parseArgv as a, ReservedAliasError as b, validateCommand as c, validateDuplicateFields as d, validateDuplicateNegations as f, DuplicateAliasError as g, CaseVariantCollisionError as h, formatValidationErrors as i, validateCrossSchemaCollisions as l, validateReservedAliases as m, runMain as n, formatCommandValidationErrors as o, validatePositionalConfig as p, runner_exports as r, validateCaseVariantCollisions as s, runCommand as t, validateDuplicateAliases as u, DuplicateNegationError as v, createDualCaseProxy as w, generateHelp as x, PositionalConfigError as y };
2789
- //# sourceMappingURL=runner-DpsAMVta.js.map
2971
+ export { ReservedFieldNameError as C, createDualCaseProxy as D, renderMarkdown as E, ReservedAliasError as S, renderInline as T, DuplicateAliasError as _, parseArgv as a, FieldTypeConflictError as b, validateCommand as c, validateDuplicateFields as d, validateDuplicateNegations as f, CaseVariantCollisionError as g, validateReservedFieldNames as h, formatValidationErrors as i, validateCrossSchemaCollisions as l, validateReservedAliases as m, runMain as n, formatCommandValidationErrors as o, validatePositionalConfig as p, runner_exports as r, validateCaseVariantCollisions as s, runCommand as t, validateDuplicateAliases as u, DuplicateFieldError as v, generateHelp as w, PositionalConfigError as x, DuplicateNegationError as y };
2972
+ //# sourceMappingURL=runner-cEPqI3qs.js.map
@@ -1,135 +1,23 @@
1
- import { n as getArgMeta$1 } from "./arg-registry-BeLLAW5-.js";
1
+ import { z } from "zod";
2
2
 
3
- //#region src/lazy.ts
3
+ //#region src/core/arg-registry.ts
4
4
  /**
5
- * Marker property for LazyCommand identification
5
+ * Custom registry for politty argument metadata
6
+ * This avoids polluting Zod's GlobalMeta
6
7
  */
7
- const LAZY_BRAND = "__politty_lazy__";
8
- /**
9
- * Type guard: check if a value is a LazyCommand
10
- */
11
- function isLazyCommand(value) {
12
- return typeof value === "object" && value !== null && LAZY_BRAND in value && value[LAZY_BRAND] === true;
13
- }
14
- /**
15
- * Create a lazily-loaded subcommand with synchronous metadata.
16
- *
17
- * The `meta` command provides names, descriptions, and args schema
18
- * for static analysis (completion scripts, help text) without loading
19
- * the full command module.
20
- *
21
- * The `load` function is called only at execution time.
22
- *
23
- * @example
24
- * ```ts
25
- * import { lazy, defineCommand } from "politty";
26
- *
27
- * const cli = defineCommand({
28
- * name: "mycli",
29
- * subCommands: {
30
- * deploy: lazy(
31
- * defineCommand({
32
- * name: "deploy",
33
- * description: "Deploy the application",
34
- * args: z.object({ env: arg(z.string()) }),
35
- * }),
36
- * () => import("./deploy.js").then((m) => m.deployCommand),
37
- * ),
38
- * },
39
- * });
40
- * ```
41
- */
42
- function lazy(meta, load) {
43
- return {
44
- [LAZY_BRAND]: true,
45
- meta,
46
- load
47
- };
48
- }
49
- /**
50
- * Resolve synchronous metadata from a SubCommandValue.
51
- * Returns null for legacy async subcommands whose metadata is unavailable.
52
- */
53
- function resolveSubCommandMeta(subCmd) {
54
- if (isLazyCommand(subCmd)) return subCmd.meta;
55
- if (typeof subCmd === "function") return null;
56
- return subCmd;
57
- }
58
-
59
- //#endregion
60
- //#region src/executor/subcommand-router.ts
61
- /**
62
- * Resolve a lazy-loaded command (sync or async)
63
- *
64
- * @param cmd - The command or lazy loader function
65
- * @returns The resolved command
66
- */
67
- async function resolveLazyCommand(cmd) {
68
- if (isLazyCommand(cmd)) return await cmd.load();
69
- if (typeof cmd === "function") return await cmd();
70
- return cmd;
71
- }
72
- /**
73
- * Resolve a subcommand by name (including alias lookup) and return both the
74
- * resolved command and the canonical name if accessed via alias.
75
- *
76
- * This avoids a redundant alias scan when the caller needs both pieces of info.
77
- */
78
- async function resolveSubcommandWithAlias(command, name) {
79
- if (!command.subCommands) return;
80
- const subCmd = Object.hasOwn(command.subCommands, name) ? command.subCommands[name] : void 0;
81
- if (subCmd) return {
82
- command: await resolveLazyCommand(subCmd),
83
- aliasFor: void 0
84
- };
85
- const canonicalName = resolveSubCommandAlias(command, name);
86
- if (canonicalName) return {
87
- command: await resolveLazyCommand(command.subCommands[canonicalName]),
88
- aliasFor: canonicalName
89
- };
90
- }
91
- /**
92
- * Resolve an alias to the canonical subcommand name.
93
- * Returns the canonical name if the given name is an alias, or undefined.
94
- *
95
- * Note: Aliases are only recognized for eagerly-defined commands and
96
- * `lazy()` commands (which carry synchronous metadata). Pure async
97
- * subcommand functions do not expose metadata synchronously, so their
98
- * aliases cannot be resolved without loading the module.
99
- *
100
- * @param command - The parent command
101
- * @param alias - The alias to look up
102
- * @returns The canonical subcommand name, or undefined
103
- */
104
- function resolveSubCommandAlias(command, alias) {
105
- if (!command.subCommands) return void 0;
106
- for (const [name, subCmd] of Object.entries(command.subCommands)) if (resolveSubCommandMeta(subCmd)?.aliases?.includes(alias)) return name;
107
- }
108
- /**
109
- * Build a set of all recognized subcommand names including aliases.
110
- *
111
- * @param command - The parent command
112
- * @returns Set of all names (canonical + aliases)
113
- */
114
- function listSubCommandNamesWithAliases(command) {
115
- const names = /* @__PURE__ */ new Set();
116
- if (!command.subCommands) return names;
117
- for (const [name, subCmd] of Object.entries(command.subCommands)) {
118
- names.add(name);
119
- const meta = resolveSubCommandMeta(subCmd);
120
- if (meta?.aliases) for (const alias of meta.aliases) names.add(alias);
121
- }
122
- return names;
8
+ const argRegistry = z.registry();
9
+ function arg(schema, meta) {
10
+ if (meta) argRegistry.add(schema, meta);
11
+ return schema;
123
12
  }
124
13
  /**
125
- * List all subcommand names for a command
14
+ * Get metadata for a schema from the registry
126
15
  *
127
- * @param command - The parent command
128
- * @returns Array of subcommand names
16
+ * @param schema - The Zod schema
17
+ * @returns The metadata if registered, undefined otherwise
129
18
  */
130
- function listSubCommands(command) {
131
- if (!command.subCommands) return [];
132
- return Object.keys(command.subCommands);
19
+ function getArgMeta$1(schema) {
20
+ return argRegistry.get(schema);
133
21
  }
134
22
 
135
23
  //#endregion
@@ -596,5 +484,5 @@ function getExtractedFields(command) {
596
484
  }
597
485
 
598
486
  //#endregion
599
- export { toCamelCase as a, listSubCommands as c, resolveSubcommandWithAlias as d, isLazyCommand as f, getUnknownKeysMode as i, resolveLazyCommand as l, resolveSubCommandMeta as m, getAllAliases as n, toKebabCase as o, lazy as p, getExtractedFields as r, listSubCommandNamesWithAliases as s, extractFields as t, resolveSubCommandAlias as u };
600
- //# sourceMappingURL=schema-extractor-GEuI_L0X.js.map
487
+ export { toCamelCase as a, getUnknownKeysMode as i, getAllAliases as n, toKebabCase as o, getExtractedFields as r, arg as s, extractFields as t };
488
+ //# sourceMappingURL=schema-extractor-wzJ1cGon.js.map