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

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 (194) hide show
  1. package/CHANGELOG.md +217 -1
  2. package/dist/core/cli/dispatch.d.mts +6 -5
  3. package/dist/core/cli/dispatch.mjs +205 -1
  4. package/dist/core/cli/help-links.d.mts +0 -1
  5. package/dist/core/cli/help-links.mjs +41 -1
  6. package/dist/core/cli/index.d.mts +81 -8
  7. package/dist/core/cli/index.mjs +945 -1
  8. package/dist/core/cli/planner.d.mts +5 -1
  9. package/dist/core/cli/planner.mjs +300 -1
  10. package/dist/core/cli/plugin.d.mts +1 -1
  11. package/dist/core/cli/plugin.mjs +41 -1
  12. package/dist/core/cli/propagate.d.mts +1 -1
  13. package/dist/core/cli/propagate.mjs +57 -1
  14. package/dist/core/cli/root-help.d.mts +2 -1
  15. package/dist/core/cli/root-help.mjs +226 -4
  16. package/dist/core/cli/root-surface.d.mts +12 -1
  17. package/dist/core/cli/root-surface.mjs +28 -1
  18. package/dist/core/cli/runtime-preflight.d.mts +14 -2
  19. package/dist/core/cli/runtime-preflight.mjs +169 -1
  20. package/dist/core/completion/index.d.mts +0 -1
  21. package/dist/core/completion/index.mjs +90 -1
  22. package/dist/core/completion/shells/bash.d.mts +0 -1
  23. package/dist/core/completion/shells/bash.mjs +308 -3
  24. package/dist/core/completion/shells/fish.d.mts +0 -1
  25. package/dist/core/completion/shells/fish.mjs +162 -2
  26. package/dist/core/completion/shells/powershell.d.mts +0 -1
  27. package/dist/core/completion/shells/powershell.mjs +358 -2
  28. package/dist/core/completion/shells/shared.d.mts +13 -2
  29. package/dist/core/completion/shells/shared.mjs +176 -1
  30. package/dist/core/completion/shells/zsh.d.mts +0 -1
  31. package/dist/core/completion/shells/zsh.mjs +251 -2
  32. package/dist/core/config/index.d.mts +2 -3
  33. package/dist/core/config/index.mjs +246 -1
  34. package/dist/core/config/package-json.d.mts +27 -4
  35. package/dist/core/config/package-json.mjs +386 -3
  36. package/dist/core/errors/index.d.mts +3 -3
  37. package/dist/core/errors/index.mjs +87 -1
  38. package/dist/core/execution/index.d.mts +0 -1
  39. package/dist/core/execution/index.mjs +201 -1
  40. package/dist/core/help/ansi.d.mts +11 -5
  41. package/dist/core/help/ansi.mjs +121 -2
  42. package/dist/core/help/index.d.mts +22 -3
  43. package/dist/core/help/index.mjs +341 -7
  44. package/dist/core/help/theme.d.mts +68 -0
  45. package/dist/core/help/theme.mjs +46 -0
  46. package/dist/core/json-schema/index.d.mts +15 -2
  47. package/dist/core/json-schema/index.mjs +536 -12
  48. package/dist/core/json-schema/meta-descriptions.generated.d.mts +55 -38
  49. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  50. package/dist/core/output/activity.d.mts +0 -1
  51. package/dist/core/output/activity.mjs +452 -1
  52. package/dist/core/output/bind.mjs +56 -1
  53. package/dist/core/output/contracts.d.mts +4 -5
  54. package/dist/core/output/contracts.mjs +57 -1
  55. package/dist/core/output/display-value.mjs +32 -1
  56. package/dist/core/output/index.d.mts +21 -1
  57. package/dist/core/output/index.mjs +442 -2
  58. package/dist/core/output/renderers.d.mts +0 -1
  59. package/dist/core/output/renderers.mjs +46 -1
  60. package/dist/core/output/writer.mjs +12 -1
  61. package/dist/core/parse/index.d.mts +40 -7
  62. package/dist/core/parse/index.mjs +727 -1
  63. package/dist/core/prompt/index.d.mts +1 -1
  64. package/dist/core/prompt/index.mjs +348 -6
  65. package/dist/core/resolve/args.d.mts +1 -1
  66. package/dist/core/resolve/args.mjs +105 -1
  67. package/dist/core/resolve/coerce.d.mts +1 -1
  68. package/dist/core/resolve/coerce.mjs +336 -1
  69. package/dist/core/resolve/config.mjs +19 -1
  70. package/dist/core/resolve/contracts.d.mts +9 -4
  71. package/dist/core/resolve/errors.d.mts +0 -1
  72. package/dist/core/resolve/errors.mjs +140 -2
  73. package/dist/core/resolve/flags.d.mts +7 -2
  74. package/dist/core/resolve/flags.mjs +251 -1
  75. package/dist/core/resolve/index.d.mts +2 -2
  76. package/dist/core/resolve/index.mjs +85 -1
  77. package/dist/core/resolve/property.d.mts +4 -2
  78. package/dist/core/resolve/property.mjs +53 -1
  79. package/dist/core/schema/activity.d.mts +31 -11
  80. package/dist/core/schema/arg.d.mts +3 -4
  81. package/dist/core/schema/arg.mjs +463 -1
  82. package/dist/core/schema/command.d.mts +26 -6
  83. package/dist/core/schema/command.mjs +726 -1
  84. package/dist/core/schema/flag.d.mts +485 -19
  85. package/dist/core/schema/flag.mjs +705 -1
  86. package/dist/core/schema/index.d.mts +4 -2
  87. package/dist/core/schema/middleware.d.mts +4 -3
  88. package/dist/core/schema/middleware.mjs +41 -1
  89. package/dist/core/schema/number-constraints.mjs +60 -1
  90. package/dist/core/schema/prompt.d.mts +6 -3
  91. package/dist/core/schema/run.d.mts +20 -1
  92. package/dist/core/schema/string-constraints.d.mts +97 -0
  93. package/dist/core/schema/string-constraints.mjs +69 -0
  94. package/dist/core/schema/value-parsers.d.mts +78 -0
  95. package/dist/core/schema/value-parsers.mjs +142 -0
  96. package/dist/core/schema-dsl/runtime.mjs +271 -2
  97. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  98. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  99. package/dist/core/testkit/index.d.mts +0 -31
  100. package/dist/core/testkit/index.mjs +83 -1
  101. package/dist/index.d.mts +11 -6
  102. package/dist/index.mjs +22 -1
  103. package/dist/runtime/adapter.d.mts +38 -2
  104. package/dist/runtime/adapter.mjs +87 -1
  105. package/dist/runtime/auto.d.mts +2 -3
  106. package/dist/runtime/auto.mjs +45 -1
  107. package/dist/runtime/deno.d.mts +24 -5
  108. package/dist/runtime/deno.mjs +262 -2
  109. package/dist/runtime/detect.mjs +45 -1
  110. package/dist/runtime/index.d.mts +3 -4
  111. package/dist/runtime/node.d.mts +8 -2
  112. package/dist/runtime/node.mjs +220 -2
  113. package/dist/runtime/paths.mjs +48 -1
  114. package/dist/runtime.d.mts +4 -4
  115. package/dist/runtime.mjs +6 -1
  116. package/dist/strings.mjs +22 -1
  117. package/dist/testkit.d.mts +1 -0
  118. package/dist/testkit.mjs +5 -1
  119. package/dist/version.d.mts +7 -3
  120. package/dist/version.mjs +7 -1
  121. package/dreamcli.schema.json +36 -7
  122. package/package.json +45 -42
  123. package/dist/runtime/bun.d.mts +0 -28
  124. package/dist/runtime/bun.mjs +0 -1
  125. package/src/core/cli/dispatch.ts +0 -355
  126. package/src/core/cli/help-links.ts +0 -82
  127. package/src/core/cli/index.ts +0 -1614
  128. package/src/core/cli/planner.ts +0 -656
  129. package/src/core/cli/plugin.ts +0 -117
  130. package/src/core/cli/propagate.ts +0 -97
  131. package/src/core/cli/root-help.ts +0 -342
  132. package/src/core/cli/root-surface.ts +0 -87
  133. package/src/core/cli/runtime-preflight.ts +0 -456
  134. package/src/core/completion/index.ts +0 -138
  135. package/src/core/completion/shells/bash.ts +0 -459
  136. package/src/core/completion/shells/fish.ts +0 -259
  137. package/src/core/completion/shells/powershell.ts +0 -439
  138. package/src/core/completion/shells/shared.ts +0 -310
  139. package/src/core/completion/shells/zsh.ts +0 -381
  140. package/src/core/config/index.ts +0 -417
  141. package/src/core/config/package-json.ts +0 -560
  142. package/src/core/errors/index.ts +0 -193
  143. package/src/core/execution/index.ts +0 -265
  144. package/src/core/help/ansi.ts +0 -144
  145. package/src/core/help/index.ts +0 -563
  146. package/src/core/json-schema/index.ts +0 -910
  147. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  148. package/src/core/output/activity.ts +0 -575
  149. package/src/core/output/bind.ts +0 -59
  150. package/src/core/output/contracts.ts +0 -194
  151. package/src/core/output/display-value.ts +0 -48
  152. package/src/core/output/index.ts +0 -704
  153. package/src/core/output/renderers.ts +0 -125
  154. package/src/core/output/writer.ts +0 -46
  155. package/src/core/parse/index.ts +0 -742
  156. package/src/core/prompt/index.ts +0 -623
  157. package/src/core/resolve/args.ts +0 -144
  158. package/src/core/resolve/coerce.ts +0 -500
  159. package/src/core/resolve/config.ts +0 -26
  160. package/src/core/resolve/contracts.ts +0 -135
  161. package/src/core/resolve/errors.ts +0 -227
  162. package/src/core/resolve/flags.ts +0 -269
  163. package/src/core/resolve/index.ts +0 -108
  164. package/src/core/resolve/property.ts +0 -99
  165. package/src/core/schema/activity.ts +0 -240
  166. package/src/core/schema/arg.ts +0 -841
  167. package/src/core/schema/command.ts +0 -1500
  168. package/src/core/schema/flag.ts +0 -917
  169. package/src/core/schema/index.ts +0 -96
  170. package/src/core/schema/middleware.ts +0 -171
  171. package/src/core/schema/number-constraints.ts +0 -153
  172. package/src/core/schema/prompt.ts +0 -171
  173. package/src/core/schema/run.ts +0 -198
  174. package/src/core/schema-dsl/index.ts +0 -109
  175. package/src/core/schema-dsl/parse.ts +0 -262
  176. package/src/core/schema-dsl/runtime.ts +0 -609
  177. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  178. package/src/core/testkit/index.ts +0 -147
  179. package/src/index.ts +0 -181
  180. package/src/runtime/adapter.ts +0 -303
  181. package/src/runtime/auto.ts +0 -86
  182. package/src/runtime/bun.ts +0 -48
  183. package/src/runtime/deno.ts +0 -367
  184. package/src/runtime/detect.ts +0 -105
  185. package/src/runtime/index.ts +0 -21
  186. package/src/runtime/node-builtins.d.ts +0 -27
  187. package/src/runtime/node.ts +0 -289
  188. package/src/runtime/paths.ts +0 -64
  189. package/src/runtime/support.ts +0 -77
  190. package/src/runtime.ts +0 -31
  191. package/src/schema.ts +0 -16
  192. package/src/strings.ts +0 -34
  193. package/src/testkit.ts +0 -25
  194. package/src/version.ts +0 -20
