@kjanat/dreamcli 1.0.0 → 2.0.1

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 (217) hide show
  1. package/CHANGELOG.md +63 -6
  2. package/LICENSE +1 -1
  3. package/README.md +296 -164
  4. package/dist/core/cli/dispatch.d.mts +85 -0
  5. package/dist/core/cli/dispatch.mjs +1 -0
  6. package/dist/core/cli/index.d.mts +418 -0
  7. package/dist/core/cli/index.mjs +1 -0
  8. package/dist/core/cli/planner.d.mts +143 -0
  9. package/dist/core/cli/planner.mjs +1 -0
  10. package/dist/core/cli/plugin.d.mts +94 -0
  11. package/dist/core/cli/plugin.mjs +1 -0
  12. package/dist/core/cli/propagate.d.mts +39 -0
  13. package/dist/core/cli/propagate.mjs +1 -0
  14. package/dist/core/cli/root-help.d.mts +28 -0
  15. package/dist/core/cli/root-help.mjs +7 -0
  16. package/dist/core/cli/root-surface.d.mts +42 -0
  17. package/dist/core/cli/root-surface.mjs +1 -0
  18. package/dist/core/cli/runtime-preflight.d.mts +149 -0
  19. package/dist/core/cli/runtime-preflight.mjs +1 -0
  20. package/dist/core/completion/index.d.mts +46 -0
  21. package/dist/core/completion/index.mjs +1 -0
  22. package/dist/core/completion/shells/bash.d.mts +24 -0
  23. package/dist/core/completion/shells/bash.mjs +3 -0
  24. package/dist/core/completion/shells/fish.d.mts +20 -0
  25. package/dist/core/completion/shells/fish.mjs +2 -0
  26. package/dist/core/completion/shells/powershell.d.mts +14 -0
  27. package/dist/core/completion/shells/powershell.mjs +2 -0
  28. package/dist/core/completion/shells/shared.d.mts +139 -0
  29. package/dist/core/completion/shells/shared.mjs +1 -0
  30. package/dist/core/completion/shells/zsh.d.mts +24 -0
  31. package/dist/core/completion/shells/zsh.mjs +2 -0
  32. package/dist/core/config/index.d.mts +161 -0
  33. package/dist/core/config/index.mjs +1 -0
  34. package/dist/core/config/package-json.d.mts +68 -0
  35. package/dist/core/config/package-json.mjs +1 -0
  36. package/dist/core/errors/index.d.mts +126 -0
  37. package/dist/core/errors/index.mjs +1 -0
  38. package/dist/core/execution/index.d.mts +49 -0
  39. package/dist/core/execution/index.mjs +1 -0
  40. package/dist/core/help/index.d.mts +49 -0
  41. package/dist/core/help/index.mjs +8 -0
  42. package/dist/core/json-schema/index.d.mts +109 -0
  43. package/dist/core/json-schema/index.mjs +55 -0
  44. package/dist/core/json-schema/meta-descriptions.generated.d.mts +185 -0
  45. package/dist/core/json-schema/meta-descriptions.generated.mjs +28 -0
  46. package/dist/core/output/activity.d.mts +194 -0
  47. package/dist/core/output/activity.mjs +1 -0
  48. package/dist/core/output/contracts.d.mts +88 -0
  49. package/dist/core/output/contracts.mjs +1 -0
  50. package/dist/core/output/display-value.d.mts +19 -0
  51. package/dist/core/output/display-value.mjs +1 -0
  52. package/dist/core/output/index.d.mts +280 -0
  53. package/dist/core/output/index.mjs +2 -0
  54. package/dist/core/output/renderers.d.mts +46 -0
  55. package/dist/core/output/renderers.mjs +1 -0
  56. package/dist/core/output/writer.d.mts +40 -0
  57. package/dist/core/output/writer.mjs +1 -0
  58. package/dist/core/parse/index.d.mts +79 -0
  59. package/dist/core/parse/index.mjs +1 -0
  60. package/dist/core/prompt/index.d.mts +205 -0
  61. package/dist/core/prompt/index.mjs +6 -0
  62. package/dist/core/resolve/args.d.mts +8 -0
  63. package/dist/core/resolve/args.mjs +1 -0
  64. package/dist/core/resolve/coerce.d.mts +22 -0
  65. package/dist/core/resolve/coerce.mjs +1 -0
  66. package/dist/core/resolve/config.d.mts +10 -0
  67. package/dist/core/resolve/config.mjs +1 -0
  68. package/dist/core/resolve/contracts.d.mts +112 -0
  69. package/dist/core/resolve/errors.d.mts +11 -0
  70. package/dist/core/resolve/errors.mjs +2 -0
  71. package/dist/core/resolve/flags.d.mts +10 -0
  72. package/dist/core/resolve/flags.mjs +1 -0
  73. package/dist/core/resolve/index.d.mts +42 -0
  74. package/dist/core/resolve/index.mjs +1 -0
  75. package/dist/core/resolve/property.d.mts +47 -0
  76. package/dist/core/resolve/property.mjs +1 -0
  77. package/dist/core/schema/activity.d.mts +169 -0
  78. package/dist/core/schema/arg.d.mts +559 -0
  79. package/dist/core/schema/arg.mjs +1 -0
  80. package/dist/core/schema/command.d.mts +960 -0
  81. package/dist/core/schema/command.mjs +1 -0
  82. package/dist/core/schema/flag.d.mts +491 -0
  83. package/dist/core/schema/flag.mjs +1 -0
  84. package/dist/core/schema/index.d.mts +8 -0
  85. package/dist/core/schema/middleware.d.mts +122 -0
  86. package/dist/core/schema/middleware.mjs +1 -0
  87. package/dist/core/schema/prompt.d.mts +117 -0
  88. package/dist/core/schema/run.d.mts +171 -0
  89. package/dist/core/schema-dsl/runtime.d.mts +144 -0
  90. package/dist/core/schema-dsl/runtime.mjs +2 -0
  91. package/dist/core/schema-dsl/to-json-schema.d.mts +30 -0
  92. package/dist/core/schema-dsl/to-json-schema.mjs +1 -0
  93. package/dist/core/testkit/index.d.mts +54 -0
  94. package/dist/core/testkit/index.mjs +1 -0
  95. package/dist/index.d.mts +28 -920
  96. package/dist/index.mjs +1 -10
  97. package/dist/runtime/adapter.d.mts +212 -0
  98. package/dist/{adapter-B37d9oia.mjs → runtime/adapter.mjs} +1 -1
  99. package/dist/runtime/auto.d.mts +26 -0
  100. package/dist/runtime/auto.mjs +1 -0
  101. package/dist/runtime/bun.d.mts +28 -0
  102. package/dist/runtime/bun.mjs +1 -0
  103. package/dist/runtime/deno.d.mts +76 -0
  104. package/dist/runtime/deno.mjs +2 -0
  105. package/dist/runtime/detect.d.mts +86 -0
  106. package/dist/runtime/detect.mjs +1 -0
  107. package/dist/runtime/index.d.mts +7 -0
  108. package/dist/runtime/node.d.mts +65 -0
  109. package/dist/runtime/node.mjs +2 -0
  110. package/dist/runtime/paths.d.mts +31 -0
  111. package/dist/runtime/paths.mjs +1 -0
  112. package/dist/runtime/support.d.mts +42 -0
  113. package/dist/runtime/support.mjs +1 -0
  114. package/dist/runtime.d.mts +6 -252
  115. package/dist/runtime.mjs +1 -1
  116. package/dist/testkit.d.mts +5 -24
  117. package/dist/testkit.mjs +1 -1
  118. package/dist/version.d.mts +16 -0
  119. package/dist/version.mjs +1 -0
  120. package/dreamcli.schema.json +338 -0
  121. package/examples/basic.ts +2 -2
  122. package/examples/gh/package.json +7 -11
  123. package/examples/gh/src/commands/auth.ts +2 -2
  124. package/examples/gh/src/commands/issue.ts +4 -4
  125. package/examples/gh/src/commands/pr.ts +4 -4
  126. package/examples/gh/src/docs.ts +11 -0
  127. package/examples/gh/src/lib/auth.ts +1 -1
  128. package/examples/gh/src/main.test.ts +6 -5
  129. package/examples/gh/src/main.ts +8 -6
  130. package/examples/interactive.ts +3 -3
  131. package/examples/json-mode.ts +4 -6
  132. package/examples/middleware.ts +3 -3
  133. package/examples/multi-command.ts +3 -3
  134. package/examples/spinner-progress.ts +5 -5
  135. package/examples/testing.ts +8 -6
  136. package/package.json +70 -44
  137. package/src/core/cli/dispatch.ts +4 -0
  138. package/src/core/cli/index.ts +185 -632
  139. package/src/core/cli/planner.ts +413 -0
  140. package/src/core/cli/plugin.ts +7 -1
  141. package/src/core/cli/propagate.ts +1 -1
  142. package/src/core/cli/runtime-preflight.ts +409 -0
  143. package/src/core/completion/index.ts +15 -9
  144. package/src/core/completion/shells/bash.ts +6 -3
  145. package/src/core/completion/shells/fish.ts +245 -10
  146. package/src/core/completion/shells/powershell.ts +390 -9
  147. package/src/core/completion/shells/shared.ts +4 -4
  148. package/src/core/completion/shells/zsh.ts +12 -7
  149. package/src/core/config/index.ts +7 -4
  150. package/src/core/config/package-json.ts +6 -2
  151. package/src/core/errors/index.ts +23 -8
  152. package/src/core/execution/index.ts +270 -0
  153. package/src/core/help/index.ts +13 -15
  154. package/src/core/json-schema/index.ts +193 -7
  155. package/src/core/json-schema/meta-descriptions.generated.ts +202 -0
  156. package/src/core/output/contracts.ts +194 -0
  157. package/src/core/output/index.ts +47 -82
  158. package/src/core/output/renderers.ts +125 -0
  159. package/src/core/parse/index.ts +39 -21
  160. package/src/core/prompt/index.ts +44 -27
  161. package/src/core/resolve/args.ts +144 -0
  162. package/src/core/resolve/coerce.ts +432 -0
  163. package/src/core/resolve/config.ts +26 -0
  164. package/src/core/resolve/contracts.ts +135 -0
  165. package/src/core/resolve/errors.ts +227 -0
  166. package/src/core/resolve/flags.ts +205 -0
  167. package/src/core/resolve/index.ts +41 -1264
  168. package/src/core/resolve/property.ts +99 -0
  169. package/src/core/schema/activity.ts +3 -0
  170. package/src/core/schema/arg.ts +26 -14
  171. package/src/core/schema/command.ts +265 -38
  172. package/src/core/schema/flag.ts +120 -15
  173. package/src/core/schema/index.ts +11 -2
  174. package/src/core/schema/middleware.ts +6 -6
  175. package/src/core/schema/prompt.ts +9 -1
  176. package/src/core/schema/run.ts +25 -17
  177. package/src/core/schema-dsl/index.ts +109 -0
  178. package/src/core/schema-dsl/parse.ts +262 -0
  179. package/src/core/schema-dsl/runtime.ts +609 -0
  180. package/src/core/schema-dsl/to-json-schema.ts +102 -0
  181. package/src/core/testkit/index.ts +55 -297
  182. package/src/index.ts +10 -4
  183. package/src/runtime/adapter.ts +13 -10
  184. package/src/runtime/auto.ts +3 -3
  185. package/src/runtime/bun.ts +4 -4
  186. package/src/runtime/deno.ts +43 -29
  187. package/src/runtime/detect.ts +4 -1
  188. package/src/runtime/index.ts +1 -1
  189. package/src/runtime/node.ts +43 -21
  190. package/src/runtime/paths.ts +9 -3
  191. package/src/runtime/support.ts +20 -4
  192. package/src/runtime.ts +1 -1
  193. package/src/testkit.ts +10 -8
  194. package/dist/adapter-CCSh5juX.cjs +0 -1
  195. package/dist/adapter-DIwO-q7K.d.mts +0 -3447
  196. package/dist/adapter-DQnxxLiE.d.cts +0 -3447
  197. package/dist/auto-5cjZaF9V.mjs +0 -3
  198. package/dist/auto-B0eSgoDw.cjs +0 -3
  199. package/dist/index.cjs +0 -10
  200. package/dist/index.d.cts +0 -920
  201. package/dist/runtime.cjs +0 -1
  202. package/dist/runtime.d.cts +0 -253
  203. package/dist/testkit-CEDYPvhF.mjs +0 -14
  204. package/dist/testkit-ClIKijxC.cjs +0 -14
  205. package/dist/testkit.cjs +0 -1
  206. package/dist/testkit.d.cts +0 -25
  207. package/examples/gh/tsconfig.json +0 -37
  208. package/examples/tsconfig.json +0 -17
  209. package/src/core/cli/AGENTS.md +0 -72
  210. package/src/core/completion/AGENTS.md +0 -72
  211. package/src/core/completion/completion-test-helpers.ts +0 -48
  212. package/src/core/output/AGENTS.md +0 -69
  213. package/src/core/resolve/AGENTS.md +0 -69
  214. package/src/core/schema/AGENTS.md +0 -61
  215. package/src/core/testkit/AGENTS.md +0 -55
  216. package/src/runtime/AGENTS.md +0 -74
  217. package/src/runtime/test-helpers.ts +0 -40
