@kjanat/dreamcli 2.5.0 → 3.0.0-rc.10

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 (202) hide show
  1. package/CHANGELOG.md +344 -1
  2. package/README.md +9 -2
  3. package/dist/core/cli/dispatch.d.mts +6 -5
  4. package/dist/core/cli/dispatch.mjs +205 -1
  5. package/dist/core/cli/help-links.d.mts +0 -1
  6. package/dist/core/cli/help-links.mjs +41 -1
  7. package/dist/core/cli/index.d.mts +185 -19
  8. package/dist/core/cli/index.mjs +945 -1
  9. package/dist/core/cli/planner.d.mts +32 -6
  10. package/dist/core/cli/planner.mjs +300 -1
  11. package/dist/core/cli/plugin.d.mts +1 -1
  12. package/dist/core/cli/plugin.mjs +41 -1
  13. package/dist/core/cli/propagate.d.mts +1 -1
  14. package/dist/core/cli/propagate.mjs +57 -1
  15. package/dist/core/cli/root-help.d.mts +18 -3
  16. package/dist/core/cli/root-help.mjs +226 -6
  17. package/dist/core/cli/root-surface.d.mts +30 -4
  18. package/dist/core/cli/root-surface.mjs +28 -1
  19. package/dist/core/cli/runtime-preflight.d.mts +30 -3
  20. package/dist/core/cli/runtime-preflight.mjs +169 -1
  21. package/dist/core/completion/index.d.mts +32 -2
  22. package/dist/core/completion/index.mjs +90 -1
  23. package/dist/core/completion/shells/bash.d.mts +0 -1
  24. package/dist/core/completion/shells/bash.mjs +308 -3
  25. package/dist/core/completion/shells/fish.d.mts +0 -1
  26. package/dist/core/completion/shells/fish.mjs +162 -2
  27. package/dist/core/completion/shells/powershell.d.mts +0 -1
  28. package/dist/core/completion/shells/powershell.mjs +358 -2
  29. package/dist/core/completion/shells/shared.d.mts +23 -2
  30. package/dist/core/completion/shells/shared.mjs +176 -1
  31. package/dist/core/completion/shells/zsh.d.mts +0 -1
  32. package/dist/core/completion/shells/zsh.mjs +251 -2
  33. package/dist/core/config/index.d.mts +2 -3
  34. package/dist/core/config/index.mjs +246 -1
  35. package/dist/core/config/package-json.d.mts +27 -4
  36. package/dist/core/config/package-json.mjs +386 -3
  37. package/dist/core/errors/index.d.mts +3 -3
  38. package/dist/core/errors/index.mjs +87 -1
  39. package/dist/core/execution/index.d.mts +0 -1
  40. package/dist/core/execution/index.mjs +201 -1
  41. package/dist/core/help/ansi.d.mts +11 -5
  42. package/dist/core/help/ansi.mjs +121 -2
  43. package/dist/core/help/index.d.mts +65 -2
  44. package/dist/core/help/index.mjs +341 -7
  45. package/dist/core/help/theme.d.mts +68 -0
  46. package/dist/core/help/theme.mjs +46 -0
  47. package/dist/core/json-schema/index.d.mts +15 -2
  48. package/dist/core/json-schema/index.mjs +536 -12
  49. package/dist/core/json-schema/meta-descriptions.generated.d.mts +22 -5
  50. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  51. package/dist/core/output/activity.d.mts +0 -1
  52. package/dist/core/output/activity.mjs +452 -1
  53. package/dist/core/output/bind.mjs +56 -1
  54. package/dist/core/output/contracts.d.mts +4 -5
  55. package/dist/core/output/contracts.mjs +57 -1
  56. package/dist/core/output/display-value.mjs +32 -1
  57. package/dist/core/output/index.d.mts +21 -1
  58. package/dist/core/output/index.mjs +442 -2
  59. package/dist/core/output/renderers.d.mts +0 -1
  60. package/dist/core/output/renderers.mjs +46 -1
  61. package/dist/core/output/writer.mjs +12 -1
  62. package/dist/core/parse/index.d.mts +54 -7
  63. package/dist/core/parse/index.mjs +727 -1
  64. package/dist/core/prompt/index.d.mts +12 -4
  65. package/dist/core/prompt/index.mjs +348 -6
  66. package/dist/core/resolve/args.d.mts +1 -1
  67. package/dist/core/resolve/args.mjs +105 -1
  68. package/dist/core/resolve/coerce.d.mts +1 -1
  69. package/dist/core/resolve/coerce.mjs +336 -1
  70. package/dist/core/resolve/config.mjs +19 -1
  71. package/dist/core/resolve/contracts.d.mts +9 -4
  72. package/dist/core/resolve/errors.d.mts +0 -1
  73. package/dist/core/resolve/errors.mjs +140 -2
  74. package/dist/core/resolve/flags.d.mts +7 -2
  75. package/dist/core/resolve/flags.mjs +251 -1
  76. package/dist/core/resolve/index.d.mts +2 -2
  77. package/dist/core/resolve/index.mjs +85 -1
  78. package/dist/core/resolve/property.d.mts +6 -2
  79. package/dist/core/resolve/property.mjs +53 -1
  80. package/dist/core/schema/activity.d.mts +31 -11
  81. package/dist/core/schema/arg.d.mts +92 -13
  82. package/dist/core/schema/arg.mjs +463 -1
  83. package/dist/core/schema/command.d.mts +29 -7
  84. package/dist/core/schema/command.mjs +726 -1
  85. package/dist/core/schema/flag.d.mts +577 -21
  86. package/dist/core/schema/flag.mjs +705 -1
  87. package/dist/core/schema/index.d.mts +5 -2
  88. package/dist/core/schema/middleware.d.mts +4 -3
  89. package/dist/core/schema/middleware.mjs +41 -1
  90. package/dist/core/schema/number-constraints.d.mts +96 -0
  91. package/dist/core/schema/number-constraints.mjs +60 -0
  92. package/dist/core/schema/prompt.d.mts +21 -3
  93. package/dist/core/schema/run.d.mts +24 -5
  94. package/dist/core/schema/string-constraints.d.mts +97 -0
  95. package/dist/core/schema/string-constraints.mjs +69 -0
  96. package/dist/core/schema/value-parsers.d.mts +78 -0
  97. package/dist/core/schema/value-parsers.mjs +142 -0
  98. package/dist/core/schema-dsl/runtime.mjs +271 -2
  99. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  100. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  101. package/dist/core/testkit/index.d.mts +9 -36
  102. package/dist/core/testkit/index.mjs +83 -1
  103. package/dist/index.d.mts +12 -6
  104. package/dist/index.mjs +22 -1
  105. package/dist/runtime/adapter.d.mts +38 -2
  106. package/dist/runtime/adapter.mjs +87 -1
  107. package/dist/runtime/auto.d.mts +2 -3
  108. package/dist/runtime/auto.mjs +45 -1
  109. package/dist/runtime/deno.d.mts +24 -5
  110. package/dist/runtime/deno.mjs +262 -2
  111. package/dist/runtime/detect.mjs +45 -1
  112. package/dist/runtime/index.d.mts +3 -4
  113. package/dist/runtime/node.d.mts +8 -2
  114. package/dist/runtime/node.mjs +220 -2
  115. package/dist/runtime/paths.mjs +48 -1
  116. package/dist/runtime.d.mts +4 -4
  117. package/dist/runtime.mjs +6 -1
  118. package/dist/strings.mjs +22 -1
  119. package/dist/testkit.d.mts +1 -0
  120. package/dist/testkit.mjs +5 -1
  121. package/dist/version.d.mts +7 -3
  122. package/dist/version.mjs +7 -1
  123. package/dreamcli.schema.json +36 -7
  124. package/examples/basic.ts +5 -1
  125. package/examples/gh/package.json +2 -7
  126. package/examples/pwsh-demo/package.json +1 -7
  127. package/examples/pwsh-demo/src/main.test.ts +1 -4
  128. package/examples/pwsh-demo/src/main.ts +14 -4
  129. package/examples/transport-launcher.ts +85 -0
  130. package/package.json +43 -49
  131. package/dist/runtime/bun.d.mts +0 -28
  132. package/dist/runtime/bun.mjs +0 -1
  133. package/dist/runtime/support.d.mts +0 -42
  134. package/dist/runtime/support.mjs +0 -1
  135. package/src/core/cli/dispatch.ts +0 -349
  136. package/src/core/cli/help-links.ts +0 -82
  137. package/src/core/cli/index.ts +0 -1413
  138. package/src/core/cli/planner.ts +0 -487
  139. package/src/core/cli/plugin.ts +0 -117
  140. package/src/core/cli/propagate.ts +0 -97
  141. package/src/core/cli/root-help.ts +0 -252
  142. package/src/core/cli/root-surface.ts +0 -74
  143. package/src/core/cli/runtime-preflight.ts +0 -438
  144. package/src/core/completion/index.ts +0 -88
  145. package/src/core/completion/shells/bash.ts +0 -459
  146. package/src/core/completion/shells/fish.ts +0 -259
  147. package/src/core/completion/shells/powershell.ts +0 -439
  148. package/src/core/completion/shells/shared.ts +0 -283
  149. package/src/core/completion/shells/zsh.ts +0 -381
  150. package/src/core/config/index.ts +0 -417
  151. package/src/core/config/package-json.ts +0 -560
  152. package/src/core/errors/index.ts +0 -193
  153. package/src/core/execution/index.ts +0 -268
  154. package/src/core/help/ansi.ts +0 -144
  155. package/src/core/help/index.ts +0 -516
  156. package/src/core/json-schema/index.ts +0 -891
  157. package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
  158. package/src/core/output/activity.ts +0 -575
  159. package/src/core/output/bind.ts +0 -59
  160. package/src/core/output/contracts.ts +0 -194
  161. package/src/core/output/display-value.ts +0 -48
  162. package/src/core/output/index.ts +0 -704
  163. package/src/core/output/renderers.ts +0 -125
  164. package/src/core/output/writer.ts +0 -46
  165. package/src/core/parse/index.ts +0 -681
  166. package/src/core/prompt/index.ts +0 -583
  167. package/src/core/resolve/args.ts +0 -144
  168. package/src/core/resolve/coerce.ts +0 -432
  169. package/src/core/resolve/config.ts +0 -26
  170. package/src/core/resolve/contracts.ts +0 -135
  171. package/src/core/resolve/errors.ts +0 -227
  172. package/src/core/resolve/flags.ts +0 -255
  173. package/src/core/resolve/index.ts +0 -108
  174. package/src/core/resolve/property.ts +0 -99
  175. package/src/core/schema/activity.ts +0 -240
  176. package/src/core/schema/arg.ts +0 -719
  177. package/src/core/schema/command.ts +0 -1498
  178. package/src/core/schema/flag.ts +0 -801
  179. package/src/core/schema/index.ts +0 -91
  180. package/src/core/schema/middleware.ts +0 -171
  181. package/src/core/schema/prompt.ts +0 -156
  182. package/src/core/schema/run.ts +0 -198
  183. package/src/core/schema-dsl/index.ts +0 -109
  184. package/src/core/schema-dsl/parse.ts +0 -262
  185. package/src/core/schema-dsl/runtime.ts +0 -609
  186. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  187. package/src/core/testkit/index.ts +0 -123
  188. package/src/index.ts +0 -179
  189. package/src/runtime/adapter.ts +0 -303
  190. package/src/runtime/auto.ts +0 -110
  191. package/src/runtime/bun.ts +0 -55
  192. package/src/runtime/deno.ts +0 -369
  193. package/src/runtime/detect.ts +0 -105
  194. package/src/runtime/index.ts +0 -21
  195. package/src/runtime/node-builtins.d.ts +0 -27
  196. package/src/runtime/node.ts +0 -300
  197. package/src/runtime/paths.ts +0 -64
  198. package/src/runtime/support.ts +0 -135
  199. package/src/runtime.ts +0 -31
  200. package/src/strings.ts +0 -34
  201. package/src/testkit.ts +0 -25
  202. package/src/version.ts +0 -20