@@ -1,3 +1,386 @@
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 { CLIError } from "../errors/index.mjs";
2
+ import { stripTrailing } from "../../strings.mjs";
3
+ //#region src/core/config/package-json.ts
4
+ /**
5
+ * Package.json auto-discovery via directory walk-up.
6
+ *
7
+ * Walks up from `adapter.cwd` to find the nearest `package.json`, parses
8
+ * it, and extracts metadata (name, version, description, bin). All I/O
9
+ * flows through the adapter — fully testable with virtual filesystems.
10
+ *
11
+ * @module dreamcli/core/config/package-json
12
+ */
13
+ /** Type guard: narrows `unknown` to a plain (non-array) object. */
14
+ function isPlainObject(value) {
15
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16
+ }
17
+ /**
18
+ * Compute the parent directory of a path using the separator detected
19
+ * from the path itself.
20
+ *
21
+ * Returns `undefined` when the path is already the root (e.g. `/` or `C:\`).
22
+ * Pure string manipulation — no filesystem access.
23
+ *
24
+ * @internal
25
+ */
26
+ function parentDir(path) {
27
+ const fwdIdx = path.lastIndexOf("/");
28
+ const bkIdx = path.lastIndexOf("\\");
29
+ const idx = Math.max(fwdIdx, bkIdx);
30
+ const sep = bkIdx > fwdIdx ? "\\" : "/";
31
+ if (idx < 0) return void 0;
32
+ if (idx === 0) return path.length > 1 ? sep : void 0;
33
+ const parent = path.slice(0, idx);
34
+ if (parent.length === 2 && parent[1] === ":") {
35
+ const driveRoot = `${parent}${sep}`;
36
+ return driveRoot === path ? void 0 : driveRoot;
37
+ }
38
+ return parent;
39
+ }
40
+ /**
41
+ * Join a base path with a filename segment.
42
+ *
43
+ * @internal
44
+ */
45
+ function joinPath(base, segment) {
46
+ const sep = base.includes("\\") ? "\\" : "/";
47
+ return base.endsWith(sep) ? `${base}${segment}` : `${base}${sep}${segment}`;
48
+ }
49
+ /** Default manifest filenames probed when none are supplied. @internal */
50
+ const DEFAULT_MANIFEST_FILES = ["package.json"];
51
+ /**
52
+ * Whether parsed manifest data carries any CLI-relevant metadata.
53
+ *
54
+ * {@link parsePackageJson} returns an empty object for a config-only manifest
55
+ * (e.g. a `deno.json` holding only `tasks` / `imports` / `compilerOptions`).
56
+ * Treating that empty result as a discovery hit would shadow a sibling
57
+ * `jsr.json` and halt the walk-up, silently dropping real metadata. Discovery
58
+ * therefore only accepts a manifest that actually carries at least one
59
+ * recognised field.
60
+ *
61
+ * @internal
62
+ */
63
+ function manifestHasMetadata(data) {
64
+ 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;
65
+ }
66
+ /**
67
+ * Discover the nearest manifest (`package.json`, `deno.json`, `jsr.json`, …)
68
+ * by walking up from `startDir` (or `adapter.cwd` when omitted).
69
+ *
70
+ * Convenience helper behind `CLIBuilder.manifest()`. Most apps should let the
71
+ * CLI runtime discover metadata automatically; call this directly when testing
72
+ * metadata inference or embedding the behavior in custom tooling.
73
+ *
74
+ * Candidate files are parsed as JSON with a JSONC fallback — `package.json`,
75
+ * `deno.json`, `jsr.json`, and `deno.jsonc` all qualify, including files that
76
+ * carry `//` / block comments or trailing commas (common in `deno.json`). A
77
+ * file that fails both parses is skipped, so discovery keeps probing.
78
+ *
79
+ * Returns the parsed metadata on success, `null` when no manifest is found
80
+ * (not an error). Malformed JSON, non-object roots, and config-only manifests
81
+ * that carry no recognised metadata (e.g. a `deno.json` with only `tasks` /
82
+ * `imports`) are all skipped, so discovery keeps probing the remaining
83
+ * candidate files and parent directories — the feature is a convenience, not a
84
+ * hard requirement.
85
+ *
86
+ * @param adapter - Adapter providing `readFile` + `cwd`.
87
+ * @param options - Optional anchor (`startDir`) and candidate filenames (`files`).
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * import { discoverManifest } from '@kjanat/dreamcli';
92
+ *
93
+ * const meta = await discoverManifest(adapter, { files: ['deno.json', 'jsr.json'] });
94
+ * if (meta !== null) {
95
+ * console.log(meta.version); // '1.2.3'
96
+ * }
97
+ * ```
98
+ */
99
+ async function discoverManifest(adapter, options = {}) {
100
+ const files = options.files ?? DEFAULT_MANIFEST_FILES;
101
+ let dir = options.startDir ?? adapter.cwd;
102
+ while (dir !== void 0) {
103
+ for (const file of files) {
104
+ let content = null;
105
+ try {
106
+ content = await adapter.readFile(joinPath(dir, file));
107
+ } catch {}
108
+ if (content !== null) {
109
+ const parsed = parsePackageJson(content);
110
+ if (parsed !== null && manifestHasMetadata(parsed)) return parsed;
111
+ }
112
+ }
113
+ dir = parentDir(dir);
114
+ }
115
+ return null;
116
+ }
117
+ /**
118
+ * Discover the nearest `package.json` by walking up from `startDir` (or
119
+ * `adapter.cwd` when omitted).
120
+ *
121
+ * @deprecated Use {@link discoverManifest} with `{ files: ['package.json'] }`
122
+ * (the default), which also supports `deno.json` / `jsr.json`.
123
+ *
124
+ * Behavior note (changed by the manifest generalization): a parseable but
125
+ * metadata-less `package.json` — `{}`, or one carrying only non-metadata fields
126
+ * such as `dependencies` / `scripts` / `type` — is no longer treated as a
127
+ * discovery hit. Previously such a file halted the walk-up and resolved to `{}`;
128
+ * now it is skipped and the walk-up CONTINUES to parent directories. In a
129
+ * monorepo this means a metadata-less leaf `package.json` no longer shadows an
130
+ * ancestor manifest, so an ancestor's `version` can surface where the old
131
+ * behavior returned `{}`. Pass pre-loaded `data` (or use {@link discoverManifest}
132
+ * with an explicit `startDir`) when you need to pin discovery to one directory.
133
+ *
134
+ * @param adapter - Adapter providing `readFile` + `cwd`.
135
+ * @param startDir - Optional explicit directory or file path to walk up from.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * import { discoverPackageJson } from '@kjanat/dreamcli';
140
+ *
141
+ * const pkg = await discoverPackageJson(adapter);
142
+ * if (pkg !== null) {
143
+ * console.log(pkg.version); // '1.2.3'
144
+ * }
145
+ * ```
146
+ */
147
+ async function discoverPackageJson(adapter, startDir) {
148
+ return discoverManifest(adapter, startDir !== void 0 ? { startDir } : {});
149
+ }
150
+ /** Whitespace characters JSON treats as insignificant. @internal */
151
+ function isJsonWhitespace(ch) {
152
+ return ch === " " || ch === " " || ch === "\n" || ch === "\r";
153
+ }
154
+ /**
155
+ * Strip JSONC extensions (line/block comments and trailing commas) so the result
156
+ * is plain JSON. String-aware: comment markers and commas inside string literals
157
+ * are preserved verbatim, so a `"https://…"` URL or a `"/* …"` value survives
158
+ * untouched. Runtime-agnostic — no dependencies, plain string scanning.
159
+ *
160
+ * Only invoked as a fallback when strict `JSON.parse` fails, so valid JSON never
161
+ * passes through here.
162
+ *
163
+ * @internal
164
+ */
165
+ function stripJsonc(input) {
166
+ let decommented = "";
167
+ let inString = false;
168
+ let escaped = false;
169
+ for (let i = 0; i < input.length; i += 1) {
170
+ const ch = input[i] ?? "";
171
+ if (inString) {
172
+ decommented += ch;
173
+ if (escaped) escaped = false;
174
+ else if (ch === "\\") escaped = true;
175
+ else if (ch === "\"") inString = false;
176
+ continue;
177
+ }
178
+ if (ch === "\"") {
179
+ inString = true;
180
+ decommented += ch;
181
+ continue;
182
+ }
183
+ if (ch === "/" && input[i + 1] === "/") {
184
+ i += 2;
185
+ while (i < input.length && input[i] !== "\n") i += 1;
186
+ i -= 1;
187
+ continue;
188
+ }
189
+ if (ch === "/" && input[i + 1] === "*") {
190
+ i += 2;
191
+ while (i < input.length && !(input[i] === "*" && input[i + 1] === "/")) i += 1;
192
+ i += 1;
193
+ continue;
194
+ }
195
+ decommented += ch;
196
+ }
197
+ let result = "";
198
+ inString = false;
199
+ escaped = false;
200
+ for (let i = 0; i < decommented.length; i += 1) {
201
+ const ch = decommented[i] ?? "";
202
+ if (inString) {
203
+ result += ch;
204
+ if (escaped) escaped = false;
205
+ else if (ch === "\\") escaped = true;
206
+ else if (ch === "\"") inString = false;
207
+ continue;
208
+ }
209
+ if (ch === "\"") {
210
+ inString = true;
211
+ result += ch;
212
+ continue;
213
+ }
214
+ if (ch === ",") {
215
+ let j = i + 1;
216
+ while (j < decommented.length && isJsonWhitespace(decommented[j] ?? "")) j += 1;
217
+ const next = decommented[j];
218
+ if (next === "}" || next === "]") continue;
219
+ }
220
+ result += ch;
221
+ }
222
+ return result;
223
+ }
224
+ /**
225
+ * Parse a manifest content string into {@link PackageJsonData}.
226
+ *
227
+ * Strict JSON is parsed directly; on failure, a JSONC fallback strips comments
228
+ * and trailing commas (common in `deno.json`) and retries. Returns `null` for
229
+ * content that is neither valid JSON nor JSONC, or whose root is not an object.
230
+ *
231
+ * @internal
232
+ */
233
+ function parsePackageJson(content) {
234
+ let parsed;
235
+ try {
236
+ parsed = JSON.parse(content);
237
+ } catch {
238
+ try {
239
+ parsed = JSON.parse(stripJsonc(content));
240
+ } catch {
241
+ return null;
242
+ }
243
+ }
244
+ try {
245
+ if (!isPlainObject(parsed)) return null;
246
+ const name = typeof parsed["name"] === "string" ? parsed["name"] : void 0;
247
+ const version = typeof parsed["version"] === "string" ? parsed["version"] : void 0;
248
+ const description = typeof parsed["description"] === "string" ? parsed["description"] : void 0;
249
+ const bin = parseBinField(parsed["bin"]);
250
+ const homepage = typeof parsed["homepage"] === "string" ? parsed["homepage"] : void 0;
251
+ const repository = parseRepositoryField(parsed["repository"]);
252
+ return {
253
+ ...name !== void 0 ? { name } : {},
254
+ ...version !== void 0 ? { version } : {},
255
+ ...description !== void 0 ? { description } : {},
256
+ ...bin !== void 0 ? { bin } : {},
257
+ ...homepage !== void 0 ? { homepage } : {},
258
+ ...repository !== void 0 ? { repository } : {}
259
+ };
260
+ } catch {
261
+ return null;
262
+ }
263
+ }
264
+ /**
265
+ * Parse the `bin` field from package.json.
266
+ *
267
+ * Accepts either a string (`"bin": "./dist/cli.js"`) or an object
268
+ * (`"bin": { "mycli": "./dist/cli.js" }`). Returns `undefined` for
269
+ * anything else.
270
+ *
271
+ * @internal
272
+ */
273
+ function parseBinField(value) {
274
+ if (typeof value === "string") return value;
275
+ if (!isPlainObject(value)) return void 0;
276
+ const result = {};
277
+ for (const [k, v] of Object.entries(value)) {
278
+ if (typeof v !== "string") return void 0;
279
+ result[k] = v;
280
+ }
281
+ return result;
282
+ }
283
+ /**
284
+ * Parse the `repository` field from package.json.
285
+ *
286
+ * Accepts either a locator string (`"repository": "github:u/r"`) or an
287
+ * object (`"repository": { "type": "git", "url": "..." }`). Returns
288
+ * `undefined` for anything else.
289
+ *
290
+ * @internal
291
+ */
292
+ function parseRepositoryField(value) {
293
+ if (typeof value === "string") return value;
294
+ if (!isPlainObject(value)) return void 0;
295
+ const type = typeof value["type"] === "string" ? value["type"] : void 0;
296
+ const url = typeof value["url"] === "string" ? value["url"] : void 0;
297
+ const directory = typeof value["directory"] === "string" ? value["directory"] : void 0;
298
+ if (type === void 0 && url === void 0 && directory === void 0) return void 0;
299
+ return {
300
+ ...type !== void 0 ? { type } : {},
301
+ ...url !== void 0 ? { url } : {},
302
+ ...directory !== void 0 ? { directory } : {}
303
+ };
304
+ }
305
+ /** Browsable base URLs for npm repository shorthand prefixes. @internal */
306
+ const SHORTHAND_HOSTS = {
307
+ github: "https://github.com",
308
+ gitlab: "https://gitlab.com",
309
+ bitbucket: "https://bitbucket.org"
310
+ };
311
+ /** Strip a trailing `.git` suffix from a repository path. @internal */
312
+ function stripGitSuffix(path) {
313
+ return path.endsWith(".git") ? path.slice(0, -4) : path;
314
+ }
315
+ function packageRepositoryUrl(pkg, options) {
316
+ const url = resolveRepositoryUrl(pkg);
317
+ if (url === void 0 && options?.require === true) throw new CLIError(pkg.repository === void 0 ? "package.json has no 'repository' field" : `package.json 'repository' is not a recognisable locator: ${JSON.stringify(pkg.repository)}`, {
318
+ code: "INVALID_REPOSITORY",
319
+ suggest: "Set 'repository' to a supported locator (e.g. 'github:user/repo' or 'git+https://github.com/user/repo.git'), or drop { require: true } and handle undefined"
320
+ });
321
+ return url;
322
+ }
323
+ /** Locator normalization behind {@link packageRepositoryUrl}. @internal */
324
+ function resolveRepositoryUrl(pkg) {
325
+ const raw = typeof pkg.repository === "string" ? pkg.repository : pkg.repository?.url;
326
+ if (raw === void 0) return void 0;
327
+ let locator = raw.trim();
328
+ if (locator.length === 0) return void 0;
329
+ const shorthand = /^(github|gitlab|bitbucket):([^/]+\/[^/]+)$/.exec(locator);
330
+ if (shorthand !== null && shorthand[1] !== void 0 && shorthand[2] !== void 0) {
331
+ const host = SHORTHAND_HOSTS[shorthand[1]];
332
+ if (host !== void 0) return `${host}/${stripGitSuffix(shorthand[2])}`;
333
+ }
334
+ if (/^[\w.-]+\/[\w.-]+$/.test(locator)) return `https://github.com/${stripGitSuffix(locator)}`;
335
+ if (locator.startsWith("git+")) locator = locator.slice(4);
336
+ const scp = /^git@([^:/]+):(.+)$/.exec(locator);
337
+ if (scp !== null && scp[1] !== void 0 && scp[2] !== void 0) return `https://${scp[1]}/${stripGitSuffix(stripTrailing(scp[2], [47]))}`;
338
+ if (!/^(?:https?|git|ssh):\/\//.test(locator)) return void 0;
339
+ try {
340
+ const url = new URL(locator);
341
+ const path = stripGitSuffix(stripTrailing(url.pathname, [47]));
342
+ return `https://${url.hostname}${path}`;
343
+ } catch {
344
+ return;
345
+ }
346
+ }
347
+ /**
348
+ * Infer the CLI binary name from manifest data.
349
+ *
350
+ * Resolution order:
351
+ * 1. First key of `bin` object (e.g. `{"mycli": "./dist/cli.js"}` → `"mycli"`)
352
+ * 2. Package `name`, scope stripped by default (e.g. `"@scope/mycli"` → `"mycli"`);
353
+ * pass `{ stripScope: false }` to keep the full scoped name
354
+ * 3. `undefined` if neither exists
355
+ *
356
+ * Note: `bin` keys are never scoped, so `stripScope` only affects the `name`
357
+ * fallback (relevant for `deno.json` / `jsr.json`, which have no `bin` field).
358
+ *
359
+ * @param pkg - Parsed manifest metadata.
360
+ * @param options - `stripScope` (default `true`): strip a leading `@scope/`
361
+ * from the `name` fallback.
362
+ *
363
+ * @example
364
+ * ```ts
365
+ * import { inferCliName } from '@kjanat/dreamcli';
366
+ *
367
+ * inferCliName({ bin: { mycli: './dist/cli.js' } }); // 'mycli'
368
+ * inferCliName({ name: '@scope/mycli' }); // 'mycli'
369
+ * inferCliName({ name: '@scope/mycli' }, { stripScope: false }); // '@scope/mycli'
370
+ * inferCliName({ name: 'mycli' }); // 'mycli'
371
+ * inferCliName({}); // undefined
372
+ * ```
373
+ */
374
+ function inferCliName(pkg, options = {}) {
375
+ if (typeof pkg.bin === "object") {
376
+ const keys = Object.keys(pkg.bin);
377
+ if (keys.length > 0 && keys[0] !== void 0) return keys[0];
378
+ }
379
+ if (pkg.name !== void 0) {
380
+ if (options.stripScope === false) return pkg.name;
381
+ const slashIdx = pkg.name.indexOf("/");
382
+ return slashIdx >= 0 ? pkg.name.slice(slashIdx + 1) : pkg.name;
383
+ }
384
+ }
385
+ //#endregion
386
+ export { discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl };
@@ -9,7 +9,7 @@
9
9
  * @module dreamcli/core/errors
10
10
  */
11
11
  /** Codes emitted during argv parsing. */
12
- type ParseErrorCode = 'UNKNOWN_FLAG' | 'UNKNOWN_COMMAND' | 'MISSING_VALUE' | 'INVALID_VALUE' | 'INVALID_SCHEMA' | 'UNEXPECTED_POSITIONAL';
12
+ type ParseErrorCode = 'UNKNOWN_FLAG' | 'UNKNOWN_COMMAND' | 'MISSING_VALUE' | 'INVALID_VALUE' | 'INVALID_SCHEMA' | 'DUPLICATE_FLAG' | 'UNEXPECTED_POSITIONAL';
13
13
  /** Codes emitted during post-parse validation / resolution. */
14
14
  type ValidationErrorCode = 'REQUIRED_FLAG' | 'REQUIRED_ARG' | 'INVALID_ENUM' | 'TYPE_MISMATCH' | 'CONSTRAINT_VIOLATED';
15
15
  /** Any framework error code (extensible via `string & {}`). */
@@ -87,7 +87,7 @@ interface ParseErrorOptions extends Omit<CLIErrorOptions, 'code' | 'exitCode'> {
87
87
  */
88
88
  declare class ParseError extends CLIError {
89
89
  /** Always `'ParseError'`. @override */
90
- readonly name: 'ParseError';
90
+ readonly name: "ParseError";
91
91
  /** Narrowed to parse-category codes. */
92
92
  readonly code: ParseErrorCode;
93
93
  /** Create a parse error with exit code defaulting to `2`. */
@@ -110,7 +110,7 @@ interface ValidationErrorOptions extends Omit<CLIErrorOptions, 'code' | 'exitCod
110
110
  */
111
111
  declare class ValidationError extends CLIError {
112
112
  /** Always `'ValidationError'`. @override */
113
- readonly name: 'ValidationError';
113
+ readonly name: "ValidationError";
114
114
  /** Narrowed to validation-category codes. */
115
115
  readonly code: ValidationErrorCode;
116
116
  /** Create a validation error with exit code defaulting to `2`. */
@@ -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 };
@@ -2,7 +2,6 @@ import { CapturedOutput } from "../output/index.mjs";
2
2
  import { CLIError } from "../errors/index.mjs";
3
3
  import { RunOptions, RunResult } from "../schema/run.mjs";
4
4
  import { CommandMeta, CommandSchema, Out, RunnableCommand } from "../schema/command.mjs";
5
-
6
5
  //#region src/core/execution/index.d.ts
7
6
  /**
8
7
  * Explicit executor input for a single command invocation.