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

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 (136) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/dist/core/cli/dispatch.mjs +214 -1
  3. package/dist/core/cli/help-links.mjs +41 -1
  4. package/dist/core/cli/index.mjs +901 -1
  5. package/dist/core/cli/planner.mjs +300 -1
  6. package/dist/core/cli/plugin.mjs +41 -1
  7. package/dist/core/cli/propagate.mjs +57 -1
  8. package/dist/core/cli/root-help.mjs +208 -4
  9. package/dist/core/cli/root-surface.mjs +27 -1
  10. package/dist/core/cli/runtime-preflight.mjs +168 -1
  11. package/dist/core/completion/index.mjs +90 -1
  12. package/dist/core/completion/shells/bash.mjs +304 -3
  13. package/dist/core/completion/shells/fish.mjs +159 -2
  14. package/dist/core/completion/shells/powershell.mjs +353 -2
  15. package/dist/core/completion/shells/shared.mjs +154 -1
  16. package/dist/core/completion/shells/zsh.mjs +244 -2
  17. package/dist/core/config/index.mjs +246 -1
  18. package/dist/core/config/package-json.mjs +385 -3
  19. package/dist/core/errors/index.mjs +87 -1
  20. package/dist/core/execution/index.mjs +189 -1
  21. package/dist/core/help/ansi.mjs +122 -2
  22. package/dist/core/help/index.mjs +329 -7
  23. package/dist/core/json-schema/index.mjs +487 -9
  24. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  25. package/dist/core/output/activity.mjs +452 -1
  26. package/dist/core/output/bind.mjs +56 -1
  27. package/dist/core/output/contracts.mjs +57 -1
  28. package/dist/core/output/display-value.mjs +32 -1
  29. package/dist/core/output/index.d.mts +21 -0
  30. package/dist/core/output/index.mjs +442 -2
  31. package/dist/core/output/renderers.mjs +46 -1
  32. package/dist/core/output/writer.mjs +12 -1
  33. package/dist/core/parse/index.mjs +555 -1
  34. package/dist/core/prompt/index.d.mts +0 -1
  35. package/dist/core/prompt/index.mjs +348 -6
  36. package/dist/core/resolve/args.mjs +105 -1
  37. package/dist/core/resolve/coerce.mjs +279 -1
  38. package/dist/core/resolve/config.mjs +19 -1
  39. package/dist/core/resolve/errors.mjs +140 -2
  40. package/dist/core/resolve/flags.mjs +196 -1
  41. package/dist/core/resolve/index.mjs +85 -1
  42. package/dist/core/resolve/property.d.mts +0 -1
  43. package/dist/core/resolve/property.mjs +45 -1
  44. package/dist/core/schema/arg.mjs +463 -1
  45. package/dist/core/schema/command.d.mts +18 -0
  46. package/dist/core/schema/command.mjs +712 -1
  47. package/dist/core/schema/flag.mjs +453 -1
  48. package/dist/core/schema/middleware.mjs +41 -1
  49. package/dist/core/schema/number-constraints.mjs +60 -1
  50. package/dist/core/schema-dsl/runtime.mjs +271 -2
  51. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  52. package/dist/core/testkit/index.mjs +83 -1
  53. package/dist/index.d.mts +2 -1
  54. package/dist/index.mjs +22 -1
  55. package/dist/runtime/adapter.mjs +82 -1
  56. package/dist/runtime/auto.mjs +46 -1
  57. package/dist/runtime/bun.mjs +28 -1
  58. package/dist/runtime/deno.mjs +217 -2
  59. package/dist/runtime/detect.mjs +45 -1
  60. package/dist/runtime/node.mjs +169 -2
  61. package/dist/runtime/paths.mjs +48 -1
  62. package/dist/runtime.mjs +7 -1
  63. package/dist/strings.mjs +22 -1
  64. package/dist/testkit.mjs +5 -1
  65. package/dist/version.mjs +7 -1
  66. package/package.json +17 -26
  67. package/src/core/cli/dispatch.ts +0 -355
  68. package/src/core/cli/help-links.ts +0 -82
  69. package/src/core/cli/index.ts +0 -1614
  70. package/src/core/cli/planner.ts +0 -656
  71. package/src/core/cli/plugin.ts +0 -117
  72. package/src/core/cli/propagate.ts +0 -97
  73. package/src/core/cli/root-help.ts +0 -342
  74. package/src/core/cli/root-surface.ts +0 -87
  75. package/src/core/cli/runtime-preflight.ts +0 -456
  76. package/src/core/completion/index.ts +0 -138
  77. package/src/core/completion/shells/bash.ts +0 -459
  78. package/src/core/completion/shells/fish.ts +0 -259
  79. package/src/core/completion/shells/powershell.ts +0 -439
  80. package/src/core/completion/shells/shared.ts +0 -310
  81. package/src/core/completion/shells/zsh.ts +0 -381
  82. package/src/core/config/index.ts +0 -417
  83. package/src/core/config/package-json.ts +0 -560
  84. package/src/core/errors/index.ts +0 -193
  85. package/src/core/execution/index.ts +0 -265
  86. package/src/core/help/ansi.ts +0 -144
  87. package/src/core/help/index.ts +0 -563
  88. package/src/core/json-schema/index.ts +0 -910
  89. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  90. package/src/core/output/activity.ts +0 -575
  91. package/src/core/output/bind.ts +0 -59
  92. package/src/core/output/contracts.ts +0 -194
  93. package/src/core/output/display-value.ts +0 -48
  94. package/src/core/output/index.ts +0 -704
  95. package/src/core/output/renderers.ts +0 -125
  96. package/src/core/output/writer.ts +0 -46
  97. package/src/core/parse/index.ts +0 -742
  98. package/src/core/prompt/index.ts +0 -623
  99. package/src/core/resolve/args.ts +0 -144
  100. package/src/core/resolve/coerce.ts +0 -500
  101. package/src/core/resolve/config.ts +0 -26
  102. package/src/core/resolve/contracts.ts +0 -135
  103. package/src/core/resolve/errors.ts +0 -227
  104. package/src/core/resolve/flags.ts +0 -269
  105. package/src/core/resolve/index.ts +0 -108
  106. package/src/core/resolve/property.ts +0 -99
  107. package/src/core/schema/activity.ts +0 -240
  108. package/src/core/schema/arg.ts +0 -841
  109. package/src/core/schema/command.ts +0 -1500
  110. package/src/core/schema/flag.ts +0 -917
  111. package/src/core/schema/index.ts +0 -96
  112. package/src/core/schema/middleware.ts +0 -171
  113. package/src/core/schema/number-constraints.ts +0 -153
  114. package/src/core/schema/prompt.ts +0 -171
  115. package/src/core/schema/run.ts +0 -198
  116. package/src/core/schema-dsl/index.ts +0 -109
  117. package/src/core/schema-dsl/parse.ts +0 -262
  118. package/src/core/schema-dsl/runtime.ts +0 -609
  119. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  120. package/src/core/testkit/index.ts +0 -147
  121. package/src/index.ts +0 -181
  122. package/src/runtime/adapter.ts +0 -303
  123. package/src/runtime/auto.ts +0 -86
  124. package/src/runtime/bun.ts +0 -48
  125. package/src/runtime/deno.ts +0 -367
  126. package/src/runtime/detect.ts +0 -105
  127. package/src/runtime/index.ts +0 -21
  128. package/src/runtime/node-builtins.d.ts +0 -27
  129. package/src/runtime/node.ts +0 -289
  130. package/src/runtime/paths.ts +0 -64
  131. package/src/runtime/support.ts +0 -77
  132. package/src/runtime.ts +0 -31
  133. package/src/schema.ts +0 -16
  134. package/src/strings.ts +0 -34
  135. package/src/testkit.ts +0 -25
  136. package/src/version.ts +0 -20
