Skip to content

Write HTML. Render video. Built for agents.

fix(core): script coalescing no longer moves an inline script past a src script (#4133)

Miguel Ángel14e5f576701a
diff --git a/packages/core/src/compiler/htmlBundler.test.ts b/packages/core/src/compiler/htmlBundler.test.ts
index c9a83ffa54..4a77abd26f 100644
--- a/packages/core/src/compiler/htmlBundler.test.ts
+++ b/packages/core/src/compiler/htmlBundler.test.ts
@@ -1798,3 +1798,50 @@ it.each(["root", "sibling", "template"])(
}
},
);
+
+describe("bundleToSingleHtml script order", () => {
+ it("keeps an inline script before the src script that follows it, and one after it after", async () => {
+ const dir = makeTempProject({
+ "index.html": `<!doctype html>
+<html><body>
+ <div data-composition-id="root" data-width="320" data-height="180"></div>
+ <script>window.MARK_BEFORE = 1;</script>
+ <script src="https://cdn.example.com/needs-before.js"></script>
+ <script>window.MARK_AFTER = 1;</script>
+</body></html>`,
+ });
+ try {
+ const bundled = await bundleToSingleHtml(dir);
+ const before = bundled.indexOf("MARK_BEFORE");
+ const lib = bundled.indexOf("cdn.example.com/needs-before.js");
+ const after = bundled.indexOf("MARK_AFTER");
+ expect(before).toBeGreaterThan(-1);
+ expect(before).toBeLessThan(lib);
+ expect(lib).toBeLessThan(after);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("still merges adjacent inline scripts into one at the end of the body", async () => {
+ const dir = makeTempProject({
+ "index.html": `<!doctype html>
+<html><body>
+ <script>window.MARK_ONE = 1;</script>
+ <div data-composition-id="root" data-width="320" data-height="180"></div>
+ <script>window.MARK_TWO = 1;</script>
+</body></html>`,
+ });
+ try {
+ const bundled = await bundleToSingleHtml(dir);
+ const { document } = parseHTML(bundled);
+ const merged = [...document.querySelectorAll("body script")].filter((el) =>
+ (el.textContent || "").includes("MARK_ONE"),
+ );
+ expect(merged).toHaveLength(1);
+ expect(merged[0]!.textContent).toContain("MARK_TWO");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts
index b335355898..f48ca0952d 100644
--- a/packages/core/src/compiler/htmlBundler.ts
+++ b/packages/core/src/compiler/htmlBundler.ts
@@ -1,3 +1,4 @@
+import { inlineScriptRuns } from "./scriptRuns";
import {
ensureExternalScriptTag,
readExternalScriptAttributes,
@@ -668,20 +669,18 @@ function coalesceHeadStylesAndBodyScripts(document: Document): void {
}
}
- const bodyInlineScripts = [...document.querySelectorAll("body script")].filter((el) => {
- if (el.hasAttribute(RUNTIME_BOOTSTRAP_ATTR) || el.hasAttribute("src")) return false;
- const type = (el.getAttribute("type") || "").trim().toLowerCase();
- return !type || type === "text/javascript" || type === "application/javascript";
- });
- if (bodyInlineScripts.length > 0) {
- const mergedJs = joinJsChunks(bodyInlineScripts.map((el) => el.textContent || ""));
- for (const el of bodyInlineScripts) el.remove();
- if (mergedJs) {
- const stripped = stripJsCommentsParserSafe(mergedJs);
- const inlineScript = document.createElement("script");
- inlineScript.textContent = stripped;
- document.body.appendChild(inlineScript);
- }
+ const isPinned = (el: Element) => el.hasAttribute(RUNTIME_BOOTSTRAP_ATTR);
+ for (const { members, anchor } of inlineScriptRuns(
+ [...document.querySelectorAll("body script")],
+ isPinned,
+ )) {
+ const mergedJs = joinJsChunks(members.map((el) => el.textContent || ""));
+ for (const el of members) el.remove();
+ if (!mergedJs) continue;
+ const inlineScript = document.createElement("script");
+ inlineScript.textContent = stripJsCommentsParserSafe(mergedJs);
+ if (anchor) anchor.before(inlineScript);
+ else document.body.appendChild(inlineScript);
}
}
diff --git a/packages/core/src/compiler/index.ts b/packages/core/src/compiler/index.ts
index 8d02e655bb..a6efa13ec4 100644
--- a/packages/core/src/compiler/index.ts
+++ b/packages/core/src/compiler/index.ts
@@ -56,6 +56,9 @@ export {
stripEmbeddedRuntimeScripts,
} from "./htmlDocument";
+// Script ordering shared by the bundler and the producer coalescers
+export { inlineScriptRuns, type InlineScriptRun } from "./scriptRuns";
+
// Static guard
export {
validateHyperframeHtmlContract,
diff --git a/packages/core/src/compiler/scriptRuns.test.ts b/packages/core/src/compiler/scriptRuns.test.ts
new file mode 100644
index 0000000000..83c2eb7263
--- /dev/null
+++ b/packages/core/src/compiler/scriptRuns.test.ts
@@ -0,0 +1,52 @@
+// @vitest-environment node
+import { parseHTML } from "linkedom";
+import { describe, expect, it } from "vitest";
+import { inlineScriptRuns } from "./scriptRuns";
+
+function runsOf(bodyHtml: string, isPinned?: (el: Element) => boolean) {
+ const { document } = parseHTML(`<!doctype html><html><body>${bodyHtml}</body></html>`);
+ return inlineScriptRuns([...document.querySelectorAll("body script")], isPinned).map((run) => ({
+ members: run.members.map((el) => el.textContent),
+ anchor: run.anchor?.getAttribute("src") ?? run.anchor?.getAttribute("type") ?? run.anchor,
+ }));
+}
+
+describe("inlineScriptRuns", () => {
+ it("makes one run anchored at the end of the body when nothing separates the scripts", () => {
+ expect(runsOf("<script>a</script><div></div><script>b</script>")).toEqual([
+ { members: ["a", "b"], anchor: null },
+ ]);
+ });
+
+ it("splits at a src script and anchors the earlier run to it", () => {
+ expect(runsOf('<script>a</script><script src="x.js"></script><script>b</script>')).toEqual([
+ { members: ["a"], anchor: "x.js" },
+ { members: ["b"], anchor: null },
+ ]);
+ });
+
+ it("splits at a module script", () => {
+ expect(runsOf('<script>a</script><script type="module">m</script><script>b</script>')).toEqual([
+ { members: ["a"], anchor: "module" },
+ { members: ["b"], anchor: null },
+ ]);
+ });
+
+ it("splits at a pinned script that has no src", () => {
+ const pinned = (el: Element) => el.hasAttribute("data-pin");
+ const runs = runsOf("<script>a</script><script data-pin>p</script><script>b</script>", pinned);
+ expect(runs.map((run) => run.members)).toEqual([["a"], ["b"]]);
+ });
+
+ it("does not split at a non-executing script such as an import map or JSON data", () => {
+ expect(
+ runsOf(
+ '<script>a</script><script type="importmap">{}</script><script type="application/json">{}</script><script>b</script>',
+ ),
+ ).toEqual([{ members: ["a", "b"], anchor: null }]);
+ });
+
+ it("returns no runs when there are no inline scripts", () => {
+ expect(runsOf('<script src="x.js"></script>')).toEqual([]);
+ });
+});
diff --git a/packages/core/src/compiler/scriptRuns.ts b/packages/core/src/compiler/scriptRuns.ts
new file mode 100644
index 0000000000..7ea577ad4d
--- /dev/null
+++ b/packages/core/src/compiler/scriptRuns.ts
@@ -0,0 +1,39 @@
+export interface InlineScriptRun {
+ members: Element[];
+ /** First later script that executes on its own; the merged run must stay before it. Null: end of body. */
+ anchor: Element | null;
+}
+
+function isClassicInline(el: Element): boolean {
+ const type = (el.getAttribute("type") || "").trim().toLowerCase();
+ return !type || type === "text/javascript" || type === "application/javascript";
+}
+
+function isSeparateExecution(el: Element, isPinned: (el: Element) => boolean): boolean {
+ return (
+ el.hasAttribute("src") ||
+ isPinned(el) ||
+ (el.getAttribute("type") || "").trim().toLowerCase() === "module"
+ );
+}
+
+/** Groups body scripts into runs of classic inline scripts split by any script that executes
+ * separately (src, module, or one the caller pins in place), so merging a run never reorders it past one. */
+export function inlineScriptRuns(
+ scripts: readonly Element[],
+ isPinned: (el: Element) => boolean = () => false,
+): InlineScriptRun[] {
+ const runs: InlineScriptRun[] = [];
+ let members: Element[] = [];
+ for (const el of scripts) {
+ if (isSeparateExecution(el, isPinned)) {
+ if (members.length === 0) continue;
+ runs.push({ members, anchor: el });
+ members = [];
+ } else if (isClassicInline(el)) {
+ members.push(el);
+ }
+ }
+ if (members.length > 0) runs.push({ members, anchor: null });
+ return runs;
+}
diff --git a/packages/producer/src/services/htmlCompiler.scriptOrder.test.ts b/packages/producer/src/services/htmlCompiler.scriptOrder.test.ts
new file mode 100644
index 0000000000..165ce90dcc
--- /dev/null
+++ b/packages/producer/src/services/htmlCompiler.scriptOrder.test.ts
@@ -0,0 +1,47 @@
+// @vitest-environment node
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { compileForRender } from "./htmlCompiler.js";
+
+const tempDirs: string[] = [];
+
+afterEach(() => {
+ for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+function project(files: Record<string, string>): string {
+ const dir = mkdtempSync(join(tmpdir(), "hf-script-order-"));
+ tempDirs.push(dir);
+ for (const [relative, content] of Object.entries(files)) {
+ const path = join(dir, relative);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, content);
+ }
+ return dir;
+}
+
+// The shape glass-shard-title ships: inline setup, a local src script that reads it, inline tail.
+const INDEX = `<!doctype html>
+<html><body>
+ <div data-composition-id="root" data-width="320" data-height="180"></div>
+ <script>window.MARK_BEFORE = 1;</script>
+ <script src="assets/needs-before.js"></script>
+ <script>window.MARK_AFTER = 1;</script>
+</body></html>`;
+
+describe("compileForRender script order", () => {
+ it("does not move an inline script past the src script that follows it", async () => {
+ const dir = project({ "index.html": INDEX, "assets/needs-before.js": "void 0;" });
+ const { html } = await compileForRender(dir, join(dir, "index.html"), join(dir, ".downloads"), {
+ allowSystemFontCapture: false,
+ });
+ const before = html.indexOf("MARK_BEFORE");
+ const lib = html.indexOf("assets/needs-before.js");
+ const after = html.indexOf("MARK_AFTER");
+ expect(before).toBeGreaterThan(-1);
+ expect(before).toBeLessThan(lib);
+ expect(lib).toBeLessThan(after);
+ });
+});
diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts
index e1180d86d8..4bc79688d5 100644
--- a/packages/producer/src/services/htmlCompiler.ts
+++ b/packages/producer/src/services/htmlCompiler.ts
@@ -44,6 +44,7 @@ import {
emitRootCompositionVariableStyles,
readDeclaredDefaults,
parseHostVariableValues,
+ inlineScriptRuns,
} from "@hyperframes/core/compiler";
import {
checkSubCompositionUsability,
@@ -853,8 +854,8 @@ class ProducerHostIdentityMap extends Map<Element, BundledHostCompositionIdentit
/**
* Merge all `<head>` `<style>` blocks into a single tag with `@import` rules
- * at the top, and merge all inline `<body>` `<script>` blocks into one at the
- * end of `<body>`.
+ * at the top, and merge each run of adjacent inline `<body>` `<script>` blocks
+ * into one, without moving any of them past a `<script src>` or module script.
*
* Mirrors the bundler's `coalesceHeadStylesAndBodyScripts` to guarantee
* identical CSS cascade order and script execution order between preview and
@@ -901,26 +902,20 @@ function coalesceHeadStylesAndBodyScripts(html: string): string {
}
if (body) {
- const bodyScripts = Array.from(body.querySelectorAll("script")).filter((el) => {
- const src = (el.getAttribute("src") || "").trim();
- if (src) return false;
- const type = (el.getAttribute("type") || "").trim().toLowerCase();
- return !type || type === "text/javascript" || type === "application/javascript";
- });
- if (bodyScripts.length > 0) {
- const mergedJs = bodyScripts
+ for (const { members, anchor } of inlineScriptRuns(
+ Array.from(body.querySelectorAll("script")),
+ )) {
+ const mergedJs = members
.map((el) => (el.textContent || "").trim())
.filter(Boolean)
.join("\n;\n")
.trim();
- for (const el of bodyScripts) {
- el.remove();
- }
- if (mergedJs) {
- const script = document.createElement("script");
- script.textContent = mergedJs;
- body.appendChild(script);
- }
+ for (const el of members) el.remove();
+ if (!mergedJs) continue;
+ const script = document.createElement("script");
+ script.textContent = mergedJs;
+ if (anchor) anchor.before(script);
+ else body.appendChild(script);
}
}
@@ -2001,11 +1996,7 @@ export async function compileForRender(
abortSignal: options.abortSignal,
});
- // Download CDN scripts and inline them AFTER coalescing. This order matters:
- // coalesceHeadStylesAndBodyScripts merges inline scripts and appends them at
- // the end of <body>. If we inlined CDN scripts first, the GSAP library would
- // become an inline script that gets moved after local <script src="script.js">
- // tags that depend on it, causing "gsap is not defined" errors.
+ // CDN scripts are inlined after coalescing so they stay separate from the merged inline runs.
const assembledHtml = await inlineExternalScripts(coalescedHtml);
// Inject studio position seek re-apply script when positions are baked into HTML.