@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.2

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 (136) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/dist/core/cli/dispatch.mjs +214 -1
  3. package/dist/core/cli/help-links.mjs +41 -1
  4. package/dist/core/cli/index.mjs +901 -1
  5. package/dist/core/cli/planner.mjs +300 -1
  6. package/dist/core/cli/plugin.mjs +41 -1
  7. package/dist/core/cli/propagate.mjs +57 -1
  8. package/dist/core/cli/root-help.mjs +208 -4
  9. package/dist/core/cli/root-surface.mjs +27 -1
  10. package/dist/core/cli/runtime-preflight.mjs +168 -1
  11. package/dist/core/completion/index.mjs +90 -1
  12. package/dist/core/completion/shells/bash.mjs +304 -3
  13. package/dist/core/completion/shells/fish.mjs +159 -2
  14. package/dist/core/completion/shells/powershell.mjs +353 -2
  15. package/dist/core/completion/shells/shared.mjs +154 -1
  16. package/dist/core/completion/shells/zsh.mjs +244 -2
  17. package/dist/core/config/index.mjs +246 -1
  18. package/dist/core/config/package-json.mjs +385 -3
  19. package/dist/core/errors/index.mjs +87 -1
  20. package/dist/core/execution/index.mjs +189 -1
  21. package/dist/core/help/ansi.mjs +122 -2
  22. package/dist/core/help/index.mjs +329 -7
  23. package/dist/core/json-schema/index.mjs +487 -9
  24. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  25. package/dist/core/output/activity.mjs +452 -1
  26. package/dist/core/output/bind.mjs +56 -1
  27. package/dist/core/output/contracts.mjs +57 -1
  28. package/dist/core/output/display-value.mjs +32 -1
  29. package/dist/core/output/index.d.mts +21 -0
  30. package/dist/core/output/index.mjs +442 -2
  31. package/dist/core/output/renderers.mjs +46 -1
  32. package/dist/core/output/writer.mjs +12 -1
  33. package/dist/core/parse/index.mjs +555 -1
  34. package/dist/core/prompt/index.d.mts +0 -1
  35. package/dist/core/prompt/index.mjs +348 -6
  36. package/dist/core/resolve/args.mjs +105 -1
  37. package/dist/core/resolve/coerce.mjs +279 -1
  38. package/dist/core/resolve/config.mjs +19 -1
  39. package/dist/core/resolve/errors.mjs +140 -2
  40. package/dist/core/resolve/flags.mjs +196 -1
  41. package/dist/core/resolve/index.mjs +85 -1
  42. package/dist/core/resolve/property.d.mts +0 -1
  43. package/dist/core/resolve/property.mjs +45 -1
  44. package/dist/core/schema/arg.mjs +463 -1
  45. package/dist/core/schema/command.d.mts +18 -0
  46. package/dist/core/schema/command.mjs +712 -1
  47. package/dist/core/schema/flag.mjs +453 -1
  48. package/dist/core/schema/middleware.mjs +41 -1
  49. package/dist/core/schema/number-constraints.mjs +60 -1
  50. package/dist/core/schema-dsl/runtime.mjs +271 -2
  51. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  52. package/dist/core/testkit/index.mjs +83 -1
  53. package/dist/index.d.mts +2 -1
  54. package/dist/index.mjs +22 -1
  55. package/dist/runtime/adapter.mjs +82 -1
  56. package/dist/runtime/auto.mjs +46 -1
  57. package/dist/runtime/bun.mjs +28 -1
  58. package/dist/runtime/deno.mjs +217 -2
  59. package/dist/runtime/detect.mjs +45 -1
  60. package/dist/runtime/node.mjs +169 -2
  61. package/dist/runtime/paths.mjs +48 -1
  62. package/dist/runtime.mjs +7 -1
  63. package/dist/strings.mjs +22 -1
  64. package/dist/testkit.mjs +5 -1
  65. package/dist/version.mjs +7 -1
  66. package/package.json +17 -26
  67. package/src/core/cli/dispatch.ts +0 -355
  68. package/src/core/cli/help-links.ts +0 -82
  69. package/src/core/cli/index.ts +0 -1614
  70. package/src/core/cli/planner.ts +0 -656
  71. package/src/core/cli/plugin.ts +0 -117
  72. package/src/core/cli/propagate.ts +0 -97
  73. package/src/core/cli/root-help.ts +0 -342
  74. package/src/core/cli/root-surface.ts +0 -87
  75. package/src/core/cli/runtime-preflight.ts +0 -456
  76. package/src/core/completion/index.ts +0 -138
  77. package/src/core/completion/shells/bash.ts +0 -459
  78. package/src/core/completion/shells/fish.ts +0 -259
  79. package/src/core/completion/shells/powershell.ts +0 -439
  80. package/src/core/completion/shells/shared.ts +0 -310
  81. package/src/core/completion/shells/zsh.ts +0 -381
  82. package/src/core/config/index.ts +0 -417
  83. package/src/core/config/package-json.ts +0 -560
  84. package/src/core/errors/index.ts +0 -193
  85. package/src/core/execution/index.ts +0 -265
  86. package/src/core/help/ansi.ts +0 -144
  87. package/src/core/help/index.ts +0 -563
  88. package/src/core/json-schema/index.ts +0 -910
  89. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  90. package/src/core/output/activity.ts +0 -575
  91. package/src/core/output/bind.ts +0 -59
  92. package/src/core/output/contracts.ts +0 -194
  93. package/src/core/output/display-value.ts +0 -48
  94. package/src/core/output/index.ts +0 -704
  95. package/src/core/output/renderers.ts +0 -125
  96. package/src/core/output/writer.ts +0 -46
  97. package/src/core/parse/index.ts +0 -742
  98. package/src/core/prompt/index.ts +0 -623
  99. package/src/core/resolve/args.ts +0 -144
  100. package/src/core/resolve/coerce.ts +0 -500
  101. package/src/core/resolve/config.ts +0 -26
  102. package/src/core/resolve/contracts.ts +0 -135
  103. package/src/core/resolve/errors.ts +0 -227
  104. package/src/core/resolve/flags.ts +0 -269
  105. package/src/core/resolve/index.ts +0 -108
  106. package/src/core/resolve/property.ts +0 -99
  107. package/src/core/schema/activity.ts +0 -240
  108. package/src/core/schema/arg.ts +0 -841
  109. package/src/core/schema/command.ts +0 -1500
  110. package/src/core/schema/flag.ts +0 -917
  111. package/src/core/schema/index.ts +0 -96
  112. package/src/core/schema/middleware.ts +0 -171
  113. package/src/core/schema/number-constraints.ts +0 -153
  114. package/src/core/schema/prompt.ts +0 -171
  115. package/src/core/schema/run.ts +0 -198
  116. package/src/core/schema-dsl/index.ts +0 -109
  117. package/src/core/schema-dsl/parse.ts +0 -262
  118. package/src/core/schema-dsl/runtime.ts +0 -609
  119. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  120. package/src/core/testkit/index.ts +0 -147
  121. package/src/index.ts +0 -181
  122. package/src/runtime/adapter.ts +0 -303
  123. package/src/runtime/auto.ts +0 -86
  124. package/src/runtime/bun.ts +0 -48
  125. package/src/runtime/deno.ts +0 -367
  126. package/src/runtime/detect.ts +0 -105
  127. package/src/runtime/index.ts +0 -21
  128. package/src/runtime/node-builtins.d.ts +0 -27
  129. package/src/runtime/node.ts +0 -289
  130. package/src/runtime/paths.ts +0 -64
  131. package/src/runtime/support.ts +0 -77
  132. package/src/runtime.ts +0 -31
  133. package/src/schema.ts +0 -16
  134. package/src/strings.ts +0 -34
  135. package/src/testkit.ts +0 -25
  136. package/src/version.ts +0 -20
