/** * In-memory stand-in for the parts of the Supabase client the identity and * files steps use: auth events, profile select/update, profile_roles and * assets selects, rpc, storage upload / download. Tests mock * `@/lib/supabase` to hand this object out. */ import { vi } from 'vitest' import type { AssetRow, AuthChangeEvent, FaunosteoClient, Profile, Session, User, } from '@faunosteo/supabase' type Listener = (event: AuthChangeEvent, session: Session | null) => void type Row = Record export function fakeUser(patch: Partial = {}): User { return { id: 'user-1', aud: 'authenticated', email: 'alice@example.test', email_confirmed_at: '2026-10-11T10:00:00Z', created_at: '2026-10-01T10:00:00Z', app_metadata: {}, user_metadata: {}, ...patch, } as User } export function fakeSession(user: User = fakeUser()): Session { return { access_token: 'at', refresh_token: 'rt', token_type: 'bearer', expires_in: 3600, user, } as Session } export function fakeProfile(patch: Partial = {}): Profile { return { id: 'user-1', display_name: 'Alice Local', first_name: null, last_name: null, phone: null, phone_verified_at: null, locale: 'fr', timezone: 'Europe/Paris', active: true, practice_name: null, professional_title: null, siret: null, created_at: '2026-10-01T10:00:00Z', updated_at: '2026-10-01T10:00:00Z', ...patch, } } export function fakeAssetRow(patch: Partial = {}): AssetRow { return { id: 'asset-1', owner_id: 'user-1', kind: 'profile_avatar', bucket_id: 'avatars', object_key: 'profiles/user-1/asset-1/avatar.webp', status: 'clean', declared_mime: 'image/jpeg', declared_size: 1000, byte_size: 900, sha256: null, rejection_reason: null, created_at: '2026-10-13T10:00:00Z', updated_at: '2026-10-13T10:00:00Z', ...patch, } } /** Minimal PostgREST builder: filters, order, limit, then select / update, awaitable. */ function builder(tables: Record, table: string) { const filters: Array<(row: Row) => boolean> = [] let patch: Row | null = null let order: { col: string; ascending: boolean } | null = null let max: number | null = null const rows = () => { let hit = (tables[table] ?? []).filter((r) => filters.every((f) => f(r))) if (order) { const { col, ascending } = order hit = [...hit].sort((a, b) => (String(a[col]) < String(b[col]) ? -1 : String(a[col]) > String(b[col]) ? 1 : 0) * (ascending ? 1 : -1), ) } return max === null ? hit : hit.slice(0, max) } const apply = () => { if (!patch) return rows() const hit = rows() hit.forEach((r) => Object.assign(r, patch)) return hit } const api = { select: () => api, update: (values: Row) => { patch = values return api }, eq: (col: string, value: unknown) => { filters.push((r) => r[col] === value) return api }, is: (col: string, value: unknown) => { filters.push((r) => r[col] === value) return api }, in: (col: string, values: unknown[]) => { filters.push((r) => values.includes(r[col])) return api }, order: (col: string, opts?: { ascending?: boolean }) => { order = { col, ascending: opts?.ascending ?? true } return api }, limit: (n: number) => { max = n return api }, maybeSingle: async () => ({ data: apply()[0] ?? null, error: null }), single: async () => { const [first] = apply() return first ? { data: first, error: null } : { data: null, error: { message: 'no row', code: 'PGRST116' } } }, then: (resolve: (v: { data: Row[]; error: null }) => void) => resolve({ data: apply(), error: null }), } return api } export interface FakeSupabase { client: FaunosteoClient tables: Record emit: (event: AuthChangeEvent, session: Session | null) => void /** Recorded rpc calls; program results with `rpcResults[name]`. */ rpcCalls: Array<[string, unknown]> rpcResults: Record { data?: unknown; error?: unknown })> storage: { upload: ReturnType download: ReturnType } auth: { initialize: ReturnType signInWithPassword: ReturnType signUp: ReturnType signOut: ReturnType updateUser: ReturnType resetPasswordForEmail: ReturnType signInWithOAuth: ReturnType } } export function createFakeSupabase( tables: Record = { profiles: [fakeProfile()], profile_roles: [], assets: [] }, ): FakeSupabase { tables.assets ??= [] const listeners: Listener[] = [] const rpcCalls: Array<[string, unknown]> = [] const rpcResults: FakeSupabase['rpcResults'] = {} const storage = { upload: vi.fn(async () => ({ data: null, error: null })), download: vi.fn(async () => ({ data: new Blob([new Uint8Array([82, 73, 70, 70])]), error: null })), } const auth = { initialize: vi.fn(async () => ({ error: null })), onAuthStateChange: vi.fn((cb: Listener) => { listeners.push(cb) return { data: { subscription: { unsubscribe: vi.fn() } } } }), signInWithPassword: vi.fn(), signUp: vi.fn(), signOut: vi.fn(async () => ({ error: null })), updateUser: vi.fn(), resetPasswordForEmail: vi.fn(), signInWithOAuth: vi.fn(), } const client = { auth, from: (table: string) => builder(tables, table), rpc: async (name: string, args?: unknown) => { rpcCalls.push([name, args]) const entry = rpcResults[name] const result = typeof entry === 'function' ? entry() : (entry ?? {}) return { data: result.data ?? null, error: result.error ?? null } }, storage: { from: () => storage }, } as unknown as FaunosteoClient return { client, tables, auth, rpcCalls, rpcResults, storage, emit: (event, session) => listeners.forEach((cb) => cb(event, session)), } } /** Resolves once the store has run its deferred account load. */ export const flush = () => new Promise((r) => setTimeout(r, 0))