Files
hyperframes/packages/studio/vite.config.ts
Miguel Angel Simon Sierra 56080c5668 perf(studio): take the AST/DOM stack off the first-paint path
Studio's eagerly-loaded JS measured 855,747B gzip against a 600KiB target.
~1.85MB of the rendered module graph was a Node-only AST/DOM stack that the
browser downloaded before first paint via the modulepreloaded vendor chunk.

Two independent causes, neither of them the SDK's openComposition alone:

1. gsapParserExports.ts re-exported `isStudioHoldSet` from gsapParser.ts, the
   retired recast-based parser. That two-line predicate over an already-parsed
   animation put recast, @babel/parser, esprima, ast-types and source-map on
   the eager graph. Move it (and STUDIO_HOLD_MARKER) to gsapConstants.ts, the
   module that already exists so browser code can reach GSAP constants without
   gsapParser; gsapParser and gsapWriterAcorn now import it from there, which
   also drops gsapWriterAcorn's duplicate copy. Those five packages leave the
   browser graph entirely.

2. linkedom (+ htmlparser2 / css-select / domutils / cssom / entities) came in
   through the SDK's openComposition and through RenderQueue importing
   CANVAS_DIMENSIONS from the @hyperframes/parsers barrel, which re-exports
   hfIds.ts. Route every openComposition call site through a new lazy
   src/utils/sdkLazy.ts (all four were already inside awaited async functions,
   same pattern as mediaProbe.ts does for mediabunny), give parsers a narrow
   ./types subpath for the barrel import, and add an `sdk-parse` manualChunks
   rule so the /node_modules/ catch-all cannot fold the stack back into eager
   vendor.

Measured: 855,747B -> 604,332B gzip, target met. Ratchet lowered to 610,000B.
Verified against the built dist in Chrome: sdk-parse is not modulepreloaded and
arrives in a second wave at 115ms, after the eager set completes at 42ms; a
timeline clip drag still round-trips through openComposition and writes the
new data-start to disk, with no console errors.
2026-08-03 22:02:33 -07:00

269 lines
9.7 KiB
TypeScript