@@ -1,24 +1,259 @@
1
1
  /**
2
- * Fish completion script generator (not yet implemented).
2
+ * Fish completion script generator.
3
+ *
4
+ * Produces a self-contained fish script with:
5
+ * - A command-path helper for nested command dispatch
6
+ * - Per-path `complete` entries for visible commands and aliases
7
+ * - Per-path flag definitions including propagated ancestor flags
8
+ * - Enum value completions for option arguments
9
+ * - Root-surface support for default-command completion policy
3
10
  *
4
11
  * @module dreamcli/core/completion/shells/fish
5
12
  * @internal
6
13
  */
7
14
 
8
15
  import type { CLISchema } from '#internals/core/cli/index.ts';
9
- import { CLIError } from '#internals/core/errors/index.ts';
10
- import type { CompletionOptions } from './shared.ts';
16
+ import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
17
+ import type { FlagSchema } from '#internals/core/schema/index.ts';
18
+ import type { CommandNode, CompletionOptions, RootCompletionSurface } from './shared.ts';
19
+ import {
20
+ quoteShellArg,
21
+ resolveRootCompletionSurface,
22
+ sanitizeShellIdentifier,
23
+ versionTag,
24
+ walkCommandTree,
25
+ } from './shared.ts';
11
26
 
12
27
  /**
13
- * Generates a fish completion script for the CLI.
28
+ * Generate a fish completion script for the CLI.
29
+ *
30
+ * @param schema - The CLI schema.
31
+ * @param options - Optional generator configuration.
32
+ * @returns A complete fish completion script.
14
33
  *
15
- * @throws {CLIError} Always — fish completions are not yet implemented.
34
+ * @example
35
+ * ```ts
36
+ * const script = generateFishCompletion(app.schema);
37
+ * // install with: mycli completions fish > ~/.config/fish/completions/mycli.fish
38
+ * ```
16
39
  */
