fix(studio-server): a page with thousands of script tags no longer stalls the preview (#8518)

Deciding whether a preview needs the motion-path plugin read every
script file the page loads, once per script tag, all at once, and kept
reading after the check gave up. A page naming one file in thousands of
script tags started thousands of reads and froze the server.

The check now answers "preload the plugin" at once for a page with more
than 64 script tags, reads each script file once, keeps at most 8 reads
in flight, starts none after its time is up or once a script names a
path, and cancels the reads still running when it ends.
This commit is contained in:
Miguel Ángel
2026-11-22 16:14:58 +00:00
committed by GitHub
parent 258a3cf4ea
commit 0bc7963ffd
2 changed files with 156 additions and 28 deletions
@@ -11,6 +11,8 @@ import {
withPreviewRuntime,
} from "./preview";
type ScriptFiles = NonNullable<Parameters<typeof provesNoPathTween>[3]>;
const GSAP_FILE = "/*! GSAP 3.12.5 */ window.gsap = { timeline: function () {} };";
const PLAIN_TWEEN = '<script>gsap.timeline({ paused: true }).to("#card", { x: 300 });</script>';
const LATE_PATH_TWEEN =
@@ -116,6 +118,104 @@ describe("the preview builder's proof that no script can tween along a path", ()
});
});
describe("the script scan's bounds", () => {
const tags = (srcs: string[]) => srcs.map((src) => `<script src="${src}"></script>`).join("");
const counting = (read: ScriptFiles["read"]) => {
const calls = { resolves: 0, reads: [] as string[] };
const files: ScriptFiles = {
resolve: async (base, rel) => (calls.resolves++, join(base, rel)),
read: (file, signal) => (calls.reads.push(file), read(file, signal)),
};
return { calls, files };
};
// As `readFile` does with its signal.
const untilAborted = (signal: AbortSignal) =>
new Promise<never>((_, reject) =>
signal.addEventListener("abort", () => reject(signal.reason)),
);
const scripts = (count: number) =>
Object.fromEntries(Array.from({ length: count }, (_, i) => [`s${i}.js`, GSAP_FILE]));
// fails without the fix: the scan resolved, stat'ed and read the one file once per tag.
it("answers false for a page with more script tags than it scans, reading nothing", async () => {
const { html, dir } = page(tags(Array(30_000).fill("gsap.min.js")), {
"gsap.min.js": GSAP_FILE,
});
const { calls, files } = counting(async () => GSAP_FILE);
const answer = await provesNoPathTween(html, dir, Number.POSITIVE_INFINITY, files);
expect(calls.resolves).toBe(0);
expect(calls.reads).toHaveLength(0);
expect(answer).toBe(false);
});
// fails without the fix: each tag read its file again.
it("reads each script file once, however many tags and spellings name it", async () => {
const srcs = Array.from({ length: 40 }, (_, i) => ["a.js", "./a.js", "b.js", "c.js"][i % 4]!);
const { html, dir } = page(tags(srcs), {
"a.js": GSAP_FILE,
"b.js": GSAP_FILE,
"c.js": GSAP_FILE,
});
const { calls, files } = counting(async () => GSAP_FILE);
expect(await provesNoPathTween(html, dir, Number.POSITIVE_INFINITY, files)).toBe(true);
expect(calls.reads.map((file) => file.slice(dir.length + 1)).sort()).toEqual([
"a.js",
"b.js",
"c.js",
]);
});
// fails without the fix: every tag's read started at once.
it("has at most 8 reads in flight", async () => {
const waiting: (() => void)[] = [];
let inFlight = 0;
let most = 0;
const { calls, files } = counting(
() =>
new Promise<string>((resolve) => {
most = Math.max(most, ++inFlight);
waiting.push(() => (inFlight--, resolve(GSAP_FILE)));
}),
);
const { html, dir } = page(tags(Object.keys(scripts(20))), scripts(20));
let answer: boolean | undefined;
void provesNoPathTween(html, dir, Number.POSITIVE_INFINITY, files).then((a) => (answer = a));
while (answer === undefined) {
waiting.shift()?.();
await new Promise(setImmediate);
}
expect(answer).toBe(true);
expect(calls.reads).toHaveLength(20);
expect(most).toBeLessThanOrEqual(8);
});
// fails without the fix: a read went on after the scan gave up on it.
it("aborts a read still in flight when the scan's time runs out", async () => {
const signals: (AbortSignal | undefined)[] = [];
const { files } = counting((_, signal) => {
signals.push(signal);
return untilAborted(signal);
});
const { html, dir } = page(tags(["gsap.min.js"]), { "gsap.min.js": GSAP_FILE });
expect(await provesNoPathTween(html, dir, performance.now() + 100, files)).toBe(false);
expect(signals).toHaveLength(1);
expect(signals[0]?.aborted).toBe(true);
});
// fails without the fix: every script was read even after one named a path.
it("starts no read after a script names a path, and aborts the ones in flight", async () => {
const signals: AbortSignal[] = [];
const { calls, files } = counting((file, signal) => {
signals.push(signal);
return file.endsWith("s0.js") ? Promise.resolve(LATE_PATH_TWEEN) : untilAborted(signal);
});
const { html, dir } = page(tags(Object.keys(scripts(20))), scripts(20));
expect(await provesNoPathTween(html, dir, Number.POSITIVE_INFINITY, files)).toBe(false);
expect(calls.reads.length).toBeLessThanOrEqual(8);
expect(signals.every((signal) => signal.aborted)).toBe(true);
});
});
describe("the preview's path-free mark", () => {
it("is set only when the builder proved the page path-free", () => {
const { html, dir } = page("");
+56 -28
View File
@@ -209,45 +209,49 @@ const PROJECT_PREVIEW_BASE =
const MAX_READ_SCRIPT_BYTES = 4 * 1024 * 1024;
const SCRIPT_SCAN_MS = 1000;
// A page with more script tags than this is unsure, and unsure already means it preloads the plugin.
const MAX_SCANNED_SCRIPTS = 64;
const SCRIPT_READS_IN_FLIGHT = 8;
/** How the scan reaches a project's files: both off the event loop. */
interface ScriptFiles {
resolve: (base: string, relativePath: string) => Promise<string | null>;
read: (file: string) => Promise<string>;
read: (file: string, signal: AbortSignal) => Promise<string>;
}
const projectFiles: ScriptFiles = {
resolve: resolveExistingProjectFileOff,
read: (file) => readFile(file, "utf-8"),
read: (file, signal) => readFile(file, { encoding: "utf-8", signal }),
};
async function projectScriptNamesNoPath(
src: string,
projectDir: string,
files: ScriptFiles,
): Promise<boolean> {
if (/^(?:[a-z][\w+.-]*:|\/)/i.test(src)) return false;
try {
const file = await files.resolve(projectDir, decodeURIComponent(src.split(/[?#]/)[0]!));
if (file === null) return false;
const info = await statFile(file);
if (!info.isFile() || info.size > MAX_READ_SCRIPT_BYTES) return false;
return !namesMotionPath(await files.read(file));
} catch {
return false;
}
async function fileNamesNoPath(file: string, files: ScriptFiles, signal: AbortSignal) {
const info = await statFile(file);
if (!info.isFile() || info.size > MAX_READ_SCRIPT_BYTES || signal.aborted) return false;
return !namesMotionPath(await files.read(file, signal));
}
async function scriptCannotTweenAlongPath(
tag: string,
projectDir: string,
files: ScriptFiles,
): Promise<boolean> {
function scriptTagAnswer(tag: string): boolean | { src: string } {
if (tag.includes(RUNTIME_BOOTSTRAP_ATTR)) return true;
if (/\stype\s*=\s*["']?module\b/i.test(tag)) return false;
const match = SCRIPT_SRC_ATTR.exec(tag);
if (!match) return true;
const src = (match[1] ?? match[2] ?? match[3] ?? "").replace(/&amp;/gi, "&");
return GSAP_ON_ITS_CDN.test(src) || projectScriptNamesNoPath(src, projectDir, files);
if (GSAP_ON_ITS_CDN.test(src)) return true;
return /^(?:[a-z][\w+.-]*:|\/)/i.test(src) ? false : { src };
}
async function inPool<T>(
items: Iterable<T>,
size: number,
signal: AbortSignal,
work: (item: T) => Promise<void>,
): Promise<void> {
const pending = items[Symbol.iterator]();
const worker = async () => {
for (let next = pending.next(); !next.done && !signal.aborted; next = pending.next()) {
await work(next.value);
}
};
await Promise.all(Array.from({ length: size }, worker));
}
/** True only when no script the page loads can tween along a path: the page's text and each project script it loads
@@ -265,14 +269,38 @@ export async function provesNoPathTween(
const now = performance.now();
const deadline = now + Math.min(SCRIPT_SCAN_MS, (requestDeadline - now) / 2);
if (deadline <= now) return false;
const scripts = findStartTags(html, "script").map((start) =>
scriptCannotTweenAlongPath(html.slice(start, html.indexOf(">", start) + 1), projectDir, files),
);
const tags = findStartTags(html, "script");
if (tags.length > MAX_SCANNED_SCRIPTS) return false;
const srcs = new Set<string>();
for (const start of tags) {
const answer = scriptTagAnswer(html.slice(start, html.indexOf(">", start) + 1));
if (answer === false) return false;
if (answer !== true) srcs.add(answer.src);
}
// Aborted when a script names a path or the scan ends, so it stops every read it started.
const scan = new AbortController();
const byFile = new Map<string, Promise<boolean>>();
const check = async (src: string) => {
const file = await files.resolve(projectDir, decodeURIComponent(src.split(/[?#]/)[0]!));
if (file === null) return false;
let answer = byFile.get(file);
if (!answer) byFile.set(file, (answer = fileNamesNoPath(file, files, scan.signal)));
return answer;
};
const stopUnlessNoPath = async (src: string) => {
if (!(await check(src).catch(() => false))) scan.abort();
};
try {
const answers = await withinDeadline(Promise.all(scripts), deadline, "scripts");
return answers.every(Boolean);
await withinDeadline(
inPool(srcs, SCRIPT_READS_IN_FLIGHT, scan.signal, stopUnlessNoPath),
deadline,
"scripts",
);
return !scan.signal.aborted;
} catch {
return false;
} finally {
scan.abort();
}
}