Skip to content

Write HTML. Render video. Built for agents.

158 KB
Raw Blame
// @vitest-environment node
import { mkdtempSync, writeFileSync, mkdirSync, symlinkSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { parseHTML } from "linkedom";
import { parse as parseJs } from "acorn";
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
import {
  bundleToSingleHtml,
  emitRootCompositionVariableStyles,
  parsesAsScript,
} from "./htmlBundler";
import { ensureExternalScriptTag } from "./externalScripts";
import { resetUnknownEnumWarnings } from "../runtime/getVariables";
import { sanitizeCssValue } from "../runtime/applyVariableBindings";
import { getHyperframeRuntimeScript } from "../generated/runtime-inline";
import { ensureHfIds } from "../parsers/hfIds";
import { AFTER_FONTS_SCRIPT_TYPE, AFTER_FONTS_SCRIPTS } from "./scriptRuns";

function makeTempProject(files: Record<string, string>): string {
  const dir = mkdtempSync(join(tmpdir(), "hf-bundler-test-"));
  for (const [rel, content] of Object.entries(files)) {
    const full = join(dir, rel);
    mkdirSync(join(full, ".."), { recursive: true });
    writeFileSync(full, content, "utf-8");
  }
  return dir;
}

/**
 * The data URL a correctly-resolved asset must inline to. Asserting on the
 * asset's CONTENT, not on the rewritten path string, is what proves rebasing
 * resolved to the right file: resolving from the wrong base directory finds no
 * file at all, so nothing is inlined and the assertion fails.
 */
const styleText = (html: string) =>
  [...html.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/gi)].map((m) => m[1]).join("\n");

function inlinedAs(mime: string, content: string): string {
  return `data:${mime};base64,${Buffer.from(content, "utf-8").toString("base64")}`;
}

