@kjanat/dreamcli 0.0.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/CHANGELOG.md +667 -0
  2. package/LICENSE +22 -0
  3. package/README.md +370 -0
  4. package/dist/adapter-B37d9oia.mjs +1 -0
  5. package/dist/adapter-CCSh5juX.cjs +1 -0
  6. package/dist/adapter-DIwO-q7K.d.mts +3447 -0
  7. package/dist/adapter-DQnxxLiE.d.cts +3447 -0
  8. package/dist/auto-5cjZaF9V.mjs +3 -0
  9. package/dist/auto-B0eSgoDw.cjs +3 -0
  10. package/dist/index.cjs +10 -0
  11. package/dist/index.d.cts +920 -0
  12. package/dist/index.d.mts +920 -0
  13. package/dist/index.mjs +10 -0
  14. package/dist/runtime.cjs +1 -0
  15. package/dist/runtime.d.cts +253 -0
  16. package/dist/runtime.d.mts +253 -0
  17. package/dist/runtime.mjs +1 -0
  18. package/dist/testkit-CEDYPvhF.mjs +14 -0
  19. package/dist/testkit-ClIKijxC.cjs +14 -0
  20. package/dist/testkit.cjs +1 -0
  21. package/dist/testkit.d.cts +25 -0
  22. package/dist/testkit.d.mts +25 -0
  23. package/dist/testkit.mjs +1 -0
  24. package/examples/basic.ts +33 -0
  25. package/examples/gh/package.json +48 -0
  26. package/examples/gh/src/commands/auth.ts +66 -0
  27. package/examples/gh/src/commands/issue.ts +120 -0
  28. package/examples/gh/src/commands/pr.ts +125 -0
  29. package/examples/gh/src/data/issues.yaml +5 -0
  30. package/examples/gh/src/data/issues.yaml.d.ts +17 -0
  31. package/examples/gh/src/data/pull-requests.yaml +7 -0
  32. package/examples/gh/src/data/pull-requests.yaml.d.ts +18 -0
  33. package/examples/gh/src/lib/auth.ts +37 -0
  34. package/examples/gh/src/lib/utils.ts +17 -0
  35. package/examples/gh/src/main.test.ts +306 -0
  36. package/examples/gh/src/main.ts +38 -0
  37. package/examples/gh/tsconfig.json +37 -0
  38. package/examples/interactive.ts +66 -0
  39. package/examples/json-mode.ts +93 -0
  40. package/examples/middleware.ts +71 -0
  41. package/examples/multi-command.ts +66 -0
  42. package/examples/spinner-progress.ts +49 -0
  43. package/examples/testing.ts +145 -0
  44. package/examples/tsconfig.json +17 -0
  45. package/package.json +123 -2
  46. package/src/core/cli/AGENTS.md +72 -0
  47. package/src/core/cli/dispatch.ts +282 -0
  48. package/src/core/cli/index.ts +1425 -0
  49. package/src/core/cli/plugin.ts +111 -0
  50. package/src/core/cli/propagate.ts +97 -0
  51. package/src/core/cli/root-help.ts +269 -0
  52. package/src/core/cli/root-surface.ts +74 -0
  53. package/src/core/completion/AGENTS.md +72 -0
  54. package/src/core/completion/completion-test-helpers.ts +48 -0
  55. package/src/core/completion/index.ts +82 -0
  56. package/src/core/completion/shells/bash.ts +456 -0
  57. package/src/core/completion/shells/fish.ts +24 -0
  58. package/src/core/completion/shells/powershell.ts +24 -0
  59. package/src/core/completion/shells/shared.ts +283 -0
  60. package/src/core/completion/shells/zsh.ts +376 -0
  61. package/src/core/config/index.ts +404 -0
  62. package/src/core/config/package-json.ts +216 -0
  63. package/src/core/errors/index.ts +178 -0
  64. package/src/core/help/index.ts +559 -0
  65. package/src/core/json-schema/index.ts +705 -0
  66. package/src/core/output/AGENTS.md +69 -0
  67. package/src/core/output/activity.ts +568 -0
  68. package/src/core/output/display-value.ts +48 -0
  69. package/src/core/output/index.ts +704 -0
  70. package/src/core/output/writer.ts +46 -0
  71. package/src/core/parse/index.ts +643 -0
  72. package/src/core/prompt/index.ts +566 -0
  73. package/src/core/resolve/AGENTS.md +69 -0
  74. package/src/core/resolve/index.ts +1331 -0
  75. package/src/core/schema/AGENTS.md +61 -0
  76. package/src/core/schema/activity.ts +237 -0
  77. package/src/core/schema/arg.ts +707 -0
  78. package/src/core/schema/command.ts +1263 -0
  79. package/src/core/schema/flag.ts +651 -0
  80. package/src/core/schema/index.ts +82 -0
  81. package/src/core/schema/middleware.ts +171 -0
  82. package/src/core/schema/prompt.ts +148 -0
  83. package/src/core/schema/run.ts +187 -0
  84. package/src/core/testkit/AGENTS.md +55 -0
  85. package/src/core/testkit/index.ts +365 -0
  86. package/src/index.ts +164 -0
  87. package/src/runtime/AGENTS.md +74 -0
  88. package/src/runtime/adapter.ts +300 -0
  89. package/src/runtime/auto.ts +110 -0
  90. package/src/runtime/bun.ts +55 -0
  91. package/src/runtime/deno.ts +355 -0
  92. package/src/runtime/detect.ts +102 -0
  93. package/src/runtime/index.ts +21 -0
  94. package/src/runtime/node-builtins.d.ts +23 -0
  95. package/src/runtime/node.ts +278 -0
  96. package/src/runtime/paths.ts +56 -0
  97. package/src/runtime/support.ts +119 -0
  98. package/src/runtime/test-helpers.ts +40 -0
  99. package/src/runtime.ts +31 -0
  100. package/src/testkit.ts +23 -0
  101. package/src/version.ts +20 -0
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+ ===========
3
+
4
+ Copyright (c) 2026 kjanat
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,370 @@
1
+ # dreamcli
2
+
3
+ Schema-first, fully typed TypeScript CLI framework. Zero runtime dependencies.
4
+
5
+ One flag declaration configures the entire resolution pipeline:
6
+
7
+ ```ts
8
+ import { cli, command, flag, arg, middleware, CLIError } from 'dreamcli';
9
+
10
+ const deploy = command('deploy')
11
+ .description('Deploy to an environment')
12
+ .arg('target', arg.string().describe('Deploy target'))
13
+ .flag(
14
+ 'region',
15
+ flag
16
+ .enum(['us', 'eu', 'ap'])
17
+ .alias('r')
18
+ .env('DEPLOY_REGION')
19
+ .config('deploy.region')
20
+ .prompt({ kind: 'select', message: 'Which region?' })
21
+ .default('us')
22
+ .propagate(),
23
+ )
24
+ .action(({ args, flags, out }) => {
25
+ out.log(`Deploying ${args.target} to ${flags.region}`);
26
+ });
27
+ ```
28
+
29
+ By the time `action` runs, `flags.region` is `"us" | "eu" | "ap"` — not `string | undefined`.
30
+
31
+ The value is resolved through a documented chain: **CLI → env → config → interactive prompt →
32
+ default**. Every step is opt-in. Every step preserves types.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ npm install dreamcli
38
+ ```
39
+
40
+ ```bash
41
+ bun add dreamcli
42
+ ```
43
+
44
+ ```bash
45
+ # Deno (JSR)
46
+ deno add jsr:@kjanat/dreamcli
47
+ ```
48
+
49
+ ## Quick start
50
+
51
+ ### Single command
52
+
53
+ ```ts
54
+ import { command, flag, arg } from 'dreamcli';
55
+
56
+ const greet = command('greet')
57
+ .description('Greet someone')
58
+ .arg('name', arg.string().describe('Who to greet'))
59
+ .flag('loud', flag.boolean().alias('l').describe('Shout the greeting'))
60
+ .flag('times', flag.number().default(1).describe('Repeat count'))
61
+ .action(({ args, flags, out }) => {
62
+ for (let i = 0; i < flags.times; i++) {
63
+ const msg = `Hello, ${args.name}!`;
64
+ out.log(flags.loud ? msg.toUpperCase() : msg);
65
+ }
66
+ });
67
+
68
+ greet.run();
69
+ ```
70
+
71
+ ### Multi-command CLI
72
+
73
+ ```ts
74
+ import { cli, command, group, flag, arg } from 'dreamcli';
75
+
76
+ const deploy = command('deploy')
77
+ .description('Deploy to an environment')
78
+ .arg('target', arg.string())
79
+ .flag('force', flag.boolean().alias('f'))
80
+ .flag('region', flag.enum(['us', 'eu', 'ap']).env('DEPLOY_REGION'))
81
+ .action(({ args, flags, out }) => {
82
+ out.log(`Deploying ${args.target} to ${flags.region ?? 'default'}`);
83
+ });
84
+
85
+ const login = command('login')
86
+ .description('Authenticate with the service')
87
+ .flag('token', flag.string().describe('Auth token'))
88
+ .action(({ flags, out }) => {
89
+ out.log(flags.token ? 'Authenticated via token' : 'Authenticated interactively');
90
+ });
91
+
92
+ // Nested command groups
93
+ const migrate = command('migrate')
94
+ .description('Run migrations')
95
+ .flag('steps', flag.number())
96
+ .action(({ flags, out }) => {
97
+ out.log(`migrating ${flags.steps ?? 'all'} steps`);
98
+ });
99
+
100
+ const seed = command('seed')
101
+ .description('Seed database')
102
+ .action(({ out }) => {
103
+ out.log('seeding');
104
+ });
105
+
106
+ const db = group('db').description('Database operations').command(migrate).command(seed);
107
+
108
+ cli('mycli')
109
+ .version('1.0.0')
110
+ .description('My awesome tool')
111
+ .command(deploy)
112
+ .command(login)
113
+ .command(db)
114
+ .run();
115
+
116
+ // mycli deploy production --force
117
+ // mycli login --token abc123
118
+ // mycli db migrate --steps 3
119
+ // mycli db seed
120
+ ```
121
+
122
+ ## Why dreamcli
123
+
124
+ Most TypeScript CLI frameworks treat the type system like decoration. You define flags in one place,
125
+ then use parsed values somewhere else as a loosely typed blob. Env vars, config files, and
126
+ interactive prompts live in separate universes. Testing means hacking `process.argv`.
127
+
128
+ dreamcli collapses all of that into a single typed schema:
129
+
130
+ Approximate comparison of first-party, built-in support as documented by each project.
131
+ Third-party plugins and custom glue can extend the other libraries.
132
+
133
+ | Capability | Commander | Yargs | Citty | CAC | Cleye | dreamcli |
134
+ | ------------------------------------------ | ------------------- | ---------------------- | --------------- | ------------- | ------------- | ------------------------------------- |
135
+ | Type inference from definition | Manual `.opts<T>()` | Good | Good | Basic | Good | Full — flags, args, context |
136
+ | Built-in value sources | CLI, defaults, env | CLI, env, config | CLI, defaults | CLI, defaults | CLI, defaults | CLI, env, config, prompt, default |
137
+ | Schema-driven prompts | No | No | No | No | No | Integrated |
138
+ | Middleware / hooks | Lifecycle hooks | Middleware | Plugins / hooks | Events | No | Yes — typed middleware |
139
+ | Built-in test harness with output capture | No | No | No | No | No | `runCommand()` + capture |
140
+ | Shell completions from command definitions | No | Built-in (bash/zsh) | No | No | No | Built-in (bash/zsh) |
141
+ | Structured output primitives | DIY | DIY | DIY | DIY | DIY | Built-in (`--json`, tables, spinners) |
142
+ | Config file support | DIY | Built-in (`.config()`) | No | No | No | Built-in (XDG discovery, JSON) |
143
+
144
+ The closest analog is what tRPC did to API routes — individual pieces existed, the insight was
145
+ wiring them so types flow end-to-end.
146
+
147
+ ## Features
148
+
149
+ ### Flag types
150
+
151
+ ```ts
152
+ flag.string(); // string | undefined
153
+ flag.number(); // number | undefined
154
+ flag.boolean(); // boolean (defaults to false)
155
+ flag.enum(['us', 'eu', 'ap']); // "us" | "eu" | "ap" | undefined
156
+ flag.array(flag.string()); // string[] | undefined
157
+ flag.custom((v) => new URL(v)); // URL | undefined
158
+ ```
159
+
160
+ Every flag supports: `.default()`, `.required()`, `.alias()`, `.env()`, `.config()`, `.describe()`,
161
+ `.prompt()`, `.deprecated()`, `.propagate()`.
162
+
163
+ ### Resolution chain
164
+
165
+ Each flag resolves through an ordered pipeline. Every step is opt-in:
166
+
167
+ ```
168
+ CLI argv → environment variable → config file → interactive prompt → default value
169
+ ```
170
+
171
+ Required flags that don't resolve produce a structured error before the action handler runs. In
172
+ non-interactive contexts (CI, piped stdin), prompts are automatically skipped.
173
+
174
+ ### Interactive prompts
175
+
176
+ Four prompt types, declared per-flag or per-command:
177
+
178
+ ```ts
179
+ // Per-flag
180
+ flag.string().prompt({ kind: 'input', message: 'Name?' });
181
+ flag.boolean().prompt({ kind: 'confirm', message: 'Sure?' });
182
+ flag.enum(['a', 'b']).prompt({ kind: 'select', message: 'Pick one' });
183
+ flag
184
+ .array(flag.string())
185
+ .prompt({ kind: 'multiselect', message: 'Pick many', choices: [{ value: 'a' }, { value: 'b' }] });
186
+
187
+ // Per-command (conditional — receives partially resolved flags)
188
+ command('deploy')
189
+ .flag('region', flag.enum(['us', 'eu', 'ap']))
190
+ .interactive(({ flags }) => ({
191
+ region: !flags.region && { kind: 'select', message: 'Which region?' },
192
+ }));
193
+ ```
194
+
195
+ ### Derive typed context from resolved input
196
+
197
+ ```ts
198
+ import { CLIError } from 'dreamcli';
199
+
200
+ command('deploy')
201
+ .flag('token', flag.string().env('AUTH_TOKEN'))
202
+ .derive(({ flags }) => {
203
+ if (!flags.token)
204
+ throw new CLIError('Not authenticated', {
205
+ code: 'AUTH_REQUIRED',
206
+ suggest: 'Run `mycli login`',
207
+ });
208
+ return { token: flags.token };
209
+ })
210
+ .action(({ ctx }) => {
211
+ ctx.token; // string — typed
212
+ });
213
+ ```
214
+
215
+ Use `derive()` when you need typed, command-scoped access to fully resolved flags and args before
216
+ the action handler runs.
217
+
218
+ ### Middleware with typed context
219
+
220
+ ```ts
221
+ import { middleware } from 'dreamcli';
222
+
223
+ const timing = middleware<{ startTime: number }>(async ({ next }) => {
224
+ const startTime = Date.now();
225
+ await next({ startTime });
226
+ });
227
+
228
+ const trace = middleware<{ traceId: string }>(async ({ next }) =>
229
+ next({ traceId: crypto.randomUUID() }),
230
+ );
231
+
232
+ command('deploy')
233
+ .middleware(timing)
234
+ .middleware(trace)
235
+ .action(({ ctx }) => {
236
+ ctx.startTime; // number — typed
237
+ ctx.traceId; // string — typed
238
+ });
239
+ ```
240
+
241
+ Context accumulates through the middleware chain via type intersection. No manual interface merging.
242
+ Use middleware when you need wrapper behavior with `next()`.
243
+
244
+ ### Output channel
245
+
246
+ Handlers receive `out` instead of `console`. Adapts to context automatically:
247
+
248
+ ```ts
249
+ .action(({ out }) => {
250
+ out.log('Human-readable message');
251
+ out.json({ status: 'ok', count: 42 });
252
+ out.table(rows, [{ key: 'name', header: 'Name' }, { key: 'status', header: 'Status' }]);
253
+
254
+ const spinner = out.spinner('Deploying...');
255
+ spinner.succeed('Done');
256
+
257
+ const progress = out.progress({ label: 'Uploading', total: 100 });
258
+ progress.update(50);
259
+ progress.done('Upload complete');
260
+ })
261
+ ```
262
+
263
+ - TTY → pretty formatting, spinners animate
264
+ - Piped → minimal stable output, spinners suppressed
265
+ - `--json` → structured JSON to stdout, everything else to stderr
266
+
267
+ ### Shell completions
268
+
269
+ Generated from the command schema — always in sync:
270
+
271
+ ```ts
272
+ import { generateCompletion } from 'dreamcli';
273
+
274
+ generateCompletion(myCli.schema, 'bash');
275
+ generateCompletion(myCli.schema, 'zsh');
276
+ ```
277
+
278
+ ### Config file discovery
279
+
280
+ ```ts
281
+ command('deploy').flag('region', flag.enum(['us', 'eu']).config('deploy.region'));
282
+ ```
283
+
284
+ Searches XDG-standard paths automatically. JSON built-in, plugin hook for YAML/TOML:
285
+
286
+ ```ts
287
+ import { configFormat } from 'dreamcli';
288
+ import { parse as parseYAML } from 'yaml';
289
+
290
+ cli('mycli')
291
+ .config('mycli')
292
+ .configLoader(configFormat(['yaml', 'yml'], parseYAML));
293
+ ```
294
+
295
+ ### Structured errors
296
+
297
+ ```ts
298
+ throw new CLIError('Deployment failed', {
299
+ code: 'DEPLOY_FAILED',
300
+ exitCode: 1,
301
+ suggest: 'Check your credentials with `mycli login`',
302
+ details: { target, region },
303
+ });
304
+ ```
305
+
306
+ Parse and validation errors include "did you mean?" suggestions. In `--json` mode, errors serialize
307
+ to machine-readable JSON.
308
+
309
+ ## Testing
310
+
311
+ dreamcli's test harness runs commands in-process with full control over inputs and outputs. No
312
+ subprocesses, no `process.argv` mutation, no mocking.
313
+
314
+ ```ts
315
+ import { runCommand, createTestPrompter, PROMPT_CANCEL } from 'dreamcli/testkit';
316
+
317
+ // Basic execution
318
+ const result = await runCommand(greet, ['Alice', '--loud']);
319
+
320
+ expect(result.exitCode).toBe(0);
321
+ expect(result.stdout).toEqual(['HELLO, ALICE!\n']);
322
+ expect(result.stderr).toEqual([]);
323
+ expect(result.error).toBeUndefined();
324
+
325
+ // With environment, config, and prompt answers
326
+ const result = await runCommand(deploy, ['production'], {
327
+ env: { DEPLOY_REGION: 'eu' },
328
+ config: { deploy: { region: 'us' } },
329
+ answers: ['ap'], // prompt answers consumed in order
330
+ });
331
+
332
+ // Simulate prompt cancellation
333
+ const result = await runCommand(cmd, [], {
334
+ prompter: createTestPrompter([PROMPT_CANCEL]),
335
+ });
336
+
337
+ // Activity events (spinners, progress)
338
+ expect(result.activity).toContainEqual(expect.objectContaining({ type: 'spinner:start' }));
339
+ ```
340
+
341
+ `RunOptions` accepts: `env`, `config`, `answers`, `prompter`, `help`, `json`, `verbosity`,
342
+ `adapter`, and more. Every dimension of CLI behavior is controllable from tests.
343
+
344
+ ## Package structure
345
+
346
+ Three subpath exports, each with a focused API surface:
347
+
348
+ | Import | Purpose |
349
+ | ------------------ | -------------------------------------------------------------------------------------- |
350
+ | `dreamcli` | Schema builders, CLI runner, output, parsing, resolution, errors |
351
+ | `dreamcli/testkit` | `runCommand()`, `createCaptureOutput()`, `createTestPrompter()`, `createTestAdapter()` |
352
+ | `dreamcli/runtime` | `createAdapter()`, `RuntimeAdapter`, runtime detection, platform adapters |
353
+
354
+ Dual ESM/CJS. Source included in package (`src/`).
355
+
356
+ ## Runtime support
357
+
358
+ | Runtime | Status |
359
+ | ------------------ | ----------------------------------- |
360
+ | Node.js >= 22.22.2 | Supported |
361
+ | Bun >= 1.3.11 | Supported |
362
+ | Deno >= 2.6.0 | Supported (JSR: `@kjanat/dreamcli`) |
363
+
364
+ Runtime detection is automatic. The core framework never imports platform-specific APIs directly — a
365
+ thin `RuntimeAdapter` interface handles the divergent edges (argv, env, filesystem, TTY detection,
366
+ exit behavior).
367
+
368
+ ## License
369
+
370
+ [MIT](LICENSE)
@@ -0,0 +1 @@
1
+ var e=class extends Error{name=`ExitError`;code;constructor(e){super(`Process exited with code ${e}`),this.code=e}};const t=()=>{},n=()=>Promise.resolve(null),r=()=>Promise.resolve(null);function i(i){let a=i?.stdinIsTTY??!1,o=a?void 0:i?.stdinData;return{argv:i?.argv??[`node`,`test`],env:i?.env??{},cwd:i?.cwd??`/test`,stdout:i?.stdout??t,stderr:i?.stderr??t,stdin:i?.stdin??n,readStdin:()=>{if(o===void 0)return Promise.resolve(null);let e=o;return o=void 0,Promise.resolve(e)},isTTY:i?.isTTY??!1,stdinIsTTY:a,exit:i?.exit??(t=>{throw new e(t)}),readFile:i?.readFile??r,homedir:i?.homedir??`/home/test`,configDir:i?.configDir??`/home/test/.config`}}export{i as n,e as t};
@@ -0,0 +1 @@
1
+ var e=class extends Error{name=`ExitError`;code;constructor(e){super(`Process exited with code ${e}`),this.code=e}};const t=()=>{},n=()=>Promise.resolve(null),r=()=>Promise.resolve(null);function i(i){let a=i?.stdinIsTTY??!1,o=a?void 0:i?.stdinData;return{argv:i?.argv??[`node`,`test`],env:i?.env??{},cwd:i?.cwd??`/test`,stdout:i?.stdout??t,stderr:i?.stderr??t,stdin:i?.stdin??n,readStdin:()=>{if(o===void 0)return Promise.resolve(null);let e=o;return o=void 0,Promise.resolve(e)},isTTY:i?.isTTY??!1,stdinIsTTY:a,exit:i?.exit??(t=>{throw new e(t)}),readFile:i?.readFile??r,homedir:i?.homedir??`/home/test`,configDir:i?.configDir??`/home/test/.config`}}Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return e}});