@kjanat/dreamcli 3.0.0 → 4.0.0-rc.1

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 (147) hide show
  1. package/CHANGELOG.md +967 -1
  2. package/README.md +9 -3
  3. package/dist/core/cli/builtins.d.mts +47 -0
  4. package/dist/core/cli/builtins.mjs +135 -0
  5. package/dist/core/cli/compiled.d.mts +29 -0
  6. package/dist/core/cli/compiled.mjs +76 -0
  7. package/dist/core/cli/dispatch.d.mts +9 -85
  8. package/dist/core/cli/help-links.d.mts +2 -14
  9. package/dist/core/cli/index.d.mts +282 -101
  10. package/dist/core/cli/index.mjs +497 -264
  11. package/dist/core/cli/planner.d.mts +13 -86
  12. package/dist/core/cli/planner.mjs +47 -30
  13. package/dist/core/cli/plugin.d.mts +1 -1
  14. package/dist/core/cli/propagate.mjs +1 -1
  15. package/dist/core/cli/reserved-flags.d.mts +1 -0
  16. package/dist/core/cli/reserved-flags.mjs +158 -0
  17. package/dist/core/cli/root-help.d.mts +1 -47
  18. package/dist/core/cli/root-help.mjs +37 -47
  19. package/dist/core/cli/root-output-flags.d.mts +1 -0
  20. package/dist/core/cli/root-output-flags.mjs +169 -0
  21. package/dist/core/cli/root-surface.d.mts +1 -68
  22. package/dist/core/cli/root-surface.mjs +2 -2
  23. package/dist/core/cli/runtime-preflight.d.mts +1 -199
  24. package/dist/core/cli/runtime-preflight.mjs +67 -17
  25. package/dist/core/completion/index.d.mts +2 -2
  26. package/dist/core/completion/shells/bash.d.mts +0 -1
  27. package/dist/core/completion/shells/bash.mjs +2 -1
  28. package/dist/core/completion/shells/fish.d.mts +0 -1
  29. package/dist/core/completion/shells/fish.mjs +2 -1
  30. package/dist/core/completion/shells/powershell.d.mts +0 -1
  31. package/dist/core/completion/shells/powershell.mjs +2 -1
  32. package/dist/core/completion/shells/shared.d.mts +3 -114
  33. package/dist/core/completion/shells/shared.mjs +9 -39
  34. package/dist/core/completion/shells/zsh.d.mts +0 -1
  35. package/dist/core/completion/shells/zsh.mjs +2 -1
  36. package/dist/core/config/index.d.mts +3 -3
  37. package/dist/core/config/index.mjs +2 -2
  38. package/dist/core/config/package-json.d.mts +2 -33
  39. package/dist/core/config/package-json.mjs +1 -34
  40. package/dist/core/errors/index.d.mts +7 -7
  41. package/dist/core/execution/index.d.mts +1 -48
  42. package/dist/core/execution/index.mjs +42 -27
  43. package/dist/core/help/ansi.d.mts +0 -11
  44. package/dist/core/help/index.d.mts +3 -35
  45. package/dist/core/help/index.mjs +29 -6
  46. package/dist/core/help/theme.d.mts +1 -21
  47. package/dist/core/json-schema/index.d.mts +279 -10
  48. package/dist/core/json-schema/index.mjs +482 -237
  49. package/dist/core/json-schema/meta-descriptions.generated.d.mts +79 -7
  50. package/dist/core/json-schema/meta-descriptions.generated.mjs +40 -6
  51. package/dist/core/output/activity.d.mts +1 -193
  52. package/dist/core/output/activity.mjs +1 -1
  53. package/dist/core/output/bind.d.mts +1 -37
  54. package/dist/core/output/contracts.d.mts +7 -13
  55. package/dist/core/output/contracts.mjs +1 -1
  56. package/dist/core/output/display-value.d.mts +1 -19
  57. package/dist/core/output/index.d.mts +5 -187
  58. package/dist/core/output/index.mjs +44 -9
  59. package/dist/core/output/renderers.d.mts +1 -45
  60. package/dist/core/output/writer.d.mts +0 -1
  61. package/dist/core/parse/index.d.mts +27 -5
  62. package/dist/core/parse/index.mjs +350 -227
  63. package/dist/core/parse/occurrences.d.mts +89 -0
  64. package/dist/core/parse/occurrences.mjs +114 -0
  65. package/dist/core/prompt/index.d.mts +3 -3
  66. package/dist/core/read-flags/index.d.mts +150 -0
  67. package/dist/core/read-flags/index.mjs +217 -0
  68. package/dist/core/resolve/args.d.mts +35 -4
  69. package/dist/core/resolve/args.mjs +132 -55
  70. package/dist/core/resolve/coerce.d.mts +66 -9
  71. package/dist/core/resolve/coerce.mjs +834 -270
  72. package/dist/core/resolve/config.d.mts +1 -10
  73. package/dist/core/resolve/contracts.d.mts +67 -44
  74. package/dist/core/resolve/errors.mjs +29 -21
  75. package/dist/core/resolve/flags.d.mts +36 -9
  76. package/dist/core/resolve/flags.mjs +129 -151
  77. package/dist/core/resolve/index.d.mts +8 -6
  78. package/dist/core/resolve/index.mjs +51 -18
  79. package/dist/core/resolve/path-checks.d.mts +47 -0
  80. package/dist/core/resolve/path-checks.mjs +102 -0
  81. package/dist/core/resolve/redaction.d.mts +12 -0
  82. package/dist/core/resolve/redaction.mjs +14 -0
  83. package/dist/core/resolve/stages.d.mts +85 -0
  84. package/dist/core/resolve/stages.mjs +170 -0
  85. package/dist/core/resolve/standard.d.mts +1 -24
  86. package/dist/core/resolve/standard.mjs +141 -43
  87. package/dist/core/schema/activity.d.mts +16 -16
  88. package/dist/core/schema/arg.d.mts +849 -71
  89. package/dist/core/schema/arg.mjs +727 -54
  90. package/dist/core/schema/brand.d.mts +17 -0
  91. package/dist/core/schema/cardinality.d.mts +301 -0
  92. package/dist/core/schema/cardinality.mjs +514 -0
  93. package/dist/core/schema/command.d.mts +181 -112
  94. package/dist/core/schema/command.mjs +305 -42
  95. package/dist/core/schema/flag.d.mts +515 -173
  96. package/dist/core/schema/flag.mjs +576 -78
  97. package/dist/core/schema/index.d.mts +11 -8
  98. package/dist/core/schema/index.mjs +10 -0
  99. package/dist/core/schema/middleware.d.mts +15 -12
  100. package/dist/core/schema/number-constraints.d.mts +5 -5
  101. package/dist/core/schema/prompt.d.mts +4 -4
  102. package/dist/core/schema/provenance.d.mts +99 -0
  103. package/dist/core/schema/provenance.mjs +28 -0
  104. package/dist/core/schema/run.d.mts +21 -60
  105. package/dist/core/schema/source.d.mts +179 -0
  106. package/dist/core/schema/source.mjs +206 -0
  107. package/dist/core/schema/standard.d.mts +12 -19
  108. package/dist/core/schema/stdin.d.mts +87 -0
  109. package/dist/core/schema/stdin.mjs +91 -0
  110. package/dist/core/schema/string-constraints.d.mts +16 -5
  111. package/dist/core/schema/string-constraints.mjs +18 -1
  112. package/dist/core/schema/value-parsers.d.mts +81 -9
  113. package/dist/core/schema/value-parsers.mjs +19 -1
  114. package/dist/core/schema/value.d.mts +242 -0
  115. package/dist/core/schema/value.mjs +573 -0
  116. package/dist/core/testkit/index.d.mts +28 -3
  117. package/dist/core/testkit/index.mjs +40 -26
  118. package/dist/index.d.mts +21 -16
  119. package/dist/index.mjs +10 -6
  120. package/dist/runtime/adapter.d.mts +3 -3
  121. package/dist/runtime/deno.d.mts +3 -3
  122. package/dist/runtime/detect.d.mts +2 -2
  123. package/dist/runtime/node.d.mts +3 -3
  124. package/dist/runtime/paths.d.mts +1 -31
  125. package/dist/runtime.d.mts +4 -4
  126. package/dist/strings.d.mts +1 -16
  127. package/dist/testkit.d.mts +2 -2
  128. package/dist/testkit.mjs +1 -1
  129. package/dist/version.d.mts +0 -13
  130. package/dist/version.mjs +2 -2
  131. package/dreamcli.schema.json +368 -78
  132. package/examples/interactive.ts +6 -5
  133. package/package.json +10 -9
  134. package/skills/cli-creation/SKILL.md +196 -0
  135. package/skills/cli-creation/agents/openai.yaml +4 -0
  136. package/skills/cli-creation/assets/templates/multi-command.bun-test.ts.tpl +20 -0
  137. package/skills/cli-creation/assets/templates/multi-command.test.ts.tpl +20 -0
  138. package/skills/cli-creation/assets/templates/multi-command.ts.tpl +89 -0
  139. package/skills/cli-creation/assets/templates/single-command.bun-test.ts.tpl +29 -0
  140. package/skills/cli-creation/assets/templates/single-command.test.ts.tpl +29 -0
  141. package/skills/cli-creation/assets/templates/single-command.ts.tpl +47 -0
  142. package/skills/cli-creation/references/consumer-workflow.md +65 -0
  143. package/skills/cli-creation/references/pattern-cookbook.md +451 -0
  144. package/skills/cli-creation/references/runtime-notes.md +29 -0
  145. package/skills/cli-creation/scripts/scaffold_cli.py +360 -0
  146. package/dist/core/resolve/property.d.mts +0 -51
  147. package/dist/core/resolve/property.mjs +0 -53
