// IndexedDB-backed Repository — saves survive refresh (the offline-capable v1 store). Same // interface as MemoryRepository, so callers don't change; atproto slots in later the same way. // // No dependency: a thin promisified wrapper over IDB. The DB opens lazily on first use. Lineage // queries (children/ancestry) scan-and-filter for now — fine at hobby scale; a multiEntry index // on `parents` is the optimization if a store ever gets large. import type { Repository, StoredRecord } from "./Repository"; import type { OrganismRecord } from "./record"; const DB_NAME = "fluodditylike"; const STORE = "organisms"; const VERSION = 1; interface Row { id: string; record: OrganismRecord; } function idb(req: IDBRequest): Promise { return new Promise((resolve, reject) => { req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); } export class LocalRepository implements Repository { private dbPromise: Promise; constructor() { this.dbPromise = new Promise((resolve, reject) => { const open = indexedDB.open(DB_NAME, VERSION); open.onupgradeneeded = () => { const db = open.result; if (!db.objectStoreNames.contains(STORE)) db.createObjectStore(STORE, { keyPath: "id" }); }; open.onsuccess = () => resolve(open.result); open.onerror = () => reject(open.error); }); } private async objectStore(mode: IDBTransactionMode): Promise { const db = await this.dbPromise; return db.transaction(STORE, mode).objectStore(STORE); } async save(record: OrganismRecord): Promise { const id = `org-${crypto.randomUUID()}`; const store = await this.objectStore("readwrite"); await idb(store.put({ id, record } satisfies Row)); return id; } async get(id: string): Promise { const store = await this.objectStore("readonly"); const row = (await idb(store.get(id))) as Row | undefined; return row?.record; } async delete(id: string): Promise { const store = await this.objectStore("readwrite"); await idb(store.delete(id)); } async list(): Promise { const store = await this.objectStore("readonly"); const rows = (await idb(store.getAll())) as Row[]; return rows.map((r) => ({ id: r.id, record: r.record })); } async children(id: string): Promise { const all = await this.list(); return all.filter((r) => r.record.parents.includes(id)); } async ancestry(id: string): Promise { // BFS up the DAG; dedupe, nearest-first. const out: StoredRecord[] = []; const seen = new Set(); const root = await this.get(id); let frontier = root?.parents ?? []; while (frontier.length) { const next: string[] = []; for (const pid of frontier) { if (seen.has(pid)) continue; seen.add(pid); const record = await this.get(pid); if (!record) continue; out.push({ id: pid, record }); next.push(...record.parents); } frontier = next; } return out; } }