import { KoraEventEmitter, SchemaDefinition } from '@korajs/core'; import { S as StorageAdapter, V as VersionGate, T as Transaction, M as MigrationPlan, b as StorageOpenState, c as StorageEvidence } from '../types-BVVjCckP.cjs'; import { W as WorkerBridge } from '../sqlite-wasm-channel-8-TlaBEp.cjs'; import '@korajs/core/lite'; /** * Logical copy of every user table of a SQLite database. Used to move a * database between storage backends (OPFS <-> IndexedDB) explicitly, and as the * IndexedDB adapter's durable snapshot format. */ interface DatabaseDump { tables: Array<{ name: string; /** * The table's `CREATE TABLE` statement (from `sqlite_master`), so a restore can * recreate a table the target database does not have yet with its constraints. * Absent in dumps written before it was recorded. */ sql?: string; columns: string[]; rows: Array>; }>; } /** * Options for creating an IndexedDbAdapter. */ interface IndexedDbAdapterOptions { /** * Database name used as the IndexedDB key for persistence. * Defaults to 'kora-db'. */ dbName?: string; /** * Injected WorkerBridge for testing. If omitted, a WebWorkerBridge is created * in browser environments. */ bridge?: WorkerBridge; /** * URL to the sqlite-wasm-worker script. Required in browsers if no bridge is provided. */ workerUrl?: string | URL; /** Timeout for worker / follower RPC responses. Defaults to 30000ms. */ workerResponseTimeoutMs?: number; /** * Debounce interval (ms) before writing snapshots to IndexedDB. Defaults to 500. */ persistenceDebounceMs?: number; /** * When set, persistence failures and quota errors are emitted on this emitter. */ emitter?: KoraEventEmitter; /** * The version gate of this database (one build writes it at a time). In a browser * (worker path) the adapter creates one when omitted; `false` disables it. */ versionGate?: VersionGate | false; /** Build id for the version gate the adapter creates. */ build?: string; /** Open single-tab in a browser without Web Locks (test environments). */ allowUncoordinatedTabs?: boolean; /** * Broadcast channel on which this adapter, as the storage leader, answers followers' * durability-barrier requests. Browsers need not set it: the adapter serves on the * database's storage channel whenever its tab leads. Tests that give the adapter an * injected bridge set it on the adapter that stands for the leader tab. */ snapshotBarrierChannel?: string; /** * Keep storage-loss evidence (manifest epoch, \`localStorage\` marker) for this database. * On by default in browsers (a real worker); tests with an injected bridge opt in. */ storageEvidence?: boolean; } /** * IndexedDB-backed adapter that uses SQLite WASM in-memory and serializes * the entire database to IndexedDB after mutations (coalesced/debounced). * * This is the fallback adapter for browsers where OPFS is not available. * It provides the same SQL interface as SqliteWasmAdapter, but persists by * serializing the full SQLite database to a single IndexedDB blob. * * @example * ```typescript * const adapter = new IndexedDbAdapter({ workerUrl: '/sqlite-wasm-worker.js' }) * ``` */ declare class IndexedDbAdapter implements StorageAdapter { private inner; private readonly dbName; private readonly emitter; private readonly scheduler; private storageOpenState; /** What survived outside the database when it was opened (null: not tracked). */ private evidence; private readonly options; /** True in browsers (a real worker), where the backend choice is recorded. */ private readonly usesRealWorker; /** * This tab's writes not yet in a saved snapshot, per worker database (lineage): the * highest commit count among them and the lineage's epoch. A write is durable only once * a snapshot of the SAME worker database at that count or later is saved. */ private readonly unconfirmedWrites; /** * Worker databases this tab wrote to that were replaced (the storage leader changed) * before those writes were saved: the writes are gone. While one is listed, every * durability barrier of this tab rejects: each covers every write committed before it, * the lost ones included, so a retry never reports them saved. The list lives as long * as this adapter: a reload opens a new adapter (and the database in a new lineage), so * the loss is reported for this session and clears on reload. */ private readonly lostLineages; /** This adapter's id among the holders of lineage pins ({@link setSnapshotLineagePins}). */ private readonly pinHolder; /** The lineages last pinned for this adapter (sorted, joined): skips unchanged updates. */ private pinnedKey; /** * The lineage this tab last wrote in. It stays pinned after its writes are saved, so the * pin record is written once per lineage (once per leader change), not after every save. */ private currentLineage; /** Pin updates run one at a time, in order. */ private pinUpdate; /** The version gate of this database, or null where it does not apply. */ private readonly versionGate; /** Admits this adapter's writes until the tab retires (version gate, section 5). */ private readonly writes; /** Page lifecycle: suspended while frozen or in the back/forward cache. */ private lifecycle; private removeLifecycleListeners; /** Set once this tab retired: no snapshot of this build is ever written again. */ private retired; /** Set once {@link close} began: the tab stops answering followers' barriers. */ private closing; /** Stops answering followers' durability barriers (this tab leads), or null. */ private stopBarrierServer; constructor(options?: IndexedDbAdapterOptions); /** The version gate this adapter's tab declares (null where it does not apply). */ getVersionGate(): VersionGate | null; /** * Version gate, steps 3 and 4 for the IndexedDB fallback: refuse new writes, wait for * every started one, then make everything this tab committed durable. A failed barrier * keeps the gate closed: the tab keeps its tab lock and retries (backoff, the user's * Retry, `visibilitychange`) until a snapshot holds every committed write, reporting * `store:persistence-error` and `unsaved-writes`. `SNAPSHOT_SUPERSEDED` (this tab's * lineage was replaced; its lost writes already rejected) does not hold it. * * When no snapshot can be taken (storage full, or no storage worker left: the leader * this tab relayed to closed), the tab's writes are settled against the snapshot * IndexedDB holds, read without a worker: when another tab's save holds them all (or * they are known lost, already reported), retirement continues. */ private retireDurably; /** * A close while this tab retires: wait for every write it admitted, then make them durable * with the throwing barrier (not the close path's best-effort flush). Writes another tab's * stored snapshot already holds, or known lost (reported), do not hold the close. * * @throws The gate's `UNSAVED_WRITES` refusal when they cannot be saved */ private saveBeforeClose; /** * Settle this tab's unsaved writes against the snapshot version IndexedDB holds (and its * ancestors), read without a worker. True when none is left unsettled: each is in a * stored snapshot, or known lost (reported by `markLost`, as a refused save would). */ private settleAgainstStoredSnapshot; /** * The explicit recovery path while a failed barrier holds retirement (storage full): a * dump of the database as this tab's worker holds it, for the prompt's Export button. */ exportRecoveryDump(): Promise; /** * Page lifecycle (`freeze`, bfcache `pagehide`), as before the version gate: a frozen page * cannot finish a snapshot, so it never keeps other tabs waiting on its storage. The * storage roles are released at once (the snapshot scheduler already flushed when the * page was hidden); writes made after the last stored snapshot stay only in this tab's * worker database and are lost if another tab takes over (reported as * `SNAPSHOT_SUPERSEDED`). No write a stored snapshot confirmed is ever lost. * * The tab lock is released only when the storage roles were: a tab still opening, * promoting or closing keeps both, so a newer build never opens behind its worker. */ private suspendForLifecycle; private resumeFromLifecycle; private installLifecycleListeners; /** @internal Tests: the page lifecycle events this adapter handles. */ handleLifecycleEvent(event: 'freeze' | 'resume'): Promise; open(schema: SchemaDefinition): Promise; private openStorage; /** * Read the OPFS copy of this database through a short-lived SQLite WASM * adapter (as leader, or as a follower of a tab that has it open). Refuses * loudly when OPFS cannot be read, instead of starting an empty copy. */ private readOpfsCopy; close(): Promise; execute(sql: string, params?: unknown[]): Promise; private executeNow; query(sql: string, params?: unknown[]): Promise; transaction(fn: (tx: Transaction) => Promise): Promise; private transactionNow; migrate(from: number, to: number, migration: MigrationPlan): Promise; private migrateNow; getStorageOpenState(): StorageOpenState | null; getStorageEvidence(): StorageEvidence | null; /** * Force an immediate snapshot write to IndexedDB (skips debounce). * Useful before tab unload or in tests. */ flushPersistence(): Promise; /** Resolves once a persisted snapshot holds every write committed so far (forces none). */ whenPersisted(): Promise; /** * Durability barrier (RT-35): resolves once every write committed before the call is * in a snapshot persisted to IndexedDB, and rejects when the snapshot cannot be * written. Sync calls it before an operation leaves the device, so the server never * holds an operation this device could lose on reload. * * A write counts as persisted only when a snapshot of the worker database it was made * in is saved. When that database was replaced first (the storage leader changed and * the new leader restored an older snapshot), the write is gone and the barrier rejects * with a {@link PersistenceError} (`context.code` `SNAPSHOT_SUPERSEDED`, `context.lineages`) * instead of resolving on a snapshot of the new database. * * A lost write stays lost for the rest of this tab's session: every later barrier also * covers it and rejects the same way, so a retry never reports it saved (the snapshot is * still written first, so later writes keep being persisted). Sync then uploads in its * degraded mode (`localDurability: 'degraded'`, RT-49), so the server keeps a copy. A * reload opens the database in a new lineage with a new adapter: the loss is cleared * there, and sync starts durable again. */ ensureDurable(): Promise; /** After a committed transaction: remember it and schedule a snapshot, if it wrote. */ private recordCommit; /** * Pin the lineages this tab has unsaved writes in, so their ancestry entries survive any * number of leader changes until this tab settles them (see `MAX_ANCESTORS`), and the * lineage it writes in now (see `currentLineage`). A tab that dies leaves at most those * behind, and only the most recent holders' pins are kept. A failed * update is reported, not thrown: the write it follows is committed, and without the pin * a lineage beyond the recent ancestry is judged by its epoch, as before. */ private syncPins; /** Remember a write this tab committed, by the worker database and count it got. */ private recordWrite; /** * Settle this tab's unsaved writes against the snapshot IndexedDB now holds (`stored`, * and the worker databases it descends from, `ancestors`). A write is durable when the * stored snapshot, or the snapshot an ancestor was saved at before it was replaced, * holds its commit count. A write in a worker database that was replaced before a * snapshot holding it was saved is lost: no snapshot can hold it any more (later saves * of that database are refused). `refused` is the lineage whose save was just refused. */ private settleWrites; /** This tab's unsaved writes in `lineage` are gone; barriers report it until reload. */ private markLost; /** * Save a snapshot of the worker database. Every tab's adapter snapshots the same worker * database (a follower's export runs on the leader's worker), so two tabs' saves can * reach IndexedDB in either order. Each snapshot carries the version it was read at, * and the save is a compare-and-put that never lets an older snapshot replace a newer * one; a save the stored snapshot already covers succeeds without writing. */ private writeSnapshot; /** * Answer followers' durability barriers (this tab leads): one strict snapshot, shared * with every barrier waiting in this tab's scheduler. Returns the function that stops. */ private serveBarriers; private answerPeerBarrier; /** * Follower: have the leader tab save the strict snapshot that covers this tab's writes. * True once the leader's snapshot is stored (the writes are then settled against it). False * when this tab leads, or the leader cannot answer (killed, frozen, hung, closing, or this * tab was promoted meanwhile): the caller then snapshots through whichever worker serves * now. That is the barrier re-issued to the new leader: its database holds this tab's * writes only if a stored snapshot did, and the settlement reports them lost otherwise * (`SNAPSHOT_SUPERSEDED`), never durable. * * @throws {PersistenceError} When the leader's snapshot failed (storage full, broken * IndexedDB): the barrier rejects, the writes stay in memory and are not durable */ private snapshotThroughLeader; private handlePersistenceError; /** * Restore the persisted snapshot into the worker database unless one was restored * into it already (this adapter or another one sharing the worker). The binary * snapshot (Node / test workers that support export) is imported whole; the JSON dump * (browsers) is restored in one transaction. */ private restoreIfFresh; /** * In `tx`: restore the JSON dump when no snapshot was restored into this database, * starting its lineage first (or with the one `restoreIfFresh` started). */ private restoreDumpIfFresh; /** * A consistent snapshot: every table and the snapshot version are read inside one * transaction (STORE-7), so the version names exactly the counted writes the dump holds. */ private exportDump; } export { IndexedDbAdapter, type IndexedDbAdapterOptions };