@@ -1,336 +1,900 @@
1
1
  import { ValidationError } from "../errors/index.mjs";
2
- import { describeNumberConstraintViolation, validateNumberConstraints } from "../schema/number-constraints.mjs";
3
- import { describeStringConstraintViolation, validateStringConstraints } from "../schema/string-constraints.mjs";
4
- import { toSharedArgPropertySchema, toSharedFlagPropertySchema } from "./property.mjs";
2
+ import { describeNumberConstraintViolation } from "../schema/number-constraints.mjs";
3
+ import { describeStringConstraintViolation, stringConstraintDetails } from "../schema/string-constraints.mjs";
4
+ import { argValueSchema, decodeValue, flagValueSchema, keepsStdinTerminator, stripTerminator } from "../schema/value.mjs";
5
+ import { argCardinality, flagCardinality, foldEntries, isCollection, splitEntriesText, splitManyText } from "../schema/cardinality.mjs";
6
+ import { stdinReadsOnDash } from "../schema/stdin.mjs";
7
+ import { entryPairsOf, liftOccurrences, occurrenceValue, readAggregated } from "../parse/occurrences.mjs";
8
+ import { REDACTED } from "./redaction.mjs";
5
9
  //#region src/core/resolve/coerce.ts
6
10
  function sourceLabel(source) {
7
11
  switch (source.kind) {
12
+ case "stdin": return "from stdin";
8
13
  case "env": return `from env ${source.envVar}`;
9
14
  case "config": return `from config ${source.configPath}`;
10
15
  case "prompt": return "from prompt";
11
16
  }
12
17
  }
18
+ /**
19
+ * How a diagnostic identifies the stage that produced the value.
20
+ *
21
+ * `source` names the stage on every one of them, which is what separates a
22
+ * failure to read a value from a source from a missing required input that
23
+ * merely declares one.
24
+ */
13
25
  function sourceDetails(source) {
14
26
  switch (source.kind) {
15
- case "env": return { envVar: source.envVar };
16
- case "config": return { configPath: source.configPath };
27
+ case "stdin": return { source: "stdin" };
28
+ case "env": return {
29
+ source: "env",
30
+ envVar: source.envVar
31
+ };
32
+ case "config": return {
33
+ source: "config",
34
+ configPath: source.configPath
35
+ };
17
36
  case "prompt": return { source: "prompt" };
18
37
  }
19
38
  }
