@kjanat/dreamcli 2.5.0 → 3.0.0-rc.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 (89) hide show
  1. package/CHANGELOG.md +128 -1
  2. package/README.md +9 -2
  3. package/dist/core/cli/index.d.mts +109 -16
  4. package/dist/core/cli/index.mjs +1 -1
  5. package/dist/core/cli/planner.d.mts +27 -5
  6. package/dist/core/cli/planner.mjs +1 -1
  7. package/dist/core/cli/root-help.d.mts +16 -2
  8. package/dist/core/cli/root-help.mjs +3 -5
  9. package/dist/core/cli/root-surface.d.mts +18 -3
  10. package/dist/core/cli/root-surface.mjs +1 -1
  11. package/dist/core/cli/runtime-preflight.d.mts +16 -1
  12. package/dist/core/cli/runtime-preflight.mjs +1 -1
  13. package/dist/core/completion/index.d.mts +32 -1
  14. package/dist/core/completion/index.mjs +1 -1
  15. package/dist/core/completion/shells/shared.d.mts +10 -0
  16. package/dist/core/completion/shells/shared.mjs +1 -1
  17. package/dist/core/help/index.d.mts +45 -1
  18. package/dist/core/help/index.mjs +6 -6
  19. package/dist/core/json-schema/index.mjs +1 -1
  20. package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
  21. package/dist/core/parse/index.d.mts +15 -1
  22. package/dist/core/parse/index.mjs +1 -1
  23. package/dist/core/prompt/index.d.mts +11 -3
  24. package/dist/core/prompt/index.mjs +3 -3
  25. package/dist/core/resolve/coerce.mjs +1 -1
  26. package/dist/core/resolve/flags.mjs +1 -1
  27. package/dist/core/resolve/property.d.mts +2 -0
  28. package/dist/core/resolve/property.mjs +1 -1
  29. package/dist/core/schema/arg.d.mts +90 -10
  30. package/dist/core/schema/arg.mjs +1 -1
  31. package/dist/core/schema/command.d.mts +3 -1
  32. package/dist/core/schema/flag.d.mts +92 -2
  33. package/dist/core/schema/flag.mjs +1 -1
  34. package/dist/core/schema/index.d.mts +2 -1
  35. package/dist/core/schema/number-constraints.d.mts +96 -0
  36. package/dist/core/schema/number-constraints.mjs +1 -0
  37. package/dist/core/schema/prompt.d.mts +15 -0
  38. package/dist/core/schema/run.d.mts +4 -4
  39. package/dist/core/testkit/index.d.mts +9 -5
  40. package/dist/core/testkit/index.mjs +1 -1
  41. package/dist/index.d.mts +2 -1
  42. package/dist/index.mjs +1 -1
  43. package/dist/runtime/auto.mjs +1 -1
  44. package/dist/runtime/bun.mjs +1 -1
  45. package/dist/runtime/deno.mjs +2 -2
  46. package/dist/runtime/node.mjs +2 -2
  47. package/dist/version.mjs +1 -1
  48. package/examples/basic.ts +5 -1
  49. package/examples/gh/package.json +2 -7
  50. package/examples/pwsh-demo/package.json +1 -7
  51. package/examples/pwsh-demo/src/main.test.ts +1 -4
  52. package/examples/pwsh-demo/src/main.ts +14 -4
  53. package/examples/transport-launcher.ts +85 -0
  54. package/package.json +15 -24
  55. package/src/core/cli/dispatch.ts +7 -1
  56. package/src/core/cli/index.ts +235 -34
  57. package/src/core/cli/planner.ts +192 -23
  58. package/src/core/cli/root-help.ts +195 -105
  59. package/src/core/cli/root-surface.ts +25 -12
  60. package/src/core/cli/runtime-preflight.ts +20 -2
  61. package/src/core/completion/index.ts +50 -0
  62. package/src/core/completion/shells/powershell.ts +2 -2
  63. package/src/core/completion/shells/shared.ts +30 -3
  64. package/src/core/execution/index.ts +1 -4
  65. package/src/core/help/index.ts +57 -10
  66. package/src/core/json-schema/index.ts +23 -4
  67. package/src/core/json-schema/meta-descriptions.generated.ts +115 -98
  68. package/src/core/parse/index.ts +62 -1
  69. package/src/core/prompt/index.ts +54 -14
  70. package/src/core/resolve/coerce.ts +73 -5
  71. package/src/core/resolve/flags.ts +14 -0
  72. package/src/core/resolve/property.ts +4 -4
  73. package/src/core/schema/arg.ts +125 -3
  74. package/src/core/schema/command.ts +3 -1
  75. package/src/core/schema/flag.ts +120 -4
  76. package/src/core/schema/index.ts +5 -0
  77. package/src/core/schema/number-constraints.ts +153 -0
  78. package/src/core/schema/prompt.ts +15 -0
  79. package/src/core/schema/run.ts +4 -4
  80. package/src/core/testkit/index.ts +32 -8
  81. package/src/index.ts +2 -0
  82. package/src/runtime/auto.ts +0 -24
  83. package/src/runtime/bun.ts +0 -7
  84. package/src/runtime/deno.ts +0 -2
  85. package/src/runtime/node.ts +0 -11
  86. package/src/runtime/support.ts +1 -59
  87. package/src/schema.ts +16 -0
  88. package/dist/runtime/support.d.mts +0 -42
  89. package/dist/runtime/support.mjs +0 -1