@@ -1 +1,45 @@
1
- const e=[`node`,`bun`,`deno`,`unknown`];function t(e){let t=e??globalThis;return typeof t.Bun?.version==`string`?`bun`:typeof t.Deno?.version?.deno==`string`?`deno`:typeof t.process?.versions?.node==`string`?`node`:`unknown`}export{e as RUNTIMES,t as detectRuntime};
1
+ //#region src/runtime/detect.ts
2
+ /**
3
+ * All known runtime values as a readonly tuple.
4
+ *
5
+ * Useful for validation, iteration, and exhaustiveness checks.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * if (RUNTIMES.includes(value)) {
10
+ * // value is a valid Runtime
11
+ * }
12
+ * ```
13
+ */
14
+ const RUNTIMES = [
15
+ "node",
16
+ "bun",
17
+ "deno",
18
+ "unknown"
19
+ ];
20
+ /**
21
+ * Detect the current JavaScript runtime.
22
+ *
23
+ * Uses `globalThis` feature detection to identify the host runtime.
24
+ * Detection order is significant: Bun is checked before Node because
25
+ * Bun exposes a Node-compatible `process` global.
26
+ *
27
+ * @param globals - Override `globalThis` for testing. Production callers
28
+ * should omit this parameter.
29
+ * @returns The detected {@link Runtime} identifier.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * const rt = detectRuntime();
34
+ * // rt === 'node' | 'bun' | 'deno' | 'unknown'
35
+ * ```
36
+ */
37
+ function detectRuntime(globals) {
38
+ const g = globals ?? globalThis;
39
+ if (typeof g.Bun?.version === "string") return "bun";
40
+ if (typeof g.Deno?.version?.deno === "string") return "deno";
41
+ if (typeof g.process?.versions?.node === "string") return "node";
42
+ return "unknown";
43
+ }
44
+ //#endregion
45
+ export { RUNTIMES, detectRuntime };
@@ -1,7 +1,6 @@
1
- import { ExitError, RuntimeAdapter, TestAdapterOptions, createTestAdapter } from "./adapter.mjs";
1
+ import { ExitError, RuntimeAdapter, TerminalSize, TestAdapterOptions, createTestAdapter } from "./adapter.mjs";
2
2
  import { GlobalForDetect, RUNTIMES, Runtime, detectRuntime } from "./detect.mjs";
