@kjanat/dreamcli 2.4.1 → 3.0.0-rc.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 (94) hide show
  1. package/CHANGELOG.md +169 -1
  2. package/README.md +14 -7
  3. package/dist/core/cli/index.d.mts +283 -81
  4. package/dist/core/cli/index.mjs +1 -1
  5. package/dist/core/cli/planner.d.mts +27 -5
  6. package/dist/core/cli/planner.mjs +1 -1
  7. package/dist/core/cli/root-help.d.mts +16 -2
  8. package/dist/core/cli/root-help.mjs +3 -5
  9. package/dist/core/cli/root-surface.d.mts +18 -3
  10. package/dist/core/cli/root-surface.mjs +1 -1
  11. package/dist/core/cli/runtime-preflight.d.mts +31 -5
  12. package/dist/core/cli/runtime-preflight.mjs +1 -1
  13. package/dist/core/completion/index.d.mts +32 -1
  14. package/dist/core/completion/index.mjs +1 -1
  15. package/dist/core/completion/shells/shared.d.mts +10 -0
  16. package/dist/core/completion/shells/shared.mjs +1 -1
  17. package/dist/core/config/index.d.mts +2 -2
  18. package/dist/core/config/package-json.d.mts +93 -20
  19. package/dist/core/config/package-json.mjs +3 -1
  20. package/dist/core/help/index.d.mts +45 -1
  21. package/dist/core/help/index.mjs +6 -6
  22. package/dist/core/json-schema/index.mjs +1 -1
  23. package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
  24. package/dist/core/parse/index.d.mts +15 -1
  25. package/dist/core/parse/index.mjs +1 -1
  26. package/dist/core/prompt/index.d.mts +11 -3
  27. package/dist/core/prompt/index.mjs +3 -3
  28. package/dist/core/resolve/coerce.mjs +1 -1
  29. package/dist/core/resolve/flags.mjs +1 -1
  30. package/dist/core/resolve/property.d.mts +2 -0
  31. package/dist/core/resolve/property.mjs +1 -1
  32. package/dist/core/schema/arg.d.mts +90 -10
  33. package/dist/core/schema/arg.mjs +1 -1
  34. package/dist/core/schema/command.d.mts +3 -1
  35. package/dist/core/schema/flag.d.mts +92 -2
  36. package/dist/core/schema/flag.mjs +1 -1
  37. package/dist/core/schema/index.d.mts +2 -1
  38. package/dist/core/schema/number-constraints.d.mts +96 -0
  39. package/dist/core/schema/number-constraints.mjs +1 -0
  40. package/dist/core/schema/prompt.d.mts +15 -0
  41. package/dist/core/schema/run.d.mts +4 -4
  42. package/dist/core/testkit/index.d.mts +9 -5
  43. package/dist/core/testkit/index.mjs +1 -1
  44. package/dist/index.d.mts +4 -3
  45. package/dist/index.mjs +1 -1
  46. package/dist/runtime/auto.mjs +1 -1
  47. package/dist/runtime/bun.mjs +1 -1
  48. package/dist/runtime/deno.mjs +2 -2
  49. package/dist/runtime/node.mjs +2 -2
  50. package/dist/version.mjs +1 -1
  51. package/examples/basic.ts +5 -1
  52. package/examples/gh/package.json +2 -7
  53. package/examples/pwsh-demo/package.json +1 -7
  54. package/examples/pwsh-demo/src/main.test.ts +1 -4
  55. package/examples/pwsh-demo/src/main.ts +14 -4
  56. package/examples/transport-launcher.ts +85 -0
  57. package/package.json +15 -24
  58. package/src/core/cli/dispatch.ts +7 -1
  59. package/src/core/cli/index.ts +521 -122
  60. package/src/core/cli/planner.ts +192 -23
  61. package/src/core/cli/root-help.ts +195 -105
  62. package/src/core/cli/root-surface.ts +25 -12
  63. package/src/core/cli/runtime-preflight.ts +43 -8
  64. package/src/core/completion/index.ts +50 -0
  65. package/src/core/completion/shells/powershell.ts +2 -2
  66. package/src/core/completion/shells/shared.ts +30 -3
  67. package/src/core/config/index.ts +12 -2
  68. package/src/core/config/package-json.ts +250 -41
  69. package/src/core/execution/index.ts +1 -4
  70. package/src/core/help/index.ts +57 -10
  71. package/src/core/json-schema/index.ts +23 -4
  72. package/src/core/json-schema/meta-descriptions.generated.ts +115 -98
  73. package/src/core/parse/index.ts +62 -1
  74. package/src/core/prompt/index.ts +54 -14
  75. package/src/core/resolve/coerce.ts +73 -5
  76. package/src/core/resolve/flags.ts +14 -0
  77. package/src/core/resolve/property.ts +4 -4
  78. package/src/core/schema/arg.ts +125 -3
  79. package/src/core/schema/command.ts +3 -1
  80. package/src/core/schema/flag.ts +120 -4
  81. package/src/core/schema/index.ts +5 -0
  82. package/src/core/schema/number-constraints.ts +153 -0
  83. package/src/core/schema/prompt.ts +15 -0
  84. package/src/core/schema/run.ts +4 -4
  85. package/src/core/testkit/index.ts +32 -8
  86. package/src/index.ts +8 -0
  87. package/src/runtime/auto.ts +0 -24
  88. package/src/runtime/bun.ts +0 -7
  89. package/src/runtime/deno.ts +0 -2
  90. package/src/runtime/node.ts +0 -11
  91. package/src/runtime/support.ts +1 -59
  92. package/src/schema.ts +16 -0
  93. package/dist/runtime/support.d.mts +0 -42
  94. package/dist/runtime/support.mjs +0 -1
@@ -7,6 +7,7 @@ import { RuntimeAdapter } from "../../runtime/adapter.mjs";
7
7
  import { PackageJsonData } from "../config/package-json.mjs";
8
8
  import { HelpLinks } from "./help-links.mjs";
9
9
  import { CompletionOptions } from "../completion/shells/shared.mjs";
10
+ import { Shell } from "../completion/index.mjs";
10
11
  import { FormatLoader } from "../config/index.mjs";
11
12
  import { formatRootHelp } from "./root-help.mjs";
12
13
 
