politty 0.11.5 → 0.11.7

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