Merge remote-tracking branch 'origin/main' into feat/media-use-v2

# Conflicts:
#	skills-manifest.json
#	skills/media-use/audio/scripts/lib/python.mjs
#	skills/media-use/audio/scripts/lib/python.test.mjs
#	skills/media-use/audio/scripts/lib/sfx.test.mjs
#	skills/media-use/scripts/resolve.mjs
This commit is contained in:
Miguel Angel Simon Sierra
2026-07-05 21:31:45 -04:00
91 changed files with 4078 additions and 315 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/aws-lambda",
"version": "0.7.29",
"version": "0.7.36",
"description": "AWS Lambda adapter for HyperFrames distributed rendering — handler, client-side SDK, and CDK construct.",
"repository": {
"type": "git",
@@ -0,0 +1,14 @@
import { describe, expect, it } from "bun:test";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
describe("build-zip handler banner", () => {
it("defines CommonJS path globals for inlined CJS dependencies", () => {
const source = readFileSync(fileURLToPath(new URL("./build-zip.ts", import.meta.url)), "utf8");
expect(source).toContain('import { fileURLToPath as __hf_fileURLToPath } from "url";');
expect(source).toContain('import { dirname as __hf_dirname } from "path";');
expect(source).toContain("const __filename = __hf_fileURLToPath(import.meta.url);");
expect(source).toContain("const __dirname = __hf_dirname(__filename);");
});
});
+4
View File
@@ -252,6 +252,10 @@ async function bundleHandler(stagingDir: string): Promise<void> {
"// hyperframes-aws-lambda handler bundle",
'import { createRequire as __hf_createRequire } from "module";',
"const require = __hf_createRequire(import.meta.url);",
'import { fileURLToPath as __hf_fileURLToPath } from "url";',
'import { dirname as __hf_dirname } from "path";',
"const __filename = __hf_fileURLToPath(import.meta.url);",
"const __dirname = __hf_dirname(__filename);",
].join("\n"),
},
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/cli",
"version": "0.7.29",
"version": "0.7.36",
"description": "HyperFrames CLI — create, preview, and render HTML video compositions",
"repository": {
"type": "git",
+9
View File
@@ -1,5 +1,6 @@
import { execSync } from "node:child_process";
import { existsSync } from "node:fs";
import { resolve } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("node:child_process", () => ({ execSync: vi.fn() }));
@@ -23,6 +24,14 @@ afterEach(() => {
});
describe("findFFmpeg", () => {
it("prefers the real Windows exe when where lists a cmd shim first", async () => {
Object.defineProperty(process, "platform", { value: "win32", configurable: true });
mockExec.mockReturnValue("C:\\tools\\ffmpeg.cmd\r\nC:\\tools\\ffmpeg.exe\r\n");
const { findFFmpeg } = await import("./ffmpeg.js");
expect(findFFmpeg()).toBe(resolve("C:\\tools\\ffmpeg.exe"));
});
it("falls back to a common install dir when `which` fails (GUI-launched PATH)", async () => {
// Simulate a process whose PATH lacks /opt/homebrew/bin: `which ffmpeg` throws.
mockExec.mockImplementation(() => {
+22 -5
View File
@@ -7,6 +7,26 @@ import { detectLinuxDistro, ffmpegInstallCommand } from "./linuxDeps.js";
export const FFMPEG_PATH_ENV = "HYPERFRAMES_FFMPEG_PATH";
export const FFPROBE_PATH_ENV = "HYPERFRAMES_FFPROBE_PATH";
function chooseBestPathCandidate(
name: "ffmpeg" | "ffprobe",
candidates: string[],
): string | undefined {
const normalized = candidates.map((s) => s.trim()).filter(Boolean);
if (normalized.length === 0) return undefined;
const lowerName = name.toLowerCase();
const preferredExe = normalized.find((candidate) =>
candidate.toLowerCase().endsWith(`${lowerName}.exe`),
);
if (preferredExe) return preferredExe;
const exact = normalized.find((candidate) => candidate.toLowerCase().endsWith(lowerName));
if (exact) return exact;
const nonShellShim = normalized.find((candidate) => {
const lower = candidate.toLowerCase();
return !lower.endsWith(".cmd") && !lower.endsWith(".bat");
});
return nonShellShim ?? normalized[0];
}
function findOnPath(name: "ffmpeg" | "ffprobe"): string | undefined {
try {
const cmd = process.platform === "win32" ? `where ${name}` : `which ${name}`;
@@ -15,11 +35,8 @@ function findOnPath(name: "ffmpeg" | "ffprobe"): string | undefined {
stdio: ["pipe", "pipe", "pipe"],
timeout: 5000,
});
const first = output
.split(/\r?\n/)
.map((s) => s.trim())
.find(Boolean);
return first ? resolve(first) : undefined;
const candidate = chooseBestPathCandidate(name, output.split(/\r?\n/));
return candidate ? resolve(candidate) : undefined;
} catch {
return undefined;
}
+92 -14
View File
@@ -21,7 +21,7 @@
* `background-removal/manager.test.ts`) so we don't touch the real
* `HOME` cache.
*/
import { join } from "node:path";
import { join, sep } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// Use `path.join` so the fake paths line up with whatever separator Node's
@@ -30,7 +30,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// `/fake/home/...` literals would fail on Windows because the set lookup
// would never match the `\\`-joined real paths.
const FAKE_HOME = join("/", "fake", "home");
const CACHE_ROOT = join(FAKE_HOME, ".cache", "hyperframes");
const HF_CACHE = join(FAKE_HOME, ".cache", "hyperframes", "chrome");
const HF_LOCK = join(CACHE_ROOT, ".chrome.install.lock");
const HF_RECLAIM_LOCK = join(CACHE_ROOT, ".chrome.install.reclaim.lock");
const PUPPETEER_CACHE = join(FAKE_HOME, ".cache", "puppeteer", "chrome-headless-shell");
const PUPPETEER_BINARY = join(
PUPPETEER_CACHE,
@@ -75,8 +78,15 @@ function installFsMocks({ existing, dirs }: FsMockOptions) {
mtimes.set(p, Date.now());
},
rmSync: (p: string) => {
paths.delete(p);
mtimes.delete(p);
// Real rmSync({recursive:true}) removes the target AND everything under
// it; the mock's flat path Set has no real tree structure, so simulate
// that by also dropping any tracked path nested under `p`.
for (const existingPath of [...paths]) {
if (existingPath === p || existingPath.startsWith(p + sep)) {
paths.delete(existingPath);
mtimes.delete(existingPath);
}
}
},
statSync: (p: string) => {
if (!paths.has(p)) {
@@ -97,9 +107,10 @@ function installFsMocks({ existing, dirs }: FsMockOptions) {
function installPuppeteerBrowsersMock(
opts: {
installedInHfCache?: Array<{ browser: string; executablePath: string }>;
installedInHfCache?: Array<{ browser: string; executablePath: string; path?: string }>;
installedInHfCacheError?: Error;
installResult?: { executablePath: string };
installImpl?: () => Promise<{ executablePath: string }>;
} = {},
) {
vi.doMock("@puppeteer/browsers", () => ({
@@ -108,7 +119,11 @@ function installPuppeteerBrowsersMock(
getInstalledBrowsers: opts.installedInHfCacheError
? vi.fn().mockRejectedValue(opts.installedInHfCacheError)
: vi.fn().mockResolvedValue(opts.installedInHfCache ?? []),
install: vi.fn().mockResolvedValue(opts.installResult ?? { executablePath: HF_BINARY }),
install: vi
.fn()
.mockImplementation(
opts.installImpl ?? (async () => opts.installResult ?? { executablePath: HF_BINARY }),
),
}));
}
@@ -169,9 +184,15 @@ describe("findBrowser — cache resolution", () => {
"chrome-headless-shell-linux64",
"redownloaded-chrome-headless-shell",
);
installFsMocks({ existing: new Set([HF_CACHE]) });
const staleInstallDir = join(HF_CACHE, "chrome-headless-shell", "linux-131.0.6778.85");
// The stale install DIR is present (extraction got partway through, e.g. an
// ABOUT/LICENSE-only extract) even though the exe itself is missing —
// exercises the purge-before-redownload fix, not just the redownload path.
const paths = installFsMocks({ existing: new Set([HF_CACHE, staleInstallDir]) });
installPuppeteerBrowsersMock({
installedInHfCache: [{ browser: "chrome-headless-shell", executablePath: HF_BINARY }],
installedInHfCache: [
{ browser: "chrome-headless-shell", executablePath: HF_BINARY, path: staleInstallDir },
],
installResult: { executablePath: redownloadedBinary },
});
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
@@ -181,6 +202,67 @@ describe("findBrowser — cache resolution", () => {
expect(result).toEqual({ executablePath: redownloadedBinary, source: "download" });
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Cached binary missing"));
// The stale directory must be gone before @puppeteer/browsers' install()
// sees it — otherwise install() throws "folder exists but exe missing"
// instead of re-extracting (the exact bug both feedback reports hit).
expect(paths.has(staleInstallDir)).toBe(false);
});
it("ensureBrowser({force: true}) purges the whole cache before downloading, bypassing any cache/system shortcut", async () => {
const staleInstallDir = join(HF_CACHE, "chrome-headless-shell", "linux-131.0.6778.85");
const downloadedBinary = join(HF_CACHE, "chrome-headless-shell", "force-downloaded");
// A HEALTHY cached binary AND system Chrome are both present — force must
// ignore both shortcuts and always re-download, which is the whole point
// of the flag (the reported bug: --force did nothing, a stale dir kept
// winning over every retry).
const paths = installFsMocks({
existing: new Set([HF_CACHE, HF_BINARY, staleInstallDir, SYSTEM_CHROME]),
});
installPuppeteerBrowsersMock({
installedInHfCache: [
{ browser: "chrome-headless-shell", executablePath: HF_BINARY, path: staleInstallDir },
],
installResult: { executablePath: downloadedBinary },
});
const { ensureBrowser } = await import("./manager.js");
const result = await ensureBrowser({ force: true });
expect(result).toEqual({ executablePath: downloadedBinary, source: "download" });
// clearBrowser() wipes prior contents; withInstallLock uses a sibling lock
// outside CACHE_DIR, so assert the purge on what was actually INSIDE it,
// not the directory's own existence.
expect(paths.has(staleInstallDir)).toBe(false);
expect(paths.has(HF_BINARY)).toBe(false);
});
it("serializes concurrent force downloads so one purge cannot delete another installer's lock", async () => {
const downloadedBinary = join(HF_CACHE, "chrome-headless-shell", "force-downloaded");
const paths = installFsMocks({ existing: new Set([CACHE_ROOT, HF_CACHE, HF_BINARY]) });
let activeInstalls = 0;
let maxActiveInstalls = 0;
installPuppeteerBrowsersMock({
installedInHfCache: [{ browser: "chrome-headless-shell", executablePath: HF_BINARY }],
installImpl: async () => {
activeInstalls += 1;
maxActiveInstalls = Math.max(maxActiveInstalls, activeInstalls);
expect(paths.has(HF_LOCK)).toBe(true);
await new Promise((resolve) => setTimeout(resolve, 20));
activeInstalls -= 1;
return { executablePath: downloadedBinary };
},
});
const { ensureBrowser } = await import("./manager.js");
await expect(
Promise.all([ensureBrowser({ force: true }), ensureBrowser({ force: true })]),
).resolves.toEqual([
{ executablePath: downloadedBinary, source: "download" },
{ executablePath: downloadedBinary, source: "download" },
]);
expect(maxActiveInstalls).toBe(1);
expect(paths.has(HF_LOCK)).toBe(false);
});
it("ensureBrowser does not leak the install lock directory after a successful download", async () => {
@@ -191,7 +273,6 @@ describe("findBrowser — cache resolution", () => {
// same extract target. mkdirSync as an atomic mutex closes that race;
// this asserts the lock is actually released afterward (a leaked lock
// would permanently wedge every future render on this machine).
const HF_LOCK = join(HF_CACHE, ".install.lock");
const downloadedBinary = join(HF_CACHE, "chrome-headless-shell", "downloaded");
// Cache dir exists but is empty (no manifest entries) — distinct from the
// ENOTDIR "cache unreadable" case, which falls back to system instead.
@@ -216,8 +297,7 @@ describe("findBrowser — cache resolution", () => {
// withInstallLock directly with tiny real timeouts (it takes an
// injectable timeoutMs/pollMs for exactly this) rather than mocking
// Date.now()/setTimeout through the full ensureBrowser call graph.
const HF_LOCK = join(HF_CACHE, ".install.lock");
const paths = installFsMocks({ existing: new Set([HF_CACHE, HF_LOCK]) });
const paths = installFsMocks({ existing: new Set([CACHE_ROOT, HF_LOCK]) });
const { withInstallLock } = await import("./manager.js");
const result = await withInstallLock(async () => "done", 10, 5);
@@ -231,9 +311,7 @@ describe("findBrowser — cache resolution", () => {
// the stale-lock deadline together, waiter A can reclaim the stale lock and
// acquire a fresh one. Waiter B's old deadline is still expired, but it must
// not delete A's fresh lock.
const HF_LOCK = join(HF_CACHE, ".install.lock");
const RECLAIM_LOCK = join(HF_CACHE, ".install.reclaim.lock");
const paths = installFsMocks({ existing: new Set([HF_CACHE, HF_LOCK]) });
const paths = installFsMocks({ existing: new Set([CACHE_ROOT, HF_LOCK]) });
const { withInstallLock } = await import("./manager.js");
const first = withInstallLock(
@@ -248,7 +326,7 @@ describe("findBrowser — cache resolution", () => {
await expect(Promise.all([first, second])).resolves.toEqual(["first", "second"]);
expect(paths.has(HF_LOCK)).toBe(false);
expect(paths.has(RECLAIM_LOCK)).toBe(false);
expect(paths.has(HF_RECLAIM_LOCK)).toBe(false);
});
it("warns and falls through when the hyperframes cache cannot be read", async () => {
+63 -20
View File
@@ -21,6 +21,7 @@ async function loadPuppeteerBrowsers(): Promise<PuppeteerBrowsers> {
}
const CHROME_VERSION = "131.0.6778.85";
const CACHE_ROOT_DIR = join(homedir(), ".cache", "hyperframes");
const CACHE_DIR = join(homedir(), ".cache", "hyperframes", "chrome");
// Puppeteer's managed cache — where `@puppeteer/browsers install
// chrome-headless-shell` (and `puppeteer install`) drop binaries. The engine's
@@ -39,8 +40,8 @@ const PUPPETEER_CACHE_DIR = join(homedir(), ".cache", "puppeteer", "chrome-headl
//
// mkdirSync is atomic (EEXIST if another process already holds it), so it
// doubles as a zero-dependency cross-process mutex — no lockfile library needed.
const INSTALL_LOCK_DIR = join(CACHE_DIR, ".install.lock");
const INSTALL_RECLAIM_LOCK_DIR = join(CACHE_DIR, ".install.reclaim.lock");
const INSTALL_LOCK_DIR = join(CACHE_ROOT_DIR, ".chrome.install.lock");
const INSTALL_RECLAIM_LOCK_DIR = join(CACHE_ROOT_DIR, ".chrome.install.reclaim.lock");
const INSTALL_LOCK_TIMEOUT_MS = 120_000; // generous: a real download+extract can take a while
const INSTALL_LOCK_POLL_MS = 200;
@@ -88,7 +89,9 @@ export async function withInstallLock<T>(
pollMs = INSTALL_LOCK_POLL_MS,
): Promise<T> {
// recursive:false below needs the parent to already exist (unlike `mkdir -p`).
if (!existsSync(CACHE_DIR)) mkdirSync(CACHE_DIR, { recursive: true });
// Keep lock dirs outside CACHE_DIR so force-clearing the Chrome cache cannot
// delete another installer's in-flight lock.
if (!existsSync(CACHE_ROOT_DIR)) mkdirSync(CACHE_ROOT_DIR, { recursive: true });
let deadline = Date.now() + timeoutMs;
for (;;) {
if (existsSync(INSTALL_RECLAIM_LOCK_DIR)) {
@@ -127,11 +130,31 @@ export interface BrowserResult {
export interface EnsureBrowserOptions {
onProgress?: (downloadedBytes: number, totalBytes: number) => void;
// Purge any cached HF-managed download before resolving, so a stale or
// partially-extracted install can't make the retry look like a no-op.
force?: boolean;
}
interface CacheLookupResult {
result?: BrowserResult;
staleHyperframesCachePath?: string;
// Root install-folder path for the stale entry (InstalledBrowser#path), NOT
// the missing executablePath above — this is what actually needs deleting.
staleInstallPath?: string;
}
/**
* Remove one browser version's install directory (not the whole CACHE_DIR).
* @puppeteer/browsers' install() treats an existing-but-incomplete directory
* as already installed and throws "folder exists but executable is missing"
* rather than re-extracting — so an extraction interrupted by a Windows AV
* lock, a sleep/wake cycle, or ctrl-C (left with only alphabetically-early
* files like ABOUT/LICENSE, no exe) wedges every subsequent ensure/render
* with the same error until someone manually deletes the directory. Purging
* it first makes the retry actually retry.
*/
function purgeStaleInstall(installPath: string): void {
rmSync(installPath, { recursive: true, force: true });
}
// --- Internal helpers -------------------------------------------------------
@@ -215,7 +238,7 @@ async function findFromCache(): Promise<CacheLookupResult> {
return { result: { executablePath: match.executablePath, source: "cache" } };
}
if (match) {
return { staleHyperframesCachePath: match.executablePath };
return { staleHyperframesCachePath: match.executablePath, staleInstallPath: match.path };
}
}
@@ -371,7 +394,10 @@ export async function findBrowser(): Promise<BrowserResult | undefined> {
`[browser] Cached binary missing at ${fromCache.staleHyperframesCachePath} — re-downloading...`,
);
try {
return await withInstallLock(() => downloadBrowser());
return await withInstallLock(async () => {
if (fromCache.staleInstallPath) purgeStaleInstall(fromCache.staleInstallPath);
return downloadBrowser();
});
} catch (err) {
const cause = normalizeErrorMessage(err);
throw new Error(
@@ -445,27 +471,44 @@ export async function ensureBrowser(options?: EnsureBrowserOptions): Promise<Bro
const fromEnv = findFromEnv();
if (fromEnv) return fromEnv;
const fromCache = await findFromCache();
if (fromCache.result) return fromCache.result;
if (fromCache.staleHyperframesCachePath) {
console.warn(
`[browser] Cached binary missing at ${fromCache.staleHyperframesCachePath} — re-downloading...`,
);
return withInstallLock(() => downloadBrowser(options));
}
if (!options?.force) {
const fromCache = await findFromCache();
if (fromCache.result) return fromCache.result;
if (fromCache.staleHyperframesCachePath) {
console.warn(
`[browser] Cached binary missing at ${fromCache.staleHyperframesCachePath} — re-downloading...`,
);
return withInstallLock(async () => {
if (fromCache.staleInstallPath) purgeStaleInstall(fromCache.staleInstallPath);
return downloadBrowser(options);
});
}
const fromSystem = findFromSystem();
if (fromSystem) {
warnSystemFallbackOnce(fromSystem.executablePath);
return fromSystem;
const fromSystem = findFromSystem();
if (fromSystem) {
warnSystemFallbackOnce(fromSystem.executablePath);
return fromSystem;
}
}
return withInstallLock(async () => {
if (options?.force) {
// `--force` means "always get a fresh managed download" — purging the
// whole HF-managed cache after acquiring the install lock keeps two
// concurrent force retries from deleting each other's in-flight lock or
// partially extracted install.
clearBrowser();
}
// Re-check after acquiring the lock: a concurrent invocation may have
// finished installing while we were waiting, in which case reuse its
// result instead of downloading and extracting a second time.
const afterLock = await findFromCache();
if (afterLock.result) return afterLock.result;
// result instead of downloading and extracting a second time. Skipped
// under --force, which already purged and always wants a fresh download.
if (!options?.force) {
const afterLock = await findFromCache();
if (afterLock.result) return afterLock.result;
if (afterLock.staleInstallPath) purgeStaleInstall(afterLock.staleInstallPath);
}
return downloadBrowser(options);
});
}
+32 -19
View File
@@ -5,6 +5,7 @@ import { c } from "../ui/colors.js";
export const examples: Example[] = [
["Find or download Chrome for rendering", "hyperframes browser ensure"],
["Purge a stale/partial download and re-download", "hyperframes browser ensure --force"],
["Print the Chrome executable path", "hyperframes browser path"],
["Remove cached Chrome download", "hyperframes browser clear"],
];
@@ -19,11 +20,11 @@ import {
} from "../browser/manager.js";
import { trackBrowserInstall, trackCommandFailure } from "../telemetry/events.js";
async function runEnsure(): Promise<void> {
async function runEnsure(options?: { force?: boolean }): Promise<void> {
clack.intro(c.bold("hyperframes browser ensure"));
// ARM64 Linux: Chrome headless shell is not available.
// Try to find system Chromium first, then attempt auto-install via apt.
// ARM64 Linux: Chrome headless shell is not available (apt-get/system-only
// install flow, no download cache to force a purge of) — --force is a no-op here.
if (isLinuxArm()) {
const s = clack.spinner();
s.start("Linux ARM64 detected — looking for system Chromium...");
@@ -61,26 +62,31 @@ async function runEnsure(): Promise<void> {
}
const s = clack.spinner();
s.start("Looking for an existing browser...");
if (!options?.force) {
s.start("Looking for an existing browser...");
const existing = await findBrowser();
if (existing) {
s.stop(c.success("Browser found"));
console.log();
console.log(` ${c.dim("Source:")} ${c.bold(existing.source)}`);
console.log(` ${c.dim("Path:")} ${c.bold(existing.executablePath)}`);
console.log();
clack.outro(c.success("Ready to render."));
return;
const existing = await findBrowser();
if (existing) {
s.stop(c.success("Browser found"));
console.log();
console.log(` ${c.dim("Source:")} ${c.bold(existing.source)}`);
console.log(` ${c.dim("Path:")} ${c.bold(existing.executablePath)}`);
console.log();
clack.outro(c.success("Ready to render."));
return;
}
s.stop("No browser found — downloading");
} else {
s.start("Purging cached download and re-downloading...");
}
s.stop("No browser found — downloading");
const downloadSpinner = clack.spinner();
downloadSpinner.start(`Downloading Chrome Headless Shell ${c.dim("v" + CHROME_VERSION)}...`);
let lastPct = -1;
const result = await ensureBrowser({
force: options?.force,
onProgress: (downloaded, total) => {
if (total <= 0) return;
const pct = Math.floor((downloaded / total) * 100);
@@ -141,6 +147,12 @@ export default defineCommand({
"ensure = find or download Chrome, path = print executable path, clear = remove cached download",
required: false,
},
force: {
type: "boolean",
description:
"ensure only: purge any cached download (including a stale/partial one) and re-download from scratch",
default: false,
},
},
async run({ args }) {
const subcommand = args.subcommand;
@@ -157,16 +169,17 @@ ${c.bold("SUBCOMMANDS:")}
${c.accent("clear")} ${c.dim("Remove cached Chrome download")}
${c.bold("EXAMPLES:")}
${c.accent("npx hyperframes browser ensure")} ${c.dim("Download Chrome if needed")}
${c.accent("npx hyperframes browser path")} ${c.dim("Print path for scripts")}
${c.accent("npx hyperframes browser clear")} ${c.dim("Remove cached browser")}
${c.accent("npx hyperframes browser ensure")} ${c.dim("Download Chrome if needed")}
${c.accent("npx hyperframes browser ensure --force")} ${c.dim("Purge a stale/partial download and re-download")}
${c.accent("npx hyperframes browser path")} ${c.dim("Print path for scripts")}
${c.accent("npx hyperframes browser clear")} ${c.dim("Remove cached browser")}
`);
return;
}
switch (subcommand) {
case "ensure":
return runEnsure();
return runEnsure({ force: args.force });
case "path":
return runPath();
case "clear":
@@ -101,4 +101,56 @@ describe("runAssetImport", () => {
/node/i,
);
});
it("records description + entity and regenerates .media/index.md", async () => {
const dir = scratch();
const out = await runAssetImport(
"KEY:1-2",
{ format: "png", description: "hero illustration", entity: "Acme hero" },
deps(dir),
);
expect(out.record.description).toBe("hero illustration");
expect(out.record.entity).toBe("Acme hero");
expect(out.snippet.html).toContain('alt="hero illustration"');
const index = readFileSync(join(dir, ".media", "index.md"), "utf8");
expect(index).toContain("hero illustration");
expect(index).toContain(out.record.id);
});
it("applies --description/--entity on a reuse hit instead of dropping them", async () => {
const dir = scratch();
const first = await runAssetImport("KEY:1-2", { format: "png" }, deps(dir));
expect(first.record.description).toBeUndefined();
const again = await runAssetImport(
"KEY:1-2",
{ format: "png", description: "Acme logo", entity: "Acme logo" },
deps(dir),
);
expect(again.reused).toBe(true);
expect(again.record.description).toBe("Acme logo");
expect(again.snippet.html).toContain('alt="Acme logo"');
const index = readFileSync(join(dir, ".media", "index.md"), "utf8");
expect(index).toContain("Acme logo");
expect(index).not.toContain("image_002");
});
it("reuses against ANY matching tuple, not just the oldest row", async () => {
const dir = scratch();
await runAssetImport("KEY:1-2", { format: "svg" }, deps(dir)); // image_001 (svg)
const png = await runAssetImport("KEY:1-2", { format: "png" }, deps(dir)); // image_002
expect(png.reused).toBe(false);
const pngAgain = await runAssetImport("KEY:1-2", { format: "png" }, deps(dir));
expect(pngAgain.reused).toBe(true);
expect(pngAgain.record.id).toBe(png.record.id);
});
it("flattens whitespace in descriptions so index.md rows stay single-line", async () => {
const dir = scratch();
const out = await runAssetImport(
"KEY:1-2",
{ format: "png", description: "line one\nline two" },
deps(dir),
);
expect(out.record.description).toBe("line one line two");
});
});
+70 -14
View File
@@ -9,12 +9,14 @@ import {
appendRecord,
buildAssetSnippet,
createFigmaClient,
findByFigmaNode,
findAllByFigmaNode,
freezeBytes,
nextId,
parseFigmaRef,
regenerateIndex,
sanitizeSvg,
typeDirPath,
updateRecord,
type AssetSnippet,
type FigmaAssetFormat,
type FigmaClient,
@@ -28,6 +30,10 @@ import { withFigmaErrors } from "./cliError.js";
export interface AssetImportOptions {
format: FigmaAssetFormat;
scale?: number;
/** human description — lands in the manifest + index.md + <img alt> */
description?: string;
/** media-use interop: entity name for `resolve --entity` cache hits */
entity?: string;
}
export interface AssetImportDeps {
@@ -55,21 +61,39 @@ export async function runAssetImport(
);
const { version } = await deps.client.fileVersion(ref.fileKey);
const description = normalizeMeta(opts.description);
const entity = normalizeMeta(opts.entity);
// Cache key per spec §5: fileKey:nodeId:format:scale:version → reuse.
// Unspecified scale is canonically 1 on both sides (figma's default), so
// `--scale 1` and no flag dedupe to the same record. Reuse also requires
// the frozen file to still exist — a deleted file falls through to
// re-import instead of returning a snippet that points at nothing.
const existing = findByFigmaNode(deps.projectDir, ref.fileKey, ref.nodeId);
if (
existing &&
existing.provenance.format === opts.format &&
(existing.provenance.scale ?? 1) === (opts.scale ?? 1) &&
existing.provenance.version === version &&
existsSync(join(deps.projectDir, existing.path))
) {
return { record: existing, snippet: buildAssetSnippet(existing), reused: true };
// Check EVERY row for the node (a node can legitimately have several
// format/scale/version tuples — the oldest-row shortcut minted duplicates
// forever once a second tuple existed). Unspecified scale is canonically 1
// on both sides (figma's default). Reuse also requires the frozen file to
// still exist — a deleted file falls through to re-import.
const existing = findAllByFigmaNode(deps.projectDir, ref.fileKey, ref.nodeId).find(
(r) =>
r.provenance.format === opts.format &&
(r.provenance.scale ?? 1) === (opts.scale ?? 1) &&
r.provenance.version === version &&
existsSync(join(deps.projectDir, r.path)),
);
if (existing) {
// Metadata supplied on a re-import still lands: upsert the row instead
// of silently discarding the flags.
let record = existing;
if (
(description !== undefined && description !== existing.description) ||
(entity !== undefined && entity !== existing.entity)
) {
record = {
...existing,
...(description !== undefined && { description }),
...(entity !== undefined && { entity }),
};
updateRecord(deps.projectDir, record);
}
safeRegenerateIndex(deps.projectDir);
return { record, snippet: buildAssetSnippet(record), reused: true };
}
const rendered = await deps.client.renderNode(ref, opts);
@@ -92,6 +116,8 @@ export async function runAssetImport(
type: "image",
path: relative(deps.projectDir, destAbs),
source: `figma:${ref.fileKey}/${ref.nodeId}`,
...(description !== undefined && { description }),
...(entity !== undefined && { entity }),
provenance: {
source: "figma",
fileKey: ref.fileKey,
@@ -102,9 +128,29 @@ export async function runAssetImport(
},
};
appendRecord(deps.projectDir, record);
safeRegenerateIndex(deps.projectDir);
return { record, snippet: buildAssetSnippet(record), reused: false };
}
/** index.md is a single table row per record — newlines/tabs in a
* description would corrupt the whole table. */
function normalizeMeta(value: string | undefined): string | undefined {
if (value === undefined) return undefined;
const cleaned = value.replace(/\s+/g, " ").trim();
return cleaned.length > 0 ? cleaned : undefined;
}
/** Keep the agent-readable inventory in step with the manifest (media-use
* regenerates the same file after its writes). Best-effort: the import is
* already durable, so an index write failure must not fail the command. */
function safeRegenerateIndex(projectDir: string): void {
try {
regenerateIndex(projectDir);
} catch (err) {
console.warn(`index.md regeneration failed: ${err instanceof Error ? err.message : err}`);
}
}
const FORMATS: readonly FigmaAssetFormat[] = ["png", "svg", "jpg", "pdf"];
function parseFormat(raw: string): FigmaAssetFormat {
@@ -122,6 +168,14 @@ export default defineCommand({
},
format: { type: "string", description: "png | svg | jpg | pdf", default: "svg" },
scale: { type: "string", description: "export scale (e.g. 2)" },
description: {
type: "string",
description: "what this asset is (index.md + <img alt>); e.g. the layer's purpose",
},
entity: {
type: "string",
description: 'entity name for media-use cache lookups (e.g. "Acme logo")',
},
dir: { type: "string", description: "project directory", default: "." },
},
async run({ args }) {
@@ -133,6 +187,8 @@ export default defineCommand({
{
format: parseFormat(args.format),
scale: args.scale !== undefined ? Number(args.scale) : undefined,
description: args.description,
entity: args.entity,
},
{ projectDir: args.dir, client, download: downloadRender },
);
+8 -4
View File
@@ -67,12 +67,14 @@ export async function runComponentImport(
// The search key must match the EMITTED (html-escaped) node id, and
// replaceAll covers the same node appearing twice in the tree.
let html = mapped.html;
const frozenAssets: string[] = [];
for (const req of mapped.rasterize) {
const asset = await runAssetImport(
`${ref.fileKey}:${req.nodeId}`,
{ format: "svg" },
{ format: "svg", description: req.name },
{ projectDir: deps.projectDir, client: deps.client, download: deps.download },
);
frozenAssets.push(asset.record.path);
// src is a URL — always forward slashes, even when relative() yields
// windows separators.
const srcRel = relative(componentDir, join(deps.projectDir, asset.record.path)).replaceAll(
@@ -99,9 +101,11 @@ export async function runComponentImport(
target: `compositions/components/${name}/${name}.html`,
type: "hyperframes:snippet",
},
...mapped.rasterize.map((r) => ({
path: `${r.slug}.svg`,
target: `.media/images/${r.slug}.svg`,
// The paths the frozen files ACTUALLY landed at (image_NNN.svg), which
// is also what the emitted HTML references — not the slug names.
...frozenAssets.map((p) => ({
path: p.split("/").pop() ?? p,
target: p.replaceAll("\\", "/"),
type: "hyperframes:asset",
})),
],
+62 -1
View File
@@ -1,8 +1,11 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import {
extractCompositionErrorsFromLint,
navigationTimeoutHint,
raceMediaReady,
resolveNavigationTimeoutMs,
shouldIgnoreRequestFailure,
waitForPreferredSeekTarget,
} from "./validate.js";
import type { ProjectLintResult } from "../utils/lintProject.js";
@@ -89,6 +92,28 @@ describe("shouldIgnoreRequestFailure", () => {
});
});
describe("waitForPreferredSeekTarget", () => {
it("waits for the runtime player/bridge target before falling back to raw timelines", async () => {
const page = {
waitForFunction: vi.fn(async () => undefined),
};
await waitForPreferredSeekTarget(page, 123);
expect(page.waitForFunction).toHaveBeenCalledWith(expect.any(Function), { timeout: 123 });
});
it("does not fail validation when only the legacy raw timeline fallback is available", async () => {
const page = {
waitForFunction: vi.fn(async () => {
throw new Error("waiting failed: timeout");
}),
};
await expect(waitForPreferredSeekTarget(page, 1)).resolves.toBeUndefined();
});
});
describe("extractCompositionErrorsFromLint", () => {
// `bundleToSingleHtml` (the inliner validate.ts bundles through) is
// intentionally tolerant of missing/empty/unparsable data-composition-src
@@ -192,3 +217,39 @@ describe("extractCompositionErrorsFromLint", () => {
expect(errors.map((e) => e.text)).toEqual(["scene-a is empty", "scene-b is empty"]);
});
});
// Regression: `validate` used a hardcoded 10s page-navigation timeout that
// ignored --timeout, so a composition loading GSAP from a CDN <script> (which
// blocks domcontentloaded) failed with an opaque "Navigation timeout of 10000ms"
// even though the full render's larger budget rode it out — with no knob to
// extend it. resolveNavigationTimeoutMs makes --timeout raise the nav budget
// (never below the 10s floor); navigationTimeoutHint replaces the opaque error.
describe("resolveNavigationTimeoutMs", () => {
it("keeps the 10s floor when --timeout is unset or smaller", () => {
expect(resolveNavigationTimeoutMs(undefined)).toBe(10000);
expect(resolveNavigationTimeoutMs(3000)).toBe(10000); // the default --timeout
expect(resolveNavigationTimeoutMs(0)).toBe(10000);
});
it("raises the navigation budget to --timeout when it exceeds the floor", () => {
expect(resolveNavigationTimeoutMs(30000)).toBe(30000);
});
});
describe("navigationTimeoutHint", () => {
it("replaces a Puppeteer navigation-timeout error with an actionable CDN/--timeout hint", () => {
const hinted = navigationTimeoutHint(
new Error("Navigation timeout of 10000 ms exceeded"),
10000,
);
expect(hinted).toBeInstanceOf(Error);
expect(hinted?.message).toContain("10000ms");
expect(hinted?.message).toContain("CDN");
expect(hinted?.message).toContain("--timeout");
});
it("returns null for any non-navigation-timeout error so the caller rethrows it as-is", () => {
expect(navigationTimeoutHint(new Error("net::ERR_CONNECTION_REFUSED"), 10000)).toBeNull();
expect(navigationTimeoutHint("some string failure", 10000)).toBeNull();
});
});
+82 -2
View File
@@ -32,7 +32,35 @@ interface ContrastEntry {
const CONTRAST_SAMPLES = 5;
const SEEK_SETTLE_MS = 150;
const PREFERRED_SEEK_TARGET_WAIT_MS = 500;
const MEDIA_EXTENSIONS = /\.(aac|flac|m4a|mov|mp3|mp4|oga|ogg|wav|webm)$/i;
// Floor for the initial page navigation. A blocking external <script> (GSAP
// from a CDN, etc.) delays `domcontentloaded`; the actual render (much larger
// budget) rides it out, so validate's navigation must be at least as patient as
// the user's --timeout, never stuck below this floor.
const NAV_TIMEOUT_FLOOR_MS = 10000;
// Navigation budget = the larger of the floor and the user's --timeout, so
// `--timeout` (already the "wait longer for slow loads" knob for media/settle)
// also extends navigation instead of being ignored by a hardcoded 10s.
export function resolveNavigationTimeoutMs(optTimeout?: number): number {
return Math.max(NAV_TIMEOUT_FLOOR_MS, optTimeout ?? 0);
}
// Turn Puppeteer's opaque "Navigation timeout of Nms exceeded" into an
// actionable message: the usual cause is a blocking CDN <script> that render
// tolerates but validate's tighter budget does not. Returns a replacement Error
// for a navigation timeout, or null for any other error (caller rethrows as-is).
export function navigationTimeoutHint(err: unknown, navTimeoutMs: number): Error | null {
const msg = err instanceof Error ? err.message : String(err);
if (!/navigation timeout/i.test(msg)) return null;
return new Error(
`Page navigation timed out after ${navTimeoutMs}ms. A blocking external <script> ` +
`(e.g. GSAP loaded from a CDN) can delay page load past this budget even when the ` +
`full render succeeds. Vendor the script locally (recommended for deterministic ` +
`renders), or re-run with a longer --timeout.`,
);
}
export function shouldIgnoreRequestFailure(
url: string,
@@ -57,7 +85,24 @@ async function getCompositionDuration(page: import("puppeteer-core").Page): Prom
}
async function seekTo(page: import("puppeteer-core").Page, time: number): Promise<void> {
await waitForPreferredSeekTarget(page);
await page.evaluate((t: number) => {
// window.__player.renderSeek is exposed directly by the composition
// runtime (packages/core/src/runtime/init.ts) on every page load, and
// — unlike raw timeline.seek() — it also runs the runtime's own
// [data-start]/[data-duration] visibility sync, hiding clips outside
// their timeline window. window.__hf.seek only exists when the
// producer's render-pipeline bridge script has been injected, which
// validate's static preview server never does, so it was always
// falling through to the raw __timelines seek below and skipping that
// sync — leaving off-window elements looking fully visible to any
// check (e.g. the contrast audit) that reads computed style afterward.
const player = (window as unknown as { __player?: { renderSeek?: (t: number) => void } })
.__player;
if (player && typeof player.renderSeek === "function") {
player.renderSeek(t);
return;
}
if (window.__hf && typeof window.__hf.seek === "function") {
window.__hf.seek(t);
return;
@@ -74,6 +119,32 @@ async function seekTo(page: import("puppeteer-core").Page, time: number): Promis
await new Promise((r) => setTimeout(r, SEEK_SETTLE_MS));
}
interface WaitForFunctionPage {
waitForFunction: (pageFunction: () => boolean, options: { timeout: number }) => Promise<unknown>;
}
export async function waitForPreferredSeekTarget(
page: WaitForFunctionPage,
timeoutMs = PREFERRED_SEEK_TARGET_WAIT_MS,
): Promise<void> {
try {
await page.waitForFunction(
() => {
const w = window as unknown as {
__hf?: { seek?: unknown };
__player?: { renderSeek?: unknown };
};
return typeof w.__player?.renderSeek === "function" || typeof w.__hf?.seek === "function";
},
{ timeout: timeoutMs },
);
} catch {
// Older/static pages may only expose raw window.__timelines. Keep the
// legacy fallback path rather than turning a missing player API into a
// validate failure.
}
}
/**
* Race a media element's `loadedmetadata`/`error` event against a deadline,
* whichever comes first. Already-ready elements resolve immediately.
@@ -353,7 +424,14 @@ async function validateInBrowser(
}
});
await page.goto(server.url, { waitUntil: "domcontentloaded", timeout: 10000 });
const navTimeoutMs = resolveNavigationTimeoutMs(opts.timeout);
try {
await page.goto(server.url, { waitUntil: "domcontentloaded", timeout: navTimeoutMs });
} catch (err) {
const hinted = navigationTimeoutHint(err, navTimeoutMs);
if (hinted) throw hinted;
throw err;
}
await new Promise((r) => setTimeout(r, opts.timeout ?? 3000));
for (const w of await auditClipDurations(page, analyzeClipMediaFit, opts.timeout ?? 3000)) {
@@ -472,7 +550,9 @@ Examples:
},
timeout: {
type: "string",
description: "Ms to wait for scripts to settle (default: 3000)",
description:
"Ms to wait for scripts to settle and media to load (default: 3000). Also raises the " +
"page-navigation budget above its 10s floor when a slow external <script> needs longer.",
default: "3000",
},
},
+11 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/core",
"version": "0.7.29",
"version": "0.7.36",
"description": "",
"repository": {
"type": "git",
@@ -95,6 +95,12 @@
"import": "./src/runtime/clipTree.ts",
"types": "./src/runtime/clipTree.ts"
},
"./runtime/position-edits": {
"bun": "./src/runtime/positionEdits.ts",
"node": "./dist/runtime/positionEdits.js",
"import": "./src/runtime/positionEdits.ts",
"types": "./src/runtime/positionEdits.ts"
},
"./runtime/lottie-readiness": {
"bun": "./src/lottieReadiness.ts",
"node": "./dist/lottieReadiness.js",
@@ -269,6 +275,10 @@
"import": "./dist/runtime/clipTree.js",
"types": "./dist/runtime/clipTree.d.ts"
},
"./runtime/position-edits": {
"import": "./dist/runtime/positionEdits.js",
"types": "./dist/runtime/positionEdits.d.ts"
},
"./runtime/lottie-readiness": {
"import": "./dist/lottieReadiness.js",
"types": "./dist/lottieReadiness.d.ts"
@@ -79,6 +79,59 @@ body { margin: 0; }
expect(fakeWindow.__captured).toEqual({ title: "Pro", price: "$29" });
});
it("routes the documented window.__hyperframes.getVariables() to the scoped variant too", () => {
// Regression: the docs (variables-and-media.md) show `window.__hyperframes.
// getVariables()`, but inside a sub-comp the scoped `window` proxy used to
// fall through to the HOST page's base __hyperframes, returning the wrong
// (or empty) variables — the bare `__hyperframes` param was the only form
// that worked. Both spellings must now resolve to this comp's variables.
const { document } = parseHTML(`<div data-composition-id="card-1"></div>`);
const fakeWindow: Record<string, unknown> = {
document,
__timelines: {},
__hfVariablesByComp: {
"card-1": { title: "Pro", price: "$29" },
"card-2": { title: "Enterprise", price: "Custom" },
},
__hyperframes: {
getVariables: () => ({ title: "TOP-LEVEL-LEAK" }),
fitTextFontSize: () => undefined,
},
};
const wrapped = wrapScopedCompositionScript(
`window.__captured = window.__hyperframes.getVariables();`,
"card-1",
);
new Function("window", wrapped)(fakeWindow);
expect(fakeWindow.__captured).toEqual({ title: "Pro", price: "$29" });
});
it("preserves non-getVariables members on window.__hyperframes (only getVariables is rescoped)", () => {
const { document } = parseHTML(`<div data-composition-id="card-1"></div>`);
let fitCalled = false;
const fakeWindow: Record<string, unknown> = {
document,
__timelines: {},
__hfVariablesByComp: { "card-1": { title: "Pro" } },
__hyperframes: {
getVariables: () => ({ title: "TOP-LEVEL-LEAK" }),
fitTextFontSize: () => {
fitCalled = true;
},
},
};
const wrapped = wrapScopedCompositionScript(
`window.__hyperframes.fitTextFontSize();`,
"card-1",
);
new Function("window", wrapped)(fakeWindow);
expect(fitCalled).toBe(true);
});
it("scoped getVariables reads from the runtime composition id when it differs", () => {
const { document } = parseHTML(`<div data-composition-id="scene"></div>`);
const fakeWindow: Record<string, unknown> = {
@@ -396,6 +396,16 @@ export function wrapScopedCompositionScript(
? new Proxy(window, {
get: function(target, prop, receiver) {
if (prop === "__timelines") return __hfGetTimelineRegistry();
// Inside a sub-composition, __hyperframes is passed as a bare script
// param bound to the SCOPED variant (per-comp getVariables). But
// authors routinely write the documented window.__hyperframes.
// getVariables() form, which would otherwise fall through to the host
// page's base __hyperframes and return the WRONG (or empty) variables
// for this instance. Route it to the scoped variant too so both
// spellings resolve to this composition's own variables.
// (__hfScopedHyperframes is a hoisted var assigned below, before any
// sub-comp script -- the only code that reads this -- runs.)
if (prop === "__hyperframes") return __hfScopedHyperframes;
return Reflect.get(target, prop, target);
},
set: function(target, prop, value, receiver) {
+3
View File
@@ -25,12 +25,15 @@ export {
mediaDir,
manifestPath,
typeDirPath,
updateRecord,
isFigmaManifestRecord,
readManifest,
appendRecord,
findAllByFigmaNode,
findByFigmaNode,
nextId,
} from "./manifest";
export { regenerateIndex } from "./mediaIndex";
export { buildAssetSnippet } from "./assetSnippet";
export { sanitizeSvg } from "./sanitizeSvg";
export {
+34 -8
View File
@@ -1,4 +1,4 @@
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { readJsonlValues } from "./jsonl";
import type { FigmaManifestRecord } from "./types";
@@ -68,15 +68,41 @@ export function findByFigmaNode(
fileKey: string,
nodeId: string,
): FigmaManifestRecord | null {
for (const r of readManifest(projectDir)) {
if (
return findAllByFigmaNode(projectDir, fileKey, nodeId)[0] ?? null;
}
/** EVERY row for a node — reuse gates must check all (format, scale, version)
* tuples, not just the oldest, or a second tuple defeats idempotency forever. */
export function findAllByFigmaNode(
projectDir: string,
fileKey: string,
nodeId: string,
): FigmaManifestRecord[] {
return readManifest(projectDir).filter(
(r) =>
r.provenance.source === "figma" &&
r.provenance.fileKey === fileKey &&
r.provenance.nodeId === nodeId
)
return r;
}
return null;
r.provenance.nodeId === nodeId,
);
}
/** Rewrite one row in place by id, preserving every other line (other
* writers' rows included) byte-for-byte. */
export function updateRecord(projectDir: string, record: FigmaManifestRecord): void {
const p = manifestPath(projectDir);
const lines = readFileSync(p, "utf8").split(/\r?\n/);
const out = lines.map((line) => {
const trimmed = line.trim();
if (trimmed.length === 0) return line;
try {
const parsed: unknown = JSON.parse(trimmed);
if (isFigmaManifestRecord(parsed) && parsed.id === record.id) return JSON.stringify(record);
} catch {
// non-JSON line — preserve untouched
}
return line;
});
writeFileSync(p, out.join("\n"));
}
export function nextId(projectDir: string, type: FigmaManifestRecord["type"]): string {
+107
View File
@@ -0,0 +1,107 @@
// @vitest-environment node
import { describe, expect, it, afterEach } from "vitest";
import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { execFileSync } from "node:child_process";
import { generateIndexContent, indexPath, regenerateIndex } from "./mediaIndex";
import { manifestPath } from "./manifest";
const dirs: string[] = [];
function project(): string {
const d = mkdtempSync(join(tmpdir(), "hf-media-index-"));
dirs.push(d);
mkdirSync(join(d, ".media"), { recursive: true });
return d;
}
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
const MEDIA_USE_ROW = {
id: "bgm_001",
type: "bgm",
path: ".media/audio/bgm/bgm_001.mp3",
source: "search",
description: "upbeat tech launch",
duration: 25,
provenance: { provider: "heygen-audio", prompt: "upbeat tech launch" },
};
const IMAGE_ROW = {
id: "image_001",
type: "image",
path: ".media/images/image_001.jpg",
source: "search",
description: "gradient tech background",
width: 1920,
height: 1080,
provenance: { provider: "heygen-asset", prompt: "gradient tech background" },
};
const ICON_ROW = {
id: "icon_001",
type: "icon",
path: ".media/images/icon_001.svg",
source: "search",
description: "rocket",
transparent: true,
provenance: { provider: "heygen-asset", prompt: "rocket" },
};
const FIGMA_ROW = {
id: "image_002",
type: "image",
path: ".media/images/image_002.svg",
source: "figma:KEY/1:2",
description: "hero illustration",
entity: "Acme hero",
provenance: { source: "figma", fileKey: "KEY", nodeId: "1:2", version: "9", format: "svg" },
};
// media-use renders every JSON-parseable row, shape or no shape — selection
// parity matters as much as format parity.
const JUNK_ROW = { note: "not a media record" };
const ALL_ROWS = [MEDIA_USE_ROW, IMAGE_ROW, ICON_ROW, FIGMA_ROW, JUNK_ROW];
describe("regenerateIndex", () => {
it("renders every writer's rows (media-use + figma) into one table", () => {
const p = project();
for (const row of ALL_ROWS) appendFileSync(manifestPath(p), JSON.stringify(row) + "\n");
regenerateIndex(p);
const index = readFileSync(indexPath(p), "utf8");
expect(index).toContain("# .media · 5 assets");
expect(index).toContain("25s");
expect(index).toContain("1920×1080");
expect(index).toContain("hero illustration");
});
it("matches media-use's index-gen output byte-for-byte on the same rows", () => {
// Covers duration, width×height, icon+transparent, no-dims, and junk-row
// selection — the full set of branches both generators format.
const ours = generateIndexContent(ALL_ROWS as Record<string, unknown>[]);
// Run the actual media-use generator on identical input. Resolve the
// script relative to THIS file (cwd varies per test runner) and hand it
// over as a file:// URL so the specifier is valid on windows too.
const genUrl = pathToFileURL(
join(
fileURLToPath(new URL(".", import.meta.url)),
"..",
"..",
"..",
"..",
"skills",
"media-use",
"scripts",
"lib",
"index-gen.mjs",
),
).href;
const script = `
import { generateIndexContent } from ${JSON.stringify(genUrl)};
const rows = ${JSON.stringify(ALL_ROWS)};
process.stdout.write(generateIndexContent(rows));
`;
const theirs = execFileSync("node", ["--input-type=module", "-e", script], {
encoding: "utf8",
});
expect(ours).toBe(theirs);
});
});
+89
View File
@@ -0,0 +1,89 @@
/**
* Regenerate .media/index.md — the agent-readable inventory table — after a
* figma import, exactly the way media-use does after a resolve. Both writers
* regenerate the SAME file from the full manifest (all writers' rows), so the
* output format AND row selection here must stay byte-identical with
* skills/media-use/scripts/lib/index-gen.mjs — including rendering every
* JSON-parseable row (no shape filtering), or the file would flip-flop
* depending on which writer ran last.
*/
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { readJsonlValues } from "./jsonl";
import { manifestPath, mediaDir } from "./manifest";
type IndexRow = Record<string, unknown>;
function isRow(value: unknown): value is IndexRow {
return typeof value === "object" && value !== null;
}
export function indexPath(projectDir: string): string {
return join(mediaDir(projectDir), "index.md");
}
function pad(str: unknown, len: number): string {
return String(str ?? "").padEnd(len);
}
function formatDur(r: IndexRow): string {
if (r.duration == null) return "—";
return `${String(r.duration)}s`;
}
function formatDims(r: IndexRow): string {
if (r.width && r.height) return `${String(r.width)}×${String(r.height)}`;
if (r.type === "icon" && r.transparent) return "svg";
return "—";
}
function len(value: unknown): number {
return String(value ?? "").length;
}
export function generateIndexContent(records: IndexRow[]): string {
const count = records.length;
const header = `# .media · ${count} asset${count === 1 ? "" : "s"}\n`;
if (count === 0) return header;
const cols = { id: 4, type: 5, dur: 4, dims: 5, path: 5 };
for (const r of records) {
cols.id = Math.max(cols.id, len(r.id));
cols.type = Math.max(cols.type, len(r.type));
cols.dur = Math.max(cols.dur, formatDur(r).length);
cols.dims = Math.max(cols.dims, formatDims(r).length);
cols.path = Math.max(cols.path, len(r.path));
}
const heading =
pad("id", cols.id + 2) +
pad("type", cols.type + 2) +
pad("dur", cols.dur + 2) +
pad("dims", cols.dims + 2) +
pad("path", cols.path + 2) +
"description";
const lines = [header, heading];
for (const r of records) {
lines.push(
pad(r.id, cols.id + 2) +
pad(r.type, cols.type + 2) +
pad(formatDur(r), cols.dur + 2) +
pad(formatDims(r), cols.dims + 2) +
pad(r.path, cols.path + 2) +
String(r.description ?? ""),
);
}
return lines.join("\n") + "\n";
}
/** Rebuild index.md from EVERY writer's manifest rows (media-use + figma). */
export function regenerateIndex(projectDir: string): string {
const records = readJsonlValues(manifestPath(projectDir)).filter(isRow);
const content = generateIndexContent(records);
const p = indexPath(projectDir);
mkdirSync(dirname(p), { recursive: true });
writeFileSync(p, content);
return content;
}
+2
View File
@@ -20,6 +20,8 @@ export interface FigmaManifestRecord {
path: string;
source: string;
description?: string;
/** media-use interop: lets `resolve --entity` find figma-imported assets */
entity?: string;
width?: number;
height?: number;
provenance: FigmaProvenance;
+2 -1
View File
@@ -12,7 +12,8 @@ export type RuntimeAnalyticsEvent =
| "composition_paused"
| "composition_seeked"
| "composition_ended"
| "element_picked";
| "element_picked"
| "position_edit_fold_skipped";
export type RuntimeAnalyticsProperties = Record<string, string | number | boolean | null>;
+13
View File
@@ -28,6 +28,7 @@ import { createRuntimeStartTimeResolver } from "./startResolver";
import { createClipTree } from "./clipTree";
import { loadExternalCompositions, loadInlineTemplateCompositions } from "./compositionLoader";
import { applyCaptionOverrides } from "./captionOverrides";
import { applyPositionEdits } from "./positionEdits";
import { createColorGradingRuntime, type RuntimeColorGradingApi } from "./colorGrading";
import { TransportClock } from "./clock";
import { WebAudioTransport } from "./webAudioTransport";
@@ -72,6 +73,12 @@ function resolveExportRenderFps(): ExportRenderFpsResolution {
export function initSandboxRuntimeModular(): void {
const state = createRuntimeState();
// SDK moveElement edits must render even when no usable GSAP timeline ever
// binds (CSS/WAAPI-animated or fully static compositions) — apply at init.
// This runs at DOMContentLoaded, after inline composition scripts have
// parsed their tweens, so GSAP (when present) won't fold the translate.
// Re-applied on every timeline bind for the rebind/soft-reload paths.
applyPositionEdits(document);
const exportRenderFps = resolveExportRenderFps();
state.canonicalFps = exportRenderFps.fps ?? state.canonicalFps;
if (window.__HF_EXPORT_RENDER_SEEK_CONFIG) {
@@ -1198,6 +1205,12 @@ export function initSandboxRuntimeModular(): void {
// during initial rebind (timing race on first load / soft reload).
const applyFn = (window as Record<string, unknown>).__hfStudioManualEditsApply;
if (typeof applyFn === "function") applyFn();
// SDK moveElement edits (data-hf-edit-base-x/y markers) render as a
// CSS translate delta. Must run after the timeline is bound so GSAP has
// already parsed the elements — a translate present at first parse gets
// folded into the cached transform and lost per-axis on seek.
applyPositionEdits(document);
}
if (resolution.diagnostics) {
postRuntimeMessage({
@@ -0,0 +1,150 @@
import { describe, expect, it } from "vitest";
import {
EDIT_BASE_X_ATTR,
EDIT_BASE_Y_ATTR,
EDIT_ORIGINAL_TRANSLATE_ATTR,
applyPositionEditToElement,
applyPositionEdits,
composeTranslate,
} from "./positionEdits";
function makeElement(attrs: Record<string, string>, style = ""): HTMLElement {
const el = document.createElement("div");
for (const [name, value] of Object.entries(attrs)) el.setAttribute(name, value);
if (style) el.setAttribute("style", style);
document.body.appendChild(el);
return el;
}
describe("composeTranslate", () => {
it("returns the delta alone when there is no original", () => {
expect(composeTranslate("", "10px", "20px")).toBe("10px 20px");
expect(composeTranslate("none", "10px", "20px")).toBe("10px 20px");
});
it("adds px values numerically", () => {
expect(composeTranslate("5px 6px", "10px", "20px")).toBe("15px 26px");
expect(composeTranslate("-5.5px 6px", "10px", "-20px")).toBe("4.5px -14px");
});
it("treats a single-part original as x-only", () => {
expect(composeTranslate("5px", "10px", "20px")).toBe("15px 20px");
});
it("falls back to calc() for non-px units and preserves z", () => {
expect(composeTranslate("10% 6px", "10px", "20px")).toBe("calc(10% + 10px) 26px");
expect(composeTranslate("1px 2px 3px", "10px", "20px")).toBe("11px 22px 3px");
});
});
describe("applyPositionEdits", () => {
it("ignores unmarked elements", () => {
const el = makeElement({ "data-x": "100", "data-y": "50" });
expect(applyPositionEdits(document)).toBe(0);
expect(el.style.getPropertyValue("translate")).toBe("");
el.remove();
});
it("applies the delta between data-x/y and the captured baseline", () => {
const el = makeElement({
"data-x": "150",
"data-y": "-30",
[EDIT_BASE_X_ATTR]: "100",
[EDIT_BASE_Y_ATTR]: "20",
});
expect(applyPositionEdits(document)).toBe(1);
expect(el.style.getPropertyValue("translate")).toBe("50px -50px");
expect(el.getAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR)).toBe("");
el.remove();
});
it("treats missing data-x/y or baseline attributes as 0", () => {
const el = makeElement({ "data-x": "40", [EDIT_BASE_X_ATTR]: "0" });
applyPositionEdits(document);
expect(el.style.getPropertyValue("translate")).toBe("40px 0px");
el.remove();
});
it("composes with a pre-existing inline translate and stays idempotent", () => {
const el = makeElement(
{ "data-x": "10", "data-y": "20", [EDIT_BASE_X_ATTR]: "0", [EDIT_BASE_Y_ATTR]: "0" },
"translate: 5px 6px",
);
applyPositionEdits(document);
expect(el.style.getPropertyValue("translate")).toBe("15px 26px");
expect(el.getAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR)).toBe("5px 6px");
// Second application must not compound.
applyPositionEdits(document);
expect(el.style.getPropertyValue("translate")).toBe("15px 26px");
el.remove();
});
it("recomputes from the same baseline after data-x changes", () => {
const el = makeElement({
"data-x": "10",
"data-y": "0",
[EDIT_BASE_X_ATTR]: "0",
[EDIT_BASE_Y_ATTR]: "0",
});
applyPositionEdits(document);
expect(el.style.getPropertyValue("translate")).toBe("10px 0px");
el.setAttribute("data-x", "70");
applyPositionEdits(document);
expect(el.style.getPropertyValue("translate")).toBe("70px 0px");
el.remove();
});
it("never re-captures the original translate once set", () => {
const el = makeElement({
"data-x": "10",
"data-y": "0",
[EDIT_BASE_X_ATTR]: "0",
[EDIT_BASE_Y_ATTR]: "0",
[EDIT_ORIGINAL_TRANSLATE_ATTR]: "3px 4px",
});
applyPositionEdits(document);
expect(el.style.getPropertyValue("translate")).toBe("13px 4px");
el.remove();
});
it("counts and applies multiple marked elements", () => {
const a = makeElement({ "data-x": "1", [EDIT_BASE_X_ATTR]: "0" });
const b = makeElement({ "data-y": "2", [EDIT_BASE_Y_ATTR]: "0" });
expect(applyPositionEdits(document)).toBe(2);
a.remove();
b.remove();
});
it("skips re-apply when the written translate was consumed externally (GSAP fold)", () => {
const el = makeElement({
"data-x": "10",
"data-y": "20",
[EDIT_BASE_X_ATTR]: "0",
[EDIT_BASE_Y_ATTR]: "0",
});
applyPositionEdits(document);
expect(el.style.getPropertyValue("translate")).toBe("10px 20px");
// GSAP folding the translate into its cached transform writes "none".
el.style.setProperty("translate", "none");
applyPositionEdits(document);
// Re-setting would double the offset on non-animated axes — must skip.
expect(el.style.getPropertyValue("translate")).toBe("none");
el.remove();
});
it("force re-applies over a clobbered translate (editor commit path)", () => {
const el = makeElement({
"data-x": "10",
"data-y": "20",
[EDIT_BASE_X_ATTR]: "0",
[EDIT_BASE_Y_ATTR]: "0",
});
applyPositionEditToElement(el);
// A drag draft overwrites the translate; the commit must recompute.
el.style.setProperty("translate", "999px 999px");
el.setAttribute("data-x", "30");
applyPositionEditToElement(el, { force: true });
expect(el.style.getPropertyValue("translate")).toBe("30px 20px");
el.remove();
});
});
+167
View File
@@ -0,0 +1,167 @@
// fallow-ignore-file code-duplication
// (splitTopLevelWhitespace intentionally mirrors the studio-side copies in
// manualEditsDom.ts / manualEditsRenderScript.ts — this module ships inside
// the self-contained runtime bundle and cannot import studio code.)
/**
* Editor position edits (SDK `moveElement`) applied at render time.
*
* The SDK's `moveElement` writes `data-x` / `data-y` plus a captured baseline
* (`data-hf-edit-base-x` / `data-hf-edit-base-y` — the values before the first
* edit). The runtime renders the edit as the DELTA between the two, via the
* independent CSS `translate` longhand, so it composes additively with any
* position the composition itself produces (GSAP tweens, `tl.set`, CSS).
*
* Why `translate` and why after timeline bind: GSAP folds a `translate` that
* is present when it FIRST parses an element into its cached transform (and
* an absolute tween then discards it on the animated axis — the per-axis loss
* bug). A `translate` set AFTER that parse is never read, cleared, or baked
* by GSAP 3.x on subsequent seeks, so a single application at bind time holds
* for the whole timeline. Before the first apply, the element's transform
* parse is primed (gsap.getProperty) so tweens and positioned set()s that
* first RENDER later reuse the cache instead of folding the edit. Known
* limitation: if GSAP itself loads only after the apply ran, a later tween's
* first parse still folds the edit (the fold guard then skips re-apply and
* emits position_edit_fold_skipped instead of double-applying).
*/
import { emitAnalyticsEvent } from "./analytics";
export const EDIT_BASE_X_ATTR = "data-hf-edit-base-x";
export const EDIT_BASE_Y_ATTR = "data-hf-edit-base-y";
export const EDIT_ORIGINAL_TRANSLATE_ATTR = "data-hf-edit-original-translate";
const num = (value: string | null): number => {
const n = parseFloat(value ?? "");
return Number.isFinite(n) ? n : 0;
};
/** Split "10px 20px" / "calc(1px + 2px) 3px" on top-level whitespace only. */
const splitTopLevelWhitespace = (value: string): string[] => {
const parts: string[] = [];
let depth = 0;
let current = "";
for (const char of value.trim()) {
if (char === "(") depth += 1;
if (char === ")") depth = Math.max(0, depth - 1);
if (/\s/.test(char) && depth === 0) {
if (current) parts.push(current);
current = "";
} else {
current += char;
}
}
if (current) parts.push(current);
return parts;
};
const PX_VALUE = /^-?(?:\d+(?:\.\d+)?|\.\d+)px$/;
/** Sum two lengths — numerically when both are plain px, via calc() otherwise. */
const addLengths = (a: string, b: string): string => {
if (PX_VALUE.test(a) && PX_VALUE.test(b)) return `${parseFloat(a) + parseFloat(b)}px`;
return `calc(${a} + ${b})`;
};
/** Compose the edit delta with the element's pre-edit translate value. */
export const composeTranslate = (original: string, x: string, y: string): string => {
if (!original || original === "none") return `${x} ${y}`;
const [ox, oy, oz] = splitTopLevelWhitespace(original);
if (ox === undefined) return `${x} ${y}`;
if (oy === undefined) return `${addLengths(ox, x)} ${y}`;
const z = oz === undefined ? "" : ` ${oz}`;
return `${addLengths(ox, x)} ${addLengths(oy, y)}${z}`;
};
/**
* Force GSAP (when present) to parse and cache the element's transform BEFORE
* the edit translate is written. GSAP folds a CSS `translate` it sees at an
* element's first parse into its cached transform (losing it per-axis on
* absolute tweens); once the cache exists, later tweens and positioned set()s
* reuse it and never read the translate again. gsap.getProperty parses
* without mutating the element. Best-effort — absent or failing GSAP is fine.
*/
const primeGsapTransformCache = (el: HTMLElement): void => {
try {
const view = el.ownerDocument.defaultView as
| (Window & { gsap?: { getProperty?: (t: Element, p: string) => unknown } })
| null;
view?.gsap?.getProperty?.(el, "x");
} catch {
// parse priming is an optimization, never a requirement
}
};
/** The element's effective translate: inline if set, computed otherwise ("" = none). */
export const readCurrentTranslate = (el: HTMLElement): string => {
const inline = el.style.getPropertyValue("translate").trim();
if (inline) return inline === "none" ? "" : inline;
try {
const view = el.ownerDocument.defaultView;
const computed = view ? view.getComputedStyle(el).getPropertyValue("translate").trim() : "";
return computed === "none" ? "" : computed;
} catch {
return "";
}
};
/**
* The translate value this module last wrote per element. When a re-apply
* (timeline rebind) finds the element's inline translate no longer matching,
* something else consumed it — in practice GSAP folding it into the cached
* transform when a lazily-created tween first-parsed the element. Re-setting
* it then would DOUBLE the offset on every axis the tween doesn't animate, so
* the non-forced path skips instead (degrading to the documented fold-loss).
*/
const lastAppliedTranslate = new WeakMap<HTMLElement, string>();
/**
* Apply one element's position edit. Idempotent — the pre-edit translate is
* captured exactly once (into EDIT_ORIGINAL_TRANSLATE_ATTR, empty string
* meaning "none") on first application, and every application recomputes from
* that baseline.
*
* `force` re-applies even when the previously written translate was clobbered
* externally — used by editor commits, where the current inline translate is
* the draft-composed one and must be overwritten.
*/
export function applyPositionEditToElement(el: HTMLElement, opts?: { force?: boolean }): void {
const previous = lastAppliedTranslate.get(el);
if (
!opts?.force &&
previous !== undefined &&
el.style.getPropertyValue("translate") !== previous
) {
// Observable signal for the documented degradation — without it, a
// fold-loss surfaces to users only as "my edit didn't stick".
emitAnalyticsEvent("position_edit_fold_skipped", {
hfId: el.getAttribute("data-hf-id"),
});
return;
}
const dx = num(el.getAttribute("data-x")) - num(el.getAttribute(EDIT_BASE_X_ATTR));
const dy = num(el.getAttribute("data-y")) - num(el.getAttribute(EDIT_BASE_Y_ATTR));
if (!el.hasAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR)) {
el.setAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR, readCurrentTranslate(el));
}
if (previous === undefined) primeGsapTransformCache(el);
const original = el.getAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR) ?? "";
const value = composeTranslate(original, `${dx}px`, `${dy}px`);
el.style.setProperty("translate", value);
lastAppliedTranslate.set(el, el.style.getPropertyValue("translate"));
}
/**
* Apply all pending position edits in the document. Returns the number of
* elements updated.
*/
export function applyPositionEdits(doc: Document): number {
const marked = doc.querySelectorAll(`[${EDIT_BASE_X_ATTR}], [${EDIT_BASE_Y_ATTR}]`);
let applied = 0;
for (let i = 0; i < marked.length; i++) {
const el = marked[i];
if (!(el instanceof HTMLElement)) continue;
applyPositionEditToElement(el);
applied += 1;
}
return applied;
}
+5 -1
View File
@@ -13,7 +13,11 @@
"outDir": "./dist",
"rootDir": "./src"
},
"files": ["src/runtime/clipTree.ts", "src/runtime/mediaVolumeEnvelope.ts"],
"files": [
"src/runtime/clipTree.ts",
"src/runtime/mediaVolumeEnvelope.ts",
"src/runtime/positionEdits.ts"
],
"include": ["src/**/*"],
"exclude": [
"node_modules",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/engine",
"version": "0.7.29",
"version": "0.7.36",
"description": "Seekable web page to video rendering engine (Puppeteer + FFmpeg)",
"repository": {
"type": "git",
@@ -0,0 +1,271 @@
// fallow-ignore-file unused-file code-duplication complexity
/**
* Browser acceptance test: SDK moveElement edits survive GSAP animation
* per-axis (the AI Studio embedded-editor per-axis loss bug).
*
* Launches headless Chrome with real GSAP + the real runtime IIFE, loads a
* fixture whose elements carry committed moveElement state (data-x/data-y +
* data-hf-edit-base-x/y), seeks the timeline across its range, and asserts
* the rendered position reflects the edit on BOTH axes at every sample:
* - an X-animated element keeps its edited offset while X animates
* - a Y-animated element keeps its edited offset while Y animates
* - a static element keeps both
*
* Runs in the plain embedded runtime — no Studio shell, no manual-edits
* render script — matching what third-party SDK consumers load.
*
* Requires: puppeteer + gsap (monorepo deps, dynamically resolved; skips
* with a notice when unavailable).
* Run: cd packages/engine && npx tsx scripts/test-runtime-position-edits-browser.ts
*/
import { createRequire } from "node:module";
import { readFileSync } from "node:fs";
import { resolve as resolvePath, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { buildHyperframesRuntimeScript } from "../../core/src/inline-scripts/hyperframesRuntime.engine";
const thisDir = dirname(fileURLToPath(import.meta.url));
function assert(condition: unknown, message: string): void {
if (!condition) {
throw new Error(`FAIL: ${message}`);
}
}
function loadGsapSource(): string | null {
const req = createRequire(import.meta.url);
// gsap is a dep of studio / player / sdk-playground, hoisted in the
// workspace store — resolve through whichever package has it.
for (const pkg of ["studio", "player", "sdk-playground"]) {
try {
const path = req.resolve("gsap/dist/gsap.min.js", {
paths: [resolvePath(thisDir, `../../${pkg}`)],
});
return readFileSync(path, "utf8");
} catch {
// try the next package
}
}
return null;
}
interface Sample {
t: number;
ax: { x: number; y: number };
ay: { x: number; y: number };
axy: { x: number; y: number };
ts: { x: number; y: number };
st: { x: number; y: number };
}
async function main(): Promise<void> {
let puppeteer;
try {
puppeteer = (await import("puppeteer")).default;
} catch {
console.log(
JSON.stringify({
event: "runtime_position_edits_browser_test_skipped",
reason: "puppeteer not available",
}),
);
return;
}
const gsapSource = loadGsapSource();
if (gsapSource === null) {
console.log(
JSON.stringify({
event: "runtime_position_edits_browser_test_skipped",
reason: "gsap not available",
}),
);
return;
}
const runtimeSource = buildHyperframesRuntimeScript({ minify: false });
assert(
runtimeSource !== null,
"buildHyperframesRuntimeScript returned null — entry.ts not found",
);
// Committed moveElement state: every element moved by (50, -70). data-x/y
// hold the post-edit values; data-hf-edit-base-x/y hold the pre-edit ones
// (absent → "0"), exactly as handleMoveElement serializes them.
const html = `<!DOCTYPE html>
<html><head><style>
body { margin: 0; }
.el { position: absolute; left: 0; top: 0; width: 40px; height: 40px; }
</style></head><body>
<div data-composition-id="root" data-width="1920" data-height="1080" data-duration="4">
<div id="ax" class="clip el" data-hf-id="hf-ax" data-start="0" data-duration="4"
data-x="50" data-y="-70" data-hf-edit-base-x="0" data-hf-edit-base-y="0"></div>
<div id="ay" class="clip el" data-hf-id="hf-ay" data-start="0" data-duration="4"
data-x="50" data-y="-70" data-hf-edit-base-x="0" data-hf-edit-base-y="0"></div>
<div id="axy" class="clip el" data-hf-id="hf-axy" data-start="0" data-duration="4"
data-x="50" data-y="-70" data-hf-edit-base-x="0" data-hf-edit-base-y="0"></div>
<div id="ts" class="clip el" data-hf-id="hf-ts" data-start="0" data-duration="4"
data-x="50" data-y="-70" data-hf-edit-base-x="0" data-hf-edit-base-y="0"></div>
<div id="st" class="clip el" data-hf-id="hf-st" data-start="0" data-duration="4"
data-x="50" data-y="-70" data-hf-edit-base-x="0" data-hf-edit-base-y="0"></div>
</div>
<script>${gsapSource}</script>
<script>
window.__timelines = window.__timelines || {};
var tl = gsap.timeline({ paused: true });
tl.fromTo("#ax", { x: 0 }, { x: 400, duration: 4, ease: "none" }, 0);
tl.fromTo("#ay", { y: 0 }, { y: 300, duration: 4, ease: "none" }, 0);
tl.fromTo("#axy", { x: 0, y: 0 }, { x: 400, y: 300, duration: 4, ease: "none" }, 0);
tl.set("#ts", { x: 200, y: 100 }, 1.0);
// #st is never targeted by GSAP.
window.__timelines.main = tl;
</script>
<script>${runtimeSource}</script>
</body></html>`;
const browser = await puppeteer.launch({
headless: true,
args: ["--no-sandbox", "--disable-setuid-sandbox"],
});
try {
const page = await browser.newPage();
await page.setContent(html, { waitUntil: "networkidle0", timeout: 10000 });
// The runtime applies position edits after it binds the timeline — wait
// for the translate to land on a marked element. String form: tsx/esbuild
// injects a __name helper into serialized closures that the page lacks.
await page.waitForFunction(
`(function () {
var el = document.getElementById("ax");
return el !== null && getComputedStyle(el).translate !== "none";
})()`,
{ timeout: 10000 },
);
const sampleScript = `(function (time) {
if (window.__player && typeof window.__player.renderSeek === "function") {
window.__player.renderSeek(time);
} else if (window.__hf && typeof window.__hf.seek === "function") {
window.__hf.seek(time);
} else {
throw new Error("no runtime seek surface (__player.renderSeek / __hf.seek)");
}
function read(id) {
var el = document.getElementById(id);
if (!el) throw new Error("missing #" + id);
var cs = getComputedStyle(el);
var m = new DOMMatrix(cs.transform === "none" ? "" : cs.transform);
var parts = cs.translate === "none" ? [] : cs.translate.split(" ");
var tx = parts.length > 0 ? parseFloat(parts[0]) : 0;
var ty = parts.length > 1 ? parseFloat(parts[1]) : 0;
return { x: m.m41 + tx, y: m.m42 + ty };
}
return {
t: time,
ax: read("ax"),
ay: read("ay"),
axy: read("axy"),
ts: read("ts"),
st: read("st"),
};
})`;
const samples: Sample[] = [];
for (const t of [0, 1, 2.5, 4]) {
const sample = (await page.evaluate(`(${sampleScript})(${t})`)) as Sample;
samples.push(sample);
}
const close = (actual: number, expected: number): boolean => Math.abs(actual - expected) <= 0.5;
for (const s of samples) {
// X-animated: x = animation (100·t) + edit (50); y = edit (−70).
assert(
close(s.ax.x, 100 * s.t + 50),
`t=${s.t}: X-animated element x should be ${100 * s.t + 50}, got ${s.ax.x}`,
);
assert(close(s.ax.y, -70), `t=${s.t}: X-animated element y should keep -70, got ${s.ax.y}`);
// Y-animated: y = animation (75·t) + edit (−70); x = edit (50).
assert(close(s.ay.x, 50), `t=${s.t}: Y-animated element x should keep 50, got ${s.ay.x}`);
assert(
close(s.ay.y, 75 * s.t - 70),
`t=${s.t}: Y-animated element y should be ${75 * s.t - 70}, got ${s.ay.y}`,
);
// Both-axis-animated: both axes = animation + edit (the shape that
// originated the per-axis loss bug).
assert(
close(s.axy.x, 100 * s.t + 50),
`t=${s.t}: XY-animated element x should be ${100 * s.t + 50}, got ${s.axy.x}`,
);
assert(
close(s.axy.y, 75 * s.t - 70),
`t=${s.t}: XY-animated element y should be ${75 * s.t - 70}, got ${s.axy.y}`,
);
// tl.set at t=1.0: before it fires, position = edit only; after, set + edit.
const setX = s.t >= 1.0 ? 200 : 0;
const setY = s.t >= 1.0 ? 100 : 0;
assert(
close(s.ts.x, setX + 50),
`t=${s.t}: tl.set element x should be ${setX + 50}, got ${s.ts.x}`,
);
assert(
close(s.ts.y, setY - 70),
`t=${s.t}: tl.set element y should be ${setY - 70}, got ${s.ts.y}`,
);
// Static: both axes hold the edit.
assert(close(s.st.x, 50), `t=${s.t}: static element x should be 50, got ${s.st.x}`);
assert(close(s.st.y, -70), `t=${s.t}: static element y should be -70, got ${s.st.y}`);
}
// GSAP-free composition: no window.gsap, no timelines — the edit must
// still render (applied at runtime init, not only at timeline bind).
const gsapFreeHtml = `<!DOCTYPE html>
<html><head><style>
body { margin: 0; }
.el { position: absolute; left: 0; top: 0; width: 40px; height: 40px; }
</style></head><body>
<div data-composition-id="root" data-width="1920" data-height="1080" data-duration="2">
<div id="st" class="clip el" data-hf-id="hf-st" data-start="0" data-duration="2"
data-x="50" data-y="-70" data-hf-edit-base-x="0" data-hf-edit-base-y="0"></div>
</div>
<script>${runtimeSource}</script>
</body></html>`;
const page2 = await browser.newPage();
await page2.setContent(gsapFreeHtml, { waitUntil: "networkidle0", timeout: 10000 });
await page2.waitForFunction(
`(function () {
var el = document.getElementById("st");
return el !== null && getComputedStyle(el).translate !== "none";
})()`,
{ timeout: 10000 },
);
const gsapFree = (await page2.evaluate(
`(function () {
var cs = getComputedStyle(document.getElementById("st"));
return { translate: cs.translate };
})()`,
)) as { translate: string };
assert(
gsapFree.translate === "50px -70px",
`GSAP-free composition should render the edit as translate 50px -70px, got ${gsapFree.translate}`,
);
console.log(
JSON.stringify({
event: "runtime_position_edits_browser_test_passed",
samples,
gsapFree,
}),
);
} finally {
await browser.close();
}
}
main().catch((err) => {
console.error(err.message);
process.exit(1);
});
+96 -34
View File
@@ -3,14 +3,29 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
const { runFfmpegMock } = vi.hoisted(() => ({
runFfmpegMock: vi.fn(async () => ({
success: true,
durationMs: 1,
stderr: "",
exitCode: 0,
})),
}));
// The mix filter graph is written to a temp file and passed via
// -filter_complex_script (not inlined via -filter_complex) so the command
// line doesn't scale with track count — production code deletes that file
// the moment the (real) ffmpeg process exits. The mock captures each call's
// filter content synchronously, while the file still exists, into an
// index-aligned side array (rather than re-reading it from disk after
// processCompositionAudio resolves, by which point it's already gone).
const { runFfmpegMock, capturedFilterScripts } = vi.hoisted(() => {
const capturedFilterScripts: string[] = [];
return {
capturedFilterScripts,
runFfmpegMock: vi.fn(async (args: string[]) => {
const idx = args.indexOf("-filter_complex_script");
if (idx >= 0) {
const { readFileSync } = await import("node:fs");
capturedFilterScripts.push(readFileSync(args[idx + 1], "utf8"));
} else {
capturedFilterScripts.push("");
}
return { success: true, durationMs: 1, stderr: "", exitCode: 0 };
}),
};
});
vi.mock("../utils/runFfmpeg.js", () => ({
runFfmpeg: runFfmpegMock,
@@ -23,6 +38,7 @@ describe("processCompositionAudio", () => {
afterEach(() => {
runFfmpegMock.mockClear();
capturedFilterScripts.length = 0;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
@@ -57,9 +73,7 @@ describe("processCompositionAudio", () => {
expect(result.success).toBe(true);
expect(runFfmpegMock).toHaveBeenCalledTimes(2);
const mixArgs = runFfmpegMock.mock.calls[1]?.[0];
const filterIndex = mixArgs.indexOf("-filter_complex");
const filter = mixArgs[filterIndex + 1];
const filter = capturedFilterScripts[1];
expect(filter).toContain("volume=0");
expect(filter).toContain("[mixed]volume=1[out]");
@@ -119,8 +133,7 @@ describe("processCompositionAudio", () => {
// 3 prepare calls (one per track via Promise.all) precede the mix call,
// so the mix is at index 3, not index 1.
expect(runFfmpegMock).toHaveBeenCalledTimes(4);
const mixArgs = runFfmpegMock.mock.calls[3]?.[0];
const filter = mixArgs[mixArgs.indexOf("-filter_complex") + 1];
const filter = capturedFilterScripts[3];
expect(filter).toContain("amix=inputs=3");
expect(filter).not.toContain("normalize=");
@@ -161,9 +174,7 @@ describe("processCompositionAudio", () => {
expect(result.success).toBe(true);
const mixArgs = runFfmpegMock.mock.calls[1]?.[0];
const filterIndex = mixArgs.indexOf("-filter_complex");
const filter = mixArgs[filterIndex + 1];
const filter = capturedFilterScripts[1];
expect(filter).toContain("volume=");
expect(filter).toContain(":eval=frame");
@@ -211,9 +222,7 @@ describe("processCompositionAudio", () => {
expect(result.success).toBe(true);
const mixArgs = runFfmpegMock.mock.calls[1]?.[0];
const filterIndex = mixArgs.indexOf("-filter_complex");
const filter = mixArgs[filterIndex + 1];
const filter = capturedFilterScripts[1];
// One nested `if(lt(...))` is emitted per segment; cap it well under the
// FFmpeg evaluator's nesting limit (MAX_VOLUME_SEGMENTS = 32).
@@ -235,20 +244,24 @@ describe("processCompositionAudio", () => {
// Simulate an ffmpeg build that rejects the automation expression: the
// first mix attempt fails, the static-volume retry succeeds. (prepare =
// call 0, automated mix = call 1, fallback mix = call 2.)
// call 0, automated mix = call 1, fallback mix = call 2.) These two
// one-time overrides bypass the default mock's capturedFilterScripts
// push, so they push an empty placeholder themselves to keep the array
// index-aligned with call order for the fallback mix's assertion below.
runFfmpegMock
.mockImplementationOnce(async () => ({
success: true,
durationMs: 1,
stderr: "",
exitCode: 0,
}))
.mockImplementationOnce(async () => ({
success: false,
durationMs: 1,
stderr: "Error initializing filters",
exitCode: 234,
}));
.mockImplementationOnce(async () => {
capturedFilterScripts.push("");
return { success: true, durationMs: 1, stderr: "", exitCode: 0 };
})
.mockImplementationOnce(async () => {
capturedFilterScripts.push("");
return {
success: false,
durationMs: 1,
stderr: "Error initializing filters",
exitCode: 234,
};
});
const result = await processCompositionAudio(
[
@@ -280,12 +293,61 @@ describe("processCompositionAudio", () => {
expect(result.error).toMatch(/base volume/i);
// The fallback mix omits the automation expression (base volume only).
const fallbackArgs = runFfmpegMock.mock.calls[2]?.[0];
const fallbackFilter = fallbackArgs[fallbackArgs.indexOf("-filter_complex") + 1];
const fallbackFilter = capturedFilterScripts[2];
expect(fallbackFilter).not.toContain(":eval=frame");
expect(fallbackFilter).toContain("volume=0.8");
});
it("keeps the ffmpeg command line short with a large track count (regression for spawn ENAMETOOLONG)", async () => {
const baseDir = mkdtempSync(join(tmpdir(), "hf-audio-base-"));
const workDir = mkdtempSync(join(tmpdir(), "hf-audio-work-"));
tempDirs.push(baseDir, workDir);
// Reported in the wild at 146 timed audio clips: the old inline
// -filter_complex string scaled with track count and blew past the OS
// command-line length limit. 150 tracks reproduces the same shape.
const trackCount = 150;
const elements = Array.from({ length: trackCount }, (_, i) => {
const filename = `clip-${i}.wav`;
writeFileSync(join(baseDir, filename), "stub");
return {
id: `clip-${i}`,
src: filename,
start: i * 0.1,
end: i * 0.1 + 0.5,
mediaStart: 0,
layer: i,
volume: 1,
type: "audio" as const,
};
});
const result = await processCompositionAudio(
elements,
baseDir,
workDir,
join(baseDir, "out.m4a"),
trackCount * 0.1 + 0.5,
);
expect(result.success).toBe(true);
expect(result.tracksProcessed).toBe(trackCount);
const mixArgs = runFfmpegMock.mock.calls.at(-1)?.[0] as string[];
expect(mixArgs).toContain("-filter_complex_script");
expect(mixArgs).not.toContain("-filter_complex");
// The only things that scale with track count are the -i pairs (short,
// fixed-size each) and the filter SCRIPT FILE's content (off the command
// line entirely) — not the args array's own total character length.
const argsLength = mixArgs.join(" ").length;
expect(argsLength).toBeLessThan(20_000);
const filter = capturedFilterScripts.at(-1);
expect(filter).toContain(`amix=inputs=${trackCount}`);
expect((filter?.match(/atrim=/g) ?? []).length).toBe(trackCount);
});
it("prepares percent-encoded non-Latin audio srcs from decoded filesystem paths", async () => {
const baseDir = mkdtempSync(join(tmpdir(), "hf-audio-base-"));
const workDir = mkdtempSync(join(tmpdir(), "hf-audio-work-"));
+30 -10
View File
@@ -4,7 +4,7 @@
* Processes and mixes audio tracks using FFmpeg.
*/
import { existsSync, mkdirSync, rmSync } from "fs";
import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, rmSync, writeFileSync } from "fs";
import { isAbsolute, join, dirname } from "path";
import { parseHTML } from "linkedom";
import { extractAudioMetadata } from "../utils/ffprobe.js";
@@ -384,11 +384,9 @@ async function mixAudioTracks(
const outputDir = dirname(outputPath);
if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
const buildArgs = (ignoreAutomation: boolean): string[] => {
const inputs: string[] = [];
const buildFilterComplex = (ignoreAutomation: boolean): string => {
const filterParts: string[] = [];
tracks.forEach((track, i) => {
inputs.push("-i", track.srcPath);
const delayMs = Math.round(track.start * 1000);
const trimDuration = track.end - track.start;
const volumeFilter = buildVolumeExpression(track, ignoreAutomation);
@@ -403,12 +401,31 @@ async function mixAudioTracks(
// gain by track count so per-track volumes authored in data-volume are preserved.
const compensatedGain = masterOutputGain * tracks.length;
const postMixGainFilter = `[mixed]volume=${formatFilterNumber(compensatedGain)}[out]`;
const fullFilter = [...filterParts, mixFilter, postMixGainFilter].join(";");
return [...filterParts, mixFilter, postMixGainFilter].join(";");
};
return [
// A large track count (100+) makes the inline `-filter_complex <string>`
// argument scale linearly with track count until it exceeds the OS
// command-line length limit — spawn ENAMETOOLONG, seen in practice at 146
// tracks — even though every individual filter segment is short. FFmpeg's
// own `-filter_complex_script <file>` reads the same graph from disk
// instead, sidestepping the argv limit for the one component of this
// command line that actually grows with the composition.
const runMix = (ignoreAutomation: boolean) => {
const inputs: string[] = [];
tracks.forEach((track) => inputs.push("-i", track.srcPath));
const scriptDir = mkdtempSync(join(outputDir, ".filter-complex-"));
const scriptPath = join(scriptDir, "graph.txt");
const fd = openSync(scriptPath, "wx", 0o600);
try {
writeFileSync(fd, buildFilterComplex(ignoreAutomation));
} finally {
closeSync(fd);
}
const args = [
...inputs,
"-filter_complex",
fullFilter,
"-filter_complex_script",
scriptPath,
"-map",
"[out]",
"-acodec",
@@ -420,9 +437,12 @@ async function mixAudioTracks(
"-y",
outputPath,
];
return runFfmpeg(args, { signal, timeout: ffmpegProcessTimeout }).finally(() =>
rmSync(scriptDir, { recursive: true, force: true }),
);
};
let result = await runFfmpeg(buildArgs(false), { signal, timeout: ffmpegProcessTimeout });
let result = await runMix(false);
// Defense in depth: volume automation is folded into an FFmpeg `volume`
// expression whose evaluator limits are build-dependent (see
@@ -432,7 +452,7 @@ async function mixAudioTracks(
let degradedAutomation = false;
const hasAutomation = tracks.some((track) => (track.volumeKeyframes?.length ?? 0) > 0);
if (!result.success && !signal?.aborted && hasAutomation) {
const retry = await runFfmpeg(buildArgs(true), { signal, timeout: ffmpegProcessTimeout });
const retry = await runMix(true);
if (retry.success) {
result = retry;
degradedAutomation = true;
@@ -8,6 +8,8 @@ import {
injectVideoFramesBatch,
syncVideoFrameVisibility,
shouldDefaultCaptureBeyondViewport,
applyDomLayerMask,
removeDomLayerMask,
} from "./screenshotService.js";
// Stub a Page + CDPSession just enough that pageScreenshotCapture can call
@@ -361,6 +363,29 @@ describe("video-frame injection respects ancestor visibility", () => {
} as unknown as Page;
}
function installDomMaskGlobals(setup: { window: Window; document: Document }): () => void {
const globals = globalThis as unknown as {
window?: Window;
document?: Document;
HTMLElement?: typeof HTMLElement;
CSS?: typeof CSS;
};
const previousWindow = globals.window;
const previousDocument = globals.document;
const previousHTMLElement = globals.HTMLElement;
const previousCSS = globals.CSS;
globals.window = setup.window;
globals.document = setup.document;
globals.HTMLElement = setup.window.HTMLElement;
globals.CSS = { escape: (value: string) => value.replace(/[^a-zA-Z0-9_-]/g, "\\$&") } as CSS;
return () => {
globals.window = previousWindow;
globals.document = previousDocument;
globals.HTMLElement = previousHTMLElement;
globals.CSS = previousCSS;
};
}
it("skips replacement-frame creation when the video's host has visibility:hidden", async () => {
const { teardown, setup } = withGlobals(setupHostHiddenScenario({ visibility: "hidden" }));
try {
@@ -546,4 +571,105 @@ describe("video-frame injection respects ancestor visibility", () => {
expect(seededImg.style.visibility).toBe("hidden");
expect(setPropertySpy).toHaveBeenCalledWith("visibility", "hidden", "important");
});
it("applyDomLayerMask does not revive hidden idless timed descendants of a shown layer", async () => {
const { window, document } = parseHTML(
`<html><head></head><body>
<div id="scene" data-start="0" data-duration="6">
<div class="label" data-start="4.5" data-duration="1.5">late label</div>
</div>
</body></html>`,
);
const scene = document.getElementById("scene") as HTMLElement;
const label = document.querySelector(".label") as HTMLElement;
label.style.visibility = "hidden";
Object.defineProperty(window, "getComputedStyle", {
configurable: true,
value: (el: Element) => ({
display: (el as HTMLElement).style.display || "block",
visibility: (el as HTMLElement).style.visibility || "visible",
}),
});
const teardown = installDomMaskGlobals({ window, document });
try {
await applyDomLayerMask(passthroughPage(), ["scene"], []);
expect(scene.style.visibility || "").toBe("");
expect(label.style.visibility).toBe("hidden");
await removeDomLayerMask(passthroughPage(), []);
expect(label.style.visibility).toBe("hidden");
expect(label.hasAttribute("data-hf-dom-layer-mask-hidden")).toBe(false);
} finally {
teardown();
}
});
it("removeDomLayerMask keeps hidden timed descendants hidden when they are also extraHideIds", async () => {
const { window, document } = parseHTML(
`<html><head></head><body>
<div id="scene" data-start="0" data-duration="6">
<div id="caption" data-start="4.5" data-duration="1.5">late label</div>
</div>
</body></html>`,
);
const caption = document.getElementById("caption") as HTMLElement;
caption.style.visibility = "hidden";
Object.defineProperty(window, "getComputedStyle", {
configurable: true,
value: (el: Element) => ({
display: (el as HTMLElement).style.display || "block",
visibility: (el as HTMLElement).style.visibility || "visible",
}),
});
const teardown = installDomMaskGlobals({ window, document });
try {
await applyDomLayerMask(passthroughPage(), ["scene"], ["caption"]);
await removeDomLayerMask(passthroughPage(), ["caption"]);
expect(caption.style.visibility).toBe("hidden");
expect(caption.hasAttribute("data-hf-dom-layer-mask-hidden")).toBe(false);
} finally {
teardown();
}
});
it("removeDomLayerMask restores extraHideIds and render frames to previous visibility", async () => {
const { window, document } = parseHTML(
`<html><head></head><body>
<div id="visible-caption" data-start="0" data-duration="1">current</div>
<video id="clip" data-start="0" data-duration="1"></video>
<img id="__render_frame_clip__" />
</body></html>`,
);
const visibleCaption = document.getElementById("visible-caption") as HTMLElement;
const clip = document.getElementById("clip") as HTMLElement;
const renderFrame = document.getElementById("__render_frame_clip__") as HTMLElement;
visibleCaption.style.visibility = "visible";
clip.style.visibility = "hidden";
renderFrame.style.setProperty("visibility", "hidden", "important");
Object.defineProperty(window, "getComputedStyle", {
configurable: true,
value: (el: Element) => ({
display: (el as HTMLElement).style.display || "block",
visibility: (el as HTMLElement).style.visibility || "visible",
}),
});
const teardown = installDomMaskGlobals({ window, document });
try {
await applyDomLayerMask(passthroughPage(), [], ["visible-caption", "clip"]);
await removeDomLayerMask(passthroughPage(), ["visible-caption", "clip"]);
expect(visibleCaption.style.visibility).toBe("visible");
expect(clip.style.visibility).toBe("hidden");
expect(renderFrame.style.visibility).toBe("hidden");
} finally {
teardown();
}
});
});
+114 -21
View File
@@ -261,6 +261,9 @@ export async function captureAlphaPng(page: Page, width: number, height: number)
* tests can assert presence/absence of the mask between captures.
*/
export const DOM_LAYER_MASK_STYLE_ID = "__hf_dom_layer_mask__";
const DOM_LAYER_MASK_HIDDEN_ATTR = "data-hf-dom-layer-mask-hidden";
const DOM_LAYER_MASK_PREV_VISIBILITY_ATTR = "data-hf-dom-layer-mask-prev-visibility";
const DOM_LAYER_MASK_PREV_PRIORITY_ATTR = "data-hf-dom-layer-mask-prev-priority";
/**
* Mask the DOM so a single layer screenshot captures ONLY the layer's pixels.
@@ -282,12 +285,15 @@ export const DOM_LAYER_MASK_STYLE_ID = "__hf_dom_layer_mask__";
* layer elements remain visible even though intermediate parents are
* hidden by the mass-hide rule.
* 2. Inline-hide each `extraHideId` (and its `__render_frame_*` sibling) with
* `visibility: hidden !important`. Inline `!important` beats stylesheet
* `!important`, so this overrides the show rule for elements that fall
* under a show selector but should NOT paint — typically other-layer
* elements that are descendants of a container layer (for example HDR
* videos and other-layer SDR videos are descendants of `#root` when we
* capture the root DOM layer).
* `visibility: hidden !important`, while first recording its previous
* inline visibility. Inline `!important` beats stylesheet `!important`,
* so this overrides the show rule for elements that fall under a show
* selector but should NOT paint — typically other-layer elements that are
* descendants of a container layer (for example HDR videos and other-layer
* SDR videos are descendants of `#root` when we capture the root DOM layer).
* 3. Inline-hide timed descendants of shown elements that were hidden before
* the mask was installed. This covers idless child clips and same-layer
* descendants that the `extraHideIds` id list cannot represent.
*
* Only `visibility` is set on extraHideIds — never `opacity`. CSS opacity is
* multiplicative through the descendant chain and a descendant cannot escape
@@ -315,12 +321,71 @@ export async function applyDomLayerMask(
extraHideIds: string[],
): Promise<void> {
await page.evaluate(
(args: { show: string[]; hide: string[]; styleId: string }) => {
(args: {
show: string[];
hide: string[];
styleId: string;
hiddenAttr: string;
prevVisibilityAttr: string;
prevPriorityAttr: string;
}) => {
const existing = document.getElementById(args.styleId);
if (existing) existing.remove();
const restoreMaskedElements = () => {
const masked = document.querySelectorAll(`[${args.hiddenAttr}="1"]`);
for (const node of masked) {
if (!(node instanceof HTMLElement)) continue;
const prevVisibility = node.getAttribute(args.prevVisibilityAttr);
const prevPriority = node.getAttribute(args.prevPriorityAttr);
if (prevVisibility === null) {
node.style.removeProperty("visibility");
} else {
node.style.setProperty("visibility", prevVisibility, prevPriority ?? "");
}
node.removeAttribute(args.hiddenAttr);
node.removeAttribute(args.prevVisibilityAttr);
node.removeAttribute(args.prevPriorityAttr);
}
};
restoreMaskedElements();
const rememberAndHideElement = (el: HTMLElement) => {
if (el.getAttribute(args.hiddenAttr) !== "1") {
const prevVisibility = el.style.getPropertyValue("visibility");
const prevPriority =
typeof el.style.getPropertyPriority === "function"
? el.style.getPropertyPriority("visibility")
: "";
if (prevVisibility) {
el.setAttribute(args.prevVisibilityAttr, prevVisibility);
} else {
el.removeAttribute(args.prevVisibilityAttr);
}
if (prevPriority) {
el.setAttribute(args.prevPriorityAttr, prevPriority);
} else {
el.removeAttribute(args.prevPriorityAttr);
}
el.setAttribute(args.hiddenAttr, "1");
}
el.style.setProperty("visibility", "hidden", "important");
};
const hiddenTimedDescendants: HTMLElement[] = [];
const rememberHiddenTimedDescendants = (root: Element) => {
for (const node of root.querySelectorAll("[data-start]")) {
if (!(node instanceof HTMLElement)) continue;
const computed = window.getComputedStyle(node);
if (computed.visibility !== "hidden" && computed.display !== "none") continue;
hiddenTimedDescendants.push(node);
}
};
const showSelectors: string[] = [];
for (const id of args.show) {
const el = document.getElementById(id);
if (el) rememberHiddenTimedDescendants(el);
const escaped = CSS.escape(id);
showSelectors.push(`#${escaped}`, `#${escaped} *`);
const renderEscaped = CSS.escape(`__render_frame_${id}__`);
@@ -338,26 +403,38 @@ export async function applyDomLayerMask(
style.textContent = `${massHideRule}\n${showRule}`;
document.head.appendChild(style);
for (const el of hiddenTimedDescendants) {
rememberAndHideElement(el);
}
for (const id of args.hide) {
const el = document.getElementById(id);
if (el) {
el.style.setProperty("visibility", "hidden", "important");
rememberAndHideElement(el);
}
const img = document.getElementById(`__render_frame_${id}__`);
if (img) {
img.style.setProperty("visibility", "hidden", "important");
rememberAndHideElement(img);
}
}
},
{ show: showIds, hide: extraHideIds, styleId: DOM_LAYER_MASK_STYLE_ID },
{
show: showIds,
hide: extraHideIds,
styleId: DOM_LAYER_MASK_STYLE_ID,
hiddenAttr: DOM_LAYER_MASK_HIDDEN_ATTR,
prevVisibilityAttr: DOM_LAYER_MASK_PREV_VISIBILITY_ATTR,
prevPriorityAttr: DOM_LAYER_MASK_PREV_PRIORITY_ATTR,
},
);
}
/**
* Tear down the mask installed by applyDomLayerMask.
*
* Removes the mask stylesheet and clears the inline `visibility` properties
* set on `extraHideIds` (and their `__render_frame_*` siblings).
* Removes the mask stylesheet and restores the inline `visibility` values
* temporarily overwritten for hidden timed descendants, `extraHideIds`, and
* their `__render_frame_*` siblings.
*
* IMPORTANT: We do NOT strip inline `opacity` here. applyDomLayerMask only
* ever sets `visibility` (never `opacity`), so any inline opacity present on
@@ -367,21 +444,37 @@ export async function applyDomLayerMask(
* we strip opacity here and then seek to the same time for the next layer,
* GSAP won't put it back and the wrapper will render fully opaque.
*/
export async function removeDomLayerMask(page: Page, extraHideIds: string[]): Promise<void> {
export async function removeDomLayerMask(page: Page, _extraHideIds: string[]): Promise<void> {
await page.evaluate(
(args: { hide: string[]; styleId: string }) => {
(args: {
styleId: string;
hiddenAttr: string;
prevVisibilityAttr: string;
prevPriorityAttr: string;
}) => {
const style = document.getElementById(args.styleId);
if (style) style.remove();
for (const id of args.hide) {
const el = document.getElementById(id);
if (el) {
el.style.removeProperty("visibility");
const masked = document.querySelectorAll(`[${args.hiddenAttr}="1"]`);
for (const node of masked) {
if (!(node instanceof HTMLElement)) continue;
const prevVisibility = node.getAttribute(args.prevVisibilityAttr);
const prevPriority = node.getAttribute(args.prevPriorityAttr);
if (prevVisibility === null) {
node.style.removeProperty("visibility");
} else {
node.style.setProperty("visibility", prevVisibility, prevPriority ?? "");
}
const img = document.getElementById(`__render_frame_${id}__`);
if (img) img.style.removeProperty("visibility");
node.removeAttribute(args.hiddenAttr);
node.removeAttribute(args.prevVisibilityAttr);
node.removeAttribute(args.prevPriorityAttr);
}
},
{ hide: extraHideIds, styleId: DOM_LAYER_MASK_STYLE_ID },
{
styleId: DOM_LAYER_MASK_STYLE_ID,
hiddenAttr: DOM_LAYER_MASK_HIDDEN_ATTR,
prevVisibilityAttr: DOM_LAYER_MASK_PREV_VISIBILITY_ATTR,
prevPriorityAttr: DOM_LAYER_MASK_PREV_PRIORITY_ATTR,
},
);
}
@@ -13,7 +13,7 @@ import { EventEmitter } from "events";
import { mkdtempSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
buildStreamingArgs,
@@ -475,9 +475,17 @@ async function resolveWithin<T>(promise: Promise<T>, ms = 100): Promise<T | "tim
}
describe("spawnStreamingEncoder lifecycle and cleanup", () => {
const originalPath = process.env.PATH;
beforeEach(() => {
process.env.PATH = "";
});
afterEach(() => {
vi.resetModules();
vi.doUnmock("child_process");
if (originalPath === undefined) delete process.env.PATH;
else process.env.PATH = originalPath;
});
it("returns a success result when ffmpeg exits cleanly after close()", async () => {
@@ -371,6 +371,13 @@ export interface ElementStackingInfo {
layoutHeight: number;
opacity: number;
visible: boolean;
/**
* True when the SDR video replacement image injected beside this element is
* currently paintable. Native videos are hidden during capture, so this lets
* the layered HDR compositor keep their replacement frames in the right DOM
* layer without reviving unrelated hidden elements.
*/
renderFrameVisible: boolean;
isHdr: boolean;
transform: string; // CSS transform matrix string, e.g. "matrix(1,0,0,1,0,0)" or "none"
borderRadius: [number, number, number, number]; // [tl, tr, br, bl] in CSS px from nearest clipping ancestor
@@ -635,6 +642,17 @@ export async function queryElementStacking(
return Number.isFinite(n) ? n : 0;
}
function isElementPaintable(node: Element): boolean {
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
return (
style.visibility !== "hidden" &&
style.display !== "none" &&
rect.width > 0 &&
rect.height > 0
);
}
for (const el of elements) {
const id = el.id;
if (!id) continue;
@@ -647,11 +665,9 @@ export async function queryElementStacking(
// remains the GSAP-controlled value. Walk from the element itself to
// multiply through any ancestor opacity stacks.
const opacity = getEffectiveOpacity(el);
const visible =
style.visibility !== "hidden" &&
style.display !== "none" &&
rect.width > 0 &&
rect.height > 0;
const visible = isElementPaintable(el);
const renderFrame = document.getElementById(`__render_frame_${id}__`);
const renderFrameVisible = renderFrame ? isElementPaintable(renderFrame) : false;
// offsetWidth/offsetHeight only exist on HTMLElement (not on
// SVGElement, MathMLElement, etc.). Fall back to the bounding rect
// dimensions for non-HTML elements so callers always get sensible
@@ -668,6 +684,7 @@ export async function queryElementStacking(
layoutHeight: htmlEl?.offsetHeight || Math.round(rect.height),
opacity,
visible,
renderFrameVisible,
isHdr: hdrSet.has(id),
// For HDR elements, use the full accumulated viewport matrix so the
// affine blit can apply rotation/scale/translate properly. For DOM
@@ -1,6 +1,8 @@
// fallow-ignore-file code-duplication
import { resolve } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
assertConfiguredFfmpegBinariesExist,
getFfmpegBinary,
@@ -10,12 +12,17 @@ import {
describe("ffmpeg binary env resolution", () => {
const originalFfmpegPath = process.env.HYPERFRAMES_FFMPEG_PATH;
const originalFfprobePath = process.env.HYPERFRAMES_FFPROBE_PATH;
const originalPath = process.env.PATH;
afterEach(() => {
vi.resetModules();
vi.doUnmock("child_process");
if (originalFfmpegPath === undefined) delete process.env.HYPERFRAMES_FFMPEG_PATH;
else process.env.HYPERFRAMES_FFMPEG_PATH = originalFfmpegPath;
if (originalFfprobePath === undefined) delete process.env.HYPERFRAMES_FFPROBE_PATH;
else process.env.HYPERFRAMES_FFPROBE_PATH = originalFfprobePath;
if (originalPath === undefined) delete process.env.PATH;
else process.env.PATH = originalPath;
});
it("uses configured absolute paths when env vars are set", () => {
@@ -40,4 +47,43 @@ describe("ffmpeg binary env resolution", () => {
expect(() => assertConfiguredFfmpegBinariesExist()).not.toThrow();
});
it("prefers the real Windows exe when PATH lookup lists a cmd shim first", async () => {
vi.resetModules();
vi.doMock("child_process", () => ({
execFileSync: () => "C:\\tools\\ffmpeg.cmd\r\nC:\\tools\\ffmpeg.exe\r\n",
}));
const { getFfmpegBinary: getMockedFfmpegBinary } = await import("./ffmpegBinaries.js");
expect(getMockedFfmpegBinary()).toBe(resolve("C:\\tools\\ffmpeg.exe"));
});
it("falls back to scanning PATH when which/where fails", async () => {
const binDir = mkdtempSync(join(tmpdir(), "hyperframes-ffmpeg-path-"));
const ffmpegPath = join(binDir, process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg");
const execFileSync = vi.fn(() => {
throw new Error("lookup command failed");
});
writeFileSync(ffmpegPath, "#!/bin/sh\n");
chmodSync(ffmpegPath, 0o755);
process.env.PATH = binDir;
vi.resetModules();
vi.doMock("child_process", () => ({ execFileSync }));
try {
const { getFfmpegBinary: getMockedFfmpegBinary } = await import("./ffmpegBinaries.js");
expect(getMockedFfmpegBinary()).toBe(resolve(ffmpegPath));
expect(execFileSync).toHaveBeenCalledOnce();
} finally {
rmSync(binDir, { force: true, recursive: true });
}
});
it("calls out a mangled replacement character in configured binary paths", () => {
process.env.HYPERFRAMES_FFMPEG_PATH = "/missing/ffmpeg�.exe";
expect(() => assertConfiguredFfmpegBinariesExist()).toThrow(/replacement character|mangled/i);
});
});
+70 -13
View File
@@ -1,15 +1,71 @@
// fallow-ignore-file code-duplication
import { execFileSync } from "child_process";
import { existsSync } from "fs";
import { resolve } from "path";
import { accessSync, constants, existsSync } from "fs";
import { delimiter, join, resolve } from "path";
export const FFMPEG_PATH_ENV = "HYPERFRAMES_FFMPEG_PATH";
export const FFPROBE_PATH_ENV = "HYPERFRAMES_FFPROBE_PATH";
const pathCache = new Map<string, string | undefined>();
function candidateFileName(candidate: string): string {
return candidate.split(/[\\/]/).at(-1)?.toLowerCase() ?? candidate.toLowerCase();
}
function chooseBestPathCandidate(
name: "ffmpeg" | "ffprobe",
candidates: readonly string[],
): string | undefined {
const normalized = candidates.map((candidate) => candidate.trim()).filter(Boolean);
return (
normalized.find((candidate) => candidateFileName(candidate) === `${name}.exe`) ??
normalized.find((candidate) => candidateFileName(candidate) === name) ??
normalized.find((candidate) => !candidateFileName(candidate).match(/\.(cmd|bat)$/i)) ??
normalized[0]
);
}
function scanPath(name: "ffmpeg" | "ffprobe"): string | undefined {
const pathValue = process.env.PATH;
if (!pathValue) return undefined;
const extensions =
process.platform === "win32"
? [
".exe",
...new Set(
(process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
.split(";")
.map((ext) => ext.trim().toLowerCase())
.filter(Boolean),
),
"",
]
: [""];
const candidates: string[] = [];
for (const dir of pathValue.split(delimiter)) {
if (!dir) continue;
for (const ext of extensions) {
const candidate = join(dir, `${name}${ext}`);
if (isExecutablePathCandidate(candidate)) candidates.push(candidate);
}
}
return chooseBestPathCandidate(name, candidates);
}
function isExecutablePathCandidate(candidate: string): boolean {
if (process.platform === "win32") return existsSync(candidate);
try {
accessSync(candidate, constants.X_OK);
return true;
} catch {
return false;
}
}
function findOnPath(name: "ffmpeg" | "ffprobe"): string | undefined {
if (pathCache.has(name)) return pathCache.get(name);
let found: string | undefined;
try {
const command = process.platform === "win32" ? "where" : "which";
const output = execFileSync(command, [name], {
@@ -17,17 +73,13 @@ function findOnPath(name: "ffmpeg" | "ffprobe"): string | undefined {
stdio: ["pipe", "pipe", "pipe"],
timeout: 5000,
});
const first = output
.split(/\r?\n/)
.map((s) => s.trim())
.find(Boolean);
const resolved = first ? resolve(first) : undefined;
pathCache.set(name, resolved);
return resolved;
found = chooseBestPathCandidate(name, output.split(/\r?\n/));
} catch {
pathCache.set(name, undefined);
return undefined;
found = scanPath(name);
}
const resolved = found ? resolve(found) : undefined;
pathCache.set(name, resolved);
return resolved;
}
function getConfiguredBinary(envName: string, binaryName: "ffmpeg" | "ffprobe"): string {
@@ -49,7 +101,7 @@ export function assertConfiguredFfmpegBinariesExist(): void {
if (ffmpegPath && !existsSync(ffmpegPath)) {
throw new Error(
`[FFmpeg] FFmpeg binary not found at ${FFMPEG_PATH_ENV}="${ffmpegPath}". ` +
"Install FFmpeg or unset the override.",
`Install FFmpeg or unset the override.${pathEncodingHint(ffmpegPath)}`,
);
}
@@ -57,7 +109,12 @@ export function assertConfiguredFfmpegBinariesExist(): void {
if (ffprobePath && !existsSync(ffprobePath)) {
throw new Error(
`[FFmpeg] FFprobe binary not found at ${FFPROBE_PATH_ENV}="${ffprobePath}". ` +
"Install FFmpeg or unset the override.",
`Install FFmpeg or unset the override.${pathEncodingHint(ffprobePath)}`,
);
}
}
function pathEncodingHint(configuredPath: string): string {
if (!configuredPath.includes("\uFFFD")) return "";
return " The path contains a Unicode replacement character, which usually means it was mangled while being copied or decoded.";
}
+12
View File
@@ -166,12 +166,19 @@ function createSpawnSpy(outcomes: SpawnOutcome[]): {
describe("ffprobe missing-binary fallback", () => {
const originalFfprobePath = process.env.HYPERFRAMES_FFPROBE_PATH;
const originalPath = process.env.PATH;
function hidePathBinaries(): void {
process.env.PATH = "";
}
afterEach(() => {
vi.resetModules();
vi.doUnmock("child_process");
if (originalFfprobePath === undefined) delete process.env.HYPERFRAMES_FFPROBE_PATH;
else process.env.HYPERFRAMES_FFPROBE_PATH = originalFfprobePath;
if (originalPath === undefined) delete process.env.PATH;
else process.env.PATH = originalPath;
});
it("spawns the configured absolute FFprobe path when HYPERFRAMES_FFPROBE_PATH is set", async () => {
@@ -198,6 +205,7 @@ describe("ffprobe missing-binary fallback", () => {
it("extractMediaMetadata falls back to PNG cICP metadata when ffprobe is missing", async () => {
const { spawn, calls } = createSpawnSpy([{ kind: "missing" }]);
hidePathBinaries();
vi.resetModules();
vi.doMock("child_process", () => ({ spawn }));
@@ -294,6 +302,7 @@ describe("ffprobe missing-binary fallback", () => {
it("extractMediaMetadata rethrows ffprobe-missing error for non-image files without fallback", async () => {
const { spawn } = createSpawnSpy([{ kind: "missing" }]);
hidePathBinaries();
vi.resetModules();
vi.doMock("child_process", () => ({ spawn }));
@@ -304,6 +313,7 @@ describe("ffprobe missing-binary fallback", () => {
it("extractAudioMetadata surfaces a ffprobe-missing error verbatim", async () => {
const { spawn, calls } = createSpawnSpy([{ kind: "missing" }]);
hidePathBinaries();
vi.resetModules();
vi.doMock("child_process", () => ({ spawn }));
@@ -318,6 +328,7 @@ describe("ffprobe missing-binary fallback", () => {
it("analyzeKeyframeIntervals surfaces a ffprobe-missing error verbatim", async () => {
const { spawn, calls } = createSpawnSpy([{ kind: "missing" }]);
hidePathBinaries();
vi.resetModules();
vi.doMock("child_process", () => ({ spawn }));
@@ -332,6 +343,7 @@ describe("ffprobe missing-binary fallback", () => {
it("ffprobe-missing error message includes install hint", async () => {
const { spawn } = createSpawnSpy([{ kind: "missing" }]);
hidePathBinaries();
vi.resetModules();
vi.doMock("child_process", () => ({ spawn }));
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/gcp-cloud-run",
"version": "0.7.29",
"version": "0.7.36",
"description": "Google Cloud Run + Workflows adapter for HyperFrames distributed rendering — request handler, client-side SDK, and Terraform module.",
"repository": {
"type": "git",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/lint",
"version": "0.7.29",
"version": "0.7.36",
"repository": {
"type": "git",
"url": "https://github.com/heygen-com/hyperframes",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/parsers",
"version": "0.7.29",
"version": "0.7.36",
"repository": {
"type": "git",
"url": "https://github.com/heygen-com/hyperframes",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/player",
"version": "0.7.29",
"version": "0.7.36",
"description": "Embeddable web component for HyperFrames compositions",
"repository": {
"type": "git",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/producer",
"version": "0.7.29",
"version": "0.7.36",
"description": "HTML-to-video rendering engine using Chrome's BeginFrame API",
"repository": {
"type": "git",
@@ -0,0 +1,64 @@
import { describe, expect, it } from "vitest";
import type { ElementStackingInfo } from "@hyperframes/engine";
import { selectDomLayerShowIds } from "./hdrCompositor.js";
function makeEl(id: string, overrides?: Partial<ElementStackingInfo>): ElementStackingInfo {
return {
id,
zIndex: 0,
x: 0,
y: 0,
width: 1920,
height: 1080,
layoutWidth: 1920,
layoutHeight: 1080,
opacity: 1,
visible: true,
renderFrameVisible: false,
isHdr: false,
transform: "none",
borderRadius: [0, 0, 0, 0],
objectFit: "fill",
objectPosition: "50% 50%",
clipRect: null,
...overrides,
};
}
describe("selectDomLayerShowIds", () => {
it("does not re-show hidden DOM elements while preserving visible injected video frames", () => {
expect(
selectDomLayerShowIds(
["visible-overlay", "hidden-later-scene", "hidden-sdr-video"],
[
makeEl("visible-overlay"),
makeEl("hidden-later-scene", { visible: false }),
makeEl("hidden-sdr-video", {
visible: false,
renderFrameVisible: true,
}),
],
),
).toEqual(["visible-overlay", "hidden-sdr-video"]);
});
it("does not re-show opacity-zero scene members or their injected frames", () => {
expect(
selectDomLayerShowIds(
["active-overlay", "inactive-scene-video", "inactive-scene-label"],
[
makeEl("active-overlay"),
makeEl("inactive-scene-video", {
opacity: 0,
visible: false,
renderFrameVisible: true,
}),
makeEl("inactive-scene-label", {
opacity: 0,
visible: true,
}),
],
),
).toEqual(["active-overlay"]);
});
});
@@ -416,6 +416,17 @@ export function resolveCompositeTransfer(
return hasHdrContent && effectiveHdr ? effectiveHdr.transfer : "srgb";
}
export function selectDomLayerShowIds(
layerElementIds: string[],
fullStacking: ElementStackingInfo[],
): string[] {
const byId = new Map(fullStacking.map((el) => [el.id, el]));
return layerElementIds.filter((id) => {
const el = byId.get(id);
return !!el && el.opacity > 0 && (el.visible || el.renderFrameVisible === true);
});
}
export interface HdrCompositeContext {
log: ProducerLogger;
domSession: CaptureSession;
@@ -607,10 +618,10 @@ export async function compositeHdrFrame(
//
// The mask:
// - mass-hides every body descendant via stylesheet
// - re-shows the layer's elements (and their descendants and
// their injected `__render_frame_*` siblings) so deep-nested
// content stays visible even though intermediate ancestors
// are hidden
// - re-shows the layer's currently paintable elements (and their
// descendants and injected `__render_frame_*` siblings) so
// deep-nested content stays visible even though intermediate
// ancestors are hidden
// - inline-hides every other data-start element so they don't
// paint when they happen to be descendants of a layer element
// (most importantly: HDR videos and other-layer SDR videos
@@ -621,6 +632,17 @@ export async function compositeHdrFrame(
// border/box-shadow of cards, etc.) and the resulting opaque
// pixels overwrite previously composited HDR content beneath.
const layerIds = new Set(layer.elementIds);
const showIds = selectDomLayerShowIds(layer.elementIds, fullStacking);
if (showIds.length === 0) {
if (shouldLog) {
log.info("[diag] dom layer skipped, all elements not paintable", {
frame: debugFrameIndex,
layerIdx,
layerIds: layer.elementIds,
});
}
continue;
}
const hideIds = allElementIds.filter((id) => !layerIds.has(id));
if (hdrPerf) hdrPerf.domLayerCaptures += 1;
@@ -640,7 +662,7 @@ export async function compositeHdrFrame(
// 3. Install the mask (mass-hide stylesheet + inline-hide non-layer ids)
await timeHdrPhaseAsync(hdrPerf, "domMaskApplyMs", () =>
applyDomLayerMask(domSession.page, layer.elementIds, hideIds),
applyDomLayerMask(domSession.page, showIds, hideIds),
);
// 4. Screenshot
@@ -669,6 +691,7 @@ export async function compositeHdrFrame(
frame: debugFrameIndex,
layerIdx,
layerIds: layer.elementIds,
showIds,
hideCount: hideIds.length,
pngBytes: domPng.length,
alphaPixels,
@@ -0,0 +1,121 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ElementStackingInfo } from "@hyperframes/engine";
import {
applyDomLayerMask,
blitRgba8OverRgb48le,
captureAlphaPng,
decodePng,
removeDomLayerMask,
} from "@hyperframes/engine";
import type { ProducerLogger } from "../../../logger.js";
import type { HdrCompositeContext } from "../../hdrCompositor.js";
import { captureSceneIntoBuffer } from "./captureHdrFrameShared.js";
vi.mock("@hyperframes/engine", async (importOriginal) => {
const actual = await importOriginal<typeof import("@hyperframes/engine")>();
return {
...actual,
applyDomLayerMask: vi.fn(async () => undefined),
captureAlphaPng: vi.fn(async () => Buffer.from("png")),
decodePng: vi.fn(() => ({ data: Buffer.alloc(4), width: 1, height: 1 })),
removeDomLayerMask: vi.fn(async () => undefined),
blitRgba8OverRgb48le: vi.fn(),
};
});
function makeEl(id: string, overrides?: Partial<ElementStackingInfo>): ElementStackingInfo {
return {
id,
zIndex: 0,
x: 0,
y: 0,
width: 1,
height: 1,
layoutWidth: 1,
layoutHeight: 1,
opacity: 1,
visible: true,
renderFrameVisible: false,
isHdr: false,
transform: "none",
borderRadius: [0, 0, 0, 0],
objectFit: "fill",
objectPosition: "50% 50%",
clipRect: null,
...overrides,
};
}
function makeContext(): HdrCompositeContext {
return {
log: makeLogger(),
domSession: { page: { evaluate: vi.fn() } } as never,
beforeCaptureHook: null,
width: 1,
height: 1,
fps: 30,
compositeTransfer: "srgb",
nativeHdrImageIds: new Set(),
hdrImageBuffers: new Map(),
hdrImageTransferCache: new Map(),
hdrVideoFrameSources: new Map(),
hdrVideoStartTimes: new Map(),
imageTransfers: new Map(),
videoTransfers: new Map(),
debugDumpEnabled: false,
debugDumpDir: null,
};
}
function makeLogger(): ProducerLogger {
return {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
} as unknown as ProducerLogger;
}
describe("captureSceneIntoBuffer", () => {
beforeEach(() => {
vi.mocked(applyDomLayerMask).mockClear();
vi.mocked(captureAlphaPng).mockClear();
vi.mocked(decodePng).mockClear();
vi.mocked(removeDomLayerMask).mockClear();
vi.mocked(blitRgba8OverRgb48le).mockClear();
});
it("does not re-show hidden transition-scene members in the DOM mask", async () => {
const page = { evaluate: vi.fn(async () => undefined) };
await captureSceneIntoBuffer({
session: { page, onBeforeCapture: null } as never,
sceneBuf: Buffer.alloc(6),
sceneIds: new Set(["visible-overlay", "hidden-inner", "hidden-sdr-video"]),
stackingInfo: [
makeEl("visible-overlay"),
makeEl("hidden-inner", { visible: false }),
makeEl("hidden-sdr-video", { visible: false, renderFrameVisible: true }),
makeEl("outside-scene"),
],
time: 0.5,
width: 1,
height: 1,
nativeHdrIds: new Set(),
nativeHdrImageIds: new Set(),
beforeCaptureHook: null,
hdrCompositeCtx: makeContext(),
compositeTransfer: "srgb",
hdrTargetTransfer: undefined,
hdrPerf: undefined,
log: makeLogger(),
frameIdx: 15,
});
expect(applyDomLayerMask).toHaveBeenCalledWith(
page,
["visible-overlay", "hidden-sdr-video"],
["outside-scene"],
);
});
});
@@ -29,6 +29,7 @@ import {
blitHdrImageLayer,
blitHdrVideoLayer,
closeHdrVideoFrameSource,
selectDomLayerShowIds,
} from "../../hdrCompositor.js";
import {
type HdrPerfCollector,
@@ -234,10 +235,11 @@ export async function captureSceneIntoBuffer(a: CaptureSceneArgs): Promise<void>
);
}
}
const showIds = Array.from(sceneIds);
const showIds = selectDomLayerShowIds(Array.from(sceneIds), stackingInfo);
const hideIds = stackingInfo
.map((e) => e.id)
.filter((id) => !sceneIds.has(id) || nativeHdrIds.has(id));
if (showIds.length === 0) return;
if (hdrPerf) hdrPerf.domLayerCaptures += 1;
await timeHdrPhaseAsync(hdrPerf, "domMaskApplyMs", () =>
applyDomLayerMask(session.page, showIds, hideIds),
File diff suppressed because one or more lines are too long
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:69c2f759a418a6e85094744011f5c267a2f311527de880b8d0ceb7cd46279c15
size 1793594
oid sha256:5808c1d2d8e794568deb36ff8c727066d3c6846bd764f4dc10b154c8c329e717
size 3689447
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/sdk",
"version": "0.7.29",
"version": "0.7.36",
"description": "Headless, framework-neutral HyperFrames composition editing engine",
"repository": {
"type": "git",
+120 -26
View File
@@ -218,12 +218,12 @@ interface FakeStyle {
}
interface FakeDomEl {
"data-hf-id": string;
"data-x": string | null;
"data-y": string | null;
_attrs: Record<string, string>;
style: FakeStyle;
isConnected: boolean;
getAttribute(name: string): string | null;
setAttribute(name: string, value: string): void;
hasAttribute(name: string): boolean;
querySelector(sel: string): FakeDomEl | null;
}
@@ -240,17 +240,21 @@ function fakeDomEl(id: string, dataX: string | null, dataY: string | null): Fake
delete this._props[name];
},
};
const attrs: Record<string, string> = { "data-hf-id": id };
if (dataX !== null) attrs["data-x"] = dataX;
if (dataY !== null) attrs["data-y"] = dataY;
const el: FakeDomEl = {
"data-hf-id": id,
"data-x": dataX,
"data-y": dataY,
_attrs: attrs,
style,
isConnected: true,
getAttribute(name) {
if (name === "data-x") return this["data-x"];
if (name === "data-y") return this["data-y"];
if (name === "data-hf-id") return this["data-hf-id"];
return null;
return this._attrs[name] ?? null;
},
setAttribute(name, value) {
this._attrs[name] = value;
},
hasAttribute(name) {
return name in this._attrs;
},
querySelector(_sel: string) {
return null;
@@ -316,6 +320,55 @@ describe("IframePreviewAdapter draft / commit / cancel", () => {
});
});
it("commitPreview mirrors the move onto the live element and applies the translate", () => {
const el = fakeDomEl("hf-abc", "100", "200");
const adapter = createIframePreviewAdapter(fakeIframe(el), vi.fn());
adapter.applyDraft("hf-abc", { dx: 30, dy: -20 });
adapter.commitPreview();
expect(el.getAttribute("data-x")).toBe("130");
expect(el.getAttribute("data-y")).toBe("180");
// Baseline captured from the pre-drag values.
expect(el.getAttribute("data-hf-edit-base-x")).toBe("100");
expect(el.getAttribute("data-hf-edit-base-y")).toBe("200");
// Final translate = delta from the baseline, held without a reload.
expect(el.getAttribute("data-hf-edit-original-translate")).toBe("");
expect(el.style.getPropertyValue("translate")).toBe("30px -20px");
// A second drag composes from the committed state and keeps the baseline.
adapter.applyDraft("hf-abc", { dx: 10, dy: 10 });
expect(el.style.getPropertyValue("translate")).toBe("40px -10px");
adapter.commitPreview();
expect(el.getAttribute("data-x")).toBe("140");
expect(el.getAttribute("data-hf-edit-base-x")).toBe("100");
expect(el.style.getPropertyValue("translate")).toBe("40px -10px");
});
it("applyDraft translates the element live and cancelPreview restores it", () => {
const el = fakeDomEl("hf-abc", "0", "0");
el.style.setProperty("translate", "5px 6px");
const adapter = createIframePreviewAdapter(fakeIframe(el), vi.fn());
adapter.applyDraft("hf-abc", { dx: 30, dy: -20 });
expect(el.style.getPropertyValue("translate")).toBe("35px -14px");
adapter.cancelPreview();
expect(el.style.getPropertyValue("translate")).toBe("5px 6px");
expect(el.getAttribute("data-hf-edit-base-x")).toBeNull();
});
it("cancelPreview removes a draft translate when there was none before", () => {
const el = fakeDomEl("hf-abc", "0", "0");
const adapter = createIframePreviewAdapter(fakeIframe(el), vi.fn());
adapter.applyDraft("hf-abc", { dx: 30 });
expect(el.style.getPropertyValue("translate")).toBe("30px 0px");
adapter.cancelPreview();
expect(el.style.getPropertyValue("translate")).toBe("");
});
it("applyDraft reuses the cached element across repeated calls (no re-query)", () => {
const el = fakeDomEl("hf-abc", "0", "0");
let queryCount = 0;
@@ -344,30 +397,17 @@ describe("IframePreviewAdapter draft / commit / cancel", () => {
adapter.commitPreview();
});
it("cancelPreview clears draft vars without dispatching", () => {
it("cancelPreview reverts the draft translate without dispatching", () => {
const dispatch = vi.fn();
const el = fakeDomEl("hf-abc", "100", "200");
const adapter = createIframePreviewAdapter(fakeIframe(el), dispatch);
adapter.applyDraft("hf-abc", { dx: 30, dy: 20 });
expect(el.style.getPropertyValue("translate")).toBe("30px 20px");
adapter.cancelPreview();
expect(dispatch).not.toHaveBeenCalled();
// CSS vars cleared
expect(el.style.getPropertyValue("--hf-studio-dx")).toBe("");
expect(el.style.getPropertyValue("--hf-studio-dy")).toBe("");
});
it("commitPreview clears draft vars after dispatching", () => {
const dispatch = vi.fn();
const el = fakeDomEl("hf-abc", "0", "0");
const adapter = createIframePreviewAdapter(fakeIframe(el), dispatch);
adapter.applyDraft("hf-abc", { dx: 10, dy: 5 });
adapter.commitPreview();
expect(el.style.getPropertyValue("--hf-studio-dx")).toBe("");
expect(el.style.getPropertyValue("--hf-studio-dy")).toBe("");
expect(el.style.getPropertyValue("translate")).toBe("");
});
it("second commitPreview after first is a no-op (draft cleared)", () => {
@@ -381,6 +421,60 @@ describe("IframePreviewAdapter draft / commit / cancel", () => {
expect(dispatch).toHaveBeenCalledTimes(1);
});
it("switching applyDraft to a new id reverts the abandoned element", () => {
const elA = fakeDomEl("hf-a", "0", "0");
const elB = fakeDomEl("hf-b", "0", "0");
const iframe = {
contentDocument: {
querySelector(sel: string) {
return sel.includes("hf-a") ? elA : elB;
},
},
} as unknown as HTMLIFrameElement;
const adapter = createIframePreviewAdapter(iframe, vi.fn());
adapter.applyDraft("hf-a", { dx: 80, dy: 0 });
expect(elA.style.getPropertyValue("translate")).toBe("80px 0px");
adapter.applyDraft("hf-b", { dx: 10, dy: 10 });
// The abandoned element is restored; the delta does not carry over.
expect(elA.style.getPropertyValue("translate")).toBe("");
expect(elB.style.getPropertyValue("translate")).toBe("10px 10px");
});
it("commitPreview reverts the draft translate when dispatch throws", () => {
const el = fakeDomEl("hf-abc", "0", "0");
el.style.setProperty("translate", "5px 6px");
const dispatch = vi.fn(() => {
throw new Error("element_not_found");
});
const adapter = createIframePreviewAdapter(fakeIframe(el), dispatch);
adapter.applyDraft("hf-abc", { dx: 30, dy: 20 });
expect(() => adapter.commitPreview()).toThrow("element_not_found");
expect(el.style.getPropertyValue("translate")).toBe("5px 6px");
expect(el.getAttribute("data-hf-edit-base-x")).toBeNull();
});
it("cancelPreview does not promote a computed (stylesheet) translate to inline", () => {
const el = fakeDomEl("hf-abc", "0", "0");
// Simulate a stylesheet-authored translate visible only via computed style.
(el as unknown as { ownerDocument: unknown }).ownerDocument = {
defaultView: {
getComputedStyle: () => ({ getPropertyValue: () => "-50% -50%" }),
},
};
const adapter = createIframePreviewAdapter(fakeIframe(el), vi.fn());
adapter.applyDraft("hf-abc", { dx: 30, dy: 20 });
// Draft composes onto the computed baseline (calc for non-px units).
expect(el.style.getPropertyValue("translate")).toBe("calc(-50% + 30px) calc(-50% + 20px)");
adapter.cancelPreview();
// Inline translate removed — the stylesheet value stays authoritative.
expect(el.style.getPropertyValue("translate")).toBe("");
});
});
// ─── WS-G: alphaIsOpaque ──────────────────────────────────────────────────────
+132 -28
View File
@@ -28,14 +28,17 @@
* here — gated on a perf spike.
*/
import {
EDIT_BASE_X_ATTR,
EDIT_BASE_Y_ATTR,
EDIT_ORIGINAL_TRANSLATE_ATTR,
applyPositionEditToElement,
composeTranslate,
readCurrentTranslate,
} from "@hyperframes/core/runtime/position-edits";
import type { PreviewAdapter, ElementAtPointResult, DraftProps } from "./types.js";
import type { EditOp } from "../types.js";
// ─── CSS var names written onto elements during drag ─────────────────────────
const VAR_DX = "--hf-studio-dx";
const VAR_DY = "--hf-studio-dy";
// ─── Pure resolver (testable without a browser) ───────────────────────────────
/**
@@ -492,6 +495,21 @@ class IframePreviewAdapter implements PreviewAdapter {
/** Tracked id and element for the in-progress drag. */
private _draftId: string | null = null;
private _draftEl: HTMLElement | null = null;
/** Accumulated drag deltas from applyDraft calls. */
private _draftDx = 0;
private _draftDy = 0;
/**
* The element's effective `translate` when the drag started (inline value,
* or computed when no inline one was set; "" = none). Drafts compose onto
* this.
*/
private _draftPrevTranslate: string | null = null;
/**
* The element's raw INLINE `translate` when the drag started ("" = not
* inline). Reverts restore exactly this, so a stylesheet-authored translate
* is never promoted to a permanent inline style.
*/
private _draftPrevInlineTranslate: string | null = null;
constructor(iframe: HTMLIFrameElement, dispatch?: (op: EditOp) => void) {
this.iframe = iframe;
@@ -543,73 +561,159 @@ class IframePreviewAdapter implements PreviewAdapter {
}
/**
* Write draft CSS custom properties (`--hf-studio-dx`, `--hf-studio-dy`) onto
* the target element inside the iframe at 60fps. The composition's CSS uses
* these vars to visually translate the element without touching the model.
* Visually translate the target element inside the iframe at 60fps without
* touching the model: sets the element's `translate` to its pre-drag value
* composed with the accumulated delta. `translate` set after GSAP's first
* parse is untouched by seeks, so this renders correctly on animated
* elements too. (The `--hf-studio-dx/dy` custom properties are no longer
* written — compositions with the authored Studio drag-bridge CSS would
* move by twice the delta if both channels applied.)
*
* Calling applyDraft with a new id replaces the tracked element (does not
* cancel the prior draft — call cancelPreview first if switching targets).
* Calling applyDraft with a new id switches the tracked element, reverting
* the previous element's draft translate first.
*
* width/height in DraftProps are not yet wired (resize → setStyle, future op).
*/
applyDraft(id: string, props: DraftProps): void {
const el = this._resolveDraftElement(id);
if (!el) return;
if (props.dx !== undefined) this._draftDx = props.dx;
if (props.dy !== undefined) this._draftDy = props.dy;
el.style.setProperty(
"translate",
composeTranslate(this._draftPrevTranslate ?? "", `${this._draftDx}px`, `${this._draftDy}px`),
);
}
/**
* Resolve and track the drag target. Reuses the tracked element across the
* 60fps drag; only re-queries when the id changes or the cached node
* detached (e.g. an iframe reload mid-drag). Switching to a different
* element reverts the previous one's draft first, then captures the new
* element's pre-drag translate.
*/
private _resolveDraftElement(id: string): HTMLElement | null {
const doc = this.iframe.contentDocument;
if (!doc) return;
if (!doc) return null;
// Reuse the tracked element across the 60fps drag; only re-query when the id
// changes or the cached node detached (e.g. an iframe reload mid-drag).
const cached = id === this._draftId && this._draftEl?.isConnected ? this._draftEl : null;
const el =
cached ??
doc.querySelector<HTMLElement>(
`[data-hf-id="${id.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"]`,
);
if (!el) return;
if (!el) return null;
if (el !== this._draftEl) {
// Abandoning a prior target mid-drag must not leave it displaced.
this._revertDraftTranslate();
this._draftDx = 0;
this._draftDy = 0;
this._draftPrevTranslate = readCurrentTranslate(el);
const inline = el.style.getPropertyValue("translate").trim();
this._draftPrevInlineTranslate = inline === "none" ? "" : inline;
}
this._draftId = id;
this._draftEl = el;
if (props.dx !== undefined) el.style.setProperty(VAR_DX, String(props.dx));
if (props.dy !== undefined) el.style.setProperty(VAR_DY, String(props.dy));
return el;
}
/**
* Read the accumulated draft deltas, derive a moveElement op, dispatch it,
* then clear the CSS vars and draft state.
* then clear the draft state.
*
* No-ops when:
* No-ops (reverting any draft translate) when:
* - No applyDraft was called (nothing to commit)
* - No dispatch callback was provided at construction
*
* If dispatch throws (e.g. the model no longer has the element), the draft
* translate is reverted and the error propagates — the element is never
* left displaced by an uncommitted draft.
*/
commitPreview(): void {
if (!this._draftId || !this._draftEl || !this._dispatch) {
this._revertDraftTranslate();
this._clearDraft();
return;
}
const el = this._draftEl;
const dx = parseFloat(el.style.getPropertyValue(VAR_DX) || "0") || 0;
const dy = parseFloat(el.style.getPropertyValue(VAR_DY) || "0") || 0;
const dataX = el.getAttribute("data-x");
const dataY = el.getAttribute("data-y");
const { x, y } = computeDraftPosition(dataX, dataY, dx, dy);
const { x, y } = computeDraftPosition(dataX, dataY, this._draftDx, this._draftDy);
this._dispatch({ type: "moveElement", target: this._draftId, x, y });
try {
this._dispatch({ type: "moveElement", target: this._draftId, x, y });
} catch (err) {
this._revertDraftTranslate();
this._clearDraft();
throw err;
}
this._mirrorCommittedMove(el, dataX, dataY, x, y);
this._clearDraft();
}
/** Revert draft CSS vars without dispatching any op. */
/**
* Mirror a committed move onto the live element so the position holds
* without a document reload — same attributes handleMoveElement writes
* into the model, rendered by the runtime's position-edit translate.
*
* The pre-edit translate is stamped from the value captured at drag start
* (the element's current inline translate is the draft-composed one, which
* must not be mistaken for the original), then the final translate is
* recomputed the same way the runtime does at bind time.
*/
private _mirrorCommittedMove(
el: HTMLElement,
dataX: string | null,
dataY: string | null,
x: number,
y: number,
): void {
if (el.getAttribute(EDIT_BASE_X_ATTR) === null) {
el.setAttribute(EDIT_BASE_X_ATTR, dataX ?? "0");
}
if (el.getAttribute(EDIT_BASE_Y_ATTR) === null) {
el.setAttribute(EDIT_BASE_Y_ATTR, dataY ?? "0");
}
if (el.getAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR) === null) {
el.setAttribute(EDIT_ORIGINAL_TRANSLATE_ATTR, this._draftPrevTranslate ?? "");
}
el.setAttribute("data-x", String(x));
el.setAttribute("data-y", String(y));
applyPositionEditToElement(el, { force: true });
}
/** Revert the draft translate without dispatching any op. */
cancelPreview(): void {
this._revertDraftTranslate();
this._clearDraft();
}
/**
* Restore the element's pre-drag INLINE `translate` (removing it when there
* was none, so a stylesheet-authored translate is never promoted to inline).
* NOT called on a successful commit — the committed position-edit translate
* is recomputed onto the element by _mirrorCommittedMove.
*/
private _revertDraftTranslate(): void {
if (!this._draftEl || this._draftPrevInlineTranslate === null) return;
if (this._draftPrevInlineTranslate === "") {
this._draftEl.style.removeProperty("translate");
} else {
this._draftEl.style.setProperty("translate", this._draftPrevInlineTranslate);
}
}
private _clearDraft(): void {
if (this._draftEl) {
this._draftEl.style.removeProperty(VAR_DX);
this._draftEl.style.removeProperty(VAR_DY);
}
this._draftId = null;
this._draftEl = null;
this._draftDx = 0;
this._draftDy = 0;
this._draftPrevTranslate = null;
this._draftPrevInlineTranslate = null;
}
// Selection -----------------------------------------------------------------
+27
View File
@@ -974,6 +974,33 @@ describe("moveElement", () => {
expect(el.getAttribute("data-x")).toBe("50");
expect(el.getAttribute("data-y")).toBe("75");
});
it("captures the pre-edit baseline on first move only", () => {
const parsed = fresh();
const el = parsed.document.querySelector('[data-hf-id="hf-title"]') as Element;
el.setAttribute("data-x", "50");
applyOp(parsed, { type: "moveElement", target: "hf-title", x: 100, y: 200 });
// Baseline = the values before the first edit (absent data-y → "0").
expect(el.getAttribute("data-hf-edit-base-x")).toBe("50");
expect(el.getAttribute("data-hf-edit-base-y")).toBe("0");
// A second move keeps the original baseline.
applyOp(parsed, { type: "moveElement", target: "hf-title", x: 300, y: 400 });
expect(el.getAttribute("data-hf-edit-base-x")).toBe("50");
expect(el.getAttribute("data-hf-edit-base-y")).toBe("0");
expect(el.getAttribute("data-x")).toBe("300");
expect(el.getAttribute("data-y")).toBe("400");
});
it("inverse of the first move removes the baseline attributes", () => {
const parsed = fresh();
const el = parsed.document.querySelector('[data-hf-id="hf-title"]') as Element;
const result = applyOp(parsed, { type: "moveElement", target: "hf-title", x: 100, y: 200 });
applyPatchesToDocument(parsed, result.inverse);
expect(el.getAttribute("data-hf-edit-base-x")).toBeNull();
expect(el.getAttribute("data-hf-edit-base-y")).toBeNull();
expect(el.getAttribute("data-x")).toBeNull();
expect(el.getAttribute("data-y")).toBeNull();
});
});
// ─── validateOp (can()) ───────────────────────────────────────────────────────
+28 -4
View File
@@ -51,6 +51,7 @@ import {
} from "./patches.js";
import { upsertCssRule } from "./cssWriter.js";
import { mintHfId, EXCLUDED_TAGS } from "@hyperframes/core/hf-ids";
import { EDIT_BASE_X_ATTR, EDIT_BASE_Y_ATTR } from "@hyperframes/core/runtime/position-edits";
import { parseGsapScriptAcornForWrite } from "@hyperframes/core/gsap-parser-acorn";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import {
@@ -342,11 +343,34 @@ function handleMoveElement(
): MutationResult {
// HF elements are positioned via data-x / data-y (parsed by htmlParser.ts,
// emitted by hyperframes generator). CSS left/top is not the convention.
const rx = handleSetAttribute(parsed, ids, "data-x", String(x));
const ry = handleSetAttribute(parsed, ids, "data-y", String(y));
//
// The pre-edit values are captured once per element into
// data-hf-edit-base-x/y. The runtime (core runtime/positionEdits.ts) renders
// the edit as translate(data-x − base, data-y − base), which composes with
// GSAP-animated transforms instead of being overwritten per-axis.
const parts: MutationResult[] = [];
for (const id of ids) {
const el = resolveScoped(parsed.document, id);
if (!el) continue;
if (el.getAttribute(EDIT_BASE_X_ATTR) === null) {
parts.push(
handleSetAttribute(parsed, [id], EDIT_BASE_X_ATTR, el.getAttribute("data-x") ?? "0"),
);
}
if (el.getAttribute(EDIT_BASE_Y_ATTR) === null) {
parts.push(
handleSetAttribute(parsed, [id], EDIT_BASE_Y_ATTR, el.getAttribute("data-y") ?? "0"),
);
}
}
parts.push(handleSetAttribute(parsed, ids, "data-x", String(x)));
parts.push(handleSetAttribute(parsed, ids, "data-y", String(y)));
return {
forward: [...rx.forward, ...ry.forward],
inverse: [...ry.inverse, ...rx.inverse],
forward: parts.flatMap((p) => p.forward),
inverse: parts
.slice()
.reverse()
.flatMap((p) => p.inverse),
};
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/shader-transitions",
"version": "0.7.29",
"version": "0.7.36",
"description": "WebGL shader transitions for HyperFrames compositions",
"repository": {
"type": "git",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/studio-server",
"version": "0.7.29",
"version": "0.7.36",
"repository": {
"type": "git",
"url": "https://github.com/heygen-com/hyperframes",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hyperframes/studio",
"version": "0.7.29",
"version": "0.7.36",
"description": "",
"repository": {
"type": "git",
@@ -1,10 +1,14 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
// @vitest-environment happy-dom
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import {
sdkResolverShadowCheck,
runResolverShadow,
recordResolverParity,
recordAnimationResolverParity,
evaluateSoakGate,
recordAttempt,
flushAttemptCounts,
__resetAttemptSchedulingForTests,
type SdkResolverMismatch,
} from "./sdkResolverShadow";
import type { PatchOperation } from "./sourcePatcher";
@@ -13,12 +17,15 @@ import { openComposition } from "@hyperframes/sdk";
// ─── Telemetry capture ────────────────────────────────────────────────────────
const trackedEvents: Array<{ event: string; props: Record<string, unknown> }> = [];
const flushViaBeacon = vi.fn();
vi.mock("./studioTelemetry", () => ({
trackStudioEvent: (event: string, props: Record<string, unknown>) =>
trackedEvents.push({ event, props }),
flushViaBeacon: () => flushViaBeacon(),
}));
beforeEach(() => {
trackedEvents.length = 0;
flushViaBeacon.mockClear();
});
const lastShadow = () =>
trackedEvents.filter((e) => e.event === "sdk_resolver_shadow").at(-1)?.props;
@@ -532,3 +539,175 @@ describe("H. inlined sub-composition leaf", () => {
expect(mismatches.some((m) => m.kind === "element_not_found")).toBe(false);
});
});
// ─── I. Attempt counter (denominator for the soak gate) ───────────────────────
describe("I. recordAttempt / flushAttemptCounts", () => {
beforeEach(() => {
// Drain any counts left over from a prior test so each test starts clean.
flushAttemptCounts();
});
it("flushAttemptCounts returns null when nothing has been recorded", () => {
expect(flushAttemptCounts()).toBeNull();
});
it("increments the counter for a given op label", () => {
recordAttempt("setTiming");
expect(flushAttemptCounts()).toEqual({ setTiming: 1 });
});
it("accumulates multiple calls with the same label", () => {
recordAttempt("setTiming");
recordAttempt("setTiming");
recordAttempt("setTiming");
expect(flushAttemptCounts()).toEqual({ setTiming: 3 });
});
it("tracks different labels independently", () => {
recordAttempt("setTiming");
recordAttempt("addGsapTween");
recordAttempt("setTiming");
expect(flushAttemptCounts()).toEqual({ setTiming: 2, addGsapTween: 1 });
});
it("resets to empty after a flush", () => {
recordAttempt("setTiming");
flushAttemptCounts();
expect(flushAttemptCounts()).toBeNull();
});
});
describe("I. attempt counting inside the three emit functions", () => {
beforeEach(() => {
flushAttemptCounts();
});
it("runResolverShadow counts an attempt on the parity (silent) path", async () => {
mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true;
const session = await openComposition(BASE_HTML);
runResolverShadow(session, "hf-box", [
{ type: "inline-style", property: "color", value: "blue" },
]);
expect(flushAttemptCounts()).toEqual({ "dom-edit": 1 });
expect(trackedEvents.filter((e) => e.event === "sdk_resolver_shadow")).toHaveLength(0);
});
it("runResolverShadow counts an attempt on the divergence (emits) path too", async () => {
mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true;
const session = await openComposition(BASE_HTML);
runResolverShadow(session, "hf-missing", [
{ type: "inline-style", property: "color", value: "blue" },
]);
expect(flushAttemptCounts()).toEqual({ "dom-edit": 1 });
expect(trackedEvents.filter((e) => e.event === "sdk_resolver_shadow")).toHaveLength(1);
});
it("recordResolverParity counts an attempt on the parity (silent) path", async () => {
mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true;
const session = await openComposition(BASE_HTML);
await recordResolverParity(session, "hf-box", "setTiming");
expect(flushAttemptCounts()).toEqual({ setTiming: 1 });
});
it("recordResolverParity counts an attempt on the divergence (emits) path too", async () => {
mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true;
const session = await openComposition(BASE_HTML);
await recordResolverParity(session, "hf-missing", "setTiming");
expect(flushAttemptCounts()).toEqual({ setTiming: 1 });
});
it("recordAnimationResolverParity counts an attempt on the parity (silent) path", async () => {
mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true;
const session = await openComposition(GSAP_HTML);
const realId = session.getElements().flatMap((e) => [...e.animationIds])[0] ?? "";
expect(realId).not.toBe(""); // fixture has a tween on hf-box, see block G above
recordAnimationResolverParity(session, realId, "removeGsapTween");
expect(flushAttemptCounts()).toEqual({ removeGsapTween: 1 });
expect(trackedEvents.filter((e) => e.event === "sdk_resolver_shadow")).toHaveLength(0);
});
it("recordAnimationResolverParity counts an attempt on the divergence (emits) path too", async () => {
mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true;
const session = await openComposition(GSAP_HTML);
recordAnimationResolverParity(session, "no-such-anim", "setGsapTween");
expect(flushAttemptCounts()).toEqual({ setGsapTween: 1 });
expect(trackedEvents.filter((e) => e.event === "sdk_resolver_shadow")).toHaveLength(1);
});
it("counts accumulate across multiple different chokepoints in one rollup", async () => {
mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true;
const session = await openComposition(BASE_HTML);
await recordResolverParity(session, "hf-box", "setTiming");
await recordResolverParity(session, "hf-box", "setTiming");
recordAnimationResolverParity(session, "no-such-anim", "setGsapTween");
expect(flushAttemptCounts()).toEqual({ setTiming: 2, setGsapTween: 1 });
});
it("does not count an attempt when the flag is off", async () => {
mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = false;
const session = await openComposition(BASE_HTML);
runResolverShadow(session, "hf-box", [
{ type: "inline-style", property: "color", value: "blue" },
]);
await recordResolverParity(session, "hf-box", "setTiming");
recordAnimationResolverParity(session, "no-such-anim", "setGsapTween");
expect(flushAttemptCounts()).toBeNull();
});
});
describe("I. production rollup wiring", () => {
beforeEach(() => {
flushAttemptCounts();
__resetAttemptSchedulingForTests();
vi.useFakeTimers({ toFake: ["setTimeout", "setInterval", "clearInterval", "clearTimeout"] });
});
afterEach(() => {
__resetAttemptSchedulingForTests();
vi.useRealTimers();
Object.defineProperty(document, "visibilityState", { value: "visible", configurable: true });
});
it("does not emit a rollup event when nothing was recorded", () => {
mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true;
vi.advanceTimersByTime(5 * 60_000);
expect(trackedEvents.filter((e) => e.event === "sdk_resolver_shadow_attempt")).toHaveLength(0);
});
it("emits a sdk_resolver_shadow_attempt rollup event every 5 minutes after the first attempt", async () => {
mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true;
const session = await openComposition(BASE_HTML);
await recordResolverParity(session, "hf-box", "setTiming");
vi.advanceTimersByTime(5 * 60_000);
const rollups = trackedEvents.filter((e) => e.event === "sdk_resolver_shadow_attempt");
expect(rollups).toHaveLength(1);
expect(rollups[0].props.counts).toBe(JSON.stringify({ setTiming: 1 }));
});
it("flushes a rollup and forces a beacon delivery on visibilitychange -> hidden", async () => {
mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true;
const session = await openComposition(BASE_HTML);
await recordResolverParity(session, "hf-box", "setTiming");
Object.defineProperty(document, "visibilityState", { value: "hidden", configurable: true });
document.dispatchEvent(new Event("visibilitychange"));
const rollups = trackedEvents.filter((e) => e.event === "sdk_resolver_shadow_attempt");
expect(rollups).toHaveLength(1);
expect(rollups[0].props.counts).toBe(JSON.stringify({ setTiming: 1 }));
// Delivery must not depend on studioTelemetry's own visibilitychange listener
// winning a race — this module forces its own beacon flush.
expect(flushViaBeacon).toHaveBeenCalledTimes(1);
});
it("does not register a duplicate visibilitychange listener after a scheduling reset", async () => {
mockFlags.STUDIO_SDK_RESOLVER_SHADOW_ENABLED = true;
const session = await openComposition(BASE_HTML);
await recordResolverParity(session, "hf-box", "setTiming");
__resetAttemptSchedulingForTests();
await recordResolverParity(session, "hf-box", "setTiming"); // re-arms scheduling, incl. listener
Object.defineProperty(document, "visibilityState", { value: "hidden", configurable: true });
document.dispatchEvent(new Event("visibilitychange"));
// If the reset had leaked the old listener, this would fire twice.
expect(flushViaBeacon).toHaveBeenCalledTimes(1);
});
});
+94 -1
View File
@@ -19,7 +19,7 @@ import type { Composition, JsonPatchOp } from "@hyperframes/sdk";
import type { PatchOperation } from "./sourcePatcher";
import { STUDIO_SDK_RESOLVER_SHADOW_ENABLED } from "../components/editor/manualEditingAvailability";
import { patchOpsToSdkEditOps } from "./sdkOpMapping";
import { trackStudioEvent } from "./studioTelemetry";
import { trackStudioEvent, flushViaBeacon } from "./studioTelemetry";
// ─── Types ────────────────────────────────────────────────────────────────────
@@ -229,6 +229,96 @@ export function sdkResolverShadowCheck(
}
}
// ─── Attempt counter (denominator for the soak gate) ──────────────────────────
//
// The three emit functions below only fire a PostHog event on divergence —
// parity is silent, by design, to avoid firing on every edit. That leaves no
// way to compute a rate (divergences / attempts): we can count failures but
// never attempts. This counter tracks attempts in memory and rolls them up
// into ONE low-frequency event instead of firing per-attempt, which would
// recreate the exact chattiness problem the divergence-only design avoids.
const attemptCounts: Record<string, number> = {};
/**
* Record that the resolver-shadow tripwire ran for `opLabel`, regardless of
* outcome (parity or divergence). No flag check of its own — only ever called
* from inside the three emit functions below, after their own
* STUDIO_SDK_RESOLVER_SHADOW_ENABLED guard, so it's already flag-gated.
*/
export function recordAttempt(opLabel: string): void {
attemptCounts[opLabel] = (attemptCounts[opLabel] ?? 0) + 1;
ensureAttemptFlushScheduled();
}
/**
* Return the accumulated attempt counts since the last flush (or `null` if
* nothing has been recorded — no point emitting an empty rollup), and reset
* the counter to empty.
*/
export function flushAttemptCounts(): Record<string, number> | null {
const keys = Object.keys(attemptCounts);
if (keys.length === 0) return null;
const snapshot: Record<string, number> = {};
for (const key of keys) {
snapshot[key] = attemptCounts[key];
delete attemptCounts[key];
}
return snapshot;
}
const ATTEMPT_FLUSH_INTERVAL_MS = 5 * 60_000;
let attemptFlushTimer: ReturnType<typeof setInterval> | null = null;
let attemptVisibilityHandler: (() => void) | null = null;
function flushAndEmitAttempts(): void {
const counts = flushAttemptCounts();
if (counts === null) return;
trackStudioEvent("sdk_resolver_shadow_attempt", { counts: JSON.stringify(counts) });
}
// Lazily starts the rollup timer + visibilitychange listener on the FIRST
// attempt in a session — mirrors studioTelemetry.ts's own lazy flushTimer
// start, so a session that never exercises the tripwire never runs a
// background timer.
function ensureAttemptFlushScheduled(): void {
if (!attemptFlushTimer) {
attemptFlushTimer = setInterval(flushAndEmitAttempts, ATTEMPT_FLUSH_INTERVAL_MS);
}
if (!attemptVisibilityHandler && typeof document !== "undefined") {
attemptVisibilityHandler = () => {
if (document.visibilityState !== "hidden") return;
flushAndEmitAttempts();
// studioTelemetry.ts registers its own visibilitychange listener (on
// window, at module load) that drains its queue via sendBeacon. Listener
// execution order between that handler and this one (on document,
// registered lazily) is not something to rely on — whichever runs
// first could otherwise beacon-flush before or after this rollup lands
// in the queue. Forcing a beacon flush here makes delivery of this
// rollup event correct regardless of that order.
flushViaBeacon();
};
document.addEventListener("visibilitychange", attemptVisibilityHandler);
}
}
/**
* Test-only: clears the lazy timer/listener singleton state so tests can
* verify the "starts on first attempt" behavior in isolation, without an
* earlier test's real-timer interval (or visibilitychange listener) silently
* surviving into a later test. Does NOT touch attemptCounts — only the
* scheduling state. Not part of the public module contract; only imported
* from sdkResolverShadow.test.ts.
*/
export function __resetAttemptSchedulingForTests(): void {
if (attemptFlushTimer) clearInterval(attemptFlushTimer);
attemptFlushTimer = null;
if (attemptVisibilityHandler && typeof document !== "undefined") {
document.removeEventListener("visibilitychange", attemptVisibilityHandler);
}
attemptVisibilityHandler = null;
}
// ─── Telemetry ────────────────────────────────────────────────────────────────
// Redact all user-content values before telemetry: style values and text both
@@ -266,6 +356,7 @@ export function runResolverShadow(
if (!STUDIO_SDK_RESOLVER_SHADOW_ENABLED) return;
if (!hfId) return;
try {
recordAttempt("dom-edit");
const mismatches = sdkResolverShadowCheck(session, hfId, ops, sourceContent);
// Emit only on divergence — parity is silent, matching recordResolverParity
// and recordAnimationResolverParity. Otherwise this fires a PostHog event on
@@ -318,6 +409,7 @@ export async function recordResolverParity(
if (!STUDIO_SDK_RESOLVER_SHADOW_ENABLED) return;
if (!session || !hfId) return;
try {
recordAttempt(opLabel);
if (resolveSnapshot(session, hfId)) return; // resolves — parity, nothing to record
// Capture BEFORE any await: this call is fire-and-forget (`void recordResolverParity(...)`)
// and the caller runs its own session mutation synchronously right after this call
@@ -380,6 +472,7 @@ export function recordAnimationResolverParity(
if (!STUDIO_SDK_RESOLVER_SHADOW_ENABLED) return;
if (!session || !animationId) return;
try {
recordAttempt(opLabel);
const elements = session.getElements();
const resolves = elements.some((el) => el.animationIds.includes(animationId));
if (resolves) return; // SDK locates the animation — parity
+27 -20
View File
@@ -90,27 +90,34 @@ async function flushEvents(): Promise<void> {
}
}
// Synchronously drains the queue via sendBeacon — safe to call from any
// tab-hide handler regardless of listener registration order. Exported so
// other modules (e.g. sdkResolverShadow.ts) can force delivery of an event
// they just queued without racing this module's own visibilitychange
// listener below.
export function flushViaBeacon(): void {
if (flushTimer) {
clearInterval(flushTimer);
flushTimer = null;
}
if (queue.length === 0) return;
const batch = queue.map((e) => ({
event: e.event,
properties: { ...e.properties, $ip: null },
distinct_id: getDistinctId(),
timestamp: e.timestamp,
}));
queue = [];
const body = JSON.stringify({ api_key: POSTHOG_API_KEY, batch });
try {
navigator.sendBeacon(`${POSTHOG_HOST}/batch/`, body);
} catch {
// best-effort
}
}
if (typeof window !== "undefined") {
window.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") {
if (flushTimer) {
clearInterval(flushTimer);
flushTimer = null;
}
if (queue.length === 0) return;
const batch = queue.map((e) => ({
event: e.event,
properties: { ...e.properties, $ip: null },
distinct_id: getDistinctId(),
timestamp: e.timestamp,
}));
queue = [];
const body = JSON.stringify({ api_key: POSTHOG_API_KEY, batch });
try {
navigator.sendBeacon(`${POSTHOG_HOST}/batch/`, body);
} catch {
// best-effort
}
}
if (document.visibilityState === "hidden") flushViaBeacon();
});
}