mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 08:32:45 +00:00
fix(core): a page naming one script in thousands of tags builds once (#8549)
* test(core): a page naming one script in thousands of tags bundles once * fix(core): a page naming one script in thousands of tags builds once * test(core): a nomodule or data-block twin keeps the regular script, many spellings stay fast * fix(core): keep the regular script beside a nomodule twin and index script tags once * test(core): tags of many types naming one file add a bounded number of copies * fix(core): one file is inlined at most four times, whatever types its tags name * test(core): every data block keeps its text, and many copies of one file are refused * fix(core): charge each inlined script copy to the page's size limit, not a per-type cap * test(core): two data blocks of one type naming one file both keep their text * fix(core): only runnable scripts are deduplicated; every data block keeps its text
This commit is contained in:
@@ -62,6 +62,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 ENTRY_PAGE = "the entry page";
|
||||
|
||||
function generatedTooLarge(file: string, bytes: number): string {
|
||||
@@ -77,6 +78,12 @@ function generatedTooLarge(file: string, bytes: number): string {
|
||||
"Use shorter URLs or bind fewer elements."
|
||||
);
|
||||
}
|
||||
if (file === LOCAL_SCRIPTS) {
|
||||
return (
|
||||
`Local scripts copied into their tags add up to ${megabytes(bytes)}. ${limitText}. ` +
|
||||
"Name each script file in one tag."
|
||||
);
|
||||
}
|
||||
if (file === REMOTE_SCRIPTS || file === REMOTE_STYLESHEETS) {
|
||||
return (
|
||||
`Inlined ${file} add up to ${megabytes(bytes)}. ${limitText}. ` +
|
||||
|
||||
@@ -17,10 +17,11 @@ export function ensureExternalScriptTag(
|
||||
doc: Document,
|
||||
src: string,
|
||||
attributes: ExternalScriptAttributes = {},
|
||||
): void {
|
||||
const existing = [...doc.querySelectorAll("script[src]")].filter(
|
||||
(el) => el.getAttribute("src")?.trim() === src,
|
||||
);
|
||||
tagsWithSrc?: Element[],
|
||||
): Element[] {
|
||||
const existing =
|
||||
tagsWithSrc ??
|
||||
[...doc.querySelectorAll("script[src]")].filter((el) => el.getAttribute("src")?.trim() === src);
|
||||
const requirements = new Set(
|
||||
[attributes.integrity, ...existing.map((el) => el.getAttribute("integrity"))]
|
||||
.map((value) =>
|
||||
@@ -49,4 +50,5 @@ export function ensureExternalScriptTag(
|
||||
el.setAttribute("src", src);
|
||||
doc.body.appendChild(el);
|
||||
}
|
||||
return elements;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
// @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 { parseHTML } from "linkedom";
|
||||
import { SCENE_PART_ATTR } from "../sceneParts";
|
||||
import { bundleToSingleHtml } from "./htmlBundler";
|
||||
import { AFTER_FONTS_SCRIPT_TYPE } from "./scriptRuns";
|
||||
|
||||
const dirs: string[] = [];
|
||||
afterAll(() => {
|
||||
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function project(files: Record<string, string>): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hf-bundle-repeats-"));
|
||||
dirs.push(dir);
|
||||
for (const [name, text] of Object.entries(files)) writeFileSync(join(dir, name), text);
|
||||
return dir;
|
||||
}
|
||||
|
||||
const page = (scripts: string) => `<!doctype html><html><body>
|
||||
<div data-composition-id="main" data-width="320" data-height="180" data-start="0" data-duration="2"></div>
|
||||
<script>window.__timelines = {};</script>
|
||||
${scripts}
|
||||
</body></html>`;
|
||||
|
||||
const tags = (count: number, src: (i: number) => string) =>
|
||||
Array.from({ length: count }, (_, i) => `<script src="${src(i)}"></script>`).join("\n");
|
||||
|
||||
// Studio's preview build: the lint pass (staticGuard) is off there, and slow on such pages on its own.
|
||||
const PREVIEW = {
|
||||
runtime: "placeholder",
|
||||
inlineAssets: false,
|
||||
staticGuard: false,
|
||||
sceneParts: true,
|
||||
} as const;
|
||||
const FOUR_MIB = 4 * 1024 * 1024;
|
||||
const MIB = 1024 * 1024;
|
||||
|
||||
describe("a page naming one script in thousands of tags", () => {
|
||||
it("reads and inlines a 4 MiB script once for 3,000 tags", { timeout: 20_000 }, async () => {
|
||||
const body = `window.big = (window.big || 0) + 1; //${"x".repeat(FOUR_MIB)}`;
|
||||
const dir = project({ "index.html": page(tags(3_000, () => "big.js")), "big.js": body });
|
||||
const heapBefore = process.memoryUsage().heapUsed;
|
||||
const started = performance.now();
|
||||
|
||||
const html = await bundleToSingleHtml(dir, PREVIEW);
|
||||
|
||||
expect(performance.now() - started).toBeLessThan(10_000);
|
||||
expect(process.memoryUsage().heapUsed - heapBefore).toBeLessThan(256 * MIB);
|
||||
expect(html.split("window.big = ").length - 1).toBe(1);
|
||||
expect(html.length).toBeLessThan(FOUR_MIB + MIB);
|
||||
});
|
||||
|
||||
it(
|
||||
"bundles 30,000 tags naming a missing script in bounded time",
|
||||
{ timeout: 20_000 },
|
||||
async () => {
|
||||
const dir = project({ "index.html": page(tags(30_000, () => "missing.js")) });
|
||||
const started = performance.now();
|
||||
|
||||
const html = await bundleToSingleHtml(dir, PREVIEW);
|
||||
|
||||
expect(performance.now() - started).toBeLessThan(10_000);
|
||||
const { document } = parseHTML(html);
|
||||
expect(document.querySelectorAll('script[src="missing.js"]')).toHaveLength(30_000);
|
||||
},
|
||||
);
|
||||
|
||||
it("inlines a file once whatever spelling each tag uses", async () => {
|
||||
const spellings = ["a.js", "./a.js", "sub/../a.js", "a.js"];
|
||||
const dir = project({
|
||||
"index.html": page(tags(spellings.length, (i) => spellings[i]!) + tags(1, () => "b.js")),
|
||||
"a.js": "window.a = (window.a || 0) + 1;",
|
||||
"b.js": "window.b = 1;",
|
||||
});
|
||||
|
||||
const html = await bundleToSingleHtml(dir, PREVIEW);
|
||||
|
||||
expect(html.split("window.a = ").length - 1).toBe(1);
|
||||
expect(html).toContain("window.b = 1;");
|
||||
expect(html.indexOf("window.a = ")).toBeLessThan(html.indexOf("window.b = 1;"));
|
||||
});
|
||||
|
||||
it(
|
||||
"keeps every tag of a pinned script external, checking the page once",
|
||||
{ timeout: 20_000 },
|
||||
async () => {
|
||||
const dir = project({
|
||||
"index.html": page(
|
||||
tags(1, () => "pinned.js").replace("></script>", ' integrity="sha384-YQ=="></script>') +
|
||||
tags(20_000, () => "pinned.js"),
|
||||
),
|
||||
"pinned.js": "window.pinned = 1;",
|
||||
});
|
||||
const started = performance.now();
|
||||
|
||||
const html = await bundleToSingleHtml(dir, PREVIEW);
|
||||
|
||||
expect(performance.now() - started).toBeLessThan(10_000);
|
||||
expect(html).not.toContain("window.pinned = 1;");
|
||||
const { document } = parseHTML(html);
|
||||
const pinned = [...document.querySelectorAll('script[src="pinned.js"]')];
|
||||
expect(pinned).toHaveLength(20_001);
|
||||
for (const el of pinned) expect(el.getAttribute("integrity")).toBe("sha384-YQ==");
|
||||
},
|
||||
);
|
||||
|
||||
it(
|
||||
"keeps 20,000 pinned tags of one script external in bounded time",
|
||||
{ timeout: 20_000 },
|
||||
async () => {
|
||||
const dir = project({
|
||||
"index.html": page(
|
||||
tags(20_000, () => "pinned.js").replaceAll(
|
||||
"></script>",
|
||||
' integrity="sha384-YQ==" crossorigin="anonymous"></script>',
|
||||
),
|
||||
),
|
||||
"pinned.js": "window.pinned = 1;",
|
||||
});
|
||||
const started = performance.now();
|
||||
|
||||
const html = await bundleToSingleHtml(dir, PREVIEW);
|
||||
|
||||
expect(performance.now() - started).toBeLessThan(10_000);
|
||||
expect(html).not.toContain("window.pinned = 1;");
|
||||
const { document } = parseHTML(html);
|
||||
expect(document.querySelectorAll('script[src="pinned.js"][integrity]')).toHaveLength(20_000);
|
||||
},
|
||||
);
|
||||
|
||||
it("inlines a composition script once whatever spelling each scene uses", async () => {
|
||||
const host = (id: string, start: number, src = "") =>
|
||||
`<div data-composition-id="${id}"${src && ` data-composition-src="${src}"`} data-start="${start}" data-duration="1"></div>`;
|
||||
const sceneBody = (id: string, src: string) =>
|
||||
`<div data-composition-id="${id}" data-width="320" data-height="180"><script src="${src}"></script></div>`;
|
||||
const dir = project({
|
||||
"index.html": `<!doctype html><html><body>
|
||||
<div data-composition-id="main" data-width="320" data-height="180" data-start="0" data-duration="3">
|
||||
${host("a", 0, "a.html")}${host("b", 1, "b.html")}${host("c", 2)}
|
||||
</div>
|
||||
<template id="c-template">${sceneBody("c", "./lib.js")}</template>
|
||||
<script>window.__timelines = {};</script>
|
||||
</body></html>`,
|
||||
"a.html": `<template>${sceneBody("a", "lib.js")}</template>`,
|
||||
"b.html": `<template>${sceneBody("b", "l%69b.js")}</template>`,
|
||||
"lib.js": "window.lib = (window.lib || 0) + 1;",
|
||||
});
|
||||
|
||||
const html = await bundleToSingleHtml(dir, PREVIEW);
|
||||
|
||||
expect(html.split("window.lib = ").length - 1).toBe(1);
|
||||
const { document } = parseHTML(html);
|
||||
const lib = [...document.querySelectorAll("script")].find((el) =>
|
||||
el.textContent?.includes("window.lib = "),
|
||||
);
|
||||
// Both scenes name it, so it runs for the film, not inside one scene's part.
|
||||
expect(lib?.getAttribute(SCENE_PART_ATTR)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the regular script after a nomodule tag naming the same file", async () => {
|
||||
const dir = project({
|
||||
"index.html": page('<script nomodule src="a.js"></script>\n<script src="a.js"></script>'),
|
||||
"a.js": "window.a = 1;",
|
||||
});
|
||||
|
||||
const html = await bundleToSingleHtml(dir, PREVIEW);
|
||||
|
||||
const { document } = parseHTML(html);
|
||||
const copies = [...document.querySelectorAll("script")].filter((el) =>
|
||||
el.textContent?.includes("window.a = 1;"),
|
||||
);
|
||||
expect(copies).toHaveLength(2);
|
||||
const runs = (el: Element) =>
|
||||
!el.hasAttribute("nomodule") && el.getAttribute("type") === AFTER_FONTS_SCRIPT_TYPE;
|
||||
expect(copies.some(runs)).toBe(true);
|
||||
});
|
||||
|
||||
it("gives every data block naming one file its text", async () => {
|
||||
const types = ["text/plain", "application/ld+json", "application/json"];
|
||||
const dir = project({
|
||||
"index.html": page(
|
||||
types.map((type) => `<script type="${type}" src="a.json"></script>`).join("\n"),
|
||||
),
|
||||
"a.json": '{"settings":1}',
|
||||
});
|
||||
|
||||
const html = await bundleToSingleHtml(dir, PREVIEW);
|
||||
|
||||
const { document } = parseHTML(html);
|
||||
for (const type of types) {
|
||||
expect(document.querySelector(`script[type="${type}"]`)?.textContent).toBe('{"settings":1}');
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps two data blocks of one type naming one file, each with its text", async () => {
|
||||
const dir = project({
|
||||
"index.html": page(
|
||||
'<script type="application/json" id="primary" src="a.json"></script>\n' +
|
||||
'<script type="application/json" id="secondary" src="a.json"></script>',
|
||||
),
|
||||
"a.json": '{"settings":1}',
|
||||
});
|
||||
|
||||
const html = await bundleToSingleHtml(dir, PREVIEW);
|
||||
|
||||
const { document } = parseHTML(html);
|
||||
for (const id of ["primary", "secondary"]) {
|
||||
expect(document.getElementById(id)?.textContent).toBe('{"settings":1}');
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses a page whose tags copy one file past the page's size limit", async () => {
|
||||
const typed = Array.from(
|
||||
{ length: 100 },
|
||||
(_, i) => `<script type="x${i}" src="a.js"></script>`,
|
||||
);
|
||||
const dir = project({
|
||||
"index.html": page(typed.join("\n")),
|
||||
"a.js": `//${"x".repeat(MIB)}`,
|
||||
});
|
||||
|
||||
const error = await bundleToSingleHtml(dir, PREVIEW).catch((caught: unknown) => caught);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
code: "COMPOSITION_TOO_LARGE",
|
||||
publicMetadata: { exceeded: "generated" },
|
||||
});
|
||||
expect(String(error)).toContain("Name each script file in one tag.");
|
||||
});
|
||||
|
||||
it(
|
||||
"carries a pin to 20,000 spellings of its file in bounded time",
|
||||
{ timeout: 20_000 },
|
||||
async () => {
|
||||
const dir = project({
|
||||
"index.html": page(
|
||||
'<script src="pinned.js" integrity="sha384-YQ=="></script>\n' +
|
||||
tags(20_000, (i) => `pinned.js?v=${i}`),
|
||||
),
|
||||
"pinned.js": "window.pinned = 1;",
|
||||
});
|
||||
const started = performance.now();
|
||||
|
||||
const html = await bundleToSingleHtml(dir, PREVIEW);
|
||||
|
||||
expect(performance.now() - started).toBeLessThan(10_000);
|
||||
expect(html).not.toContain("window.pinned = 1;");
|
||||
const { document } = parseHTML(html);
|
||||
expect(document.querySelectorAll('script[src^="pinned.js"][integrity]')).toHaveLength(20_001);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -71,7 +71,11 @@ import {
|
||||
import { validateHyperframeHtmlContract } from "./staticGuard";
|
||||
import { getHyperframeRuntimeScript } from "../generated/runtime-inline";
|
||||
import { readDeclaredDefaults } from "../runtime/getVariables";
|
||||
import { assertCompositionFileSize, CompositionExpansionBudget } from "./compositionSizeLimit";
|
||||
import {
|
||||
assertCompositionFileSize,
|
||||
CompositionExpansionBudget,
|
||||
LOCAL_SCRIPTS,
|
||||
} from "./compositionSizeLimit";
|
||||
import {
|
||||
ensureExternalLinkTag,
|
||||
inlineSubCompositions,
|
||||
@@ -131,6 +135,7 @@ interface BundleReadScope {
|
||||
projectDir: string;
|
||||
privateFiles: BundlePrivateFiles;
|
||||
noteRead: (filePath: string) => void;
|
||||
scripts: Map<string, string | null>;
|
||||
}
|
||||
|
||||
const bundleReads = new AsyncLocalStorage<BundleReadScope>();
|
||||
@@ -156,6 +161,13 @@ function safeReadFile(filePath: string): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
function readScriptOnce(filePath: string): string | null {
|
||||
const scripts = bundleReads.getStore()?.scripts;
|
||||
if (!scripts) return safeReadFile(filePath);
|
||||
if (!scripts.has(filePath)) scripts.set(filePath, safeReadFile(filePath));
|
||||
return scripts.get(filePath) ?? null;
|
||||
}
|
||||
|
||||
const CSS_PLACEHOLDER_RE = /\/\*__hf_(?:c|import_)\d+__\*\//g;
|
||||
|
||||
export function restoreCssPlaceholders(css: string, texts: ReadonlyMap<string, string>): string {
|
||||
@@ -964,51 +976,86 @@ export type BundlePrivateFiles = "vcs-and-secrets" | "studio";
|
||||
|
||||
type DeferredScriptChunk = string | (() => string);
|
||||
|
||||
function preserveLocalScriptIntegrity(
|
||||
/** The page's script tags by `src`, collected at first use; a pin carried to a new spelling adds its tag. */
|
||||
function scriptTagsBySrc(doc: Document): () => Map<string, Element[]> {
|
||||
let index: Map<string, Element[]> | undefined;
|
||||
return () => {
|
||||
if (index) return index;
|
||||
index = new Map();
|
||||
for (const el of doc.querySelectorAll("script[src]")) {
|
||||
const src = el.getAttribute("src")?.trim() ?? "";
|
||||
const tags = index.get(src);
|
||||
if (tags) tags.push(el);
|
||||
else index.set(src, [el]);
|
||||
}
|
||||
return index;
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether a local script stays external because a tag pins its file; the page's pins are indexed once. */
|
||||
function localScriptPins(
|
||||
doc: Document,
|
||||
src: string,
|
||||
resolvePath: (src: string) => string | null,
|
||||
): boolean {
|
||||
const path = resolvePath(src);
|
||||
if (!path) return false;
|
||||
const pinned = [...doc.querySelectorAll("script[src][integrity]")].filter((el) => {
|
||||
const candidate = el.getAttribute("src") || "";
|
||||
return (
|
||||
isRelativeUrl(candidate) &&
|
||||
resolvePath(candidate) === path &&
|
||||
el.getAttribute("integrity")?.trim()
|
||||
);
|
||||
});
|
||||
for (const el of pinned) ensureExternalScriptTag(doc, src, readExternalScriptAttributes(el));
|
||||
return pinned.length > 0;
|
||||
tagsBySrc: () => Map<string, Element[]>,
|
||||
): (src: string) => boolean {
|
||||
let pins: Map<string, Map<string, ExternalScriptAttributes>> | undefined;
|
||||
const carried = new Set<string>();
|
||||
return (src) => {
|
||||
if (!pins) {
|
||||
pins = new Map();
|
||||
for (const el of doc.querySelectorAll("script[src][integrity]")) {
|
||||
const candidate = el.getAttribute("src") || "";
|
||||
if (!isRelativeUrl(candidate) || !el.getAttribute("integrity")?.trim()) continue;
|
||||
const path = resolvePath(candidate);
|
||||
if (!path) continue;
|
||||
const attributes = readExternalScriptAttributes(el);
|
||||
const key = JSON.stringify(attributes);
|
||||
const byAttributes = pins.get(path) ?? new Map<string, ExternalScriptAttributes>();
|
||||
byAttributes.delete(key);
|
||||
pins.set(path, byAttributes.set(key, attributes));
|
||||
}
|
||||
}
|
||||
const path = resolvePath(src);
|
||||
const pinned = path ? pins.get(path) : undefined;
|
||||
if (!pinned) return false;
|
||||
if (!carried.has(src)) {
|
||||
carried.add(src);
|
||||
const index = tagsBySrc();
|
||||
for (const attributes of pinned.values())
|
||||
index.set(src, ensureExternalScriptTag(doc, src, attributes, index.get(src) ?? []));
|
||||
}
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
interface SeenCompScripts {
|
||||
srcs: Set<string>;
|
||||
paths: Set<string>;
|
||||
keepsPinned: (src: string) => boolean;
|
||||
}
|
||||
|
||||
function hoistExternalScript(
|
||||
src: string,
|
||||
projectDir: string,
|
||||
doc: Document,
|
||||
seenSrcs: Set<string>,
|
||||
seen: SeenCompScripts,
|
||||
chunks: DeferredScriptChunk[],
|
||||
attributes: ExternalScriptAttributes,
|
||||
): void {
|
||||
if (attributes.integrity?.trim()) {
|
||||
ensureExternalScriptTag(doc, src, attributes);
|
||||
seenSrcs.add(src);
|
||||
seen.srcs.add(src);
|
||||
return;
|
||||
}
|
||||
if (seenSrcs.has(src)) return;
|
||||
seenSrcs.add(src);
|
||||
if (seen.srcs.has(src)) return;
|
||||
seen.srcs.add(src);
|
||||
if (!isNonRelativeUrl(src) && !isAbsolute(src) && attributes.type !== "module") {
|
||||
const jsPath = resolveWithinProject(projectDir, decodedUrlPath(src));
|
||||
const js = jsPath ? safeReadFile(jsPath) : null;
|
||||
if (js != null) {
|
||||
chunks.push(() =>
|
||||
preserveLocalScriptIntegrity(doc, src, (value) =>
|
||||
resolveWithinProject(projectDir, decodedUrlPath(value)),
|
||||
)
|
||||
? ""
|
||||
: js,
|
||||
);
|
||||
if (jsPath && seen.paths.has(jsPath)) return;
|
||||
const js = jsPath ? readScriptOnce(jsPath) : null;
|
||||
if (jsPath && js != null) {
|
||||
seen.paths.add(jsPath);
|
||||
chunks.push(() => (seen.keepsPinned(src) ? "" : js));
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1024,7 +1071,7 @@ function hoistCompositionScripts(
|
||||
runtimeScope: string | undefined;
|
||||
runtimeCompId: string | undefined;
|
||||
authoredRootId: string | undefined;
|
||||
seenCompScriptSrcs: Set<string>;
|
||||
seenCompScripts: SeenCompScripts;
|
||||
compScriptChunks: DeferredScriptChunk[];
|
||||
importMaps: ImportMap[];
|
||||
moduleScripts: string[];
|
||||
@@ -1050,7 +1097,7 @@ function hoistCompositionScripts(
|
||||
externalSrc,
|
||||
opts.projectDir,
|
||||
opts.document,
|
||||
opts.seenCompScriptSrcs,
|
||||
opts.seenCompScripts,
|
||||
opts.compScriptChunks,
|
||||
readExternalScriptAttributes(scriptEl),
|
||||
);
|
||||
@@ -1087,6 +1134,7 @@ export function bundleToSingleHtml(projectDir: string, options?: BundleOptions):
|
||||
projectDir,
|
||||
privateFiles: options?.privateFiles ?? "studio",
|
||||
noteRead,
|
||||
scripts: new Map(),
|
||||
};
|
||||
return bundleReads.run(scope, () => bundleProject(projectDir, options));
|
||||
}
|
||||
@@ -1188,16 +1236,19 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
// Read before sub-compositions add theirs: only the root's own scripts can reach into scenes.
|
||||
const rootScripts = options?.sceneParts
|
||||
? [
|
||||
...document.querySelectorAll(`script:not([${RUNTIME_BOOTSTRAP_ATTR}])`),
|
||||
...[...document.querySelectorAll("template")].flatMap((t) => [
|
||||
...(templateContent(t)?.querySelectorAll("script") ?? []),
|
||||
]),
|
||||
].map((el) => {
|
||||
const src = el.getAttribute("src");
|
||||
const path = src && isRelativeUrl(src) ? resolveEntryUrl(src) : null;
|
||||
const text = src ? (path && safeReadFile(path)) || "" : el.textContent || "";
|
||||
return isLibraryCopy(text) ? "" : text;
|
||||
})
|
||||
...new Set(
|
||||
[
|
||||
...document.querySelectorAll(`script:not([${RUNTIME_BOOTSTRAP_ATTR}])`),
|
||||
...[...document.querySelectorAll("template")].flatMap((t) => [
|
||||
...(templateContent(t)?.querySelectorAll("script") ?? []),
|
||||
]),
|
||||
].map((el) => {
|
||||
const src = el.getAttribute("src");
|
||||
const path = src && isRelativeUrl(src) ? resolveEntryUrl(src) : null;
|
||||
return src ? (path && readScriptOnce(path)) || "" : el.textContent || "";
|
||||
}),
|
||||
),
|
||||
].map((text) => (isLibraryCopy(text) ? "" : text))
|
||||
: [];
|
||||
|
||||
// Inline sub-compositions (via shared function)
|
||||
@@ -1242,7 +1293,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
tagScenes: options?.sceneParts === true,
|
||||
readProjectScript: (path: string) => {
|
||||
const resolved = isRelativeUrl(path) ? resolveEntryUrl(path) : null;
|
||||
return resolved ? safeReadFile(resolved) : null;
|
||||
return resolved ? readScriptOnce(resolved) : null;
|
||||
},
|
||||
readVariableDefaults: readDeclaredDefaults,
|
||||
parseHostVariables: parseHostVariableValues,
|
||||
@@ -1268,11 +1319,24 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
const compVariablesByComp: Record<string, Record<string, unknown>> = {
|
||||
...subCompResult.variablesByComp,
|
||||
};
|
||||
const seenCompScriptSrcs = new Set<string>();
|
||||
const scenesBySrc = new Map<string, Set<string | undefined>>();
|
||||
const pageScriptTags = scriptTagsBySrc(document);
|
||||
const keepsEntryPinned = localScriptPins(document, resolveEntryUrl, pageScriptTags);
|
||||
const seenCompScripts: SeenCompScripts = {
|
||||
srcs: new Set(),
|
||||
paths: new Set(),
|
||||
keepsPinned: localScriptPins(
|
||||
document,
|
||||
(value) => resolveWithinProject(projectDir, decodedUrlPath(value)),
|
||||
pageScriptTags,
|
||||
),
|
||||
};
|
||||
const scriptFile = (src: string) => (isRelativeUrl(src) && resolveEntryUrl(src)) || src;
|
||||
const scenesByFile = new Map<string, Set<string | undefined>>();
|
||||
for (const item of subCompResult.scriptItems)
|
||||
if (item.kind !== "inline")
|
||||
scenesBySrc.set(item.src, (scenesBySrc.get(item.src) ?? new Set()).add(item.scene));
|
||||
if (item.kind !== "inline") {
|
||||
const file = scriptFile(item.src);
|
||||
scenesByFile.set(file, (scenesByFile.get(file) ?? new Set()).add(item.scene));
|
||||
}
|
||||
for (const scriptItem of subCompResult.scriptItems) {
|
||||
if (scriptItem.kind === "inline") {
|
||||
pushRun(scriptRuns, scriptItem.scene, scriptItem.content);
|
||||
@@ -1281,20 +1345,21 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
const extSrc = scriptItem.src;
|
||||
if (scriptItem.integrity?.trim()) {
|
||||
ensureExternalScriptTag(document, extSrc, scriptItem);
|
||||
seenCompScriptSrcs.add(extSrc);
|
||||
seenCompScripts.srcs.add(extSrc);
|
||||
continue;
|
||||
}
|
||||
if (seenCompScriptSrcs.has(extSrc)) continue;
|
||||
seenCompScriptSrcs.add(extSrc);
|
||||
if (seenCompScripts.srcs.has(extSrc)) continue;
|
||||
seenCompScripts.srcs.add(extSrc);
|
||||
// Run once for the film when scenes share it: a scene mounts without the one that loaded it first.
|
||||
const scene = (scenesBySrc.get(extSrc)?.size ?? 0) > 1 ? undefined : scriptItem.scene;
|
||||
const scene =
|
||||
(scenesByFile.get(scriptFile(extSrc))?.size ?? 0) > 1 ? undefined : scriptItem.scene;
|
||||
if (isRelativeUrl(extSrc) && scriptItem.type !== "module") {
|
||||
const jsPath = resolveEntryUrl(extSrc);
|
||||
const js = jsPath ? safeReadFile(jsPath) : null;
|
||||
if (js != null) {
|
||||
const chunk = () =>
|
||||
preserveLocalScriptIntegrity(document, extSrc, resolveEntryUrl) ? "" : js;
|
||||
pushRun(scriptRuns, scene, chunk);
|
||||
if (jsPath && seenCompScripts.paths.has(jsPath)) continue;
|
||||
const js = jsPath ? readScriptOnce(jsPath) : null;
|
||||
if (jsPath && js != null) {
|
||||
seenCompScripts.paths.add(jsPath);
|
||||
pushRun(scriptRuns, scene, () => (keepsEntryPinned(extSrc) ? "" : js));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -1379,7 +1444,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
runtimeScope,
|
||||
runtimeCompId,
|
||||
authoredRootId: authoredRootId ?? undefined,
|
||||
seenCompScriptSrcs,
|
||||
seenCompScripts,
|
||||
compScriptChunks,
|
||||
importMaps: subCompResult.importMaps,
|
||||
moduleScripts: subCompResult.moduleScripts,
|
||||
@@ -1416,7 +1481,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
runtimeScope,
|
||||
runtimeCompId,
|
||||
authoredRootId: undefined,
|
||||
seenCompScriptSrcs,
|
||||
seenCompScripts,
|
||||
compScriptChunks,
|
||||
importMaps: subCompResult.importMaps,
|
||||
moduleScripts: subCompResult.moduleScripts,
|
||||
@@ -1432,17 +1497,27 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
templateEl.remove();
|
||||
}
|
||||
|
||||
// A file named by several regular (or nomodule) tags runs once, as a composition's scripts do: a copy per tag grew
|
||||
// the page past memory. Data blocks each keep their text; every copy is charged to the page's budget.
|
||||
const inlinedRootRuns = new Set<string>();
|
||||
for (const el of [...document.querySelectorAll("script[src]")]) {
|
||||
const src = el.getAttribute("src");
|
||||
if (!src || !isRelativeUrl(src)) continue;
|
||||
if (preserveLocalScriptIntegrity(document, src, resolveEntryUrl)) continue;
|
||||
if (keepsEntryPinned(src)) continue;
|
||||
// Module scripts can contain static imports whose resolution is relative
|
||||
// to the script URL. Folding their source into a classic inline script
|
||||
// both drops module semantics and changes the import base URL.
|
||||
if ((el.getAttribute("type") || "").trim().toLowerCase() === "module") continue;
|
||||
const jsPath = resolveEntryUrl(src);
|
||||
const js = jsPath ? safeReadFile(jsPath) : null;
|
||||
if (js == null) continue;
|
||||
const run = isJavaScriptType(el) ? `${el.hasAttribute("nomodule")} ${jsPath}` : null;
|
||||
if (jsPath && run !== null && inlinedRootRuns.has(run)) {
|
||||
el.remove();
|
||||
continue;
|
||||
}
|
||||
const js = jsPath ? readScriptOnce(jsPath) : null;
|
||||
if (!jsPath || js == null) continue;
|
||||
budget.chargeGenerated(LOCAL_SCRIPTS, Buffer.byteLength(js));
|
||||
if (run !== null) inlinedRootRuns.add(run);
|
||||
el.setAttribute(INLINED_FILE_ATTR, src);
|
||||
el.removeAttribute("src");
|
||||
el.textContent = js;
|
||||
|
||||
Reference in New Issue
Block a user