@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.11

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 (194) hide show
  1. package/CHANGELOG.md +227 -1
  2. package/dist/core/cli/dispatch.d.mts +6 -5
  3. package/dist/core/cli/dispatch.mjs +205 -1
  4. package/dist/core/cli/help-links.d.mts +0 -1
  5. package/dist/core/cli/help-links.mjs +41 -1
  6. package/dist/core/cli/index.d.mts +81 -8
  7. package/dist/core/cli/index.mjs +945 -1
  8. package/dist/core/cli/planner.d.mts +5 -1
  9. package/dist/core/cli/planner.mjs +300 -1
  10. package/dist/core/cli/plugin.d.mts +1 -1
  11. package/dist/core/cli/plugin.mjs +41 -1
  12. package/dist/core/cli/propagate.d.mts +1 -1
  13. package/dist/core/cli/propagate.mjs +57 -1
  14. package/dist/core/cli/root-help.d.mts +2 -1
  15. package/dist/core/cli/root-help.mjs +226 -4
  16. package/dist/core/cli/root-surface.d.mts +12 -1
  17. package/dist/core/cli/root-surface.mjs +28 -1
  18. package/dist/core/cli/runtime-preflight.d.mts +14 -2
  19. package/dist/core/cli/runtime-preflight.mjs +169 -1
  20. package/dist/core/completion/index.d.mts +0 -1
  21. package/dist/core/completion/index.mjs +90 -1
  22. package/dist/core/completion/shells/bash.d.mts +0 -1
  23. package/dist/core/completion/shells/bash.mjs +308 -3
  24. package/dist/core/completion/shells/fish.d.mts +0 -1
  25. package/dist/core/completion/shells/fish.mjs +162 -2
  26. package/dist/core/completion/shells/powershell.d.mts +0 -1
  27. package/dist/core/completion/shells/powershell.mjs +358 -2
  28. package/dist/core/completion/shells/shared.d.mts +13 -2
  29. package/dist/core/completion/shells/shared.mjs +176 -1
  30. package/dist/core/completion/shells/zsh.d.mts +0 -1
  31. package/dist/core/completion/shells/zsh.mjs +251 -2
  32. package/dist/core/config/index.d.mts +2 -3
  33. package/dist/core/config/index.mjs +246 -1
  34. package/dist/core/config/package-json.d.mts +27 -4
  35. package/dist/core/config/package-json.mjs +386 -3
  36. package/dist/core/errors/index.d.mts +3 -3
  37. package/dist/core/errors/index.mjs +87 -1
  38. package/dist/core/execution/index.d.mts +0 -1
  39. package/dist/core/execution/index.mjs +201 -1
  40. package/dist/core/help/ansi.d.mts +11 -5
  41. package/dist/core/help/ansi.mjs +121 -2
  42. package/dist/core/help/index.d.mts +22 -3
  43. package/dist/core/help/index.mjs +341 -7
  44. package/dist/core/help/theme.d.mts +68 -0
  45. package/dist/core/help/theme.mjs +46 -0
  46. package/dist/core/json-schema/index.d.mts +15 -2
  47. package/dist/core/json-schema/index.mjs +536 -12
  48. package/dist/core/json-schema/meta-descriptions.generated.d.mts +55 -38
  49. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  50. package/dist/core/output/activity.d.mts +0 -1
  51. package/dist/core/output/activity.mjs +452 -1
  52. package/dist/core/output/bind.mjs +56 -1
  53. package/dist/core/output/contracts.d.mts +4 -5
  54. package/dist/core/output/contracts.mjs +57 -1
  55. package/dist/core/output/display-value.mjs +32 -1
  56. package/dist/core/output/index.d.mts +21 -1
  57. package/dist/core/output/index.mjs +442 -2
  58. package/dist/core/output/renderers.d.mts +0 -1
  59. package/dist/core/output/renderers.mjs +46 -1
  60. package/dist/core/output/writer.mjs +12 -1
  61. package/dist/core/parse/index.d.mts +40 -7
  62. package/dist/core/parse/index.mjs +727 -1
  63. package/dist/core/prompt/index.d.mts +1 -1
  64. package/dist/core/prompt/index.mjs +348 -6
  65. package/dist/core/resolve/args.d.mts +1 -1
  66. package/dist/core/resolve/args.mjs +105 -1
  67. package/dist/core/resolve/coerce.d.mts +1 -1
  68. package/dist/core/resolve/coerce.mjs +336 -1
  69. package/dist/core/resolve/config.mjs +19 -1
  70. package/dist/core/resolve/contracts.d.mts +9 -4
  71. package/dist/core/resolve/errors.d.mts +0 -1
  72. package/dist/core/resolve/errors.mjs +140 -2
  73. package/dist/core/resolve/flags.d.mts +7 -2
  74. package/dist/core/resolve/flags.mjs +251 -1
  75. package/dist/core/resolve/index.d.mts +2 -2
  76. package/dist/core/resolve/index.mjs +85 -1
  77. package/dist/core/resolve/property.d.mts +4 -2
  78. package/dist/core/resolve/property.mjs +53 -1
  79. package/dist/core/schema/activity.d.mts +31 -11
  80. package/dist/core/schema/arg.d.mts +3 -4
  81. package/dist/core/schema/arg.mjs +463 -1
  82. package/dist/core/schema/command.d.mts +26 -6
  83. package/dist/core/schema/command.mjs +726 -1
  84. package/dist/core/schema/flag.d.mts +485 -19
  85. package/dist/core/schema/flag.mjs +705 -1
  86. package/dist/core/schema/index.d.mts +4 -2
  87. package/dist/core/schema/middleware.d.mts +4 -3
  88. package/dist/core/schema/middleware.mjs +41 -1
  89. package/dist/core/schema/number-constraints.mjs +60 -1
  90. package/dist/core/schema/prompt.d.mts +6 -3
  91. package/dist/core/schema/run.d.mts +20 -1
  92. package/dist/core/schema/string-constraints.d.mts +97 -0
  93. package/dist/core/schema/string-constraints.mjs +69 -0
  94. package/dist/core/schema/value-parsers.d.mts +78 -0
  95. package/dist/core/schema/value-parsers.mjs +142 -0
  96. package/dist/core/schema-dsl/runtime.mjs +271 -2
  97. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  98. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  99. package/dist/core/testkit/index.d.mts +0 -31
  100. package/dist/core/testkit/index.mjs +83 -1
  101. package/dist/index.d.mts +11 -6
  102. package/dist/index.mjs +22 -1
  103. package/dist/runtime/adapter.d.mts +38 -2
  104. package/dist/runtime/adapter.mjs +87 -1
  105. package/dist/runtime/auto.d.mts +2 -3
  106. package/dist/runtime/auto.mjs +45 -1
  107. package/dist/runtime/deno.d.mts +24 -5
  108. package/dist/runtime/deno.mjs +262 -2
  109. package/dist/runtime/detect.mjs +45 -1
  110. package/dist/runtime/index.d.mts +3 -4
  111. package/dist/runtime/node.d.mts +8 -2
  112. package/dist/runtime/node.mjs +220 -2
  113. package/dist/runtime/paths.mjs +48 -1
  114. package/dist/runtime.d.mts +4 -4
  115. package/dist/runtime.mjs +6 -1
  116. package/dist/strings.mjs +22 -1
  117. package/dist/testkit.d.mts +1 -0
  118. package/dist/testkit.mjs +5 -1
  119. package/dist/version.d.mts +7 -3
  120. package/dist/version.mjs +7 -1
  121. package/dreamcli.schema.json +36 -7
  122. package/package.json +45 -42
  123. package/dist/runtime/bun.d.mts +0 -28
  124. package/dist/runtime/bun.mjs +0 -1
  125. package/src/core/cli/dispatch.ts +0 -355
  126. package/src/core/cli/help-links.ts +0 -82
  127. package/src/core/cli/index.ts +0 -1614
  128. package/src/core/cli/planner.ts +0 -656
  129. package/src/core/cli/plugin.ts +0 -117
  130. package/src/core/cli/propagate.ts +0 -97
  131. package/src/core/cli/root-help.ts +0 -342
  132. package/src/core/cli/root-surface.ts +0 -87
  133. package/src/core/cli/runtime-preflight.ts +0 -456
  134. package/src/core/completion/index.ts +0 -138
  135. package/src/core/completion/shells/bash.ts +0 -459
  136. package/src/core/completion/shells/fish.ts +0 -259
  137. package/src/core/completion/shells/powershell.ts +0 -439
  138. package/src/core/completion/shells/shared.ts +0 -310
  139. package/src/core/completion/shells/zsh.ts +0 -381
  140. package/src/core/config/index.ts +0 -417
  141. package/src/core/config/package-json.ts +0 -560
  142. package/src/core/errors/index.ts +0 -193
  143. package/src/core/execution/index.ts +0 -265
  144. package/src/core/help/ansi.ts +0 -144
  145. package/src/core/help/index.ts +0 -563
  146. package/src/core/json-schema/index.ts +0 -910
  147. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  148. package/src/core/output/activity.ts +0 -575
  149. package/src/core/output/bind.ts +0 -59
  150. package/src/core/output/contracts.ts +0 -194
  151. package/src/core/output/display-value.ts +0 -48
  152. package/src/core/output/index.ts +0 -704
  153. package/src/core/output/renderers.ts +0 -125
  154. package/src/core/output/writer.ts +0 -46
  155. package/src/core/parse/index.ts +0 -742
  156. package/src/core/prompt/index.ts +0 -623
  157. package/src/core/resolve/args.ts +0 -144
  158. package/src/core/resolve/coerce.ts +0 -500
  159. package/src/core/resolve/config.ts +0 -26
  160. package/src/core/resolve/contracts.ts +0 -135
  161. package/src/core/resolve/errors.ts +0 -227
  162. package/src/core/resolve/flags.ts +0 -269
  163. package/src/core/resolve/index.ts +0 -108
  164. package/src/core/resolve/property.ts +0 -99
  165. package/src/core/schema/activity.ts +0 -240
  166. package/src/core/schema/arg.ts +0 -841
  167. package/src/core/schema/command.ts +0 -1500
  168. package/src/core/schema/flag.ts +0 -917
  169. package/src/core/schema/index.ts +0 -96
  170. package/src/core/schema/middleware.ts +0 -171
  171. package/src/core/schema/number-constraints.ts +0 -153
  172. package/src/core/schema/prompt.ts +0 -171
  173. package/src/core/schema/run.ts +0 -198
  174. package/src/core/schema-dsl/index.ts +0 -109
  175. package/src/core/schema-dsl/parse.ts +0 -262
  176. package/src/core/schema-dsl/runtime.ts +0 -609
  177. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  178. package/src/core/testkit/index.ts +0 -147
  179. package/src/index.ts +0 -181
  180. package/src/runtime/adapter.ts +0 -303
  181. package/src/runtime/auto.ts +0 -86
  182. package/src/runtime/bun.ts +0 -48
  183. package/src/runtime/deno.ts +0 -367
  184. package/src/runtime/detect.ts +0 -105
  185. package/src/runtime/index.ts +0 -21
  186. package/src/runtime/node-builtins.d.ts +0 -27
  187. package/src/runtime/node.ts +0 -289
  188. package/src/runtime/paths.ts +0 -64
  189. package/src/runtime/support.ts +0 -77
  190. package/src/runtime.ts +0 -31
  191. package/src/schema.ts +0 -16
  192. package/src/strings.ts +0 -34
  193. package/src/testkit.ts +0 -25
  194. package/src/version.ts +0 -20
