@politty/valibot 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +31 -0
  2. package/dist/cli-main-B4FX3h4J.js +1 -0
  3. package/dist/cli-main-CjYk6tAX.js +2 -0
  4. package/dist/cli-run-NzniMJwW.js +1 -0
  5. package/dist/cli.js +1 -15
  6. package/dist/command-Mbdt0bmN.js +1 -0
  7. package/dist/compile-cache-VuUbFWIo.js +1 -0
  8. package/dist/compile-cache.js +1 -3
  9. package/dist/completion-D8DMrPqg.js +116 -0
  10. package/dist/completion-DUMcvXkT.js +1 -0
  11. package/dist/completion.d.ts +87 -7
  12. package/dist/completion.js +1 -4
  13. package/dist/docs.d.ts +1 -1
  14. package/dist/docs.js +84 -3063
  15. package/dist/dynamic-CMtee4tD.js +1 -0
  16. package/dist/dynamic-CrnlveHj.js +6 -0
  17. package/dist/field-meta-COGya7xp.js +1 -0
  18. package/dist/index.d.ts +3 -3
  19. package/dist/index.js +1 -27
  20. package/dist/log-collector-DICKib75.js +1 -0
  21. package/dist/logger-CJsyJ8sb.js +1 -0
  22. package/dist/prompt-CqmGq1_N.js +1 -0
  23. package/dist/prompt-clack.d.ts +1 -1
  24. package/dist/prompt-clack.js +1 -32
  25. package/dist/prompt-inquirer.d.ts +1 -1
  26. package/dist/prompt-inquirer.js +1 -47
  27. package/dist/prompt.d.ts +1 -1
  28. package/dist/prompt.js +1 -4
  29. package/dist/register-BnpFle4e.js +1 -0
  30. package/dist/runner-BIdcntiz.js +29 -0
  31. package/dist/runner-Chaf_5lK.js +1 -0
  32. package/dist/schema-BiUP_KyV.js +1 -0
  33. package/dist/schema-extractor-DU0Vuhbd.js +1 -0
  34. package/dist/skill.d.ts +1 -1
  35. package/dist/skill.js +2 -1803
  36. package/dist/subcommand-router-D8GTMXYL.js +1 -0
  37. package/dist/{arg-registry-Be4GJADw.d.ts → types-BBh8jmcS.d.ts} +839 -839
  38. package/dist/{index-B4NylQOW.d.ts → with-completion-command-BmOeO0qq.d.ts} +3 -74
  39. package/dist/with-completion-command-DDohm8U6.js +3 -0
  40. package/package.json +3 -3
  41. package/dist/cli-main-CGU1lFOR.js +0 -3
  42. package/dist/cli-main-zB-0qgHP.js +0 -314
  43. package/dist/cli-run-kxxQnIi_.js +0 -8
  44. package/dist/command-k-4yAz4J.js +0 -42
  45. package/dist/compile-cache-BC65o7MH.js +0 -103
  46. package/dist/completion-Ot2qpNNw.js +0 -5616
  47. package/dist/field-meta-CO38jOvl.js +0 -148
  48. package/dist/log-collector-CoUkLVJB.js +0 -114
  49. package/dist/logger-i_bb-Jhc.js +0 -133
  50. package/dist/prompt-BjIZThsH.js +0 -169
  51. package/dist/register-B9K5n0KG.js +0 -494
  52. package/dist/runner-Bz3arOqh.js +0 -3051
  53. package/dist/runner-Cs-Mz9JN.js +0 -3
  54. package/dist/schema-extractor-CVNDs07l.js +0 -250
  55. package/dist/src-CNyWzJXg.js +0 -6
  56. package/dist/src-CoQ2TUba.js +0 -12
  57. package/dist/subcommand-router-Cskpofdk.js +0 -134
