import { cloneTemplateInto, workerDatabaseUri } from "./test-db";
/**
* Per-fork vitest setup, appended AFTER vitest.setup.ts in setupFiles. Gives
* every fork its own clone of the template database (`_w`),
* repoints DATABASE_URI at it, and caps the pg pool per Payload boot so N
* forks stay far below Postgres' max_connections.
*
* No-ops outside workers mode: with `TEST_DATABASE_URI` set the suite runs in
* legacy serial mode against the single override db (bisect hatch), and a
* missing VITEST_WORKER_ID means this is not a vitest worker process.
*
* NOTE: vitest imports setupFiles but never calls their default export, so
* the work happens in a top-level IIFE below. The vite-node SSR transform
* hoists top-level await into an async wrapper, so side effects MUST live
* inside the awaited function, not before it.
*
* The clone happens ONCE PER FORK, not per test file: setup files re-run
* before every file under isolate:true, but process.env survives those module
* resets, so the marker env var short-circuits repeats. Within a fork, files
* keep running sequentially against one database that started empty plus the
* seeded baseline, exactly mirroring the old cross-file semantics while two
* forks never share tables.
*/
const CLONED_MARKER_ENV = "PTF_WORKER_DB_CLONED";
async function attachWorkerDatabase(): Promise {
if (process.env.TEST_DATABASE_URI || !process.env.VITEST_WORKER_ID) return;
// vitest.setup.ts already repointed DATABASE_URI at the serial test db, so
// derive names from THAT (re-resolving would append `_test` twice).
const uri = workerDatabaseUri(process.env.VITEST_WORKER_ID, process.env.DATABASE_URI);
if (process.env[CLONED_MARKER_ENV] === uri) return;
await cloneTemplateInto(uri);
process.env[CLONED_MARKER_ENV] = uri;
process.env.DATABASE_URI = uri;
if (!process.env.TEST_PG_POOL_MAX) {
// Reads as pg PoolConfig.max in src/payload.config.ts (unset elsewhere).
process.env.TEST_PG_POOL_MAX = "3";
}
}
await attachWorkerDatabase();