function makeColorGradingProject(lutSrc: string, files: Record<string, string> = {}): string {
  return makeTempProject({
    "index.html": `<!doctype html>
<html><body>
  <div data-composition-id="root" data-width="320" data-height="180">
    <video
      id="clip"
      src="clip.mp4"
      data-color-grading='{"lut":{"src":"${lutSrc}","intensity":0.5}}'></video>
  </div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
    ...files,
  });
}

function readBundledColorGradingLutSrc(bundled: string): string | undefined {
  const { document } = parseHTML(bundled);
  const rawLook = document.getElementById("clip")?.getAttribute("data-color-grading") ?? "";
  const parsed = JSON.parse(rawLook) as { lut?: { src?: string } };
  return parsed.lut?.src;
}

// Mirror the repo convention (preview.test.ts): skip symlink cases on
// non-symlink-privileged Windows runners rather than crash the suite.
function tryCreateSymlink(target: string, path: string, type: "dir" | "file"): boolean {
  try {
    symlinkSync(target, path, type);
    return true;
  } catch {
    return false;
  }
}

function makeSymlinkProject(
  projectFiles: Record<string, string>,
  secretCss: string,
): { dir: string; outsideDir: string } {
  const outsideDir = mkdtempSync(join(tmpdir(), "hf-outside-"));
  writeFileSync(join(outsideDir, "secret.css"), secretCss);
  const dir = makeTempProject(projectFiles);
  symlinkSync(join(outsideDir, "secret.css"), join(dir, "evil.css"));
  return { dir, outsideDir };
}

describe("bundleToSingleHtml", () => {
  it("re-encodes physical directories when rebasing stylesheet and composition asset URLs", async () => {
    const dir = makeTempProject({
      "index.html":
        '<html><head><link rel="stylesheet" href="css%2520%23/style.css"></head><body><main data-composition-id="root" data-width="320" data-height="180"><div data-composition-id="scene" data-composition-src="scenes%20#/scene.html" data-start="0" data-duration="1"></div></main></body></html>',
      "css%20#/style.css": ".image {background:url(icon.png)}",
      "css%20#/icon.png": "stylesheet directory witness",
      "scenes%20#/scene.html":
        '<template><div data-composition-id="scene" data-width="320" data-height="180"><img src="icon%28a%29.png"></div></template>',
      "scenes%20#/icon(a).png": "composition directory witness",
    });
    try {
      const bundled = await bundleToSingleHtml(dir);
      expect(bundled).toContain(inlinedAs("image/png", "stylesheet directory witness"));
      expect(bundled).toContain(inlinedAs("image/png", "composition directory witness"));
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  it("resolves encoded URL filenames once across asset, stylesheet and script consumers", async () => {
    const dir = makeTempProject({
      "index.html":
        '<html><head><link rel="stylesheet" href="style%2520%23.css?cache=1"></head><body><main data-composition-id="root" data-width="320" data-height="180"><img src="image%2520%23.png#view"><div data-composition-id="scene" data-composition-src="scene%20.html" data-start="0" data-duration="1"></div></main><script src="app%2520%23.js?cache=1"></script></body></html>',
      "style%20#.css": '@import "base%2520%23.css"; .image {background:url(image%2520%23.png)}',
      "base%20#.css": ".decoded-import { color: blue; }",
      "image%20#.png": "encoded image witness",
      "app%20#.js": "window.encodedScriptWitness = true;",
      "scene%20.html":
        '<template><div data-composition-id="scene" data-width="320" data-height="180"><p>raw composition witness</p></div></template>',
    });
    try {
      const bundled = await bundleToSingleHtml(dir);
      expect(bundled).toContain(inlinedAs("image/png", "encoded image witness"));
      expect(bundled).toContain(".decoded-import");
      expect(bundled).toContain("window.encodedScriptWitness = true;");
      expect(bundled).toContain("raw composition witness");
      expect(bundled).not.toContain('src="app%2520%23.js');
      expect(styleText(bundled)).not.toContain("url(image%2520%23.png)");
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  it("checks project containment after decoding an asset URL", async () => {
    const dir = makeTempProject({
      "index.html":
        '<html><body><main data-composition-id="root" data-width="320" data-height="180"><img src="%2e%2e/outside.png"></main></body></html>',
    });
    const reads = new Set<string>();
    try {
      const bundled = await bundleToSingleHtml(dir, { onRead: (path) => reads.add(path) });
      expect(bundled).toContain("%2e%2e/outside.png");
      expect(reads).not.toContain(join(dir, "..", "outside.png"));
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  it("reports every project file it reads or looks for through onRead", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html><html><head>
        <link rel="stylesheet" href="style.css"><link rel="stylesheet" href="missing.css">
      </head><body>
        <div data-composition-id="root" data-width="320" data-height="180" data-start="0" data-duration="2">
          <img src="small.svg">
          <div data-composition-id="intro" data-composition-src="scenes/intro.html" data-start="0" data-duration="1"></div>
        </div>
        <script src="app.js"></script>
        <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
      </body></html>`,
      "style.css": '@import "base.css"; .a { color: red; }',
      "base.css": ".b { color: blue; }",
      "app.js": "window.appLoaded = true;",
      "small.svg": '<svg xmlns="http://www.w3.org/2000/svg"></svg>',
      "scenes/intro.html": `<template><div data-composition-id="intro" data-width="320" data-height="180">
        <link rel="stylesheet" href="intro.css"><p>intro</p></div></template>`,
      "scenes/intro.css": ".intro { color: green; }",
      "notes.md": "not part of the film",
    });
    const reads = new Set<string>();

    await bundleToSingleHtml(dir, { onRead: (file) => reads.add(file) });

    const expected = ["index.html", "style.css", "base.css", "missing.css", "app.js", "small.svg"];
    for (const file of [...expected, "scenes/intro.html", "scenes/intro.css"]) {
      expect(reads).toContain(join(dir, file));
    }
    expect(reads).not.toContain(join(dir, "notes.md"));
  });

  it("bundles a direct composition entry with paths relative to its file", async () => {
    const dir = makeTempProject({
      "index.html": "<html><body>wrong entry</body></html>",
      "compositions/scene.html": `<!doctype html><html><head><link rel="stylesheet" href="scene.css"></head><body>
        <div data-composition-id="scene" data-width="320" data-height="180">direct scene</div>
      </body></html>`,
      "compositions/scene.css": ".direct-scene { color: rgb(1, 2, 3); }",
    });

    const bundled = await bundleToSingleHtml(dir, { entryFile: "compositions/scene.html" });

    expect(bundled).toContain("direct scene");
    expect(bundled).not.toContain("wrong entry");
    expect(bundled).toContain(".direct-scene { color: rgb(1, 2, 3); }");
  });

  it("bundles a template scene entry inside the index that mounts it", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html><html><head><script src="vendor/gsap.js"></script></head><body>
        <div data-composition-id="root" data-width="320" data-height="180" data-duration="9">
          <div data-composition-id="intro" data-composition-src="compositions/intro.html" data-start="0" data-duration="3"></div>
          <div data-composition-id="scene" data-composition-src="./compositions/scene.html" data-start="3" data-duration="6"></div>
        </div>
      </body></html>`,
      "vendor/gsap.js": "window.ROOT_GSAP_LOADED = true;",
      "compositions/intro.html": `<template><div data-composition-id="intro">intro scene</div></template>`,
      "compositions/scene.html": `<template><div data-composition-id="scene" data-duration="6">
        <h1 id="title">mounted scene</h1></div></template>`,
    });

    const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
    const bundled = await bundleToSingleHtml(dir, { entryFile: "compositions/scene.html" });
    const guardWarnings = warn.mock.calls.filter(([m]) => String(m).includes("[StaticGuard]"));
    warn.mockRestore();

    expect(guardWarnings).toEqual([]);
    expect(bundled).toContain("window.ROOT_GSAP_LOADED = true;");
    expect(bundled).toContain('data-composition-id="root"');
    expect(bundled).toContain("mounted scene");
    expect(bundled).not.toContain("intro scene");
  });

  it("rebases direct-entry authored asset paths before inlining", async () => {
    const spriteSvg = '<svg xmlns="http://www.w3.org/2000/svg"><circle r="4"/></svg>';
    const bgSvg = '<svg xmlns="http://www.w3.org/2000/svg"><rect width="8" height="8"/></svg>';
    const dir = makeTempProject({
      "index.html": "<html><body>wrong entry</body></html>",
      "compositions/scene.html": `<!doctype html><html><head>
        <style>.scene { background-image: url("./bg.svg"); }</style>
      </head><body>
        <div class="scene" data-composition-id="scene" data-width="320" data-height="180" data-start="0" data-duration="1">
          <img src="./sprite.svg">
        </div>
        <script>window.__timelines = window.__timelines || {}; window.__timelines.scene = {}</script>
      </body></html>`,
      "compositions/sprite.svg": spriteSvg,
      "compositions/bg.svg": bgSvg,
    });

    const bundled = await bundleToSingleHtml(dir, { entryFile: "compositions/scene.html" });
    const spriteDataUrl = `data:image/svg+xml;base64,${Buffer.from(spriteSvg).toString("base64")}`;
    const bgDataUrl = `data:image/svg+xml;base64,${Buffer.from(bgSvg).toString("base64")}`;

    expect(bundled).toContain(`src="${spriteDataUrl}"`);
    expect(bundled).toContain(`url("${bgDataUrl}")`);
    expect(bundled).not.toContain("./sprite.svg");
    expect(bundled).not.toContain("./bg.svg");
  });

  it("preserves external SVG fragment references used by <use>", async () => {
    const spriteSvg = `<svg xmlns="http://www.w3.org/2000/svg">
      <symbol id="patch-head" viewBox="0 0 10 10"><circle cx="5" cy="5" r="4" /></symbol>
    </svg>`;
    const dir = makeTempProject({
      "index.html": `<!doctype html><html><body>
        <div data-composition-id="main" data-width="320" data-height="180" data-start="0" data-duration="1">
          <svg>
            <use id="href-use" href="assets/patch.svg#patch-head"></use>
            <use id="xlink-use" xlink:href="assets/patch.svg#patch-head"></use>
          </svg>
        </div>
        <script>window.__timelines = window.__timelines || {}; window.__timelines.main = {}</script>
      </body></html>`,
      "assets/patch.svg": spriteSvg,
    });

    const bundled = await bundleToSingleHtml(dir);
    const { document } = parseHTML(bundled);
    expect(document.getElementById("href-use")?.getAttribute("href")).toBe(
      "assets/patch.svg#patch-head",
    );
    expect(document.getElementById("xlink-use")?.getAttribute("xlink:href")).toBe(
      "assets/patch.svg#patch-head",
    );
    expect(bundled).not.toContain("data:image/svg+xml;base64");
  });

  it("does not merge author scripts into the runtime bootstrap placeholder", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <div data-composition-id="main" data-width="320" data-height="180">
    <canvas id="scene"></canvas>
  </div>
  <script>
    const canvas = document.getElementById("scene");
    window.__timelines = window.__timelines || {};
    window.__timelines.main = { duration: () => 1, seek() {}, pause() {} };
  </script>
</body></html>`,
    });

    const bundled = await bundleToSingleHtml(dir);
    const runtimeBlock = bundled.match(
      /<script\b[^>]*data-hyperframes-preview-runtime[^>]*>[\s\S]*?<\/script>/i,
    )?.[0];

    expect(runtimeBlock).toBeDefined();
    // The runtime block must contain the inlined HF runtime IIFE — bundled
    // output is self-contained, so the bundle's runtime body is loaded inline,
    // not referenced via src.
    expect(runtimeBlock).toMatch(/data-hyperframes-preview-runtime="1">/);
    expect(runtimeBlock).not.toMatch(/src=""/);
    // The author's specific composition script must NOT be merged INTO the
    // runtime tag — it stays as its own <script> elsewhere in the document.
    expect(runtimeBlock).not.toContain("window.__timelines.main = { duration:");
    expect(bundled).toContain('document.getElementById("scene")');
  });

  it("defers the root's and every mounted composition's scripts until fonts, but not the runtime", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <div data-composition-id="main" data-width="320" data-height="180">
    <div data-composition-id="scene" data-composition-src="compositions/scene.html"></div>
  </div>
  <script>window.ROOT_SCRIPT = 1;</script>
  <script type="module">window.ROOT_MODULE = 1;</script>
</body></html>`,
      "compositions/scene.html": `<template><div data-composition-id="scene" data-width="320" data-height="180">
  <script>window.SCENE_SCRIPT = 1;</script>
</div></template>`,
    });

    const { document } = parseHTML(await bundleToSingleHtml(dir));
    const deferred = [...document.querySelectorAll(AFTER_FONTS_SCRIPTS)].map(
      (el) => el.textContent,
    );
    for (const mark of ["SCENE_SCRIPT", "ROOT_SCRIPT", "ROOT_MODULE"]) {
      expect(deferred.some((text) => text?.includes(mark))).toBe(true);
    }
    expect([...document.querySelectorAll("body script")].length).toBe(deferred.length);
    const runtime = document.querySelector("script[data-hyperframes-preview-runtime]");
    expect(runtime?.getAttribute("type")).toBeNull();
  });

  it("binds a mounted composition's scripts to its own file for __hyperframes.assetUrl", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div id="blk-host" data-composition-id="blk" data-composition-src="compositions/blk/blk.html"
      data-start="0" data-duration="5"></div>
  </div>
</body></html>`,
      "compositions/blk/blk.html": `<div data-composition-id="blk" data-width="1920" data-height="1080">
  <script>window.__envUrl = __hyperframes.assetUrl("assets/env.hdr");</script>
</div>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain('var __hfCompositionSrc = "compositions/blk/blk.html";');
  });

  it("keeps a mounted file's import map and module script as such, bound to that file", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div id="blk-host" data-composition-id="blk" data-composition-src="compositions/blk/blk.html"
      data-start="0" data-duration="5"></div>
  </div>
</body></html>`,
      "compositions/blk/assets/three.js": "export const REVISION = 1;",
      "compositions/blk/assets/addons/env.js": "export const ENV = 1;",
      "compositions/blk/assets/scene.js": 'import * as THREE from "three"; export const SCENE = 1;',
      "compositions/blk/blk.html": `<div data-composition-id="blk" data-width="1920" data-height="1080">
  <script type="module" src="./assets/scene.js"></script>
  <script type="module" src="https://cdn.test/mod.js"></script>
  <script type="importmap">{ "imports": { "three": "./assets/three.js", "three/addons/": "./assets/addons/", "cdn": "https://cdn.test/x.js" } }</script>
  <script type="module">import * as THREE from "three"; window.__url = __hyperframes.assetUrl("assets/leaf.webp");</script>
  <script>window.__classic = 1;</script>
</div>`,
    });

    const { document } = parseHTML(await bundleToSingleHtml(dir));
    const importMaps = [...document.querySelectorAll('script[type="importmap"]')];
    // Deferred until fonts: the runtime runs each as the type its marker names.
    const modules = [
      ...document.querySelectorAll(`script[type="${AFTER_FONTS_SCRIPT_TYPE}+module"]`),
    ];
    const classic = [...document.querySelectorAll(`script[type="${AFTER_FONTS_SCRIPT_TYPE}"]`)].map(
      (s) => s.textContent,
    );

    expect(importMaps).toHaveLength(1);
    expect(JSON.parse(importMaps[0]!.textContent || "")).toEqual({
      imports: {
        three: "./compositions/blk/assets/three.js",
        "three/addons/": "./compositions/blk/assets/addons/",
        cdn: "https://cdn.test/x.js",
      },
    });
    expect(modules.map((m) => m.getAttribute("src")).filter(Boolean)).toEqual([
      "compositions/blk/assets/scene.js",
      "https://cdn.test/mod.js",
    ]);
    const inline = modules.filter((m) => !m.hasAttribute("src"));
    expect(inline).toHaveLength(1);
    expect(inline[0]!.textContent).toMatch(/^const __hyperframes = /);
    expect(inline[0]!.textContent).toContain('"compositions/blk/blk.html"');
    expect(inline[0]!.textContent).toContain('import * as THREE from "three";');
    expect(classic.join("")).not.toContain("SCENE");
    expect(classic.join("")).toContain(".__classic = 1;");
    expect(classic.join("")).not.toContain('"imports"');
    expect(classic.join("")).not.toContain("import * as THREE");
  });

  it("binds a <template> composition authored in a mounted file to that file", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div id="blk-host" data-composition-id="blk" data-composition-src="compositions/blk/blk.html"
      data-start="0" data-duration="5"></div>
  </div>
</body></html>`,
      "compositions/blk/blk.html": `<div data-composition-id="blk" data-width="1920" data-height="1080">
  <template id="chip-template">
    <div data-composition-id="chip" data-width="200" data-height="200">
      <script>window.__chipUrl = __hyperframes.assetUrl("assets/chip.png");</script>
    </div>
  </template>
  <div data-composition-id="chip"></div>
</div>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toMatch(
      /var __hfCompId = "chip";(?:(?!__hfCompId)[\s\S])*var __hfCompositionSrc = "compositions\/blk\/blk\.html";/,
    );
  });

  it("inlines an in-project sub-composition script but not one reached through a symlink escaping the project root", async () => {
    // Security: a shared/cloned project may carry a symlink pointing outside the
    // root (e.g. ext -> /etc). The bundler reads+inlines local assets, so it must
    // refuse to follow such a symlink and leak external file contents.
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
</head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div id="scene-host"
      data-composition-id="scene"
      data-composition-src="compositions/scene.html"
      data-start="0" data-duration="5"></div>
  </div>
  <script>window.__timelines={}; const tl=gsap.timeline({paused:true}); window.__timelines["main"]=tl;</script>
</body></html>`,
      "compositions/scene.html": `<template id="scene-template">
  <div data-composition-id="scene" data-width="1920" data-height="1080">
    <script src="assets/local.js"></script>
    <script src="ext/secret.js"></script>
    <script>
      window.__timelines = window.__timelines || {};
      window.__timelines["scene"] = gsap.timeline({ paused: true });
    </script>
  </div>
</template>`,
      "assets/local.js": `window.__HF_LOCAL__ = "LOCAL_MARKER_INLINED";`,
    });
    const external = mkdtempSync(join(tmpdir(), "hf-bundler-external-"));
    writeFileSync(join(external, "secret.js"), `window.__HF_SECRET__ = "SECRET_MARKER_LEAKED";`);
    if (!tryCreateSymlink(external, join(dir, "ext"), "dir")) return;

    const bundled = await bundleToSingleHtml(dir);

    // Positive control: the in-project sub-comp script IS inlined, so the bundler
    // would have inlined the symlinked one too had isSafePath not rejected it.
    expect(bundled).toContain("LOCAL_MARKER_INLINED");
    expect(bundled).not.toContain("SECRET_MARKER_LEAKED");
  });

  it("produces a self-contained runtime script when no HYPERFRAME_RUNTIME_URL is set", async () => {
    // Regression guard: hf#XXX. The bundler used to emit
    // <script ... src=""></script> when no runtime URL was configured. An
    // empty src resolves to the page URL itself, which Chrome flags as an
    // infinite-fetch hazard. Verify that bundleToSingleHtml inlines the
    // runtime body so the bundle is genuinely self-contained.
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <div data-composition-id="root" data-width="320" data-height="180"></div>
</body></html>`,
    });

    const previousUrl = process.env.HYPERFRAME_RUNTIME_URL;
    delete process.env.HYPERFRAME_RUNTIME_URL;
    let bundled: string;
    try {
      bundled = await bundleToSingleHtml(dir);
    } finally {
      if (previousUrl !== undefined) process.env.HYPERFRAME_RUNTIME_URL = previousUrl;
    }

    const runtimeBlock = bundled.match(
      /<script\b[^>]*data-hyperframes-preview-runtime[^>]*>[\s\S]*?<\/script>/i,
    )?.[0];
    expect(runtimeBlock).toBeDefined();
    // Must NOT have an empty src attribute (would self-fetch).
    expect(runtimeBlock).not.toMatch(/src=""/);
    // Must have a non-trivial inlined body (the runtime IIFE is ~150KB).
    const innerLength = (runtimeBlock!.match(/>([\s\S]*?)<\/script>/)?.[1] ?? "").length;
    expect(innerLength).toBeGreaterThan(1000);
  });

  it("preserves `$&` replace-pattern characters in the inlined runtime body", async () => {
    // Regression guard: `injectInterceptor` used to insert the runtime via
    // `sanitized.replace("</head>", `${tag}\n</head>`)`. `String.prototype.replace`'s
    // second argument is a substitution template — `$&` expands to the matched
    // substring (here, `</head>`). The minified runtime IIFE contains legitimate
    // `$&` sequences (e.g. `if(te&&$&!y.hasAttribute(...))`), so the bundler
    // silently injected stray `</head>` tags inside the runtime, producing a JS
    // SyntaxError that broke every timeline in the bundle. Switching to the
    // function-replacer form passes the runtime body through verbatim.
    // Use a document with an explicit `<head>` so the bundler takes the
    // `sanitized.replace("</head>", …)` injection path — the only branch that
    // exercises the substitution-template behavior. Authoring without a
    // `<head>` falls back to slice+concat (safe but doesn't catch this bug).
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div data-composition-id="root" data-width="320" data-height="180"></div>
</body></html>`,
    });

    const previousUrl = process.env.HYPERFRAME_RUNTIME_URL;
    delete process.env.HYPERFRAME_RUNTIME_URL;
    let bundled: string;
    try {
      bundled = await bundleToSingleHtml(dir);
    } finally {
      if (previousUrl !== undefined) process.env.HYPERFRAME_RUNTIME_URL = previousUrl;
    }

    const original = getHyperframeRuntimeScript();
    // Sanity: the built runtime exercises this regression (no `$&` means the
    // test would tautologically pass even with the broken implementation).
    expect(original).toContain("$&");

    const runtimeBlock = bundled.match(
      /<script\b[^>]*data-hyperframes-preview-runtime[^>]*>([\s\S]*?)<\/script>/i,
    );
    expect(runtimeBlock).not.toBeNull();
    const runtimeBody = runtimeBlock?.[1] ?? "";
    expect(runtimeBody).toBe(original);

    // Defense in depth: the entire bundled document should contain exactly one
    // `</head>` — the real closing tag. Before the fix, every `$&` in the
    // runtime expanded to an extra `</head>` inside the inlined IIFE,
    // producing a `Unexpected token '<'` SyntaxError at parse time.
    const headCloses = bundled.match(/<\/head>/g) ?? [];
    expect(headCloses.length).toBe(1);
  });

  it("preserves chunk integrity when a chunk ends with a line comment (ASI hazard guard)", async () => {
    // Regression guard for the joinJsChunks helper. If a chunk ends with `// ...`
    // and we naively appended `;` on the same line, the appended semicolon would
    // be eaten by the comment, leaving the next chunk's first statement attached
    // to the previous chunk's last expression. Verify the helper appends `\n;`
    // instead so the comment terminates and the semicolon stands alone.
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script src="local-a.js"></script>
  <script src="local-b.js"></script>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      // Chunk A ends with a // line comment — without the \n separator before
      // the appended ;, that ; would be eaten by the comment.
      "local-a.js": "window.__a = 1 // trailing line comment",
      "local-b.js": "window.__b = 2",
    });

    const bundled = await bundleToSingleHtml(dir);
    // Run every inline script body through esbuild; if the line comment ate
    // the separator, parse would fail with an unexpected-token error somewhere
    // around the chunk boundary. Use a real HTML parser (CodeQL flags regex-
    // based script extraction as bad-tag-filter).
    const { transformSync } = await import("esbuild");
    const { document } = parseHTML(bundled);
    for (const script of document.querySelectorAll("script")) {
      const body = script.textContent;
      if (!body || !body.trim()) continue;
      expect(() => transformSync(body, { loader: "js", minify: false })).not.toThrow();
    }
  });

  it("does not produce stray bare-semicolon lines between concatenated JS chunks", async () => {
    // Regression guard: hf#XXX. Earlier the bundler joined script chunks with
    // `\n;\n`, which produces a lone `;` on its own line between chunks. Valid
    // JS but reads as a code smell. Each chunk should end in `;` and chunks
    // should join with `\n`.
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <div data-composition-id="root" data-width="320" data-height="180">
    <div id="child-host"
         data-composition-id="child"
         data-composition-src="compositions/child.html"
         data-start="0" data-duration="2"></div>
  </div>
  <script src="local-a.js"></script>
  <script src="local-b.js"></script>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "local-a.js": "window.__a = 1",
      "local-b.js": "window.__b = 2",
      "compositions/child.html": `<template id="child-template">
  <div data-composition-id="child" data-width="320" data-height="180">
    <script>window.__c = 3</script>
  </div>
</template>`,
    });

    const bundled = await bundleToSingleHtml(dir);
    // No line is JUST a bare semicolon (with optional surrounding whitespace).
    expect(bundled).not.toMatch(/\n\s*;\s*\n/);
  });

  it("hoists external CDN scripts from sub-compositions into the bundle", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
</head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div id="rockets-host"
      data-composition-id="rockets"
      data-composition-src="compositions/rockets.html"
      data-start="0" data-duration="2"></div>
  </div>
  <script>window.__timelines={}; const tl=gsap.timeline({paused:true}); window.__timelines["main"]=tl;</script>
</body></html>`,
      "compositions/rockets.html": `<template id="rockets-template">
  <div data-composition-id="rockets" data-width="1920" data-height="1080">
    <div id="rocket-container"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lottie-web/5.12.2/lottie.min.js"></script>
    <script>
      window.__timelines = window.__timelines || {};
      const anim = lottie.loadAnimation({ container: document.querySelector("#rocket-container"), path: "rocket.json" });
      window.__timelines["rockets"] = gsap.timeline({ paused: true });
    </script>
  </div>
</template>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    // Lottie CDN script from sub-composition must be present in the bundle
    expect(bundled).toContain(
      "https://cdnjs.cloudflare.com/ajax/libs/lottie-web/5.12.2/lottie.min.js",
    );

    // Should only appear once (deduped)
    const occurrences = (bundled.match(/cdnjs\.cloudflare\.com\/ajax\/libs\/lottie-web/g) ?? [])
      .length;
    expect(occurrences).toBe(1);

    // GSAP CDN from main doc should still be present
    expect(bundled).toContain("cdn.jsdelivr.net/npm/gsap");

    // data-composition-src should be stripped from the host element (composition
    // was inlined). The literal string may still appear inside the inlined
    // runtime IIFE that knows how to look up that attribute — so check the DOM,
    // not the raw text.
    const { document: doc } = parseHTML(bundled);
    const hostEl = doc.getElementById("rockets-host");
    expect(hostEl).toBeTruthy();
    expect(hostEl?.hasAttribute("data-composition-src")).toBe(false);
  });

  it("inlines local scripts referenced by sub-compositions into the bundle", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
</head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div id="scene-host"
      data-composition-id="scene"
      data-composition-src="compositions/scene.html"
      data-start="0" data-duration="5"></div>
  </div>
  <script>window.__timelines={}; const tl=gsap.timeline({paused:true}); window.__timelines["main"]=tl;</script>
</body></html>`,
      "compositions/scene.html": `<template id="scene-template">
  <div data-composition-id="scene" data-width="1920" data-height="1080">
    <div id="scene-copy">Scene</div>
    <script src="vendor/effect-plugin.js"></script>
    <script src="assets/scene-runtime.js"></script>
    <script>
      window.__timelines = window.__timelines || {};
      window.__timelines["scene"] = gsap.timeline({ paused: true });
    </script>
  </div>
</template>`,
      "vendor/effect-plugin.js": `window.PowerGlitch = { glitch(){ return { startGlitch(){}, stopGlitch(){} }; } };`,
      "assets/scene-runtime.js": `window.__HF_SHARED_TEST__ = "shared-runtime-loaded";`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain('__HF_SHARED_TEST__ = "shared-runtime-loaded"');
    expect(bundled).toContain("window.PowerGlitch = { glitch()");
    expect(bundled).not.toContain('src="assets/scene-runtime.js"');
    expect(bundled).not.toContain('src="vendor/effect-plugin.js"');
  });

  it("preserves local module scripts and their import base URL", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html><html><body>
        <div data-composition-id="main" data-start="0" data-duration="1"></div>
        <script type="module" src="./module.js"></script>
      </body></html>`,
      "module.js": `import { value } from "./value.js"; window.result = value;`,
      "value.js": `export const value = "loaded";`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toMatch(
      /<script\b[^>]*\btype="text\/hf-after-fonts\+module"[^>]*\bsrc="\.\/module\.js"/,
    );
    expect(bundled).not.toContain('import { value } from "./value.js"');
  });

  it("preserves local sub-composition script order before inline scene scripts", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
</head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div
      id="scene-host"
      data-composition-id="scene"
      data-composition-src="compositions/scene.html"
      data-start="0" data-duration="5"></div>
  </div>
  <script>window.__timelines={}; const tl=gsap.timeline({paused:true}); window.__timelines["main"]=tl;</script>
</body></html>`,
      "compositions/scene.html": `<template id="scene-template">
  <div data-composition-id="scene" data-width="1920" data-height="1080">
    <script src="assets/component-runtime.js"></script>
    <script>
      window.__HF_COMPONENT_CALL__ = true;
      window.Component.mount("#scene-host");
    </script>
  </div>
</template>`,
      "assets/component-runtime.js": `window.__HF_COMPONENT_DEF__ = true; window.Component = { mount(){ window.__HF_COMPONENT_MOUNTED__ = true; } };`,
    });

    const bundled = await bundleToSingleHtml(dir);
    const componentIndex = bundled.indexOf("__HF_COMPONENT_DEF__");
    const sceneIndex = bundled.indexOf("__HF_COMPONENT_CALL__");

    expect(componentIndex).toBeGreaterThan(-1);
    expect(sceneIndex).toBeGreaterThan(-1);
    expect(componentIndex).toBeLessThan(sceneIndex);
  });

  it("does not duplicate CDN scripts already present in the main document", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
</head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div id="child-host"
      data-composition-id="child"
      data-composition-src="compositions/child.html"
      data-start="0" data-duration="5"></div>
  </div>
  <script>window.__timelines={}; const tl=gsap.timeline({paused:true}); window.__timelines["main"]=tl;</script>
</body></html>`,
      "compositions/child.html": `<template id="child-template">
  <div data-composition-id="child" data-width="1920" data-height="1080">
    <div id="stage"></div>
    <!-- Same GSAP CDN as parent — should not be duplicated -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
    <script>
      window.__timelines = window.__timelines || {};
      window.__timelines["child"] = gsap.timeline({ paused: true });
    </script>
  </div>
</template>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    // GSAP CDN should appear exactly once (deduped)
    const gsapOccurrences = (
      bundled.match(/cdn\.jsdelivr\.net\/npm\/gsap@3\.14\.2\/dist\/gsap\.min\.js/g) ?? []
    ).length;
    expect(gsapOccurrences).toBe(1);
  });

  it("inlines <template> compositions into matching empty host elements", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
</head><body>
  <template id="logo-reveal-template">
    <div data-composition-id="logo-reveal" data-width="1920" data-height="1080">
      <style>.logo { opacity: 0; }</style>
      <div class="logo">Logo Here</div>
      <script>
        window.__timelines = window.__timelines || {};
        window.__timelines["logo-reveal"] = gsap.timeline({ paused: true });
      </script>
    </div>
  </template>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div id="logo-host"
      data-composition-id="logo-reveal"
      data-start="0" data-duration="5"
      data-track-index="1"></div>
  </div>
  <script>window.__timelines={}; const tl=gsap.timeline({paused:true}); window.__timelines["main"]=tl;</script>
</body></html>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    // Template element should be removed
    expect(bundled).not.toContain("<template");

    // Host should contain the template content (the logo div)
    expect(bundled).toContain("Logo Here");

    // Styles from template should be hoisted
    expect(bundled).toContain(".logo");

    // Scripts from template should be included
    expect(bundled).toContain('__timelines["logo-reveal"]');
  });

  it("does not inline template when host already has content", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <template id="comp-template">
    <div data-composition-id="comp" data-width="800" data-height="600">
      <p>Template content</p>
    </div>
  </template>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div data-composition-id="comp" data-start="0" data-duration="5">
      <span>Already filled</span>
    </div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    // Existing content should be preserved
    expect(bundled).toContain("Already filled");

    // Template content should NOT replace the existing host content
    // (template element may still exist in the output since it was not consumed)
    const hostMatch = bundled.match(
      /data-composition-id="comp"[^>]*data-start="0"[^>]*>([\s\S]*?)<\/div>/,
    );
    expect(hostMatch).toBeTruthy();
    expect(hostMatch![1]).toContain("Already filled");
    expect(hostMatch![1]).not.toContain("Template content");
  });

  it("copies dimension attributes from inline template to host", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <template id="sized-template">
    <div data-composition-id="sized" data-width="800" data-height="600">
      <p>Sized content</p>
    </div>
  </template>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div data-composition-id="sized" data-start="0" data-duration="3"></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    // The host should have dimensions copied from the template inner root
    expect(bundled).toContain('data-width="800"');
    expect(bundled).toContain('data-height="600"');
    expect(bundled).toContain("Sized content");
  });

  it("flattens the sub-composition root onto the host when inlining external compositions", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div
      id="scene-host"
      data-composition-id="scene"
      data-composition-src="compositions/scene.html"
      data-start="intro"
      data-duration="5"></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/scene.html": `<template id="scene-template">
  <div data-composition-id="scene" data-start="0" data-width="1920" data-height="1080">
    <style>[data-composition-id="scene"][data-start="0"] .title { opacity: 0; }</style>
    <h1 class="title">Scene</h1>
    <script>
      window.__timelines = window.__timelines || {};
      const root = document.querySelector('[data-composition-id="scene"][data-start="0"]');
      window.__timelines["scene"] = { root };
    </script>
  </div>
</template>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    const { document } = parseHTML(bundled);
    const host = document.querySelector("#scene-host");

    expect(host?.getAttribute("data-composition-id")).toBe("scene");
    expect(host?.getAttribute("data-composition-file")).toBe("compositions/scene.html");
    expect(host?.getAttribute("data-start")).toBe("intro");
    expect(host?.getAttribute("data-width")).toBe("1920");
    expect(host?.querySelector(".title")?.textContent).toBe("Scene");
    expect(host?.querySelector(".title")?.closest("[data-composition-file]")).toBe(host);
    expect(
      Array.from(host?.children ?? []).some(
        (child) => child.getAttribute("data-composition-id") === "scene",
      ),
    ).toBe(false);
    expect(bundled).toContain('[data-composition-id="scene"] .title');
    expect(bundled).toContain("__hfNormalizeSelector");
  });

  it("keeps an authored inner root wrapper for root id and class selectors", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div
      id="scene-host"
      data-composition-id="scene"
      data-composition-src="compositions/scene.html"
      data-start="0"
      data-duration="5"></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/scene.html": `<template id="scene-template">
  <div id="scene-root" class="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
    <style>
      .scene-root .title { opacity: 0; }
      #scene-root { font-family: Inter, sans-serif; }
    </style>
    <h1 class="title">Scene</h1>
  </div>
</template>`,
    });

    const bundled = await bundleToSingleHtml(dir);
    const { document } = parseHTML(bundled);
    const host = document.querySelector("#scene-host");
    const authoredRoot = host?.querySelector('[data-hf-authored-id="scene-root"]');

    expect(host).toBeTruthy();
    expect(authoredRoot).toBeTruthy();
    expect(authoredRoot?.id).toBe("");
    expect(authoredRoot?.getAttribute("data-composition-id")).toBeNull();
    expect(authoredRoot?.getAttribute("data-hf-inner-root")).toBe("true");
    expect(authoredRoot?.getAttribute("data-hf-authored-id")).toBe("scene-root");
    expect(bundled).toContain('[data-composition-id="scene"] .scene-root .title');
    expect(bundled).toContain('[data-composition-id="scene"] [data-hf-authored-id="scene-root"]');
  });

  it("does not keep duplicate authored root ids when the same external composition mounts twice", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div
      id="scene-host-a"
      data-composition-id="scene"
      data-composition-src="compositions/scene.html"
      data-start="0"
      data-duration="5"></div>
    <div
      id="scene-host-b"
      data-composition-id="scene"
      data-composition-src="compositions/scene.html"
      data-start="5"
      data-duration="5"></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/scene.html": `<template id="scene-template">
  <div id="scene-root" class="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
    <h1 class="title">Scene</h1>
  </div>
</template>`,
    });

    const bundled = await bundleToSingleHtml(dir);
    const { document } = parseHTML(bundled);
    const authoredRoots = document.querySelectorAll('[data-hf-authored-id="scene-root"]');

    expect(authoredRoots).toHaveLength(2);
    expect(document.querySelectorAll("#scene-root")).toHaveLength(0);
    expect(Array.from(authoredRoots).every((root) => !root.getAttribute("id"))).toBe(true);
  });

  it("mounts duplicate inline-template hosts instead of only the first one", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div id="scene-host-a" data-composition-id="scene"></div>
    <div id="scene-host-b" data-composition-id="scene"></div>
  </div>
  <template id="scene-template">
    <div id="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
      <h1 class="title">Scene</h1>
    </div>
  </template>
  <script>window.__timelines={};</script>
</body></html>`,
    });

    const bundled = await bundleToSingleHtml(dir);
    const { document } = parseHTML(bundled);
    const hostA = document.querySelector("#scene-host-a");
    const hostB = document.querySelector("#scene-host-b");

    expect(hostA?.querySelector(".title")?.textContent).toBe("Scene");
    expect(hostB?.querySelector(".title")?.textContent).toBe("Scene");
    expect(hostA?.getAttribute("data-composition-id")).toBe("scene__hf1");
    expect(hostB?.getAttribute("data-composition-id")).toBe("scene__hf2");
    expect(hostA?.getAttribute("data-hf-original-composition-id")).toBe("scene");
    expect(hostB?.getAttribute("data-hf-original-composition-id")).toBe("scene");
  });

  it("emits scoped style and script chunks for each duplicate inline-template host", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div id="scene-host-a" data-composition-id="scene"></div>
    <div id="scene-host-b" data-composition-id="scene"></div>
  </div>
  <template id="scene-template">
    <div id="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
      <style>.title { opacity: 0; }</style>
      <h1 class="title">Scene</h1>
      <script>
        window.__timelines = window.__timelines || {};
        window.__timelines.scene = { marker: "scene" };
      </script>
    </div>
  </template>
  <script>window.__timelines={};</script>
</body></html>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain('[data-composition-id="scene__hf1"] .title');
    expect(bundled).toContain('[data-composition-id="scene__hf2"] .title');
    expect(bundled).toContain('var __hfTimelineCompId = "scene__hf1"');
    expect(bundled).toContain('var __hfTimelineCompId = "scene__hf2"');
  });

  it("gives a mount that shares the page root's id its own runtime id", async () => {
    const cliRoot = (title: string) =>
      `<div id="root" data-composition-id="main" data-width="1920" data-height="1080"><h1>${title}</h1>`;
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  ${cliRoot("Host")}
    <div id="main_2" data-composition-id="main" data-composition-src="compositions/scene.html"></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/scene.html": `<!doctype html><html><body>${cliRoot("Scene")}</div>
  <script>window.__timelines["main"] = "scene";</script>
</body></html>`,
    });

    const bundled = await bundleToSingleHtml(dir);
    const host = parseHTML(bundled).document.querySelector("#main_2");

    expect(host?.getAttribute("data-composition-id")).toBe("main__hf1");
    expect(host?.getAttribute("data-hf-original-composition-id")).toBe("main");
    expect(bundled).toContain('var __hfTimelineCompId = "main__hf1"');
  });

  it("uniquifies duplicate sub-compositions across inline-template and external hosts", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div id="scene-host-inline" data-composition-id="scene"></div>
    <div
      id="scene-host-external"
      data-composition-id="scene"
      data-composition-src="compositions/scene.html"></div>
  </div>
  <template id="scene-template">
    <div data-composition-id="scene" data-width="1920" data-height="1080">
      <p>Inline scene</p>
    </div>
  </template>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/scene.html": `<template id="scene-template">
  <div data-composition-id="scene" data-width="1920" data-height="1080">
    <p>External scene</p>
  </div>
</template>`,
    });

    const bundled = await bundleToSingleHtml(dir);
    const { document } = parseHTML(bundled);
    const inlineHost = document.querySelector("#scene-host-inline");
    const externalHost = document.querySelector("#scene-host-external");

    expect(inlineHost?.getAttribute("data-composition-id")).toBe("scene__hf1");
    expect(externalHost?.getAttribute("data-composition-id")).toBe("scene__hf2");
    expect(inlineHost?.getAttribute("data-hf-original-composition-id")).toBe("scene");
    expect(externalHost?.getAttribute("data-hf-original-composition-id")).toBe("scene");
    expect(inlineHost?.querySelector("p")?.textContent).toBe("Inline scene");
    expect(externalHost?.querySelector("p")?.textContent).toBe("External scene");
  });

  it("keeps an installed sub-composition's declared defaults for getVariables", async () => {
    // `hyperframes add` writes a marker comment above the doctype.
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div data-composition-id="blk" data-composition-src="compositions/blk.html"></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/blk.html": `<!-- hyperframes-registry-item: blk -->
<!doctype html>
<html data-composition-variables='[{"id":"image1","type":"image","default":"assets/blk/one.jpg"}]'>
  <body>
    <div id="blk-root" data-composition-id="blk" data-width="1920" data-height="1080">
      <script>window.__blkVars = __hyperframes.getVariables();</script>
    </div>
  </body>
</html>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toMatch(/__hfVariablesByComp = Object\.assign\([^;]*assets\/blk\/one\.jpg/);
  });

  it("emits per-instance scoped variables for bundled sub-compositions", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div
      id="card-a"
      data-composition-id="card"
      data-composition-src="compositions/card.html"
      data-variable-values='{"title":"Pro"}'></div>
    <div
      id="card-b"
      data-composition-id="card"
      data-composition-src="compositions/card.html"
      data-variable-values='{"title":"Enterprise"}'></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/card.html": `<!doctype html>
<html data-composition-variables='[
  {"id":"title","type":"string","label":"Title","default":"Default Title"},
  {"id":"theme","type":"string","label":"Theme","default":"light"}
]'>
  <body>
    <div id="card-root" data-composition-id="card" data-width="1920" data-height="1080">
      <script>
        window.__timelines = window.__timelines || {};
        window.__timelines[document.currentScript?.dataset.slot || "missing"] = __hyperframes.getVariables();
      </script>
    </div>
  </body>
</html>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain("window.__hfVariablesByComp");
    expect(bundled).toMatch(/card__hf1[\s\S]*Pro[\s\S]*light/);
    expect(bundled).toMatch(/card__hf2[\s\S]*Enterprise[\s\S]*light/);
  });

  it("does not redefine an authored CSS variable for a bundled sub-composition", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head>
  <style>:root { --accent: #4287f5; } .host-badge { color: var(--accent); }</style>
</head><body>
  <div
    data-composition-id="main"
    data-width="1920"
    data-height="1080"
    data-start="0"
    data-duration="5">
    <div
      data-composition-id="card"
      data-composition-src="compositions/card.html"
      data-variable-values='{"accent":"blue"}'></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/card.html": `<!doctype html>
<html data-composition-variables='[{"id":"accent","type":"string","label":"Accent","default":"red"}]'>
  <body>
    <div
      data-composition-id="card"
      data-width="1920"
      data-height="1080"
      data-start="0"
      data-duration="5"></div>
  </body>
</html>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain(":root { --accent: #4287f5; }");
    expect(bundled).not.toMatch(/\[data-composition-id="card[^"]*"\]\s*\{[^}]*--accent:\s*blue/);
  });

  it("scopes external sub-composition styles and classic scripts", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
</head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div
      id="scene-host"
      data-composition-id="scene"
      data-composition-src="compositions/scene.html"
      data-start="0"
      data-duration="5"></div>
    <div data-composition-id="other"><h1 class="title">Other</h1></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/scene.html": `<template id="scene-template">
  <div data-composition-id="scene" data-width="1920" data-height="1080">
    <style>
      .title { opacity: 0; transform: translateY(30px); }
      @media (min-width: 800px) { .title { color: red; } }
    </style>
    <h1 class="title">Scene</h1>
    <script>
      const tl = gsap.timeline({ paused: true });
      tl.to('.title', { opacity: 1 });
      window.__timelines["scene"] = tl;
    </script>
  </div>
</template>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain('[data-composition-id="scene"] .title');
    expect(bundled).toContain('[data-composition-id="scene"] .title { color: red; }');
    expect(bundled).toContain("new Proxy(window.document");
    expect(bundled).toContain("new Proxy(__hfBaseGsap");
    expect(bundled).toContain("(function(document, gsap, window, __hyperframes)");
    expect(bundled).toContain('tl.to(".title"');
  });

  it("isolates sibling instances of the same external sub-composition", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
</head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div
      id="scene-a"
      data-composition-id="scene"
      data-composition-src="compositions/scene.html"
      data-start="0"
      data-duration="5"></div>
    <div
      id="scene-b"
      data-composition-id="scene"
      data-composition-src="compositions/scene.html"
      data-start="5"
      data-duration="5"></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/scene.html": `<template id="scene-template">
  <div data-composition-id="scene" data-width="1920" data-height="1080">
    <style>[data-composition-id="scene"] .title { opacity: 0; }</style>
    <h1 class="title">Scene</h1>
    <script>
      const tl = gsap.timeline({ paused: true });
      tl.to('[data-composition-id="scene"] .title', { opacity: 1 });
      window.__timelines = window.__timelines || {};
      window.__timelines["scene"] = tl;
    </script>
  </div>
</template>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    const { document } = parseHTML(bundled);
    const sceneA = document.querySelector("#scene-a");
    const sceneB = document.querySelector("#scene-b");
    const sceneAId = sceneA?.getAttribute("data-composition-id") ?? "";
    const sceneBId = sceneB?.getAttribute("data-composition-id") ?? "";

    expect(sceneAId).not.toBe("scene");
    expect(sceneBId).not.toBe("scene");
    expect(sceneAId).not.toBe(sceneBId);
    expect(sceneA?.getAttribute("data-hf-original-composition-id")).toBe("scene");
    expect(sceneB?.getAttribute("data-hf-original-composition-id")).toBe("scene");
    expect(bundled).toContain(`[data-composition-id="${sceneAId}"] .title`);
    expect(bundled).toContain(`[data-composition-id="${sceneBId}"] .title`);
    expect(bundled).toContain('var __hfTimelineCompId = "scene__hf1"');
    expect(bundled).toContain('var __hfTimelineCompId = "scene__hf2"');
    expect(bundled).not.toContain('[data-composition-id="scene"] .title { opacity: 0; }');
  });

  it("rewrites CSS url(...) asset paths from sub-compositions when styles are hoisted", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div
      data-composition-id="hero"
      data-composition-src="compositions/hero.html"
      data-start="0"
      data-duration="2"></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/hero.html": `<template id="hero-template">
  <div data-composition-id="hero" data-width="1920" data-height="1080">
    <style>
      @font-face {
        font-family: "Brand Sans";
        src: url("../fonts/brand.woff2") format("woff2");
      }
    </style>
    <p>Hello</p>
  </div>
</template>`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain('url("fonts/brand.woff2")');
    expect(bundled).not.toContain('url("../fonts/brand.woff2")');
  });

  it("resolves CSS @import statements when inlining stylesheets", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <link rel="stylesheet" href="styles/canvas.css">
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "styles/canvas.css": `@import url('./tokens.css');\nbody { margin: 0; }`,
      "styles/tokens.css": `:root { --brand: #ff5728; }`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain("--brand: #ff5728");
    expect(styleText(bundled)).not.toContain("@import");
    expect(bundled).toContain("margin: 0");
  });

  it("inlines cube LUT files referenced from data-color-grading", async () => {
    const dir = makeColorGradingProject("assets/luts/identity.cube", {
      "assets/luts/identity.cube": `LUT_3D_SIZE 2
0 0 0
1 0 0
0 1 0
1 1 0
0 0 1
1 0 1
0 1 1
1 1 1`,
    });

    const bundled = await bundleToSingleHtml(dir);
    const lutSrc = readBundledColorGradingLutSrc(bundled);

    expect(lutSrc).toMatch(/^data:text\/plain;base64,/);
    expect(lutSrc).not.toContain("assets/luts/identity.cube");
  });

  it("can keep data-color-grading LUT paths external for studio preview", async () => {
    const dir = makeColorGradingProject("assets/luts/identity.cube", {
      "assets/luts/identity.cube": `LUT_3D_SIZE 2
0 0 0
1 0 0
0 1 0
1 1 0
0 0 1
1 0 1
0 1 1
1 1 1`,
    });

    const bundled = await bundleToSingleHtml(dir, { inlineColorGradingLuts: false });
    const lutSrc = readBundledColorGradingLutSrc(bundled);

    expect(lutSrc).toBe("assets/luts/identity.cube");
  });

  it("inlineAssets: false also keeps a LUT path external, without inlineColorGradingLuts", async () => {
    const dir = makeColorGradingProject("assets/luts/identity.cube", {
      "assets/luts/identity.cube": "LUT_3D_SIZE 2",
    });

    const bundled = await bundleToSingleHtml(dir, { inlineAssets: false });
    const lutSrc = readBundledColorGradingLutSrc(bundled);

    expect(lutSrc).toBe("assets/luts/identity.cube");
  });

  it("warns when a render bundle cannot inline a referenced color grading LUT", async () => {
    const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
    try {
      const dir = makeColorGradingProject("assets/luts/missing.cube");

      const bundled = await bundleToSingleHtml(dir);
      const lutSrc = readBundledColorGradingLutSrc(bundled);

      expect(lutSrc).toBe("assets/luts/missing.cube");
      expect(warnSpy).toHaveBeenCalledWith(
        expect.stringContaining('Could not inline color grading LUT "assets/luts/missing.cube"'),
      );
    } finally {
      warnSpy.mockRestore();
    }
  });

  it("resolves nested CSS @import chains", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <link rel="stylesheet" href="styles/main.css">
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "styles/main.css": `@import url('./base.css');\n.main { color: red; }`,
      "styles/base.css": `@import url('../tokens.css');\n.base { display: flex; }`,
      "tokens.css": `:root { --tk-teal: #1a3540; }`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain("--tk-teal: #1a3540");
    expect(bundled).toContain("display: flex");
    expect(bundled).toContain("color: red");
    expect(styleText(bundled)).not.toContain("@import");
  });

  it("wraps @import with media query in @media block", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <link rel="stylesheet" href="print.css">
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "print.css": `@import url('./print-tokens.css') print;\nbody { font-size: 12pt; }`,
      "print-tokens.css": `.print-only { display: block; }`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain("@media print");
    expect(bundled).toContain("display: block");
    expect(styleText(bundled)).not.toContain("@import");
  });

  describe("head style coalescing", () => {
    async function bundledHeadStyles(head: string, files: Record<string, string> = {}) {
      const dir = makeTempProject({
        ...files,
        "index.html": `<!doctype html>
<html><head>${head}</head><body>
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      });
      const { document } = parseHTML(await bundleToSingleHtml(dir));
      return [
        ...document.querySelectorAll("head style:not([data-hyperframes-text-rendering])"),
      ].map((el) => ({
        media: el.getAttribute("media"),
        type: el.getAttribute("type"),
        css: el.textContent,
        ...(el.hasAttribute("title") && { title: el.getAttribute("title") }),
      }));
    }

    it("does not merge a non-CSS style into CSS", async () => {
      expect(
        await bundledHeadStyles(
          `<style>p{color:red}</style><style type="text/x-tpl">{{ a }}</style>`,
        ),
      ).toEqual([
        { media: null, type: null, css: "p{color:red}" },
        { media: null, type: "text/x-tpl", css: "{{ a }}" },
      ]);
    });

    it("still merges styles the browser applies under the same condition", async () => {
      expect(
        await bundledHeadStyles(
          `<style>a{color:red}</style><style type="text/css">b{color:red}</style>` +
            `<style media="all">i{color:red}</style><style type="TEXT/CSS">u{color:red}</style>` +
            `<style media=" ALL ">s{color:red}</style>` +
            `<style media="print">a{color:blue}</style><style media="print">b{color:blue}</style>`,
        ),
      ).toEqual([
        {
          media: null,
          type: null,
          css: "a{color:red}\n\nb{color:red}\n\ni{color:red}\n\nu{color:red}\n\ns{color:red}",
        },
        { media: "print", type: null, css: "a{color:blue}\n\nb{color:blue}" },
      ]);
    });

    it("inlines each linked sheet at its link's place with the link's media", async () => {
      expect(
        await bundledHeadStyles(
          `<style>p{color:red}</style><link rel="stylesheet" href="print.css" media="print">` +
            `<style>p{color:green}</style><link rel="stylesheet" href="late.css">`,
          { "print.css": "p{color:blue}", "late.css": "p{color:black}" },
        ),
      ).toEqual([
        { media: null, type: null, css: "p{color:red}" },
        { media: "print", type: null, css: "p{color:blue}" },
        { media: null, type: null, css: "p{color:green}\n\np{color:black}" },
      ]);
    });

    it("does not inline a linked sheet of a non-CSS type as CSS", async () => {
      expect(
        await bundledHeadStyles(`<link rel="stylesheet" type="text/x-scss" href="a.scss">`, {
          "a.scss": "p{color:blue}",
        }),
      ).toEqual([]);
    });

    it("does not inline a disabled linked sheet", async () => {
      expect(
        await bundledHeadStyles(`<link rel="stylesheet" href="a.css" disabled>`, {
          "a.css": "p{color:blue}",
        }),
      ).toEqual([]);
    });

    it("merges a titled style only with styles of the same title", async () => {
      expect(
        await bundledHeadStyles(
          `<style>a{color:red}</style><style title="t">b{color:red}</style><style title="t">i{color:red}</style>` +
            `<style title="T">u{color:red}</style><style title="">s{color:red}</style><style>q{color:red}</style>` +
            `<link rel="stylesheet" href="alt.css" title="u">`,
          { "alt.css": "p{color:blue}" },
        ),
      ).toEqual([
        { media: null, type: null, css: "a{color:red}" },
        { media: null, type: null, css: "b{color:red}\n\ni{color:red}", title: "t" },
        { media: null, type: null, css: "u{color:red}", title: "T" },
        { media: null, type: null, css: "s{color:red}\n\nq{color:red}", title: "" },
        { media: null, type: null, css: "p{color:blue}", title: "u" },
      ]);
    });

    it("keeps a composition's print style print-only and its non-CSS style out of CSS", async () => {
      const comp = (
        id: string,
      ) => `<div data-composition-id="${id}" data-width="320" data-height="180">
  <style media="print">.${id}-p{color:blue}</style><style type="text/x-tpl">.${id}-t{color:red}</style>
  <p class="${id}-p">x</p></div>`;
      const dir = makeTempProject({
        "index.html": `<!doctype html>
<html><head></head><body>
  <div data-composition-id="root" data-width="320" data-height="180">
    <div data-composition-id="file" data-composition-src="file.html"></div>
    <div data-composition-id="inline"></div>
  </div>
  <template id="inline-template">${comp("inline")}</template>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
        "file.html": `<template id="file-template">${comp("file")}</template>`,
      });
      const { document } = parseHTML(await bundleToSingleHtml(dir));
      const css = (selector: string) =>
        [...document.querySelectorAll(selector)].map((el) => el.textContent).join("\n");
      for (const id of ["file", "inline"]) {
        expect(css('style[media="print"]')).toContain(`.${id}-p{color:blue}`);
        expect(css("style:not([media]):not([type])")).not.toContain(`.${id}-p{`);
        expect(css("style:not([type])")).not.toContain(`.${id}-t{`);
      }
    });

    it("keeps rule order across a conditional style", async () => {
      expect(
        await bundledHeadStyles(
          `<style>p{color:red}</style><style media="print">p{color:blue}</style><style>p{color:green}</style>`,
        ),
      ).toEqual([
        { media: null, type: null, css: "p{color:red}" },
        { media: "print", type: null, css: "p{color:blue}" },
        { media: null, type: null, css: "p{color:green}" },
      ]);
    });

    it("inlines a linked sheet whose type carries a charset, but not a style with that type", async () => {
      expect(
        await bundledHeadStyles(
          `<link rel="stylesheet" type="text/css; charset=utf-8" href="a.css">` +
            `<style type="text/css; charset=utf-8">p{color:red}</style>`,
          { "a.css": "p{color:blue}" },
        ),
      ).toEqual([
        { media: null, type: null, css: "p{color:blue}" },
        { media: null, type: "text/css; charset=utf-8", css: "p{color:red}" },
      ]);
    });

    it("keeps the untitled copy of a @font-face that a later alternate style repeats", async () => {
      const face = `@font-face{font-family:"PF";src:url(https://cdn.example/f.woff2)}`;
      const dir = makeTempProject({
        "index.html": `<!doctype html>
<html><head><style>${face}.t{font-family:"PF"}</style><style title="main">.x{}</style>
<style title="alt">${face}</style></head><body>
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      });
      const { document } = parseHTML(await bundleToSingleHtml(dir));
      const untitled = [...document.querySelectorAll("head style:not([title])")];
      expect(untitled.map((el) => el.textContent).join("")).toContain("@font-face");
    });

    it("keeps a root-less template's non-CSS style out of CSS", async () => {
      const dir = makeTempProject({
        "index.html": `<!doctype html>
<html><head></head><body>
  <div data-composition-id="root" data-width="320" data-height="180">
    <div data-composition-id="bare"></div>
  </div>
  <template id="bare-template"><style type="text/x-tpl">.bare-t{color:red}</style><p>x</p></template>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      });
      const { document } = parseHTML(await bundleToSingleHtml(dir));
      const css = [...document.querySelectorAll("style:not([type])")].map((el) => el.textContent);
      expect(css.join("\n")).not.toContain(".bare-t{");
    });
  });

  describe("composition links to the same file", () => {
    async function sharedLinks(aLink: string, bLink: string, rootHead = "", rootBody = "") {
      const comp = (id: string, link: string) =>
        `<template id="${id}-template"><div data-composition-id="${id}" data-width="320" data-height="180">${link}<p class="${id}">x</p></div></template>`;
      const dir = makeTempProject({
        "index.html": `<!doctype html>
<html><head>${rootHead}</head><body>${rootBody}
  <div data-composition-id="root" data-width="320" data-height="180">
    <div data-composition-id="a" data-composition-src="a.html"></div>
    <div data-composition-id="b" data-composition-src="b.html"></div>
  </div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
        "a.html": comp("a", aLink.replace("HREF", "shared.css")),
        "b.html": comp("b", bLink.replace("HREF", "shared.css")),
        "shared.css": ".a,.b{color:green}",
      });
      const { document } = parseHTML(await bundleToSingleHtml(dir));
      return [...document.querySelectorAll("link[href]")].map((el) =>
        Object.fromEntries([...el.attributes].map((attr) => [attr.name, attr.value])),
      );
    }
    const link = (attrs = "") => `<link rel="stylesheet" href="HREF"${attrs}>`;
    const plain = { href: "shared.css", rel: "stylesheet" };
    const print = { ...plain, media: "print" };

    it.each([
      ["a plain link after a print one", link(' media="print"'), link(), [print, plain]],
      [
        "a plain link after a titled one",
        link(' title="alt"'),
        link(),
        [{ ...plain, title: "alt" }, plain],
      ],
      ["a print link after a plain one", link(), link(' media="print"'), [plain, print]],
      [
        "a screen link after a print one",
        link(' media="print"'),
        link(' media="screen"'),
        [print, { ...plain, media: "screen" }],
      ],
      ["two print links", link(' media="print"'), link(' media="print"'), [print]],
      ["two plain links", link(), link(), [plain]],
      [
        "a plain link after a disabled one",
        link(" disabled"),
        link(),
        [{ ...plain, disabled: "" }, plain],
      ],
      [
        "a stylesheet after a preload of the same file",
        '<link rel="preload" as="style" href="HREF">',
        link(),
        [plain, { href: "shared.css", rel: "preload", as: "style" }],
      ],
      [
        "two links of different non-CSS types",
        link(' type="text/x-scss"'),
        link(' type="text/x-less"'),
        [
          { ...plain, type: "text/x-scss" },
          { ...plain, type: "text/x-less" },
        ],
      ],
      [
        "a plain link after a CORS one, as one link",
        link(" crossorigin"),
        link(),
        [{ ...plain, crossorigin: "" }],
      ],
      [
        "two CORS links spelled differently, as one link",
        link(' crossorigin=""'),
        link(' crossorigin="anonymous"'),
        [{ ...plain, crossorigin: "" }],
      ],
    ])("keeps %s under its own condition", async (_, aLink, bLink, expected) => {
      expect(await sharedLinks(aLink, bLink)).toEqual(expected);
    });

    it("keeps a plain link after an alternate one", async () => {
      const links = await sharedLinks(
        `<link rel="alternate stylesheet" title="alt" href="HREF">`,
        link(),
      );
      expect(links).toContainEqual(plain);
    });

    it("keeps a composition's plain link when the root links the same URL for print", async () => {
      const url = "https://cdn.example/shared.css";
      const links = await sharedLinks(
        link().replace("HREF", url),
        link(),
        `<link rel="stylesheet" href="${url}" media="print">`,
      );
      expect(links).toEqual([{ ...print, href: url }, { ...plain, href: url }, plain]);
    });

    it("lets the root's link stand for a composition's that differs only in fetch attributes", async () => {
      const url = "https://cdn.example/shared.css";
      const snippet = ' integrity="sha512-x" crossorigin="anonymous" referrerpolicy="no-referrer"';
      for (const [rootAttrs, compAttrs] of [
        [' integrity="sha384-x"', ""],
        [' referrerpolicy="no-referrer"', ""],
        [" crossorigin", ""],
        [snippet, snippet],
      ]) {
        const rootLink = link(rootAttrs).replace("HREF", url);
        const links = await sharedLinks(link(compAttrs).replace("HREF", url), "", rootLink);
        expect(links).toHaveLength(1);
      }
    });

    it("keeps a composition's link when the root's same link is in a noscript", async () => {
      const url = "https://cdn.example/shared.css";
      expect(
        await sharedLinks(
          link().replace("HREF", url),
          "",
          "",
          `<noscript>${link().replace("HREF", url)}</noscript>`,
        ),
      ).toEqual([
        { ...plain, href: url },
        { ...plain, href: url },
      ]);
    });

    it("carries a composition link's type and disabled state", async () => {
      const dir = makeTempProject({
        "index.html": `<!doctype html>
<html><head></head><body>
  <div data-composition-id="root" data-width="320" data-height="180">
    <div data-composition-id="a" data-composition-src="a.html"></div>
  </div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
        "a.html": `<template id="a-template"><div data-composition-id="a" data-width="320" data-height="180">
<link rel="stylesheet" href="x.scss" type="text/x-scss"><link rel="stylesheet" href="off.css" disabled><p>x</p></div></template>`,
      });
      const { document } = parseHTML(await bundleToSingleHtml(dir));
      expect(document.querySelector('link[href="x.scss"]')?.getAttribute("type")).toBe(
        "text/x-scss",
      );
      expect(document.querySelector('link[href="off.css"]')?.hasAttribute("disabled")).toBe(true);
    });
  });

  it("preserves @import for absolute URLs", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <link rel="stylesheet" href="app.css">
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "app.css": `@import url('https://fonts.googleapis.com/css2?family=Inter');\nbody { margin: 0; }`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain("@import url('https://fonts.googleapis.com/css2?family=Inter')");
    expect(bundled).toContain("margin: 0");
  });

  it("rebases url() paths in @import-resolved CSS to project root", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <link rel="stylesheet" href="styles/canvas.css">
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "styles/canvas.css": `@import url('./tokens.css');\nbody { margin: 0; }`,
      "styles/tokens.css": `@font-face { src: url('assets/fonts/brand.woff2') format('woff2'); }`,
      "styles/assets/fonts/brand.woff2": "fake-font-data",
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain(`url('${inlinedAs("font/woff2", "fake-font-data")}')`);
    expect(bundled).not.toContain("url('assets/fonts/brand.woff2')");
    expect(styleText(bundled)).not.toContain("@import");
  });

  it("rebases url() paths in <link>-inlined CSS from subdirectories", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <link rel="stylesheet" href="theme/styles.css">
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "theme/styles.css": `.bg { background: url('./images/grain.png'); }`,
      "theme/images/grain.png": "fake-image-data",
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain(`url('${inlinedAs("image/png", "fake-image-data")}')`);
    expect(bundled).not.toContain("url('./images/grain.png')");
  });

  it("decodes CSS escapes before rebasing linked stylesheet asset URLs", async () => {
    const dir = makeTempProject({
      "index.html": `<link rel="stylesheet" href="css/theme.css"><div data-composition-id="root" data-width="320" data-height="180"></div>`,
      "css/theme.css": String.raw`.bg { background: url(icon\ 1.png); }`,
      "css/icon 1.png": "escaped-space-image",
    });

    const linked = await bundleToSingleHtml(dir, { inlineAssets: false });
    expect(styleText(linked)).toContain("url(css/icon%201.png)");
    const inlined = await bundleToSingleHtml(dir);
    expect(styleText(inlined)).toContain(inlinedAs("image/png", "escaped-space-image"));
  });

  it("keeps raw URL backslashes distinct from encoded filename backslashes in linked CSS", async () => {
    const dir = makeTempProject({
      "index.html": `<link rel="stylesheet" href="css/theme.css"><div data-composition-id="root" data-width="320" data-height="180"></div>`,
      "css/theme.css": String.raw`.raw { background: url("assets\\logo.png"); } .encoded { background: url("assets%5Clogo.png"); }`,
      "css/assets/logo.png": "separator-image",
      ...(process.platform === "win32"
        ? {}
        : { "css/assets\\logo.png": "literal-backslash-image" }),
    });
    const linked = await bundleToSingleHtml(dir, { inlineAssets: false });
    expect(styleText(linked)).toContain('url("css/assets/logo.png")');
    const encodedUrl =
      process.platform === "win32" ? 'url("css/assets/logo.png")' : 'url("css/assets%5Clogo.png")';
    expect(styleText(linked)).toContain(encodedUrl);
    const inlined = await bundleToSingleHtml(dir);
    expect(styleText(inlined)).toContain(inlinedAs("image/png", "separator-image"));
    const encodedFileContents =
      process.platform === "win32" ? "separator-image" : "literal-backslash-image";
    expect(styleText(inlined)).toContain(inlinedAs("image/png", encodedFileContents));
  });

  it("removes CSS line continuations before rebasing linked stylesheet URLs", async () => {
    const dir = makeTempProject({
      "index.html": `<link rel="stylesheet" href="css/theme.css"><div data-composition-id="root" data-width="320" data-height="180"></div>`,
      "css/theme.css": '.bg { background: url("icon\\\n1.png"); }',
      "css/icon1.png": "continued-image",
    });

    const linked = await bundleToSingleHtml(dir, { inlineAssets: false });
    expect(styleText(linked)).toContain('url("css/icon1.png")');
  });

  it("preserves escaped leading spaces as part of linked CSS asset identity", async () => {
    const dir = makeTempProject({
      "index.html": `<link rel="stylesheet" href="css/theme.css"><div data-composition-id="root" data-width="320" data-height="180"></div>`,
      "css/theme.css": String.raw`.bg { background: url(\ image.png); }`,
      "css/ image.png": "leading-space-image",
      "css/image.png": "different-image",
    });

    const linked = await bundleToSingleHtml(dir, { inlineAssets: false });
    expect(styleText(linked)).toContain("url(css/%20image.png)");
    const inlined = await bundleToSingleHtml(dir);
    expect(styleText(inlined)).toContain(inlinedAs("image/png", "leading-space-image"));
    expect(styleText(inlined)).not.toContain(inlinedAs("image/png", "different-image"));
  });

  it.each([
    ["", String.raw`?v=\ 1`, String.raw`?v=\0000201`],
    ['"', String.raw`?v=\22 1`, String.raw`?v=\0000221`],
    ['"', String.raw`?v=\22`, String.raw`?v=\000022`],
    ['"', String.raw`?v=\3c /style\3e 1`, String.raw`?v=\00003c/style\00003e1`],
  ])("escapes decoded CSS URL suffixes with delimiter %j", async (quote, suffix, escaped) => {
    const dir = makeTempProject({
      "index.html": `<link rel="stylesheet" href="css/theme.css"><div data-composition-id="root" data-width="320" data-height="180"></div>`,
      "css/theme.css": `.bg { background: url(${quote}icon.png${suffix}${quote}); }`,
      "css/icon.png": "suffix-image",
    });

    const linked = await bundleToSingleHtml(dir, { inlineAssets: false });
    expect(styleText(linked)).toContain(`url(${quote}css/icon.png${escaped}${quote})`);
    const inlined = await bundleToSingleHtml(dir);
    expect(styleText(inlined)).toContain(inlinedAs("image/png", "suffix-image"));
  });

  it("normalizes CSS nulls before resolving linked stylesheet assets", async () => {
    const dir = makeTempProject({
      "index.html": `<link rel="stylesheet" href="css/theme.css"><div data-composition-id="root" data-width="320" data-height="180"></div>`,
      "css/theme.css": ".bg { background: url(\0.png); }",
      "css/\uFFFD.png": "replacement-character-image",
    });

    const linked = await bundleToSingleHtml(dir, { inlineAssets: false });
    expect(styleText(linked)).toContain("url(css/%EF%BF%BD.png)");
    const inlined = await bundleToSingleHtml(dir);
    expect(styleText(inlined)).toContain(inlinedAs("image/png", "replacement-character-image"));
  });

  it("rebases url() paths with ../ traversal in nested @import", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <link rel="stylesheet" href="styles/main.css">
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "styles/main.css": `@import url('./base/reset.css');`,
      "styles/base/reset.css": `body { background: url('../../assets/bg.png'); }`,
      "assets/bg.png": "fake-image",
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain(`url('${inlinedAs("image/png", "fake-image")}')`);
    expect(bundled).not.toContain("url('../../assets/bg.png')");
  });

  it("preserves absolute and data url() references during rebasing", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <link rel="stylesheet" href="styles/app.css">
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "styles/app.css": [
        `@font-face { src: url('https://cdn.example.com/font.woff2'); }`,
        `.icon { background: url('data:image/svg+xml,<svg/>'); }`,
        `.local { background: url('./img/bg.png'); }`,
      ].join("\n"),
      "styles/img/bg.png": "fake",
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain("url('https://cdn.example.com/font.woff2')");
    expect(bundled).toContain("url('data:image/svg+xml,<svg/>')");
    expect(bundled).toContain(`url('${inlinedAs("image/png", "fake")}')`);
  });

  it("preserves url() query strings and hash fragments during rebasing", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <link rel="stylesheet" href="styles/icons.css">
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "styles/icons.css": `.icon { background: url('./sprite.png?v=2#section'); }`,
      "styles/sprite.png": "fake-sprite",
    });

    const bundled = await bundleToSingleHtml(dir);

    // The query/hash suffix rides along onto the inlined data URL.
    expect(bundled).toContain(`url('${inlinedAs("image/png", "fake-sprite")}?v=2#section')`);
  });

  it("inlines fonts, images and scripts so no relative asset reference survives", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head>
  <style>
    @font-face { font-family: "Brand"; src: url('assets/fonts/brand.woff2') format('woff2'); }
    .hero { background: url('assets/hero.jpg'); }
  </style>
</head><body>
  <div data-composition-id="root" data-width="320" data-height="180">
    <img id="logo" src="assets/logo.png" srcset="assets/logo2x.webp 2x">
    <video id="clip" poster="assets/poster.gif"></video>
  </div>
  <script src="assets/app.js"></script>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "assets/fonts/brand.woff2": "font-bytes",
      "assets/hero.jpg": "hero-bytes",
      "assets/logo.png": "logo-bytes",
      "assets/logo2x.webp": "logo2x-bytes",
      "assets/poster.gif": "poster-bytes",
      "assets/app.js": "window.__APP_LOADED__ = true;",
    });

    const bundled = await bundleToSingleHtml(dir);

    // Each asset arrives as its own bytes, which is what proves its path
    // resolved to the right file rather than merely being rewritten.
    expect(bundled).toContain(inlinedAs("font/woff2", "font-bytes"));
    expect(bundled).toContain(inlinedAs("image/jpeg", "hero-bytes"));
    expect(bundled).toContain(inlinedAs("image/png", "logo-bytes"));
    expect(bundled).toContain(inlinedAs("image/webp", "logo2x-bytes"));
    expect(bundled).toContain(inlinedAs("image/gif", "poster-bytes"));
    // A local classic script is folded in as source, not as a data: URL.
    expect(bundled).toContain("window.__APP_LOADED__ = true;");

    // Nothing still points into the sibling assets/ directory that a consumer
    // storing this bundle as a lone file will not have.
    expect(bundled).not.toMatch(/["'(]assets\//);
  });

  it("keeps every asset's literal relative src when inlineAssets is false", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head>
  <style>
    @font-face { font-family: "Brand"; src: url('assets/fonts/brand.woff2') format('woff2'); }
    .hero { background: url('assets/hero.jpg'); }
  </style>
</head><body>
  <div data-composition-id="root" data-width="320" data-height="180">
    <img id="avatar" src="assets/avatar-01.png" srcset="assets/[email protected] 2x">
  </div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "assets/fonts/brand.woff2": "font-bytes",
      "assets/hero.jpg": "hero-bytes",
      "assets/avatar-01.png": "avatar-bytes",
      "assets/[email protected]": "avatar-2x-bytes",
    });

    const bundled = await bundleToSingleHtml(dir, { inlineAssets: false });

    // The composition's own script can read `img.getAttribute("src")` back and
    // still find its authored path — this is what a same-origin asset route
    // (a sibling preview endpoint) needs to serve the real bytes.
    expect(bundled).toContain('src="assets/avatar-01.png"');
    expect(bundled).toContain("assets/[email protected] 2x");
    expect(bundled).toContain("url('assets/fonts/brand.woff2')");
    expect(bundled).toContain("url('assets/hero.jpg')");
    expect(bundled).not.toContain("data:image/png");
    expect(bundled).not.toContain("data:font/woff2");
  });

  it("inlines a font shared by two compositions once, keeping a rule that differs in weight", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div
      data-composition-id="hero"
      data-composition-src="compositions/hero.html"
      data-start="0"
      data-duration="2"></div>
    <div
      data-composition-id="outro"
      data-composition-src="compositions/outro.html"
      data-start="2"
      data-duration="2"></div>
    <div
      data-composition-id="bold"
      data-composition-src="compositions/bold.html"
      data-start="4"
      data-duration="2"></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/hero.html": `<template id="hero-template">
  <div data-composition-id="hero" data-width="1920" data-height="1080">
    <style>
      @font-face {
        font-family: "Brand Sans";
        font-weight: 400;
        font-style: normal;
        src: url("../fonts/brand.woff2") format("woff2");
      }
    </style>
    <p>Hero</p>
  </div>
</template>`,
      // A separate composition declaring the byte-identical @font-face rule:
      // its bytes must ship once, not once per composition that repeats it.
      "compositions/outro.html": `<template id="outro-template">
  <div data-composition-id="outro" data-width="1920" data-height="1080">
    <style>
      @font-face {
        font-family: "Brand Sans";
        font-weight: 400;
        font-style: normal;
        src: url("../fonts/brand.woff2") format("woff2");
      }
    </style>
    <p>Outro</p>
  </div>
</template>`,
      // Same family and src, but a different font-weight: a genuinely
      // different rule that must survive dedupe untouched.
      "compositions/bold.html": `<template id="bold-template">
  <div data-composition-id="bold" data-width="1920" data-height="1080">
    <style>
      @font-face {
        font-family: "Brand Sans";
        font-weight: 700;
        font-style: normal;
        src: url("../fonts/brand.woff2") format("woff2");
      }
    </style>
    <p>Bold</p>
  </div>
</template>`,
      "fonts/brand.woff2": "brand-font-bytes",
    });

    const bundled = await bundleToSingleHtml(dir);
    const fontFaceRules = bundled.match(/@font-face\s*{[^}]*}/g) ?? [];
    const rulesByWeight = (weight: string) =>
      fontFaceRules.filter((rule) => rule.includes(`font-weight: ${weight};`));

    expect(fontFaceRules).toHaveLength(2);
    expect(rulesByWeight("400")).toHaveLength(1);
    expect(rulesByWeight("700")).toHaveLength(1);
    expect(bundled.split(inlinedAs("font/woff2", "brand-font-bytes")).length - 1).toBe(2);
  });

  it.each([
    ["a media query", `<style media="print">FACE</style>`],
    ["a non-CSS type", `<style type="text/x-template">FACE</style>`],
    ["<noscript>", `<noscript><style>FACE</style></noscript>`],
    ["<svg>", `<svg><style>FACE</style></svg>`],
  ])("keeps a font's always-applied copy when the later copy sits behind %s", async (_, later) => {
    const face = `@font-face { font-family: "Brand"; src: url("fonts/brand.woff2") format("woff2"); }`;
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head><style>${face}</style></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    ${later.replace("FACE", face)}
    <p>Hi</p>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "fonts/brand.woff2": "brand-font-bytes",
    });

    const { document } = parseHTML(await bundleToSingleHtml(dir));
    const headCss = [...document.querySelectorAll("head style")].map((s) => s.textContent).join("");
    expect(headCss).toContain("@font-face");
  });

  it("leaves an oversized asset relative and warns rather than inlining it", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <div data-composition-id="root" data-width="320" data-height="180">
    <img id="big" src="assets/huge.png">
  </div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "assets/huge.png": "x".repeat(2 * 1024 * 1024 + 1),
    });
    const warn = vi.spyOn(console, "warn").mockImplementation(() => {});

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain('src="assets/huge.png"');
    expect(bundled).not.toContain("data:image/png");
    expect(warn.mock.calls.flat().join(" ")).toContain("may not be self-contained");
    warn.mockRestore();
  });

  it("deduplicates diamond @import (same file imported by two parents)", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <link rel="stylesheet" href="styles/main.css">
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "styles/main.css": `@import url('./a.css');\n@import url('./b.css');`,
      "styles/a.css": `@import url('./shared.css');\n.a { color: red; }`,
      "styles/b.css": `@import url('./shared.css');\n.b { color: blue; }`,
      "styles/shared.css": `:root { --shared: 1; }`,
    });

    const bundled = await bundleToSingleHtml(dir);

    const sharedCount = (bundled.match(/--shared: 1/g) || []).length;
    expect(sharedCount).toBe(1);
    expect(bundled).toContain(".a { color: red; }");
    expect(bundled).toContain(".b { color: blue; }");
    expect(styleText(bundled)).not.toContain("@import");
  });

  it("does not resolve @import inside CSS comments", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <link rel="stylesheet" href="app.css">
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
</body></html>`,
      "app.css": `/* @import url('./old.css'); */\nbody { margin: 0; }`,
      "old.css": `.old { display: none; }`,
    });

    const bundled = await bundleToSingleHtml(dir);

    expect(bundled).toContain("/* @import url('./old.css'); */");
    expect(bundled).not.toContain(".old { display: none; }");
  });

  // Forces `text-rendering: geometricPrecision` so headless-shell BeginFrame
  // renders match full Chrome (which is the snapshot/preview path). See
  // `injectTextRenderingRule` in htmlBundler.ts.
  it("injects a single text-rendering:geometricPrecision rule into <head>", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html>
<head><title>t</title></head>
<body>
  <div data-composition-id="root" data-width="640" data-height="360">
    <h1>Hello</h1>
  </div>
</body></html>`,
    });

    const bundled = await bundleToSingleHtml(dir);
    const { document } = parseHTML(bundled);
    const styleEls = document.querySelectorAll("style[data-hyperframes-text-rendering]");

    expect(styleEls.length).toBe(1);
    expect((styleEls[0]?.textContent || "").replace(/\s+/g, "")).toContain(
      "html,body,*{text-rendering:geometricPrecision}",
    );
    expect(styleEls[0]?.parentElement?.tagName.toLowerCase()).toBe("head");
  });

  // Regression: cli-feedback field cluster (crons 61-68, n=25+, cross-OS,
  // versions 0.7.56-0.7.64). Reporter L3 cite (ts=1784519869):
  // "bundleToSingleHtml compiles data-duration into data-end, then validates
  // the compiled HTML and reports its own generated data-end as deprecated.
  // Raw-source lint passes with 0 errors and 0 warnings." The end-to-end
  // guarantee: source authored with only data-duration must round-trip through
  // bundle + StaticGuard without producing a StaticGuard warning on the
  // compiler's own consistent data-end. Facet-(a)/(e) fix.
  it("does not emit a StaticGuard warning for source-authored data-duration on media", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html>
<head><title>t</title></head>
<body>
  <div data-composition-id="root" data-width="1920" data-height="1080" data-start="0" data-duration="18">
    <audio id="bgm" src="bgm.mp3" data-start="0" data-duration="18"></audio>
    <audio id="narration" src="narr.mp3" data-start="5" data-duration="10"></audio>
  </div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.root = { duration: () => 18, seek() {}, pause() {} };</script>
</body></html>`,
      "bgm.mp3": "",
      "narr.mp3": "",
    });

    const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
    try {
      const bundled = await bundleToSingleHtml(dir);
      // Sanity: the compiler MUST have emitted data-end for both audio elements,
      // so the linter is actually seeing the compiled shape (not the raw source).
      expect(bundled).toContain('id="bgm"');
      expect(bundled).toMatch(/id="bgm"[^>]*data-end="18"|data-end="18"[^>]*id="bgm"/);
      expect(bundled).toMatch(/id="narration"[^>]*data-end="15"|data-end="15"[^>]*id="narration"/);

      const staticGuardWarnings = warnSpy.mock.calls
        .map((call) => String(call[0] ?? ""))
        .filter((line) => line.includes("[StaticGuard]"));
      expect(staticGuardWarnings).toEqual([]);
    } finally {
      warnSpy.mockRestore();
    }
  });

  it("runs the StaticGuard lint unless staticGuard is false", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html><html><head></head><body>
  <div data-composition-id="root" data-width="320" data-height="180"></div>
</body></html>`,
    });
    const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
    const guardWarnings = () =>
      warnSpy.mock.calls
        .map((call) => String(call[0] ?? ""))
        .filter((line) => line.includes("[StaticGuard]"));
    try {
      await bundleToSingleHtml(dir, { staticGuard: false });
      expect(guardWarnings()).toEqual([]);

      await bundleToSingleHtml(dir);
      expect(guardWarnings()).toHaveLength(1);
    } finally {
      warnSpy.mockRestore();
    }
  });

  describe("symlink path traversal (security: F-005)", () => {
    it("does not inline CSS from a symlink pointing outside projectDir", async () => {
      const { dir, outsideDir } = makeSymlinkProject(
        {
          "index.html": `<!doctype html><html><head>
<link rel="stylesheet" href="evil.css"></head>
<body><div data-composition-id="root" data-width="320" data-height="180"></div></body></html>`,
        },
        ".outside-secret { color: red; }",
      );
      try {
        expect(await bundleToSingleHtml(dir)).not.toContain("outside-secret");
      } finally {
        rmSync(outsideDir, { recursive: true, force: true });
      }
    });

    it("does not inline CSS via @import through a symlink pointing outside projectDir", async () => {
      const { dir, outsideDir } = makeSymlinkProject(
        {
          "index.html": `<!doctype html><html><head>
<link rel="stylesheet" href="main.css"></head>
<body><div data-composition-id="root" data-width="320" data-height="180"></div></body></html>`,
          "main.css": "@import './evil.css';",
        },
        ".import-secret { color: blue; }",
      );
      try {
        expect(await bundleToSingleHtml(dir)).not.toContain("import-secret");
      } finally {
        rmSync(outsideDir, { recursive: true, force: true });
      }
    });
  });
});

/**
 * A sub-composition given a value outside a declared enum's `options` falls
 * back silently. The runtime guard in getVariables.ts cannot see it: the
 * bundler bakes the per-instance values into `window.__hfVariablesByComp` at
 * compile time and the sub-comp's scoped `getVariables` shim only reads that
 * table. Compile time is therefore the only place the defect is observable on
 * this path, so the same warning is emitted here.
 */
describe("bundleToSingleHtml unknown enum values", () => {
  let warnings: string[];

  beforeEach(() => {
    resetUnknownEnumWarnings();
    warnings = [];
    vi.spyOn(console, "warn").mockImplementation((...args: unknown[]) => {
      warnings.push(args.map(String).join(" "));
    });
  });

  afterEach(() => {
    vi.restoreAllMocks();
    resetUnknownEnumWarnings();
  });

  const enumWarnings = () => warnings.filter((w) => w.includes("runtime_unknown_enum_value"));

  const ACCENT_ENUM =
    '[{"id":"accent","type":"enum","label":"Accent","default":"green","options":["green","blue","violet"]}]';

  function makeSubCompProject(variableValues: string, declaration = ACCENT_ENUM): string {
    return makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div
      data-composition-id="card"
      data-composition-src="compositions/card.html"
      data-variable-values='${variableValues}'></div>
  </div>
  <script>window.__timelines={};</script>
</body></html>`,
      "compositions/card.html": `<!doctype html>
<html data-composition-variables='${declaration}'>
  <body>
    <div data-composition-id="card" data-width="1920" data-height="1080"></div>
  </body>
</html>`,
    });
  }

  it("warns when a sub-composition instance value is not a declared option", async () => {
    await bundleToSingleHtml(makeSubCompProject('{"accent":"orange"}'));

    expect(enumWarnings()).toEqual([
      '[hyperframes] runtime_unknown_enum_value: card variable "accent" got "orange", ' +
        "which is not a declared option (green, blue, violet). " +
        'Rendering "green" instead.',
    ]);
  });

  it("is silent when the instance value is a declared option", async () => {
    await bundleToSingleHtml(makeSubCompProject('{"accent":"violet"}'));

    expect(enumWarnings()).toEqual([]);
  });

  it("never inspects a variable declared without options", async () => {
    const declaration = '[{"id":"accent","type":"string","label":"Accent","default":"green"}]';
    await bundleToSingleHtml(makeSubCompProject('{"accent":"orange"}', declaration));

    expect(enumWarnings()).toEqual([]);
  });

  it("is silent for a declared enum absent from the instance values", async () => {
    await bundleToSingleHtml(makeSubCompProject('{"unrelated":"whatever"}'));

    expect(enumWarnings()).toEqual([]);
  });

  it("passes the unknown value through to the bundle unrewritten", async () => {
    const bundled = await bundleToSingleHtml(makeSubCompProject('{"accent":"orange"}'));

    expect(bundled).toContain("window.__hfVariablesByComp = Object.assign({}, ");
    expect(bundled).toContain('{ "card": { "accent": "orange" } }');
    expect(bundled).toMatch(/\[data-composition-id="card"\]\s*\{[^}]*--accent:\s*orange/);
    expect(bundled).not.toContain("--accent: green");
  });

  it("warns once for the same composition, variable and value across bundles", async () => {
    const dir = makeSubCompProject('{"accent":"orange"}');
    await bundleToSingleHtml(dir);
    await bundleToSingleHtml(dir);

    expect(enumWarnings()).toHaveLength(1);
  });

  it("warns for a <template>-mounted composition too", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
    <div data-composition-id="card" data-variable-values='{"accent":"orange"}'></div>
  </div>
  <template id="card-template">
    <div data-composition-id="card" data-width="1920" data-height="1080"
      data-composition-variables='${ACCENT_ENUM}'></div>
  </template>
  <script>window.__timelines={};</script>
</body></html>`,
    });

    await bundleToSingleHtml(dir);

    expect(enumWarnings()).toEqual([
      '[hyperframes] runtime_unknown_enum_value: card variable "accent" got "orange", ' +
        "which is not a declared option (green, blue, violet). " +
        'Rendering "green" instead.',
    ]);
  });
});

/**
 * Composition variable values are emitted as CSS declarations inside a `<style>`
 * element. `<style>` is a RAW TEXT element: HTML serialization does not escape its
 * content and the tokenizer closes it at the first `</style`. An unescaped value could
 * therefore close the element and have the remainder parsed as markup.
 */
describe("emitRootCompositionVariableStyles — <style> breakout", () => {
  /**
   * The payload leads with a benign `<` before its `</style`, so escaping or
   * stripping only the first match does not pass: that pins the `/g` flag rather
   * than merely "something ran". A lone `<` in a value (`a < b`) is the common case.
   */
  const BREAKOUT = "x<y</style><script>window.__pwned=1</script><style>";

  /** Emit into a document, serialize it the way the compilers do, then re-parse. */
  function scriptsAfterRoundTrip(
    variablesByComp: Record<string, Record<string, unknown>>,
    body = "x",
  ) {
    const { document } = parseHTML(`<!doctype html><html><head></head><body>${body}</body></html>`);
    emitRootCompositionVariableStyles(document, variablesByComp);
    const { document: reparsed } = parseHTML(document.toString());
    return {
      scripts: [...reparsed.querySelectorAll("script")].map((s) => s.textContent ?? ""),
      css: [...reparsed.querySelectorAll("style")].map((s) => s.textContent ?? "").join("\n"),
      reparsed,
    };
  }

  it("does not let a variable VALUE close the style element", () => {
    const { scripts } = scriptsAfterRoundTrip({ "comp-a": { brand: BREAKOUT } });
    expect(scripts).toEqual([]);
  });

  it("does not let a COMP ID close the style element through the generated selector", () => {
    // The comp id reaches the stylesheet as an attribute selector, which is escaped
    // for selector-string syntax but says nothing about element termination.
    const { scripts, css } = scriptsAfterRoundTrip(
      { [`comp-a${BREAKOUT}`]: { brand: "#fff" } },
      '<div data-composition-id="comp-a"></div>',
    );
    expect(scripts).toEqual([]);
    expect(css).not.toContain("</style");
  });

  it("strips the characters that smuggle a sibling rule, matching the runtime", () => {
    // `sanitizeCssValue` is the runtime contract for a scalar folded into
    // `background: var(--x)`; the compile path has to reach the same result, or a
    // rendered MP4 diverges from the preview it was approved from.
    const smuggle = "red; } body { background-image: url(//evil?data=1) } x { y:z";
    const { css } = scriptsAfterRoundTrip({ "comp-a": { brand: smuggle } });

    expect(css).not.toContain("body {");
    // One rule, one declaration: with no `;{}` left in the value there is nothing to
    // close the declaration with, so no sibling rule can be opened.
    expect(css.match(/\}/g) ?? []).toHaveLength(1);
    expect(css).toContain(`--brand: ${sanitizeCssValue(smuggle)};`);
  });

  it("strips '<' from a value the way the runtime does", () => {
    const { css, scripts } = scriptsAfterRoundTrip({ "comp-a": { brand: "a<b" } });
    expect(scripts).toEqual([]);
    expect(css).not.toContain("a<b");
    expect(css).toContain("ab");
  });

  it("leaves values without '<' untouched", () => {
    const { css } = scriptsAfterRoundTrip({ "comp-a": { brand: "#ff0066" } });
    expect(css).toContain("#ff0066");
  });
});

describe("nested script integrity", () => {
  it("preserves and deduplicates a nested pin even when the root already loads that URL", async () => {
    const src = "https://cdn.example.com/pinned.js";
    const dir = makeTempProject({
      "index.html": `<html><head><script src="${src}"></script></head><body><div data-composition-id="root" data-width="320" data-height="180" data-duration="1"><div data-composition-id="child" data-composition-src="child.html"></div></div></body></html>`,
      "child.html": `<html><head><script src="${src}" integrity="sha384-YQ==" crossorigin="anonymous"></script></head><body><div data-composition-id="child" data-width="320" data-height="180" data-duration="1">Child</div></body></html>`,
    });
    try {
      const bundled = await bundleToSingleHtml(dir);
      const { document } = parseHTML(bundled);
      const scripts = [...document.querySelectorAll("script[src]")].filter(
        (el) => el.getAttribute("src") === src,
      );
      expect(scripts).toHaveLength(1);
      expect(scripts[0]?.getAttribute("integrity")).toBe("sha384-YQ==");
      expect(scripts[0]?.getAttribute("crossorigin")).toBe("anonymous");
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });
});

it("preserves every duplicate script pin and rejects conflicting requirements", () => {
  const { document } = parseHTML(
    '<html><body><script src="https://cdn.example.com/a.js"></script><script src="https://cdn.example.com/a.js"></script></body></html>',
  );
  const src = "https://cdn.example.com/a.js";
  ensureExternalScriptTag(document, src, { integrity: "sha384-YQ==", crossorigin: "anonymous" });
  ensureExternalScriptTag(document, src);
  for (const el of document.querySelectorAll("script")) {
    expect(el.getAttribute("integrity")).toBe("sha384-YQ==");
    expect(el.getAttribute("crossorigin")).toBe("anonymous");
  }
  expect(() => ensureExternalScriptTag(document, src, { integrity: "sha384-Yg==" })).toThrow(
    "Conflicting script integrity",
  );
});

it("keeps protected local scripts external when hoisting an inline template", async () => {
  const dir = makeTempProject({
    "index.html": `<html><body><template id="child-template"><div data-composition-id="child" data-width="320" data-height="180"><script src="local.js" integrity="sha384-YQ==" crossorigin="anonymous"></script></div></template><div data-composition-id="root" data-width="320" data-height="180" data-duration="1"><div data-composition-id="child" data-start="0" data-duration="1"></div></div></body></html>`,
    "local.js": "window.localPinWitness = true;",
  });
  try {
    const bundled = await bundleToSingleHtml(dir);
    const { document } = parseHTML(bundled);
    const script = document.querySelector('script[src="local.js"]');
    expect(script?.getAttribute("integrity")).toBe("sha384-YQ==");
    expect(script?.getAttribute("crossorigin")).toBe("anonymous");
    expect(bundled).not.toContain("window.localPinWitness = true;");
  } finally {
    rmSync(dir, { recursive: true, force: true });
  }
});

it.each(["root", "sibling", "template"])(
  "does not inline local bytes before a later %s integrity requirement",
  async (placement) => {
    const unpinned = '<script src="local.js"></script>';
    const pinned =
      '<script src="./local.js" integrity="sHa384-YQ==" crossorigin="anonymous"></script>';
    const rootScript = placement === "root" ? unpinned : "";
    const first =
      placement === "sibling"
        ? '<div data-composition-id="first" data-composition-src="first.html"></div>'
        : "";
    const templates =
      placement === "template"
        ? `<template id="first-template"><div data-composition-id="first">${unpinned}</div></template><template id="child-template"><div data-composition-id="child">${pinned}</div></template>`
        : "";
    const children =
      placement === "template"
        ? '<div data-composition-id="first" data-start="0" data-duration="1"></div><div data-composition-id="child" data-start="0" data-duration="1"></div>'
        : `${first}<div data-composition-id="child" data-composition-src="child.html"></div>`;
    const dir = makeTempProject({
      "index.html": `<html><head>${rootScript}</head><body>${templates}<div data-composition-id="root" data-width="320" data-height="180" data-duration="1">${children}</div></body></html>`,
      "first.html": `<html><head>${unpinned}</head><body><div data-composition-id="first" data-width="320" data-height="180" data-duration="1">First</div></body></html>`,
      "child.html": `<html><head>${pinned}</head><body><div data-composition-id="child" data-width="320" data-height="180" data-duration="1">Child</div></body></html>`,
      "local.js": "window.alteredLocalBytes = true;",
    });
    try {
      const bundled = await bundleToSingleHtml(dir);
      expect(bundled).not.toContain("window.alteredLocalBytes = true;");
      const { document } = parseHTML(bundled);
      const local = [...document.querySelectorAll("script[src]")].filter((el) =>
        /local\.js$/.test(el.getAttribute("src") || ""),
      );
      expect(local.length).toBeGreaterThan(0);
      for (const el of local) expect(el.getAttribute("integrity")).toBe("sha384-YQ==");
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  },
);

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 });
    }
  });

  const LOCAL_ORDER_GSAP = "https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js";
  async function bundledBody(scripts: string, files: Record<string, string>) {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  ${scripts}
</body></html>`,
      ...files,
    });
    try {
      const { document } = parseHTML(await bundleToSingleHtml(dir));
      return [...document.querySelectorAll("body script")];
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  }

  it("keeps each local script in its own place around a CDN script", async () => {
    const scripts = await bundledBody(
      `<script src="setup.js"></script>
  <script src="${LOCAL_ORDER_GSAP}"></script>
  <script src="main.js"></script>`,
      { "setup.js": "window.SETUP_RAN = 1;", "main.js": "window.MAIN_RAN = gsap.version;" },
    );
    const setupAt = scripts.findIndex((el) => el.textContent?.includes("SETUP_RAN"));
    const gsapAt = scripts.findIndex((el) => el.getAttribute("src") === LOCAL_ORDER_GSAP);
    const mainAt = scripts.findIndex((el) => el.textContent?.includes("MAIN_RAN"));
    expect(setupAt).toBeGreaterThan(-1);
    expect(setupAt).toBeLessThan(gsapAt);
    expect(gsapAt).toBeLessThan(mainAt);
  });

  it.each(["defer", "async"])(
    "inlines a local %s script in its own tag, keeping the attribute so the runtime times it",
    async (when) => {
      const scripts = await bundledBody(
        `<script>window.FIRST = 1;</script>
  <script ${when} src="main.js"></script>
  <script>window.LAST = 1;</script>`,
        { "main.js": "window.MAIN_RAN = 1;" },
      );
      const main = scripts.find((el) => el.textContent?.includes("MAIN_RAN"));
      expect(main?.hasAttribute(when)).toBe(true);
      expect(main?.hasAttribute("src")).toBe(false);
      expect(main?.getAttribute("data-hf-inlined-src")).toBe("main.js");
      expect(main?.textContent).not.toMatch(/FIRST|LAST/);
    },
  );

  it.each(["", ' type="text/babel"'])(
    "escapes a local file's script-closing text, so the page keeps its structure (%s)",
    async (type) => {
      const scripts = await bundledBody(
        `<script${type} src="main.js"></script><p id="after">ok</p>`,
        {
          "main.js": `window.CLOSE = "</script><p id='leak'>x</p>"; window.OPEN = "<!-- <script>";`,
        },
      );
      const holder = scripts.find((el) => el.textContent?.includes("window.CLOSE"));
      expect(holder?.textContent).toContain("window.OPEN");
      expect(holder?.textContent).not.toMatch(/<\/script|<!--/i);
      expect(holder?.ownerDocument.getElementById("leak")).toBeNull();
    },
  );

  it.each([
    ["a local file", `<script nomodule src="legacy.js"></script>`],
    ["an inline script", `<script nomodule>window.LEGACY_RAN = 1;</script>`],
  ])("keeps nomodule on %s, so modern browsers still skip it", async (_, legacy) => {
    const scripts = await bundledBody(
      `<script>window.FIRST = 1;</script>\n  ${legacy}\n  <script>window.LAST = 1;</script>`,
      {
        "legacy.js": "window.LEGACY_RAN = 1;",
      },
    );
    const holder = scripts.find((el) => el.textContent?.includes("LEGACY_RAN"));
    expect(holder?.hasAttribute("nomodule")).toBe(true);
    expect(holder?.textContent).not.toMatch(/FIRST|LAST/);
  });

  it("keeps a local script's non-JavaScript type, so it is not run as JavaScript", async () => {
    const scripts = await bundledBody(`<script type="text/babel" src="app.jsx"></script>`, {
      "app.jsx": "const App = () => <div />;",
    });
    const holder = scripts.find((el) => el.textContent?.includes("const App"));
    expect(holder?.getAttribute("type")).toBe("text/babel");
  });

  it.each(["", ' type="text/babel"'])(
    "keeps a local file's unicode regex for <!-- valid JavaScript (%s)",
    async (type) => {
      const scripts = await bundledBody(`<script${type} src="main.js"></script>`, {
        "main.js": "window.HAS_COMMENT = /<!--/u.test(document.body.innerHTML);",
      });
      const holder = scripts.find((el) => el.textContent?.includes("HAS_COMMENT"));
      expect(() => new Function(holder?.textContent ?? "")).not.toThrow();
    },
  );

  it("keeps an authored script that reads the runtime global", async () => {
    const scripts = await bundledBody(
      `<script>if (window.__hyperframeRuntime) window.AUTHOR_SEEN = 1;</script>`,
      {},
    );
    expect(scripts.some((el) => el.textContent?.includes("AUTHOR_SEEN"))).toBe(true);
  });

  it("keeps a run that merges a local file with a legacy <!-- comment valid, every script in order", async () => {
    const scripts = await bundledBody(
      `<script src="esc.js"></script>
  <script src="legacy.js"></script>
  <script>window.RAN.push("a");</script>
  <script>window.RAN.push("b");</script>
  <script src="plain.js"></script>`,
      {
        "esc.js": 'window.RAN = ["esc"]; window.CLOSE = "</script>";',
        "legacy.js": '<!-- a legacy comment\nwindow.RAN.push("legacy");',
        "plain.js": 'window.RAN.push("plain");',
      },
    );
    const merged = scripts.find((el) => el.textContent?.includes('"plain"'));
    expect(merged?.textContent).not.toMatch(/<\/script|<!--/i);
    const page = { RAN: [] as string[] };
    new Function("window", merged?.textContent ?? "")(page);
    expect(page.RAN).toEqual(["esc", "legacy", "a", "b", "plain"]);
  });

  it.each([
    ["in <head>", `<script src="legacy.js"></script>`, ""],
    ["deferred in <body>", "", `<script defer src="legacy.js"></script>`],
  ])(
    "keeps a local file with a legacy <!-- comment valid when it is inlined on its own (%s)",
    async (_, head, body) => {
      const dir = makeTempProject({
        "index.html": `<!doctype html>
<html><head>${head}</head><body>
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  ${body}
</body></html>`,
        "legacy.js": '<!-- a legacy comment\nwindow.RAN = ["legacy"];',
      });
      try {
        const { document } = parseHTML(await bundleToSingleHtml(dir));
        const file = document.querySelector("script[data-hf-inlined-src]");
        expect(file?.textContent).not.toContain("<!--");
        const page = { RAN: [] as string[] };
        new Function("window", file?.textContent ?? "")(page);
        expect(page.RAN).toEqual(["legacy"]);
      } finally {
        rmSync(dir, { recursive: true, force: true });
      }
    },
  );

  it("leaves a local non-JavaScript file's text as written", async () => {
    const scripts = await bundledBody(`<script type="application/json" src="data.json"></script>`, {
      "data.json": "[1,2]",
    });
    expect(scripts.find((el) => el.getAttribute("type") === "application/json")?.textContent).toBe(
      "[1,2]",
    );
  });

  it("still adds the runtime when an authored script mentions its marker attribute", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div data-composition-id="root" data-width="320" data-height="180"></div>
  <script>window.MARKER = document.querySelector("[data-hyperframes-preview-runtime]");</script>
</body></html>`,
    });
    try {
      const { document } = parseHTML(await bundleToSingleHtml(dir));
      const scripts = [...document.querySelectorAll("script")];
      expect(
        scripts.filter((el) => el.hasAttribute("data-hyperframes-preview-runtime")),
      ).toHaveLength(1);
      expect(scripts.some((el) => el.textContent?.includes("window.MARKER"))).toBe(true);
    } 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 });
    }
  });
});

describe("bundleToSingleHtml composition scripts that are not JavaScript", () => {
  const sceneFile = (id: string, extra: string) => `<template id="${id}-template">
<div data-composition-id="${id}" data-width="320" data-height="180" data-duration="2">
  ${extra}
  <script>window.__timelines = window.__timelines || {}; window.__timelines.${id} = 1;</script>
</div></template>`;

  async function bundleFilm(
    sceneExtra: string,
    options?: { sceneParts?: boolean },
    files: Record<string, string> = {},
  ) {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <div id="root" data-composition-id="main" data-width="320" data-height="180" data-duration="4">
    <div data-composition-id="intro" data-composition-src="compositions/intro.html" data-start="0" data-duration="2"></div>
    <div data-composition-id="scene" data-composition-src="compositions/scene.html" data-start="2" data-duration="2"></div>
  </div>
  <script>window.__timelines = window.__timelines || {}; window.__timelines.main = 1;</script>
</body></html>`,
      "compositions/intro.html": sceneFile("intro", ""),
      "compositions/scene.html": sceneFile("scene", sceneExtra),
      ...files,
    });
    try {
      const html = await bundleToSingleHtml(dir, options);
      return Object.assign(parseHTML(html).document, { html });
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  }

  const runnable = (document: Document) =>
    [...document.querySelectorAll("body script:not([src]):not([nomodule])")].filter((el) =>
      [null, AFTER_FONTS_SCRIPT_TYPE].includes(el.getAttribute("type")),
    );
  const parses = (el: Element) => {
    try {
      parseJs(el.textContent ?? "", { ecmaVersion: "latest", sourceType: "script" });
      return true;
    } catch {
      return false;
    }
  };
  const timelinesThatRun = (document: Document) =>
    ["main", "intro", "scene"].filter((id) =>
      runnable(document).some(
        (el) => parses(el) && (el.textContent ?? "").includes(`__timelines.${id} =`),
      ),
    );

  it("keeps a sub-composition's JSON data script readable and out of the JavaScript", async () => {
    const document = await bundleFilm(
      `<script type="application/json" id="meta">{"title": "x", "beats": [1, 2]}</script>`,
    );
    const meta = document.querySelector('script[type="application/json"]');
    expect(meta?.getAttribute("id")).toBe("meta");
    expect(JSON.parse(meta?.textContent ?? "")).toEqual({ title: "x", beats: [1, 2] });
    expect(runnable(document).every(parses)).toBe(true);
    expect(runnable(document).some((el) => el.textContent?.includes('"beats"'))).toBe(false);
    expect(timelinesThatRun(document)).toEqual(["main", "intro", "scene"]);
  });

  // Bun 1.3's vm.Script accepts all of these; CI runs Node, so this pins the rules, not the engine.
  it.each([
    ["window.broken = {:", false],
    ["window.broken = 1; return;", false],
    ["export const broken = 1;", false],
    ["window.ok = 1;", true],
  ])("parsesAsScript(%j) is %s", (source, parses) => {
    expect(parsesAsScript(source)).toBe(parses);
  });

  const BROKEN_INLINE = [`<script>window.broken = {:</script>`, {}] as const;
  // An inline script is wrapped in a function, where return is legal; a local file is not.
  const BROKEN_RETURN = [
    `<script src="return.js"></script>`,
    { "compositions/return.js": "window.broken = 1; return;" },
  ] as const;
  const BROKEN_FILE = [
    `<script src="lib.js"></script>`,
    { "compositions/lib.js": "export const broken = 1;" },
  ] as const;
  it.each([
    [false, ...BROKEN_INLINE],
    [true, ...BROKEN_INLINE],
    [false, ...BROKEN_FILE],
    [true, ...BROKEN_FILE],
    [false, ...BROKEN_RETURN],
    [true, ...BROKEN_RETURN],
  ])(
    "keeps a sub-composition script that does not parse apart, so the others still run (sceneParts %s, %s)",
    async (sceneParts, extra, files) => {
      const document = await bundleFilm(extra, { sceneParts }, files);
      const broken = runnable(document).filter((el) => !parses(el));
      expect(broken).toHaveLength(1);
      expect(broken[0]!.textContent).toContain("broken");
      expect(timelinesThatRun(document)).toEqual(["main", "intro", "scene"]);
    },
  );

  it("mounts a JSON data script authored outside the composition root next to it", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <div id="root" data-composition-id="main" data-width="320" data-height="180" data-duration="4">
    <div data-composition-id="scene" data-composition-src="compositions/scene.html" data-start="0" data-duration="2"></div>
    <div data-composition-id="page" data-composition-src="compositions/page.html" data-start="2" data-duration="2"></div>
  </div>
</body></html>`,
      "compositions/scene.html": `<template id="scene-template">
  <script type="application/json" id="beside">{"where": "template"}</script>
  <div data-composition-id="scene" data-width="320" data-height="180"></div>
</template>`,
      "compositions/page.html": `<!doctype html>
<html><head><script type="application/json" id="in-head">{"where": "head"}</script></head>
<body><div data-composition-id="page" data-width="320" data-height="180"></div></body></html>`,
    });
    try {
      const document = parseHTML(await bundleToSingleHtml(dir)).document;
      const beside = document.querySelector('[data-composition-id="scene"] #beside');
      const inHead = document.querySelector('[data-composition-id="page"] #in-head');
      expect(JSON.parse(beside?.textContent ?? "")).toEqual({ where: "template" });
      expect(JSON.parse(inHead?.textContent ?? "")).toEqual({ where: "head" });
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  it("does not run a sub-composition's nomodule script", async () => {
    const document = await bundleFilm(`<script nomodule>window.LEGACY_ONLY = 1;</script>`);
    expect(runnable(document).some((el) => el.textContent?.includes("LEGACY_ONLY"))).toBe(false);
  });

  it("runs an inline template composition's module script as a module and merges its import map", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <template id="card-template"><div data-composition-id="card" data-width="320" data-height="180">
    <script type="importmap">{"imports": {"lib": "./lib.js"}}</script>
    <script type="module">import "lib"; window.CARD_MODULE = 1;</script>
  </div></template>
  <div id="root" data-composition-id="main" data-width="320" data-height="180" data-duration="2">
    <div data-composition-id="card" data-start="0" data-duration="2"></div>
  </div>
</body></html>`,
    });
    try {
      const document = parseHTML(await bundleToSingleHtml(dir)).document;
      expect(runnable(document).some((el) => el.textContent?.includes("CARD_MODULE"))).toBe(false);
      const modules = [...document.querySelectorAll("script")].filter((el) =>
        (el.getAttribute("type") ?? "").includes("module"),
      );
      expect(modules.some((el) => el.textContent?.includes("CARD_MODULE"))).toBe(true);
      const map = document.querySelector('script[type="importmap"]');
      expect(JSON.parse(map?.textContent ?? "{}").imports).toEqual({ lib: "./lib.js" });
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  it("keeps an inline template composition's JSON data script readable and out of the JavaScript", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <template id="card-template"><div data-composition-id="card" data-width="320" data-height="180">
    <script type="application/json" id="card-meta">{"title": "x"}</script>
    <script>window.__timelines = window.__timelines || {}; window.__timelines.card = 1;</script>
  </div></template>
  <div id="root" data-composition-id="main" data-width="320" data-height="180" data-duration="2">
    <div data-composition-id="card" data-start="0" data-duration="2"></div>
  </div>
</body></html>`,
    });
    try {
      const document = parseHTML(await bundleToSingleHtml(dir)).document;
      const meta = document.querySelector('[data-composition-id="card"] #card-meta');
      expect(meta?.getAttribute("type")).toBe("application/json");
      expect(JSON.parse(meta?.textContent ?? "")).toEqual({ title: "x" });
      expect(runnable(document).every(parses)).toBe(true);
      expect(runnable(document).some((el) => el.textContent?.includes("__timelines.card ="))).toBe(
        true,
      );
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  it("mounts a JSON data script authored beside the root of an inline template composition", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><body>
  <template id="card-template">
    <script type="application/json" id="beside">{"where": "template"}</script>
    <div data-composition-id="card" data-width="320" data-height="180"></div>
  </template>
  <div id="root" data-composition-id="main" data-width="320" data-height="180" data-duration="2">
    <div data-composition-id="card" data-start="0" data-duration="2"></div>
  </div>
</body></html>`,
    });
    try {
      const document = parseHTML(await bundleToSingleHtml(dir)).document;
      const beside = document.querySelector('[data-composition-id="card"] #beside');
      expect(JSON.parse(beside?.textContent ?? "")).toEqual({ where: "template" });
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  it.each([
    [false, `<script>window.broken = {:</script>`],
    [true, `<script>window.broken = {:</script>`],
    [true, ""],
  ])(
    "escapes a composition script it does not merge (sceneParts %s, extra %j)",
    async (sceneParts, extra) => {
      const document = await bundleFilm(
        `<script src="lib.js"></script>${extra}`,
        { sceneParts },
        { "compositions/lib.js": 'window.tag = "</script><b>LEAK</b><!--";' },
      );
      expect(document.html).not.toContain("</script><b>LEAK");
      const lib = runnable(document).find((el) => el.textContent?.includes("LEAK"));
      const literal = lib?.textContent?.match(/window\.tag\s*=\s*("(?:[^"\\]|\\.)*")/)?.[1];
      expect(new Function(`return ${literal}`)()).toBe("</script><b>LEAK</b><!--");
    },
  );
});

