// IndexedDB persistence (offline-first local working copy). import { openDB, type DBSchema, type IDBPDatabase } from 'idb'; import type { CanvasData } from '$lib/model/types'; export interface FileRecord { /** Repo-relative path, e.g. "school/math/lecture2.pdf" or "school/math" for a folder. */ path: string; kind: 'canvas' | 'folder'; updatedAt: number; /** Git blob sha of the version last pulled/pushed. */ remoteSha?: string; /** Local changes not yet pushed. */ dirty: boolean; /** Tombstone: deleted locally, deletion not yet pushed. */ deleted?: boolean; } export interface SearchRecord { path: string; pages: { id: string; text: string; origin?: string }[]; } interface Schema extends DBSchema { files: { key: string; value: FileRecord }; docs: { key: string; value: CanvasData }; sources: { key: string; value: Uint8Array }; search: { key: string; value: SearchRecord }; kv: { key: string; value: unknown }; } let dbp: Promise> | null = null; export function db() { dbp ??= openDB('papure', 1, { upgrade(d) { d.createObjectStore('files', { keyPath: 'path' }); d.createObjectStore('docs'); d.createObjectStore('sources'); d.createObjectStore('search', { keyPath: 'path' }); d.createObjectStore('kv'); } }); return dbp; } export async function kvGet(key: string): Promise { return (await (await db()).get('kv', key)) as T | undefined; } export async function kvSet(key: string, value: unknown) { await (await db()).put('kv', value, key); }