20
- function coercionError(flagName, source, code, expected, raw, messageSuffix, suggest, extraDetails) {
39
+ /** Where the caller must change the value, phrased for the source that produced it. */
40
+ function suggestBySource(source, parts) {
41
+ switch (source.kind) {
42
+ case "stdin": return parts.stdin;
43
+ case "env": return parts.env(source.envVar);
44
+ case "config": return parts.config(source.configPath);
45
+ case "prompt": return parts.prompt;
46
+ }
47
+ }
48
+ function coercionError(flagName, source, code, expected, messageSuffix, suggest, extraDetails) {
49
+ return new ValidationError(`${messageSuffix} ${sourceLabel(source)} for flag --${flagName}`, {
50
+ code,
51
+ details: {
52
+ flag: flagName,
53
+ ...sourceDetails(source),
54
+ expected,
55
+ ...extraDetails
56
+ },
57
+ suggest
58
+ });
59
+ }
60
+ /**
61
+ * Which source a binding's diagnostics name.
62
+ *
63
+ * @param binding - The stage that produced the value.
64
+ * @returns The diagnostic context for that stage.
65
+ */
66
+ function diagnosticSourceOf(binding) {
67
+ switch (binding.stage) {
68
+ case "stdin": return { kind: "stdin" };
69
+ case "env": return {
70
+ kind: "env",
71
+ envVar: binding.envVar
72
+ };
73
+ case "config": return {
74
+ kind: "config",
75
+ configPath: binding.configPath
76
+ };
77
+ case "prompt": return { kind: "prompt" };
78
+ }
79
+ }
80
+ /**
81
+ * Coerce a raw value from stdin/env/config/prompt into what a flag declares.
82
+ *
83
+ * The cardinality axis decides how many values the source carries and how they
84
+ * combine; the value axis decides what each one means; the binding decides how
85
+ * the source's text splits and whether a single value is trimmed.
86
+ */
87
+ function coerceValue(flagName, binding, raw, schema) {
88
+ const source = diagnosticSourceOf(binding);
89
+ const cardinality = flagCardinality(schema);
90
+ if (cardinality.kind === "count") return coerceCount(flagName, source, raw);
91
+ if (cardinality.kind === "one") {
92
+ const value = flagValueSchema(schema);
93
+ return coerceValueSchema(flagName, source, trimmedStdinValue(binding, raw, value), value);
94
+ }
95
+ return coerceCollection(cardinality, source, binding.split, raw, (element) => coerceValueSchema(flagName, source, element, flagValueSchema(schema)), flagCollectionErrors(flagName, source), flagAggregationErrors(flagName));
96
+ }
97
+ /**
98
+ * Apply `.stdin({ trim: true })` to a single value read off the stream.
99
+ *
100
+ * Only the string codec keeps the terminator a pipe appends, and only a single
101
+ * value carries one: a collection's terminators frame its elements and the
102
+ * split policy consumes them. Every other codec drops it while decoding, so
103
+ * trimming there would take a second terminator off the value.
104
+ *
105
+ * @param binding - The stage that produced the value.
106
+ * @param raw - The value that stage produced.
107
+ * @param value - The value axis about to decode it.
108
+ * @returns The value to decode.
109
+ */
110
+ function trimmedStdinValue(binding, raw, value) {
111
+ if (binding.stage !== "stdin" || !binding.trim || typeof raw !== "string") return raw;
112
+ return keepsStdinTerminator(value) ? stripTerminator(raw) : raw;
113
+ }
114
+ /** Read a raw value as a non-negative integer occurrence count. */
115
+ function coerceCount(flagName, source, raw) {
116
+ const value = typeof raw === "string" ? raw.trim() === "" ? NaN : Number(raw) : raw;
117
+ if (typeof value === "number" && Number.isInteger(value) && value >= 0) return {
118
+ ok: true,
119
+ value
120
+ };
21
121
  return {
22
122
  ok: false,
23
- error: new ValidationError(`${messageSuffix} ${sourceLabel(source)} for flag --${flagName}`, {
24
- code,
25
- details: {
26
- flag: flagName,
27
- ...sourceDetails(source),
28
- value: raw,
29
- expected,
30
- ...extraDetails
31
- },
32
- suggest
33
- })
123
+ error: coercionError(flagName, source, "TYPE_MISMATCH", "count", `Invalid count value '${REDACTED}'`, suggestBySource(source, {
124
+ stdin: `Pipe a non-negative integer to stdin for --${flagName}`,
125
+ env: (envVar) => `Set ${envVar} to a non-negative integer`,
126
+ config: (configPath) => `Set ${configPath} to a non-negative integer in your config`,
127
+ prompt: `Enter a non-negative integer for --${flagName}`
128
+ }))
129
+ };
130
+ }
131
+ /**
132
+ * The clause naming where a value came from, empty for the tokens the user
133
+ * typed.
134
+ *
135
+ * @param source - The source that carried the value.
136
+ * @returns A trailing-spaced clause, or `''` for the CLI.
137
+ */
138
+ function sourceClause(source) {
139
+ return source.kind === "cli" ? "" : `${sourceLabel(source)} `;
140
+ }
141
+ /** The identification fields a source contributes to an aggregation error. */
142
+ function aggregationSourceDetails(source) {
143
+ return source.kind === "cli" ? {} : sourceDetails(source);
144
+ }
145
+ /**
146
+ * How a duplicate key is quoted, and whether `details` carries it.
147
+ *
148
+ * A key is half of a `KEY=VALUE` pair, so it is value text from whatever source
149
+ * carried it. A token the user typed is quoted like every other argv value; a
150
+ * key that arrived from stdin, the environment, a config file, or a prompt takes
151
+ * the same redaction the pair itself takes when it fails to split.
152
+ *
153
+ * @param source - The source that carried the repeating pair.
154
+ * @param key - The key that repeated.
155
+ * @returns The quoted key for the message, and the detail fields it contributes.
156
+ */
157
+ function duplicateKeyReport(source, key) {
158
+ return source.kind === "cli" ? {
159
+ quoted: `'${key}'`,
160
+ details: { key }
161
+ } : {
162
+ quoted: `'${REDACTED}'`,
163
+ details: {}
34
164
  };
35
165
  }
166
+ /** What a duplicate-key suggestion asks the caller to change. */
167
+ function duplicateKeySubject(source, key) {
168
+ return source.kind === "cli" ? `'${key}'` : "the repeated key";
169
+ }
36
170
  /**
37
- * Apply numeric constraints to an already-parsed number. Shares the single
38
- * {@link validateNumberConstraints} check used by the parse path, so the two
39
- * boundaries cannot drift. On violation, returns a `CONSTRAINT_VIOLATED`
40
- * failure; the human-readable reason is also surfaced in `details.constraint`
41
- * (the violation kind) and the message suffix.
171
+ * Read a source value as a collection and aggregate it.
172
+ *
173
+ * @param cardinality - The `many` or `entries` axis being filled.
174
+ * @param source - Which stage produced the value.
175
+ * @param policy - How that stage's text decodes into elements.
176
+ * @param raw - The value that stage produced.
177
+ * @param decodeElement - Decodes one element through the value axis.
178
+ * @param errors - Words a read fault for the surface being resolved.
179
+ * @param aggregationErrors - Words an aggregation fault for the same surface.
180
+ * @returns The aggregated array or record, or the first failure.
42
181
  */
43
- function finalizeNumber(flagName, source, raw, value, constraints) {
44
- const violation = validateNumberConstraints(value, constraints);
45
- if (violation === void 0) return {
182
+ function coerceCollection(cardinality, source, policy, raw, decodeElement, errors, aggregationErrors) {
183
+ if (cardinality.kind === "many") {
184
+ const parts = readManyParts(source, raw, policy);
185
+ if (!parts.ok) return {
186
+ ok: false,
187
+ error: errors(parts.fault)
188
+ };
189
+ const coerced = [];
190
+ for (const part of parts.parts) {
191
+ const result = decodeElement(part);
192
+ if (!result.ok) return result;
193
+ coerced.push(result.value);
194
+ }
195
+ return {
196
+ ok: true,
197
+ value: coerced
198
+ };
199
+ }
200
+ const pairs = readEntryPairs(raw, policy);
201
+ if (!pairs.ok) return {
202
+ ok: false,
203
+ error: errors(pairs.fault)
204
+ };
205
+ const coerced = [];
206
+ for (const [key, value] of pairs.pairs) {
207
+ const result = decodeElement(value);
208
+ if (!result.ok) return result;
209
+ coerced.push([key, result.value]);
210
+ }
211
+ const folded = foldEntries(coerced, cardinality.duplicateKeys);
212
+ if (!folded.ok) return {
213
+ ok: false,
214
+ error: aggregationErrors({
215
+ kind: "duplicate-key",
216
+ key: folded.duplicateKey
217
+ }, source)
218
+ };
219
+ return {
46
220
  ok: true,
47
- value
221
+ value: folded.value
222
+ };
223
+ }
224
+ /** Turn a split failure into the fault the surface words. */
225
+ function splitFault(failure) {
226
+ switch (failure.kind) {
227
+ case "json": return {
228
+ kind: "json",
229
+ error: failure.error
230
+ };
231
+ case "json-shape": return {
232
+ kind: "json-shape",
233
+ expected: failure.expected
234
+ };
235
+ case "pair": return {
236
+ kind: "pair",
237
+ segment: failure.raw
238
+ };
239
+ }
240
+ }
241
+ /** Read the elements a source carries for a `many` collection. */
242
+ function readManyParts(source, raw, policy) {
243
+ if (Array.isArray(raw)) return {
244
+ ok: true,
245
+ parts: raw
246
+ };
247
+ if (typeof raw !== "string") return {
248
+ ok: false,
249
+ fault: {
250
+ kind: "shape",
251
+ expected: "array"
252
+ }
253
+ };
254
+ const split = splitManyText(policy, raw);
255
+ if (!split.ok) return {
256
+ ok: false,
257
+ fault: splitFault(split.failure)
48
258
  };
49
- const reason = describeNumberConstraintViolation(violation);
50
259
  return {
260
+ ok: true,
261
+ parts: source.kind === "prompt" ? split.parts.map(trimStringPart) : split.parts
262
+ };
263
+ }
264
+ /** Read the pairs a source carries for an `entries` collection. */
265
+ function readEntryPairs(raw, policy) {
266
+ if (isPairList(raw)) return {
267
+ ok: true,
268
+ pairs: raw
269
+ };
270
+ if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) return {
271
+ ok: true,
272
+ pairs: Object.entries(raw)
273
+ };
274
+ if (typeof raw !== "string") return {
51
275
  ok: false,
52
- error: new ValidationError(`Invalid number value '${String(raw)}' ${sourceLabel(source)} for flag --${flagName}: ${reason}`, {
276
+ fault: {
277
+ kind: "shape",
278
+ expected: "object"
279
+ }
280
+ };
281
+ const split = splitEntriesText(policy, raw);
282
+ if (!split.ok) return {
283
+ ok: false,
284
+ fault: splitFault(split.failure)
285
+ };
286
+ return {
287
+ ok: true,
288
+ pairs: split.parts
289
+ };
290
+ }
291
+ /** Whether a value is an ordered list of key/value pairs. */
292
+ function isPairList(value) {
293
+ return Array.isArray(value) && value.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string");
294
+ }
295
+ /** Trim a prompt-sourced element, leaving a non-string element untouched. */
296
+ function trimStringPart(part) {
297
+ return typeof part === "string" ? part.trim() : part;
298
+ }
299
+ /** Word a collection fault for a flag, without echoing the value. */
300
+ function flagCollectionErrors(flagName, source) {
301
+ return (fault) => {
302
+ switch (fault.kind) {
303
+ case "shape": {
304
+ const collectionLabel = fault.expected === "array" ? "values" : "KEY=VALUE pairs";
305
+ return coercionError(flagName, source, "TYPE_MISMATCH", fault.expected, `Invalid ${fault.expected} value`, suggestBySource(source, {
306
+ stdin: `Pipe ${collectionLabel} to stdin for --${flagName}`,
307
+ env: (envVar) => `Set ${envVar} to comma-separated ${collectionLabel}`,
308
+ config: (configPath) => `Set ${configPath} to an ${fault.expected} in your config`,
309
+ prompt: `Provide valid ${collectionLabel} for --${flagName}`
310
+ }));
311
+ }
312
+ case "pair": return coercionError(flagName, source, "TYPE_MISMATCH", "key=value", `Invalid key-value pair '${REDACTED}'`, suggestBySource(source, {
313
+ stdin: `Pipe KEY=VALUE pairs to stdin for --${flagName}`,
314
+ env: (envVar) => `Set ${envVar} to comma-separated KEY=VALUE pairs`,
315
+ config: (configPath) => `Set ${configPath} to an object with string values`,
316
+ prompt: `Use KEY=VALUE for --${flagName}`
317
+ }));
318
+ case "json": return coercionError(flagName, source, "TYPE_MISMATCH", "json", "Invalid JSON value", `Provide valid JSON for --${flagName}`);
319
+ case "json-shape": return new ValidationError(`Invalid JSON value ${sourceLabel(source)} for flag --${flagName}, expected an ${fault.expected}`, {
320
+ code: "TYPE_MISMATCH",
321
+ details: {
322
+ flag: flagName,
323
+ ...sourceDetails(source),
324
+ expected: fault.expected
325
+ },
326
+ suggest: `Provide a JSON ${fault.expected} for --${flagName}`
327
+ });
328
+ }
329
+ };
330
+ }
331
+ /** Word an aggregation fault for a flag, naming the source that carried it. */
332
+ function flagAggregationErrors(flagName) {
333
+ return (fault, source) => {
334
+ if (fault.kind === "dash-without-stdin") return new ValidationError(`No piped stdin for the '-' occurrence of flag --${flagName}`, {
335
+ code: "MISSING_STDIN",
336
+ details: {
337
+ flag: flagName,
338
+ source: "stdin"
339
+ },
340
+ suggest: `Pipe a value to stdin, or drop the '-' occurrence of --${flagName}`
341
+ });
342
+ if (fault.kind === "shape") {
343
+ const collectionLabel = fault.expected === "array" ? "values" : "KEY=VALUE pairs";
344
+ return new ValidationError(`Invalid ${fault.expected} value ${sourceClause(source)}for flag --${flagName}`, {
345
+ code: "TYPE_MISMATCH",
346
+ details: {
347
+ flag: flagName,
348
+ ...aggregationSourceDetails(source),
349
+ expected: fault.expected
350
+ },
351
+ suggest: `Provide ${collectionLabel} for --${flagName}`
352
+ });
353
+ }
354
+ const report = duplicateKeyReport(source, fault.key);
355
+ return new ValidationError(`Duplicate key ${report.quoted} ${sourceClause(source)}for flag --${flagName}`, {
53
356
  code: "CONSTRAINT_VIOLATED",
54
357
  details: {
55
358
  flag: flagName,
56
- ...sourceDetails(source),
57
- value: raw,
58
- expected: "number",
59
- constraint: violation.kind,
60
- ..."bound" in violation ? { bound: violation.bound } : {}
359
+ ...aggregationSourceDetails(source),
360
+ ...report.details
61
361
  },
62
- suggest: source.kind === "env" ? `Set ${source.envVar} to a valid number` : source.kind === "config" ? `Set ${source.configPath} to a valid number in your config` : `Enter a valid number for --${flagName}`
63
- })
362
+ suggest: `Set ${duplicateKeySubject(source, fault.key)} once for --${flagName}`
363
+ });
364
+ };
365
+ }
366
+ /** Word a collection fault for a positional, without echoing the value. */
367
+ function argCollectionErrors(argName, source) {
368
+ return (fault) => {
369
+ switch (fault.kind) {
370
+ case "shape": return new ValidationError(`Invalid ${fault.expected} value ${argSourceLabel(source)} for argument <${argName}>`, {
371
+ code: "TYPE_MISMATCH",
372
+ details: {
373
+ arg: argName,
374
+ ...argSourceDetails(source),
375
+ expected: fault.expected
376
+ },
377
+ suggest: fault.expected === "object" ? `Use KEY=VALUE for <${argName}>` : `Provide values for <${argName}>`
378
+ });
379
+ case "pair": return new ValidationError(`Invalid key-value pair '${REDACTED}' ${argSourceLabel(source)} for argument <${argName}>`, {
380
+ code: "TYPE_MISMATCH",
381
+ details: {
382
+ arg: argName,
383
+ ...argSourceDetails(source),
384
+ expected: "key=value"
385
+ },
386
+ suggest: `Use KEY=VALUE for <${argName}>`
387
+ });
388
+ case "json": return new ValidationError(`Invalid JSON value ${argSourceLabel(source)} for argument <${argName}>`, {
389
+ code: "TYPE_MISMATCH",
390
+ details: {
391
+ arg: argName,
392
+ ...argSourceDetails(source),
393
+ expected: "json"
394
+ },
395
+ suggest: `Provide valid JSON for <${argName}>`
396
+ });
397
+ case "json-shape": return new ValidationError(`Invalid JSON value ${argSourceLabel(source)} for argument <${argName}>, expected an ${fault.expected}`, {
398
+ code: "TYPE_MISMATCH",
399
+ details: {
400
+ arg: argName,
401
+ ...argSourceDetails(source),
402
+ expected: fault.expected
403
+ },
404
+ suggest: `Provide a JSON ${fault.expected} for <${argName}>`
405
+ });
406
+ }
407
+ };
408
+ }
409
+ /** Word an aggregation fault for a positional, naming the source that carried it. */
410
+ function argAggregationErrors(argName) {
411
+ return (fault, source) => {
412
+ if (fault.kind === "dash-without-stdin") return new ValidationError(`No piped stdin for the '-' occurrence of argument <${argName}>`, {
413
+ code: "MISSING_STDIN",
414
+ details: {
415
+ arg: argName,
416
+ source: "stdin"
417
+ },
418
+ suggest: `Pipe a value to stdin, or drop the '-' from <${argName}>`
419
+ });
420
+ if (fault.kind === "shape") return new ValidationError(`Invalid ${fault.expected} value ${sourceClause(source)}for argument <${argName}>`, {
421
+ code: "TYPE_MISMATCH",
422
+ details: {
423
+ arg: argName,
424
+ ...aggregationSourceDetails(source),
425
+ expected: fault.expected
426
+ },
427
+ suggest: `Provide KEY=VALUE pairs for <${argName}>`
428
+ });
429
+ const report = duplicateKeyReport(source, fault.key);
430
+ return new ValidationError(`Duplicate key ${report.quoted} ${sourceClause(source)}for argument <${argName}>`, {
431
+ code: "CONSTRAINT_VIOLATED",
432
+ details: {
433
+ arg: argName,
434
+ ...aggregationSourceDetails(source),
435
+ ...report.details
436
+ },
437
+ suggest: `Set ${duplicateKeySubject(source, fault.key)} once for <${argName}>`
438
+ });
64
439
  };
65
440
  }
66
441
  /**
67
- * Apply string constraints to an already-string value. Shares the single
68
- * {@link validateStringConstraints} check used by the parse path, so the two
69
- * boundaries cannot drift. On violation, returns a `CONSTRAINT_VIOLATED`
70
- * failure mirroring {@link finalizeNumber}.
442
+ * Decode a raw env/config/prompt value through the shared value layer and name
443
+ * the flag or arg that carried it on failure.
444
+ *
445
+ * The value layer decides what the value means; every message, code, detail
446
+ * field, and suggestion below belongs to this surface.
71
447
  */
72
- function finalizeString(flagName, source, value, constraints) {
73
- const violation = validateStringConstraints(value, constraints);
74
- if (violation === void 0) return {
448
+ function coerceValueSchema(name, source, raw, value) {
449
+ const decoded = decodeValue(value, raw, valueInputOf(source));
450
+ if (decoded.ok) return {
75
451
  ok: true,
76
- value
452
+ value: decoded.value
77
453
  };
78
- const reason = describeStringConstraintViolation(violation);
79
454
  return {
80
455
  ok: false,
81
- error: new ValidationError(`Invalid value '${value}' ${sourceLabel(source)} for flag --${flagName}: ${reason}`, {
456
+ error: valueCoercionError(name, source, decoded.failure)
457
+ };
458
+ }
459
+ /**
460
+ * Which value-layer input surface a resolver source speaks for.
461
+ *
462
+ * The stage names and the value-layer input names are the same set by
463
+ * construction, so this is the identity.
464
+ */
465
+ function valueInputOf(source) {
466
+ return source.kind;
467
+ }
468
+ /** Turn a value-layer failure into the resolver's validation error. */
469
+ function valueCoercionError(name, source, failure) {
470
+ switch (failure.kind) {
471
+ case "type": return typeCoercionError(name, source, failure.expected);
472
+ case "enum": {
473
+ const allowed = failure.enumValues ?? [];
474
+ return new ValidationError(`Invalid value '${REDACTED}' ${sourceLabel(source)} for flag --${name}. Allowed: ${allowed.join(", ")}`, {
475
+ code: "INVALID_ENUM",
476
+ details: {
477
+ flag: name,
478
+ ...sourceDetails(source),
479
+ allowed
480
+ },
481
+ suggest: suggestBySource(source, {
482
+ stdin: `Pipe one of: ${allowed.join(", ")}`,
483
+ env: (envVar) => `Set ${envVar} to one of: ${allowed.join(", ")}`,
484
+ config: (configPath) => `Set ${configPath} to one of: ${allowed.join(", ")}`,
485
+ prompt: `Select one of: ${allowed.join(", ")}`
486
+ })
487
+ });
488
+ }
489
+ case "string-constraint": return new ValidationError(`Invalid value '${REDACTED}' ${sourceLabel(source)} for flag --${name}: ${describeStringConstraintViolation(failure.violation)}`, {
82
490
  code: "CONSTRAINT_VIOLATED",
83
491
  details: {
84
- flag: flagName,
492
+ flag: name,
85
493
  ...sourceDetails(source),
86
- value,
87
494
  expected: "string",
88
- constraint: violation.kind,
89
- ..."bound" in violation ? { bound: violation.bound } : {},
90
- ..."pattern" in violation ? { pattern: violation.pattern } : {}
495
+ ...stringConstraintDetails(failure.violation)
91
496
  },
92
- suggest: source.kind === "env" ? `Set ${source.envVar} to a valid string` : source.kind === "config" ? `Set ${source.configPath} to a valid string in your config` : `Enter a valid value for --${flagName}`
93
- })
94
- };
95
- }
96
- /** Coerce a raw value from env/config/prompt into the type declared by a flag schema. */
97
- function coerceValue(flagName, source, raw, schema) {
98
- const sharedSchema = toSharedFlagPropertySchema(schema);
99
- if (sharedSchema !== void 0) return coerceSharedPropertyValue(flagName, source, raw, sharedSchema);
100
- switch (schema.kind) {
101
- case "boolean":
102
- if (typeof raw === "boolean") return {
103
- ok: true,
104
- value: raw
105
- };
106
- if (typeof raw === "string") {
107
- const lower = raw.toLowerCase();
108
- if (lower === "true" || lower === "1" || lower === "yes" || source.kind === "prompt" && lower === "y") return {
109
- ok: true,
110
- value: true
111
- };
112
- if (lower === "false" || lower === "0" || lower === "no" || lower === "" || source.kind === "prompt" && lower === "n") return {
113
- ok: true,
114
- value: false
115
- };
116
- }
117
- return coercionError(flagName, source, "TYPE_MISMATCH", "boolean", raw, typeof raw === "string" ? `Invalid boolean value '${raw}'` : "Invalid boolean value", source.kind === "env" ? `Set ${source.envVar} to true/false, 1/0, or yes/no` : source.kind === "config" ? `Set ${source.configPath} to true or false in your config` : `Answer yes or no for --${flagName}`);
118
- case "array":
119
- if (Array.isArray(raw)) {
120
- if (schema.elementSchema) {
121
- const coerced = [];
122
- for (const element of raw) {
123
- const result = coerceValue(flagName, source, element, schema.elementSchema);
124
- if (!result.ok) return result;
125
- coerced.push(result.value);
126
- }
127
- return {
128
- ok: true,
129
- value: coerced
130
- };
131
- }
132
- return {
133
- ok: true,
134
- value: raw
135
- };
136
- }
137
- if (typeof raw === "string") {
138
- if (raw === "") return {
139
- ok: true,
140
- value: []
141
- };
142
- const parts = raw.split(schema.separator ?? ",").filter((part) => part.length > 0);
143
- if (schema.elementSchema) {
144
- const coerced = [];
145
- for (const part of parts) {
146
- const result = coerceValue(flagName, source, source.kind === "prompt" ? part.trim() : part, schema.elementSchema);
147
- if (!result.ok) return result;
148
- coerced.push(result.value);
149
- }
150
- return {
151
- ok: true,
152
- value: coerced
153
- };
154
- }
155
- return {
156
- ok: true,
157
- value: source.kind === "prompt" ? parts.map((part) => part.trim()) : parts
158
- };
159
- }
160
- return coercionError(flagName, source, "TYPE_MISMATCH", "array", raw, "Invalid array value", source.kind === "env" ? `Set ${source.envVar} to comma-separated values` : source.kind === "config" ? `Set ${source.configPath} to an array in your config` : `Provide valid values for --${flagName}`);
161
- case "count": {
162
- const value = typeof raw === "string" ? raw.trim() === "" ? NaN : Number(raw) : raw;
163
- if (typeof value === "number" && Number.isInteger(value) && value >= 0) return {
164
- ok: true,
165
- value
166
- };
167
- return coercionError(flagName, source, "TYPE_MISMATCH", "count", raw, typeof raw === "string" ? `Invalid count value '${raw}'` : "Invalid count value", source.kind === "env" ? `Set ${source.envVar} to a non-negative integer` : source.kind === "config" ? `Set ${source.configPath} to a non-negative integer in your config` : `Enter a non-negative integer for --${flagName}`);
168
- }
169
- case "keyValue":
170
- if (isStringRecord(raw)) return {
171
- ok: true,
172
- value: { ...raw }
173
- };
174
- if (typeof raw === "string") {
175
- if (raw === "") return {
176
- ok: true,
177
- value: {}
178
- };
179
- const pairs = [];
180
- for (const pair of raw.split(",").filter((segment) => segment.length > 0)) {
181
- const eq = pair.indexOf("=");
182
- if (eq <= 0) return coercionError(flagName, source, "TYPE_MISMATCH", "key=value", raw, `Invalid key-value pair '${pair}'`, source.kind === "env" ? `Set ${source.envVar} to comma-separated KEY=VALUE pairs` : source.kind === "config" ? `Set ${source.configPath} to an object with string values` : `Use KEY=VALUE for --${flagName}`);
183
- pairs.push([pair.slice(0, eq), pair.slice(eq + 1)]);
184
- }
185
- return {
186
- ok: true,
187
- value: Object.fromEntries(pairs)
188
- };
189
- }
190
- return coercionError(flagName, source, "TYPE_MISMATCH", "key=value", raw, "Invalid key-value value", source.kind === "env" ? `Set ${source.envVar} to comma-separated KEY=VALUE pairs` : source.kind === "config" ? `Set ${source.configPath} to an object with string values` : `Use KEY=VALUE for --${flagName}`);
191
- }
192
- throw new Error(`Unreachable flag coercion kind: ${schema.kind}`);
193
- }
194
- /** Narrow config-sourced objects to plain string-valued records. */
195
- function isStringRecord(value) {
196
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
197
- return Object.values(value).every((entry) => typeof entry === "string");
198
- }
199
- function coerceSharedPropertyValue(flagName, source, raw, schema) {
200
- switch (schema.kind) {
201
- case "string":
202
- if (typeof raw === "string") return finalizeString(flagName, source, raw, schema.stringConstraints);
203
- if (source.kind === "prompt") return finalizeString(flagName, source, String(raw), schema.stringConstraints);
204
- if (source.kind === "config" && (typeof raw === "number" || typeof raw === "boolean")) return finalizeString(flagName, source, String(raw), schema.stringConstraints);
205
- return coercionError(flagName, source, "TYPE_MISMATCH", "string", raw, "Invalid string value", source.kind === "config" ? `Set ${source.configPath} to a string in your config` : `Enter a valid string for --${flagName}`);
206
- case "number":
207
- if (typeof raw === "number") {
208
- if (Number.isNaN(raw)) return coercionError(flagName, source, "TYPE_MISMATCH", "number", raw, "Invalid number value NaN", source.kind === "env" ? `Set ${source.envVar} to a valid number` : source.kind === "config" ? `Set ${source.configPath} to a valid number in your config` : `Enter a valid number for --${flagName}`);
209
- return finalizeNumber(flagName, source, raw, raw, schema.numberConstraints);
210
- }
211
- if (typeof raw === "string") {
212
- const value = Number(raw);
213
- if (!Number.isNaN(value)) return finalizeNumber(flagName, source, raw, value, schema.numberConstraints);
214
- }
215
- return coercionError(flagName, source, "TYPE_MISMATCH", "number", raw, typeof raw === "string" ? `Invalid number value '${raw}'` : "Invalid number value", source.kind === "env" ? `Set ${source.envVar} to a valid number` : source.kind === "config" ? `Set ${source.configPath} to a valid number in your config` : `Enter a valid number for --${flagName}`);
216
- case "enum": {
217
- const allowed = schema.enumValues ?? [];
218
- if (typeof raw === "string" && allowed.includes(raw)) return {
219
- ok: true,
220
- value: raw
221
- };
222
- return {
223
- ok: false,
224
- error: new ValidationError(`Invalid value '${String(raw)}' ${sourceLabel(source)} for flag --${flagName}. Allowed: ${allowed.join(", ")}`, {
225
- code: "INVALID_ENUM",
226
- details: {
227
- flag: flagName,
228
- ...sourceDetails(source),
229
- value: raw,
230
- allowed
231
- },
232
- suggest: source.kind === "env" ? `Set ${source.envVar} to one of: ${allowed.join(", ")}` : source.kind === "config" ? `Set ${source.configPath} to one of: ${allowed.join(", ")}` : `Select one of: ${allowed.join(", ")}`
497
+ suggest: suggestBySource(source, {
498
+ stdin: `Pipe a valid string to stdin for --${name}`,
499
+ env: (envVar) => `Set ${envVar} to a valid string`,
500
+ config: (configPath) => `Set ${configPath} to a valid string in your config`,
501
+ prompt: `Enter a valid value for --${name}`
502
+ })
503
+ });
504
+ case "number-constraint": return new ValidationError(`Invalid number value '${REDACTED}' ${sourceLabel(source)} for flag --${name}: ${describeNumberConstraintViolation(failure.violation)}`, {
505
+ code: "CONSTRAINT_VIOLATED",
506
+ details: {
507
+ flag: name,
508
+ ...sourceDetails(source),
509
+ expected: "number",
510
+ constraint: failure.violation.kind,
511
+ ..."bound" in failure.violation ? { bound: failure.violation.bound } : {}
512
+ },
513
+ suggest: suggestBySource(source, {
514
+ stdin: `Pipe a valid number to stdin for --${name}`,
515
+ env: (envVar) => `Set ${envVar} to a valid number`,
516
+ config: (configPath) => `Set ${configPath} to a valid number in your config`,
517
+ prompt: `Enter a valid number for --${name}`
518
+ })
519
+ });
520
+ case "thrown": {
521
+ const message = failure.error instanceof Error ? failure.error.message : String(failure.error);
522
+ const sourceRef = suggestBySource(source, {
523
+ stdin: "stdin value",
524
+ env: (envVar) => `env ${envVar}`,
525
+ config: (configPath) => `config ${configPath}`,
526
+ prompt: "prompt value"
527
+ });
528
+ return new ValidationError(`Failed to parse ${sourceRef} for flag --${name}: ${message}`, {
529
+ code: "TYPE_MISMATCH",
530
+ details: {
531
+ flag: name,
532
+ ...sourceDetails(source),
533
+ expected: "custom"
534
+ },
535
+ suggest: suggestBySource(source, {
536
+ stdin: `Pipe a valid value to stdin for --${name}`,
537
+ env: (envVar) => `Set ${envVar} to a valid value for --${name}`,
538
+ config: (configPath) => `Set ${configPath} to a valid value for --${name} in your config`,
539
+ prompt: `Enter a valid value for --${name}`
233
540
  })
234
- };
541
+ });
235
542
  }
236
- case "custom":
237
- if (schema.parseFn === void 0) return {
238
- ok: true,
239
- value: raw
240
- };
241
- try {
242
- return {
243
- ok: true,
244
- value: schema.parseFn(raw)
245
- };
246
- } catch (error) {
247
- const message = error instanceof Error ? error.message : String(error);
248
- return {
249
- ok: false,
250
- error: new ValidationError(`Failed to parse ${source.kind === "env" ? `env ${source.envVar}` : source.kind === "config" ? `config ${source.configPath}` : "prompt value"} for flag --${flagName}: ${message}`, {
251
- code: "TYPE_MISMATCH",
252
- details: {
253
- flag: flagName,
254
- ...sourceDetails(source),
255
- value: raw,
256
- expected: "custom"
257
- },
258
- suggest: source.kind === "env" ? `Set ${source.envVar} to a valid value for --${flagName}` : source.kind === "config" ? `Set ${source.configPath} to a valid value for --${flagName} in your config` : `Enter a valid value for --${flagName}`
259
- })
260
- };
261
- }
262
543
  }
263
544
  }
545
+ /** Build the error for a raw value the codec could not read as its primitive. */
546
+ function typeCoercionError(name, source, expected) {
547
+ if (expected === "string") return coercionError(name, source, "TYPE_MISMATCH", "string", "Invalid string value", suggestBySource(source, {
548
+ stdin: `Pipe a valid string to stdin for --${name}`,
549
+ env: (envVar) => `Set ${envVar} to a valid string`,
550
+ config: (configPath) => `Set ${configPath} to a string in your config`,
551
+ prompt: `Enter a valid string for --${name}`
552
+ }));
553
+ if (expected === "number") return coercionError(name, source, "TYPE_MISMATCH", "number", `Invalid number value '${REDACTED}'`, suggestBySource(source, {
554
+ stdin: `Pipe a valid number to stdin for --${name}`,
555
+ env: (envVar) => `Set ${envVar} to a valid number`,
556
+ config: (configPath) => `Set ${configPath} to a valid number in your config`,
557
+ prompt: `Enter a valid number for --${name}`
558
+ }));
559
+ return coercionError(name, source, "TYPE_MISMATCH", "boolean", `Invalid boolean value '${REDACTED}'`, suggestBySource(source, {
560
+ stdin: `Pipe true/false, 1/0, or yes/no to stdin for --${name}`,
561
+ env: (envVar) => `Set ${envVar} to true/false, 1/0, or yes/no`,
562
+ config: (configPath) => `Set ${configPath} to true or false in your config`,
563
+ prompt: `Answer yes or no for --${name}`
564
+ }));
565
+ }
264
566
  function argSourceLabel(source) {
265
- return source.kind === "env" ? `from env ${source.envVar}` : "from stdin";
567
+ return sourceLabel(source);
266
568
  }
267
569
  function argSourceDetails(source) {
268
- return source.kind === "env" ? { envVar: source.envVar } : { source: "stdin" };
570
+ return sourceDetails(source);
269
571
  }
270
572
  function buildArgCoercionSuggest(argName, source, expected) {
271
- if (source.kind === "env") return expected === "number" ? `Set ${source.envVar} to a valid number` : `Set ${source.envVar} to a valid value for <${argName}>`;
272
- return expected === "number" ? `Pipe a valid number to stdin for <${argName}>` : `Pipe a valid value to stdin for <${argName}>`;
273
- }
274
- function argSourceToCoerceSource(source) {
275
- return source.kind === "env" ? {
276
- kind: "env",
277
- envVar: source.envVar
278
- } : { kind: "prompt" };
279
- }
280
- function redactArgCoercionMessage(argName, source, schema, error) {
281
- switch (schema.kind) {
282
- case "number": {
283
- const base = `Invalid number value '<redacted>' ${argSourceLabel(source)} for argument <${argName}>`;
284
- if (error.code !== "CONSTRAINT_VIOLATED") return base;
285
- const suffix = /: ([^:]+)$/.exec(error.message)?.[1];
286
- return suffix !== void 0 ? `${base}: ${suffix}` : base;
287
- }
573
+ const subject = expected === "custom" ? "value" : expected;
574
+ return suggestBySource(source, {
575
+ stdin: `Pipe a valid ${subject} to stdin for <${argName}>`,
576
+ env: (envVar) => expected === "custom" ? `Set ${envVar} to a valid value for <${argName}>` : `Set ${envVar} to a valid ${expected}`,
577
+ config: (configPath) => `Set ${configPath} to a valid ${subject} for <${argName}>`,
578
+ prompt: `Enter a valid ${subject} for <${argName}>`
579
+ });
580
+ }
581
+ /** The spellings the boolean codec reads, named for the source that carried one. */
582
+ function argBooleanSuggest(argName, source) {
583
+ return suggestBySource(source, {
584
+ stdin: `Pipe true/false, 1/0, or yes/no to stdin for <${argName}>`,
585
+ env: (envVar) => `Set ${envVar} to true/false, 1/0, or yes/no`,
586
+ config: (configPath) => `Set ${configPath} to true or false in your config`,
587
+ prompt: `Answer yes or no for <${argName}>`
588
+ });
589
+ }
590
+ /**
591
+ * Turn a value-layer failure into the positional surface's validation error.
592
+ *
593
+ * The failure states the reason, so this surface words its own diagnostic from
594
+ * it. Reading a reason back out of the message another surface wrote loses the
595
+ * part of it that follows a colon.
596
+ *
597
+ * @param argName - Name of the positional the value belongs to.
598
+ * @param source - The stage that carried the value.
599
+ * @param failure - What the value layer rejected.
600
+ * @returns The redacted error for this surface.
601
+ */
602
+ function argValueCoercionError(argName, source, failure) {
603
+ const subject = `${argSourceLabel(source)} for argument <${argName}>`;
604
+ switch (failure.kind) {
605
+ case "type": return argTypeCoercionError(argName, source, failure.expected);
288
606
  case "enum": {
289
- const allowed = Array.isArray(error.details?.allowed) ? error.details.allowed.filter((value) => typeof value === "string") : [];
290
- return `Invalid value '<redacted>' ${argSourceLabel(source)} for argument <${argName}>. Allowed: ${allowed.join(", ")}`;
607
+ const allowed = failure.enumValues ?? [];
608
+ const allowedList = allowed.join(", ");
609
+ return new ValidationError(`Invalid value '${REDACTED}' ${subject}. Allowed: ${allowedList}`, {
610
+ code: "INVALID_ENUM",
611
+ details: {
612
+ arg: argName,
613
+ ...argSourceDetails(source),
614
+ allowed
615
+ },
616
+ suggest: suggestBySource(source, {
617
+ stdin: `Provide one of: ${allowedList}`,
618
+ env: (envVar) => `Set ${envVar} to one of: ${allowedList}`,
619
+ config: (configPath) => `Set ${configPath} to one of: ${allowedList}`,
620
+ prompt: `Provide one of: ${allowedList}`
621
+ })
622
+ });
291
623
  }
292
- case "custom": {
293
- const suffix = /: ([^:]+)$/.exec(error.message)?.[1];
294
- return suffix !== void 0 ? `Invalid value '<redacted>' ${argSourceLabel(source)} for argument <${argName}>: ${suffix}` : `Invalid value '<redacted>' ${argSourceLabel(source)} for argument <${argName}>`;
624
+ case "string-constraint": return new ValidationError(`Invalid value '${REDACTED}' ${subject}: ${describeStringConstraintViolation(failure.violation)}`, {
625
+ code: "CONSTRAINT_VIOLATED",
626
+ details: {
627
+ arg: argName,
628
+ ...argSourceDetails(source),
629
+ expected: "string",
630
+ ...stringConstraintDetails(failure.violation)
631
+ },
632
+ suggest: buildArgCoercionSuggest(argName, source, "string")
633
+ });
634
+ case "number-constraint": return new ValidationError(`Invalid number value '${REDACTED}' ${subject}: ${describeNumberConstraintViolation(failure.violation)}`, {
635
+ code: "CONSTRAINT_VIOLATED",
636
+ details: {
637
+ arg: argName,
638
+ ...argSourceDetails(source),
639
+ expected: "number",
640
+ constraint: failure.violation.kind,
641
+ ..."bound" in failure.violation ? { bound: failure.violation.bound } : {}
642
+ },
643
+ suggest: buildArgCoercionSuggest(argName, source, "number")
644
+ });
645
+ case "thrown": {
646
+ const message = failure.error instanceof Error ? failure.error.message : String(failure.error);
647
+ const sourceRef = suggestBySource(source, {
648
+ stdin: "stdin value",
649
+ env: (envVar) => `env ${envVar}`,
650
+ config: (configPath) => `config ${configPath}`,
651
+ prompt: "prompt value"
652
+ });
653
+ return new ValidationError(`Failed to parse ${sourceRef} for argument <${argName}>: ${message}`, {
654
+ code: "TYPE_MISMATCH",
655
+ details: {
656
+ arg: argName,
657
+ ...argSourceDetails(source),
658
+ expected: "custom"
659
+ },
660
+ suggest: buildArgCoercionSuggest(argName, source, "custom")
661
+ });
295
662
  }
296
- case "string": return `Invalid value '<redacted>' ${argSourceLabel(source)} for argument <${argName}>`;
297
- default: return schema.kind;
298
663
  }
299
664
  }
300
- function redactArgCoercionDetails(argName, source, schema, error) {
301
- return {
665
+ /** Build the error for a raw value the codec could not read as its primitive. */
666
+ function argTypeCoercionError(argName, source, expected) {
667
+ const subject = `${argSourceLabel(source)} for argument <${argName}>`;
668
+ const details = {
302
669
  arg: argName,
303
670
  ...argSourceDetails(source),
304
- ...schema.kind === "number" || schema.kind === "custom" ? { expected: schema.kind } : {},
305
- ...schema.kind === "number" && typeof error.details?.constraint === "string" ? { constraint: error.details.constraint } : {},
306
- ...schema.kind === "number" && typeof error.details?.bound === "number" ? { bound: error.details.bound } : {},
307
- ...schema.kind === "enum" && Array.isArray(error.details?.allowed) ? { allowed: error.details.allowed.filter((value) => typeof value === "string") } : {}
671
+ expected
308
672
  };
673
+ if (expected === "string") return new ValidationError(`Invalid string value ${subject}`, {
674
+ code: "TYPE_MISMATCH",
675
+ details,
676
+ suggest: buildArgCoercionSuggest(argName, source, "string")
677
+ });
678
+ if (expected === "number") return new ValidationError(`Invalid number value '${REDACTED}' ${subject}`, {
679
+ code: "TYPE_MISMATCH",
680
+ details,
681
+ suggest: buildArgCoercionSuggest(argName, source, "number")
682
+ });
683
+ return new ValidationError(`Invalid boolean value '${REDACTED}' ${subject}`, {
684
+ code: "TYPE_MISMATCH",
685
+ details,
686
+ suggest: argBooleanSuggest(argName, source)
687
+ });
309
688
  }
310
- function redactArgCoercionSuggest(argName, source, schema, error) {
311
- if (schema.kind === "number" || schema.kind === "custom") return buildArgCoercionSuggest(argName, source, schema.kind);
312
- if (schema.kind === "enum") {
313
- const allowedList = (Array.isArray(error.details?.allowed) ? error.details.allowed.filter((value) => typeof value === "string") : []).join(", ");
314
- return source.kind === "env" ? `Set ${source.envVar} to one of: ${allowedList}` : `Provide one of: ${allowedList}`;
315
- }
689
+ /**
690
+ * Coerce a value from a non-CLI source into the type declared by an arg schema,
691
+ * redacting the raw value in error diagnostics.
692
+ *
693
+ * Every source outside argv may carry a secret a user piped, exported, or
694
+ * stored, so the arg surface reports the failure without echoing the value.
695
+ *
696
+ * @param argName - Name of the positional the value belongs to.
697
+ * @param binding - The stage that produced the value.
698
+ * @param raw - The value that stage produced.
699
+ * @param schema - Runtime descriptor of the arg.
700
+ * @returns The coerced value, or a redacted {@link ValidationError}.
701
+ */
702
+ function coerceArgValue(argName, binding, raw, schema) {
703
+ const source = diagnosticSourceOf(binding);
704
+ const cardinality = argCardinality(schema);
705
+ if (isCollection(cardinality)) return coerceCollection(cardinality, source, binding.split, raw, (element) => coerceArgElement(argName, source, element, schema), argCollectionErrors(argName, source), argAggregationErrors(argName));
706
+ return coerceArgElement(argName, source, trimmedStdinValue(binding, raw, argValueSchema(schema)), schema);
316
707
  }
317
- /** Coerce a string value from stdin/env into the type declared by an arg schema, redacting raw values in error diagnostics. */
318
- function coerceArgStringValue(argName, source, raw, schema) {
319
- const coerced = coerceSharedPropertyValue(argName, argSourceToCoerceSource(source), raw, toSharedArgPropertySchema(schema));
320
- if (coerced.ok) return coerced;
321
- const suggest = redactArgCoercionSuggest(argName, source, schema, coerced.error);
322
- const options = suggest === void 0 ? {
323
- code: coerced.error.code,
324
- details: redactArgCoercionDetails(argName, source, schema, coerced.error)
708
+ /**
709
+ * Decode one arg value through the value layer, redacting the raw value in
710
+ * diagnostics.
711
+ *
712
+ * An entries arg projects onto the value of one entry, so the failure a decode
713
+ * reports already describes the element rather than the record.
714
+ */
715
+ function coerceArgElement(argName, source, raw, schema) {
716
+ const decoded = decodeValue(argValueSchema(schema), raw, valueInputOf(source));
717
+ return decoded.ok ? {
718
+ ok: true,
719
+ value: decoded.value
325
720
  } : {
326
- code: coerced.error.code,
327
- details: redactArgCoercionDetails(argName, source, schema, coerced.error),
328
- suggest
721
+ ok: false,
722
+ error: argValueCoercionError(argName, source, decoded.failure)
723
+ };
724
+ }
725
+ /**
726
+ * Finish the CLI value of a flag, splicing stdin into occurrence order.
727
+ *
728
+ * A scalar keeps what the parser produced. A collection carries its occurrences
729
+ * in the order they were typed, and an occurrence of `-` stands for the whole
730
+ * stdin source at that position: what the buffer decodes to is spliced in
731
+ * there, so `--tag before --tag - --tag after` over `'a\nb\n'` resolves to
732
+ * `['before', 'a', 'b', 'after']`.
733
+ *
734
+ * @param flagName - Canonical flag name.
735
+ * @param schema - The flag being resolved.
736
+ * @param value - What the parser produced for it.
737
+ * @param stdinData - The pre-read stdin buffer, when one was read.
738
+ * @param stdin - The flag's stdin source, when it declares one.
739
+ * @returns The finished value, a failure, or absence when only `-` was given
740
+ * and nothing was piped.
741
+ */
742
+ function finishCliFlagValue(flagName, schema, value, stdinData, stdin) {
743
+ const cardinality = flagCardinality(schema);
744
+ if (!isCollection(cardinality)) return {
745
+ kind: "value",
746
+ value,
747
+ viaStdin: false
748
+ };
749
+ return spliceCliCollection(cardinality, value, stdinData, stdin, (element) => coerceValueSchema(flagName, { kind: "stdin" }, element, flagValueSchema(schema)), flagCollectionErrors(flagName, { kind: "stdin" }), flagAggregationErrors(flagName));
750
+ }
751
+ /**
752
+ * Finish the CLI value of a positional, splicing stdin into occurrence order.
753
+ *
754
+ * @param argName - Positional arg name.
755
+ * @param schema - The arg being resolved.
756
+ * @param value - What the parser produced for it.
757
+ * @param stdinData - The pre-read stdin buffer, when one was read.
758
+ * @param stdin - The arg's stdin source, when it declares one.
759
+ * @returns The finished value, a failure, or absence when only `-` was given
760
+ * and nothing was piped.
761
+ */
762
+ function finishCliArgValue(argName, schema, value, stdinData, stdin) {
763
+ const cardinality = argCardinality(schema);
764
+ if (!isCollection(cardinality)) return {
765
+ kind: "value",
766
+ value,
767
+ viaStdin: false
768
+ };
769
+ return spliceCliCollection(cardinality, value, stdinData, stdin, (element) => coerceArgElement(argName, { kind: "stdin" }, element, schema), argCollectionErrors(argName, { kind: "stdin" }), argAggregationErrors(argName));
770
+ }
771
+ /** The tokens the user typed, as the source of an occurrence. */
772
+ const CLI_SOURCE = { kind: "cli" };
773
+ /** The buffer a `-` stood for, as the source of an occurrence. */
774
+ const STDIN_SOURCE = { kind: "stdin" };
775
+ /**
776
+ * Replace every stdin sentinel among the occurrences with what stdin decodes to,
777
+ * then aggregate what is left.
778
+ *
779
+ * A value the parser did not leave as an occurrence list is the aggregate a
780
+ * caller built by hand, and it reaches the resolved value untouched. Each
781
+ * occurrence keeps the source it came from, so an aggregation failure names
782
+ * either the typed token or the pipe.
783
+ */
784
+ function spliceCliCollection(cardinality, value, stdinData, stdin, decodeElement, errors, aggregationErrors) {
785
+ const occurrences = liftOccurrences(cardinality, value, stdin !== void 0 && stdinReadsOnDash(stdin));
786
+ const aggregated = readAggregated(occurrences);
787
+ if (aggregated !== void 0) return {
788
+ kind: "value",
789
+ value: aggregated.value,
790
+ viaStdin: false
791
+ };
792
+ const spliced = [];
793
+ let sentinels = 0;
794
+ let viaStdin = false;
795
+ for (const occurrence of occurrences) {
796
+ if (occurrence.kind !== "stdin") {
797
+ spliced.push({
798
+ occurrence,
799
+ source: CLI_SOURCE
800
+ });
801
+ continue;
802
+ }
803
+ sentinels += 1;
804
+ if (stdin === void 0 || typeof stdinData !== "string") continue;
805
+ const read = readStdinOccurrence(cardinality, stdin.split, stdinData, decodeElement, errors);
806
+ if (read.kind !== "value") return read;
807
+ viaStdin = true;
808
+ for (const element of read.occurrences) spliced.push({
809
+ occurrence: element,
810
+ source: STDIN_SOURCE
811
+ });
812
+ }
813
+ if (sentinels > 0 && typeof stdinData !== "string") {
814
+ if (sentinels === occurrences.length) return { kind: "absent" };
815
+ return {
816
+ kind: "error",
817
+ error: aggregationErrors({ kind: "dash-without-stdin" }, CLI_SOURCE)
818
+ };
819
+ }
820
+ if (cardinality.kind === "many") return {
821
+ kind: "value",
822
+ value: spliced.map((entry) => occurrenceValue(entry.occurrence)),
823
+ viaStdin
824
+ };
825
+ const entries = [];
826
+ for (const entry of spliced) {
827
+ if (entry.occurrence.kind !== "entry") return {
828
+ kind: "error",
829
+ error: aggregationErrors({
830
+ kind: "shape",
831
+ expected: "object"
832
+ }, entry.source)
833
+ };
834
+ entries.push(entry);
835
+ }
836
+ const folded = foldEntries(entryPairsOf(entries.map((entry) => entry.occurrence)), cardinality.duplicateKeys);
837
+ if (!folded.ok) return {
838
+ kind: "error",
839
+ error: aggregationErrors({
840
+ kind: "duplicate-key",
841
+ key: folded.duplicateKey
842
+ }, entries[folded.at]?.source ?? CLI_SOURCE)
329
843
  };
330
844
  return {
331
- ok: false,
332
- error: new ValidationError(redactArgCoercionMessage(argName, source, schema, coerced.error), options)
845
+ kind: "value",
846
+ value: folded.value,
847
+ viaStdin
848
+ };
849
+ }
850
+ /** Decode the stdin buffer into the occurrences one `-` stands for. */
851
+ function readStdinOccurrence(cardinality, policy, stdinData, decodeElement, errors) {
852
+ const source = { kind: "stdin" };
853
+ if (cardinality.kind === "many") {
854
+ const parts = readManyParts(source, stdinData, policy);
855
+ if (!parts.ok) return {
856
+ kind: "error",
857
+ error: errors(parts.fault)
858
+ };
859
+ const occurrences = [];
860
+ for (const part of parts.parts) {
861
+ const decoded = decodeElement(part);
862
+ if (!decoded.ok) return {
863
+ kind: "error",
864
+ error: decoded.error
865
+ };
866
+ occurrences.push({
867
+ kind: "value",
868
+ value: decoded.value
869
+ });
870
+ }
871
+ return {
872
+ kind: "value",
873
+ occurrences
874
+ };
875
+ }
876
+ const pairs = readEntryPairs(stdinData, policy);
877
+ if (!pairs.ok) return {
878
+ kind: "error",
879
+ error: errors(pairs.fault)
880
+ };
881
+ const occurrences = [];
882
+ for (const [key, raw] of pairs.pairs) {
883
+ const decoded = decodeElement(raw);
884
+ if (!decoded.ok) return {
885
+ kind: "error",
886
+ error: decoded.error
887
+ };
888
+ occurrences.push({
889
+ kind: "entry",
890
+ key,
891
+ value: decoded.value
892
+ });
893
+ }
894
+ return {
895
+ kind: "value",
896
+ occurrences
333
897
  };
334
898
  }
335
899
  //#endregion
336
- export { coerceArgStringValue, coerceValue };
900
+ export { coerceArgValue, coerceValue, finishCliArgValue, finishCliFlagValue };