@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/CHANGELOG.md +217 -1
  2. package/dist/core/cli/dispatch.d.mts +6 -5
  3. package/dist/core/cli/dispatch.mjs +205 -1
  4. package/dist/core/cli/help-links.d.mts +0 -1
  5. package/dist/core/cli/help-links.mjs +41 -1
  6. package/dist/core/cli/index.d.mts +81 -8
  7. package/dist/core/cli/index.mjs +945 -1
  8. package/dist/core/cli/planner.d.mts +5 -1
  9. package/dist/core/cli/planner.mjs +300 -1
  10. package/dist/core/cli/plugin.d.mts +1 -1
  11. package/dist/core/cli/plugin.mjs +41 -1
  12. package/dist/core/cli/propagate.d.mts +1 -1
  13. package/dist/core/cli/propagate.mjs +57 -1
  14. package/dist/core/cli/root-help.d.mts +2 -1
  15. package/dist/core/cli/root-help.mjs +226 -4
  16. package/dist/core/cli/root-surface.d.mts +12 -1
  17. package/dist/core/cli/root-surface.mjs +28 -1
  18. package/dist/core/cli/runtime-preflight.d.mts +14 -2
  19. package/dist/core/cli/runtime-preflight.mjs +169 -1
  20. package/dist/core/completion/index.d.mts +0 -1
  21. package/dist/core/completion/index.mjs +90 -1
  22. package/dist/core/completion/shells/bash.d.mts +0 -1
  23. package/dist/core/completion/shells/bash.mjs +308 -3
  24. package/dist/core/completion/shells/fish.d.mts +0 -1
  25. package/dist/core/completion/shells/fish.mjs +162 -2
  26. package/dist/core/completion/shells/powershell.d.mts +0 -1
  27. package/dist/core/completion/shells/powershell.mjs +358 -2
  28. package/dist/core/completion/shells/shared.d.mts +13 -2
  29. package/dist/core/completion/shells/shared.mjs +176 -1
  30. package/dist/core/completion/shells/zsh.d.mts +0 -1
  31. package/dist/core/completion/shells/zsh.mjs +251 -2
  32. package/dist/core/config/index.d.mts +2 -3
  33. package/dist/core/config/index.mjs +246 -1
  34. package/dist/core/config/package-json.d.mts +27 -4
  35. package/dist/core/config/package-json.mjs +386 -3
  36. package/dist/core/errors/index.d.mts +3 -3
  37. package/dist/core/errors/index.mjs +87 -1
  38. package/dist/core/execution/index.d.mts +0 -1
  39. package/dist/core/execution/index.mjs +201 -1
  40. package/dist/core/help/ansi.d.mts +11 -5
  41. package/dist/core/help/ansi.mjs +121 -2
  42. package/dist/core/help/index.d.mts +22 -3
  43. package/dist/core/help/index.mjs +341 -7
  44. package/dist/core/help/theme.d.mts +68 -0
  45. package/dist/core/help/theme.mjs +46 -0
  46. package/dist/core/json-schema/index.d.mts +15 -2
  47. package/dist/core/json-schema/index.mjs +536 -12
  48. package/dist/core/json-schema/meta-descriptions.generated.d.mts +55 -38
  49. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  50. package/dist/core/output/activity.d.mts +0 -1
  51. package/dist/core/output/activity.mjs +452 -1
  52. package/dist/core/output/bind.mjs +56 -1
  53. package/dist/core/output/contracts.d.mts +4 -5
  54. package/dist/core/output/contracts.mjs +57 -1
  55. package/dist/core/output/display-value.mjs +32 -1
  56. package/dist/core/output/index.d.mts +21 -1
  57. package/dist/core/output/index.mjs +442 -2
  58. package/dist/core/output/renderers.d.mts +0 -1
  59. package/dist/core/output/renderers.mjs +46 -1
  60. package/dist/core/output/writer.mjs +12 -1
  61. package/dist/core/parse/index.d.mts +40 -7
  62. package/dist/core/parse/index.mjs +727 -1
  63. package/dist/core/prompt/index.d.mts +1 -1
  64. package/dist/core/prompt/index.mjs +348 -6
  65. package/dist/core/resolve/args.d.mts +1 -1
  66. package/dist/core/resolve/args.mjs +105 -1
  67. package/dist/core/resolve/coerce.d.mts +1 -1
  68. package/dist/core/resolve/coerce.mjs +336 -1
  69. package/dist/core/resolve/config.mjs +19 -1
  70. package/dist/core/resolve/contracts.d.mts +9 -4
  71. package/dist/core/resolve/errors.d.mts +0 -1
  72. package/dist/core/resolve/errors.mjs +140 -2
  73. package/dist/core/resolve/flags.d.mts +7 -2
  74. package/dist/core/resolve/flags.mjs +251 -1
  75. package/dist/core/resolve/index.d.mts +2 -2
  76. package/dist/core/resolve/index.mjs +85 -1
  77. package/dist/core/resolve/property.d.mts +4 -2
  78. package/dist/core/resolve/property.mjs +53 -1
  79. package/dist/core/schema/activity.d.mts +31 -11
  80. package/dist/core/schema/arg.d.mts +3 -4
  81. package/dist/core/schema/arg.mjs +463 -1
  82. package/dist/core/schema/command.d.mts +26 -6
  83. package/dist/core/schema/command.mjs +726 -1
  84. package/dist/core/schema/flag.d.mts +485 -19
  85. package/dist/core/schema/flag.mjs +705 -1
  86. package/dist/core/schema/index.d.mts +4 -2
  87. package/dist/core/schema/middleware.d.mts +4 -3
  88. package/dist/core/schema/middleware.mjs +41 -1
  89. package/dist/core/schema/number-constraints.mjs +60 -1
  90. package/dist/core/schema/prompt.d.mts +6 -3
  91. package/dist/core/schema/run.d.mts +20 -1
  92. package/dist/core/schema/string-constraints.d.mts +97 -0
  93. package/dist/core/schema/string-constraints.mjs +69 -0
  94. package/dist/core/schema/value-parsers.d.mts +78 -0
  95. package/dist/core/schema/value-parsers.mjs +142 -0
  96. package/dist/core/schema-dsl/runtime.mjs +271 -2
  97. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  98. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  99. package/dist/core/testkit/index.d.mts +0 -31
  100. package/dist/core/testkit/index.mjs +83 -1
  101. package/dist/index.d.mts +11 -6
  102. package/dist/index.mjs +22 -1
  103. package/dist/runtime/adapter.d.mts +38 -2
  104. package/dist/runtime/adapter.mjs +87 -1
  105. package/dist/runtime/auto.d.mts +2 -3
  106. package/dist/runtime/auto.mjs +45 -1
  107. package/dist/runtime/deno.d.mts +24 -5
  108. package/dist/runtime/deno.mjs +262 -2
  109. package/dist/runtime/detect.mjs +45 -1
  110. package/dist/runtime/index.d.mts +3 -4
  111. package/dist/runtime/node.d.mts +8 -2
  112. package/dist/runtime/node.mjs +220 -2
  113. package/dist/runtime/paths.mjs +48 -1
  114. package/dist/runtime.d.mts +4 -4
  115. package/dist/runtime.mjs +6 -1
  116. package/dist/strings.mjs +22 -1
  117. package/dist/testkit.d.mts +1 -0
  118. package/dist/testkit.mjs +5 -1
  119. package/dist/version.d.mts +7 -3
  120. package/dist/version.mjs +7 -1
  121. package/dreamcli.schema.json +36 -7
  122. package/package.json +45 -42
  123. package/dist/runtime/bun.d.mts +0 -28
  124. package/dist/runtime/bun.mjs +0 -1
  125. package/src/core/cli/dispatch.ts +0 -355
  126. package/src/core/cli/help-links.ts +0 -82
  127. package/src/core/cli/index.ts +0 -1614
  128. package/src/core/cli/planner.ts +0 -656
  129. package/src/core/cli/plugin.ts +0 -117
  130. package/src/core/cli/propagate.ts +0 -97
  131. package/src/core/cli/root-help.ts +0 -342
  132. package/src/core/cli/root-surface.ts +0 -87
  133. package/src/core/cli/runtime-preflight.ts +0 -456
  134. package/src/core/completion/index.ts +0 -138
  135. package/src/core/completion/shells/bash.ts +0 -459
  136. package/src/core/completion/shells/fish.ts +0 -259
  137. package/src/core/completion/shells/powershell.ts +0 -439
  138. package/src/core/completion/shells/shared.ts +0 -310
  139. package/src/core/completion/shells/zsh.ts +0 -381
  140. package/src/core/config/index.ts +0 -417
  141. package/src/core/config/package-json.ts +0 -560
  142. package/src/core/errors/index.ts +0 -193
  143. package/src/core/execution/index.ts +0 -265
  144. package/src/core/help/ansi.ts +0 -144
  145. package/src/core/help/index.ts +0 -563
  146. package/src/core/json-schema/index.ts +0 -910
  147. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  148. package/src/core/output/activity.ts +0 -575
  149. package/src/core/output/bind.ts +0 -59
  150. package/src/core/output/contracts.ts +0 -194
  151. package/src/core/output/display-value.ts +0 -48
  152. package/src/core/output/index.ts +0 -704
  153. package/src/core/output/renderers.ts +0 -125
  154. package/src/core/output/writer.ts +0 -46
  155. package/src/core/parse/index.ts +0 -742
  156. package/src/core/prompt/index.ts +0 -623
  157. package/src/core/resolve/args.ts +0 -144
  158. package/src/core/resolve/coerce.ts +0 -500
  159. package/src/core/resolve/config.ts +0 -26
  160. package/src/core/resolve/contracts.ts +0 -135
  161. package/src/core/resolve/errors.ts +0 -227
  162. package/src/core/resolve/flags.ts +0 -269
  163. package/src/core/resolve/index.ts +0 -108
  164. package/src/core/resolve/property.ts +0 -99
  165. package/src/core/schema/activity.ts +0 -240
  166. package/src/core/schema/arg.ts +0 -841
  167. package/src/core/schema/command.ts +0 -1500
  168. package/src/core/schema/flag.ts +0 -917
  169. package/src/core/schema/index.ts +0 -96
  170. package/src/core/schema/middleware.ts +0 -171
  171. package/src/core/schema/number-constraints.ts +0 -153
  172. package/src/core/schema/prompt.ts +0 -171
  173. package/src/core/schema/run.ts +0 -198
  174. package/src/core/schema-dsl/index.ts +0 -109
  175. package/src/core/schema-dsl/parse.ts +0 -262
  176. package/src/core/schema-dsl/runtime.ts +0 -609
  177. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  178. package/src/core/testkit/index.ts +0 -147
  179. package/src/index.ts +0 -181
  180. package/src/runtime/adapter.ts +0 -303
  181. package/src/runtime/auto.ts +0 -86
  182. package/src/runtime/bun.ts +0 -48
  183. package/src/runtime/deno.ts +0 -367
  184. package/src/runtime/detect.ts +0 -105
  185. package/src/runtime/index.ts +0 -21
  186. package/src/runtime/node-builtins.d.ts +0 -27
  187. package/src/runtime/node.ts +0 -289
  188. package/src/runtime/paths.ts +0 -64
  189. package/src/runtime/support.ts +0 -77
  190. package/src/runtime.ts +0 -31
  191. package/src/schema.ts +0 -16
  192. package/src/strings.ts +0 -34
  193. package/src/testkit.ts +0 -25
  194. 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 };