@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
@@ -0,0 +1,94 @@
1
+ import { DeprecationWarning } from "../resolve/contracts.mjs";
2
+ import { CommandMeta, CommandSchema, Out } from "../schema/command.mjs";
3
+
4
+ //#region src/core/cli/plugin.d.ts
5
+ /** Shared hook payload for a concrete command execution. */
6
+ interface PluginCommandContext {
7
+ /** Runtime command schema being executed. */
8
+ readonly command: CommandSchema;
9
+ /** CLI metadata for this execution. */
10
+ readonly meta: CommandMeta;
11
+ /** Output channel for this execution. */
12
+ readonly out: Out;
13
+ }
14
+ /** Payload for `beforeParse`. */
15
+ interface BeforeParseParams extends PluginCommandContext {
16
+ /** Raw argv that will be parsed for the leaf command. */
17
+ readonly argv: readonly string[];
18
+ }
19
+ /** Payload for hooks that observe resolved inputs. */
20
+ interface ResolvedCommandParams extends PluginCommandContext {
21
+ /** Fully resolved flag values. */
22
+ readonly flags: Readonly<Record<string, unknown>>;
23
+ /** Fully resolved argument values. */
24
+ readonly args: Readonly<Record<string, unknown>>;
25
+ /** Structured deprecation warnings collected during resolution. */
26
+ readonly deprecations: readonly DeprecationWarning[];
27
+ }
28
+ /**
29
+ * Individual lifecycle hooks that a plugin may implement.
30
+ *
31
+ * Hook order for a successful command run is:
32
+ * `beforeParse` → `afterResolve` → `beforeAction` → middleware/action → `afterAction`.
33
+ *
34
+ * Hooks are awaited serially and run in plugin registration order at each
35
+ * stage. Throwing from any hook aborts the command just like throwing from
36
+ * middleware or the action handler. `afterAction` runs only after the
37
+ * middleware chain and action complete successfully.
38
+ */
39
+ interface CLIPluginHooks {
40
+ /** Called immediately before leaf-command argv is parsed. */
41
+ readonly beforeParse?: (params: BeforeParseParams) => void | Promise<void>;
42
+ /** Called after parse + resolve, before middleware or action execution. */
43
+ readonly afterResolve?: (params: ResolvedCommandParams) => void | Promise<void>;
44
+ /** Called immediately before the middleware chain and action handler run. */
45
+ readonly beforeAction?: (params: ResolvedCommandParams) => void | Promise<void>;
46
+ /** Called after the middleware chain and action handler complete successfully. */
47
+ readonly afterAction?: (params: ResolvedCommandParams) => void | Promise<void>;
48
+ }
49
+ /**
50
+ * Immutable plugin definition registered via `CLIBuilder.plugin()`.
51
+ *
52
+ * Use {@link plugin} to construct values of this shape instead of manually
53
+ * assembling the object.
54
+ */
55
+ interface CLIPlugin {
56
+ /** Optional label for diagnostics and debugging. */
57
+ readonly name: string | undefined;
58
+ /** Lifecycle hooks implemented by the plugin. */
59
+ readonly hooks: CLIPluginHooks;
60
+ }
61
+ /**
62
+ * Create a CLI plugin from lifecycle hooks.
63
+ *
64
+ * @param hooks - Lifecycle hooks to register.
65
+ * @param name - Optional plugin name for diagnostics.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * import { cli, command, plugin } from '@kjanat/dreamcli';
70
+ *
71
+ * const deploy = command('deploy').action(({ out }) => {
72
+ * out.log('deploying');
73
+ * });
74
+ *
75
+ * const trace = plugin(
76
+ * {
77
+ * beforeParse: ({ argv, out }) => {
78
+ * out.info(`argv: ${argv.join(' ')}`);
79
+ * },
80
+ * afterResolve: ({ flags, args }) => {
81
+ * console.log({ flags, args });
82
+ * },
83
+ * },
84
+ * 'trace',
85
+ * );
86
+ *
87
+ * cli('mycli').plugin(trace).command(deploy).run();
88
+ * ```
89
+ *
90
+ * @returns A frozen {@link CLIPlugin} definition.
91
+ */
92
+ declare function plugin(hooks: CLIPluginHooks, name?: string): CLIPlugin;
93
+ //#endregion
94
+ export { type BeforeParseParams, type CLIPlugin, type CLIPluginHooks, type PluginCommandContext, type ResolvedCommandParams, plugin };
@@ -0,0 +1 @@
1
+ function e(e,t){let n=Object.freeze({...e});return Object.freeze({hooks:n,name:t})}export{e as plugin};
@@ -0,0 +1,39 @@
1
+ import { FlagSchema } from "../schema/flag.mjs";
2
+ import { CommandSchema } from "../schema/command.mjs";
3
+
4
+ //#region src/core/cli/propagate.d.ts
5
+ /**
6
+ * Collect propagated flags from a command path.
7
+ *
8
+ * The command path is an ordered array of {@linkcode CommandSchema} from the root
9
+ * ancestor to the target command that will actually execute. Each ancestor's
10
+ * flags marked `propagate: true` are accumulated. If a descendant (including
11
+ * the target) defines a flag with the same name — regardless of whether the
12
+ * descendant's flag has `propagate: true` — it shadows the ancestor's flag.
13
+ *
14
+ * The target command's own flags are **not** included in the result. This
15
+ * function returns only the *inherited* propagated flags that should be merged
16
+ * into the target command's flag set before resolution.
17
+ *
18
+ * @param commandPath - Ordered schemas from root ancestor to target (inclusive).
19
+ * Must contain at least one element (the target itself). When the path has
20
+ * only one element, no ancestors exist and the result is empty.
21
+ *
22
+ * @returns A record of propagated flag schemas keyed by flag name. Empty when
23
+ * the path has no ancestors or no ancestor flags have `propagate: true`.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * // Given: root (--verbose [propagate]) → db → migrate
28
+ * // Where migrate does NOT define --verbose
29
+ * const inherited = collectPropagatedFlags([rootSchema, dbSchema, migrateSchema]);
30
+ * // inherited = { verbose: <FlagSchema from root> }
31
+ *
32
+ * // If db also defines --verbose (shadowing root):
33
+ * const inherited2 = collectPropagatedFlags([rootSchema, dbSchemaWithVerbose, migrateSchema]);
34
+ * // inherited2 = { verbose: <FlagSchema from db> }
35
+ * ```
36
+ */
37
+ declare function collectPropagatedFlags(commandPath: readonly CommandSchema[]): Readonly<Record<string, FlagSchema>>;
38
+ //#endregion
39
+ export { collectPropagatedFlags };
@@ -0,0 +1 @@
1
+ function e(e){if(e.length<=1)return{};let t={};for(let n=0;n<e.length-1;n++){let r=e[n];if(r!==void 0){for(let[i,a]of Object.entries(r.flags))if(a.propagate){let r=!1;for(let t=n+1;t<e.length-1;t++){let n=e[t];if(n!==void 0&&i in n.flags){r=!0;break}}r||(t[i]=a)}}}let n=e[e.length-1];if(n!==void 0)for(let e of Object.keys(n.flags))delete t[e];return t}export{e as collectPropagatedFlags};
@@ -0,0 +1,28 @@
1
+ import { HelpOptions } from "../help/index.mjs";
2
+ import { CommandSchema } from "../schema/command.mjs";
3
+
4
+ //#region src/core/cli/root-help.d.ts
5
+ /** Structural subset of `CLISchema` — avoids circular imports through the barrel. */
6
+ interface CLISchemaLike {
7
+ readonly name: string;
8
+ readonly version: string | undefined;
9
+ readonly description: string | undefined;
10
+ readonly commands: ReadonlyArray<{
11
+ readonly schema: CommandSchema;
12
+ }>;
13
+ readonly defaultCommand: {
14
+ readonly schema: CommandSchema;
15
+ } | undefined;
16
+ }
17
+ /**
18
+ * Generate root-level help text for the CLI program.
19
+ *
20
+ * Shows program name, version, description, usage line, and available
21
+ * commands. When the default command is the only visible top-level
22
+ * command, merges the root summary with that command's detailed help.
23
+ *
24
+ * @internal
25
+ */
26
+ declare function formatRootHelp(schema: CLISchemaLike, options?: HelpOptions): string;
27
+ //#endregion
28
+ export { formatRootHelp };
@@ -0,0 +1,7 @@
1
+ import{resolveRootSurface as e}from"./root-surface.mjs";import{formatHelpSections as t}from"../help/index.mjs";function n(n,a){let s=a?.width??80,c=e(n);if(c.hasSingleVisibleDefault){let e=c.visibleDefaultCommand;if(e!==void 0){let i=r(n,c.visibleCommands,c.visibleDefaultCommand,s),l=i.findIndex(e=>e.startsWith(`Usage: `)),u=[...t(e,{...a,binName:n.name,isDefaultHelp:!0})],d=u.shift();return l!==-1&&d!==void 0&&(i[l]=o(i[l]??``,d)),e.description!==void 0&&n.description!==void 0&&e.description===n.description&&u.shift(),i.push(...u),`${i.join(`
2
+
3
+ `)}\n`}}let l=r(n,c.visibleCommands,c.visibleDefaultCommand,s),u=i(c.visibleCommands,c.visibleDefaultCommand);return l.push(u.length>0?`Run '${n.name} ${u} --help' for more information.`:`Run '${n.name} --help' for more information.`),`${l.join(`
4
+
5
+ `)}\n`}function r(e,t,n,r){let o=[],s=e.version===void 0?e.name:`${e.name} v${e.version}`;o.push(s),e.description!==void 0&&o.push(e.description);let c=i(t,n);return o.push(c.length>0?`Usage: ${e.name} ${c} [options]`:`Usage: ${e.name} [options]`),t.length>0&&o.push(a(t,n?.name,r)),o}function i(e,t){return e.length===0&&t===void 0?``:t===void 0?`<command>`:`[command]`}function a(e,t,n){let r=[`Commands:`],i=0;for(let n of e){let e=n.name===t?10:0,r=n.name.length+e;r>i&&(i=r)}let a=2+i+2;for(let i of e){let e=s(` ${i.name===t?`${i.name} (default)`:i.name}`,a),o=i.description??``;o.length===0?r.push(e.trimEnd()):r.push(`${e}${c(o,n,a)}`)}return r.join(`
6
+ `)}function o(e,t){let n=t.startsWith(`Usage: `)?t.slice(7):t;return`${e}\n${` `.repeat(7)}${n}`}function s(e,t){return e.length>=t?e:e+` `.repeat(t-e.length)}function c(e,t,n){if(e.length+n<=t)return e;let r=t-n;if(r<=0)return e;let i=e.split(` `),a=[],o=``;for(let e of i)o.length===0?o=e:o.length+1+e.length<=r?o+=` ${e}`:(a.push(o),o=e);o.length>0&&a.push(o);let s=` `.repeat(n);return a.map((e,t)=>t===0?e:`${s}${e}`).join(`
7
+ `)}export{n as formatRootHelp};
@@ -0,0 +1,42 @@
1
+ import { CommandSchema } from "../schema/command.mjs";
2
+
3
+ //#region src/core/cli/root-surface.d.ts
4
+ /**
5
+ * Structural CLI shape needed for root-surface analysis.
6
+ *
7
+ * Uses structural typing to avoid importing the full `CLISchema` and
8
+ * creating unnecessary cross-module coupling.
9
+ *
10
+ * @internal
11
+ */
12
+ interface RootSurfaceSchemaLike {
13
+ readonly commands: ReadonlyArray<{
14
+ readonly schema: CommandSchema;
15
+ }>;
16
+ readonly defaultCommand: {
17
+ readonly schema: CommandSchema;
18
+ } | undefined;
19
+ }
20
+ /**
21
+ * Normalized root shape shared by help and completion logic.
22
+ *
23
+ * @internal
24
+ */
25
+ interface RootSurface {
26
+ readonly visibleCommands: readonly CommandSchema[];
27
+ readonly visibleDefaultCommand: CommandSchema | undefined;
28
+ readonly hasSingleVisibleDefault: boolean;
29
+ readonly hasVisibleSiblingCommands: boolean;
30
+ }
31
+ /**
32
+ * Resolve the visible shape of the CLI root.
33
+ *
34
+ * Hidden commands are excluded from the visible command list. Hidden
35
+ * default commands remain executable, but are not surfaced through
36
+ * help or completions.
37
+ *
38
+ * @internal
39
+ */
40
+ declare function resolveRootSurface(schema: RootSurfaceSchemaLike): RootSurface;
41
+ //#endregion
42
+ export { type RootSurface, type RootSurfaceSchemaLike, resolveRootSurface };
@@ -0,0 +1 @@
1
+ function e(e){let t=e.commands.map(e=>e.schema).filter(e=>!e.hidden),n=e.defaultCommand?.schema,r=n!==void 0&&!n.hidden?n:void 0;return{visibleCommands:t,visibleDefaultCommand:r,hasSingleVisibleDefault:r!==void 0&&t.length===1&&t[0]?.name===r.name,hasVisibleSiblingCommands:r!==void 0&&t.some(e=>e.name!==r.name)}}export{e as resolveRootSurface};
@@ -0,0 +1,149 @@
1
+ import { Verbosity } from "../output/contracts.mjs";
2
+ import { PromptEngine } from "../prompt/index.mjs";
3
+ import { CLIPlugin } from "./plugin.mjs";
4
+ import { CLIError } from "../errors/index.mjs";
5
+ import { CommandSchema, ErasedCommand } from "../schema/command.mjs";
6
+ import { RuntimeAdapter } from "../../runtime/adapter.mjs";
7
+ import { FormatLoader } from "../config/index.mjs";
8
+
9
+ //#region src/core/cli/runtime-preflight.d.ts
10
+ /** Config discovery settings extracted from CLISchema for preflight use. @internal */
11
+ interface RuntimeConfigSettings {
12
+ /** Application name used to locate config files (e.g. `~/.config/<appName>/`). */
13
+ readonly appName: string;
14
+ /** Optional format loaders (JSON/YAML/TOML); `undefined` uses built-in JSON. */
15
+ readonly loaders: readonly FormatLoader[] | undefined;
16
+ }
17
+ /** Package.json discovery settings extracted from CLISchema. @internal */
18
+ interface RuntimePackageJsonSettings {
19
+ /** Whether to infer the CLI binary name from `package.json` `bin` field. */
20
+ readonly inferName: boolean;
21
+ }
22
+ /**
23
+ * Structural subset of CLISchema used by runtime preflight.
24
+ *
25
+ * Decouples adapter-driven sourcing (config, package.json, stdin) from the
26
+ * full CLIBuilder surface so preflight can be tested independently.
27
+ * @internal
28
+ */
29
+ interface RuntimePreflightSchemaLike {
30
+ /** CLI program name; may be overridden by package.json discovery or inheritance. */
31
+ readonly name: string;
32
+ /** Whether this CLI inherits its name from a parent (nested CLI embedding). */
33
+ readonly inheritName: boolean;
34
+ /** Declared version; `undefined` means version will be inferred from package.json if available. */
35
+ readonly version: string | undefined;
36
+ /** Declared description; `undefined` allows package.json inference. */
37
+ readonly description: string | undefined;
38
+ /** Registered top-level commands for dispatch planning during stdin detection. */
39
+ readonly commands: readonly ErasedCommand[];
40
+ /** Fallback command when no subcommand token matches. */
41
+ readonly defaultCommand: ErasedCommand | undefined;
42
+ /** Config file discovery settings; `undefined` disables config loading. */
43
+ readonly configSettings: RuntimeConfigSettings | undefined;
44
+ /** Package.json discovery settings; `undefined` disables package.json inference. */
45
+ readonly packageJsonSettings: RuntimePackageJsonSettings | undefined;
46
+ /** Whether `.completions()` registered the built-in completions command. */
47
+ readonly hasBuiltInCompletions: boolean;
48
+ /** Plugins forwarded into the execution pipeline. */
49
+ readonly plugins: readonly CLIPlugin[];
50
+ }
51
+ /**
52
+ * Caller-supplied overrides for runtime preflight.
53
+ *
54
+ * When provided, these bypass adapter auto-detection (useful for testing
55
+ * and the `CLIRunOptions` public surface).
56
+ * @internal
57
+ */
58
+ interface RuntimePreflightOptions {
59
+ /** Environment variables override; bypasses adapter env when set. */
60
+ readonly env?: Readonly<Record<string, string | undefined>>;
61
+ /** Pre-loaded config object; skips config file discovery when set. */
62
+ readonly config?: Readonly<Record<string, unknown>>;
63
+ /** Pre-read stdin data; `null` means stdin was explicitly empty. */
64
+ readonly stdinData?: string | null;
65
+ /** Custom prompt engine; bypasses terminal prompter auto-creation. */
66
+ readonly prompter?: PromptEngine;
67
+ /** Output verbosity level override. */
68
+ readonly verbosity?: Verbosity;
69
+ /** Force JSON output mode regardless of `--json` flag presence. */
70
+ readonly jsonMode?: boolean;
71
+ /** TTY detection override; bypasses adapter TTY check. */
72
+ readonly isTTY?: boolean;
73
+ }
74
+ /**
75
+ * Fully resolved runtime inputs ready for the execution pipeline.
76
+ *
77
+ * All adapter vs. caller-override decisions are settled by the time this
78
+ * is constructed; the executor treats these as final truth.
79
+ * @internal
80
+ */
81
+ interface RuntimeExecutionInputs {
82
+ /** Resolved environment variables (from adapter or caller override). */
83
+ readonly env: Readonly<Record<string, string | undefined>>;
84
+ /** Whether stdout is a TTY (controls color, spinners, interactive prompts). */
85
+ readonly isTTY: boolean;
86
+ /** Whether structured JSON output mode is active. */
87
+ readonly jsonMode: boolean;
88
+ /** Output verbosity level. */
89
+ readonly verbosity: Verbosity;
90
+ /** Pre-read stdin data if the invocation declared stdin-mode args. */
91
+ readonly stdinData?: string | null;
92
+ /** Prompt engine for interactive flag resolution; absent in non-TTY. */
93
+ readonly prompter?: PromptEngine;
94
+ /** Loaded config data for the config resolution step. */
95
+ readonly config?: Readonly<Record<string, unknown>>;
96
+ }
97
+ /** Preflight succeeded — all runtime inputs are resolved and ready for execution. @internal */
98
+ interface ReadyRuntimePreflight {
99
+ /** Discriminant — preflight completed without errors. */
100
+ readonly kind: 'ready';
101
+ /** Schema after package.json discovery and name inheritance applied. */
102
+ readonly schema: RuntimePreflightSchemaLike;
103
+ /** Argv with valid runtime `--config` tokens stripped out. */
104
+ readonly filteredArgv: readonly string[];
105
+ /** Fully resolved runtime inputs for the execution pipeline. */
106
+ readonly inputs: RuntimeExecutionInputs;
107
+ }
108
+ /** Preflight failed during config file discovery/loading. @internal */
109
+ interface RuntimeConfigErrorPreflight {
110
+ /** Discriminant — config loading produced a structured error. */
111
+ readonly kind: 'config-error';
112
+ /** The config discovery/parse error to render. */
113
+ readonly error: CLIError;
114
+ /** Whether JSON output was requested (needed to choose error rendering). */
115
+ readonly jsonMode: boolean;
116
+ }
117
+ /** Discriminated union of preflight outcomes — either ready or config-error. @internal */
118
+ type RuntimePreflightResult = ReadyRuntimePreflight | RuntimeConfigErrorPreflight;
119
+ /** Options bag for {@linkcode prepareRuntimePreflight}. @internal */
120
+ interface PrepareRuntimePreflightOptions {
121
+ /** CLI schema subset driving preflight decisions. */
122
+ readonly schema: RuntimePreflightSchemaLike;
123
+ /** Runtime adapter providing argv, env, stdin, and filesystem access. */
124
+ readonly adapter: RuntimeAdapter;
125
+ /** Caller-supplied overrides; `undefined` means auto-detect everything. */
126
+ readonly options: RuntimePreflightOptions | undefined;
127
+ /** Name inherited from a parent CLI (nested embedding); `undefined` for standalone. */
128
+ readonly inheritedName: string | undefined;
129
+ }
130
+ /** Extract and strip valid runtime `--config` forms from argv, returning path + filtered tokens. @internal */
131
+ declare function extractConfigFlag(argv: readonly string[]): {
132
+ readonly configPath: string | undefined;
133
+ readonly filteredArgv: readonly string[];
134
+ };
135
+ /** Check whether a single command's args declare stdin-mode and argv leaves them unresolved. @internal */
136
+ declare function commandInvocationNeedsStdin(schema: CommandSchema, argv: readonly string[]): boolean;
137
+ /** Plan the invocation and check whether the matched command needs stdin data. @internal */
138
+ declare function invocationNeedsStdin(schema: RuntimePreflightSchemaLike, argv: readonly string[]): boolean;
139
+ /**
140
+ * Run all adapter-driven sourcing work before command execution.
141
+ *
142
+ * Discovers config files, reads package.json metadata, detects stdin needs,
143
+ * wires up the prompt engine, and resolves output policy overrides into a
144
+ * single {@linkcode RuntimePreflightResult}.
145
+ * @internal
146
+ */
147
+ declare function prepareRuntimePreflight(options: PrepareRuntimePreflightOptions): Promise<RuntimePreflightResult>;
148
+ //#endregion
149
+ export { type PrepareRuntimePreflightOptions, type ReadyRuntimePreflight, type RuntimeExecutionInputs, type RuntimePreflightOptions, type RuntimePreflightResult, type RuntimePreflightSchemaLike, commandInvocationNeedsStdin, extractConfigFlag, invocationNeedsStdin, prepareRuntimePreflight };
@@ -0,0 +1 @@
1
+ import{CLIError as e,ParseError as t}from"../errors/index.mjs";import{parse as n}from"../parse/index.mjs";import{createTerminalPrompter as r}from"../prompt/index.mjs";import{planInvocation as i}from"./planner.mjs";import{discoverPackageJson as a,inferCliName as o}from"../config/package-json.mjs";import{discoverConfig as s}from"../config/index.mjs";const c={jsonMode:!1,isTTY:!1,verbosity:`normal`};function l(e){let t=[],n;for(let r=0;r<e.length;r+=1){let i=e[r];if(i!==void 0){if(i===`--`){t.push(...e.slice(r));break}if(n===void 0&&i.startsWith(`--config=`)){let e=i.slice(9);if(e.length>0){n=e;continue}t.push(i);continue}if(n===void 0&&i===`--config`){let a=e[r+1];if(a!==void 0&&!a.startsWith(`-`)&&a!==`--`){n=a,r+=1;continue}t.push(i);continue}t.push(i)}}return{configPath:n,filteredArgv:t}}function u(e,r){if(r.includes(`--help`)||r.includes(`-h`))return!1;try{let t=n(e,r);return e.args.some(({name:e,schema:n})=>{let r=t.args[e];return n.stdinMode&&(r===void 0||r===`-`)})}catch(e){if(e instanceof t)return!1;throw e}}function d(e,t){let n=i({schema:e,argv:t,help:{binName:e.name},output:c});switch(n.kind){case`match`:return u(n.plan.mergedSchema,n.plan.argv);case`dispatch-error`:case`needs-subcommand`:case`root-help`:case`root-version`:return!1}}function f(e,t){if(!e.hasBuiltInCompletions)return!1;let n=i({schema:e,argv:t,help:{binName:e.name},output:c});return n.kind===`match`&&n.plan.command.schema.name===`completions`}async function p(e,t,n,r){let i=e.packageJsonSettings,s=i!==void 0&&!r?await(async()=>{let n=await a(t);if(n===null)return e;let r=i.inferName?o(n):void 0;return{...e,...e.version===void 0&&n.version!==void 0?{version:n.version}:{},...e.description===void 0&&n.description!==void 0?{description:n.description}:{},...r===void 0?{}:{name:r}}})():e;return n===void 0?s:{...s,name:n}}async function m(t,n,r,i,a){if(t.configSettings===void 0||i||a!==void 0)return a;try{let e=await s(t.configSettings.appName,n,{...r===void 0?{}:{configPath:r},...t.configSettings.loaders===void 0?{}:{loaders:t.configSettings.loaders}});return e.found?e.data:void 0}catch(t){if(t instanceof e)return t;throw t}}async function h(t){let n=t.adapter.argv.slice(2),{configPath:i,filteredArgv:a}=t.schema.configSettings===void 0?{configPath:void 0,filteredArgv:n}:l(n),o=a.includes(`--json`)||t.options?.jsonMode===!0,s=f(t.schema,a),c=await p(t.schema,t.adapter,t.inheritedName,s),u=await m(c,t.adapter,i,s,t.options?.config);if(u instanceof e)return{kind:`config-error`,error:u,jsonMode:o};let h=t.options?.prompter===void 0&&t.adapter.stdinIsTTY?r(t.adapter.stdin,t.adapter.stderr):void 0,g=t.options?.stdinData===void 0&&d(c,a)?await t.adapter.readStdin():t.options?.stdinData;return{kind:`ready`,schema:c,filteredArgv:a,inputs:{env:t.options?.env??t.adapter.env,isTTY:t.options?.isTTY??t.adapter.isTTY,jsonMode:o,verbosity:t.options?.verbosity??`normal`,...g===void 0?{}:{stdinData:g},...t.options?.prompter===void 0?h===void 0?{}:{prompter:h}:{prompter:t.options.prompter},...u===void 0?{}:{config:u}}}}export{h as prepareRuntimePreflight};
@@ -0,0 +1,46 @@
1
+ import { CompletionOptions } from "./shells/shared.mjs";
2
+ import { generateBashCompletion } from "./shells/bash.mjs";
3
+ import { generateFishCompletion } from "./shells/fish.mjs";
4
+ import { generatePowerShellCompletion } from "./shells/powershell.mjs";
5
+ import { generateZshCompletion } from "./shells/zsh.mjs";
6
+ import { CLISchema } from "../cli/index.mjs";
7
+
8
+ //#region src/core/completion/index.d.ts
9
+ /**
10
+ * Supported shell targets for completion script generation.
11
+ *
12
+ * `bash`, `zsh`, `fish`, and `powershell` are implemented today.
13
+ */
14
+ type Shell = 'bash' | 'zsh' | 'fish' | 'powershell';
15
+ /**
16
+ * Implemented shell values as a frozen readonly non-empty tuple.
17
+ *
18
+ * Use this tuple for user-facing validation and shell selection UIs.
19
+ * It intentionally matches the shipped {@link Shell} union exactly so docs,
20
+ * help output, and completion generation advertise the same support surface.
21
+ *
22
+ * @see {@link Shell} for the union type matching these entries.
23
+ */
24
+ declare const SHELLS: Readonly<readonly ['bash', 'zsh', 'fish', 'powershell']>;
25
+ /**
26
+ * Generate a completion script for the given shell.
27
+ *
28
+ * This is the primary completion entrypoint for most consumers. Pass a CLI
29
+ * schema and target shell, then write the returned script to a file or source
30
+ * it directly from the command line.
31
+ *
32
+ * @param schema - The CLI schema describing commands, flags, and args.
33
+ * @param shell - Target shell.
34
+ * @param options - Optional generator configuration such as function naming
35
+ * and root default-command completion behavior.
36
+ * @returns A complete shell completion script as a string.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * const script = generateCompletion(app.schema, 'bash');
41
+ * // e.g. source <(mycli completions bash)
42
+ * ```
43
+ */
44
+ declare function generateCompletion(schema: CLISchema, shell: Shell, options?: CompletionOptions): string;
45
+ //#endregion
46
+ export { type CompletionOptions, SHELLS, type Shell, generateBashCompletion, generateCompletion, generateFishCompletion, generatePowerShellCompletion, generateZshCompletion };
@@ -0,0 +1 @@
1
+ import{generateBashCompletion as e}from"./shells/bash.mjs";import{generateFishCompletion as t}from"./shells/fish.mjs";import{generatePowerShellCompletion as n}from"./shells/powershell.mjs";import{generateZshCompletion as r}from"./shells/zsh.mjs";const i=Object.freeze([`bash`,`zsh`,`fish`,`powershell`]);function a(i,a,o){switch(a){case`bash`:return e(i,o);case`zsh`:return r(i,o);case`fish`:return t(i,o);case`powershell`:return n(i,o)}}export{i as SHELLS,a as generateCompletion};
@@ -0,0 +1,24 @@
1
+ import { CompletionOptions } from "./shared.mjs";
2
+ import { CLISchema } from "../../cli/index.mjs";
3
+
4
+ //#region src/core/completion/shells/bash.d.ts
5
+ /**
6
+ * Generate a bash completion script for the CLI.
7
+ *
8
+ * Use this when you want a bash-specific script directly rather than routing
9
+ * through {@link generateCompletion}. The generated script expects the
10
+ * `bash-completion` package because it relies on `_init_completion`.
11
+ *
12
+ * @param schema - The CLI schema.
13
+ * @param options - Optional generator configuration.
14
+ * @returns A complete bash completion script.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const script = generateBashCompletion(app.schema);
19
+ * // install with: mycli completions bash > /etc/bash_completion.d/mycli
20
+ * ```
21
+ */
22
+ declare function generateBashCompletion(schema: CLISchema, options?: CompletionOptions): string;
23
+ //#endregion
24
+ export { generateBashCompletion };
@@ -0,0 +1,3 @@
1
+ import{getFlagAliasNames as e}from"../../schema/flag.mjs";import{quoteShellArg as t,resolveRootCompletionSurface as n,sanitizeShellIdentifier as r,versionTag as i,walkCommandTree as a}from"./shared.mjs";function o(e,o){let l=`_${r(o?.functionPrefix??e.name)}_completions`,u=n(e,o?.rootMode),p=u.visibleCommands,v=a(p),y=v.reduce((e,t)=>Math.max(e,t.path.length),0),b=[];if(b.push(`#!/usr/bin/env bash`),b.push(`# Bash completion for ${e.name}`),b.push(`# Generated by ${i()}`),b.push(`#`),b.push(`# Usage: source <(${e.name} completions bash)`),b.push(`#`),b.push(`# Install permanently:`),b.push(`# ${e.name} completions bash > /etc/bash_completion.d/${e.name} # Linux`),b.push(`# ${e.name} completions bash > $(brew --prefix)/etc/bash_completion.d/${e.name} # macOS`),b.push(`#`),b.push(`# Requires: bash-completion (provides _init_completion)`),b.push(``),b.push(`${l}() {`),b.push(` local cur prev words cword`),b.push(` _init_completion || return`),b.push(``),p.length>0){let e=v.filter(e=>e.children.length>0),t=h(v,u);b.push(` # Build subcommand path by scanning COMP_WORDS`),b.push(` local subcmd_path=""`),b.push(` local i`),b.push(` for ((i = 1; i < cword; i++)); do`),b.push(' case "${words[i]}" in'),b.push(` --) break ;;`),t.length>0&&b.push(`\t\t\t${t}) ((i++)); continue ;;`),b.push(` -*) continue ;;`),b.push(` esac`),s(b,p,e,y),b.push(` done`),b.push(``),b.push(` # Complete flags and subcommands for the active path`),b.push(` case "$subcmd_path" in`);for(let e of v){let t=e.path.join(` `),n=e.mergedFlags,r=_(n),i=m(n),a=g(e.children.flatMap(e=>[e.name,...e.aliases])).map(d).join(` `),o=i.split(` `).filter(Boolean).map(d).join(` `),s=a.length>0?`${a} ${o}`:o;if(b.push(`\t\t${c(t)})`),r.length>0){b.push(` local enum_flag=""`),b.push(` local enum_cur="$cur"`),b.push(` local enum_prefix=""`),b.push(` if [[ "$cur" == --*=* ]]; then`),b.push(' enum_flag="${cur%%=*}"'),b.push(' enum_cur="${cur#*=}"'),b.push(' enum_prefix="${cur%%=*}="'),b.push(` fi`),b.push(' case "${enum_flag:-$prev}" in');for(let e of r)b.push(`\t\t\t\t${e.flags})`),b.push(f(e.values,` `,`enum_cur`,`enum_prefix`)),b.push(` return`),b.push(` ;;`);b.push(` *)`),b.push(` ;;`),b.push(` esac`)}b.push(`\t\t\tCOMPREPLY=($(compgen -W '${s.trim()}' -- "$cur"))`),b.push(` return`),b.push(` ;;`)}b.push(` *)`),b.push(` ;;`),b.push(` esac`),b.push(``);let n=m(u.rootFlags).split(` `).filter(Boolean),r=u.includeDefaultFlags?m(u.defaultFlags).split(` `).filter(Boolean):[],i=g([...p.flatMap(e=>[e.name,...e.aliases]),...n,...r]).map(d).join(` `);b.push(` # Root-level completions: visible root surface`),b.push(`\tCOMPREPLY=($(compgen -W '${i}' -- "$cur"))`)}else{let e=m(u.rootFlags);b.push(`\tCOMPREPLY=($(compgen -W '${e}' -- "$cur"))`)}return b.push(`}`),b.push(``),b.push(`complete -F ${l} ${t(e.name)}`),b.push(``),b.join(`
2
+ `)}function s(e,t,n,r){e.push(` case "$subcmd_path" in`),e.push(` '')`),e.push(' case "${words[i]}" in');for(let n of t){let t=[n.name,...n.aliases].map(l);e.push(`\t\t\t\t\t${t.join(`|`)})`),e.push(`\t\t\t\t\t\tsubcmd_path="${u(n.name)}"`),e.push(` ;;`)}if(e.push(` esac`),e.push(` ;;`),r>1)for(let t of n){let n=t.path.join(` `);e.push(`\t\t\t${c(n)})`),e.push(' case "${words[i]}" in');for(let n of t.children){let t=[n.name,...n.aliases].map(l);e.push(`\t\t\t\t\t${t.join(`|`)})`),e.push(`\t\t\t\t\t\tsubcmd_path="$subcmd_path ${u(n.name)}"`),e.push(` ;;`)}e.push(` esac`),e.push(` ;;`)}e.push(` esac`)}function c(e){return e.includes(` `)?`"${u(e)}"`:l(e)}function l(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/"/g,`\\"`).replace(/\|/g,`\\|`).replace(/\*/g,`\\*`).replace(/\?/g,`\\?`).replace(/\[/g,`\\[`).replace(/\]/g,`\\]`).replace(/\(/g,`\\(`).replace(/\)/g,`\\)`).replace(/\{/g,`\\{`).replace(/\}/g,`\\}`).replace(/\+/g,`\\+`).replace(/!/g,`\\!`).replace(/@/g,`\\@`).replace(/#/g,`\\#`).replace(/~/g,`\\~`).replace(/\s/g,e=>e===` `?`\\ `:`\\${e}`)}function u(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\$/g,`\\$`).replace(/`/g,"\\`")}function d(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/'/g,`'\\''`)}function f(e,t,n=`cur`,r){let i=[];if(e.some(e=>!/^[a-zA-Z0-9_\-.]+$/.test(e))){let r=e.map(p).join(`\\n`);i.push(`${t}local IFS=$'\\n'`),i.push(`${t}COMPREPLY=($(compgen -W $'${r}' -- "$${n}"))`)}else i.push(`${t}COMPREPLY=($(compgen -W '${e.join(` `)}' -- "$${n}"))`);return r!==void 0&&(i.push(`${t}if [[ -n "$${r}" && "\${#COMPREPLY[@]}" -gt 0 ]]; then`),i.push(`${t}\tlocal i`),i.push(`${t}\tfor ((i = 0; i < \${#COMPREPLY[@]}; i++)); do`),i.push(`${t}\t\tCOMPREPLY[i]="$${r}\${COMPREPLY[i]}"`),i.push(`${t}\tdone`),i.push(`${t}fi`)),i.join(`
3
+ `)}function p(e){return e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`)}function m(t){let n=[];for(let[r,i]of Object.entries(t)){n.push(`--${r}`);for(let t of e(i))n.push(t.length===1?`-${t}`:`--${t}`)}return n.join(` `)}function h(t,n){let r=new Set,i=t=>{for(let[n,i]of Object.entries(t))if(i.kind!==`boolean`){r.add(`--${n}`);for(let t of e(i,{includeHidden:!0}))r.add(t.length===1?`-${t}`:`--${t}`)}};for(let e of t)i(e.mergedFlags);return i(n.rootFlags),n.includeDefaultFlags&&i(n.defaultFlags),[...r].map(l).join(`|`)}function g(e){return[...new Set(e)]}function _(t){let n=[];for(let[r,i]of Object.entries(t)){if(i.kind!==`enum`||i.enumValues===void 0)continue;let t=[`--${r}`,...e(i,{includeHidden:!0}).map(e=>e.length===1?`-${e}`:`--${e}`)].map(l);n.push({flags:t.join(`|`),values:i.enumValues})}return n}export{o as generateBashCompletion};
@@ -0,0 +1,20 @@
1
+ import { CompletionOptions } from "./shared.mjs";
2
+ import { CLISchema } from "../../cli/index.mjs";
3
+
4
+ //#region src/core/completion/shells/fish.d.ts
5
+ /**
6
+ * Generate a fish completion script for the CLI.
7
+ *
8
+ * @param schema - The CLI schema.
9
+ * @param options - Optional generator configuration.
10
+ * @returns A complete fish completion script.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * const script = generateFishCompletion(app.schema);
15
+ * // install with: mycli completions fish > ~/.config/fish/completions/mycli.fish
16
+ * ```
17
+ */
18
+ declare function generateFishCompletion(schema: CLISchema, options?: CompletionOptions): string;
19
+ //#endregion
20
+ export { generateFishCompletion };
@@ -0,0 +1,2 @@
1
+ import{getFlagAliasNames as e}from"../../schema/flag.mjs";import{quoteShellArg as t,resolveRootCompletionSurface as n,sanitizeShellIdentifier as r,versionTag as i,walkCommandTree as a}from"./shared.mjs";function o(e,o){let u=`__${r(o?.functionPrefix??e.name)}_completions`,d=`${u}_path`,f=`${u}_path_is`,p=n(e,o?.rootMode),m=p.visibleCommands,h=a(m),g=t(e.name),_=[];_.push(`# Fish completion for ${e.name}`),_.push(`# Generated by ${i()}`),_.push(`#`),_.push(`# Usage: source (${e.name} completions fish | psub)`),_.push(`#`),_.push(`# Install permanently:`),_.push(`# ${e.name} completions fish > ~/.config/fish/completions/${e.name}.fish`),_.push(``),_.push(`complete -c ${g} -f`),_.push(``),s(_,d,f,m,h,p),c(_,g,f,``,m),l(_,g,f,``,p.rootFlags),p.includeDefaultFlags&&l(_,g,f,``,p.defaultFlags);for(let e of h){let t=e.path.join(` `);c(_,g,f,t,e.children),l(_,g,f,t,e.mergedFlags)}return _.join(`
2
+ `)}function s(e,n,r,i,a,o){let s=u(a,o);e.push(`function ${n}`),e.push(` set -l words (commandline -opc)`),e.push(` if test (count $words) -gt 0`),e.push(` set -e words[1]`),e.push(` end`),e.push(` set -l subcmd_path ''`),e.push(` set -l expect_value 0`),e.push(` for word in $words`),e.push(` if test $expect_value -eq 1`),e.push(` set expect_value 0`),e.push(` continue`),e.push(` end`),e.push(` switch $word`),e.push(` case '--'`),e.push(` break`),s.exact.length>0&&(e.push(`\t\t\tcase ${s.exact.map(t).join(` `)}`),e.push(` set expect_value 1`),e.push(` continue`)),s.prefix.length>0&&(e.push(`\t\t\tcase ${s.prefix.map(t).join(` `)}`),e.push(` continue`)),e.push(` case '-*'`),e.push(` continue`),e.push(` end`),e.push(` switch "$subcmd_path|$word"`);for(let n of i)for(let r of[n.name,...n.aliases])e.push(`\t\t\tcase ${t(`|${r}`)}`),e.push(`\t\t\t\tset subcmd_path ${t(n.name)}`);for(let n of a)for(let r of n.children)for(let i of[r.name,...r.aliases])e.push(`\t\t\tcase ${t(`${n.path.join(` `)}|${i}`)}`),e.push(`\t\t\t\tset subcmd_path ${t(`${n.path.join(` `)} ${r.name}`)}`);e.push(` case '*'`),e.push(` break`),e.push(` end`),e.push(` end`),e.push(` printf '%s\\n' "$subcmd_path"`),e.push(`end`),e.push(``),e.push(`function ${r}`),e.push(` set -l expected "$argv[1]"`),e.push(`\ttest (${n}) = "$expected"`),e.push(`end`),e.push(``)}function c(e,n,r,i,a){let o=d(r,i);for(let r of a){let i=t(r.description??r.name);for(let a of[r.name,...r.aliases])e.push(`complete -c ${n} -n "${o}" -a ${t(a)} -d ${i}`)}a.length>0&&e.push(``)}function l(n,r,i,a,o){let s=d(i,a);for(let[i,a]of Object.entries(o)){let o=[`complete -c ${r}`,`-n "${s}"`];for(let n of e(a,{kind:`short`}))o.push(`-s ${t(n)}`);o.push(`-l ${t(i)}`);for(let n of e(a,{kind:`long`}))o.push(`-l ${t(n)}`);if(o.push(`-d ${t(a.description??i)}`),a.kind!==`boolean`&&o.push(`-r`,`-f`),a.kind===`enum`&&a.enumValues!==void 0){for(let e of a.enumValues)n.push([...o,`-a ${t(e)}`].join(` `));continue}n.push(o.join(` `))}Object.keys(o).length>0&&n.push(``)}function u(t,n){let r=new Set,i=new Set,a=[n.rootFlags,...n.includeDefaultFlags?[n.defaultFlags]:[],...t.map(e=>e.mergedFlags)];for(let t of a)for(let[n,a]of Object.entries(t))if(a.kind!==`boolean`){r.add(`--${n}`),i.add(`--${n}=*`);for(let t of e(a,{kind:`short`,includeHidden:!0}))r.add(`-${t}`),i.add(`-${t}*`);for(let t of e(a,{kind:`long`,includeHidden:!0}))r.add(`--${t}`),i.add(`--${t}=*`)}return{exact:[...r],prefix:[...i]}}function d(e,n){return`${e} ${t(n)}`}export{o as generateFishCompletion};
@@ -0,0 +1,14 @@
1
+ import { CompletionOptions } from "./shared.mjs";
2
+ import { CLISchema } from "../../cli/index.mjs";
3
+
4
+ //#region src/core/completion/shells/powershell.d.ts
5
+ /**
6
+ * Generate a PowerShell completion script for the CLI.
7
+ *
8
+ * @param schema - The CLI schema.
9
+ * @param options - Optional generator configuration.
10
+ * @returns A complete PowerShell completion script.
11
+ */
12
+ declare function generatePowerShellCompletion(schema: CLISchema, options?: CompletionOptions): string;
13
+ //#endregion
14
+ export { generatePowerShellCompletion };
@@ -0,0 +1,2 @@
1
+ import{getFlagAliasNames as e}from"../../schema/flag.mjs";import{resolveRootCompletionSurface as t,sanitizeShellIdentifier as n,versionTag as r,walkCommandTree as i}from"./shared.mjs";function a(e,a){let s=`__${n(a?.functionPrefix??e.name)}_completions`,u=`${s}_paths`,d=t(e,a?.rootMode),f=d.visibleCommands,p=i(f),m=[];return m.push(`# PowerShell completion for ${e.name}`),m.push(`# Generated by ${r()}`),m.push(`#`),m.push(`# Install for the current session:`),m.push(`# ${e.name} completions powershell | Invoke-Expression`),m.push(`#`),m.push(`# Install permanently:`),m.push(`# ${e.name} completions powershell > $PROFILE.CurrentUserCurrentHost`),m.push(``),m.push(`using namespace System.Management.Automation`),m.push(`using namespace System.Management.Automation.Language`),m.push(``),o(m,u,d,p),m.push(``),c(m,s,u),m.push(``),m.push(`Register-ArgumentCompleter -Native -CommandName ${l(e.name)} -ScriptBlock {`),m.push(` param($wordToComplete, $commandAst, $cursorPosition)`),m.push(`\t$state = ${s}_GetState -CommandAst $commandAst -CursorPosition $cursorPosition`),m.push(` if ($null -eq $state.PathData) {`),m.push(` return`),m.push(` }`),m.push(``),m.push(` $results = [System.Collections.Generic.List[CompletionResult]]::new()`),m.push(` $wordPrefix = if ([string]::IsNullOrEmpty($wordToComplete)) { '' } else { $wordToComplete }`),m.push(``),m.push(` if ($state.ExpectingValue) {`),m.push(`\t\t${s}_AddEnumResults -Results $results -Flag $state.ValueFlag -WordToComplete $wordPrefix`),m.push(` return $results`),m.push(` }`),m.push(``),m.push(`\t$inlineValue = ${s}_ResolveInlineValueCompletion -PathData $state.PathData -WordToComplete $wordPrefix`),m.push(` if ($null -ne $inlineValue) {`),m.push(`\t\t${s}_AddInlineEnumResults -Results $results -InlineValue $inlineValue -WordToComplete $wordPrefix`),m.push(` return $results`),m.push(` }`),m.push(``),m.push(` if ($wordPrefix.StartsWith('-')) {`),m.push(`\t\t${s}_AddFlagResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`),m.push(` return $results`),m.push(` }`),m.push(``),m.push(`\t${s}_AddCommandResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`),m.push(`\t${s}_AddFlagResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`),m.push(` return $results`),m.push(`}`),m.join(`
2
+ `)}function o(e,t,n,r){e.push(`$script:${t} = @{`),s(e,``,n.visibleCommands,{...n.rootFlags,...n.includeDefaultFlags?n.defaultFlags:{}});for(let t of r)s(e,t.path.join(` `),t.children,t.mergedFlags);e.push(`}`)}function s(t,n,r,i){t.push(`\t${l(n)} = @{`),t.push(` Commands = @(`);for(let e of r)t.push(` @{`),t.push(`\t\t\t\tCanonicalName = ${l(e.name)}`),t.push(`\t\t\t\tNames = ${u([e.name,...e.aliases])}`),t.push(`\t\t\t\tDescription = ${l(e.description??e.name)}`),t.push(` }`);t.push(` )`),t.push(` Flags = @(`);for(let[n,r]of Object.entries(i)){let i=d([`--${n}`,...e(r,{kind:`short`}).map(e=>`-${e}`),...e(r,{kind:`long`}).map(e=>`--${e}`)]),a=d([`--${n}`,...e(r,{kind:`short`,includeHidden:!0}).map(e=>`-${e}`),...e(r,{kind:`long`,includeHidden:!0}).map(e=>`--${e}`)]);t.push(` @{`),t.push(`\t\t\t\tCanonicalName = ${l(n)}`),t.push(`\t\t\t\tForms = ${u(i)}`),t.push(`\t\t\t\tParseForms = ${u(a)}`),t.push(`\t\t\t\tRequiresValue = ${r.kind===`boolean`?`$false`:`$true`}`),t.push(`\t\t\t\tDescription = ${l(r.description??n)}`),t.push(`\t\t\t\tEnumValues = ${u(r.enumValues??[])}`),t.push(` }`)}t.push(` )`),t.push(` }`)}function c(e,t,n){e.push(`function ${t}_UnquoteToken {`),e.push(` param([string]$TokenText)`),e.push(` if ($TokenText.Length -lt 2) {`),e.push(` return $TokenText`),e.push(` }`),e.push(``),e.push(` if (($TokenText.StartsWith("'") -and $TokenText.EndsWith("'")) -or`),e.push(` ($TokenText.StartsWith('"') -and $TokenText.EndsWith('"'))) {`),e.push(` return $TokenText.Substring(1, $TokenText.Length - 2)`),e.push(` }`),e.push(``),e.push(` return $TokenText`),e.push(`}`),e.push(``),e.push(`function ${t}_FindCommand {`),e.push(` param($PathData, [string]$Token)`),e.push(` foreach ($command in $PathData.Commands) {`),e.push(` foreach ($name in $command.Names) {`),e.push(` if ($name -eq $Token) {`),e.push(` return $command`),e.push(` }`),e.push(` }`),e.push(` }`),e.push(` return $null`),e.push(`}`),e.push(``),e.push(`function ${t}_ResolveFlagToken {`),e.push(` param($PathData, [string]$Token)`),e.push(` foreach ($flag in $PathData.Flags) {`),e.push(` foreach ($form in $flag.ParseForms) {`),e.push(` if ($Token -eq $form) {`),e.push(` return @{ Flag = $flag; InlinePrefix = $null }`),e.push(` }`),e.push(``),e.push(` if (-not $flag.RequiresValue) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` if ($form.StartsWith('--') -and $Token.StartsWith("$form=")) {`),e.push(` return @{ Flag = $flag; InlinePrefix = "$form=" }`),e.push(` }`),e.push(``),e.push(` if ($form.StartsWith('-') -and -not $form.StartsWith('--') -and $Token.StartsWith($form) -and $Token.Length -gt $form.Length) {`),e.push(` return @{ Flag = $flag; InlinePrefix = $form }`),e.push(` }`),e.push(` }`),e.push(` }`),e.push(` return $null`),e.push(`}`),e.push(``),e.push(`function ${t}_GetState {`),e.push(` param([CommandAst]$CommandAst, [int]$CursorPosition)`),e.push(`\t$pathData = $script:${n}[${l(``)}]`),e.push(` $path = ""`),e.push(` $expectingValue = $false`),e.push(` $valueFlag = $null`),e.push(` $tokens = [System.Collections.Generic.List[string]]::new()`),e.push(``),e.push(` foreach ($element in $CommandAst.CommandElements | Select-Object -Skip 1) {`),e.push(` if ($element.Extent.EndOffset -gt $CursorPosition) {`),e.push(` break`),e.push(` }`),e.push(`\t\t$tokenText = ${t}_UnquoteToken $element.Extent.Text`),e.push(` [void]$tokens.Add($tokenText)`),e.push(` }`),e.push(``),e.push(` foreach ($token in $tokens) {`),e.push(` if ($expectingValue) {`),e.push(` $expectingValue = $false`),e.push(` $valueFlag = $null`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` if ($token -eq '--') {`),e.push(` break`),e.push(` }`),e.push(``),e.push(`\t\t$flagMatch = ${t}_ResolveFlagToken -PathData $pathData -Token $token`),e.push(` if ($null -ne $flagMatch) {`),e.push(` if ($flagMatch.InlinePrefix -eq $null -and $flagMatch.Flag.RequiresValue) {`),e.push(` $expectingValue = $true`),e.push(` $valueFlag = $flagMatch.Flag`),e.push(` }`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` if ($token.StartsWith('-')) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(`\t\t$command = ${t}_FindCommand -PathData $pathData -Token $token`),e.push(` if ($null -eq $command) {`),e.push(` break`),e.push(` }`),e.push(``),e.push(` $path = if ([string]::IsNullOrEmpty($path)) {`),e.push(` $command.CanonicalName`),e.push(` } else {`),e.push(` "$path $($command.CanonicalName)"`),e.push(` }`),e.push(`\t\t$nextPathData = $script:${n}[$path]`),e.push(` if ($null -eq $nextPathData) {`),e.push(` break`),e.push(` }`),e.push(` $pathData = $nextPathData`),e.push(` }`),e.push(``),e.push(` return @{`),e.push(` Path = $path`),e.push(` PathData = $pathData`),e.push(` ExpectingValue = $expectingValue`),e.push(` ValueFlag = $valueFlag`),e.push(` }`),e.push(`}`),e.push(``),e.push(`function ${t}_ResolveInlineValueCompletion {`),e.push(` param($PathData, [string]$WordToComplete)`),e.push(`\t$flagMatch = ${t}_ResolveFlagToken -PathData $PathData -Token $WordToComplete`),e.push(` if ($null -eq $flagMatch -or $flagMatch.InlinePrefix -eq $null) {`),e.push(` return $null`),e.push(` }`),e.push(` return $flagMatch`),e.push(`}`),e.push(``),e.push(`function ${t}_AddCommandResults {`),e.push(` param($Results, $PathData, [string]$WordToComplete)`),e.push(` foreach ($command in $PathData.Commands) {`),e.push(` foreach ($name in $command.Names) {`),e.push(` if (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $name.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` $Results.Add([CompletionResult]::new(`),e.push(` $name,`),e.push(` $name,`),e.push(` [CompletionResultType]::Command,`),e.push(` $command.Description`),e.push(` ))`),e.push(` }`),e.push(` }`),e.push(`}`),e.push(``),e.push(`function ${t}_AddFlagResults {`),e.push(` param($Results, $PathData, [string]$WordToComplete)`),e.push(` foreach ($flag in $PathData.Flags) {`),e.push(` foreach ($form in $flag.Forms) {`),e.push(` if (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $form.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` $Results.Add([CompletionResult]::new(`),e.push(` $form,`),e.push(` $form,`),e.push(` [CompletionResultType]::ParameterName,`),e.push(` $flag.Description`),e.push(` ))`),e.push(` }`),e.push(` }`),e.push(`}`),e.push(``),e.push(`function ${t}_AddEnumResults {`),e.push(` param($Results, $Flag, [string]$WordToComplete)`),e.push(` foreach ($value in $Flag.EnumValues) {`),e.push(` if (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $value.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` $Results.Add([CompletionResult]::new(`),e.push(` $value,`),e.push(` $value,`),e.push(` [CompletionResultType]::ParameterValue,`),e.push(` $Flag.Description`),e.push(` ))`),e.push(` }`),e.push(`}`),e.push(``),e.push(`function ${t}_AddInlineEnumResults {`),e.push(` param($Results, $InlineValue, [string]$WordToComplete)`),e.push(` foreach ($value in $InlineValue.Flag.EnumValues) {`),e.push(` $completion = "$($InlineValue.InlinePrefix)$value"`),e.push(` if (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $completion.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` $Results.Add([CompletionResult]::new(`),e.push(` $completion,`),e.push(` $value,`),e.push(` [CompletionResultType]::ParameterValue,`),e.push(` $InlineValue.Flag.Description`),e.push(` ))`),e.push(` }`),e.push(`}`)}function l(e){return`'${e.replace(/'/g,`''`)}'`}function u(e){return e.length===0?`@()`:`@(${e.map(l).join(`, `)})`}function d(e){return[...new Set(e)]}export{a as generatePowerShellCompletion};