@@ -51,25 +52,91 @@ interface CLISchema {
51
52
  */
52
53
  readonly configSettings: ConfigSettings | undefined;
53
54
  /**
54
- * Package.json auto-discovery settings. When defined, `.run()` discovers
55
- * the nearest `package.json` and merges metadata before dispatch.
55
+ * Manifest auto-discovery settings. When defined, `.run()` discovers the
56
+ * nearest manifest (`package.json`, `deno.json`, `jsr.json`, …) and merges
57
+ * metadata before dispatch.
56
58
  *
57
- * Set via the {@linkcode CLIBuilder.packageJson | .packageJson()} builder method.
59
+ * Set via the {@linkcode CLIBuilder.manifest | .manifest()} builder method
60
+ * (or the {@linkcode CLIBuilder.packageJson | .packageJson()} /
61
+ * {@linkcode CLIBuilder.denoJson | .denoJson()} presets).
58
62
  */
59
- readonly packageJsonSettings: PackageJsonSettings | undefined;
63
+ readonly packageJsonSettings: ResolvedManifestSettings | undefined;
60
64
  /**
61
65
  * OSC 8 hyperlink targets for the root-help header (name/version).
62
66
  *
63
67
  * Set via the {@linkcode CLIBuilder.links | .links()} builder method.
64
- * Fields left `undefined` are derived from package.json metadata
65
- * (`repository` / `homepage`) when `.packageJson()` is active.
68
+ * Fields left `undefined` are derived from manifest metadata
69
+ * (`repository` / `homepage`) when manifest discovery ({@linkcode
70
+ * CLIBuilder.manifest | .manifest()}) is active.
66
71
  */
67
72
  readonly helpLinks: HelpLinks | undefined;
68
- /** Whether built-in `.completions()` command registration is active. */
73
+ /** Whether built-in `.completions()` registration (command or flag) is active. */
69
74
  readonly hasBuiltInCompletions: boolean;
75
+ /**
76
+ * Eager `--completions <shell>` flag configuration.
77
+ *
78
+ * Set when `.completions({ as: 'flag' })` is used instead of the default
79
+ * `completions` subcommand. When defined, the planner intercepts
80
+ * `--completions <shell>` before dispatch, prints the script, and exits;
81
+ * root help advertises the flag in its `Flags:` section.
82
+ */
83
+ readonly completionsFlag: CompletionsFlagConfig | undefined;
84
+ /**
85
+ * Consumer-configured root-help defaults.
86
+ *
87
+ * Set via the {@linkcode CLIBuilder.help | .help()} builder method and merged
88
+ * under runtime `options.help` (runtime wins) before rendering.
89
+ */
90
+ readonly helpConfig: HelpConfig | undefined;
70
91
  /** Registered CLI plugins. */
71
92
  readonly plugins: readonly CLIPlugin[];
72
93
  }
94
+ /**
95
+ * Configuration for the eager `--completions <shell>` flag.
96
+ *
97
+ * Stored in {@link CLISchema} when `.completions({ as: 'flag' })` is used.
98
+ *
99
+ * @internal
100
+ */
101
+ interface CompletionsFlagConfig {
102
+ /** Shell targets the flag accepts (mirrors {@link SHELLS}). */
103
+ readonly shells: readonly Shell[];
104
+ /** Generator options captured at build time (e.g. `functionPrefix`, `rootMode`). */
105
+ readonly options: CompletionOptions | undefined;
106
+ }
107
+ /**
108
+ * Consumer-facing root-help configuration set via {@linkcode CLIBuilder.help}.
109
+ *
110
+ * Every field is optional; unset fields fall back to built-in defaults and may
111
+ * be overridden per call through runtime `options.help`.
112
+ */
113
+ interface HelpConfig {
114
+ /**
115
+ * Render the default command's arguments and flags inline at the root.
116
+ *
117
+ * @defaultValue `true`
118
+ */
119
+ readonly inlineDefault?: boolean;
120
+ /**
121
+ * Also list the default command in the root `Commands:` table.
122
+ *
123
+ * By default the default command is the root surface and is omitted from the
124
+ * command list (its args/flags render inline instead).
125
+ *
126
+ * @defaultValue `false`
127
+ */
128
+ readonly showDefaultInCommands?: boolean;
129
+ /**
130
+ * Show the `Run '<bin> <command> --help' for more information.` hint.
131
+ *
132
+ * Defaults to showing the hint only when visible subcommands exist.
133
+ */
134
+ readonly footer?: boolean;
135
+ /** Maximum line width (columns). */
136
+ readonly width?: number;
137
+ /** Emit OSC 8 hyperlinks in the header when supported. */
138
+ readonly hyperlinks?: boolean;
139
+ }
73
140
  /**
74
141
  * Config discovery settings for automatic config file loading.
75
142
  *
@@ -90,14 +157,22 @@ interface ConfigSettings {
90
157
  readonly loaders: readonly FormatLoader[] | undefined;
91
158
  }
92
159
  /**
93
- * Package.json auto-discovery settings.
160
+ * Manifest auto-discovery settings — the resolved/normalized shape stored in
161
+ * the schema.
94
162
  *
95
163
  * Stored in {@link CLISchema} and consumed by `CLIBuilder.run()` to
96
- * call {@link discoverPackageJson} before dispatching to a command.
164
+ * call {@link discoverManifest} before dispatching to a command.
165
+ *
166
+ * Note: the schema FIELD name (`packageJsonSettings`) keeps its `packageJson`
167
+ * prefix for backward compatibility — renaming it would break consumers reading
168
+ * `app.schema.packageJsonSettings`. The type itself is now generically named
169
+ * (it holds discovery config for any manifest — `package.json`, `deno.json`,
170
+ * `jsr.json`); the legacy {@link PackageJsonSettings} alias remains exported for
171
+ * backward compatibility.
97
172
  */
