@politty/zod 0.1.1 → 0.2.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 (59) hide show
  1. package/README.md +31 -0
  2. package/dist/{arg-registry-B8QvBM_Q.d.ts → arg-registry-Be4GJADw.d.ts} +15 -1
  3. package/dist/augment.d.ts +1 -1
  4. package/dist/augment.js +1 -1
  5. package/dist/cli-main-C8D_mKfv.js +2 -0
  6. package/dist/cli-main-ClQaGXB3.js +1 -0
  7. package/dist/cli-run-BFXIag27.js +1 -0
  8. package/dist/cli.js +1 -15
  9. package/dist/command-Mbdt0bmN.js +1 -0
  10. package/dist/compile-cache-VuUbFWIo.js +1 -0
  11. package/dist/compile-cache.js +1 -3
  12. package/dist/completion-D8DMrPqg.js +116 -0
  13. package/dist/completion-DUMcvXkT.js +1 -0
  14. package/dist/completion.d.ts +87 -7
  15. package/dist/completion.js +1 -4
  16. package/dist/docs.d.ts +1 -1
  17. package/dist/docs.js +84 -3045
  18. package/dist/dynamic-CMtee4tD.js +1 -0
  19. package/dist/dynamic-CrnlveHj.js +6 -0
  20. package/dist/field-meta-COGya7xp.js +1 -0
  21. package/dist/index.d.ts +20 -16
  22. package/dist/index.js +1 -27
  23. package/dist/log-collector-hiFa3sNm.js +1 -0
  24. package/dist/logger-CJsyJ8sb.js +1 -0
  25. package/dist/prompt-CqmGq1_N.js +1 -0
  26. package/dist/prompt-clack.d.ts +1 -1
  27. package/dist/prompt-clack.js +1 -32
  28. package/dist/prompt-inquirer.d.ts +1 -1
  29. package/dist/prompt-inquirer.js +1 -47
  30. package/dist/prompt.d.ts +1 -1
  31. package/dist/prompt.js +1 -4
  32. package/dist/register-C1WbbeYH.js +1 -0
  33. package/dist/runner-C_wCXh6X.js +1 -0
  34. package/dist/runner-uPmkI9Gb.js +29 -0
  35. package/dist/schema-BiUP_KyV.js +1 -0
  36. package/dist/schema-extractor-DU0Vuhbd.js +1 -0
  37. package/dist/skill.d.ts +1 -1
  38. package/dist/skill.js +2 -1835
  39. package/dist/subcommand-router-D8GTMXYL.js +1 -0
  40. package/dist/with-completion-command-DDohm8U6.js +3 -0
  41. package/dist/{index-CMb2xLiJ.d.ts → with-completion-command-xaVZtAga.d.ts} +3 -74
  42. package/package.json +3 -3
  43. package/dist/cli-main-BQfutJEX.js +0 -3
  44. package/dist/cli-main-D4kkrRfX.js +0 -314
  45. package/dist/cli-run-wxd6kPPf.js +0 -8
  46. package/dist/command-k-4yAz4J.js +0 -42
  47. package/dist/compile-cache-BC65o7MH.js +0 -103
  48. package/dist/completion-DW5qVc3l.js +0 -5613
  49. package/dist/field-meta-DMy5BcRr.js +0 -146
  50. package/dist/log-collector-CoUkLVJB.js +0 -114
  51. package/dist/logger-i_bb-Jhc.js +0 -133
  52. package/dist/prompt-BjIZThsH.js +0 -169
  53. package/dist/register-DlGnMLIY.js +0 -440
  54. package/dist/runner-DAGvxV2P.js +0 -2980
  55. package/dist/runner-MMjpKeEa.js +0 -3
  56. package/dist/schema-extractor-DMSozq40.js +0 -250
  57. package/dist/src-CLogLsbS.js +0 -12
  58. package/dist/src-bYH2XCQ4.js +0 -6
  59. package/dist/subcommand-router-Cskpofdk.js +0 -134
