@kjanat/dreamcli 0.0.0 → 1.0.0

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 (101) hide show
  1. package/CHANGELOG.md +667 -0
  2. package/LICENSE +22 -0
  3. package/README.md +370 -0
  4. package/dist/adapter-B37d9oia.mjs +1 -0
  5. package/dist/adapter-CCSh5juX.cjs +1 -0
  6. package/dist/adapter-DIwO-q7K.d.mts +3447 -0
  7. package/dist/adapter-DQnxxLiE.d.cts +3447 -0
  8. package/dist/auto-5cjZaF9V.mjs +3 -0
  9. package/dist/auto-B0eSgoDw.cjs +3 -0
  10. package/dist/index.cjs +10 -0
  11. package/dist/index.d.cts +920 -0
  12. package/dist/index.d.mts +920 -0
  13. package/dist/index.mjs +10 -0
  14. package/dist/runtime.cjs +1 -0
  15. package/dist/runtime.d.cts +253 -0
  16. package/dist/runtime.d.mts +253 -0
  17. package/dist/runtime.mjs +1 -0
  18. package/dist/testkit-CEDYPvhF.mjs +14 -0
  19. package/dist/testkit-ClIKijxC.cjs +14 -0
  20. package/dist/testkit.cjs +1 -0
  21. package/dist/testkit.d.cts +25 -0
  22. package/dist/testkit.d.mts +25 -0
  23. package/dist/testkit.mjs +1 -0
  24. package/examples/basic.ts +33 -0
  25. package/examples/gh/package.json +48 -0
  26. package/examples/gh/src/commands/auth.ts +66 -0
  27. package/examples/gh/src/commands/issue.ts +120 -0
  28. package/examples/gh/src/commands/pr.ts +125 -0
  29. package/examples/gh/src/data/issues.yaml +5 -0
  30. package/examples/gh/src/data/issues.yaml.d.ts +17 -0
  31. package/examples/gh/src/data/pull-requests.yaml +7 -0
  32. package/examples/gh/src/data/pull-requests.yaml.d.ts +18 -0
  33. package/examples/gh/src/lib/auth.ts +37 -0
  34. package/examples/gh/src/lib/utils.ts +17 -0
  35. package/examples/gh/src/main.test.ts +306 -0
  36. package/examples/gh/src/main.ts +38 -0
  37. package/examples/gh/tsconfig.json +37 -0
  38. package/examples/interactive.ts +66 -0
  39. package/examples/json-mode.ts +93 -0
  40. package/examples/middleware.ts +71 -0
  41. package/examples/multi-command.ts +66 -0
  42. package/examples/spinner-progress.ts +49 -0
  43. package/examples/testing.ts +145 -0
  44. package/examples/tsconfig.json +17 -0
  45. package/package.json +123 -2
  46. package/src/core/cli/AGENTS.md +72 -0
  47. package/src/core/cli/dispatch.ts +282 -0
  48. package/src/core/cli/index.ts +1425 -0
  49. package/src/core/cli/plugin.ts +111 -0
  50. package/src/core/cli/propagate.ts +97 -0
  51. package/src/core/cli/root-help.ts +269 -0
  52. package/src/core/cli/root-surface.ts +74 -0
  53. package/src/core/completion/AGENTS.md +72 -0
  54. package/src/core/completion/completion-test-helpers.ts +48 -0
  55. package/src/core/completion/index.ts +82 -0
  56. package/src/core/completion/shells/bash.ts +456 -0
  57. package/src/core/completion/shells/fish.ts +24 -0
  58. package/src/core/completion/shells/powershell.ts +24 -0
  59. package/src/core/completion/shells/shared.ts +283 -0
  60. package/src/core/completion/shells/zsh.ts +376 -0
  61. package/src/core/config/index.ts +404 -0
  62. package/src/core/config/package-json.ts +216 -0
  63. package/src/core/errors/index.ts +178 -0
  64. package/src/core/help/index.ts +559 -0
  65. package/src/core/json-schema/index.ts +705 -0
  66. package/src/core/output/AGENTS.md +69 -0
  67. package/src/core/output/activity.ts +568 -0
  68. package/src/core/output/display-value.ts +48 -0
  69. package/src/core/output/index.ts +704 -0
  70. package/src/core/output/writer.ts +46 -0
  71. package/src/core/parse/index.ts +643 -0
  72. package/src/core/prompt/index.ts +566 -0
  73. package/src/core/resolve/AGENTS.md +69 -0
  74. package/src/core/resolve/index.ts +1331 -0
  75. package/src/core/schema/AGENTS.md +61 -0
  76. package/src/core/schema/activity.ts +237 -0
  77. package/src/core/schema/arg.ts +707 -0
  78. package/src/core/schema/command.ts +1263 -0
  79. package/src/core/schema/flag.ts +651 -0
  80. package/src/core/schema/index.ts +82 -0
  81. package/src/core/schema/middleware.ts +171 -0
  82. package/src/core/schema/prompt.ts +148 -0
  83. package/src/core/schema/run.ts +187 -0
  84. package/src/core/testkit/AGENTS.md +55 -0
  85. package/src/core/testkit/index.ts +365 -0
  86. package/src/index.ts +164 -0
  87. package/src/runtime/AGENTS.md +74 -0
  88. package/src/runtime/adapter.ts +300 -0
  89. package/src/runtime/auto.ts +110 -0
  90. package/src/runtime/bun.ts +55 -0
  91. package/src/runtime/deno.ts +355 -0
  92. package/src/runtime/detect.ts +102 -0
  93. package/src/runtime/index.ts +21 -0
  94. package/src/runtime/node-builtins.d.ts +23 -0
  95. package/src/runtime/node.ts +278 -0
  96. package/src/runtime/paths.ts +56 -0
  97. package/src/runtime/support.ts +119 -0
  98. package/src/runtime/test-helpers.ts +40 -0
  99. package/src/runtime.ts +31 -0
  100. package/src/testkit.ts +23 -0
  101. package/src/version.ts +20 -0
