import { S as StorageAdapter, C as CollectionRecord, k as WriteTracker, W as WriteOptions, l as StoreConfig, m as StorageEviction, A as ApplyRemoteOptions, n as RemoteApplyBatch, P as ProvisionalSideEffect, o as OverlayController, h as LocalMutationHandler, p as MaterializedRowSnapshot, q as RowVersionState, U as UnappliedOperation, r as WriteDurabilityState, T as Transaction } from './types-BVVjCckP.cjs'; export { s as AdapterError, B as BridgeTerminatedError, t as BuildSupersededError, u as BuildSupersededInfo, I as InstantUpdatesOptions, v as LeaderUnresponsiveError, w as LocalDatabaseNotFoundError, M as MigrationPlan, N as NoLeaderError, x as NodeOwnedByAnotherUserError, y as OptimisticLockError, z as OrderByClause, D as OrderByDirection, E as PersistenceError, F as QueryCoverage, Q as QueryDescriptor, G as QueryErrorPhase, H as QuerySubscriptionError, J as RecordNotFoundError, K as RemoteBatchCollectionReader, X as RequestAbortedError, Y as RetirePhase, Z as SchemaVersionAheadError, _ as StampedFieldError, $ as StorageBackendMismatchError, a0 as StorageDurabilityError, a1 as StorageFallbackReason, a2 as StorageFormatAheadError, a3 as StorageInUseError, b as StorageOpenState, a4 as StoreIsolation, a5 as StoreNotOpenError, a6 as SubscribeOptions, a7 as SubscriptionCallback, a8 as SupersededInfo, a9 as TabCoordinationUnavailableError, aa as TabIdentity, ab as UnsyncedDataError, V as VersionGate, ac as VersionGateClosedError, ad as VersionGateMode, ae as VersionGateOptions, af as VersionGateSnapshot, ag as VersionGateState, ah as WhereClause, ai as WhereOperators, aj as WorkerInitError, ak as WorkerTimeoutError, i as WriteNotDurableError, al as compareTabKeys, am as parseTabLockName, an as schemaFingerprint, ao as tabLockName } from './types-BVVjCckP.cjs'; import { SchemaDefinition, HybridLogicalClock, CausalTracker, SecretKeyProvider, Operation, MergeTrace, VersionVector, HLCTimestamp, SequenceConfig, OperationLog, OperationTransform, ApplyResult, FoldState, OfflineCompletion, OfflineUnitKey, OfflineMarksSnapshot, KoraEventEmitter, KoraEventType, KoraEventListener, KoraEventByType, KoraError as KoraError$1, StateMachineDefinition, CollectionDefinition, KoraBytesValue, KoraEvent, BlobRefMetadata, BlobRef } from '@korajs/core'; export { ApplyResult } from '@korajs/core'; import { R as RelationEnforcer, j as LocalDeleteHook, k as RecordFolder, L as LocalMutationContext, A as AdoptionSchedule, T as TerminalRejection, l as LocalNodeRecord } from './sql-builder-BirWBjAa.cjs'; export { C as Collection, P as ParkedAdoption, V as VIRTUAL_TIMESTAMP_FIELDS, m as VIRTUAL_TIMESTAMP_FIELD_NAMES, n as VirtualTimestampField, o as mergeYjsUpdates } from './sql-builder-BirWBjAa.cjs'; import { Q as QueryBuilder, R as RecordsChangeListener, S as SubscriptionManager } from './lite-693ZNHzF.cjs'; export { a as QueryStore, b as QueryStoreCache, c as RecordsChange, d as RegisterOptions, e as ResultsEqual, f as StoreReadOnlyError, g as SubscriptionManagerOptions, h as SubscriptionStats, i as assertQueryReady, j as getSharedQueryStoreCache, n as normalizeWhere, q as queryKey } from './lite-693ZNHzF.cjs'; import * as yjs from 'yjs'; import { C as ContentAddressedBlobStore } from './content-addressed-blob-store-CRUU_iCe.cjs'; export { B as BlobIntegrityError, M as MemoryBlobStore } from './content-addressed-blob-store-CRUU_iCe.cjs'; export { B as BlobGcOptions, a as BlobGcResult, D as DEFAULT_BLOB_GC_GRACE_MS, S as ServerBlobCallbacks, c as collectBlobGarbage, b as createMemoryServerBlobStore, e as extractBlobRefs, t as toServerBlobCallbacks } from './blob-gc-DUg6MzMP.cjs'; import { KoraError } from '@korajs/core/lite'; /** An insert whose values are validated and in their at-rest form. */ interface PreparedInsert { readonly collection: string; readonly recordId: string; /** Record-shaped, at-rest values (secret fields hashed / encrypted). */ readonly data: Record; } /** * Thrown when a query is invalid (bad field names, invalid operators, etc.). */ declare class QueryError extends KoraError { constructor(message: string, context?: Record); } /** * A buffered mutation. Buffered entries hold the developer's INTENT, not built * operations: they are written at commit, inside the commit's storage * transaction, through the same single local write path as single-record writes * (W6). That is what gives transaction writes in-transaction sequence * reservation, per-field version stamps, state-machine validation and atomic ops * resolved against the committed row. */ type BufferedEntry = { readonly kind: 'insert'; readonly collection: string; readonly insert: PreparedInsert; } | { readonly kind: 'update'; readonly collection: string; readonly id: string; /** Schema-validated update data; may contain atomic op descriptors. */ readonly data: Record; } | { readonly kind: 'delete'; readonly collection: string; readonly id: string; }; /** One buffered write of a transaction, as {@link TransactionCommitOptions.prepare} sees it. */ type TransactionWrite = BufferedEntry; /** * A committed row the transaction's callback read (through `update`, `delete` or * `findById`), BEFORE its own buffered writes were applied, with the * {@link TransactionContextConfig.readToken} taken just before the read was issued. Only * recorded when the store has instant updates (S6a): the group's predictor may use it as a * record's base instead of reading the row again, if the token still matches. */ interface ObservedRead { readonly collection: string; readonly id: string; readonly record: CollectionRecord | null; readonly token: number; } /** * Registers a sealed transaction with the instant-updates overlay. Called synchronously, * immediately before the storage transaction starts, so registration order is transaction * order. Returns the tracker of the registered group, or null when nothing was registered. */ type TransactionRegistrar = () => WriteTracker | null; /** Options for {@link TransactionContext.commit}. */ interface TransactionCommitOptions { /** * Instant updates (S6a): called once the buffer is sealed and before the storage * transaction starts, with every buffered write in order. It may read (the base records * of updates and deletes), so it returns a registrar or a promise of one; the registrar * runs in the same synchronous step as the start of the storage transaction. With a * tracker, a transaction that rejects after its body finished is looked up by its first * operation (M2). Must not throw; a failure is treated as "nothing registered". Never * reads back into the write: the statements written are the same with or without it. */ readonly prepare?: (writes: readonly TransactionWrite[], observed: ReadonlyMap) => TransactionRegistrar | Promise; } /** * Internal configuration for creating a TransactionContext. * Passed from Store to avoid exposing Store internals publicly. */ interface TransactionContextConfig { schema: SchemaDefinition; adapter: StorageAdapter; clock: HybridLogicalClock; nodeId: string; relationEnforcer: RelationEnforcer | null; causalTracker: CausalTracker | null; /** * Key provider for `t.secret()` encrypted fields. Transaction writes transform * secret fields through the same helper as single-record writes (STORE-4). */ secretKeyProvider?: SecretKeyProvider; /** Referential hook run for every local delete inside the commit (see {@link LocalDeleteHook}). */ beforeLocalDelete?: LocalDeleteHook; /** Called when the commit's storage transaction fails, before the error propagates. */ onStorageError?: (error: unknown) => void; /** The W7 record fold (see `WriteEnv.fold`). */ fold?: RecordFolder; /** See `WriteEnv.maxOperationBytes`. */ maxOperationBytes?: number; /** See `WriteEnv.assertLocalWriteAllowed`. */ assertLocalWriteAllowed?: () => void; /** See `WriteEnv.signedInUser`. */ signedInUser?: () => string | null; /** * Instant updates (S6a): a token for the freshness of committed rows of a collection * (the overlay registry's seed stamp), taken before each committed-row read of the * callback. Absent (the default): nothing is recorded. */ readToken?: (collection: string) => number; } /** * A collection accessor within a transaction. * Operations are buffered and committed atomically when the transaction completes. */ interface TransactionCollectionAccessor { insert(data: Record): Promise; /** * Insert several records as part of the transaction, in input order (the same as * calling `insert` for each). Every row is validated before any is buffered. */ insertMany(rows: readonly Record[]): Promise; update(id: string, data: Record): Promise; delete(id: string): Promise; findById(id: string): Promise; } /** * TransactionContext provides atomic multi-collection operations. * * Mutations are validated and buffered when called (so errors surface at the * call site and `insert` returns the new id immediately), then written in a * single `StorageAdapter.transaction()` at commit. All operations share the * same transactionId (UUID v7) and one contiguous block of sequence numbers. * * Subscription notifications are deferred until after commit. * * @example * ```typescript * const { operations, affectedCollections } = await txContext.commit() * // Notify subscriptions after commit * for (const op of operations) { * subscriptionManager.notify(op.collection, op) * } * ``` */ declare class TransactionContext { private readonly transactionId; private mutationName; private readonly buffer; /** Committed rows the callback read, by `collection\u0000id` (only with `readToken`). */ private readonly observed; private committed; private rolledBack; private readonly config; constructor(config: TransactionContextConfig); /** * Set a human-readable mutation name for this transaction. * Propagated to all operations for DevTools display. */ setMutationName(name: string): void; /** * Get the mutation name, if set. */ getMutationName(): string | undefined; /** * Get a collection accessor for buffered operations within this transaction. */ collection(name: string): TransactionCollectionAccessor; /** * Commit all buffered mutations atomically. * * Every entry is written, in call order, inside ONE storage transaction through * the single local write path: sequence numbers are reserved inside the * transaction (one contiguous block covering referential side effects too) and * each operation is built only after its number is reserved. * * Returns the list of operations and affected collections for subscription notification. * * @param options - `prepare`: the instant-updates registration of the group (S6a) */ commit(options?: TransactionCommitOptions): Promise<{ operations: Operation[]; affectedCollections: Set; }>; /** * Mark the transaction as rolled back. No operations will be committed. */ rollback(): void; /** * Get the transaction ID shared by all operations in this transaction. */ getTransactionId(): string; private writeEnv; private ensureActive; private insert; private insertMany; private update; private deleteRecord; /** * The values an update will write, resolved against `current` (the effective * record) for read-your-writes inside the transaction. Secret fields are shown * in their at-rest form, like the record a committed update returns. */ private previewUpdate; /** * The effective state of a record: the committed row overlaid with this * transaction's buffered mutations, in call order. */ private getEffectiveRecord; } /** * In-memory materialized state at a causal cut in the operation log. * Read-only — does not mutate the live store. */ interface ReplaySnapshot { /** The operation whose causal past was replayed (inclusive). */ targetOperation: Operation; /** Operations applied in causal order (ancestors + target). */ operationsApplied: Operation[]; /** Non-deleted records per collection after replay. */ collections: Record; /** Look up a single record at the replay cut. Returns null if deleted or missing. */ findRecord(collection: string, recordId: string): CollectionRecord | null; } /** * A merge or constraint decision persisted for enterprise audit export. */ interface PersistedAuditTrace { /** Unique row id (UUID v7). */ id: string; /** Wall-clock time when the trace was recorded (epoch ms). */ recordedAt: number; /** Source event type from the Kora event bus. */ eventType: 'merge:completed' | 'merge:conflict' | 'constraint:violated'; /** Constraint name when {@link eventType} is `constraint:violated`. */ constraint?: string; /** Full merge trace including conflicting operations and resolution details. */ trace: MergeTrace; } /** * Manifest embedded in audit export files. */ interface AuditExportManifest { /** Audit export format version */ version: 1; /** When the export was created (epoch ms) */ exportedAt: number; /** Node ID of the originating device */ nodeId: string; /** Schema version at export time */ schemaVersion: number; /** Number of operations included */ operationCount: number; /** Number of merge traces included */ mergeTraceCount: number; /** SHA-256 hex checksum of content sections */ checksum: string; } /** * Decoded audit export payload. */ interface AuditExportPayload { manifest: AuditExportManifest; operations: Operation[]; mergeTraces: PersistedAuditTrace[]; } /** * Progress reported during audit export. */ interface AuditExportProgress { phase: 'reading' | 'writing' | 'verifying'; /** 0-1 progress ratio */ progress: number; message: string; } /** * Options for {@link exportAudit}. */ interface AuditExportOptions { /** Subset of collections for operations and traces. All if omitted. */ collections?: string[]; /** Include only traces recorded at or after this timestamp (epoch ms). */ since?: number; /** Include only traces recorded at or before this timestamp (epoch ms). */ until?: number; /** Progress callback */ onProgress?: (progress: AuditExportProgress) => void; } /** * Query filters for reading persisted audit traces. */ interface AuditTraceQuery { collections?: string[]; since?: number; until?: number; } /** * Manifest embedded in every backup file. */ interface BackupManifest { /** Backup format version (2 since STORE-5; version 1 files need `convertBackupV1`) */ version: number; /** When the backup was created (epoch ms) */ createdAt: number; /** * Node ID of the originating device. Informational only: a restore never copies a * device identity into the importing database. */ nodeId: string; /** Schema version at backup time */ schemaVersion: number; /** Total number of operations in the backup */ operationCount: number; /** Collection names included in the backup */ collections: string[]; /** Whether materialized records are included */ includesRecords: boolean; /** Whether the records include deleted rows (tombstones). False for converted v1 files. */ includesTombstones?: boolean; /** Set on a file produced by `convertBackupV1`. */ convertedFrom?: number; /** * The file carries the W7 fold's per-record base states (`fold_base`), row * snapshots (`fold_snapshot`) and the compacted prefixes (`compacted_through`), so * a compacted device's history survives a restore on another device (RT-66). * Absent on files from earlier releases: their log may be incomplete (compacted), * so a restore rebuilds their records on top of the backup's rows. */ includesFoldState?: boolean; /** The exporting database had compacted its log (it then needs `fold_base`). */ compacted?: boolean; /** SHA-256 hex checksum of all content sections */ checksum: string; } /** * Progress reported during backup/restore operations. */ interface BackupProgress { phase: 'reading' | 'writing' | 'verifying' | 'restoring'; /** 0-1 progress ratio */ progress: number; message: string; } /** * Result of a restore operation. */ interface RestoreResult { /** Number of operations restored */ operationsRestored: number; /** Number of records restored */ recordsRestored: number; /** Whether the restore completed successfully */ success: boolean; /** Error message if failed */ error?: string; /** Error code if failed (`BACKUP_CHECKSUM_MISMATCH`, `BACKUP_OPERATION_INVALID`, ...) */ errorCode?: string; /** * Set when the file was a version-1 backup (Kora 1.0.0-beta.12 and earlier) that the * import converted first, as `convertBackupV1` does. */ convertedFromVersion?: 1; /** * Replace mode: this device's own writes the sync server had not acknowledged, * re-applied on top of the restored data (see `RestoreOptions.keepUnsyncedWrites`). */ unsyncedWritesKept?: number; /** * Merge mode: operations of server-authority nodes (`kora:` nodes and the explicit * server authorities this device learned) the file held and the import left out. * Server decisions reach a device only from the sync server. */ serverOperationsSkipped?: number; /** Duration in ms */ duration: number; } /** * Options for exporting a backup. */ interface BackupOptions { /** Include materialized record snapshots (default: true) */ includeRecords?: boolean; /** Subset of collections to backup. All if omitted. */ collections?: string[]; /** Progress callback */ onProgress?: (progress: BackupProgress) => void; } /** * Options for restoring from a backup. */ interface RestoreOptions { /** Subset of collections to restore. All if omitted. */ collections?: string[]; /** Progress callback */ onProgress?: (progress: BackupProgress) => void; /** * If true, merge the backup into the existing data: every operation is applied like * one received from sync (deduplicated by id, merged per field), the version vector * advances by MAX, and nothing of the exporting device's identity or sync state is * imported. If false (default), replace the local data with the backup's. */ merge?: boolean; /** * Replace mode only: keep this device's own writes that the sync server has not * acknowledged, re-applied on top of the backup, so a restore never discards writes * that exist nowhere else. Writes of a node the server has accepted are always kept * (they are in flight). Default: true for `store.importBackup`; `app.importBackup` * defaults it to whether sync is configured, so a local-only app gets an exact * replace. */ keepUnsyncedWrites?: boolean; } /** * How the local operation log may be compacted. * Materialized collection rows are always kept as the convergence baseline. */ type CompactionStrategy = { mode: 'never'; } | { mode: 'after-ack'; /** Server version vector; defaults to persisted last-acked vector on the store. */ serverVector?: VersionVector; } | { mode: 'after-days'; /** Delete only ops older than this many days (still requires ack watermark). */ days: number; serverVector?: VersionVector; }; /** * Result of a compaction run. */ interface CompactionResult { /** Number of operation log rows removed. */ deletedCount: number; /** Per-node sequence ceiling used for deletion (from server ack vector). */ watermark: VersionVector; } declare const COMPACTION_BASELINE_META_KEY = "compaction_baseline_at"; /** * Log-integrity scan (W8 step 0). * * Every later fold of the operation log (W7 re-materialization, replay, compaction) * trusts that each stored row is a canonical operation. Two earlier releases could * break that: * * - beta.12's backup restore wrote `JSON.stringify(timestamp)` into the timestamp * column, which `HybridLogicalClock.deserialize` reads as `wallTime: NaN` (a `null` * once re-exported), and a second restore of such a backup nested the damage; * - compaction deletes acknowledged operations, leaving holes in a node's sequence. * * The scan detects rows that do not round-trip through `deserializeOperation` / * `serializeOperation`, repairs the ones whose original value is recoverable from the * row itself (the JSON-encoded timestamp), and moves the rest to * {@link LOG_QUARANTINE_TABLE} (never deleted), so no fold ever reads them. It also * reports sequence gaps in this database's own nodes. Remote nodes' gaps are normal * (scoped sync only delivers part of another device's log) and are not reported. */ /** Rows that could not be repaired, kept verbatim. Never cleared automatically. */ declare const LOG_QUARANTINE_TABLE = "_kora_log_quarantine"; /** What is wrong with an operation row. */ type LogRowProblem = /** The timestamp is a JSON-encoded HLC (beta.12 backup restore). Repairable. */ 'timestamp-json' /** The timestamp cannot be read as an HLC and is not recoverable. */ | 'timestamp-malformed' /** `id`, `node_id` or `record_id` is missing. */ | 'identity-malformed' /** `type` is not insert, update or delete. */ | 'type-invalid' /** `sequence_number` is not a positive integer. */ | 'sequence-invalid' /** `data` or `previous_data` is not a JSON object. */ | 'data-malformed' /** `causal_deps` is not a JSON array of operation ids. */ | 'causal-deps-malformed' /** The row cannot be turned into an operation and back. */ | 'round-trip-failed'; /** One operation row the scan repaired or quarantined. */ interface LogIntegrityRow { collection: string; operationId: string; nodeId: string | null; sequenceNumber: number | null; problem: LogRowProblem; /** Human-readable detail: the bad value, or how it was repaired. */ detail: string; } /** Sequence numbers missing from one of this database's own nodes. */ interface LogSequenceGap { nodeId: string; /** First missing sequence number (inclusive). */ from: number; /** Last missing sequence number (inclusive). */ to: number; } /** * Result of {@link scanLogIntegrity} / `Store.verifyLogIntegrity()`. * * `clean` is the precondition for rebuilding state from the log (W7): every row is * canonical, nothing is quarantined, and this database's own nodes have no holes * below their highest stored sequence number. */ interface LogIntegrityReport { /** True when the log can be folded as-is (no quarantined rows, no own-node gaps). */ clean: boolean; /** `full`: every row was checked in JS. `quick`: SQL prefilter, suspects checked in JS. */ mode: 'full' | 'quick'; /** Rows checked in JS (all rows in full mode, suspects in quick mode). */ checkedRows: number; /** Rows this scan repaired in place. */ repaired: LogIntegrityRow[]; /** Rows this scan moved to the quarantine table. */ newlyQuarantined: LogIntegrityRow[]; /** Every row in the quarantine table (this scan's and earlier ones'). */ quarantined: LogIntegrityRow[]; /** Holes in this database's own nodes' sequences (compaction, a lost tail). */ gaps: LogSequenceGap[]; /** When the log was last compacted (epoch ms), or null when never. */ compactedAt: number | null; /** False when the scan only reported (`repair: false`). */ repairApplied: boolean; } /** What a refused write was: its collection (when it has one) and its operation. */ interface WriteScope { collection?: string; operation: string; } /** One record to seed: a read-through answer's record in the delivery wire form. */ interface SeedInput { collection: string; id: string; /** The schema fields, as a scope entry carries them (binary as `{ $koraBytes }`). */ values: Record; /** The HLC of the write that produced each field's current value. */ fieldVersions: Record; created: HLCTimestamp; latest: HLCTimestamp; } /** What the answer was read at. */ interface SeedMeta { /** The server's delivery counter after the rows were read. */ frontier: number; /** Hash of the grant the rows were read under. */ grantKey: string; } /** Why a record was not seeded. Nothing is dropped silently: each skip is reported. */ type SeedSkipReason = /** The collection is not in the schema. */ 'unknown-collection' /** The record has history here (operations, fold state, an ordinary snapshot): the store is authoritative. */ | 'has-history' /** An array holds repeated values: a snapshot cannot say which copy a later local edit removes. */ | 'array-duplicates' /** The clock refused the record's timestamp (invalid, or too far ahead). */ | 'clock-refused' /** The record already has a seed read at the same or a later frontier. */ | 'not-newer' /** This database does not fold records (a legacy-materialized database): it cannot hold seeds. */ | 'fold-inactive'; /** The result of seeding. */ interface SeedOutcome { seeded: Array<{ collection: string; id: string; }>; skipped: Array<{ collection: string; id: string; reason: SeedSkipReason; }>; } /** A seed marker. */ interface SeedRow { collection: string; recordId: string; frontier: number; grantKey: string; } /** What {@link purgeSeedsInTx} did. */ interface PurgeOutcome { /** Seeds whose record was removed: the device had never written to it. */ removed: SeedRow[]; /** * Seeds the device has written to. The seed marker is gone but the snapshot stays as an * ordinary row snapshot (RT-68), because without it the record would have no insert and * the user's own edit would disappear. The caller settles it once the record's real history * arrives (the merge replays the staged operations), or keeps it and reports it orphaned * (`read:seed-orphaned`) when none does. */ retained: SeedRow[]; } /** * Manages offline-safe sequences backed by a `_kora_sequences` table. * * Each sequence counter is scoped by (name, scope, nodeId), ensuring * that different devices never collide. The counter is atomically * incremented within a database transaction. * * @example * ```typescript * const mgr = new SequenceManager(adapter, 'node-abc') * * const receipt = await mgr.next('receipt', { * scope: 'store-1', * format: 'S-{date}-{node4}-{seq}', * }) * // → "S-20260508-node-0001" * ``` */ declare class SequenceManager { private readonly adapter; private readonly nodeId; constructor(adapter: StorageAdapter, nodeId: string); /** * Get the next value in a sequence, atomically incrementing the counter. * * @param name - The sequence name (e.g., 'receipt', 'invoice') * @param config - Optional configuration for scope, format, and starting value * @returns The formatted sequence value */ next(name: string, config?: SequenceConfig): Promise; /** * Get the current counter value without incrementing. * * @param name - The sequence name * @param config - Optional scope * @returns The current counter value, or 0 if the sequence has never been used */ current(name: string, config?: { scope?: string; }): Promise; /** * Reset a sequence counter. * * @param name - The sequence name * @param config - Optional scope and target value */ reset(name: string, config?: { scope?: string; to?: number; }): Promise; } /** A pin as stored. */ interface StoredOfflinePin { id: string; collection: string; where: Record; files: boolean; /** Kept by `keep()` and not yet released. */ explicit: boolean; createdAt: number; completedAt: number | null; } /** A component's hold on a pin, as stored. */ interface StoredOfflinePinHold { pinId: string; /** This tab's id plus a per-hold id. */ holder: string; /** The holder's tab (the `tabId` of its version-gate tab lock). */ tabId: string; /** The name of the holder's tab lock, when it has one (what a watcher waits on). */ tabLock: string | null; } /** What a pin write changed, so callers know whether to tell the sync view. */ interface OfflinePinWriteResult { /** The pin row was created by this write. */ created: boolean; /** The pin row was deleted by this write. */ deleted: boolean; } /** The fields a pin is created with. */ interface NewOfflinePin { id: string; collection: string; where: Record; files: boolean; } /** * Result of re-stamping unsynced operations after a clock correction. */ interface ClockRebaseResult { /** The rewritten operations, in causal order (original HLC total order preserved). */ operations: Operation[]; /** Maps each old (pre-rebase) operation id to its new content-addressed id. */ idMapping: Record; /** Number of operations that were re-stamped. */ rebasedCount: number; /** Highest timestamp assigned during the rebase, or null when nothing was rebased. */ newMaxTimestamp: HLCTimestamp | null; } /** Result of `Store.resequenceOperation` (RT-35 renumbering). */ interface ResequenceResult { /** The renumbered operation (a version-2 one under a new id). */ operation: Operation; /** Never-sent dependents rewritten to name the new id (re-hashed), in sequence order. */ dependents: Operation[]; /** Old id -> new id, for the operation and every re-hashed dependent. */ idMapping: Record; } /** Result of {@link rotateUnsyncedOperationsInLog}. */ interface NodeRotationResult { /** The node id the device uses from now on. */ nodeId: string; /** The rewritten operations under the new node id, in their original causal order. */ operations: Operation[]; /** Maps each old operation id to its new content-addressed id. */ idMapping: Record; } /** Result of {@link Store.bindPrincipal} (RT-42). */ interface PrincipalBinding { /** The node id local writes use from now on. */ nodeId: string; /** The node id in use before the call. */ previousNodeId: string; /** The store moved to another node id. */ switched: boolean; /** The node id is pinned and belongs to another user: nothing may upload it now. */ conflict: boolean; } declare class Store implements OperationLog { private writeDurabilityFailing; private writeDurabilitySince; private writeDurabilityMessage; /** A superseded IndexedDB lineage can never become durable in this store instance. */ private writeDurabilityPermanentlyFailed; private opened; private nodeId; /** Records an access narrowing kept for their unsent writes (loaded lazily). */ private keptOutsideNarrowing; private sequenceNumber; private versionVector; private clock; private collections; private subscriptionManager; private sequenceManager; private readonly schema; private readonly adapter; /** * Admits this store's writes until the tab is superseded by a newer build of the app * (version gate, section 5): then every write entry point refuses with * `BuildSupersededError` and retirement waits for every write it admitted. */ private readonly writeGate; private readonly configNodeId; /** The one user this database belongs to (`StoreConfig.databaseOwner`), or null. */ private readonly databaseOwner; /** The owner of the pinned node while it belongs to another user than the signed-in one (F9). */ private pinnedNodeOwnedBy; /** The sync server refused the pinned node as another user's (F9). */ private pinnedNodeRefusedByServer; /** Set while the app must not write locally ({@link setReadOnly}). */ private readOnlyReason; /** The user of the last {@link bindPrincipal}. */ private signedInPrincipal; /** * Delivery positions of operations the sync engine is about to apply, by operation id * (see {@link noteDeliveryPosition}); `replay` marks a quarantine replay. */ private readonly deliveryPositions; /** Who `stamp('userId')` fields are filled with: the signed-in user, null when signed out. */ private stampingUser; private readonly dbName; private readonly isolation; private readonly emitter; private localMutationHandler; /** * The instant-updates overlay of this store (S4), or null (the default). It is created * here, per store, from `StoreConfig.instantUpdates`; nothing outside the store holds a * process-wide one. */ private readonly overlayController; private relationEnforcer; private causalTracker; private readonly secretKeyProvider; /** Releases the per-tab node lock (RT-40); null when none is held. */ private releaseNodeLock; /** How rows are materialized ({@link StoreConfig.materialization}). */ private readonly materialization; /** The W7 record fold; null under legacy materialization. */ private readonly folder; /** True once every row of the database is a materialization of its fold state. */ private foldActive; private foreignKeyIndex; /** * How many seeds the database holds (0 almost always). The remote-apply path asks only when * it is not zero, so a database without seeds pays nothing per operation. */ private seedCount; /** Schema transforms applied at fold time (RT-84); never to stored operations. */ private readonly operationTransforms; /** Largest operation a local write may produce (RT-86); default in the write path. */ private readonly maxOperationBytes; /** The version gate this store's writes follow (configured, or the adapter's). */ private readonly versionGate; constructor(config: StoreConfig); /** * Open the store: initialize the database, load or generate a node ID, * restore the sequence number and version vector, and create Collection instances. */ open(): Promise; /** The part of {@link open} that runs once the adapter is open. */ private openOverAdapter; /** True when `_kora_meta` holds neither a node id nor an epoch: the database is new. */ private isDatabaseNew; /** * After the first durable open: report a vanished database, give this one an epoch, and * refresh the evidence kept outside it. Never fails the open: evidence is advisory. */ private finishStorageEvidence; /** * A detected loss of this database's storage (`store:storage-evicted`) the app has not * acknowledged yet, or null. */ getStorageEviction(): StorageEviction | null; /** The app told the user about the storage loss: forget it, durably. */ acknowledgeStorageEviction(): Promise; /** Whether the adapter keeps storage-loss evidence for this database (browser, durable). */ hasStorageEvidence(): boolean; /** * Record how many writes only this device holds, next to the database (storage * manifest), so a vanished database can say what it lost. `exact` is true when no write * follows this recording. A no-op on adapters that keep no evidence. */ recordUnsyncedWrites(count: number, exact: boolean): Promise; /** * Before a close, while this tab retires for a newer build (version gate, section 5 step * 4): wait for every admitted write, then make them durable or throw `PersistenceError` * (`context.code: 'UNSAVED_WRITES'`) with everything still open. A no-op otherwise. * `app.close()` calls it before it tears anything down. */ prepareClose(): Promise; /** * Close the store: clear subscriptions and close the adapter. */ close(): Promise; /** * Check the operation log (W8 step 0): every row must round-trip through the * canonical operation serializer. Rows an earlier release damaged in a recoverable * way (a JSON-encoded timestamp written by a beta.12 backup restore) are repaired; * unrecoverable rows move to the quarantine table, where no fold reads them. Also * reports sequence gaps in this database's own nodes (compaction, a lost tail). * * The store runs a quick variant (SQL prefilter) on every open. Rebuilding state from * the log must only run on a `clean` report. * * @param options - `repair: false` only reports; `mode: 'quick'` checks only the rows * a SQL prefilter flags (default `'full'`: every row) * @returns The integrity report; emits `store:log-integrity` when rows changed */ verifyLogIntegrity(options?: { repair?: boolean; mode?: 'full' | 'quick'; }): Promise; private scanLog; /** * Get a Collection instance for CRUD operations. * @throws {StoreNotOpenError} If the store is not open * @throws {KoraError} `UNKNOWN_COLLECTION` if the collection name is not in the schema */ collection(name: string): CollectionAccessor; /** * Get the current version vector. */ getVersionVector(): VersionVector; /** * Get the node ID for this store instance. */ /** * Records the offset between server time and this device's clock * (serverTime - localTime), learned at sync handshake. Lets the store's HLC * validate remote timestamps correctly even when the local clock is wrong. */ setClockReferenceOffset(offsetMs: number): void; getNodeId(): string; /** * Whether the journaled write with this key already reached the store. Answered from the * table the write's own transaction filled, so it is exact after a crash at any point. */ hasJournalApplied(opKey: string): Promise; /** * Forget journaled-write keys whose journal entries are gone (`opKeys`), and any key older * than `olderThanMs` (an entry that old was pruned long ago). */ forgetJournalApplied(opKeys: readonly string[], olderThanMs?: number): Promise; /** The schema transforms the fold applies (transforms at fold time, RT-84). */ getOperationTransforms(): readonly OperationTransform[]; /** * Apply a remote operation received from sync. * Checks for duplicates, applies to the data table, persists the operation, * and updates the version vector. */ applyRemoteOperation(stored: Operation, options?: ApplyRemoteOptions): Promise; private applyRemoteOperationNow; private applyRemoteOperationUnmarked; /** * W7 remote apply: append the operation, then merge it into its record's fold * state, which re-materializes the row, all in one write transaction. There is no * read-decide-write race to guard: the state is read and written inside the * transaction, and the merge does not depend on the order operations arrive in. */ private applyRemoteFolded; /** * The transactional part of a W7 remote apply: dedup, retraction visibility, append, * fold and version vector, all through `tx`. Nothing in memory is published here * (see {@link publishRemoteApply}), so a caller that rolls `tx` back leaves no trace * except the HLC having seen the timestamp (monotonic, harmless). */ private applyRemoteFoldedInTx; /** * {@link applyRemoteFoldedInTx} answered from what a delivery batch read up front (C3b, * `RemoteBatchPrefetch`): the same writes in the same order, without the reads. Returns * null, having done nothing, when this operation or its record is not one the cache can * answer for (a retracted record, a base, a snapshot, a shared node id, a taken sequence * number, a record the batch changed by another route); the caller then applies it the * per-operation way. */ private applyRemoteFoldedPrefetched; /** After commit: the in-memory effects of a committed remote apply. */ private publishRemoteApply; /** * Apply a delivery batch of remote operations in ONE storage transaction (C3, * docs/design/fast-first-sync.md). `fn` receives a {@link RemoteApplyBatch} whose * writes all go through that transaction; each operation (and retraction) runs in its * own savepoint, so a failing one is rolled back alone and the caller decides what * to do (quarantine it, or abort the batch). * * Everything this runtime publishes (version vector, subscription notifications, * `operation:applied`, merge traces, effects the caller registered with * {@link RemoteApplyBatch.afterCommit}) is held until the transaction commits and * runs in registration order after it; a rolled-back batch publishes nothing. * * @returns `fn`'s result, or `null` when this store cannot batch (legacy * materialization, or records an access narrowing kept for unsent writes: those * paths keep their per-operation bookkeeping) and the caller must apply one by one * @throws Whatever `fn` throws (the transaction is rolled back), or a storage error */ applyRemoteBatch(fn: (batch: RemoteApplyBatch) => Promise): Promise<{ value: T; } | null>; private applyRemoteBatchNow; /** * After a transaction that rejected although its body finished: whether `op`, which that * transaction added to the log, is in the log now (so the commit landed). A lookup that * itself fails proves nothing, so it answers false and the caller reports the original error. */ private commitLanded; /** DevTools: every fold decision that was a conflict, plus one completion per merge. */ private emitMergeTraces; /** * A remote operation applied for a delivery whose position moved while it waited for the * database writes nothing: asked first thing inside the write transaction (the wait for * the adapter's mutex is unbounded), the transaction rolls back. */ private assertDeliveryStillCurrent; /** The delivery position of a remote operation being applied, if known. */ private deliveryPositionOf; /** * The columns of each collection that reference another collection's rows, as the * schema's tables declare them (`REFERENCES`): a write of one can fail on a missing parent. */ private foreignKeysByCollection; /** The record fold, once the database's rows are fold materializations. */ private activeFold; /** * The record's W7 fold state (null under legacy materialization or when the * record has none). For DevTools, tests and the server-comparison harness. */ getFoldState(collection: string, recordId: string): Promise; /** Whether rows are materialized by the W7 fold (false under `materialization: 'legacy'`). */ isFoldMaterialized(): boolean; private readMeta; private writeMeta; /** * Write every genuine beta.12 clear of the op log into its logged body, once per * database (RT-83, RT-85): the fold folds bodies as written, so the clear must be in * the body. Records already materialized by the fold are re-folded. */ private ensureLegacyBodiesCanonical; /** * Make every row a materialization of its record's fold state (W7), once per * database and fold-state version. Runs after the W8 log-integrity scan: a * clean log is rebuilt with the fold; an incomplete (compacted) log rebuilds on * top of the rows as base snapshots; a log with quarantined rows is never * rebuilt from (rows are kept and become base snapshots), and * `store:rematerialized` reports which happened. */ private ensureMaterialization; /** * Refuse to open when a schema version in the local operation log has no transform * path to the current schema (RT-103). Operations of a NEWER schema (authored by an * upgraded peer) are not checked: they are kept aside until this device upgrades. */ private assertTransformCoverage; /** * Re-fold the records of every collection whose fold plan changed since the rows * were materialized (RT-63): a field that became `merge('counter')`, an array that * became append-only, a new or edited resolver. Their stored states hold fields of * the old kind, which the fold refuses (`FoldStateError`). Each record is rebuilt * from its log with the new plan; compacted bases and row snapshots are adapted * (a re-planned field restarts from its materialized value at its version). The * client's equivalent of the server stores' `fold_plan_fingerprint`. */ private ensureFoldPlan; /** * Row snapshots were created (RT-68): ask the sync server for a full resync (the * delivery watermarks restart at 0, as after a restore), so each such record gets * its complete history back; {@link settleSnapshotRecords} then drops the * snapshots once the resync has caught up. */ private requestSnapshotResync; /** * Records whose state still folds against a row snapshot (approximate: a late * concurrent write older than a field's version is not folded, RT-68). */ getSnapshotRecords(): Promise>; /** * Called by sync when a delivery stream has caught up (its final batch fully * applied). After the full resync {@link requestSnapshotResync} asked for, every * row-snapshot record whose insert is back in the log is re-folded from its * complete history and stops being approximate (RT-68). Also retires the * provisional cascades of remote deletes (RT-69): the server's own copies were * delivered by now, and any it did not derive must not stay applied locally. * * With `provisionalOnly` only the provisional cascades are retired (RT-93: a stream * batch from a server that derives no cascades, which is not the end of a resync). * * @param options - `provisionalOnly`: leave row snapshots for the next catch-up * @returns How many snapshots were dropped */ settleAfterCatchUp(options?: { provisionalOnly?: boolean; }): Promise; /** * Apply the cascades / set-nulls of a REMOTE delete as local-only provisional * effects (RT-69): folded into the children like operations, but never logged, * sequenced or queued for upload. The server derives and relays its own copy; * when it arrives (same parent, same record) the provisional effect is retired. * * @param parent - The remote delete * @param effects - Its side effects, as the referential check derived them */ applyProvisionalSideEffects(parent: Operation, effects: ReadonlyArray): Promise; /** The provisional operations of a remote delete's side effects (RT-69). */ private buildProvisionalSideEffects; /** * Node ids whose writes win `merge('server-authoritative')` fields (the server's, * from the sync handshake). Every `kora:server:` id is authoritative by prefix, so * only explicit ids (legacy server node ids, configured extras) are kept: the device * persists the UNION of every explicit id it has learned and never drops one (RT-75). * Handshakes differ per server instance (each lists what it knows), so a list that * omits an id is not a revocation. * * Revocation is explicit (RT-81): ids a handshake lists in `revokedAuthoritativeNodeIds` * are removed from the union, persisted as revoked, and never learned again. Records * of collections with such fields are re-folded only when the explicit set changes * (grows, or loses a revoked id). * * @param nodeIds - The server's authoritative node ids (one handshake's list) * @param revokedNodeIds - Explicit ids the server revoked (one handshake's list) */ setAuthoritativeNodeIds(nodeIds: readonly string[], revokedNodeIds?: readonly string[]): Promise; /** * A log rewrite's in-transaction step (rebase, rotation, re-author): re-fold the records * of the rewritten operations in the transaction that rewrites them, so a crash can never * leave a fold state with the old stamps or ids. `more` runs first in the same * transaction. `touched` collects the records, for invalidating views after the commit. */ private refoldInRewrite; /** Views over records a rewrite re-folded in its transaction read them again. */ private invalidateRefolded; /** * Re-fold the records of these operations from base + log (W7 exclusion: an * operation with a terminal-rejection marker is left out). */ private refoldRecordsOf; /** * Append a remote operation to the log. If another operation of the same node * already holds its sequence number (a beta.12 device could produce such * pairs), the log keeps the existing row and this one is recorded in the * sequence-conflicts table, where dedup and record folds still see it. */ private appendRemoteOperationRow; /** * Record where in the delivery stream an operation the sync engine is about to apply * was delivered (`replay`: it is a quarantine replay), or clear it (`null`). The * remote apply of that operation decides a retracted record's visibility by it * (scopeVisibilityAfter). Keyed by operation id, so side effects the apply derives * for other records never inherit it. */ noteDeliveryPosition(operationId: string, position: { position?: number; replay: boolean; isCurrent?: () => boolean; } | null): void; /** * A delivery run starts at `watermark` (every handshake). Everything a run up to the * watermark positioned is at most `watermark + 0.5` (a scope entry at the watermark's * own sequence). Anything above was positioned by a run that went further: the stream * restarted lower (another view, a server rollback, a forced full resync). Retraction * markers above move to `watermark + 0.25` and quarantined operations above to * `watermark`, so they come before everything the new run delivers: an operation it * delivers shows a record again, and a quarantined one stays behind the retraction it * came before. A resumed stream moves nothing. */ rebaseDeliveryRun(watermark: number): Promise; /** * Hide a record from this client's authorized materialized view. This writes no * replicated operation and therefore cannot be mistaken for a domain deletion. * The marker records `position`, where in delivery order the record was hidden: only * an operation delivered after it shows the record again (unknown: see * scopeVisibilityAfter). */ applyScopeRetraction(collection: string, recordId: string, position?: number, options?: { isCurrent?: () => boolean; }): Promise; /** The writes of {@link applyScopeRetraction}, through `tx`. */ private applyScopeRetractionInTx; /** * Hide every live row of `collection` outside `scope` (null: the whole collection), * except the records in `keep` (records with unsent local operations). Judged on * local values. Returns the ids hidden. * * A kept record outside the scope is remembered (in `_kora_meta`, so a restart keeps * it): {@link recheckAccessNarrowing} hides it once its operations are refused. */ applyCollectionNarrowing(collection: string, scope: Record | null, keep: ReadonlySet, position?: number, options?: { isCurrent?: () => boolean; view?: string; }): Promise; /** * Defer a scope retraction of a record of an access collection while the record has * unsent writes: they upload and the server judges them, and the record is hidden * once none is pending ({@link recheckAccessNarrowing}). Returns false (retract now) * for any other collection. With `isCurrent`, nothing is recorded for a delivery whose * position moved (asked inside the transaction that writes it). */ deferScopeRetraction(collection: string, recordId: string, options?: { isCurrent?: () => boolean; }): Promise; /** * Hide the records an access narrowing kept for their unsent operations once none of * their operations is pending any more (refused, or quarantined) and they are still * outside the narrowed scope. Returns the records hidden. * * @param pending - The record ids of a collection that still have unsent operations */ recheckAccessNarrowing(pending: (collection: string) => ReadonlySet, options?: { retractedOnly?: boolean; position?: number; view?: string; }): Promise>; /** Drop one record from the records an access narrowing kept (it was re-sent). */ private forgetKeptOutsideNarrowing; private loadKeptOutsideNarrowing; /** The meta write of {@link saveKeptOutsideNarrowing} through `tx` (the cache is the caller's, after the commit). */ private writeKeptOutsideNarrowingInTx; private saveKeptOutsideNarrowing; /** * Hide all live rows that no longer match a newly accepted server scope. With * `shouldContinue`, stops before the next retraction once it returns false (the * sync session that accepted the scope ended) and returns the rows already hidden. */ applyScopeNarrowing(scopes: Record>, options?: { shouldContinue?: () => boolean; position?: number; }): Promise>; /** * Materialize a server scope-entry insert (RT-19) whose fields each carry their * own version (RT-27). The entry restates the record's current server values; a * single whole-row stamp would let a field the server last wrote long ago * overwrite this device's newer unsynced edit of it, after which the device's own * operation uploads and wins on the server (divergence). So every field is resolved * on its own, by last-write-wins against this row's `_field_versions`: * * - no row: inserted with each field stamped at its own version, `_created_at` * at the record's creation (the entry's `timestamp`), then any orphaned * updates/deletes are folded in as for any insert; * - live row, or a row hidden by a scope retraction: per-field LWW (a retracted * row is shown again; `_created_at` is kept); * - domain tombstone: revived only when the entry's newest field version is * newer than the tombstone, then per-field LWW. * * Deterministic and idempotent: the outcome depends only on the stored and * incoming per-field versions, and a re-applied entry wins no field. */ private applyFieldVersionedInsert; /** * Materialize update/delete operations that were logged for a record BEFORE * its insert arrived (reordered delivery). Runs inside the insert's write * transaction, folding each orphan in timestamp order through the exact * per-field LWW / LWW-delete rules the normal apply paths use, so the final * row state equals what a device that received the operations in causal * order computed. Called only when the insert created a previously-absent * row — in that case every logged update/delete for the record is * necessarily an orphan (rows are soft-deleted, never removed, so a row * that is absent now was never materialized). */ private foldOrphanedOperations; /** * Get operations from a node within a sequence number range. * Implements the OperationLog interface for computeDelta. */ getRange(nodeId: string, fromSeq: number, toSeq: number): Promise; /** * Get operations from a node within a sequence number range. */ getOperationRange(nodeId: string, fromSeq: number, toSeq: number): Promise; /** * Load every operation from the local append-only log across all collections. * Used by sync delta computation, backup export, and time-travel replay. */ getAllOperations(): Promise; /** * Rebuild an in-memory snapshot of materialized state at a causal cut in the op log. * Does not mutate the live store — intended for DevTools time-travel inspection. * * @param operationId - Content-addressed id of the operation to replay through (inclusive) * @throws {OperationError} When the operation id is not present in the local log */ replayTo(operationId: string): Promise; /** * Persist a merge trace to the durable audit log. */ appendAuditTrace(trace: PersistedAuditTrace): Promise; private readonly auditQueue; private auditFlushScheduled; private flushAuditQueue; /** * Read persisted audit traces with optional filters. */ getAuditTraces(query?: AuditTraceQuery): Promise; /** * Export operations and merge traces as a portable audit bundle. */ exportAudit(options?: AuditExportOptions): Promise; /** * Get the schema definition. */ getSchema(): SchemaDefinition; /** * The instant-updates overlay of this store, or null when it was not built with * `instantUpdates`. Internal: `createApp` reads it for `app.storage.writes`, tests for * the registry. * * @internal */ getOverlayController(): OverlayController | null; /** * Route local CRUD through the unified apply pipeline (korajs ApplyPipeline). */ setLocalMutationHandler(handler: LocalMutationHandler | null): void; /** * Notify this store that another same-origin runtime committed an operation to * the shared local database. The operation has already been persisted and * materialized by the database owner; this method only advances in-memory causal * watermarks and invalidates local reactive queries so already-open tabs stay * live without reapplying or rewriting the operation. */ notifyExternalOperation(operation: Operation): void; /** * Notify this store that another same-origin runtime changed rows of a collection * in the shared local database without an operation this tab can see (a re-fold, * a scope retraction, a restore; RT-98). Only re-runs the affected live queries. * * @param collection - The collection whose rows changed */ notifyExternalChange(collection: string): void; /** * Listen to every committed change this store makes to collection rows: local * writes, remote applies, and changes without a new operation (re-folds, scope * retraction, cascade settling, rematerialization, restore). The cross-tab bus * relays these to other tabs on the same database (RT-98). * * @returns An unsubscribe function */ onRecordsChanged(listener: RecordsChangeListener): () => void; /** * Build the local write context for a collection: everything the single local * write path needs (used by Collection writes and by ApplyPipeline). */ createMutationContext(collection: string, options?: { extraCausalDeps?: string[]; /** * Stamp the writes with this clock instead of the store's (it must be this * node's). Used for the side effects of a remote delete, stamped right after * the delete like the server's copy (seam 5), never with the device's "now". */ clock?: HybridLogicalClock; }): LocalMutationContext; /** * Load a materialized row by ID, including soft-deleted tombstones. */ findMaterializedRow(collection: string, recordId: string): Promise; /** * A collection's reads through `tx`, with the same SQL and deserialization as * `store.collection(name)` (the same {@link QueryBuilder}, on a read-only view of `tx`). */ private readInTransaction; /** {@link findMaterializedRow} through a given handle (a transaction, or the adapter). */ private findMaterializedRowIn; /** * Raw version state of a materialized row, for optimistic-concurrency guarded * applies: capture this snapshot before computing a merge, pass it as * `guardRowState`, and the apply refuses to write if the row changed since. * Returns null when no row exists (which is itself a valid guard state — the * apply then requires the row to still be absent). */ getRowVersionState(collection: string, recordId: string): Promise; /** * Latest operation from this device for a record (used for delete-vs-update merge on sync). */ /** * Load the last server version vector acknowledged by this client (persisted in `_kora_meta`). */ loadLastAckedServerVector(): Promise; /** * Persist the last server version vector this client believes the server has applied. */ saveLastAckedServerVector(vector: VersionVector): Promise; /** * Load the per-device node token the sync server issued for this node id (RT-12). */ loadNodeToken(nodeId?: string): Promise; /** * Persist the per-device node token under its node id (the current one by default). */ saveNodeToken(token: string, nodeId?: string): Promise; /** * Load the node ids the sync server named authoritative (protocol v2), or null when * no protocol-2 server ever answered. */ loadAuthoritativeNodeIds(): Promise; /** * Persist the node ids the sync server named authoritative (protocol v2). Same as * {@link setAuthoritativeNodeIds}: merged into the union of learned explicit ids, * and the fold re-folds affected records only when that set grows. */ saveAuthoritativeNodeIds(nodeIds: string[]): Promise; /** * Load persisted delta cursor for resuming paginated initial sync. */ loadDeltaCursor(): Promise; /** * Persist or clear the delta cursor for paginated initial sync resume. */ saveDeltaCursor(cursor: string | null): Promise; /** * Load the persisted delivery watermark for a view signature (0 when none recorded). * Defaults to the unfiltered view so existing single-watermark reads keep working. */ loadDeliveryWatermark(signature?: string): Promise; /** * Persist the delivery watermark for a view signature so it survives a client restart. */ saveDeliveryWatermark(signature: string, watermark: number, completion?: OfflineCompletion): Promise; /** * A view's delivery watermark going back to 0 is a full resync (a forced resync, a * snapshot resync, a sequence-conflict recovery): the stream replays the view, so * nothing pending is kept over it (I12). Only reads when something is pending. */ private clearOverlayOnWatermarkReset; /** Record that a delivery unit is about to apply operations (offline-readiness 4.1). */ openOfflineUnit(unit: OfflineUnitKey): Promise; /** Delete every completion mark (clear-before-apply, watermark resets). */ clearOfflineMarks(): Promise; /** Every completion mark and open unit key. */ loadOfflineMarks(): Promise; /** Every pin of `app.offline.keep()`, oldest first. */ loadOfflinePins(): Promise; /** Every component hold on a pin, across all tabs. */ loadOfflinePinHolds(): Promise; /** * `keep()`: record a pin (idempotent) and mark it explicit. Refused past the pin limit * (`OFFLINE_PIN_LIMIT`). Durable when the promise resolves, on the IndexedDB fallback too. */ keepOfflinePin(pin: NewOfflinePin): Promise; /** `release()`: clear the explicit flag; the pin goes when no component holds it. */ releaseOfflinePin(id: string, options?: { stillHeld?: boolean; }): Promise; /** Create a pin without marking it kept by the app (explicit-mode holds). */ ensureOfflinePin(pin: NewOfflinePin): Promise; /** A component starts holding a pin, creating it when absent. */ addOfflinePinHold(pin: NewOfflinePin, hold: Omit): Promise; /** A component stops holding a pin; the pin goes with its last holder unless explicit. */ removeOfflinePinHold(pinId: string, holder: string): Promise; /** Delete the holds of tabs for which `isStale(tabId)` is true, and pins only they kept. */ pruneOfflinePinHolds(isStale: (tabId: string) => boolean): Promise<{ holdsRemoved: number; pinsRemoved: number; }>; /** Record when a pin was last seen complete (display only). */ markOfflinePinCompleted(id: string, at: number | null): Promise; private writeOfflinePins; /** * Resolves once everything committed so far is in a persisted snapshot, without forcing * one. Null on adapters whose commits are durable. */ whenPersisted(): Promise | null; /** * Load every persisted view watermark, keyed by signature. */ loadAllDeliveryWatermarks(): Promise>; /** * Delete a persisted view watermark (safe: the view back-fills from 0 when next visited). */ deleteDeliveryWatermark(signature: string): Promise; /** * Record delivered operations the sync engine deliberately did not apply (inbound * quarantine, W4) and, when given, advance a view's delivery watermark in the same * transaction, so the watermark never passes an operation that is neither applied nor * recorded. */ saveInboundQuarantine(entries: UnappliedOperation[], watermark?: { signature: string; watermark: number; completion?: OfflineCompletion; }): Promise; /** Every quarantined inbound operation, oldest delivery first. */ loadInboundQuarantine(): Promise; /** Remove quarantined inbound operations (applied on replay, or reconciled). */ removeInboundQuarantine(operationIds: string[]): Promise; /** * The contiguous acknowledged prefix of this device's own operations for a node id, * or null when none was recorded under that contract (W3). */ loadOwnAckedThrough(nodeId: string): Promise; /** Persist the contiguous acknowledged own-operation prefix for a node id. */ saveOwnAckedThrough(nodeId: string, sequence: number): Promise; /** The downlink scope the sync server last accepted (null when none). */ loadAcceptedDownlinkScope(): Promise> | null>; /** Persist (or clear) the downlink scope the sync server last accepted. */ /** * Delivery anchors by view signature, each with the watermark it belongs to. The sync * engine reports a view's anchor at handshake only while it still matches the view's * watermark, which is how a server whose log was rewound by a restore recognizes it. */ loadDeliveryAnchors(): Promise>; /** Persist a view's delivery anchor, replacing the previous one. */ saveDeliveryAnchor(signature: string, record: { watermark: number; anchor: string; }): Promise; /** The access read rules' key this device was last fully re-scoped under (null: none). */ loadAccessRulesKey(): Promise; /** Persist the access read rules' key this device was fully re-scoped under. */ saveAccessRulesKey(key: string): Promise; saveAcceptedDownlinkScope(scope: Record> | null): Promise; /** * Local operations not yet reflected on the server version vector. */ getUnsyncedOperations(serverVector: VersionVector): Promise; /** * Move this device to a fresh node id, re-authoring its never-acknowledged * operations under it (RT-21). Used when the sync server refuses the current node * id (`NODE_ID_CLAIMED`): the device keeps every local write and uploads it under * the new id. Acknowledged history stays under the old id. Persisted atomically; * later writes use the new id. * * @param unsyncedOpIds - Ids of this node's operations the server never acknowledged * @returns The new node id and the rewritten operations (for the outbound queue) * @throws {KoraError} When the node id is pinned (`StoreConfig.nodeId`, or per-tab isolation) */ rotateNodeId(unsyncedOpIds: string[]): Promise; /** * Re-author another local node's never-acknowledged operations under a fresh node id * bound to `principal` (the user they belong to). Used when the sync server refuses an * adopted node whose writes belong to the signed-in user (the app assigned them, or * the node was created for them) but which no claims-aware server ever accepted: a * beta.12 database's node with history the server recorded no owner for. The store's * own node id, clock and counters are untouched; the fresh node is registered, so the * sync engine adopts it like any other local node. * * @param fromNodeId - The refused local node (never the store's own) * @param unsyncedOpIds - Ids of its operations the server never acknowledged * @param principal - The user the writes belong to (the fresh node's binding) * @returns The fresh node id and the rewritten operations (for the outbound queue) * @throws {KoraError} `NODE_ID_UNKNOWN` when `fromNodeId` is the store's own node or * not a local node */ reauthorLocalNode(fromNodeId: string, unsyncedOpIds: string[], principal: string): Promise; /** * Re-author a retired local node's operations under this store's own node (a browser * shared between accounts: see `LocalNodeRecord.retired`). The caller passes the ones * the sync server does NOT hold (it asked by id) and that it never refused for good; * the server's version-vector entry for a shared node says nothing about this * database's writes, so it is never used here. Each keeps its type, record, data and * HLC wall time and counter, and takes the own node id (in `nodeId` and * `timestamp.nodeId`), the own node's next sequence numbers (allocated in the same * transaction as every local write's), and a recomputed content id; causal deps among * them are rewritten and materialized versions re-stamped (the node-rotation path). * * When a rewritten timestamp would equal one the own node already used (a device clock * that went back), the operations go to a fresh node bound to the same user instead, * which uploads like any adopted node. * * @param fromNodeId - The retired node (never the store's own) * @param operationIds - Its operations to re-author * @returns The node they now belong to, the rewritten operations and the id mapping * @throws {KoraError} `NODE_ID_UNKNOWN` when `fromNodeId` is the store's own node or not * a retired local node */ reauthorIntoOwnNode(fromNodeId: string, operationIds: string[]): Promise; private reauthorUnderFreshNode; /** * Move this database back to a node id it authored under before (RT-38): after the * sync server refused the current node, the device tries a node a returning user * owns. Nothing is rewritten; later writes use `nodeId`. * * @throws {KoraError} When the node id is pinned, or `nodeId` is not a local node */ switchNodeId(nodeId: string): Promise; /** Point the clock, sequence counter and collections at `nodeId` (already persisted). */ private rebindToNode; /** * Bind this database's writes to the signed-in user (RT-42). Call it whenever the * signed-in user is known or changes, BEFORE the next local write (`createApp` does * so at start and on every auth change of `sync.authClient`). * * - The current node belongs to `principal`: nothing changes. * - The current node is unbound and has no history (no write, never synced): it is * bound to `principal` (every write under it from now on is theirs). * - The current node is unbound but has history (a database from before RT-42, or * writes made while nobody was signed in): its owner is NOT guessed (RT-50). The * store moves to `principal`'s own node, and the old node's owner is learned from * the sync server (the first accepted handshake as it binds it; a refusal rules * that user out). A node that never synced cannot be attributed by anyone: its * unsynced writes are held for the app to assign or discard (`app.sync.assignHeld`, * `app.sync.discardHeld`). * - It belongs to another user: the store moves to `principal`'s own local node (the * most recent one, not held), or to a fresh node bound to `principal`. Nothing is * rewritten: the other user's unsynced writes stay under their node, and sync never * uploads them on this user's session (they count as `heldOperations`). * * A pinned node id (`StoreConfig.nodeId`, such as an auth device id) cannot move: * `conflict` is then true when it belongs to another user, and sync refuses to * upload it under `principal`; an unbound pinned node with history stays unbound * until the server accepts it for a user. Under `per-tab` isolation the tab moves to * a fresh per-tab node. * * @param principal - The signed-in user id * @returns The node now in use and whether it changed */ bindPrincipal(principal: string): Promise; /** * The user signed out: inserts stop stamping `stamp('userId')` fields with the previous * user. The node binding is left as it is (the next sign-in decides it). */ clearSignedInUser(): void; /** * The sync server refused this store's pinned node id because another user owns it * (`owned: true`), or later accepted it (`false`). A pinned node cannot move to a fresh * id, so writes made under it could only ever upload as its owner: while the server * says so, local writes are refused (F9). A no-op for a store whose node is not pinned * (it moves to a fresh node instead). * * @param owned - Whether the server reported the node owned by another user */ setPinnedNodeOwnedElsewhere(owned: boolean): void; /** * Make this store read-only (a reason) or writable again (null). While read-only, every local * write (insert, update, delete, transaction) throws {@link StoreReadOnlyError} before anything * is recorded; reads, subscriptions and incoming sync carry on. It applies to this app instance * only and is not persisted. * * @param reason - Why, in words a person reads ("previewing as Ama"); null to allow writes again */ setReadOnly(reason: string | null): void; /** The reason this store is read-only, or null when it is writable. */ getReadOnlyReason(): string | null; /** Throws when a local write is not allowed now (read-only, or the node is another user's). */ assertWritable(): void; /** Refuse a local write while read-only, or while the pinned node belongs to another user (F9). */ private assertLocalWriteAllowed; private bindPrincipalToNode; /** * A sync handshake as `nodeId` was accepted for `principal` (RT-50): bind an unbound * node (or replace a guessed binding) from the server's answer. */ confirmNodePrincipal(nodeId: string, principal: string): Promise; /** * The sync server refused `nodeId` for `principal` (RT-50): clear a guessed binding, * and remember that an unbound node is not theirs. */ recordNodeRefusedFor(nodeId: string, principal: string): Promise; /** * Assign a held, unbound local node's writes to `principal` (RT-50): an explicit app * decision for writes nobody can attribute (a database that never synced). * * @returns false when the node is unknown, the store's own, already bound, or was * refused for `principal` by the server */ assignNodePrincipal(nodeId: string, principal: string): Promise; /** * Forget a local node other than the store's own whatever it still holds (RT-50: the * app discarded its held writes, which were marked never to upload first). */ dropLocalNode(nodeId: string): Promise; /** The adoption schedule of this database's local nodes (RT-46). */ loadAdoptionSchedule(): Promise; /** Persist the adoption schedule (RT-46). */ saveAdoptionSchedule(schedule: AdoptionSchedule): Promise; /** * Raise a local node's sequence counter to at least `floor`, in a transaction (the * same MAX every reservation uses, W6), so the next write never reuses a number the * server already holds (RT-35: the device lost the tail of its log, for example on a * reload inside the IndexedDB snapshot window or after restoring an older copy). * * @returns Whether the counter moved */ raiseSequenceFloor(nodeId: string, floor: number): Promise; /** * Give one of a local node's operations a fresh sequence number above `floor` * (RT-35): the server refused it with `SEQUENCE_CONFLICT` because it holds another * operation of this node under that number (one this device lost). A version-1 * operation keeps its id (its hash does not cover the sequence number), exactly like * the W6 sequence repair; a version-2 operation (protocol v2) is re-hashed under the * new number, so it carries a new id. The old identity is recorded in * `_kora_seq_conflicts` (`reemitted_as`). * * A new id would leave later operations naming the old one in `causalDeps`: those in * `rewritableDependents` (operations the server never stored: never sent) are * rewritten to name the new id, and re-hashed, transitively, in the same * transaction. Dependents already sent keep their ids (the server may hold them); * their dep resolves through the `_kora_seq_conflicts` record. Every touched record * is re-folded (fold stamps carry operation ids). * * @param rewritableDependents - Ids of this node's operations that were never sent * @returns The renumbered operation and the rewritten dependents, or null when the * operation is not in the log */ resequenceOperation(operationId: string, nodeId: string, floor: number, rewritableDependents?: readonly string[]): Promise; /** * Durability barrier (RT-35): resolves once every write committed so far is durable * on this device. Sync awaits it before an operation leaves the device. */ ensureDurable(): Promise; /** Record operations the server refused for good (RT-36). Never cleared. */ recordTerminalRejections(entries: TerminalRejection[]): Promise; /** Which of these operation ids the server refused for good (RT-36). */ findTerminalRejections(operationIds: string[]): Promise>; /** Every node id this database authored operations under (RT-38, RT-40). */ listLocalNodes(): Promise; /** Forget a drained local node other than this store's own (RT-40). */ forgetLocalNode(nodeId: string): Promise; /** The current refusal cycle: the count of accepted sync handshakes (RT-38). */ loadAcceptedCycle(): Promise; /** Record an accepted sync handshake as `nodeId` (RT-38). */ markLocalNodeAccepted(nodeId: string): Promise; /** Record that the sync server refused `nodeId`; `held` holds its writes (RT-38). */ markLocalNodeRefused(nodeId: string, held: boolean): Promise; /** * Retire another local node whose writes belong to `principal` (bound as `binding`): * it is never used for a session again, and its writes the server does not hold are * re-authored under this store's node ({@link reauthorIntoOwnNode}). */ retireLocalNode(nodeId: string, principal: string, binding: 'app' | 'fresh' | 'database'): Promise; /** * Which of `operations` (all of local node `nodeId`) this database authored itself * rather than received under that node (see `findAuthoredHere` in local-sync-records). */ findAuthoredHere(nodeId: string, operations: ReadonlyArray<{ id: string; sequenceNumber: number; }>): Promise>; /** * Take over another local node's unsynced writes (RT-40): resolves to a release * function when no live tab uses `nodeId` (its lock is free), or null when one does. * Without Web Locks (Node, old browsers) the node is assumed free. */ claimLocalNode(nodeId: string): Promise<(() => void) | null>; /** Whether a live tab holds `nodeId` (per-tab isolation, RT-40). */ isLocalNodeLive(nodeId: string): Promise; /** * Re-stamp never-acknowledged local operations after a fast device clock was * corrected, so sync can resume immediately. Safe because unacknowledged * operations are private to this device (like unpushed git commits); * acknowledged/shared operations are immutable and never touched. * * After the rewrite the store's HLC is advanced past the highest new * timestamp so subsequent local writes keep sorting after the rebased ops. * No data-change notifications are emitted: materialized values are * unchanged, only version stamps move. */ rebaseUnsyncedOperations(unsyncedOpIds: string[], correctedNowMs: number): Promise; /** * Count of local operations ahead of the server version vector. */ countUnsyncedOperations(serverVector: VersionVector): Promise; /** * Compact the local operation log. Only removes ops the server has acknowledged * (per {@link CompactionStrategy}). With the W7 fold (STORE-14), the effect of the * removed operations is first joined into each record's base fold state, so a * re-fold (rejection exclusion, a later re-materialization) and the merge of a * late operation stay exact; delete, atomic and custom-resolver operations are * kept, and a re-delivered compacted id is a duplicate by its node's compacted * prefix. */ compact(strategy: CompactionStrategy): Promise; private compactNow; /** * Merge session remote vector with persisted last-acked vector (max per node). */ mergeServerVectors(sessionVector: VersionVector, persistedVector: VersionVector): VersionVector; getLatestLocalOperationForRecord(collection: string, recordId: string): Promise; /** * Latest operation for a record from any node (for 3-way merge when local op log is empty). */ getLatestOperationForRecord(collection: string, recordId: string): Promise; /** * All operations for a record, sorted in HLC total order (wallTime, logical, * nodeId). Used by the apply pipeline to materialize atomic-op fields by folding * the record's log, matching the server's materialization exactly. */ getOperationsForRecord(collection: string, recordId: string): Promise; /** Expose the subscription manager for direct access (e.g., by QueryBuilder) */ getSubscriptionManager(): SubscriptionManager; /** * Get the sequence manager for offline-safe sequence generation. * @throws {StoreNotOpenError} If the store is not open */ getSequenceManager(): SequenceManager; /** * Create a TransactionContext for atomic multi-collection operations. * The returned context buffers all mutations and commits them atomically. * * After commit, the caller is responsible for notifying subscriptions * and emitting events for each operation. */ createTransaction(): TransactionContext; /** * Execute a function within a transaction. All mutations performed on the * TransactionContext are committed atomically. Subscription notifications * are batched and fired after the commit. * * If the function throws, the transaction is rolled back and the error is re-thrown. * * @param fn - Function receiving a TransactionContext for buffered operations * @returns The operations that were committed */ transaction(fn: (tx: TransactionContext) => Promise): Promise; private transactionNow; /** * Instant updates for a transaction (S6a): predict its sealed buffer as one entry group. * Undefined (the commit runs exactly as without the overlay) unless the store has one. */ private transactionOverlayOptions; /** * Export all data as a portable backup binary. * Includes operations, version vector, metadata, and optionally materialized records. * * @param options - Backup options (includeRecords, collections, onProgress) * @returns Backup as a Uint8Array */ exportBackup(options?: BackupOptions): Promise; /** * Restore data from a backup binary (format version 2, STORE-5). * * - `merge: true`: every backup operation is applied through the remote-apply path * (deduplicated by id, merged per field), the version vector advances by MAX, and * nothing of the exporting device's identity or sync state is imported. * - Replace (default): the data is replaced by the backup's while this device keeps * its node id, local nodes and principal bindings, its own sequence counters never * move backwards, and unsynced own writes are kept (see * `RestoreOptions.keepUnsyncedWrites`). Then {@link reloadFromDisk} runs. * * A version-1 file (Kora 1.0.0-beta.12 and earlier) is converted first, exactly as * `convertBackupV1` does (`result.convertedFromVersion: 1`); one holding an operation * whose timestamp cannot be recovered is refused (`BACKUP_OPERATION_INVALID`). * * @param data - The backup data * @param options - Restore options (merge, collections, keepUnsyncedWrites, onProgress) * @param internal - `applyOperation`: the app's remote-apply path (defaults to * {@link applyRemoteOperation}); `createApp` passes the merge-aware pipeline sync uses * @returns Result of the restore operation */ importBackup(data: Uint8Array, options?: RestoreOptions, internal?: { applyOperation?: (operation: Operation) => Promise; }): Promise; private importBackupNow; /** * Merge mode (RT-66): join the backup's compacted base states and row snapshots * into this database's, and re-fold those records, before the backup's operations * are applied. The join is the fold's state-based merge, so the result equals * folding both devices' histories together. Compacted prefixes advance by MAX * (unfiltered restores only: the prefix is per node, across collections). */ private mergeBackupFoldState; /** * Re-read this store's state from the database after it changed underneath it (a * backup restore): the node id, version vector and own sequence counter, the clock * (advanced past every timestamp in the log), and a fresh causal tracker. Every live * query re-runs. The local node registry and terminal rejections are always read * from the database, so they need no reload. */ reloadFromDisk(): Promise; /** The greatest HLC timestamp in the operation log (canonical strings sort by HLC). */ private loadNewestLogTimestamp; /** * Read backup manifest without loading the entire backup. * * @param data - The raw backup data * @returns The backup manifest */ static readBackupManifest(data: Uint8Array): BackupManifest; private recordOperationSequence; /** Post-commit publication of a committed local operation. */ private publishLocalOperation; /** * Map an out-of-space storage failure to `store:quota-exceeded` (STORE-15). * The error itself still propagates to the caller; this only makes the * condition observable on every adapter, not just IndexedDB. */ private reportStorageError; /** * Whether resolved local writes are durable (`app.storage.writes`). `failing` after a * committed write could not be confirmed on durable storage; `permanent` when its * snapshot lineage was superseded, which holds until the page is reloaded. */ getWriteDurability(): WriteDurabilityState; private reportWriteDurabilityError; private reportWriteDurabilityRestored; /** Report a database a newer storage format opened (`store:format-ahead`), build the error. */ private formatAhead; /** * Run `fn` as one write of this store: refused with `BuildSupersededError` (nothing * started) once the tab is superseded by a newer build, and waited for by retirement * otherwise. The app routes its own write entry points (blobs) through it. */ /** Evidence kept outside the database (null: the adapter keeps none). */ private storageEvidence; /** A detected storage loss the app has not acknowledged yet. */ private storageEviction; trackWrite(scope: WriteScope, fn: () => Promise): Promise; /** * Writes this store admitted that have not settled yet: local writes, transactions and * applied sync batches. A reload while this is above zero can lose a write the user * already saw (instant updates), so updates and unload guards wait for zero. */ pendingWriteCount(): number; /** Resolves once every write admitted so far, and any admitted meanwhile, has settled. Never rejects. */ whenWritesSettled(): Promise; /** Whether this store refuses writes because a newer build superseded its tab. */ isWriteRefused(): boolean; /** Report a database a newer build migrated (`store:schema-ahead`) and build the error. */ private schemaAhead; /** * Run pending schema migrations (STORE-13, NEW-STORE-1): one transaction per version * (DDL, backfills, `schema_version`); backfills write operations through the local * write path so they sync, unless declared `localOnly`. */ private runMigrationsIfNeeded; /** * The pinned node of a database that belongs to one user moved (the user's auth device * id changed: on a browser shared between accounts each account gets its own, and a * beta.12 browser gave every account the same one). The previous node may be shared * with another user's database, so it is retired: never used for a session, adopted or * handed over again. Its writes are this user's (the database is opened only for them); * those the server does not hold are re-authored under this user's node once the server * says which it holds (`reauthorIntoOwnNode`). A retired node that is pinned again is * revived. * * @returns The node ids this database authored its own operations under, for the * sequence-uniqueness repair */ private retireMovedPinnedNode; /** The node id the database persisted before this open, if any. */ private readPersistedNodeId; /** * Register node ids this database authored under that the registry does not know * yet: the node id a pinned `nodeId` (the auth device id) just replaced, and the * authors of queued operations. A beta.12 database had no registry, and a template * app created before its user signed in authored under a random node; once the * store is pinned to the device id, that node's queued writes would otherwise sit in * the queue forever, neither uploaded nor reported. Registered, they are adopted or * held (`status.heldNodes`) like any other local node's writes. Only the outbound * queue is read: received operations never enter it. */ private registerUnregisteredAuthors; private loadOrGenerateNodeId; private loadSequenceNumber; private loadVersionVector; /** * Open a staging replica: a scratch in-memory store of the same schema that a large * first sync is applied into, then merged here in one controlled pass (see * {@link StagingReplica}). Null when this store cannot stage: the adapter has no scratch * database, rows are not fold materializations, an access narrowing kept records for * unsent writes, the log holds quarantined rows, or the schema has a `restrict` * relation (a remote delete is judged against the live children, which staging does not * hold). The caller then replicates straight into this store, as before. */ beginStaging(options?: { explicit?: boolean; cancelWaitMs?: number; }): Promise; /** * Keep the records a read-through answer showed, so this device can answer the same queries * from its own database before replication delivers them (first-visit parity S4b, 5.6). * Seeds are no operations: nothing is logged, sequenced or uploaded. A record the database * already holds history for is not touched, and every skip is reported. * * @param inputs - Records of an answer, in the delivery wire form * @param meta - The frontier and grant key the answer was read at * @returns Which records were seeded and which were skipped, with the reason */ seedRecords(inputs: readonly SeedInput[], meta: SeedMeta): Promise; /** * Delete seeds: all of them, or those of `only`. A seeded record this device never wrote to * is removed as if it had never been read; one it wrote to keeps its snapshot (the marker * goes) so the user's edit stays visible, and is returned as `retained`. Used by the merge, * by a change of grant and by the clear points (sign-out, user switch, resync, restore). */ purgeSeeds(only?: ReadonlyArray<{ collection: string; recordId: string; }>): Promise; /** {@link purgeSeeds} without the open check: a resync can be requested while the store opens. */ private purgeSeedsNow; /** * Drop the row snapshots (RT-68) of records whose real history is now in the log, and * re-fold them exactly. Called after a merge replayed the operations of seeded records. * * @returns The records that still have only a snapshot as history (orphaned), reported * as a `SEED_ORPHANED` persistence notice; they keep the snapshot so edits stay visible */ settleSnapshots(collection: string, ids: readonly string[]): Promise; /** * Delete the seeds read under a grant other than `grantKey` (a revoked membership must not * leave seeded rows behind, 5.6.4). A seed the device has written to is left as it is: the * user's own edit is theirs, and the server judges the upload. * * @returns The seeds that were deleted */ purgeSeedsExceptGrant(grantKey: string): Promise; /** * A clear point (sign-out, user switch, full resync, restore, reload): what was read under * the previous state must not outlive it, whatever the reason, so a failure is never * swallowed. */ private clearSeedsAtClearPoint; /** * Seeds exist only while replication goes to the staging replica (I3): the first remote * operation that reaches the main database for a seeded record releases that record's seed, * so the operation folds exactly as it would have without one. A record the device wrote to * keeps its snapshot until its insert arrives. * * @returns Whether a seed was released */ private releaseSeedFor; private refreshSeedCount; /** The seed markers the database holds. */ listSeeds(): Promise; /** Advance the clock past a seeded record's newest write; false when the clock refuses it. */ private adoptSeedTimestamp; private ensureOpen; } /** * Public-facing collection accessor. Provides CRUD + where. */ interface CollectionAccessor { insert(data: Record, options?: WriteOptions): Promise; /** * Insert several records in ONE storage transaction: all of them or none. Every * row is validated before anything is written; each becomes its own insert * operation, in input order, sharing one `transactionId`. Live queries are * notified once, after the commit. Much faster than an `insert` loop for bulk * writes (one transaction and one commit instead of one per record). * * @returns The inserted records, in input order */ insertMany(rows: readonly Record[], options?: WriteOptions): Promise; findById(id: string): Promise; update(id: string, data: Record, options?: WriteOptions): Promise; delete(id: string, options?: WriteOptions): Promise; where(conditions: Record): QueryBuilder; } /** * What a merge needs from the store it merges into. The store implements this over its * private state, so this module never reaches into the store. */ interface StagingMergeHost { readonly schema: SchemaDefinition; /** Run `fn` as one write transaction on the live database (the store's write gate applies). */ transaction(fn: (tx: Transaction) => Promise): Promise; /** Node ids this database authors under; their operations never copy (see the merge). */ localNodeIds(): Promise>; /** The collection's rows are about to change: instant-update verification must not trust them. */ touchCollection(collection: string): void; /** A merge chunk committed: the version vector in memory follows the one in the database. */ noteVersionVector(entries: ReadonlyMap): void; /** The newest timestamp the merged operations carry; local writes must be stamped after it. */ receiveTimestamp(timestamp: HLCTimestamp): void; /** Re-run live queries over `collection` (once, after the merge). */ invalidate(collection: string): void; /** Apply one operation exactly as the sync engine would (deduplicates, folds, cascades). */ replay(operation: Operation): Promise; /** Throw when this store may not take a merge now (retired tab, closed store). */ assertWritable(): void; /** The tab is shutting down or the engine gave up the merge: stop between chunks. */ shouldContinue(): boolean; /** * A chunk committed: these records of `collection` were copied whole (`copied`) or replayed * through the ordinary path (`contested`). Lets the caller account for what is already live * when the merge ends early. */ noteChunk?(collection: string, copied: readonly string[], contested: readonly string[]): void; /** * Delete read-through seeds (first-visit parity S4b) inside the merge's own transaction, * before the merge looks at what the live database holds: a seeded record the device never * wrote to must be absent, so the staged copy is whole; one it wrote to is kept and * replayed onto. `ids` null means every seed. */ purgeSeeds?(tx: Transaction, collection: string | null, ids: readonly string[] | null): Promise; /** * After the operations of contested records were replayed: drop row snapshots whose record * now has its real history, and report the ones that still have none (they stay, so the * user's edit is not hidden). * * @returns The ids whose snapshot is still the only history, so they are orphaned */ settleSnapshots?(collection: string, ids: readonly string[]): Promise; } /** Outcome of {@link mergeStagingInto}. */ type StagingMergeResult = { kind: 'merged'; /** Operations copied into the live log (replayed ones excluded). */ operations: number; /** Records copied whole. */ records: number; /** Records the live database already knew: their staged operations were replayed. */ contestedRecords: number; /** Staged operations replayed through the ordinary apply path. */ replayedOperations: number; /** Quarantine rows copied. */ quarantined: number; /** Sequence-conflict rows copied with their records (legacy duplicates of a beta.12 log). */ sequenceConflicts: number; /** Main-database transactions the merge used. */ chunks: number; /** Apply events the replica buffered beyond its cap and did not replay. */ eventsDropped?: number; /** `eventsDropped` by event type. */ eventCounts?: Record; /** Exceptions thrown by listeners while the buffered events were replayed (caught). */ listenerErrors?: number; durationMs: number; } | { kind: 'unmergeable'; reason: string; /** The merge stopped because the store closed or the replica was discarded, not because the stream cannot be merged. */ cancelled?: true; }; /** What replaying a buffer did. */ interface ReplicaEventFlush { /** Events not kept at the caps, by event type (reported, never silently dropped). */ summarized: Record; /** Listener exceptions caught while replaying (a listener must not undo a committed merge). */ listenerErrors: number; } /** * The events of a replica's applies (operation applied, merge traces, constraint reports). * The replica's operations are not in the live database yet, so nothing is published about * them: the events are kept and replayed in order to the live listeners once the merge has * committed ("events after commit only"), in slices so replaying cannot stall the page. * Applies and the rarer, more important merge/constraint events have separate budgets; * what exceeds a budget is counted by type and reported with the merge. `query:*` events are * not kept (nothing subscribes to the replica; the merge invalidates the live queries itself) * and a storage failure of the replica is reported at once. */ declare class ReplicaEventBuffer implements KoraEventEmitter { private readonly live; private readonly inner; private events; private appliedKept; private otherKept; private summarized; constructor(live: KoraEventEmitter | null); on(type: T, listener: KoraEventListener): () => void; off(type: T, listener: KoraEventListener): void; emit(event: KoraEventByType): void; /** * Replay the kept events to `live` in order. `only` limits the replay to events about * records it accepts (the records an unfinished merge already made live); events about no * record are kept only with `keepKeyless`. */ flush(only?: (recordKey: string) => boolean, keepKeyless?: boolean): Promise; /** Forget everything kept (the replica was discarded). */ clear(): void; } /** Where the merged replica's delivery progress lands in the live database. */ interface StagingProgress { /** The delivery view (its signature) the staged stream belonged to. */ signature: string; /** The delivery watermark the staged stream reached: every in-scope operation up to it is staged. */ watermark: number; /** The completion mark of a final batch, written in the same transaction as the watermark. */ completion?: OfflineCompletion; /** Whether the position the stream was received at still stands (asked inside every merge transaction). */ isCurrent?: () => boolean; } /** What {@link StagingReplica.merge} may do beyond copying. */ interface StagingMergeOptions { /** * Apply one staged operation the live database already has history for, exactly as the * sync engine would (default: `Store.applyRemoteOperation`). `MergeAwareSyncStore` passes * its pipeline, so referential cascades and constraint reports are the ordinary ones. */ replay?: (operation: Operation) => Promise; } /** * A scratch replica of the live database that a large first sync is applied into before it * is merged (`docs/design/first-visit-parity.md` 6). * * `store` is an ordinary {@link import('../store/store').Store} over an in-memory database of * the same engine, so `applyRemoteBatch`, the batch prefetch and the fold run unmodified; its * delivery watermark, version vector and quarantine rows are its own. Nothing reads it but the * merge, and nothing about it survives the page: a crash, a reload or a replaced worker loses * it, and replication simply starts again from the live database's watermark (decision D10). * Because it is in memory it has no rollback journal to write, which is where the first sync's * cost went (docs/design/first-visit-parity.md 6, "The replica"). */ declare class StagingReplica { /** The staging store the engine applies delivery batches into. */ readonly store: Store; private readonly staging; private readonly host; private readonly authoritiesUnchanged; private readonly release; private readonly events; /** How long `discard()` waits for a running chunk (injectable for tests). */ private readonly cancelWaitMs; private closed; private cancelled; private merging; private mergeRun; /** Records (`collection\0id`) a merge that has not finished already copied whole into the live database. */ private readonly copiedRecords; /** Records (`collection\0id`) the live database already knew, merged through the ordinary apply path. */ private readonly contestedRecords; /** @internal Created by `Store.beginStaging`. */ constructor( /** The staging store the engine applies delivery batches into. */ store: Store, staging: StorageAdapter, host: StagingMergeHost, authoritiesUnchanged: () => boolean, release: () => void, events: ReplicaEventBuffer, /** How long `discard()` waits for a running chunk (injectable for tests). */ cancelWaitMs?: number); /** The replica's event buffer: hand it to the replica's merge-aware store as its emitter. */ get emitter(): KoraEventEmitter; /** Whether the replica was discarded, cancelled or merged away (a running merge stops between chunks). */ isClosed(): boolean; /** Bytes the replica's database holds (pages in use times page size). */ sizeBytes(): Promise; /** * Merge everything staged into the live database and write `progress` in the last * transaction. On `merged` the replica is closed. On `unmergeable` it is closed too: the * caller replicates again from the live watermark (nothing wrong stays behind: the chunks * that committed hold whole records, and the events of their records are replayed). */ merge(progress: StagingProgress, options?: StagingMergeOptions): Promise; private runMerge; /** * Drop the replica and everything in it. A merge in flight is cancelled and awaited (a * bounded wait), so no chunk commits after this resolves and the live database's overlay * guard is not released under a running write. Safe to call more than once. */ discard(): Promise; private finish; } /** * Compute per-node sequence watermarks safe to compact (server has acknowledged these ops). */ declare function computeAckCompactionWatermark(serverVector: VersionVector): VersionVector; /** * Remove acknowledged, materialized operation log entries from `_kora_ops_*` tables. * Does not modify collection rows — they are the compaction baseline snapshot. */ declare function compactOperationLog(adapter: StorageAdapter, schema: SchemaDefinition, strategy: CompactionStrategy, serverVector: VersionVector): Promise; /** * How a database is re-materialized on its first open with the W7 fold: * * - `'log'`: the log is clean (W8 integrity scan): every record is rebuilt with the * fold from its operations. This also repairs replicas that diverged under the * pairwise merge of beta.12/13. * - `'snapshot+log'`: the log is not complete (it was compacted, or has sequence * gaps): each existing row becomes the record's row snapshot (its values at * their `_field_versions`, exact where a stored fold state still has them), and * the remaining operations are folded on top. * - `'kept'`: the log has quarantined rows (W8). Only the records that own a * quarantined row are kept exactly as they are (their row becomes their snapshot, * nothing is rebuilt from their log); every other record is rebuilt as in `'log'` * or `'snapshot+log'` (RT-68). * * Row snapshots are approximate (see `createSnapshotState`); records that fold * against one are listed in `_kora_fold_snapshot` until their history is complete * again (a scope entry with the server's fold state, or a full resync). */ type RematerializationMode = 'log' | 'snapshot+log' | 'kept'; declare const LAST_ACKED_SERVER_VECTOR_META_KEY = "last_acked_server_vector"; /** * Serialize a version vector for `_kora_meta` storage. */ declare function serializeVersionVectorToMeta(vector: VersionVector): string; /** * Deserialize a version vector from `_kora_meta`. */ declare function deserializeVersionVectorFromMeta(value: string): VersionVector; /** * Merge two version vectors, keeping the maximum sequence per node. */ declare function mergeVersionVectors(a: VersionVector, b: VersionVector): VersionVector; /** * Operations present locally but not yet on the server (per server version vector). */ declare function collectOperationsAheadOfServer(localVector: VersionVector, serverVector: VersionVector, fetchRange: (nodeId: string, fromSeq: number, toSeq: number) => Promise): Promise; /** * Durable-storage state of this origin, as far as Kora knows (NEW-STORE-4). * - `unknown`: not checked yet (the boot check runs in the background). * - `persisted`: the browser granted persistent storage; it will not evict this * origin's data under storage pressure. * - `best-effort`: storage may be evicted under pressure (the browser default). * - `unsupported`: the runtime has no StorageManager persistence API (Node, * older browsers, some WebViews). * - `error`: the check or request threw; `lastError` says why. */ type StoragePersistenceState = 'unknown' | 'persisted' | 'best-effort' | 'unsupported' | 'error'; /** Snapshot returned by `app.storage.persistence.status()`. */ interface StoragePersistenceStatus { state: StoragePersistenceState; /** True only when the browser reported persistent storage. */ persisted: boolean; /** True once `persist()` was asked for (explicitly or by an automatic trigger). */ requested: boolean; /** Message of the last failure, when `state` is `error`. */ lastError?: string; } /** Why an automatic (background) persistence request was made. */ type PersistenceRequestReason = 'explicit' | 'sign-in' | 'first-write' | 'installed-app' | 'offline-keep'; /** The subset of `navigator.storage` used here. */ interface PersistenceStorageManager { persist?: () => Promise; persisted?: () => Promise; } /** Options for {@link StoragePersistence}. */ interface StoragePersistenceOptions { /** Receives `storage:persistence` events. */ emitter?: KoraEventEmitter | null; /** * The StorageManager to use. Defaults to `globalThis.navigator.storage`, * resolved on each call so tests and late polyfills are honoured. */ storage?: PersistenceStorageManager | null; } /** * Tracks and requests durable storage (`navigator.storage.persist()`) without ever * putting it on the startup path (NEW-STORE-4). * * In Firefox `persist()` opens a permission prompt and its promise stays pending * until the user answers, so awaiting it inside startup could hang `app.ready` * forever. Kora therefore: * - checks `persisted()` at boot, which never prompts, in the background; * - requests persistence only on an explicit `request()` or, without awaiting, * after a meaningful moment (sign-in, the first local write, running as an * installed app); * - surfaces every result through `status()` and the `storage:persistence` event, * never by blocking. */ declare class StoragePersistence { private current; private inFlightRequest; private readonly emitter; private readonly storageOverride; constructor(options?: StoragePersistenceOptions); /** Synchronous snapshot of the last known state. Never prompts. */ status(): StoragePersistenceStatus; /** * Read whether storage is already persistent (`navigator.storage.persisted()`). * Never prompts and never throws: a failure becomes `state: 'error'`. */ check(): Promise; /** * Ask the browser for persistent storage (`navigator.storage.persist()`). * May show a permission prompt (Firefox), so call it from a user gesture or a * meaningful moment, and do not block rendering on it. Concurrent calls share * one request. Never throws: a failure becomes `state: 'error'`. * * @returns The state after the browser answered */ request(): Promise; /** * Fire-and-forget `request()` for an automatic trigger. Never awaited by Kora, * so a pending prompt cannot block anything; the outcome arrives as a * `storage:persistence` event. Skipped when storage is already persistent or a * request was already made this session. * * @param _reason - Which trigger fired (kept for tracing at call sites) */ requestInBackground(_reason: PersistenceRequestReason): void; private storage; private update; private emit; } /** * Bloom filter for subscription dependency tracking. * * Each subscription adds its watched collection (and optionally fields) to the * filter. When a mutation arrives, we check "collection" and "collection:field" * keys against the filter. A negative result means no subscription cares about * this mutation, so we can skip the expensive per-subscription scan. * * @example * ```typescript * const filter = new SubscriptionBloomFilter(100, 0.01) * filter.add('todos') * filter.add('todos', 'completed') * * filter.mightContain('todos') // true (definitely added) * filter.mightContain('projects') // false (definitely not added) * filter.mightContain('todos', 'completed') // true (definitely added) * ``` */ declare class SubscriptionBloomFilter { private bits; private readonly bitCount; private readonly hashCount; private itemCount; constructor(expectedItems: number, falsePositiveRate?: number); /** * Add a collection (and optional field) to the bloom filter. * * @param collection - Collection name (e.g., "todos") * @param field - Optional field name (e.g., "completed") */ add(collection: string, field?: string): void; /** * Check if a collection (and optional field) might be in the filter. * * A return value of `false` means the item is DEFINITELY NOT in the filter. * A return value of `true` means the item MIGHT be in the filter (possible false positive). * * @param collection - Collection name to check * @param field - Optional field name to check * @returns false = definitely absent, true = possibly present */ mightContain(collection: string, field?: string): boolean; /** * Reset the bloom filter, clearing all bits and the item count. */ clear(): void; /** * Estimate the current false positive rate based on the number of items inserted. * * Formula: (1 - e^(-kn/m))^k * where k = hash count, n = item count, m = bit count. * * @returns Estimated false positive rate as a number between 0 and 1 */ estimatedFalsePositiveRate(): number; /** * @returns The number of items that have been added to the filter */ getItemCount(): number; /** * @returns The total number of bits in the filter */ getBitCount(): number; /** * @returns The number of hash functions used */ getHashCount(): number; /** * Count the number of bits currently set to 1. * Uses Brian Kernighan's algorithm: each iteration clears the lowest set bit, * so the loop runs exactly as many times as there are set bits. * * @returns Number of bits set to 1 */ getSetBitCount(): number; /** * Compute k bit positions for a given key using Kirsch-Mitzenmacker double hashing. * * Instead of computing k independent hash functions, we compute two base hashes * (h1 and h2) and derive the rest as: h_i = (h1 + i * h2) mod m. * This technique is proven to have the same asymptotic false positive rate as * k independent hash functions. * * We derive h1 and h2 from a single FNV-1a hash by splitting and mixing: * h1 = fnv1a(key), h2 = fnv1a(key + "\0salt") to ensure independence. */ private getPositions; } /** * Error thrown when a local mutation attempts an invalid state transition. * * Contains enough context to debug without reproduction: * the collection, record, field, current state, attempted state, and allowed transitions. */ declare class InvalidStateTransitionError extends KoraError$1 { readonly collection: string; readonly recordId: string; readonly field: string; readonly fromState: string; readonly toState: string; readonly allowedStates: string[]; constructor(collection: string, recordId: string, field: string, fromState: string, toState: string, allowedStates: string[]); } /** * Validates a state machine transition for a local mutation (insert or update). * * For inserts: validates that the initial state (from the data or the default value) * is a known state in the state machine. * * For updates: looks up the current state field value and checks whether * the transition to the new value is allowed. * * @param collectionName - Name of the collection * @param recordId - The record being mutated * @param stateMachine - The state machine definition * @param currentState - The current value of the state field (null for inserts) * @param newState - The new value being set for the state field * @returns An object indicating whether the transition is valid, and if not, the allowed states. * When `onInvalidTransition` is 'last-valid-state', callers should suppress the field update * rather than throwing. */ declare function validateStateTransition(collectionName: string, recordId: string, stateMachine: StateMachineDefinition, currentState: string | null, newState: string): { valid: boolean; allowedStates: string[]; }; /** * Checks whether a collection update data object contains a change to the state machine field, * and if so, validates the transition. * * If the state field is not in the update data, returns the data unchanged. * If the transition is invalid and mode is 'last-valid-state', removes the field from the data. * If the transition is invalid and mode is 'reject', throws InvalidStateTransitionError. * * @param collectionName - Name of the collection * @param recordId - The record being updated * @param collectionDef - The collection definition from the schema * @param currentRecord - The current record data (must include the state field) * @param updateData - The partial update data * @returns The update data, potentially with the state field removed if invalid and mode is 'last-valid-state' */ declare function validateUpdateStateMachine(collectionName: string, recordId: string, collectionDef: CollectionDefinition, currentRecord: Record, updateData: Record): Record; /** User identity for collaborative cursor presence. */ interface RichTextAwarenessUser { name: string; color: string; avatar?: string; } /** Remote collaborator cursor for a richtext field. */ interface RichTextCursorInfo { clientId: number; userName: string; color: string; anchor: number; head: number; } /** Minimal sync surface required for richtext collaboration. */ interface RichTextSyncEngine { getRichtextDocChannel?(): RichTextDocChannel; getAwarenessManager(): RichTextAwarenessManager; } interface RichTextDocChannel { shouldUseChannel(snapshotBytes: number, useDocChannel?: boolean): boolean; send(collection: string, recordId: string, field: string, update: Uint8Array): void; subscribe(collection: string, recordId: string, field: string, listener: (update: Uint8Array) => void): () => void; } interface RichTextAwarenessManager { clientId: number; getLocalState(): RichTextAwarenessState | null; setLocalState(state: RichTextAwarenessState): void; getStates(): Map; on(event: 'change', listener: () => void): () => void; } interface RichTextAwarenessState { user: RichTextAwarenessUser; cursor?: { collection: string; recordId: string; field: string; anchor: number; head: number; }; } interface CreateRichTextControllerOptions { collection: CollectionAccessor; collectionName: string; recordId: string; fieldName: string; store: { collection(name: string): CollectionAccessor; }; syncEngine?: RichTextSyncEngine | null; useDocChannel?: boolean; user?: RichTextAwarenessUser; } interface RichTextControllerSnapshot { ready: boolean; error: Error | null; canUndo: boolean; canRedo: boolean; cursors: readonly RichTextCursorInfo[]; /** * True while local edits are not in a successful save: a save is pending, in * flight, or was refused (see `error`). The edits stay in the live document and * are saved by the next edit or `retrySave()`. */ hasUnsavedChanges: boolean; } interface RichTextController { readonly doc: yjs.Doc; readonly text: yjs.Text; getSnapshot(): RichTextControllerSnapshot; subscribe(listener: () => void): () => void; undo(): void; redo(): void; setCursor(anchor: number, head: number): void; clearCursor(): void; setUser(user: RichTextAwarenessUser | undefined): void; /** * Save the live document now (for example after a refused save, once the cause * is fixed). Resolves when the save settled; its outcome is in the snapshot. */ retrySave(): Promise; /** * The full document state (a Yjs update) while local edits are unsaved, else * null. Keep it as a recovery copy when saves keep failing. */ getUnsavedState(): Uint8Array | null; /** Stop syncing; edits still waiting for the debounced save are saved first. */ destroy(): void; } /** * Framework-agnostic richtext binding: Yjs document lifecycle, persistence, * incremental doc channel, and awareness cursors. * * Every save writes the full state of the live Y.Doc, which holds every local edit * and every merged remote change, so a stored change arriving while a save waits * cannot drop local typing. A refused save keeps the edits unsaved * (`hasUnsavedChanges`, `getUnsavedState()`) and the next edit or `retrySave()` * saves them again; the first successful save clears `error`. */ declare function createRichTextController(options: CreateRichTextControllerOptions): RichTextController; /** * Narrows a sync engine reference to the richtext controller surface. * SyncEngine satisfies this interface at runtime; types live in different packages. */ declare function asRichTextSyncEngine(engine: unknown): RichTextSyncEngine | null; type RichtextInput = string | Uint8Array | ArrayBuffer | null | undefined; /** * Encodes richtext values into Yjs document updates. * * Also accepts the tagged `{ $koraBytes }` form that binary richtext values * take inside `op.data` (and, for old dev databases, the pre-fix numeric-key * object shape), so every consumer that writes op-data values to columns * inherits the decoding. Plain strings keep their exact historical behavior: * encoded as a fresh Yjs document containing the string. */ declare function encodeRichtext(value: RichtextInput | KoraBytesValue): Uint8Array | null; /** * Decodes driver-provided richtext values into Uint8Array. */ declare function decodeRichtext(value: unknown): Uint8Array | null; /** * Reads plain text from a richtext Yjs state update. */ declare function richtextToPlainText(value: RichtextInput): string; /** * Compares two richtext values by decoded plain text. * Yjs update bytes are not stable across separate encodes of the same string. */ declare function richtextStatesEqual(a: unknown, b: unknown): boolean; /** * Minimal pluralization/singularization utilities for relation name resolution. * Handles common English patterns — not meant to be exhaustive. */ /** * Pluralize a word using common English rules. * * @example * ``` * pluralize('project') // 'projects' * pluralize('category') // 'categories' * pluralize('match') // 'matches' * ``` */ declare function pluralize(word: string): string; /** * Singularize a word using common English rules. * * @example * ``` * singularize('projects') // 'project' * singularize('categories') // 'category' * singularize('matches') // 'match' * ``` */ declare function singularize(word: string): string; /** Current backup format version. */ declare const BACKUP_VERSION = 2; /** A backup file this release cannot restore as-is. */ declare class BackupFormatError extends KoraError$1 { constructor(message: string, code: string, context?: Record); } /** * Export a backup (format version 2) from an opened database. * * Everything is read inside one transaction, so the backup is a consistent snapshot. * Operations are exported in canonical form (exactly what `deserializeOperation` reads * back), including tombstones, so a restore rebuilds the same log. * * @param adapter - The storage adapter * @param schema - The schema definition * @param nodeId - Node id of the exporting device (informational only; never imported) * @param schemaVersion - Schema version * @param options - Backup options * @returns Backup as a Uint8Array */ declare function exportBackup(adapter: StorageAdapter, schema: SchemaDefinition, nodeId: string, schemaVersion: number, options?: BackupOptions): Promise; /** * Read backup manifest without loading the entire backup. * * @param data - The raw backup data * @returns The backup manifest */ declare function readBackupManifest(data: Uint8Array): BackupManifest; /** * Validate the backup checksum. * * @param data - The raw backup data * @returns True if the checksum is valid */ declare function verifyBackupChecksum(data: Uint8Array): Promise; /** Options for {@link convertBackupV1}. */ interface ConvertBackupV1Options { /** * Drop operations whose timestamp cannot be recovered instead of refusing the file. * Default false. */ dropUnrecoverable?: boolean; } /** * Convert a version-1 backup (Kora 1.0.0-beta.12 and earlier) to version 2. * * - Operations: a v1 file exported from a database that a v1 restore had damaged holds * misread timestamps (`wallTime: null`); they are recovered from the misread values * (the same rule as the log-integrity scan). An unrecoverable one refuses the file * unless `dropUnrecoverable` is set. * - The `meta` section (the exporting device's node id, node tokens, sync state) is * dropped: it must never be imported into another database. * - Record rows are kept; v1 exported live rows only, so the manifest records * `includesTombstones: false`. Bytes that v1 serialized as `{"0":..,"1":..}` objects * are decoded on restore. * * @throws {BackupFormatError} When the input is not a valid version-1 backup */ declare function convertBackupV1(data: Uint8Array, options?: ConvertBackupV1Options): Promise; /** * Restore a backup into the database behind `adapter`. * * @deprecated Use `store.importBackup()` / `app.importBackup()`: restoring needs the * store (the device's identity, version vector, clock and live queries). This entry * point opens a temporary `Store` on `adapter`, imports, and CLOSES the adapter. * * @param adapter - A storage adapter no store is using * @param schema - The schema definition * @param data - The backup data * @param options - Restore options */ declare function restoreBackup(adapter: StorageAdapter, schema: SchemaDefinition, data: Uint8Array, options?: RestoreOptions): Promise; /** * Build a {@link PersistedAuditTrace} from a merge-related Kora event. */ declare function persistedAuditTraceFromEvent(event: Extract): PersistedAuditTrace; /** * Decode an audit export binary into structured data. */ declare function decodeAuditExport(data: Uint8Array): AuditExportPayload; /** * Read only the manifest from an audit export without decoding all sections. */ declare function readAuditExportManifest(data: Uint8Array): AuditExportManifest; /** * Verify the checksum of an audit export file. */ declare function verifyAuditExportChecksum(data: Uint8Array): Promise; /** * The minimal directory abstraction an {@link OpfsBlobStore} needs. Blobs are * laid out as `/` (shard = first two hex chars of the hash) so a * single directory never holds millions of entries. * * The real backend ({@link createOpfsBlobDirectory}) is the browser Origin * Private File System; tests supply an in-memory implementation. Keeping this * port small means the content-addressed logic (hashing, integrity, dedup, * sharding) is fully testable without a browser. */ interface OpfsBlobDirectory { /** Read the bytes at `/`, or null if absent. */ read(shard: string, name: string): Promise; /** * Write bytes at `/`, creating the shard directory as needed. * Must be atomic: a crash mid-write may not leave a partially-written file * that a later read would trust. */ write(shard: string, name: string, bytes: Uint8Array): Promise; /** Remove `/`. Returns whether anything was removed. */ remove(shard: string, name: string): Promise; /** Whether `/` exists. */ has(shard: string, name: string): Promise; /** Count of stored blobs across all shards (temp files excluded). */ count(): Promise; /** Every stored blob name (hash) across all shards (temp files excluded). */ keys(): Promise; } /** * A persistent {@link ContentAddressedBlobStore} for the browser, backed by the * Origin Private File System (OPFS) — the same durable storage the SQLite WASM * adapter uses. Blobs survive reloads, are sharded by hash prefix, deduplicated, * and integrity-verified on read (the returned bytes are checked to hash to the * requested key). Writes commit atomically so a torn write cannot surface as * trusted data. * * The store itself is environment-neutral: it talks to an {@link OpfsBlobDirectory}. * Use {@link createOpfsBlobStore} in a browser to get one backed by real OPFS. */ declare class OpfsBlobStore implements ContentAddressedBlobStore { private readonly dir; readonly durable = true; constructor(dir: OpfsBlobDirectory); private shardFor; put(bytes: Uint8Array, metadata?: BlobRefMetadata): Promise; get(hash: string): Promise; has(hash: string): Promise; delete(hash: string): Promise; size(): Promise; list(): Promise; } /** * Create an {@link OpfsBlobDirectory} backed by the browser's Origin Private * File System, rooted at a named subdirectory. It does not request persistent * storage: that is `app.storage.persistence`, kept off the startup path. * * @param rootDirName - The OPFS subdirectory to store blobs under (default `kora-blobs`) * @throws {KoraError} `OPFS_UNAVAILABLE` if OPFS is unavailable (e.g. called outside a browser) */ declare function createOpfsBlobDirectory(rootDirName?: string): Promise; /** * Create a persistent {@link OpfsBlobStore} backed by real browser OPFS. * * @param rootDirName - The OPFS subdirectory to store blobs under (default `kora-blobs`) * @throws {KoraError} `OPFS_UNAVAILABLE` if OPFS is unavailable (e.g. called outside a browser) */ declare function createOpfsBlobStore(rootDirName?: string): Promise; /** Default chunk size for out-of-band blob transfer (256 KiB). */ declare const DEFAULT_CHUNK_SIZE: number; /** * A manifest describing how a blob is split into content-addressed chunks. * * The manifest is small and travels with the operation stream (or alongside it); * the chunk bytes travel out of band. Because every chunk is content-addressed, * identical chunks across blobs are stored and transferred once, and a peer only * ever requests chunk hashes it does not already hold. */ interface BlobManifest { /** Hex SHA-256 hash of the full reassembled blob (its content address). */ blobHash: string; /** Total size of the full blob in bytes. */ size: number; /** The chunk size used to split the blob. */ chunkSize: number; /** Ordered hashes of each chunk. Repeats when identical chunks recur. */ chunkHashes: string[]; mimeType?: string; filename?: string; } /** Optional metadata carried on a manifest. */ interface BlobManifestMetadata { mimeType?: string; filename?: string; } /** * Split a blob into content-addressed chunks and produce its manifest. * * @param bytes - The full blob content * @param chunkSize - Bytes per chunk (defaults to {@link DEFAULT_CHUNK_SIZE}) * @param metadata - Optional mime type / filename to record on the manifest * @returns The manifest and a map of chunk hash to chunk bytes (deduplicated) */ declare function chunkBlob(bytes: Uint8Array, chunkSize?: number, metadata?: BlobManifestMetadata): Promise<{ manifest: BlobManifest; chunks: Map; }>; /** * Reassemble a blob from chunks held in a content-addressed store, verifying * integrity at both levels: each chunk is verified by the store on read, and the * reassembled whole is verified against the manifest's blob hash. * * @param manifest - The blob manifest * @param chunkStore - A store holding the chunk bytes keyed by chunk hash * @returns The full reassembled blob bytes * @throws {BlobIntegrityError} If the reassembled bytes do not match blobHash * @throws {KoraError} `BLOB_CHUNK_MISSING` if a chunk named in the manifest is missing from the store */ declare function reassembleBlob(manifest: BlobManifest, chunkStore: ContentAddressedBlobStore): Promise; /** * A source of chunk bytes on the sending side of a transfer. In production this * is backed by the sync connection (the receiver requests a chunk hash, the peer * that holds the blob answers with the bytes); in tests it is backed by a map. */ interface ChunkProvider { /** * Fetch the bytes for a chunk hash, or null if the provider does not have it. A * provider may instead reject with a `BlobTransferError` that carries its own * diagnostics (the remote provider does, with the attempts it sent). */ getChunk(hash: string): Promise; } /** Result of receiving a blob out of band. */ interface ReceiveBlobResult { /** The content-addressed reference to the reassembled blob. */ ref: BlobRef; /** Number of chunks actually fetched from the provider. */ chunksFetched: number; /** Number of chunks skipped because they were already held locally. */ chunksSkipped: number; } /** Stores used while receiving a blob. */ interface ReceiveBlobStores { /** * Where fetched chunks are staged, keyed by chunk hash. A persistent chunk * store makes a transfer resumable: an interrupted transfer leaves its chunks * here, and a resumed transfer skips them. */ chunkStore: ContentAddressedBlobStore; /** Where the fully reassembled, verified blob is written. */ blobStore: ContentAddressedBlobStore; } /** * Receive a blob out of band, chunk by chunk, resumably and with integrity * verification at every step. * * For each chunk named in the manifest: if the chunk store already holds it (a * prior, possibly interrupted transfer), it is skipped; otherwise it is fetched * from the provider and verified to hash to the expected chunk hash before being * staged. Once every chunk is present, the blob is reassembled, verified against * the manifest's blob hash, and written to the blob store (which deduplicates). * * The transfer is idempotent: running it again after completion fetches nothing * and returns the same reference. * * @param manifest - The manifest of the blob to receive * @param provider - The source of chunk bytes * @param stores - The chunk staging store and the destination blob store * @returns The reference plus how many chunks were fetched versus skipped * @throws {BlobIntegrityError} If a fetched chunk or the whole blob fails verification * @throws {BlobTransferError} If a required chunk cannot be obtained: `BLOB_CHUNK_UNAVAILABLE` * when the provider answers that nobody holds it, or the provider's own code * (`BLOB_CHUNK_TIMEOUT`, `BLOB_CHUNK_CANCELLED`) */ declare function receiveBlob(manifest: BlobManifest, provider: ChunkProvider, stores: ReceiveBlobStores): Promise; /** * Prepare a blob for out-of-band sending: split it into chunks, stage those * chunks in a content-addressed store, and return the manifest plus a * {@link ChunkProvider} that serves the chunks from that store. * * @param bytes - The full blob content * @param chunkStore - Where to stage the chunks (served to receivers) * @param options - Optional chunk size and metadata * @returns The manifest and a provider that serves the staged chunks */ declare function prepareBlobForSend(bytes: Uint8Array, chunkStore: ContentAddressedBlobStore, options?: { chunkSize?: number; mimeType?: string; filename?: string; }): Promise<{ manifest: BlobManifest; provider: ChunkProvider; }>; /** * Serialize a {@link BlobManifest} to canonical bytes for content addressing. * * Fields are emitted in a fixed order so the same manifest always produces the * same bytes, which is what lets the manifest be stored and fetched under its own * SHA-256 hash. Optional fields are omitted when absent. */ declare function serializeBlobManifest(manifest: BlobManifest): Uint8Array; /** * Parse canonical manifest bytes back into a {@link BlobManifest}, validating the * shape. Throws on malformed input rather than returning a partial manifest. */ declare function parseBlobManifest(bytes: Uint8Array): BlobManifest; /** * Store a blob for out-of-band transfer, addressed entirely by content. * * Stages the blob's chunks (so this device can serve them), stores the full blob * (so local reads by hash are O(1)), and stores the blob's manifest as its own * content-addressed object. The returned {@link BlobRef} carries `manifestHash`, * so a peer that receives the reference in a synced record can pull the bytes * knowing only the reference — no separate manifest hand-off. * * @param store - The content-addressed store to stage chunks, blob, and manifest in * @param bytes - The full blob content * @param options - Optional chunk size and metadata * @returns The reference (including `manifestHash`) and the manifest */ declare function putBlobForTransfer(store: ContentAddressedBlobStore, bytes: Uint8Array, options?: { chunkSize?: number; } & BlobRefMetadata): Promise<{ ref: BlobRef; manifest: BlobManifest; }>; /** * Fetch and integrity-verify a blob's manifest from a {@link ChunkProvider}. * * The manifest is a content-addressed object like a chunk, so it is requested by * its hash, verified to hash to that value, and parsed. Used to resolve a * {@link BlobRef}'s manifest before pulling the blob's chunks. * * @param provider - The source to fetch the manifest bytes from * @param manifestHash - The manifest's content hash (from `BlobRef.manifestHash`) * @throws {BlobIntegrityError} If the fetched bytes do not hash to `manifestHash` * @throws {BlobTransferError} If the provider cannot supply the manifest (`BLOB_CHUNK_UNAVAILABLE`, * or the provider's own code) */ declare function fetchBlobManifest(provider: ChunkProvider, manifestHash: string): Promise; /** * Resolve the manifest for a {@link BlobRef} that was stored via * {@link putBlobForTransfer}. Fetches and verifies the manifest by the ref's * `manifestHash`. * * @throws {KoraError} `BLOB_MANIFEST_MISSING` if the ref has no `manifestHash` (it was not stored for transfer) */ declare function resolveBlobManifest(provider: ChunkProvider, ref: BlobRef): Promise; /** Why a blob chunk request ended without bytes. */ declare const BLOB_TRANSFER_ERROR_CODES: readonly ["BLOB_CHUNK_TIMEOUT", "BLOB_CHUNK_UNAVAILABLE", "BLOB_CHUNK_CANCELLED"]; type BlobTransferErrorCode = (typeof BLOB_TRANSFER_ERROR_CODES)[number]; /** * Why the last attempt of a blob chunk request did not produce bytes: * `not-connected` (the last try could not be sent; with `attempts` 0 the request never * left the device), `timeout` (sent, no answer), * `throttled` (the server asked to retry later), `not-held` (answered: nobody holds * it), `closed` (the provider was closed). */ type BlobChunkFailureReason = 'not-connected' | 'timeout' | 'throttled' | 'not-held' | 'closed'; /** * A blob chunk could not be obtained. The transfer is resumable: chunks already * received are kept, so pulling the blob again later fetches only what is missing. * * `code` tells "lost" from "refused": `BLOB_CHUNK_TIMEOUT` (nothing answered in time, * after retries), `BLOB_CHUNK_UNAVAILABLE` (answered: no reachable peer or server * holds it), `BLOB_CHUNK_CANCELLED` (the app closed while it waited). */ declare class BlobTransferError extends KoraError$1 { readonly hash: string; /** Requests actually sent (0 when none could be); tries made offline are not counted. */ readonly attempts: number; readonly lastReason: BlobChunkFailureReason; constructor(message: string, code: BlobTransferErrorCode, hash: string, /** Requests actually sent (0 when none could be); tries made offline are not counted. */ attempts: number, lastReason: BlobChunkFailureReason); } /** * Blob chunk exchange messages. These ride any message transport (the sync * WebSocket in production, an in-memory pair in tests). A receiver requests a * chunk by hash and correlates the answer by `requestId`. */ interface ChunkRequestMessage { type: 'blob-chunk-request'; requestId: string; hash: string; } interface ChunkResponseMessage { type: 'blob-chunk-response'; requestId: string; /** The chunk bytes, or null when the responder does not hold that hash. */ bytes: Uint8Array | null; /** * The server refused the request for rate, not because the chunk is missing * (RT-24). The requester retries after `retryAfterMs` instead of failing. */ throttled?: boolean; /** With `throttled`: how long to wait before retrying, in ms. */ retryAfterMs?: number; } type ChunkMessage = ChunkRequestMessage | ChunkResponseMessage; /** * A bidirectional message port carrying {@link ChunkMessage}s. Implemented over * the sync connection in production; `createChunkPortPair` provides an in-memory * duplex pair for tests. */ interface ChunkMessagePort { /** * Send a message. Returns `false` when it could not be sent (no live connection); * any other return (including none) counts as sent. */ send(message: ChunkMessage): boolean | void; /** Register a handler for incoming messages. Multiple handlers are allowed. */ onMessage(handler: (message: ChunkMessage) => void): void; /** * Optional: register a handler called each time the connection becomes able to * carry requests again (after a connect or a reconnect). A requester re-sends its * pending requests there, since they may have been lost with the old connection. * Handlers live as long as the port. */ onReady?(handler: () => void): void; } /** A {@link ChunkProvider} that fetches chunks over a message port. */ interface RemoteChunkProvider extends ChunkProvider { /** Number of requests still awaiting a response (for diagnostics/tests). */ pendingCount(): number; /** * Stop: every pending request rejects with `BLOB_CHUNK_CANCELLED`, every timer is * cleared, and later `getChunk` calls reject at once. Called when the app closes. */ close(): void; } /** Timer functions the provider uses; injectable so tests need no real time. */ interface ChunkProviderClock { now(): number; setTimeout(callback: () => void, delayMs: number): unknown; clearTimeout(handle: unknown): void; } /** Options for {@link createRemoteChunkProvider}. */ interface RemoteChunkProviderOptions { /** * Longest time one request may go without any answer before it fails with * `BLOB_CHUNK_TIMEOUT` (default 2 minutes). Until then it is re-sent, under the * same request id, each time an attempt goes unanswered and each time the * connection comes back. A "throttled" answer counts as an answer. */ deadlineMs?: number; /** @deprecated Use `deadlineMs`: the time after which a request nobody answers fails. */ timeoutMs?: number; /** Wait for an answer to the first attempt before re-sending, in ms (default 5 s). */ attemptTimeoutMs?: number; /** Largest wait for one attempt; each unanswered attempt doubles it (default 30 s). */ maxAttemptTimeoutMs?: number; /** Random spread of each attempt wait, as a fraction (default 0.2, so plus or minus 20%). */ jitter?: number; /** * Longest time, counted from the request's start, after which a "throttled" answer * fails the request instead of being waited out (default 10 minutes). The transfer * is resumable, so a failed request can simply be retried later. */ maxThrottleWaitMs?: number; /** Smallest back-off after a throttled answer, in ms (default 250). */ minThrottleDelayMs?: number; /** Largest single back-off after a throttled answer, in ms (default 30s). */ maxThrottleDelayMs?: number; /** Receives `blob:request-retried` and `blob:request-failed`. */ emitter?: KoraEventEmitter; /** Clock and timers (default: `Date.now`, `setTimeout`, `clearTimeout`). */ clock?: ChunkProviderClock; /** Random source in [0, 1) for the jitter (default `Math.random`). */ random?: () => number; } /** Default time after which a request that nobody answers fails. */ declare const DEFAULT_BLOB_CHUNK_DEADLINE_MS = 120000; /** Default wait for an answer to a request's first attempt. */ declare const DEFAULT_BLOB_CHUNK_ATTEMPT_TIMEOUT_MS = 5000; /** Default largest wait for one attempt. */ declare const DEFAULT_BLOB_CHUNK_MAX_ATTEMPT_TIMEOUT_MS = 30000; /** * Create a {@link ChunkProvider} that requests chunks over a message port and * correlates each answer to its request by `requestId`. * * A request never rests on a single message: an unanswered attempt is re-sent, * under the same request id, after a wait that grows from `attemptTimeoutMs` to * `maxAttemptTimeoutMs` (with jitter), and every pending request is re-sent when * the port reports the connection ready again. Only after `deadlineMs` without any * answer does it fail, with a {@link BlobTransferError} (`BLOB_CHUNK_TIMEOUT`) * carrying the hash, the attempt count and the last reason. Re-sending is safe: * answering a chunk request only reads, and the first answer wins. * * A "not held" answer rejects with `BLOB_CHUNK_UNAVAILABLE` (the attempt count and * `lastReason: 'not-held'`) rather than resolving null, so the error reports how many * attempts were made; `getChunk` resolves only with bytes. * * A "throttled" answer (the server's blob request budget is spent, RT-24) is not a * failure: the request is re-sent after the server's `retryAfterMs` (bounded, with * exponential back-off when absent), until `maxThrottleWaitMs` has elapsed. * * @param port - The message port to the peer that holds the blob * @param options - Deadlines, back-off bounds, events and an injectable clock */ declare function createRemoteChunkProvider(port: ChunkMessagePort, options?: RemoteChunkProviderOptions): RemoteChunkProvider; /** * Serve blob chunk requests arriving on a message port from a blob store. Answers * each `blob-chunk-request` with the bytes for that hash, or null when the store * does not hold it. Returns nothing; attach it once per connection. * * @param port - The message port from the peer requesting chunks * @param blobStore - The store to serve chunks from (keyed by chunk hash) */ declare function serveBlobChunks(port: ChunkMessagePort, blobStore: ContentAddressedBlobStore): void; /** * Create a connected in-memory pair of {@link ChunkMessagePort}s. Messages sent * on one arrive on the other, asynchronously (next microtask) so the pair models * a real transport rather than re-entrant synchronous delivery. For tests. */ declare function createChunkPortPair(): { a: ChunkMessagePort; b: ChunkMessagePort; }; export { AdoptionSchedule, ApplyRemoteOptions, type AuditExportManifest, type AuditExportOptions, type AuditExportPayload, type AuditExportProgress, type AuditTraceQuery, BACKUP_VERSION, BackupFormatError, type BackupManifest, type BackupOptions, type BackupProgress, type BlobChunkFailureReason, type BlobManifest, type BlobManifestMetadata, BlobTransferError, type BlobTransferErrorCode, COMPACTION_BASELINE_META_KEY, type ChunkMessage, type ChunkMessagePort, type ChunkProvider, type ChunkProviderClock, type ChunkRequestMessage, type ChunkResponseMessage, type ClockRebaseResult, type CollectionAccessor, CollectionRecord, type CompactionResult, type CompactionStrategy, ContentAddressedBlobStore, type ConvertBackupV1Options, type CreateRichTextControllerOptions, DEFAULT_BLOB_CHUNK_ATTEMPT_TIMEOUT_MS, DEFAULT_BLOB_CHUNK_DEADLINE_MS, DEFAULT_BLOB_CHUNK_MAX_ATTEMPT_TIMEOUT_MS, DEFAULT_CHUNK_SIZE, InvalidStateTransitionError, LAST_ACKED_SERVER_VECTOR_META_KEY, LOG_QUARANTINE_TABLE, LocalMutationHandler, LocalNodeRecord, type LogIntegrityReport, type LogIntegrityRow, type LogRowProblem, type LogSequenceGap, MaterializedRowSnapshot, type NewOfflinePin, type NodeRotationResult, type OfflinePinWriteResult, type OpfsBlobDirectory, OpfsBlobStore, type PersistedAuditTrace, type PersistenceRequestReason, type PersistenceStorageManager, type PrincipalBinding, ProvisionalSideEffect, type PurgeOutcome, QueryBuilder, QueryError, type ReceiveBlobResult, type ReceiveBlobStores, RecordsChangeListener, type RematerializationMode, RemoteApplyBatch, type RemoteChunkProvider, type RemoteChunkProviderOptions, type ReplaySnapshot, type ResequenceResult, type RestoreOptions, type RestoreResult, type RichTextAwarenessUser, type RichTextController, type RichTextControllerSnapshot, type RichTextCursorInfo, type RichTextSyncEngine, RowVersionState, type SeedInput, type SeedMeta, type SeedOutcome, type SeedRow, type SeedSkipReason, SequenceManager, type StagingMergeOptions, type StagingMergeResult, type StagingProgress, StagingReplica, StorageAdapter, StorageEviction, StoragePersistence, type StoragePersistenceOptions, type StoragePersistenceState, type StoragePersistenceStatus, Store, StoreConfig, type StoredOfflinePin, type StoredOfflinePinHold, SubscriptionBloomFilter, SubscriptionManager, TerminalRejection, Transaction, type TransactionCollectionAccessor, TransactionContext, type TransactionContextConfig, UnappliedOperation, WriteDurabilityState, WriteOptions, type WriteScope, asRichTextSyncEngine, chunkBlob, collectOperationsAheadOfServer, compactOperationLog, computeAckCompactionWatermark, convertBackupV1, createChunkPortPair, createOpfsBlobDirectory, createOpfsBlobStore, createRemoteChunkProvider, createRichTextController, decodeAuditExport, decodeRichtext, deserializeVersionVectorFromMeta, encodeRichtext, exportBackup, fetchBlobManifest, mergeVersionVectors, parseBlobManifest, persistedAuditTraceFromEvent, pluralize, prepareBlobForSend, putBlobForTransfer, readAuditExportManifest, readBackupManifest, reassembleBlob, receiveBlob, resolveBlobManifest, restoreBackup, richtextStatesEqual, richtextToPlainText, serializeBlobManifest, serializeVersionVectorToMeta, serveBlobChunks, singularize, validateStateTransition, validateUpdateStateMachine, verifyAuditExportChecksum, verifyBackupChecksum };