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

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 (137) hide show
  1. package/CHANGELOG.md +37 -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.d.mts +7 -3
  66. package/dist/version.mjs +7 -1
  67. package/package.json +21 -26
  68. package/src/core/cli/dispatch.ts +0 -355
  69. package/src/core/cli/help-links.ts +0 -82
  70. package/src/core/cli/index.ts +0 -1614
  71. package/src/core/cli/planner.ts +0 -656
  72. package/src/core/cli/plugin.ts +0 -117
  73. package/src/core/cli/propagate.ts +0 -97
  74. package/src/core/cli/root-help.ts +0 -342
  75. package/src/core/cli/root-surface.ts +0 -87
  76. package/src/core/cli/runtime-preflight.ts +0 -456
  77. package/src/core/completion/index.ts +0 -138
  78. package/src/core/completion/shells/bash.ts +0 -459
  79. package/src/core/completion/shells/fish.ts +0 -259
  80. package/src/core/completion/shells/powershell.ts +0 -439
  81. package/src/core/completion/shells/shared.ts +0 -310
  82. package/src/core/completion/shells/zsh.ts +0 -381
  83. package/src/core/config/index.ts +0 -417
  84. package/src/core/config/package-json.ts +0 -560
  85. package/src/core/errors/index.ts +0 -193
  86. package/src/core/execution/index.ts +0 -265
  87. package/src/core/help/ansi.ts +0 -144
  88. package/src/core/help/index.ts +0 -563
  89. package/src/core/json-schema/index.ts +0 -910
  90. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  91. package/src/core/output/activity.ts +0 -575
  92. package/src/core/output/bind.ts +0 -59
  93. package/src/core/output/contracts.ts +0 -194
  94. package/src/core/output/display-value.ts +0 -48
  95. package/src/core/output/index.ts +0 -704
  96. package/src/core/output/renderers.ts +0 -125
  97. package/src/core/output/writer.ts +0 -46
  98. package/src/core/parse/index.ts +0 -742
  99. package/src/core/prompt/index.ts +0 -623
  100. package/src/core/resolve/args.ts +0 -144
  101. package/src/core/resolve/coerce.ts +0 -500
  102. package/src/core/resolve/config.ts +0 -26
  103. package/src/core/resolve/contracts.ts +0 -135
  104. package/src/core/resolve/errors.ts +0 -227
  105. package/src/core/resolve/flags.ts +0 -269
  106. package/src/core/resolve/index.ts +0 -108
  107. package/src/core/resolve/property.ts +0 -99
  108. package/src/core/schema/activity.ts +0 -240
  109. package/src/core/schema/arg.ts +0 -841
  110. package/src/core/schema/command.ts +0 -1500
  111. package/src/core/schema/flag.ts +0 -917
  112. package/src/core/schema/index.ts +0 -96
  113. package/src/core/schema/middleware.ts +0 -171
  114. package/src/core/schema/number-constraints.ts +0 -153
  115. package/src/core/schema/prompt.ts +0 -171
  116. package/src/core/schema/run.ts +0 -198
  117. package/src/core/schema-dsl/index.ts +0 -109
  118. package/src/core/schema-dsl/parse.ts +0 -262
  119. package/src/core/schema-dsl/runtime.ts +0 -609
  120. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  121. package/src/core/testkit/index.ts +0 -147
  122. package/src/index.ts +0 -181
  123. package/src/runtime/adapter.ts +0 -303
  124. package/src/runtime/auto.ts +0 -86
  125. package/src/runtime/bun.ts +0 -48
  126. package/src/runtime/deno.ts +0 -367
  127. package/src/runtime/detect.ts +0 -105
  128. package/src/runtime/index.ts +0 -21
  129. package/src/runtime/node-builtins.d.ts +0 -27
  130. package/src/runtime/node.ts +0 -289
  131. package/src/runtime/paths.ts +0 -64
  132. package/src/runtime/support.ts +0 -77
  133. package/src/runtime.ts +0 -31
  134. package/src/schema.ts +0 -16
  135. package/src/strings.ts +0 -34
  136. package/src/testkit.ts +0 -25
  137. package/src/version.ts +0 -20