3
3
  import { createAdapter } from "./auto.mjs";
4
- import { NodeProcess, createNodeAdapter } from "./node.mjs";
5
- import { createBunAdapter } from "./bun.mjs";
6
4
  import { DenoNamespace, createDenoAdapter } from "./deno.mjs";
7
- export { type DenoNamespace, ExitError, type GlobalForDetect, type NodeProcess, RUNTIMES, type Runtime, type RuntimeAdapter, type TestAdapterOptions, createAdapter, createBunAdapter, createDenoAdapter, createNodeAdapter, createTestAdapter, detectRuntime };
5
+ import { NodeProcess, createNodeAdapter } from "./node.mjs";
6
+ export { type DenoNamespace, ExitError, type GlobalForDetect, type NodeProcess, RUNTIMES, type Runtime, type RuntimeAdapter, type TerminalSize, type TestAdapterOptions, createAdapter, createDenoAdapter, createNodeAdapter, createTestAdapter, detectRuntime };
@@ -1,5 +1,4 @@
1
1
  import { RuntimeAdapter } from "./adapter.mjs";
2
-
3
2
  //#region src/runtime/node.d.ts
4
3
  /**
5
4
  * Minimal subset of the Node.js `process` object needed by the adapter.
@@ -24,12 +23,19 @@ interface NodeProcess {
24
23
  readonly platform: string;
25
24
  /** Standard input stream with TTY detection and async iteration. */
26
25
  readonly stdin: {
27
- readonly isTTY?: boolean; /** Async iterable for reading all of stdin (used by readStdin). */
26
+ readonly isTTY?: boolean;
27
+ /** Async iterable for reading all of stdin (used by readStdin). */
28
28
  [Symbol.asyncIterator](): AsyncIterator<Uint8Array>;
29
29
  };
30
30
  /** Standard output stream with TTY detection and write. */
31
31
  readonly stdout: {
32
32
  readonly isTTY?: boolean;
33
+ readonly columns?: number;
34
+ readonly rows?: number;
35
+ getWindowSize?(): readonly [number, number];
36
+ on?(event: 'resize', listener: () => void): unknown;
37
+ off?(event: 'resize', listener: () => void): unknown;
38
+ removeListener?(event: 'resize', listener: () => void): unknown;
33
39
  write(data: string): unknown;
34
40
  };
35
41
  /** Standard error stream with write. */