@@ -1,917 +0,0 @@
1
- /**
2
- * Flag schema builder with full type inference.
3
- *
4
- * Each factory (`flag.string()`, `flag.boolean()`, etc.) returns an immutable
5
- * {@linkcode FlagBuilder} whose generic parameter tracks the value type and presence
6
- * state. Chained modifiers (`.default()`, `.required()`, `.alias()`, …) return
7
- * new builders with updated type-level and runtime state.
8
- *
9
- * @module dreamcli/core/schema/flag
10
- */
11
-
12
- import { assertNumberConstraints, type NumberConstraints } from './number-constraints.ts';
13
- import type {
14
- ConfirmPromptConfig,
15
- InputPromptConfig,
16
- MultiselectPromptConfig,
17
- PromptConfig,
18
- SelectPromptConfig,
19
- } from './prompt.ts';
20
-
21
- // --- Type-level configuration (phantom state tracked through the chain)
22
-
23
- /** All flag presence states as a runtime array. */
24
- const FLAG_PRESENCES = ['optional', 'required', 'defaulted'] as const;
25
-
26
- /**
27
- * Presence describes whether a flag value is guaranteed to exist when the
28
- * action handler runs:
29
- *
30
- * - `'optional'` — not required; unresolved value follows the kind-specific
31
- * optional fallback (`undefined` for most flags, `[]` for arrays)
32
- * - `'required'` — must be supplied; error if missing
33
- * - `'defaulted'` — always present (falls back to default value)
34
- */
35
- type FlagPresence = (typeof FLAG_PRESENCES)[number];
36
-
37
- /**
38
- * Fallback behavior when an optional flag resolves no value from any source.
39
- *
40
- * Most optional flags resolve to `undefined`; array flags instead resolve to
41
- * an empty array `[]`.
42
- */
43
- type OptionalFallback = 'undefined' | 'empty-array';
44
-
45
- /**
46
- * Compile-time state carried through the builder chain.
47
- *
48
- * Adding new tracked properties only requires extending this interface — no
49
- * builder signature changes.
50
- */
51
- interface FlagConfig {
52
- /** The resolved value type (e.g. `string`, `number`, `'us' | 'eu'`). */
53
- readonly valueType: unknown;
54
- /** Whether the flag is optional, required, or has a default. */
55
- readonly presence: FlagPresence;
56
- /** What an unresolved optional flag becomes at the action boundary. */
57
- readonly optionalFallback: OptionalFallback;
58
- /** The runtime kind discriminator, mirroring {@link FlagKind}. */
59
- readonly flagKind: FlagKind;
60
- }
61
-
62
- // --- Type-level helpers
63
-
64
- /**
65
- * Advanced type helper used by {@linkcode FlagBuilder} modifiers to replace presence.
66
- * Most consumers rely on inference and never reference this directly.
67
- */
68
- type WithPresence<C extends FlagConfig, P extends FlagPresence> = {
69
- readonly valueType: C['valueType'];
70
- readonly presence: P;
71
- readonly optionalFallback: C['optionalFallback'];
72
- readonly flagKind: C['flagKind'];
73
- };
74
-
75
- /**
76
- * Compute the final value type from config — this is what handlers receive.
77
- *
78
- * Advanced type helper: this powers {@link InferFlag} and action-handler
79
- * inference. Most apps do not need to mention it explicitly.
80
- *
81
- * - `'optional'` + `'undefined'` fallback → `T | undefined`
82
- * - `'optional'` + `'empty-array'` fallback → `T`
83
- * - `'required'` → `T`
84
- * - `'defaulted'` → `T`
85
- */
86
- type ResolvedValue<C extends FlagConfig> = C['presence'] extends 'optional'
87
- ? C['optionalFallback'] extends 'empty-array'
88
- ? C['valueType']
89
- : C['valueType'] | undefined
90
- : C['valueType'];
91
-
92
- /** Extract the resolved value type from a {@linkcode FlagBuilder}. */
93
- type InferFlag<B> = B extends FlagBuilder<infer C extends FlagConfig> ? ResolvedValue<C> : never;
94
-
95
- /** Extract resolved value types from a record of builders. */
96
- type InferFlags<T extends Record<string, FlagBuilder<FlagConfig>>> = {
97
- [K in keyof T]: InferFlag<T[K]>;
98
- };
99
-
100
- /**
101
- * Maps a {@linkcode FlagConfig} to the prompt config types that are compatible
102
- * with the flag's kind. Prevents compile-time mismatches such as
103
- * `flag.enum([…]).prompt({ kind: 'multiselect' })`.
104
- *
105
- * - `'boolean'` → {@link ConfirmPromptConfig}
106
- * - `'string'` → {@link InputPromptConfig} | {@link SelectPromptConfig}
107
- * - `'number'` → {@link InputPromptConfig}
108
- * - `'enum'` → {@link SelectPromptConfig} | {@link InputPromptConfig}
109
- * - `'array'` → {@link MultiselectPromptConfig}
110
- * - `'custom'` → all prompt kinds ({@link PromptConfig})
111
- */
112
- type PromptConfigByFlagKind = {
113
- readonly string: InputPromptConfig | SelectPromptConfig;
114
- readonly number: InputPromptConfig;
115
- readonly boolean: ConfirmPromptConfig;
116
- readonly enum: SelectPromptConfig | InputPromptConfig;
117
- readonly array: MultiselectPromptConfig;
118
- readonly custom: PromptConfig;
119
- };
120
-
121
- type AllowedPromptConfig<C extends FlagConfig> = PromptConfigByFlagKind[C['flagKind']];
122
-
123
- // --- Runtime schema data
124
-
125
- /** All flag kind discriminators as a runtime array. */
126
- const FLAG_KINDS = ['string', 'number', 'boolean', 'enum', 'array', 'custom'] as const;
127
-
128
- /** Discriminator for the kind of value a flag accepts. */
129
- type FlagKind = (typeof FLAG_KINDS)[number];
130
-
131
- /**
132
- * Custom parse function for `flag.custom()`.
133
- *
134
- * Receives `string` from CLI argv and env vars, or any JSON-representable
135
- * value from config files. Narrow inside the function as needed.
136
- */
137
- type FlagParseFn<T> = (raw: unknown) => T;
138
-
139
- /** Runtime descriptor for a flag alias. */
140
- interface FlagAlias {
141
- /** Alias name without `-` / `--` prefix. */
142
- readonly name: string;
143
- /** Whether the alias is parser-only and hidden from user-facing surfaces. */
144
- readonly hidden: boolean;
145
- }
146
-
147
- /**
148
- * The runtime descriptor stored inside every {@linkcode FlagBuilder}. Consumers (parser,
149
- * help generator, resolution chain) read this to understand the flag's shape
150
- * without touching generics.
151
- */
152
- interface FlagSchema {
153
- /** What kind of value this flag accepts. */
154
- readonly kind: FlagKind;
155
- /** Current presence state. */
156
- readonly presence: FlagPresence;
157
- /** Runtime default value (if any). */
158
- readonly defaultValue: unknown;
159
- /** Short/long aliases (e.g. `[{ name: 'f', hidden: false }]` for `--force`). */
160
- readonly aliases: readonly FlagAlias[];
161
- /** Environment variable name for v0.2+ resolution. */
162
- readonly envVar: string | undefined;
163
- /** Dotted config path for v0.2+ resolution (e.g. `'deploy.region'`). */
164
- readonly configPath: string | undefined;
165
- /** Human-readable description for help text. */
166
- readonly description: string | undefined;
167
- /** Allowed literal values when `kind === 'enum'`. */
168
- readonly enumValues: readonly string[] | undefined;
169
- /**
170
- * Numeric constraints when `kind === 'number'` (`undefined` otherwise).
171
- *
172
- * Enforced at the parse and resolution boundaries. `finite` defaults to
173
- * `true`, so `Infinity` is rejected even when no constraints object is set.
174
- */
175
- readonly numberConstraints: NumberConstraints | undefined;
176
- /** Element schema when `kind === 'array'`. */
177
- readonly elementSchema: FlagSchema | undefined;
178
- /** Interactive prompt configuration for v0.3+ resolution. */
179
- readonly prompt: PromptConfig | undefined;
180
- /** Custom parse function (only when `kind === 'custom'`). */
181
- readonly parseFn: FlagParseFn<unknown> | undefined;
182
- /**
183
- * Deprecation marker.
184
- *
185
- * - `undefined` — not deprecated (default)
186
- * - `true` — deprecated with no migration message
187
- * - `string` — deprecated with a reason/migration message
188
- *
189
- * When a deprecated flag is used, a warning is emitted to stderr.
190
- * Help text shows `[deprecated]` or `[deprecated: <reason>]`.
191
- */
192
- readonly deprecated: string | true | undefined;
193
- /**
194
- * Whether this flag propagates to subcommands in nested command trees.
195
- *
196
- * When `true`, the flag is automatically available to all descendant
197
- * commands. A child command that defines a flag with the same name
198
- * shadows the propagated parent flag.
199
- *
200
- * @defaultValue `false`
201
- */
202
- readonly propagate: boolean;
203
- }
204
-
205
- /**
206
- * Low-level overrides accepted by {@link createSchema}.
207
- *
208
- * `aliases` accepts both legacy string input and structured {@link FlagAlias}
209
- * objects so tests and internal fixtures can be migrated incrementally.
210
- */
211
- type FlagSchemaOverrides = Omit<Partial<FlagSchema>, 'aliases'> & {
212
- readonly aliases?: readonly (string | FlagAlias)[];
213
- };
214
-
215
- /**
216
- * Normalise an alias input into a full {@link FlagAlias} object.
217
- *
218
- * @param alias - Raw alias name or structured alias object.
219
- * @returns Normalised alias record.
220
- */
221
- function normalizeFlagAlias(alias: string | FlagAlias): FlagAlias {
222
- if (typeof alias === 'string') {
223
- return { name: alias, hidden: false };
224
- }
225
-
226
- return {
227
- name: alias.name,
228
- hidden: alias.hidden,
229
- };
230
- }
231
-
232
- /**
233
- * Normalise alias input into immutable alias records.
234
- *
235
- * @param aliases - Alias input values.
236
- * @returns Normalised alias objects.
237
- */
238
- function normalizeFlagAliases(aliases: readonly (string | FlagAlias)[]): readonly FlagAlias[] {
239
- return aliases.map(normalizeFlagAlias);
240
- }
241
-
242
- /**
243
- * List alias names for a flag schema.
244
- *
245
- * @param schema - Flag schema whose aliases should be listed.
246
- * @param options - Visibility and length filtering.
247
- * @returns Alias names in registration order.
248
- */
249
- function getFlagAliasNames(
250
- schema: FlagSchema,
251
- options?: {
252
- readonly includeHidden?: boolean;
253
- readonly kind?: 'all' | 'short' | 'long';
254
- },
255
- ): readonly string[] {
256
- const includeHidden = options?.includeHidden ?? false;
257
- const kind = options?.kind ?? 'all';
258
-
259
- return schema.aliases
260
- .filter((alias) => includeHidden || !alias.hidden)
261
- .filter((alias) => {
262
- if (kind === 'short') return alias.name.length === 1;
263
- if (kind === 'long') return alias.name.length > 1;
264
- return true;
265
- })
266
- .map((alias) => alias.name);
267
- }
268
-
269
- /**
270
- * Create a raw {@link FlagSchema} object with sensible defaults.
271
- *
272
- * Most consumers should prefer the higher-level {@link flag} factory,
273
- * which returns an immutable {@link FlagBuilder} with type inference and
274
- * safe modifier chaining. `createSchema()` is the low-level escape hatch
275
- * for advanced schema composition, tests, or custom factories that need to
276
- * work directly with the runtime descriptor.
277
- *
278
- * `overrides` are shallow-merged on top of the default shape, so callers are
279
- * responsible for keeping the resulting schema internally consistent.
280
- *
281
- * @param kind - Discriminator for the value type this flag accepts.
282
- * @param overrides - Partial {@link FlagSchema} fields merged onto defaults.
283
- * @returns A fully populated {@link FlagSchema}.
284
- *
285
- * @example
286
- * ```ts
287
- * const schema = createSchema('enum', {
288
- * enumValues: ['us', 'eu', 'ap'],
289
- * description: 'Deployment region',
290
- * });
291
- * ```
292
- */
293
- function createSchema(kind: FlagKind, overrides?: FlagSchemaOverrides): FlagSchema {
294
- const aliases =
295
- overrides?.aliases !== undefined ? normalizeFlagAliases(overrides.aliases) : ([] as const);
296
- const { aliases: _ignoredAliases, ...rest } = overrides ?? {};
297
-
298
- return {
299
- kind,
300
- presence: 'optional',
301
- defaultValue: undefined,
302
- envVar: undefined,
303
- configPath: undefined,
304
- description: undefined,
305
- enumValues: undefined,
306
- numberConstraints: undefined,
307
- elementSchema: undefined,
308
- prompt: undefined,
309
- parseFn: undefined,
310
- deprecated: undefined,
311
- propagate: false,
312
- ...rest,
313
- aliases,
314
- };
315
- }
316
-
317
- // --- FlagBuilder — immutable builder with type-level tracking
318
-
319
- /**
320
- * Immutable flag schema builder.
321
- *
322
- * The type parameter `C` is a phantom that tracks the value type and presence
323
- * through the fluent chain. Each modifier returns a **new** builder — the
324
- * original is never mutated.
325
- *
326
- * @example
327
- * ```ts
328
- * const port = flag.number().default(8080);
329
- * type Port = InferFlag<typeof port>; // number
330
- *
331
- * const region = flag.enum(['us', 'eu', 'ap']);
332
- * type Region = InferFlag<typeof region>; // 'us' | 'eu' | 'ap' | undefined
333
- * ```
334
- */
335
- class FlagBuilder<C extends FlagConfig> {
336
- /** @internal Runtime schema descriptor. */
337
- readonly schema: FlagSchema;
338
-
339
- /**
340
- * @internal Type brand — exists only in the type system (`declare`
341
- * produces no runtime property). Used by {@linkcode InferFlag} / {@linkcode InferFlags}.
342
- */
343
- declare readonly _config: C;
344
-
345
- /**
346
- * Create a flag builder from a pre-built schema descriptor.
347
- *
348
- * @param schema - Runtime descriptor seeding this builder's state.
349
- */
350
- constructor(schema: FlagSchema) {
351
- this.schema = schema;
352
- }
353
-
354
- // -- Presence modifiers --------------------------------------------------
355
-
356
- /**
357
- * Provide a default value. The flag becomes "always present" — handlers
358
- * will never see `undefined`.
359
- *
360
- * The generic constraint `V extends C['valueType']` ensures the default
361
- * matches the flag's declared type.
362
- *
363
- * @param value - Fallback value used when no source provides one.
364
- * @returns The builder (for chaining).
365
- *
366
- * @example
367
- * ```ts
368
- * flag.number().default(8080).describe('Port to listen on')
369
- *
370
- * // $ mycli serve → port = 8080
371
- * // $ mycli serve --port 443 → port = 443
372
- * ```
373
- */
374
- default<V extends C['valueType']>(value: V): FlagBuilder<WithPresence<C, 'defaulted'>> {
375
- return new FlagBuilder({
376
- ...this.schema,
377
- presence: 'defaulted',
378
- defaultValue: value,
379
- });
380
- }
381
-
382
- /**
383
- * Mark the flag as required. If not resolved from any source the framework
384
- * will emit a `ValidationError` before the action handler runs.
385
- *
386
- * @returns The builder (for chaining).
387
- *
388
- * @example
389
- * ```ts
390
- * flag.string().required().describe('Deploy target')
391
- *
392
- * // $ mycli deploy
393
- * // # → Error: Missing required flag --target
394
- * // $ mycli deploy --target staging
395
- * // # → target = 'staging'
396
- * ```
397
- */
398
- required(): FlagBuilder<WithPresence<C, 'required'>> {
399
- return new FlagBuilder({
400
- ...this.schema,
401
- presence: 'required',
402
- });
403
- }
404
-
405
- // -- Metadata modifiers --------------------------------------------------
406
-
407
- /**
408
- * Add a short or long alias (e.g. `'f'` for `--force`, `'verbose'` as an
409
- * alternative long name).
410
- *
411
- * @param name - Single-char short alias or alternative long name.
412
- * @param options - Optional alias metadata. Hidden aliases remain parseable
413
- * but are omitted from help, completions, and suggestions.
414
- * @returns The builder (for chaining).
415
- *
416
- * @example
417
- * ```ts
418
- * flag.boolean().alias('v').describe('Enable verbose output')
419
- *
420
- * // $ mycli build -v → verbose = true
421
- * // $ mycli build --verbose → verbose = true
422
- * ```
423
- */
424
- alias(name: string, options?: { hidden?: boolean }): FlagBuilder<C> {
425
- return new FlagBuilder({
426
- ...this.schema,
427
- aliases: [
428
- ...this.schema.aliases,
429
- {
430
- name,
431
- hidden: options?.hidden ?? false,
432
- },
433
- ],
434
- });
435
- }
436
-
437
- /**
438
- * Bind to an environment variable (resolved in v0.2+).
439
- *
440
- * @param varName - Environment variable name (e.g. `'PORT'`).
441
- * @returns The builder (for chaining).
442
- *
443
- * @example
444
- * ```ts
445
- * flag.string().env('API_KEY').describe('Service API key')
446
- *
447
- * // $ API_KEY=sk-123 mycli request → apiKey = 'sk-123'
448
- * // $ mycli request --api-key sk-456 → apiKey = 'sk-456' (CLI wins)
449
- * ```
450
- */
451
- env(varName: string): FlagBuilder<C> {
452
- return new FlagBuilder({
453
- ...this.schema,
454
- envVar: varName,
455
- });
456
- }
457
-
458
- /**
459
- * Bind to a dotted config path (resolved in v0.2+).
460
- *
461
- * @param path - Dotted config key (e.g. `'deploy.region'`).
462
- * @returns The builder (for chaining).
463
- *
464
- * @example
465
- * ```ts
466
- * flag.string().config('deploy.region').default('us-east-1')
467
- * // Config file: { "deploy": { "region": "eu-west-1" } }
468
- * // $ mycli deploy
469
- * // # → region = 'eu-west-1' (from config)
470
- * // $ mycli deploy --region ap-south-1
471
- * // # → CLI flag wins
472
- * ```
473
- */
474
- config(path: string): FlagBuilder<C> {
475
- return new FlagBuilder({
476
- ...this.schema,
477
- configPath: path,
478
- });
479
- }
480
-
481
- /**
482
- * Human-readable description shown in help output.
483
- *
484
- * @param description - Text displayed next to the flag in `--help`.
485
- * @returns The builder (for chaining).
486
- */
487
- describe(description: string): FlagBuilder<C> {
488
- return new FlagBuilder({
489
- ...this.schema,
490
- description,
491
- });
492
- }
493
-
494
- /**
495
- * Attach interactive prompt configuration for v0.3+ resolution.
496
- *
497
- * When a flag value is not resolved from CLI, env, or config, the
498
- * prompt engine uses this config to interactively ask the user.
499
- * In non-interactive contexts (CI, piped stdin) prompts are skipped
500
- * and resolution falls through to default or required validation.
501
- *
502
- * @param config - {@link PromptConfig} describing the interactive prompt.
503
- * @returns The builder (for chaining).
504
- *
505
- * @example
506
- * ```ts
507
- * flag.string().prompt({ kind: 'input', message: 'Enter value:' })
508
- *
509
- * // $ mycli init → prompts "Enter value:" interactively
510
- * // $ mycli init --name foo → skips prompt, uses CLI value
511
- * ```
512
- */
513
- prompt(config: AllowedPromptConfig<C>): FlagBuilder<C> {
514
- return new FlagBuilder({
515
- ...this.schema,
516
- prompt: config,
517
- });
518
- }
519
-
520
- /**
521
- * Mark this flag as deprecated.
522
- *
523
- * When used, a warning is emitted to stderr. Help text shows
524
- * `[deprecated]` or `[deprecated: <reason>]`.
525
- *
526
- * Does not change the flag's type-level config — it's metadata only.
527
- *
528
- * @param message - Optional migration reason/guidance.
529
- * @returns The builder (for chaining).
530
- *
531
- * @example
532
- * ```ts
533
- * flag.string().deprecated('Use --target instead')
534
- *
535
- * // $ mycli deploy --dest staging
536
- * // ⚠ --dest is deprecated: Use --target instead
537
- * ```
538
- */
539
- deprecated(message?: string): FlagBuilder<C> {
540
- return new FlagBuilder({
541
- ...this.schema,
542
- deprecated: message ?? true,
543
- });
544
- }
545
-
546
- /**
547
- * Mark this flag as propagated to subcommands.
548
- *
549
- * Propagated flags are automatically available to all descendant
550
- * commands in a nested command tree. A child command that defines
551
- * a flag with the same name shadows the propagated parent flag.
552
- *
553
- * Does not change the flag's type-level config — it's metadata only.
554
- *
555
- * @returns The builder (for chaining).
556
- *
557
- * @example
558
- * ```ts
559
- * flag.boolean().alias('v').propagate().describe('Enable verbose output')
560
- *
561
- * // $ mycli --verbose deploy staging
562
- * // # → verbose = true in deploy handler
563
- * // $ mycli deploy --verbose staging
564
- * // # → same, inherited from parent
565
- * ```
566
- */
567
- propagate(): FlagBuilder<C> {
568
- return new FlagBuilder({
569
- ...this.schema,
570
- propagate: true,
571
- });
572
- }
573
-
574
- // -- Numeric constraint modifiers ----------------------------------------
575
- //
576
- // Compile-time guarded via a `this` parameter so they are only callable on
577
- // number-kind builders. They merge onto the single `numberConstraints`
578
- // representation, overriding any value set by `flag.number({ … })`.
579
-
580
- /**
581
- * Require an integer value. Composes with other numeric constraints.
582
- *
583
- * @param value - Whether to require an integer.
584
- * @defaultValue `true`
585
- * @returns The builder (for chaining).
586
- *
587
- * @example
588
- * ```ts
589
- * flag.number().int() // rejects 3.7, accepts 3
590
- * flag.number({ int: true }).int(false) // re-allows non-integers
591
- * ```
592
- */
593
- int(this: FlagBuilder<C & { readonly flagKind: 'number' }>, value = true): FlagBuilder<C> {
594
- return new FlagBuilder({
595
- ...this.schema,
596
- numberConstraints: { ...this.schema.numberConstraints, int: value },
597
- });
598
- }
599
-
600
- /**
601
- * Set an inclusive lower bound. Composes with other numeric constraints;
602
- * a later call overrides an earlier `min` (including one from the options
603
- * object).
604
- *
605
- * @param value - Inclusive minimum.
606
- * @returns The builder (for chaining).
607
- *
608
- * @example
609
- * ```ts
610
- * flag.number().min(0) // rejects -1, accepts 0
611
- * flag.number({ min: 0 }).min(5) // effective min is 5
612
- * ```
613
- */
614
- min(this: FlagBuilder<C & { readonly flagKind: 'number' }>, value: number): FlagBuilder<C> {
615
- const numberConstraints = { ...this.schema.numberConstraints, min: value };
616
- assertNumberConstraints(numberConstraints);
617
- return new FlagBuilder({ ...this.schema, numberConstraints });
618
- }
619
-
620
- /**
621
- * Set an inclusive upper bound. Composes with other numeric constraints;
622
- * a later call overrides an earlier `max`.
623
- *
624
- * @param value - Inclusive maximum.
625
- * @returns The builder (for chaining).
626
- *
627
- * @example
628
- * ```ts
629
- * flag.number().max(100) // rejects 101, accepts 100
630
- * ```
631
- */
632
- max(this: FlagBuilder<C & { readonly flagKind: 'number' }>, value: number): FlagBuilder<C> {
633
- const numberConstraints = { ...this.schema.numberConstraints, max: value };
634
- assertNumberConstraints(numberConstraints);
635
- return new FlagBuilder({ ...this.schema, numberConstraints });
636
- }
637
-
638
- /**
639
- * Require (or, with `false`, allow) a finite value. Finiteness is enforced
640
- * by default, so this is mainly used as `.finite(false)` to re-allow
641
- * `Infinity` / `-Infinity`.
642
- *
643
- * @param allow - Whether to require a finite value.
644
- * @defaultValue `true`
645
- * @returns The builder (for chaining).
646
- *
647
- * @example
648
- * ```ts
649
- * flag.number().finite(false) // accepts Infinity
650
- * ```
651
- */
652
- finite(this: FlagBuilder<C & { readonly flagKind: 'number' }>, allow = true): FlagBuilder<C> {
653
- return new FlagBuilder({
654
- ...this.schema,
655
- numberConstraints: { ...this.schema.numberConstraints, finite: allow },
656
- });
657
- }
658
- }
659
-
660
- // --- Factory namespace
661
-
662
- /**
663
- * Factory that creates {@link FlagBuilder} instances seeded with the correct
664
- * {@link FlagKind} and initial type-level config.
665
- */
666
- interface FlagFactory {
667
- /**
668
- * String-valued flag.
669
- *
670
- * @returns A {@link FlagBuilder} for `string` values.
671
- */
672
- string(): FlagBuilder<{
673
- readonly valueType: string;
674
- readonly presence: 'optional';
675
- readonly optionalFallback: 'undefined';
676
- readonly flagKind: 'string';
677
- }>;
678
-
679
- /**
680
- * Number-valued flag, with optional numeric constraints.
681
- *
682
- * Constraints are enforced at the parse and resolution boundaries. The
683
- * resolved value type stays `number` — constraints are runtime + schema, not
684
- * type-level. Bounds are inclusive.
685
- *
686
- * Constraints also compose via chained methods (`.int()`, `.min()`,
687
- * `.max()`, `.finite()`), which override values set here.
688
- *
689
- * @param constraints - Optional numeric constraints. `finite` defaults to
690
- * `true`, so `Infinity` / `-Infinity` are rejected unless `finite: false`.
691
- * @defaultValue `undefined` (finite-only, no bounds, non-integer allowed)
692
- * @returns A {@link FlagBuilder} for `number` values.
693
- *
694
- * @example
695
- * ```ts
696
- * flag.number() // finite numbers only
697
- * flag.number({ int: true, min: 0 }) // non-negative integers
698
- * flag.number({ finite: false }) // also accepts Infinity
699
- * ```
700
- */
701
- number(constraints?: NumberConstraints): FlagBuilder<{
702
- readonly valueType: number;
703
- readonly presence: 'optional';
704
- readonly optionalFallback: 'undefined';
705
- readonly flagKind: 'number';
706
- }>;
707
-
708
- /**
709
- * Boolean flag. Implicitly defaults to `false` — the only flag kind where
710
- * the absence of a value is still meaningful (not `undefined`).
711
- *
712
- * @returns A {@link FlagBuilder} for `boolean` values (defaulted to `false`).
713
- */
714
- boolean(): FlagBuilder<{
715
- readonly valueType: boolean;
716
- readonly presence: 'defaulted';
717
- readonly optionalFallback: 'undefined';
718
- readonly flagKind: 'boolean';
719
- }>;
720
-
721
- /**
722
- * Enum flag with literal type inference.
723
- *
724
- * Requires a **non-empty** readonly tuple so that `T[number]` produces a
725
- * union of string literals rather than just `string`.
726
- *
727
- * @example
728
- * ```ts
729
- * flag.enum(['us', 'eu', 'ap'])
730
- * // inferred type: 'us' | 'eu' | 'ap'
731
- * ```
732
- *
733
- * @param values - Non-empty tuple of allowed string literals.
734
- * @returns A {@link FlagBuilder} whose value type is the union of `values`.
735
- */
736
- enum<const T extends readonly [string, ...string[]]>(
737
- values: T,
738
- ): FlagBuilder<{
739
- readonly valueType: T[number];
740
- readonly presence: 'optional';
741
- readonly optionalFallback: 'undefined';
742
- readonly flagKind: 'enum';
743
- }>;
744
-
745
- /**
746
- * Array flag — collects multiple values of the same element type.
747
- *
748
- * @example
749
- * ```ts
750
- * flag.array(flag.string())
751
- * // inferred type: string[]
752
- * ```
753
- *
754
- * @param element - {@link FlagBuilder} describing the element type.
755
- * @returns A {@link FlagBuilder} for arrays of the element type.
756
- */
757
- array<E extends FlagConfig>(
758
- element: FlagBuilder<E>,
759
- ): FlagBuilder<{
760
- readonly valueType: E['valueType'][];
761
- readonly presence: 'optional';
762
- readonly optionalFallback: 'empty-array';
763
- readonly flagKind: 'array';
764
- }>;
765
-
766
- /**
767
- * Custom-parsed flag. The parse function receives the raw value and must
768
- * return a value of type `T`. The return type is inferred from `parseFn`.
769
- *
770
- * The input is `string` from CLI argv and env vars, or any JSON value
771
- * from config files. Narrow inside the function as needed:
772
- *
773
- * ```ts
774
- * flag.custom((raw: unknown): string[] => {
775
- * if (Array.isArray(raw)) return raw.map(String);
776
- * if (typeof raw === 'string') return raw.split(',');
777
- * throw new Error(`Expected string or array, got ${typeof raw}`);
778
- * })
779
- * ```
780
- *
781
- * Throw an `Error` (or `ParseError`) to signal invalid input — it will
782
- * be wrapped with context and re-thrown as a `ParseError`.
783
- *
784
- * @see `coerceConfigValue` `'custom'` case in `core/resolve/index.ts`
785
- *
786
- * @example
787
- * ```ts
788
- * flag.custom((raw) => new URL(String(raw)))
789
- * // inferred type: URL | undefined
790
- * ```
791
- *
792
- * @param parseFn - Converts the raw input into a value of type `T`.
793
- * @returns A {@link FlagBuilder} whose value type is inferred from `parseFn`.
794
- */
795
- custom<T>(parseFn: FlagParseFn<T>): FlagBuilder<{
796
- readonly valueType: T;
797
- readonly presence: 'optional';
798
- readonly optionalFallback: 'undefined';
799
- readonly flagKind: 'custom';
800
- }>;
801
- }
802
-
803
- /**
804
- * Flag schema factory. Call `flag.<kind>()` to create an immutable
805
- * {@link FlagBuilder} with full type inference and safe modifier chaining.
806
- */
807
- const flag: FlagFactory = {
808
- string(): FlagBuilder<{
809
- readonly valueType: string;
810
- readonly presence: 'optional';
811
- readonly optionalFallback: 'undefined';
812
- readonly flagKind: 'string';
813
- }> {
814
- return new FlagBuilder(createSchema('string'));
815
- },
816
-
817
- number(constraints?: NumberConstraints): FlagBuilder<{
818
- readonly valueType: number;
819
- readonly presence: 'optional';
820
- readonly optionalFallback: 'undefined';
821
- readonly flagKind: 'number';
822
- }> {
823
- if (constraints !== undefined) {
824
- assertNumberConstraints(constraints);
825
- }
826
- return new FlagBuilder(
827
- createSchema('number', constraints !== undefined ? { numberConstraints: constraints } : {}),
828
- );
829
- },
830
-
831
- boolean(): FlagBuilder<{
832
- readonly valueType: boolean;
833
- readonly presence: 'defaulted';
834
- readonly optionalFallback: 'undefined';
835
- readonly flagKind: 'boolean';
836
- }> {
837
- return new FlagBuilder(
838
- createSchema('boolean', {
839
- presence: 'defaulted',
840
- defaultValue: false,
841
- }),
842
- );
843
- },
844
-
845
- enum<const T extends readonly [string, ...string[]]>(
846
- values: T,
847
- ): FlagBuilder<{
848
- readonly valueType: T[number];
849
- readonly presence: 'optional';
850
- readonly optionalFallback: 'undefined';
851
- readonly flagKind: 'enum';
852
- }> {
853
- return new FlagBuilder(createSchema('enum', { enumValues: values }));
854
- },
855
-
856
- array<E extends FlagConfig>(
857
- element: FlagBuilder<E>,
858
- ): FlagBuilder<{
859
- readonly valueType: E['valueType'][];
860
- readonly presence: 'optional';
861
- readonly optionalFallback: 'empty-array';
862
- readonly flagKind: 'array';
863
- }> {
864
- return new FlagBuilder(createSchema('array', { elementSchema: element.schema }));
865
- },
866
-
867
- custom<T>(parseFn: FlagParseFn<T>): FlagBuilder<{
868
- readonly valueType: T;
869
- readonly presence: 'optional';
870
- readonly optionalFallback: 'undefined';
871
- readonly flagKind: 'custom';
872
- }> {
873
- return new FlagBuilder(createSchema('custom', { parseFn: parseFn as FlagParseFn<unknown> }));
874
- },
875
- };
876
-
877
- // --- Exports
878
-
879
- // Re-export prompt types for consumers
880
- export type {
881
- ConfirmPromptConfig,
882
- InputPromptConfig,
883
- MultiselectPromptConfig,
884
- PromptConfig,
885
- PromptConfigBase,
886
- PromptKind,
887
- PromptResult,
888
- SelectChoice,
889
- SelectPromptConfig,
890
- } from './prompt.ts';
891
- export { PROMPT_KINDS } from './prompt.ts';
892
- export type {
893
- AllowedPromptConfig,
894
- FlagAlias,
895
- FlagConfig,
896
- FlagFactory,
897
- FlagKind,
898
- FlagParseFn,
899
- FlagPresence,
900
- FlagSchema,
901
- FlagSchemaOverrides,
902
- InferFlag,
903
- InferFlags,
904
- OptionalFallback,
905
- ResolvedValue,
906
- WithPresence,
907
- };
908
- export {
909
- createSchema,
910
- FLAG_KINDS,
911
- FLAG_PRESENCES,
912
- FlagBuilder,
913
- flag,
914
- getFlagAliasNames,
915
- normalizeFlagAlias,
916
- normalizeFlagAliases,
917
- };