padrone 1.4.0 → 1.6.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 (141) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/README.md +108 -283
  3. package/dist/args-Cnq0nwSM.mjs +272 -0
  4. package/dist/args-Cnq0nwSM.mjs.map +1 -0
  5. package/dist/codegen/index.d.mts +28 -3
  6. package/dist/codegen/index.d.mts.map +1 -1
  7. package/dist/codegen/index.mjs +169 -19
  8. package/dist/codegen/index.mjs.map +1 -1
  9. package/dist/commands-B_gufyR9.mjs +514 -0
  10. package/dist/commands-B_gufyR9.mjs.map +1 -0
  11. package/dist/{completion.mjs → completion-BEuflbDO.mjs} +86 -108
  12. package/dist/completion-BEuflbDO.mjs.map +1 -0
  13. package/dist/docs/index.d.mts +22 -2
  14. package/dist/docs/index.d.mts.map +1 -1
  15. package/dist/docs/index.mjs +92 -7
  16. package/dist/docs/index.mjs.map +1 -1
  17. package/dist/errors-CL63UOzt.mjs +137 -0
  18. package/dist/errors-CL63UOzt.mjs.map +1 -0
  19. package/dist/{formatter-ClUK5hcQ.d.mts → formatter-DrvhDMrq.d.mts} +35 -6
  20. package/dist/formatter-DrvhDMrq.d.mts.map +1 -0
  21. package/dist/help-B5Kk83of.mjs +849 -0
  22. package/dist/help-B5Kk83of.mjs.map +1 -0
  23. package/dist/index-BaU3X6dY.d.mts +1178 -0
  24. package/dist/index-BaU3X6dY.d.mts.map +1 -0
  25. package/dist/index.d.mts +763 -36
  26. package/dist/index.d.mts.map +1 -1
  27. package/dist/index.mjs +3608 -1534
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/mcp-BM-d0nZi.mjs +377 -0
  30. package/dist/mcp-BM-d0nZi.mjs.map +1 -0
  31. package/dist/serve-Bk0JUlCj.mjs +402 -0
  32. package/dist/serve-Bk0JUlCj.mjs.map +1 -0
  33. package/dist/stream-DC4H8YTx.mjs +77 -0
  34. package/dist/stream-DC4H8YTx.mjs.map +1 -0
  35. package/dist/test.d.mts +5 -8
  36. package/dist/test.d.mts.map +1 -1
  37. package/dist/test.mjs +5 -27
  38. package/dist/test.mjs.map +1 -1
  39. package/dist/{update-check-EbNDkzyV.mjs → update-check-CZ2VqjnV.mjs} +16 -17
  40. package/dist/update-check-CZ2VqjnV.mjs.map +1 -0
  41. package/dist/zod.d.mts +32 -0
  42. package/dist/zod.d.mts.map +1 -0
  43. package/dist/zod.mjs +50 -0
  44. package/dist/zod.mjs.map +1 -0
  45. package/package.json +20 -9
  46. package/src/cli/completions.ts +14 -11
  47. package/src/cli/docs.ts +13 -16
  48. package/src/cli/doctor.ts +213 -24
  49. package/src/cli/index.ts +28 -82
  50. package/src/cli/init.ts +12 -10
  51. package/src/cli/link.ts +22 -18
  52. package/src/cli/wrap.ts +14 -11
  53. package/src/codegen/discovery.ts +80 -28
  54. package/src/codegen/index.ts +2 -1
  55. package/src/codegen/parsers/bash.ts +179 -0
  56. package/src/codegen/schema-to-code.ts +2 -1
  57. package/src/core/args.ts +296 -0
  58. package/src/core/commands.ts +373 -0
  59. package/src/core/create.ts +268 -0
  60. package/src/{runtime.ts → core/default-runtime.ts} +70 -135
  61. package/src/{errors.ts → core/errors.ts} +22 -0
  62. package/src/core/exec.ts +259 -0
  63. package/src/core/interceptors.ts +302 -0
  64. package/src/{parse.ts → core/parse.ts} +36 -89
  65. package/src/core/program-methods.ts +301 -0
  66. package/src/core/results.ts +229 -0
  67. package/src/core/runtime.ts +246 -0
  68. package/src/core/validate.ts +247 -0
  69. package/src/docs/index.ts +124 -11
  70. package/src/extension/auto-output.ts +95 -0
  71. package/src/extension/color.ts +38 -0
  72. package/src/extension/completion.ts +49 -0
  73. package/src/extension/config.ts +262 -0
  74. package/src/extension/env.ts +101 -0
  75. package/src/extension/help.ts +192 -0
  76. package/src/extension/index.ts +43 -0
  77. package/src/extension/ink.ts +93 -0
  78. package/src/extension/interactive.ts +106 -0
  79. package/src/extension/logger.ts +214 -0
  80. package/src/extension/man.ts +51 -0
  81. package/src/extension/mcp.ts +52 -0
  82. package/src/extension/progress-renderer.ts +338 -0
  83. package/src/extension/progress.ts +299 -0
  84. package/src/extension/repl.ts +94 -0
  85. package/src/extension/serve.ts +48 -0
  86. package/src/extension/signal.ts +87 -0
  87. package/src/extension/stdin.ts +62 -0
  88. package/src/extension/suggestions.ts +114 -0
  89. package/src/extension/timing.ts +81 -0
  90. package/src/extension/tracing.ts +175 -0
  91. package/src/extension/update-check.ts +77 -0
  92. package/src/extension/utils.ts +51 -0
  93. package/src/extension/version.ts +63 -0
  94. package/src/{completion.ts → feature/completion.ts} +130 -57
  95. package/src/{interactive.ts → feature/interactive.ts} +47 -6
  96. package/src/feature/mcp.ts +387 -0
  97. package/src/{repl-loop.ts → feature/repl-loop.ts} +26 -16
  98. package/src/feature/serve.ts +438 -0
  99. package/src/feature/test.ts +262 -0
  100. package/src/{update-check.ts → feature/update-check.ts} +16 -16
  101. package/src/{wrap.ts → feature/wrap.ts} +27 -27
  102. package/src/index.ts +120 -11
  103. package/src/output/colorizer.ts +154 -0
  104. package/src/{formatter.ts → output/formatter.ts} +281 -135
  105. package/src/{help.ts → output/help.ts} +62 -15
  106. package/src/{zod.d.ts → schema/zod.d.ts} +1 -1
  107. package/src/schema/zod.ts +50 -0
  108. package/src/test.ts +2 -285
  109. package/src/types/args-meta.ts +151 -0
  110. package/src/types/builder.ts +697 -0
  111. package/src/types/command.ts +157 -0
  112. package/src/types/index.ts +59 -0
  113. package/src/types/interceptor.ts +296 -0
  114. package/src/types/preferences.ts +83 -0
  115. package/src/types/result.ts +71 -0
  116. package/src/types/schema.ts +19 -0
  117. package/src/util/dotenv.ts +244 -0
  118. package/src/{shell-utils.ts → util/shell-utils.ts} +26 -9
  119. package/src/util/stream.ts +101 -0
  120. package/src/{type-helpers.ts → util/type-helpers.ts} +23 -16
  121. package/src/{type-utils.ts → util/type-utils.ts} +99 -37
  122. package/src/util/utils.ts +51 -0
  123. package/src/zod.ts +1 -0
  124. package/dist/args-CVDbyyzG.mjs +0 -199
  125. package/dist/args-CVDbyyzG.mjs.map +0 -1
  126. package/dist/chunk-y_GBKt04.mjs +0 -5
  127. package/dist/completion.d.mts +0 -64
  128. package/dist/completion.d.mts.map +0 -1
  129. package/dist/completion.mjs.map +0 -1
  130. package/dist/formatter-ClUK5hcQ.d.mts.map +0 -1
  131. package/dist/help-CcBe91bV.mjs +0 -1254
  132. package/dist/help-CcBe91bV.mjs.map +0 -1
  133. package/dist/types-DjIdJN5G.d.mts +0 -1059
  134. package/dist/types-DjIdJN5G.d.mts.map +0 -1
  135. package/dist/update-check-EbNDkzyV.mjs.map +0 -1
  136. package/src/args.ts +0 -461
  137. package/src/colorizer.ts +0 -41
  138. package/src/command-utils.ts +0 -532
  139. package/src/create.ts +0 -1477
  140. package/src/types.ts +0 -1109
  141. package/src/utils.ts +0 -140