import { defineConfig, type Plugin } from "vite";
import react from "@vitejs/plugin-react";
import { readFileSync, readdirSync, existsSync, lstatSync, realpathSync } from "node:fs";
import { join, resolve } from "node:path";
import { readNodeRequestBody } from "./vite.request-body.js";
import { createViteAdapter, isPathWithin } from "./vite.adapter";
async function loadRuntimeSourceForDev(
server: import("vite").ViteDevServer,
): Promise<string | null> {
try {
const mod = await server.ssrLoadModule(
resolve(__dirname, "../core/src/inline-scripts/hyperframe.ts"),
);
if (typeof mod.loadHyperframeRuntimeSource === "function") {
return mod.loadHyperframeRuntimeSource();
}
} catch (err) {
console.warn("[Studio] Failed to load runtime source from core:", err);
}
return null;
}
const studioPkg = JSON.parse(readFileSync(resolve(__dirname, "package.json"), "utf-8"));
// ── Bridge Hono fetch → Node http response ───────────────────────────────────
async function bridgeHonoResponse(
honoResponse: Response,
res: import("node:http").ServerResponse,
): Promise<void> {
const headers: Record<string, string> = {};
honoResponse.headers.forEach((v, k) => {
headers[k] = v;
});
res.writeHead(honoResponse.status, headers);
if (!honoResponse.body) {
res.end();
return;
}
const reader = honoResponse.body.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
res.write(value);
}
} catch {
/* client disconnected */
}
res.end();
}
// ── Vite plugin ──────────────────────────────────────────────────────────────
function devProjectApi(): Plugin {
const dataDir = resolve(__dirname, "data/projects");
const runtimePath = resolve(__dirname, "../core/dist/hyperframe.runtime.iife.js");
return {
name: "studio-dev-api",
configureServer(server): void {
let _api: { fetch: (req: Request) => Promise<Response> } | null = null;
let _studioServerModule: {
createStudioApi: (adapter: ReturnType<typeof createViteAdapter>) => {
fetch: (req: Request) => Promise<Response>;
};
consumeFileWriteReceipt?: (path: string) => {
path: string;
version: string;
writeToken: string;
} | null;
} | null = null;
const getApi = async () => {
if (!_api) {
const mod = await server.ssrLoadModule("@hyperframes/studio-server");
_studioServerModule = mod as typeof _studioServerModule;
const adapter = createViteAdapter(dataDir, server);
_api = mod.createStudioApi(adapter);
}
return _api;
};
// Runtime endpoint — prefer source build over dist artifact
server.middlewares.use((req, res, next) => {
if (req.url !== "/api/runtime.js") return next();
const serve = async () => {
let runtimeSource = await loadRuntimeSourceForDev(server);
if (!runtimeSource && existsSync(runtimePath)) {
runtimeSource = readFileSync(runtimePath, "utf-8");
}
if (!runtimeSource) {
res.writeHead(404);
res.end("runtime not available — build packages/core or load runtime source");
return;
}
res.writeHead(200, {
"Content-Type": "text/javascript",
"Cache-Control": "no-store",
});
res.end(runtimeSource);
};
void serve().catch((err) => {
console.error("[Studio runtime] Failed to serve runtime", err);
if (!res.headersSent) {
res.writeHead(500);
res.end("failed to serve runtime");
}
});
});
// API middleware
server.middlewares.use(async (req, res, next) => {
if (!req.url?.startsWith("/api/")) return next();
try {
const api = await getApi();
const url = new URL(req.url, `http://${req.headers.host}`);
url.pathname = url.pathname.slice(4);
let body: Buffer | undefined;
if (req.method !== "GET" && req.method !== "HEAD") {
const bytes = await readNodeRequestBody(req);
body = bytes.byteLength > 0 ? bytes : undefined;
}
const headers: Record<string, string> = {};
for (const [key, value] of Object.entries(req.headers)) {
if (value != null) headers[key] = Array.isArray(value) ? value.join(", ") : value;
}
const fetchReq = new Request(url.toString(), {
method: req.method,
headers,
body,
});
const response = await api.fetch(fetchReq);
await bridgeHonoResponse(response, res);
} catch (err) {
console.error("[Studio API] Error:", err);
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Internal server error" }));
}
}
});
// Watch project directories for file changes → HMR
const realProjectPaths: string[] = [];
try {
for (const entry of readdirSync(dataDir, { withFileTypes: true })) {
const full = join(dataDir, entry.name);
try {
const real = lstatSync(full).isSymbolicLink() ? realpathSync(full) : full;
realProjectPaths.push(real);
server.watcher.add(real);
} catch {
/* skip broken symlinks */
}
}
} catch {
/* dataDir doesn't exist yet */
}
server.watcher.on("change", (filePath: string) => {
const isProjectFile = realProjectPaths.some((p) => isPathWithin(p, filePath));
if (
isProjectFile &&
(filePath.endsWith(".html") ||
filePath.endsWith(".css") ||
filePath.endsWith(".js") ||
filePath.endsWith(".json"))
) {
console.log(`[Studio] File changed: ${filePath}`);
const receipt = _studioServerModule?.consumeFileWriteReceipt?.(filePath) ?? null;
server.ws.send({
type: "custom",
event: "hf:file-change",
data: receipt ?? { path: filePath },
});
}
});
},
};
}
/**
* linkedom and everything only it drags in. Kept as one list so the SDK's
* HTML-parsing stack stays out of the eager `vendor` chunk — see the
* `manualChunks` rule that uses it. Adding a package here is only safe while
* nothing on the eager graph imports it; `tests/e2e/studio-bundle-budget.mjs`
* is the check that fails if that stops being true.
*/
const SDK_PARSE_DEPS =
/\/node_modules\/(linkedom|htmlparser2|domhandler|dom-serializer|domelementtype|domutils|css-select|css-what|nth-check|boolbase|entities|cssom|uhyphen)\//;
export default defineConfig({
plugins: [react(), devProjectApi()],
define: {
__STUDIO_VERSION__: JSON.stringify(studioPkg.version),
},
resolve: {
alias: {
"@hyperframes/player": resolve(__dirname, "../player/src/hyperframes-player.ts"),
"@hyperframes/studio-server/source-mutation": resolve(
__dirname,
"../studio-server/src/helpers/sourceMutation.ts",
),
},
},
build: {
outDir: "dist",
emptyOutDir: true,
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes("/node_modules/@codemirror/") || id.includes("/node_modules/@lezer/")) {
return "source-editor";
}
if (
id.includes("/node_modules/crelt/") ||
id.includes("/node_modules/style-mod/") ||
id.includes("/node_modules/w3c-keyname/")
) {
return "source-editor";
}
if (id.includes("/node_modules/marked/") || id.includes("/node_modules/dompurify/")) {
return "markdown";
}
if (id.includes("/node_modules/mediabunny/")) return "media-probe";
// linkedom + its DOM/CSS parsing deps. Reachable ONLY through the
// dynamic `import("@hyperframes/sdk")` in src/utils/sdkLazy.ts, but the
// `/node_modules/` catch-all below would still fold them into the
// modulepreloaded `vendor` chunk and undo that deferral — moving bytes
// between eager chunks is not deferral. Naming them keeps them in a
// chunk nothing eager references, so the browser fetches it on the
// first edit instead of before first paint.
if (SDK_PARSE_DEPS.test(id)) return "sdk-parse";
if (
id.includes("/node_modules/react/") ||
id.includes("/node_modules/react-dom/") ||
id.includes("/node_modules/scheduler/")
) {
return "react-vendor";
}
if (id.includes("/node_modules/")) return "vendor";
},
},
},
},
optimizeDeps: {
include: ["bpm-detective"],
},
server: {
port: 5190,
},
ssr: {
// recast / @babel/parser are CommonJS and call `require("fs")`. They are
// reachable only server-side via the Node-only `@hyperframes/parsers/gsap-parser`
// subpath (studio-api GSAP mutations + the linter), which the dev server loads
// through Vite SSR. Externalizing them makes SSR load the native Node modules
// instead of esbuild-transforming the `require` into a shim that throws
// "Dynamic require of fs is not supported". Browser bundles never reach them.
external: ["recast", "@babel/parser", "ast-types"],
},
test: {
exclude: ["data/**", "node_modules/**"],
setupFiles: ["src/test-setup.ts"],
},
});