@kjanat/dreamcli 2.5.0 → 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.
- package/CHANGELOG.md +153 -1
- package/README.md +9 -2
- package/dist/core/cli/dispatch.mjs +214 -1
- package/dist/core/cli/help-links.mjs +41 -1
- package/dist/core/cli/index.d.mts +109 -16
- package/dist/core/cli/index.mjs +901 -1
- package/dist/core/cli/planner.d.mts +27 -5
- package/dist/core/cli/planner.mjs +300 -1
- package/dist/core/cli/plugin.mjs +41 -1
- package/dist/core/cli/propagate.mjs +57 -1
- package/dist/core/cli/root-help.d.mts +16 -2
- package/dist/core/cli/root-help.mjs +208 -6
- package/dist/core/cli/root-surface.d.mts +18 -3
- package/dist/core/cli/root-surface.mjs +27 -1
- package/dist/core/cli/runtime-preflight.d.mts +16 -1
- package/dist/core/cli/runtime-preflight.mjs +168 -1
- package/dist/core/completion/index.d.mts +32 -1
- package/dist/core/completion/index.mjs +90 -1
- package/dist/core/completion/shells/bash.mjs +304 -3
- package/dist/core/completion/shells/fish.mjs +159 -2
- package/dist/core/completion/shells/powershell.mjs +353 -2
- package/dist/core/completion/shells/shared.d.mts +10 -0
- package/dist/core/completion/shells/shared.mjs +154 -1
- package/dist/core/completion/shells/zsh.mjs +244 -2
- package/dist/core/config/index.mjs +246 -1
- package/dist/core/config/package-json.mjs +385 -3
- package/dist/core/errors/index.mjs +87 -1
- package/dist/core/execution/index.mjs +189 -1
- package/dist/core/help/ansi.mjs +122 -2
- package/dist/core/help/index.d.mts +45 -1
- package/dist/core/help/index.mjs +329 -7
- package/dist/core/json-schema/index.mjs +487 -9
- package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
- package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
- package/dist/core/output/activity.mjs +452 -1
- package/dist/core/output/bind.mjs +56 -1
- package/dist/core/output/contracts.mjs +57 -1
- package/dist/core/output/display-value.mjs +32 -1
- package/dist/core/output/index.d.mts +21 -0
- package/dist/core/output/index.mjs +442 -2
- package/dist/core/output/renderers.mjs +46 -1
- package/dist/core/output/writer.mjs +12 -1
- package/dist/core/parse/index.d.mts +15 -1
- package/dist/core/parse/index.mjs +555 -1
- package/dist/core/prompt/index.d.mts +11 -4
- package/dist/core/prompt/index.mjs +348 -6
- package/dist/core/resolve/args.mjs +105 -1
- package/dist/core/resolve/coerce.mjs +279 -1
- package/dist/core/resolve/config.mjs +19 -1
- package/dist/core/resolve/errors.mjs +140 -2
- package/dist/core/resolve/flags.mjs +196 -1
- package/dist/core/resolve/index.mjs +85 -1
- package/dist/core/resolve/property.d.mts +2 -1
- package/dist/core/resolve/property.mjs +45 -1
- package/dist/core/schema/arg.d.mts +90 -10
- package/dist/core/schema/arg.mjs +463 -1
- package/dist/core/schema/command.d.mts +21 -1
- package/dist/core/schema/command.mjs +712 -1
- package/dist/core/schema/flag.d.mts +92 -2
- package/dist/core/schema/flag.mjs +453 -1
- package/dist/core/schema/index.d.mts +2 -1
- package/dist/core/schema/middleware.mjs +41 -1
- package/dist/core/schema/number-constraints.d.mts +96 -0
- package/dist/core/schema/number-constraints.mjs +60 -0
- package/dist/core/schema/prompt.d.mts +15 -0
- package/dist/core/schema/run.d.mts +4 -4
- package/dist/core/schema-dsl/runtime.mjs +271 -2
- package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
- package/dist/core/testkit/index.d.mts +9 -5
- package/dist/core/testkit/index.mjs +83 -1
- package/dist/index.d.mts +3 -1
- package/dist/index.mjs +22 -1
- package/dist/runtime/adapter.mjs +82 -1
- package/dist/runtime/auto.mjs +46 -1
- package/dist/runtime/bun.mjs +28 -1
- package/dist/runtime/deno.mjs +217 -2
- package/dist/runtime/detect.mjs +45 -1
- package/dist/runtime/node.mjs +169 -2
- package/dist/runtime/paths.mjs +48 -1
- package/dist/runtime.mjs +7 -1
- package/dist/strings.mjs +22 -1
- package/dist/testkit.mjs +5 -1
- package/dist/version.mjs +7 -1
- package/examples/basic.ts +5 -1
- package/examples/gh/package.json +2 -7
- package/examples/pwsh-demo/package.json +1 -7
- package/examples/pwsh-demo/src/main.test.ts +1 -4
- package/examples/pwsh-demo/src/main.ts +14 -4
- package/examples/transport-launcher.ts +85 -0
- package/package.json +23 -41
- package/dist/runtime/support.d.mts +0 -42
- package/dist/runtime/support.mjs +0 -1
- package/src/core/cli/dispatch.ts +0 -349
- package/src/core/cli/help-links.ts +0 -82
- package/src/core/cli/index.ts +0 -1413
- package/src/core/cli/planner.ts +0 -487
- package/src/core/cli/plugin.ts +0 -117
- package/src/core/cli/propagate.ts +0 -97
- package/src/core/cli/root-help.ts +0 -252
- package/src/core/cli/root-surface.ts +0 -74
- package/src/core/cli/runtime-preflight.ts +0 -438
- package/src/core/completion/index.ts +0 -88
- package/src/core/completion/shells/bash.ts +0 -459
- package/src/core/completion/shells/fish.ts +0 -259
- package/src/core/completion/shells/powershell.ts +0 -439
- package/src/core/completion/shells/shared.ts +0 -283
- package/src/core/completion/shells/zsh.ts +0 -381
- package/src/core/config/index.ts +0 -417
- package/src/core/config/package-json.ts +0 -560
- package/src/core/errors/index.ts +0 -193
- package/src/core/execution/index.ts +0 -268
- package/src/core/help/ansi.ts +0 -144
- package/src/core/help/index.ts +0 -516
- package/src/core/json-schema/index.ts +0 -891
- package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
- package/src/core/output/activity.ts +0 -575
- package/src/core/output/bind.ts +0 -59
- package/src/core/output/contracts.ts +0 -194
- package/src/core/output/display-value.ts +0 -48
- package/src/core/output/index.ts +0 -704
- package/src/core/output/renderers.ts +0 -125
- package/src/core/output/writer.ts +0 -46
- package/src/core/parse/index.ts +0 -681
- package/src/core/prompt/index.ts +0 -583
- package/src/core/resolve/args.ts +0 -144
- package/src/core/resolve/coerce.ts +0 -432
- package/src/core/resolve/config.ts +0 -26
- package/src/core/resolve/contracts.ts +0 -135
- package/src/core/resolve/errors.ts +0 -227
- package/src/core/resolve/flags.ts +0 -255
- package/src/core/resolve/index.ts +0 -108
- package/src/core/resolve/property.ts +0 -99
- package/src/core/schema/activity.ts +0 -240
- package/src/core/schema/arg.ts +0 -719
- package/src/core/schema/command.ts +0 -1498
- package/src/core/schema/flag.ts +0 -801
- package/src/core/schema/index.ts +0 -91
- package/src/core/schema/middleware.ts +0 -171
- package/src/core/schema/prompt.ts +0 -156
- package/src/core/schema/run.ts +0 -198
- package/src/core/schema-dsl/index.ts +0 -109
- package/src/core/schema-dsl/parse.ts +0 -262
- package/src/core/schema-dsl/runtime.ts +0 -609
- package/src/core/schema-dsl/to-json-schema.ts +0 -102
- package/src/core/testkit/index.ts +0 -123
- package/src/index.ts +0 -179
- package/src/runtime/adapter.ts +0 -303
- package/src/runtime/auto.ts +0 -110
- package/src/runtime/bun.ts +0 -55
- package/src/runtime/deno.ts +0 -369
- package/src/runtime/detect.ts +0 -105
- package/src/runtime/index.ts +0 -21
- package/src/runtime/node-builtins.d.ts +0 -27
- package/src/runtime/node.ts +0 -300
- package/src/runtime/paths.ts +0 -64
- package/src/runtime/support.ts +0 -135
- package/src/runtime.ts +0 -31
- package/src/strings.ts +0 -34
- package/src/testkit.ts +0 -25
- package/src/version.ts +0 -20
|
@@ -1,3 +1,385 @@
|
|
|
1
|
-
import{stripTrailing
|
|
2
|
-
|
|
3
|
-
|
|
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
|
-
|
|
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
|
|
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 };
|