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