@kjanat/dreamcli 2.4.1 → 3.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 (94) hide show
  1. package/CHANGELOG.md +169 -1
  2. package/README.md +14 -7
  3. package/dist/core/cli/index.d.mts +283 -81
  4. package/dist/core/cli/index.mjs +1 -1
  5. package/dist/core/cli/planner.d.mts +27 -5
  6. package/dist/core/cli/planner.mjs +1 -1
  7. package/dist/core/cli/root-help.d.mts +16 -2
  8. package/dist/core/cli/root-help.mjs +3 -5
  9. package/dist/core/cli/root-surface.d.mts +18 -3
  10. package/dist/core/cli/root-surface.mjs +1 -1
  11. package/dist/core/cli/runtime-preflight.d.mts +31 -5
  12. package/dist/core/cli/runtime-preflight.mjs +1 -1
  13. package/dist/core/completion/index.d.mts +32 -1
  14. package/dist/core/completion/index.mjs +1 -1
  15. package/dist/core/completion/shells/shared.d.mts +10 -0
  16. package/dist/core/completion/shells/shared.mjs +1 -1
  17. package/dist/core/config/index.d.mts +2 -2
  18. package/dist/core/config/package-json.d.mts +93 -20
  19. package/dist/core/config/package-json.mjs +3 -1
  20. package/dist/core/help/index.d.mts +45 -1
  21. package/dist/core/help/index.mjs +6 -6
  22. package/dist/core/json-schema/index.mjs +1 -1
  23. package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
  24. package/dist/core/parse/index.d.mts +15 -1
  25. package/dist/core/parse/index.mjs +1 -1
  26. package/dist/core/prompt/index.d.mts +11 -3
  27. package/dist/core/prompt/index.mjs +3 -3
  28. package/dist/core/resolve/coerce.mjs +1 -1
  29. package/dist/core/resolve/flags.mjs +1 -1
  30. package/dist/core/resolve/property.d.mts +2 -0
  31. package/dist/core/resolve/property.mjs +1 -1
  32. package/dist/core/schema/arg.d.mts +90 -10
  33. package/dist/core/schema/arg.mjs +1 -1
  34. package/dist/core/schema/command.d.mts +3 -1
  35. package/dist/core/schema/flag.d.mts +92 -2
  36. package/dist/core/schema/flag.mjs +1 -1
  37. package/dist/core/schema/index.d.mts +2 -1
  38. package/dist/core/schema/number-constraints.d.mts +96 -0
  39. package/dist/core/schema/number-constraints.mjs +1 -0
  40. package/dist/core/schema/prompt.d.mts +15 -0
  41. package/dist/core/schema/run.d.mts +4 -4
  42. package/dist/core/testkit/index.d.mts +9 -5
  43. package/dist/core/testkit/index.mjs +1 -1
  44. package/dist/index.d.mts +4 -3
  45. package/dist/index.mjs +1 -1
  46. package/dist/runtime/auto.mjs +1 -1
  47. package/dist/runtime/bun.mjs +1 -1
  48. package/dist/runtime/deno.mjs +2 -2
  49. package/dist/runtime/node.mjs +2 -2
  50. package/dist/version.mjs +1 -1
  51. package/examples/basic.ts +5 -1
  52. package/examples/gh/package.json +2 -7
  53. package/examples/pwsh-demo/package.json +1 -7
  54. package/examples/pwsh-demo/src/main.test.ts +1 -4
  55. package/examples/pwsh-demo/src/main.ts +14 -4
  56. package/examples/transport-launcher.ts +85 -0
  57. package/package.json +15 -24
  58. package/src/core/cli/dispatch.ts +7 -1
  59. package/src/core/cli/index.ts +521 -122
  60. package/src/core/cli/planner.ts +192 -23
  61. package/src/core/cli/root-help.ts +195 -105
  62. package/src/core/cli/root-surface.ts +25 -12
  63. package/src/core/cli/runtime-preflight.ts +43 -8
  64. package/src/core/completion/index.ts +50 -0
  65. package/src/core/completion/shells/powershell.ts +2 -2
  66. package/src/core/completion/shells/shared.ts +30 -3
  67. package/src/core/config/index.ts +12 -2
  68. package/src/core/config/package-json.ts +250 -41
  69. package/src/core/execution/index.ts +1 -4
  70. package/src/core/help/index.ts +57 -10
  71. package/src/core/json-schema/index.ts +23 -4
  72. package/src/core/json-schema/meta-descriptions.generated.ts +115 -98
  73. package/src/core/parse/index.ts +62 -1
  74. package/src/core/prompt/index.ts +54 -14
  75. package/src/core/resolve/coerce.ts +73 -5
  76. package/src/core/resolve/flags.ts +14 -0
  77. package/src/core/resolve/property.ts +4 -4
  78. package/src/core/schema/arg.ts +125 -3
  79. package/src/core/schema/command.ts +3 -1
  80. package/src/core/schema/flag.ts +120 -4
  81. package/src/core/schema/index.ts +5 -0
  82. package/src/core/schema/number-constraints.ts +153 -0
  83. package/src/core/schema/prompt.ts +15 -0
  84. package/src/core/schema/run.ts +4 -4
  85. package/src/core/testkit/index.ts +32 -8
  86. package/src/index.ts +8 -0
  87. package/src/runtime/auto.ts +0 -24
  88. package/src/runtime/bun.ts +0 -7
  89. package/src/runtime/deno.ts +0 -2
  90. package/src/runtime/node.ts +0 -11
  91. package/src/runtime/support.ts +1 -59
  92. package/src/schema.ts +16 -0
  93. package/dist/runtime/support.d.mts +0 -42
  94. package/dist/runtime/support.mjs +0 -1
