@kjanat/dreamcli 3.0.1 → 4.0.0-rc.2

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 (137) hide show
  1. package/CHANGELOG.md +962 -1
  2. package/README.md +7 -3
  3. package/dist/core/cli/builtins.d.mts +47 -0
  4. package/dist/core/cli/builtins.mjs +135 -0
  5. package/dist/core/cli/compiled.d.mts +29 -0
  6. package/dist/core/cli/compiled.mjs +76 -0
  7. package/dist/core/cli/dispatch.d.mts +9 -85
  8. package/dist/core/cli/help-links.d.mts +2 -14
  9. package/dist/core/cli/index.d.mts +282 -101
  10. package/dist/core/cli/index.mjs +497 -264
  11. package/dist/core/cli/planner.d.mts +13 -86
  12. package/dist/core/cli/planner.mjs +47 -30
  13. package/dist/core/cli/plugin.d.mts +1 -1
  14. package/dist/core/cli/propagate.mjs +1 -1
  15. package/dist/core/cli/reserved-flags.d.mts +1 -0
  16. package/dist/core/cli/reserved-flags.mjs +158 -0
  17. package/dist/core/cli/root-help.d.mts +1 -47
  18. package/dist/core/cli/root-help.mjs +37 -47
  19. package/dist/core/cli/root-output-flags.d.mts +1 -0
  20. package/dist/core/cli/root-output-flags.mjs +169 -0
  21. package/dist/core/cli/root-surface.d.mts +1 -68
  22. package/dist/core/cli/root-surface.mjs +2 -2
  23. package/dist/core/cli/runtime-preflight.d.mts +1 -199
  24. package/dist/core/cli/runtime-preflight.mjs +67 -17
  25. package/dist/core/completion/index.d.mts +2 -2
  26. package/dist/core/completion/shells/bash.d.mts +0 -1
  27. package/dist/core/completion/shells/bash.mjs +2 -1
  28. package/dist/core/completion/shells/fish.d.mts +0 -1
  29. package/dist/core/completion/shells/fish.mjs +2 -1
  30. package/dist/core/completion/shells/powershell.d.mts +0 -1
  31. package/dist/core/completion/shells/powershell.mjs +2 -1
  32. package/dist/core/completion/shells/shared.d.mts +3 -114
  33. package/dist/core/completion/shells/shared.mjs +9 -39
  34. package/dist/core/completion/shells/zsh.d.mts +0 -1
  35. package/dist/core/completion/shells/zsh.mjs +2 -1
  36. package/dist/core/config/index.d.mts +3 -3
  37. package/dist/core/config/index.mjs +2 -2
  38. package/dist/core/config/package-json.d.mts +2 -33
  39. package/dist/core/config/package-json.mjs +1 -34
  40. package/dist/core/errors/index.d.mts +7 -7
  41. package/dist/core/execution/index.d.mts +1 -48
  42. package/dist/core/execution/index.mjs +42 -27
  43. package/dist/core/help/ansi.d.mts +0 -11
  44. package/dist/core/help/index.d.mts +3 -35
  45. package/dist/core/help/index.mjs +29 -6
  46. package/dist/core/help/theme.d.mts +1 -21
  47. package/dist/core/json-schema/index.d.mts +279 -10
  48. package/dist/core/json-schema/index.mjs +482 -237
  49. package/dist/core/json-schema/meta-descriptions.generated.d.mts +79 -7
  50. package/dist/core/json-schema/meta-descriptions.generated.mjs +40 -6
  51. package/dist/core/output/activity.d.mts +1 -193
  52. package/dist/core/output/activity.mjs +1 -1
  53. package/dist/core/output/bind.d.mts +1 -37
  54. package/dist/core/output/contracts.d.mts +7 -13
  55. package/dist/core/output/contracts.mjs +1 -1
  56. package/dist/core/output/display-value.d.mts +1 -19
  57. package/dist/core/output/index.d.mts +5 -187
  58. package/dist/core/output/index.mjs +44 -9
  59. package/dist/core/output/renderers.d.mts +1 -45
  60. package/dist/core/output/writer.d.mts +0 -1
  61. package/dist/core/parse/index.d.mts +27 -5
  62. package/dist/core/parse/index.mjs +350 -227
  63. package/dist/core/parse/occurrences.d.mts +89 -0
  64. package/dist/core/parse/occurrences.mjs +114 -0
  65. package/dist/core/prompt/index.d.mts +3 -3
  66. package/dist/core/read-flags/index.d.mts +150 -0
  67. package/dist/core/read-flags/index.mjs +217 -0
  68. package/dist/core/resolve/args.d.mts +35 -4
  69. package/dist/core/resolve/args.mjs +132 -55
  70. package/dist/core/resolve/coerce.d.mts +66 -9
  71. package/dist/core/resolve/coerce.mjs +834 -270
  72. package/dist/core/resolve/config.d.mts +1 -10
  73. package/dist/core/resolve/contracts.d.mts +67 -44
  74. package/dist/core/resolve/errors.mjs +29 -21
  75. package/dist/core/resolve/flags.d.mts +36 -9
  76. package/dist/core/resolve/flags.mjs +129 -151
  77. package/dist/core/resolve/index.d.mts +8 -6
  78. package/dist/core/resolve/index.mjs +51 -18
  79. package/dist/core/resolve/path-checks.d.mts +47 -0
  80. package/dist/core/resolve/path-checks.mjs +102 -0
  81. package/dist/core/resolve/redaction.d.mts +12 -0
  82. package/dist/core/resolve/redaction.mjs +14 -0
  83. package/dist/core/resolve/stages.d.mts +85 -0
  84. package/dist/core/resolve/stages.mjs +170 -0
  85. package/dist/core/resolve/standard.d.mts +1 -24
  86. package/dist/core/resolve/standard.mjs +141 -43
  87. package/dist/core/schema/activity.d.mts +16 -16
  88. package/dist/core/schema/arg.d.mts +849 -71
  89. package/dist/core/schema/arg.mjs +727 -54
  90. package/dist/core/schema/brand.d.mts +17 -0
  91. package/dist/core/schema/cardinality.d.mts +301 -0
  92. package/dist/core/schema/cardinality.mjs +514 -0
  93. package/dist/core/schema/command.d.mts +173 -119
  94. package/dist/core/schema/command.mjs +305 -42
  95. package/dist/core/schema/flag.d.mts +515 -173
  96. package/dist/core/schema/flag.mjs +576 -78
  97. package/dist/core/schema/index.d.mts +11 -8
  98. package/dist/core/schema/index.mjs +10 -0
  99. package/dist/core/schema/middleware.d.mts +15 -12
  100. package/dist/core/schema/number-constraints.d.mts +5 -5
  101. package/dist/core/schema/prompt.d.mts +4 -4
  102. package/dist/core/schema/provenance.d.mts +99 -0
  103. package/dist/core/schema/provenance.mjs +28 -0
  104. package/dist/core/schema/run.d.mts +21 -60
  105. package/dist/core/schema/source.d.mts +179 -0
  106. package/dist/core/schema/source.mjs +206 -0
  107. package/dist/core/schema/standard.d.mts +12 -19
  108. package/dist/core/schema/stdin.d.mts +87 -0
  109. package/dist/core/schema/stdin.mjs +91 -0
  110. package/dist/core/schema/string-constraints.d.mts +16 -5
  111. package/dist/core/schema/string-constraints.mjs +18 -1
  112. package/dist/core/schema/value-parsers.d.mts +81 -9
  113. package/dist/core/schema/value-parsers.mjs +19 -1
  114. package/dist/core/schema/value.d.mts +242 -0
  115. package/dist/core/schema/value.mjs +573 -0
  116. package/dist/core/testkit/index.d.mts +30 -3
  117. package/dist/core/testkit/index.mjs +40 -26
  118. package/dist/index.d.mts +21 -16
  119. package/dist/index.mjs +10 -6
  120. package/dist/runtime/adapter.d.mts +3 -3
  121. package/dist/runtime/deno.d.mts +3 -3
  122. package/dist/runtime/detect.d.mts +2 -2
  123. package/dist/runtime/node.d.mts +3 -3
  124. package/dist/runtime/paths.d.mts +1 -31
  125. package/dist/runtime.d.mts +4 -4
  126. package/dist/strings.d.mts +1 -16
  127. package/dist/testkit.d.mts +2 -2
  128. package/dist/testkit.mjs +1 -1
  129. package/dist/version.d.mts +0 -13
  130. package/dist/version.mjs +2 -2
  131. package/dreamcli.schema.json +368 -78
  132. package/examples/interactive.ts +6 -5
  133. package/package.json +12 -11
  134. package/skills/cli-creation/SKILL.md +72 -16
  135. package/skills/cli-creation/references/pattern-cookbook.md +169 -11
  136. package/dist/core/resolve/property.d.mts +0 -51
  137. package/dist/core/resolve/property.mjs +0 -53
