@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.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 (285) hide show
  1. package/CHANGELOG.md +251 -0
  2. package/LICENSE +1 -1
  3. package/LICENSE-cobra.txt +174 -0
  4. package/NOTICE +15 -0
  5. package/README.md +55 -259
  6. package/dist/aim-DZHwwiIc.d.ts +139 -0
  7. package/dist/aim.d.ts +1 -116
  8. package/dist/aim.js +13 -414
  9. package/dist/alias-D9_qFlyP.d.ts +174 -0
  10. package/dist/alias.d.ts +2 -73
  11. package/dist/alias.js +27 -207
  12. package/dist/api-DAexsu2H.d.ts +77 -0
  13. package/dist/api.d.ts +1 -62
  14. package/dist/api.js +10 -164
  15. package/dist/auth-2-jfgiHn.d.ts +34 -0
  16. package/dist/auth.d.ts +1 -26
  17. package/dist/auth.js +6 -40
  18. package/dist/chunk-2JV3A7OP.js +1894 -0
  19. package/dist/chunk-3FIKGFKI.js +54 -0
  20. package/dist/chunk-4UE5TCMQ.js +104 -0
  21. package/dist/chunk-6HFAEZ52.js +29 -0
  22. package/dist/chunk-6SVOHNIC.js +17 -0
  23. package/dist/chunk-72XZWQX7.js +504 -0
  24. package/dist/chunk-ABQSE7AI.js +513 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BLS2OBIQ.js +263 -0
  27. package/dist/chunk-BRNEKPWX.js +37 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-GGWJRWWA.js +309 -0
  30. package/dist/chunk-GHPJJV5L.js +613 -0
  31. package/dist/chunk-IXVQ62NZ.js +334 -0
  32. package/dist/chunk-JKMQSAJP.js +174 -0
  33. package/dist/chunk-JZ22ZUFA.js +1131 -0
  34. package/dist/chunk-K7VCKJ27.js +814 -0
  35. package/dist/chunk-KVG7YCTS.js +115 -0
  36. package/dist/chunk-L23O2FFE.js +51 -0
  37. package/dist/chunk-MQXYDYRD.js +968 -0
  38. package/dist/chunk-MUIQVU6E.js +251 -0
  39. package/dist/chunk-NLMS7HGP.js +178 -0
  40. package/dist/chunk-POR5L2DG.js +247 -0
  41. package/dist/chunk-PSFYJGDG.js +1445 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QPUCXQXT.js +67 -0
  44. package/dist/chunk-QQQYCWSC.js +240 -0
  45. package/dist/chunk-R5U7XKVJ.js +16 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T46YPHKN.js +669 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-WBVO43HU.js +355 -0
  50. package/dist/chunk-WUOAQVOA.js +86 -0
  51. package/dist/chunk-WWUKGJB5.js +90 -0
  52. package/dist/chunk-XJTRY453.js +868 -0
  53. package/dist/chunk-YGYQUFGY.js +219 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-C5B5tnpA.d.ts +400 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +70 -945
  58. package/dist/completion-csVun6SP.d.ts +112 -0
  59. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  60. package/dist/completion-values.d.ts +1 -0
  61. package/dist/completion-values.js +29 -0
  62. package/dist/completion.d.ts +3 -0
  63. package/dist/completion.js +34 -0
  64. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  65. package/dist/compliance.d.ts +1 -0
  66. package/dist/compliance.js +17 -0
  67. package/dist/config-CaK60ByQ.d.ts +241 -0
  68. package/dist/config.d.ts +1 -97
  69. package/dist/config.js +8 -78
  70. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  71. package/dist/errcorrect.d.ts +1 -37
  72. package/dist/errcorrect.js +8 -68
  73. package/dist/error-Do8Qji43.d.ts +231 -0
  74. package/dist/id/index.d.ts +2 -83
  75. package/dist/id/index.js +14 -65
  76. package/dist/index-BKJZClJx.d.ts +1486 -0
  77. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  78. package/dist/index-DCe1boBz.d.ts +328 -0
  79. package/dist/index-VLDcI5NF.d.ts +95 -0
  80. package/dist/index.d.ts +37 -0
  81. package/dist/index.js +132 -0
  82. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  83. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  84. package/dist/llm-anthropic.d.ts +2 -0
  85. package/dist/llm-anthropic.js +13 -0
  86. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  87. package/dist/llm-openai.d.ts +2 -0
  88. package/dist/llm-openai.js +19 -0
  89. package/dist/llm.d.ts +1 -188
  90. package/dist/llm.js +101 -356
  91. package/dist/log-CkaxMX3U.d.ts +115 -0
  92. package/dist/log.d.ts +2 -0
  93. package/dist/log.js +14 -0
  94. package/dist/mcp/index.d.ts +4 -0
  95. package/dist/mcp/index.js +184 -0
  96. package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
  97. package/dist/netpolicy.d.ts +1 -0
  98. package/dist/netpolicy.js +25 -0
  99. package/dist/output-CjZWmL8s.d.ts +420 -0
  100. package/dist/output.d.ts +3 -213
  101. package/dist/output.js +137 -447
  102. package/dist/parity-CvMuYcVI.d.ts +61 -0
  103. package/dist/progress-CAzyxeWl.d.ts +38 -0
  104. package/dist/progress.d.ts +1 -30
  105. package/dist/progress.js +6 -55
  106. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  107. package/dist/provenance.d.ts +1 -24
  108. package/dist/provenance.js +6 -31
  109. package/dist/routellm-B0nv59mH.d.ts +111 -0
  110. package/dist/routellm.d.ts +2 -64
  111. package/dist/routellm.js +13 -255
  112. package/dist/rpc-D31Lg0Kc.d.ts +32 -0
  113. package/dist/rpc.d.ts +2 -25
  114. package/dist/rpc.js +4 -98
  115. package/dist/safety-CUaYEjZc.d.ts +30 -0
  116. package/dist/safety.d.ts +1 -24
  117. package/dist/safety.js +6 -43
  118. package/dist/scope-BrhYB4ij.d.ts +141 -0
  119. package/dist/scope.d.ts +1 -121
  120. package/dist/scope.js +20 -377
  121. package/dist/serve-D8yWMrTc.d.ts +646 -0
  122. package/dist/serve.d.ts +3 -0
  123. package/dist/serve.js +75 -0
  124. package/dist/sqlstore.js +6 -39
  125. package/dist/stream-CrjeCp0M.d.ts +44 -0
  126. package/dist/stream.d.ts +1 -35
  127. package/dist/stream.js +8 -51
  128. package/dist/telemetry/index.d.ts +1 -315
  129. package/dist/telemetry/index.js +26 -599
  130. package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
  131. package/dist/toolspec.d.ts +2 -0
  132. package/dist/toolspec.js +37 -0
  133. package/dist/tui/index.d.ts +6 -298
  134. package/dist/tui/index.js +17 -381
  135. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  136. package/dist/upgrade.d.ts +1 -95
  137. package/dist/upgrade.js +6 -114
  138. package/dist/xdg-DB7Shoib.d.ts +179 -0
  139. package/dist/xdg.d.ts +1 -169
  140. package/dist/xdg.js +14 -128
  141. package/package.json +192 -24
  142. package/src/README.md +15 -0
  143. package/src/alias.conformance.test.ts +250 -0
  144. package/src/alias.test.ts +206 -2
  145. package/src/alias.ts +196 -21
  146. package/src/cli.help-command.test.ts +105 -0
  147. package/src/cli.offline.test.ts +93 -0
  148. package/src/cli.parity.test.ts +192 -0
  149. package/src/cli.test.ts +95 -1
  150. package/src/cli.ts +195 -25
  151. package/src/completion-scripts.ts +16 -0
  152. package/src/completion-values.test.ts +76 -16
  153. package/src/completion-values.ts +170 -66
  154. package/src/completion.conformance.test.ts +297 -0
  155. package/src/completion.test.ts +256 -145
  156. package/src/completion.ts +767 -121
  157. package/src/compliance.test.ts +196 -2
  158. package/src/compliance.ts +440 -20
  159. package/src/config-merge.test.ts +425 -0
  160. package/src/config.test.ts +228 -1
  161. package/src/config.ts +429 -16
  162. package/src/gen/crud_pb.ts +7 -7
  163. package/src/id/README.md +38 -0
  164. package/src/id/contract.test.ts +1 -1
  165. package/src/id/index.test.ts +1 -1
  166. package/src/id/index.ts +3 -2
  167. package/src/index.test.ts +71 -0
  168. package/src/index.ts +46 -0
  169. package/src/llm-anthropic.conformance.test.ts +1135 -0
  170. package/src/llm-anthropic.test.ts +152 -0
  171. package/src/llm-anthropic.ts +940 -0
  172. package/src/llm-choice-hermetic.test.ts +335 -0
  173. package/src/llm-config.test.ts +232 -0
  174. package/src/llm-config.ts +106 -0
  175. package/src/llm-endpoint.ts +254 -0
  176. package/src/llm-error.ts +17 -0
  177. package/src/llm-errors.ts +152 -0
  178. package/src/llm-file.ts +126 -0
  179. package/src/llm-http.ts +317 -0
  180. package/src/llm-keys.ts +167 -0
  181. package/src/llm-media.conformance.test.ts +87 -0
  182. package/src/llm-media.test.ts +279 -0
  183. package/src/llm-media.ts +322 -0
  184. package/src/llm-openai.conformance.test.ts +407 -0
  185. package/src/llm-openai.test.ts +510 -0
  186. package/src/llm-openai.ts +708 -0
  187. package/src/llm-payload.ts +155 -0
  188. package/src/llm-quote.ts +46 -0
  189. package/src/llm-routellm.conformance.test.ts +44 -0
  190. package/src/llm-toolnames.conformance.test.ts +112 -0
  191. package/src/llm-toolnames.test.ts +132 -0
  192. package/src/llm-toolnames.ts +298 -0
  193. package/src/llm-uri.ts +99 -0
  194. package/src/llm.test.ts +43 -15
  195. package/src/llm.toolcall.test.ts +175 -0
  196. package/src/llm.ts +602 -190
  197. package/src/log.parity.test.ts +105 -0
  198. package/src/log.test.ts +270 -1
  199. package/src/log.ts +228 -49
  200. package/src/mcp/README.md +63 -0
  201. package/src/mcp/args-separator.test.ts +164 -0
  202. package/src/mcp/args.test.ts +223 -0
  203. package/src/mcp/args.ts +160 -0
  204. package/src/mcp/audit.test.ts +520 -0
  205. package/src/mcp/audit.ts +70 -0
  206. package/src/mcp/bridge.test.ts +222 -0
  207. package/src/mcp/bridge.ts +291 -0
  208. package/src/mcp/conformance.test.ts +357 -0
  209. package/src/mcp/dispatch.ts +359 -0
  210. package/src/mcp/identity.test.ts +166 -0
  211. package/src/mcp/identity.ts +72 -0
  212. package/src/mcp/index.ts +176 -0
  213. package/src/mcp/legacy-notify.test.ts +59 -0
  214. package/src/mcp/legacy.ts +367 -0
  215. package/src/mcp/mcp.test.ts +707 -0
  216. package/src/mcp/modern-confirm.test.ts +520 -0
  217. package/src/mcp/modern-confirm.ts +484 -0
  218. package/src/mcp/modern.ts +788 -0
  219. package/src/mcp/stdio.test.ts +313 -0
  220. package/src/mcp/stdio.ts +254 -0
  221. package/src/mcp/tasks.ts +82 -0
  222. package/src/mcp/testtree.ts +250 -0
  223. package/src/mcp/toolname.test.ts +147 -0
  224. package/src/mcp/types.ts +689 -0
  225. package/src/netpolicy.test.ts +280 -0
  226. package/src/netpolicy.ts +256 -0
  227. package/src/output/README.md +46 -0
  228. package/src/output/builtins.ts +5 -5
  229. package/src/output/dispatch.ts +10 -2
  230. package/src/output/error.ts +459 -0
  231. package/src/output/formatter.ts +29 -5
  232. package/src/output/formatters/README.md +50 -0
  233. package/src/output/formatters/csv.ts +48 -12
  234. package/src/output/formatters/json.ts +4 -25
  235. package/src/output/formatters/project.ts +34 -0
  236. package/src/output/formatters/table.ts +8 -6
  237. package/src/output/formatters/text.ts +7 -3
  238. package/src/output/formatters/yaml.ts +5 -22
  239. package/src/output/projection.test.ts +298 -0
  240. package/src/output/projection.ts +33 -59
  241. package/src/output/template.ts +11 -21
  242. package/src/output.surface.test.ts +41 -0
  243. package/src/output.ts +64 -3
  244. package/src/published-types.test.ts +133 -0
  245. package/src/routellm.test.ts +209 -28
  246. package/src/routellm.toolcall.test.ts +521 -0
  247. package/src/routellm.ts +213 -177
  248. package/src/router/README.md +44 -0
  249. package/src/router/server.test.ts +41 -0
  250. package/src/router/server.ts +11 -0
  251. package/src/safety.test.ts +19 -9
  252. package/src/scope-defaults.json +29 -29
  253. package/src/serve.test.ts +1257 -0
  254. package/src/serve.ts +1665 -0
  255. package/src/telemetry/README.md +48 -0
  256. package/src/telemetry/client.test.ts +31 -0
  257. package/src/telemetry/client.ts +12 -6
  258. package/src/telemetry/offline.test.ts +64 -0
  259. package/src/toolspec-internal.ts +279 -0
  260. package/src/toolspec-manifest.test.ts +167 -0
  261. package/src/toolspec-manifest.ts +410 -0
  262. package/src/toolspec-spec-schemas.ts +12 -0
  263. package/src/toolspec-spec.test.ts +273 -0
  264. package/src/toolspec-spec.ts +458 -0
  265. package/src/toolspec.from-command.test.ts +350 -0
  266. package/src/toolspec.test.ts +2 -2
  267. package/src/toolspec.ts +222 -0
  268. package/src/triton/README.md +34 -0
  269. package/src/tui/README.md +42 -0
  270. package/src/tui/parity.test.ts +120 -31
  271. package/src/tui/parity.ts +58 -7
  272. package/src/wizard.test.ts +7 -7
  273. package/test/llm/conformance-helpers.ts +100 -0
  274. package/test/output/csv.test.ts +164 -0
  275. package/test/output/dispatch.test.ts +1 -2
  276. package/test/output/error.test.ts +277 -0
  277. package/test/output/smoke-capture.ts +2 -2
  278. package/test/output/smoke.test.ts +2 -2
  279. package/test/output/taxonomy-contract.test.ts +148 -0
  280. package/test/setup-env.ts +16 -0
  281. package/test/toolspec/fixture.ts +79 -0
  282. package/tsconfig.json +3 -1
  283. package/tsconfig.test.json +10 -0
  284. package/vitest.config.ts +9 -0
  285. package/src/tui/parity.json +0 -74