@@ -6,176 +6,193 @@
6
6
 
7
7
  const definitionMetaSchemaDescriptions = {
8
8
  root: {
9
- description: "Runtime descriptor for the CLI program.\n\nStores the program name, version, description, and registered commands.\\\nBuilt incrementally by CLIBuilder.",
9
+ description:
10
+ 'Runtime descriptor for the CLI program.\n\nStores the program name, version, description, and registered commands.\\\nBuilt incrementally by CLIBuilder.',
10
11
  properties: {
11
- "name": {
12
- description: "Program name (used in help text, usage lines, and completion scripts).",
12
+ name: {
13
+ description: 'Program name (used in help text, usage lines, and completion scripts).',
13
14
  },
14
- "version": {
15
- description: "Program version (shown by `--version`).",
15
+ version: {
16
+ description: 'Program version (shown by `--version`).',
16
17
  },
17
- "description": {
18
- description: "Program description (shown in root help).",
18
+ description: {
19
+ description: 'Program description (shown in root help).',
19
20
  },
20
- "defaultCommand": {
21
- description: "Default command dispatched when no subcommand matches.\n\nWhen set, the CLI root behaves like a hybrid command group: subcommands\ndispatch by name as usual, but empty argv or flags-only argv falls\nthrough to this command instead of showing root help.\n\nSet via the .default() builder method.",
21
+ defaultCommand: {
22
+ description:
23
+ 'Default command dispatched when no subcommand matches.\n\nWhen set, the CLI root behaves like a hybrid command group: subcommands\ndispatch by name as usual, but empty argv or flags-only argv falls\nthrough to this command instead of showing root help.\n\nSet via the .default() builder method.',
22
24
  },
23
- "commands": {
24
- description: "Registered commands (type-erased for heterogeneous storage).",
25
+ commands: {
26
+ description: 'Registered commands (type-erased for heterogeneous storage).',
25
27
  },
26
28
  },
27
29
  },
28
30
  defs: {
29
- "command": {
30
- description: "Runtime descriptor produced by CommandBuilder.\n\nConsumers (parser, help generator, CLI dispatcher) read this to\nunderstand the command's shape — flags, args, aliases, subcommands,\nmiddleware, and interactive resolver.",
31
+ command: {
32
+ description:
33
+ "Runtime descriptor produced by CommandBuilder.\n\nConsumers (parser, help generator, CLI dispatcher) read this to\nunderstand the command's shape — flags, args, aliases, subcommands,\nmiddleware, and interactive resolver.",
31
34
  properties: {
32
- "name": {
35
+ name: {
33
36
  description: "The command name (used for dispatch, e.g. `'deploy'`).",
34
37
  },
35
- "description": {
36
- description: "Human-readable description for help text.",
38
+ description: {
39
+ description: 'Human-readable description for help text.',
37
40
  },
38
- "aliases": {
39
- description: "Alternative names for this command.",
41
+ aliases: {
42
+ description: 'Alternative names for this command.',
40
43
  },
41
- "hidden": {
42
- description: "Whether this command is hidden from help listings.",
44
+ hidden: {
45
+ description: 'Whether this command is hidden from help listings.',
43
46
  },
44
- "examples": {
45
- description: "Usage examples for help text.",
47
+ examples: {
48
+ description: 'Usage examples for help text.',
46
49
  },
47
- "flags": {
48
- description: "Named flag schemas, keyed by flag name.",
50
+ flags: {
51
+ description: 'Named flag schemas, keyed by flag name.',
49
52
  },
50
- "args": {
51
- description: "Ordered positional arg entries (name + schema).",
53
+ args: {
54
+ description: 'Ordered positional arg entries (name + schema).',
52
55
  },
53
- "commands": {
54
- description: "Nested subcommand schemas (for help rendering and completion).\n\nPure data — no execution closures. Populated by `.command()` on\n`CommandBuilder`. Empty for leaf commands.",
56
+ commands: {
57
+ description:
58
+ 'Nested subcommand schemas (for help rendering and completion).\n\nPure data — no execution closures. Populated by `.command()` on\n`CommandBuilder`. Empty for leaf commands.',
55
59
  },
56
60
  },
57
61
  },
58
- "flag": {
59
- description: "The runtime descriptor stored inside every FlagBuilder. Consumers (parser,\nhelp generator, resolution chain) read this to understand the flag's shape\nwithout touching generics.",
62
+ flag: {
63
+ description:
64
+ "The runtime descriptor stored inside every FlagBuilder. Consumers (parser,\nhelp generator, resolution chain) read this to understand the flag's shape\nwithout touching generics.",
60
65
  properties: {
61
- "kind": {
62
- description: "What kind of value this flag accepts.",
66
+ kind: {
67
+ description: 'What kind of value this flag accepts.',
63
68
  },
64
- "presence": {
65
- description: "Presence describes whether a flag value is guaranteed to exist when the\naction handler runs:\n\n- `'optional'` — not required; unresolved value follows the kind-specific\n optional fallback (`undefined` for most flags, `[]` for arrays)\n- `'required'` — must be supplied; error if missing\n- `'defaulted'` — always present (falls back to default value)",
69
+ presence: {
70
+ description:
71
+ "Presence describes whether a flag value is guaranteed to exist when the\naction handler runs:\n\n- `'optional'` — not required; unresolved value follows the kind-specific\n optional fallback (`undefined` for most flags, `[]` for arrays)\n- `'required'` — must be supplied; error if missing\n- `'defaulted'` — always present (falls back to default value)",
66
72
  },
67
- "defaultValue": {
68
- description: "Runtime default value (if any).",
73
+ defaultValue: {
74
+ description: 'Runtime default value (if any).',
69
75
  },
70
- "aliases": {
76
+ aliases: {
71
77
  description: "Short/long aliases (e.g. `[{ name: 'f', hidden: false }]` for `--force`).",
72
78
  },
73
- "envVar": {
74
- description: "Environment variable name for v0.2+ resolution.",
79
+ envVar: {
80
+ description: 'Environment variable name for v0.2+ resolution.',
75
81
  },
76
- "configPath": {
82
+ configPath: {
77
83
  description: "Dotted config path for v0.2+ resolution (e.g. `'deploy.region'`).",
78
84
  },
79
- "description": {
80
- description: "Human-readable description for help text.",
85
+ description: {
86
+ description: 'Human-readable description for help text.',
81
87
  },
82
- "enumValues": {
88
+ enumValues: {
83
89
  description: "Allowed literal values when `kind === 'enum'`.",
84
90
  },
85
- "elementSchema": {
91
+ elementSchema: {
86
92
  description: "Element schema when `kind === 'array'`.",
87
93
  },
88
- "prompt": {
89
- description: "Interactive prompt configuration for v0.3+ resolution.",
94
+ prompt: {
95
+ description: 'Interactive prompt configuration for v0.3+ resolution.',
90
96
  },
91
- "deprecated": {
92
- description: "Deprecation marker.\n\n- `undefined` — not deprecated (default)\n- `true` — deprecated with no migration message\n- `string` — deprecated with a reason/migration message\n\nWhen a deprecated flag is used, a warning is emitted to stderr.\nHelp text shows `[deprecated]` or `[deprecated: <reason>]`.",
97
+ deprecated: {
98
+ description:
99
+ 'Deprecation marker.\n\n- `undefined` — not deprecated (default)\n- `true` — deprecated with no migration message\n- `string` — deprecated with a reason/migration message\n\nWhen a deprecated flag is used, a warning is emitted to stderr.\nHelp text shows `[deprecated]` or `[deprecated: <reason>]`.',
93
100
  },
94
- "propagate": {
95
- description: "Whether this flag propagates to subcommands in nested command trees.\n\nWhen `true`, the flag is automatically available to all descendant\ncommands. A child command that defines a flag with the same name\nshadows the propagated parent flag.",
101
+ propagate: {
102
+ description:
103
+ 'Whether this flag propagates to subcommands in nested command trees.\n\nWhen `true`, the flag is automatically available to all descendant\ncommands. A child command that defines a flag with the same name\nshadows the propagated parent flag.',
96
104
  },
97
105
  },
98
106
  },
99
- "arg": {
100
- description: "The runtime descriptor stored inside every ArgBuilder. Consumers (parser,\nhelp generator) read this to understand the arg's shape without touching\ngenerics.",
107
+ arg: {
108
+ description:
109
+ "The runtime descriptor stored inside every ArgBuilder. Consumers (parser,\nhelp generator) read this to understand the arg's shape without touching\ngenerics.",
101
110
  properties: {
102
- "name": {
103
- description: "A named positional argument entry in the command schema.\n\nPairs a user-facing arg name with its ArgSchema descriptor.\nThe array ordering in CommandSchema.args determines CLI position.",
111
+ name: {
112
+ description:
113
+ 'A named positional argument entry in the command schema.\n\nPairs a user-facing arg name with its ArgSchema descriptor.\nThe array ordering in CommandSchema.args determines CLI position.',
104
114
  },
105
- "kind": {
106
- description: "What kind of value this arg accepts.",
115
+ kind: {
116
+ description: 'What kind of value this arg accepts.',
107
117
  },
108
- "presence": {
109
- description: "Presence describes whether a positional arg is guaranteed to exist when the\naction handler runs:\n\n- `'required'` — must be supplied; error if missing (default)\n- `'optional'` — may be `undefined` if not supplied\n- `'defaulted'` — always present (falls back to default value)",
118
+ presence: {
119
+ description:
120
+ "Presence describes whether a positional arg is guaranteed to exist when the\naction handler runs:\n\n- `'required'` — must be supplied; error if missing (default)\n- `'optional'` — may be `undefined` if not supplied\n- `'defaulted'` — always present (falls back to default value)",
110
121
  },
111
- "variadic": {
112
- description: "Whether this arg consumes all remaining positionals.",
122
+ variadic: {
123
+ description: 'Whether this arg consumes all remaining positionals.',
113
124
  },
114
- "stdinMode": {
115
- description: "Whether this arg may read from stdin during resolution.",
125
+ stdinMode: {
126
+ description: 'Whether this arg may read from stdin during resolution.',
116
127
  },
117
- "defaultValue": {
118
- description: "Runtime default value (if any).",
128
+ defaultValue: {
129
+ description: 'Runtime default value (if any).',
119
130
  },
120
- "description": {
121
- description: "Human-readable description for help text.",
131
+ description: {
132
+ description: 'Human-readable description for help text.',
122
133
  },
123
- "envVar": {
124
- description: "Environment variable name for env resolution.\n\nWhen set and the CLI value is absent, the resolver reads this env var\nand coerces the string to the arg's declared kind.",
134
+ envVar: {
135
+ description:
136
+ "Environment variable name for env resolution.\n\nWhen set and the CLI value is absent, the resolver reads this env var\nand coerces the string to the arg's declared kind.",
125
137
  },
126
- "enumValues": {
138
+ enumValues: {
127
139
  description: "Allowed literal values when `kind === 'enum'`.",
128
140
  },
129
- "deprecated": {
130
- description: "Deprecation marker.\n\n- `undefined` — not deprecated (default)\n- `true` — deprecated with no migration message\n- `string` — deprecated with a reason/migration message\n\nWhen a deprecated arg is used, a warning is emitted to stderr.\nHelp text shows `[deprecated]` or `[deprecated: <reason>]`.",
141
+ deprecated: {
142
+ description:
143
+ 'Deprecation marker.\n\n- `undefined` — not deprecated (default)\n- `true` — deprecated with no migration message\n- `string` — deprecated with a reason/migration message\n\nWhen a deprecated arg is used, a warning is emitted to stderr.\nHelp text shows `[deprecated]` or `[deprecated: <reason>]`.',
131
144
  },
132
145
  },
133
146
  },
134
- "prompt": {
135
- description: "Discriminated union of all prompt configurations.\n\nUse the `kind` field to narrow:\n```ts\nif (config.kind === 'select') {\n config.choices // readonly SelectChoice[] | undefined\n}\n```",
147
+ prompt: {
148
+ description:
149
+ "Discriminated union of all prompt configurations.\n\nUse the `kind` field to narrow:\n```ts\nif (config.kind === 'select') {\n config.choices // readonly SelectChoice[] | undefined\n}\n```",
136
150
  properties: {
137
- "kind": {
138
- description: "The kind of interactive prompt to present.\n\n- `'confirm'` — yes/no boolean question\n- `'input'` — free-text string input\n- `'select'` — single selection from a list\n- `'multiselect'` — multiple selections from a list",
151
+ kind: {
152
+ description:
153
+ "The kind of interactive prompt to present.\n\n- `'confirm'` — yes/no boolean question\n- `'input'` — free-text string input\n- `'select'` — single selection from a list\n- `'multiselect'` — multiple selections from a list",
139
154
  },
140
- "message": {
141
- description: "The question displayed to the user.",
155
+ message: {
156
+ description: 'The question displayed to the user.',
142
157
  },
143
- "placeholder": {
144
- description: "Placeholder text shown before user types (informational only).",
158
+ placeholder: {
159
+ description: 'Placeholder text shown before user types (informational only).',
145
160
  },
146
- "choices": {
147
- description: "Available choices. When omitted for `enum` flags, the enum values\nfrom the flag schema are used automatically.",
161
+ choices: {
162
+ description:
163
+ 'Available choices. When omitted for `enum` flags, the enum values\nfrom the flag schema are used automatically.',
148
164
  },
149
- "min": {
150
- description: "Minimum number of selections required.",
165
+ min: {
166
+ description: 'Minimum number of selections required.',
151
167
  },
152
- "max": {
153
- description: "Maximum number of selections allowed.",
168
+ max: {
169
+ description: 'Maximum number of selections allowed.',
154
170
  },
155
171
  },
156
172
  },
157
- "choice": {
158
- description: "A selectable option for SelectPromptConfig and MultiselectPromptConfig prompts.",
173
+ choice: {
174
+ description:
175
+ 'A selectable option for SelectPromptConfig and MultiselectPromptConfig prompts.',
159
176
  properties: {
160
- "value": {
161
- description: "The value returned when this choice is selected.",
177
+ value: {
178
+ description: 'The value returned when this choice is selected.',
162
179
  },
163
- "label": {
164
- description: "Display label shown to the user.",
180
+ label: {
181
+ description: 'Display label shown to the user.',
165
182
  },
166
- "description": {
167
- description: "Optional description shown alongside the choice.",
183
+ description: {
184
+ description: 'Optional description shown alongside the choice.',
168
185
  },
169
186
  },
170
187
  },
171
- "example": {
172
- description: "A single usage example shown in help text.",
188
+ example: {
189
+ description: 'A single usage example shown in help text.',
173
190
  properties: {
174
- "command": {
191
+ command: {
175
192
  description: "The command invocation (e.g. `'deploy production --force'`).",
176
193
  },
177
- "description": {
178
- description: "Optional description of what this example does.",
194
+ description: {
195
+ description: 'Optional description of what this example does.',
179
196
  },
180
197
  },
181
198
  },
@@ -21,6 +21,10 @@ import type {
21
21
  CommandSchema,
22
22
  FlagSchema,
23
23
  } from '#internals/core/schema/index.ts';
24
+ import {
25
+ describeNumberConstraintViolation,
26
+ validateNumberConstraints,
27
+ } from '#internals/core/schema/index.ts';
24
28
 
25
29
  // --- Tokenizer — schema-agnostic argv splitting
26
30
 
@@ -121,6 +125,27 @@ function includesBeforeSeparator(argv: readonly string[], token: string): boolea
121
125
  return false;
122
126
  }
123
127
 
128
+ /**
129
+ * Remove every occurrence of `token` that appears before the `--` end-of-options
130
+ * separator, leaving post-separator literals untouched.
131
+ *
132
+ * The strip counterpart to {@linkcode includesBeforeSeparator}: root-level flags
133
+ * (`--json`) are stripped before dispatch/parse so the command schema never sees
134
+ * them, but a literal after `--` (`-- --json`) must reach the command unchanged.
135
+ *
136
+ * @param argv - Raw argument strings.
137
+ * @param token - Exact flag token to strip (e.g. `--json`).
138
+ * @returns A new argv with pre-separator occurrences of `token` removed, or the
139
+ * original reference when `token` does not occur before the separator.
140
+ */
141
+ function stripBeforeSeparator(argv: readonly string[], token: string): readonly string[] {
142
+ const separatorIndex = argv.indexOf('--');
143
+ const head = separatorIndex === -1 ? argv : argv.slice(0, separatorIndex);
144
+ if (!head.includes(token)) return argv;
145
+ const filteredHead = head.filter((arg) => arg !== token);
146
+ return separatorIndex === -1 ? filteredHead : [...filteredHead, ...argv.slice(separatorIndex)];
147
+ }
148
+
124
149
  // --- Parse result
125
150
 
126
151
  /**
@@ -198,6 +223,21 @@ function coerceFlagValue(
198
223
  details: { flag: flagName, input: displayName, value: raw, expected: 'number' },
199
224
  });
200
225
  }
226
+ const violation = validateNumberConstraints(n, schema.numberConstraints);
227
+ if (violation !== undefined) {
228
+ const reason = describeNumberConstraintViolation(violation);
229
+ throw new ParseError(`Invalid number value '${raw}' for flag ${displayName}: ${reason}`, {
230
+ code: 'INVALID_VALUE',
231
+ details: {
232
+ flag: flagName,
233
+ input: displayName,
234
+ value: raw,
235
+ expected: 'number',
236
+ constraint: violation.kind,
237
+ ...('bound' in violation ? { bound: violation.bound } : {}),
238
+ },
239
+ });
240
+ }
201
241
  return n;
202
242
  }
203
243
 
@@ -284,6 +324,20 @@ function coerceArgValue(argName: string, raw: string, schema: ArgSchema): unknow
284
324
  details: { arg: argName, value: raw, expected: 'number' },
285
325
  });
286
326
  }
327
+ const violation = validateNumberConstraints(n, schema.numberConstraints);
328
+ if (violation !== undefined) {
329
+ const reason = describeNumberConstraintViolation(violation);
330
+ throw new ParseError(`Invalid number value '${raw}' for argument <${argName}>: ${reason}`, {
331
+ code: 'INVALID_VALUE',
332
+ details: {
333
+ arg: argName,
334
+ value: raw,
335
+ expected: 'number',
336
+ constraint: violation.kind,
337
+ ...('bound' in violation ? { bound: violation.bound } : {}),
338
+ },
339
+ });
340
+ }
287
341
  return n;
288
342
  }
289
343
 
@@ -678,4 +732,11 @@ function levenshtein(a: string, b: string): number {
678
732
  // --- Exports
679
733
 
680
734
  export type { ParseResult, Token };
681
- export { buildFlagLookup, flagExpectsValue, includesBeforeSeparator, parse, tokenize };
735
+ export {
736
+ buildFlagLookup,
737
+ flagExpectsValue,
738
+ includesBeforeSeparator,
739
+ parse,
740
+ stripBeforeSeparator,
741
+ tokenize,
742
+ };
@@ -148,9 +148,11 @@ const PROMPT_CANCEL: unique symbol = Symbol.for('dreamcli.prompt.cancel') as typ
148
148
  * A queued answer consumed by {@link createTestPrompter}.
149
149
  *
150
150
  * The test prompter returns these values exactly as provided; it does not
151
- * coerce or validate them. The normal resolution pipeline performs any later
152
- * type coercion, so tests can supply values in the same shapes real prompts
153
- * would yield:
151
+ * coerce them. The one exception mirrors the terminal prompter: a string answer
152
+ * to an `input` prompt is run through the prompt's `validate` function, and a
153
+ * failing answer is rejected as a cancellation (see {@link createTestPrompter}).
154
+ * The normal resolution pipeline performs any later type coercion, so tests can
155
+ * supply values in the same shapes real prompts would yield:
154
156
  *
155
157
  * - `string` for `input` and `select`
156
158
  * - `boolean` for `confirm`
@@ -186,6 +188,12 @@ interface TestPrompterOptions {
186
188
  * Pass `PROMPT_CANCEL` as an answer to simulate the user cancelling
187
189
  * that prompt.
188
190
  *
191
+ * For `input` prompts that declare a `validate` function, a string answer is
192
+ * validated just as the terminal prompter does. An answer that fails validation
193
+ * is rejected as a cancellation (`{ answered: false }`) — mirroring the terminal
194
+ * prompter exhausting its retries — so prompt validation is integration-testable
195
+ * via {@linkcode runCommand} rather than silently accepted as the resolved value.
196
+ *
189
197
  * @param answers - Ordered queue of answers. Use `PROMPT_CANCEL` for
190
198
  * cancellation.
191
199
  * @param options - Controls behavior when the queue is exhausted.
@@ -206,7 +214,7 @@ function createTestPrompter(
206
214
  ): PromptEngine {
207
215
  let index = 0;
208
216
  return {
209
- promptOne(): Promise<PromptResult> {
217
+ promptOne(config): Promise<PromptResult> {
210
218
  if (index >= answers.length) {
211
219
  if (options?.onExhausted === 'cancel') {
212
220
  return Promise.resolve({ answered: false });
@@ -222,6 +230,20 @@ function createTestPrompter(
222
230
  if (answer === PROMPT_CANCEL) {
223
231
  return Promise.resolve({ answered: false });
224
232
  }
233
+ // Mirror the terminal prompter's `input` contract: run `config.validate`
234
+ // against the queued answer so prompt validation is integration-testable
235
+ // (#36). A failing answer is rejected the way the terminal prompter
236
+ // rejects after exhausting its retries — as a cancellation — so the
237
+ // resolution pipeline surfaces it (required-flag error / default
238
+ // fallback) instead of injecting the invalid value verbatim. Only
239
+ // `input` prompts carry a validator and only string answers are the
240
+ // shape the terminal prompter would ever validate; non-string answers
241
+ // stay verbatim so downstream coercion paths remain testable.
242
+ if (config.kind === 'input' && config.validate !== undefined && typeof answer === 'string') {
243
+ if (config.validate(answer) !== true) {
244
+ return Promise.resolve({ answered: false });
245
+ }
246
+ }
225
247
  return Promise.resolve({ answered: true, value: answer });
226
248
  },
227
249
  };
@@ -283,10 +305,11 @@ const MAX_RETRIES = 10;
283
305
  /**
284
306
  * Confirm prompt: yes/no question.
285
307
  *
286
- * Displays `(Y/n)` because empty input defaults to yes.
287
- * Accepts: y, yes, n, no, empty (uses default). Case-insensitive.
308
+ * The hint reflects {@link ConfirmPromptConfig.default}: `(Y/n)` when the
309
+ * default is `true` (or unset), `(y/N)` when `false`. An empty submission
310
+ * resolves to that default. Accepts: y, yes, n, no, empty. Case-insensitive.
288
311
  *
289
- * @param config - {@link ConfirmPromptConfig} with the question message
312
+ * @param config - {@link ConfirmPromptConfig} with the question message and optional default
290
313
  * @param read - {@link ReadFn} for reading a line of user input
291
314
  * @param write - {@link WriteFn} for rendering prompt text
292
315
  * @returns Resolved {@link PromptResult} — `true`/`false` value, or cancelled on EOF
@@ -296,7 +319,7 @@ async function promptConfirm(
296
319
  read: ReadFn,
297
320
  write: WriteFn,
298
321
  ): Promise<PromptResult> {
299
- const defaultValue = true;
322
+ const defaultValue = config.default ?? true;
300
323
  let retries = 0;
301
324
 
302
325
  while (retries < MAX_RETRIES) {
@@ -328,13 +351,17 @@ async function promptConfirm(
328
351
  /**
329
352
  * Input prompt: free-text string entry.
330
353
  *
331
- * Displays the message, reads a line, and optionally validates via
332
- * `config.validate`. Loops on invalid input up to `MAX_RETRIES`.
354
+ * Displays the message and a hint listing the placeholder and/or
355
+ * {@link InputPromptConfig.default | default}, reads a line, and optionally
356
+ * validates via {@link InputPromptConfig.validate | validate}. When a default
357
+ * is configured, an empty submission resolves to it without running validation;
358
+ * otherwise an empty submission is returned verbatim (and treated as "no answer"
359
+ * by the resolver). Loops on invalid input up to `MAX_RETRIES`.
333
360
  *
334
- * @param config - {@link InputPromptConfig} with message, optional placeholder and validator
361
+ * @param config - {@link InputPromptConfig} with message, optional placeholder, default, and validator
335
362
  * @param read - {@link ReadFn} for reading a line of user input
336
363
  * @param write - {@link WriteFn} for rendering prompt text and validation errors
337
- * @returns Resolved {@link PromptResult} — trimmed string value, or cancelled on EOF/exhausted retries
364
+ * @returns Resolved {@link PromptResult} — trimmed string value (or default), or cancelled on EOF/exhausted retries
338
365
  */
339
366
  async function promptInput(
340
367
  config: InputPromptConfig,
@@ -343,15 +370,28 @@ async function promptInput(
343
370
  ): Promise<PromptResult> {
344
371
  let retries = 0;
345
372
 
373
+ const hints: string[] = [];
374
+ if (config.placeholder !== undefined) hints.push(config.placeholder);
375
+ if (config.default !== undefined) hints.push(`default: ${config.default}`);
376
+ const hint = hints.length > 0 ? ` (${hints.join(', ')})` : '';
377
+
346
378
  while (retries < MAX_RETRIES) {
347
- const placeholder = config.placeholder !== undefined ? ` (${config.placeholder})` : '';
348
- write(`${config.message}${placeholder}: `);
379
+ write(`${config.message}${hint}: `);
349
380
 
350
381
  const line = await read();
351
382
  if (line === null) return { answered: false };
352
383
 
353
384
  const trimmed = line.trim();
354
385
 
386
+ // An empty submission is the absence of a value, not a value to validate:
387
+ // resolve to the configured default, else return blank so the resolver can
388
+ // treat it as "no answer" and fall through to the flag's own default.
389
+ if (trimmed === '') {
390
+ return config.default !== undefined
391
+ ? { answered: true, value: config.default }
392
+ : { answered: true, value: '' };
393
+ }
394
+
355
395
  if (config.validate !== undefined) {
356
396
  const result = config.validate(trimmed);
357
397
  if (result !== true) {
@@ -7,7 +7,11 @@
7
7
 
8
8
  import type { ValidationErrorCode } from '#internals/core/errors/index.ts';
9
9
  import { ValidationError } from '#internals/core/errors/index.ts';
10
- import type { ArgSchema, FlagSchema } from '#internals/core/schema/index.ts';
10
+ import type { ArgSchema, FlagSchema, NumberConstraints } from '#internals/core/schema/index.ts';
11
+ import {
12
+ describeNumberConstraintViolation,
13
+ validateNumberConstraints,
14
+ } from '#internals/core/schema/index.ts';
11
15
  import type { ArgDiagnosticSource, FlagDiagnosticSource } from './contracts.ts';
12
16
  import type { SharedPropertySchema } from './property.ts';
13
17
  import { toSharedArgPropertySchema, toSharedFlagPropertySchema } from './property.ts';
@@ -61,6 +65,51 @@ function coercionError(
61
65
  };
62
66
  }
63
67
 
68
+ /**
69
+ * Apply numeric constraints to an already-parsed number. Shares the single
70
+ * {@link validateNumberConstraints} check used by the parse path, so the two
71
+ * boundaries cannot drift. On violation, returns a `CONSTRAINT_VIOLATED`
72
+ * failure; the human-readable reason is also surfaced in `details.constraint`
73
+ * (the violation kind) and the message suffix.
74
+ */
75
+ function finalizeNumber(
76
+ flagName: string,
77
+ source: CoerceSource,
78
+ raw: unknown,
79
+ value: number,
80
+ constraints: NumberConstraints | undefined,
81
+ ): CoerceResult {
82
+ const violation = validateNumberConstraints(value, constraints);
83
+ if (violation === undefined) {
84
+ return { ok: true, value };
85
+ }
86
+
87
+ const reason = describeNumberConstraintViolation(violation);
88
+ return {
89
+ ok: false,
90
+ error: new ValidationError(
91
+ `Invalid number value '${String(raw)}' ${sourceLabel(source)} for flag --${flagName}: ${reason}`,
92
+ {
93
+ code: 'CONSTRAINT_VIOLATED',
94
+ details: {
95
+ flag: flagName,
96
+ ...sourceDetails(source),
97
+ value: raw,
98
+ expected: 'number',
99
+ constraint: violation.kind,
100
+ ...('bound' in violation ? { bound: violation.bound } : {}),
101
+ },
102
+ suggest:
103
+ source.kind === 'env'
104
+ ? `Set ${source.envVar} to a valid number`
105
+ : source.kind === 'config'
106
+ ? `Set ${source.configPath} to a valid number in your config`
107
+ : `Enter a valid number for --${flagName}`,
108
+ },
109
+ ),
110
+ };
111
+ }
112
+
64
113
  /** Coerce a raw value from env/config/prompt into the type declared by a flag schema. */
65
114
  function coerceValue(
66
115
  flagName: string,
@@ -200,11 +249,13 @@ function coerceSharedPropertyValue(
200
249
  : `Enter a valid number for --${flagName}`,
201
250
  );
202
251
  }
203
- return { ok: true, value: raw };
252
+ return finalizeNumber(flagName, source, raw, raw, schema.numberConstraints);
204
253
  }
205
254
  if (typeof raw === 'string') {
206
255
  const value = Number(raw);
207
- if (!Number.isNaN(value)) return { ok: true, value };
256
+ if (!Number.isNaN(value)) {
257
+ return finalizeNumber(flagName, source, raw, value, schema.numberConstraints);
258
+ }
208
259
  }
209
260
  return coercionError(
210
261
  flagName,
@@ -322,8 +373,19 @@ function redactArgCoercionMessage(
322
373
  error: ValidationError,
323
374
  ): string {
324
375
  switch (schema.kind) {
325
- case 'number':
326
- return `Invalid number value '<redacted>' ${argSourceLabel(source)} for argument <${argName}>`;
376
+ case 'number': {
377
+ const base = `Invalid number value '<redacted>' ${argSourceLabel(source)} for argument <${argName}>`;
378
+ // Only a constraint violation carries a schema-derived reason suffix
379
+ // (e.g. `: must be >= 0`), which is safe to keep. Any other failure
380
+ // (e.g. TYPE_MISMATCH) embeds the raw value in `error.message`, so
381
+ // extracting a trailing suffix there could leak user input.
382
+ if (error.code !== 'CONSTRAINT_VIOLATED') {
383
+ return base;
384
+ }
385
+ const match = /: ([^:]+)$/.exec(error.message);
386
+ const suffix = match?.[1];
387
+ return suffix !== undefined ? `${base}: ${suffix}` : base;
388
+ }
327
389
  case 'enum': {
328
390
  const allowed = Array.isArray(error.details?.allowed)
329
391
  ? error.details.allowed.filter((value): value is string => typeof value === 'string')
@@ -356,6 +418,12 @@ function redactArgCoercionDetails(
356
418
  arg: argName,
357
419
  ...argSourceDetails(source),
358
420
  ...(schema.kind === 'number' || schema.kind === 'custom' ? { expected: schema.kind } : {}),
421
+ ...(schema.kind === 'number' && typeof error.details?.constraint === 'string'
422
+ ? { constraint: error.details.constraint }
423
+ : {}),
424
+ ...(schema.kind === 'number' && typeof error.details?.bound === 'number'
425
+ ? { bound: error.details.bound }
426
+ : {}),
359
427
  ...(schema.kind === 'enum' && Array.isArray(error.details?.allowed)
360
428
  ? {
361
429
  allowed: error.details.allowed.filter(
@@ -227,6 +227,20 @@ async function resolvePromptValueWithConfig(
227
227
  return { ok: false, error: undefined };
228
228
  }
229
229
 
230
+ // An empty/blank `input` answer with no prompt-level default is not a real
231
+ // answer — fall through (ok: false) so resolution reaches the flag's
232
+ // `.default()`. When a prompt-level default exists, the prompt engine has
233
+ // already applied it (so the value is the default, not blank), giving it
234
+ // precedence over the flag default.
235
+ if (
236
+ promptConfig.kind === 'input' &&
237
+ promptConfig.default === undefined &&
238
+ typeof result.value === 'string' &&
239
+ result.value.trim() === ''
240
+ ) {
241
+ return { ok: false, error: undefined };
242
+ }
243
+
230
244
  return coerceValue(flagName, { kind: 'prompt' }, result.value, schema);
231
245
  }
232
246