Something went wrong. Try again.
A Social Deduction / Deception Game
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364// Tiny SQLite-backed key/value stores under .data/ (node:sqlite, no deps).// tsx watch restarts the server on every edit, so in-memory login state would// be lost constantly during development — and lost on every deploy/restart in// production. SQLite (WAL) writes one row at a time and survives a crash// mid-write, so OAuth sessions (and the sid→DID cookie map) outlive the process.import { existsSync, mkdirSync, readFileSync, renameSync } from 'node:fs'import { join } from 'node:path'import { DatabaseSync } from 'node:sqlite'
export const DATA_DIR = join(process.cwd(), '.data')mkdirSync(DATA_DIR, { recursive: true })
const db = new DatabaseSync(join(DATA_DIR, 'store.db'))db.exec('PRAGMA journal_mode = WAL')db.exec(` CREATE TABLE IF NOT EXISTS kv ( store TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (store, key) ) WITHOUT ROWID`)
const getStmt = db.prepare('SELECT value FROM kv WHERE store = ? AND key = ?')const setStmt = db.prepare( 'INSERT INTO kv (store, key, value) VALUES (?, ?, ?) ON CONFLICT (store, key) DO UPDATE SET value = excluded.value',)const delStmt = db.prepare('DELETE FROM kv WHERE store = ? AND key = ?')
export class SqliteStore<V> { private readonly store: string
constructor(store: string) { this.store = store this.importLegacyJson() }
async get(key: string): Promise<V | undefined> { const row = getStmt.get(this.store, key) as { value: string } | undefined return row ? (JSON.parse(row.value) as V) : undefined }
async set(key: string, value: V): Promise<void> { setStmt.run(this.store, key, JSON.stringify(value)) }
async del(key: string): Promise<void> { delStmt.run(this.store, key) }
/** One-time import from the pre-SQLite per-store JSON file, then rename it * out of the way so it can't shadow rows deleted later. */ private importLegacyJson(): void { const path = join(DATA_DIR, `${this.store}.json`) if (!existsSync(path)) return const data = JSON.parse(readFileSync(path, 'utf8')) as Record<string, V> for (const [key, value] of Object.entries(data)) { setStmt.run(this.store, key, JSON.stringify(value)) } renameSync(path, `${path}.imported`) console.log(`store: imported ${Object.keys(data).length} entries from ${this.store}.json`) }}