@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -1
- package/dist/core/cli/dispatch.mjs +214 -1
- package/dist/core/cli/help-links.mjs +41 -1
- package/dist/core/cli/index.mjs +901 -1
- package/dist/core/cli/planner.mjs +300 -1
- package/dist/core/cli/plugin.mjs +41 -1
- package/dist/core/cli/propagate.mjs +57 -1
- package/dist/core/cli/root-help.mjs +208 -4
- package/dist/core/cli/root-surface.mjs +27 -1
- package/dist/core/cli/runtime-preflight.mjs +168 -1
- package/dist/core/completion/index.mjs +90 -1
- package/dist/core/completion/shells/bash.mjs +304 -3
- package/dist/core/completion/shells/fish.mjs +159 -2
- package/dist/core/completion/shells/powershell.mjs +353 -2
- package/dist/core/completion/shells/shared.mjs +154 -1
- package/dist/core/completion/shells/zsh.mjs +244 -2
- package/dist/core/config/index.mjs +246 -1
- package/dist/core/config/package-json.mjs +385 -3
- package/dist/core/errors/index.mjs +87 -1
- package/dist/core/execution/index.mjs +189 -1
- package/dist/core/help/ansi.mjs +122 -2
- package/dist/core/help/index.mjs +329 -7
- package/dist/core/json-schema/index.mjs +487 -9
- package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
- package/dist/core/output/activity.mjs +452 -1
- package/dist/core/output/bind.mjs +56 -1
- 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 -0
- package/dist/core/output/index.mjs +442 -2
- package/dist/core/output/renderers.mjs +46 -1
- package/dist/core/output/writer.mjs +12 -1
- package/dist/core/parse/index.mjs +555 -1
- package/dist/core/prompt/index.d.mts +0 -1
- package/dist/core/prompt/index.mjs +348 -6
- package/dist/core/resolve/args.mjs +105 -1
- package/dist/core/resolve/coerce.mjs +279 -1
- package/dist/core/resolve/config.mjs +19 -1
- package/dist/core/resolve/errors.mjs +140 -2
- package/dist/core/resolve/flags.mjs +196 -1
- package/dist/core/resolve/index.mjs +85 -1
- package/dist/core/resolve/property.d.mts +0 -1
- package/dist/core/resolve/property.mjs +45 -1
- package/dist/core/schema/arg.mjs +463 -1
- package/dist/core/schema/command.d.mts +18 -0
- package/dist/core/schema/command.mjs +712 -1
- package/dist/core/schema/flag.mjs +453 -1
- package/dist/core/schema/middleware.mjs +41 -1
- package/dist/core/schema/number-constraints.mjs +60 -1
- package/dist/core/schema-dsl/runtime.mjs +271 -2
- package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
- package/dist/core/testkit/index.mjs +83 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +22 -1
- package/dist/runtime/adapter.mjs +82 -1
- package/dist/runtime/auto.mjs +46 -1
- package/dist/runtime/bun.mjs +28 -1
- package/dist/runtime/deno.mjs +217 -2
- package/dist/runtime/detect.mjs +45 -1
- package/dist/runtime/node.mjs +169 -2
- package/dist/runtime/paths.mjs +48 -1
- package/dist/runtime.mjs +7 -1
- package/dist/strings.mjs +22 -1
- package/dist/testkit.mjs +5 -1
- package/dist/version.mjs +7 -1
- package/package.json +17 -26
- 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
|
@@ -1 +1,154 @@
|
|
|
1
|
-
import{collectPropagatedFlags
|
|
1
|
+
import { collectPropagatedFlags } from "../../cli/propagate.mjs";
|
|
2
|
+
import { resolveRootSurface } from "../../cli/root-surface.mjs";
|
|
3
|
+
import { DREAMCLI_REVISION, DREAMCLI_VERSION } from "../../../version.mjs";
|
|
4
|
+
//#region src/core/completion/shells/shared.ts
|
|
5
|
+
/**
|
|
6
|
+
* Shared infrastructure for shell completion generators.
|
|
7
|
+
*
|
|
8
|
+
* Provides the command tree walker, shell escaping utilities, and
|
|
9
|
+
* the version tag used in generated script headers. Consumed by
|
|
10
|
+
* the per-shell generators in sibling files.
|
|
11
|
+
*
|
|
12
|
+
* @module dreamcli/core/completion/shells/shared
|
|
13
|
+
* @internal
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Format a version tag for generated completion script headers.
|
|
17
|
+
*
|
|
18
|
+
* Produces e.g. `"@kjanat/dreamcli v0.9.1 (f9b5f1a)"` when built, or
|
|
19
|
+
* `"@kjanat/dreamcli"` when running unbundled in development.
|
|
20
|
+
*
|
|
21
|
+
* @internal
|
|
22
|
+
*/
|
|
23
|
+
function versionTag() {
|
|
24
|
+
return `@kjanat/dreamcli v${DREAMCLI_VERSION}${` (${DREAMCLI_REVISION})`}`;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Resolve the root-level completion surface from the CLI schema and policy.
|
|
28
|
+
*
|
|
29
|
+
* @internal
|
|
30
|
+
*/
|
|
31
|
+
function resolveRootCompletionSurface(schema, rootMode = "subcommands") {
|
|
32
|
+
const rootSurface = resolveRootSurface(schema);
|
|
33
|
+
const rootFlags = createRootFlags(schema.version !== void 0);
|
|
34
|
+
const defaultFlags = rootSurface.visibleDefaultCommand?.flags ?? {};
|
|
35
|
+
const includeDefaultFlags = rootMode === "surface" ? rootSurface.hasVisibleDefault : rootSurface.hasVisibleDefault && !rootSurface.hasVisibleSubcommands;
|
|
36
|
+
const defaultCommand = rootSurface.visibleDefaultCommand;
|
|
37
|
+
const alreadyListed = defaultCommand !== void 0 && rootSurface.visibleCommands.some((c) => c.name === defaultCommand.name);
|
|
38
|
+
return {
|
|
39
|
+
visibleCommands: defaultCommand !== void 0 && !alreadyListed ? [defaultCommand, ...rootSurface.visibleCommands] : rootSurface.visibleCommands,
|
|
40
|
+
visibleDefaultCommand: rootSurface.visibleDefaultCommand,
|
|
41
|
+
rootFlags,
|
|
42
|
+
defaultFlags,
|
|
43
|
+
includeDefaultFlags
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Build the synthetic root-level flags (`--help`, optionally `--version`).
|
|
48
|
+
*
|
|
49
|
+
* @param hasVersion - Whether to include a `--version` flag.
|
|
50
|
+
* @returns A record of root flag schemas.
|
|
51
|
+
* @internal
|
|
52
|
+
*/
|
|
53
|
+
function createRootFlags(hasVersion) {
|
|
54
|
+
return {
|
|
55
|
+
help: createSyntheticRootFlag("Show help text"),
|
|
56
|
+
...hasVersion ? { version: createSyntheticRootFlag("Show version") } : {}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Create a minimal boolean {@link FlagSchema} for a synthetic root flag.
|
|
61
|
+
*
|
|
62
|
+
* @param description - Help text for the flag.
|
|
63
|
+
* @returns A complete flag schema with all optional fields defaulted.
|
|
64
|
+
* @internal
|
|
65
|
+
*/
|
|
66
|
+
function createSyntheticRootFlag(description) {
|
|
67
|
+
return {
|
|
68
|
+
kind: "boolean",
|
|
69
|
+
presence: "optional",
|
|
70
|
+
defaultValue: void 0,
|
|
71
|
+
aliases: [],
|
|
72
|
+
envVar: void 0,
|
|
73
|
+
configPath: void 0,
|
|
74
|
+
description,
|
|
75
|
+
enumValues: void 0,
|
|
76
|
+
numberConstraints: void 0,
|
|
77
|
+
elementSchema: void 0,
|
|
78
|
+
prompt: void 0,
|
|
79
|
+
parseFn: void 0,
|
|
80
|
+
deprecated: void 0,
|
|
81
|
+
propagate: false
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Walk the command tree depth-first, producing a flat list of
|
|
86
|
+
* {@link CommandNode}s with propagated flag context.
|
|
87
|
+
*
|
|
88
|
+
* @param topLevel - Top-level visible command schemas.
|
|
89
|
+
* @param ancestorSchemas - Schema path from root (for propagation calculation).
|
|
90
|
+
* @returns Flat list of all visible nodes in the tree.
|
|
91
|
+
*
|
|
92
|
+
* @internal
|
|
93
|
+
*/
|
|
94
|
+
function walkCommandTree(topLevel, ancestorSchemas = []) {
|
|
95
|
+
const nodes = [];
|
|
96
|
+
for (const schema of topLevel) {
|
|
97
|
+
if (schema.hidden) continue;
|
|
98
|
+
const fullPath = [...ancestorSchemas, schema];
|
|
99
|
+
const propagatedFlags = collectPropagatedFlags(fullPath);
|
|
100
|
+
const mergedFlags = {
|
|
101
|
+
...propagatedFlags,
|
|
102
|
+
...schema.flags
|
|
103
|
+
};
|
|
104
|
+
const children = schema.commands.filter((c) => !c.hidden);
|
|
105
|
+
nodes.push({
|
|
106
|
+
path: fullPath.map((s) => s.name),
|
|
107
|
+
schema,
|
|
108
|
+
propagatedFlags,
|
|
109
|
+
mergedFlags,
|
|
110
|
+
children
|
|
111
|
+
});
|
|
112
|
+
if (children.length > 0) nodes.push(...walkCommandTree(children, fullPath));
|
|
113
|
+
}
|
|
114
|
+
return nodes;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Sanitize a string for use as a shell function identifier.
|
|
118
|
+
* Replaces non-alphanumeric/underscore characters with underscores.
|
|
119
|
+
* When sanitization changes the name, appends a short stable hash suffix so
|
|
120
|
+
* distinct originals cannot collide on the same helper identifier.
|
|
121
|
+
* Used by both bash and zsh generators.
|
|
122
|
+
*
|
|
123
|
+
* @internal
|
|
124
|
+
*/
|
|
125
|
+
function sanitizeShellIdentifier(name) {
|
|
126
|
+
const sanitized = name.replace(/[^a-zA-Z0-9_]/g, "_");
|
|
127
|
+
if (sanitized === name) return sanitized;
|
|
128
|
+
let hash = 2166136261;
|
|
129
|
+
for (let i = 0; i < name.length; i += 1) {
|
|
130
|
+
hash ^= name.charCodeAt(i);
|
|
131
|
+
hash = Math.imul(hash, 16777619);
|
|
132
|
+
}
|
|
133
|
+
return `${sanitized}_${(hash >>> 0).toString(16).padStart(8, "0")}`;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Quote a string for safe interpolation into a shell script.
|
|
137
|
+
*
|
|
138
|
+
* Uses single-quote wrapping with the standard `'\''` idiom for
|
|
139
|
+
* embedded single quotes. This prevents shell injection from CLI
|
|
140
|
+
* names containing spaces, semicolons, backticks, or other
|
|
141
|
+
* special characters.
|
|
142
|
+
*
|
|
143
|
+
* Returns the input unquoted if it consists only of shell-safe
|
|
144
|
+
* characters (`[a-zA-Z0-9_\-.]`), avoiding unnecessary noise
|
|
145
|
+
* in generated scripts for common CLI names like `my-cli` or `app.v2`.
|
|
146
|
+
*
|
|
147
|
+
* @internal
|
|
148
|
+
*/
|
|
149
|
+
function quoteShellArg(value) {
|
|
150
|
+
if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
|
|
151
|
+
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
152
|
+
}
|
|
153
|
+
//#endregion
|
|
154
|
+
export { quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree };
|
|
@@ -1,2 +1,244 @@
|
|
|
1
|
-
import{getFlagAliasNames
|
|
2
|
-
|
|
1
|
+
import { getFlagAliasNames } from "../../schema/flag.mjs";
|
|
2
|
+
import { quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree } from "./shared.mjs";
|
|
3
|
+
import { CLIError } from "../../errors/index.mjs";
|
|
4
|
+
//#region src/core/completion/shells/zsh.ts
|
|
5
|
+
/**
|
|
6
|
+
* Generate a zsh completion script for the CLI.
|
|
7
|
+
*
|
|
8
|
+
* Use this when you want a zsh-specific script directly rather than routing
|
|
9
|
+
* through {@link generateCompletion}. The generated script is compatible with
|
|
10
|
+
* zsh's normal `#compdef` / `fpath` loading flow.
|
|
11
|
+
*
|
|
12
|
+
* @param schema - The CLI schema.
|
|
13
|
+
* @param options - Optional generator configuration.
|
|
14
|
+
* @returns A complete zsh completion script.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* const script = generateZshCompletion(app.schema);
|
|
19
|
+
* // install with: mycli completions zsh > "${fpath[1]}/_mycli"
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
function generateZshCompletion(schema, options) {
|
|
23
|
+
const funcName = `_${sanitizeShellIdentifier(options?.functionPrefix ?? schema.name)}`;
|
|
24
|
+
const rootSurface = resolveRootCompletionSurface(schema, options?.rootMode);
|
|
25
|
+
const visibleCommands = rootSurface.visibleCommands;
|
|
26
|
+
const nodes = walkCommandTree(visibleCommands);
|
|
27
|
+
const lines = [];
|
|
28
|
+
lines.push(`#compdef ${quoteShellArg(schema.name)}`);
|
|
29
|
+
lines.push(`# Zsh completion for ${schema.name}`);
|
|
30
|
+
lines.push(`# Generated by ${versionTag()}`);
|
|
31
|
+
lines.push("#");
|
|
32
|
+
lines.push(`# Usage: source <(${schema.name} completions zsh)`);
|
|
33
|
+
lines.push("#");
|
|
34
|
+
lines.push("# Install permanently:");
|
|
35
|
+
lines.push(`# ${schema.name} completions zsh > "\${fpath[1]}/_${schema.name}"`);
|
|
36
|
+
lines.push("# # Then restart your shell");
|
|
37
|
+
lines.push("");
|
|
38
|
+
const groupNodes = nodes.filter((n) => n.children.length > 0);
|
|
39
|
+
const leafNodes = nodes.filter((n) => n.children.length === 0);
|
|
40
|
+
for (const node of leafNodes) {
|
|
41
|
+
if (node.path.length < 2) continue;
|
|
42
|
+
emitZshLeafFunction(lines, `${funcName}_${node.path.map(sanitizeShellIdentifier).join("_")}`, node);
|
|
43
|
+
}
|
|
44
|
+
const sortedGroups = [...groupNodes].sort((a, b) => b.path.length - a.path.length);
|
|
45
|
+
for (const node of sortedGroups) emitZshGroupFunction(lines, `${funcName}_${node.path.map(sanitizeShellIdentifier).join("_")}`, funcName, node);
|
|
46
|
+
lines.push(`${funcName}() {`);
|
|
47
|
+
if (visibleCommands.length > 0) {
|
|
48
|
+
lines.push(" local -a subcmds");
|
|
49
|
+
lines.push(" local line state");
|
|
50
|
+
lines.push("");
|
|
51
|
+
const rootFlagSpecs = buildZshFlagSpecsFromFlags({
|
|
52
|
+
...rootSurface.rootFlags,
|
|
53
|
+
...rootSurface.includeDefaultFlags ? rootSurface.defaultFlags : {}
|
|
54
|
+
});
|
|
55
|
+
lines.push(" _arguments -C \\");
|
|
56
|
+
for (const spec of rootFlagSpecs) lines.push(`\t\t${spec} \\`);
|
|
57
|
+
lines.push(" '1: :->subcmd' \\");
|
|
58
|
+
lines.push(" '*::arg:->args'");
|
|
59
|
+
lines.push("");
|
|
60
|
+
lines.push(" case \"$state\" in");
|
|
61
|
+
lines.push(" subcmd)");
|
|
62
|
+
lines.push(" subcmds=(");
|
|
63
|
+
appendZshCommandCandidates(lines, visibleCommands, " ");
|
|
64
|
+
lines.push(" )");
|
|
65
|
+
lines.push(" _describe 'command' subcmds");
|
|
66
|
+
lines.push(" ;;");
|
|
67
|
+
lines.push(" args)");
|
|
68
|
+
lines.push(" case \"$line[1]\" in");
|
|
69
|
+
for (const cmd of visibleCommands) {
|
|
70
|
+
const allNames = [cmd.name, ...cmd.aliases].map(escapeZshCasePatternValue);
|
|
71
|
+
const childCommands = cmd.commands.filter((c) => !c.hidden);
|
|
72
|
+
lines.push(`\t\t\t\t${allNames.join("|")})`);
|
|
73
|
+
if (childCommands.length > 0) {
|
|
74
|
+
const helperName = `${funcName}_${sanitizeShellIdentifier(cmd.name)}`;
|
|
75
|
+
lines.push(`\t\t\t\t\t${helperName}`);
|
|
76
|
+
} else {
|
|
77
|
+
const node = nodes.find((n) => n.path.length === 1 && n.schema.name === cmd.name);
|
|
78
|
+
if (node === void 0) throw new CLIError(`Missing completion node for command '${cmd.name}'`, { code: "UNEXPECTED_ERROR" });
|
|
79
|
+
const flagSpecs = buildZshFlagSpecsFromFlags(node.mergedFlags);
|
|
80
|
+
if (flagSpecs.length > 0) {
|
|
81
|
+
lines.push(" _arguments \\");
|
|
82
|
+
for (let i = 0; i < flagSpecs.length; i++) {
|
|
83
|
+
const trailing = i < flagSpecs.length - 1 ? " \\" : "";
|
|
84
|
+
lines.push(`\t\t\t\t\t\t${flagSpecs[i]}${trailing}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
lines.push(" ;;");
|
|
89
|
+
}
|
|
90
|
+
lines.push(" esac");
|
|
91
|
+
lines.push(" ;;");
|
|
92
|
+
lines.push(" esac");
|
|
93
|
+
} else {
|
|
94
|
+
const globalFlags = buildZshFlagSpecsFromFlags(rootSurface.rootFlags);
|
|
95
|
+
lines.push(" _arguments \\");
|
|
96
|
+
for (let i = 0; i < globalFlags.length; i++) {
|
|
97
|
+
const trailing = i < globalFlags.length - 1 ? " \\" : "";
|
|
98
|
+
lines.push(`\t\t${globalFlags[i]}${trailing}`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
lines.push("}");
|
|
102
|
+
lines.push("");
|
|
103
|
+
lines.push(`compdef ${funcName} ${quoteShellArg(schema.name)}`);
|
|
104
|
+
lines.push("");
|
|
105
|
+
return lines.join("\n");
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Emit a zsh helper function for a group command (has subcommands).
|
|
109
|
+
*
|
|
110
|
+
* Uses `_arguments -C` for its own flags plus subcommand dispatch.
|
|
111
|
+
*
|
|
112
|
+
* @internal
|
|
113
|
+
*/
|
|
114
|
+
function emitZshGroupFunction(lines, helperName, rootFuncName, node) {
|
|
115
|
+
lines.push(`${helperName}() {`);
|
|
116
|
+
lines.push(" local -a subcmds");
|
|
117
|
+
lines.push(" local line state");
|
|
118
|
+
lines.push("");
|
|
119
|
+
const flagSpecs = buildZshFlagSpecsFromFlags(node.mergedFlags);
|
|
120
|
+
lines.push(" _arguments -C \\");
|
|
121
|
+
for (const spec of flagSpecs) lines.push(`\t\t${spec} \\`);
|
|
122
|
+
lines.push(" '1: :->subcmd' \\");
|
|
123
|
+
lines.push(" '*::arg:->args'");
|
|
124
|
+
lines.push("");
|
|
125
|
+
lines.push(" case \"$state\" in");
|
|
126
|
+
lines.push(" subcmd)");
|
|
127
|
+
lines.push(" subcmds=(");
|
|
128
|
+
appendZshCommandCandidates(lines, node.children, " ");
|
|
129
|
+
lines.push(" )");
|
|
130
|
+
lines.push(" _describe 'command' subcmds");
|
|
131
|
+
lines.push(" ;;");
|
|
132
|
+
lines.push(" args)");
|
|
133
|
+
lines.push(" case \"$line[1]\" in");
|
|
134
|
+
for (const child of node.children) {
|
|
135
|
+
const allNames = [child.name, ...child.aliases].map(escapeZshCasePatternValue);
|
|
136
|
+
const childFuncName = `${rootFuncName}_${[...node.path, child.name].map(sanitizeShellIdentifier).join("_")}`;
|
|
137
|
+
lines.push(`\t\t\t\t${allNames.join("|")})`);
|
|
138
|
+
lines.push(`\t\t\t\t\t${childFuncName}`);
|
|
139
|
+
lines.push(" ;;");
|
|
140
|
+
}
|
|
141
|
+
lines.push(" esac");
|
|
142
|
+
lines.push(" ;;");
|
|
143
|
+
lines.push(" esac");
|
|
144
|
+
lines.push("}");
|
|
145
|
+
lines.push("");
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Emit a zsh helper function for a leaf command (no subcommands).
|
|
149
|
+
*
|
|
150
|
+
* Uses plain `_arguments` with the command's own flags plus propagated flags.
|
|
151
|
+
*
|
|
152
|
+
* @internal
|
|
153
|
+
*/
|
|
154
|
+
function emitZshLeafFunction(lines, helperName, node) {
|
|
155
|
+
const flagSpecs = buildZshFlagSpecsFromFlags(node.mergedFlags);
|
|
156
|
+
lines.push(`${helperName}() {`);
|
|
157
|
+
if (flagSpecs.length > 0) {
|
|
158
|
+
lines.push(" _arguments \\");
|
|
159
|
+
for (let i = 0; i < flagSpecs.length; i++) {
|
|
160
|
+
const trailing = i < flagSpecs.length - 1 ? " \\" : "";
|
|
161
|
+
lines.push(`\t\t${flagSpecs[i]}${trailing}`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
lines.push("}");
|
|
165
|
+
lines.push("");
|
|
166
|
+
}
|
|
167
|
+
function appendZshCommandCandidates(lines, commands, indent) {
|
|
168
|
+
for (const command of commands) {
|
|
169
|
+
const description = command.description ?? command.name;
|
|
170
|
+
for (const alias of [command.name, ...command.aliases]) lines.push(`${indent}${quoteShellArg(`${alias}:${description}`)}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Escape a value for use in a zsh `case` pattern.
|
|
175
|
+
*
|
|
176
|
+
* Escapes glob metacharacters so arbitrary command and alias names match
|
|
177
|
+
* literally rather than being interpreted as shell patterns.
|
|
178
|
+
*
|
|
179
|
+
* @internal
|
|
180
|
+
*/
|
|
181
|
+
function escapeZshCasePatternValue(value) {
|
|
182
|
+
if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
|
|
183
|
+
return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/"/g, "\\\"").replace(/`/g, "\\`").replace(/\|/g, "\\|").replace(/\*/g, "\\*").replace(/\?/g, "\\?").replace(/\[/g, "\\[").replace(/\]/g, "\\]").replace(/\(/g, "\\(").replace(/\)/g, "\\)").replace(/\{/g, "\\{").replace(/\}/g, "\\}").replace(/\+/g, "\\+").replace(/!/g, "\\!").replace(/@/g, "\\@").replace(/#/g, "\\#").replace(/~/g, "\\~").replace(/\s/g, (match) => match === " " ? "\\ " : `\\${match}`);
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Escape a description for use inside a zsh `_arguments` flag spec.
|
|
187
|
+
*
|
|
188
|
+
* `]` closes the description segment, so it must be escaped. Backslashes are
|
|
189
|
+
* escaped as well so descriptions with literal escapes remain stable.
|
|
190
|
+
*
|
|
191
|
+
* @internal
|
|
192
|
+
*/
|
|
193
|
+
function escapeZshDescription(value) {
|
|
194
|
+
return value.replace(/\\/g, "\\\\").replace(/\]/g, "\\]");
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Build `_arguments` flag spec strings from a merged flag record.
|
|
198
|
+
*
|
|
199
|
+
* Each flag produces one or more spec strings in zsh `_arguments` format:
|
|
200
|
+
* - `'--name[description]'` for simple flags
|
|
201
|
+
* - `'--name[description]:value:(v1 v2 v3)'` for enum flags
|
|
202
|
+
* - `'(-s --name --alias)'{-s,--name,--alias}'[description]'` for flags with
|
|
203
|
+
* visible aliases
|
|
204
|
+
*
|
|
205
|
+
* @internal
|
|
206
|
+
*/
|
|
207
|
+
function buildZshFlagSpecsFromFlags(flags) {
|
|
208
|
+
const specs = [];
|
|
209
|
+
for (const [name, schema] of Object.entries(flags)) {
|
|
210
|
+
const desc = escapeZshDescription(schema.description ?? name);
|
|
211
|
+
const longFlag = `--${name}`;
|
|
212
|
+
const shortFlags = getFlagAliasNames(schema, { kind: "short" }).map((alias) => `-${alias}`);
|
|
213
|
+
const longAliases = getFlagAliasNames(schema, { kind: "long" }).map((alias) => `--${alias}`);
|
|
214
|
+
const allForms = [
|
|
215
|
+
...shortFlags,
|
|
216
|
+
longFlag,
|
|
217
|
+
...longAliases
|
|
218
|
+
];
|
|
219
|
+
let valuePart = "";
|
|
220
|
+
if (schema.kind === "boolean") {} else if (schema.kind === "enum" && schema.enumValues !== void 0) valuePart = `:value:(${schema.enumValues.map(escapeZshEnumValue).join(" ")})`;
|
|
221
|
+
else valuePart = ":value:";
|
|
222
|
+
if (allForms.length > 1) {
|
|
223
|
+
const escapedForms = allForms.map(escapeZshCasePatternValue).join(",");
|
|
224
|
+
specs.push(`${quoteShellArg(`(${allForms.join(" ")})`)}{${escapedForms}}${quoteShellArg(`[${desc}]${valuePart}`)}`);
|
|
225
|
+
} else specs.push(quoteShellArg(`${longFlag}[${desc}]${valuePart}`));
|
|
226
|
+
}
|
|
227
|
+
return specs;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Escape a single enum value for use inside a zsh `(v1 v2)` value list.
|
|
231
|
+
*
|
|
232
|
+
* Simple identifier-like values (matching `[a-zA-Z0-9_\-.]`) pass through
|
|
233
|
+
* unescaped. Values containing spaces, quotes, backslashes, or parentheses
|
|
234
|
+
* are escaped with backslash prefixes for each special character, which
|
|
235
|
+
* is the standard mechanism within zsh parenthesized completion lists.
|
|
236
|
+
*
|
|
237
|
+
* @internal
|
|
238
|
+
*/
|
|
239
|
+
function escapeZshEnumValue(value) {
|
|
240
|
+
if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
|
|
241
|
+
return value.replace(/\\/g, "\\\\").replace(/ /g, "\\ ").replace(/\(/g, "\\(").replace(/\)/g, "\\)");
|
|
242
|
+
}
|
|
243
|
+
//#endregion
|
|
244
|
+
export { generateZshCompletion };
|
|
@@ -1 +1,246 @@
|
|
|
1
|
-
import{CLIError
|
|
1
|
+
import { CLIError } from "../errors/index.mjs";
|
|
2
|
+
import "./package-json.mjs";
|
|
3
|
+
//#region src/core/config/index.ts
|
|
4
|
+
/**
|
|
5
|
+
* Config file discovery and loading.
|
|
6
|
+
*
|
|
7
|
+
* Probes a prioritised list of candidate paths, reads the first match via
|
|
8
|
+
* {@link RuntimeAdapter.readFile}, and parses the content using an
|
|
9
|
+
* extension-based loader (JSON built-in, others additive via {@link FormatLoader}).
|
|
10
|
+
*
|
|
11
|
+
* The module is pure — all I/O flows through the adapter, making it fully
|
|
12
|
+
* testable with {@link createTestAdapter}'s virtual filesystem.
|
|
13
|
+
*
|
|
14
|
+
* @module dreamcli/core/config
|
|
15
|
+
*/
|
|
16
|
+
/** @internal */
|
|
17
|
+
function isPlainObject(value) {
|
|
18
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
19
|
+
const proto = Object.getPrototypeOf(value);
|
|
20
|
+
return proto === Object.prototype || proto === null;
|
|
21
|
+
}
|
|
22
|
+
/** @internal */
|
|
23
|
+
const jsonLoader = {
|
|
24
|
+
extensions: ["json"],
|
|
25
|
+
parse: (content) => {
|
|
26
|
+
const parsed = JSON.parse(content);
|
|
27
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("Config must be a JSON object");
|
|
28
|
+
return parsed;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Join path segments using the separator detected from the base path.
|
|
33
|
+
*
|
|
34
|
+
* Avoids importing `node:path` — the base path is already platform-native
|
|
35
|
+
* (comes from `adapter.cwd` / `adapter.configDir`), so we infer the
|
|
36
|
+
* separator from its content.
|
|
37
|
+
*
|
|
38
|
+
* @internal
|
|
39
|
+
*/
|
|
40
|
+
function joinPath(base, ...segments) {
|
|
41
|
+
const sep = base.includes("\\") ? "\\" : "/";
|
|
42
|
+
return [base, ...segments].join(sep);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Extract the file extension (without leading dot, lowercased).
|
|
46
|
+
* Returns empty string when no extension is present.
|
|
47
|
+
*
|
|
48
|
+
* @internal
|
|
49
|
+
*/
|
|
50
|
+
function getExtension(path) {
|
|
51
|
+
const lastDot = path.lastIndexOf(".");
|
|
52
|
+
if (lastDot <= Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"))) return "";
|
|
53
|
+
return path.slice(lastDot + 1).toLowerCase();
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Build the default config search paths for an app.
|
|
57
|
+
*
|
|
58
|
+
* Advanced helper used by DreamCLI's config discovery. Most apps should call
|
|
59
|
+
* `.config()` or {@link discoverConfig} instead of constructing search paths
|
|
60
|
+
* manually. Exported for debugging, custom discovery flows, and help text.
|
|
61
|
+
*
|
|
62
|
+
* Search order (first match wins):
|
|
63
|
+
* 1. `$CWD/.{appName}.json` — dotfile in project root
|
|
64
|
+
* 2. `$CWD/{appName}.config.json` — explicit config in project root
|
|
65
|
+
* 3. `$CONFIG_DIR/{appName}/config.json` — XDG / AppData standard
|
|
66
|
+
* (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
|
|
67
|
+
* `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
|
|
68
|
+
*
|
|
69
|
+
* When custom {@link ConfigDiscoveryOptions.loaders | loaders} are registered,
|
|
70
|
+
* each path pattern is repeated per supported extension (JSON always first).
|
|
71
|
+
*
|
|
72
|
+
* @param appName - CLI application name used to derive config filenames.
|
|
73
|
+
* @param cwd - Current working directory (project-root search location).
|
|
74
|
+
* @param configDir - Platform config directory (XDG / AppData).
|
|
75
|
+
* @param loaders - Optional custom {@link FormatLoader}s whose extensions expand the search set.
|
|
76
|
+
* @returns Ordered list of candidate config file paths (first match wins).
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* const paths = buildConfigSearchPaths('mycli', '/repo', '/home/me/.config');
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
function buildConfigSearchPaths(appName, cwd, configDir, loaders) {
|
|
84
|
+
const extensions = buildExtensionList(loaders);
|
|
85
|
+
const paths = [];
|
|
86
|
+
for (const ext of extensions) paths.push(joinPath(cwd, `.${appName}.${ext}`));
|
|
87
|
+
for (const ext of extensions) paths.push(joinPath(cwd, `${appName}.config.${ext}`));
|
|
88
|
+
for (const ext of extensions) paths.push(joinPath(configDir, appName, `config.${ext}`));
|
|
89
|
+
return paths;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Collect unique extensions from the built-in JSON loader + any custom loaders.
|
|
93
|
+
* JSON always comes first. Order otherwise matches loader registration order.
|
|
94
|
+
*
|
|
95
|
+
* @param loaders - Optional custom {@link FormatLoader}s to append after JSON.
|
|
96
|
+
* @returns Deduplicated, lowercased extension list (JSON first).
|
|
97
|
+
*
|
|
98
|
+
* @internal
|
|
99
|
+
*/
|
|
100
|
+
function buildExtensionList(loaders) {
|
|
101
|
+
const seen = /* @__PURE__ */ new Set();
|
|
102
|
+
const result = [];
|
|
103
|
+
for (const ext of jsonLoader.extensions) {
|
|
104
|
+
const lower = ext.toLowerCase();
|
|
105
|
+
if (!seen.has(lower)) {
|
|
106
|
+
seen.add(lower);
|
|
107
|
+
result.push(lower);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (loaders !== void 0) for (const loader of loaders) for (const ext of loader.extensions) {
|
|
111
|
+
const lower = ext.toLowerCase();
|
|
112
|
+
if (!seen.has(lower)) {
|
|
113
|
+
seen.add(lower);
|
|
114
|
+
result.push(lower);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return result;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Build extension → loader lookup. Later loaders for the same extension
|
|
121
|
+
* override earlier ones (allows user to replace the built-in JSON loader).
|
|
122
|
+
*
|
|
123
|
+
* @param loaders - Optional custom {@link FormatLoader}s (later entries override earlier for same extension).
|
|
124
|
+
* @returns Map from lowercased extension to its {@link FormatLoader}.
|
|
125
|
+
*
|
|
126
|
+
* @internal
|
|
127
|
+
*/
|
|
128
|
+
function buildLoaderMap(loaders) {
|
|
129
|
+
const map = /* @__PURE__ */ new Map();
|
|
130
|
+
for (const ext of jsonLoader.extensions) map.set(ext.toLowerCase(), jsonLoader);
|
|
131
|
+
if (loaders !== void 0) for (const loader of loaders) for (const ext of loader.extensions) map.set(ext.toLowerCase(), loader);
|
|
132
|
+
return map;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Discover and load a config file.
|
|
136
|
+
*
|
|
137
|
+
* Low-level discovery helper behind `CLIBuilder.config()`. Most apps should
|
|
138
|
+
* let the CLI runtime call this automatically; call it directly when testing
|
|
139
|
+
* config behavior or building custom bootstrapping around {@linkcode RuntimeAdapter}.
|
|
140
|
+
*
|
|
141
|
+
* Pure function — all filesystem I/O flows through `adapter.readFile`.
|
|
142
|
+
* Returns a discriminated union: `{ found: true, ... }` when a config
|
|
143
|
+
* file was found and parsed, `{ found: false }` when no file exists.
|
|
144
|
+
*
|
|
145
|
+
* @throws {CLIError} code `CONFIG_NOT_FOUND` — explicit `configPath` doesn't exist
|
|
146
|
+
* @throws {CLIError} code `CONFIG_PARSE_ERROR` — file exists but fails to parse
|
|
147
|
+
* @throws {CLIError} code `CONFIG_UNKNOWN_FORMAT` — no loader for the file extension
|
|
148
|
+
*
|
|
149
|
+
* @example
|
|
150
|
+
* ```ts
|
|
151
|
+
* const result = await discoverConfig('mycli', adapter, {
|
|
152
|
+
* loaders: [
|
|
153
|
+
* configFormat(['yaml', 'yml'], Bun.YAML.parse),
|
|
154
|
+
* configFormat(['toml'], Bun.TOML.parse),
|
|
155
|
+
* ],
|
|
156
|
+
* });
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
159
|
+
async function discoverConfig(appName, adapter, options) {
|
|
160
|
+
const loaderMap = buildLoaderMap(options?.loaders);
|
|
161
|
+
const searchPaths = options?.configPath !== void 0 ? [options.configPath] : options?.searchPaths ?? buildConfigSearchPaths(appName, adapter.cwd, adapter.configDir, options?.loaders);
|
|
162
|
+
for (const candidatePath of searchPaths) {
|
|
163
|
+
const content = await adapter.readFile(candidatePath);
|
|
164
|
+
if (content === null) {
|
|
165
|
+
if (options?.configPath !== void 0) throw new CLIError(`Config file not found: ${candidatePath}`, {
|
|
166
|
+
code: "CONFIG_NOT_FOUND",
|
|
167
|
+
details: { path: candidatePath },
|
|
168
|
+
suggest: "Create the config file or remove the --config flag"
|
|
169
|
+
});
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const ext = getExtension(candidatePath);
|
|
173
|
+
const loader = loaderMap.get(ext);
|
|
174
|
+
if (loader === void 0) throw new CLIError(`No loader registered for config format: .${ext}`, {
|
|
175
|
+
code: "CONFIG_UNKNOWN_FORMAT",
|
|
176
|
+
details: {
|
|
177
|
+
path: candidatePath,
|
|
178
|
+
extension: ext
|
|
179
|
+
},
|
|
180
|
+
suggest: `Supported formats: ${[...loaderMap.keys()].join(", ")}`
|
|
181
|
+
});
|
|
182
|
+
try {
|
|
183
|
+
const data = loader.parse(content);
|
|
184
|
+
if (!isPlainObject(data)) throw new Error("Config loader must return a plain object");
|
|
185
|
+
return {
|
|
186
|
+
found: true,
|
|
187
|
+
path: candidatePath,
|
|
188
|
+
data,
|
|
189
|
+
format: ext
|
|
190
|
+
};
|
|
191
|
+
} catch (cause) {
|
|
192
|
+
throw new CLIError(`Failed to parse config file: ${candidatePath}`, {
|
|
193
|
+
code: "CONFIG_PARSE_ERROR",
|
|
194
|
+
cause,
|
|
195
|
+
details: {
|
|
196
|
+
path: candidatePath,
|
|
197
|
+
format: ext,
|
|
198
|
+
message: cause instanceof Error ? cause.message : String(cause)
|
|
199
|
+
},
|
|
200
|
+
suggest: "Check the config file for syntax errors"
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return { found: false };
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Create a {@link FormatLoader} from extensions and a parse function.
|
|
208
|
+
*
|
|
209
|
+
* Convenience factory for config loading. It avoids manually constructing the
|
|
210
|
+
* `{ extensions, parse }` object and makes intent clearer at call sites.
|
|
211
|
+
*
|
|
212
|
+
* Later loaders registered for the same extension override earlier ones. Any
|
|
213
|
+
* error thrown by `parse` is wrapped by {@link discoverConfig} as
|
|
214
|
+
* `CONFIG_PARSE_ERROR`.
|
|
215
|
+
*
|
|
216
|
+
* @param extensions - File extensions this loader handles (without dot, e.g. `'yaml'`).
|
|
217
|
+
* @param parse - Parse function: takes file content string and returns a parsed config value.
|
|
218
|
+
* @returns A {@link FormatLoader} ready to pass to {@link ConfigDiscoveryOptions.loaders}.
|
|
219
|
+
*
|
|
220
|
+
* @example
|
|
221
|
+
* ```ts
|
|
222
|
+
* import { cli, configFormat } from '@kjanat/dreamcli';
|
|
223
|
+
* import { parse as parseYaml } from 'yaml';
|
|
224
|
+
* import { parse as parseTOML } from '@iarna/toml';
|
|
225
|
+
*
|
|
226
|
+
* const yamlPackageLoader = configFormat(['yaml', 'yml'], parseYaml);
|
|
227
|
+
* const tomlPackageLoader = configFormat(['toml'], parseTOML);
|
|
228
|
+
* // Or with Bun's built-in parsers:
|
|
229
|
+
* // const yamlLoader = configFormat(['yaml', 'yml'], Bun.YAML.parse);
|
|
230
|
+
* // const tomlLoader = configFormat(['toml'], Bun.TOML.parse);
|
|
231
|
+
*
|
|
232
|
+
* cli('myapp')
|
|
233
|
+
* .config('myapp')
|
|
234
|
+
* .configLoader(yamlLoader)
|
|
235
|
+
* .configLoader(tomlLoader)
|
|
236
|
+
* .run();
|
|
237
|
+
* ```
|
|
238
|
+
*/
|
|
239
|
+
function configFormat(extensions, parse) {
|
|
240
|
+
return {
|
|
241
|
+
extensions,
|
|
242
|
+
parse
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
//#endregion
|
|
246
|
+
export { buildConfigSearchPaths, configFormat, discoverConfig };
|