@kjanat/dreamcli 2.5.0 → 3.0.0-rc.10

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 (202) hide show
  1. package/CHANGELOG.md +344 -1
  2. package/README.md +9 -2
  3. package/dist/core/cli/dispatch.d.mts +6 -5
  4. package/dist/core/cli/dispatch.mjs +205 -1
  5. package/dist/core/cli/help-links.d.mts +0 -1
  6. package/dist/core/cli/help-links.mjs +41 -1
  7. package/dist/core/cli/index.d.mts +185 -19
  8. package/dist/core/cli/index.mjs +945 -1
  9. package/dist/core/cli/planner.d.mts +32 -6
  10. package/dist/core/cli/planner.mjs +300 -1
  11. package/dist/core/cli/plugin.d.mts +1 -1
  12. package/dist/core/cli/plugin.mjs +41 -1
  13. package/dist/core/cli/propagate.d.mts +1 -1
  14. package/dist/core/cli/propagate.mjs +57 -1
  15. package/dist/core/cli/root-help.d.mts +18 -3
  16. package/dist/core/cli/root-help.mjs +226 -6
  17. package/dist/core/cli/root-surface.d.mts +30 -4
  18. package/dist/core/cli/root-surface.mjs +28 -1
  19. package/dist/core/cli/runtime-preflight.d.mts +30 -3
  20. package/dist/core/cli/runtime-preflight.mjs +169 -1
  21. package/dist/core/completion/index.d.mts +32 -2
  22. package/dist/core/completion/index.mjs +90 -1
  23. package/dist/core/completion/shells/bash.d.mts +0 -1
  24. package/dist/core/completion/shells/bash.mjs +308 -3
  25. package/dist/core/completion/shells/fish.d.mts +0 -1
  26. package/dist/core/completion/shells/fish.mjs +162 -2
  27. package/dist/core/completion/shells/powershell.d.mts +0 -1
  28. package/dist/core/completion/shells/powershell.mjs +358 -2
  29. package/dist/core/completion/shells/shared.d.mts +23 -2
  30. package/dist/core/completion/shells/shared.mjs +176 -1
  31. package/dist/core/completion/shells/zsh.d.mts +0 -1
  32. package/dist/core/completion/shells/zsh.mjs +251 -2
  33. package/dist/core/config/index.d.mts +2 -3
  34. package/dist/core/config/index.mjs +246 -1
  35. package/dist/core/config/package-json.d.mts +27 -4
  36. package/dist/core/config/package-json.mjs +386 -3
  37. package/dist/core/errors/index.d.mts +3 -3
  38. package/dist/core/errors/index.mjs +87 -1
  39. package/dist/core/execution/index.d.mts +0 -1
  40. package/dist/core/execution/index.mjs +201 -1
  41. package/dist/core/help/ansi.d.mts +11 -5
  42. package/dist/core/help/ansi.mjs +121 -2
  43. package/dist/core/help/index.d.mts +65 -2
  44. package/dist/core/help/index.mjs +341 -7
  45. package/dist/core/help/theme.d.mts +68 -0
  46. package/dist/core/help/theme.mjs +46 -0
  47. package/dist/core/json-schema/index.d.mts +15 -2
  48. package/dist/core/json-schema/index.mjs +536 -12
  49. package/dist/core/json-schema/meta-descriptions.generated.d.mts +22 -5
  50. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  51. package/dist/core/output/activity.d.mts +0 -1
  52. package/dist/core/output/activity.mjs +452 -1
  53. package/dist/core/output/bind.mjs +56 -1
  54. package/dist/core/output/contracts.d.mts +4 -5
  55. package/dist/core/output/contracts.mjs +57 -1
  56. package/dist/core/output/display-value.mjs +32 -1
  57. package/dist/core/output/index.d.mts +21 -1
  58. package/dist/core/output/index.mjs +442 -2
  59. package/dist/core/output/renderers.d.mts +0 -1
  60. package/dist/core/output/renderers.mjs +46 -1
  61. package/dist/core/output/writer.mjs +12 -1
  62. package/dist/core/parse/index.d.mts +54 -7
  63. package/dist/core/parse/index.mjs +727 -1
  64. package/dist/core/prompt/index.d.mts +12 -4
  65. package/dist/core/prompt/index.mjs +348 -6
  66. package/dist/core/resolve/args.d.mts +1 -1
  67. package/dist/core/resolve/args.mjs +105 -1
  68. package/dist/core/resolve/coerce.d.mts +1 -1
  69. package/dist/core/resolve/coerce.mjs +336 -1
  70. package/dist/core/resolve/config.mjs +19 -1
  71. package/dist/core/resolve/contracts.d.mts +9 -4
  72. package/dist/core/resolve/errors.d.mts +0 -1
  73. package/dist/core/resolve/errors.mjs +140 -2
  74. package/dist/core/resolve/flags.d.mts +7 -2
  75. package/dist/core/resolve/flags.mjs +251 -1
  76. package/dist/core/resolve/index.d.mts +2 -2
  77. package/dist/core/resolve/index.mjs +85 -1
  78. package/dist/core/resolve/property.d.mts +6 -2
  79. package/dist/core/resolve/property.mjs +53 -1
  80. package/dist/core/schema/activity.d.mts +31 -11
  81. package/dist/core/schema/arg.d.mts +92 -13
  82. package/dist/core/schema/arg.mjs +463 -1
  83. package/dist/core/schema/command.d.mts +29 -7
  84. package/dist/core/schema/command.mjs +726 -1
  85. package/dist/core/schema/flag.d.mts +577 -21
  86. package/dist/core/schema/flag.mjs +705 -1
  87. package/dist/core/schema/index.d.mts +5 -2
  88. package/dist/core/schema/middleware.d.mts +4 -3
  89. package/dist/core/schema/middleware.mjs +41 -1
  90. package/dist/core/schema/number-constraints.d.mts +96 -0
  91. package/dist/core/schema/number-constraints.mjs +60 -0
  92. package/dist/core/schema/prompt.d.mts +21 -3
  93. package/dist/core/schema/run.d.mts +24 -5
  94. package/dist/core/schema/string-constraints.d.mts +97 -0
  95. package/dist/core/schema/string-constraints.mjs +69 -0
  96. package/dist/core/schema/value-parsers.d.mts +78 -0
  97. package/dist/core/schema/value-parsers.mjs +142 -0
  98. package/dist/core/schema-dsl/runtime.mjs +271 -2
  99. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  100. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  101. package/dist/core/testkit/index.d.mts +9 -36
  102. package/dist/core/testkit/index.mjs +83 -1
  103. package/dist/index.d.mts +12 -6
  104. package/dist/index.mjs +22 -1
  105. package/dist/runtime/adapter.d.mts +38 -2
  106. package/dist/runtime/adapter.mjs +87 -1
  107. package/dist/runtime/auto.d.mts +2 -3
  108. package/dist/runtime/auto.mjs +45 -1
  109. package/dist/runtime/deno.d.mts +24 -5
  110. package/dist/runtime/deno.mjs +262 -2
  111. package/dist/runtime/detect.mjs +45 -1
  112. package/dist/runtime/index.d.mts +3 -4
  113. package/dist/runtime/node.d.mts +8 -2
  114. package/dist/runtime/node.mjs +220 -2
  115. package/dist/runtime/paths.mjs +48 -1
  116. package/dist/runtime.d.mts +4 -4
  117. package/dist/runtime.mjs +6 -1
  118. package/dist/strings.mjs +22 -1
  119. package/dist/testkit.d.mts +1 -0
  120. package/dist/testkit.mjs +5 -1
  121. package/dist/version.d.mts +7 -3
  122. package/dist/version.mjs +7 -1
  123. package/dreamcli.schema.json +36 -7
  124. package/examples/basic.ts +5 -1
  125. package/examples/gh/package.json +2 -7
  126. package/examples/pwsh-demo/package.json +1 -7
  127. package/examples/pwsh-demo/src/main.test.ts +1 -4
  128. package/examples/pwsh-demo/src/main.ts +14 -4
  129. package/examples/transport-launcher.ts +85 -0
  130. package/package.json +43 -49
  131. package/dist/runtime/bun.d.mts +0 -28
  132. package/dist/runtime/bun.mjs +0 -1
  133. package/dist/runtime/support.d.mts +0 -42
  134. package/dist/runtime/support.mjs +0 -1
  135. package/src/core/cli/dispatch.ts +0 -349
  136. package/src/core/cli/help-links.ts +0 -82
  137. package/src/core/cli/index.ts +0 -1413
  138. package/src/core/cli/planner.ts +0 -487
  139. package/src/core/cli/plugin.ts +0 -117
  140. package/src/core/cli/propagate.ts +0 -97
  141. package/src/core/cli/root-help.ts +0 -252
  142. package/src/core/cli/root-surface.ts +0 -74
  143. package/src/core/cli/runtime-preflight.ts +0 -438
  144. package/src/core/completion/index.ts +0 -88
  145. package/src/core/completion/shells/bash.ts +0 -459
  146. package/src/core/completion/shells/fish.ts +0 -259
  147. package/src/core/completion/shells/powershell.ts +0 -439
  148. package/src/core/completion/shells/shared.ts +0 -283
  149. package/src/core/completion/shells/zsh.ts +0 -381
  150. package/src/core/config/index.ts +0 -417
  151. package/src/core/config/package-json.ts +0 -560
  152. package/src/core/errors/index.ts +0 -193
  153. package/src/core/execution/index.ts +0 -268
  154. package/src/core/help/ansi.ts +0 -144
  155. package/src/core/help/index.ts +0 -516
  156. package/src/core/json-schema/index.ts +0 -891
  157. package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
  158. package/src/core/output/activity.ts +0 -575
  159. package/src/core/output/bind.ts +0 -59
  160. package/src/core/output/contracts.ts +0 -194
  161. package/src/core/output/display-value.ts +0 -48
  162. package/src/core/output/index.ts +0 -704
  163. package/src/core/output/renderers.ts +0 -125
  164. package/src/core/output/writer.ts +0 -46
  165. package/src/core/parse/index.ts +0 -681
  166. package/src/core/prompt/index.ts +0 -583
  167. package/src/core/resolve/args.ts +0 -144
  168. package/src/core/resolve/coerce.ts +0 -432
  169. package/src/core/resolve/config.ts +0 -26
  170. package/src/core/resolve/contracts.ts +0 -135
  171. package/src/core/resolve/errors.ts +0 -227
  172. package/src/core/resolve/flags.ts +0 -255
  173. package/src/core/resolve/index.ts +0 -108
  174. package/src/core/resolve/property.ts +0 -99
  175. package/src/core/schema/activity.ts +0 -240
  176. package/src/core/schema/arg.ts +0 -719
  177. package/src/core/schema/command.ts +0 -1498
  178. package/src/core/schema/flag.ts +0 -801
  179. package/src/core/schema/index.ts +0 -91
  180. package/src/core/schema/middleware.ts +0 -171
  181. package/src/core/schema/prompt.ts +0 -156
  182. package/src/core/schema/run.ts +0 -198
  183. package/src/core/schema-dsl/index.ts +0 -109
  184. package/src/core/schema-dsl/parse.ts +0 -262
  185. package/src/core/schema-dsl/runtime.ts +0 -609
  186. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  187. package/src/core/testkit/index.ts +0 -123
  188. package/src/index.ts +0 -179
  189. package/src/runtime/adapter.ts +0 -303
  190. package/src/runtime/auto.ts +0 -110
  191. package/src/runtime/bun.ts +0 -55
  192. package/src/runtime/deno.ts +0 -369
  193. package/src/runtime/detect.ts +0 -105
  194. package/src/runtime/index.ts +0 -21
  195. package/src/runtime/node-builtins.d.ts +0 -27
  196. package/src/runtime/node.ts +0 -300
  197. package/src/runtime/paths.ts +0 -64
  198. package/src/runtime/support.ts +0 -135
  199. package/src/runtime.ts +0 -31
  200. package/src/strings.ts +0 -34
  201. package/src/testkit.ts +0 -25
  202. package/src/version.ts +0 -20