@@ -1,86 +0,0 @@
1
- /**
2
- * Auto-detecting adapter factory.
3
- *
4
- * Uses {@link detectRuntime} to identify the current runtime and
5
- * creates the appropriate {@link RuntimeAdapter}. Falls back to the
6
- * Node adapter for unknown runtimes (safest default — most runtimes
7
- * provide a Node-compatible `process` global).
8
- *
9
- * @module @kjanat/dreamcli/runtime/auto
10
- */
11
-
12
- import type { RuntimeAdapter } from './adapter.ts';
13
- import { createBunAdapter } from './bun.ts';
14
- import type { DenoNamespace } from './deno.ts';
15
- import { createDenoAdapter } from './deno.ts';
16
- import type { GlobalForDetect } from './detect.ts';
17
- import { detectRuntime } from './detect.ts';
18
- import { createNodeAdapter } from './node.ts';
19
-
20
- function isDenoNamespace(value: unknown): value is DenoNamespace {
21
- if (typeof value !== 'object' || value === null) return false;
22
-
23
- const candidate = value as Partial<DenoNamespace>;
24
- return (
25
- Array.isArray(candidate.args) &&
26
- typeof candidate.cwd === 'function' &&
27
- typeof candidate.exit === 'function' &&
28
- typeof candidate.readTextFile === 'function' &&
29
- typeof candidate.env?.get === 'function' &&
30
- typeof candidate.env.toObject === 'function' &&
31
- typeof candidate.stdout?.writeSync === 'function' &&
32
- typeof candidate.stdout.isTerminal === 'function' &&
33
- typeof candidate.stderr?.writeSync === 'function' &&
34
- typeof candidate.stdin?.isTerminal === 'function' &&
35
- typeof candidate.stdin?.readable?.getReader === 'function'
36
- );
37
- }
38
-
39
- function getInjectedDenoNamespace(globals: GlobalForDetect): DenoNamespace | undefined {
40
- const candidate = (globals as { readonly Deno?: unknown }).Deno;
41
- return isDenoNamespace(candidate) ? candidate : undefined;
42
- }
43
-
44
- // --- Auto-adapter factory
45
-
46
- /**
47
- * Create a runtime adapter for the current environment.
48
- *
49
- * Detection order follows {@link detectRuntime}: Bun → Deno → Node → unknown.
50
- * Unknown runtimes fall back to the Node adapter because most JS runtimes
51
- * expose a Node-compatible `process` global.
52
- *
53
- * @param globals - Override `globalThis` for testing. Production callers
54
- * should omit this parameter.
55
- * @returns A {@linkcode RuntimeAdapter} for the detected runtime.
56
- *
57
- * @example
58
- * ```ts
59
- * import { cli } from '@kjanat/dreamcli';
60
- *
61
- * // Auto-detects Node/Bun/Deno and creates the right adapter
62
- * cli('mycli').run(); // uses createAdapter() internally
63
- * ```
64
- */
65
- function createAdapter(globals?: GlobalForDetect): RuntimeAdapter {
66
- const runtimeGlobals = globals ?? globalThis;
67
- const runtime = detectRuntime(runtimeGlobals);
68
-
69
- switch (runtime) {
70
- case 'bun':
71
- return createBunAdapter();
72
- case 'deno':
73
- return createDenoAdapter(getInjectedDenoNamespace(runtimeGlobals));
74
- case 'node':
75
- case 'unknown':
76
- return createNodeAdapter();
77
- default: {
78
- const _exhaustive: never = runtime;
79
- return _exhaustive;
80
- }
81
- }
82
- }
83
-
84
- // --- Exports
85
-
86
- export { createAdapter };
@@ -1,48 +0,0 @@
1
- /**
2
- * Bun runtime adapter implementation.
3
- *
4
- * Bun provides a Node-compatible `process` global, so this adapter
5
- * delegates to {@link createNodeAdapter} for all operations. The
6
- * separate factory exists to:
7
- *
8
- * 1. Make runtime selection explicit when auto-detection picks Bun
9
- * 2. Provide an extension point for Bun-specific overrides in the future
10
- * (e.g. `Bun.write` for optimized I/O, `Bun.stdin` for streaming)
11
- *
12
- * @module @kjanat/dreamcli/runtime/bun
13
- */
14
-
15
- import type { RuntimeAdapter } from './adapter.ts';
16
- import type { NodeProcess } from './node.ts';
17
- import { createNodeAdapter } from './node.ts';
18
-
19
- // --- Bun adapter factory
20
-
21
- /**
22
- * Create a runtime adapter backed by Bun's Node-compatible `process` global.
23
- *
24
- * Bun exposes `globalThis.process` with the same shape as Node.js, so this
25
- * delegates entirely to {@link createNodeAdapter}. If Bun-specific optimizations
26
- * are needed in the future (e.g. `Bun.write` for I/O), they can be layered
27
- * here without changing the public API.
28
- *
29
- * @param proc - Override the process object (useful for testing the adapter itself).
30
- * @returns A {@linkcode RuntimeAdapter} backed by Bun's process state.
31
- *
32
- * @example
33
- * ```ts
34
- * import { cli } from '@kjanat/dreamcli';
35
- * import { createBunAdapter } from '@kjanat/dreamcli/runtime';
36
- *
37
- * cli('mycli')
38
- * .command(deploy)
39
- * .run({ adapter: createBunAdapter() });
40
- * ```
41
- */
42
- function createBunAdapter(proc?: NodeProcess): RuntimeAdapter {
43
- return createNodeAdapter(proc);
44
- }
45
-
46
- // --- Exports
47
-
48
- export { createBunAdapter };
@@ -1,367 +0,0 @@
1
- /**
2
- * Deno runtime adapter implementation.
3
- *
4
- * Bridges the platform-agnostic {@linkcode RuntimeAdapter} interface to Deno's
5
- * namespace APIs (`Deno.args`, `Deno.env`, `Deno.cwd()`, etc.).
6
- *
7
- * Deno requires explicit permissions for some operations. The adapter
8
- * handles missing permissions gracefully:
9
- *
10
- * - **`--allow-env`**: needed for `Deno.env.toObject()`. Without it,
11
- * the adapter falls back to an empty env (flags using env sources
12
- * simply won't resolve from env).
13
- * - **`--allow-read`**: needed for `Deno.readTextFile()`. Without it,
14
- * `readFile` returns `null` (same as file-not-found).
15
- *
16
- * No permissions are needed for `Deno.args`, `Deno.stdout`, `Deno.stderr`,
17
- * `Deno.stdin`, `Deno.exit()`, or TTY detection.
18
- *
19
- * @module @kjanat/dreamcli/runtime/deno
20
- */
21
-
22
- import type { WriteFn } from '#internals/core/output/index.ts';
23
- import type { ReadFn } from '#internals/core/prompt/index.ts';
24
- import type { RuntimeAdapter } from './adapter.ts';
25
- import { resolveConfigDirectory, resolveHomeDirectory } from './paths.ts';
26
-
27
- // --- Minimal Deno namespace shape — avoids @types/deno dependency
28
-
29
- /**
30
- * Minimal subset of the Deno namespace needed by the adapter.
31
- *
32
- * We avoid `@types/deno` to keep the core runtime-agnostic at the type level.
33
- * This interface declares only what `createDenoAdapter` actually reads.
34
- *
35
- * The `env` property is optional because it requires `--allow-env` permission.
36
- * When permission is denied, the adapter catches the error and falls back to
37
- * an empty env object.
38
- */
39
- interface DenoNamespace {
40
- /** Build target metadata (OS detection). */
41
- readonly build: {
42
- readonly os:
43
- | 'darwin'
44
- | 'linux'
45
- | 'android'
46
- | 'windows'
47
- | 'freebsd'
48
- | 'netbsd'
49
- | 'aix'
50
- | 'solaris'
51
- | 'illumos';
52
- };
53
- /** Deno version info — used for minimum-version guard. */
54
- readonly version?: {
55
- readonly deno?: string;
56
- };
57
- /** Raw command-line args (excludes the binary/script — Deno pre-strips them). */
58
- readonly args: readonly string[];
59
-
60
- /** Environment variable access (requires `--allow-env`). */
61
- readonly env: {
62
- /** Get a single env var. Returns `undefined` if unset or permission denied. */
63
- get(key: string): string | undefined;
64
- /** Get all env vars as a plain object. Throws on permission denied. */
65
- toObject(): Record<string, string>;
66
- };
67
-
68
- /** Current working directory (may throw if `--allow-read` is denied for cwd). */
69
- cwd(): string;
70
-
71
- /** Standard output — synchronous byte writer with TTY detection. */
72
- readonly stdout: {
73
- /** Write raw bytes to stdout synchronously. */
74
- writeSync(p: Uint8Array): number;
75
- /** Whether stdout is connected to a TTY. */
76
- isTerminal(): boolean;
77
- };
78
-
79
- /** Standard error — synchronous byte writer. */
80
- readonly stderr: {
81
- /** Write raw bytes to stderr synchronously. */
82
- writeSync(p: Uint8Array): number;
83
- };
84
-
85
- /** Standard input — TTY detection and readable byte stream. */
86
- readonly stdin: {
87
- /** Whether stdin is connected to a TTY. */
88
- isTerminal(): boolean;
89
- /** Readable stream for stdin bytes. */
90
- readonly readable: ReadableStream<Uint8Array>;
91
- };
92
-
93
- /** Exit the process with the given code. */
94
- exit(code: number): never;
95
-
96
- /** Read a file as UTF-8 text (requires `--allow-read`). */
97
- readTextFile(path: string): Promise<string>;
98
- }
99
-
100
- // --- Permission-safe helpers
101
-
102
- /**
103
- * Detect whether an unknown thrown value is a Deno error by name.
104
- *
105
- * @internal
106
- */
107
- function isDenoErrorNamed(err: unknown, name: string): boolean {
108
- if (typeof err !== 'object' || err === null || !('name' in err)) return false;
109
- // After the `in` check, TS narrows err to `object & Record<'name', unknown>`.
110
- const candidate: { name: unknown } = err;
111
- return typeof candidate.name === 'string' && candidate.name === name;
112
- }
113
-
114
- /**
115
- * Safely read all environment variables. Returns empty object if
116
- * `--allow-env` permission is not granted.
117
- *
118
- * @internal
119
- */
120
- function safeEnvToObject(deno: DenoNamespace): Readonly<Record<string, string | undefined>> {
121
- try {
122
- return deno.env.toObject();
123
- } catch (err: unknown) {
124
- if (isDenoErrorNamed(err, 'PermissionDenied')) return {};
125
- throw err;
126
- }
127
- }
128
-
129
- /**
130
- * Safely get the current working directory. Returns `/` if the cwd is
131
- * inaccessible due to missing permissions.
132
- *
133
- * @internal
134
- */
135
- function safeCwd(deno: DenoNamespace): string {
136
- try {
137
- return deno.cwd();
138
- } catch (err: unknown) {
139
- if (isDenoErrorNamed(err, 'PermissionDenied')) return '/';
140
- throw err;
141
- }
142
- }
143
-
144
- // --- Deno adapter factory
145
-
146
- /**
147
- * Create a runtime adapter backed by the Deno namespace.
148
- *
149
- * Reads `Deno.args`, `Deno.env`, `Deno.cwd()`, and wraps Deno's stream-based
150
- * I/O into the {@linkcode WriteFn}/{@linkcode ReadFn} functions expected by the framework.
151
- *
152
- * Unlike Node/Bun, Deno strips the binary and script path from `Deno.args`.
153
- * The adapter prepends synthetic entries (`['deno', 'run']`) so the argv
154
- * shape matches the {@linkcode RuntimeAdapter} contract (binary + script + user args).
155
- *
156
- * @param ns - Override the Deno namespace (useful for testing the adapter itself).
157
- * @returns A {@linkcode RuntimeAdapter} backed by Deno's namespace APIs.
158
- *
159
- * @example
160
- * ```ts
161
- * import { cli } from '@kjanat/dreamcli';
162
- * import { createDenoAdapter } from '@kjanat/dreamcli/runtime';
163
- *
164
- * cli('mycli')
165
- * .command(deploy)
166
- * .run({ adapter: createDenoAdapter() });
167
- * ```
168
- */
169
- function createDenoAdapter(ns?: DenoNamespace): RuntimeAdapter {
170
- const d = ns ?? getDenoNamespace();
171
- const encoder = new TextEncoder();
172
-
173
- // --- Synthetic argv: Deno.args has user args only (no binary/script) ---
174
- const argv: readonly string[] = ['deno', 'run', ...d.args];
175
-
176
- // --- Environment (permission-safe) ---
177
- const env = safeEnvToObject(d);
178
-
179
- // --- CWD (permission-safe) ---
180
- const cwd = safeCwd(d);
181
-
182
- // --- I/O writers ---
183
- const stdoutWrite: WriteFn = (data) => {
184
- d.stdout.writeSync(encoder.encode(data));
185
- };
186
- const stderrWrite: WriteFn = (data) => {
187
- d.stderr.writeSync(encoder.encode(data));
188
- };
189
-
190
- // --- Stdin line reading ---
191
- const stdinRead = createDenoReadLine(d);
192
-
193
- // --- Filesystem ---
194
- const readFile = async (path: string): Promise<string | null> => {
195
- try {
196
- return await d.readTextFile(path);
197
- } catch (err: unknown) {
198
- // NotFound = file doesn't exist → null (expected for config probing)
199
- if (isDenoErrorNamed(err, 'NotFound')) return null;
200
- // PermissionDenied = --allow-read not granted → treat as not found
201
- // (config discovery is opt-in; failing silently is the graceful path)
202
- if (isDenoErrorNamed(err, 'PermissionDenied')) return null;
203
- throw err; // Other I/O errors propagate
204
- }
205
- };
206
-
207
- // --- Home directory ---
208
- const homedir = resolveDenoHomedir(env, d.build.os === 'windows');
209
-
210
- // --- Config directory ---
211
- const configDir = resolveDenoConfigDir(env, homedir, d.build.os === 'windows');
212
-
213
- const stdinIsTTY = d.stdin.isTerminal();
214
-
215
- return {
216
- argv,
217
- env,
218
- cwd,
219
- stdout: stdoutWrite,
220
- stderr: stderrWrite,
221
- stdin: stdinRead,
222
- readStdin: () => readDenoStdinAll(d, stdinIsTTY),
223
- isTTY: d.stdout.isTerminal(),
224
- stdinIsTTY,
225
- exit: (code) => d.exit(code),
226
- readFile,
227
- homedir,
228
- configDir,
229
- };
230
- }
231
-
232
- // --- Deno namespace access — isolated for testability
233
-
234
- /**
235
- * Access the global `Deno` namespace.
236
- *
237
- * Cast through `unknown` to avoid TypeScript errors when Deno types
238
- * aren't installed. Safe because this adapter is only used on Deno
239
- * where `globalThis.Deno` is always defined.
240
- *
241
- * @internal
242
- */
243
- function getDenoNamespace(): DenoNamespace {
244
- return (globalThis as unknown as { Deno: DenoNamespace }).Deno;
245
- }
246
-
247
- // --- Stdin reading — line (prompts) and full (piped data)
248
-
249
- /**
250
- * Read all of stdin as a single string (for piped data).
251
- *
252
- * Returns `null` immediately if stdin is a TTY — the user is typing
253
- * interactively, so there's no piped data to consume. When stdin is
254
- * piped, collects all chunks via the `ReadableStream` until EOF and
255
- * returns the decoded string, which may be empty for an empty pipe.
256
- *
257
- * @internal
258
- */
259
- async function readDenoStdinAll(deno: DenoNamespace, stdinIsTTY: boolean): Promise<string | null> {
260
- if (stdinIsTTY) return null;
261
-
262
- const reader = deno.stdin.readable.getReader();
263
- const decoder = new TextDecoder();
264
- const chunks: string[] = [];
265
-
266
- try {
267
- for (;;) {
268
- const { value, done } = await reader.read();
269
- if (done) {
270
- // Flush any trailing bytes held by the streaming decoder
271
- chunks.push(decoder.decode());
272
- break;
273
- }
274
- chunks.push(decoder.decode(value, { stream: true }));
275
- }
276
- } finally {
277
- reader.releaseLock();
278
- }
279
-
280
- return chunks.join('');
281
- }
282
-
283
- /**
284
- * Read a single line from Deno's stdin.
285
- *
286
- * Uses the `ReadableStream` API with a manual buffer to read until
287
- * a newline character is found. Returns `null` on EOF.
288
- *
289
- * This is intentionally simple — the terminal prompter handles retries
290
- * and validation.
291
- *
292
- * @internal
293
- */
294
- function createDenoReadLine(deno: DenoNamespace): ReadFn {
295
- const decoder = new TextDecoder();
296
- let buffer = '';
297
- let done = false;
298
-
299
- return async (): Promise<string | null> => {
300
- const reader = deno.stdin.readable.getReader();
301
- try {
302
- for (;;) {
303
- const newlineIndex = buffer.indexOf('\n');
304
- if (newlineIndex !== -1) {
305
- const line = buffer.slice(0, newlineIndex).replace(/\r$/, '');
306
- buffer = buffer.slice(newlineIndex + 1);
307
- return line;
308
- }
309
-
310
- if (done) {
311
- if (buffer.length === 0) return null;
312
- const line = buffer;
313
- buffer = '';
314
- return line;
315
- }
316
-
317
- const { value, done: readDone } = await reader.read();
318
- if (readDone) {
319
- buffer += decoder.decode();
320
- done = true;
321
- continue;
322
- }
323
- buffer += decoder.decode(value, { stream: true });
324
- }
325
- } finally {
326
- reader.releaseLock();
327
- }
328
- };
329
- }
330
-
331
- // --- Home / config directory resolution
332
-
333
- /**
334
- * Resolve the user's home directory from environment variables.
335
- *
336
- * Deno doesn't expose `os.homedir()` without `--allow-sys`, so we derive
337
- * it from env vars — same approach as the Node adapter.
338
- *
339
- * @internal
340
- */
341
- function resolveDenoHomedir(
342
- env: Readonly<Record<string, string | undefined>>,
343
- isWindows: boolean,
344
- ): string {
345
- return resolveHomeDirectory(env, isWindows);
346
- }
347
-
348
- /**
349
- * Resolve the platform-specific user configuration directory.
350
- *
351
- * Uses `Deno.build.os` for platform detection, then applies the same fallback
352
- * chain as the Node adapter.
353
- *
354
- * @internal
355
- */
356
- function resolveDenoConfigDir(
357
- env: Readonly<Record<string, string | undefined>>,
358
- homedir: string,
359
- isWindows: boolean,
360
- ): string {
361
- return resolveConfigDirectory(env, isWindows, homedir);
362
- }
363
-
364
- // --- Exports
365
-
366
- export type { DenoNamespace };
367
- export { createDenoAdapter };
@@ -1,105 +0,0 @@
1
- /**
2
- * Auto-detects the current JavaScript runtime environment.
3
- *
4
- * Uses `globalThis` feature detection (version globals) to identify
5
- * the runtime without importing platform-specific modules. This is
6
- * the recommended approach because each runtime defines a unique
7
- * global marker:
8
- *
9
- * - **Bun:** `globalThis.Bun.version` (string)
10
- * - **Deno:** `globalThis.Deno.version` (object with `deno` key)
11
- * - **Node:** `globalThis.process.versions.node` (string)
12
- *
13
- * Detection order matters: Bun provides a Node-compatible `process`
14
- * global, so it must be checked *before* Node to avoid misidentification.
15
- *
16
- * @module @kjanat/dreamcli/runtime/detect
17
- */
18
-
19
- // --- Runtime type
20
-
21
- /**
22
- * Known JavaScript runtime environments.
23
- *
24
- * - `'node'` — Node.js
25
- * - `'bun'` — Bun
26
- * - `'deno'` — Deno
27
- * - `'unknown'` — Unrecognized environment
28
- */
29
- type Runtime = 'node' | 'bun' | 'deno' | 'unknown';
30
-
31
- /**
32
- * All known runtime values as a readonly tuple.
33
- *
34
- * Useful for validation, iteration, and exhaustiveness checks.
35
- *
36
- * @example
37
- * ```ts
38
- * if (RUNTIMES.includes(value)) {
39
- * // value is a valid Runtime
40
- * }
41
- * ```
42
- */
43
- const RUNTIMES: readonly ['node', 'bun', 'deno', 'unknown'] = [
44
- 'node',
45
- 'bun',
46
- 'deno',
47
- 'unknown',
48
- ] as const satisfies readonly Runtime[];
49
-
50
- // --- Minimal global shapes — avoid importing @types/* for each runtime
51
-
52
- /**
53
- * Minimal `globalThis` shape used for runtime detection.
54
- *
55
- * Each field is optional — only the present one identifies the runtime.
56
- * Typed as `unknown` where we only need truthiness; version fields are
57
- * typed just enough to distinguish runtimes safely.
58
- */
59
- interface GlobalForDetect {
60
- /** Present when running on Bun. */
61
- readonly Bun?: { readonly version?: string };
62
- /** Present when running on Deno. */
63
- readonly Deno?: { readonly version?: { readonly deno?: string } };
64
- /** Present on Node.js (and Bun, which mimics it). */
65
- readonly process?: { readonly versions?: { readonly node?: string; readonly bun?: string } };
66
- }
67
-
68
- // --- Detection
69
-
70
- /**
71
- * Detect the current JavaScript runtime.
72
- *
73
- * Uses `globalThis` feature detection to identify the host runtime.
74
- * Detection order is significant: Bun is checked before Node because
75
- * Bun exposes a Node-compatible `process` global.
76
- *
77
- * @param globals - Override `globalThis` for testing. Production callers
78
- * should omit this parameter.
79
- * @returns The detected {@link Runtime} identifier.
80
- *
81
- * @example
82
- * ```ts
83
- * const rt = detectRuntime();
84
- * // rt === 'node' | 'bun' | 'deno' | 'unknown'
85
- * ```
86
- */
87
- function detectRuntime(globals?: GlobalForDetect): Runtime {
88
- const g = globals ?? (globalThis as unknown as GlobalForDetect);
89
-
90
- // Bun first — it also has `process.versions.node`
91
- if (typeof g.Bun?.version === 'string') return 'bun';
92
-
93
- // Deno — check the nested version object
94
- if (typeof g.Deno?.version?.deno === 'string') return 'deno';
95
-
96
- // Node.js — last because Bun mimics it
97
- if (typeof g.process?.versions?.node === 'string') return 'node';
98
-
99
- return 'unknown';
100
- }
101
-
102
- // --- Exports
103
-
104
- export type { GlobalForDetect, Runtime };
105
- export { detectRuntime, RUNTIMES };
@@ -1,21 +0,0 @@
1
- /**
2
- * Runtime adapters for platform portability (Node, Bun, Deno).
3
- *
4
- * The adapter interface ({@link RuntimeAdapter}) defines the contract
5
- * between the platform-agnostic core and the host runtime. Concrete
6
- * adapters wrap platform-specific APIs (Node `process`, Deno namespace, etc.)
7
- * behind this uniform interface.
8
- *
9
- * @module @kjanat/dreamcli/runtime
10
- */
11
-
12
- export type { RuntimeAdapter, TestAdapterOptions } from './adapter.ts';
13
- export { createTestAdapter, ExitError } from './adapter.ts';
14
- export { createAdapter } from './auto.ts';
15
- export { createBunAdapter } from './bun.ts';
16
- export type { DenoNamespace } from './deno.ts';
17
- export { createDenoAdapter } from './deno.ts';
18
- export type { GlobalForDetect, Runtime } from './detect.ts';
19
- export { detectRuntime, RUNTIMES } from './detect.ts';
20
- export type { NodeProcess } from './node.ts';
21
- export { createNodeAdapter } from './node.ts';
@@ -1,27 +0,0 @@
1
- /**
2
- * Minimal type declarations for Node.js built-in modules.
3
- *
4
- * This file provides just enough type information for the runtime
5
- * adapter to dynamically import `readline` without depending on
6
- * `@types/node`. Only the subset actually used is declared.
7
- *
8
- * @internal
9
- */
10
-
11
- declare module 'node:readline' {
12
- interface ReadlineInterface {
13
- once(event: 'line', listener: (line: string) => void): void;
14
- once(event: 'close', listener: () => void): void;
15
- close(): void;
16
- }
17
-
18
- function createInterface(options: { input: unknown; terminal: boolean }): ReadlineInterface;
19
- }
20
-
21
- declare module 'node:fs/promises' {
22
- function readFile(path: string | URL, encoding: 'utf8'): Promise<string>;
23
- }
24
-
25
- declare module 'node:url' {
26
- function fileURLToPath(url: string | URL): string;
27
- }