@kjanat/dreamcli 4.0.0-rc.3 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -7
- package/dist/{runtime/adapter.d.mts → adapter-D0hbBNVB.d.mts} +2 -4
- package/dist/completion-D4mz6axB.mjs +6 -0
- package/dist/completion.d.mts +90 -0
- package/dist/completion.mjs +1 -0
- package/dist/config-B9ddC-Kb.mjs +1 -0
- package/dist/config.d.mts +2 -0
- package/dist/config.mjs +1 -0
- package/dist/core-Cp2w8vRq.mjs +17 -0
- package/dist/index-BziI2aKc.d.mts +5440 -0
- package/dist/index-DOfClfYR.d.mts +370 -0
- package/dist/index-DWsnGZlx.d.mts +831 -0
- package/dist/{core/cli/index.d.mts → index-DXROeDPC.d.mts} +116 -57
- package/dist/index-DndPmT8J.d.mts +275 -0
- package/dist/{core/json-schema/index.d.mts → index-DyoaS234.d.mts} +43 -34
- package/dist/index.d.mts +190 -41
- package/dist/index.mjs +1 -26
- package/dist/json-schema-C9SzZ7jY.mjs +52 -0
- package/dist/json-schema.d.mts +2 -0
- package/dist/json-schema.mjs +1 -0
- package/dist/package-json-BgE9YjjQ.mjs +3 -0
- package/dist/prompt.d.mts +48 -0
- package/dist/prompt.mjs +1 -0
- package/dist/rolldown-runtime-G4Kt5YOX.mjs +1 -0
- package/dist/runtime.d.mts +2 -6
- package/dist/runtime.mjs +1 -6
- package/dist/terminal-C8KTXjv5.mjs +6 -0
- package/dist/test-prompter-v__jT2yG.mjs +1 -0
- package/dist/testkit.d.mts +54 -6
- package/dist/testkit.mjs +1 -5
- package/dist/version.mjs +1 -7
- package/dreamcli.schema.json +697 -538
- package/package.json +29 -7
- package/skills/cli-creation/SKILL.md +16 -11
- package/CHANGELOG.md +0 -1116
- package/dist/core/cli/builtins.d.mts +0 -117
- package/dist/core/cli/builtins.mjs +0 -135
- package/dist/core/cli/compiled.d.mts +0 -66
- package/dist/core/cli/compiled.mjs +0 -76
- package/dist/core/cli/dispatch.d.mts +0 -115
- package/dist/core/cli/dispatch.mjs +0 -205
- package/dist/core/cli/help-links.d.mts +0 -27
- package/dist/core/cli/help-links.mjs +0 -41
- package/dist/core/cli/index.mjs +0 -1271
- package/dist/core/cli/planner.d.mts +0 -174
- package/dist/core/cli/planner.mjs +0 -323
- package/dist/core/cli/plugin.d.mts +0 -94
- package/dist/core/cli/plugin.mjs +0 -41
- package/dist/core/cli/propagate.d.mts +0 -39
- package/dist/core/cli/propagate.mjs +0 -57
- package/dist/core/cli/reserved-flags.d.mts +0 -19
- package/dist/core/cli/reserved-flags.mjs +0 -158
- package/dist/core/cli/root-help.d.mts +0 -53
- package/dist/core/cli/root-help.mjs +0 -221
- package/dist/core/cli/root-output-flags.d.mts +0 -74
- package/dist/core/cli/root-output-flags.mjs +0 -169
- package/dist/core/cli/root-surface.d.mts +0 -64
- package/dist/core/cli/root-surface.mjs +0 -28
- package/dist/core/cli/runtime-preflight.d.mts +0 -213
- package/dist/core/cli/runtime-preflight.mjs +0 -221
- package/dist/core/completion/index.d.mts +0 -76
- package/dist/core/completion/index.mjs +0 -90
- package/dist/core/completion/shells/bash.d.mts +0 -23
- package/dist/core/completion/shells/bash.mjs +0 -312
- package/dist/core/completion/shells/fish.d.mts +0 -19
- package/dist/core/completion/shells/fish.mjs +0 -164
- package/dist/core/completion/shells/powershell.d.mts +0 -13
- package/dist/core/completion/shells/powershell.mjs +0 -360
- package/dist/core/completion/shells/shared.d.mts +0 -164
- package/dist/core/completion/shells/shared.mjs +0 -147
- package/dist/core/completion/shells/zsh.d.mts +0 -23
- package/dist/core/completion/shells/zsh.mjs +0 -256
- package/dist/core/config/index.d.mts +0 -191
- package/dist/core/config/index.mjs +0 -285
- package/dist/core/config/package-json.d.mts +0 -179
- package/dist/core/config/package-json.mjs +0 -353
- package/dist/core/errors/index.d.mts +0 -125
- package/dist/core/errors/index.mjs +0 -87
- package/dist/core/execution/index.d.mts +0 -61
- package/dist/core/execution/index.mjs +0 -220
- package/dist/core/help/ansi.d.mts +0 -84
- package/dist/core/help/ansi.mjs +0 -121
- package/dist/core/help/index.d.mts +0 -149
- package/dist/core/help/index.mjs +0 -418
- package/dist/core/help/theme.d.mts +0 -86
- package/dist/core/help/theme.mjs +0 -69
- package/dist/core/json-schema/index.mjs +0 -1008
- package/dist/core/json-schema/meta-descriptions.generated.d.mts +0 -274
- package/dist/core/json-schema/meta-descriptions.generated.mjs +0 -136
- package/dist/core/output/activity.d.mts +0 -193
- package/dist/core/output/activity.mjs +0 -452
- package/dist/core/output/bind.d.mts +0 -37
- package/dist/core/output/bind.mjs +0 -56
- package/dist/core/output/contracts.d.mts +0 -82
- package/dist/core/output/contracts.mjs +0 -57
- package/dist/core/output/display-value.d.mts +0 -19
- package/dist/core/output/display-value.mjs +0 -32
- package/dist/core/output/index.d.mts +0 -344
- package/dist/core/output/index.mjs +0 -514
- package/dist/core/output/renderers.d.mts +0 -45
- package/dist/core/output/renderers.mjs +0 -46
- package/dist/core/output/writer.d.mts +0 -39
- package/dist/core/output/writer.mjs +0 -12
- package/dist/core/parse/index.d.mts +0 -178
- package/dist/core/parse/index.mjs +0 -850
- package/dist/core/parse/occurrences.d.mts +0 -90
- package/dist/core/parse/occurrences.mjs +0 -114
- package/dist/core/prompt/index.d.mts +0 -213
- package/dist/core/prompt/index.mjs +0 -348
- package/dist/core/read-flags/index.d.mts +0 -150
- package/dist/core/read-flags/index.mjs +0 -217
- package/dist/core/resolve/args.d.mts +0 -39
- package/dist/core/resolve/args.mjs +0 -182
- package/dist/core/resolve/coerce.d.mts +0 -79
- package/dist/core/resolve/coerce.mjs +0 -900
- package/dist/core/resolve/config.d.mts +0 -10
- package/dist/core/resolve/config.mjs +0 -19
- package/dist/core/resolve/contracts.d.mts +0 -146
- package/dist/core/resolve/errors.d.mts +0 -10
- package/dist/core/resolve/errors.mjs +0 -148
- package/dist/core/resolve/flags.d.mts +0 -74
- package/dist/core/resolve/flags.mjs +0 -246
- package/dist/core/resolve/index.d.mts +0 -44
- package/dist/core/resolve/index.mjs +0 -123
- package/dist/core/resolve/path-checks.d.mts +0 -48
- package/dist/core/resolve/path-checks.mjs +0 -102
- package/dist/core/resolve/redaction.d.mts +0 -13
- package/dist/core/resolve/redaction.mjs +0 -14
- package/dist/core/resolve/stages.d.mts +0 -86
- package/dist/core/resolve/stages.mjs +0 -170
- package/dist/core/resolve/standard.d.mts +0 -26
- package/dist/core/resolve/standard.mjs +0 -212
- package/dist/core/schema/activity.d.mts +0 -189
- package/dist/core/schema/arg.d.mts +0 -1461
- package/dist/core/schema/arg.mjs +0 -1139
- package/dist/core/schema/brand.d.mts +0 -17
- package/dist/core/schema/cardinality.d.mts +0 -302
- package/dist/core/schema/cardinality.mjs +0 -514
- package/dist/core/schema/command.d.mts +0 -1132
- package/dist/core/schema/command.mjs +0 -999
- package/dist/core/schema/flag.d.mts +0 -1495
- package/dist/core/schema/flag.mjs +0 -1207
- package/dist/core/schema/index.d.mts +0 -15
- package/dist/core/schema/index.mjs +0 -10
- package/dist/core/schema/middleware.d.mts +0 -129
- package/dist/core/schema/middleware.mjs +0 -41
- package/dist/core/schema/number-constraints.d.mts +0 -96
- package/dist/core/schema/number-constraints.mjs +0 -60
- package/dist/core/schema/prompt.d.mts +0 -135
- package/dist/core/schema/provenance.d.mts +0 -99
- package/dist/core/schema/provenance.mjs +0 -28
- package/dist/core/schema/run.d.mts +0 -211
- package/dist/core/schema/source.d.mts +0 -180
- package/dist/core/schema/source.mjs +0 -206
- package/dist/core/schema/standard.d.mts +0 -100
- package/dist/core/schema/standard.mjs +0 -15
- package/dist/core/schema/stdin.d.mts +0 -97
- package/dist/core/schema/stdin.mjs +0 -91
- package/dist/core/schema/string-constraints.d.mts +0 -108
- package/dist/core/schema/string-constraints.mjs +0 -86
- package/dist/core/schema/value-parsers.d.mts +0 -150
- package/dist/core/schema/value-parsers.mjs +0 -160
- package/dist/core/schema/value.d.mts +0 -243
- package/dist/core/schema/value.mjs +0 -573
- package/dist/core/testkit/index.d.mts +0 -63
- package/dist/core/testkit/index.mjs +0 -102
- package/dist/runtime/adapter.mjs +0 -92
- package/dist/runtime/auto.d.mts +0 -25
- package/dist/runtime/auto.mjs +0 -45
- package/dist/runtime/deno.d.mts +0 -99
- package/dist/runtime/deno.mjs +0 -265
- package/dist/runtime/detect.d.mts +0 -86
- package/dist/runtime/detect.mjs +0 -45
- package/dist/runtime/index.d.mts +0 -6
- package/dist/runtime/node.d.mts +0 -71
- package/dist/runtime/node.mjs +0 -228
- package/dist/runtime/paths.d.mts +0 -31
- package/dist/runtime/paths.mjs +0 -48
- package/dist/strings.d.mts +0 -27
- package/dist/strings.mjs +0 -22
- package/examples/basic.ts +0 -37
- package/examples/flag-types.ts +0 -79
- package/examples/gh/package.json +0 -45
- package/examples/gh/src/commands/auth.ts +0 -66
- package/examples/gh/src/commands/issue.ts +0 -120
- package/examples/gh/src/commands/pr.ts +0 -125
- package/examples/gh/src/data/issues.yaml +0 -5
- package/examples/gh/src/data/issues.yaml.d.ts +0 -17
- package/examples/gh/src/data/pull-requests.yaml +0 -7
- package/examples/gh/src/data/pull-requests.yaml.d.ts +0 -18
- package/examples/gh/src/docs.ts +0 -11
- package/examples/gh/src/lib/auth.ts +0 -37
- package/examples/gh/src/lib/utils.ts +0 -17
- package/examples/gh/src/main.test.ts +0 -307
- package/examples/gh/src/main.ts +0 -46
- package/examples/help-config.ts +0 -43
- package/examples/interactive.ts +0 -67
- package/examples/json-mode.ts +0 -95
- package/examples/middleware.ts +0 -71
- package/examples/multi-command.ts +0 -66
- package/examples/output-extras.ts +0 -46
- package/examples/parser-control.ts +0 -40
- package/examples/pwsh-demo/README.md +0 -40
- package/examples/pwsh-demo/package.json +0 -41
- package/examples/pwsh-demo/pwsh-demo.cmd +0 -3
- package/examples/pwsh-demo/smoke-powershell.ps1 +0 -218
- package/examples/pwsh-demo/src/main.test.ts +0 -45
- package/examples/pwsh-demo/src/main.ts +0 -140
- package/examples/spinner-progress.ts +0 -49
- package/examples/standard-schema.ts +0 -45
- package/examples/testing.ts +0 -147
- package/examples/transport-launcher.ts +0 -85
package/dist/core/cli/index.mjs
DELETED
|
@@ -1,1271 +0,0 @@
|
|
|
1
|
-
import { CLIError } from "../errors/index.mjs";
|
|
2
|
-
import { getFlagAliasNames, getFlagNegatedName } from "../schema/flag.mjs";
|
|
3
|
-
import { arg } from "../schema/arg.mjs";
|
|
4
|
-
import { command, createCommandSchema } from "../schema/command.mjs";
|
|
5
|
-
import { normalizeBuiltins } from "./builtins.mjs";
|
|
6
|
-
import { SHELLS, detectShell, generateCompletion, normalizeShell } from "../completion/index.mjs";
|
|
7
|
-
import { formatHelp } from "../help/index.mjs";
|
|
8
|
-
import { generateCommandSchema, generateSchema } from "../json-schema/index.mjs";
|
|
9
|
-
import { clearRequestedExitCode, createCaptureOutput, createOutput, resolveHyperlinkOverride } from "../output/index.mjs";
|
|
10
|
-
import { buildRunResult, executeCommand } from "../execution/index.mjs";
|
|
11
|
-
import { stripTrailing } from "../../strings.mjs";
|
|
12
|
-
import { createAdapter } from "../../runtime/auto.mjs";
|
|
13
|
-
import { assertNoSiblingRouteConflict, commandRoutes, compileCommand } from "./compiled.mjs";
|
|
14
|
-
import { deriveHelpLinks } from "./help-links.mjs";
|
|
15
|
-
import { readRootOutputFlags, resolveRootJsonMode, resolveRootVerbosity } from "./root-output-flags.mjs";
|
|
16
|
-
import { planInvocation } from "./planner.mjs";
|
|
17
|
-
import { plugin } from "./plugin.mjs";
|
|
18
|
-
import { assertNoReservedFlagCollisions } from "./reserved-flags.mjs";
|
|
19
|
-
import { formatRootHelp } from "./root-help.mjs";
|
|
20
|
-
import { prepareRuntimePreflight } from "./runtime-preflight.mjs";
|
|
21
|
-
//#region src/core/cli/index.ts
|
|
22
|
-
/** Long-flag name reserved by `.completions({ as: 'flag' })`; the planner intercepts it before dispatch. */
|
|
23
|
-
const COMPLETIONS_FLAG_NAME = "completions";
|
|
24
|
-
/**
|
|
25
|
-
* Whether a command — or any of its nested subcommands — declares a flag that
|
|
26
|
-
* collides with the eager `--completions` flag, by canonical name, long alias,
|
|
27
|
-
* or negated spelling.
|
|
28
|
-
*
|
|
29
|
-
* @internal
|
|
30
|
-
*/
|
|
31
|
-
function commandReservesCompletionsFlag(schema) {
|
|
32
|
-
if (Object.hasOwn(schema.flags, 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
|
-
}
|
|
40
|
-
return schema.commands.some(commandReservesCompletionsFlag);
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Reject a command whose flags would be shadowed by the eager `--completions`
|
|
44
|
-
* flag once `.completions({ as: 'flag' })` is active. Because the planner
|
|
45
|
-
* intercepts `--completions` before dispatch, such a flag could never be reached.
|
|
46
|
-
*
|
|
47
|
-
* @internal
|
|
48
|
-
*/
|
|
49
|
-
function assertNoCompletionsFlagCollision(schema) {
|
|
50
|
-
if (commandReservesCompletionsFlag(schema)) throw new CLIError(`Command '${schema.name}' defines a '--${COMPLETIONS_FLAG_NAME}' flag, which is reserved by .completions({ as: 'flag' })`, {
|
|
51
|
-
code: "RESERVED_FLAG",
|
|
52
|
-
suggest: `Rename the flag, or register completions as a subcommand with .completions() instead of { as: 'flag' }`
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
function assertNoTopLevelRouteConflict(commands, incoming, defaultCommand) {
|
|
56
|
-
const routeOwners = /* @__PURE__ */ new Map();
|
|
57
|
-
const existing = defaultCommand !== void 0 ? [...commands, defaultCommand] : commands;
|
|
58
|
-
for (const registered of existing) for (const route of commandRoutes(registered)) assertNoSiblingRouteConflict("root", routeOwners, route, registered.name);
|
|
59
|
-
for (const route of commandRoutes(incoming)) {
|
|
60
|
-
const owner = routeOwners.get(route);
|
|
61
|
-
if (owner !== void 0) throw new CLIError(`Command route '${route}' is already registered by '${owner}'`, {
|
|
62
|
-
code: "DUPLICATE_COMMAND",
|
|
63
|
-
suggest: owner === incoming.name ? `Ensure command '${incoming.name}' does not reuse route '${route}'` : `Rename '${incoming.name}' or remove route '${route}' from '${owner}'`
|
|
64
|
-
});
|
|
65
|
-
routeOwners.set(route, incoming.name);
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Compiled execution graph per builder instance.
|
|
70
|
-
*
|
|
71
|
-
* Keyed weakly so handlers and execution steps stay off the public schema and
|
|
72
|
-
* out of the emitted declarations.
|
|
73
|
-
*
|
|
74
|
-
* @internal
|
|
75
|
-
*/
|
|
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);
|
|
202
|
-
}
|
|
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;
|
|
211
|
-
}
|
|
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
|
-
/**
|
|
232
|
-
* Resolve the render context for content built before `.run()`.
|
|
233
|
-
*
|
|
234
|
-
* Content styled ahead of execution — hand-rendered banners, custom help, or
|
|
235
|
-
* anything else emitted outside an action handler — has no `out` to consult,
|
|
236
|
-
* which pushes consumers into re-deriving the framework's decisions from raw
|
|
237
|
-
* argv (`argv.includes('--json')` misreads a post-`--` literal). This probe
|
|
238
|
-
* runs the same composition `.execute()`/`.run()` feed into the output
|
|
239
|
-
* channel — `--`-aware `--json` detection, the color gate, and the hyperlink
|
|
240
|
-
* override — so pre-run styling matches the channel that will render.
|
|
241
|
-
*
|
|
242
|
-
* @param argv - Raw argv tokens (NOT including the binary/script path,
|
|
243
|
-
* i.e. equivalent to `process.argv.slice(2)`).
|
|
244
|
-
* @param options - Host facts and overrides.
|
|
245
|
-
* @returns The resolved output decisions.
|
|
246
|
-
*
|
|
247
|
-
* @example
|
|
248
|
-
* ```ts
|
|
249
|
-
* const ctx = resolveRenderContext(process.argv.slice(2), {
|
|
250
|
-
* isTTY: process.stdout.isTTY === true,
|
|
251
|
-
* env: process.env,
|
|
252
|
-
* });
|
|
253
|
-
* const banner = ctx.color.bold('mycli');
|
|
254
|
-
* ```
|
|
255
|
-
*/
|
|
256
|
-
function resolveRenderContext(argv, options) {
|
|
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,
|
|
262
|
-
isTTY: options?.isTTY ?? false,
|
|
263
|
-
verbosity,
|
|
264
|
-
...options?.color !== void 0 ? { color: options.color } : {},
|
|
265
|
-
...hyperlinksOption(resolveHyperlinkOverride(options?.env ?? {}, argv))
|
|
266
|
-
}));
|
|
267
|
-
}
|
|
268
|
-
/**
|
|
269
|
-
* Conditional-spread wrapper for the output channel's `hyperlinks` option:
|
|
270
|
-
* omit the key entirely when there is no override so `exactOptionalPropertyTypes`
|
|
271
|
-
* stays happy and the channel falls back to `isTTY`.
|
|
272
|
-
*
|
|
273
|
-
* @internal
|
|
274
|
-
*/
|
|
275
|
-
function hyperlinksOption(override) {
|
|
276
|
-
return override !== void 0 ? { hyperlinks: override } : {};
|
|
277
|
-
}
|
|
278
|
-
/** Resolve the hyperlink decision shared by help rendering and the output channel. @internal */
|
|
279
|
-
function resolveEffectiveHyperlinkOverride(runtimeHelp, configuredHelp, env, argv) {
|
|
280
|
-
return runtimeHelp?.hyperlinks ?? configuredHelp?.hyperlinks ?? resolveHyperlinkOverride(env, argv);
|
|
281
|
-
}
|
|
282
|
-
/**
|
|
283
|
-
* Build {@linkcode RunOptions} from {@linkcode CLIExecuteOptions}, conditionally spreading each
|
|
284
|
-
* field to satisfy `exactOptionalPropertyTypes`.
|
|
285
|
-
*
|
|
286
|
-
* @param options - CLI-level run options (may be `undefined` for defaults).
|
|
287
|
-
* @param helpOptions - Help formatting options forwarded to commands.
|
|
288
|
-
* @param meta - Optional command metadata (omitted for root-level dispatch).
|
|
289
|
-
* @returns Options record ready for the shared executor.
|
|
290
|
-
*
|
|
291
|
-
* @internal
|
|
292
|
-
*/
|
|
293
|
-
function buildCommandRunOptions(options, helpOptions, meta) {
|
|
294
|
-
return {
|
|
295
|
-
help: helpOptions,
|
|
296
|
-
...meta !== void 0 ? { meta } : {},
|
|
297
|
-
...options?.plugins !== void 0 ? { plugins: options.plugins } : {},
|
|
298
|
-
...options?.builtins !== void 0 ? { builtins: options.builtins } : {},
|
|
299
|
-
...options?.env !== void 0 ? { env: options.env } : {},
|
|
300
|
-
...options?.config !== void 0 ? { config: options.config } : {},
|
|
301
|
-
...options?.stdinData !== void 0 ? { stdinData: options.stdinData } : {},
|
|
302
|
-
...options?.prompter !== void 0 ? { prompter: options.prompter } : {},
|
|
303
|
-
...options?.answers !== void 0 ? { answers: options.answers } : {},
|
|
304
|
-
...options?.stat !== void 0 ? { stat: options.stat } : {},
|
|
305
|
-
...options?.mkdir !== void 0 ? { mkdir: options.mkdir } : {},
|
|
306
|
-
...options?.verbosity !== void 0 ? { verbosity: options.verbosity } : {},
|
|
307
|
-
...options?.jsonMode !== void 0 ? { jsonMode: options.jsonMode } : {},
|
|
308
|
-
...options?.isTTY !== void 0 ? { isTTY: options.isTTY } : {},
|
|
309
|
-
...options?.out !== void 0 ? { out: options.out } : {},
|
|
310
|
-
...options?.captured !== void 0 ? { captured: options.captured } : {},
|
|
311
|
-
...options?.flags !== void 0 ? { flags: options.flags } : {}
|
|
312
|
-
};
|
|
313
|
-
}
|
|
314
|
-
/**
|
|
315
|
-
* Immutable CLI program builder.
|
|
316
|
-
*
|
|
317
|
-
* Registers commands, handles root-level `--help`/`--version`, and
|
|
318
|
-
* dispatches to the matched command based on argv.
|
|
319
|
-
*
|
|
320
|
-
* Two execution paths:
|
|
321
|
-
* - `.execute(argv, options?)` — testable, returns {@linkcode RunResult}
|
|
322
|
-
* - `.run(options?)` — production entry, reads `process.argv`, exits process
|
|
323
|
-
*
|
|
324
|
-
* @example
|
|
325
|
-
* ```ts
|
|
326
|
-
* import { cli, command, flag, arg } from '@kjanat/dreamcli';
|
|
327
|
-
*
|
|
328
|
-
* const deploy = command('deploy')
|
|
329
|
-
* .arg('target', arg.string())
|
|
330
|
-
* .flag('force', flag.boolean().alias('f'))
|
|
331
|
-
* .action(({ args, flags, out }) => {
|
|
332
|
-
* out.log(`Deploying ${args.target}...`);
|
|
333
|
-
* });
|
|
334
|
-
*
|
|
335
|
-
* cli('mycli')
|
|
336
|
-
* .version('1.0.0')
|
|
337
|
-
* .command(deploy)
|
|
338
|
-
* .run();
|
|
339
|
-
* ```
|
|
340
|
-
*/
|
|
341
|
-
var CLIBuilder = class CLIBuilder {
|
|
342
|
-
/** @internal Runtime schema descriptor. */
|
|
343
|
-
schema;
|
|
344
|
-
constructor(schema) {
|
|
345
|
-
this.schema = schema;
|
|
346
|
-
}
|
|
347
|
-
/**
|
|
348
|
-
* Build a CLI builder around a schema and its compiled execution graph.
|
|
349
|
-
*
|
|
350
|
-
* @param schema - Runtime schema descriptor.
|
|
351
|
-
* @param compiled - Compiled commands, default command, and plugins.
|
|
352
|
-
* @returns The builder, with its compiled state registered.
|
|
353
|
-
*
|
|
354
|
-
* @internal
|
|
355
|
-
*/
|
|
356
|
-
static _from(schema, compiled) {
|
|
357
|
-
const builder = new CLIBuilder(schema);
|
|
358
|
-
compiledStates.set(builder, compiled);
|
|
359
|
-
return builder;
|
|
360
|
-
}
|
|
361
|
-
/**
|
|
362
|
-
* Set the program version (shown by `--version`).
|
|
363
|
-
*
|
|
364
|
-
* Declaring a version also reserves `--version`/`-V` on every registered
|
|
365
|
-
* command, so this rejects a command that already declares either spelling.
|
|
366
|
-
*
|
|
367
|
-
* @param v - Semantic version string.
|
|
368
|
-
* @returns The builder (for chaining).
|
|
369
|
-
* @throws {@link CLIError} `RESERVED_FLAG` when a registered command spells
|
|
370
|
-
* `--version` or `-V` as a flag name, an alias, or a negated spelling.
|
|
371
|
-
*/
|
|
372
|
-
version(v) {
|
|
373
|
-
assertNoReservedFlagCollisions(v, [this.schema.defaultCommand, ...this.schema.commands], this.schema.builtins);
|
|
374
|
-
return rebuild(this, {
|
|
375
|
-
...this.schema,
|
|
376
|
-
version: v
|
|
377
|
-
});
|
|
378
|
-
}
|
|
379
|
-
/**
|
|
380
|
-
* Choose which built-in flags the root keeps.
|
|
381
|
-
*
|
|
382
|
-
* `--help`/`-h`, `--json`, and `--quiet`/`-q` are root-owned by default and
|
|
383
|
-
* never reach a command handler. Setting one to `'off'` releases every
|
|
384
|
-
* spelling it answers to: the root stops reading it out of argv, root help
|
|
385
|
-
* stops advertising it under `Global options:`, and a command may declare it
|
|
386
|
-
* as an ordinary flag. `RunOptions.jsonMode` and `RunOptions.verbosity`
|
|
387
|
-
* keep working either way, since only argv-driven activation is disabled.
|
|
388
|
-
*
|
|
389
|
-
* `version` and `completions` are absent by design, since `.version()` and
|
|
390
|
-
* `.completions()` are opt-in and a CLI declines those by omission.
|
|
391
|
-
*
|
|
392
|
-
* Call multiple times to set built-ins incrementally; the last mode given for
|
|
393
|
-
* a built-in wins. Turning one back `'on'` re-checks every registered command
|
|
394
|
-
* for a collision. Call this **before** registering the commands that declare
|
|
395
|
-
* a released flag, since `.command()` rejects the flag while the root still
|
|
396
|
-
* owns the token.
|
|
397
|
-
*
|
|
398
|
-
* @param config - Built-in modes to apply over the current state.
|
|
399
|
-
* @returns The builder (for chaining).
|
|
400
|
-
* @throws {@link CLIError} `INVALID_SCHEMA` when a value is neither `'on'` nor `'off'`.
|
|
401
|
-
* @throws {@link CLIError} `RESERVED_FLAG` when a registered command already
|
|
402
|
-
* declares a flag spelled like a built-in this call keeps or restores.
|
|
403
|
-
* @see {@link BuiltinsConfig} for the accepted keys and modes.
|
|
404
|
-
* @see https://dreamcli.kjanat.dev/guide/output#taking-a-built-in-over
|
|
405
|
-
*
|
|
406
|
-
* @example
|
|
407
|
-
* ```ts
|
|
408
|
-
* // `--json` names the document the command validates.
|
|
409
|
-
* cli('schematool')
|
|
410
|
-
* .builtins({ json: 'off' })
|
|
411
|
-
* .default(
|
|
412
|
-
* command('validate')
|
|
413
|
-
* .flag('json', flag.string().describe('Document to validate'))
|
|
414
|
-
* .action(({ flags, out }) => out.log(flags.json)),
|
|
415
|
-
* )
|
|
416
|
-
* .run();
|
|
417
|
-
* ```
|
|
418
|
-
*/
|
|
419
|
-
builtins(config) {
|
|
420
|
-
const definedConfig = {
|
|
421
|
-
...config.help !== void 0 ? { help: config.help } : {},
|
|
422
|
-
...config.json !== void 0 ? { json: config.json } : {},
|
|
423
|
-
...config.quiet !== void 0 ? { quiet: config.quiet } : {}
|
|
424
|
-
};
|
|
425
|
-
const builtins = normalizeBuiltins({
|
|
426
|
-
...this.schema.builtins,
|
|
427
|
-
...definedConfig
|
|
428
|
-
});
|
|
429
|
-
assertNoReservedFlagCollisions(this.schema.version, [this.schema.defaultCommand, ...this.schema.commands], builtins);
|
|
430
|
-
return rebuild(this, sealCLISchema({
|
|
431
|
-
...this.schema,
|
|
432
|
-
builtins
|
|
433
|
-
}));
|
|
434
|
-
}
|
|
435
|
-
/**
|
|
436
|
-
* Set the program description (shown in root help).
|
|
437
|
-
*
|
|
438
|
-
* @param text - Short description displayed in root help output.
|
|
439
|
-
* @returns The builder (for chaining).
|
|
440
|
-
*/
|
|
441
|
-
description(text) {
|
|
442
|
-
return rebuild(this, {
|
|
443
|
-
...this.schema,
|
|
444
|
-
description: text
|
|
445
|
-
});
|
|
446
|
-
}
|
|
447
|
-
/**
|
|
448
|
-
* Make the root-help header clickable with OSC 8 hyperlinks.
|
|
449
|
-
*
|
|
450
|
-
* Links the program name and version on the first line of root `--help`
|
|
451
|
-
* output in terminals that support
|
|
452
|
-
* [OSC 8 hyperlinks](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda).
|
|
453
|
-
* The escapes are only emitted when stdout is a TTY (overridable via
|
|
454
|
-
* `options.help.hyperlinks`), and only in the header — usage lines, the
|
|
455
|
-
* `--help` hint, the commands table, and completion scripts stay plain.
|
|
456
|
-
*
|
|
457
|
-
* URLs not provided here are derived from manifest metadata when
|
|
458
|
-
* `.manifest()` is active (works with both filesystem discovery and
|
|
459
|
-
* pre-loaded data):
|
|
460
|
-
* - **name** → normalized `repository` URL, falling back to `homepage`
|
|
461
|
-
* - **version** → forge release tag (`{repo}/releases/tag/v{version}` on
|
|
462
|
-
* GitHub, `{repo}/-/releases/v{version}` on GitLab)
|
|
463
|
-
*
|
|
464
|
-
* @param links - Explicit URLs; omit to derive everything from the manifest.
|
|
465
|
-
* @returns The builder (for chaining).
|
|
466
|
-
*
|
|
467
|
-
* @example
|
|
468
|
-
* ```ts
|
|
469
|
-
* // Derive both links from the manifest repository/homepage:
|
|
470
|
-
* cli('mycli')
|
|
471
|
-
* .manifest()
|
|
472
|
-
* .links()
|
|
473
|
-
* .run();
|
|
474
|
-
*
|
|
475
|
-
* // Explicit URLs (no package.json required):
|
|
476
|
-
* cli('mycli')
|
|
477
|
-
* .version('1.0.0')
|
|
478
|
-
* .links({
|
|
479
|
-
* name: 'https://github.com/me/mycli',
|
|
480
|
-
* version: 'https://github.com/me/mycli/releases/tag/v1.0.0',
|
|
481
|
-
* })
|
|
482
|
-
* .run();
|
|
483
|
-
* ```
|
|
484
|
-
*/
|
|
485
|
-
links(links) {
|
|
486
|
-
return rebuild(this, {
|
|
487
|
-
...this.schema,
|
|
488
|
-
helpLinks: {
|
|
489
|
-
name: toUrlString(links?.name),
|
|
490
|
-
version: toUrlString(links?.version)
|
|
491
|
-
}
|
|
492
|
-
});
|
|
493
|
-
}
|
|
494
|
-
/**
|
|
495
|
-
* Configure root-help rendering defaults.
|
|
496
|
-
*
|
|
497
|
-
* Stored on the schema and merged **under** any runtime `options.help`
|
|
498
|
-
* (runtime wins). Call multiple times to set fields incrementally.
|
|
499
|
-
*
|
|
500
|
-
* @param config - Help rendering options (see {@link HelpConfig}).
|
|
501
|
-
* @returns The builder (for chaining).
|
|
502
|
-
*
|
|
503
|
-
* @example
|
|
504
|
-
* ```ts
|
|
505
|
-
* // Echo the default command under Commands and never show the footer:
|
|
506
|
-
* cli('mycli')
|
|
507
|
-
* .help({ showDefaultInCommands: true, footer: false })
|
|
508
|
-
* .default(serve)
|
|
509
|
-
* .run();
|
|
510
|
-
* ```
|
|
511
|
-
*/
|
|
512
|
-
help(config) {
|
|
513
|
-
return rebuild(this, {
|
|
514
|
-
...this.schema,
|
|
515
|
-
helpConfig: {
|
|
516
|
-
...this.schema.helpConfig,
|
|
517
|
-
...config
|
|
518
|
-
}
|
|
519
|
-
});
|
|
520
|
-
}
|
|
521
|
-
/**
|
|
522
|
-
* Enable automatic config file discovery.
|
|
523
|
-
*
|
|
524
|
-
* When enabled, `.run()` probes standard paths before dispatching,
|
|
525
|
-
* first match wins, no merging:
|
|
526
|
-
* 1. Project scope — for `$CWD` and each ancestor directory up to the
|
|
527
|
-
* filesystem root, nearest first:
|
|
528
|
-
* `.{appName}.json`, `{appName}.config.json`, `.config/{appName}.json`
|
|
529
|
-
* 2. User scope — `{dir}/{appName}/config.json` for each user config
|
|
530
|
-
* root (`$XDG_CONFIG_HOME` / `~/.config` on Unix, plus
|
|
531
|
-
* `~/Library/Application Support` on macOS,
|
|
532
|
-
* `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
|
|
533
|
-
* 3. System scope — `/etc/{appName}/config.json` on Linux and macOS
|
|
534
|
-
*
|
|
535
|
-
* The user can override the path via `--config <path>` or `--config=<path>`.
|
|
536
|
-
*
|
|
537
|
-
* Loaded config feeds into the resolution chain
|
|
538
|
-
* (CLI → env → **config** → prompt → default) for flags that
|
|
539
|
-
* declare `.config('dotted.path')`.
|
|
540
|
-
*
|
|
541
|
-
* Has no effect in `.execute()` (which receives config via
|
|
542
|
-
* `options.config` directly).
|
|
543
|
-
*
|
|
544
|
-
* @param appName - Name used to build search paths.
|
|
545
|
-
* @param loaders - Additional {@link FormatLoader}s (JSON is built-in).
|
|
546
|
-
* @returns The builder (for chaining).
|
|
547
|
-
*/
|
|
548
|
-
config(appName, loaders) {
|
|
549
|
-
return rebuild(this, sealCLISchema({
|
|
550
|
-
...this.schema,
|
|
551
|
-
configSettings: {
|
|
552
|
-
appName,
|
|
553
|
-
loaders
|
|
554
|
-
}
|
|
555
|
-
}));
|
|
556
|
-
}
|
|
557
|
-
/**
|
|
558
|
-
* Register a custom config format loader.
|
|
559
|
-
*
|
|
560
|
-
* Adds a {@link FormatLoader} incrementally — call multiple times to
|
|
561
|
-
* register multiple formats. Loaders registered later for the same
|
|
562
|
-
* extension override earlier ones.
|
|
563
|
-
*
|
|
564
|
-
* Requires `.config()` to have been called first (sets the app name).
|
|
565
|
-
*
|
|
566
|
-
* @param loader - Format loader (or extensions + parse function).
|
|
567
|
-
* @returns The builder (for chaining).
|
|
568
|
-
*
|
|
569
|
-
* @example Bun built-in parsers
|
|
570
|
-
* ```ts
|
|
571
|
-
* import { configFormat } from '@kjanat/dreamcli';
|
|
572
|
-
*
|
|
573
|
-
* cli('myapp')
|
|
574
|
-
* .config('myapp')
|
|
575
|
-
* .configLoader(configFormat(['yaml', 'yml'], Bun.YAML.parse))
|
|
576
|
-
* .configLoader(configFormat(['toml'], Bun.TOML.parse))
|
|
577
|
-
* .run();
|
|
578
|
-
* ```
|
|
579
|
-
*
|
|
580
|
-
* @example npm package parsers
|
|
581
|
-
* ```ts
|
|
582
|
-
* import { configFormat } from '@kjanat/dreamcli';
|
|
583
|
-
* import { parse as parseYaml } from 'yaml';
|
|
584
|
-
* import { parse as parseTOML } from '@iarna/toml';
|
|
585
|
-
*
|
|
586
|
-
* cli('myapp')
|
|
587
|
-
* .config('myapp')
|
|
588
|
-
* .configLoader(configFormat(['yaml', 'yml'], parseYaml))
|
|
589
|
-
* .configLoader(configFormat(['toml'], parseTOML))
|
|
590
|
-
* .run();
|
|
591
|
-
* ```
|
|
592
|
-
*/
|
|
593
|
-
configLoader(loader) {
|
|
594
|
-
if (this.schema.configSettings === void 0) throw new CLIError(".configLoader() requires .config() to be called first", {
|
|
595
|
-
code: "INVALID_BUILDER_STATE",
|
|
596
|
-
suggest: "Call .config(appName) before .configLoader()"
|
|
597
|
-
});
|
|
598
|
-
const existing = this.schema.configSettings.loaders ?? [];
|
|
599
|
-
return rebuild(this, sealCLISchema({
|
|
600
|
-
...this.schema,
|
|
601
|
-
configSettings: {
|
|
602
|
-
...this.schema.configSettings,
|
|
603
|
-
loaders: [...existing, loader]
|
|
604
|
-
}
|
|
605
|
-
}));
|
|
606
|
-
}
|
|
607
|
-
manifest(input) {
|
|
608
|
-
const next = buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES);
|
|
609
|
-
assertNoReservedFlagCollisions(next.version, [next.defaultCommand, ...next.commands], next.builtins);
|
|
610
|
-
return rebuild(this, next);
|
|
611
|
-
}
|
|
612
|
-
/**
|
|
613
|
-
* Register a command with the CLI program.
|
|
614
|
-
*
|
|
615
|
-
* The command's schema joins {@link CLISchema.commands}; its handler and
|
|
616
|
-
* subcommand tree are compiled into the builder's execution graph.
|
|
617
|
-
*
|
|
618
|
-
* @param cmd - {@link CommandBuilder} to register.
|
|
619
|
-
* @returns The builder (for chaining).
|
|
620
|
-
* @throws {@link CLIError} `RESERVED_FLAG` when the command, or one of its
|
|
621
|
-
* nested subcommands, spells a root-owned flag (`--json`, `--quiet`/`-q`,
|
|
622
|
-
* `--help`/`-h`, and `--version`/`-V` once
|
|
623
|
-
* {@link CLIBuilder.version | .version()} is set) as a flag name, an alias,
|
|
624
|
-
* or a negated spelling. A built-in released through
|
|
625
|
-
* {@link CLIBuilder.builtins | .builtins()} is not reserved.
|
|
626
|
-
*/
|
|
627
|
-
command(cmd) {
|
|
628
|
-
assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema, this.schema.defaultCommand);
|
|
629
|
-
assertNoReservedFlagCollisions(this.schema.version, [cmd.schema], this.schema.builtins);
|
|
630
|
-
if (this.schema.completionsFlag !== void 0) assertNoCompletionsFlagCollision(cmd.schema);
|
|
631
|
-
const compiled = compiledStateOf(this);
|
|
632
|
-
return CLIBuilder._from({
|
|
633
|
-
...this.schema,
|
|
634
|
-
commands: [...this.schema.commands, cmd.schema]
|
|
635
|
-
}, {
|
|
636
|
-
...compiled,
|
|
637
|
-
commands: [...compiled.commands, compileCommand(cmd)]
|
|
638
|
-
});
|
|
639
|
-
}
|
|
640
|
-
/**
|
|
641
|
-
* Register a command as the default — dispatched when no subcommand is given.
|
|
642
|
-
*
|
|
643
|
-
* The CLI root behaves like a hybrid command group: named subcommands
|
|
644
|
-
* dispatch normally, but empty argv or flags-only argv falls through to
|
|
645
|
-
* this command instead of showing root help.
|
|
646
|
-
*
|
|
647
|
-
* The default command is the CLI's root *surface*: its flags and arguments
|
|
648
|
-
* are rendered inline in root help. By default it is **not** a named
|
|
649
|
-
* subcommand — it cannot be invoked by its own name (`mycli mycmd` does not
|
|
650
|
-
* route to it) and it is omitted from the root `Commands:` list (re-enable
|
|
651
|
-
* listing with `.help({ showDefaultInCommands: true })`). Only one default is
|
|
652
|
-
* allowed.
|
|
653
|
-
*
|
|
654
|
-
* Pass `{ route: true }` to *also* expose the command under its own name as a
|
|
655
|
-
* routable top-level command: `mycli` and `mycli <name>` then run the same
|
|
656
|
-
* command object, and it is listed in `Commands:` beside its siblings. This
|
|
657
|
-
* avoids duplicating the command just to keep both forms equivalent during a
|
|
658
|
-
* v3 migration.
|
|
659
|
-
*
|
|
660
|
-
* @example
|
|
661
|
-
* ```ts
|
|
662
|
-
* // Single-command CLI — no subcommand name needed:
|
|
663
|
-
* // mytool --force production
|
|
664
|
-
* cli('mytool')
|
|
665
|
-
* .default(deploy)
|
|
666
|
-
* .run();
|
|
667
|
-
*
|
|
668
|
-
* // Multi-command CLI with a default:
|
|
669
|
-
* // mytool production → runs deploy
|
|
670
|
-
* // mytool status → runs status
|
|
671
|
-
* cli('mytool')
|
|
672
|
-
* .default(deploy)
|
|
673
|
-
* .command(status)
|
|
674
|
-
* .run();
|
|
675
|
-
*
|
|
676
|
-
* // Default that is also a named route — `mytool` and `mytool status` are
|
|
677
|
-
* // the same surface, and `status` is listed beside `logs`:
|
|
678
|
-
* cli('mytool')
|
|
679
|
-
* .default(status, { route: true })
|
|
680
|
-
* .command(logs)
|
|
681
|
-
* .run();
|
|
682
|
-
* ```
|
|
683
|
-
*
|
|
684
|
-
* @param cmd - {@link CommandBuilder} to register as the default.
|
|
685
|
-
* @param options - Default-command options. `{ route: true }` also exposes
|
|
686
|
-
* the command under its own name (see {@link DefaultCommandOptions}).
|
|
687
|
-
* @returns The builder (for chaining).
|
|
688
|
-
* @throws {@link CLIError} `RESERVED_FLAG` when the command, or one of its
|
|
689
|
-
* nested subcommands, spells a root-owned flag (`--json`, `--quiet`/`-q`,
|
|
690
|
-
* `--help`/`-h`, and `--version`/`-V` once
|
|
691
|
-
* {@link CLIBuilder.version | .version()} is set) as a flag name, an alias,
|
|
692
|
-
* or a negated spelling. A built-in released through
|
|
693
|
-
* {@link CLIBuilder.builtins | .builtins()} is not reserved.
|
|
694
|
-
*/
|
|
695
|
-
default(cmd, options) {
|
|
696
|
-
if (this.schema.defaultCommand !== void 0) throw new CLIError("Only one default command is allowed", {
|
|
697
|
-
code: "DUPLICATE_DEFAULT",
|
|
698
|
-
suggest: "Call .default() only once when building the CLI"
|
|
699
|
-
});
|
|
700
|
-
assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
|
|
701
|
-
assertNoReservedFlagCollisions(this.schema.version, [cmd.schema], this.schema.builtins);
|
|
702
|
-
if (this.schema.completionsFlag !== void 0) assertNoCompletionsFlagCollision(cmd.schema);
|
|
703
|
-
const compiled = compiledStateOf(this);
|
|
704
|
-
return CLIBuilder._from({
|
|
705
|
-
...this.schema,
|
|
706
|
-
defaultCommand: cmd.schema,
|
|
707
|
-
defaultCommandRouted: options?.route ?? false
|
|
708
|
-
}, {
|
|
709
|
-
...compiled,
|
|
710
|
-
defaultCommand: compileCommand(cmd)
|
|
711
|
-
});
|
|
712
|
-
}
|
|
713
|
-
/**
|
|
714
|
-
* Register a CLI plugin.
|
|
715
|
-
*
|
|
716
|
-
* Plugins run in registration order. At each lifecycle stage, all hooks for
|
|
717
|
-
* the first plugin run before hooks for the second plugin, and so on.
|
|
718
|
-
*
|
|
719
|
-
* @param definition - A frozen {@link CLIPlugin} created by {@link plugin}.
|
|
720
|
-
* @returns The builder (for chaining).
|
|
721
|
-
* @see {@link plugin} to construct plugin definitions.
|
|
722
|
-
*/
|
|
723
|
-
plugin(definition) {
|
|
724
|
-
const compiled = compiledStateOf(this);
|
|
725
|
-
return CLIBuilder._from(this.schema, {
|
|
726
|
-
...compiled,
|
|
727
|
-
plugins: [...compiled.plugins, definition]
|
|
728
|
-
});
|
|
729
|
-
}
|
|
730
|
-
/**
|
|
731
|
-
* Register built-in shell completion.
|
|
732
|
-
*
|
|
733
|
-
* By default (`{ as: 'command' }`) this registers a `completions` subcommand
|
|
734
|
-
* that accepts a `shell` argument and writes the script to stdout. With
|
|
735
|
-
* `{ as: 'flag' }` it instead exposes an eager `--completions <shell>` flag on
|
|
736
|
-
* the CLI root — no subcommand is registered, so a default command stays the
|
|
737
|
-
* lone root surface. The flag may be given without a value to auto-detect the
|
|
738
|
-
* shell from `$SHELL` / `$PSModulePath`.
|
|
739
|
-
*
|
|
740
|
-
* In subcommand mode, call this **after** registering all other commands so
|
|
741
|
-
* the completion script includes the full command set: that path snapshots the
|
|
742
|
-
* schema (and completion options) at call time, so commands registered
|
|
743
|
-
* afterwards will not appear in that subcommand's generated script. In flag
|
|
744
|
-
* mode, generation runs at execution time from the final builder schema, so
|
|
745
|
-
* registration order does not matter.
|
|
746
|
-
*
|
|
747
|
-
* @example
|
|
748
|
-
* ```ts
|
|
749
|
-
* // Subcommand form (default):
|
|
750
|
-
* cli('mycli')
|
|
751
|
-
* .version('1.0.0')
|
|
752
|
-
* .command(deploy)
|
|
753
|
-
* .completions({ rootMode: 'surface' })
|
|
754
|
-
* .run();
|
|
755
|
-
*
|
|
756
|
-
* // Eager-flag form, ideal for single-command CLIs:
|
|
757
|
-
* cli('mycli')
|
|
758
|
-
* .completions({ as: 'flag' })
|
|
759
|
-
* .default(serve)
|
|
760
|
-
* .run();
|
|
761
|
-
* ```
|
|
762
|
-
*/
|
|
763
|
-
completions(options) {
|
|
764
|
-
if (this.schema.hasBuiltInCompletions) throw new CLIError(".completions() has already been called", {
|
|
765
|
-
code: "DUPLICATE_COMMAND",
|
|
766
|
-
suggest: "Call .completions() only once when building the CLI"
|
|
767
|
-
});
|
|
768
|
-
if (options?.as === "flag") {
|
|
769
|
-
if (this.schema.defaultCommand !== void 0) assertNoCompletionsFlagCollision(this.schema.defaultCommand);
|
|
770
|
-
for (const registered of this.schema.commands) assertNoCompletionsFlagCollision(registered);
|
|
771
|
-
return rebuild(this, {
|
|
772
|
-
...this.schema,
|
|
773
|
-
hasBuiltInCompletions: true,
|
|
774
|
-
completionsFlag: {
|
|
775
|
-
shells: SHELLS,
|
|
776
|
-
options
|
|
777
|
-
}
|
|
778
|
-
});
|
|
779
|
-
}
|
|
780
|
-
const cliSchema = this.schema;
|
|
781
|
-
const completionOptions = options;
|
|
782
|
-
const cmd = command("completions").alias("completion").description("Generate shell completion script").arg("shell", arg.custom((raw) => {
|
|
783
|
-
const shell = normalizeShell(raw);
|
|
784
|
-
if (shell === void 0) throw new Error(`Unknown shell '${raw}'. Valid shells: ${SHELLS.join(", ")}`);
|
|
785
|
-
return shell;
|
|
786
|
-
}).env("SHELL").describe(`Target shell (${SHELLS.join(", ")})`)).action(({ args, meta, out }) => {
|
|
787
|
-
const completionSchema = meta.bin === cliSchema.name ? cliSchema : {
|
|
788
|
-
...cliSchema,
|
|
789
|
-
name: meta.bin
|
|
790
|
-
};
|
|
791
|
-
const script = generateCompletion(completionSchema, args.shell, completionOptions);
|
|
792
|
-
if (out.jsonMode) out.json({
|
|
793
|
-
shell: args.shell,
|
|
794
|
-
script
|
|
795
|
-
});
|
|
796
|
-
else out.log(script);
|
|
797
|
-
});
|
|
798
|
-
const withCompletions = this.command(cmd);
|
|
799
|
-
return rebuild(withCompletions, {
|
|
800
|
-
...withCompletions.schema,
|
|
801
|
-
hasBuiltInCompletions: true
|
|
802
|
-
});
|
|
803
|
-
}
|
|
804
|
-
/**
|
|
805
|
-
* Execute the CLI program against explicit argv.
|
|
806
|
-
*
|
|
807
|
-
* This is the testable execution path — no process state is touched.
|
|
808
|
-
* Returns a structured {@linkcode RunResult} with exit code and captured output.
|
|
809
|
-
*
|
|
810
|
-
* @param argv - Raw argv tokens (NOT including the binary/script path,
|
|
811
|
-
* i.e. equivalent to `process.argv.slice(2)`).
|
|
812
|
-
* @param options - Injectable runtime state.
|
|
813
|
-
* @returns Structured result with exit code and captured output.
|
|
814
|
-
*/
|
|
815
|
-
async execute(argv, options) {
|
|
816
|
-
return executeCLI(this, argv, options);
|
|
817
|
-
}
|
|
818
|
-
/**
|
|
819
|
-
* Run the CLI program as a production entry point.
|
|
820
|
-
*
|
|
821
|
-
* Reads argv from the runtime adapter, dispatches to the matched
|
|
822
|
-
* command, writes output to real streams, and exits the process.
|
|
823
|
-
*
|
|
824
|
-
* This is the **only** place that touches process state (via the
|
|
825
|
-
* adapter). For testing, use `.execute()` instead — or provide a
|
|
826
|
-
* test adapter via `options.adapter`.
|
|
827
|
-
*
|
|
828
|
-
* Defaults to {@linkcode createAdapter | createAdapter()} when no adapter is provided,
|
|
829
|
-
* which auto-detects the runtime (Node.js, Bun) and creates
|
|
830
|
-
* the appropriate adapter.
|
|
831
|
-
*
|
|
832
|
-
* @param options - Optional runtime configuration including adapter.
|
|
833
|
-
*/
|
|
834
|
-
async run(options) {
|
|
835
|
-
const adapter = options?.adapter ?? createAdapter();
|
|
836
|
-
const inheritedName = this.schema.inheritName ? inferInvocationName(adapter.argv) : void 0;
|
|
837
|
-
const compiled = compiledStateOf(this);
|
|
838
|
-
const preflight = await prepareRuntimePreflight({
|
|
839
|
-
schema: this.schema,
|
|
840
|
-
compiled,
|
|
841
|
-
adapter,
|
|
842
|
-
options,
|
|
843
|
-
inheritedName
|
|
844
|
-
});
|
|
845
|
-
if (preflight.kind === "startup-error") {
|
|
846
|
-
if (preflight.jsonMode) adapter.stdout(`${JSON.stringify({ error: preflight.error.toJSON() })}\n`);
|
|
847
|
-
else {
|
|
848
|
-
adapter.stderr(`Error: ${preflight.error.message}\n`);
|
|
849
|
-
if (preflight.error.suggest !== void 0) adapter.stderr(`Suggestion: ${preflight.error.suggest}\n`);
|
|
850
|
-
}
|
|
851
|
-
return adapter.exit(preflight.error.exitCode);
|
|
852
|
-
}
|
|
853
|
-
const effectiveBuilder = preflight.schema === this.schema ? this : rebuild(this, sealCLISchema({
|
|
854
|
-
...this.schema,
|
|
855
|
-
...preflight.schema
|
|
856
|
-
}));
|
|
857
|
-
const terminalSize = adapter.getTerminalSize();
|
|
858
|
-
const runtimeHelpWidth = options?.help?.width === void 0 && preflight.schema.helpConfig?.width === void 0 ? terminalSize?.columns : void 0;
|
|
859
|
-
const runtimeHelpOptions = runtimeHelpWidth !== void 0 ? {
|
|
860
|
-
...options?.help,
|
|
861
|
-
width: runtimeHelpWidth
|
|
862
|
-
} : options?.help;
|
|
863
|
-
const hyperlinkOverride = resolveEffectiveHyperlinkOverride(runtimeHelpOptions, effectiveBuilder.schema.helpConfig, adapter.env, adapter.argv);
|
|
864
|
-
const executeOptions = {
|
|
865
|
-
...options,
|
|
866
|
-
...preflight.inputs,
|
|
867
|
-
...runtimeHelpOptions !== void 0 ? { help: runtimeHelpOptions } : {},
|
|
868
|
-
out: createOutput({
|
|
869
|
-
stdout: adapter.stdout,
|
|
870
|
-
stderr: adapter.stderr,
|
|
871
|
-
jsonMode: preflight.inputs.jsonMode,
|
|
872
|
-
isTTY: preflight.inputs.isTTY,
|
|
873
|
-
...preflight.inputs.verbosity !== "normal" ? { verbosity: preflight.inputs.verbosity } : {},
|
|
874
|
-
...hyperlinksOption(hyperlinkOverride)
|
|
875
|
-
})
|
|
876
|
-
};
|
|
877
|
-
const result = await executeCLI(effectiveBuilder, preflight.filteredArgv, executeOptions);
|
|
878
|
-
for (const line of result.stdout) adapter.stdout(line);
|
|
879
|
-
for (const line of result.stderr) adapter.stderr(line);
|
|
880
|
-
return adapter.exit(result.exitCode);
|
|
881
|
-
}
|
|
882
|
-
};
|
|
883
|
-
/**
|
|
884
|
-
* Execution body shared by {@linkcode CLIBuilder.execute} and {@linkcode CLIBuilder.run},
|
|
885
|
-
* accepting the framework-populated output channel and plugin fields.
|
|
886
|
-
*
|
|
887
|
-
* @param builder - Builder supplying the schema and compiled command graph.
|
|
888
|
-
* @param argv - Raw argv tokens (NOT including the binary/script path).
|
|
889
|
-
* @param options - Injectable runtime state plus framework-populated fields.
|
|
890
|
-
* @returns Structured result with exit code and captured output.
|
|
891
|
-
*
|
|
892
|
-
* @internal
|
|
893
|
-
*/
|
|
894
|
-
async function executeCLI(builder, argv, options) {
|
|
895
|
-
const rootOutputFlags = readRootOutputFlags(argv, builder.schema.builtins);
|
|
896
|
-
const jsonMode = resolveRootJsonMode(rootOutputFlags, options?.jsonMode);
|
|
897
|
-
const verbosity = resolveRootVerbosity(rootOutputFlags, options?.verbosity);
|
|
898
|
-
const hyperlinkOverride = resolveEffectiveHyperlinkOverride(options?.help, builder.schema.helpConfig, options?.env ?? {}, argv);
|
|
899
|
-
const captureOptions = {
|
|
900
|
-
...verbosity !== void 0 ? { verbosity } : {},
|
|
901
|
-
...jsonMode ? { jsonMode } : {},
|
|
902
|
-
...options?.isTTY !== void 0 ? { isTTY: options.isTTY } : {},
|
|
903
|
-
...hyperlinksOption(hyperlinkOverride)
|
|
904
|
-
};
|
|
905
|
-
let out;
|
|
906
|
-
let captured;
|
|
907
|
-
if (options?.out !== void 0) {
|
|
908
|
-
out = options.out;
|
|
909
|
-
captured = options.captured ?? {
|
|
910
|
-
stdout: [],
|
|
911
|
-
stderr: [],
|
|
912
|
-
activity: []
|
|
913
|
-
};
|
|
914
|
-
} else [out, captured] = createCaptureOutput(Object.keys(captureOptions).length > 0 ? captureOptions : void 0);
|
|
915
|
-
clearRequestedExitCode(out);
|
|
916
|
-
const resolvedVersion = options?.help?.version ?? builder.schema.version;
|
|
917
|
-
const helpOptions = {
|
|
918
|
-
...builder.schema.helpConfig,
|
|
919
|
-
...options?.help,
|
|
920
|
-
binName: options?.help?.binName ?? builder.schema.name,
|
|
921
|
-
hyperlinks: out.isHyperlinkSupported,
|
|
922
|
-
colors: options?.help?.colors ?? out.color,
|
|
923
|
-
...resolvedVersion !== void 0 ? { version: resolvedVersion } : {}
|
|
924
|
-
};
|
|
925
|
-
const compiled = compiledStateOf(builder);
|
|
926
|
-
const flagSettings = options?.flags ?? builder.schema.flagSettings;
|
|
927
|
-
const effectiveOptions = {
|
|
928
|
-
...options,
|
|
929
|
-
plugins: compiled.plugins,
|
|
930
|
-
builtins: builder.schema.builtins,
|
|
931
|
-
...jsonMode ? { jsonMode } : {},
|
|
932
|
-
...verbosity !== void 0 ? { verbosity } : {},
|
|
933
|
-
...flagSettings !== void 0 ? { flags: flagSettings } : {}
|
|
934
|
-
};
|
|
935
|
-
const output = {
|
|
936
|
-
jsonMode,
|
|
937
|
-
isTTY: out.isTTY,
|
|
938
|
-
verbosity: verbosity ?? "normal"
|
|
939
|
-
};
|
|
940
|
-
const planSchema = options?.flags !== void 0 ? {
|
|
941
|
-
...builder.schema,
|
|
942
|
-
flagSettings
|
|
943
|
-
} : builder.schema;
|
|
944
|
-
const planned = planInvocation({
|
|
945
|
-
schema: planSchema,
|
|
946
|
-
compiled,
|
|
947
|
-
argv,
|
|
948
|
-
help: helpOptions,
|
|
949
|
-
output
|
|
950
|
-
});
|
|
951
|
-
switch (planned.kind) {
|
|
952
|
-
case "root-version":
|
|
953
|
-
out.log(planned.version);
|
|
954
|
-
return buildRunResult({
|
|
955
|
-
exitCode: 0,
|
|
956
|
-
error: void 0
|
|
957
|
-
}, captured);
|
|
958
|
-
case "root-completions": {
|
|
959
|
-
const shell = planned.shell ?? detectShell(options?.env ?? {});
|
|
960
|
-
if (shell === void 0) {
|
|
961
|
-
const error = new CLIError("Could not detect shell", {
|
|
962
|
-
code: "MISSING_VALUE",
|
|
963
|
-
suggest: `Pass one explicitly, e.g. '${helpOptions.binName} --completions zsh'`
|
|
964
|
-
});
|
|
965
|
-
if (jsonMode) out.json({ error: error.toJSON() });
|
|
966
|
-
else {
|
|
967
|
-
out.error(error.message);
|
|
968
|
-
out.error(`Suggestion: ${error.suggest}`);
|
|
969
|
-
}
|
|
970
|
-
return buildRunResult({
|
|
971
|
-
exitCode: error.exitCode,
|
|
972
|
-
error
|
|
973
|
-
}, captured);
|
|
974
|
-
}
|
|
975
|
-
const completionSchema = helpOptions.binName === void 0 || helpOptions.binName === builder.schema.name ? builder.schema : {
|
|
976
|
-
...builder.schema,
|
|
977
|
-
name: helpOptions.binName
|
|
978
|
-
};
|
|
979
|
-
const script = generateCompletion(completionSchema, shell, planned.options);
|
|
980
|
-
if (jsonMode) out.json({
|
|
981
|
-
shell,
|
|
982
|
-
script
|
|
983
|
-
});
|
|
984
|
-
else out.log(script);
|
|
985
|
-
return buildRunResult({
|
|
986
|
-
exitCode: 0,
|
|
987
|
-
error: void 0
|
|
988
|
-
}, captured);
|
|
989
|
-
}
|
|
990
|
-
case "root-help":
|
|
991
|
-
if (jsonMode) out.json(generateSchema(builder.schema, void 0, {
|
|
992
|
-
name: planned.help.binName ?? builder.schema.name,
|
|
993
|
-
version: planned.help.version ?? builder.schema.version
|
|
994
|
-
}));
|
|
995
|
-
else {
|
|
996
|
-
const helpText = formatRootHelp(resolveHelpLinksSchema(builder.schema), planned.help);
|
|
997
|
-
out.log(helpText);
|
|
998
|
-
}
|
|
999
|
-
return buildRunResult({
|
|
1000
|
-
exitCode: 0,
|
|
1001
|
-
error: void 0
|
|
1002
|
-
}, captured);
|
|
1003
|
-
case "dispatch-error":
|
|
1004
|
-
if (jsonMode) out.json({ error: planned.error.toJSON() });
|
|
1005
|
-
else {
|
|
1006
|
-
out.error(planned.error.message);
|
|
1007
|
-
if (planned.error.suggest !== void 0 && planned.error.code !== "NO_ACTION") out.error(`Suggestion: ${planned.error.suggest}`);
|
|
1008
|
-
}
|
|
1009
|
-
return buildRunResult({
|
|
1010
|
-
exitCode: planned.error.exitCode,
|
|
1011
|
-
error: planned.error
|
|
1012
|
-
}, captured);
|
|
1013
|
-
case "needs-subcommand":
|
|
1014
|
-
if (jsonMode) out.json(generateCommandSchema(planned.command.schema, void 0, {
|
|
1015
|
-
name: planned.help.binName ?? planned.command.schema.name,
|
|
1016
|
-
version: planned.help.version
|
|
1017
|
-
}));
|
|
1018
|
-
else {
|
|
1019
|
-
const helpText = formatHelp(planned.command.schema, planned.help);
|
|
1020
|
-
out.log(helpText);
|
|
1021
|
-
}
|
|
1022
|
-
return buildRunResult({
|
|
1023
|
-
exitCode: 0,
|
|
1024
|
-
error: void 0
|
|
1025
|
-
}, captured);
|
|
1026
|
-
case "match": {
|
|
1027
|
-
const commandRunOptions = buildCommandRunOptions(effectiveOptions, planned.plan.help ?? helpOptions, planned.plan.meta);
|
|
1028
|
-
const result = await executeCommand({
|
|
1029
|
-
command: {
|
|
1030
|
-
handler: planned.plan.command.handler,
|
|
1031
|
-
steps: planned.plan.command.steps
|
|
1032
|
-
},
|
|
1033
|
-
argv: planned.plan.argv,
|
|
1034
|
-
out,
|
|
1035
|
-
schema: planned.plan.mergedSchema,
|
|
1036
|
-
meta: planned.plan.meta,
|
|
1037
|
-
options: commandRunOptions
|
|
1038
|
-
});
|
|
1039
|
-
return buildRunResult(result, captured);
|
|
1040
|
-
}
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
|
-
const RUNTIME_BINARIES = /* @__PURE__ */ new Set([
|
|
1044
|
-
"bun",
|
|
1045
|
-
"deno",
|
|
1046
|
-
"node",
|
|
1047
|
-
"tsx"
|
|
1048
|
-
]);
|
|
1049
|
-
/**
|
|
1050
|
-
* Extract the final path segment from a path-like or URL-like string.
|
|
1051
|
-
*
|
|
1052
|
-
* @param input - Forward- or backslash-delimited path.
|
|
1053
|
-
* @returns Trailing segment, or `undefined` when the input is empty or slash-only.
|
|
1054
|
-
*
|
|
1055
|
-
* @internal
|
|
1056
|
-
*/
|
|
1057
|
-
function basename(input) {
|
|
1058
|
-
const trimmed = stripTrailing(input, [47, 92]);
|
|
1059
|
-
if (trimmed.length === 0) return void 0;
|
|
1060
|
-
const slashIdx = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
|
|
1061
|
-
const name = slashIdx >= 0 ? trimmed.slice(slashIdx + 1) : trimmed;
|
|
1062
|
-
return name.length > 0 ? name : void 0;
|
|
1063
|
-
}
|
|
1064
|
-
/**
|
|
1065
|
-
* Detect known interpreter/runtime binary names (node, bun, deno, tsx).
|
|
1066
|
-
*
|
|
1067
|
-
* @param input - Candidate binary name, with or without `.exe` suffix.
|
|
1068
|
-
* @returns `true` when `input` matches a known runtime after normalization.
|
|
1069
|
-
*
|
|
1070
|
-
* @internal
|
|
1071
|
-
*/
|
|
1072
|
-
function isRuntimeBinaryName(input) {
|
|
1073
|
-
const normalized = input.toLowerCase().replace(/\.exe$/i, "");
|
|
1074
|
-
return RUNTIME_BINARIES.has(normalized);
|
|
1075
|
-
}
|
|
1076
|
-
/**
|
|
1077
|
-
* Infer the displayed CLI name from the current runtime invocation.
|
|
1078
|
-
*
|
|
1079
|
-
* Resolution order:
|
|
1080
|
-
* 1. Node/Bun/tsx-style interpreters → script/entry argument basename
|
|
1081
|
-
* 2. Standalone executable invocations → argv[0] basename
|
|
1082
|
-
* 3. `undefined` when no stable entrypoint can be inferred (e.g. Deno synthetic argv)
|
|
1083
|
-
*
|
|
1084
|
-
* @param argv - Full process argv (typically `process.argv` or adapter equivalent).
|
|
1085
|
-
* @returns Inferred program name, or `undefined` when inference is ambiguous.
|
|
1086
|
-
*
|
|
1087
|
-
* @internal
|
|
1088
|
-
*/
|
|
1089
|
-
function inferInvocationName(argv) {
|
|
1090
|
-
const argv0 = argv[0];
|
|
1091
|
-
const argv1 = argv[1];
|
|
1092
|
-
const runtimeName = argv0 !== void 0 ? basename(argv0) : void 0;
|
|
1093
|
-
if (runtimeName !== void 0 && isRuntimeBinaryName(runtimeName)) {
|
|
1094
|
-
if (runtimeName === "bun" && argv1 === "run") {
|
|
1095
|
-
const entryArg = argv[2];
|
|
1096
|
-
if (entryArg === void 0 || entryArg.startsWith("-")) return void 0;
|
|
1097
|
-
return basename(entryArg);
|
|
1098
|
-
}
|
|
1099
|
-
if (runtimeName === "deno" && argv1 === "run") return void 0;
|
|
1100
|
-
if (argv1 === void 0 || argv1.startsWith("-")) return void 0;
|
|
1101
|
-
return basename(argv1);
|
|
1102
|
-
}
|
|
1103
|
-
return argv0 !== void 0 ? basename(argv0) : void 0;
|
|
1104
|
-
}
|
|
1105
|
-
/** Coerce a `string | URL` link input to its string form. @internal */
|
|
1106
|
-
function toUrlString(value) {
|
|
1107
|
-
if (value === void 0) return void 0;
|
|
1108
|
-
return value instanceof URL ? value.href : value;
|
|
1109
|
-
}
|
|
1110
|
-
/**
|
|
1111
|
-
* Resolve derived help links against pre-loaded manifest data.
|
|
1112
|
-
*
|
|
1113
|
-
* `.run()` resolves links during runtime preflight (where discovered manifest
|
|
1114
|
-
* metadata lives); this covers the filesystem-free `.execute()` path, where
|
|
1115
|
-
* only the `.manifest(data)` overload can contribute. Idempotent —
|
|
1116
|
-
* already-resolved fields pass through unchanged.
|
|
1117
|
-
*
|
|
1118
|
-
* @internal
|
|
1119
|
-
*/
|
|
1120
|
-
function resolveHelpLinksSchema(schema) {
|
|
1121
|
-
if (schema.helpLinks === void 0) return schema;
|
|
1122
|
-
return {
|
|
1123
|
-
...schema,
|
|
1124
|
-
helpLinks: deriveHelpLinks(schema.helpLinks, schema.packageJsonSettings?.data, schema.version)
|
|
1125
|
-
};
|
|
1126
|
-
}
|
|
1127
|
-
/** Default manifest filenames for `.manifest()`. @internal */
|
|
1128
|
-
const DEFAULT_MANIFEST_FILES = ["package.json"];
|
|
1129
|
-
/**
|
|
1130
|
-
* Normalise an {@link InferNameOption} into the flat `{ inferName, stripScope }`
|
|
1131
|
-
* pair stored in {@link ResolvedManifestSettings}.
|
|
1132
|
-
*
|
|
1133
|
-
* @internal
|
|
1134
|
-
*/
|
|
1135
|
-
function normalizeInferName(option) {
|
|
1136
|
-
if (option === void 0 || option === false) return {
|
|
1137
|
-
inferName: false,
|
|
1138
|
-
stripScope: true
|
|
1139
|
-
};
|
|
1140
|
-
if (option === true) return {
|
|
1141
|
-
inferName: true,
|
|
1142
|
-
stripScope: true
|
|
1143
|
-
};
|
|
1144
|
-
return {
|
|
1145
|
-
inferName: true,
|
|
1146
|
-
stripScope: option.scope !== "keep"
|
|
1147
|
-
};
|
|
1148
|
-
}
|
|
1149
|
-
/**
|
|
1150
|
-
* Build the next {@link CLISchema} for {@link CLIBuilder.manifest}.
|
|
1151
|
-
*
|
|
1152
|
-
* The data overload (detected via field shape) merges `version`/`description`
|
|
1153
|
-
* immediately so `.execute()` sees them; the settings overload stores discovery
|
|
1154
|
-
* config for runtime preflight.
|
|
1155
|
-
*
|
|
1156
|
-
* @internal
|
|
1157
|
-
*/
|
|
1158
|
-
function buildManifestSchema(schema, input, defaultFiles) {
|
|
1159
|
-
if (isPackageJsonData(input)) return {
|
|
1160
|
-
...schema,
|
|
1161
|
-
...schema.version === void 0 && input.version !== void 0 ? { version: input.version } : {},
|
|
1162
|
-
...schema.description === void 0 && input.description !== void 0 ? { description: input.description } : {},
|
|
1163
|
-
packageJsonSettings: {
|
|
1164
|
-
inferName: false,
|
|
1165
|
-
stripScope: true,
|
|
1166
|
-
from: void 0,
|
|
1167
|
-
files: defaultFiles,
|
|
1168
|
-
data: input
|
|
1169
|
-
}
|
|
1170
|
-
};
|
|
1171
|
-
const { inferName, stripScope } = normalizeInferName(input?.inferName);
|
|
1172
|
-
const files = input?.files ?? defaultFiles;
|
|
1173
|
-
return {
|
|
1174
|
-
...schema,
|
|
1175
|
-
packageJsonSettings: {
|
|
1176
|
-
inferName,
|
|
1177
|
-
stripScope,
|
|
1178
|
-
from: normalizeFromSetting(input?.from),
|
|
1179
|
-
files,
|
|
1180
|
-
data: void 0
|
|
1181
|
-
}
|
|
1182
|
-
};
|
|
1183
|
-
}
|
|
1184
|
-
/**
|
|
1185
|
-
* Coerce a {@link ResolvedManifestSettings.from | `manifest.from`} input
|
|
1186
|
-
* (string path, `file:` URL string, {@link URL} instance, or `import.meta`) to
|
|
1187
|
-
* a plain filesystem path string. `undefined` passes through unchanged.
|
|
1188
|
-
*
|
|
1189
|
-
* Runtime-agnostic by design — relies only on the `URL` global (available in
|
|
1190
|
-
* every JS runtime) rather than `node:url`, keeping core free of Node
|
|
1191
|
-
* built-ins. Non-`file:` inputs are returned unchanged as paths.
|
|
1192
|
-
*
|
|
1193
|
-
* @internal
|
|
1194
|
-
*/
|
|
1195
|
-
function normalizeFromSetting(from) {
|
|
1196
|
-
if (from === void 0) return void 0;
|
|
1197
|
-
const source = typeof from === "object" && !(from instanceof URL) ? from.url : from;
|
|
1198
|
-
if (source instanceof URL) {
|
|
1199
|
-
if (source.protocol !== "file:") return source.href;
|
|
1200
|
-
} else if (!source.startsWith("file:")) return source;
|
|
1201
|
-
const decoded = decodeURIComponent(new URL(source).pathname);
|
|
1202
|
-
if (/^\/[A-Za-z]:/.test(decoded)) return decoded.slice(1).replace(/\//g, "\\");
|
|
1203
|
-
return decoded;
|
|
1204
|
-
}
|
|
1205
|
-
/**
|
|
1206
|
-
* Predicate distinguishing the {@link PackageJsonData | data} overload of
|
|
1207
|
-
* `.manifest()` from the settings overload at runtime.
|
|
1208
|
-
*
|
|
1209
|
-
* A value is treated as `PackageJsonData` when it's a plain object that
|
|
1210
|
-
* carries at least one recognised field (`name`, `version`, `description`,
|
|
1211
|
-
* `bin`, `homepage`, or `repository`). An empty `{}` or a settings-shaped
|
|
1212
|
-
* object (`inferName` / `from`) falls through to the settings overload.
|
|
1213
|
-
*
|
|
1214
|
-
* npm's `files` field (publish globs) is intentionally NOT recognised here, so
|
|
1215
|
-
* an object whose only key is `files` routes to the settings overload — where
|
|
1216
|
-
* `files` means candidate manifest filenames, never publish globs. Manifests
|
|
1217
|
-
* that publish a CLI carry `name`/`version`, so those route to the data overload
|
|
1218
|
-
* as expected.
|
|
1219
|
-
*
|
|
1220
|
-
* Edge case: a metadata-less manifest (e.g. a versionless private-root
|
|
1221
|
-
* `package.json` carrying only `files`/`private`) routes to settings, so its
|
|
1222
|
-
* `files` would be read as candidate filenames and the object is not stored as
|
|
1223
|
-
* data. This is harmless in practice — a metadata-less manifest contributes no
|
|
1224
|
-
* `version`/`description` either way — but it means a pre-loaded object must
|
|
1225
|
-
* carry real metadata to be honoured as data.
|
|
1226
|
-
*
|
|
1227
|
-
* @internal
|
|
1228
|
-
*/
|
|
1229
|
-
function isPackageJsonData(value) {
|
|
1230
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
1231
|
-
return "name" in value || "version" in value || "description" in value || "bin" in value || "homepage" in value || "repository" in value;
|
|
1232
|
-
}
|
|
1233
|
-
function cli(nameOrOptions, extraOptions) {
|
|
1234
|
-
const options = typeof nameOrOptions === "string" ? {
|
|
1235
|
-
name: nameOrOptions,
|
|
1236
|
-
...extraOptions
|
|
1237
|
-
} : nameOrOptions;
|
|
1238
|
-
const name = options.name ?? "cli";
|
|
1239
|
-
const inheritName = options.inherit ?? false;
|
|
1240
|
-
return CLIBuilder._from(createCLISchema({
|
|
1241
|
-
name,
|
|
1242
|
-
inheritName,
|
|
1243
|
-
flagSettings: options.flags
|
|
1244
|
-
}), {
|
|
1245
|
-
commands: [],
|
|
1246
|
-
defaultCommand: void 0,
|
|
1247
|
-
plugins: []
|
|
1248
|
-
});
|
|
1249
|
-
}
|
|
1250
|
-
/**
|
|
1251
|
-
* Report whether the calling module is the process entrypoint, cross-runtime.
|
|
1252
|
-
*
|
|
1253
|
-
* Node, Bun, and Deno set `import.meta.main` on the module invoked directly;
|
|
1254
|
-
* projects with the runtime's ambient types can read that property directly.
|
|
1255
|
-
* This helper is a compatibility form for projects whose `tsconfig.json` `lib`
|
|
1256
|
-
* override drops those `ImportMeta` extras: passing `import.meta` whole avoids
|
|
1257
|
-
* a direct `.main` access without requiring global augmentation.
|
|
1258
|
-
*
|
|
1259
|
-
* @param meta - The calling module's `import.meta`.
|
|
1260
|
-
* @returns `true` when the module was run as the entrypoint.
|
|
1261
|
-
*
|
|
1262
|
-
* @example
|
|
1263
|
-
* ```ts
|
|
1264
|
-
* if (isMainModule(import.meta)) cli('mycli').command(deploy).run();
|
|
1265
|
-
* ```
|
|
1266
|
-
*/
|
|
1267
|
-
function isMainModule(meta) {
|
|
1268
|
-
return meta.main === true;
|
|
1269
|
-
}
|
|
1270
|
-
//#endregion
|
|
1271
|
-
export { CLIBuilder, cli, compiledStateOf, createCLISchema, executeCLI, isMainModule, plugin, resolveRenderContext };
|