@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.10
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/CHANGELOG.md +217 -1
- package/dist/core/cli/dispatch.d.mts +6 -5
- package/dist/core/cli/dispatch.mjs +205 -1
- package/dist/core/cli/help-links.d.mts +0 -1
- package/dist/core/cli/help-links.mjs +41 -1
- package/dist/core/cli/index.d.mts +81 -8
- package/dist/core/cli/index.mjs +945 -1
- package/dist/core/cli/planner.d.mts +5 -1
- package/dist/core/cli/planner.mjs +300 -1
- package/dist/core/cli/plugin.d.mts +1 -1
- package/dist/core/cli/plugin.mjs +41 -1
- package/dist/core/cli/propagate.d.mts +1 -1
- package/dist/core/cli/propagate.mjs +57 -1
- package/dist/core/cli/root-help.d.mts +2 -1
- package/dist/core/cli/root-help.mjs +226 -4
- package/dist/core/cli/root-surface.d.mts +12 -1
- package/dist/core/cli/root-surface.mjs +28 -1
- package/dist/core/cli/runtime-preflight.d.mts +14 -2
- package/dist/core/cli/runtime-preflight.mjs +169 -1
- package/dist/core/completion/index.d.mts +0 -1
- package/dist/core/completion/index.mjs +90 -1
- package/dist/core/completion/shells/bash.d.mts +0 -1
- package/dist/core/completion/shells/bash.mjs +308 -3
- package/dist/core/completion/shells/fish.d.mts +0 -1
- package/dist/core/completion/shells/fish.mjs +162 -2
- package/dist/core/completion/shells/powershell.d.mts +0 -1
- package/dist/core/completion/shells/powershell.mjs +358 -2
- package/dist/core/completion/shells/shared.d.mts +13 -2
- package/dist/core/completion/shells/shared.mjs +176 -1
- package/dist/core/completion/shells/zsh.d.mts +0 -1
- package/dist/core/completion/shells/zsh.mjs +251 -2
- package/dist/core/config/index.d.mts +2 -3
- package/dist/core/config/index.mjs +246 -1
- package/dist/core/config/package-json.d.mts +27 -4
- package/dist/core/config/package-json.mjs +386 -3
- package/dist/core/errors/index.d.mts +3 -3
- package/dist/core/errors/index.mjs +87 -1
- package/dist/core/execution/index.d.mts +0 -1
- package/dist/core/execution/index.mjs +201 -1
- package/dist/core/help/ansi.d.mts +11 -5
- package/dist/core/help/ansi.mjs +121 -2
- package/dist/core/help/index.d.mts +22 -3
- package/dist/core/help/index.mjs +341 -7
- package/dist/core/help/theme.d.mts +68 -0
- package/dist/core/help/theme.mjs +46 -0
- package/dist/core/json-schema/index.d.mts +15 -2
- package/dist/core/json-schema/index.mjs +536 -12
- package/dist/core/json-schema/meta-descriptions.generated.d.mts +55 -38
- package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
- package/dist/core/output/activity.d.mts +0 -1
- package/dist/core/output/activity.mjs +452 -1
- package/dist/core/output/bind.mjs +56 -1
- package/dist/core/output/contracts.d.mts +4 -5
- package/dist/core/output/contracts.mjs +57 -1
- package/dist/core/output/display-value.mjs +32 -1
- package/dist/core/output/index.d.mts +21 -1
- package/dist/core/output/index.mjs +442 -2
- package/dist/core/output/renderers.d.mts +0 -1
- package/dist/core/output/renderers.mjs +46 -1
- package/dist/core/output/writer.mjs +12 -1
- package/dist/core/parse/index.d.mts +40 -7
- package/dist/core/parse/index.mjs +727 -1
- package/dist/core/prompt/index.d.mts +1 -1
- package/dist/core/prompt/index.mjs +348 -6
- package/dist/core/resolve/args.d.mts +1 -1
- package/dist/core/resolve/args.mjs +105 -1
- package/dist/core/resolve/coerce.d.mts +1 -1
- package/dist/core/resolve/coerce.mjs +336 -1
- package/dist/core/resolve/config.mjs +19 -1
- package/dist/core/resolve/contracts.d.mts +9 -4
- package/dist/core/resolve/errors.d.mts +0 -1
- package/dist/core/resolve/errors.mjs +140 -2
- package/dist/core/resolve/flags.d.mts +7 -2
- package/dist/core/resolve/flags.mjs +251 -1
- package/dist/core/resolve/index.d.mts +2 -2
- package/dist/core/resolve/index.mjs +85 -1
- package/dist/core/resolve/property.d.mts +4 -2
- package/dist/core/resolve/property.mjs +53 -1
- package/dist/core/schema/activity.d.mts +31 -11
- package/dist/core/schema/arg.d.mts +3 -4
- package/dist/core/schema/arg.mjs +463 -1
- package/dist/core/schema/command.d.mts +26 -6
- package/dist/core/schema/command.mjs +726 -1
- package/dist/core/schema/flag.d.mts +485 -19
- package/dist/core/schema/flag.mjs +705 -1
- package/dist/core/schema/index.d.mts +4 -2
- package/dist/core/schema/middleware.d.mts +4 -3
- package/dist/core/schema/middleware.mjs +41 -1
- package/dist/core/schema/number-constraints.mjs +60 -1
- package/dist/core/schema/prompt.d.mts +6 -3
- package/dist/core/schema/run.d.mts +20 -1
- package/dist/core/schema/string-constraints.d.mts +97 -0
- package/dist/core/schema/string-constraints.mjs +69 -0
- package/dist/core/schema/value-parsers.d.mts +78 -0
- package/dist/core/schema/value-parsers.mjs +142 -0
- package/dist/core/schema-dsl/runtime.mjs +271 -2
- package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
- package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
- package/dist/core/testkit/index.d.mts +0 -31
- package/dist/core/testkit/index.mjs +83 -1
- package/dist/index.d.mts +11 -6
- package/dist/index.mjs +22 -1
- package/dist/runtime/adapter.d.mts +38 -2
- package/dist/runtime/adapter.mjs +87 -1
- package/dist/runtime/auto.d.mts +2 -3
- package/dist/runtime/auto.mjs +45 -1
- package/dist/runtime/deno.d.mts +24 -5
- package/dist/runtime/deno.mjs +262 -2
- package/dist/runtime/detect.mjs +45 -1
- package/dist/runtime/index.d.mts +3 -4
- package/dist/runtime/node.d.mts +8 -2
- package/dist/runtime/node.mjs +220 -2
- package/dist/runtime/paths.mjs +48 -1
- package/dist/runtime.d.mts +4 -4
- package/dist/runtime.mjs +6 -1
- package/dist/strings.mjs +22 -1
- package/dist/testkit.d.mts +1 -0
- package/dist/testkit.mjs +5 -1
- package/dist/version.d.mts +7 -3
- package/dist/version.mjs +7 -1
- package/dreamcli.schema.json +36 -7
- package/package.json +45 -42
- package/dist/runtime/bun.d.mts +0 -28
- package/dist/runtime/bun.mjs +0 -1
- package/src/core/cli/dispatch.ts +0 -355
- package/src/core/cli/help-links.ts +0 -82
- package/src/core/cli/index.ts +0 -1614
- package/src/core/cli/planner.ts +0 -656
- package/src/core/cli/plugin.ts +0 -117
- package/src/core/cli/propagate.ts +0 -97
- package/src/core/cli/root-help.ts +0 -342
- package/src/core/cli/root-surface.ts +0 -87
- package/src/core/cli/runtime-preflight.ts +0 -456
- package/src/core/completion/index.ts +0 -138
- package/src/core/completion/shells/bash.ts +0 -459
- package/src/core/completion/shells/fish.ts +0 -259
- package/src/core/completion/shells/powershell.ts +0 -439
- package/src/core/completion/shells/shared.ts +0 -310
- package/src/core/completion/shells/zsh.ts +0 -381
- package/src/core/config/index.ts +0 -417
- package/src/core/config/package-json.ts +0 -560
- package/src/core/errors/index.ts +0 -193
- package/src/core/execution/index.ts +0 -265
- package/src/core/help/ansi.ts +0 -144
- package/src/core/help/index.ts +0 -563
- package/src/core/json-schema/index.ts +0 -910
- package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
- package/src/core/output/activity.ts +0 -575
- package/src/core/output/bind.ts +0 -59
- package/src/core/output/contracts.ts +0 -194
- package/src/core/output/display-value.ts +0 -48
- package/src/core/output/index.ts +0 -704
- package/src/core/output/renderers.ts +0 -125
- package/src/core/output/writer.ts +0 -46
- package/src/core/parse/index.ts +0 -742
- package/src/core/prompt/index.ts +0 -623
- package/src/core/resolve/args.ts +0 -144
- package/src/core/resolve/coerce.ts +0 -500
- package/src/core/resolve/config.ts +0 -26
- package/src/core/resolve/contracts.ts +0 -135
- package/src/core/resolve/errors.ts +0 -227
- package/src/core/resolve/flags.ts +0 -269
- package/src/core/resolve/index.ts +0 -108
- package/src/core/resolve/property.ts +0 -99
- package/src/core/schema/activity.ts +0 -240
- package/src/core/schema/arg.ts +0 -841
- package/src/core/schema/command.ts +0 -1500
- package/src/core/schema/flag.ts +0 -917
- package/src/core/schema/index.ts +0 -96
- package/src/core/schema/middleware.ts +0 -171
- package/src/core/schema/number-constraints.ts +0 -153
- package/src/core/schema/prompt.ts +0 -171
- package/src/core/schema/run.ts +0 -198
- package/src/core/schema-dsl/index.ts +0 -109
- package/src/core/schema-dsl/parse.ts +0 -262
- package/src/core/schema-dsl/runtime.ts +0 -609
- package/src/core/schema-dsl/to-json-schema.ts +0 -102
- package/src/core/testkit/index.ts +0 -147
- package/src/index.ts +0 -181
- package/src/runtime/adapter.ts +0 -303
- package/src/runtime/auto.ts +0 -86
- package/src/runtime/bun.ts +0 -48
- package/src/runtime/deno.ts +0 -367
- package/src/runtime/detect.ts +0 -105
- package/src/runtime/index.ts +0 -21
- package/src/runtime/node-builtins.d.ts +0 -27
- package/src/runtime/node.ts +0 -289
- package/src/runtime/paths.ts +0 -64
- package/src/runtime/support.ts +0 -77
- package/src/runtime.ts +0 -31
- package/src/schema.ts +0 -16
- package/src/strings.ts +0 -34
- package/src/testkit.ts +0 -25
- package/src/version.ts +0 -20
package/src/core/cli/index.ts
DELETED
|
@@ -1,1614 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* CLI entry point builder with command registration and dispatch.
|
|
3
|
-
*
|
|
4
|
-
* The {@linkcode cli | cli()} factory returns an immutable {@linkcode CLIBuilder} that registers
|
|
5
|
-
* commands, handles `--help`/`--version` at root level, dispatches to
|
|
6
|
-
* the matched command, and provides both a testable `.execute()` path
|
|
7
|
-
* and a production `.run()` path.
|
|
8
|
-
*
|
|
9
|
-
* @module dreamcli/core/cli
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import type { CompletionOptions, Shell } from '#internals/core/completion/index.ts';
|
|
13
|
-
import {
|
|
14
|
-
detectShell,
|
|
15
|
-
generateCompletion,
|
|
16
|
-
normalizeShell,
|
|
17
|
-
SHELLS,
|
|
18
|
-
} from '#internals/core/completion/index.ts';
|
|
19
|
-
import type { FormatLoader } from '#internals/core/config/index.ts';
|
|
20
|
-
import type { PackageJsonData } from '#internals/core/config/package-json.ts';
|
|
21
|
-
import { CLIError } from '#internals/core/errors/index.ts';
|
|
22
|
-
import { buildRunResult, executeCommand } from '#internals/core/execution/index.ts';
|
|
23
|
-
import type { HelpOptions } from '#internals/core/help/index.ts';
|
|
24
|
-
import { formatHelp } from '#internals/core/help/index.ts';
|
|
25
|
-
import type { CapturedOutput } from '#internals/core/output/index.ts';
|
|
26
|
-
import {
|
|
27
|
-
clearRequestedExitCode,
|
|
28
|
-
createCaptureOutput,
|
|
29
|
-
createOutput,
|
|
30
|
-
} from '#internals/core/output/index.ts';
|
|
31
|
-
import { includesBeforeSeparator } from '#internals/core/parse/index.ts';
|
|
32
|
-
import type { ArgBuilder, ArgConfig } from '#internals/core/schema/arg.ts';
|
|
33
|
-
import { arg } from '#internals/core/schema/arg.ts';
|
|
34
|
-
import type {
|
|
35
|
-
AnyCommandBuilder,
|
|
36
|
-
CommandBuilder,
|
|
37
|
-
CommandMeta,
|
|
38
|
-
CommandSchema,
|
|
39
|
-
ErasedCommand,
|
|
40
|
-
Out,
|
|
41
|
-
} from '#internals/core/schema/command.ts';
|
|
42
|
-
import { command } from '#internals/core/schema/command.ts';
|
|
43
|
-
import type { FlagBuilder, FlagConfig } from '#internals/core/schema/flag.ts';
|
|
44
|
-
import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
|
|
45
|
-
import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
|
|
46
|
-
import { runCommand } from '#internals/core/testkit/index.ts';
|
|
47
|
-
import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
|
|
48
|
-
import { createAdapter } from '#internals/runtime/auto.ts';
|
|
49
|
-
import { BACKSLASH, SLASH, stripTrailing } from '#internals/strings.ts';
|
|
50
|
-
import type { HelpLinks } from './help-links.ts';
|
|
51
|
-
import { deriveHelpLinks } from './help-links.ts';
|
|
52
|
-
import type { OutputPolicy } from './planner.ts';
|
|
53
|
-
import { planInvocation } from './planner.ts';
|
|
54
|
-
import type { CLIPlugin } from './plugin.ts';
|
|
55
|
-
import { plugin } from './plugin.ts';
|
|
56
|
-
import { formatRootHelp } from './root-help.ts';
|
|
57
|
-
import { prepareRuntimePreflight } from './runtime-preflight.ts';
|
|
58
|
-
|
|
59
|
-
// --- Type-erased command — erasure function (interface now in schema/command.ts)
|
|
60
|
-
|
|
61
|
-
/** Long-flag name reserved by `.completions({ as: 'flag' })`; the planner intercepts it before dispatch. */
|
|
62
|
-
const COMPLETIONS_FLAG_NAME = 'completions';
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Whether a command — or any of its nested subcommands — declares a flag that
|
|
66
|
-
* collides with the eager `--completions` flag, by canonical name or long alias.
|
|
67
|
-
*
|
|
68
|
-
* @internal
|
|
69
|
-
*/
|
|
70
|
-
function commandReservesCompletionsFlag(schema: CommandSchema): boolean {
|
|
71
|
-
if (Object.hasOwn(schema.flags, COMPLETIONS_FLAG_NAME)) return true;
|
|
72
|
-
for (const flagSchema of Object.values(schema.flags)) {
|
|
73
|
-
if (
|
|
74
|
-
getFlagAliasNames(flagSchema, { kind: 'long', includeHidden: true }).includes(
|
|
75
|
-
COMPLETIONS_FLAG_NAME,
|
|
76
|
-
)
|
|
77
|
-
) {
|
|
78
|
-
return true;
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
return schema.commands.some(commandReservesCompletionsFlag);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Reject a command whose flags would be shadowed by the eager `--completions`
|
|
86
|
-
* flag once `.completions({ as: 'flag' })` is active. Because the planner
|
|
87
|
-
* intercepts `--completions` before dispatch, such a flag could never be reached.
|
|
88
|
-
*
|
|
89
|
-
* @internal
|
|
90
|
-
*/
|
|
91
|
-
function assertNoCompletionsFlagCollision(schema: CommandSchema): void {
|
|
92
|
-
if (commandReservesCompletionsFlag(schema)) {
|
|
93
|
-
throw new CLIError(
|
|
94
|
-
`Command '${schema.name}' defines a '--${COMPLETIONS_FLAG_NAME}' flag, which is reserved by .completions({ as: 'flag' })`,
|
|
95
|
-
{
|
|
96
|
-
code: 'RESERVED_FLAG',
|
|
97
|
-
suggest: `Rename the flag, or register completions as a subcommand with .completions() instead of { as: 'flag' }`,
|
|
98
|
-
},
|
|
99
|
-
);
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
function commandRoutes(schema: CommandSchema): readonly string[] {
|
|
104
|
-
return [schema.name, ...schema.aliases];
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
function assertNoSiblingRouteConflict(
|
|
108
|
-
parentCommandName: string,
|
|
109
|
-
routeOwners: Map<string, string>,
|
|
110
|
-
route: string,
|
|
111
|
-
commandName: string,
|
|
112
|
-
): void {
|
|
113
|
-
const owner = routeOwners.get(route);
|
|
114
|
-
if (owner !== undefined) {
|
|
115
|
-
throw new CLIError(
|
|
116
|
-
`Duplicate command route '${route}' under '${parentCommandName}' (${owner} and ${commandName})`,
|
|
117
|
-
{
|
|
118
|
-
code: 'DUPLICATE_COMMAND',
|
|
119
|
-
suggest: 'Ensure sibling command names and aliases are unique',
|
|
120
|
-
},
|
|
121
|
-
);
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
routeOwners.set(route, commandName);
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
function assertNoTopLevelRouteConflict(
|
|
128
|
-
commands: readonly ErasedCommand[],
|
|
129
|
-
incoming: CommandSchema,
|
|
130
|
-
defaultCommand?: ErasedCommand | undefined,
|
|
131
|
-
): void {
|
|
132
|
-
const routeOwners = new Map<string, string>();
|
|
133
|
-
|
|
134
|
-
const existing = defaultCommand !== undefined ? [...commands, defaultCommand] : commands;
|
|
135
|
-
for (const command of existing) {
|
|
136
|
-
for (const route of commandRoutes(command.schema)) {
|
|
137
|
-
assertNoSiblingRouteConflict('root', routeOwners, route, command.schema.name);
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
for (const route of commandRoutes(incoming)) {
|
|
142
|
-
const owner = routeOwners.get(route);
|
|
143
|
-
if (owner !== undefined) {
|
|
144
|
-
throw new CLIError(`Command route '${route}' is already registered by '${owner}'`, {
|
|
145
|
-
code: 'DUPLICATE_COMMAND',
|
|
146
|
-
suggest:
|
|
147
|
-
owner === incoming.name
|
|
148
|
-
? `Ensure command '${incoming.name}' does not reuse route '${route}'`
|
|
149
|
-
: `Rename '${incoming.name}' or remove route '${route}' from '${owner}'`,
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
routeOwners.set(route, incoming.name);
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* Erase a typed {@linkcode CommandBuilder} into an {@linkcode ErasedCommand}, recursively
|
|
159
|
-
* building the subcommand tree.
|
|
160
|
-
*
|
|
161
|
-
* The closure captures the fully-typed builder, so {@linkcode runCommand()} receives
|
|
162
|
-
* the original `CommandBuilder<F, A>` — no type assertions needed.\
|
|
163
|
-
* Subcommands are recursively erased and indexed by name and alias for
|
|
164
|
-
* O(1) lookup during dispatch.
|
|
165
|
-
*
|
|
166
|
-
* @internal
|
|
167
|
-
*/
|
|
168
|
-
function eraseCommand<
|
|
169
|
-
F extends Record<string, FlagBuilder<FlagConfig>>,
|
|
170
|
-
A extends Record<string, ArgBuilder<ArgConfig>>,
|
|
171
|
-
C extends Record<string, unknown>,
|
|
172
|
-
>(cmd: CommandBuilder<F, A, C>): ErasedCommand {
|
|
173
|
-
// Recursively erase subcommands, keyed by name and alias.
|
|
174
|
-
const subcommands = new Map<string, ErasedCommand>();
|
|
175
|
-
const routeOwners = new Map<string, string>();
|
|
176
|
-
for (const sub of cmd._subcommands) {
|
|
177
|
-
const routes = commandRoutes(sub.schema);
|
|
178
|
-
for (const route of routes) {
|
|
179
|
-
assertNoSiblingRouteConflict(cmd.schema.name, routeOwners, route, sub.schema.name);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
const erased = eraseCommand(sub);
|
|
183
|
-
for (const route of routes) {
|
|
184
|
-
subcommands.set(route, erased);
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
return {
|
|
189
|
-
schema: cmd.schema,
|
|
190
|
-
subcommands,
|
|
191
|
-
_command: cmd as unknown as AnyCommandBuilder,
|
|
192
|
-
_execute(argv, options) {
|
|
193
|
-
return runCommand(cmd, argv, options);
|
|
194
|
-
},
|
|
195
|
-
};
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
// --- CLI schema — runtime descriptor for the CLI program
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* Runtime descriptor for the CLI program.
|
|
202
|
-
*
|
|
203
|
-
* Stores the program name, version, description, and registered commands.\
|
|
204
|
-
* Built incrementally by {@linkcode CLIBuilder}.
|
|
205
|
-
*/
|
|
206
|
-
interface CLISchema {
|
|
207
|
-
/** Program name (used in help text, usage lines, and completion scripts). */
|
|
208
|
-
readonly name: string;
|
|
209
|
-
/**
|
|
210
|
-
* Whether `.run()` should replace `name` with the invoked program name.
|
|
211
|
-
*
|
|
212
|
-
* Set via the `cli({ inherit: true })` factory form.
|
|
213
|
-
*/
|
|
214
|
-
readonly inheritName: boolean;
|
|
215
|
-
/** Program version (shown by `--version`). */
|
|
216
|
-
readonly version: string | undefined;
|
|
217
|
-
/** Program description (shown in root help). */
|
|
218
|
-
readonly description: string | undefined;
|
|
219
|
-
/** Registered commands (type-erased for heterogeneous storage). */
|
|
220
|
-
readonly commands: readonly ErasedCommand[];
|
|
221
|
-
/**
|
|
222
|
-
* Default command dispatched when no subcommand matches.
|
|
223
|
-
*
|
|
224
|
-
* When set, the CLI root behaves like a hybrid command group: subcommands
|
|
225
|
-
* dispatch by name as usual, but empty argv or flags-only argv falls
|
|
226
|
-
* through to this command instead of showing root help.
|
|
227
|
-
*
|
|
228
|
-
* Set via the {@linkcode CLIBuilder.default | .default()} builder method.
|
|
229
|
-
*/
|
|
230
|
-
readonly defaultCommand: ErasedCommand | undefined;
|
|
231
|
-
/**
|
|
232
|
-
* Config discovery settings.
|
|
233
|
-
*
|
|
234
|
-
* When defined, {@linkcode CLIBuilder.run | .run()} auto-discovers and loads a config file before command dispatch.
|
|
235
|
-
*
|
|
236
|
-
* Set via the {@linkcode CLIBuilder.config | .config()} builder method.
|
|
237
|
-
*/
|
|
238
|
-
readonly configSettings: ConfigSettings | undefined;
|
|
239
|
-
/**
|
|
240
|
-
* Manifest auto-discovery settings. When defined, `.run()` discovers the
|
|
241
|
-
* nearest manifest (`package.json`, `deno.json`, `jsr.json`, …) and merges
|
|
242
|
-
* metadata before dispatch.
|
|
243
|
-
*
|
|
244
|
-
* Set via the {@linkcode CLIBuilder.manifest | .manifest()} builder method
|
|
245
|
-
* (or the {@linkcode CLIBuilder.packageJson | .packageJson()} /
|
|
246
|
-
* {@linkcode CLIBuilder.denoJson | .denoJson()} presets).
|
|
247
|
-
*/
|
|
248
|
-
readonly packageJsonSettings: ResolvedManifestSettings | undefined;
|
|
249
|
-
/**
|
|
250
|
-
* OSC 8 hyperlink targets for the root-help header (name/version).
|
|
251
|
-
*
|
|
252
|
-
* Set via the {@linkcode CLIBuilder.links | .links()} builder method.
|
|
253
|
-
* Fields left `undefined` are derived from manifest metadata
|
|
254
|
-
* (`repository` / `homepage`) when manifest discovery ({@linkcode
|
|
255
|
-
* CLIBuilder.manifest | .manifest()}) is active.
|
|
256
|
-
*/
|
|
257
|
-
readonly helpLinks: HelpLinks | undefined;
|
|
258
|
-
/** Whether built-in `.completions()` registration (command or flag) is active. */
|
|
259
|
-
readonly hasBuiltInCompletions: boolean;
|
|
260
|
-
/**
|
|
261
|
-
* Eager `--completions <shell>` flag configuration.
|
|
262
|
-
*
|
|
263
|
-
* Set when `.completions({ as: 'flag' })` is used instead of the default
|
|
264
|
-
* `completions` subcommand. When defined, the planner intercepts
|
|
265
|
-
* `--completions <shell>` before dispatch, prints the script, and exits;
|
|
266
|
-
* root help advertises the flag in its `Flags:` section.
|
|
267
|
-
*/
|
|
268
|
-
readonly completionsFlag: CompletionsFlagConfig | undefined;
|
|
269
|
-
/**
|
|
270
|
-
* Consumer-configured root-help defaults.
|
|
271
|
-
*
|
|
272
|
-
* Set via the {@linkcode CLIBuilder.help | .help()} builder method and merged
|
|
273
|
-
* under runtime `options.help` (runtime wins) before rendering.
|
|
274
|
-
*/
|
|
275
|
-
readonly helpConfig: HelpConfig | undefined;
|
|
276
|
-
/** Registered CLI plugins. */
|
|
277
|
-
readonly plugins: readonly CLIPlugin[];
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
/**
|
|
281
|
-
* Configuration for the eager `--completions <shell>` flag.
|
|
282
|
-
*
|
|
283
|
-
* Stored in {@link CLISchema} when `.completions({ as: 'flag' })` is used.
|
|
284
|
-
*
|
|
285
|
-
* @internal
|
|
286
|
-
*/
|
|
287
|
-
interface CompletionsFlagConfig {
|
|
288
|
-
/** Shell targets the flag accepts (mirrors {@link SHELLS}). */
|
|
289
|
-
readonly shells: readonly Shell[];
|
|
290
|
-
/** Generator options captured at build time (e.g. `functionPrefix`, `rootMode`). */
|
|
291
|
-
readonly options: CompletionOptions | undefined;
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
/**
|
|
295
|
-
* Consumer-facing root-help configuration set via {@linkcode CLIBuilder.help}.
|
|
296
|
-
*
|
|
297
|
-
* Every field is optional; unset fields fall back to built-in defaults and may
|
|
298
|
-
* be overridden per call through runtime `options.help`.
|
|
299
|
-
*/
|
|
300
|
-
interface HelpConfig {
|
|
301
|
-
/**
|
|
302
|
-
* Render the default command's arguments and flags inline at the root.
|
|
303
|
-
*
|
|
304
|
-
* @defaultValue `true`
|
|
305
|
-
*/
|
|
306
|
-
readonly inlineDefault?: boolean;
|
|
307
|
-
/**
|
|
308
|
-
* Also list the default command in the root `Commands:` table.
|
|
309
|
-
*
|
|
310
|
-
* By default the default command is the root surface and is omitted from the
|
|
311
|
-
* command list (its args/flags render inline instead).
|
|
312
|
-
*
|
|
313
|
-
* @defaultValue `false`
|
|
314
|
-
*/
|
|
315
|
-
readonly showDefaultInCommands?: boolean;
|
|
316
|
-
/**
|
|
317
|
-
* Show the `Run '<bin> <command> --help' for more information.` hint.
|
|
318
|
-
*
|
|
319
|
-
* Defaults to showing the hint only when visible subcommands exist.
|
|
320
|
-
*/
|
|
321
|
-
readonly footer?: boolean;
|
|
322
|
-
/** Maximum line width (columns). */
|
|
323
|
-
readonly width?: number;
|
|
324
|
-
/** Emit OSC 8 hyperlinks in the header when supported. */
|
|
325
|
-
readonly hyperlinks?: boolean;
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
/**
|
|
329
|
-
* Config discovery settings for automatic config file loading.
|
|
330
|
-
*
|
|
331
|
-
* Stored in {@link CLISchema} and consumed by {@linkcode CLIBuilder.run()} to call
|
|
332
|
-
* {@link discoverConfig} before dispatching to a command.
|
|
333
|
-
*/
|
|
334
|
-
interface ConfigSettings {
|
|
335
|
-
/**
|
|
336
|
-
* Application name used to build config search paths.
|
|
337
|
-
*
|
|
338
|
-
* Search paths: `.{appName}.json` (cwd), `{appName}.config.json` (cwd),
|
|
339
|
-
* and `{configDir}/{appName}/config.json` where `configDir` is
|
|
340
|
-
* `$XDG_CONFIG_HOME` / `~/.config` on Unix or `%APPDATA%` /
|
|
341
|
-
* `%USERPROFILE%\\AppData\\Roaming` on Windows.
|
|
342
|
-
*/
|
|
343
|
-
readonly appName: string;
|
|
344
|
-
|
|
345
|
-
/** Additional format loaders beyond the built-in JSON loader. */
|
|
346
|
-
readonly loaders: readonly FormatLoader[] | undefined;
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
/**
|
|
350
|
-
* Manifest auto-discovery settings — the resolved/normalized shape stored in
|
|
351
|
-
* the schema.
|
|
352
|
-
*
|
|
353
|
-
* Stored in {@link CLISchema} and consumed by `CLIBuilder.run()` to
|
|
354
|
-
* call {@link discoverManifest} before dispatching to a command.
|
|
355
|
-
*
|
|
356
|
-
* Note: the schema FIELD name (`packageJsonSettings`) keeps its `packageJson`
|
|
357
|
-
* prefix for backward compatibility — renaming it would break consumers reading
|
|
358
|
-
* `app.schema.packageJsonSettings`. The type itself is now generically named
|
|
359
|
-
* (it holds discovery config for any manifest — `package.json`, `deno.json`,
|
|
360
|
-
* `jsr.json`); the legacy {@link PackageJsonSettings} alias remains exported for
|
|
361
|
-
* backward compatibility.
|
|
362
|
-
*/
|
|
363
|
-
interface ResolvedManifestSettings {
|
|
364
|
-
/**
|
|
365
|
-
* Infer CLI name from manifest `bin` keys or `name` field.
|
|
366
|
-
*
|
|
367
|
-
* When `true`, the discovered name replaces the `cli(name)` value.
|
|
368
|
-
* Explicit `.version()`/`.description()` calls still take precedence
|
|
369
|
-
* over discovered values.
|
|
370
|
-
*
|
|
371
|
-
* @defaultValue `false`
|
|
372
|
-
*/
|
|
373
|
-
readonly inferName: boolean;
|
|
374
|
-
/**
|
|
375
|
-
* Strip a leading `@scope/` from the inferred `name` fallback.
|
|
376
|
-
*
|
|
377
|
-
* Only consulted when {@link ResolvedManifestSettings.inferName | `inferName`}
|
|
378
|
-
* is `true` and the name comes from the manifest `name` field (not a `bin`
|
|
379
|
-
* key, which is never scoped).
|
|
380
|
-
*
|
|
381
|
-
* @defaultValue `true`
|
|
382
|
-
*/
|
|
383
|
-
readonly stripScope: boolean;
|
|
384
|
-
/**
|
|
385
|
-
* Explicit filesystem anchor for discovery; overrides `adapter.cwd`.
|
|
386
|
-
*
|
|
387
|
-
* Resolved to a string path before storage. When set, `discoverManifest`
|
|
388
|
-
* walks up from here instead of the runtime cwd. Required for installable
|
|
389
|
-
* CLIs whose version should reflect THEIR OWN package, not the consumer's
|
|
390
|
-
* working directory.
|
|
391
|
-
*/
|
|
392
|
-
readonly from: string | undefined;
|
|
393
|
-
/**
|
|
394
|
-
* Candidate manifest filenames, in per-directory priority order
|
|
395
|
-
* (e.g. `['deno.json', 'deno.jsonc', 'jsr.json']` for `.denoJson()`).
|
|
396
|
-
*/
|
|
397
|
-
readonly files: readonly string[];
|
|
398
|
-
/**
|
|
399
|
-
* Pre-loaded data; skips filesystem discovery, uses values verbatim.
|
|
400
|
-
*
|
|
401
|
-
* @example
|
|
402
|
-
* ```ts
|
|
403
|
-
* import pkg from './package.json' with { type: 'json' };
|
|
404
|
-
*
|
|
405
|
-
* cli('mycli').manifest(pkg);
|
|
406
|
-
* ```
|
|
407
|
-
*/
|
|
408
|
-
readonly data: PackageJsonData | undefined;
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
/**
|
|
412
|
-
* Resolved manifest discovery settings stored in {@link CLISchema}.
|
|
413
|
-
*
|
|
414
|
-
* @deprecated Renamed to {@link ResolvedManifestSettings}. The stored shape
|
|
415
|
-
* holds generic manifest discovery config (`package.json`, `deno.json`,
|
|
416
|
-
* `jsr.json`), not just `package.json`; the misleading name is kept only for
|
|
417
|
-
* backward compatibility.
|
|
418
|
-
*/
|
|
419
|
-
type PackageJsonSettings = ResolvedManifestSettings;
|
|
420
|
-
|
|
421
|
-
// --- Options for execute/run
|
|
422
|
-
|
|
423
|
-
/**
|
|
424
|
-
* Options for {@linkcode CLIBuilder.execute | .execute()} and {@linkcode CLIBuilder.run | .run()}.
|
|
425
|
-
*
|
|
426
|
-
* Derives from {@linkcode RunOptions} while excluding command-execution internals
|
|
427
|
-
* (`meta`, `mergedSchema`) and adding the CLI-level runtime adapter.
|
|
428
|
-
*/
|
|
429
|
-
interface CLIRunOptions extends Omit<RunOptions, 'meta' | 'mergedSchema'> {
|
|
430
|
-
/**
|
|
431
|
-
* Runtime adapter providing platform-specific I/O, argv, env, etc.
|
|
432
|
-
*
|
|
433
|
-
* When provided to `.run()`, replaces the default Node adapter.
|
|
434
|
-
* Ignored by `.execute()` (which is process-free by design).
|
|
435
|
-
*/
|
|
436
|
-
readonly adapter?: RuntimeAdapter;
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
// --- Command run options builder
|
|
440
|
-
|
|
441
|
-
/**
|
|
442
|
-
* Build {@linkcode RunOptions} from {@linkcode CLIRunOptions}, conditionally spreading each
|
|
443
|
-
* field to satisfy `exactOptionalPropertyTypes`.
|
|
444
|
-
*
|
|
445
|
-
* @param options - CLI-level run options (may be `undefined` for defaults).
|
|
446
|
-
* @param helpOptions - Help formatting options forwarded to commands.
|
|
447
|
-
* @param meta - Optional command metadata (omitted for root-level dispatch).
|
|
448
|
-
* @returns Options record ready for {@linkcode ErasedCommand._execute | ErasedCommand._execute()}.
|
|
449
|
-
*
|
|
450
|
-
* @internal
|
|
451
|
-
*/
|
|
452
|
-
function buildCommandRunOptions(
|
|
453
|
-
options: CLIRunOptions | undefined,
|
|
454
|
-
helpOptions: HelpOptions,
|
|
455
|
-
meta?: CommandMeta,
|
|
456
|
-
): RunOptions {
|
|
457
|
-
return {
|
|
458
|
-
help: helpOptions,
|
|
459
|
-
...(meta !== undefined ? { meta } : {}),
|
|
460
|
-
...(options?.plugins !== undefined ? { plugins: options.plugins } : {}),
|
|
461
|
-
...(options?.env !== undefined ? { env: options.env } : {}),
|
|
462
|
-
...(options?.config !== undefined ? { config: options.config } : {}),
|
|
463
|
-
...(options?.stdinData !== undefined ? { stdinData: options.stdinData } : {}),
|
|
464
|
-
...(options?.prompter !== undefined ? { prompter: options.prompter } : {}),
|
|
465
|
-
...(options?.answers !== undefined ? { answers: options.answers } : {}),
|
|
466
|
-
...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
|
|
467
|
-
...(options?.jsonMode !== undefined ? { jsonMode: options.jsonMode } : {}),
|
|
468
|
-
...(options?.isTTY !== undefined ? { isTTY: options.isTTY } : {}),
|
|
469
|
-
...(options?.out !== undefined ? { out: options.out } : {}),
|
|
470
|
-
...(options?.captured !== undefined ? { captured: options.captured } : {}),
|
|
471
|
-
};
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
// --- CLIBuilder — immutable builder for the CLI program
|
|
475
|
-
|
|
476
|
-
/**
|
|
477
|
-
* Immutable CLI program builder.
|
|
478
|
-
*
|
|
479
|
-
* Registers commands, handles root-level `--help`/`--version`, and
|
|
480
|
-
* dispatches to the matched command based on argv.
|
|
481
|
-
*
|
|
482
|
-
* Two execution paths:
|
|
483
|
-
* - `.execute(argv, options?)` — testable, returns {@linkcode RunResult}
|
|
484
|
-
* - `.run(options?)` — production entry, reads `process.argv`, exits process
|
|
485
|
-
*
|
|
486
|
-
* @example
|
|
487
|
-
* ```ts
|
|
488
|
-
* import { cli, command, flag, arg } from '@kjanat/dreamcli';
|
|
489
|
-
*
|
|
490
|
-
* const deploy = command('deploy')
|
|
491
|
-
* .arg('target', arg.string())
|
|
492
|
-
* .flag('force', flag.boolean().alias('f'))
|
|
493
|
-
* .action(({ args, flags, out }) => {
|
|
494
|
-
* out.log(`Deploying ${args.target}...`);
|
|
495
|
-
* });
|
|
496
|
-
*
|
|
497
|
-
* cli('mycli')
|
|
498
|
-
* .version('1.0.0')
|
|
499
|
-
* .command(deploy)
|
|
500
|
-
* .run();
|
|
501
|
-
* ```
|
|
502
|
-
*/
|
|
503
|
-
class CLIBuilder {
|
|
504
|
-
/** @internal Runtime schema descriptor. */
|
|
505
|
-
readonly schema: CLISchema;
|
|
506
|
-
|
|
507
|
-
/** Build a CLIBuilder from a pre-constructed schema descriptor. */
|
|
508
|
-
constructor(schema: CLISchema) {
|
|
509
|
-
this.schema = schema;
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
// -- Metadata modifiers --------------------------------------------------
|
|
513
|
-
|
|
514
|
-
/**
|
|
515
|
-
* Set the program version (shown by `--version`).
|
|
516
|
-
*
|
|
517
|
-
* @param v - Semantic version string.
|
|
518
|
-
* @returns The builder (for chaining).
|
|
519
|
-
*/
|
|
520
|
-
version(v: string): CLIBuilder {
|
|
521
|
-
return new CLIBuilder({ ...this.schema, version: v });
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
/**
|
|
525
|
-
* Set the program description (shown in root help).
|
|
526
|
-
*
|
|
527
|
-
* @param text - Short description displayed in root help output.
|
|
528
|
-
* @returns The builder (for chaining).
|
|
529
|
-
*/
|
|
530
|
-
description(text: string): CLIBuilder {
|
|
531
|
-
return new CLIBuilder({ ...this.schema, description: text });
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
/**
|
|
535
|
-
* Make the root-help header clickable with OSC 8 hyperlinks.
|
|
536
|
-
*
|
|
537
|
-
* Links the program name and version on the first line of root `--help`
|
|
538
|
-
* output in terminals that support
|
|
539
|
-
* [OSC 8 hyperlinks](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda).
|
|
540
|
-
* The escapes are only emitted when stdout is a TTY (overridable via
|
|
541
|
-
* `options.help.hyperlinks`), and only in the header — usage lines, the
|
|
542
|
-
* `--help` hint, the commands table, and completion scripts stay plain.
|
|
543
|
-
*
|
|
544
|
-
* URLs not provided here are derived from manifest metadata when
|
|
545
|
-
* `.manifest()` is active (works with both filesystem discovery and
|
|
546
|
-
* pre-loaded data):
|
|
547
|
-
* - **name** → normalized `repository` URL, falling back to `homepage`
|
|
548
|
-
* - **version** → forge release tag (`{repo}/releases/tag/v{version}` on
|
|
549
|
-
* GitHub, `{repo}/-/releases/v{version}` on GitLab)
|
|
550
|
-
*
|
|
551
|
-
* @param links - Explicit URLs; omit to derive everything from the manifest.
|
|
552
|
-
* @returns The builder (for chaining).
|
|
553
|
-
*
|
|
554
|
-
* @example
|
|
555
|
-
* ```ts
|
|
556
|
-
* // Derive both links from the manifest repository/homepage:
|
|
557
|
-
* cli('mycli')
|
|
558
|
-
* .manifest()
|
|
559
|
-
* .links()
|
|
560
|
-
* .run();
|
|
561
|
-
*
|
|
562
|
-
* // Explicit URLs (no package.json required):
|
|
563
|
-
* cli('mycli')
|
|
564
|
-
* .version('1.0.0')
|
|
565
|
-
* .links({
|
|
566
|
-
* name: 'https://github.com/me/mycli',
|
|
567
|
-
* version: 'https://github.com/me/mycli/releases/tag/v1.0.0',
|
|
568
|
-
* })
|
|
569
|
-
* .run();
|
|
570
|
-
* ```
|
|
571
|
-
*/
|
|
572
|
-
links(links?: { readonly name?: string | URL; readonly version?: string | URL }): CLIBuilder {
|
|
573
|
-
return new CLIBuilder({
|
|
574
|
-
...this.schema,
|
|
575
|
-
helpLinks: {
|
|
576
|
-
name: toUrlString(links?.name),
|
|
577
|
-
version: toUrlString(links?.version),
|
|
578
|
-
},
|
|
579
|
-
});
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
/**
|
|
583
|
-
* Configure root-help rendering defaults.
|
|
584
|
-
*
|
|
585
|
-
* Stored on the schema and merged **under** any runtime `options.help`
|
|
586
|
-
* (runtime wins). Call multiple times to set fields incrementally.
|
|
587
|
-
*
|
|
588
|
-
* @param config - Help rendering options (see {@link HelpConfig}).
|
|
589
|
-
* @returns The builder (for chaining).
|
|
590
|
-
*
|
|
591
|
-
* @example
|
|
592
|
-
* ```ts
|
|
593
|
-
* // Echo the default command under Commands and never show the footer:
|
|
594
|
-
* cli('mycli')
|
|
595
|
-
* .help({ showDefaultInCommands: true, footer: false })
|
|
596
|
-
* .default(serve)
|
|
597
|
-
* .run();
|
|
598
|
-
* ```
|
|
599
|
-
*/
|
|
600
|
-
help(config: HelpConfig): CLIBuilder {
|
|
601
|
-
return new CLIBuilder({
|
|
602
|
-
...this.schema,
|
|
603
|
-
helpConfig: { ...this.schema.helpConfig, ...config },
|
|
604
|
-
});
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
/**
|
|
608
|
-
* Enable automatic config file discovery.
|
|
609
|
-
*
|
|
610
|
-
* When enabled, `.run()` probes standard paths before dispatching:
|
|
611
|
-
* 1. `$CWD/.{appName}.json`
|
|
612
|
-
* 2. `$CWD/{appName}.config.json`
|
|
613
|
-
* 3. `$CONFIG_DIR/{appName}/config.json`
|
|
614
|
-
* (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
|
|
615
|
-
* `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
|
|
616
|
-
*
|
|
617
|
-
* The user can override the path via `--config <path>` or `--config=<path>`.
|
|
618
|
-
*
|
|
619
|
-
* Loaded config feeds into the resolution chain
|
|
620
|
-
* (CLI → env → **config** → prompt → default) for flags that
|
|
621
|
-
* declare `.config('dotted.path')`.
|
|
622
|
-
*
|
|
623
|
-
* Has no effect in `.execute()` (which receives config via
|
|
624
|
-
* `options.config` directly).
|
|
625
|
-
*
|
|
626
|
-
* @param appName - Name used to build search paths.
|
|
627
|
-
* @param loaders - Additional {@link FormatLoader}s (JSON is built-in).
|
|
628
|
-
* @returns The builder (for chaining).
|
|
629
|
-
*/
|
|
630
|
-
config(appName: string, loaders?: readonly FormatLoader[]): CLIBuilder {
|
|
631
|
-
return new CLIBuilder({
|
|
632
|
-
...this.schema,
|
|
633
|
-
configSettings: {
|
|
634
|
-
appName,
|
|
635
|
-
loaders,
|
|
636
|
-
},
|
|
637
|
-
});
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
/**
|
|
641
|
-
* Register a custom config format loader.
|
|
642
|
-
*
|
|
643
|
-
* Adds a {@link FormatLoader} incrementally — call multiple times to
|
|
644
|
-
* register multiple formats. Loaders registered later for the same
|
|
645
|
-
* extension override earlier ones.
|
|
646
|
-
*
|
|
647
|
-
* Requires `.config()` to have been called first (sets the app name).
|
|
648
|
-
*
|
|
649
|
-
* @param loader - Format loader (or extensions + parse function).
|
|
650
|
-
* @returns The builder (for chaining).
|
|
651
|
-
*
|
|
652
|
-
* @example Bun built-in parsers
|
|
653
|
-
* ```ts
|
|
654
|
-
* import { configFormat } from '@kjanat/dreamcli';
|
|
655
|
-
*
|
|
656
|
-
* cli('myapp')
|
|
657
|
-
* .config('myapp')
|
|
658
|
-
* .configLoader(configFormat(['yaml', 'yml'], Bun.YAML.parse))
|
|
659
|
-
* .configLoader(configFormat(['toml'], Bun.TOML.parse))
|
|
660
|
-
* .run();
|
|
661
|
-
* ```
|
|
662
|
-
*
|
|
663
|
-
* @example npm package parsers
|
|
664
|
-
* ```ts
|
|
665
|
-
* import { configFormat } from '@kjanat/dreamcli';
|
|
666
|
-
* import { parse as parseYaml } from 'yaml';
|
|
667
|
-
* import { parse as parseTOML } from '@iarna/toml';
|
|
668
|
-
*
|
|
669
|
-
* cli('myapp')
|
|
670
|
-
* .config('myapp')
|
|
671
|
-
* .configLoader(configFormat(['yaml', 'yml'], parseYaml))
|
|
672
|
-
* .configLoader(configFormat(['toml'], parseTOML))
|
|
673
|
-
* .run();
|
|
674
|
-
* ```
|
|
675
|
-
*/
|
|
676
|
-
configLoader(loader: FormatLoader): CLIBuilder {
|
|
677
|
-
if (this.schema.configSettings === undefined) {
|
|
678
|
-
throw new CLIError('.configLoader() requires .config() to be called first', {
|
|
679
|
-
code: 'INVALID_BUILDER_STATE',
|
|
680
|
-
suggest: 'Call .config(appName) before .configLoader()',
|
|
681
|
-
});
|
|
682
|
-
}
|
|
683
|
-
const existing = this.schema.configSettings.loaders ?? [];
|
|
684
|
-
return new CLIBuilder({
|
|
685
|
-
...this.schema,
|
|
686
|
-
configSettings: {
|
|
687
|
-
...this.schema.configSettings,
|
|
688
|
-
loaders: [...existing, loader],
|
|
689
|
-
},
|
|
690
|
-
});
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
/**
|
|
694
|
-
* Enable manifest metadata from pre-loaded data.
|
|
695
|
-
*
|
|
696
|
-
* Pass an already-imported manifest (`package.json`, `deno.json`, `jsr.json`)
|
|
697
|
-
* to skip filesystem discovery entirely — useful for bundled or installable
|
|
698
|
-
* CLIs where the version should be locked at build time. The data's
|
|
699
|
-
* `version`/`description` are merged into the CLI schema immediately, so this
|
|
700
|
-
* form works in **both** `.run()` and `.execute()` (the filesystem-free path).
|
|
701
|
-
* Explicit `.version()`/`.description()` calls still take precedence, and the
|
|
702
|
-
* data form does not infer the CLI name — `inferName` / `{ scope }` are
|
|
703
|
-
* available only on the discovery (settings) form. For a pre-loaded manifest
|
|
704
|
-
* whose scoped `name` should drive the CLI name, set the name explicitly via
|
|
705
|
-
* `cli(name)` (or call {@link inferCliName} on the data yourself).
|
|
706
|
-
*
|
|
707
|
-
* Detected by field shape: an object carrying at least one of
|
|
708
|
-
* `name`/`version`/`description`/`bin`/`homepage`/`repository`. An empty `{}`
|
|
709
|
-
* or a settings-shaped object falls through to the settings overload.
|
|
710
|
-
*
|
|
711
|
-
* @param data - Pre-loaded manifest metadata.
|
|
712
|
-
*
|
|
713
|
-
* @example
|
|
714
|
-
* ```ts
|
|
715
|
-
* import denoCfg from './deno.json' with { type: 'json' };
|
|
716
|
-
*
|
|
717
|
-
* // No filesystem; works in .run() AND .execute():
|
|
718
|
-
* cli('mycli')
|
|
719
|
-
* .manifest(denoCfg)
|
|
720
|
-
* .command(deploy)
|
|
721
|
-
* .run();
|
|
722
|
-
* ```
|
|
723
|
-
*/
|
|
724
|
-
manifest(data: PackageJsonData): CLIBuilder;
|
|
725
|
-
/**
|
|
726
|
-
* Enable automatic manifest metadata discovery.
|
|
727
|
-
*
|
|
728
|
-
* When enabled, `.run()` walks up from `cwd` (or {@link ManifestSettings.from})
|
|
729
|
-
* to find the nearest manifest among {@link ManifestSettings.files} and merges
|
|
730
|
-
* its `version`/`description` into the CLI schema. Explicit `.version()` /
|
|
731
|
-
* `.description()` calls always take precedence.
|
|
732
|
-
*
|
|
733
|
-
* Files are parsed as JSON with a JSONC fallback — `package.json`, `deno.json`,
|
|
734
|
-
* `jsr.json`, and `deno.jsonc` all qualify, including files with `//` / block
|
|
735
|
-
* comments or trailing commas. A file that fails both parses is skipped
|
|
736
|
-
* (discovery keeps walking).
|
|
737
|
-
*
|
|
738
|
-
* Has no effect in `.execute()` (filesystem-free) — use the data overload.
|
|
739
|
-
*
|
|
740
|
-
* @param settings - Optional settings:
|
|
741
|
-
* - `files`: candidate manifest filenames in priority order
|
|
742
|
-
* (default `['package.json']`).
|
|
743
|
-
* - `inferName`: infer the CLI name from `bin` keys or `name`. Pass
|
|
744
|
-
* `{ scope: 'keep' }` to keep a leading `@scope/` (stripped by default).
|
|
745
|
-
* - `from`: anchor discovery to a file/URL/path instead of `cwd`. Pass
|
|
746
|
-
* `import.meta.url` for installable CLIs that must report THEIR OWN
|
|
747
|
-
* version. Accepts string paths, `file:` URL strings, or `URL` instances.
|
|
748
|
-
*
|
|
749
|
-
* @example
|
|
750
|
-
* ```ts
|
|
751
|
-
* // Deno CLI: discover OUR deno.json (then jsr.json), keep the scope in name:
|
|
752
|
-
* cli('mycli')
|
|
753
|
-
* .manifest({
|
|
754
|
-
* files: ['deno.json', 'jsr.json'],
|
|
755
|
-
* from: import.meta.url,
|
|
756
|
-
* inferName: { scope: 'keep' },
|
|
757
|
-
* })
|
|
758
|
-
* .command(deploy)
|
|
759
|
-
* .run();
|
|
760
|
-
* ```
|
|
761
|
-
*/
|
|
762
|
-
manifest(settings?: ManifestSettings): CLIBuilder;
|
|
763
|
-
manifest(input?: PackageJsonData | ManifestSettings): CLIBuilder {
|
|
764
|
-
return new CLIBuilder(buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES, false));
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
/**
|
|
768
|
-
* Discover metadata from `package.json` (preset for {@link CLIBuilder.manifest}).
|
|
769
|
-
*
|
|
770
|
-
* @deprecated Use {@link CLIBuilder.manifest} — `.manifest()` defaults to
|
|
771
|
-
* `package.json` and also supports `deno.json` / `jsr.json` via `files`.
|
|
772
|
-
*
|
|
773
|
-
* @param data - Pre-loaded `package.json` metadata.
|
|
774
|
-
*/
|
|
775
|
-
packageJson(data: PackageJsonData): CLIBuilder;
|
|
776
|
-
/**
|
|
777
|
-
* Discover metadata from `package.json` (preset for {@link CLIBuilder.manifest}).
|
|
778
|
-
*
|
|
779
|
-
* @deprecated Use {@link CLIBuilder.manifest}.
|
|
780
|
-
*
|
|
781
|
-
* @param settings - `inferName` / `from` (see {@link CLIBuilder.manifest}).
|
|
782
|
-
*/
|
|
783
|
-
packageJson(settings?: ManifestPresetSettings): CLIBuilder;
|
|
784
|
-
packageJson(input?: PackageJsonData | ManifestPresetSettings): CLIBuilder {
|
|
785
|
-
return new CLIBuilder(buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES, true));
|
|
786
|
-
}
|
|
787
|
-
|
|
788
|
-
/**
|
|
789
|
-
* Discover metadata from `deno.json`, `deno.jsonc`, then `jsr.json` (preset for
|
|
790
|
-
* {@link CLIBuilder.manifest}).
|
|
791
|
-
*
|
|
792
|
-
* @deprecated Use `.manifest({ files: ['deno.json', 'deno.jsonc', 'jsr.json'] })`.
|
|
793
|
-
*
|
|
794
|
-
* @param data - Pre-loaded `deno.json` / `jsr.json` metadata.
|
|
795
|
-
*/
|
|
796
|
-
denoJson(data: PackageJsonData): CLIBuilder;
|
|
797
|
-
/**
|
|
798
|
-
* Discover metadata from `deno.json`, `deno.jsonc`, then `jsr.json` (preset for
|
|
799
|
-
* {@link CLIBuilder.manifest}).
|
|
800
|
-
*
|
|
801
|
-
* @deprecated Use `.manifest({ files: ['deno.json', 'deno.jsonc', 'jsr.json'] })`.
|
|
802
|
-
*
|
|
803
|
-
* @param settings - `inferName` / `from` (see {@link CLIBuilder.manifest}).
|
|
804
|
-
* `deno.json` / `jsr.json` have no `bin` field, so `inferName` resolves
|
|
805
|
-
* from `name`; pass `{ scope: 'keep' }` to retain a leading `@scope/`.
|
|
806
|
-
*
|
|
807
|
-
* @example
|
|
808
|
-
* ```ts
|
|
809
|
-
* cli('mycli')
|
|
810
|
-
* .denoJson({ from: import.meta.url })
|
|
811
|
-
* .command(deploy)
|
|
812
|
-
* .run();
|
|
813
|
-
* ```
|
|
814
|
-
*/
|
|
815
|
-
denoJson(settings?: ManifestPresetSettings): CLIBuilder;
|
|
816
|
-
denoJson(input?: PackageJsonData | ManifestPresetSettings): CLIBuilder {
|
|
817
|
-
return new CLIBuilder(buildManifestSchema(this.schema, input, DENO_MANIFEST_FILES, true));
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
// -- Command registration ------------------------------------------------
|
|
821
|
-
|
|
822
|
-
/**
|
|
823
|
-
* Register a command with the CLI program.
|
|
824
|
-
*
|
|
825
|
-
* The command's type parameters are erased for heterogeneous storage.
|
|
826
|
-
* Type safety is preserved inside the closure that delegates to
|
|
827
|
-
* {@linkcode runCommand | runCommand()}.
|
|
828
|
-
*
|
|
829
|
-
* @param cmd - {@link CommandBuilder} to register.
|
|
830
|
-
* @returns The builder (for chaining).
|
|
831
|
-
*/
|
|
832
|
-
command<
|
|
833
|
-
F extends Record<string, FlagBuilder<FlagConfig>>,
|
|
834
|
-
A extends Record<string, ArgBuilder<ArgConfig>>,
|
|
835
|
-
C extends Record<string, unknown>,
|
|
836
|
-
>(cmd: CommandBuilder<F, A, C>): CLIBuilder {
|
|
837
|
-
assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema, this.schema.defaultCommand);
|
|
838
|
-
if (this.schema.completionsFlag !== undefined) {
|
|
839
|
-
assertNoCompletionsFlagCollision(cmd.schema);
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
return new CLIBuilder({
|
|
843
|
-
...this.schema,
|
|
844
|
-
commands: [...this.schema.commands, eraseCommand(cmd)],
|
|
845
|
-
});
|
|
846
|
-
}
|
|
847
|
-
|
|
848
|
-
/**
|
|
849
|
-
* Register a command as the default — dispatched when no subcommand is given.
|
|
850
|
-
*
|
|
851
|
-
* The CLI root behaves like a hybrid command group: named subcommands
|
|
852
|
-
* dispatch normally, but empty argv or flags-only argv falls through to
|
|
853
|
-
* this command instead of showing root help.
|
|
854
|
-
*
|
|
855
|
-
* The default command is the CLI's root *surface*: its flags and arguments
|
|
856
|
-
* are rendered inline in root help. It is **not** a named subcommand — it
|
|
857
|
-
* cannot be invoked by its own name (`mycli mycmd` does not route to it) and
|
|
858
|
-
* it is omitted from the root `Commands:` list by default (re-enable with
|
|
859
|
-
* `.help({ showDefaultInCommands: true })`). Only one default is allowed.
|
|
860
|
-
*
|
|
861
|
-
* @example
|
|
862
|
-
* ```ts
|
|
863
|
-
* // Single-command CLI — no subcommand name needed:
|
|
864
|
-
* // mytool --force production
|
|
865
|
-
* cli('mytool')
|
|
866
|
-
* .default(deploy)
|
|
867
|
-
* .run();
|
|
868
|
-
*
|
|
869
|
-
* // Multi-command CLI with a default:
|
|
870
|
-
* // mytool production → runs deploy
|
|
871
|
-
* // mytool status → runs status
|
|
872
|
-
* cli('mytool')
|
|
873
|
-
* .default(deploy)
|
|
874
|
-
* .command(status)
|
|
875
|
-
* .run();
|
|
876
|
-
* ```
|
|
877
|
-
*
|
|
878
|
-
* @param cmd - {@link CommandBuilder} to register as the default.
|
|
879
|
-
* @returns The builder (for chaining).
|
|
880
|
-
*/
|
|
881
|
-
default<
|
|
882
|
-
F extends Record<string, FlagBuilder<FlagConfig>>,
|
|
883
|
-
A extends Record<string, ArgBuilder<ArgConfig>>,
|
|
884
|
-
C extends Record<string, unknown>,
|
|
885
|
-
>(cmd: CommandBuilder<F, A, C>): CLIBuilder {
|
|
886
|
-
if (this.schema.defaultCommand !== undefined) {
|
|
887
|
-
throw new CLIError('Only one default command is allowed', {
|
|
888
|
-
code: 'DUPLICATE_DEFAULT',
|
|
889
|
-
suggest: 'Call .default() only once when building the CLI',
|
|
890
|
-
});
|
|
891
|
-
}
|
|
892
|
-
|
|
893
|
-
assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
|
|
894
|
-
if (this.schema.completionsFlag !== undefined) {
|
|
895
|
-
assertNoCompletionsFlagCollision(cmd.schema);
|
|
896
|
-
}
|
|
897
|
-
|
|
898
|
-
const erased = eraseCommand(cmd);
|
|
899
|
-
return new CLIBuilder({
|
|
900
|
-
...this.schema,
|
|
901
|
-
defaultCommand: erased,
|
|
902
|
-
});
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
/**
|
|
906
|
-
* Register a CLI plugin.
|
|
907
|
-
*
|
|
908
|
-
* Plugins run in registration order. At each lifecycle stage, all hooks for
|
|
909
|
-
* the first plugin run before hooks for the second plugin, and so on.
|
|
910
|
-
*
|
|
911
|
-
* @param definition - A frozen {@link CLIPlugin} created by {@link plugin}.
|
|
912
|
-
* @returns The builder (for chaining).
|
|
913
|
-
* @see {@link plugin} to construct plugin definitions.
|
|
914
|
-
*/
|
|
915
|
-
plugin(definition: CLIPlugin): CLIBuilder {
|
|
916
|
-
return new CLIBuilder({
|
|
917
|
-
...this.schema,
|
|
918
|
-
plugins: [...this.schema.plugins, definition],
|
|
919
|
-
});
|
|
920
|
-
}
|
|
921
|
-
|
|
922
|
-
// -- Built-in subcommands ------------------------------------------------
|
|
923
|
-
|
|
924
|
-
/**
|
|
925
|
-
* Register built-in shell completion.
|
|
926
|
-
*
|
|
927
|
-
* By default (`{ as: 'command' }`) this registers a `completions` subcommand
|
|
928
|
-
* that accepts a `shell` argument and writes the script to stdout. With
|
|
929
|
-
* `{ as: 'flag' }` it instead exposes an eager `--completions <shell>` flag on
|
|
930
|
-
* the CLI root — no subcommand is registered, so a default command stays the
|
|
931
|
-
* lone root surface. The flag may be given without a value to auto-detect the
|
|
932
|
-
* shell from `$SHELL` / `$PSModulePath`.
|
|
933
|
-
*
|
|
934
|
-
* In subcommand mode, call this **after** registering all other commands so
|
|
935
|
-
* the completion script includes the full command set: that path snapshots the
|
|
936
|
-
* schema (and completion options) at call time, so commands registered
|
|
937
|
-
* afterwards will not appear in that subcommand's generated script. In flag
|
|
938
|
-
* mode, generation runs at execution time from the final builder schema, so
|
|
939
|
-
* registration order does not matter.
|
|
940
|
-
*
|
|
941
|
-
* @example
|
|
942
|
-
* ```ts
|
|
943
|
-
* // Subcommand form (default):
|
|
944
|
-
* cli('mycli')
|
|
945
|
-
* .version('1.0.0')
|
|
946
|
-
* .command(deploy)
|
|
947
|
-
* .completions({ rootMode: 'surface' })
|
|
948
|
-
* .run();
|
|
949
|
-
*
|
|
950
|
-
* // Eager-flag form, ideal for single-command CLIs:
|
|
951
|
-
* cli('mycli')
|
|
952
|
-
* .completions({ as: 'flag' })
|
|
953
|
-
* .default(serve)
|
|
954
|
-
* .run();
|
|
955
|
-
* ```
|
|
956
|
-
*/
|
|
957
|
-
completions(options?: CompletionOptions): CLIBuilder {
|
|
958
|
-
if (this.schema.hasBuiltInCompletions) {
|
|
959
|
-
throw new CLIError('.completions() has already been called', {
|
|
960
|
-
code: 'DUPLICATE_COMMAND',
|
|
961
|
-
suggest: 'Call .completions() only once when building the CLI',
|
|
962
|
-
});
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
// `as: 'flag'` exposes an eager `--completions <shell>` flag instead of a
|
|
966
|
-
// subcommand. The planner intercepts it before dispatch (see planner.ts)
|
|
967
|
-
// and root help advertises it in the Flags section. No subcommand is
|
|
968
|
-
// registered, so the default command stays the lone root surface.
|
|
969
|
-
if (options?.as === 'flag') {
|
|
970
|
-
// The planner intercepts `--completions` before dispatch, so no command
|
|
971
|
-
// may already reserve that flag name.
|
|
972
|
-
if (this.schema.defaultCommand !== undefined) {
|
|
973
|
-
assertNoCompletionsFlagCollision(this.schema.defaultCommand.schema);
|
|
974
|
-
}
|
|
975
|
-
for (const registered of this.schema.commands) {
|
|
976
|
-
assertNoCompletionsFlagCollision(registered.schema);
|
|
977
|
-
}
|
|
978
|
-
return new CLIBuilder({
|
|
979
|
-
...this.schema,
|
|
980
|
-
hasBuiltInCompletions: true,
|
|
981
|
-
completionsFlag: { shells: SHELLS, options },
|
|
982
|
-
});
|
|
983
|
-
}
|
|
984
|
-
|
|
985
|
-
// Capture current schema — includes all commands registered so far.
|
|
986
|
-
// The completions command itself is deliberately excluded from the
|
|
987
|
-
// generated script (it would be noise in shell completions).
|
|
988
|
-
const cliSchema = this.schema;
|
|
989
|
-
const completionOptions = options;
|
|
990
|
-
|
|
991
|
-
const cmd = command('completions')
|
|
992
|
-
.alias('completion')
|
|
993
|
-
.description('Generate shell completion script')
|
|
994
|
-
.arg(
|
|
995
|
-
'shell',
|
|
996
|
-
arg
|
|
997
|
-
.custom((raw: string): Shell => {
|
|
998
|
-
// Normalize $SHELL paths across Unix/Windows:
|
|
999
|
-
// /bin/zsh → zsh, C:\Program Files\PowerShell\7\pwsh.exe → pwsh
|
|
1000
|
-
const shell = normalizeShell(raw);
|
|
1001
|
-
if (shell === undefined) {
|
|
1002
|
-
throw new Error(`Unknown shell '${raw}'. Valid shells: ${SHELLS.join(', ')}`);
|
|
1003
|
-
}
|
|
1004
|
-
return shell;
|
|
1005
|
-
})
|
|
1006
|
-
.env('SHELL')
|
|
1007
|
-
.describe(`Target shell (${SHELLS.join(', ')})`),
|
|
1008
|
-
)
|
|
1009
|
-
.action(({ args, meta, out }) => {
|
|
1010
|
-
const completionSchema =
|
|
1011
|
-
meta.bin === cliSchema.name ? cliSchema : { ...cliSchema, name: meta.bin };
|
|
1012
|
-
const script = generateCompletion(completionSchema, args.shell, completionOptions);
|
|
1013
|
-
if (out.jsonMode) {
|
|
1014
|
-
out.json({ shell: args.shell, script });
|
|
1015
|
-
} else {
|
|
1016
|
-
out.log(script);
|
|
1017
|
-
}
|
|
1018
|
-
});
|
|
1019
|
-
|
|
1020
|
-
const withCompletions = this.command(cmd);
|
|
1021
|
-
return new CLIBuilder({
|
|
1022
|
-
...withCompletions.schema,
|
|
1023
|
-
hasBuiltInCompletions: true,
|
|
1024
|
-
});
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
// -- Execution -----------------------------------------------------------
|
|
1028
|
-
|
|
1029
|
-
/**
|
|
1030
|
-
* Execute the CLI program against explicit argv.
|
|
1031
|
-
*
|
|
1032
|
-
* This is the testable execution path — no process state is touched.
|
|
1033
|
-
* Returns a structured {@linkcode RunResult} with exit code and captured output.
|
|
1034
|
-
*
|
|
1035
|
-
* @param argv - Raw argv tokens (NOT including the binary/script path,
|
|
1036
|
-
* i.e. equivalent to `process.argv.slice(2)`).
|
|
1037
|
-
* @param options - Injectable runtime state.
|
|
1038
|
-
* @returns Structured result with exit code and captured output.
|
|
1039
|
-
*/
|
|
1040
|
-
async execute(argv: readonly string[], options?: CLIRunOptions): Promise<RunResult> {
|
|
1041
|
-
// -- Detect global --json mode before building output ---------------------
|
|
1042
|
-
// Only a `--json` before the `--` separator toggles JSON mode; a literal
|
|
1043
|
-
// `--json` positional (after `--`) must reach the command unchanged (#28).
|
|
1044
|
-
const hasJsonFlag = includesBeforeSeparator(argv, '--json');
|
|
1045
|
-
const jsonMode = hasJsonFlag || options?.jsonMode === true;
|
|
1046
|
-
|
|
1047
|
-
const captureOptions = {
|
|
1048
|
-
...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
|
|
1049
|
-
...(jsonMode ? { jsonMode } : {}),
|
|
1050
|
-
...(options?.isTTY !== undefined ? { isTTY: options.isTTY } : {}),
|
|
1051
|
-
};
|
|
1052
|
-
let out: Out;
|
|
1053
|
-
let captured: CapturedOutput;
|
|
1054
|
-
if (options?.out !== undefined) {
|
|
1055
|
-
out = options.out;
|
|
1056
|
-
captured = options.captured ?? { stdout: [], stderr: [], activity: [] };
|
|
1057
|
-
} else {
|
|
1058
|
-
[out, captured] = createCaptureOutput(
|
|
1059
|
-
Object.keys(captureOptions).length > 0 ? captureOptions : undefined,
|
|
1060
|
-
);
|
|
1061
|
-
}
|
|
1062
|
-
clearRequestedExitCode(out);
|
|
1063
|
-
|
|
1064
|
-
// Resolve help options — builder-level `.help()` config under runtime
|
|
1065
|
-
// `options.help` (runtime wins), then default binName to the CLI program
|
|
1066
|
-
// name and hyperlinks to TTY detection (escapes never leak into piped output).
|
|
1067
|
-
const helpOptions: HelpOptions = {
|
|
1068
|
-
...this.schema.helpConfig,
|
|
1069
|
-
...options?.help,
|
|
1070
|
-
binName: options?.help?.binName ?? this.schema.name,
|
|
1071
|
-
hyperlinks: options?.help?.hyperlinks ?? this.schema.helpConfig?.hyperlinks ?? out.isTTY,
|
|
1072
|
-
};
|
|
1073
|
-
|
|
1074
|
-
// -- Shared options for command execution ----------------------------------
|
|
1075
|
-
const effectiveOptions: CLIRunOptions = {
|
|
1076
|
-
...options,
|
|
1077
|
-
plugins: this.schema.plugins,
|
|
1078
|
-
...(jsonMode ? { jsonMode } : {}),
|
|
1079
|
-
};
|
|
1080
|
-
const output: OutputPolicy = {
|
|
1081
|
-
jsonMode,
|
|
1082
|
-
isTTY: out.isTTY,
|
|
1083
|
-
verbosity: options?.verbosity ?? 'normal',
|
|
1084
|
-
};
|
|
1085
|
-
const planned = planInvocation({
|
|
1086
|
-
schema: this.schema,
|
|
1087
|
-
argv,
|
|
1088
|
-
help: helpOptions,
|
|
1089
|
-
output,
|
|
1090
|
-
});
|
|
1091
|
-
|
|
1092
|
-
switch (planned.kind) {
|
|
1093
|
-
case 'root-version':
|
|
1094
|
-
out.log(planned.version);
|
|
1095
|
-
return buildRunResult({ exitCode: 0, error: undefined }, captured);
|
|
1096
|
-
|
|
1097
|
-
case 'root-completions': {
|
|
1098
|
-
const shell = planned.shell ?? detectShell(options?.env ?? {});
|
|
1099
|
-
if (shell === undefined) {
|
|
1100
|
-
const error = new CLIError('Could not detect shell', {
|
|
1101
|
-
code: 'MISSING_VALUE',
|
|
1102
|
-
suggest: `Pass one explicitly, e.g. '${helpOptions.binName} --completions zsh'`,
|
|
1103
|
-
});
|
|
1104
|
-
if (jsonMode) {
|
|
1105
|
-
out.json({ error: error.toJSON() });
|
|
1106
|
-
} else {
|
|
1107
|
-
out.error(error.message);
|
|
1108
|
-
out.error(`Suggestion: ${error.suggest}`);
|
|
1109
|
-
}
|
|
1110
|
-
return buildRunResult({ exitCode: error.exitCode, error }, captured);
|
|
1111
|
-
}
|
|
1112
|
-
const completionSchema =
|
|
1113
|
-
helpOptions.binName === undefined || helpOptions.binName === this.schema.name
|
|
1114
|
-
? this.schema
|
|
1115
|
-
: { ...this.schema, name: helpOptions.binName };
|
|
1116
|
-
const script = generateCompletion(completionSchema, shell, planned.options);
|
|
1117
|
-
if (jsonMode) {
|
|
1118
|
-
out.json({ shell, script });
|
|
1119
|
-
} else {
|
|
1120
|
-
out.log(script);
|
|
1121
|
-
}
|
|
1122
|
-
return buildRunResult({ exitCode: 0, error: undefined }, captured);
|
|
1123
|
-
}
|
|
1124
|
-
|
|
1125
|
-
case 'root-help': {
|
|
1126
|
-
const helpText = formatRootHelp(resolveHelpLinksSchema(this.schema), planned.help);
|
|
1127
|
-
out.log(helpText);
|
|
1128
|
-
return buildRunResult({ exitCode: 0, error: undefined }, captured);
|
|
1129
|
-
}
|
|
1130
|
-
|
|
1131
|
-
case 'dispatch-error': {
|
|
1132
|
-
if (jsonMode) {
|
|
1133
|
-
out.json({ error: planned.error.toJSON() });
|
|
1134
|
-
} else {
|
|
1135
|
-
out.error(planned.error.message);
|
|
1136
|
-
if (planned.error.suggest !== undefined && planned.error.code !== 'NO_ACTION') {
|
|
1137
|
-
out.error(`Suggestion: ${planned.error.suggest}`);
|
|
1138
|
-
}
|
|
1139
|
-
}
|
|
1140
|
-
return buildRunResult({ exitCode: planned.error.exitCode, error: planned.error }, captured);
|
|
1141
|
-
}
|
|
1142
|
-
|
|
1143
|
-
case 'needs-subcommand': {
|
|
1144
|
-
const helpText = formatHelp(planned.command.schema, planned.help);
|
|
1145
|
-
out.log(helpText);
|
|
1146
|
-
return buildRunResult({ exitCode: 0, error: undefined }, captured);
|
|
1147
|
-
}
|
|
1148
|
-
|
|
1149
|
-
case 'match': {
|
|
1150
|
-
const commandRunOptions = buildCommandRunOptions(
|
|
1151
|
-
effectiveOptions,
|
|
1152
|
-
planned.plan.help ?? helpOptions,
|
|
1153
|
-
planned.plan.meta,
|
|
1154
|
-
);
|
|
1155
|
-
if (planned.plan.command._command === undefined) {
|
|
1156
|
-
return planned.plan.command._execute(planned.plan.argv, {
|
|
1157
|
-
...commandRunOptions,
|
|
1158
|
-
mergedSchema: planned.plan.mergedSchema,
|
|
1159
|
-
});
|
|
1160
|
-
}
|
|
1161
|
-
const result = await executeCommand({
|
|
1162
|
-
command: planned.plan.command._command,
|
|
1163
|
-
argv: planned.plan.argv,
|
|
1164
|
-
out,
|
|
1165
|
-
schema: planned.plan.mergedSchema,
|
|
1166
|
-
meta: planned.plan.meta,
|
|
1167
|
-
options: commandRunOptions,
|
|
1168
|
-
});
|
|
1169
|
-
return buildRunResult(result, captured);
|
|
1170
|
-
}
|
|
1171
|
-
}
|
|
1172
|
-
}
|
|
1173
|
-
|
|
1174
|
-
/**
|
|
1175
|
-
* Run the CLI program as a production entry point.
|
|
1176
|
-
*
|
|
1177
|
-
* Reads argv from the runtime adapter, dispatches to the matched
|
|
1178
|
-
* command, writes output to real streams, and exits the process.
|
|
1179
|
-
*
|
|
1180
|
-
* This is the **only** place that touches process state (via the
|
|
1181
|
-
* adapter). For testing, use `.execute()` instead — or provide a
|
|
1182
|
-
* test adapter via `options.adapter`.
|
|
1183
|
-
*
|
|
1184
|
-
* Defaults to {@linkcode createAdapter | createAdapter()} when no adapter is provided,
|
|
1185
|
-
* which auto-detects the runtime (Node.js, Bun) and creates
|
|
1186
|
-
* the appropriate adapter.
|
|
1187
|
-
*
|
|
1188
|
-
* @param options - Optional runtime configuration including adapter.
|
|
1189
|
-
*/
|
|
1190
|
-
async run(options?: CLIRunOptions): Promise<never> {
|
|
1191
|
-
const adapter = options?.adapter ?? createAdapter();
|
|
1192
|
-
const inheritedName = this.schema.inheritName ? inferInvocationName(adapter.argv) : undefined;
|
|
1193
|
-
|
|
1194
|
-
const preflight = await prepareRuntimePreflight({
|
|
1195
|
-
schema: this.schema,
|
|
1196
|
-
adapter,
|
|
1197
|
-
options,
|
|
1198
|
-
inheritedName,
|
|
1199
|
-
});
|
|
1200
|
-
|
|
1201
|
-
if (preflight.kind === 'config-error') {
|
|
1202
|
-
if (preflight.jsonMode) {
|
|
1203
|
-
adapter.stdout(`${JSON.stringify({ error: preflight.error.toJSON() })}\n`);
|
|
1204
|
-
} else {
|
|
1205
|
-
adapter.stderr(`Error: ${preflight.error.message}\n`);
|
|
1206
|
-
if (preflight.error.suggest !== undefined) {
|
|
1207
|
-
adapter.stderr(`Suggestion: ${preflight.error.suggest}\n`);
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
return adapter.exit(preflight.error.exitCode);
|
|
1211
|
-
}
|
|
1212
|
-
|
|
1213
|
-
const effectiveBuilder =
|
|
1214
|
-
preflight.schema === this.schema ? this : new CLIBuilder(preflight.schema);
|
|
1215
|
-
const executeOptions: CLIRunOptions = {
|
|
1216
|
-
...options,
|
|
1217
|
-
...preflight.inputs,
|
|
1218
|
-
out: createOutput({
|
|
1219
|
-
stdout: adapter.stdout,
|
|
1220
|
-
stderr: adapter.stderr,
|
|
1221
|
-
jsonMode: preflight.inputs.jsonMode,
|
|
1222
|
-
isTTY: preflight.inputs.isTTY,
|
|
1223
|
-
...(preflight.inputs.verbosity !== 'normal'
|
|
1224
|
-
? { verbosity: preflight.inputs.verbosity }
|
|
1225
|
-
: {}),
|
|
1226
|
-
}),
|
|
1227
|
-
};
|
|
1228
|
-
const result = await effectiveBuilder.execute(preflight.filteredArgv, executeOptions);
|
|
1229
|
-
|
|
1230
|
-
// Write captured output to real streams via adapter
|
|
1231
|
-
for (const line of result.stdout) {
|
|
1232
|
-
adapter.stdout(line);
|
|
1233
|
-
}
|
|
1234
|
-
for (const line of result.stderr) {
|
|
1235
|
-
adapter.stderr(line);
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
return adapter.exit(result.exitCode);
|
|
1239
|
-
}
|
|
1240
|
-
}
|
|
1241
|
-
const RUNTIME_BINARIES = new Set(['bun', 'deno', 'node', 'tsx']);
|
|
1242
|
-
|
|
1243
|
-
/**
|
|
1244
|
-
* Extract the final path segment from a path-like or URL-like string.
|
|
1245
|
-
*
|
|
1246
|
-
* @param input - Forward- or backslash-delimited path.
|
|
1247
|
-
* @returns Trailing segment, or `undefined` when the input is empty or slash-only.
|
|
1248
|
-
*
|
|
1249
|
-
* @internal
|
|
1250
|
-
*/
|
|
1251
|
-
function basename(input: string): string | undefined {
|
|
1252
|
-
const trimmed = stripTrailing(input, [SLASH, BACKSLASH]);
|
|
1253
|
-
if (trimmed.length === 0) return undefined;
|
|
1254
|
-
const slashIdx = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
|
|
1255
|
-
const name = slashIdx >= 0 ? trimmed.slice(slashIdx + 1) : trimmed;
|
|
1256
|
-
return name.length > 0 ? name : undefined;
|
|
1257
|
-
}
|
|
1258
|
-
|
|
1259
|
-
/**
|
|
1260
|
-
* Detect known interpreter/runtime binary names (node, bun, deno, tsx).
|
|
1261
|
-
*
|
|
1262
|
-
* @param input - Candidate binary name, with or without `.exe` suffix.
|
|
1263
|
-
* @returns `true` when `input` matches a known runtime after normalization.
|
|
1264
|
-
*
|
|
1265
|
-
* @internal
|
|
1266
|
-
*/
|
|
1267
|
-
function isRuntimeBinaryName(input: string): boolean {
|
|
1268
|
-
const normalized = input.toLowerCase().replace(/\.exe$/i, '');
|
|
1269
|
-
return RUNTIME_BINARIES.has(normalized);
|
|
1270
|
-
}
|
|
1271
|
-
|
|
1272
|
-
/**
|
|
1273
|
-
* Infer the displayed CLI name from the current runtime invocation.
|
|
1274
|
-
*
|
|
1275
|
-
* Resolution order:
|
|
1276
|
-
* 1. Node/Bun/tsx-style interpreters → script/entry argument basename
|
|
1277
|
-
* 2. Standalone executable invocations → argv[0] basename
|
|
1278
|
-
* 3. `undefined` when no stable entrypoint can be inferred (e.g. Deno synthetic argv)
|
|
1279
|
-
*
|
|
1280
|
-
* @param argv - Full process argv (typically `process.argv` or adapter equivalent).
|
|
1281
|
-
* @returns Inferred program name, or `undefined` when inference is ambiguous.
|
|
1282
|
-
*
|
|
1283
|
-
* @internal
|
|
1284
|
-
*/
|
|
1285
|
-
function inferInvocationName(argv: readonly string[]): string | undefined {
|
|
1286
|
-
const argv0 = argv[0];
|
|
1287
|
-
const argv1 = argv[1];
|
|
1288
|
-
const runtimeName = argv0 !== undefined ? basename(argv0) : undefined;
|
|
1289
|
-
|
|
1290
|
-
if (runtimeName !== undefined && isRuntimeBinaryName(runtimeName)) {
|
|
1291
|
-
if (runtimeName === 'bun' && argv1 === 'run') {
|
|
1292
|
-
const entryArg = argv[2];
|
|
1293
|
-
if (entryArg === undefined || entryArg.startsWith('-')) return undefined;
|
|
1294
|
-
return basename(entryArg);
|
|
1295
|
-
}
|
|
1296
|
-
if (runtimeName === 'deno' && argv1 === 'run') return undefined;
|
|
1297
|
-
if (argv1 === undefined || argv1.startsWith('-')) return undefined;
|
|
1298
|
-
return basename(argv1);
|
|
1299
|
-
}
|
|
1300
|
-
|
|
1301
|
-
return argv0 !== undefined ? basename(argv0) : undefined;
|
|
1302
|
-
}
|
|
1303
|
-
|
|
1304
|
-
// --- Help link helpers
|
|
1305
|
-
|
|
1306
|
-
/** Coerce a `string | URL` link input to its string form. @internal */
|
|
1307
|
-
function toUrlString(value: string | URL | undefined): string | undefined {
|
|
1308
|
-
if (value === undefined) return undefined;
|
|
1309
|
-
return value instanceof URL ? value.href : value;
|
|
1310
|
-
}
|
|
1311
|
-
|
|
1312
|
-
/**
|
|
1313
|
-
* Resolve derived help links against pre-loaded package.json data.
|
|
1314
|
-
*
|
|
1315
|
-
* `.run()` resolves links during runtime preflight (where discovered
|
|
1316
|
-
* package.json metadata lives); this covers the filesystem-free
|
|
1317
|
-
* `.execute()` path, where only the `.packageJson(data)` overload can
|
|
1318
|
-
* contribute. Idempotent — already-resolved fields pass through unchanged.
|
|
1319
|
-
*
|
|
1320
|
-
* @internal
|
|
1321
|
-
*/
|
|
1322
|
-
function resolveHelpLinksSchema(schema: CLISchema): CLISchema {
|
|
1323
|
-
if (schema.helpLinks === undefined) return schema;
|
|
1324
|
-
return {
|
|
1325
|
-
...schema,
|
|
1326
|
-
helpLinks: deriveHelpLinks(schema.helpLinks, schema.packageJsonSettings?.data, schema.version),
|
|
1327
|
-
};
|
|
1328
|
-
}
|
|
1329
|
-
|
|
1330
|
-
// --- manifest discovery settings
|
|
1331
|
-
|
|
1332
|
-
/** Default manifest filenames for `.manifest()` / `.packageJson()`. @internal */
|
|
1333
|
-
const DEFAULT_MANIFEST_FILES: readonly string[] = ['package.json'];
|
|
1334
|
-
|
|
1335
|
-
/** Manifest filenames for the `.denoJson()` preset, in priority order. @internal */
|
|
1336
|
-
const DENO_MANIFEST_FILES: readonly string[] = ['deno.json', 'deno.jsonc', 'jsr.json'];
|
|
1337
|
-
|
|
1338
|
-
/**
|
|
1339
|
-
* CLI-name inference control for {@link ManifestSettings.inferName}.
|
|
1340
|
-
*
|
|
1341
|
-
* - `false` (or omitted): do not infer the name.
|
|
1342
|
-
* - `true`: infer, stripping a leading `@scope/` from the `name` fallback.
|
|
1343
|
-
* - `{ scope: 'keep' }`: infer, keeping the full scoped name.
|
|
1344
|
-
* - `{ scope: 'strip' }`: infer, stripping the scope (explicit form of `true`).
|
|
1345
|
-
*
|
|
1346
|
-
* `scope` is required in the object form: an empty `{}` is rejected so that an
|
|
1347
|
-
* options object can never silently enable inference (use `true` for that).
|
|
1348
|
-
*/
|
|
1349
|
-
type InferNameOption = boolean | { readonly scope: 'keep' | 'strip' };
|
|
1350
|
-
|
|
1351
|
-
/** Discovery settings accepted by {@link CLIBuilder.manifest}. */
|
|
1352
|
-
interface ManifestSettings {
|
|
1353
|
-
/** Infer the CLI name from `bin` keys or `name`. @defaultValue `false` */
|
|
1354
|
-
readonly inferName?: InferNameOption;
|
|
1355
|
-
/** Anchor discovery to a file/URL/path instead of `cwd`. */
|
|
1356
|
-
readonly from?: string | URL;
|
|
1357
|
-
/**
|
|
1358
|
-
* Candidate manifest filenames in priority order — NOT npm's `files` publish
|
|
1359
|
-
* globs. Discovery probes each name per directory and takes the first that
|
|
1360
|
-
* parses.
|
|
1361
|
-
*
|
|
1362
|
-
* @defaultValue `['package.json']`
|
|
1363
|
-
*/
|
|
1364
|
-
readonly files?: readonly string[];
|
|
1365
|
-
}
|
|
1366
|
-
|
|
1367
|
-
/**
|
|
1368
|
-
* Discovery settings for the `.packageJson()` / `.denoJson()` presets (no `files`).
|
|
1369
|
-
*
|
|
1370
|
-
* @deprecated Both presets are deprecated; use {@link ManifestSettings} with
|
|
1371
|
-
* {@link CLIBuilder.manifest}.
|
|
1372
|
-
*/
|
|
1373
|
-
type ManifestPresetSettings = Omit<ManifestSettings, 'files'>;
|
|
1374
|
-
|
|
1375
|
-
/**
|
|
1376
|
-
* Normalise an {@link InferNameOption} into the flat `{ inferName, stripScope }`
|
|
1377
|
-
* pair stored in {@link ResolvedManifestSettings}.
|
|
1378
|
-
*
|
|
1379
|
-
* @internal
|
|
1380
|
-
*/
|
|
1381
|
-
function normalizeInferName(option: InferNameOption | undefined): {
|
|
1382
|
-
readonly inferName: boolean;
|
|
1383
|
-
readonly stripScope: boolean;
|
|
1384
|
-
} {
|
|
1385
|
-
if (option === undefined || option === false) return { inferName: false, stripScope: true };
|
|
1386
|
-
if (option === true) return { inferName: true, stripScope: true };
|
|
1387
|
-
return { inferName: true, stripScope: option.scope !== 'keep' };
|
|
1388
|
-
}
|
|
1389
|
-
|
|
1390
|
-
/**
|
|
1391
|
-
* Build the next {@link CLISchema} for a manifest builder method.
|
|
1392
|
-
*
|
|
1393
|
-
* Shared by {@link CLIBuilder.manifest}, {@link CLIBuilder.packageJson}, and
|
|
1394
|
-
* {@link CLIBuilder.denoJson}. The data overload (detected via field shape)
|
|
1395
|
-
* merges `version`/`description` immediately so `.execute()` sees them; the
|
|
1396
|
-
* settings overload stores discovery config for runtime preflight.
|
|
1397
|
-
*
|
|
1398
|
-
* @internal
|
|
1399
|
-
*/
|
|
1400
|
-
function buildManifestSchema(
|
|
1401
|
-
schema: CLISchema,
|
|
1402
|
-
input: PackageJsonData | ManifestSettings | undefined,
|
|
1403
|
-
defaultFiles: readonly string[],
|
|
1404
|
-
pinFiles: boolean,
|
|
1405
|
-
): CLISchema {
|
|
1406
|
-
if (isPackageJsonData(input)) {
|
|
1407
|
-
// Merge data into schema immediately so `.execute()` (which skips runtime
|
|
1408
|
-
// preflight) still picks up version/description. Explicit
|
|
1409
|
-
// `.version()`/`.description()` calls win, matching settings semantics.
|
|
1410
|
-
return {
|
|
1411
|
-
...schema,
|
|
1412
|
-
...(schema.version === undefined && input.version !== undefined
|
|
1413
|
-
? { version: input.version }
|
|
1414
|
-
: {}),
|
|
1415
|
-
...(schema.description === undefined && input.description !== undefined
|
|
1416
|
-
? { description: input.description }
|
|
1417
|
-
: {}),
|
|
1418
|
-
packageJsonSettings: {
|
|
1419
|
-
inferName: false,
|
|
1420
|
-
stripScope: true,
|
|
1421
|
-
from: undefined,
|
|
1422
|
-
files: defaultFiles,
|
|
1423
|
-
data: input,
|
|
1424
|
-
},
|
|
1425
|
-
};
|
|
1426
|
-
}
|
|
1427
|
-
const { inferName, stripScope } = normalizeInferName(input?.inferName);
|
|
1428
|
-
// Presets (`pinFiles`) always use their fixed list: the `Omit<…,'files'>` guard
|
|
1429
|
-
// only stops fresh literals at compile time, so a `ManifestSettings`-typed
|
|
1430
|
-
// variable could otherwise leak `files` through the data-overload dispatch gap.
|
|
1431
|
-
const files = pinFiles ? defaultFiles : (input?.files ?? defaultFiles);
|
|
1432
|
-
return {
|
|
1433
|
-
...schema,
|
|
1434
|
-
packageJsonSettings: {
|
|
1435
|
-
inferName,
|
|
1436
|
-
stripScope,
|
|
1437
|
-
from: normalizeFromSetting(input?.from),
|
|
1438
|
-
files,
|
|
1439
|
-
data: undefined,
|
|
1440
|
-
},
|
|
1441
|
-
};
|
|
1442
|
-
}
|
|
1443
|
-
|
|
1444
|
-
// --- packageJson.from normalisation
|
|
1445
|
-
|
|
1446
|
-
/**
|
|
1447
|
-
* Coerce a {@link ResolvedManifestSettings.from | `manifest.from`} input
|
|
1448
|
-
* (string path, `file:` URL string, or {@link URL} instance) to a plain
|
|
1449
|
-
* filesystem path string. `undefined` passes through unchanged.
|
|
1450
|
-
*
|
|
1451
|
-
* Runtime-agnostic by design — relies only on the `URL` global (available in
|
|
1452
|
-
* every JS runtime) rather than `node:url`, keeping core free of Node
|
|
1453
|
-
* built-ins. Non-`file:` inputs are returned unchanged as paths.
|
|
1454
|
-
*
|
|
1455
|
-
* @internal
|
|
1456
|
-
*/
|
|
1457
|
-
function normalizeFromSetting(from: string | URL | undefined): string | undefined {
|
|
1458
|
-
if (from === undefined) return undefined;
|
|
1459
|
-
if (from instanceof URL) {
|
|
1460
|
-
// Only file: URLs map to a filesystem path; pass others through verbatim.
|
|
1461
|
-
if (from.protocol !== 'file:') return from.href;
|
|
1462
|
-
} else if (!from.startsWith('file:')) {
|
|
1463
|
-
// Plain path (or non-file URL string) — already usable as-is.
|
|
1464
|
-
return from;
|
|
1465
|
-
}
|
|
1466
|
-
|
|
1467
|
-
/*
|
|
1468
|
-
* `URL.pathname` strips the `file://` scheme/authority; `decodeURIComponent`
|
|
1469
|
-
* resolves percent-escapes. A leading-slash drive letter (`/C:/…`) marks a
|
|
1470
|
-
* Windows path — drop the slash and switch to backslashes; otherwise it is a
|
|
1471
|
-
* POSIX path already.
|
|
1472
|
-
*/
|
|
1473
|
-
const decoded = decodeURIComponent(new URL(from).pathname);
|
|
1474
|
-
if (/^\/[A-Za-z]:/.test(decoded)) {
|
|
1475
|
-
return decoded.slice(1).replace(/\//g, '\\');
|
|
1476
|
-
}
|
|
1477
|
-
return decoded;
|
|
1478
|
-
}
|
|
1479
|
-
|
|
1480
|
-
/**
|
|
1481
|
-
* Predicate distinguishing the {@link PackageJsonData | data} overload of
|
|
1482
|
-
* `.packageJson()` from the settings overload at runtime.
|
|
1483
|
-
*
|
|
1484
|
-
* A value is treated as `PackageJsonData` when it's a plain object that
|
|
1485
|
-
* carries at least one recognised field (`name`, `version`, `description`,
|
|
1486
|
-
* `bin`, `homepage`, or `repository`). An empty `{}` or a settings-shaped
|
|
1487
|
-
* object (`inferName` / `from`) falls through to the settings overload.
|
|
1488
|
-
*
|
|
1489
|
-
* npm's `files` field (publish globs) is intentionally NOT recognised here, so
|
|
1490
|
-
* an object whose only key is `files` routes to the settings overload — where
|
|
1491
|
-
* `files` means candidate manifest filenames, never publish globs. Manifests
|
|
1492
|
-
* that publish a CLI carry `name`/`version`, so those route to the data overload
|
|
1493
|
-
* as expected.
|
|
1494
|
-
*
|
|
1495
|
-
* Edge case: a metadata-less manifest (e.g. a versionless private-root
|
|
1496
|
-
* `package.json` carrying only `files`/`private`) routes to settings, so its
|
|
1497
|
-
* `files` would be read as candidate filenames and the object is not stored as
|
|
1498
|
-
* data. This is harmless in practice — a metadata-less manifest contributes no
|
|
1499
|
-
* `version`/`description` either way — but it means a pre-loaded object must
|
|
1500
|
-
* carry real metadata to be honoured as data.
|
|
1501
|
-
*
|
|
1502
|
-
* @internal
|
|
1503
|
-
*/
|
|
1504
|
-
function isPackageJsonData(value: unknown): value is PackageJsonData {
|
|
1505
|
-
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
|
|
1506
|
-
return (
|
|
1507
|
-
'name' in value ||
|
|
1508
|
-
'version' in value ||
|
|
1509
|
-
'description' in value ||
|
|
1510
|
-
'bin' in value ||
|
|
1511
|
-
'homepage' in value ||
|
|
1512
|
-
'repository' in value
|
|
1513
|
-
);
|
|
1514
|
-
}
|
|
1515
|
-
|
|
1516
|
-
// --- Factory function
|
|
1517
|
-
|
|
1518
|
-
/**
|
|
1519
|
-
* Options for the `cli({...})` factory form.
|
|
1520
|
-
*
|
|
1521
|
-
* This form is useful when the displayed CLI name should be inferred from the
|
|
1522
|
-
* current runtime invocation instead of always being hard-coded.
|
|
1523
|
-
*/
|
|
1524
|
-
interface CLIOptions {
|
|
1525
|
-
/**
|
|
1526
|
-
* Explicit fallback CLI name.
|
|
1527
|
-
*
|
|
1528
|
-
* Used by `.execute()`, and by `.run()` when runtime name inheritance is
|
|
1529
|
-
* disabled or the invocation name cannot be inferred.
|
|
1530
|
-
*
|
|
1531
|
-
* @defaultValue `'cli'`
|
|
1532
|
-
*/
|
|
1533
|
-
readonly name?: string;
|
|
1534
|
-
|
|
1535
|
-
/**
|
|
1536
|
-
* Replace `name` with the invoked program basename during `.run()`.
|
|
1537
|
-
*
|
|
1538
|
-
* Examples:
|
|
1539
|
-
* - `node ./bin/mycli.ts` → `mycli.ts`
|
|
1540
|
-
* - `/usr/local/bin/mycli` → `mycli`
|
|
1541
|
-
*
|
|
1542
|
-
* @defaultValue `false`
|
|
1543
|
-
*/
|
|
1544
|
-
readonly inherit?: boolean;
|
|
1545
|
-
}
|
|
1546
|
-
|
|
1547
|
-
/**
|
|
1548
|
-
* Create a new CLI program builder.
|
|
1549
|
-
*
|
|
1550
|
-
* The CLI name is used in help text, usage lines, and generated completion scripts.
|
|
1551
|
-
*
|
|
1552
|
-
* @example
|
|
1553
|
-
* ```ts
|
|
1554
|
-
* cli('mycli')
|
|
1555
|
-
* .version('1.0.0')
|
|
1556
|
-
* .description('My awesome tool')
|
|
1557
|
-
* .command(deploy)
|
|
1558
|
-
* .command(login)
|
|
1559
|
-
* .run();
|
|
1560
|
-
*
|
|
1561
|
-
* cli({ inherit: true })
|
|
1562
|
-
* .command(deploy)
|
|
1563
|
-
* .run();
|
|
1564
|
-
* ```
|
|
1565
|
-
*/
|
|
1566
|
-
|
|
1567
|
-
function cli(name: string): CLIBuilder;
|
|
1568
|
-
/** Create a new CLI program builder from an options object. */
|
|
1569
|
-
function cli(options: CLIOptions): CLIBuilder;
|
|
1570
|
-
function cli(nameOrOptions: string | CLIOptions): CLIBuilder {
|
|
1571
|
-
const name = typeof nameOrOptions === 'string' ? nameOrOptions : (nameOrOptions.name ?? 'cli');
|
|
1572
|
-
const inheritName = typeof nameOrOptions === 'string' ? false : (nameOrOptions.inherit ?? false);
|
|
1573
|
-
|
|
1574
|
-
return new CLIBuilder({
|
|
1575
|
-
name,
|
|
1576
|
-
inheritName,
|
|
1577
|
-
version: undefined,
|
|
1578
|
-
description: undefined,
|
|
1579
|
-
commands: [],
|
|
1580
|
-
defaultCommand: undefined,
|
|
1581
|
-
configSettings: undefined,
|
|
1582
|
-
packageJsonSettings: undefined,
|
|
1583
|
-
helpLinks: undefined,
|
|
1584
|
-
hasBuiltInCompletions: false,
|
|
1585
|
-
completionsFlag: undefined,
|
|
1586
|
-
helpConfig: undefined,
|
|
1587
|
-
plugins: [],
|
|
1588
|
-
});
|
|
1589
|
-
}
|
|
1590
|
-
|
|
1591
|
-
// --- Exports
|
|
1592
|
-
|
|
1593
|
-
export type { HelpLinks } from './help-links.ts';
|
|
1594
|
-
export type {
|
|
1595
|
-
BeforeParseParams,
|
|
1596
|
-
CLIPlugin,
|
|
1597
|
-
CLIPluginHooks,
|
|
1598
|
-
PluginCommandContext,
|
|
1599
|
-
ResolvedCommandParams,
|
|
1600
|
-
} from './plugin.ts';
|
|
1601
|
-
export type {
|
|
1602
|
-
CLIOptions,
|
|
1603
|
-
CLIRunOptions,
|
|
1604
|
-
CLISchema,
|
|
1605
|
-
CompletionsFlagConfig,
|
|
1606
|
-
ConfigSettings,
|
|
1607
|
-
HelpConfig,
|
|
1608
|
-
InferNameOption,
|
|
1609
|
-
ManifestPresetSettings,
|
|
1610
|
-
ManifestSettings,
|
|
1611
|
-
PackageJsonSettings,
|
|
1612
|
-
ResolvedManifestSettings,
|
|
1613
|
-
};
|
|
1614
|
-
export { CLIBuilder, cli, formatRootHelp, plugin };
|