@powerhousedao/devtools 0.0.0-stage → 6.3.0-dev.12

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite-INmnb9pz.mjs","names":[],"sources":["../src/paths.ts","../src/api.ts","../src/server/guards.ts","../src/server/handler.ts","../src/host.ts","../src/server/project/project-fs.ts","../src/server/project/revision.ts","../src/server/project/reader.ts","../src/server/stack.ts","../src/server/vite.ts"],"sourcesContent":["/** The standalone page, below the dev server's base path. */\nexport const DEVTOOLS_PAGE_PATH = \"/__ph/devtools\";\n\n/** The API's routes, below the dev server's base path. */\nexport const DEVTOOLS_API_PATH = `${DEVTOOLS_PAGE_PATH}/api`;\n\n/** The `<meta name>` the dev server delivers the token in. */\nexport const DEVTOOLS_TOKEN_META = \"ph-devtools-token\";\n","export {\n DEVTOOLS_API_PATH,\n DEVTOOLS_PAGE_PATH,\n DEVTOOLS_TOKEN_META,\n} from \"./paths.js\";\n\nexport const DEVTOOLS_TOKEN_HEADER = \"x-ph-devtools-token\";\n\nexport type {\n DevStackInfo,\n ProjectApp,\n ProjectCheck,\n ProjectCheckId,\n ProjectDiagnostic,\n ProjectDocumentModel,\n ProjectDocumentModelDetail,\n ProjectDocumentModelVersion,\n ProjectEditor,\n ProjectFile,\n ProjectFileList,\n ProjectFileText,\n ProjectModuleFiles,\n ProjectModuleKind,\n ProjectOperation,\n ProjectProcessor,\n ProjectSection,\n ProjectSnapshot,\n ProjectStateScope,\n ProjectSubgraph,\n ProjectReader,\n} from \"./project-types.js\";\n\nexport type DevtoolsApiErrorCode =\n | \"bad_host\"\n | \"bad_origin\"\n | \"bad_token\"\n | \"bad_method\"\n | \"not_found\"\n | \"internal\";\n\nexport type DevtoolsApiError = {\n error: { code: DevtoolsApiErrorCode; message: string };\n};\n","import { timingSafeEqual } from \"node:crypto\";\nimport type { IncomingMessage } from \"node:http\";\nimport { DEVTOOLS_TOKEN_HEADER } from \"../api.js\";\n\nconst LOOPBACK_HOST = /^(localhost|127\\.0\\.0\\.1|\\[::1\\])(?::(\\d+))?$/;\n\nfunction isLoopbackAddress(address: string | undefined): boolean {\n if (!address) return false;\n const v4 = address.startsWith(\"::ffff:\") ? address.slice(7) : address;\n return v4.startsWith(\"127.\") || address === \"::1\";\n}\n\n/** Whether the server accepted this request on a loopback address: a client\n * on another machine arrives on one that is not. */\nexport const onLoopbackSocket = (req: IncomingMessage) =>\n isLoopbackAddress(req.socket.localAddress);\n\n/** Headers a proxy or a tunnel adds. One that runs on this machine reaches\n * the server on loopback, for a client that may be anywhere. */\nconst FORWARDED_HEADERS = [\n \"forwarded\",\n \"x-forwarded-for\",\n \"x-forwarded-host\",\n \"x-real-ip\",\n \"via\",\n];\n\n/** The name the client asked for. HTTP/2 sends it as `:authority`. */\nfunction requestedHost(req: IncomingMessage): string {\n const authority = req.headers[\":authority\"];\n const host = typeof authority === \"string\" ? authority : req.headers.host;\n return host?.toLowerCase() ?? \"\";\n}\n\nconst isEncrypted = (req: IncomingMessage) =>\n \"encrypted\" in req.socket && req.socket.encrypted === true;\n\n/**\n * The host the client asked for, when it names loopback on the port this\n * socket accepted on and nothing forwarded the request. A page on another\n * site whose name resolves to 127.0.0.1 (DNS rebinding) sends that site's\n * name, and a server that also listens beyond loopback (`--host`) accepts a\n * LAN client on a socket whose address is not loopback.\n */\nexport function loopbackHost(req: IncomingMessage): string | undefined {\n if (!onLoopbackSocket(req)) return undefined;\n if (FORWARDED_HEADERS.some((name) => req.headers[name] !== undefined)) {\n return undefined;\n }\n const host = requestedHost(req);\n const match = LOOPBACK_HOST.exec(host);\n if (!match) return undefined;\n const port = Number(match.at(2) ?? (isEncrypted(req) ? 443 : 80));\n return port === req.socket.localPort ? host : undefined;\n}\n\n/** Whether a browser sent this request from the page `host` served: another\n * origin's script, even one on another loopback port, is refused. */\nexport function sameOrigin(req: IncomingMessage, host: string): boolean {\n const origin = req.headers.origin;\n const own = `${isEncrypted(req) ? \"https\" : \"http\"}://${host}`;\n if (origin !== undefined && origin !== own) return false;\n const site = req.headers[\"sec-fetch-site\"];\n return site === undefined || site === \"same-origin\" || site === \"none\";\n}\n\nexport function tokenMatches(req: IncomingMessage, token: Buffer): boolean {\n const sent = req.headers[DEVTOOLS_TOKEN_HEADER];\n if (typeof sent !== \"string\") return false;\n const given = Buffer.from(sent);\n return given.length === token.length && timingSafeEqual(given, token);\n}\n","import { randomBytes } from \"node:crypto\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport {\n DEVTOOLS_API_PATH,\n DEVTOOLS_TOKEN_HEADER,\n type DevtoolsApiError,\n type DevtoolsApiErrorCode,\n type DevStackInfo,\n type ProjectReader,\n} from \"../api.js\";\nimport { loopbackHost, sameOrigin, tokenMatches } from \"./guards.js\";\n\nexport type DevtoolsApiOptions = {\n /** What the served page sends back in the token header. */\n token: string;\n /** The dev server's base path, for example `/app/`. The API answers below\n * it and at the bare path, as the dev server's other routes do. */\n base?: string;\n /** Read at each request. */\n info: () => DevStackInfo | Promise<DevStackInfo>;\n /** Without it the `project` routes answer `not_found`. */\n project?: ProjectReader;\n};\n\nexport type DevtoolsApiHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n) => void;\n\nconst STATUS: Record<DevtoolsApiErrorCode, number> = {\n bad_host: 403,\n bad_origin: 403,\n bad_token: 401,\n bad_method: 405,\n not_found: 404,\n internal: 500,\n};\n\nexport function createDevtoolsToken(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\nconst etagOf = (revision: string) => `\"${revision}\"`;\n\nfunction sendJson(\n res: ServerResponse,\n status: number,\n body: unknown,\n revision?: string,\n): void {\n res.statusCode = status;\n if (revision !== undefined) res.setHeader(\"ETag\", etagOf(revision));\n res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n res.end(JSON.stringify(body));\n}\n\nfunction sendError(\n res: ServerResponse,\n code: DevtoolsApiErrorCode,\n message: string,\n): void {\n const body: DevtoolsApiError = { error: { code, message } };\n sendJson(res, STATUS[code], body);\n}\n\nfunction apiPrefixes(base: string | undefined): string[] {\n const trimmed = (base ?? \"/\").replace(/\\/+$/, \"\");\n return [...new Set([`${trimmed}${DEVTOOLS_API_PATH}`, DEVTOOLS_API_PATH])];\n}\n\n/**\n * Serves the DevTools API behind its guards. Every route needs a loopback\n * `Host`, the page's own origin and the page's token. Any other path goes to\n * `next`, the standalone page's included.\n */\nexport function createDevtoolsApiHandler(\n options: DevtoolsApiOptions,\n): DevtoolsApiHandler {\n const token = Buffer.from(options.token);\n const prefixes = apiPrefixes(options.base);\n\n /** Routes that name one item by an escaped segment. */\n const ITEM_ROUTES: [\n string,\n (\n reader: ProjectReader,\n name: string,\n ) => Promise<{ revision: string } | undefined>,\n ][] = [\n [\"project/document-models/\", (reader, name) => reader.documentModel(name)],\n [\"project/files/\", (reader, name) => reader.file(name)],\n ];\n\n const readProject = (\n reader: ProjectReader,\n path: string,\n ): Promise<{ revision: string } | undefined> | undefined => {\n if (path === \"project\") return reader.snapshot();\n if (path === \"project/files\") return reader.fileList();\n for (const [prefix, read] of ITEM_ROUTES) {\n if (!path.startsWith(prefix)) continue;\n let name: string;\n try {\n name = decodeURIComponent(path.slice(prefix.length));\n } catch {\n // A malformed escape names nothing.\n return undefined;\n }\n return read(reader, name);\n }\n return undefined;\n };\n\n const route = async (\n req: IncomingMessage,\n res: ServerResponse,\n path: string,\n ): Promise<void> => {\n const reader =\n path === \"project\" || path.startsWith(\"project/\")\n ? options.project\n : undefined;\n const notFound = () =>\n sendError(res, \"not_found\", `No DevTools route \"${path}\".`);\n if (path !== \"info\" && !reader) return notFound();\n if (req.method !== \"GET\") {\n res.setHeader(\"Allow\", \"GET\");\n return sendError(res, \"bad_method\", \"This route answers GET only.\");\n }\n if (!reader) return sendJson(res, 200, await options.info());\n\n const notModified = (revision: string) => {\n if (req.headers[\"if-none-match\"] !== etagOf(revision)) return false;\n res.statusCode = 304;\n res.setHeader(\"ETag\", etagOf(revision));\n res.end();\n return true;\n };\n // The snapshot is the route the page polls: its revision is known before\n // the project is read. The others answer only for what they find.\n if (path === \"project\" && notModified(await reader.revision())) return;\n const answer = await readProject(reader, path);\n if (answer === undefined) return notFound();\n if (notModified(answer.revision)) return;\n sendJson(res, 200, answer, answer.revision);\n };\n\n return (req, res, next) => {\n let pathname: string;\n try {\n ({ pathname } = new URL(req.url ?? \"/\", \"http://localhost\"));\n } catch {\n // A request target that is no URL names no API path.\n return next();\n }\n const prefix = prefixes.find(\n (candidate) =>\n pathname === candidate || pathname.startsWith(`${candidate}/`),\n );\n if (prefix === undefined) return next();\n\n const host = loopbackHost(req);\n if (!host) return sendError(res, \"bad_host\", \"Host is not loopback.\");\n if (!sameOrigin(req, host)) {\n return sendError(res, \"bad_origin\", \"Cross-origin requests are refused.\");\n }\n if (!tokenMatches(req, token)) {\n return sendError(\n res,\n \"bad_token\",\n `Missing or wrong ${DEVTOOLS_TOKEN_HEADER}.`,\n );\n }\n route(req, res, pathname.slice(prefix.length + 1)).catch(\n (error: unknown) => {\n if (res.headersSent) return;\n sendError(\n res,\n \"internal\",\n error instanceof Error ? error.message : String(error),\n );\n },\n );\n };\n}\n","import { DEVTOOLS_TOKEN_META } from \"./paths.js\";\n\n/** The attribute of the token tag that names the dev server's base path. */\nexport const DEVTOOLS_BASE_ATTRIBUTE = \"data-base\";\n\nfunction tokenTag(): HTMLMetaElement | undefined {\n // A server that renders the app has no document.\n const page = globalThis.document as Document | undefined;\n return (\n page?.querySelector<HTMLMetaElement>(\n `meta[name=\"${DEVTOOLS_TOKEN_META}\"]`,\n ) ?? undefined\n );\n}\n\n/**\n * The token the dev server put in this page, or undefined on a page no\n * DevTools dev server served: a build, or a dev server without DevTools.\n * This is the one switch: DevTools shows only where it returns a token.\n */\nexport function readDevtoolsToken(): string | undefined {\n return tokenTag()?.content.trim() || undefined;\n}\n\n/** The base path the dev server serves the app under, as its tag says. */\nexport function readDevtoolsBase(): string | undefined {\n return tokenTag()?.getAttribute(DEVTOOLS_BASE_ATTRIBUTE) ?? undefined;\n}\n\nconst attribute = (value: string) =>\n value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\").replace(/</g, \"&lt;\");\n\n/** The tag a dev server puts in the `<head>` of the pages it serves. */\nexport function devtoolsTokenTag(token: string, base = \"/\"): string {\n return `<meta name=\"${DEVTOOLS_TOKEN_META}\" content=\"${attribute(token)}\" ${DEVTOOLS_BASE_ATTRIBUTE}=\"${attribute(base)}\">`;\n}\n","import { pathWithin } from \"@powerhousedao/shared/clis/real-paths\";\nimport {\n closeSync,\n fstatSync,\n openSync,\n readdirSync,\n readFileSync,\n readSync,\n realpathSync,\n statSync,\n} from \"node:fs\";\nimport { join, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nconst SKIPPED_DIRECTORIES = new Set([\"node_modules\", \"dist\"]);\n\n/** Files that hold secrets wherever they are, as Vite's `server.fs.deny`\n * has them: dot-files such as `.env`, and keys and certificates. */\nconst holdsSecrets = (name: string) =>\n name.startsWith(\".\") || /\\.(pem|key|crt|p12|pfx)$/i.test(name);\n\n/** Whether a real path stays inside the project and passes the same filters\n * as a name in a listing: a symlink's own name says nothing of its target. */\nconst shownWithin = (realRoot: string, real: string) => {\n const inside = pathWithin(realRoot, real);\n return (\n inside !== null &&\n !inside\n .split(sep)\n .some((part) => SKIPPED_DIRECTORIES.has(part) || holdsSecrets(part))\n );\n};\n\n/** Orders by code unit, so a listing does not depend on the machine's locale. */\nexport const byText = (left: string, right: string) =>\n left < right ? -1 : left > right ? 1 : 0;\n\nexport const byKey =\n <T>(key: (item: T) => string) =>\n (left: T, right: T) =>\n byText(key(left), key(right));\n\n/**\n * The files below `dir`, as sorted POSIX paths relative to `root`. Skips\n * `node_modules`, `dist`, dot-directories, dot-files, keys and certificates.\n * A symlink is followed, as the\n * model loader and ts-morph follow it, while its real path stays inside the\n * project and skips none of these; each real directory is entered through a\n * link once. A missing or\n * unreadable directory has none.\n */\nexport function listFiles(root: string, dir: string): string[] {\n const files: string[] = [];\n let realRoot: string | undefined;\n const linked = new Set<string>();\n /** What a symlink inside the project points at, or undefined to skip it. */\n const followed = (path: string): \"file\" | \"directory\" | undefined => {\n try {\n realRoot ??= realpathSync.native(root);\n const real = realpathSync.native(join(root, path));\n if (!shownWithin(realRoot, real)) return undefined;\n const stats = statSync(real);\n if (stats.isFile()) return \"file\";\n if (!stats.isDirectory() || linked.has(real)) return undefined;\n linked.add(real);\n return \"directory\";\n } catch {\n return undefined;\n }\n };\n const visit = (relativeDir: string) => {\n let entries;\n try {\n entries = readdirSync(join(root, relativeDir), { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries.sort(byKey(({ name }) => name))) {\n const path =\n relativeDir === \"\" ? entry.name : `${relativeDir}/${entry.name}`;\n const skipped =\n SKIPPED_DIRECTORIES.has(entry.name) || entry.name.startsWith(\".\");\n const kind = entry.isFile()\n ? \"file\"\n : entry.isDirectory()\n ? \"directory\"\n : entry.isSymbolicLink() && !SKIPPED_DIRECTORIES.has(entry.name)\n ? followed(path)\n : undefined;\n if (kind === \"file\") {\n if (!holdsSecrets(entry.name)) files.push(path);\n } else if (kind === \"directory\" && !skipped) visit(path);\n }\n };\n visit(dir);\n return files;\n}\n\n/** The file's text, or undefined when it is missing or unreadable. */\nexport function readText(root: string, path: string): string | undefined {\n try {\n return readFileSync(join(root, path), \"utf8\");\n } catch {\n return undefined;\n }\n}\n\n/** Where a cut at `end` leaves `bytes` whole: before a character whose\n * bytes would run past it. */\nfunction utf8Boundary(bytes: Buffer, end: number): number {\n let start = end - 1;\n while (start > end - 4 && start > 0 && (bytes[start] & 0xc0) === 0x80) {\n start -= 1;\n }\n const lead = bytes[start];\n const length = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : lead >= 0xc0 ? 2 : 1;\n return start + length > end ? start : end;\n}\n\n/**\n * Up to `limit` bytes of a regular file as text, cut where a character\n * starts. Undefined when the file is missing, unreadable, not a file, or its\n * real path leaves the project.\n */\nexport function readTextWithin(\n root: string,\n path: string,\n limit: number,\n): { text: string; truncated: boolean } | undefined {\n let descriptor: number | undefined;\n try {\n const real = realpathSync.native(join(root, path));\n if (!shownWithin(realpathSync.native(root), real)) return undefined;\n descriptor = openSync(real, \"r\");\n if (!fstatSync(descriptor).isFile()) return undefined;\n // One byte past the limit says whether the file goes on.\n const buffer = Buffer.alloc(limit + 1);\n const read = readSync(descriptor, buffer, 0, buffer.length, 0);\n const truncated = read > limit;\n const end = truncated ? utf8Boundary(buffer, limit) : read;\n return { text: buffer.toString(\"utf8\", 0, end), truncated };\n } catch {\n return undefined;\n } finally {\n if (descriptor !== undefined) closeSync(descriptor);\n }\n}\n\n/** What a thrown value says, with the project's own path written as `.`. */\nexport function projectRelativeMessage(root: string, error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return [pathToFileURL(root).href, root, root.replaceAll(\"\\\\\", \"/\")].reduce(\n (text, absolute) => text.replaceAll(absolute, \".\"),\n message,\n );\n}\n","import {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport { createHash } from \"node:crypto\";\nimport { realpathSync, statSync } from \"node:fs\";\nimport { isAbsolute, join, resolve, sep } from \"node:path\";\nimport { listFiles, readText } from \"./project-fs.js\";\n\nexport const MANIFEST_FILE = \"powerhouse.manifest.json\";\nexport const CONFIG_FILE = \"powerhouse.config.json\";\nexport const EDITORS_DIR = \"editors\";\nexport const SUBGRAPHS_DIR = \"subgraphs\";\nexport const PROCESSORS_DIR = \"processors\";\n\nconst DEFAULT_DOCUMENT_MODELS_DIR = \"document-models\";\n\n/** `scalars/index.ts` is an input of every stored model, wherever the models are. */\nconst SCALARS_DIR = \"scalars\";\n\n/**\n * The config's `documentModelsDir` as a POSIX path relative to the project.\n * It mirrors the loader's `resolveDocumentModelsDir` (document-model's\n * `tooling/model-directories.ts`), which this module cannot import without\n * loading the definition tooling into every dev server. Where the loader\n * refuses the directory the models are not read at all, so the default is\n * answered.\n */\nexport function documentModelsDirOf(root: string): string {\n try {\n const { documentModelsDir } = JSON.parse(\n readText(root, CONFIG_FILE) ?? \"{}\",\n ) as { documentModelsDir?: unknown };\n if (\n typeof documentModelsDir !== \"string\" ||\n documentModelsDir.trim() === \"\"\n ) {\n return DEFAULT_DOCUMENT_MODELS_DIR;\n }\n const path = resolve(root, documentModelsDir);\n const inside = pathWithin(root, path);\n const real = pathWithin(\n realpathSync.native(root),\n realPathThroughExistingParent(path),\n );\n return inside === null || inside === \"\" || real === null\n ? DEFAULT_DOCUMENT_MODELS_DIR\n : inside.split(sep).join(\"/\");\n } catch {\n return DEFAULT_DOCUMENT_MODELS_DIR;\n }\n}\n\n/** Hashes each path with its modification time and size, without reading it. */\nfunction fingerprint(root: string, paths: readonly string[]): string {\n const hash = createHash(\"sha256\");\n for (const path of paths) {\n const stats = statSync(isAbsolute(path) ? path : join(root, path), {\n throwIfNoEntry: false,\n });\n hash.update(\n stats === undefined\n ? `${path}\\0missing\\n`\n : `${path}\\0${stats.mtimeMs}\\0${stats.size}\\n`,\n );\n }\n return hash.digest(\"hex\");\n}\n\n/** The files of the models directory and of the project's scalars, relative to the project. */\nexport function modelsFiles(root: string): string[] {\n return [\n ...listFiles(root, documentModelsDirOf(root)),\n ...listFiles(root, SCALARS_DIR),\n ];\n}\n\n/**\n * What a read of the document models depends on: the models directory, the\n * project's scalars, the config, and `imported`, the absolute files the\n * last read's code-first sources evaluated, which can be anywhere.\n */\nexport function modelsFingerprint(\n root: string,\n imported: readonly string[],\n): string {\n return fingerprint(root, [...modelsFiles(root), CONFIG_FILE, ...imported]);\n}\n\n/** What the other sections depend on. `tsconfig.json` is here because they\n * cannot be read without it. */\nexport function modulesFingerprint(root: string): string {\n return fingerprint(root, [\n ...[EDITORS_DIR, SUBGRAPHS_DIR, PROCESSORS_DIR].flatMap((dir) =>\n listFiles(root, dir),\n ),\n MANIFEST_FILE,\n \"tsconfig.json\",\n ]);\n}\n\n/** One short token for the response's `ETag`. */\nexport function revisionOf(...parts: readonly (string | number)[]): string {\n return createHash(\"sha256\")\n .update(parts.join(\"\\0\"))\n .digest(\"hex\")\n .slice(0, 16);\n}\n","import type { ProjectReader } from \"../../project-types.js\";\nimport { pathWithin } from \"@powerhousedao/shared/clis/real-paths\";\nimport { realpathSync } from \"node:fs\";\nimport { resolve, sep } from \"node:path\";\nimport type { ProjectBuild, ProjectBuilder } from \"./build.js\";\nimport {\n modelsFiles,\n modelsFingerprint,\n modulesFingerprint,\n revisionOf,\n} from \"./revision.js\";\n\nexport type ProjectReaderOptions = {\n /** How long one read may take before it is stopped. A code-first model's\n * module is evaluated in this process and can wait forever. */\n buildTimeoutMs?: number;\n /** How long a revision is reused before the files are fingerprinted again. */\n revisionTtlMs?: number;\n /** How long a read that is not settled is kept before the next request reads again. */\n retryAfterMs?: number;\n now?: () => number;\n};\n\ntype Stamp = { revision: string; modelsKey: string };\n\ntype Reading = {\n revision: string;\n build: Promise<ProjectBuild>;\n /** When a read that failed or is not settled finished. Undefined while it\n * runs and once it is settled. */\n unsettledAt?: number;\n /** Whether the document models are part of what is not settled. */\n modelsUnsettled?: boolean;\n};\n\nfunction realPathOr(path: string): string {\n try {\n return realpathSync.native(path);\n } catch {\n return path;\n }\n}\n\nfunction withTimeout<T>(\n work: Promise<T>,\n ms: number,\n onTimeout: () => Error,\n): Promise<T> {\n return new Promise<T>((resolvePromise, reject) => {\n const timer = setTimeout(() => reject(onTimeout()), ms);\n // The dev server must be able to exit while a read is pending.\n timer.unref();\n work.then(resolvePromise, reject).finally(() => clearTimeout(timer));\n });\n}\n\n/**\n * Reads what a project's code contains. It never writes to the\n * project and watches nothing: a request fingerprints the files again.\n *\n * - Requests for one revision share one read, including those that arrive\n * while it runs. Reads never overlap: a newer revision waits for the read\n * in flight, then is read once.\n * - A read that takes longer than the limit is stopped and fails. A module\n * it was evaluating may run on: the same files are not read again until\n * that module ends.\n * - A read that failed or is not settled (a section failed, or a model's\n * source did not import) can depend on files outside the fingerprint, so\n * it gets a new revision and is read again after `retryAfterMs`.\n */\nexport function createProjectReader(\n projectDir: string,\n {\n buildTimeoutMs = 30_000,\n revisionTtlMs = 300,\n retryAfterMs = 5_000,\n now = Date.now,\n }: ProjectReaderOptions = {},\n): ProjectReader {\n const root = resolve(projectDir);\n /** The files outside the module folders that the last read's models evaluated. */\n let imported: string[] = [];\n /** Counts the retries of unsettled reads, so each one has its own revision. */\n let retries = 0;\n /** Counts those whose models were not settled: only they load the models\n * again. A retry for a failed section alone keeps the models it has. */\n let modelRetries = 0;\n let stamped: { at: number; stamp: Stamp } | undefined;\n let current: Reading | undefined;\n let inFlight: Promise<void> | undefined;\n // Loaded on first use: the readers pull in ts-morph and the definition\n // tooling, which a dev server whose tools never ask does not need.\n let builder: Promise<ProjectBuilder> | undefined;\n\n const stamp = (): Stamp => {\n const at = now();\n if (stamped !== undefined && at - stamped.at < revisionTtlMs) {\n return stamped.stamp;\n }\n if (\n current?.unsettledAt !== undefined &&\n at - current.unsettledAt >= retryAfterMs\n ) {\n if (current.modelsUnsettled) modelRetries += 1;\n current = undefined;\n retries += 1;\n }\n const modelsKey = revisionOf(\n modelsFingerprint(root, imported),\n modelRetries,\n );\n const revision = revisionOf(modelsKey, modulesFingerprint(root), retries);\n stamped = { at, stamp: { revision, modelsKey } };\n return stamped.stamp;\n };\n\n /**\n * Keeps the files the models evaluated that the fingerprint does not\n * already cover: those of the project, outside `node_modules`, the models\n * directory and the scalars.\n */\n const follow = (build: ProjectBuild) => {\n const covered = new Set(modelsFiles(root));\n // The module graph names a file by its real path, which leaves out a\n // symlink, a junction or a `subst` drive on the way to the project.\n const realRoot = realPathOr(root);\n const files = build.importedFiles.filter((file) => {\n const inside = (\n pathWithin(realRoot, file) ?? pathWithin(root, file)\n )?.split(sep);\n return (\n inside !== undefined &&\n !inside.includes(\"node_modules\") &&\n !covered.has(inside.join(\"/\"))\n );\n });\n // A source that did not import reports no files, so the ones it\n // evaluated before stay followed until it imports again.\n const next = [\n ...new Set(build.settled ? files : [...imported, ...files]),\n ].sort();\n if (next.join(\"\\0\") === imported.join(\"\\0\")) return;\n imported = next;\n stamped = undefined;\n };\n\n const start = ({ revision, modelsKey }: Stamp): Promise<ProjectBuild> => {\n const stop = new AbortController();\n builder ??= import(\"./build.js\").then(({ createProjectBuilder }) =>\n createProjectBuilder(root),\n );\n const work = builder.then((run) => run(revision, modelsKey, stop.signal));\n const build = withTimeout(work, buildTimeoutMs, () => {\n const error = new Error(\n `Reading the project took longer than ${buildTimeoutMs / 1000} s and was stopped. A document model's module may be waiting for something that never settles.`,\n );\n stop.abort(error);\n return error;\n });\n const reading: Reading = { revision, build };\n current = reading;\n const settling = build\n .then(\n (done) => {\n follow(done);\n if (!done.settled) {\n reading.unsettledAt = now();\n reading.modelsUnsettled = !done.modelsSettled;\n }\n },\n () => {\n // A read that failed stays the answer for its revision, so a poll\n // does not start it again: the files change it, or `retryAfterMs`.\n // A stopped read can still be evaluating a module, which nothing\n // can end, so `retryAfterMs` counts from when that module ends.\n const failed = () => {\n reading.unsettledAt = now();\n reading.modelsUnsettled = true;\n };\n if (stop.signal.aborted) void work.then(failed, failed);\n else failed();\n },\n )\n .finally(() => {\n if (inFlight === settling) inFlight = undefined;\n });\n inFlight = settling;\n return build;\n };\n\n const build = async (): Promise<ProjectBuild> => {\n for (;;) {\n const next = stamp();\n if (current?.revision === next.revision) return current.build;\n if (inFlight === undefined) return start(next);\n await inFlight;\n }\n };\n\n return {\n revision: () => stamp().revision,\n snapshot: async () => (await build()).snapshot,\n documentModel: async (documentType) =>\n (await build()).documentModel(documentType),\n fileList: async () => (await build()).fileList(),\n file: async (path) => (await build()).file(path),\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { DevStackInfo } from \"../api.js\";\n\n/** What the tool that started the server knows of the run. */\nexport type DevtoolsRun = {\n /** The tool that runs the server, for example the `ph` CLI. */\n tool: { name: string; version: string };\n /** When the run came up, as an ISO timestamp. */\n startedAt: string | null;\n /** Where the run's other services answer: a URL by service name. DevTools\n * shows `connect`, `switchboard` and `mcp`. */\n services: Readonly<Record<string, string>>;\n};\n\nexport type DevtoolsStackOptions = {\n /** The folder of the project the server runs. */\n projectRoot: string;\n /** Read at each request: the services of a run come up after its server. */\n run?: () => DevtoolsRun;\n /** Where the app answers, when the server knows better than `run`. */\n appUrl?: () => string | undefined;\n};\n\nfunction readProject(projectRoot: string): DevStackInfo[\"project\"] {\n try {\n const pkg = JSON.parse(\n readFileSync(join(projectRoot, \"package.json\"), \"utf8\"),\n ) as { name?: unknown; version?: unknown };\n return {\n name: typeof pkg.name === \"string\" ? pkg.name : null,\n version: typeof pkg.version === \"string\" ? pkg.version : null,\n };\n } catch {\n return { name: null, version: null };\n }\n}\n\n/** The project and where the parts of its stack answer, read now. */\nexport function readStack({\n projectRoot,\n run,\n appUrl,\n}: DevtoolsStackOptions): DevStackInfo {\n const known = run?.();\n const service = (name: string) => known?.services[name] ?? null;\n return {\n project: readProject(projectRoot),\n ph: { version: known?.tool.version ?? \"unknown\" },\n app: { url: appUrl?.() ?? service(\"connect\") },\n switchboard: { url: service(\"switchboard\") },\n mcp: { url: service(\"mcp\") },\n startedAt: known?.startedAt ?? null,\n };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport type { ProjectReader } from \"../api.js\";\nimport { DEVTOOLS_BASE_ATTRIBUTE } from \"../host.js\";\nimport { DEVTOOLS_TOKEN_META } from \"../paths.js\";\nimport { onLoopbackSocket } from \"./guards.js\";\nimport { createDevtoolsApiHandler, createDevtoolsToken } from \"./handler.js\";\nimport { createProjectReader } from \"./project/reader.js\";\nimport { readStack, type DevtoolsRun } from \"./stack.js\";\n\n/** What the page loads. `connect` also does what DevTools needs from a\n * Connect app: its page route and what the app knows. */\nexport type DevtoolsClient = \"page\" | \"connect\";\n\nexport type DevtoolsVitePluginOptions = {\n /** The folder of the project the dev server runs. The working directory\n * by default. */\n projectRoot?: string;\n /** What the tool that started the dev server knows of the run. */\n run?: () => DevtoolsRun;\n /** In place of the reader DevTools makes for `projectRoot`. */\n project?: ProjectReader;\n /** \"page\" by default: DevTools mounted on the page, and nothing else. */\n client?: DevtoolsClient;\n};\n\n/** The module the page loads, and the one its code imports the mount from. */\nexport const DEVTOOLS_CLIENT_ID = \"virtual:ph-devtools/client\";\nconst MOUNT_ID = \"virtual:ph-devtools/mount\";\n\nconst CLIENT_FILE: Record<DevtoolsClient, string> = {\n page: \"client-page.js\",\n connect: \"client-connect.js\",\n};\n\n/** A file of this package's build, from its source and from its build. */\nfunction built(file: string): string {\n const manifest = createRequire(import.meta.url).resolve(\n \"@powerhousedao/devtools/package.json\",\n );\n return join(dirname(manifest), \"dist\", file);\n}\n\n/** Whether this run serves DevTools: `PH_DEVTOOLS=0` turns it off, and so\n * does `NODE_ENV=production`, whatever the server is. */\nexport function devtoolsRequested(\n env: Record<string, string | undefined> = process.env,\n): boolean {\n return env.PH_DEVTOOLS !== \"0\" && env.NODE_ENV !== \"production\";\n}\n\n/**\n * DevTools for a Vite dev server: the loopback API, the token tag that turns\n * DevTools on in the page, and the module that mounts it there. It applies\n * to a dev server only, never to a build or a preview, and not at all under\n * `PH_DEVTOOLS=0` or `NODE_ENV=production`: a build has no reference to\n * DevTools. A page the server sends to another machine (`--host`) gets\n * neither the tag nor the module: the API would refuse it.\n *\n * One token for the plugin's life, so the servers a config change restarts\n * keep answering the tab that is already open.\n */\nexport function devtoolsVitePlugin({\n projectRoot = process.cwd(),\n run,\n project = createProjectReader(projectRoot),\n client = \"page\",\n}: DevtoolsVitePluginOptions = {}): Plugin {\n const token = createDevtoolsToken();\n // The server a config change restarts replaces the one before it.\n let serving: ViteDevServer | undefined;\n // Whether the request being answered came in on loopback. Vite does not\n // hand `transformIndexHtml` the request.\n const fromLoopback = new AsyncLocalStorage<boolean>();\n return {\n name: \"ph-devtools\",\n apply: (_config, env) =>\n env.command === \"serve\" && !env.isPreview && devtoolsRequested(),\n resolveId(id) {\n if (id === DEVTOOLS_CLIENT_ID) return `\\0${DEVTOOLS_CLIENT_ID}`;\n if (id === MOUNT_ID) return built(\"mount.js\");\n return undefined;\n },\n // Served as a module of the project, not of this package: its imports of\n // the app's own packages resolve as the project's code does.\n load(id) {\n return id === `\\0${DEVTOOLS_CLIENT_ID}`\n ? readFileSync(built(CLIENT_FILE[client]), \"utf8\")\n : undefined;\n },\n configureServer(server) {\n // Ahead of Vite's own middlewares, so the HTML fallback never answers\n // an API path.\n serving = server;\n server.middlewares.use((req, _res, next) =>\n fromLoopback.run(onLoopbackSocket(req), next),\n );\n server.middlewares.use(\n createDevtoolsApiHandler({\n token,\n base: server.config.base,\n info: () =>\n readStack({\n projectRoot,\n run,\n appUrl: () => serving?.resolvedUrls?.local[0],\n }),\n project,\n }),\n );\n },\n transformIndexHtml(_html, { server }) {\n // Outside a request of this server's, a host that renders the page\n // itself asked: it serves whom it chooses.\n if (fromLoopback.getStore() === false) return [];\n const base = server?.config.base ?? \"/\";\n return [\n {\n tag: \"meta\",\n attrs: {\n name: DEVTOOLS_TOKEN_META,\n content: token,\n [DEVTOOLS_BASE_ATTRIBUTE]: base,\n },\n injectTo: \"head\",\n },\n {\n tag: \"script\",\n attrs: { type: \"module\", src: `${base}@id/${DEVTOOLS_CLIENT_ID}` },\n injectTo: \"head\",\n },\n ];\n },\n };\n}\n"],"mappings":";;;;;;;;;AACA,MAAa,qBAAqB;;AAGlC,MAAa,oBAAoB,GAAG,mBAAmB;;AAGvD,MAAa,sBAAsB;;;ACDnC,MAAa,wBAAwB;;;ACFrC,MAAM,gBAAgB;AAEtB,SAAS,kBAAkB,SAAsC;CAC/D,IAAI,CAAC,SAAS,OAAO;CAErB,QADW,QAAQ,WAAW,SAAS,IAAI,QAAQ,MAAM,CAAC,IAAI,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pC,OAAO,CACL;IACE,KAAK;IACL,OAAO;KACL,MAAM;KACN,SAAS;MACR,0BAA0B;IAC7B;IACA,UAAU;GACZ,GACA;IACE,KAAK;IACL,OAAO;KAAE,MAAM;KAAU,KAAK,GAAG,KAAK,MAAM;IAAqB;IACjE,UAAU;GACZ,CACF;EACF;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,96 @@
1
1
  {
2
2
  "name": "@powerhousedao/devtools",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "6.3.0-dev.12",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "description": "DevTools for Powerhouse projects: a dev-server plugin with its loopback API and the dock it mounts on the page",
8
+ "type": "module",
9
+ "license": "AGPL-3.0-only",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/powerhouse-inc/powerhouse",
13
+ "directory": "packages/devtools"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "!dist/*.js.map"
18
+ ],
19
+ "sideEffects": [
20
+ "./dist/client-*.js"
21
+ ],
22
+ "exports": {
23
+ "./connect": {
24
+ "source": "./src/connect/index.ts",
25
+ "types": "./dist/connect.d.mts",
26
+ "import": "./dist/connect.mjs",
27
+ "default": "./dist/connect.mjs"
28
+ },
29
+ "./mount": {
30
+ "source": "./src/mount.tsx",
31
+ "types": "./dist/mount.d.ts",
32
+ "import": "./dist/mount.js",
33
+ "default": "./dist/mount.js"
34
+ },
35
+ "./server": {
36
+ "source": "./src/server/index.ts",
37
+ "types": "./dist/server.d.mts",
38
+ "import": "./dist/server.mjs",
39
+ "default": "./dist/server.mjs"
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "dependencies": {
44
+ "@powerhousedao/codegen": "6.3.0-dev.12",
45
+ "@powerhousedao/host-core": "6.3.0-dev.12",
46
+ "@powerhousedao/shared": "6.3.0-dev.12",
47
+ "change-case": "5.4.4",
48
+ "document-model": "6.3.0-dev.12",
49
+ "graphql": "^16",
50
+ "ts-morph": "27.0.2"
51
+ },
52
+ "devDependencies": {
53
+ "@base-ui/react": "1.9.0",
54
+ "@dagrejs/dagre": "3.1.3",
55
+ "@powerhousedao/connect-core": "6.3.0-dev.12",
56
+ "@powerhousedao/design-system": "6.3.0-dev.12",
57
+ "@powerhousedao/reactor-browser": "6.3.0-dev.12",
58
+ "@tailwindcss/cli": "4.2.2",
59
+ "@testing-library/dom": "^10.4.0",
60
+ "@testing-library/react": "^16.0.1",
61
+ "@types/node": "25.2.3",
62
+ "@types/react": "19.2.14",
63
+ "@types/react-dom": "19.2.3",
64
+ "@vitejs/plugin-react": "6.1.1",
65
+ "@xyflow/react": "12.11.6",
66
+ "class-variance-authority": "^0.7.0",
67
+ "clsx": "^2.1.1",
68
+ "cmdk": "^1.0.4",
69
+ "happy-dom": "^20.8.9",
70
+ "html-to-image": "1.11.13",
71
+ "lucide-react": "^1.16.0",
72
+ "react": "19.2.6",
73
+ "react-dom": "19.2.6",
74
+ "tailwind-merge": "3.4.0",
75
+ "tailwindcss": "4.2.2",
76
+ "tsdown": "0.23.0",
77
+ "typescript": "7.0.2",
78
+ "vite": "8.3.4",
79
+ "vitest": "5.0.3"
80
+ },
81
+ "peerDependencies": {
82
+ "vite": ">=6.0.0"
83
+ },
84
+ "peerDependenciesMeta": {
85
+ "vite": {
86
+ "optional": true
87
+ }
88
+ },
89
+ "scripts": {
90
+ "tsc": "tsc",
91
+ "lint": "cd ../.. && oxlint packages/devtools",
92
+ "build": "pnpm run build:css && tsdown",
93
+ "build:css": "tailwindcss -i standalone.css -o .cache/standalone.css --minify",
94
+ "test": "vitest --run"
95
+ }
6
96
  }