@kjanat/dreamcli 0.0.0 → 2.0.0

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