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