@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.2

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 (136) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/dist/core/cli/dispatch.mjs +214 -1
  3. package/dist/core/cli/help-links.mjs +41 -1
  4. package/dist/core/cli/index.mjs +901 -1
  5. package/dist/core/cli/planner.mjs +300 -1
  6. package/dist/core/cli/plugin.mjs +41 -1
  7. package/dist/core/cli/propagate.mjs +57 -1
  8. package/dist/core/cli/root-help.mjs +208 -4
  9. package/dist/core/cli/root-surface.mjs +27 -1
  10. package/dist/core/cli/runtime-preflight.mjs +168 -1
  11. package/dist/core/completion/index.mjs +90 -1
  12. package/dist/core/completion/shells/bash.mjs +304 -3
  13. package/dist/core/completion/shells/fish.mjs +159 -2
  14. package/dist/core/completion/shells/powershell.mjs +353 -2
  15. package/dist/core/completion/shells/shared.mjs +154 -1
  16. package/dist/core/completion/shells/zsh.mjs +244 -2
  17. package/dist/core/config/index.mjs +246 -1
  18. package/dist/core/config/package-json.mjs +385 -3
  19. package/dist/core/errors/index.mjs +87 -1
  20. package/dist/core/execution/index.mjs +189 -1
  21. package/dist/core/help/ansi.mjs +122 -2
  22. package/dist/core/help/index.mjs +329 -7
  23. package/dist/core/json-schema/index.mjs +487 -9
  24. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  25. package/dist/core/output/activity.mjs +452 -1
  26. package/dist/core/output/bind.mjs +56 -1
  27. package/dist/core/output/contracts.mjs +57 -1
  28. package/dist/core/output/display-value.mjs +32 -1
  29. package/dist/core/output/index.d.mts +21 -0
  30. package/dist/core/output/index.mjs +442 -2
  31. package/dist/core/output/renderers.mjs +46 -1
  32. package/dist/core/output/writer.mjs +12 -1
  33. package/dist/core/parse/index.mjs +555 -1
  34. package/dist/core/prompt/index.d.mts +0 -1
  35. package/dist/core/prompt/index.mjs +348 -6
  36. package/dist/core/resolve/args.mjs +105 -1
  37. package/dist/core/resolve/coerce.mjs +279 -1
  38. package/dist/core/resolve/config.mjs +19 -1
  39. package/dist/core/resolve/errors.mjs +140 -2
  40. package/dist/core/resolve/flags.mjs +196 -1
  41. package/dist/core/resolve/index.mjs +85 -1
  42. package/dist/core/resolve/property.d.mts +0 -1
  43. package/dist/core/resolve/property.mjs +45 -1
  44. package/dist/core/schema/arg.mjs +463 -1
  45. package/dist/core/schema/command.d.mts +18 -0
  46. package/dist/core/schema/command.mjs +712 -1
  47. package/dist/core/schema/flag.mjs +453 -1
  48. package/dist/core/schema/middleware.mjs +41 -1
  49. package/dist/core/schema/number-constraints.mjs +60 -1
  50. package/dist/core/schema-dsl/runtime.mjs +271 -2
  51. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  52. package/dist/core/testkit/index.mjs +83 -1
  53. package/dist/index.d.mts +2 -1
  54. package/dist/index.mjs +22 -1
  55. package/dist/runtime/adapter.mjs +82 -1
  56. package/dist/runtime/auto.mjs +46 -1
  57. package/dist/runtime/bun.mjs +28 -1
  58. package/dist/runtime/deno.mjs +217 -2
  59. package/dist/runtime/detect.mjs +45 -1
  60. package/dist/runtime/node.mjs +169 -2
  61. package/dist/runtime/paths.mjs +48 -1
  62. package/dist/runtime.mjs +7 -1
  63. package/dist/strings.mjs +22 -1
  64. package/dist/testkit.mjs +5 -1
  65. package/dist/version.mjs +7 -1
  66. package/package.json +17 -26
  67. package/src/core/cli/dispatch.ts +0 -355
  68. package/src/core/cli/help-links.ts +0 -82
  69. package/src/core/cli/index.ts +0 -1614
  70. package/src/core/cli/planner.ts +0 -656
  71. package/src/core/cli/plugin.ts +0 -117
  72. package/src/core/cli/propagate.ts +0 -97
  73. package/src/core/cli/root-help.ts +0 -342
  74. package/src/core/cli/root-surface.ts +0 -87
  75. package/src/core/cli/runtime-preflight.ts +0 -456
  76. package/src/core/completion/index.ts +0 -138
  77. package/src/core/completion/shells/bash.ts +0 -459
  78. package/src/core/completion/shells/fish.ts +0 -259
  79. package/src/core/completion/shells/powershell.ts +0 -439
  80. package/src/core/completion/shells/shared.ts +0 -310
  81. package/src/core/completion/shells/zsh.ts +0 -381
  82. package/src/core/config/index.ts +0 -417
  83. package/src/core/config/package-json.ts +0 -560
  84. package/src/core/errors/index.ts +0 -193
  85. package/src/core/execution/index.ts +0 -265
  86. package/src/core/help/ansi.ts +0 -144
  87. package/src/core/help/index.ts +0 -563
  88. package/src/core/json-schema/index.ts +0 -910
  89. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  90. package/src/core/output/activity.ts +0 -575
  91. package/src/core/output/bind.ts +0 -59
  92. package/src/core/output/contracts.ts +0 -194
  93. package/src/core/output/display-value.ts +0 -48
  94. package/src/core/output/index.ts +0 -704
  95. package/src/core/output/renderers.ts +0 -125
  96. package/src/core/output/writer.ts +0 -46
  97. package/src/core/parse/index.ts +0 -742
  98. package/src/core/prompt/index.ts +0 -623
  99. package/src/core/resolve/args.ts +0 -144
  100. package/src/core/resolve/coerce.ts +0 -500
  101. package/src/core/resolve/config.ts +0 -26
  102. package/src/core/resolve/contracts.ts +0 -135
  103. package/src/core/resolve/errors.ts +0 -227
  104. package/src/core/resolve/flags.ts +0 -269
  105. package/src/core/resolve/index.ts +0 -108
  106. package/src/core/resolve/property.ts +0 -99
  107. package/src/core/schema/activity.ts +0 -240
  108. package/src/core/schema/arg.ts +0 -841
  109. package/src/core/schema/command.ts +0 -1500
  110. package/src/core/schema/flag.ts +0 -917
  111. package/src/core/schema/index.ts +0 -96
  112. package/src/core/schema/middleware.ts +0 -171
  113. package/src/core/schema/number-constraints.ts +0 -153
  114. package/src/core/schema/prompt.ts +0 -171
  115. package/src/core/schema/run.ts +0 -198
  116. package/src/core/schema-dsl/index.ts +0 -109
  117. package/src/core/schema-dsl/parse.ts +0 -262
  118. package/src/core/schema-dsl/runtime.ts +0 -609
  119. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  120. package/src/core/testkit/index.ts +0 -147
  121. package/src/index.ts +0 -181
  122. package/src/runtime/adapter.ts +0 -303
  123. package/src/runtime/auto.ts +0 -86
  124. package/src/runtime/bun.ts +0 -48
  125. package/src/runtime/deno.ts +0 -367
  126. package/src/runtime/detect.ts +0 -105
  127. package/src/runtime/index.ts +0 -21
  128. package/src/runtime/node-builtins.d.ts +0 -27
  129. package/src/runtime/node.ts +0 -289
  130. package/src/runtime/paths.ts +0 -64
  131. package/src/runtime/support.ts +0 -77
  132. package/src/runtime.ts +0 -31
  133. package/src/schema.ts +0 -16
  134. package/src/strings.ts +0 -34
  135. package/src/testkit.ts +0 -25
  136. package/src/version.ts +0 -20