@@ -0,0 +1,1178 @@
1
+ import { a as ColorConfig, n as HelpFormat, o as ColorTheme, t as HelpDetail } from "./formatter-DrvhDMrq.mjs";
2
+ import { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
3
+ import { Tool } from "ai";
4
+
5
+ //#region src/types/args-meta.d.ts
6
+ type Letter = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z';
7
+ /** A single letter character, valid as a short CLI flag (e.g. `'v'`, `'n'`, `'V'`). */
8
+ type SingleChar = Letter | Uppercase<Letter>;
9
+ interface PadroneFieldMeta {
10
+ description?: string;
11
+ /** Single-character short flags (stackable: `-abc` = `-a -b -c`). Used with single dash. */
12
+ flags?: readonly SingleChar[] | SingleChar;
13
+ /** Multi-character alternative long names. Used with double dash (e.g. `--dry-run` for `--dryRun`). */
14
+ alias?: readonly string[] | string;
15
+ deprecated?: boolean | string;
16
+ hidden?: boolean;
17
+ examples?: readonly unknown[];
18
+ /** Group name for organizing this option under a labeled section in help output. */
19
+ group?: string;
20
+ }
21
+ type PositionalArgs<TObj> = TObj extends Record<string, any> ? { [K in keyof TObj]: NonNullable<TObj[K]> extends Array<any> ? `...${K & string}` | (K & string) : K & string }[keyof TObj] : string;
22
+ /**
23
+ * Meta configuration for arguments, including positional arguments.
24
+ * The `positional` array defines which arguments are positional and their order.
25
+ * Use '...name' prefix to indicate variadic (rest) arguments, matching JS/TS rest syntax.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * .arguments(schema, {
30
+ * positional: ['source', '...files', 'dest'], // '...files' is variadic
31
+ * })
32
+ * ```
33
+ */
34
+ /**
35
+ * Configuration for reading from stdin and mapping it to an argument field.
36
+ * Simply specify the field name — the read mode is inferred from the schema:
37
+ * - `string` field → reads all stdin as text
38
+ * - `string[]` field → reads stdin line-by-line
39
+ */
40
+ type StdinConfig<TObj = Record<string, any>> = keyof TObj & string;
41
+ interface PadroneArgsSchemaMeta<TObj = Record<string, any>> {
42
+ /**
43
+ * Array of argument names that should be treated as positional arguments.
44
+ * Order in array determines position. Use '...name' prefix for variadic args.
45
+ * @example ['source', '...files', 'dest'] - 'files' captures multiple values
46
+ */
47
+ positional?: readonly PositionalArgs<TObj>[];
48
+ /**
49
+ * Per-argument metadata.
50
+ */
51
+ fields?: { [K in keyof TObj]?: PadroneFieldMeta };
52
+ /**
53
+ * Automatically generate kebab-case aliases for camelCase option names.
54
+ * For example, `dryRun` automatically gets `--dry-run` as an alias.
55
+ * Defaults to `true`. Set to `false` to disable.
56
+ *
57
+ * @default true
58
+ * @example
59
+ * ```ts
60
+ * // Auto-aliases enabled (default): --dry-run → dryRun
61
+ * .arguments(z.object({ dryRun: z.boolean() }))
62
+ *
63
+ * // Disable auto-aliases
64
+ * .arguments(z.object({ dryRun: z.boolean() }), { autoAlias: false })
65
+ * ```
66
+ */
67
+ autoAlias?: boolean;
68
+ /**
69
+ * Read from stdin and inject the data into the specified argument field.
70
+ * Only reads when stdin is piped (not a TTY) and the field wasn't already provided via CLI flags.
71
+ *
72
+ * The read mode is inferred from the schema type of the target field:
73
+ * - `string` field → reads all stdin as a single string
74
+ * - `string[]` field → reads stdin line-by-line into an array
75
+ *
76
+ * Precedence: CLI flags > stdin > env vars > config file > schema defaults.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * // Read all stdin as text into 'data' field
81
+ * .arguments(z.object({ data: z.string() }), { stdin: 'data' })
82
+ *
83
+ * // Read stdin lines into 'lines' field (inferred from array schema)
84
+ * .arguments(z.object({ lines: z.string().array() }), { stdin: 'lines' })
85
+ * ```
86
+ */
87
+ stdin?: StdinConfig<TObj>;
88
+ /**
89
+ * Fields to interactively prompt for when their values are missing after CLI/env/config resolution.
90
+ * - `true`: prompt for all required fields that are missing.
91
+ * - `string[]`: prompt for these specific fields if missing.
92
+ *
93
+ * Interactive prompting only occurs in `cli()` when the runtime has `interactive: true`.
94
+ * Setting this makes `parse()` and `cli()` return Promises.
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * .arguments(schema, {
99
+ * interactive: true, // prompt all missing required fields
100
+ * interactive: ['name', 'template'], // prompt only these fields
101
+ * })
102
+ * ```
103
+ */
104
+ interactive?: true | readonly (keyof TObj & string)[];
105
+ /**
106
+ * Optional fields offered after required interactive prompts.
107
+ * Users are shown a multi-select to choose which of these fields to configure.
108
+ * - `true`: offer all optional fields that are missing.
109
+ * - `string[]`: offer these specific fields.
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * .arguments(schema, {
114
+ * interactive: ['name'],
115
+ * optionalInteractive: ['typescript', 'eslint', 'prettier'],
116
+ * })
117
+ * ```
118
+ */
119
+ optionalInteractive?: true | readonly (keyof TObj & string)[];
120
+ }
121
+ //#endregion
122
+ //#region src/core/runtime.d.ts
123
+ /** Process signals that Padrone can handle for graceful shutdown. */
124
+ type PadroneSignal = 'SIGINT' | 'SIGTERM' | 'SIGHUP';
125
+ /** Value accepted by `PadroneProgressIndicator.update()`. */
126
+ type PadroneProgressUpdate = string | number | {
127
+ message?: string;
128
+ progress?: number;
129
+ indeterminate?: boolean;
130
+ time?: boolean;
131
+ };
132
+ /**
133
+ * A progress indicator instance (spinner, progress bar, etc).
134
+ * Created by the runtime's `progress` factory and used to show loading state during command execution.
135
+ */
136
+ type PadroneProgressIndicator = {
137
+ /**
138
+ * Update the indicator.
139
+ * - `string` — update the displayed message.
140
+ * - `number` — set progress ratio (0–1). Values outside this range are clamped.
141
+ * - `{ message?, progress?, indeterminate? }` — update message, progress, or both.
142
+ *
143
+ * Set `indeterminate: true` to force the bar into indeterminate mode (shows animation, no percentage).
144
+ * This makes the bar visible even in `show: 'auto'` mode without providing a number.
145
+ * Omitting `progress` (or passing a string) leaves the bar in its current state.
146
+ * Setting `progress` when bar mode is not enabled is a no-op for the bar portion.
147
+ *
148
+ * Set `time: true` to start the elapsed timer on demand (useful when `time` was not set in options).
149
+ * Set `time: false` to hide the elapsed timer.
150
+ */
151
+ update: (value: PadroneProgressUpdate) => void; /** Mark as succeeded and stop. Pass `null` to stop without rendering a final message. */
152
+ succeed: (message?: string | null, options?: {
153
+ indicator?: string;
154
+ }) => void; /** Mark as failed and stop. Pass `null` to stop without rendering a final message. */
155
+ fail: (message?: string | null, options?: {
156
+ indicator?: string;
157
+ }) => void; /** Stop without success/fail status. */
158
+ stop: () => void; /** Temporarily hide the indicator so other output can be written cleanly. */
159
+ pause: () => void; /** Redraw the indicator after a `pause()`. */
160
+ resume: () => void;
161
+ };
162
+ /** Controls when a progress element (spinner or bar) is visible. */
163
+ type PadroneProgressShow = 'auto' | 'always' | 'never';
164
+ /** Built-in spinner presets. */
165
+ type PadroneSpinnerPreset = 'dots' | 'line' | 'arc' | 'bounce';
166
+ /**
167
+ * Spinner configuration for progress indicators.
168
+ * - A preset name (e.g., `'dots'`) to use built-in frames.
169
+ * - `true` — default spinner with `show: 'always'` (visible even alongside a bar).
170
+ * - An object with custom `frames`, `interval`, and/or `show`.
171
+ * - `false` to disable the spinner (`show: 'never'`).
172
+ *
173
+ * Default `show` is `'auto'`: visible when the bar is not shown.
174
+ */
175
+ type PadroneSpinnerConfig = PadroneSpinnerPreset | boolean | {
176
+ frames?: string[];
177
+ interval?: number;
178
+ show?: PadroneProgressShow;
179
+ };
180
+ /**
181
+ * Options passed to the runtime's `progress` factory.
182
+ */
183
+ /** Common fill/empty character pairs for progress bars. */
184
+ type PadroneBarChar = '█' | '░' | '▓' | '▒' | '─' | '━' | '■' | '□' | '#' | '-' | '=' | '·' | '▰' | '▱' | (string & {});
185
+ /**
186
+ * Built-in indeterminate bar animation presets.
187
+ * - `'bounce'` — a filled segment slides back and forth (default).
188
+ * - `'slide'` — a filled segment slides left-to-right and wraps around.
189
+ * - `'pulse'` — the entire bar fades in and out using gradient characters (`░▒▓█▓▒░`).
190
+ */
191
+ type PadroneBarAnimation = 'bounce' | 'slide' | 'pulse';
192
+ /**
193
+ * Progress bar configuration.
194
+ */
195
+ type PadroneBarConfig = {
196
+ /** Total width of the bar in characters. Defaults to `20`. */width?: number; /** Character used for the filled portion of the bar. Defaults to `'█'`. */
197
+ filled?: PadroneBarChar; /** Character used for the empty portion of the bar. Defaults to `'░'`. */
198
+ empty?: PadroneBarChar; /** Indeterminate animation style. Defaults to `'bounce'`. */
199
+ animation?: PadroneBarAnimation;
200
+ /**
201
+ * When the bar is visible. Defaults to `'always'` when bar is enabled, `'auto'` when bar is not explicitly configured.
202
+ * - `'always'` — bar is always shown (indeterminate until a number is provided).
203
+ * - `'auto'` — bar is shown only after `update()` is called with a number.
204
+ * - `'never'` — bar is never shown.
205
+ */
206
+ show?: PadroneProgressShow;
207
+ };
208
+ type PadroneProgressOptions = {
209
+ spinner?: PadroneSpinnerConfig; /** Enable a progress bar. `true` for defaults (`show: 'always'`), or a `PadroneBarConfig` object. `false` to disable entirely. When omitted, bar defaults to `show: 'auto'` (appears when a number is provided). */
210
+ bar?: boolean | PadroneBarConfig; /** Show elapsed time since the indicator started. Defaults to `false`. */
211
+ time?: boolean; /** Show estimated time remaining based on progress rate. Requires numeric `update()` calls. Defaults to `false`. */
212
+ eta?: boolean; /** Character/string shown before the success message. Defaults to `'✔'`. */
213
+ successIndicator?: string; /** Character/string shown before the error message. Defaults to `'✖'`. */
214
+ errorIndicator?: string;
215
+ };
216
+ /**
217
+ * Controls interactive prompting capability and default behavior at the runtime level.
218
+ * - `'supported'` — capable; caller decides.
219
+ * - `'unsupported'` — hard veto; nothing can override.
220
+ * - `'forced'` — capable and forces prompts by default.
221
+ * - `'disabled'` — capable but suppresses prompts by default.
222
+ */
223
+ type InteractiveMode = 'supported' | 'unsupported' | 'forced' | 'disabled';
224
+ /**
225
+ * Configuration passed to the runtime's `prompt` function for interactive field prompting.
226
+ * The prompt type and choices are auto-detected from the field's JSON schema.
227
+ */
228
+ type InteractivePromptConfig = {
229
+ /** The field name being prompted. */name: string; /** Human-readable message/label for the prompt, derived from the field's description or name. */
230
+ message: string; /** The prompt type, auto-detected from the JSON schema. */
231
+ type: 'input' | 'confirm' | 'select' | 'multiselect' | 'password'; /** Available choices for select/multiselect prompts. */
232
+ choices?: {
233
+ label: string;
234
+ value: unknown;
235
+ }[]; /** Default value from the schema. */
236
+ default?: unknown;
237
+ };
238
+ /**
239
+ * Defines the execution context for a Padrone program.
240
+ * Abstracts all environment-dependent I/O so the CLI framework
241
+ * can run outside of a terminal (e.g., web UIs, chat interfaces, testing).
242
+ *
243
+ * All fields are optional — unspecified fields fall back to the Node.js/Bun defaults.
244
+ */
245
+ type PadroneRuntime = {
246
+ /** Write normal output (replaces console.log). Receives the raw value — runtime handles formatting. */output?: (...args: unknown[]) => void; /** Write error output (replaces console.error). */
247
+ error?: (text: string) => void; /** Return the raw CLI arguments (replaces process.argv.slice(2)). */
248
+ argv?: () => string[]; /** Return environment variables (replaces process.env). */
249
+ env?: () => Record<string, string | undefined>; /** Default help output format. */
250
+ format?: HelpFormat | 'auto'; /** Color theme for ANSI/console help output. A theme name or partial color config. */
251
+ theme?: ColorTheme | ColorConfig;
252
+ /**
253
+ * Standard input abstraction. Provides methods to read piped data from stdin.
254
+ * When not provided, defaults to reading from `process.stdin`.
255
+ *
256
+ * Used by commands that declare a `stdin` field in their arguments meta.
257
+ * The framework reads stdin automatically during the validate phase and
258
+ * injects the data into the specified argument field.
259
+ */
260
+ stdin?: {
261
+ /** Whether stdin is a TTY (interactive terminal) vs a pipe/file. */isTTY?: boolean; /** Read all of stdin as a string. */
262
+ text: () => Promise<string>; /** Async iterable of lines for streaming. */
263
+ lines: () => AsyncIterable<string>;
264
+ };
265
+ /**
266
+ * Controls interactive prompting capability and default behavior.
267
+ * - `'supported'` — runtime can handle prompts; caller (flag/pref) decides whether to prompt. This is the default when `prompt` is provided.
268
+ * - `'unsupported'` — runtime cannot handle prompts; hard veto that nothing can override.
269
+ * - `'forced'` — runtime supports prompts and forces them by default (prompts even for provided values).
270
+ * - `'disabled'` — runtime supports prompts but suppresses them by default.
271
+ *
272
+ * `'unsupported'` is the only immutable state. For the others, the `--interactive`/`-i` flag
273
+ * and `cli()` preferences can override the default behavior.
274
+ */
275
+ interactive?: InteractiveMode;
276
+ /**
277
+ * Prompt the user for input. Called during `cli()` for fields marked as interactive.
278
+ * When `interactive` is `true` and this is not provided, defaults to an Enquirer-based terminal prompt.
279
+ */
280
+ prompt?: (config: InteractivePromptConfig) => Promise<unknown>;
281
+ /**
282
+ * Read a line of input from the user. Used by `repl()` for custom runtimes
283
+ * (web UIs, chat interfaces, testing).
284
+ * Returns the input string, `null` on EOF (e.g. Ctrl+D, closed connection),
285
+ * or `REPL_SIGINT` when the user presses Ctrl+C.
286
+ *
287
+ * When not provided, `repl()` uses a built-in Node.js readline session
288
+ * with command history (up/down arrows) and tab completion.
289
+ */
290
+ readLine?: (prompt: string) => Promise<string | typeof REPL_SIGINT | null>;
291
+ /**
292
+ * Register a callback for process signals. Returns an unsubscribe function.
293
+ * The default runtime wires this to `process.on('SIGINT' | 'SIGTERM' | 'SIGHUP')`.
294
+ * Non-Node runtimes (web UIs, tests) can map their own cancellation semantics.
295
+ *
296
+ * When not provided, signal handling is disabled for this runtime.
297
+ */
298
+ onSignal?: (callback: (signal: PadroneSignal) => void) => () => void;
299
+ /**
300
+ * Terminal/output capabilities. Used for ANSI detection, text wrapping, and TTY checks.
301
+ * The default runtime auto-detects from `process.stdout`. Non-terminal runtimes
302
+ * (web UIs, tests) should provide explicit values.
303
+ */
304
+ terminal?: {
305
+ /** Number of columns in the terminal. Used for text wrapping. */columns?: number; /** Whether stdout is a TTY. Affects ANSI color output and interactive features. */
306
+ isTTY?: boolean;
307
+ };
308
+ /**
309
+ * Force-exit the process. The default runtime wires this to `process.exit()`.
310
+ * Non-Node runtimes can throw an error or no-op.
311
+ */
312
+ exit?: (code: number) => never;
313
+ };
314
+ /**
315
+ * Internal resolved runtime where all fields are guaranteed to be present.
316
+ * The `prompt`, `interactive`, and `readLine` fields remain optional since not all runtimes provide them.
317
+ */
318
+ type ResolvedPadroneRuntime = Required<Omit<PadroneRuntime, 'prompt' | 'interactive' | 'readLine' | 'stdin' | 'theme' | 'onSignal' | 'terminal' | 'exit'>> & Pick<PadroneRuntime, 'prompt' | 'interactive' | 'readLine' | 'stdin' | 'theme' | 'onSignal' | 'terminal' | 'exit'>;
319
+ /**
320
+ * Sentinel value returned by the terminal REPL session when Ctrl+C is pressed.
321
+ * Distinguished from empty string (user pressed enter) and null (EOF/Ctrl+D).
322
+ */
323
+ declare const REPL_SIGINT: unique symbol;
324
+ //#endregion
325
+ //#region src/feature/mcp.d.ts
326
+ type PadroneMcpPreferences = {
327
+ /** Server name. Defaults to the program name. */name?: string; /** Server version. Defaults to the program version. */
328
+ version?: string;
329
+ /**
330
+ * Transport mode.
331
+ * - `'http'` — Start a Streamable HTTP server (default). Responds with `application/json` or `text/event-stream` based on the client's `Accept` header. Use `port` and `host` to configure.
332
+ * - `'stdio'` — Communicate over stdin/stdout with newline-delimited JSON.
333
+ */
334
+ transport?: 'http' | 'stdio'; /** HTTP port. Defaults to `3000`. Only used with `transport: 'http'`. */
335
+ port?: number; /** HTTP host. Defaults to `'127.0.0.1'`. Only used with `transport: 'http'`. */
336
+ host?: string; /** Base path for the MCP endpoint. Defaults to `'/mcp'`. Only used with `transport: 'http'`. */
337
+ basePath?: string; /** CORS allowed origin. Defaults to `'*'`. Set to a specific origin or `false` to disable CORS headers. Only used with HTTP transports. */
338
+ cors?: string | false;
339
+ };
340
+ //#endregion
341
+ //#region src/feature/serve.d.ts
342
+ type PadroneServePreferences = {
343
+ /** Port to listen on. Default: 3000 */port?: number; /** Host to bind to. Default: '127.0.0.1' */
344
+ host?: string; /** Base path prefix for all routes. Default: '/' */
345
+ basePath?: string; /** CORS allowed origin. Default: '*'. Set to `false` to disable CORS headers. */
346
+ cors?: string | false; /** Control built-in utility endpoints. All enabled by default. */
347
+ builtins?: {
348
+ /** GET /_health — returns 200 OK. */health?: boolean; /** GET /_help and GET /_help/:command — returns help text. */
349
+ help?: boolean; /** GET /_schema and GET /_schema/:command — returns JSON Schema. */
350
+ schema?: boolean; /** GET /_docs — Scalar OpenAPI docs viewer. */
351
+ docs?: boolean;
352
+ }; /** Hook to run before each request. Return a Response to short-circuit. */
353
+ onRequest?: (req: Request) => Response | void | Promise<Response | void>; /** Transform errors into responses. */
354
+ onError?: (error: unknown, req: Request) => Response;
355
+ };
356
+ //#endregion
357
+ //#region src/feature/wrap.d.ts
358
+ /**
359
+ * Configuration for wrapping an external CLI tool.
360
+ */
361
+ type WrapConfig<TCommandArgs extends PadroneSchema = PadroneSchema, TWrapArgs extends PadroneSchema = TCommandArgs> = {
362
+ /**
363
+ * The command to execute (e.g., 'git', 'docker', 'npm').
364
+ */
365
+ command: string;
366
+ /**
367
+ * Optional fixed arguments that always precede the arguments (e.g., ['commit'] for 'git commit').
368
+ */
369
+ args?: string[];
370
+ /**
371
+ * Positional argument configuration for the external command.
372
+ * If not provided, defaults to the wrapping command's positional configuration.
373
+ */
374
+ positional?: string[];
375
+ /**
376
+ * Whether to inherit stdio streams (stdin, stdout, stderr) from the parent process.
377
+ * Default: true
378
+ */
379
+ inheritStdio?: boolean;
380
+ /**
381
+ * Optional schema that transforms command arguments to external CLI arguments.
382
+ * The schema's input type should match the command arguments, and its output type defines
383
+ * the arguments expected by the external command.
384
+ * If not provided, command arguments are passed through as-is.
385
+ */
386
+ schema?: TWrapArgs | ((commandArguments: TCommandArgs) => TWrapArgs);
387
+ };
388
+ /**
389
+ * Result from executing a wrapped CLI tool.
390
+ */
391
+ type WrapResult = {
392
+ /**
393
+ * The exit code of the process.
394
+ */
395
+ exitCode: number;
396
+ /**
397
+ * Standard output from the process (only if inheritStdio is false).
398
+ */
399
+ stdout?: string;
400
+ /**
401
+ * Standard error from the process (only if inheritStdio is false).
402
+ */
403
+ stderr?: string;
404
+ /**
405
+ * Whether the process exited successfully (exit code 0).
406
+ */
407
+ success: boolean;
408
+ };
409
+ //#endregion
410
+ //#region src/output/help.d.ts
411
+ type HelpPreferences = {
412
+ format?: HelpFormat | 'auto';
413
+ detail?: HelpDetail;
414
+ theme?: ColorTheme | ColorConfig; /** Show all global commands and flags in full detail */
415
+ all?: boolean; /** Terminal width for text wrapping. Defaults to terminal columns or 80. */
416
+ width?: number; /** Terminal capabilities for auto-detection of ANSI and width. */
417
+ terminal?: {
418
+ columns?: number;
419
+ isTTY?: boolean;
420
+ }; /** Environment variables for auto-detection (e.g., NO_COLOR, CI). */
421
+ env?: Record<string, string | undefined>;
422
+ };
423
+ //#endregion
424
+ //#region src/types/schema.d.ts
425
+ /**
426
+ * A schema that supports both validation (StandardSchemaV1) and JSON schema generation (StandardJSONSchemaV1).
427
+ * This is the type required for command arguments in Padrone.
428
+ */
429
+ type PadroneSchema<Input = unknown, Output = Input> = StandardSchemaV1<Input, Output> & StandardJSONSchemaV1<Input, Output>;
430
+ /**
431
+ * A schema branded as async. When passed to `.arguments()`, `.configFile()`, or `.env()`,
432
+ * the command is automatically marked as async, causing `parse()` and `cli()` to return Promises.
433
+ *
434
+ * Use the `asyncSchema()` helper to brand an existing schema:
435
+ * ```ts
436
+ * import { asyncSchema } from 'padrone';
437
+ * const schema = asyncSchema(z.object({ name: z.string() }).check(async (v) => { ... }));
438
+ * ```
439
+ */
440
+ type AsyncPadroneSchema<Input = unknown, Output = Input> = PadroneSchema<Input, Output> & {
441
+ '~async': true;
442
+ };
443
+ //#endregion
444
+ //#region src/util/type-utils.d.ts
445
+ type SafeString = string & {};
446
+ type IsUnknown<T> = unknown extends T ? true : false;
447
+ type IsAny<T> = any extends T ? true : false;
448
+ type IsNever<T> = [T] extends [never] ? true : false;
449
+ type IsGeneric<T> = IsAny<T> extends true ? true : IsUnknown<T> extends true ? true : IsNever<T> extends true ? true : false;
450
+ /**
451
+ * Detects whether a schema has been branded as async via the `'~async'` property.
452
+ * Standard Schema V1's `validate()` always types its return as `Result | Promise<Result>`
453
+ * regardless of whether the schema is actually async, so we rely on an explicit brand instead.
454
+ *
455
+ * Use `asyncSchema(schema)` to brand a schema, or check for the `{ '~async': true }` property.
456
+ */
457
+ type IsAsyncSchema<T> = IsAny<T> extends true ? false : T extends {
458
+ '~async': true;
459
+ } ? true : false;
460
+ /**
461
+ * Computes the new TAsync flag when a schema is added to a builder.
462
+ * Once TAsync is `true`, it stays `true`. Otherwise, checks if the new schema is branded async.
463
+ */
464
+ type OrAsync<TExisting extends boolean, TSchema> = TExisting extends true ? true : IsAsyncSchema<TSchema> extends true ? true : false;
465
+ /**
466
+ * Detects whether argument meta contains interactive or optionalInteractive configuration.
467
+ * When either is `true` or a `string[]`, the command requires async execution for prompting.
468
+ */
469
+ type HasInteractive<TMeta> = TMeta extends {
470
+ interactive: true | readonly string[];
471
+ } ? true : TMeta extends {
472
+ optionalInteractive: true | readonly string[];
473
+ } ? true : false;
474
+ /**
475
+ * Combines schema-level async detection with meta-level interactive detection.
476
+ * Returns `true` if the existing async flag is set, the schema is branded async, or the meta has interactive fields.
477
+ */
478
+ type OrAsyncMeta<TExisting extends boolean, TMeta> = TExisting extends true ? true : HasInteractive<TMeta> extends true ? true : false;
479
+ /**
480
+ * Unwraps a result type by resolving Promises and collecting iterables into arrays.
481
+ * - `AsyncIterable<U>` → `U[]`
482
+ * - `Iterable<U>` (excluding strings) → `U[]`
483
+ * - `Promise<U>` → `Drained<U>` (recursively unwraps)
484
+ * - `T` → `T`
485
+ */
486
+ type Drained<T> = T extends Promise<infer U> ? Drained<U> : T extends AsyncIterable<infer U> ? U[] : T extends string ? T : T extends Iterable<infer U> ? U[] : T;
487
+ /**
488
+ * A sync value augmented with Promise-like methods (.then, .catch, .finally).
489
+ * Unlike a real Promise, properties of T are accessible synchronously.
490
+ */
491
+ type Thenable<T> = T & PromiseLike<T> & {
492
+ catch: Promise<T>['catch'];
493
+ finally: Promise<T>['finally'];
494
+ };
495
+ /**
496
+ * Conditionally wraps a type in Promise based on the TAsync flag.
497
+ * - `true` → `Promise<T>`
498
+ * - `false` → `T & Thenable<T>` (thenable: supports `.then()`, `.catch()`, `.finally()`, and `await`)
499
+ * - `boolean` (union of true|false) → `Promise<T>` (safe default when async-ness is uncertain)
500
+ * - `any` → `T` (for generic/any typed commands like AnyPadroneCommand)
501
+ */
502
+ type MaybePromise<T, TAsync> = IsAny<TAsync> extends true ? T : true extends TAsync ? Promise<T> : Thenable<T>;
503
+ type SplitString<TName extends string, TSplitBy extends string = ' '> = TName extends `${infer FirstPart}${TSplitBy}${infer RestParts}` ? [FirstPart, ...SplitString<RestParts, TSplitBy>] : [TName];
504
+ type JoinString<TParts extends string[], TJoinBy extends string = ' '> = TParts extends [infer FirstPart extends string, ...infer RestParts extends string[]] ? RestParts extends [] ? FirstPart : `${FirstPart}${TJoinBy}${JoinString<RestParts, TJoinBy>}` : TParts extends [] ? '' : TParts[number];
505
+ type SplitLastSpace<S extends string> = SplitString<S> extends [...infer Init extends string[], infer Last extends string] ? Init extends [] ? [S, never] : [JoinString<Init>, Last] : [S, never];
506
+ type AnyPartExtends<U, T> = [U] extends [never] ? false : U extends any ? (U extends T ? true : never) : never extends true ? true : false;
507
+ type FullCommandName<TName extends string, TParentName extends string = ''> = TParentName extends '' ? TName : `${TParentName} ${TName}`;
508
+ /**
509
+ * Generate full alias paths by combining parent path with each alias.
510
+ */
511
+ type FullAliasPaths<TAliases extends string[], TParentName extends string = ''> = TAliases extends [infer First extends string, ...infer Rest extends string[]] ? FullCommandName<First, TParentName> | FullAliasPaths<Rest, TParentName> : never;
512
+ /**
513
+ * Get all paths for a command including its primary path and all alias paths.
514
+ */
515
+ type GetCommandPathsAndAliases<TCommand extends AnyPadroneCommand> = TCommand['~types']['path'] extends infer Path extends string ? TCommand['~types']['aliases'] extends infer Aliases extends string[] ? TCommand['~types']['parentName'] extends infer ParentName extends string ? Path | FullAliasPaths<Aliases, ParentName> : Path : Path : never;
516
+ /**
517
+ * Find a direct child command in a tuple by name.
518
+ * Unlike PickCommandByName, this does NOT flatten — it only checks direct children by their `name` field.
519
+ * Uses indexed access (O(1) depth) instead of recursive tuple walking.
520
+ */
521
+ type FindDirectChild<TCommands extends AnyPadroneCommand[], TName extends string> = Extract<TCommands[number], {
522
+ '~types': {
523
+ name: TName;
524
+ };
525
+ }>;
526
+ /**
527
+ * Replace a command in a tuple by name, or append if not found.
528
+ * Used by `.command()` override semantics: re-registering a name replaces that entry.
529
+ * Uses mapped type (O(1) depth) instead of recursive tuple walking.
530
+ */
531
+ type ReplaceOrAppendCommand<TCommands extends [...AnyPadroneCommand[]], TName extends string, TNew extends AnyPadroneCommand> = HasDirectChild<TCommands, TName> extends true ? ReplaceInTuple<TCommands, TName, TNew> : [...TCommands, TNew];
532
+ type HasDirectChild<TCommands extends AnyPadroneCommand[], TName extends string> = TName extends TCommands[number]['~types']['name'] ? true : false;
533
+ type ReplaceInTuple<TCommands extends AnyPadroneCommand[], TName extends string, TNew extends AnyPadroneCommand> = { [K in keyof TCommands]: TCommands[K] extends AnyPadroneCommand ? TCommands[K]['~types']['name'] extends TName ? TNew : TCommands[K] : TCommands[K] };
534
+ /**
535
+ * Utility type for extensions that add a command to a builder/program.
536
+ * Replaces the boilerplate `With*<T>` pattern used across all extension files.
537
+ */
538
+ type WithCommand<T, TName extends string, TCmd extends AnyPadroneCommand> = T extends {
539
+ '~types': {
540
+ programName: infer PN extends string;
541
+ name: infer N extends string;
542
+ parentName: infer PaN extends string;
543
+ argsSchema: infer A extends PadroneSchema;
544
+ result: infer R;
545
+ commands: infer C extends [...AnyPadroneCommand[]];
546
+ async: infer AS extends boolean;
547
+ context: infer CTX;
548
+ contextProvided: infer CTXP;
549
+ };
550
+ } ? T extends {
551
+ run: any;
552
+ } ? PadroneProgram<PN, N, PaN, A, R, ReplaceOrAppendCommand<C, TName, TCmd>, any, AS, CTX, CTXP> : PadroneBuilder<PN, N, PaN, A, R, ReplaceOrAppendCommand<C, TName, TCmd>, any, AS, CTX, CTXP> : T;
553
+ /**
554
+ * Utility type for extensions that register a context-providing interceptor.
555
+ * Extends `TContextProvided` with `TProvides` while preserving all other builder/program type params.
556
+ */
557
+ type WithInterceptor<T, TProvides> = T extends {
558
+ '~types': {
559
+ programName: infer PN extends string;
560
+ name: infer N extends string;
561
+ parentName: infer PaN extends string;
562
+ argsSchema: infer A extends PadroneSchema;
563
+ result: infer R;
564
+ commands: infer C extends [...AnyPadroneCommand[]];
565
+ async: infer AS extends boolean;
566
+ context: infer CTX;
567
+ contextProvided: infer CTXP;
568
+ };
569
+ } ? T extends {
570
+ run: any;
571
+ } ? PadroneProgram<PN, N, PaN, A, R, C, any, AS, CTX, CTXP & TProvides> : PadroneBuilder<PN, N, PaN, A, R, C, any, AS, CTX, CTXP & TProvides> : T;
572
+ type PickCommandByName<TCommands extends AnyPadroneCommand[], TName extends string | AnyPadroneCommand> = TName extends AnyPadroneCommand ? TName : FlattenCommands<TCommands> extends infer Cmd extends AnyPadroneCommand ? Cmd extends AnyPadroneCommand ? TName extends GetCommandPathsAndAliases<Cmd> ? Cmd : never : never : never;
573
+ type FlattenCommands<TCommands extends AnyPadroneCommand[]> = TCommands extends [] ? never : number extends TCommands['length'] ? IsAny<TCommands[number]> extends true ? never : TCommands[number] : TCommands[number] extends infer Cmd extends AnyPadroneCommand ? Cmd | FlattenCommands<Cmd['~types']['commands']> : never;
574
+ /**
575
+ * Get all command paths including alias paths for all commands.
576
+ */
577
+ type GetCommandPathsOrAliases<TCommands extends AnyPadroneCommand[]> = GetCommandPathsAndAliases<FlattenCommands<TCommands>>;
578
+ /**
579
+ * Find all the commands that are prefixed with a command name or alias.
580
+ * This is needed to avoid matching other commands when followed by a space and another word.
581
+ * For example, let's say `level1` and `level1 level2` are commands.
582
+ * Then `level1 ${string}` would also match `level1 level2`,
583
+ * and it would cause `level1 level2` to not show up in the autocomplete.
584
+ * By excluding those cases, we can ensure autocomplete works correctly.
585
+ */
586
+ type PrefixedCommands<TCommands extends AnyPadroneCommand[]> = GetCommandPathsOrAliases<TCommands> extends infer CommandNames ? CommandNames extends string ? AnyPartExtends<GetCommandPathsOrAliases<TCommands>, `${CommandNames} ${string}`> extends true ? never : `${CommandNames} ${string}` : never : never;
587
+ /**
588
+ * The possible commands are the commands that can be parsed by the program.
589
+ * This includes the string that are exact matches to a command name or alias, and strings that are prefixed with a command name or alias.
590
+ */
591
+ type PossibleCommands<TCommands extends AnyPadroneCommand[], TWithPrefixed extends boolean = false, TWithObjects extends boolean = false, TWithFallback extends boolean = true> = GetCommandPathsOrAliases<TCommands> | (TWithPrefixed extends true ? PrefixedCommands<TCommands> : never) | (TWithObjects extends true ? FlattenCommands<TCommands> : never) | (TWithFallback extends true ? SafeString : never);
592
+ type CommandIsUnknownable<TCommand> = IsGeneric<TCommand> extends true ? true : string extends TCommand ? true : SafeString extends TCommand ? true : false;
593
+ /**
594
+ * Match a string to a command by the possible commands.
595
+ * This is done by recursively splitting the string by the last space, and then checking if the prefix is a valid command name or alias.
596
+ * This is needed to avoid matching the top-level command when there are nested commands.
597
+ */
598
+ /**
599
+ * Recursively re-paths a command's children under a new parent path.
600
+ * Used by `mount()` to update all nested command paths when a program is mounted as a subcommand.
601
+ */
602
+ type RepathCommands<TCommands extends [...AnyPadroneCommand[]], TNewParentPath extends string> = TCommands extends [infer First extends AnyPadroneCommand, ...infer Rest extends AnyPadroneCommand[]] ? [RepathCommand<First, TNewParentPath>, ...RepathCommands<Rest, TNewParentPath>] : [];
603
+ type RepathCommand<TCommand extends AnyPadroneCommand, TNewParentName extends string> = PadroneCommand<TCommand['~types']['name'], TNewParentName, TCommand['~types']['argsSchema'], TCommand['~types']['result'], RepathCommands<TCommand['~types']['commands'], FullCommandName<TCommand['~types']['name'], TNewParentName>>, TCommand['~types']['aliases'], TCommand['~types']['async'], TCommand['~types']['context'], TCommand['~types']['contextProvided']>;
604
+ type PickCommandByPossibleCommands<TCommands extends AnyPadroneCommand[], TCommand extends PossibleCommands<TCommands, true, true> | SafeString> = CommandIsUnknownable<TCommand> extends true ? FlattenCommands<TCommands> : TCommand extends AnyPadroneCommand ? TCommand : TCommand extends string ? TCommand extends GetCommandPathsOrAliases<TCommands> ? PickCommandByName<TCommands, TCommand> : SplitLastSpace<TCommand> extends [infer Prefix extends string, infer Rest] ? IsNever<Rest> extends true ? PickCommandByName<TCommands, Prefix> : PickCommandByPossibleCommands<TCommands, Prefix> : never : never;
605
+ //#endregion
606
+ //#region src/types/interceptor.d.ts
607
+ /** Base context shared across all interceptor phases within a single execution. */
608
+ type InterceptorBaseContext<TContext = unknown> = {
609
+ /** The resolved command for this execution. In the parse phase, this is the root program. */command: AnyPadroneCommand; /** The raw CLI input string (undefined when invoked without input). */
610
+ input: string | undefined; /** Cancellation signal that fires when the process receives a termination signal. */
611
+ signal: AbortSignal; /** User-defined context object, resolved through the command's parent chain. */
612
+ context: TContext; /** The resolved runtime for this execution. Interceptors can override this before calling `next()`. */
613
+ runtime: ResolvedPadroneRuntime; /** The program instance. Available for extensions that need program-level methods. */
614
+ program: AnyPadroneProgram; /** The invocation method that triggered this execution (e.g. 'cli', 'eval', 'run'). */
615
+ caller: PadroneActionContext['caller'];
616
+ };
617
+ /** Context for the parse phase. */
618
+ type InterceptorParseContext<TContext = unknown> = InterceptorBaseContext<TContext>;
619
+ /** Result returned by the parse phase's `next()`. */
620
+ type InterceptorParseResult = {
621
+ command: AnyPadroneCommand;
622
+ rawArgs: Record<string, unknown>;
623
+ positionalArgs: string[];
624
+ };
625
+ /** Context for the validate phase. */
626
+ type InterceptorValidateContext<TContext = unknown> = InterceptorBaseContext<TContext> & {
627
+ /** Raw named arguments extracted by the parser. Mutable — modify before `next()` to inject/override values. */rawArgs: Record<string, unknown>; /** Positional argument strings extracted by the parser. */
628
+ positionalArgs: string[]; /** Interactive mode override (set by the interactive extension when `--interactive` / `-i` flag is used). */
629
+ interactive?: boolean; /** Interactive mode preference from eval/cli options. Available for the interactive extension. */
630
+ evalInteractive?: boolean;
631
+ };
632
+ /** Result returned by the validate phase's `next()`. */
633
+ type InterceptorValidateResult<TArgs = unknown> = {
634
+ args: TArgs;
635
+ argsResult: StandardSchemaV1.Result<TArgs>;
636
+ };
637
+ /** Context for the execute phase. Includes validate context fields (rawArgs, positionalArgs). */
638
+ type InterceptorExecuteContext<TArgs = unknown, TContext = unknown> = InterceptorValidateContext<TContext> & {
639
+ /** Validated arguments that will be passed to the action. Mutable — modify before `next()` to override. */args: TArgs;
640
+ };
641
+ /** Result returned by the execute phase's `next()`. */
642
+ type InterceptorExecuteResult<TResult = unknown> = {
643
+ result: TResult;
644
+ };
645
+ /** Context for the start phase. Runs before parsing, wraps the entire pipeline. */
646
+ type InterceptorStartContext<TContext = unknown> = InterceptorBaseContext<TContext>;
647
+ /** Context for the error phase. Called when the pipeline throws. Includes pipeline state accumulated before the error. */
648
+ type InterceptorErrorContext<TContext = unknown> = InterceptorBaseContext<TContext> & {
649
+ /** The error that was thrown. */error: unknown; /** Raw named arguments (available if parse completed). */
650
+ rawArgs?: Record<string, unknown>; /** Positional argument strings (available if parse completed). */
651
+ positionalArgs?: string[]; /** Validated arguments (available if validate completed). */
652
+ args?: unknown;
653
+ };
654
+ /** Result returned by the error phase's `next()`. */
655
+ type InterceptorErrorResult<TResult = unknown> = {
656
+ /** The error (possibly transformed). Set to `undefined` to suppress the error. */error?: unknown; /** A replacement result when suppressing the error. */
657
+ result?: TResult;
658
+ };
659
+ /** Context for the shutdown phase. Always runs after the pipeline (success or failure). Includes pipeline state accumulated before completion. */
660
+ type InterceptorShutdownContext<TResult = unknown, TContext = unknown> = InterceptorBaseContext<TContext> & {
661
+ /** The error, if the pipeline failed (after error phase processing). */error?: unknown; /** The pipeline result, if it succeeded. */
662
+ result?: TResult; /** Raw named arguments (available if parse completed). */
663
+ rawArgs?: Record<string, unknown>; /** Positional argument strings (available if parse completed). */
664
+ positionalArgs?: string[]; /** Validated arguments (available if validate completed). */
665
+ args?: unknown;
666
+ };
667
+ /** Overrides passable to `next()`. Provides autocomplete for common fields; accepts any phase-specific fields. */
668
+ type InterceptorNextOverrides = Partial<InterceptorBaseContext> & Record<string, unknown>;
669
+ /**
670
+ * A phase handler function for the interceptor middleware chain.
671
+ *
672
+ * - `TCtx` — the context object available to the handler.
673
+ * - `TNextResult` — the typed result returned by `next()`, giving the handler type-safe access to downstream output.
674
+ * - `TReturn` — the type the handler itself returns. Defaults to `TNextResult` but can be wider,
675
+ * allowing interceptors to transform or replace the result (e.g., error-recovery interceptors returning a different type).
676
+ */
677
+ type InterceptorPhaseHandler<TCtx, TNextResult, TReturn = TNextResult> = (ctx: TCtx, next: (overrides?: InterceptorNextOverrides) => TNextResult | Promise<TNextResult>) => TReturn | Promise<TReturn>;
678
+ /** Static metadata for an interceptor. Always available at registration time without calling the factory. */
679
+ type InterceptorMeta = {
680
+ /** Display name for this interceptor. Used for identification in logs and debugging. */name: string;
681
+ /**
682
+ * Optional unique identifier for deduplication. When multiple interceptors share the same `id`,
683
+ * only the last one registered is kept. Useful for allowing downstream code to override
684
+ * an interceptor without accumulating duplicates.
685
+ */
686
+ id?: string;
687
+ /**
688
+ * Ordering hint. Lower values run as outer layers (earlier before `next()`, later after).
689
+ * Interceptors with the same order preserve registration order. Defaults to `0`.
690
+ */
691
+ order?: number;
692
+ /**
693
+ * When `true`, the interceptor is skipped during execution. Combined with `id`-based deduplication,
694
+ * this lets downstream code disable an interceptor by re-registering it with `disabled: true`.
695
+ */
696
+ disabled?: boolean;
697
+ /**
698
+ * When `false`, the interceptor applies only to the command it was registered on
699
+ * and is not inherited by subcommands. Defaults to `true`.
700
+ */
701
+ inherit?: boolean;
702
+ };
703
+ /**
704
+ * Phase handler definitions returned by an interceptor factory.
705
+ * The factory's closure provides typed, scoped cross-phase state.
706
+ *
707
+ * Type parameters:
708
+ * - `TArgs` — the validated arguments type (output of the args schema).
709
+ * - `TResult` — the command's return type.
710
+ */
711
+ type InterceptorPhases<TArgs = unknown, TResult = unknown, TContext = unknown> = {
712
+ /**
713
+ * Runs before the pipeline (parse → validate → execute). `next()` proceeds to the pipeline.
714
+ * Root interceptors only. Use for startup tasks like telemetry, update checks, or global config loading.
715
+ */
716
+ start?: InterceptorPhaseHandler<InterceptorStartContext<TContext>, unknown>; /** Intercepts command routing and raw argument extraction. */
717
+ parse?: InterceptorPhaseHandler<InterceptorParseContext<TContext>, InterceptorParseResult>; /** Intercepts argument preprocessing and schema validation. Interactive prompting is handled by the interactive extension. */
718
+ validate?: InterceptorPhaseHandler<InterceptorValidateContext<TContext>, InterceptorValidateResult<TArgs>, InterceptorValidateResult>; /** Intercepts handler execution. */
719
+ execute?: InterceptorPhaseHandler<InterceptorExecuteContext<TArgs, TContext>, InterceptorExecuteResult<TResult>, InterceptorExecuteResult>;
720
+ /**
721
+ * Called when the pipeline throws an error. `next()` passes to the next error handler
722
+ * (innermost returns `{ error }` unchanged). Return `{ result }` without `error` to suppress.
723
+ */
724
+ error?: InterceptorPhaseHandler<InterceptorErrorContext<TContext>, InterceptorErrorResult<TResult>, InterceptorErrorResult>;
725
+ /**
726
+ * Always runs after the pipeline completes (success or failure). `next()` calls the next shutdown handler.
727
+ * Use for cleanup: closing connections, flushing logs, etc.
728
+ */
729
+ shutdown?: InterceptorPhaseHandler<InterceptorShutdownContext<TResult, TContext>, void>;
730
+ };
731
+ /**
732
+ * Factory function that creates phase handlers for an interceptor.
733
+ * Called once per command execution — the closure provides typed, scoped cross-phase state across phases.
734
+ */
735
+ type InterceptorFactory<TArgs = unknown, TResult = unknown, TContext = unknown> = () => InterceptorPhases<TArgs, TResult, TContext>;
736
+ /**
737
+ * A self-contained interceptor value: a factory function with static metadata as own properties.
738
+ * Created via `defineInterceptor(meta, factory)`. This is the distributable form — a single
739
+ * importable value that packages can export.
740
+ *
741
+ * Also accepted directly by `.intercept()` as the single-argument form.
742
+ * Call `.provides<T>()` to brand it as a context-providing interceptor.
743
+ */
744
+ type PadroneInterceptorFn<TArgs = unknown, TResult = unknown, TContext = unknown> = InterceptorFactory<TArgs, TResult, TContext> & InterceptorMeta & {
745
+ /** Brand this interceptor as providing additional context of type `TProvides`. No-op at runtime; purely a type-level cast. */provides: <TProvides>() => PadroneContextInterceptor<TProvides, TArgs, TResult, TContext>;
746
+ /**
747
+ * Brand this interceptor as requiring context of type `TRequires` to be available.
748
+ * `.intercept()` will produce a compile error if the required context is not satisfied.
749
+ * Use optional properties for soft requirements: `.requires<{ db: DB; logger?: Logger }>()`.
750
+ * No-op at runtime; purely a type-level cast.
751
+ */
752
+ requires: <TRequires>() => PadroneInterceptorFn<TArgs, TResult, TContext> & InterceptorRequiresBrand<TRequires>;
753
+ };
754
+ /**
755
+ * A Padrone interceptor in its single-value distributable form.
756
+ * Alias for `PadroneInterceptorFn` — this is the primary public type.
757
+ *
758
+ * Create with `defineInterceptor(meta, factory)` or pass `(meta, factory)` directly to `.intercept()`.
759
+ */
760
+ type PadroneInterceptor<TArgs = unknown, TResult = unknown, TContext = unknown> = PadroneInterceptorFn<TArgs, TResult, TContext>;
761
+ /**
762
+ * A context-providing interceptor. Carries a phantom `'~context'` brand declaring what it adds
763
+ * to the command context. When registered via `.intercept()`, the builder's context type is
764
+ * intersected with `TProvides`.
765
+ *
766
+ * Created by calling `.provides<T>()` on a `PadroneInterceptorFn`.
767
+ * Chain `.requires<T>()` to also declare context dependencies.
768
+ */
769
+ type PadroneContextInterceptor<TProvides = unknown, TArgs = unknown, TResult = unknown, TContext = unknown> = Omit<PadroneInterceptorFn<TArgs, TResult, TContext>, 'requires'> & InterceptorFactory<TArgs, TResult, TContext> & {
770
+ /** Phantom brand — declares the context type this interceptor provides. */'~context': TProvides; /** Like `.requires()` on `PadroneInterceptorFn` but preserves the `'~context'` brand. */
771
+ requires: <TRequires>() => PadroneContextInterceptor<TProvides, TArgs, TResult, TContext> & InterceptorRequiresBrand<TRequires>;
772
+ };
773
+ /**
774
+ * Phantom brand for context requirements. Uses a contravariant function type so that
775
+ * `.intercept()` overloads can check `TAvailableContext extends TRequires` via assignability.
776
+ */
777
+ type InterceptorRequiresBrand<TRequires> = {
778
+ '~contextRequires': (ctx: TRequires) => void;
779
+ };
780
+ /** Extracts the provided context type from a context-providing interceptor, or `unknown` if not branded. */
781
+ type ExtractInterceptorContext<T> = T extends {
782
+ '~context': infer C;
783
+ } ? C : unknown;
784
+ /** Extracts the required context type from an interceptor, or `unknown` if no requirements. */
785
+ type ExtractInterceptorRequires<T> = T extends {
786
+ '~contextRequires': (ctx: infer R) => void;
787
+ } ? R : unknown;
788
+ /**
789
+ * Checks whether an interceptor's context requirements are satisfied by the available context.
790
+ * Returns `true` if the interceptor has no requirements or if the available context extends the requirements.
791
+ */
792
+ type InterceptorRequiresCheck<TInterceptor, TAvailableContext> = TInterceptor extends {
793
+ '~contextRequires': (ctx: infer TReq) => void;
794
+ } ? TAvailableContext extends TReq ? true : false : true;
795
+ /** Error brand returned by `.intercept()` when the interceptor's required context is not satisfied. */
796
+ type InterceptorRequiresError = {
797
+ readonly '~error': 'Required context not satisfied. Ensure required interceptors are registered before this one.';
798
+ };
799
+ /**
800
+ * Builder returned by `defineInterceptor(meta)` (single-arg form).
801
+ * Call `.requires<T>()` to declare (and type) the context dependency, then `.factory()` to provide the phase handlers.
802
+ */
803
+ type InterceptorDefBuilder<TContext = unknown, TBrand = unknown> = {
804
+ /** Declare the context type this interceptor requires. Sets `TContext` for phase handler typing. */requires: <TRequires>() => InterceptorDefBuilder<TRequires, InterceptorRequiresBrand<TRequires>>; /** Provide the interceptor factory. Phase handlers receive the typed `TContext` from `.requires()`. */
805
+ factory: <TArgs = unknown, TResult = unknown>(factory: InterceptorFactory<TArgs, TResult, TContext>) => PadroneInterceptorFn<TArgs, TResult, TContext> & TBrand;
806
+ };
807
+ /**
808
+ * Internal stored form on command objects. Separates static metadata from the factory
809
+ * so that deduplication and sorting can happen without calling the factory.
810
+ */
811
+ type RegisteredInterceptor = {
812
+ meta: InterceptorMeta;
813
+ factory: InterceptorFactory<any, any, any>;
814
+ };
815
+ //#endregion
816
+ //#region src/types/command.d.ts
817
+ type UnknownRecord = Record<string, unknown>;
818
+ type DefaultArgs$1 = UnknownRecord | void;
819
+ /**
820
+ * Read-only metadata about a Padrone program.
821
+ * Returned by `program.info` to expose program-level properties without leaking internal command internals.
822
+ */
823
+ type PadroneProgramMeta<TName extends string = string> = {
824
+ /** The program name (CLI binary name). */name: TName; /** Display title shown in help output. */
825
+ title?: string; /** Program description. */
826
+ description?: string; /** Program version string. */
827
+ version?: string; /** Usage examples shown in help output. */
828
+ examples?: string[]; /** Whether the program is deprecated. */
829
+ deprecated?: boolean | string; /** Names of registered subcommands. */
830
+ commands: string[];
831
+ };
832
+ /**
833
+ * Context object passed as the second argument to command action handlers.
834
+ * Contains the resolved runtime, the executing command, and the program instance.
835
+ */
836
+ type PadroneActionContext<TContext = unknown> = {
837
+ /** The resolved runtime for this command (I/O, env, config, etc.). */runtime: ResolvedPadroneRuntime; /** The command being executed. */
838
+ command: AnyPadroneCommand; /** The root program instance. */
839
+ program: AnyPadroneProgram;
840
+ /**
841
+ * Cancellation signal that fires when the process receives SIGINT, SIGTERM, or SIGHUP.
842
+ * Use with `fetch()`, child processes, or any API that accepts `AbortSignal`.
843
+ * Check `signal.aborted` to test if cancellation was requested.
844
+ * The `signal.reason` is a `PadroneSignal` string ('SIGINT', 'SIGTERM', or 'SIGHUP').
845
+ */
846
+ signal: AbortSignal; /** User-defined context object. Set via `.context()` on the builder and provided at `cli()`/`eval()` time. */
847
+ context: TContext; /** Which API entry point triggered this execution. */
848
+ caller: 'cli' | 'eval' | 'run' | 'repl' | 'serve' | 'mcp' | 'tool';
849
+ };
850
+ /**
851
+ * Configuration for a command.
852
+ */
853
+ type PadroneCommandConfig = {
854
+ /** A short title for the command, displayed in help. */title?: string; /** A longer description of what the command does. */
855
+ description?: string; /** The version of the command. */
856
+ version?: string; /** Whether the command is deprecated, or a message explaining the deprecation. */
857
+ deprecated?: boolean | string; /** Whether the command should be hidden from help output. */
858
+ hidden?: boolean; /** Group name for organizing this command under a labeled section in help output. */
859
+ group?: string; /** Usage examples shown in help output. Each entry is a command-line invocation string. */
860
+ examples?: string[];
861
+ /**
862
+ * Whether this command performs a mutation (create, update, delete).
863
+ * - In `serve()`: mutation commands accept POST only; non-mutation commands accept GET and POST.
864
+ * - In `mcp()`: sets `annotations.destructiveHint` on the tool definition.
865
+ * - In `tool()`: defaults `needsApproval` to `true` when not explicitly set.
866
+ */
867
+ mutation?: boolean;
868
+ };
869
+ type PadroneCommand<TName extends string = string, TParentName extends string = '', TArgs extends PadroneSchema = PadroneSchema<DefaultArgs$1>, TRes = void, TCommands extends [...AnyPadroneCommand[]] = [], TAliases extends string[] = string[], TAsync extends boolean = false, TContext = unknown, TContextProvided = unknown> = {
870
+ name: TName;
871
+ path: FullCommandName<TName, TParentName>;
872
+ title?: string;
873
+ description?: string;
874
+ version?: string; /** Alternative names that can be used to invoke this command. Derived from the names passed to command(). */
875
+ aliases?: TAliases;
876
+ deprecated?: boolean | string;
877
+ hidden?: boolean; /** Group name for organizing this command under a labeled section in help output. */
878
+ group?: string; /** Whether this command performs a mutation (create, update, delete). Affects HTTP method in serve (POST-only) and MCP tool annotations (destructiveHint). */
879
+ mutation?: boolean;
880
+ needsApproval?: boolean | ((args: TArgs) => Promise<boolean> | boolean); /** Usage examples shown in help output. Each entry is a command-line invocation string. */
881
+ examples?: string[];
882
+ argsSchema?: TArgs;
883
+ meta?: GetArgsMeta<TArgs>;
884
+ action?: (args: StandardSchemaV1.InferOutput<TArgs>, ctx: PadroneActionContext<TContext & TContextProvided>) => TRes; /** Runtime flag indicating this command uses async validation. Set by `.async()` or `asyncSchema()`. */
885
+ isAsync?: boolean; /** Runtime configuration for I/O abstraction. */
886
+ runtime?: PadroneRuntime; /** Transform function that maps parent context to this command's context. Set by `.context(transform)`. */
887
+ contextTransform?: (ctx: unknown) => unknown; /** Interceptors registered on this command. Collected from the parent chain at execution time. */
888
+ interceptors?: RegisteredInterceptor[];
889
+ parent?: AnyPadroneCommand;
890
+ commands?: TCommands; /** @deprecated Internal use only */
891
+ '~types': {
892
+ name: TName;
893
+ parentName: TParentName;
894
+ path: FullCommandName<TName, TParentName>;
895
+ aliases: TAliases;
896
+ argsSchema: TArgs;
897
+ argsInput: StandardSchemaV1.InferInput<TArgs>;
898
+ argsOutput: StandardSchemaV1.InferOutput<TArgs>;
899
+ result: TRes;
900
+ commands: TCommands;
901
+ async: TAsync;
902
+ context: TContext;
903
+ contextProvided: TContextProvided;
904
+ };
905
+ };
906
+ type AnyPadroneCommand = PadroneCommand<string, any, any, any, [...AnyPadroneCommand[]], string[], any, any, any>;
907
+ /**
908
+ * Base type for extracting command information from builder or program.
909
+ * Both PadroneBuilder and PadroneProgram share this structure.
910
+ */
911
+ type CommandTypesBase = {
912
+ '~types': {
913
+ command: AnyPadroneCommand;
914
+ };
915
+ };
916
+ type GetArgsMeta<TArgs extends PadroneSchema> = PadroneArgsSchemaMeta<NonNullable<StandardSchemaV1.InferInput<TArgs>>>;
917
+ //#endregion
918
+ //#region src/types/preferences.d.ts
919
+ /**
920
+ * Options for `repl()` to customize the REPL session.
921
+ */
922
+ /** A single spacing value: blank line (`true`), separator string, or an array of these for multiple lines. */
923
+ type PadroneReplSpacing = boolean | string | (boolean | string)[];
924
+ type PadroneReplPreferences<TScope extends string = string> = {
925
+ /** The prompt string displayed before each input, or a function returning it. Defaults to `"<programName>> "`. */prompt?: string | (() => string);
926
+ /**
927
+ * A greeting message displayed when the REPL starts.
928
+ * When not provided, defaults to `"Welcome to <name> v<version>"` (or just `"Welcome to <name>"` if no version).
929
+ * Set to `false` to suppress the default greeting entirely.
930
+ */
931
+ greeting?: string | false;
932
+ /**
933
+ * A hint message displayed below the greeting in dimmed text.
934
+ * When not provided, defaults to `'Type ".help" for more information, ".exit" to quit.'`.
935
+ * Set to `false` to suppress the hint.
936
+ */
937
+ hint?: string | false; /** Initial history entries (most recent last). Arrow keys navigate history in the terminal. */
938
+ history?: string[]; /** Set to `false` to disable tab completion. Defaults to `true`. */
939
+ completion?: boolean;
940
+ /**
941
+ * Add spacing/separators around each command's output.
942
+ * A spacing value can be:
943
+ * - `true` — blank line
944
+ * - A string — separator line (single char like `'─'` repeats to terminal width, multi-char prints as-is)
945
+ * - An array of the above — multiple lines in order (e.g. `[true, '─']` for blank line then separator)
946
+ *
947
+ * Shorthand applies to both before and after. Use `{ before?, after? }` for independent control.
948
+ */
949
+ spacing?: PadroneReplSpacing | {
950
+ before?: PadroneReplSpacing;
951
+ after?: PadroneReplSpacing;
952
+ }; /** Prefix each line of command output/error with this string (e.g. `'│ '`, `' '`, `'▎ '`). */
953
+ outputPrefix?: string;
954
+ /**
955
+ * Start the REPL scoped to a command subtree. The scope path is a space-separated command path
956
+ * (e.g. `'db'` or `'db migrate'`). Commands are resolved relative to the scoped command.
957
+ * Users can change scope at runtime with `.scope <subcommand>` and `.scope ..`/`..`.
958
+ */
959
+ scope?: TScope;
960
+ };
961
+ /**
962
+ * Options that can be passed to `eval()` to control execution behavior.
963
+ */
964
+ type PadroneEvalPreferences = {
965
+ /**
966
+ * Controls interactive prompting for this execution.
967
+ * Overrides the runtime's `interactive` setting, but is itself overridden by `--interactive` / `-i` flags.
968
+ *
969
+ * - `undefined`: inherit from runtime (default).
970
+ * - `true`: force prompting for all configured interactive fields, even if values are already provided.
971
+ * - `false`: suppress all interactive prompts.
972
+ */
973
+ interactive?: boolean;
974
+ /**
975
+ * Override the runtime for this execution.
976
+ * Partial — only the provided fields replace the command's resolved runtime.
977
+ * Useful for capturing output, injecting test doubles, or running in non-terminal contexts (e.g. AI tool calls).
978
+ */
979
+ runtime?: PadroneRuntime;
980
+ /**
981
+ * User-defined context object passed to command action handlers via `ctx.context`.
982
+ * The context flows through the command tree and can be transformed by subcommands via `.context(transform)`.
983
+ */
984
+ context?: unknown; /** @internal Which API entry point triggered this execution. */
985
+ caller?: PadroneActionContext['caller'];
986
+ };
987
+ /**
988
+ * Options that can be passed to `cli()` to control execution behavior.
989
+ */
990
+ type PadroneCliPreferences = PadroneEvalPreferences;
991
+ //#endregion
992
+ //#region src/types/result.d.ts
993
+ type EmptyRecord = Record<string, never>;
994
+ type NormalizeArguments<TArgs> = IsGeneric<TArgs> extends true ? void | EmptyRecord : TArgs;
995
+ type GetArguments<TDir extends 'in' | 'out', TCommand extends AnyPadroneCommand> = TDir extends 'in' ? NormalizeArguments<TCommand['~types']['argsInput']> : NormalizeArguments<TCommand['~types']['argsOutput']>;
996
+ type GetResults<TCommand extends AnyPadroneCommand> = ReturnType<NonNullable<TCommand['action']>>;
997
+ /**
998
+ * Result of `drain()` — a discriminated union that never throws.
999
+ * On success, `value` holds the fully resolved/collected result; on failure, `error` holds the error.
1000
+ */
1001
+ type PadroneDrainResult<TResult> = {
1002
+ value: Drained<TResult>;
1003
+ error?: never;
1004
+ } | {
1005
+ error: unknown;
1006
+ value?: never;
1007
+ };
1008
+ /**
1009
+ * Result returned by `eval()`, `cli()`, and `run()`. Never thrown — errors are captured in the `error` field.
1010
+ * Discriminated union: check `error` to distinguish success from failure.
1011
+ *
1012
+ * On success: `command`, `args`, `argsResult`, `result` are populated; `error` is absent.
1013
+ * On failure: `error` is populated; `command` may be present if routing succeeded.
1014
+ */
1015
+ type PadroneCommandResult<TCommand extends AnyPadroneCommand = AnyPadroneCommand> = (PadroneParseResult<TCommand> & {
1016
+ result: GetResults<TCommand>;
1017
+ error?: never; /** The signal that caused cancellation, if any. */
1018
+ signal?: PadroneSignal; /** Suggested exit code (e.g. 130 for SIGINT). Present when a signal caused termination. */
1019
+ exitCode?: number; /** Flattens the result: awaits Promises, collects iterables, catches errors. Never throws. */
1020
+ drain: () => Promise<PadroneDrainResult<GetResults<TCommand>>>;
1021
+ }) | {
1022
+ command?: TCommand;
1023
+ args?: GetArguments<'out', TCommand>;
1024
+ argsResult?: StandardSchemaV1.Result<GetArguments<'out', TCommand>>;
1025
+ error: unknown;
1026
+ result?: never; /** The signal that caused cancellation, if any. */
1027
+ signal?: PadroneSignal; /** Suggested exit code (e.g. 130 for SIGINT). Present when a signal caused termination. */
1028
+ exitCode?: number; /** Returns `{ error }` since there is no result to drain. */
1029
+ drain: () => Promise<PadroneDrainResult<GetResults<TCommand>>>;
1030
+ };
1031
+ /**
1032
+ * Like `MaybePromise<PadroneCommandResult<TCommand>, TAsync>` but ensures `drain()` is available
1033
+ * at the outer level in all cases — both sync (Thenable) and async (Promise).
1034
+ */
1035
+ type MaybePromiseCommandResult<TCommand extends AnyPadroneCommand, TAsync> = MaybePromise<PadroneCommandResult<TCommand>, TAsync> & {
1036
+ drain: () => Promise<PadroneDrainResult<GetResults<TCommand>>>;
1037
+ };
1038
+ type PadroneParseResult<TCommand extends AnyPadroneCommand = AnyPadroneCommand> = {
1039
+ command: TCommand;
1040
+ args?: GetArguments<'out', TCommand>;
1041
+ argsResult?: StandardSchemaV1.Result<GetArguments<'out', TCommand>>;
1042
+ };
1043
+ type PadroneAPI<TCommand extends AnyPadroneCommand> = PadroneAPICommand<TCommand> & { [K in TCommand['~types']['commands'][number] as K['name']]: PadroneAPI<K> };
1044
+ type PadroneAPICommand<TCommand extends AnyPadroneCommand> = (args: GetArguments<'in', TCommand>) => GetResults<TCommand>;
1045
+ //#endregion
1046
+ //#region src/types/builder.d.ts
1047
+ /**
1048
+ * Helper type to set aliases on a command type.
1049
+ * Uses intersection to override just the aliases while preserving all other type information.
1050
+ */
1051
+ type WithAliases<TCommand extends AnyPadroneCommand, TAliases extends string[]> = Omit<TCommand, 'aliases' | '~types'> & {
1052
+ aliases?: TAliases;
1053
+ '~types': Omit<TCommand['~types'], 'aliases'> & {
1054
+ aliases: TAliases;
1055
+ };
1056
+ };
1057
+ /**
1058
+ * Resolves aliases for a command override: if new aliases are provided (non-empty), use them;
1059
+ * otherwise, preserve the existing command's aliases.
1060
+ */
1061
+ type ResolvedAliases<TCommands extends [...AnyPadroneCommand[]], TNameNested extends string, TAliases extends string[]> = TAliases extends [] ? FindDirectChild<TCommands, TNameNested> extends infer E extends AnyPadroneCommand ? E['~types']['aliases'] : [] : TAliases;
1062
+ /**
1063
+ * When TContext is `unknown` (no `.context()` called), context param is optional.
1064
+ * Otherwise it is required.
1065
+ */
1066
+ type ContextParam<TContext> = unknown extends TContext ? {
1067
+ context?: TContext;
1068
+ } : {
1069
+ context: TContext;
1070
+ };
1071
+ /** Options for the `mount()` method. */
1072
+ type MountOptions<TContext, TNewContext> = {
1073
+ context: (ctx: TContext) => TNewContext;
1074
+ };
1075
+ /**
1076
+ * Resolves the initial builder type for a `.command()` call.
1077
+ * If TNameNested already exists in TCommands, the builder starts pre-populated with that command's types.
1078
+ * Otherwise, a fresh builder with default types is used.
1079
+ */
1080
+ type InitialCommandBuilder<TProgramName extends string, TNameNested extends string, TParentPath extends string, TParentArgs extends PadroneSchema, TCommands extends [...AnyPadroneCommand[]], TParentContext> = [FindDirectChild<TCommands, TNameNested>] extends [never] ? PadroneBuilder<TProgramName, TNameNested, TParentPath, PadroneSchema<void>, void, [], TParentArgs, false, TParentContext> : FindDirectChild<TCommands, TNameNested> extends infer E extends AnyPadroneCommand ? PadroneBuilder<TProgramName, TNameNested, TParentPath, E['~types']['argsSchema'], E['~types']['result'], E['~types']['commands'], TParentArgs, E['~types']['async'], E['~types']['context'], E['~types']['contextProvided']> : PadroneBuilder<TProgramName, TNameNested, TParentPath, PadroneSchema<void>, void, [], TParentArgs, false, TParentContext>;
1081
+ type AnyPadroneBuilder = InitialCommandBuilder<string, string, string, any, [...AnyPadroneCommand[]], any>;
1082
+ /**
1083
+ * Like InitialCommandBuilder but uses `any` for args in the fresh case.
1084
+ * Used as the default for TBuilder when no builderFn is provided.
1085
+ */
1086
+ type DefaultCommandBuilder<TProgramName extends string, TNameNested extends string, TParentPath extends string, TParentArgs extends PadroneSchema, TCommands extends [...AnyPadroneCommand[]], TParentContext> = [FindDirectChild<TCommands, TNameNested>] extends [never] ? PadroneBuilder<TProgramName, TNameNested, TParentPath, any, void, [], TParentArgs, false, TParentContext> : FindDirectChild<TCommands, TNameNested> extends infer E extends AnyPadroneCommand ? PadroneBuilder<TProgramName, TNameNested, TParentPath, E['~types']['argsSchema'], E['~types']['result'], E['~types']['commands'], TParentArgs, E['~types']['async'], E['~types']['context'], E['~types']['contextProvided']> : PadroneBuilder<TProgramName, TNameNested, TParentPath, any, void, [], TParentArgs, false, TParentContext>;
1087
+ /**
1088
+ * Conditional type that returns either PadroneBuilder or PadroneProgram based on TReturn.
1089
+ * Used to avoid repetition in PadroneBuilderMethods return types.
1090
+ */
1091
+ type BuilderOrProgram<TReturn extends 'builder' | 'program', TProgramName extends string, TName extends string, TParentName extends string, TArgs extends PadroneSchema, TRes, TCommands extends [...AnyPadroneCommand[]], TParentArgs extends PadroneSchema, TAsync extends boolean, TContext, TContextProvided = unknown> = TReturn extends 'builder' ? PadroneBuilder<TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, TAsync, TContext, TContextProvided> : PadroneProgram<TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, TAsync, TContext, TContextProvided>;
1092
+ /**
1093
+ * Base builder methods shared between PadroneBuilder and PadroneProgram.
1094
+ * These methods are used for defining command structure (arguments, action, subcommands).
1095
+ */
1096
+ type PadroneBuilderMethods<TProgramName extends string, TName extends string, TParentName extends string, TArgs extends PadroneSchema, TRes, TCommands extends [...AnyPadroneCommand[]], TParentArgs extends PadroneSchema, TAsync extends boolean, TContext, TContextProvided, /** The return type for builder methods - either PadroneBuilder or PadroneProgram */TReturn extends 'builder' | 'program'> = {
1097
+ /** Apply a build-time extension that transforms this builder/program. @category Builder */extend: <TResult extends CommandTypesBase>(extension: PadroneExtension<BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, TAsync, TContext, TContextProvided>, TResult>) => TResult; /** Register a runtime interceptor for lifecycle phases (parse, validate, execute, etc.). @category Builder */
1098
+ intercept: {
1099
+ /** Context-providing interceptor — extends context type. Rejects if required context is not satisfied. */<TInterceptor extends PadroneContextInterceptor<any, StandardSchemaV1.InferOutput<TArgs>, TRes, any>>(interceptor: TInterceptor): InterceptorRequiresCheck<TInterceptor, TContext & TContextProvided> extends true ? BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, TAsync, TContext, TContextProvided & ExtractInterceptorContext<TInterceptor>> : InterceptorRequiresError; /** Plain interceptor — no context change. Rejects if required context is not satisfied. */
1100
+ <TInterceptor extends PadroneInterceptorFn<StandardSchemaV1.InferOutput<TArgs>, TRes, any>>(interceptor: TInterceptor): InterceptorRequiresCheck<TInterceptor, TContext & TContextProvided> extends true ? BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, TAsync, TContext, TContextProvided> : InterceptorRequiresError; /** Register an interceptor with static metadata and a factory function. Context is strongly typed. */
1101
+ (meta: InterceptorMeta, factory: InterceptorFactory<StandardSchemaV1.InferOutput<TArgs>, TRes, TContext & TContextProvided>): BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, TAsync, TContext, TContextProvided>;
1102
+ }; /** Set command metadata like title, description, version, hidden, deprecated, etc. @category Builder */
1103
+ configure: (config: PadroneCommandConfig) => BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, TAsync, TContext, TContextProvided>; /** Override the runtime adapter (process, IO, environment). @category Builder */
1104
+ runtime: (runtime: PadroneRuntime) => BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, TAsync, TContext, TContextProvided>; /** Mark this command as async, forcing all return types to be `Promise`-wrapped. @category Builder */
1105
+ async: () => BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, true, TContext, TContextProvided>;
1106
+ /**
1107
+ * Declare or transform the user-defined context type for this command.
1108
+ *
1109
+ * - Without a callback: narrows the context type (type-only, no runtime transform).
1110
+ * - With a callback: transforms the parent/current context into a new type. Chainable — multiple calls compose.
1111
+ *
1112
+ * Interceptor-provided context (`TContextProvided`) is preserved across `.context()` calls.
1113
+ * @category Builder
1114
+ */
1115
+ context: {
1116
+ <TNewContext>(): BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, TAsync, TNewContext, TContextProvided>;
1117
+ <TNewContext>(transform: (ctx: TContext) => TNewContext): BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, TAsync, TNewContext, TContextProvided>;
1118
+ }; /** Define the argument/option schema for this command. Accepts a Standard Schema or a function that extends the parent schema. @category Builder */
1119
+ arguments: <TNewArgs extends PadroneSchema = PadroneSchema<void>, TMeta extends GetArgsMeta<TNewArgs> = GetArgsMeta<TNewArgs>>(schema?: TNewArgs | ((parentSchema: TParentArgs) => TNewArgs), meta?: TMeta) => BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TNewArgs, TRes, TCommands, TParentArgs, OrAsyncMeta<OrAsync<TAsync, TNewArgs>, TMeta>, TContext, TContextProvided>; /** Set the handler function that runs when this command is executed. @category Builder */
1120
+ action: <TNewRes>(handler?: (args: StandardSchemaV1.InferOutput<TArgs>, ctx: PadroneActionContext<TContext & TContextProvided>, base: (args: StandardSchemaV1.InferOutput<TArgs>, ctx: PadroneActionContext<TContext & TContextProvided>) => TRes) => TNewRes) => BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TNewRes, TCommands, TParentArgs, TAsync, TContext, TContextProvided>; /** Wrap an external CLI tool, delegating execution to a shell command. @category Builder */
1121
+ wrap: <TWrapArgs extends PadroneSchema = TArgs>(config: WrapConfig<TArgs, TWrapArgs>) => BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, Promise<WrapResult>, TCommands, TParentArgs, TAsync, TContext, TContextProvided>; /** Add or override a subcommand. Pass a builder function to define its schema, action, and nested commands. @category Builder */
1122
+ command: <TNameNested extends string, TAliases extends string[] = [], TBuilder extends CommandTypesBase = DefaultCommandBuilder<TProgramName, TNameNested, FullCommandName<TName, TParentName>, TArgs, TCommands, TContext & TContextProvided>>(name: TNameNested | readonly [TNameNested, ...TAliases], builderFn?: (builder: InitialCommandBuilder<TProgramName, TNameNested, FullCommandName<TName, TParentName>, TArgs, TCommands, TContext & TContextProvided>) => TBuilder) => BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TRes, TCommands extends [] ? [WithAliases<TBuilder['~types']['command'], TAliases>] : AnyPadroneCommand[] extends TCommands ? [WithAliases<TBuilder['~types']['command'], TAliases>] : ReplaceOrAppendCommand<TCommands, TNameNested, WithAliases<TBuilder['~types']['command'], ResolvedAliases<TCommands, TNameNested, TAliases>>>, TParentArgs, TAsync, TContext, TContextProvided>; /** Mount an existing program as a subcommand, optionally transforming the context. @category Builder */
1123
+ mount: {
1124
+ <TNameNested extends string, TAliases extends string[] = [], TProgram extends CommandTypesBase = CommandTypesBase>(name: TNameNested | readonly [TNameNested, ...TAliases], program: TProgram): BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TRes, TCommands extends [] ? [WithAliases<PadroneCommand<TNameNested, FullCommandName<TName, TParentName>, TProgram['~types']['command']['~types']['argsSchema'], TProgram['~types']['command']['~types']['result'], RepathCommands<TProgram['~types']['command']['~types']['commands'], FullCommandName<TNameNested, FullCommandName<TName, TParentName>>>, [], TProgram['~types']['command']['~types']['async'], TContext & TContextProvided>, TAliases>] : AnyPadroneCommand[] extends TCommands ? [WithAliases<PadroneCommand<TNameNested, FullCommandName<TName, TParentName>, TProgram['~types']['command']['~types']['argsSchema'], TProgram['~types']['command']['~types']['result'], RepathCommands<TProgram['~types']['command']['~types']['commands'], FullCommandName<TNameNested, FullCommandName<TName, TParentName>>>, [], TProgram['~types']['command']['~types']['async'], TContext & TContextProvided>, TAliases>] : ReplaceOrAppendCommand<TCommands, TNameNested, WithAliases<PadroneCommand<TNameNested, FullCommandName<TName, TParentName>, TProgram['~types']['command']['~types']['argsSchema'], TProgram['~types']['command']['~types']['result'], RepathCommands<TProgram['~types']['command']['~types']['commands'], FullCommandName<TNameNested, FullCommandName<TName, TParentName>>>, [], TProgram['~types']['command']['~types']['async'], TContext & TContextProvided>, ResolvedAliases<TCommands, TNameNested, TAliases>>>, TParentArgs, TAsync, TContext, TContextProvided>;
1125
+ <TNameNested extends string, TAliases extends string[] = [], TProgram extends CommandTypesBase = CommandTypesBase, TNewContext = unknown>(name: TNameNested | readonly [TNameNested, ...TAliases], program: TProgram, options: MountOptions<TContext & TContextProvided, TNewContext>): BuilderOrProgram<TReturn, TProgramName, TName, TParentName, TArgs, TRes, TCommands extends [] ? [WithAliases<PadroneCommand<TNameNested, FullCommandName<TName, TParentName>, TProgram['~types']['command']['~types']['argsSchema'], TProgram['~types']['command']['~types']['result'], RepathCommands<TProgram['~types']['command']['~types']['commands'], FullCommandName<TNameNested, FullCommandName<TName, TParentName>>>, [], TProgram['~types']['command']['~types']['async'], TNewContext>, TAliases>] : AnyPadroneCommand[] extends TCommands ? [WithAliases<PadroneCommand<TNameNested, FullCommandName<TName, TParentName>, TProgram['~types']['command']['~types']['argsSchema'], TProgram['~types']['command']['~types']['result'], RepathCommands<TProgram['~types']['command']['~types']['commands'], FullCommandName<TNameNested, FullCommandName<TName, TParentName>>>, [], TProgram['~types']['command']['~types']['async'], TNewContext>, TAliases>] : ReplaceOrAppendCommand<TCommands, TNameNested, WithAliases<PadroneCommand<TNameNested, FullCommandName<TName, TParentName>, TProgram['~types']['command']['~types']['argsSchema'], TProgram['~types']['command']['~types']['result'], RepathCommands<TProgram['~types']['command']['~types']['commands'], FullCommandName<TNameNested, FullCommandName<TName, TParentName>>>, [], TProgram['~types']['command']['~types']['async'], TNewContext>, ResolvedAliases<TCommands, TNameNested, TAliases>>>, TParentArgs, TAsync, TContext, TContextProvided>;
1126
+ }; /** @deprecated Internal use only */
1127
+ '~types': {
1128
+ programName: TProgramName;
1129
+ name: TName;
1130
+ parentName: TParentName;
1131
+ path: FullCommandName<TName, TParentName>;
1132
+ aliases: [];
1133
+ argsSchema: TArgs;
1134
+ result: TRes;
1135
+ commands: TCommands;
1136
+ async: TAsync;
1137
+ context: TContext;
1138
+ contextProvided: TContextProvided;
1139
+ command: PadroneCommand<TName, TParentName, TArgs, TRes, TCommands, [], TAsync, TContext, TContextProvided>;
1140
+ };
1141
+ };
1142
+ type PadroneBuilder<TProgramName extends string = '', TName extends string = string, TParentName extends string = '', TArgs extends PadroneSchema = PadroneSchema<DefaultArgs>, TRes = void, TCommands extends [...AnyPadroneCommand[]] = [], TParentArgs extends PadroneSchema = PadroneSchema<void>, TAsync extends boolean = false, TContext = unknown, TContextProvided = unknown> = PadroneBuilderMethods<TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, TAsync, TContext, TContextProvided, 'builder'>;
1143
+ type PadroneProgram<TProgramName extends string = '', TName extends string = string, TParentName extends string = '', TArgs extends PadroneSchema = PadroneSchema<DefaultArgs>, TRes = void, TCommands extends [...AnyPadroneCommand[]] = [], TParentArgs extends PadroneSchema = PadroneSchema<void>, TAsync extends boolean = false, TContext = unknown, TContextProvided = unknown> = PadroneBuilderMethods<TProgramName, TName, TParentName, TArgs, TRes, TCommands, TParentArgs, TAsync, TContext, TContextProvided, 'program'> & {
1144
+ /** Execute a command by name with pre-validated args (skips parsing and validation). @category Execution */run: <const TCommand extends PossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>], true, true>>(name: TCommand | SafeString, args: NoInfer<GetArguments<'in', PickCommandByName<[PadroneCommand<'', '', TArgs, TRes, TCommands>], TCommand>>>, prefs?: ContextParam<TContext>) => PadroneCommandResult<PickCommandByName<[PadroneCommand<'', '', TArgs, TRes, TCommands>], TCommand>>; /** Parse and execute a string input through the full interceptor pipeline. @category Execution */
1145
+ eval: <const TCommand extends PossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>], true, true>>(input: TCommand | SafeString, prefs?: PadroneEvalPreferences & ContextParam<TContext>) => MaybePromiseCommandResult<PickCommandByPossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>], TCommand>, PickCommandByPossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>], TCommand>['~types']['async']>; /** Parse and execute from `process.argv` through the full interceptor pipeline. @category Execution */
1146
+ cli: (prefs?: PadroneCliPreferences & ContextParam<TContext>) => MaybePromiseCommandResult<FlattenCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>]>, TAsync>; /** Parse and validate input without executing the action. @category Execution */
1147
+ parse: <const TCommand extends PossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>], true, false>>(input?: TCommand | SafeString) => MaybePromise<PadroneParseResult<PickCommandByPossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>], TCommand>>, PickCommandByPossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>], TCommand>['~types']['async']>; /** Serialize args back into a CLI string. @category Utility */
1148
+ stringify: <const TCommand extends PossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>], false, true>>(command?: TCommand | SafeString, args?: GetArguments<'out', PickCommandByPossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>], TCommand>>) => string; /** Look up a command definition by name. @category Utility */
1149
+ find: <const TFind extends PossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>], false, true>>(command: TFind | SafeString) => PickCommandByPossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>], TFind> | undefined; /** Get a structured API representation of all commands. @category Utility */
1150
+ api: () => PadroneAPI<PadroneCommand<'', '', TArgs, TRes, TCommands>>; /** Start an interactive REPL session. @category Execution */
1151
+ repl: (options?: PadroneReplPreferences<PossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>]>>) => AsyncIterable<PadroneCommandResult<FlattenCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>]>>> & {
1152
+ drain: () => Promise<PadroneDrainResult<PadroneCommandResult<FlattenCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>]>>[]>>;
1153
+ }; /** Export as an AI SDK tool. @category Utility */
1154
+ tool: () => Tool<{
1155
+ command: string;
1156
+ }>; /** Generate help text for a command. @category Utility */
1157
+ help: <const TCommand extends PossibleCommands<[PadroneCommand<'', '', TArgs, TRes, TCommands>], false, true>>(command?: TCommand, prefs?: HelpPreferences) => string; /** Generate shell completion script. @category Utility */
1158
+ completion: (shell?: 'bash' | 'zsh' | 'fish' | 'powershell') => Promise<string>; /** Start a Model Context Protocol server. @category Server */
1159
+ mcp: (prefs?: PadroneMcpPreferences) => Promise<void>; /** Start a REST HTTP server with OpenAPI docs. @category Server */
1160
+ serve: (prefs?: PadroneServePreferences) => Promise<void>; /** Read-only metadata about the program (name, version, description, commands, etc.). @category Utility */
1161
+ info: PadroneProgramMeta<TProgramName>;
1162
+ };
1163
+ type AnyPadroneProgram = PadroneProgram<string, string, string, any, any, [...AnyPadroneCommand[]]>;
1164
+ /**
1165
+ * A build-time extension that transforms a builder/program.
1166
+ * Extensions can add commands, arguments, interceptors, configure settings, etc.
1167
+ *
1168
+ * Use with `.extend(extension)`:
1169
+ * ```ts
1170
+ * const withAuth = (b) => b.arguments(authSchema).command('login', ...)
1171
+ * program.extend(withAuth)
1172
+ * ```
1173
+ */
1174
+ type PadroneExtension<TIn extends CommandTypesBase = CommandTypesBase, TOut extends CommandTypesBase = TIn> = (builder: TIn) => TOut;
1175
+ type DefaultArgs = Record<string, unknown> | void;
1176
+ //#endregion
1177
+ export { PadroneProgressOptions as $, InterceptorStartContext as A, WithInterceptor as B, InterceptorExecuteResult as C, InterceptorParseResult as D, InterceptorParseContext as E, PadroneInterceptorFn as F, PadroneServePreferences as G, PadroneSchema as H, Drained as I, InteractivePromptConfig as J, PadroneMcpPreferences as K, PickCommandByName as L, InterceptorValidateResult as M, PadroneContextInterceptor as N, InterceptorPhases as O, PadroneInterceptor as P, PadroneProgressIndicator as Q, PossibleCommands as R, InterceptorExecuteContext as S, InterceptorMeta as T, WrapConfig as U, AsyncPadroneSchema as V, WrapResult as W, PadroneBarChar as X, PadroneBarAnimation as Y, PadroneBarConfig as Z, ExtractInterceptorRequires as _, PadroneProgram as a, PadroneSpinnerPreset as at, InterceptorErrorContext as b, PadroneParseResult as c, CommandTypesBase as d, PadroneProgressShow as et, GetArgsMeta as f, ExtractInterceptorContext as g, PadroneProgramMeta as h, PadroneExtension as i, PadroneSpinnerConfig as it, InterceptorValidateContext as j, InterceptorShutdownContext as k, PadroneReplPreferences as l, PadroneCommand as m, AnyPadroneProgram as n, PadroneRuntime as nt, PadroneCommandResult as o, REPL_SIGINT as ot, PadroneActionContext as p, InteractiveMode as q, PadroneBuilder as r, PadroneSignal as rt, PadroneDrainResult as s, AnyPadroneBuilder as t, PadroneProgressUpdate as tt, AnyPadroneCommand as u, InterceptorBaseContext as v, InterceptorFactory as w, InterceptorErrorResult as x, InterceptorDefBuilder as y, WithCommand as z };
1178
+ //# sourceMappingURL=index-BaU3X6dY.d.mts.map