17
- function generateFishCompletion(_schema: CLISchema, _options?: CompletionOptions): string {
18
- throw new CLIError("Shell completion for 'fish' is not yet supported", {
19
- code: 'UNSUPPORTED_OPERATION',
20
- suggest: 'Supported shells: bash, zsh',
21
- });
40
+ function generateFishCompletion(schema: CLISchema, options?: CompletionOptions): string {
41
+ const prefix = options?.functionPrefix ?? schema.name;
42
+ const helperPrefix = `__${sanitizeShellIdentifier(prefix)}_completions`;
43
+ const pathFuncName = `${helperPrefix}_path`;
44
+ const pathIsFuncName = `${helperPrefix}_path_is`;
45
+ const rootSurface = resolveRootCompletionSurface(schema, options?.rootMode);
46
+ const visibleCommands = rootSurface.visibleCommands;
47
+ const nodes = walkCommandTree(visibleCommands);
48
+ const commandName = quoteShellArg(schema.name);
49
+
50
+ const lines: string[] = [];
51
+
52
+ lines.push(`# Fish completion for ${schema.name}`);
53
+ lines.push(`# Generated by ${versionTag()}`);
54
+ lines.push('#');
55
+ lines.push(`# Usage: source (${schema.name} completions fish | psub)`);
56
+ lines.push('#');
57
+ lines.push('# Install permanently:');
58
+ lines.push(
59
+ `# ${schema.name} completions fish > ~/.config/fish/completions/${schema.name}.fish`,
60
+ );
61
+ lines.push('');
62
+ lines.push(`complete -c ${commandName} -f`);
63
+ lines.push('');
64
+
65
+ emitFishPathHelpers(lines, pathFuncName, pathIsFuncName, visibleCommands, nodes, rootSurface);
66
+
67
+ appendFishCommandCompletions(lines, commandName, pathIsFuncName, '', visibleCommands);
68
+ appendFishFlagCompletions(lines, commandName, pathIsFuncName, '', rootSurface.rootFlags);
69
+ if (rootSurface.includeDefaultFlags) {
70
+ appendFishFlagCompletions(lines, commandName, pathIsFuncName, '', rootSurface.defaultFlags);
71
+ }
72
+
73
+ for (const node of nodes) {
74
+ const path = node.path.join(' ');
75
+ appendFishCommandCompletions(lines, commandName, pathIsFuncName, path, node.children);
76
+ appendFishFlagCompletions(lines, commandName, pathIsFuncName, path, node.mergedFlags);
77
+ }
78
+
79
+ return lines.join('\n');
80
+ }
81
+
82
+ function emitFishPathHelpers(
83
+ lines: string[],
84
+ pathFuncName: string,
85
+ pathIsFuncName: string,
86
+ visibleCommands: readonly {
87
+ readonly name: string;
88
+ readonly aliases: readonly string[];
89
+ }[],
90
+ nodes: readonly CommandNode[],
91
+ rootSurface: RootCompletionSurface,
92
+ ): void {
93
+ const valueFlags = collectFishValueFlagPatterns(nodes, rootSurface);
94
+
95
+ lines.push(`function ${pathFuncName}`);
96
+ lines.push('\tset -l words (commandline -opc)');
97
+ lines.push('\tif test (count $words) -gt 0');
98
+ lines.push('\t\tset -e words[1]');
99
+ lines.push('\tend');
100
+ lines.push("\tset -l subcmd_path ''");
101
+ lines.push('\tset -l expect_value 0');
102
+ lines.push('\tfor word in $words');
103
+ lines.push('\t\tif test $expect_value -eq 1');
104
+ lines.push('\t\t\tset expect_value 0');
105
+ lines.push('\t\t\tcontinue');
106
+ lines.push('\t\tend');
107
+ lines.push('\t\tswitch $word');
108
+ lines.push("\t\t\tcase '--'");
109
+ lines.push('\t\t\t\tbreak');
110
+ if (valueFlags.exact.length > 0) {
111
+ lines.push(`\t\t\tcase ${valueFlags.exact.map(quoteShellArg).join(' ')}`);
112
+ lines.push('\t\t\t\tset expect_value 1');
113
+ lines.push('\t\t\t\tcontinue');
114
+ }
115
+ if (valueFlags.prefix.length > 0) {
116
+ lines.push(`\t\t\tcase ${valueFlags.prefix.map(quoteShellArg).join(' ')}`);
117
+ lines.push('\t\t\t\tcontinue');
118
+ }
119
+ lines.push("\t\t\tcase '-*'");
120
+ lines.push('\t\t\t\tcontinue');
121
+ lines.push('\t\tend');
122
+ lines.push('\t\tswitch "$subcmd_path|$word"');
123
+
124
+ for (const command of visibleCommands) {
125
+ for (const name of [command.name, ...command.aliases]) {
126
+ lines.push(`\t\t\tcase ${quoteShellArg(`|${name}`)}`);
127
+ lines.push(`\t\t\t\tset subcmd_path ${quoteShellArg(command.name)}`);
128
+ }
129
+ }
130
+
131
+ for (const node of nodes) {
132
+ for (const child of node.children) {
133
+ for (const name of [child.name, ...child.aliases]) {
134
+ lines.push(`\t\t\tcase ${quoteShellArg(`${node.path.join(' ')}|${name}`)}`);
135
+ lines.push(
136
+ `\t\t\t\tset subcmd_path ${quoteShellArg(`${node.path.join(' ')} ${child.name}`)}`,
137
+ );
138
+ }
139
+ }
140
+ }
141
+
142
+ lines.push("\t\t\tcase '*'");
143
+ lines.push('\t\t\t\tbreak');
144
+ lines.push('\t\tend');
145
+ lines.push('\tend');
146
+ lines.push('\tprintf \'%s\\n\' "$subcmd_path"');
147
+ lines.push('end');
148
+ lines.push('');
149
+ lines.push(`function ${pathIsFuncName}`);
150
+ lines.push('\tset -l expected "$argv[1]"');
151
+ lines.push(`\ttest (${pathFuncName}) = "$expected"`);
152
+ lines.push('end');
153
+ lines.push('');
154
+ }
155
+
156
+ function appendFishCommandCompletions(
157
+ lines: string[],
158
+ commandName: string,
159
+ pathIsFuncName: string,
160
+ path: string,
161
+ commands: ReadonlyArray<{
162
+ readonly name: string;
163
+ readonly aliases: readonly string[];
164
+ readonly description: string | undefined;
165
+ }>,
166
+ ): void {
167
+ const condition = buildFishCondition(pathIsFuncName, path);
168
+ for (const command of commands) {
169
+ const description = quoteShellArg(command.description ?? command.name);
170
+ for (const name of [command.name, ...command.aliases]) {
171
+ lines.push(
172
+ `complete -c ${commandName} -n "${condition}" -a ${quoteShellArg(name)} -d ${description}`,
173
+ );
174
+ }
175
+ }
176
+ if (commands.length > 0) {
177
+ lines.push('');
178
+ }
179
+ }
180
+
181
+ function appendFishFlagCompletions(
182
+ lines: string[],
183
+ commandName: string,
184
+ pathIsFuncName: string,
185
+ path: string,
186
+ flags: Readonly<Record<string, FlagSchema>>,
187
+ ): void {
188
+ const condition = buildFishCondition(pathIsFuncName, path);
189
+ for (const [name, schema] of Object.entries(flags)) {
190
+ const parts = [`complete -c ${commandName}`, `-n "${condition}"`];
191
+ for (const alias of getFlagAliasNames(schema, { kind: 'short' })) {
192
+ parts.push(`-s ${quoteShellArg(alias)}`);
193
+ }
194
+ parts.push(`-l ${quoteShellArg(name)}`);
195
+ for (const alias of getFlagAliasNames(schema, { kind: 'long' })) {
196
+ parts.push(`-l ${quoteShellArg(alias)}`);
197
+ }
198
+ parts.push(`-d ${quoteShellArg(schema.description ?? name)}`);
199
+
200
+ if (schema.kind !== 'boolean') {
201
+ parts.push('-r', '-f');
202
+ }
203
+ if (schema.kind === 'enum' && schema.enumValues !== undefined) {
204
+ for (const enumValue of schema.enumValues) {
205
+ lines.push([...parts, `-a ${quoteShellArg(enumValue)}`].join(' '));
206
+ }
207
+ continue;
208
+ }
209
+
210
+ lines.push(parts.join(' '));
211
+ }
212
+ if (Object.keys(flags).length > 0) {
213
+ lines.push('');
214
+ }
215
+ }
216
+
217
+ function collectFishValueFlagPatterns(
218
+ nodes: readonly CommandNode[],
219
+ rootSurface: RootCompletionSurface,
220
+ ): {
221
+ readonly exact: readonly string[];
222
+ readonly prefix: readonly string[];
223
+ } {
224
+ const exact = new Set<string>();
225
+ const prefix = new Set<string>();
226
+ const flagSets: ReadonlyArray<Readonly<Record<string, FlagSchema>>> = [
227
+ rootSurface.rootFlags,
228
+ ...(rootSurface.includeDefaultFlags ? [rootSurface.defaultFlags] : []),
229
+ ...nodes.map((node) => node.mergedFlags),
230
+ ];
231
+
232
+ for (const flags of flagSets) {
233
+ for (const [name, schema] of Object.entries(flags)) {
234
+ if (schema.kind === 'boolean') continue;
235
+
236
+ exact.add(`--${name}`);
237
+ prefix.add(`--${name}=*`);
238
+ for (const alias of getFlagAliasNames(schema, { kind: 'short', includeHidden: true })) {
239
+ exact.add(`-${alias}`);
240
+ prefix.add(`-${alias}*`);
241
+ }
242
+ for (const alias of getFlagAliasNames(schema, { kind: 'long', includeHidden: true })) {
243
+ exact.add(`--${alias}`);
244
+ prefix.add(`--${alias}=*`);
245
+ }
246
+ }
247
+ }
248
+
249
+ return {
250
+ exact: [...exact],
251
+ prefix: [...prefix],
252
+ };
253
+ }
254
+
255
+ function buildFishCondition(pathIsFuncName: string, path: string): string {
256
+ return `${pathIsFuncName} ${quoteShellArg(path)}`;
22
257
  }
23
258
 
24
259
  export { generateFishCompletion };
@@ -1,24 +1,405 @@
1
1
  /**
2
- * PowerShell completion script generator (not yet implemented).
2
+ * PowerShell completion script generator.
3
+ *
4
+ * Produces a self-contained PowerShell script with:
5
+ * - A native `Register-ArgumentCompleter` registration
6
+ * - Precomputed command-path metadata for nested dispatch
7
+ * - Per-path command and flag entries including propagated ancestor flags
8
+ * - Enum value completions for option arguments
9
+ * - Root-surface support for default-command completion policy
3
10
  *
4
11
  * @module dreamcli/core/completion/shells/powershell
5
12
  * @internal
6
13
  */
7
14
 
8
15
  import type { CLISchema } from '#internals/core/cli/index.ts';
9
- import { CLIError } from '#internals/core/errors/index.ts';
10
- import type { CompletionOptions } from './shared.ts';
16
+ import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
17
+ import type { FlagSchema } from '#internals/core/schema/index.ts';
18
+ import type { CommandNode, CompletionOptions, RootCompletionSurface } from './shared.ts';
19
+ import {
20
+ resolveRootCompletionSurface,
21
+ sanitizeShellIdentifier,
22
+ versionTag,
23
+ walkCommandTree,
24
+ } from './shared.ts';
11
25
 
12
26
  /**
13
- * Generates a PowerShell completion script for the CLI.
27
+ * Generate a PowerShell completion script for the CLI.
14
28
  *
15
- * @throws {CLIError} Always — PowerShell completions are not yet implemented.
29
+ * @param schema - The CLI schema.
30
+ * @param options - Optional generator configuration.
31
+ * @returns A complete PowerShell completion script.
16
32
  */
17
- function generatePowerShellCompletion(_schema: CLISchema, _options?: CompletionOptions): string {
18
- throw new CLIError("Shell completion for 'powershell' is not yet supported", {
19
- code: 'UNSUPPORTED_OPERATION',
20
- suggest: 'Supported shells: bash, zsh',
33
+ function generatePowerShellCompletion(schema: CLISchema, options?: CompletionOptions): string {
34
+ const prefix = options?.functionPrefix ?? schema.name;
35
+ const helperPrefix = `__${sanitizeShellIdentifier(prefix)}_completions`;
36
+ const dataVarName = `${helperPrefix}_paths`;
37
+ const rootSurface = resolveRootCompletionSurface(schema, options?.rootMode);
38
+ const visibleCommands = rootSurface.visibleCommands;
39
+ const nodes = walkCommandTree(visibleCommands);
40
+
41
+ const lines: string[] = [];
42
+
43
+ lines.push(`# PowerShell completion for ${schema.name}`);
44
+ lines.push(`# Generated by ${versionTag()}`);
45
+ lines.push('#');
46
+ lines.push('# Install for the current session:');
47
+ lines.push(`# ${schema.name} completions powershell | Invoke-Expression`);
48
+ lines.push('#');
49
+ lines.push('# Install permanently:');
50
+ lines.push(`# ${schema.name} completions powershell > $PROFILE.CurrentUserCurrentHost`);
51
+ lines.push('');
52
+ lines.push('using namespace System.Management.Automation');
53
+ lines.push('using namespace System.Management.Automation.Language');
54
+ lines.push('');
55
+
56
+ emitPowerShellPathTable(lines, dataVarName, rootSurface, nodes);
57
+ lines.push('');
58
+ emitPowerShellHelpers(lines, helperPrefix, dataVarName);
59
+ lines.push('');
60
+ lines.push(
61
+ `Register-ArgumentCompleter -Native -CommandName ${quotePowerShellString(schema.name)} -ScriptBlock {`,
62
+ );
63
+ lines.push('\tparam($wordToComplete, $commandAst, $cursorPosition)');
64
+ lines.push(
65
+ `\t$state = ${helperPrefix}_GetState -CommandAst $commandAst -CursorPosition $cursorPosition`,
66
+ );
67
+ lines.push('\tif ($null -eq $state.PathData) {');
68
+ lines.push('\t\treturn');
69
+ lines.push('\t}');
70
+ lines.push('');
71
+ lines.push('\t$results = [System.Collections.Generic.List[CompletionResult]]::new()');
72
+ lines.push(
73
+ `\t$wordPrefix = if ([string]::IsNullOrEmpty($wordToComplete)) { '' } else { $wordToComplete }`,
74
+ );
75
+ lines.push('');
76
+ lines.push('\tif ($state.ExpectingValue) {');
77
+ lines.push(
78
+ `\t\t${helperPrefix}_AddEnumResults -Results $results -Flag $state.ValueFlag -WordToComplete $wordPrefix`,
79
+ );
80
+ lines.push('\t\treturn $results');
81
+ lines.push('\t}');
82
+ lines.push('');
83
+ lines.push(
84
+ `\t$inlineValue = ${helperPrefix}_ResolveInlineValueCompletion -PathData $state.PathData -WordToComplete $wordPrefix`,
85
+ );
86
+ lines.push('\tif ($null -ne $inlineValue) {');
87
+ lines.push(
88
+ `\t\t${helperPrefix}_AddInlineEnumResults -Results $results -InlineValue $inlineValue -WordToComplete $wordPrefix`,
89
+ );
90
+ lines.push('\t\treturn $results');
91
+ lines.push('\t}');
92
+ lines.push('');
93
+ lines.push("\tif ($wordPrefix.StartsWith('-')) {");
94
+ lines.push(
95
+ `\t\t${helperPrefix}_AddFlagResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`,
96
+ );
97
+ lines.push('\t\treturn $results');
98
+ lines.push('\t}');
99
+ lines.push('');
100
+ lines.push(
101
+ `\t${helperPrefix}_AddCommandResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`,
102
+ );
103
+ lines.push(
104
+ `\t${helperPrefix}_AddFlagResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`,
105
+ );
106
+ lines.push('\treturn $results');
107
+ lines.push('}');
108
+
109
+ return lines.join('\n');
110
+ }
111
+
112
+ function emitPowerShellPathTable(
113
+ lines: string[],
114
+ dataVarName: string,
115
+ rootSurface: RootCompletionSurface,
116
+ nodes: readonly CommandNode[],
117
+ ): void {
118
+ lines.push(`$script:${dataVarName} = @{`);
119
+ appendPowerShellPathEntry(lines, '', rootSurface.visibleCommands, {
120
+ ...rootSurface.rootFlags,
121
+ ...(rootSurface.includeDefaultFlags ? rootSurface.defaultFlags : {}),
21
122
  });
123
+
124
+ for (const node of nodes) {
125
+ appendPowerShellPathEntry(lines, node.path.join(' '), node.children, node.mergedFlags);
126
+ }
127
+
128
+ lines.push('}');
129
+ }
130
+
131
+ function appendPowerShellPathEntry(
132
+ lines: string[],
133
+ path: string,
134
+ commands: ReadonlyArray<{
135
+ readonly name: string;
136
+ readonly aliases: readonly string[];
137
+ readonly description: string | undefined;
138
+ }>,
139
+ flags: Readonly<Record<string, FlagSchema>>,
140
+ ): void {
141
+ lines.push(`\t${quotePowerShellString(path)} = @{`);
142
+ lines.push('\t\tCommands = @(');
143
+ for (const command of commands) {
144
+ lines.push('\t\t\t@{');
145
+ lines.push(`\t\t\t\tCanonicalName = ${quotePowerShellString(command.name)}`);
146
+ lines.push(`\t\t\t\tNames = ${formatPowerShellArray([command.name, ...command.aliases])}`);
147
+ lines.push(
148
+ `\t\t\t\tDescription = ${quotePowerShellString(command.description ?? command.name)}`,
149
+ );
150
+ lines.push('\t\t\t}');
151
+ }
152
+ lines.push('\t\t)');
153
+ lines.push('\t\tFlags = @(');
154
+ for (const [name, schema] of Object.entries(flags)) {
155
+ const forms = dedupeValues([
156
+ `--${name}`,
157
+ ...getFlagAliasNames(schema, { kind: 'short' }).map((alias) => `-${alias}`),
158
+ ...getFlagAliasNames(schema, { kind: 'long' }).map((alias) => `--${alias}`),
159
+ ]);
160
+ const parseForms = dedupeValues([
161
+ `--${name}`,
162
+ ...getFlagAliasNames(schema, { kind: 'short', includeHidden: true }).map(
163
+ (alias) => `-${alias}`,
164
+ ),
165
+ ...getFlagAliasNames(schema, { kind: 'long', includeHidden: true }).map(
166
+ (alias) => `--${alias}`,
167
+ ),
168
+ ]);
169
+ lines.push('\t\t\t@{');
170
+ lines.push(`\t\t\t\tCanonicalName = ${quotePowerShellString(name)}`);
171
+ lines.push(`\t\t\t\tForms = ${formatPowerShellArray(forms)}`);
172
+ lines.push(`\t\t\t\tParseForms = ${formatPowerShellArray(parseForms)}`);
173
+ lines.push(`\t\t\t\tRequiresValue = ${schema.kind === 'boolean' ? '$false' : '$true'}`);
174
+ lines.push(`\t\t\t\tDescription = ${quotePowerShellString(schema.description ?? name)}`);
175
+ lines.push(`\t\t\t\tEnumValues = ${formatPowerShellArray(schema.enumValues ?? [])}`);
176
+ lines.push('\t\t\t}');
177
+ }
178
+ lines.push('\t\t)');
179
+ lines.push('\t}');
180
+ }
181
+
182
+ function emitPowerShellHelpers(lines: string[], helperPrefix: string, dataVarName: string): void {
183
+ lines.push(`function ${helperPrefix}_UnquoteToken {`);
184
+ lines.push('\tparam([string]$TokenText)');
185
+ lines.push('\tif ($TokenText.Length -lt 2) {');
186
+ lines.push('\t\treturn $TokenText');
187
+ lines.push('\t}');
188
+ lines.push('');
189
+ lines.push('\tif (($TokenText.StartsWith("\'") -and $TokenText.EndsWith("\'")) -or');
190
+ lines.push("\t\t($TokenText.StartsWith('\"') -and $TokenText.EndsWith('\"'))) {");
191
+ lines.push('\t\treturn $TokenText.Substring(1, $TokenText.Length - 2)');
192
+ lines.push('\t}');
193
+ lines.push('');
194
+ lines.push('\treturn $TokenText');
195
+ lines.push('}');
196
+ lines.push('');
197
+ lines.push(`function ${helperPrefix}_FindCommand {`);
198
+ lines.push('\tparam($PathData, [string]$Token)');
199
+ lines.push('\tforeach ($command in $PathData.Commands) {');
200
+ lines.push('\t\tforeach ($name in $command.Names) {');
201
+ lines.push('\t\t\tif ($name -eq $Token) {');
202
+ lines.push('\t\t\t\treturn $command');
203
+ lines.push('\t\t\t}');
204
+ lines.push('\t\t}');
205
+ lines.push('\t}');
206
+ lines.push('\treturn $null');
207
+ lines.push('}');
208
+ lines.push('');
209
+ lines.push(`function ${helperPrefix}_ResolveFlagToken {`);
210
+ lines.push('\tparam($PathData, [string]$Token)');
211
+ lines.push('\tforeach ($flag in $PathData.Flags) {');
212
+ lines.push('\t\tforeach ($form in $flag.ParseForms) {');
213
+ lines.push('\t\t\tif ($Token -eq $form) {');
214
+ lines.push('\t\t\t\treturn @{ Flag = $flag; InlinePrefix = $null }');
215
+ lines.push('\t\t\t}');
216
+ lines.push('');
217
+ lines.push('\t\t\tif (-not $flag.RequiresValue) {');
218
+ lines.push('\t\t\t\tcontinue');
219
+ lines.push('\t\t\t}');
220
+ lines.push('');
221
+ lines.push('\t\t\tif ($form.StartsWith(\'--\') -and $Token.StartsWith("$form=")) {');
222
+ lines.push('\t\t\t\treturn @{ Flag = $flag; InlinePrefix = "$form=" }');
223
+ lines.push('\t\t\t}');
224
+ lines.push('');
225
+ lines.push(
226
+ "\t\t\tif ($form.StartsWith('-') -and -not $form.StartsWith('--') -and $Token.StartsWith($form) -and $Token.Length -gt $form.Length) {",
227
+ );
228
+ lines.push('\t\t\t\treturn @{ Flag = $flag; InlinePrefix = $form }');
229
+ lines.push('\t\t\t}');
230
+ lines.push('\t\t}');
231
+ lines.push('\t}');
232
+ lines.push('\treturn $null');
233
+ lines.push('}');
234
+ lines.push('');
235
+ lines.push(`function ${helperPrefix}_GetState {`);
236
+ lines.push('\tparam([CommandAst]$CommandAst, [int]$CursorPosition)');
237
+ lines.push(`\t$pathData = $script:${dataVarName}[${quotePowerShellString('')}]`);
238
+ lines.push('\t$path = ""');
239
+ lines.push('\t$expectingValue = $false');
240
+ lines.push('\t$valueFlag = $null');
241
+ lines.push('\t$tokens = [System.Collections.Generic.List[string]]::new()');
242
+ lines.push('');
243
+ lines.push('\tforeach ($element in $CommandAst.CommandElements | Select-Object -Skip 1) {');
244
+ lines.push('\t\tif ($element.Extent.EndOffset -gt $CursorPosition) {');
245
+ lines.push('\t\t\tbreak');
246
+ lines.push('\t\t}');
247
+ lines.push(`\t\t$tokenText = ${helperPrefix}_UnquoteToken $element.Extent.Text`);
248
+ lines.push('\t\t[void]$tokens.Add($tokenText)');
249
+ lines.push('\t}');
250
+ lines.push('');
251
+ lines.push('\tforeach ($token in $tokens) {');
252
+ lines.push('\t\tif ($expectingValue) {');
253
+ lines.push('\t\t\t$expectingValue = $false');
254
+ lines.push('\t\t\t$valueFlag = $null');
255
+ lines.push('\t\t\tcontinue');
256
+ lines.push('\t\t}');
257
+ lines.push('');
258
+ lines.push("\t\tif ($token -eq '--') {");
259
+ lines.push('\t\t\tbreak');
260
+ lines.push('\t\t}');
261
+ lines.push('');
262
+ lines.push(`\t\t$flagMatch = ${helperPrefix}_ResolveFlagToken -PathData $pathData -Token $token`);
263
+ lines.push('\t\tif ($null -ne $flagMatch) {');
264
+ lines.push('\t\t\tif ($flagMatch.InlinePrefix -eq $null -and $flagMatch.Flag.RequiresValue) {');
265
+ lines.push('\t\t\t\t$expectingValue = $true');
266
+ lines.push('\t\t\t\t$valueFlag = $flagMatch.Flag');
267
+ lines.push('\t\t\t}');
268
+ lines.push('\t\t\tcontinue');
269
+ lines.push('\t\t}');
270
+ lines.push('');
271
+ lines.push("\t\tif ($token.StartsWith('-')) {");
272
+ lines.push('\t\t\tcontinue');
273
+ lines.push('\t\t}');
274
+ lines.push('');
275
+ lines.push(`\t\t$command = ${helperPrefix}_FindCommand -PathData $pathData -Token $token`);
276
+ lines.push('\t\tif ($null -eq $command) {');
277
+ lines.push('\t\t\tbreak');
278
+ lines.push('\t\t}');
279
+ lines.push('');
280
+ lines.push('\t\t$path = if ([string]::IsNullOrEmpty($path)) {');
281
+ lines.push('\t\t\t$command.CanonicalName');
282
+ lines.push('\t\t} else {');
283
+ lines.push('\t\t\t"$path $($command.CanonicalName)"');
284
+ lines.push('\t\t}');
285
+ lines.push(`\t\t$nextPathData = $script:${dataVarName}[$path]`);
286
+ lines.push('\t\tif ($null -eq $nextPathData) {');
287
+ lines.push('\t\t\tbreak');
288
+ lines.push('\t\t}');
289
+ lines.push('\t\t$pathData = $nextPathData');
290
+ lines.push('\t}');
291
+ lines.push('');
292
+ lines.push('\treturn @{');
293
+ lines.push('\t\tPath = $path');
294
+ lines.push('\t\tPathData = $pathData');
295
+ lines.push('\t\tExpectingValue = $expectingValue');
296
+ lines.push('\t\tValueFlag = $valueFlag');
297
+ lines.push('\t}');
298
+ lines.push('}');
299
+ lines.push('');
300
+ lines.push(`function ${helperPrefix}_ResolveInlineValueCompletion {`);
301
+ lines.push('\tparam($PathData, [string]$WordToComplete)');
302
+ lines.push(
303
+ `\t$flagMatch = ${helperPrefix}_ResolveFlagToken -PathData $PathData -Token $WordToComplete`,
304
+ );
305
+ lines.push('\tif ($null -eq $flagMatch -or $flagMatch.InlinePrefix -eq $null) {');
306
+ lines.push('\t\treturn $null');
307
+ lines.push('\t}');
308
+ lines.push('\treturn $flagMatch');
309
+ lines.push('}');
310
+ lines.push('');
311
+ lines.push(`function ${helperPrefix}_AddCommandResults {`);
312
+ lines.push('\tparam($Results, $PathData, [string]$WordToComplete)');
313
+ lines.push('\tforeach ($command in $PathData.Commands) {');
314
+ lines.push('\t\tforeach ($name in $command.Names) {');
315
+ lines.push(
316
+ '\t\t\tif (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $name.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {',
317
+ );
318
+ lines.push('\t\t\t\tcontinue');
319
+ lines.push('\t\t\t}');
320
+ lines.push('');
321
+ lines.push('\t\t\t$Results.Add([CompletionResult]::new(');
322
+ lines.push('\t\t\t\t$name,');
323
+ lines.push('\t\t\t\t$name,');
324
+ lines.push('\t\t\t\t[CompletionResultType]::Command,');
325
+ lines.push('\t\t\t\t$command.Description');
326
+ lines.push('\t\t\t))');
327
+ lines.push('\t\t}');
328
+ lines.push('\t}');
329
+ lines.push('}');
330
+ lines.push('');
331
+ lines.push(`function ${helperPrefix}_AddFlagResults {`);
332
+ lines.push('\tparam($Results, $PathData, [string]$WordToComplete)');
333
+ lines.push('\tforeach ($flag in $PathData.Flags) {');
334
+ lines.push('\t\tforeach ($form in $flag.Forms) {');
335
+ lines.push(
336
+ '\t\t\tif (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $form.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {',
337
+ );
338
+ lines.push('\t\t\t\tcontinue');
339
+ lines.push('\t\t\t}');
340
+ lines.push('');
341
+ lines.push('\t\t\t$Results.Add([CompletionResult]::new(');
342
+ lines.push('\t\t\t\t$form,');
343
+ lines.push('\t\t\t\t$form,');
344
+ lines.push('\t\t\t\t[CompletionResultType]::ParameterName,');
345
+ lines.push('\t\t\t\t$flag.Description');
346
+ lines.push('\t\t\t))');
347
+ lines.push('\t\t}');
348
+ lines.push('\t}');
349
+ lines.push('}');
350
+ lines.push('');
351
+ lines.push(`function ${helperPrefix}_AddEnumResults {`);
352
+ lines.push('\tparam($Results, $Flag, [string]$WordToComplete)');
353
+ lines.push('\tforeach ($value in $Flag.EnumValues) {');
354
+ lines.push(
355
+ '\t\tif (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $value.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {',
356
+ );
357
+ lines.push('\t\t\tcontinue');
358
+ lines.push('\t\t}');
359
+ lines.push('');
360
+ lines.push('\t\t$Results.Add([CompletionResult]::new(');
361
+ lines.push('\t\t\t$value,');
362
+ lines.push('\t\t\t$value,');
363
+ lines.push('\t\t\t[CompletionResultType]::ParameterValue,');
364
+ lines.push('\t\t\t$Flag.Description');
365
+ lines.push('\t\t))');
366
+ lines.push('\t}');
367
+ lines.push('}');
368
+ lines.push('');
369
+ lines.push(`function ${helperPrefix}_AddInlineEnumResults {`);
370
+ lines.push('\tparam($Results, $InlineValue, [string]$WordToComplete)');
371
+ lines.push('\tforeach ($value in $InlineValue.Flag.EnumValues) {');
372
+ lines.push('\t\t$completion = "$($InlineValue.InlinePrefix)$value"');
373
+ lines.push(
374
+ '\t\tif (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $completion.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {',
375
+ );
376
+ lines.push('\t\t\tcontinue');
377
+ lines.push('\t\t}');
378
+ lines.push('');
379
+ lines.push('\t\t$Results.Add([CompletionResult]::new(');
380
+ lines.push('\t\t\t$completion,');
381
+ lines.push('\t\t\t$value,');
382
+ lines.push('\t\t\t[CompletionResultType]::ParameterValue,');
383
+ lines.push('\t\t\t$InlineValue.Flag.Description');
384
+ lines.push('\t\t))');
385
+ lines.push('\t}');
386
+ lines.push('}');
387
+ }
388
+
389
+ function quotePowerShellString(value: string): string {
390
+ return `'${value.replace(/'/g, "''")}'`;
391
+ }
392
+
393
+ function formatPowerShellArray(values: readonly string[]): string {
394
+ if (values.length === 0) {
395
+ return '@()';
396
+ }
397
+
398
+ return `@(${values.map(quotePowerShellString).join(', ')})`;
399
+ }
400
+
401
+ function dedupeValues(values: readonly string[]): readonly string[] {
402
+ return [...new Set(values)];
22
403
  }
23
404
 
24
405
  export { generatePowerShellCompletion };