diff --git a/packages/core/package-subpaths.json b/packages/core/package-subpaths.json index 1ee7e64b44..2e01fd22b7 100644 --- a/packages/core/package-subpaths.json +++ b/packages/core/package-subpaths.json @@ -530,6 +530,12 @@ "types": "./dist/runtime/levelTap.d.ts", "environments": ["browser", "bun", "node"] }, + "./compiler/composition-size-limit": { + "source": "./src/compiler/compositionSizeLimit.ts", + "runtime": "./dist/compiler/compositionSizeLimit.js", + "types": "./dist/compiler/compositionSizeLimit.d.ts", + "environments": ["bun", "node"] + }, "./compiler/html-document": { "source": "./src/compiler/htmlDocument.ts", "runtime": "./dist/compiler/htmlDocument.js", diff --git a/packages/core/package.json b/packages/core/package.json index b0e11248aa..5b61a45217 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -537,6 +537,12 @@ "import": "./src/runtime/levelTap.ts", "types": "./src/runtime/levelTap.ts" }, + "./compiler/composition-size-limit": { + "bun": "./src/compiler/compositionSizeLimit.ts", + "node": "./dist/compiler/compositionSizeLimit.js", + "import": "./src/compiler/compositionSizeLimit.ts", + "types": "./src/compiler/compositionSizeLimit.ts" + }, "./compiler/html-document": { "bun": "./src/compiler/htmlDocument.ts", "node": "./dist/compiler/htmlDocument.js", @@ -1051,6 +1057,10 @@ "import": "./dist/runtime/levelTap.js", "types": "./dist/runtime/levelTap.d.ts" }, + "./compiler/composition-size-limit": { + "import": "./dist/compiler/compositionSizeLimit.js", + "types": "./dist/compiler/compositionSizeLimit.d.ts" + }, "./compiler/html-document": { "import": "./dist/compiler/htmlDocument.js", "types": "./dist/compiler/htmlDocument.d.ts" diff --git a/packages/core/src/compiler/htmlBundler.expansionBudget.test.ts b/packages/core/src/compiler/htmlBundler.expansionBudget.test.ts index e7f63b9ca4..cdb56e7e91 100644 --- a/packages/core/src/compiler/htmlBundler.expansionBudget.test.ts +++ b/packages/core/src/compiler/htmlBundler.expansionBudget.test.ts @@ -72,6 +72,20 @@ describe("preview bundle expansion budget", () => { }); }); + it("refuses mounts that copy more elements than the limit", async () => { + const dir = project({ + "index.html": root(mounts("scene.html", 60)), + "scene.html": scene("".repeat(2_000)), + }); + + const error = await bundleError(dir); + + expect(error).toMatchObject({ + code: "COMPOSITION_TOO_LARGE", + publicMetadata: { exceeded: "elements" }, + }); + }); + it("refuses scripts and styles generated for mounts past the limit", async () => { const scripts = ``.repeat( Math.ceil(MAX_EXPANDED_COMPOSITION_BYTES / 10_000), diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts index e2f4a19ad0..2919b9cb06 100644 --- a/packages/core/src/compiler/htmlBundler.ts +++ b/packages/core/src/compiler/htmlBundler.ts @@ -1226,6 +1226,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi return source; }, chargeEmitted: (srcPath: string, bytes: number) => budget.chargeGenerated(srcPath, bytes), + chargeElements: (srcPath: string, count: number) => budget.chargeElements(srcPath, count), parseHtml: parseHTMLContent, hostIdentityMap: hostIdentityByElement, rewriteInlineStyles: true, diff --git a/packages/studio-server/src/helpers/subComposition.ts b/packages/studio-server/src/helpers/subComposition.ts index d4029268c2..446ba02818 100644 --- a/packages/studio-server/src/helpers/subComposition.ts +++ b/packages/studio-server/src/helpers/subComposition.ts @@ -1,7 +1,8 @@ -import { existsSync, readFileSync } from "node:fs"; +import { existsSync, readFileSync, statSync } from "node:fs"; import { join } from "node:path"; import { parseHTML } from "linkedom"; import { firstHtmlTemplate } from "@hyperframes/parsers/sub-composition-validity"; +import { decodedUrlPath } from "@hyperframes/parsers/asset-paths"; import { rewriteAssetPaths, rewriteCssAssetUrls, @@ -15,6 +16,10 @@ import { import { findStartTags, isFullHtmlDocument } from "@hyperframes/core/compiler/html-document"; import { gsapCdnDist } from "@hyperframes/core/gsap-cdn"; import { resolveWithinProject } from "@hyperframes/core/safe-path"; +import { + assertCompositionFileSize, + CompositionExpansionBudget, +} from "@hyperframes/core/compiler/composition-size-limit"; import { TIMELINE_REGISTRY_SCRIPT } from "./authoredCode.js"; import { htmlHasGsapCore, insertGsapCoreBeforeHeadPlugin } from "./gsapCoreScript.js"; import { withRootPathsRelative } from "./rootPaths.js"; @@ -366,6 +371,7 @@ export function buildSubCompositionHtml( `${rewrittenContent}`, ); deferScriptsUntilFonts(scriptsDoc as unknown as Document); + chargeMountsTheBrowserFetches(projectDir, scriptsDoc as unknown as Document); rewrittenContent = scriptsDoc.body.innerHTML; // The comp's root carries data-composition-id but (unlike inlined sub-comps, @@ -425,6 +431,32 @@ ${rewrittenContent} `; } +function mountedFileBytes(projectDir: string, src: string): number { + const file = resolveWithinProject(projectDir, decodedUrlPath(src)); + if (!file) return 0; + assertCompositionFileSize(file, src); + try { + const stats = statSync(file); + return stats.isFile() ? stats.size : 0; + } catch { + return 0; + } +} + +function chargeMountsTheBrowserFetches(projectDir: string, doc: Document): void { + const budget = new CompositionExpansionBudget(); + const bytesBySrc = new Map(); + for (const host of doc.querySelectorAll("[data-composition-src]")) { + const src = host.getAttribute("data-composition-src") ?? ""; + let bytes = bytesBySrc.get(src); + if (bytes === undefined) { + bytes = mountedFileBytes(projectDir, src); + bytesBySrc.set(src, bytes); + } + budget.charge(src, bytes); + } +} + /** True for a real `` element; the text " 0; diff --git a/packages/studio-server/src/helpers/subCompositionBuild.ts b/packages/studio-server/src/helpers/subCompositionBuild.ts index 6920272ec8..655ecc00cd 100644 --- a/packages/studio-server/src/helpers/subCompositionBuild.ts +++ b/packages/studio-server/src/helpers/subCompositionBuild.ts @@ -25,7 +25,9 @@ export interface FinishJob { } export type SubCompositionJob = BuildJob | FinishJob; -type Result = J extends BuildJob ? { html: string; references: string[] } | null : string; +type Result = J extends BuildJob + ? { html: string; references: string[] } | { refused: string } | null + : string; export class SubCompositionDeadlineError extends Error { constructor(compPath: string) { diff --git a/packages/studio-server/src/helpers/subCompositionWorker.ts b/packages/studio-server/src/helpers/subCompositionWorker.ts index 73ffe6f768..fb7377c4e5 100644 --- a/packages/studio-server/src/helpers/subCompositionWorker.ts +++ b/packages/studio-server/src/helpers/subCompositionWorker.ts @@ -6,11 +6,21 @@ import { injectStudioPreviewAugmentations, withPreviewRuntime } from "../routes/ import { previewReferences } from "./previewReads.js"; import { injectPreviewVariables } from "./previewVariables.js"; import { withRootImportMap } from "./rootImportMap.js"; +import { isCompositionTooLargeError } from "@hyperframes/core/compiler/composition-size-limit"; import { buildSubCompositionHtml } from "./subComposition.js"; import type { BuildJob, FinishJob, SubCompositionJob } from "./subCompositionBuild.js"; +function buildOrRefuse(buildPage: () => string | null): string | { refused: string } | null { + try { + return buildPage(); + } catch (error) { + if (isCompositionTooLargeError(error)) return { refused: error.message }; + throw error; + } +} + /** The page with its runtime and the files it names, hf-ids pinned to the source's; null once the file is gone. */ -function build(job: BuildJob): { html: string; references: string[] } | null { +function build(job: BuildJob): { html: string; references: string[] } | { refused: string } | null { const { projectDir, compPath, compFile, runtimeUrl, baseHref, gsapBaseUrl } = job; let pinned: string | undefined; if (/\.html?$/i.test(compPath)) { @@ -20,15 +30,10 @@ function build(job: BuildJob): { html: string; references: string[] } | null { return null; // removed between the route's stat and this read } } - const built = buildSubCompositionHtml( - projectDir, - compPath, - runtimeUrl, - baseHref, - pinned, - gsapBaseUrl, + const built = buildOrRefuse(() => + buildSubCompositionHtml(projectDir, compPath, runtimeUrl, baseHref, pinned, gsapBaseUrl), ); - if (!built) return null; + if (typeof built !== "string") return built; const html = withPreviewRuntime(withRootImportMap(built, baseHref), runtimeUrl); return { html, references: [...previewReferences(html)] }; } diff --git a/packages/studio-server/src/routes/preview.compTooLarge.test.ts b/packages/studio-server/src/routes/preview.compTooLarge.test.ts new file mode 100644 index 0000000000..d2ddb17868 --- /dev/null +++ b/packages/studio-server/src/routes/preview.compTooLarge.test.ts @@ -0,0 +1,69 @@ +// @vitest-environment node +import { afterAll, describe, expect, it } from "vitest"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { STUDIO_PREVIEW_ERRORS } from "@hyperframes/core/studio-preview-mark"; +import { MAX_EXPANDED_COMPOSITION_BYTES } from "@hyperframes/core/compiler/composition-size-limit"; +import { createStudioApi } from "../createStudioApi"; +import type { StudioApiAdapter } from "../types"; + +const projectDir = mkdtempSync(join(tmpdir(), "hf-preview-comp-too-large-")); +afterAll(() => rmSync(projectDir, { recursive: true, force: true })); + +const mounts = (src: string, count: number) => + `
`.repeat(count); +const page = (body: string) => + ``; + +writeFileSync(join(projectDir, "index.html"), ""); +writeFileSync(join(projectDir, "leaf.html"), page("

Leaf

")); +writeFileSync(join(projectDir, "many.html"), page(mounts("leaf.html", 10_001))); +writeFileSync( + join(projectDir, "big.html"), + page(`

${"x".repeat(Math.ceil(MAX_EXPANDED_COMPOSITION_BYTES / 5))}

`), +); +writeFileSync(join(projectDir, "heavy.html"), page(mounts("big.html", 6))); +writeFileSync(join(projectDir, "heavy-encoded.html"), page(mounts("b%69g.html", 6))); +writeFileSync(join(projectDir, "few.html"), page(mounts("leaf.html", 3))); + +const adapter: StudioApiAdapter = { + listProjects: () => [], + resolveProject: async (id: string) => ({ id, dir: projectDir }), + bundle: async () => null, + lint: async () => ({ findings: [] }), + runtimeUrl: "/api/runtime.js", + rendersDir: () => join(projectDir, "renders"), + startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/out.mp4" }), +}; +const api = createStudioApi(adapter); +const open = (file: string) => api.request(`http://localhost/projects/demo/preview/comp/${file}`); + +describe("a sub-composition preview over a size limit", () => { + it("refuses a page whose mounts the browser would fetch past the mount limit", async () => { + const html = await (await open("many.html")).text(); + expect(html).toContain(`window.${STUDIO_PREVIEW_ERRORS}=["`); + expect(html).toContain("Mount large or repeated scenes fewer times"); + expect(html).not.toContain('data-composition-src="leaf.html"'); + }); + + it("refuses a page whose mounts add up past the byte limit", async () => { + const html = await (await open("heavy.html")).text(); + expect(html).toContain(`window.${STUDIO_PREVIEW_ERRORS}=["`); + expect(html).not.toContain('data-composition-src="big.html"'); + }); + + it("charges a percent-encoded src for the file the route serves for it", async () => { + const html = await (await open("heavy-encoded.html")).text(); + expect(html).toContain(`window.${STUDIO_PREVIEW_ERRORS}=["`); + expect(html).not.toContain('data-composition-src="b%69g.html"'); + }); + + it("still serves a page with a few mounts", async () => { + const res = await open("few.html"); + expect(res.status).toBe(200); + const html = await res.text(); + expect(html.split('data-composition-src="leaf.html"').length - 1).toBe(3); + expect(html).not.toContain(`window.${STUDIO_PREVIEW_ERRORS}=["`); + }); +}); diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.ts index 43f0392634..f6c3ae6f7a 100644 --- a/packages/studio-server/src/routes/preview.ts +++ b/packages/studio-server/src/routes/preview.ts @@ -111,6 +111,7 @@ import { } from "../helpers/mediaProxyPreview.js"; import { requestSubPath } from "../helpers/requestSubPath.js"; import { previewRefusalPage } from "../helpers/previewErrorPage.js"; +import { isCompositionTooLargeError } from "@hyperframes/core/compiler/composition-size-limit"; import { lazyPreviewImages } from "../helpers/lazyPreviewImages.js"; import { corsProjectVideos } from "../helpers/captureVideos.js"; import { createJobSlots, JobAbandonedError, JobQueueFullError } from "../helpers/jobSlots.js"; @@ -166,10 +167,6 @@ function parseStudioMotionManifestContent(content: string): { } /** Preview hooks must install before authored head scripts register media consumers. */ -function isCompositionTooLarge(error: unknown): error is Error { - return error instanceof Error && "code" in error && error.code === "COMPOSITION_TOO_LARGE"; -} - export function withPreviewRuntime(html: string, runtimeUrl: string): string { const tag = ``; return insertRuntimeTag(stripEmbeddedRuntimeScripts(html), tag, true); @@ -590,7 +587,7 @@ export function registerPreviewRoutes( } return bundled; } catch (error) { - if (isCompositionTooLarge(error)) return previewRefusalPage(error.message); + if (isCompositionTooLargeError(error)) return previewRefusalPage(error.message); // Re-read disk on bundle failure so we serve the latest file content, // not the pre-request snapshot that may have been saved over. const fallback = resolveProjectMainHtml(project.dir, project.id); @@ -711,6 +708,7 @@ export function registerPreviewRoutes( compPath, ); if (!built) return c.text("not found", 404); + if ("refused" in built) return c.html(previewRefusalPage(built.refused), 200); for (const path of built.references) recordPreviewRead(project.dir, path); const transformed = await withinDeadline( transformPreviewHtml(built.html, adapter, project, compPath),