@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
@@ -0,0 +1,17 @@
1
+ /**
2
+ * TypeScript declaration for the walkthrough issue YAML data.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ type Issue = {
8
+ readonly number: number;
9
+ readonly title: string;
10
+ readonly state: 'open' | 'closed';
11
+ readonly author: string;
12
+ readonly labels: readonly string[];
13
+ };
14
+
15
+ declare const contents: readonly Issue[];
16
+
17
+ export = contents;
@@ -0,0 +1,7 @@
1
+ ---
2
+ - { number: 137, title: Fix date parsing in Safari, state: open, author: dave, labels: [bug], draft: false }
3
+ - { number: 138, title: Refactor auth module, state: merged, author: alice, labels: [refactor], draft: false }
4
+ - { number: 139, title: Add rate limiting, state: closed, author: carol, labels: [enhancement], draft: true }
5
+ - { number: 140, title: Bump dependencies, state: merged, author: dependabot, labels: [chore], draft: false }
6
+ - { number: 141, title: Fix OAuth redirect loop, state: open, author: bob, labels: [bug], draft: false }
7
+ - { number: 142, title: Add dark mode toggle, state: open, author: alice, labels: [enhancement, ui], draft: false }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * TypeScript declaration for the walkthrough pull request YAML data.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ type PR = {
8
+ readonly number: number;
9
+ readonly title: string;
10
+ readonly state: 'open' | 'closed' | 'merged';
11
+ readonly author: string;
12
+ readonly labels: readonly string[];
13
+ readonly draft: boolean;
14
+ };
15
+
16
+ declare const contents: readonly PR[];
17
+
18
+ export = contents;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Authentication guard and authenticated-command factory for the walkthrough `gh` example.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ import { CLIError, command, flag } from 'dreamcli';
8
+
9
+ export function tokenFlag(description = 'GitHub token') {
10
+ return flag.string().env('GH_TOKEN').describe(description);
11
+ }
12
+
13
+ export function requireAuth(token: string | undefined): { readonly token: string } {
14
+ const normalizedToken = token?.trim();
15
+ if (!normalizedToken) {
16
+ throw new CLIError('Authentication required', {
17
+ code: 'AUTH_REQUIRED',
18
+ suggest: 'Run `gh auth login` or set GH_TOKEN',
19
+ exitCode: 1,
20
+ });
21
+ }
22
+
23
+ return { token: normalizedToken };
24
+ }
25
+
26
+ /** Redacts a token for display, keeping the first 8 and last 4 characters visible. */
27
+ export function redactToken(token: string): string {
28
+ if (token.length <= 12) return '***';
29
+ return `${token.slice(0, 8)}...${token.slice(-4)}`;
30
+ }
31
+
32
+ /** A {@linkcode command} pre-wired with a `--token` / `GH_TOKEN` flag and auth guard. */
33
+ export function authedCommand(name: string) {
34
+ return command(name)
35
+ .flag('token', tokenFlag())
36
+ .derive(({ flags }) => requireAuth(flags.token));
37
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Shared helpers for the walkthrough `gh` example.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ export function sleep(ms: number): Promise<void> {
8
+ return new Promise((resolve) => setTimeout(resolve, ms));
9
+ }
10
+
11
+ export function normalizeLimit(value: number): number {
12
+ if (!Number.isFinite(value)) {
13
+ return 10;
14
+ }
15
+
16
+ return Math.max(1, Math.floor(value));
17
+ }
@@ -0,0 +1,306 @@
1
+ /**
2
+ * Smoke tests for the walkthrough `gh` example.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ import { describe, expect, it } from 'bun:test';
8
+
9
+ import { runCommand } from 'dreamcli/testkit';
10
+
11
+ import { authLogin, authStatus } from '$gh/commands/auth.ts';
12
+ import { issueList, issueTriage } from '$gh/commands/issue.ts';
13
+ import { prCreate, prList, prView } from '$gh/commands/pr.ts';
14
+ import { normalizeLimit, sleep } from '$gh/lib/utils.ts';
15
+
16
+ const token = 'ghp_test_token_1234';
17
+
18
+ // === auth login
19
+
20
+ describe('gh example — auth login', () => {
21
+ it('logs the redacted token in human mode', async () => {
22
+ const result = await runCommand(authLogin, [], {
23
+ env: { GH_TOKEN: token },
24
+ });
25
+
26
+ expect(result.exitCode).toBe(0);
27
+ expect(result.stdout).toEqual([
28
+ 'Logged in with token ghp_test...1234\n',
29
+ 'Token would be saved to ~/.config/gh/config.json\n',
30
+ ]);
31
+ });
32
+
33
+ it('returns structured JSON in json mode', async () => {
34
+ const result = await runCommand(authLogin, [], {
35
+ env: { GH_TOKEN: token },
36
+ jsonMode: true,
37
+ });
38
+
39
+ expect(result.exitCode).toBe(0);
40
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual({
41
+ host: 'github.com',
42
+ token: 'ghp_test...1234',
43
+ storedAt: '~/.config/gh/config.json',
44
+ });
45
+ });
46
+ });
47
+
48
+ // === auth status
49
+
50
+ describe('gh example — auth status', () => {
51
+ it('resolves GH_TOKEN through the command schema', async () => {
52
+ const result = await runCommand(authStatus, [], {
53
+ env: { GH_TOKEN: token },
54
+ });
55
+
56
+ expect(result.exitCode).toBe(0);
57
+ expect(result.stdout).toEqual(['github.com\n', 'Logged in with token ghp_test...1234\n']);
58
+ });
59
+
60
+ it('warns when no token resolves', async () => {
61
+ const result = await runCommand(authStatus, []);
62
+
63
+ expect(result.exitCode).toBe(0);
64
+ expect(result.stderr).toEqual(['Not logged in. Run `gh auth login`.\n']);
65
+ });
66
+
67
+ it('returns structured JSON in json mode', async () => {
68
+ const result = await runCommand(authStatus, [], {
69
+ env: { GH_TOKEN: token },
70
+ jsonMode: true,
71
+ });
72
+
73
+ expect(result.exitCode).toBe(0);
74
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual({
75
+ authenticated: true,
76
+ host: 'github.com',
77
+ token: 'ghp_test...1234',
78
+ });
79
+ });
80
+ });
81
+
82
+ // === pr list
83
+
84
+ describe('gh example — pr list', () => {
85
+ it('filters pull requests and emits JSON rows', async () => {
86
+ const result = await runCommand(prList, ['--label', 'bug', '--limit', '2'], {
87
+ env: { GH_TOKEN: token },
88
+ jsonMode: true,
89
+ });
90
+
91
+ expect(result.exitCode).toBe(0);
92
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual([
93
+ { '#': 137, title: 'Fix date parsing in Safari', state: 'open', author: 'dave' },
94
+ { '#': 141, title: 'Fix OAuth redirect loop', state: 'open', author: 'bob' },
95
+ ]);
96
+ });
97
+
98
+ it('requires authentication before listing', async () => {
99
+ const result = await runCommand(prList, []);
100
+
101
+ expect(result.exitCode).toBe(1);
102
+ expect(result.error?.code).toBe('AUTH_REQUIRED');
103
+ expect(result.stderr.join('')).toContain('Authentication required');
104
+ });
105
+ });
106
+
107
+ // === pr view
108
+
109
+ describe('gh example — pr view', () => {
110
+ it('renders the human summary by default', async () => {
111
+ const result = await runCommand(prView, ['142'], {
112
+ env: { GH_TOKEN: token },
113
+ });
114
+
115
+ expect(result.exitCode).toBe(0);
116
+ expect(result.stdout).toEqual([
117
+ '#142 Add dark mode toggle\nState: open Author: alice Draft: false\nLabels: enhancement, ui\n',
118
+ ]);
119
+ });
120
+
121
+ it('renders only JSON in json mode', async () => {
122
+ const result = await runCommand(prView, ['142'], {
123
+ env: { GH_TOKEN: token },
124
+ jsonMode: true,
125
+ });
126
+
127
+ expect(result.exitCode).toBe(0);
128
+ expect(result.stderr).toEqual([]);
129
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual({
130
+ number: 142,
131
+ title: 'Add dark mode toggle',
132
+ state: 'open',
133
+ author: 'alice',
134
+ labels: ['enhancement', 'ui'],
135
+ draft: false,
136
+ });
137
+ });
138
+
139
+ it('returns a structured not-found error', async () => {
140
+ const result = await runCommand(prView, ['999'], {
141
+ env: { GH_TOKEN: token },
142
+ });
143
+
144
+ expect(result.exitCode).toBe(1);
145
+ expect(result.error?.code).toBe('NOT_FOUND');
146
+ expect(result.stderr.join('')).toContain('Pull request #999 not found');
147
+ });
148
+ });
149
+
150
+ // === pr create
151
+
152
+ describe('gh example — pr create', () => {
153
+ it('creates a draft pull request in human mode', async () => {
154
+ const result = await runCommand(
155
+ prCreate,
156
+ ['--title', 'Fix login', '--body', 'Correct callback URL', '--draft'],
157
+ {
158
+ env: { GH_TOKEN: token },
159
+ },
160
+ );
161
+
162
+ expect(result.exitCode).toBe(0);
163
+ expect(result.stdout).toEqual([
164
+ '#143 Fix login\n',
165
+ 'Marked as draft\n',
166
+ 'https://github.com/you/repo/pull/143\n',
167
+ ]);
168
+ expect(result.activity).toEqual([
169
+ { type: 'spinner:start', text: 'Creating pull request...' },
170
+ { type: 'spinner:succeed', text: 'Pull request created' },
171
+ ]);
172
+ });
173
+
174
+ it('emits only JSON in json mode', async () => {
175
+ const result = await runCommand(
176
+ prCreate,
177
+ ['--title', 'Fix login', '--body', 'Correct callback URL'],
178
+ {
179
+ env: { GH_TOKEN: token },
180
+ jsonMode: true,
181
+ },
182
+ );
183
+
184
+ expect(result.exitCode).toBe(0);
185
+ expect(result.stderr).toEqual([]);
186
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual({
187
+ number: 143,
188
+ title: 'Fix login',
189
+ url: 'https://github.com/you/repo/pull/143',
190
+ });
191
+ });
192
+ });
193
+
194
+ // === issue list
195
+
196
+ describe('gh example — issue list', () => {
197
+ it('applies the state filter before rendering', async () => {
198
+ const result = await runCommand(issueList, ['--state', 'closed'], {
199
+ env: { GH_TOKEN: token },
200
+ jsonMode: true,
201
+ });
202
+
203
+ expect(result.exitCode).toBe(0);
204
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual([
205
+ { '#': 87, title: 'Typo in README', state: 'closed', author: 'grace' },
206
+ ]);
207
+ });
208
+
209
+ it('filters issues and emits JSON rows', async () => {
210
+ const result = await runCommand(issueList, ['--state', 'all', '--label', 'bug'], {
211
+ env: { GH_TOKEN: token },
212
+ jsonMode: true,
213
+ });
214
+
215
+ expect(result.exitCode).toBe(0);
216
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual([
217
+ { '#': 86, title: 'Dark mode colors wrong', state: 'open', author: 'alice' },
218
+ { '#': 89, title: 'Login fails on Firefox', state: 'open', author: 'eve' },
219
+ ]);
220
+ });
221
+ });
222
+
223
+ // === issue triage
224
+
225
+ describe('gh example — issue triage', () => {
226
+ it('guides backlog triage with conditional prompts', async () => {
227
+ const result = await runCommand(issueTriage, ['89', '--decision', 'backlog'], {
228
+ env: { GH_TOKEN: token },
229
+ answers: [['bug', 'ui']],
230
+ });
231
+
232
+ expect(result.exitCode).toBe(0);
233
+ expect(result.stdout).toEqual([
234
+ '#89 Login fails on Firefox\n',
235
+ 'Status: open (backlog)\n',
236
+ 'Labels: bug, ui\n',
237
+ ]);
238
+ });
239
+
240
+ it('switches to the close branch and returns structured JSON', async () => {
241
+ const result = await runCommand(issueTriage, ['89', '--decision', 'close'], {
242
+ env: { GH_TOKEN: token },
243
+ answers: [true],
244
+ jsonMode: true,
245
+ });
246
+
247
+ expect(result.exitCode).toBe(0);
248
+ expect(result.stderr).toEqual([]);
249
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual({
250
+ number: 89,
251
+ title: 'Login fails on Firefox',
252
+ decision: 'close',
253
+ state: 'closed',
254
+ labels: ['bug'],
255
+ commented: true,
256
+ });
257
+ });
258
+
259
+ it('shows the close branch in human mode', async () => {
260
+ const result = await runCommand(issueTriage, ['89', '--decision', 'close'], {
261
+ env: { GH_TOKEN: token },
262
+ answers: [true],
263
+ });
264
+
265
+ expect(result.exitCode).toBe(0);
266
+ expect(result.stdout).toEqual([
267
+ '#89 Login fails on Firefox\n',
268
+ 'Status: closed\n',
269
+ 'Would post a follow-up comment\n',
270
+ ]);
271
+ });
272
+
273
+ it('fails non-interactively when the required decision is missing', async () => {
274
+ const result = await runCommand(issueTriage, ['89'], {
275
+ env: { GH_TOKEN: token },
276
+ });
277
+
278
+ expect(result.exitCode).toBe(2);
279
+ expect(result.error?.code).toBe('REQUIRED_FLAG');
280
+ expect(result.stderr.join('')).toContain('Missing required flag --decision');
281
+ });
282
+
283
+ it('returns a structured not-found error', async () => {
284
+ const result = await runCommand(issueTriage, ['999', '--decision', 'backlog'], {
285
+ env: { GH_TOKEN: token },
286
+ });
287
+
288
+ expect(result.exitCode).toBe(1);
289
+ expect(result.error?.code).toBe('NOT_FOUND');
290
+ expect(result.stderr.join('')).toContain('Issue #999 not found');
291
+ });
292
+ });
293
+
294
+ // === utils
295
+
296
+ describe('gh example — utils', () => {
297
+ it('normalizes numeric limits', () => {
298
+ expect(normalizeLimit(4.8)).toBe(4);
299
+ expect(normalizeLimit(0)).toBe(1);
300
+ expect(normalizeLimit(Number.POSITIVE_INFINITY)).toBe(10);
301
+ });
302
+
303
+ it('sleep resolves', async () => {
304
+ expect(await sleep(0)).toBeUndefined();
305
+ });
306
+ });
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Walkthrough example package entrypoint for a miniature `gh` clone.
4
+ *
5
+ * Usage:
6
+ * GH_TOKEN=ghp_abc123 bun --cwd=examples/gh src/main.ts pr list
7
+ * GH_TOKEN=ghp_abc123 bun --cwd=examples/gh src/main.ts pr list --state all --json
8
+ * GH_TOKEN=ghp_abc123 bun --cwd=examples/gh src/main.ts pr view 142
9
+ * GH_TOKEN=ghp_abc123 bun --cwd=examples/gh src/main.ts pr create
10
+ * GH_TOKEN=ghp_abc123 bun --cwd=examples/gh src/main.ts issue list --label bug
11
+ * GH_TOKEN=ghp_abc123 bun --cwd=examples/gh src/main.ts issue triage 89
12
+ * bun --cwd=examples/gh src/main.ts auth login
13
+ * bun --cwd=examples/gh src/main.ts auth status
14
+ * bun --cwd=examples/gh src/main.ts --help
15
+ *
16
+ * @module
17
+ */
18
+
19
+ import { type CLIBuilder, cli } from 'dreamcli';
20
+
21
+ import { auth } from '$gh/commands/auth.ts';
22
+ import { issue } from '$gh/commands/issue.ts';
23
+ import { pr } from '$gh/commands/pr.ts';
24
+
25
+ /**
26
+ * Create the example CLI and register commands.
27
+ *
28
+ * {@linkcode CLIBuilder.packageJson | packageJson()} fills `version` and `description` from the nearest `package.json`.\
29
+ * The CLI name still comes from `cli('gh')` unless `packageJson({ inferName: true })` is used.
30
+ *
31
+ * Command registration order determines the order shown in `--help`.
32
+ */
33
+ const gh = cli('gh').packageJson();
34
+
35
+ // Run the CLI if this file is executed directly (e.g. `bun src/main.ts ...`).
36
+ if (import.meta.main) {
37
+ void gh.command(auth).command(pr).command(issue).completions().run();
38
+ }
@@ -0,0 +1,37 @@
1
+ {
2
+ "compilerOptions": {
3
+ // Environment setup & latest features
4
+ "lib": ["ESNext"],
5
+ "target": "ESNext",
6
+ "module": "Preserve",
7
+ "moduleDetection": "force",
8
+ "allowJs": true,
9
+
10
+ // Bundler mode
11
+ "moduleResolution": "bundler",
12
+ "allowImportingTsExtensions": true,
13
+ "verbatimModuleSyntax": true,
14
+ "noEmit": true,
15
+
16
+ // Best practices
17
+ "strict": true,
18
+ "skipLibCheck": true,
19
+ "noFallthroughCasesInSwitch": true,
20
+ "noUncheckedIndexedAccess": true,
21
+ "noImplicitOverride": true,
22
+
23
+ // Some stricter flags (disabled by default)
24
+ "noUnusedLocals": true,
25
+ "noUnusedParameters": true,
26
+ "noPropertyAccessFromIndexSignature": false,
27
+
28
+ "composite": true,
29
+
30
+ "types": ["bun"],
31
+ "rootDir": ".",
32
+ "paths": {
33
+ "$gh": ["./src/main.ts"],
34
+ "$gh/*": ["./src/*"]
35
+ }
36
+ }
37
+ }
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Interactive prompts with config file fallback.
4
+ *
5
+ * Demonstrates: per-flag .prompt(), command-level .interactive(),
6
+ * .env(), .config(), resolution chain (CLI → env → config → prompt → default).
7
+ *
8
+ * The resolution chain means:
9
+ * 1. Explicit CLI flag wins: --region eu
10
+ * 2. Then environment variable: DEPLOY_REGION=eu
11
+ * 3. Then config file value: { "deploy": { "region": "eu" } }
12
+ * 4. Then interactive prompt: prompts user to select
13
+ * 5. Then default value: "us"
14
+ *
15
+ * Usage:
16
+ * npx tsx examples/interactive.ts # prompts for everything
17
+ * npx tsx examples/interactive.ts --region eu # skips region prompt
18
+ * DEPLOY_REGION=ap npx tsx examples/interactive.ts # env resolves region
19
+ * echo '{}' | npx tsx examples/interactive.ts # non-interactive: uses defaults / errors
20
+ */
21
+
22
+ import { arg, cli, command, flag } from 'dreamcli';
23
+
24
+ const deploy = command('deploy')
25
+ .description('Deploy to an environment')
26
+ .arg('target', arg.string().describe('Deploy target').default('staging'))
27
+ .flag(
28
+ 'region',
29
+ flag
30
+ .enum(['us', 'eu', 'ap'])
31
+ .env('DEPLOY_REGION')
32
+ .config('deploy.region')
33
+ .prompt({ kind: 'select', message: 'Which region?' })
34
+ .default('us')
35
+ .describe('Target region'),
36
+ )
37
+ .flag(
38
+ 'confirm',
39
+ flag
40
+ .boolean()
41
+ .prompt({ kind: 'confirm', message: 'Proceed with deployment?' })
42
+ .describe('Confirm deployment'),
43
+ )
44
+ .flag(
45
+ 'tag',
46
+ flag
47
+ .string()
48
+ .prompt({ kind: 'input', message: 'Release tag (e.g. v1.2.3):' })
49
+ .describe('Release tag'),
50
+ )
51
+ .action(({ args, flags, out }) => {
52
+ // All flags are resolved by the time action runs.
53
+ // flags.region: "us" | "eu" | "ap" — guaranteed by prompt/default
54
+ // flags.confirm: boolean
55
+ // flags.tag: string | undefined — only if user provided one
56
+ if (!flags.confirm) {
57
+ out.warn('Deployment cancelled');
58
+ return;
59
+ }
60
+ out.log(`Deploying ${args.target} to ${flags.region}`);
61
+ if (flags.tag !== undefined) {
62
+ out.log(`Tagged: ${flags.tag}`);
63
+ }
64
+ });
65
+
66
+ void cli('deploy').default(deploy).run();
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Mixed machine-readable JSON and human-readable side-channel output.
4
+ *
5
+ * Demonstrates: always-on `out.json()` machine output to stdout,
6
+ * human-readable stderr side channels via `out.table(..., { format: 'text',
7
+ * stream: 'stderr' })` / `out.error()`, plus `--json` for CLI-managed JSON
8
+ * behavior such as structured errors.
9
+ *
10
+ * Usage:
11
+ * npx tsx examples/json-mode.ts list # JSON stdout + plain stderr side channel
12
+ * npx tsx examples/json-mode.ts list --format table # JSON stdout + table stderr side channel
13
+ * npx tsx examples/json-mode.ts list --json # same success output; CLI-managed errors stay JSON-safe
14
+ * npx tsx examples/json-mode.ts show web-api
15
+ * npx tsx examples/json-mode.ts show nonexistent # structured error
16
+ * npx tsx examples/json-mode.ts show nonexistent --json # JSON error
17
+ */
18
+
19
+ import { arg, CLIError, cli, command, flag } from 'dreamcli';
20
+
21
+ // --- Sample data ---
22
+
23
+ type Service = {
24
+ readonly name: string;
25
+ readonly status: 'healthy' | 'degraded' | 'down';
26
+ readonly uptime: number;
27
+ };
28
+
29
+ const services: readonly Service[] = [
30
+ { name: 'web-api', status: 'healthy', uptime: 99.9 },
31
+ { name: 'worker', status: 'degraded', uptime: 95.2 },
32
+ { name: 'database', status: 'healthy', uptime: 99.99 },
33
+ { name: 'cache', status: 'down', uptime: 0 },
34
+ ];
35
+
36
+ // --- Commands ---
37
+
38
+ const list = command('list')
39
+ .description('List all services')
40
+ .flag(
41
+ 'format',
42
+ flag.enum(['table', 'plain']).default('plain').alias('f').describe('Output format'),
43
+ )
44
+ .action(({ flags, out }) => {
45
+ // This example always emits machine-readable JSON to stdout. `--json`
46
+ // still matters for DreamCLI-managed output such as structured errors.
47
+ out.json(services);
48
+
49
+ if (flags.format === 'table') {
50
+ out.table(
51
+ services,
52
+ [
53
+ { key: 'name', header: 'Service' },
54
+ { key: 'status', header: 'Status' },
55
+ { key: 'uptime', header: 'Uptime %' },
56
+ ],
57
+ { format: 'text', stream: 'stderr' },
58
+ );
59
+ } else {
60
+ for (const s of services) {
61
+ out.error(`${s.name}: ${s.status} (${s.uptime}%)`);
62
+ }
63
+ }
64
+ });
65
+
66
+ const show = command('show')
67
+ .description('Show details for a service')
68
+ .arg('name', arg.string().describe('Service name'))
69
+ .action(({ args, out }) => {
70
+ const service = services.find((s) => s.name === args.name);
71
+
72
+ if (!service) {
73
+ // CLIError with details serializes cleanly in --json mode.
74
+ throw new CLIError(`Service '${args.name}' not found`, {
75
+ code: 'NOT_FOUND',
76
+ exitCode: 1,
77
+ suggest: `Available: ${services.map((s) => s.name).join(', ')}`,
78
+ details: { requested: args.name, available: services.map((s) => s.name) },
79
+ });
80
+ }
81
+
82
+ out.json(service);
83
+ out.error(`${service.name}: ${service.status} (uptime ${service.uptime}%)`);
84
+ });
85
+
86
+ // --- CLI with --json support ---
87
+
88
+ void cli('services')
89
+ .version('1.0.0')
90
+ .description('Service status dashboard')
91
+ .command(list)
92
+ .command(show)
93
+ .run();