@@ -1,2980 +0,0 @@
1
- import { a as getValidatorAdapter, i as toKebabCase, r as toCamelCase, t as getAllAliases } from "./field-meta-DMy5BcRr.js";
2
- import { n as getExtractedFields, o as isInternalArgsSchema, s as validateInternalArgs, t as extractFields } from "./schema-extractor-DMSozq40.js";
3
- import { n as enableCompileCache } from "./compile-cache-BC65o7MH.js";
4
- import { n as emptyLogs, r as mergeLogs, t as createLogCollector } from "./log-collector-CoUkLVJB.js";
5
- import { a as resolveSubcommandWithAlias, c as resolveSubCommandMeta, n as listSubCommands, o as isLazyCommand, r as resolveLazyCommand, t as listSubCommandNamesWithAliases } from "./subcommand-router-Cskpofdk.js";
6
- import { a as symbols, i as styles } from "./logger-i_bb-Jhc.js";
7
- import { stripVTControlCharacters } from "node:util";
8
-
9
- //#region ../core/src/executor/command-runner.ts
10
- /**
11
- * Execute a command lifecycle: setup → run → cleanup
12
- *
13
- * This is an internal function that executes the command's lifecycle hooks.
14
- * For running commands with argument parsing, use `runCommand` instead.
15
- *
16
- * @param command - The command to execute
17
- * @param args - Already validated arguments
18
- * @param options - Lifecycle options
19
- * @returns The result of command execution
20
- * @internal
21
- */
22
- async function executeLifecycle(command, args, _options = {}) {
23
- let error;
24
- let result;
25
- const collector = _options.captureLogs ?? false ? createLogCollector() : null;
26
- collector?.start();
27
- const setupContext = { args };
28
- const cleanupContext = {
29
- args,
30
- error
31
- };
32
- let signalHandler;
33
- if (_options.handleSignals) {
34
- signalHandler = async (_signal) => {
35
- if (signalHandler) {
36
- process.off("SIGINT", signalHandler);
37
- process.off("SIGTERM", signalHandler);
38
- }
39
- const signalError = /* @__PURE__ */ new Error("Process interrupted");
40
- cleanupContext.error = signalError;
41
- if (command.cleanup) try {
42
- await command.cleanup(cleanupContext);
43
- } catch (e) {
44
- console.error("Error during signal cleanup:", e);
45
- }
46
- if (_options.globalCleanup) try {
47
- await _options.globalCleanup({ error: signalError });
48
- } catch (e) {
49
- console.error("Error during global signal cleanup:", e);
50
- }
51
- collector?.stop();
52
- if (process.stdout.writableNeedDrain) await new Promise((resolve) => {
53
- const timeout = setTimeout(() => {
54
- process.stdout.off("drain", onDrain);
55
- resolve();
56
- }, 200);
57
- const onDrain = () => {
58
- clearTimeout(timeout);
59
- resolve();
60
- };
61
- process.stdout.once("drain", onDrain);
62
- });
63
- process.exit(1);
64
- };
65
- process.on("SIGINT", signalHandler);
66
- process.on("SIGTERM", signalHandler);
67
- }
68
- try {
69
- if (command.setup) await command.setup(setupContext);
70
- if (command.run) result = await command.run(args);
71
- } catch (e) {
72
- error = e instanceof Error ? e : new Error(String(e));
73
- } finally {
74
- if (signalHandler) {
75
- process.off("SIGINT", signalHandler);
76
- process.off("SIGTERM", signalHandler);
77
- }
78
- }
79
- if (command.cleanup) {
80
- cleanupContext.error = error;
81
- try {
82
- await command.cleanup(cleanupContext);
83
- } catch (cleanupError) {
84
- if (!error) error = cleanupError instanceof Error ? cleanupError : new Error(String(cleanupError));
85
- }
86
- }
87
- collector?.stop();
88
- const existingLogs = _options.existingLogs ?? emptyLogs();
89
- const collectedLogs = collector?.getLogs() ?? emptyLogs();
90
- const logs = mergeLogs(existingLogs, collectedLogs);
91
- if (error) return {
92
- success: false,
93
- error,
94
- exitCode: 1,
95
- logs
96
- };
97
- return {
98
- success: true,
99
- result,
100
- exitCode: 0,
101
- logs
102
- };
103
- }
104
-
105
- //#endregion
106
- //#region ../core/src/output/string-width.ts
107
- /**
108
- * Lightweight replacement for the `string-width` package.
109
- *
110
- * Computes the visual (terminal) width of a string by:
111
- * 1. Stripping ANSI escape codes (via Node's `stripVTControlCharacters`)
112
- * 2. Skipping zero-width characters (combining marks, control chars, etc.)
113
- * 3. Counting East Asian wide / fullwidth characters and most emoji as 2
114
- * 4. Counting everything else as 1
115
- *
116
- * This covers the cases the markdown renderer cares about (CJK text, emoji,
117
- * and already-styled ANSI strings) without pulling in an external dependency.
118
- */
119
- /**
120
- * Whether a code point has no visual width (combining marks, zero-width
121
- * spaces/joiners, variation selectors, control characters).
122
- */
123
- function isZeroWidth(cp) {
124
- return cp <= 31 || cp >= 127 && cp <= 159 || cp >= 768 && cp <= 879 || cp >= 6832 && cp <= 6911 || cp >= 7616 && cp <= 7679 || cp >= 8400 && cp <= 8447 || cp >= 65056 && cp <= 65071 || cp === 8203 || cp >= 8204 && cp <= 8207 || cp === 65279 || cp >= 65024 && cp <= 65039 || cp >= 917760 && cp <= 917999;
125
- }
126
- /**
127
- * Whether a code point is rendered at double (full) width in a terminal.
128
- * Based on Unicode East Asian Width (Wide/Fullwidth) plus common emoji ranges.
129
- */
130
- function isFullWidth(cp) {
131
- return cp >= 4352 && cp <= 4447 || cp >= 11904 && cp <= 12350 || cp >= 12353 && cp <= 13311 || cp >= 13312 && cp <= 19903 || cp >= 19968 && cp <= 40959 || cp >= 40960 && cp <= 42191 || cp >= 43360 && cp <= 43391 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65040 && cp <= 65049 || cp >= 65072 && cp <= 65135 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 110592 && cp <= 110959 || cp >= 127488 && cp <= 127569 || cp >= 131072 && cp <= 262141 || cp >= 9728 && cp <= 10175 || cp >= 126976 && cp <= 129791;
132
- }
133
- /**
134
- * Visual width of a single grapheme cluster (a user-perceived character).
135
- *
136
- * Iterating by code point would over-count multi-code-point clusters such as
137
- * ZWJ emoji sequences (👨‍👩‍👧), regional-indicator flags (🇯🇵), and emoji with
138
- * skin-tone modifiers (👍🏽). These render as a single glyph, so the whole
139
- * cluster contributes width 0/1/2 once.
140
- */
141
- function graphemeWidth(grapheme) {
142
- let hasVisible = false;
143
- let hasWide = false;
144
- let hasEmojiVariation = false;
145
- for (const char of grapheme) {
146
- const cp = char.codePointAt(0);
147
- if (cp === 65039) {
148
- hasEmojiVariation = true;
149
- continue;
150
- }
151
- if (isZeroWidth(cp)) continue;
152
- hasVisible = true;
153
- if (isFullWidth(cp)) hasWide = true;
154
- }
155
- if (!hasVisible) return 0;
156
- return hasWide || hasEmojiVariation ? 2 : 1;
157
- }
158
- const segmenter = (() => {
159
- try {
160
- return new Intl.Segmenter("en", { granularity: "grapheme" });
161
- } catch {
162
- return;
163
- }
164
- })();
165
- /**
166
- * Compute the visual width of a string as rendered in a terminal.
167
- */
168
- function stringWidth(input) {
169
- if (input.length === 0) return 0;
170
- const str = input.includes("\x1B") || input.includes("›") ? stripVTControlCharacters(input) : input;
171
- let width = 0;
172
- if (segmenter) for (const { segment } of segmenter.segment(str)) width += graphemeWidth(segment);
173
- else for (const char of str) width += graphemeWidth(char);
174
- return width;
175
- }
176
-
177
- //#endregion
178
- //#region ../core/src/output/markdown-renderer.ts
179
- /**
180
- * Lightweight Markdown-to-terminal renderer.
181
- *
182
- * Supports a subset of Markdown tailored for CLI help notes:
183
- * - Inline: bold, italic, inline code, links
184
- * - Block: paragraphs, unordered/ordered lists, blockquotes, headings,
185
- * horizontal rules, fenced code blocks
186
- */
187
- /**
188
- * Apply inline Markdown formatting to a string.
189
- *
190
- * Processing order matters to avoid conflicts:
191
- * 1. Inline code (backticks) — content inside is literal, no further processing
192
- * 2. Bold (**text**)
193
- * 3. Italic (*text* or _text_)
194
- * 4. Links [text](url)
195
- */
196
- function renderInline(text) {
197
- const codeSpans = [];
198
- let result = text.replace(/`([^`]+)`/g, (_match, code) => {
199
- const index = codeSpans.length;
200
- codeSpans.push(styles.cyan(code));
201
- return `\x00CODE${index}\x00`;
202
- });
203
- result = result.replace(/\*\*(.+?)\*\*/g, (_match, content) => styles.bold(content));
204
- result = result.replace(/__(.+?)__/g, (_match, content) => styles.bold(content));
205
- result = result.replace(/\*(.+?)\*/g, (_match, content) => styles.italic(content));
206
- result = result.replace(/(?<!\w)_(.+?)_(?!\w)/g, (_match, content) => styles.italic(content));
207
- result = result.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_match, linkText, url) => `${styles.underline(linkText)} ${styles.dim(`(${url})`)}`);
208
- result = result.replace(/\x00CODE(\d+)\x00/g, (_match, index) => codeSpans[Number(index)]);
209
- return result;
210
- }
211
- /**
212
- * Render a Markdown string to styled terminal output.
213
- *
214
- * Block-level processing:
215
- * - Splits input into blocks separated by blank lines
216
- * - Detects headings, horizontal rules, blockquotes, lists, code blocks, and paragraphs
217
- * - Applies inline formatting within each block
218
- */
219
- function renderMarkdown(markdown) {
220
- return splitIntoBlocks(markdown.split("\n")).map(renderBlock).join("\n\n");
221
- }
222
- const HEADING_RE = /^(#{1,6})\s+(.+)$/;
223
- const HR_RE = /^(?:---+|\*\*\*+|___+)\s*$/;
224
- const BLOCKQUOTE_RE = /^>\s?(.*)$/;
225
- const UL_RE = /^-\s+(.+)$/;
226
- const OL_RE = /^(\d+)[.)]\s+(.+)$/;
227
- const FENCE_OPEN_RE = /^(`{3,}|~{3,})(\S*)\s*$/;
228
- const ALERT_RE = /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$/;
229
- const TABLE_ROW_RE = /^\|(.+)\|$/;
230
- const TABLE_SEP_RE = /^\|(\s*:?-+:?\s*\|)+$/;
231
- /**
232
- * Split lines into logical blocks separated by blank lines.
233
- * Consecutive lines of the same block type are grouped together.
234
- */
235
- function splitIntoBlocks(lines) {
236
- const blocks = [];
237
- let i = 0;
238
- while (i < lines.length) {
239
- const line = lines[i];
240
- if (line.trim() === "") {
241
- i++;
242
- continue;
243
- }
244
- const fenceMatch = line.match(FENCE_OPEN_RE);
245
- if (fenceMatch) {
246
- const fence = fenceMatch[1];
247
- const lang = fenceMatch[2] ?? "";
248
- const codeLines = [];
249
- i++;
250
- while (i < lines.length) {
251
- if (lines[i].startsWith(fence.charAt(0).repeat(fence.length)) && lines[i].trim() === fence.charAt(0).repeat(Math.max(fence.length, lines[i].trim().length))) {
252
- i++;
253
- break;
254
- }
255
- codeLines.push(lines[i]);
256
- i++;
257
- }
258
- blocks.push({
259
- type: "code",
260
- lang,
261
- lines: codeLines
262
- });
263
- continue;
264
- }
265
- const headingMatch = line.match(HEADING_RE);
266
- if (headingMatch) {
267
- blocks.push({
268
- type: "heading",
269
- level: headingMatch[1].length,
270
- content: headingMatch[2]
271
- });
272
- i++;
273
- continue;
274
- }
275
- if (HR_RE.test(line)) {
276
- blocks.push({ type: "hr" });
277
- i++;
278
- continue;
279
- }
280
- if (BLOCKQUOTE_RE.test(line)) {
281
- const bqLines = [];
282
- while (i < lines.length) {
283
- const bqMatch = lines[i].match(BLOCKQUOTE_RE);
284
- if (bqMatch) {
285
- bqLines.push(bqMatch[1]);
286
- i++;
287
- } else break;
288
- }
289
- if (bqLines.length > 0) {
290
- const alertMatch = bqLines[0].match(ALERT_RE);
291
- if (alertMatch) {
292
- const contentLines = bqLines.slice(1).filter((l) => l !== "");
293
- blocks.push({
294
- type: "alert",
295
- alertType: alertMatch[1],
296
- lines: contentLines
297
- });
298
- continue;
299
- }
300
- }
301
- blocks.push({
302
- type: "blockquote",
303
- lines: bqLines
304
- });
305
- continue;
306
- }
307
- if (UL_RE.test(line)) {
308
- const items = [];
309
- while (i < lines.length) {
310
- const ulMatch = lines[i].match(UL_RE);
311
- if (ulMatch) {
312
- items.push(ulMatch[1]);
313
- i++;
314
- } else break;
315
- }
316
- blocks.push({
317
- type: "ul",
318
- items
319
- });
320
- continue;
321
- }
322
- const olMatch = line.match(OL_RE);
323
- if (olMatch) {
324
- const start = Number(olMatch[1]);
325
- const items = [];
326
- while (i < lines.length) {
327
- const match = lines[i].match(OL_RE);
328
- if (match) {
329
- items.push(match[2]);
330
- i++;
331
- } else break;
332
- }
333
- blocks.push({
334
- type: "ol",
335
- items,
336
- start
337
- });
338
- continue;
339
- }
340
- if (TABLE_ROW_RE.test(line) && i + 1 < lines.length && TABLE_SEP_RE.test(lines[i + 1])) {
341
- const headers = parseCells(line);
342
- const alignments = parseAlignments(lines[i + 1]);
343
- i += 2;
344
- const rows = [];
345
- while (i < lines.length && TABLE_ROW_RE.test(lines[i])) {
346
- rows.push(parseCells(lines[i]));
347
- i++;
348
- }
349
- blocks.push({
350
- type: "table",
351
- headers,
352
- alignments,
353
- rows
354
- });
355
- continue;
356
- }
357
- const paraLines = [];
358
- while (i < lines.length) {
359
- const l = lines[i];
360
- if (l.trim() === "" || HEADING_RE.test(l) || HR_RE.test(l) || BLOCKQUOTE_RE.test(l) || UL_RE.test(l) || OL_RE.test(l) || FENCE_OPEN_RE.test(l) || TABLE_ROW_RE.test(l) && i + 1 < lines.length && TABLE_SEP_RE.test(lines[i + 1])) break;
361
- paraLines.push(l);
362
- i++;
363
- }
364
- if (paraLines.length > 0) blocks.push({
365
- type: "paragraph",
366
- lines: paraLines
367
- });
368
- }
369
- return blocks;
370
- }
371
- /**
372
- * Parse cells from a table row: `| a | b | c |` → `["a", "b", "c"]`
373
- */
374
- function parseCells(row) {
375
- return row.slice(1, -1).split("|").map((cell) => cell.trim());
376
- }
377
- /**
378
- * Parse alignment from separator row: `|:---|:---:|---:|` → `["left", "center", "right"]`
379
- */
380
- function parseAlignments(sepRow) {
381
- return sepRow.slice(1, -1).split("|").map((cell) => {
382
- const trimmed = cell.trim();
383
- if (trimmed.startsWith(":") && trimmed.endsWith(":")) return "center";
384
- if (trimmed.endsWith(":")) return "right";
385
- return "left";
386
- });
387
- }
388
- /**
389
- * Pad a string to a given width with the specified alignment.
390
- */
391
- function alignText(text, width, alignment) {
392
- const visualWidth = stringWidth(text);
393
- const total = Math.max(0, width - visualWidth);
394
- if (alignment === "right") return " ".repeat(total) + text;
395
- if (alignment === "center") {
396
- const left = Math.floor(total / 2);
397
- return " ".repeat(left) + text + " ".repeat(total - left);
398
- }
399
- return text + " ".repeat(total);
400
- }
401
- /**
402
- * Style configuration for GitHub-style alert blocks.
403
- */
404
- const alertStyles = {
405
- NOTE: {
406
- icon: "ℹ",
407
- label: "Note",
408
- styleFn: styles.cyan
409
- },
410
- TIP: {
411
- icon: "💡",
412
- label: "Tip",
413
- styleFn: styles.green
414
- },
415
- IMPORTANT: {
416
- icon: "❗",
417
- label: "Important",
418
- styleFn: styles.magenta
419
- },
420
- WARNING: {
421
- icon: "⚠",
422
- label: "Warning",
423
- styleFn: styles.yellow
424
- },
425
- CAUTION: {
426
- icon: "🔴",
427
- label: "Caution",
428
- styleFn: styles.red
429
- }
430
- };
431
- /**
432
- * Render a single block to styled terminal output.
433
- */
434
- function renderBlock(block) {
435
- switch (block.type) {
436
- case "heading": return styles.green(styles.bold(renderInline(block.content)));
437
- case "hr": return styles.dim("─".repeat(40));
438
- case "blockquote": {
439
- const prefix = styles.dim("│ ");
440
- return block.lines.map((line) => `${prefix}${renderInline(line)}`).join("\n");
441
- }
442
- case "alert": {
443
- const { icon, label, styleFn } = alertStyles[block.alertType];
444
- const prefix = styleFn(styles.bold("│")) + " ";
445
- const header = `${prefix}${styleFn(icon)} ${styleFn(label)}`;
446
- if (block.lines.length === 0) return header;
447
- return `${header}\n${block.lines.map((line) => `${prefix}${renderInline(line)}`).join("\n")}`;
448
- }
449
- case "ul": return block.items.map((item) => `${styles.dim("•")} ${renderInline(item)}`).join("\n");
450
- case "ol": {
451
- const maxNum = block.start + block.items.length - 1;
452
- const width = String(maxNum).length;
453
- return block.items.map((item, i) => {
454
- const num = String(block.start + i).padStart(width, " ");
455
- return `${styles.dim(`${num}.`)} ${renderInline(item)}`;
456
- }).join("\n");
457
- }
458
- case "table": {
459
- const colCount = block.headers.length;
460
- const renderedHeaders = block.headers.map((h) => renderInline(h));
461
- const renderedRows = block.rows.map((row) => Array.from({ length: colCount }, (_, i) => renderInline(row[i] ?? "")));
462
- const colWidths = renderedHeaders.map((h, i) => {
463
- const headerWidth = stringWidth(h);
464
- const cellWidths = renderedRows.map((row) => stringWidth(row[i]));
465
- return Math.max(headerWidth, ...cellWidths);
466
- });
467
- const pipe = styles.dim("│");
468
- const topBorder = styles.dim(`┌─${colWidths.map((w) => "─".repeat(w)).join("─┬─")}─┐`);
469
- const midBorder = styles.dim(`├─${colWidths.map((w) => "─".repeat(w)).join("─┼─")}─┤`);
470
- const botBorder = styles.dim(`└─${colWidths.map((w) => "─".repeat(w)).join("─┴─")}─┘`);
471
- return [
472
- topBorder,
473
- `${pipe} ${renderedHeaders.map((h, i) => styles.bold(alignText(h, colWidths[i], block.alignments[i] ?? "left"))).join(` ${pipe} `)} ${pipe}`,
474
- midBorder,
475
- ...renderedRows.map((row) => {
476
- const cells = row.map((cell, i) => alignText(cell, colWidths[i], block.alignments[i] ?? "left"));
477
- return `${pipe} ${cells.join(` ${pipe} `)} ${pipe}`;
478
- }),
479
- botBorder
480
- ].join("\n");
481
- }
482
- case "code": return block.lines.map((line) => ` ${styles.yellow(line)}`).join("\n");
483
- case "paragraph": return renderInline(block.lines.join(" "));
484
- }
485
- }
486
-
487
- //#endregion
488
- //#region ../core/src/output/help-generator.ts
489
- /**
490
- * Default descriptions for built-in options
491
- */
492
- const defaultBuiltinDescriptions = {
493
- help: "Show help",
494
- helpAll: "Show help with all subcommand options",
495
- version: "Show version"
496
- };
497
- /**
498
- * Internal subcommands are reserved for framework internals and hidden from help output.
499
- */
500
- function isVisibleSubcommand(name) {
501
- return !name.startsWith("__");
502
- }
503
- function getVisibleSubcommandEntries(subCommands) {
504
- return Object.entries(subCommands).filter(([name]) => isVisibleSubcommand(name));
505
- }
506
- /**
507
- * Build full command name from context
508
- */
509
- function buildFullCommandName(command, context) {
510
- if (context?.rootName && context.commandPath && context.commandPath.length > 0) return context.commandPath.join(" ");
511
- return command.name ?? "command";
512
- }
513
- /**
514
- * Build usage command name (includes root name for subcommands)
515
- */
516
- function buildUsageCommandName(command, context) {
517
- if (context?.rootName && context.commandPath && context.commandPath.length > 0) return `${context.rootName} ${context.commandPath.join(" ")}`;
518
- return command.name ?? "command";
519
- }
520
- /**
521
- * Render the usage line for a command
522
- */
523
- function renderUsageLine(command, context) {
524
- const parts = [];
525
- const name = buildUsageCommandName(command, context);
526
- parts.push(styles.commandName(name));
527
- if (context?.globalExtracted?.fields.length) parts.push(styles.placeholder("[global options]"));
528
- const extracted = getExtractedFields(command);
529
- if (extracted) {
530
- const positionals = extracted.fields.filter((a) => a.positional);
531
- if (extracted.fields.filter((a) => !a.positional).length > 0) parts.push(styles.placeholder("[options]"));
532
- if (command.subCommands && getVisibleSubcommandEntries(command.subCommands).length > 0) if (command.run) parts.push(styles.placeholder("[command]"));
533
- else parts.push(styles.option("<command>"));
534
- for (const arg of positionals) if (arg.required) parts.push(styles.option(`<${arg.name}>`));
535
- else parts.push(styles.placeholder(`[${arg.name}]`));
536
- } else if (command.subCommands && getVisibleSubcommandEntries(command.subCommands).length > 0) if (command.run) parts.push(styles.placeholder("[command]"));
537
- else parts.push(styles.option("<command>"));
538
- return parts.join(" ");
539
- }
540
- /**
541
- * Render the options section
542
- */
543
- function renderOptions(command, descriptions = {}, context) {
544
- const lines = [];
545
- const desc = {
546
- help: descriptions.help ?? defaultBuiltinDescriptions.help,
547
- helpAll: descriptions.helpAll ?? defaultBuiltinDescriptions.helpAll,
548
- version: descriptions.version ?? defaultBuiltinDescriptions.version
549
- };
550
- const extracted = getExtractedFields(command);
551
- const hasUserDefinedh = extracted?.fields.some((f) => f.overrideBuiltinAlias === true && getAllAliases(f).includes("h")) ?? false;
552
- const hasUserDefinedH = extracted?.fields.some((f) => f.overrideBuiltinAlias === true && getAllAliases(f).includes("H")) ?? false;
553
- if (hasUserDefinedh) lines.push(formatOption(styles.option("--help"), desc.help));
554
- else lines.push(formatOption(`${styles.option("-h")}, ${styles.option("--help")}`, desc.help));
555
- if (hasUserDefinedH) lines.push(formatOption(styles.option("--help-all"), desc.helpAll));
556
- else lines.push(formatOption(`${styles.option("-H")}, ${styles.option("--help-all")}`, desc.helpAll));
557
- if (context?.rootVersion) lines.push(formatOption(styles.option("--version"), desc.version));
558
- if (!extracted) return lines.join("\n");
559
- if (extracted.schemaType === "discriminatedUnion" && extracted.discriminator) return renderDiscriminatedUnionOptions(extracted, command, lines);
560
- if (extracted.schemaType === "union" && extracted.unionOptions) return renderUnionOptions(extracted, command, lines);
561
- if (extracted.schemaType === "xor" && extracted.unionOptions) return renderUnionOptions(extracted, command, lines);
562
- const options = extracted.fields.filter((a) => !a.positional);
563
- for (const opt of options) {
564
- const flags = formatFlags(opt);
565
- let desc = opt.description ?? "";
566
- if (opt.defaultValue !== void 0) desc += ` ${styles.defaultValue(`(default: ${JSON.stringify(opt.defaultValue)})`)}`;
567
- if (opt.required) desc += ` ${styles.required("(required)")}`;
568
- const envInfo = formatEnvInfo(opt.env);
569
- if (envInfo) desc += ` ${envInfo}`;
570
- lines.push(formatOption(flags, desc));
571
- const negationLine = formatNegationLine(opt);
572
- if (negationLine) lines.push(negationLine);
573
- }
574
- return lines.join("\n");
575
- }
576
- /**
577
- * Render a separate line for the custom negation option when a
578
- * `negationDescription` is provided. When no description is given, the
579
- * negation is shown inline by `formatFlags`.
580
- */
581
- function formatNegationLine(opt, indent = 0, extraDescPadding = 0) {
582
- if (!opt.negationDisplay || !opt.negationDescription) return null;
583
- return formatOption(styles.option(`--${opt.negationDisplay}`), `${opt.negationDescription} ${styles.dim(`(↔ --${opt.cliName})`)}`, indent, extraDescPadding);
584
- }
585
- /**
586
- * Render options for discriminated union with variants
587
- */
588
- function renderDiscriminatedUnionOptions(extracted, _command, lines) {
589
- const discriminator = extracted.discriminator;
590
- const variants = extracted.variants ?? [];
591
- const discriminatorField = extracted.fields.find((f) => f.name === discriminator);
592
- if (discriminatorField) {
593
- const variantValues = variants.map((v) => v.discriminatorValue).join("|");
594
- const flags = `${styles.option(`--${discriminator}`)} ${styles.placeholder(`<${variantValues}>`)}`;
595
- const description = extracted.description ?? discriminatorField.description ?? "Action to perform";
596
- lines.push(formatOption(flags, description));
597
- }
598
- const commonFields = /* @__PURE__ */ new Set();
599
- const allFieldNames = /* @__PURE__ */ new Set();
600
- for (const variant of variants) for (const field of variant.fields) allFieldNames.add(field.name);
601
- for (const fieldName of allFieldNames) {
602
- if (fieldName === discriminator) continue;
603
- if (variants.every((v) => v.fields.some((f) => f.name === fieldName))) commonFields.add(fieldName);
604
- }
605
- for (const fieldName of commonFields) {
606
- const field = extracted.fields.find((f) => f.name === fieldName);
607
- if (field && !field.positional) {
608
- const flags = formatFlags(field);
609
- let desc = field.description ?? "";
610
- if (field.defaultValue !== void 0) desc += ` ${styles.defaultValue(`(default: ${JSON.stringify(field.defaultValue)})`)}`;
611
- const envInfo = formatEnvInfo(field.env);
612
- if (envInfo) desc += ` ${envInfo}`;
613
- lines.push(formatOption(flags, desc));
614
- const negationLine = formatNegationLine(field);
615
- if (negationLine) lines.push(negationLine);
616
- }
617
- }
618
- for (const variant of variants) {
619
- const variantFields = variant.fields.filter((f) => f.name !== discriminator && !commonFields.has(f.name) && !f.positional);
620
- if (variantFields.length > 0) {
621
- lines.push("");
622
- const variantLabel = variant.description ? `${styles.dim("When")} ${styles.option(discriminator)}=${styles.bold(variant.discriminatorValue)}: ${variant.description}` : `${styles.dim("When")} ${styles.option(discriminator)}=${styles.bold(variant.discriminatorValue)}:`;
623
- lines.push(variantLabel);
624
- for (const field of variantFields) {
625
- const flags = formatFlags(field);
626
- let desc = field.description ?? "";
627
- if (field.defaultValue !== void 0) desc += ` ${styles.defaultValue(`(default: ${JSON.stringify(field.defaultValue)})`)}`;
628
- if (field.required) desc += ` ${styles.required("(required)")}`;
629
- const envInfo = formatEnvInfo(field.env);
630
- if (envInfo) desc += ` ${envInfo}`;
631
- lines.push(formatOption(flags, desc, 1));
632
- const negationLine = formatNegationLine(field, 1);
633
- if (negationLine) lines.push(negationLine);
634
- }
635
- }
636
- }
637
- return lines.join("\n");
638
- }
639
- /**
640
- * Render options for union with multiple options
641
- */
642
- function renderUnionOptions(extracted, _command, lines) {
643
- const unionOptions = extracted.unionOptions ?? [];
644
- const commonFields = /* @__PURE__ */ new Set();
645
- const allFieldNames = /* @__PURE__ */ new Set();
646
- for (const option of unionOptions) for (const field of option.fields) allFieldNames.add(field.name);
647
- for (const fieldName of allFieldNames) if (unionOptions.every((o) => o.fields.some((f) => f.name === fieldName))) commonFields.add(fieldName);
648
- for (const fieldName of commonFields) {
649
- const field = extracted.fields.find((f) => f.name === fieldName);
650
- if (field && !field.positional) {
651
- const flags = formatFlags(field);
652
- let desc = field.description ?? "";
653
- if (field.defaultValue !== void 0) desc += ` ${styles.defaultValue(`(default: ${JSON.stringify(field.defaultValue)})`)}`;
654
- const envInfo = formatEnvInfo(field.env);
655
- if (envInfo) desc += ` ${envInfo}`;
656
- lines.push(formatOption(flags, desc));
657
- const negationLine = formatNegationLine(field);
658
- if (negationLine) lines.push(negationLine);
659
- }
660
- }
661
- for (let i = 0; i < unionOptions.length; i++) {
662
- const option = unionOptions[i];
663
- if (!option) continue;
664
- const uniqueFields = option.fields.filter((f) => !commonFields.has(f.name) && !f.positional);
665
- const label = option.description ?? `Variant ${i + 1}`;
666
- if (uniqueFields.length > 0) {
667
- lines.push("");
668
- lines.push(` ${styles.bold(`${label}:`)}`);
669
- for (const field of uniqueFields) {
670
- const flags = formatFlags(field);
671
- let desc = field.description ?? "";
672
- if (field.defaultValue !== void 0) desc += ` ${styles.defaultValue(`(default: ${JSON.stringify(field.defaultValue)})`)}`;
673
- if (field.required) desc += ` ${styles.required("(required)")}`;
674
- const envInfo = formatEnvInfo(field.env);
675
- if (envInfo) desc += ` ${envInfo}`;
676
- lines.push(formatOption(flags, desc, 1));
677
- const negationLine = formatNegationLine(field, 1);
678
- if (negationLine) lines.push(negationLine);
679
- }
680
- } else {
681
- lines.push("");
682
- lines.push(` ${styles.bold(`${label}:`)}`);
683
- lines.push(` ${styles.dim(styles.italic("no options"))}`);
684
- }
685
- }
686
- return lines.join("\n");
687
- }
688
- /**
689
- * Format option flags (-v, --verbose <VALUE>)
690
- * Uses cliName (kebab-case) for display
691
- */
692
- function formatFlags(opt) {
693
- const aliasParts = [];
694
- if (opt.alias) {
695
- for (const alias of opt.alias) if (alias.length === 1) aliasParts.push(styles.option(`-${alias}`));
696
- }
697
- let longFlag = styles.option(`--${opt.cliName}`);
698
- if (opt.type !== "boolean") {
699
- const placeholder = opt.placeholder ?? opt.cliName.toUpperCase();
700
- longFlag += ` ${styles.placeholder(`<${placeholder}>`)}`;
701
- }
702
- aliasParts.push(longFlag);
703
- if (opt.alias) {
704
- for (const alias of opt.alias) if (alias.length > 1) {
705
- let longAlias = styles.option(`--${alias}`);
706
- if (opt.type !== "boolean") {
707
- const placeholder = opt.placeholder ?? opt.cliName.toUpperCase();
708
- longAlias += ` ${styles.placeholder(`<${placeholder}>`)}`;
709
- }
710
- aliasParts.push(longAlias);
711
- }
712
- }
713
- const aliasStr = aliasParts.join(", ");
714
- if (opt.type === "boolean" && opt.negationDisplay && !opt.negationDescription) return `${aliasStr} / ${styles.option(`--${opt.negationDisplay}`)}`;
715
- return aliasStr;
716
- }
717
- /**
718
- * Format environment variable info for help display
719
- */
720
- function formatEnvInfo(env) {
721
- if (!env) return "";
722
- const envNames = Array.isArray(env) ? env : [env];
723
- return styles.dim(`[env: ${envNames.join(", ")}]`);
724
- }
725
- /**
726
- * Strip ANSI escape codes from a string to get visual length
727
- */
728
- function stripAnsi(str) {
729
- return str.replace(/\x1B\[[0-9;]*m/g, "");
730
- }
731
- /**
732
- * Pad a string that may contain ANSI codes to a visual width
733
- */
734
- function padEndVisual(str, width) {
735
- const visualLength = stripAnsi(str).length;
736
- const padding = Math.max(0, width - visualLength);
737
- return str + " ".repeat(padding);
738
- }
739
- /**
740
- * Re-indent the continuation lines of a multi-line description so they align
741
- * under the description column. A `\n` in a description is treated as a hard
742
- * line break; every line after the first is padded to `column` spaces.
743
- */
744
- function indentDescription(description, column) {
745
- if (!description.includes("\n")) return description;
746
- const pad = " ".repeat(column);
747
- return description.split("\n").join(`\n${pad}`);
748
- }
749
- /**
750
- * Format a single option line
751
- * If flags exceed the column width, description is moved to the next line
752
- *
753
- * Descriptions may contain `\n` line breaks; continuation lines are indented to
754
- * stay aligned under the description column.
755
- */
756
- function formatOption(flags, description, indent = 0, extraDescPadding = 0) {
757
- const flagWidth = 32;
758
- const indentStr = " ".repeat(indent);
759
- const visualFlagLength = stripAnsi(flags).length;
760
- const effectiveFlagWidth = flagWidth - indent * 2 + extraDescPadding;
761
- const descColumn = effectiveFlagWidth + 2 + indent * 2;
762
- const desc = indentDescription(description, descColumn);
763
- if (visualFlagLength >= effectiveFlagWidth) return `${indentStr} ${flags}\n${" ".repeat(descColumn)}${desc}`;
764
- return `${indentStr} ${padEndVisual(flags, effectiveFlagWidth)}${desc}`;
765
- }
766
- /**
767
- * Format a single option field as a help line
768
- */
769
- function formatFieldLine(opt, indent = 0, extraDescPadding = 0) {
770
- const flags = formatFlags(opt);
771
- let desc = opt.description ?? "";
772
- if (opt.defaultValue !== void 0) desc += ` ${styles.defaultValue(`(default: ${JSON.stringify(opt.defaultValue)})`)}`;
773
- if (opt.required) desc += ` ${styles.required("(required)")}`;
774
- const envInfo = formatEnvInfo(opt.env);
775
- if (envInfo) desc += ` ${envInfo}`;
776
- return formatOption(flags, desc, indent, extraDescPadding);
777
- }
778
- /**
779
- * Render global options section
780
- */
781
- function renderGlobalOptions(globalExtracted) {
782
- const lines = [];
783
- for (const opt of globalExtracted.fields) {
784
- if (opt.positional) continue;
785
- lines.push(formatFieldLine(opt));
786
- const negationLine = formatNegationLine(opt);
787
- if (negationLine) lines.push(negationLine);
788
- }
789
- return lines.join("\n");
790
- }
791
- /**
792
- * Render options for a subcommand (used by showSubcommandOptions)
793
- */
794
- function renderSubcommandOptionsCompact(command, indent) {
795
- const lines = [];
796
- const extracted = getExtractedFields(command);
797
- if (extracted) {
798
- const options = extracted.fields.filter((a) => !a.positional);
799
- for (const opt of options) {
800
- const flags = formatFlags(opt);
801
- let desc = opt.description ?? "";
802
- if (opt.defaultValue !== void 0) desc += ` ${styles.defaultValue(`(default: ${JSON.stringify(opt.defaultValue)})`)}`;
803
- const envInfo = formatEnvInfo(opt.env);
804
- if (envInfo) desc += ` ${envInfo}`;
805
- lines.push(formatOption(flags, desc, indent, 2));
806
- const negationLine = formatNegationLine(opt, indent, 2);
807
- if (negationLine) lines.push(negationLine);
808
- }
809
- }
810
- return lines;
811
- }
812
- /**
813
- * Render subcommands recursively with their options (flat style)
814
- */
815
- function renderSubcommandsWithOptions(subCommands, parentPath, baseIndent) {
816
- const lines = [];
817
- for (const [name, subCmd] of getVisibleSubcommandEntries(subCommands)) {
818
- const cmd = resolveSubCommandMeta(subCmd);
819
- const fullPath = parentPath ? `${parentPath} ${name}` : name;
820
- const desc = cmd?.description ?? "";
821
- const aliases = cmd?.aliases;
822
- const displayName = aliases && aliases.length > 0 ? `${fullPath}, ${aliases.join(", ")}` : fullPath;
823
- lines.push(formatOption(styles.command(displayName), desc, baseIndent));
824
- if (cmd) {
825
- const optionLines = renderSubcommandOptionsCompact(cmd, baseIndent + 1);
826
- lines.push(...optionLines);
827
- const visibleNestedSubCommands = cmd.subCommands ? Object.fromEntries(getVisibleSubcommandEntries(cmd.subCommands)) : void 0;
828
- if (visibleNestedSubCommands && Object.keys(visibleNestedSubCommands).length > 0) {
829
- const nestedLines = renderSubcommandsWithOptions(visibleNestedSubCommands, fullPath, baseIndent);
830
- lines.push(...nestedLines);
831
- }
832
- }
833
- }
834
- return lines;
835
- }
836
- /**
837
- * Generate help text for a command
838
- *
839
- * @param command - The command to generate help for
840
- * @param options - Help generation options
841
- * @returns Formatted help text
842
- */
843
- function generateHelp(command, options) {
844
- const sections = [];
845
- const context = options.context;
846
- const displayName = buildFullCommandName(command, context);
847
- if (displayName) {
848
- let header = styles.commandName(displayName);
849
- if (context?.rootName && context.commandPath && context.commandPath.length > 0) if (context.rootVersion) header += ` ${styles.version(`(${context.rootName} v${context.rootVersion})`)}`;
850
- else header += ` ${styles.version(`(${context.rootName})`)}`;
851
- else if (context?.rootVersion) header += ` ${styles.version(`v${context.rootVersion}`)}`;
852
- sections.push(header);
853
- }
854
- if (context?.aliasFor) sections.push(styles.dim(`Alias for ${styles.commandName(context.aliasFor)}`));
855
- if (command.description) sections.push(command.description);
856
- if (!context?.aliasFor && command.aliases && command.aliases.length > 0) sections.push(`${styles.sectionHeader("Aliases:")} ${command.aliases.map((a) => styles.command(a)).join(", ")}`);
857
- sections.push(`${styles.sectionHeader("Usage:")} ${renderUsageLine(command, context)}`);
858
- const optionsText = renderOptions(command, options.descriptions, context);
859
- if (optionsText) sections.push(`${styles.sectionHeader("Options:")}\n${optionsText}`);
860
- if (context?.globalExtracted?.fields.length) sections.push(`${styles.sectionHeader("Global Options:")}\n${renderGlobalOptions(context.globalExtracted)}`);
861
- if (options.showSubcommands !== false && command.subCommands && getVisibleSubcommandEntries(command.subCommands).length > 0) {
862
- const currentPath = context?.commandPath?.join(" ") ?? "";
863
- const visibleSubCommands = Object.fromEntries(getVisibleSubcommandEntries(command.subCommands));
864
- if (options.showSubcommandOptions) {
865
- const subLines = renderSubcommandsWithOptions(visibleSubCommands, currentPath, 0);
866
- sections.push(`${styles.sectionHeader("Commands:")}\n${subLines.join("\n")}`);
867
- } else {
868
- const subLines = [];
869
- for (const [name, subCmd] of Object.entries(visibleSubCommands)) {
870
- const cmd = resolveSubCommandMeta(subCmd);
871
- const desc = cmd?.description ?? "";
872
- const fullName = currentPath ? `${currentPath} ${name}` : name;
873
- const aliases = cmd?.aliases;
874
- const displayName = aliases && aliases.length > 0 ? `${fullName}, ${aliases.join(", ")}` : fullName;
875
- subLines.push(formatOption(styles.command(displayName), desc));
876
- }
877
- sections.push(`${styles.sectionHeader("Commands:")}\n${subLines.join("\n")}`);
878
- }
879
- }
880
- if (command.examples && command.examples.length > 0) {
881
- const exampleLines = renderExamplesForHelp(command.examples, context);
882
- sections.push(`${styles.sectionHeader("Examples:")}\n${exampleLines}`);
883
- }
884
- if (command.notes) {
885
- const indented = renderMarkdown(command.notes).split("\n").map((line) => line === "" ? "" : ` ${line}`).join("\n");
886
- sections.push(`${styles.sectionHeader("Notes:")}\n${indented}`);
887
- }
888
- return `\n${sections.join("\n\n")}\n`;
889
- }
890
- /**
891
- * Render examples for CLI help output
892
- */
893
- function renderExamplesForHelp(examples, context) {
894
- const lines = [];
895
- const cmdPrefix = context?.rootName ? `${context.rootName} ` : "";
896
- const cmdPath = context?.commandPath?.join(" ") ?? "";
897
- const fullPrefix = cmdPath ? `${cmdPrefix}${cmdPath} ` : cmdPrefix;
898
- for (const example of examples) {
899
- lines.push(` ${styles.dim(example.desc).split("\n").join("\n ")}`);
900
- lines.push(` ${styles.dim("$")} ${fullPrefix}${example.cmd}`);
901
- if (example.output) for (const line of example.output.split("\n")) lines.push(` ${line}`);
902
- lines.push("");
903
- }
904
- if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
905
- return lines.join("\n");
906
- }
907
-
908
- //#endregion
909
- //#region ../core/src/validator/validation-errors.ts
910
- /**
911
- * Error thrown when positional argument configuration is invalid
912
- */
913
- var PositionalConfigError = class extends Error {
914
- constructor(message) {
915
- super(message);
916
- this.name = "PositionalConfigError";
917
- }
918
- };
919
- /**
920
- * Error thrown when a reserved alias is used
921
- */
922
- var ReservedAliasError = class extends Error {
923
- constructor(message) {
924
- super(message);
925
- this.name = "ReservedAliasError";
926
- }
927
- };
928
- /**
929
- * Error thrown when duplicate field names are detected
930
- */
931
- var DuplicateFieldError = class extends Error {
932
- constructor(message) {
933
- super(message);
934
- this.name = "DuplicateFieldError";
935
- }
936
- };
937
- /**
938
- * Error thrown when duplicate aliases are detected
939
- */
940
- var DuplicateAliasError = class extends Error {
941
- constructor(message) {
942
- super(message);
943
- this.name = "DuplicateAliasError";
944
- }
945
- };
946
- /**
947
- * Error thrown when fields are case variants of each other (e.g. "my-option" and "myOption")
948
- */
949
- var CaseVariantCollisionError = class extends Error {
950
- constructor(message) {
951
- super(message);
952
- this.name = "CaseVariantCollisionError";
953
- }
954
- };
955
- /**
956
- * Error thrown when a custom boolean negation name collides with another
957
- * field's name, cliName, alias, or another field's negation (including
958
- * derived camelCase variants).
959
- */
960
- var DuplicateNegationError = class extends Error {
961
- constructor(message) {
962
- super(message);
963
- this.name = "DuplicateNegationError";
964
- }
965
- };
966
- /**
967
- * Error thrown when a field name collides with a reserved, framework-injected
968
- * key on the final args object (e.g. `$source`).
969
- */
970
- var ReservedFieldNameError = class extends Error {
971
- constructor(message) {
972
- super(message);
973
- this.name = "ReservedFieldNameError";
974
- }
975
- };
976
- /**
977
- * Error thrown when a global field and a same-named local field have
978
- * different definitions (per `extractFields()`'s type bucket, whether the
979
- * field is positional, and enum values). Only exactly-matching definitions
980
- * are allowed to share a name across global/local schemas — anything else
981
- * is rejected at validation time rather than risking a value from one
982
- * schema silently flowing into the other.
983
- */
984
- var FieldTypeConflictError = class extends Error {
985
- constructor(message) {
986
- super(message);
987
- this.name = "FieldTypeConflictError";
988
- }
989
- };
990
-
991
- //#endregion
992
- //#region ../core/src/validator/command-validator.ts
993
- /**
994
- * Check for duplicate field names
995
- */
996
- function checkDuplicateFields(extracted, commandPath) {
997
- const errors = [];
998
- const seenNames = /* @__PURE__ */ new Map();
999
- for (const field of extracted.fields) {
1000
- if (seenNames.has(field.name)) errors.push({
1001
- commandPath,
1002
- type: "duplicate_field",
1003
- message: `Duplicate field name "${field.name}" detected.`,
1004
- field: field.name
1005
- });
1006
- seenNames.set(field.name, field.name);
1007
- }
1008
- return errors;
1009
- }
1010
- /**
1011
- * Check for case-variant collisions (e.g. "my-option" and "myOption" defined simultaneously)
1012
- */
1013
- function checkCaseVariantCollisions(extracted, commandPath) {
1014
- const errors = [];
1015
- const canonicalMap = /* @__PURE__ */ new Map();
1016
- for (const field of extracted.fields) {
1017
- const camel = toCamelCase(field.name);
1018
- const existing = canonicalMap.get(camel);
1019
- if (existing && existing !== field.name) errors.push({
1020
- commandPath,
1021
- type: "case_variant_collision",
1022
- message: `Fields "${existing}" and "${field.name}" are case variants of each other and would collide.`,
1023
- field: field.name
1024
- });
1025
- canonicalMap.set(camel, field.name);
1026
- }
1027
- return errors;
1028
- }
1029
- /**
1030
- * Check for duplicate aliases and alias-field name conflicts
1031
- */
1032
- function checkDuplicateAliases(extracted, commandPath) {
1033
- const errors = [];
1034
- const seenAliases = /* @__PURE__ */ new Map();
1035
- const fieldNames = new Set(extracted.fields.map((f) => f.name));
1036
- const cliNames = new Set(extracted.fields.map((f) => f.cliName));
1037
- const registerAlias = (alias, fieldName, isDerived) => {
1038
- if (fieldNames.has(alias) || cliNames.has(alias)) errors.push({
1039
- commandPath,
1040
- type: "duplicate_alias",
1041
- message: `Alias "${alias}" for field "${fieldName}" conflicts with existing field name or CLI name "${alias}".`,
1042
- field: fieldName
1043
- });
1044
- const existingField = seenAliases.get(alias);
1045
- if (existingField && existingField !== fieldName) {
1046
- const qualifier = isDerived ? " (derived camelCase variant)" : "";
1047
- errors.push({
1048
- commandPath,
1049
- type: "duplicate_alias",
1050
- message: `Duplicate alias "${alias}"${qualifier} detected. Both "${existingField}" and "${fieldName}" use the same alias.`,
1051
- field: fieldName
1052
- });
1053
- }
1054
- seenAliases.set(alias, fieldName);
1055
- };
1056
- for (const field of extracted.fields) {
1057
- const allAliases = getAllAliases(field);
1058
- if (allAliases.length === 0) continue;
1059
- for (const alias of allAliases) {
1060
- registerAlias(alias, field.name, false);
1061
- if (alias.length > 1 && alias.includes("-")) {
1062
- const camelVariant = toCamelCase(alias);
1063
- if (camelVariant !== alias && !fieldNames.has(camelVariant)) registerAlias(camelVariant, field.name, true);
1064
- }
1065
- }
1066
- }
1067
- return errors;
1068
- }
1069
- /**
1070
- * Check for collisions involving custom boolean `negation` names
1071
- */
1072
- function checkDuplicateNegations(extracted, commandPath) {
1073
- const errors = [];
1074
- const claimed = /* @__PURE__ */ new Map();
1075
- const claim = (name, fieldName, kind) => {
1076
- if (!claimed.has(name)) claimed.set(name, {
1077
- field: fieldName,
1078
- kind
1079
- });
1080
- };
1081
- for (const field of extracted.fields) {
1082
- claim(field.name, field.name, "field name");
1083
- if (field.name.includes("-")) {
1084
- const camelName = toCamelCase(field.name);
1085
- if (camelName !== field.name) claim(camelName, field.name, "field name");
1086
- }
1087
- if (field.cliName !== field.name) claim(field.cliName, field.name, "CLI name");
1088
- if (field.cliName.includes("-")) {
1089
- const camelCli = toCamelCase(field.cliName);
1090
- if (camelCli !== field.cliName) claim(camelCli, field.name, "CLI name");
1091
- }
1092
- for (const alias of getAllAliases(field)) {
1093
- claim(alias, field.name, "alias");
1094
- if (alias.length > 1 && alias.includes("-")) {
1095
- const camelVariant = toCamelCase(alias);
1096
- if (camelVariant !== alias) claim(camelVariant, field.name, "alias");
1097
- }
1098
- }
1099
- if (field.type === "boolean" && field.negation === true) {
1100
- const defaultKebab = `no-${field.cliName}`;
1101
- claim(defaultKebab, field.name, "default negation");
1102
- const camelBase = toCamelCase(field.cliName);
1103
- const defaultCamel = `no${camelBase[0]?.toUpperCase() ?? ""}${camelBase.slice(1)}`;
1104
- if (defaultCamel !== defaultKebab) claim(defaultCamel, field.name, "default negation");
1105
- }
1106
- }
1107
- const seenNegations = /* @__PURE__ */ new Map();
1108
- const register = (name, fieldName, isDerived) => {
1109
- const claim = claimed.get(name);
1110
- if (claim) {
1111
- const qualifier = isDerived ? " (derived camelCase variant)" : "";
1112
- const conflict = claim.field === fieldName ? `the same field's own ${claim.kind} "${name}"` : `${claim.kind} "${name}" of field "${claim.field}"`;
1113
- errors.push({
1114
- commandPath,
1115
- type: "duplicate_negation",
1116
- message: `Negation "${name}"${qualifier} for field "${fieldName}" conflicts with ${conflict}.`,
1117
- field: fieldName
1118
- });
1119
- }
1120
- const existing = seenNegations.get(name);
1121
- if (existing && existing !== fieldName) {
1122
- const qualifier = isDerived ? " (derived camelCase variant)" : "";
1123
- errors.push({
1124
- commandPath,
1125
- type: "duplicate_negation",
1126
- message: `Duplicate negation "${name}"${qualifier} detected. Both "${existing}" and "${fieldName}" use the same negation name.`,
1127
- field: fieldName
1128
- });
1129
- }
1130
- seenNegations.set(name, fieldName);
1131
- };
1132
- for (const field of extracted.fields) {
1133
- if (typeof field.negation !== "string") continue;
1134
- register(field.negation, field.name, false);
1135
- if (field.negation.includes("-")) {
1136
- const camelVariant = toCamelCase(field.negation);
1137
- if (camelVariant !== field.negation) register(camelVariant, field.name, true);
1138
- }
1139
- }
1140
- return errors;
1141
- }
1142
- /**
1143
- * Check positional argument configuration
1144
- */
1145
- function checkPositionalConfig(extracted, commandPath) {
1146
- const errors = [];
1147
- const positionalFields = extracted.fields.filter((f) => f.positional);
1148
- let foundArrayPositional = null;
1149
- let foundOptionalPositional = null;
1150
- for (const field of positionalFields) {
1151
- if (foundArrayPositional !== null) errors.push({
1152
- commandPath,
1153
- type: "positional_config",
1154
- message: `Positional argument "${field.name}" cannot follow array positional argument "${foundArrayPositional}".`,
1155
- field: field.name
1156
- });
1157
- if (field.type === "array" && foundOptionalPositional !== null) errors.push({
1158
- commandPath,
1159
- type: "positional_config",
1160
- message: `Array positional "${field.name}" cannot be used with optional positional "${foundOptionalPositional}" (ambiguous parsing).`,
1161
- field: field.name
1162
- });
1163
- if (foundOptionalPositional !== null && field.required) errors.push({
1164
- commandPath,
1165
- type: "positional_config",
1166
- message: `Required positional "${field.name}" cannot follow optional positional "${foundOptionalPositional}".`,
1167
- field: field.name
1168
- });
1169
- if (field.type === "array") foundArrayPositional = field.name;
1170
- if (!field.required) foundOptionalPositional = field.name;
1171
- }
1172
- return errors;
1173
- }
1174
- /**
1175
- * Check for reserved aliases used without override flag
1176
- */
1177
- function checkReservedAliases(extracted, commandPath) {
1178
- const errors = [];
1179
- for (const field of extracted.fields) {
1180
- if (field.overrideBuiltinAlias === true) continue;
1181
- for (const alias of getAllAliases(field)) if (alias === "h" || alias === "H") errors.push({
1182
- commandPath,
1183
- type: "reserved_alias",
1184
- message: `Alias "${alias}" is reserved for --${alias === "h" ? "help" : "help-all"}.`,
1185
- field: field.name
1186
- });
1187
- }
1188
- return errors;
1189
- }
1190
- /**
1191
- * Check for field names starting with `$`.
1192
- *
1193
- * The `$` prefix is reserved for framework-injected helpers on the final
1194
- * args object (e.g. `$source`). It is also impractical as a real CLI flag
1195
- * since an unquoted `$name` is expanded by the shell before it ever reaches
1196
- * the program, so this is rejected outright rather than merely discouraged.
1197
- *
1198
- * Aliases can't start with `$` (schema extraction already restricts alias
1199
- * characters to `[A-Za-z0-9-]`), and `cliName` is derived from `name` via
1200
- * `toKebabCase`, which never strips or moves a leading `$` — so checking
1201
- * `field.name` alone covers every way `$` could reach the final args object.
1202
- */
1203
- function checkReservedFieldNames(extracted, commandPath) {
1204
- const errors = [];
1205
- for (const field of extracted.fields) if (field.name.startsWith("$")) errors.push({
1206
- commandPath,
1207
- type: "reserved_field_name",
1208
- message: `Field "${field.name}" starts with "$", which is reserved for framework-injected helpers (e.g. $source).`,
1209
- field: field.name
1210
- });
1211
- return errors;
1212
- }
1213
- /**
1214
- * Validate that no duplicate field names exist
1215
- *
1216
- * @param extracted - Extracted fields from schema
1217
- * @throws {DuplicateFieldError} If duplicate field names are found
1218
- */
1219
- function validateDuplicateFields(extracted) {
1220
- const errors = checkDuplicateFields(extracted, []);
1221
- if (errors.length > 0) {
1222
- const field = errors[0]?.field ?? "unknown";
1223
- throw new DuplicateFieldError(`Duplicate field name "${field}" detected. Each field must have a unique name.`);
1224
- }
1225
- }
1226
- /**
1227
- * Validate that no duplicate aliases exist
1228
- *
1229
- * Also checks for conflicts between aliases and field names
1230
- *
1231
- * @param extracted - Extracted fields from schema
1232
- * @throws {DuplicateAliasError} If duplicate aliases are found or alias conflicts with field name
1233
- */
1234
- function validateDuplicateAliases(extracted) {
1235
- const errors = checkDuplicateAliases(extracted, []);
1236
- if (errors.length > 0) {
1237
- const err = errors[0];
1238
- throw new DuplicateAliasError(err.message);
1239
- }
1240
- }
1241
- /**
1242
- * Validate positional argument configuration
1243
- *
1244
- * Rules:
1245
- * - Array positional arguments must be the last positional
1246
- * - No positional arguments can follow an array positional
1247
- * - Required positional arguments cannot follow optional positional arguments
1248
- * - Array positional and optional positional cannot be used together (ambiguous parsing)
1249
- *
1250
- * @param extracted - Extracted fields from schema
1251
- * @throws {PositionalConfigError} If configuration is invalid
1252
- */
1253
- function validatePositionalConfig(extracted) {
1254
- const errors = checkPositionalConfig(extracted, []);
1255
- if (errors.length > 0) {
1256
- const err = errors[0];
1257
- throw new PositionalConfigError(err.message);
1258
- }
1259
- }
1260
- /**
1261
- * Validate that no reserved aliases are used without explicit override
1262
- *
1263
- * Reserved aliases:
1264
- * - 'h' is reserved for --help
1265
- * - 'H' is reserved for --help-all
1266
- *
1267
- * Users can override these by setting overrideBuiltinAlias: true
1268
- *
1269
- * @param extracted - Extracted fields from schema
1270
- * @param _hasSubCommands - Whether the command has subcommands (reserved for future use)
1271
- * @throws {ReservedAliasError} If a reserved alias is used without override flag
1272
- */
1273
- function validateReservedAliases(extracted, _hasSubCommands) {
1274
- const errors = checkReservedAliases(extracted, []);
1275
- if (errors.length > 0) {
1276
- const field = errors[0].field ?? "unknown";
1277
- const found = extracted.fields.find((f) => f.name === field);
1278
- const alias = (found ? getAllAliases(found) : []).find((a) => a === "h" || a === "H") ?? "h";
1279
- throw new ReservedAliasError(`Alias "${alias}" is reserved for --${alias === "h" ? "help" : "help-all"}. To override this, set { overrideBuiltinAlias: true } for "${field}" and keep the alias where it is currently defined (in alias or hiddenAlias).`);
1280
- }
1281
- }
1282
- /**
1283
- * Validate that no field name starts with `$`
1284
- *
1285
- * The `$` prefix is reserved for framework-injected helpers on the final
1286
- * args object (e.g. `$source`), and is unusable as a real CLI flag anyway
1287
- * since an unquoted `$name` gets shell-expanded before the program sees it.
1288
- *
1289
- * Checking `field.name` alone is sufficient: aliases can't start with `$`
1290
- * (schema extraction already restricts alias characters to `[A-Za-z0-9-]`),
1291
- * and `cliName` is derived from `name` via `toKebabCase`, which never strips
1292
- * or moves a leading `$`. See {@link checkReservedFieldNames}.
1293
- *
1294
- * @param extracted - Extracted fields from schema
1295
- * @throws {ReservedFieldNameError} If a field name starts with "$"
1296
- */
1297
- function validateReservedFieldNames(extracted) {
1298
- const errors = checkReservedFieldNames(extracted, []);
1299
- if (errors.length > 0) {
1300
- const err = errors[0];
1301
- throw new ReservedFieldNameError(err.message);
1302
- }
1303
- }
1304
- /**
1305
- * Validate that custom boolean negation names do not collide with anything
1306
- *
1307
- * @param extracted - Extracted fields from schema
1308
- * @throws {DuplicateNegationError} If a colliding negation is found
1309
- */
1310
- function validateDuplicateNegations(extracted) {
1311
- const errors = checkDuplicateNegations(extracted, []);
1312
- if (errors.length > 0) {
1313
- const err = errors[0];
1314
- throw new DuplicateNegationError(err.message);
1315
- }
1316
- }
1317
- /**
1318
- * Validate that no case-variant collisions exist
1319
- *
1320
- * @param extracted - Extracted fields from schema
1321
- * @throws {CaseVariantCollisionError} If case-variant collisions are found
1322
- */
1323
- function validateCaseVariantCollisions(extracted) {
1324
- const errors = checkCaseVariantCollisions(extracted, []);
1325
- if (errors.length > 0) {
1326
- const err = errors[0];
1327
- throw new CaseVariantCollisionError(err.message);
1328
- }
1329
- }
1330
- /**
1331
- * Check whether two same-named fields from different schemas (e.g. global
1332
- * args and command args) have identical definitions. Only the facts
1333
- * `extractFields()` already exposes are compared: the coarse type bucket,
1334
- * whether the field is positional, and, for enum-like fields, the exact
1335
- * set of allowed values. Anything `extractFields()` can't see (e.g. a
1336
- * `.refine()`) is intentionally not compared — this is a coarse, cheap
1337
- * equality check, not a full schema comparison.
1338
- */
1339
- function fieldsAreIdentical(a, b) {
1340
- if (a.type !== b.type) return false;
1341
- if (a.positional !== b.positional) return false;
1342
- const aEnum = a.enumValues;
1343
- const bEnum = b.enumValues;
1344
- if (!aEnum && !bEnum) return true;
1345
- if (!aEnum || !bEnum) return false;
1346
- const aSet = new Set(aEnum);
1347
- const bSet = new Set(bEnum);
1348
- if (aSet.size !== bSet.size) return false;
1349
- for (const value of aSet) if (!bSet.has(value)) return false;
1350
- return true;
1351
- }
1352
- /**
1353
- * Check for cross-schema collisions between two schemas (e.g., global args
1354
- * and command args): neither a case-variant collision (same canonical name,
1355
- * different spelling) nor a same-named field with a different definition
1356
- * (same spelling, but the two schemas don't agree on what values are valid).
1357
- */
1358
- function checkCrossSchemaCollisions(extractedA, extractedB, commandPath) {
1359
- const errors = [];
1360
- const canonicalMap = /* @__PURE__ */ new Map();
1361
- for (const field of extractedA.fields) canonicalMap.set(toCamelCase(field.name), field);
1362
- for (const field of extractedB.fields) {
1363
- const camel = toCamelCase(field.name);
1364
- const existing = canonicalMap.get(camel);
1365
- if (!existing) continue;
1366
- if (existing.name !== field.name) {
1367
- errors.push({
1368
- commandPath,
1369
- type: "case_variant_collision",
1370
- message: `Global field "${existing.name}" and command field "${field.name}" are case variants of each other and would collide.`,
1371
- field: field.name
1372
- });
1373
- continue;
1374
- }
1375
- if (!fieldsAreIdentical(existing, field)) errors.push({
1376
- commandPath,
1377
- type: "field_type_conflict",
1378
- message: `Global field "${existing.name}" and command field "${field.name}" share the same name but have different definitions.`,
1379
- field: field.name
1380
- });
1381
- }
1382
- return errors;
1383
- }
1384
- /**
1385
- * Validate that no cross-schema collisions exist between two schemas
1386
- * (e.g., global args and command args): neither a case-variant collision
1387
- * (same canonical name, different spelling) nor a same-named field with a
1388
- * different definition (same spelling, but the two schemas don't agree on
1389
- * what values are valid).
1390
- *
1391
- * @param extractedA - Extracted fields from first schema (e.g., global args)
1392
- * @param extractedB - Extracted fields from second schema (e.g., command args)
1393
- * @throws {CaseVariantCollisionError} If cross-schema case-variant collisions are found
1394
- * @throws {FieldTypeConflictError} If a same-named field has a different definition on each schema
1395
- */
1396
- function validateCrossSchemaCollisions(extractedA, extractedB) {
1397
- const err = checkCrossSchemaCollisions(extractedA, extractedB, [])[0];
1398
- if (!err) return;
1399
- if (err.type === "case_variant_collision") throw new CaseVariantCollisionError(err.message);
1400
- throw new FieldTypeConflictError(err.message);
1401
- }
1402
- /**
1403
- * Collect validation errors for a single command's schema (non-throwing)
1404
- */
1405
- function collectSchemaErrors(extracted, _hasSubCommands, commandPath) {
1406
- return [
1407
- ...checkDuplicateFields(extracted, commandPath),
1408
- ...checkCaseVariantCollisions(extracted, commandPath),
1409
- ...checkDuplicateAliases(extracted, commandPath),
1410
- ...checkDuplicateNegations(extracted, commandPath),
1411
- ...checkPositionalConfig(extracted, commandPath),
1412
- ...checkReservedAliases(extracted, commandPath),
1413
- ...checkReservedFieldNames(extracted, commandPath)
1414
- ];
1415
- }
1416
- /**
1417
- * Check for alias conflicts within subcommands
1418
- * - Aliases must not conflict with subcommand names
1419
- * - Aliases must not conflict with other aliases
1420
- */
1421
- function checkSubCommandAliasConflicts(command, commandPath) {
1422
- const errors = [];
1423
- if (!command.subCommands) return errors;
1424
- const nameToOwner = /* @__PURE__ */ new Map();
1425
- for (const [name] of Object.entries(command.subCommands)) nameToOwner.set(name, name);
1426
- for (const [name, subCmdValue] of Object.entries(command.subCommands)) {
1427
- const resolved = isLazyCommand(subCmdValue) ? subCmdValue.meta : typeof subCmdValue !== "function" ? subCmdValue : null;
1428
- if (!resolved?.aliases) continue;
1429
- const subCommandPath = [...commandPath, name];
1430
- for (const alias of resolved.aliases) {
1431
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(alias)) {
1432
- errors.push({
1433
- commandPath: subCommandPath,
1434
- type: "invalid_alias",
1435
- message: `Alias "${alias}" is invalid. Aliases must start with an alphanumeric character and contain only alphanumeric characters, hyphens, or underscores.`,
1436
- field: name
1437
- });
1438
- continue;
1439
- }
1440
- if (alias === name) {
1441
- errors.push({
1442
- commandPath: subCommandPath,
1443
- type: "duplicate_alias",
1444
- message: `Alias "${alias}" conflicts with its own name.`,
1445
- field: name
1446
- });
1447
- continue;
1448
- }
1449
- const existing = nameToOwner.get(alias);
1450
- if (existing) if (existing === name) errors.push({
1451
- commandPath: subCommandPath,
1452
- type: "duplicate_alias",
1453
- message: `Alias "${alias}" is duplicated within the alias list.`,
1454
- field: name
1455
- });
1456
- else errors.push({
1457
- commandPath: subCommandPath,
1458
- type: "duplicate_alias",
1459
- message: `Alias "${alias}" conflicts with existing subcommand or alias "${existing}".`,
1460
- field: name
1461
- });
1462
- else nameToOwner.set(alias, name);
1463
- }
1464
- }
1465
- return errors;
1466
- }
1467
- /**
1468
- * Validate a command and all its subcommands recursively
1469
- *
1470
- * This function collects all validation errors without throwing,
1471
- * making it suitable for test assertions.
1472
- *
1473
- * @param command - The command to validate
1474
- * @param options - Validation options
1475
- * @returns Validation result with all errors collected
1476
- *
1477
- * @example
1478
- * ```ts
1479
- * const result = await validateCommand(myCommand);
1480
- * if (!result.valid) {
1481
- * console.error(result.errors);
1482
- * }
1483
- * ```
1484
- */
1485
- async function validateCommand(command, options = {}) {
1486
- const commandPath = options.commandPath ?? [command.name];
1487
- const errors = [];
1488
- const hasSubCommands = command.subCommands ? Object.keys(command.subCommands).length > 0 : false;
1489
- const globalExtracted = options.globalArgs ? extractFields(options.globalArgs) : void 0;
1490
- if (command.args) {
1491
- const extracted = extractFields(command.args);
1492
- errors.push(...collectSchemaErrors(extracted, hasSubCommands, commandPath));
1493
- if (globalExtracted) errors.push(...checkCrossSchemaCollisions(globalExtracted, extracted, commandPath));
1494
- }
1495
- errors.push(...checkSubCommandAliasConflicts(command, commandPath));
1496
- if (command.subCommands) for (const [name, subCmd] of Object.entries(command.subCommands)) {
1497
- const subResult = await validateCommand(await resolveLazyCommand(subCmd), {
1498
- commandPath: [...commandPath, name],
1499
- ...options.globalArgs ? { globalArgs: options.globalArgs } : {}
1500
- });
1501
- if (!subResult.valid) errors.push(...subResult.errors);
1502
- }
1503
- if (errors.length === 0) return { valid: true };
1504
- return {
1505
- valid: false,
1506
- errors
1507
- };
1508
- }
1509
- /**
1510
- * Format command validation errors for display
1511
- *
1512
- * @param errors - Array of validation errors
1513
- * @returns Formatted error message
1514
- */
1515
- function formatCommandValidationErrors(errors) {
1516
- if (errors.length === 0) return "";
1517
- const lines = ["Command definition errors:"];
1518
- for (const error of errors) {
1519
- const path = error.commandPath.join(" > ");
1520
- lines.push(` - [${path}] ${error.message}`);
1521
- }
1522
- return lines.join("\n");
1523
- }
1524
-
1525
- //#endregion
1526
- //#region ../core/src/parser/long-option-resolver.ts
1527
- /** Return a long option's name without leading dashes or an inline value. */
1528
- function getLongOptionName(arg) {
1529
- const equalsIndex = arg.indexOf("=");
1530
- return equalsIndex >= 0 ? arg.slice(2, equalsIndex) : arg.slice(2);
1531
- }
1532
- function resolveLongOption(arg, lookup) {
1533
- const withoutDashes = getLongOptionName(arg);
1534
- if (!arg.includes("=")) {
1535
- const negatedField = lookup.negationMap.get(withoutDashes);
1536
- if (negatedField && lookup.booleanFlags.has(negatedField)) return {
1537
- resolvedName: negatedField,
1538
- withoutDashes,
1539
- isNegated: true,
1540
- isCustomNegation: true,
1541
- isSuppressedNegation: false
1542
- };
1543
- }
1544
- const hasEquals = arg.includes("=");
1545
- if (!hasEquals && withoutDashes.startsWith("no-")) {
1546
- const flagName = withoutDashes.slice(3);
1547
- if (flagName === flagName.toLowerCase()) {
1548
- const resolvedName = lookup.aliasMap.get(flagName) ?? flagName;
1549
- if (lookup.booleanFlags.has(resolvedName)) {
1550
- const asIsResolved = lookup.aliasMap.get(withoutDashes) ?? withoutDashes;
1551
- if (!lookup.definedNames.has(asIsResolved)) {
1552
- if (lookup.defaultNegationDisabledFields.has(resolvedName)) return {
1553
- resolvedName,
1554
- withoutDashes,
1555
- isNegated: false,
1556
- isCustomNegation: false,
1557
- isSuppressedNegation: true
1558
- };
1559
- return {
1560
- resolvedName,
1561
- withoutDashes,
1562
- isNegated: true,
1563
- isCustomNegation: false,
1564
- isSuppressedNegation: false
1565
- };
1566
- }
1567
- }
1568
- }
1569
- }
1570
- if (!hasEquals && withoutDashes.length > 2 && withoutDashes.startsWith("no") && /[A-Z]/.test(withoutDashes[2])) {
1571
- const camelFlagName = withoutDashes[2].toLowerCase() + withoutDashes.slice(3);
1572
- const resolvedName = lookup.aliasMap.get(camelFlagName) ?? camelFlagName;
1573
- if (lookup.booleanFlags.has(resolvedName)) {
1574
- const asIsResolved = lookup.aliasMap.get(withoutDashes) ?? withoutDashes;
1575
- if (!lookup.definedNames.has(asIsResolved)) {
1576
- if (lookup.defaultNegationDisabledFields.has(resolvedName)) return {
1577
- resolvedName,
1578
- withoutDashes,
1579
- isNegated: false,
1580
- isCustomNegation: false,
1581
- isSuppressedNegation: true
1582
- };
1583
- return {
1584
- resolvedName,
1585
- withoutDashes,
1586
- isNegated: true,
1587
- isCustomNegation: false,
1588
- isSuppressedNegation: false
1589
- };
1590
- }
1591
- }
1592
- }
1593
- return {
1594
- resolvedName: lookup.aliasMap.get(withoutDashes) ?? withoutDashes,
1595
- withoutDashes,
1596
- isNegated: false,
1597
- isCustomNegation: false,
1598
- isSuppressedNegation: false
1599
- };
1600
- }
1601
-
1602
- //#endregion
1603
- //#region ../core/src/parser/argv-parser.ts
1604
- /**
1605
- * Coerce a `--flag=value` string to a boolean for boolean-typed flags.
1606
- * Values other than "true"/"false" are passed through unchanged so
1607
- * downstream validation reports the invalid input instead of silently
1608
- * guessing.
1609
- */
1610
- function coerceBoolean(value) {
1611
- if (value === "true") return true;
1612
- if (value === "false") return false;
1613
- return value;
1614
- }
1615
- /**
1616
- * Matches tokens that look like a negative number (e.g. "-5", "-5.2", "-.5"),
1617
- * as opposed to another flag. Used to decide whether a dash-prefixed token
1618
- * should still be consumed as a value-taking option's value.
1619
- */
1620
- const NEGATIVE_NUMBER_PATTERN = /^-\.?\d/;
1621
- function looksLikeNegativeNumber(value) {
1622
- return NEGATIVE_NUMBER_PATTERN.test(value);
1623
- }
1624
- /**
1625
- * Parse argv into a flat record
1626
- *
1627
- * Supports:
1628
- * - Long options: --flag, --flag=value, --flag value
1629
- * - Short options: -f, -f=value, -f value
1630
- * - Combined short options: -abc (treated as -a -b -c if all are boolean)
1631
- * - Positional arguments
1632
- * - -- to stop parsing options
1633
- * - Boolean negation: --no-flag, --noFlag (requires `booleanFlags` and `negation: true`)
1634
- *
1635
- * **Note:** When using negation detection (`--noFlag` / `--no-flag`),
1636
- * supply `definedNames` so that options whose names happen to start with
1637
- * "no" (e.g. `noDryRun`) are not mistaken for negation of another flag.
1638
- * Without `definedNames`, all `--noX` forms matching a boolean flag will
1639
- * be treated as negation.
1640
- *
1641
- * @param argv - Command line arguments
1642
- * @param options - Parser options
1643
- * @returns Parsed arguments
1644
- */
1645
- function parseArgv(argv, options = {}) {
1646
- const { aliasMap = /* @__PURE__ */ new Map(), booleanFlags = /* @__PURE__ */ new Set(), arrayFlags = /* @__PURE__ */ new Set(), definedNames = /* @__PURE__ */ new Set(), negationMap = /* @__PURE__ */ new Map(), defaultNegationDisabledFields: configuredDefaultNegationDisabledFields } = options;
1647
- const longOptionLookup = {
1648
- aliasMap,
1649
- booleanFlags,
1650
- definedNames,
1651
- negationMap,
1652
- defaultNegationDisabledFields: configuredDefaultNegationDisabledFields ?? new Set(booleanFlags)
1653
- };
1654
- const result = {
1655
- options: {},
1656
- positionals: [],
1657
- rest: []
1658
- };
1659
- let i = 0;
1660
- let stopParsing = false;
1661
- const setOption = (name, value) => {
1662
- const resolvedName = aliasMap.get(name) ?? name;
1663
- if (arrayFlags.has(resolvedName)) {
1664
- const existing = result.options[resolvedName];
1665
- if (Array.isArray(existing)) existing.push(value);
1666
- else if (existing !== void 0) result.options[resolvedName] = [existing, value];
1667
- else result.options[resolvedName] = [value];
1668
- } else result.options[resolvedName] = value;
1669
- };
1670
- while (i < argv.length) {
1671
- const arg = argv[i];
1672
- if (stopParsing) {
1673
- result.rest.push(arg);
1674
- i++;
1675
- continue;
1676
- }
1677
- if (arg === "--") {
1678
- stopParsing = true;
1679
- i++;
1680
- continue;
1681
- }
1682
- if (arg.startsWith("--")) {
1683
- const withoutDashes = arg.slice(2);
1684
- const resolution = resolveLongOption(arg, longOptionLookup);
1685
- if (resolution.isSuppressedNegation) {
1686
- setOption(resolution.withoutDashes, true);
1687
- i++;
1688
- continue;
1689
- }
1690
- if (resolution.isNegated) {
1691
- setOption(resolution.resolvedName, false);
1692
- i++;
1693
- continue;
1694
- }
1695
- const eqIndex = withoutDashes.indexOf("=");
1696
- if (eqIndex !== -1) {
1697
- const name = withoutDashes.slice(0, eqIndex);
1698
- const value = withoutDashes.slice(eqIndex + 1);
1699
- const resolvedName = aliasMap.get(name) ?? name;
1700
- setOption(name, booleanFlags.has(resolvedName) ? coerceBoolean(value) : value);
1701
- i++;
1702
- } else {
1703
- const name = withoutDashes;
1704
- const resolvedName = aliasMap.get(name) ?? name;
1705
- if (booleanFlags.has(resolvedName)) {
1706
- setOption(name, true);
1707
- i++;
1708
- } else {
1709
- const nextArg = argv[i + 1];
1710
- if (nextArg !== void 0 && (!nextArg.startsWith("-") || looksLikeNegativeNumber(nextArg))) {
1711
- setOption(name, nextArg);
1712
- i += 2;
1713
- } else {
1714
- setOption(name, true);
1715
- i++;
1716
- }
1717
- }
1718
- }
1719
- continue;
1720
- }
1721
- if (arg.startsWith("-") && arg.length > 1 && !arg.startsWith("--")) {
1722
- const withoutDash = arg.slice(1);
1723
- const eqIndex = withoutDash.indexOf("=");
1724
- if (eqIndex !== -1) {
1725
- const name = withoutDash.slice(0, eqIndex);
1726
- const value = withoutDash.slice(eqIndex + 1);
1727
- const resolvedName = aliasMap.get(name) ?? name;
1728
- setOption(name, booleanFlags.has(resolvedName) ? coerceBoolean(value) : value);
1729
- i++;
1730
- } else if (withoutDash.length === 1) {
1731
- const name = withoutDash;
1732
- const resolvedName = aliasMap.get(name) ?? name;
1733
- if (booleanFlags.has(resolvedName)) {
1734
- setOption(name, true);
1735
- i++;
1736
- } else {
1737
- const nextArg = argv[i + 1];
1738
- if (nextArg !== void 0 && (!nextArg.startsWith("-") || looksLikeNegativeNumber(nextArg))) {
1739
- setOption(name, nextArg);
1740
- i += 2;
1741
- } else {
1742
- setOption(name, true);
1743
- i++;
1744
- }
1745
- }
1746
- } else {
1747
- for (const char of withoutDash) setOption(char, true);
1748
- i++;
1749
- }
1750
- continue;
1751
- }
1752
- result.positionals.push(arg);
1753
- i++;
1754
- }
1755
- return result;
1756
- }
1757
- /**
1758
- * Build parser options from extracted fields
1759
- */
1760
- function buildParserOptions(extracted) {
1761
- const aliasMap = /* @__PURE__ */ new Map();
1762
- const booleanFlags = /* @__PURE__ */ new Set();
1763
- const arrayFlags = /* @__PURE__ */ new Set();
1764
- const definedNames = /* @__PURE__ */ new Set();
1765
- const negationMap = /* @__PURE__ */ new Map();
1766
- const defaultNegationDisabledFields = /* @__PURE__ */ new Set();
1767
- for (const field of extracted.fields) definedNames.add(field.name);
1768
- for (const field of extracted.fields) {
1769
- if (field.cliName !== field.name) aliasMap.set(field.cliName, field.name);
1770
- for (const alias of getAllAliases(field)) {
1771
- aliasMap.set(alias, field.name);
1772
- if (alias.length > 1 && alias.includes("-")) {
1773
- const camelAlias = toCamelCase(alias);
1774
- if (camelAlias !== alias && !definedNames.has(camelAlias) && !aliasMap.has(camelAlias)) aliasMap.set(camelAlias, field.name);
1775
- }
1776
- }
1777
- const camelVariant = toCamelCase(field.name);
1778
- if (camelVariant !== field.name && !definedNames.has(camelVariant) && !aliasMap.has(camelVariant)) aliasMap.set(camelVariant, field.name);
1779
- if (field.type === "boolean") booleanFlags.add(field.name);
1780
- if (field.type === "array") arrayFlags.add(field.name);
1781
- if (field.type === "boolean" && field.negation !== true) {
1782
- defaultNegationDisabledFields.add(field.name);
1783
- if (typeof field.negation === "string") {
1784
- negationMap.set(field.negation, field.name);
1785
- if (field.negation.includes("-")) {
1786
- const camelNegation = toCamelCase(field.negation);
1787
- if (camelNegation !== field.negation) negationMap.set(camelNegation, field.name);
1788
- }
1789
- }
1790
- }
1791
- }
1792
- return {
1793
- aliasMap,
1794
- booleanFlags,
1795
- arrayFlags,
1796
- definedNames,
1797
- negationMap,
1798
- defaultNegationDisabledFields
1799
- };
1800
- }
1801
- /**
1802
- * Merge parsed argv with positional fields to create a flat record
1803
- */
1804
- function mergeWithPositionals(parsed, extracted) {
1805
- const result = { ...parsed.options };
1806
- const positionalFields = extracted.fields.filter((f) => f.positional);
1807
- const allPositionals = parsed.rest.length > 0 ? [...parsed.positionals, ...parsed.rest] : parsed.positionals;
1808
- let positionalIndex = 0;
1809
- for (const field of positionalFields) {
1810
- if (positionalIndex >= allPositionals.length) break;
1811
- if (field.type === "array") {
1812
- result[field.name] = allPositionals.slice(positionalIndex);
1813
- break;
1814
- } else {
1815
- result[field.name] = allPositionals[positionalIndex];
1816
- positionalIndex++;
1817
- }
1818
- }
1819
- return result;
1820
- }
1821
-
1822
- //#endregion
1823
- //#region ../core/src/parser/subcommand-scanner.ts
1824
- /**
1825
- * Build lookup tables from extracted global schema fields.
1826
- * Shared by scanForSubcommand, separateGlobalArgs, and findFirstPositional.
1827
- */
1828
- function buildGlobalFlagLookup(globalExtracted) {
1829
- const { aliasMap = /* @__PURE__ */ new Map(), booleanFlags = /* @__PURE__ */ new Set(), definedNames = /* @__PURE__ */ new Set(), negationMap = /* @__PURE__ */ new Map(), defaultNegationDisabledFields = /* @__PURE__ */ new Set() } = buildParserOptions(globalExtracted);
1830
- const shortAliases = /* @__PURE__ */ new Set();
1831
- for (const field of globalExtracted.fields) for (const alias of getAllAliases(field)) if (alias.length === 1) shortAliases.add(alias);
1832
- return {
1833
- aliasMap,
1834
- booleanFlags,
1835
- definedNames,
1836
- flagNames: new Set(globalExtracted.fields.map((f) => f.name)),
1837
- cliNames: new Set(globalExtracted.fields.map((f) => f.cliName)),
1838
- aliases: shortAliases,
1839
- negationMap,
1840
- defaultNegationDisabledFields
1841
- };
1842
- }
1843
- /**
1844
- * Resolve a long option (--flag, --flag=value, --no-flag, --custom-negation)
1845
- * against global flag lookup. Returns the resolved camelCase name and whether
1846
- * it is a known global flag.
1847
- *
1848
- * `isSuppressedNegation` is true when the token matches a disabled default
1849
- * `--no-X` form on the target field.
1850
- * The caller may use this to keep argv scanning past such tokens (so a
1851
- * trailing subcommand is still detected) even though they no longer negate.
1852
- */
1853
- function resolveGlobalLongOption(arg, lookup) {
1854
- const { resolvedName, withoutDashes, isNegated, isCustomNegation, isSuppressedNegation } = resolveLongOption(arg, lookup);
1855
- if (isSuppressedNegation) return {
1856
- resolvedName,
1857
- withoutDashes,
1858
- isNegated: false,
1859
- isGlobal: false,
1860
- isSuppressedNegation
1861
- };
1862
- const flagName = isNegated && !isCustomNegation ? withoutDashes.startsWith("no-") ? withoutDashes.slice(3) : withoutDashes[2].toLowerCase() + withoutDashes.slice(3) : withoutDashes;
1863
- return {
1864
- resolvedName,
1865
- withoutDashes,
1866
- isNegated,
1867
- isGlobal: lookup.flagNames.has(resolvedName) || lookup.cliNames.has(withoutDashes) || lookup.cliNames.has(flagName),
1868
- isSuppressedNegation: false
1869
- };
1870
- }
1871
- /**
1872
- * Check whether a non-boolean flag should consume the next argv token as its value.
1873
- * Returns true when the next token exists, is not a flag, and the current flag
1874
- * is not boolean / negated / using = syntax.
1875
- */
1876
- function shouldConsumeValue(arg, resolvedName, isNegated, nextArg, booleanFlags) {
1877
- return !arg.includes("=") && !booleanFlags.has(resolvedName) && !isNegated && nextArg !== void 0 && !nextArg.startsWith("-");
1878
- }
1879
- /**
1880
- * Collect a recognized global flag (and its value if applicable) into `dest`,
1881
- * returning how many argv positions were consumed (1 or 2).
1882
- */
1883
- function collectGlobalFlag(argv, i, resolvedName, isNegated, booleanFlags, dest) {
1884
- const arg = argv[i];
1885
- dest.push(arg);
1886
- if (shouldConsumeValue(arg, resolvedName, isNegated, argv[i + 1], booleanFlags)) {
1887
- dest.push(argv[i + 1]);
1888
- return 2;
1889
- }
1890
- return 1;
1891
- }
1892
- /**
1893
- * Scan argv to find the subcommand position, skipping over global flags.
1894
- *
1895
- * Walks argv and recognizes global flags (long, short, --no-*) so that
1896
- * `my-cli --verbose build --output dist` correctly identifies `build` as
1897
- * the subcommand (index 1) rather than treating `--verbose` as the subcommand.
1898
- *
1899
- * Limitation: flags appearing before the subcommand name are matched only
1900
- * against the global schema. If a flag is defined in both global and a
1901
- * subcommand's local schema, the pre-subcommand occurrence is always treated
1902
- * as global because the local schema is not available until the subcommand is
1903
- * identified (lazy-loaded commands make eager checking infeasible). Place
1904
- * colliding flags after the subcommand name so that `separateGlobalArgs` can
1905
- * apply local-precedence logic.
1906
- *
1907
- * @param argv - Command line arguments
1908
- * @param subCommandNames - Valid subcommand names
1909
- * @param globalExtracted - Extracted fields from global args schema
1910
- * @returns Scan result with subcommand position and token separation
1911
- */
1912
- function scanForSubcommand(argv, subCommandNames, globalExtracted) {
1913
- const lookup = buildGlobalFlagLookup(globalExtracted);
1914
- const subCommandNameSet = new Set(subCommandNames);
1915
- const globalTokensBefore = [];
1916
- const suppressedTokens = [];
1917
- let i = 0;
1918
- while (i < argv.length) {
1919
- const arg = argv[i];
1920
- if (arg === "--" || BUILTIN_FLAGS.has(arg)) break;
1921
- if (!arg.startsWith("-") && subCommandNameSet.has(arg)) return {
1922
- subCommandIndex: i,
1923
- globalTokensBefore,
1924
- tokensAfterSubcommand: argv.slice(i + 1),
1925
- suppressedTokens
1926
- };
1927
- if (arg.startsWith("--")) {
1928
- const { resolvedName, withoutDashes, isNegated, isGlobal, isSuppressedNegation } = resolveGlobalLongOption(arg, lookup);
1929
- if (isGlobal) {
1930
- i += collectGlobalFlag(argv, i, resolvedName, isNegated, lookup.booleanFlags, globalTokensBefore);
1931
- continue;
1932
- }
1933
- if (isSuppressedNegation) {
1934
- suppressedTokens.push(withoutDashes);
1935
- i++;
1936
- continue;
1937
- }
1938
- break;
1939
- }
1940
- if (arg.startsWith("-") && arg.length > 1) {
1941
- const withoutDash = arg.includes("=") ? arg.slice(1, arg.indexOf("=")) : arg.slice(1);
1942
- if (withoutDash.length === 1) {
1943
- const resolvedName = lookup.aliasMap.get(withoutDash) ?? withoutDash;
1944
- if (lookup.aliases.has(withoutDash) || lookup.flagNames.has(resolvedName)) {
1945
- i += collectGlobalFlag(argv, i, resolvedName, false, lookup.booleanFlags, globalTokensBefore);
1946
- continue;
1947
- }
1948
- }
1949
- break;
1950
- }
1951
- break;
1952
- }
1953
- return {
1954
- subCommandIndex: -1,
1955
- globalTokensBefore,
1956
- tokensAfterSubcommand: [],
1957
- suppressedTokens
1958
- };
1959
- }
1960
- const BUILTIN_FLAGS = /* @__PURE__ */ new Set([
1961
- "--help",
1962
- "-h",
1963
- "--help-all",
1964
- "-H",
1965
- "--version"
1966
- ]);
1967
- /**
1968
- * Find the index of the first positional argument in argv, properly skipping
1969
- * global flag values. Returns -1 when no positional is present.
1970
- *
1971
- * Mirrors `scanForSubcommand`'s conservative stop conditions: the scan stops
1972
- * (returning -1) on a `--` terminator, a builtin flag (`--help`/`--version`),
1973
- * an unknown long flag, or an unknown/combined short flag. Past such tokens we
1974
- * can't tell a flag *value* from a positional, so continuing would misclassify
1975
- * e.g. `--help plugin` or `--unknown value` and wrongly trip plugin dispatch.
1976
- *
1977
- * Without globalExtracted, no flag is global, so any leading flag halts the
1978
- * scan and a positional is only found when it precedes every flag.
1979
- */
1980
- function findFirstPositionalIndex(argv, globalExtracted, options = {}) {
1981
- const stopOnSuppressedNegation = options.stopOnSuppressedNegation === true || globalExtracted?.unknownKeysMode === "strict";
1982
- const lookup = globalExtracted ? buildGlobalFlagLookup(globalExtracted) : {
1983
- aliasMap: /* @__PURE__ */ new Map(),
1984
- booleanFlags: /* @__PURE__ */ new Set(),
1985
- definedNames: /* @__PURE__ */ new Set(),
1986
- flagNames: /* @__PURE__ */ new Set(),
1987
- cliNames: /* @__PURE__ */ new Set(),
1988
- aliases: /* @__PURE__ */ new Set(),
1989
- negationMap: /* @__PURE__ */ new Map(),
1990
- defaultNegationDisabledFields: /* @__PURE__ */ new Set()
1991
- };
1992
- for (let i = 0; i < argv.length; i++) {
1993
- const arg = argv[i];
1994
- if (!arg.startsWith("-")) return i;
1995
- if (arg === "--" || BUILTIN_FLAGS.has(arg)) return -1;
1996
- if (arg.startsWith("--")) {
1997
- const { resolvedName, isNegated, isGlobal, isSuppressedNegation } = resolveGlobalLongOption(arg, lookup);
1998
- if (isGlobal) {
1999
- if (shouldConsumeValue(arg, resolvedName, isNegated, argv[i + 1], lookup.booleanFlags)) i++;
2000
- continue;
2001
- }
2002
- if (isSuppressedNegation) {
2003
- if (stopOnSuppressedNegation) return -1;
2004
- continue;
2005
- }
2006
- return -1;
2007
- }
2008
- const withoutDash = arg.includes("=") ? arg.slice(1, arg.indexOf("=")) : arg.slice(1);
2009
- if (withoutDash.length === 1) {
2010
- const resolvedName = lookup.aliasMap.get(withoutDash) ?? withoutDash;
2011
- if (lookup.aliases.has(withoutDash) || lookup.flagNames.has(resolvedName)) {
2012
- if (shouldConsumeValue(arg, resolvedName, false, argv[i + 1], lookup.booleanFlags)) i++;
2013
- continue;
2014
- }
2015
- }
2016
- return -1;
2017
- }
2018
- return -1;
2019
- }
2020
- /**
2021
- * Find the first positional argument in argv, properly skipping global flag
2022
- * values. Thin wrapper over {@link findFirstPositionalIndex} — see that
2023
- * function for the scan and stop conditions. Returns `undefined` when none.
2024
- */
2025
- function findFirstPositional(argv, globalExtracted) {
2026
- const index = findFirstPositionalIndex(argv, globalExtracted);
2027
- return index >= 0 ? argv[index] : void 0;
2028
- }
2029
-
2030
- //#endregion
2031
- //#region ../core/src/parser/arg-parser.ts
2032
- /**
2033
- * Parse CLI arguments for a command
2034
- *
2035
- * @param argv - Command line arguments
2036
- * @param command - The command to parse for
2037
- * @param options - Parse options
2038
- * @returns Parse result
2039
- */
2040
- function parseArgs(argv, command, options = {}) {
2041
- const subCommandNameSet = listSubCommandNamesWithAliases(command);
2042
- const subCommandNames = [...subCommandNameSet];
2043
- const hasSubCommands = subCommandNames.length > 0;
2044
- if (hasSubCommands && argv.length > 0) if (options.globalExtracted) {
2045
- const scanResult = scanForSubcommand(argv, subCommandNames, options.globalExtracted);
2046
- if (scanResult.subCommandIndex >= 0) {
2047
- const rawGlobalArgs = parseGlobalArgs(scanResult.globalTokensBefore, options.globalExtracted);
2048
- return {
2049
- helpRequested: false,
2050
- helpAllRequested: false,
2051
- versionRequested: false,
2052
- subCommand: argv[scanResult.subCommandIndex],
2053
- remainingArgs: scanResult.tokensAfterSubcommand,
2054
- rawArgs: {},
2055
- positionals: [],
2056
- rest: [],
2057
- unknownFlags: scanResult.suppressedTokens,
2058
- unknownGlobalFlags: scanResult.suppressedTokens,
2059
- rawGlobalArgs
2060
- };
2061
- }
2062
- } else {
2063
- const firstArg = argv[0];
2064
- if (firstArg && !firstArg.startsWith("-") && subCommandNameSet.has(firstArg)) return {
2065
- helpRequested: false,
2066
- helpAllRequested: false,
2067
- versionRequested: false,
2068
- subCommand: firstArg,
2069
- remainingArgs: argv.slice(1),
2070
- rawArgs: {},
2071
- positionals: [],
2072
- rest: [],
2073
- unknownFlags: []
2074
- };
2075
- }
2076
- let extracted;
2077
- if (command.args) {
2078
- extracted = extractFields(command.args);
2079
- if (!options.skipValidation) {
2080
- validateDuplicateFields(extracted);
2081
- validateCaseVariantCollisions(extracted);
2082
- validateDuplicateAliases(extracted);
2083
- validateDuplicateNegations(extracted);
2084
- validatePositionalConfig(extracted);
2085
- validateReservedAliases(extracted, hasSubCommands);
2086
- validateReservedFieldNames(extracted);
2087
- if (options.globalExtracted) validateCrossSchemaCollisions(options.globalExtracted, extracted);
2088
- }
2089
- }
2090
- let commandArgv = argv;
2091
- let rawGlobalArgs;
2092
- let suppressedGlobalFlags = [];
2093
- if (options.globalExtracted) {
2094
- const { separated, globalParsed, suppressedTokens } = separateGlobalArgs(argv, options.globalExtracted, extracted);
2095
- commandArgv = separated;
2096
- rawGlobalArgs = globalParsed;
2097
- suppressedGlobalFlags = suppressedTokens;
2098
- }
2099
- const ddIdx = argv.indexOf("--");
2100
- const flagScanArgv = ddIdx >= 0 ? argv.slice(0, ddIdx) : argv;
2101
- const hasUserDefinedH = extracted?.fields.some((f) => f.overrideBuiltinAlias === true && getAllAliases(f).includes("H")) ?? false;
2102
- const hasUserDefinedh = extracted?.fields.some((f) => f.overrideBuiltinAlias === true && getAllAliases(f).includes("h")) ?? false;
2103
- const helpAllRequested = flagScanArgv.includes("--help-all") || !hasUserDefinedH && flagScanArgv.includes("-H");
2104
- const helpRequested = !helpAllRequested && (flagScanArgv.includes("--help") || !hasUserDefinedh && flagScanArgv.includes("-h"));
2105
- const versionRequested = flagScanArgv.includes("--version");
2106
- if (helpRequested || helpAllRequested || versionRequested) return {
2107
- helpRequested,
2108
- helpAllRequested,
2109
- versionRequested,
2110
- subCommand: void 0,
2111
- remainingArgs: [],
2112
- rawArgs: {},
2113
- positionals: [],
2114
- rest: [],
2115
- unknownFlags: [],
2116
- unknownGlobalFlags: suppressedGlobalFlags,
2117
- rawGlobalArgs
2118
- };
2119
- if (!extracted) {
2120
- const ddIdx = commandArgv.indexOf("--");
2121
- return {
2122
- helpRequested: false,
2123
- helpAllRequested: false,
2124
- versionRequested: false,
2125
- subCommand: void 0,
2126
- remainingArgs: [],
2127
- rawArgs: {},
2128
- positionals: ddIdx >= 0 ? commandArgv.slice(0, ddIdx) : commandArgv,
2129
- rest: ddIdx >= 0 ? commandArgv.slice(ddIdx + 1) : [],
2130
- unknownFlags: [],
2131
- unknownGlobalFlags: suppressedGlobalFlags,
2132
- rawGlobalArgs
2133
- };
2134
- }
2135
- const parserOptions = buildParserOptions(extracted);
2136
- const parsed = parseArgv(commandArgv, parserOptions);
2137
- const rawArgs = mergeWithPositionals(parsed, extracted);
2138
- const envFallbackFields = /* @__PURE__ */ new Set();
2139
- for (const field of extracted.fields) if (field.env && rawArgs[field.name] === void 0) {
2140
- const envNames = Array.isArray(field.env) ? field.env : [field.env];
2141
- for (const envName of envNames) {
2142
- const envValue = process.env[envName];
2143
- if (envValue !== void 0) {
2144
- rawArgs[field.name] = envValue;
2145
- envFallbackFields.add(field.name);
2146
- break;
2147
- }
2148
- }
2149
- }
2150
- const knownFlags = new Set(extracted.fields.map((f) => f.name));
2151
- const knownCliNames = new Set(extracted.fields.map((f) => f.cliName));
2152
- const knownAliases = /* @__PURE__ */ new Set();
2153
- for (const f of extracted.fields) for (const alias of getAllAliases(f)) knownAliases.add(alias);
2154
- if (options.globalExtracted) for (const f of options.globalExtracted.fields) {
2155
- knownFlags.add(f.name);
2156
- knownCliNames.add(f.cliName);
2157
- for (const alias of getAllAliases(f)) knownAliases.add(alias);
2158
- }
2159
- const unknownFlags = [];
2160
- for (const key of Object.keys(parsed.options)) if (!knownFlags.has(key) && !knownCliNames.has(key) && !knownAliases.has(key)) unknownFlags.push(key);
2161
- return {
2162
- helpRequested: false,
2163
- helpAllRequested: false,
2164
- versionRequested: false,
2165
- subCommand: void 0,
2166
- remainingArgs: [],
2167
- rawArgs,
2168
- positionals: parsed.positionals,
2169
- rest: parsed.rest,
2170
- unknownFlags,
2171
- unknownGlobalFlags: suppressedGlobalFlags,
2172
- extractedFields: extracted,
2173
- rawGlobalArgs,
2174
- envFallbackFields
2175
- };
2176
- }
2177
- /**
2178
- * Parse global args from a list of tokens (e.g., tokens before the subcommand).
2179
- * Env fallbacks are applied later in the runner on the accumulated global args.
2180
- */
2181
- function parseGlobalArgs(tokens, globalExtracted) {
2182
- if (tokens.length === 0) return {};
2183
- const parserOptions = buildParserOptions(globalExtracted);
2184
- const parsed = parseArgv(tokens, parserOptions);
2185
- return mergeWithPositionals(parsed, globalExtracted);
2186
- }
2187
- /**
2188
- * Separate global flags from command-local args in argv.
2189
- * Global flags mixed with command args (e.g., `build --verbose --output dist`)
2190
- * are extracted and returned separately.
2191
- * When a flag is defined in both global and local schemas, the local definition
2192
- * takes precedence (the flag stays in the command tokens).
2193
- *
2194
- * Note: Combined short flags (e.g., `-vq`) are not decomposed here; only
2195
- * single-character short options are recognized as global. The underlying
2196
- * `parseArgv` handles combined shorts for command-local parsing.
2197
- */
2198
- function separateGlobalArgs(argv, globalExtracted, localExtracted) {
2199
- const lookup = buildGlobalFlagLookup(globalExtracted);
2200
- const localFieldNames = new Set(localExtracted?.fields.map((f) => f.name) ?? []);
2201
- const localCliNames = new Set(localExtracted?.fields.map((f) => f.cliName) ?? []);
2202
- const localParserOptions = localExtracted ? buildParserOptions(localExtracted) : void 0;
2203
- const localAliasMapKeys = new Set(localParserOptions?.aliasMap?.keys() ?? []);
2204
- const localNegationMapKeys = new Set(localParserOptions?.negationMap?.keys() ?? []);
2205
- const localDefaultNegationKeys = /* @__PURE__ */ new Set();
2206
- for (const field of localExtracted?.fields ?? []) {
2207
- if (field.type !== "boolean" || field.negation !== true) continue;
2208
- for (const name of [field.cliName, ...getAllAliases(field)]) {
2209
- const kebab = `no-${name}`;
2210
- localDefaultNegationKeys.add(kebab);
2211
- localDefaultNegationKeys.add(toCamelCase(kebab));
2212
- }
2213
- }
2214
- const globalTokens = [];
2215
- const commandTokens = [];
2216
- const suppressedTokens = [];
2217
- for (let i = 0; i < argv.length; i++) {
2218
- const arg = argv[i];
2219
- if (arg === "--") {
2220
- commandTokens.push(...argv.slice(i));
2221
- break;
2222
- }
2223
- if (arg.startsWith("--")) {
2224
- const { resolvedName, withoutDashes, isNegated, isGlobal, isSuppressedNegation } = resolveGlobalLongOption(arg, lookup);
2225
- const flagName = resolvedName;
2226
- const isLocalCollision = localFieldNames.has(withoutDashes) || localFieldNames.has(flagName) || localCliNames.has(withoutDashes) || localCliNames.has(flagName) || localAliasMapKeys.has(withoutDashes) || localAliasMapKeys.has(flagName) || localNegationMapKeys.has(withoutDashes) || localNegationMapKeys.has(flagName) || localDefaultNegationKeys.has(withoutDashes);
2227
- if (isGlobal && !isLocalCollision) {
2228
- i += collectGlobalFlag(argv, i, resolvedName, isNegated, lookup.booleanFlags, globalTokens) - 1;
2229
- continue;
2230
- }
2231
- if (isSuppressedNegation && !isLocalCollision) {
2232
- suppressedTokens.push(withoutDashes);
2233
- continue;
2234
- }
2235
- } else if (arg.startsWith("-") && arg.length > 1) {
2236
- const withoutDash = arg.includes("=") ? arg.slice(1, arg.indexOf("=")) : arg.slice(1);
2237
- if (withoutDash.length === 1) {
2238
- const resolvedName = lookup.aliasMap.get(withoutDash) ?? withoutDash;
2239
- if ((lookup.aliases.has(withoutDash) || lookup.flagNames.has(resolvedName)) && !localAliasMapKeys.has(withoutDash)) {
2240
- i += collectGlobalFlag(argv, i, resolvedName, false, lookup.booleanFlags, globalTokens) - 1;
2241
- continue;
2242
- }
2243
- }
2244
- }
2245
- commandTokens.push(arg);
2246
- }
2247
- return {
2248
- separated: commandTokens,
2249
- globalParsed: parseGlobalArgs(globalTokens, globalExtracted),
2250
- suppressedTokens
2251
- };
2252
- }
2253
-
2254
- //#endregion
2255
- //#region ../core/src/validator/args-validator.ts
2256
- /**
2257
- * Args validation facade.
2258
- *
2259
- * Routes raw parsed args to the implementation that understands the
2260
- * command's schema: politty's internal validator-free descriptors, or the
2261
- * registered validator adapter for user schemas. Neutral error shapes live
2262
- * in `adapter/types.ts`; the schema-library-specific validation lives in
2263
- * the adapter package (e.g. `@politty/zod`).
2264
- */
2265
- /**
2266
- * Validate raw arguments against a schema
2267
- *
2268
- * @param rawArgs - Parsed but unvalidated arguments
2269
- * @param schema - Args schema (ZodObject, ZodDiscriminatedUnion, internal descriptor, etc.)
2270
- * @returns Validation result with typed data or errors
2271
- */
2272
- function validateArgs(rawArgs, schema) {
2273
- if (isInternalArgsSchema(schema)) return validateInternalArgs(rawArgs, schema);
2274
- return getValidatorAdapter().validate(rawArgs, schema);
2275
- }
2276
- /**
2277
- * Format validation errors for display
2278
- */
2279
- function formatValidationErrors(errors) {
2280
- return errors.map((e) => {
2281
- return `${e.path.length > 0 ? `${e.path.join(".")}: ` : ""}${e.message}`;
2282
- }).join("\n");
2283
- }
2284
-
2285
- //#endregion
2286
- //#region ../core/src/validator/error-formatter.ts
2287
- /**
2288
- * Calculate Levenshtein distance between two strings
2289
- */
2290
- function levenshteinDistance(a, b) {
2291
- const matrix = [];
2292
- for (let i = 0; i <= b.length; i++) matrix[i] = [i];
2293
- for (let j = 0; j <= a.length; j++) matrix[0][j] = j;
2294
- for (let i = 1; i <= b.length; i++) for (let j = 1; j <= a.length; j++) if (b.charAt(i - 1) === a.charAt(j - 1)) matrix[i][j] = matrix[i - 1][j - 1];
2295
- else matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1);
2296
- return matrix[b.length][a.length];
2297
- }
2298
- /**
2299
- * Find similar strings from a list
2300
- */
2301
- function findSimilar(target, candidates) {
2302
- const threshold = Math.max(2, Math.floor(target.length / 2));
2303
- return candidates.map((candidate) => ({
2304
- candidate,
2305
- distance: levenshteinDistance(target.toLowerCase(), candidate.toLowerCase())
2306
- })).filter(({ distance }) => distance <= threshold).sort((a, b) => a.distance - b.distance).map(({ candidate }) => candidate).slice(0, 3);
2307
- }
2308
- /**
2309
- * Format unknown flag warning with suggestions (for strip mode)
2310
- *
2311
- * @param flag - The unknown flag (e.g., "--verbos")
2312
- * @param knownFlags - List of known flag names
2313
- * @returns Formatted warning message with suggestions
2314
- */
2315
- function formatUnknownFlagWarning(flag, knownFlags) {
2316
- const similar = findSimilar(flag.replace(/^-{1,2}/, ""), knownFlags);
2317
- let message = `${styles.warning("Warning: Unknown option:")} ${styles.bold(flag)}`;
2318
- if (similar.length > 0) {
2319
- message += `\n\n${styles.info("Did you mean?")}`;
2320
- for (const suggestion of similar) message += `\n ${symbols.arrow} ${styles.option(`--${suggestion}`)}`;
2321
- }
2322
- return message;
2323
- }
2324
- /**
2325
- * Format runtime error
2326
- *
2327
- * @param error - The error that occurred
2328
- * @param debug - Whether to include stack trace
2329
- * @returns Formatted error message
2330
- */
2331
- function formatRuntimeError(error, debug) {
2332
- if (debug && error.stack) return `${styles.error("Error:")} ${error.message}\n\n${styles.dim(error.stack)}`;
2333
- return `${styles.error("Error:")} ${error.message}`;
2334
- }
2335
-
2336
- //#endregion
2337
- //#region ../core/src/core/case-proxy.ts
2338
- /**
2339
- * Wrap an args object with a Proxy that allows dual-case access.
2340
- *
2341
- * Given `{ "my-option": "value" }`, both `obj["my-option"]` and `obj.myOption`
2342
- * will return `"value"`.
2343
- *
2344
- * - `Object.keys()`, `JSON.stringify()`, and spread return only the original keys.
2345
- * - The `in` operator detects both case variants.
2346
- */
2347
- function createDualCaseProxy(obj) {
2348
- return new Proxy(obj, {
2349
- get(target, prop, receiver) {
2350
- if (typeof prop === "string") {
2351
- if (prop in target) return Reflect.get(target, prop, receiver);
2352
- const camel = toCamelCase(prop);
2353
- if (camel !== prop && camel in target) return Reflect.get(target, camel, receiver);
2354
- const kebab = toKebabCase(prop);
2355
- if (kebab !== prop && kebab in target) return Reflect.get(target, kebab, receiver);
2356
- }
2357
- return Reflect.get(target, prop, receiver);
2358
- },
2359
- has(target, prop) {
2360
- if (typeof prop === "string") {
2361
- if (prop in target) return true;
2362
- const camel = toCamelCase(prop);
2363
- if (camel !== prop && camel in target) return true;
2364
- const kebab = toKebabCase(prop);
2365
- if (kebab !== prop && kebab in target) return true;
2366
- }
2367
- return Reflect.has(target, prop);
2368
- }
2369
- });
2370
- }
2371
-
2372
- //#endregion
2373
- //#region ../core/src/core/effect-runner.ts
2374
- /**
2375
- * Execute all registered effect callbacks for validated args.
2376
- *
2377
- * Effects run sequentially in field-definition order.
2378
- * Only fires for fields that have an `effect` callback defined.
2379
- *
2380
- * @param validatedArgs - The validated (post-Zod) argument values
2381
- * @param extracted - The extracted fields from the schema
2382
- * @param globalArgs - The validated global args (passed to command arg effects)
2383
- */
2384
- async function runEffects(validatedArgs, extracted, globalArgs) {
2385
- for (const field of extracted.fields) {
2386
- if (!field.effect) continue;
2387
- await field.effect(validatedArgs[field.name], {
2388
- name: field.name,
2389
- args: validatedArgs,
2390
- ...globalArgs != null && { globalArgs }
2391
- });
2392
- }
2393
- }
2394
-
2395
- //#endregion
2396
- //#region ../core/src/core/runner.ts
2397
- /**
2398
- * Default logger using console
2399
- */
2400
- const defaultLogger = {
2401
- log: (message) => console.log(message),
2402
- error: (message) => console.error(message),
2403
- warn: (message) => console.warn(message)
2404
- };
2405
- /**
2406
- * Attach a non-enumerable `$source` helper to the final args object so it
2407
- * stays invisible to `Object.keys`/`JSON.stringify`/spread (those only ever
2408
- * see real field values) while still being reachable via property access
2409
- * (including through `createDualCaseProxy`).
2410
- */
2411
- function attachArgSource(target, sourceMap) {
2412
- Object.defineProperty(target, "$source", {
2413
- value: (name) => sourceMap.get(name) ?? sourceMap.get(toCamelCase(name)) ?? sourceMap.get(toKebabCase(name)) ?? "default",
2414
- enumerable: false
2415
- });
2416
- }
2417
- /**
2418
- * Run a command with the given arguments (programmatic/test usage)
2419
- *
2420
- * This function parses arguments, validates them, routes to subcommands,
2421
- * and executes the command. It does NOT call process.exit.
2422
- *
2423
- * @param command - The command to run
2424
- * @param argv - Command line arguments to parse
2425
- * @param options - Run options
2426
- * @returns The result of command execution
2427
- *
2428
- * @example
2429
- * ```ts
2430
- * import { defineCommand, runCommand } from "politty";
2431
- *
2432
- * const command = defineCommand({
2433
- * name: "my-cli",
2434
- * args: z.object({ name: z.string() }),
2435
- * run: ({ name }) => console.log(`Hello, ${name}!`),
2436
- * });
2437
- *
2438
- * // In tests
2439
- * const result = await runCommand(command, ["--name", "World"]);
2440
- * expect(result.exitCode).toBe(0);
2441
- * ```
2442
- */
2443
- async function runCommand(command, argv, options = {}) {
2444
- const globalExtracted = extractAndValidateGlobal(options);
2445
- const shouldCaptureLogs = options.captureLogs ?? false;
2446
- const globalCollector = shouldCaptureLogs ? createLogCollector() : null;
2447
- if (options.setup) {
2448
- globalCollector?.start();
2449
- try {
2450
- await options.setup({});
2451
- } catch (e) {
2452
- const error = e instanceof Error ? e : new Error(String(e));
2453
- if (options.cleanup) try {
2454
- await options.cleanup({ error });
2455
- } catch {}
2456
- globalCollector?.stop();
2457
- return {
2458
- success: false,
2459
- error,
2460
- exitCode: 1,
2461
- logs: globalCollector?.getLogs() ?? emptyLogs()
2462
- };
2463
- }
2464
- globalCollector?.stop();
2465
- }
2466
- const result = await runCommandInternal(command, argv, {
2467
- ...options,
2468
- handleSignals: false,
2469
- _globalExtracted: globalExtracted,
2470
- _globalCleanup: options.cleanup,
2471
- _existingLogs: globalCollector?.getLogs()
2472
- });
2473
- if (options.cleanup) {
2474
- const cleanupCollector = shouldCaptureLogs ? createLogCollector() : null;
2475
- cleanupCollector?.start();
2476
- const cleanupCtx = { error: !result.success ? result.error : void 0 };
2477
- try {
2478
- await options.cleanup(cleanupCtx);
2479
- } catch (e) {
2480
- if (result.success) {
2481
- const error = e instanceof Error ? e : new Error(String(e));
2482
- cleanupCollector?.stop();
2483
- return {
2484
- success: false,
2485
- error,
2486
- exitCode: 1,
2487
- logs: mergeLogs(result.logs, cleanupCollector?.getLogs() ?? emptyLogs())
2488
- };
2489
- }
2490
- }
2491
- cleanupCollector?.stop();
2492
- const cleanupLogs = cleanupCollector?.getLogs() ?? emptyLogs();
2493
- if (cleanupLogs.entries.length > 0) return {
2494
- ...result,
2495
- logs: mergeLogs(result.logs, cleanupLogs)
2496
- };
2497
- }
2498
- return result;
2499
- }
2500
- /**
2501
- * Hidden internal subcommands (e.g. `__refresh-completion`) are spawned
2502
- * by background hooks and must not run user-provided
2503
- * `setup`/`cleanup`/`prompt` or required `globalArgs`. Those exist for
2504
- * the foreground CLI run; replaying them in a detached child causes
2505
- * duplicate side effects, stuck prompts, and validation failures the
2506
- * user never opted into.
2507
- *
2508
- * We treat any registered subcommand whose name starts with `__` as
2509
- * internal. We use `findFirstPositional` (schema-aware) instead of the
2510
- * naive "first non-flag token" so an option *value* like
2511
- * `--name __refresh-completion` doesn't trip the bypass — that would
2512
- * silently skip lifecycle hooks for ordinary invocations.
2513
- */
2514
- function isInternalSubcommandInvocation(command, argv, globalExtracted) {
2515
- const firstPositional = findFirstPositional(argv, globalExtracted);
2516
- if (!firstPositional || !firstPositional.startsWith("__")) return false;
2517
- return Object.hasOwn(command.subCommands ?? {}, firstPositional);
2518
- }
2519
- /**
2520
- * Run a CLI command as the main entry point
2521
- *
2522
- * This function:
2523
- * - Uses process.argv for arguments
2524
- * - Handles SIGINT/SIGTERM signals
2525
- * - Calls process.exit with the appropriate exit code
2526
- * - Invokes `command.runMainHook` once before parsing if set, so plug-ins
2527
- * like `withCompletionCommand` can fire detached background work
2528
- * - Bypasses user `setup`/`cleanup`/`prompt` and required `globalArgs`
2529
- * for registered hidden subcommands whose name starts with `__`
2530
- * (e.g. `__refresh-completion`)
2531
- *
2532
- * @param command - The command to run
2533
- * @param options - Main options (version, debug)
2534
- *
2535
- * @example
2536
- * ```ts
2537
- * import { defineCommand, runMain } from "politty";
2538
- *
2539
- * const command = defineCommand({
2540
- * name: "my-cli",
2541
- * run: () => console.log("Hello!"),
2542
- * });
2543
- *
2544
- * runMain(command, { version: "1.0.0" });
2545
- * ```
2546
- */
2547
- async function runMain(command, options = {}) {
2548
- if (options.compileCache !== false) enableCompileCache(typeof options.compileCache === "string" ? { cacheDir: options.compileCache } : { programName: command.name });
2549
- if (command.runMainHook) try {
2550
- command.runMainHook(process.argv.slice(2));
2551
- } catch {}
2552
- const argv = process.argv.slice(2);
2553
- let globalExtractedForBypass;
2554
- if (options.globalArgs) try {
2555
- globalExtractedForBypass = extractFields(options.globalArgs);
2556
- } catch {}
2557
- let effectiveOptions = options;
2558
- if (isInternalSubcommandInvocation(command, argv, globalExtractedForBypass)) {
2559
- const { setup: _s, cleanup: _c, prompt: _p, globalArgs: _g, ...rest } = options;
2560
- effectiveOptions = rest;
2561
- }
2562
- const globalExtracted = extractAndValidateGlobal(effectiveOptions);
2563
- if (effectiveOptions.onUnknownSubcommand && !command.run && !isInternalSubcommandInvocation(command, argv, globalExtractedForBypass)) {
2564
- const knownSubCommands = listSubCommandNamesWithAliases(command);
2565
- if (knownSubCommands.size > 0) {
2566
- const positionalIndex = findFirstPositionalIndex(argv, globalExtracted, { stopOnSuppressedNegation: globalExtracted?.unknownKeysMode !== "passthrough" });
2567
- const name = positionalIndex >= 0 ? argv[positionalIndex] : void 0;
2568
- if (name && !knownSubCommands.has(name)) {
2569
- const forwardArgs = argv.slice(positionalIndex + 1);
2570
- const exitCode = await effectiveOptions.onUnknownSubcommand({
2571
- commandPath: [],
2572
- name,
2573
- args: forwardArgs,
2574
- precedingArgs: argv.slice(0, positionalIndex)
2575
- });
2576
- if (typeof exitCode === "number") {
2577
- await flushStandardStreams();
2578
- return process.exit(exitCode);
2579
- }
2580
- }
2581
- }
2582
- }
2583
- if (effectiveOptions.setup) try {
2584
- await effectiveOptions.setup({});
2585
- } catch (e) {
2586
- const error = e instanceof Error ? e : new Error(String(e));
2587
- if (effectiveOptions.cleanup) try {
2588
- await effectiveOptions.cleanup({ error });
2589
- } catch {}
2590
- process.exit(1);
2591
- }
2592
- const result = await runCommandInternal(command, argv, {
2593
- debug: effectiveOptions.debug,
2594
- captureLogs: effectiveOptions.captureLogs,
2595
- skipValidation: effectiveOptions.skipValidation,
2596
- handleSignals: true,
2597
- logger: effectiveOptions.logger,
2598
- globalArgs: effectiveOptions.globalArgs,
2599
- prompt: effectiveOptions.prompt,
2600
- onUnknownSubcommand: effectiveOptions.onUnknownSubcommand,
2601
- _globalExtracted: globalExtracted,
2602
- _globalCleanup: effectiveOptions.cleanup,
2603
- _context: {
2604
- commandPath: [],
2605
- rootName: command.name,
2606
- rootVersion: effectiveOptions.version,
2607
- globalExtracted
2608
- }
2609
- });
2610
- if ((effectiveOptions.displayErrors ?? true) && !result.success && result.error) (effectiveOptions.logger ?? defaultLogger).error(formatRuntimeError(result.error, effectiveOptions.debug ?? false));
2611
- if (effectiveOptions.cleanup) {
2612
- const cleanupCtx = { error: !result.success ? result.error : void 0 };
2613
- try {
2614
- await effectiveOptions.cleanup(cleanupCtx);
2615
- } catch {}
2616
- }
2617
- await flushStandardStreams();
2618
- process.exit(result.exitCode);
2619
- }
2620
- /**
2621
- * Flush stdout/stderr before exit to prevent truncated output when piped
2622
- * (pipe writes are buffered asynchronously, so exiting early loses data).
2623
- *
2624
- * We await a zero-byte write's callback rather than a `drain` event: `drain`
2625
- * only fires after a `write()` returned `false` (backpressure), so buffered
2626
- * writes that never tripped it would hang. The write callback is ordered after
2627
- * all pending writes, so it resolves once the buffer is flushed.
2628
- */
2629
- async function flushStandardStreams() {
2630
- await Promise.all([process.stdout, process.stderr].map((stream) => stream.writableLength > 0 ? new Promise((resolve) => stream.write("", () => resolve())) : Promise.resolve()));
2631
- }
2632
- /**
2633
- * Internal implementation of command running
2634
- */
2635
- async function runCommandInternal(command, argv, options = {}) {
2636
- const logger = options.logger ?? defaultLogger;
2637
- const context = options._context ?? {
2638
- commandPath: [],
2639
- rootName: command.name,
2640
- globalExtracted: options._globalExtracted
2641
- };
2642
- const collector = options.captureLogs ?? false ? createLogCollector() : null;
2643
- collector?.start();
2644
- const getCurrentLogs = () => {
2645
- const existingLogs = options._existingLogs ?? emptyLogs();
2646
- const collectedLogs = collector?.getLogs() ?? emptyLogs();
2647
- return mergeLogs(existingLogs, collectedLogs);
2648
- };
2649
- try {
2650
- const parseResult = parseArgs(argv, command, {
2651
- skipValidation: options.skipValidation,
2652
- globalExtracted: options._globalExtracted
2653
- });
2654
- const accumulatedGlobalArgs = {
2655
- ...options._parsedGlobalArgs,
2656
- ...parseResult.rawGlobalArgs
2657
- };
2658
- const nestedCommandPath = context.commandPath ?? [];
2659
- if (options.onUnknownSubcommand && !command.run && nestedCommandPath.length > 0) {
2660
- const knownSubCommands = listSubCommandNamesWithAliases(command);
2661
- if (knownSubCommands.size > 0) {
2662
- const positionalIndex = findFirstPositionalIndex(argv, options._globalExtracted, { stopOnSuppressedNegation: options._globalExtracted?.unknownKeysMode !== "passthrough" });
2663
- const name = positionalIndex >= 0 ? argv[positionalIndex] : void 0;
2664
- if (name && !knownSubCommands.has(name)) {
2665
- const forwardArgs = argv.slice(positionalIndex + 1);
2666
- const exitCode = await options.onUnknownSubcommand({
2667
- commandPath: nestedCommandPath,
2668
- name,
2669
- args: forwardArgs,
2670
- precedingArgs: [...options._precedingArgs ?? [], ...argv.slice(0, positionalIndex)]
2671
- });
2672
- if (typeof exitCode === "number") {
2673
- collector?.stop();
2674
- if (options.handleSignals) {
2675
- if (options._globalCleanup) try {
2676
- await options._globalCleanup({ error: void 0 });
2677
- } catch {}
2678
- await flushStandardStreams();
2679
- process.exit(exitCode);
2680
- }
2681
- return exitCode === 0 ? {
2682
- success: true,
2683
- result: void 0,
2684
- exitCode: 0,
2685
- logs: getCurrentLogs()
2686
- } : {
2687
- success: false,
2688
- error: /* @__PURE__ */ new Error(`Plugin "${[...nestedCommandPath, name].join(" ")}" exited with code ${exitCode}`),
2689
- exitCode,
2690
- logs: getCurrentLogs()
2691
- };
2692
- }
2693
- }
2694
- }
2695
- }
2696
- if (parseResult.helpRequested || parseResult.helpAllRequested) {
2697
- let hasUnknownSubcommand = false;
2698
- const subCmdNames = listSubCommands(command);
2699
- const allSubCmdNameSet = listSubCommandNamesWithAliases(command);
2700
- if (subCmdNames.length > 0) {
2701
- const potentialSubCmd = findFirstPositional(argv, context.globalExtracted);
2702
- if (potentialSubCmd && !allSubCmdNameSet.has(potentialSubCmd)) hasUnknownSubcommand = true;
2703
- }
2704
- const help = generateHelp(command, {
2705
- showSubcommands: options.showSubcommands ?? true,
2706
- showSubcommandOptions: parseResult.helpAllRequested || options.showSubcommandOptions,
2707
- context
2708
- });
2709
- logger.log(help);
2710
- collector?.stop();
2711
- if (hasUnknownSubcommand) {
2712
- const unknownCmd = findFirstPositional(argv, context.globalExtracted) ?? "";
2713
- const similar = findSimilar(unknownCmd, [...allSubCmdNameSet]);
2714
- const suggestion = similar.length > 0 ? ` Did you mean: ${similar.join(", ")}?` : "";
2715
- return {
2716
- success: false,
2717
- error: /* @__PURE__ */ new Error(`Unknown subcommand: ${unknownCmd}${suggestion ? `.${suggestion}` : ""}`),
2718
- exitCode: 1,
2719
- logs: getCurrentLogs()
2720
- };
2721
- }
2722
- return {
2723
- success: true,
2724
- result: void 0,
2725
- exitCode: 0,
2726
- logs: getCurrentLogs()
2727
- };
2728
- }
2729
- if (parseResult.unknownGlobalFlags && parseResult.unknownGlobalFlags.length > 0) {
2730
- const globalMode = context.globalExtracted?.unknownKeysMode ?? "strip";
2731
- if (globalMode === "strict") {
2732
- collector?.stop();
2733
- return {
2734
- success: false,
2735
- error: /* @__PURE__ */ new Error(`Unknown flags: ${parseResult.unknownGlobalFlags.join(", ")}`),
2736
- exitCode: 1,
2737
- logs: getCurrentLogs()
2738
- };
2739
- }
2740
- if (globalMode === "strip") {
2741
- const knownGlobalFlags = context.globalExtracted?.fields.map((f) => f.name) ?? [];
2742
- for (const flag of parseResult.unknownGlobalFlags) logger.error(formatUnknownFlagWarning(flag, knownGlobalFlags));
2743
- }
2744
- }
2745
- if (parseResult.versionRequested) {
2746
- const version = context.rootVersion;
2747
- if (version) logger.log(version);
2748
- collector?.stop();
2749
- return {
2750
- success: true,
2751
- result: void 0,
2752
- exitCode: 0,
2753
- logs: getCurrentLogs()
2754
- };
2755
- }
2756
- if (parseResult.subCommand) {
2757
- const resolved = await resolveSubcommandWithAlias(command, parseResult.subCommand);
2758
- if (resolved) {
2759
- const subContext = {
2760
- commandPath: [...context.commandPath ?? [], parseResult.subCommand],
2761
- rootName: context.rootName,
2762
- rootVersion: context.rootVersion,
2763
- globalExtracted: context.globalExtracted,
2764
- aliasFor: resolved.aliasFor
2765
- };
2766
- collector?.stop();
2767
- const suppressedNames = new Set(options._globalExtracted?.unknownKeysMode === "passthrough" ? [] : parseResult.unknownGlobalFlags ?? []);
2768
- const isSuppressedFlag = (token) => {
2769
- return token.startsWith("--") && suppressedNames.has(getLongOptionName(token));
2770
- };
2771
- const levelPrecedingArgs = argv.slice(0, argv.length - parseResult.remainingArgs.length - 1).filter((token) => !isSuppressedFlag(token));
2772
- return runCommandInternal(resolved.command, parseResult.remainingArgs, {
2773
- ...options,
2774
- _context: subContext,
2775
- _existingLogs: getCurrentLogs(),
2776
- _parsedGlobalArgs: accumulatedGlobalArgs,
2777
- _precedingArgs: [...options._precedingArgs ?? [], ...levelPrecedingArgs]
2778
- });
2779
- }
2780
- }
2781
- const positionalFields = parseResult.extractedFields?.fields.filter((f) => f.positional) ?? [];
2782
- const hasArrayPositional = positionalFields.some((f) => f.type === "array");
2783
- const allPositionals = [...parseResult.positionals, ...parseResult.rest];
2784
- const extraPositionals = hasArrayPositional ? [] : allPositionals.slice(positionalFields.length);
2785
- const unconsumedRegulars = hasArrayPositional ? [] : parseResult.positionals.slice(positionalFields.length);
2786
- if (listSubCommands(command).length > 0 && !parseResult.subCommand && !command.run && extraPositionals.length === 0) {
2787
- const help = generateHelp(command, {
2788
- showSubcommands: options.showSubcommands ?? true,
2789
- context
2790
- });
2791
- logger.log(help);
2792
- collector?.stop();
2793
- return {
2794
- success: true,
2795
- result: void 0,
2796
- exitCode: 0,
2797
- logs: getCurrentLogs()
2798
- };
2799
- }
2800
- if (parseResult.unknownFlags.length > 0) {
2801
- const unknownKeysMode = parseResult.extractedFields?.unknownKeysMode ?? "strip";
2802
- const knownFlags = parseResult.extractedFields?.fields.map((f) => f.name) ?? [];
2803
- if (unknownKeysMode === "strict") {
2804
- collector?.stop();
2805
- return {
2806
- success: false,
2807
- error: /* @__PURE__ */ new Error(`Unknown flags: ${parseResult.unknownFlags.join(", ")}`),
2808
- exitCode: 1,
2809
- logs: getCurrentLogs()
2810
- };
2811
- } else if (unknownKeysMode === "strip") for (const flag of parseResult.unknownFlags) logger.error(formatUnknownFlagWarning(flag, knownFlags));
2812
- }
2813
- if (extraPositionals.length > 0) {
2814
- const subCmdNames = listSubCommandNamesWithAliases(command);
2815
- if (subCmdNames.size > 0) {
2816
- const unknownCmd = unconsumedRegulars.find((t) => !t.startsWith("-") && !subCmdNames.has(t));
2817
- if (unknownCmd) {
2818
- const similar = findSimilar(unknownCmd, [...subCmdNames]);
2819
- const suggestion = similar.length > 0 ? ` Did you mean: ${similar.join(", ")}?` : "";
2820
- collector?.stop();
2821
- return {
2822
- success: false,
2823
- error: /* @__PURE__ */ new Error(`Unknown subcommand: ${unknownCmd}${suggestion ? `.${suggestion}` : ""}`),
2824
- exitCode: 1,
2825
- logs: getCurrentLogs()
2826
- };
2827
- }
2828
- }
2829
- const unknownKeysMode = parseResult.extractedFields?.unknownKeysMode ?? "strip";
2830
- if (unknownKeysMode === "strict") {
2831
- collector?.stop();
2832
- return {
2833
- success: false,
2834
- error: /* @__PURE__ */ new Error(`Unexpected positional argument${extraPositionals.length > 1 ? "s" : ""}: ${extraPositionals.join(", ")}`),
2835
- exitCode: 1,
2836
- logs: getCurrentLogs()
2837
- };
2838
- } else if (unknownKeysMode === "strip") for (const positional of extraPositionals) (logger.warn ?? logger.error)(`Warning: Unexpected positional argument: ${positional}`);
2839
- }
2840
- let validatedGlobalArgs = {};
2841
- const isCompletionInvocation = command.name === "__complete";
2842
- const cliProvidedGlobalFields = new Set(Object.keys(accumulatedGlobalArgs));
2843
- const envFallbackGlobalFields = /* @__PURE__ */ new Set();
2844
- if (options.globalArgs && options._globalExtracted && !isCompletionInvocation) {
2845
- for (const field of options._globalExtracted.fields) if (field.env && accumulatedGlobalArgs[field.name] === void 0) {
2846
- const envNames = Array.isArray(field.env) ? field.env : [field.env];
2847
- for (const envName of envNames) {
2848
- const envValue = process.env[envName];
2849
- if (envValue !== void 0) {
2850
- accumulatedGlobalArgs[field.name] = envValue;
2851
- envFallbackGlobalFields.add(field.name);
2852
- break;
2853
- }
2854
- }
2855
- }
2856
- if (options.prompt) {
2857
- const resolved = await options.prompt(accumulatedGlobalArgs, options._globalExtracted);
2858
- for (const [key, value] of Object.entries(resolved)) if (value !== void 0) accumulatedGlobalArgs[key] = value;
2859
- }
2860
- const globalValidation = validateArgs(accumulatedGlobalArgs, options.globalArgs);
2861
- if (!globalValidation.success) {
2862
- collector?.stop();
2863
- return {
2864
- success: false,
2865
- error: new Error(formatValidationErrors(globalValidation.errors)),
2866
- exitCode: 1,
2867
- logs: getCurrentLogs()
2868
- };
2869
- }
2870
- validatedGlobalArgs = globalValidation.data;
2871
- }
2872
- if (!command.args) {
2873
- const globalSourceMap = /* @__PURE__ */ new Map();
2874
- for (const name of cliProvidedGlobalFields) globalSourceMap.set(name, "cli");
2875
- for (const name of envFallbackGlobalFields) globalSourceMap.set(name, "env");
2876
- attachArgSource(validatedGlobalArgs, globalSourceMap);
2877
- const proxiedGlobalArgs = createDualCaseProxy(validatedGlobalArgs);
2878
- if (options._globalExtracted && !isCompletionInvocation) await runEffects(proxiedGlobalArgs, options._globalExtracted, proxiedGlobalArgs);
2879
- collector?.stop();
2880
- return await executeLifecycle(command, proxiedGlobalArgs, {
2881
- handleSignals: options.handleSignals,
2882
- captureLogs: options.captureLogs,
2883
- existingLogs: getCurrentLogs(),
2884
- globalCleanup: options._globalCleanup
2885
- });
2886
- }
2887
- let argsToValidate = parseResult.rawArgs;
2888
- const promptResolvedFields = /* @__PURE__ */ new Set();
2889
- if (options.prompt && parseResult.extractedFields) {
2890
- const resolved = await options.prompt(argsToValidate, parseResult.extractedFields);
2891
- const nextArgsToValidate = { ...argsToValidate };
2892
- for (const [key, value] of Object.entries(resolved)) if (value !== void 0) {
2893
- nextArgsToValidate[key] = value;
2894
- promptResolvedFields.add(key);
2895
- }
2896
- argsToValidate = nextArgsToValidate;
2897
- }
2898
- const globalPrefilledFields = /* @__PURE__ */ new Set();
2899
- if (parseResult.extractedFields) {
2900
- for (const field of parseResult.extractedFields.fields) if (!(Object.hasOwn(parseResult.rawArgs, field.name) || promptResolvedFields.has(field.name)) && cliProvidedGlobalFields.has(field.name) && Object.hasOwn(validatedGlobalArgs, field.name)) {
2901
- argsToValidate = {
2902
- ...argsToValidate,
2903
- [field.name]: validatedGlobalArgs[field.name]
2904
- };
2905
- globalPrefilledFields.add(field.name);
2906
- }
2907
- }
2908
- const validationResult = validateArgs(argsToValidate, command.args);
2909
- if (!validationResult.success) {
2910
- collector?.stop();
2911
- return {
2912
- success: false,
2913
- error: new Error(formatValidationErrors(validationResult.errors)),
2914
- exitCode: 1,
2915
- logs: getCurrentLogs()
2916
- };
2917
- }
2918
- const proxiedCommandArgs = createDualCaseProxy(validationResult.data);
2919
- const proxiedGlobalArgs = createDualCaseProxy(validatedGlobalArgs);
2920
- if (options._globalExtracted && !isCompletionInvocation) await runEffects(proxiedGlobalArgs, options._globalExtracted, proxiedGlobalArgs);
2921
- if (parseResult.extractedFields && !isCompletionInvocation) await runEffects(proxiedCommandArgs, parseResult.extractedFields, proxiedGlobalArgs);
2922
- const mergedPlainArgs = {
2923
- ...proxiedGlobalArgs,
2924
- ...proxiedCommandArgs
2925
- };
2926
- const argSourceMap = /* @__PURE__ */ new Map();
2927
- for (const name of cliProvidedGlobalFields) argSourceMap.set(name, "cli");
2928
- for (const name of envFallbackGlobalFields) argSourceMap.set(name, "env");
2929
- const localEnvFallbackFields = parseResult.envFallbackFields ?? /* @__PURE__ */ new Set();
2930
- for (const field of parseResult.extractedFields?.fields ?? []) {
2931
- if (globalPrefilledFields.has(field.name)) {
2932
- argSourceMap.set(field.name, "cli");
2933
- continue;
2934
- }
2935
- const localHasCliOrEnvValue = Object.hasOwn(parseResult.rawArgs, field.name) || localEnvFallbackFields.has(field.name);
2936
- argSourceMap.set(field.name, localHasCliOrEnvValue ? localEnvFallbackFields.has(field.name) ? "env" : "cli" : "default");
2937
- }
2938
- attachArgSource(mergedPlainArgs, argSourceMap);
2939
- const mergedArgs = createDualCaseProxy(mergedPlainArgs);
2940
- collector?.stop();
2941
- return await executeLifecycle(command, mergedArgs, {
2942
- handleSignals: options.handleSignals,
2943
- captureLogs: options.captureLogs,
2944
- existingLogs: getCurrentLogs(),
2945
- globalCleanup: options._globalCleanup
2946
- });
2947
- } catch (error) {
2948
- const err = error instanceof Error ? error : new Error(String(error));
2949
- collector?.stop();
2950
- return {
2951
- success: false,
2952
- error: err,
2953
- exitCode: 1,
2954
- logs: getCurrentLogs()
2955
- };
2956
- }
2957
- }
2958
- /**
2959
- * Extract global fields from options.globalArgs and validate the schema upfront.
2960
- * Rejects positional fields since global options must be flags.
2961
- * Returns undefined when no globalArgs is provided.
2962
- */
2963
- function extractAndValidateGlobal(options) {
2964
- if (!options.globalArgs) return void 0;
2965
- const extracted = extractFields(options.globalArgs);
2966
- if (!options.skipValidation) {
2967
- validateDuplicateFields(extracted);
2968
- validateCaseVariantCollisions(extracted);
2969
- validateDuplicateAliases(extracted);
2970
- validateDuplicateNegations(extracted);
2971
- validateReservedAliases(extracted, true);
2972
- validateReservedFieldNames(extracted);
2973
- const positionalNames = extracted.fields.filter((f) => f.positional).map((f) => f.name);
2974
- if (positionalNames.length > 0) throw new Error(`Global options schema must not contain positional arguments. Found: ${positionalNames.join(", ")}`);
2975
- }
2976
- return extracted;
2977
- }
2978
-
2979
- //#endregion
2980
- export { ReservedFieldNameError as C, renderMarkdown as E, ReservedAliasError as S, renderInline as T, DuplicateAliasError as _, parseArgv as a, FieldTypeConflictError as b, validateCommand as c, validateDuplicateFields as d, validateDuplicateNegations as f, CaseVariantCollisionError as g, validateReservedFieldNames as h, formatValidationErrors as i, validateCrossSchemaCollisions as l, validateReservedAliases as m, runMain as n, formatCommandValidationErrors as o, validatePositionalConfig as p, createDualCaseProxy as r, validateCaseVariantCollisions as s, runCommand as t, validateDuplicateAliases as u, DuplicateFieldError as v, generateHelp as w, PositionalConfigError as x, DuplicateNegationError as y };