Skip to content

Write HTML. Render video. Built for agents.

fix(player): honor runtime discovery and source in embeds (#5244)

Abdullah M. Nazif2dd708e0a214
diff --git a/packages/player/src/composition-probe.test.ts b/packages/player/src/composition-probe.test.ts
index 2b4a749ac4..010c85c07f 100644
--- a/packages/player/src/composition-probe.test.ts
+++ b/packages/player/src/composition-probe.test.ts
@@ -1,5 +1,10 @@
-import { describe, expect, it } from "vitest";
-import { readCompositionSizeFromDocument, runtimeCdnUrlForVersion } from "./composition-probe.js";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ CompositionProbe,
+ type ProbeCallbacks,
+ readCompositionSizeFromDocument,
+ runtimeCdnUrlForVersion,
+} from "./composition-probe.js";
describe("readCompositionSizeFromDocument", () => {
it("reads dimensions from the composition root", () => {
@@ -36,3 +41,130 @@ describe("runtimeCdnUrlForVersion", () => {
expect(() => runtimeCdnUrlForVersion("latest")).toThrow("Invalid HyperFrames runtime version");
});
});
+
+describe("src embed runtime discovery", () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => {
+ document.body.innerHTML = "";
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ });
+
+ const root = '<div data-composition-id="main" data-width="640" data-height="360"></div>';
+ const nested =
+ '<div data-composition-id="main"><div data-composition-src="child.html"></div></div>';
+ const timeline = {
+ duration: () => 2,
+ time: () => 0,
+ seek: () => {},
+ play: () => {},
+ pause: () => {},
+ };
+
+ function mount(
+ markup: string,
+ globals: Record<string, unknown> = {},
+ callbacks: Partial<ProbeCallbacks> = {},
+ ) {
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+ const doc = iframe.contentDocument;
+ const win = iframe.contentWindow;
+ if (!doc || !win) throw new Error("missing fixture document");
+ doc.body.innerHTML = markup;
+ Object.assign(win, globals);
+ const onReady = vi.fn();
+ const onError = vi.fn();
+ const probe = new CompositionProbe(iframe, { ...callbacks, onReady, onError });
+ probe.start();
+ return { iframe, doc, win, probe, onReady, onError };
+ }
+
+ function injectedScript(doc: Document) {
+ const script = doc.querySelector("script[src]");
+ if (!(script instanceof HTMLScriptElement)) throw new Error("runtime script was not injected");
+ return script;
+ }
+
+ it.each([{}, { shaderTransitionsReady: Promise.resolve() }, { seek: () => {} }, null])(
+ "drives an authored timeline beside the shared __hf namespace %s",
+ (namespace) => {
+ const { onReady, onError } = mount(root, {
+ __hf: namespace,
+ __timelines: { main: timeline },
+ });
+ vi.advanceTimersByTime(200);
+ expect(onReady).toHaveBeenCalledOnce();
+ expect(onReady.mock.calls[0][0].adapter).toMatchObject({ kind: "direct-timeline", timeline });
+ expect(onReady.mock.calls[0][0].duration).toBe(2);
+ expect(onError).not.toHaveBeenCalled();
+ },
+ );
+
+ it("keeps the runtime bridge ahead of authored timelines", () => {
+ const { doc, onReady } = mount(root, {
+ __hf: {},
+ __player: { getDuration: () => 5 },
+ __timelines: { main: timeline },
+ });
+ vi.advanceTimersByTime(200);
+ expect(onReady.mock.calls[0][0]).toMatchObject({ duration: 5, adapter: { kind: "runtime" } });
+ expect(doc.querySelector("script")).toBeNull();
+ });
+
+ it("injects the runtime for nested scenes even when shaders created __hf", () => {
+ const { doc, onReady } = mount(nested, {
+ __hf: { shaderTransitionsReady: Promise.resolve() },
+ __timelines: { main: timeline },
+ });
+ vi.advanceTimersByTime(200);
+ expect(injectedScript(doc).src).toContain("hyperframe.runtime.iife.js");
+ expect(onReady).not.toHaveBeenCalled();
+ });
+
+ it("uses the configured URL at injection time", () => {
+ let url = "http://127.0.0.1:8000/first.js";
+ const { doc } = mount(nested, {}, { resolveRuntimeUrl: () => url });
+ url = "http://127.0.0.1:8000/current.js";
+ vi.advanceTimersByTime(200);
+ expect(injectedScript(doc).src).toBe(url);
+ });
+
+ it("reports a failed runtime load once and latches the failed document", () => {
+ const url = "http://127.0.0.1:8000/missing-runtime.js";
+ const { doc, probe, onError, onReady } = mount(nested, {}, { resolveRuntimeUrl: () => url });
+ vi.advanceTimersByTime(200);
+ injectedScript(doc).dispatchEvent(new Event("error"));
+ expect(onError).toHaveBeenCalledExactlyOnceWith(
+ "HyperFrames runtime failed to load from " + url,
+ );
+ expect(probe.failed).toBe(true);
+ vi.advanceTimersByTime(16000);
+ expect(onError).toHaveBeenCalledOnce();
+ expect(onReady).not.toHaveBeenCalled();
+ });
+
+ it("ignores a script error after the probe stopped", () => {
+ const { doc, probe, onError } = mount(nested);
+ vi.advanceTimersByTime(200);
+ const oldScript = injectedScript(doc);
+ probe.stop();
+ oldScript.dispatchEvent(new Event("error"));
+ expect(onError).not.toHaveBeenCalled();
+ expect(probe.failed).toBe(false);
+ });
+
+ it("does not let an old script error fail a restarted probe", () => {
+ const { doc, probe, win, onReady, onError } = mount(nested);
+ vi.advanceTimersByTime(200);
+ const oldScript = injectedScript(doc);
+ probe.start();
+ oldScript.dispatchEvent(new Event("error"));
+ vi.advanceTimersByTime(200);
+ Object.assign(win, { __player: { getDuration: () => 2 } });
+ vi.advanceTimersByTime(200);
+ expect(onReady).toHaveBeenCalledOnce();
+ expect(onError).not.toHaveBeenCalled();
+ expect(probe.failed).toBe(false);
+ });
+});
diff --git a/packages/player/src/composition-probe.ts b/packages/player/src/composition-probe.ts
index 226919f850..3ccf3f1f05 100644
--- a/packages/player/src/composition-probe.ts
+++ b/packages/player/src/composition-probe.ts
@@ -37,6 +37,7 @@ export interface ProbeCallbacks {
onError: (message: string) => void;
/** Called when runtime is successfully injected (informational). */
onRuntimeInjected?: () => void;
+ resolveRuntimeUrl?: () => string;
}
/**
@@ -83,6 +84,7 @@ function firstAuthorError(errors: unknown): string | null {
export class CompositionProbe {
private _interval: ReturnType<typeof setInterval> | null = null;
private _runtimeInjected = false;
+ private _runtimeScript: HTMLScriptElement | null = null;
private _failure: { document: Document | null } | null = null;
get failed(): boolean {
@@ -179,6 +181,10 @@ export class CompositionProbe {
}
stop(): void {
+ if (this._runtimeScript) {
+ this._runtimeScript.onerror = null;
+ this._runtimeScript = null;
+ }
if (!this.failed) this._failure = null;
if (this._interval !== null) {
clearInterval(this._interval);
@@ -204,7 +210,7 @@ export class CompositionProbe {
}
hasRuntimeBridge(win: Window): boolean {
- return Reflect.get(win, "__hf") !== undefined || isObjectRecord(Reflect.get(win, "__player"));
+ return isObjectRecord(Reflect.get(win, "__player"));
}
// ── Private ──────────────────────────────────────────────────────────────
@@ -215,7 +221,14 @@ export class CompositionProbe {
const doc = this._iframe.contentDocument;
if (!doc) return;
const script = doc.createElement("script");
- script.src = RUNTIME_CDN_URL;
+ script.src = this._callbacks.resolveRuntimeUrl?.() ?? RUNTIME_CDN_URL;
+ this._runtimeScript = script;
+ script.onerror = () => {
+ if (this._runtimeScript !== script || this._iframe.contentDocument !== doc) return;
+ this.stop();
+ this._failure = { document: doc };
+ this._callbacks.onError("HyperFrames runtime failed to load from " + script.src);
+ };
(doc.head || doc.documentElement).appendChild(script);
this._callbacks.onRuntimeInjected?.();
} catch {
diff --git a/packages/player/src/hyperframes-player.ts b/packages/player/src/hyperframes-player.ts
index d09b78086f..38e04beac2 100644
--- a/packages/player/src/hyperframes-player.ts
+++ b/packages/player/src/hyperframes-player.ts
@@ -20,6 +20,7 @@ import {
getShaderModeFromElement,
prepareSrcForElement,
prepareSrcdocForElement,
+ runtimeSrcFromElement,
} from "./shader-options.js";
import { createShaderLoader } from "./shader-loader-element.js";
import { ShaderLoaderState } from "./shader-loader-state.js";
@@ -204,6 +205,7 @@ class HyperframesPlayer extends HTMLElement {
});
this.probe = new CompositionProbe(this.iframe, {
+ resolveRuntimeUrl: () => runtimeSrcFromElement(this),
onReady: (result) => this._onProbeReady(result),
onError: (message) => this._emit(new CustomEvent("error", { detail: { message } })),
});
diff --git a/packages/player/src/probeTerminalReadiness.test.ts b/packages/player/src/probeTerminalReadiness.test.ts
index 55fe62d182..fbc0f13ba3 100644
--- a/packages/player/src/probeTerminalReadiness.test.ts
+++ b/packages/player/src/probeTerminalReadiness.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { HyperframesPlayer } from "./hyperframes-player.js";
+import { RUNTIME_CDN_URL } from "./runtime-url.js";
function mountPlayer() {
const player = document.createElement("hyperframes-player") as HyperframesPlayer;
@@ -102,4 +103,48 @@ describe("terminal probe readiness", () => {
sendTimeline(iframe);
expectUnready(player, onReady);
});
+
+ it.each([
+ ["http://127.0.0.1:8900/custom-runtime.js", "http://127.0.0.1:8900/custom-runtime.js"],
+ ["/custom-runtime.js", "http://localhost:3000/custom-runtime.js"],
+ ["https://foreign.example/custom-runtime.js", null],
+ ['javascript:alert("no")', null],
+ ])("resolves runtime-src %s for a src embed", (configured, expected) => {
+ const { player, iframe } = mountPlayer();
+ player.setAttribute("runtime-src", configured);
+ player.setAttribute("src", "composition.html");
+ const doc = iframe.contentDocument;
+ if (!doc) throw new Error("missing fixture document");
+ doc.body.innerHTML =
+ '<div data-composition-id="main"><div data-composition-src="child.html"></div></div>';
+ iframe.dispatchEvent(new Event("load"));
+ vi.advanceTimersByTime(200);
+ const script = iframe.contentDocument?.querySelector("script[src]");
+ if (!(script instanceof HTMLScriptElement)) throw new Error("missing injected runtime");
+ expect(script.src).toBe(expected ?? RUNTIME_CDN_URL);
+ });
+
+ it("rejects a late runtime handshake after a load failure", () => {
+ const { player, iframe, onError, onReady } = mountPlayer();
+ vi.advanceTimersByTime(200);
+ const script = iframe.contentDocument?.querySelector("script[src]");
+ if (!(script instanceof HTMLScriptElement)) throw new Error("missing injected runtime");
+ script.dispatchEvent(new Event("error"));
+ expect(onError).toHaveBeenCalledOnce();
+ sendTimeline(iframe);
+ expectUnready(player, onReady);
+ });
+
+ it("can recover from a load failure in the next document", () => {
+ const { player, iframe, onReady } = mountPlayer();
+ vi.advanceTimersByTime(200);
+ const script = iframe.contentDocument?.querySelector("script[src]");
+ if (!(script instanceof HTMLScriptElement)) throw new Error("missing injected runtime");
+ script.dispatchEvent(new Event("error"));
+ const replacement = document.implementation.createHTMLDocument("Replacement");
+ keepDocument(iframe, replacement);
+ iframe.dispatchEvent(new Event("load"));
+ sendTimeline(iframe);
+ expectTimelineReady(player, onReady);
+ });
});
diff --git a/packages/player/src/shader-options.ts b/packages/player/src/shader-options.ts
index 094867830a..b7e6ca0a7f 100644
--- a/packages/player/src/shader-options.ts
+++ b/packages/player/src/shader-options.ts
@@ -158,7 +158,7 @@ export function prepareSrcdocForElement(el: Element, srcdoc: string): string {
);
}
-function runtimeSrcFromElement(el: Element): string {
+export function runtimeSrcFromElement(el: Element): string {
const configured = el.getAttribute(RUNTIME_SRC_ATTR)?.trim();
if (!configured) return RUNTIME_CDN_URL;
try {
diff --git a/packages/player/src/shouldInjectRuntime.ts b/packages/player/src/shouldInjectRuntime.ts
index f409f519e8..9f761b0f2f 100644
--- a/packages/player/src/shouldInjectRuntime.ts
+++ b/packages/player/src/shouldInjectRuntime.ts
@@ -3,7 +3,7 @@
* current probe tick.
*
* The player polls the loaded iframe every 200ms to discover either:
- * - a runtime bridge already installed (`window.__hf` / `window.__player`), or
+ * - a runtime bridge already installed (`window.__player`), or
* - GSAP timelines registered at `window.__timelines`.
*
* Two classes of composition require different injection timing:
diff --git a/packages/player/vitest.config.ts b/packages/player/vitest.config.ts
index d1120714f3..0744efa273 100644
--- a/packages/player/vitest.config.ts
+++ b/packages/player/vitest.config.ts
@@ -25,6 +25,9 @@ export default defineConfig({
},
test: {
environment: "happy-dom",
+ environmentOptions: {
+ happyDOM: { settings: { handleDisabledFileLoadingAsSuccess: true } },
+ },
setupFiles: ["./src/slideshow/test-setup.ts"],
},
});