describe("bundleToSingleHtml sceneParts", () => {
  const film = () =>
    makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080" data-duration="4">
    <div data-composition-id="a" data-composition-src="compositions/a.html" data-start="0" data-duration="2"></div>
    <div data-composition-id="b" data-composition-src="compositions/b.html" data-start="2" data-duration="2"></div>
  </div>
  <script>window.__rootRan = true;</script>
</body></html>`,
      "compositions/a.html": `<template id="a-template"><div data-composition-id="a">
  <style>.a-text { color: red; }</style><p class="a-text">A</p>
  <div data-composition-id="n" data-composition-src="compositions/n.html"></div>
  <script>window.__aRan = true;</script>
</div></template>`,
      "compositions/n.html": `<template id="n-template"><div data-composition-id="n">
  <style>.n-text { color: blue; }</style><p class="n-text">N</p><script>window.__nRan = true;</script>
</div></template>`,
      "compositions/b.html": `<template id="b-template"><div data-composition-id="b">
  <style>.b-text { color: green; }</style><p class="b-text">B</p><script>window.__bRan = true;</script>
</div></template>`,
    });
  const partsOf = (doc: Document, scene: string) =>
    [...doc.querySelectorAll(`[data-hf-scene="${scene}"]`)].map((el) => el.tagName.toLowerCase());

  it("puts a @font-face two scenes share in one style outside the scenes, once", async () => {
    const face = `@font-face { font-family: "Brand"; src: url('assets/fonts/brand.woff2'); }`;
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080" data-duration="4">
    <div data-composition-id="a" data-composition-src="compositions/a.html" data-start="0" data-duration="2"></div>
    <div data-composition-id="b" data-composition-src="compositions/b.html" data-start="2" data-duration="2"></div>
  </div>
</body></html>`,
      "compositions/a.html": `<template id="a-template"><div data-composition-id="a"><style>${face}</style><p>A</p></div></template>`,
      "compositions/b.html": `<template id="b-template"><div data-composition-id="b"><style>${face}</style><p>B</p></div></template>`,
    });
    const doc = parseHTML(
      await bundleToSingleHtml(dir, { sceneParts: true, inlineAssets: false }),
    ).document;
    for (const scene of ["a", "b"]) {
      const css = [...doc.querySelectorAll(`style[data-hf-scene="${scene}"]`)]
        .map((el) => el.textContent ?? "")
        .join("\n");
      expect(css).not.toContain("@font-face");
    }
    const fonts = doc.querySelector("style[data-hf-scene-fonts]");
    expect(fonts?.hasAttribute("data-hf-scene")).toBe(false);
    const faces = (css: string) => css.match(/@font-face/g)?.length ?? 0;
    expect(faces(fonts?.textContent ?? "")).toBe(1);
    const allCss = [...doc.querySelectorAll("style")].map((el) => el.textContent ?? "").join("\n");
    expect(faces(allCss)).toBe(1);
  });

  it("tags each top-level scene's host, styles and scripts, with nested scenes in their parent's parts", async () => {
    const doc = parseHTML(await bundleToSingleHtml(film(), { sceneParts: true })).document;
    // The nested scene is reached after b, so a's parts come in two runs around b's.
    expect(partsOf(doc, "a").sort()).toEqual(["div", "script", "script", "style", "style"]);
    expect(partsOf(doc, "b").sort()).toEqual(["div", "script", "style"]);
    expect(partsOf(doc, "n")).toEqual([]);
    const textOf = (selector: string) =>
      [...doc.querySelectorAll(selector)].map((el) => el.textContent ?? "").join("\n");
    const aStyle = textOf('style[data-hf-scene="a"]');
    const aScript = textOf('script[data-hf-scene="a"]');
    expect(aStyle).toContain("a-text");
    expect(aStyle).toContain("n-text");
    expect(aScript).toContain("__aRan");
    expect(aScript).toContain("__nRan");
    expect(aScript).not.toContain("__bRan");
    const shared = [
      ...doc.querySelectorAll("style:not([data-hf-scene]), script:not([data-hf-scene])"),
    ]
      .map((el) => el.textContent ?? "")
      .join("\n");
    expect(shared).not.toMatch(/a-text|b-text|__aRan|__bRan/);
    expect(shared).toContain("__rootRan");
  });

  it("emits styles and scripts in render order, a nested scene, an @import and root variables included", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html>
<html><head><style>.root-text { color: black; }</style></head><body>
  <div id="root" data-composition-id="main" data-width="1920" data-height="1080" data-duration="4">
    <div data-composition-id="a" data-composition-src="compositions/a.html" data-start="0" data-duration="2"
      data-variable-values='{"accent":"blue"}'></div>
    <div data-composition-id="b" data-composition-src="compositions/b.html" data-start="2" data-duration="2"></div>
  </div>
</body></html>`,
      "compositions/a.html": `<html data-composition-variables='[{"id":"accent","type":"string","label":"Accent","default":"red"}]'><body>
<template id="a-template"><div data-composition-id="a">
  <style>@keyframes pulse { to { opacity: 0.1; } }</style><p>A</p>
  <div data-composition-id="n" data-composition-src="compositions/n.html"></div>
  <script>window.__order = ["a"];</script>
</div></template></body></html>`,
      "compositions/n.html": `<template id="n-template"><div data-composition-id="n">
  <style>@keyframes pulse { to { opacity: 0.3; } }</style><p>N</p><script>window.__order.push("n");</script>
</div></template>`,
      "compositions/b.html": `<template id="b-template"><div data-composition-id="b">
  <link rel="stylesheet" href="https://fonts.example.com/b.css">
  <style>@import url("data:text/css,@keyframes%20pulse%7Bto%7Bopacity:0.9%7D%7D");
  @keyframes pulse { to { opacity: 0.2; } }</style><p>B</p><script>window.__order.push("b");</script>
</div></template>`,
    });
    const order = (html: string) => {
      const doc = parseHTML(html).document;
      const text = (sel: string) =>
        [...doc.querySelectorAll(sel)].map((el) => el.textContent ?? "");
      const js = text("script").join("\n");
      const head = [...doc.head.children].map((el) => el.tagName.toLowerCase());
      return {
        head: head.filter((tag, i) => tag !== head[i - 1]),
        css: text("style").join("").replace(/\s+/g, ""),
        scripts: ['["a"]', 'push("n")', 'push("b")'].sort((x, y) => js.indexOf(x) - js.indexOf(y)),
      };
    };
    expect(order(await bundleToSingleHtml(dir, { sceneParts: true }))).toEqual(
      order(await bundleToSingleHtml(dir)),
    );
  });

  it("leaves renders untagged", async () => {
    const html = await bundleToSingleHtml(film());
    expect(
      parseHTML(html).document.querySelector("[data-hf-scene], [data-hf-scene-no-swap]"),
    ).toBeNull();
    expect(html).toContain("__aRan");
  });

  it("puts every @import once at the front of the head, as a render's merged sheet does", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html><html><head></head><body>
  <div data-composition-id="main" data-width="1920" data-height="1080" data-duration="2">
    <div data-composition-id="a" data-composition-src="compositions/a.html" data-start="0" data-duration="2"></div>
  </div></body></html>`,
      "compositions/a.html": `<template id="a-template"><div data-composition-id="a">
  <style>.t { color: red; }</style>
  <div data-composition-id="n" data-composition-src="compositions/n.html"></div></div></template>`,
      "compositions/n.html": `<template id="n-template"><div data-composition-id="n">
  <style>@import url("https://fonts.example.com/inter.css"); .n { color: blue; }</style></div></template>`,
    });
    const doc = parseHTML(await bundleToSingleHtml(dir, { sceneParts: true })).document;
    const first = doc.querySelector(
      "head style:not([data-hf-scene]):not([data-hyperframes-text-rendering])",
    );
    expect(
      first?.textContent?.startsWith('@import url("https://fonts.example.com/inter.css")'),
    ).toBe(true);
    expect(doc.querySelector('style[data-hf-scene="a"]')?.textContent).not.toContain("@import");
    expect(styleText(doc.documentElement.outerHTML).match(/@import/g)).toHaveLength(1);
  });

  it("marks a scene whose own script leaves work running as not swappable, and only that scene", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html><html><head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
  <script src="https://cdn.example.com/d-scene.js"></script></head><body>
  <div data-composition-id="main" data-width="1920" data-height="1080" data-duration="4">
    <div data-composition-id="a" data-composition-src="compositions/a.html" data-start="0" data-duration="2"></div>
    <div data-composition-id="b" data-composition-src="compositions/b.html" data-start="2" data-duration="2"></div>
    <div data-composition-id="c" data-composition-src="compositions/c.html" data-start="0" data-duration="2"></div>
    <div data-composition-id="d" data-composition-src="compositions/d.html" data-start="2" data-duration="2"></div>
    <div data-composition-id="e" data-composition-src="compositions/e.html" data-start="2" data-duration="2"></div>
    <div data-composition-id="f" data-composition-src="compositions/f.html" data-start="2" data-duration="2"></div>
  </div></body></html>`,
      "compositions/e.html": `<template id="e-template"><div data-composition-id="e"><p>E</p>
  <script src="https://cdn.jsdelivr.net/npm/gsap@3/../lottie-web@5/build/player/lottie.min.js"></script></div></template>`,
      "compositions/f.html": `<template id="f-template"><div data-composition-id="f"><p>F</p>
  <script>gsap.timeline().to(window.__sharedState, { x: 1 });</script></div></template>`,
      "compositions/d.html": `<template id="d-template"><div data-composition-id="d"><p>D</p>
  <script src="https://cdn.example.com/d-scene.js"></script></div></template>`,
      "compositions/c.html": `<template id="c-template"><div data-composition-id="c"><p>C</p>
  <script src="c.js"></script></div></template>`,
      "compositions/c.js": `document.querySelector("p").animate([], 1000);`,
      "compositions/a.html": `<template id="a-template"><div data-composition-id="a"><p>A</p>
  <div data-composition-id="n" data-composition-src="compositions/n.html"></div>
  <script>window.__timelines = window.__timelines || {};</script></div></template>`,
      "compositions/n.html": `<template id="n-template"><div data-composition-id="n">
  <script>window.addEventListener("hf-seek", () => {});</script></div></template>`,
      "compositions/b.html": `<template id="b-template"><div data-composition-id="b"><p>B</p>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
  <script>gsap.timeline({ onComplete: () => {} });</script></div></template>`,
    });
    const doc = parseHTML(await bundleToSingleHtml(dir, { sceneParts: true })).document;
    const host = (id: string) => doc.querySelector(`div[data-hf-scene="${id}"]`);
    expect(host("a")?.getAttribute("data-hf-scene-no-swap")).toBe(
      "its script uses addEventListener",
    );
    expect(host("b")?.hasAttribute("data-hf-scene-no-swap")).toBe(false);
    expect(host("c")?.getAttribute("data-hf-scene-no-swap")).toBe(
      "it runs a script that is not a known library",
    );
    // The root loading the same URL does not make a scene's own initializer a library.
    expect(host("d")?.getAttribute("data-hf-scene-no-swap")).toBe(
      "it runs a script that is not a known library",
    );
    expect(host("e")?.getAttribute("data-hf-scene-no-swap")).toBe(
      "it runs a script that is not a known library",
    );
    // A timeline built and chained in one expression is never registered, so a swap leaves it running.
    expect(host("f")?.getAttribute("data-hf-scene-no-swap")).toBe(
      "its script uses gsap.timeline().to(",
    );
    const rendered = await bundleToSingleHtml(dir);
    expect(parseHTML(rendered).document.querySelector("[data-hf-scene-no-swap]")).toBeNull();
  });

  const rootProject = (root: string, extra: Record<string, string> = {}) =>
    makeTempProject({
      "index.html": `<!doctype html><html><head></head><body>
  <div data-composition-id="main" data-width="1920" data-height="1080" data-duration="2">
    <div data-composition-id="a" data-composition-src="compositions/a.html" data-start="0" data-duration="1"></div>
    <div data-composition-id="b" data-composition-src="compositions/b.html" data-start="1" data-duration="1"></div>
  </div>${root}</body></html>`,
      "compositions/a.html": `<template id="a-template"><div data-composition-id="a"><button class="go">Go</button><span id="count">0</span><em>!</em></div></template>`,
      "compositions/b.html": `<template id="b-template"><div data-composition-id="b"><p>B</p></div></template>`,
      ...extra,
    });
  const swapMarks = async (dir: string) => {
    const doc = parseHTML(await bundleToSingleHtml(dir, { sceneParts: true })).document;
    return ["a", "b"].map((id) =>
      doc.querySelector(`div[data-hf-scene="${id}"]`)?.getAttribute("data-hf-scene-no-swap"),
    );
  };

  it.each([
    [
      "binds a listener, inline",
      `<script>document.querySelector(".go").addEventListener("click", () => {});</script>`,
      {},
      ".go",
    ],
    [
      "binds a listener from a local file",
      `<script src="root.js"></script>`,
      { "root.js": `document.querySelector(".go").onclick = () => {};` },
      ".go",
    ],
    [
      "tweens a scene node from the root timeline",
      `<script>gsap.timeline({ paused: true }).to("#count", { opacity: 0 }, 1);</script>`,
      {},
      "#count",
    ],
    [
      "binds listeners by tag name",
      `<script>document.querySelectorAll("em").forEach((e) => e.addEventListener("click", () => {}));</script>`,
      {},
      "em",
    ],
    [
      "reaches a node by a tag selector",
      `<script>document.querySelector("div button").onclick = () => {};</script>`,
      {},
      "div button",
    ],
    [
      "updates a scene node from a timer",
      `<script>setTimeout(function tick() { document.getElementById("count").textContent++; setTimeout(tick, 100); }, 100);</script>`,
      {},
      "count",
    ],
    [
      "binds a listener from an inline template's script",
      `<template id="t-template"><div data-composition-id="t"><script>document.querySelector(".go").addEventListener("click", () => {});</script></div></template><div data-composition-id="t" data-start="0" data-duration="1"></div>`,
      {},
      ".go",
    ],
  ])("marks the scene a script outside it reaches when it %s", async (_, root, extra, selected) => {
    expect(await swapMarks(rootProject(root, extra))).toEqual([
      `a script outside the scene selects ${selected}`,
      null,
    ]);
  });

  const selects = (selector: string) => `a script outside the scene selects ${selector}`;
  it.each([
    ["an upper-case tag name", "BUTTON", [selects("BUTTON"), null]],
    ["everything", "*", [selects("*"), selects("*")]],
    ["everything, padded", " * ", [selects(" * "), selects(" * ")]],
    ["a tag above the scenes", "body button", [selects("body button"), null]],
    ["everything below a tag above the scenes", "body *", [selects("body *"), selects("body *")]],
  ] as const)(
    "marks the scenes a script outside them reaches by %s",
    async (_, selector, marks) => {
      const root = `<script>document.querySelectorAll("${selector}").forEach((el) => el.normalize());</script>`;
      expect(await swapMarks(rootProject(root))).toEqual(marks);
    },
  );

  it("keeps scenes swappable when a script outside them never names their nodes", async () => {
    const root = `<script>document.addEventListener("click", () => {}); requestAnimationFrame(() => {}); parent.postMessage({ at: Date.now() },
    "*"); document.querySelectorAll("NAV"); document.getElementById("Count");
  document.body.append(document.createElement("div"), document.createElementNS("http://www.w3.org/2000/svg", "span"));</script>
  <script type="application/json">{"note": "addEventListener"}</script>`;
    expect(await swapMarks(rootProject(root))).toEqual([null, null]);
  });

  it("runs a scene's local script file in source order with its inline scripts, as a render does", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html><html><head></head><body>
  <div data-composition-id="main" data-width="1920" data-height="1080" data-duration="2">
    <div data-composition-id="a" data-composition-src="compositions/a.html" data-start="0" data-duration="2"></div>
  </div></body></html>`,
      "compositions/a.html": `<template id="a-template"><div data-composition-id="a"><p>A</p>
  <script>window.__assetBase = "compositions/assets/";</script>
  <script src="reader.js"></script></div></template>`,
      "compositions/reader.js": `window.__readBase = window.__assetBase;`,
    });
    const order = (html: string) => [html.indexOf("__assetBase = "), html.indexOf("__readBase =")];
    const [setPreview, readPreview] = order(await bundleToSingleHtml(dir, { sceneParts: true }));
    const [setRender, readRender] = order(await bundleToSingleHtml(dir));
    expect(setRender).toBeGreaterThan(-1);
    expect(setRender).toBeLessThan(readRender);
    expect(setPreview).toBeGreaterThan(-1);
    expect(setPreview).toBeLessThan(readPreview);
  });

  it("refuses to swap a scene that runs a module script or an import map", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html><html><head></head><body>
  <div data-composition-id="main" data-width="1920" data-height="1080" data-duration="2">
    <div data-composition-id="m" data-composition-src="compositions/m.html" data-start="0" data-duration="1"></div>
    <div data-composition-id="i" data-composition-src="compositions/i.html" data-start="1" data-duration="1"></div>
  </div></body></html>`,
      "compositions/m.html": `<template id="m-template"><div data-composition-id="m"><p>M</p>
  <script type="module">window.__mRan = true;</script></div></template>`,
      "compositions/i.html": `<template id="i-template"><div data-composition-id="i"><p>I</p>
  <div data-composition-id="n" data-composition-src="compositions/n.html"></div></div></template>`,
      "compositions/n.html": `<template id="n-template"><div data-composition-id="n">
  <script type="importmap">{"imports":{"x":"./x.js"}}</script></div></template>`,
    });
    const doc = parseHTML(await bundleToSingleHtml(dir, { sceneParts: true })).document;
    for (const id of ["m", "i"]) {
      expect(
        doc.querySelector(`div[data-hf-scene="${id}"]`)?.getAttribute("data-hf-scene-no-swap"),
      ).toBe("it runs a module script or import map");
    }
  });

  it("refuses to swap a scene for every kind of work its script can leave behind", async () => {
    const leaks = [
      'window.addEventListener("resize", f)',
      "requestAnimationFrame(f)",
      "requestIdleCallback(f)",
      "setTimeout(f, 1)",
      "setInterval(f, 1)",
      "queueMicrotask(f)",
      'c.getContext("webgl")',
      "new WebGLRenderer()",
      "navigator.gpu",
      "new Worker(u)",
      "new Audio(u).play()",
      "new AudioContext()",
      "new ResizeObserver(f)",
      "fetch(u)",
      'import("x")',
      "eval(s)",
      "new Function(s)",
      "Promise.resolve()",
      "async function f() {}",
      "await img.decode()",
      "d3.json(u).then(f)",
      "el.animate([], 1000)",
      "gsap.ticker.add(f)",
      "gsap.delayedCall(1, f)",
      "ScrollTrigger.create({})",
      "lottie.loadAnimation({})",
      "new THREE.Scene()",
      "window.__hfLottie = []",
      "window.onresize = f",
      'el["onclick"] = f',
      "document.head.appendChild(s)",
      "document.body.append(s)",
      "new WebGPURenderer()",
      'customElements.define("x-a", A)',
      "CSS.registerProperty(p)",
      "new WebSocket(u)",
      "new EventSource(u)",
      "Draggable.create(el)",
      "anime({ loop: true })",
      'document.documentElement.style.setProperty("--x", "1")',
      'document.getElementsByTagName("head")[0]',
      'document.querySelector("body").append(s)',
      "gsap.to(el, { x: 1, repeat: -1 })",
      "onresize = f",
      'Object.defineProperty(window, "__ready", { value: true })',
      "matchMedia(q).addListener(f)",
      "tl.repeat(-1)",
      "document.fonts.add(face)",
      "document.adoptedStyleSheets = [sheet]",
      'history.pushState({}, "", u)',
      'new BroadcastChannel("c")',
      "gsap.to(window.__shared, { value: 200, duration: 10 })",
    ];
    const files: Record<string, string> = {};
    const hosts = leaks
      .map(
        (_, i) =>
          `<div data-composition-id="s${i}" data-composition-src="compositions/s${i}.html" data-start="0" data-duration="1"></div>`,
      )
      .join("\n");
    files["index.html"] = `<!doctype html><html><head></head><body>
  <div data-composition-id="main" data-width="1920" data-height="1080" data-duration="1">${hosts}</div></body></html>`;
    leaks.forEach((code, i) => {
      files[`compositions/s${i}.html`] =
        `<template id="s${i}-template"><div data-composition-id="s${i}"><p>${i}</p>
  <script>${code};</script></div></template>`;
    });
    const doc = parseHTML(
      await bundleToSingleHtml(makeTempProject(files), { sceneParts: true }),
    ).document;
    const unmarked = leaks.filter(
      (_, i) =>
        !doc.querySelector(`div[data-hf-scene="s${i}"]`)?.hasAttribute("data-hf-scene-no-swap"),
    );
    expect(unmarked).toEqual([]);
  });

  it("keeps the shared style's @import first when scene styles are split out", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html><html><head><style>.root { color: red; }
@import url("https://fonts.example.com/montserrat.css");</style></head><body>
  <div data-composition-id="main" data-width="1920" data-height="1080" data-duration="2">
    <div data-composition-id="a" data-composition-src="compositions/a.html" data-start="0" data-duration="2"></div>
  </div></body></html>`,
      "compositions/a.html": `<template id="a-template"><div data-composition-id="a"><style>.a { color: blue; }</style></div></template>`,
    });
    const shared = (html: string) =>
      [...parseHTML(html).document.querySelectorAll("head style:not([data-hf-scene])")]
        .map((el) => el.textContent ?? "")
        .find((css) => css.includes(".root")) ?? "";
    expect(shared(await bundleToSingleHtml(dir, { sceneParts: true })).startsWith("@import")).toBe(
      true,
    );
    expect(shared(await bundleToSingleHtml(dir)).startsWith("@import")).toBe(true);
  });

  it("does not refuse a scene for words that only look like side effects", async () => {
    const dir = makeTempProject({
      "index.html": `<!doctype html><html><head></head><body>
  <div data-composition-id="main" data-width="1920" data-height="1080" data-duration="1">
    <div data-composition-id="a" data-composition-src="compositions/a.html" data-start="0" data-duration="1"></div>
  </div></body></html>`,
      "compositions/a.html": `<template id="a-template"><div data-composition-id="a"><p id="nt-ticker-track">A</p>
  <script>
    // animate the title in, then hold
    const tl = gsap.timeline({ paused: true, onComplete: () => {} });
    tl.to("#nt-ticker-track", { x: 10, className: "fade-animate" });
    window.__timelines = window.__timelines || {};
    window.__timelines["a"] = tl;
    const state = {};
    Object.defineProperty(state, "flap", { get: () => 1 });
  </script></div></template>`,
    });
    const doc = parseHTML(await bundleToSingleHtml(dir, { sceneParts: true })).document;
    expect(
      doc.querySelector('div[data-hf-scene="a"]')?.getAttribute("data-hf-scene-no-swap"),
    ).toBeNull();
  });
});

