@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.3
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 +37 -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.d.mts +7 -3
- package/dist/version.mjs +7 -1
- package/package.json +21 -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,310 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Shared infrastructure for shell completion generators.
|
|
3
|
-
*
|
|
4
|
-
* Provides the command tree walker, shell escaping utilities, and
|
|
5
|
-
* the version tag used in generated script headers. Consumed by
|
|
6
|
-
* the per-shell generators in sibling files.
|
|
7
|
-
*
|
|
8
|
-
* @module dreamcli/core/completion/shells/shared
|
|
9
|
-
* @internal
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import { collectPropagatedFlags } from '#internals/core/cli/propagate.ts';
|
|
13
|
-
import { resolveRootSurface } from '#internals/core/cli/root-surface.ts';
|
|
14
|
-
import type { CommandSchema, FlagSchema } from '#internals/core/schema/index.ts';
|
|
15
|
-
import { DREAMCLI_REVISION, DREAMCLI_VERSION } from '#internals/version.ts';
|
|
16
|
-
|
|
17
|
-
// --- Version tag for generated script headers
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Format a version tag for generated completion script headers.
|
|
21
|
-
*
|
|
22
|
-
* Produces e.g. `"@kjanat/dreamcli v0.9.1 (f9b5f1a)"` when built, or
|
|
23
|
-
* `"@kjanat/dreamcli"` when running unbundled in development.
|
|
24
|
-
*
|
|
25
|
-
* @internal
|
|
26
|
-
*/
|
|
27
|
-
function versionTag(): string {
|
|
28
|
-
if (DREAMCLI_VERSION === 'dev') return '@kjanat/dreamcli';
|
|
29
|
-
const rev = DREAMCLI_REVISION !== 'dev' ? ` (${DREAMCLI_REVISION})` : '';
|
|
30
|
-
return `@kjanat/dreamcli v${DREAMCLI_VERSION}${rev}`;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
// --- CompletionOptions — generator configuration
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Options for completion script generation.
|
|
37
|
-
*
|
|
38
|
-
* Passed to individual shell generators alongside the CLI schema.
|
|
39
|
-
*
|
|
40
|
-
* These options affect the generated script text, not runtime completion
|
|
41
|
-
* behavior after installation.
|
|
42
|
-
*/
|
|
43
|
-
interface CompletionOptions {
|
|
44
|
-
/**
|
|
45
|
-
* Override the generated shell function name prefix.
|
|
46
|
-
*
|
|
47
|
-
* Defaults to the CLI name from the schema. This is mainly useful when
|
|
48
|
-
* embedding multiple generated scripts in the same environment and you want
|
|
49
|
-
* deterministic, collision-free helper names.
|
|
50
|
-
*
|
|
51
|
-
* @example
|
|
52
|
-
* ```ts
|
|
53
|
-
* generateCompletion(schema, 'bash', { functionPrefix: 'acme' });
|
|
54
|
-
* ```
|
|
55
|
-
*/
|
|
56
|
-
readonly functionPrefix?: string;
|
|
57
|
-
/**
|
|
58
|
-
* Where the built-in shell completion is exposed.
|
|
59
|
-
*
|
|
60
|
-
* - `'command'` registers a `completions` subcommand (the default).
|
|
61
|
-
* - `'flag'` exposes an eager `--completions <shell>` flag on the CLI root
|
|
62
|
-
* instead, keeping the root free of a `completions` subcommand.
|
|
63
|
-
*
|
|
64
|
-
* @defaultValue `'command'`
|
|
65
|
-
*/
|
|
66
|
-
readonly as?: 'command' | 'flag';
|
|
67
|
-
/**
|
|
68
|
-
* Controls which root-level surface shell completion exposes when a
|
|
69
|
-
* default command exists.
|
|
70
|
-
*
|
|
71
|
-
* - `'subcommands'` keeps hybrid CLIs command-centric at the root while
|
|
72
|
-
* still exposing default-command flags for a single visible default
|
|
73
|
-
* command.
|
|
74
|
-
* - `'surface'` exposes the default command's root-usable flags at the
|
|
75
|
-
* root whenever a visible default command exists.
|
|
76
|
-
*
|
|
77
|
-
* @defaultValue `'subcommands'`
|
|
78
|
-
*/
|
|
79
|
-
readonly rootMode?: 'subcommands' | 'surface';
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// --- Root completion surface — shared policy resolver
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Normalized root completion surface consumed by shell generators.
|
|
86
|
-
*
|
|
87
|
-
* @internal
|
|
88
|
-
*/
|
|
89
|
-
interface RootCompletionSurface {
|
|
90
|
-
readonly visibleCommands: readonly CommandSchema[];
|
|
91
|
-
readonly visibleDefaultCommand: CommandSchema | undefined;
|
|
92
|
-
readonly rootFlags: Readonly<Record<string, FlagSchema>>;
|
|
93
|
-
readonly defaultFlags: Readonly<Record<string, FlagSchema>>;
|
|
94
|
-
readonly includeDefaultFlags: boolean;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Schema shape needed to compute the root completion surface.
|
|
99
|
-
*
|
|
100
|
-
* @internal
|
|
101
|
-
*/
|
|
102
|
-
interface RootCompletionSchemaLike {
|
|
103
|
-
readonly commands: ReadonlyArray<{
|
|
104
|
-
readonly schema: CommandSchema;
|
|
105
|
-
}>;
|
|
106
|
-
readonly defaultCommand: { readonly schema: CommandSchema } | undefined;
|
|
107
|
-
readonly version: string | undefined;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Resolve the root-level completion surface from the CLI schema and policy.
|
|
112
|
-
*
|
|
113
|
-
* @internal
|
|
114
|
-
*/
|
|
115
|
-
function resolveRootCompletionSurface(
|
|
116
|
-
schema: RootCompletionSchemaLike,
|
|
117
|
-
rootMode: CompletionOptions['rootMode'] = 'subcommands',
|
|
118
|
-
): RootCompletionSurface {
|
|
119
|
-
const rootSurface = resolveRootSurface(schema);
|
|
120
|
-
const rootFlags = createRootFlags(schema.version !== undefined);
|
|
121
|
-
const defaultFlags = rootSurface.visibleDefaultCommand?.flags ?? {};
|
|
122
|
-
// Default flags surface at the root either always (`surface`) or only when
|
|
123
|
-
// the default is the sole surface (`subcommands`).
|
|
124
|
-
const includeDefaultFlags =
|
|
125
|
-
rootMode === 'surface'
|
|
126
|
-
? rootSurface.hasVisibleDefault
|
|
127
|
-
: rootSurface.hasVisibleDefault && !rootSurface.hasVisibleSubcommands;
|
|
128
|
-
|
|
129
|
-
// Generated completion scripts keep treating the default command as part of
|
|
130
|
-
// the root surface (a walkable node carrying its own flags/args), regardless
|
|
131
|
-
// of whether it is registered under `commands` — since v0.3 `.default()` keeps
|
|
132
|
-
// it only in `defaultCommand`. Re-add it here so the per-shell generators,
|
|
133
|
-
// which build their dispatch machinery from this list, behave unchanged.
|
|
134
|
-
const defaultCommand = rootSurface.visibleDefaultCommand;
|
|
135
|
-
const alreadyListed =
|
|
136
|
-
defaultCommand !== undefined &&
|
|
137
|
-
rootSurface.visibleCommands.some((c) => c.name === defaultCommand.name);
|
|
138
|
-
const visibleCommands =
|
|
139
|
-
defaultCommand !== undefined && !alreadyListed
|
|
140
|
-
? [defaultCommand, ...rootSurface.visibleCommands]
|
|
141
|
-
: rootSurface.visibleCommands;
|
|
142
|
-
|
|
143
|
-
return {
|
|
144
|
-
visibleCommands,
|
|
145
|
-
visibleDefaultCommand: rootSurface.visibleDefaultCommand,
|
|
146
|
-
rootFlags,
|
|
147
|
-
defaultFlags,
|
|
148
|
-
includeDefaultFlags,
|
|
149
|
-
};
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/**
|
|
153
|
-
* Build the synthetic root-level flags (`--help`, optionally `--version`).
|
|
154
|
-
*
|
|
155
|
-
* @param hasVersion - Whether to include a `--version` flag.
|
|
156
|
-
* @returns A record of root flag schemas.
|
|
157
|
-
* @internal
|
|
158
|
-
*/
|
|
159
|
-
function createRootFlags(hasVersion: boolean): Readonly<Record<string, FlagSchema>> {
|
|
160
|
-
return {
|
|
161
|
-
help: createSyntheticRootFlag('Show help text'),
|
|
162
|
-
...(hasVersion ? { version: createSyntheticRootFlag('Show version') } : {}),
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/**
|
|
167
|
-
* Create a minimal boolean {@link FlagSchema} for a synthetic root flag.
|
|
168
|
-
*
|
|
169
|
-
* @param description - Help text for the flag.
|
|
170
|
-
* @returns A complete flag schema with all optional fields defaulted.
|
|
171
|
-
* @internal
|
|
172
|
-
*/
|
|
173
|
-
function createSyntheticRootFlag(description: string): FlagSchema {
|
|
174
|
-
return {
|
|
175
|
-
kind: 'boolean',
|
|
176
|
-
presence: 'optional',
|
|
177
|
-
defaultValue: undefined,
|
|
178
|
-
aliases: [],
|
|
179
|
-
envVar: undefined,
|
|
180
|
-
configPath: undefined,
|
|
181
|
-
description,
|
|
182
|
-
enumValues: undefined,
|
|
183
|
-
numberConstraints: undefined,
|
|
184
|
-
elementSchema: undefined,
|
|
185
|
-
prompt: undefined,
|
|
186
|
-
parseFn: undefined,
|
|
187
|
-
deprecated: undefined,
|
|
188
|
-
propagate: false,
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
// --- Command tree walking — shared infrastructure
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* A flattened node from the command tree, carrying its ancestry context.
|
|
196
|
-
*
|
|
197
|
-
* Used by both bash and zsh generators to produce completions at every
|
|
198
|
-
* nesting level with correct propagated flag inheritance.
|
|
199
|
-
*
|
|
200
|
-
* @internal
|
|
201
|
-
*/
|
|
202
|
-
interface CommandNode {
|
|
203
|
-
/** Name path from root: `['db', 'migrate']` */
|
|
204
|
-
readonly path: readonly string[];
|
|
205
|
-
/** The command schema at this node */
|
|
206
|
-
readonly schema: CommandSchema;
|
|
207
|
-
/** Propagated flags inherited from ancestors (excludes own flags) */
|
|
208
|
-
readonly propagatedFlags: Readonly<Record<string, FlagSchema>>;
|
|
209
|
-
/** Merged flags: propagated + own (own shadows propagated) */
|
|
210
|
-
readonly mergedFlags: Readonly<Record<string, FlagSchema>>;
|
|
211
|
-
/** Visible child command schemas (for subcommand completion) */
|
|
212
|
-
readonly children: readonly CommandSchema[];
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
/**
|
|
216
|
-
* Walk the command tree depth-first, producing a flat list of
|
|
217
|
-
* {@link CommandNode}s with propagated flag context.
|
|
218
|
-
*
|
|
219
|
-
* @param topLevel - Top-level visible command schemas.
|
|
220
|
-
* @param ancestorSchemas - Schema path from root (for propagation calculation).
|
|
221
|
-
* @returns Flat list of all visible nodes in the tree.
|
|
222
|
-
*
|
|
223
|
-
* @internal
|
|
224
|
-
*/
|
|
225
|
-
function walkCommandTree(
|
|
226
|
-
topLevel: readonly CommandSchema[],
|
|
227
|
-
ancestorSchemas: readonly CommandSchema[] = [],
|
|
228
|
-
): readonly CommandNode[] {
|
|
229
|
-
const nodes: CommandNode[] = [];
|
|
230
|
-
|
|
231
|
-
for (const schema of topLevel) {
|
|
232
|
-
if (schema.hidden) continue;
|
|
233
|
-
|
|
234
|
-
const fullPath = [...ancestorSchemas, schema];
|
|
235
|
-
const propagatedFlags = collectPropagatedFlags(fullPath);
|
|
236
|
-
const mergedFlags: Record<string, FlagSchema> = { ...propagatedFlags, ...schema.flags };
|
|
237
|
-
const children = schema.commands.filter((c) => !c.hidden);
|
|
238
|
-
|
|
239
|
-
nodes.push({
|
|
240
|
-
path: fullPath.map((s) => s.name),
|
|
241
|
-
schema,
|
|
242
|
-
propagatedFlags,
|
|
243
|
-
mergedFlags,
|
|
244
|
-
children,
|
|
245
|
-
});
|
|
246
|
-
|
|
247
|
-
// Recurse into visible children only (hidden subtrees skipped entirely)
|
|
248
|
-
if (children.length > 0) {
|
|
249
|
-
nodes.push(...walkCommandTree(children, fullPath));
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
return nodes;
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
// --- Shell escaping utilities
|
|
257
|
-
|
|
258
|
-
/**
|
|
259
|
-
* Sanitize a string for use as a shell function identifier.
|
|
260
|
-
* Replaces non-alphanumeric/underscore characters with underscores.
|
|
261
|
-
* When sanitization changes the name, appends a short stable hash suffix so
|
|
262
|
-
* distinct originals cannot collide on the same helper identifier.
|
|
263
|
-
* Used by both bash and zsh generators.
|
|
264
|
-
*
|
|
265
|
-
* @internal
|
|
266
|
-
*/
|
|
267
|
-
function sanitizeShellIdentifier(name: string): string {
|
|
268
|
-
const sanitized = name.replace(/[^a-zA-Z0-9_]/g, '_');
|
|
269
|
-
if (sanitized === name) {
|
|
270
|
-
return sanitized;
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
let hash = 2166136261;
|
|
274
|
-
for (let i = 0; i < name.length; i += 1) {
|
|
275
|
-
hash ^= name.charCodeAt(i);
|
|
276
|
-
hash = Math.imul(hash, 16777619);
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
return `${sanitized}_${(hash >>> 0).toString(16).padStart(8, '0')}`;
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
/**
|
|
283
|
-
* Quote a string for safe interpolation into a shell script.
|
|
284
|
-
*
|
|
285
|
-
* Uses single-quote wrapping with the standard `'\''` idiom for
|
|
286
|
-
* embedded single quotes. This prevents shell injection from CLI
|
|
287
|
-
* names containing spaces, semicolons, backticks, or other
|
|
288
|
-
* special characters.
|
|
289
|
-
*
|
|
290
|
-
* Returns the input unquoted if it consists only of shell-safe
|
|
291
|
-
* characters (`[a-zA-Z0-9_\-.]`), avoiding unnecessary noise
|
|
292
|
-
* in generated scripts for common CLI names like `my-cli` or `app.v2`.
|
|
293
|
-
*
|
|
294
|
-
* @internal
|
|
295
|
-
*/
|
|
296
|
-
function quoteShellArg(value: string): string {
|
|
297
|
-
if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
|
|
298
|
-
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
// --- Exports
|
|
302
|
-
|
|
303
|
-
export type { CommandNode, CompletionOptions, RootCompletionSurface };
|
|
304
|
-
export {
|
|
305
|
-
quoteShellArg,
|
|
306
|
-
resolveRootCompletionSurface,
|
|
307
|
-
sanitizeShellIdentifier,
|
|
308
|
-
versionTag,
|
|
309
|
-
walkCommandTree,
|
|
310
|
-
};
|
|
@@ -1,381 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Zsh completion script generator.
|
|
3
|
-
*
|
|
4
|
-
* Produces a self-contained zsh script with:
|
|
5
|
-
* - A `#compdef` directive for auto-loading
|
|
6
|
-
* - A main `_<name>` function with subcommand dispatch
|
|
7
|
-
* - Per-group helper functions (`_<name>_<cmd>`) with recursive dispatch
|
|
8
|
-
* - `_arguments` calls for flags with descriptions (including propagated flags)
|
|
9
|
-
* - `_describe` for subcommand lists at each nesting level
|
|
10
|
-
* - Enum value completions via `->state` dispatch
|
|
11
|
-
*
|
|
12
|
-
* @module dreamcli/core/completion/shells/zsh
|
|
13
|
-
* @internal
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
import type { CLISchema } from '#internals/core/cli/index.ts';
|
|
17
|
-
import { CLIError } from '#internals/core/errors/index.ts';
|
|
18
|
-
import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
|
|
19
|
-
import type { FlagSchema } from '#internals/core/schema/index.ts';
|
|
20
|
-
import type { CommandNode, CompletionOptions } from './shared.ts';
|
|
21
|
-
import {
|
|
22
|
-
quoteShellArg,
|
|
23
|
-
resolveRootCompletionSurface,
|
|
24
|
-
sanitizeShellIdentifier,
|
|
25
|
-
versionTag,
|
|
26
|
-
walkCommandTree,
|
|
27
|
-
} from './shared.ts';
|
|
28
|
-
|
|
29
|
-
// --- Public generator
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Generate a zsh completion script for the CLI.
|
|
33
|
-
*
|
|
34
|
-
* Use this when you want a zsh-specific script directly rather than routing
|
|
35
|
-
* through {@link generateCompletion}. The generated script is compatible with
|
|
36
|
-
* zsh's normal `#compdef` / `fpath` loading flow.
|
|
37
|
-
*
|
|
38
|
-
* @param schema - The CLI schema.
|
|
39
|
-
* @param options - Optional generator configuration.
|
|
40
|
-
* @returns A complete zsh completion script.
|
|
41
|
-
*
|
|
42
|
-
* @example
|
|
43
|
-
* ```ts
|
|
44
|
-
* const script = generateZshCompletion(app.schema);
|
|
45
|
-
* // install with: mycli completions zsh > "${fpath[1]}/_mycli"
|
|
46
|
-
* ```
|
|
47
|
-
*/
|
|
48
|
-
function generateZshCompletion(schema: CLISchema, options?: CompletionOptions): string {
|
|
49
|
-
const prefix = options?.functionPrefix ?? schema.name;
|
|
50
|
-
const funcName = `_${sanitizeShellIdentifier(prefix)}`;
|
|
51
|
-
const rootSurface = resolveRootCompletionSurface(schema, options?.rootMode);
|
|
52
|
-
const visibleCommands = rootSurface.visibleCommands;
|
|
53
|
-
const nodes = walkCommandTree(visibleCommands);
|
|
54
|
-
|
|
55
|
-
const lines: string[] = [];
|
|
56
|
-
|
|
57
|
-
lines.push(`#compdef ${quoteShellArg(schema.name)}`);
|
|
58
|
-
lines.push(`# Zsh completion for ${schema.name}`);
|
|
59
|
-
lines.push(`# Generated by ${versionTag()}`);
|
|
60
|
-
lines.push('#');
|
|
61
|
-
lines.push(`# Usage: source <(${schema.name} completions zsh)`);
|
|
62
|
-
lines.push('#');
|
|
63
|
-
lines.push('# Install permanently:');
|
|
64
|
-
lines.push(`# ${schema.name} completions zsh > "\${fpath[1]}/_${schema.name}"`);
|
|
65
|
-
lines.push('# # Then restart your shell');
|
|
66
|
-
lines.push('');
|
|
67
|
-
|
|
68
|
-
// --- Generate helper functions for group commands (bottom-up) ---
|
|
69
|
-
// Process deepest nodes first so all helpers exist before they're called.
|
|
70
|
-
const groupNodes = nodes.filter((n) => n.children.length > 0);
|
|
71
|
-
const leafNodes = nodes.filter((n) => n.children.length === 0);
|
|
72
|
-
|
|
73
|
-
// Emit leaf helper functions
|
|
74
|
-
for (const node of leafNodes) {
|
|
75
|
-
if (node.path.length < 2) continue; // Top-level leaves handled inline
|
|
76
|
-
const helperName = `${funcName}_${node.path.map(sanitizeShellIdentifier).join('_')}`;
|
|
77
|
-
emitZshLeafFunction(lines, helperName, node);
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
// Emit group helper functions (deepest first)
|
|
81
|
-
const sortedGroups = [...groupNodes].sort((a, b) => b.path.length - a.path.length);
|
|
82
|
-
for (const node of sortedGroups) {
|
|
83
|
-
const helperName = `${funcName}_${node.path.map(sanitizeShellIdentifier).join('_')}`;
|
|
84
|
-
emitZshGroupFunction(lines, helperName, funcName, node);
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
// --- Main function ---
|
|
88
|
-
lines.push(`${funcName}() {`);
|
|
89
|
-
|
|
90
|
-
if (visibleCommands.length > 0) {
|
|
91
|
-
lines.push('\tlocal -a subcmds');
|
|
92
|
-
lines.push('\tlocal line state');
|
|
93
|
-
lines.push('');
|
|
94
|
-
|
|
95
|
-
// --- Root-level: visible root surface ---
|
|
96
|
-
const rootFlags = {
|
|
97
|
-
...rootSurface.rootFlags,
|
|
98
|
-
...(rootSurface.includeDefaultFlags ? rootSurface.defaultFlags : {}),
|
|
99
|
-
};
|
|
100
|
-
const rootFlagSpecs = buildZshFlagSpecsFromFlags(rootFlags);
|
|
101
|
-
|
|
102
|
-
lines.push('\t_arguments -C \\');
|
|
103
|
-
for (const spec of rootFlagSpecs) {
|
|
104
|
-
lines.push(`\t\t${spec} \\`);
|
|
105
|
-
}
|
|
106
|
-
lines.push("\t\t'1: :->subcmd' \\");
|
|
107
|
-
lines.push("\t\t'*::arg:->args'");
|
|
108
|
-
lines.push('');
|
|
109
|
-
|
|
110
|
-
// --- Subcommand list ---
|
|
111
|
-
lines.push('\tcase "$state" in');
|
|
112
|
-
lines.push('\t\tsubcmd)');
|
|
113
|
-
lines.push('\t\t\tsubcmds=(');
|
|
114
|
-
appendZshCommandCandidates(lines, visibleCommands, '\t\t\t\t');
|
|
115
|
-
lines.push('\t\t\t)');
|
|
116
|
-
lines.push("\t\t\t_describe 'command' subcmds");
|
|
117
|
-
lines.push('\t\t\t;;');
|
|
118
|
-
|
|
119
|
-
// --- Per-command arguments ---
|
|
120
|
-
lines.push('\t\targs)');
|
|
121
|
-
lines.push('\t\t\tcase "$line[1]" in');
|
|
122
|
-
for (const cmd of visibleCommands) {
|
|
123
|
-
const allNames = [cmd.name, ...cmd.aliases].map(escapeZshCasePatternValue);
|
|
124
|
-
const childCommands = cmd.commands.filter((c) => !c.hidden);
|
|
125
|
-
lines.push(`\t\t\t\t${allNames.join('|')})`);
|
|
126
|
-
|
|
127
|
-
if (childCommands.length > 0) {
|
|
128
|
-
// Group command — delegate to helper function
|
|
129
|
-
const helperName = `${funcName}_${sanitizeShellIdentifier(cmd.name)}`;
|
|
130
|
-
lines.push(`\t\t\t\t\t${helperName}`);
|
|
131
|
-
} else {
|
|
132
|
-
// Leaf command — emit flags inline
|
|
133
|
-
const node = nodes.find((n) => n.path.length === 1 && n.schema.name === cmd.name);
|
|
134
|
-
if (node === undefined) {
|
|
135
|
-
throw new CLIError(`Missing completion node for command '${cmd.name}'`, {
|
|
136
|
-
code: 'UNEXPECTED_ERROR',
|
|
137
|
-
});
|
|
138
|
-
}
|
|
139
|
-
const flagSpecs = buildZshFlagSpecsFromFlags(node.mergedFlags);
|
|
140
|
-
|
|
141
|
-
if (flagSpecs.length > 0) {
|
|
142
|
-
lines.push('\t\t\t\t\t_arguments \\');
|
|
143
|
-
for (let i = 0; i < flagSpecs.length; i++) {
|
|
144
|
-
const trailing = i < flagSpecs.length - 1 ? ' \\' : '';
|
|
145
|
-
lines.push(`\t\t\t\t\t\t${flagSpecs[i]}${trailing}`);
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
lines.push('\t\t\t\t\t;;');
|
|
150
|
-
}
|
|
151
|
-
lines.push('\t\t\tesac');
|
|
152
|
-
lines.push('\t\t\t;;');
|
|
153
|
-
lines.push('\tesac');
|
|
154
|
-
} else {
|
|
155
|
-
// --- No subcommands: just global flags ---
|
|
156
|
-
const globalFlags = buildZshFlagSpecsFromFlags(rootSurface.rootFlags);
|
|
157
|
-
lines.push('\t_arguments \\');
|
|
158
|
-
for (let i = 0; i < globalFlags.length; i++) {
|
|
159
|
-
const trailing = i < globalFlags.length - 1 ? ' \\' : '';
|
|
160
|
-
lines.push(`\t\t${globalFlags[i]}${trailing}`);
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
lines.push('}');
|
|
165
|
-
lines.push('');
|
|
166
|
-
// Register with compdef for `source <(cmd completions zsh)` usage.
|
|
167
|
-
// fpath-based autoloading is handled by the `#compdef` directive above.
|
|
168
|
-
lines.push(`compdef ${funcName} ${quoteShellArg(schema.name)}`);
|
|
169
|
-
lines.push('');
|
|
170
|
-
|
|
171
|
-
return lines.join('\n');
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
// --- Zsh helpers — internal
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Emit a zsh helper function for a group command (has subcommands).
|
|
178
|
-
*
|
|
179
|
-
* Uses `_arguments -C` for its own flags plus subcommand dispatch.
|
|
180
|
-
*
|
|
181
|
-
* @internal
|
|
182
|
-
*/
|
|
183
|
-
function emitZshGroupFunction(
|
|
184
|
-
lines: string[],
|
|
185
|
-
helperName: string,
|
|
186
|
-
rootFuncName: string,
|
|
187
|
-
node: CommandNode,
|
|
188
|
-
): void {
|
|
189
|
-
lines.push(`${helperName}() {`);
|
|
190
|
-
lines.push('\tlocal -a subcmds');
|
|
191
|
-
lines.push('\tlocal line state');
|
|
192
|
-
lines.push('');
|
|
193
|
-
|
|
194
|
-
// Flags for this group (including propagated)
|
|
195
|
-
const flagSpecs = buildZshFlagSpecsFromFlags(node.mergedFlags);
|
|
196
|
-
|
|
197
|
-
lines.push('\t_arguments -C \\');
|
|
198
|
-
for (const spec of flagSpecs) {
|
|
199
|
-
lines.push(`\t\t${spec} \\`);
|
|
200
|
-
}
|
|
201
|
-
lines.push("\t\t'1: :->subcmd' \\");
|
|
202
|
-
lines.push("\t\t'*::arg:->args'");
|
|
203
|
-
lines.push('');
|
|
204
|
-
|
|
205
|
-
lines.push('\tcase "$state" in');
|
|
206
|
-
lines.push('\t\tsubcmd)');
|
|
207
|
-
lines.push('\t\t\tsubcmds=(');
|
|
208
|
-
appendZshCommandCandidates(lines, node.children, '\t\t\t\t');
|
|
209
|
-
lines.push('\t\t\t)');
|
|
210
|
-
lines.push("\t\t\t_describe 'command' subcmds");
|
|
211
|
-
lines.push('\t\t\t;;');
|
|
212
|
-
|
|
213
|
-
lines.push('\t\targs)');
|
|
214
|
-
lines.push('\t\t\tcase "$line[1]" in');
|
|
215
|
-
for (const child of node.children) {
|
|
216
|
-
const allNames = [child.name, ...child.aliases].map(escapeZshCasePatternValue);
|
|
217
|
-
const childPath = [...node.path, child.name];
|
|
218
|
-
const childFuncName = `${rootFuncName}_${childPath.map(sanitizeShellIdentifier).join('_')}`;
|
|
219
|
-
lines.push(`\t\t\t\t${allNames.join('|')})`);
|
|
220
|
-
lines.push(`\t\t\t\t\t${childFuncName}`);
|
|
221
|
-
lines.push('\t\t\t\t\t;;');
|
|
222
|
-
}
|
|
223
|
-
lines.push('\t\t\tesac');
|
|
224
|
-
lines.push('\t\t\t;;');
|
|
225
|
-
lines.push('\tesac');
|
|
226
|
-
|
|
227
|
-
lines.push('}');
|
|
228
|
-
lines.push('');
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
/**
|
|
232
|
-
* Emit a zsh helper function for a leaf command (no subcommands).
|
|
233
|
-
*
|
|
234
|
-
* Uses plain `_arguments` with the command's own flags plus propagated flags.
|
|
235
|
-
*
|
|
236
|
-
* @internal
|
|
237
|
-
*/
|
|
238
|
-
function emitZshLeafFunction(lines: string[], helperName: string, node: CommandNode): void {
|
|
239
|
-
const flagSpecs = buildZshFlagSpecsFromFlags(node.mergedFlags);
|
|
240
|
-
|
|
241
|
-
lines.push(`${helperName}() {`);
|
|
242
|
-
if (flagSpecs.length > 0) {
|
|
243
|
-
lines.push('\t_arguments \\');
|
|
244
|
-
for (let i = 0; i < flagSpecs.length; i++) {
|
|
245
|
-
const trailing = i < flagSpecs.length - 1 ? ' \\' : '';
|
|
246
|
-
lines.push(`\t\t${flagSpecs[i]}${trailing}`);
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
lines.push('}');
|
|
250
|
-
lines.push('');
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
function appendZshCommandCandidates(
|
|
254
|
-
lines: string[],
|
|
255
|
-
commands: ReadonlyArray<{
|
|
256
|
-
readonly name: string;
|
|
257
|
-
readonly aliases: readonly string[];
|
|
258
|
-
readonly description: string | undefined;
|
|
259
|
-
}>,
|
|
260
|
-
indent: string,
|
|
261
|
-
): void {
|
|
262
|
-
for (const command of commands) {
|
|
263
|
-
const description = command.description ?? command.name;
|
|
264
|
-
for (const alias of [command.name, ...command.aliases]) {
|
|
265
|
-
lines.push(`${indent}${quoteShellArg(`${alias}:${description}`)}`);
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
/**
|
|
271
|
-
* Escape a value for use in a zsh `case` pattern.
|
|
272
|
-
*
|
|
273
|
-
* Escapes glob metacharacters so arbitrary command and alias names match
|
|
274
|
-
* literally rather than being interpreted as shell patterns.
|
|
275
|
-
*
|
|
276
|
-
* @internal
|
|
277
|
-
*/
|
|
278
|
-
function escapeZshCasePatternValue(value: string): string {
|
|
279
|
-
if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
|
|
280
|
-
return value
|
|
281
|
-
.replace(/\\/g, '\\\\')
|
|
282
|
-
.replace(/'/g, "\\'")
|
|
283
|
-
.replace(/"/g, '\\"')
|
|
284
|
-
.replace(/`/g, '\\`')
|
|
285
|
-
.replace(/\|/g, '\\|')
|
|
286
|
-
.replace(/\*/g, '\\*')
|
|
287
|
-
.replace(/\?/g, '\\?')
|
|
288
|
-
.replace(/\[/g, '\\[')
|
|
289
|
-
.replace(/\]/g, '\\]')
|
|
290
|
-
.replace(/\(/g, '\\(')
|
|
291
|
-
.replace(/\)/g, '\\)')
|
|
292
|
-
.replace(/\{/g, '\\{')
|
|
293
|
-
.replace(/\}/g, '\\}')
|
|
294
|
-
.replace(/\+/g, '\\+')
|
|
295
|
-
.replace(/!/g, '\\!')
|
|
296
|
-
.replace(/@/g, '\\@')
|
|
297
|
-
.replace(/#/g, '\\#')
|
|
298
|
-
.replace(/~/g, '\\~')
|
|
299
|
-
.replace(/\s/g, (match) => (match === ' ' ? '\\ ' : `\\${match}`));
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
/**
|
|
303
|
-
* Escape a description for use inside a zsh `_arguments` flag spec.
|
|
304
|
-
*
|
|
305
|
-
* `]` closes the description segment, so it must be escaped. Backslashes are
|
|
306
|
-
* escaped as well so descriptions with literal escapes remain stable.
|
|
307
|
-
*
|
|
308
|
-
* @internal
|
|
309
|
-
*/
|
|
310
|
-
function escapeZshDescription(value: string): string {
|
|
311
|
-
return value.replace(/\\/g, '\\\\').replace(/\]/g, '\\]');
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
/**
|
|
315
|
-
* Build `_arguments` flag spec strings from a merged flag record.
|
|
316
|
-
*
|
|
317
|
-
* Each flag produces one or more spec strings in zsh `_arguments` format:
|
|
318
|
-
* - `'--name[description]'` for simple flags
|
|
319
|
-
* - `'--name[description]:value:(v1 v2 v3)'` for enum flags
|
|
320
|
-
* - `'(-s --name --alias)'{-s,--name,--alias}'[description]'` for flags with
|
|
321
|
-
* visible aliases
|
|
322
|
-
*
|
|
323
|
-
* @internal
|
|
324
|
-
*/
|
|
325
|
-
function buildZshFlagSpecsFromFlags(
|
|
326
|
-
flags: Readonly<Record<string, FlagSchema>>,
|
|
327
|
-
): readonly string[] {
|
|
328
|
-
const specs: string[] = [];
|
|
329
|
-
for (const [name, schema] of Object.entries(flags)) {
|
|
330
|
-
const desc = escapeZshDescription(schema.description ?? name);
|
|
331
|
-
const longFlag = `--${name}`;
|
|
332
|
-
const shortFlags = getFlagAliasNames(schema, { kind: 'short' }).map((alias) => `-${alias}`);
|
|
333
|
-
const longAliases = getFlagAliasNames(schema, { kind: 'long' }).map((alias) => `--${alias}`);
|
|
334
|
-
const allForms = [...shortFlags, longFlag, ...longAliases];
|
|
335
|
-
|
|
336
|
-
let valuePart = '';
|
|
337
|
-
if (schema.kind === 'boolean') {
|
|
338
|
-
// Boolean flags take no argument value
|
|
339
|
-
} else if (schema.kind === 'enum' && schema.enumValues !== undefined) {
|
|
340
|
-
const escapedValues = schema.enumValues.map(escapeZshEnumValue);
|
|
341
|
-
valuePart = `:value:(${escapedValues.join(' ')})`;
|
|
342
|
-
} else {
|
|
343
|
-
valuePart = ':value:';
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
if (allForms.length > 1) {
|
|
347
|
-
// Mutual exclusion group with all visible forms for the same flag.
|
|
348
|
-
// Format: '(-v --verbose --verb)'{-v,--verbose,--verb}'[desc]:value'
|
|
349
|
-
const escapedForms = allForms.map(escapeZshCasePatternValue).join(',');
|
|
350
|
-
specs.push(
|
|
351
|
-
`${quoteShellArg(`(${allForms.join(' ')})`)}{${escapedForms}}${quoteShellArg(
|
|
352
|
-
`[${desc}]${valuePart}`,
|
|
353
|
-
)}`,
|
|
354
|
-
);
|
|
355
|
-
} else {
|
|
356
|
-
specs.push(quoteShellArg(`${longFlag}[${desc}]${valuePart}`));
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
return specs;
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
/**
|
|
363
|
-
* Escape a single enum value for use inside a zsh `(v1 v2)` value list.
|
|
364
|
-
*
|
|
365
|
-
* Simple identifier-like values (matching `[a-zA-Z0-9_\-.]`) pass through
|
|
366
|
-
* unescaped. Values containing spaces, quotes, backslashes, or parentheses
|
|
367
|
-
* are escaped with backslash prefixes for each special character, which
|
|
368
|
-
* is the standard mechanism within zsh parenthesized completion lists.
|
|
369
|
-
*
|
|
370
|
-
* @internal
|
|
371
|
-
*/
|
|
372
|
-
function escapeZshEnumValue(value: string): string {
|
|
373
|
-
if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
|
|
374
|
-
return value
|
|
375
|
-
.replace(/\\/g, '\\\\')
|
|
376
|
-
.replace(/ /g, '\\ ')
|
|
377
|
-
.replace(/\(/g, '\\(')
|
|
378
|
-
.replace(/\)/g, '\\)');
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
export { generateZshCompletion };
|