@@ -1,19 +1,21 @@
1
1
  import { CLIError } from "../errors/index.mjs";
2
- import { getFlagAliasNames } from "../schema/flag.mjs";
2
+ import { getFlagAliasNames, getFlagNegatedName } from "../schema/flag.mjs";
3
3
  import { arg } from "../schema/arg.mjs";
4
- import { command } from "../schema/command.mjs";
5
- import { includesBeforeSeparator } from "../parse/index.mjs";
4
+ import { command, createCommandSchema } from "../schema/command.mjs";
5
+ import { normalizeBuiltins } from "./builtins.mjs";
6
6
  import { SHELLS, detectShell, generateCompletion, normalizeShell } from "../completion/index.mjs";
7
7
  import { formatHelp } from "../help/index.mjs";
8
8
  import { generateCommandSchema, generateSchema } from "../json-schema/index.mjs";
9
9
  import { clearRequestedExitCode, createCaptureOutput, createOutput, resolveHyperlinkOverride } from "../output/index.mjs";
10
10
  import { buildRunResult, executeCommand } from "../execution/index.mjs";
11
- import { runCommand } from "../testkit/index.mjs";
12
11
  import { stripTrailing } from "../../strings.mjs";
13
12
  import { createAdapter } from "../../runtime/auto.mjs";
13
+ import { assertNoSiblingRouteConflict, commandRoutes, compileCommand } from "./compiled.mjs";
14
14
  import { deriveHelpLinks } from "./help-links.mjs";
15
+ import { readRootOutputFlags, resolveRootJsonMode, resolveRootVerbosity } from "./root-output-flags.mjs";
15
16
  import { planInvocation } from "./planner.mjs";
16
17
  import { plugin } from "./plugin.mjs";
18
+ import { assertNoReservedFlagCollisions } from "./reserved-flags.mjs";
17
19
  import { formatRootHelp } from "./root-help.mjs";
18
20
  import { prepareRuntimePreflight } from "./runtime-preflight.mjs";
19
21
  //#region src/core/cli/index.ts
@@ -21,16 +23,20 @@ import { prepareRuntimePreflight } from "./runtime-preflight.mjs";
21
23
  const COMPLETIONS_FLAG_NAME = "completions";
22
24
  /**
23
25
  * Whether a command — or any of its nested subcommands — declares a flag that
24
- * collides with the eager `--completions` flag, by canonical name or long alias.
26
+ * collides with the eager `--completions` flag, by canonical name, long alias,
27
+ * or negated spelling.
25
28
  *
26
29
  * @internal
27
30
  */
28
31
  function commandReservesCompletionsFlag(schema) {
29
32
  if (Object.hasOwn(schema.flags, COMPLETIONS_FLAG_NAME)) return true;
30
- for (const flagSchema of Object.values(schema.flags)) if (getFlagAliasNames(flagSchema, {
31
- kind: "long",
32
- includeHidden: true
33
- }).includes(COMPLETIONS_FLAG_NAME)) return true;
33
+ for (const [flagName, flagSchema] of Object.entries(schema.flags)) {
34
+ if (getFlagAliasNames(flagSchema, {
35
+ kind: "long",
36
+ includeHidden: true
37
+ }).includes(COMPLETIONS_FLAG_NAME)) return true;
38
+ if (getFlagNegatedName(flagName, flagSchema) === COMPLETIONS_FLAG_NAME) return true;
39
+ }
34
40
  return schema.commands.some(commandReservesCompletionsFlag);
35
41
  }
36
42
  /**
@@ -46,21 +52,10 @@ function assertNoCompletionsFlagCollision(schema) {
46
52
  suggest: `Rename the flag, or register completions as a subcommand with .completions() instead of { as: 'flag' }`
47
53
  });
48
54
  }
49
- function commandRoutes(schema) {
50
- return [schema.name, ...schema.aliases];
51
- }
52
- function assertNoSiblingRouteConflict(parentCommandName, routeOwners, route, commandName) {
53
- const owner = routeOwners.get(route);
54
- if (owner !== void 0) throw new CLIError(`Duplicate command route '${route}' under '${parentCommandName}' (${owner} and ${commandName})`, {
55
- code: "DUPLICATE_COMMAND",
56
- suggest: "Ensure sibling command names and aliases are unique"
57
- });
58
- routeOwners.set(route, commandName);
59
- }
60
55
  function assertNoTopLevelRouteConflict(commands, incoming, defaultCommand) {
61
56
  const routeOwners = /* @__PURE__ */ new Map();
62
57
  const existing = defaultCommand !== void 0 ? [...commands, defaultCommand] : commands;
