From 19253b3c867930ce8e2966ddb6eaecfccaf1f809 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Fri, 20 Nov 2026 21:22:17 +0000 Subject: [PATCH] fix(core): give the preview bundler the render's expansion budget (#8306) * fix(core): give the preview bundler the render's expansion budget The preview bundler inlined every sub-composition mount with only a depth limit, so a few small files that mount each other many times assembled a page without bound. The producer's expansion budget now lives in core, and the bundler charges every mount and the scripts and styles generated for it to that budget, and checks each file's size before reading it. Studio preview shows the refusal instead of falling back to the raw page, whose mounts the browser would expand the same way. * refactor: drop comments the names already carry * test(core): give the preview fan-out budget test a 30 s timeout The flake gate saw it pass 9 of 10 runs under CPU contention, timing out at the default 5 s. The neighbouring scoper bound tests use 30 s too. --- docs/guides/rendering.mdx | 2 + .../studioServer.previewTooLarge.test.ts | 51 ++++++++ packages/cli/src/server/studioServer.ts | 2 + .../src/compiler}/compositionSizeLimit.ts | 4 + .../htmlBundler.expansionBudget.test.ts | 115 ++++++++++++++++++ packages/core/src/compiler/htmlBundler.ts | 6 + packages/core/src/compiler/index.ts | 12 ++ .../services/htmlCompiler.sizeLimit.test.ts | 2 +- .../producer/src/services/htmlCompiler.ts | 2 +- .../render/stages/compileStage.test.ts | 2 +- .../services/render/stages/compileStage.ts | 2 +- .../src/helpers/previewErrorPage.ts | 11 +- .../preview.compositionTooLarge.test.ts | 56 +++++++++ packages/studio-server/src/routes/preview.ts | 8 +- 14 files changed, 268 insertions(+), 7 deletions(-) create mode 100644 packages/cli/src/server/studioServer.previewTooLarge.test.ts rename packages/{producer/src/services => core/src/compiler}/compositionSizeLimit.ts (97%) create mode 100644 packages/core/src/compiler/htmlBundler.expansionBudget.test.ts create mode 100644 packages/studio-server/src/routes/preview.compositionTooLarge.test.ts diff --git a/docs/guides/rendering.mdx b/docs/guides/rendering.mdx index 01f385d03f..8702937e16 100644 --- a/docs/guides/rendering.mdx +++ b/docs/guides/rendering.mdx @@ -418,6 +418,8 @@ A render refuses any composition HTML file, the entry or a sub-composition, that The same error refuses a render whose sub-composition mounts add up to more than 64 MB of composition HTML, to more than 10,000 mounts, or to more than 100,000 elements copied by those mounts. Every mount counts, including each repeat of the same file and each mount nested inside another. The scripts and scoped styles generated for those mounts have their own 64 MB limit. Every inline script in a mounted file is wrapped in a few kilobytes of scoping code, and every style rule is prefixed with its host's `data-composition-id`. Many tiny inline scripts, or a long composition id over many style rules, can reach this limit. Merge small scripts and rules, or keep ids short. +Studio preview and the CLI commands that assemble a project, such as `validate` and `compare`, apply the same limits with the same error. Studio shows the error in place of the preview. + Always watch the exported file itself. Preview proves that the project can play; the output file proves that the delivery is correct. diff --git a/packages/cli/src/server/studioServer.previewTooLarge.test.ts b/packages/cli/src/server/studioServer.previewTooLarge.test.ts new file mode 100644 index 0000000000..ea53839014 --- /dev/null +++ b/packages/cli/src/server/studioServer.previewTooLarge.test.ts @@ -0,0 +1,51 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import * as fs from "node:fs"; +import * as path from "node:path"; +import { STUDIO_PREVIEW_ERRORS } from "@hyperframes/core/studio-preview-mark"; +import { createStudioServer, type StudioServer } from "./studioServer.js"; +import { cleanupStudioServerRoot, makeStudioServerRoot } from "./studioServerTestFixture.js"; + +const mounts = (src: string, count: number) => + `
`.repeat( + count, + ); + +let root: string; +let projectDir: string; +let server: StudioServer; + +beforeEach(() => { + ({ root, projectDir } = makeStudioServerRoot("hf-preview-too-large-")); + // Four levels of ten: 11,110 mounts from five small files. + fs.writeFileSync( + path.join(projectDir, "index.html"), + `
${mounts("level-0.html", 10)}
`, + ); + for (let level = 0; level < 3; level += 1) { + fs.writeFileSync( + path.join(projectDir, `level-${level}.html`), + ``, + ); + } + fs.writeFileSync( + path.join(projectDir, "level-3.html"), + ``, + ); + server = createStudioServer({ projectDir, projectName: "film" }); +}); + +afterEach(() => { + cleanupStudioServerRoot(server, root); +}); + +describe("studio preview of a project over the mount limit", () => { + it("serves the refusal, not the raw page that would expand the mounts in the browser", async () => { + const response = await server.app.request("/api/projects/film/preview"); + const html = await response.text(); + + expect(html).toContain(`window.${STUDIO_PREVIEW_ERRORS}=[`); + expect(html).toContain("Mount large or repeated scenes fewer times"); + expect(html).not.toContain("

Leaf

"); + expect(html).not.toContain('data-composition-src="level-0.html"'); + }); +}); diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts index 73555f0f2a..a61d91f51c 100644 --- a/packages/cli/src/server/studioServer.ts +++ b/packages/cli/src/server/studioServer.ts @@ -613,6 +613,8 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { ); return html; } catch (err) { + const { isCompositionTooLargeError } = await import("@hyperframes/core/compiler"); + if (isCompositionTooLargeError(err)) throw err; console.error("[studio] Bundle failed:", err); return null; } diff --git a/packages/producer/src/services/compositionSizeLimit.ts b/packages/core/src/compiler/compositionSizeLimit.ts similarity index 97% rename from packages/producer/src/services/compositionSizeLimit.ts rename to packages/core/src/compiler/compositionSizeLimit.ts index d553a82951..bcd13fd2f6 100644 --- a/packages/producer/src/services/compositionSizeLimit.ts +++ b/packages/core/src/compiler/compositionSizeLimit.ts @@ -42,6 +42,10 @@ class CompositionTooLargeError extends Error { } } +export function isCompositionTooLargeError(error: unknown): error is Error { + return error instanceof Error && "code" in error && error.code === COMPOSITION_TOO_LARGE; +} + const fileTooLarge = (file: string, bytes: number) => new CompositionTooLargeError( `Composition file "${file}" is ${megabytes(bytes)}, over the ` + diff --git a/packages/core/src/compiler/htmlBundler.expansionBudget.test.ts b/packages/core/src/compiler/htmlBundler.expansionBudget.test.ts new file mode 100644 index 0000000000..e7f63b9ca4 --- /dev/null +++ b/packages/core/src/compiler/htmlBundler.expansionBudget.test.ts @@ -0,0 +1,115 @@ +// @vitest-environment node +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { MAX_COMPOSITION_HTML_BYTES, MAX_EXPANDED_COMPOSITION_BYTES } from "./compositionSizeLimit"; +import { bundleToSingleHtml } from "./htmlBundler"; + +const dirs: string[] = []; +afterAll(() => { + for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); +}); + +function project(files: Record): string { + const dir = mkdtempSync(join(tmpdir(), "hf-bundle-budget-")); + dirs.push(dir); + for (const [name, text] of Object.entries(files)) writeFileSync(join(dir, name), text); + return dir; +} + +const mounts = (src: string, count: number) => + `
`.repeat( + count, + ); + +const root = (body: string) => ` +
+${body} +
+ +`; + +const scene = (body: string) => + ``; + +const bundleError = (dir: string, onRead?: (path: string) => void) => + bundleToSingleHtml(dir, { inlineAssets: false, onRead }).then( + () => undefined, + (error: unknown) => error, + ); + +describe("preview bundle expansion budget", () => { + it("refuses small files that mount each other past the mount limit, reading each file once", async () => { + // Four levels of ten: 11,110 mounts from five small files. + const files: Record = { "index.html": root(mounts("level-0.html", 10)) }; + for (let level = 0; level < 3; level += 1) { + files[`level-${level}.html`] = scene(mounts(`level-${level + 1}.html`, 10)); + } + files["level-3.html"] = scene("

Leaf

"); + const dir = project(files); + const reads: string[] = []; + + const error = await bundleError(dir, (path) => reads.push(path)); + + expect(error).toMatchObject({ + code: "COMPOSITION_TOO_LARGE", + publicMetadata: { exceeded: "mounts" }, + }); + expect(String(error)).toContain("Mount large or repeated scenes fewer times"); + expect(reads.filter((path) => path.endsWith(".html")).length).toBe(5); + }, 30_000); + + it("refuses one large file mounted past the byte limit", async () => { + const big = scene(`

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

`); + const dir = project({ "index.html": root(mounts("big.html", 6)), "big.html": big }); + + const error = await bundleError(dir); + + expect(error).toMatchObject({ + code: "COMPOSITION_TOO_LARGE", + publicMetadata: { exceeded: "bytes" }, + }); + }); + + it("refuses scripts and styles generated for mounts past the limit", async () => { + const scripts = ``.repeat( + Math.ceil(MAX_EXPANDED_COMPOSITION_BYTES / 10_000), + ); + const dir = project({ + "index.html": root(mounts("scene.html", 1)), + "scene.html": scene(scripts), + }); + + const error = await bundleError(dir); + + expect(error).toMatchObject({ + code: "COMPOSITION_TOO_LARGE", + publicMetadata: { exceeded: "generated" }, + }); + }); + + it("refuses a sub-composition file over the per-file limit before reading it", async () => { + const dir = project({ + "index.html": root(mounts("huge.html", 1)), + "huge.html": "x".repeat(MAX_COMPOSITION_HTML_BYTES + 1), + }); + + const error = await bundleError(dir); + + expect(error).toMatchObject({ code: "COMPOSITION_TOO_LARGE" }); + expect(String(error)).toContain('Composition file "huge.html"'); + }); + + it("still bundles a scene mounted a few times, once per mount", async () => { + const dir = project({ + "index.html": root(mounts("wrapper.html", 3)), + "wrapper.html": scene(mounts("scene.html", 2)), + "scene.html": scene("

Scene

"), + }); + + const html = await bundleToSingleHtml(dir, { inlineAssets: false }); + + expect(html.split("

Scene

").length - 1).toBe(6); + }); +}); diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts index ec505e6ee7..e2f4a19ad0 100644 --- a/packages/core/src/compiler/htmlBundler.ts +++ b/packages/core/src/compiler/htmlBundler.ts @@ -71,6 +71,7 @@ import { import { validateHyperframeHtmlContract } from "./staticGuard"; import { getHyperframeRuntimeScript } from "../generated/runtime-inline"; import { readDeclaredDefaults } from "../runtime/getVariables"; +import { assertCompositionFileSize, CompositionExpansionBudget } from "./compositionSizeLimit"; import { ensureExternalLinkTag, inlineSubCompositions, @@ -1110,6 +1111,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi throw new Error(`${entryFile} not found in project directory`); } noteRead(indexPath); + assertCompositionFileSize(indexPath, entryFile); const entryHtml = readTextFile(indexPath); const mountedShell = readMountedSceneShell(projectDir, entryFile, entryHtml); const sourceDir = mountedShell ? projectDir : dirname(indexPath); @@ -1205,6 +1207,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi host.hasAttribute("data-composition-src"), ); const sceneSources = new Map(); + const budget = new CompositionExpansionBudget(); const subCompResult = inlineSubCompositions(document, subCompositionHosts, { resolveHtml: (srcPath: string) => { if (!isRelativeUrl(srcPath)) return null; @@ -1212,14 +1215,17 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi if (!compPath) return null; let source = sceneSources.get(compPath); if (source === undefined) { + if (readAllowed(compPath)) assertCompositionFileSize(compPath, srcPath); const html = safeReadFile(compPath); source = html === null ? null : readSource(html); sceneSources.set(compPath, source); } else { noteRead(compPath); } + if (source !== null) budget.charge(srcPath, Buffer.byteLength(source)); return source; }, + chargeEmitted: (srcPath: string, bytes: number) => budget.chargeGenerated(srcPath, bytes), parseHtml: parseHTMLContent, hostIdentityMap: hostIdentityByElement, rewriteInlineStyles: true, diff --git a/packages/core/src/compiler/index.ts b/packages/core/src/compiler/index.ts index 03e654d559..a0b7cdd915 100644 --- a/packages/core/src/compiler/index.ts +++ b/packages/core/src/compiler/index.ts @@ -97,6 +97,18 @@ export { wrapScopedCompositionScript, } from "./compositionScoping"; +// Size limits on one compile's expansion (shared between bundler and producer) +export { + assertCompositionFileSize, + CompositionExpansionBudget, + isCompositionTooLargeError, + MAX_COMPOSITION_HTML_BYTES, + MAX_EXPANDED_COMPOSITION_BYTES, + MAX_EXPANDED_ELEMENTS, + REMOTE_SCRIPTS, + REMOTE_STYLESHEETS, +} from "./compositionSizeLimit"; + // Sub-composition inlining (shared between bundler and producer) export { ensureExternalLinkTag, diff --git a/packages/producer/src/services/htmlCompiler.sizeLimit.test.ts b/packages/producer/src/services/htmlCompiler.sizeLimit.test.ts index 08582982ad..706b3afdc5 100644 --- a/packages/producer/src/services/htmlCompiler.sizeLimit.test.ts +++ b/packages/producer/src/services/htmlCompiler.sizeLimit.test.ts @@ -10,7 +10,7 @@ import { MAX_COMPOSITION_HTML_BYTES, MAX_EXPANDED_COMPOSITION_BYTES, MAX_EXPANDED_ELEMENTS, -} from "./compositionSizeLimit.js"; +} from "@hyperframes/core/compiler"; import { compileForRender, inlineExternalScripts, diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index 669c94b61b..c30e0fce9a 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -109,7 +109,7 @@ import { CompositionExpansionBudget, REMOTE_SCRIPTS, REMOTE_STYLESHEETS, -} from "./compositionSizeLimit.js"; +} from "@hyperframes/core/compiler"; import { escapesAssetRoot, isPathInside, diff --git a/packages/producer/src/services/render/stages/compileStage.test.ts b/packages/producer/src/services/render/stages/compileStage.test.ts index e403c69022..41972f25cb 100644 --- a/packages/producer/src/services/render/stages/compileStage.test.ts +++ b/packages/producer/src/services/render/stages/compileStage.test.ts @@ -30,7 +30,7 @@ import { type CompileStageResult, } from "./compileStage.js"; import type { RenderJob } from "../../renderOrchestrator.js"; -import { MAX_COMPOSITION_HTML_BYTES } from "../../compositionSizeLimit.js"; +import { MAX_COMPOSITION_HTML_BYTES } from "@hyperframes/core/compiler"; const noopLog = { error: () => {}, diff --git a/packages/producer/src/services/render/stages/compileStage.ts b/packages/producer/src/services/render/stages/compileStage.ts index ed34e186f6..1366059087 100644 --- a/packages/producer/src/services/render/stages/compileStage.ts +++ b/packages/producer/src/services/render/stages/compileStage.ts @@ -43,7 +43,7 @@ import { privateCacheRoot, type ChromaSubsampling, type EngineConfig } from "@hy import { suggestMatchingPreset, type CanvasResolution } from "@hyperframes/core"; import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler"; import { readTextFile } from "@hyperframes/parsers/asset-resolution"; -import { assertCompositionFileSize } from "../../compositionSizeLimit.js"; +import { assertCompositionFileSize } from "@hyperframes/core/compiler"; import type { CompiledComposition } from "../../htmlCompiler.js"; import { compileForRender } from "../../htmlCompiler.js"; import type { ProducerLogger } from "../../../logger.js"; diff --git a/packages/studio-server/src/helpers/previewErrorPage.ts b/packages/studio-server/src/helpers/previewErrorPage.ts index b2f59c1c4f..3df55c601a 100644 --- a/packages/studio-server/src/helpers/previewErrorPage.ts +++ b/packages/studio-server/src/helpers/previewErrorPage.ts @@ -3,7 +3,14 @@ import { STUDIO_PREVIEW_ERRORS, } from "@hyperframes/core/studio-preview-mark"; +const htmlText = (text: string) => + text.replace(/&/g, "&").replace(//g, ">"); + +export function previewRefusalPage(message: string): string { + const script = JSON.stringify(message).replace(/

${htmlText(message)}

`; +} + export function previewErrorPage(status: number): string { - const message = refusedPreviewMessage(status); - return `

${message}

`; + return previewRefusalPage(refusedPreviewMessage(status)); } diff --git a/packages/studio-server/src/routes/preview.compositionTooLarge.test.ts b/packages/studio-server/src/routes/preview.compositionTooLarge.test.ts new file mode 100644 index 0000000000..f3515ae4d5 --- /dev/null +++ b/packages/studio-server/src/routes/preview.compositionTooLarge.test.ts @@ -0,0 +1,56 @@ +// @vitest-environment node +import { afterEach, 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 { createStudioApi } from "../createStudioApi"; +import type { StudioApiAdapter } from "../types"; + +const dirs: string[] = []; +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +const RAW_ENTRY = `
`; + +function api(bundle: StudioApiAdapter["bundle"]) { + const project = mkdtempSync(join(tmpdir(), "hf-preview-too-large-")); + dirs.push(project); + writeFileSync(join(project, "index.html"), RAW_ENTRY); + return createStudioApi({ + listProjects: () => [], + resolveProject: async (id) => ({ id, dir: project }), + bundle, + lint: async () => ({ findings: [] }), + runtimeUrl: "/api/runtime.js", + rendersDir: () => join(project, "renders"), + startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "out.mp4" }), + }); +} + +const tooLarge = (message: string) => + Object.assign(new Error(message), { code: "COMPOSITION_TOO_LARGE" as const }); + +describe("a preview over a size limit", () => { + it("shows the refusal instead of the raw page, whose mounts the browser would expand", async () => { + const message = 'Sub-composition mounts, ending at "scene.html", add up to 64.1 MB.'; + const res = await api(async () => { + throw tooLarge(message); + }).request("http://localhost/projects/demo/preview"); + + const page = await res.text(); + expect(page).toContain(`window.${STUDIO_PREVIEW_ERRORS}=[`); + expect(page).toContain("<b>scene</b>.html"); + expect(page).not.toContain("scene"); + expect(page).not.toContain('data-composition-src="scene.html"'); + }); + + it("still falls back to the raw page for any other bundle failure", async () => { + const res = await api(async () => { + throw new Error("esbuild failed"); + }).request("http://localhost/projects/demo/preview"); + + expect(await res.text()).toContain('data-composition-src="scene.html"'); + }); +}); diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.ts index b29a7c8158..43f0392634 100644 --- a/packages/studio-server/src/routes/preview.ts +++ b/packages/studio-server/src/routes/preview.ts @@ -110,6 +110,7 @@ import { type PreviewApiAdapter, } from "../helpers/mediaProxyPreview.js"; import { requestSubPath } from "../helpers/requestSubPath.js"; +import { previewRefusalPage } from "../helpers/previewErrorPage.js"; import { lazyPreviewImages } from "../helpers/lazyPreviewImages.js"; import { corsProjectVideos } from "../helpers/captureVideos.js"; import { createJobSlots, JobAbandonedError, JobQueueFullError } from "../helpers/jobSlots.js"; @@ -165,6 +166,10 @@ 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); @@ -584,7 +589,8 @@ export function registerPreviewRoutes( if (!capture) adapter.previewDocuments?.write(builtKey, bundled); } return bundled; - } catch { + } catch (error) { + if (isCompositionTooLarge(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);