describe("stampHfIds", () => {
  const project = () =>
    makeTempProject({
      "index.html": `<!doctype html><html><head></head><body><div id="root" data-composition-id="main" data-width="1920" data-height="1080"><div id="s" data-composition-id="scene" data-composition-src="compositions/scene.html" data-start="0" data-duration="3"></div></div></body></html>`,
      "compositions/scene.html": `<template id="scene-template"><div data-composition-id="scene" data-width="1920" data-height="1080"><img class="logo" src="logo.png"></div></template>`,
      "compositions/logo.png": "png",
    });
  const logo = (html: string) => /<img[^>]*class="logo"[^>]*>/.exec(html)?.[0] ?? "";

  it("gives an inlined element the id its source file mints, though the bundle re-points its src", async () => {
    const dir = project();
    const html = await bundleToSingleHtml(dir, { inlineAssets: false, stampHfIds: true });
    const source = ensureHfIds(
      `<template id="scene-template"><div data-composition-id="scene" data-width="1920" data-height="1080"><img class="logo" src="logo.png"></div></template>`,
    );
    expect(logo(html)).toContain("compositions/logo.png");
    expect(/data-hf-id="([^"]+)"/.exec(logo(html))?.[1]).toBe(
      /<img[^>]*data-hf-id="([^"]+)"/.exec(source)?.[1],
    );
  });

  it("leaves a render's bundle without ids", async () => {
    const html = await bundleToSingleHtml(project(), { inlineAssets: false });
    expect(logo(html)).toContain("compositions/logo.png");
    expect(logo(html)).not.toContain("data-hf-id");
  });
});

describe("emitRootCompositionVariableStyles — authored definitions", () => {
  function emitted(authoredCss: string): string {
    const { document } = parseHTML(
      `<!doctype html><html><head><style>${authoredCss}</style></head>` +
        `<body><div data-composition-id="card"></div></body></html>`,
    );
    emitRootCompositionVariableStyles(document, {
      card: { accent: "blue", "accent-dark": "navy" },
    });
    return document.querySelector("style[data-hf-composition-variables]")?.textContent ?? "";
  }

  it("leaves a variable the stylesheet defines, whatever space sits before its colon", () => {
    for (const authored of [
      ":root{--accent:red}",
      ":root { --accent : red }",
      ":root {\n  --accent\n  : red }",
    ]) {
      const css = emitted(authored);
      expect(css).not.toContain("--accent:");
      expect(css).toContain("--accent-dark: navy");
    }
  });

  it("still emits a variable whose name only begins a longer authored one, or is only read", () => {
    const css = emitted(":root { --accent-dark: black; } .badge { color: var(--accent); }");
    expect(css).toContain("--accent: blue");
    expect(css).not.toContain("--accent-dark");
  });
});