mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 16:37:32 +00:00
fix(core): count copied stylesheets and scene scripts toward a bundle's size limit (#8573)
This commit is contained in:
@@ -63,6 +63,7 @@ const limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSI
|
||||
export const REMOTE_SCRIPTS = "remote scripts";
|
||||
export const REMOTE_STYLESHEETS = "remote stylesheets";
|
||||
export const LOCAL_SCRIPTS = "local scripts";
|
||||
export const LOCAL_STYLESHEETS = "local stylesheets";
|
||||
export const ENTRY_PAGE = "the entry page";
|
||||
|
||||
function generatedTooLarge(file: string, bytes: number): string {
|
||||
@@ -84,6 +85,12 @@ function generatedTooLarge(file: string, bytes: number): string {
|
||||
"Name each script file in one tag."
|
||||
);
|
||||
}
|
||||
if (file === LOCAL_STYLESHEETS) {
|
||||
return (
|
||||
`Local stylesheets copied into the page add up to ${megabytes(bytes)}. ${limitText}. ` +
|
||||
"Link each stylesheet once and import each file once."
|
||||
);
|
||||
}
|
||||
if (file === REMOTE_SCRIPTS || file === REMOTE_STYLESHEETS) {
|
||||
return (
|
||||
`Inlined ${file} add up to ${megabytes(bytes)}. ${limitText}. ` +
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
// @vitest-environment node
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { mkdtempSync, rmSync, symlinkSync, 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 MIB = 1024 * 1024;
|
||||
const dirs: string[] = [];
|
||||
afterAll(() => {
|
||||
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
|
||||
@@ -115,6 +116,101 @@ describe("preview bundle expansion budget", () => {
|
||||
expect(String(error)).toContain('Composition file "huge.html"');
|
||||
});
|
||||
|
||||
it("refuses one stylesheet linked past the page's size limit", async () => {
|
||||
const links = '<link rel="stylesheet" href="a.css">'.repeat(70);
|
||||
const dir = project({
|
||||
"index.html": root("").replace("<body>", `<head>${links}</head><body>`),
|
||||
"a.css": `/*${"x".repeat(MIB)}*/`,
|
||||
});
|
||||
|
||||
const error = await bundleToSingleHtml(dir, { inlineAssets: false, staticGuard: false }).catch(
|
||||
(caught: unknown) => caught,
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
code: "COMPOSITION_TOO_LARGE",
|
||||
publicMetadata: { exceeded: "generated" },
|
||||
});
|
||||
expect(String(error)).toContain("Link each stylesheet once");
|
||||
});
|
||||
|
||||
it("refuses one stylesheet imported past the page's size limit", async () => {
|
||||
const dir = project({
|
||||
"index.html": root("").replace(
|
||||
"<body>",
|
||||
'<head><link rel="stylesheet" href="a.css"></head><body>',
|
||||
),
|
||||
"a.css": '@import "b.css";\n'.repeat(70),
|
||||
"b.css": `/*${"x".repeat(MIB)}*/`,
|
||||
});
|
||||
|
||||
const error = await bundleError(dir);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
code: "COMPOSITION_TOO_LARGE",
|
||||
publicMetadata: { exceeded: "generated" },
|
||||
});
|
||||
expect(String(error)).toContain("import each file once");
|
||||
});
|
||||
|
||||
it("refuses @imports that copy the same file past the limit", async () => {
|
||||
// Each level imports the next twice: 2^11 copies of a 64 KiB sheet.
|
||||
const files: Record<string, string> = {
|
||||
"index.html": root("").replace(
|
||||
"<body>",
|
||||
'<head><link rel="stylesheet" href="s0.css"></head><body>',
|
||||
),
|
||||
"s11.css": `/*${"x".repeat(64 * 1024)}*/`,
|
||||
};
|
||||
for (let level = 0; level < 11; level += 1) {
|
||||
const next = `s${level + 1}.css`;
|
||||
files[`s${level}.css`] = `@import "${next}";\n@import url(${next}) print;\n`;
|
||||
}
|
||||
|
||||
const error = await bundleError(project(files));
|
||||
|
||||
expect(error).toMatchObject({
|
||||
code: "COMPOSITION_TOO_LARGE",
|
||||
publicMetadata: { exceeded: "generated" },
|
||||
});
|
||||
}, 30_000);
|
||||
|
||||
it.each([
|
||||
[
|
||||
"a mounted scene file",
|
||||
(tags: string) => ({ index: root(mounts("scene.html", 1)), scene: scene(tags) }),
|
||||
],
|
||||
[
|
||||
"an inline template",
|
||||
(tags: string) => ({
|
||||
index: root(
|
||||
`<template id="scene-template"><div data-composition-id="scene" data-width="320" data-height="180">${tags}</div></template>` +
|
||||
'<div data-composition-id="scene" data-start="0" data-duration="2"></div>',
|
||||
),
|
||||
scene: "",
|
||||
}),
|
||||
],
|
||||
])("refuses %s naming one script file by many names past the limit", async (_, page) => {
|
||||
const names = Array.from({ length: 70 }, (_, i) => `alias-${i}.js`);
|
||||
const { index, scene: sceneHtml } = page(
|
||||
names.map((n) => `<script src="${n}"></script>`).join(""),
|
||||
);
|
||||
const dir = project({
|
||||
"index.html": index,
|
||||
"scene.html": sceneHtml,
|
||||
"a.js": `//${"x".repeat(MIB)}`,
|
||||
});
|
||||
for (const name of names) symlinkSync(join(dir, "a.js"), join(dir, name));
|
||||
|
||||
const error = await bundleError(dir);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
code: "COMPOSITION_TOO_LARGE",
|
||||
publicMetadata: { exceeded: "generated" },
|
||||
});
|
||||
expect(String(error)).toContain("Name each script file in one tag.");
|
||||
});
|
||||
|
||||
it("still bundles a scene mounted a few times, once per mount", async () => {
|
||||
const dir = project({
|
||||
"index.html": root(mounts("wrapper.html", 3)),
|
||||
|
||||
@@ -75,6 +75,7 @@ import {
|
||||
assertCompositionFileSize,
|
||||
CompositionExpansionBudget,
|
||||
LOCAL_SCRIPTS,
|
||||
LOCAL_STYLESHEETS,
|
||||
} from "./compositionSizeLimit";
|
||||
import {
|
||||
ensureExternalLinkTag,
|
||||
@@ -286,7 +287,10 @@ function inlineCssFile(
|
||||
cssFileDir: string,
|
||||
projectDir: string,
|
||||
activeImports: Set<string>,
|
||||
budget: CompositionExpansionBudget,
|
||||
): string {
|
||||
// Charged per copy, before its imports are read: a file imported twice at every level doubles per level.
|
||||
budget.chargeGenerated(LOCAL_STYLESHEETS, Buffer.byteLength(css));
|
||||
const { stripped: strippedCss, comments: placeholders } = withCommentsStripped(css);
|
||||
const withPlaceholders = replaceMatches(
|
||||
strippedCss,
|
||||
@@ -302,7 +306,7 @@ function inlineCssFile(
|
||||
const content = safeReadFile(resolved);
|
||||
if (content == null) return full;
|
||||
activeImports.add(resolved);
|
||||
const inlined = inlineCssFile(content, dirname(resolved), projectDir, activeImports);
|
||||
const inlined = inlineCssFile(content, dirname(resolved), projectDir, activeImports, budget);
|
||||
activeImports.delete(resolved);
|
||||
const trimmedMedia = (mediaQuery || "").trim();
|
||||
const block = trimmedMedia ? `@media ${trimmedMedia} {\n${inlined}\n}\n` : inlined + "\n";
|
||||
@@ -1031,7 +1035,25 @@ function localScriptPins(
|
||||
interface SeenCompScripts {
|
||||
srcs: Set<string>;
|
||||
paths: Set<string>;
|
||||
keepsPinned: (src: string) => boolean;
|
||||
inlineFile: (src: string, js: string) => DeferredScriptChunk;
|
||||
}
|
||||
|
||||
/**
|
||||
* A local script file copied in for a composition. Charged when read, so many names for one file stop at
|
||||
* the budget; given back if a pin keeps the file external.
|
||||
*/
|
||||
function inlinedScriptFile(
|
||||
js: string,
|
||||
keepsPinned: () => boolean,
|
||||
budget: CompositionExpansionBudget,
|
||||
): DeferredScriptChunk {
|
||||
const bytes = Buffer.byteLength(js);
|
||||
budget.chargeGenerated(LOCAL_SCRIPTS, bytes);
|
||||
return () => {
|
||||
if (!keepsPinned()) return js;
|
||||
budget.chargeGenerated(LOCAL_SCRIPTS, -bytes);
|
||||
return "";
|
||||
};
|
||||
}
|
||||
|
||||
function hoistExternalScript(
|
||||
@@ -1055,7 +1077,7 @@ function hoistExternalScript(
|
||||
const js = jsPath ? readScriptOnce(jsPath) : null;
|
||||
if (jsPath && js != null) {
|
||||
seen.paths.add(jsPath);
|
||||
chunks.push(() => (seen.keepsPinned(src) ? "" : js));
|
||||
chunks.push(seen.inlineFile(src, js));
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1216,6 +1238,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
rebaseEntryAuthoredAssetPaths(document, sourceDir, projectDir);
|
||||
}
|
||||
|
||||
const budget = new CompositionExpansionBudget();
|
||||
for (const el of [...document.querySelectorAll('link[rel="stylesheet"]')]) {
|
||||
const href = el.getAttribute("href");
|
||||
if (!href || !isRelativeUrl(href) || cssStyleMergeKey(el) === undefined) continue;
|
||||
@@ -1229,7 +1252,13 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
const value = el.getAttribute(name);
|
||||
if (value !== null) style.setAttribute(name, value);
|
||||
}
|
||||
style.textContent = inlineCssFile(css, dirname(cssPath), projectDir, new Set([cssPath]));
|
||||
style.textContent = inlineCssFile(
|
||||
css,
|
||||
dirname(cssPath),
|
||||
projectDir,
|
||||
new Set([cssPath]),
|
||||
budget,
|
||||
);
|
||||
el.replaceWith(style);
|
||||
}
|
||||
|
||||
@@ -1258,7 +1287,6 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
host.hasAttribute("data-composition-src"),
|
||||
);
|
||||
const sceneSources = new Map<string, string | null>();
|
||||
const budget = new CompositionExpansionBudget();
|
||||
const subCompResult = inlineSubCompositions(document, subCompositionHosts, {
|
||||
resolveHtml: (srcPath: string) => {
|
||||
if (!isRelativeUrl(srcPath)) return null;
|
||||
@@ -1321,14 +1349,15 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
};
|
||||
const pageScriptTags = scriptTagsBySrc(document);
|
||||
const keepsEntryPinned = localScriptPins(document, resolveEntryUrl, pageScriptTags);
|
||||
const keepsCompPinned = localScriptPins(
|
||||
document,
|
||||
(value) => resolveWithinProject(projectDir, decodedUrlPath(value)),
|
||||
pageScriptTags,
|
||||
);
|
||||
const seenCompScripts: SeenCompScripts = {
|
||||
srcs: new Set(),
|
||||
paths: new Set(),
|
||||
keepsPinned: localScriptPins(
|
||||
document,
|
||||
(value) => resolveWithinProject(projectDir, decodedUrlPath(value)),
|
||||
pageScriptTags,
|
||||
),
|
||||
inlineFile: (src, js) => inlinedScriptFile(js, () => keepsCompPinned(src), budget),
|
||||
};
|
||||
const scriptFile = (src: string) => (isRelativeUrl(src) && resolveEntryUrl(src)) || src;
|
||||
const scenesByFile = new Map<string, Set<string | undefined>>();
|
||||
@@ -1359,7 +1388,11 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
const js = jsPath ? readScriptOnce(jsPath) : null;
|
||||
if (jsPath && js != null) {
|
||||
seenCompScripts.paths.add(jsPath);
|
||||
pushRun(scriptRuns, scene, () => (keepsEntryPinned(extSrc) ? "" : js));
|
||||
pushRun(
|
||||
scriptRuns,
|
||||
scene,
|
||||
inlinedScriptFile(js, () => keepsEntryPinned(extSrc), budget),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user