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