mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-19 11:26:02 +00:00
* fix(cli): a subfolder of an imported project keeps its received-files record Publish, cloud render and feedback now read the received-files record at the nearest folder at or above the one they stage, so staging a subfolder of an imported project still leaves out the outside files its received files reference. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): a received file counts under any spelling of the same file on disk The received-files lookup now also matches a project file that is the same file on disk as a listed path, so a name respelled in letter case on a case-insensitive disk keeps its received status. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): cloud render prepares only the GIFs staging kept The entry GIF prep before a cloud render upload now reads only the staged copies it is handed. An image whose source staging left out keeps its reference as written and is never read from disk. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli,studio-server): never hand a playlist named as media to ffmpeg A media file whose first bytes are an HLS playlist, an XML manifest or a concat script now stays out of ffprobe and ffmpeg: cloud render leaves it in the zip as authored, the media probe reports it as not media, and the proxy copy refuses it. Real media never starts with these bytes, so it probes and transcodes as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(studio-server): catch playlists with control bytes, and keep them from stills and audio probes A text playlist or concat script is detected whatever bytes follow its first line; only markup must be all text. A still frame and the audio probe behind waveforms, peaks and loudness now refuse a file the probe reads as not media, as the proxy copy already does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): a parent folder's state the CLI cannot read never marks a project received The walk up for a received-files record now skips a parent whose record cannot be reached. Only a record file that is there but cannot be read or parsed counts every file as received. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): a drive that reports no file ids matches no received file by identity Some network and virtual drives report a file id of 0 for every file, so the same-file match now gives such a file no identity instead of matching it to every listed file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(studio-server): read a media file's first bytes with a read stream The playlist check reads the first 64 bytes through a bounded read stream instead of a raw file descriptor, and the audio-track probe's doc comment sits on its function again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(studio-server): raise the packed size budget for the media playlist check Main packs @hyperframes/studio-server close to the 1% tolerance on the 168500 budget, and the playlist check adds about 320 bytes, which put the Build over. Set the budget to 172000. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli,studio-server): open media only through self-contained media demuxers Every ffprobe and ffmpeg input that cloud render offload, the publish proxy bake and Studio's media helpers open now carries a demuxer whitelist built from the supported media extensions: MP4/MOV/M4A/AVIF, Matroska/WebM, MXF, AVI, MPEG-PS/TS, FLV, ASF, Ogg, WAV, MP3, AAC, FLAC, AIFF and the still-image formats. Playlist, manifest and concat demuxers can no longer open, whatever a file's bytes say. The proxy's own concat step is left as it is. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli,studio-server): keep media probe argv flat, and expect the demuxer list in loudness args Two probe argv literals built from nested spreads are flat again, so "--" stays the visible second-to-last entry the argv contract checks. The normalize-audio test expects the demuxer list before the input. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): play and present answer only local host names and allowed hosts play and present listen on every interface. Each request now passes the same Host check preview uses: localhost, loopback addresses and this machine's own addresses and names are answered, and any other host name gets a 403 naming HYPERFRAMES_PREVIEW_ALLOWED_HOSTS until it is listed there. Phones and other machines on the network still open them by LAN address or .local name. * fix(cli): a local render of a received composition leaves out files outside the project When the composition a local render opens is listed in the project's received-files record, hyperframes render (full and range) no longer brings in files outside the project. It prints one line naming the references it leaves out and why. An unreadable record counts as received. A project whose entry is the person's own, or that has no record, renders exactly as before. * fix(cli): received-render scan reads safely and treats an unreadable record as unknown The scan behind the received-composition notice skips a file it cannot read, finds url() references with a linear forward scan, and reads at most 2 MB of each file. An unreadable received-files record no longer counts as everything received for local render: the render keeps outside files and names the record it could not read. Publish and cloud upload still treat it as received. The notice now says the render stops on a sub-composition outside the project rather than leaving it out. * fix(cli): the studio render of a received composition leaves out files outside the project The Studio render route applies the same rule as hyperframes render: when the composition it renders is listed in the received-files record, the job does not bring in files outside the project, and the server log names the references it refuses. * chore(cli): name the unreadable received-files record helper without a comment * fix(cli): local render refuses outside files when any composition it plays was received The received-file rule for local render (CLI and Studio) now checks every page and stylesheet the render pulls in, not only the entry, so an own index.html that plays a received scene also reads nothing outside the project, and the notice names the received file. An unreadable, truncated or empty received-files record refuses outside files too, as publish and cloud upload do, and the notice names the record it could not read. * fix(cli): decide a received render from the files the compiler reads Local render (CLI and Studio) now leaves outside-file handling as it is for a project with no received-files record or an empty one, without scanning anything. When the record lists files, the compiler's own read list for the composition decides: the bundler runs out of process with a deadline and reports every project file it reads, so stylesheet imports and files past any scan limit count. A received file in that list, a build that fails or runs past its deadline, or an unreadable record refuses outside files. The scan that names refused references in the notice is advisory only: it guards every file system call, tracks visited files by real path, and caps the files and bytes it reads. * fix(cli,producer): decide a received render with the render compiler's own composition traversal The producer exports renderCompositionFiles, which walks data-composition-src with the same resolution, normalization and private file rules the render's sub-composition pass uses; that pass now calls the same helper. The received-render decision adds those files to the bundler's read list, so leading-slash and percent-encoded references the render reads count. The advisory scan resolves compositions the same way and reads template contents. * fix(cli): refuse outside files in a local render whenever the project has received files A local render (CLI and Studio) reads nothing outside the project when the project's received-files record lists any file, or cannot be read. No static list matches what a render consumes: the page loads its stylesheets and scripts through the browser at capture time, and scripts can load more, so the decision no longer depends on one. The reference scan stays only to name what the notice says is left out. This drops the out-of-process bundler read list and the producer composition walk added for that decision. * fix(cli): refuse outside files only when a received file can load other files A local render (CLI and Studio) reads nothing outside the project when the received-files record cannot be read, or lists a received file that can reference others: an .html, .htm, .css, .js, .mjs, .cjs or .svg name, or content that reads as HTML, SVG or CSS. A project that only received images, video, audio or fonts keeps bringing in outside files as before. * fix(cli): keep outside files only when every received file is positively media, a font or an image A local render keeps bringing in outside files only when each file the received-files record lists has a known media, font or image extension and starts with that type's signature bytes. Any other received file, a listed file that is missing or unreadable, or a mismatch between name and content refuses outside files. An ancestor record's entries now match a subfolder whose name is spelled in another Unicode form; the entry keeps its own spelling on disk. * fix(producer,core): a sub-composition must be an .html file The render compiler and the runtime load a data-composition-src only when it names an .html or .htm file. Any other file, such as an image or video, is refused as a page: render stops naming it, and the runtime reports the load failure without fetching it. * fix(producer,cli): the render and static file servers forbid type sniffing Both servers send X-Content-Type-Options: nosniff with every response, so the browser loads a file only as the type its extension names: an image or video cannot run as a script or apply as a stylesheet. .cjs is served as JavaScript. * test(cli): a received media file in a composition slot is refused as a page * test(cli): an empty nested received-files record cannot hide an outer record's received page * fix(cli): a received media file reached under another name refuses outside files The received-render decision now compares file identities, not names. It walks the project once, bounded by entry count and time, and refuses outside files when a hardlink or a symlink with a name that is not media reaches a received file, or when the walk cannot finish. A received file with no identity matches nothing, as in the received files check. * fix(cli): compare received files by link target and keep outside files for an empty record A received media file and every other project name are now compared by the identity of the file they reach with links followed. A linked folder that leads outside the project, or a file whose identity cannot be read, counts as unchecked and refuses outside files. An empty received-files record keeps outside files without walking the project. * chore: raise the producer unpacked size budget for the composition file checks --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1981 lines
77 KiB
TypeScript
1981 lines
77 KiB
TypeScript
import { describe, it, expect, vi, afterEach, beforeAll } from "vitest";
|
|
import { loadCompositions } from "./compositionLoader";
|
|
|
|
type LoaderParams = Parameters<typeof loadCompositions>[0];
|
|
|
|
function createLoaderParams(overrides: Partial<LoaderParams> = {}): LoaderParams {
|
|
return {
|
|
injectedStyles: [],
|
|
injectedScripts: [],
|
|
injectedLinks: [],
|
|
parseDimensionPx: (value) => (value ? `${value}px` : null),
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
async function loadFixture(overrides: Partial<LoaderParams> = {}) {
|
|
const params = createLoaderParams(overrides);
|
|
await loadCompositions(params);
|
|
return params;
|
|
}
|
|
|
|
function appendExternalHost(source: string, compositionId: string): HTMLDivElement {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", source);
|
|
host.setAttribute("data-composition-id", compositionId);
|
|
document.body.appendChild(host);
|
|
return host;
|
|
}
|
|
|
|
// jsdom doesn't provide CSS.escape
|
|
const nativeQuerySelector = Element.prototype.querySelector;
|
|
const nativeQuerySelectorAll = Element.prototype.querySelectorAll;
|
|
afterEach(() => {
|
|
Element.prototype.querySelector = nativeQuerySelector;
|
|
Element.prototype.querySelectorAll = nativeQuerySelectorAll;
|
|
delete window.__hfSvgSelectorAliases;
|
|
});
|
|
|
|
beforeAll(() => {
|
|
if (typeof globalThis.CSS === "undefined") {
|
|
(globalThis as any).CSS = {};
|
|
}
|
|
if (typeof CSS.escape !== "function") {
|
|
CSS.escape = (value: string) => value.replace(/([^\w-])/g, "\\$1");
|
|
}
|
|
});
|
|
|
|
describe("loadCompositions external hosts", () => {
|
|
afterEach(() => {
|
|
document.body.innerHTML = "";
|
|
document.head.querySelectorAll("style, link").forEach((node) => node.remove());
|
|
delete (window as Window & { gsap?: unknown; __selectedTitle?: unknown }).gsap;
|
|
delete (window as Window & { gsap?: unknown; __selectedTitle?: unknown }).__selectedTitle;
|
|
delete (window as Window & { __hyperframes?: unknown }).__hyperframes;
|
|
delete (window as Window & { __timelines?: unknown }).__timelines;
|
|
delete (window as WindowWithScopedVars).__hfVariablesByComp;
|
|
delete (document as { fonts?: unknown }).fonts;
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
it("does nothing when no composition-src elements exist", async () => {
|
|
const fetchSpy = vi.spyOn(globalThis, "fetch");
|
|
await loadFixture();
|
|
expect(fetchSpy).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("binds a fetched composition's scripts to its own URL for __hyperframes.assetUrl", async () => {
|
|
appendExternalHost("https://example.com/blocks/blk/blk.html", "blk");
|
|
const compositionHtml =
|
|
`<div data-composition-id="blk"><script>window.__url = __hyperframes.assetUrl("assets/env.hdr");</scr` +
|
|
`ipt></div>`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
const { injectedScripts } = await loadFixture();
|
|
|
|
expect(injectedScripts.map((script) => script.textContent).join("")).toContain(
|
|
'var __hfCompositionSrc = "https://example.com/blocks/blk/blk.html";',
|
|
);
|
|
});
|
|
|
|
it("injects a fetched composition's import map and module script bound to its own URL", async () => {
|
|
appendExternalHost("https://example.com/blocks/blk/blk.html", "blk");
|
|
const compositionHtml =
|
|
`<div data-composition-id="blk">` +
|
|
`<script type="importmap">{ "imports": { "three": "./lib/three.js" } }</scr` +
|
|
`ipt><script type="module">import "three"; window.__url = __hyperframes.assetUrl("a.png");</scr` +
|
|
`ipt></div>`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
const { injectedScripts } = await loadFixture();
|
|
|
|
const importMap = injectedScripts.find((script) => script.type === "importmap");
|
|
const moduleScript = injectedScripts.find((script) => script.type === "module");
|
|
expect(JSON.parse(importMap?.textContent || "")).toEqual({
|
|
imports: { three: "https://example.com/blocks/blk/lib/three.js" },
|
|
});
|
|
expect(moduleScript?.textContent).toMatch(/^const __hyperframes = /);
|
|
expect(moduleScript?.textContent).toContain('"https://example.com/blocks/blk/blk.html"');
|
|
});
|
|
|
|
it("mounts import maps with blocked entries and rebases only usable addresses", async () => {
|
|
appendExternalHost("https://example.com/blocks/blk/blk.html", "blk");
|
|
const compositionHtml =
|
|
'<div data-composition-id="blk"><script type="importmap">' +
|
|
'{"imports":{"ok":"./ok.js","blocked":null,"number":17},"scopes":{"./lib/":{"ok":"./scoped.js","blocked":null}}}' +
|
|
"</scr" +
|
|
'ipt><script type="module">import "ok";</scr' +
|
|
"ipt></div>";
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
const { injectedScripts } = await loadFixture();
|
|
const map = injectedScripts.find((script) => script.type === "importmap");
|
|
expect(JSON.parse(map?.textContent || "null")).toEqual({
|
|
imports: { ok: "https://example.com/blocks/blk/ok.js", blocked: null, number: null },
|
|
scopes: {
|
|
"https://example.com/blocks/blk/lib/": {
|
|
ok: "https://example.com/blocks/blk/scoped.js",
|
|
blocked: null,
|
|
},
|
|
},
|
|
});
|
|
expect(injectedScripts.some((script) => script.type === "module")).toBe(true);
|
|
});
|
|
|
|
it("fetches and mounts external composition HTML", async () => {
|
|
const host = appendExternalHost("https://example.com/comp.html", "scene-1");
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<div data-composition-id="scene-1" data-width="1920" data-height="1080">
|
|
<p>Hello World</p>
|
|
</div>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
await loadFixture();
|
|
|
|
const mountedParagraph = host.querySelector("p");
|
|
|
|
expect(mountedParagraph).toBeTruthy();
|
|
expect(mountedParagraph?.textContent).toBe("Hello World");
|
|
expect(host.getAttribute("data-width")).toBe("1920");
|
|
expect(host.getAttribute("data-height")).toBe("1080");
|
|
expect(
|
|
Array.from(host.children).some(
|
|
(child) => child.getAttribute("data-composition-id") === "scene-1",
|
|
),
|
|
).toBe(false);
|
|
});
|
|
|
|
it.each([
|
|
["a card template before the scene", `<template><div class="card">card</div></template>`, ""],
|
|
[
|
|
"two scene templates",
|
|
"",
|
|
`<template><div data-composition-id="other"><p>second scene</p></div></template>`,
|
|
],
|
|
])("mounts the scene template of a fetched file with %s", async (_label, before, after) => {
|
|
const host = appendExternalHost("https://example.com/comp.html", "scene-1");
|
|
const scene = `<template><div data-composition-id="scene-1"><p>Hello World</p></div></template>`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(`${before}${scene}${after}`, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
expect(host.textContent).toContain("Hello World");
|
|
expect(host.textContent).not.toContain("card");
|
|
expect(host.textContent).not.toContain("second scene");
|
|
});
|
|
|
|
it("sizes a flattened inner root from a px-suffixed or fractional size", async () => {
|
|
const host = appendExternalHost("https://example.com/comp.html", "scene-1");
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<div data-composition-id="scene-1" data-width="1080px" data-height="540.5"><p>Hi</p></div>
|
|
</body></html>
|
|
`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
await loadFixture();
|
|
|
|
const flattened = host.querySelector("p")?.parentElement;
|
|
expect(flattened?.style.width).toBe("1080px");
|
|
expect(flattened?.style.height).toBe("540.5px");
|
|
});
|
|
|
|
it("injects styles into document head", async () => {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "https://example.com/comp.html");
|
|
document.body.appendChild(host);
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<style>.test { color: red; }</style>
|
|
<p>Styled</p>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
const { injectedStyles } = await loadFixture();
|
|
|
|
expect(injectedStyles.length).toBeGreaterThan(0);
|
|
});
|
|
|
|
it("mounts <style>/<script> authored as siblings of the composition root", async () => {
|
|
// The canonical sub-composition shape puts <style> and <script> directly
|
|
// inside <template>, NEXT TO the root div rather than inside it. Collecting
|
|
// only from the root dropped the composition's whole stylesheet, so rules
|
|
// keyed on the root (`#root { container-type: size }`) never landed and every
|
|
// container-query unit in the composition resolved against the wrong basis.
|
|
const host = appendExternalHost("https://example.com/scene.html", "scene");
|
|
|
|
const compositionHtml =
|
|
`
|
|
<html><body>
|
|
<template>
|
|
<style>#root { container-type: size; }</style>
|
|
<div id="root" data-composition-id="scene"><p>Scene</p></div>
|
|
<script>window.__sceneRan = true;</scr` +
|
|
`ipt>
|
|
</template>
|
|
</body></html>
|
|
`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
const { injectedStyles, injectedScripts } = await loadFixture();
|
|
|
|
expect(injectedStyles.map((style) => style.textContent).join("")).toContain(
|
|
"container-type: size",
|
|
);
|
|
expect(injectedScripts.map((script) => script.textContent).join("")).toContain("__sceneRan");
|
|
// The extracted nodes are stripped from the mounted copy, not duplicated.
|
|
expect(host.querySelectorAll("style, script")).toHaveLength(0);
|
|
expect(host.querySelector("p")?.textContent).toBe("Scene");
|
|
});
|
|
|
|
it.each(["scene", "different-host-id"])(
|
|
"hoists fragment stylesheets once for %s",
|
|
async (hostId) => {
|
|
const host = appendExternalHost("https://example.com/compositions/scene.html", hostId);
|
|
const html = `<div data-composition-id="scene">
|
|
<link rel="stylesheet" href="scene.css"><link rel="icon" href="icon.svg"><p>Styled scene</p></div>`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(html, { status: 200 }));
|
|
|
|
await loadFixture();
|
|
|
|
expect(
|
|
document.head.querySelectorAll('link[href="https://example.com/compositions/scene.css"]'),
|
|
).toHaveLength(1);
|
|
expect(host.querySelectorAll('link[rel="stylesheet"]')).toHaveLength(0);
|
|
expect(host.querySelectorAll('link[rel="icon"]')).toHaveLength(1);
|
|
expect(host.querySelector("p")?.textContent).toBe("Styled scene");
|
|
},
|
|
);
|
|
|
|
it("preserves head stylesheets when an external composition uses a template", async () => {
|
|
appendExternalHost("https://example.com/compositions/scene.html", "scene");
|
|
|
|
const compositionHtml = `
|
|
<html>
|
|
<head><link rel="stylesheet" href="./scene.css"></head>
|
|
<body>
|
|
<template id="scene-template">
|
|
<div data-composition-id="scene"><p>Styled scene</p></div>
|
|
</template>
|
|
</body>
|
|
</html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
await loadFixture();
|
|
|
|
expect(
|
|
document.head.querySelector(
|
|
'link[rel="stylesheet"][href="https://example.com/compositions/scene.css"]',
|
|
),
|
|
).not.toBeNull();
|
|
});
|
|
|
|
it("does not resolve an empty stylesheet href to the composition HTML", async () => {
|
|
appendExternalHost("https://example.com/compositions/scene.html", "scene");
|
|
|
|
const compositionHtml = `
|
|
<html>
|
|
<head><link rel="stylesheet" href=""></head>
|
|
<body>
|
|
<template id="scene-template">
|
|
<div data-composition-id="scene"><p>Unstyled scene</p></div>
|
|
</template>
|
|
</body>
|
|
</html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
await loadFixture();
|
|
|
|
expect(
|
|
document.head.querySelector(
|
|
'link[rel="stylesheet"][href="https://example.com/compositions/scene.html"]',
|
|
),
|
|
).toBeNull();
|
|
});
|
|
|
|
it("does not inject stylesheet href variants that resolve to the composition document", async () => {
|
|
appendExternalHost("https://example.com/compositions/scene.html", "scene");
|
|
|
|
const compositionHtml = `
|
|
<html>
|
|
<head>
|
|
<link rel="stylesheet" href=" ">
|
|
<link rel="stylesheet" href="#theme">
|
|
<link rel="stylesheet" href="?v=1">
|
|
<link rel="stylesheet" href="./scene.html?v=2#theme">
|
|
<link rel="stylesheet" href="./scene.css?v=1">
|
|
</head>
|
|
<body>
|
|
<template id="scene-template">
|
|
<div data-composition-id="scene"><p>Styled scene</p></div>
|
|
</template>
|
|
</body>
|
|
</html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
await loadFixture();
|
|
|
|
const injectedHrefs = Array.from(document.head.querySelectorAll('link[rel="stylesheet"]')).map(
|
|
(link) => (link as HTMLLinkElement).href,
|
|
);
|
|
expect(injectedHrefs).toEqual(["https://example.com/compositions/scene.css?v=1"]);
|
|
});
|
|
|
|
it("does not execute head script src variants that resolve to the composition document", async () => {
|
|
appendExternalHost("https://example.com/compositions/scene.html", "scene");
|
|
|
|
const compositionHtml = `
|
|
<html>
|
|
<head>
|
|
<script src="#theme"></script>
|
|
<script src="?v=1"></script>
|
|
<script src="./scene.html?v=2#theme"></script>
|
|
</head>
|
|
<body><div data-composition-id="scene"><p>Scene</p></div></body>
|
|
</html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
const originalAppendChild = document.body.appendChild.bind(document.body);
|
|
vi.spyOn(document.body, "appendChild").mockImplementation((node: Node) => {
|
|
const appended = originalAppendChild(node);
|
|
if (node instanceof HTMLScriptElement && node.src) {
|
|
queueMicrotask(() => node.dispatchEvent(new Event("load")));
|
|
}
|
|
return appended;
|
|
});
|
|
|
|
const { injectedScripts } = await loadFixture();
|
|
|
|
expect(injectedScripts).toEqual([]);
|
|
});
|
|
|
|
it("does not execute content script src variants that resolve to the composition document", async () => {
|
|
appendExternalHost("https://example.com/compositions/scene.html", "scene");
|
|
|
|
const compositionHtml = `
|
|
<html>
|
|
<body>
|
|
<div data-composition-id="scene">
|
|
<p>Scene</p>
|
|
<script src="#theme"></script>
|
|
<script src="?v=1"></script>
|
|
<script src="./scene.html?v=2#theme"></script>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
const { injectedScripts } = await loadFixture();
|
|
|
|
expect(injectedScripts).toEqual([]);
|
|
});
|
|
|
|
it("does not fail composition mounting when a head script src is malformed", async () => {
|
|
appendExternalHost("https://example.com/compositions/scene.html", "scene");
|
|
|
|
const compositionHtml = `
|
|
<html>
|
|
<head><script src="http://[invalid"></script></head>
|
|
<body><div data-composition-id="scene"><p>Scene</p></div></body>
|
|
</html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
const originalAppendChild = document.body.appendChild.bind(document.body);
|
|
vi.spyOn(document.body, "appendChild").mockImplementation((node: Node) => {
|
|
const appended = originalAppendChild(node);
|
|
if (node instanceof HTMLScriptElement && node.src) {
|
|
queueMicrotask(() => node.dispatchEvent(new Event("load")));
|
|
}
|
|
return appended;
|
|
});
|
|
|
|
const onDiagnostic = vi.fn();
|
|
const { injectedScripts } = await loadFixture({ onDiagnostic });
|
|
|
|
expect(injectedScripts).toHaveLength(1);
|
|
expect(onDiagnostic).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("calls onDiagnostic when fetch fails", async () => {
|
|
appendExternalHost("https://example.com/broken.html", "broken");
|
|
|
|
vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("Network error"));
|
|
|
|
const onDiagnostic = vi.fn();
|
|
await loadCompositions({
|
|
...createLoaderParams(),
|
|
onDiagnostic,
|
|
});
|
|
|
|
expect(onDiagnostic).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
code: "external_composition_load_failed",
|
|
details: expect.objectContaining({
|
|
hostCompositionSrc: "https://example.com/broken.html",
|
|
errorMessage: "Network error",
|
|
}),
|
|
}),
|
|
);
|
|
});
|
|
|
|
it.each(["https://example.com/scene.png", "https://example.com/scene.mp4?x=.html", "scene"])(
|
|
"never fetches a data-composition-src that is not an .html file: %s",
|
|
async (src) => {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", src);
|
|
document.body.appendChild(host);
|
|
const fetchSpy = vi
|
|
.spyOn(globalThis, "fetch")
|
|
.mockResolvedValue(new Response("<p>media as page</p>"));
|
|
const onDiagnostic = vi.fn();
|
|
await loadCompositions({ ...createLoaderParams(), onDiagnostic });
|
|
expect(fetchSpy).not.toHaveBeenCalled();
|
|
expect(host.innerHTML).not.toContain("media as page");
|
|
expect(onDiagnostic).toHaveBeenCalledWith(
|
|
expect.objectContaining({ code: "external_composition_load_failed" }),
|
|
);
|
|
},
|
|
);
|
|
|
|
it("calls onDiagnostic when HTTP response is not ok", async () => {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "https://example.com/404.html");
|
|
document.body.appendChild(host);
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("Not Found", { status: 404 }));
|
|
|
|
const onDiagnostic = vi.fn();
|
|
await loadCompositions({
|
|
...createLoaderParams(),
|
|
onDiagnostic,
|
|
});
|
|
|
|
expect(onDiagnostic).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
code: "external_composition_load_failed",
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("uses local template when available", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "local-comp-template";
|
|
template.innerHTML = "<p>From template</p>";
|
|
document.body.appendChild(template);
|
|
|
|
const host = appendExternalHost("https://example.com/comp.html", "local-comp");
|
|
|
|
const fetchSpy = vi.spyOn(globalThis, "fetch");
|
|
|
|
await loadFixture();
|
|
|
|
// Should use local template and not fetch
|
|
expect(fetchSpy).not.toHaveBeenCalled();
|
|
expect(host.querySelector("p")?.textContent).toBe("From template");
|
|
});
|
|
|
|
it("skips hosts without data-composition-src value", async () => {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "");
|
|
document.body.appendChild(host);
|
|
|
|
const fetchSpy = vi.spyOn(globalThis, "fetch");
|
|
await loadFixture();
|
|
expect(fetchSpy).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("clears host content before mounting", async () => {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "https://example.com/comp.html");
|
|
host.innerHTML = "<span>Old content</span>";
|
|
document.body.appendChild(host);
|
|
|
|
const compositionHtml = `<html><body><p>New</p></body></html>`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
await loadFixture();
|
|
expect(host.querySelector("span")).toBeNull();
|
|
});
|
|
|
|
it("handles inline scripts", async () => {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "https://example.com/comp.html");
|
|
document.body.appendChild(host);
|
|
|
|
// Only inline scripts (no external src) to avoid waitForExternalScriptLoad timeout
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<script>console.log("inline")</script>
|
|
<p>With inline script</p>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
const { injectedScripts } = await loadFixture();
|
|
|
|
expect(injectedScripts.length).toBeGreaterThan(0);
|
|
expect(injectedScripts[0].textContent).toContain("console.log");
|
|
});
|
|
|
|
it("mounts the content, then runs its scripts only once web fonts are ready", async () => {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "https://example.com/comp.html");
|
|
document.body.appendChild(host);
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(`<html><body><p>Text</p><script>void 0</script></body></html>`, {
|
|
status: 200,
|
|
}),
|
|
);
|
|
let fontsLoaded = () => {};
|
|
const ready = new Promise<void>((resolve) => (fontsLoaded = resolve));
|
|
Object.defineProperty(document, "fonts", { configurable: true, value: { ready } });
|
|
const injectedScripts: HTMLScriptElement[] = [];
|
|
|
|
const loading = loadCompositions({ ...createLoaderParams(), injectedScripts });
|
|
await vi.waitFor(() => expect(host.textContent).toContain("Text"));
|
|
expect(injectedScripts).toHaveLength(0);
|
|
fontsLoaded();
|
|
await loading;
|
|
expect(injectedScripts).toHaveLength(1);
|
|
});
|
|
|
|
it("scopes injected styles and document selectors to the mounted composition root", async () => {
|
|
const otherRoot = document.createElement("div");
|
|
otherRoot.setAttribute("data-composition-id", "other");
|
|
otherRoot.innerHTML = '<h1 class="title">Other</h1>';
|
|
document.body.appendChild(otherRoot);
|
|
|
|
const host = appendExternalHost("https://example.com/comp.html", "scene");
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<div data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<style>.title { opacity: 0; }</style>
|
|
<h1 class="title">Scene</h1>
|
|
<script>
|
|
window.__selectedTitle = document.querySelector('.title')?.textContent;
|
|
</script>
|
|
</div>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
const { injectedStyles, injectedScripts } = await loadFixture();
|
|
|
|
expect(injectedStyles[0]?.textContent).toContain('[data-composition-id="scene"] .title');
|
|
expect(injectedScripts[0]?.textContent).toContain('var __hfCompId = "scene";');
|
|
expect(injectedScripts[0]?.textContent).toContain("new Proxy(window.document");
|
|
expect(host.querySelector(".title")?.textContent).toBe("Scene");
|
|
expect(
|
|
Array.from(host.children).some(
|
|
(child) => child.getAttribute("data-composition-id") === "scene",
|
|
),
|
|
).toBe(false);
|
|
});
|
|
|
|
it("preserves the authored inner root wrapper for class and id scoped styles", async () => {
|
|
const host = appendExternalHost("https://example.com/comp.html", "scene");
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<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>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
const { injectedStyles } = await loadFixture();
|
|
|
|
const authoredRoot = host.querySelector('[data-hf-authored-id="scene-root"]');
|
|
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(injectedStyles[0]?.textContent).toContain(
|
|
'[data-composition-id="scene"] .scene-root .title',
|
|
);
|
|
expect(injectedStyles[0]?.textContent).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 hostA = document.createElement("div");
|
|
hostA.setAttribute("data-composition-src", "https://example.com/comp.html");
|
|
hostA.setAttribute("data-composition-id", "scene");
|
|
document.body.appendChild(hostA);
|
|
|
|
const hostB = document.createElement("div");
|
|
hostB.setAttribute("data-composition-src", "https://example.com/comp.html");
|
|
hostB.setAttribute("data-composition-id", "scene");
|
|
document.body.appendChild(hostB);
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<div id="scene-root" class="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<h1 class="title">Scene</h1>
|
|
</div>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockImplementation(
|
|
async () => new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
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("isolates sibling instances of the same external sub-composition at runtime", async () => {
|
|
const hostA = document.createElement("div");
|
|
hostA.setAttribute("data-composition-src", "https://example.com/scene.html");
|
|
hostA.setAttribute("data-composition-id", "scene");
|
|
hostA.setAttribute("data-variable-values", '{"title":"Scene A"}');
|
|
document.body.appendChild(hostA);
|
|
|
|
const hostB = document.createElement("div");
|
|
hostB.setAttribute("data-composition-src", "https://example.com/scene.html");
|
|
hostB.setAttribute("data-composition-id", "scene");
|
|
hostB.setAttribute("data-variable-values", '{"title":"Scene B"}');
|
|
document.body.appendChild(hostB);
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<div id="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<style>[data-composition-id="scene"] .title { opacity: 0; }</style>
|
|
<h1 class="title">Default</h1>
|
|
<script>
|
|
const titleEl = document.querySelector(".title");
|
|
const runtimeId = titleEl?.closest("[data-composition-id]")?.getAttribute("data-composition-id") || "missing";
|
|
if (titleEl) titleEl.textContent = runtimeId;
|
|
window.__timelines = window.__timelines || {};
|
|
window.__timelines["scene"] = { marker: runtimeId };
|
|
</script>
|
|
</div>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockImplementation(
|
|
async () => new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
const { injectedScripts } = await loadFixture();
|
|
|
|
const runtimeIdA = hostA.getAttribute("data-composition-id") ?? "";
|
|
const runtimeIdB = hostB.getAttribute("data-composition-id") ?? "";
|
|
const variables =
|
|
(window as Window & { __hfVariablesByComp?: Record<string, { title?: string }> })
|
|
.__hfVariablesByComp ?? {};
|
|
|
|
expect(runtimeIdA).not.toBe("scene");
|
|
expect(runtimeIdB).not.toBe("scene");
|
|
expect(runtimeIdA).not.toBe(runtimeIdB);
|
|
expect(hostA.getAttribute("data-hf-original-composition-id")).toBe("scene");
|
|
expect(hostB.getAttribute("data-hf-original-composition-id")).toBe("scene");
|
|
expect(hostA.querySelector(".title")?.textContent).toBe(runtimeIdA);
|
|
expect(hostB.querySelector(".title")?.textContent).toBe(runtimeIdB);
|
|
expect(variables[runtimeIdA]?.title).toBe("Scene A");
|
|
expect(variables[runtimeIdB]?.title).toBe("Scene B");
|
|
expect(
|
|
injectedScripts.some((script) =>
|
|
script.textContent?.includes(`var __hfTimelineCompId = "${runtimeIdA}"`),
|
|
),
|
|
).toBe(true);
|
|
expect(
|
|
injectedScripts.some((script) =>
|
|
script.textContent?.includes(`var __hfTimelineCompId = "${runtimeIdB}"`),
|
|
),
|
|
).toBe(true);
|
|
});
|
|
|
|
it("keeps the authored composition id stable across repeat loadCompositions runs", async () => {
|
|
const hostA = document.createElement("div");
|
|
hostA.setAttribute("data-composition-src", "https://example.com/scene.html");
|
|
hostA.setAttribute("data-composition-id", "scene");
|
|
document.body.appendChild(hostA);
|
|
|
|
const hostB = document.createElement("div");
|
|
hostB.setAttribute("data-composition-src", "https://example.com/scene.html");
|
|
hostB.setAttribute("data-composition-id", "scene");
|
|
document.body.appendChild(hostB);
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<div id="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<h1 class="title">Scene</h1>
|
|
</div>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockImplementation(
|
|
async () => new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
const runtimeIdA1 = hostA.getAttribute("data-composition-id");
|
|
const runtimeIdB1 = hostB.getAttribute("data-composition-id");
|
|
expect(hostA.getAttribute("data-hf-original-composition-id")).toBe("scene");
|
|
expect(hostB.getAttribute("data-hf-original-composition-id")).toBe("scene");
|
|
|
|
await loadFixture();
|
|
|
|
expect(hostA.getAttribute("data-hf-original-composition-id")).toBe("scene");
|
|
expect(hostB.getAttribute("data-hf-original-composition-id")).toBe("scene");
|
|
expect(hostA.getAttribute("data-composition-id")).toBe(runtimeIdA1);
|
|
expect(hostB.getAttribute("data-composition-id")).toBe(runtimeIdB1);
|
|
expect(hostA.querySelector('[data-hf-authored-id="scene-root"]')).toBeTruthy();
|
|
expect(hostB.querySelector('[data-hf-authored-id="scene-root"]')).toBeTruthy();
|
|
});
|
|
|
|
it("gives a mount that shares the page root's id its own runtime id", async () => {
|
|
const root = document.createElement("div");
|
|
root.setAttribute("data-composition-id", "main");
|
|
document.body.appendChild(root);
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "https://example.com/scene.html");
|
|
host.setAttribute("data-composition-id", "main");
|
|
root.appendChild(host);
|
|
vi.spyOn(globalThis, "fetch").mockImplementation(
|
|
async () =>
|
|
new Response(
|
|
`<html><body><div data-composition-id="main" data-width="1920" data-height="1080"><h1>Scene</h1></div></body></html>`,
|
|
{ status: 200 },
|
|
),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
expect(root.getAttribute("data-composition-id")).toBe("main");
|
|
expect(host.getAttribute("data-composition-id")).toBe("main__hf1");
|
|
expect(host.getAttribute("data-hf-original-composition-id")).toBe("main");
|
|
expect(host.querySelector("h1")?.textContent).toBe("Scene");
|
|
});
|
|
|
|
it("normalizes a runtime composition id back to the authored id when only one host remains", async () => {
|
|
const hostA = document.createElement("div");
|
|
hostA.setAttribute("data-composition-src", "https://example.com/scene.html");
|
|
hostA.setAttribute("data-composition-id", "scene");
|
|
document.body.appendChild(hostA);
|
|
|
|
const hostB = document.createElement("div");
|
|
hostB.setAttribute("data-composition-src", "https://example.com/scene.html");
|
|
hostB.setAttribute("data-composition-id", "scene");
|
|
document.body.appendChild(hostB);
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<div id="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<h1 class="title">Scene</h1>
|
|
</div>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockImplementation(
|
|
async () => new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
expect(hostB.getAttribute("data-composition-id")).toBe("scene__hf2");
|
|
expect(hostB.getAttribute("data-hf-original-composition-id")).toBe("scene");
|
|
|
|
hostA.remove();
|
|
|
|
await loadFixture();
|
|
|
|
expect(hostB.getAttribute("data-composition-id")).toBe("scene");
|
|
expect(hostB.hasAttribute("data-hf-original-composition-id")).toBe(false);
|
|
expect(hostB.querySelector('[data-hf-authored-id="scene-root"]')).toBeTruthy();
|
|
});
|
|
|
|
it("clears stale variable entries when a host runtime composition id changes", async () => {
|
|
const hostA = document.createElement("div");
|
|
hostA.setAttribute("data-composition-src", "https://example.com/scene.html");
|
|
hostA.setAttribute("data-composition-id", "scene");
|
|
document.body.appendChild(hostA);
|
|
|
|
const hostB = document.createElement("div");
|
|
hostB.setAttribute("data-composition-src", "https://example.com/scene.html");
|
|
hostB.setAttribute("data-composition-id", "scene");
|
|
hostB.setAttribute("data-variable-values", '{"title":"Scene B"}');
|
|
document.body.appendChild(hostB);
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<div id="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<h1 class="title">Scene</h1>
|
|
</div>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockImplementation(
|
|
async () => new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
const byCompAfterFirstMount = (window as WindowWithScopedVars).__hfVariablesByComp ?? {};
|
|
expect(byCompAfterFirstMount["scene__hf2"]).toEqual({ title: "Scene B" });
|
|
|
|
hostA.remove();
|
|
hostB.innerHTML = "";
|
|
|
|
await loadFixture();
|
|
|
|
const byCompAfterSecondMount = (window as WindowWithScopedVars).__hfVariablesByComp ?? {};
|
|
expect(byCompAfterSecondMount["scene"]).toEqual({ title: "Scene B" });
|
|
expect(byCompAfterSecondMount["scene__hf2"]).toBeUndefined();
|
|
});
|
|
|
|
it("handles multiple compositions in parallel", async () => {
|
|
const host1 = document.createElement("div");
|
|
host1.setAttribute("data-composition-src", "https://example.com/a.html");
|
|
document.body.appendChild(host1);
|
|
|
|
const host2 = document.createElement("div");
|
|
host2.setAttribute("data-composition-src", "https://example.com/b.html");
|
|
document.body.appendChild(host2);
|
|
|
|
vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
|
|
const url = typeof input === "string" ? input : (input as Request).url;
|
|
if (url.includes("a.html")) {
|
|
return new Response("<html><body><p>A</p></body></html>", { status: 200 });
|
|
}
|
|
return new Response("<html><body><p>B</p></body></html>", { status: 200 });
|
|
});
|
|
|
|
await loadFixture();
|
|
expect(host1.querySelector("p")?.textContent).toBe("A");
|
|
expect(host2.querySelector("p")?.textContent).toBe("B");
|
|
});
|
|
|
|
describe("asset path rewriting (Studio preview parity with render)", () => {
|
|
/**
|
|
* Authored compositions live at `compositions/frames/*.html` and may
|
|
* reference assets either as project-root-relative (`assets/x.mp4`,
|
|
* which already resolves against the main document's base) or as
|
|
* sub-comp-relative with `../../` (which the server-side bundler
|
|
* rewrites for the baked render, but which historically broke in
|
|
* Studio preview because the runtime did no such rewriting and the
|
|
* `../../` traversed above the project root).
|
|
*
|
|
* These tests pin the rewrite contract so the runtime stays in
|
|
* lockstep with the producer's `inlineSubCompositions` path.
|
|
*/
|
|
const FRAME_URL =
|
|
"http://localhost:5190/api/projects/demo/preview/compositions/frames/scene.html";
|
|
|
|
it("rewrites `../`-traversing src on elements inside <template>", async () => {
|
|
const host = appendExternalHost(FRAME_URL, "scene");
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<template>
|
|
<div data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<video id="hero" src="../../assets/hero.mp4"></video>
|
|
<img id="badge" src="../../assets/badge.png" />
|
|
</div>
|
|
</template>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
const hero = host.querySelector("#hero");
|
|
const badge = host.querySelector("#badge");
|
|
expect(hero?.getAttribute("src")).toBe(
|
|
"http://localhost:5190/api/projects/demo/preview/assets/hero.mp4",
|
|
);
|
|
expect(badge?.getAttribute("src")).toBe(
|
|
"http://localhost:5190/api/projects/demo/preview/assets/badge.png",
|
|
);
|
|
});
|
|
|
|
it("leaves plain project-root-relative paths untouched (no double-prefix)", async () => {
|
|
const host = appendExternalHost(FRAME_URL, "scene");
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<template>
|
|
<div data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<video id="hero" src="assets/hero.mp4"></video>
|
|
<img id="badge" src="assets/badge.png" />
|
|
</div>
|
|
</template>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
// Plain relative paths resolve against the main document's base, which
|
|
// points at the project preview root — so the runtime must NOT rewrite
|
|
// them. Doing so would risk double-prefixing the URL.
|
|
const hero = host.querySelector("#hero");
|
|
const badge = host.querySelector("#badge");
|
|
expect(hero?.getAttribute("src")).toBe("assets/hero.mp4");
|
|
expect(badge?.getAttribute("src")).toBe("assets/badge.png");
|
|
});
|
|
|
|
it("leaves absolute URLs, data URIs, and hash refs untouched", async () => {
|
|
const host = appendExternalHost(FRAME_URL, "scene");
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<template>
|
|
<div data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<video id="abs" src="https://cdn.example.com/clip.mp4"></video>
|
|
<img id="dat" src="data:image/png;base64,AA" />
|
|
<a id="hash" href="#main">jump</a>
|
|
<img id="root" src="/global/logo.png" />
|
|
</div>
|
|
</template>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
expect(host.querySelector("#abs")?.getAttribute("src")).toBe(
|
|
"https://cdn.example.com/clip.mp4",
|
|
);
|
|
expect(host.querySelector("#dat")?.getAttribute("src")).toBe("data:image/png;base64,AA");
|
|
expect(host.querySelector("#hash")?.getAttribute("href")).toBe("#main");
|
|
expect(host.querySelector("#root")?.getAttribute("src")).toBe("/global/logo.png");
|
|
});
|
|
|
|
it("rewrites CSS url(...) `../` references inside <style> blocks", async () => {
|
|
appendExternalHost(FRAME_URL, "scene");
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<template>
|
|
<div data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<style>
|
|
@font-face { font-family: 'Brand'; src: url("../../assets/fonts/brand.woff2") format("woff2"); }
|
|
.cover { background-image: url('../../assets/cover.png'); }
|
|
.icon { background-image: url(assets/icon.svg); }
|
|
</style>
|
|
<p>scoped</p>
|
|
</div>
|
|
</template>
|
|
</body></html>
|
|
`;
|
|
|
|
const injectedStyles: HTMLStyleElement[] = [];
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
await loadCompositions({ ...createLoaderParams(), injectedStyles });
|
|
|
|
const cssText = injectedStyles.map((s) => s.textContent || "").join("\n");
|
|
expect(cssText).toContain(
|
|
'url("http://localhost:5190/api/projects/demo/preview/assets/fonts/brand.woff2")',
|
|
);
|
|
expect(cssText).toContain(
|
|
"url('http://localhost:5190/api/projects/demo/preview/assets/cover.png')",
|
|
);
|
|
// Plain relative path stays untouched — the main document's base
|
|
// already covers it, and double-prefixing would 404.
|
|
expect(cssText).toContain("url(assets/icon.svg)");
|
|
});
|
|
|
|
it("rewrites url(...) inside inline style attributes", async () => {
|
|
const host = appendExternalHost(FRAME_URL, "scene");
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<template>
|
|
<div data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<div id="card" style="background-image: url('../../assets/card-bg.png');"></div>
|
|
</div>
|
|
</template>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
await loadFixture();
|
|
|
|
const card = host.querySelector("#card");
|
|
expect(card?.getAttribute("style")).toContain(
|
|
"url('http://localhost:5190/api/projects/demo/preview/assets/card-bg.png')",
|
|
);
|
|
});
|
|
|
|
it("rewrites `../`-traversing src on non-template (full HTML doc) sub-comps", async () => {
|
|
const host = appendExternalHost(FRAME_URL, "scene");
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<div data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<video id="hero" src="../../assets/hero.mp4"></video>
|
|
</div>
|
|
</body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
await loadFixture();
|
|
|
|
const hero = host.querySelector("#hero");
|
|
expect(hero?.getAttribute("src")).toBe(
|
|
"http://localhost:5190/api/projects/demo/preview/assets/hero.mp4",
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("variable scoping (window.__hfVariablesByComp)", () => {
|
|
type WindowWithScopedVars = Window & {
|
|
__hfVariablesByComp?: Record<string, Record<string, unknown>>;
|
|
};
|
|
|
|
afterEach(() => {
|
|
delete (window as WindowWithScopedVars).__hfVariablesByComp;
|
|
});
|
|
|
|
it("merges sub-comp declared defaults with host data-variable-values", async () => {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "https://example.com/card.html");
|
|
host.setAttribute("data-composition-id", "card-1");
|
|
host.setAttribute("data-variable-values", '{"title":"Pro","price":"$29"}');
|
|
document.body.appendChild(host);
|
|
|
|
const compositionHtml = `
|
|
<html data-composition-variables='[
|
|
{"id":"title","type":"string","label":"Title","default":"Default"},
|
|
{"id":"price","type":"string","label":"Price","default":"$0"},
|
|
{"id":"theme","type":"string","label":"Theme","default":"light"}
|
|
]'>
|
|
<body>
|
|
<div data-composition-id="card-1"><p>card</p></div>
|
|
</body>
|
|
</html>
|
|
`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
const byComp = (window as WindowWithScopedVars).__hfVariablesByComp ?? {};
|
|
expect(byComp["card-1"]).toEqual({
|
|
title: "Pro", // host wins over declared default
|
|
price: "$29", // host wins
|
|
theme: "light", // host omits → declared default falls through
|
|
});
|
|
});
|
|
|
|
it("binds the scene's variable text before its scripts run", async () => {
|
|
const host = appendExternalHost("https://example.com/card.html", "card-1");
|
|
host.setAttribute("data-variable-values", '{"title":"Pro"}');
|
|
const compositionHtml =
|
|
`<html data-composition-variables='[{"id":"title","type":"string","label":"Title","default":"Default"}]'>` +
|
|
`<body><div data-composition-id="card-1"><h1 id="t" data-var-text="title">Default</h1></div>` +
|
|
`<script>var t = document.getElementById("t"); t.setAttribute("data-seen", t.textContent);</scr` +
|
|
`ipt></body></html>`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
await vi.waitFor(() =>
|
|
expect(host.querySelector("#t")?.getAttribute("data-seen")).toBe("Pro"),
|
|
);
|
|
});
|
|
|
|
it("does not redefine a CSS variable already authored on the host", async () => {
|
|
const style = document.createElement("style");
|
|
style.textContent = ":root { --accent: #4287f5; }";
|
|
document.head.appendChild(style);
|
|
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "https://example.com/card.html");
|
|
host.setAttribute("data-composition-id", "card-authored-token");
|
|
host.setAttribute("data-variable-values", '{"accent":"blue"}');
|
|
document.body.appendChild(host);
|
|
|
|
const compositionHtml = `
|
|
<html data-composition-variables='[
|
|
{"id":"accent","type":"string","label":"Accent","default":"red"}
|
|
]'>
|
|
<body><div data-composition-id="card-authored-token"><p>x</p></div></body>
|
|
</html>
|
|
`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
expect(host.style.getPropertyValue("--accent")).toBe("");
|
|
expect(window.getComputedStyle(host).getPropertyValue("--accent")).toBe("#4287f5");
|
|
});
|
|
|
|
it("uses declared defaults when host has no data-variable-values", async () => {
|
|
appendExternalHost("https://example.com/card.html", "card-2");
|
|
|
|
const compositionHtml = `
|
|
<html data-composition-variables='[
|
|
{"id":"title","type":"string","label":"Title","default":"Default Title"}
|
|
]'>
|
|
<body><div data-composition-id="card-2"><p>x</p></div></body>
|
|
</html>
|
|
`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
const byComp = (window as WindowWithScopedVars).__hfVariablesByComp ?? {};
|
|
expect(byComp["card-2"]).toEqual({ title: "Default Title" });
|
|
});
|
|
|
|
it("skips registration when neither declared defaults nor host overrides exist", async () => {
|
|
appendExternalHost("https://example.com/card.html", "card-empty");
|
|
|
|
const compositionHtml = `
|
|
<html><body><div data-composition-id="card-empty"><p>x</p></div></body></html>
|
|
`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
const byComp = (window as WindowWithScopedVars).__hfVariablesByComp;
|
|
expect(byComp?.["card-empty"]).toBeUndefined();
|
|
});
|
|
|
|
it("clears stale registered variables when a repeat mount has no values left", async () => {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "https://example.com/card.html");
|
|
host.setAttribute("data-composition-id", "card-clear");
|
|
host.setAttribute("data-variable-values", '{"title":"Pro"}');
|
|
document.body.appendChild(host);
|
|
|
|
const firstCompositionHtml = `
|
|
<html data-composition-variables='[
|
|
{"id":"title","type":"string","label":"Title","default":"Default Title"}
|
|
]'>
|
|
<body><div data-composition-id="card-clear"><p>x</p></div></body>
|
|
</html>
|
|
`;
|
|
const secondCompositionHtml = `
|
|
<html><body><div data-composition-id="card-clear"><p>y</p></div></body></html>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch")
|
|
.mockResolvedValueOnce(new Response(firstCompositionHtml, { status: 200 }))
|
|
.mockResolvedValueOnce(new Response(secondCompositionHtml, { status: 200 }));
|
|
|
|
await loadFixture();
|
|
|
|
const byCompAfterFirstMount = (window as WindowWithScopedVars).__hfVariablesByComp ?? {};
|
|
expect(byCompAfterFirstMount["card-clear"]).toEqual({ title: "Pro" });
|
|
|
|
host.removeAttribute("data-variable-values");
|
|
host.innerHTML = "";
|
|
|
|
await loadFixture();
|
|
|
|
const byCompAfterSecondMount = (window as WindowWithScopedVars).__hfVariablesByComp;
|
|
expect(byCompAfterSecondMount?.["card-clear"]).toBeUndefined();
|
|
});
|
|
|
|
it("ignores invalid JSON in host data-variable-values", async () => {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "https://example.com/card.html");
|
|
host.setAttribute("data-composition-id", "card-bad");
|
|
host.setAttribute("data-variable-values", "{not json");
|
|
document.body.appendChild(host);
|
|
|
|
const compositionHtml = `
|
|
<html data-composition-variables='[{"id":"title","type":"string","label":"Title","default":"OK"}]'>
|
|
<body><div data-composition-id="card-bad"><p>x</p></div></body>
|
|
</html>
|
|
`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
const byComp = (window as WindowWithScopedVars).__hfVariablesByComp ?? {};
|
|
expect(byComp["card-bad"]).toEqual({ title: "OK" });
|
|
});
|
|
|
|
it("registers per-instance entries for multiple sub-comps with the same source", async () => {
|
|
const host1 = document.createElement("div");
|
|
host1.setAttribute("data-composition-src", "https://example.com/card.html");
|
|
host1.setAttribute("data-composition-id", "card-A");
|
|
host1.setAttribute("data-variable-values", '{"title":"Pro","price":"$29"}');
|
|
document.body.appendChild(host1);
|
|
|
|
const host2 = document.createElement("div");
|
|
host2.setAttribute("data-composition-src", "https://example.com/card.html");
|
|
host2.setAttribute("data-composition-id", "card-B");
|
|
host2.setAttribute("data-variable-values", '{"title":"Enterprise","price":"Custom"}');
|
|
document.body.appendChild(host2);
|
|
|
|
const compositionHtml = `
|
|
<html data-composition-variables='[
|
|
{"id":"title","type":"string","label":"Title","default":"Default"},
|
|
{"id":"price","type":"string","label":"Price","default":"$0"}
|
|
]'>
|
|
<body><div data-composition-id="card-A"><p>x</p></div></body>
|
|
</html>
|
|
`;
|
|
vi.spyOn(globalThis, "fetch").mockImplementation(
|
|
async () => new Response(compositionHtml, { status: 200 }),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
const byComp = (window as WindowWithScopedVars).__hfVariablesByComp ?? {};
|
|
expect(byComp["card-A"]).toEqual({ title: "Pro", price: "$29" });
|
|
expect(byComp["card-B"]).toEqual({ title: "Enterprise", price: "Custom" });
|
|
});
|
|
|
|
it("clears stale variable entries when a previous host was removed from the DOM", async () => {
|
|
const hostA = document.createElement("div");
|
|
hostA.setAttribute("data-composition-src", "https://example.com/card-a.html");
|
|
hostA.setAttribute("data-composition-id", "card-a");
|
|
hostA.setAttribute("data-variable-values", '{"title":"A"}');
|
|
document.body.appendChild(hostA);
|
|
|
|
const hostB = document.createElement("div");
|
|
hostB.setAttribute("data-composition-src", "https://example.com/card-b.html");
|
|
hostB.setAttribute("data-composition-id", "card-b");
|
|
hostB.setAttribute("data-variable-values", '{"title":"B"}');
|
|
document.body.appendChild(hostB);
|
|
|
|
vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
|
|
const url = String(input);
|
|
if (url.includes("card-a.html")) {
|
|
return new Response(
|
|
`<html><body><div data-composition-id="card-a"><p>A</p></div></body></html>`,
|
|
{ status: 200 },
|
|
);
|
|
}
|
|
return new Response(
|
|
`<html><body><div data-composition-id="card-b"><p>B</p></div></body></html>`,
|
|
{ status: 200 },
|
|
);
|
|
});
|
|
|
|
await loadFixture();
|
|
|
|
const byCompAfterFirstMount = (window as WindowWithScopedVars).__hfVariablesByComp ?? {};
|
|
expect(byCompAfterFirstMount["card-a"]).toEqual({ title: "A" });
|
|
expect(byCompAfterFirstMount["card-b"]).toEqual({ title: "B" });
|
|
|
|
hostB.remove();
|
|
hostA.innerHTML = "";
|
|
|
|
await loadFixture();
|
|
|
|
const byCompAfterSecondMount = (window as WindowWithScopedVars).__hfVariablesByComp ?? {};
|
|
expect(byCompAfterSecondMount["card-a"]).toEqual({ title: "A" });
|
|
expect(byCompAfterSecondMount["card-b"]).toBeUndefined();
|
|
});
|
|
|
|
it("clears stale variable entries when the last host was removed from the DOM", async () => {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "https://example.com/card-last.html");
|
|
host.setAttribute("data-composition-id", "card-last");
|
|
host.setAttribute("data-variable-values", '{"title":"Last"}');
|
|
document.body.appendChild(host);
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(
|
|
`<html><body><div data-composition-id="card-last"><p>Last</p></div></body></html>`,
|
|
{ status: 200 },
|
|
),
|
|
);
|
|
|
|
await loadFixture();
|
|
|
|
const byCompAfterFirstMount = (window as WindowWithScopedVars).__hfVariablesByComp ?? {};
|
|
expect(byCompAfterFirstMount["card-last"]).toEqual({ title: "Last" });
|
|
|
|
host.remove();
|
|
|
|
await loadFixture();
|
|
|
|
const byCompAfterSecondMount = (window as WindowWithScopedVars).__hfVariablesByComp;
|
|
expect(byCompAfterSecondMount?.["card-last"]).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
it("scopes an anonymous host's composition to the id its own content declares", async () => {
|
|
// A host naming no composition id used to mount the fetched content WHOLE:
|
|
// unflattened, and with its CSS injected unscoped, so the composition's
|
|
// rules landed on the host document at large. The compiler has always
|
|
// fallen back to the first root declared in the content, scoped to it, and
|
|
// restored the id that flattening strips. The mount path does the same now.
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-src", "https://example.com/scoped-text.html");
|
|
document.body.appendChild(host);
|
|
|
|
const compositionHtml = `
|
|
<template id="scoped-text-template">
|
|
<style>.label { color: rgb(1, 2, 3); }</style>
|
|
<div data-composition-id="scoped-text" data-width="1080" data-height="1920">
|
|
<div class="label">Scoped Text Should Stay Styled</div>
|
|
</div>
|
|
</template>
|
|
`;
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
const { injectedStyles } = await loadFixture();
|
|
|
|
// Flattened like every other mount, with the declared id restored so the
|
|
// composition's scoped CSS and self-referencing queries still resolve.
|
|
const mountedRoot = host.querySelector('[data-composition-id="scoped-text"]');
|
|
expect(mountedRoot?.getAttribute("data-hf-inner-root")).toBe("true");
|
|
expect(mountedRoot?.querySelector(".label")?.textContent).toBe(
|
|
"Scoped Text Should Stay Styled",
|
|
);
|
|
// The stylesheet is scoped to the composition rather than leaking whole.
|
|
const injectedCss = injectedStyles.map((style) => style.textContent).join("\n");
|
|
expect(injectedCss).toContain('[data-composition-id="scoped-text"]');
|
|
expect(injectedCss).not.toMatch(/^\s*\.label\s*\{/);
|
|
});
|
|
|
|
// --- D1/D4 regressions: what the compiler and the mount path now agree on ---
|
|
|
|
it("executes an inline <head> script of a non-templated composition", async () => {
|
|
// The compiler used to drop this one on the floor (its <head> loop had a
|
|
// `src` branch and no else); the mount path always executed it.
|
|
appendExternalHost("https://example.com/head-script.html", "head-script");
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(
|
|
`<html><head><script>window.__headScriptRan = true;</script></head><body>
|
|
<div data-composition-id="head-script"><p>Body</p></div>
|
|
</body></html>`,
|
|
{ status: 200 },
|
|
),
|
|
);
|
|
|
|
const { injectedScripts } = await loadFixture();
|
|
|
|
expect(injectedScripts.map((script) => script.textContent).join("\n")).toContain(
|
|
"window.__headScriptRan = true;",
|
|
);
|
|
});
|
|
|
|
it("scopes scripts to the id the content declares when the host names another", async () => {
|
|
// Two scope ids, not one: CSS stays on the id the host asked for, scripts
|
|
// follow the id the content actually declares, so a script's own
|
|
// querySelector('[data-composition-id="..."]') resolves. Collapsing them
|
|
// pointed every self-query at an id that is nowhere in the content.
|
|
appendExternalHost("https://example.com/captions.html", "captions-comp");
|
|
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
|
new Response(
|
|
`<template id="captions-comp-template">
|
|
<div data-composition-id="captions"><p>Caption</p></div>
|
|
<script>void 0;</script>
|
|
</template>`,
|
|
{ status: 200 },
|
|
),
|
|
);
|
|
|
|
const { injectedScripts } = await loadFixture();
|
|
|
|
const scriptSource = injectedScripts.map((script) => script.textContent).join("\n");
|
|
expect(scriptSource).toContain('var __hfCompId = "captions";');
|
|
expect(scriptSource).not.toContain('var __hfCompId = "captions-comp";');
|
|
});
|
|
});
|
|
|
|
describe("loadCompositions inline templates", () => {
|
|
afterEach(() => {
|
|
document.body.innerHTML = "";
|
|
document.head.querySelectorAll("style").forEach((s) => s.remove());
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
it("mounts template content into matching empty host", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "logo-reveal-template";
|
|
template.innerHTML = `
|
|
<div data-composition-id="logo-reveal" data-width="1920" data-height="1080">
|
|
<p>Logo content</p>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template);
|
|
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-id", "logo-reveal");
|
|
host.setAttribute("data-start", "0");
|
|
host.setAttribute("data-duration", "10");
|
|
document.body.appendChild(host);
|
|
|
|
await loadFixture();
|
|
|
|
expect(host.querySelector("p")?.textContent).toBe("Logo content");
|
|
});
|
|
|
|
it("does nothing when no matching template exists", async () => {
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-id", "no-template");
|
|
document.body.appendChild(host);
|
|
|
|
await loadFixture();
|
|
|
|
// Host should remain empty
|
|
expect(host.children.length).toBe(0);
|
|
});
|
|
|
|
it("does nothing when no inline template hosts exist", async () => {
|
|
// Add a template with no matching host
|
|
const template = document.createElement("template");
|
|
template.id = "orphan-template";
|
|
template.innerHTML = "<p>Orphan</p>";
|
|
document.body.appendChild(template);
|
|
|
|
await loadFixture();
|
|
|
|
// Nothing should change — no hosts match
|
|
expect(document.querySelector("p")).toBeNull();
|
|
});
|
|
|
|
it("skips hosts that already have content", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "filled-template";
|
|
template.innerHTML = `
|
|
<div data-composition-id="filled" data-width="800" data-height="600">
|
|
<p>Template content</p>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template);
|
|
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-id", "filled");
|
|
host.innerHTML = "<span>Existing content</span>";
|
|
document.body.appendChild(host);
|
|
|
|
await loadFixture();
|
|
|
|
// Original content should remain
|
|
expect(host.querySelector("span")?.textContent).toBe("Existing content");
|
|
expect(host.querySelector("p")).toBeNull();
|
|
});
|
|
|
|
it("uses the cached matching template for an external host", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "external-template";
|
|
template.innerHTML = `
|
|
<div data-composition-id="external" data-width="800" data-height="600">
|
|
<p>Cached content</p>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template);
|
|
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-id", "external");
|
|
host.setAttribute("data-composition-src", "https://example.com/comp.html");
|
|
document.body.appendChild(host);
|
|
|
|
const fetch = vi.spyOn(globalThis, "fetch");
|
|
await loadFixture();
|
|
|
|
expect(host.querySelector("p")?.textContent).toBe("Cached content");
|
|
expect(fetch).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("processes multiple inline templates", async () => {
|
|
const template1 = document.createElement("template");
|
|
template1.id = "comp-a-template";
|
|
template1.innerHTML = `
|
|
<div data-composition-id="comp-a" data-width="1920" data-height="1080">
|
|
<p>Content A</p>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template1);
|
|
|
|
const template2 = document.createElement("template");
|
|
template2.id = "comp-b-template";
|
|
template2.innerHTML = `
|
|
<div data-composition-id="comp-b" data-width="800" data-height="600">
|
|
<p>Content B</p>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template2);
|
|
|
|
const host1 = document.createElement("div");
|
|
host1.setAttribute("data-composition-id", "comp-a");
|
|
document.body.appendChild(host1);
|
|
|
|
const host2 = document.createElement("div");
|
|
host2.setAttribute("data-composition-id", "comp-b");
|
|
document.body.appendChild(host2);
|
|
|
|
await loadFixture();
|
|
|
|
expect(host1.querySelector("p")?.textContent).toBe("Content A");
|
|
expect(host2.querySelector("p")?.textContent).toBe("Content B");
|
|
});
|
|
|
|
it("injects styles from template into document head", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "styled-comp-template";
|
|
template.innerHTML = `
|
|
<div data-composition-id="styled-comp" data-width="1920" data-height="1080">
|
|
<style>.test-inline { color: blue; }</style>
|
|
<p>Styled content</p>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template);
|
|
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-id", "styled-comp");
|
|
document.body.appendChild(host);
|
|
|
|
const { injectedStyles } = await loadFixture();
|
|
|
|
expect(injectedStyles.length).toBeGreaterThan(0);
|
|
});
|
|
|
|
it("injects scripts from template", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "scripted-comp-template";
|
|
template.innerHTML = `
|
|
<div data-composition-id="scripted-comp" data-width="1920" data-height="1080">
|
|
<p>Content with script</p>
|
|
<script>console.log("inline template script")</script>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template);
|
|
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-id", "scripted-comp");
|
|
document.body.appendChild(host);
|
|
|
|
const { injectedScripts } = await loadFixture();
|
|
|
|
expect(injectedScripts.length).toBeGreaterThan(0);
|
|
expect(injectedScripts[0].textContent).toContain("inline template script");
|
|
});
|
|
|
|
it("leaves a JSON data script in the mounted content instead of running it", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "data-comp-template";
|
|
template.innerHTML = `
|
|
<div data-composition-id="data-comp" data-width="1920" data-height="1080">
|
|
<script type="application/json" id="meta">{"title": "x"}</script>
|
|
<script>window.__dataCompRan = 1;</script>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template);
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-id", "data-comp");
|
|
document.body.appendChild(host);
|
|
|
|
const { injectedScripts } = await loadFixture();
|
|
|
|
expect(injectedScripts.map((script) => script.textContent).join("\n")).not.toContain("title");
|
|
expect(injectedScripts.some((script) => script.textContent?.includes("__dataCompRan"))).toBe(
|
|
true,
|
|
);
|
|
const meta = host.querySelector("#meta");
|
|
expect(meta?.getAttribute("type")).toBe("application/json");
|
|
expect(JSON.parse(meta?.textContent ?? "")).toEqual({ title: "x" });
|
|
});
|
|
|
|
it("mounts a JSON data script authored beside the composition root, and never runs a nomodule script", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "beside-comp-template";
|
|
template.innerHTML = `
|
|
<script type="application/json" id="beside">{"where": "template"}</script>
|
|
<script nomodule>window.__legacyOnly = 1;</script>
|
|
<div data-composition-id="beside-comp" data-width="1920" data-height="1080"></div>
|
|
`;
|
|
document.body.appendChild(template);
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-id", "beside-comp");
|
|
document.body.appendChild(host);
|
|
|
|
const { injectedScripts } = await loadFixture();
|
|
|
|
expect(JSON.parse(host.querySelector("#beside")?.textContent ?? "")).toEqual({
|
|
where: "template",
|
|
});
|
|
expect(injectedScripts.some((script) => script.textContent?.includes("__legacyOnly"))).toBe(
|
|
false,
|
|
);
|
|
});
|
|
|
|
it("copies dimension attributes from template inner root to host", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "dim-comp-template";
|
|
template.innerHTML = `
|
|
<div data-composition-id="dim-comp" data-width="1920" data-height="1080">
|
|
<p>Dimensioned</p>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template);
|
|
|
|
const host = document.createElement("div");
|
|
host.setAttribute("data-composition-id", "dim-comp");
|
|
document.body.appendChild(host);
|
|
|
|
await loadFixture();
|
|
|
|
expect(host.getAttribute("data-width")).toBe("1920");
|
|
expect(host.getAttribute("data-height")).toBe("1080");
|
|
});
|
|
|
|
it("keeps authored template lookup stable across repeat inline loads for duplicate hosts", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "scene-template";
|
|
template.innerHTML = `
|
|
<div id="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<p>Inline scene</p>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template);
|
|
|
|
const hostA = document.createElement("div");
|
|
hostA.setAttribute("data-composition-id", "scene");
|
|
document.body.appendChild(hostA);
|
|
|
|
const hostB = document.createElement("div");
|
|
hostB.setAttribute("data-composition-id", "scene");
|
|
document.body.appendChild(hostB);
|
|
|
|
await loadFixture();
|
|
|
|
const runtimeIdA = hostA.getAttribute("data-composition-id");
|
|
const runtimeIdB = hostB.getAttribute("data-composition-id");
|
|
expect(runtimeIdA).not.toBe("scene");
|
|
expect(runtimeIdB).not.toBe("scene");
|
|
expect(runtimeIdA).not.toBe(runtimeIdB);
|
|
expect(hostA.getAttribute("data-hf-original-composition-id")).toBe("scene");
|
|
expect(hostB.getAttribute("data-hf-original-composition-id")).toBe("scene");
|
|
|
|
hostA.innerHTML = "";
|
|
hostB.innerHTML = "";
|
|
|
|
await loadFixture();
|
|
|
|
expect(hostA.getAttribute("data-hf-original-composition-id")).toBe("scene");
|
|
expect(hostB.getAttribute("data-hf-original-composition-id")).toBe("scene");
|
|
expect(hostA.getAttribute("data-composition-id")).toBe(runtimeIdA);
|
|
expect(hostB.getAttribute("data-composition-id")).toBe(runtimeIdB);
|
|
expect(hostA.querySelector('[data-hf-authored-id="scene-root"]')).toBeTruthy();
|
|
expect(hostB.querySelector('[data-hf-authored-id="scene-root"]')).toBeTruthy();
|
|
});
|
|
|
|
it("does not rewrite ids for duplicate inline hosts that are skipped", async () => {
|
|
const filledTemplate = document.createElement("template");
|
|
filledTemplate.id = "filled-scene-template";
|
|
filledTemplate.innerHTML = `
|
|
<div data-composition-id="filled-scene" data-width="1920" data-height="1080">
|
|
<p>Filled scene</p>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(filledTemplate);
|
|
|
|
const filledHostA = document.createElement("div");
|
|
filledHostA.setAttribute("data-composition-id", "filled-scene");
|
|
filledHostA.innerHTML = "<span>Existing A</span>";
|
|
document.body.appendChild(filledHostA);
|
|
|
|
const filledHostB = document.createElement("div");
|
|
filledHostB.setAttribute("data-composition-id", "filled-scene");
|
|
filledHostB.innerHTML = "<span>Existing B</span>";
|
|
document.body.appendChild(filledHostB);
|
|
|
|
const orphanHostA = document.createElement("div");
|
|
orphanHostA.setAttribute("data-composition-id", "orphan-scene");
|
|
document.body.appendChild(orphanHostA);
|
|
|
|
const orphanHostB = document.createElement("div");
|
|
orphanHostB.setAttribute("data-composition-id", "orphan-scene");
|
|
document.body.appendChild(orphanHostB);
|
|
|
|
await loadFixture();
|
|
|
|
expect(filledHostA.getAttribute("data-composition-id")).toBe("filled-scene");
|
|
expect(filledHostB.getAttribute("data-composition-id")).toBe("filled-scene");
|
|
expect(filledHostA.hasAttribute("data-hf-original-composition-id")).toBe(false);
|
|
expect(filledHostB.hasAttribute("data-hf-original-composition-id")).toBe(false);
|
|
expect(orphanHostA.getAttribute("data-composition-id")).toBe("orphan-scene");
|
|
expect(orphanHostB.getAttribute("data-composition-id")).toBe("orphan-scene");
|
|
expect(orphanHostA.hasAttribute("data-hf-original-composition-id")).toBe(false);
|
|
expect(orphanHostB.hasAttribute("data-hf-original-composition-id")).toBe(false);
|
|
});
|
|
|
|
it("uniquifies a mounted inline host when a skipped sibling already uses the authored id", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "scene-template";
|
|
template.innerHTML = `
|
|
<div id="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<p>Inline scene</p>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template);
|
|
|
|
const skippedHost = document.createElement("div");
|
|
skippedHost.setAttribute("data-composition-id", "scene");
|
|
skippedHost.innerHTML = "<span>Existing scene</span>";
|
|
document.body.appendChild(skippedHost);
|
|
|
|
const mountedHost = document.createElement("div");
|
|
mountedHost.setAttribute("data-composition-id", "scene");
|
|
document.body.appendChild(mountedHost);
|
|
|
|
await loadFixture();
|
|
|
|
expect(skippedHost.getAttribute("data-composition-id")).toBe("scene");
|
|
expect(skippedHost.hasAttribute("data-hf-original-composition-id")).toBe(false);
|
|
expect(mountedHost.getAttribute("data-composition-id")).not.toBe("scene");
|
|
expect(mountedHost.getAttribute("data-hf-original-composition-id")).toBe("scene");
|
|
expect(mountedHost.querySelector('[data-hf-authored-id="scene-root"]')).toBeTruthy();
|
|
});
|
|
|
|
it("re-numbers duplicate inline runtime ids when the mount set grows", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "scene-template";
|
|
template.innerHTML = `
|
|
<div id="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<p>Inline scene</p>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template);
|
|
|
|
const hostA = document.createElement("div");
|
|
hostA.setAttribute("data-composition-id", "scene");
|
|
hostA.innerHTML = "<span>Existing A</span>";
|
|
document.body.appendChild(hostA);
|
|
|
|
const hostB = document.createElement("div");
|
|
hostB.setAttribute("data-composition-id", "scene");
|
|
document.body.appendChild(hostB);
|
|
|
|
await loadFixture();
|
|
|
|
expect(hostA.getAttribute("data-composition-id")).toBe("scene");
|
|
expect(hostB.getAttribute("data-composition-id")).toBe("scene__hf1");
|
|
|
|
hostA.innerHTML = "";
|
|
hostB.innerHTML = "";
|
|
|
|
await loadFixture();
|
|
|
|
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("uniquifies duplicate sub-compositions across inline-template and external hosts", async () => {
|
|
const template = document.createElement("template");
|
|
template.id = "scene-template";
|
|
template.innerHTML = `
|
|
<div id="scene-root" data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<p>Inline scene</p>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(template);
|
|
|
|
const inlineHost = document.createElement("div");
|
|
inlineHost.setAttribute("data-composition-id", "scene");
|
|
document.body.appendChild(inlineHost);
|
|
|
|
const externalHost = document.createElement("div");
|
|
externalHost.setAttribute("data-composition-id", "scene");
|
|
externalHost.setAttribute("data-composition-src", "https://example.com/scene.html");
|
|
document.body.appendChild(externalHost);
|
|
|
|
const compositionHtml = `
|
|
<html><body>
|
|
<div data-composition-id="scene" data-width="1920" data-height="1080">
|
|
<p>External scene</p>
|
|
</div>
|
|
</body></html>
|
|
`;
|
|
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));
|
|
|
|
await loadFixture();
|
|
|
|
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).toBeTruthy();
|
|
});
|
|
});
|
|
|
|
describe("namespaceMountedSvgIds", () => {
|
|
afterEach(() => {
|
|
document.body.innerHTML = "";
|
|
document.head.querySelectorAll("style").forEach((s) => s.remove());
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
const CLIPPED = (id: string) =>
|
|
`<svg><g clip-path="url(#${id})"><path d="M0 0h24v24H0z"/></g>` +
|
|
`<defs><clipPath id="${id}"><rect width="24" height="24"/></clipPath></defs></svg>`;
|
|
|
|
async function mountAll(files: Record<string, string>, body: string) {
|
|
document.body.innerHTML = body;
|
|
vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
|
|
return new Response(files[String(input)], { status: 200 });
|
|
});
|
|
const params = {
|
|
injectedStyles: [] as HTMLStyleElement[],
|
|
injectedScripts: [] as HTMLScriptElement[],
|
|
injectedLinks: [] as HTMLLinkElement[],
|
|
parseDimensionPx: () => null,
|
|
};
|
|
await loadCompositions(params);
|
|
return params.injectedStyles;
|
|
}
|
|
|
|
const host = (id: string) =>
|
|
document.querySelector<HTMLElement>(`[data-composition-id="${id}"][data-composition-src]`)!;
|
|
const clipTarget = (el: Element | null) =>
|
|
document.getElementById(/#([^)"']+)/.exec(el!.getAttribute("clip-path")!)![1]!);
|
|
const external = (id: string) =>
|
|
`<div data-composition-id="${id}" data-composition-src="https://x.test/${id}.html"></div>`;
|
|
|
|
it("resolves each loaded composition's clip-path to its own clipPath when ids collide", async () => {
|
|
await mountAll(
|
|
{
|
|
"https://x.test/intro.html": `<div data-composition-id="intro">${CLIPPED("clip0_1_2")}</div>`,
|
|
"https://x.test/grid.html": `<div data-composition-id="grid">${CLIPPED("clip0_1_2")}</div>`,
|
|
},
|
|
external("intro") + external("grid"),
|
|
);
|
|
|
|
for (const id of ["intro", "grid"]) {
|
|
expect(host(id).contains(clipTarget(host(id).querySelector("g")))).toBe(true);
|
|
}
|
|
expect(host("grid").querySelector("clipPath")!.id).toBe("grid--clip0_1_2");
|
|
});
|
|
|
|
it("rewrites a url(#id) used only from a composition's <style> along with the element", async () => {
|
|
const filtered = (id: string) =>
|
|
`<div data-composition-id="${id}"><style>.box { filter: url(#fx); }</style>` +
|
|
`<svg><filter id="fx"><feGaussianBlur stdDeviation="2"/></filter></svg><div class="box"></div></div>`;
|
|
const styles = await mountAll(
|
|
{ "https://x.test/a.html": filtered("a"), "https://x.test/b.html": filtered("b") },
|
|
external("a") + external("b"),
|
|
);
|
|
|
|
const css = (id: string) =>
|
|
styles.find((style) => style.textContent!.includes(`[data-composition-id="${id}"]`))!
|
|
.textContent;
|
|
expect(host("b").querySelector("filter")!.id).toBe("b--fx");
|
|
expect(css("a")).toContain("url(#fx)");
|
|
expect(css("b")).toContain("url(#b--fx)");
|
|
});
|
|
|
|
it("leaves an id that does not collide untouched", async () => {
|
|
await mountAll(
|
|
{
|
|
"https://x.test/a.html": `<div data-composition-id="a">${CLIPPED("c")}</div>`,
|
|
"https://x.test/b.html": `<div data-composition-id="b">${CLIPPED("c")}${CLIPPED("only-b")}</div>`,
|
|
},
|
|
external("a") + external("b"),
|
|
);
|
|
|
|
const [renamed, onlyB] = host("b").querySelectorAll("clipPath");
|
|
expect(renamed!.id).toBe("b--c");
|
|
expect(onlyB!.id).toBe("only-b");
|
|
expect(onlyB!.hasAttribute("data-hf-authored-id")).toBe(false);
|
|
expect(host("b").querySelectorAll("g")[1]!.getAttribute("clip-path")).toBe("url(#only-b)");
|
|
});
|
|
|
|
it("keeps a nested composition's references out of its parent's renames", async () => {
|
|
await mountAll(
|
|
{
|
|
"https://x.test/outer.html":
|
|
`<div data-composition-id="outer"><div id="inner-host" data-composition-id="inner"></div>` +
|
|
`${CLIPPED("c")}</div>`,
|
|
},
|
|
`<template id="inner-template"><div data-composition-id="inner">${CLIPPED("c")}</div></template>` +
|
|
external("outer"),
|
|
);
|
|
|
|
const inner = document.getElementById("inner-host")!;
|
|
expect(inner.contains(clipTarget(inner.querySelector("g")))).toBe(true);
|
|
const outerG = [...host("outer").querySelectorAll("g")].find((g) => !inner.contains(g))!;
|
|
const outerClip = clipTarget(outerG);
|
|
expect(host("outer").contains(outerClip) && !inner.contains(outerClip)).toBe(true);
|
|
});
|
|
|
|
// fails without the fix: the second scene's clip-path resolved to the first scene's clipPath.
|
|
it("resolves each top-level scene clip to its own clipPath, and a shared page-level one for both", async () => {
|
|
const scene = (start: number) =>
|
|
`<div class="scene" data-start="${start}" data-duration="10">${CLIPPED("c")}` +
|
|
`<svg><rect class="shared" clip-path="url(#page)"/></svg></div>`;
|
|
await mountAll(
|
|
{},
|
|
`<svg><clipPath id="page"><rect width="1" height="1"/></clipPath></svg>` +
|
|
`<div data-composition-id="main" data-start="0">${scene(0)}${scene(10)}</div>`,
|
|
);
|
|
|
|
const scenes = [...document.querySelectorAll(".scene")];
|
|
for (const each of scenes)
|
|
expect(each.contains(clipTarget(each.querySelector("g")))).toBe(true);
|
|
expect(scenes[0]!.querySelector("clipPath")!.id).toBe("c");
|
|
for (const rect of document.querySelectorAll(".shared"))
|
|
expect(clipTarget(rect)).toBe(document.getElementById("page"));
|
|
});
|
|
});
|