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/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",
},
},