@politty/zod 0.0.0

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