package/src/completion.ts CHANGED
@@ -2,157 +2,803 @@
2
2
  * @module completion
3
3
  * @package @hop-top/kit
4
4
  *
5
- * Shell completion script generators for Commander-based CLIs.
6
- * Extracts subcommand names and flag names from the program tree
7
- * and generates bash/zsh/fish completion scripts.
5
+ * Shell completion for Commander-based CLIs, in cobra's protocol so a
6
+ * TS kit CLI completes like a Go or Rust one
7
+ * (`contracts/completion-v1`, Go canonical):
8
+ *
9
+ * - `completion bash|zsh|fish|powershell [--no-descriptions]` writes
10
+ * cobra v1.10.2's scripts byte for byte ({@link completionCommand}).
11
+ * - The scripts call back into the hidden `__complete` /
12
+ * `__completeNoDesc` entry point. {@link installCompletionRequest}
13
+ * (done by `createCLI` and {@link completionCommand}) answers it
14
+ * before commander parses, so no hook or action runs on tab. It walks
15
+ * the live command tree: subcommands, aliases, each command's own and
16
+ * inherited flags, choices and the completers bound with
17
+ * {@link bindFlag} / {@link bindArgs}.
18
+ *
19
+ * Wire format: one completion per line (`value`, or
20
+ * `value<TAB>description`), then `:<directive>`; stderr carries
21
+ * `Completion ended with directive: <name>`. Exit code 0.
22
+ *
23
+ * Commander has no public accessor for a few facts read here; they are
24
+ * typed locally in {@link CommanderInternals} (commander 15).
8
25
  */