@@ -1,2 +1,220 @@
1
- import{resolveConfigDirectory as e,resolveHomeDirectory as t}from"./paths.mjs";import{assertRuntimeVersionSupported as n}from"./support.mjs";function r(){return globalThis.process}function i(e){return typeof e!=`object`||!e||!(`code`in e)?!1:typeof e.code==`string`}function a(e,n){return t(e,n===`win32`)}function o(t,n,r){return e(t,n===`win32`,r)}function s(e){if(e.versions?.bun!==void 0){n(`bun`,e.versions.bun);return}n(`node`,e.versions?.node)}function c(e){let t=e??r();s(t);let n=e=>{t.stdout.write(e)},c=e=>{t.stderr.write(e)},d=u(t),f=async e=>{let t=await import(`node:fs/promises`);try{return await t.readFile(e,`utf8`)}catch(e){if(i(e)&&e.code===`ENOENT`)return null;throw e}},p=a(t.env,t.platform),m=o(t.env,t.platform,p),h=t.stdin.isTTY===!0;return{argv:t.argv,env:t.env,cwd:t.cwd(),stdout:n,stderr:c,stdin:d,readStdin:()=>l(t,h),isTTY:t.stdout.isTTY===!0,stdinIsTTY:h,exit:e=>t.exit(e),readFile:f,homedir:p,configDir:m}}async function l(e,t){if(t)return null;let n=[],r=new TextDecoder;for await(let t of e.stdin)n.push(r.decode(t,{stream:!0}));return n.push(r.decode()),n.join(``)}function u(e){let t=e.stdin[Symbol.asyncIterator](),n=new TextDecoder,r=``,i=!1;return async()=>{for(;;){let e=r.indexOf(`
2
- `);if(e!==-1){let t=r.slice(0,e).replace(/\r$/,``);return r=r.slice(e+1),t}if(i){if(r.length===0)return null;let e=r;return r=``,e}let a=await t.next();if(a.done){r+=n.decode(),i=!0;continue}r+=n.decode(a.value,{stream:!0})}}}export{c as createNodeAdapter};
1
+ import { resolveConfigDirectory, resolveHomeDirectory } from "./paths.mjs";
2
+ //#region src/runtime/node.ts
3
+ /**
4
+ * Access the global `process` object without importing `@types/node`.
5
+ *
6
+ * Cast through `unknown` to avoid TypeScript errors when `@types/node`
7
+ * isn't installed. Safe because this adapter is only used on Node/Bun
8
+ * where `globalThis.process` is always defined.
9
+ *
10
+ * @internal
11
+ */
12
+ function getNodeProcess() {
13
+ return globalThis.process;
14
+ }
15
+ /**
16
+ * Detect whether an unknown thrown value is a Node.js system error
17
+ * with a string `code` property (e.g. `'ENOENT'`, `'EACCES'`).
18
+ *
19
+ * @internal
20
+ */
21
+ function isNodeSystemError(err) {
22
+ if (typeof err !== "object" || err === null || !("code" in err)) return false;
23
+ return typeof err.code === "string";
24
+ }
25
+ /**
26
+ * Resolve the user's home directory from environment variables.
27
+ *
28
+ * **Windows** (`win32`): `USERPROFILE` → `HOMEDRIVE`+`HOMEPATH` (both required) → `HOME` → `C:\`
29
+ * **Unix**: `HOME` → `/`
30
+ *
31
+ * `HOMEPATH` alone is never used — it is a relative fragment (e.g. `\Users\alice`) that only
32
+ * makes sense when combined with `HOMEDRIVE` (e.g. `C:`). Using `HOMEPATH` without `HOMEDRIVE`
33
+ * could resolve against the working drive, producing an incorrect path.
34
+ *
35
+ * We avoid importing `node:os` to keep the factory synchronous and
36
+ * to maintain the pattern of deriving everything from the process object.
37
+ *
38
+ * @internal
39
+ */
40
+ function resolveHomedir(env, platform) {
41
+ return resolveHomeDirectory(env, platform === "win32");
42
+ }
43
+ /**
44
+ * Resolve the platform-specific user configuration directory.
45
+ *
46
+ * - Unix: `$XDG_CONFIG_HOME` (if set), otherwise `~/.config`
47
+ * - Windows: `%APPDATA%` (if set), otherwise `~\AppData\Roaming`
48
+ *
49
+ * @internal
50
+ */
51
+ function resolveConfigDir(env, platform, homedir) {
52
+ return resolveConfigDirectory(env, platform === "win32", homedir);
53
+ }
54
+ /**
55
+ * Create a runtime adapter backed by Node.js `process` globals.
56
+ *
57
+ * Reads `process.argv`, `process.env`, `process.cwd()`, and wraps
58
+ * `process.stdout.write`/`process.stderr.write` as {@linkcode WriteFn} functions.
59
+ *
60
+ * Also works on Bun, which provides a Node-compatible `process` global.
61
+ *
62
+ * @param proc - Override the process object (useful for testing the adapter itself).
63
+ * @returns A {@linkcode RuntimeAdapter} backed by Node.js process state.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * import { cli } from '@kjanat/dreamcli';
68
+ * import { createNodeAdapter } from '@kjanat/dreamcli/runtime/node';
69
+ *
70
+ * cli('mycli')
71
+ * .command(deploy)
72
+ * .run({ adapter: createNodeAdapter() });
73
+ * ```
74
+ */
75
+ function createNodeAdapter(proc) {
76
+ const p = proc ?? getNodeProcess();
77
+ const stdoutWrite = (data) => {
78
+ p.stdout.write(data);
79
+ };
80
+ const stderrWrite = (data) => {
81
+ p.stderr.write(data);
82
+ };
83
+ const stdinRead = createNodeReadLine(p);
84
+ const readFile = async (path) => {
85
+ const fs = await import("node:fs/promises");
86
+ try {
87
+ return await fs.readFile(path, "utf8");
88
+ } catch (err) {
89
+ if (isNodeSystemError(err) && err.code === "ENOENT") return null;
90
+ throw err;
91
+ }
92
+ };
93
+ const stat = async (path) => {
94
+ const fs = await import("node:fs/promises");
95
+ try {
96
+ return (await fs.stat(path)).isDirectory() ? "directory" : "file";
97
+ } catch (err) {
98
+ if (isNodeSystemError(err) && (err.code === "ENOENT" || err.code === "ENOTDIR")) return null;
99
+ throw err;
100
+ }
101
+ };
102
+ const homedir = resolveHomedir(p.env, p.platform);
103
+ const configDir = resolveConfigDir(p.env, p.platform, homedir);
104
+ const stdinIsTTY = p.stdin.isTTY === true;
105
+ return {
106
+ argv: p.argv,
107
+ env: p.env,
108
+ cwd: p.cwd(),
109
+ stdout: stdoutWrite,
110
+ stderr: stderrWrite,
111
+ stdin: stdinRead,
112
+ readStdin: () => readNodeStdinAll(p, stdinIsTTY),
113
+ isTTY: p.stdout.isTTY === true,
114
+ stdinIsTTY,
115
+ getTerminalSize: () => readNodeTerminalSize(p),
116
+ onTerminalResize: (listener) => onNodeTerminalResize(p, listener),
117
+ exit: (code) => p.exit(code),
118
+ readFile,
119
+ stat,
120
+ homedir,
121
+ configDir
122
+ };
123
+ }
124
+ /** Normalize terminal dimensions and discard unusable values. @internal */
125
+ function normalizeTerminalSize(columns, rows) {
126
+ if (columns === void 0 || rows === void 0) return void 0;
127
+ if (!Number.isFinite(columns) || !Number.isFinite(rows)) return void 0;
128
+ if (columns <= 0 || rows <= 0) return void 0;
129
+ return {
130
+ columns,
131
+ rows
132
+ };
133
+ }
134
+ /** Read Node/Bun terminal dimensions from stdout. @internal */
135
+ function readNodeTerminalSize(proc) {
136
+ if (proc.stdout.isTTY !== true) return void 0;
137
+ try {
138
+ const size = proc.stdout.getWindowSize?.();
139
+ if (size !== void 0) {
140
+ const [columns, rows] = size;
141
+ const normalized = normalizeTerminalSize(columns, rows);
142
+ if (normalized !== void 0) return normalized;
143
+ }
144
+ } catch {}
145
+ return normalizeTerminalSize(proc.stdout.columns, proc.stdout.rows);
146
+ }
147
+ /** Subscribe to Node/Bun stdout resize events when available. @internal */
148
+ function onNodeTerminalResize(proc, listener) {
149
+ if (proc.stdout.isTTY !== true || proc.stdout.on === void 0) return void 0;
150
+ if (proc.stdout.off !== void 0) {
151
+ proc.stdout.on("resize", listener);
152
+ return () => {
153
+ proc.stdout.off?.("resize", listener);
154
+ };
155
+ }
156
+ if (proc.stdout.removeListener !== void 0) {
157
+ proc.stdout.on("resize", listener);
158
+ return () => {
159
+ proc.stdout.removeListener?.("resize", listener);
160
+ };
161
+ }
162
+ }
163
+ /**
164
+ * Read all of stdin as a single string (for piped data).
165
+ *
166
+ * Returns `null` immediately if stdin is a TTY — the user is typing
167
+ * interactively, so there's no piped data to consume. When stdin is
168
+ * piped, collects all chunks via the async iterator until EOF and
169
+ * returns the decoded string, which may be empty for an empty pipe.
170
+ *
171
+ * @internal
172
+ */
173
+ async function readNodeStdinAll(proc, stdinIsTTY) {
174
+ if (stdinIsTTY) return null;
175
+ const chunks = [];
176
+ const decoder = new TextDecoder();
177
+ for await (const chunk of proc.stdin) chunks.push(decoder.decode(chunk, { stream: true }));
178
+ chunks.push(decoder.decode());
179
+ return chunks.join("");
180
+ }
181
+ /**
182
+ * Read a single line from Node's stdin via its async iterator.
183
+ *
184
+ * Iterates stdin chunks manually (without `for-await` to avoid calling
185
+ * `iterator.return()` which would close the stream). Returns `null`
186
+ * on EOF.
187
+ *
188
+ * @internal
189
+ */
190
+ function createNodeReadLine(proc) {
191
+ const iter = proc.stdin[Symbol.asyncIterator]();
192
+ const decoder = new TextDecoder();
193
+ let buffer = "";
194
+ let done = false;
195
+ return async () => {
196
+ for (;;) {
197
+ const nlIndex = buffer.indexOf("\n");
198
+ if (nlIndex !== -1) {
199
+ const line = buffer.slice(0, nlIndex).replace(/\r$/, "");
200
+ buffer = buffer.slice(nlIndex + 1);
201
+ return line;
202
+ }
203
+ if (done) {
204
+ if (buffer.length === 0) return null;
205
+ const line = buffer;
206
+ buffer = "";
207
+ return line;
208
+ }
209
+ const result = await iter.next();
210
+ if (result.done) {
211
+ buffer += decoder.decode();
212
+ done = true;
213
+ continue;
214
+ }
215
+ buffer += decoder.decode(result.value, { stream: true });
216
+ }
217
+ };
218
+ }
219
+ //#endregion
220
+ export { createNodeAdapter };
@@ -1 +1,48 @@
1
- import{stripTrailing as e}from"../strings.mjs";function t(e,t){return t?e.USERPROFILE?e.USERPROFILE:e.HOMEDRIVE&&e.HOMEPATH?e.HOMEDRIVE+e.HOMEPATH:e.HOME||`C:\\`:e.HOME||`/`}function n(t,n,r){if(n)return t.APPDATA!==void 0&&t.APPDATA!==``?t.APPDATA:`${e(r,[47,92])||r}\\AppData\\Roaming`;let i=e(r,[47]);return t.XDG_CONFIG_HOME!==void 0&&t.XDG_CONFIG_HOME!==``?t.XDG_CONFIG_HOME:i.length===0?`/.config`:`${i}/.config`}export{n as resolveConfigDirectory,t as resolveHomeDirectory};
1
+ import { stripTrailing } from "../strings.mjs";
2
+ //#region src/runtime/paths.ts
3
+ /**
4
+ * Shared env-based path resolution for runtime adapters.
5
+ *
6
+ * Node, Bun, and Deno all need the same user home/config directory behavior.
7
+ * These helpers keep the fallback chain identical across runtimes while
8
+ * letting each adapter supply its own platform detection.
9
+ *
10
+ * @module @kjanat/dreamcli/runtime/paths
11
+ */
12
+ /**
13
+ * Resolve the user's home directory from environment variables.
14
+ *
15
+ * @param env - Environment variable map.
16
+ * @param isWindows - Whether the platform is Windows.
17
+ * @returns Absolute path to the home directory.
18
+ * @internal
19
+ */
20
+ function resolveHomeDirectory(env, isWindows) {
21
+ if (isWindows) {
22
+ if (env.USERPROFILE) return env.USERPROFILE;
23
+ if (env.HOMEDRIVE && env.HOMEPATH) return env.HOMEDRIVE + env.HOMEPATH;
24
+ return env.HOME || "C:\\";
25
+ }
26
+ return env.HOME || "/";
27
+ }
28
+ /**
29
+ * Resolve the user's config directory (`XDG_CONFIG_HOME` / `APPDATA`).
30
+ *
31
+ * @param env - Environment variable map.
32
+ * @param isWindows - Whether the platform is Windows.
33
+ * @param homedir - Pre-resolved home directory (from {@link resolveHomeDirectory}).
34
+ * @returns Absolute path to the config directory.
35
+ * @internal
36
+ */
37
+ function resolveConfigDirectory(env, isWindows, homedir) {
38
+ if (isWindows) {
39
+ if (env.APPDATA !== void 0 && env.APPDATA !== "") return env.APPDATA;
40
+ return `${stripTrailing(homedir, [47, 92]) || homedir}\\AppData\\Roaming`;
41
+ }
42
+ const normalizedHome = stripTrailing(homedir, [47]);
43
+ if (env.XDG_CONFIG_HOME !== void 0 && env.XDG_CONFIG_HOME !== "") return env.XDG_CONFIG_HOME;
44
+ if (normalizedHome.length === 0) return "/.config";
45
+ return `${normalizedHome}/.config`;
46
+ }
47
+ //#endregion
48
+ export { resolveConfigDirectory, resolveHomeDirectory };
@@ -1,7 +1,7 @@
1
- import { ExitError, RuntimeAdapter } from "./runtime/adapter.mjs";
1
+ import { ExitError, RuntimeAdapter, TerminalSize } from "./runtime/adapter.mjs";
2
2
  import { RUNTIMES, Runtime, detectRuntime } from "./runtime/detect.mjs";
