import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import type { Browser, Frame, Page } from "puppeteer-core";
import { afterAll, beforeAll, expect, it, vi } from "vitest";
import { closeTestChrome, launchTestChrome } from "../../../tests/chromeTestUtils";
import { buildStudioBundle } from "../../../tests/sealedPreviewHarness";
import { PARITY_MODES as MODES } from "../../../tests/parityModes";
import type { MountedPlayer } from "../../../tests/playerMount";
import { RUNTIME_BOOTSTRAP_ATTR } from "@hyperframes/core/compiler";
vi.setConfig({ testTimeout: 90_000, hookTimeout: 60_000 });
const require = createRequire(import.meta.url);
const ORIGIN = "http://studio.test";
const TOKEN = "t".repeat(43);
// The player's load check gives up after 30 s on Linux; the slow runtime file answers after that.
const LINUX_UA =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/158.0.0.0 Safari/537.36";
const RUNTIME_LATE_MS = 32_000;
let browser: Browser;
let bundle: string;
let runtime: string;
beforeAll(async () => {
browser = await launchTestChrome();
bundle = await buildStudioBundle([`export { mountPlayer } from "../tests/playerMount";`]);
runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8");
});
afterAll(() => closeTestChrome(browser));
type Host = { mounted: MountedPlayer };
const RUNTIME_TAG = ``;
// Links the runtime once the page has loaded, so the player's check starts before the runtime can answer.
const RUNTIME_AT_LOAD = ``;
/** A two-clip film as Studio's server answers a project preview: clip b shows from 1 s. */
const film = (head: string, body = "") => `
${head}
${body}`;
async function openStudio(mode: string, html: string, runtimeDelayMs = 0) {
const page: Page = await browser.newPage();
if (runtimeDelayMs) {
const cdp = await page.createCDPSession();
await cdp.send("Emulation.setUserAgentOverride", {
userAgent: LINUX_UA,
platform: "Linux",
userAgentMetadata: {
platform: "Linux",
platformVersion: "",
architecture: "x86",
model: "",
mobile: false,
},
});
}
const files: Record = {
"/": {
type: "text/html",
body: ``,
},
"/api/projects/p/frame-token": {
type: "application/json",
body: JSON.stringify({ token: TOKEN }),
},
"/api/projects/p/preview": { type: "text/html", body: html },
[`/api/projects/p/preview/~${TOKEN}`]: { type: "text/html", body: html },
"/runtime.js": { type: "text/javascript", body: runtime },
};
await page.setRequestInterception(true);
page.on("request", (request) => {
const path = new URL(request.url()).pathname;
const file = files[path];
if (!file) return void request.respond({ status: 404, body: "" });
const answer = () =>
request.respond({
status: 200,
contentType: file.type,
headers: { "Access-Control-Allow-Origin": "*" },
body: file.body,
});
if (path === "/runtime.js" && runtimeDelayMs) setTimeout(answer, runtimeDelayMs);
else void answer();
});
await page.goto(`${ORIGIN}/`);
await page.evaluate(bundle);
await page.evaluate((sealed) => {
const w = window as unknown as Host & {
hfStudio: { mountPlayer(host: HTMLElement, id: string, sealed: boolean): MountedPlayer };
};
w.mounted = w.hfStudio.mountPlayer(document.getElementById("app")!, "p", sealed);
}, mode === "sealed");
return { page };
}
async function filmFrame(page: Page): Promise {
const handle = await page.waitForFunction(() => (window as unknown as Host).mounted.frame());
return (await handle.asElement()!.contentFrame())!;
}
const shown = (page: Page) =>
page.waitForFunction(() => (window as unknown as Host).mounted.readyToShow, { timeout: 60_000 });
const state = (page: Page) =>
page.evaluate(() => {
const m = (window as unknown as Host).mounted;
return { sealed: m.sealed(), errors: m.errors, errorShown: m.errorShown() };
});
it.each(MODES)("Studio's preview loads and plays in a %s preview", async (mode) => {
const { page } = await openStudio(mode, film(RUNTIME_TAG));
await shown(page);
expect(await state(page)).toEqual({ sealed: mode === "sealed", errors: [], errorShown: false });
const frame = await filmFrame(page);
const secondClipShown = () =>
frame.evaluate(() => getComputedStyle(document.getElementById("b")!).visibility !== "hidden");
expect(await secondClipShown()).toBe(false);
await page.evaluate(() => (window as unknown as Host).mounted.play());
await frame.waitForFunction(
() => (window as unknown as { __player: { getTime(): number } }).__player.getTime() > 1.2,
{ timeout: 10_000 },
);
expect(await secondClipShown()).toBe(true);
await page.close();
});
it.each(MODES)(
"a %s preview whose runtime answers after the player's load check still comes up",
async (mode) => {
const { page } = await openStudio(mode, film("", RUNTIME_AT_LOAD), RUNTIME_LATE_MS);
await page.waitForFunction(() => (window as unknown as Host).mounted.errors.length > 0, {
timeout: 60_000,
});
await shown(page);
const after = await state(page);
expect(after.sealed).toBe(mode === "sealed");
expect(after.errors).toEqual([expect.stringContaining("not found after 30s")]);
expect(after.errorShown).toBe(false);
await page.close();
},
);