import { spawn } from 'node:child_process'; import type { ChildProcess } from 'node:child_process'; import { access, copyFile, mkdir, open, readFile, rename, rm, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { validateExportExpectation } from './shared/export-spec.ts'; import { assertRenderSubprocessEnvClean, injectStudioRenderParityIntoHydratedDir, injectStudioRenderParityScripts, } from './src/workers/render-env.ts'; export { injectStudioRenderParityIntoHydratedDir, injectStudioRenderParityScripts }; export const HYPERFRAMES_VERSION = '0.9.7'; // Omitting registry uses the pinned CLI's official catalog, just like a native project. export const nativeProjectConfig = { $schema: 'https://hyperframes.heygen.com/schema/hyperframes.json', paths: { blocks: 'compositions', components: 'compositions/components', assets: 'assets' }, }; export const pluginRoot = fileURLToPath(new URL('./', import.meta.url)); export const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); const commands = new Set(); function terminate(child: ChildProcess, signal: NodeJS.Signals = 'SIGTERM') { try { if (process.platform !== 'win32' && child.pid) process.kill(-child.pid, signal); else if (child.pid && process.platform === 'win32') spawn('taskkill.exe', ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true, stdio: 'ignore' }).on('error', () => child.kill(signal)); else child.kill(signal); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error; } } export function stopCommands() { for (const child of commands) terminate(child); } export function runtimeEnv(): NodeJS.ProcessEnv { const captureFix = '--import=' + new URL('./shared/hyperframes-capture-fix.mjs', import.meta.url).href; return { ...process.env, HYPERFRAMES_NO_TELEMETRY: '1', HYPERFRAMES_PREVIEW_HOST: '127.0.0.1', NODE_OPTIONS: process.env.NODE_OPTIONS?.includes(captureFix) ? process.env.NODE_OPTIONS : [process.env.NODE_OPTIONS, captureFix].filter(Boolean).join(' '), // shortcut: pinned Node can hang in Windows compile-cache startup; remove after upstream fix is verified (nodejs/node#66438). ...(process.platform === 'win32' ? { NODE_DISABLE_COMPILE_CACHE: '1' } : {}), ...(!process.env.HYPERFRAMES_FFMPEG_PATH && process.env.FFMPEG_PATH ? { HYPERFRAMES_FFMPEG_PATH: process.env.FFMPEG_PATH } : {}), ...(!process.env.HYPERFRAMES_FFPROBE_PATH && process.env.FFPROBE_PATH ? { HYPERFRAMES_FFPROBE_PATH: process.env.FFPROBE_PATH } : {}) }; } export type CommandResult = { code: number; stdout: string; stderr: string }; export interface IsolatedExecuteOptions { readonly env: Record; readonly timeoutMs?: number; readonly signal?: AbortSignal; readonly onStdoutLine?: (line: string) => void; readonly onStderrLine?: (line: string) => void; } /** * Execute a subprocess inside `worker-render` using ONLY the strictly allowlisted `options.env`. * Unlike `execute()`, this NEVER inherits `process.env` or `runtimeEnv()` and enforces * `assertRenderSubprocessEnvClean(options.env)` before spawning Chromium / Hyperframes. */ export function executeIsolated( command: string, args: string[], cwd: string, options: IsolatedExecuteOptions, ): Promise { assertRenderSubprocessEnvClean(options.env); const timeout = options.timeoutMs ?? 25 * 60_000; const signal = options.signal; return new Promise((resolve, reject) => { if (signal?.aborted) { reject(new Error('COMMAND_CANCELLED')); return; } const child = spawn(command, args, { cwd, env: { ...options.env }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32', }); commands.add(child); let stdout = ''; let stderr = ''; let stdoutLineBuf = ''; let stderrLineBuf = ''; let timedOut = false; const timer = setTimeout(() => { timedOut = true; terminate(child); }, timeout); const killer = setTimeout(() => terminate(child, 'SIGKILL'), timeout + 5000); let cancellationKiller: ReturnType | undefined; const cancel = () => { terminate(child); cancellationKiller = setTimeout(() => terminate(child, 'SIGKILL'), 5000); }; signal?.addEventListener('abort', cancel, { once: true }); const flushLines = (chunk: string, buf: string, callback?: (line: string) => void): string => { if (!callback) return ''; let combined = buf + chunk; let idx = combined.indexOf('\n'); while (idx >= 0) { const line = combined.slice(0, idx).replace(/\r$/, ''); combined = combined.slice(idx + 1); try { callback(line); } catch { // Never allow progress listener error to crash subprocess lifecycle handling. } idx = combined.indexOf('\n'); } return combined; }; const cleanup = () => { commands.delete(child); clearTimeout(timer); clearTimeout(killer); clearTimeout(cancellationKiller); signal?.removeEventListener('abort', cancel); }; child.stdout.on('data', (data) => { const text = String(data); stdout = (stdout + text).slice(-4 * 1024 * 1024); stdoutLineBuf = flushLines(text, stdoutLineBuf, options.onStdoutLine); }); child.stderr.on('data', (data) => { const text = String(data); stderr = (stderr + text).slice(-64 * 1024); stderrLineBuf = flushLines(text, stderrLineBuf, options.onStderrLine); }); child.on('error', (error) => { cleanup(); reject(error); }); child.on('close', (code) => { if (stdoutLineBuf.length > 0 && options.onStdoutLine) { try { options.onStdoutLine(stdoutLineBuf.replace(/\r$/, '')); } catch { // Ignore trailing callback error. } } if (stderrLineBuf.length > 0 && options.onStderrLine) { try { options.onStderrLine(stderrLineBuf.replace(/\r$/, '')); } catch { // Ignore trailing callback error. } } cleanup(); if (signal?.aborted) { reject(new Error('COMMAND_CANCELLED')); } else if (timedOut) { reject(Object.assign(new Error('Hyperframes render timed out: ' + stderr.slice(-1000)), { code: 'COMMAND_TIMEOUT' })); } else { resolve({ code: code ?? 1, stdout, stderr }); } }); }); } export async function runHyperframesIsolated( runtimeRoot: string, directory: string, args: string[], options: IsolatedExecuteOptions, ): Promise { return executeIsolated(process.execPath, [cliPath(runtimeRoot), ...args], directory, options); } export async function inspectProjectIsolated( runtimeRoot: string, directory: string, view: 'info' | 'lint' | 'timeline', options: IsolatedExecuteOptions, ): Promise<{ exitCode: number; result: unknown }> { const result = view === 'lint' ? await executeIsolated( process.execPath, [path.join(pluginRoot, 'scripts/lint-project.mjs'), runtimeRoot, directory], directory, options, ) : await runHyperframesIsolated(runtimeRoot, directory, [view, '.', '--json'], options); try { return { exitCode: result.code, result: JSON.parse(result.stdout) }; } catch { throw new Error(`Hyperframes ${view} failed: ${(result.stderr || result.stdout).slice(-1500)}`); } } function readHtmlAttribute(element: Element, name: string): string | undefined { return Array.from(element.attributes).find((item) => item.name.toLowerCase() === name)?.value; } function findRootCompositionInDocument( document: Document, parseHTMLContent: (html: string) => Document, ): { root: Element; fromTemplate: boolean } | undefined { const pickRoot = (doc: Document): Element | undefined => { const compositions = Array.from(doc.querySelectorAll('*')) as Element[]; const roots = compositions.filter((element) => readHtmlAttribute(element, 'data-composition-id') !== undefined); return roots.find((element) => readHtmlAttribute(element, 'data-root') === 'true') || roots[0]; }; const direct = pickRoot(document); if (direct) return { root: direct, fromTemplate: false }; for (const template of Array.from(document.querySelectorAll('template')) as Element[]) { const innerHtml = template.innerHTML; if (!innerHtml) continue; const innerRoot = pickRoot(parseHTMLContent(innerHtml)); if (innerRoot) return { root: innerRoot, fromTemplate: true }; } return undefined; } function parsePositiveNumberAttr(raw: string | undefined): number | undefined { if (!raw) return undefined; const parsed = Number(raw.trim()); return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined; } function parseDurationSecondsAttr(raw: string | undefined): number | undefined { if (!raw) return undefined; const trimmed = raw.trim(); if (!trimmed) return undefined; const match = /^([+-]?(?:\d+\.?\d*|\.\d+))(ms|s)?$/i.exec(trimmed); if (!match) return undefined; const value = Number(match[1]); if (!Number.isFinite(value) || value <= 0) return undefined; return match[2]?.toLowerCase() === 'ms' ? value / 1000 : value; } async function resolveSnapshotCompositionContext( runtimeRoot: string, directory: string, compositionPath: string, ) { const coreRoot = path.join(runtimeRoot, 'node_modules/@hyperframes/core'); const core = JSON.parse(await readFile(path.join(coreRoot, 'package.json'), 'utf8')); const [ { parseHTMLContent, isTemplateEntry, extractStandaloneEntryFromIndex }, { parseFps, fpsToNumber, CANVAS_DIMENSIONS }, ] = await Promise.all([ import(pathToFileURL(path.join(coreRoot, core.exports['./compiler'].import)).href), import(pathToFileURL(path.join(coreRoot, core.exports['.'].import)).href), ]); const entryHtml = await readFile(path.join(directory, compositionPath), 'utf8'); const entryDoc = parseHTMLContent(entryHtml); const found = findRootCompositionInDocument(entryDoc, parseHTMLContent); if (!found) { return { sceneRoot: undefined, fromTemplate: false, shellRoot: undefined, parseFps, fpsToNumber, CANVAS_DIMENSIONS, }; } // Match hyperframes@0.9.7 producer: a