{"version":3,"sources":["/home/runner/work/kora/kora/packages/store/dist/index.cjs","../src/persistence/storage-persistence.ts","../src/richtext/create-richtext-controller.ts","../src/richtext/as-rich-text-sync-engine.ts","../src/blob/opfs-blob-store.ts","../src/blob/blob-transfer.ts","../src/blob/blob-chunk-transport.ts","../src/index.ts"],"names":["hashBlob"],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B,gCAA6B;AAC7B,gCAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACvEA,SAAS,qBAAA,CAAA,EAA0D;AAClE,EAAA,MAAM,IAAA,EAAO,UAAA,CAAuE,SAAA;AACpF,EAAA,wCAAO,GAAA,2BAAK,SAAA,UAAW,MAAA;AACxB;AAEA,SAAS,YAAA,CAAa,KAAA,EAAwB;AAC7C,EAAA,OAAO,MAAA,WAAiB,MA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ACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,sgOAAC","file":"/home/runner/work/kora/kora/packages/store/dist/index.cjs","sourcesContent":[null,"import type { KoraEventEmitter } from '@korajs/core'\n\n/**\n * Durable-storage state of this origin, as far as Kora knows (NEW-STORE-4).\n * - `unknown`: not checked yet (the boot check runs in the background).\n * - `persisted`: the browser granted persistent storage; it will not evict this\n *   origin's data under storage pressure.\n * - `best-effort`: storage may be evicted under pressure (the browser default).\n * - `unsupported`: the runtime has no StorageManager persistence API (Node,\n *   older browsers, some WebViews).\n * - `error`: the check or request threw; `lastError` says why.\n */\nexport type StoragePersistenceState =\n\t| 'unknown'\n\t| 'persisted'\n\t| 'best-effort'\n\t| 'unsupported'\n\t| 'error'\n\n/** Snapshot returned by `app.storage.persistence.status()`. */\nexport interface StoragePersistenceStatus {\n\tstate: StoragePersistenceState\n\t/** True only when the browser reported persistent storage. */\n\tpersisted: boolean\n\t/** True once `persist()` was asked for (explicitly or by an automatic trigger). */\n\trequested: boolean\n\t/** Message of the last failure, when `state` is `error`. */\n\tlastError?: string\n}\n\n/** Why an automatic (background) persistence request was made. */\nexport type PersistenceRequestReason =\n\t| 'explicit'\n\t| 'sign-in'\n\t| 'first-write'\n\t| 'installed-app'\n\t| 'offline-keep'\n\n/** The subset of `navigator.storage` used here. */\nexport interface PersistenceStorageManager {\n\tpersist?: () => Promise<boolean>\n\tpersisted?: () => Promise<boolean>\n}\n\n/** Options for {@link StoragePersistence}. */\nexport interface StoragePersistenceOptions {\n\t/** Receives `storage:persistence` events. */\n\temitter?: KoraEventEmitter | null\n\t/**\n\t * The StorageManager to use. Defaults to `globalThis.navigator.storage`,\n\t * resolved on each call so tests and late polyfills are honoured.\n\t */\n\tstorage?: PersistenceStorageManager | null\n}\n\nfunction defaultStorageManager(): PersistenceStorageManager | null {\n\tconst nav = (globalThis as { navigator?: { storage?: PersistenceStorageManager } }).navigator\n\treturn nav?.storage ?? null\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error)\n}\n\n/**\n * Tracks and requests durable storage (`navigator.storage.persist()`) without ever\n * putting it on the startup path (NEW-STORE-4).\n *\n * In Firefox `persist()` opens a permission prompt and its promise stays pending\n * until the user answers, so awaiting it inside startup could hang `app.ready`\n * forever. Kora therefore:\n * - checks `persisted()` at boot, which never prompts, in the background;\n * - requests persistence only on an explicit `request()` or, without awaiting,\n *   after a meaningful moment (sign-in, the first local write, running as an\n *   installed app);\n * - surfaces every result through `status()` and the `storage:persistence` event,\n *   never by blocking.\n */\nexport class StoragePersistence {\n\tprivate current: StoragePersistenceStatus = {\n\t\tstate: 'unknown',\n\t\tpersisted: false,\n\t\trequested: false,\n\t}\n\tprivate inFlightRequest: Promise<StoragePersistenceStatus> | null = null\n\tprivate readonly emitter: KoraEventEmitter | null\n\tprivate readonly storageOverride: PersistenceStorageManager | null | undefined\n\n\tconstructor(options: StoragePersistenceOptions = {}) {\n\t\tthis.emitter = options.emitter ?? null\n\t\tthis.storageOverride = options.storage\n\t}\n\n\t/** Synchronous snapshot of the last known state. Never prompts. */\n\tstatus(): StoragePersistenceStatus {\n\t\treturn { ...this.current }\n\t}\n\n\t/**\n\t * Read whether storage is already persistent (`navigator.storage.persisted()`).\n\t * Never prompts and never throws: a failure becomes `state: 'error'`.\n\t */\n\tasync check(): Promise<StoragePersistenceStatus> {\n\t\tconst storage = this.storage()\n\t\tif (!storage || typeof storage.persisted !== 'function') {\n\t\t\tthis.update({ state: 'unsupported', persisted: false })\n\t\t\tif (storage) this.emit('unsupported', false)\n\t\t\treturn this.status()\n\t\t}\n\t\ttry {\n\t\t\tconst persisted = (await storage.persisted()) === true\n\t\t\t// A grant observed by a concurrent request() is never downgraded here.\n\t\t\tif (!this.current.persisted) {\n\t\t\t\tthis.update({ state: persisted ? 'persisted' : 'best-effort', persisted })\n\t\t\t}\n\t\t\tthis.emit('checked', this.current.persisted)\n\t\t} catch (error) {\n\t\t\tthis.update({ state: 'error', persisted: false, lastError: errorMessage(error) })\n\t\t\tthis.emit('error', false, errorMessage(error))\n\t\t}\n\t\treturn this.status()\n\t}\n\n\t/**\n\t * Ask the browser for persistent storage (`navigator.storage.persist()`).\n\t * May show a permission prompt (Firefox), so call it from a user gesture or a\n\t * meaningful moment, and do not block rendering on it. Concurrent calls share\n\t * one request. Never throws: a failure becomes `state: 'error'`.\n\t *\n\t * @returns The state after the browser answered\n\t */\n\trequest(): Promise<StoragePersistenceStatus> {\n\t\tif (this.inFlightRequest) return this.inFlightRequest\n\t\tconst storage = this.storage()\n\t\tif (!storage || typeof storage.persist !== 'function') {\n\t\t\tthis.update({ state: 'unsupported', persisted: false })\n\t\t\tif (storage) this.emit('unsupported', false)\n\t\t\treturn Promise.resolve(this.status())\n\t\t}\n\t\tif (this.current.persisted) return Promise.resolve(this.status())\n\t\tconst persist = storage.persist.bind(storage)\n\t\tthis.current = { ...this.current, requested: true }\n\t\tconst pending = (async (): Promise<StoragePersistenceStatus> => {\n\t\t\ttry {\n\t\t\t\tconst persisted = (await persist()) === true\n\t\t\t\tthis.update({ state: persisted ? 'persisted' : 'best-effort', persisted })\n\t\t\t\tthis.emit('requested', persisted)\n\t\t\t} catch (error) {\n\t\t\t\tthis.update({ state: 'error', persisted: false, lastError: errorMessage(error) })\n\t\t\t\tthis.emit('error', false, errorMessage(error))\n\t\t\t} finally {\n\t\t\t\tthis.inFlightRequest = null\n\t\t\t}\n\t\t\treturn this.status()\n\t\t})()\n\t\tthis.inFlightRequest = pending\n\t\treturn pending\n\t}\n\n\t/**\n\t * Fire-and-forget `request()` for an automatic trigger. Never awaited by Kora,\n\t * so a pending prompt cannot block anything; the outcome arrives as a\n\t * `storage:persistence` event. Skipped when storage is already persistent or a\n\t * request was already made this session.\n\t *\n\t * @param _reason - Which trigger fired (kept for tracing at call sites)\n\t */\n\trequestInBackground(_reason: PersistenceRequestReason): void {\n\t\tif (this.current.persisted || this.current.requested) return\n\t\tvoid this.request()\n\t}\n\n\tprivate storage(): PersistenceStorageManager | null {\n\t\treturn this.storageOverride === undefined ? defaultStorageManager() : this.storageOverride\n\t}\n\n\tprivate update(next: Omit<StoragePersistenceStatus, 'requested'>): void {\n\t\tthis.current = { ...next, requested: this.current.requested }\n\t}\n\n\tprivate emit(\n\t\tstate: 'checked' | 'requested' | 'unsupported' | 'error',\n\t\tpersisted: boolean,\n\t\tmessage?: string,\n\t): void {\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'storage:persistence',\n\t\t\tstate,\n\t\t\tpersisted,\n\t\t\t...(message !== undefined ? { message } : {}),\n\t\t})\n\t}\n}\n","import * as Y from 'yjs'\nimport { encodeRichtext } from '../serialization/richtext-serializer'\nimport type {\n\tCreateRichTextControllerOptions,\n\tRichTextAwarenessState,\n\tRichTextAwarenessUser,\n\tRichTextController,\n\tRichTextControllerSnapshot,\n\tRichTextCursorInfo,\n} from './types'\n\nconst LOAD_ORIGIN = 'kora-load'\nconst REMOTE_ORIGIN = 'kora-remote'\nconst DOC_CHANNEL_ORIGIN = 'kora-doc-channel'\nconst TEXT_KEY = 'content'\nconst PERSIST_DEBOUNCE_MS = 400\n\n/**\n * Framework-agnostic richtext binding: Yjs document lifecycle, persistence,\n * incremental doc channel, and awareness cursors.\n *\n * Every save writes the full state of the live Y.Doc, which holds every local edit\n * and every merged remote change, so a stored change arriving while a save waits\n * cannot drop local typing. A refused save keeps the edits unsaved\n * (`hasUnsavedChanges`, `getUnsavedState()`) and the next edit or `retrySave()`\n * saves them again; the first successful save clears `error`.\n */\nexport function createRichTextController(\n\toptions: CreateRichTextControllerOptions,\n): RichTextController {\n\tconst {\n\t\tcollection,\n\t\tcollectionName,\n\t\trecordId,\n\t\tfieldName,\n\t\tstore,\n\t\tsyncEngine = null,\n\t\tuseDocChannel,\n\t} = options\n\n\tconst doc = new Y.Doc()\n\tconst text = doc.getText(TEXT_KEY)\n\tconst undoManager = new Y.UndoManager(text)\n\n\tlet user = options.user\n\tlet disposed = false\n\tlet ready = false\n\tlet error: Error | null = null\n\tlet canUndo = false\n\tlet canRedo = false\n\tlet cursors: RichTextCursorInfo[] = []\n\t// Local edits are counted; a save that succeeds covers every edit made before it\n\t// read the document. Edits after the last covered one are unsaved.\n\tlet editGeneration = 0\n\tlet savedGeneration = 0\n\tlet saving: Promise<void> | null = null\n\tlet saveAgain = false\n\n\tconst listeners = new Set<() => void>()\n\tlet snapshot: RichTextControllerSnapshot = {\n\t\tready: false,\n\t\terror: null,\n\t\tcanUndo: false,\n\t\tcanRedo: false,\n\t\tcursors: [],\n\t\thasUnsavedChanges: false,\n\t}\n\tconst docChannelActiveRef = { current: false }\n\tlet persistTimer: ReturnType<typeof setTimeout> | null = null\n\n\tlet recordUnsubscribe: (() => void) | null = null\n\tlet docChannelUnsubscribe: (() => void) | null = null\n\tlet awarenessUnsubscribe: (() => void) | null = null\n\n\tconst refreshSnapshot = (): void => {\n\t\tsnapshot = {\n\t\t\tready,\n\t\t\terror,\n\t\t\tcanUndo,\n\t\t\tcanRedo,\n\t\t\tcursors: [...cursors],\n\t\t\thasUnsavedChanges: editGeneration > savedGeneration,\n\t\t}\n\t}\n\n\tconst notify = (): void => {\n\t\trefreshSnapshot()\n\t\tfor (const listener of listeners) {\n\t\t\tlistener()\n\t\t}\n\t}\n\n\tconst syncHistoryState = (): void => {\n\t\tcanUndo = undoManager.undoStack.length > 0\n\t\tcanRedo = undoManager.redoStack.length > 0\n\t\tnotify()\n\t}\n\n\tconst getSnapshot = (): RichTextControllerSnapshot => snapshot\n\n\tconst resolveAwarenessUser = (): RichTextAwarenessUser => {\n\t\tif (user) {\n\t\t\treturn user\n\t\t}\n\t\tif (syncEngine) {\n\t\t\tconst existing = syncEngine.getAwarenessManager().getLocalState()?.user\n\t\t\tif (existing) {\n\t\t\t\treturn existing\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tname: 'Anonymous',\n\t\t\tcolor: '#6366f1',\n\t\t}\n\t}\n\n\tconst setCursor = (anchor: number, head: number): void => {\n\t\tif (!syncEngine) {\n\t\t\treturn\n\t\t}\n\n\t\tconst awareness = syncEngine.getAwarenessManager()\n\t\tconst state: RichTextAwarenessState = {\n\t\t\tuser: resolveAwarenessUser(),\n\t\t\tcursor: {\n\t\t\t\tcollection: collectionName,\n\t\t\t\trecordId,\n\t\t\t\tfield: fieldName,\n\t\t\t\tanchor,\n\t\t\t\thead,\n\t\t\t},\n\t\t}\n\t\tawareness.setLocalState(state)\n\t}\n\n\tconst clearCursor = (): void => {\n\t\tif (!syncEngine) {\n\t\t\treturn\n\t\t}\n\n\t\tconst awareness = syncEngine.getAwarenessManager()\n\t\tconst current = awareness.getLocalState()\n\t\tif (!current?.cursor) {\n\t\t\treturn\n\t\t}\n\t\tif (\n\t\t\tcurrent.cursor.collection !== collectionName ||\n\t\t\tcurrent.cursor.recordId !== recordId ||\n\t\t\tcurrent.cursor.field !== fieldName\n\t\t) {\n\t\t\treturn\n\t\t}\n\n\t\tawareness.setLocalState({ user: current.user })\n\t}\n\n\tconst applyRemoteSnapshot = (value: unknown): void => {\n\t\tconst encoded = encodeRichtextInput(value)\n\t\tif (!encoded) {\n\t\t\treturn\n\t\t}\n\n\t\tconst currentSnapshot = Y.encodeStateAsUpdate(doc)\n\t\tif (updatesEqual(currentSnapshot, encoded)) {\n\t\t\treturn\n\t\t}\n\n\t\t// A Yjs merge: the stored state joins the live document and local edits that\n\t\t// are not saved yet stay in it, so the next save (of the live document) keeps them.\n\t\tY.applyUpdate(doc, encoded, REMOTE_ORIGIN)\n\t\tsyncHistoryState()\n\t}\n\n\t/** Save the live document once; the outcome updates `error` and the unsaved state. */\n\tconst persistOnce = async (): Promise<void> => {\n\t\tconst generation = editGeneration\n\t\tconst state = Y.encodeStateAsUpdate(doc)\n\t\ttry {\n\t\t\tawait collection.update(recordId, {\n\t\t\t\t[fieldName]: state,\n\t\t\t})\n\t\t\tif (generation > savedGeneration) savedGeneration = generation\n\t\t\terror = null\n\t\t} catch (cause) {\n\t\t\terror = cause instanceof Error ? cause : new Error(String(cause))\n\t\t}\n\t\tif (!disposed) notify()\n\t}\n\n\t/**\n\t * Save the live document. Saves run one at a time; a request during a save runs\n\t * one more save after it, which reads the document then and so holds every edit.\n\t */\n\tconst flushPersist = (): Promise<void> => {\n\t\tif (saving) {\n\t\t\tsaveAgain = true\n\t\t\treturn saving\n\t\t}\n\t\tconst run = (async () => {\n\t\t\tdo {\n\t\t\t\tsaveAgain = false\n\t\t\t\tawait persistOnce()\n\t\t\t} while (saveAgain)\n\t\t})()\n\t\tsaving = run\n\t\tvoid run.finally(() => {\n\t\t\tif (saving === run) saving = null\n\t\t})\n\t\treturn run\n\t}\n\n\tconst schedulePersist = (): void => {\n\t\tif (persistTimer) {\n\t\t\tclearTimeout(persistTimer)\n\t\t}\n\t\tpersistTimer = setTimeout(() => {\n\t\t\tpersistTimer = null\n\t\t\tvoid flushPersist()\n\t\t}, PERSIST_DEBOUNCE_MS)\n\t}\n\n\tconst onDocUpdate = (update: Uint8Array, origin: unknown): void => {\n\t\tsyncHistoryState()\n\t\tif (origin === LOAD_ORIGIN || origin === REMOTE_ORIGIN || origin === DOC_CHANNEL_ORIGIN) {\n\t\t\treturn\n\t\t}\n\n\t\teditGeneration += 1\n\n\t\tif (docChannelActiveRef.current && syncEngine) {\n\t\t\tsyncEngine.getRichtextDocChannel?.().send(collectionName, recordId, fieldName, update)\n\t\t\tschedulePersist()\n\t\t\treturn\n\t\t}\n\n\t\tvoid flushPersist()\n\t}\n\n\tconst subscribeRecordChanges = (): void => {\n\t\trecordUnsubscribe?.()\n\t\trecordUnsubscribe = store\n\t\t\t.collection(collectionName)\n\t\t\t.where({ id: recordId })\n\t\t\t.subscribe((results) => {\n\t\t\t\tconst record = results[0]\n\t\t\t\tif (!record) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tapplyRemoteSnapshot(record[fieldName])\n\t\t\t})\n\t}\n\n\tconst subscribeDocChannel = (): void => {\n\t\tdocChannelUnsubscribe?.()\n\t\tif (!ready || !syncEngine || !docChannelActiveRef.current) {\n\t\t\treturn\n\t\t}\n\n\t\tconst channel = syncEngine.getRichtextDocChannel?.()\n\t\tif (!channel) {\n\t\t\treturn\n\t\t}\n\n\t\tdocChannelUnsubscribe = channel.subscribe(collectionName, recordId, fieldName, (update) => {\n\t\t\tY.applyUpdate(doc, update, DOC_CHANNEL_ORIGIN)\n\t\t\tsyncHistoryState()\n\t\t})\n\t}\n\n\tconst updateCursors = (): void => {\n\t\tif (!syncEngine) {\n\t\t\tcursors = []\n\t\t\tnotify()\n\t\t\treturn\n\t\t}\n\n\t\tconst awareness = syncEngine.getAwarenessManager()\n\t\tconst localClientId = awareness.clientId\n\t\tconst states = awareness.getStates()\n\t\tconst fieldCursors: RichTextCursorInfo[] = []\n\n\t\tfor (const [clientId, state] of states) {\n\t\t\tif (clientId === localClientId) continue\n\t\t\tif (!state.cursor) continue\n\t\t\tif (\n\t\t\t\tstate.cursor.collection !== collectionName ||\n\t\t\t\tstate.cursor.recordId !== recordId ||\n\t\t\t\tstate.cursor.field !== fieldName\n\t\t\t) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfieldCursors.push({\n\t\t\t\tclientId,\n\t\t\t\tuserName: state.user.name,\n\t\t\t\tcolor: state.user.color,\n\t\t\t\tanchor: state.cursor.anchor,\n\t\t\t\thead: state.cursor.head,\n\t\t\t})\n\t\t}\n\n\t\tcursors = fieldCursors\n\t\tnotify()\n\t}\n\n\tconst subscribeAwareness = (): void => {\n\t\tawarenessUnsubscribe?.()\n\t\tif (!syncEngine) {\n\t\t\tcursors = []\n\t\t\tnotify()\n\t\t\treturn\n\t\t}\n\n\t\tconst awareness = syncEngine.getAwarenessManager()\n\t\tawarenessUnsubscribe = awareness.on('change', () => {\n\t\t\tupdateCursors()\n\t\t})\n\t\tupdateCursors()\n\t}\n\n\tconst initialize = async (): Promise<void> => {\n\t\tready = false\n\t\terror = null\n\t\tnotify()\n\n\t\ttry {\n\t\t\tconst record = await collection.findById(recordId)\n\t\t\tif (disposed) return\n\n\t\t\tdoc.transact(() => {\n\t\t\t\tconst target = doc.getText(TEXT_KEY)\n\t\t\t\ttarget.delete(0, target.length)\n\t\t\t}, LOAD_ORIGIN)\n\n\t\t\tconst encoded = encodeRichtextInput(record?.[fieldName])\n\t\t\tif (encoded) {\n\t\t\t\tY.applyUpdate(doc, encoded, LOAD_ORIGIN)\n\t\t\t}\n\n\t\t\tconst channel = syncEngine?.getRichtextDocChannel?.()\n\t\t\tdocChannelActiveRef.current =\n\t\t\t\tchannel?.shouldUseChannel(encoded?.length ?? 0, useDocChannel) ?? false\n\n\t\t\tready = true\n\t\t\tsyncHistoryState()\n\t\t\tsubscribeRecordChanges()\n\t\t\tsubscribeDocChannel()\n\t\t\tsubscribeAwareness()\n\t\t\tnotify()\n\t\t} catch (cause) {\n\t\t\tif (disposed) return\n\t\t\terror = cause instanceof Error ? cause : new Error(String(cause))\n\t\t\tnotify()\n\t\t}\n\t}\n\n\tdoc.on('update', onDocUpdate)\n\tvoid initialize()\n\n\treturn {\n\t\tdoc,\n\t\ttext,\n\t\tgetSnapshot,\n\t\tsubscribe(listener) {\n\t\t\tlisteners.add(listener)\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener)\n\t\t\t}\n\t\t},\n\t\tundo() {\n\t\t\tundoManager.undo()\n\t\t\tsyncHistoryState()\n\t\t},\n\t\tredo() {\n\t\t\tundoManager.redo()\n\t\t\tsyncHistoryState()\n\t\t},\n\t\tsetCursor,\n\t\tclearCursor,\n\t\tsetUser(nextUser: RichTextAwarenessUser | undefined) {\n\t\t\tuser = nextUser\n\t\t},\n\t\tretrySave() {\n\t\t\tif (persistTimer) {\n\t\t\t\tclearTimeout(persistTimer)\n\t\t\t\tpersistTimer = null\n\t\t\t}\n\t\t\treturn flushPersist()\n\t\t},\n\t\tgetUnsavedState() {\n\t\t\treturn editGeneration > savedGeneration ? Y.encodeStateAsUpdate(doc) : null\n\t\t},\n\t\tdestroy() {\n\t\t\tif (disposed) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdisposed = true\n\t\t\t// Edits waiting for the debounced save are saved now, not dropped.\n\t\t\tif (persistTimer) {\n\t\t\t\tclearTimeout(persistTimer)\n\t\t\t\tpersistTimer = null\n\t\t\t}\n\t\t\tif (editGeneration > savedGeneration) {\n\t\t\t\tvoid flushPersist()\n\t\t\t}\n\t\t\tdoc.off('update', onDocUpdate)\n\t\t\trecordUnsubscribe?.()\n\t\t\tdocChannelUnsubscribe?.()\n\t\t\tawarenessUnsubscribe?.()\n\t\t\tclearCursor()\n\t\t\tundoManager.destroy()\n\t\t\tdocChannelActiveRef.current = false\n\t\t\tlisteners.clear()\n\t\t},\n\t}\n}\n\nfunction encodeRichtextInput(value: unknown): Uint8Array | null {\n\tif (value === null || value === undefined) {\n\t\treturn null\n\t}\n\n\ttry {\n\t\treturn encodeRichtext(value as Parameters<typeof encodeRichtext>[0])\n\t} catch {\n\t\tif (typeof value === 'string') {\n\t\t\tconst fallbackDoc = new Y.Doc()\n\t\t\tfallbackDoc.getText(TEXT_KEY).insert(0, value)\n\t\t\treturn Y.encodeStateAsUpdate(fallbackDoc)\n\t\t}\n\t\tthrow new Error('Richtext record value must be a string, Uint8Array, ArrayBuffer, or null.')\n\t}\n}\n\nfunction updatesEqual(left: Uint8Array, right: Uint8Array): boolean {\n\tif (left.length !== right.length) {\n\t\treturn false\n\t}\n\tfor (let index = 0; index < left.length; index++) {\n\t\tif (left[index] !== right[index]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n","import type { RichTextSyncEngine } from './types'\n\n/**\n * Narrows a sync engine reference to the richtext controller surface.\n * SyncEngine satisfies this interface at runtime; types live in different packages.\n */\nexport function asRichTextSyncEngine(engine: unknown): RichTextSyncEngine | null {\n\tif (engine == null) {\n\t\treturn null\n\t}\n\treturn engine as RichTextSyncEngine\n}\n","import {\n\ttype BlobRef,\n\ttype BlobRefMetadata,\n\tKoraError,\n\tcreateBlobRef,\n\thashBlob,\n} from '@korajs/core'\nimport { BlobIntegrityError, type ContentAddressedBlobStore } from './content-addressed-blob-store'\n\n/**\n * The minimal directory abstraction an {@link OpfsBlobStore} needs. Blobs are\n * laid out as `<shard>/<name>` (shard = first two hex chars of the hash) so a\n * single directory never holds millions of entries.\n *\n * The real backend ({@link createOpfsBlobDirectory}) is the browser Origin\n * Private File System; tests supply an in-memory implementation. Keeping this\n * port small means the content-addressed logic (hashing, integrity, dedup,\n * sharding) is fully testable without a browser.\n */\nexport interface OpfsBlobDirectory {\n\t/** Read the bytes at `<shard>/<name>`, or null if absent. */\n\tread(shard: string, name: string): Promise<Uint8Array | null>\n\t/**\n\t * Write bytes at `<shard>/<name>`, creating the shard directory as needed.\n\t * Must be atomic: a crash mid-write may not leave a partially-written file\n\t * that a later read would trust.\n\t */\n\twrite(shard: string, name: string, bytes: Uint8Array): Promise<void>\n\t/** Remove `<shard>/<name>`. Returns whether anything was removed. */\n\tremove(shard: string, name: string): Promise<boolean>\n\t/** Whether `<shard>/<name>` exists. */\n\thas(shard: string, name: string): Promise<boolean>\n\t/** Count of stored blobs across all shards (temp files excluded). */\n\tcount(): Promise<number>\n\t/** Every stored blob name (hash) across all shards (temp files excluded). */\n\tkeys(): Promise<string[]>\n}\n\n/**\n * A persistent {@link ContentAddressedBlobStore} for the browser, backed by the\n * Origin Private File System (OPFS) — the same durable storage the SQLite WASM\n * adapter uses. Blobs survive reloads, are sharded by hash prefix, deduplicated,\n * and integrity-verified on read (the returned bytes are checked to hash to the\n * requested key). Writes commit atomically so a torn write cannot surface as\n * trusted data.\n *\n * The store itself is environment-neutral: it talks to an {@link OpfsBlobDirectory}.\n * Use {@link createOpfsBlobStore} in a browser to get one backed by real OPFS.\n */\nexport class OpfsBlobStore implements ContentAddressedBlobStore {\n\treadonly durable = true\n\n\tconstructor(private readonly dir: OpfsBlobDirectory) {}\n\n\tprivate shardFor(hash: string): string {\n\t\t// Two hex chars → 256 shards. Hashes are hex, so this is always well-formed.\n\t\treturn hash.slice(0, 2)\n\t}\n\n\tasync put(bytes: Uint8Array, metadata: BlobRefMetadata = {}): Promise<BlobRef> {\n\t\tconst ref = await createBlobRef(bytes, metadata)\n\t\tconst shard = this.shardFor(ref.hash)\n\n\t\t// Dedup: identical content already stored is a no-op.\n\t\tif (await this.dir.has(shard, ref.hash)) {\n\t\t\treturn ref\n\t\t}\n\n\t\t// Copy into an exactly-sized buffer so a subarray view writes its own bytes.\n\t\tconst out = new Uint8Array(bytes.byteLength)\n\t\tout.set(bytes)\n\t\tawait this.dir.write(shard, ref.hash, out)\n\t\treturn ref\n\t}\n\n\tasync get(hash: string): Promise<Uint8Array | null> {\n\t\tconst bytes = await this.dir.read(this.shardFor(hash), hash)\n\t\tif (bytes === null) {\n\t\t\treturn null\n\t\t}\n\t\tconst actual = await hashBlob(bytes)\n\t\tif (actual !== hash) {\n\t\t\tthrow new BlobIntegrityError(hash, actual)\n\t\t}\n\t\treturn bytes\n\t}\n\n\tasync has(hash: string): Promise<boolean> {\n\t\treturn this.dir.has(this.shardFor(hash), hash)\n\t}\n\n\tasync delete(hash: string): Promise<boolean> {\n\t\treturn this.dir.remove(this.shardFor(hash), hash)\n\t}\n\n\tasync size(): Promise<number> {\n\t\treturn this.dir.count()\n\t}\n\n\tasync list(): Promise<string[]> {\n\t\treturn this.dir.keys()\n\t}\n}\n\n// --- Real OPFS binding (browser only) ---\n\n/** Minimal structural views of the File System Access handles we use. */\ninterface OpfsWritableStream {\n\twrite(data: Uint8Array): Promise<void>\n\tclose(): Promise<void>\n}\ninterface OpfsFileHandle {\n\tcreateWritable(options?: { keepExistingData?: boolean }): Promise<OpfsWritableStream>\n\tgetFile(): Promise<{ arrayBuffer(): Promise<ArrayBuffer> }>\n}\ninterface OpfsDirectoryHandle {\n\tgetDirectoryHandle(name: string, options?: { create?: boolean }): Promise<OpfsDirectoryHandle>\n\tgetFileHandle(name: string, options?: { create?: boolean }): Promise<OpfsFileHandle>\n\tremoveEntry(name: string, options?: { recursive?: boolean }): Promise<void>\n\tkeys(): AsyncIterableIterator<string>\n}\n\ninterface StorageManagerLike {\n\tgetDirectory(): Promise<OpfsDirectoryHandle>\n}\n\nfunction getStorageManager(): StorageManagerLike {\n\tconst nav = (globalThis as unknown as { navigator?: { storage?: StorageManagerLike } }).navigator\n\tif (!nav?.storage || typeof nav.storage.getDirectory !== 'function') {\n\t\tthrow new KoraError(\n\t\t\t'OPFS is unavailable in this environment. The OPFS blob store requires a browser with Origin Private File System support; use MemoryBlobStore or a server-side store elsewhere.',\n\t\t\t'OPFS_UNAVAILABLE',\n\t\t)\n\t}\n\treturn nav.storage\n}\n\nfunction isNotFoundError(error: unknown): boolean {\n\treturn (\n\t\ttypeof error === 'object' &&\n\t\terror !== null &&\n\t\t(error as { name?: string }).name === 'NotFoundError'\n\t)\n}\n\n/**\n * Create an {@link OpfsBlobDirectory} backed by the browser's Origin Private\n * File System, rooted at a named subdirectory. It does not request persistent\n * storage: that is `app.storage.persistence`, kept off the startup path.\n *\n * @param rootDirName - The OPFS subdirectory to store blobs under (default `kora-blobs`)\n * @throws {KoraError} `OPFS_UNAVAILABLE` if OPFS is unavailable (e.g. called outside a browser)\n */\nexport async function createOpfsBlobDirectory(\n\trootDirName = 'kora-blobs',\n): Promise<OpfsBlobDirectory> {\n\tconst storage = getStorageManager()\n\t// NEW-STORE-4: no persist() here. In Firefox it opens a permission prompt that\n\t// stays pending until the user answers, and this runs inside app startup.\n\t// Durable storage is checked and requested by StoragePersistence\n\t// (app.storage.persistence), never on the startup path.\n\tconst opfsRoot = await storage.getDirectory()\n\tconst root = await opfsRoot.getDirectoryHandle(rootDirName, { create: true })\n\n\tasync function shardHandle(shard: string, create: boolean): Promise<OpfsDirectoryHandle | null> {\n\t\ttry {\n\t\t\treturn await root.getDirectoryHandle(shard, { create })\n\t\t} catch (error) {\n\t\t\tif (isNotFoundError(error)) {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t}\n\n\treturn {\n\t\tasync read(shard, name) {\n\t\t\tconst dir = await shardHandle(shard, false)\n\t\t\tif (!dir) {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\tlet handle: OpfsFileHandle\n\t\t\ttry {\n\t\t\t\thandle = await dir.getFileHandle(name, { create: false })\n\t\t\t} catch (error) {\n\t\t\t\tif (isNotFoundError(error)) {\n\t\t\t\t\treturn null\n\t\t\t\t}\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tconst file = await handle.getFile()\n\t\t\treturn new Uint8Array(await file.arrayBuffer())\n\t\t},\n\t\tasync write(shard, name, bytes) {\n\t\t\tconst dir = await root.getDirectoryHandle(shard, { create: true })\n\t\t\tconst handle = await dir.getFileHandle(name, { create: true })\n\t\t\t// createWritable buffers to a swap file and only commits on close(), so\n\t\t\t// the target file is updated atomically. Combined with integrity-on-read,\n\t\t\t// a torn write is never trusted.\n\t\t\tconst writable = await handle.createWritable({ keepExistingData: false })\n\t\t\ttry {\n\t\t\t\tawait writable.write(bytes)\n\t\t\t} finally {\n\t\t\t\tawait writable.close()\n\t\t\t}\n\t\t},\n\t\tasync remove(shard, name) {\n\t\t\tconst dir = await shardHandle(shard, false)\n\t\t\tif (!dir) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait dir.removeEntry(name)\n\t\t\t\treturn true\n\t\t\t} catch (error) {\n\t\t\t\tif (isNotFoundError(error)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tthrow error\n\t\t\t}\n\t\t},\n\t\tasync has(shard, name) {\n\t\t\tconst dir = await shardHandle(shard, false)\n\t\t\tif (!dir) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait dir.getFileHandle(name, { create: false })\n\t\t\t\treturn true\n\t\t\t} catch (error) {\n\t\t\t\tif (isNotFoundError(error)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tthrow error\n\t\t\t}\n\t\t},\n\t\tasync count() {\n\t\t\tlet total = 0\n\t\t\tfor await (const shard of root.keys()) {\n\t\t\t\tconst dir = await shardHandle(shard, false)\n\t\t\t\tif (!dir) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfor await (const name of dir.keys()) {\n\t\t\t\t\tif (!name.endsWith('.tmp')) {\n\t\t\t\t\t\ttotal++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn total\n\t\t},\n\t\tasync keys() {\n\t\t\tconst names: string[] = []\n\t\t\tfor await (const shard of root.keys()) {\n\t\t\t\tconst dir = await shardHandle(shard, false)\n\t\t\t\tif (!dir) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfor await (const name of dir.keys()) {\n\t\t\t\t\tif (!name.endsWith('.tmp')) {\n\t\t\t\t\t\tnames.push(name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn names\n\t\t},\n\t}\n}\n\n/**\n * Create a persistent {@link OpfsBlobStore} backed by real browser OPFS.\n *\n * @param rootDirName - The OPFS subdirectory to store blobs under (default `kora-blobs`)\n * @throws {KoraError} `OPFS_UNAVAILABLE` if OPFS is unavailable (e.g. called outside a browser)\n */\nexport async function createOpfsBlobStore(rootDirName = 'kora-blobs'): Promise<OpfsBlobStore> {\n\treturn new OpfsBlobStore(await createOpfsBlobDirectory(rootDirName))\n}\n","import { type BlobRef, hashBlob } from '@korajs/core'\nimport { type BlobManifest, chunkBlob, reassembleBlob } from './blob-chunking'\nimport { BlobTransferError } from './blob-transfer-error'\nimport { BlobIntegrityError, type ContentAddressedBlobStore } from './content-addressed-blob-store'\n\n/**\n * A source of chunk bytes on the sending side of a transfer. In production this\n * is backed by the sync connection (the receiver requests a chunk hash, the peer\n * that holds the blob answers with the bytes); in tests it is backed by a map.\n */\nexport interface ChunkProvider {\n\t/**\n\t * Fetch the bytes for a chunk hash, or null if the provider does not have it. A\n\t * provider may instead reject with a `BlobTransferError` that carries its own\n\t * diagnostics (the remote provider does, with the attempts it sent).\n\t */\n\tgetChunk(hash: string): Promise<Uint8Array | null>\n}\n\n/** Result of receiving a blob out of band. */\nexport interface ReceiveBlobResult {\n\t/** The content-addressed reference to the reassembled blob. */\n\tref: BlobRef\n\t/** Number of chunks actually fetched from the provider. */\n\tchunksFetched: number\n\t/** Number of chunks skipped because they were already held locally. */\n\tchunksSkipped: number\n}\n\n/** Stores used while receiving a blob. */\nexport interface ReceiveBlobStores {\n\t/**\n\t * Where fetched chunks are staged, keyed by chunk hash. A persistent chunk\n\t * store makes a transfer resumable: an interrupted transfer leaves its chunks\n\t * here, and a resumed transfer skips them.\n\t */\n\tchunkStore: ContentAddressedBlobStore\n\t/** Where the fully reassembled, verified blob is written. */\n\tblobStore: ContentAddressedBlobStore\n}\n\n/**\n * Receive a blob out of band, chunk by chunk, resumably and with integrity\n * verification at every step.\n *\n * For each chunk named in the manifest: if the chunk store already holds it (a\n * prior, possibly interrupted transfer), it is skipped; otherwise it is fetched\n * from the provider and verified to hash to the expected chunk hash before being\n * staged. Once every chunk is present, the blob is reassembled, verified against\n * the manifest's blob hash, and written to the blob store (which deduplicates).\n *\n * The transfer is idempotent: running it again after completion fetches nothing\n * and returns the same reference.\n *\n * @param manifest - The manifest of the blob to receive\n * @param provider - The source of chunk bytes\n * @param stores - The chunk staging store and the destination blob store\n * @returns The reference plus how many chunks were fetched versus skipped\n * @throws {BlobIntegrityError} If a fetched chunk or the whole blob fails verification\n * @throws {BlobTransferError} If a required chunk cannot be obtained: `BLOB_CHUNK_UNAVAILABLE`\n *   when the provider answers that nobody holds it, or the provider's own code\n *   (`BLOB_CHUNK_TIMEOUT`, `BLOB_CHUNK_CANCELLED`)\n */\nexport async function receiveBlob(\n\tmanifest: BlobManifest,\n\tprovider: ChunkProvider,\n\tstores: ReceiveBlobStores,\n): Promise<ReceiveBlobResult> {\n\tlet chunksFetched = 0\n\tlet chunksSkipped = 0\n\n\t// Distinct chunk hashes only: a manifest may repeat a hash, but we need each\n\t// unique chunk exactly once. Skipping duplicates also means a blob made of\n\t// identical chunks transfers that chunk a single time.\n\tconst seen = new Set<string>()\n\tfor (const hash of manifest.chunkHashes) {\n\t\tif (seen.has(hash)) {\n\t\t\tcontinue\n\t\t}\n\t\tseen.add(hash)\n\n\t\tif (await stores.chunkStore.has(hash)) {\n\t\t\tchunksSkipped++\n\t\t\tcontinue\n\t\t}\n\n\t\tconst bytes = await provider.getChunk(hash)\n\t\tif (bytes === null) {\n\t\t\t// A plain null is one provider call answered \"not held\": attempts is 1, the\n\t\t\t// calls made here. A provider that retried reports its own count by rejecting.\n\t\t\tthrow new BlobTransferError(\n\t\t\t\t`Blob transfer failed: provider could not supply chunk ${hash} (no reachable peer or server holds it, or may share it with this device)`,\n\t\t\t\t'BLOB_CHUNK_UNAVAILABLE',\n\t\t\t\thash,\n\t\t\t\t1,\n\t\t\t\t'not-held',\n\t\t\t)\n\t\t}\n\t\tconst actual = await hashBlob(bytes)\n\t\tif (actual !== hash) {\n\t\t\tthrow new BlobIntegrityError(hash, actual)\n\t\t}\n\t\tawait stores.chunkStore.put(bytes)\n\t\tchunksFetched++\n\t}\n\n\tconst full = await reassembleBlob(manifest, stores.chunkStore)\n\tconst ref = await stores.blobStore.put(full, {\n\t\tmimeType: manifest.mimeType,\n\t\tfilename: manifest.filename,\n\t})\n\n\treturn { ref, chunksFetched, chunksSkipped }\n}\n\n/**\n * Prepare a blob for out-of-band sending: split it into chunks, stage those\n * chunks in a content-addressed store, and return the manifest plus a\n * {@link ChunkProvider} that serves the chunks from that store.\n *\n * @param bytes - The full blob content\n * @param chunkStore - Where to stage the chunks (served to receivers)\n * @param options - Optional chunk size and metadata\n * @returns The manifest and a provider that serves the staged chunks\n */\nexport async function prepareBlobForSend(\n\tbytes: Uint8Array,\n\tchunkStore: ContentAddressedBlobStore,\n\toptions: { chunkSize?: number; mimeType?: string; filename?: string } = {},\n): Promise<{ manifest: BlobManifest; provider: ChunkProvider }> {\n\tconst { manifest, chunks } = await chunkBlob(bytes, options.chunkSize, {\n\t\tmimeType: options.mimeType,\n\t\tfilename: options.filename,\n\t})\n\tfor (const chunk of chunks.values()) {\n\t\tawait chunkStore.put(chunk)\n\t}\n\tconst provider: ChunkProvider = {\n\t\tgetChunk: (hash) => chunkStore.get(hash),\n\t}\n\treturn { manifest, provider }\n}\n","import { type KoraEvent, type KoraEventEmitter, generateUUIDv7 } from '@korajs/core'\nimport type { ChunkProvider } from './blob-transfer'\nimport {\n\ttype BlobChunkFailureReason,\n\tBlobTransferError,\n\ttype BlobTransferErrorCode,\n} from './blob-transfer-error'\nimport type { ContentAddressedBlobStore } from './content-addressed-blob-store'\n\n/**\n * Blob chunk exchange messages. These ride any message transport (the sync\n * WebSocket in production, an in-memory pair in tests). A receiver requests a\n * chunk by hash and correlates the answer by `requestId`.\n */\nexport interface ChunkRequestMessage {\n\ttype: 'blob-chunk-request'\n\trequestId: string\n\thash: string\n}\nexport interface ChunkResponseMessage {\n\ttype: 'blob-chunk-response'\n\trequestId: string\n\t/** The chunk bytes, or null when the responder does not hold that hash. */\n\tbytes: Uint8Array | null\n\t/**\n\t * The server refused the request for rate, not because the chunk is missing\n\t * (RT-24). The requester retries after `retryAfterMs` instead of failing.\n\t */\n\tthrottled?: boolean\n\t/** With `throttled`: how long to wait before retrying, in ms. */\n\tretryAfterMs?: number\n}\nexport type ChunkMessage = ChunkRequestMessage | ChunkResponseMessage\n\n/**\n * A bidirectional message port carrying {@link ChunkMessage}s. Implemented over\n * the sync connection in production; `createChunkPortPair` provides an in-memory\n * duplex pair for tests.\n */\nexport interface ChunkMessagePort {\n\t/**\n\t * Send a message. Returns `false` when it could not be sent (no live connection);\n\t * any other return (including none) counts as sent.\n\t */\n\t// biome-ignore lint/suspicious/noConfusingVoidType: ports written against the earlier void-returning signature must still type-check; only an explicit false means \"not sent\".\n\tsend(message: ChunkMessage): boolean | void\n\t/** Register a handler for incoming messages. Multiple handlers are allowed. */\n\tonMessage(handler: (message: ChunkMessage) => void): void\n\t/**\n\t * Optional: register a handler called each time the connection becomes able to\n\t * carry requests again (after a connect or a reconnect). A requester re-sends its\n\t * pending requests there, since they may have been lost with the old connection.\n\t * Handlers live as long as the port.\n\t */\n\tonReady?(handler: () => void): void\n}\n\n/** A {@link ChunkProvider} that fetches chunks over a message port. */\nexport interface RemoteChunkProvider extends ChunkProvider {\n\t/** Number of requests still awaiting a response (for diagnostics/tests). */\n\tpendingCount(): number\n\t/**\n\t * Stop: every pending request rejects with `BLOB_CHUNK_CANCELLED`, every timer is\n\t * cleared, and later `getChunk` calls reject at once. Called when the app closes.\n\t */\n\tclose(): void\n}\n\n/** Timer functions the provider uses; injectable so tests need no real time. */\nexport interface ChunkProviderClock {\n\tnow(): number\n\tsetTimeout(callback: () => void, delayMs: number): unknown\n\tclearTimeout(handle: unknown): void\n}\n\n/** Options for {@link createRemoteChunkProvider}. */\nexport interface RemoteChunkProviderOptions {\n\t/**\n\t * Longest time one request may go without any answer before it fails with\n\t * `BLOB_CHUNK_TIMEOUT` (default 2 minutes). Until then it is re-sent, under the\n\t * same request id, each time an attempt goes unanswered and each time the\n\t * connection comes back. A \"throttled\" answer counts as an answer.\n\t */\n\tdeadlineMs?: number\n\t/** @deprecated Use `deadlineMs`: the time after which a request nobody answers fails. */\n\ttimeoutMs?: number\n\t/** Wait for an answer to the first attempt before re-sending, in ms (default 5 s). */\n\tattemptTimeoutMs?: number\n\t/** Largest wait for one attempt; each unanswered attempt doubles it (default 30 s). */\n\tmaxAttemptTimeoutMs?: number\n\t/** Random spread of each attempt wait, as a fraction (default 0.2, so plus or minus 20%). */\n\tjitter?: number\n\t/**\n\t * Longest time, counted from the request's start, after which a \"throttled\" answer\n\t * fails the request instead of being waited out (default 10 minutes). The transfer\n\t * is resumable, so a failed request can simply be retried later.\n\t */\n\tmaxThrottleWaitMs?: number\n\t/** Smallest back-off after a throttled answer, in ms (default 250). */\n\tminThrottleDelayMs?: number\n\t/** Largest single back-off after a throttled answer, in ms (default 30s). */\n\tmaxThrottleDelayMs?: number\n\t/** Receives `blob:request-retried` and `blob:request-failed`. */\n\temitter?: KoraEventEmitter\n\t/** Clock and timers (default: `Date.now`, `setTimeout`, `clearTimeout`). */\n\tclock?: ChunkProviderClock\n\t/** Random source in [0, 1) for the jitter (default `Math.random`). */\n\trandom?: () => number\n}\n\n/** Default time after which a request that nobody answers fails. */\nexport const DEFAULT_BLOB_CHUNK_DEADLINE_MS = 120_000\n/** Default wait for an answer to a request's first attempt. */\nexport const DEFAULT_BLOB_CHUNK_ATTEMPT_TIMEOUT_MS = 5_000\n/** Default largest wait for one attempt. */\nexport const DEFAULT_BLOB_CHUNK_MAX_ATTEMPT_TIMEOUT_MS = 30_000\n\nconst DEFAULT_CLOCK: ChunkProviderClock = {\n\tnow: () => Date.now(),\n\tsetTimeout: (callback, delayMs) => setTimeout(callback, delayMs),\n\tclearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),\n}\n\ntype RetryReason = 'timeout' | 'not-connected' | 'reconnected' | 'throttled'\n\n/** The events the provider emits. */\ntype BlobProviderEvent = Extract<\n\tKoraEvent,\n\t{ type: 'blob:request-retried' } | { type: 'blob:request-failed' }\n>\n\ninterface PendingChunkRequest {\n\trequestId: string\n\thash: string\n\tresolve: (bytes: Uint8Array | null) => void\n\treject: (error: Error) => void\n\t/** The one timer this request owns: its attempt timeout or a throttle back-off. */\n\ttimer: unknown\n\t/** Waiting out a throttle back-off (a reconnect does not cut it short). */\n\tbackingOff: boolean\n\tstartedAtMs: number\n\t/** When the other side last answered about this request (start, or a throttle). */\n\tlastAnswerAtMs: number\n\t/** Requests that actually left the port (a send that returned false or threw is not one). */\n\tattempts: number\n\t/** Every try, sent or not: drives the growing wait between tries. */\n\ttries: number\n\tthrottledCount: number\n\tlastReason: BlobChunkFailureReason\n}\n\n/**\n * Create a {@link ChunkProvider} that requests chunks over a message port and\n * correlates each answer to its request by `requestId`.\n *\n * A request never rests on a single message: an unanswered attempt is re-sent,\n * under the same request id, after a wait that grows from `attemptTimeoutMs` to\n * `maxAttemptTimeoutMs` (with jitter), and every pending request is re-sent when\n * the port reports the connection ready again. Only after `deadlineMs` without any\n * answer does it fail, with a {@link BlobTransferError} (`BLOB_CHUNK_TIMEOUT`)\n * carrying the hash, the attempt count and the last reason. Re-sending is safe:\n * answering a chunk request only reads, and the first answer wins.\n *\n * A \"not held\" answer rejects with `BLOB_CHUNK_UNAVAILABLE` (the attempt count and\n * `lastReason: 'not-held'`) rather than resolving null, so the error reports how many\n * attempts were made; `getChunk` resolves only with bytes.\n *\n * A \"throttled\" answer (the server's blob request budget is spent, RT-24) is not a\n * failure: the request is re-sent after the server's `retryAfterMs` (bounded, with\n * exponential back-off when absent), until `maxThrottleWaitMs` has elapsed.\n *\n * @param port - The message port to the peer that holds the blob\n * @param options - Deadlines, back-off bounds, events and an injectable clock\n */\nexport function createRemoteChunkProvider(\n\tport: ChunkMessagePort,\n\toptions: RemoteChunkProviderOptions = {},\n): RemoteChunkProvider {\n\tconst deadlineMs = options.deadlineMs ?? options.timeoutMs ?? DEFAULT_BLOB_CHUNK_DEADLINE_MS\n\tconst attemptTimeoutMs = options.attemptTimeoutMs ?? DEFAULT_BLOB_CHUNK_ATTEMPT_TIMEOUT_MS\n\tconst maxAttemptTimeoutMs = Math.max(\n\t\tattemptTimeoutMs,\n\t\toptions.maxAttemptTimeoutMs ?? DEFAULT_BLOB_CHUNK_MAX_ATTEMPT_TIMEOUT_MS,\n\t)\n\tconst jitter = Math.min(1, Math.max(0, options.jitter ?? 0.2))\n\tconst maxThrottleWaitMs = options.maxThrottleWaitMs ?? 10 * 60_000\n\tconst minDelayMs = options.minThrottleDelayMs ?? 250\n\tconst maxDelayMs = options.maxThrottleDelayMs ?? 30_000\n\tconst clock = options.clock ?? DEFAULT_CLOCK\n\tconst random = options.random ?? Math.random\n\tconst emitter = options.emitter ?? null\n\tconst pending = new Map<string, PendingChunkRequest>()\n\tlet closed = false\n\n\t/** Remove a request and its timer. False when it already ended (first answer wins). */\n\tconst finish = (entry: PendingChunkRequest): boolean => {\n\t\tif (pending.get(entry.requestId) !== entry) return false\n\t\tpending.delete(entry.requestId)\n\t\tclock.clearTimeout(entry.timer)\n\t\treturn true\n\t}\n\n\t/**\n\t * Emit an event last, after the request's state change and settlement, and isolate\n\t * its listeners: one that throws is logged (never swallowed), and never leaves a\n\t * request unsettled or stops a loop over pending requests (close, reconnect).\n\t */\n\tconst notify = (event: BlobProviderEvent): void => {\n\t\tif (!emitter) return\n\t\ttry {\n\t\t\temitter.emit(event)\n\t\t} catch (error) {\n\t\t\tconsole.error(`[Kora] a ${event.type} listener threw`, error)\n\t\t}\n\t}\n\n\tconst fail = (entry: PendingChunkRequest, code: BlobTransferErrorCode, message: string): void => {\n\t\tif (!finish(entry)) return\n\t\t// Settled before the event: a throwing listener cannot leave getChunk pending.\n\t\tentry.reject(new BlobTransferError(message, code, entry.hash, entry.attempts, entry.lastReason))\n\t\tnotify({\n\t\t\ttype: 'blob:request-failed',\n\t\t\thash: entry.hash,\n\t\t\trequestId: entry.requestId,\n\t\t\tattempts: entry.attempts,\n\t\t\tcode,\n\t\t\treason: entry.lastReason,\n\t\t\tmessage,\n\t\t})\n\t}\n\n\t/** The wait for an answer to the current attempt, never past the deadline. */\n\tconst attemptWaitMs = (entry: PendingChunkRequest): number => {\n\t\tconst base = Math.min(maxAttemptTimeoutMs, attemptTimeoutMs * 2 ** (entry.tries - 1))\n\t\tconst spread = base * jitter * (2 * random() - 1)\n\t\tconst wait = Math.max(1, Math.round(base + spread))\n\t\tconst remaining = entry.lastAnswerAtMs + deadlineMs - clock.now()\n\t\treturn Math.max(0, Math.min(wait, remaining))\n\t}\n\n\t/**\n\t * Try to send the request (the first try, or a retry under the same request id) and\n\t * arm its timeout. Only a request that left the port counts as an attempt and emits\n\t * `blob:request-retried` (numbered by the requests actually sent), so `attempts`\n\t * never counts a try made while offline.\n\t */\n\tconst attempt = (entry: PendingChunkRequest, retryReason: RetryReason | null): void => {\n\t\tif (pending.get(entry.requestId) !== entry) return\n\t\tclock.clearTimeout(entry.timer)\n\t\tentry.backingOff = false\n\t\tentry.tries += 1\n\t\t// Counted before sending, so a port that answers synchronously (inside send) is\n\t\t// reported with this attempt included; taken back below if it was not sent.\n\t\tentry.attempts += 1\n\t\tentry.lastReason = 'timeout'\n\t\t// Armed before sending: a port that answers synchronously finds the timer to\n\t\t// clear (or replace with a throttle back-off) instead of leaking a new one.\n\t\tentry.timer = clock.setTimeout(() => onAttemptTimeout(entry), attemptWaitMs(entry))\n\t\tlet sent: boolean\n\t\ttry {\n\t\t\tsent =\n\t\t\t\tport.send({ type: 'blob-chunk-request', requestId: entry.requestId, hash: entry.hash }) !==\n\t\t\t\tfalse\n\t\t} catch {\n\t\t\t// A port that throws (its connection just closed) did not send: the request\n\t\t\t// stays pending and is re-sent by its timer or on ready, never lost.\n\t\t\tsent = false\n\t\t}\n\t\tif (!sent) {\n\t\t\tif (pending.get(entry.requestId) === entry) {\n\t\t\t\tentry.attempts -= 1\n\t\t\t\tif (!entry.backingOff) entry.lastReason = 'not-connected'\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (retryReason !== null) {\n\t\t\tnotify({\n\t\t\t\ttype: 'blob:request-retried',\n\t\t\t\thash: entry.hash,\n\t\t\t\trequestId: entry.requestId,\n\t\t\t\tattempt: entry.attempts,\n\t\t\t\treason: retryReason,\n\t\t\t})\n\t\t}\n\t}\n\n\tconst retry = (entry: PendingChunkRequest, reason: RetryReason): void => {\n\t\tattempt(entry, reason)\n\t}\n\n\tconst failThrottledTooLong = (entry: PendingChunkRequest): void => {\n\t\tfail(\n\t\t\tentry,\n\t\t\t'BLOB_CHUNK_TIMEOUT',\n\t\t\t`Blob chunk request for ${entry.hash} was throttled for longer than ${maxThrottleWaitMs}ms`,\n\t\t)\n\t}\n\n\t/**\n\t * Fail the request if a budget ran out, judged by the clock now, not when the timer\n\t * or re-send was planned: an event loop suspended past a budget (a sleeping tab or\n\t * device) must not re-send a request it should already have failed, nor keep it\n\t * pending for another deadline. Every timer callback and the reconnect re-send call\n\t * this first. Returns true when the request failed.\n\t */\n\tconst failIfOverBudget = (entry: PendingChunkRequest): boolean => {\n\t\tif (pending.get(entry.requestId) !== entry) return true\n\t\tconst now = clock.now()\n\t\tif (entry.backingOff && now - entry.startedAtMs > maxThrottleWaitMs) {\n\t\t\tfailThrottledTooLong(entry)\n\t\t\treturn true\n\t\t}\n\t\tif (now - entry.lastAnswerAtMs >= deadlineMs) {\n\t\t\tfail(\n\t\t\t\tentry,\n\t\t\t\t'BLOB_CHUNK_TIMEOUT',\n\t\t\t\t`Blob chunk request for ${entry.hash} got no answer within ${deadlineMs}ms (${entry.attempts} attempts, last: ${entry.lastReason}). The transfer is resumable: pull the blob again to fetch the missing chunks.`,\n\t\t\t)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tconst onAttemptTimeout = (entry: PendingChunkRequest): void => {\n\t\tif (failIfOverBudget(entry)) return\n\t\tretry(entry, entry.lastReason === 'not-connected' ? 'not-connected' : 'timeout')\n\t}\n\n\tconst onBackoffEnd = (entry: PendingChunkRequest): void => {\n\t\tif (failIfOverBudget(entry)) return\n\t\tretry(entry, 'throttled')\n\t}\n\n\tport.onMessage((message) => {\n\t\tif (message.type !== 'blob-chunk-response') {\n\t\t\treturn\n\t\t}\n\t\tconst entry = pending.get(message.requestId)\n\t\tif (!entry) {\n\t\t\t// Already answered (a re-sent request is answered twice), failed or closed:\n\t\t\t// the first answer won, so a late duplicate is ignored.\n\t\t\treturn\n\t\t}\n\t\tif (message.throttled === true) {\n\t\t\t// Over the server's blob budget: back off and ask again, same request id.\n\t\t\tclock.clearTimeout(entry.timer)\n\t\t\tconst now = clock.now()\n\t\t\tentry.lastAnswerAtMs = now\n\t\t\tentry.lastReason = 'throttled'\n\t\t\tentry.throttledCount += 1\n\t\t\tconst backoff = Math.min(maxDelayMs, minDelayMs * 2 ** (entry.throttledCount - 1))\n\t\t\tconst delay = Math.min(maxDelayMs, Math.max(minDelayMs, message.retryAfterMs ?? backoff))\n\t\t\tif (now + delay - entry.startedAtMs > maxThrottleWaitMs) {\n\t\t\t\tfailThrottledTooLong(entry)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tentry.backingOff = true\n\t\t\tentry.timer = clock.setTimeout(() => onBackoffEnd(entry), delay)\n\t\t\treturn\n\t\t}\n\t\tif (message.bytes === null) {\n\t\t\t// A real answer (\"not held\"). It fails here, not as a bare null, so the error\n\t\t\t// carries what only this provider measured: how many attempts were sent before\n\t\t\t// the answer (re-sends after silence, reconnects, throttles), not a guessed 1.\n\t\t\t// The ChunkProvider contract allows either; receiveBlob and fetchBlobManifest\n\t\t\t// report both as BLOB_CHUNK_UNAVAILABLE.\n\t\t\tentry.lastReason = 'not-held'\n\t\t\tfail(\n\t\t\t\tentry,\n\t\t\t\t'BLOB_CHUNK_UNAVAILABLE',\n\t\t\t\t`Blob chunk ${entry.hash} could not be obtained after ${entry.attempts} attempts: no reachable peer or server holds it, or may share it with this device`,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tif (!finish(entry)) return\n\t\tentry.resolve(message.bytes)\n\t})\n\n\t// Requests pending across a reconnect may have been lost with the old connection\n\t// (or never sent): re-send them at once instead of waiting out their timers.\n\tport.onReady?.(() => {\n\t\tif (closed) return\n\t\tfor (const entry of [...pending.values()]) {\n\t\t\t// A reconnect after a suspension may come before the overdue timers run.\n\t\t\tif (failIfOverBudget(entry)) continue\n\t\t\tif (entry.backingOff) continue\n\t\t\tretry(entry, 'reconnected')\n\t\t}\n\t})\n\n\treturn {\n\t\tpendingCount: () => pending.size,\n\t\tclose(): void {\n\t\t\tif (closed) return\n\t\t\tclosed = true\n\t\t\tfor (const entry of [...pending.values()]) {\n\t\t\t\tentry.lastReason = 'closed'\n\t\t\t\tfail(\n\t\t\t\t\tentry,\n\t\t\t\t\t'BLOB_CHUNK_CANCELLED',\n\t\t\t\t\t`Blob chunk request for ${entry.hash} was cancelled: the chunk provider closed`,\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\t\tgetChunk(hash: string): Promise<Uint8Array | null> {\n\t\t\tif (closed) {\n\t\t\t\treturn Promise.reject(\n\t\t\t\t\tnew BlobTransferError(\n\t\t\t\t\t\t`Blob chunk request for ${hash} was refused: the chunk provider is closed`,\n\t\t\t\t\t\t'BLOB_CHUNK_CANCELLED',\n\t\t\t\t\t\thash,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\t'closed',\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst requestId = generateUUIDv7()\n\t\t\treturn new Promise<Uint8Array | null>((resolve, reject) => {\n\t\t\t\tconst now = clock.now()\n\t\t\t\tconst entry: PendingChunkRequest = {\n\t\t\t\t\trequestId,\n\t\t\t\t\thash,\n\t\t\t\t\tresolve,\n\t\t\t\t\treject,\n\t\t\t\t\ttimer: undefined,\n\t\t\t\t\tbackingOff: false,\n\t\t\t\t\tstartedAtMs: now,\n\t\t\t\t\tlastAnswerAtMs: now,\n\t\t\t\t\tattempts: 0,\n\t\t\t\t\ttries: 0,\n\t\t\t\t\tthrottledCount: 0,\n\t\t\t\t\tlastReason: 'timeout',\n\t\t\t\t}\n\t\t\t\tpending.set(requestId, entry)\n\t\t\t\tattempt(entry, null)\n\t\t\t})\n\t\t},\n\t}\n}\n\n/**\n * Serve blob chunk requests arriving on a message port from a blob store. Answers\n * each `blob-chunk-request` with the bytes for that hash, or null when the store\n * does not hold it. Returns nothing; attach it once per connection.\n *\n * @param port - The message port from the peer requesting chunks\n * @param blobStore - The store to serve chunks from (keyed by chunk hash)\n */\nexport function serveBlobChunks(\n\tport: ChunkMessagePort,\n\tblobStore: ContentAddressedBlobStore,\n): void {\n\tport.onMessage((message) => {\n\t\tif (message.type !== 'blob-chunk-request') {\n\t\t\treturn\n\t\t}\n\t\tvoid blobStore.get(message.hash).then(\n\t\t\t(bytes) => {\n\t\t\t\tport.send({ type: 'blob-chunk-response', requestId: message.requestId, bytes })\n\t\t\t},\n\t\t\t() => {\n\t\t\t\t// Integrity failure or read error: report as not-held rather than\n\t\t\t\t// crashing the connection. The requester treats null as unavailable.\n\t\t\t\tport.send({ type: 'blob-chunk-response', requestId: message.requestId, bytes: null })\n\t\t\t},\n\t\t)\n\t})\n}\n\n/**\n * Create a connected in-memory pair of {@link ChunkMessagePort}s. Messages sent\n * on one arrive on the other, asynchronously (next microtask) so the pair models\n * a real transport rather than re-entrant synchronous delivery. For tests.\n */\nexport function createChunkPortPair(): { a: ChunkMessagePort; b: ChunkMessagePort } {\n\tconst handlersA: Array<(m: ChunkMessage) => void> = []\n\tconst handlersB: Array<(m: ChunkMessage) => void> = []\n\n\tconst a: ChunkMessagePort = {\n\t\tsend(message) {\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tfor (const handler of handlersB) {\n\t\t\t\t\thandler(message)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn true\n\t\t},\n\t\tonMessage(handler) {\n\t\t\thandlersA.push(handler)\n\t\t},\n\t}\n\tconst b: ChunkMessagePort = {\n\t\tsend(message) {\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tfor (const handler of handlersA) {\n\t\t\t\t\thandler(message)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn true\n\t\t},\n\t\tonMessage(handler) {\n\t\t\thandlersB.push(handler)\n\t\t},\n\t}\n\treturn { a, b }\n}\n","// @korajs/store — public API\n// Every export here is a public API commitment. Be explicit.\n\n// === Types ===\nexport type {\n\tApplyRemoteOptions,\n\tApplyResult,\n\tInstantUpdatesOptions,\n\tLocalMutationHandler,\n\tMaterializedRowSnapshot,\n\tProvisionalSideEffect,\n\tRemoteApplyBatch,\n\tRemoteBatchCollectionReader,\n\tRowVersionState,\n\tCollectionRecord,\n\tReplaySnapshot,\n\tMigrationPlan,\n\tOrderByClause,\n\tOrderByDirection,\n\tQueryDescriptor,\n\tStoreConfig,\n\tStoreIsolation,\n\tStorageFallbackReason,\n\tStorageOpenState,\n\tStorageAdapter,\n\tSubscriptionCallback,\n\tTransaction,\n\tWhereClause,\n\tWhereOperators,\n\tWriteDurabilityState,\n\tWriteOptions,\n} from './types'\n\n// === Storage-loss evidence ===\nexport type { StorageEviction } from './adapters/storage-evidence'\n\n// === Staged replication (first-visit parity S3) ===\nexport { StagingReplica } from './staging/staging-replica'\nexport type { StagingMergeOptions, StagingProgress } from './staging/staging-replica'\nexport type { StagingMergeResult } from './staging/staging-merge'\n\n// === Errors ===\nexport {\n\tAdapterError,\n\tBridgeTerminatedError,\n\tBuildSupersededError,\n\ttype BuildSupersededInfo,\n\tLeaderUnresponsiveError,\n\tLocalDatabaseNotFoundError,\n\tNoLeaderError,\n\tNodeOwnedByAnotherUserError,\n\tStoreReadOnlyError,\n\tOptimisticLockError,\n\tPersistenceError,\n\tQueryError,\n\tRecordNotFoundError,\n\tStampedFieldError,\n\tRequestAbortedError,\n\tSchemaVersionAheadError,\n\tStorageBackendMismatchError,\n\tStorageDurabilityError,\n\tStorageFormatAheadError,\n\tStorageInUseError,\n\tStoreNotOpenError,\n\tTabCoordinationUnavailableError,\n\tVersionGateClosedError,\n\tUnsyncedDataError,\n\tWorkerInitError,\n\tWorkerTimeoutError,\n\tWriteNotDurableError,\n} from './errors'\n\n// === Offline pins (app.offline.keep) ===\nexport type {\n\tNewOfflinePin,\n\tOfflinePinWriteResult,\n\tStoredOfflinePin,\n\tStoredOfflinePinHold,\n} from './sync/offline-pins'\n\n// === Version gate (one build writes a database at a time) ===\nexport {\n\tVersionGate,\n\tcompareTabKeys,\n\tparseTabLockName,\n\ttabLockName,\n\tschemaFingerprint,\n\ttype RetirePhase,\n\ttype SupersededInfo,\n\ttype TabIdentity,\n\ttype VersionGateMode,\n\ttype VersionGateOptions,\n\ttype VersionGateSnapshot,\n\ttype VersionGateState,\n} from './multi-tab/version-gate'\nexport type { WriteScope } from './multi-tab/write-gate'\n\n// === Operation log compaction ===\nexport type { CompactionResult, CompactionStrategy } from './compaction/types'\nexport { COMPACTION_BASELINE_META_KEY } from './compaction/types'\nexport {\n\tcompactOperationLog,\n\tcomputeAckCompactionWatermark,\n} from './compaction/compact-operation-log'\n\n// === W7 record fold (client materialization) ===\nexport { mergeYjsUpdates } from './fold/record-folder'\nexport type { RematerializationMode } from './fold/rematerialize'\n\n// === Seeds (first-visit parity S4b) ===\nexport type {\n\tPurgeOutcome,\n\tSeedInput,\n\tSeedMeta,\n\tSeedOutcome,\n\tSeedRow,\n\tSeedSkipReason,\n} from './seed/seed-store'\n\n// === Clock rebase (timestamp rebase of unsynced operations) ===\nexport type { ClockRebaseResult } from './sync/rebase-unsynced-operations'\nexport type { NodeRotationResult } from './sync/rotate-node-id'\nexport type { ResequenceResult } from './sync/rehash-operation'\nexport type { UnappliedOperation } from './sync/sync-durability'\nexport type {\n\tAdoptionSchedule,\n\tLocalNodeRecord,\n\tParkedAdoption,\n\tTerminalRejection,\n} from './sync/local-sync-records'\nexport type { PrincipalBinding } from './store/store'\n\n// === Sync state helpers ===\nexport {\n\tcollectOperationsAheadOfServer,\n\tdeserializeVersionVectorFromMeta,\n\tLAST_ACKED_SERVER_VECTOR_META_KEY,\n\tmergeVersionVectors,\n\tserializeVersionVectorToMeta,\n} from './sync/sync-state'\n\n// === Store ===\nexport { Store } from './store/store'\nexport type { CollectionAccessor } from './store/store'\n\n// === Query ===\nexport { QueryBuilder } from './query/query-builder'\nexport { normalizeWhere, queryKey } from './query/query-key'\nexport { VIRTUAL_TIMESTAMP_FIELDS, VIRTUAL_TIMESTAMP_FIELD_NAMES } from './query/sql-builder'\nexport type { VirtualTimestampField } from './query/sql-builder'\nexport type {\n\tQueryCoverage,\n\tQueryErrorPhase,\n\tQuerySubscriptionError,\n\tSubscribeOptions,\n} from './types'\n\n// === Durable storage (navigator.storage.persist), never on the startup path ===\nexport { StoragePersistence } from './persistence/storage-persistence'\nexport type {\n\tPersistenceRequestReason,\n\tPersistenceStorageManager,\n\tStoragePersistenceOptions,\n\tStoragePersistenceState,\n\tStoragePersistenceStatus,\n} from './persistence/storage-persistence'\nexport { QueryStore } from './reactivity/query-store'\nexport { assertQueryReady } from './reactivity/assert-query-ready'\nexport {\n\tgetSharedQueryStoreCache,\n\tQueryStoreCache,\n} from './reactivity/query-store-cache'\n\n// === Subscription ===\nexport { SubscriptionManager } from './subscription/subscription-manager'\nexport type {\n\tRecordsChange,\n\tRecordsChangeListener,\n\tRegisterOptions,\n\tSubscriptionManagerOptions,\n\tSubscriptionStats,\n} from './subscription/subscription-manager'\nexport type { ResultsEqual } from './subscription/result-equality'\nexport { SubscriptionBloomFilter } from './subscription/bloom-filter'\n\n// === Collection ===\nexport { Collection } from './collection/collection'\n\n// === State Machine Validation ===\nexport {\n\tInvalidStateTransitionError,\n\tvalidateStateTransition,\n\tvalidateUpdateStateMachine,\n} from './state-machine/state-validator'\n\n// === Transaction ===\nexport { TransactionContext } from './transaction/transaction-context'\nexport type {\n\tTransactionCollectionAccessor,\n\tTransactionContextConfig,\n} from './transaction/transaction-context'\n\n// === Sequences ===\nexport { SequenceManager } from './sequences/sequence-manager'\n\n// === Richtext controller (framework bindings) ===\nexport { createRichTextController } from './richtext/create-richtext-controller'\nexport { asRichTextSyncEngine } from './richtext/as-rich-text-sync-engine'\nexport type {\n\tCreateRichTextControllerOptions,\n\tRichTextAwarenessUser,\n\tRichTextController,\n\tRichTextControllerSnapshot,\n\tRichTextCursorInfo,\n\tRichTextSyncEngine,\n} from './richtext/types'\n\n// === Richtext Serialization ===\nexport {\n\tdecodeRichtext,\n\tencodeRichtext,\n\trichtextToPlainText,\n\trichtextStatesEqual,\n} from './serialization/richtext-serializer'\n\n// === Query Utilities ===\nexport { pluralize, singularize } from './query/pluralize'\n\n// === Backup/Restore ===\nexport {\n\tBACKUP_VERSION,\n\tBackupFormatError,\n\tconvertBackupV1,\n\texportBackup,\n\treadBackupManifest,\n\trestoreBackup,\n\tverifyBackupChecksum,\n} from './backup'\nexport type {\n\tConvertBackupV1Options,\n\tBackupManifest,\n\tBackupOptions,\n\tBackupProgress,\n\tRestoreOptions,\n\tRestoreResult,\n} from './backup'\n\n// === Log integrity (W8 step 0) ===\nexport { LOG_QUARANTINE_TABLE } from './log-integrity/log-integrity'\nexport type {\n\tLogIntegrityReport,\n\tLogIntegrityRow,\n\tLogRowProblem,\n\tLogSequenceGap,\n} from './log-integrity/log-integrity'\n\n// === Audit export ===\nexport {\n\tdecodeAuditExport,\n\tpersistedAuditTraceFromEvent,\n\treadAuditExportManifest,\n\tverifyAuditExportChecksum,\n} from './audit'\nexport type {\n\tAuditExportManifest,\n\tAuditExportOptions,\n\tAuditExportPayload,\n\tAuditExportProgress,\n\tAuditTraceQuery,\n\tPersistedAuditTrace,\n} from './audit'\n\n// === Content-addressed blob store ===\nexport {\n\tBlobIntegrityError,\n\tMemoryBlobStore,\n\ttype ContentAddressedBlobStore,\n} from './blob/content-addressed-blob-store'\nexport {\n\tOpfsBlobStore,\n\tcreateOpfsBlobDirectory,\n\tcreateOpfsBlobStore,\n\ttype OpfsBlobDirectory,\n} from './blob/opfs-blob-store'\nexport {\n\tDEFAULT_CHUNK_SIZE,\n\tchunkBlob,\n\treassembleBlob,\n\ttype BlobManifest,\n\ttype BlobManifestMetadata,\n} from './blob/blob-chunking'\nexport {\n\tprepareBlobForSend,\n\treceiveBlob,\n\ttype ChunkProvider,\n\ttype ReceiveBlobResult,\n\ttype ReceiveBlobStores,\n} from './blob/blob-transfer'\nexport {\n\tfetchBlobManifest,\n\tparseBlobManifest,\n\tputBlobForTransfer,\n\tresolveBlobManifest,\n\tserializeBlobManifest,\n} from './blob/blob-manifest-transfer'\nexport {\n\tcreateMemoryServerBlobStore,\n\ttoServerBlobCallbacks,\n\ttype ServerBlobCallbacks,\n} from './blob/server-blob-callbacks'\nexport {\n\tcollectBlobGarbage,\n\tDEFAULT_BLOB_GC_GRACE_MS,\n\textractBlobRefs,\n\ttype BlobGcOptions,\n\ttype BlobGcResult,\n} from './blob/blob-gc'\nexport {\n\tBlobTransferError,\n\ttype BlobChunkFailureReason,\n\ttype BlobTransferErrorCode,\n} from './blob/blob-transfer-error'\nexport {\n\tcreateChunkPortPair,\n\tcreateRemoteChunkProvider,\n\tserveBlobChunks,\n\tDEFAULT_BLOB_CHUNK_ATTEMPT_TIMEOUT_MS,\n\tDEFAULT_BLOB_CHUNK_DEADLINE_MS,\n\tDEFAULT_BLOB_CHUNK_MAX_ATTEMPT_TIMEOUT_MS,\n\ttype ChunkProviderClock,\n\ttype ChunkMessage,\n\ttype ChunkMessagePort,\n\ttype ChunkRequestMessage,\n\ttype ChunkResponseMessage,\n\ttype RemoteChunkProvider,\n\ttype RemoteChunkProviderOptions,\n} from './blob/blob-chunk-transport'\n\n// The store reads `schema.access` (access narrowing of its own writes). A production browser\n// bundle of the lite entry defers the access compiler; whoever loads the store has it.\nimport { registerAccessCompiler } from '@korajs/core'\nregisterAccessCompiler()\n"]}