mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 08:32:45 +00:00
fix(player): a sealed player plays media from hosts without CORS and names a missing runtime (#8142)
* feat(player): a composition can no longer read the page that embeds the player BREAKING CHANGE: the player's composition frame no longer shares the embedding page's origin by default. Add sandbox-origin="same-origin" to keep reading the composition's DOM or runtime directly (editors, recorders, custom timelines), only for compositions you trust. * chore(skills): refresh the slideshow skill's manifest hash * fix(player): a sealed player's timeout says how to play a composition without the runtime A sealed player cannot add the runtime to a composition, so one with a GSAP timeline and no runtime never became ready and failed with a bare timeout. The timeout now names the two fixes, the README says a sealed composition brings its own runtime, and a browser test covers the sealed, trusted and runtime-bundled paths. * test(player): the heavy-films bench embeds the trusted player, since it reads the film from inside * test(player): the bench host stays sealed; only the bench that reads the film asks for trust * test(player): the perf server answers CORS, so a sealed player's film loads its own media * test(player): a sealed film on a host without CORS must still play its videos * test(core): a sealed video whose CORS load fails loads again once without crossorigin * fix(core): a sealed film's video loads once more without CORS when its host refuses CORS * fix(core): the sealed media fallback reads its event target without a realm-bound instanceof * fix(player): keep the player's origin sharing as today; sealing stays opt-in with sandbox-origin * test(core): a failed sealed media source spares its siblings; a refused URL drops the helper's CORS * fix(core): a sealed film tries every CORS source before falling back and drops CORS for refused URLs * fix(cli): the play page shares its origin as today; docs say sealing is opt-in * refactor(core): split the sealed media fallback into small steps * test(player): sealed media decides CORS per element in Chrome; probe advice follows the policy * fix(core): each sealed media element owns its CORS choice; probe advice follows the policy * test(player): a sealed player's late timeline expects the sealed advice; media cases await each read * test(player): sealed media rows for a skipped first source, author writes and a recovered URL * fix(core): sealed media falls back only when the browser has no source left, once per URL * test(player): the skipped-source row's loads are never cached, so each one is counted * test(player): the skipped-source row bounds the video's load attempts as well as its requests * test(player): sealed media rows for a mismatched-source reload, an outage and two refusing sources * fix(core): a sealed media element owns one fallback state; only a played fallback is remembered * test(player): a generated table of sealed media edits, each element checked on its own * fix(core): sealed media CORS is decided per element and chosen source, with no shared cache * test(player): the media table counts the runtime's loads against other selections * fix(core): a sealed media element guesses the source it last played * test(player): the media table attributes loads exactly and lets a failing host stay down * test: sealed media rows check per-element CORS; the generated table replaces the hand-picked ones * fix(core): a media element's own src counts as the source that failed * fix(core): starting sealed media CORS twice adds no second set of listeners * test(player): judge the sealed media table against frames without the runtime * test(player): compare the sealed media table with the same film unsealed * test(player): run the unsealed control film before the sealed one in one tab * test(player): judge an authored crossorigin only on the composition's value * test(player): an all-own list returning to an upgraded URL keeps its pixels * test(player): source and playback against the sealed film with the helper off * test(player): count every runtime load of a table video, net of the film without the helper * test(player): the all-own return row plays the other clip alone before the URL comes back * test(player): judge every round of the sealed media table, not only the end * fix(core): sealed media keeps the browser's source choice and its playback across our reloads * test(player): the table plays a video only after the runtime has bound it * fix(core): a sealed video drops a stale crossorigin its source already refused * test(player): the table exempts foreign hosts from pixels and allows a range request per load * test(core): unit rows for the source choice, down hosts and playback across reloads * refactor(core): sealed media restores time through the media clock, and its failure path is split * test(player): the table compares play() outcomes, recovers a down host, and reads a seek at seeked * test(player): the table judges a seek by where it settles and lets a composition pause on rejection * test(player): the table holds the helper to a play() the film without it resolved * test(player): pin the generated sequences that found the recovery and play() faults * test(player): a slow host keeps the composition's play() pending when its source fails * test(player): pin the sequences that find the play() and recovery faults with the slow host * test(player): the table can start its generated sequences at any seed * test(player): pin the generated sequences that find the recovered source skipped * test(player): keep the pinned sequences that are red in every run in both browsers * test(player): a looping video starting over is not a seek after the composition's * fix(core): a sealed video retries a recovered source and keeps the composition's play() alive * test(core): the playback row watches the play() the runtime's retry makes * test(player): a slow host delays its first answer only; the composition's own abort is skipped * test(player): a loop restart is told from a seek by where the seek began * test(player): restarts are read at metadata, and a buffering control judges no playback * test(player): the table counts and limits the comparisons it skips * test(player): our restore after a composition seek stays within a frame; all selections count * test(player): a playhead counts as moving if it moves within a second * fix(core): only the composition's own load() makes a sealed video retry a down source * fix(core): a sealed video's down source stays down through the runtime's preload load * test(player): judge sealed media rows by what each step makes possible, not page timing * test(player): print sealed and unsealed seek landings each sealed media run * test(player): read a looping clip after its loop restart in every film alike * fix(core): the runtime's preload loads a media element once per source list * fix(core): the runtime's prefetch shares the preload's one load per source list * test(player): a table step interrupts the CORS handling's own reload, not the runtime's preload * test(core): an undo puts a clip's colour grade back in a sealed preview in place * fix(core): an undo of a colour grade applies in place in a sealed preview * test(player): a second table seek lands during the CORS reload of a playing clip * test(core): an undo in a sealed preview keeps the media attributes the runtime added * fix(core): an undo in a sealed preview keeps the media attributes the runtime added * test(player): the playing-clip seek row plays a clip that starts past 0, as a trimmed one does * test(player): the playing-clip seek is armed with its video, before the play step waits * test(player): the down-then-back row reloads again, so every film's control has a frame * test(player): the playing-clip seek row's host answers late, so the clip plays before its reload * fix(player): a sealed player plays a same-site composition with the runtime it ships * fix(player): a switch to video unloads a sealed composition shown as srcdoc * test(core): the runtime's preload mid-selection keeps a down source's mark * fix(core): a sealed film's down source keeps its mark through the runtime's own loads * chore(player): fallow reads the cjs and iife runtime file as an entry * fix(core): declare the html-tokens subpath where package exports are generated * fix(player): a sealed composition that brings its runtime loads by src under its own headers * test(player): expect the sealed player's own timeout message in the late-runtime tests * test(core): a grade undo on a far clip whose length is loading applies in place * fix(core): a far clip's length probe records the preload it sets, so a grade undo applies * fix(player): a sealed film shown as srcdoc keeps its URL, so its sound still plays * test(player): the late-timeline switch uses a film from another origin, which must still fail * fix(player): a sealed Studio preview keeps its own runtime and loads by src * fix(player): the player package carries the runtime once, and Studio none * fix(core): a sealed video reads its own source's pixels in a list that names another host * fix(player): a sealed player with no bundler still gets the runtime, only when it needs it * fix(core): keep the mixed-list change within the comment budget * fix(core): opt a mixed list in only when its first source plays, so a reload keeps that video * fix(core): a CORS reload keeps the source that was playing * fix(core): the composition's own load() picks from its full source list again * fix(core): a reload's pin keeps a source type the composition wrote meanwhile * fix(core): a reload's pin stops at the source the browser picked, not a skipped copy of its URL * fix(core): a reload's pin stops at the source element that played, not the first copy of its URL * fix(core): a reload's pin keeps the source element that played or refused * style(core): format the source pin * style(player): keep the runtime source comment under the line limit * fix(player): only a real </script> closing tag ends a script in the runtime check * test(player): count the sealed helper's loads by the crossorigin they change * fix(core): a sealed video asks its host once before treating a failed CORS load as a refusal * test(player): the sealed table expects pixels from a host that answers CORS after a failed load * test(core): each refusal row waits for the CORS question it starts * test(player): the sealed media table waits on each clip's own events * refactor(core): a pinned-out source's error gets its own check in the sealed media helper * test(player): the loop restart wait keeps its two-second window * style(player): format the table's event wait * chore(fallow): resolve workspace exports to source as bun does, so no false package cycle * refactor(player): read script tag attributes in small steps, the same result * refactor(player): the shader loading attribute reads its words from one table * refactor(player): the attribute helpers' names say what their comments did * fix(core): the CORS question never follows a redirect, and stays quiet while it waits * style(core): format the CORS question's rows * test(player): a sealed same-site page keeps its own policy; a stuck fetch reports the limit * fix(player): a sealed same-site page keeps its own policy, and a stuck fetch ends at the limit * fix(player): a sealed page whose headers can't all be read, as after a redirect, loads by src * style(player): format the sealed player and name the probe's preparation state
This commit is contained in:
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/fallow-rs/fallow/main/config-schema.json",
|
||||
// Resolve workspace exports as bun does, to their source: without it fallow took Studio's vite alias for
|
||||
// @hyperframes/core/runtime-script in player source and reported a player -> studio package cycle.
|
||||
"resolve": { "conditions": ["bun"] },
|
||||
"entry": [
|
||||
// IconButton, Tabs and cn are exported before their first consumer exists.
|
||||
"packages/studio/src/components/ui/index.ts",
|
||||
@@ -47,6 +50,8 @@
|
||||
"packages/core/stubs/audio-fx-runtime-entry.ts",
|
||||
// And for the SVG selector alias installer compiled scene scripts carry.
|
||||
"packages/core/stubs/svg-selector-aliases-entry.ts",
|
||||
// The player's cjs and iife builds alias @hyperframes/core/runtime-script to it in tsup.config.ts.
|
||||
"packages/player/src/runtime-beside-bundle.ts",
|
||||
// In-page audit scripts read as raw strings and injected via
|
||||
// page.addScriptTag (see layout.ts / validate.ts) — referenced by file
|
||||
// path, never imported, so they have no import-graph referrer.
|
||||
|
||||
@@ -129,6 +129,20 @@ jobs:
|
||||
PUPPETEER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
|
||||
run: bun run test:browser-security
|
||||
|
||||
- name: Verify a sealed film plays on a host with or without CORS (load shard only)
|
||||
if: matrix.shard == 'load'
|
||||
working-directory: packages/player
|
||||
env:
|
||||
PUPPETEER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
|
||||
run: bun run test:browser-sealed-media
|
||||
|
||||
- name: Verify a sealed same-site film plays with the runtime the player ships (load shard only)
|
||||
if: matrix.shard == 'load'
|
||||
working-directory: packages/player
|
||||
env:
|
||||
PUPPETEER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
|
||||
run: bun run test:browser-sealed-runtime
|
||||
|
||||
- name: Verify the preview rasters at its shown size (load shard only)
|
||||
if: matrix.shard == 'load'
|
||||
working-directory: packages/player
|
||||
|
||||
@@ -95,7 +95,7 @@ Start with the [SDK quickstart](/sdk/quickstart).
|
||||
```html title="index.html"
|
||||
<script
|
||||
type="module"
|
||||
src="https://cdn.jsdelivr.net/npm/@hyperframes/player"
|
||||
src="https://cdn.jsdelivr.net/npm/@hyperframes/player/dist/hyperframes-player.js"
|
||||
></script>
|
||||
|
||||
<hyperframes-player
|
||||
|
||||
@@ -458,7 +458,7 @@ Run before delivering. Check with actual code, not assumptions.
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
<script type="module" src="https://cdn.jsdelivr.net/npm/@hyperframes/player"></script>
|
||||
<script type="module" src="https://cdn.jsdelivr.net/npm/@hyperframes/player/dist/hyperframes-player.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<hyperframes-player
|
||||
|
||||
@@ -19,7 +19,7 @@ Use Player when an application needs to play and seek an HTML composition. Use
|
||||
### Via CDN
|
||||
|
||||
```html title="index.html"
|
||||
<script type="module" src="https://cdn.jsdelivr.net/npm/@hyperframes/player"></script>
|
||||
<script type="module" src="https://cdn.jsdelivr.net/npm/@hyperframes/player/dist/hyperframes-player.js"></script>
|
||||
|
||||
<hyperframes-player
|
||||
src="./my-composition/index.html"
|
||||
@@ -223,7 +223,11 @@ iframeRef.current = resolveIframe(player);
|
||||
|
||||
The composition runs in a sandboxed iframe inside the player's Shadow DOM. This
|
||||
isolates its styles, scales it to the player container, and lets the player
|
||||
communicate with the HyperFrames runtime through `postMessage`.
|
||||
communicate with the HyperFrames runtime through `postMessage`. Set
|
||||
`sandbox-origin="opaque"` to seal the frame, so the composition cannot read
|
||||
your page or its cookies. The player adds the runtime itself to a composition
|
||||
from your own site; a composition from another site must include the runtime
|
||||
script.
|
||||
|
||||
## Related topics
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import { buildPlayApp } from "./play.js";
|
||||
import { buildPresentApp } from "./present.js";
|
||||
|
||||
// HeyGen's sign-in sends a CLI sign-in code back to any local port, and the play and present pages
|
||||
// share their origin with the composition frame (`sandbox-origin="same-origin"`), so anything those
|
||||
// share their origin with the composition frame (the player's default), so anything those
|
||||
// pages can read, a project's script can read through `parent`. Each probe runs on the server's own
|
||||
// page and checks that a sign-in return address that landed on that server stays out of its reach.
|
||||
|
||||
|
||||
@@ -548,6 +548,12 @@
|
||||
"types": "./dist/compiler/compositionSizeLimit.d.ts",
|
||||
"environments": ["bun", "node"]
|
||||
},
|
||||
"./compiler/html-tokens": {
|
||||
"source": "./src/compiler/htmlTokens.ts",
|
||||
"runtime": "./dist/compiler/htmlTokens.js",
|
||||
"types": "./dist/compiler/htmlTokens.d.ts",
|
||||
"environments": ["browser", "bun", "node"]
|
||||
},
|
||||
"./compiler/html-document": {
|
||||
"source": "./src/compiler/htmlDocument.ts",
|
||||
"runtime": "./dist/compiler/htmlDocument.js",
|
||||
|
||||
@@ -555,6 +555,12 @@
|
||||
"import": "./src/compiler/compositionSizeLimit.ts",
|
||||
"types": "./src/compiler/compositionSizeLimit.ts"
|
||||
},
|
||||
"./compiler/html-tokens": {
|
||||
"bun": "./src/compiler/htmlTokens.ts",
|
||||
"node": "./dist/compiler/htmlTokens.js",
|
||||
"import": "./src/compiler/htmlTokens.ts",
|
||||
"types": "./src/compiler/htmlTokens.ts"
|
||||
},
|
||||
"./compiler/html-document": {
|
||||
"bun": "./src/compiler/htmlDocument.ts",
|
||||
"node": "./dist/compiler/htmlDocument.js",
|
||||
@@ -1087,6 +1093,10 @@
|
||||
"import": "./dist/compiler/compositionSizeLimit.js",
|
||||
"types": "./dist/compiler/compositionSizeLimit.d.ts"
|
||||
},
|
||||
"./compiler/html-tokens": {
|
||||
"import": "./dist/compiler/htmlTokens.js",
|
||||
"types": "./dist/compiler/htmlTokens.d.ts"
|
||||
},
|
||||
"./compiler/html-document": {
|
||||
"import": "./dist/compiler/htmlDocument.js",
|
||||
"types": "./dist/compiler/htmlDocument.d.ts"
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import { acceleratedCanvasTrackerSource } from "../pageMotionBlur.js";
|
||||
import { findSceneTemplate, templateContent } from "@hyperframes/parsers/sub-composition-validity";
|
||||
import { parseHTML } from "linkedom";
|
||||
|
||||
export const RUNTIME_BOOTSTRAP_ATTR = "data-hyperframes-preview-runtime";
|
||||
import {
|
||||
escapeInlineScriptSource,
|
||||
indexOfLower,
|
||||
lowerAscii,
|
||||
RUNTIME_BOOTSTRAP_ATTR,
|
||||
startsWithLower,
|
||||
} from "./htmlTokens.js";
|
||||
export { escapeInlineScriptSource, RUNTIME_BOOTSTRAP_ATTR };
|
||||
|
||||
const RUNTIME_FILES = [
|
||||
"hyperframe.runtime.iife.js",
|
||||
@@ -57,33 +63,6 @@ export function parseHTMLContent(html: string): Document {
|
||||
return parseHTML(`<!DOCTYPE html><html><head></head><body>${html}</body></html>`).document;
|
||||
}
|
||||
|
||||
/** ASCII-only chunks bound match arrays; starting at uppercase preserves unchanged spans. */
|
||||
function lowerAscii(text: string): string {
|
||||
return text.replace(/[A-Z][\s\S]{0,65535}/g, (chunk) =>
|
||||
chunk.replace(/[A-Z]+/g, (letters) => letters.toLowerCase()),
|
||||
);
|
||||
}
|
||||
|
||||
function startsWithLower(text: string, token: string, at: number): boolean {
|
||||
if (at < 0 || at + token.length > text.length) return false;
|
||||
for (let i = 0; i < token.length; i += 1) {
|
||||
const code = text.charCodeAt(at + i);
|
||||
if ((code >= 65 && code <= 90 ? code + 32 : code) !== token.charCodeAt(i)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function indexOfLower(text: string, token: string, from: number): number {
|
||||
for (
|
||||
let at = text.indexOf(token.charAt(0), from);
|
||||
at !== -1;
|
||||
at = text.indexOf(token.charAt(0), at + 1)
|
||||
) {
|
||||
if (startsWithLower(text, token, at)) return at;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function lastIndexOfLower(text: string, token: string): number {
|
||||
for (
|
||||
let at = text.lastIndexOf(token.charAt(0));
|
||||
@@ -225,38 +204,6 @@ function isHtmlWhitespace(char: string): boolean {
|
||||
return char === " " || char === "\n" || char === "\t" || char === "\r" || char === "\f";
|
||||
}
|
||||
|
||||
export function escapeInlineScriptSource(source: string): string {
|
||||
return escapeCaseInsensitiveToken(
|
||||
escapeCaseInsensitiveToken(source, "</script", (match) => `<\\/${match.slice(2)}`),
|
||||
"<!--",
|
||||
() => "\\x3C!--",
|
||||
);
|
||||
}
|
||||
|
||||
function escapeCaseInsensitiveToken(
|
||||
source: string,
|
||||
token: string,
|
||||
replacement: (match: string) => string,
|
||||
): string {
|
||||
const loweredToken = lowerAscii(token);
|
||||
let output = "";
|
||||
let cursor = 0;
|
||||
|
||||
while (cursor < source.length) {
|
||||
const tokenStart = indexOfLower(source, loweredToken, cursor);
|
||||
if (tokenStart === -1) {
|
||||
output += source.slice(cursor);
|
||||
break;
|
||||
}
|
||||
output +=
|
||||
source.slice(cursor, tokenStart) +
|
||||
replacement(source.slice(tokenStart, tokenStart + token.length));
|
||||
cursor = tokenStart + token.length;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
function inlineScriptTags(scripts: readonly string[]): string {
|
||||
return scripts
|
||||
.map((source, index) => `${source}\n//# sourceURL=hyperframes://injected/${index}`)
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/** Case-insensitive HTML token scans, with no DOM: the player inlines scripts with these too. */
|
||||
|
||||
export const RUNTIME_BOOTSTRAP_ATTR = "data-hyperframes-preview-runtime";
|
||||
|
||||
/** ASCII-only chunks bound match arrays; starting at uppercase preserves unchanged spans. */
|
||||
export function lowerAscii(text: string): string {
|
||||
return text.replace(/[A-Z][\s\S]{0,65535}/g, (chunk) =>
|
||||
chunk.replace(/[A-Z]+/g, (letters) => letters.toLowerCase()),
|
||||
);
|
||||
}
|
||||
|
||||
export function startsWithLower(text: string, token: string, at: number): boolean {
|
||||
if (at < 0 || at + token.length > text.length) return false;
|
||||
for (let i = 0; i < token.length; i += 1) {
|
||||
const code = text.charCodeAt(at + i);
|
||||
if ((code >= 65 && code <= 90 ? code + 32 : code) !== token.charCodeAt(i)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function indexOfLower(text: string, token: string, from: number): number {
|
||||
for (
|
||||
let at = text.indexOf(token.charAt(0), from);
|
||||
at !== -1;
|
||||
at = text.indexOf(token.charAt(0), at + 1)
|
||||
) {
|
||||
if (startsWithLower(text, token, at)) return at;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
export function escapeInlineScriptSource(source: string): string {
|
||||
return escapeCaseInsensitiveToken(
|
||||
escapeCaseInsensitiveToken(source, "</script", (match) => `<\\/${match.slice(2)}`),
|
||||
"<!--",
|
||||
() => "\\x3C!--",
|
||||
);
|
||||
}
|
||||
|
||||
function escapeCaseInsensitiveToken(
|
||||
source: string,
|
||||
token: string,
|
||||
replacement: (match: string) => string,
|
||||
): string {
|
||||
const loweredToken = lowerAscii(token);
|
||||
let output = "";
|
||||
let cursor = 0;
|
||||
|
||||
while (cursor < source.length) {
|
||||
const tokenStart = indexOfLower(source, loweredToken, cursor);
|
||||
if (tokenStart === -1) {
|
||||
output += source.slice(cursor);
|
||||
break;
|
||||
}
|
||||
output +=
|
||||
source.slice(cursor, tokenStart) +
|
||||
replacement(source.slice(tokenStart, tokenStart + token.length));
|
||||
cursor = tokenStart + token.length;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { parseRestoreAttributes, restoreInPlace } from "./restoreAttributes";
|
||||
import { corsForSealedMedia } from "../sealedMediaCors";
|
||||
import { setRuntimePreload } from "../runtimeAttributes";
|
||||
import {
|
||||
HF_COLOR_GRADING_ATTR,
|
||||
normalizeHfColorGrading,
|
||||
serializeHfColorGrading,
|
||||
} from "../../colorGrading";
|
||||
|
||||
type TestWindow = Window & Record<string, unknown>;
|
||||
const win = window as TestWindow;
|
||||
@@ -45,6 +52,104 @@ describe("restore-attributes", () => {
|
||||
expect(calls).toEqual(["seek 1.5", "rebind", "manual"]);
|
||||
});
|
||||
|
||||
describe("a clip's colour grade", () => {
|
||||
const graded = (grading: string) => {
|
||||
document.body.innerHTML = `<video data-hf-id="clip"></video>`;
|
||||
document.querySelector("video")!.setAttribute(HF_COLOR_GRADING_ATTR, grading);
|
||||
player();
|
||||
};
|
||||
const undoTo = (grading: string) =>
|
||||
restore("hf:clip", [
|
||||
["data-hf-id", "clip"],
|
||||
[HF_COLOR_GRADING_ATTR, grading],
|
||||
]);
|
||||
const live = () => document.querySelector("video")!.getAttribute(HF_COLOR_GRADING_ATTR);
|
||||
|
||||
it("is put back in place, rebuilt from the grade's own fields rather than copied", () => {
|
||||
graded('{"adjust":{"exposure":1.5}}');
|
||||
const restored = '{ "adjust": { "exposure": 0.1 }, "onload": "alert(1)" }';
|
||||
|
||||
expect(restoreInPlace(undoTo(restored))).toBe("applied");
|
||||
expect(live()).toBe(serializeHfColorGrading(normalizeHfColorGrading(restored)));
|
||||
expect(live()).not.toContain("onload");
|
||||
});
|
||||
|
||||
it("is refused when it would load a LUT the clip does not already use", () => {
|
||||
graded('{"adjust":{"exposure":1.5}}');
|
||||
const before = document.body.innerHTML;
|
||||
|
||||
expect(restoreInPlace(undoTo('{"lut":{"src":"https://example.com/look.cube"}}'))).toBe(
|
||||
"refused",
|
||||
);
|
||||
expect(document.body.innerHTML).toBe(before);
|
||||
});
|
||||
|
||||
it("keeps the clip's own LUT when only the rest of the grade changes", () => {
|
||||
graded('{"lut":{"src":"luts/look.cube"},"adjust":{"exposure":1.5}}');
|
||||
const restored = '{"lut":{"src":"luts/look.cube"},"adjust":{"exposure":0.1}}';
|
||||
|
||||
expect(restoreInPlace(undoTo(restored))).toBe("applied");
|
||||
expect(normalizeHfColorGrading(live())?.adjust.exposure).toBe(0.1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a video's crossorigin and preload", () => {
|
||||
const retimed = restore("hf:clip", [
|
||||
["data-hf-id", "clip"],
|
||||
["src", "media/clip.mp4"],
|
||||
["data-start", "1"],
|
||||
]);
|
||||
|
||||
it("are kept when the runtime added them (crossorigin through the sealed CORS writer), and the restore applies", async () => {
|
||||
document.head.innerHTML = '<base href="http://localhost:4817/api/projects/demo/preview/">';
|
||||
vi.stubGlobal("origin", "null");
|
||||
const observer = corsForSealedMedia();
|
||||
document.body.innerHTML =
|
||||
'<video data-hf-id="clip" src="media/clip.mp4" data-start="0"></video>';
|
||||
await Promise.resolve();
|
||||
const video = document.querySelector("video")!;
|
||||
setRuntimePreload(video, "auto");
|
||||
player();
|
||||
|
||||
expect(restoreInPlace(retimed)).toBe("applied");
|
||||
expect(video.getAttribute("data-start")).toBe("1");
|
||||
expect(video.getAttribute("crossorigin")).toBe("anonymous");
|
||||
expect(video.getAttribute("preload")).toBe("auto");
|
||||
observer?.disconnect();
|
||||
vi.unstubAllGlobals();
|
||||
document.head.innerHTML = "";
|
||||
});
|
||||
|
||||
it("stop being kept once the film changes the runtime's crossorigin itself", async () => {
|
||||
document.head.innerHTML = '<base href="http://localhost:4817/api/projects/demo/preview/">';
|
||||
vi.stubGlobal("origin", "null");
|
||||
const observer = corsForSealedMedia();
|
||||
document.body.innerHTML =
|
||||
'<video data-hf-id="clip" src="media/clip.mp4" data-start="0"></video>';
|
||||
await Promise.resolve();
|
||||
const video = document.querySelector("video")!;
|
||||
video.setAttribute("crossorigin", "use-credentials");
|
||||
await Promise.resolve();
|
||||
player();
|
||||
|
||||
expect(restoreInPlace(retimed)).toBe("refused");
|
||||
expect(video.getAttribute("crossorigin")).toBe("use-credentials");
|
||||
observer?.disconnect();
|
||||
vi.unstubAllGlobals();
|
||||
document.head.innerHTML = "";
|
||||
});
|
||||
|
||||
it("still count as dropped when the film's own file set them", () => {
|
||||
document.body.innerHTML =
|
||||
'<video data-hf-id="clip" src="media/clip.mp4" data-start="0" crossorigin="anonymous" preload="auto"></video>';
|
||||
player();
|
||||
const before = document.body.innerHTML;
|
||||
|
||||
expect(restoreInPlace(retimed)).toBe("refused");
|
||||
expect(document.body.innerHTML).toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
it("restores each copy of an inlined sub-composition", () => {
|
||||
document.body.innerHTML = [1, 2]
|
||||
.map((n) => `<section data-composition-file="sub.html" id="host${n}">${moved}</section>`)
|
||||
|
||||
@@ -5,7 +5,13 @@ import {
|
||||
STUDIO_REAPPLIED_MARKS,
|
||||
STUDIO_SEEK_REAPPLY_STARTED,
|
||||
} from "../../studioReappliedMarks";
|
||||
import {
|
||||
HF_COLOR_GRADING_ATTR,
|
||||
normalizeHfColorGrading,
|
||||
serializeHfColorGrading,
|
||||
} from "../../colorGrading";
|
||||
import type { SoftReloadRerun } from "./softReload";
|
||||
import { isRuntimeAttribute } from "../runtimeAttributes";
|
||||
|
||||
/** `hf:<data-hf-id>` or `id:<id>`, the key the parent's restore diff uses. */
|
||||
export type RestoreElementKey = string;
|
||||
@@ -143,6 +149,28 @@ function scopeRoots(file: string | null): ParentNode[] {
|
||||
);
|
||||
}
|
||||
|
||||
function gradeRebuiltWithoutNewLut(value: string, current: string | null): string | null {
|
||||
const next = normalizeHfColorGrading(value);
|
||||
if (!next) return null;
|
||||
if (next.lut && next.lut.src !== normalizeHfColorGrading(current)?.lut?.src) return null;
|
||||
return serializeHfColorGrading(next);
|
||||
}
|
||||
|
||||
function settable(el: Element, set: RestoreAttribute[]): RestoreAttribute[] | null {
|
||||
const safe: RestoreAttribute[] = [];
|
||||
for (const [name, value] of set) {
|
||||
const next =
|
||||
name === HF_COLOR_GRADING_ATTR
|
||||
? gradeRebuiltWithoutNewLut(value, el.getAttribute(HF_COLOR_GRADING_ATTR))
|
||||
: safeToSet(name)
|
||||
? value
|
||||
: null;
|
||||
if (next === null) return null;
|
||||
safe.push([name, next]);
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
|
||||
export type RestorePlan = [Element, drop: string[], set: RestoreAttribute[]][];
|
||||
|
||||
/** Adds `root`'s live elements to `plan`; false when any is missing, not the file's own, or unsafe to change. */
|
||||
@@ -158,10 +186,13 @@ function planRoot(
|
||||
// The preview rewrites a sub-composition's own root, so its attributes are not the file's.
|
||||
if (!el || el.hasAttribute("data-hf-inner-root")) return false;
|
||||
const keep = new Set(attributes.map(([name]) => name));
|
||||
const drop = el.getAttributeNames().filter((name) => !keep.has(name));
|
||||
const drop = el
|
||||
.getAttributeNames()
|
||||
.filter((name) => !keep.has(name) && !isRuntimeAttribute(el, name));
|
||||
const set = attributes.filter(([name, value]) => el.getAttribute(name) !== value);
|
||||
if (!drop.every(safeToDrop) || !set.every(([name]) => safeToSet(name))) return false;
|
||||
plan.push([el, drop, set]);
|
||||
const safeSet = settable(el, set);
|
||||
if (!drop.every(safeToDrop) || !safeSet) return false;
|
||||
plan.push([el, drop, safeSet]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -533,6 +533,36 @@ describe("runtime entry", () => {
|
||||
expect(loadsOf(now!)).toEqual([1]);
|
||||
});
|
||||
|
||||
// fails without the fix: the far clip's length probe set preload without recording it, so a grade undo on that
|
||||
// clip read preload as an attribute it would drop and was refused while the length loaded.
|
||||
it("a grade undo on a far clip whose length is still loading applies in place", async () => {
|
||||
spyLoad();
|
||||
servePreview();
|
||||
const clips = videos(mountRoot(), "0", "1.5", "6");
|
||||
for (const clip of clips) clip.removeAttribute("data-duration");
|
||||
const later = clips[2] as HTMLVideoElement;
|
||||
later.setAttribute("data-hf-id", "later");
|
||||
const authored = later
|
||||
.getAttributeNames()
|
||||
.map((name): [string, string] => [name, later.getAttribute(name)!]);
|
||||
|
||||
await evaluateRuntime();
|
||||
expect(later.preload).toBe("metadata");
|
||||
const { isRuntimeAttribute } = await import("./runtimeAttributes");
|
||||
const { restoreInPlace } = await import("./editing/restoreAttributes");
|
||||
expect(isRuntimeAttribute(later, "preload")).toBe(true);
|
||||
const grade: [string, string] = [
|
||||
HF_COLOR_GRADING_ATTR,
|
||||
serializeHfColorGrading({ adjust: { exposure: 0.5 } }),
|
||||
];
|
||||
const undo = {
|
||||
scopes: [{ file: null, elements: [{ key: "hf:later", attributes: [...authored, grade] }] }],
|
||||
scripted: false,
|
||||
time: 0,
|
||||
};
|
||||
expect(restoreInPlace(undo)).toBe("applied");
|
||||
});
|
||||
|
||||
// fails without the fix: a preview loaded every clip with no authored length in full, so a film of hundreds ran
|
||||
// the page out of memory.
|
||||
it("in a preview a far clip with no authored length loads only its length, then gives its decoder back and keeps the length", async () => {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { rememberSourceLength, sourceLengthOf } from "./sourceLength";
|
||||
import { restSceneAt, sceneRestingAt, takeSceneRedrawDue } from "./sceneRest";
|
||||
import { wallClearTimeout, wallSetTimeout } from "./wallClock";
|
||||
import { runtimeLoad } from "./runtimeLoad";
|
||||
import { setPreviewRasterScale } from "./previewRasterHints";
|
||||
import { createFarSceneSkip } from "./farScenes";
|
||||
import {
|
||||
@@ -269,6 +270,7 @@ import {
|
||||
type StylableElement,
|
||||
} from "./domRealm";
|
||||
import { audibleVideoNeedsWebAudio, isAudibleVideoElement, parentCopyOf } from "../audibleVideo";
|
||||
import { setRuntimePreload } from "./runtimeAttributes";
|
||||
|
||||
/**
|
||||
* A `window.__timelines` entry is authored content and may be a PARTIAL
|
||||
@@ -2776,7 +2778,7 @@ export function initSandboxRuntimeModular(): void {
|
||||
learnsLength(el) &&
|
||||
resolveAbsoluteMediaStartSeconds(el) > state.currentTime + LOOKAHEAD_SECONDS
|
||||
) {
|
||||
el.preload = "metadata";
|
||||
setRuntimePreload(el, "metadata");
|
||||
el.load();
|
||||
} else preloadMedia(el);
|
||||
};
|
||||
@@ -2792,7 +2794,7 @@ export function initSandboxRuntimeModular(): void {
|
||||
}
|
||||
if (!freesBufferedVideo(el) || mediaNearPlayhead.get(el) !== false || el.readyState === 0)
|
||||
return;
|
||||
el.preload = "none";
|
||||
setRuntimePreload(el, "none");
|
||||
withoutOwnTimingRecords(el, () => releaseMedia(el, true));
|
||||
};
|
||||
const onMediaErrorForProxy = (event: Event) => {
|
||||
@@ -3380,7 +3382,7 @@ export function initSandboxRuntimeModular(): void {
|
||||
mediaNearPlayhead.set(el, near);
|
||||
if (!near) {
|
||||
const wasPreloading = el.preload !== "none";
|
||||
el.preload = "none";
|
||||
setRuntimePreload(el, "none");
|
||||
const video = freesBufferedVideo(el);
|
||||
const holdsPipeline = video
|
||||
? decided || el.readyState > 0 || el.networkState === 2
|
||||
@@ -5212,8 +5214,8 @@ export function initSandboxRuntimeModular(): void {
|
||||
moveMediaWindow(time, clips);
|
||||
for (const { el } of clips) {
|
||||
if (!isVideoElement(el) || el.videoWidth > 0) continue;
|
||||
if (el.preload === "none") el.preload = "metadata";
|
||||
if (el.networkState !== 2) el.load();
|
||||
if (el.preload === "none") setRuntimePreload(el, "metadata");
|
||||
if (el.networkState !== 2) runtimeLoad(el);
|
||||
}
|
||||
const requests = clips.flatMap((clip) =>
|
||||
isVideoElement(clip.el)
|
||||
@@ -5267,7 +5269,7 @@ export function initSandboxRuntimeModular(): void {
|
||||
moveMediaWindow(time, clips);
|
||||
for (const clip of clips) {
|
||||
const { el } = clip;
|
||||
if (el.preload !== "auto") el.preload = "auto";
|
||||
if (el.preload !== "auto") setRuntimePreload(el, "auto");
|
||||
if (el.readyState === 1 && !el.seeking)
|
||||
el.currentTime = mediaElementTime(mediaSourceTimeAt(clip, time));
|
||||
}
|
||||
@@ -6234,7 +6236,7 @@ export function initSandboxRuntimeModular(): void {
|
||||
)
|
||||
.map((clip) => {
|
||||
const { el } = clip;
|
||||
el.preload = "metadata";
|
||||
setRuntimePreload(el, "metadata");
|
||||
withoutOwnTimingRecords(el, () => releaseMedia(el));
|
||||
if (el.readyState === 0)
|
||||
el.addEventListener(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { sourceLengthOf } from "./sourceLength";
|
||||
import { wallClearTimeout, wallSetTimeout } from "./wallClock";
|
||||
import { runtimeLoad } from "./runtimeLoad";
|
||||
import { swallow } from "./diagnostics";
|
||||
import { isClipVisibleAt, isInClipWindow } from "./clipWindow";
|
||||
import { isWebKit, mediaElementTime, startsSoundOnlyInsideATap } from "./mediaClock";
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
MEDIA_SYNC_TOLERANCE_SECONDS,
|
||||
steerMedia,
|
||||
} from "./mediaSteer.js";
|
||||
import { setRuntimePreload } from "./runtimeAttributes";
|
||||
export { MEDIA_HARD_SYNC_SECONDS, MEDIA_SYNC_TOLERANCE_SECONDS } from "./mediaSteer.js";
|
||||
export type { RuntimeMediaClip } from "./types.js";
|
||||
export {
|
||||
@@ -698,7 +700,7 @@ export function syncRuntimeMedia(params: {
|
||||
// past the buffered range. Setting this on every tick is cheap
|
||||
// (no-op when already "auto") and catches elements whose preload
|
||||
// was overridden after init.ts set it.
|
||||
if (el.preload !== "auto" && !isRenderFrameVideo(el)) el.preload = "auto";
|
||||
if (el.preload !== "auto" && !isRenderFrameVideo(el)) setRuntimePreload(el, "auto");
|
||||
if (!params.playing && ownsPausedVideoTime(el)) {
|
||||
if (!el.paused) el.pause();
|
||||
continue;
|
||||
@@ -854,7 +856,7 @@ export function syncRuntimeMedia(params: {
|
||||
else heldTailSeekedTo.delete(el);
|
||||
if (Math.abs(el.currentTime - relTime) > 0.5 && !seekLoadRetried.has(el)) {
|
||||
seekLoadRetried.add(el);
|
||||
el.load();
|
||||
runtimeLoad(el);
|
||||
try {
|
||||
el.currentTime = mediaElementTime(relTime);
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { wallClearInterval, wallSetInterval, wallSetTimeout } from "./wallClock";
|
||||
import { runtimeLoad } from "./runtimeLoad";
|
||||
import { postRuntimeMessage } from "./bridge";
|
||||
import { swallow } from "./diagnostics";
|
||||
import {
|
||||
@@ -243,7 +244,7 @@ function restoreOriginal(el: HTMLMediaElement): void {
|
||||
holdShownFrame(el);
|
||||
el.setAttribute("src", original);
|
||||
}
|
||||
el.load();
|
||||
runtimeLoad(el);
|
||||
}
|
||||
|
||||
// Wide enough to stand in for the picture for the moment a swap takes; small enough to encode in a few ms.
|
||||
@@ -310,7 +311,7 @@ function loadProxy(
|
||||
holdShownFrame(el);
|
||||
keepFileSize(el, href, originalSrc);
|
||||
el.src = href;
|
||||
el.load();
|
||||
runtimeLoad(el);
|
||||
}
|
||||
|
||||
// Each size this page pinned, keyed by mark and copy address, so a video given any other file is sized as before.
|
||||
|
||||
@@ -21,10 +21,23 @@ function media(tagName = "VIDEO", networkState = 2, readyState = 0, id = "", ren
|
||||
networkState,
|
||||
readyState,
|
||||
preload: "metadata",
|
||||
error: null,
|
||||
querySelectorAll: () => [],
|
||||
load: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
function videoReading(state: { networkState: number; readyState?: number; code?: number }) {
|
||||
const video = document.createElement("video");
|
||||
video.load = vi.fn();
|
||||
Object.defineProperties(video, {
|
||||
networkState: { get: () => state.networkState },
|
||||
readyState: { get: () => state.readyState ?? 0 },
|
||||
error: { get: () => (state.code ? { code: state.code } : null) },
|
||||
});
|
||||
return video;
|
||||
}
|
||||
|
||||
describe("a video the render replaces with extracted frames", () => {
|
||||
const ids = window as Window & { __HF_RENDER_FRAME_VIDEO_IDS?: readonly string[] };
|
||||
afterEach(() => delete ids.__HF_RENDER_FRAME_VIDEO_IDS);
|
||||
@@ -109,6 +122,105 @@ describe("initial media preload", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a preload load per source list", () => {
|
||||
it("loads a video on <source> children once while its selection reads idle with no data", () => {
|
||||
const video = videoReading({ networkState: 1 });
|
||||
video.innerHTML = '<source src="down.mp4"><source src="a.mp4">';
|
||||
preloadMedia(video);
|
||||
preloadMedia(video);
|
||||
expect(video.load).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("loads a suspended preload none video once, and gives it eager preload", () => {
|
||||
const video = videoReading({ networkState: 1 });
|
||||
video.setAttribute("src", "a.mp4");
|
||||
video.preload = "none";
|
||||
preloadMedia(video);
|
||||
preloadMedia(video);
|
||||
expect(video.load).toHaveBeenCalledOnce();
|
||||
expect(video.preload).toBe("auto");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["an error", { networkState: 3, code: 4 }],
|
||||
["no source left", { networkState: 3 }],
|
||||
])("loads a single src video again once its load ended with %s", (_, ended) => {
|
||||
const state = { networkState: 1 };
|
||||
const video = videoReading(state);
|
||||
video.setAttribute("src", "down.mp4");
|
||||
preloadMedia(video);
|
||||
Object.assign(state, ended);
|
||||
preloadMedia(video);
|
||||
expect(video.load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("loads again when the source list changes", () => {
|
||||
const video = videoReading({ networkState: 1 });
|
||||
video.setAttribute("src", "a.mp4");
|
||||
preloadMedia(video);
|
||||
video.setAttribute("src", "b.mp4");
|
||||
preloadMedia(video);
|
||||
expect(video.load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["", false, 2],
|
||||
[" in Studio's preview, where the release loads once itself", true, 3],
|
||||
])("loads again after its download was released%s", (_, studio, loads) => {
|
||||
const mark = studio
|
||||
? document.head.appendChild(
|
||||
Object.assign(document.createElement("meta"), { name: STUDIO_PREVIEW_MARK_META }),
|
||||
)
|
||||
: null;
|
||||
const video = videoReading({ networkState: 1 });
|
||||
video.setAttribute("src", "a.mp4");
|
||||
preloadMedia(video);
|
||||
releaseMedia(video);
|
||||
preloadMedia(video);
|
||||
mark?.remove();
|
||||
expect(video.load).toHaveBeenCalledTimes(loads);
|
||||
});
|
||||
|
||||
describe("shared with the prefetch, on Chromium", () => {
|
||||
beforeEach(() =>
|
||||
vi
|
||||
.spyOn(navigator, "userAgent", "get")
|
||||
.mockReturnValue(
|
||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/120.0 Safari/537.36",
|
||||
),
|
||||
);
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it("prefetches a clip once while its selection reads idle with no data", () => {
|
||||
const video = videoReading({ networkState: 1 });
|
||||
video.setAttribute("src", "a.mp4");
|
||||
prefetchMedia(video);
|
||||
prefetchMedia(video);
|
||||
expect(video.load).toHaveBeenCalledOnce();
|
||||
expect(video.preload).toBe("metadata");
|
||||
});
|
||||
|
||||
it("does not prefetch a clip its preload already loaded", () => {
|
||||
const video = videoReading({ networkState: 1 });
|
||||
video.setAttribute("src", "a.mp4");
|
||||
preloadMedia(video);
|
||||
prefetchMedia(video);
|
||||
expect(video.load).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("loads a prefetched clip again when it is shown short of future data, as raising preload alone does not", () => {
|
||||
const state = { networkState: 1, readyState: 0 };
|
||||
const video = videoReading(state);
|
||||
video.setAttribute("src", "a.mp4");
|
||||
prefetchMedia(video);
|
||||
state.readyState = 1;
|
||||
preloadMedia(video);
|
||||
expect(video.load).toHaveBeenCalledTimes(2);
|
||||
expect(video.preload).toBe("auto");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("releasing a clip's download", () => {
|
||||
const srcWrites = (el: Element) => {
|
||||
const observer = new MutationObserver(() => {});
|
||||
|
||||
@@ -12,15 +12,43 @@ import { readMediaRenderId } from "./renderFrameSibling";
|
||||
import { defersMedia } from "./timedClipHide";
|
||||
import { capturePageIn, inPlayerFrame, servedToStudio } from "../studioPreviewMark";
|
||||
import { swallow } from "./diagnostics";
|
||||
import { runtimeLoad } from "./runtimeLoad";
|
||||
import { isChromium, isWebKit, mediaElementTime } from "./mediaClock";
|
||||
import { setRuntimePreload } from "./runtimeAttributes";
|
||||
|
||||
const MEDIA_EDGE_SECONDS = 0.1;
|
||||
|
||||
type PreloadableMedia = Pick<
|
||||
HTMLMediaElement,
|
||||
"id" | "tagName" | "getAttribute" | "preload" | "readyState" | "networkState" | "load"
|
||||
| "id"
|
||||
| "tagName"
|
||||
| "getAttribute"
|
||||
| "querySelectorAll"
|
||||
| "preload"
|
||||
| "readyState"
|
||||
| "networkState"
|
||||
| "error"
|
||||
| "load"
|
||||
>;
|
||||
|
||||
type Loaded = { list: string; preload: "auto" | "metadata" };
|
||||
const loadedFor = new WeakMap<object, Loaded>();
|
||||
const sourceList = (media: PreloadableMedia) =>
|
||||
[
|
||||
media.getAttribute("src"),
|
||||
...[...media.querySelectorAll("source")].map((el) => el.getAttribute("src")),
|
||||
].join(" ");
|
||||
|
||||
function loadOncePerList(media: PreloadableMedia, preload: Loaded["preload"]): void {
|
||||
const list = sourceList(media);
|
||||
const last = loadedFor.get(media);
|
||||
const ended = media.error !== null || media.networkState === 3;
|
||||
const covered = last?.list === list && (last.preload === "auto" || preload === "metadata");
|
||||
if (covered && !ended) return;
|
||||
loadedFor.set(media, { list, preload });
|
||||
runtimeLoad(media);
|
||||
}
|
||||
|
||||
export function isRenderFrameVideo(
|
||||
media: Pick<Element, "getAttribute" | "id" | "tagName">,
|
||||
): boolean {
|
||||
@@ -31,17 +59,17 @@ export function isRenderFrameVideo(
|
||||
|
||||
export function preloadMedia(media: PreloadableMedia): void {
|
||||
if (isRenderFrameVideo(media)) return;
|
||||
if (media.preload !== "auto") media.preload = "auto";
|
||||
if (media.preload !== "auto") setRuntimePreload(media, "auto");
|
||||
// load() resets an in-flight video fetch, discarding its selected resource and buffered data.
|
||||
const videoAlreadyLoading = media.tagName === "VIDEO" && media.networkState === 2;
|
||||
if (media.readyState < 3 && !videoAlreadyLoading) media.load();
|
||||
if (media.readyState < 3 && !videoAlreadyLoading) loadOncePerList(media, "auto");
|
||||
}
|
||||
|
||||
export function prefetchMedia(media: PreloadableMedia): void {
|
||||
if (!isChromium()) return preloadMedia(media);
|
||||
if (isRenderFrameVideo(media)) return;
|
||||
if (media.preload !== "metadata") media.preload = "metadata";
|
||||
if (media.readyState === 0 && media.networkState !== 2) media.load();
|
||||
if (media.preload !== "metadata") setRuntimePreload(media, "metadata");
|
||||
if (media.readyState === 0 && media.networkState !== 2) loadOncePerList(media, "metadata");
|
||||
}
|
||||
|
||||
const pendingPlaybackStart = new WeakMap<HTMLMediaElement, () => void>();
|
||||
@@ -86,9 +114,10 @@ export function prepareUpcomingMedia(media: HTMLMediaElement, isUpcoming: () =>
|
||||
/** Ends a fetch in flight for good, which preload none alone does not. */
|
||||
export function stopMediaDownload(media: HTMLMediaElement): void {
|
||||
cancelPlaybackStart(media);
|
||||
loadedFor.delete(media);
|
||||
for (const source of media.querySelectorAll("source")) source.remove();
|
||||
media.removeAttribute("src");
|
||||
media.load();
|
||||
runtimeLoad(media);
|
||||
}
|
||||
|
||||
function wholeFileBuffered(media: HTMLMediaElement): boolean {
|
||||
@@ -112,6 +141,7 @@ export function releaseMedia(media: HTMLMediaElement, whenBuffered = false): voi
|
||||
return;
|
||||
}
|
||||
cancelPlaybackStart(media);
|
||||
loadedFor.delete(media);
|
||||
media.removeAttribute("src");
|
||||
media.setAttribute("src", src);
|
||||
}
|
||||
@@ -233,8 +263,8 @@ export function deferMediaUntilDue(): void {
|
||||
const media = el as HTMLMediaElement;
|
||||
const authoredPreload = media.preload;
|
||||
const later = startInFilm(el) > 0;
|
||||
if (later) media.preload = "none";
|
||||
const restore = () => (media.preload = authoredPreload);
|
||||
if (later) setRuntimePreload(media, "none");
|
||||
const restore = () => setRuntimePreload(media, authoredPreload);
|
||||
openLongSourceAtInPoint(media, later, restore, later && parsedEarly ? restore : undefined);
|
||||
};
|
||||
win.__hfMediaDeferral = new MutationObserver((records) => {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
const addedByRuntime = new WeakMap<object, Set<string>>();
|
||||
|
||||
export function recordRuntimeAttribute(el: object, name: string): void {
|
||||
const names = addedByRuntime.get(el) ?? new Set<string>();
|
||||
names.add(name);
|
||||
addedByRuntime.set(el, names);
|
||||
}
|
||||
|
||||
export function forgetRuntimeAttribute(el: Element, name: string): boolean {
|
||||
return addedByRuntime.get(el)?.delete(name) === true;
|
||||
}
|
||||
|
||||
export function isRuntimeAttribute(el: Element, name: string): boolean {
|
||||
return addedByRuntime.get(el)?.has(name) === true;
|
||||
}
|
||||
|
||||
export function setRuntimePreload(
|
||||
media: Pick<HTMLMediaElement, "preload"> & Partial<Pick<Element, "hasAttribute">>,
|
||||
value: HTMLMediaElement["preload"],
|
||||
): void {
|
||||
if (media.hasAttribute?.("preload") === false) recordRuntimeAttribute(media, "preload");
|
||||
media.preload = value;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
let loading: object | null = null;
|
||||
|
||||
/** Every load() the runtime makes goes through here, so the sealed CORS handling can tell it from the composition's. */
|
||||
export function runtimeLoad(media: Pick<HTMLMediaElement, "load">): void {
|
||||
const outer = loading;
|
||||
loading = media;
|
||||
try {
|
||||
media.load();
|
||||
} finally {
|
||||
loading = outer;
|
||||
}
|
||||
}
|
||||
|
||||
export const loadedByRuntime = (media: object): boolean => loading === media;
|
||||
@@ -1,4 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { preloadMedia } from "./preloadMedia";
|
||||
import { corsForSealedMedia } from "./sealedMediaCors";
|
||||
|
||||
const PREVIEW = "http://localhost:4817/api/projects/demo/preview/~token/";
|
||||
@@ -6,6 +7,13 @@ let observer: MutationObserver | null = null;
|
||||
|
||||
// MutationObserver callbacks run as a microtask after the insertion.
|
||||
const settled = () => Promise.resolve();
|
||||
const answered = () => new Promise<void>((resolve) => setTimeout(resolve));
|
||||
|
||||
/** The first frame of a load, of `url`: what makes a no-CORS fallback count as having played. */
|
||||
function playsFrom(media: HTMLMediaElement, url: string) {
|
||||
Object.defineProperty(media, "currentSrc", { value: url, configurable: true });
|
||||
media.dispatchEvent(new Event("loadeddata"));
|
||||
}
|
||||
|
||||
function add(html: string): Element {
|
||||
const host = document.createElement("div");
|
||||
@@ -17,9 +25,11 @@ function add(html: string): Element {
|
||||
beforeEach(() => {
|
||||
document.head.innerHTML = `<base href="${PREVIEW}">`;
|
||||
document.body.innerHTML = "";
|
||||
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch")));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
afterEach(async () => {
|
||||
await answered();
|
||||
observer?.disconnect();
|
||||
observer = null;
|
||||
vi.unstubAllGlobals();
|
||||
@@ -44,7 +54,7 @@ describe("corsForSealedMedia", () => {
|
||||
observer = corsForSealedMedia();
|
||||
const host = add(
|
||||
`<video src="https://cdn.example.com/clip.mp4"></video>` +
|
||||
`<video><source src="media/a.mp4"><source src="https://cdn.example.com/a.webm"></video>`,
|
||||
`<video><source src="https://cdn.example.com/a.webm"><source src="media/a.mp4"></video>`,
|
||||
);
|
||||
await settled();
|
||||
expect([...host.querySelectorAll("video")].map((el) => el.hasAttribute("crossorigin"))).toEqual(
|
||||
@@ -104,6 +114,388 @@ describe("corsForSealedMedia", () => {
|
||||
);
|
||||
});
|
||||
|
||||
// fails without the fix: a host with no CORS headers failed every opted-in video, and nothing loaded it again.
|
||||
it("loads a video again once without crossorigin when its CORS load fails, and says so once it plays", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(`<video src="media/plain-host.mp4"></video>`).querySelector("video")!;
|
||||
await settled();
|
||||
const load = vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
expect(video.getAttribute("crossorigin")).toBe("anonymous");
|
||||
|
||||
video.dispatchEvent(new Event("error"));
|
||||
expect(video.hasAttribute("crossorigin")).toBe(false);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
playsFrom(video, `${PREVIEW}media/plain-host.mp4`);
|
||||
await answered();
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
expect(warn.mock.calls[0]![0]).toContain(`${PREVIEW}media/plain-host.mp4`);
|
||||
|
||||
video.dispatchEvent(new Event("error"));
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it("keeps a refusal to the element it happened on", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
observer = corsForSealedMedia();
|
||||
const first = add(`<video src="media/refused.mp4"></video>`).querySelector("video")!;
|
||||
await settled();
|
||||
vi.spyOn(first, "load").mockImplementation(() => {});
|
||||
first.dispatchEvent(new Event("error"));
|
||||
playsFrom(first, `${PREVIEW}media/refused.mp4`);
|
||||
await answered();
|
||||
|
||||
const second = add(`<video src="media/refused.mp4"></video>`).querySelector("video")!;
|
||||
first.src = `${PREVIEW}media/refused.mp4`;
|
||||
await settled();
|
||||
expect(second.getAttribute("crossorigin")).toBe("anonymous");
|
||||
expect(first.hasAttribute("crossorigin")).toBe(false);
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it("drops CORS at once when a source fails with it, so the browser picks again as without it, and leaves other elements alone", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
observer = corsForSealedMedia();
|
||||
const host = add(
|
||||
`<video><source src="media/gone.mp4"><source src="media/healthy.mp4"></video>`,
|
||||
);
|
||||
await settled();
|
||||
const video = host.querySelector("video")!;
|
||||
const load = vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
video.querySelector("source")!.dispatchEvent(new Event("error"));
|
||||
expect([video.hasAttribute("crossorigin"), load.mock.calls.length]).toEqual([false, 1]);
|
||||
const later = add(`<video src="media/healthy.mp4"></video>`).querySelector("video")!;
|
||||
await settled();
|
||||
expect(later.getAttribute("crossorigin")).toBe("anonymous");
|
||||
});
|
||||
it("plays a source that refused CORS without it, says so once, and opts nothing back in for it", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
observer = corsForSealedMedia();
|
||||
const host = add(
|
||||
`<video><source src="media/no-cors-a.mp4"><source src="media/no-cors-b.mp4"></video>`,
|
||||
);
|
||||
await settled();
|
||||
const video = host.querySelector("video")!;
|
||||
const load = vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
video.querySelector("source")!.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/no-cors-a.mp4`);
|
||||
await answered();
|
||||
playsFrom(video, `${PREVIEW}media/no-cors-a.mp4`);
|
||||
expect([video.hasAttribute("crossorigin"), load.mock.calls.length]).toEqual([false, 1]);
|
||||
expect(warn.mock.calls.map(([line]) => String(line).split(" ")[1])).toEqual([
|
||||
`${PREVIEW}media/no-cors-a.mp4`,
|
||||
]);
|
||||
warn.mockRestore();
|
||||
});
|
||||
it("opts a source back in once its host answers CORS after a failed CORS load, and asks that host once", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const fetch = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
observer = corsForSealedMedia();
|
||||
const host = add(`<video src="media/blip.mp4"></video>`);
|
||||
await settled();
|
||||
const video = host.querySelector("video")!;
|
||||
const load = vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
video.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/blip.mp4`);
|
||||
await answered();
|
||||
expect(video.getAttribute("crossorigin")).toBe("anonymous");
|
||||
video.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/blip.mp4`);
|
||||
await settled();
|
||||
expect([fetch.mock.calls, video.hasAttribute("crossorigin"), load.mock.calls.length]).toEqual([
|
||||
[
|
||||
[
|
||||
`${PREVIEW}media/blip.mp4`,
|
||||
{ method: "HEAD", mode: "cors", cache: "no-store", redirect: "error" },
|
||||
],
|
||||
],
|
||||
false,
|
||||
3,
|
||||
]);
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
warn.mockRestore();
|
||||
});
|
||||
it("says nothing while its CORS question is still out, and opts back in when the host answers", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
let answer!: (response: Response) => void;
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(() => new Promise<Response>((resolve) => (answer = resolve))),
|
||||
);
|
||||
observer = corsForSealedMedia();
|
||||
const host = add(`<video src="media/slow.mp4"></video>`);
|
||||
await settled();
|
||||
const video = host.querySelector("video")!;
|
||||
vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
video.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/slow.mp4`);
|
||||
playsFrom(video, `${PREVIEW}media/slow.mp4`);
|
||||
await answered();
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
answer(new Response(null, { status: 200 }));
|
||||
await answered();
|
||||
expect([warn.mock.calls.length, video.getAttribute("crossorigin")]).toEqual([0, "anonymous"]);
|
||||
warn.mockRestore();
|
||||
});
|
||||
it("keeps a source without CORS when its host refuses the CORS question too", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
observer = corsForSealedMedia();
|
||||
const host = add(`<video src="media/no-cors.mp4"></video>`);
|
||||
await settled();
|
||||
const video = host.querySelector("video")!;
|
||||
const load = vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
video.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/no-cors.mp4`);
|
||||
await answered();
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
expect([video.hasAttribute("crossorigin"), load.mock.calls.length]).toEqual([false, 1]);
|
||||
warn.mockRestore();
|
||||
});
|
||||
it("takes back its own crossorigin when its src returns to a URL that refused CORS on it, and keeps an authored one", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
observer = corsForSealedMedia();
|
||||
const host = add(
|
||||
`<video src="media/refused-once.mp4"></video><video src="media/fine-b.mp4" crossorigin="anonymous"></video>`,
|
||||
);
|
||||
await settled();
|
||||
const [ours, authored] = host.querySelectorAll("video");
|
||||
vi.spyOn(ours!, "load").mockImplementation(() => {});
|
||||
ours!.dispatchEvent(new Event("error"));
|
||||
playsFrom(ours!, `${PREVIEW}media/refused-once.mp4`);
|
||||
ours!.src = "media/fine-a.mp4";
|
||||
await settled();
|
||||
expect(ours!.getAttribute("crossorigin")).toBe("anonymous");
|
||||
ours!.src = "media/refused-once.mp4";
|
||||
authored!.src = "media/refused-once.mp4";
|
||||
await settled();
|
||||
expect([ours!.hasAttribute("crossorigin"), authored!.getAttribute("crossorigin")]).toEqual([
|
||||
false,
|
||||
"anonymous",
|
||||
]);
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it("forgets a source that failed without CORS too, and opts back in once it plays", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(`<video src="media/down.mp4"></video>`).querySelector("video")!;
|
||||
await settled();
|
||||
const load = vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
video.dispatchEvent(new Event("error"));
|
||||
video.dispatchEvent(new Event("error"));
|
||||
expect([load.mock.calls.length, warn.mock.calls.length]).toEqual([1, 0]);
|
||||
expect(video.hasAttribute("crossorigin")).toBe(false);
|
||||
const fresh = add(`<video src="media/down.mp4"></video>`).querySelector("video")!;
|
||||
await settled();
|
||||
expect(fresh.getAttribute("crossorigin")).toBe("anonymous");
|
||||
|
||||
playsFrom(video, `${PREVIEW}media/down.mp4`);
|
||||
expect(video.getAttribute("crossorigin")).toBe("anonymous");
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it("loads nothing more while a host stays down both ways", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(`<video src="media/gone.mp4"></video>`).querySelector("video")!;
|
||||
await settled();
|
||||
const load = vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
for (let selection = 0; selection < 4; selection++) video.dispatchEvent(new Event("error"));
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("opts back in for an own source played without CORS behind a host that is down, and drops it again if it refuses", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(
|
||||
`<video><source src="media/down.mp4"><source src="media/own.mp4"></video>`,
|
||||
).querySelector("video")!;
|
||||
await settled();
|
||||
const load = vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
const [down, own] = video.querySelectorAll("source");
|
||||
down!.dispatchEvent(new Event("error"));
|
||||
down!.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
expect([video.getAttribute("crossorigin"), load.mock.calls.length]).toEqual(["anonymous", 2]);
|
||||
down!.dispatchEvent(new Event("error"));
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
own!.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
expect([video.hasAttribute("crossorigin"), load.mock.calls.length]).toEqual([false, 3]);
|
||||
});
|
||||
|
||||
it("loads a list naming another host as written, and keeps it so while the other host's source plays", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(
|
||||
`<video><source src="https://cdn.example.com/x.webm"><source src="media/own.mp4"></video>`,
|
||||
).querySelector("video")!;
|
||||
await settled();
|
||||
expect(video.hasAttribute("crossorigin")).toBe(false);
|
||||
const load = vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
playsFrom(video, "https://cdn.example.com/x.webm");
|
||||
expect([video.hasAttribute("crossorigin"), load.mock.calls.length]).toEqual([false, 0]);
|
||||
});
|
||||
|
||||
it("opts in an own source that plays first in a list naming another host", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(
|
||||
`<video><source src="media/own.mp4"><source src="https://cdn.example.com/x.webm"></video>`,
|
||||
).querySelector("video")!;
|
||||
await settled();
|
||||
const load = vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
expect([video.getAttribute("crossorigin"), load.mock.calls.length]).toEqual(["anonymous", 1]);
|
||||
});
|
||||
|
||||
it("opts in an own source reached after another host's failed, and keeps that source through the reload", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(
|
||||
`<video><source src="https://cdn.example.com/x.webm"><source src="media/own.mp4"></video>`,
|
||||
).querySelector("video")!;
|
||||
await settled();
|
||||
const load = vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
const [foreign] = video.querySelectorAll("source");
|
||||
foreign!.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
expect([video.getAttribute("crossorigin"), load.mock.calls.length]).toEqual(["anonymous", 1]);
|
||||
expect(foreign!.hasAttribute("type")).toBe(true);
|
||||
foreign!.dispatchEvent(new Event("error"));
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
expect([foreign!.hasAttribute("type"), video.getAttribute("crossorigin")]).toEqual([
|
||||
false,
|
||||
"anonymous",
|
||||
]);
|
||||
});
|
||||
it("keeps a type the composition writes on a source sitting out a reload", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(
|
||||
`<video><source src="https://cdn.example.com/x.webm"><source src="media/own.mp4"></video>`,
|
||||
).querySelector("video")!;
|
||||
await settled();
|
||||
vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
const [foreign] = video.querySelectorAll("source");
|
||||
foreign!.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
foreign!.setAttribute("type", "video/webm");
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
expect(foreign!.getAttribute("type")).toBe("video/webm");
|
||||
});
|
||||
|
||||
it("pins out every source ahead of the one playing, past a skipped copy of its URL", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(
|
||||
`<video><source src="media/own.mp4" type="video/x-unplayable"><source src="https://cdn.example.com/x.webm"><source src="media/own.mp4"></video>`,
|
||||
).querySelector("video")!;
|
||||
await settled();
|
||||
vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
const foreign = video.querySelectorAll("source")[1]!;
|
||||
foreign.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
expect([video.getAttribute("crossorigin"), foreign.hasAttribute("type")]).toEqual([
|
||||
"anonymous",
|
||||
true,
|
||||
]);
|
||||
});
|
||||
|
||||
it("pins out a failed copy of the playing URL and a foreign source after it", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(
|
||||
`<video><source src="media/own.mp4"><source src="https://cdn.example.com/x.webm"><source src="media/own.mp4"></video>`,
|
||||
).querySelector("video")!;
|
||||
await settled();
|
||||
vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
video.dispatchEvent(new Event("loadstart"));
|
||||
const [first, foreign, last] = video.querySelectorAll("source");
|
||||
first!.dispatchEvent(new Event("error"));
|
||||
foreign!.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
expect([first, foreign, last].map((el) => el!.hasAttribute("type"))).toEqual([
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
]);
|
||||
});
|
||||
|
||||
it("follows the first source the browser would pick when the list changes", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(`<video><source src="media/a.mp4"></video>`).querySelector("video")!;
|
||||
await settled();
|
||||
vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
video.querySelector("source")!.dispatchEvent(new Event("error"));
|
||||
const source = (src: string) => Object.assign(document.createElement("source"), { src });
|
||||
video.append(source("media/b.mp4"));
|
||||
await settled();
|
||||
expect(video.hasAttribute("crossorigin")).toBe(false);
|
||||
video.prepend(source("media/c.mp4"));
|
||||
await settled();
|
||||
expect(video.getAttribute("crossorigin")).toBe("anonymous");
|
||||
});
|
||||
|
||||
it("keeps the playhead, rate and play state across its own load", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
const play = vi.spyOn(HTMLMediaElement.prototype, "play").mockResolvedValue(undefined);
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(`<video><source src="media/a.mp4"></video>`).querySelector("video")!;
|
||||
await settled();
|
||||
video.currentTime = 2;
|
||||
video.playbackRate = 1.5;
|
||||
Object.defineProperty(video, "paused", { configurable: true, value: false });
|
||||
vi.spyOn(video, "load").mockImplementation(() => {
|
||||
video.currentTime = 0;
|
||||
video.playbackRate = 1;
|
||||
});
|
||||
video.querySelector("source")!.dispatchEvent(new Event("error"));
|
||||
expect(video.currentTime).toBeCloseTo(2, 4);
|
||||
expect([video.playbackRate, play.mock.calls.length]).toEqual([1.5, 1]);
|
||||
});
|
||||
it("keeps a crossorigin the composition sets on media that was there when it started", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
const video = add(`<video src="media/clip.mp4"></video>`).querySelector("video")!;
|
||||
observer = corsForSealedMedia();
|
||||
expect(video.getAttribute("crossorigin")).toBe("anonymous");
|
||||
await settled();
|
||||
video.setAttribute("crossorigin", "use-credentials");
|
||||
await settled();
|
||||
video.setAttribute("src", "https://cdn.example.com/clip.mp4");
|
||||
await settled();
|
||||
expect(video.getAttribute("crossorigin")).toBe("use-credentials");
|
||||
});
|
||||
|
||||
it("leaves an authored crossorigin and its errors alone", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
observer = corsForSealedMedia();
|
||||
const host = add(`<video crossorigin="use-credentials" src="media/own.mp4"></video>`);
|
||||
const video = host.querySelector("video")!;
|
||||
await settled();
|
||||
const load = vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
video.dispatchEvent(new Event("error"));
|
||||
expect(video.getAttribute("crossorigin")).toBe("use-credentials");
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("changes nothing in a document with its own origin", async () => {
|
||||
observer = corsForSealedMedia();
|
||||
const host = add(`<video src="media/clip.mp4"></video>`);
|
||||
@@ -111,4 +503,138 @@ describe("corsForSealedMedia", () => {
|
||||
expect(observer).toBeNull();
|
||||
expect(host.querySelector("video")!.hasAttribute("crossorigin")).toBe(false);
|
||||
});
|
||||
it("tries a down source again when the composition calls load(), and only then", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const load = vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(() => {});
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(
|
||||
`<video><source src="media/down.mp4"><source src="media/own.mp4"></video>`,
|
||||
).querySelector("video")!;
|
||||
await settled();
|
||||
const down = video.querySelector("source")!;
|
||||
down.dispatchEvent(new Event("error"));
|
||||
down.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
video.dispatchEvent(new Event("loadstart"));
|
||||
down.dispatchEvent(new Event("error"));
|
||||
expect([video.getAttribute("crossorigin"), load.mock.calls.length]).toEqual(["anonymous", 2]);
|
||||
video.load();
|
||||
down.dispatchEvent(new Event("error"));
|
||||
expect([video.hasAttribute("crossorigin"), load.mock.calls.length]).toEqual([false, 4]);
|
||||
});
|
||||
|
||||
// fails without the fix: the runtime's preload load() 2 ms after our reload cleared the mark, costing two loads.
|
||||
it("keeps a down mark through a load() made before our reload's selection starts", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const load = vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(() => {});
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(
|
||||
`<video><source src="media/down.mp4"><source src="media/own.mp4"></video>`,
|
||||
).querySelector("video")!;
|
||||
await settled();
|
||||
const down = video.querySelector("source")!;
|
||||
down.dispatchEvent(new Event("error"));
|
||||
down.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
preloadMedia(video);
|
||||
video.dispatchEvent(new Event("loadstart"));
|
||||
down.dispatchEvent(new Event("error"));
|
||||
expect([video.getAttribute("crossorigin"), load.mock.calls.length]).toEqual(["anonymous", 3]);
|
||||
});
|
||||
|
||||
// fails without the fix: the runtime's binding preload mid-selection cleared the mark; the clip loaded twice more.
|
||||
it("keeps a down mark through the runtime's preload in the middle of a selection", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const load = vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(() => {});
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(
|
||||
`<video><source src="media/down.mp4"><source src="media/own.mp4"></video>`,
|
||||
).querySelector("video")!;
|
||||
await settled();
|
||||
const down = video.querySelector("source")!;
|
||||
down.dispatchEvent(new Event("error"));
|
||||
down.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
video.dispatchEvent(new Event("loadstart"));
|
||||
down.dispatchEvent(new Event("error"));
|
||||
preloadMedia(video);
|
||||
video.dispatchEvent(new Event("loadstart"));
|
||||
down.dispatchEvent(new Event("error"));
|
||||
expect([video.getAttribute("crossorigin"), load.mock.calls.length]).toEqual(["anonymous", 3]);
|
||||
});
|
||||
|
||||
it("tries a down source again when the composition calls load() after the runtime's preload", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const load = vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(() => {});
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(
|
||||
`<video><source src="media/down.mp4"><source src="media/own.mp4"></video>`,
|
||||
).querySelector("video")!;
|
||||
await settled();
|
||||
const down = video.querySelector("source")!;
|
||||
down.dispatchEvent(new Event("error"));
|
||||
down.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
video.dispatchEvent(new Event("loadstart"));
|
||||
preloadMedia(video);
|
||||
video.load();
|
||||
video.dispatchEvent(new Event("loadstart"));
|
||||
down.dispatchEvent(new Event("error"));
|
||||
expect([video.hasAttribute("crossorigin"), load.mock.calls.length]).toEqual([false, 5]);
|
||||
});
|
||||
|
||||
// fails if every load() before loadstart joined our selection: the author's swapped sources kept the old mark.
|
||||
it("counts a load() after the author swaps sources before loadstart as a new attempt", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const load = vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(() => {});
|
||||
observer = corsForSealedMedia();
|
||||
const video = add(
|
||||
`<video><source src="media/down.mp4"><source src="media/own.mp4"></video>`,
|
||||
).querySelector("video")!;
|
||||
await settled();
|
||||
const [first, second] = [...video.querySelectorAll("source")];
|
||||
first!.dispatchEvent(new Event("error"));
|
||||
first!.dispatchEvent(new Event("error"));
|
||||
playsFrom(video, `${PREVIEW}media/own.mp4`);
|
||||
first!.setAttribute("src", "media/own.mp4");
|
||||
second!.setAttribute("src", "media/down.mp4");
|
||||
await settled();
|
||||
video.load();
|
||||
video.dispatchEvent(new Event("loadstart"));
|
||||
second!.dispatchEvent(new Event("error"));
|
||||
expect([video.hasAttribute("crossorigin"), load.mock.calls.length]).toEqual([false, 4]);
|
||||
});
|
||||
|
||||
it("settles the composition's play() with the playback its load retried", async () => {
|
||||
vi.stubGlobal("origin", "null");
|
||||
const play = vi
|
||||
.spyOn(HTMLMediaElement.prototype, "play")
|
||||
.mockResolvedValue(undefined)
|
||||
.mockImplementationOnce(() => Promise.reject(new DOMException("load()", "AbortError")))
|
||||
.mockImplementationOnce(() => Promise.resolve())
|
||||
.mockImplementationOnce(() => Promise.reject(new DOMException("load()", "AbortError")))
|
||||
.mockImplementationOnce(() => Promise.reject(new DOMException("none", "NotSupportedError")));
|
||||
observer = corsForSealedMedia();
|
||||
const [first, second] = [0, 1].map(
|
||||
() => add(`<video><source src="media/a.mp4"></video>`).querySelector("video")!,
|
||||
);
|
||||
await settled();
|
||||
const outcomes = [first!, second!].map((video) => {
|
||||
vi.spyOn(video, "load").mockImplementation(() => {});
|
||||
Object.defineProperty(video, "paused", { configurable: true, value: false });
|
||||
const outcome = video.play().then(
|
||||
() => "resolved",
|
||||
(error: DOMException) => error.name,
|
||||
);
|
||||
video.querySelector("source")!.dispatchEvent(new Event("error"));
|
||||
return outcome;
|
||||
});
|
||||
expect(await Promise.all(outcomes)).toEqual(["resolved", "NotSupportedError"]);
|
||||
expect(play).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import { mediaElementTime } from "./mediaClock";
|
||||
import { forgetRuntimeAttribute, recordRuntimeAttribute } from "./runtimeAttributes";
|
||||
import { loadedByRuntime, runtimeLoad } from "./runtimeLoad";
|
||||
|
||||
// A sealed preview's document has an opaque origin, so its own server's media is cross-origin to it. Without
|
||||
// `crossorigin` the browser loads that media in no-cors mode: WebGL and canvases refuse its frames, Web Audio treats it
|
||||
// as foreign. The preview server answers CORS loads from an opaque origin, so its own media opts in; other hosts don't.
|
||||
@@ -5,14 +9,6 @@
|
||||
const isMedia = (el: Element): el is HTMLMediaElement =>
|
||||
el.localName === "video" || el.localName === "audio";
|
||||
|
||||
function servedHere(media: HTMLMediaElement, home: string): boolean {
|
||||
const urls = [media, ...media.querySelectorAll("source")]
|
||||
.map((el) => el.getAttribute("src"))
|
||||
.filter((src): src is string => Boolean(src));
|
||||
const own = originOf(home, home);
|
||||
return urls.length > 0 && urls.every((src) => originOf(src, home) === own);
|
||||
}
|
||||
|
||||
function originOf(url: string, base: string): string | null {
|
||||
try {
|
||||
return new URL(url, base).origin;
|
||||
@@ -21,26 +17,275 @@ function originOf(url: string, base: string): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
// Only a crossorigin added here is taken back when a src moves to a host that may not answer CORS.
|
||||
const optedIn = new WeakSet<HTMLMediaElement>();
|
||||
const resolved = (src: string, home: string) => {
|
||||
try {
|
||||
return new URL(src, home).href;
|
||||
} catch {
|
||||
return src;
|
||||
}
|
||||
};
|
||||
|
||||
function sync(media: HTMLMediaElement, home: string): void {
|
||||
const own = servedHere(media, home);
|
||||
if (own && !media.hasAttribute("crossorigin")) {
|
||||
media.setAttribute("crossorigin", "anonymous");
|
||||
optedIn.add(media);
|
||||
} else if (!own && optedIn.delete(media)) {
|
||||
// Per element, never shared: a source that refused CORS here, and one that failed both ways, its host down.
|
||||
const refused = new WeakMap<HTMLMediaElement, Set<string>>();
|
||||
const down = new WeakMap<HTMLMediaElement, Set<string>>();
|
||||
const warned = new WeakMap<HTMLMediaElement, Set<string>>();
|
||||
const seen = new WeakSet<HTMLMediaElement>();
|
||||
// A crossorigin change we did not write, even to our own value, makes the attribute the composition's for good.
|
||||
const authored = new WeakSet<HTMLMediaElement>();
|
||||
const pendingWrites = new WeakMap<HTMLMediaElement, number>();
|
||||
const pendingPlays = new WeakMap<HTMLMediaElement, Set<object>>();
|
||||
const retryOf = new WeakMap<object, Promise<void>>();
|
||||
let nativePlay: HTMLMediaElement["play"];
|
||||
let nativeLoad: HTMLMediaElement["load"];
|
||||
|
||||
function setOf<T>(map: WeakMap<HTMLMediaElement, Set<T>>, media: HTMLMediaElement): Set<T> {
|
||||
let set = map.get(media);
|
||||
if (!set) map.set(media, (set = new Set()));
|
||||
return set;
|
||||
}
|
||||
|
||||
const has = (map: WeakMap<HTMLMediaElement, Set<string>>, media: HTMLMediaElement, url: string) =>
|
||||
map.get(media)?.has(url) ?? false;
|
||||
|
||||
function candidate(media: HTMLMediaElement, el: HTMLSourceElement, home: string): string | null {
|
||||
const src = el.getAttribute("src");
|
||||
const type = el.getAttribute("type");
|
||||
const query = el.getAttribute("media");
|
||||
const playable = !type || (type !== PINNED_OUT && media.canPlayType(type));
|
||||
if (!src || !playable || (query && !matchMedia(query).matches)) return null;
|
||||
return resolved(src, home);
|
||||
}
|
||||
|
||||
function selectable(media: HTMLMediaElement, home: string): string[] {
|
||||
const own = media.getAttribute("src");
|
||||
if (media.hasAttribute("src")) return own ? [resolved(own, home)] : [];
|
||||
return [...media.querySelectorAll("source")].flatMap((el) => candidate(media, el, home) ?? []);
|
||||
}
|
||||
|
||||
const isHome = (url: string, home: string) => originOf(url, home) === originOf(home, home);
|
||||
// As unsealed Studio reads pixels: only the preview's own host; a list naming another host loads as written first.
|
||||
const allHome = (urls: string[], home: string) =>
|
||||
urls.length > 0 && urls.every((url) => isHome(url, home));
|
||||
|
||||
function write(media: HTMLMediaElement, value: string | null): void {
|
||||
pendingWrites.set(media, (pendingWrites.get(media) ?? 0) + 1);
|
||||
if (value === null) {
|
||||
media.removeAttribute("crossorigin");
|
||||
forgetRuntimeAttribute(media, "crossorigin");
|
||||
} else {
|
||||
media.setAttribute("crossorigin", value);
|
||||
recordRuntimeAttribute(media, "crossorigin");
|
||||
}
|
||||
}
|
||||
|
||||
// The parser can add a <source> after its media element, and a script can change either's src.
|
||||
function crossOriginChanged(media: HTMLMediaElement): void {
|
||||
const pending = pendingWrites.get(media) ?? 0;
|
||||
if (pending > 0) pendingWrites.set(media, pending - 1);
|
||||
else {
|
||||
authored.add(media);
|
||||
forgetRuntimeAttribute(media, "crossorigin");
|
||||
}
|
||||
}
|
||||
|
||||
function setCors(media: HTMLMediaElement, want: boolean): void {
|
||||
if (want !== media.hasAttribute("crossorigin")) write(media, want ? "anonymous" : null);
|
||||
}
|
||||
|
||||
function sync(media: HTMLMediaElement, home: string): void {
|
||||
if (!seen.has(media)) {
|
||||
seen.add(media);
|
||||
if (media.hasAttribute("crossorigin")) authored.add(media);
|
||||
}
|
||||
if (authored.has(media)) return;
|
||||
const urls = selectable(media, home);
|
||||
setCors(media, allHome(urls, home) && !has(refused, media, urls[0]!));
|
||||
}
|
||||
|
||||
// load() resets the playhead, rate and play state; set in the same task, a later change by the composition wins.
|
||||
function reload(media: HTMLMediaElement): void {
|
||||
const { currentTime, playbackRate, paused } = media;
|
||||
runtimeLoad(media);
|
||||
if (currentTime) media.currentTime = mediaElementTime(currentTime);
|
||||
media.playbackRate = playbackRate;
|
||||
if (paused) return;
|
||||
const retry = nativePlay.call(media);
|
||||
retry.catch(() => undefined);
|
||||
for (const play of pendingPlays.get(media) ?? []) retryOf.set(play, retry);
|
||||
}
|
||||
|
||||
// The composition's play() settles with the playback our load retried, as it would without us: load() rejects it.
|
||||
function play(this: HTMLMediaElement): Promise<void> {
|
||||
const token = {};
|
||||
const plays = setOf(pendingPlays, this);
|
||||
plays.add(token);
|
||||
const settle = (promise: Promise<void>): Promise<void> =>
|
||||
promise.catch((error: unknown) => {
|
||||
const retry = retryOf.get(token);
|
||||
retryOf.delete(token);
|
||||
if (retry) return settle(retry);
|
||||
throw error;
|
||||
});
|
||||
return settle(nativePlay.call(this)).finally(() => plays.delete(token));
|
||||
}
|
||||
|
||||
// Only the composition's own load() tries a down source again, as the browser would; the runtime's keep the mark.
|
||||
function load(this: HTMLMediaElement): void {
|
||||
if (!loadedByRuntime(this)) {
|
||||
down.delete(this);
|
||||
unpin(this);
|
||||
}
|
||||
nativeLoad.call(this);
|
||||
}
|
||||
|
||||
function mediaOf(el: Element): HTMLMediaElement | null {
|
||||
if (isMedia(el)) return el;
|
||||
const parent = el.localName === "source" ? el.parentElement : null;
|
||||
return parent && isMedia(parent) ? parent : null;
|
||||
}
|
||||
|
||||
function warnOnce(media: HTMLMediaElement, url: string): void {
|
||||
const said = setOf(warned, media);
|
||||
if (said.has(url)) return;
|
||||
said.add(url);
|
||||
console.warn(
|
||||
`[hyperframes] ${url} did not load with CORS, so it plays without: colour grading, canvas reads and ` +
|
||||
"audio effects are off for it. Serve it with Access-Control-Allow-Origin to keep them.",
|
||||
);
|
||||
}
|
||||
|
||||
function failedUrl(media: HTMLMediaElement, el: Element, home: string): string {
|
||||
const own = media.getAttribute("src");
|
||||
return el !== media
|
||||
? (el as HTMLSourceElement).src
|
||||
: own
|
||||
? resolved(own, home)
|
||||
: media.currentSrc;
|
||||
}
|
||||
|
||||
// Refused with CORS: drop it at once, so the browser picks as it would without us. Failed without too: host down.
|
||||
function failure(event: Event, home: string): { media: HTMLMediaElement; url: string } | null {
|
||||
const el = event.target as Element | null;
|
||||
const media = el?.nodeType === 1 ? mediaOf(el) : null;
|
||||
if (!el || !media || authored.has(media)) return null;
|
||||
const url = failedUrl(media, el, home);
|
||||
return url && selectable(media, home).includes(url) ? { media, url } : null;
|
||||
}
|
||||
|
||||
function wasDown(media: HTMLMediaElement, url: string): void {
|
||||
if (setOf(refused, media).delete(url)) setOf(down, media).add(url);
|
||||
}
|
||||
|
||||
const PINNED_OUT = "video/x-hyperframes-pinned-out";
|
||||
const pinned = new WeakMap<HTMLMediaElement, Array<[HTMLSourceElement, string | null]>>();
|
||||
const erredThisPick = new WeakMap<HTMLMediaElement, Set<Element>>();
|
||||
|
||||
function pinTo(media: HTMLMediaElement, keep: Element | null): void {
|
||||
if (!keep || keep === media) return;
|
||||
const held: Array<[HTMLSourceElement, string | null]> = [];
|
||||
for (const el of media.querySelectorAll("source")) {
|
||||
if (el === keep) break;
|
||||
held.push([el, el.getAttribute("type")]);
|
||||
el.setAttribute("type", PINNED_OUT);
|
||||
}
|
||||
if (held.length) pinned.set(media, held);
|
||||
}
|
||||
|
||||
function playingSource(media: HTMLMediaElement, chosen: string, home: string): Element | null {
|
||||
const erred = erredThisPick.get(media);
|
||||
return (
|
||||
[...media.querySelectorAll("source")].find(
|
||||
(el) => candidate(media, el, home) === chosen && !erred?.has(el),
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
function unpin(media: HTMLMediaElement): void {
|
||||
for (const [el, type] of pinned.get(media) ?? []) {
|
||||
if (el.getAttribute("type") !== PINNED_OUT) continue;
|
||||
if (type === null) el.removeAttribute("type");
|
||||
else el.setAttribute("type", type);
|
||||
}
|
||||
pinned.delete(media);
|
||||
}
|
||||
|
||||
function pinnedOutError(target: Element | null): boolean {
|
||||
const owner = target?.nodeType === 1 ? mediaOf(target) : null;
|
||||
if (!owner) return false;
|
||||
if (target !== owner) setOf(erredThisPick, owner).add(target!);
|
||||
if (pinned.get(owner)?.some(([el]) => el === target)) return true;
|
||||
unpin(owner);
|
||||
return false;
|
||||
}
|
||||
|
||||
function failed(event: Event, home: string): void {
|
||||
if (pinnedOutError(event.target as Element | null)) return;
|
||||
const found = failure(event, home);
|
||||
if (!found) return;
|
||||
const { media, url } = found;
|
||||
if (!media.hasAttribute("crossorigin")) return wasDown(media, url);
|
||||
if (has(down, media, url)) return;
|
||||
setOf(refused, media).add(url);
|
||||
write(media, null);
|
||||
pinTo(media, event.target as Element);
|
||||
reload(media);
|
||||
}
|
||||
|
||||
function optIn(media: HTMLMediaElement, chosen: string, home: string): void {
|
||||
write(media, "anonymous");
|
||||
pinTo(media, playingSource(media, chosen, home));
|
||||
reload(media);
|
||||
}
|
||||
|
||||
const probed = new WeakMap<HTMLMediaElement, Set<string>>();
|
||||
const probing = new WeakMap<HTMLMediaElement, Set<string>>();
|
||||
|
||||
function askHost(media: HTMLMediaElement, url: string, home: string): void {
|
||||
if (!isHome(url, home)) return warnOnce(media, url);
|
||||
const asked = setOf(probed, media);
|
||||
if (asked.has(url)) return has(probing, media, url) ? undefined : warnOnce(media, url);
|
||||
asked.add(url);
|
||||
setOf(probing, media).add(url);
|
||||
const answered = () => probing.get(media)?.delete(url);
|
||||
fetch(url, { method: "HEAD", mode: "cors", cache: "no-store", redirect: "error" }).then(
|
||||
(answer) => {
|
||||
answered();
|
||||
if (!answer.ok) return warnOnce(media, url);
|
||||
const still = media.currentSrc === url && !media.hasAttribute("crossorigin");
|
||||
if (!still || authored.has(media) || !selectable(media, home).includes(url)) return;
|
||||
setOf(refused, media).delete(url);
|
||||
optIn(media, url, home);
|
||||
},
|
||||
() => {
|
||||
answered();
|
||||
warnOnce(media, url);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Played without CORS from our own host: opt back in; refused here once, ask the host once if that was a refusal.
|
||||
function firstFrame(event: Event, home: string): void {
|
||||
const media = event.target as HTMLMediaElement;
|
||||
if (!isMedia(media) || authored.has(media)) return;
|
||||
unpin(media);
|
||||
const chosen = media.currentSrc;
|
||||
down.get(media)?.delete(chosen);
|
||||
if (media.hasAttribute("crossorigin")) return;
|
||||
if (has(refused, media, chosen)) return askHost(media, chosen, home);
|
||||
if (!isHome(chosen, home) || !selectable(media, home).includes(chosen)) return;
|
||||
optIn(media, chosen, home);
|
||||
}
|
||||
|
||||
// Chrome tries an exhausted element's sources again on a crossorigin write; only an insertion resumes it.
|
||||
const resumes = (media: HTMLMediaElement, record: MutationRecord) =>
|
||||
record.addedNodes.length > 0 || media.networkState !== HTMLMediaElement.NETWORK_NO_SOURCE;
|
||||
|
||||
function changed(record: MutationRecord, home: string): void {
|
||||
const target = record.target as Element;
|
||||
if (record.type === "attributes") return visit(target, home);
|
||||
if (isMedia(target) && resumes(target, record)) sync(target, home);
|
||||
record.addedNodes.forEach((node) => visit(node, home));
|
||||
}
|
||||
|
||||
function visit(node: Node, home: string): void {
|
||||
if (node.nodeType !== 1) return;
|
||||
const el = node as Element;
|
||||
@@ -49,7 +294,14 @@ function visit(node: Node, home: string): void {
|
||||
for (const inner of el.querySelectorAll("video, audio")) sync(inner as HTMLMediaElement, home);
|
||||
}
|
||||
|
||||
/** In a sealed document, opts the preview server's own media into CORS as it parses or changes src, before it loads. */
|
||||
let home = "";
|
||||
// One function each, so a second start adds no second listener.
|
||||
const onError = (event: Event) => failed(event, home);
|
||||
const onFirstFrame = (event: Event) => firstFrame(event, home);
|
||||
const onPickStart = (event: Event) => erredThisPick.delete(event.target as HTMLMediaElement);
|
||||
|
||||
/** In a sealed document, opts the preview server's own media into CORS as it parses or changes src, before it loads;
|
||||
* a source that refuses CORS on an element plays there without it, after one more load. */
|
||||
export function corsForSealedMedia(): MutationObserver | null {
|
||||
if (
|
||||
typeof MutationObserver === "undefined" ||
|
||||
@@ -57,19 +309,29 @@ export function corsForSealedMedia(): MutationObserver | null {
|
||||
window.origin !== "null"
|
||||
)
|
||||
return null;
|
||||
const home = document.baseURI;
|
||||
visit(document.documentElement, home);
|
||||
home = document.baseURI;
|
||||
// Every crossorigin change in a batch is accounted for first, so an author's write beside a src change wins.
|
||||
const observer = new MutationObserver((records) => {
|
||||
for (const record of records) {
|
||||
if (record.type === "attributes") visit(record.target, home);
|
||||
else record.addedNodes.forEach((node) => visit(node, home));
|
||||
if (record.attributeName === "crossorigin" && isMedia(record.target as Element))
|
||||
crossOriginChanged(record.target as HTMLMediaElement);
|
||||
}
|
||||
for (const record of records) if (record.attributeName !== "crossorigin") changed(record, home);
|
||||
});
|
||||
// Observing first: the writes the first scan makes are counted against their own records.
|
||||
observer.observe(document.documentElement, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
attributeFilter: ["src"],
|
||||
attributeFilter: ["src", "crossorigin"],
|
||||
});
|
||||
visit(document.documentElement, home);
|
||||
// Media events do not bubble; capture listeners on the document hear every element's.
|
||||
document.addEventListener("error", onError, true);
|
||||
document.addEventListener("loadeddata", onFirstFrame, true);
|
||||
document.addEventListener("loadstart", onPickStart, true);
|
||||
const media = HTMLMediaElement.prototype;
|
||||
if (media.play !== play) [nativePlay, media.play] = [media.play, play];
|
||||
if (media.load !== load) [nativeLoad, media.load] = [media.load, load];
|
||||
return observer;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,10 @@ npm install @hyperframes/player
|
||||
Or load directly via CDN:
|
||||
|
||||
```html
|
||||
<script type="module" src="https://cdn.jsdelivr.net/npm/@hyperframes/player"></script>
|
||||
<script
|
||||
type="module"
|
||||
src="https://cdn.jsdelivr.net/npm/@hyperframes/player/dist/hyperframes-player.js"
|
||||
></script>
|
||||
```
|
||||
|
||||
If you need a classic `<script>` tag instead of ESM, use the explicit global build:
|
||||
@@ -207,6 +210,11 @@ composition because browser sandbox changes take effect only on navigation. Opaq
|
||||
parent DOM. Direct `contentDocument`, `__player`, and `__timelines` access is intentionally
|
||||
unavailable in that mode.
|
||||
|
||||
An opaque player adds the HyperFrames runtime itself, the version it was built with, so the embedder adds nothing. A composition from the embedding page's own site that brings the runtime loads by `src` as before. One without it is fetched and shown with the runtime inlined, so the frame loads nothing from another origin; inside it, `location` reads `about:srcdoc` while relative paths resolve against the composition's URL, and the embedding page's `script-src` policy applies to its scripts. A composition from another site loads as before and must include the runtime script.
|
||||
Hosting the player's script yourself, serve the runtime file from the package's `dist` folder beside it: an opaque player loads it from next to its own `<script>`. A bundler should use the ES module build, which carries the runtime as a chunk the bundler emits; under the CommonJS build the player cannot tell where it was loaded from, and a sealed player that needs the runtime reports that it failed to load.
|
||||
|
||||
An opaque composition loads the videos and audio served from its own host with CORS, so colour grading, canvas reads and audio effects can use them. Serve them with `Access-Control-Allow-Origin` (for example `*`). From a host that sends no CORS headers, each one plays anyway: it is loaded again once without CORS, those effects are off for it, and the console names it.
|
||||
|
||||
If you are building a trusted editor integration that needs direct access, use the `iframeElement` getter:
|
||||
|
||||
```js
|
||||
@@ -348,7 +356,7 @@ The `width` and `height` attributes define the composition's native resolution f
|
||||
|
||||
## How it works
|
||||
|
||||
The player renders compositions in a sandboxed `<iframe>` inside a Shadow DOM. It communicates with the HyperFrames runtime via `postMessage`. If the composition has GSAP timelines (`window.__timelines`) but no runtime, the player auto-injects it from CDN.
|
||||
The player renders compositions in a sandboxed `<iframe>` inside a Shadow DOM. It communicates with the HyperFrames runtime via `postMessage`. If the composition has GSAP timelines (`window.__timelines`) but no runtime, the player auto-injects it from CDN. An opaque player adds the runtime only to a composition from its own site that sets no security policy of its own; any other composition must load the runtime script itself, or the player fires `error` at the load limit with a message naming both fixes.
|
||||
|
||||
## Distribution
|
||||
|
||||
|
||||
@@ -32,6 +32,8 @@
|
||||
"typecheck": "tsc --noEmit && tsc --noEmit -p tests/perf/tsconfig.json && tsc --noEmit -p tests/playbench/tsconfig.json",
|
||||
"test": "vitest run",
|
||||
"test:browser-security": "bun run tests/browser/sandbox-origin.ts",
|
||||
"test:browser-sealed-media": "bun run tests/browser/sealed-media.ts && bun run tests/browser/sealed-media-table.ts",
|
||||
"test:browser-sealed-runtime": "bun run tests/browser/sealed-runtime.ts",
|
||||
"test:browser-raster": "bun run tests/browser/preview-raster-size.ts",
|
||||
"test:browser-box": "bun run tests/browser/player-box.ts",
|
||||
"test:browser-sealed-audio": "bun run tests/browser/sealed-audio.ts",
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
const root = join(import.meta.dirname, "..");
|
||||
const { version } = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
||||
@@ -22,4 +24,38 @@ for (const bundle of bundles) {
|
||||
}
|
||||
}
|
||||
|
||||
// A sealed player carries the runtime itself: the exact files the core it was built with emits.
|
||||
const coreDist = join(
|
||||
dirname(createRequire(import.meta.url).resolve("@hyperframes/core/package.json")),
|
||||
"dist",
|
||||
);
|
||||
const read = (path) => readFileSync(path, "utf8");
|
||||
if (
|
||||
read(join(root, "dist/hyperframe.runtime.iife.js")) !==
|
||||
read(join(coreDist, "hyperframe.runtime.iife.js"))
|
||||
) {
|
||||
throw new Error("dist/hyperframe.runtime.iife.js is not the runtime core built");
|
||||
}
|
||||
const esm = read(join(root, "dist/hyperframes-player.js"));
|
||||
if (!esm.includes('import("@hyperframes/core/runtime-script")')) {
|
||||
throw new Error("the ESM build does not leave the runtime to core's runtime-script export");
|
||||
}
|
||||
const built = (
|
||||
await import(pathToFileURL(join(coreDist, "generated/runtime-inline.js")).href)
|
||||
).getHyperframeRuntimeScript();
|
||||
// A run of the runtime's code that survives being embedded as a string: no quotes or backslashes.
|
||||
const marker = built.match(/[\w.(){};=,!&|+-]{80}/)?.[0];
|
||||
if (!marker || !read(join(coreDist, "generated/runtime-inline.js")).includes(marker)) {
|
||||
throw new Error("the inlined-runtime check would not see a runtime embedded in a bundle");
|
||||
}
|
||||
const shipped = readdirSync(join(root, "dist"), { recursive: true })
|
||||
.map(String)
|
||||
.filter((file) => file.endsWith(".js") || file.endsWith(".cjs"))
|
||||
.filter((file) => file !== "hyperframe.runtime.iife.js");
|
||||
for (const file of shipped) {
|
||||
if (read(join(root, "dist", file)).includes(marker)) {
|
||||
throw new Error(`dist/${file} carries the runtime; only dist/hyperframe.runtime.iife.js may`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Verified Player runtime injection is pinned to @hyperframes/core@${version}.`);
|
||||
|
||||
@@ -26,6 +26,15 @@ import {
|
||||
|
||||
import { RUNTIME_CDN_URL, runtimeCdnUrlForVersion } from "./runtime-url.js";
|
||||
|
||||
const SEALED_RUNTIME_HINT =
|
||||
". A sealed player adds the HyperFrames runtime only to a composition from its own site: " +
|
||||
"include the runtime script in a composition from another site, or play a composition you trust without sandbox-origin.";
|
||||
|
||||
export function timelineNotFound(limitMs: number, sealed: boolean): string {
|
||||
const message = `Composition timeline not found after ${limitMs / 1000}s`;
|
||||
return sealed ? message + SEALED_RUNTIME_HINT : message;
|
||||
}
|
||||
|
||||
export { runtimeCdnUrlForVersion };
|
||||
|
||||
export interface ProbeResult {
|
||||
@@ -42,6 +51,7 @@ export interface ProbeCallbacks {
|
||||
onRuntimeInjected?: () => void;
|
||||
resolveRuntimeUrl?: () => string;
|
||||
hostOwnsDeadline?: () => boolean;
|
||||
sealed?: () => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,6 +108,9 @@ export class CompositionProbe {
|
||||
private _limitMs = loadLimitMs();
|
||||
private _navigationPending = false;
|
||||
private _timedFromNavigation = false;
|
||||
private _preparationTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private _limitReportedBeforeLoad = false;
|
||||
private _preparedDocumentUnwritten = false;
|
||||
|
||||
get failed(): boolean {
|
||||
if (this._failure === null || this._failure.deadline) return false;
|
||||
@@ -115,10 +128,36 @@ export class CompositionProbe {
|
||||
this._limitMs = loadLimitMs();
|
||||
this._navigationPending = true;
|
||||
this._timedFromNavigation = true;
|
||||
this._endPreparation();
|
||||
}
|
||||
|
||||
markPreparation(): void {
|
||||
this.markNavigation();
|
||||
this._preparedDocumentUnwritten = true;
|
||||
this._preparationTimer = setTimeout(() => this._reportLimitBeforeLoad(), this._limitMs);
|
||||
}
|
||||
|
||||
frameWritten(): void {
|
||||
this._preparedDocumentUnwritten = false;
|
||||
}
|
||||
|
||||
endNavigation(): void {
|
||||
this._navigationPending = false;
|
||||
this._endPreparation();
|
||||
}
|
||||
|
||||
private _endPreparation(): void {
|
||||
if (this._preparationTimer !== null) clearTimeout(this._preparationTimer);
|
||||
this._preparationTimer = null;
|
||||
this._limitReportedBeforeLoad = false;
|
||||
this._preparedDocumentUnwritten = false;
|
||||
}
|
||||
|
||||
private _reportLimitBeforeLoad(): void {
|
||||
this._preparationTimer = null;
|
||||
if (!this._navigationPending || this._callbacks.hostOwnsDeadline?.()) return;
|
||||
this._limitReportedBeforeLoad = true;
|
||||
this._callbacks.onError(timelineNotFound(this._limitMs, this._callbacks.sealed?.() === true));
|
||||
}
|
||||
|
||||
get limitMs(): number {
|
||||
@@ -140,6 +179,7 @@ export class CompositionProbe {
|
||||
this.stop();
|
||||
this._failure = null;
|
||||
this._runtimeInjected = false;
|
||||
if (this._preparedDocumentUnwritten) return;
|
||||
if (!this._navigationPending) {
|
||||
this._startedAt = performance.now();
|
||||
this._limitMs = loadLimitMs();
|
||||
@@ -147,7 +187,8 @@ export class CompositionProbe {
|
||||
}
|
||||
this._navigationPending = false;
|
||||
let attempts = 0;
|
||||
let limitReached = false;
|
||||
let limitReached = this._limitReportedBeforeLoad;
|
||||
this._endPreparation();
|
||||
|
||||
const tick = () => {
|
||||
attempts++;
|
||||
@@ -183,7 +224,7 @@ export class CompositionProbe {
|
||||
if (this._interval) clearInterval(this._interval);
|
||||
this._interval = setInterval(tick, LATE_POLL_MS);
|
||||
this._failure = { document: this._iframe.contentDocument, deadline: true };
|
||||
this._callbacks.onError(`Composition timeline not found after ${this._limitMs / 1000}s`);
|
||||
this._callbacks.onError(timelineNotFound(this._limitMs, this._callbacks.sealed?.() === true));
|
||||
}
|
||||
|
||||
private _poll(attempts: number): ProbeOutcome {
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { CompositionProbe, loadLimitMs } from "./composition-probe.js";
|
||||
import { CompositionProbe, loadLimitMs, timelineNotFound } from "./composition-probe.js";
|
||||
import type { ProbeCallbacks } from "./composition-probe.js";
|
||||
|
||||
const LIMIT = loadLimitMs();
|
||||
const TIMED_OUT = `Composition timeline not found after ${LIMIT / 1000}s`;
|
||||
const TIMED_OUT = timelineNotFound(LIMIT, false);
|
||||
|
||||
function mount(markup: string, globals: Record<string, unknown> = {}) {
|
||||
function mount(
|
||||
markup: string,
|
||||
globals: Record<string, unknown> = {},
|
||||
callbacks: Partial<ProbeCallbacks> = {},
|
||||
) {
|
||||
const iframe = document.createElement("iframe");
|
||||
document.body.appendChild(iframe);
|
||||
iframe.contentDocument!.body.innerHTML = markup;
|
||||
Object.assign(iframe.contentWindow!, globals);
|
||||
const onReady = vi.fn();
|
||||
const onError = vi.fn();
|
||||
const probe = new CompositionProbe(iframe, { onReady, onError });
|
||||
const probe = new CompositionProbe(iframe, { onReady, onError, ...callbacks });
|
||||
probe.start();
|
||||
return { iframe, probe, onReady, onError };
|
||||
}
|
||||
@@ -126,6 +131,31 @@ describe("composition probe readiness", () => {
|
||||
vi.advanceTimersByTime(LIMIT);
|
||||
expect(onError).toHaveBeenCalledOnce();
|
||||
});
|
||||
const unreadable = (sealed: boolean) => {
|
||||
const { iframe, onError } = mount(
|
||||
'<div data-composition-id="main"></div>',
|
||||
{},
|
||||
{ sealed: () => sealed },
|
||||
);
|
||||
Object.defineProperty(iframe, "contentWindow", {
|
||||
get: () => {
|
||||
throw new DOMException("Blocked a frame with origin", "SecurityError");
|
||||
},
|
||||
});
|
||||
vi.advanceTimersByTime(LIMIT);
|
||||
return onError;
|
||||
};
|
||||
|
||||
it("names the runtime script and sandbox-origin when a sealed frame never shows a timeline", () => {
|
||||
const sealedTimeout = timelineNotFound(LIMIT, true);
|
||||
expect(unreadable(true)).toHaveBeenCalledExactlyOnceWith(sealedTimeout);
|
||||
expect(sealedTimeout).toContain("without sandbox-origin");
|
||||
expect(sealedTimeout).toContain("runtime script");
|
||||
});
|
||||
|
||||
it("gives an unsealed player whose composition is on another origin the plain timeout", () => {
|
||||
expect(unreadable(false)).toHaveBeenCalledExactlyOnceWith(TIMED_OUT);
|
||||
});
|
||||
it("does not invent duration for an unresolved document", () => {
|
||||
const { onReady, onError } = mount('<div data-composition-id="main"></div>');
|
||||
vi.advanceTimersByTime(LIMIT);
|
||||
|
||||
@@ -21,8 +21,10 @@ import {
|
||||
getShaderModeFromElement,
|
||||
prepareSrcForElement,
|
||||
prepareSrcdocForElement,
|
||||
prepareSealedSrcdocForElement,
|
||||
runtimeSrcFromElement,
|
||||
} from "./shader-options.js";
|
||||
import { carriesRuntime, decodePage } from "./runtime-in-srcdoc.js";
|
||||
import { createShaderLoader } from "./shader-loader-element.js";
|
||||
import { ShaderLoaderState } from "./shader-loader-state.js";
|
||||
import { PLAYER_STYLES } from "./styles.js";
|
||||
@@ -42,9 +44,27 @@ import {
|
||||
// timeline itself respects. Clamping here also shields the native
|
||||
// HTMLMediaElement.playbackRate setter, which throws for extreme values in
|
||||
// production browsers.
|
||||
function parseUrl(src: string): URL | null {
|
||||
try {
|
||||
return new URL(src, document.baseURI);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const MIN_PLAYBACK_RATE = 0.1;
|
||||
const MAX_PLAYBACK_RATE = 5;
|
||||
const SANDBOX_ORIGIN_ATTR = "sandbox-origin";
|
||||
const SEALED_RUNTIME_LOAD_FAILED = "The HyperFrames runtime this player ships with failed to load";
|
||||
|
||||
type FrameTarget = { src: string } | { srcdoc: string | null };
|
||||
type SealedPage = { bySrc: true } | { bySrc: false; html: string; url: string };
|
||||
|
||||
// A srcdoc copy runs under the embedding page's policy, so a page that sets its own, or whose headers this
|
||||
// player can't all read (a redirect to another site), loads by src.
|
||||
const OWN_POLICY_HEADERS = ["content-security-policy", "x-frame-options"];
|
||||
const mayCarryOwnPolicy = (response: Response) =>
|
||||
response.type !== "basic" || OWN_POLICY_HEADERS.some((name) => response.headers.has(name));
|
||||
const RUNTIME_DATA_DELIVERY_TIMEOUT_MS = 10_000;
|
||||
// Bounds how long the player waits on a same-origin composition's readiness
|
||||
// inputs (media, compute, paint-and-idle) before playing anyway — a stuck
|
||||
@@ -134,6 +154,10 @@ class HyperframesPlayer extends HTMLElement {
|
||||
private probe: CompositionProbe;
|
||||
|
||||
private _ready = false;
|
||||
/** Bumped by every navigation, so a sealed load that resolves late shows nothing stale. */
|
||||
private _documentLoad = 0;
|
||||
/** The URL a sealed srcdoc was fetched from, so its media resolve as they would by `src`. */
|
||||
private _srcdocUrl: string | null = null;
|
||||
private _readyBeforeRuntime = false;
|
||||
private _readyDocument: Document | null = null;
|
||||
private _awaitingLoad = false;
|
||||
@@ -224,6 +248,7 @@ class HyperframesPlayer extends HTMLElement {
|
||||
this.probe = new CompositionProbe(this.iframe, {
|
||||
resolveRuntimeUrl: () => runtimeSrcFromElement(this),
|
||||
hostOwnsDeadline: () => this.hasAttribute("no-load-timeout"),
|
||||
sealed: () => this.hasAttribute(SANDBOX_ORIGIN_ATTR),
|
||||
onReady: (result) => this._onProbeReady(result),
|
||||
onError: (message) => this._emit(new CustomEvent("error", { detail: { message } })),
|
||||
});
|
||||
@@ -250,8 +275,7 @@ class HyperframesPlayer extends HTMLElement {
|
||||
if (this.hasAttribute("poster"))
|
||||
this.posterEl = setupPoster(this.shadow, this.getAttribute("poster"), this.posterEl);
|
||||
if (this.hasAttribute("audio-src")) this._media.setupFromUrl(this.getAttribute("audio-src")!);
|
||||
if (this.hasAttribute("srcdoc"))
|
||||
this._navigateFrame({ srcdoc: prepareSrcdocForElement(this, this.getAttribute("srcdoc")!) });
|
||||
if (this.hasAttribute("srcdoc")) this._showDocument(this.getAttribute("srcdoc")!);
|
||||
if (this.hasAttribute("src")) this._loadSrc(this.getAttribute("src")!);
|
||||
|
||||
// Host-environment audio lock: when the embedding host (e.g. Claude
|
||||
@@ -269,6 +293,7 @@ class HyperframesPlayer extends HTMLElement {
|
||||
this._stopIframeMedia();
|
||||
this.resizeObserver.disconnect();
|
||||
window.removeEventListener("message", this._onMessage);
|
||||
this.probe.endNavigation();
|
||||
this.probe.stop();
|
||||
this._directTimelineClock.stop();
|
||||
this._stopParentTickClock();
|
||||
@@ -306,11 +331,13 @@ class HyperframesPlayer extends HTMLElement {
|
||||
if (val !== null) {
|
||||
this._pauseForVideoSwitch();
|
||||
this._teardownVideo();
|
||||
this._navigateFrame({ srcdoc: prepareSrcdocForElement(this, val) });
|
||||
this._showDocument(val);
|
||||
} else {
|
||||
this._documentLoad++;
|
||||
this._navigateFrame({ srcdoc: null });
|
||||
const src = this.getAttribute("src");
|
||||
if (src !== null && this._wantsVideo()) this._navigateSrc(src);
|
||||
if (src !== null && (this._wantsVideo() || this.hasAttribute(SANDBOX_ORIGIN_ATTR)))
|
||||
this._navigateSrc(src);
|
||||
}
|
||||
break;
|
||||
case SANDBOX_ORIGIN_ATTR:
|
||||
@@ -399,7 +426,7 @@ class HyperframesPlayer extends HTMLElement {
|
||||
this._abandonComposition("Sandbox policy changed before runtime data was applied");
|
||||
const srcdoc = this.getAttribute("srcdoc");
|
||||
if (srcdoc !== null) {
|
||||
this._navigateFrame({ srcdoc: prepareSrcdocForElement(this, srcdoc) });
|
||||
this._showDocument(srcdoc);
|
||||
return;
|
||||
}
|
||||
const src = this.getAttribute("src");
|
||||
@@ -1049,9 +1076,7 @@ class HyperframesPlayer extends HTMLElement {
|
||||
// explanatory rejection the caller gets from every other navigating path.
|
||||
this._abandonComposition("Shader options changed before runtime data was applied");
|
||||
if (this.hasAttribute("srcdoc")) {
|
||||
this._navigateFrame({
|
||||
srcdoc: prepareSrcdocForElement(this, this.getAttribute("srcdoc") || ""),
|
||||
});
|
||||
this._showDocument(this.getAttribute("srcdoc") || "");
|
||||
return;
|
||||
}
|
||||
if (this.hasAttribute("src")) this._loadSrc(this.getAttribute("src") || "");
|
||||
@@ -1079,21 +1104,101 @@ class HyperframesPlayer extends HTMLElement {
|
||||
}
|
||||
|
||||
private _loadSrc(src: string): void {
|
||||
this._documentLoad++;
|
||||
if (this._wantsVideo()) {
|
||||
// A sealed composition shown as srcdoc would outlive the frame's about:blank.
|
||||
this.iframe.removeAttribute("srcdoc");
|
||||
this._loadVideo(src);
|
||||
return;
|
||||
}
|
||||
this._teardownVideo();
|
||||
this._navigateFrame({ src: prepareSrcForElement(this, src) });
|
||||
if (this.hasAttribute("srcdoc")) {
|
||||
this._navigateFrame({ src: prepareSrcForElement(this, src) });
|
||||
return;
|
||||
}
|
||||
const url = parseUrl(src);
|
||||
if (url && this.hasAttribute(SANDBOX_ORIGIN_ATTR) && url.origin === location.origin) {
|
||||
this._showSealedSrc(src, url.href);
|
||||
return;
|
||||
}
|
||||
this.probe.markNavigation();
|
||||
this._writeSrcOverSrcdoc(src);
|
||||
}
|
||||
|
||||
private _navigateFrame(to: { src: string } | { srcdoc: string | null }): void {
|
||||
/** Loads src in place of a sealed srcdoc this player may be showing. */
|
||||
private _writeSrcOverSrcdoc(src: string): void {
|
||||
this.iframe.removeAttribute("srcdoc");
|
||||
this._writeFrame({ src: prepareSrcForElement(this, src) });
|
||||
}
|
||||
|
||||
private _navigateFrame(to: FrameTarget): void {
|
||||
this.probe.markNavigation();
|
||||
this._writeFrame(to);
|
||||
}
|
||||
|
||||
private _writeFrame(to: FrameTarget): void {
|
||||
this.probe.frameWritten();
|
||||
if (!("srcdoc" in to)) this.iframe.src = to.src;
|
||||
else if (to.srcdoc === null) this.iframe.removeAttribute("srcdoc");
|
||||
else this.iframe.srcdoc = to.srcdoc;
|
||||
}
|
||||
|
||||
/** The frame shows `html`. A sealed frame gets the runtime as text, so it is shown once that loads. */
|
||||
private _showDocument(html: string): void {
|
||||
const load = ++this._documentLoad;
|
||||
if (!this.hasAttribute(SANDBOX_ORIGIN_ATTR)) {
|
||||
this._srcdocUrl = null;
|
||||
this._navigateFrame({ srcdoc: prepareSrcdocForElement(this, html) });
|
||||
return;
|
||||
}
|
||||
this.probe.markPreparation();
|
||||
this._showSealedDocument(html, undefined, load);
|
||||
}
|
||||
|
||||
private _showSealedDocument(html: string, base: string | undefined, load: number): void {
|
||||
prepareSealedSrcdocForElement(this, html, base).then(
|
||||
(doc) => {
|
||||
if (load !== this._documentLoad) return;
|
||||
this._srcdocUrl = base ?? null;
|
||||
this._writeFrame({ srcdoc: doc });
|
||||
},
|
||||
() => {
|
||||
if (load !== this._documentLoad) return;
|
||||
this.probe.endNavigation();
|
||||
this._emit(new CustomEvent("error", { detail: { message: SEALED_RUNTIME_LOAD_FAILED } }));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A sealed frame cannot be reached once it loads, so a same-site composition without the runtime is
|
||||
* fetched and shown as srcdoc carrying it. One that brings its own, or that can't be fetched, loads by
|
||||
* `src` as before, under its own headers.
|
||||
*/
|
||||
private _showSealedSrc(src: string, href: string): void {
|
||||
const load = ++this._documentLoad;
|
||||
this.probe.markPreparation();
|
||||
fetch(href, { credentials: "same-origin" })
|
||||
.then(async (response): Promise<SealedPage> => {
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
if (mayCarryOwnPolicy(response)) return { bySrc: true };
|
||||
const html = decodePage(await response.arrayBuffer(), response.headers.get("content-type"));
|
||||
return carriesRuntime(html)
|
||||
? { bySrc: true }
|
||||
: { bySrc: false, html, url: response.url || href };
|
||||
})
|
||||
.then(
|
||||
(page) => {
|
||||
if (load !== this._documentLoad) return;
|
||||
if (page.bySrc) this._writeSrcOverSrcdoc(src);
|
||||
else this._showSealedDocument(page.html, page.url, load);
|
||||
},
|
||||
() => {
|
||||
if (load === this._documentLoad) this._writeSrcOverSrcdoc(src);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private _loadVideo(src: string): void {
|
||||
if (!this._videoSource) {
|
||||
this._videoSource = createVideoSource({
|
||||
@@ -1122,6 +1227,7 @@ class HyperframesPlayer extends HTMLElement {
|
||||
// Unloads a composition this player was showing before it switched to video.
|
||||
this.iframe.src = "about:blank";
|
||||
}
|
||||
this.probe.endNavigation();
|
||||
this.probe.stop();
|
||||
const { video, adapter } = this._videoSource;
|
||||
this._directTimelineAdapter = adapter;
|
||||
@@ -1302,7 +1408,7 @@ class HyperframesPlayer extends HTMLElement {
|
||||
sendControl: (action, extra) => this._sendControl(action, extra),
|
||||
getIframeDoc: () => this.iframe.contentDocument,
|
||||
getCompositionUrl: () =>
|
||||
this.iframe.hasAttribute("srcdoc") ? null : this.iframe.src || null,
|
||||
this.iframe.hasAttribute("srcdoc") ? this._srcdocUrl : this.iframe.src || null,
|
||||
onRuntimeReady: () => {
|
||||
this._runtimeBridgeReady = true;
|
||||
this._replayBridgeState();
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
export const bundleScriptUrl =
|
||||
typeof document !== "undefined" && document.currentScript instanceof HTMLScriptElement
|
||||
? document.currentScript.src
|
||||
: null;
|
||||
|
||||
export async function runtimeBeside(scriptUrl: string | null): Promise<string> {
|
||||
if (!scriptUrl) throw new Error("The player's script URL is unknown");
|
||||
const response = await fetch(new URL("hyperframe.runtime.iife.js", scriptUrl));
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
return response.text();
|
||||
}
|
||||
|
||||
/** What the cjs and iife builds load for `@hyperframes/core/runtime-script`. */
|
||||
export const getHyperframeRuntimeScript = (): Promise<string> => runtimeBeside(bundleScriptUrl);
|
||||
@@ -1,6 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ensureRuntimeBeforeBodyScripts } from "./runtime-in-srcdoc.js";
|
||||
import {
|
||||
carriesRuntime,
|
||||
ensureRuntimeBeforeBodyScripts,
|
||||
inlineRuntimeBeforeBodyScripts,
|
||||
withBaseHref,
|
||||
} from "./runtime-in-srcdoc.js";
|
||||
|
||||
const URL = "https://cdn.example/hyperframe.runtime.iife.js";
|
||||
|
||||
@@ -79,3 +84,49 @@ describe("ensureRuntimeBeforeBodyScripts", () => {
|
||||
expect(out.indexOf(URL)).toBeGreaterThan(out.indexOf("</header>"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("carriesRuntime", () => {
|
||||
it("reads a script's own src, not text inside another attribute's quoted value", () => {
|
||||
expect(
|
||||
carriesRuntime(`<script data-note="see src=/hyperframe.runtime.iife.js"></script>`),
|
||||
).toBe(false);
|
||||
expect(
|
||||
carriesRuntime(`<script data-note='a' src=/v1/hyperframe.runtime.iife.js></script>`),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("inlineRuntimeBeforeBodyScripts", () => {
|
||||
it("puts the runtime's text ahead of the script that reads variables", () => {
|
||||
const out = inlineRuntimeBeforeBodyScripts(COMPONENT_PAGE, "window.__hyperframes = {};");
|
||||
|
||||
expect(out).toContain("<head><script>window.__hyperframes = {};</script>");
|
||||
expect(out.indexOf("__hyperframes = {}")).toBeLessThan(out.indexOf("getVariables"));
|
||||
});
|
||||
|
||||
it("adds no second copy to a page that links or inlines it", () => {
|
||||
const linked = `<html><head><script src="${URL}"></script></head><body></body></html>`;
|
||||
const inlined = inlineRuntimeBeforeBodyScripts(COMPONENT_PAGE, "window.__hyperframes = {};");
|
||||
|
||||
expect(inlineRuntimeBeforeBodyScripts(linked, "window.__hyperframes = {};")).toBe(linked);
|
||||
expect(inlineRuntimeBeforeBodyScripts(inlined, "window.__hyperframes = {};")).toBe(inlined);
|
||||
});
|
||||
});
|
||||
|
||||
describe("withBaseHref", () => {
|
||||
it("resolves the page's relative paths at the URL it came from, quoted safely", () => {
|
||||
const out = withBaseHref("<html><head></head></html>", 'https://site.example/a b/"x".html');
|
||||
|
||||
expect(out).toBe(
|
||||
'<html><head><base href="https://site.example/a b/"x".html"></head></html>',
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves a base the page names itself and puts it first", () => {
|
||||
const page = '<html><head><base href="media/"></head></html>';
|
||||
|
||||
expect(withBaseHref(page, "https://site.example/film/")).toBe(
|
||||
'<html><head><base href="https://site.example/film/media/"><base href="media/"></head></html>',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { RUNTIME_BOOTSTRAP_ATTR } from "@hyperframes/core/compiler/html-tokens";
|
||||
|
||||
/**
|
||||
* Put the runtime in the document's head, before anything in the body runs.
|
||||
*
|
||||
@@ -25,24 +27,96 @@
|
||||
*/
|
||||
|
||||
/** Already carrying the runtime: a CLI-rendered page, or a second preparation. */
|
||||
function alreadyHasRuntime(html: string, runtimeUrl: string): boolean {
|
||||
if (html.includes(runtimeUrl)) return true;
|
||||
// The engine inlines the runtime rather than linking it, and it defines this
|
||||
// global on the way in. Matching the source avoids a second, redundant copy.
|
||||
return /hyperframe\.runtime\.iife\.js|__hyperframes\s*=/.test(html);
|
||||
function alreadyHasRuntime(html: string, runtimeUrl: string | null): boolean {
|
||||
if (runtimeUrl && html.includes(runtimeUrl)) return true;
|
||||
// The engine inlines the runtime rather than linking it, and it assigns this global on the way in.
|
||||
return /__hyperframes\s*=(?!=)/.test(html) || linksRuntime(html);
|
||||
}
|
||||
|
||||
/** A page that brings the runtime itself, which a sealed player then loads by `src` as before. */
|
||||
export const carriesRuntime = (html: string): boolean => alreadyHasRuntime(html, null);
|
||||
|
||||
function linksRuntime(html: string): boolean {
|
||||
for (
|
||||
let tag = findOpeningTag(html, "script");
|
||||
tag;
|
||||
tag = findOpeningTag(html, "script", afterScript(html, tag.end))
|
||||
) {
|
||||
const attributes = tagAttributes(html.slice(tag.index + "<script".length, tag.end - 1));
|
||||
if (attributes.has(RUNTIME_BOOTSTRAP_ATTR)) return true;
|
||||
if (attributes.get("src")?.includes("hyperframe.runtime.iife.js")) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function afterScript(html: string, from: number): number {
|
||||
const lower = html.toLowerCase();
|
||||
for (
|
||||
let close = lower.indexOf("</script", from);
|
||||
close >= 0;
|
||||
close = lower.indexOf("</script", close + 1)
|
||||
)
|
||||
if (CLOSING_TAG_BOUNDARIES.has(lower[close + "</script".length])) return close;
|
||||
return html.length;
|
||||
}
|
||||
|
||||
const isSpace = (c: string) => c === " " || c === "\t" || c === "\n" || c === "\r" || c === "\f";
|
||||
const isGap = (c: string) => isSpace(c) || c === "/";
|
||||
const inName = (c: string) => !isGap(c) && c !== "=";
|
||||
const notSpace = (c: string) => !isSpace(c);
|
||||
|
||||
function skip(text: string, from: number, more: (c: string) => boolean): number {
|
||||
let i = from;
|
||||
while (i < text.length && more(text.charAt(i))) i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
function attributeValue(text: string, from: number): { value: string; end: number } {
|
||||
const quote = text.charAt(from);
|
||||
if (quote !== '"' && quote !== "'") {
|
||||
const end = skip(text, from, notSpace);
|
||||
return { value: text.slice(from, end), end };
|
||||
}
|
||||
const close = text.indexOf(quote, from + 1);
|
||||
const end = close < 0 ? text.length : close;
|
||||
return { value: text.slice(from + 1, end), end: end + 1 };
|
||||
}
|
||||
|
||||
function tagAttributes(text: string): Map<string, string> {
|
||||
const attributes = new Map<string, string>();
|
||||
for (let i = skip(text, 0, isGap); i < text.length; i = skip(text, i, isGap)) {
|
||||
const start = i;
|
||||
i = skip(text, i, inName);
|
||||
if (i === start) break;
|
||||
const name = text.slice(start, i).toLowerCase();
|
||||
i = skip(text, i, isSpace);
|
||||
let value = "";
|
||||
if (text.charAt(i) === "=")
|
||||
({ value, end: i } = attributeValue(text, skip(text, i + 1, isSpace)));
|
||||
attributes.set(name, value);
|
||||
}
|
||||
return attributes;
|
||||
}
|
||||
|
||||
type OpeningTag = { index: number; end: number };
|
||||
const OPENING_TAG_BOUNDARIES = new Set<string | undefined>([">", " ", "\t", "\n", "\r", "\f"]);
|
||||
const CLOSING_TAG_BOUNDARIES = new Set<string | undefined>([...OPENING_TAG_BOUNDARIES, "/"]);
|
||||
|
||||
/** Find an opening tag in one linear pass, without a backtracking regex over caller-owned HTML. */
|
||||
function findOpeningTag(html: string, tagName: string): OpeningTag | null {
|
||||
function findOpeningTag(html: string, tagName: string, start = 0): OpeningTag | null {
|
||||
const lower = html.toLowerCase();
|
||||
const prefix = `<${tagName}`;
|
||||
let from = 0;
|
||||
let from = start;
|
||||
while (from < lower.length) {
|
||||
const index = lower.indexOf(prefix, from);
|
||||
if (index < 0) return null;
|
||||
const comment = lower.indexOf("<!--", from);
|
||||
if (comment >= 0 && comment < index) {
|
||||
const closed = lower.indexOf("-->", comment + 4);
|
||||
if (closed < 0) return null;
|
||||
from = closed + 3;
|
||||
continue;
|
||||
}
|
||||
const boundary = lower[index + prefix.length];
|
||||
if (OPENING_TAG_BOUNDARIES.has(boundary)) {
|
||||
const close = lower.indexOf(">", index + prefix.length);
|
||||
@@ -56,8 +130,56 @@ function findOpeningTag(html: string, tagName: string): OpeningTag | null {
|
||||
|
||||
export function ensureRuntimeBeforeBodyScripts(html: string, runtimeUrl: string): string {
|
||||
if (!html || alreadyHasRuntime(html, runtimeUrl)) return html;
|
||||
return insertAtHeadStart(html, `<script src="${runtimeUrl}"></script>`);
|
||||
}
|
||||
|
||||
const tag = `<script src="${runtimeUrl}"></script>`;
|
||||
/** The same placement with the runtime's own text, for a sealed frame: it then loads nothing from another origin. */
|
||||
export function inlineRuntimeBeforeBodyScripts(html: string, escapedSource: string): string {
|
||||
if (!html || alreadyHasRuntime(html, null)) return html;
|
||||
return insertAtHeadStart(html, `<script>${escapedSource}</script>`);
|
||||
}
|
||||
|
||||
/**
|
||||
* A document fetched from `url` and shown as srcdoc still resolves its relative paths there. The first
|
||||
* `<base href>` wins, so the page's own one is resolved against `url` and put first.
|
||||
*/
|
||||
export function withBaseHref(html: string, url: string): string {
|
||||
return insertAtHeadStart(html, `<base href="${escapeAttr(baseOf(html, url))}">`);
|
||||
}
|
||||
|
||||
function baseOf(html: string, url: string): string {
|
||||
for (let tag = findOpeningTag(html, "base"); tag; tag = findOpeningTag(html, "base", tag.end)) {
|
||||
const href = /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(
|
||||
html.slice(tag.index, tag.end),
|
||||
);
|
||||
if (!href) continue;
|
||||
try {
|
||||
return new URL(href[1] ?? href[2] ?? href[3] ?? "", url).href;
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/** The bytes of a fetched page as the browser would read them: the response's charset, else the page's own. */
|
||||
export function decodePage(bytes: ArrayBuffer, contentType: string | null): string {
|
||||
const declared =
|
||||
/charset=["']?([\w-]+)/i.exec(contentType ?? "")?.[1] ??
|
||||
/<meta[^>]{0,200}charset=["']?([\w-]+)/i.exec(
|
||||
new TextDecoder("latin1").decode(bytes.slice(0, 1024)),
|
||||
)?.[1];
|
||||
try {
|
||||
return new TextDecoder(declared ?? "utf-8").decode(bytes);
|
||||
} catch {
|
||||
return new TextDecoder().decode(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
const escapeAttr = (value: string): string =>
|
||||
value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
||||
|
||||
function insertAtHeadStart(html: string, tag: string): string {
|
||||
const head = findOpeningTag(html, "head");
|
||||
if (head) {
|
||||
return html.slice(0, head.end) + tag + html.slice(head.end);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { escapeInlineScriptSource } from "@hyperframes/core/compiler/html-tokens";
|
||||
import { runtimeBeside } from "./runtime-beside-bundle.js";
|
||||
|
||||
let source: Promise<string> | undefined;
|
||||
|
||||
export function sealedRuntimeSource(): Promise<string> {
|
||||
// esm: the bundler resolves this, else the file beside the module; cjs/iife alias it.
|
||||
source ??= import("@hyperframes/core/runtime-script")
|
||||
.then(
|
||||
(runtime) => runtime.getHyperframeRuntimeScript(),
|
||||
(error: unknown) =>
|
||||
import.meta.url ? runtimeBeside(import.meta.url) : Promise.reject(error),
|
||||
)
|
||||
.then(escapeInlineScriptSource);
|
||||
source.catch(() => (source = undefined));
|
||||
return source;
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { loadLimitMs } from "./composition-probe.js";
|
||||
import { loadLimitMs, timelineNotFound } from "./composition-probe.js";
|
||||
|
||||
const LIMIT = loadLimitMs();
|
||||
const TIMED_OUT = `error Composition timeline not found after ${LIMIT / 1000}s`;
|
||||
const TIMED_OUT = `error ${timelineNotFound(LIMIT, true)}`;
|
||||
|
||||
type Player = HTMLElement & {
|
||||
ready: boolean;
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { loadLimitMs, timelineNotFound } from "./composition-probe.js";
|
||||
|
||||
const LIMIT = loadLimitMs();
|
||||
|
||||
// The player's own runtime, standing in for core's 750 KB build. Its "</script>" must not end the inlined script.
|
||||
const RUNTIME = 'window.__hyperframes = { built: "</script>" };';
|
||||
vi.mock("@hyperframes/core/runtime-script", () => ({ getHyperframeRuntimeScript: () => RUNTIME }));
|
||||
|
||||
type Player = HTMLElement & { iframeElement: HTMLIFrameElement };
|
||||
|
||||
const page = (head = "", body = "<script>window.composition = 1;</script>") =>
|
||||
`<!doctype html><html><head>${head}</head><body>${body}</body></html>`;
|
||||
const sameSite = () => `${location.origin}/films/one/index.html?take=2`;
|
||||
|
||||
/** A response from the player's own site, as fetch gives it: every header readable. */
|
||||
function siteResponse(body?: BodyInit | null, init?: ResponseInit, type: ResponseType = "basic") {
|
||||
const response = new Response(body, init);
|
||||
Object.defineProperty(response, "type", { value: type });
|
||||
return response;
|
||||
}
|
||||
|
||||
function player(attributes: Record<string, string>): Player {
|
||||
const el = document.createElement("hyperframes-player") as Player;
|
||||
for (const [name, value] of Object.entries(attributes)) el.setAttribute(name, value);
|
||||
document.body.appendChild(el);
|
||||
return el;
|
||||
}
|
||||
|
||||
const srcdocOf = async (el: Player) => {
|
||||
await vi.waitFor(() => expect(el.iframeElement.getAttribute("srcdoc")).toBeTruthy());
|
||||
return el.iframeElement.getAttribute("srcdoc")!;
|
||||
};
|
||||
|
||||
describe("a sealed player brings its own runtime", () => {
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(async () => {
|
||||
await import("./hyperframes-player.js");
|
||||
fetchMock = vi.fn(async () => siteResponse(page()));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.replaceChildren();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("shows a composition from its own site with the runtime inlined, resolving paths at its URL", async () => {
|
||||
const el = player({ "sandbox-origin": "", src: sameSite() });
|
||||
const doc = await srcdocOf(el);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(sameSite(), { credentials: "same-origin" });
|
||||
expect(doc).not.toContain("cdn.jsdelivr.net");
|
||||
expect(doc).toContain('built: "<\\/script>"');
|
||||
// Base first, then the runtime, both ahead of the composition's own script.
|
||||
expect(doc.indexOf(`<base href="${sameSite()}">`)).toBeGreaterThan(-1);
|
||||
expect(doc.indexOf("<base")).toBeLessThan(doc.indexOf("__hyperframes"));
|
||||
expect(doc.indexOf("__hyperframes")).toBeLessThan(doc.indexOf("window.composition"));
|
||||
});
|
||||
|
||||
it("loads a composition that brings its own runtime by src, under its own headers", async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
siteResponse(page('<script src="/vendor/hyperframe.runtime.iife.js"></script>')),
|
||||
);
|
||||
const el = player({ "sandbox-origin": "", src: sameSite() });
|
||||
|
||||
await vi.waitFor(() => expect(el.iframeElement.src).toBe(sameSite()));
|
||||
expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
|
||||
});
|
||||
|
||||
it("loads a preview that links the runtime by its marker, as Studio's does, by src", async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
siteResponse(
|
||||
page('<script data-hyperframes-preview-runtime="1" src="/api/runtime.js"></script>'),
|
||||
),
|
||||
);
|
||||
const el = player({ "sandbox-origin": "", src: sameSite() });
|
||||
|
||||
await vi.waitFor(() => expect(el.iframeElement.src).toBe(sameSite()));
|
||||
expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
|
||||
});
|
||||
|
||||
it("still adds the runtime when a script only mentions Studio's marker", async () => {
|
||||
for (const head of [
|
||||
'<script data-note="data-hyperframes-preview-runtime"></script>',
|
||||
'<script>var tag = "<script data-hyperframes-preview-runtime src=x>";</script>',
|
||||
'<script>var end = "</scripted"; var tag = "<script data-hyperframes-preview-runtime src=x>";</script>',
|
||||
'<SCRIPT>var end = "</SCRIPTS"; var tag = "<script data-hyperframes-preview-runtime>";</SCRIPT>',
|
||||
]) {
|
||||
fetchMock.mockResolvedValueOnce(siteResponse(page(head)));
|
||||
expect(await srcdocOf(player({ "sandbox-origin": "", src: sameSite() }))).toContain("built:");
|
||||
document.body.replaceChildren();
|
||||
}
|
||||
});
|
||||
|
||||
it("still adds the runtime when a page only compares or names it", async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
siteResponse(
|
||||
page(
|
||||
"<!-- needs hyperframe.runtime.iife.js --><script>if (window.__hyperframes === undefined) {}</script>",
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(await srcdocOf(player({ "sandbox-origin": "", src: sameSite() }))).toContain("built:");
|
||||
});
|
||||
|
||||
it("resolves paths at the URL a redirect landed on", async () => {
|
||||
const landed = `${location.origin}/films/one/`;
|
||||
const response = siteResponse(page());
|
||||
Object.defineProperty(response, "url", { value: landed });
|
||||
fetchMock.mockResolvedValueOnce(response);
|
||||
const doc = await srcdocOf(
|
||||
player({ "sandbox-origin": "", src: `${location.origin}/films/one` }),
|
||||
);
|
||||
|
||||
expect(doc).toContain(`<base href="${landed}">`);
|
||||
});
|
||||
|
||||
it("resolves the composition's own relative base against its URL, ahead of it", async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
siteResponse(page('<base target="_blank"><base href="assets/">')),
|
||||
);
|
||||
const doc = await srcdocOf(player({ "sandbox-origin": "", src: sameSite() }));
|
||||
|
||||
const ours = doc.indexOf(`<base href="${location.origin}/films/one/assets/">`);
|
||||
expect(ours).toBeGreaterThan(-1);
|
||||
expect(ours).toBeLessThan(doc.indexOf('<base target="_blank">'));
|
||||
});
|
||||
|
||||
it("puts the runtime in the real head, not one named in a comment", async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
siteResponse("<!-- <head> --><html><head></head><body></body></html>"),
|
||||
);
|
||||
const doc = await srcdocOf(player({ "sandbox-origin": "", src: sameSite() }));
|
||||
|
||||
expect(doc.indexOf("built:")).toBeGreaterThan(doc.indexOf("<html><head>"));
|
||||
});
|
||||
|
||||
it("reads the page in the charset its response names", async () => {
|
||||
const encode = (text: string) => [...new TextEncoder().encode(text)];
|
||||
const [before, after] = page("", "<p>caf\u00e9</p>").split("\u00e9");
|
||||
const bytes = new Uint8Array([...encode(before!), 0xe9, ...encode(after!)]);
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
siteResponse(bytes, { headers: { "content-type": "text/html; charset=windows-1252" } }),
|
||||
);
|
||||
expect(await srcdocOf(player({ "sandbox-origin": "", src: sameSite() }))).toContain("café");
|
||||
});
|
||||
|
||||
it("carries the shader options a src would have carried in its query", async () => {
|
||||
const doc = await srcdocOf(
|
||||
player({ "sandbox-origin": "", "shader-capture-scale": "0.5", src: sameSite() }),
|
||||
);
|
||||
|
||||
expect(doc).toContain('window.__HF_SHADER_CAPTURE_SCALE="0.5";');
|
||||
});
|
||||
|
||||
it("inlines the runtime in a sealed srcdoc instead of linking the CDN", async () => {
|
||||
const doc = await srcdocOf(player({ "sandbox-origin": "", srcdoc: page() }));
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(doc).not.toContain("cdn.jsdelivr.net");
|
||||
expect(doc).toContain("built:");
|
||||
});
|
||||
|
||||
it("loads a composition from another site as before", () => {
|
||||
const el = player({ "sandbox-origin": "", src: "https://films.example/one.html" });
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(el.iframeElement.src).toBe("https://films.example/one.html");
|
||||
expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
|
||||
});
|
||||
|
||||
it("loads src as before when its own site refuses the fetch", async () => {
|
||||
fetchMock.mockResolvedValueOnce(siteResponse("", { status: 404 }));
|
||||
const el = player({ "sandbox-origin": "", src: sameSite() });
|
||||
|
||||
await vi.waitFor(() => expect(el.iframeElement.src).toBe(sameSite()));
|
||||
expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
|
||||
});
|
||||
|
||||
// fails without the fix: the page was shown as srcdoc, under the embedding page's policy instead of its own.
|
||||
it("loads a page whose response sets its own security policy by src, under that policy", async () => {
|
||||
for (const header of [
|
||||
["content-security-policy", "script-src 'self'"],
|
||||
["x-frame-options", "SAMEORIGIN"],
|
||||
] satisfies [string, string][]) {
|
||||
fetchMock.mockResolvedValueOnce(siteResponse(page(), { headers: [header] }));
|
||||
const el = player({ "sandbox-origin": "", src: sameSite() });
|
||||
|
||||
await vi.waitFor(() => expect(el.iframeElement.src).toBe(sameSite()));
|
||||
expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
|
||||
document.body.replaceChildren();
|
||||
}
|
||||
});
|
||||
|
||||
// fails without the fix: a redirect to another site that allows CORS hides that page's policy headers from
|
||||
// the fetch, so the page was shown as srcdoc although its own policy could not be read.
|
||||
it("loads by src when the page's headers can't all be read, as after a redirect to another site", async () => {
|
||||
fetchMock.mockResolvedValueOnce(siteResponse(page(), {}, "cors"));
|
||||
const el = player({ "sandbox-origin": "", src: sameSite() });
|
||||
|
||||
await vi.waitFor(() => expect(el.iframeElement.src).toBe(sameSite()));
|
||||
expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
|
||||
});
|
||||
|
||||
// fails without the fix: the load clock started only once the frame was written, so a fetch that never answered
|
||||
// left a blank player with no error at all.
|
||||
it("reports the load limit once while its own site's fetch is still pending", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let answer: (response: Response) => void = () => {};
|
||||
fetchMock.mockReturnValueOnce(new Promise<Response>((resolve) => (answer = resolve)));
|
||||
const el = player({ "sandbox-origin": "", src: sameSite() });
|
||||
const errors: string[] = [];
|
||||
el.addEventListener("error", (event: Event) =>
|
||||
errors.push((event as CustomEvent<{ message: string }>).detail.message),
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(LIMIT - 1);
|
||||
expect(errors).toEqual([]);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(errors).toEqual([timelineNotFound(LIMIT, true)]);
|
||||
|
||||
answer(siteResponse(page()));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(el.iframeElement.getAttribute("srcdoc")).toContain("built:");
|
||||
await vi.advanceTimersByTimeAsync(LIMIT);
|
||||
expect(errors).toHaveLength(1);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows nothing from a fetch that answers after the player moved to another composition", async () => {
|
||||
let answer: (response: Response) => void = () => {};
|
||||
fetchMock.mockReturnValueOnce(new Promise<Response>((resolve) => (answer = resolve)));
|
||||
const el = player({ "sandbox-origin": "", src: sameSite() });
|
||||
el.setAttribute("src", "https://films.example/two.html");
|
||||
answer(siteResponse(page()));
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
|
||||
expect(el.iframeElement.src).toBe("https://films.example/two.html");
|
||||
expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
|
||||
});
|
||||
|
||||
it("hands a src that is not a URL to the frame as before, without throwing", () => {
|
||||
const el = player({ "sandbox-origin": "", src: "http://[not a host" });
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(el.iframeElement.getAttribute("src")).toContain("[not a host");
|
||||
});
|
||||
|
||||
it("unloads a sealed composition when the player switches to a video", async () => {
|
||||
const el = player({ "sandbox-origin": "", src: sameSite() });
|
||||
await srcdocOf(el);
|
||||
el.setAttribute("type", "video/mp4");
|
||||
el.setAttribute("src", `${location.origin}/clip.mp4`);
|
||||
|
||||
expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
|
||||
});
|
||||
|
||||
// fails without the fix: the pending fetch's load limit still fired, over the playing video.
|
||||
it("reports no load limit after a player waiting on its own site's fetch switches to a video", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
fetchMock.mockReturnValueOnce(new Promise<Response>(() => {}));
|
||||
const el = player({ "sandbox-origin": "", src: sameSite() });
|
||||
const errors: string[] = [];
|
||||
el.addEventListener("error", (event: Event) =>
|
||||
errors.push((event as CustomEvent<{ message: string }>).detail.message),
|
||||
);
|
||||
el.setAttribute("type", "video/mp4");
|
||||
el.setAttribute("src", `${location.origin}/clip.mp4`);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(LIMIT);
|
||||
expect(errors).toEqual([]);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves an unsealed player's src load as it was", () => {
|
||||
const el = player({ src: sameSite() });
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(el.iframeElement.src).toBe(sameSite());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@hyperframes/core/runtime-script", () => ({
|
||||
getHyperframeRuntimeScript: () => {
|
||||
throw new Error("chunk missing");
|
||||
},
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
document.body.replaceChildren();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("names a runtime that failed to load instead of showing a sealed frame that never plays", async () => {
|
||||
await import("./hyperframes-player.js");
|
||||
const el = document.createElement("hyperframes-player");
|
||||
el.setAttribute("sandbox-origin", "");
|
||||
el.setAttribute("srcdoc", "<!doctype html><html><head></head><body></body></html>");
|
||||
const errors: string[] = [];
|
||||
el.addEventListener("error", (event: Event) =>
|
||||
errors.push((event as CustomEvent<{ message: string }>).detail.message),
|
||||
);
|
||||
document.body.appendChild(el);
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(errors).toEqual(["The HyperFrames runtime this player ships with failed to load"]),
|
||||
);
|
||||
});
|
||||
|
||||
it("names it on a same-site src too, instead of loading the bare src", async () => {
|
||||
await import("./hyperframes-player.js");
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => new Response("<html><head></head><body></body></html>")),
|
||||
);
|
||||
const el = document.createElement("hyperframes-player") as HTMLElement & {
|
||||
iframeElement: HTMLIFrameElement;
|
||||
};
|
||||
el.setAttribute("sandbox-origin", "");
|
||||
el.setAttribute("src", `${location.origin}/films/one/index.html`);
|
||||
const errors: string[] = [];
|
||||
el.addEventListener("error", (event: Event) =>
|
||||
errors.push((event as CustomEvent<{ message: string }>).detail.message),
|
||||
);
|
||||
document.body.appendChild(el);
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(errors).toEqual(["The HyperFrames runtime this player ships with failed to load"]),
|
||||
);
|
||||
expect(el.iframeElement.getAttribute("src")).toBeNull();
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { loadLimitMs } from "./composition-probe.js";
|
||||
import { loadLimitMs, timelineNotFound } from "./composition-probe.js";
|
||||
|
||||
const LIMIT = loadLimitMs();
|
||||
|
||||
@@ -77,7 +77,7 @@ describe("a sealed film whose runtime boots late", () => {
|
||||
const { player, events, postStatic } = framedPlayer();
|
||||
postStatic(over);
|
||||
vi.advanceTimersByTime(LIMIT);
|
||||
expect(events).toEqual([`error Composition timeline not found after ${LIMIT / 1000}s`]);
|
||||
expect(events).toEqual([`error ${timelineNotFound(LIMIT, true)}`]);
|
||||
expect(player.ready).toBe(false);
|
||||
});
|
||||
|
||||
@@ -85,7 +85,7 @@ describe("a sealed film whose runtime boots late", () => {
|
||||
const { player, events, postStatic } = framedPlayer();
|
||||
postStatic({}, window);
|
||||
vi.advanceTimersByTime(LIMIT);
|
||||
expect(events).toEqual([`error Composition timeline not found after ${LIMIT / 1000}s`]);
|
||||
expect(events).toEqual([`error ${timelineNotFound(LIMIT, true)}`]);
|
||||
expect(player.ready).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getShaderModeFromElement, SHADER_LOADING_ATTR } from "./shader-options.js";
|
||||
|
||||
const modeOf = (value: string | null) => {
|
||||
const el = document.createElement("div");
|
||||
if (value !== null) el.setAttribute(SHADER_LOADING_ATTR, value);
|
||||
return getShaderModeFromElement(el);
|
||||
};
|
||||
|
||||
describe("getShaderModeFromElement", () => {
|
||||
it.each([
|
||||
[null, "composition"],
|
||||
["", "composition"],
|
||||
[" ", "composition"],
|
||||
["none", "none"],
|
||||
[" OFF ", "none"],
|
||||
["false", "none"],
|
||||
["0", "none"],
|
||||
["player", "player"],
|
||||
["True", "player"],
|
||||
["1", "player"],
|
||||
["on", "player"],
|
||||
["composition", "composition"],
|
||||
["sometimes", "composition"],
|
||||
["constructor", "composition"],
|
||||
["__proto__", "composition"],
|
||||
])("reads %j as %s", (value, mode) => {
|
||||
expect(modeOf(value)).toBe(mode);
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,13 @@
|
||||
* URLs and srcdoc HTML.
|
||||
*/
|
||||
|
||||
import { ensureRuntimeBeforeBodyScripts } from "./runtime-in-srcdoc.js";
|
||||
import {
|
||||
carriesRuntime,
|
||||
ensureRuntimeBeforeBodyScripts,
|
||||
inlineRuntimeBeforeBodyScripts,
|
||||
withBaseHref,
|
||||
} from "./runtime-in-srcdoc.js";
|
||||
import { sealedRuntimeSource } from "./sealed-runtime.js";
|
||||
import { RUNTIME_CDN_URL } from "./runtime-url.js";
|
||||
|
||||
export const SHADER_CAPTURE_SCALE_ATTR = "shader-capture-scale";
|
||||
@@ -42,26 +48,19 @@ function normalizeShaderCaptureScale(value: string | null): string | null {
|
||||
return String(Math.min(1, Math.max(0.25, parsed)));
|
||||
}
|
||||
|
||||
const SHADER_LOADING_WORDS = new Map<string, ShaderLoadingMode>([
|
||||
["none", "none"],
|
||||
["false", "none"],
|
||||
["0", "none"],
|
||||
["off", "none"],
|
||||
["player", "player"],
|
||||
["true", "player"],
|
||||
["1", "player"],
|
||||
["on", "player"],
|
||||
]);
|
||||
|
||||
function normalizeShaderLoadingMode(value: string | null): ShaderLoadingMode {
|
||||
if (value === null || value.trim() === "") return "composition";
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (
|
||||
normalized === "none" ||
|
||||
normalized === "false" ||
|
||||
normalized === "0" ||
|
||||
normalized === "off"
|
||||
) {
|
||||
return "none";
|
||||
}
|
||||
if (
|
||||
normalized === "player" ||
|
||||
normalized === "true" ||
|
||||
normalized === "1" ||
|
||||
normalized === "on"
|
||||
) {
|
||||
return "player";
|
||||
}
|
||||
return "composition";
|
||||
return SHADER_LOADING_WORDS.get(value?.trim().toLowerCase() ?? "") ?? "composition";
|
||||
}
|
||||
|
||||
/** Drop one of our own keys from raw `a=1&b=2` pairs, matched by name so that
|
||||
@@ -158,6 +157,34 @@ export function prepareSrcdocForElement(el: Element, srcdoc: string): string {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `prepareSrcdocForElement` for a sealed frame, which the player cannot reach into after it loads:
|
||||
* the runtime goes in as text, unless the embedder named its own `runtime-src`.
|
||||
*/
|
||||
export async function prepareSealedSrcdocForElement(
|
||||
el: Element,
|
||||
html: string,
|
||||
base?: string,
|
||||
): Promise<string> {
|
||||
const doc =
|
||||
runtimeSrcFromElement(el) !== RUNTIME_CDN_URL
|
||||
? prepareSrcdocForElement(el, html)
|
||||
: await withSealedRuntime(
|
||||
injectShaderOptionsIntoSrcdoc(
|
||||
html,
|
||||
normalizeShaderCaptureScale(el.getAttribute(SHADER_CAPTURE_SCALE_ATTR)),
|
||||
getShaderModeFromElement(el),
|
||||
),
|
||||
);
|
||||
return base ? withBaseHref(doc, base) : doc;
|
||||
}
|
||||
|
||||
async function withSealedRuntime(page: string): Promise<string> {
|
||||
return carriesRuntime(page)
|
||||
? page
|
||||
: inlineRuntimeBeforeBodyScripts(page, await sealedRuntimeSource());
|
||||
}
|
||||
|
||||
export function runtimeSrcFromElement(el: Element): string {
|
||||
const configured = el.getAttribute(RUNTIME_SRC_ATTR)?.trim();
|
||||
if (!configured) return RUNTIME_CDN_URL;
|
||||
|
||||
@@ -47,6 +47,69 @@ try {
|
||||
true,
|
||||
"removing the policy must reload into the documented trusted mode",
|
||||
);
|
||||
// A sealed player adds the runtime to a composition from its own site, so the missing-runtime
|
||||
// error belongs to one from another origin (localhost against 127.0.0.1).
|
||||
const direct = await browser.newPage();
|
||||
await direct.goto(`${server.origin}/host.html?fixture=direct-timeline&sealed=1`, {
|
||||
waitUntil: "domcontentloaded",
|
||||
});
|
||||
await direct.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
|
||||
await direct.evaluate(
|
||||
(url) => {
|
||||
document.querySelector("hyperframes-player")!.setAttribute("src", url);
|
||||
},
|
||||
`${server.origin.replace("127.0.0.1", "localhost")}/fixtures/direct-timeline/index.html`,
|
||||
);
|
||||
// Linux's 30 s load limit, as on CI, plus slack.
|
||||
await direct.waitForFunction(() => window.__playerError !== undefined, { timeout: 36_000 });
|
||||
const sealedError = String(await direct.evaluate(() => window.__playerError));
|
||||
assert.match(
|
||||
sealedError,
|
||||
/include the runtime script/,
|
||||
"a sealed timeout must name the runtime script",
|
||||
);
|
||||
assert.match(sealedError, /without sandbox-origin/, "a sealed timeout must name the trusted way");
|
||||
|
||||
const elsewhere = await browser.newPage();
|
||||
await elsewhere.goto(`${server.origin}/host.html?fixture=direct-timeline`, {
|
||||
waitUntil: "domcontentloaded",
|
||||
});
|
||||
await elsewhere.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
|
||||
await elsewhere.evaluate(
|
||||
(url) => {
|
||||
document.querySelector("hyperframes-player")!.setAttribute("src", url);
|
||||
},
|
||||
`${server.origin.replace("127.0.0.1", "localhost")}/fixtures/direct-timeline/index.html`,
|
||||
);
|
||||
// Linux's 30 s load limit, as on CI, plus slack.
|
||||
await elsewhere.waitForFunction(() => window.__playerError !== undefined, { timeout: 36_000 });
|
||||
assert.doesNotMatch(
|
||||
String(await elsewhere.evaluate(() => window.__playerError)),
|
||||
/sandbox-origin/,
|
||||
"a default player with a composition on another origin is not told it is sealed",
|
||||
);
|
||||
|
||||
const trusted = await browser.newPage();
|
||||
await trusted.goto(`${server.origin}/host.html?fixture=direct-timeline`, {
|
||||
waitUntil: "domcontentloaded",
|
||||
});
|
||||
await trusted.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
|
||||
assert.equal(
|
||||
await trusted.evaluate(() => window.__playerDuration),
|
||||
5,
|
||||
"a default player must still add the runtime to a composition that has none",
|
||||
);
|
||||
|
||||
const bundled = await browser.newPage();
|
||||
await bundled.goto(`${server.origin}/host.html?fixture=direct-timeline-runtime&sealed=1`, {
|
||||
waitUntil: "domcontentloaded",
|
||||
});
|
||||
await bundled.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
|
||||
assert.equal(
|
||||
await bundled.evaluate(() => window.__playerDuration),
|
||||
5,
|
||||
"a sealed player must play a composition that brings the runtime script",
|
||||
);
|
||||
|
||||
// fails without the fix: the old document's timeline, landing after a switch, made the new load skip its probe.
|
||||
const switched = await browser.newPage();
|
||||
@@ -70,21 +133,25 @@ try {
|
||||
() => (window as { __lastTimeline?: unknown }).__lastTimeline !== undefined,
|
||||
{ timeout: 15_000 },
|
||||
);
|
||||
const lateError = await switched.evaluate(async () => {
|
||||
const w = window as { __lastTimeline?: unknown; __playerError?: string };
|
||||
const player = document.querySelector("hyperframes-player")!;
|
||||
const frame = player.shadowRoot!.querySelector("iframe")!;
|
||||
w.__playerError = undefined;
|
||||
player.setAttribute("src", "/fixtures/sandbox-probe/index.html");
|
||||
dispatchEvent(
|
||||
new MessageEvent("message", { data: w.__lastTimeline, source: frame.contentWindow }),
|
||||
);
|
||||
const started = performance.now();
|
||||
// Linux's 30 s load limit, as on CI, plus slack.
|
||||
while (performance.now() - started < 36_000 && w.__playerError === undefined)
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
return w.__playerError ?? null;
|
||||
});
|
||||
// From another origin, since a same-site film gets the runtime added.
|
||||
const lateError = await switched.evaluate(
|
||||
async (url) => {
|
||||
const w = window as { __lastTimeline?: unknown; __playerError?: string };
|
||||
const player = document.querySelector("hyperframes-player")!;
|
||||
const frame = player.shadowRoot!.querySelector("iframe")!;
|
||||
w.__playerError = undefined;
|
||||
player.setAttribute("src", url);
|
||||
dispatchEvent(
|
||||
new MessageEvent("message", { data: w.__lastTimeline, source: frame.contentWindow }),
|
||||
);
|
||||
const started = performance.now();
|
||||
// Linux's 30 s load limit, as on CI, plus slack.
|
||||
while (performance.now() - started < 36_000 && w.__playerError === undefined)
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
return w.__playerError ?? null;
|
||||
},
|
||||
`${server.origin.replace("127.0.0.1", "localhost")}/fixtures/sandbox-probe/index.html`,
|
||||
);
|
||||
assert.ok(
|
||||
lateError,
|
||||
"a sealed player switched to a film with no runtime must fail, even after a late old timeline",
|
||||
|
||||
@@ -6,9 +6,15 @@ import { startServer } from "../perf/server.js";
|
||||
const server = startServer();
|
||||
const browser = await launchBrowser({ autoplay: "gesture" });
|
||||
|
||||
try {
|
||||
type Player = HTMLElement & {
|
||||
play: () => void;
|
||||
_audioOwner: string;
|
||||
_parentMedia: { el: HTMLMediaElement }[];
|
||||
};
|
||||
|
||||
async function copiesOf(fixture: string) {
|
||||
const page = await browser.newPage();
|
||||
await page.goto(`${server.origin}/host.html?fixture=sealed-audio`, {
|
||||
await page.goto(`${server.origin}/host.html?fixture=${fixture}`, {
|
||||
waitUntil: "domcontentloaded",
|
||||
});
|
||||
await page.waitForFunction(() => window.__playerReady || window.__playerError, {
|
||||
@@ -23,11 +29,6 @@ try {
|
||||
await page.waitForFunction(() => window.__playerReady || window.__playerError, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
type Player = HTMLElement & {
|
||||
play: () => void;
|
||||
_audioOwner: string;
|
||||
_parentMedia: { el: HTMLMediaElement }[];
|
||||
};
|
||||
await page.evaluate(() => (document.getElementById("player") as Player).play());
|
||||
await page.waitForFunction(
|
||||
() => (document.getElementById("player") as Player)._audioOwner === "parent",
|
||||
@@ -36,11 +37,21 @@ try {
|
||||
const copies = await page.evaluate(() =>
|
||||
(document.getElementById("player") as Player)._parentMedia.map((m) => m.el.src),
|
||||
);
|
||||
await page.close();
|
||||
return copies;
|
||||
}
|
||||
|
||||
try {
|
||||
assert.deepEqual(
|
||||
copies,
|
||||
await copiesOf("sealed-audio"),
|
||||
[`${server.origin}/fixtures/sealed-audio/tone.m4a`],
|
||||
"a sealed player loaded by src copies its film's sound into the page when the frame may not start it",
|
||||
);
|
||||
assert.deepEqual(
|
||||
await copiesOf("sealed-audio-bare"),
|
||||
[`${server.origin}/fixtures/sealed-audio-bare/tone.m4a`],
|
||||
"a film without the runtime, shown sealed as srcdoc, still has its sound copied once",
|
||||
);
|
||||
console.log("[sealed-audio] a refused sealed frame's sound plays from a copy in the page");
|
||||
} finally {
|
||||
await browser.close();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,95 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { launchBrowser } from "../perf/runner.js";
|
||||
import { startServer } from "../perf/server.js";
|
||||
|
||||
const server = startServer();
|
||||
const browser = await launchBrowser();
|
||||
|
||||
type VideoState = { crossOrigin: string | null; readyState: number; error: number | null };
|
||||
|
||||
/** A sealed player playing the 10-video film from a host with or without CORS headers. */
|
||||
async function play(cors: boolean) {
|
||||
const page = await browser.newPage();
|
||||
const warnings: string[] = [];
|
||||
page.on("console", (message) => {
|
||||
if (message.type() === "warn") warnings.push(message.text());
|
||||
});
|
||||
await page.goto(
|
||||
`${server.origin}/host.html?fixture=10-video-grid&sealed=1${cors ? "" : "&cors=0"}`,
|
||||
{
|
||||
waitUntil: "domcontentloaded",
|
||||
},
|
||||
);
|
||||
await page.waitForFunction(() => window.__playerReady || window.__playerError, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
await page.evaluate(() =>
|
||||
(document.getElementById("player") as HTMLElement & { play: () => void }).play(),
|
||||
);
|
||||
// A sealed same-site film is shown as srcdoc: reach its frame through the player, not by URL.
|
||||
const frame = await (
|
||||
await page.evaluateHandle(
|
||||
() => document.getElementById("player")!.shadowRoot!.querySelector("iframe")!,
|
||||
)
|
||||
)
|
||||
.asElement()!
|
||||
.contentFrame();
|
||||
assert.ok(frame, "the film's frame must load");
|
||||
await frame.waitForFunction(
|
||||
() => [...document.querySelectorAll("video")].every((v) => v.readyState >= 2 || v.error),
|
||||
{ timeout: 30_000 },
|
||||
);
|
||||
const videos: VideoState[] = await frame.evaluate(() =>
|
||||
[...document.querySelectorAll("video")].map((v) => ({
|
||||
crossOrigin: v.getAttribute("crossorigin"),
|
||||
readyState: v.readyState,
|
||||
error: v.error?.code ?? null,
|
||||
})),
|
||||
);
|
||||
const pixels = await frame.evaluate(() => {
|
||||
const video = document.querySelector("video")!;
|
||||
const canvas = document.createElement("canvas");
|
||||
const context = canvas.getContext("2d")!;
|
||||
context.drawImage(video, 0, 0, 1, 1);
|
||||
try {
|
||||
context.getImageData(0, 0, 1, 1);
|
||||
return "readable";
|
||||
} catch {
|
||||
return "refused";
|
||||
}
|
||||
});
|
||||
await page.close();
|
||||
return { videos, pixels, warnings };
|
||||
}
|
||||
|
||||
try {
|
||||
const plain = await play(false);
|
||||
assert.equal(
|
||||
plain.videos.filter((v) => v.readyState >= 2 && v.error === null).length,
|
||||
10,
|
||||
`a sealed film on a host without CORS must still play all 10 videos: ${JSON.stringify(plain.videos)}`,
|
||||
);
|
||||
assert.ok(
|
||||
plain.videos.every((v) => v.crossOrigin === null),
|
||||
"a video whose CORS load failed plays without crossorigin",
|
||||
);
|
||||
const named = plain.warnings.filter((w) => w.includes("10-video-grid/sample.mp4"));
|
||||
assert.equal(named.length, 10, `the fallback is said once per video: ${JSON.stringify(named)}`);
|
||||
|
||||
const shared = await play(true);
|
||||
assert.equal(
|
||||
shared.videos.filter((v) => v.crossOrigin === "anonymous" && v.readyState >= 2).length,
|
||||
10,
|
||||
`a sealed film on a CORS host keeps crossorigin: ${JSON.stringify(shared.videos)}`,
|
||||
);
|
||||
assert.equal(shared.pixels, "readable", "a CORS-loaded video's pixels can be read");
|
||||
assert.deepEqual(
|
||||
shared.warnings.filter((w) => w.includes("sample.mp4")),
|
||||
[],
|
||||
);
|
||||
console.log("[sealed-media] a host without CORS plays; a CORS host keeps pixel access");
|
||||
} finally {
|
||||
await browser.close();
|
||||
await server.stop();
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { launchBrowser } from "../perf/runner.js";
|
||||
import { startServer } from "../perf/server.js";
|
||||
|
||||
const PLAYER_DIST = join(import.meta.dirname, "../../dist");
|
||||
const server = startServer();
|
||||
const browser = await launchBrowser();
|
||||
|
||||
type Player = HTMLElement & { play(): void; currentTime: number };
|
||||
|
||||
/** A sealed player given a same-site composition by URL, as an embedder writes it, with nothing added. */
|
||||
async function play(fixture: string) {
|
||||
const page = await browser.newPage();
|
||||
const elsewhere: string[] = [];
|
||||
page.on("request", (request) => {
|
||||
const url = request.url();
|
||||
if (/^https?:/.test(url) && new URL(url).origin !== server.origin) elsewhere.push(url);
|
||||
});
|
||||
await page.goto(`${server.origin}/host.html?fixture=${fixture}&sealed=1`, {
|
||||
waitUntil: "domcontentloaded",
|
||||
});
|
||||
await page.waitForFunction(() => window.__playerReady || window.__playerError, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
const error = await page.evaluate(() => window.__playerError ?? null);
|
||||
await page.evaluate(() => (document.getElementById("player") as Player).play());
|
||||
await page
|
||||
.waitForFunction(() => (document.getElementById("player") as Player).currentTime > 0.3, {
|
||||
timeout: 10_000,
|
||||
})
|
||||
.catch(() => {});
|
||||
const time = await page.evaluate(() => (document.getElementById("player") as Player).currentTime);
|
||||
const iframe = await page.evaluateHandle(
|
||||
() => document.getElementById("player")!.shadowRoot!.querySelector("iframe")!,
|
||||
);
|
||||
const frame = await iframe.asElement()!.contentFrame();
|
||||
const inFrame = await frame!.evaluate(() => ({
|
||||
origin: window.origin,
|
||||
runtimes: [...document.scripts].filter(
|
||||
(s) => s.src.includes("hyperframe.runtime") || s.text.includes("__hyperframes"),
|
||||
).length,
|
||||
moved: getComputedStyle(document.getElementById("box")!).transform,
|
||||
}));
|
||||
await page.close();
|
||||
return { error, time, elsewhere, ...inFrame };
|
||||
}
|
||||
|
||||
/** A page with its scripts inlined, as a CLI render carries the runtime: a sealed srcdoc can't fetch loopback files. */
|
||||
async function inlinedScripts(path: string): Promise<string> {
|
||||
const read = async (url: string) => (await fetch(`${server.origin}${url}`)).text();
|
||||
let html = await read(path);
|
||||
for (const src of ["/vendor/gsap.min.js", "/vendor/hyperframe.runtime.iife.js"]) {
|
||||
const code = (await read(src)).replace(/<\/script/gi, "<\\/script");
|
||||
html = html.replace(` src="${src}"></script>`, () => `>${code}</script>`);
|
||||
}
|
||||
return html;
|
||||
}
|
||||
|
||||
async function playAsModule(sealed: boolean, load: { src: string } | { srcdocFrom: string }) {
|
||||
const page = await browser.newPage();
|
||||
const asked: string[] = [];
|
||||
await page.setRequestInterception(true);
|
||||
page.on("request", (request) => {
|
||||
const path = new URL(request.url()).pathname;
|
||||
asked.push(path);
|
||||
const options = sealed ? ' sandbox-origin="opaque"' : "";
|
||||
if (path === "/module-host.html") {
|
||||
void request.respond({
|
||||
contentType: "text/html",
|
||||
body: `<!doctype html><script type="module" src="/module/hyperframes-player.js"></script>
|
||||
<hyperframes-player id="player"${options} width="640" height="360" muted></hyperframes-player>`,
|
||||
});
|
||||
} else if (path.startsWith("/module/")) {
|
||||
void request.respond({
|
||||
contentType: "text/javascript",
|
||||
body: readFileSync(join(PLAYER_DIST, path.slice("/module/".length))),
|
||||
});
|
||||
} else void request.continue();
|
||||
});
|
||||
await page.goto(`${server.origin}/module-host.html`, { waitUntil: "domcontentloaded" });
|
||||
await page.waitForFunction(() => customElements.get("hyperframes-player") !== undefined);
|
||||
const srcdoc = "srcdocFrom" in load ? await inlinedScripts(load.srcdocFrom) : null;
|
||||
const outcome = await page.evaluate(
|
||||
(src, html) =>
|
||||
new Promise<string>((resolve) => {
|
||||
const el = document.getElementById("player")!;
|
||||
el.addEventListener("ready", () => resolve("ready"));
|
||||
el.addEventListener("error", (e) => resolve(String((e as CustomEvent).detail?.message)));
|
||||
if (html === null) el.setAttribute("src", src!);
|
||||
else el.setAttribute("srcdoc", html);
|
||||
}),
|
||||
"src" in load ? load.src : null,
|
||||
srcdoc,
|
||||
);
|
||||
let time = 0;
|
||||
if (outcome === "ready") {
|
||||
await page.evaluate(() => (document.getElementById("player") as Player).play());
|
||||
await page
|
||||
.waitForFunction(() => (document.getElementById("player") as Player).currentTime > 0.3, {
|
||||
timeout: 10_000,
|
||||
})
|
||||
.catch(() => {});
|
||||
time = await page.evaluate(() => (document.getElementById("player") as Player).currentTime);
|
||||
}
|
||||
await page.close();
|
||||
return { outcome, time, readRuntime: asked.includes("/module/hyperframe.runtime.iife.js") };
|
||||
}
|
||||
|
||||
try {
|
||||
const bare = await play("direct-timeline");
|
||||
assert.equal(bare.error, null, `a sealed composition with no runtime must load: ${bare.error}`);
|
||||
assert.equal(bare.origin, "null", "the frame stays sealed");
|
||||
assert.ok(bare.time > 0.3, `it plays: currentTime ${bare.time}`);
|
||||
assert.notEqual(bare.moved, "none", "its animation runs");
|
||||
assert.equal(bare.runtimes, 1, "the player adds the runtime once");
|
||||
assert.deepEqual(bare.elsewhere, [], "nothing is fetched from another origin");
|
||||
|
||||
const carried = await play("direct-timeline-runtime");
|
||||
assert.equal(
|
||||
carried.error,
|
||||
null,
|
||||
`a sealed composition with its own runtime loads: ${carried.error}`,
|
||||
);
|
||||
assert.equal(carried.runtimes, 1, "a composition carrying the runtime gets no second copy");
|
||||
// fails without the fix: the ES build's bare runtime import can't resolve without a bundler.
|
||||
for (const load of [
|
||||
{ src: "/fixtures/direct-timeline/index.html" },
|
||||
{ srcdocFrom: "/fixtures/direct-timeline-runtime/index.html" },
|
||||
]) {
|
||||
const open = await playAsModule(false, load);
|
||||
const sealed = await playAsModule(true, load);
|
||||
assert.equal(open.outcome, "ready", `unsealed, the module page plays ${JSON.stringify(load)}`);
|
||||
assert.equal(sealed.outcome, "ready", `sealed, it plays as unsealed: ${sealed.outcome}`);
|
||||
assert.ok(sealed.time > 0.3, `sealed, it plays: currentTime ${sealed.time}`);
|
||||
assert.equal(
|
||||
sealed.readRuntime,
|
||||
"src" in load,
|
||||
"only a composition without its own runtime reads the file beside the module",
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
"[sealed-runtime] a sealed same-site composition plays with the runtime the player ships",
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
await server.stop();
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Direct GSAP timeline with the runtime</title>
|
||||
<script src="/vendor/gsap.min.js"></script>
|
||||
<script data-hyperframes-runtime="1" src="/vendor/hyperframe.runtime.iife.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div
|
||||
id="root"
|
||||
data-composition-id="main"
|
||||
data-width="1920"
|
||||
data-height="1080"
|
||||
data-duration="5"
|
||||
>
|
||||
<div id="box" style="width: 100px; height: 100px; background: #3b82f6"></div>
|
||||
</div>
|
||||
<script>
|
||||
const tl = gsap.timeline({ paused: true });
|
||||
tl.to("#box", { x: 400, duration: 5 });
|
||||
window.__timelines = { main: tl };
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Direct GSAP timeline, no runtime</title>
|
||||
<script src="/vendor/gsap.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="box" style="width: 100px; height: 100px; background: #3b82f6"></div>
|
||||
<script>
|
||||
const tl = gsap.timeline({ paused: true });
|
||||
tl.to("#box", { x: 400, duration: 5 });
|
||||
window.__timelines = { main: tl };
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,27 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>perf fixture: sealed-audio-bare</title>
|
||||
<script src="/vendor/gsap.min.js"></script>
|
||||
</head>
|
||||
<body style="margin: 0; background: #050714">
|
||||
<div
|
||||
id="root"
|
||||
data-composition-id="main"
|
||||
data-width="640"
|
||||
data-height="360"
|
||||
data-duration="4"
|
||||
data-fps="30"
|
||||
>
|
||||
<div id="card" style="width: 640px; height: 360px; background: #2a6"></div>
|
||||
<audio id="tone" src="tone.m4a" data-start="0" data-duration="4" preload="auto"></audio>
|
||||
</div>
|
||||
<script>
|
||||
var tl = gsap.timeline({ paused: true });
|
||||
tl.fromTo("#card", { opacity: 0.5 }, { opacity: 1, duration: 4 }, 0);
|
||||
window.__timelines = window.__timelines || {};
|
||||
window.__timelines["main"] = tl;
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
@@ -14,10 +14,17 @@ import { fileURLToPath } from "node:url";
|
||||
* URL routes:
|
||||
* / → host.html (default fixture: gsap-heavy)
|
||||
* /host.html?fixture=<name> → embed page hosting <hyperframes-player>
|
||||
* /host.html?...&sealed=1 → the same with sandbox-origin="opaque"
|
||||
* /host.html?...&cors=0 → the film from /fixtures-no-cors/, a host that sends no CORS headers
|
||||
* /player/hyperframes-player.global.js
|
||||
* /player/hyperframe.runtime.iife.js → the runtime file shipped beside it
|
||||
* /vendor/gsap.min.js
|
||||
* /vendor/hyperframe.runtime.iife.js
|
||||
* /fixtures/<name>/<file> → fixture HTML + assets
|
||||
* /fixtures-flaky/<name>/<file> → as /fixtures/, but a 503 the first time each URL is asked (?fail=N: N times)
|
||||
* /fixtures-lapse/<name>/<file>?id=… → a 503 until recover(id), then the file (CORS headers only with ?cors)
|
||||
* ...?delay=ms → the first answer for that URL comes that much later
|
||||
* ...?no-store → never cached, so every load reaches the server
|
||||
*/
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
@@ -33,6 +40,7 @@ function firstExisting(candidates: string[]): string {
|
||||
|
||||
const PATHS = {
|
||||
player: join(PLAYER_PKG, "dist/hyperframes-player.global.js"),
|
||||
playerRuntime: join(PLAYER_PKG, "dist/hyperframe.runtime.iife.js"),
|
||||
runtime: join(REPO_ROOT, "packages/core/dist/hyperframe.runtime.iife.js"),
|
||||
// bun installs gsap into the package's node_modules in workspace mode, but
|
||||
// hoists it to the repo root if multiple packages share the same version.
|
||||
@@ -53,6 +61,9 @@ export type ServeOptions = {
|
||||
export type RunningServer = {
|
||||
port: number;
|
||||
origin: string;
|
||||
/** Every URL asked for, in order. */
|
||||
requested: string[];
|
||||
recover(id: string): void;
|
||||
stop(): Promise<void>;
|
||||
};
|
||||
|
||||
@@ -79,9 +90,15 @@ function mimeFor(path: string): string {
|
||||
return MIME_TYPES[path.slice(dot).toLowerCase()] ?? "application/octet-stream";
|
||||
}
|
||||
|
||||
function buildHostHtml(fixtureName: string, width: number, height: number): string {
|
||||
function buildHostHtml(
|
||||
fixtureName: string,
|
||||
width: number,
|
||||
height: number,
|
||||
sealed: boolean,
|
||||
cors = true,
|
||||
): string {
|
||||
const playerSrc = "/player/hyperframes-player.global.js";
|
||||
const fixtureSrc = `/fixtures/${fixtureName}/index.html`;
|
||||
const fixtureSrc = `/${cors ? "fixtures" : "fixtures-no-cors"}/${fixtureName}/index.html`;
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
@@ -94,7 +111,7 @@ function buildHostHtml(fixtureName: string, width: number, height: number): stri
|
||||
</head>
|
||||
<body>
|
||||
<hyperframes-player
|
||||
id="player"
|
||||
id="player"${sealed ? '\n sandbox-origin="opaque"' : ""}
|
||||
src="${fixtureSrc}"
|
||||
width="${width}"
|
||||
height="${height}"
|
||||
@@ -159,17 +176,29 @@ function applyCacheHeaders(res: Response, noCache: boolean): Response {
|
||||
export function startServer(options: ServeOptions = {}): RunningServer {
|
||||
const noCache = options.noCache ?? false;
|
||||
|
||||
const failures = new Map<string, number>();
|
||||
const requested: string[] = [];
|
||||
const recovered = new Set<string>();
|
||||
const delayed = new Set<string>();
|
||||
const server = Bun.serve({
|
||||
port: options.port ?? 0,
|
||||
async fetch(req) {
|
||||
const url = new URL(req.url);
|
||||
requested.push(url.href);
|
||||
const path = url.pathname;
|
||||
|
||||
if (path === "/" || path === "/host.html") {
|
||||
const fixture = url.searchParams.get("fixture") || "gsap-heavy";
|
||||
const width = Number(url.searchParams.get("width") || "1920");
|
||||
const height = Number(url.searchParams.get("height") || "1080");
|
||||
const html = buildHostHtml(fixture, width, height);
|
||||
const params = url.searchParams;
|
||||
const html = buildHostHtml(
|
||||
fixture,
|
||||
width,
|
||||
height,
|
||||
params.get("sealed") === "1",
|
||||
params.get("cors") !== "0",
|
||||
);
|
||||
return applyCacheHeaders(
|
||||
new Response(html, { headers: { "Content-Type": "text/html; charset=utf-8" } }),
|
||||
noCache,
|
||||
@@ -180,6 +209,11 @@ export function startServer(options: ServeOptions = {}): RunningServer {
|
||||
return applyCacheHeaders(await readBunFile(PATHS.player), noCache);
|
||||
}
|
||||
|
||||
// Beside the bundle, as an embedder hosting the player's dist serves it: a sealed player loads it.
|
||||
if (path === "/player/hyperframe.runtime.iife.js") {
|
||||
return applyCacheHeaders(await readBunFile(PATHS.playerRuntime), noCache);
|
||||
}
|
||||
|
||||
if (path === "/vendor/hyperframe.runtime.iife.js") {
|
||||
return applyCacheHeaders(await readBunFile(PATHS.runtime), noCache);
|
||||
}
|
||||
@@ -188,15 +222,38 @@ export function startServer(options: ServeOptions = {}): RunningServer {
|
||||
return applyCacheHeaders(await readBunFile(PATHS.gsap), noCache);
|
||||
}
|
||||
|
||||
if (path.startsWith("/fixtures/")) {
|
||||
const rel = path.replace(/^\/fixtures\//, "");
|
||||
const filePath = join(PATHS.fixturesDir, rel);
|
||||
const served = /^\/(fixtures|fixtures-no-cors|fixtures-flaky|fixtures-lapse)\//.exec(path);
|
||||
const failed = failures.get(url.href) ?? 0;
|
||||
const delay = Number(url.searchParams.get("delay") ?? 0);
|
||||
if (served && delay > 0 && !delayed.has(url.href)) {
|
||||
delayed.add(url.href);
|
||||
await new Promise((wake) => setTimeout(wake, delay));
|
||||
}
|
||||
const lapsed =
|
||||
served?.[1] === "fixtures-lapse" && !recovered.has(url.searchParams.get("id") ?? "");
|
||||
if (
|
||||
lapsed ||
|
||||
(served?.[1] === "fixtures-flaky" && failed < Number(url.searchParams.get("fail") ?? 1))
|
||||
) {
|
||||
failures.set(url.href, failed + 1);
|
||||
return new Response("Busy", {
|
||||
status: 503,
|
||||
headers: { "Access-Control-Allow-Origin": "*" },
|
||||
});
|
||||
}
|
||||
if (served) {
|
||||
const filePath = join(PATHS.fixturesDir, path.slice(served[0].length));
|
||||
if (!filePath.startsWith(PATHS.fixturesDir)) {
|
||||
return new Response("Forbidden", { status: 403 });
|
||||
}
|
||||
// A sealed player's film has an opaque origin and loads its own media with CORS, as from a CORS-capable host.
|
||||
const res = applyCacheHeaders(await readBunFile(filePath), noCache);
|
||||
// A sealed film has an opaque origin, so it reads its own media as from a CORS host.
|
||||
res.headers.set("Access-Control-Allow-Origin", "*");
|
||||
const cors =
|
||||
served[1] === "fixtures-lapse"
|
||||
? url.searchParams.has("cors")
|
||||
: served[1] !== "fixtures-no-cors";
|
||||
if (cors) res.headers.set("Access-Control-Allow-Origin", "*");
|
||||
if (url.searchParams.has("no-store")) res.headers.set("Cache-Control", "no-store");
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -214,6 +271,8 @@ export function startServer(options: ServeOptions = {}): RunningServer {
|
||||
return {
|
||||
port,
|
||||
origin: `http://127.0.0.1:${port}`,
|
||||
requested,
|
||||
recover: (id: string) => void recovered.add(id),
|
||||
async stop() {
|
||||
server.stop(true);
|
||||
},
|
||||
|
||||
@@ -1,20 +1,51 @@
|
||||
import { defineConfig } from "tsup";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { copyFileSync, readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
const packageVersion = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"))
|
||||
.version as string;
|
||||
|
||||
export default defineConfig({
|
||||
const RUNTIME_FILE = "hyperframe.runtime.iife.js";
|
||||
const coreDist = join(
|
||||
dirname(createRequire(import.meta.url).resolve("@hyperframes/core/package.json")),
|
||||
"dist",
|
||||
);
|
||||
|
||||
const shared = {
|
||||
entry: ["src/hyperframes-player.ts", "src/slideshow/hyperframes-slideshow.ts"],
|
||||
format: ["esm", "cjs", "iife"],
|
||||
globalName: "HyperframesPlayer",
|
||||
noExternal: ["@hyperframes/core"],
|
||||
dts: true,
|
||||
clean: true,
|
||||
minify: true,
|
||||
define: {
|
||||
__HYPERFRAMES_RUNTIME_CDN_URL__: JSON.stringify(
|
||||
`https://cdn.jsdelivr.net/npm/@hyperframes/core@${packageVersion}/dist/hyperframe.runtime.iife.js`,
|
||||
`https://cdn.jsdelivr.net/npm/@hyperframes/core@${packageVersion}/dist/${RUNTIME_FILE}`,
|
||||
),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export default defineConfig([
|
||||
// An app's bundler takes the runtime from core, which the player depends on, as a chunk loaded only when needed.
|
||||
{
|
||||
...shared,
|
||||
format: ["esm"],
|
||||
dts: true,
|
||||
clean: true,
|
||||
esbuildOptions: (options) => {
|
||||
options.external = [...(options.external ?? []), "@hyperframes/core/runtime-script"];
|
||||
},
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
format: ["cjs", "iife"],
|
||||
// These formats cannot split a chunk out, so the runtime stays a file beside them.
|
||||
esbuildOptions: (options) => {
|
||||
options.alias = {
|
||||
...options.alias,
|
||||
"@hyperframes/core/runtime-script": "./src/runtime-beside-bundle.ts",
|
||||
};
|
||||
options.define = { ...options.define, "import.meta.url": "undefined" };
|
||||
},
|
||||
onSuccess: async () => copyFileSync(join(coreDist, RUNTIME_FILE), join("dist", RUNTIME_FILE)),
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { studioApiFetch } from "../utils/studioApiFetch";
|
||||
|
||||
export async function getHyperframeRuntimeScript(): Promise<string> {
|
||||
const response = await studioApiFetch("/api/runtime.js");
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
return response.text();
|
||||
}
|
||||
@@ -376,6 +376,11 @@ export default defineConfig({
|
||||
// openComposition and silently loses its SDK session. See the stub.
|
||||
canvas: resolve(__dirname, "src/shims/canvasBrowserStub.js"),
|
||||
"@hyperframes/player": resolve(__dirname, "../player/src/hyperframes-player.ts"),
|
||||
// Studio serves the runtime itself, so the player it bundles carries no second copy.
|
||||
"@hyperframes/core/runtime-script": resolve(
|
||||
__dirname,
|
||||
"src/shims/runtimeScriptFromStudio.ts",
|
||||
),
|
||||
"@hyperframes/studio-server/source-mutation": resolve(
|
||||
__dirname,
|
||||
"../studio-server/src/helpers/sourceMutation.ts",
|
||||
|
||||
@@ -32,8 +32,8 @@
|
||||
"unpacked": 915000
|
||||
},
|
||||
"@hyperframes/player": {
|
||||
"packed": 172000,
|
||||
"unpacked": 590000
|
||||
"packed": 437000,
|
||||
"unpacked": 1396000
|
||||
},
|
||||
"@hyperframes/producer": {
|
||||
"packed": 1065767,
|
||||
|
||||
Reference in New Issue
Block a user