3
3
  import { createAdapter } from "./runtime/auto.mjs";
4
- import { createNodeAdapter } from "./runtime/node.mjs";
5
- import { createBunAdapter } from "./runtime/bun.mjs";
6
4
  import { createDenoAdapter } from "./runtime/deno.mjs";
7
- export { ExitError, RUNTIMES, type Runtime, type RuntimeAdapter, createAdapter, createBunAdapter, createDenoAdapter, createNodeAdapter, detectRuntime };
5
+ import { createNodeAdapter } from "./runtime/node.mjs";
6
+ import "./runtime/index.mjs";
7
+ export { ExitError, RUNTIMES, type Runtime, type RuntimeAdapter, type TerminalSize, createAdapter, createDenoAdapter, createNodeAdapter, detectRuntime };
package/dist/runtime.mjs CHANGED
@@ -1 +1,6 @@
1
- import{createNodeAdapter as e}from"./runtime/node.mjs";import{createBunAdapter as t}from"./runtime/bun.mjs";import{createDenoAdapter as n}from"./runtime/deno.mjs";import{RUNTIMES as r,detectRuntime as i}from"./runtime/detect.mjs";import{createAdapter as a}from"./runtime/auto.mjs";import{ExitError as o}from"./runtime/adapter.mjs";export{o as ExitError,r as RUNTIMES,a as createAdapter,t as createBunAdapter,n as createDenoAdapter,e as createNodeAdapter,i as detectRuntime};
1
+ import { createDenoAdapter } from "./runtime/deno.mjs";
2
+ import { RUNTIMES, detectRuntime } from "./runtime/detect.mjs";
3
+ import { createNodeAdapter } from "./runtime/node.mjs";
4
+ import { createAdapter } from "./runtime/auto.mjs";
5
+ import { ExitError } from "./runtime/adapter.mjs";
6
+ export { ExitError, RUNTIMES, createAdapter, createDenoAdapter, createNodeAdapter, detectRuntime };
package/dist/strings.mjs CHANGED
@@ -1 +1,22 @@
1
- function e(e,t){let n=e.length;for(;n>0&&t.includes(e.charCodeAt(n-1));)--n;return n===e.length?e:e.slice(0,n)}export{e as stripTrailing};
1
+ //#region src/strings.ts
2
+ /**
3
+ * Remove trailing characters whose code points appear in `codes`.
4
+ *
5
+ * Linear-time replacement for trailing-character regexes such as
6
+ * `/[\\/]+$/`. Those patterns are polynomial-ReDoS prone: the engine
7
+ * greedily consumes the run, fails the end anchor, backtracks one
8
+ * character at a time, and repeats that work from every start position —
9
+ * O(n²) on adversarial input. This scan is O(n) with no backtracking.
10
+ *
11
+ * @param input - Source string.
12
+ * @param codes - Character codes to strip from the end of `input`.
13
+ * @returns `input` with all trailing matching characters removed.
14
+ * @internal
15
+ */
16
+ function stripTrailing(input, codes) {
17
+ let end = input.length;
18
+ while (end > 0 && codes.includes(input.charCodeAt(end - 1))) end -= 1;
19
+ return end === input.length ? input : input.slice(0, end);
20
+ }
21
+ //#endregion
22
+ export { stripTrailing };
@@ -3,4 +3,5 @@ import { PROMPT_CANCEL, TestAnswer, TestPrompterOptions, createTestPrompter } fr
3
3
  import { RunOptions, RunResult } from "./core/schema/run.mjs";