@@ -1,147 +0,0 @@
1
- /**
2
- * Test harness: command.run() with injected state, output capture.
3
- *
4
- * Provides {@linkcode runCommand()} — the in-process test harness wrapper over DreamCLI's
5
- * shared executor.\
6
- * It wires capture output and standalone command metadata,
7
- * then returns a structured {@linkcode RunResult} with exitCode and captured output.
8
- *
9
- * This keeps command tests process-free without testkit owning the canonical pipeline:
10
- *
11
- * ```text
12
- * parse -> resolve -> execute
13
- * ```
14
- * @module dreamcli/core/testkit
15
- */
16
-
17
- import { buildRunResult, executeCommand } from '#internals/core/execution/index.ts';
18
- import type { CapturedOutput } from '#internals/core/output/index.ts';
19
- import { createCaptureOutput } from '#internals/core/output/index.ts';
20
- import { includesBeforeSeparator, stripBeforeSeparator } from '#internals/core/parse/index.ts';
21
- import type { CommandMeta, Out, RunnableCommand } from '#internals/core/schema/command.ts';
22
- import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
23
-
24
- // RunOptions and RunResult are defined in schema/run.ts so the execution
25
- // contract is shared by schema, CLI dispatch, and testkit. Re-exported here
26
- // for public testkit continuity.
27
-
28
- // --- Core execution pipeline
29
-
30
- /**
31
- * Run a command builder against the given argv with injected options.
32
- *
33
- * This is the testkit wrapper around the shared executor:
34
- * 1. Apply the CLI root-flag layer (detect/strip `--json`) so copied real argv works
35
- * 2. Create or reuse capture output
36
- * 3. Build standalone schema/meta defaults when CLI dispatch did not
37
- * 4. Delegate parse -> resolve -> execute to the shared executor
38
- * 5. Return the structured result with captured buffers
39
- *
40
- * Errors are normalized by the shared executor into structured {@linkcode RunResult}s
41
- * with appropriate exit codes. The function never throws.
42
- *
43
- * @param cmd - The command builder (must have an action handler)
44
- * @param argv - Raw argv strings (NOT including the command name itself). A
45
- * CLI-level `--json` before the `--` separator is honored and stripped here,
46
- * just like the real CLI root — so `['--json']` enables JSON mode rather than
47
- * failing as an unknown flag. Equivalent to passing `{ jsonMode: true }`.
48
- * @param options - Injectable runtime state
49
- * @returns Structured run result with exit code and captured output
50
- */
51
- async function runCommand(
52
- cmd: RunnableCommand,
53
- argv: readonly string[],
54
- options?: RunOptions,
55
- ): Promise<RunResult> {
56
- // Root-flag layer mirroring `CLIBuilder.execute()`: `--json` is owned by the
57
- // CLI root, not the command schema, so it would otherwise reach `parse()` as
58
- // an unknown flag (#33). Detect it before the `--` separator (a literal
59
- // `--json` positional after `--` survives), enable JSON mode, and strip it so
60
- // the command schema never sees it. The explicit `options.jsonMode` keeps
61
- // working — either source enables JSON mode.
62
- const hasJsonFlag = includesBeforeSeparator(argv, '--json');
63
- const jsonMode = hasJsonFlag || options?.jsonMode === true;
64
- const effectiveArgv = hasJsonFlag ? stripBeforeSeparator(argv, '--json') : argv;
65
-
66
- let out: Out;
67
- let captured: CapturedOutput;
68
- if (options?.out !== undefined) {
69
- out = options.out;
70
- captured = options.captured ?? { stdout: [], stderr: [], activity: [] };
71
- } else {
72
- const captureOptions = {
73
- ...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
74
- ...(jsonMode ? { jsonMode } : {}),
75
- ...(options?.isTTY !== undefined ? { isTTY: options.isTTY } : {}),
76
- };
77
- [out, captured] = createCaptureOutput(
78
- Object.keys(captureOptions).length > 0 ? captureOptions : undefined,
79
- );
80
- }
81
-
82
- // Use merged schema (with propagated flags) when provided by dispatch layer,
83
- // otherwise fall back to the command's own schema.
84
- const schema = options?.mergedSchema ?? cmd.schema;
85
- const meta: CommandMeta = options?.meta ?? {
86
- name: schema.name,
87
- bin: options?.help?.binName ?? schema.name,
88
- version: undefined,
89
- command: schema.name,
90
- };
91
-
92
- // Thread the effective JSON mode into the executor so its error path renders
93
- // structured JSON, matching dispatch where the planner sets `options.jsonMode`.
94
- const effectiveOptions: RunOptions | undefined =
95
- options !== undefined
96
- ? { ...options, ...(jsonMode ? { jsonMode } : {}) }
97
- : jsonMode
98
- ? { jsonMode }
99
- : undefined;
100
-
101
- const result = await executeCommand({
102
- command: cmd,
103
- argv: effectiveArgv,
104
- out,
105
- schema,
106
- meta,
107
- ...(effectiveOptions !== undefined ? { options: effectiveOptions } : {}),
108
- });
109
-
110
- return buildRunResult(result, captured);
111
- }
112
-
113
- // --- Exports
114
-
115
- /**
116
- * Options for {@linkcode runCommand} — process-free command execution.
117
- *
118
- * Every field is optional. Inject env, config, prompt answers, and
119
- * output capture without touching process state.
120
- *
121
- * @example
122
- * ```ts
123
- * const result = await runCommand(cmd, ['--verbose'], {
124
- * env: { LOG_LEVEL: 'debug' },
125
- * config: { theme: 'dark' },
126
- * });
127
- * ```
128
- */
129
- /**
130
- * Structured result from {@linkcode runCommand}.
131
- *
132
- * Contains the exit code, captured stdout/stderr output, recorded
133
- * {@linkcode ActivityEvent | activity events}, and an `error` field
134
- * that is `undefined` on success and a {@linkcode CLIError} on failure.
135
- *
136
- * @example
137
- * ```ts
138
- * const result = await runCommand(greetCmd, ['World']);
139
- *
140
- * expect(result.exitCode).toBe(0);
141
- * expect(result.stdout).toContain('Hello, World!');
142
- * expect(result.error).toBeUndefined();
143
- * ```
144
- */
145
- export type { RunOptions, RunResult };
146
-
147
- export { runCommand };
package/src/index.ts DELETED
@@ -1,181 +0,0 @@
1
- /**
2
- * DreamCLI — Schema-first, fully typed TypeScript CLI framework.
3
- *
4
- * Start here for most applications:
5
- * - {@link cli} to define a program
6
- * - {@link command} to define commands and groups
7
- * - {@link flag} and {@link arg} to describe inputs
8
- *
9
- * This root entrypoint also re-exports lower-level building blocks such as
10
- * parsing, resolution, config discovery, and help formatting. Those are useful
11
- * for advanced integrations, custom tooling, or focused tests, but they are
12
- * not the typical starting point for application code.
13
- *
14
- * Test utilities (runCommand, createCaptureOutput, createTestPrompter, etc.)
15
- * are available from `@kjanat/dreamcli/testkit`. Runtime adapters (createAdapter,
16
- * RuntimeAdapter, etc.) are available from `@kjanat/dreamcli/runtime`.
17
- *
18
- * @module @kjanat/dreamcli
19
- */
20
-
21
- export type {
22
- BeforeParseParams,
23
- CLIOptions,
24
- CLIPlugin,
25
- CLIPluginHooks,
26
- CLIRunOptions,
27
- CLISchema,
28
- ConfigSettings,
29
- HelpLinks,
30
- InferNameOption,
31
- ManifestPresetSettings,
32
- ManifestSettings,
33
- PackageJsonSettings,
34
- PluginCommandContext,
35
- ResolvedCommandParams,
36
- ResolvedManifestSettings,
37
- } from './core/cli/index.ts';
38
- export { CLIBuilder, cli, plugin } from './core/cli/index.ts';
39
- export type { CompletionOptions, Shell } from './core/completion/index.ts';
40
- export {
41
- generateBashCompletion,
42
- generateCompletion,
43
- generateFishCompletion,
44
- generatePowerShellCompletion,
45
- generateZshCompletion,
46
- SHELLS,
47
- } from './core/completion/index.ts';
48
- export type {
49
- ConfigAdapter,
50
- ConfigDiscoveryOptions,
51
- ConfigDiscoveryResult,
52
- ConfigFound,
53
- ConfigNotFound,
54
- FormatLoader,
55
- ManifestDiscoveryOptions,
56
- PackageJsonAdapter,
57
- PackageJsonData,
58
- PackageRepository,
59
- } from './core/config/index.ts';
60
- export {
61
- buildConfigSearchPaths,
62
- configFormat,
63
- discoverConfig,
64
- discoverManifest,
65
- discoverPackageJson,
66
- inferCliName,
67
- packageRepositoryUrl,
68
- } from './core/config/index.ts';
69
- export type {
70
- CLIErrorJSON,
71
- CLIErrorOptions,
72
- ErrorCode,
73
- ParseErrorCode,
74
- ParseErrorOptions,
75
- ValidationErrorCode,
76
- ValidationErrorOptions,
77
- } from './core/errors/index.ts';
78
- export {
79
- CLIError,
80
- isCLIError,
81
- isParseError,
82
- isValidationError,
83
- ParseError,
84
- ValidationError,
85
- } from './core/errors/index.ts';
86
- export type { HelpOptions } from './core/help/index.ts';
87
- export { formatHelp, osc8, visibleWidth } from './core/help/index.ts';
88
- export type { JsonSchemaOptions } from './core/json-schema/index.ts';
89
- export {
90
- definitionMetaSchema,
91
- generateInputSchema,
92
- generateSchema,
93
- } from './core/json-schema/index.ts';
94
- export type { OutputOptions, Verbosity, WriteFn } from './core/output/index.ts';
95
- export { createOutput } from './core/output/index.ts';
96
- export type { ParseResult, Token } from './core/parse/index.ts';
97
- export { parse, tokenize } from './core/parse/index.ts';
98
- export type {
99
- PromptEngine,
100
- ReadFn,
101
- ResolvedMultiselectPromptConfig,
102
- ResolvedPromptConfig,
103
- ResolvedSelectPromptConfig,
104
- } from './core/prompt/index.ts';
105
- export { createTerminalPrompter, resolvePromptConfig } from './core/prompt/index.ts';
106
- export type { DeprecationWarning, ResolveOptions, ResolveResult } from './core/resolve/index.ts';
107
- export { resolve } from './core/resolve/index.ts';
108
- export type {
109
- ActionHandler,
110
- ActionParams,
111
- ActivityEvent,
112
- AnyCommandBuilder,
113
- ArgConfig,
114
- ArgFactory,
115
- ArgKind,
116
- ArgParseFn,
117
- ArgPresence,
118
- ArgSchema,
119
- CommandArgEntry,
120
- CommandConfig,
121
- CommandExample,
122
- CommandMeta,
123
- CommandSchema,
124
- ConfirmPromptConfig,
125
- DeriveHandler,
126
- DeriveParams,
127
- Fallback,
128
- FlagConfig,
129
- FlagFactory,
130
- FlagKind,
131
- FlagParseFn,
132
- FlagPresence,
133
- FlagSchema,
134
- InferArg,
135
- InferArgs,
136
- InferFlag,
137
- InferFlags,
138
- InputPromptConfig,
139
- InteractiveParams,
140
- InteractiveResolver,
141
- InteractiveResult,
142
- Middleware,
143
- MiddlewareHandler,
144
- MiddlewareParams,
145
- MultiselectPromptConfig,
146
- NumberConstraints,
147
- NumberConstraintViolation,
148
- Out,
149
- ProgressHandle,
150
- ProgressOptions,
151
- PromptConfig,
152
- PromptConfigBase,
153
- PromptKind,
154
- PromptResult,
155
- ResolvedArgValue,
156
- ResolvedValue,
157
- RunResult,
158
- SelectChoice,
159
- SelectPromptConfig,
160
- SpinnerHandle,
161
- SpinnerOptions,
162
- TableColumn,
163
- TableFormat,
164
- TableOptions,
165
- TableStream,
166
- WithArgPresence,
167
- WithPresence,
168
- WithVariadic,
169
- } from './core/schema/index.ts';
170
- export {
171
- ArgBuilder,
172
- arg,
173
- CommandBuilder,
174
- command,
175
- createArgSchema,
176
- createSchema,
177
- FlagBuilder,
178
- flag,
179
- group,
180
- middleware,
181
- } from './core/schema/index.ts';
@@ -1,303 +0,0 @@
1
- /**
2
- * Runtime adapter interface. Core never imports runtime-specific modules directly;
3
- * all platform-dependent behavior flows through this contract.
4
- *
5
- * The adapter abstracts the minimal set of platform-dependent operations:
6
- * argv/env access, I/O streams, TTY detection, working directory, and
7
- * process exit. Concrete implementations exist for Node, Bun, and Deno.
8
- *
9
- * @module @kjanat/dreamcli/runtime/adapter
10
- */
11
-
12
- import type { WriteFn } from '#internals/core/output/index.ts';
13
- import type { ReadFn } from '#internals/core/prompt/index.ts';
14
-
15
- // --- Runtime adapter interface — the single platform abstraction boundary
16
-
17
- /**
18
- * Runtime adapter interface.
19
- *
20
- * Defines the minimal contract between the platform-agnostic core and
21
- * the host runtime (Node.js, Bun, Deno). Every platform-dependent
22
- * operation flows through this interface — the core never calls
23
- * `process.*`, `Deno.*`, or `Bun.*` directly.
24
- *
25
- * Adapters are designed to be:
26
- * - **Immutable in shape:** all properties are readonly
27
- * - **Minimal:** only the operations the framework actually needs
28
- * - **Testable:** easily stubbed in tests via {@linkcode createTestAdapter | createTestAdapter()}
29
- *
30
- * @example
31
- * ```ts
32
- * // Production: auto-detected
33
- * cli('mycli').run(); // uses Node/Bun/Deno adapter
34
- *
35
- * // Test: explicit adapter
36
- * cli('mycli').run({ adapter: createTestAdapter({ argv: ['deploy'] }) });
37
- * ```
38
- */
39
- interface RuntimeAdapter {
40
- /** Raw argv array (including binary + script path, e.g. `['node', 'cli.js', 'deploy']`). */
41
- readonly argv: readonly string[];
42
-
43
- /**
44
- * Environment variables.
45
- * Values are `string | undefined` — mirrors Node's `process.env` semantics.
46
- */
47
- readonly env: Readonly<Record<string, string | undefined>>;
48
-
49
- /** Current working directory (absolute path). */
50
- readonly cwd: string;
51
-
52
- /** Writer for stdout. Framework routes `out.log`/`out.info` through this. */
53
- readonly stdout: WriteFn;
54
-
55
- /** Writer for stderr. Framework routes `out.warn`/`out.error` through this. */
56
- readonly stderr: WriteFn;
57
-
58
- /**
59
- * Line reader for stdin. Used by the prompt engine for interactive input.
60
- *
61
- * Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
62
- * indicating the user closed the input stream (treated as cancel).
63
- */
64
- readonly stdin: ReadFn;
65
-
66
- /**
67
- * Read all of stdin as a single string (for piped data).
68
- *
69
- * Returns the full stdin contents when data is piped (`stdinIsTTY` is
70
- * false), or `null` when stdin is a TTY (no piped data available).
71
- *
72
- * Used by the resolve chain for args with `.stdin()` configured.
73
- * Unlike {@link stdin} (which reads one line for prompts), this
74
- * consumes the entire stream to EOF.
75
- *
76
- * @returns Full stdin contents as a string, or `null` if stdin is a TTY.
77
- */
78
- readonly readStdin: () => Promise<string | null>;
79
-
80
- /** Whether stdout is connected to a TTY. */
81
- readonly isTTY: boolean;
82
-
83
- /** Whether stdin is connected to a TTY (used for prompt gating). */
84
- readonly stdinIsTTY: boolean;
85
-
86
- /**
87
- * Exit the process with the given code.
88
- * Must not return (divergent function).
89
- */
90
- readonly exit: (code: number) => never;
91
-
92
- // --- Filesystem primitives (config file discovery) ---
93
-
94
- /**
95
- * Read a file as UTF-8 text.
96
- *
97
- * Returns file contents on success, `null` if the file does not exist
98
- * (ENOENT/NotFound). Throws on other I/O errors (permission denied,
99
- * is-directory, etc.) — those indicate unexpected failures, not
100
- * "try the next path".
101
- *
102
- * Used by config file discovery to probe multiple candidate paths.
103
- */
104
- readonly readFile: (path: string) => Promise<string | null>;
105
-
106
- /**
107
- * User home directory (absolute path).
108
- *
109
- * - Node/Bun: derived from `HOME` / `USERPROFILE` env
110
- * - Deno: `Deno.env.get('HOME')` / `Deno.env.get('USERPROFILE')`
111
- */
112
- readonly homedir: string;
113
-
114
- /**
115
- * Platform-specific user configuration directory (absolute path).
116
- *
117
- * - Unix: `$XDG_CONFIG_HOME` or `~/.config`
118
- * - Windows: `%APPDATA%` or `~\AppData\Roaming`
119
- *
120
- * Config discovery appends the app-specific subdirectory.
121
- */
122
- readonly configDir: string;
123
- }
124
-
125
- // --- Test adapter — injectable stub for testing
126
-
127
- /**
128
- * Options for creating a test adapter.
129
- *
130
- * All fields are optional — sensible defaults are applied for testing
131
- * scenarios (empty argv, empty env, noop stdout/stderr, non-TTY, exit
132
- * throws instead of killing the process).
133
- */
134
- interface TestAdapterOptions {
135
- /** Raw argv (defaults to `['node', 'test']`). */
136
- readonly argv?: readonly string[];
137
-
138
- /** Environment variables (defaults to `{}`). */
139
- readonly env?: Readonly<Record<string, string | undefined>>;
140
-
141
- /** Working directory (defaults to `'/test'`). */
142
- readonly cwd?: string;
143
-
144
- /** Stdout writer (defaults to noop). */
145
- readonly stdout?: WriteFn;
146
-
147
- /** Stderr writer (defaults to noop). */
148
- readonly stderr?: WriteFn;
149
-
150
- /**
151
- * Stdin line reader (defaults to returning `null` — immediate EOF).
152
- *
153
- * Use a custom {@linkcode ReadFn} to simulate user input in tests.
154
- */
155
- readonly stdin?: ReadFn;
156
-
157
- /**
158
- * Piped stdin data for testing args with `.stdin()` configured.
159
- *
160
- * When provided and `stdinIsTTY` is `false`, `readStdin()` returns this
161
- * string once, then `null` on subsequent reads. When absent, or when
162
- * `stdinIsTTY` is `true`, `readStdin()` returns `null`.
163
- *
164
- * @example
165
- * ```ts
166
- * createTestAdapter({
167
- * stdinData: '{"key": "value"}',
168
- * })
169
- * ```
170
- */
171
- readonly stdinData?: string;
172
-
173
- /** TTY flag for stdout (defaults to `false`). */
174
- readonly isTTY?: boolean;
175
-
176
- /** TTY flag for stdin (defaults to `false`). */
177
- readonly stdinIsTTY?: boolean;
178
-
179
- /**
180
- * Exit function (defaults to throwing {@linkcode ExitError}).
181
- * The default throw-based exit allows tests to catch the exit code.
182
- */
183
- readonly exit?: (code: number) => never;
184
-
185
- // --- Filesystem stubs ---
186
-
187
- /**
188
- * File reader stub (defaults to returning `null` — all files not found).
189
- *
190
- * Supply a custom function to simulate a virtual filesystem in tests:
191
- * ```ts
192
- * createTestAdapter({
193
- * readFile: (path) => Promise.resolve(
194
- * path === '/home/test/.config/myapp/config.json'
195
- * ? '{"region":"eu"}'
196
- * : null
197
- * ),
198
- * })
199
- * ```
200
- */
201
- readonly readFile?: (path: string) => Promise<string | null>;
202
-
203
- /** Home directory (defaults to `'/home/test'`). */
204
- readonly homedir?: string;
205
-
206
- /** Config directory (defaults to `'/home/test/.config'`). */
207
- readonly configDir?: string;
208
- }
209
-
210
- /**
211
- * Error thrown by adapter implementations that model process exit as an
212
- * exception instead of terminating immediately.
213
- *
214
- * Runtime and CLI dispatch layers can catch this to perform real process
215
- * termination, while tests can assert on exit codes without killing the
216
- * runner:
217
- *
218
- * ```ts
219
- * try {
220
- * await cli.run({ adapter: createTestAdapter() });
221
- * } catch (e) {
222
- * if (e instanceof ExitError) expect(e.code).toBe(0);
223
- * }
224
- * ```
225
- */
226
- class ExitError extends Error {
227
- /** Error name — always `'ExitError'` for `instanceof` checks. */
228
- override readonly name = 'ExitError';
229
-
230
- /** The exit code passed to `exit()`. */
231
- readonly code: number;
232
-
233
- /** Create an ExitError for the given process exit code. */
234
- constructor(code: number) {
235
- super(`Process exited with code ${code}`);
236
- this.code = code;
237
- }
238
- }
239
-
240
- /** Noop writer — silently discards output. */
241
- const noopWrite: WriteFn = () => {};
242
-
243
- /** Noop reader — returns `null` (EOF) immediately. */
244
- const eofRead: ReadFn = () => Promise.resolve(null);
245
-
246
- /** Noop file reader — returns `null` (not found) for all paths. */
247
- const noopReadFile: (path: string) => Promise<string | null> = () => Promise.resolve(null);
248
-
249
- /**
250
- * Create a test runtime adapter with injectable process state.
251
- *
252
- * Use this in `@kjanat/dreamcli/testkit` tests when you need to simulate argv,
253
- * environment variables, TTY state, stdin, or config-file reads without
254
- * touching the host process.
255
- *
256
- * @param options - Optional overrides for any adapter field.
257
- * @returns A {@linkcode RuntimeAdapter} suitable for test scenarios.
258
- *
259
- * @example
260
- * ```ts
261
- * const adapter = createTestAdapter({
262
- * argv: ['node', 'cli.js', 'deploy', '--force'],
263
- * env: { DEPLOY_REGION: 'us' },
264
- * });
265
- *
266
- * const result = await cli('mycli').run({ adapter });
267
- * ```
268
- */
269
- function createTestAdapter(options?: TestAdapterOptions): RuntimeAdapter {
270
- const stdinIsTTY = options?.stdinIsTTY ?? false;
271
- let stdinData = !stdinIsTTY ? options?.stdinData : undefined;
272
- return {
273
- argv: options?.argv ?? ['node', 'test'],
274
- env: options?.env ?? {},
275
- cwd: options?.cwd ?? '/test',
276
- stdout: options?.stdout ?? noopWrite,
277
- stderr: options?.stderr ?? noopWrite,
278
- stdin: options?.stdin ?? eofRead,
279
- readStdin: () => {
280
- if (stdinData === undefined) {
281
- return Promise.resolve(null);
282
- }
283
- const result = stdinData;
284
- stdinData = undefined;
285
- return Promise.resolve(result);
286
- },
287
- isTTY: options?.isTTY ?? false,
288
- stdinIsTTY,
289
- exit:
290
- options?.exit ??
291
- ((code: number): never => {
292
- throw new ExitError(code);
293
- }),
294
- readFile: options?.readFile ?? noopReadFile,
295
- homedir: options?.homedir ?? '/home/test',
296
- configDir: options?.configDir ?? '/home/test/.config',
297
- };
298
- }
299
-
300
- // --- Exports
301
-
302
- export type { RuntimeAdapter, TestAdapterOptions };
303
- export { createTestAdapter, ExitError };