import { spawnSync } from "node:child_process"; import { cp, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { linkFixtureNodeModules } from "../../../scripts/lib/fixture-node-modules.ts"; /** * Real production builds of an edited temp copy of the repository, in the * template's default configuration (`serviceWorker: null`). `edit` changes the * copy right before that build runs, and edits persist into later builds. The * working tree and its `dist` (served by the e2e preview server) are never * touched. Serve the result with `startBuildServer` from * `service-worker-builds.ts`. */ const repoRoot = path.resolve(import.meta.dirname, "../../.."); const skipped = new Set([ "node_modules", ".git", ".claude", ".generated", ".tmp", "dist", "artifacts", "graphify-out", ]); export type FixtureBuild = Readonly<{ name: Name; edit?: (root: string) => Promise; }>; export type FixtureBuilds = Readonly<{ root: string; dist: Readonly>; }>; /** Replaces the one occurrence of `search` in `file` of the copy. */ export async function editOnce( file: string, search: string, replacement: string, ): Promise { const source = await readFile(file, "utf8"); if (source.split(search).length !== 2) { throw new Error(`Expected exactly one "${search}" in ${file}.`); } await writeFile(file, source.replace(search, replacement)); } function run(cwd: string, script: string, buildId: string): void { const result = spawnSync("node", [script], { cwd, encoding: "utf8", env: { ...process.env, VITE_BUILD_ID: buildId, RELEASE_ID: buildId }, }); if (result.status !== 0) { throw new Error( `${script} failed for ${buildId}:\n${result.stdout}\n${result.stderr}`, ); } } export async function prepareFixtureBuilds( prefix: string, builds: readonly FixtureBuild[], ): Promise> { const root = await mkdtemp(path.join(tmpdir(), `${prefix}-`)); try { await cp(repoRoot, root, { recursive: true, filter: (source) => !skipped.has(path.relative(repoRoot, source).split(path.sep)[0]!), }); await linkFixtureNodeModules(root, repoRoot); const dist = {} as Record; for (const build of builds) { await build.edit?.(root); const buildId = `${prefix}-${build.name}`; run(root, "scripts/generate-product-feature-index.ts", buildId); run(root, "scripts/build-frontend.ts", buildId); dist[build.name] = path.join(root, `dist-${build.name}`); await rename(path.join(root, "dist"), dist[build.name]); } return { root, dist }; } catch (error) { await rm(root, { recursive: true, force: true }); throw error; } } export async function removeFixtureBuilds( builds: Readonly<{ root: string }> | undefined, ): Promise { if (builds) await rm(builds.root, { recursive: true, force: true }); }