@powerhousedao/devtools 0.0.0-stage → 6.4.0-next.5
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/LICENSE +661 -0
- package/README.md +116 -2
- package/dist/build-FMqn8eub.mjs +693 -0
- package/dist/build-FMqn8eub.mjs.map +1 -0
- package/dist/client-connect.js +44 -0
- package/dist/client-page.js +4 -0
- package/dist/connect.d.mts +14 -0
- package/dist/connect.d.mts.map +1 -0
- package/dist/connect.mjs +21 -0
- package/dist/connect.mjs.map +1 -0
- package/dist/es-BgJ5sfYg.js +3 -0
- package/dist/input-group-Ce9ByF9k.js +155 -0
- package/dist/mount.d.ts +97 -0
- package/dist/mount.d.ts.map +1 -0
- package/dist/mount.js +264 -0
- package/dist/schema-diagram-CdVGWeZX.js +109 -0
- package/dist/server.d.mts +360 -0
- package/dist/server.d.mts.map +1 -0
- package/dist/server.mjs +25 -0
- package/dist/server.mjs.map +1 -0
- package/dist/vite-INmnb9pz.mjs +604 -0
- package/dist/vite-INmnb9pz.mjs.map +1 -0
- package/package.json +93 -3
|
@@ -0,0 +1,604 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
3
|
+
import { pathWithin, realPathThroughExistingParent } from "@powerhousedao/shared/clis/real-paths";
|
|
4
|
+
import { closeSync, fstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
5
|
+
import { dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
8
|
+
//#region src/paths.ts
|
|
9
|
+
/** The standalone page, below the dev server's base path. */
|
|
10
|
+
const DEVTOOLS_PAGE_PATH = "/__ph/devtools";
|
|
11
|
+
/** The API's routes, below the dev server's base path. */
|
|
12
|
+
const DEVTOOLS_API_PATH = `${DEVTOOLS_PAGE_PATH}/api`;
|
|
13
|
+
/** The `<meta name>` the dev server delivers the token in. */
|
|
14
|
+
const DEVTOOLS_TOKEN_META = "ph-devtools-token";
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region src/api.ts
|
|
17
|
+
const DEVTOOLS_TOKEN_HEADER = "x-ph-devtools-token";
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/server/guards.ts
|
|
20
|
+
const LOOPBACK_HOST = /^(localhost|127\.0\.0\.1|\[::1\])(?::(\d+))?$/;
|
|
21
|
+
function isLoopbackAddress(address) {
|
|
22
|
+
if (!address) return false;
|
|
23
|
+
return (address.startsWith("::ffff:") ? address.slice(7) : address).startsWith("127.") || address === "::1";
|
|
24
|
+
}
|
|
25
|
+
/** Whether the server accepted this request on a loopback address: a client
|
|
26
|
+
* on another machine arrives on one that is not. */
|
|
27
|
+
const onLoopbackSocket = (req) => isLoopbackAddress(req.socket.localAddress);
|
|
28
|
+
/** Headers a proxy or a tunnel adds. One that runs on this machine reaches
|
|
29
|
+
* the server on loopback, for a client that may be anywhere. */
|
|
30
|
+
const FORWARDED_HEADERS = [
|
|
31
|
+
"forwarded",
|
|
32
|
+
"x-forwarded-for",
|
|
33
|
+
"x-forwarded-host",
|
|
34
|
+
"x-real-ip",
|
|
35
|
+
"via"
|
|
36
|
+
];
|
|
37
|
+
/** The name the client asked for. HTTP/2 sends it as `:authority`. */
|
|
38
|
+
function requestedHost(req) {
|
|
39
|
+
const authority = req.headers[":authority"];
|
|
40
|
+
return (typeof authority === "string" ? authority : req.headers.host)?.toLowerCase() ?? "";
|
|
41
|
+
}
|
|
42
|
+
const isEncrypted = (req) => "encrypted" in req.socket && req.socket.encrypted === true;
|
|
43
|
+
/**
|
|
44
|
+
* The host the client asked for, when it names loopback on the port this
|
|
45
|
+
* socket accepted on and nothing forwarded the request. A page on another
|
|
46
|
+
* site whose name resolves to 127.0.0.1 (DNS rebinding) sends that site's
|
|
47
|
+
* name, and a server that also listens beyond loopback (`--host`) accepts a
|
|
48
|
+
* LAN client on a socket whose address is not loopback.
|
|
49
|
+
*/
|
|
50
|
+
function loopbackHost(req) {
|
|
51
|
+
if (!onLoopbackSocket(req)) return void 0;
|
|
52
|
+
if (FORWARDED_HEADERS.some((name) => req.headers[name] !== void 0)) return;
|
|
53
|
+
const host = requestedHost(req);
|
|
54
|
+
const match = LOOPBACK_HOST.exec(host);
|
|
55
|
+
if (!match) return void 0;
|
|
56
|
+
return Number(match.at(2) ?? (isEncrypted(req) ? 443 : 80)) === req.socket.localPort ? host : void 0;
|
|
57
|
+
}
|
|
58
|
+
/** Whether a browser sent this request from the page `host` served: another
|
|
59
|
+
* origin's script, even one on another loopback port, is refused. */
|
|
60
|
+
function sameOrigin(req, host) {
|
|
61
|
+
const origin = req.headers.origin;
|
|
62
|
+
const own = `${isEncrypted(req) ? "https" : "http"}://${host}`;
|
|
63
|
+
if (origin !== void 0 && origin !== own) return false;
|
|
64
|
+
const site = req.headers["sec-fetch-site"];
|
|
65
|
+
return site === void 0 || site === "same-origin" || site === "none";
|
|
66
|
+
}
|
|
67
|
+
function tokenMatches(req, token) {
|
|
68
|
+
const sent = req.headers[DEVTOOLS_TOKEN_HEADER];
|
|
69
|
+
if (typeof sent !== "string") return false;
|
|
70
|
+
const given = Buffer.from(sent);
|
|
71
|
+
return given.length === token.length && timingSafeEqual(given, token);
|
|
72
|
+
}
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region src/server/handler.ts
|
|
75
|
+
const STATUS = {
|
|
76
|
+
bad_host: 403,
|
|
77
|
+
bad_origin: 403,
|
|
78
|
+
bad_token: 401,
|
|
79
|
+
bad_method: 405,
|
|
80
|
+
not_found: 404,
|
|
81
|
+
internal: 500
|
|
82
|
+
};
|
|
83
|
+
function createDevtoolsToken() {
|
|
84
|
+
return randomBytes(32).toString("base64url");
|
|
85
|
+
}
|
|
86
|
+
const etagOf = (revision) => `"${revision}"`;
|
|
87
|
+
function sendJson(res, status, body, revision) {
|
|
88
|
+
res.statusCode = status;
|
|
89
|
+
if (revision !== void 0) res.setHeader("ETag", etagOf(revision));
|
|
90
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
91
|
+
res.setHeader("Cache-Control", "no-store");
|
|
92
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
93
|
+
res.end(JSON.stringify(body));
|
|
94
|
+
}
|
|
95
|
+
function sendError(res, code, message) {
|
|
96
|
+
const body = { error: {
|
|
97
|
+
code,
|
|
98
|
+
message
|
|
99
|
+
} };
|
|
100
|
+
sendJson(res, STATUS[code], body);
|
|
101
|
+
}
|
|
102
|
+
function apiPrefixes(base) {
|
|
103
|
+
const trimmed = (base ?? "/").replace(/\/+$/, "");
|
|
104
|
+
return [.../* @__PURE__ */ new Set([`${trimmed}${DEVTOOLS_API_PATH}`, DEVTOOLS_API_PATH])];
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Serves the DevTools API behind its guards. Every route needs a loopback
|
|
108
|
+
* `Host`, the page's own origin and the page's token. Any other path goes to
|
|
109
|
+
* `next`, the standalone page's included.
|
|
110
|
+
*/
|
|
111
|
+
function createDevtoolsApiHandler(options) {
|
|
112
|
+
const token = Buffer.from(options.token);
|
|
113
|
+
const prefixes = apiPrefixes(options.base);
|
|
114
|
+
/** Routes that name one item by an escaped segment. */
|
|
115
|
+
const ITEM_ROUTES = [["project/document-models/", (reader, name) => reader.documentModel(name)], ["project/files/", (reader, name) => reader.file(name)]];
|
|
116
|
+
const readProject = (reader, path) => {
|
|
117
|
+
if (path === "project") return reader.snapshot();
|
|
118
|
+
if (path === "project/files") return reader.fileList();
|
|
119
|
+
for (const [prefix, read] of ITEM_ROUTES) {
|
|
120
|
+
if (!path.startsWith(prefix)) continue;
|
|
121
|
+
let name;
|
|
122
|
+
try {
|
|
123
|
+
name = decodeURIComponent(path.slice(prefix.length));
|
|
124
|
+
} catch {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
return read(reader, name);
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
const route = async (req, res, path) => {
|
|
131
|
+
const reader = path === "project" || path.startsWith("project/") ? options.project : void 0;
|
|
132
|
+
const notFound = () => sendError(res, "not_found", `No DevTools route "${path}".`);
|
|
133
|
+
if (path !== "info" && !reader) return notFound();
|
|
134
|
+
if (req.method !== "GET") {
|
|
135
|
+
res.setHeader("Allow", "GET");
|
|
136
|
+
return sendError(res, "bad_method", "This route answers GET only.");
|
|
137
|
+
}
|
|
138
|
+
if (!reader) return sendJson(res, 200, await options.info());
|
|
139
|
+
const notModified = (revision) => {
|
|
140
|
+
if (req.headers["if-none-match"] !== etagOf(revision)) return false;
|
|
141
|
+
res.statusCode = 304;
|
|
142
|
+
res.setHeader("ETag", etagOf(revision));
|
|
143
|
+
res.end();
|
|
144
|
+
return true;
|
|
145
|
+
};
|
|
146
|
+
if (path === "project" && notModified(await reader.revision())) return;
|
|
147
|
+
const answer = await readProject(reader, path);
|
|
148
|
+
if (answer === void 0) return notFound();
|
|
149
|
+
if (notModified(answer.revision)) return;
|
|
150
|
+
sendJson(res, 200, answer, answer.revision);
|
|
151
|
+
};
|
|
152
|
+
return (req, res, next) => {
|
|
153
|
+
let pathname;
|
|
154
|
+
try {
|
|
155
|
+
({pathname} = new URL(req.url ?? "/", "http://localhost"));
|
|
156
|
+
} catch {
|
|
157
|
+
return next();
|
|
158
|
+
}
|
|
159
|
+
const prefix = prefixes.find((candidate) => pathname === candidate || pathname.startsWith(`${candidate}/`));
|
|
160
|
+
if (prefix === void 0) return next();
|
|
161
|
+
const host = loopbackHost(req);
|
|
162
|
+
if (!host) return sendError(res, "bad_host", "Host is not loopback.");
|
|
163
|
+
if (!sameOrigin(req, host)) return sendError(res, "bad_origin", "Cross-origin requests are refused.");
|
|
164
|
+
if (!tokenMatches(req, token)) return sendError(res, "bad_token", `Missing or wrong ${DEVTOOLS_TOKEN_HEADER}.`);
|
|
165
|
+
route(req, res, pathname.slice(prefix.length + 1)).catch((error) => {
|
|
166
|
+
if (res.headersSent) return;
|
|
167
|
+
sendError(res, "internal", error instanceof Error ? error.message : String(error));
|
|
168
|
+
});
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
//#endregion
|
|
172
|
+
//#region src/host.ts
|
|
173
|
+
/** The attribute of the token tag that names the dev server's base path. */
|
|
174
|
+
const DEVTOOLS_BASE_ATTRIBUTE = "data-base";
|
|
175
|
+
const attribute = (value) => value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
176
|
+
/** The tag a dev server puts in the `<head>` of the pages it serves. */
|
|
177
|
+
function devtoolsTokenTag(token, base = "/") {
|
|
178
|
+
return `<meta name="${DEVTOOLS_TOKEN_META}" content="${attribute(token)}" ${DEVTOOLS_BASE_ATTRIBUTE}="${attribute(base)}">`;
|
|
179
|
+
}
|
|
180
|
+
//#endregion
|
|
181
|
+
//#region src/server/project/project-fs.ts
|
|
182
|
+
const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set(["node_modules", "dist"]);
|
|
183
|
+
/** Files that hold secrets wherever they are, as Vite's `server.fs.deny`
|
|
184
|
+
* has them: dot-files such as `.env`, and keys and certificates. */
|
|
185
|
+
const holdsSecrets = (name) => name.startsWith(".") || /\.(pem|key|crt|p12|pfx)$/i.test(name);
|
|
186
|
+
/** Whether a real path stays inside the project and passes the same filters
|
|
187
|
+
* as a name in a listing: a symlink's own name says nothing of its target. */
|
|
188
|
+
const shownWithin = (realRoot, real) => {
|
|
189
|
+
const inside = pathWithin(realRoot, real);
|
|
190
|
+
return inside !== null && !inside.split(sep).some((part) => SKIPPED_DIRECTORIES.has(part) || holdsSecrets(part));
|
|
191
|
+
};
|
|
192
|
+
/** Orders by code unit, so a listing does not depend on the machine's locale. */
|
|
193
|
+
const byText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
194
|
+
const byKey = (key) => (left, right) => byText(key(left), key(right));
|
|
195
|
+
/**
|
|
196
|
+
* The files below `dir`, as sorted POSIX paths relative to `root`. Skips
|
|
197
|
+
* `node_modules`, `dist`, dot-directories, dot-files, keys and certificates.
|
|
198
|
+
* A symlink is followed, as the
|
|
199
|
+
* model loader and ts-morph follow it, while its real path stays inside the
|
|
200
|
+
* project and skips none of these; each real directory is entered through a
|
|
201
|
+
* link once. A missing or
|
|
202
|
+
* unreadable directory has none.
|
|
203
|
+
*/
|
|
204
|
+
function listFiles(root, dir) {
|
|
205
|
+
const files = [];
|
|
206
|
+
let realRoot;
|
|
207
|
+
const linked = /* @__PURE__ */ new Set();
|
|
208
|
+
/** What a symlink inside the project points at, or undefined to skip it. */
|
|
209
|
+
const followed = (path) => {
|
|
210
|
+
try {
|
|
211
|
+
realRoot ??= realpathSync.native(root);
|
|
212
|
+
const real = realpathSync.native(join(root, path));
|
|
213
|
+
if (!shownWithin(realRoot, real)) return void 0;
|
|
214
|
+
const stats = statSync(real);
|
|
215
|
+
if (stats.isFile()) return "file";
|
|
216
|
+
if (!stats.isDirectory() || linked.has(real)) return void 0;
|
|
217
|
+
linked.add(real);
|
|
218
|
+
return "directory";
|
|
219
|
+
} catch {
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
const visit = (relativeDir) => {
|
|
224
|
+
let entries;
|
|
225
|
+
try {
|
|
226
|
+
entries = readdirSync(join(root, relativeDir), { withFileTypes: true });
|
|
227
|
+
} catch {
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
for (const entry of entries.sort(byKey(({ name }) => name))) {
|
|
231
|
+
const path = relativeDir === "" ? entry.name : `${relativeDir}/${entry.name}`;
|
|
232
|
+
const skipped = SKIPPED_DIRECTORIES.has(entry.name) || entry.name.startsWith(".");
|
|
233
|
+
const kind = entry.isFile() ? "file" : entry.isDirectory() ? "directory" : entry.isSymbolicLink() && !SKIPPED_DIRECTORIES.has(entry.name) ? followed(path) : void 0;
|
|
234
|
+
if (kind === "file") {
|
|
235
|
+
if (!holdsSecrets(entry.name)) files.push(path);
|
|
236
|
+
} else if (kind === "directory" && !skipped) visit(path);
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
visit(dir);
|
|
240
|
+
return files;
|
|
241
|
+
}
|
|
242
|
+
/** The file's text, or undefined when it is missing or unreadable. */
|
|
243
|
+
function readText(root, path) {
|
|
244
|
+
try {
|
|
245
|
+
return readFileSync(join(root, path), "utf8");
|
|
246
|
+
} catch {
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/** Where a cut at `end` leaves `bytes` whole: before a character whose
|
|
251
|
+
* bytes would run past it. */
|
|
252
|
+
function utf8Boundary(bytes, end) {
|
|
253
|
+
let start = end - 1;
|
|
254
|
+
while (start > end - 4 && start > 0 && (bytes[start] & 192) === 128) start -= 1;
|
|
255
|
+
const lead = bytes[start];
|
|
256
|
+
return start + (lead >= 240 ? 4 : lead >= 224 ? 3 : lead >= 192 ? 2 : 1) > end ? start : end;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Up to `limit` bytes of a regular file as text, cut where a character
|
|
260
|
+
* starts. Undefined when the file is missing, unreadable, not a file, or its
|
|
261
|
+
* real path leaves the project.
|
|
262
|
+
*/
|
|
263
|
+
function readTextWithin(root, path, limit) {
|
|
264
|
+
let descriptor;
|
|
265
|
+
try {
|
|
266
|
+
const real = realpathSync.native(join(root, path));
|
|
267
|
+
if (!shownWithin(realpathSync.native(root), real)) return void 0;
|
|
268
|
+
descriptor = openSync(real, "r");
|
|
269
|
+
if (!fstatSync(descriptor).isFile()) return void 0;
|
|
270
|
+
const buffer = Buffer.alloc(limit + 1);
|
|
271
|
+
const read = readSync(descriptor, buffer, 0, buffer.length, 0);
|
|
272
|
+
const truncated = read > limit;
|
|
273
|
+
const end = truncated ? utf8Boundary(buffer, limit) : read;
|
|
274
|
+
return {
|
|
275
|
+
text: buffer.toString("utf8", 0, end),
|
|
276
|
+
truncated
|
|
277
|
+
};
|
|
278
|
+
} catch {
|
|
279
|
+
return;
|
|
280
|
+
} finally {
|
|
281
|
+
if (descriptor !== void 0) closeSync(descriptor);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/** What a thrown value says, with the project's own path written as `.`. */
|
|
285
|
+
function projectRelativeMessage(root, error) {
|
|
286
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
287
|
+
return [
|
|
288
|
+
pathToFileURL(root).href,
|
|
289
|
+
root,
|
|
290
|
+
root.replaceAll("\\", "/")
|
|
291
|
+
].reduce((text, absolute) => text.replaceAll(absolute, "."), message);
|
|
292
|
+
}
|
|
293
|
+
//#endregion
|
|
294
|
+
//#region src/server/project/revision.ts
|
|
295
|
+
const MANIFEST_FILE = "powerhouse.manifest.json";
|
|
296
|
+
const CONFIG_FILE = "powerhouse.config.json";
|
|
297
|
+
const EDITORS_DIR = "editors";
|
|
298
|
+
const SUBGRAPHS_DIR = "subgraphs";
|
|
299
|
+
const PROCESSORS_DIR = "processors";
|
|
300
|
+
const DEFAULT_DOCUMENT_MODELS_DIR = "document-models";
|
|
301
|
+
/** `scalars/index.ts` is an input of every stored model, wherever the models are. */
|
|
302
|
+
const SCALARS_DIR = "scalars";
|
|
303
|
+
/**
|
|
304
|
+
* The config's `documentModelsDir` as a POSIX path relative to the project.
|
|
305
|
+
* It mirrors the loader's `resolveDocumentModelsDir` (document-model's
|
|
306
|
+
* `tooling/model-directories.ts`), which this module cannot import without
|
|
307
|
+
* loading the definition tooling into every dev server. Where the loader
|
|
308
|
+
* refuses the directory the models are not read at all, so the default is
|
|
309
|
+
* answered.
|
|
310
|
+
*/
|
|
311
|
+
function documentModelsDirOf(root) {
|
|
312
|
+
try {
|
|
313
|
+
const { documentModelsDir } = JSON.parse(readText(root, "powerhouse.config.json") ?? "{}");
|
|
314
|
+
if (typeof documentModelsDir !== "string" || documentModelsDir.trim() === "") return DEFAULT_DOCUMENT_MODELS_DIR;
|
|
315
|
+
const path = resolve(root, documentModelsDir);
|
|
316
|
+
const inside = pathWithin(root, path);
|
|
317
|
+
const real = pathWithin(realpathSync.native(root), realPathThroughExistingParent(path));
|
|
318
|
+
return inside === null || inside === "" || real === null ? DEFAULT_DOCUMENT_MODELS_DIR : inside.split(sep).join("/");
|
|
319
|
+
} catch {
|
|
320
|
+
return DEFAULT_DOCUMENT_MODELS_DIR;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
/** Hashes each path with its modification time and size, without reading it. */
|
|
324
|
+
function fingerprint(root, paths) {
|
|
325
|
+
const hash = createHash("sha256");
|
|
326
|
+
for (const path of paths) {
|
|
327
|
+
const stats = statSync(isAbsolute(path) ? path : join(root, path), { throwIfNoEntry: false });
|
|
328
|
+
hash.update(stats === void 0 ? `${path}\0missing\n` : `${path}\0${stats.mtimeMs}\0${stats.size}\n`);
|
|
329
|
+
}
|
|
330
|
+
return hash.digest("hex");
|
|
331
|
+
}
|
|
332
|
+
/** The files of the models directory and of the project's scalars, relative to the project. */
|
|
333
|
+
function modelsFiles(root) {
|
|
334
|
+
return [...listFiles(root, documentModelsDirOf(root)), ...listFiles(root, SCALARS_DIR)];
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* What a read of the document models depends on: the models directory, the
|
|
338
|
+
* project's scalars, the config, and `imported`, the absolute files the
|
|
339
|
+
* last read's code-first sources evaluated, which can be anywhere.
|
|
340
|
+
*/
|
|
341
|
+
function modelsFingerprint(root, imported) {
|
|
342
|
+
return fingerprint(root, [
|
|
343
|
+
...modelsFiles(root),
|
|
344
|
+
CONFIG_FILE,
|
|
345
|
+
...imported
|
|
346
|
+
]);
|
|
347
|
+
}
|
|
348
|
+
/** What the other sections depend on. `tsconfig.json` is here because they
|
|
349
|
+
* cannot be read without it. */
|
|
350
|
+
function modulesFingerprint(root) {
|
|
351
|
+
return fingerprint(root, [
|
|
352
|
+
...[
|
|
353
|
+
EDITORS_DIR,
|
|
354
|
+
SUBGRAPHS_DIR,
|
|
355
|
+
PROCESSORS_DIR
|
|
356
|
+
].flatMap((dir) => listFiles(root, dir)),
|
|
357
|
+
MANIFEST_FILE,
|
|
358
|
+
"tsconfig.json"
|
|
359
|
+
]);
|
|
360
|
+
}
|
|
361
|
+
/** One short token for the response's `ETag`. */
|
|
362
|
+
function revisionOf(...parts) {
|
|
363
|
+
return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 16);
|
|
364
|
+
}
|
|
365
|
+
//#endregion
|
|
366
|
+
//#region src/server/project/reader.ts
|
|
367
|
+
function realPathOr(path) {
|
|
368
|
+
try {
|
|
369
|
+
return realpathSync.native(path);
|
|
370
|
+
} catch {
|
|
371
|
+
return path;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
function withTimeout(work, ms, onTimeout) {
|
|
375
|
+
return new Promise((resolvePromise, reject) => {
|
|
376
|
+
const timer = setTimeout(() => reject(onTimeout()), ms);
|
|
377
|
+
timer.unref();
|
|
378
|
+
work.then(resolvePromise, reject).finally(() => clearTimeout(timer));
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Reads what a project's code contains. It never writes to the
|
|
383
|
+
* project and watches nothing: a request fingerprints the files again.
|
|
384
|
+
*
|
|
385
|
+
* - Requests for one revision share one read, including those that arrive
|
|
386
|
+
* while it runs. Reads never overlap: a newer revision waits for the read
|
|
387
|
+
* in flight, then is read once.
|
|
388
|
+
* - A read that takes longer than the limit is stopped and fails. A module
|
|
389
|
+
* it was evaluating may run on: the same files are not read again until
|
|
390
|
+
* that module ends.
|
|
391
|
+
* - A read that failed or is not settled (a section failed, or a model's
|
|
392
|
+
* source did not import) can depend on files outside the fingerprint, so
|
|
393
|
+
* it gets a new revision and is read again after `retryAfterMs`.
|
|
394
|
+
*/
|
|
395
|
+
function createProjectReader(projectDir, { buildTimeoutMs = 3e4, revisionTtlMs = 300, retryAfterMs = 5e3, now = Date.now } = {}) {
|
|
396
|
+
const root = resolve(projectDir);
|
|
397
|
+
/** The files outside the module folders that the last read's models evaluated. */
|
|
398
|
+
let imported = [];
|
|
399
|
+
/** Counts the retries of unsettled reads, so each one has its own revision. */
|
|
400
|
+
let retries = 0;
|
|
401
|
+
/** Counts those whose models were not settled: only they load the models
|
|
402
|
+
* again. A retry for a failed section alone keeps the models it has. */
|
|
403
|
+
let modelRetries = 0;
|
|
404
|
+
let stamped;
|
|
405
|
+
let current;
|
|
406
|
+
let inFlight;
|
|
407
|
+
let builder;
|
|
408
|
+
const stamp = () => {
|
|
409
|
+
const at = now();
|
|
410
|
+
if (stamped !== void 0 && at - stamped.at < revisionTtlMs) return stamped.stamp;
|
|
411
|
+
if (current?.unsettledAt !== void 0 && at - current.unsettledAt >= retryAfterMs) {
|
|
412
|
+
if (current.modelsUnsettled) modelRetries += 1;
|
|
413
|
+
current = void 0;
|
|
414
|
+
retries += 1;
|
|
415
|
+
}
|
|
416
|
+
const modelsKey = revisionOf(modelsFingerprint(root, imported), modelRetries);
|
|
417
|
+
stamped = {
|
|
418
|
+
at,
|
|
419
|
+
stamp: {
|
|
420
|
+
revision: revisionOf(modelsKey, modulesFingerprint(root), retries),
|
|
421
|
+
modelsKey
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
return stamped.stamp;
|
|
425
|
+
};
|
|
426
|
+
/**
|
|
427
|
+
* Keeps the files the models evaluated that the fingerprint does not
|
|
428
|
+
* already cover: those of the project, outside `node_modules`, the models
|
|
429
|
+
* directory and the scalars.
|
|
430
|
+
*/
|
|
431
|
+
const follow = (build) => {
|
|
432
|
+
const covered = new Set(modelsFiles(root));
|
|
433
|
+
const realRoot = realPathOr(root);
|
|
434
|
+
const files = build.importedFiles.filter((file) => {
|
|
435
|
+
const inside = (pathWithin(realRoot, file) ?? pathWithin(root, file))?.split(sep);
|
|
436
|
+
return inside !== void 0 && !inside.includes("node_modules") && !covered.has(inside.join("/"));
|
|
437
|
+
});
|
|
438
|
+
const next = [...new Set(build.settled ? files : [...imported, ...files])].sort();
|
|
439
|
+
if (next.join("\0") === imported.join("\0")) return;
|
|
440
|
+
imported = next;
|
|
441
|
+
stamped = void 0;
|
|
442
|
+
};
|
|
443
|
+
const start = ({ revision, modelsKey }) => {
|
|
444
|
+
const stop = new AbortController();
|
|
445
|
+
builder ??= import("./build-FMqn8eub.mjs").then(({ createProjectBuilder }) => createProjectBuilder(root));
|
|
446
|
+
const work = builder.then((run) => run(revision, modelsKey, stop.signal));
|
|
447
|
+
const build = withTimeout(work, buildTimeoutMs, () => {
|
|
448
|
+
const error = /* @__PURE__ */ new Error(`Reading the project took longer than ${buildTimeoutMs / 1e3} s and was stopped. A document model's module may be waiting for something that never settles.`);
|
|
449
|
+
stop.abort(error);
|
|
450
|
+
return error;
|
|
451
|
+
});
|
|
452
|
+
const reading = {
|
|
453
|
+
revision,
|
|
454
|
+
build
|
|
455
|
+
};
|
|
456
|
+
current = reading;
|
|
457
|
+
const settling = build.then((done) => {
|
|
458
|
+
follow(done);
|
|
459
|
+
if (!done.settled) {
|
|
460
|
+
reading.unsettledAt = now();
|
|
461
|
+
reading.modelsUnsettled = !done.modelsSettled;
|
|
462
|
+
}
|
|
463
|
+
}, () => {
|
|
464
|
+
const failed = () => {
|
|
465
|
+
reading.unsettledAt = now();
|
|
466
|
+
reading.modelsUnsettled = true;
|
|
467
|
+
};
|
|
468
|
+
if (stop.signal.aborted) work.then(failed, failed);
|
|
469
|
+
else failed();
|
|
470
|
+
}).finally(() => {
|
|
471
|
+
if (inFlight === settling) inFlight = void 0;
|
|
472
|
+
});
|
|
473
|
+
inFlight = settling;
|
|
474
|
+
return build;
|
|
475
|
+
};
|
|
476
|
+
const build = async () => {
|
|
477
|
+
for (;;) {
|
|
478
|
+
const next = stamp();
|
|
479
|
+
if (current?.revision === next.revision) return current.build;
|
|
480
|
+
if (inFlight === void 0) return start(next);
|
|
481
|
+
await inFlight;
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
return {
|
|
485
|
+
revision: () => stamp().revision,
|
|
486
|
+
snapshot: async () => (await build()).snapshot,
|
|
487
|
+
documentModel: async (documentType) => (await build()).documentModel(documentType),
|
|
488
|
+
fileList: async () => (await build()).fileList(),
|
|
489
|
+
file: async (path) => (await build()).file(path)
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
//#endregion
|
|
493
|
+
//#region src/server/stack.ts
|
|
494
|
+
function readProject(projectRoot) {
|
|
495
|
+
try {
|
|
496
|
+
const pkg = JSON.parse(readFileSync(join(projectRoot, "package.json"), "utf8"));
|
|
497
|
+
return {
|
|
498
|
+
name: typeof pkg.name === "string" ? pkg.name : null,
|
|
499
|
+
version: typeof pkg.version === "string" ? pkg.version : null
|
|
500
|
+
};
|
|
501
|
+
} catch {
|
|
502
|
+
return {
|
|
503
|
+
name: null,
|
|
504
|
+
version: null
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
/** The project and where the parts of its stack answer, read now. */
|
|
509
|
+
function readStack({ projectRoot, run, appUrl }) {
|
|
510
|
+
const known = run?.();
|
|
511
|
+
const service = (name) => known?.services[name] ?? null;
|
|
512
|
+
return {
|
|
513
|
+
project: readProject(projectRoot),
|
|
514
|
+
ph: { version: known?.tool.version ?? "unknown" },
|
|
515
|
+
app: { url: appUrl?.() ?? service("connect") },
|
|
516
|
+
switchboard: { url: service("switchboard") },
|
|
517
|
+
mcp: { url: service("mcp") },
|
|
518
|
+
startedAt: known?.startedAt ?? null
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
//#endregion
|
|
522
|
+
//#region src/server/vite.ts
|
|
523
|
+
/** The module the page loads, and the one its code imports the mount from. */
|
|
524
|
+
const DEVTOOLS_CLIENT_ID = "virtual:ph-devtools/client";
|
|
525
|
+
const MOUNT_ID = "virtual:ph-devtools/mount";
|
|
526
|
+
const CLIENT_FILE = {
|
|
527
|
+
page: "client-page.js",
|
|
528
|
+
connect: "client-connect.js"
|
|
529
|
+
};
|
|
530
|
+
/** A file of this package's build, from its source and from its build. */
|
|
531
|
+
function built(file) {
|
|
532
|
+
const manifest = createRequire(import.meta.url).resolve("@powerhousedao/devtools/package.json");
|
|
533
|
+
return join(dirname(manifest), "dist", file);
|
|
534
|
+
}
|
|
535
|
+
/** Whether this run serves DevTools: `PH_DEVTOOLS=0` turns it off, and so
|
|
536
|
+
* does `NODE_ENV=production`, whatever the server is. */
|
|
537
|
+
function devtoolsRequested(env = process.env) {
|
|
538
|
+
return env.PH_DEVTOOLS !== "0" && env.NODE_ENV !== "production";
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* DevTools for a Vite dev server: the loopback API, the token tag that turns
|
|
542
|
+
* DevTools on in the page, and the module that mounts it there. It applies
|
|
543
|
+
* to a dev server only, never to a build or a preview, and not at all under
|
|
544
|
+
* `PH_DEVTOOLS=0` or `NODE_ENV=production`: a build has no reference to
|
|
545
|
+
* DevTools. A page the server sends to another machine (`--host`) gets
|
|
546
|
+
* neither the tag nor the module: the API would refuse it.
|
|
547
|
+
*
|
|
548
|
+
* One token for the plugin's life, so the servers a config change restarts
|
|
549
|
+
* keep answering the tab that is already open.
|
|
550
|
+
*/
|
|
551
|
+
function devtoolsVitePlugin({ projectRoot = process.cwd(), run, project = createProjectReader(projectRoot), client = "page" } = {}) {
|
|
552
|
+
const token = createDevtoolsToken();
|
|
553
|
+
let serving;
|
|
554
|
+
const fromLoopback = new AsyncLocalStorage();
|
|
555
|
+
return {
|
|
556
|
+
name: "ph-devtools",
|
|
557
|
+
apply: (_config, env) => env.command === "serve" && !env.isPreview && devtoolsRequested(),
|
|
558
|
+
resolveId(id) {
|
|
559
|
+
if (id === "virtual:ph-devtools/client") return `\0${DEVTOOLS_CLIENT_ID}`;
|
|
560
|
+
if (id === MOUNT_ID) return built("mount.js");
|
|
561
|
+
},
|
|
562
|
+
load(id) {
|
|
563
|
+
return id === `\0virtual:ph-devtools/client` ? readFileSync(built(CLIENT_FILE[client]), "utf8") : void 0;
|
|
564
|
+
},
|
|
565
|
+
configureServer(server) {
|
|
566
|
+
serving = server;
|
|
567
|
+
server.middlewares.use((req, _res, next) => fromLoopback.run(onLoopbackSocket(req), next));
|
|
568
|
+
server.middlewares.use(createDevtoolsApiHandler({
|
|
569
|
+
token,
|
|
570
|
+
base: server.config.base,
|
|
571
|
+
info: () => readStack({
|
|
572
|
+
projectRoot,
|
|
573
|
+
run,
|
|
574
|
+
appUrl: () => serving?.resolvedUrls?.local[0]
|
|
575
|
+
}),
|
|
576
|
+
project
|
|
577
|
+
}));
|
|
578
|
+
},
|
|
579
|
+
transformIndexHtml(_html, { server }) {
|
|
580
|
+
if (fromLoopback.getStore() === false) return [];
|
|
581
|
+
const base = server?.config.base ?? "/";
|
|
582
|
+
return [{
|
|
583
|
+
tag: "meta",
|
|
584
|
+
attrs: {
|
|
585
|
+
name: DEVTOOLS_TOKEN_META,
|
|
586
|
+
content: token,
|
|
587
|
+
[DEVTOOLS_BASE_ATTRIBUTE]: base
|
|
588
|
+
},
|
|
589
|
+
injectTo: "head"
|
|
590
|
+
}, {
|
|
591
|
+
tag: "script",
|
|
592
|
+
attrs: {
|
|
593
|
+
type: "module",
|
|
594
|
+
src: `${base}@id/${DEVTOOLS_CLIENT_ID}`
|
|
595
|
+
},
|
|
596
|
+
injectTo: "head"
|
|
597
|
+
}];
|
|
598
|
+
}
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
//#endregion
|
|
602
|
+
export { DEVTOOLS_TOKEN_META as S, createDevtoolsApiHandler as _, EDITORS_DIR as a, DEVTOOLS_API_PATH as b, SUBGRAPHS_DIR as c, byText as d, listFiles as f, devtoolsTokenTag as g, readTextWithin as h, createProjectReader as i, documentModelsDirOf as l, readText as m, devtoolsVitePlugin as n, MANIFEST_FILE as o, projectRelativeMessage as p, readStack as r, PROCESSORS_DIR as s, devtoolsRequested as t, byKey as u, createDevtoolsToken as v, DEVTOOLS_PAGE_PATH as x, DEVTOOLS_TOKEN_HEADER as y };
|
|
603
|
+
|
|
604
|
+
//# sourceMappingURL=vite-INmnb9pz.mjs.map
|