@@ -1 +1,555 @@
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 { describeNumberConstraintViolation, validateNumberConstraints } from "../schema/number-constraints.mjs";
2
+ import { getFlagAliasNames } from "../schema/flag.mjs";
3
+ import { ParseError } from "../errors/index.mjs";
4
+ //#region src/core/parse/index.ts
5
+ /**
6
+ * Argv tokenization and parsing against command schemas.
7
+ *
8
+ * Two-phase design:
9
+ *
10
+ * 1. **Tokenize** — split raw argv into structured tokens (long flags, short
11
+ * flags, positionals, separator). Schema-agnostic.
12
+ *
13
+ * 2. **Parse** — walk tokens against a {@linkcode CommandSchema} to produce typed raw
14
+ * values. Emits {@linkcode ParseError} for unknown flags, type mismatches, missing
15
+ * values.
16
+ *
17
+ * @module dreamcli/core/parse
18
+ */
19
+ /**
20
+ * Tokenize raw argv into structured tokens.
21
+ *
22
+ * Low-level utility: most apps should use {@link parse}, `cli().run()`, or
23
+ * `runCommand()` instead of tokenizing manually. Reach for `tokenize()` when
24
+ * building custom tooling such as debuggers, inspectors, or parser tests.
25
+ *
26
+ * Rules:
27
+ * - `--` → separator (everything after is positional)
28
+ * - `--flag` → long flag, no inline value
29
+ * - `--flag=v` → long flag with inline value
30
+ * - `-abc` → short flags (expanded individually by parser)
31
+ * - `-` → positional (convention: stdin placeholder)
32
+ * - everything else → positional
33
+ *
34
+ * @param argv - Raw argument strings to tokenize
35
+ * @returns Ordered token array ready for {@link parse}
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * tokenize(['deploy', '--force', '--region=eu', '-v']);
40
+ * ```
41
+ */
42
+ function tokenize(argv) {
43
+ const tokens = [];
44
+ let pastSeparator = false;
45
+ for (const raw of argv) {
46
+ if (pastSeparator) {
47
+ tokens.push({
48
+ kind: "positional",
49
+ value: raw
50
+ });
51
+ continue;
52
+ }
53
+ if (raw === "--") {
54
+ tokens.push({ kind: "separator" });
55
+ pastSeparator = true;
56
+ continue;
57
+ }
58
+ if (raw.startsWith("--")) {
59
+ const eqIdx = raw.indexOf("=");
60
+ if (eqIdx !== -1) tokens.push({
61
+ kind: "long-flag",
62
+ name: raw.slice(2, eqIdx),
63
+ value: raw.slice(eqIdx + 1)
64
+ });
65
+ else tokens.push({
66
+ kind: "long-flag",
67
+ name: raw.slice(2),
68
+ value: void 0
69
+ });
70
+ continue;
71
+ }
72
+ if (raw.startsWith("-") && raw.length > 1) {
73
+ tokens.push({
74
+ kind: "short-flags",
75
+ chars: raw.slice(1)
76
+ });
77
+ continue;
78
+ }
79
+ tokens.push({
80
+ kind: "positional",
81
+ value: raw
82
+ });
83
+ }
84
+ return tokens;
85
+ }
86
+ /**
87
+ * Whether `token` appears in argv before the `--` end-of-options separator.
88
+ *
89
+ * Everything at or after the first `--` is a literal positional, so root-level
90
+ * flag interception (`--help` / `--version` / `--json`) must use this instead of
91
+ * a naive `Array.includes()` — otherwise a post-separator literal (`-- --json`)
92
+ * is wrongly treated as the flag.
93
+ *
94
+ * @param argv - Raw argument strings.
95
+ * @param token - Exact flag token to look for (e.g. `--version`).
96
+ * @returns `true` if `token` occurs before any `--` separator.
97
+ */
98
+ function includesBeforeSeparator(argv, token) {
99
+ for (const arg of argv) {
100
+ if (arg === "--") return false;
101
+ if (arg === token) return true;
102
+ }
103
+ return false;
104
+ }
105
+ /**
106
+ * Remove every occurrence of `token` that appears before the `--` end-of-options
107
+ * separator, leaving post-separator literals untouched.
108
+ *
109
+ * The strip counterpart to {@linkcode includesBeforeSeparator}: root-level flags
110
+ * (`--json`) are stripped before dispatch/parse so the command schema never sees
111
+ * them, but a literal after `--` (`-- --json`) must reach the command unchanged.
112
+ *
113
+ * @param argv - Raw argument strings.
114
+ * @param token - Exact flag token to strip (e.g. `--json`).
115
+ * @returns A new argv with pre-separator occurrences of `token` removed, or the
116
+ * original reference when `token` does not occur before the separator.
117
+ */
118
+ function stripBeforeSeparator(argv, token) {
119
+ const separatorIndex = argv.indexOf("--");
120
+ const head = separatorIndex === -1 ? argv : argv.slice(0, separatorIndex);
121
+ if (!head.includes(token)) return argv;
122
+ const filteredHead = head.filter((arg) => arg !== token);
123
+ return separatorIndex === -1 ? filteredHead : [...filteredHead, ...argv.slice(separatorIndex)];
124
+ }
125
+ /**
126
+ * Build a map from flag name/alias → [canonicalName, {@link FlagSchema}].
127
+ *
128
+ * Supports both long names and single-char aliases for short flag expansion.
129
+ *
130
+ * @param flags - Flag schemas keyed by canonical name
131
+ * @returns Lookup map covering all names and aliases
132
+ */
133
+ function buildFlagLookup(flags) {
134
+ const lookup = /* @__PURE__ */ new Map();
135
+ for (const [name, schema] of Object.entries(flags)) {
136
+ lookup.set(name, [name, schema]);
137
+ for (const alias of getFlagAliasNames(schema, { includeHidden: true })) lookup.set(alias, [name, schema]);
138
+ }
139
+ return lookup;
140
+ }
141
+ /**
142
+ * Whether a flag kind expects a value argument (vs. being a bare boolean).
143
+ *
144
+ * @param schema - Flag schema to check
145
+ * @returns `true` if the flag expects a value token after it
146
+ */
147
+ function flagExpectsValue(schema) {
148
+ return schema.kind !== "boolean";
149
+ }
150
+ /**
151
+ * Coerce a raw string to the flag's declared kind.
152
+ *
153
+ * @param flagName - Canonical flag name (for error messages)
154
+ * @param raw - Raw string value from argv
155
+ * @param schema - {@link FlagSchema} declaring the expected kind
156
+ * @returns Coerced value matching the schema's kind
157
+ * @throws ParseError on type mismatch
158
+ */
159
+ function coerceFlagValue(flagName, raw, schema, displayName = `--${flagName}`) {
160
+ switch (schema.kind) {
161
+ case "string": return raw;
162
+ case "number": {
163
+ const n = Number(raw);
164
+ if (Number.isNaN(n)) throw new ParseError(`Invalid number value '${raw}' for flag ${displayName}`, {
165
+ code: "INVALID_VALUE",
166
+ details: {
167
+ flag: flagName,
168
+ input: displayName,
169
+ value: raw,
170
+ expected: "number"
171
+ }
172
+ });
173
+ const violation = validateNumberConstraints(n, schema.numberConstraints);
174
+ if (violation !== void 0) throw new ParseError(`Invalid number value '${raw}' for flag ${displayName}: ${describeNumberConstraintViolation(violation)}`, {
175
+ code: "INVALID_VALUE",
176
+ details: {
177
+ flag: flagName,
178
+ input: displayName,
179
+ value: raw,
180
+ expected: "number",
181
+ constraint: violation.kind,
182
+ ..."bound" in violation ? { bound: violation.bound } : {}
183
+ }
184
+ });
185
+ return n;
186
+ }
187
+ case "boolean":
188
+ if (raw === "true" || raw === "1") return true;
189
+ if (raw === "false" || raw === "0") return false;
190
+ throw new ParseError(`Invalid boolean value '${raw}' for flag ${displayName}. Use true/false or 1/0`, {
191
+ code: "INVALID_VALUE",
192
+ details: {
193
+ flag: flagName,
194
+ input: displayName,
195
+ value: raw,
196
+ expected: "boolean"
197
+ }
198
+ });
199
+ case "enum": {
200
+ const allowed = schema.enumValues;
201
+ if (allowed === void 0) throw new ParseError(`Enum flag --${flagName} is misconfigured: no allowed values declared`, {
202
+ code: "INVALID_SCHEMA",
203
+ details: {
204
+ flag: flagName,
205
+ kind: "enum",
206
+ missing: "enumValues"
207
+ }
208
+ });
209
+ if (!allowed.includes(raw)) throw new ParseError(`Invalid value '${raw}' for flag ${displayName}. Allowed: ${allowed.join(", ")}`, {
210
+ code: "INVALID_VALUE",
211
+ details: {
212
+ flag: flagName,
213
+ input: displayName,
214
+ value: raw,
215
+ allowed
216
+ }
217
+ });
218
+ return raw;
219
+ }
220
+ case "array":
221
+ if (schema.elementSchema) return coerceFlagValue(flagName, raw, schema.elementSchema);
222
+ return raw;
223
+ case "custom":
224
+ if (!schema.parseFn) return raw;
225
+ try {
226
+ return schema.parseFn(raw);
227
+ } catch (err) {
228
+ if (err instanceof ParseError) throw err;
229
+ throw new ParseError(`Failed to parse flag ${displayName}: ${err instanceof Error ? err.message : String(err)}`, {
230
+ code: "INVALID_VALUE",
231
+ details: {
232
+ flag: flagName,
233
+ input: displayName,
234
+ value: raw
235
+ },
236
+ cause: err
237
+ });
238
+ }
239
+ }
240
+ }
241
+ /**
242
+ * Coerce a raw string to the arg's declared kind.
243
+ *
244
+ * @param argName - Positional arg name (for error messages)
245
+ * @param raw - Raw string value from argv
246
+ * @param schema - {@link ArgSchema} declaring the expected kind
247
+ * @returns Coerced value matching the schema's kind
248
+ * @throws ParseError on type mismatch or custom parse failure
249
+ */
250
+ function coerceArgValue(argName, raw, schema) {
251
+ switch (schema.kind) {
252
+ case "string": return raw;
253
+ case "number": {
254
+ const n = Number(raw);
255
+ if (Number.isNaN(n)) throw new ParseError(`Invalid number value '${raw}' for argument <${argName}>`, {
256
+ code: "INVALID_VALUE",
257
+ details: {
258
+ arg: argName,
259
+ value: raw,
260
+ expected: "number"
261
+ }
262
+ });
263
+ const violation = validateNumberConstraints(n, schema.numberConstraints);
264
+ if (violation !== void 0) throw new ParseError(`Invalid number value '${raw}' for argument <${argName}>: ${describeNumberConstraintViolation(violation)}`, {
265
+ code: "INVALID_VALUE",
266
+ details: {
267
+ arg: argName,
268
+ value: raw,
269
+ expected: "number",
270
+ constraint: violation.kind,
271
+ ..."bound" in violation ? { bound: violation.bound } : {}
272
+ }
273
+ });
274
+ return n;
275
+ }
276
+ case "enum": {
277
+ const allowed = schema.enumValues;
278
+ if (allowed === void 0) throw new ParseError(`Enum argument <${argName}> is misconfigured: no allowed values declared`, {
279
+ code: "INVALID_SCHEMA",
280
+ details: {
281
+ arg: argName,
282
+ kind: "enum",
283
+ missing: "enumValues"
284
+ }
285
+ });
286
+ if (!allowed.includes(raw)) throw new ParseError(`Invalid value '${raw}' for argument <${argName}>. Allowed: ${allowed.join(", ")}`, {
287
+ code: "INVALID_VALUE",
288
+ details: {
289
+ arg: argName,
290
+ value: raw,
291
+ allowed
292
+ }
293
+ });
294
+ return raw;
295
+ }
296
+ case "custom":
297
+ if (!schema.parseFn) return raw;
298
+ try {
299
+ return schema.parseFn(raw);
300
+ } catch (err) {
301
+ if (err instanceof ParseError) throw err;
302
+ throw new ParseError(`Failed to parse argument <${argName}>: ${err instanceof Error ? err.message : String(err)}`, {
303
+ code: "INVALID_VALUE",
304
+ details: {
305
+ arg: argName,
306
+ value: raw
307
+ },
308
+ cause: err
309
+ });
310
+ }
311
+ }
312
+ }
313
+ /**
314
+ * Parse tokenized argv against a command schema.
315
+ *
316
+ * Low-level API: most apps should let `cli()` or `runCommand()` handle parsing
317
+ * automatically. Call `parse()` directly when you need raw parsed values before
318
+ * env/config/default resolution or when writing custom tooling around schemas.
319
+ *
320
+ * @param schema - The command schema to parse against
321
+ * @param argv - Raw argv strings (NOT including the command name itself)
322
+ * @returns Parsed flag and arg values
323
+ * @throws ParseError for unknown flags, missing values, type mismatches
324
+ *
325
+ * @example
326
+ * ```ts
327
+ * const parsed = parse(deploy.schema, ['production', '--force']);
328
+ * // => { args: { target: 'production' }, flags: { force: true } }
329
+ * ```
330
+ */
331
+ function parse(schema, argv) {
332
+ const tokens = tokenize(argv);
333
+ const flagLookup = buildFlagLookup(schema.flags);
334
+ const flags = {};
335
+ const positionals = [];
336
+ let i = 0;
337
+ while (i < tokens.length) {
338
+ const token = tokens[i];
339
+ if (token === void 0) break;
340
+ if (token.kind === "separator") {
341
+ i++;
342
+ continue;
343
+ }
344
+ if (token.kind === "positional") {
345
+ positionals.push(token.value);
346
+ i++;
347
+ continue;
348
+ }
349
+ if (token.kind === "long-flag") {
350
+ i = parseLongFlag(token, tokens, i, flagLookup, flags);
351
+ continue;
352
+ }
353
+ i = parseShortFlags(token, tokens, i, flagLookup, flags);
354
+ }
355
+ return {
356
+ flags,
357
+ args: mapPositionals(schema.args, positionals)
358
+ };
359
+ }
360
+ /**
361
+ * Parse a long flag token, consuming a value from the next token if needed.
362
+ *
363
+ * @param token - Long-flag token to process
364
+ * @param tokens - Full token array (for lookahead)
365
+ * @param startIdx - Current index of `token` in the array
366
+ * @param flagLookup - Name/alias → [canonical, schema] map from {@link buildFlagLookup}
367
+ * @param flags - Mutable accumulator for resolved flag values
368
+ * @returns Next index to continue parsing from
369
+ */
370
+ function parseLongFlag(token, tokens, startIdx, flagLookup, flags) {
371
+ const entry = flagLookup.get(token.name);
372
+ if (!entry) {
373
+ const suggestion = suggestFlag(token.name, flagLookup);
374
+ throw new ParseError(`Unknown flag --${token.name}${suggestion ? `. Did you mean --${suggestion}?` : ""}`, {
375
+ code: "UNKNOWN_FLAG",
376
+ details: {
377
+ flag: token.name,
378
+ ...suggestion ? { suggestion } : {}
379
+ },
380
+ ...suggestion ? { suggest: `--${suggestion}` } : {}
381
+ });
382
+ }
383
+ const [canonicalName, flagSchema] = entry;
384
+ if (!flagExpectsValue(flagSchema)) {
385
+ if (token.value !== void 0) flags[canonicalName] = coerceFlagValue(canonicalName, token.value, flagSchema, `--${token.name}`);
386
+ else flags[canonicalName] = true;
387
+ return startIdx + 1;
388
+ }
389
+ if (token.value !== void 0) {
390
+ setFlagValue(flags, canonicalName, flagSchema, token.value);
391
+ return startIdx + 1;
392
+ }
393
+ const nextToken = tokens[startIdx + 1];
394
+ if (nextToken?.kind !== "positional") throw new ParseError(`Flag --${token.name} requires a value`, {
395
+ code: "MISSING_VALUE",
396
+ details: {
397
+ flag: canonicalName,
398
+ input: token.name,
399
+ kind: flagSchema.kind
400
+ }
401
+ });
402
+ setFlagValue(flags, canonicalName, flagSchema, nextToken.value, `--${token.name}`);
403
+ return startIdx + 2;
404
+ }
405
+ /**
406
+ * Parse combined short flags, expanding -abc into individual flags.
407
+ *
408
+ * @param token - Short-flags token to expand
409
+ * @param tokens - Full token array (for lookahead)
410
+ * @param startIdx - Current index of `token` in the array
411
+ * @param flagLookup - Name/alias → [canonical, schema] map from {@link buildFlagLookup}
412
+ * @param flags - Mutable accumulator for resolved flag values
413
+ * @returns Next index to continue parsing from
414
+ */
415
+ function parseShortFlags(token, tokens, startIdx, flagLookup, flags) {
416
+ const { chars } = token;
417
+ let nextIdx = startIdx + 1;
418
+ for (let ci = 0; ci < chars.length; ci++) {
419
+ const ch = chars.charAt(ci);
420
+ const entry = flagLookup.get(ch);
421
+ if (!entry) throw new ParseError(`Unknown flag -${ch}`, {
422
+ code: "UNKNOWN_FLAG",
423
+ details: { flag: ch }
424
+ });
425
+ const [canonicalName, flagSchema] = entry;
426
+ if (!flagExpectsValue(flagSchema)) {
427
+ flags[canonicalName] = true;
428
+ continue;
429
+ }
430
+ if (ci < chars.length - 1) {
431
+ setFlagValue(flags, canonicalName, flagSchema, chars.slice(ci + 1), `-${ch}`);
432
+ break;
433
+ }
434
+ const nextToken = tokens[nextIdx];
435
+ if (nextToken?.kind !== "positional") throw new ParseError(`Flag -${ch} requires a value`, {
436
+ code: "MISSING_VALUE",
437
+ details: {
438
+ flag: canonicalName,
439
+ input: ch,
440
+ kind: flagSchema.kind
441
+ }
442
+ });
443
+ setFlagValue(flags, canonicalName, flagSchema, nextToken.value, `-${ch}`);
444
+ nextIdx++;
445
+ }
446
+ return nextIdx;
447
+ }
448
+ /**
449
+ * Set or accumulate a flag value, handling array flags specially.
450
+ *
451
+ * @param flags - Mutable accumulator for resolved flag values
452
+ * @param name - Canonical flag name
453
+ * @param schema - {@link FlagSchema} declaring the expected kind
454
+ * @param rawValue - Raw string value from argv
455
+ */
456
+ function setFlagValue(flags, name, schema, rawValue, displayName = `--${name}`) {
457
+ const coerced = coerceFlagValue(name, rawValue, schema, displayName);
458
+ if (schema.kind === "array") {
459
+ const existing = flags[name];
460
+ if (Array.isArray(existing)) existing.push(coerced);
461
+ else flags[name] = [coerced];
462
+ } else flags[name] = coerced;
463
+ }
464
+ /**
465
+ * Map positional values to named args based on schema ordering.
466
+ *
467
+ * @param argEntries - Ordered arg schemas from the command
468
+ * @param positionals - Positional values collected during tokenization
469
+ * @returns Named arg values keyed by arg name
470
+ * @throws ParseError if too many positionals and no variadic arg absorbs them
471
+ */
472
+ function mapPositionals(argEntries, positionals) {
473
+ const args = {};
474
+ let posIdx = 0;
475
+ for (const entry of argEntries) {
476
+ if (entry.schema.variadic) {
477
+ const remaining = positionals.slice(posIdx);
478
+ args[entry.name] = remaining.map((raw) => coerceArgValue(entry.name, raw, entry.schema));
479
+ posIdx = positionals.length;
480
+ break;
481
+ }
482
+ const rawPositional = positionals[posIdx];
483
+ if (rawPositional !== void 0) {
484
+ args[entry.name] = coerceArgValue(entry.name, rawPositional, entry.schema);
485
+ posIdx++;
486
+ }
487
+ }
488
+ if (posIdx < positionals.length) {
489
+ const excess = positionals.slice(posIdx);
490
+ throw new ParseError(`Unexpected positional argument${excess.length > 1 ? "s" : ""}: ${excess.join(", ")}`, {
491
+ code: "UNEXPECTED_POSITIONAL",
492
+ details: {
493
+ excess,
494
+ expected: argEntries.length
495
+ }
496
+ });
497
+ }
498
+ return args;
499
+ }
500
+ /**
501
+ * Suggest the closest flag name if the edit distance is small enough.
502
+ *
503
+ * @param input - Misspelled flag name from the user
504
+ * @param lookup - Flag lookup map from {@link buildFlagLookup}
505
+ * @returns Closest flag name, or `undefined` if no close match exists
506
+ */
507
+ function suggestFlag(input, lookup) {
508
+ let bestName;
509
+ let bestDist = Number.POSITIVE_INFINITY;
510
+ const threshold = Math.max(2, Math.floor(input.length / 2));
511
+ for (const key of lookup.keys()) {
512
+ const entry = lookup.get(key);
513
+ if (entry === void 0) continue;
514
+ const [canonicalName, schema] = entry;
515
+ const alias = schema.aliases.find((candidate) => candidate.name === key);
516
+ if (key.length < 2) continue;
517
+ if (key !== canonicalName && alias?.hidden) continue;
518
+ const dist = levenshtein(input, key);
519
+ if (dist < bestDist && dist <= threshold) {
520
+ bestDist = dist;
521
+ bestName = key;
522
+ }
523
+ }
524
+ return bestName;
525
+ }
526
+ /**
527
+ * Classic Levenshtein distance using a single-row DP approach.
528
+ *
529
+ * @param a - First string
530
+ * @param b - Second string
531
+ * @returns Edit distance between `a` and `b`
532
+ */
533
+ function levenshtein(a, b) {
534
+ if (a === b) return 0;
535
+ if (a.length === 0) return b.length;
536
+ if (b.length === 0) return a.length;
537
+ const short = a.length <= b.length ? a : b;
538
+ const long = a.length <= b.length ? b : a;
539
+ const aLen = short.length;
540
+ const bLen = long.length;
541
+ const row = Array.from({ length: aLen + 1 }, (_, i) => i);
542
+ for (let j = 1; j <= bLen; j++) {
543
+ let prev = row[0] ?? 0;
544
+ row[0] = j;
545
+ for (let k = 1; k <= aLen; k++) {
546
+ const cost = short.charAt(k - 1) === long.charAt(j - 1) ? 0 : 1;
547
+ const current = Math.min((row[k] ?? 0) + 1, (row[k - 1] ?? 0) + 1, prev + cost);
548
+ prev = row[k] ?? 0;
549
+ row[k] = current;
550
+ }
551
+ }
552
+ return row[aLen] ?? 0;
553
+ }
554
+ //#endregion
555
+ export { buildFlagLookup, flagExpectsValue, includesBeforeSeparator, parse, stripBeforeSeparator, tokenize };
@@ -1,6 +1,5 @@
1
1
  import { ConfirmPromptConfig, InputPromptConfig, PromptConfig, PromptResult, SelectChoice } from "../schema/prompt.mjs";
2
2
  import { WriteFn } from "../output/writer.mjs";
3
-
4
3
  //#region src/core/prompt/index.d.ts
5
4
  /**
6
5
  * A select prompt config with choices guaranteed non-empty.