@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,407 @@
1
+ /**
2
+ * Config file discovery and loading.
3
+ *
4
+ * Probes a prioritised list of candidate paths, reads the first match via
5
+ * {@link RuntimeAdapter.readFile}, and parses the content using an
6
+ * extension-based loader (JSON built-in, others additive via {@link FormatLoader}).
7
+ *
8
+ * The module is pure — all I/O flows through the adapter, making it fully
9
+ * testable with {@link createTestAdapter}'s virtual filesystem.
10
+ *
11
+ * @module dreamcli/core/config
12
+ */
13
+
14
+ import { CLIError } from '#internals/core/errors/index.ts';
15
+ import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
16
+
17
+ /** @internal */
18
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
19
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
20
+ return false;
21
+ }
22
+ const proto = Object.getPrototypeOf(value);
23
+ return proto === Object.prototype || proto === null;
24
+ }
25
+
26
+ // --- Types — format loaders
27
+
28
+ /**
29
+ * Format loader — parses file content into a config object.
30
+ *
31
+ * Register custom config formats by providing file extensions and a parser.
32
+ * Parsers may return any parsed value; {@link discoverConfig} validates that
33
+ * the result is a plain object before feeding it into the resolution chain.
34
+ *
35
+ * Implementations should throw on syntax or shape errors; the caller wraps
36
+ * those failures as {@link CLIError} with code `CONFIG_PARSE_ERROR`.
37
+ */
38
+ interface FormatLoader {
39
+ /** File extensions this loader handles (without leading dot, e.g. `'toml'`). */
40
+ readonly extensions: readonly string[];
41
+
42
+ /**
43
+ * Parse file content into a config value.
44
+ *
45
+ * Arrays, primitives, and `null` are allowed at this boundary so generic
46
+ * parsers like `Bun.YAML.parse` can be passed directly. Those values are
47
+ * still rejected by {@link discoverConfig}, which requires a plain object.
48
+ */
49
+ readonly parse: (content: string) => unknown;
50
+ }
51
+
52
+ // --- Types — discovery options + result
53
+
54
+ /** Options for {@link discoverConfig}. */
55
+ interface ConfigDiscoveryOptions {
56
+ /**
57
+ * Explicit config file path (`--config` override).
58
+ * When provided, skips search — loads only this path.
59
+ */
60
+ readonly configPath?: string;
61
+
62
+ /**
63
+ * Additional format loaders (JSON is built-in).
64
+ * Later loaders for the same extension win (allows override).
65
+ */
66
+ readonly loaders?: readonly FormatLoader[];
67
+
68
+ /**
69
+ * Custom search paths (absolute).
70
+ * Replaces the default search paths when provided.
71
+ * Probed in order; first found wins.
72
+ */
73
+ readonly searchPaths?: readonly string[];
74
+ }
75
+
76
+ /** Successful config discovery — file found and parsed. */
77
+ interface ConfigFound {
78
+ /** Discriminant — `true` indicates a config file was found and parsed successfully. */
79
+ readonly found: true;
80
+ /** Absolute path to the config file that was loaded. */
81
+ readonly path: string;
82
+ /** Parsed config data. */
83
+ readonly data: Readonly<Record<string, unknown>>;
84
+ /** File extension that determined the loader (e.g. `'json'`). */
85
+ readonly format: string;
86
+ }
87
+
88
+ /** No config file found at any candidate path (not an error). */
89
+ interface ConfigNotFound {
90
+ /** Discriminant — `false` indicates no config file exists at any candidate path. */
91
+ readonly found: false;
92
+ }
93
+
94
+ /** Discriminated result of config discovery. */
95
+ type ConfigDiscoveryResult = ConfigFound | ConfigNotFound;
96
+
97
+ // --- Built-in JSON loader
98
+
99
+ /** @internal */
100
+ const jsonLoader: FormatLoader = {
101
+ extensions: ['json'],
102
+ parse: (content: string): Record<string, unknown> => {
103
+ const parsed: unknown = JSON.parse(content);
104
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
105
+ throw new Error('Config must be a JSON object');
106
+ }
107
+ return parsed as Record<string, unknown>;
108
+ },
109
+ };
110
+
111
+ // --- Path utilities
112
+
113
+ /**
114
+ * Join path segments using the separator detected from the base path.
115
+ *
116
+ * Avoids importing `node:path` — the base path is already platform-native
117
+ * (comes from `adapter.cwd` / `adapter.configDir`), so we infer the
118
+ * separator from its content.
119
+ *
120
+ * @internal
121
+ */
122
+ function joinPath(base: string, ...segments: readonly string[]): string {
123
+ const sep = base.includes('\\') ? '\\' : '/';
124
+ return [base, ...segments].join(sep);
125
+ }
126
+
127
+ /**
128
+ * Extract the file extension (without leading dot, lowercased).
129
+ * Returns empty string when no extension is present.
130
+ *
131
+ * @internal
132
+ */
133
+ function getExtension(path: string): string {
134
+ const lastDot = path.lastIndexOf('.');
135
+ const lastSep = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
136
+ if (lastDot <= lastSep) return '';
137
+ return path.slice(lastDot + 1).toLowerCase();
138
+ }
139
+
140
+ // --- buildConfigSearchPaths
141
+
142
+ /**
143
+ * Build the default config search paths for an app.
144
+ *
145
+ * Advanced helper used by DreamCLI's config discovery. Most apps should call
146
+ * `.config()` or {@link discoverConfig} instead of constructing search paths
147
+ * manually. Exported for debugging, custom discovery flows, and help text.
148
+ *
149
+ * Search order (first match wins):
150
+ * 1. `$CWD/.{appName}.json` — dotfile in project root
151
+ * 2. `$CWD/{appName}.config.json` — explicit config in project root
152
+ * 3. `$CONFIG_DIR/{appName}/config.json` — XDG / AppData standard
153
+ * (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
154
+ * `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
155
+ *
156
+ * When custom {@link ConfigDiscoveryOptions.loaders | loaders} are registered,
157
+ * each path pattern is repeated per supported extension (JSON always first).
158
+ *
159
+ * @param appName - CLI application name used to derive config filenames.
160
+ * @param cwd - Current working directory (project-root search location).
161
+ * @param configDir - Platform config directory (XDG / AppData).
162
+ * @param loaders - Optional custom {@link FormatLoader}s whose extensions expand the search set.
163
+ * @returns Ordered list of candidate config file paths (first match wins).
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * const paths = buildConfigSearchPaths('mycli', '/repo', '/home/me/.config');
168
+ * ```
169
+ */
170
+ function buildConfigSearchPaths(
171
+ appName: string,
172
+ cwd: string,
173
+ configDir: string,
174
+ loaders?: readonly FormatLoader[],
175
+ ): readonly string[] {
176
+ const extensions = buildExtensionList(loaders);
177
+
178
+ const paths: string[] = [];
179
+ for (const ext of extensions) {
180
+ paths.push(joinPath(cwd, `.${appName}.${ext}`));
181
+ }
182
+ for (const ext of extensions) {
183
+ paths.push(joinPath(cwd, `${appName}.config.${ext}`));
184
+ }
185
+ for (const ext of extensions) {
186
+ paths.push(joinPath(configDir, appName, `config.${ext}`));
187
+ }
188
+ return paths;
189
+ }
190
+
191
+ /**
192
+ * Collect unique extensions from the built-in JSON loader + any custom loaders.
193
+ * JSON always comes first. Order otherwise matches loader registration order.
194
+ *
195
+ * @param loaders - Optional custom {@link FormatLoader}s to append after JSON.
196
+ * @returns Deduplicated, lowercased extension list (JSON first).
197
+ *
198
+ * @internal
199
+ */
200
+ function buildExtensionList(loaders?: readonly FormatLoader[]): readonly string[] {
201
+ const seen = new Set<string>();
202
+ const result: string[] = [];
203
+
204
+ // JSON first — always built-in
205
+ for (const ext of jsonLoader.extensions) {
206
+ const lower = ext.toLowerCase();
207
+ if (!seen.has(lower)) {
208
+ seen.add(lower);
209
+ result.push(lower);
210
+ }
211
+ }
212
+
213
+ // Additional loaders
214
+ if (loaders !== undefined) {
215
+ for (const loader of loaders) {
216
+ for (const ext of loader.extensions) {
217
+ const lower = ext.toLowerCase();
218
+ if (!seen.has(lower)) {
219
+ seen.add(lower);
220
+ result.push(lower);
221
+ }
222
+ }
223
+ }
224
+ }
225
+
226
+ return result;
227
+ }
228
+
229
+ // --- buildLoaderMap
230
+
231
+ /**
232
+ * Build extension → loader lookup. Later loaders for the same extension
233
+ * override earlier ones (allows user to replace the built-in JSON loader).
234
+ *
235
+ * @param loaders - Optional custom {@link FormatLoader}s (later entries override earlier for same extension).
236
+ * @returns Map from lowercased extension to its {@link FormatLoader}.
237
+ *
238
+ * @internal
239
+ */
240
+ function buildLoaderMap(loaders?: readonly FormatLoader[]): ReadonlyMap<string, FormatLoader> {
241
+ const map = new Map<string, FormatLoader>();
242
+ for (const ext of jsonLoader.extensions) {
243
+ map.set(ext.toLowerCase(), jsonLoader);
244
+ }
245
+ if (loaders !== undefined) {
246
+ for (const loader of loaders) {
247
+ for (const ext of loader.extensions) {
248
+ map.set(ext.toLowerCase(), loader);
249
+ }
250
+ }
251
+ }
252
+ return map;
253
+ }
254
+
255
+ // --- discoverConfig
256
+
257
+ /**
258
+ * The subset of {@link RuntimeAdapter} needed for config discovery.
259
+ *
260
+ * Exported so custom hosts and tests can type the minimal adapter required by
261
+ * {@link discoverConfig} without depending on the full runtime adapter shape.
262
+ */
263
+ type ConfigAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd' | 'configDir'>;
264
+
265
+ /**
266
+ * Discover and load a config file.
267
+ *
268
+ * Low-level discovery helper behind `CLIBuilder.config()`. Most apps should
269
+ * let the CLI runtime call this automatically; call it directly when testing
270
+ * config behavior or building custom bootstrapping around {@linkcode RuntimeAdapter}.
271
+ *
272
+ * Pure function — all filesystem I/O flows through `adapter.readFile`.
273
+ * Returns a discriminated union: `{ found: true, ... }` when a config
274
+ * file was found and parsed, `{ found: false }` when no file exists.
275
+ *
276
+ * @throws {CLIError} code `CONFIG_NOT_FOUND` — explicit `configPath` doesn't exist
277
+ * @throws {CLIError} code `CONFIG_PARSE_ERROR` — file exists but fails to parse
278
+ * @throws {CLIError} code `CONFIG_UNKNOWN_FORMAT` — no loader for the file extension
279
+ *
280
+ * @example
281
+ * ```ts
282
+ * const result = await discoverConfig('mycli', adapter, {
283
+ * loaders: [
284
+ * configFormat(['yaml', 'yml'], Bun.YAML.parse),
285
+ * configFormat(['toml'], Bun.TOML.parse),
286
+ * ],
287
+ * });
288
+ * ```
289
+ */
290
+ async function discoverConfig(
291
+ appName: string,
292
+ adapter: ConfigAdapter,
293
+ options?: ConfigDiscoveryOptions,
294
+ ): Promise<ConfigDiscoveryResult> {
295
+ const loaderMap = buildLoaderMap(options?.loaders);
296
+
297
+ const searchPaths =
298
+ options?.configPath !== undefined
299
+ ? [options.configPath]
300
+ : (options?.searchPaths ??
301
+ buildConfigSearchPaths(appName, adapter.cwd, adapter.configDir, options?.loaders));
302
+
303
+ for (const candidatePath of searchPaths) {
304
+ const content = await adapter.readFile(candidatePath);
305
+
306
+ if (content === null) {
307
+ // Explicit --config path must exist
308
+ if (options?.configPath !== undefined) {
309
+ throw new CLIError(`Config file not found: ${candidatePath}`, {
310
+ code: 'CONFIG_NOT_FOUND',
311
+ details: { path: candidatePath },
312
+ suggest: 'Create the config file or remove the --config flag',
313
+ });
314
+ }
315
+ continue;
316
+ }
317
+
318
+ // File found — resolve loader by extension
319
+ const ext = getExtension(candidatePath);
320
+ const loader = loaderMap.get(ext);
321
+
322
+ if (loader === undefined) {
323
+ throw new CLIError(`No loader registered for config format: .${ext}`, {
324
+ code: 'CONFIG_UNKNOWN_FORMAT',
325
+ details: { path: candidatePath, extension: ext },
326
+ suggest: `Supported formats: ${[...loaderMap.keys()].join(', ')}`,
327
+ });
328
+ }
329
+
330
+ try {
331
+ const data = loader.parse(content);
332
+ if (!isPlainObject(data)) {
333
+ throw new Error('Config loader must return a plain object');
334
+ }
335
+ return { found: true, path: candidatePath, data, format: ext };
336
+ } catch (cause: unknown) {
337
+ throw new CLIError(`Failed to parse config file: ${candidatePath}`, {
338
+ code: 'CONFIG_PARSE_ERROR',
339
+ cause,
340
+ details: {
341
+ path: candidatePath,
342
+ format: ext,
343
+ message: cause instanceof Error ? cause.message : String(cause),
344
+ },
345
+ suggest: 'Check the config file for syntax errors',
346
+ });
347
+ }
348
+ }
349
+
350
+ return { found: false };
351
+ }
352
+
353
+ // --- configFormat — convenience factory for FormatLoader
354
+
355
+ /**
356
+ * Create a {@link FormatLoader} from extensions and a parse function.
357
+ *
358
+ * Convenience factory for config loading. It avoids manually constructing the
359
+ * `{ extensions, parse }` object and makes intent clearer at call sites.
360
+ *
361
+ * Later loaders registered for the same extension override earlier ones. Any
362
+ * error thrown by `parse` is wrapped by {@link discoverConfig} as
363
+ * `CONFIG_PARSE_ERROR`.
364
+ *
365
+ * @param extensions - File extensions this loader handles (without dot, e.g. `'yaml'`).
366
+ * @param parse - Parse function: takes file content string and returns a parsed config value.
367
+ * @returns A {@link FormatLoader} ready to pass to {@link ConfigDiscoveryOptions.loaders}.
368
+ *
369
+ * @example
370
+ * ```ts
371
+ * import { cli, configFormat } from '@kjanat/dreamcli';
372
+ * import { parse as parseYaml } from 'yaml';
373
+ * import { parse as parseTOML } from '@iarna/toml';
374
+ *
375
+ * const yamlPackageLoader = configFormat(['yaml', 'yml'], parseYaml);
376
+ * const tomlPackageLoader = configFormat(['toml'], parseTOML);
377
+ * // Or with Bun's built-in parsers:
378
+ * // const yamlLoader = configFormat(['yaml', 'yml'], Bun.YAML.parse);
379
+ * // const tomlLoader = configFormat(['toml'], Bun.TOML.parse);
380
+ *
381
+ * cli('myapp')
382
+ * .config('myapp')
383
+ * .configLoader(yamlLoader)
384
+ * .configLoader(tomlLoader)
385
+ * .run();
386
+ * ```
387
+ */
388
+ function configFormat(
389
+ extensions: readonly string[],
390
+ parse: (content: string) => unknown,
391
+ ): FormatLoader {
392
+ return { extensions, parse };
393
+ }
394
+
395
+ // --- Exports
396
+
397
+ export type { PackageJsonAdapter, PackageJsonData } from './package-json.ts';
398
+ export { discoverPackageJson, inferCliName } from './package-json.ts';
399
+ export type {
400
+ ConfigAdapter,
401
+ ConfigDiscoveryOptions,
402
+ ConfigDiscoveryResult,
403
+ ConfigFound,
404
+ ConfigNotFound,
405
+ FormatLoader,
406
+ };
407
+ export { buildConfigSearchPaths, configFormat, discoverConfig };
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Package.json auto-discovery via directory walk-up.
3
+ *
4
+ * Walks up from `adapter.cwd` to find the nearest `package.json`, parses
5
+ * it, and extracts metadata (name, version, description, bin). All I/O
6
+ * flows through the adapter — fully testable with virtual filesystems.
7
+ *
8
+ * @module dreamcli/core/config/package-json
9
+ */
10
+
11
+ import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
12
+
13
+ // --- Narrowing helpers
14
+
15
+ /** Type guard: narrows `unknown` to a plain (non-array) object. */
16
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
17
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
18
+ }
19
+
20
+ // --- Types
21
+
22
+ /**
23
+ * Subset of package.json fields relevant to CLI metadata.
24
+ *
25
+ * All fields are optional — a valid package.json may omit any of them.
26
+ */
27
+ interface PackageJsonData {
28
+ /** Package name (e.g. `@scope/mycli`). */
29
+ readonly name?: string;
30
+ /** Semver version string from `package.json`. */
31
+ readonly version?: string;
32
+ /** One-line package description. */
33
+ readonly description?: string;
34
+ /** Binary entry point(s) — string for single-bin, object for multi-bin. */
35
+ readonly bin?: string | Readonly<Record<string, string>>;
36
+ }
37
+
38
+ /**
39
+ * The subset of {@link RuntimeAdapter} needed for package.json discovery.
40
+ *
41
+ * Using a narrow pick keeps the function easy to test and makes the
42
+ * dependency explicit.
43
+ */
44
+ type PackageJsonAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd'>;
45
+
46
+ // --- Path utilities
47
+
48
+ /**
49
+ * Compute the parent directory of a path using the separator detected
50
+ * from the path itself.
51
+ *
52
+ * Returns `undefined` when the path is already the root (e.g. `/` or `C:\`).
53
+ * Pure string manipulation — no filesystem access.
54
+ *
55
+ * @internal
56
+ */
57
+ function parentDir(path: string): string | undefined {
58
+ // Handle mixed separators (common on Windows) by finding the last of either.
59
+ const fwdIdx = path.lastIndexOf('/');
60
+ const bkIdx = path.lastIndexOf('\\');
61
+ const idx = Math.max(fwdIdx, bkIdx);
62
+ // Derive separator from whichever was found last (for drive root construction).
63
+ const sep = bkIdx > fwdIdx ? '\\' : '/';
64
+ // Already at root (Unix `/` or Windows `C:\`)
65
+ if (idx < 0) return undefined;
66
+ if (idx === 0) return path.length > 1 ? sep : undefined;
67
+ const parent = path.slice(0, idx);
68
+ // Windows drive root: `C:` → `C:\`, but already AT drive root → stop
69
+ if (parent.length === 2 && parent[1] === ':') {
70
+ const driveRoot = `${parent}${sep}`;
71
+ return driveRoot === path ? undefined : driveRoot;
72
+ }
73
+ return parent;
74
+ }
75
+
76
+ /**
77
+ * Join a base path with a filename segment.
78
+ *
79
+ * @internal
80
+ */
81
+ function joinPath(base: string, segment: string): string {
82
+ const sep = base.includes('\\') ? '\\' : '/';
83
+ return base.endsWith(sep) ? `${base}${segment}` : `${base}${sep}${segment}`;
84
+ }
85
+
86
+ // --- discoverPackageJson
87
+
88
+ /**
89
+ * Discover the nearest `package.json` by walking up from `adapter.cwd`.
90
+ *
91
+ * Convenience helper behind `CLIBuilder.packageJson()`. Most apps should let
92
+ * the CLI runtime discover package metadata automatically; call this directly
93
+ * when testing metadata inference or embedding the behavior in custom tooling.
94
+ *
95
+ * Returns the parsed metadata on success, `null` when no `package.json`
96
+ * is found (not an error). Malformed JSON and non-object roots also
97
+ * return `null` — the feature is a convenience, not a hard requirement.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * import { discoverPackageJson } from '@kjanat/dreamcli';
102
+ *
103
+ * const pkg = await discoverPackageJson(adapter);
104
+ * if (pkg !== null) {
105
+ * console.log(pkg.version); // '1.2.3'
106
+ * }
107
+ * ```
108
+ */
109
+ async function discoverPackageJson(adapter: PackageJsonAdapter): Promise<PackageJsonData | null> {
110
+ let dir: string | undefined = adapter.cwd;
111
+
112
+ while (dir !== undefined) {
113
+ let content: string | null = null;
114
+ try {
115
+ content = await adapter.readFile(joinPath(dir, 'package.json'));
116
+ } catch {
117
+ // Adapter may throw on permission errors, is-directory, or other
118
+ // syscall failures — skip this directory and keep walking up.
119
+ }
120
+ if (content !== null) {
121
+ const parsed = parsePackageJson(content);
122
+ if (parsed !== null) {
123
+ return parsed;
124
+ }
125
+ }
126
+ dir = parentDir(dir);
127
+ }
128
+
129
+ return null;
130
+ }
131
+
132
+ // --- parsePackageJson
133
+
134
+ /**
135
+ * Parse a package.json content string into {@link PackageJsonData}.
136
+ *
137
+ * Returns `null` for malformed JSON or non-object roots.
138
+ *
139
+ * @internal
140
+ */
141
+ function parsePackageJson(content: string): PackageJsonData | null {
142
+ try {
143
+ const parsed: unknown = JSON.parse(content);
144
+ if (!isPlainObject(parsed)) {
145
+ return null;
146
+ }
147
+ const name = typeof parsed['name'] === 'string' ? parsed['name'] : undefined;
148
+ const version = typeof parsed['version'] === 'string' ? parsed['version'] : undefined;
149
+ const description =
150
+ typeof parsed['description'] === 'string' ? parsed['description'] : undefined;
151
+ const bin = parseBinField(parsed['bin']);
152
+ return {
153
+ ...(name !== undefined ? { name } : {}),
154
+ ...(version !== undefined ? { version } : {}),
155
+ ...(description !== undefined ? { description } : {}),
156
+ ...(bin !== undefined ? { bin } : {}),
157
+ };
158
+ } catch {
159
+ return null;
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Parse the `bin` field from package.json.
165
+ *
166
+ * Accepts either a string (`"bin": "./dist/cli.js"`) or an object
167
+ * (`"bin": { "mycli": "./dist/cli.js" }`). Returns `undefined` for
168
+ * anything else.
169
+ *
170
+ * @internal
171
+ */
172
+ function parseBinField(value: unknown): string | Readonly<Record<string, string>> | undefined {
173
+ if (typeof value === 'string') return value;
174
+ if (!isPlainObject(value)) return undefined;
175
+ const result: Record<string, string> = {};
176
+ for (const [k, v] of Object.entries(value)) {
177
+ if (typeof v !== 'string') return undefined;
178
+ result[k] = v;
179
+ }
180
+ return result;
181
+ }
182
+
183
+ // --- inferCliName
184
+
185
+ /**
186
+ * Infer the CLI binary name from package.json data.
187
+ *
188
+ * Resolution order:
189
+ * 1. First key of `bin` object (e.g. `{"mycli": "./dist/cli.js"}` → `"mycli"`)
190
+ * 2. Package `name` with scope stripped (e.g. `"@scope/mycli"` → `"mycli"`)
191
+ * 3. `undefined` if neither exists
192
+ *
193
+ * @example
194
+ * ```ts
195
+ * import { inferCliName } from '@kjanat/dreamcli';
196
+ *
197
+ * inferCliName({ bin: { mycli: './dist/cli.js' } }); // 'mycli'
198
+ * inferCliName({ name: '@scope/mycli' }); // 'mycli'
199
+ * inferCliName({ name: 'mycli' }); // 'mycli'
200
+ * inferCliName({}); // undefined
201
+ * ```
202
+ */
203
+ function inferCliName(pkg: PackageJsonData): string | undefined {
204
+ // Prefer bin key name
205
+ if (typeof pkg.bin === 'object') {
206
+ const keys = Object.keys(pkg.bin);
207
+ if (keys.length > 0 && keys[0] !== undefined) return keys[0];
208
+ }
209
+ // Fall back to package name, stripped of scope
210
+ if (pkg.name !== undefined) {
211
+ const slashIdx = pkg.name.indexOf('/');
212
+ return slashIdx >= 0 ? pkg.name.slice(slashIdx + 1) : pkg.name;
213
+ }
214
+ return undefined;
215
+ }
216
+
217
+ // --- Exports
218
+
219
+ export type { PackageJsonAdapter, PackageJsonData };
220
+ export { discoverPackageJson, inferCliName };