4
4
  import { TestAdapterOptions, createTestAdapter } from "./runtime/adapter.mjs";
5
5
  import { runCommand } from "./core/testkit/index.mjs";
6
+ import "./runtime/index.mjs";
6
7
  export { type CapturedOutput, PROMPT_CANCEL, type RunOptions, type RunResult, type TestAdapterOptions, type TestAnswer, type TestPrompterOptions, createCaptureOutput, createTestAdapter, createTestPrompter, runCommand };
package/dist/testkit.mjs CHANGED
@@ -1 +1,5 @@
1
- import{createCaptureOutput as e}from"./core/output/index.mjs";import{PROMPT_CANCEL as t,createTestPrompter as n}from"./core/prompt/index.mjs";import{runCommand as r}from"./core/testkit/index.mjs";import{createTestAdapter as i}from"./runtime/adapter.mjs";export{t as PROMPT_CANCEL,e as createCaptureOutput,i as createTestAdapter,n as createTestPrompter,r as runCommand};
1
+ import { createCaptureOutput } from "./core/output/index.mjs";
2
+ import { PROMPT_CANCEL, createTestPrompter } from "./core/prompt/index.mjs";
3
+ import { runCommand } from "./core/testkit/index.mjs";
4
+ import { createTestAdapter } from "./runtime/adapter.mjs";
5
+ export { PROMPT_CANCEL, createCaptureOutput, createTestAdapter, createTestPrompter, runCommand };
@@ -1,12 +1,16 @@
1
1
  //#region src/version.d.ts
