@kjanat/dreamcli 1.0.0 → 2.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/CHANGELOG.md +45 -6
- package/LICENSE +1 -1
- package/README.md +296 -164
- package/dist/core/cli/dispatch.d.mts +85 -0
- package/dist/core/cli/dispatch.mjs +1 -0
- package/dist/core/cli/index.d.mts +418 -0
- package/dist/core/cli/index.mjs +1 -0
- package/dist/core/cli/planner.d.mts +143 -0
- package/dist/core/cli/planner.mjs +1 -0
- package/dist/core/cli/plugin.d.mts +94 -0
- package/dist/core/cli/plugin.mjs +1 -0
- package/dist/core/cli/propagate.d.mts +39 -0
- package/dist/core/cli/propagate.mjs +1 -0
- package/dist/core/cli/root-help.d.mts +28 -0
- package/dist/core/cli/root-help.mjs +7 -0
- package/dist/core/cli/root-surface.d.mts +42 -0
- package/dist/core/cli/root-surface.mjs +1 -0
- package/dist/core/cli/runtime-preflight.d.mts +149 -0
- package/dist/core/cli/runtime-preflight.mjs +1 -0
- package/dist/core/completion/index.d.mts +46 -0
- package/dist/core/completion/index.mjs +1 -0
- package/dist/core/completion/shells/bash.d.mts +24 -0
- package/dist/core/completion/shells/bash.mjs +3 -0
- package/dist/core/completion/shells/fish.d.mts +20 -0
- package/dist/core/completion/shells/fish.mjs +2 -0
- package/dist/core/completion/shells/powershell.d.mts +14 -0
- package/dist/core/completion/shells/powershell.mjs +2 -0
- package/dist/core/completion/shells/shared.d.mts +139 -0
- package/dist/core/completion/shells/shared.mjs +1 -0
- package/dist/core/completion/shells/zsh.d.mts +24 -0
- package/dist/core/completion/shells/zsh.mjs +2 -0
- package/dist/core/config/index.d.mts +161 -0
- package/dist/core/config/index.mjs +1 -0
- package/dist/core/config/package-json.d.mts +68 -0
- package/dist/core/config/package-json.mjs +1 -0
- package/dist/core/errors/index.d.mts +126 -0
- package/dist/core/errors/index.mjs +1 -0
- package/dist/core/execution/index.d.mts +49 -0
- package/dist/core/execution/index.mjs +1 -0
- package/dist/core/help/index.d.mts +49 -0
- package/dist/core/help/index.mjs +8 -0
- package/dist/core/json-schema/index.d.mts +109 -0
- package/dist/core/json-schema/index.mjs +55 -0
- package/dist/core/json-schema/meta-descriptions.generated.d.mts +185 -0
- package/dist/core/json-schema/meta-descriptions.generated.mjs +28 -0
- package/dist/core/output/activity.d.mts +194 -0
- package/dist/core/output/activity.mjs +1 -0
- package/dist/core/output/contracts.d.mts +88 -0
- package/dist/core/output/contracts.mjs +1 -0
- package/dist/core/output/display-value.d.mts +19 -0
- package/dist/core/output/display-value.mjs +1 -0
- package/dist/core/output/index.d.mts +280 -0
- package/dist/core/output/index.mjs +2 -0
- package/dist/core/output/renderers.d.mts +46 -0
- package/dist/core/output/renderers.mjs +1 -0
- package/dist/core/output/writer.d.mts +40 -0
- package/dist/core/output/writer.mjs +1 -0
- package/dist/core/parse/index.d.mts +79 -0
- package/dist/core/parse/index.mjs +1 -0
- package/dist/core/prompt/index.d.mts +205 -0
- package/dist/core/prompt/index.mjs +6 -0
- package/dist/core/resolve/args.d.mts +8 -0
- package/dist/core/resolve/args.mjs +1 -0
- package/dist/core/resolve/coerce.d.mts +22 -0
- package/dist/core/resolve/coerce.mjs +1 -0
- package/dist/core/resolve/config.d.mts +10 -0
- package/dist/core/resolve/config.mjs +1 -0
- package/dist/core/resolve/contracts.d.mts +112 -0
- package/dist/core/resolve/errors.d.mts +11 -0
- package/dist/core/resolve/errors.mjs +2 -0
- package/dist/core/resolve/flags.d.mts +10 -0
- package/dist/core/resolve/flags.mjs +1 -0
- package/dist/core/resolve/index.d.mts +42 -0
- package/dist/core/resolve/index.mjs +1 -0
- package/dist/core/resolve/property.d.mts +47 -0
- package/dist/core/resolve/property.mjs +1 -0
- package/dist/core/schema/activity.d.mts +169 -0
- package/dist/core/schema/arg.d.mts +559 -0
- package/dist/core/schema/arg.mjs +1 -0
- package/dist/core/schema/command.d.mts +960 -0
- package/dist/core/schema/command.mjs +1 -0
- package/dist/core/schema/flag.d.mts +491 -0
- package/dist/core/schema/flag.mjs +1 -0
- package/dist/core/schema/index.d.mts +8 -0
- package/dist/core/schema/middleware.d.mts +122 -0
- package/dist/core/schema/middleware.mjs +1 -0
- package/dist/core/schema/prompt.d.mts +117 -0
- package/dist/core/schema/run.d.mts +171 -0
- package/dist/core/schema-dsl/runtime.d.mts +144 -0
- package/dist/core/schema-dsl/runtime.mjs +2 -0
- package/dist/core/schema-dsl/to-json-schema.d.mts +30 -0
- package/dist/core/schema-dsl/to-json-schema.mjs +1 -0
- package/dist/core/testkit/index.d.mts +54 -0
- package/dist/core/testkit/index.mjs +1 -0
- package/dist/index.d.mts +28 -920
- package/dist/index.mjs +1 -10
- package/dist/runtime/adapter.d.mts +212 -0
- package/dist/{adapter-B37d9oia.mjs → runtime/adapter.mjs} +1 -1
- package/dist/runtime/auto.d.mts +26 -0
- package/dist/runtime/auto.mjs +1 -0
- package/dist/runtime/bun.d.mts +28 -0
- package/dist/runtime/bun.mjs +1 -0
- package/dist/runtime/deno.d.mts +76 -0
- package/dist/runtime/deno.mjs +2 -0
- package/dist/runtime/detect.d.mts +86 -0
- package/dist/runtime/detect.mjs +1 -0
- package/dist/runtime/index.d.mts +7 -0
- package/dist/runtime/node.d.mts +65 -0
- package/dist/runtime/node.mjs +2 -0
- package/dist/runtime/paths.d.mts +31 -0
- package/dist/runtime/paths.mjs +1 -0
- package/dist/runtime/support.d.mts +42 -0
- package/dist/runtime/support.mjs +1 -0
- package/dist/runtime.d.mts +6 -252
- package/dist/runtime.mjs +1 -1
- package/dist/testkit.d.mts +5 -24
- package/dist/testkit.mjs +1 -1
- package/dist/version.d.mts +16 -0
- package/dist/version.mjs +1 -0
- package/dreamcli.schema.json +338 -0
- package/examples/basic.ts +2 -2
- package/examples/gh/package.json +7 -11
- package/examples/gh/src/commands/auth.ts +2 -2
- package/examples/gh/src/commands/issue.ts +4 -4
- package/examples/gh/src/commands/pr.ts +4 -4
- package/examples/gh/src/docs.ts +11 -0
- package/examples/gh/src/lib/auth.ts +1 -1
- package/examples/gh/src/main.test.ts +6 -5
- package/examples/gh/src/main.ts +8 -6
- package/examples/interactive.ts +3 -3
- package/examples/json-mode.ts +4 -6
- package/examples/middleware.ts +3 -3
- package/examples/multi-command.ts +3 -3
- package/examples/spinner-progress.ts +5 -5
- package/examples/testing.ts +8 -6
- package/package.json +70 -44
- package/src/core/cli/dispatch.ts +4 -0
- package/src/core/cli/index.ts +185 -632
- package/src/core/cli/planner.ts +413 -0
- package/src/core/cli/plugin.ts +7 -1
- package/src/core/cli/propagate.ts +1 -1
- package/src/core/cli/runtime-preflight.ts +409 -0
- package/src/core/completion/index.ts +15 -9
- package/src/core/completion/shells/bash.ts +6 -3
- package/src/core/completion/shells/fish.ts +245 -10
- package/src/core/completion/shells/powershell.ts +390 -9
- package/src/core/completion/shells/shared.ts +4 -4
- package/src/core/completion/shells/zsh.ts +12 -7
- package/src/core/config/index.ts +7 -4
- package/src/core/config/package-json.ts +6 -2
- package/src/core/errors/index.ts +23 -8
- package/src/core/execution/index.ts +270 -0
- package/src/core/help/index.ts +13 -15
- package/src/core/json-schema/index.ts +193 -7
- package/src/core/json-schema/meta-descriptions.generated.ts +202 -0
- package/src/core/output/contracts.ts +194 -0
- package/src/core/output/index.ts +47 -82
- package/src/core/output/renderers.ts +125 -0
- package/src/core/parse/index.ts +39 -21
- package/src/core/prompt/index.ts +44 -27
- package/src/core/resolve/args.ts +144 -0
- package/src/core/resolve/coerce.ts +432 -0
- package/src/core/resolve/config.ts +26 -0
- package/src/core/resolve/contracts.ts +135 -0
- package/src/core/resolve/errors.ts +227 -0
- package/src/core/resolve/flags.ts +205 -0
- package/src/core/resolve/index.ts +41 -1264
- package/src/core/resolve/property.ts +99 -0
- package/src/core/schema/activity.ts +3 -0
- package/src/core/schema/arg.ts +26 -14
- package/src/core/schema/command.ts +265 -38
- package/src/core/schema/flag.ts +120 -15
- package/src/core/schema/index.ts +11 -2
- package/src/core/schema/middleware.ts +6 -6
- package/src/core/schema/prompt.ts +9 -1
- package/src/core/schema/run.ts +25 -17
- package/src/core/schema-dsl/index.ts +109 -0
- package/src/core/schema-dsl/parse.ts +262 -0
- package/src/core/schema-dsl/runtime.ts +609 -0
- package/src/core/schema-dsl/to-json-schema.ts +102 -0
- package/src/core/testkit/index.ts +55 -297
- package/src/index.ts +10 -4
- package/src/runtime/adapter.ts +13 -10
- package/src/runtime/auto.ts +3 -3
- package/src/runtime/bun.ts +4 -4
- package/src/runtime/deno.ts +43 -29
- package/src/runtime/detect.ts +4 -1
- package/src/runtime/index.ts +1 -1
- package/src/runtime/node.ts +43 -21
- package/src/runtime/paths.ts +9 -3
- package/src/runtime/support.ts +20 -4
- package/src/runtime.ts +1 -1
- package/src/testkit.ts +10 -8
- package/dist/adapter-CCSh5juX.cjs +0 -1
- package/dist/adapter-DIwO-q7K.d.mts +0 -3447
- package/dist/adapter-DQnxxLiE.d.cts +0 -3447
- package/dist/auto-5cjZaF9V.mjs +0 -3
- package/dist/auto-B0eSgoDw.cjs +0 -3
- package/dist/index.cjs +0 -10
- package/dist/index.d.cts +0 -920
- package/dist/runtime.cjs +0 -1
- package/dist/runtime.d.cts +0 -253
- package/dist/testkit-CEDYPvhF.mjs +0 -14
- package/dist/testkit-ClIKijxC.cjs +0 -14
- package/dist/testkit.cjs +0 -1
- package/dist/testkit.d.cts +0 -25
- package/examples/gh/tsconfig.json +0 -37
- package/examples/tsconfig.json +0 -17
- package/src/core/cli/AGENTS.md +0 -72
- package/src/core/completion/AGENTS.md +0 -72
- package/src/core/completion/completion-test-helpers.ts +0 -48
- package/src/core/output/AGENTS.md +0 -69
- package/src/core/resolve/AGENTS.md +0 -69
- package/src/core/schema/AGENTS.md +0 -61
- package/src/core/testkit/AGENTS.md +0 -55
- package/src/runtime/AGENTS.md +0 -74
- package/src/runtime/test-helpers.ts +0 -40
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { CommandSchema, ErasedCommand } from "../schema/command.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/core/cli/dispatch.d.ts
|
|
4
|
+
/** Successful dispatch — target command found with argv path. */
|
|
5
|
+
interface DispatchMatch {
|
|
6
|
+
/** Discriminant — a command name in argv matched a registered command. */
|
|
7
|
+
readonly kind: 'match';
|
|
8
|
+
/** The matched (target) command. */
|
|
9
|
+
readonly command: ErasedCommand;
|
|
10
|
+
/** Root → target (inclusive). Used for `collectPropagatedFlags()`. */
|
|
11
|
+
readonly commandPath: readonly CommandSchema[];
|
|
12
|
+
/** argv after consuming command name segments. */
|
|
13
|
+
readonly remainingArgv: readonly string[];
|
|
14
|
+
}
|
|
15
|
+
/** Target has subcommands but no handler and no subcommand was specified/matched. */
|
|
16
|
+
interface DispatchNeedsSubcommand {
|
|
17
|
+
/** Discriminant — command group reached without a subcommand or handler. */
|
|
18
|
+
readonly kind: 'needs-subcommand';
|
|
19
|
+
/** The group command that needs a subcommand. */
|
|
20
|
+
readonly command: ErasedCommand;
|
|
21
|
+
/** Root → group (inclusive). */
|
|
22
|
+
readonly commandPath: readonly CommandSchema[];
|
|
23
|
+
}
|
|
24
|
+
/** Unknown command name at this dispatch level. */
|
|
25
|
+
interface DispatchUnknown {
|
|
26
|
+
/** Discriminant — no registered command matched the input token. */
|
|
27
|
+
readonly kind: 'unknown';
|
|
28
|
+
/** The unrecognised input token. Empty string when no token present. */
|
|
29
|
+
readonly input: string;
|
|
30
|
+
/** Commands available at the level where matching failed. */
|
|
31
|
+
readonly candidates: readonly ErasedCommand[];
|
|
32
|
+
/** Ancestor path up to (but not including) the unknown level. */
|
|
33
|
+
readonly parentPath: readonly CommandSchema[];
|
|
34
|
+
}
|
|
35
|
+
/** Discriminated result of recursive command dispatch. */
|
|
36
|
+
type DispatchResult = DispatchMatch | DispatchNeedsSubcommand | DispatchUnknown;
|
|
37
|
+
/**
|
|
38
|
+
* Recursively walk argv, consuming command name segments from the front.
|
|
39
|
+
*
|
|
40
|
+
* At each level, the first non-flag token is tested as a command name
|
|
41
|
+
* against the provided command map. If matched and the matched command
|
|
42
|
+
* has subcommands, dispatch recurses into the child level with the
|
|
43
|
+
* remaining argv.
|
|
44
|
+
*
|
|
45
|
+
* Ambiguity resolution for commands that have both an action handler AND
|
|
46
|
+
* subcommands (e.g. `git remote` lists remotes, `git remote add` dispatches):
|
|
47
|
+
* - If the next token matches a subcommand → descend
|
|
48
|
+
* - If the next token is unknown and the command has a handler → match here
|
|
49
|
+
* - If the next token is unknown and no handler → propagate unknown error
|
|
50
|
+
* - If no next token and command has a handler → match here
|
|
51
|
+
* - If no next token and no handler → needs-subcommand
|
|
52
|
+
*
|
|
53
|
+
* @param argv - Remaining argv tokens (command names + flags + args).
|
|
54
|
+
* @param commands - Command map at the current tree level.
|
|
55
|
+
* @param ancestorPath - Schema path from root to current level (exclusive).
|
|
56
|
+
* @returns Discriminated dispatch result.
|
|
57
|
+
*
|
|
58
|
+
* @internal
|
|
59
|
+
*/
|
|
60
|
+
declare function dispatch(argv: readonly string[], commands: ReadonlyMap<string, ErasedCommand>, ancestorPath?: readonly CommandSchema[]): DispatchResult;
|
|
61
|
+
/**
|
|
62
|
+
* Levenshtein distance between two strings.
|
|
63
|
+
* @internal
|
|
64
|
+
*/
|
|
65
|
+
declare function levenshtein(a: string, b: string): number;
|
|
66
|
+
/**
|
|
67
|
+
* Find the closest command name match for a "did you mean?" suggestion.
|
|
68
|
+
*
|
|
69
|
+
* Searches command names and aliases. Returns `undefined` if no
|
|
70
|
+
* sufficiently close match exists (threshold: 3).
|
|
71
|
+
*
|
|
72
|
+
* @internal
|
|
73
|
+
*/
|
|
74
|
+
declare function findClosestCommand(input: string, commands: readonly ErasedCommand[]): string | undefined;
|
|
75
|
+
/**
|
|
76
|
+
* Deduplicate commands from a name+alias map.
|
|
77
|
+
*
|
|
78
|
+
* A map keyed by name *and* alias contains duplicate entries for aliased
|
|
79
|
+
* commands. This returns unique commands (by schema identity).
|
|
80
|
+
*
|
|
81
|
+
* @internal
|
|
82
|
+
*/
|
|
83
|
+
declare function uniqueCommands(commands: ReadonlyMap<string, ErasedCommand>): readonly ErasedCommand[];
|
|
84
|
+
//#endregion
|
|
85
|
+
export { type DispatchMatch, type DispatchNeedsSubcommand, type DispatchResult, type DispatchUnknown, dispatch, findClosestCommand, levenshtein, uniqueCommands };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(t,n,i=[]){let a=-1;for(let e=0;e<t.length;e++){let n=t[e];if(n===`--`){e+1<t.length&&(a=e+1);break}if(n!==void 0&&!n.startsWith(`-`)){a=e;break}}if(a===-1)return{kind:`unknown`,input:``,candidates:r(n),parentPath:i};let o=t[a];if(o===void 0)return{kind:`unknown`,input:``,candidates:r(n),parentPath:i};let s=n.get(o);if(s===void 0)return{kind:`unknown`,input:o,candidates:r(n),parentPath:i};let c=[...t.slice(0,a),...t.slice(a+1)],l=[...i,s.schema];if(s.subcommands.size>0){let t=e(c,s.subcommands,l);switch(t.kind){case`match`:return t;case`unknown`:return t.input===``?s.schema.hasAction?{kind:`match`,command:s,commandPath:l,remainingArgv:c}:{kind:`needs-subcommand`,command:s,commandPath:l}:s.schema.hasAction?{kind:`match`,command:s,commandPath:l,remainingArgv:c}:t;case`needs-subcommand`:return t;default:return t}}return{kind:`match`,command:s,commandPath:l,remainingArgv:c}}function t(e,t){let n=e.length,r=t.length,i=r+1,a=new Uint16Array(i),o=new Uint16Array(i);for(let e=0;e<=r;e++)a[e]=e;for(let i=1;i<=n;i++){o[0]=i;for(let n=1;n<=r;n++){let r=e.charAt(i-1)===t.charAt(n-1)?0:1,s=a[n]??0,c=o[n-1]??0,l=a[n-1]??0;o[n]=Math.min(s+1,c+1,l+r)}[a,o]=[o,a]}return a[r]??Math.max(n,r)}function n(e,n){let r,i=4;for(let a of n){let n=t(e,a.schema.name);n<i&&(i=n,r=a.schema.name);for(let n of a.schema.aliases){let o=t(e,n);o<i&&(i=o,r=a.schema.name)}}return i<=3?r:void 0}function r(e){let t=new Set,n=[];for(let r of e.values())t.has(r)||(t.add(r),n.push(r));return n}export{e as dispatch,n as findClosestCommand};
|
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import { ArgBuilder, ArgConfig } from "../schema/arg.mjs";
|
|
2
|
+
import { FlagBuilder, FlagConfig } from "../schema/flag.mjs";
|
|
3
|
+
import { BeforeParseParams, CLIPlugin, CLIPluginHooks, PluginCommandContext, ResolvedCommandParams, plugin } from "./plugin.mjs";
|
|
4
|
+
import { RunOptions, RunResult } from "../schema/run.mjs";
|
|
5
|
+
import { CommandBuilder, ErasedCommand } from "../schema/command.mjs";
|
|
6
|
+
import { CompletionOptions } from "../completion/shells/shared.mjs";
|
|
7
|
+
import { RuntimeAdapter } from "../../runtime/adapter.mjs";
|
|
8
|
+
import { FormatLoader } from "../config/index.mjs";
|
|
9
|
+
import { formatRootHelp } from "./root-help.mjs";
|
|
10
|
+
|
|
11
|
+
//#region src/core/cli/index.d.ts
|
|
12
|
+
/**
|
|
13
|
+
* Runtime descriptor for the CLI program.
|
|
14
|
+
*
|
|
15
|
+
* Stores the program name, version, description, and registered commands.\
|
|
16
|
+
* Built incrementally by {@linkcode CLIBuilder}.
|
|
17
|
+
*/
|
|
18
|
+
interface CLISchema {
|
|
19
|
+
/** Program name (used in help text, usage lines, and completion scripts). */
|
|
20
|
+
readonly name: string;
|
|
21
|
+
/**
|
|
22
|
+
* Whether `.run()` should replace `name` with the invoked program name.
|
|
23
|
+
*
|
|
24
|
+
* Set via the `cli({ inherit: true })` factory form.
|
|
25
|
+
*/
|
|
26
|
+
readonly inheritName: boolean;
|
|
27
|
+
/** Program version (shown by `--version`). */
|
|
28
|
+
readonly version: string | undefined;
|
|
29
|
+
/** Program description (shown in root help). */
|
|
30
|
+
readonly description: string | undefined;
|
|
31
|
+
/** Registered commands (type-erased for heterogeneous storage). */
|
|
32
|
+
readonly commands: readonly ErasedCommand[];
|
|
33
|
+
/**
|
|
34
|
+
* Default command dispatched when no subcommand matches.
|
|
35
|
+
*
|
|
36
|
+
* When set, the CLI root behaves like a hybrid command group: subcommands
|
|
37
|
+
* dispatch by name as usual, but empty argv or flags-only argv falls
|
|
38
|
+
* through to this command instead of showing root help.
|
|
39
|
+
*
|
|
40
|
+
* Set via the {@linkcode CLIBuilder.default | .default()} builder method.
|
|
41
|
+
*/
|
|
42
|
+
readonly defaultCommand: ErasedCommand | undefined;
|
|
43
|
+
/**
|
|
44
|
+
* Config discovery settings.
|
|
45
|
+
*
|
|
46
|
+
* When defined, {@linkcode CLIBuilder.run | .run()} auto-discovers and loads a config file before command dispatch.
|
|
47
|
+
*
|
|
48
|
+
* Set via the {@linkcode CLIBuilder.config | .config()} builder method.
|
|
49
|
+
*/
|
|
50
|
+
readonly configSettings: ConfigSettings | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* Package.json auto-discovery settings. When defined, `.run()` discovers
|
|
53
|
+
* the nearest `package.json` and merges metadata before dispatch.
|
|
54
|
+
*
|
|
55
|
+
* Set via the {@linkcode CLIBuilder.packageJson | .packageJson()} builder method.
|
|
56
|
+
*/
|
|
57
|
+
readonly packageJsonSettings: PackageJsonSettings | undefined;
|
|
58
|
+
/** Whether built-in `.completions()` command registration is active. */
|
|
59
|
+
readonly hasBuiltInCompletions: boolean;
|
|
60
|
+
/** Registered CLI plugins. */
|
|
61
|
+
readonly plugins: readonly CLIPlugin[];
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Config discovery settings for automatic config file loading.
|
|
65
|
+
*
|
|
66
|
+
* Stored in {@link CLISchema} and consumed by {@linkcode CLIBuilder.run()} to call
|
|
67
|
+
* {@link discoverConfig} before dispatching to a command.
|
|
68
|
+
*/
|
|
69
|
+
interface ConfigSettings {
|
|
70
|
+
/**
|
|
71
|
+
* Application name used to build config search paths.
|
|
72
|
+
*
|
|
73
|
+
* Search paths: `.{appName}.json` (cwd), `{appName}.config.json` (cwd),
|
|
74
|
+
* and `{configDir}/{appName}/config.json` where `configDir` is
|
|
75
|
+
* `$XDG_CONFIG_HOME` / `~/.config` on Unix or `%APPDATA%` /
|
|
76
|
+
* `%USERPROFILE%\\AppData\\Roaming` on Windows.
|
|
77
|
+
*/
|
|
78
|
+
readonly appName: string;
|
|
79
|
+
/** Additional format loaders beyond the built-in JSON loader. */
|
|
80
|
+
readonly loaders: readonly FormatLoader[] | undefined;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Package.json auto-discovery settings.
|
|
84
|
+
*
|
|
85
|
+
* Stored in {@link CLISchema} and consumed by `CLIBuilder.run()` to
|
|
86
|
+
* call {@link discoverPackageJson} before dispatching to a command.
|
|
87
|
+
*/
|
|
88
|
+
interface PackageJsonSettings {
|
|
89
|
+
/**
|
|
90
|
+
* Infer CLI name from package.json `bin` keys or `name` field.
|
|
91
|
+
*
|
|
92
|
+
* When `true`, the discovered name replaces the `cli(name)` value.
|
|
93
|
+
* Explicit `.version()`/`.description()` calls still take precedence
|
|
94
|
+
* over discovered values.
|
|
95
|
+
*
|
|
96
|
+
* @defaultValue `false`
|
|
97
|
+
*/
|
|
98
|
+
readonly inferName: boolean;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Options for {@linkcode CLIBuilder.execute | .execute()} and {@linkcode CLIBuilder.run | .run()}.
|
|
102
|
+
*
|
|
103
|
+
* Derives from {@linkcode RunOptions} while excluding command-execution internals
|
|
104
|
+
* (`meta`, `mergedSchema`) and adding the CLI-level runtime adapter.
|
|
105
|
+
*/
|
|
106
|
+
interface CLIRunOptions extends Omit<RunOptions, 'meta' | 'mergedSchema'> {
|
|
107
|
+
/**
|
|
108
|
+
* Runtime adapter providing platform-specific I/O, argv, env, etc.
|
|
109
|
+
*
|
|
110
|
+
* When provided to `.run()`, replaces the default Node adapter.
|
|
111
|
+
* Ignored by `.execute()` (which is process-free by design).
|
|
112
|
+
*/
|
|
113
|
+
readonly adapter?: RuntimeAdapter;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Immutable CLI program builder.
|
|
117
|
+
*
|
|
118
|
+
* Registers commands, handles root-level `--help`/`--version`, and
|
|
119
|
+
* dispatches to the matched command based on argv.
|
|
120
|
+
*
|
|
121
|
+
* Two execution paths:
|
|
122
|
+
* - `.execute(argv, options?)` — testable, returns {@linkcode RunResult}
|
|
123
|
+
* - `.run(options?)` — production entry, reads `process.argv`, exits process
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* import { cli, command, flag, arg } from '@kjanat/dreamcli';
|
|
128
|
+
*
|
|
129
|
+
* const deploy = command('deploy')
|
|
130
|
+
* .arg('target', arg.string())
|
|
131
|
+
* .flag('force', flag.boolean().alias('f'))
|
|
132
|
+
* .action(({ args, flags, out }) => {
|
|
133
|
+
* out.log(`Deploying ${args.target}...`);
|
|
134
|
+
* });
|
|
135
|
+
*
|
|
136
|
+
* cli('mycli')
|
|
137
|
+
* .version('1.0.0')
|
|
138
|
+
* .command(deploy)
|
|
139
|
+
* .run();
|
|
140
|
+
* ```
|
|
141
|
+
*/
|
|
142
|
+
declare class CLIBuilder {
|
|
143
|
+
/** @internal Runtime schema descriptor. */
|
|
144
|
+
readonly schema: CLISchema;
|
|
145
|
+
/** Build a CLIBuilder from a pre-constructed schema descriptor. */
|
|
146
|
+
constructor(schema: CLISchema);
|
|
147
|
+
/**
|
|
148
|
+
* Set the program version (shown by `--version`).
|
|
149
|
+
*
|
|
150
|
+
* @param v - Semantic version string.
|
|
151
|
+
* @returns The builder (for chaining).
|
|
152
|
+
*/
|
|
153
|
+
version(v: string): CLIBuilder;
|
|
154
|
+
/**
|
|
155
|
+
* Set the program description (shown in root help).
|
|
156
|
+
*
|
|
157
|
+
* @param text - Short description displayed in root help output.
|
|
158
|
+
* @returns The builder (for chaining).
|
|
159
|
+
*/
|
|
160
|
+
description(text: string): CLIBuilder;
|
|
161
|
+
/**
|
|
162
|
+
* Enable automatic config file discovery.
|
|
163
|
+
*
|
|
164
|
+
* When enabled, `.run()` probes standard paths before dispatching:
|
|
165
|
+
* 1. `$CWD/.{appName}.json`
|
|
166
|
+
* 2. `$CWD/{appName}.config.json`
|
|
167
|
+
* 3. `$CONFIG_DIR/{appName}/config.json`
|
|
168
|
+
* (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
|
|
169
|
+
* `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
|
|
170
|
+
*
|
|
171
|
+
* The user can override the path via `--config <path>` or `--config=<path>`.
|
|
172
|
+
*
|
|
173
|
+
* Loaded config feeds into the resolution chain
|
|
174
|
+
* (CLI → env → **config** → prompt → default) for flags that
|
|
175
|
+
* declare `.config('dotted.path')`.
|
|
176
|
+
*
|
|
177
|
+
* Has no effect in `.execute()` (which receives config via
|
|
178
|
+
* `options.config` directly).
|
|
179
|
+
*
|
|
180
|
+
* @param appName - Name used to build search paths.
|
|
181
|
+
* @param loaders - Additional {@link FormatLoader}s (JSON is built-in).
|
|
182
|
+
* @returns The builder (for chaining).
|
|
183
|
+
*/
|
|
184
|
+
config(appName: string, loaders?: readonly FormatLoader[]): CLIBuilder;
|
|
185
|
+
/**
|
|
186
|
+
* Register a custom config format loader.
|
|
187
|
+
*
|
|
188
|
+
* Adds a {@link FormatLoader} incrementally — call multiple times to
|
|
189
|
+
* register multiple formats. Loaders registered later for the same
|
|
190
|
+
* extension override earlier ones.
|
|
191
|
+
*
|
|
192
|
+
* Requires `.config()` to have been called first (sets the app name).
|
|
193
|
+
*
|
|
194
|
+
* @param loader - Format loader (or extensions + parse function).
|
|
195
|
+
* @returns The builder (for chaining).
|
|
196
|
+
*
|
|
197
|
+
* @example Bun built-in parsers
|
|
198
|
+
* ```ts
|
|
199
|
+
* import { configFormat } from '@kjanat/dreamcli';
|
|
200
|
+
*
|
|
201
|
+
* cli('myapp')
|
|
202
|
+
* .config('myapp')
|
|
203
|
+
* .configLoader(configFormat(['yaml', 'yml'], Bun.YAML.parse))
|
|
204
|
+
* .configLoader(configFormat(['toml'], Bun.TOML.parse))
|
|
205
|
+
* .run();
|
|
206
|
+
* ```
|
|
207
|
+
*
|
|
208
|
+
* @example npm package parsers
|
|
209
|
+
* ```ts
|
|
210
|
+
* import { configFormat } from '@kjanat/dreamcli';
|
|
211
|
+
* import { parse as parseYaml } from 'yaml';
|
|
212
|
+
* import { parse as parseTOML } from '@iarna/toml';
|
|
213
|
+
*
|
|
214
|
+
* cli('myapp')
|
|
215
|
+
* .config('myapp')
|
|
216
|
+
* .configLoader(configFormat(['yaml', 'yml'], parseYaml))
|
|
217
|
+
* .configLoader(configFormat(['toml'], parseTOML))
|
|
218
|
+
* .run();
|
|
219
|
+
* ```
|
|
220
|
+
*/
|
|
221
|
+
configLoader(loader: FormatLoader): CLIBuilder;
|
|
222
|
+
/**
|
|
223
|
+
* Enable automatic package.json metadata discovery.
|
|
224
|
+
*
|
|
225
|
+
* When enabled, `.run()` walks up from `cwd` to find the nearest
|
|
226
|
+
* `package.json` and merges its `version` and `description` fields
|
|
227
|
+
* into the CLI schema. Explicit `.version()` and `.description()`
|
|
228
|
+
* calls always take precedence over discovered values.
|
|
229
|
+
*
|
|
230
|
+
* Has no effect in `.execute()` (which is filesystem-free by design).
|
|
231
|
+
*
|
|
232
|
+
* @param settings - Optional settings. Pass `{ inferName: true }` to
|
|
233
|
+
* also infer the CLI name from `bin` keys or the package `name` field.
|
|
234
|
+
*
|
|
235
|
+
* @example
|
|
236
|
+
* ```ts
|
|
237
|
+
* // Auto-fill version + description from nearest package.json:
|
|
238
|
+
* cli('mycli')
|
|
239
|
+
* .packageJson()
|
|
240
|
+
* .command(deploy)
|
|
241
|
+
* .run();
|
|
242
|
+
*
|
|
243
|
+
* // Also infer CLI name from bin key / package name:
|
|
244
|
+
* cli('mycli')
|
|
245
|
+
* .packageJson({ inferName: true })
|
|
246
|
+
* .command(deploy)
|
|
247
|
+
* .run();
|
|
248
|
+
*
|
|
249
|
+
* // Explicit values always win:
|
|
250
|
+
* cli('mycli')
|
|
251
|
+
* .packageJson()
|
|
252
|
+
* .version('2.0.0-beta') // wins over package.json
|
|
253
|
+
* .run();
|
|
254
|
+
* ```
|
|
255
|
+
*/
|
|
256
|
+
packageJson(settings?: {
|
|
257
|
+
readonly inferName?: boolean;
|
|
258
|
+
}): CLIBuilder;
|
|
259
|
+
/**
|
|
260
|
+
* Register a command with the CLI program.
|
|
261
|
+
*
|
|
262
|
+
* The command's type parameters are erased for heterogeneous storage.
|
|
263
|
+
* Type safety is preserved inside the closure that delegates to
|
|
264
|
+
* {@linkcode runCommand | runCommand()}.
|
|
265
|
+
*
|
|
266
|
+
* @param cmd - {@link CommandBuilder} to register.
|
|
267
|
+
* @returns The builder (for chaining).
|
|
268
|
+
*/
|
|
269
|
+
command<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown>>(cmd: CommandBuilder<F, A, C>): CLIBuilder;
|
|
270
|
+
/**
|
|
271
|
+
* Register a command as the default — dispatched when no subcommand is given.
|
|
272
|
+
*
|
|
273
|
+
* The CLI root behaves like a hybrid command group: named subcommands
|
|
274
|
+
* dispatch normally, but empty argv or flags-only argv falls through to
|
|
275
|
+
* this command instead of showing root help.
|
|
276
|
+
*
|
|
277
|
+
* The command is also registered as a normal subcommand (can be invoked
|
|
278
|
+
* by name). Only one default command is allowed.
|
|
279
|
+
*
|
|
280
|
+
* @example
|
|
281
|
+
* ```ts
|
|
282
|
+
* // Single-command CLI — no subcommand name needed:
|
|
283
|
+
* // mytool --force production
|
|
284
|
+
* cli('mytool')
|
|
285
|
+
* .default(deploy)
|
|
286
|
+
* .run();
|
|
287
|
+
*
|
|
288
|
+
* // Multi-command CLI with a default:
|
|
289
|
+
* // mytool production → runs deploy
|
|
290
|
+
* // mytool status → runs status
|
|
291
|
+
* cli('mytool')
|
|
292
|
+
* .default(deploy)
|
|
293
|
+
* .command(status)
|
|
294
|
+
* .run();
|
|
295
|
+
* ```
|
|
296
|
+
*
|
|
297
|
+
* @param cmd - {@link CommandBuilder} to register as the default.
|
|
298
|
+
* @returns The builder (for chaining).
|
|
299
|
+
*/
|
|
300
|
+
default<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown>>(cmd: CommandBuilder<F, A, C>): CLIBuilder;
|
|
301
|
+
/**
|
|
302
|
+
* Register a CLI plugin.
|
|
303
|
+
*
|
|
304
|
+
* Plugins run in registration order. At each lifecycle stage, all hooks for
|
|
305
|
+
* the first plugin run before hooks for the second plugin, and so on.
|
|
306
|
+
*
|
|
307
|
+
* @param definition - A frozen {@link CLIPlugin} created by {@link plugin}.
|
|
308
|
+
* @returns The builder (for chaining).
|
|
309
|
+
* @see {@link plugin} to construct plugin definitions.
|
|
310
|
+
*/
|
|
311
|
+
plugin(definition: CLIPlugin): CLIBuilder;
|
|
312
|
+
/**
|
|
313
|
+
* Register a built-in `completions` subcommand that generates shell
|
|
314
|
+
* completion scripts.
|
|
315
|
+
*
|
|
316
|
+
* The generated command accepts a `--shell` flag (required, enum of
|
|
317
|
+
* all {@link Shell} values) and writes the completion script to stdout
|
|
318
|
+
* via `out.log()`. Unsupported shells throw a descriptive {@linkcode CLIError}
|
|
319
|
+
* instead of a generic parse error.
|
|
320
|
+
*
|
|
321
|
+
* Call this **after** registering all other commands so the completion
|
|
322
|
+
* script includes the full command set. The captured schema is a
|
|
323
|
+
* snapshot at call time — commands registered after `.completions()`
|
|
324
|
+
* will not appear in the generated script. Completion options are also
|
|
325
|
+
* captured at call time.
|
|
326
|
+
*
|
|
327
|
+
* @example
|
|
328
|
+
* ```ts
|
|
329
|
+
* cli('mycli')
|
|
330
|
+
* .version('1.0.0')
|
|
331
|
+
* .command(deploy)
|
|
332
|
+
* .command(login)
|
|
333
|
+
* .completions({ rootMode: 'surface' })
|
|
334
|
+
* .run();
|
|
335
|
+
* ```
|
|
336
|
+
*/
|
|
337
|
+
completions(options?: CompletionOptions): CLIBuilder;
|
|
338
|
+
/**
|
|
339
|
+
* Execute the CLI program against explicit argv.
|
|
340
|
+
*
|
|
341
|
+
* This is the testable execution path — no process state is touched.
|
|
342
|
+
* Returns a structured {@linkcode RunResult} with exit code and captured output.
|
|
343
|
+
*
|
|
344
|
+
* @param argv - Raw argv tokens (NOT including the binary/script path,
|
|
345
|
+
* i.e. equivalent to `process.argv.slice(2)`).
|
|
346
|
+
* @param options - Injectable runtime state.
|
|
347
|
+
* @returns Structured result with exit code and captured output.
|
|
348
|
+
*/
|
|
349
|
+
execute(argv: readonly string[], options?: CLIRunOptions): Promise<RunResult>;
|
|
350
|
+
/**
|
|
351
|
+
* Run the CLI program as a production entry point.
|
|
352
|
+
*
|
|
353
|
+
* Reads argv from the runtime adapter, dispatches to the matched
|
|
354
|
+
* command, writes output to real streams, and exits the process.
|
|
355
|
+
*
|
|
356
|
+
* This is the **only** place that touches process state (via the
|
|
357
|
+
* adapter). For testing, use `.execute()` instead — or provide a
|
|
358
|
+
* test adapter via `options.adapter`.
|
|
359
|
+
*
|
|
360
|
+
* Defaults to {@linkcode createAdapter | createAdapter()} when no adapter is provided,
|
|
361
|
+
* which auto-detects the runtime (Node.js, Bun) and creates
|
|
362
|
+
* the appropriate adapter.
|
|
363
|
+
*
|
|
364
|
+
* @param options - Optional runtime configuration including adapter.
|
|
365
|
+
*/
|
|
366
|
+
run(options?: CLIRunOptions): Promise<never>;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Options for the `cli({...})` factory form.
|
|
370
|
+
*
|
|
371
|
+
* This form is useful when the displayed CLI name should be inferred from the
|
|
372
|
+
* current runtime invocation instead of always being hard-coded.
|
|
373
|
+
*/
|
|
374
|
+
interface CLIOptions {
|
|
375
|
+
/**
|
|
376
|
+
* Explicit fallback CLI name.
|
|
377
|
+
*
|
|
378
|
+
* Used by `.execute()`, and by `.run()` when runtime name inheritance is
|
|
379
|
+
* disabled or the invocation name cannot be inferred.
|
|
380
|
+
*
|
|
381
|
+
* @defaultValue `'cli'`
|
|
382
|
+
*/
|
|
383
|
+
readonly name?: string;
|
|
384
|
+
/**
|
|
385
|
+
* Replace `name` with the invoked program basename during `.run()`.
|
|
386
|
+
*
|
|
387
|
+
* Examples:
|
|
388
|
+
* - `node ./bin/mycli.ts` → `mycli.ts`
|
|
389
|
+
* - `/usr/local/bin/mycli` → `mycli`
|
|
390
|
+
*
|
|
391
|
+
* @defaultValue `false`
|
|
392
|
+
*/
|
|
393
|
+
readonly inherit?: boolean;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Create a new CLI program builder.
|
|
397
|
+
*
|
|
398
|
+
* The CLI name is used in help text, usage lines, and generated completion scripts.
|
|
399
|
+
*
|
|
400
|
+
* @example
|
|
401
|
+
* ```ts
|
|
402
|
+
* cli('mycli')
|
|
403
|
+
* .version('1.0.0')
|
|
404
|
+
* .description('My awesome tool')
|
|
405
|
+
* .command(deploy)
|
|
406
|
+
* .command(login)
|
|
407
|
+
* .run();
|
|
408
|
+
*
|
|
409
|
+
* cli({ inherit: true })
|
|
410
|
+
* .command(deploy)
|
|
411
|
+
* .run();
|
|
412
|
+
* ```
|
|
413
|
+
*/
|
|
414
|
+
declare function cli(name: string): CLIBuilder;
|
|
415
|
+
/** Create a new CLI program builder from an options object. */
|
|
416
|
+
declare function cli(options: CLIOptions): CLIBuilder;
|
|
417
|
+
//#endregion
|
|
418
|
+
export { type BeforeParseParams, CLIBuilder, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type ConfigSettings, type PackageJsonSettings, type PluginCommandContext, type ResolvedCommandParams, cli, formatRootHelp, plugin };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{CLIError as e}from"../errors/index.mjs";import{SHELLS as t,generateCompletion as n}from"../completion/index.mjs";import{formatHelp as r}from"../help/index.mjs";import{buildRunResult as i,executeCommand as a}from"../execution/index.mjs";import{createCaptureOutput as o,createOutput as s}from"../output/index.mjs";import{arg as c}from"../schema/arg.mjs";import{command as l}from"../schema/command.mjs";import{runCommand as u}from"../testkit/index.mjs";import{createAdapter as d}from"../../runtime/auto.mjs";import{planInvocation as f}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as p}from"./root-help.mjs";import{prepareRuntimePreflight as m}from"./runtime-preflight.mjs";function h(e){return[e.name,...e.aliases]}function g(t,n,r,i){let a=n.get(r);if(a!==void 0)throw new e(`Duplicate command route '${r}' under '${t}' (${a} and ${i})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure sibling command names and aliases are unique`});n.set(r,i)}function _(t,n){let r=new Map;for(let e of t)for(let t of h(e.schema))g(`root`,r,t,e.schema.name);for(let t of h(n)){let i=r.get(t);if(i!==void 0)throw new e(`Command route '${t}' is already registered by '${i}'`,{code:`DUPLICATE_COMMAND`,suggest:i===n.name?`Ensure command '${n.name}' does not reuse route '${t}'`:`Rename '${n.name}' or remove route '${t}' from '${i}'`});r.set(t,n.name)}}function v(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=h(r.schema);for(let t of i)g(e.schema.name,n,t,r.schema.name);let a=v(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return u(e,t,n)}}}function y(e,t,n){return{help:t,...n===void 0?{}:{meta:n},...e?.plugins===void 0?{}:{plugins:e.plugins},...e?.env===void 0?{}:{env:e.env},...e?.config===void 0?{}:{config:e.config},...e?.stdinData===void 0?{}:{stdinData:e.stdinData},...e?.prompter===void 0?{}:{prompter:e.prompter},...e?.answers===void 0?{}:{answers:e.answers},...e?.verbosity===void 0?{}:{verbosity:e.verbosity},...e?.jsonMode===void 0?{}:{jsonMode:e.jsonMode},...e?.isTTY===void 0?{}:{isTTY:e.isTTY},...e?.out===void 0?{}:{out:e.out},...e?.captured===void 0?{}:{captured:e.captured}}}var b=class u{schema;constructor(e){this.schema=e}version(e){return new u({...this.schema,version:e})}description(e){return new u({...this.schema,description:e})}config(e,t){return new u({...this.schema,configSettings:{appName:e,loaders:t}})}configLoader(t){if(this.schema.configSettings===void 0)throw new e(`.configLoader() requires .config() to be called first`,{code:`INVALID_BUILDER_STATE`,suggest:`Call .config(appName) before .configLoader()`});let n=this.schema.configSettings.loaders??[];return new u({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...n,t]}})}packageJson(e){return new u({...this.schema,packageJsonSettings:{inferName:e?.inferName??!1}})}command(e){return _(this.schema.commands,e.schema),new u({...this.schema,commands:[...this.schema.commands,v(e)]})}default(t){if(this.schema.defaultCommand!==void 0)throw new e(`Only one default command is allowed`,{code:`DUPLICATE_DEFAULT`,suggest:`Call .default() only once when building the CLI`});_(this.schema.commands,t.schema);let n=v(t);return new u({...this.schema,commands:[...this.schema.commands,n],defaultCommand:n})}plugin(e){return new u({...this.schema,plugins:[...this.schema.plugins,e]})}completions(r){if(this.schema.hasBuiltInCompletions)throw new e(`.completions() has already been called`,{code:`DUPLICATE_COMMAND`,suggest:`Call .completions() only once when building the CLI`});let i=this.schema,a=r,o=new Map;for(let e of t)o.set(e,e);o.set(`pwsh`,`powershell`);let s=l(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,c.custom(e=>{let n=e.split(/[\\/]/),r=(n[n.length-1]??e).replace(/\.(?:exe|cmd|bat)$/i,``),i=o.get(r);if(i===void 0)throw Error(`Unknown shell '${r}'. Valid shells: ${t.join(`, `)}`);return i}).env(`SHELL`).describe(`Target shell (${t.join(`, `)})`)).action(({args:e,meta:t,out:r})=>{let o=n(t.bin===i.name?i:{...i,name:t.bin},e.shell,a);r.jsonMode?r.json({shell:e.shell,script:o}):r.log(o)});return new u({...this.command(s).schema,hasBuiltInCompletions:!0})}async execute(e,t){let n=e.includes(`--json`)||t?.jsonMode===!0,s={...t?.verbosity===void 0?{}:{verbosity:t.verbosity},...n?{jsonMode:n}:{},...t?.isTTY===void 0?{}:{isTTY:t.isTTY}},c,l;t?.out===void 0?[c,l]=o(Object.keys(s).length>0?s:void 0):(c=t.out,l=t.captured??{stdout:[],stderr:[],activity:[]});let u={...t?.help,binName:t?.help?.binName??this.schema.name},d={...t,plugins:this.schema.plugins,...n?{jsonMode:n}:{}},m={jsonMode:n,isTTY:c.isTTY,verbosity:t?.verbosity??`normal`},h=f({schema:this.schema,argv:e,help:u,output:m});switch(h.kind){case`root-version`:return c.log(h.version),i({exitCode:0,error:void 0},l);case`root-help`:{let e=p(this.schema,h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`dispatch-error`:return n?c.json({error:h.error.toJSON()}):(c.error(h.error.message),h.error.suggest!==void 0&&h.error.code!==`NO_ACTION`&&c.error(`Suggestion: ${h.error.suggest}`)),i({exitCode:h.error.exitCode,error:h.error},l);case`needs-subcommand`:{let e=r(h.command.schema,h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`match`:{let e=y(d,h.plan.help??u,h.plan.meta);return h.plan.command._command===void 0?h.plan.command._execute(h.plan.argv,{...e,mergedSchema:h.plan.mergedSchema}):i(await a({command:h.plan.command._command,argv:h.plan.argv,out:c,schema:h.plan.mergedSchema,meta:h.plan.meta,options:e}),l)}}}async run(e){let t=e?.adapter??d(),n=this.schema.inheritName?w(t.argv):void 0,r=await m({schema:this.schema,adapter:t,options:e,inheritedName:n});if(r.kind===`config-error`)return r.jsonMode?t.stdout(`${JSON.stringify({error:r.error.toJSON()})}\n`):(t.stderr(`Error: ${r.error.message}\n`),r.error.suggest!==void 0&&t.stderr(`Suggestion: ${r.error.suggest}\n`)),t.exit(r.error.exitCode);let i=r.schema===this.schema?this:new u(r.schema),a={...e,...r.inputs,out:s({stdout:t.stdout,stderr:t.stderr,jsonMode:r.inputs.jsonMode,isTTY:r.inputs.isTTY,...r.inputs.verbosity===`normal`?{}:{verbosity:r.inputs.verbosity}})},o=await i.execute(r.filteredArgv,a);for(let e of o.stdout)t.stdout(e);for(let e of o.stderr)t.stderr(e);return t.exit(o.exitCode)}};const x=new Set([`bun`,`deno`,`node`,`tsx`]);function S(e){let t=e.replace(/[\\/]+$/g,``);if(t.length===0)return;let n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`)),r=n>=0?t.slice(n+1):t;return r.length>0?r:void 0}function C(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return x.has(t)}function w(e){let t=e[0],n=e[1],r=t===void 0?void 0:S(t);if(r!==void 0&&C(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:S(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:S(n)}return t===void 0?void 0:S(t)}function T(e){return new b({name:typeof e==`string`?e:e.name??`cli`,inheritName:typeof e==`string`?!1:e.inherit??!1,version:void 0,description:void 0,commands:[],defaultCommand:void 0,configSettings:void 0,packageJsonSettings:void 0,hasBuiltInCompletions:!1,plugins:[]})}export{b as CLIBuilder,T as cli};
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { OutputPolicy } from "../output/contracts.mjs";
|
|
2
|
+
import { CLIPlugin } from "./plugin.mjs";
|
|
3
|
+
import { CLIError } from "../errors/index.mjs";
|
|
4
|
+
import { HelpOptions } from "../help/index.mjs";
|
|
5
|
+
import { CommandMeta, CommandSchema, ErasedCommand } from "../schema/command.mjs";
|
|
6
|
+
|
|
7
|
+
//#region src/core/cli/planner.d.ts
|
|
8
|
+
/**
|
|
9
|
+
* Structural subset of CLISchema used by the planner.
|
|
10
|
+
*
|
|
11
|
+
* Decouples invocation planning from the full CLIBuilder surface so the
|
|
12
|
+
* planner can be tested and reasoned about without constructing a real CLI.
|
|
13
|
+
* @internal
|
|
14
|
+
*/
|
|
15
|
+
interface PlannerSchemaLike {
|
|
16
|
+
/** CLI program name used in help text and error messages. */
|
|
17
|
+
readonly name: string;
|
|
18
|
+
/** Declared version string; `undefined` disables `--version` interception. */
|
|
19
|
+
readonly version: string | undefined;
|
|
20
|
+
/** Registered top-level commands available for dispatch. */
|
|
21
|
+
readonly commands: readonly ErasedCommand[];
|
|
22
|
+
/** Fallback command when no subcommand token matches. */
|
|
23
|
+
readonly defaultCommand: ErasedCommand | undefined;
|
|
24
|
+
/** Plugins forwarded into every matched execution plan. */
|
|
25
|
+
readonly plugins: readonly CLIPlugin[];
|
|
26
|
+
}
|
|
27
|
+
/** Root-level help interception outcome. */
|
|
28
|
+
interface RootHelpOutcome {
|
|
29
|
+
/** Discriminant — argv matched `--help` / `-h` before any command. */
|
|
30
|
+
readonly kind: 'root-help';
|
|
31
|
+
/** Help options to render root-level usage. */
|
|
32
|
+
readonly help: HelpOptions;
|
|
33
|
+
}
|
|
34
|
+
/** Root-level version interception outcome. */
|
|
35
|
+
interface RootVersionOutcome {
|
|
36
|
+
/** Discriminant — argv matched `--version` / `-V` and schema declares a version. */
|
|
37
|
+
readonly kind: 'root-version';
|
|
38
|
+
/** Resolved version string to render. */
|
|
39
|
+
readonly version: string;
|
|
40
|
+
}
|
|
41
|
+
/** CLI-level dispatch failure before command execution starts. */
|
|
42
|
+
interface DispatchErrorOutcome {
|
|
43
|
+
/** Discriminant — dispatch could not resolve a command from argv. */
|
|
44
|
+
readonly kind: 'dispatch-error';
|
|
45
|
+
/** Structured error with suggestion text for the caller to render. */
|
|
46
|
+
readonly error: CLIError;
|
|
47
|
+
}
|
|
48
|
+
/** Successful planner handoff to the shared command execution path. */
|
|
49
|
+
interface PlannerMatchOutcome {
|
|
50
|
+
/** Discriminant — dispatch found a matching command for argv. */
|
|
51
|
+
readonly kind: 'match';
|
|
52
|
+
/** Fully resolved execution plan ready for the executor pipeline. */
|
|
53
|
+
readonly plan: CommandExecutionPlan;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Stable planner result union for the re-foundation workstream.
|
|
57
|
+
*
|
|
58
|
+
* `CLIBuilder.execute()` still renders and executes these outcomes, but
|
|
59
|
+
* planning itself is intentionally bounded to this union.
|
|
60
|
+
*/
|
|
61
|
+
type DispatchOutcome = RootHelpOutcome | RootVersionOutcome | DispatchErrorOutcome | PlannerMatchOutcome;
|
|
62
|
+
/**
|
|
63
|
+
* Concrete execution handoff produced by a successful planner match.
|
|
64
|
+
*
|
|
65
|
+
* `mergedSchema` is the exact command schema the executor sees after
|
|
66
|
+
* propagated ancestor flags are collected and child definitions shadow them.
|
|
67
|
+
*/
|
|
68
|
+
interface CommandExecutionPlan {
|
|
69
|
+
/** Type-erased command instance that owns the handler. */
|
|
70
|
+
readonly command: ErasedCommand;
|
|
71
|
+
/** Command schema with propagated ancestor flags merged in. */
|
|
72
|
+
readonly mergedSchema: CommandSchema;
|
|
73
|
+
/** Remaining argv tokens after command dispatch consumed the command path. */
|
|
74
|
+
readonly argv: readonly string[];
|
|
75
|
+
/** CLI-level metadata (program name, bin, version) for the handler context. */
|
|
76
|
+
readonly meta: CommandMeta;
|
|
77
|
+
/** Plugins to run through the execution lifecycle. */
|
|
78
|
+
readonly plugins: readonly CLIPlugin[];
|
|
79
|
+
/** Output policy (json mode, TTY, verbosity) governing handler rendering. */
|
|
80
|
+
readonly output: OutputPolicy;
|
|
81
|
+
/** Help options for rendering per-command help; `undefined` when unavailable. */
|
|
82
|
+
readonly help: HelpOptions | undefined;
|
|
83
|
+
}
|
|
84
|
+
interface BuildCommandExecutionPlanOptions {
|
|
85
|
+
readonly command: ErasedCommand;
|
|
86
|
+
readonly commandPath: readonly CommandSchema[];
|
|
87
|
+
readonly argv: readonly string[];
|
|
88
|
+
readonly meta: CommandMeta;
|
|
89
|
+
readonly plugins: readonly CLIPlugin[];
|
|
90
|
+
readonly output: OutputPolicy;
|
|
91
|
+
readonly help: HelpOptions | undefined;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Dispatch resolved a group command that requires a subcommand selection.
|
|
95
|
+
*
|
|
96
|
+
* The caller should render subcommand-level help for the matched group.
|
|
97
|
+
* @internal
|
|
98
|
+
*/
|
|
99
|
+
interface NeedsSubcommandOutcome {
|
|
100
|
+
/** Discriminant — group command matched but no leaf subcommand was selected. */
|
|
101
|
+
readonly kind: 'needs-subcommand';
|
|
102
|
+
/** The group command that was matched. */
|
|
103
|
+
readonly command: ErasedCommand;
|
|
104
|
+
/** Full ancestor path from root to this group, used for propagated flag collection. */
|
|
105
|
+
readonly commandPath: readonly CommandSchema[];
|
|
106
|
+
/** Help options scoped to the group command's bin path. */
|
|
107
|
+
readonly help: HelpOptions;
|
|
108
|
+
}
|
|
109
|
+
/** Full planner result including the `needs-subcommand` variant used by CLIBuilder. @internal */
|
|
110
|
+
type InvocationPlan = DispatchOutcome | NeedsSubcommandOutcome;
|
|
111
|
+
/** Options bag for {@linkcode planInvocation}. @internal */
|
|
112
|
+
interface PlanInvocationOptions {
|
|
113
|
+
/** CLI schema subset driving dispatch decisions. */
|
|
114
|
+
readonly schema: PlannerSchemaLike;
|
|
115
|
+
/** Raw argv tokens (typically `adapter.argv.slice(2)`). */
|
|
116
|
+
readonly argv: readonly string[];
|
|
117
|
+
/** Root-level help configuration for rendering. */
|
|
118
|
+
readonly help: HelpOptions;
|
|
119
|
+
/** Output policy propagated into matched execution plans. */
|
|
120
|
+
readonly output: OutputPolicy;
|
|
121
|
+
}
|
|
122
|
+
/** Build a name+alias lookup map for top-level commands. @internal */
|
|
123
|
+
declare function buildRootCommandMap(commands: readonly ErasedCommand[]): ReadonlyMap<string, ErasedCommand>;
|
|
124
|
+
/**
|
|
125
|
+
* Merge propagated ancestor flags into the matched command schema.
|
|
126
|
+
*
|
|
127
|
+
* Child flag definitions win when names collide, matching current CLI
|
|
128
|
+
* dispatch semantics and the future planner contract.
|
|
129
|
+
*/
|
|
130
|
+
declare function mergeCommandSchema(command: ErasedCommand, commandPath: readonly CommandSchema[]): CommandSchema;
|
|
131
|
+
/** Build the planner handoff for a matched command invocation. */
|
|
132
|
+
declare function buildCommandExecutionPlan(options: BuildCommandExecutionPlanOptions): CommandExecutionPlan;
|
|
133
|
+
/**
|
|
134
|
+
* Decide what to do with an argv invocation before any command executes.
|
|
135
|
+
*
|
|
136
|
+
* Handles root interception (`--help`, `--version`, bare `help` token),
|
|
137
|
+
* dispatches into the command tree, falls back to the default command, and
|
|
138
|
+
* produces structured errors for unknown commands/flags.
|
|
139
|
+
* @internal
|
|
140
|
+
*/
|
|
141
|
+
declare function planInvocation(options: PlanInvocationOptions): InvocationPlan;
|
|
142
|
+
//#endregion
|
|
143
|
+
export { type CommandExecutionPlan, type DispatchErrorOutcome, type DispatchOutcome, type InvocationPlan, type NeedsSubcommandOutcome, type OutputPolicy, type PlanInvocationOptions, type PlannerMatchOutcome, type PlannerSchemaLike, type RootHelpOutcome, type RootVersionOutcome, buildCommandExecutionPlan, buildRootCommandMap, mergeCommandSchema, planInvocation };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{collectPropagatedFlags as e}from"./propagate.mjs";import{CLIError as t,ParseError as n}from"../errors/index.mjs";import{dispatch as r,findClosestCommand as i}from"./dispatch.mjs";function a(e,t,n){return{name:e.name,bin:t.binName??e.name,version:e.version,command:n}}function o(e){let n=new Map,r=(e,r)=>{let i=n.get(e);if(i!==void 0)throw new t(`Duplicate root command route '${e}' (${i.schema.name} and ${r.schema.name})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure root command names and aliases are unique`});n.set(e,r)};for(let t of e){r(t.schema.name,t);for(let e of t.schema.aliases)r(e,t)}return n}function s(t,n){let r=e(n);return Object.keys(r).length===0?t.schema:{...t.schema,flags:{...r,...t.schema.flags}}}function c(e){return{command:e.command,mergedSchema:s(e.command,e.commandPath),argv:e.argv,meta:e.meta,plugins:e.plugins,output:e.output,help:e.help}}function l(e,t,n,r,i,o){return{kind:`match`,plan:c({command:t,commandPath:n,argv:r,meta:a(e,i,t.schema.name),plugins:e.plugins,output:o,help:i})}}function u(e){let a=e.argv.includes(`--json`)?e.argv.filter(e=>e!==`--json`):e.argv;if(e.schema.version!==void 0&&(a.includes(`--version`)||a.includes(`-V`)))return{kind:`root-version`,version:e.schema.version};let s=a[0];if(s===`--help`||s===`-h`)return{kind:`root-help`,help:e.help};if(s===`help`&&!e.schema.commands.some(e=>e.schema.name===`help`||e.schema.aliases.includes(`help`))){let t=a.slice(1);return t.length===0?{kind:`root-help`,help:e.help}:u({...e,argv:[...t,`--help`]})}if(s===void 0&&e.schema.defaultCommand===void 0)return{kind:`root-help`,help:e.help};if(e.schema.commands.length===0)return{kind:`dispatch-error`,error:new t(`No commands registered`,{code:`NO_ACTION`,suggest:`Add commands via .command() before calling .run()`})};let c=r(a,o(e.schema.commands)),d=e.schema.defaultCommand;switch(c.kind){case`unknown`:{if(d!==void 0&&c.parentPath.length===0&&(c.input===``?void 0:i(c.input,c.candidates))===void 0)return l(e.schema,d,[d.schema],a,e.help,e.output);if(c.input===``){let t=a.find(e=>e.startsWith(`-`));return t===void 0?{kind:`root-help`,help:e.help}:{kind:`dispatch-error`,error:new n(`Unknown flag ${t}`,{code:`UNKNOWN_FLAG`,suggest:`Run '${e.schema.name} --help' for available commands`})}}let t=i(c.input,c.candidates),r=c.parentPath.length>0?`${e.schema.name} ${c.parentPath.map(e=>e.name).join(` `)}`:e.schema.name;return{kind:`dispatch-error`,error:new n(`Unknown command: ${c.input}`,{code:`UNKNOWN_COMMAND`,suggest:t===void 0?`Run '${r} --help' for available commands`:`Did you mean '${t}'?`})}}case`needs-subcommand`:{let t=c.commandPath.slice(0,-1).map(e=>e.name);return{kind:`needs-subcommand`,command:c.command,commandPath:c.commandPath,help:{...e.help,binName:[e.schema.name,...t].join(` `)}}}case`match`:return l(e.schema,c.command,c.commandPath,c.remainingArgv,e.help,e.output)}}export{u as planInvocation};
|