@@ -10,7 +10,12 @@
10
10
  */
11
11
 
12
12
  import type { CompletionOptions, Shell } from '#internals/core/completion/index.ts';
13
- import { generateCompletion, SHELLS } from '#internals/core/completion/index.ts';
13
+ import {
14
+ detectShell,
15
+ generateCompletion,
16
+ normalizeShell,
17
+ SHELLS,
18
+ } from '#internals/core/completion/index.ts';
14
19
  import type { FormatLoader } from '#internals/core/config/index.ts';
15
20
  import type { PackageJsonData } from '#internals/core/config/package-json.ts';
16
21
  import { CLIError } from '#internals/core/errors/index.ts';
@@ -36,6 +41,7 @@ import type {
36
41
  } from '#internals/core/schema/command.ts';
37
42
  import { command } from '#internals/core/schema/command.ts';
38
43
  import type { FlagBuilder, FlagConfig } from '#internals/core/schema/flag.ts';
44
+ import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
39
45
  import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
40
46
  import { runCommand } from '#internals/core/testkit/index.ts';
41
47
  import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
@@ -52,6 +58,48 @@ import { prepareRuntimePreflight } from './runtime-preflight.ts';
52
58
 
53
59
  // --- Type-erased command — erasure function (interface now in schema/command.ts)
54
60
 
61
+ /** Long-flag name reserved by `.completions({ as: 'flag' })`; the planner intercepts it before dispatch. */
62
+ const COMPLETIONS_FLAG_NAME = 'completions';
63
+
64
+ /**
65
+ * Whether a command — or any of its nested subcommands — declares a flag that
66
+ * collides with the eager `--completions` flag, by canonical name or long alias.
67
+ *
68
+ * @internal
69
+ */
70
+ function commandReservesCompletionsFlag(schema: CommandSchema): boolean {
71
+ if (Object.hasOwn(schema.flags, COMPLETIONS_FLAG_NAME)) return true;
72
+ for (const flagSchema of Object.values(schema.flags)) {
73
+ if (
74
+ getFlagAliasNames(flagSchema, { kind: 'long', includeHidden: true }).includes(
75
+ COMPLETIONS_FLAG_NAME,
76
+ )
77
+ ) {
78
+ return true;
79
+ }
80
+ }
81
+ return schema.commands.some(commandReservesCompletionsFlag);
82
+ }
83
+
84
+ /**
85
+ * Reject a command whose flags would be shadowed by the eager `--completions`
86
+ * flag once `.completions({ as: 'flag' })` is active. Because the planner
87
+ * intercepts `--completions` before dispatch, such a flag could never be reached.
88
+ *
89
+ * @internal
90
+ */
91
+ function assertNoCompletionsFlagCollision(schema: CommandSchema): void {
92
+ if (commandReservesCompletionsFlag(schema)) {
93
+ throw new CLIError(
94
+ `Command '${schema.name}' defines a '--${COMPLETIONS_FLAG_NAME}' flag, which is reserved by .completions({ as: 'flag' })`,
95
+ {
96
+ code: 'RESERVED_FLAG',
97
+ suggest: `Rename the flag, or register completions as a subcommand with .completions() instead of { as: 'flag' }`,
98
+ },
99
+ );
100
+ }
101
+ }
102
+
55
103
  function commandRoutes(schema: CommandSchema): readonly string[] {
56
104
  return [schema.name, ...schema.aliases];
57
105
  }
