import { Database } from 'bun:sqlite' import { randomUUID } from 'node:crypto' import { existsSync, unlinkSync } from 'node:fs' import { tmpdir } from 'node:os' import { resolve } from 'node:path' import { afterAll } from 'bun:test' import { initDatabase, resetDbSingleton } from '../../db/sqlite' const _tempDbs: string[] = [] /** * Create a fresh database instance for testing. * Automatically cleans up temp files in afterAll. * * Note: even without this helper, tests/preload.ts (bunfig [test].preload) * redirects the getDb() *fallback* to a private per-process temp file, so a * test that forgets initDatabase can never touch the shared dev DB * (tmpdir()/rcs-dev.db) anymore. This helper remains best practice — it * gives each test file an explicit, cleaned-up path. */ export function freshDb(): Database { try { resetDbSingleton() } catch { // ignore cleanup errors } const path = resolve( tmpdir(), `rcs-test-${randomUUID().replace(/-/g, '').slice(0, 8)}.db`, ) const db = initDatabase(path) _tempDbs.push(path) return db } afterAll(() => { for (const path of _tempDbs) { for (const suffix of ['', '-wal', '-shm']) { try { if (existsSync(path + suffix)) { unlinkSync(path + suffix) } } catch { // ignore cleanup errors } } } _tempDbs.length = 0 })