9
26
 
10
- import { Command } from 'commander';
27
+ import { appendFileSync } from 'node:fs';
28
+ import { Command, Option } from 'commander';
29
+
30
+ import { SCRIPT_TEMPLATES } from './completion-scripts';
31
+ import {
32
+ type Completer,
33
+ type CompletionContext,
34
+ directiveName,
35
+ funcCompleter,
36
+ resolveCompletions,
37
+ ShellCompDirective,
38
+ } from './completion-values';
39
+
40
+ /** Name of the hidden command a shell script calls for completions. */
41
+ export const REQUEST_CMD = '__complete';
42
+ /** Name of the hidden command that returns completions without descriptions. */
43
+ export const NO_DESC_REQUEST_CMD = '__completeNoDesc';
44
+
45
+ /** A shell `completion` writes a script for. */
46
+ export type Shell = 'bash' | 'zsh' | 'fish' | 'powershell';
47
+ /** Every shell, in the order the `completion` command lists them. */
48
+ export const SHELLS: readonly Shell[] = ['bash', 'zsh', 'fish', 'powershell'];
11
49
 
12
- /** Collect all visible subcommand names + aliases (non-hidden, excluding help). */
13
- function collectCommands(cmd: Command): string[] {
14
- return cmd.commands
15
- .filter(c => !(c as any)._hidden && c.name() !== 'help')
16
- .flatMap(c => [c.name(), ...c.aliases()]);
50
+ /** commander 15 private members this module reads (no public accessor). */
51
+ interface CommanderInternals {
52
+ _hidden?: boolean;
53
+ _enablePositionalOptions?: boolean;
54
+ _versionOptionName?: string;
55
+ _getHelpOption?(): Option | null;
17
56
  }
18
57
 
19
- /** Collect all option long-names (e.g. --format, --quiet). */
20
- function collectFlags(cmd: Command): string[] {
21
- return cmd.options.map(o => o.long).filter(Boolean) as string[];
58
+ function internals(c: Command): CommanderInternals {
59
+ return c as unknown as CommanderInternals;
22
60
  }
23
61
 
24
- /** Generate a bash completion script for the given program. */
25
- export function generateBashCompletion(program: Command): string {
26
- const name = program.name();
27
- const cmds = collectCommands(program);
28
- const flags = collectFlags(program);
29
- const words = [...cmds, ...flags].join(' ');
62
+ // Per-command state lives on the command under registry symbols, so two
63
+ // copies of this module (separate bundles) still share it.
64
+ const FLAG_COMPLETERS = Symbol.for('@hop-top/kit/completion/flags');
65
+ const ARGS_COMPLETER = Symbol.for('@hop-top/kit/completion/args');
66
+ const ROOT_ALIASES = Symbol.for('@hop-top/kit/completion/aliases');
67
+ const BUILTIN = Symbol.for('@hop-top/kit/completion/builtin');
68
+ const INSTALLED = Symbol.for('@hop-top/kit/completion/installed');
30
69
 
31
- return `# bash completion for ${name}
32
- # eval "$(${name} completion bash)"
70
+ type Tagged = Command & {
71
+ [FLAG_COMPLETERS]?: Map<string, Completer>;
72
+ [ARGS_COMPLETER]?: Completer;
73
+ [ROOT_ALIASES]?: Map<string, string>;
74
+ [BUILTIN]?: boolean;
75
+ [INSTALLED]?: boolean;
76
+ };
33
77
 
34
- _${name}_completions() {
35
- local cur="\${COMP_WORDS[COMP_CWORD]}"
36
- local commands="${words}"
78
+ // ---------------------------------------------------------------------------
79
+ // Scripts
80
+ // ---------------------------------------------------------------------------
37
81
 
38
- COMPREPLY=( $(compgen -W "\${commands}" -- "\${cur}") )
82
+ /** cobra's `<PROGRAM>_<SUFFIX>` variable name. */
83
+ function configEnvVar(name: string, suffix: string): string {
84
+ return `${name}_${suffix}`.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
39
85
  }
40
86
 
41
- complete -F _${name}_completions ${name}
42
- `;
87
+ /** The `completion <shell>` script for program `name`, cobra's byte for byte. */
88
+ export function renderCompletionScript(
89
+ shell: Shell,
90
+ name: string,
91
+ includeDescriptions = true,
92
+ ): string {
93
+ const vars: Record<string, string> = {
94
+ NAME_PAD36: name.padEnd(36),
95
+ // Shell identifiers cannot hold '-' or ':'.
96
+ NAME_VAR: name.replace(/[-:]/g, '_'),
97
+ ACTIVE_HELP_VAR: configEnvVar(name, 'ACTIVE_HELP'),
98
+ COMP_CMD: includeDescriptions ? REQUEST_CMD : NO_DESC_REQUEST_CMD,
99
+ NAME: name,
100
+ };
101
+ return SCRIPT_TEMPLATES[shell].replace(
102
+ /@@(NAME_PAD36|NAME_VAR|ACTIVE_HELP_VAR|COMP_CMD|NAME)@@/g,
103
+ (_m, k: string) => vars[k]!,
104
+ );
105
+ }
106
+
107
+ /** Generate a bash completion script (cobra V2; needs bash-completion). */
108
+ export function generateBashCompletion(program: Command, includeDescriptions = true): string {
109
+ return renderCompletionScript('bash', program.name(), includeDescriptions);
43
110
  }
44
111
 
45
112
  /** Generate a zsh completion script for the given program. */
46
- export function generateZshCompletion(program: Command): string {
47
- const name = program.name();
48
- const cmds = collectCommands(program);
49
- const flags = collectFlags(program);
50
-
51
- const cmdEntries = cmds
52
- .map(c => {
53
- const sub = program.commands.find(
54
- s => s.name() === c || s.aliases().includes(c),
55
- );
56
- const desc = sub?.description() ?? '';
57
- return ` '${c}:${desc}'`;
58
- })
59
- .join('\n');
60
-
61
- const flagEntries = flags
62
- .map(f => ` '${f}[${f}]'`)
63
- .join('\n');
64
-
65
- return `#compdef ${name}
66
- # eval "$(${name} completion zsh)"
67
-
68
- _${name}() {
69
- local -a commands flags
70
-
71
- commands=(
72
- ${cmdEntries}
73
- )
74
-
75
- flags=(
76
- ${flagEntries}
77
- )
78
-
79
- _arguments -s \\
80
- '1:command:->cmds' \\
81
- '*::flags:->flags'
82
-
83
- case "$state" in
84
- cmds)
85
- _describe -t commands 'commands' commands
86
- ;;
87
- flags)
88
- _describe -t flags 'flags' flags
89
- ;;
90
- esac
91
- }
92
-
93
- compdef _${name} ${name}
94
- `;
113
+ export function generateZshCompletion(program: Command, includeDescriptions = true): string {
114
+ return renderCompletionScript('zsh', program.name(), includeDescriptions);
95
115
  }
96
116
 
97
117
  /** Generate a fish completion script for the given program. */
98
- export function generateFishCompletion(program: Command): string {
99
- const name = program.name();
100
- const cmds = collectCommands(program);
101
- const flags = collectFlags(program);
102
-
103
- const lines = [
104
- `# fish completion for ${name}`,
105
- `# ${name} completion fish | source`,
106
- '',
107
- ];
118
+ export function generateFishCompletion(program: Command, includeDescriptions = true): string {
119
+ return renderCompletionScript('fish', program.name(), includeDescriptions);
120
+ }
108
121
 
109
- for (const c of cmds) {
110
- const sub = program.commands.find(
111
- s => s.name() === c || s.aliases().includes(c),
112
- );
113
- const desc = sub?.description() ?? '';
114
- lines.push(
115
- `complete -c ${name} -n '__fish_use_subcommand' ` +
116
- `-a '${c}' -d '${desc}'`
117
- );
118
- }
122
+ /** Generate a PowerShell completion script for the given program. */
123
+ export function generatePowerShellCompletion(
124
+ program: Command,
125
+ includeDescriptions = true,
126
+ ): string {
127
+ return renderCompletionScript('powershell', program.name(), includeDescriptions);
128
+ }
119
129
 
120
- for (const f of flags) {
121
- const long = f.replace(/^--/, '');
122
- lines.push(
123
- `complete -c ${name} -l '${long}'`
124
- );
125
- }
130
+ function shellHelp(sh: Shell, p: string): string {
131
+ switch (sh) {
132
+ case 'bash':
133
+ return `
134
+ This script depends on the 'bash-completion' package.
135
+ If it is not installed already, you can install it via your OS's package manager.
136
+
137
+ To load completions in your current shell session:
138
+
139
+ \tsource <(${p} completion bash)
140
+
141
+ To load completions for every new session, execute once:
142
+
143
+ #### Linux:
144
+
145
+ \t${p} completion bash > /etc/bash_completion.d/${p}
146
+
147
+ #### macOS:
126
148
 
127
- lines.push('');
128
- return lines.join('\n');
149
+ \t${p} completion bash > $(brew --prefix)/etc/bash_completion.d/${p}
150
+
151
+ You will need to start a new shell for this setup to take effect.
152
+ `;
153
+ case 'zsh':
154
+ return `
155
+ If shell completion is not already enabled in your environment you will need
156
+ to enable it. You can execute the following once:
157
+
158
+ \techo "autoload -U compinit; compinit" >> ~/.zshrc
159
+
160
+ To load completions in your current shell session:
161
+
162
+ \tsource <(${p} completion zsh)
163
+
164
+ To load completions for every new session, execute once:
165
+
166
+ #### Linux:
167
+
168
+ \t${p} completion zsh > "\${fpath[1]}/_${p}"
169
+
170
+ #### macOS:
171
+
172
+ \t${p} completion zsh > $(brew --prefix)/share/zsh/site-functions/_${p}
173
+
174
+ You will need to start a new shell for this setup to take effect.
175
+ `;
176
+ case 'fish':
177
+ return `
178
+ To load completions in your current shell session:
179
+
180
+ \t${p} completion fish | source
181
+
182
+ To load completions for every new session, execute once:
183
+
184
+ \t${p} completion fish > ~/.config/fish/completions/${p}.fish
185
+
186
+ You will need to start a new shell for this setup to take effect.
187
+ `;
188
+ case 'powershell':
189
+ return `
190
+ To load completions in your current shell session:
191
+
192
+ \t${p} completion powershell | Out-String | Invoke-Expression
193
+
194
+ To load completions for every new session, add the output of the above command
195
+ to your powershell profile.
196
+ `;
197
+ }
129
198
  }
130
199
 
200
+ /** Completes nothing and no files: cobra's `NoFileCompletions`. */
201
+ const NO_FILE_COMPLETIONS = funcCompleter(() => []);
202
+
131
203
  /**
132
- * Create a hidden `completion` command with bash/zsh/fish subcommands.
133
- * Each prints the completion script to stdout.
204
+ * cobra's `completion` command: `completion bash|zsh|fish|powershell
205
+ * [--no-descriptions]`, each printing the script to stdout. Add it to
206
+ * the program (kit puts it in the hidden `management` group). It also
207
+ * installs the `__complete` entry point on `program`.
134
208
  */
135
209
  export function completionCommand(program: Command): Command {
210
+ installCompletionRequest(program);
136
211
  const cmd = new Command('completion')
137
- .description('Generate shell completion scripts');
212
+ .description('Generate the autocompletion script for the specified shell');
213
+ (cmd as Tagged)[BUILTIN] = true;
214
+ bindArgs(cmd, NO_FILE_COMPLETIONS);
138
215
 
139
- cmd.command('bash')
140
- .description('Generate bash completion script')
141
- .action(() => {
142
- process.stdout.write(generateBashCompletion(program));
143
- });
216
+ for (const sh of SHELLS) {
217
+ const leaf = cmd.command(sh)
218
+ .description(`Generate the autocompletion script for ${sh}`)
219
+ .option('--no-descriptions', 'disable completion descriptions')
220
+ .addHelpText('after', shellHelp(sh, program.name()))
221
+ .action((opts: { descriptions?: boolean }) => {
222
+ process.stdout.write(
223
+ renderCompletionScript(sh, program.name(), opts.descriptions !== false),
224
+ );
225
+ });
226
+ bindArgs(leaf, NO_FILE_COMPLETIONS);
227
+ }
228
+ return cmd;
229
+ }
144
230
 
145
- cmd.command('zsh')
146
- .description('Generate zsh completion script')
147
- .action(() => {
148
- process.stdout.write(generateZshCompletion(program));
149
- });
231
+ // ---------------------------------------------------------------------------
232
+ // Binding
233
+ // ---------------------------------------------------------------------------
234
+
235
+ /**
236
+ * Binds `completer` as the value completion of `cmd`'s own flag `flag`
237
+ * (long name, with or without `--`). An unknown flag is silent and the
238
+ * first binding wins, as with cobra's `RegisterFlagCompletionFunc`. A
239
+ * flag subcommands inherit is bound on the command declaring it.
240
+ */
241
+ export function bindFlag(cmd: Command, flag: string, completer: Completer): void {
242
+ const name = flag.replace(/^--?/, '');
243
+ if (!cmd.options.some(o => o.long === `--${name}`)) return;
244
+ const t = cmd as Tagged;
245
+ const m = (t[FLAG_COMPLETERS] ??= new Map());
246
+ if (!m.has(name)) m.set(name, completer);
247
+ }
248
+
249
+ /** Binds `completer` as the completion of `cmd`'s positional arguments; replaces an earlier binding. */
250
+ export function bindArgs(cmd: Command, completer: Completer): void {
251
+ (cmd as Tagged)[ARGS_COMPLETER] = completer;
252
+ }
253
+
254
+ /**
255
+ * Records `name` as a root-level alias of the command at `target` (a
256
+ * space-separated path), so root argument completion offers it as
257
+ * `name<TAB>alias for <target>`, and a root subcommand named `name`
258
+ * completes as a flagless stand-in. `bridgeAliases` calls this for
259
+ * every alias but a visible or custom-dispatch proxy, which completes
260
+ * as an ordinary subcommand.
261
+ */
262
+ export function registerRootAlias(root: Command, name: string, target: string): void {
263
+ const t = root as Tagged;
264
+ (t[ROOT_ALIASES] ??= new Map()).set(name, target.trim().split(/\s+/).join(' '));
265
+ }
266
+
267
+ // ---------------------------------------------------------------------------
268
+ // Request entry point
269
+ // ---------------------------------------------------------------------------
270
+
271
+ /** Where a request writes. */
272
+ export interface CompletionIO {
273
+ out(s: string): void;
274
+ err(s: string): void;
275
+ }
276
+
277
+ const stdio: CompletionIO = {
278
+ out: s => { process.stdout.write(s); },
279
+ err: s => { process.stderr.write(s); },
280
+ };
281
+
282
+ type ParseOptions = { from?: string };
283
+
284
+ /** The user words of `argv`, as commander's `_prepareUserArgs` finds them. */
285
+ function userArgs(argv: readonly string[] | undefined, opts?: ParseOptions): string[] | null {
286
+ let from = opts?.from;
287
+ if (argv === undefined && from === undefined) {
288
+ if (process.versions?.electron) from = 'electron';
289
+ const ea = process.execArgv ?? [];
290
+ if (['-e', '--eval', '-p', '--print'].some(f => ea.includes(f))) from = 'eval';
291
+ }
292
+ const a = argv ?? process.argv;
293
+ switch (from) {
294
+ case undefined:
295
+ case 'node': return a.slice(2);
296
+ case 'electron': return (process as { defaultApp?: boolean }).defaultApp ? a.slice(2) : a.slice(1);
297
+ case 'user': return a.slice(0);
298
+ case 'eval': return a.slice(1);
299
+ default: return null;
300
+ }
301
+ }
302
+
303
+ async function serve(program: Command, words: string[], noDesc: boolean): Promise<void> {
304
+ if (words.length === 0) {
305
+ stdio.err(`Error: requires at least 1 arg(s), only received 0\n`);
306
+ process.exitCode = 1;
307
+ return;
308
+ }
309
+ try {
310
+ await completeRequest(program, words, noDesc);
311
+ } catch (e) {
312
+ stdio.err(`Error: ${e instanceof Error ? e.message : String(e)}\n`);
313
+ process.exitCode = 1;
314
+ }
315
+ }
316
+
317
+ /**
318
+ * Makes `program.parse` / `parseAsync` answer `__complete` and
319
+ * `__completeNoDesc` requests themselves, before commander parses, so
320
+ * no hook, option handler or action runs on tab. Idempotent.
321
+ */
322
+ export function installCompletionRequest(program: Command): void {
323
+ const t = program as Tagged;
324
+ if (t[INSTALLED]) return;
325
+ t[INSTALLED] = true;
326
+ const request = (argv?: readonly string[], opts?: ParseOptions) => {
327
+ const words = userArgs(argv, opts);
328
+ const first = words?.[0];
329
+ if (first !== REQUEST_CMD && first !== NO_DESC_REQUEST_CMD) return null;
330
+ return serve(program, words!.slice(1), first === NO_DESC_REQUEST_CMD);
331
+ };
332
+ const parse = program.parse.bind(program);
333
+ const parseAsync = program.parseAsync.bind(program);
334
+ program.parse = ((argv?: readonly string[], opts?: ParseOptions) => {
335
+ const pending = request(argv, opts);
336
+ if (!pending) return parse(argv, opts as never);
337
+ void pending;
338
+ return program;
339
+ }) as typeof program.parse;
340
+ program.parseAsync = (async (argv?: readonly string[], opts?: ParseOptions) => {
341
+ const pending = request(argv, opts);
342
+ if (!pending) return parseAsync(argv, opts as never);
343
+ await pending;
344
+ return program;
345
+ }) as typeof program.parseAsync;
346
+ }
347
+
348
+ /**
349
+ * Answers a completion request: `words` are the words after
350
+ * `__complete` (the last is the word being completed). Writes one
351
+ * completion per line, then `:<directive>`, to `io.out`, and the
352
+ * directive's name to `io.err`, in cobra's format.
353
+ */
354
+ export async function completeRequest(
355
+ program: Command,
356
+ words: string[],
357
+ noDesc = false,
358
+ io: CompletionIO = stdio,
359
+ ): Promise<void> {
360
+ const { completions, directive, error } = await getCompletions(program, words);
361
+ if (error) compError(io, error);
362
+ if (!noDesc) {
363
+ const v = envConfig(program.name(), 'COMPLETION_DESCRIPTIONS');
364
+ const b = v === undefined ? undefined : parseBool(v);
365
+ if (b !== undefined) noDesc = !b;
366
+ }
367
+ for (let c of completions) {
368
+ if (noDesc) c = c.split('\t')[0]!;
369
+ // First line only: a description with a line break would read as
370
+ // further completions.
371
+ c = c.split('\n')[0]!;
372
+ io.out(`${goTrimSpace(c)}\n`);
373
+ }
374
+ io.out(`:${directive}\n`);
375
+ io.err(`Completion ended with directive: ${directiveName(directive)}\n`);
376
+ }
150
377
 
151
- cmd.command('fish')
152
- .description('Generate fish completion script')
153
- .action(() => {
154
- process.stdout.write(generateFishCompletion(program));
378
+ /** cobra `getEnvConfig`: `<PROGRAM>_<SUFFIX>`, else `COBRA_<SUFFIX>`. */
379
+ function envConfig(prog: string, suffix: string): string | undefined {
380
+ for (const k of [configEnvVar(prog, suffix), configEnvVar('COBRA', suffix)]) {
381
+ const v = process.env[k];
382
+ if (v) return v;
383
+ }
384
+ return undefined;
385
+ }
386
+
387
+ /** Go `strconv.ParseBool`. */
388
+ function parseBool(v: string): boolean | undefined {
389
+ if (['1', 't', 'T', 'TRUE', 'true', 'True'].includes(v)) return true;
390
+ if (['0', 'f', 'F', 'FALSE', 'false', 'False'].includes(v)) return false;
391
+ return undefined;
392
+ }
393
+
394
+ /** Go `strings.TrimSpace`. */
395
+ function goTrimSpace(s: string): string {
396
+ const ws = '[\\t\\n\\v\\f\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]';
397
+ return s.replace(new RegExp(`^${ws}+|${ws}+$`, 'g'), '');
398
+ }
399
+
400
+ /** cobra `CompErrorln`: stderr, plus `$BASH_COMP_DEBUG_FILE` when set. */
401
+ function compError(io: CompletionIO, msg: string): void {
402
+ const line = `[Debug] [Error] ${msg}\n`;
403
+ const file = process.env['BASH_COMP_DEBUG_FILE'];
404
+ if (file) {
405
+ try { appendFileSync(file, line); } catch { /* best effort */ }
406
+ }
407
+ io.err(line);
408
+ }
409
+
410
+ // ---------------------------------------------------------------------------
411
+ // Engine: cobra's getCompletions over a commander tree
412
+ // ---------------------------------------------------------------------------
413
+
414
+ /** A flag as completion sees it. */
415
+ interface Flag {
416
+ owner: Command;
417
+ /** Long name without `--`. */
418
+ long?: string;
419
+ /** Shorthand without `-`. */
420
+ short?: string;
421
+ usage: string;
422
+ takesValue: boolean;
423
+ multi: boolean;
424
+ hidden: boolean;
425
+ required: boolean;
426
+ /** Help or version: given, completion stops. */
427
+ stops: boolean;
428
+ inherited: boolean;
429
+ choices?: readonly string[];
430
+ }
431
+
432
+ function flagName(f: Flag): string {
433
+ return f.long ?? f.short ?? '';
434
+ }
435
+
436
+ function toFlag(o: Option, owner: Command, root: Command, inherited: boolean): Flag {
437
+ const help = internals(owner)._getHelpOption?.() === o;
438
+ const version = !help && internals(owner)._versionOptionName === o.attributeName();
439
+ let usage = o.description;
440
+ if (help) usage = `help for ${owner.name()}`;
441
+ else if (version) usage = `version for ${root.name()}`;
442
+ else if (o.argChoices?.length) {
443
+ const suffix = `(one of: ${o.argChoices.join(', ')})`;
444
+ usage = usage ? `${usage} ${suffix}` : suffix;
445
+ }
446
+ return {
447
+ owner,
448
+ long: o.long?.replace(/^--/, ''),
449
+ short: o.short?.replace(/^-/, ''),
450
+ usage,
451
+ takesValue: o.required || o.optional,
452
+ multi: o.variadic,
453
+ hidden: o.hidden,
454
+ required: o.mandatory,
455
+ stops: help || version,
456
+ inherited,
457
+ choices: o.argChoices,
458
+ };
459
+ }
460
+
461
+ /**
462
+ * The flags of the last command of `chain`, as commander accepts them:
463
+ * ancestors' options (unless an ancestor has positional options), then
464
+ * its own plus its help option. A root-alias shim takes no flags of its
465
+ * own, only help.
466
+ */
467
+ function flagsOf(root: Command, chain: Command[]): Flag[] {
468
+ const cmd = chain[chain.length - 1]!;
469
+ const out: Flag[] = [];
470
+ for (let i = chain.length - 2; i >= 0; i--) {
471
+ const anc = chain[i]!;
472
+ if (internals(anc)._enablePositionalOptions) break;
473
+ for (const o of anc.options) out.push(toFlag(o, anc, root, true));
474
+ }
475
+ if (isShim(root, cmd)) {
476
+ out.push({
477
+ owner: cmd, long: 'help', short: 'h', usage: `help for ${cmd.name()}`,
478
+ takesValue: false, multi: false, hidden: false, required: false,
479
+ stops: true, inherited: false,
155
480
  });
481
+ return out;
482
+ }
483
+ for (const o of cmd.options) out.push(toFlag(o, cmd, root, false));
484
+ const help = internals(cmd)._getHelpOption?.();
485
+ if (help && !cmd.options.includes(help)) out.push(toFlag(help, cmd, root, false));
486
+ return out;
487
+ }
156
488
 
157
- return cmd;
489
+ function rootAliases(root: Command): Map<string, string> {
490
+ return (root as Tagged)[ROOT_ALIASES] ?? new Map();
491
+ }
492
+
493
+ /** A hidden root subcommand standing in for a deep root alias. */
494
+ function isShim(root: Command, cmd: Command): boolean {
495
+ return cmd.parent === root && rootAliases(root).has(cmd.name());
496
+ }
497
+
498
+ const lookupLong = (flags: Flag[], name: string) => flags.find(f => f.long === name);
499
+ const lookupShort = (flags: Flag[], s: string) => flags.find(f => f.short === s);
500
+
501
+ function subcommand(cmd: Command, word: string): Command | undefined {
502
+ return cmd.commands.find(c => c.name() === word || c.aliases().includes(word));
503
+ }
504
+
505
+ /** pflag `isFlagArg`. */
506
+ function isFlagArg(a: string): boolean {
507
+ return (a.length >= 3 && a.startsWith('--')) || (a.length >= 2 && a[0] === '-' && a[1] !== '-');
508
+ }
509
+
510
+ /** Whether a dash word consumes the next one (unknown flags do, as in cobra). */
511
+ function consumesNext(flags: Flag[], s: string): boolean {
512
+ if (s.includes('=')) return false;
513
+ if (s.startsWith('--')) return lookupLong(flags, s.slice(2))?.takesValue ?? true;
514
+ if (s.startsWith('-') && s.length === 2) return lookupShort(flags, s.slice(1))?.takesValue ?? true;
515
+ return false;
516
+ }
517
+
518
+ /** cobra `stripFlags`: the non-flag words, skipping flag values. */
519
+ function stripFlags(args: string[], flags: Flag[]): string[] {
520
+ const commands: string[] = [];
521
+ for (let i = 0; i < args.length;) {
522
+ const s = args[i++]!;
523
+ if (s === '--') break;
524
+ if (s.startsWith('-') && consumesNext(flags, s)) {
525
+ if (args.length - i <= 1) break;
526
+ i++;
527
+ continue;
528
+ }
529
+ if (s !== '' && !s.startsWith('-')) commands.push(s);
530
+ }
531
+ return commands;
532
+ }
533
+
534
+ /** cobra `argsMinusFirstX`: `args` without the first non-flag `x`. */
535
+ function argsMinusFirst(args: string[], x: string, flags: Flag[]): string[] {
536
+ for (let pos = 0; pos < args.length;) {
537
+ const s = args[pos]!;
538
+ if (s === '--') break;
539
+ if (s.startsWith('-') && consumesNext(flags, s)) {
540
+ pos += 2;
541
+ continue;
542
+ }
543
+ if (!s.startsWith('-') && s === x) return [...args.slice(0, pos), ...args.slice(pos + 1)];
544
+ pos++;
545
+ }
546
+ return args;
547
+ }
548
+
549
+ /** cobra `Find`: descend through subcommand names and aliases. */
550
+ function find(root: Command, args: string[]) {
551
+ const chain = [root];
552
+ const words: string[] = [];
553
+ let rest = args;
554
+ for (;;) {
555
+ const cur = chain[chain.length - 1]!;
556
+ const flags = flagsOf(root, chain);
557
+ const next = stripFlags(rest, flags)[0];
558
+ if (next === undefined) break;
559
+ const sub = subcommand(cur, next);
560
+ if (!sub) break;
561
+ rest = argsMinusFirst(rest, next, flags);
562
+ words.push(sub.name());
563
+ chain.push(sub);
564
+ }
565
+ return { chain, words, rest };
566
+ }
567
+
568
+ /** pflag's parse of the final command's arguments, with its error texts. */
569
+ function parseFlags(flags: Flag[], args: string[]): { seen: Flag[]; positionals: string[] } {
570
+ const seen: Flag[] = [];
571
+ const positionals: string[] = [];
572
+ let dashdash = false;
573
+ for (let i = 0; i < args.length;) {
574
+ const s = args[i++]!;
575
+ if (dashdash || s.length < 2 || !s.startsWith('-')) {
576
+ positionals.push(s);
577
+ continue;
578
+ }
579
+ if (s === '--') {
580
+ dashdash = true;
581
+ continue;
582
+ }
583
+ if (s.startsWith('--')) {
584
+ const body = s.slice(2);
585
+ if (body.startsWith('-') || body.startsWith('=')) throw new Error(`bad flag syntax: ${s}`);
586
+ const eq = body.indexOf('=');
587
+ const name = eq < 0 ? body : body.slice(0, eq);
588
+ const f = lookupLong(flags, name);
589
+ if (!f) throw new Error(`unknown flag: --${name}`);
590
+ if (eq < 0 && f.takesValue) {
591
+ if (i >= args.length) throw new Error(`flag needs an argument: ${s}`);
592
+ i++;
593
+ }
594
+ seen.push(f);
595
+ continue;
596
+ }
597
+ const shorthands = s.slice(1);
598
+ for (let j = 0; j < shorthands.length; j++) {
599
+ const c = shorthands[j]!;
600
+ const f = lookupShort(flags, c);
601
+ if (!f) throw new Error(`unknown shorthand flag: '${c}' in -${shorthands}`);
602
+ seen.push(f);
603
+ const rest = shorthands.slice(j + 1);
604
+ if (rest.startsWith('=')) break;
605
+ if (!f.takesValue) continue;
606
+ if (rest === '') {
607
+ if (i >= args.length) throw new Error(`flag needs an argument: '${c}' in -${shorthands}`);
608
+ i++;
609
+ }
610
+ break;
611
+ }
612
+ }
613
+ return { seen, positionals };
614
+ }
615
+
616
+ interface FlagCheck {
617
+ flag?: Flag;
618
+ args: string[];
619
+ toComplete: string;
620
+ error?: string;
621
+ }
622
+
623
+ /** cobra `checkIfFlagCompletion`: is the word the value of a flag? */
624
+ function checkFlagCompletion(cmd: Command, flags: Flag[], args: string[], last: string): FlagCheck {
625
+ let name = '';
626
+ let trimmed = args;
627
+ let withEqual = false;
628
+ let value = last;
629
+ if (last.startsWith('-')) {
630
+ const idx = last.indexOf('=');
631
+ if (idx < 0) return { args, toComplete: last };
632
+ // The last shorthand of a cluster: `-asd=` completes `d`.
633
+ name = last.startsWith('--') ? last.slice(2, idx) : last.slice(0, idx).slice(-1);
634
+ value = last.slice(idx + 1);
635
+ withEqual = true;
636
+ }
637
+ if (name === '' && args.length > 0) {
638
+ const prev = args[args.length - 1]!;
639
+ if (isFlagArg(prev) && !prev.includes('=')) {
640
+ name = prev.startsWith('--') ? prev.slice(2) : prev.slice(-1);
641
+ trimmed = args.slice(0, -1);
642
+ }
643
+ }
644
+ if (name === '') return { args: trimmed, toComplete: value };
645
+ // cobra `findFlag`: a one-letter name is a shorthand first.
646
+ const flag = (name.length === 1 ? lookupShort(flags, name) : undefined) ?? lookupLong(flags, name);
647
+ if (!flag) {
648
+ return {
649
+ args, toComplete: last,
650
+ error: `Subcommand '${cmd.name()}' does not support flag '${name}'`,
651
+ };
652
+ }
653
+ // A boolean flag takes no value: complete the word as an argument.
654
+ if (!withEqual && !flag.takesValue) return { args, toComplete: value };
655
+ return { flag, args: trimmed, toComplete: value };
656
+ }
657
+
658
+ /** Inherited first, then own, each sorted by name (pflag's visit order). */
659
+ function orderedFlags(flags: Flag[]): Flag[] {
660
+ const byName = (a: Flag, b: Flag) => {
661
+ const x = flagName(a);
662
+ const y = flagName(b);
663
+ return x < y ? -1 : x > y ? 1 : 0;
664
+ };
665
+ return [
666
+ ...flags.filter(f => f.inherited).sort(byName),
667
+ ...flags.filter(f => !f.inherited).sort(byName),
668
+ ];
669
+ }
670
+
671
+ /** `--long<TAB>usage` and `-s<TAB>usage` when they match; nothing for a hidden flag. */
672
+ function flagNameCompletions(f: Flag, toComplete: string): string[] {
673
+ if (f.hidden) return [];
674
+ const out: string[] = [];
675
+ if (f.long && `--${f.long}`.startsWith(toComplete)) out.push(`--${f.long}\t${f.usage}`);
676
+ if (f.short && `-${f.short}`.startsWith(toComplete)) out.push(`-${f.short}\t${f.usage}`);
677
+ return out;
678
+ }
679
+
680
+ function requiredFlags(flags: Flag[], seen: Flag[], toComplete: string): string[] {
681
+ return orderedFlags(flags)
682
+ .filter(f => f.required && !seen.includes(f))
683
+ .flatMap(f => flagNameCompletions(f, toComplete));
684
+ }
685
+
686
+ /** The choices of the positional at index `n`, the variadic last one covering the rest. */
687
+ function positionalChoices(cmd: Command, n: number): readonly string[] | undefined {
688
+ const args = cmd.registeredArguments;
689
+ const last = args[args.length - 1];
690
+ const a = args[n] ?? (last?.variadic ? last : undefined);
691
+ return a?.argChoices;
692
+ }
693
+
694
+ interface Outcome {
695
+ completions: string[];
696
+ directive: number;
697
+ error?: string;
698
+ }
699
+
700
+ async function getCompletions(root: Command, args: string[]): Promise<Outcome> {
701
+ const toCompleteRaw = args.length ? args[args.length - 1]! : '';
702
+ const { chain, words, rest } = find(root, args.slice(0, -1));
703
+ const cmd = chain[chain.length - 1]!;
704
+ const flags = flagsOf(root, chain);
705
+
706
+ const fc = checkFlagCompletion(cmd, flags, rest, toCompleteRaw);
707
+ const { flag, toComplete } = fc;
708
+ // A `--` already on the line turns later dash words into arguments.
709
+ const flagCompletion = !fc.args.includes('--');
710
+ let parsed;
711
+ try {
712
+ parsed = parseFlags(flags, fc.args);
713
+ } catch (e) {
714
+ return {
715
+ completions: [], directive: ShellCompDirective.Default,
716
+ error: `Error while parsing flags from args [${fc.args.join(' ')}]: ${(e as Error).message}`,
717
+ };
718
+ }
719
+ if (fc.error && flagCompletion) {
720
+ return { completions: [], directive: ShellCompDirective.Default, error: fc.error };
721
+ }
722
+ if (parsed.seen.some(f => f.stops)) {
723
+ return { completions: [], directive: ShellCompDirective.NoFileComp };
724
+ }
725
+ const finalArgs = parsed.positionals;
726
+ const ctx: CompletionContext = { commandPath: words.join(' '), args: finalArgs };
727
+
728
+ let completions: string[] = [];
729
+ if (!flag && toComplete.startsWith('-') && !toComplete.includes('=') && flagCompletion) {
730
+ completions = requiredFlags(flags, parsed.seen, toComplete);
731
+ if (completions.length === 0) {
732
+ for (const f of orderedFlags(flags)) {
733
+ if (!parsed.seen.includes(f) || f.multi) completions.push(...flagNameCompletions(f, toComplete));
734
+ }
735
+ }
736
+ const noSpace = completions.length === 1 && completions[0]!.endsWith('=');
737
+ return {
738
+ completions,
739
+ directive: noSpace ? ShellCompDirective.NoSpace : ShellCompDirective.NoFileComp,
740
+ };
741
+ }
742
+
743
+ let directive: number = ShellCompDirective.Default;
744
+ if (!flag) {
745
+ const localGiven = parsed.seen.some(f => !f.inherited);
746
+ if (finalArgs.length === 0 && !localGiven) {
747
+ const subs = cmd.commands
748
+ .filter(s => !internals(s)._hidden && !(s as Tagged)[BUILTIN])
749
+ .sort((a, b) => (a.name() < b.name() ? -1 : a.name() > b.name() ? 1 : 0));
750
+ for (const s of subs) {
751
+ if (s.name().startsWith(toComplete)) {
752
+ completions.push(`${s.name()}\t${s.summary() || s.description()}`);
753
+ }
754
+ directive = ShellCompDirective.NoFileComp;
755
+ }
756
+ }
757
+ completions.push(...requiredFlags(flags, parsed.seen, toComplete));
758
+
759
+ // Positional choices play cobra's ValidArgs: they win over a binding.
760
+ const choices = positionalChoices(cmd, finalArgs.length);
761
+ if (choices?.length) {
762
+ completions.push(...choices.filter(v => v.startsWith(toComplete)));
763
+ return { completions, directive: ShellCompDirective.NoFileComp };
764
+ }
765
+ }
766
+
767
+ const result = flag && flagCompletion
768
+ ? await flagValueCompletion(flag, ctx, toComplete)
769
+ : await argsCompletion(root, cmd, ctx, toComplete);
770
+ if (result) {
771
+ completions.push(...result.completions);
772
+ directive = result.directive;
773
+ }
774
+ return { completions, directive };
775
+ }
776
+
777
+ /** The completer bound to `flag`, else its choices; null when neither exists. */
778
+ async function flagValueCompletion(flag: Flag, ctx: CompletionContext, toComplete: string) {
779
+ const bound = (flag.owner as Tagged)[FLAG_COMPLETERS]?.get(flagName(flag));
780
+ if (bound) return resolveCompletions(bound, toComplete, ctx);
781
+ if (!flag.choices?.length) return null;
782
+ const lower = toComplete.toLowerCase();
783
+ return {
784
+ completions: flag.choices.filter(v => v.toLowerCase().startsWith(lower)),
785
+ directive: ShellCompDirective.NoFileComp,
786
+ };
787
+ }
788
+
789
+ /** The completer bound to `cmd`'s positionals, plus root aliases at the root. */
790
+ async function argsCompletion(root: Command, cmd: Command, ctx: CompletionContext, toComplete: string) {
791
+ const bound = (cmd as Tagged)[ARGS_COMPLETER];
792
+ const aliases = cmd === root ? rootAliases(root) : new Map<string, string>();
793
+ if (!bound && aliases.size === 0) return null;
794
+ const r = bound
795
+ ? await resolveCompletions(bound, toComplete, ctx)
796
+ : { completions: [] as string[], directive: ShellCompDirective.Default as number };
797
+ if (aliases.size > 0) {
798
+ r.directive |= ShellCompDirective.NoFileComp;
799
+ for (const [name, target] of [...aliases].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
800
+ if (name.startsWith(toComplete)) r.completions.push(`${name}\talias for ${target}`);
801
+ }
802
+ }
803
+ return r;
158
804
  }