@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/CHANGELOG.md +227 -1
  2. package/dist/core/cli/dispatch.d.mts +6 -5
  3. package/dist/core/cli/dispatch.mjs +205 -1
  4. package/dist/core/cli/help-links.d.mts +0 -1
  5. package/dist/core/cli/help-links.mjs +41 -1
  6. package/dist/core/cli/index.d.mts +81 -8
  7. package/dist/core/cli/index.mjs +945 -1
  8. package/dist/core/cli/planner.d.mts +5 -1
  9. package/dist/core/cli/planner.mjs +300 -1
  10. package/dist/core/cli/plugin.d.mts +1 -1
  11. package/dist/core/cli/plugin.mjs +41 -1
  12. package/dist/core/cli/propagate.d.mts +1 -1
  13. package/dist/core/cli/propagate.mjs +57 -1
  14. package/dist/core/cli/root-help.d.mts +2 -1
  15. package/dist/core/cli/root-help.mjs +226 -4
  16. package/dist/core/cli/root-surface.d.mts +12 -1
  17. package/dist/core/cli/root-surface.mjs +28 -1
  18. package/dist/core/cli/runtime-preflight.d.mts +14 -2
  19. package/dist/core/cli/runtime-preflight.mjs +169 -1
  20. package/dist/core/completion/index.d.mts +0 -1
  21. package/dist/core/completion/index.mjs +90 -1
  22. package/dist/core/completion/shells/bash.d.mts +0 -1
  23. package/dist/core/completion/shells/bash.mjs +308 -3
  24. package/dist/core/completion/shells/fish.d.mts +0 -1
  25. package/dist/core/completion/shells/fish.mjs +162 -2
  26. package/dist/core/completion/shells/powershell.d.mts +0 -1
  27. package/dist/core/completion/shells/powershell.mjs +358 -2
  28. package/dist/core/completion/shells/shared.d.mts +13 -2
  29. package/dist/core/completion/shells/shared.mjs +176 -1
  30. package/dist/core/completion/shells/zsh.d.mts +0 -1
  31. package/dist/core/completion/shells/zsh.mjs +251 -2
  32. package/dist/core/config/index.d.mts +2 -3
  33. package/dist/core/config/index.mjs +246 -1
  34. package/dist/core/config/package-json.d.mts +27 -4
  35. package/dist/core/config/package-json.mjs +386 -3
  36. package/dist/core/errors/index.d.mts +3 -3
  37. package/dist/core/errors/index.mjs +87 -1
  38. package/dist/core/execution/index.d.mts +0 -1
  39. package/dist/core/execution/index.mjs +201 -1
  40. package/dist/core/help/ansi.d.mts +11 -5
  41. package/dist/core/help/ansi.mjs +121 -2
  42. package/dist/core/help/index.d.mts +22 -3
  43. package/dist/core/help/index.mjs +341 -7
  44. package/dist/core/help/theme.d.mts +68 -0
  45. package/dist/core/help/theme.mjs +46 -0
  46. package/dist/core/json-schema/index.d.mts +15 -2
  47. package/dist/core/json-schema/index.mjs +536 -12
  48. package/dist/core/json-schema/meta-descriptions.generated.d.mts +55 -38
  49. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  50. package/dist/core/output/activity.d.mts +0 -1
  51. package/dist/core/output/activity.mjs +452 -1
  52. package/dist/core/output/bind.mjs +56 -1
  53. package/dist/core/output/contracts.d.mts +4 -5
  54. package/dist/core/output/contracts.mjs +57 -1
  55. package/dist/core/output/display-value.mjs +32 -1
  56. package/dist/core/output/index.d.mts +21 -1
  57. package/dist/core/output/index.mjs +442 -2
  58. package/dist/core/output/renderers.d.mts +0 -1
  59. package/dist/core/output/renderers.mjs +46 -1
  60. package/dist/core/output/writer.mjs +12 -1
  61. package/dist/core/parse/index.d.mts +40 -7
  62. package/dist/core/parse/index.mjs +727 -1
  63. package/dist/core/prompt/index.d.mts +1 -1
  64. package/dist/core/prompt/index.mjs +348 -6
  65. package/dist/core/resolve/args.d.mts +1 -1
  66. package/dist/core/resolve/args.mjs +105 -1
  67. package/dist/core/resolve/coerce.d.mts +1 -1
  68. package/dist/core/resolve/coerce.mjs +336 -1
  69. package/dist/core/resolve/config.mjs +19 -1
  70. package/dist/core/resolve/contracts.d.mts +9 -4
  71. package/dist/core/resolve/errors.d.mts +0 -1
  72. package/dist/core/resolve/errors.mjs +140 -2
  73. package/dist/core/resolve/flags.d.mts +7 -2
  74. package/dist/core/resolve/flags.mjs +251 -1
  75. package/dist/core/resolve/index.d.mts +2 -2
  76. package/dist/core/resolve/index.mjs +85 -1
  77. package/dist/core/resolve/property.d.mts +4 -2
  78. package/dist/core/resolve/property.mjs +53 -1
  79. package/dist/core/schema/activity.d.mts +31 -11
  80. package/dist/core/schema/arg.d.mts +3 -4
  81. package/dist/core/schema/arg.mjs +463 -1
  82. package/dist/core/schema/command.d.mts +26 -6
  83. package/dist/core/schema/command.mjs +726 -1
  84. package/dist/core/schema/flag.d.mts +485 -19
  85. package/dist/core/schema/flag.mjs +705 -1
  86. package/dist/core/schema/index.d.mts +4 -2
  87. package/dist/core/schema/middleware.d.mts +4 -3
  88. package/dist/core/schema/middleware.mjs +41 -1
  89. package/dist/core/schema/number-constraints.mjs +60 -1
  90. package/dist/core/schema/prompt.d.mts +6 -3
  91. package/dist/core/schema/run.d.mts +20 -1
  92. package/dist/core/schema/string-constraints.d.mts +97 -0
  93. package/dist/core/schema/string-constraints.mjs +69 -0
  94. package/dist/core/schema/value-parsers.d.mts +78 -0
  95. package/dist/core/schema/value-parsers.mjs +142 -0
  96. package/dist/core/schema-dsl/runtime.mjs +271 -2
  97. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  98. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  99. package/dist/core/testkit/index.d.mts +0 -31
  100. package/dist/core/testkit/index.mjs +83 -1
  101. package/dist/index.d.mts +11 -6
  102. package/dist/index.mjs +22 -1
  103. package/dist/runtime/adapter.d.mts +38 -2
  104. package/dist/runtime/adapter.mjs +87 -1
  105. package/dist/runtime/auto.d.mts +2 -3
  106. package/dist/runtime/auto.mjs +45 -1
  107. package/dist/runtime/deno.d.mts +24 -5
  108. package/dist/runtime/deno.mjs +262 -2
  109. package/dist/runtime/detect.mjs +45 -1
  110. package/dist/runtime/index.d.mts +3 -4
  111. package/dist/runtime/node.d.mts +8 -2
  112. package/dist/runtime/node.mjs +220 -2
  113. package/dist/runtime/paths.mjs +48 -1
  114. package/dist/runtime.d.mts +4 -4
  115. package/dist/runtime.mjs +6 -1
  116. package/dist/strings.mjs +22 -1
  117. package/dist/testkit.d.mts +1 -0
  118. package/dist/testkit.mjs +5 -1
  119. package/dist/version.d.mts +7 -3
  120. package/dist/version.mjs +7 -1
  121. package/dreamcli.schema.json +36 -7
  122. package/package.json +45 -42
  123. package/dist/runtime/bun.d.mts +0 -28
  124. package/dist/runtime/bun.mjs +0 -1
  125. package/src/core/cli/dispatch.ts +0 -355
  126. package/src/core/cli/help-links.ts +0 -82
  127. package/src/core/cli/index.ts +0 -1614
  128. package/src/core/cli/planner.ts +0 -656
  129. package/src/core/cli/plugin.ts +0 -117
  130. package/src/core/cli/propagate.ts +0 -97
  131. package/src/core/cli/root-help.ts +0 -342
  132. package/src/core/cli/root-surface.ts +0 -87
  133. package/src/core/cli/runtime-preflight.ts +0 -456
  134. package/src/core/completion/index.ts +0 -138
  135. package/src/core/completion/shells/bash.ts +0 -459
  136. package/src/core/completion/shells/fish.ts +0 -259
  137. package/src/core/completion/shells/powershell.ts +0 -439
  138. package/src/core/completion/shells/shared.ts +0 -310
  139. package/src/core/completion/shells/zsh.ts +0 -381
  140. package/src/core/config/index.ts +0 -417
  141. package/src/core/config/package-json.ts +0 -560
  142. package/src/core/errors/index.ts +0 -193
  143. package/src/core/execution/index.ts +0 -265
  144. package/src/core/help/ansi.ts +0 -144
  145. package/src/core/help/index.ts +0 -563
  146. package/src/core/json-schema/index.ts +0 -910
  147. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  148. package/src/core/output/activity.ts +0 -575
  149. package/src/core/output/bind.ts +0 -59
  150. package/src/core/output/contracts.ts +0 -194
  151. package/src/core/output/display-value.ts +0 -48
  152. package/src/core/output/index.ts +0 -704
  153. package/src/core/output/renderers.ts +0 -125
  154. package/src/core/output/writer.ts +0 -46
  155. package/src/core/parse/index.ts +0 -742
  156. package/src/core/prompt/index.ts +0 -623
  157. package/src/core/resolve/args.ts +0 -144
  158. package/src/core/resolve/coerce.ts +0 -500
  159. package/src/core/resolve/config.ts +0 -26
  160. package/src/core/resolve/contracts.ts +0 -135
  161. package/src/core/resolve/errors.ts +0 -227
  162. package/src/core/resolve/flags.ts +0 -269
  163. package/src/core/resolve/index.ts +0 -108
  164. package/src/core/resolve/property.ts +0 -99
  165. package/src/core/schema/activity.ts +0 -240
  166. package/src/core/schema/arg.ts +0 -841
  167. package/src/core/schema/command.ts +0 -1500
  168. package/src/core/schema/flag.ts +0 -917
  169. package/src/core/schema/index.ts +0 -96
  170. package/src/core/schema/middleware.ts +0 -171
  171. package/src/core/schema/number-constraints.ts +0 -153
  172. package/src/core/schema/prompt.ts +0 -171
  173. package/src/core/schema/run.ts +0 -198
  174. package/src/core/schema-dsl/index.ts +0 -109
  175. package/src/core/schema-dsl/parse.ts +0 -262
  176. package/src/core/schema-dsl/runtime.ts +0 -609
  177. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  178. package/src/core/testkit/index.ts +0 -147
  179. package/src/index.ts +0 -181
  180. package/src/runtime/adapter.ts +0 -303
  181. package/src/runtime/auto.ts +0 -86
  182. package/src/runtime/bun.ts +0 -48
  183. package/src/runtime/deno.ts +0 -367
  184. package/src/runtime/detect.ts +0 -105
  185. package/src/runtime/index.ts +0 -21
  186. package/src/runtime/node-builtins.d.ts +0 -27
  187. package/src/runtime/node.ts +0 -289
  188. package/src/runtime/paths.ts +0 -64
  189. package/src/runtime/support.ts +0 -77
  190. package/src/runtime.ts +0 -31
  191. package/src/schema.ts +0 -16
  192. package/src/strings.ts +0 -34
  193. package/src/testkit.ts +0 -25
  194. package/src/version.ts +0 -20