2
2
  /**
3
- * Build-time version constants.
3
+ * DreamCLI's own build-time version constants.
4
+ *
5
+ * Not the app version configured via `cli().version(...)` — these identify
6
+ * the framework build itself (diagnostics, bug reports, completion-script
7
+ * stamps). Kept on a dedicated subpath so they stay out of root-entrypoint
8
+ * import completions.
4
9
  *
5
10
  * Replaced by tsdown `define` during bundling. In development (unbundled),
6
11
  * the declared globals resolve to the `'dev'` fallback.
7
12
  *
8
- * @module dreamcli/version
9
- * @internal
13
+ * @module @kjanat/dreamcli/version
10
14
  */
11
15
  /** Package version (e.g. `"0.9.1"`). `"dev"` when running unbundled. */
12
16
  declare const DREAMCLI_VERSION: string;
package/dist/version.mjs CHANGED
@@ -1 +1,7 @@
1
- const e=`2.5.0`,t=`6d9491b`;export{t as DREAMCLI_REVISION,e as DREAMCLI_VERSION};
1
+ //#region src/version.ts
2
+ /** Package version (e.g. `"0.9.1"`). `"dev"` when running unbundled. */
3
+ const DREAMCLI_VERSION = "3.0.0-rc.10";
4
+ /** Git short SHA (e.g. `"f9b5f1a"`). `"dev"` when running unbundled. */
5
+ const DREAMCLI_REVISION = "3846d43";
6
+ //#endregion
7
+ export { DREAMCLI_REVISION, DREAMCLI_VERSION };
@@ -22,7 +22,7 @@
22
22
  "description": "Program description (shown in root help)."
23
23
  },
24
24
  "defaultCommand": {
25
- "type": "string",
25
+ "$ref": "#/$defs/command",
26
26
  "description": "Default command dispatched when no subcommand matches.\n\nWhen set, the CLI root behaves like a hybrid command group: subcommands\ndispatch by name as usual, but empty argv or flags-only argv falls\nthrough to this command instead of showing root help.\n\nSet via the .default() builder method."
27
27
  },
28
28
  "commands": {
@@ -110,7 +110,9 @@
110
110
  "boolean",
111
111
  "enum",
112
112
  "array",
113
- "custom"
113
+ "custom",
114
+ "count",
115
+ "keyValue"
114
116
  ],
115
117
  "description": "What kind of value this flag accepts."
116
118
  },
@@ -172,7 +174,19 @@
172
174
  },
173
175
  "propagate": {
174
176
  "const": true,
175
- "description": "Whether this flag propagates to subcommands in nested command trees.\n\nWhen `true`, the flag is automatically available to all descendant\ncommands. A child command that defines a flag with the same name\nshadows the propagated parent flag."
177
+ "description": "Whether this flag propagates to subcommands in nested command trees.\n\nWhen `true`, the flag is automatically available to all descendant\ncommands. A child command that defines a flag with the same name\nshadows the propagated parent flag.\n\nDefault: `false`"
178
+ },
179
+ "negation": {
180
+ "$ref": "#/$defs/negation",
181
+ "description": "Negation settings when `kind === 'boolean'` and `.negatable()` was\ncalled (`undefined` otherwise). See FlagNegation."
182
+ },
183
+ "duplicates": {
184
+ "enum": [
185
+ "last",
186
+ "first",
187
+ "error"
188
+ ],
189
+ "description": "How repeated CLI occurrences of a singleton flag combine.\n\n- `'last'` — last occurrence wins (matches historic behavior)\n- `'first'` — first occurrence wins; later ones parse but are ignored\n- `'error'` — a second occurrence is a `ParseError` (`DUPLICATE_FLAG`)\n\nApplies to CLI token occurrences only — env/config/prompt/default\nresolution keeps its precedence semantics and never raises duplicates.\nOccurrences are counted per *logical* flag: aliases and the negated\nspelling all count toward the same flag.\n\nDefault: `'last'`"
176
190
  }
177
191
  },
178
192
  "required": [
@@ -181,6 +195,21 @@
181
195
  ],
182
196
  "description": "The runtime descriptor stored inside every FlagBuilder. Consumers (parser,\nhelp generator, resolution chain) read this to understand the flag's shape\nwithout touching generics."
183
197
  },
198
+ "negation": {
199
+ "type": "object",
200
+ "additionalProperties": false,
201
+ "properties": {
202
+ "alias": {
203
+ "type": "string",
204
+ "description": "Explicit negated spelling without the `--` prefix (e.g. `'no-sandbox'`).\n`undefined` synthesizes `no-<flagName>` wherever the flag name is known."
205
+ },
206
+ "hidden": {
207
+ "const": true,
208
+ "description": "Hide the negated spelling from help, completions, and suggestions."
209
+ }
210
+ },
211
+ "description": "Negation settings for a boolean flag (set by `.negatable()`).\n\nThe negated spelling and the positive form are two spellings of ONE\nlogical flag: they share duplicate policy, and the last CLI occurrence\nwins across both. The negated spelling is presence-only — `--no-foo=x`\nis rejected."
212
+ },
184
213
  "arg": {
185
214
  "type": "object",
186
215
  "additionalProperties": false,
@@ -212,7 +241,7 @@
212
241
  },
213
242
  "stdinMode": {
214
243
  "const": true,
215
- "description": "Whether this arg may read from stdin during resolution."
244
+ "description": "Whether this arg may read from stdin during resolution.\n\nDefault: `false`"
216
245
  },
217
246
  "defaultValue": {
218
247
  "description": "Runtime default value (if any)."
@@ -281,11 +310,11 @@
281
310
  },
282
311
  "min": {
283
312
  "type": "integer",
284
- "description": "Minimum number of selections required."
313
+ "description": "Minimum number of selections required.\n\nDefault: `0`"
285
314
  },