98
- interface PackageJsonSettings {
173
+ interface ResolvedManifestSettings {
99
174
  /**
100
- * Infer CLI name from package.json `bin` keys or `name` field.
175
+ * Infer CLI name from manifest `bin` keys or `name` field.
101
176
  *
102
177
  * When `true`, the discovered name replaces the `cli(name)` value.
103
178
  * Explicit `.version()`/`.description()` calls still take precedence
@@ -106,15 +181,30 @@ interface PackageJsonSettings {
106
181
  * @defaultValue `false`
107
182
  */
108
183
  readonly inferName: boolean;
184
+ /**
185
+ * Strip a leading `@scope/` from the inferred `name` fallback.
186
+ *
187
+ * Only consulted when {@link ResolvedManifestSettings.inferName | `inferName`}
188
+ * is `true` and the name comes from the manifest `name` field (not a `bin`
189
+ * key, which is never scoped).
190
+ *
191
+ * @defaultValue `true`
192
+ */
193
+ readonly stripScope: boolean;
109
194
  /**
110
195
  * Explicit filesystem anchor for discovery; overrides `adapter.cwd`.
111
196
  *
112
- * Resolved to a string path before storage. When set, `discoverPackageJson`
197
+ * Resolved to a string path before storage. When set, `discoverManifest`
113
198
  * walks up from here instead of the runtime cwd. Required for installable
114
199
  * CLIs whose version should reflect THEIR OWN package, not the consumer's
115
200
  * working directory.
116
201
  */
117
202
  readonly from: string | undefined;
203
+ /**
204
+ * Candidate manifest filenames, in per-directory priority order
205
+ * (e.g. `['deno.json', 'deno.jsonc', 'jsr.json']` for `.denoJson()`).
206
+ */
207
+ readonly files: readonly string[];
118
208
  /**
119
209
  * Pre-loaded data; skips filesystem discovery, uses values verbatim.
120
210
  *
@@ -122,11 +212,20 @@ interface PackageJsonSettings {
122
212
  * ```ts
123
213
  * import pkg from './package.json' with { type: 'json' };
124
214
  *
125
- * cli('mycli').packageJson(pkg);
215
+ * cli('mycli').manifest(pkg);
126
216
  * ```
127
217
  */
128
218
  readonly data: PackageJsonData | undefined;
129
219
  }
220
+ /**
221
+ * Resolved manifest discovery settings stored in {@link CLISchema}.
222
+ *
223
+ * @deprecated Renamed to {@link ResolvedManifestSettings}. The stored shape
224
+ * holds generic manifest discovery config (`package.json`, `deno.json`,
225
+ * `jsr.json`), not just `package.json`; the misleading name is kept only for
226
+ * backward compatibility.
227
+ */
228
+ type PackageJsonSettings = ResolvedManifestSettings;
130
229
  /**
131
230
  * Options for {@linkcode CLIBuilder.execute | .execute()} and {@linkcode CLIBuilder.run | .run()}.
132
231
  *
@@ -198,21 +297,21 @@ declare class CLIBuilder {
198
297
  * `options.help.hyperlinks`), and only in the header — usage lines, the
199
298
  * `--help` hint, the commands table, and completion scripts stay plain.
200
299
  *
201
- * URLs not provided here are derived from package.json metadata when
202
- * `.packageJson()` is active (works with both filesystem discovery and
300
+ * URLs not provided here are derived from manifest metadata when
301
+ * `.manifest()` is active (works with both filesystem discovery and
203
302
  * pre-loaded data):
204
303
  * - **name** → normalized `repository` URL, falling back to `homepage`
205
304
  * - **version** → forge release tag (`{repo}/releases/tag/v{version}` on
206
305
  * GitHub, `{repo}/-/releases/v{version}` on GitLab)
207
306
  *
208
- * @param links - Explicit URLs; omit to derive everything from package.json.
307
+ * @param links - Explicit URLs; omit to derive everything from the manifest.
209
308
  * @returns The builder (for chaining).
210
309
  *
211
310
  * @example
212
311
  * ```ts
213
- * // Derive both links from package.json repository/homepage:
312
+ * // Derive both links from the manifest repository/homepage:
214
313
  * cli('mycli')
215
- * .packageJson()
314
+ * .manifest()
216
315
  * .links()
217
316
  * .run();
218
317
  *
@@ -230,6 +329,25 @@ declare class CLIBuilder {
230
329
  readonly name?: string | URL;
231
330
  readonly version?: string | URL;
232
331
  }): CLIBuilder;
332
+ /**
333
+ * Configure root-help rendering defaults.
334
+ *
335
+ * Stored on the schema and merged **under** any runtime `options.help`
336
+ * (runtime wins). Call multiple times to set fields incrementally.
337
+ *
338
+ * @param config - Help rendering options (see {@link HelpConfig}).
339
+ * @returns The builder (for chaining).
340
+ *
341
+ * @example
342
+ * ```ts
343
+ * // Echo the default command under Commands and never show the footer:
344
+ * cli('mycli')
345
+ * .help({ showDefaultInCommands: true, footer: false })
346
+ * .default(serve)
347
+ * .run();
348
+ * ```
349
+ */
350
+ help(config: HelpConfig): CLIBuilder;
233
351
  /**
234
352
  * Enable automatic config file discovery.
235
353
  *
@@ -292,83 +410,120 @@ declare class CLIBuilder {
292
410
  */
293
411
  configLoader(loader: FormatLoader): CLIBuilder;
294
412
  /**
295
- * Enable package.json metadata from pre-loaded data.
296
- *
297
- * Pass an already-imported `package.json` to skip filesystem discovery
298
- * entirely — useful for bundled or installable CLIs where the version
299
- * should be locked at build time. The data's `version`/`description` are
300
- * merged into the CLI schema immediately, so this form works in **both**
301
- * `.run()` and `.execute()` (the filesystem-free path). Explicit
302
- * `.version()`/`.description()` calls still take precedence, and the data
303
- * form does not infer the CLI name.
413
+ * Enable manifest metadata from pre-loaded data.
414
+ *
415
+ * Pass an already-imported manifest (`package.json`, `deno.json`, `jsr.json`)
416
+ * to skip filesystem discovery entirely — useful for bundled or installable
417
+ * CLIs where the version should be locked at build time. The data's
418
+ * `version`/`description` are merged into the CLI schema immediately, so this
419
+ * form works in **both** `.run()` and `.execute()` (the filesystem-free path).
420
+ * Explicit `.version()`/`.description()` calls still take precedence, and the
421
+ * data form does not infer the CLI name — `inferName` / `{ scope }` are
422
+ * available only on the discovery (settings) form. For a pre-loaded manifest
423
+ * whose scoped `name` should drive the CLI name, set the name explicitly via
424
+ * `cli(name)` (or call {@link inferCliName} on the data yourself).
304
425
  *
305
426
  * Detected by field shape: an object carrying at least one of
306
- * `name`/`version`/`description`/`bin`. An empty `{}` or a settings-shaped
307
- * object falls through to the settings overload.
427
+ * `name`/`version`/`description`/`bin`/`homepage`/`repository`. An empty `{}`
428
+ * or a settings-shaped object falls through to the settings overload.
308
429
  *
309
- * @param data - Pre-loaded `package.json` metadata.
430
+ * @param data - Pre-loaded manifest metadata.
310
431
  *
311
432
  * @example
312
433
  * ```ts
313
- * import pkg from './package.json' with { type: 'json' };
434
+ * import denoCfg from './deno.json' with { type: 'json' };
314
435
  *
315
436
  * // No filesystem; works in .run() AND .execute():
316
437
  * cli('mycli')
317
- * .packageJson(pkg)
438
+ * .manifest(denoCfg)
318
439
  * .command(deploy)
319
440
  * .run();
320
441
  * ```
321
442
  */
322
- packageJson(data: PackageJsonData): CLIBuilder;
443
+ manifest(data: PackageJsonData): CLIBuilder;
323
444
  /**
324
- * Enable automatic package.json metadata discovery.
445
+ * Enable automatic manifest metadata discovery.
325
446
  *
326
- * When enabled, `.run()` walks up from `cwd` to find the nearest
327
- * `package.json` and merges its `version` and `description` fields
328
- * into the CLI schema. Explicit `.version()` and `.description()`
329
- * calls always take precedence over discovered values.
447
+ * When enabled, `.run()` walks up from `cwd` (or {@link ManifestSettings.from})
448
+ * to find the nearest manifest among {@link ManifestSettings.files} and merges
449
+ * its `version`/`description` into the CLI schema. Explicit `.version()` /
450
+ * `.description()` calls always take precedence.
330
451
  *
331
- * Has no effect in `.execute()` (which is filesystem-free by design) —
332
- * use the {@link CLIBuilder.packageJson | data overload} for that.
452
+ * Files are parsed as JSON with a JSONC fallback — `package.json`, `deno.json`,
453
+ * `jsr.json`, and `deno.jsonc` all qualify, including files with `//` / block
454
+ * comments or trailing commas. A file that fails both parses is skipped
455
+ * (discovery keeps walking).
456
+ *
457
+ * Has no effect in `.execute()` (filesystem-free) — use the data overload.
333
458
  *
334
459
  * @param settings - Optional settings:
335
- * - `inferName`: also infer the CLI name from `bin` keys or `name` field.
336
- * - `from`: anchor discovery to a specific file/URL/path instead of `cwd`.
337
- * Pass `import.meta.url` for installable CLIs that need to report
338
- * THEIR OWN version (not the consumer's project version). Accepts
339
- * string paths, `file:` URL strings, or `URL` instances.
460
+ * - `files`: candidate manifest filenames in priority order
461
+ * (default `['package.json']`).
462
+ * - `inferName`: infer the CLI name from `bin` keys or `name`. Pass
463
+ * `{ scope: 'keep' }` to keep a leading `@scope/` (stripped by default).
464
+ * - `from`: anchor discovery to a file/URL/path instead of `cwd`. Pass
465
+ * `import.meta.url` for installable CLIs that must report THEIR OWN
466
+ * version. Accepts string paths, `file:` URL strings, or `URL` instances.
340
467
  *
341
468
  * @example
342
469
  * ```ts
343
- * // Auto-fill version + description from nearest package.json:
470
+ * // Deno CLI: discover OUR deno.json (then jsr.json), keep the scope in name:
344
471
  * cli('mycli')
345
- * .packageJson()
472
+ * .manifest({
473
+ * files: ['deno.json', 'jsr.json'],
474
+ * from: import.meta.url,
475
+ * inferName: { scope: 'keep' },
476
+ * })
346
477
  * .command(deploy)
347
478
  * .run();
479
+ * ```
480
+ */
481
+ manifest(settings?: ManifestSettings): CLIBuilder;
482
+ /**
483
+ * Discover metadata from `package.json` (preset for {@link CLIBuilder.manifest}).
348
484
  *
349
- * // Also infer CLI name from bin key / package name:
350
- * cli('mycli')
351
- * .packageJson({ inferName: true })
352
- * .command(deploy)
353
- * .run();
485
+ * @deprecated Use {@link CLIBuilder.manifest} — `.manifest()` defaults to
486
+ * `package.json` and also supports `deno.json` / `jsr.json` via `files`.
354
487
  *
355
- * // Installable CLI; discover OUR package.json, not the consumer's:
356
- * cli('mycli')
357
- * .packageJson({ from: import.meta.url })
358
- * .command(deploy)
359
- * .run();
488
+ * @param data - Pre-loaded `package.json` metadata.
489
+ */
490
+ packageJson(data: PackageJsonData): CLIBuilder;
491
+ /**
492
+ * Discover metadata from `package.json` (preset for {@link CLIBuilder.manifest}).
493
+ *
494
+ * @deprecated Use {@link CLIBuilder.manifest}.
495
+ *
496
+ * @param settings - `inferName` / `from` (see {@link CLIBuilder.manifest}).
497
+ */
498
+ packageJson(settings?: ManifestPresetSettings): CLIBuilder;
499
+ /**
500
+ * Discover metadata from `deno.json`, `deno.jsonc`, then `jsr.json` (preset for
501
+ * {@link CLIBuilder.manifest}).
502
+ *
503
+ * @deprecated Use `.manifest({ files: ['deno.json', 'deno.jsonc', 'jsr.json'] })`.
504
+ *
505
+ * @param data - Pre-loaded `deno.json` / `jsr.json` metadata.
506
+ */
507
+ denoJson(data: PackageJsonData): CLIBuilder;
508
+ /**
509
+ * Discover metadata from `deno.json`, `deno.jsonc`, then `jsr.json` (preset for
510
+ * {@link CLIBuilder.manifest}).
511
+ *
512
+ * @deprecated Use `.manifest({ files: ['deno.json', 'deno.jsonc', 'jsr.json'] })`.
360
513
  *
361
- * // Explicit values always win:
514
+ * @param settings - `inferName` / `from` (see {@link CLIBuilder.manifest}).
515
+ * `deno.json` / `jsr.json` have no `bin` field, so `inferName` resolves
516
+ * from `name`; pass `{ scope: 'keep' }` to retain a leading `@scope/`.
517
+ *
518
+ * @example
519
+ * ```ts
362
520
  * cli('mycli')
363
- * .packageJson()
364
- * .version('2.0.0-beta') // wins over package.json
521
+ * .denoJson({ from: import.meta.url })
522
+ * .command(deploy)
365
523
  * .run();
366
524
  * ```
367
525
  */
368
- packageJson(settings?: {
369
- readonly inferName?: boolean;
370
- readonly from?: string | URL;
371
- }): CLIBuilder;
526
+ denoJson(settings?: ManifestPresetSettings): CLIBuilder;
372
527
  /**
373
528
  * Register a command with the CLI program.
374
529
  *
@@ -387,8 +542,11 @@ declare class CLIBuilder {
387
542
  * dispatch normally, but empty argv or flags-only argv falls through to
388
543
  * this command instead of showing root help.
389
544
  *
390
- * The command is also registered as a normal subcommand (can be invoked
391
- * by name). Only one default command is allowed.
545
+ * The default command is the CLI's root *surface*: its flags and arguments
546
+ * are rendered inline in root help. It is **not** a named subcommand — it
547
+ * cannot be invoked by its own name (`mycli mycmd` does not route to it) and
548
+ * it is omitted from the root `Commands:` list by default (re-enable with
549
+ * `.help({ showDefaultInCommands: true })`). Only one default is allowed.
392
550
  *
393
551
  * @example
394
552
  * ```ts
@@ -423,28 +581,36 @@ declare class CLIBuilder {
423
581
  */
424
582
  plugin(definition: CLIPlugin): CLIBuilder;
425
583
  /**
426
- * Register a built-in `completions` subcommand that generates shell
427
- * completion scripts.
428
- *
429
- * The generated command accepts a `--shell` flag (required, enum of
430
- * all {@link Shell} values) and writes the completion script to stdout
431
- * via `out.log()`. Unsupported shells throw a descriptive {@linkcode CLIError}
432
- * instead of a generic parse error.
433
- *
434
- * Call this **after** registering all other commands so the completion
435
- * script includes the full command set. The captured schema is a
436
- * snapshot at call time — commands registered after `.completions()`
437
- * will not appear in the generated script. Completion options are also
438
- * captured at call time.
584
+ * Register built-in shell completion.
585
+ *
586
+ * By default (`{ as: 'command' }`) this registers a `completions` subcommand
587
+ * that accepts a `shell` argument and writes the script to stdout. With
588
+ * `{ as: 'flag' }` it instead exposes an eager `--completions <shell>` flag on
589
+ * the CLI root — no subcommand is registered, so a default command stays the
590
+ * lone root surface. The flag may be given without a value to auto-detect the
591
+ * shell from `$SHELL` / `$PSModulePath`.
592
+ *
593
+ * In subcommand mode, call this **after** registering all other commands so
594
+ * the completion script includes the full command set: that path snapshots the
595
+ * schema (and completion options) at call time, so commands registered
596
+ * afterwards will not appear in that subcommand's generated script. In flag
597
+ * mode, generation runs at execution time from the final builder schema, so
598
+ * registration order does not matter.
439
599
  *
440
600
  * @example
441
601
  * ```ts
602
+ * // Subcommand form (default):
442
603
  * cli('mycli')
443
604
  * .version('1.0.0')
444
605
  * .command(deploy)
445
- * .command(login)
446
606
  * .completions({ rootMode: 'surface' })
447
607
  * .run();
608
+ *
609
+ * // Eager-flag form, ideal for single-command CLIs:
610
+ * cli('mycli')
611
+ * .completions({ as: 'flag' })
612
+ * .default(serve)
613
+ * .run();
448
614
  * ```
449
615
  */
450
616
  completions(options?: CompletionOptions): CLIBuilder;
@@ -478,6 +644,42 @@ declare class CLIBuilder {
478
644
  */
479
645
  run(options?: CLIRunOptions): Promise<never>;
480
646
  }
647
+ /**
648
+ * CLI-name inference control for {@link ManifestSettings.inferName}.
649
+ *
650
+ * - `false` (or omitted): do not infer the name.
651
+ * - `true`: infer, stripping a leading `@scope/` from the `name` fallback.
652
+ * - `{ scope: 'keep' }`: infer, keeping the full scoped name.
653
+ * - `{ scope: 'strip' }`: infer, stripping the scope (explicit form of `true`).
654
+ *
655
+ * `scope` is required in the object form: an empty `{}` is rejected so that an
656
+ * options object can never silently enable inference (use `true` for that).
657
+ */
658
+ type InferNameOption = boolean | {
659
+ readonly scope: 'keep' | 'strip';
660
+ };
661
+ /** Discovery settings accepted by {@link CLIBuilder.manifest}. */
662
+ interface ManifestSettings {
663
+ /** Infer the CLI name from `bin` keys or `name`. @defaultValue `false` */
664
+ readonly inferName?: InferNameOption;
665
+ /** Anchor discovery to a file/URL/path instead of `cwd`. */
666
+ readonly from?: string | URL;
667
+ /**
668
+ * Candidate manifest filenames in priority order — NOT npm's `files` publish
669
+ * globs. Discovery probes each name per directory and takes the first that
670
+ * parses.
671
+ *
672
+ * @defaultValue `['package.json']`
673
+ */
674
+ readonly files?: readonly string[];
675
+ }
676
+ /**
677
+ * Discovery settings for the `.packageJson()` / `.denoJson()` presets (no `files`).
678
+ *
679
+ * @deprecated Both presets are deprecated; use {@link ManifestSettings} with
680
+ * {@link CLIBuilder.manifest}.
681
+ */
682
+ type ManifestPresetSettings = Omit<ManifestSettings, 'files'>;
481
683
  /**
482
684
  * Options for the `cli({...})` factory form.
483
685
  *
@@ -528,4 +730,4 @@ declare function cli(name: string): CLIBuilder;
528
730
  /** Create a new CLI program builder from an options object. */
529
731
  declare function cli(options: CLIOptions): CLIBuilder;
530
732
  //#endregion
531
- export { type BeforeParseParams, CLIBuilder, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type ConfigSettings, type HelpLinks, type PackageJsonSettings, type PluginCommandContext, type ResolvedCommandParams, cli, formatRootHelp, plugin };
733
+ export { type BeforeParseParams, CLIBuilder, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type CompletionsFlagConfig, type ConfigSettings, type HelpConfig, type HelpLinks, type InferNameOption, type ManifestPresetSettings, type ManifestSettings, type PackageJsonSettings, type PluginCommandContext, type ResolvedCommandParams, type ResolvedManifestSettings, cli, formatRootHelp, plugin };
@@ -1 +1 @@
1
- import{CLIError as e}from"../errors/index.mjs";import{SHELLS as t,generateCompletion as n}from"../completion/index.mjs";import{formatHelp as r}from"../help/index.mjs";import{clearRequestedExitCode as i,createCaptureOutput as a,createOutput as o}from"../output/index.mjs";import{includesBeforeSeparator as s}from"../parse/index.mjs";import{buildRunResult as c,executeCommand as l}from"../execution/index.mjs";import{arg as u}from"../schema/arg.mjs";import{command as d}from"../schema/command.mjs";import{runCommand as f}from"../testkit/index.mjs";import{stripTrailing as p}from"../../strings.mjs";import{createAdapter as m}from"../../runtime/auto.mjs";import{deriveHelpLinks as h}from"./help-links.mjs";import{planInvocation as g}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as _}from"./root-help.mjs";import{prepareRuntimePreflight as v}from"./runtime-preflight.mjs";function y(e){return[e.name,...e.aliases]}function b(t,n,r,i){let a=n.get(r);if(a!==void 0)throw new e(`Duplicate command route '${r}' under '${t}' (${a} and ${i})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure sibling command names and aliases are unique`});n.set(r,i)}function x(t,n){let r=new Map;for(let e of t)for(let t of y(e.schema))b(`root`,r,t,e.schema.name);for(let t of y(n)){let i=r.get(t);if(i!==void 0)throw new e(`Command route '${t}' is already registered by '${i}'`,{code:`DUPLICATE_COMMAND`,suggest:i===n.name?`Ensure command '${n.name}' does not reuse route '${t}'`:`Rename '${n.name}' or remove route '${t}' from '${i}'`});r.set(t,n.name)}}function S(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=y(r.schema);for(let t of i)b(e.schema.name,n,t,r.schema.name);let a=S(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return f(e,t,n)}}}function C(e,t,n){return{help:t,...n===void 0?{}:{meta:n},...e?.plugins===void 0?{}:{plugins:e.plugins},...e?.env===void 0?{}:{env:e.env},...e?.config===void 0?{}:{config:e.config},...e?.stdinData===void 0?{}:{stdinData:e.stdinData},...e?.prompter===void 0?{}:{prompter:e.prompter},...e?.answers===void 0?{}:{answers:e.answers},...e?.verbosity===void 0?{}:{verbosity:e.verbosity},...e?.jsonMode===void 0?{}:{jsonMode:e.jsonMode},...e?.isTTY===void 0?{}:{isTTY:e.isTTY},...e?.out===void 0?{}:{out:e.out},...e?.captured===void 0?{}:{captured:e.captured}}}var w=class f{schema;constructor(e){this.schema=e}version(e){return new f({...this.schema,version:e})}description(e){return new f({...this.schema,description:e})}links(e){return new f({...this.schema,helpLinks:{name:k(e?.name),version:k(e?.version)}})}config(e,t){return new f({...this.schema,configSettings:{appName:e,loaders:t}})}configLoader(t){if(this.schema.configSettings===void 0)throw new e(`.configLoader() requires .config() to be called first`,{code:`INVALID_BUILDER_STATE`,suggest:`Call .config(appName) before .configLoader()`});let n=this.schema.configSettings.loaders??[];return new f({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...n,t]}})}packageJson(e){return M(e)?new f({...this.schema,...this.schema.version===void 0&&e.version!==void 0?{version:e.version}:{},...this.schema.description===void 0&&e.description!==void 0?{description:e.description}:{},packageJsonSettings:{inferName:!1,from:void 0,data:e}}):new f({...this.schema,packageJsonSettings:{inferName:e?.inferName??!1,from:j(e?.from),data:void 0}})}command(e){return x(this.schema.commands,e.schema),new f({...this.schema,commands:[...this.schema.commands,S(e)]})}default(t){if(this.schema.defaultCommand!==void 0)throw new e(`Only one default command is allowed`,{code:`DUPLICATE_DEFAULT`,suggest:`Call .default() only once when building the CLI`});x(this.schema.commands,t.schema);let n=S(t);return new f({...this.schema,commands:[...this.schema.commands,n],defaultCommand:n})}plugin(e){return new f({...this.schema,plugins:[...this.schema.plugins,e]})}completions(r){if(this.schema.hasBuiltInCompletions)throw new e(`.completions() has already been called`,{code:`DUPLICATE_COMMAND`,suggest:`Call .completions() only once when building the CLI`});let i=this.schema,a=r,o=new Map;for(let e of t)o.set(e,e);o.set(`pwsh`,`powershell`);let s=d(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,u.custom(e=>{let n=e.split(/[\\/]/),r=(n[n.length-1]??e).replace(/\.(?:exe|cmd|bat)$/i,``),i=o.get(r);if(i===void 0)throw Error(`Unknown shell '${r}'. Valid shells: ${t.join(`, `)}`);return i}).env(`SHELL`).describe(`Target shell (${t.join(`, `)})`)).action(({args:e,meta:t,out:r})=>{let o=n(t.bin===i.name?i:{...i,name:t.bin},e.shell,a);r.jsonMode?r.json({shell:e.shell,script:o}):r.log(o)});return new f({...this.command(s).schema,hasBuiltInCompletions:!0})}async execute(e,t){let n=s(e,`--json`)||t?.jsonMode===!0,o={...t?.verbosity===void 0?{}:{verbosity:t.verbosity},...n?{jsonMode:n}:{},...t?.isTTY===void 0?{}:{isTTY:t.isTTY}},u,d;t?.out===void 0?[u,d]=a(Object.keys(o).length>0?o:void 0):(u=t.out,d=t.captured??{stdout:[],stderr:[],activity:[]}),i(u);let f={...t?.help,binName:t?.help?.binName??this.schema.name,hyperlinks:t?.help?.hyperlinks??u.isTTY},p={...t,plugins:this.schema.plugins,...n?{jsonMode:n}:{}},m={jsonMode:n,isTTY:u.isTTY,verbosity:t?.verbosity??`normal`},h=g({schema:this.schema,argv:e,help:f,output:m});switch(h.kind){case`root-version`:return u.log(h.version),c({exitCode:0,error:void 0},d);case`root-help`:{let e=_(A(this.schema),h.help);return u.log(e),c({exitCode:0,error:void 0},d)}case`dispatch-error`:return n?u.json({error:h.error.toJSON()}):(u.error(h.error.message),h.error.suggest!==void 0&&h.error.code!==`NO_ACTION`&&u.error(`Suggestion: ${h.error.suggest}`)),c({exitCode:h.error.exitCode,error:h.error},d);case`needs-subcommand`:{let e=r(h.command.schema,h.help);return u.log(e),c({exitCode:0,error:void 0},d)}case`match`:{let e=C(p,h.plan.help??f,h.plan.meta);return h.plan.command._command===void 0?h.plan.command._execute(h.plan.argv,{...e,mergedSchema:h.plan.mergedSchema}):c(await l({command:h.plan.command._command,argv:h.plan.argv,out:u,schema:h.plan.mergedSchema,meta:h.plan.meta,options:e}),d)}}}async run(e){let t=e?.adapter??m(),n=this.schema.inheritName?O(t.argv):void 0,r=await v({schema:this.schema,adapter:t,options:e,inheritedName:n});if(r.kind===`config-error`)return r.jsonMode?t.stdout(`${JSON.stringify({error:r.error.toJSON()})}\n`):(t.stderr(`Error: ${r.error.message}\n`),r.error.suggest!==void 0&&t.stderr(`Suggestion: ${r.error.suggest}\n`)),t.exit(r.error.exitCode);let i=r.schema===this.schema?this:new f(r.schema),a={...e,...r.inputs,out:o({stdout:t.stdout,stderr:t.stderr,jsonMode:r.inputs.jsonMode,isTTY:r.inputs.isTTY,...r.inputs.verbosity===`normal`?{}:{verbosity:r.inputs.verbosity}})},s=await i.execute(r.filteredArgv,a);for(let e of s.stdout)t.stdout(e);for(let e of s.stderr)t.stderr(e);return t.exit(s.exitCode)}};const T=new Set([`bun`,`deno`,`node`,`tsx`]);function E(e){let t=p(e,[47,92]);if(t.length===0)return;let n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`)),r=n>=0?t.slice(n+1):t;return r.length>0?r:void 0}function D(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return T.has(t)}function O(e){let t=e[0],n=e[1],r=t===void 0?void 0:E(t);if(r!==void 0&&D(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:E(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:E(n)}return t===void 0?void 0:E(t)}function k(e){if(e!==void 0)return e instanceof URL?e.href:e}function A(e){return e.helpLinks===void 0?e:{...e,helpLinks:h(e.helpLinks,e.packageJsonSettings?.data,e.version)}}function j(e){if(e===void 0)return;if(e instanceof URL){if(e.protocol!==`file:`)return e.href}else if(!e.startsWith(`file:`))return e;let t=decodeURIComponent(new URL(e).pathname);return/^\/[A-Za-z]:/.test(t)?t.slice(1).replace(/\//g,`\\`):t}function M(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:`name`in e||`version`in e||`description`in e||`bin`in e||`homepage`in e||`repository`in e}function N(e){return new w({name:typeof e==`string`?e:e.name??`cli`,inheritName:typeof e==`string`?!1:e.inherit??!1,version:void 0,description:void 0,commands:[],defaultCommand:void 0,configSettings:void 0,packageJsonSettings:void 0,helpLinks:void 0,hasBuiltInCompletions:!1,plugins:[]})}export{w as CLIBuilder,N as cli};
1
+ import{getFlagAliasNames as e}from"../schema/flag.mjs";import{CLIError as t}from"../errors/index.mjs";import{SHELLS as n,detectShell as r,generateCompletion as i,normalizeShell as a}from"../completion/index.mjs";import{formatHelp as o}from"../help/index.mjs";import{clearRequestedExitCode as s,createCaptureOutput as c,createOutput as l}from"../output/index.mjs";import{arg as u}from"../schema/arg.mjs";import{command as d}from"../schema/command.mjs";import{includesBeforeSeparator as f}from"../parse/index.mjs";import{buildRunResult as p,executeCommand as m}from"../execution/index.mjs";import{runCommand as h}from"../testkit/index.mjs";import{stripTrailing as g}from"../../strings.mjs";import{createAdapter as _}from"../../runtime/auto.mjs";import{deriveHelpLinks as v}from"./help-links.mjs";import{planInvocation as y}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as b}from"./root-help.mjs";import{prepareRuntimePreflight as x}from"./runtime-preflight.mjs";const S=`completions`;function C(t){if(Object.hasOwn(t.flags,S))return!0;for(let n of Object.values(t.flags))if(e(n,{kind:`long`,includeHidden:!0}).includes(S))return!0;return t.commands.some(C)}function w(e){if(C(e))throw new t(`Command '${e.name}' defines a '--${S}' flag, which is reserved by .completions({ as: 'flag' })`,{code:`RESERVED_FLAG`,suggest:`Rename the flag, or register completions as a subcommand with .completions() instead of { as: 'flag' }`})}function T(e){return[e.name,...e.aliases]}function E(e,n,r,i){let a=n.get(r);if(a!==void 0)throw new t(`Duplicate command route '${r}' under '${e}' (${a} and ${i})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure sibling command names and aliases are unique`});n.set(r,i)}function D(e,n,r){let i=new Map,a=r===void 0?e:[...e,r];for(let e of a)for(let t of T(e.schema))E(`root`,i,t,e.schema.name);for(let e of T(n)){let r=i.get(e);if(r!==void 0)throw new t(`Command route '${e}' is already registered by '${r}'`,{code:`DUPLICATE_COMMAND`,suggest:r===n.name?`Ensure command '${n.name}' does not reuse route '${e}'`:`Rename '${n.name}' or remove route '${e}' from '${r}'`});i.set(e,n.name)}}function O(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=T(r.schema);for(let t of i)E(e.schema.name,n,t,r.schema.name);let a=O(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return h(e,t,n)}}}function k(e,t,n){return{help:t,...n===void 0?{}:{meta:n},...e?.plugins===void 0?{}:{plugins:e.plugins},...e?.env===void 0?{}:{env:e.env},...e?.config===void 0?{}:{config:e.config},...e?.stdinData===void 0?{}:{stdinData:e.stdinData},...e?.prompter===void 0?{}:{prompter:e.prompter},...e?.answers===void 0?{}:{answers:e.answers},...e?.verbosity===void 0?{}:{verbosity:e.verbosity},...e?.jsonMode===void 0?{}:{jsonMode:e.jsonMode},...e?.isTTY===void 0?{}:{isTTY:e.isTTY},...e?.out===void 0?{}:{out:e.out},...e?.captured===void 0?{}:{captured:e.captured}}}var A=class e{schema;constructor(e){this.schema=e}version(t){return new e({...this.schema,version:t})}description(t){return new e({...this.schema,description:t})}links(t){return new e({...this.schema,helpLinks:{name:F(t?.name),version:F(t?.version)}})}help(t){return new e({...this.schema,helpConfig:{...this.schema.helpConfig,...t}})}config(t,n){return new e({...this.schema,configSettings:{appName:t,loaders:n}})}configLoader(n){if(this.schema.configSettings===void 0)throw new t(`.configLoader() requires .config() to be called first`,{code:`INVALID_BUILDER_STATE`,suggest:`Call .config(appName) before .configLoader()`});let r=this.schema.configSettings.loaders??[];return new e({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...r,n]}})}manifest(t){return new e(B(this.schema,t,L,!1))}packageJson(t){return new e(B(this.schema,t,L,!0))}denoJson(t){return new e(B(this.schema,t,R,!0))}command(t){return D(this.schema.commands,t.schema,this.schema.defaultCommand),this.schema.completionsFlag!==void 0&&w(t.schema),new e({...this.schema,commands:[...this.schema.commands,O(t)]})}default(n){if(this.schema.defaultCommand!==void 0)throw new t(`Only one default command is allowed`,{code:`DUPLICATE_DEFAULT`,suggest:`Call .default() only once when building the CLI`});D(this.schema.commands,n.schema),this.schema.completionsFlag!==void 0&&w(n.schema);let r=O(n);return new e({...this.schema,defaultCommand:r})}plugin(t){return new e({...this.schema,plugins:[...this.schema.plugins,t]})}completions(r){if(this.schema.hasBuiltInCompletions)throw new t(`.completions() has already been called`,{code:`DUPLICATE_COMMAND`,suggest:`Call .completions() only once when building the CLI`});if(r?.as===`flag`){this.schema.defaultCommand!==void 0&&w(this.schema.defaultCommand.schema);for(let e of this.schema.commands)w(e.schema);return new e({...this.schema,hasBuiltInCompletions:!0,completionsFlag:{shells:n,options:r}})}let o=this.schema,s=r,c=d(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,u.custom(e=>{let t=a(e);if(t===void 0)throw Error(`Unknown shell '${e}'. Valid shells: ${n.join(`, `)}`);return t}).env(`SHELL`).describe(`Target shell (${n.join(`, `)})`)).action(({args:e,meta:t,out:n})=>{let r=i(t.bin===o.name?o:{...o,name:t.bin},e.shell,s);n.jsonMode?n.json({shell:e.shell,script:r}):n.log(r)});return new e({...this.command(c).schema,hasBuiltInCompletions:!0})}async execute(e,n){let a=f(e,`--json`)||n?.jsonMode===!0,l={...n?.verbosity===void 0?{}:{verbosity:n.verbosity},...a?{jsonMode:a}:{},...n?.isTTY===void 0?{}:{isTTY:n.isTTY}},u,d;n?.out===void 0?[u,d]=c(Object.keys(l).length>0?l:void 0):(u=n.out,d=n.captured??{stdout:[],stderr:[],activity:[]}),s(u);let h={...this.schema.helpConfig,...n?.help,binName:n?.help?.binName??this.schema.name,hyperlinks:n?.help?.hyperlinks??this.schema.helpConfig?.hyperlinks??u.isTTY},g={...n,plugins:this.schema.plugins,...a?{jsonMode:a}:{}},_={jsonMode:a,isTTY:u.isTTY,verbosity:n?.verbosity??`normal`},v=y({schema:this.schema,argv:e,help:h,output:_});switch(v.kind){case`root-version`:return u.log(v.version),p({exitCode:0,error:void 0},d);case`root-completions`:{let e=v.shell??r(n?.env??{});if(e===void 0){let e=new t(`Could not detect shell`,{code:`MISSING_VALUE`,suggest:`Pass one explicitly, e.g. '${h.binName} --completions zsh'`});return a?u.json({error:e.toJSON()}):(u.error(e.message),u.error(`Suggestion: ${e.suggest}`)),p({exitCode:e.exitCode,error:e},d)}let o=i(h.binName===void 0||h.binName===this.schema.name?this.schema:{...this.schema,name:h.binName},e,v.options);return a?u.json({shell:e,script:o}):u.log(o),p({exitCode:0,error:void 0},d)}case`root-help`:{let e=b(I(this.schema),v.help);return u.log(e),p({exitCode:0,error:void 0},d)}case`dispatch-error`:return a?u.json({error:v.error.toJSON()}):(u.error(v.error.message),v.error.suggest!==void 0&&v.error.code!==`NO_ACTION`&&u.error(`Suggestion: ${v.error.suggest}`)),p({exitCode:v.error.exitCode,error:v.error},d);case`needs-subcommand`:{let e=o(v.command.schema,v.help);return u.log(e),p({exitCode:0,error:void 0},d)}case`match`:{let e=k(g,v.plan.help??h,v.plan.meta);return v.plan.command._command===void 0?v.plan.command._execute(v.plan.argv,{...e,mergedSchema:v.plan.mergedSchema}):p(await m({command:v.plan.command._command,argv:v.plan.argv,out:u,schema:v.plan.mergedSchema,meta:v.plan.meta,options:e}),d)}}}async run(t){let n=t?.adapter??_(),r=this.schema.inheritName?P(n.argv):void 0,i=await x({schema:this.schema,adapter:n,options:t,inheritedName:r});if(i.kind===`config-error`)return i.jsonMode?n.stdout(`${JSON.stringify({error:i.error.toJSON()})}\n`):(n.stderr(`Error: ${i.error.message}\n`),i.error.suggest!==void 0&&n.stderr(`Suggestion: ${i.error.suggest}\n`)),n.exit(i.error.exitCode);let a=i.schema===this.schema?this:new e(i.schema),o={...t,...i.inputs,out:l({stdout:n.stdout,stderr:n.stderr,jsonMode:i.inputs.jsonMode,isTTY:i.inputs.isTTY,...i.inputs.verbosity===`normal`?{}:{verbosity:i.inputs.verbosity}})},s=await a.execute(i.filteredArgv,o);for(let e of s.stdout)n.stdout(e);for(let e of s.stderr)n.stderr(e);return n.exit(s.exitCode)}};const j=new Set([`bun`,`deno`,`node`,`tsx`]);function M(e){let t=g(e,[47,92]);if(t.length===0)return;let n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`)),r=n>=0?t.slice(n+1):t;return r.length>0?r:void 0}function N(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return j.has(t)}function P(e){let t=e[0],n=e[1],r=t===void 0?void 0:M(t);if(r!==void 0&&N(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:M(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:M(n)}return t===void 0?void 0:M(t)}function F(e){if(e!==void 0)return e instanceof URL?e.href:e}function I(e){return e.helpLinks===void 0?e:{...e,helpLinks:v(e.helpLinks,e.packageJsonSettings?.data,e.version)}}const L=[`package.json`],R=[`deno.json`,`deno.jsonc`,`jsr.json`];function z(e){return e===void 0||e===!1?{inferName:!1,stripScope:!0}:e===!0?{inferName:!0,stripScope:!0}:{inferName:!0,stripScope:e.scope!==`keep`}}function B(e,t,n,r){if(H(t))return{...e,...e.version===void 0&&t.version!==void 0?{version:t.version}:{},...e.description===void 0&&t.description!==void 0?{description:t.description}:{},packageJsonSettings:{inferName:!1,stripScope:!0,from:void 0,files:n,data:t}};let{inferName:i,stripScope:a}=z(t?.inferName),o=r?n:t?.files??n;return{...e,packageJsonSettings:{inferName:i,stripScope:a,from:V(t?.from),files:o,data:void 0}}}function V(e){if(e===void 0)return;if(e instanceof URL){if(e.protocol!==`file:`)return e.href}else if(!e.startsWith(`file:`))return e;let t=decodeURIComponent(new URL(e).pathname);return/^\/[A-Za-z]:/.test(t)?t.slice(1).replace(/\//g,`\\`):t}function H(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:`name`in e||`version`in e||`description`in e||`bin`in e||`homepage`in e||`repository`in e}function U(e){return new A({name:typeof e==`string`?e:e.name??`cli`,inheritName:typeof e==`string`?!1:e.inherit??!1,version:void 0,description:void 0,commands:[],defaultCommand:void 0,configSettings:void 0,packageJsonSettings:void 0,helpLinks:void 0,hasBuiltInCompletions:!1,completionsFlag:void 0,helpConfig:void 0,plugins:[]})}export{A as CLIBuilder,U as cli};
@@ -3,6 +3,8 @@ import { CLIPlugin } from "./plugin.mjs";
3
3
  import { CLIError } from "../errors/index.mjs";
4
4
  import { HelpOptions } from "../help/index.mjs";
5
5
  import { CommandMeta, CommandSchema, ErasedCommand } from "../schema/command.mjs";
6
+ import { CompletionOptions } from "../completion/shells/shared.mjs";
7
+ import { Shell } from "../completion/index.mjs";
6
8
 
7
9
  //#region src/core/cli/planner.d.ts
8
10
  /**
@@ -21,6 +23,14 @@ interface PlannerSchemaLike {
21
23
  readonly commands: readonly ErasedCommand[];
22
24
  /** Fallback command when no subcommand token matches. */
23
25
  readonly defaultCommand: ErasedCommand | undefined;
26
+ /**
27
+ * Eager `--completions <shell>` flag configuration, when `.completions()`
28
+ * was registered with `{ as: 'flag' }`. `undefined` disables interception.
29
+ */
30
+ readonly completionsFlag: {
31
+ readonly shells: readonly Shell[];
32
+ readonly options: CompletionOptions | undefined;
33
+ } | undefined;
24
34
  /** Plugins forwarded into every matched execution plan. */
25
35
  readonly plugins: readonly CLIPlugin[];
26
36
  }
@@ -38,6 +48,18 @@ interface RootVersionOutcome {
38
48
  /** Resolved version string to render. */
39
49
  readonly version: string;
40
50
  }
51
+ /** Root-level `--completions [shell]` interception outcome. */
52
+ interface RootCompletionsOutcome {
53
+ /** Discriminant — argv matched the eager `--completions [shell]` flag. */
54
+ readonly kind: 'root-completions';
55
+ /**
56
+ * Resolved, validated target shell, or `undefined` when the flag was given
57
+ * without a value and the shell should be auto-detected from the environment.
58
+ */
59
+ readonly shell: Shell | undefined;
60
+ /** Generator options captured at build time. */
61
+ readonly options: CompletionOptions | undefined;
62
+ }
41
63
  /** CLI-level dispatch failure before command execution starts. */
42
64
  interface DispatchErrorOutcome {
43
65
  /** Discriminant — dispatch could not resolve a command from argv. */
@@ -58,7 +80,7 @@ interface PlannerMatchOutcome {
58
80
  * `CLIBuilder.execute()` still renders and executes these outcomes, but
59
81
  * planning itself is intentionally bounded to this union.
60
82
  */
61
- type DispatchOutcome = RootHelpOutcome | RootVersionOutcome | DispatchErrorOutcome | PlannerMatchOutcome;
83
+ type DispatchOutcome = RootHelpOutcome | RootVersionOutcome | RootCompletionsOutcome | DispatchErrorOutcome | PlannerMatchOutcome;
62
84
  /**
63
85
  * Concrete execution handoff produced by a successful planner match.
64
86
  *
@@ -133,11 +155,11 @@ declare function buildCommandExecutionPlan(options: BuildCommandExecutionPlanOpt
133
155
  /**
134
156
  * Decide what to do with an argv invocation before any command executes.
135
157
  *
136
- * Handles root interception (`--help`, `--version`, bare `help` token),
137
- * dispatches into the command tree, falls back to the default command, and
138
- * produces structured errors for unknown commands/flags.
158
+ * Handles root interception (`--help`, `--version`, `--completions <shell>`,
159
+ * bare `help` token), dispatches into the command tree, falls back to the
160
+ * default command, and produces structured errors for unknown commands/flags.
139
161
  * @internal
140
162
  */
141
163
  declare function planInvocation(options: PlanInvocationOptions): InvocationPlan;
142
164
  //#endregion
143
- export { type CommandExecutionPlan, type DispatchErrorOutcome, type DispatchOutcome, type InvocationPlan, type NeedsSubcommandOutcome, type OutputPolicy, type PlanInvocationOptions, type PlannerMatchOutcome, type PlannerSchemaLike, type RootHelpOutcome, type RootVersionOutcome, buildCommandExecutionPlan, buildRootCommandMap, mergeCommandSchema, planInvocation };
165
+ export { type CommandExecutionPlan, type DispatchErrorOutcome, type DispatchOutcome, type InvocationPlan, type NeedsSubcommandOutcome, type OutputPolicy, type PlanInvocationOptions, type PlannerMatchOutcome, type PlannerSchemaLike, type RootCompletionsOutcome, type RootHelpOutcome, type RootVersionOutcome, buildCommandExecutionPlan, buildRootCommandMap, mergeCommandSchema, planInvocation };