@@ -0,0 +1,111 @@
1
+ /**
2
+ * CLI plugin lifecycle hooks.
3
+ *
4
+ * Plugins attach to `CLIBuilder` and observe command execution at stable
5
+ * points: before parse, after resolve, before action, and after action.
6
+ *
7
+ * @module dreamcli/core/cli/plugin
8
+ */
9
+
10
+ import type { DeprecationWarning } from '#internals/core/resolve/index.ts';
11
+ import type { CommandMeta, CommandSchema, Out } from '#internals/core/schema/command.ts';
12
+
13
+ /** Shared hook payload for a concrete command execution. */
14
+ interface PluginCommandContext {
15
+ /** Runtime command schema being executed. */
16
+ readonly command: CommandSchema;
17
+ /** CLI metadata for this execution. */
18
+ readonly meta: CommandMeta;
19
+ /** Output channel for this execution. */
20
+ readonly out: Out;
21
+ }
22
+
23
+ /** Payload for `beforeParse`. */
24
+ interface BeforeParseParams extends PluginCommandContext {
25
+ /** Raw argv that will be parsed for the leaf command. */
26
+ readonly argv: readonly string[];
27
+ }
28
+
29
+ /** Payload for hooks that observe resolved inputs. */
30
+ interface ResolvedCommandParams extends PluginCommandContext {
31
+ /** Fully resolved flag values. */
32
+ readonly flags: Readonly<Record<string, unknown>>;
33
+ /** Fully resolved argument values. */
34
+ readonly args: Readonly<Record<string, unknown>>;
35
+ /** Structured deprecation warnings collected during resolution. */
36
+ readonly deprecations: readonly DeprecationWarning[];
37
+ }
38
+
39
+ /**
40
+ * Individual lifecycle hooks that a plugin may implement.
41
+ *
42
+ * Hook order for a successful command run is:
43
+ * `beforeParse` → `afterResolve` → `beforeAction` → middleware/action → `afterAction`.
44
+ *
45
+ * Hooks are awaited serially and run in plugin registration order at each
46
+ * stage. Throwing from any hook aborts the command just like throwing from
47
+ * middleware or the action handler. `afterAction` runs only after the
48
+ * middleware chain and action complete successfully.
49
+ */
50
+ interface CLIPluginHooks {
51
+ /** Called immediately before leaf-command argv is parsed. */
52
+ readonly beforeParse?: (params: BeforeParseParams) => void | Promise<void>;
53
+ /** Called after parse + resolve, before middleware or action execution. */
54
+ readonly afterResolve?: (params: ResolvedCommandParams) => void | Promise<void>;
55
+ /** Called immediately before the middleware chain and action handler run. */
56
+ readonly beforeAction?: (params: ResolvedCommandParams) => void | Promise<void>;
57
+ /** Called after the middleware chain and action handler complete successfully. */
58
+ readonly afterAction?: (params: ResolvedCommandParams) => void | Promise<void>;
59
+ }
60
+
61
+ /**
62
+ * Immutable plugin definition registered via `CLIBuilder.plugin()`.
63
+ *
64
+ * Use {@link plugin} to construct values of this shape instead of manually
65
+ * assembling the object.
66
+ */
67
+ interface CLIPlugin {
68
+ /** Optional label for diagnostics and debugging. */
69
+ readonly name: string | undefined;
70
+ /** Lifecycle hooks implemented by the plugin. */
71
+ readonly hooks: CLIPluginHooks;
72
+ }
73
+
74
+ /**
75
+ * Create a CLI plugin from lifecycle hooks.
76
+ *
77
+ * @param hooks - Lifecycle hooks to register.
78
+ * @param name - Optional plugin name for diagnostics.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * const trace = plugin(
83
+ * {
84
+ * beforeParse: ({ argv, out }) => {
85
+ * out.info(`argv: ${argv.join(' ')}`);
86
+ * },
87
+ * afterResolve: ({ flags, args }) => {
88
+ * console.log({ flags, args });
89
+ * },
90
+ * },
91
+ * 'trace',
92
+ * );
93
+ *
94
+ * cli('mycli').plugin(trace).command(deploy);
95
+ * ```
96
+ *
97
+ * @returns A frozen {@link CLIPlugin} definition.
98
+ */
99
+ function plugin(hooks: CLIPluginHooks, name?: string): CLIPlugin {
100
+ const frozenHooks = Object.freeze({ ...hooks });
101
+ return Object.freeze({ hooks: frozenHooks, name });
102
+ }
103
+
104
+ export type {
105
+ BeforeParseParams,
106
+ CLIPlugin,
107
+ CLIPluginHooks,
108
+ PluginCommandContext,
109
+ ResolvedCommandParams,
110
+ };
111
+ export { plugin };
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Propagated flag collection for nested command dispatch.
3
+ *
4
+ * Walks a command path (root ancestor to target) and collects flags marked
5
+ * `propagate: true`. Child commands that define a flag with the same name
6
+ * as a propagated ancestor flag "shadow" the ancestor's flag — the child's
7
+ * definition wins.
8
+ *
9
+ * @module dreamcli/core/cli/propagate
10
+ */
11
+
12
+ import type { CommandSchema, FlagSchema } from '#internals/core/schema/index.ts';
13
+
14
+ // --- Propagated flag collection
15
+
16
+ /**
17
+ * Collect propagated flags from a command path.
18
+ *
19
+ * The command path is an ordered array of `CommandSchema` from the root
20
+ * ancestor to the target command that will actually execute. Each ancestor's
21
+ * flags marked `propagate: true` are accumulated. If a descendant (including
22
+ * the target) defines a flag with the same name — regardless of whether the
23
+ * descendant's flag has `propagate: true` — it shadows the ancestor's flag.
24
+ *
25
+ * The target command's own flags are **not** included in the result. This
26
+ * function returns only the *inherited* propagated flags that should be merged
27
+ * into the target command's flag set before resolution.
28
+ *
29
+ * @param commandPath - Ordered schemas from root ancestor to target (inclusive).
30
+ * Must contain at least one element (the target itself). When the path has
31
+ * only one element, no ancestors exist and the result is empty.
32
+ *
33
+ * @returns A record of propagated flag schemas keyed by flag name. Empty when
34
+ * the path has no ancestors or no ancestor flags have `propagate: true`.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * // Given: root (--verbose [propagate]) → db → migrate
39
+ * // Where migrate does NOT define --verbose
40
+ * const inherited = collectPropagatedFlags([rootSchema, dbSchema, migrateSchema]);
41
+ * // inherited = { verbose: <FlagSchema from root> }
42
+ *
43
+ * // If db also defines --verbose (shadowing root):
44
+ * const inherited2 = collectPropagatedFlags([rootSchema, dbSchemaWithVerbose, migrateSchema]);
45
+ * // inherited2 = { verbose: <FlagSchema from db> }
46
+ * ```
47
+ */
48
+ function collectPropagatedFlags(
49
+ commandPath: readonly CommandSchema[],
50
+ ): Readonly<Record<string, FlagSchema>> {
51
+ if (commandPath.length <= 1) return {};
52
+
53
+ // Ancestors = all elements except the last (target).
54
+ // Walk root → ... → parent, accumulating propagated flags.
55
+ // Later ancestors shadow earlier ones (natural overwrite order).
56
+ const accumulated: Record<string, FlagSchema> = {};
57
+
58
+ for (let i = 0; i < commandPath.length - 1; i++) {
59
+ const ancestor = commandPath[i];
60
+ if (ancestor === undefined) continue;
61
+
62
+ for (const [name, flagSchema] of Object.entries(ancestor.flags)) {
63
+ if (flagSchema.propagate) {
64
+ // Check if any descendant (between this ancestor and the target)
65
+ // defines a flag with the same name — if so, skip the ancestor's
66
+ // flag entirely. This ensures a child that redefines a flag
67
+ // (even without propagate) masks the ancestor's propagated flag.
68
+ let shadowedByDescendant = false;
69
+ for (let j = i + 1; j < commandPath.length - 1; j++) {
70
+ const descendant = commandPath[j];
71
+ if (descendant !== undefined && name in descendant.flags) {
72
+ shadowedByDescendant = true;
73
+ break;
74
+ }
75
+ }
76
+ if (!shadowedByDescendant) {
77
+ accumulated[name] = flagSchema;
78
+ }
79
+ }
80
+ }
81
+ }
82
+
83
+ // Remove any flag names that the target command defines directly.
84
+ // A target's own flag — propagated or not — shadows inherited flags.
85
+ const target = commandPath[commandPath.length - 1];
86
+ if (target !== undefined) {
87
+ for (const name of Object.keys(target.flags)) {
88
+ delete accumulated[name];
89
+ }
90
+ }
91
+
92
+ return accumulated;
93
+ }
94
+
95
+ // --- Exports
96
+
97
+ export { collectPropagatedFlags };
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Root-level help formatter for the CLI program.
3
+ *
4
+ * Separate from `help/formatHelp()` which renders per-command help —
5
+ * different concerns, different format.
6
+ *
7
+ * @module dreamcli/core/cli/root-help
8
+ * @internal
9
+ */
10
+
11
+ import type { HelpOptions } from '#internals/core/help/index.ts';
12
+ import { formatHelpSections } from '#internals/core/help/index.ts';
13
+ import type { CommandSchema } from '#internals/core/schema/command.ts';
14
+ import { resolveRootSurface } from './root-surface.ts';
15
+
16
+ // Re-use CLISchema inline to avoid circular import through the barrel.
17
+ // Only the shape matters — we read `.name`, `.version`, `.description`, `.commands`,
18
+ // `.defaultCommand`.
19
+ /** Structural subset of `CLISchema` — avoids circular imports through the barrel. */
20
+ interface CLISchemaLike {
21
+ readonly name: string;
22
+ readonly version: string | undefined;
23
+ readonly description: string | undefined;
24
+ readonly commands: ReadonlyArray<{
25
+ readonly schema: CommandSchema;
26
+ }>;
27
+ readonly defaultCommand: { readonly schema: CommandSchema } | undefined;
28
+ }
29
+
30
+ // --- Root help formatter
31
+
32
+ /**
33
+ * Generate root-level help text for the CLI program.
34
+ *
35
+ * Shows program name, version, description, usage line, and available
36
+ * commands. When the default command is the only visible top-level
37
+ * command, merges the root summary with that command's detailed help.
38
+ *
39
+ * @internal
40
+ */
41
+ function formatRootHelp(schema: CLISchemaLike, options?: HelpOptions): string {
42
+ const width = options?.width ?? 80;
43
+ const rootSurface = resolveRootSurface(schema);
44
+ if (rootSurface.hasSingleVisibleDefault) {
45
+ const defaultCommand = rootSurface.visibleDefaultCommand;
46
+ if (defaultCommand !== undefined) {
47
+ const sections = buildRootSections(
48
+ schema,
49
+ rootSurface.visibleCommands,
50
+ rootSurface.visibleDefaultCommand,
51
+ width,
52
+ );
53
+ const usageIndex = sections.findIndex((section) => section.startsWith('Usage: '));
54
+ const commandSections = [
55
+ ...formatHelpSections(defaultCommand, {
56
+ ...options,
57
+ binName: schema.name,
58
+ isDefaultHelp: true,
59
+ }),
60
+ ];
61
+ const commandUsage = commandSections.shift();
62
+ if (usageIndex !== -1 && commandUsage !== undefined) {
63
+ sections[usageIndex] = mergeUsageSections(sections[usageIndex] ?? '', commandUsage);
64
+ }
65
+ if (
66
+ defaultCommand.description !== undefined &&
67
+ schema.description !== undefined &&
68
+ defaultCommand.description === schema.description
69
+ ) {
70
+ commandSections.shift();
71
+ }
72
+ sections.push(...commandSections);
73
+ return `${sections.join('\n\n')}\n`;
74
+ }
75
+ }
76
+
77
+ const sections = buildRootSections(
78
+ schema,
79
+ rootSurface.visibleCommands,
80
+ rootSurface.visibleDefaultCommand,
81
+ width,
82
+ );
83
+ const placeholder = commandPlaceholder(
84
+ rootSurface.visibleCommands,
85
+ rootSurface.visibleDefaultCommand,
86
+ );
87
+ sections.push(
88
+ placeholder.length > 0
89
+ ? `Run '${schema.name} ${placeholder} --help' for more information.`
90
+ : `Run '${schema.name} --help' for more information.`,
91
+ );
92
+
93
+ return `${sections.join('\n\n')}\n`;
94
+ }
95
+
96
+ /**
97
+ * Assemble the header, description, usage, and commands sections for root help.
98
+ *
99
+ * @param schema - The CLI schema.
100
+ * @param visibleCommands - Non-hidden top-level commands.
101
+ * @param width - Terminal width for text wrapping.
102
+ * @returns Ordered help sections (joined later with blank lines).
103
+ * @internal
104
+ */
105
+ function buildRootSections(
106
+ schema: CLISchemaLike,
107
+ visibleCommands: readonly CommandSchema[],
108
+ visibleDefaultCommand: CommandSchema | undefined,
109
+ width: number,
110
+ ): string[] {
111
+ const sections: string[] = [];
112
+
113
+ // ---- Header: name + version ---------------------------------------------
114
+ const header = schema.version !== undefined ? `${schema.name} v${schema.version}` : schema.name;
115
+ sections.push(header);
116
+
117
+ // ---- Description --------------------------------------------------------
118
+ if (schema.description !== undefined) {
119
+ sections.push(schema.description);
120
+ }
121
+
122
+ // ---- Usage line ---------------------------------------------------------
123
+ const placeholder = commandPlaceholder(visibleCommands, visibleDefaultCommand);
124
+ sections.push(
125
+ placeholder.length > 0
126
+ ? `Usage: ${schema.name} ${placeholder} [options]`
127
+ : `Usage: ${schema.name} [options]`,
128
+ );
129
+
130
+ // ---- Commands list (skip hidden) ----------------------------------------
131
+ if (visibleCommands.length > 0) {
132
+ sections.push(formatRootCommandsSection(visibleCommands, visibleDefaultCommand?.name, width));
133
+ }
134
+
135
+ return sections;
136
+ }
137
+
138
+ /**
139
+ * Return the usage-line placeholder for commands (`<command>`, `[command]`, or empty).
140
+ *
141
+ * @param visibleCommands - Non-hidden top-level commands.
142
+ * @param defaultCommand - The default command, if any.
143
+ * @returns Placeholder string for the usage line.
144
+ * @internal
145
+ */
146
+ function commandPlaceholder(
147
+ visibleCommands: readonly CommandSchema[],
148
+ defaultCommand: CommandSchema | undefined,
149
+ ): string {
150
+ if (visibleCommands.length === 0 && defaultCommand === undefined) {
151
+ return '';
152
+ }
153
+
154
+ return defaultCommand !== undefined ? '[command]' : '<command>';
155
+ }
156
+
157
+ /**
158
+ * Format the "Commands:" section with aligned names and descriptions.
159
+ *
160
+ * @param visibleCommands - Non-hidden top-level commands.
161
+ * @param defaultName - Name of the default command (appends " (default)" tag).
162
+ * @param width - Terminal width for description wrapping.
163
+ * @returns Formatted commands block.
164
+ * @internal
165
+ */
166
+ function formatRootCommandsSection(
167
+ visibleCommands: readonly CommandSchema[],
168
+ defaultName: string | undefined,
169
+ width: number,
170
+ ): string {
171
+ const lines: string[] = ['Commands:'];
172
+ const GAP = 2;
173
+ const DEFAULT_TAG = ' (default)';
174
+
175
+ // Compute max command name length for alignment (account for default tag)
176
+ let maxNameLen = 0;
177
+ for (const cmd of visibleCommands) {
178
+ const tagLen = cmd.name === defaultName ? DEFAULT_TAG.length : 0;
179
+ const nameLen = cmd.name.length + tagLen;
180
+ if (nameLen > maxNameLen) {
181
+ maxNameLen = nameLen;
182
+ }
183
+ }
184
+
185
+ const descCol = 2 + maxNameLen + GAP; // 2 for indent
186
+ for (const cmd of visibleCommands) {
187
+ const isDefault = cmd.name === defaultName;
188
+ const label = isDefault ? `${cmd.name}${DEFAULT_TAG}` : cmd.name;
189
+ const padded = padEnd(` ${label}`, descCol);
190
+ const desc = cmd.description ?? '';
191
+ if (desc.length === 0) {
192
+ lines.push(padded.trimEnd());
193
+ } else {
194
+ lines.push(`${padded}${wrapText(desc, width, descCol)}`);
195
+ }
196
+ }
197
+
198
+ return lines.join('\n');
199
+ }
200
+
201
+ /**
202
+ * Merge root and default-command usage lines into a single block.
203
+ *
204
+ * @param rootUsage - The root usage line (e.g. `Usage: mycli [command] [options]`).
205
+ * @param commandUsage - The default command's usage line.
206
+ * @returns Combined usage block with aligned continuation.
207
+ * @internal
208
+ */
209
+ function mergeUsageSections(rootUsage: string, commandUsage: string): string {
210
+ const usagePrefix = 'Usage: ';
211
+ const commandSuffix = commandUsage.startsWith(usagePrefix)
212
+ ? commandUsage.slice(usagePrefix.length)
213
+ : commandUsage;
214
+ return `${rootUsage}\n${' '.repeat(usagePrefix.length)}${commandSuffix}`;
215
+ }
216
+
217
+ // --- Text helpers (duplicated from help module to avoid coupling)
218
+
219
+ /**
220
+ * Pad `text` to `length` with trailing spaces.
221
+ *
222
+ * @param text - The string to pad.
223
+ * @param length - Target width.
224
+ * @returns Padded string.
225
+ */
226
+ function padEnd(text: string, length: number): string {
227
+ if (text.length >= length) return text;
228
+ return text + ' '.repeat(length - text.length);
229
+ }
230
+
231
+ /**
232
+ * Wrap text to `width`, preserving leading indent on continuation lines.
233
+ *
234
+ * @param text - The text to wrap.
235
+ * @param width - Maximum line width.
236
+ * @param indent - Indentation for continuation lines.
237
+ * @returns Wrapped text with continuation indentation.
238
+ */
239
+ function wrapText(text: string, width: number, indent: number): string {
240
+ if (text.length + indent <= width) return text;
241
+
242
+ const maxLen = width - indent;
243
+ if (maxLen <= 0) return text;
244
+
245
+ const words = text.split(' ');
246
+ const lines: string[] = [];
247
+ let current = '';
248
+
249
+ for (const word of words) {
250
+ if (current.length === 0) {
251
+ current = word;
252
+ } else if (current.length + 1 + word.length <= maxLen) {
253
+ current += ` ${word}`;
254
+ } else {
255
+ lines.push(current);
256
+ current = word;
257
+ }
258
+ }
259
+ if (current.length > 0) {
260
+ lines.push(current);
261
+ }
262
+
263
+ const pad = ' '.repeat(indent);
264
+ return lines.map((line, i) => (i === 0 ? line : `${pad}${line}`)).join('\n');
265
+ }
266
+
267
+ // --- Exports
268
+
269
+ export { formatRootHelp };
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Shared root-surface analysis for help and completion rendering.
3
+ *
4
+ * Answers structural questions about what the CLI root looks like:
5
+ * which top-level commands are visible, whether the default command is
6
+ * visible, and whether the root is effectively a single visible default.
7
+ *
8
+ * @module dreamcli/core/cli/root-surface
9
+ * @internal
10
+ */
11
+
12
+ import type { CommandSchema } from '#internals/core/schema/command.ts';
13
+
14
+ /**
15
+ * Structural CLI shape needed for root-surface analysis.
16
+ *
17
+ * Uses structural typing to avoid importing the full `CLISchema` and
18
+ * creating unnecessary cross-module coupling.
19
+ *
20
+ * @internal
21
+ */
22
+ interface RootSurfaceSchemaLike {
23
+ readonly commands: ReadonlyArray<{
24
+ readonly schema: CommandSchema;
25
+ }>;
26
+ readonly defaultCommand: { readonly schema: CommandSchema } | undefined;
27
+ }
28
+
29
+ /**
30
+ * Normalized root shape shared by help and completion logic.
31
+ *
32
+ * @internal
33
+ */
34
+ interface RootSurface {
35
+ readonly visibleCommands: readonly CommandSchema[];
36
+ readonly visibleDefaultCommand: CommandSchema | undefined;
37
+ readonly hasSingleVisibleDefault: boolean;
38
+ readonly hasVisibleSiblingCommands: boolean;
39
+ }
40
+
41
+ /**
42
+ * Resolve the visible shape of the CLI root.
43
+ *
44
+ * Hidden commands are excluded from the visible command list. Hidden
45
+ * default commands remain executable, but are not surfaced through
46
+ * help or completions.
47
+ *
48
+ * @internal
49
+ */
50
+ function resolveRootSurface(schema: RootSurfaceSchemaLike): RootSurface {
51
+ const visibleCommands = schema.commands
52
+ .map((command) => command.schema)
53
+ .filter((command) => !command.hidden);
54
+ const rawDefaultCommand = schema.defaultCommand?.schema;
55
+ const visibleDefaultCommand =
56
+ rawDefaultCommand !== undefined && !rawDefaultCommand.hidden ? rawDefaultCommand : undefined;
57
+ const hasSingleVisibleDefault =
58
+ visibleDefaultCommand !== undefined &&
59
+ visibleCommands.length === 1 &&
60
+ visibleCommands[0]?.name === visibleDefaultCommand.name;
61
+ const hasVisibleSiblingCommands =
62
+ visibleDefaultCommand !== undefined &&
63
+ visibleCommands.some((command) => command.name !== visibleDefaultCommand.name);
64
+
65
+ return {
66
+ visibleCommands,
67
+ visibleDefaultCommand,
68
+ hasSingleVisibleDefault,
69
+ hasVisibleSiblingCommands,
70
+ };
71
+ }
72
+
73
+ export type { RootSurface, RootSurfaceSchemaLike };
74
+ export { resolveRootSurface };
@@ -0,0 +1,72 @@
1
+ # completion — Shell completion script generation
2
+
3
+ Split into per-shell generators under `shells/`. Barrel `index.ts` re-exports public API and
4
+ dispatches via `generateCompletion()`.
5
+
6
+ ## FILES
7
+
8
+ | File | Lines | Purpose |
9
+ | ---------------------- | ----: | -------------------------------------------------------- |
10
+ | `index.ts` | 80 | Barrel — `Shell` type, `SHELLS` constant, dispatch |
11
+ | `shells/shared.ts` | 160 | `CommandNode`, `walkCommandTree`, escaping, `versionTag` |
12
+ | `shells/bash.ts` | 275 | `generateBashCompletion()` + all bash helpers |
13
+ | `shells/zsh.ts` | 280 | `generateZshCompletion()` + all zsh helpers |
14
+ | `shells/fish.ts` | 25 | Stub — throws `UNSUPPORTED_OPERATION` |
15
+ | `shells/powershell.ts` | 25 | Stub — throws `UNSUPPORTED_OPERATION` |
16
+
17
+ ## PUBLIC API
18
+
19
+ | Symbol | Exported from | Role |
20
+ | -------------------------- | ------------- | ------------------------------------------------ |
21
+ | `generateCompletion()` | `index.ts` | Shell-agnostic dispatch → per-shell generators |
22
+ | `generateBashCompletion()` | `index.ts` | Bash completion script from command tree |
23
+ | `generateZshCompletion()` | `index.ts` | Zsh completion script from command tree |
24
+ | `SHELLS` | `index.ts` | `readonly ['bash', 'zsh', 'fish', 'powershell']` |
25
+ | `CompletionOptions` | `index.ts` | Options type (re-exported from `shared.ts`) |
26
+ | `Shell` | `index.ts` | Union type of supported shells |
27
+
28
+ ## ARCHITECTURE
29
+
30
+ 1. Walk command tree → `CommandNode[]` (shared infrastructure in `shells/shared.ts`)
31
+ 2. Per-shell generator receives `CLISchema` + `CompletionOptions`, calls `walkCommandTree()`
32
+ 3. Emit shell-specific functions (one per command node)
33
+ 4. Bash: `complete -F` with `compgen`; Zsh: `_arguments` + `_describe`
34
+
35
+ Handles nested command groups: `mycli db migrate` generates completions for each depth level.
36
+
37
+ ## INTERNAL HELPERS (all `@internal`)
38
+
39
+ ### `shells/shared.ts`
40
+
41
+ - `versionTag()` — build-time version string for script headers
42
+ - `CommandNode` — flattened tree node with propagated flag context
43
+ - `walkCommandTree()` — depth-first command tree walker
44
+ - `sanitizeShellIdentifier()`, `quoteShellArg()` — shell escaping
45
+
46
+ ### `shells/bash.ts`
47
+
48
+ - `emitBashPathDetection`, `quoteShellCasePattern` — subcommand path detection
49
+ - `escapeForSingleQuote`, `escapeBashDollarQuote` — bash string escaping
50
+ - `formatBashEnumCompletion` — COMPREPLY for enum values
51
+ - `collectFlagWords`, `collectEnumCasesFromFlags`, `EnumCase` — flag extraction
52
+
53
+ ### `shells/zsh.ts`
54
+
55
+ - `emitZshGroupFunction`, `emitZshLeafFunction` — helper function emitters
56
+ - `escapeZshDescription`, `escapeZshEnumValue` — zsh string escaping
57
+ - `buildZshFlagSpecsFromFlags`, `buildZshFlagSpecs` — `_arguments` spec builders
58
+
59
+ ## GOTCHAS
60
+
61
+ - `shells/shared.ts` imports `cli/propagate.ts` directly (`@internal` file, not through cli barrel)
62
+ — needs `collectPropagatedFlags()` for flag inheritance in nested commands
63
+ - `biome-ignore noTemplateCurlyInString` in `shells/bash.ts` — emitting bash `${words[i]}` syntax
64
+ - Fish and PowerShell stubs throw `CLIError` with code `UNSUPPORTED_OPERATION`
65
+ - `CompletionOptions` lives in `shells/shared.ts`, re-exported through `index.ts`
66
+
67
+ ## TEST FILES (2)
68
+
69
+ | File | Tests |
70
+ | ----------------------- | ----------------------------------------------------------- |
71
+ | `completion.test.ts` | ~1690 lines — largest test file; bash + zsh output matching |
72
+ | (cli-completion-e2e.ts) | Lives in `cli/` — end-to-end completion via CLI builder |
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Shared test helpers for extracting structure from generated completion scripts.
3
+ *
4
+ * @module dreamcli/core/completion/completion-test-helpers
5
+ * @internal
6
+ */
7
+
8
+ /**
9
+ * @internal
10
+ * Extract the root-level completion words from a bash completion script.
11
+ *
12
+ * Finds the last `compgen -W '...' -- "$cur"` block and returns the
13
+ * space-separated words as an array.
14
+ *
15
+ * @param script - The full generated bash completion script.
16
+ * @returns The root-level completion words.
17
+ */
18
+ function extractBashRootWords(script: string): readonly string[] {
19
+ const matches = [...script.matchAll(/compgen -W '([^']*)' -- "\$cur"/g)];
20
+ const words = matches[matches.length - 1]?.[1];
21
+ if (words === undefined) {
22
+ throw new Error('Could not find root bash completion words');
23
+ }
24
+ return words.split(' ').filter(Boolean);
25
+ }
26
+
27
+ /**
28
+ * @internal
29
+ * Extract the body of the root zsh completion function from a zsh
30
+ * completion script.
31
+ *
32
+ * @param script - The full generated zsh completion script.
33
+ * @param funcName - The function name to locate (e.g. `'_mycli'`).
34
+ * @returns The function body (from signature through closing brace).
35
+ */
36
+ function extractZshRootFunction(script: string, funcName: string): string {
37
+ const start = script.indexOf(`${funcName}() {`);
38
+ if (start === -1) {
39
+ throw new Error(`Could not find zsh root function '${funcName}'`);
40
+ }
41
+ const end = script.indexOf(`\n}\n\n${funcName} "$@"`, start);
42
+ if (end === -1) {
43
+ throw new Error(`Could not find end of zsh root function '${funcName}'`);
44
+ }
45
+ return script.slice(start, end + 2);
46
+ }
47
+
48
+ export { extractBashRootWords, extractZshRootFunction };