@@ -44,996 +44,996 @@ interface SchemaLike<Output = unknown> {
44
44
  /** Infer the output type of a {@link SchemaLike}. */
45
45
  type InferSchemaOutput<S> = S extends SchemaLike ? NonNullable<S["~standard"]["types"]>["output"] : never;
46
46
  //#endregion
47
- //#region ../core/src/adapter/field-meta.d.ts
47
+ //#region ../core/src/core/dynamic-completion-types.d.ts
48
48
  /**
49
- * Resolved metadata for an argument field
49
+ * Types for in-process dynamic value completion.
50
+ *
51
+ * A `resolve` callback registered on `arg(...)` receives parsed context
52
+ * (other arg values typed so far, previous values supplied to the same
53
+ * option, the current word being completed, target shell) and returns
54
+ * candidates. The callback runs inside the `__complete` command. Dispatcher
55
+ * shell scripts call `__complete` for every completion request; static shell
56
+ * scripts delegate to it for any spec that uses `resolve`.
57
+ *
58
+ * Defined under `core/` (not `completion/`) so `arg-registry.ts` can
59
+ * reference the resolver type without crossing the lint-enforced
60
+ * `completion → core` boundary.
50
61
  */
51
- interface ResolvedFieldMeta {
52
- /** Field name (camelCase, as defined in schema) */
53
- name: string;
54
- /** CLI option name (kebab-case, for command line usage) */
55
- cliName: string;
56
- /**
57
- * Aliases for this option, normalized to an array.
58
- * 1-char entries are short aliases (`-v`); multi-char entries are long
59
- * aliases (`--to-be`).
60
- */
61
- alias?: string[] | undefined;
62
- /**
63
- * Aliases that are accepted at parse time but hidden from help,
64
- * generated docs, and shell completion.
65
- */
66
- hiddenAlias?: string[] | undefined;
67
- /** Argument description */
68
- description?: string | undefined;
69
- /** Whether this is a positional argument */
70
- positional: boolean;
71
- /** Placeholder for help display */
72
- placeholder?: string | undefined;
73
- /**
74
- * Environment variable name(s) to read value from.
75
- * If an array, earlier entries take priority.
76
- */
77
- env?: string | string[] | undefined;
78
- /** Whether this argument is required */
79
- required: boolean;
80
- /** Default value if any */
81
- defaultValue?: unknown;
82
- /** Detected type from schema */
83
- type: "string" | "number" | "boolean" | "array" | "unknown";
62
+ /** Bitmask combining `CompletionDirective` values. */
63
+ type CompletionDirectiveMask = number;
64
+ interface DynamicCompletionContext {
65
+ /** Word being completed. `--field=` inline prefix is stripped before this is set. */
66
+ currentWord: string;
67
+ /** Target shell formatting requested by the caller. */
68
+ shell: "bash" | "zsh" | "fish";
84
69
  /**
85
- * Original field schema, carried through opaquely for downstream
86
- * consumers. Its concrete type belongs to the adapter's schema library
87
- * (zod, valibot, or an internal descriptor); core never calls into it.
70
+ * Best-effort parsed values of OTHER args on the same command, keyed by
71
+ * camelCase name. Includes positionals and other options. Zod validation
72
+ * is NOT applied; values are raw strings (or arrays of raw strings for
73
+ * array-typed options/variadic positionals).
88
74
  */
89
- schema: unknown;
90
- /** True if this overrides built-in aliases (-h, -H) */
91
- overrideBuiltinAlias?: true;
92
- /** Enum values if detected from schema (z.enum) */
93
- enumValues?: string[] | undefined;
94
- /** Completion metadata from arg() */
95
- completion?: CompletionMeta | undefined;
96
- /** Prompt metadata from arg() for interactive input */
97
- prompt?: PromptMeta | undefined;
75
+ parsedArgs: Readonly<Record<string, unknown>>;
98
76
  /**
99
- * Negation configuration for this boolean field.
100
- *
101
- * - String (e.g. `"disable-cache"`): the default `--no-<cliName>` form is
102
- * suppressed and only `--<negation>` (plus its camelCase variant) is
103
- * accepted as the negation flag.
104
- * - `true`: the default `--no-<cliName>` form is accepted **and** shown in
105
- * help, generated docs, and shell completions.
106
- * - `false`: neither the default `--no-<cliName>` nor any custom name is
107
- * accepted; the field only responds to the positive flag.
108
- * - `undefined`: no negation form is accepted or shown.
109
- *
110
- * Only applies to boolean fields; populated as `undefined` otherwise.
77
+ * Values already supplied for the SAME option/positional being completed.
78
+ * Useful for de-duplicating repeated array options.
111
79
  */
112
- negation?: string | boolean | undefined;
80
+ previousValues: readonly string[];
113
81
  /**
114
- * Derived display name (no `--` prefix) for the negation flag in help,
115
- * generated docs, and shell completions. `undefined` means the negation
116
- * is hidden from those surfaces. Computed from `negation` + `cliName`.
82
+ * Subcommand path from root (e.g. ["api"]). Reflects what the user
83
+ * actually typed — aliases are NOT resolved to their canonical names, so
84
+ * resolvers that branch on the path should accept every alias they care
85
+ * about.
117
86
  */
118
- negationDisplay?: string | undefined;
119
- /** Description shown for the negation option in help/docs. */
120
- negationDescription?: string | undefined;
121
- /** Side-effect callback from arg() metadata */
122
- effect?: ((value: unknown, context: EffectContext) => void | PromiseLike<void>) | undefined;
87
+ subcommandPath: readonly string[];
123
88
  }
124
- /**
125
- * Extracted fields from a schema
126
- */
127
- interface ExtractedFields {
128
- /** All field definitions */
129
- fields: ResolvedFieldMeta[];
130
- /** Original schema for validation */
131
- schema: ArgsSchema;
132
- /** Schema type */
133
- schemaType: "object" | "discriminatedUnion" | "union" | "xor" | "intersection";
134
- /** Discriminator key (for discriminatedUnion) */
135
- discriminator?: string;
136
- /** Variants (for discriminatedUnion) */
137
- variants?: Array<{
138
- discriminatorValue: string;
139
- fields: ResolvedFieldMeta[];
140
- description?: string;
141
- }>;
142
- /** Options (for union) */
143
- unionOptions?: ExtractedFields[];
144
- /** Schema description */
89
+ interface DynamicCompletionCandidate {
90
+ value: string;
145
91
  description?: string;
92
+ }
93
+ interface DynamicCompletionResult {
94
+ /** Candidates to surface. Strings or `{value, description}` objects. */
95
+ candidates: Array<string | DynamicCompletionCandidate>;
146
96
  /**
147
- * Unknown keys handling mode
148
- * - "strict": Unknown keys cause validation errors (z.strictObject or z.object().strict())
149
- * - "strip": Unknown keys trigger warnings (default, z.object())
150
- * - "passthrough": Unknown keys are silently ignored (z.looseObject or z.object().passthrough())
97
+ * Optional directive override. When omitted, defaults to
98
+ * `FilterPrefix | NoFileCompletion` (matches `choices` behaviour).
151
99
  */
152
- unknownKeysMode: UnknownKeysMode;
100
+ directive?: CompletionDirectiveMask;
153
101
  }
102
+ type DynamicCompletionResolver = (ctx: DynamicCompletionContext) => DynamicCompletionResult | Promise<DynamicCompletionResult>;
103
+ //#endregion
104
+ //#region ../core/src/core/expand-completion-types.d.ts
154
105
  /**
155
- * Unknown keys handling mode for object schemas
156
- * - "strict": Unknown keys cause validation errors
157
- * - "strip": Unknown keys are silently ignored (default)
158
- * - "passthrough": Unknown keys are passed through
159
- */
160
- type UnknownKeysMode = "strict" | "strip" | "passthrough";
161
- /**
162
- * Convert camelCase to kebab-case
163
- * @example toKebabCase("dryRun") => "dry-run"
164
- * @example toKebabCase("outputDir") => "output-dir"
165
- * @example toKebabCase("XMLParser") => "xml-parser"
106
+ * Types for "expand" completion — candidates that depend on sibling arg
107
+ * values.
108
+ *
109
+ * The user provides `dependsOn` (sibling arg names that must have static
110
+ * `choices` or an enum schema) and `enumerate(deps)`. Dispatcher scripts call
111
+ * `enumerate` inside `__complete` for the dependency values already typed on
112
+ * the command line. Static scripts walk the cartesian product of the
113
+ * dependsOn values, call `enumerate` for each combination, and emit a shell
114
+ * lookup table.
115
+ *
116
+ * Defined under `core/` (not `completion/`) so `arg-registry.ts` can
117
+ * reference these types without crossing the lint-enforced
118
+ * `completion → core` boundary.
166
119
  */
167
- declare function toKebabCase(str: string): string;
120
+ /** Candidate returned by an `enumerate` callback. */
121
+ interface ExpandCandidate {
122
+ value: string;
123
+ description?: string;
124
+ }
125
+ /** Resolved candidate stored on a {@link ValueCompletion} after enumeration. */
126
+ interface ResolvedExpandCandidate {
127
+ value: string;
128
+ description?: string;
129
+ }
168
130
  /**
169
- * Convert hyphen-separated sequences to camelCase.
131
+ * User-facing spec attached to `completion.custom.expand`.
170
132
  *
171
- * Replaces `-x` (hyphen followed by a lowercase letter) with the uppercase
172
- * variant. Non-hyphenated input (e.g., already camelCase) is returned as-is.
133
+ * `dependsOn` lists sibling args (camelCase names) whose values determine
134
+ * which candidates apply. Each named arg must have a static set of values —
135
+ * either an explicit `completion.custom.choices` or an enum schema. The
136
+ * order of `dependsOn` is the order in which `deps` keys are exposed to
137
+ * `enumerate`.
173
138
  *
174
- * @param str - A string that may contain hyphens
175
- * @example toCamelCase("dry-run") => "dryRun"
176
- * @example toCamelCase("output-dir") => "outputDir"
177
- * @example toCamelCase("dryRun") => "dryRun"
139
+ * In dispatcher mode, `enumerate` runs during `__complete` for the dependency
140
+ * values already typed by the user. In static mode, it runs once per
141
+ * cartesian-product combination at script-generation time (e.g. when the user
142
+ * runs `<program> completion zsh --static`). It must be a pure function of
143
+ * `deps`.
178
144
  */
179
- declare function toCamelCase(str: string): string;
145
+ interface ExpandCompletion {
146
+ dependsOn: readonly string[];
147
+ enumerate: (deps: Readonly<Record<string, string>>) => ReadonlyArray<string | ExpandCandidate>;
148
+ }
180
149
  //#endregion
181
- //#region ../core/src/lazy.d.ts
150
+ //#region ../core/src/core/arg-registry.d.ts
182
151
  /**
183
- * A lazily-loaded command that carries synchronous metadata for
184
- * static analysis (completion, help) while deferring full module
185
- * loading to execution time.
152
+ * Built-in completion types
186
153
  */
187
- interface LazyCommand<T extends AnyCommand = AnyCommand> {
188
- readonly __politty_lazy__: true;
189
- readonly meta: T;
190
- readonly load: () => Promise<AnyCommand>;
191
- }
154
+ type CompletionType = "file" | "directory" | "none";
192
155
  /**
193
- * Type guard: check if a value is a LazyCommand
156
+ * Custom completion specification.
157
+ *
158
+ * `choices`, `shellCommand`, `resolve`, and `expand` are mutually exclusive —
159
+ * specifying more than one throws when the field metadata is resolved.
194
160
  */
195
- declare function isLazyCommand(value: unknown): value is LazyCommand;
161
+ interface CustomCompletion {
162
+ /** Static list of choices for completion */
163
+ choices?: string[];
164
+ /** Shell command to execute for dynamic completion */
165
+ shellCommand?: string;
166
+ /**
167
+ * In-process JS callback for dynamic completion. Receives parsed context
168
+ * (other arg values typed so far, previously supplied values for this same
169
+ * option) and returns candidates. Dispatcher scripts call
170
+ * `<program> __complete` for every completion request; static scripts
171
+ * delegate to it whenever this is set.
172
+ */
173
+ resolve?: DynamicCompletionResolver;
174
+ /**
175
+ * Completion whose candidates depend on sibling arg values. Dispatcher
176
+ * scripts call `enumerate` inside `__complete` for the dependency values
177
+ * already typed on the command line. Static scripts pre-enumerate every
178
+ * combination of `dependsOn` values at script-generation time and dispatch
179
+ * via a shell lookup table.
180
+ */
181
+ expand?: ExpandCompletion;
182
+ }
196
183
  /**
197
- * Create a lazily-loaded subcommand with synchronous metadata.
198
- *
199
- * The `meta` command provides names, descriptions, and args schema
200
- * for static analysis (completion scripts, help text) without loading
201
- * the full command module.
202
- *
203
- * The `load` function is called only at execution time.
184
+ * Completion metadata for an argument
204
185
  *
205
186
  * @example
206
187
  * ```ts
207
- * import { lazy, defineCommand } from "politty";
188
+ * // File completion with extension filter
189
+ * input: arg(z.string(), {
190
+ * completion: { type: "file", extensions: ["json", "yaml"] }
191
+ * })
208
192
  *
209
- * const cli = defineCommand({
210
- * name: "mycli",
211
- * subCommands: {
212
- * deploy: lazy(
213
- * defineCommand({
214
- * name: "deploy",
215
- * description: "Deploy the application",
216
- * args: z.object({ env: arg(z.string()) }),
217
- * }),
218
- * () => import("./deploy.js").then((m) => m.deployCommand),
219
- * ),
220
- * },
221
- * });
193
+ * // Directory completion
194
+ * outputDir: arg(z.string(), {
195
+ * completion: { type: "directory" }
196
+ * })
197
+ *
198
+ * // Custom static choices
199
+ * logLevel: arg(z.string(), {
200
+ * completion: { custom: { choices: ["debug", "info", "warn", "error"] } }
201
+ * })
202
+ *
203
+ * // Dynamic completion from shell command
204
+ * branch: arg(z.string(), {
205
+ * completion: { custom: { shellCommand: "git branch --format='%(refname:short)'" } }
206
+ * })
207
+ *
208
+ * // File completion with glob pattern matcher
209
+ * envFile: arg(z.string(), {
210
+ * completion: { type: "file", matcher: [".env.*"] }
211
+ * })
222
212
  * ```
223
213
  */
224
- declare function lazy<T extends AnyCommand>(meta: T, load: () => Promise<AnyCommand>): LazyCommand<T>;
225
- //#endregion
226
- //#region ../core/src/types.d.ts
214
+ type CompletionMeta = {
215
+ /** Built-in completion type */
216
+ type?: CompletionType;
217
+ /** Custom completion (takes precedence over type if both specified) */
218
+ custom?: CustomCompletion;
219
+ } & ({
220
+ /** File extension filter (only applies when type is "file") */ extensions?: string[];
221
+ matcher?: never;
222
+ } | {
223
+ /** Glob patterns for file matching (only applies when type is "file") */ matcher?: string[];
224
+ extensions?: never;
225
+ });
227
226
  /**
228
- * Global args interface for declaration merging (Pattern 3).
229
- * Users can extend this interface to add global options to all commands:
227
+ * Prompt input type for interactive prompts
230
228
  *
231
- * ```ts
232
- * declare module "politty" {
233
- * interface GlobalArgs { verbose: boolean; config?: string; }
234
- * }
235
- * ```
229
+ * - "text": free-form text input (default for string schemas)
230
+ * - "password": masked text input
231
+ * - "confirm": yes/no prompt (default for boolean schemas)
232
+ * - "select": single selection from choices (default for enum schemas)
233
+ * - "file": file path input (inherited from completion type)
234
+ * - "directory": directory path input (inherited from completion type)
236
235
  */
237
- interface GlobalArgs {}
236
+ type PromptType = "text" | "password" | "confirm" | "select" | "file" | "directory";
238
237
  /**
239
- * Detect empty interface (used for GlobalArgs declaration merging)
238
+ * Prompt metadata for interactive input when a value is missing.
239
+ * Used by the `politty/prompt` module to request user input for unresolved arguments.
240
+ *
241
+ * @example
242
+ * ```ts
243
+ * // Custom prompt message
244
+ * name: arg(z.string(), {
245
+ * prompt: { message: "What is your name?" }
246
+ * })
247
+ *
248
+ * // Password input (masked)
249
+ * token: arg(z.string(), {
250
+ * prompt: { type: "password", message: "Enter API token" }
251
+ * })
252
+ *
253
+ * // Select with custom choices
254
+ * region: arg(z.string(), {
255
+ * prompt: { choices: ["us-east-1", "eu-west-1", "ap-northeast-1"] }
256
+ * })
257
+ * ```
240
258
  */
241
- type IsEmpty<T> = keyof T extends never ? true : false;
259
+ interface PromptMeta {
260
+ /** Prompt message shown to the user. Defaults to the field's description or name. */
261
+ message?: string;
262
+ /** Explicit prompt type. Overrides auto-detection from schema/completion. */
263
+ type?: PromptType;
264
+ /** Choices for select prompt. Overrides enum values from schema. */
265
+ choices?: Array<string | {
266
+ label: string;
267
+ value: string;
268
+ }>;
269
+ /** Whether to enable prompting for this field (default: true when prompt is set) */
270
+ enabled?: boolean;
271
+ }
242
272
  /**
243
- * Where a resolved arg value came from:
244
- * - `"cli"`: an explicit CLI token (flag or positional)
245
- * - `"env"`: `field.env` fallback (no CLI token was provided)
246
- * - `"default"`: neither of the above (e.g. a schema default, or a value
247
- * resolved by a `prompt` handler)
273
+ * Context provided to effect callbacks.
274
+ * When GlobalArgs is extended via declaration merging, `globalArgs` is typed accordingly.
248
275
  */
249
- type ArgSource = "cli" | "env" | "default";
276
+ type EffectContext = {
277
+ /** Field name (camelCase) */
278
+ name: string;
279
+ /** Validated args for this schema (global args for global effects, command args for command effects) */
280
+ args: Readonly<Record<string, unknown>>;
281
+ } & (IsEmpty<GlobalArgs> extends true ? {
282
+ globalArgs?: Readonly<Record<string, unknown>>;
283
+ } : {
284
+ globalArgs?: Readonly<GlobalArgs>;
285
+ });
250
286
  /**
251
- * Identifies the CLI name a command was invoked with in the current run.
252
- * - `name`: the literal token typed on the CLI to reach this command
253
- * (a canonical subcommand name or one of its `aliases`).
254
- * - `aliasFor`: set only when `name` is an alias, to the canonical
255
- * subcommand name it resolves to; `undefined` when invoked by its
256
- * canonical name (or run directly, with no subcommand routing involved).
287
+ * Base metadata shared by all argument types
257
288
  */
258
- interface RunInvocation {
259
- /** The name or alias actually typed on the CLI to reach this command */
260
- name: string;
261
- /** Canonical name `name` is an alias for; undefined when not an alias */
262
- aliasFor?: string | undefined;
289
+ interface BaseArgMeta<TValue = unknown> {
290
+ /** Argument description */
291
+ description?: string;
292
+ /** Treat as positional argument */
293
+ positional?: boolean;
294
+ /** Placeholder for help display */
295
+ placeholder?: string;
296
+ /**
297
+ * Environment variable name(s) to read value from.
298
+ * If an array is provided, earlier entries take priority.
299
+ * CLI arguments always take precedence over environment variables.
300
+ *
301
+ * @example
302
+ * ```ts
303
+ * // Single env var
304
+ * port: arg(z.coerce.number(), { env: "PORT" })
305
+ *
306
+ * // Multiple env vars (PORT takes priority over SERVER_PORT)
307
+ * port: arg(z.coerce.number(), { env: ["PORT", "SERVER_PORT"] })
308
+ * ```
309
+ */
310
+ env?: string | string[];
311
+ /** Completion configuration for shell tab-completion */
312
+ completion?: CompletionMeta;
313
+ /**
314
+ * Interactive prompt configuration for missing values.
315
+ * When set, the `politty/prompt` module will prompt the user interactively
316
+ * if this argument is not provided via CLI args or environment variables.
317
+ *
318
+ * @example
319
+ * ```ts
320
+ * name: arg(z.string(), {
321
+ * description: "User name",
322
+ * prompt: { message: "What is your name?" },
323
+ * })
324
+ * ```
325
+ */
326
+ prompt?: PromptMeta;
327
+ /**
328
+ * Control the boolean negation option.
329
+ *
330
+ * Boolean fields accept `--no-<cliName>` (and the camelCase `--no<Name>`
331
+ * form) to set the value to `false` only when `negation: true` is set.
332
+ * By default no negation form is accepted. This option lets you customize
333
+ * or expose that behavior:
334
+ *
335
+ * - `string` — replaces the auto-generated `--no-*` form with a custom
336
+ * name. The default `--no-*` is no longer recognized.
337
+ * - `true` — enables the default `--no-<cliName>` form and advertises it
338
+ * in help, generated docs, and shell completions.
339
+ * - `false` — disables negation entirely; same as the default, but explicit.
340
+ * Neither the default `--no-*` nor any custom name is accepted.
341
+ *
342
+ * String values follow the same naming conventions as `cliName`
343
+ * (kebab-case is recommended). Only valid on boolean fields; setting
344
+ * `negation` on a non-boolean field is a type error and raises a
345
+ * runtime error during command parsing.
346
+ *
347
+ * @example
348
+ * ```ts
349
+ * // Custom negation name
350
+ * cache: arg(z.boolean().default(true), {
351
+ * description: "Enable caching",
352
+ * negation: "disable-cache",
353
+ * })
354
+ * // Accepts: --cache (true), --disable-cache (false)
355
+ * // No longer accepts: --no-cache
356
+ *
357
+ * // Enable default `--no-X` in parsing/help/docs/completion
358
+ * verbose: arg(z.boolean().default(false), {
359
+ * negation: true,
360
+ * })
361
+ * // Help shows `--verbose / --no-verbose`
362
+ *
363
+ * // Disable negation entirely
364
+ * dryRun: arg(z.boolean().default(false), {
365
+ * negation: false,
366
+ * })
367
+ * // Accepts: --dry-run (true)
368
+ * // No longer accepts: --no-dry-run
369
+ * ```
370
+ */
371
+ negation?: string | boolean;
372
+ /**
373
+ * Description shown for the negation option in help and generated docs.
374
+ * Only meaningful when `negation` is set to a custom name string or `true`.
375
+ * Disallowed when `negation` is `false`.
376
+ */
377
+ negationDescription?: string;
378
+ /**
379
+ * Side-effect callback executed after argument parsing and validation.
380
+ * Runs before the command lifecycle (setup/run/cleanup).
381
+ * Use Zod .transform() for value transformation instead.
382
+ *
383
+ * @example
384
+ * ```ts
385
+ * verbose: arg(z.boolean().default(false), {
386
+ * alias: "v",
387
+ * effect: (value) => {
388
+ * if (value) logger.setLevel("debug");
389
+ * },
390
+ * })
391
+ * ```
392
+ */
393
+ effect?: (value: TValue, context: EffectContext) => void | PromiseLike<void>;
263
394
  }
264
395
  /**
265
- * Example definition for a command
396
+ * Metadata for regular arguments (non-builtin aliases)
397
+ *
398
+ * `alias` accepts either a single string or an array of strings.
399
+ * Single-character entries become short options (e.g. `-v`); multi-character
400
+ * entries become additional long options (e.g. `--to-be` for `--tobe`).
266
401
  */
267
- interface Example {
268
- /** Command arguments to execute (e.g., "World" or "--loud Alice") */
269
- cmd: string;
270
- /** Description of the example */
271
- desc: string;
272
- /** Expected output (optional, for documentation) */
273
- output?: string;
402
+ interface RegularArgMeta<TValue = unknown> extends BaseArgMeta<TValue> {
403
+ /**
404
+ * Alias name(s) for this option.
405
+ * - 1-char string → short alias (`-v`)
406
+ * - >1-char string → long alias (`--long-name`)
407
+ * - array → multiple aliases of either kind
408
+ */
409
+ alias?: string | string[] | readonly string[];
410
+ /**
411
+ * Alias name(s) that are accepted by the parser but hidden from help,
412
+ * generated docs, and shell completion. Useful for legacy or deprecated
413
+ * names that should still work without being advertised.
414
+ */
415
+ hiddenAlias?: string | string[] | readonly string[];
274
416
  }
275
417
  /**
276
- * Logger interface for CLI output
277
- * Can be overridden by passing a custom logger to runMain or runCommand
418
+ * Metadata for overriding built-in aliases (-h, -H)
278
419
  */
279
- interface Logger {
280
- /** Log informational message to stdout */
281
- log(message: string): void;
282
- /** Log error message to stderr */
283
- error(message: string): void;
284
- /** Log warning message to stderr */
285
- warn?(message: string): void;
420
+ interface BuiltinOverrideArgMeta<TValue = unknown> extends BaseArgMeta<TValue> {
421
+ /** Built-in alias to override ('h' or 'H'), optionally combined with extra aliases */
422
+ alias: "h" | "H" | Array<"h" | "H" | string> | ReadonlyArray<"h" | "H" | string>;
423
+ /** Hidden aliases (accepted but not surfaced in help/docs/completion) */
424
+ hiddenAlias?: string | string[] | readonly string[];
425
+ /** Must be true to override built-in aliases */
426
+ overrideBuiltinAlias: true;
286
427
  }
287
428
  /**
288
- * Supported schema types for args: any Standard Schema (zod, valibot, ...)
289
- * whose output is an object. Adapter packages narrow this back to their
290
- * library's own schema type in their public exports (e.g. `@politty/zod`
291
- * exports `ArgsSchema = z.ZodType<Record<string, any>>`).
429
+ * Metadata options for argument definition
292
430
  */
293
- type ArgsSchema = SchemaLike<Record<string, any>>;
431
+ type ArgMeta<TValue = unknown> = RegularArgMeta<TValue> | BuiltinOverrideArgMeta<TValue>;
294
432
  /**
295
- * Context provided to setup function
433
+ * Register metadata for a schema
434
+ *
435
+ * @param schema - The schema to attach metadata to
436
+ * @param meta - Argument metadata
437
+ * @returns The same schema (for chaining)
438
+ *
439
+ * @example
440
+ * ```ts
441
+ * import { z } from "zod";
442
+ * import { arg, defineCommand } from "politty";
443
+ *
444
+ * const cmd = defineCommand({
445
+ * args: z.object({
446
+ * name: arg(z.string(), { description: "User name", positional: true }),
447
+ * verbose: arg(z.boolean().default(false), { alias: "v" }),
448
+ * }),
449
+ * run: (args) => {
450
+ * console.log(args.name, args.verbose);
451
+ * },
452
+ * });
453
+ * ```
296
454
  */
297
- interface SetupContext<TArgs = unknown> {
298
- /** Parsed and validated arguments */
299
- args: TArgs;
300
- }
301
455
  /**
302
- * Context provided to cleanup function
456
+ * Detect whether `A` contains a reserved alias ("h" or "H"), for either a
457
+ * plain string or a tuple/array of strings. Uses `[A] extends [never]` to
458
+ * prevent distribution returning `never` for missing fields.
303
459
  */
304
- interface CleanupContext<TArgs = unknown> {
305
- /** Parsed and validated arguments */
306
- args: TArgs;
307
- /** Error if command execution failed */
308
- error?: Error | undefined;
309
- }
460
+ type ContainsReservedAlias<A> = [A] extends [never] ? false : A extends "h" | "H" ? true : A extends readonly (infer E)[] ? [Extract<E, "h" | "H">] extends [never] ? false : true : false;
461
+ type ReservedAliasTypeError<M> = { [K in keyof M]: M[K]; } & {
462
+ __typeError: "Alias 'h' or 'H' requires overrideBuiltinAlias: true";
463
+ };
464
+ type NegationTypeError<M> = { [K in keyof M]: M[K]; } & {
465
+ __typeError: "negation/negationDescription can only be used on boolean fields";
466
+ };
467
+ type AliasFieldOf<M> = M extends {
468
+ alias: infer A;
469
+ } ? A : never;
470
+ type HiddenAliasFieldOf<M> = M extends {
471
+ hiddenAlias: infer H;
472
+ } ? H : never;
310
473
  /**
311
- * Context provided to global setup function (runMain/runCommand level)
474
+ * Check whether a Zod output type is a (possibly optional) boolean.
475
+ * Strips `undefined` to allow `z.boolean().optional()`. Requires both
476
+ * `boolean extends NonNullable<T>` (so `z.literal(true)` is rejected — the full
477
+ * `boolean` domain is needed) and `NonNullable<T> extends boolean` (so unions
478
+ * such as `z.union([z.boolean(), z.string()])` are rejected at the type level
479
+ * to match the runtime check).
312
480
  */
313
- interface GlobalSetupContext {}
481
+ type IsBooleanField<T> = boolean extends NonNullable<T> ? ([NonNullable<T>] extends [boolean] ? true : false) : false;
314
482
  /**
315
- * Context provided to global cleanup function (runMain/runCommand level)
483
+ * Detect whether `M` has `K` set to a non-undefined value.
484
+ *
485
+ * When `M` is inferred from a literal such as `{ negation: "off" }`,
486
+ * `M["negation"]` is `"off"` (without `undefined`), so this returns `true`.
487
+ * When `M` is the wider `ArgMeta` type, `M["negation"]` is
488
+ * `string | boolean | undefined`, so this returns `false` and avoids
489
+ * false-positive type errors on broadly-typed meta values.
316
490
  */
317
- interface GlobalCleanupContext {
318
- /** Error if command execution failed */
319
- error?: Error | undefined;
320
- }
491
+ type HasExplicit<M, K extends string> = K extends keyof M ? undefined extends M[K] ? false : true : false;
321
492
  /**
322
- * Base command interface (shared properties)
323
- * @template TArgsSchema - The args schema type (from the CLI's schema library)
324
- * @template TArgs - The inferred args type from the schema
493
+ * Reject `negation` / `negationDescription` on non-boolean fields.
494
+ * Uses {@link HasExplicit} so the error only fires when the user explicitly
495
+ * sets the field on a narrowly-inferred meta literal.
325
496
  */
326
- interface CommandBase<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown> {
327
- /** Command name (required) */
328
- name: string;
329
- /** Command description */
330
- description?: string | undefined;
331
- /** Alternative names for this command (used as subcommand aliases) */
332
- aliases?: string[] | undefined;
333
- /** Argument schema (preserves the original schema type) */
334
- args: TArgsSchema;
335
- /** Subcommands */
336
- subCommands?: SubCommandsRecord | undefined;
337
- /** Setup hook */
338
- setup?: ((context: SetupContext<TArgs>) => void | Promise<void>) | undefined;
339
- /** Cleanup hook */
340
- cleanup?: ((context: CleanupContext<TArgs>) => void | Promise<void>) | undefined;
341
- /** Additional notes */
342
- notes?: string | undefined;
343
- /** Example usages for this command */
344
- examples?: Example[] | undefined;
345
- /**
346
- * @internal
347
- * Hook invoked once at the top of `runMain`, before any parsing. Used
348
- * by `withCompletionCommand` to fire its detached background-refresh
349
- * spawn. Best-effort; never throws.
350
- */
351
- runMainHook?: ((argv: readonly string[]) => void) | undefined;
352
- }
497
+ type ValidateNegation<M, TValue> = HasExplicit<M, "negation"> extends true ? IsBooleanField<TValue> extends true ? M : NegationTypeError<M> : HasExplicit<M, "negationDescription"> extends true ? IsBooleanField<TValue> extends true ? M : NegationTypeError<M> : M;
353
498
  /**
354
- * A command with a run function
355
- * @template TArgsSchema - The args schema type (from the CLI's schema library)
356
- * @template TArgs - The inferred args type from the schema
357
- * @template TResult - The return type of the run function
499
+ * Type helper to validate ArgMeta.
500
+ * Forces a type error when a reserved alias ("h" / "H") is used without
501
+ * `overrideBuiltinAlias: true`, whether the alias is provided as a string
502
+ * or as part of an array, and whether it appears in `alias` or `hiddenAlias`.
503
+ * Also rejects `negation` / `negationDescription` on non-boolean fields.
358
504
  */
359
- interface RunnableCommand<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown, TResult = unknown> extends CommandBase<TArgsSchema, TArgs> {
360
- /** Main run function */
361
- run: (args: TArgs) => TResult;
362
- }
505
+ type ValidateArgMeta<M, TValue = unknown> = M extends {
506
+ overrideBuiltinAlias: true;
507
+ } ? ValidateNegation<M, TValue> : ContainsReservedAlias<AliasFieldOf<M>> extends true ? ReservedAliasTypeError<M> : ContainsReservedAlias<HiddenAliasFieldOf<M>> extends true ? ReservedAliasTypeError<M> : ValidateNegation<M, TValue>;
363
508
  /**
364
- * A command without a run function (e.g., subcommand-only parent)
365
- * @template TArgsSchema - The args schema type (from the CLI's schema library)
366
- * @template TArgs - The inferred args type from the schema
509
+ * The overloaded `arg()` signature, parameterized by the schema constraint.
510
+ * Core's `arg` accepts any Standard Schema; adapter packages re-pin the same
511
+ * runtime function to their library's schema type (e.g. `ArgFn<z.ZodType>`
512
+ * in `@politty/zod`) so a schema from the wrong library is rejected at the
513
+ * type level.
367
514
  */
368
- interface NonRunnableCommand<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown> extends CommandBase<TArgsSchema, TArgs> {
369
- /** No run function */
370
- run?: undefined;
515
+ interface ArgFn<TSchemaBase extends SchemaLike = SchemaLike> {
516
+ <T extends TSchemaBase>(schema: T): T;
517
+ <T extends TSchemaBase, M extends ArgMeta<InferSchemaOutput<T>>>(schema: T, meta: ValidateArgMeta<M, InferSchemaOutput<T>>): T;
371
518
  }
519
+ //#endregion
520
+ //#region ../core/src/adapter/field-meta.d.ts
372
521
  /**
373
- * A defined command (union of runnable and non-runnable)
522
+ * Resolved metadata for an argument field
374
523
  */
375
- type Command<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown, TResult = unknown> = RunnableCommand<TArgsSchema, TArgs, TResult> | NonRunnableCommand<TArgsSchema, TArgs>;
524
+ interface ResolvedFieldMeta {
525
+ /** Field name (camelCase, as defined in schema) */
526
+ name: string;
527
+ /** CLI option name (kebab-case, for command line usage) */
528
+ cliName: string;
529
+ /**
530
+ * Aliases for this option, normalized to an array.
531
+ * 1-char entries are short aliases (`-v`); multi-char entries are long
532
+ * aliases (`--to-be`).
533
+ */
534
+ alias?: string[] | undefined;
535
+ /**
536
+ * Aliases that are accepted at parse time but hidden from help,
537
+ * generated docs, and shell completion.
538
+ */
539
+ hiddenAlias?: string[] | undefined;
540
+ /** Argument description */
541
+ description?: string | undefined;
542
+ /** Whether this is a positional argument */
543
+ positional: boolean;
544
+ /** Placeholder for help display */
545
+ placeholder?: string | undefined;
546
+ /**
547
+ * Environment variable name(s) to read value from.
548
+ * If an array, earlier entries take priority.
549
+ */
550
+ env?: string | string[] | undefined;
551
+ /** Whether this argument is required */
552
+ required: boolean;
553
+ /** Default value if any */
554
+ defaultValue?: unknown;
555
+ /** Detected type from schema */
556
+ type: "string" | "number" | "boolean" | "array" | "unknown";
557
+ /**
558
+ * Original field schema, carried through opaquely for downstream
559
+ * consumers. Its concrete type belongs to the adapter's schema library
560
+ * (zod, valibot, or an internal descriptor); core never calls into it.
561
+ */
562
+ schema: unknown;
563
+ /** True if this overrides built-in aliases (-h, -H) */
564
+ overrideBuiltinAlias?: true;
565
+ /** Enum values if detected from schema (z.enum) */
566
+ enumValues?: string[] | undefined;
567
+ /** Completion metadata from arg() */
568
+ completion?: CompletionMeta | undefined;
569
+ /** Prompt metadata from arg() for interactive input */
570
+ prompt?: PromptMeta | undefined;
571
+ /**
572
+ * Negation configuration for this boolean field.
573
+ *
574
+ * - String (e.g. `"disable-cache"`): the default `--no-<cliName>` form is
575
+ * suppressed and only `--<negation>` (plus its camelCase variant) is
576
+ * accepted as the negation flag.
577
+ * - `true`: the default `--no-<cliName>` form is accepted **and** shown in
578
+ * help, generated docs, and shell completions.
579
+ * - `false`: neither the default `--no-<cliName>` nor any custom name is
580
+ * accepted; the field only responds to the positive flag.
581
+ * - `undefined`: no negation form is accepted or shown.
582
+ *
583
+ * Only applies to boolean fields; populated as `undefined` otherwise.
584
+ */
585
+ negation?: string | boolean | undefined;
586
+ /**
587
+ * Derived display name (no `--` prefix) for the negation flag in help,
588
+ * generated docs, and shell completions. `undefined` means the negation
589
+ * is hidden from those surfaces. Computed from `negation` + `cliName`.
590
+ */
591
+ negationDisplay?: string | undefined;
592
+ /** Description shown for the negation option in help/docs. */
593
+ negationDescription?: string | undefined;
594
+ /** Side-effect callback from arg() metadata */
595
+ effect?: ((value: unknown, context: EffectContext) => void | PromiseLike<void>) | undefined;
596
+ }
376
597
  /**
377
- * Type alias for any args type.
378
- * Note: `any` is required here due to TypeScript's function parameter contravariance.
379
- * Using `unknown` would make it impossible to assign concrete command types to AnyCommand.
380
- * @internal
598
+ * Extracted fields from a schema
381
599
  */
382
- type AnyArgs = any;
600
+ interface ExtractedFields {
601
+ /** All field definitions */
602
+ fields: ResolvedFieldMeta[];
603
+ /** Original schema for validation */
604
+ schema: ArgsSchema;
605
+ /** Schema type */
606
+ schemaType: "object" | "discriminatedUnion" | "union" | "xor" | "intersection";
607
+ /** Discriminator key (for discriminatedUnion) */
608
+ discriminator?: string;
609
+ /** Variants (for discriminatedUnion) */
610
+ variants?: Array<{
611
+ discriminatorValue: string;
612
+ fields: ResolvedFieldMeta[];
613
+ description?: string;
614
+ }>;
615
+ /** Options (for union) */
616
+ unionOptions?: ExtractedFields[];
617
+ /** Schema description */
618
+ description?: string;
619
+ /**
620
+ * Unknown keys handling mode
621
+ * - "strict": Unknown keys cause validation errors (z.strictObject or z.object().strict())
622
+ * - "strip": Unknown keys trigger warnings (default, z.object())
623
+ * - "passthrough": Unknown keys are silently ignored (z.looseObject or z.object().passthrough())
624
+ */
625
+ unknownKeysMode: UnknownKeysMode;
626
+ }
383
627
  /**
384
- * Type alias for any result type.
385
- * @internal
628
+ * Unknown keys handling mode for object schemas
629
+ * - "strict": Unknown keys cause validation errors
630
+ * - "strip": Unknown keys are silently ignored (default)
631
+ * - "passthrough": Unknown keys are passed through
386
632
  */
387
- type AnyResult = any;
633
+ type UnknownKeysMode = "strict" | "strip" | "passthrough";
388
634
  /**
389
- * Command type that accepts any args/result types
390
- * Used in internal functions that don't need specific type information
635
+ * Convert camelCase to kebab-case
636
+ * @example toKebabCase("dryRun") => "dry-run"
637
+ * @example toKebabCase("outputDir") => "output-dir"
638
+ * @example toKebabCase("XMLParser") => "xml-parser"
391
639
  */
392
- type AnyCommand = Command<ArgsSchema | undefined, AnyArgs, AnyResult>;
640
+ declare function toKebabCase(str: string): string;
393
641
  /**
394
- * Subcommand value type (either a command or a lazy-loaded command)
642
+ * Convert hyphen-separated sequences to camelCase.
643
+ *
644
+ * Replaces `-x` (hyphen followed by a lowercase letter) with the uppercase
645
+ * variant. Non-hyphenated input (e.g., already camelCase) is returned as-is.
646
+ *
647
+ * @param str - A string that may contain hyphens
648
+ * @example toCamelCase("dry-run") => "dryRun"
649
+ * @example toCamelCase("output-dir") => "outputDir"
650
+ * @example toCamelCase("dryRun") => "dryRun"
395
651
  */
396
- type SubCommandValue = AnyCommand | (() => Promise<AnyCommand>) | LazyCommand;
652
+ declare function toCamelCase(str: string): string;
653
+ //#endregion
654
+ //#region ../core/src/lazy.d.ts
397
655
  /**
398
- * Record of subcommands indexed by name
656
+ * A lazily-loaded command that carries synchronous metadata for
657
+ * static analysis (completion, help) while deferring full module
658
+ * loading to execution time.
399
659
  */
400
- type SubCommandsRecord = Record<string, SubCommandValue>;
660
+ interface LazyCommand<T extends AnyCommand = AnyCommand> {
661
+ readonly __politty_lazy__: true;
662
+ readonly meta: T;
663
+ readonly load: () => Promise<AnyCommand>;
664
+ }
401
665
  /**
402
- * Async callback to resolve missing argument values interactively.
403
- * Called after env fallback, before schema validation.
404
- * Provided by adapter subpath modules (e.g. `politty/prompt/clack`).
666
+ * Type guard: check if a value is a LazyCommand
405
667
  */
406
- type PromptResolver = (rawArgs: Record<string, unknown>, extracted: ExtractedFields) => Promise<Record<string, unknown>>;
668
+ declare function isLazyCommand(value: unknown): value is LazyCommand;
407
669
  /**
408
- * Options for runMain (CLI entry point)
670
+ * Create a lazily-loaded subcommand with synchronous metadata.
671
+ *
672
+ * The `meta` command provides names, descriptions, and args schema
673
+ * for static analysis (completion scripts, help text) without loading
674
+ * the full command module.
675
+ *
676
+ * The `load` function is called only at execution time.
677
+ *
678
+ * @example
679
+ * ```ts
680
+ * import { lazy, defineCommand } from "politty";
681
+ *
682
+ * const cli = defineCommand({
683
+ * name: "mycli",
684
+ * subCommands: {
685
+ * deploy: lazy(
686
+ * defineCommand({
687
+ * name: "deploy",
688
+ * description: "Deploy the application",
689
+ * args: z.object({ env: arg(z.string()) }),
690
+ * }),
691
+ * () => import("./deploy.js").then((m) => m.deployCommand),
692
+ * ),
693
+ * },
694
+ * });
695
+ * ```
409
696
  */
410
- interface MainOptions {
411
- /** Command version */
412
- version?: string;
413
- /** Enable debug mode (show stack traces on errors) */
414
- debug?: boolean;
415
- /** Capture console output during execution (default: false) */
416
- captureLogs?: boolean;
417
- /** Skip command definition validation (useful in production where tests already verified) */
418
- skipValidation?: boolean;
419
- /** Custom logger for output (default: console) */
420
- logger?: Logger;
421
- /** Global args schema (shared across all subcommands) */
422
- globalArgs?: ArgsSchema;
423
- /** Global setup hook (runs before command execution) */
424
- setup?: ((context: GlobalSetupContext) => void | Promise<void>) | undefined;
425
- /** Global cleanup hook (runs after command execution, always executes even on error) */
426
- cleanup?: ((context: GlobalCleanupContext) => void | Promise<void>) | undefined;
427
- /** Whether to display errors to stderr before process.exit (default: true) */
428
- displayErrors?: boolean;
429
- /** Prompt resolver for interactive missing-arg prompts (e.g. from `politty/prompt/clack`). */
430
- prompt?: PromptResolver | undefined;
431
- /**
432
- * Fallback hook for CLI plugin dispatch, invoked when a positional is not a
433
- * known subcommand at any level whose command exposes subcommands (e.g. exec
434
- * an external `<cli>-<path...>-<name>` binary).
435
- *
436
- * Return a number to treat it as handled and exit with that code; return
437
- * `undefined` (or omit) to fall back to the default unknown-subcommand/help
438
- * behavior. Not invoked for internal `__*` subcommands.
439
- */
440
- onUnknownSubcommand?: UnknownSubcommandHandler | undefined;
441
- /**
442
- * Node.js on-disk compile cache (V8 code cache) control. `runMain` enables
443
- * it before executing the command so dynamically imported modules (e.g.
444
- * `lazy()` subcommands) skip recompilation on warm starts (Node >= 22.8.0;
445
- * no-op otherwise).
446
- * - omitted / `true`: derive the directory from the command name
447
- * (`${XDG_CACHE_HOME:-$HOME/.cache}/<sanitized name>/node-compile-cache`,
448
- * shared with shell-completion workers; the name is reduced to a single
449
- * safe path segment, e.g. `@scope/cli` → `scope-cli`)
450
- * - `string`: use this cache directory
451
- * - `false`: do not enable
452
- *
453
- * The `NODE_COMPILE_CACHE` environment variable always takes precedence.
454
- * Note: the entry module's static import graph is compiled before `runMain`
455
- * runs and cannot be cached here — see the `compile-cache` subpath for the
456
- * bin-shim pattern that covers it.
457
- */
458
- compileCache?: boolean | string;
459
- }
697
+ declare function lazy<T extends AnyCommand>(meta: T, load: () => Promise<AnyCommand>): LazyCommand<T>;
698
+ //#endregion
699
+ //#region ../core/src/types.d.ts
460
700
  /**
461
- * Handler for an unrecognized subcommand. See {@link MainOptions.onUnknownSubcommand}.
701
+ * Global args interface for declaration merging (Pattern 3).
702
+ * Users can extend this interface to add global options to all commands:
703
+ *
704
+ * ```ts
705
+ * declare module "politty" {
706
+ * interface GlobalArgs { verbose: boolean; config?: string; }
707
+ * }
708
+ * ```
462
709
  */
463
- type UnknownSubcommandHandler = (context: {
464
- /**
465
- * Known subcommand names traversed before the unknown name (excludes the
466
- * root command name). Empty at the root level.
467
- */
468
- commandPath: readonly string[];
469
- /** The unrecognized subcommand name (first unmatched positional). */
470
- name: string;
471
- /** Args following the name, forwarded verbatim to the plugin. */
472
- args: readonly string[];
473
- /**
474
- * Option tokens the host consumed before the unknown name across every
475
- * traversed level (e.g. global flags typed before the plugin command),
476
- * excluding the traversed subcommand names themselves. Concatenate with
477
- * `args` to reconstruct the user's full flag set when forwarding to a
478
- * plugin: `[...precedingArgs, ...args]`.
479
- */
480
- precedingArgs: readonly string[];
481
- }) => number | undefined | Promise<number | undefined>;
710
+ interface GlobalArgs {}
482
711
  /**
483
- * Options for runCommand (programmatic/test usage)
712
+ * Detect empty interface (used for GlobalArgs declaration merging)
484
713
  */
485
- interface RunCommandOptions {
486
- /** Enable debug mode (show stack traces on errors) */
487
- debug?: boolean;
488
- /** Capture console output during execution (default: false) */
489
- captureLogs?: boolean;
490
- /** Skip command definition validation (useful in production where tests already verified) */
491
- skipValidation?: boolean;
492
- /** Custom logger for output (default: console) */
493
- logger?: Logger;
494
- /** Global args schema (shared across all subcommands) */
495
- globalArgs?: ArgsSchema;
496
- /** Global setup hook (runs before command execution) */
497
- setup?: ((context: GlobalSetupContext) => void | Promise<void>) | undefined;
498
- /** Global cleanup hook (runs after command execution, always executes even on error) */
499
- cleanup?: ((context: GlobalCleanupContext) => void | Promise<void>) | undefined;
500
- /** Prompt resolver for interactive missing-arg prompts (e.g. from `politty/prompt/clack`). */
501
- prompt?: PromptResolver | undefined;
502
- }
714
+ type IsEmpty<T> = keyof T extends never ? true : false;
503
715
  /**
504
- * Log level type
716
+ * Where a resolved arg value came from:
717
+ * - `"cli"`: an explicit CLI token (flag or positional)
718
+ * - `"env"`: `field.env` fallback (no CLI token was provided)
719
+ * - `"default"`: neither of the above (e.g. a schema default, or a value
720
+ * resolved by a `prompt` handler)
505
721
  */
506
- type LogLevel = "log" | "info" | "debug" | "warn" | "error";
722
+ type ArgSource = "cli" | "env" | "default";
507
723
  /**
508
- * Output stream type
724
+ * Identifies the CLI name a command was invoked with in the current run.
725
+ * - `name`: the literal token typed on the CLI to reach this command
726
+ * (a canonical subcommand name or one of its `aliases`).
727
+ * - `aliasFor`: set only when `name` is an alias, to the canonical
728
+ * subcommand name it resolves to; `undefined` when invoked by its
729
+ * canonical name (or run directly, with no subcommand routing involved).
509
730
  */
510
- type LogStream = "stdout" | "stderr";
731
+ interface RunInvocation {
732
+ /** The name or alias actually typed on the CLI to reach this command */
733
+ name: string;
734
+ /** Canonical name `name` is an alias for; undefined when not an alias */
735
+ aliasFor?: string | undefined;
736
+ }
511
737
  /**
512
- * A single log entry collected during command execution
738
+ * Example definition for a command
513
739
  */
514
- interface LogEntry {
515
- /** Log message */
516
- message: string;
517
- /** Timestamp when the log was recorded */
518
- timestamp: Date;
519
- /** Log level */
520
- level: LogLevel;
521
- /** Output stream (stdout or stderr) */
522
- stream: LogStream;
740
+ interface Example {
741
+ /** Command arguments to execute (e.g., "World" or "--loud Alice") */
742
+ cmd: string;
743
+ /** Description of the example */
744
+ desc: string;
745
+ /** Expected output (optional, for documentation) */
746
+ output?: string;
523
747
  }
524
748
  /**
525
- * Collected logs during command execution
749
+ * Logger interface for CLI output
750
+ * Can be overridden by passing a custom logger to runMain or runCommand
526
751
  */
527
- interface CollectedLogs {
528
- /** All log entries in order */
529
- entries: LogEntry[];
752
+ interface Logger {
753
+ /** Log informational message to stdout */
754
+ log(message: string): void;
755
+ /** Log error message to stderr */
756
+ error(message: string): void;
757
+ /** Log warning message to stderr */
758
+ warn?(message: string): void;
530
759
  }
531
760
  /**
532
- * Successful command execution result
761
+ * Supported schema types for args: any Standard Schema (zod, valibot, ...)
762
+ * whose output is an object. Adapter packages narrow this back to their
763
+ * library's own schema type in their public exports (e.g. `@politty/zod`
764
+ * exports `ArgsSchema = z.ZodType<Record<string, any>>`).
533
765
  */
534
- interface RunResultSuccess<T = unknown> {
535
- /** Indicates successful execution */
536
- success: true;
537
- /** Command return value */
538
- result: T | undefined;
539
- /** Error that occurred during execution */
540
- error?: never;
541
- /** Exit code (always 0 for success) */
542
- exitCode: 0;
543
- /** Collected logs during execution */
544
- logs: CollectedLogs;
766
+ type ArgsSchema = SchemaLike<Record<string, any>>;
767
+ /**
768
+ * Context provided to setup function
769
+ */
770
+ interface SetupContext<TArgs = unknown> {
771
+ /** Parsed and validated arguments */
772
+ args: TArgs;
545
773
  }
546
774
  /**
547
- * Failed command execution result
775
+ * Context provided to cleanup function
548
776
  */
549
- interface RunResultFailure {
550
- /** Indicates failed execution */
551
- success: false;
552
- /** Command return value */
553
- result?: never;
554
- /** Error that occurred during execution */
555
- error: Error;
556
- /** Exit code (non-zero for failure) */
557
- exitCode: number;
558
- /** Collected logs during execution */
559
- logs: CollectedLogs;
777
+ interface CleanupContext<TArgs = unknown> {
778
+ /** Parsed and validated arguments */
779
+ args: TArgs;
780
+ /** Error if command execution failed */
781
+ error?: Error | undefined;
560
782
  }
561
783
  /**
562
- * Result of command execution (discriminated union)
784
+ * Context provided to global setup function (runMain/runCommand level)
563
785
  */
564
- type RunResult<T = unknown> = RunResultSuccess<T> | RunResultFailure;
565
- //#endregion
566
- //#region ../core/src/core/dynamic-completion-types.d.ts
786
+ interface GlobalSetupContext {}
567
787
  /**
568
- * Types for in-process dynamic value completion.
569
- *
570
- * A `resolve` callback registered on `arg(...)` receives parsed context
571
- * (other arg values typed so far, previous values supplied to the same
572
- * option, the current word being completed, target shell) and returns
573
- * candidates. The callback runs inside the `__complete` command. Dispatcher
574
- * shell scripts call `__complete` for every completion request; static shell
575
- * scripts delegate to it for any spec that uses `resolve`.
576
- *
577
- * Defined under `core/` (not `completion/`) so `arg-registry.ts` can
578
- * reference the resolver type without crossing the lint-enforced
579
- * `completion → core` boundary.
788
+ * Context provided to global cleanup function (runMain/runCommand level)
580
789
  */
581
- /** Bitmask combining `CompletionDirective` values. */
582
- type CompletionDirectiveMask = number;
583
- interface DynamicCompletionContext {
584
- /** Word being completed. `--field=` inline prefix is stripped before this is set. */
585
- currentWord: string;
586
- /** Target shell formatting requested by the caller. */
587
- shell: "bash" | "zsh" | "fish";
588
- /**
589
- * Best-effort parsed values of OTHER args on the same command, keyed by
590
- * camelCase name. Includes positionals and other options. Zod validation
591
- * is NOT applied; values are raw strings (or arrays of raw strings for
592
- * array-typed options/variadic positionals).
593
- */
594
- parsedArgs: Readonly<Record<string, unknown>>;
595
- /**
596
- * Values already supplied for the SAME option/positional being completed.
597
- * Useful for de-duplicating repeated array options.
598
- */
599
- previousValues: readonly string[];
600
- /**
601
- * Subcommand path from root (e.g. ["api"]). Reflects what the user
602
- * actually typed — aliases are NOT resolved to their canonical names, so
603
- * resolvers that branch on the path should accept every alias they care
604
- * about.
605
- */
606
- subcommandPath: readonly string[];
607
- }
608
- interface DynamicCompletionCandidate {
609
- value: string;
610
- description?: string;
611
- }
612
- interface DynamicCompletionResult {
613
- /** Candidates to surface. Strings or `{value, description}` objects. */
614
- candidates: Array<string | DynamicCompletionCandidate>;
615
- /**
616
- * Optional directive override. When omitted, defaults to
617
- * `FilterPrefix | NoFileCompletion` (matches `choices` behaviour).
618
- */
619
- directive?: CompletionDirectiveMask;
790
+ interface GlobalCleanupContext {
791
+ /** Error if command execution failed */
792
+ error?: Error | undefined;
620
793
  }
621
- type DynamicCompletionResolver = (ctx: DynamicCompletionContext) => DynamicCompletionResult | Promise<DynamicCompletionResult>;
622
- //#endregion
623
- //#region ../core/src/core/expand-completion-types.d.ts
624
794
  /**
625
- * Types for "expand" completion — candidates that depend on sibling arg
626
- * values.
627
- *
628
- * The user provides `dependsOn` (sibling arg names that must have static
629
- * `choices` or an enum schema) and `enumerate(deps)`. Dispatcher scripts call
630
- * `enumerate` inside `__complete` for the dependency values already typed on
631
- * the command line. Static scripts walk the cartesian product of the
632
- * dependsOn values, call `enumerate` for each combination, and emit a shell
633
- * lookup table.
634
- *
635
- * Defined under `core/` (not `completion/`) so `arg-registry.ts` can
636
- * reference these types without crossing the lint-enforced
637
- * `completion → core` boundary.
795
+ * Base command interface (shared properties)
796
+ * @template TArgsSchema - The args schema type (from the CLI's schema library)
797
+ * @template TArgs - The inferred args type from the schema
638
798
  */
639
- /** Candidate returned by an `enumerate` callback. */
640
- interface ExpandCandidate {
641
- value: string;
642
- description?: string;
643
- }
644
- /** Resolved candidate stored on a {@link ValueCompletion} after enumeration. */
645
- interface ResolvedExpandCandidate {
646
- value: string;
647
- description?: string;
799
+ interface CommandBase<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown> {
800
+ /** Command name (required) */
801
+ name: string;
802
+ /** Command description */
803
+ description?: string | undefined;
804
+ /** Alternative names for this command (used as subcommand aliases) */
805
+ aliases?: string[] | undefined;
806
+ /** Argument schema (preserves the original schema type) */
807
+ args: TArgsSchema;
808
+ /** Subcommands */
809
+ subCommands?: SubCommandsRecord | undefined;
810
+ /** Setup hook */
811
+ setup?: ((context: SetupContext<TArgs>) => void | Promise<void>) | undefined;
812
+ /** Cleanup hook */
813
+ cleanup?: ((context: CleanupContext<TArgs>) => void | Promise<void>) | undefined;
814
+ /** Additional notes */
815
+ notes?: string | undefined;
816
+ /** Example usages for this command */
817
+ examples?: Example[] | undefined;
818
+ /**
819
+ * @internal
820
+ * Hook invoked once at the top of `runMain`, before any parsing. Used
821
+ * by `withCompletionCommand` to fire its detached background-refresh
822
+ * spawn. Best-effort; never throws.
823
+ */
824
+ runMainHook?: ((argv: readonly string[]) => void) | undefined;
648
825
  }
649
826
  /**
650
- * User-facing spec attached to `completion.custom.expand`.
651
- *
652
- * `dependsOn` lists sibling args (camelCase names) whose values determine
653
- * which candidates apply. Each named arg must have a static set of values —
654
- * either an explicit `completion.custom.choices` or an enum schema. The
655
- * order of `dependsOn` is the order in which `deps` keys are exposed to
656
- * `enumerate`.
657
- *
658
- * In dispatcher mode, `enumerate` runs during `__complete` for the dependency
659
- * values already typed by the user. In static mode, it runs once per
660
- * cartesian-product combination at script-generation time (e.g. when the user
661
- * runs `<program> completion zsh --static`). It must be a pure function of
662
- * `deps`.
827
+ * A command with a run function
828
+ * @template TArgsSchema - The args schema type (from the CLI's schema library)
829
+ * @template TArgs - The inferred args type from the schema
830
+ * @template TResult - The return type of the run function
663
831
  */
664
- interface ExpandCompletion {
665
- dependsOn: readonly string[];
666
- enumerate: (deps: Readonly<Record<string, string>>) => ReadonlyArray<string | ExpandCandidate>;
832
+ interface RunnableCommand<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown, TResult = unknown> extends CommandBase<TArgsSchema, TArgs> {
833
+ /** Main run function */
834
+ run: (args: TArgs) => TResult;
667
835
  }
668
- //#endregion
669
- //#region ../core/src/core/arg-registry.d.ts
670
- /**
671
- * Built-in completion types
672
- */
673
- type CompletionType = "file" | "directory" | "none";
674
836
  /**
675
- * Custom completion specification.
676
- *
677
- * `choices`, `shellCommand`, `resolve`, and `expand` are mutually exclusive —
678
- * specifying more than one throws when the field metadata is resolved.
837
+ * A command without a run function (e.g., subcommand-only parent)
838
+ * @template TArgsSchema - The args schema type (from the CLI's schema library)
839
+ * @template TArgs - The inferred args type from the schema
679
840
  */
680
- interface CustomCompletion {
681
- /** Static list of choices for completion */
682
- choices?: string[];
683
- /** Shell command to execute for dynamic completion */
684
- shellCommand?: string;
685
- /**
686
- * In-process JS callback for dynamic completion. Receives parsed context
687
- * (other arg values typed so far, previously supplied values for this same
688
- * option) and returns candidates. Dispatcher scripts call
689
- * `<program> __complete` for every completion request; static scripts
690
- * delegate to it whenever this is set.
691
- */
692
- resolve?: DynamicCompletionResolver;
693
- /**
694
- * Completion whose candidates depend on sibling arg values. Dispatcher
695
- * scripts call `enumerate` inside `__complete` for the dependency values
696
- * already typed on the command line. Static scripts pre-enumerate every
697
- * combination of `dependsOn` values at script-generation time and dispatch
698
- * via a shell lookup table.
699
- */
700
- expand?: ExpandCompletion;
841
+ interface NonRunnableCommand<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown> extends CommandBase<TArgsSchema, TArgs> {
842
+ /** No run function */
843
+ run?: undefined;
701
844
  }
702
845
  /**
703
- * Completion metadata for an argument
704
- *
705
- * @example
706
- * ```ts
707
- * // File completion with extension filter
708
- * input: arg(z.string(), {
709
- * completion: { type: "file", extensions: ["json", "yaml"] }
710
- * })
711
- *
712
- * // Directory completion
713
- * outputDir: arg(z.string(), {
714
- * completion: { type: "directory" }
715
- * })
716
- *
717
- * // Custom static choices
718
- * logLevel: arg(z.string(), {
719
- * completion: { custom: { choices: ["debug", "info", "warn", "error"] } }
720
- * })
721
- *
722
- * // Dynamic completion from shell command
723
- * branch: arg(z.string(), {
724
- * completion: { custom: { shellCommand: "git branch --format='%(refname:short)'" } }
725
- * })
726
- *
727
- * // File completion with glob pattern matcher
728
- * envFile: arg(z.string(), {
729
- * completion: { type: "file", matcher: [".env.*"] }
730
- * })
731
- * ```
846
+ * A defined command (union of runnable and non-runnable)
732
847
  */
733
- type CompletionMeta = {
734
- /** Built-in completion type */
735
- type?: CompletionType;
736
- /** Custom completion (takes precedence over type if both specified) */
737
- custom?: CustomCompletion;
738
- } & ({
739
- /** File extension filter (only applies when type is "file") */ extensions?: string[];
740
- matcher?: never;
741
- } | {
742
- /** Glob patterns for file matching (only applies when type is "file") */ matcher?: string[];
743
- extensions?: never;
744
- });
848
+ type Command<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown, TResult = unknown> = RunnableCommand<TArgsSchema, TArgs, TResult> | NonRunnableCommand<TArgsSchema, TArgs>;
745
849
  /**
746
- * Prompt input type for interactive prompts
747
- *
748
- * - "text": free-form text input (default for string schemas)
749
- * - "password": masked text input
750
- * - "confirm": yes/no prompt (default for boolean schemas)
751
- * - "select": single selection from choices (default for enum schemas)
752
- * - "file": file path input (inherited from completion type)
753
- * - "directory": directory path input (inherited from completion type)
850
+ * Type alias for any args type.
851
+ * Note: `any` is required here due to TypeScript's function parameter contravariance.
852
+ * Using `unknown` would make it impossible to assign concrete command types to AnyCommand.
853
+ * @internal
754
854
  */
755
- type PromptType = "text" | "password" | "confirm" | "select" | "file" | "directory";
855
+ type AnyArgs = any;
756
856
  /**
757
- * Prompt metadata for interactive input when a value is missing.
758
- * Used by the `politty/prompt` module to request user input for unresolved arguments.
759
- *
760
- * @example
761
- * ```ts
762
- * // Custom prompt message
763
- * name: arg(z.string(), {
764
- * prompt: { message: "What is your name?" }
765
- * })
766
- *
767
- * // Password input (masked)
768
- * token: arg(z.string(), {
769
- * prompt: { type: "password", message: "Enter API token" }
770
- * })
771
- *
772
- * // Select with custom choices
773
- * region: arg(z.string(), {
774
- * prompt: { choices: ["us-east-1", "eu-west-1", "ap-northeast-1"] }
775
- * })
776
- * ```
857
+ * Type alias for any result type.
858
+ * @internal
777
859
  */
778
- interface PromptMeta {
779
- /** Prompt message shown to the user. Defaults to the field's description or name. */
780
- message?: string;
781
- /** Explicit prompt type. Overrides auto-detection from schema/completion. */
782
- type?: PromptType;
783
- /** Choices for select prompt. Overrides enum values from schema. */
784
- choices?: Array<string | {
785
- label: string;
786
- value: string;
787
- }>;
788
- /** Whether to enable prompting for this field (default: true when prompt is set) */
789
- enabled?: boolean;
790
- }
860
+ type AnyResult = any;
791
861
  /**
792
- * Context provided to effect callbacks.
793
- * When GlobalArgs is extended via declaration merging, `globalArgs` is typed accordingly.
862
+ * Command type that accepts any args/result types
863
+ * Used in internal functions that don't need specific type information
794
864
  */
795
- type EffectContext = {
796
- /** Field name (camelCase) */
797
- name: string;
798
- /** Validated args for this schema (global args for global effects, command args for command effects) */
799
- args: Readonly<Record<string, unknown>>;
800
- } & (IsEmpty<GlobalArgs> extends true ? {
801
- globalArgs?: Readonly<Record<string, unknown>>;
802
- } : {
803
- globalArgs?: Readonly<GlobalArgs>;
804
- });
865
+ type AnyCommand = Command<ArgsSchema | undefined, AnyArgs, AnyResult>;
805
866
  /**
806
- * Base metadata shared by all argument types
867
+ * Subcommand value type (either a command or a lazy-loaded command)
807
868
  */
808
- interface BaseArgMeta<TValue = unknown> {
809
- /** Argument description */
810
- description?: string;
811
- /** Treat as positional argument */
812
- positional?: boolean;
813
- /** Placeholder for help display */
814
- placeholder?: string;
815
- /**
816
- * Environment variable name(s) to read value from.
817
- * If an array is provided, earlier entries take priority.
818
- * CLI arguments always take precedence over environment variables.
819
- *
820
- * @example
821
- * ```ts
822
- * // Single env var
823
- * port: arg(z.coerce.number(), { env: "PORT" })
824
- *
825
- * // Multiple env vars (PORT takes priority over SERVER_PORT)
826
- * port: arg(z.coerce.number(), { env: ["PORT", "SERVER_PORT"] })
827
- * ```
828
- */
829
- env?: string | string[];
830
- /** Completion configuration for shell tab-completion */
831
- completion?: CompletionMeta;
832
- /**
833
- * Interactive prompt configuration for missing values.
834
- * When set, the `politty/prompt` module will prompt the user interactively
835
- * if this argument is not provided via CLI args or environment variables.
836
- *
837
- * @example
838
- * ```ts
839
- * name: arg(z.string(), {
840
- * description: "User name",
841
- * prompt: { message: "What is your name?" },
842
- * })
843
- * ```
844
- */
845
- prompt?: PromptMeta;
846
- /**
847
- * Control the boolean negation option.
848
- *
849
- * Boolean fields accept `--no-<cliName>` (and the camelCase `--no<Name>`
850
- * form) to set the value to `false` only when `negation: true` is set.
851
- * By default no negation form is accepted. This option lets you customize
852
- * or expose that behavior:
853
- *
854
- * - `string` — replaces the auto-generated `--no-*` form with a custom
855
- * name. The default `--no-*` is no longer recognized.
856
- * - `true` — enables the default `--no-<cliName>` form and advertises it
857
- * in help, generated docs, and shell completions.
858
- * - `false` — disables negation entirely; same as the default, but explicit.
859
- * Neither the default `--no-*` nor any custom name is accepted.
860
- *
861
- * String values follow the same naming conventions as `cliName`
862
- * (kebab-case is recommended). Only valid on boolean fields; setting
863
- * `negation` on a non-boolean field is a type error and raises a
864
- * runtime error during command parsing.
865
- *
866
- * @example
867
- * ```ts
868
- * // Custom negation name
869
- * cache: arg(z.boolean().default(true), {
870
- * description: "Enable caching",
871
- * negation: "disable-cache",
872
- * })
873
- * // Accepts: --cache (true), --disable-cache (false)
874
- * // No longer accepts: --no-cache
875
- *
876
- * // Enable default `--no-X` in parsing/help/docs/completion
877
- * verbose: arg(z.boolean().default(false), {
878
- * negation: true,
879
- * })
880
- * // Help shows `--verbose / --no-verbose`
881
- *
882
- * // Disable negation entirely
883
- * dryRun: arg(z.boolean().default(false), {
884
- * negation: false,
885
- * })
886
- * // Accepts: --dry-run (true)
887
- * // No longer accepts: --no-dry-run
888
- * ```
889
- */
890
- negation?: string | boolean;
869
+ type SubCommandValue = AnyCommand | (() => Promise<AnyCommand>) | LazyCommand;
870
+ /**
871
+ * Record of subcommands indexed by name
872
+ */
873
+ type SubCommandsRecord = Record<string, SubCommandValue>;
874
+ /**
875
+ * Async callback to resolve missing argument values interactively.
876
+ * Called after env fallback, before schema validation.
877
+ * Provided by adapter subpath modules (e.g. `politty/prompt/clack`).
878
+ */
879
+ type PromptResolver = (rawArgs: Record<string, unknown>, extracted: ExtractedFields) => Promise<Record<string, unknown>>;
880
+ /**
881
+ * Options for runMain (CLI entry point)
882
+ */
883
+ interface MainOptions {
884
+ /** Command version */
885
+ version?: string;
886
+ /** Enable debug mode (show stack traces on errors) */
887
+ debug?: boolean;
888
+ /** Capture console and process.stdout/stderr output during execution (default: false) */
889
+ captureLogs?: boolean;
890
+ /** Skip command definition validation (useful in production where tests already verified) */
891
+ skipValidation?: boolean;
892
+ /** Custom logger for output (default: console) */
893
+ logger?: Logger;
894
+ /** Global args schema (shared across all subcommands) */
895
+ globalArgs?: ArgsSchema;
896
+ /** Global setup hook (runs before command execution) */
897
+ setup?: ((context: GlobalSetupContext) => void | Promise<void>) | undefined;
898
+ /** Global cleanup hook (runs after command execution, always executes even on error) */
899
+ cleanup?: ((context: GlobalCleanupContext) => void | Promise<void>) | undefined;
900
+ /** Whether to display errors to stderr before process.exit (default: true) */
901
+ displayErrors?: boolean;
902
+ /** Prompt resolver for interactive missing-arg prompts (e.g. from `politty/prompt/clack`). */
903
+ prompt?: PromptResolver | undefined;
891
904
  /**
892
- * Description shown for the negation option in help and generated docs.
893
- * Only meaningful when `negation` is set to a custom name string or `true`.
894
- * Disallowed when `negation` is `false`.
905
+ * Fallback hook for CLI plugin dispatch, invoked when a positional is not a
906
+ * known subcommand at any level whose command exposes subcommands (e.g. exec
907
+ * an external `<cli>-<path...>-<name>` binary).
908
+ *
909
+ * Return a number to treat it as handled and exit with that code; return
910
+ * `undefined` (or omit) to fall back to the default unknown-subcommand/help
911
+ * behavior. Not invoked for internal `__*` subcommands.
895
912
  */
896
- negationDescription?: string;
913
+ onUnknownSubcommand?: UnknownSubcommandHandler | undefined;
897
914
  /**
898
- * Side-effect callback executed after argument parsing and validation.
899
- * Runs before the command lifecycle (setup/run/cleanup).
900
- * Use Zod .transform() for value transformation instead.
915
+ * Node.js on-disk compile cache (V8 code cache) control. `runMain` enables
916
+ * it before executing the command so dynamically imported modules (e.g.
917
+ * `lazy()` subcommands) skip recompilation on warm starts (Node >= 22.8.0;
918
+ * no-op otherwise).
919
+ * - omitted / `true`: derive the directory from the command name
920
+ * (`${XDG_CACHE_HOME:-$HOME/.cache}/<sanitized name>/node-compile-cache`,
921
+ * shared with shell-completion workers; the name is reduced to a single
922
+ * safe path segment, e.g. `@scope/cli` → `scope-cli`)
923
+ * - `string`: use this cache directory
924
+ * - `false`: do not enable
901
925
  *
902
- * @example
903
- * ```ts
904
- * verbose: arg(z.boolean().default(false), {
905
- * alias: "v",
906
- * effect: (value) => {
907
- * if (value) logger.setLevel("debug");
908
- * },
909
- * })
910
- * ```
926
+ * The `NODE_COMPILE_CACHE` environment variable always takes precedence.
927
+ * Note: the entry module's static import graph is compiled before `runMain`
928
+ * runs and cannot be cached here — see the `compile-cache` subpath for the
929
+ * bin-shim pattern that covers it.
911
930
  */
912
- effect?: (value: TValue, context: EffectContext) => void | PromiseLike<void>;
931
+ compileCache?: boolean | string;
913
932
  }
914
933
  /**
915
- * Metadata for regular arguments (non-builtin aliases)
916
- *
917
- * `alias` accepts either a single string or an array of strings.
918
- * Single-character entries become short options (e.g. `-v`); multi-character
919
- * entries become additional long options (e.g. `--to-be` for `--tobe`).
934
+ * Handler for an unrecognized subcommand. See {@link MainOptions.onUnknownSubcommand}.
920
935
  */
921
- interface RegularArgMeta<TValue = unknown> extends BaseArgMeta<TValue> {
936
+ type UnknownSubcommandHandler = (context: {
922
937
  /**
923
- * Alias name(s) for this option.
924
- * - 1-char string → short alias (`-v`)
925
- * - >1-char string → long alias (`--long-name`)
926
- * - array → multiple aliases of either kind
938
+ * Known subcommand names traversed before the unknown name (excludes the
939
+ * root command name). Empty at the root level.
927
940
  */
928
- alias?: string | string[] | readonly string[];
941
+ commandPath: readonly string[];
942
+ /** The unrecognized subcommand name (first unmatched positional). */
943
+ name: string;
944
+ /** Args following the name, forwarded verbatim to the plugin. */
945
+ args: readonly string[];
929
946
  /**
930
- * Alias name(s) that are accepted by the parser but hidden from help,
931
- * generated docs, and shell completion. Useful for legacy or deprecated
932
- * names that should still work without being advertised.
947
+ * Option tokens the host consumed before the unknown name across every
948
+ * traversed level (e.g. global flags typed before the plugin command),
949
+ * excluding the traversed subcommand names themselves. Concatenate with
950
+ * `args` to reconstruct the user's full flag set when forwarding to a
951
+ * plugin: `[...precedingArgs, ...args]`.
933
952
  */
934
- hiddenAlias?: string | string[] | readonly string[];
935
- }
953
+ precedingArgs: readonly string[];
954
+ }) => number | undefined | Promise<number | undefined>;
936
955
  /**
937
- * Metadata for overriding built-in aliases (-h, -H)
956
+ * Options for runCommand (programmatic/test usage)
938
957
  */
939
- interface BuiltinOverrideArgMeta<TValue = unknown> extends BaseArgMeta<TValue> {
940
- /** Built-in alias to override ('h' or 'H'), optionally combined with extra aliases */
941
- alias: "h" | "H" | Array<"h" | "H" | string> | ReadonlyArray<"h" | "H" | string>;
942
- /** Hidden aliases (accepted but not surfaced in help/docs/completion) */
943
- hiddenAlias?: string | string[] | readonly string[];
944
- /** Must be true to override built-in aliases */
945
- overrideBuiltinAlias: true;
958
+ interface RunCommandOptions {
959
+ /** Enable debug mode (show stack traces on errors) */
960
+ debug?: boolean;
961
+ /** Capture console and process.stdout/stderr output during execution (default: false) */
962
+ captureLogs?: boolean;
963
+ /** Skip command definition validation (useful in production where tests already verified) */
964
+ skipValidation?: boolean;
965
+ /** Custom logger for output (default: console) */
966
+ logger?: Logger;
967
+ /** Global args schema (shared across all subcommands) */
968
+ globalArgs?: ArgsSchema;
969
+ /** Global setup hook (runs before command execution) */
970
+ setup?: ((context: GlobalSetupContext) => void | Promise<void>) | undefined;
971
+ /** Global cleanup hook (runs after command execution, always executes even on error) */
972
+ cleanup?: ((context: GlobalCleanupContext) => void | Promise<void>) | undefined;
973
+ /** Prompt resolver for interactive missing-arg prompts (e.g. from `politty/prompt/clack`). */
974
+ prompt?: PromptResolver | undefined;
946
975
  }
947
976
  /**
948
- * Metadata options for argument definition
949
- */
950
- type ArgMeta<TValue = unknown> = RegularArgMeta<TValue> | BuiltinOverrideArgMeta<TValue>;
951
- /**
952
- * Register metadata for a schema
953
- *
954
- * @param schema - The schema to attach metadata to
955
- * @param meta - Argument metadata
956
- * @returns The same schema (for chaining)
957
- *
958
- * @example
959
- * ```ts
960
- * import { z } from "zod";
961
- * import { arg, defineCommand } from "politty";
962
- *
963
- * const cmd = defineCommand({
964
- * args: z.object({
965
- * name: arg(z.string(), { description: "User name", positional: true }),
966
- * verbose: arg(z.boolean().default(false), { alias: "v" }),
967
- * }),
968
- * run: (args) => {
969
- * console.log(args.name, args.verbose);
970
- * },
971
- * });
972
- * ```
977
+ * Log level type
973
978
  */
979
+ type LogLevel = "log" | "info" | "debug" | "warn" | "error";
974
980
  /**
975
- * Detect whether `A` contains a reserved alias ("h" or "H"), for either a
976
- * plain string or a tuple/array of strings. Uses `[A] extends [never]` to
977
- * prevent distribution returning `never` for missing fields.
981
+ * Output stream type
978
982
  */
979
- type ContainsReservedAlias<A> = [A] extends [never] ? false : A extends "h" | "H" ? true : A extends readonly (infer E)[] ? [Extract<E, "h" | "H">] extends [never] ? false : true : false;
980
- type ReservedAliasTypeError<M> = { [K in keyof M]: M[K]; } & {
981
- __typeError: "Alias 'h' or 'H' requires overrideBuiltinAlias: true";
982
- };
983
- type NegationTypeError<M> = { [K in keyof M]: M[K]; } & {
984
- __typeError: "negation/negationDescription can only be used on boolean fields";
985
- };
986
- type AliasFieldOf<M> = M extends {
987
- alias: infer A;
988
- } ? A : never;
989
- type HiddenAliasFieldOf<M> = M extends {
990
- hiddenAlias: infer H;
991
- } ? H : never;
983
+ type LogStream = "stdout" | "stderr";
992
984
  /**
993
- * Check whether a Zod output type is a (possibly optional) boolean.
994
- * Strips `undefined` to allow `z.boolean().optional()`. Requires both
995
- * `boolean extends NonNullable<T>` (so `z.literal(true)` is rejected — the full
996
- * `boolean` domain is needed) and `NonNullable<T> extends boolean` (so unions
997
- * such as `z.union([z.boolean(), z.string()])` are rejected at the type level
998
- * to match the runtime check).
985
+ * A single log entry collected during command execution
999
986
  */
1000
- type IsBooleanField<T> = boolean extends NonNullable<T> ? ([NonNullable<T>] extends [boolean] ? true : false) : false;
987
+ interface LogEntry {
988
+ /** Log message */
989
+ message: string;
990
+ /** Timestamp when the log was recorded */
991
+ timestamp: Date;
992
+ /** Log level */
993
+ level: LogLevel;
994
+ /** Output stream (stdout or stderr) */
995
+ stream: LogStream;
996
+ }
1001
997
  /**
1002
- * Detect whether `M` has `K` set to a non-undefined value.
1003
- *
1004
- * When `M` is inferred from a literal such as `{ negation: "off" }`,
1005
- * `M["negation"]` is `"off"` (without `undefined`), so this returns `true`.
1006
- * When `M` is the wider `ArgMeta` type, `M["negation"]` is
1007
- * `string | boolean | undefined`, so this returns `false` and avoids
1008
- * false-positive type errors on broadly-typed meta values.
998
+ * Collected logs during command execution
1009
999
  */
1010
- type HasExplicit<M, K extends string> = K extends keyof M ? undefined extends M[K] ? false : true : false;
1000
+ interface CollectedLogs {
1001
+ /** All log entries in order */
1002
+ entries: LogEntry[];
1003
+ }
1011
1004
  /**
1012
- * Reject `negation` / `negationDescription` on non-boolean fields.
1013
- * Uses {@link HasExplicit} so the error only fires when the user explicitly
1014
- * sets the field on a narrowly-inferred meta literal.
1005
+ * Successful command execution result
1015
1006
  */
1016
- type ValidateNegation<M, TValue> = HasExplicit<M, "negation"> extends true ? IsBooleanField<TValue> extends true ? M : NegationTypeError<M> : HasExplicit<M, "negationDescription"> extends true ? IsBooleanField<TValue> extends true ? M : NegationTypeError<M> : M;
1007
+ interface RunResultSuccess<T = unknown> {
1008
+ /** Indicates successful execution */
1009
+ success: true;
1010
+ /** Command return value */
1011
+ result: T | undefined;
1012
+ /** Error that occurred during execution */
1013
+ error?: never;
1014
+ /** Exit code (always 0 for success) */
1015
+ exitCode: 0;
1016
+ /** Collected logs during execution */
1017
+ logs: CollectedLogs;
1018
+ }
1017
1019
  /**
1018
- * Type helper to validate ArgMeta.
1019
- * Forces a type error when a reserved alias ("h" / "H") is used without
1020
- * `overrideBuiltinAlias: true`, whether the alias is provided as a string
1021
- * or as part of an array, and whether it appears in `alias` or `hiddenAlias`.
1022
- * Also rejects `negation` / `negationDescription` on non-boolean fields.
1020
+ * Failed command execution result
1023
1021
  */
1024
- type ValidateArgMeta<M, TValue = unknown> = M extends {
1025
- overrideBuiltinAlias: true;
1026
- } ? ValidateNegation<M, TValue> : ContainsReservedAlias<AliasFieldOf<M>> extends true ? ReservedAliasTypeError<M> : ContainsReservedAlias<HiddenAliasFieldOf<M>> extends true ? ReservedAliasTypeError<M> : ValidateNegation<M, TValue>;
1022
+ interface RunResultFailure {
1023
+ /** Indicates failed execution */
1024
+ success: false;
1025
+ /** Command return value */
1026
+ result?: never;
1027
+ /** Error that occurred during execution */
1028
+ error: Error;
1029
+ /** Exit code (non-zero for failure) */
1030
+ exitCode: number;
1031
+ /** Collected logs during execution */
1032
+ logs: CollectedLogs;
1033
+ }
1027
1034
  /**
1028
- * The overloaded `arg()` signature, parameterized by the schema constraint.
1029
- * Core's `arg` accepts any Standard Schema; adapter packages re-pin the same
1030
- * runtime function to their library's schema type (e.g. `ArgFn<z.ZodType>`
1031
- * in `@politty/zod`) so a schema from the wrong library is rejected at the
1032
- * type level.
1035
+ * Result of command execution (discriminated union)
1033
1036
  */
1034
- interface ArgFn<TSchemaBase extends SchemaLike = SchemaLike> {
1035
- <T extends TSchemaBase>(schema: T): T;
1036
- <T extends TSchemaBase, M extends ArgMeta<InferSchemaOutput<T>>>(schema: T, meta: ValidateArgMeta<M, InferSchemaOutput<T>>): T;
1037
- }
1037
+ type RunResult<T = unknown> = RunResultSuccess<T> | RunResultFailure;
1038
1038
  //#endregion
1039
- export { toCamelCase as $, LogEntry as A, RunResultFailure as B, Command as C, GlobalCleanupContext as D, GlobalArgs as E, NonRunnableCommand as F, SubCommandsRecord as G, RunnableCommand as H, PromptResolver as I, isLazyCommand as J, UnknownSubcommandHandler as K, RunCommandOptions as L, LogStream as M, Logger as N, GlobalSetupContext as O, MainOptions as P, UnknownKeysMode as Q, RunInvocation as R, CollectedLogs as S, Example as T, SetupContext as U, RunResultSuccess as V, SubCommandValue as W, ExtractedFields as X, lazy as Y, ResolvedFieldMeta as Z, DynamicCompletionResult as _, CustomCompletion as a, ArgsSchema as b, PromptType as c, ExpandCompletion as d, toKebabCase as et, ResolvedExpandCandidate as f, DynamicCompletionResolver as g, DynamicCompletionContext as h, CompletionType as i, LogLevel as j, IsEmpty as k, ValidateArgMeta as l, DynamicCompletionCandidate as m, ArgMeta as n, SchemaLike as nt, EffectContext as o, CompletionDirectiveMask as p, LazyCommand as q, CompletionMeta as r, PromptMeta as s, ArgFn as t, InferSchemaOutput as tt, ExpandCandidate as u, AnyCommand as v, CommandBase as w, CleanupContext as x, ArgSource as y, RunResult as z };
1039
+ export { DynamicCompletionResolver as $, LazyCommand as A, CompletionMeta as B, RunResultFailure as C, SubCommandValue as D, SetupContext as E, UnknownKeysMode as F, PromptType as G, CustomCompletion as H, toCamelCase as I, ExpandCompletion as J, ValidateArgMeta as K, toKebabCase as L, lazy as M, ExtractedFields as N, SubCommandsRecord as O, ResolvedFieldMeta as P, DynamicCompletionContext as Q, ArgFn as R, RunResult as S, RunnableCommand as T, EffectContext as U, CompletionType as V, PromptMeta as W, CompletionDirectiveMask as X, ResolvedExpandCandidate as Y, DynamicCompletionCandidate as Z, MainOptions as _, CollectedLogs as a, RunCommandOptions as b, Example as c, GlobalSetupContext as d, DynamicCompletionResult as et, IsEmpty as f, Logger as g, LogStream as h, CleanupContext as i, isLazyCommand as j, UnknownSubcommandHandler as k, GlobalArgs as l, LogLevel as m, ArgSource as n, SchemaLike as nt, Command as o, LogEntry as p, ExpandCandidate as q, ArgsSchema as r, CommandBase as s, AnyCommand as t, InferSchemaOutput as tt, GlobalCleanupContext as u, NonRunnableCommand as v, RunResultSuccess as w, RunInvocation as x, PromptResolver as y, ArgMeta as z };