/** * An in-memory stand-in for the Prisma client: every model the app uses, with the schema's * defaults and unique fields, and generic `where` matching (equality, in / notIn, gt / gte / lt / * lte, not, contains with mode insensitive, AND / OR). Enough to run the whole app in tests, * including oidc-provider's storage. */ import crypto from 'node:crypto'; type Row = Record; const DEFAULTS: Record Row> = { account: () => ({ givenName: null, familyName: null, emailVerified: false, phone: null, phoneVerified: false, passwordHash: null, role: 'member', status: 'active', twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: null, noticeVersionAccepted: 0, failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, }), recoveryCode: () => ({ usedAt: null }), pendingSignIn: () => ({ accountId: null, codeHash: null, codeSentAt: null, attempts: 0, amr: [], pendingTotpSecret: null, remember: false }), emailToken: () => ({ interactionUid: null, usedAt: null }), loginEvent: () => ({ accountId: null, clientId: null, ip: null, userAgent: null, detail: null }), privacyNotice: () => ({ publishedById: null }), auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }), productLink: () => ({ connectedById: null }), oidcPayload: () => ({ grantId: null, userCode: null, uid: null, accountId: null, expiresAt: null, consumedAt: null }), delivery: () => ({ status: 'pending', attempts: 0, lastError: null, reply: null, deliveredAt: null }), dataExport: () => ({ status: 'collecting', parts: {}, file: null, readyAt: null }), deletionRequest: () => ({ status: 'waiting_approval', approvedAt: null, approvedById: null, products: {}, completedAt: null }), }; const KEYS: Record = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version' }; const UNIQUE: Record = { account: ['email'], recoveryCode: ['codeHash'], emailToken: ['tokenHash'], delivery: ['callId'] }; const HAS_UPDATED_AT = new Set(['account', 'appSetting', 'productLink']); const v = (x: unknown) => (x instanceof Date ? x.getTime() : x); function matchValue(actual: unknown, cond: unknown): boolean { if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) { const c = cond as Record; const insensitive = c.mode === 'insensitive'; return Object.entries(c).every(([op, x]) => { switch (op) { case 'mode': return true; case 'equals': return v(actual) === v(x); case 'in': return (x as unknown[]).map(v).includes(v(actual)); case 'notIn': return !(x as unknown[]).map(v).includes(v(actual)); case 'gt': return actual != null && (v(actual) as number) > (v(x) as number); case 'gte': return actual != null && (v(actual) as number) >= (v(x) as number); case 'lt': return actual != null && (v(actual) as number) < (v(x) as number); case 'lte': return actual != null && (v(actual) as number) <= (v(x) as number); case 'not': return x === null ? actual != null : !matchValue(actual, x); case 'contains': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().includes(String(x).toLowerCase()) : actual.includes(String(x))); default: throw new Error(`memoryDb: no operator ${op}`); } }); } return v(actual) === v(cond); } export function matches(row: Row, where: Row = {}): boolean { return Object.entries(where ?? {}).every(([k, cond]) => { if (k === 'AND') return (cond as Row[]).every((w) => matches(row, w)); if (k === 'OR') return (cond as Row[]).some((w) => matches(row, w)); if (k === 'NOT') return !matches(row, cond as Row); return matchValue(row[k], cond); }); } const clone = (x: T): T => structuredClone(x); const pick = (row: Row, select?: Row) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row); function order(rows: Row[], orderBy?: Row | Row[]) { const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : []; return [...rows].sort((a, b) => { for (const o of list) { const [k, dir] = Object.entries(o)[0]!; const x = v(a[k]) as number; const y = v(b[k]) as number; const d = x < y ? -1 : x > y ? 1 : 0; if (d) return dir === 'desc' ? -d : d; } return 0; }); } function prismaError(code: string, message: string) { return Object.assign(new Error(message), { code }); } function model(name: string, tables: Map>) { const key = KEYS[name] ?? 'id'; const table = () => { if (!tables.has(name)) tables.set(name, new Map()); return tables.get(name)!; }; const findWhere = (where: Row) => { if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null; for (const u of UNIQUE[name] ?? []) if (where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null; return [...table().values()].find((r) => matches(r, where)) ?? null; }; const checkUnique = (row: Row, except?: unknown) => { for (const u of UNIQUE[name] ?? []) { if (row[u] == null) continue; if ([...table().values()].some((r) => r[key] !== except && r[u] === row[u])) throw prismaError('P2002', `Unique constraint failed on ${name}.${u}`); } }; const api = { findUnique: async ({ where, select }: { where: Row; select?: Row }) => { const r = findWhere(where); return r ? pick(clone(r), select) : null; }, findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; }, findFirst: async ({ where, orderBy }: { where?: Row; orderBy?: Row | Row[] } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? clone(r) : null; }, findMany: async ({ where, orderBy, take, skip, select }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row } = {}) => order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => pick(clone(r), select)), count: async ({ where }: { where?: Row } = {}) => [...table().values()].filter((x) => matches(x, where)).length, create: async ({ data }: { data: Row }) => { const now = new Date(); const row: Row = { ...(DEFAULTS[name]?.() ?? {}), ...(key === 'id' ? { id: crypto.randomUUID() } : {}), createdAt: now, ...(HAS_UPDATED_AT.has(name) ? { updatedAt: now } : {}), ...clone(data) }; if (table().has(row[key])) throw prismaError('P2002', `Unique constraint failed on ${name}.${key}`); checkUnique(row); table().set(row[key], row); return clone(row); }, update: async ({ where, data }: { where: Row; data: Row }) => { const r = findWhere(where); if (!r) throw prismaError('P2025', `Record to update not found (${name})`); const next = { ...r, ...clone(data), ...(HAS_UPDATED_AT.has(name) ? { updatedAt: new Date() } : {}) }; checkUnique(next, r[key]); table().set(r[key], next); return clone(next); }, updateMany: async ({ where, data }: { where?: Row; data: Row }) => { let count = 0; for (const [k, r] of table()) if (matches(r, where)) { table().set(k, { ...r, ...clone(data) }); count++; } return { count }; }, upsert: async ({ where, create, update }: { where: Row; create: Row; update: Row }) => { const r = findWhere(where); return r ? api.update({ where, data: update }) : api.create({ data: create }); }, delete: async ({ where }: { where: Row }) => { const r = findWhere(where); if (!r) throw prismaError('P2025', `Record to delete does not exist (${name})`); table().delete(r[key]); cascade(name, r[key]); return clone(r); }, deleteMany: async ({ where }: { where?: Row } = {}) => { let count = 0; for (const [k, r] of [...table()]) if (matches(r, where)) { table().delete(k); cascade(name, k); count++; } return { count }; }, }; const cascade = (from: string, id: unknown) => { if (from === 'productLink') for (const [k, r] of tables.get('delivery') ?? []) if (r.linkId === id) tables.get('delivery')!.delete(k); if (from === 'account') for (const t of ['recoveryCode', 'emailToken', 'loginEvent', 'noticeAcceptance', 'consentChange', 'dataExport', 'deletionRequest']) for (const [k, r] of tables.get(t) ?? []) if (r.accountId === id) tables.get(t)!.delete(k); }; return api; } export type MemoryDb = Record> & { tables: Map>; $queryRawUnsafe: () => Promise; $disconnect: () => Promise }; export function memoryDb(): MemoryDb { const tables = new Map>(); const models = new Map>(); return new Proxy({} as MemoryDb, { get(_t, prop: string) { if (prop === 'tables') return tables; if (prop === '$queryRawUnsafe') return async () => [{ ok: 1 }]; if (prop === '$disconnect') return async () => {}; if (prop === 'then') return undefined; if (!models.has(prop)) models.set(prop, model(prop, tables)); return models.get(prop); }, }); }