Files
hyperframes/packages/cli/src/cloud/offload.ts
T
Miguel Ángel d106f9c8c7 fix: stop crashing on SVG elements named template (#8241)
* test: pages holding an SVG element named template

* fix: read template content only from HTML templates

* test: SVG elements named template in previews, inline mounts and lint

* fix: treat only HTML templates as scenes and inline mounts

* test: scene ids next to SVG elements named template

* fix: take scene ids only from HTML templates
2026-11-19 12:27:21 +00:00

1215 lines
43 KiB
TypeScript

/**
* Moves a cloud render's heavy media out of the project zip into HeyGen assets and points the
* staged copy's references at the asset URLs. The project on disk is never touched.
*/
import { execFile, spawn } from "node:child_process";
import { createHash } from "node:crypto";
import {
closeSync,
copyFileSync,
createReadStream,
mkdirSync,
mkdtempSync,
openSync,
readFileSync,
readSync,
renameSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, extname, join, posix, relative, resolve } from "node:path";
import { promisify } from "node:util";
import { parseHTML } from "linkedom";
import { parseAnimatedGifMetadata } from "@hyperframes/core";
import { rewriteAssetPath } from "@hyperframes/parsers/asset-paths";
import { templateContent } from "@hyperframes/parsers/sub-composition-validity";
import {
cleanAssetUrl,
isRemoteOrInlineUrl,
resolveLocalAssetCandidates,
} from "@hyperframes/parsers/asset-resolution";
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
import { probeAudio } from "../audio/analysis/decode.js";
import { formatBytes } from "../ui/format.js";
import { bytesMatchExtension } from "./offloadSniff.js";
import {
AUDIO_EXTS,
CONVERTIBLE_IMAGE_EXTS,
mediaInputArgs,
startsAsMediaPlaylist,
VIDEO_EXTS,
} from "@hyperframes/studio-server/outside-file";
import { followFfmpegProgress } from "@hyperframes/parsers/ff-binaries";
import { type PlayedSegment, planTrim } from "./offloadTrim.js";
import {
archiveKey,
assertUnchanged,
type HtmlAttributeResolver,
readChecked,
rewriteCssUrls,
rewriteHtmlAttributes,
rewriteStyleBlocks,
type StagedFile,
stagedSize,
TEXT_FILE_EXTS,
} from "../utils/publishProject.js";
import { hyperframesCacheDir } from "@hyperframes/core/cache-dir";
import { runWithConcurrencyLimit } from "../utils/concurrency.js";
const execFileAsync = promisify(execFile);
/** Staged media this big stays on disk until it uploads; an entry GIF this big becomes a video first. */
export const OFFLOAD_MIN_BYTES = 5 * 1024 * 1024;
const OFFLOAD_CONCURRENCY = 8;
const MiB = 1024 * 1024;
const AUDIO_MAX_BYTES = 1_500_000_000;
export const CACHE_CHECK_TIMEOUT_MS = 10_000;
// What POST /v3/assets/direct-uploads takes as-is, and its per-type cap.
const ACCEPTED: Record<string, { contentType: string; maxBytes: number }> = {
".mp4": { contentType: "video/mp4", maxBytes: 200 * MiB },
".m4v": { contentType: "video/mp4", maxBytes: 200 * MiB },
".mov": { contentType: "video/quicktime", maxBytes: 200 * MiB },
".webm": { contentType: "video/webm", maxBytes: 200 * MiB },
".png": { contentType: "image/png", maxBytes: 200 * MiB },
".jpg": { contentType: "image/jpeg", maxBytes: 200 * MiB },
".jpeg": { contentType: "image/jpeg", maxBytes: 200 * MiB },
".webp": { contentType: "image/webp", maxBytes: 200 * MiB },
".wav": { contentType: "audio/wav", maxBytes: AUDIO_MAX_BYTES },
".mp3": { contentType: "audio/mpeg", maxBytes: AUDIO_MAX_BYTES },
};
/** Visually lossless re-encodes for media the asset API refuses or caps. Quality lives here. */
const REENCODE_PRESETS = {
video: {
ext: ".mp4",
contentType: "video/mp4",
args: ["-c:v", "libx264", "-preset", "slow", "-crf", "18", "-pix_fmt", "yuv420p"],
audio: ["-c:a", "aac", "-b:a", "320k", "-movflags", "+faststart"],
},
hdrVideo: {
ext: ".mp4",
contentType: "video/mp4",
args: ["-c:v", "libx265", "-preset", "slow", "-crf", "18", "-pix_fmt", "yuv420p10le"],
audio: ["-tag:v", "hvc1", "-c:a", "aac", "-b:a", "320k", "-movflags", "+faststart"],
},
alphaVideo: {
ext: ".webm",
contentType: "video/webm",
args: ["-c:v", "libvpx-vp9", "-crf", "18", "-b:v", "0", "-pix_fmt", "yuva420p"],
audio: ["-c:a", "libopus", "-b:a", "256k"],
},
audio: {
ext: ".wav",
contentType: "audio/wav",
args: ["-vn"],
audio: ["-c:a", "pcm_s16le"],
},
image: {
ext: ".png",
contentType: "image/png",
args: ["-frames:v", "1"],
audio: [],
},
} as const;
export type PresetName = keyof typeof REENCODE_PRESETS;
export interface OffloadedMedia {
path: string;
size_bytes: number;
/** What happened (or, on a dry run, would happen) to the file. */
action: "upload" | "reencode" | "cached";
url?: string;
asset_id?: string;
/** Seconds of the source kept when only the parts the composition plays are uploaded. */
trimmed_to_seconds?: number;
/** Still referenced from a script or data file, so a copy also stays in the zip. */
kept_in_archive?: boolean;
}
/** In memory, or a file on disk that the upload streams. */
export type UploadableFile = { filename: string; contentType: string } & (
| { bytes: Uint8Array }
| { path: string; size: number }
);
export interface OffloadOptions {
/** Cache key namespace, so assets from one API host are never reused on another. */
apiBaseUrl: string;
/** Absent on a dry run: nothing is encoded, uploaded or fetched. */
upload?: (file: UploadableFile) => Promise<{ asset_id: string; url: string }>;
fetchImpl?: typeof fetch;
cachePath?: string;
/** The composition the render starts from; its animated GIFs are prepared as video. */
entryPath?: string;
/** Overrides ffprobe/ffmpeg for tests. */
reencoder?: Reencoder;
/** Overrides the renderer's GIF preparation for tests. */
gifPrep?: GifPrep;
onFile?: (item: OffloadedMedia) => void;
/** Hears a re-encode's output seconds made so far; `totalSeconds` is null when the length is unknown. */
onReencodeProgress?: (event: ReencodeProgress) => void;
variablesText?: string;
/** Media leaves the zip, largest first, only while the zip is over this; absent, all used media leaves. */
zipBudgetBytes?: number;
}
export interface ReencodeProgress {
path: string;
doneSeconds: number;
totalSeconds: number | null;
}
type MediaKind = "video" | "audio" | "image";
export interface Reencoder {
/** `null` keeps the file in the zip as authored. */
choose: (sourcePath: string, kind: MediaKind) => Promise<PresetName | null>;
/** Positions per second a cut may land on (the frame rate), or null when the file cannot be cut. */
trimGrid?: (sourcePath: string, kind: MediaKind) => Promise<number | null>;
/** Whether a container named as video holds a video stream; `true` when that cannot be told. */
hasVideo?: (sourcePath: string) => Promise<boolean>;
run: (
sourcePath: string,
preset: PresetName,
segments?: PlayedSegment[],
onProgress?: (doneSeconds: number, totalSeconds: number | null) => void,
) => Promise<UploadableFile>;
}
export type GifPrep = (
html: string,
options: {
projectDir: string;
downloadDir: string;
outputDir: string;
outputSrcPrefix: string;
cacheDir: string;
sourceAssets: Map<string, string>;
assetRoot: string;
},
) => Promise<{ html: string; preparedGifs: Array<{ sourceSrc: string; outputPath: string }> }>;
interface CacheEntry {
asset_id: string;
url: string;
size_bytes: number;
}
function defaultOffloadCachePath(): string {
return hyperframesCacheDir("cloud-assets.json");
}
function readCache(path: string): Record<string, CacheEntry> {
try {
return (JSON.parse(readFileSync(path, "utf-8")) as Record<string, CacheEntry> | null) ?? {};
} catch {
return {};
}
}
function writeCache(path: string, cache: Record<string, CacheEntry>): void {
mkdirSync(dirname(path), { recursive: true });
const tmp = `${path}.${process.pid}.tmp`;
writeFileSync(tmp, JSON.stringify(cache, null, 2));
renameSync(tmp, path);
}
// Asset URLs are public and unsigned, so HEAD needs no auth; a deleted or replaced asset fails it.
async function stillServed(entry: CacheEntry, fetchImpl: typeof fetch): Promise<boolean> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), CACHE_CHECK_TIMEOUT_MS);
try {
const res = await fetchImpl(entry.url, { method: "HEAD", signal: controller.signal });
return res.ok && Number(res.headers.get("content-length")) === entry.size_bytes;
} catch {
return false;
} finally {
clearTimeout(timer);
}
}
function mediaKind(path: string): MediaKind | null {
const ext = extname(path).toLowerCase();
if (VIDEO_EXTS.has(ext)) return "video";
if (AUDIO_EXTS.has(ext)) return "audio";
if (ACCEPTED[ext] || CONVERTIBLE_IMAGE_EXTS.has(ext)) return "image";
return null;
}
interface VideoProbe {
alpha: boolean;
hdr: boolean;
codec?: string;
color: { primaries?: string; transfer?: string; space?: string };
}
async function probeVideo(path: string): Promise<VideoProbe> {
const ffprobe = findFFprobe();
if (!ffprobe)
throw new Error(`Re-encoding needs ffprobe. Install ffmpeg: ${getFFmpegInstallHint()}`);
const { stdout } = await execFileAsync(ffprobe, [
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=codec_name,pix_fmt,color_primaries,color_transfer,color_space:stream_tags",
"-of",
"json",
...mediaInputArgs(path),
"--",
path,
]);
const stream = (JSON.parse(stdout).streams?.[0] ?? {}) as Record<string, unknown>;
const tags = (stream.tags ?? {}) as Record<string, string>;
const alphaTag = Object.entries(tags).some(
([k, v]) => k.toLowerCase() === "alpha_mode" && v === "1",
);
const transfer = stream.color_transfer as string | undefined;
return {
// VP9 alpha keeps pix_fmt yuv420p and flags the plane only in the ALPHA_MODE tag.
alpha: alphaTag || /^(yuva|rgba|argb|bgra|abgr|gbrap|ya)/.test(String(stream.pix_fmt ?? "")),
hdr: transfer === "smpte2084" || transfer === "arib-std-b67",
codec: stream.codec_name as string | undefined,
color: {
primaries: stream.color_primaries as string | undefined,
transfer,
space: stream.color_space as string | undefined,
},
};
}
// ffmpeg's native VP8/VP9 decoders drop the alpha plane; libvpx keeps it.
function alphaDecoderArgs(probe: VideoProbe): string[] {
if (!probe.alpha) return [];
if (probe.codec === "vp9") return ["-c:v", "libvpx-vp9"];
if (probe.codec === "vp8") return ["-c:v", "libvpx"];
return [];
}
function hdrColorArgs({ color }: VideoProbe): string[] {
return [
...(color.primaries ? ["-color_primaries", color.primaries] : []),
...(color.transfer ? ["-color_trc", color.transfer] : []),
...(color.space ? ["-colorspace", color.space] : []),
];
}
// Seconds floored to the microsecond, so a frame-aligned cut never rounds past its first frame.
const seconds = (t: number) => (Math.floor(t * 1e6) / 1e6).toFixed(6);
/** Inputs and mapping for a cut: one accurately seeked input per segment, joined in order. */
async function segmentArgs(
sourcePath: string,
decoder: string[],
segments: PlayedSegment[] | undefined,
media: "audio" | "image" | "video",
): Promise<string[]> {
if (media === "image") return [...decoder, ...mediaInputArgs(sourcePath), "-i", sourcePath];
const audio = await keptAudio(sourcePath, media);
const cuts = segments?.length ? segments : [undefined];
const inputs = cuts.flatMap((s) => [
...decoder,
...seekArgs(s),
...mediaInputArgs(sourcePath),
"-i",
sourcePath,
]);
const video = media === "video";
return [
...inputs,
...(cuts.length > 1 ? concatArgs(cuts.length, video, audio) : streamMaps(video, audio)),
];
}
async function keptAudio(sourcePath: string, media: "audio" | "video"): Promise<number | null> {
const audio = (await probeAudio(sourcePath, mediaInputArgs(sourcePath)))?.audioStream ?? null;
if (media === "audio" && audio === null) {
throw new Error("the file has no audio track ffmpeg can decode");
}
return audio;
}
const seekArgs = (s: PlayedSegment | undefined) =>
s ? ["-ss", seconds(s.start), "-t", seconds(s.end - s.start)] : [];
const streamMaps = (video: boolean, audio: number | null) => [
...(video ? ["-map", "0:V:0"] : []),
...(audio === null ? [] : ["-map", `0:a:${audio}`]),
];
const mediaOf = (preset: PresetName) =>
preset === "audio" || preset === "image" ? preset : ("video" as const);
function concatArgs(count: number, video: boolean, audio: number | null): string[] {
const pad = (i: number) =>
(video ? `[${i}:v]` : "") + (audio === null ? "" : `[${i}:a:${audio}]`);
const pads = Array.from({ length: count }, (_, i) => pad(i)).join("");
const flags = `n=${count}:v=${video ? 1 : 0}:a=${audio === null ? 0 : 1}`;
return [
"-filter_complex",
`${pads}concat=${flags}${video ? "[v]" : ""}${audio === null ? "" : "[a]"}`,
...(video ? ["-map", "[v]"] : []),
...(audio === null ? [] : ["-map", "[a]"]),
];
}
const LIMITED_SHARE = 0.85;
/** Rate limits that keep a re-encode under `maxBytes` while crf stays the quality target; empty when none apply. */
export function sizeLimitArgs(opts: {
maxBytes: number;
seconds: number;
audioBitsPerSecond: number;
}): string[] {
if (!(opts.seconds > 0)) return [];
const bits = (opts.maxBytes * 8 * LIMITED_SHARE) / opts.seconds - opts.audioBitsPerSecond;
if (!(bits >= 1000)) return [];
const rate = `${Math.floor(bits / 1000)}k`;
return ["-maxrate", rate, "-bufsize", rate];
}
const bitsPerSecond = (args: readonly string[]) => {
const rate = args[args.indexOf("-b:a") + 1];
return rate ? Number.parseInt(rate, 10) * 1000 : 0;
};
async function durationSeconds(sourcePath: string): Promise<number | null> {
const ffprobe = findFFprobe();
if (!ffprobe) return null;
const { stdout } = await execFileAsync(ffprobe, [
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"csv=p=0",
...mediaInputArgs(sourcePath),
"--",
sourcePath,
]);
const value = Number(stdout.trim());
return Number.isFinite(value) && value > 0 ? value : null;
}
const capOf = (presetName: PresetName) => ACCEPTED[REENCODE_PRESETS[presetName].ext]?.maxBytes ?? 0;
const playedSeconds = (segments: PlayedSegment[]) =>
segments.reduce((sum, s) => sum + s.end - s.start, 0);
const outputSeconds = (sourcePath: string, segments: PlayedSegment[] | undefined) =>
segments?.length ? Promise.resolve(playedSeconds(segments)) : durationSeconds(sourcePath);
export async function limitFor(
sourcePath: string,
presetName: PresetName,
segments: PlayedSegment[] | undefined,
maxBytes = capOf(presetName),
): Promise<string[]> {
if (mediaOf(presetName) !== "video") return [];
const seconds = await outputSeconds(sourcePath, segments);
const limit = sizeLimitArgs({
maxBytes,
seconds: seconds ?? 0,
audioBitsPerSecond: bitsPerSecond(REENCODE_PRESETS[presetName].audio),
});
// VP9 takes its ceiling from -b:v; the preset's `-b:v 0` is pure constant quality and ignores -maxrate.
return presetName === "alphaVideo" && limit.length ? [...limit, "-b:v", limit[1]!] : limit;
}
/** ffmpeg with `-progress` on stdout, so `onSeconds` hears the output time made; fails with ffmpeg's own stderr. */
function runFfmpeg(
ffmpeg: string,
args: string[],
onSeconds: (seconds: number) => void,
): Promise<void> {
return new Promise((resolve, reject) => {
const proc = spawn(ffmpeg, ["-progress", "pipe:1", "-nostats", ...args], {
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
});
followFfmpegProgress(proc.stdout, onSeconds);
let stderr = "";
proc.stderr.on("data", (chunk: Buffer) => {
stderr = (stderr + chunk.toString()).slice(-16_384);
});
proc.on("error", reject);
proc.on("close", (code, signal) => {
if (code === 0) return resolve();
const ended = signal ? `was ended by ${signal}` : `exited with code ${code}`;
reject(new Error(`ffmpeg ${ended}: ${stderr.trim()}`));
});
});
}
async function ffmpegReencode(
sourcePath: string,
presetName: PresetName,
segments?: PlayedSegment[],
onProgress?: (doneSeconds: number, totalSeconds: number | null) => void,
): Promise<UploadableFile> {
const ffmpeg = findFFmpeg();
if (!ffmpeg) throw new Error(`Re-encoding needs ffmpeg. Install it: ${getFFmpegInstallHint()}`);
const preset = REENCODE_PRESETS[presetName];
const probe = preset.contentType.startsWith("video/") ? await probeVideo(sourcePath) : undefined;
const decoder = probe ? alphaDecoderArgs(probe) : [];
const color = presetName === "hdrVideo" && probe ? hdrColorArgs(probe) : [];
const totalSeconds = onProgress ? await outputSeconds(sourcePath, segments) : null;
const workDir = mkdtempSync(join(tmpdir(), "hf-offload-"));
const outPath = join(workDir, `${basename(sourcePath, extname(sourcePath))}${preset.ext}`);
try {
await runFfmpeg(
ffmpeg,
[
"-v",
"error",
"-y",
...(await segmentArgs(sourcePath, decoder, segments, mediaOf(presetName))),
...preset.args,
...(await limitFor(sourcePath, presetName, segments)),
...color,
...preset.audio,
outPath,
],
(doneSeconds) => onProgress?.(doneSeconds, totalSeconds),
);
// Never read an output the asset API would refuse: it can exceed what one read can hold.
return {
bytes: readChecked(outPath, ({ size }) => assertFitsAsset(sourcePath, outPath, size)),
filename: basename(outPath),
contentType: preset.contentType,
};
} finally {
rmSync(workDir, { recursive: true, force: true });
}
}
async function choosePreset(sourcePath: string, kind: MediaKind): Promise<PresetName | null> {
if (kind === "audio") return "audio";
// An animated image's first frame is not the image; such files stay in the zip.
if (kind === "image") return (await isAnimatedImage(sourcePath)) ? null : "image";
const probe = await probeVideo(sourcePath);
return probe.alpha ? "alphaVideo" : probe.hdr ? "hdrVideo" : "video";
}
async function isAnimatedImage(path: string): Promise<boolean> {
if (extname(path).toLowerCase() === ".gif") {
return parseAnimatedGifMetadata(readFileSync(path))?.animated ?? true;
}
const ffprobe = findFFprobe();
if (!ffprobe) return true;
try {
const { stdout } = await execFileAsync(ffprobe, [
"-v",
"error",
"-show_entries",
"stream=nb_frames",
"-of",
"csv=p=0",
...mediaInputArgs(path),
"--",
path,
]);
return stdout.split("\n").some((line) => Number(line) > 1);
} catch {
return true;
}
}
// Audio cuts land on the millisecond; video only on a constant frame rate's frames.
async function trimGrid(sourcePath: string, kind: MediaKind): Promise<number | null> {
if (kind === "audio") return 1000;
if (kind !== "video") return null;
const ffprobe = findFFprobe();
if (!ffprobe) return null;
const { stdout } = await execFileAsync(ffprobe, [
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=r_frame_rate,avg_frame_rate",
"-of",
"csv=p=0",
...mediaInputArgs(sourcePath),
"--",
sourcePath,
]);
const rate = (fraction: string | undefined) => {
const [num, den] = (fraction ?? "").split("/").map(Number);
return num && den ? num / den : NaN;
};
const [real, average] = stdout.trim().split(",");
const fps = rate(real);
return Number.isFinite(fps) && Math.abs(fps - rate(average)) < 0.01 ? fps : null;
}
async function hasVideoStream(sourcePath: string): Promise<boolean> {
const ffprobe = findFFprobe();
if (!ffprobe) return true;
try {
const { stdout } = await execFileAsync(ffprobe, [
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=codec_type",
"-of",
"csv=p=0",
...mediaInputArgs(sourcePath),
"--",
sourcePath,
]);
return stdout.trim() !== "";
} catch {
return true;
}
}
const ffmpegReencoder: Reencoder = {
choose: choosePreset,
trimGrid,
hasVideo: hasVideoStream,
run: ffmpegReencode,
};
async function stagedSha256(file: StagedFile): Promise<string> {
if (Buffer.isBuffer(file)) return createHash("sha256").update(file).digest("hex");
const hash = createHash("sha256");
for await (const chunk of createReadStream(file.absPath)) hash.update(chunk as Buffer);
assertUnchanged(file);
return hash.digest("hex");
}
/**
* A path holding the staged bytes, so an encode reads what its cache key hashed: a file left on disk
* is used in place (checked unchanged after use), one staged in memory gets a temp copy.
*/
function snapshotPath(path: string, file: StagedFile, tempFiles: string[]): string {
return Buffer.isBuffer(file) ? stagedCopy(path, file, tempFiles) : file.absPath;
}
/** A private copy of the staged bytes, for readers that cache what they read before any check runs. */
function stagedCopy(path: string, file: StagedFile, tempFiles: string[]): string {
const dir = mkdtempSync(join(tmpdir(), "hf-offload-src-"));
tempFiles.push(dir);
const copy = join(dir, basename(path));
if (Buffer.isBuffer(file)) writeFileSync(copy, file);
else {
copyFileSync(file.absPath, copy);
assertUnchanged(file);
}
return copy;
}
/** A text file's contents; media is never decoded, since it can exceed the longest string V8 allows. */
function textOf(path: string, file: StagedFile | undefined): string | undefined {
return TEXT_FILE_EXTS.test(path) && Buffer.isBuffer(file) ? file.toString("utf-8") : undefined;
}
/** What the page's scripts can read: inline scripts of HTML files, and script and data files. */
function scriptCode(fileMap: Map<string, StagedFile>): string {
const parts: string[] = [];
for (const [path, content] of fileMap) {
const text = textOf(path, content);
if (text === undefined) continue;
if (/\.html?$/i.test(path)) {
const { document } = parseHTML(text);
const pages = [
document,
...[...document.querySelectorAll("template")].flatMap((t) => templateContent(t) ?? []),
];
for (const script of pages.flatMap((p) => [...p.querySelectorAll("script:not([src])")])) {
parts.push(script.textContent ?? "");
}
} else if (/\.(m?js|cjs|json)$/i.test(path)) parts.push(text);
}
return parts.join("\n");
}
function assertFitsAsset(path: string, filename: string, size: number): void {
const maxBytes = ACCEPTED[extname(filename).toLowerCase()]?.maxBytes ?? 0;
if (size > maxBytes) {
throw new Error(
`${path} is ${formatBytes(size)} after re-encoding at visually lossless quality, over the ${formatBytes(maxBytes)} a HeyGen asset can hold.`,
);
}
}
interface OffloadContext {
absDir: string;
opts: OffloadOptions;
cachePath: string;
cache: Record<string, CacheEntry>;
cachedSizes: Set<number>;
fetchImpl: typeof fetch;
reencoder: Reencoder;
tempFiles: string[];
/** Staged GIFs the entry composition no longer shows as images. */
preparedGifSources: string[];
fileMap: Map<string, StagedFile>;
uploadsInFlightByKey: Map<string, Promise<{ url: string; asset_id: string }>>;
}
interface FilePlan {
key?: string;
preset?: PresetName;
sourcePath: string;
contentType?: string;
segments?: PlayedSegment[];
}
function readHead(file: StagedFile): Buffer {
if (Buffer.isBuffer(file)) return file.subarray(0, 16);
const fd = openSync(file.absPath, "r");
try {
const head = Buffer.alloc(16);
readSync(fd, head, 0, 16, 0);
return head;
} finally {
closeSync(fd);
}
}
function mediaFileKind(path: string, file: StagedFile): MediaKind | null {
const kind = mediaKind(path);
return kind && !startsAsMediaPlaylist(readHead(file)) ? kind : null;
}
async function planFile(
ctx: OffloadContext,
path: string,
file: StagedFile,
): Promise<FilePlan | null> {
const size = stagedSize(file);
let kind = mediaFileKind(path, file);
if (!kind) return null;
const ext = extname(path).toLowerCase();
const accepted = ACCEPTED[ext];
// The API reads the stored bytes, not the name: a file whose bytes differ from its extension is re-encoded.
let asIs =
accepted !== undefined && size <= accepted.maxBytes && bytesMatchExtension(ext, readHead(file));
let sourcePath: string | undefined;
if (kind === "video" && ctx.reencoder.hasVideo) {
sourcePath = snapshotPath(path, file, ctx.tempFiles);
// An audio-only MP4 is audio whatever its name says.
if (!(await ctx.reencoder.hasVideo(sourcePath))) {
kind = "audio";
asIs = false;
}
}
const mayBeCached =
ctx.opts.upload !== undefined || (asIs ? ctx.cachedSizes.has(size) : ctx.cachedSizes.size > 0);
const sha256 = mayBeCached ? await stagedSha256(file) : undefined;
const keyFor = (variant: string) => sha256 && `${ctx.opts.apiBaseUrl} ${sha256} ${variant}`;
if (asIs) {
return { key: keyFor("as-is"), sourcePath: "", contentType: accepted?.contentType };
}
sourcePath ??= snapshotPath(path, file, ctx.tempFiles);
const preset = await ctx.reencoder.choose(sourcePath, kind);
// Files left as authored stay in the zip; the archive size check names them.
if (!preset) return null;
const segments = kind === "image" ? null : await planFileTrim(ctx, path, sourcePath, kind);
// Keyed by encode settings and cut too, so either changing re-encodes instead of reusing old output.
const variant = JSON.stringify([REENCODE_PRESETS[preset], segments]);
return { key: keyFor(variant), preset, sourcePath, segments: segments ?? undefined };
}
/** Cuts a re-encoded file to what the entry composition plays, shifting its clips to match. */
async function planFileTrim(
ctx: OffloadContext,
path: string,
sourcePath: string,
kind: MediaKind,
): Promise<PlayedSegment[] | null> {
const entryPath = ctx.opts.entryPath ?? "index.html";
if (!textOf(entryPath, ctx.fileMap.get(entryPath))) return null;
const gridPerSecond = await ctx.reencoder.trimGrid?.(sourcePath, kind);
const entryHtmlAfterOthersPlanned = textOf(entryPath, ctx.fileMap.get(entryPath));
if (!entryHtmlAfterOthersPlanned || !gridPerSecond) return null;
const name = basename(path);
const plan = planTrim({
entryHtml: entryHtmlAfterOthersPlanned,
path,
gridPerSecond,
resolveKey: (raw) => htmlSrcKey(ctx.absDir, entryPath, raw, ctx.fileMap),
mentionedElsewhere: [...ctx.fileMap].some(
([other, content]) =>
other !== entryPath && other !== path && !!textOf(other, content)?.includes(name),
),
scriptCode: scriptCode(ctx.fileMap),
});
if (!plan) return null;
ctx.fileMap.set(entryPath, Buffer.from(plan.html, "utf-8"));
return plan.segments;
}
async function offloadFile(
ctx: OffloadContext,
path: string,
file: StagedFile,
): Promise<OffloadedMedia | null> {
const plan = await planFile(ctx, path, file);
if (!plan) return null;
const item: OffloadedMedia = {
path,
size_bytes: stagedSize(file),
action: plan.preset ? "reencode" : "upload",
...(plan.segments && {
trimmed_to_seconds: plan.segments.reduce((sum, s) => sum + s.end - s.start, 0),
}),
};
const hit = plan.key === undefined ? undefined : ctx.cache[plan.key];
if (hit && (!ctx.opts.upload || (await stillServed(hit, ctx.fetchImpl)))) {
return { ...item, action: "cached", url: hit.url, asset_id: hit.asset_id };
}
if (!ctx.opts.upload) return item;
return { ...item, ...(await uploadPlanned(ctx, ctx.opts.upload, path, file, plan)) };
}
async function uploadPlanned(
ctx: OffloadContext,
upload: NonNullable<OffloadOptions["upload"]>,
path: string,
staged: StagedFile,
plan: FilePlan,
): Promise<{ url: string; asset_id: string }> {
if (plan.key === undefined) return uploadOnce(ctx, upload, path, staged, plan);
const pending = ctx.uploadsInFlightByKey.get(plan.key);
if (pending) return pending;
const started = uploadOnce(ctx, upload, path, staged, plan);
ctx.uploadsInFlightByKey.set(plan.key, started);
return started;
}
async function uploadOnce(
ctx: OffloadContext,
upload: NonNullable<OffloadOptions["upload"]>,
path: string,
staged: StagedFile,
plan: FilePlan,
): Promise<{ url: string; asset_id: string }> {
const filename = basename(path);
const report = ctx.opts.onReencodeProgress;
const file: UploadableFile = plan.preset
? await ctx.reencoder.run(
plan.sourcePath,
plan.preset,
plan.segments,
report && ((doneSeconds, totalSeconds) => report({ path, doneSeconds, totalSeconds })),
)
: Buffer.isBuffer(staged)
? { bytes: staged, filename, contentType: plan.contentType! }
: { path: staged.absPath, size: staged.size, filename, contentType: plan.contentType! };
if (plan.preset && !Buffer.isBuffer(staged)) assertUnchanged(staged);
const size = "bytes" in file ? file.bytes.byteLength : file.size;
assertFitsAsset(path, file.filename, size);
const asset = await upload(file);
if (!Buffer.isBuffer(staged)) assertUnchanged(staged);
if (plan.key !== undefined) {
ctx.cache[plan.key] = { asset_id: asset.asset_id, url: asset.url, size_bytes: size };
writeCache(ctx.cachePath, ctx.cache);
}
return { url: asset.url, asset_id: asset.asset_id };
}
const GIF_PREFIX = "_animated_gif";
// The renderer's own GIF prep turns each animated <img> into a seek-synced WebM <video>, which then
// offloads like any video. Sub-compositions are prepared by the renderer after inlining, so not here.
async function prepareEntryGifs(
ctx: OffloadContext,
fileMap: Map<string, StagedFile>,
): Promise<void> {
const entryPath = ctx.opts.entryPath ?? "index.html";
const html = textOf(entryPath, fileMap.get(entryPath));
if (!html || !/\.gif\b/i.test(html)) return;
const sourceAssets = entryGifSources(ctx, entryPath, html);
if (!sourceAssets) return;
const prep = ctx.opts.gifPrep ?? (await import("@hyperframes/producer")).prepareAnimatedGifInputs;
const outputDir = mkdtempSync(join(tmpdir(), "hf-offload-gif-"));
ctx.tempFiles.push(outputDir);
const result = await prep(html, {
projectDir: ctx.absDir,
downloadDir: outputDir,
outputDir,
outputSrcPrefix: posix.relative(posix.dirname(entryPath), GIF_PREFIX),
cacheDir: hyperframesCacheDir("animated-gif"),
sourceAssets,
assetRoot: outputDir,
});
if (result.preparedGifs.length === 0) return;
fileMap.set(entryPath, Buffer.from(result.html, "utf-8"));
for (const gif of result.preparedGifs) {
fileMap.set(`${GIF_PREFIX}/${basename(gif.outputPath)}`, readFileSync(gif.outputPath));
const source = htmlSrcKey(ctx.absDir, entryPath, gif.sourceSrc.trim(), fileMap);
if (source) ctx.preparedGifSources.push(source);
}
}
/**
* Each entry GIF's staged bytes, resolved the way the renderer rebases a nested entry; `null` when none
* is heavy, since the renderer's own GIF prep then suffices and needs no local ffmpeg.
*/
function entryGifSources(
ctx: OffloadContext,
entryPath: string,
html: string,
): Map<string, string> | null {
const sourceAssets = new Map<string, string>();
let heavy = false;
for (const img of parseHTML(html).document.querySelectorAll("img[src]")) {
const src = img.getAttribute("src")!.trim();
const key = htmlSrcKey(ctx.absDir, entryPath, src, ctx.fileMap);
if (!key?.toLowerCase().endsWith(".gif")) continue;
const file = ctx.fileMap.get(key)!;
sourceAssets.set(src, stagedCopy(key, file, ctx.tempFiles));
heavy ||= stagedSize(file) >= OFFLOAD_MIN_BYTES;
}
return heavy ? sourceAssets : null;
}
/**
* Moves used media out of the zip as assets (cached ones reused), largest first, until the zip fits the budget.
* Without `upload`, nothing uploads and only animated GIFs are encoded.
*/
export async function offloadHeavyMedia(
projectDir: string,
fileMap: Map<string, StagedFile>,
opts: OffloadOptions,
): Promise<OffloadedMedia[]> {
const cachePath = opts.cachePath ?? defaultOffloadCachePath();
const cache = readCache(cachePath);
const apiPrefix = `${opts.apiBaseUrl} `;
const ctx: OffloadContext = {
absDir: resolve(projectDir),
opts,
cachePath,
cache,
cachedSizes: new Set(
Object.entries(cache).flatMap(([key, entry]) =>
key.startsWith(apiPrefix) ? [entry.size_bytes] : [],
),
),
fetchImpl: opts.fetchImpl ?? fetch,
reencoder: opts.reencoder ?? ffmpegReencoder,
tempFiles: [],
preparedGifSources: [],
fileMap,
uploadsInFlightByKey: new Map(),
};
const urls = new Map<string, string>();
const report: OffloadedMedia[] = [];
let referenced = new Set<string>();
try {
await prepareEntryGifs(ctx, fileMap);
// Only files a reference points at: one used through render-time --variables must stay in the zip.
referenced = referencedFiles(ctx.absDir, fileMap);
const budget = opts.zipBudgetBytes ?? 0;
const zipped = [...fileMap.values()].reduce((sum, file) => sum + stagedSize(file), 0);
const left = dropUnusedMediaWhileOver(ctx, referenced, zipped, budget);
await uploadLargestWhileOver(ctx, referenced, left, budget, urls, report);
report.sort((a, b) => a.path.localeCompare(b.path));
} finally {
for (const dir of ctx.tempFiles) rmSync(dir, { recursive: true, force: true });
}
if (urls.size > 0) rewriteReferences(ctx.absDir, fileMap, (key) => urls.get(key) ?? null);
dropReplacedFiles(fileMap, report, ctx.preparedGifSources, [...urls.values()]);
return report;
}
/** Drops media no page, script or variable names, largest first, while the zip is over budget; returns its size. */
function dropUnusedMediaWhileOver(
ctx: OffloadContext,
referenced: Set<string>,
zipped: number,
budget: number,
): number {
const { fileMap } = ctx;
const code = scriptCode(fileMap);
const variables = ctx.opts.variablesText ?? "";
const unused = [...fileMap]
.filter(([path]) => !referenced.has(path) && mediaKind(path) !== null)
.filter(([path]) => !variables.includes(basename(path)))
.filter(([path]) => !isStillMentioned(fileMap, path, code, (text) => text))
.sort(byLargest);
let left = zipped;
for (const [path, file] of unused) {
if (left <= budget) break;
fileMap.delete(path);
left -= stagedSize(file);
}
return left;
}
const byLargest = ([a, x]: [string, StagedFile], [b, y]: [string, StagedFile]) =>
stagedSize(y) - stagedSize(x) || a.localeCompare(b);
async function uploadLargestWhileOver(
ctx: OffloadContext,
referenced: Set<string>,
zipped: number,
budget: number,
urls: Map<string, string>,
report: OffloadedMedia[],
): Promise<void> {
const used = [...ctx.fileMap].filter(([path]) => referenced.has(path)).sort(byLargest);
let left = zipped;
let next = 0;
while (left > budget && next < used.length) {
const batch: [string, StagedFile][] = [];
for (let after = left; after > budget && next < used.length; next += 1) {
batch.push(used[next]!);
after -= stagedSize(used[next]![1]);
}
const items = await runWithConcurrencyLimit(
batch,
OFFLOAD_CONCURRENCY,
async ([path, file]) => {
const item = await offloadFile(ctx, path, file);
if (item) ctx.opts.onFile?.(item);
return item;
},
);
for (const [index, item] of items.entries()) {
if (!item) continue;
// A dry run rewrites to a stand-in URL so the reported archive size matches the real one.
urls.set(item.path, item.url ?? `https://assets.invalid/${report.length}`);
report.push(item);
left -= stagedSize(batch[index]![1]);
}
}
}
function dropReplacedFiles(
fileMap: Map<string, StagedFile>,
report: OffloadedMedia[],
preparedGifSources: string[],
assetUrls: string[],
): void {
// Asset URLs end in names like original.mp4 that can collide with a project file's name.
const withoutUrls = (text: string) =>
assetUrls.reduce((acc, url) => acc.replaceAll(url, ""), text);
const code = withoutUrls(scriptCode(fileMap));
for (const item of report) {
if (isStillMentioned(fileMap, item.path, code, withoutUrls)) item.kept_in_archive = true;
else fileMap.delete(item.path);
}
for (const gif of preparedGifSources) {
if (!isStillMentioned(fileMap, gif, code, withoutUrls)) fileMap.delete(gif);
}
}
const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
function namesFile(text: string, path: string): boolean {
const tokens = text.match(new RegExp(`[\\w./-]*${escapeRegExp(basename(path))}`, "g")) ?? [];
return tokens.some((token) => {
const tail = token.replace(/^[./]+/, "");
return path === tail || path.endsWith(`/${tail}`);
});
}
/** A path ending in its name, or in script code its stem as a string with the extension nearby ("clip" + ".mp4"). */
function isStillMentioned(
fileMap: Map<string, StagedFile>,
path: string,
code: string,
withoutUrls: (text: string) => string,
): boolean {
const ext = extname(path);
const stem = new RegExp(`["'\`/]${escapeRegExp(basename(path, ext))}\\.?["'\`$]`);
if (stem.test(code) && code.includes(ext.slice(1))) return true;
const name = basename(path);
for (const [entryPath, content] of fileMap) {
const contentText = textOf(entryPath, content);
if (entryPath === path || !contentText?.includes(name)) continue;
if (namesFile(withoutUrls(contentText), path)) return true;
}
return false;
}
/** The staged file an HTML src loads, resolved the way the renderer inlines sub-compositions. */
function htmlSrcKey(
absDir: string,
entryPath: string,
raw: string,
fileMap: Map<string, StagedFile>,
): string | null {
const clean = cleanAssetUrl(raw);
if (!clean || isRemoteOrInlineUrl(clean)) return null;
const rootRelative = clean.startsWith("/")
? clean
: rewriteAssetPath(entryPath, clean, (p) => fileMap.has(archiveKey(p)));
for (const candidate of resolveLocalAssetCandidates(absDir, rootRelative)) {
const key = archiveKey(relative(absDir, candidate).replaceAll("\\", "/"));
if (fileMap.has(key)) return key;
}
return null;
}
type UrlFor = (rootRelative: string) => string | null;
/** The staged files that references rewriteReferences would replace point at. */
function referencedFiles(absDir: string, fileMap: Map<string, StagedFile>): Set<string> {
const keys = new Set<string>();
rewriteReferences(absDir, fileMap, (key) => {
if (fileMap.has(key)) keys.add(key);
return null;
});
return keys;
}
function rewriteReferences(
absDir: string,
fileMap: Map<string, StagedFile>,
urlForKey: (key: string) => string | null,
): void {
const urlFor: UrlFor = (rootRelative) => {
for (const candidate of resolveLocalAssetCandidates(absDir, rootRelative)) {
const url = urlForKey(archiveKey(relative(absDir, candidate).replaceAll("\\", "/")));
if (url) return url;
}
return null;
};
for (const [entryPath, content] of [...fileMap]) {
const rewrite = rewriterFor(absDir, entryPath, urlFor, fileMap);
const text = rewrite ? textOf(entryPath, content) : undefined;
const next = rewrite && text !== undefined ? rewrite(text) : null;
if (next !== null) fileMap.set(entryPath, Buffer.from(next, "utf-8"));
}
}
function rewriterFor(
absDir: string,
entryPath: string,
urlFor: UrlFor,
fileMap: Map<string, StagedFile>,
): ((text: string) => string | null) | null {
if (/\.html?$/i.test(entryPath)) {
return (text) => rewriteHtmlEntry(absDir, entryPath, text, urlFor, fileMap);
}
if (/\.css$/i.test(entryPath)) return (text) => rewriteCssEntry(absDir, entryPath, text, urlFor);
if (/\.(m?js|cjs|json)$/i.test(entryPath)) return (text) => rewriteStringLiterals(text, urlFor);
return null;
}
function localTarget(raw: string, toRootRelative: (clean: string) => string, urlFor: UrlFor) {
const clean = cleanAssetUrl(raw);
if (!clean || isRemoteOrInlineUrl(clean)) return null;
const url = urlFor(clean.startsWith("/") ? clean : toRootRelative(clean));
// Keep a query or media fragment such as #t=5,8.
return url && url + raw.trim().slice(clean.length);
}
function rewriteCssEntry(absDir: string, entryPath: string, css: string, urlFor: UrlFor) {
// A stylesheet's url() resolves against the stylesheet itself.
const result = rewriteCssUrls(css, resolve(absDir, dirname(entryPath)), entryPath, (raw) =>
localTarget(raw, (clean) => posix.join(posix.dirname(entryPath), clean), urlFor),
);
return result.modified ? result.css : null;
}
const TEMPLATE_SCENE_RE = /(<template\b[^>]*>)([\s\S]*?)(<\/template>)/gi;
/** An entry's HTML with each <template> scene rewritten too: the runtime stamps those scenes into the page. */
function rewriteHtmlEntry(
absDir: string,
entryPath: string,
source: string,
urlFor: UrlFor,
fileMap: Map<string, StagedFile>,
): string | null {
const html = source.replace(
TEMPLATE_SCENE_RE,
(full, open: string, inner: string, close: string) => {
const next = rewriteHtmlEntry(absDir, entryPath, inner, urlFor, fileMap);
return next === null ? full : open + next + close;
},
);
return (
rewriteHtmlDocument(absDir, entryPath, html, urlFor, fileMap) ?? (html === source ? null : html)
);
}
function rewriteHtmlDocument(
absDir: string,
entryPath: string,
html: string,
urlFor: UrlFor,
fileMap: Map<string, StagedFile>,
): string | null {
const referrerAbsDir = resolve(absDir, dirname(entryPath));
// Sub-composition srcs resolve the way the renderer inlines them.
const resolveTarget: HtmlAttributeResolver = (raw) =>
localTarget(
raw,
(clean) => rewriteAssetPath(entryPath, clean, (p) => fileMap.has(archiveKey(p))),
urlFor,
);
const { document } = parseHTML(html);
const attrs = rewriteHtmlAttributes(document, referrerAbsDir, entryPath, resolveTarget, {
attrs: ["src", "poster", "href"],
});
const srcsets = rewriteSrcsets(document, resolveTarget);
const styles = rewriteStyleBlocks(document, referrerAbsDir, entryPath, resolveTarget);
let scripts = false;
for (const script of document.querySelectorAll("script")) {
if (script.hasAttribute("src")) continue;
const next = rewriteStringLiterals(script.textContent ?? "", urlFor);
if (next === null) continue;
script.textContent = next;
scripts = true;
}
return attrs || srcsets || styles || scripts ? document.toString() : null;
}
// A plain string literal: no escapes, interpolation or line breaks.
const STRING_LITERAL_RE = /(["'`])([^"'`\\\n$]+)\1/g;
/** Script URLs resolve against the page, which the renderer roots at the project. */
function rewriteStringLiterals(code: string, urlFor: UrlFor): string | null {
let modified = false;
const next = code.replace(STRING_LITERAL_RE, (full, quote: string, value: string) => {
const url = localTarget(value, (clean) => clean, urlFor);
if (!url) return full;
modified = true;
return `${quote}${url}${quote}`;
});
return modified ? next : null;
}
function rewriteSrcsets(document: Document, resolveTarget: HtmlAttributeResolver): boolean {
let modified = false;
for (const el of document.querySelectorAll("[srcset]")) {
const srcset = el.getAttribute("srcset") ?? "";
// A data: candidate carries its own commas; leave such a srcset as authored.
if (srcset.includes("data:")) continue;
let changed = false;
const next = srcset
.split(",")
.map((part) => {
const [url, ...descriptors] = part.trim().split(/\s+/);
const target = url ? resolveTarget(url, "") : null;
if (!target) return part.trim();
changed = true;
return [target, ...descriptors].join(" ");
})
.join(", ");
if (changed) {
el.setAttribute("srcset", next);
modified = true;
}
}
return modified;
}