@kjanat/dreamcli 0.0.0 → 2.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 (205) hide show
  1. package/CHANGELOG.md +706 -0
  2. package/LICENSE +22 -0
  3. package/README.md +502 -0
  4. package/dist/core/cli/dispatch.d.mts +85 -0
  5. package/dist/core/cli/dispatch.mjs +1 -0
  6. package/dist/core/cli/index.d.mts +418 -0
  7. package/dist/core/cli/index.mjs +1 -0
  8. package/dist/core/cli/planner.d.mts +143 -0
  9. package/dist/core/cli/planner.mjs +1 -0
  10. package/dist/core/cli/plugin.d.mts +94 -0
  11. package/dist/core/cli/plugin.mjs +1 -0
  12. package/dist/core/cli/propagate.d.mts +39 -0
  13. package/dist/core/cli/propagate.mjs +1 -0
  14. package/dist/core/cli/root-help.d.mts +28 -0
  15. package/dist/core/cli/root-help.mjs +7 -0
  16. package/dist/core/cli/root-surface.d.mts +42 -0
  17. package/dist/core/cli/root-surface.mjs +1 -0
  18. package/dist/core/cli/runtime-preflight.d.mts +149 -0
  19. package/dist/core/cli/runtime-preflight.mjs +1 -0
  20. package/dist/core/completion/index.d.mts +46 -0
  21. package/dist/core/completion/index.mjs +1 -0
  22. package/dist/core/completion/shells/bash.d.mts +24 -0
  23. package/dist/core/completion/shells/bash.mjs +3 -0
  24. package/dist/core/completion/shells/fish.d.mts +20 -0
  25. package/dist/core/completion/shells/fish.mjs +2 -0
  26. package/dist/core/completion/shells/powershell.d.mts +14 -0
  27. package/dist/core/completion/shells/powershell.mjs +2 -0
  28. package/dist/core/completion/shells/shared.d.mts +139 -0
  29. package/dist/core/completion/shells/shared.mjs +1 -0
  30. package/dist/core/completion/shells/zsh.d.mts +24 -0
  31. package/dist/core/completion/shells/zsh.mjs +2 -0
  32. package/dist/core/config/index.d.mts +161 -0
  33. package/dist/core/config/index.mjs +1 -0
  34. package/dist/core/config/package-json.d.mts +68 -0
  35. package/dist/core/config/package-json.mjs +1 -0
  36. package/dist/core/errors/index.d.mts +126 -0
  37. package/dist/core/errors/index.mjs +1 -0
  38. package/dist/core/execution/index.d.mts +49 -0
  39. package/dist/core/execution/index.mjs +1 -0
  40. package/dist/core/help/index.d.mts +49 -0
  41. package/dist/core/help/index.mjs +8 -0
  42. package/dist/core/json-schema/index.d.mts +109 -0
  43. package/dist/core/json-schema/index.mjs +55 -0
  44. package/dist/core/json-schema/meta-descriptions.generated.d.mts +185 -0
  45. package/dist/core/json-schema/meta-descriptions.generated.mjs +28 -0
  46. package/dist/core/output/activity.d.mts +194 -0
  47. package/dist/core/output/activity.mjs +1 -0
  48. package/dist/core/output/contracts.d.mts +88 -0
  49. package/dist/core/output/contracts.mjs +1 -0
  50. package/dist/core/output/display-value.d.mts +19 -0
  51. package/dist/core/output/display-value.mjs +1 -0
  52. package/dist/core/output/index.d.mts +280 -0
  53. package/dist/core/output/index.mjs +2 -0
  54. package/dist/core/output/renderers.d.mts +46 -0
  55. package/dist/core/output/renderers.mjs +1 -0
  56. package/dist/core/output/writer.d.mts +40 -0
  57. package/dist/core/output/writer.mjs +1 -0
  58. package/dist/core/parse/index.d.mts +79 -0
  59. package/dist/core/parse/index.mjs +1 -0
  60. package/dist/core/prompt/index.d.mts +205 -0
  61. package/dist/core/prompt/index.mjs +6 -0
  62. package/dist/core/resolve/args.d.mts +8 -0
  63. package/dist/core/resolve/args.mjs +1 -0
  64. package/dist/core/resolve/coerce.d.mts +22 -0
  65. package/dist/core/resolve/coerce.mjs +1 -0
  66. package/dist/core/resolve/config.d.mts +10 -0
  67. package/dist/core/resolve/config.mjs +1 -0
  68. package/dist/core/resolve/contracts.d.mts +112 -0
  69. package/dist/core/resolve/errors.d.mts +11 -0
  70. package/dist/core/resolve/errors.mjs +2 -0
  71. package/dist/core/resolve/flags.d.mts +10 -0
  72. package/dist/core/resolve/flags.mjs +1 -0
  73. package/dist/core/resolve/index.d.mts +42 -0
  74. package/dist/core/resolve/index.mjs +1 -0
  75. package/dist/core/resolve/property.d.mts +47 -0
  76. package/dist/core/resolve/property.mjs +1 -0
  77. package/dist/core/schema/activity.d.mts +169 -0
  78. package/dist/core/schema/arg.d.mts +559 -0
  79. package/dist/core/schema/arg.mjs +1 -0
  80. package/dist/core/schema/command.d.mts +960 -0
  81. package/dist/core/schema/command.mjs +1 -0
  82. package/dist/core/schema/flag.d.mts +491 -0
  83. package/dist/core/schema/flag.mjs +1 -0
  84. package/dist/core/schema/index.d.mts +8 -0
  85. package/dist/core/schema/middleware.d.mts +122 -0
  86. package/dist/core/schema/middleware.mjs +1 -0
  87. package/dist/core/schema/prompt.d.mts +117 -0
  88. package/dist/core/schema/run.d.mts +171 -0
  89. package/dist/core/schema-dsl/runtime.d.mts +144 -0
  90. package/dist/core/schema-dsl/runtime.mjs +2 -0
  91. package/dist/core/schema-dsl/to-json-schema.d.mts +30 -0
  92. package/dist/core/schema-dsl/to-json-schema.mjs +1 -0
  93. package/dist/core/testkit/index.d.mts +54 -0
  94. package/dist/core/testkit/index.mjs +1 -0
  95. package/dist/index.d.mts +28 -0
  96. package/dist/index.mjs +1 -0
  97. package/dist/runtime/adapter.d.mts +212 -0
  98. package/dist/runtime/adapter.mjs +1 -0
  99. package/dist/runtime/auto.d.mts +26 -0
  100. package/dist/runtime/auto.mjs +1 -0
  101. package/dist/runtime/bun.d.mts +28 -0
  102. package/dist/runtime/bun.mjs +1 -0
  103. package/dist/runtime/deno.d.mts +76 -0
  104. package/dist/runtime/deno.mjs +2 -0
  105. package/dist/runtime/detect.d.mts +86 -0
  106. package/dist/runtime/detect.mjs +1 -0
  107. package/dist/runtime/index.d.mts +7 -0
  108. package/dist/runtime/node.d.mts +65 -0
  109. package/dist/runtime/node.mjs +2 -0
  110. package/dist/runtime/paths.d.mts +31 -0
  111. package/dist/runtime/paths.mjs +1 -0
  112. package/dist/runtime/support.d.mts +42 -0
  113. package/dist/runtime/support.mjs +1 -0
  114. package/dist/runtime.d.mts +7 -0
  115. package/dist/runtime.mjs +1 -0
  116. package/dist/testkit.d.mts +6 -0
  117. package/dist/testkit.mjs +1 -0
  118. package/dist/version.d.mts +16 -0
  119. package/dist/version.mjs +1 -0
  120. package/dreamcli.schema.json +338 -0
  121. package/examples/basic.ts +33 -0
  122. package/examples/gh/package.json +44 -0
  123. package/examples/gh/src/commands/auth.ts +66 -0
  124. package/examples/gh/src/commands/issue.ts +120 -0
  125. package/examples/gh/src/commands/pr.ts +125 -0
  126. package/examples/gh/src/data/issues.yaml +5 -0
  127. package/examples/gh/src/data/issues.yaml.d.ts +17 -0
  128. package/examples/gh/src/data/pull-requests.yaml +7 -0
  129. package/examples/gh/src/data/pull-requests.yaml.d.ts +18 -0
  130. package/examples/gh/src/docs.ts +11 -0
  131. package/examples/gh/src/lib/auth.ts +37 -0
  132. package/examples/gh/src/lib/utils.ts +17 -0
  133. package/examples/gh/src/main.test.ts +307 -0
  134. package/examples/gh/src/main.ts +40 -0
  135. package/examples/interactive.ts +66 -0
  136. package/examples/json-mode.ts +91 -0
  137. package/examples/middleware.ts +71 -0
  138. package/examples/multi-command.ts +66 -0
  139. package/examples/spinner-progress.ts +49 -0
  140. package/examples/testing.ts +147 -0
  141. package/package.json +149 -2
  142. package/src/core/cli/dispatch.ts +286 -0
  143. package/src/core/cli/index.ts +978 -0
  144. package/src/core/cli/planner.ts +413 -0
  145. package/src/core/cli/plugin.ts +117 -0
  146. package/src/core/cli/propagate.ts +97 -0
  147. package/src/core/cli/root-help.ts +269 -0
  148. package/src/core/cli/root-surface.ts +74 -0
  149. package/src/core/cli/runtime-preflight.ts +409 -0
  150. package/src/core/completion/index.ts +88 -0
  151. package/src/core/completion/shells/bash.ts +459 -0
  152. package/src/core/completion/shells/fish.ts +259 -0
  153. package/src/core/completion/shells/powershell.ts +405 -0
  154. package/src/core/completion/shells/shared.ts +283 -0
  155. package/src/core/completion/shells/zsh.ts +381 -0
  156. package/src/core/config/index.ts +407 -0
  157. package/src/core/config/package-json.ts +220 -0
  158. package/src/core/errors/index.ts +193 -0
  159. package/src/core/execution/index.ts +270 -0
  160. package/src/core/help/index.ts +557 -0
  161. package/src/core/json-schema/index.ts +891 -0
  162. package/src/core/json-schema/meta-descriptions.generated.ts +202 -0
  163. package/src/core/output/activity.ts +568 -0
  164. package/src/core/output/contracts.ts +194 -0
  165. package/src/core/output/display-value.ts +48 -0
  166. package/src/core/output/index.ts +669 -0
  167. package/src/core/output/renderers.ts +125 -0
  168. package/src/core/output/writer.ts +46 -0
  169. package/src/core/parse/index.ts +661 -0
  170. package/src/core/prompt/index.ts +583 -0
  171. package/src/core/resolve/args.ts +144 -0
  172. package/src/core/resolve/coerce.ts +432 -0
  173. package/src/core/resolve/config.ts +26 -0
  174. package/src/core/resolve/contracts.ts +135 -0
  175. package/src/core/resolve/errors.ts +227 -0
  176. package/src/core/resolve/flags.ts +205 -0
  177. package/src/core/resolve/index.ts +108 -0
  178. package/src/core/resolve/property.ts +99 -0
  179. package/src/core/schema/activity.ts +240 -0
  180. package/src/core/schema/arg.ts +719 -0
  181. package/src/core/schema/command.ts +1490 -0
  182. package/src/core/schema/flag.ts +756 -0
  183. package/src/core/schema/index.ts +91 -0
  184. package/src/core/schema/middleware.ts +171 -0
  185. package/src/core/schema/prompt.ts +156 -0
  186. package/src/core/schema/run.ts +195 -0
  187. package/src/core/schema-dsl/index.ts +109 -0
  188. package/src/core/schema-dsl/parse.ts +262 -0
  189. package/src/core/schema-dsl/runtime.ts +609 -0
  190. package/src/core/schema-dsl/to-json-schema.ts +102 -0
  191. package/src/core/testkit/index.ts +123 -0
  192. package/src/index.ts +170 -0
  193. package/src/runtime/adapter.ts +303 -0
  194. package/src/runtime/auto.ts +110 -0
  195. package/src/runtime/bun.ts +55 -0
  196. package/src/runtime/deno.ts +369 -0
  197. package/src/runtime/detect.ts +105 -0
  198. package/src/runtime/index.ts +21 -0
  199. package/src/runtime/node-builtins.d.ts +23 -0
  200. package/src/runtime/node.ts +300 -0
  201. package/src/runtime/paths.ts +62 -0
  202. package/src/runtime/support.ts +135 -0
  203. package/src/runtime.ts +31 -0
  204. package/src/testkit.ts +25 -0
  205. package/src/version.ts +20 -0
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Pull request commands for the walkthrough `gh` example.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ import { arg, CLIError, flag, group } from '@kjanat/dreamcli';
8
+
9
+ import pullRequests from '../data/pull-requests.yaml' with { type: 'yaml' };
10
+ import { authedCommand } from '../lib/auth.ts';
11
+ import { normalizeLimit, sleep } from '../lib/utils.ts';
12
+
13
+ const prList = authedCommand('list')
14
+ .description('List pull requests')
15
+ .flag(
16
+ 'state',
17
+ flag
18
+ .enum(['open', 'closed', 'merged', 'all'])
19
+ .default('open')
20
+ .alias('s')
21
+ .describe('Filter by state'),
22
+ )
23
+ .flag('limit', flag.number().default(10).alias('L').describe('Maximum number of results'))
24
+ .flag('label', flag.string().alias('l').describe('Filter by label'))
25
+ .action(({ flags, out }) => {
26
+ let results = [...pullRequests];
27
+
28
+ if (flags.state !== 'all') {
29
+ results = results.filter((pr) => pr.state === flags.state);
30
+ }
31
+
32
+ if (flags.label !== undefined) {
33
+ const label = flags.label;
34
+ results = results.filter((pr) => pr.labels.includes(label));
35
+ }
36
+
37
+ results = results.slice(0, normalizeLimit(flags.limit));
38
+
39
+ out.table(
40
+ results.map((pr) => ({
41
+ '#': pr.number,
42
+ title: pr.title,
43
+ state: pr.state,
44
+ author: pr.author,
45
+ })),
46
+ );
47
+ });
48
+
49
+ const prView = authedCommand('view')
50
+ .description('View a pull request')
51
+ .arg('number', arg.number().describe('PR number'))
52
+ .action(({ args, out }) => {
53
+ const pr = pullRequests.find((candidate) => candidate.number === args.number);
54
+
55
+ if (!pr) {
56
+ throw new CLIError(`Pull request #${args.number} not found`, {
57
+ code: 'NOT_FOUND',
58
+ exitCode: 1,
59
+ suggest: 'Try: gh pr list',
60
+ details: { requested: args.number },
61
+ });
62
+ }
63
+
64
+ if (out.jsonMode) {
65
+ out.json(pr);
66
+ return;
67
+ }
68
+
69
+ out.log(`\
70
+ #${pr.number} ${pr.title}
71
+ State: ${pr.state} Author: ${pr.author} Draft: ${String(pr.draft)}
72
+ Labels: ${pr.labels.join(', ')}`);
73
+ });
74
+
75
+ const prCreate = authedCommand('create')
76
+ .description('Create a pull request')
77
+ .flag(
78
+ 'title',
79
+ flag
80
+ .string()
81
+ .required()
82
+ .alias('t')
83
+ .describe('PR title')
84
+ .prompt({ kind: 'input', message: 'Title:' }),
85
+ )
86
+ .flag(
87
+ 'body',
88
+ flag
89
+ .string()
90
+ .required()
91
+ .alias('b')
92
+ .describe('PR body')
93
+ .prompt({ kind: 'input', message: 'Body:' }),
94
+ )
95
+ .flag('draft', flag.boolean().alias('d').default(false).describe('Create as draft'))
96
+ .action(async ({ flags, out }) => {
97
+ const spinner = out.spinner('Creating pull request...');
98
+ await sleep(1500);
99
+ spinner.succeed('Pull request created');
100
+
101
+ const createdPr = {
102
+ number: 143,
103
+ title: flags.title,
104
+ url: 'https://github.com/you/repo/pull/143',
105
+ };
106
+
107
+ if (out.jsonMode) {
108
+ out.json(createdPr);
109
+ return;
110
+ }
111
+
112
+ out.log(`#${createdPr.number} ${createdPr.title}`);
113
+ if (flags.draft) {
114
+ out.info('Marked as draft');
115
+ }
116
+ out.log(createdPr.url);
117
+ });
118
+
119
+ export { prCreate, prList, prView };
120
+
121
+ export const pr = group('pr')
122
+ .description('Manage pull requests')
123
+ .command(prList)
124
+ .command(prView)
125
+ .command(prCreate);
@@ -0,0 +1,5 @@
1
+ ---
2
+ - { number: 86, title: Dark mode colors wrong, state: open, author: alice, labels: [bug, ui] }
3
+ - { number: 87, title: Typo in README, state: closed, author: grace, labels: [docs] }
4
+ - { number: 88, title: Add keyboard shortcuts, state: open, author: frank, labels: [enhancement] }
5
+ - { number: 89, title: Login fails on Firefox, state: open, author: eve, labels: [bug] }
@@ -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,11 @@
1
+ /**
2
+ * Docs-facing exports for walkthrough Twoslash snippets.
3
+ *
4
+ * Keeps guide imports stable while reusing real command definitions.
5
+ *
6
+ * @module
7
+ */
8
+
9
+ export { authLogin, authStatus } from './commands/auth.ts';
10
+ export { issueList, issueTriage } from './commands/issue.ts';
11
+ export { prCreate, prList, prView } from './commands/pr.ts';
@@ -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 '@kjanat/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,307 @@
1
+ /**
2
+ * Smoke tests for the walkthrough `gh` example.
3
+ *
4
+ * @module
5
+ */
6
+ /// <reference types="bun" />
7
+
8
+ import { describe, expect, it } from 'bun:test';
9
+
10
+ import { runCommand } from '@kjanat/dreamcli/testkit';
11
+
12
+ import { authLogin, authStatus } from './commands/auth.ts';
13
+ import { issueList, issueTriage } from './commands/issue.ts';
14
+ import { prCreate, prList, prView } from './commands/pr.ts';
15
+ import { normalizeLimit, sleep } from './lib/utils.ts';
16
+
17
+ const token = 'ghp_test_token_1234';
18
+
19
+ // === auth login
20
+
21
+ describe('gh example — auth login', () => {
22
+ it('logs the redacted token in human mode', async () => {
23
+ const result = await runCommand(authLogin, [], {
24
+ env: { GH_TOKEN: token },
25
+ });
26
+
27
+ expect(result.exitCode).toBe(0);
28
+ expect(result.stdout).toEqual([
29
+ 'Logged in with token ghp_test...1234\n',
30
+ 'Token would be saved to ~/.config/gh/config.json\n',
31
+ ]);
32
+ });
33
+
34
+ it('returns structured JSON in json mode', async () => {
35
+ const result = await runCommand(authLogin, [], {
36
+ env: { GH_TOKEN: token },
37
+ jsonMode: true,
38
+ });
39
+
40
+ expect(result.exitCode).toBe(0);
41
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual({
42
+ host: 'github.com',
43
+ token: 'ghp_test...1234',
44
+ storedAt: '~/.config/gh/config.json',
45
+ });
46
+ });
47
+ });
48
+
49
+ // === auth status
50
+
51
+ describe('gh example — auth status', () => {
52
+ it('resolves GH_TOKEN through the command schema', async () => {
53
+ const result = await runCommand(authStatus, [], {
54
+ env: { GH_TOKEN: token },
55
+ });
56
+
57
+ expect(result.exitCode).toBe(0);
58
+ expect(result.stdout).toEqual(['github.com\n', 'Logged in with token ghp_test...1234\n']);
59
+ });
60
+
61
+ it('warns when no token resolves', async () => {
62
+ const result = await runCommand(authStatus, []);
63
+
64
+ expect(result.exitCode).toBe(0);
65
+ expect(result.stderr).toEqual(['Not logged in. Run `gh auth login`.\n']);
66
+ });
67
+
68
+ it('returns structured JSON in json mode', async () => {
69
+ const result = await runCommand(authStatus, [], {
70
+ env: { GH_TOKEN: token },
71
+ jsonMode: true,
72
+ });
73
+
74
+ expect(result.exitCode).toBe(0);
75
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual({
76
+ authenticated: true,
77
+ host: 'github.com',
78
+ token: 'ghp_test...1234',
79
+ });
80
+ });
81
+ });
82
+
83
+ // === pr list
84
+
85
+ describe('gh example — pr list', () => {
86
+ it('filters pull requests and emits JSON rows', async () => {
87
+ const result = await runCommand(prList, ['--label', 'bug', '--limit', '2'], {
88
+ env: { GH_TOKEN: token },
89
+ jsonMode: true,
90
+ });
91
+
92
+ expect(result.exitCode).toBe(0);
93
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual([
94
+ { '#': 137, title: 'Fix date parsing in Safari', state: 'open', author: 'dave' },
95
+ { '#': 141, title: 'Fix OAuth redirect loop', state: 'open', author: 'bob' },
96
+ ]);
97
+ });
98
+
99
+ it('requires authentication before listing', async () => {
100
+ const result = await runCommand(prList, []);
101
+
102
+ expect(result.exitCode).toBe(1);
103
+ expect(result.error?.code).toBe('AUTH_REQUIRED');
104
+ expect(result.stderr.join('')).toContain('Authentication required');
105
+ });
106
+ });
107
+
108
+ // === pr view
109
+
110
+ describe('gh example — pr view', () => {
111
+ it('renders the human summary by default', async () => {
112
+ const result = await runCommand(prView, ['142'], {
113
+ env: { GH_TOKEN: token },
114
+ });
115
+
116
+ expect(result.exitCode).toBe(0);
117
+ expect(result.stdout).toEqual([
118
+ '#142 Add dark mode toggle\nState: open Author: alice Draft: false\nLabels: enhancement, ui\n',
119
+ ]);
120
+ });
121
+
122
+ it('renders only JSON in json mode', async () => {
123
+ const result = await runCommand(prView, ['142'], {
124
+ env: { GH_TOKEN: token },
125
+ jsonMode: true,
126
+ });
127
+
128
+ expect(result.exitCode).toBe(0);
129
+ expect(result.stderr).toEqual([]);
130
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual({
131
+ number: 142,
132
+ title: 'Add dark mode toggle',
133
+ state: 'open',
134
+ author: 'alice',
135
+ labels: ['enhancement', 'ui'],
136
+ draft: false,
137
+ });
138
+ });
139
+
140
+ it('returns a structured not-found error', async () => {
141
+ const result = await runCommand(prView, ['999'], {
142
+ env: { GH_TOKEN: token },
143
+ });
144
+
145
+ expect(result.exitCode).toBe(1);
146
+ expect(result.error?.code).toBe('NOT_FOUND');
147
+ expect(result.stderr.join('')).toContain('Pull request #999 not found');
148
+ });
149
+ });
150
+
151
+ // === pr create
152
+
153
+ describe('gh example — pr create', () => {
154
+ it('creates a draft pull request in human mode', async () => {
155
+ const result = await runCommand(
156
+ prCreate,
157
+ ['--title', 'Fix login', '--body', 'Correct callback URL', '--draft'],
158
+ {
159
+ env: { GH_TOKEN: token },
160
+ },
161
+ );
162
+
163
+ expect(result.exitCode).toBe(0);
164
+ expect(result.stdout).toEqual([
165
+ '#143 Fix login\n',
166
+ 'Marked as draft\n',
167
+ 'https://github.com/you/repo/pull/143\n',
168
+ ]);
169
+ expect(result.activity).toEqual([
170
+ { type: 'spinner:start', text: 'Creating pull request...' },
171
+ { type: 'spinner:succeed', text: 'Pull request created' },
172
+ ]);
173
+ });
174
+
175
+ it('emits only JSON in json mode', async () => {
176
+ const result = await runCommand(
177
+ prCreate,
178
+ ['--title', 'Fix login', '--body', 'Correct callback URL'],
179
+ {
180
+ env: { GH_TOKEN: token },
181
+ jsonMode: true,
182
+ },
183
+ );
184
+
185
+ expect(result.exitCode).toBe(0);
186
+ expect(result.stderr).toEqual([]);
187
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual({
188
+ number: 143,
189
+ title: 'Fix login',
190
+ url: 'https://github.com/you/repo/pull/143',
191
+ });
192
+ });
193
+ });
194
+
195
+ // === issue list
196
+
197
+ describe('gh example — issue list', () => {
198
+ it('applies the state filter before rendering', async () => {
199
+ const result = await runCommand(issueList, ['--state', 'closed'], {
200
+ env: { GH_TOKEN: token },
201
+ jsonMode: true,
202
+ });
203
+
204
+ expect(result.exitCode).toBe(0);
205
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual([
206
+ { '#': 87, title: 'Typo in README', state: 'closed', author: 'grace' },
207
+ ]);
208
+ });
209
+
210
+ it('filters issues and emits JSON rows', async () => {
211
+ const result = await runCommand(issueList, ['--state', 'all', '--label', 'bug'], {
212
+ env: { GH_TOKEN: token },
213
+ jsonMode: true,
214
+ });
215
+
216
+ expect(result.exitCode).toBe(0);
217
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual([
218
+ { '#': 86, title: 'Dark mode colors wrong', state: 'open', author: 'alice' },
219
+ { '#': 89, title: 'Login fails on Firefox', state: 'open', author: 'eve' },
220
+ ]);
221
+ });
222
+ });
223
+
224
+ // === issue triage
225
+
226
+ describe('gh example — issue triage', () => {
227
+ it('guides backlog triage with conditional prompts', async () => {
228
+ const result = await runCommand(issueTriage, ['89', '--decision', 'backlog'], {
229
+ env: { GH_TOKEN: token },
230
+ answers: [['bug', 'ui']],
231
+ });
232
+
233
+ expect(result.exitCode).toBe(0);
234
+ expect(result.stdout).toEqual([
235
+ '#89 Login fails on Firefox\n',
236
+ 'Status: open (backlog)\n',
237
+ 'Labels: bug, ui\n',
238
+ ]);
239
+ });
240
+
241
+ it('switches to the close branch and returns structured JSON', async () => {
242
+ const result = await runCommand(issueTriage, ['89', '--decision', 'close'], {
243
+ env: { GH_TOKEN: token },
244
+ answers: [true],
245
+ jsonMode: true,
246
+ });
247
+
248
+ expect(result.exitCode).toBe(0);
249
+ expect(result.stderr).toEqual([]);
250
+ expect(JSON.parse(result.stdout[0] ?? '')).toEqual({
251
+ number: 89,
252
+ title: 'Login fails on Firefox',
253
+ decision: 'close',
254
+ state: 'closed',
255
+ labels: ['bug'],
256
+ commented: true,
257
+ });
258
+ });
259
+
260
+ it('shows the close branch in human mode', async () => {
261
+ const result = await runCommand(issueTriage, ['89', '--decision', 'close'], {
262
+ env: { GH_TOKEN: token },
263
+ answers: [true],
264
+ });
265
+
266
+ expect(result.exitCode).toBe(0);
267
+ expect(result.stdout).toEqual([
268
+ '#89 Login fails on Firefox\n',
269
+ 'Status: closed\n',
270
+ 'Would post a follow-up comment\n',
271
+ ]);
272
+ });
273
+
274
+ it('fails non-interactively when the required decision is missing', async () => {
275
+ const result = await runCommand(issueTriage, ['89'], {
276
+ env: { GH_TOKEN: token },
277
+ });
278
+
279
+ expect(result.exitCode).toBe(2);
280
+ expect(result.error?.code).toBe('REQUIRED_FLAG');
281
+ expect(result.stderr.join('')).toContain('Missing required flag --decision');
282
+ });
283
+
284
+ it('returns a structured not-found error', async () => {
285
+ const result = await runCommand(issueTriage, ['999', '--decision', 'backlog'], {
286
+ env: { GH_TOKEN: token },
287
+ });
288
+
289
+ expect(result.exitCode).toBe(1);
290
+ expect(result.error?.code).toBe('NOT_FOUND');
291
+ expect(result.stderr.join('')).toContain('Issue #999 not found');
292
+ });
293
+ });
294
+
295
+ // === utils
296
+
297
+ describe('gh example — utils', () => {
298
+ it('normalizes numeric limits', () => {
299
+ expect(normalizeLimit(4.8)).toBe(4);
300
+ expect(normalizeLimit(0)).toBe(1);
301
+ expect(normalizeLimit(Number.POSITIVE_INFINITY)).toBe(10);
302
+ });
303
+
304
+ it('sleep resolves', async () => {
305
+ expect(await sleep(0)).toBeUndefined();
306
+ });
307
+ });
@@ -0,0 +1,40 @@
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
+ // oxlint-disable-next-line no-unused-vars -- for CLIBuilder type in JSDoc
20
+ import type { CLIBuilder } from '@kjanat/dreamcli';
21
+ import { cli } from '@kjanat/dreamcli';
22
+
23
+ import { auth } from './commands/auth.ts';
24
+ import { issue } from './commands/issue.ts';
25
+ import { pr } from './commands/pr.ts';
26
+
27
+ /**
28
+ * Create the example CLI and register commands.
29
+ *
30
+ * {@linkcode CLIBuilder.packageJson | packageJson()} fills `version` and `description` from the nearest `package.json`.\
31
+ * The CLI name still comes from `cli('gh')` unless `packageJson({ inferName: true })` is used.
32
+ *
33
+ * Command registration order determines the order shown in `--help`.
34
+ */
35
+ export const gh = cli('gh').packageJson().command(auth).command(pr).command(issue).completions();
36
+
37
+ // Run the CLI if this file is executed directly (e.g. `bun src/main.ts ...`).
38
+ if (import.meta.main) {
39
+ gh.run();
40
+ }
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Interactive prompts with config file fallback.
4
+ *
5
+ * Demonstrates: per-flag `.prompt()`, `.env()`, `.config()`, and the full
6
+ * 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 '@kjanat/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();