286
315
  "max": {
287
316
  "type": "integer",
288
- "description": "Maximum number of selections allowed."
317
+ "description": "Maximum number of selections allowed.\n\nDefault: `Infinity`"
289
318
  }
290
319
  },
291
320
  "required": [
@@ -304,7 +333,7 @@
304
333
  },
305
334
  "label": {
306
335
  "type": "string",
307
- "description": "Display label shown to the user."
336
+ "description": "Display label shown to the user.\n\nDefault: value"
308
337
  },
309
338
  "description": {
310
339
  "type": "string",
package/examples/basic.ts CHANGED
@@ -24,7 +24,11 @@ const greet = command('greet')
24
24
  // args.name: string — required positional
25
25
  // flags.loud: boolean — defaults to false (all booleans do)
26
26
  // flags.times: number — defaults to 1 (never undefined)
27
- for (let i = 0; i < flags.times; i++) {
27
+ const repeatCount = Number.isFinite(flags.times)
28
+ ? Math.max(0, Math.min(100, Math.floor(flags.times)))
29
+ : 1;
30
+
31
+ for (let i = 0; i < repeatCount; i++) {
28
32
  const msg = `Hello, ${args.name}!`;
29
33
  out.log(flags.loud ? msg.toUpperCase() : msg);
30
34
  }
@@ -10,13 +10,8 @@
10
10
  },
11
11
  "type": "module",
12
12
  "module": "src/main.ts",
13
- "bin": {
14
- "gh": "src/main.ts"
15
- },
16
- "files": [
17
- "src",
18
- "!src/**/*.test.ts"
19
- ],
13
+ "bin": "src/main.ts",
14
+ "files": ["src", "!src/**/*.test.ts"],
20
15
  "scripts": {
21
16
  "bd": "bun run build",
22
17
  "build": "bun build src/main.ts --install --outdir=dist --format=esm --target=node --external @kjanat/dreamcli",
@@ -13,13 +13,7 @@
13
13
  "bin": {
14
14
  "pwsh-demo": "src/main.ts"
15
15
  },
16
- "files": [
17
- "src",
18
- "README.md",
19
- "smoke-powershell.ps1",
20
- "pwsh-demo.cmd",
21
- "!src/**/*.test.ts"
22
- ],
16
+ "files": ["src", "README.md", "smoke-powershell.ps1", "pwsh-demo.cmd", "!src/**/*.test.ts"],
23
17
  "scripts": {
24
18
  "build": "bun build src/main.ts --install --outdir=dist --format=esm --target=node --external @kjanat/dreamcli",
25
19
  "smoke:powershell": "pwsh -NoLogo -NoProfile -ExecutionPolicy Bypass -File ./smoke-powershell.ps1",
@@ -40,9 +40,6 @@ describe('pwsh-demo example', () => {
40
40
  const result = await pwshDemo.execute(['bravo', '--profile', 'ops', '--shell', 'cmd']);
41
41
 
42
42
  expect(result.exitCode).toBe(0);
43
- expect(result.stdout).toEqual([
44
- 'Opening bravo with ops profile in cmd\n',
45
- 'Format: table\n',
46
- ]);
43
+ expect(result.stdout).toEqual(['Opening bravo with ops profile in cmd\n', 'Format: table\n']);
47
44
  });
48
45
  });
@@ -35,7 +35,9 @@ const open = command('open')
35
35
  .flag('format', flag.enum(['table', 'json', 'yaml']).alias('f').describe('Output format'))
36
36
  .flag('verbose', flag.boolean().alias('v').describe('Verbose logging'))
37
37
  .action(({ args, flags, out }) => {
38
- out.log(`Opening ${args.workspace} with ${flags.profile ?? 'default'} profile in ${flags.shell}`);
38
+ out.log(
39
+ `Opening ${args.workspace} with ${flags.profile ?? 'default'} profile in ${flags.shell}`,
40
+ );
39
41
  out.log(`Format: ${flags.format ?? 'table'}`);
40
42
  if (flags.verbose) out.log('Verbose output enabled');
41
43
  });
@@ -55,7 +57,9 @@ const deploy = command('deploy')
55
57
  .flag('approval', flag.enum(['manual', 'auto']).describe('Approval mode'))
56
58
  .flag('dryRun', flag.boolean().alias('d').describe('Preview the rollout without applying it'))
57
59
  .action(({ args, flags, out }) => {
58
- out.log(`Deploying ${args.target} to ${flags.region ?? 'us'} with ${flags.strategy ?? 'rolling'}`);
60
+ out.log(
61
+ `Deploying ${args.target} to ${flags.region ?? 'us'} with ${flags.strategy ?? 'rolling'}`,
62
+ );
59
63
  out.log(`Approval: ${flags.approval ?? 'manual'}`);
60
64
  if (flags.dryRun) out.log('Dry run only');
61
65
  });
@@ -82,7 +86,10 @@ const configSet = command('set')
82
86
  .description('Write a saved setting')
83
87
  .arg('key', arg.enum(['theme', 'region', 'profile']).describe('Setting to write'))
84
88
  .arg('value', arg.string().describe('New value'))
85
- .flag('scope', flag.enum(['user', 'workspace']).alias('s').default('user').describe('Config scope'))
89
+ .flag(
90
+ 'scope',
91
+ flag.enum(['user', 'workspace']).alias('s').default('user').describe('Config scope'),
92
+ )
86
93
  .action(({ args, flags, out }) => {
87
94
  out.log(`Saved ${args.key}=${args.value} to ${flags.scope} scope`);
88
95
  });
@@ -107,7 +114,10 @@ const debugDump = command('debug-dump')
107
114
  .hidden()
108
115
  .flag(
109
116
  'section',
110
- flag.enum(['schema', 'completions', 'runtime']).default('schema').describe('Section to inspect'),
117
+ flag
118
+ .enum(['schema', 'completions', 'runtime'])
119
+ .default('schema')
120
+ .describe('Section to inspect'),
111
121
  )
112
122
  .action(({ flags, out }) => {
113
123
  out.log(JSON.stringify({ section: flags.section, hidden: true }, null, 2));