@@ -1 +1,727 @@
1
- import{describeNumberConstraintViolation as e,validateNumberConstraints as t}from"../schema/number-constraints.mjs";import{getFlagAliasNames as n}from"../schema/flag.mjs";import{ParseError as r}from"../errors/index.mjs";function i(e){let t=[],n=!1;for(let r of e){if(n){t.push({kind:`positional`,value:r});continue}if(r===`--`){t.push({kind:`separator`}),n=!0;continue}if(r.startsWith(`--`)){let e=r.indexOf(`=`);e===-1?t.push({kind:`long-flag`,name:r.slice(2),value:void 0}):t.push({kind:`long-flag`,name:r.slice(2,e),value:r.slice(e+1)});continue}if(r.startsWith(`-`)&&r.length>1){t.push({kind:`short-flags`,chars:r.slice(1)});continue}t.push({kind:`positional`,value:r})}return t}function a(e,t){for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1}function o(e,t){let n=e.indexOf(`--`),r=n===-1?e:e.slice(0,n);if(!r.includes(t))return e;let i=r.filter(e=>e!==t);return n===-1?i:[...i,...e.slice(n)]}function s(e){let t=new Map;for(let[r,i]of Object.entries(e)){t.set(r,[r,i]);for(let e of n(i,{includeHidden:!0}))t.set(e,[r,i])}return t}function c(e){return e.kind!==`boolean`}function l(n,i,a,o=`--${n}`){switch(a.kind){case`string`:return i;case`number`:{let s=Number(i);if(Number.isNaN(s))throw new r(`Invalid number value '${i}' for flag ${o}`,{code:`INVALID_VALUE`,details:{flag:n,input:o,value:i,expected:`number`}});let c=t(s,a.numberConstraints);if(c!==void 0)throw new r(`Invalid number value '${i}' for flag ${o}: ${e(c)}`,{code:`INVALID_VALUE`,details:{flag:n,input:o,value:i,expected:`number`,constraint:c.kind,...`bound`in c?{bound:c.bound}:{}}});return s}case`boolean`:if(i===`true`||i===`1`)return!0;if(i===`false`||i===`0`)return!1;throw new r(`Invalid boolean value '${i}' for flag ${o}. Use true/false or 1/0`,{code:`INVALID_VALUE`,details:{flag:n,input:o,value:i,expected:`boolean`}});case`enum`:{let e=a.enumValues;if(e===void 0)throw new r(`Enum flag --${n} is misconfigured: no allowed values declared`,{code:`INVALID_SCHEMA`,details:{flag:n,kind:`enum`,missing:`enumValues`}});if(!e.includes(i))throw new r(`Invalid value '${i}' for flag ${o}. Allowed: ${e.join(`, `)}`,{code:`INVALID_VALUE`,details:{flag:n,input:o,value:i,allowed:e}});return i}case`array`:return a.elementSchema?l(n,i,a.elementSchema):i;case`custom`:if(!a.parseFn)return i;try{return a.parseFn(i)}catch(e){throw e instanceof r?e:new r(`Failed to parse flag ${o}: ${e instanceof Error?e.message:String(e)}`,{code:`INVALID_VALUE`,details:{flag:n,input:o,value:i},cause:e})}}}function u(n,i,a){switch(a.kind){case`string`:return i;case`number`:{let o=Number(i);if(Number.isNaN(o))throw new r(`Invalid number value '${i}' for argument <${n}>`,{code:`INVALID_VALUE`,details:{arg:n,value:i,expected:`number`}});let s=t(o,a.numberConstraints);if(s!==void 0)throw new r(`Invalid number value '${i}' for argument <${n}>: ${e(s)}`,{code:`INVALID_VALUE`,details:{arg:n,value:i,expected:`number`,constraint:s.kind,...`bound`in s?{bound:s.bound}:{}}});return o}case`enum`:{let e=a.enumValues;if(e===void 0)throw new r(`Enum argument <${n}> is misconfigured: no allowed values declared`,{code:`INVALID_SCHEMA`,details:{arg:n,kind:`enum`,missing:`enumValues`}});if(!e.includes(i))throw new r(`Invalid value '${i}' for argument <${n}>. Allowed: ${e.join(`, `)}`,{code:`INVALID_VALUE`,details:{arg:n,value:i,allowed:e}});return i}case`custom`:if(!a.parseFn)return i;try{return a.parseFn(i)}catch(e){throw e instanceof r?e:new r(`Failed to parse argument <${n}>: ${e instanceof Error?e.message:String(e)}`,{code:`INVALID_VALUE`,details:{arg:n,value:i},cause:e})}}}function d(e,t){let n=i(t),r=s(e.flags),a={},o=[],c=0;for(;c<n.length;){let e=n[c];if(e===void 0)break;if(e.kind===`separator`){c++;continue}if(e.kind===`positional`){o.push(e.value),c++;continue}if(e.kind===`long-flag`){c=f(e,n,c,r,a);continue}c=p(e,n,c,r,a)}return{flags:a,args:h(e.args,o)}}function f(e,t,n,i,a){let o=i.get(e.name);if(!o){let t=g(e.name,i);throw new r(`Unknown flag --${e.name}${t?`. Did you mean --${t}?`:``}`,{code:`UNKNOWN_FLAG`,details:{flag:e.name,...t?{suggestion:t}:{}},...t?{suggest:`--${t}`}:{}})}let[s,u]=o;if(!c(u))return e.value===void 0?a[s]=!0:a[s]=l(s,e.value,u,`--${e.name}`),n+1;if(e.value!==void 0)return m(a,s,u,e.value),n+1;let d=t[n+1];if(d?.kind!==`positional`)throw new r(`Flag --${e.name} requires a value`,{code:`MISSING_VALUE`,details:{flag:s,input:e.name,kind:u.kind}});return m(a,s,u,d.value,`--${e.name}`),n+2}function p(e,t,n,i,a){let{chars:o}=e,s=n+1;for(let e=0;e<o.length;e++){let n=o.charAt(e),l=i.get(n);if(!l)throw new r(`Unknown flag -${n}`,{code:`UNKNOWN_FLAG`,details:{flag:n}});let[u,d]=l;if(!c(d)){a[u]=!0;continue}if(e<o.length-1){m(a,u,d,o.slice(e+1),`-${n}`);break}let f=t[s];if(f?.kind!==`positional`)throw new r(`Flag -${n} requires a value`,{code:`MISSING_VALUE`,details:{flag:u,input:n,kind:d.kind}});m(a,u,d,f.value,`-${n}`),s++}return s}function m(e,t,n,r,i=`--${t}`){let a=l(t,r,n,i);if(n.kind===`array`){let n=e[t];Array.isArray(n)?n.push(a):e[t]=[a]}else e[t]=a}function h(e,t){let n={},i=0;for(let r of e){if(r.schema.variadic){let e=t.slice(i);n[r.name]=e.map(e=>u(r.name,e,r.schema)),i=t.length;break}let e=t[i];e!==void 0&&(n[r.name]=u(r.name,e,r.schema),i++)}if(i<t.length){let n=t.slice(i);throw new r(`Unexpected positional argument${n.length>1?`s`:``}: ${n.join(`, `)}`,{code:`UNEXPECTED_POSITIONAL`,details:{excess:n,expected:e.length}})}return n}function g(e,t){let n,r=1/0,i=Math.max(2,Math.floor(e.length/2));for(let a of t.keys()){let o=t.get(a);if(o===void 0)continue;let[s,c]=o,l=c.aliases.find(e=>e.name===a);if(a.length<2||a!==s&&l?.hidden)continue;let u=_(e,a);u<r&&u<=i&&(r=u,n=a)}return n}function _(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=e.length<=t.length?e:t,r=e.length<=t.length?t:e,i=n.length,a=r.length,o=Array.from({length:i+1},(e,t)=>t);for(let e=1;e<=a;e++){let t=o[0]??0;o[0]=e;for(let a=1;a<=i;a++){let i=n.charAt(a-1)===r.charAt(e-1)?0:1,s=Math.min((o[a]??0)+1,(o[a-1]??0)+1,t+i);t=o[a]??0,o[a]=s}}return o[i]??0}export{s as buildFlagLookup,c as flagExpectsValue,a as includesBeforeSeparator,d as parse,o as stripBeforeSeparator,i as tokenize};
1
+ import { ParseError } from "../errors/index.mjs";
2
+ import { describeNumberConstraintViolation, validateNumberConstraints } from "../schema/number-constraints.mjs";
3
+ import { describeStringConstraintViolation, validateStringConstraints } from "../schema/string-constraints.mjs";
4
+ import { getFlagAliasNames, getFlagNegatedName } from "../schema/flag.mjs";
5
+ //#region src/core/parse/index.ts
6
+ /**
7
+ * Argv tokenization and parsing against command schemas.
8
+ *
9
+ * Two-phase design:
10
+ *
11
+ * 1. **Tokenize** — split raw argv into structured tokens (long flags, short
12
+ * flags, positionals, separator). Schema-agnostic.
13
+ *
14
+ * 2. **Parse** — walk tokens against a {@linkcode CommandSchema} to produce typed raw
15
+ * values. Emits {@linkcode ParseError} for unknown flags, type mismatches, missing
16
+ * values.
17
+ *
18
+ * @module dreamcli/core/parse
19
+ */
20
+ /**
21
+ * Tokenize raw argv into structured tokens.
22
+ *
23
+ * Low-level utility: most apps should use {@link parse}, `cli().run()`, or
24
+ * `runCommand()` instead of tokenizing manually. Reach for `tokenize()` when
25
+ * building custom tooling such as debuggers, inspectors, or parser tests.
26
+ *
27
+ * Rules:
28
+ * - `--` → separator (everything after is positional)
29
+ * - `--flag` → long flag, no inline value
30
+ * - `--flag=v` → long flag with inline value
31
+ * - `-abc` → short flags (expanded individually by parser)
32
+ * - `-` → positional (convention: stdin placeholder)
33
+ * - everything else → positional
34
+ *
35
+ * @param argv - Raw argument strings to tokenize
36
+ * @returns Ordered token array ready for {@link parse}
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * tokenize(['deploy', '--force', '--region=eu', '-v']);
41
+ * ```
42
+ */
43
+ function tokenize(argv) {
44
+ const tokens = [];
45
+ let pastSeparator = false;
46
+ for (const raw of argv) {
47
+ if (pastSeparator) {
48
+ tokens.push({
49
+ kind: "positional",
50
+ value: raw
51
+ });
52
+ continue;
53
+ }
54
+ if (raw === "--") {
55
+ tokens.push({ kind: "separator" });
56
+ pastSeparator = true;
57
+ continue;
58
+ }
59
+ if (raw.startsWith("--")) {
60
+ const eqIdx = raw.indexOf("=");
61
+ if (eqIdx !== -1) tokens.push({
62
+ kind: "long-flag",
63
+ name: raw.slice(2, eqIdx),
64
+ value: raw.slice(eqIdx + 1)
65
+ });
66
+ else tokens.push({
67
+ kind: "long-flag",
68
+ name: raw.slice(2),
69
+ value: void 0
70
+ });
71
+ continue;
72
+ }
73
+ if (raw.startsWith("-") && raw.length > 1) {
74
+ tokens.push({
75
+ kind: "short-flags",
76
+ chars: raw.slice(1)
77
+ });
78
+ continue;
79
+ }
80
+ tokens.push({
81
+ kind: "positional",
82
+ value: raw
83
+ });
84
+ }
85
+ return tokens;
86
+ }
87
+ /**
88
+ * Whether `token` appears in argv before the `--` end-of-options separator.
89
+ *
90
+ * Everything at or after the first `--` is a literal positional, so root-level
91
+ * flag interception (`--help` / `--version` / `--json`) must use this instead of
92
+ * a naive `Array.includes()` — otherwise a post-separator literal (`-- --json`)
93
+ * is wrongly treated as the flag.
94
+ *
95
+ * @param argv - Raw argument strings.
96
+ * @param token - Exact flag token to look for (e.g. `--version`).
97
+ * @returns `true` if `token` occurs before any `--` separator.
98
+ */
99
+ function includesBeforeSeparator(argv, token) {
100
+ for (const arg of argv) {
101
+ if (arg === "--") return false;
102
+ if (arg === token) return true;
103
+ }
104
+ return false;
105
+ }
106
+ /**
107
+ * Remove every occurrence of `token` that appears before the `--` end-of-options
108
+ * separator, leaving post-separator literals untouched.
109
+ *
110
+ * The strip counterpart to {@linkcode includesBeforeSeparator}: root-level flags
111
+ * (`--json`) are stripped before dispatch/parse so the command schema never sees
112
+ * them, but a literal after `--` (`-- --json`) must reach the command unchanged.
113
+ *
114
+ * @param argv - Raw argument strings.
115
+ * @param token - Exact flag token to strip (e.g. `--json`).
116
+ * @returns A new argv with pre-separator occurrences of `token` removed, or the
117
+ * original reference when `token` does not occur before the separator.
118
+ */
119
+ function stripBeforeSeparator(argv, token) {
120
+ const separatorIndex = argv.indexOf("--");
121
+ const head = separatorIndex === -1 ? argv : argv.slice(0, separatorIndex);
122
+ if (!head.includes(token)) return argv;
123
+ const filteredHead = head.filter((arg) => arg !== token);
124
+ return separatorIndex === -1 ? filteredHead : [...filteredHead, ...argv.slice(separatorIndex)];
125
+ }
126
+ /** `do-this` → `doThis`. Returns the input unchanged when nothing converts. */
127
+ function kebabToCamel(name) {
128
+ return name.replace(/-+([a-z0-9])/g, (_match, char) => char.toUpperCase());
129
+ }
130
+ /** `doThis` → `do-this`. Returns the input unchanged when nothing converts. */
131
+ function camelToKebab(name) {
132
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
133
+ }
134
+ /**
135
+ * The kebab↔camel counterpart spelling of a flag name, or `undefined` when
136
+ * the name has none (single-char aliases, single lowercase words).
137
+ */
138
+ function counterpartSpelling(name) {
139
+ if (name.length < 2) return void 0;
140
+ if (name.includes("-")) {
141
+ const camel = kebabToCamel(name);
142
+ return camel !== name ? camel : void 0;
143
+ }
144
+ const kebab = camelToKebab(name);
145
+ return kebab !== name ? kebab : void 0;
146
+ }
147
+ /**
148
+ * Build a map from flag spelling → {@link FlagLookupEntry}.
149
+ *
150
+ * Covers canonical names, aliases (long + single-char), negated spellings of
151
+ * `.negatable()` booleans, and — unless `caseParity` is `false` — the
152
+ * kebab↔camel counterpart of every declared spelling. Counterparts never
153
+ * override declared spellings: when a command defines both `do-this` and
154
+ * `doThis` explicitly, each spelling exact-matches its own flag and no
155
+ * parity entries are added for the pair.
156
+ *
157
+ * @param flags - Flag schemas keyed by canonical name
158
+ * @param options - Parity toggle (see {@link ParseOptions})
159
+ * @returns Lookup map covering all resolvable spellings
160
+ */
161
+ function buildFlagLookup(flags, options) {
162
+ const lookup = /* @__PURE__ */ new Map();
163
+ for (const [name, schema] of Object.entries(flags)) {
164
+ lookup.set(name, {
165
+ name,
166
+ schema,
167
+ negated: false,
168
+ parity: false
169
+ });
170
+ for (const alias of getFlagAliasNames(schema, { includeHidden: true })) lookup.set(alias, {
171
+ name,
172
+ schema,
173
+ negated: false,
174
+ parity: false
175
+ });
176
+ const negatedName = getFlagNegatedName(name, schema);
177
+ if (negatedName !== void 0) lookup.set(negatedName, {
178
+ name,
179
+ schema,
180
+ negated: true,
181
+ parity: false
182
+ });
183
+ }
184
+ if (options?.caseParity !== false) {
185
+ const declared = [...lookup];
186
+ for (const [spelling, entry] of declared) {
187
+ const counterpart = counterpartSpelling(spelling);
188
+ if (counterpart !== void 0 && !lookup.has(counterpart)) lookup.set(counterpart, {
189
+ ...entry,
190
+ parity: true
191
+ });
192
+ }
193
+ }
194
+ return lookup;
195
+ }
196
+ /**
197
+ * Record one CLI occurrence of a logical flag and enforce its duplicate
198
+ * policy.
199
+ *
200
+ * @param occurrences - Per-parse accumulator keyed by canonical name
201
+ * @param name - Canonical flag name
202
+ * @param schema - Flag schema (read for {@link FlagSchema.duplicates})
203
+ * @param value - The occurrence's raw value (or the boolean it implies)
204
+ * @param displayName - User-facing spelling for error messages
205
+ * @returns `true` when the occurrence should be applied; `false` when the
206
+ * `'first'` policy suppresses it (the token is still consumed)
207
+ * @throws ParseError `DUPLICATE_FLAG` on a repeat under the `'error'` policy
208
+ */
209
+ function recordFlagOccurrence(occurrences, name, schema, value, displayName) {
210
+ const record = occurrences.get(name) ?? {
211
+ count: 0,
212
+ values: []
213
+ };
214
+ record.count += 1;
215
+ record.values.push(value);
216
+ occurrences.set(name, record);
217
+ if (record.count === 1) return true;
218
+ if (schema.duplicates === "error") throw new ParseError(`Flag --${name} may only be specified once`, {
219
+ code: "DUPLICATE_FLAG",
220
+ details: {
221
+ flag: name,
222
+ input: displayName,
223
+ count: record.count,
224
+ values: [...record.values]
225
+ }
226
+ });
227
+ return schema.duplicates !== "first";
228
+ }
229
+ /**
230
+ * Whether a flag kind expects a value argument (vs. being a bare boolean).
231
+ *
232
+ * @param schema - Flag schema to check
233
+ * @returns `true` if the flag expects a value token after it
234
+ */
235
+ function flagExpectsValue(schema) {
236
+ return schema.kind !== "boolean" && schema.kind !== "count";
237
+ }
238
+ /**
239
+ * Coerce a raw string to the flag's declared kind.
240
+ *
241
+ * @param flagName - Canonical flag name (for error messages)
242
+ * @param raw - Raw string value from argv
243
+ * @param schema - {@link FlagSchema} declaring the expected kind
244
+ * @returns Coerced value matching the schema's kind
245
+ * @throws ParseError on type mismatch
246
+ */
247
+ function coerceFlagValue(flagName, raw, schema, displayName = `--${flagName}`) {
248
+ switch (schema.kind) {
249
+ case "string": {
250
+ const violation = validateStringConstraints(raw, schema.stringConstraints);
251
+ if (violation !== void 0) throw new ParseError(`Invalid value '${raw}' for flag ${displayName}: ${describeStringConstraintViolation(violation)}`, {
252
+ code: "INVALID_VALUE",
253
+ details: {
254
+ flag: flagName,
255
+ input: displayName,
256
+ value: raw,
257
+ expected: "string",
258
+ constraint: violation.kind,
259
+ ..."bound" in violation ? { bound: violation.bound } : {},
260
+ ..."pattern" in violation ? { pattern: violation.pattern } : {}
261
+ }
262
+ });
263
+ return raw;
264
+ }
265
+ case "number": {
266
+ const n = Number(raw);
267
+ if (Number.isNaN(n)) throw new ParseError(`Invalid number value '${raw}' for flag ${displayName}`, {
268
+ code: "INVALID_VALUE",
269
+ details: {
270
+ flag: flagName,
271
+ input: displayName,
272
+ value: raw,
273
+ expected: "number"
274
+ }
275
+ });
276
+ const violation = validateNumberConstraints(n, schema.numberConstraints);
277
+ if (violation !== void 0) throw new ParseError(`Invalid number value '${raw}' for flag ${displayName}: ${describeNumberConstraintViolation(violation)}`, {
278
+ code: "INVALID_VALUE",
279
+ details: {
280
+ flag: flagName,
281
+ input: displayName,
282
+ value: raw,
283
+ expected: "number",
284
+ constraint: violation.kind,
285
+ ..."bound" in violation ? { bound: violation.bound } : {}
286
+ }
287
+ });
288
+ return n;
289
+ }
290
+ case "boolean":
291
+ if (raw === "true" || raw === "1") return true;
292
+ if (raw === "false" || raw === "0") return false;
293
+ throw new ParseError(`Invalid boolean value '${raw}' for flag ${displayName}. Use true/false or 1/0`, {
294
+ code: "INVALID_VALUE",
295
+ details: {
296
+ flag: flagName,
297
+ input: displayName,
298
+ value: raw,
299
+ expected: "boolean"
300
+ }
301
+ });
302
+ case "enum": {
303
+ const allowed = schema.enumValues;
304
+ if (allowed === void 0) throw new ParseError(`Enum flag --${flagName} is misconfigured: no allowed values declared`, {
305
+ code: "INVALID_SCHEMA",
306
+ details: {
307
+ flag: flagName,
308
+ kind: "enum",
309
+ missing: "enumValues"
310
+ }
311
+ });
312
+ if (!allowed.includes(raw)) throw new ParseError(`Invalid value '${raw}' for flag ${displayName}. Allowed: ${allowed.join(", ")}`, {
313
+ code: "INVALID_VALUE",
314
+ details: {
315
+ flag: flagName,
316
+ input: displayName,
317
+ value: raw,
318
+ allowed
319
+ }
320
+ });
321
+ return raw;
322
+ }
323
+ case "array":
324
+ if (schema.elementSchema) return coerceFlagValue(flagName, raw, schema.elementSchema);
325
+ return raw;
326
+ case "custom":
327
+ if (!schema.parseFn) return raw;
328
+ try {
329
+ return schema.parseFn(raw);
330
+ } catch (err) {
331
+ if (err instanceof ParseError) throw err;
332
+ throw new ParseError(`Failed to parse flag ${displayName}: ${err instanceof Error ? err.message : String(err)}`, {
333
+ code: "INVALID_VALUE",
334
+ details: {
335
+ flag: flagName,
336
+ input: displayName,
337
+ value: raw
338
+ },
339
+ cause: err
340
+ });
341
+ }
342
+ case "count": {
343
+ const n = raw.trim() === "" ? NaN : Number(raw);
344
+ if (!Number.isInteger(n) || n < 0) throw new ParseError(`Invalid count value '${raw}' for flag ${displayName}. Use a non-negative integer`, {
345
+ code: "INVALID_VALUE",
346
+ details: {
347
+ flag: flagName,
348
+ input: displayName,
349
+ value: raw,
350
+ expected: "count"
351
+ }
352
+ });
353
+ return n;
354
+ }
355
+ case "keyValue": return parseKeyValuePair(flagName, raw, displayName);
356
+ }
357
+ }
358
+ /**
359
+ * Coerce a raw string to the arg's declared kind.
360
+ *
361
+ * @param argName - Positional arg name (for error messages)
362
+ * @param raw - Raw string value from argv
363
+ * @param schema - {@link ArgSchema} declaring the expected kind
364
+ * @returns Coerced value matching the schema's kind
365
+ * @throws ParseError on type mismatch or custom parse failure
366
+ */
367
+ function coerceArgValue(argName, raw, schema) {
368
+ switch (schema.kind) {
369
+ case "string": return raw;
370
+ case "number": {
371
+ const n = Number(raw);
372
+ if (Number.isNaN(n)) throw new ParseError(`Invalid number value '${raw}' for argument <${argName}>`, {
373
+ code: "INVALID_VALUE",
374
+ details: {
375
+ arg: argName,
376
+ value: raw,
377
+ expected: "number"
378
+ }
379
+ });
380
+ const violation = validateNumberConstraints(n, schema.numberConstraints);
381
+ if (violation !== void 0) throw new ParseError(`Invalid number value '${raw}' for argument <${argName}>: ${describeNumberConstraintViolation(violation)}`, {
382
+ code: "INVALID_VALUE",
383
+ details: {
384
+ arg: argName,
385
+ value: raw,
386
+ expected: "number",
387
+ constraint: violation.kind,
388
+ ..."bound" in violation ? { bound: violation.bound } : {}
389
+ }
390
+ });
391
+ return n;
392
+ }
393
+ case "enum": {
394
+ const allowed = schema.enumValues;
395
+ if (allowed === void 0) throw new ParseError(`Enum argument <${argName}> is misconfigured: no allowed values declared`, {
396
+ code: "INVALID_SCHEMA",
397
+ details: {
398
+ arg: argName,
399
+ kind: "enum",
400
+ missing: "enumValues"
401
+ }
402
+ });
403
+ if (!allowed.includes(raw)) throw new ParseError(`Invalid value '${raw}' for argument <${argName}>. Allowed: ${allowed.join(", ")}`, {
404
+ code: "INVALID_VALUE",
405
+ details: {
406
+ arg: argName,
407
+ value: raw,
408
+ allowed
409
+ }
410
+ });
411
+ return raw;
412
+ }
413
+ case "custom":
414
+ if (!schema.parseFn) return raw;
415
+ try {
416
+ return schema.parseFn(raw);
417
+ } catch (err) {
418
+ if (err instanceof ParseError) throw err;
419
+ throw new ParseError(`Failed to parse argument <${argName}>: ${err instanceof Error ? err.message : String(err)}`, {
420
+ code: "INVALID_VALUE",
421
+ details: {
422
+ arg: argName,
423
+ value: raw
424
+ },
425
+ cause: err
426
+ });
427
+ }
428
+ }
429
+ }
430
+ /**
431
+ * Parse tokenized argv against a command schema.
432
+ *
433
+ * Low-level API: most apps should let `cli()` or `runCommand()` handle parsing
434
+ * automatically. Call `parse()` directly when you need raw parsed values before
435
+ * env/config/default resolution or when writing custom tooling around schemas.
436
+ *
437
+ * @param schema - The command schema to parse against
438
+ * @param argv - Raw argv strings (NOT including the command name itself)
439
+ * @param options - Parser behavior toggles (see {@link ParseOptions})
440
+ * @returns Parsed flag and arg values
441
+ * @throws ParseError for unknown flags, missing values, type mismatches
442
+ *
443
+ * @example
444
+ * ```ts
445
+ * const parsed = parse(deploy.schema, ['production', '--force']);
446
+ * // => { args: { target: 'production' }, flags: { force: true } }
447
+ * ```
448
+ */
449
+ function parse(schema, argv, options) {
450
+ const tokens = tokenize(argv);
451
+ const flagLookup = buildFlagLookup(schema.flags, options);
452
+ const flags = {};
453
+ const positionals = [];
454
+ const occurrences = /* @__PURE__ */ new Map();
455
+ let i = 0;
456
+ while (i < tokens.length) {
457
+ const token = tokens[i];
458
+ if (token === void 0) break;
459
+ if (token.kind === "separator") {
460
+ i++;
461
+ continue;
462
+ }
463
+ if (token.kind === "positional") {
464
+ positionals.push(token.value);
465
+ i++;
466
+ continue;
467
+ }
468
+ if (token.kind === "long-flag") {
469
+ i = parseLongFlag(token, tokens, i, flagLookup, flags, occurrences);
470
+ continue;
471
+ }
472
+ i = parseShortFlags(token, tokens, i, flagLookup, flags, occurrences);
473
+ }
474
+ return {
475
+ flags,
476
+ args: mapPositionals(schema.args, positionals)
477
+ };
478
+ }
479
+ /**
480
+ * Parse a long flag token, consuming a value from the next token if needed.
481
+ *
482
+ * @param token - Long-flag token to process
483
+ * @param tokens - Full token array (for lookahead)
484
+ * @param startIdx - Current index of `token` in the array
485
+ * @param flagLookup - Spelling → {@link FlagLookupEntry} map from {@link buildFlagLookup}
486
+ * @param flags - Mutable accumulator for resolved flag values
487
+ * @param occurrences - Per-parse duplicate-occurrence accumulator
488
+ * @returns Next index to continue parsing from
489
+ */
490
+ function parseLongFlag(token, tokens, startIdx, flagLookup, flags, occurrences) {
491
+ const entry = flagLookup.get(token.name);
492
+ if (!entry) {
493
+ const suggestion = suggestFlag(token.name, flagLookup);
494
+ throw new ParseError(`Unknown flag --${token.name}${suggestion ? `. Did you mean --${suggestion}?` : ""}`, {
495
+ code: "UNKNOWN_FLAG",
496
+ details: {
497
+ flag: token.name,
498
+ ...suggestion ? { suggestion } : {}
499
+ },
500
+ ...suggestion ? { suggest: `--${suggestion}` } : {}
501
+ });
502
+ }
503
+ const { name: canonicalName, schema: flagSchema, negated } = entry;
504
+ const displayName = `--${token.name}`;
505
+ if (negated) {
506
+ if (token.value !== void 0) throw new ParseError(`Flag ${displayName} does not take a value`, {
507
+ code: "INVALID_VALUE",
508
+ details: {
509
+ flag: canonicalName,
510
+ input: token.name,
511
+ value: token.value
512
+ }
513
+ });
514
+ if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, false, displayName)) flags[canonicalName] = false;
515
+ return startIdx + 1;
516
+ }
517
+ if (!flagExpectsValue(flagSchema)) {
518
+ if (token.value !== void 0) {
519
+ const coerced = coerceFlagValue(canonicalName, token.value, flagSchema, displayName);
520
+ if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, coerced, displayName)) flags[canonicalName] = coerced;
521
+ } else if (flagSchema.kind === "count") {
522
+ const existing = flags[canonicalName];
523
+ flags[canonicalName] = (typeof existing === "number" ? existing : 0) + 1;
524
+ } else if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, true, displayName)) flags[canonicalName] = true;
525
+ return startIdx + 1;
526
+ }
527
+ if (token.value !== void 0) {
528
+ if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, token.value, displayName)) setFlagValue(flags, canonicalName, flagSchema, token.value);
529
+ return startIdx + 1;
530
+ }
531
+ const nextToken = tokens[startIdx + 1];
532
+ if (nextToken?.kind !== "positional") throw new ParseError(`Flag ${displayName} requires a value`, {
533
+ code: "MISSING_VALUE",
534
+ details: {
535
+ flag: canonicalName,
536
+ input: token.name,
537
+ kind: flagSchema.kind
538
+ }
539
+ });
540
+ if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, nextToken.value, displayName)) setFlagValue(flags, canonicalName, flagSchema, nextToken.value, displayName);
541
+ return startIdx + 2;
542
+ }
543
+ /**
544
+ * Parse combined short flags, expanding -abc into individual flags.
545
+ *
546
+ * @param token - Short-flags token to expand
547
+ * @param tokens - Full token array (for lookahead)
548
+ * @param startIdx - Current index of `token` in the array
549
+ * @param flagLookup - Spelling → {@link FlagLookupEntry} map from {@link buildFlagLookup}
550
+ * @param flags - Mutable accumulator for resolved flag values
551
+ * @param occurrences - Per-parse duplicate-occurrence accumulator
552
+ * @returns Next index to continue parsing from
553
+ */
554
+ function parseShortFlags(token, tokens, startIdx, flagLookup, flags, occurrences) {
555
+ const { chars } = token;
556
+ let nextIdx = startIdx + 1;
557
+ for (let ci = 0; ci < chars.length; ci++) {
558
+ const ch = chars.charAt(ci);
559
+ const entry = flagLookup.get(ch);
560
+ if (!entry) throw new ParseError(`Unknown flag -${ch}`, {
561
+ code: "UNKNOWN_FLAG",
562
+ details: { flag: ch }
563
+ });
564
+ const { name: canonicalName, schema: flagSchema } = entry;
565
+ const displayName = `-${ch}`;
566
+ if (!flagExpectsValue(flagSchema)) {
567
+ if (flagSchema.kind === "count") {
568
+ const existing = flags[canonicalName];
569
+ flags[canonicalName] = (typeof existing === "number" ? existing : 0) + 1;
570
+ } else if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, true, displayName)) flags[canonicalName] = true;
571
+ continue;
572
+ }
573
+ if (ci < chars.length - 1) {
574
+ const inlineValue = chars.slice(ci + 1);
575
+ if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, inlineValue, displayName)) setFlagValue(flags, canonicalName, flagSchema, inlineValue, displayName);
576
+ break;
577
+ }
578
+ const nextToken = tokens[nextIdx];
579
+ if (nextToken?.kind !== "positional") throw new ParseError(`Flag -${ch} requires a value`, {
580
+ code: "MISSING_VALUE",
581
+ details: {
582
+ flag: canonicalName,
583
+ input: ch,
584
+ kind: flagSchema.kind
585
+ }
586
+ });
587
+ if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, nextToken.value, displayName)) setFlagValue(flags, canonicalName, flagSchema, nextToken.value, displayName);
588
+ nextIdx++;
589
+ }
590
+ return nextIdx;
591
+ }
592
+ /**
593
+ * Set or accumulate a flag value, handling array flags specially.
594
+ *
595
+ * @param flags - Mutable accumulator for resolved flag values
596
+ * @param name - Canonical flag name
597
+ * @param schema - {@link FlagSchema} declaring the expected kind
598
+ * @param rawValue - Raw string value from argv
599
+ */
600
+ function setFlagValue(flags, name, schema, rawValue, displayName = `--${name}`) {
601
+ if (schema.kind === "array") {
602
+ const coercedParts = (schema.separator !== void 0 ? rawValue.split(schema.separator) : [rawValue]).filter((part) => schema.separator === void 0 || part.length > 0).map((part) => coerceFlagValue(name, part, schema, displayName));
603
+ const existing = flags[name];
604
+ if (Array.isArray(existing)) existing.push(...coercedParts);
605
+ else flags[name] = coercedParts;
606
+ return;
607
+ }
608
+ if (schema.kind === "keyValue") {
609
+ const pair = parseKeyValuePair(name, rawValue, displayName);
610
+ const existing = flags[name];
611
+ flags[name] = Object.fromEntries([...isPlainRecord(existing) ? Object.entries(existing) : [], pair]);
612
+ return;
613
+ }
614
+ flags[name] = coerceFlagValue(name, rawValue, schema, displayName);
615
+ }
616
+ /** Narrow to a mutable string-record accumulator (keyValue flags only ever store these). */
617
+ function isPlainRecord(value) {
618
+ return typeof value === "object" && value !== null && !Array.isArray(value);
619
+ }
620
+ /**
621
+ * Split a `KEY=VALUE` token at the first `=`.
622
+ *
623
+ * @throws ParseError when the token has no `=` or an empty key.
624
+ */
625
+ function parseKeyValuePair(flagName, raw, displayName = `--${flagName}`) {
626
+ const eq = raw.indexOf("=");
627
+ if (eq <= 0) throw new ParseError(`Invalid value '${raw}' for flag ${displayName}. Use KEY=VALUE`, {
628
+ code: "INVALID_VALUE",
629
+ details: {
630
+ flag: flagName,
631
+ input: displayName,
632
+ value: raw,
633
+ expected: "key=value"
634
+ }
635
+ });
636
+ return [raw.slice(0, eq), raw.slice(eq + 1)];
637
+ }
638
+ /**
639
+ * Map positional values to named args based on schema ordering.
640
+ *
641
+ * @param argEntries - Ordered arg schemas from the command
642
+ * @param positionals - Positional values collected during tokenization
643
+ * @returns Named arg values keyed by arg name
644
+ * @throws ParseError if too many positionals and no variadic arg absorbs them
645
+ */
646
+ function mapPositionals(argEntries, positionals) {
647
+ const args = {};
648
+ let posIdx = 0;
649
+ for (const entry of argEntries) {
650
+ if (entry.schema.variadic) {
651
+ const remaining = positionals.slice(posIdx);
652
+ args[entry.name] = remaining.map((raw) => coerceArgValue(entry.name, raw, entry.schema));
653
+ posIdx = positionals.length;
654
+ break;
655
+ }
656
+ const rawPositional = positionals[posIdx];
657
+ if (rawPositional !== void 0) {
658
+ args[entry.name] = coerceArgValue(entry.name, rawPositional, entry.schema);
659
+ posIdx++;
660
+ }
661
+ }
662
+ if (posIdx < positionals.length) {
663
+ const excess = positionals.slice(posIdx);
664
+ throw new ParseError(`Unexpected positional argument${excess.length > 1 ? "s" : ""}: ${excess.join(", ")}`, {
665
+ code: "UNEXPECTED_POSITIONAL",
666
+ details: {
667
+ excess,
668
+ expected: argEntries.length
669
+ }
670
+ });
671
+ }
672
+ return args;
673
+ }
674
+ /**
675
+ * Suggest the closest flag name if the edit distance is small enough.
676
+ *
677
+ * @param input - Misspelled flag name from the user
678
+ * @param lookup - Flag lookup map from {@link buildFlagLookup}
679
+ * @returns Closest flag name, or `undefined` if no close match exists
680
+ */
681
+ function suggestFlag(input, lookup) {
682
+ let bestName;
683
+ let bestDist = Number.POSITIVE_INFINITY;
684
+ const threshold = Math.max(2, Math.floor(input.length / 2));
685
+ for (const [key, entry] of lookup) {
686
+ if (key.length < 2 || entry.parity) continue;
687
+ if (entry.negated && entry.schema.negation?.hidden === true) continue;
688
+ const alias = entry.schema.aliases.find((candidate) => candidate.name === key);
689
+ if (key !== entry.name && !entry.negated && alias?.hidden) continue;
690
+ const dist = levenshtein(input, key);
691
+ if (dist < bestDist && dist <= threshold) {
692
+ bestDist = dist;
693
+ bestName = key;
694
+ }
695
+ }
696
+ return bestName;
697
+ }
698
+ /**
699
+ * Classic Levenshtein distance using a single-row DP approach.
700
+ *
701
+ * @param a - First string
702
+ * @param b - Second string
703
+ * @returns Edit distance between `a` and `b`
704
+ */
705
+ function levenshtein(a, b) {
706
+ if (a === b) return 0;
707
+ if (a.length === 0) return b.length;
708
+ if (b.length === 0) return a.length;
709
+ const short = a.length <= b.length ? a : b;
710
+ const long = a.length <= b.length ? b : a;
711
+ const aLen = short.length;
712
+ const bLen = long.length;
713
+ const row = Array.from({ length: aLen + 1 }, (_, i) => i);
714
+ for (let j = 1; j <= bLen; j++) {
715
+ let prev = row[0] ?? 0;
716
+ row[0] = j;
717
+ for (let k = 1; k <= aLen; k++) {
718
+ const cost = short.charAt(k - 1) === long.charAt(j - 1) ? 0 : 1;
719
+ const current = Math.min((row[k] ?? 0) + 1, (row[k - 1] ?? 0) + 1, prev + cost);
720
+ prev = row[k] ?? 0;
721
+ row[k] = current;
722
+ }
723
+ }
724
+ return row[aLen] ?? 0;
725
+ }
726
+ //#endregion
727
+ export { buildFlagLookup, camelToKebab, flagExpectsValue, includesBeforeSeparator, kebabToCamel, parse, stripBeforeSeparator, tokenize };