import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import vm from 'node:vm'; import { brotliDecompressSync, gunzipSync } from 'node:zlib'; import { PREVIEW_THUMBNAIL_CAPTURE } from '../../src/studio/engine/preview-thumbnail-capture.ts'; import { PREVIEW_BRIDGE_SCRIPT } from '../../src/studio/engine/preview-bridge.ts'; import { buildSubCompositionHtmlInMemory } from '../../src/studio/engine/preview-bundler.ts'; import { createStudioPreviewRoutes, SNAPDOM_VENDOR_PATH } from '../../src/studio/routes/preview.ts'; import { computePreviewImpact } from '../../shared/preview-impact.ts'; import { computeCompositionRevisions } from '../../src/studio/routes/projects.ts'; describe('preview-thumbnail-capture embedded bridge script', () => { it('parses as valid ES5 browser code and registers capture-frames in preview-bridge', () => { assert.doesNotThrow(() => new vm.Script(`(function(){${PREVIEW_THUMBNAIL_CAPTURE}})()`)); assert.match(PREVIEW_BRIDGE_SCRIPT, /capture-frames/); assert.match(PREVIEW_BRIDGE_SCRIPT, /thumbnail-capture/); assert.equal(SNAPDOM_VENDOR_PATH, '/api/vendor/snapdom.js'); }); it('pauses playback, recovers when rAF is throttled, and downgrades preview-asset fetch credentials for 302 S3 redirects', async () => { let paused = false; const sought: number[] = []; const observedFetches: Array<{ url: string; credentials?: string }> = []; const origFetch = (input: string, init?: { credentials?: string }) => { observedFetches.push({ url: input, credentials: init?.credentials }); return Promise.resolve({ ok: true }); }; const fakeStage = { nodeType: 1, tagName: 'DIV', clientWidth: 1280, clientHeight: 720, textContent: 'Hello', getAttribute: (name: string) => (name === 'data-width' ? '1280' : name === 'data-height' ? '720' : null), querySelectorAll: () => [], querySelector: () => null, getBoundingClientRect: () => ({ width: 1280, height: 720 }), }; const fakeCanvas = { width: 0, height: 0, getContext: () => ({ drawImage: () => {} }), toBlob: (cb: (blob: { arrayBuffer: () => Promise }) => void) => { cb({ arrayBuffer: () => Promise.resolve(new Uint8Array([0xff, 0xd8, 0x01]).buffer) }); }, }; const sandbox: Record = { URL, Promise, Array, Object, Number, Math, String, Error, setTimeout, clearTimeout, location: { origin: 'https://preview.example.test', href: 'https://preview.example.test/api/projects/p1/preview/comp/s1.html?capture=1&pt=tok' }, // Simulate throttled cross-origin iframe where requestAnimationFrame never fires. requestAnimationFrame: () => 0, player: () => ({ pause: () => { paused = true; }, seek: (t: number) => { sought.push(t); }, }), document: { body: fakeStage, fonts: { ready: Promise.resolve() }, querySelector: () => fakeStage, querySelectorAll: () => [], createElement: (tag: string) => (tag === 'canvas' ? { ...fakeCanvas } : {}), }, window: { innerWidth: 1280, innerHeight: 720, fetch: origFetch, snapdom: async () => { const fetchFn = (sandbox.window as { fetch: typeof origFetch }).fetch; await fetchFn('https://preview.example.test/api/projects/p1/preview/~assets/lease/assets/hero.png', { credentials: 'include' }); await fetchFn('https://cdn.example.test/other.png', { credentials: 'include' }); return { toCanvas: async () => ({}) }; }, }, }; const capturePreviewFrames = vm.runInNewContext( `(function(){${PREVIEW_THUMBNAIL_CAPTURE}; return capturePreviewFrames;})()`, sandbox, ) as (msg: Record) => Promise<{ frames: ArrayBuffer[]; width: number; height: number }>; const result = await capturePreviewFrames({ times: [0.5, 2.5], width: 240 }); assert.equal(paused, true); assert.deepEqual(sought, [0.5, 2.5]); assert.equal(result.frames.length, 2); assert.equal(result.width, 240); assert.equal(result.height, 135); assert.equal((sandbox.window as { fetch: unknown }).fetch, origFetch, 'window.fetch must be restored'); assert.deepEqual(observedFetches.slice(0, 2), [ { url: 'https://preview.example.test/api/projects/p1/preview/~assets/lease/assets/hero.png', credentials: 'same-origin', }, { url: 'https://cdn.example.test/other.png', credentials: 'include', }, ]); }); it('streams progressive frames hero-cover first and returns streamed metadata when onFrame is supplied', async () => { const sought: number[] = []; const emitted: Array<{ index: number; total: number; byte0: number }> = []; let frameCounter = 0; const fakeStage = { nodeType: 1, tagName: 'DIV', clientWidth: 1920, clientHeight: 1080, textContent: 'Scene', getAttribute: (name: string) => (name === 'data-width' ? '1920' : name === 'data-height' ? '1080' : null), querySelectorAll: () => [], querySelector: () => null, getBoundingClientRect: () => ({ width: 1920, height: 1080 }), }; const fakeCanvas = { width: 0, height: 0, getContext: () => ({ drawImage: () => {} }), toBlob: (cb: (blob: { arrayBuffer: () => Promise }) => void) => { const seq = ++frameCounter; cb({ arrayBuffer: () => Promise.resolve(new Uint8Array([seq]).buffer) }); }, }; const sandbox: Record = { URL, Promise, Array, Object, Number, Math, String, Error, setTimeout, clearTimeout, location: { origin: 'https://preview.example.test', href: 'https://preview.example.test/api/projects/p1/preview/comp/s1.html?capture=1&pt=tok' }, requestAnimationFrame: (fn: () => void) => setTimeout(fn, 0), player: () => ({ pause: () => {}, seek: (t: number) => { sought.push(t); }, }), document: { body: fakeStage, fonts: { ready: Promise.resolve() }, querySelector: () => fakeStage, querySelectorAll: () => [], createElement: (tag: string) => (tag === 'canvas' ? { ...fakeCanvas } : {}), }, window: { innerWidth: 1920, innerHeight: 1080, fetch: () => Promise.resolve({ ok: true }), snapdom: async () => ({ toCanvas: async () => ({}) }), }, }; const capturePreviewFrames = vm.runInNewContext( `(function(){${PREVIEW_THUMBNAIL_CAPTURE}; return capturePreviewFrames;})()`, sandbox, ) as ( msg: Record, onFrame: (ev: { index: number; total: number; frame: ArrayBuffer }, buf: ArrayBuffer) => void, ) => Promise<{ frames: ArrayBuffer[]; streamed?: boolean; frameCount?: number }>; const result = await capturePreviewFrames({ times: [0.4, 3.4, 6.4, 9.4], width: 240, progressive: true }, (ev, buf) => { emitted.push({ index: ev.index, total: ev.total, byte0: new Uint8Array(buf)[0]! }); }); // Mid-scene hero frame (index 2 => 6.4s) is captured and streamed first, then remaining indices. assert.deepEqual(sought, [6.4, 0.4, 3.4, 9.4]); assert.deepEqual(emitted.map((e) => e.index), [2, 0, 1, 3]); assert.equal(result.streamed, true); assert.equal(result.frameCount, 4); assert.equal(result.frames.length, 0); }); it('announces capture=1 timeline-state immediately via fast boot poll without waiting 500ms or preloading video', async () => { const posted: Array> = []; const appendedScripts: string[] = []; let videoLoadCalls = 0; const intervals: Array> = []; const trackedSetInterval = ((fn: () => void, ms: number) => { const id = setInterval(fn, ms); intervals.push(id); return id; }) as typeof setInterval; const fakeVideo = { tagName: 'VIDEO', preload: 'none', readyState: 0, networkState: 0, hasAttribute: () => false, getAttribute: (name: string) => (name === 'src' ? 'assets/heavy.mp4' : null), querySelector: () => null, addEventListener: () => {}, removeEventListener: () => {}, load: () => { videoLoadCalls += 1; }, }; const fakeWindow: Record = { addEventListener: () => {}, innerWidth: 1920, innerHeight: 1080, __player: null, __clipManifest: { compositionWidth: 1920, compositionHeight: 1080, fps: 30, durationInFrames: 180 }, parent: { postMessage: (msg: Record) => { posted.push(msg); }, }, }; const fakeDocument = { readyState: 'interactive', visibilityState: 'visible', referrer: 'https://studio.example.test/', baseURI: 'https://preview.example.test/api/projects/p1/preview/~assets/lease-1/', currentScript: { getAttribute: () => JSON.stringify({ projectId: 'p1', compositionPath: 'compositions/s1.html', sourceVersions: {} }), }, head: { appendChild: (node: { src?: string }) => { if (node.src) appendedScripts.push(node.src); }, }, documentElement: { appendChild: () => {} }, addEventListener: () => {}, querySelector: () => null, querySelectorAll: (sel: string) => (sel === 'video' ? [fakeVideo] : []), createElement: () => ({}), }; const sandbox: Record = { URL, Promise, Array, Object, Number, Math, String, Error, JSON, Boolean, setTimeout, clearTimeout, setInterval: trackedSetInterval, clearInterval, location: { origin: 'https://preview.example.test', href: 'https://preview.example.test/api/projects/p1/preview/comp/compositions/s1.html?capture=1&pt=tok-fast', }, window: fakeWindow, document: fakeDocument, innerWidth: 1920, innerHeight: 1080, }; try { const start = Date.now(); vm.runInNewContext(PREVIEW_BRIDGE_SCRIPT, sandbox); // SnapDOM preload starts eagerly in capture=1 mode. assert.deepEqual(appendedScripts, ['/api/vendor/snapdom.js']); // Simulate async runtime boot 30ms later (well before the 500ms heartbeat, without window.load). setTimeout(() => { fakeWindow.__player = { getTime: () => 0, getDuration: () => 6, isPlaying: () => false }; }, 30); await new Promise((resolve, reject) => { const check = setInterval(() => { if (posted.some((m) => m.type === 'timeline-state' && Number(m.duration) === 6)) { clearInterval(check); resolve(); } else if (Date.now() - start > 300) { clearInterval(check); reject(new Error('Expected fast boot poll to emit timeline-state well under 500ms')); } }, 10); }); const elapsed = Date.now() - start; assert.ok(elapsed < 300, `Expected <300ms fast boot handshake, got ${elapsed}ms`); assert.equal(videoLoadCalls, 0, 'capture=1 must not preload