/** * A seed run that ends early must fail loudly. `payload run` starts the CLI with `void start()` and then * `await import(script)`: when a seed script's top-level `await getPayload()` (or a later await) is left with * nothing that keeps Node's event loop alive, Node simply exits — code 0, no output. In Coolify's Terminal * that looks exactly like a successful run. The guard turns it into exit 1 with the reason. * * Dependency-free on purpose: no Payload, no Node imports — safe to import first in any seed script. */ type ExitListener = () => void /** The bits of `process` the guard uses — injectable for tests. */ export type SeedExitProcess = { exit: (code: number) => void exitCode?: null | number | string off: (event: 'beforeExit', listener: ExitListener) => unknown on: (event: 'beforeExit', listener: ExitListener) => unknown } export type SeedExitGuardOptions = { /** Prefix of the message. Default '[seed]'. */ label?: string /** Where the message goes. Default stderr. */ log?: (line: string) => void /** Default the real `process`. */ process?: SeedExitProcess } export type SeedExitGuard = { /** Stops watching (the run decides its exit code itself). */ dispose: () => void /** The seed ended: `summary()` calls it. */ finished: () => void /** Payload is up: `createSeeder` calls it. */ initialized: () => void readonly state: 'finished' | 'initialized' | 'waiting' } let active: null | SeedExitGuard = null /** The guard of the current run, if the script started one (`createSeeder` and `summary()` report to it). */ export function activeSeedExitGuard(): null | SeedExitGuard { return active } /** * Call it first in a seed script, before `getPayload()`. Until `summary()` runs, an exit through an empty * event loop prints "[seed] ended before Payload initialized" (or "… before the seed finished") and exits 1. * A normal `process.exit(code)` — after the summary, on an error, or the guard's own refusal — is untouched. */ export function guardSeedExit(options: SeedExitGuardOptions = {}): SeedExitGuard { const proc: SeedExitProcess = options.process ?? process const label = options.label ?? '[seed]' const log = options.log ?? ((line: string) => {process.stderr.write(`${line}\n`)}) let state: SeedExitGuard['state'] = 'waiting' const onBeforeExit = () => { if (state === 'finished') {return} const when = state === 'waiting' ? 'before Payload initialized' : 'before the seed finished' log( `${label} ended ${when} — the run stopped early and nothing after that point was written. ` + 'Exit code 1. Run it again; if it repeats, check the database connection and the seed script.', ) proc.exitCode = 1 proc.exit(1) } const guard: SeedExitGuard = { dispose: () => { proc.off('beforeExit', onBeforeExit) if (active === guard) {active = null} }, finished: () => { state = 'finished' }, initialized: () => { if (state === 'waiting') {state = 'initialized'} }, get state() { return state }, } active?.dispose() proc.on('beforeExit', onBeforeExit) active = guard return guard }