@@ -1,681 +0,0 @@
1
- /**
2
- * Argv tokenization and parsing against command schemas.
3
- *
4
- * Two-phase design:
5
- *
6
- * 1. **Tokenize** — split raw argv into structured tokens (long flags, short
7
- * flags, positionals, separator). Schema-agnostic.
8
- *
9
- * 2. **Parse** — walk tokens against a {@linkcode CommandSchema} to produce typed raw
10
- * values. Emits {@linkcode ParseError} for unknown flags, type mismatches, missing
11
- * values.
12
- *
13
- * @module dreamcli/core/parse
14
- */
15
-
16
- import { ParseError } from '#internals/core/errors/index.ts';
17
- import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
18
- import type {
19
- ArgSchema,
20
- CommandArgEntry,
21
- CommandSchema,
22
- FlagSchema,
23
- } from '#internals/core/schema/index.ts';
24
-
25
- // --- Tokenizer — schema-agnostic argv splitting
26
-
27
- /**
28
- * Token discriminated union.
29
- *
30
- * The tokenizer produces these from raw argv strings. The parser then
31
- * interprets them against a command schema.
32
- */
33
- type Token =
34
- | { readonly kind: 'long-flag'; readonly name: string; readonly value: string | undefined }
35
- | { readonly kind: 'short-flags'; readonly chars: string }
36
- | { readonly kind: 'positional'; readonly value: string }
37
- | { readonly kind: 'separator' };
38
-
39
- /**
40
- * Tokenize raw argv into structured tokens.
41
- *
42
- * Low-level utility: most apps should use {@link parse}, `cli().run()`, or
43
- * `runCommand()` instead of tokenizing manually. Reach for `tokenize()` when
44
- * building custom tooling such as debuggers, inspectors, or parser tests.
45
- *
46
- * Rules:
47
- * - `--` → separator (everything after is positional)
48
- * - `--flag` → long flag, no inline value
49
- * - `--flag=v` → long flag with inline value
50
- * - `-abc` → short flags (expanded individually by parser)
51
- * - `-` → positional (convention: stdin placeholder)
52
- * - everything else → positional
53
- *
54
- * @param argv - Raw argument strings to tokenize
55
- * @returns Ordered token array ready for {@link parse}
56
- *
57
- * @example
58
- * ```ts
59
- * tokenize(['deploy', '--force', '--region=eu', '-v']);
60
- * ```
61
- */
62
- function tokenize(argv: readonly string[]): readonly Token[] {
63
- const tokens: Token[] = [];
64
- let pastSeparator = false;
65
-
66
- for (const raw of argv) {
67
- if (pastSeparator) {
68
- tokens.push({ kind: 'positional', value: raw });
69
- continue;
70
- }
71
-
72
- if (raw === '--') {
73
- tokens.push({ kind: 'separator' });
74
- pastSeparator = true;
75
- continue;
76
- }
77
-
78
- if (raw.startsWith('--')) {
79
- const eqIdx = raw.indexOf('=');
80
- if (eqIdx !== -1) {
81
- tokens.push({
82
- kind: 'long-flag',
83
- name: raw.slice(2, eqIdx),
84
- value: raw.slice(eqIdx + 1),
85
- });
86
- } else {
87
- tokens.push({ kind: 'long-flag', name: raw.slice(2), value: undefined });
88
- }
89
- continue;
90
- }
91
-
92
- // Single `-` is a positional (stdin convention), not a flag
93
- if (raw.startsWith('-') && raw.length > 1) {
94
- tokens.push({ kind: 'short-flags', chars: raw.slice(1) });
95
- continue;
96
- }
97
-
98
- tokens.push({ kind: 'positional', value: raw });
99
- }
100
-
101
- return tokens;
102
- }
103
-
104
- /**
105
- * Whether `token` appears in argv before the `--` end-of-options separator.
106
- *
107
- * Everything at or after the first `--` is a literal positional, so root-level
108
- * flag interception (`--help` / `--version` / `--json`) must use this instead of
109
- * a naive `Array.includes()` — otherwise a post-separator literal (`-- --json`)
110
- * is wrongly treated as the flag.
111
- *
112
- * @param argv - Raw argument strings.
113
- * @param token - Exact flag token to look for (e.g. `--version`).
114
- * @returns `true` if `token` occurs before any `--` separator.
115
- */
116
- function includesBeforeSeparator(argv: readonly string[], token: string): boolean {
117
- for (const arg of argv) {
118
- if (arg === '--') return false;
119
- if (arg === token) return true;
120
- }
121
- return false;
122
- }
123
-
124
- // --- Parse result
125
-
126
- /**
127
- * Raw parsed values before resolution (defaults, env, config, etc.).
128
- *
129
- * Flag values are `unknown` because type coercion happens here but the
130
- * generic type info lives in the schema builders, not at runtime.
131
- */
132
- interface ParseResult {
133
- /** Flag values keyed by canonical flag name. */
134
- readonly flags: Readonly<Record<string, unknown>>;
135
- /** Positional arg values keyed by arg name. */
136
- readonly args: Readonly<Record<string, unknown>>;
137
- }
138
-
139
- // --- Internal lookup helpers
140
-
141
- /**
142
- * Build a map from flag name/alias → [canonicalName, {@link FlagSchema}].
143
- *
144
- * Supports both long names and single-char aliases for short flag expansion.
145
- *
146
- * @param flags - Flag schemas keyed by canonical name
147
- * @returns Lookup map covering all names and aliases
148
- */
149
- function buildFlagLookup(
150
- flags: Readonly<Record<string, FlagSchema>>,
151
- ): ReadonlyMap<string, readonly [name: string, schema: FlagSchema]> {
152
- const lookup = new Map<string, readonly [string, FlagSchema]>();
153
- for (const [name, schema] of Object.entries(flags)) {
154
- lookup.set(name, [name, schema]);
155
- for (const alias of getFlagAliasNames(schema, { includeHidden: true })) {
156
- lookup.set(alias, [name, schema]);
157
- }
158
- }
159
- return lookup;
160
- }
161
-
162
- /**
163
- * Whether a flag kind expects a value argument (vs. being a bare boolean).
164
- *
165
- * @param schema - Flag schema to check
166
- * @returns `true` if the flag expects a value token after it
167
- */
168
- function flagExpectsValue(schema: FlagSchema): boolean {
169
- return schema.kind !== 'boolean';
170
- }
171
-
172
- // --- Value coercion
173
-
174
- /**
175
- * Coerce a raw string to the flag's declared kind.
176
- *
177
- * @param flagName - Canonical flag name (for error messages)
178
- * @param raw - Raw string value from argv
179
- * @param schema - {@link FlagSchema} declaring the expected kind
180
- * @returns Coerced value matching the schema's kind
181
- * @throws ParseError on type mismatch
182
- */
183
- function coerceFlagValue(
184
- flagName: string,
185
- raw: string,
186
- schema: FlagSchema,
187
- displayName = `--${flagName}`,
188
- ): unknown {
189
- switch (schema.kind) {
190
- case 'string':
191
- return raw;
192
-
193
- case 'number': {
194
- const n = Number(raw);
195
- if (Number.isNaN(n)) {
196
- throw new ParseError(`Invalid number value '${raw}' for flag ${displayName}`, {
197
- code: 'INVALID_VALUE',
198
- details: { flag: flagName, input: displayName, value: raw, expected: 'number' },
199
- });
200
- }
201
- return n;
202
- }
203
-
204
- case 'boolean':
205
- // Explicit boolean values: --flag=true / --flag=false
206
- if (raw === 'true' || raw === '1') return true;
207
- if (raw === 'false' || raw === '0') return false;
208
- throw new ParseError(
209
- `Invalid boolean value '${raw}' for flag ${displayName}. Use true/false or 1/0`,
210
- {
211
- code: 'INVALID_VALUE',
212
- details: { flag: flagName, input: displayName, value: raw, expected: 'boolean' },
213
- },
214
- );
215
-
216
- case 'enum': {
217
- const allowed = schema.enumValues;
218
- if (allowed === undefined) {
219
- throw new ParseError(
220
- `Enum flag --${flagName} is misconfigured: no allowed values declared`,
221
- {
222
- code: 'INVALID_SCHEMA',
223
- details: { flag: flagName, kind: 'enum', missing: 'enumValues' },
224
- },
225
- );
226
- }
227
- if (!allowed.includes(raw)) {
228
- throw new ParseError(
229
- `Invalid value '${raw}' for flag ${displayName}. Allowed: ${allowed.join(', ')}`,
230
- {
231
- code: 'INVALID_VALUE',
232
- details: { flag: flagName, input: displayName, value: raw, allowed },
233
- },
234
- );
235
- }
236
- return raw;
237
- }
238
-
239
- case 'array':
240
- // Array element — coerce via element schema if present
241
- if (schema.elementSchema) {
242
- return coerceFlagValue(flagName, raw, schema.elementSchema);
243
- }
244
- return raw;
245
-
246
- case 'custom': {
247
- if (!schema.parseFn) {
248
- return raw;
249
- }
250
- try {
251
- return schema.parseFn(raw);
252
- } catch (err) {
253
- if (err instanceof ParseError) throw err;
254
- const message = err instanceof Error ? err.message : String(err);
255
- throw new ParseError(`Failed to parse flag ${displayName}: ${message}`, {
256
- code: 'INVALID_VALUE',
257
- details: { flag: flagName, input: displayName, value: raw },
258
- cause: err,
259
- });
260
- }
261
- }
262
- }
263
- }
264
-
265
- /**
266
- * Coerce a raw string to the arg's declared kind.
267
- *
268
- * @param argName - Positional arg name (for error messages)
269
- * @param raw - Raw string value from argv
270
- * @param schema - {@link ArgSchema} declaring the expected kind
271
- * @returns Coerced value matching the schema's kind
272
- * @throws ParseError on type mismatch or custom parse failure
273
- */
274
- function coerceArgValue(argName: string, raw: string, schema: ArgSchema): unknown {
275
- switch (schema.kind) {
276
- case 'string':
277
- return raw;
278
-
279
- case 'number': {
280
- const n = Number(raw);
281
- if (Number.isNaN(n)) {
282
- throw new ParseError(`Invalid number value '${raw}' for argument <${argName}>`, {
283
- code: 'INVALID_VALUE',
284
- details: { arg: argName, value: raw, expected: 'number' },
285
- });
286
- }
287
- return n;
288
- }
289
-
290
- case 'enum': {
291
- const allowed = schema.enumValues;
292
- if (allowed === undefined) {
293
- throw new ParseError(
294
- `Enum argument <${argName}> is misconfigured: no allowed values declared`,
295
- {
296
- code: 'INVALID_SCHEMA',
297
- details: { arg: argName, kind: 'enum', missing: 'enumValues' },
298
- },
299
- );
300
- }
301
- if (!allowed.includes(raw)) {
302
- throw new ParseError(
303
- `Invalid value '${raw}' for argument <${argName}>. Allowed: ${allowed.join(', ')}`,
304
- {
305
- code: 'INVALID_VALUE',
306
- details: { arg: argName, value: raw, allowed },
307
- },
308
- );
309
- }
310
- return raw;
311
- }
312
-
313
- case 'custom': {
314
- if (!schema.parseFn) {
315
- return raw;
316
- }
317
- try {
318
- return schema.parseFn(raw);
319
- } catch (err) {
320
- if (err instanceof ParseError) throw err;
321
- const message = err instanceof Error ? err.message : String(err);
322
- throw new ParseError(`Failed to parse argument <${argName}>: ${message}`, {
323
- code: 'INVALID_VALUE',
324
- details: { arg: argName, value: raw },
325
- cause: err,
326
- });
327
- }
328
- }
329
- }
330
- }
331
-
332
- // --- Parser — schema-aware token interpretation
333
-
334
- /**
335
- * Parse tokenized argv against a command schema.
336
- *
337
- * Low-level API: most apps should let `cli()` or `runCommand()` handle parsing
338
- * automatically. Call `parse()` directly when you need raw parsed values before
339
- * env/config/default resolution or when writing custom tooling around schemas.
340
- *
341
- * @param schema - The command schema to parse against
342
- * @param argv - Raw argv strings (NOT including the command name itself)
343
- * @returns Parsed flag and arg values
344
- * @throws ParseError for unknown flags, missing values, type mismatches
345
- *
346
- * @example
347
- * ```ts
348
- * const parsed = parse(deploy.schema, ['production', '--force']);
349
- * // => { args: { target: 'production' }, flags: { force: true } }
350
- * ```
351
- */
352
- function parse(schema: CommandSchema, argv: readonly string[]): ParseResult {
353
- const tokens = tokenize(argv);
354
- const flagLookup = buildFlagLookup(schema.flags);
355
-
356
- // Mutable accumulators — frozen in the result
357
- const flags: Record<string, unknown> = {};
358
- const positionals: string[] = [];
359
-
360
- let i = 0;
361
- while (i < tokens.length) {
362
- const token = tokens[i];
363
- if (token === undefined) break; // unreachable — loop guard ensures i < length
364
-
365
- if (token.kind === 'separator') {
366
- i++;
367
- continue;
368
- }
369
-
370
- if (token.kind === 'positional') {
371
- positionals.push(token.value);
372
- i++;
373
- continue;
374
- }
375
-
376
- if (token.kind === 'long-flag') {
377
- i = parseLongFlag(token, tokens, i, flagLookup, flags);
378
- continue;
379
- }
380
-
381
- // token.kind === 'short-flags'
382
- i = parseShortFlags(token, tokens, i, flagLookup, flags);
383
- }
384
-
385
- // Map positionals to named args
386
- const args = mapPositionals(schema.args, positionals);
387
-
388
- return { flags, args };
389
- }
390
-
391
- // --- Long flag parsing
392
-
393
- /**
394
- * Parse a long flag token, consuming a value from the next token if needed.
395
- *
396
- * @param token - Long-flag token to process
397
- * @param tokens - Full token array (for lookahead)
398
- * @param startIdx - Current index of `token` in the array
399
- * @param flagLookup - Name/alias → [canonical, schema] map from {@link buildFlagLookup}
400
- * @param flags - Mutable accumulator for resolved flag values
401
- * @returns Next index to continue parsing from
402
- */
403
- function parseLongFlag(
404
- token: { readonly kind: 'long-flag'; readonly name: string; readonly value: string | undefined },
405
- tokens: readonly Token[],
406
- startIdx: number,
407
- flagLookup: ReadonlyMap<string, readonly [string, FlagSchema]>,
408
- flags: Record<string, unknown>,
409
- ): number {
410
- const entry = flagLookup.get(token.name);
411
- if (!entry) {
412
- const suggestion = suggestFlag(token.name, flagLookup);
413
- throw new ParseError(
414
- `Unknown flag --${token.name}${suggestion ? `. Did you mean --${suggestion}?` : ''}`,
415
- {
416
- code: 'UNKNOWN_FLAG',
417
- details: { flag: token.name, ...(suggestion ? { suggestion } : {}) },
418
- ...(suggestion ? { suggest: `--${suggestion}` } : {}),
419
- },
420
- );
421
- }
422
-
423
- const [canonicalName, flagSchema] = entry;
424
-
425
- if (!flagExpectsValue(flagSchema)) {
426
- // Boolean flag
427
- if (token.value !== undefined) {
428
- flags[canonicalName] = coerceFlagValue(
429
- canonicalName,
430
- token.value,
431
- flagSchema,
432
- `--${token.name}`,
433
- );
434
- } else {
435
- flags[canonicalName] = true;
436
- }
437
- return startIdx + 1;
438
- }
439
-
440
- if (token.value !== undefined) {
441
- // --flag=value (inline)
442
- setFlagValue(flags, canonicalName, flagSchema, token.value);
443
- return startIdx + 1;
444
- }
445
-
446
- // --flag value (next token is the value)
447
- const nextToken = tokens[startIdx + 1];
448
- if (nextToken?.kind !== 'positional') {
449
- throw new ParseError(`Flag --${token.name} requires a value`, {
450
- code: 'MISSING_VALUE',
451
- details: { flag: canonicalName, input: token.name, kind: flagSchema.kind },
452
- });
453
- }
454
- setFlagValue(flags, canonicalName, flagSchema, nextToken.value, `--${token.name}`);
455
- return startIdx + 2;
456
- }
457
-
458
- // --- Short flag parsing
459
-
460
- /**
461
- * Parse combined short flags, expanding -abc into individual flags.
462
- *
463
- * @param token - Short-flags token to expand
464
- * @param tokens - Full token array (for lookahead)
465
- * @param startIdx - Current index of `token` in the array
466
- * @param flagLookup - Name/alias → [canonical, schema] map from {@link buildFlagLookup}
467
- * @param flags - Mutable accumulator for resolved flag values
468
- * @returns Next index to continue parsing from
469
- */
470
- function parseShortFlags(
471
- token: { readonly kind: 'short-flags'; readonly chars: string },
472
- tokens: readonly Token[],
473
- startIdx: number,
474
- flagLookup: ReadonlyMap<string, readonly [string, FlagSchema]>,
475
- flags: Record<string, unknown>,
476
- ): number {
477
- const { chars } = token;
478
- let nextIdx = startIdx + 1;
479
-
480
- for (let ci = 0; ci < chars.length; ci++) {
481
- const ch = chars.charAt(ci);
482
- const entry = flagLookup.get(ch);
483
- if (!entry) {
484
- throw new ParseError(`Unknown flag -${ch}`, {
485
- code: 'UNKNOWN_FLAG',
486
- details: { flag: ch },
487
- });
488
- }
489
-
490
- const [canonicalName, flagSchema] = entry;
491
-
492
- if (!flagExpectsValue(flagSchema)) {
493
- // Boolean short flag
494
- flags[canonicalName] = true;
495
- continue;
496
- }
497
-
498
- if (ci < chars.length - 1) {
499
- // Value-expecting flag in the middle of combined shorts:
500
- // -oFile → -o with value "File" (rest of chars is the value)
501
- const inlineValue = chars.slice(ci + 1);
502
- setFlagValue(flags, canonicalName, flagSchema, inlineValue, `-${ch}`);
503
- break; // consumed all remaining chars
504
- }
505
-
506
- // Last char in the group — consume next token as value
507
- const nextToken = tokens[nextIdx];
508
- if (nextToken?.kind !== 'positional') {
509
- throw new ParseError(`Flag -${ch} requires a value`, {
510
- code: 'MISSING_VALUE',
511
- details: { flag: canonicalName, input: ch, kind: flagSchema.kind },
512
- });
513
- }
514
- setFlagValue(flags, canonicalName, flagSchema, nextToken.value, `-${ch}`);
515
- nextIdx++;
516
- }
517
-
518
- return nextIdx;
519
- }
520
-
521
- // --- Flag value setter (handles array accumulation)
522
-
523
- /**
524
- * Set or accumulate a flag value, handling array flags specially.
525
- *
526
- * @param flags - Mutable accumulator for resolved flag values
527
- * @param name - Canonical flag name
528
- * @param schema - {@link FlagSchema} declaring the expected kind
529
- * @param rawValue - Raw string value from argv
530
- */
531
- function setFlagValue(
532
- flags: Record<string, unknown>,
533
- name: string,
534
- schema: FlagSchema,
535
- rawValue: string,
536
- displayName = `--${name}`,
537
- ): void {
538
- const coerced = coerceFlagValue(name, rawValue, schema, displayName);
539
-
540
- if (schema.kind === 'array') {
541
- const existing = flags[name];
542
- if (Array.isArray(existing)) {
543
- existing.push(coerced);
544
- } else {
545
- flags[name] = [coerced];
546
- }
547
- } else {
548
- flags[name] = coerced;
549
- }
550
- }
551
-
552
- // --- Positional arg mapping
553
-
554
- /**
555
- * Map positional values to named args based on schema ordering.
556
- *
557
- * @param argEntries - Ordered arg schemas from the command
558
- * @param positionals - Positional values collected during tokenization
559
- * @returns Named arg values keyed by arg name
560
- * @throws ParseError if too many positionals and no variadic arg absorbs them
561
- */
562
- function mapPositionals(
563
- argEntries: readonly CommandArgEntry[],
564
- positionals: readonly string[],
565
- ): Record<string, unknown> {
566
- const args: Record<string, unknown> = {};
567
- let posIdx = 0;
568
-
569
- for (const entry of argEntries) {
570
- if (entry.schema.variadic) {
571
- // Variadic arg consumes all remaining positionals
572
- const remaining = positionals.slice(posIdx);
573
- args[entry.name] = remaining.map((raw) => coerceArgValue(entry.name, raw, entry.schema));
574
- posIdx = positionals.length;
575
- break;
576
- }
577
-
578
- const rawPositional = positionals[posIdx];
579
- if (rawPositional !== undefined) {
580
- args[entry.name] = coerceArgValue(entry.name, rawPositional, entry.schema);
581
- posIdx++;
582
- }
583
- // If no positional available, leave absent (resolution/validation handles defaults/required)
584
- }
585
-
586
- // Check for excess positionals
587
- if (posIdx < positionals.length) {
588
- const excess = positionals.slice(posIdx);
589
- throw new ParseError(
590
- `Unexpected positional argument${excess.length > 1 ? 's' : ''}: ${excess.join(', ')}`,
591
- {
592
- code: 'UNEXPECTED_POSITIONAL',
593
- details: { excess, expected: argEntries.length },
594
- },
595
- );
596
- }
597
-
598
- return args;
599
- }
600
-
601
- // --- Suggestion helper (Levenshtein-based "did you mean?")
602
-
603
- /**
604
- * Suggest the closest flag name if the edit distance is small enough.
605
- *
606
- * @param input - Misspelled flag name from the user
607
- * @param lookup - Flag lookup map from {@link buildFlagLookup}
608
- * @returns Closest flag name, or `undefined` if no close match exists
609
- */
610
- function suggestFlag(
611
- input: string,
612
- lookup: ReadonlyMap<string, readonly [string, FlagSchema]>,
613
- ): string | undefined {
614
- let bestName: string | undefined;
615
- let bestDist = Number.POSITIVE_INFINITY;
616
- const threshold = Math.max(2, Math.floor(input.length / 2));
617
-
618
- for (const key of lookup.keys()) {
619
- const entry = lookup.get(key);
620
- if (entry === undefined) continue;
621
- const [canonicalName, schema] = entry;
622
- const alias = schema.aliases.find((candidate) => candidate.name === key);
623
-
624
- // Only suggest canonical names or visible long aliases.
625
- if (key.length < 2) continue;
626
- if (key !== canonicalName && alias?.hidden) continue;
627
-
628
- const dist = levenshtein(input, key);
629
- if (dist < bestDist && dist <= threshold) {
630
- bestDist = dist;
631
- bestName = key;
632
- }
633
- }
634
-
635
- return bestName;
636
- }
637
-
638
- /**
639
- * Classic Levenshtein distance using a single-row DP approach.
640
- *
641
- * @param a - First string
642
- * @param b - Second string
643
- * @returns Edit distance between `a` and `b`
644
- */
645
- function levenshtein(a: string, b: string): number {
646
- if (a === b) return 0;
647
- if (a.length === 0) return b.length;
648
- if (b.length === 0) return a.length;
649
-
650
- // Ensure `short` is the shorter string for the single-row optimisation
651
- const short = a.length <= b.length ? a : b;
652
- const long = a.length <= b.length ? b : a;
653
-
654
- const aLen = short.length;
655
- const bLen = long.length;
656
-
657
- // Previous row of distances
658
- const row = Array.from({ length: aLen + 1 }, (_, i) => i);
659
-
660
- for (let j = 1; j <= bLen; j++) {
661
- let prev = row[0] ?? 0;
662
- row[0] = j;
663
- for (let k = 1; k <= aLen; k++) {
664
- const cost = short.charAt(k - 1) === long.charAt(j - 1) ? 0 : 1;
665
- const current = Math.min(
666
- (row[k] ?? 0) + 1, // deletion
667
- (row[k - 1] ?? 0) + 1, // insertion
668
- prev + cost, // substitution
669
- );
670
- prev = row[k] ?? 0;
671
- row[k] = current;
672
- }
673
- }
674
-
675
- return row[aLen] ?? 0;
676
- }
677
-
678
- // --- Exports
679
-
680
- export type { ParseResult, Token };
681
- export { buildFlagLookup, flagExpectsValue, includesBeforeSeparator, parse, tokenize };