@mostra/runtime 0.14.0 → 0.15.1
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/dist/bin.js +1 -1
- package/dist/child-protocol-CPXR6pMu.js +13 -0
- package/dist/child-protocol-CPXR6pMu.js.map +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{instance-CFTw3g-c.js → instance-Bw1BxctF.js} +2581 -189
- package/dist/instance-Bw1BxctF.js.map +1 -0
- package/dist/plugins/child/host.d.ts +1 -0
- package/dist/plugins/child/host.js +165 -0
- package/dist/plugins/child/host.js.map +1 -0
- package/dist/reference/cli.md +147 -5
- package/dist/reference/diagnostics.json +234 -0
- package/dist/reference/errors/MOSTRA_LICENSE_ACCEPT_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_LICENSE_MISMATCH.md +23 -0
- package/dist/reference/errors/MOSTRA_LICENSE_UNACCEPTED.md +23 -0
- package/dist/reference/errors/MOSTRA_LICENSE_UNDECLARED.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_ADDRESS_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_CSS_UNIMPORTED.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_FETCH_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_FILE_EXISTS.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_ITEM_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_ITEM_NOT_FOUND.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_NOT_APPLIED.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_OFFLINE.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_TARGET_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_CONFLICT.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_ENTRY_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_EXPORTER_UNKNOWN.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_MANIFEST_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_MANIFEST_WARNING.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_NOT_A_PLUGIN.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_NOT_INSTALLED.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_OPTIONS_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_PLATFORM_UNSUPPORTED.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_SCOPE_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_SHADOWED.md +23 -0
- package/dist/skill/SKILL.md +4 -2
- package/dist/skill/references/mcp.md +2 -2
- package/dist/skill/references/plugins.md +51 -0
- package/package.json +10 -7
- package/src/deps/index.ts +407 -90
- package/src/deps/installer.ts +53 -10
- package/src/deps/lock.ts +74 -2
- package/src/home/settings.ts +3 -0
- package/src/instance/index.ts +57 -0
- package/src/packs/index.ts +7 -0
- package/src/packs/methods.ts +49 -0
- package/src/packs/packs.ts +706 -0
- package/src/packs/read.ts +759 -0
- package/src/platform/index.ts +1 -0
- package/src/platform/shell.ts +14 -0
- package/src/plugins/child/host.ts +231 -0
- package/src/plugins/child-protocol.ts +68 -0
- package/src/plugins/index.ts +7 -0
- package/src/plugins/location.ts +109 -0
- package/src/plugins/methods.ts +269 -0
- package/src/plugins/plugins.ts +1396 -0
- package/src/publish/publisher.ts +71 -3
- package/dist/instance-CFTw3g-c.js.map +0 -1
package/src/platform/index.ts
CHANGED
|
@@ -52,4 +52,5 @@ export {
|
|
|
52
52
|
} from "./helper.ts";
|
|
53
53
|
export { isSameProcess, listProcesses, readProcess } from "./identity.ts";
|
|
54
54
|
export { adoptable, launch, reapRecorded } from "./launch.ts";
|
|
55
|
+
export { shellWord } from "./shell.ts";
|
|
55
56
|
export { installHint, type ToolCommand, toolCommand } from "./tools.ts";
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A value as one word of a command a diagnostic's fix names (`mostra add … --artifact <path>`),
|
|
3
|
+
* for the shell an agent pastes it into: POSIX quoting, or on Windows the double quotes PowerShell
|
|
4
|
+
* and `cmd` both read (a Windows path holds no `"`). A plain word stays as it is: letters, digits
|
|
5
|
+
* and `@%+=:,./-`, a backslash on Windows, and a `~` that doesn't start the word (a short Windows
|
|
6
|
+
* name such as `RUNNER~1`; a leading one would be a POSIX shell's home).
|
|
7
|
+
*/
|
|
8
|
+
import { WINDOWS } from "./directories.ts";
|
|
9
|
+
|
|
10
|
+
/** `value` as one shell word. */
|
|
11
|
+
export function shellWord(value: string): string {
|
|
12
|
+
if (WINDOWS) return /^[\w@%+=:,./\\~-]+$/.test(value) ? value : `"${value}"`;
|
|
13
|
+
return /^(?!~)[\w@%+=:,./~-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
|
|
14
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plugin child's entry (`dist/plugins/child/host.js`, D30): the process that loads a plugin's
|
|
3
|
+
* Node.js modules, so the supervisor never runs plugin code (RT-02). The supervisor starts one per
|
|
4
|
+
* task through the process manager, in the plugin's package directory with the artifact
|
|
5
|
+
* environment, and stops it after the answer. It exits with its supervisor.
|
|
6
|
+
*
|
|
7
|
+
* - `plugin/inspect` loads entries and answers what each exports: the stamp `define*` put on it,
|
|
8
|
+
* and its ID, so the supervisor checks contracts without trusting the manifest alone.
|
|
9
|
+
* - `plugin/export` loads an exporter, checks it is one this runtime serves and that the options
|
|
10
|
+
* fit its schema, then runs it on a version's files and answers the files it returned.
|
|
11
|
+
*/
|
|
12
|
+
import { readdir, readFile, realpath } from "node:fs/promises";
|
|
13
|
+
import { isAbsolute, join, relative, sep } from "node:path";
|
|
14
|
+
import { pathToFileURL } from "node:url";
|
|
15
|
+
import { checkArtifactPath } from "@mostra/protocol";
|
|
16
|
+
import { stampServed } from "@mostra/protocol/plugin";
|
|
17
|
+
import * as z from "zod";
|
|
18
|
+
import { connectToSupervisor } from "../../processes/index.ts";
|
|
19
|
+
import {
|
|
20
|
+
EXPORT_METHOD,
|
|
21
|
+
type ExportRequest,
|
|
22
|
+
type ExportResponse,
|
|
23
|
+
INSPECT_METHOD,
|
|
24
|
+
type InspectedEntry,
|
|
25
|
+
type InspectRequest,
|
|
26
|
+
} from "../child-protocol.ts";
|
|
27
|
+
|
|
28
|
+
/** A module's export, by name (`default` for the default export). */
|
|
29
|
+
async function load(file: string, name: string): Promise<unknown> {
|
|
30
|
+
const module = (await import(pathToFileURL(file).href)) as Record<string, unknown>;
|
|
31
|
+
return module[name];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function inspect(request: InspectRequest): Promise<InspectedEntry[]> {
|
|
35
|
+
const answers: InspectedEntry[] = [];
|
|
36
|
+
for (const entry of request.entries) {
|
|
37
|
+
try {
|
|
38
|
+
const value = await load(entry.file, entry.export);
|
|
39
|
+
if (typeof value !== "object" || value === null) {
|
|
40
|
+
answers.push({
|
|
41
|
+
ok: false,
|
|
42
|
+
error: `exports ${entry.export === "default" ? "no default" : `no ${entry.export}`} definition (found ${value === null ? "null" : typeof value})`,
|
|
43
|
+
});
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const record = value as Record<string, unknown>;
|
|
47
|
+
answers.push({
|
|
48
|
+
ok: true,
|
|
49
|
+
stamp: record["contract"] ?? null,
|
|
50
|
+
...(typeof record["id"] === "string" ? { id: record["id"] } : {}),
|
|
51
|
+
...(Array.isArray(record["path"])
|
|
52
|
+
? { path: (record["path"] as unknown[]).map((word) => String(word)) }
|
|
53
|
+
: {}),
|
|
54
|
+
functions: Object.keys(record).filter((key) => typeof record[key] === "function"),
|
|
55
|
+
});
|
|
56
|
+
} catch (error) {
|
|
57
|
+
answers.push({ ok: false, error: error instanceof Error ? error.message : String(error) });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return answers;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** `inner` is `outer` or inside it (both real paths), judged by whole segments. */
|
|
64
|
+
function isInside(outer: string, inner: string): boolean {
|
|
65
|
+
const from = relative(outer, inner);
|
|
66
|
+
return from === "" || (from !== ".." && !from.startsWith(`..${sep}`) && !isAbsolute(from));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Whether a path inside the version names its server code (case-folded: some systems fold). */
|
|
70
|
+
const isServer = (relativePath: string): boolean =>
|
|
71
|
+
(relativePath.split(/[/\\]/)[0] ?? "").toLowerCase() === "server";
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* A version's files, read-only, as the exporter contract's `FileTree`: every file but its server
|
|
75
|
+
* code. A path is judged after it is normalized and its links resolved, so `./server/x`,
|
|
76
|
+
* `client/../server/x` and `SERVER/x` name server code too.
|
|
77
|
+
*/
|
|
78
|
+
function tree(root: string) {
|
|
79
|
+
const file = async (path: string): Promise<string> => {
|
|
80
|
+
const check = checkArtifactPath(path);
|
|
81
|
+
if (!check.ok) throw new Error(`${path} isn't a file of the version.`);
|
|
82
|
+
if (isServer(check.path)) throw new Error("Server code isn't part of an export's input.");
|
|
83
|
+
const realRoot = await realpath(root);
|
|
84
|
+
const full = await realpath(join(root, ...check.path.split("/")));
|
|
85
|
+
if (!isInside(realRoot, full)) throw new Error(`${path} isn't a file of the version.`);
|
|
86
|
+
if (isServer(relative(realRoot, full))) {
|
|
87
|
+
throw new Error("Server code isn't part of an export's input.");
|
|
88
|
+
}
|
|
89
|
+
return full;
|
|
90
|
+
};
|
|
91
|
+
const walk = async (dir: string, prefix: string): Promise<string[]> => {
|
|
92
|
+
const found: string[] = [];
|
|
93
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
94
|
+
const path = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
|
|
95
|
+
if (prefix === "" && isServer(entry.name)) continue;
|
|
96
|
+
if (entry.isDirectory()) found.push(...(await walk(join(dir, entry.name), path)));
|
|
97
|
+
else if (entry.isFile()) found.push(path);
|
|
98
|
+
}
|
|
99
|
+
return found;
|
|
100
|
+
};
|
|
101
|
+
return {
|
|
102
|
+
list: async () => (await walk(root, "")).sort(),
|
|
103
|
+
read: async (path: string) => new Uint8Array(await readFile(await file(path))),
|
|
104
|
+
readText: async (path: string) => readFile(await file(path), "utf8"),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Why an options schema refuses `options`, in one line. */
|
|
109
|
+
function optionProblems(schema: unknown, options: Readonly<Record<string, unknown>>): string {
|
|
110
|
+
const parsed = z
|
|
111
|
+
.fromJSONSchema(schema as Parameters<typeof z.fromJSONSchema>[0])
|
|
112
|
+
.safeParse(options);
|
|
113
|
+
if (parsed.success) return "";
|
|
114
|
+
return parsed.error.issues
|
|
115
|
+
.slice(0, 10)
|
|
116
|
+
.map((issue) => `${issue.path.length > 0 ? issue.path.join(".") : "options"}: ${issue.message}`)
|
|
117
|
+
.join("; ");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function runExport(request: ExportRequest): Promise<ExportResponse> {
|
|
121
|
+
const value = await load(request.file, request.export);
|
|
122
|
+
const refuse = (
|
|
123
|
+
code:
|
|
124
|
+
| "MOSTRA_PLUGIN_ENTRY_INVALID"
|
|
125
|
+
| "MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED"
|
|
126
|
+
| "MOSTRA_PLUGIN_OPTIONS_INVALID",
|
|
127
|
+
message: string,
|
|
128
|
+
): ExportResponse => ({ refused: { code, message } });
|
|
129
|
+
if (typeof value !== "object" || value === null) {
|
|
130
|
+
return refuse("MOSTRA_PLUGIN_ENTRY_INVALID", "its entry exports no exporter definition");
|
|
131
|
+
}
|
|
132
|
+
const exporter = value as {
|
|
133
|
+
contract?: unknown;
|
|
134
|
+
id?: unknown;
|
|
135
|
+
output?: { layout?: unknown; extension?: unknown };
|
|
136
|
+
options?: unknown;
|
|
137
|
+
export?: unknown;
|
|
138
|
+
};
|
|
139
|
+
const stamp = exporter.contract as { name?: unknown; version?: unknown } | undefined;
|
|
140
|
+
if (stamp?.name !== "exporter" || typeof exporter.export !== "function") {
|
|
141
|
+
return refuse(
|
|
142
|
+
"MOSTRA_PLUGIN_ENTRY_INVALID",
|
|
143
|
+
"its entry exports no stamped exporter definition",
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
if (!stampServed(stamp, "exporter", request.implemented)) {
|
|
147
|
+
return refuse(
|
|
148
|
+
"MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED",
|
|
149
|
+
`it was built with @mostra/contract-exporter ${String(stamp.version)}; this Mostra serves ${request.implemented.join(", ")}`,
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
if (exporter.id !== request.id) {
|
|
153
|
+
return refuse(
|
|
154
|
+
"MOSTRA_PLUGIN_ENTRY_INVALID",
|
|
155
|
+
`its definition is "${String(exporter.id)}", not "${request.id}" as the manifest says`,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
const layout = exporter.output?.layout === "file" ? "file" : "directory";
|
|
159
|
+
const extension =
|
|
160
|
+
typeof exporter.output?.extension === "string" ? exporter.output.extension : undefined;
|
|
161
|
+
if (exporter.options === undefined) {
|
|
162
|
+
if (Object.keys(request.options).length > 0) {
|
|
163
|
+
return refuse(
|
|
164
|
+
"MOSTRA_PLUGIN_OPTIONS_INVALID",
|
|
165
|
+
`it takes no options, and was given ${Object.keys(request.options).join(", ")}`,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
} else {
|
|
169
|
+
let problems: string;
|
|
170
|
+
try {
|
|
171
|
+
problems = optionProblems(exporter.options, request.options);
|
|
172
|
+
} catch (error) {
|
|
173
|
+
return refuse(
|
|
174
|
+
"MOSTRA_PLUGIN_ENTRY_INVALID",
|
|
175
|
+
`its options aren't a JSON Schema Mostra reads (${error instanceof Error ? error.message : String(error)})`,
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
if (problems !== "") return refuse("MOSTRA_PLUGIN_OPTIONS_INVALID", problems);
|
|
179
|
+
}
|
|
180
|
+
const controller = new AbortController();
|
|
181
|
+
const lines: string[] = [];
|
|
182
|
+
const result = (await (
|
|
183
|
+
exporter.export as (
|
|
184
|
+
input: unknown,
|
|
185
|
+
context: unknown,
|
|
186
|
+
) => Promise<{
|
|
187
|
+
files?: readonly { path: unknown; content: unknown }[];
|
|
188
|
+
entry?: unknown;
|
|
189
|
+
findings?: unknown;
|
|
190
|
+
}>
|
|
191
|
+
).call(
|
|
192
|
+
exporter,
|
|
193
|
+
{ version: request.version, files: tree(request.versionDir), options: request.options },
|
|
194
|
+
{
|
|
195
|
+
signal: controller.signal,
|
|
196
|
+
log: (message: string) => {
|
|
197
|
+
if (lines.length < 1000) lines.push(String(message).slice(0, 4000));
|
|
198
|
+
},
|
|
199
|
+
mostraVersion: request.mostraVersion,
|
|
200
|
+
},
|
|
201
|
+
)) as
|
|
202
|
+
| {
|
|
203
|
+
files?: readonly { path: unknown; content: unknown }[];
|
|
204
|
+
entry?: unknown;
|
|
205
|
+
findings?: unknown;
|
|
206
|
+
}
|
|
207
|
+
| undefined;
|
|
208
|
+
const files = (result?.files ?? []).map((file) => {
|
|
209
|
+
if (typeof file.path !== "string") throw new Error("An exported file has no path.");
|
|
210
|
+
if (typeof file.content === "string") return { path: file.path, text: file.content };
|
|
211
|
+
if (file.content instanceof Uint8Array) {
|
|
212
|
+
return { path: file.path, base64: Buffer.from(file.content).toString("base64") };
|
|
213
|
+
}
|
|
214
|
+
throw new Error(`${file.path}'s content is neither text nor bytes.`);
|
|
215
|
+
});
|
|
216
|
+
return {
|
|
217
|
+
files,
|
|
218
|
+
...(typeof result?.entry === "string" ? { entry: result.entry } : {}),
|
|
219
|
+
output: { layout, ...(extension !== undefined ? { extension } : {}) },
|
|
220
|
+
findings: Array.isArray(result?.findings) ? (result.findings as unknown[]) : [],
|
|
221
|
+
log: lines,
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
connectToSupervisor({
|
|
226
|
+
onRequest: async (method, params) => {
|
|
227
|
+
if (method === INSPECT_METHOD) return inspect(params as unknown as InspectRequest);
|
|
228
|
+
if (method === EXPORT_METHOD) return runExport(params as unknown as ExportRequest);
|
|
229
|
+
throw new Error(`The plugin child doesn't serve ${method}.`);
|
|
230
|
+
},
|
|
231
|
+
});
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The messages between the supervisor and the plugin child (`child/host.ts`), over Node IPC.
|
|
3
|
+
* Internal: the child and the supervisor always come from the same runtime.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Loads entries and reports what each exports. */
|
|
7
|
+
export const INSPECT_METHOD = "plugin/inspect";
|
|
8
|
+
|
|
9
|
+
/** Runs an exporter. */
|
|
10
|
+
export const EXPORT_METHOD = "plugin/export";
|
|
11
|
+
|
|
12
|
+
/** `plugin/inspect`'s request. */
|
|
13
|
+
export interface InspectRequest {
|
|
14
|
+
readonly entries: readonly { readonly file: string; readonly export: string }[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** What one entry exports. */
|
|
18
|
+
export type InspectedEntry =
|
|
19
|
+
| {
|
|
20
|
+
readonly ok: true;
|
|
21
|
+
/** The value's `contract` property: the stamp its `define*` put on it, or `null`. */
|
|
22
|
+
readonly stamp: unknown;
|
|
23
|
+
readonly id?: string;
|
|
24
|
+
/** A CLI command's words. */
|
|
25
|
+
readonly path?: readonly string[];
|
|
26
|
+
/** The names of its function-valued properties. */
|
|
27
|
+
readonly functions: readonly string[];
|
|
28
|
+
}
|
|
29
|
+
| { readonly ok: false; readonly error: string };
|
|
30
|
+
|
|
31
|
+
/** `plugin/export`'s request. */
|
|
32
|
+
export interface ExportRequest {
|
|
33
|
+
readonly file: string;
|
|
34
|
+
readonly export: string;
|
|
35
|
+
/** The exporter's ID, as the manifest names it: the loaded definition must say the same. */
|
|
36
|
+
readonly id: string;
|
|
37
|
+
/** The exporter contract's versions this runtime serves: the stamp must be of their line. */
|
|
38
|
+
readonly implemented: readonly string[];
|
|
39
|
+
/** The version's directory in the home: its files are the export's input. */
|
|
40
|
+
readonly versionDir: string;
|
|
41
|
+
readonly version: Readonly<Record<string, unknown>>;
|
|
42
|
+
readonly options: Readonly<Record<string, unknown>>;
|
|
43
|
+
readonly mostraVersion: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** `plugin/export`'s answer: the export, or why the child refused to run it. */
|
|
47
|
+
export type ExportResponse =
|
|
48
|
+
| {
|
|
49
|
+
readonly files: readonly (
|
|
50
|
+
| { readonly path: string; readonly text: string }
|
|
51
|
+
| { readonly path: string; readonly base64: string }
|
|
52
|
+
)[];
|
|
53
|
+
readonly entry?: string;
|
|
54
|
+
/** What the definition says it writes. */
|
|
55
|
+
readonly output: { readonly layout: "file" | "directory"; readonly extension?: string };
|
|
56
|
+
readonly findings: readonly unknown[];
|
|
57
|
+
readonly log: readonly string[];
|
|
58
|
+
}
|
|
59
|
+
| {
|
|
60
|
+
/** Refused before `export` ran: not a definition this runtime serves, or bad options. */
|
|
61
|
+
readonly refused: {
|
|
62
|
+
readonly code:
|
|
63
|
+
| "MOSTRA_PLUGIN_ENTRY_INVALID"
|
|
64
|
+
| "MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED"
|
|
65
|
+
| "MOSTRA_PLUGIN_OPTIONS_INVALID";
|
|
66
|
+
readonly message: string;
|
|
67
|
+
};
|
|
68
|
+
};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a JSON path sits in a JSON text, so a diagnostic about a manifest field points at its line
|
|
3
|
+
* and column in `package.json` (INTERFACES §13's location). A small scanner over the text as it
|
|
4
|
+
* is: it never reformats or reparses it into something else.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** The 1-based line and column of the value at `path` (or of the closest ancestor found). */
|
|
8
|
+
export function jsonLocation(
|
|
9
|
+
text: string,
|
|
10
|
+
path: readonly (string | number)[],
|
|
11
|
+
): { line: number; column: number } {
|
|
12
|
+
let at = 0;
|
|
13
|
+
const skip = (): void => {
|
|
14
|
+
while (at < text.length && /\s/.test(text[at] as string)) at += 1;
|
|
15
|
+
};
|
|
16
|
+
const string = (): string => {
|
|
17
|
+
// At an opening quote: reads to the matching one, honoring escapes.
|
|
18
|
+
let value = "";
|
|
19
|
+
at += 1;
|
|
20
|
+
while (at < text.length && text[at] !== '"') {
|
|
21
|
+
if (text[at] === "\\") {
|
|
22
|
+
value += text.slice(at, at + 2);
|
|
23
|
+
at += 2;
|
|
24
|
+
} else {
|
|
25
|
+
value += text[at];
|
|
26
|
+
at += 1;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
at += 1;
|
|
30
|
+
try {
|
|
31
|
+
return JSON.parse(`"${value}"`) as string;
|
|
32
|
+
} catch {
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
const skipValue = (): void => {
|
|
37
|
+
skip();
|
|
38
|
+
const open = text[at];
|
|
39
|
+
if (open === '"') {
|
|
40
|
+
string();
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (open === "{" || open === "[") {
|
|
44
|
+
let depth = 0;
|
|
45
|
+
while (at < text.length) {
|
|
46
|
+
const char = text[at];
|
|
47
|
+
if (char === '"') {
|
|
48
|
+
string();
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (char === "{" || char === "[") depth += 1;
|
|
52
|
+
if (char === "}" || char === "]") depth -= 1;
|
|
53
|
+
at += 1;
|
|
54
|
+
if (depth === 0) return;
|
|
55
|
+
}
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
while (at < text.length && !/[,}\]\s]/.test(text[at] as string)) at += 1;
|
|
59
|
+
};
|
|
60
|
+
let found = 0;
|
|
61
|
+
skip();
|
|
62
|
+
for (const part of path) {
|
|
63
|
+
skip();
|
|
64
|
+
const open = text[at];
|
|
65
|
+
if (open === "{" && typeof part === "string") {
|
|
66
|
+
at += 1;
|
|
67
|
+
let hit = false;
|
|
68
|
+
for (;;) {
|
|
69
|
+
skip();
|
|
70
|
+
if (text[at] === "}" || at >= text.length) break;
|
|
71
|
+
const keyAt = at;
|
|
72
|
+
const key = string();
|
|
73
|
+
skip();
|
|
74
|
+
at += 1; // the colon
|
|
75
|
+
if (key === part) {
|
|
76
|
+
skip();
|
|
77
|
+
found = keyAt;
|
|
78
|
+
hit = true;
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
skipValue();
|
|
82
|
+
skip();
|
|
83
|
+
if (text[at] === ",") at += 1;
|
|
84
|
+
}
|
|
85
|
+
if (!hit) break;
|
|
86
|
+
} else if (open === "[" && typeof part === "number") {
|
|
87
|
+
at += 1;
|
|
88
|
+
let index = 0;
|
|
89
|
+
let hit = false;
|
|
90
|
+
for (;;) {
|
|
91
|
+
skip();
|
|
92
|
+
if (text[at] === "]" || at >= text.length) break;
|
|
93
|
+
if (index === part) {
|
|
94
|
+
found = at;
|
|
95
|
+
hit = true;
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
skipValue();
|
|
99
|
+
skip();
|
|
100
|
+
if (text[at] === ",") at += 1;
|
|
101
|
+
index += 1;
|
|
102
|
+
}
|
|
103
|
+
if (!hit) break;
|
|
104
|
+
} else break;
|
|
105
|
+
}
|
|
106
|
+
const before = text.slice(0, found);
|
|
107
|
+
const lines = before.split("\n");
|
|
108
|
+
return { line: lines.length, column: (lines.at(-1)?.length ?? 0) + 1 };
|
|
109
|
+
}
|