@@ -1,3 +1,385 @@
1
- import{stripTrailing as e}from"../../strings.mjs";function t(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function n(e){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`\\`),r=Math.max(t,n),i=n>t?`\\`:`/`;if(r<0)return;if(r===0)return e.length>1?i:void 0;let a=e.slice(0,r);if(a.length===2&&a[1]===`:`){let t=`${a}${i}`;return t===e?void 0:t}return a}function r(e,t){let n=e.includes(`\\`)?`\\`:`/`;return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}const i=[`package.json`];function a(e){return e.name!==void 0||e.version!==void 0||e.description!==void 0||e.bin!==void 0||e.homepage!==void 0||e.repository!==void 0}async function o(e,t={}){let o=t.files??i,s=t.startDir??e.cwd;for(;s!==void 0;){for(let t of o){let n=null;try{n=await e.readFile(r(s,t))}catch{}if(n!==null){let e=u(n);if(e!==null&&a(e))return e}}s=n(s)}return null}async function s(e,t){return o(e,t===void 0?{}:{startDir:t})}function c(e){return e===` `||e===` `||e===`
2
- `||e===`\r`}function l(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i]??``;if(n){t+=a,r?r=!1:a===`\\`?r=!0:a===`"`&&(n=!1);continue}if(a===`"`){n=!0,t+=a;continue}if(a===`/`&&e[i+1]===`/`){for(i+=2;i<e.length&&e[i]!==`
3
- `;)i+=1;--i;continue}if(a===`/`&&e[i+1]===`*`){for(i+=2;i<e.length&&!(e[i]===`*`&&e[i+1]===`/`);)i+=1;i+=1;continue}t+=a}let i=``;n=!1,r=!1;for(let e=0;e<t.length;e+=1){let a=t[e]??``;if(n){i+=a,r?r=!1:a===`\\`?r=!0:a===`"`&&(n=!1);continue}if(a===`"`){n=!0,i+=a;continue}if(a===`,`){let n=e+1;for(;n<t.length&&c(t[n]??``);)n+=1;let r=t[n];if(r===`}`||r===`]`)continue}i+=a}return i}function u(e){let n;try{n=JSON.parse(e)}catch{try{n=JSON.parse(l(e))}catch{return null}}try{if(!t(n))return null;let e=typeof n.name==`string`?n.name:void 0,r=typeof n.version==`string`?n.version:void 0,i=typeof n.description==`string`?n.description:void 0,a=d(n.bin),o=typeof n.homepage==`string`?n.homepage:void 0,s=f(n.repository);return{...e===void 0?{}:{name:e},...r===void 0?{}:{version:r},...i===void 0?{}:{description:i},...a===void 0?{}:{bin:a},...o===void 0?{}:{homepage:o},...s===void 0?{}:{repository:s}}}catch{return null}}function d(e){if(typeof e==`string`)return e;if(!t(e))return;let n={};for(let[t,r]of Object.entries(e)){if(typeof r!=`string`)return;n[t]=r}return n}function f(e){if(typeof e==`string`)return e;if(!t(e))return;let n=typeof e.type==`string`?e.type:void 0,r=typeof e.url==`string`?e.url:void 0,i=typeof e.directory==`string`?e.directory:void 0;if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{type:n},...r===void 0?{}:{url:r},...i===void 0?{}:{directory:i}}}const p={github:`https://github.com`,gitlab:`https://gitlab.com`,bitbucket:`https://bitbucket.org`};function m(e){return e.endsWith(`.git`)?e.slice(0,-4):e}function h(t){let n=typeof t.repository==`string`?t.repository:t.repository?.url;if(n===void 0)return;let r=n.trim();if(r.length===0)return;let i=/^(github|gitlab|bitbucket):([^/]+\/[^/]+)$/.exec(r);if(i!==null&&i[1]!==void 0&&i[2]!==void 0){let e=p[i[1]];if(e!==void 0)return`${e}/${m(i[2])}`}if(/^[\w.-]+\/[\w.-]+$/.test(r))return`https://github.com/${m(r)}`;r.startsWith(`git+`)&&(r=r.slice(4));let a=/^git@([^:/]+):(.+)$/.exec(r);if(a!==null&&a[1]!==void 0&&a[2]!==void 0)return`https://${a[1]}/${m(e(a[2],[47]))}`;if(/^(?:https?|git|ssh):\/\//.test(r))try{let t=new URL(r),n=m(e(t.pathname,[47]));return`https://${t.hostname}${n}`}catch{return}}function g(e,t={}){if(typeof e.bin==`object`){let t=Object.keys(e.bin);if(t.length>0&&t[0]!==void 0)return t[0]}if(e.name!==void 0){if(t.stripScope===!1)return e.name;let n=e.name.indexOf(`/`);return n>=0?e.name.slice(n+1):e.name}}export{o as discoverManifest,s as discoverPackageJson,g as inferCliName,h as packageRepositoryUrl};
1
+ import { stripTrailing } from "../../strings.mjs";
2
+ //#region src/core/config/package-json.ts
3
+ /** Type guard: narrows `unknown` to a plain (non-array) object. */
4
+ function isPlainObject(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ /**
8
+ * Compute the parent directory of a path using the separator detected
9
+ * from the path itself.
10
+ *
11
+ * Returns `undefined` when the path is already the root (e.g. `/` or `C:\`).
12
+ * Pure string manipulation — no filesystem access.
13
+ *
14
+ * @internal
15
+ */
16
+ function parentDir(path) {
17
+ const fwdIdx = path.lastIndexOf("/");
18
+ const bkIdx = path.lastIndexOf("\\");
19
+ const idx = Math.max(fwdIdx, bkIdx);
20
+ const sep = bkIdx > fwdIdx ? "\\" : "/";
21
+ if (idx < 0) return void 0;
22
+ if (idx === 0) return path.length > 1 ? sep : void 0;
23
+ const parent = path.slice(0, idx);
24
+ if (parent.length === 2 && parent[1] === ":") {
25
+ const driveRoot = `${parent}${sep}`;
26
+ return driveRoot === path ? void 0 : driveRoot;
27
+ }
28
+ return parent;
29
+ }
30
+ /**
31
+ * Join a base path with a filename segment.
32
+ *
33
+ * @internal
34
+ */
35
+ function joinPath(base, segment) {
36
+ const sep = base.includes("\\") ? "\\" : "/";
37
+ return base.endsWith(sep) ? `${base}${segment}` : `${base}${sep}${segment}`;
38
+ }
39
+ /** Default manifest filenames probed when none are supplied. @internal */
40
+ const DEFAULT_MANIFEST_FILES = ["package.json"];
41
+ /**
42
+ * Whether parsed manifest data carries any CLI-relevant metadata.
43
+ *
44
+ * {@link parsePackageJson} returns an empty object for a config-only manifest
45
+ * (e.g. a `deno.json` holding only `tasks` / `imports` / `compilerOptions`).
46
+ * Treating that empty result as a discovery hit would shadow a sibling
47
+ * `jsr.json` and halt the walk-up, silently dropping real metadata. Discovery
48
+ * therefore only accepts a manifest that actually carries at least one
49
+ * recognised field.
50
+ *
51
+ * @internal
52
+ */
53
+ function manifestHasMetadata(data) {
54
+ return data.name !== void 0 || data.version !== void 0 || data.description !== void 0 || data.bin !== void 0 || data.homepage !== void 0 || data.repository !== void 0;
55
+ }
56
+ /**
57
+ * Discover the nearest manifest (`package.json`, `deno.json`, `jsr.json`, …)
58
+ * by walking up from `startDir` (or `adapter.cwd` when omitted).
59
+ *
60
+ * Convenience helper behind `CLIBuilder.manifest()`. Most apps should let the
61
+ * CLI runtime discover metadata automatically; call this directly when testing
62
+ * metadata inference or embedding the behavior in custom tooling.
63
+ *
64
+ * Candidate files are parsed as JSON with a JSONC fallback — `package.json`,
65
+ * `deno.json`, `jsr.json`, and `deno.jsonc` all qualify, including files that
66
+ * carry `//` / block comments or trailing commas (common in `deno.json`). A
67
+ * file that fails both parses is skipped, so discovery keeps probing.
68
+ *
69
+ * Returns the parsed metadata on success, `null` when no manifest is found
70
+ * (not an error). Malformed JSON, non-object roots, and config-only manifests
71
+ * that carry no recognised metadata (e.g. a `deno.json` with only `tasks` /
72
+ * `imports`) are all skipped, so discovery keeps probing the remaining
73
+ * candidate files and parent directories — the feature is a convenience, not a
74
+ * hard requirement.
75
+ *
76
+ * @param adapter - Adapter providing `readFile` + `cwd`.
77
+ * @param options - Optional anchor (`startDir`) and candidate filenames (`files`).
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * import { discoverManifest } from '@kjanat/dreamcli';
82
+ *
83
+ * const meta = await discoverManifest(adapter, { files: ['deno.json', 'jsr.json'] });
84
+ * if (meta !== null) {
85
+ * console.log(meta.version); // '1.2.3'
86
+ * }
87
+ * ```
88
+ */
89
+ async function discoverManifest(adapter, options = {}) {
90
+ const files = options.files ?? DEFAULT_MANIFEST_FILES;
91
+ let dir = options.startDir ?? adapter.cwd;
92
+ while (dir !== void 0) {
93
+ for (const file of files) {
94
+ let content = null;
95
+ try {
96
+ content = await adapter.readFile(joinPath(dir, file));
97
+ } catch {}
98
+ if (content !== null) {
99
+ const parsed = parsePackageJson(content);
100
+ if (parsed !== null && manifestHasMetadata(parsed)) return parsed;
101
+ }
102
+ }
103
+ dir = parentDir(dir);
104
+ }
105
+ return null;
106
+ }
107
+ /**
108
+ * Discover the nearest `package.json` by walking up from `startDir` (or
109
+ * `adapter.cwd` when omitted).
110
+ *
111
+ * @deprecated Use {@link discoverManifest} with `{ files: ['package.json'] }`
112
+ * (the default), which also supports `deno.json` / `jsr.json`.
113
+ *
114
+ * Behavior note (changed by the manifest generalization): a parseable but
115
+ * metadata-less `package.json` — `{}`, or one carrying only non-metadata fields
116
+ * such as `dependencies` / `scripts` / `type` — is no longer treated as a
117
+ * discovery hit. Previously such a file halted the walk-up and resolved to `{}`;
118
+ * now it is skipped and the walk-up CONTINUES to parent directories. In a
119
+ * monorepo this means a metadata-less leaf `package.json` no longer shadows an
120
+ * ancestor manifest, so an ancestor's `version` can surface where the old
121
+ * behavior returned `{}`. Pass pre-loaded `data` (or use {@link discoverManifest}
122
+ * with an explicit `startDir`) when you need to pin discovery to one directory.
123
+ *
124
+ * @param adapter - Adapter providing `readFile` + `cwd`.
125
+ * @param startDir - Optional explicit directory or file path to walk up from.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * import { discoverPackageJson } from '@kjanat/dreamcli';
130
+ *
131
+ * const pkg = await discoverPackageJson(adapter);
132
+ * if (pkg !== null) {
133
+ * console.log(pkg.version); // '1.2.3'
134
+ * }
135
+ * ```
136
+ */
137
+ async function discoverPackageJson(adapter, startDir) {
138
+ return discoverManifest(adapter, startDir !== void 0 ? { startDir } : {});
139
+ }
140
+ /** Whitespace characters JSON treats as insignificant. @internal */
141
+ function isJsonWhitespace(ch) {
142
+ return ch === " " || ch === " " || ch === "\n" || ch === "\r";
143
+ }
144
+ /**
145
+ * Strip JSONC extensions (line/block comments and trailing commas) so the result
146
+ * is plain JSON. String-aware: comment markers and commas inside string literals
147
+ * are preserved verbatim, so a `"https://…"` URL or a `"/* …"` value survives
148
+ * untouched. Runtime-agnostic — no dependencies, plain string scanning.
149
+ *
150
+ * Only invoked as a fallback when strict `JSON.parse` fails, so valid JSON never
151
+ * passes through here.
152
+ *
153
+ * @internal
154
+ */
155
+ function stripJsonc(input) {
156
+ let decommented = "";
157
+ let inString = false;
158
+ let escaped = false;
159
+ for (let i = 0; i < input.length; i += 1) {
160
+ const ch = input[i] ?? "";
161
+ if (inString) {
162
+ decommented += ch;
163
+ if (escaped) escaped = false;
164
+ else if (ch === "\\") escaped = true;
165
+ else if (ch === "\"") inString = false;
166
+ continue;
167
+ }
168
+ if (ch === "\"") {
169
+ inString = true;
170
+ decommented += ch;
171
+ continue;
172
+ }
173
+ if (ch === "/" && input[i + 1] === "/") {
174
+ i += 2;
175
+ while (i < input.length && input[i] !== "\n") i += 1;
176
+ i -= 1;
177
+ continue;
178
+ }
179
+ if (ch === "/" && input[i + 1] === "*") {
180
+ i += 2;
181
+ while (i < input.length && !(input[i] === "*" && input[i + 1] === "/")) i += 1;
182
+ i += 1;
183
+ continue;
184
+ }
185
+ decommented += ch;
186
+ }
187
+ let result = "";
188
+ inString = false;
189
+ escaped = false;
190
+ for (let i = 0; i < decommented.length; i += 1) {
191
+ const ch = decommented[i] ?? "";
192
+ if (inString) {
193
+ result += ch;
194
+ if (escaped) escaped = false;
195
+ else if (ch === "\\") escaped = true;
196
+ else if (ch === "\"") inString = false;
197
+ continue;
198
+ }
199
+ if (ch === "\"") {
200
+ inString = true;
201
+ result += ch;
202
+ continue;
203
+ }
204
+ if (ch === ",") {
205
+ let j = i + 1;
206
+ while (j < decommented.length && isJsonWhitespace(decommented[j] ?? "")) j += 1;
207
+ const next = decommented[j];
208
+ if (next === "}" || next === "]") continue;
209
+ }
210
+ result += ch;
211
+ }
212
+ return result;
213
+ }
214
+ /**
215
+ * Parse a manifest content string into {@link PackageJsonData}.
216
+ *
217
+ * Strict JSON is parsed directly; on failure, a JSONC fallback strips comments
218
+ * and trailing commas (common in `deno.json`) and retries. Returns `null` for
219
+ * content that is neither valid JSON nor JSONC, or whose root is not an object.
220
+ *
221
+ * @internal
222
+ */
223
+ function parsePackageJson(content) {
224
+ let parsed;
225
+ try {
226
+ parsed = JSON.parse(content);
227
+ } catch {
228
+ try {
229
+ parsed = JSON.parse(stripJsonc(content));
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+ try {
235
+ if (!isPlainObject(parsed)) return null;
236
+ const name = typeof parsed["name"] === "string" ? parsed["name"] : void 0;
237
+ const version = typeof parsed["version"] === "string" ? parsed["version"] : void 0;
238
+ const description = typeof parsed["description"] === "string" ? parsed["description"] : void 0;
239
+ const bin = parseBinField(parsed["bin"]);
240
+ const homepage = typeof parsed["homepage"] === "string" ? parsed["homepage"] : void 0;
241
+ const repository = parseRepositoryField(parsed["repository"]);
242
+ return {
243
+ ...name !== void 0 ? { name } : {},
244
+ ...version !== void 0 ? { version } : {},
245
+ ...description !== void 0 ? { description } : {},
246
+ ...bin !== void 0 ? { bin } : {},
247
+ ...homepage !== void 0 ? { homepage } : {},
248
+ ...repository !== void 0 ? { repository } : {}
249
+ };
250
+ } catch {
251
+ return null;
252
+ }
253
+ }
254
+ /**
255
+ * Parse the `bin` field from package.json.
256
+ *
257
+ * Accepts either a string (`"bin": "./dist/cli.js"`) or an object
258
+ * (`"bin": { "mycli": "./dist/cli.js" }`). Returns `undefined` for
259
+ * anything else.
260
+ *
261
+ * @internal
262
+ */
263
+ function parseBinField(value) {
264
+ if (typeof value === "string") return value;
265
+ if (!isPlainObject(value)) return void 0;
266
+ const result = {};
267
+ for (const [k, v] of Object.entries(value)) {
268
+ if (typeof v !== "string") return void 0;
269
+ result[k] = v;
270
+ }
271
+ return result;
272
+ }
273
+ /**
274
+ * Parse the `repository` field from package.json.
275
+ *
276
+ * Accepts either a locator string (`"repository": "github:u/r"`) or an
277
+ * object (`"repository": { "type": "git", "url": "..." }`). Returns
278
+ * `undefined` for anything else.
279
+ *
280
+ * @internal
281
+ */
282
+ function parseRepositoryField(value) {
283
+ if (typeof value === "string") return value;
284
+ if (!isPlainObject(value)) return void 0;
285
+ const type = typeof value["type"] === "string" ? value["type"] : void 0;
286
+ const url = typeof value["url"] === "string" ? value["url"] : void 0;
287
+ const directory = typeof value["directory"] === "string" ? value["directory"] : void 0;
288
+ if (type === void 0 && url === void 0 && directory === void 0) return void 0;
289
+ return {
290
+ ...type !== void 0 ? { type } : {},
291
+ ...url !== void 0 ? { url } : {},
292
+ ...directory !== void 0 ? { directory } : {}
293
+ };
294
+ }
295
+ /** Browsable base URLs for npm repository shorthand prefixes. @internal */
296
+ const SHORTHAND_HOSTS = {
297
+ github: "https://github.com",
298
+ gitlab: "https://gitlab.com",
299
+ bitbucket: "https://bitbucket.org"
300
+ };
301
+ /** Strip a trailing `.git` suffix from a repository path. @internal */
302
+ function stripGitSuffix(path) {
303
+ return path.endsWith(".git") ? path.slice(0, -4) : path;
304
+ }
305
+ /**
306
+ * Resolve a package's `repository` field to a browsable `https://` URL.
307
+ *
308
+ * Handles the locator formats npm accepts:
309
+ * - object form: `{ "type": "git", "url": "git+https://github.com/u/r.git" }`
310
+ * - `https`/`git`/`ssh` URLs (`git+` prefix and `.git` suffix stripped)
311
+ * - scp-style locators: `git@github.com:u/r.git`
312
+ * - shorthands: `github:u/r`, `gitlab:u/r`, `bitbucket:u/r`, and bare `u/r`
313
+ * (GitHub, per npm convention)
314
+ *
315
+ * Returns `undefined` when the field is absent or unrecognised.
316
+ *
317
+ * @example
318
+ * ```ts
319
+ * packageRepositoryUrl({ repository: 'git+https://github.com/u/r.git' });
320
+ * // 'https://github.com/u/r'
321
+ * ```
322
+ */
323
+ function packageRepositoryUrl(pkg) {
324
+ const raw = typeof pkg.repository === "string" ? pkg.repository : pkg.repository?.url;
325
+ if (raw === void 0) return void 0;
326
+ let locator = raw.trim();
327
+ if (locator.length === 0) return void 0;
328
+ const shorthand = /^(github|gitlab|bitbucket):([^/]+\/[^/]+)$/.exec(locator);
329
+ if (shorthand !== null && shorthand[1] !== void 0 && shorthand[2] !== void 0) {
330
+ const host = SHORTHAND_HOSTS[shorthand[1]];
331
+ if (host !== void 0) return `${host}/${stripGitSuffix(shorthand[2])}`;
332
+ }
333
+ if (/^[\w.-]+\/[\w.-]+$/.test(locator)) return `https://github.com/${stripGitSuffix(locator)}`;
334
+ if (locator.startsWith("git+")) locator = locator.slice(4);
335
+ const scp = /^git@([^:/]+):(.+)$/.exec(locator);
336
+ if (scp !== null && scp[1] !== void 0 && scp[2] !== void 0) return `https://${scp[1]}/${stripGitSuffix(stripTrailing(scp[2], [47]))}`;
337
+ if (!/^(?:https?|git|ssh):\/\//.test(locator)) return void 0;
338
+ try {
339
+ const url = new URL(locator);
340
+ const path = stripGitSuffix(stripTrailing(url.pathname, [47]));
341
+ return `https://${url.hostname}${path}`;
342
+ } catch {
343
+ return;
344
+ }
345
+ }
346
+ /**
347
+ * Infer the CLI binary name from manifest data.
348
+ *
349
+ * Resolution order:
350
+ * 1. First key of `bin` object (e.g. `{"mycli": "./dist/cli.js"}` → `"mycli"`)
351
+ * 2. Package `name`, scope stripped by default (e.g. `"@scope/mycli"` → `"mycli"`);
352
+ * pass `{ stripScope: false }` to keep the full scoped name
353
+ * 3. `undefined` if neither exists
354
+ *
355
+ * Note: `bin` keys are never scoped, so `stripScope` only affects the `name`
356
+ * fallback (relevant for `deno.json` / `jsr.json`, which have no `bin` field).
357
+ *
358
+ * @param pkg - Parsed manifest metadata.
359
+ * @param options - `stripScope` (default `true`): strip a leading `@scope/`
360
+ * from the `name` fallback.
361
+ *
362
+ * @example
363
+ * ```ts
364
+ * import { inferCliName } from '@kjanat/dreamcli';
365
+ *
366
+ * inferCliName({ bin: { mycli: './dist/cli.js' } }); // 'mycli'
367
+ * inferCliName({ name: '@scope/mycli' }); // 'mycli'
368
+ * inferCliName({ name: '@scope/mycli' }, { stripScope: false }); // '@scope/mycli'
369
+ * inferCliName({ name: 'mycli' }); // 'mycli'
370
+ * inferCliName({}); // undefined
371
+ * ```
372
+ */
373
+ function inferCliName(pkg, options = {}) {
374
+ if (typeof pkg.bin === "object") {
375
+ const keys = Object.keys(pkg.bin);
376
+ if (keys.length > 0 && keys[0] !== void 0) return keys[0];
377
+ }
378
+ if (pkg.name !== void 0) {
379
+ if (options.stripScope === false) return pkg.name;
380
+ const slashIdx = pkg.name.indexOf("/");
381
+ return slashIdx >= 0 ? pkg.name.slice(slashIdx + 1) : pkg.name;
382
+ }
383
+ }
384
+ //#endregion
385
+ export { discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl };
@@ -1 +1,87 @@
1
- var e=class extends Error{name=`CLIError`;code;exitCode;suggest;details;constructor(e,t){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.code=t.code,this.exitCode=t.exitCode??1,this.suggest=t.suggest,this.details=t.details}toJSON(){return{name:this.name,code:this.code,message:this.message,exitCode:this.exitCode,...this.suggest!==void 0&&{suggest:this.suggest},...this.details!==void 0&&{details:this.details}}}},t=class extends e{name=`ParseError`;constructor(e,t){super(e,{...t,exitCode:t.exitCode??2})}},n=class extends e{name=`ValidationError`;constructor(e,t){super(e,{...t,exitCode:t.exitCode??2})}};function r(t){return t instanceof e}function i(e){return e instanceof t}function a(e){return e instanceof n}export{e as CLIError,t as ParseError,n as ValidationError,r as isCLIError,i as isParseError,a as isValidationError};
1
+ //#region src/core/errors/index.ts
2
+ /**
3
+ * Base structured error for DreamCLI.
4
+ *
5
+ * Every error surfaced by the framework extends this class, ensuring a
6
+ * consistent shape for rendering (TTY pretty-print, `--json`, test assertions).
7
+ */
8
+ var CLIError = class extends Error {
9
+ /** Error class name, always `'CLIError'` for the base class. @override */
10
+ name = "CLIError";
11
+ /** Stable machine-readable identifier. */
12
+ code;
13
+ /** Process exit code (defaults to `1`). */
14
+ exitCode;
15
+ /** One-liner actionable hint. */
16
+ suggest;
17
+ /** Structured payload for machine output. */
18
+ details;
19
+ /** Create a structured CLI error from a human message and machine-readable options. */
20
+ constructor(message, options) {
21
+ super(message, options.cause !== void 0 ? { cause: options.cause } : void 0);
22
+ this.code = options.code;
23
+ this.exitCode = options.exitCode ?? 1;
24
+ this.suggest = options.suggest;
25
+ this.details = options.details;
26
+ }
27
+ /**
28
+ * Serialise to a plain object suitable for JSON output.
29
+ * @sealed
30
+ */
31
+ toJSON() {
32
+ return {
33
+ name: this.name,
34
+ code: this.code,
35
+ message: this.message,
36
+ exitCode: this.exitCode,
37
+ ...this.suggest !== void 0 && { suggest: this.suggest },
38
+ ...this.details !== void 0 && { details: this.details }
39
+ };
40
+ }
41
+ };
42
+ /**
43
+ * Error thrown when argv tokenization / parsing fails.
44
+ *
45
+ * Exit code defaults to `2` (standard for CLI usage errors).
46
+ */
47
+ var ParseError = class extends CLIError {
48
+ /** Always `'ParseError'`. @override */
49
+ name = "ParseError";
50
+ /** Create a parse error with exit code defaulting to `2`. */
51
+ constructor(message, options) {
52
+ super(message, {
53
+ ...options,
54
+ exitCode: options.exitCode ?? 2
55
+ });
56
+ }
57
+ };
58
+ /**
59
+ * Error thrown when resolved values fail validation constraints.
60
+ *
61
+ * Exit code defaults to `2` (standard for CLI usage errors).
62
+ */
63
+ var ValidationError = class extends CLIError {
64
+ /** Always `'ValidationError'`. @override */
65
+ name = "ValidationError";
66
+ /** Create a validation error with exit code defaulting to `2`. */
67
+ constructor(message, options) {
68
+ super(message, {
69
+ ...options,
70
+ exitCode: options.exitCode ?? 2
71
+ });
72
+ }
73
+ };
74
+ /** Narrows an unknown value to `CLIError`. */
75
+ function isCLIError(value) {
76
+ return value instanceof CLIError;
77
+ }
78
+ /** Narrows an unknown value to `ParseError`. */
79
+ function isParseError(value) {
80
+ return value instanceof ParseError;
81
+ }
82
+ /** Narrows an unknown value to `ValidationError`. */
83
+ function isValidationError(value) {
84
+ return value instanceof ValidationError;
85
+ }
86
+ //#endregion
87
+ export { CLIError, ParseError, ValidationError, isCLIError, isParseError, isValidationError };
@@ -1 +1,189 @@
1
- import{CLIError as e}from"../errors/index.mjs";import{formatHelp as t}from"../help/index.mjs";import{clearRequestedExitCode as n,getRequestedExitCode as r}from"../output/index.mjs";import{includesBeforeSeparator as i,parse as a}from"../parse/index.mjs";import{createTestPrompter as o}from"../prompt/index.mjs";import{resolve as s}from"../resolve/index.mjs";async function c(c){let{argv:f,command:m,meta:h,options:g,out:_,schema:v}=c;n(_);try{if(i(f,`--help`)||i(f,`-h`)){let e=t(v,g?.help);return _.log(e),{exitCode:0,error:void 0}}let n=m.handler;if(n===void 0){let t=new e(`Command '${m.schema.name}' has no action handler`,{code:`NO_ACTION`,suggest:`Add an .action() handler to the '${m.schema.name}' command`});return _.error(t.message),{exitCode:1,error:t}}await l(g?.plugins,{argv:f,command:v,meta:h,out:_});let c=a(v,f),y=g?.prompter??(g?.answers===void 0?void 0:o(g.answers)),b=await s(v,c,{...g?.stdinData===void 0?{}:{stdinData:g.stdinData},...g?.env===void 0?{}:{env:g.env},...g?.config===void 0?{}:{config:g.config},...y===void 0?{}:{prompter:y}}),x={args:b.args,flags:b.flags,deprecations:b.deprecations,command:v,meta:h,out:_};await u(g?.plugins,`afterResolve`,x);for(let e of b.deprecations)_.warn(p(e));return await u(g?.plugins,`beforeAction`,x),await d(m,n,b.flags,b.args,_,h),await u(g?.plugins,`afterAction`,x),{exitCode:r(_)??0,error:void 0}}catch(t){if(t instanceof e)return g?.jsonMode===!0?_.json({error:t.toJSON()}):(_.error(t.message),t.suggest!==void 0&&_.error(`Suggestion: ${t.suggest}`)),{exitCode:t.exitCode,error:t};let n=new e(`Unexpected error: ${t instanceof Error?t.message:String(t)}`,{code:`UNEXPECTED_ERROR`,cause:t});return g?.jsonMode===!0?_.json({error:n.toJSON()}):_.error(n.message),{exitCode:1,error:n}}finally{_.stopActive(),n(_)}}async function l(e,t){if(e!==void 0)for(let n of e){let e=n.hooks.beforeParse;e!==void 0&&await e(t)}}async function u(e,t,n){if(e!==void 0)for(let r of e){let e=r.hooks[t];e!==void 0&&await e(n)}}async function d(t,n,r,i,a,o){let s=t._executionSteps,c=async e=>{await n({flags:r,args:i,ctx:e,out:a,meta:o})};for(let t=s.length-1;t>=0;t--){let n=s[t];if(n===void 0)continue;let l=c;switch(n.kind){case`derive`:c=async t=>{let s=await n.handler({args:i,flags:r,ctx:t,out:a,meta:o});if(s===void 0){await l(t);return}if(typeof s!=`object`||!s||Array.isArray(s))throw new e(`derive() must return an object or undefined`,{code:`INVALID_BUILDER_STATE`,suggest:`Return an object to add context, or return nothing for validation-only derive handlers`});await l({...t,...s})};break;case`middleware`:c=async e=>{await n.handler({args:i,flags:r,ctx:e,out:a,meta:o,next:async t=>{await l({...e,...t})}})};break}}await c({})}function f(e,t){return{exitCode:e.exitCode,stdout:t.stdout,stderr:t.stderr,activity:t.activity,error:e.error}}function p(e){let t=e.kind===`flag`?`flag --${e.name}`:`argument <${e.name}>`;return typeof e.message==`string`?`Warning: ${t} is deprecated: ${e.message}`:`Warning: ${t} is deprecated`}export{f as buildRunResult,c as executeCommand};
1
+ import { CLIError } from "../errors/index.mjs";
2
+ import { formatHelp } from "../help/index.mjs";
3
+ import { clearRequestedExitCode, getRequestedExitCode } from "../output/index.mjs";
4
+ import { includesBeforeSeparator, parse } from "../parse/index.mjs";
5
+ import { createTestPrompter } from "../prompt/index.mjs";
6
+ import { resolve } from "../resolve/index.mjs";
7
+ //#region src/core/execution/index.ts
8
+ /**
9
+ * Run the full parse -> resolve -> plugin -> handler pipeline for one command.
10
+ *
11
+ * Handles `--help` short-circuit, plugin lifecycle hooks, deprecation warnings,
12
+ * and error wrapping. Both CLI dispatch and testkit `runCommand` converge here.
13
+ * @internal
14
+ */
15
+ async function executeCommand(request) {
16
+ const { argv, command, meta, options, out, schema } = request;
17
+ clearRequestedExitCode(out);
18
+ try {
19
+ if (includesBeforeSeparator(argv, "--help") || includesBeforeSeparator(argv, "-h")) {
20
+ const helpText = formatHelp(schema, options?.help);
21
+ out.log(helpText);
22
+ return {
23
+ exitCode: 0,
24
+ error: void 0
25
+ };
26
+ }
27
+ const handler = command.handler;
28
+ if (handler === void 0) {
29
+ const error = new CLIError(`Command '${command.schema.name}' has no action handler`, {
30
+ code: "NO_ACTION",
31
+ suggest: `Add an .action() handler to the '${command.schema.name}' command`
32
+ });
33
+ out.error(error.message);
34
+ return {
35
+ exitCode: 1,
36
+ error
37
+ };
38
+ }
39
+ await runBeforeParseHooks(options?.plugins, {
40
+ argv,
41
+ command: schema,
42
+ meta,
43
+ out
44
+ });
45
+ const parsed = parse(schema, argv);
46
+ const effectivePrompter = options?.prompter ?? (options?.answers !== void 0 ? createTestPrompter(options.answers) : void 0);
47
+ const resolved = await resolve(schema, parsed, {
48
+ ...options?.stdinData !== void 0 ? { stdinData: options.stdinData } : {},
49
+ ...options?.env !== void 0 ? { env: options.env } : {},
50
+ ...options?.config !== void 0 ? { config: options.config } : {},
51
+ ...effectivePrompter !== void 0 ? { prompter: effectivePrompter } : {}
52
+ });
53
+ const resolvedParams = {
54
+ args: resolved.args,
55
+ flags: resolved.flags,
56
+ deprecations: resolved.deprecations,
57
+ command: schema,
58
+ meta,
59
+ out
60
+ };
61
+ await runResolvedHooks(options?.plugins, "afterResolve", resolvedParams);
62
+ for (const deprecation of resolved.deprecations) out.warn(formatDeprecation(deprecation));
63
+ await runResolvedHooks(options?.plugins, "beforeAction", resolvedParams);
64
+ await executeWithExecutionSteps(command, handler, resolved.flags, resolved.args, out, meta);
65
+ await runResolvedHooks(options?.plugins, "afterAction", resolvedParams);
66
+ return {
67
+ exitCode: getRequestedExitCode(out) ?? 0,
68
+ error: void 0
69
+ };
70
+ } catch (error) {
71
+ if (error instanceof CLIError) {
72
+ if (options?.jsonMode === true) out.json({ error: error.toJSON() });
73
+ else {
74
+ out.error(error.message);
75
+ if (error.suggest !== void 0) out.error(`Suggestion: ${error.suggest}`);
76
+ }
77
+ return {
78
+ exitCode: error.exitCode,
79
+ error
80
+ };
81
+ }
82
+ const wrapped = new CLIError(`Unexpected error: ${error instanceof Error ? error.message : String(error)}`, {
83
+ code: "UNEXPECTED_ERROR",
84
+ cause: error
85
+ });
86
+ if (options?.jsonMode === true) out.json({ error: wrapped.toJSON() });
87
+ else out.error(wrapped.message);
88
+ return {
89
+ exitCode: 1,
90
+ error: wrapped
91
+ };
92
+ } finally {
93
+ out.stopActive();
94
+ clearRequestedExitCode(out);
95
+ }
96
+ }
97
+ async function runBeforeParseHooks(plugins, params) {
98
+ if (plugins === void 0) return;
99
+ for (const current of plugins) {
100
+ const hook = current.hooks.beforeParse;
101
+ if (hook !== void 0) await hook(params);
102
+ }
103
+ }
104
+ async function runResolvedHooks(plugins, hookName, params) {
105
+ if (plugins === void 0) return;
106
+ for (const current of plugins) {
107
+ const hook = current.hooks[hookName];
108
+ if (hook !== void 0) await hook(params);
109
+ }
110
+ }
111
+ async function executeWithExecutionSteps(command, handler, flags, args, out, meta) {
112
+ const steps = command._executionSteps;
113
+ let chain = async (ctx) => {
114
+ await handler({
115
+ flags,
116
+ args,
117
+ ctx,
118
+ out,
119
+ meta
120
+ });
121
+ };
122
+ for (let i = steps.length - 1; i >= 0; i--) {
123
+ const step = steps[i];
124
+ if (step === void 0) continue;
125
+ const downstream = chain;
126
+ switch (step.kind) {
127
+ case "derive":
128
+ chain = async (ctx) => {
129
+ const additions = await step.handler({
130
+ args,
131
+ flags,
132
+ ctx,
133
+ out,
134
+ meta
135
+ });
136
+ if (additions === void 0) {
137
+ await downstream(ctx);
138
+ return;
139
+ }
140
+ if (typeof additions !== "object" || additions === null || Array.isArray(additions)) throw new CLIError("derive() must return an object or undefined", {
141
+ code: "INVALID_BUILDER_STATE",
142
+ suggest: "Return an object to add context, or return nothing for validation-only derive handlers"
143
+ });
144
+ await downstream({
145
+ ...ctx,
146
+ ...additions
147
+ });
148
+ };
149
+ break;
150
+ case "middleware":
151
+ chain = async (ctx) => {
152
+ await step.handler({
153
+ args,
154
+ flags,
155
+ ctx,
156
+ out,
157
+ meta,
158
+ next: async (additions) => {
159
+ await downstream({
160
+ ...ctx,
161
+ ...additions
162
+ });
163
+ }
164
+ });
165
+ };
166
+ break;
167
+ }
168
+ }
169
+ await chain({});
170
+ }
171
+ /**
172
+ * Assemble a {@linkcode CommandExecutionResult} and captured output buffers into a public `RunResult`.
173
+ * @internal
174
+ */
175
+ function buildRunResult(result, captured) {
176
+ return {
177
+ exitCode: result.exitCode,
178
+ stdout: captured.stdout,
179
+ stderr: captured.stderr,
180
+ activity: captured.activity,
181
+ error: result.error
182
+ };
183
+ }
184
+ function formatDeprecation(deprecation) {
185
+ const entity = deprecation.kind === "flag" ? `flag --${deprecation.name}` : `argument <${deprecation.name}>`;
186
+ return typeof deprecation.message === "string" ? `Warning: ${entity} is deprecated: ${deprecation.message}` : `Warning: ${entity} is deprecated`;
187
+ }
188
+ //#endregion
189
+ export { buildRunResult, executeCommand };