@kjanat/dreamcli 0.0.0 → 2.0.0

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