import * as _korajs_core from '@korajs/core'; import { FoldState, Operation, SchemaDefinition, KoraEvent, KoraEventEmitter, VersionGateTabIdentity, HLCTimestamp, ApplyResult, OfflineCompletion, SecretKeyProvider, OperationTransform } from '@korajs/core'; import { KoraError } from '@korajs/core/lite'; /** Why a write was not predicted. Stable strings: they are reported to DevTools. */ type MissReason = 'secret-field' | 'richtext-field' | 'unsupported-field-kind' | 'atomic-op' | 'merge-strategy' | 'custom-resolver' | 'state-machine' | 'cascade-target' | 'no-base' | 'base-timeout' /** An array is written and the record's fold state could not be had (read refused or empty). */ | 'no-fold-state' /** An earlier unsettled write of the record carries no fold state to build the array write on. */ | 'array-chain' /** The fold state read does not describe the base record (a change landed between the two). */ | 'fold-state-stale' | 'no-change' | 'write-gate' | 'writes-refused' | 'pending-cap' | 'bytes-cap' | 'records-cap' | 'unsupported-write' | 'predictor-error' /** The write passed `{ durable: true }`: shown at commit, as with instant updates off. */ | 'durable-option' /** The circuit breaker opened for the collection after repeated divergences (I10). */ | 'collection-disabled'; /** The kind of a local write. */ type PredictedWriteKind = 'insert' | 'update' | 'delete'; /** What a write is predicted to do to one record. */ interface PredictedChange { readonly predicted: true; readonly kind: PredictedWriteKind; readonly collection: string; readonly recordId: string; /** * Read-shaped field values the write sets: every field of the record for an insert, * the written fields plus `updatedAt` for an update, null for a delete (a tombstone). */ readonly patch: Readonly> | null; /** * For an update: the values the patched fields (and `updatedAt`) had before the write, * from the same base the prediction used. Lets the patcher tell a row that enters a * query (it did not match before) from one that vanished (it did) without reading it. * Null for an insert and a delete. */ readonly previous?: Readonly> | null; /** * The record as it stands after the write (the full record for an insert and update). * For a delete: the record as it stood when it was tombstoned. */ readonly record: CollectionRecord; /** * The record's fold state after the write, when the prediction was made on a real fold * state (a fresh insert, or an update of an array). The next write of the record builds * on it while this one is unsettled. */ readonly foldState?: FoldState; /** * Predict the same write again from the values the transaction actually read as its * base (`operation.previousData`), for the commit-time check when the base moved. Not * stored in the registry. */ readonly replay?: (previous: Readonly>, priorState?: FoldState | null) => Prediction; } /** A write the predictor declined. */ interface PredictionMiss { readonly predicted: false; readonly reason: MissReason; } /** The predictor's answer. */ type Prediction = PredictedChange | PredictionMiss; /** One write's place in the order of the writes that read. */ interface WriteTurn { /** * Resolves when every earlier write that was still reading has started its storage * transaction. Null when there is none: the write proceeds synchronously. Await it * before reading. */ readonly wait: Promise | null; /** * The write is going to be asynchronous (it reads): writes called from now on wait for * it. Already held when `wait` is not null. */ hold(): void; /** The write has started its storage transaction, or was given up. Idempotent. */ release(): void; } /** Per-registry bookkeeping of the writes that are reading, by record key. */ declare class WriteOrder { private readonly tails; /** The turn of a write that waits for everything (a delete): every later write waits for it. */ private barrier; /** * Call synchronously when a local update, delete or transaction is called. * * @param keys - The records the write touches (`recordKey(collection, id)`) * @param options - `all`: also wait for every held turn (a delete, whose cascades reach * other records) */ enter(keys: readonly string[], options?: { all?: boolean; }): WriteTurn; /** Whether a write is reading right now (diagnostics and tests). */ get busy(): boolean; } /** Where an entry is in its life. */ type EntryState = /** Predicted; its transaction has not answered. */ 'pending' /** Its transaction did not answer in time (or the commit outcome is unknown): kept shown. */ | 'unknown' /** Its transaction committed; kept (settling) until subscriptions have re-read. */ | 'committed'; /** The outcome of a write, as reported in `store:write-settled`. */ type SettleOutcome = 'committed' | 'rolled-back' | 'unknown'; /** One pending write, as the registry hands it out. Never mutated in place. */ interface PendingEntry { readonly writeId: string; readonly kind: PredictedWriteKind; readonly collection: string; readonly recordId: string; /** See {@link PredictedChange.patch}. */ readonly patch: Readonly> | null; /** See {@link PredictedChange.previous}. */ readonly previous: Readonly> | null; /** * The record after this write (for a delete: the record as it was). Replaced by the * committed record once the transaction commits. */ readonly record: CollectionRecord; /** The write this one was derived from (an earlier pending write of the same record). */ readonly dependsOn: string | null; /** * Every write this one was derived from, nearest first (bounded): `dependsOn` and its own * ancestors. The chain survives the retirement of the links in between, so the commit * verification can tell that a write rests on one that has not reported (or was rolled back). */ readonly ancestors: readonly string[]; /** * The transaction this entry belongs to (stage S6a), or null for a single write. Members * of a group share their fate: they are registered, committed, marked unknown and rolled * back together, and a subscription applies all of them or none (design 5.9). */ readonly groupId: string | null; readonly state: EntryState; /** Epoch assigned at commit; null while the write is not committed. */ readonly retiredAt: number | null; /** Registry clock reading when the entry was added. */ readonly registeredAtMs: number; /** Registry clock reading at commit, or null. */ readonly retiredAtMs: number | null; /** Estimated size of the entry, in bytes. */ readonly bytes: number; /** Ids of the operations the write created; empty until it commits. */ readonly operationIds: readonly string[]; /** * Changes to the collection this registry did not make (a remote apply, a cross-tab * change, a write that was not predicted) seen when the entry was added. The settle * check only judges an entry when the count is unchanged: otherwise the database may * legitimately differ from the prediction. */ readonly foreignAtAdd: number; /** * The registry's foreign-change sequence when the entry was added (see * {@link PendingWrites.invalidate}). A remote apply or another tab's change to this * record after that point makes the entry's `record` older than the database, so it is no * longer a base for the next write of the record. */ readonly foreignSeqAtAdd: number; /** The collection's remote-apply activity when the entry was added (see {@link PendingWrites.foreignSince}). */ readonly foreignActivityAtAdd: number; /** * When the commit's answer was lost: the content-addressed id of the write's primary * operation, which decides whether it landed (M2). Null otherwise. */ readonly lookupOperationId: string | null; /** * The record's fold state after this write, when the prediction was made on one (a * fresh insert, an update of an array). The next array write of the record builds on it * while this entry is unsettled; absent for a write predicted from values alone. */ readonly foldState: FoldState | null; } /** * A change to the registry that can alter what a subscription displays (S3). Reported to * {@link PendingWrites.onChange} listeners synchronously, after the change is made. * * - `added`, `rolled-back`, `cleared`: the set of entries that apply changed. * - `committed`, `unknown`: the entry is still shown, nothing to recompute (reported so a * listener can track settling). */ interface RegistryChange { readonly kind: 'added' | 'committed' | 'rolled-back' | 'unknown' | 'cleared'; /** Collections whose entries changed. */ readonly collections: readonly string[]; } /** Listener for {@link RegistryChange}s. */ type RegistryListener = (change: RegistryChange) => void; /** What a `store:write-pending` describes: one write, or a transaction (an entry group). */ type WriteEventKind = PredictedWriteKind | 'transaction'; /** Events the registry reports (names match docs/design 9.4). */ type OverlayEvent = { readonly type: 'store:write-pending'; readonly writeId: string; readonly collection: string; /** Every collection of a transaction; absent for a single write. */ readonly collections?: readonly string[]; readonly recordIds: readonly string[]; readonly kind: WriteEventKind; readonly predicted: true; } | { readonly type: 'store:write-pending'; readonly writeId: string; readonly collection: string; readonly collections?: readonly string[]; readonly recordIds: readonly string[]; readonly kind: WriteEventKind; readonly predicted: false; readonly reason: MissReason; } | { readonly type: 'store:write-settled'; readonly writeId: string; readonly collection: string; readonly collections?: readonly string[]; readonly outcome: SettleOutcome; readonly operationIds?: readonly string[]; readonly pendingMs: number; } | { readonly type: 'store:overlay-diverged'; readonly writeId: string; readonly collection: string; readonly fields: readonly string[]; }; /** Registry limits (design section 11) and its clock. */ interface PendingWritesOptions { /** Pending (uncommitted) entries per tab. Default 256. */ readonly maxPendingWrites?: number; /** Estimated bytes of pending and settling entries. Default 8 MiB. */ readonly maxPendingBytes?: number; /** Records one write may touch. Default 100. */ readonly maxRecordsPerWrite?: number; /** How long a committed entry may wait for subscriptions to re-read. Default 2,000 ms. */ readonly settleMs?: number; /** How long an entry may stay pending before it becomes `unknown`. Default 60,000 ms. */ readonly pendingTtlMs?: number; /** Rows in the committed-row cache (LRU). Default 512. */ readonly rowCacheSize?: number; /** Milliseconds, monotonic. Default `performance.now`. Injected by tests. */ readonly now?: () => number; /** Receives {@link OverlayEvent}s. A throwing listener never affects the registry. */ readonly onEvent?: (event: OverlayEvent) => void; } /** Result of {@link PendingWrites.add}. */ type AddResult = { readonly ok: true; readonly entry: PendingEntry; } | { readonly ok: false; readonly reason: MissReason; }; /** One write of a transaction, for {@link PendingWrites.addGroup}. */ interface GroupChange { readonly change: PredictedChange; /** A pending write OUTSIDE the group this write was derived from, or null. */ readonly dependsOn: string | null; } /** Result of {@link PendingWrites.addGroup}. */ type AddGroupResult = { readonly ok: true; readonly groupId: string; readonly entries: readonly PendingEntry[]; } | { readonly ok: false; readonly reason: MissReason; }; /** What the registry knows of a record's current values (5.6). */ type BaseLookup = /** The newest pending or settling write, or the cache, holds the record. */ { readonly found: 'record'; readonly record: CollectionRecord; readonly source: 'pending' | 'cache'; } /** The newest pending or settling write deleted the record. */ | { readonly found: 'deleted'; } /** Nothing is known: the caller must read. */ | { readonly found: 'none'; }; /** What the registry knows of a record's fold state (S6b), for an array write. */ type FoldStateLookup = /** The newest unsettled write of the record carries its predicted fold state. */ { readonly found: 'state'; readonly state: FoldState; } /** * The newest unsettled write was predicted from values alone: the state after it is * not known, and the database does not hold it yet either. */ | { readonly found: 'unknown'; } /** No unsettled write: the caller reads the committed state. */ | { readonly found: 'none'; }; /** Committed facts of a write, reported by {@link PendingWrites.commit}. */ interface CommitInfo { /** The record as stored (`WriteResult.record`); absent for a no-op update. */ readonly record?: CollectionRecord; /** Ids of the operations the write created. */ readonly operationIds?: readonly string[]; /** * The update wrote nothing (its values were already the record's, as a write that moved * under it found). Nothing changed in the database, so no read will ever contain this * entry: it is dropped at commit instead of waiting to be settled, and the display is * the stored row, not the prediction (and its `updatedAt`). */ readonly unchanged?: boolean; } /** Result of {@link PendingWrites.sweep}. */ interface SweepResult { /** Entries that stayed pending past the TTL and are now `unknown`. */ readonly expired: readonly PendingEntry[]; /** Committed entries older than the settle window: the caller forces a re-read, then drops them. */ readonly lagging: readonly PendingEntry[]; } /** * Registry of the writes this tab has predicted but not yet seen settle. * * Lifecycle of an entry: {@link add} (`pending`) then either {@link commit} * (`committed`, kept until {@link settleCollection} or {@link drop}), {@link rollback} * (removed together with the entries derived from it), or {@link markUnknown} / the TTL * in {@link sweep} (`unknown`, kept shown until decided). */ /** Why a commit check judged fewer fields than the whole record. */ type UnverifiedReason = /** A remote apply in the collection overlapped the write. */ 'concurrent-remote' /** A write this one was derived from had not reported, or was rolled back. */ | 'unsettled-base' /** A field whose base moved could not be predicted again. */ | 'replay-declined'; /** Handle of a remote apply in progress, see {@link PendingWrites.beginForeign}. */ interface ForeignApply { /** The apply touches this collection from now until `end`. */ touch(collection: string): void; /** The apply has published its changes (or failed). */ end(): void; } declare class PendingWrites { private readonly options; private readonly now; private readonly onEvent; /** Insertion order is registration order. */ private readonly entries; private readonly cache; private writeCounter; private epochCounter; private totalBytes; private floorWallTime; /** Start order of the writes that have to read before they are predicted (S6b). */ readonly order: WriteOrder; private readonly missCounts; private readonly changeListeners; private readonly foreignCounts; /** Bumped by every {@link invalidate}; entries remember the value they were added at. */ private foreignSeq; /** Ids of writes that were rolled back, newest last: a retired write may still name one as its base. */ private readonly unverifiedCounts; private readonly rolledBackIds; /** Remote applies that have begun and not yet published their change, by collection. */ private readonly foreignInFlight; /** Begin and end events of remote applies, by collection. */ private readonly foreignActivity; /** Foreign sequence of the last change to a record / a whole collection, by key. */ private readonly recordMarks; private readonly collectionMarks; /** Marks dropped for size: an entry older than this is treated as changed. */ private markFloor; /** Commits of this registry's own writes, by collection (see {@link seedStamp}). */ private readonly commitCounts; /** Bumped by {@link clear}: a read issued before it must not seed anything. */ private generation; private seeded; /** Records with a running write that was not predicted, by cache key. */ private readonly unpredicted; /** Callers of {@link whenRecordSettled} waiting for a record's running writes to finish. */ private readonly settleWaiters; constructor(options?: PendingWritesOptions); /** Monotonic counter, bumped at every commit. A read's `issuedAt` is the epoch when it was issued. */ get epoch(): number; /** Writes shown but not yet committed (`pending` and `unknown`). */ get pendingCount(): number; /** Committed entries still waiting for subscriptions to re-read. */ get settlingCount(): number; /** Estimated bytes held by pending and settling entries. */ get bytes(): number; /** Rows in the committed-row cache. */ get cachedRows(): number; /** Rows put in the cache from subscription results over the registry's life (diagnostics). */ get seededRows(): number; /** Counted misses by reason (writes that were not predicted). */ get misses(): ReadonlyMap; /** The configured limits. */ get limits(): Readonly>>; /** * Highest `createdAt` or `updatedAt` this registry has seen committed. A predicted * wall time is `max(Date.now(), wallTimeFloor())`, so a predicted record sorts where * the committed one will land (5.3d) even when the device clock is behind its HLC. */ wallTimeFloor(): number; /** Allocate a write id. */ nextWriteId(): string; /** * Register a predicted write. * * Refused (never thrown) when a cap would be exceeded: the write then runs as it does * today and the miss is counted (I8). Nothing already registered is ever dropped to * make room. * * @param change - The predictor's answer for the write * @param options - `dependsOn`: the pending write this one was derived from; * `recordCount`: records the write touches (default 1); `writeId`: pre-allocated id */ add(change: PredictedChange, options?: { dependsOn?: string | null; recordCount?: number; writeId?: string; }): AddResult; /** * Register the entries of one multi-record write (`insertMany`) together or not at all: * a cap that the whole group would exceed refuses all of it (I8), so a group never * shows half of its records. One change notification covers the group. */ addMany(changes: readonly PredictedChange[]): { readonly ok: true; readonly entries: PendingEntry[]; } | { readonly ok: false; readonly reason: MissReason; }; /** * Register the writes of one transaction as ONE entry group (stage S6a), all of them or * none: the pending, byte and record caps are checked for the whole group before any * entry exists (T1), so a group is never partially registered. The entries keep the * transaction's write order (the order its storage transaction writes them in). One * `store:write-pending` (`kind: 'transaction'`, `writeId` the group id) and one change * notification cover the group, so a single patch pass shows all of it. * * @param changes - Every write of the transaction, in buffer order, each with the * pending write outside the group it was derived from */ addGroup(changes: readonly GroupChange[]): AddGroupResult; /** * Report a transaction that is not predicted (one counted miss for the whole group). * Allocates a write id for the event. */ noteGroupMiss(collections: readonly string[], recordIds: readonly string[], reason: MissReason): void; /** The members of a group still in the registry, in registration order. */ groupMembers(groupId: string): PendingEntry[]; /** * Report a write that was not predicted (a counted miss, with its reason), so * DevTools can show why. Allocates a write id for the event. */ noteMiss(kind: PredictedWriteKind, collection: string, recordIds: readonly string[], reason: MissReason): void; /** * The write's transaction committed. The entry gets `retiredAt = ++epoch` and stays * (its display must not flicker between commit and the SQL re-read, F3); the * committed record replaces the prediction as the base for later updates, and fills * the row cache. * * @returns The retired entry, or null when it was already removed */ commit(writeId: string, info?: CommitInfo): PendingEntry | null; /** * A transaction committed: every member of the group retires with ONE epoch value, so a * SQL read either contains the whole group or none of it (design 5.9). * Members are retired in registration order (the order the transaction wrote them), so * the committed-row cache ends with each record's last write. One * `store:write-settled committed` carries every operation id of the group. * * @param groupId - The group, from {@link addGroup} * @param infos - Committed facts per member write id; a member without one keeps its * prediction as its record (an outcome decided later by lookup) * @returns The retired members (empty when the group is gone or already committed) */ commitGroup(groupId: string, infos?: ReadonlyMap): PendingEntry[]; /** * The write failed (nothing was committed). The entry is removed together with every * entry derived from it, transitively and not yet committed (5.6): a dependent cannot * succeed, so it is not left showing until its own transaction fails. The caller * recomputes each affected display from its base (F10). * * @returns The removed entries, the rolled-back one first */ rollback(writeId: string): PendingEntry[]; /** * The outcome is not known (the commit answer was lost, or the transaction did not * settle): the entry stays shown and is decided later, never silently rolled back. */ markUnknown(writeId: string, lookupOperationId?: string | null): PendingEntry | null; /** * An entry already unknown (the sweep expired it before its commit answered) learns the * operation that witnesses it, so a later read can decide it ({@link resolveUnknown}). No * event: its outcome was already reported unknown. The whole group learns it. */ private learnWitness; /** {@link markUnknown} for a member: the whole group becomes unknown, with one event (T2, T7). */ private markGroupUnknown; /** * Apply the time limits: pending entries older than `pendingTtlMs` become `unknown`; * committed entries older than `settleMs` are reported as lagging (the caller forces a * re-run of their collections, then {@link drop}s them). */ sweep(): SweepResult; /** * Every subscription of `collection` has delivered a SQL result issued at or after * `issuedAt`: committed entries retired at or before it are contained in those * results and are dropped. * * @returns The dropped entries */ settleCollection(collection: string, issuedAt: number): PendingEntry[]; /** Remove committed entries (after a forced re-run). Unknown ids and uncommitted entries are ignored. */ drop(entries: readonly PendingEntry[]): void; /** * The entries that apply to a read of `collection` issued when the epoch was * `issuedAt`, in registration order (5.5): * `retiredAt === null || retiredAt > issuedAt`. A read issued before an entry's * commit may not contain it; one issued after contains it. */ applicable(collection: string, issuedAt: number): PendingEntry[]; /** Whether any committed entry of `collection` still waits for subscriptions to re-read. */ hasSettling(collection: string): boolean; /** Entries whose outcome is unknown, optionally of one collection, in registration order. */ unknownEntries(collection?: string): PendingEntry[]; /** * Committed entries of `collection` that a SQL read issued at epoch `to` contains but * one issued at epoch `from` did not (`from < retiredAt <= to`): the writes whose * prediction the settle check compares with the database. */ crossed(collection: string, from: number, to: number): PendingEntry[]; /** Changes to `collection` that were not this registry's own predicted writes (see {@link PendingEntry.foreignAtAdd}). */ foreignCount(collection: string): number; /** One entry by id. */ get(writeId: string): PendingEntry | undefined; /** All entries, in registration order. */ list(): PendingEntry[]; /** Collections that have at least one entry. */ collections(): Set; /** * What the registry knows of a record's current values, for predicting the next write * to it (5.6): the newest entry for the record (pending chains, and settling commits * the SQL has not yet been read back for), else the committed-row cache. */ baseFor(collection: string, id: string): BaseLookup; /** * What the registry knows of a record's fold state (S6b): the newest entry for the * record carries it (a pending chain, or a settling commit), or the state is unknown * (the newest pending entry was predicted from values alone), or nothing is registered * and the committed state has to be read. A committed entry that carries no state is * `none`: its commit is in the database, so a read issued now contains it. */ foldStateFor(collection: string, id: string): FoldStateLookup; /** * A write to existing records that is NOT predicted (a miss) is about to run. Until it * finishes, the registry cannot say what those records hold: their cached rows are * dropped, later writes read the record instead of deriving it from an older entry, * and the settle check skips the collection's pending entries (the record changes * without a prediction). * * @returns Release function; call it once the write has committed, failed or become unknown */ holdUnpredicted(collection: string, ids: readonly string[]): () => void; /** Whether a write the overlay did not predict is changing this record right now. */ isHeld(collection: string, id: string): boolean; /** * Settles once no write of this record is running: no pending entry and no unpredicted * write (`null` when none is running now). A base read waits for it: a read issued while * an earlier write of the record is still queued (or held in its transaction's write * buffer) sees the record without that write, and a prediction built on it shows the * record without it until the commit corrects the display. */ whenRecordSettled(collection: string, id: string): Promise | null; private isRunning; private wakeSettled; /** The newest not-committed entry for a record: what a new update would derive from. */ pendingFor(collection: string, id: string): PendingEntry | undefined; /** Put a row the store itself read into the cache. */ cacheRecord(collection: string, record: CollectionRecord): void; /** * A token for {@link seedFromRead}: take it before a read of `collection` is issued and * hand it back with the result. It is the sum of three counters that only grow: changes * to the collection that were not this registry's predicted writes (remote applies, * cross-tab changes, unpredicted local writes: {@link invalidate}, {@link holdUnpredicted}), * commits of this registry's own writes to it, and clears. Any of them between the read's * issue and its delivery changes the token, because any of them can make the result * older than what the registry already knows. */ seedStamp(collection: string): number; /** * Fill the committed-row cache from rows a subscription's SQL read delivered, so the * common update or delete (of a row the user is looking at) finds its base without a * read (S5 follow-up, design 5.6). * * A seeded row must never be staler than what the registry could have learned itself, so * the call does nothing unless `stamp` (taken when the read was issued) still equals * {@link seedStamp}: the result is then at least as new as every change the registry has * been told about. Within an accepted result it skips a record that already has a cached * row (the cache is kept exact by commits and invalidations, so it is never older than * the result), one with a pending or settling entry (the entry is the base) and one with * an unpredicted write in flight. Seeds are copies (a subscriber may hold or mutate the * delivered objects), stop at the cache size, and go in with the first rows of the * result most recently used. * * @param collection - The collection the query reads * @param rows - The SQL result, in the read shape, from a query without relations * @param stamp - {@link seedStamp} when the read was issued * @returns How many rows were added */ seedFromRead(collection: string, rows: readonly CollectionRecord[], stamp: number): number; /** * Forget cached rows of a collection (or one record). Called when a remote apply or a * cross-tab change names it: a cached row may then be stale (F21). */ invalidate(collection: string, ids?: readonly string[] | null): void; /** * A remote apply (or an inbound batch) is starting. Its rows can reach the database before * its post-commit {@link invalidate} runs, so a local write that commits in between reads a * record some unwritten field of which the prediction could not know. For the collections * the apply touches, between `touch` and `end`, and for any write that overlapped it, * verification is limited to the fields the write sets ({@link PendingWrites.foreignSince}). * Applies in other collections do not weaken the check. * * @param collection - The collection of a single operation; omit for a batch and `touch` * each collection as its operations are applied * @returns `touch` marks a collection as being applied (idempotent); call `end` once when * the apply has published (or failed) */ beginForeign(collection?: string): ForeignApply; private activityOf; private ancestorsOf; /** Whether a write was rolled back (recent ones only: the record is bounded). */ wasRolledBack(writeId: string): boolean; /** Whether a remote apply in the entry's collection overlapped it, or is in flight now. */ foreignSince(entry: PendingEntry): boolean; /** * Count a commit check that could not judge every field (the write overlapped a remote * apply, rested on an unsettled write, or could not be re-predicted). Not an error: the * fields the write sets are still judged. Lets a test or DevTools see how often the check * ran at reduced strength instead of the reduction being silent. */ noteUnverified(reason: UnverifiedReason): void; /** Reduced-strength commit checks by reason since the registry was created. */ get unverified(): ReadonlyMap; /** Keep the per-record marks bounded; a dropped mark makes older entries count as changed. */ private boundMarks; /** * Whether a foreign change (a remote apply, another tab) touched the entry's record after * the entry was added: its `record` is then older than the database on fields it did not * write, so it must not be the base of the next write. The next write reads the record. */ private isOutdated; /** * Drop everything (store close, user switch, restore, `reloadFromDisk`, full resync: * invariant I12). No events are emitted: the data the entries described is gone. * * @returns The entries that were dropped */ clear(): PendingEntry[]; /** * Listen to changes that can alter what a subscription displays (S3). The listener runs * synchronously inside the call that changed the registry (a write's `add`), so it must * only schedule work. A throwing listener never affects the registry. * * @returns An unsubscribe function */ onChange(listener: RegistryListener): () => void; /** * Whether `operationId` was created by a write this registry committed and still holds. * The subscription manager uses it to tell the post-commit publication of a predicted * local write (the cache already holds its committed row) from every other change * (which invalidates cached rows, F21). */ ownsOperation(operationId: string): boolean; /** * Compare a committed record with the prediction the entry carried (5.3e) and report * `store:overlay-diverged` on a difference outside `createdAt` and `updatedAt`. */ reportDivergence(entry: PendingEntry, fields: readonly string[]): void; private refuse; private remove; private recordCommitted; private putCache; private changed; private emit; } /** * Thrown on an insert into a collection with a field declared `t.string().stamp('userId')` * when Kora cannot fill it: the app does not know the signed-in user yet, or the insert * names another user. */ declare class StampedFieldError extends KoraError { constructor(message: string, code: 'STAMP_USER_UNKNOWN' | 'STAMP_MISMATCH', context: Record); } /** * Thrown when a record is not found by ID (findById, update, delete on missing record). */ declare class RecordNotFoundError extends KoraError { constructor(collection: string, recordId: string); } /** * Thrown inside `applyRemoteOperation` when the row's version state changed * between the caller's snapshot read and the guarded write (a concurrent local * mutation landed in the window). The transaction is rolled back with nothing * written; the caller re-reads fresh state, recomputes its merge, and retries. * This is the optimistic-concurrency guard that keeps merge-engine results * (richtext, add-wins arrays, constraint resolutions) from clobbering newer * local edits they never saw. */ declare class OptimisticLockError extends KoraError { constructor(collection: string, recordId: string); } /** * Thrown when a storage adapter operation fails. */ declare class AdapterError extends KoraError { constructor(message: string, context?: Record); } /** * Thrown when a write reaches a storage adapter that could not obtain durable * storage (it opened, or was promoted to leader, on a non-persistent in-memory * database). Kora refuses such writes instead of accepting data that would be * lost on reload. Reads still work. * * Fix: close other tabs or apps using the same origin's OPFS storage and reopen, * or opt in explicitly with `allowNonDurable: true` if in-memory storage is * acceptable for this app. */ declare class StorageDurabilityError extends KoraError { constructor(dbName: string, phase: 'open' | 'promotion', reason: string); } /** * A local write committed to the live database but its backend could not prove * that the commit reached durable storage before the write promise returned. * * The operation still exists in the open store and may already be queued for * sync. Callers must not retry it blindly: doing so can duplicate an application * action. Keep the app open, surface the failure, and let Kora retry persistence. */ declare class WriteNotDurableError extends KoraError { readonly operationIds: readonly string[]; readonly cause: unknown; constructor(operationIds: readonly string[], cause: unknown); /** The first operation, for the common single-record write case. */ get operationId(): string | null; } /** * Thrown when the store opens a database a NEWER build of the app already migrated: its * stored schema version is above this code's `schema.version` (RT-109). Running older * code against it would write operations of the old schema into the new one, or fail * part-way, so the store refuses before changing anything and emits `store:schema-ahead`. * * Fix: run the newer build (reload while online, or accept the app's update prompt). * Never lower `schema.version` in a deployed app. */ declare class SchemaVersionAheadError extends KoraError { readonly dbName: string; readonly storedVersion: number; readonly codeVersion: number; constructor(dbName: string, storedVersion: number, codeVersion: number); } /** * Thrown when an operation is attempted on a store that has not been opened. */ declare class StoreNotOpenError extends KoraError { constructor(); } /** * Thrown when the Web Worker fails to initialize (WASM load failure, OPFS unavailable, etc.). */ declare class WorkerInitError extends KoraError { constructor(message: string, context?: Record); } /** * Thrown when the Web Worker does not respond within the configured timeout. */ declare class WorkerTimeoutError extends KoraError { constructor(operation: string, timeoutMs: number); } /** * Thrown when a follower tab cannot reach a live leader tab over the multi-tab * broadcast channel (the leader tab was closed, crashed, or is unresponsive). * Distinct from {@link WorkerTimeoutError}: this fails fast on a confirmed-absent * leader instead of waiting out the full RPC timeout. */ declare class NoLeaderError extends KoraError { constructor(operation: string, message?: string, code?: string, context?: Record); } /** * Thrown to a follower tab's pending storage requests when the leader tab that * was answering stopped sending heartbeats (hung, frozen, or suspended). The * request may or may not have been applied: retry it with the same `requestId` * (in the error context). The same leader de-duplicates it; a leader that took * over since keeps no record of it, so a retried write may then apply twice. * Retriable. */ declare class LeaderUnresponsiveError extends NoLeaderError { constructor(operation: string, silentMs: number, requestId: string); } /** * Thrown to pending storage requests when their bridge was torn down, typically * because this tab was just promoted to leader or the leader handed over. * Retriable: the next attempt goes to the new leader. */ declare class BridgeTerminatedError extends KoraError { constructor(operation: string, reason: string); } /** Thrown when a storage request is cancelled through its `AbortSignal`. */ declare class RequestAbortedError extends KoraError { constructor(operation: string, requestId: string); } /** * Thrown when an explicit local-database management operation needs exclusive * access but the database is open in some tab or worker on this origin. */ declare class StorageInUseError extends KoraError { constructor(dbName: string); } /** Thrown when an explicitly named local database does not exist. */ declare class LocalDatabaseNotFoundError extends KoraError { constructor(dbName: string); } /** * Thrown by `deleteDatabase()` when the database still holds operations that * never reached the server. Sync first, or pass `{ force: true }` to discard them. */ declare class UnsyncedDataError extends KoraError { constructor(dbName: string); } /** * Thrown when a database's data lives in a storage backend this runtime cannot * read (for example it was written to OPFS, and OPFS is unavailable now). Kora * refuses to start an empty, disjoint copy rather than hide the existing data. */ declare class StorageBackendMismatchError extends KoraError { constructor(dbName: string, recorded: string, requested: string, reason: string); } /** * Thrown when IndexedDB persistence operations fail (serialize/deserialize). */ declare class PersistenceError extends KoraError { constructor(message: string, context?: Record); } /** * Thrown by a local write while the store's pinned node id (an auth device id) belongs * to another user than the one signed in (F9): a browser two users shared. The write * could only be stored under the owner's node and would later upload as the owner's. */ declare class NodeOwnedByAnotherUserError extends KoraError { constructor(nodeId: string, principal: string | null); } /** Builds named in a {@link BuildSupersededError}. */ interface BuildSupersededInfo { /** The build this tab runs. */ currentBuild: string; /** The build of the tab that superseded it. */ newerBuild: string; } /** * Thrown by a write started in a tab that a tab running a newer build of the app (or a * later-opened deployment) has superseded (version gate). Nothing of the write was * applied. The tab is retiring: it shows "A new version of this app is available. Reload * to continue." and only a reload, which loads the newer build, brings writes back. * Retriable after the reload. A local refusal: never a server rejection. * * Carries the collection and operation that were refused, never the data. */ declare class BuildSupersededError extends KoraError { readonly collection: string | undefined; readonly operation: string; readonly retriable = true; constructor(scope: { collection?: string; operation: string; }, info: BuildSupersededInfo); } /** * Thrown when the local database was opened by a build whose Kora storage format is newer * than this code's (version gate, section 3). Older code does not know the newer layout of * Kora's internal tables and keys, so the store refuses before writing anything and emits * `store:format-ahead`. Like a schema ahead, it never falls back to an empty database. * * Fix: run the newer build (reload while online). A release that bumps the format cannot * be rolled back by redeploying an earlier build. */ declare class StorageFormatAheadError extends KoraError { readonly dbName: string; readonly storedFormat: number; readonly codeFormat: number; constructor(dbName: string, storedFormat: number, codeFormat: number); } /** * Thrown when a browser has no Web Locks: without them Kora cannot keep two tabs from * keeping separate copies of the database and overwriting each other's writes, so storage * open is refused (version gate, section 4.1.1). Every browser Kora supports has Web * Locks; test environments (jsdom, happy-dom) set `store.allowUncoordinatedTabs: true`. */ declare class TabCoordinationUnavailableError extends KoraError { constructor(dbName: string); } /** * Thrown by a pending version gate open (or resume) when the gate was closed meanwhile * (the app or adapter closed while it waited for an older tab): storage does not open. */ declare class VersionGateClosedError extends KoraError { constructor(dbName: string); } /** Result of writing one local operation. */ interface WriteResult { /** The operation, or null when the write turned out to be a no-op. */ readonly operation: Operation | null; /** The record as stored after the write. */ readonly record: CollectionRecord; /** Operations created as side effects (referential cascades), in creation order. */ readonly sideEffects: Operation[]; /** * An update's record fold state as the merge read it, before the operation (record fold * only). The overlay re-predicts an array write from it when it checks the commit. */ readonly priorFoldState?: FoldState; } /** What a base-record read needs: the adapter to read through and the schema to shape the row. */ interface OverlayReadEnv { readonly adapter: StorageAdapter; readonly schema: SchemaDefinition; } /** What the entry points need from an installed overlay. */ interface WriteOverlay { readonly registry: PendingWrites; /** * True while the adapter refuses writes (the durability-lost state). Checked before a * write is registered, never after (F2). Default: writes are accepted. */ readonly writesRefused?: () => boolean; /** * Read a record by id (the read the store itself would make). Default: a `SELECT` on * the write's adapter. Tests pass a controllable one. */ readonly readRecord?: (ctx: OverlayReadEnv, collection: string, id: string) => Promise; /** * Read a record's stored fold state (an array write builds on it, S6b). Default: a * `SELECT` on the write's adapter. Resolves null when there is none or it cannot be * used. Tests pass a controllable one. */ readonly readFoldState?: (ctx: OverlayReadEnv, collection: string, id: string) => Promise; /** Wall clock for predicted timestamps; default `Date.now`. Injected by tests. */ readonly wallClock?: () => number; /** Longest base read, in ms; default {@link BASE_READ_TIMEOUT_MS}. */ readonly baseReadTimeoutMs?: number; /** * True while prediction is switched off for a collection (the circuit breaker, I10). * Checked before a write is registered; such a write runs as it does without the overlay. */ readonly isCollectionDisabled?: (collection: string) => boolean; /** * Called after a write was rolled back, with every entry the rollback removed (the * write's own and the ones derived from it) and the error that failed the write. */ readonly onRolledBack?: (entries: readonly PendingEntry[], error: unknown) => void; } /** * Follows one predicted write from registration to its outcome. The entry points call * {@link WriteTracker.committed} from `runLocalWrite`'s post-commit hook and * {@link WriteTracker.failed} when the write rejects. Neither can throw. */ interface WriteTracker { /** The transaction committed. */ committed(results: readonly WriteResult[]): void; /** * The write failed. A no-op once the write has committed (a later barrier failure is * not a rollback) or its outcome was left unknown (a commit that cannot be confirmed * is never silently rolled back, F11). */ failed(error?: unknown): void; /** * The commit's answer was lost and the lookup could not decide: the entries stay shown * as `unknown` until a later read decides (7). * * @param lookupOperationId - The content-addressed id that decides whether it landed */ unknown(lookupOperationId: string | null): void; } /** Hooks for tests and benchmarks. Internal: free to change. */ interface OverlayControllerInternals { /** Wall clock for predicted timestamps; default `Date.now`. */ readonly wallClock?: () => number; /** Reads a record for an update's base; default a `SELECT` on the store's adapter. */ readonly readRecord?: WriteOverlay['readRecord']; /** Reads a record's fold state for an array write's base; default a `SELECT`. */ readonly readFoldState?: WriteOverlay['readFoldState']; /** Longest base read, in ms. */ readonly baseReadTimeoutMs?: number; /** Monotonic milliseconds for the registry. Default `performance.now`. */ readonly now?: () => number; /** Settle window and pending TTL, in ms (registry options). */ readonly settleMs?: number; readonly pendingTtlMs?: number; readonly rowCacheSize?: number; /** Report a divergence loudly; default throws from a microtask in test builds only. */ readonly raise?: (error: Error) => void; /** Raise on divergence. Default: true when `NODE_ENV` is `test`. */ readonly strict?: boolean; /** Divergences before the breaker opens. Default {@link DIVERGENCE_LIMIT}. */ readonly divergenceLimit?: number; /** Schedule the expiry sweep. Default `setTimeout` (unref'd where the runtime has it). */ readonly schedule?: (callback: () => void, delayMs: number) => unknown; readonly cancel?: (handle: unknown) => void; } /** What the store gives its controller. */ interface OverlayControllerOptions { readonly options: InstantUpdatesOptions; readonly adapter: StorageAdapter; readonly emit: (event: KoraEvent) => void; /** True while the adapter refuses writes (the durability-lost state). */ readonly writesRefused: () => boolean; /** Re-run the live queries of a collection (after an unknown outcome was decided). */ readonly refresh: (collection: string) => void; readonly internals?: OverlayControllerInternals; } /** A rolled-back write, as `onRollback` listeners get it. */ interface RollbackInfo { readonly writeId: string; readonly collection: string; readonly recordIds: readonly string[]; readonly error: unknown; } /** The overlay of one store. */ declare class OverlayController { readonly registry: PendingWrites; readonly overlay: WriteOverlay; private readonly emit; private readonly adapter; private readonly refresh; private readonly strict; private readonly raise; private readonly divergenceLimit; private readonly divergences; private readonly disabled; private readonly reported; private readonly rollbackListeners; private readonly deciding; private readonly schedule; private readonly cancel; private sweepHandle; private sweepEveryMs; private stopped; private unsubscribeRegistry; constructor(config: OverlayControllerOptions); /** Writes shown but not yet committed (pending, or committed with an unknown outcome). */ get pending(): number; /** Whether prediction is switched off for a collection (the breaker is open). */ isDisabled(collection: string): boolean; /** Listen to rolled-back writes. Returns an unsubscribe function. */ onRollback(listener: (info: RollbackInfo) => void): () => void; /** * Forget every pending write (I12): the data they described is gone or no longer this * user's. Runs BEFORE the live queries re-run, so nothing pending is applied over the * new state. Nothing is emitted for the entries: they are not outcomes. */ clear(): void; /** Clear, and never schedule again (store close). */ dispose(): void; /** * Decide writes whose commit answer was lost (M2) with a lookup, now that a SQL read of * their collection succeeded: the adapter is answering again. Found: committed. Not * found: rolled back. Still unreadable: they stay shown. Never throws. * * @param collection - Only entries of this collection; all when omitted */ resolveUnknown(collection?: string): Promise; private onRolledBack; /** Public events, one for one with the registry's (names and fields match section 9.4). */ private onRegistryEvent; /** A prediction the database contradicted: report it, count it, maybe open the breaker (I10). */ private onDiverged; private armSweep; private cancelSweep; /** Expire pending entries past their TTL into `unknown`; keep sweeping while any are pending. */ sweep(): void; /** Rows of the committed-row cache, for diagnostics. */ get cachedRows(): number; } /** * Kora-owned manifest of the local databases this origin created (W8a). * * One record per database name, kept in its own IndexedDB database so it is * readable from any tab without opening the OPFS pools. It records which backend * holds the database's data, which is how Kora keeps OPFS and IndexedDB from * ever holding two disjoint copies: a backend switch is a recorded, explicit * migration, never a silent fresh start (NEW-STORE-5, LMS-5c). * * The manifest is advisory for listing and authoritative for the backend * choice. Nothing is ever evicted automatically; deletion is the explicit * `deleteDatabase()` API. */ /** Where a database's data lives. */ type LocalDatabaseBackend = 'opfs' | 'indexeddb'; /** One manifest entry, as returned by `listDatabases()`. */ interface LocalDatabaseRecord { /** The store name (`store.name`, plus the per-user suffix if namespaced). */ dbName: string; /** The backend that holds the authoritative copy. */ backend: LocalDatabaseBackend; /** OPFS pool holding the file (opfs backend only). */ poolName?: string; /** Wall-clock milliseconds; informational only, never used for ordering. */ createdAt: number; /** Wall-clock milliseconds of the last durable open; informational only. */ lastOpenedAt: number; /** * Random id of this database's life (also `_kora_meta.db_epoch`), written once the * first durable open completed. A record without one may belong to a database whose * creation never finished, so it is weak evidence of eviction (see storage-evidence). */ epoch?: string; /** Unsynced writes at `unsyncedAt` (offline-readiness: what a vanished database lost). */ unsynced?: number; /** Wall-clock milliseconds `unsynced` was recorded; informational only. */ unsyncedAt?: number; /** True when no write followed the recording of `unsynced` (it is exact, not stale). */ unsyncedExact?: boolean; } /** * Evidence that a database existed on this device, kept OUTSIDE the database (A1 of the * offline-readiness design, section 6). * * A database whose OPFS pool or IndexedDB copy vanished reopens empty, and an empty * database looks exactly like a first visit. Two independent records tell the two apart: * * 1. the storage manifest (IndexedDB `kora-manifest`), extended with the database's * `epoch` and its last known unsynced-write count; * 2. `localStorage['kora:db:']`, which survives the loss of the IndexedDB copy the * manifest shares a backend with, and carries the backend itself. * * Both are written only after a database finished its first durable open, so a crash * during creation never leaves evidence of a database that never existed. */ /** The `localStorage` marker of a database. */ interface StorageMarker { v: 1; epoch: string; backend: LocalDatabaseBackend; } /** What survived outside the database at the time it was opened. */ interface FoundStorageEvidence { manifest: LocalDatabaseRecord | null; marker: StorageMarker | null; } /** * A database that existed and vanished (`store:storage-evicted`, `storage.evicted`). */ interface StorageEviction { dbName: string; /** Wall-clock milliseconds the loss was detected. */ detectedAt: number; /** Wall-clock milliseconds of the vanished database's last durable open, when known. */ lastOpenedAt: number | null; /** Which independent records named the vanished database. */ evidence: Array<'manifest' | 'localStorage'>; /** * Unsynced writes the vanished database held when it was last recorded. `certain` is * true when no write followed that recording; otherwise the count may be too low. */ lostWrites: { count: number; certain: boolean; }; } /** * Evidence kept for one open database: what was found at open, and the writers that keep * the records current. Adapters that persist durably create one per open. */ declare class StorageEvidence { readonly dbName: string; readonly backend: LocalDatabaseBackend; private readonly found; constructor(options: { dbName: string; backend: LocalDatabaseBackend; found: FoundStorageEvidence; }); /** * The eviction these records prove, or null. Only meaningful for a database that was * just created (the caller checks); a record for ANOTHER backend is never evidence (the * explicit IndexedDB/OPFS migration or `StorageBackendMismatchError` governs that case, * and this holds with the `localStorage` marker alone). */ detectEviction(now?: number): StorageEviction | null; /** * Record the database's epoch after its first durable open completed. `fresh` marks a * database that was just created (including after an eviction): its unsynced count * restarts at zero, exactly. */ recordEpoch(epoch: string, fresh: boolean): Promise; /** * Record how many writes only this device holds. Written when the count crosses zero * and when the page is hidden, so it is cheap and at worst stale (`exact` false). */ recordUnsynced(count: number, exact: boolean): Promise; } /** * Version gate: one build of the app writes a database at a time * (`docs/design/version-gate.md`). * * Every tab of an origin that opens a database declares an identity * `{ build, format, openSeq, tabId }` and holds an exclusive Web Lock named after it (its * tab lock) for its life. The set of held tab locks is the roster: `navigator.locks.query()` * lists every tab, including silent followers and tabs that have not processed any message. * * - The ordering key is `(format, openSeq)`: a newer storage format always wins, and within * a format the later-opened tab wins (a deployment, or the rollback of one). `openSeq` * comes from an IndexedDB counter ({@link allocateOpenSeq}), never from the clock. * - A tab RETIRES as soon as it learns of a tab of a different build with a higher key: * it refuses new writes, drains the writes it started, makes them durable, stops sync, * gives up its storage roles, and releases its tab lock. Retirement's steps are * registered by the layers that own them ({@link VersionGate.addRetireStep}). * - A tab's write gate OPENS (its storage opens) only when no tab of another build with a * lower key holds a tab lock: it waits for each one's release, with no deadline. * * Runtimes without a window (Node, native adapters) do not apply the gate: one process * owns the database file. A browser without `BroadcastChannel` gets an exclusive single * tab; a browser without Web Locks refuses to open unless `allowUncoordinatedTabs` is set. */ /** The identity a tab declares to the gate. */ type TabIdentity = VersionGateTabIdentity; /** * Compare two tabs' ordering keys `(format, openSeq)`: positive when `a` wins. `openSeq` is * unique per database, so ties do not occur; `tabId` decides one deterministically anyway. */ declare function compareTabKeys(a: TabIdentity, b: TabIdentity): number; /** The tab lock name of `identity`: the prefix followed by the identity as JSON. */ declare function tabLockName(dbName: string, identity: TabIdentity): string; /** The identity in a tab lock name of `dbName`, or null for any other lock. */ declare function parseTabLockName(dbName: string, name: string): TabIdentity | null; /** * A build id derived from the storage format and the schema (collections, fields, version), * used only when the app supplies none (version gate, section 3): it still tells apart two * deployments whose schemas differ. Never the `korajs` package version. */ declare function schemaFingerprint(schema: SchemaDefinition, format?: number): string; /** The part of a Web Lock the gate uses. */ interface GateLock { name: string; } /** Options of a Web Locks request, as the gate uses them. */ interface GateLockRequestOptions { mode?: 'exclusive' | 'shared'; ifAvailable?: boolean; signal?: AbortSignal; } /** The part of `navigator.locks` the gate uses (injected in tests). */ interface GateLockManager { request(name: string, options: GateLockRequestOptions, callback: (lock: GateLock | null) => unknown): Promise; query(): Promise<{ held?: ReadonlyArray<{ name?: string; }>; }>; } /** The part of a `BroadcastChannel` the gate uses (injected in tests). */ interface GateChannel { postMessage(message: unknown): void; addEventListener(type: 'message', listener: (event: { data: unknown; }) => void): void; removeEventListener(type: 'message', listener: (event: { data: unknown; }) => void): void; close(): void; } /** What the runtime offers the gate. Detected from globals unless injected. */ interface VersionGateRuntime { /** A browser page (a `window` and a `document`): the gate applies. */ browser: boolean; locks: GateLockManager | null; createChannel: ((name: string) => GateChannel) | null; /** * The page is not a secure context (plain HTTP on a non-localhost origin), where browsers * expose no Web Locks: the gate does not apply there (section 4.1.1). */ insecureContext?: boolean; } /** How the gate coordinates in this runtime (section 4.1.1). */ type VersionGateMode = /** Not a browser: one process owns the database; nothing to coordinate. */ 'off' /** Web Locks and `BroadcastChannel`: the full protocol. */ | 'full' /** Web Locks, no `BroadcastChannel`: one tab at a time. */ | 'exclusive' /** No Web Locks in a secure context (an old browser): refused, unless allowed. */ | 'unavailable' /** * Not a secure context (plain HTTP, not localhost): browsers expose no Web Locks there. * The gate does not apply (as before it), with one console warning. */ | 'insecure-context' /** No Web Locks, `allowUncoordinatedTabs`: single-tab as before the gate. */ | 'uncoordinated'; /** Lifecycle of a gate. */ type VersionGateState = 'idle' | 'opening' | 'waiting' | 'open' | 'suspended' | 'retiring' | 'retired' | 'closed'; /** Phases of retirement, run in this order (section 5, steps 3 to 6). */ type RetirePhase = 'drain' | 'durability' | 'sync' | 'roles'; /** Passed to supersede listeners and retirement steps. */ interface SupersededInfo { /** This tab. */ current: TabIdentity; /** The tab of a different build whose key is higher. */ newer: TabIdentity; } /** A change listeners of {@link VersionGate.onChange} hear about. */ interface VersionGateSnapshot { state: VersionGateState; identity: TabIdentity | null; /** Set once this tab is superseded. */ newer: TabIdentity | null; /** This tab's retirement is held because its latest writes are not saved yet. */ unsaved: boolean; /** While waiting: the tabs this one waits for, and why. */ waiting: { waitingFor: TabIdentity[]; reason: 'live-writer' | 'unsaved-writes' | 'legacy-build'; } | null; } /** Options of {@link VersionGate}. */ interface VersionGateOptions { /** The Kora database name the gate guards. */ dbName: string; /** * The app's build id (`createApp({ build })`, or injected by the `@korajs/cli/vite` * plugins). When absent, the adapter derives one from the schema before opening * ({@link VersionGate.useSchemaFingerprint}) and `store:build-unidentified` is reported. */ build?: string; /** Kora storage format of this code. Defaults to `KORA_STORAGE_FORMAT`. */ format?: number; emitter?: KoraEventEmitter; /** Open single-tab in a browser without Web Locks (test environments). */ allowUncoordinatedTabs?: boolean; /** @internal Test seam: the runtime's coordination APIs. */ runtime?: Partial; /** @internal Test seam: the open-order counter. */ allocateOpenSeq?: (dbName: string) => Promise; /** Interval of re-sent hellos while waiting. Default 1000 ms. */ heartbeatMs?: number; /** Waiting time before `store:build-gate-waiting` is reported. Default 10 s. */ waitingReportMs?: number; /** Backoff of a failed durability barrier's retries. Default 1 s doubling to 30 s. */ retryBackoffMs?: { initial: number; max: number; }; /** @internal Test seam: this tab's random id. */ tabId?: string; } /** * The version gate of one database in one tab. See the module documentation. * * @example * ```typescript * const gate = new VersionGate({ dbName: 'my-app', build: import.meta.env.VITE_COMMIT_SHA }) * gate.onSuperseded(({ newer }) => showReloadBanner(newer.build)) * await gate.open() // resolves once no tab of another build writes this database * ``` */ declare class VersionGate { readonly dbName: string; readonly format: number; private build; private buildUnidentified; private readonly emitter; private readonly runtime; private readonly allocate; private readonly heartbeatMs; private readonly waitingReportMs; private readonly retryBackoff; private readonly tabId; private readonly allowUncoordinatedTabs; private currentMode; private state; private identity; private openedAt; private openPromise; private tabLock; private exclusiveLock; private channel; private readonly onMessage; private newer; private retirement; private retiredSignal; private readonly retiredPromise; private supersededSignal; private readonly supersededPromise; private readonly supersededListeners; private readonly changeListeners; private readonly steps; private unsaved; private unsavedMarker; /** Unsaved marker locks seen at the last discovery. */ private unsavedHeld; /** Identity-named gated-leader markers found by the last discovery (other tabs only). */ private heldLeaders; /** Their lock names, by tab id, exactly as held (waited on by name). */ private heldLeaderLockNames; private readonly unsavedPeers; private waiting; private waitingReported; private waitingTimers; private readonly waitAborts; private legacyReported; private retryWake; private recoveryExporter; private closeCheck; /** Aborts lock requests still queued when the gate closes. */ private readonly closeAbort; constructor(options: VersionGateOptions); /** How the gate coordinates in this runtime. */ get mode(): VersionGateMode; /** Whether tabs are coordinated at all (`full` or `exclusive`). */ isCoordinating(): boolean; /** This tab's identity, once the gate allocated its `openSeq`. */ getIdentity(): TabIdentity | null; /** The build this gate declares (null until set). */ getBuild(): string | null; /** DevTools: identity, open time (display only) and state. */ getInfo(): { identity: TabIdentity | null; openedAt: number | null; state: VersionGateState; }; getState(): VersionGateState; /** * The refusal of a close while this tab retires with writes no stored snapshot holds (its * durability barrier is failing), or null. Closing then would release the tab lock and * let the newer build open without them, so `Store.close`, the IndexedDB adapter and * `app.close()` check it first and throw it (surfaced, never silent); the prompt's Retry * and Export keep working. */ unsavedCloseError(): PersistenceError | null; /** The `UNSAVED_WRITES` refusal of a close (see {@link assertClosable}). */ closeRefusal(cause?: unknown): PersistenceError; /** * Set by the adapter that owns durability (the IndexedDB fallback): from the moment this * tab retires until it retired, a close first runs this check, which saves every committed * write and throws {@link closeRefusal} when that fails. */ setCloseCheck(check: (() => Promise) | null): void; /** * Before a close tears anything down: while this tab retires (from the moment retirement * starts, not only after a failed save), make every committed write durable or refuse with * `UNSAVED_WRITES`. Closing would release the tab lock and let the newer build open * without them. A no-op when not retiring. */ assertClosable(): Promise; /** True once this tab is superseded (retiring or retired). */ isSuperseded(): boolean; /** The builds of a supersession, for {@link BuildSupersededError}. */ supersededInfo(): BuildSupersededInfo | null; /** * Use a fingerprint of the storage format and the schema as the build, when the app gave * none. Reported as `store:build-unidentified` at open. */ useSchemaFingerprint(schema: SchemaDefinition): void; /** * Called synchronously when this tab is superseded, before any write is refused * (section 5, steps 1 and 2). Listeners close their write gates and show the prompt. */ onSuperseded(listener: (info: SupersededInfo) => void): () => void; /** Listen to state changes (prompts: waiting, unsaved writes, retired). */ onChange(listener: (snapshot: VersionGateSnapshot) => void): () => void; /** Current state, as {@link onChange} reports it. */ snapshot(): VersionGateSnapshot; /** * Register a retirement step. Steps run once, in phase order (`drain`, `durability`, * `sync`, `roles`), each awaited; then the tab posts `kora-build-retired` and releases * its tab lock, which opens the newer tab's gate. */ addRetireStep(phase: RetirePhase, step: (info: SupersededInfo) => Promise): () => void; /** * Open the write gate: allocate `openSeq`, take the tab lock, discover the other tabs and * wait until no tab of another build with a lower key holds its lock. Resolves when this * tab may open storage. Rejects with {@link BuildSupersededError} when a tab of another * build with a higher key exists (this tab retires instead), and with * {@link TabCoordinationUnavailableError} in a browser without Web Locks. */ open(): Promise; private doOpen; /** * A gate closed while it opened or resumed never reaches `open`: its tab lock and channel * are gone, so storage must not open behind it. */ private throwIfClosed; /** * After every await of an open or a resume, before any state change: closed * ({@link VersionGateClosedError}) or superseded ({@link BuildSupersededError}) stops it. */ private throwIfStopped; /** * Called by a tab granted the storage leader lock (first open or promotion) before it * opens a worker (rule 4). False when a tab of another build with a higher key is listed * (this tab retires) or this tab is already retiring: the caller releases the leader lock * unopened. */ mayLead(): Promise; /** * Page lifecycle (`freeze`, bfcache `pagehide`): release the tab lock. The caller has * already made every committed write durable and released the storage leader lock (the * lifecycle rule of section 4.1). No-op unless the gate is open. */ suspend(): void; /** * Page lifecycle (`resume`, `pageshow`): re-acquire the tab lock and run discovery before * anything else (rule 5). False when this tab must not use storage again: it is retired, * retiring, or a newer build appeared meanwhile (it retires now). */ resume(): Promise; /** * {@link resume}, retried with backoff (or the user's Retry, `visibilitychange`) while it * fails for another reason than supersession or closure (a lock query rejected). Between * attempts the gate is suspended and holds no lock, so no tab waits on a tab without a * storage worker. False once this tab must not use storage (superseded, closed). */ resumeWithRetry(): Promise; /** * Report whether this retiring tab's durability barrier is failing, so waiting tabs can * name it (`unsaved-writes`) and this tab's prompt can offer Retry and Export. */ reportUnsavedWrites(unsaved: boolean): void; /** * Wait before the next durability retry: the backoff for `attempt`, or until * {@link retryNow} (the user's Retry, `visibilitychange`), whichever is first. */ waitForRetry(attempt: number): Promise; /** Retry a failed durability barrier now (the prompt's Retry button). */ retryNow(): void; /** Set by the IndexedDB adapter: a download of the in-memory database (Export button). */ setRecoveryExporter(exporter: (() => Promise) | null): void; /** * The explicit recovery path while a failed barrier holds retirement: the in-memory * database as a dump. Null when no adapter offers one (OPFS: committed is durable). */ exportRecoveryDump(): Promise; /** Resolves once this tab has retired (its tab lock released). */ whenRetired(): Promise; /** * Leader, retiring: wait until every other tab that is itself superseded (a tab of a * different build with a higher key is present) has released its tab lock, so their * retirement, which may still need this worker to finish a write or save a snapshot, * completes before the worker stops. Tabs that will not retire (the winning build's) * are never waited for, so this cannot wait on the tab that waits for this one. */ waitForPeersToRetire(): Promise; /** * While this tab holds writes not yet in a stored snapshot (a failed barrier while it * retires), it holds an unsaved marker lock and tells the channel. The lock is * what a tab that opens later finds (`query()`): it may never see the message. */ private updateUnsavedMarker; /** Normal close: release the locks and leave the channel. A pending open fails. */ close(): void; private supersedes; /** * Wait until no tab of another build with a lower key holds its tab lock (rule 2), or * throw {@link BuildSupersededError} when one with a higher key exists (rule 1). */ private settle; /** * A pre-gate build is the storage leader when the leader lock is held without the gated * leader marker (every gated leader takes {@link gatedLeaderLockName} right after it is * granted the leader lock, and releases it after the leader lock). The marker is checked * twice, one heartbeat apart, so a gated leader between its two grants is not mistaken * for a pre-gate one. */ private legacyLeaderPresent; private waitingReason; private discover; private handleMessage; /** Rule 1: retire as soon as a tab of another build with a higher key is known. */ private consider; /** Section 5: announce, refuse writes, then run the registered steps in phase order. */ private retire; private runRetirement; private throwIfSuperseded; private refreshWaitingReason; private startWaitingTimers; private stopWaitingTimers; private reportWaiting; private reportUnidentified; private reportLegacy; private postHello; private post; private startChannel; private stopChannel; /** Request an exclusive lock and hold it until released. */ private acquire; /** Exclusive single tab (no `BroadcastChannel`): hold `kora-db:` for the tab's life. */ private acquireExclusive; /** Resolves once no tab holds `name` (a shared request is granted only then). */ private waitForRelease; private releaseHeldLocks; private requireLocks; private setState; private notifyChange; } /** A delivered operation the client did not apply, as stored in `_kora_unapplied_ops`. */ interface UnappliedOperation { /** The operation as delivered (still encrypted when decryption failed). */ operation: Operation; /** Delivery sequence of the batch that carried it, or null for a legacy batch. */ deliverySequence: number | null; /** * Its own delivery position, when the server sent one (decides whether its replay * shows a record a later retraction hid). Absent otherwise. */ position?: number; /** Machine-readable reason. */ code: string; /** Human-readable explanation. */ message: string; /** Wall-clock time (ms) it was quarantined. Display only. */ quarantinedAt: number; } /** * Transaction interface for executing multiple operations atomically. */ /** Options of `StorageAdapter.transaction`. */ interface TransactionOptions { /** Take the write lock when the transaction begins (see `StorageAdapter.transaction`). */ immediate?: boolean; } interface Transaction { execute(sql: string, params?: unknown[]): Promise; query(sql: string, params?: unknown[]): Promise; /** * Optional: run several write statements of this transaction, in order, in one * call (one worker message for the SQLite WASM adapter). Stops at the first * failing statement and rejects; statements before it ran inside the * transaction, which the caller then rolls back like after any failed * `execute`. Adapters without it get the statements one `execute` at a time. */ executeBatch?(statements: readonly TransactionStatement[]): Promise; } /** One write statement of {@link Transaction.executeBatch}. */ interface TransactionStatement { readonly sql: string; readonly params?: unknown[]; } /** * Migration plan containing SQL statements and optional data transforms. */ interface MigrationPlan { statements: string[]; transforms?: Array<(row: Record) => Record>; } type StorageFallbackReason = 'lock-conflict' | 'timeout' | 'unsupported'; interface StorageOpenState { /** True when the selected adapter can survive reload/browser restart. */ persistent: boolean; /** The concrete storage mode the adapter is using after open. */ mode: 'opfs' | 'indexeddb' | 'memory' | 'native' | 'unknown'; /** Present when a primary storage mode degraded during open. */ fallbackReason?: StorageFallbackReason; /** OPFS pool that owns the database file (one pool per database), when known. */ poolName?: string; /** * SQLite journal mode the database actually runs with, when known (NEW-STORE-11). * OPFS (opfs-sahpool): `delete`, the rollback journal; WAL is not available on * that VFS. In-memory fallback: `memory`. Native better-sqlite3: `wal`. */ journalMode?: string; } /** * Storage adapter interface. All storage backends must implement this. * Operations are async to support both sync (better-sqlite3) and async (IndexedDB, WASM) backends. */ interface StorageAdapter { /** Open or create the database */ open(schema: SchemaDefinition): Promise; /** Close the database and release resources */ close(): Promise; /** Execute a write query (INSERT, UPDATE, DELETE) within a transaction */ execute(sql: string, params?: unknown[]): Promise; /** Execute a read query (SELECT) */ query(sql: string, params?: unknown[]): Promise; /** * Execute multiple operations atomically. * * `options.immediate` asks for the write lock at the start (SQLite `BEGIN IMMEDIATE`) for a * transaction that reads and then writes, so two connections to one file (two processes) * queue up instead of failing with `database is locked`. Adapters with a single connection * ignore it. */ transaction(fn: (tx: Transaction) => Promise, options?: TransactionOptions): Promise; /** Apply a schema migration */ migrate(from: number, to: number, migration: MigrationPlan): Promise; /** * Optional post-open storage state. Adapters that can silently degrade at * runtime should expose this so higher-level runtimes can promote to a durable * fallback before app code starts reading or writing user data. */ getStorageOpenState?(): StorageOpenState | null; /** * Optional: true while the adapter refuses every write (it has no durable storage and * the app did not opt into that, `StorageDurabilityError`). The instant-updates overlay * asks before it shows a write, so it never shows one the adapter will refuse. */ refusesWrites?(): boolean; /** * Optional durability barrier (RT-35): resolve once every write committed before the * call is durable, reject when it cannot be made durable. Adapters whose commits are * durable when they resolve (SQLite on a file or OPFS) omit it; an adapter that * persists asynchronously (the IndexedDB snapshot fallback) must implement it. */ ensureDurable?(): Promise; /** * Optional: resolves once every write committed so far is in a persisted snapshot, * WITHOUT forcing one (it waits for the next debounced snapshot). Adapters whose writes * are durable on commit omit it. Used to know when a completion mark reached disk. */ whenPersisted?(): Promise; /** * Optional: the version gate this adapter's tab declares (browser adapters). The store * closes its write gate when the tab is superseded and drains its writes as the first * retirement step; the app adds its own steps (prompt, sync). */ getVersionGate?(): VersionGate | null; /** * Optional: the evidence kept outside the database that it existed (storage manifest and * `localStorage` marker), captured when it was opened. Browser adapters that persist * durably return one; the store uses it to tell a vanished database from a first visit * and to keep the records current. */ getStorageEvidence?(): StorageEvidence | null; /** * Optional: a new, empty scratch database of the same engine, in memory, that the * store replicates a large first sync into before merging it into this database * (`docs/design/first-visit-parity.md` 6). The caller opens and closes it. * Memory, not a file: nothing of it survives a crash or a reload (a torn staging * database can never be trusted, decision D10), it needs no pool slot, and its journal * lives in memory. Adapters without a cheap scratch database omit it; the store then * replicates straight into this database, as before. */ createStagingAdapter?(): Promise; /** * Whether staged replication pays off on this adapter without being asked for. Browser * OPFS databases pay a journaled commit per batch that a memory replica avoids; native * SQLite has no such cost, so a second pass only adds work and it stages only when the * app opts in (`sync.bulkReplication: true` or an object). Absent means true. */ readonly prefersStaging?: boolean; } /** * Routes local mutations through a unified apply pipeline (korajs ApplyPipeline). * * Every local write — including each entry of an `app.transaction` commit — is * built and persisted by the store's single local write path; the handler adds * pipeline behaviour around it. */ interface LocalMutationHandler { insert(collection: string, data: Record, options?: WriteOptions): Promise; /** * Insert several records in one storage transaction, all or none (see * `CollectionAccessor.insertMany`). Optional: without it the store writes the * batch through its own local write path. */ insertMany?(collection: string, rows: readonly Record[], options?: WriteOptions): Promise; update(collection: string, id: string, data: Record, options?: WriteOptions): Promise; delete(collection: string, id: string, options?: WriteOptions): Promise; /** * Called inside the write transaction for every local delete (single-record, * transactional and cascaded), after the delete operation is built and before * referential side effects run. Reads must go through `tx`. Throwing aborts * the whole write. */ beforeLocalDelete?(operation: Operation, tx: Transaction): Promise; } type StoreIsolation = 'shared' | 'per-tab'; /** * Per-write options of `insert`, `insertMany`, `update` and `delete`. */ interface WriteOptions { /** * Wait for the commit before this write is shown: no instant-updates prediction for * this one write, so live queries show it when its transaction has committed, exactly * as with `store.instantUpdates` off. It adds no durability: the write is stored the * same way either way, and its promise resolves at the same point. Has no effect when * instant updates are off. */ durable?: boolean; } /** * Options of `createApp({ store: { instantUpdates } })`: show this tab's own writes in * its live queries before their storage transaction commits. * * The write path is unchanged (same operations, ids and order); the view is a tab-local * prediction that the database overwrites at commit, and that disappears if the write * fails. A row shown this way is NOT saved: only the write's promise resolving means * that. Off by default in beta.15. */ interface InstantUpdatesOptions { /** Writes shown but not yet committed, per tab. Beyond it, writes wait for the commit. Default 256. */ maxPendingWrites?: number; /** Estimated bytes of pending and settling writes. Default 8 MiB. */ maxPendingBytes?: number; /** Largest number of records one write may touch and still be shown early. Default 100. */ maxRecordsPerWrite?: number; } interface StoreConfig { schema: SchemaDefinition; adapter: StorageAdapter; /** * The version gate of this database when the adapter does not own one (an adapter that * ignores it, an embedder that opens the gate itself). Defaults to * `adapter.getVersionGate()`. */ versionGate?: VersionGate | null; /** Database name used for per-tab node id keys. Defaults to 'kora-db'. */ dbName?: string; /** * `shared` (default): one node id per database in `_kora_meta`. * `per-tab`: unique node id per browser tab via sessionStorage. */ isolation?: StoreIsolation; /** Optional node ID. If omitted, one is generated or loaded from the database. */ nodeId?: string; /** * The one user this database belongs to: it is opened only for them (`createApp` sets * it with `store.namespaceByAuthUser`). With a pinned {@link nodeId}, a database whose * pinned node moved retires the previous one: its writes are this user's, and those the * sync server does not hold are re-authored under this user's node (a browser shared * between accounts gives each account a device id, and so a node, of its own). */ databaseOwner?: string; /** Optional event emitter. When provided, local mutations emit 'operation:created' events. */ emitter?: KoraEventEmitter; /** Routes local mutations through a unified apply pipeline when provided. */ localMutationHandler?: LocalMutationHandler; /** Called when a reactive query subscription is registered (for sync query subsets). */ onQuerySubscribed?: (descriptor: QueryDescriptor) => () => void; /** * Supplies the key used to encrypt `encrypted` secret fields at write time. * Required only when the schema declares encrypted secret fields. */ secretKeyProvider?: SecretKeyProvider; /** * How rows are materialized. `'fold'` (default, W7): every write merges into the * record's per-field CRDT fold state, which re-materializes the row. `'legacy'`: * the beta.12 per-field LWW write paths, kept only so tests can build the database a * beta.12 device left behind and prove it is repaired. Applications never set it. * Switching modes on an existing database re-materializes it on open. */ materialization?: 'fold' | 'legacy'; /** * Schema transforms applied at fold time (RT-84): an operation authored under an * older schema version is stored exactly as written and folded as * `operationSchemaView(op, schema.version, transforms)` reads it. Pass the same list * as the sync engine's `operationTransforms` (`createApp` does). Transforms must be * pure and deterministic; they are part of the fold plan fingerprint, so changing * them re-folds once. */ operationTransforms?: readonly OperationTransform[]; /** * Largest serialized operation a local write may produce, in bytes (RT-86). Set it to * the sync server's `maxOperationBytes`. A write over it is refused with * `OperationTooLargeError` and nothing is written. Default 256 KiB, the server's * default. */ maxOperationBytes?: number; /** * Show this store's own local writes in its live queries before their transaction * commits (`true`, or limits). Per store, default off. See {@link InstantUpdatesOptions}. */ instantUpdates?: boolean | InstantUpdatesOptions; /** * Test and benchmark hooks of the instant-updates overlay. Internal: not part of the * public API and free to change. * * @internal */ instantUpdatesInternals?: OverlayControllerInternals; } /** * Operators for where clause conditions. */ interface WhereOperators { $eq?: unknown; $ne?: unknown; $gt?: number | string; $gte?: number | string; $lt?: number | string; $lte?: number | string; $in?: unknown[]; } /** * Where clause: field name to value (shorthand for $eq) or WhereOperators. */ type WhereClause = Record; /** * Order direction for sorting query results. */ type OrderByDirection = 'asc' | 'desc'; /** * Order-by clause: field name and optional direction. */ interface OrderByClause { field: string; direction: OrderByDirection; } /** * Internal representation of a query to be compiled to SQL. */ interface QueryDescriptor { collection: string; where: WhereClause; orderBy: OrderByClause[]; limit?: number; offset?: number; /** Relation names to include in results (for relational queries). */ include?: string[]; /** Resolved collection names for included relations (for subscription tracking). */ includeCollections?: string[]; } /** * Callback for reactive subscriptions. Receives the current result set. */ type SubscriptionCallback = (results: T[]) => void; /** * Where a subscription failure happened. * - `initial`: the first run of the query, before any result was delivered. * - `refresh`: a re-run after a write to a collection the query reads. * - `callback`: the query succeeded but the subscriber's own callback threw. */ type QueryErrorPhase = 'initial' | 'refresh' | 'callback'; /** * A failure delivered to a subscriber's `onError` (STORE-12). The previous result * set stays current; the subscription stays registered and is re-run on the next * write, and a later success is delivered even if it equals the last results. */ interface QuerySubscriptionError { /** The error thrown by the query or the callback. */ error: Error; phase: QueryErrorPhase; /** The collection the query reads. */ collection: string; /** Subscription id, the same `queryId` carried by the `query:error` event. */ queryId: string; } /** * Options for `QueryBuilder.subscribe()`. */ /** * Where a subscription's rows come from and whether they are the whole answer. * - `server`: an answer read from the server before the local store opened (complete for the query). * - `local`: the local store; `complete` is false until the device holds the full scope * (a first visit that is still replicating shows only what it holds so far). * - `pending`: no result yet. */ interface QueryCoverage { source: 'local' | 'server' | 'pending'; complete: boolean; } interface SubscribeOptions { /** * Called with the coverage of the rows delivered to the callback, when it changes. A query * that reports nothing is a plain local query: `{ source: 'local', complete: true }`. */ onCoverage?: (coverage: QueryCoverage) => void; /** * Called when the query fails (or the callback throws) instead of the failure * becoming an unhandled rejection. Every failure is also emitted as a * `query:error` event; without `onError` it is additionally logged. */ onError?: (failure: QuerySubscriptionError) => void; } /** * Serialized row in the operations log table. */ interface OperationRow { id: string; node_id: string; type: string; record_id: string; data: string | null; previous_data: string | null; timestamp: string; sequence_number: number; causal_deps: string; schema_version: number; } /** * Record type returned from collection queries. * Includes the id and mapped metadata fields. */ interface CollectionRecord { id: string; createdAt: number; updatedAt: number; [key: string]: unknown; } /** * Internal row shape returned from SQL queries on collection tables. */ interface RawCollectionRow { id: string; _created_at: number; _updated_at: number; _version?: string; /** JSON map of per-field last-writer HLC versions: { field -> serialized HLC }. */ _field_versions?: string; _deleted: number; [key: string]: unknown; } /** * A registered subscription tracked by the SubscriptionManager. */ interface Subscription { id: string; descriptor: QueryDescriptor; callback: SubscriptionCallback; executeFn: () => Promise; lastResults: T[]; /** Result-set comparator (structural, per field kind). */ resultsEqual?: (prev: readonly T[], next: readonly T[]) => boolean; onError?: (failure: QuerySubscriptionError) => void; /** Monotonic run counter: a slower, older run never overwrites a newer result. */ runsStarted?: number; lastAppliedRun?: number; /** True after a failure until the next successful delivery. */ errored?: boolean; /** True once a result set has been delivered to the callback. */ delivered?: boolean; /** * Instant-UI overlay (S3). The last authoritative (SQL) result, before any pending * write was applied; null until the first result arrives. `lastResults` is what was * last delivered to the callback (the design's `displayed`). */ base?: T[] | null; /** Overlay epoch when the read that produced `base` was issued (design 5.5). */ baseIssuedAt?: number; /** Whether the evaluator may patch this query (decided once, on first use). */ patchable?: boolean; /** * Pending writes the last patch could not apply to this query (limit pages, ties): * its display did not include them, so the settle check does not compare them. */ skippedWrites?: ReadonlySet; } /** * Options for applying a remote operation to materialized storage. */ interface ApplyRemoteOptions { /** * W7: receives the merge traces of the operation (conflicting field decisions), * after commit. The store also emits them as `merge:*` events. */ onMergeTraces?: (traces: _korajs_core.MergeTrace[]) => void; /** When true, a winning remote update clears soft-delete on the row. */ reactivateIfDeleted?: boolean; /** * Where in the server's delivery stream this operation was delivered. Decides whether * it shows a record a scope retraction hid: only when it comes after the retraction. * Usually supplied by the sync engine through `Store.noteDeliveryPosition` instead. */ deliveryPosition?: number; /** * When true, materialize the update unconditionally, bypassing the LWW * version guard. Used only for authoritative three-way merge results: the * merged value already incorporates the current local row, so it must be * written even when its timestamp ties the current row version (which * happens on the device that authored the newer of two concurrent edits — * without this, that device's CRDT/merge result is silently dropped). */ forceMaterialize?: boolean; /** * Data to materialize into the row INSTEAD of `op.data`, without altering * what is stored in the append-only operation log. Merge results must never * be persisted under the original operation's content-addressed id (ops are * immutable); the pipeline passes the merged values here so the log keeps * the canonical operation while the row reflects the merge. */ materializeData?: Record; /** * Version timestamp to stamp on the materialized row INSTEAD of * `op.timestamp` (e.g. max(local, remote) for a merge result). The logged * operation keeps its own timestamp. */ materializeTimestamp?: HLCTimestamp; /** * Optimistic-concurrency guard: the row version state the caller observed * when it computed the data it is now applying. Inside the write * transaction, if the row's current `_version` / `_field_versions` no longer * match this snapshot, the apply throws `OptimisticLockError` (rolling back, * writing nothing) so the caller can recompute against fresh state. */ guardRowState?: RowVersionState; /** * When true, append the operation to the log (advancing the version vector and * enabling dedup) WITHOUT materializing anything into the row. Used when a fold * of the record's log has determined the operation does not change the * authoritative row state (e.g. a stale update that loses to a newer delete): * the op must still be persisted so a later fold — for example an atomic * resurrection composing this op's delta — is complete, but the row (a clean * tombstone) must be left untouched, with no zombie fields and no version regression. */ logOnly?: boolean; } /** * Raw version state of a materialized row, used for optimistic-concurrency * guarded applies. `null` means the row (or column value) was absent. */ interface RowVersionState { version: string | null; fieldVersions: string | null; } /** A cascade or set-null a remote delete derived, folded as a provisional effect (RT-69). */ interface ProvisionalSideEffect { type: 'delete' | 'update'; collection: string; recordId: string; data: Record | null; previousData: Record | null; ruleId: string; } /** Reads of one collection through a remote batch's transaction (see `RemoteApplyBatch.read`). */ interface RemoteBatchCollectionReader { findById(id: string): Promise; where(conditions: WhereClause): { exec(): Promise; count(): Promise; }; } /** * One delivery batch being applied in a single storage transaction (C3, * `Store.applyRemoteBatch`). Every write goes through {@link tx}; every operation and * retraction runs in its own savepoint, so a failing one is undone alone. Nothing is * published (notifications, events, version vector) until the transaction commits. */ interface RemoteApplyBatch { /** The batch's transaction, for reads that must see the batch's own writes. */ readonly tx: Transaction; /** * Optional (C3b): tell the batch which operations it is about to apply, so it reads * what they need (log, fold states, rows) in a few queries instead of a dozen per * operation. An operation not announced is applied exactly as before. Call it before * the first `applyRemoteOperation` of those operations. */ prefetch(operations: readonly Operation[]): Promise; /** * Write every statement the batch has buffered (steps whose writes cannot fail share one * buffer and are sent together). Call it before a check that decides whether the batch may * still commit: a check made before it does not cover the writes that are still waiting. */ flush(): Promise; /** * Append and fold one remote operation (W7) in a savepoint. Rejects (with only this * operation rolled back) when it cannot be applied. */ applyRemoteOperation(op: Operation, options?: Pick): Promise; /** Hide a record a scope retraction removed from this view (see `Store.applyScopeRetraction`). */ applyScopeRetraction(collection: string, recordId: string, position?: number): Promise; /** Fold a remote delete's provisional side effects (see `Store.applyProvisionalSideEffects`). */ applyProvisionalSideEffects(parent: Operation, effects: ReadonlyArray): Promise; /** A materialized row as the batch sees it (its own writes included). */ findMaterializedRow(collection: string, recordId: string): Promise; /** * Read a collection as the batch sees it (its own writes included), with exactly the * queries `store.collection(name)` runs: `findById` (live records only) and * `where(conditions).exec()` / `.count()`. For checks that must see the state right * after one operation of the batch (the optimistic constraint check). */ read(collection: string): RemoteBatchCollectionReader; /** Record quarantined operations (and the watermark advance) in the batch's transaction. */ saveInboundQuarantine(entries: UnappliedOperation[], watermark?: { signature: string; watermark: number; completion?: OfflineCompletion; }): Promise; /** * Persist a view's delivery watermark in the batch's transaction, with the completion * mark of a final batch (set in the same transaction). */ saveDeliveryWatermark(signature: string, watermark: number, completion?: OfflineCompletion): Promise; /** * Run `effect` once the batch committed, in registration order with the store's own * notifications. Dropped when the step that registered it (or the batch) rolls back. */ afterCommit(effect: () => void): void; } /** * Snapshot of a materialized row, including soft-deleted records. */ interface MaterializedRowSnapshot { /** Deserialized application record (excludes tombstone metadata). */ record: CollectionRecord; /** Whether the row is soft-deleted (_deleted = 1). */ deleted: boolean; } /** * Metadata row from _kora_meta table. */ interface MetaRow { key: string; value: string; } /** * Version vector row from _kora_version_vector table. */ interface VersionVectorRow { node_id: string; sequence_number: number; } /** * Whether resolved local writes are durable (`app.storage.writes`). `failing` after a * committed write could not be confirmed on durable storage (IndexedDB fallback only); * `permanent` means its snapshot lineage was superseded and nothing in this page can * prove it saved: reload before making more changes. */ type WriteDurabilityState = { readonly state: 'durable'; } | { readonly state: 'failing'; readonly permanent: boolean; readonly since: number; readonly message: string; }; export { StorageBackendMismatchError as $, type ApplyRemoteOptions as A, BridgeTerminatedError as B, type CollectionRecord as C, type OrderByDirection as D, PersistenceError as E, type QueryCoverage as F, type QueryErrorPhase as G, type QuerySubscriptionError as H, type InstantUpdatesOptions as I, RecordNotFoundError as J, type RemoteBatchCollectionReader as K, type LocalDatabaseRecord as L, type MigrationPlan as M, NoLeaderError as N, type OperationRow as O, type ProvisionalSideEffect as P, type QueryDescriptor as Q, type RawCollectionRow as R, type StorageAdapter as S, type Transaction as T, type UnappliedOperation as U, VersionGate as V, type WriteOptions as W, RequestAbortedError as X, type RetirePhase as Y, SchemaVersionAheadError as Z, StampedFieldError as _, type TransactionOptions as a, StorageDurabilityError as a0, type StorageFallbackReason as a1, StorageFormatAheadError as a2, StorageInUseError as a3, type StoreIsolation as a4, StoreNotOpenError as a5, type SubscribeOptions as a6, type SubscriptionCallback as a7, type SupersededInfo as a8, TabCoordinationUnavailableError as a9, type TabIdentity as aa, UnsyncedDataError as ab, VersionGateClosedError as ac, type VersionGateMode as ad, type VersionGateOptions as ae, type VersionGateSnapshot as af, type VersionGateState as ag, type WhereClause as ah, type WhereOperators as ai, WorkerInitError as aj, WorkerTimeoutError as ak, compareTabKeys as al, parseTabLockName as am, schemaFingerprint as an, tabLockName as ao, PendingWrites as ap, type StorageOpenState as b, StorageEvidence as c, type LocalDatabaseBackend as d, type MetaRow as e, type Subscription as f, type VersionVectorRow as g, type LocalMutationHandler as h, WriteNotDurableError as i, type WriteOverlay as j, type WriteTracker as k, type StoreConfig as l, type StorageEviction as m, type RemoteApplyBatch as n, OverlayController as o, type MaterializedRowSnapshot as p, type RowVersionState as q, type WriteDurabilityState as r, AdapterError as s, BuildSupersededError as t, type BuildSupersededInfo as u, LeaderUnresponsiveError as v, LocalDatabaseNotFoundError as w, NodeOwnedByAnotherUserError as x, OptimisticLockError as y, type OrderByClause as z };