← Files Flows by plugin.spaceARCHIVED FILE

lib/capture-runtime.mjs

5.58 KB · Nov 30, 2026 · 00:17 UTC

↓ Download file

import { createRequire } from 'node:module';
import { homedir } from 'node:os';
import { dirname, isAbsolute, relative, resolve } from 'node:path';
import { mkdir, readFile, writeFile, open, rm } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import { findNpmCli, launcherCommand, nodeEnvironment } from './node-runtime.mjs';

export const PLAYWRIGHT_VERSION = '1.62.1';
export const defaultRuntimeDirectory = () => resolve(homedir(), '.cache', 'flows', `playwright-${PLAYWRIGHT_VERSION}`);

function loadAt(directory, managed = false) {
  const require = createRequire(resolve(directory, 'package.json'));
  for (const name of managed ? ['playwright'] : ['playwright', '@playwright/test']) {
    try {
      const packagePath = require.resolve(`${name}/package.json`);
      const version = require(`${name}/package.json`).version;
      const packageRelative = relative(resolve(directory, 'node_modules'), packagePath);
      if (managed && (version !== PLAYWRIGHT_VERSION || packageRelative.startsWith('..') || isAbsolute(packageRelative))) continue;
      const playwright = require(name);
      return { playwright, version, directory, cli: resolve(dirname(require.resolve('playwright/package.json')), 'cli.js') };
    } catch (error) { if (!['MODULE_NOT_FOUND', 'ERR_PACKAGE_PATH_NOT_EXPORTED'].includes(error.code)) throw error; }
  }
  return null;
}

export function findCaptureRuntime({ project, runtimeDirectory = defaultRuntimeDirectory() } = {}) {
  return loadAt(runtimeDirectory, true) ?? (project ? loadAt(project) : null);
}

function run(command, args, cwd, onProgress) {
  return new Promise((resolvePromise, reject) => {
    const child = spawn(command, args, { cwd, env: nodeEnvironment(), shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
    let tail = '';
    for (const stream of [child.stdout, child.stderr]) stream.on('data', data => { const line = data.toString(); tail = (tail + line).slice(-1500); onProgress(line.trim()); });
    child.on('error', reject);
    child.on('close', code => code === 0 ? resolvePromise() : reject(new Error(`Capture setup failed (${code}). ${tail}`)));
  });
}

export async function installCaptureRuntime(directory = defaultRuntimeDirectory(), onProgress = () => {}) {
  const npm = findNpmCli();
  if (!npm) throw new Error('npm is unavailable. Run setup-capture --install through scripts/run.sh or scripts/run.ps1 to prepare the private Node.js runtime.');
  await mkdir(directory, { recursive: true, mode: 0o700 });
  const lockPath = resolve(directory, '.install.lock');
  let lock;
  try { lock = await open(lockPath, 'wx', 0o600); }
  catch (error) { if (error.code === 'EEXIST') throw new Error('Capture setup is already running. Wait for it to finish.'); throw error; }
  try {
    const existing = loadAt(directory, true);
    if (existing) return existing;
    // The dedicated cache contains only Flows's capture dependency.
    const manifestPath = resolve(directory, 'package.json');
    let existingManifest;
    try { existingManifest = JSON.parse(await readFile(manifestPath, 'utf8')); } catch (error) { if (error.code !== 'ENOENT') throw error; }
    if (existingManifest && existingManifest.name !== 'flows-capture-runtime') throw new Error('Runtime directory contains a different project. Choose an empty dedicated directory.');
    await writeFile(manifestPath, `${JSON.stringify({ name: 'flows-capture-runtime', private: true, version: '1.0.0', dependencies: { playwright: PLAYWRIGHT_VERSION } }, null, 2)}\n`, { mode: 0o600 });
    await run(process.execPath, [npm, 'install', '--ignore-scripts', '--no-audit', '--no-fund', '--registry=https://registry.npmjs.org'], directory, onProgress);
    const runtime = loadAt(directory, true);
    if (!runtime) throw new Error('Playwright did not install correctly in the capture runtime.');
    return runtime;
  } finally { await lock.close(); await rm(lockPath, { force: true }); }
}

const missingBrowser = error => /Executable doesn't exist|executable doesn't exist|distribution .*not found|executable.*not found/i.test(error.message);
export async function launchCaptureBrowser(chromium, channel) {
  if (channel) return { browser: await chromium.launch({ headless: true, channel }), channel };
  try { return { browser: await chromium.launch({ headless: true }), channel: 'chromium' }; }
  catch (error) { if (!missingBrowser(error)) throw error; }
  try { return { browser: await chromium.launch({ headless: true, channel: 'chrome' }), channel: 'chrome' }; }
  catch (error) { if (!missingBrowser(error)) throw error; throw Object.assign(new Error(`No capture browser is installed. Run ${launcherCommand('setup-capture')} --install.`), { code: 'BROWSER_MISSING' }); }
}

export async function prepareCaptureRuntime({ project, runtimeDirectory = defaultRuntimeDirectory(), install = false, channel, onProgress = () => {} } = {}) {
  let runtime = findCaptureRuntime({ project, runtimeDirectory });
  if (!runtime && install) runtime = await installCaptureRuntime(runtimeDirectory, onProgress);
  if (!runtime) throw new Error('Capture runtime is missing. Run setup-capture --install through <PLUGIN_ROOT>/scripts/run.sh (macOS/Linux) or scripts/run.ps1 (Windows). No dependency needs to be added to your app.');
  let launched;
  try { launched = await launchCaptureBrowser(runtime.playwright.chromium, channel); }
  catch (error) {
    if (!install || error.code !== 'BROWSER_MISSING') throw error;
    await run(process.execPath, [runtime.cli, 'install', 'chromium'], runtime.directory, onProgress);
    launched = await launchCaptureBrowser(runtime.playwright.chromium);
  }
  await launched.browser.close();
  return { runtime, channel: launched.channel };
}

SHA-256: 9ec2138a32278123070759427759b391280b3f3c71d32111456f38071cb00fed