← Files Flows by plugin.spaceARCHIVED FILE
scripts/capture.mjs
7.82 KB · Nov 30, 2026 · 00:17 UTC
#!/usr/bin/env node
import { createLibrary, inferApplication } from '../lib/library.mjs';
import { launcherCommand } from '../lib/node-runtime.mjs';
import { readFile, stat } from 'node:fs/promises';
import { resolve } from 'node:path';
import { isEntrypoint } from '../lib/entrypoint.mjs';
import { readDocument } from '../lib/document.mjs';
import { DEFAULT_CAPTURE_SETTINGS } from '../lib/capture-settings.mjs';
import { attachScreenshots, discardScreenshots, saveScreenshot } from '../lib/screenshots.mjs';
import { findCaptureRuntime, launchCaptureBrowser } from '../lib/capture-runtime.mjs';
import { isHttpUrl, validateSteps, applySteps, verifyUrl, MANUAL_LOGIN_MESSAGE } from '../lib/capture-session.mjs';
export function validatePlan(plan, document, profiles) {
if (!Array.isArray(plan?.screens) || plan.screens.length < 1 || plan.screens.length > 64) throw new Error('A plan needs 1–64 screens.');
if ('auth' in plan || 'storageState' in plan) throw new Error(`Scripted login and session imports are no longer supported. ${MANUAL_LOGIN_MESSAGE}`);
const ids = new Set();
for (const screen of plan.screens) {
if (!screen || !document.nodes.some(node => node.id === screen.nodeId && node.type === 'screen') || ids.has(screen.nodeId)) throw new Error('Each plan entry needs a unique existing screen nodeId.');
ids.add(screen.nodeId);
if (!isHttpUrl(screen.url) || (screen.expectedUrl !== undefined && !isHttpUrl(screen.expectedUrl))) throw new Error('Use HTTP(S) capture URLs without credentials.');
if (typeof screen.readySelector !== 'string' || !screen.readySelector || screen.readySelector.length > 1000) throw new Error('Each screen needs a readySelector identifying its actual state.');
validateSteps(screen.steps ?? []);
if (screen.profileSteps !== undefined) {
if (!screen.profileSteps || typeof screen.profileSteps !== 'object' || Array.isArray(screen.profileSteps)) throw new Error('profileSteps must map profile IDs to steps.');
for (const [id, steps] of Object.entries(screen.profileSteps)) { if (!profiles.some(profile => profile.id === id)) throw new Error(`Unknown or disabled profile: ${id}`); validateSteps(steps); }
}
}
}
export async function captureFlow({ file, plan, chromium, channel, storageState, profileIds, timeout = 30000, onProgress = () => {}, library }) {
if (storageState !== undefined) throw new Error(`Session imports are no longer supported. ${MANUAL_LOGIN_MESSAGE}`);
const localId = library ? await library.register(file, await inferApplication(file)) : undefined;
if (library) await library.withWritable(localId, () => {});
const { document, revision } = await readDocument(file);
const settings = library ? await library.capturePreferences.effective(document.captureSettings) : document.captureSettings ?? DEFAULT_CAPTURE_SETTINGS;
const profiles = settings.profiles.filter(profile => profile.enabled && (!profileIds || profileIds.includes(profile.id)));
if (!profiles.length || profileIds?.some(id => !profiles.some(profile => profile.id === id))) throw new Error('Choose enabled capture profiles from the document settings.');
validatePlan(plan, document, settings.profiles);
if (plan.screens.length * profiles.length > 64) throw new Error('Use at most 64 captures per run; choose fewer screens or profiles.');
const { browser } = await launchCaptureBrowser(chromium, channel);
const shots = [];
let attached = false;
try {
for (const screen of plan.screens) for (const profile of profiles) {
const context = await browser.newContext({ viewport: { width: profile.width, height: profile.height }, deviceScaleFactor: 1, isMobile: profile.isMobile, hasTouch: profile.hasTouch, colorScheme: settings.colorScheme, reducedMotion: 'reduce' });
try {
const page = await context.newPage();
page.setDefaultTimeout(timeout); page.setDefaultNavigationTimeout(timeout);
const response = await page.goto(screen.url, { waitUntil: 'domcontentloaded' });
if ([401, 403].includes(response?.status())) throw new Error(`The application requires access. ${MANUAL_LOGIN_MESSAGE}`);
if (!response?.ok()) throw new Error('The target page did not load successfully.');
if (![screen.url, screen.expectedUrl].filter(Boolean).some(url => new URL(url).href === page.url())) throw new Error(`The page redirected to a different URL before capture. ${MANUAL_LOGIN_MESSAGE}`);
await applySteps(page, [...(screen.steps ?? []), ...(screen.profileSteps?.[profile.id] ?? [])]);
try { await verifyUrl(page, screen.expectedUrl ?? screen.url, Math.min(timeout, 5000)); }
catch { throw new Error(`The page redirected to a different URL. ${MANUAL_LOGIN_MESSAGE}`); }
await page.locator(screen.readySelector).waitFor({ state: 'visible' });
await page.waitForFunction(() => document.fonts.status === 'loaded' && [...document.images].every(image => image.complete), null, { timeout });
const buffer = await page.screenshot({ type: 'png', fullPage: settings.fullPage, animations: 'disabled', timeout });
shots.push(await saveScreenshot(file, { nodeId: screen.nodeId, profile, buffer, method: 'playwright', url: page.url() }));
onProgress(`${screen.nodeId} · ${profile.name} · ${profile.width} × ${profile.height}`);
} catch (error) {
throw new Error(`Capture failed for ${screen.nodeId}/${profile.id}: ${error.message}`);
}
finally { await context.close(); }
}
const attach = () => attachScreenshots(file, revision, shots, settings);
const result = library ? await library.withWritable(localId, attach) : await attach();
attached = true;
return { ...result, count: shots.length };
} finally { try { if (!attached) await discardScreenshots(shots); } finally { await browser.close(); } }
}
export function loadPlaywright(project, runtimeDirectory) {
const runtime = findCaptureRuntime({ project, runtimeDirectory });
if (runtime) return runtime.playwright;
throw new Error(`Run ${launcherCommand('setup-capture')} --install to prepare Flows capture. Your app does not need Playwright.`);
}
export async function main(args = process.argv.slice(2)) {
if (args.includes('--help')) { console.log(`Capture real screens at enabled flow viewport sizes.\nPrepare once: ${launcherCommand('setup-capture')} --install\n${launcherCommand('capture')} --file flow.flows.json --plan capture-plan.json [--runtime /capture-cache] [--project /app] [--profiles mobile,desktop] [--channel chrome]\nFor screens requiring login: ${MANUAL_LOGIN_MESSAGE}\nUse the browser's screenshot tool and attach-screen for authenticated screens. Screenshot URLs omit query strings and fragments.`); return; }
if (args.includes('--storage-state')) throw new Error(`Session imports are no longer supported. ${MANUAL_LOGIN_MESSAGE}`);
const options = {};
for (let index = 0; index < args.length; index += 2) {
if (!['--file', '--plan', '--project', '--profiles', '--channel', '--runtime', '--library'].includes(args[index]) || !args[index + 1]) throw new Error('Invalid option. Use --help.');
options[args[index]] = args[index + 1];
}
if (!options['--file'] || !options['--plan']) throw new Error('Provide --file and --plan.');
if ((await stat(options['--plan'])).size > 1024 * 1024) throw new Error('Capture plan exceeds 1 MB.');
const plan = JSON.parse(await readFile(options['--plan'], 'utf8'));
const { chromium } = loadPlaywright(options['--project'], options['--runtime']);
const result = await captureFlow({ library: createLibrary(options['--library']), file: resolve(options['--file']), plan, chromium, channel: options['--channel'], profileIds: options['--profiles']?.split(','), onProgress: message => console.log(message) });
console.log(`Saved ${result.count} real screenshots. The viewer will refresh automatically.`);
}
if (isEntrypoint(import.meta.url)) main().catch(error => { console.error(error.message); process.exitCode = 1; });
SHA-256: 1c1381cc1c78b43c8751d0c29243c37604cec7533d41b9d5ca83ab938ff7226e