@@ -79,10 +127,12 @@ function assertNoSiblingRouteConflict(
79
127
  function assertNoTopLevelRouteConflict(
80
128
  commands: readonly ErasedCommand[],
81
129
  incoming: CommandSchema,
130
+ defaultCommand?: ErasedCommand | undefined,
82
131
  ): void {
83
132
  const routeOwners = new Map<string, string>();
84
133
 
85
- for (const command of commands) {
134
+ const existing = defaultCommand !== undefined ? [...commands, defaultCommand] : commands;
135
+ for (const command of existing) {
86
136
  for (const route of commandRoutes(command.schema)) {
87
137
  assertNoSiblingRouteConflict('root', routeOwners, route, command.schema.name);
88
138
  }
@@ -205,12 +255,76 @@ interface CLISchema {
205
255
  * CLIBuilder.manifest | .manifest()}) is active.
206
256
  */
207
257
  readonly helpLinks: HelpLinks | undefined;
208
- /** Whether built-in `.completions()` command registration is active. */
258
+ /** Whether built-in `.completions()` registration (command or flag) is active. */
209
259
  readonly hasBuiltInCompletions: boolean;
260
+ /**
261
+ * Eager `--completions <shell>` flag configuration.
262
+ *
263
+ * Set when `.completions({ as: 'flag' })` is used instead of the default
264
+ * `completions` subcommand. When defined, the planner intercepts
265
+ * `--completions <shell>` before dispatch, prints the script, and exits;
266
+ * root help advertises the flag in its `Flags:` section.
267
+ */
268
+ readonly completionsFlag: CompletionsFlagConfig | undefined;
269
+ /**
270
+ * Consumer-configured root-help defaults.
271
+ *
272
+ * Set via the {@linkcode CLIBuilder.help | .help()} builder method and merged
273
+ * under runtime `options.help` (runtime wins) before rendering.
274
+ */
275
+ readonly helpConfig: HelpConfig | undefined;
210
276
  /** Registered CLI plugins. */
211
277
  readonly plugins: readonly CLIPlugin[];
212
278
  }
213
279
 
280
+ /**
281
+ * Configuration for the eager `--completions <shell>` flag.
282
+ *
283
+ * Stored in {@link CLISchema} when `.completions({ as: 'flag' })` is used.
284
+ *
285
+ * @internal
286
+ */
287
+ interface CompletionsFlagConfig {
288
+ /** Shell targets the flag accepts (mirrors {@link SHELLS}). */
289
+ readonly shells: readonly Shell[];
290
+ /** Generator options captured at build time (e.g. `functionPrefix`, `rootMode`). */
291
+ readonly options: CompletionOptions | undefined;
292
+ }
293
+
294
+ /**
295
+ * Consumer-facing root-help configuration set via {@linkcode CLIBuilder.help}.
296
+ *
297
+ * Every field is optional; unset fields fall back to built-in defaults and may
298
+ * be overridden per call through runtime `options.help`.
299
+ */
300
+ interface HelpConfig {
301
+ /**
302
+ * Render the default command's arguments and flags inline at the root.
303
+ *
304
+ * @defaultValue `true`
305
+ */
306
+ readonly inlineDefault?: boolean;
307
+ /**
308
+ * Also list the default command in the root `Commands:` table.
309
+ *
310
+ * By default the default command is the root surface and is omitted from the
311
+ * command list (its args/flags render inline instead).
312
+ *
313
+ * @defaultValue `false`
314
+ */
315
+ readonly showDefaultInCommands?: boolean;
316
+ /**
317
+ * Show the `Run '<bin> <command> --help' for more information.` hint.
318
+ *
319
+ * Defaults to showing the hint only when visible subcommands exist.
320
+ */
321
+ readonly footer?: boolean;
322
+ /** Maximum line width (columns). */
323
+ readonly width?: number;
324
+ /** Emit OSC 8 hyperlinks in the header when supported. */
325
+ readonly hyperlinks?: boolean;
326
+ }
327
+
214
328
  /**
215
329
  * Config discovery settings for automatic config file loading.
216
330
  *
@@ -465,6 +579,31 @@ class CLIBuilder {
465
579
  });
466
580
  }
467
581
 
582
+ /**
583
+ * Configure root-help rendering defaults.
584
+ *
585
+ * Stored on the schema and merged **under** any runtime `options.help`
586
+ * (runtime wins). Call multiple times to set fields incrementally.
587
+ *
588
+ * @param config - Help rendering options (see {@link HelpConfig}).
589
+ * @returns The builder (for chaining).
590
+ *
591
+ * @example
592
+ * ```ts
593
+ * // Echo the default command under Commands and never show the footer:
594
+ * cli('mycli')
595
+ * .help({ showDefaultInCommands: true, footer: false })
596
+ * .default(serve)
597
+ * .run();
598
+ * ```
599
+ */
600
+ help(config: HelpConfig): CLIBuilder {
601
+ return new CLIBuilder({
602
+ ...this.schema,
603
+ helpConfig: { ...this.schema.helpConfig, ...config },
604
+ });
605
+ }
606
+
468
607
  /**
469
608
  * Enable automatic config file discovery.
470
609
  *
@@ -695,7 +834,10 @@ class CLIBuilder {
695
834
  A extends Record<string, ArgBuilder<ArgConfig>>,
696
835
  C extends Record<string, unknown>,
697
836
  >(cmd: CommandBuilder<F, A, C>): CLIBuilder {
698
- assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
837
+ assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema, this.schema.defaultCommand);
838
+ if (this.schema.completionsFlag !== undefined) {
839
+ assertNoCompletionsFlagCollision(cmd.schema);
840
+ }
699
841
 
700
842
  return new CLIBuilder({
701
843
  ...this.schema,
@@ -710,8 +852,11 @@ class CLIBuilder {
710
852
  * dispatch normally, but empty argv or flags-only argv falls through to
711
853
  * this command instead of showing root help.
712
854
  *
713
- * The command is also registered as a normal subcommand (can be invoked
714
- * by name). Only one default command is allowed.
855
+ * The default command is the CLI's root *surface*: its flags and arguments
856
+ * are rendered inline in root help. It is **not** a named subcommand — it
857
+ * cannot be invoked by its own name (`mycli mycmd` does not route to it) and
858
+ * it is omitted from the root `Commands:` list by default (re-enable with
859
+ * `.help({ showDefaultInCommands: true })`). Only one default is allowed.
715
860
  *
716
861
  * @example
717
862
  * ```ts
@@ -746,11 +891,13 @@ class CLIBuilder {
746
891
  }
747
892
 
748
893
  assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
894
+ if (this.schema.completionsFlag !== undefined) {
895
+ assertNoCompletionsFlagCollision(cmd.schema);
896
+ }
749
897
 
750
898
  const erased = eraseCommand(cmd);
751
899
  return new CLIBuilder({
752
900
  ...this.schema,
753
- commands: [...this.schema.commands, erased],
754
901
  defaultCommand: erased,
755
902
  });
756
903
  }
@@ -775,28 +922,36 @@ class CLIBuilder {
775
922
  // -- Built-in subcommands ------------------------------------------------
776
923
 
777
924
  /**
778
- * Register a built-in `completions` subcommand that generates shell
779
- * completion scripts.
780
- *
781
- * The generated command accepts a `--shell` flag (required, enum of
782
- * all {@link Shell} values) and writes the completion script to stdout
783
- * via `out.log()`. Unsupported shells throw a descriptive {@linkcode CLIError}
784
- * instead of a generic parse error.
785
- *
786
- * Call this **after** registering all other commands so the completion
787
- * script includes the full command set. The captured schema is a
788
- * snapshot at call time — commands registered after `.completions()`
789
- * will not appear in the generated script. Completion options are also
790
- * captured at call time.
925
+ * Register built-in shell completion.
926
+ *
927
+ * By default (`{ as: 'command' }`) this registers a `completions` subcommand
928
+ * that accepts a `shell` argument and writes the script to stdout. With
929
+ * `{ as: 'flag' }` it instead exposes an eager `--completions <shell>` flag on
930
+ * the CLI root — no subcommand is registered, so a default command stays the
931
+ * lone root surface. The flag may be given without a value to auto-detect the
932
+ * shell from `$SHELL` / `$PSModulePath`.
933
+ *
934
+ * In subcommand mode, call this **after** registering all other commands so
935
+ * the completion script includes the full command set: that path snapshots the
936
+ * schema (and completion options) at call time, so commands registered
937
+ * afterwards will not appear in that subcommand's generated script. In flag
938
+ * mode, generation runs at execution time from the final builder schema, so
939
+ * registration order does not matter.
791
940
  *
792
941
  * @example
793
942
  * ```ts
943
+ * // Subcommand form (default):
794
944
  * cli('mycli')
795
945
  * .version('1.0.0')
796
946
  * .command(deploy)
797
- * .command(login)
798
947
  * .completions({ rootMode: 'surface' })
799
948
  * .run();
949
+ *
950
+ * // Eager-flag form, ideal for single-command CLIs:
951
+ * cli('mycli')
952
+ * .completions({ as: 'flag' })
953
+ * .default(serve)
954
+ * .run();
800
955
  * ```
801
956
  */
802
957
  completions(options?: CompletionOptions): CLIBuilder {
@@ -807,17 +962,32 @@ class CLIBuilder {
807
962
  });
808
963
  }
809
964
 
965
+ // `as: 'flag'` exposes an eager `--completions <shell>` flag instead of a
966
+ // subcommand. The planner intercepts it before dispatch (see planner.ts)
967
+ // and root help advertises it in the Flags section. No subcommand is
968
+ // registered, so the default command stays the lone root surface.
969
+ if (options?.as === 'flag') {
970
+ // The planner intercepts `--completions` before dispatch, so no command
971
+ // may already reserve that flag name.
972
+ if (this.schema.defaultCommand !== undefined) {
973
+ assertNoCompletionsFlagCollision(this.schema.defaultCommand.schema);
974
+ }
975
+ for (const registered of this.schema.commands) {
976
+ assertNoCompletionsFlagCollision(registered.schema);
977
+ }
978
+ return new CLIBuilder({
979
+ ...this.schema,
980
+ hasBuiltInCompletions: true,
981
+ completionsFlag: { shells: SHELLS, options },
982
+ });
983
+ }
984
+
810
985
  // Capture current schema — includes all commands registered so far.
811
986
  // The completions command itself is deliberately excluded from the
812
987
  // generated script (it would be noise in shell completions).
813
988
  const cliSchema = this.schema;
814
989
  const completionOptions = options;
815
990
 
816
- // Supported shells for validation. Keep in sync with completion/index.ts SHELLS.
817
- const shellMap = new Map<string, Shell>();
818
- for (const s of SHELLS) shellMap.set(s, s);
819
- shellMap.set('pwsh', 'powershell');
820
-
821
991
  const cmd = command('completions')
822
992
  .alias('completion')
823
993
  .description('Generate shell completion script')
@@ -827,12 +997,9 @@ class CLIBuilder {
827
997
  .custom((raw: string): Shell => {
828
998
  // Normalize $SHELL paths across Unix/Windows:
829
999
  // /bin/zsh → zsh, C:\Program Files\PowerShell\7\pwsh.exe → pwsh
830
- const segments = raw.split(/[\\/]/);
831
- const basename = segments[segments.length - 1] ?? raw;
832
- const name = basename.replace(/\.(?:exe|cmd|bat)$/i, '');
833
- const shell = shellMap.get(name);
1000
+ const shell = normalizeShell(raw);
834
1001
  if (shell === undefined) {
835
- throw new Error(`Unknown shell '${name}'. Valid shells: ${SHELLS.join(', ')}`);
1002
+ throw new Error(`Unknown shell '${raw}'. Valid shells: ${SHELLS.join(', ')}`);
836
1003
  }
837
1004
  return shell;
838
1005
  })
@@ -894,12 +1061,14 @@ class CLIBuilder {
894
1061
  }
895
1062
  clearRequestedExitCode(out);
896
1063
 
897
- // Resolve help options — default binName to CLI program name,
898
- // hyperlinks to TTY detection (escapes never leak into piped output)
1064
+ // Resolve help options — builder-level `.help()` config under runtime
1065
+ // `options.help` (runtime wins), then default binName to the CLI program
1066
+ // name and hyperlinks to TTY detection (escapes never leak into piped output).
899
1067
  const helpOptions: HelpOptions = {
1068
+ ...this.schema.helpConfig,
900
1069
  ...options?.help,
901
1070
  binName: options?.help?.binName ?? this.schema.name,
902
- hyperlinks: options?.help?.hyperlinks ?? out.isTTY,
1071
+ hyperlinks: options?.help?.hyperlinks ?? this.schema.helpConfig?.hyperlinks ?? out.isTTY,
903
1072
  };
904
1073
 
905
1074
  // -- Shared options for command execution ----------------------------------
@@ -925,6 +1094,34 @@ class CLIBuilder {
925
1094
  out.log(planned.version);
926
1095
  return buildRunResult({ exitCode: 0, error: undefined }, captured);
927
1096
 
1097
+ case 'root-completions': {
1098
+ const shell = planned.shell ?? detectShell(options?.env ?? {});
1099
+ if (shell === undefined) {
1100
+ const error = new CLIError('Could not detect shell', {
1101
+ code: 'MISSING_VALUE',
1102
+ suggest: `Pass one explicitly, e.g. '${helpOptions.binName} --completions zsh'`,
1103
+ });
1104
+ if (jsonMode) {
1105
+ out.json({ error: error.toJSON() });
1106
+ } else {
1107
+ out.error(error.message);
1108
+ out.error(`Suggestion: ${error.suggest}`);
1109
+ }
1110
+ return buildRunResult({ exitCode: error.exitCode, error }, captured);
1111
+ }
1112
+ const completionSchema =
1113
+ helpOptions.binName === undefined || helpOptions.binName === this.schema.name
1114
+ ? this.schema
1115
+ : { ...this.schema, name: helpOptions.binName };
1116
+ const script = generateCompletion(completionSchema, shell, planned.options);
1117
+ if (jsonMode) {
1118
+ out.json({ shell, script });
1119
+ } else {
1120
+ out.log(script);
1121
+ }
1122
+ return buildRunResult({ exitCode: 0, error: undefined }, captured);
1123
+ }
1124
+
928
1125
  case 'root-help': {
929
1126
  const helpText = formatRootHelp(resolveHelpLinksSchema(this.schema), planned.help);
930
1127
  out.log(helpText);
@@ -1385,6 +1582,8 @@ function cli(nameOrOptions: string | CLIOptions): CLIBuilder {
1385
1582
  packageJsonSettings: undefined,
1386
1583
  helpLinks: undefined,
1387
1584
  hasBuiltInCompletions: false,
1585
+ completionsFlag: undefined,
1586
+ helpConfig: undefined,
1388
1587
  plugins: [],
1389
1588
  });
1390
1589
  }
@@ -1403,7 +1602,9 @@ export type {
1403
1602
  CLIOptions,
1404
1603
  CLIRunOptions,
1405
1604
  CLISchema,
1605
+ CompletionsFlagConfig,
1406
1606
  ConfigSettings,
1607
+ HelpConfig,
1407
1608
  InferNameOption,
1408
1609
  ManifestPresetSettings,
1409
1610
  ManifestSettings,