63
- for (const command of existing) for (const route of commandRoutes(command.schema)) assertNoSiblingRouteConflict("root", routeOwners, route, command.schema.name);
58
+ for (const registered of existing) for (const route of commandRoutes(registered)) assertNoSiblingRouteConflict("root", routeOwners, route, registered.name);
64
59
  for (const route of commandRoutes(incoming)) {
65
60
  const owner = routeOwners.get(route);
66
61
  if (owner !== void 0) throw new CLIError(`Command route '${route}' is already registered by '${owner}'`, {
@@ -71,35 +66,169 @@ function assertNoTopLevelRouteConflict(commands, incoming, defaultCommand) {
71
66
  }
72
67
  }
73
68
  /**
74
- * Erase a typed {@linkcode CommandBuilder} into an {@linkcode ErasedCommand}, recursively
75
- * building the subcommand tree.
69
+ * Compiled execution graph per builder instance.
76
70
  *
77
- * The closure captures the fully-typed builder, so {@linkcode runCommand()} receives
78
- * the original `CommandBuilder<F, A>` — no type assertions needed.\
79
- * Subcommands are recursively erased and indexed by name and alias for
80
- * O(1) lookup during dispatch.
71
+ * Keyed weakly so handlers and execution steps stay off the public schema and
72
+ * out of the emitted declarations.
81
73
  *
82
74
  * @internal
83
75
  */
84
- function eraseCommand(cmd) {
85
- const subcommands = /* @__PURE__ */ new Map();
86
- const routeOwners = /* @__PURE__ */ new Map();
87
- for (const sub of cmd._subcommands) {
88
- const routes = commandRoutes(sub.schema);
89
- for (const route of routes) assertNoSiblingRouteConflict(cmd.schema.name, routeOwners, route, sub.schema.name);
90
- const erased = eraseCommand(sub);
91
- for (const route of routes) subcommands.set(route, erased);
76
+ const compiledStates = /* @__PURE__ */ new WeakMap();
77
+ /**
78
+ * Read the compiled state seeded by {@linkcode CLIBuilder._from}.
79
+ *
80
+ * @param builder - Builder to look up.
81
+ * @returns Its compiled execution graph.
82
+ * @throws {@linkcode CLIError} `INVALID_BUILDER_STATE` when the builder was not created by `cli()`.
83
+ *
84
+ * @internal
85
+ */
86
+ function compiledStateOf(builder) {
87
+ const compiled = compiledStates.get(builder);
88
+ if (compiled === void 0) throw new CLIError("CLI builder carries no compiled command graph", {
89
+ code: "INVALID_BUILDER_STATE",
90
+ suggest: "Create CLI builders with cli()"
91
+ });
92
+ return compiled;
93
+ }
94
+ /**
95
+ * Build the next builder in a chain, carrying the current compiled state.
96
+ *
97
+ * @param builder - Builder the chained call was made on.
98
+ * @param schema - Schema for the new builder.
99
+ * @returns The new builder.
100
+ *
101
+ * @internal
102
+ */
103
+ function rebuild(builder, schema) {
104
+ return CLIBuilder._from(schema, compiledStateOf(builder));
105
+ }
106
+ /**
107
+ * Apply the type-only seal to a fully populated CLI schema draft.
108
+ *
109
+ * The brand has no runtime value, so this is the single construction path for
110
+ * {@link CLISchema}, {@link ConfigSettings}, and {@link Builtins} values in
111
+ * this module.
112
+ *
113
+ * @param draft - Draft carrying every schema field.
114
+ * @returns The sealed schema.
115
+ *
116
+ * @internal
117
+ */
118
+ function sealCLISchema(draft) {
119
+ return draft;
120
+ }
121
+ /**
122
+ * Merge definition fields onto the {@link CLISchema} defaults.
123
+ *
124
+ * @param definition - CLI definition with the name already validated.
125
+ * @returns A fully populated {@link CLISchema}.
126
+ *
127
+ * @internal
128
+ */
129
+ function buildCLISchema(definition) {
130
+ const configSettings = definition.configSettings;
131
+ return sealCLISchema({
132
+ name: definition.name,
133
+ inheritName: definition.inheritName ?? false,
134
+ version: definition.version,
135
+ description: definition.description,
136
+ commands: (definition.commands ?? []).map((child) => createCommandSchema(child)),
137
+ defaultCommand: definition.defaultCommand !== void 0 ? createCommandSchema(definition.defaultCommand) : void 0,
138
+ defaultCommandRouted: definition.defaultCommandRouted ?? false,
139
+ configSettings: configSettings !== void 0 ? {
140
+ appName: configSettings.appName,
141
+ loaders: configSettings.loaders
142
+ } : void 0,
143
+ packageJsonSettings: definition.packageJsonSettings,
144
+ helpLinks: definition.helpLinks,
145
+ hasBuiltInCompletions: definition.hasBuiltInCompletions ?? false,
146
+ completionsFlag: definition.completionsFlag,
147
+ helpConfig: definition.helpConfig,
148
+ flagSettings: definition.flagSettings,
149
+ builtins: normalizeBuiltins(definition.builtins)
150
+ });
151
+ }
152
+ /**
153
+ * Create a {@link CLISchema} from a plain definition object.
154
+ *
155
+ * Most consumers should prefer {@link cli | cli()}, which returns a
156
+ * {@link CLIBuilder} carrying the execution graph. `createCLISchema()` builds a
157
+ * description only: it normalizes commands recursively through
158
+ * {@link createCommandSchema}, so handlers and execution steps are not part of
159
+ * the result and the schema cannot be executed.
160
+ *
161
+ * Feeding a built schema back in produces a deep-equal schema.
162
+ *
163
+ * @param definition - Program name plus optional metadata and commands.
164
+ * @returns A fully populated {@link CLISchema}.
165
+ * @throws {CLIError} With code `'INVALID_SCHEMA'` when the program name is
166
+ * empty, a `builtins` entry is neither `'on'` nor `'off'`, a command name at
167
+ * any depth is empty, a flag or arg at any depth is named `__proto__`, or a
168
+ * flag record at any depth has a replaced prototype.
169
+ * @throws {CLIError} With code `'FLAG_NAME_COLLISION'` when two flags on one
170
+ * command share a spelling, at any depth of the command tree.
171
+ * @throws {CLIError} With code `'PROPAGATED_FLAG_COLLISION'` when a command flag
172
+ * shadows a spelling propagated from an ancestor command.
173
+ * @throws {CLIError} With code `'INVALID_BUILDER_STATE'` when a positional comes
174
+ * after a variadic one, or `'DUPLICATE_STDIN_INPUT'` when two inputs on one
175
+ * command consume stdin and either is exclusive.
176
+ * @throws {CLIError} With code `'RESERVED_FLAG'` when a command spells a flag
177
+ * the same way as a root-owned flag (`--json`, `--quiet`/`-q`, `--help`/`-h`,
178
+ * `--version`/`-V` once `version` is set, and `--completions` once
179
+ * `completionsFlag` is set), by name, alias, or negated spelling. A built-in
180
+ * set to `'off'` in `builtins` is not reserved.
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * const schema = createCLISchema({
185
+ * name: 'mycli',
186
+ * version: '1.0.0',
187
+ * commands: [{ name: 'deploy', flags: { force: { kind: 'boolean' } } }],
188
+ * });
189
+ * ```
190
+ */
191
+ function createCLISchema(definition) {
192
+ if (definition.name === "") throw new CLIError("CLI schema requires a non-empty name", {
193
+ code: "INVALID_SCHEMA",
194
+ details: { name: definition.name },
195
+ suggest: "Pass a program name such as { name: \"mycli\" }"
196
+ });
197
+ const schema = buildCLISchema(definition);
198
+ const registered = [];
199
+ for (const commandSchema of schema.commands) {
200
+ assertNoTopLevelRouteConflict(registered, commandSchema);
201
+ registered.push(commandSchema);
92
202
  }
93
- return {
94
- schema: cmd.schema,
95
- subcommands,
96
- _command: cmd,
97
- _execute(argv, options) {
98
- return runCommand(cmd, argv, options);
99
- }
100
- };
203
+ const defaultIsRegisteredCommand = definition.defaultCommand !== void 0 && definition.commands?.includes(definition.defaultCommand) === true;
204
+ if (schema.defaultCommand !== void 0 && !defaultIsRegisteredCommand) assertNoTopLevelRouteConflict(registered, schema.defaultCommand);
205
+ const allCommands = [schema.defaultCommand, ...schema.commands];
206
+ assertNoReservedFlagCollisions(schema.version, allCommands, schema.builtins);
207
+ if (schema.completionsFlag !== void 0) {
208
+ for (const cmd of allCommands) if (cmd !== void 0) assertNoCompletionsFlagCollision(cmd);
209
+ }
210
+ return schema;
101
211
  }
102
212
  /**
213
+ * Concrete {@linkcode RenderContext} carrying the resolved output decisions.
214
+ *
215
+ * @internal
216
+ */
217
+ var ResolvedRenderContext = class {
218
+ jsonMode;
219
+ verbosity;
220
+ isTTY;
221
+ color;
222
+ isHyperlinkSupported;
223
+ constructor(out) {
224
+ this.jsonMode = out.jsonMode;
225
+ this.verbosity = out.verbosity;
226
+ this.isTTY = out.isTTY;
227
+ this.color = out.color;
228
+ this.isHyperlinkSupported = out.isHyperlinkSupported;
229
+ }
230
+ };
231
+ /**
103
232
  * Resolve the render context for content built before `.run()`.
104
233
  *
105
234
  * Content styled ahead of execution — hand-rendered banners, custom help, or
@@ -125,18 +254,16 @@ function eraseCommand(cmd) {
125
254
  * ```
126
255
  */
127
256
  function resolveRenderContext(argv, options) {
128
- const out = createOutput({
129
- jsonMode: includesBeforeSeparator(argv, "--json") || options?.jsonMode === true,
257
+ const rootOutputFlags = readRootOutputFlags(argv, options?.builtins);
258
+ const jsonMode = resolveRootJsonMode(rootOutputFlags, options?.jsonMode);
259
+ const verbosity = resolveRootVerbosity(rootOutputFlags, options?.verbosity) ?? "normal";
260
+ return new ResolvedRenderContext(createOutput({
261
+ jsonMode,
130
262
  isTTY: options?.isTTY ?? false,
263
+ verbosity,
131
264
  ...options?.color !== void 0 ? { color: options.color } : {},
132
265
  ...hyperlinksOption(resolveHyperlinkOverride(options?.env ?? {}, argv))
133
- });
134
- return {
135
- jsonMode: out.jsonMode,
136
- isTTY: out.isTTY,
137
- color: out.color,
138
- isHyperlinkSupported: out.isHyperlinkSupported
139
- };
266
+ }));
140
267
  }
141
268
  /**
142
269
  * Conditional-spread wrapper for the output channel's `hyperlinks` option:
@@ -149,13 +276,13 @@ function hyperlinksOption(override) {
149
276
  return override !== void 0 ? { hyperlinks: override } : {};
150
277
  }
151
278
  /**
152
- * Build {@linkcode RunOptions} from {@linkcode CLIRunOptions}, conditionally spreading each
279
+ * Build {@linkcode RunOptions} from {@linkcode CLIExecuteOptions}, conditionally spreading each
153
280
  * field to satisfy `exactOptionalPropertyTypes`.
154
281
  *
155
282
  * @param options - CLI-level run options (may be `undefined` for defaults).
156
283
  * @param helpOptions - Help formatting options forwarded to commands.
157
284
  * @param meta - Optional command metadata (omitted for root-level dispatch).
158
- * @returns Options record ready for {@linkcode ErasedCommand._execute | ErasedCommand._execute()}.
285
+ * @returns Options record ready for the shared executor.
159
286
  *
160
287
  * @internal
161
288
  */
@@ -164,6 +291,7 @@ function buildCommandRunOptions(options, helpOptions, meta) {
164
291
  help: helpOptions,
165
292
  ...meta !== void 0 ? { meta } : {},
166
293
  ...options?.plugins !== void 0 ? { plugins: options.plugins } : {},
294
+ ...options?.builtins !== void 0 ? { builtins: options.builtins } : {},
167
295
  ...options?.env !== void 0 ? { env: options.env } : {},
168
296
  ...options?.config !== void 0 ? { config: options.config } : {},
169
297
  ...options?.stdinData !== void 0 ? { stdinData: options.stdinData } : {},
@@ -209,30 +337,105 @@ function buildCommandRunOptions(options, helpOptions, meta) {
209
337
  var CLIBuilder = class CLIBuilder {
210
338
  /** @internal Runtime schema descriptor. */
211
339
  schema;
212
- /** Build a CLIBuilder from a pre-constructed schema descriptor. */
213
340
  constructor(schema) {
214
341
  this.schema = schema;
215
342
  }
216
343
  /**
344
+ * Build a CLI builder around a schema and its compiled execution graph.
345
+ *
346
+ * @param schema - Runtime schema descriptor.
347
+ * @param compiled - Compiled commands, default command, and plugins.
348
+ * @returns The builder, with its compiled state registered.
349
+ *
350
+ * @internal
351
+ */
352
+ static _from(schema, compiled) {
353
+ const builder = new CLIBuilder(schema);
354
+ compiledStates.set(builder, compiled);
355
+ return builder;
356
+ }
357
+ /**
217
358
  * Set the program version (shown by `--version`).
218
359
  *
360
+ * Declaring a version also reserves `--version`/`-V` on every registered
361
+ * command, so this rejects a command that already declares either spelling.
362
+ *
219
363
  * @param v - Semantic version string.
220
364
  * @returns The builder (for chaining).
365
+ * @throws {@link CLIError} `RESERVED_FLAG` when a registered command spells
366
+ * `--version` or `-V` as a flag name, an alias, or a negated spelling.
221
367
  */
222
368
  version(v) {
223
- return new CLIBuilder({
369
+ assertNoReservedFlagCollisions(v, [this.schema.defaultCommand, ...this.schema.commands], this.schema.builtins);
370
+ return rebuild(this, {
224
371
  ...this.schema,
225
372
  version: v
226
373
  });
227
374
  }
228
375
  /**
376
+ * Choose which built-in flags the root keeps.
377
+ *
378
+ * `--help`/`-h`, `--json`, and `--quiet`/`-q` are root-owned by default and
379
+ * never reach a command handler. Setting one to `'off'` releases every
380
+ * spelling it answers to: the root stops reading it out of argv, root help
381
+ * stops advertising it under `Global options:`, and a command may declare it
382
+ * as an ordinary flag. `RunOptions.jsonMode` and `RunOptions.verbosity`
383
+ * keep working either way, since only argv-driven activation is disabled.
384
+ *
385
+ * `version` and `completions` are absent by design, since `.version()` and
386
+ * `.completions()` are opt-in and a CLI declines those by omission.
387
+ *
388
+ * Call multiple times to set built-ins incrementally; the last mode given for
389
+ * a built-in wins. Turning one back `'on'` re-checks every registered command
390
+ * for a collision. Call this **before** registering the commands that declare
391
+ * a released flag, since `.command()` rejects the flag while the root still
392
+ * owns the token.
393
+ *
394
+ * @param config - Built-in modes to apply over the current state.
395
+ * @returns The builder (for chaining).
396
+ * @throws {@link CLIError} `INVALID_SCHEMA` when a value is neither `'on'` nor `'off'`.
397
+ * @throws {@link CLIError} `RESERVED_FLAG` when a registered command already
398
+ * declares a flag spelled like a built-in this call keeps or restores.
399
+ * @see {@link BuiltinsConfig} for the accepted keys and modes.
400
+ * @see https://dreamcli.kjanat.dev/guide/output#taking-a-built-in-over
401
+ *
402
+ * @example
403
+ * ```ts
404
+ * // `--json` names the document the command validates.
405
+ * cli('schematool')
406
+ * .builtins({ json: 'off' })
407
+ * .default(
408
+ * command('validate')
409
+ * .flag('json', flag.string().describe('Document to validate'))
410
+ * .action(({ flags, out }) => out.log(flags.json)),
411
+ * )
412
+ * .run();
413
+ * ```
414
+ */
415
+ builtins(config) {
416
+ const definedConfig = {
417
+ ...config.help !== void 0 ? { help: config.help } : {},
418
+ ...config.json !== void 0 ? { json: config.json } : {},
419
+ ...config.quiet !== void 0 ? { quiet: config.quiet } : {}
420
+ };
421
+ const builtins = normalizeBuiltins({
422
+ ...this.schema.builtins,
423
+ ...definedConfig
424
+ });
425
+ assertNoReservedFlagCollisions(this.schema.version, [this.schema.defaultCommand, ...this.schema.commands], builtins);
426
+ return rebuild(this, sealCLISchema({
427
+ ...this.schema,
428
+ builtins
429
+ }));
430
+ }
431
+ /**
229
432
  * Set the program description (shown in root help).
230
433
  *
231
434
  * @param text - Short description displayed in root help output.
232
435
  * @returns The builder (for chaining).
233
436
  */
234
437
  description(text) {
235
- return new CLIBuilder({
438
+ return rebuild(this, {
236
439
  ...this.schema,
237
440
  description: text
238
441
  });
@@ -276,7 +479,7 @@ var CLIBuilder = class CLIBuilder {
276
479
  * ```
277
480
  */
278
481
  links(links) {
279
- return new CLIBuilder({
482
+ return rebuild(this, {
280
483
  ...this.schema,
281
484
  helpLinks: {
282
485
  name: toUrlString(links?.name),
@@ -303,7 +506,7 @@ var CLIBuilder = class CLIBuilder {
303
506
  * ```
304
507
  */
305
508
  help(config) {
306
- return new CLIBuilder({
509
+ return rebuild(this, {
307
510
  ...this.schema,
308
511
  helpConfig: {
309
512
  ...this.schema.helpConfig,
@@ -339,13 +542,13 @@ var CLIBuilder = class CLIBuilder {
339
542
  * @returns The builder (for chaining).
340
543
  */
341
544
  config(appName, loaders) {
342
- return new CLIBuilder({
545
+ return rebuild(this, sealCLISchema({
343
546
  ...this.schema,
344
547
  configSettings: {
345
548
  appName,
346
549
  loaders
347
550
  }
348
- });
551
+ }));
349
552
  }
350
553
  /**
351
554
  * Register a custom config format loader.
@@ -389,39 +592,45 @@ var CLIBuilder = class CLIBuilder {
389
592
  suggest: "Call .config(appName) before .configLoader()"
390
593
  });
391
594
  const existing = this.schema.configSettings.loaders ?? [];
392
- return new CLIBuilder({
595
+ return rebuild(this, sealCLISchema({
393
596
  ...this.schema,
394
597
  configSettings: {
395
598
  ...this.schema.configSettings,
396
599
  loaders: [...existing, loader]
397
600
  }
398
- });
601
+ }));
399
602
  }
400
603
  manifest(input) {
401
- return new CLIBuilder(buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES, false));
402
- }
403
- packageJson(input) {
404
- return new CLIBuilder(buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES, true));
405
- }
406
- denoJson(input) {
407
- return new CLIBuilder(buildManifestSchema(this.schema, input, DENO_MANIFEST_FILES, true));
604
+ const next = buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES);
605
+ assertNoReservedFlagCollisions(next.version, [next.defaultCommand, ...next.commands], next.builtins);
606
+ return rebuild(this, next);
408
607
  }
409
608
  /**
410
609
  * Register a command with the CLI program.
411
610
  *
412
- * The command's type parameters are erased for heterogeneous storage.
413
- * Type safety is preserved inside the closure that delegates to
414
- * {@linkcode runCommand | runCommand()}.
611
+ * The command's schema joins {@link CLISchema.commands}; its handler and
612
+ * subcommand tree are compiled into the builder's execution graph.
415
613
  *
416
614
  * @param cmd - {@link CommandBuilder} to register.
417
615
  * @returns The builder (for chaining).
616
+ * @throws {@link CLIError} `RESERVED_FLAG` when the command, or one of its
617
+ * nested subcommands, spells a root-owned flag (`--json`, `--quiet`/`-q`,
618
+ * `--help`/`-h`, and `--version`/`-V` once
619
+ * {@link CLIBuilder.version | .version()} is set) as a flag name, an alias,
620
+ * or a negated spelling. A built-in released through
621
+ * {@link CLIBuilder.builtins | .builtins()} is not reserved.
418
622
  */
419
623
  command(cmd) {
420
624
  assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema, this.schema.defaultCommand);
625
+ assertNoReservedFlagCollisions(this.schema.version, [cmd.schema], this.schema.builtins);
421
626
  if (this.schema.completionsFlag !== void 0) assertNoCompletionsFlagCollision(cmd.schema);
422
- return new CLIBuilder({
627
+ const compiled = compiledStateOf(this);
628
+ return CLIBuilder._from({
423
629
  ...this.schema,
424
- commands: [...this.schema.commands, eraseCommand(cmd)]
630
+ commands: [...this.schema.commands, cmd.schema]
631
+ }, {
632
+ ...compiled,
633
+ commands: [...compiled.commands, compileCommand(cmd)]
425
634
  });
426
635
  }
427
636
  /**
@@ -472,6 +681,12 @@ var CLIBuilder = class CLIBuilder {
472
681
  * @param options - Default-command options. `{ route: true }` also exposes
473
682
  * the command under its own name (see {@link DefaultCommandOptions}).
474
683
  * @returns The builder (for chaining).
684
+ * @throws {@link CLIError} `RESERVED_FLAG` when the command, or one of its
685
+ * nested subcommands, spells a root-owned flag (`--json`, `--quiet`/`-q`,
686
+ * `--help`/`-h`, and `--version`/`-V` once
687
+ * {@link CLIBuilder.version | .version()} is set) as a flag name, an alias,
688
+ * or a negated spelling. A built-in released through
689
+ * {@link CLIBuilder.builtins | .builtins()} is not reserved.
475
690
  */
476
691
  default(cmd, options) {
477
692
  if (this.schema.defaultCommand !== void 0) throw new CLIError("Only one default command is allowed", {
@@ -479,12 +694,16 @@ var CLIBuilder = class CLIBuilder {
479
694
  suggest: "Call .default() only once when building the CLI"
480
695
  });
481
696
  assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
697
+ assertNoReservedFlagCollisions(this.schema.version, [cmd.schema], this.schema.builtins);
482
698
  if (this.schema.completionsFlag !== void 0) assertNoCompletionsFlagCollision(cmd.schema);
483
- const erased = eraseCommand(cmd);
484
- return new CLIBuilder({
699
+ const compiled = compiledStateOf(this);
700
+ return CLIBuilder._from({
485
701
  ...this.schema,
486
- defaultCommand: erased,
702
+ defaultCommand: cmd.schema,
487
703
  defaultCommandRouted: options?.route ?? false
704
+ }, {
705
+ ...compiled,
706
+ defaultCommand: compileCommand(cmd)
488
707
  });
489
708
  }
490
709
  /**
@@ -498,9 +717,10 @@ var CLIBuilder = class CLIBuilder {
498
717
  * @see {@link plugin} to construct plugin definitions.
499
718
  */
500
719
  plugin(definition) {
501
- return new CLIBuilder({
502
- ...this.schema,
503
- plugins: [...this.schema.plugins, definition]
720
+ const compiled = compiledStateOf(this);
721
+ return CLIBuilder._from(this.schema, {
722
+ ...compiled,
723
+ plugins: [...compiled.plugins, definition]
504
724
  });
505
725
  }
506
726
  /**
@@ -542,9 +762,9 @@ var CLIBuilder = class CLIBuilder {
542
762
  suggest: "Call .completions() only once when building the CLI"
543
763
  });
544
764
  if (options?.as === "flag") {
545
- if (this.schema.defaultCommand !== void 0) assertNoCompletionsFlagCollision(this.schema.defaultCommand.schema);
546
- for (const registered of this.schema.commands) assertNoCompletionsFlagCollision(registered.schema);
547
- return new CLIBuilder({
765
+ if (this.schema.defaultCommand !== void 0) assertNoCompletionsFlagCollision(this.schema.defaultCommand);
766
+ for (const registered of this.schema.commands) assertNoCompletionsFlagCollision(registered);
767
+ return rebuild(this, {
548
768
  ...this.schema,
549
769
  hasBuiltInCompletions: true,
550
770
  completionsFlag: {
@@ -560,10 +780,11 @@ var CLIBuilder = class CLIBuilder {
560
780
  if (shell === void 0) throw new Error(`Unknown shell '${raw}'. Valid shells: ${SHELLS.join(", ")}`);
561
781
  return shell;
562
782
  }).env("SHELL").describe(`Target shell (${SHELLS.join(", ")})`)).action(({ args, meta, out }) => {
563
- const script = generateCompletion(meta.bin === cliSchema.name ? cliSchema : {
783
+ const completionSchema = meta.bin === cliSchema.name ? cliSchema : {
564
784
  ...cliSchema,
565
785
  name: meta.bin
566
- }, args.shell, completionOptions);
786
+ };
787
+ const script = generateCompletion(completionSchema, args.shell, completionOptions);
567
788
  if (out.jsonMode) out.json({
568
789
  shell: args.shell,
569
790
  script
@@ -571,7 +792,7 @@ var CLIBuilder = class CLIBuilder {
571
792
  else out.log(script);
572
793
  });
573
794
  const withCompletions = this.command(cmd);
574
- return new CLIBuilder({
795
+ return rebuild(withCompletions, {
575
796
  ...withCompletions.schema,
576
797
  hasBuiltInCompletions: true
577
798
  });
@@ -588,146 +809,7 @@ var CLIBuilder = class CLIBuilder {
588
809
  * @returns Structured result with exit code and captured output.
589
810
  */
590
811
  async execute(argv, options) {
591
- const jsonMode = includesBeforeSeparator(argv, "--json") || options?.jsonMode === true;
592
- const verbosity = includesBeforeSeparator(argv, "--quiet") || includesBeforeSeparator(argv, "-q") ? "quiet" : options?.verbosity;
593
- const captureOptions = {
594
- ...verbosity !== void 0 ? { verbosity } : {},
595
- ...jsonMode ? { jsonMode } : {},
596
- ...options?.isTTY !== void 0 ? { isTTY: options.isTTY } : {},
597
- ...hyperlinksOption(resolveHyperlinkOverride(options?.env ?? {}, argv))
598
- };
599
- let out;
600
- let captured;
601
- if (options?.out !== void 0) {
602
- out = options.out;
603
- captured = options.captured ?? {
604
- stdout: [],
605
- stderr: [],
606
- activity: []
607
- };
608
- } else [out, captured] = createCaptureOutput(Object.keys(captureOptions).length > 0 ? captureOptions : void 0);
609
- clearRequestedExitCode(out);
610
- const resolvedVersion = options?.help?.version ?? this.schema.version;
611
- const helpOptions = {
612
- ...this.schema.helpConfig,
613
- ...options?.help,
614
- binName: options?.help?.binName ?? this.schema.name,
615
- hyperlinks: options?.help?.hyperlinks ?? this.schema.helpConfig?.hyperlinks ?? out.isHyperlinkSupported,
616
- colors: options?.help?.colors ?? out.color,
617
- ...resolvedVersion !== void 0 ? { version: resolvedVersion } : {}
618
- };
619
- const flagSettings = options?.flags ?? this.schema.flagSettings;
620
- const effectiveOptions = {
621
- ...options,
622
- plugins: this.schema.plugins,
623
- ...jsonMode ? { jsonMode } : {},
624
- ...verbosity !== void 0 ? { verbosity } : {},
625
- ...flagSettings !== void 0 ? { flags: flagSettings } : {}
626
- };
627
- const output = {
628
- jsonMode,
629
- isTTY: out.isTTY,
630
- verbosity: verbosity ?? "normal"
631
- };
632
- const planned = planInvocation({
633
- schema: options?.flags !== void 0 ? {
634
- ...this.schema,
635
- flagSettings
636
- } : this.schema,
637
- argv,
638
- help: helpOptions,
639
- output
640
- });
641
- switch (planned.kind) {
642
- case "root-version":
643
- out.log(planned.version);
644
- return buildRunResult({
645
- exitCode: 0,
646
- error: void 0
647
- }, captured);
648
- case "root-completions": {
649
- const shell = planned.shell ?? detectShell(options?.env ?? {});
650
- if (shell === void 0) {
651
- const error = new CLIError("Could not detect shell", {
652
- code: "MISSING_VALUE",
653
- suggest: `Pass one explicitly, e.g. '${helpOptions.binName} --completions zsh'`
654
- });
655
- if (jsonMode) out.json({ error: error.toJSON() });
656
- else {
657
- out.error(error.message);
658
- out.error(`Suggestion: ${error.suggest}`);
659
- }
660
- return buildRunResult({
661
- exitCode: error.exitCode,
662
- error
663
- }, captured);
664
- }
665
- const script = generateCompletion(helpOptions.binName === void 0 || helpOptions.binName === this.schema.name ? this.schema : {
666
- ...this.schema,
667
- name: helpOptions.binName
668
- }, shell, planned.options);
669
- if (jsonMode) out.json({
670
- shell,
671
- script
672
- });
673
- else out.log(script);
674
- return buildRunResult({
675
- exitCode: 0,
676
- error: void 0
677
- }, captured);
678
- }
679
- case "root-help":
680
- if (jsonMode) out.json(generateSchema(this.schema, void 0, {
681
- name: planned.help.binName ?? this.schema.name,
682
- version: planned.help.version ?? this.schema.version
683
- }));
684
- else {
685
- const helpText = formatRootHelp(resolveHelpLinksSchema(this.schema), planned.help);
686
- out.log(helpText);
687
- }
688
- return buildRunResult({
689
- exitCode: 0,
690
- error: void 0
691
- }, captured);
692
- case "dispatch-error":
693
- if (jsonMode) out.json({ error: planned.error.toJSON() });
694
- else {
695
- out.error(planned.error.message);
696
- if (planned.error.suggest !== void 0 && planned.error.code !== "NO_ACTION") out.error(`Suggestion: ${planned.error.suggest}`);
697
- }
698
- return buildRunResult({
699
- exitCode: planned.error.exitCode,
700
- error: planned.error
701
- }, captured);
702
- case "needs-subcommand":
703
- if (jsonMode) out.json(generateCommandSchema(planned.command.schema, void 0, {
704
- name: planned.help.binName ?? planned.command.schema.name,
705
- version: planned.help.version
706
- }));
707
- else {
708
- const helpText = formatHelp(planned.command.schema, planned.help);
709
- out.log(helpText);
710
- }
711
- return buildRunResult({
712
- exitCode: 0,
713
- error: void 0
714
- }, captured);
715
- case "match": {
716
- const commandRunOptions = buildCommandRunOptions(effectiveOptions, planned.plan.help ?? helpOptions, planned.plan.meta);
717
- if (planned.plan.command._command === void 0) return planned.plan.command._execute(planned.plan.argv, {
718
- ...commandRunOptions,
719
- mergedSchema: planned.plan.mergedSchema
720
- });
721
- return buildRunResult(await executeCommand({
722
- command: planned.plan.command._command,
723
- argv: planned.plan.argv,
724
- out,
725
- schema: planned.plan.mergedSchema,
726
- meta: planned.plan.meta,
727
- options: commandRunOptions
728
- }), captured);
729
- }
730
- }
812
+ return executeCLI(this, argv, options);
731
813
  }
732
814
  /**
733
815
  * Run the CLI program as a production entry point.
@@ -748,13 +830,15 @@ var CLIBuilder = class CLIBuilder {
748
830
  async run(options) {
749
831
  const adapter = options?.adapter ?? createAdapter();
750
832
  const inheritedName = this.schema.inheritName ? inferInvocationName(adapter.argv) : void 0;
833
+ const compiled = compiledStateOf(this);
751
834
  const preflight = await prepareRuntimePreflight({
752
835
  schema: this.schema,
836
+ compiled,
753
837
  adapter,
754
838
  options,
755
839
  inheritedName
756
840
  });
757
- if (preflight.kind === "config-error") {
841
+ if (preflight.kind === "startup-error") {
758
842
  if (preflight.jsonMode) adapter.stdout(`${JSON.stringify({ error: preflight.error.toJSON() })}\n`);
759
843
  else {
760
844
  adapter.stderr(`Error: ${preflight.error.message}\n`);
@@ -762,7 +846,10 @@ var CLIBuilder = class CLIBuilder {
762
846
  }
763
847
  return adapter.exit(preflight.error.exitCode);
764
848
  }
765
- const effectiveBuilder = preflight.schema === this.schema ? this : new CLIBuilder(preflight.schema);
849
+ const effectiveBuilder = preflight.schema === this.schema ? this : rebuild(this, sealCLISchema({
850
+ ...this.schema,
851
+ ...preflight.schema
852
+ }));
766
853
  const terminalSize = adapter.getTerminalSize();
767
854
  const runtimeHelpWidth = options?.help?.width === void 0 && preflight.schema.helpConfig?.width === void 0 ? terminalSize?.columns : void 0;
768
855
  const runtimeHelpOptions = runtimeHelpWidth !== void 0 ? {
@@ -782,12 +869,171 @@ var CLIBuilder = class CLIBuilder {
782
869
  ...hyperlinksOption(resolveHyperlinkOverride(adapter.env, adapter.argv))
783
870
  })
784
871
  };
785
- const result = await effectiveBuilder.execute(preflight.filteredArgv, executeOptions);
872
+ const result = await executeCLI(effectiveBuilder, preflight.filteredArgv, executeOptions);
786
873
  for (const line of result.stdout) adapter.stdout(line);
787
874
  for (const line of result.stderr) adapter.stderr(line);
788
875
  return adapter.exit(result.exitCode);
789
876
  }
790
877
  };
878
+ /**
879
+ * Execution body shared by {@linkcode CLIBuilder.execute} and {@linkcode CLIBuilder.run},
880
+ * accepting the framework-populated output channel and plugin fields.
881
+ *
882
+ * @param builder - Builder supplying the schema and compiled command graph.
883
+ * @param argv - Raw argv tokens (NOT including the binary/script path).
884
+ * @param options - Injectable runtime state plus framework-populated fields.
885
+ * @returns Structured result with exit code and captured output.
886
+ *
887
+ * @internal
888
+ */
889
+ async function executeCLI(builder, argv, options) {
890
+ const rootOutputFlags = readRootOutputFlags(argv, builder.schema.builtins);
891
+ const jsonMode = resolveRootJsonMode(rootOutputFlags, options?.jsonMode);
892
+ const verbosity = resolveRootVerbosity(rootOutputFlags, options?.verbosity);
893
+ const captureOptions = {
894
+ ...verbosity !== void 0 ? { verbosity } : {},
895
+ ...jsonMode ? { jsonMode } : {},
896
+ ...options?.isTTY !== void 0 ? { isTTY: options.isTTY } : {},
897
+ ...hyperlinksOption(resolveHyperlinkOverride(options?.env ?? {}, argv))
898
+ };
899
+ let out;
900
+ let captured;
901
+ if (options?.out !== void 0) {
902
+ out = options.out;
903
+ captured = options.captured ?? {
904
+ stdout: [],
905
+ stderr: [],
906
+ activity: []
907
+ };
908
+ } else [out, captured] = createCaptureOutput(Object.keys(captureOptions).length > 0 ? captureOptions : void 0);
909
+ clearRequestedExitCode(out);
910
+ const resolvedVersion = options?.help?.version ?? builder.schema.version;
911
+ const helpOptions = {
912
+ ...builder.schema.helpConfig,
913
+ ...options?.help,
914
+ binName: options?.help?.binName ?? builder.schema.name,
915
+ hyperlinks: options?.help?.hyperlinks ?? builder.schema.helpConfig?.hyperlinks ?? out.isHyperlinkSupported,
916
+ colors: options?.help?.colors ?? out.color,
917
+ ...resolvedVersion !== void 0 ? { version: resolvedVersion } : {}
918
+ };
919
+ const compiled = compiledStateOf(builder);
920
+ const flagSettings = options?.flags ?? builder.schema.flagSettings;
921
+ const effectiveOptions = {
922
+ ...options,
923
+ plugins: compiled.plugins,
924
+ builtins: builder.schema.builtins,
925
+ ...jsonMode ? { jsonMode } : {},
926
+ ...verbosity !== void 0 ? { verbosity } : {},
927
+ ...flagSettings !== void 0 ? { flags: flagSettings } : {}
928
+ };
929
+ const output = {
930
+ jsonMode,
931
+ isTTY: out.isTTY,
932
+ verbosity: verbosity ?? "normal"
933
+ };
934
+ const planSchema = options?.flags !== void 0 ? {
935
+ ...builder.schema,
936
+ flagSettings
937
+ } : builder.schema;
938
+ const planned = planInvocation({
939
+ schema: planSchema,
940
+ compiled,
941
+ argv,
942
+ help: helpOptions,
943
+ output
944
+ });
945
+ switch (planned.kind) {
946
+ case "root-version":
947
+ out.log(planned.version);
948
+ return buildRunResult({
949
+ exitCode: 0,
950
+ error: void 0
951
+ }, captured);
952
+ case "root-completions": {
953
+ const shell = planned.shell ?? detectShell(options?.env ?? {});
954
+ if (shell === void 0) {
955
+ const error = new CLIError("Could not detect shell", {
956
+ code: "MISSING_VALUE",
957
+ suggest: `Pass one explicitly, e.g. '${helpOptions.binName} --completions zsh'`
958
+ });
959
+ if (jsonMode) out.json({ error: error.toJSON() });
960
+ else {
961
+ out.error(error.message);
962
+ out.error(`Suggestion: ${error.suggest}`);
963
+ }
964
+ return buildRunResult({
965
+ exitCode: error.exitCode,
966
+ error
967
+ }, captured);
968
+ }
969
+ const completionSchema = helpOptions.binName === void 0 || helpOptions.binName === builder.schema.name ? builder.schema : {
970
+ ...builder.schema,
971
+ name: helpOptions.binName
972
+ };
973
+ const script = generateCompletion(completionSchema, shell, planned.options);
974
+ if (jsonMode) out.json({
975
+ shell,
976
+ script
977
+ });
978
+ else out.log(script);
979
+ return buildRunResult({
980
+ exitCode: 0,
981
+ error: void 0
982
+ }, captured);
983
+ }
984
+ case "root-help":
985
+ if (jsonMode) out.json(generateSchema(builder.schema, void 0, {
986
+ name: planned.help.binName ?? builder.schema.name,
987
+ version: planned.help.version ?? builder.schema.version
988
+ }));
989
+ else {
990
+ const helpText = formatRootHelp(resolveHelpLinksSchema(builder.schema), planned.help);
991
+ out.log(helpText);
992
+ }
993
+ return buildRunResult({
994
+ exitCode: 0,
995
+ error: void 0
996
+ }, captured);
997
+ case "dispatch-error":
998
+ if (jsonMode) out.json({ error: planned.error.toJSON() });
999
+ else {
1000
+ out.error(planned.error.message);
1001
+ if (planned.error.suggest !== void 0 && planned.error.code !== "NO_ACTION") out.error(`Suggestion: ${planned.error.suggest}`);
1002
+ }
1003
+ return buildRunResult({
1004
+ exitCode: planned.error.exitCode,
1005
+ error: planned.error
1006
+ }, captured);
1007
+ case "needs-subcommand":
1008
+ if (jsonMode) out.json(generateCommandSchema(planned.command.schema, void 0, {
1009
+ name: planned.help.binName ?? planned.command.schema.name,
1010
+ version: planned.help.version
1011
+ }));
1012
+ else {
1013
+ const helpText = formatHelp(planned.command.schema, planned.help);
1014
+ out.log(helpText);
1015
+ }
1016
+ return buildRunResult({
1017
+ exitCode: 0,
1018
+ error: void 0
1019
+ }, captured);
1020
+ case "match": {
1021
+ const commandRunOptions = buildCommandRunOptions(effectiveOptions, planned.plan.help ?? helpOptions, planned.plan.meta);
1022
+ const result = await executeCommand({
1023
+ command: {
1024
+ handler: planned.plan.command.handler,
1025
+ steps: planned.plan.command.steps
1026
+ },
1027
+ argv: planned.plan.argv,
1028
+ out,
1029
+ schema: planned.plan.mergedSchema,
1030
+ meta: planned.plan.meta,
1031
+ options: commandRunOptions
1032
+ });
1033
+ return buildRunResult(result, captured);
1034
+ }
1035
+ }
1036
+ }
791
1037
  const RUNTIME_BINARIES = /* @__PURE__ */ new Set([
792
1038
  "bun",
793
1039
  "deno",
@@ -856,12 +1102,12 @@ function toUrlString(value) {
856
1102
  return value instanceof URL ? value.href : value;
857
1103
  }
858
1104
  /**
859
- * Resolve derived help links against pre-loaded package.json data.
1105
+ * Resolve derived help links against pre-loaded manifest data.
860
1106
  *
861
- * `.run()` resolves links during runtime preflight (where discovered
862
- * package.json metadata lives); this covers the filesystem-free
863
- * `.execute()` path, where only the `.packageJson(data)` overload can
864
- * contribute. Idempotent — already-resolved fields pass through unchanged.
1107
+ * `.run()` resolves links during runtime preflight (where discovered manifest
1108
+ * metadata lives); this covers the filesystem-free `.execute()` path, where
1109
+ * only the `.manifest(data)` overload can contribute. Idempotent —
1110
+ * already-resolved fields pass through unchanged.
865
1111
  *
866
1112
  * @internal
867
1113
  */
@@ -872,14 +1118,8 @@ function resolveHelpLinksSchema(schema) {
872
1118
  helpLinks: deriveHelpLinks(schema.helpLinks, schema.packageJsonSettings?.data, schema.version)
873
1119
  };
874
1120
  }
875
- /** Default manifest filenames for `.manifest()` / `.packageJson()`. @internal */
1121
+ /** Default manifest filenames for `.manifest()`. @internal */
876
1122
  const DEFAULT_MANIFEST_FILES = ["package.json"];
877
- /** Manifest filenames for the `.denoJson()` preset, in priority order. @internal */
878
- const DENO_MANIFEST_FILES = [
879
- "deno.json",
880
- "deno.jsonc",
881
- "jsr.json"
882
- ];
883
1123
  /**
884
1124
  * Normalise an {@link InferNameOption} into the flat `{ inferName, stripScope }`
885
1125
  * pair stored in {@link ResolvedManifestSettings}.
@@ -901,16 +1141,15 @@ function normalizeInferName(option) {
901
1141
  };
902
1142
  }
903
1143
  /**
904
- * Build the next {@link CLISchema} for a manifest builder method.
1144
+ * Build the next {@link CLISchema} for {@link CLIBuilder.manifest}.
905
1145
  *
906
- * Shared by {@link CLIBuilder.manifest}, {@link CLIBuilder.packageJson}, and
907
- * {@link CLIBuilder.denoJson}. The data overload (detected via field shape)
908
- * merges `version`/`description` immediately so `.execute()` sees them; the
909
- * settings overload stores discovery config for runtime preflight.
1146
+ * The data overload (detected via field shape) merges `version`/`description`
1147
+ * immediately so `.execute()` sees them; the settings overload stores discovery
1148
+ * config for runtime preflight.
910
1149
  *
911
1150
  * @internal
912
1151
  */
913
- function buildManifestSchema(schema, input, defaultFiles, pinFiles) {
1152
+ function buildManifestSchema(schema, input, defaultFiles) {
914
1153
  if (isPackageJsonData(input)) return {
915
1154
  ...schema,
916
1155
  ...schema.version === void 0 && input.version !== void 0 ? { version: input.version } : {},
@@ -924,7 +1163,7 @@ function buildManifestSchema(schema, input, defaultFiles, pinFiles) {
924
1163
  }
925
1164
  };
926
1165
  const { inferName, stripScope } = normalizeInferName(input?.inferName);
927
- const files = pinFiles ? defaultFiles : input?.files ?? defaultFiles;
1166
+ const files = input?.files ?? defaultFiles;
928
1167
  return {
929
1168
  ...schema,
930
1169
  packageJsonSettings: {
@@ -959,7 +1198,7 @@ function normalizeFromSetting(from) {
959
1198
  }
960
1199
  /**
961
1200
  * Predicate distinguishing the {@link PackageJsonData | data} overload of
962
- * `.packageJson()` from the settings overload at runtime.
1201
+ * `.manifest()` from the settings overload at runtime.
963
1202
  *
964
1203
  * A value is treated as `PackageJsonData` when it's a plain object that
965
1204
  * carries at least one recognised field (`name`, `version`, `description`,
@@ -990,21 +1229,15 @@ function cli(nameOrOptions, extraOptions) {
990
1229
  name: nameOrOptions,
991
1230
  ...extraOptions
992
1231
  } : nameOrOptions;
993
- return new CLIBuilder({
994
- name: options.name ?? "cli",
995
- inheritName: options.inherit ?? false,
996
- version: void 0,
997
- description: void 0,
1232
+ const name = options.name ?? "cli";
1233
+ const inheritName = options.inherit ?? false;
1234
+ return CLIBuilder._from(createCLISchema({
1235
+ name,
1236
+ inheritName,
1237
+ flagSettings: options.flags
1238
+ }), {
998
1239
  commands: [],
999
1240
  defaultCommand: void 0,
1000
- defaultCommandRouted: false,
1001
- configSettings: void 0,
1002
- packageJsonSettings: void 0,
1003
- helpLinks: void 0,
1004
- hasBuiltInCompletions: false,
1005
- completionsFlag: void 0,
1006
- helpConfig: void 0,
1007
- flagSettings: options.flags,
1008
1241
  plugins: []
1009
1242
  });
1010
1243
  }
@@ -1029,4 +1262,4 @@ function isMainModule(meta) {
1029
1262
  return meta.main === true;
1030
1263
  }
1031
1264
  //#endregion
1032
- export { CLIBuilder, cli, formatRootHelp, isMainModule, plugin, resolveRenderContext };
1265
+ export { CLIBuilder, cli, compiledStateOf, createCLISchema, executeCLI, isMainModule, plugin, resolveRenderContext };