snapback2 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +127 -0
- package/bin/snapback2.mjs +36 -0
- package/dist/api.d.ts +20 -0
- package/dist/assets.d.ts +34 -0
- package/dist/client-assets.d.ts +26 -0
- package/dist/client-offline.d.ts +94 -0
- package/dist/client-outbox.d.ts +58 -0
- package/dist/client-upload.d.ts +41 -0
- package/dist/client-wire.d.ts +41 -0
- package/dist/client.d.ts +12 -0
- package/dist/client.mjs +5 -0
- package/dist/client.mjs.map +7 -0
- package/dist/compiler-core.mjs +60 -0
- package/dist/compiler-core.mjs.map +7 -0
- package/dist/compiler-lib.d.ts +71 -0
- package/dist/compiler.mjs +5 -0
- package/dist/compiler.mjs.map +7 -0
- package/dist/drain.d.ts +33 -0
- package/dist/expo/files.d.ts +3 -0
- package/dist/expo/index.d.ts +16 -0
- package/dist/expo/token-store.d.ts +7 -0
- package/dist/expo/witness.d.ts +28 -0
- package/dist/expo/witness.mjs +2 -0
- package/dist/expo/witness.mjs.map +7 -0
- package/dist/expo.d.ts +4 -0
- package/dist/expo.mjs +9 -0
- package/dist/expo.mjs.map +7 -0
- package/dist/guide/auth.md +89 -0
- package/dist/guide/effects.md +52 -0
- package/dist/guide/families.json +446 -0
- package/dist/guide/grammar.md +52 -0
- package/dist/guide/live-query.md +27 -0
- package/dist/guide/offline.md +75 -0
- package/dist/guide/personas.md +15 -0
- package/dist/guide/quarry.md +297 -0
- package/dist/guide/testing.md +57 -0
- package/dist/index.d.ts +362 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +7 -0
- package/dist/offline-protocol.d.ts +180 -0
- package/dist/offline-schema.d.ts +1 -0
- package/dist/offline.d.ts +177 -0
- package/dist/react-core.d.ts +91 -0
- package/dist/react-core.mjs +2 -0
- package/dist/react-core.mjs.map +7 -0
- package/dist/react-native/components.d.ts +23 -0
- package/dist/react-native/files.d.ts +43 -0
- package/dist/react-native/source.d.ts +16 -0
- package/dist/react-native.d.ts +4 -0
- package/dist/react-native.mjs +2 -0
- package/dist/react-native.mjs.map +7 -0
- package/dist/react.d.ts +19 -0
- package/dist/react.mjs +2 -0
- package/dist/react.mjs.map +7 -0
- package/dist/sqlite-test.mjs +1720 -0
- package/dist/sqlite-test.mjs.map +7 -0
- package/dist/sse.d.ts +44 -0
- package/dist/store/byte-cache.d.ts +162 -0
- package/dist/store/canonical.d.ts +2 -0
- package/dist/store/indexeddb.d.ts +23 -0
- package/dist/store/locks.d.ts +11 -0
- package/dist/store/outbox.d.ts +113 -0
- package/dist/store/overlay-retirement.d.ts +17 -0
- package/dist/store/projection.d.ts +11 -0
- package/dist/store/range-store.d.ts +388 -0
- package/dist/store/sqlite-driver.conformance.d.ts +7 -0
- package/dist/store/sqlite-driver.d.ts +16 -0
- package/dist/store/sqlite-expo.d.ts +3 -0
- package/dist/store/sqlite.d.ts +31 -0
- package/dist/templates/chat/expo/App.tsx +29 -0
- package/dist/templates/chat/expo/app.json +11 -0
- package/dist/templates/chat/expo/index.js +3 -0
- package/dist/templates/chat/expo/shared/log.js +92 -0
- package/dist/templates/chat/expo/shared/log.ts +130 -0
- package/dist/templates/chat/expo/shared/offline.js +8 -0
- package/dist/templates/chat/expo/shared/offline.ts +9 -0
- package/dist/templates/chat/expo/src/Chat.tsx +23 -0
- package/dist/templates/chat/expo/src/Composer.tsx +23 -0
- package/dist/templates/chat/expo/src/MediaView.tsx +29 -0
- package/dist/templates/chat/expo/src/Witness.tsx +131 -0
- package/dist/templates/chat/expo/src/screens/Inbox.tsx +9 -0
- package/dist/templates/chat/expo/src/screens/Search.tsx +10 -0
- package/dist/templates/chat/expo/src/screens/Thread.tsx +22 -0
- package/dist/templates/chat/expo/src/witness-state.ts +68 -0
- package/dist/templates/chat/expo/tsconfig.json +5 -0
- package/dist/templates/chat/react/index.html +5 -0
- package/dist/templates/chat/react/shared/log.js +92 -0
- package/dist/templates/chat/react/shared/log.ts +130 -0
- package/dist/templates/chat/react/shared/offline.js +8 -0
- package/dist/templates/chat/react/shared/offline.ts +9 -0
- package/dist/templates/chat/react/src/App.tsx +36 -0
- package/dist/templates/chat/react/src/Composer.tsx +45 -0
- package/dist/templates/chat/react/src/Inbox.tsx +24 -0
- package/dist/templates/chat/react/src/Search.tsx +26 -0
- package/dist/templates/chat/react/src/Thread.tsx +126 -0
- package/dist/templates/chat/react/src/env.d.ts +1 -0
- package/dist/templates/chat/react/src/main.tsx +20 -0
- package/dist/templates/chat/shared/log.js +92 -0
- package/dist/templates/chat/shared/log.ts +130 -0
- package/dist/templates/chat/shared/offline.js +8 -0
- package/dist/templates/chat/shared/offline.ts +9 -0
- package/dist/templates/chat/snapback/deliveries.q +33 -0
- package/dist/templates/chat/snapback/delivery.ts +30 -0
- package/dist/templates/chat/snapback/feeds.q +14 -0
- package/dist/templates/chat/snapback/follows.q +11 -0
- package/dist/templates/chat/snapback/groups.q +40 -0
- package/dist/templates/chat/snapback/messages.q +32 -0
- package/dist/templates/chat/snapback/notifications.q +7 -0
- package/dist/templates/chat/snapback/posts.q +4 -0
- package/dist/templates/chat/snapback/profiles.q +17 -0
- package/dist/templates/chat/snapback/schema.q +136 -0
- package/dist/templates/chat/snapback/seed.ts +45 -0
- package/dist/templates/chat/snapback/tests/chat.test.ts +759 -0
- package/dist/templates/react/index.html +5 -0
- package/dist/templates/react/src/App.tsx +5 -0
- package/dist/templates/react/src/main.tsx +18 -0
- package/dist/templates/todos/snapback/schema.q +11 -0
- package/dist/templates/todos/snapback/seed.ts +10 -0
- package/dist/templates/todos/snapback/tests/todos.test.ts +13 -0
- package/dist/templates/todos/snapback/todos.q +6 -0
- package/dist/test-runner.mjs +8541 -0
- package/dist/test-runner.mjs.map +7 -0
- package/dist/test.d.ts +28 -0
- package/dist/test.mjs +8541 -0
- package/dist/test.mjs.map +7 -0
- package/dist/token-store.d.ts +3 -0
- package/dist/twin-hydrate.d.ts +43 -0
- package/dist/twin.d.ts +70 -0
- package/dist/types.d.ts +410 -0
- package/dist/witness-test.mjs +2 -0
- package/dist/witness-test.mjs.map +7 -0
- package/package.json +117 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/store/sqlite-node.ts", "../src/store/sqlite-driver.ts", "../src/store/byte-cache.ts", "../src/store/canonical.ts", "../src/store/overlay-retirement.ts", "../src/store/range-store.ts", "../src/store/locks.ts", "../src/store/projection.ts", "../src/store/sqlite.ts", "../src/store/sqlite-driver.conformance.ts", "../tests/sqlite-state.ts", "../src/react-native/files.ts"],
|
|
4
|
+
"sourcesContent": ["import { DatabaseSync } from \"node:sqlite\";\nimport { realpathSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { driverQueue, type SqliteDriver, type SqliteExecutor } from \"./sqlite-driver.js\";\n\n/** Test-only Node 24 driver. Opening is lazy so carrier failures use E_OFFLINE_CARRIER. */\nexport function nodeSqliteDriver(path: string): SqliteDriver {\n let database: DatabaseSync | undefined;\n let identity: string | undefined;\n const db = () => database ??= new DatabaseSync(path);\n const queue = driverQueue();\n const executor: SqliteExecutor = {\n async run(sql, params = []) { db().prepare(sql).run(...params); },\n async get<T>(sql: string, params = []) { return (db().prepare(sql).get(...params) ?? undefined) as T | undefined; },\n async all<T>(sql: string, params = []) { return db().prepare(sql).all(...params) as T[]; },\n };\n return {\n get identity() {\n db(); // Resolve after open creates the file; symlinks must share ownership.\n return identity ??= path === \":memory:\" || path === \"\"\n ? `sqlite:temporary:${randomUUID()}` : `sqlite:${realpathSync(path)}`;\n },\n run: (sql, params) => queue(() => executor.run(sql, params)),\n get: (sql, params) => queue(() => executor.get(sql, params)),\n all: (sql, params) => queue(() => executor.all(sql, params)),\n exec: (sql) => queue(async () => { db().exec(sql); }),\n // @ref LLP 1013#3-the-sqlite-carrier \u2014 await the async body before COMMIT;\n // a synchronous callback transaction would commit while the body is suspended.\n transaction: (body) => queue(async () => {\n db().exec(\"BEGIN IMMEDIATE\");\n try {\n const result = await body(executor);\n db().exec(\"COMMIT\");\n return result;\n } catch (error) {\n try { db().exec(\"ROLLBACK\"); } catch { /* Preserve the body/COMMIT failure. */ }\n throw error;\n }\n }),\n close: () => queue(async () => { database?.close(); database = undefined; }),\n };\n}\n", "export type SqliteParams = Array<string | number | null | Uint8Array>;\n\nexport interface SqliteExecutor {\n run(sql: string, params?: SqliteParams): Promise<void>;\n get<T>(sql: string, params?: SqliteParams): Promise<T | undefined>;\n all<T>(sql: string, params?: SqliteParams): Promise<T[]>;\n}\n\nexport interface SqliteDriver extends SqliteExecutor {\n /** Stable identity of the database, shared by every connection/factory opening it. */\n readonly identity: string;\n exec(sql: string): Promise<void>;\n /** All statements in body must use tx. Commit only after its promise resolves. */\n transaction<T>(body: (tx: SqliteExecutor) => Promise<T>): Promise<T>;\n close(): Promise<void>;\n}\n\n/** Outer operations wait for an async transaction; its executor bypasses the queue. */\nexport function driverQueue(): <T>(body: () => Promise<T>) => Promise<T> {\n let tail = Promise.resolve();\n return (body) => {\n const result = tail.then(body);\n tail = result.then(() => undefined, () => undefined);\n return result;\n };\n}\n", "// @ref LLP 1006#9b-bytes-on-the-device-author-ruling-2026-09-04 \u2014 bytes are cached under the owning row's lease, or not at all.\n// @ref LLP 1012#9-asset-bytes-on-the-device \u2014 the ByteCache sits beside the range store and joins its swap; view-once is excluded at view time.\n\nimport type { RangeStore, RowRef, StoredRow } from \"./range-store.js\";\n\n/** One cached rendition: what a component fetched at the width it asked for. */\nexport interface ByteCacheEntry {\n assetId: string;\n width: number | null;\n size: number;\n type: string;\n /** Logical last-read stamp on the range store's clock; the LRU orders by it. */\n lastRead: number;\n}\n\n/** A view-once row that was viewed, with the asset ids it carried at that moment. */\nexport interface ViewedRecord { at: number; assets: string[] }\n\nexport interface ByteCachePut { assetId: string; width: number | null; bytes: Uint8Array; type: string }\nexport interface ByteSwapRequest { put?: ByteCachePut[]; touch?: string[]; ceiling?: number }\n\n/** What a carrier persists beside the state in the same swap: payloads to write and keys to drop. */\nexport interface ByteDelta { put: Array<{ key: string; bytes: Uint8Array }>; remove: string[] }\n\nexport interface ByteCacheStatus { entries: ByteCacheEntry[]; totalBytes: number; viewed: RowRef[] }\nexport interface AssetBytes { bytes: Uint8Array; type: string }\n/** An opaque identity held by one mounted viewing instance, never shared by asset id. */\nexport interface AssetFetchOptions { signal?: AbortSignal; viewing?: object }\nexport type ByteCacheOutcome = \"cached\" | \"viewed\" | \"unleased\" | \"refused\";\nexport type ViewOncePredicate = (table: string, row: Record<string, unknown>) => boolean;\n\n/** The byte surface the swap engine exposes beside `RangeStore`; only the carriers implement it. */\nexport interface ByteCarrier {\n readBytes(assetId: string, width: number | null): Promise<{ bytes: Uint8Array; type: string } | undefined>;\n bytes(): Promise<ByteCacheStatus>;\n rowsReferencing(assetId: string): Promise<StoredRow[]>;\n viewedAsset(assetId: string): Promise<boolean>;\n viewedRows(): Promise<RowRef[]>;\n /** LRU read stamps, coalesced: stamped in memory now, persisted by the next swap. */\n touchBytes(keys: string[]): Promise<void>;\n commit(swap: { bytes?: ByteSwapRequest; viewed?: RowRef[] }): Promise<void>;\n}\n\n/** The client-facing byte cache: `client.assetCache` when the client has an offline store. */\nexport interface AssetCache {\n /** Session custody changes revoke mounted object URLs. */\n subscribeCustody?(listener: () => void): () => void;\n getCustody?(): number;\n getBytes(assetId: string, width: number | null, viewing?: object): Promise<AssetBytes | undefined>;\n putBytes(assetId: string, width: number | null, value: AssetBytes, viewing?: object): Promise<ByteCacheOutcome>;\n canServe(assetId: string, viewing?: object): Promise<boolean>;\n /** The held bytes for an asset at a width, or nothing: never fetched, evicted with its row, viewed, or sealed. */\n get(assetId: string, width: number | null, viewing?: object): Promise<Blob | undefined>;\n /** True once a view-once row carrying this asset was viewed on this partition. */\n viewed(assetId: string): Promise<boolean>;\n /** True while a held row carrying this asset is view-once (`offline.viewOnce`) and not yet viewed. */\n viewOnce(assetId: string): Promise<boolean>;\n /** Marks the held view-once rows carrying this asset viewed: what a player calls when playback starts. */\n markViewed(assetId: string): Promise<boolean>;\n status(): Promise<ByteCacheStatus>;\n}\n\nexport const ASSET_ID = /^s2id-[0-9a-f]{32}-[0-9a-f]{16}$/;\nconst SESSION_VIEW_LIMIT = 8;\n\nexport function byteKey(assetId: string, width: number | null): string {\n return width === null ? assetId : `${assetId}.w${width}`;\n}\n\nfunction rowKey(ref: RowRef): string {\n return `${ref.table}\\u0000${ref.id}`;\n}\n\nfunction positive(value: unknown): boolean {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0;\n}\n\n/** The closed asset record shape (LLP 1006 \u00A71): exactly id, width, height, and duration for video. */\nexport function assetRecordId(value: unknown): string | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort().join(\",\");\n if (keys !== \"height,id,width\" && keys !== \"duration,height,id,width\") return undefined;\n if (typeof record.id !== \"string\" || !ASSET_ID.test(record.id)) return undefined;\n if (!positive(record.width) || !positive(record.height)) return undefined;\n if (\"duration\" in record && !positive(record.duration)) return undefined;\n return record.id;\n}\n\nexport function assetIdsIn(value: unknown, output = new Set<string>()): Set<string> {\n const id = assetRecordId(value);\n if (id !== undefined) output.add(id);\n else if (Array.isArray(value)) for (const item of value) assetIdsIn(item, output);\n else if (value && typeof value === \"object\") {\n for (const item of Object.values(value as Record<string, unknown>)) assetIdsIn(item, output);\n }\n return output;\n}\n\n/** Assets a held delivery references: through pooled rows and through inline answer data. */\nexport function leasedAssets(rows: Iterable<StoredRow>, answers: Iterable<{ data?: unknown }>): Set<string> {\n const leased = new Set<string>();\n for (const row of rows) assetIdsIn(row.row, leased);\n for (const answer of answers) if (answer.data !== undefined) assetIdsIn(answer.data, leased);\n return leased;\n}\n\nexport interface ByteSwapState {\n clock: number;\n rows: Record<string, StoredRow>;\n assets: Record<string, ByteCacheEntry>;\n viewed: Record<string, ViewedRecord>;\n}\n\n/**\n * View-once is tracked per row, never per asset id: an asset is refused only while\n * every held row carrying it was viewed. A row that is not viewed keeps its lease,\n * so one shared id never poisons an ordinary row's bytes.\n */\nexport function viewedOnlyAssets(state: Pick<ByteSwapState, \"rows\" | \"viewed\">): Set<string> {\n const viewed = new Set<string>();\n for (const record of Object.values(state.viewed)) for (const id of record.assets) viewed.add(id);\n if (viewed.size === 0) return viewed;\n for (const [key, row] of Object.entries(state.rows)) {\n if (state.viewed[key]) continue;\n for (const id of assetIdsIn(row.row)) viewed.delete(id);\n }\n return viewed;\n}\n\nfunction checkedPut(put: ByteCachePut): void {\n if (!put || typeof put !== \"object\" || typeof put.assetId !== \"string\" || !ASSET_ID.test(put.assetId)) {\n throw new TypeError(\"byte cache put must name an engine-minted asset id\");\n }\n if (put.width !== null && !positive(put.width)) throw new TypeError(\"byte cache put width must be null or a positive integer\");\n if (!(put.bytes instanceof Uint8Array)) throw new TypeError(\"byte cache put bytes must be a Uint8Array\");\n if (typeof put.type !== \"string\") throw new TypeError(\"byte cache put type must be a string\");\n}\n\n/**\n * The byte half of one swap, run after the row rules settled `state.rows`: viewed\n * marks, the lease purge, read touches, puts, then the ceiling. Returns what the\n * carrier must write and drop in the same transaction.\n */\nexport function applyByteSwap(\n state: ByteSwapState,\n swap: { bytes?: ByteSwapRequest; viewed?: RowRef[] },\n leased: Set<string>,\n): ByteDelta {\n const delta: ByteDelta = { put: [], remove: [] };\n for (const ref of swap.viewed ?? []) {\n if (!ref || typeof ref.table !== \"string\" || typeof ref.id !== \"string\") throw new TypeError(\"viewed rows must be row references\");\n const key = rowKey(ref);\n const assets = new Set(state.viewed[key]?.assets ?? []);\n assetIdsIn(state.rows[key]?.row, assets);\n state.viewed[key] = { at: Date.now(), assets: [...assets] };\n }\n const viewedAssets = viewedOnlyAssets(state);\n for (const [key, entry] of Object.entries(state.assets)) {\n if (leased.has(entry.assetId) && !viewedAssets.has(entry.assetId)) continue;\n delete state.assets[key];\n delta.remove.push(key);\n }\n for (const key of swap.bytes?.touch ?? []) {\n const entry = state.assets[key];\n if (entry) entry.lastRead = ++state.clock;\n }\n const ceiling = swap.bytes?.ceiling ?? Number.POSITIVE_INFINITY;\n if (!(ceiling > 0)) throw new TypeError(\"byte cache ceiling must be positive\");\n for (const put of swap.bytes?.put ?? []) {\n checkedPut(put);\n if (!leased.has(put.assetId) || viewedAssets.has(put.assetId)) continue;\n const size = put.bytes.byteLength;\n if (size === 0 || size > ceiling) continue;\n const key = byteKey(put.assetId, put.width);\n state.assets[key] = { assetId: put.assetId, width: put.width, size, type: put.type, lastRead: ++state.clock };\n delta.put.push({ key, bytes: put.bytes });\n }\n let total = Object.values(state.assets).reduce((sum, entry) => sum + entry.size, 0);\n while (total > ceiling) {\n const [key, victim] = Object.entries(state.assets)\n .reduce((least, item) => item[1].lastRead < least[1].lastRead ? item : least);\n delete state.assets[key];\n delta.remove.push(key);\n total -= victim.size;\n }\n delta.put = delta.put.filter((item) => state.assets[item.key] !== undefined);\n delta.remove = [...new Set(delta.remove)].filter((key) => state.assets[key] === undefined);\n return delta;\n}\n\nfunction isByteCarrier(store: RangeStore): store is RangeStore & ByteCarrier {\n const candidate = store as Partial<ByteCarrier>;\n return typeof candidate.readBytes === \"function\"\n && typeof candidate.bytes === \"function\"\n && typeof candidate.rowsReferencing === \"function\"\n && typeof candidate.viewedAsset === \"function\"\n && typeof candidate.viewedRows === \"function\"\n && typeof candidate.touchBytes === \"function\";\n}\n\nfunction checkedAssetId(assetId: string): string {\n if (typeof assetId !== \"string\" || !ASSET_ID.test(assetId)) throw new TypeError(\"asset id must be engine-minted\");\n return assetId;\n}\n\n/**\n * Bytes a component fetched, kept under the owning row's lease in the same\n * partition as the rows. A store without a byte carrier caches nothing.\n */\nexport class ByteCache implements AssetCache {\n /**\n * View-once bytes stay renderable inside the instance that viewed them, keyed by\n * the partition that viewed them; nothing here is durable. The runtime forgets it\n * on seal, wipe, partition change, and close, and `get` serves it only under the\n * custody the carrier path applies: this partition, unsealed, the row still held.\n */\n private readonly session = new Map<string, { viewing: object; value: AssetBytes }>();\n private partition?: string;\n private custody = 0;\n private readonly custodyListeners = new Set<() => void>();\n readonly getCustody = () => this.custody;\n readonly subscribeCustody = (listener: () => void) => {\n this.custodyListeners.add(listener);\n return () => { this.custodyListeners.delete(listener); };\n };\n private admissions: Promise<unknown> = Promise.resolve();\n\n constructor(\n readonly store: RangeStore,\n private readonly options: { maxAssetBytes: number; viewOnce?: ViewOncePredicate },\n ) {}\n\n /** The partition the runtime opened; a change drops every session blob. */\n bind(partition: string | undefined): void {\n if (this.partition !== partition) this.forget();\n this.partition = partition;\n }\n\n /** Drops the session blobs: seal, close, and wipe call this. */\n forget(): void {\n this.custody++;\n this.session.clear();\n for (const listener of this.custodyListeners) listener();\n }\n\n async get(assetId: string, width: number | null, viewing?: object): Promise<Blob | undefined> {\n const held = await this.getBytes(assetId, width, viewing);\n return held ? new Blob([held.bytes as BlobPart], { type: held.type }) : undefined;\n }\n\n // @ref LLP 1013#2-decisions \u2014 native paths exchange bytes, never RN Blobs.\n async getBytes(assetId: string, width: number | null, viewing?: object): Promise<AssetBytes | undefined> {\n const custody = this.custody;\n checkedAssetId(assetId);\n const store = this.carrier();\n if (!store) return undefined;\n // `viewedAsset` is false on a sealed partition, so the session is never consulted past a seal.\n if (await store.viewedAsset(assetId)) {\n const held = await this.sessionBytes(assetId, width, viewing);\n return custody === this.custody ? held : undefined;\n }\n if (await this.viewOnce(assetId)) return undefined;\n const held = await store.readBytes(assetId, width);\n if (!held) return undefined;\n // The touch is the LRU stamp, coalesced into the next swap; a closing partition may refuse it.\n await store.touchBytes([byteKey(assetId, width)]).catch(() => undefined);\n return await this.canServe(assetId, viewing) && custody === this.custody ? held : undefined;\n }\n\n /** Completion fence for both a cached source and an uncached ordinary source. */\n async canServe(assetId: string, viewing?: object): Promise<boolean> {\n const custody = this.custody;\n const store = this.carrier();\n if (!store) return false;\n const rows = await store.rowsReferencing(assetId);\n if (rows.length === 0) return false;\n const viewed = await store.viewedAsset(assetId);\n const once = rows.every((row) => this.options.viewOnce?.(row.table, row.row) === true);\n const owns = (!viewed && !once) || [...this.session.entries()].some(([key, entry]) =>\n entry.viewing === viewing && key.startsWith(this.sessionKey(assetId)));\n return custody === this.custody && owns;\n }\n\n async viewed(assetId: string): Promise<boolean> {\n checkedAssetId(assetId);\n const store = this.carrier();\n return store ? store.viewedAsset(assetId) : false;\n }\n\n async viewOnce(assetId: string): Promise<boolean> {\n checkedAssetId(assetId);\n const store = this.carrier();\n if (!store) return false;\n const once = await this.viewOnceRows(assetId);\n if (once.length === 0) return false;\n const viewed = new Set((await store.viewedRows()).map(rowKey));\n return once.some((ref) => !viewed.has(rowKey(ref)));\n }\n\n async markViewed(assetId: string): Promise<boolean> {\n checkedAssetId(assetId);\n const store = this.carrier();\n if (!store) return false;\n const once = await this.viewOnceRows(assetId);\n if (once.length === 0) return false;\n await store.commit({ viewed: once });\n return true;\n }\n\n /** After a network fetch: cache under the row's lease, or mark the view-once rows viewed and cache nothing. */\n async put(assetId: string, width: number | null, blob: Blob, viewing?: object): Promise<ByteCacheOutcome> {\n const custody = this.custody;\n const bytes = new Uint8Array(await blob.arrayBuffer());\n if (custody !== this.custody) return \"refused\";\n return this.putBytes(assetId, width, { bytes, type: blob.type }, viewing);\n }\n\n putBytes(assetId: string, width: number | null, value: AssetBytes, viewing?: object): Promise<ByteCacheOutcome> {\n const custody = this.custody;\n // Two concurrent consumers may fetch; only one can acquire the viewing allowance.\n const result = this.admissions.then(() => custody === this.custody\n ? this.admit(assetId, width, value, viewing) : \"refused\" as const);\n this.admissions = result.catch(() => undefined);\n return result;\n }\n\n private async admit(assetId: string, width: number | null, value: AssetBytes, viewing?: object): Promise<ByteCacheOutcome> {\n const custody = this.custody;\n checkedAssetId(assetId);\n checkedPut({ assetId, width, ...value });\n const store = this.carrier();\n if (!store) return \"unleased\";\n if (await store.viewedAsset(assetId)) return \"refused\";\n const rows = await store.rowsReferencing(assetId);\n if (rows.length === 0 || custody !== this.custody) return \"unleased\";\n const once = rows\n .filter((row) => this.options.viewOnce?.(row.table, row.row) === true)\n .map(({ table, id }) => ({ table, id }));\n // Per row: the view-once rows are marked viewed; an ordinary row sharing the id still leases the bytes.\n if (once.length > 0 && !viewing) return \"refused\";\n if (once.length === rows.length) {\n try {\n await store.commit({ viewed: once });\n } catch {\n return \"refused\";\n }\n if (custody !== this.custody || (await store.rowsReferencing(assetId)).length === 0\n || !await store.viewedAsset(assetId) || custody !== this.custody) return \"unleased\";\n if (this.session.size >= SESSION_VIEW_LIMIT) this.session.delete(this.session.keys().next().value!);\n if (viewing) this.session.set(this.sessionKey(assetId, width), { viewing, value: { bytes: value.bytes.slice(), type: value.type } });\n return \"viewed\";\n }\n try {\n await store.commit({\n ...(once.length === 0 ? {} : { viewed: once }),\n bytes: { put: [{ assetId, width, ...value }], ceiling: this.options.maxAssetBytes },\n });\n } catch {\n return \"refused\";\n }\n const status = await store.bytes();\n return custody === this.custody && status.entries.some((entry) => entry.assetId === assetId && entry.width === width) ? \"cached\" : \"refused\";\n }\n\n async status(): Promise<ByteCacheStatus> {\n const store = this.carrier();\n return store ? store.bytes() : { entries: [], totalBytes: 0, viewed: [] };\n }\n\n /** Nothing is served, marked, or cached without an open partition and a byte carrier. */\n private carrier(): (RangeStore & ByteCarrier) | undefined {\n return this.partition !== undefined && isByteCarrier(this.store) ? this.store : undefined;\n }\n\n private sessionKey(assetId: string, width?: number | null): string {\n return `${this.partition}\\u0000${assetId}\\u0000${width === undefined ? \"\" : width}`;\n }\n\n /** The session blob, only while the row that was viewed is still held on this partition. */\n private async sessionBytes(assetId: string, width: number | null, viewing?: object): Promise<AssetBytes | undefined> {\n const store = this.carrier();\n if (!store) return undefined;\n const key = this.sessionKey(assetId, width);\n const blob = this.session.get(key);\n if (!viewing || blob?.viewing !== viewing) return undefined;\n if ((await store.rowsReferencing(assetId)).length > 0) return blob.value;\n this.session.delete(key);\n return undefined;\n }\n\n private async viewOnceRows(assetId: string): Promise<RowRef[]> {\n const store = this.carrier();\n if (!store) return [];\n const rows = await store.rowsReferencing(assetId);\n return rows\n .filter((row) => this.options.viewOnce?.(row.table, row.row) === true)\n .map(({ table, id }) => ({ table, id }));\n }\n}\n", "/** The store's answer and cursor-chain keys share one shape-preserving encoding. */\nexport function canonical(value: unknown): string {\n if (value === undefined) return \"undefined\";\n if (value === null || typeof value !== \"object\") return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n return `{${Object.keys(value as object).sort().map((key) =>\n `${JSON.stringify(key)}:${canonical((value as Record<string, unknown>)[key])}`).join(\",\")}}`;\n}\n", "// @ref LLP 1012#7-writes-offline \u2014 cursor identity is not order. Only held,\n// post-commit next links prove progress; explicit negatives settle deletions.\nimport type { StoredAnswer, WatermarkRecord } from \"./range-store.js\";\nimport { canonical } from \"./canonical.js\";\n\nexport interface OverlayWatermark extends Pick<WatermarkRecord, \"op\" | \"args\" | \"watermark\"> {\n cursorArg: string;\n /** Last proven progress, and positions already consumed, survive a remount/reopen. */\n progress?: string;\n consumed?: string[];\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Each page keeps the name used when it was filed, including a pre-manifest c. */\nexport function pagePosition(page: Pick<StoredAnswer, \"op\" | \"args\" | \"cursorArg\">, mark: OverlayWatermark): string | null | undefined {\n if (page.op !== mark.op || !object(page.args) || !object(mark.args)) return undefined;\n const cursor = page.cursorArg ?? mark.cursorArg;\n const base = { ...mark.args };\n const args = { ...page.args };\n // Before the manifest, a caller can already pass { after: null } while the\n // recorded name is c. Only the now-known cursor substitutes for that missing\n // field; other nullable/string arguments remain part of the query identity.\n delete base[Object.hasOwn(base, mark.cursorArg) ? mark.cursorArg : cursor];\n delete args[cursor];\n if (canonical(base) !== canonical(args)) return undefined;\n const position = page.args[cursor];\n return position === null || typeof position === \"string\" ? position : undefined;\n}\n\n/**\n * An ordered path starting at the commit snapshot, never inferred from a newer\n * seq or a different opaque string. A cycle, ambiguity, or missing link ends\n * the proven prefix. The caller supplies only non-empty, intact held pages.\n */\nexport function cursorChain(pages: StoredAnswer[], mark: OverlayWatermark, committedSeq: number): string[] {\n const links = new Map<string | null, string | null>();\n for (const page of pages) {\n if ((page.nextSeq ?? page.seq) < committedSeq || typeof page.next !== \"string\") continue;\n const position = pagePosition(page, mark);\n if (position === undefined) continue;\n // Conflicting links quarantine only this position, including off-path ones.\n links.set(position, links.has(position) && links.get(position) !== page.next ? null : page.next);\n }\n const seen = new Set<string | null>([mark.watermark]);\n const chain: string[] = [];\n let position = mark.watermark;\n while (links.has(position)) {\n const next = links.get(position);\n if (next == null || seen.has(next)) break;\n seen.add(next);\n chain.push(next);\n position = next;\n }\n return chain;\n}\n\n/** A re-mark can consume progress only once and only beyond the last proven mark. */\nexport function advanceOverlay(mark: OverlayWatermark, tail: WatermarkRecord | undefined, chain: string[]): boolean {\n if (!tail || pagePosition({ ...tail, args: object(tail.args)\n ? { ...tail.args, [tail.cursorArg ?? mark.cursorArg]: tail.watermark } : tail.args }, mark) === undefined) return false;\n if (typeof tail.watermark !== \"string\" || (mark.consumed ?? []).includes(tail.watermark)) return false;\n const at = chain.indexOf(tail.watermark);\n if (mark.progress !== undefined && !chain.includes(mark.progress)) {\n // A page can grow or be evicted. Re-anchor at the nearest surviving consumed\n // position (or the snapshot root), without forgetting what already counted.\n mark.progress = [...(mark.consumed ?? [])].reverse().find((position) => chain.includes(position));\n }\n const previous = mark.progress === undefined ? -1 : chain.indexOf(mark.progress);\n if (at < 0 || at <= previous) return false;\n mark.progress = tail.watermark;\n mark.consumed = [...new Set([...(mark.consumed ?? []), ...chain.slice(0, at + 1)])];\n return true;\n}\n", "// @ref LLP 1012#4-the-range-store \u2014 every carrier persists the same per-principal answer/range model.\n// @ref LLP 1012#5-retention-revocation-and-the-fence \u2014 eviction is decided once over a complete swap.\n// @ref LLP 1012#9-asset-bytes-on-the-device \u2014 asset bytes leave in the same commit as the row whose lease held them.\n\nimport {\n applyByteSwap,\n assetIdsIn,\n byteKey,\n leasedAssets,\n viewedOnlyAssets,\n type ByteCacheEntry,\n type ByteCacheStatus,\n type ByteDelta,\n type ByteSwapRequest,\n type ViewedRecord,\n} from \"./byte-cache.js\";\n\nimport { advanceOverlay, cursorChain, pagePosition, type OverlayWatermark } from \"./overlay-retirement.js\";\nimport { canonical } from \"./canonical.js\";\n\nexport type PrincipalPartition = string;\nexport type RetentionPolicy = \"until-revoked\" | \"delivered-history\";\n\nexport interface RowRef { table: string; id: string }\nexport interface StoredRow extends RowRef { row: Record<string, unknown> }\n\nexport interface ReceiptRange {\n site: string;\n table: string;\n index: string;\n prefix: unknown[];\n order: \"Asc\" | \"Desc\";\n take: number;\n after: unknown;\n before: unknown;\n gt: unknown;\n gte: unknown;\n lt: unknown;\n lte: unknown;\n rowIds: string[];\n stop: \"Limit\" | \"Exhausted\";\n absence: boolean;\n haloId?: string;\n ruleHash: string;\n /**\n * Members this page was recorded with that a later swap evicted (LLP 1012 \u00A75):\n * the page's answer is `partial/evicted` from then on, and the twin's\n * drained-prefix rule (\u00A76) no longer counts the page as a link in a complete chain.\n */\n evictedIds?: string[];\n}\n\nexport interface Receipt {\n ranges: ReceiptRange[];\n absences: Array<[table: string, index: string, key: unknown[]]>;\n verdicts: unknown[];\n}\n\nexport interface HeldAnswer<Result = unknown> {\n op: string;\n args: unknown;\n state: \"complete\" | \"capped\" | \"partial\" | \"denied\";\n data?: Result;\n next?: string | null;\n seq: number;\n validator?: string;\n receipt?: Receipt;\n deliveredAt: number;\n retained?: boolean;\n caughtUp?: boolean;\n watermark?: string | null;\n reason?: string;\n rule?: string;\n}\n\nexport interface StoredAnswer extends Omit<HeldAnswer, \"data\"> {\n data?: unknown;\n refs: RowRef[];\n order: number;\n fingerprint?: string;\n /** Cursor argument used when this page was filed, before or after manifest load. */\n cursorArg?: string;\n /** Seq of the delivery that recorded `next`; conditional refreshes cannot renew a link. */\n nextSeq?: number;\n}\n\nexport interface WatermarkRecord {\n op: string;\n args: unknown;\n /** The argument the manifest types as this query's cursor; `c` before the manifest loads. */\n cursorArg?: string;\n watermark: string | null;\n validator?: string;\n generation?: string;\n schemaHash?: string;\n authEpoch?: number;\n updatedAt: number;\n /**\n * Durable position among this partition's drained queries: assigned by the store\n * when the query first records a watermark, kept across every later mark. The\n * lowest order is the log a settlement and a resume name (LLP 1012 \u00A77).\n */\n order?: number;\n}\n\n/** The generation and authority every held envelope of a partition was delivered under. */\nexport interface CoverageFacts {\n generation: string;\n schemaHash: string;\n authEpoch: number;\n}\n\n/** One certified operation as `GET /api/program` serves it: the IR the twin runs and its certificate. */\nexport interface HeldOperation {\n kind: \"query\" | \"mutation\";\n planHash: string;\n ir: unknown;\n certificate: unknown;\n}\n\n// @ref LLP 1012#8-the-delivery-envelope-the-validator-and-resume \u2014 the program\n// custody the evaluator ticket names: the certified IR, certificates, and the\n// schema of one generation, held in the partition so a cold start with the\n// network cut still evaluates and prices from the certificate.\nexport interface HeldProgram {\n generation: string;\n schemaHash: string;\n schema: OfflineSchema & Record<string, unknown>;\n programs: Record<string, HeldOperation>;\n}\n\nexport interface Coverage {\n rows: StoredRow[];\n ranges: ReceiptRange[];\n absences: Receipt[\"absences\"];\n verdicts: unknown[];\n watermarks: WatermarkRecord[];\n /**\n * View-once rows already viewed on this partition: absent from `rows`, listed under\n * `absences` as a `byId` point, and named here so a replay never renders them (LLP 1012 \u00A79).\n */\n viewed?: RowRef[];\n /** Rows a swap evicted (LLP 1012 \u00A75): the twin reports a read of one as `evicted`, not `never-held`. */\n evicted?: RowRef[];\n /** The generation and auth epoch the held coverage was delivered under; absent when nothing is held. */\n facts?: CoverageFacts;\n /**\n * The facts a later delivery arrived under when its generation or schema differ\n * from `facts`: the held answers predate the program the server now runs, so the\n * twin serves nothing from them \u2014 every read is `hydrating` \u2014 until the reset\n * path drops this coverage and rebuilds it under the live generation (LLP 1012 \u00A78).\n */\n superseded?: CoverageFacts;\n /** The newest delivery's time: what an answer the twin computes reports as `stale.since`. */\n deliveredAt?: number;\n}\n\nexport type OutboxState = \"queued\" | \"committed\" | \"rejected\" | \"expired\";\n/** What the twin read when the intent was queued: the replay envelope's `trace` (LLP 1012 \u00A77). */\nexport interface OutboxTrace {\n points: Array<{ table: string; index: string; key: unknown[]; digest: string | null }>;\n verdicts: Array<{ ruleHash: string; inputsDigest: string; result: boolean }>;\n}\n// @ref LLP 1012#7-writes-offline \u2014 one durable intent: its pinned id slice, its\n// bytes, and its terminal response, so a retry is the same envelope.\nexport interface OutboxEntry {\n intent: string;\n grant: string;\n offset: number;\n count: number;\n ids: string[];\n op: string;\n args: unknown;\n issuedSeq: number;\n state: OutboxState;\n response?: unknown;\n predicted?: boolean;\n /** Prediction and its trace were skipped; the program will check this write on the server. */\n reason?: \"fence\";\n /** Engine-owned aggregate targets the prediction's overlay omits by design (the server writes them); absent when none. */\n omitted?: string[];\n trace?: OutboxTrace;\n createdAt: number;\n updatedAt: number;\n /** Durable FIFO position; assigned by the store when absent. */\n order?: number;\n}\n\n/** A principal-bound replay grant plus the client's own consumption cursor. */\nexport interface OutboxGrant {\n id: string;\n from: string;\n count: number;\n mintedAt: number;\n expiresAt: number;\n used: number;\n}\n\nexport interface OutboxStore {\n all(): Promise<OutboxEntry[]>;\n get(intent: string): Promise<OutboxEntry | undefined>;\n put(entry: OutboxEntry): Promise<void>;\n remove(intent: string): Promise<void>;\n /** The grant new intents consume from, if one is held. */\n grant(): Promise<OutboxGrant | undefined>;\n /** Every held grant, including those older queued intents still name. */\n grants(): Promise<OutboxGrant[]>;\n /** Each op's persisted write bound (`maxNewIds`); an enqueue refuses without one. */\n bounds(): Promise<Record<string, number>>;\n /** The prediction overlay by intent: the rows a queued intent's local run wrote, `removed` for a delete. */\n overlay(): Promise<Record<string, OverlayRow[]>>;\n /** The certified programs held for this partition, keyed by generation. */\n programs(): Promise<Record<string, HeldProgram>>;\n}\n\n/** A predicted row: the write's final image, or a `removed` marker for a row the intent deletes. */\nexport interface OverlayRow extends StoredRow { removed?: true }\n\nexport interface StoreDelivery {\n cursorArg?: string;\n op: string;\n args: unknown;\n state: HeldAnswer[\"state\"];\n data?: unknown;\n next?: string | null;\n seq: number;\n validator?: string;\n receipt?: Receipt;\n rows?: StoredRow[];\n deliveredAt?: number;\n reason?: string;\n rule?: string;\n}\n\nexport interface StoreTombstone extends RowRef { seq: number }\nexport interface StoreRefresh {\n op: string;\n args: unknown;\n seq: number;\n validator: string;\n deliveredAt?: number;\n}\n\nexport interface OfflineSchema {\n tables?: Record<string, {\n columns?: Record<string, unknown>;\n indexes?: Record<string, { columns?: string[] }>;\n retain?: RetentionPolicy;\n }>;\n}\n\nexport interface StoreSwap {\n deliveries?: StoreDelivery[];\n refreshes?: StoreRefresh[];\n tombstones?: StoreTombstone[];\n retention?: Record<string, RetentionPolicy>;\n schema?: OfflineSchema;\n watermark?: WatermarkRecord;\n resetCoverage?: boolean;\n /** One validated resume response, including unchanged; never a query re-delivery. */\n resumeSeq?: number;\n dropAnswers?: string[];\n outbox?: { put?: OutboxEntry[]; remove?: string[] };\n /**\n * Byte-cache puts and read touches; they land in the same swap as the rows: one\n * readwrite transaction on IndexedDB, an ordered payload write + state rename with\n * a sweep on open for the Node file carrier.\n */\n bytes?: ByteSwapRequest;\n /** View-once rows viewed now: excluded from every later answer, their bytes never cached. */\n viewed?: RowRef[];\n /** `current` names the grant new intents consume; `null` clears it. */\n grants?: { put?: OutboxGrant[]; current?: string | null; remove?: string[] };\n /** Predicted rows keyed by intent; visible to the twin's local evaluation, never to `answer()` (LLP 1012 \u00A77). */\n overlay?: { put?: Record<string, OverlayRow[]>; remove?: string[] };\n /** The certified programs, replaced whole (one generation is held at a time); custody like the outbox. */\n programs?: Record<string, HeldProgram>;\n /** The facts the swap's envelopes were delivered under; cleared by `resetCoverage`. */\n facts?: CoverageFacts;\n /** A rotation: the facts a refused delivery arrived under; held coverage is superseded until rebuild completion clears it with `null`. */\n superseded?: CoverageFacts | null;\n /**\n * The program's write bounds, replaced whole: what `/api/program` certified each op may\n * mint. Custody like the outbox \u2014 a coverage reset never touches it (LLP 1012 \u00A77).\n */\n bounds?: Record<string, number>;\n}\n\nexport interface RangeStore {\n open(partition: PrincipalPartition): Promise<void>;\n unseal(): Promise<void>;\n seal(): Promise<void>;\n wipe(partition: PrincipalPartition): Promise<void>;\n answer<Result = unknown>(op: string, args: unknown): Promise<HeldAnswer<Result> | undefined>;\n commit(swap: StoreSwap): Promise<void>;\n coverage(): Promise<Coverage>;\n readonly outbox: OutboxStore;\n close?(): Promise<void> | void;\n}\n\nexport interface RangeStoreFactory {\n (): RangeStore;\n readonly carrier?: string;\n}\n\nexport class OfflineStoreFailure extends Error {\n constructor(readonly code: \"E_OFFLINE_CARRIER\" | \"E_OFFLINE_LOCK\", message: string, readonly rewrite?: string) {\n super(message);\n this.name = \"OfflineStoreFailure\";\n }\n}\n\nexport interface PersistedRangeState {\n version: 1;\n sealed: boolean;\n clock: number;\n rows: Record<string, StoredRow>;\n answers: Record<string, StoredAnswer>;\n watermarks: Record<string, WatermarkRecord>;\n outbox: Record<string, OutboxEntry>;\n grants: Record<string, OutboxGrant>;\n currentGrant?: string;\n overlay: Record<string, OverlayRow[]>;\n /** Per committed intent, successful resumes or proven tail advances without its rows. */\n overlayMisses: Record<string, number>;\n /** The commit-time tail snapshot; null after reset until the next drain establishes a new head. */\n overlayWatermarks: Record<string, OverlayWatermark | null>;\n /** Only primary absences and tombstones, scoped to each prediction's ids. */\n overlayNegatives: Record<string, Record<string, { seq: number; source: \"absence\" | \"tombstone\" }>>;\n bounds: Record<string, number>;\n programs: Record<string, HeldProgram>;\n facts?: CoverageFacts;\n superseded?: CoverageFacts;\n negative: Record<string, number>;\n rowSeq: Record<string, number>;\n /** The byte-cache index; payloads live beside the state in the carrier, keyed by `byteKey`. */\n assets: Record<string, ByteCacheEntry>;\n viewed: Record<string, ViewedRecord>;\n}\n\nexport interface RangeStoreBackend {\n readonly carrier: string;\n open(partition: PrincipalPartition): Promise<PersistedRangeState | undefined>;\n /** One carrier transaction: the state, plus the byte payloads to write and the keys to drop. */\n replace(state: PersistedRangeState, bytes: ByteDelta): Promise<void>;\n readBytes?(key: string): Promise<Uint8Array | undefined>;\n wipe(partition: PrincipalPartition): Promise<void>;\n close(): Promise<void> | void;\n}\n\nconst NO_BYTES: ByteDelta = { put: [], remove: [] };\n\nexport function emptyState(): PersistedRangeState {\n return {\n version: 1, sealed: false, clock: 0, rows: {}, answers: {}, watermarks: {}, outbox: {},\n grants: {}, overlay: {}, overlayMisses: {}, overlayWatermarks: {}, overlayNegatives: {}, bounds: {}, programs: {}, negative: {}, rowSeq: {}, assets: {}, viewed: {},\n };\n}\n\nfunction clone<T>(value: T): T {\n return structuredClone(value);\n}\n\nexport function canonicalAnswerKey(op: string, args: unknown): string {\n return `${op}\\u0000${canonical(args === undefined ? args : jsonState(args))}`;\n}\n\nfunction rowKey(ref: RowRef): string {\n return `${ref.table}\\u0000${ref.id}`;\n}\n\nfunction viewedRef(key: string): RowRef {\n const at = key.indexOf(String.fromCharCode(0));\n return { table: key.slice(0, at), id: key.slice(at + 1) };\n}\n\nfunction recordEviction(evictions: Map<string, StoreTombstone>, eviction: StoreTombstone): void {\n const key = rowKey(eviction);\n if ((evictions.get(key)?.seq ?? -1) <= eviction.seq) evictions.set(key, eviction);\n}\n\nexport function rowReference(table: string, id: string): { $row: RowRef } {\n return { $row: { table, id } };\n}\n\nfunction asRowRef(value: unknown): RowRef | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const marker = (value as { $row?: unknown }).$row;\n return marker !== null && typeof marker === \"object\" && !Array.isArray(marker)\n && Object.keys(marker).sort().join(\",\") === \"id,table\"\n && typeof (marker as RowRef).table === \"string\" && typeof (marker as RowRef).id === \"string\"\n ? { table: (marker as RowRef).table, id: (marker as RowRef).id }\n : undefined;\n}\n\nfunction collectRefs(value: unknown, refs = new Map<string, RowRef>()): RowRef[] {\n const ref = asRowRef(value);\n if (ref) refs.set(rowKey(ref), ref);\n else if (Array.isArray(value)) for (const item of value) collectRefs(item, refs);\n else if (value && typeof value === \"object\") {\n for (const item of Object.values(value as Record<string, unknown>)) collectRefs(item, refs);\n }\n return [...refs.values()];\n}\n\nfunction expand(value: unknown, rows: Record<string, StoredRow>, viewed?: Record<string, unknown>): unknown {\n const ref = asRowRef(value);\n if (ref) return viewed?.[rowKey(ref)] ? null : rows[rowKey(ref)]?.row ?? null;\n if (Array.isArray(value)) return value.map((item) => expand(item, rows, viewed));\n if (!value || typeof value !== \"object\") return value;\n return Object.fromEntries(Object.entries(value as Record<string, unknown>)\n .map(([key, item]) => [key, expand(item, rows, viewed)]));\n}\n\nfunction hiddenRefs(before: unknown, after: unknown, output = new Map<string, RowRef>()): RowRef[] {\n if (after === null || after === undefined) {\n for (const ref of collectRefs(before)) output.set(rowKey(ref), ref);\n return [...output.values()];\n }\n const ref = asRowRef(before);\n if (ref && after === null) output.set(rowKey(ref), ref);\n else if (Array.isArray(before) && Array.isArray(after)) {\n for (let index = 0; index < before.length; index += 1) {\n hiddenRefs(before[index], index < after.length ? after[index] : undefined, output);\n }\n } else if (before && after && typeof before === \"object\" && typeof after === \"object\"\n && !Array.isArray(before) && !Array.isArray(after)) {\n for (const key of Object.keys(before as object)) {\n hiddenRefs(\n (before as Record<string, unknown>)[key],\n Object.prototype.hasOwnProperty.call(after, key) ? (after as Record<string, unknown>)[key] : undefined,\n output,\n );\n }\n }\n return [...output.values()];\n}\n\nfunction restoreRetained(before: unknown, after: unknown, retained: Set<string>): unknown {\n const ref = asRowRef(before);\n if (ref && (after === null || after === undefined) && retained.has(rowKey(ref))) return before;\n if (Array.isArray(before) && Array.isArray(after)) {\n const result = after.map((item, index) => index < before.length\n ? restoreRetained(before[index], item, retained) : item);\n for (let index = after.length; index < before.length; index += 1) {\n if (collectRefs(before[index]).some((item) => retained.has(rowKey(item)))) result.push(clone(before[index]));\n }\n return result;\n }\n if (before && after && typeof before === \"object\" && typeof after === \"object\"\n && !Array.isArray(before) && !Array.isArray(after)) {\n const result = clone(after as Record<string, unknown>);\n for (const key of Object.keys(before as object)) {\n const old = (before as Record<string, unknown>)[key];\n if (Object.prototype.hasOwnProperty.call(result, key)) result[key] = restoreRetained(old, result[key], retained);\n else if (collectRefs(old).some((item) => retained.has(rowKey(item)))) result[key] = clone(old);\n }\n return result;\n }\n if ((after === null || after === undefined)\n && collectRefs(before).some((item) => retained.has(rowKey(item)))) return clone(before);\n return after;\n}\n\nfunction sameRange(left: ReceiptRange, right: ReceiptRange): boolean {\n return left.site === right.site && left.table === right.table && left.index === right.index\n && canonical(left.prefix) === canonical(right.prefix)\n && left.order === right.order\n && canonical(left.after) === canonical(right.after)\n && canonical(left.before) === canonical(right.before)\n && canonical(left.gt) === canonical(right.gt)\n && canonical(left.gte) === canonical(right.gte)\n && canonical(left.lt) === canonical(right.lt)\n && canonical(left.lte) === canonical(right.lte)\n && left.ruleHash === right.ruleHash;\n}\n\nfunction compareValue(left: unknown, right: unknown): number {\n if (left === right) return 0;\n if (typeof left === \"number\" && typeof right === \"number\") return left < right ? -1 : 1;\n if (typeof left === \"string\" && typeof right === \"string\") return left < right ? -1 : 1;\n if (typeof left === \"boolean\" && typeof right === \"boolean\") return left ? 1 : -1;\n const a = canonical(left);\n const b = canonical(right);\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction compareKey(left: unknown[], right: unknown[]): number {\n for (let index = 0; index < Math.min(left.length, right.length); index += 1) {\n const order = compareValue(left[index], right[index]);\n if (order !== 0) return order;\n }\n return left.length - right.length;\n}\n\nfunction indexKey(schema: OfflineSchema | undefined, range: ReceiptRange, row: StoredRow | undefined): unknown[] | undefined {\n const columns = schema?.tables?.[range.table]?.indexes?.[range.index]?.columns;\n if (!row || !Array.isArray(columns) || !columns.every((item) => typeof item === \"string\")) return undefined;\n const key = columns.map((column) => row.row[column]);\n return key.some((item) => item === undefined) ? undefined : key;\n}\n\nfunction cursorKey(value: unknown, width: number): unknown[] | undefined {\n if (value === null || value === undefined) return undefined;\n if (Array.isArray(value)) return value.length === width ? value : undefined;\n return width === 1 ? [value] : undefined;\n}\n\nfunction insidePrefixBounds(key: unknown[], range: ReceiptRange): boolean {\n if (key.length < range.prefix.length\n || compareKey(key.slice(0, range.prefix.length), range.prefix) !== 0) return false;\n const suffix = key.slice(range.prefix.length);\n const after = cursorKey(range.after, suffix.length);\n const before = cursorKey(range.before, suffix.length);\n if (after && (range.order === \"Asc\" ? compareKey(suffix, after) <= 0 : compareKey(suffix, after) >= 0)) return false;\n if (before && (range.order === \"Asc\" ? compareKey(suffix, before) >= 0 : compareKey(suffix, before) <= 0)) return false;\n const first = suffix[0];\n if (range.gt !== null && range.gt !== undefined && compareValue(first, range.gt) <= 0) return false;\n if (range.gte !== null && range.gte !== undefined && compareValue(first, range.gte) < 0) return false;\n if (range.lt !== null && range.lt !== undefined && compareValue(first, range.lt) >= 0) return false;\n if (range.lte !== null && range.lte !== undefined && compareValue(first, range.lte) > 0) return false;\n return true;\n}\n\nfunction inFreshExtent(\n id: string,\n held: ReceiptRange,\n fresh: ReceiptRange,\n rows: Record<string, StoredRow>,\n schema: OfflineSchema | undefined,\n): boolean {\n const key = indexKey(schema, held, rows[rowKey({ table: held.table, id })]);\n if (!key) return fresh.stop === \"Exhausted\";\n if (!insidePrefixBounds(key, fresh)) return false;\n if (fresh.stop === \"Exhausted\") return true;\n const presentKeys = fresh.rowIds\n .map((rowId) => indexKey(schema, fresh, rows[rowKey({ table: fresh.table, id: rowId })]))\n .filter(Array.isArray) as unknown[][];\n if (presentKeys.length === 0) return false;\n const first = presentKeys.reduce((a, b) => compareKey(a, b) <= 0 ? a : b);\n const last = presentKeys.reduce((a, b) => compareKey(a, b) >= 0 ? a : b);\n return compareKey(key, first) >= 0 && compareKey(key, last) <= 0;\n}\n\n/** One JSON form for warm state and every carrier: omit undefined fields, preserve null. */\nexport function jsonState<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction normalizeState(value: PersistedRangeState | undefined): PersistedRangeState {\n if (!value) return emptyState();\n value = jsonState(value);\n if (value.version !== 1 || typeof value.rows !== \"object\" || typeof value.answers !== \"object\") {\n throw new OfflineStoreFailure(\"E_OFFLINE_CARRIER\", \"range store contains an unsupported format\");\n }\n return {\n ...value,\n watermarks: value.watermarks ?? {},\n outbox: value.outbox ?? {},\n grants: value.grants ?? {},\n overlay: value.overlay ?? {},\n overlayMisses: value.overlayMisses ?? {},\n overlayWatermarks: value.overlayWatermarks ?? {},\n overlayNegatives: value.overlayNegatives ?? {},\n bounds: value.bounds ?? {},\n programs: value.programs ?? {},\n negative: value.negative ?? {},\n rowSeq: value.rowSeq ?? {},\n assets: value.assets ?? {},\n viewed: value.viewed ?? {},\n };\n}\n\n/**\n * The log a settlement's tail request and a resume's `log` both name: the drained\n * query whose watermark was recorded first in this partition \u2014 the first-mounted\n * drain, since a drain records its watermark when it first catches up \u2014 by the\n * store's durable `order`, so the choice survives restarts and re-marks and never\n * follows whichever page moved last (LLP 1012 \u00A77, \u00A78).\n */\nexport function tailWatermark(watermarks: WatermarkRecord[]): WatermarkRecord | undefined {\n return [...watermarks].sort((a, b) =>\n (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER)\n || a.updatedAt - b.updatedAt\n || canonicalAnswerKey(a.op, a.args).localeCompare(canonicalAnswerKey(b.op, b.args)))[0];\n}\n\n/** Two post-commit resumes or proven tail advances retire a stranded prediction. */\nconst OVERLAY_PATIENCE = 2;\n\nfunction outboxOrder(entries: Record<string, OutboxEntry>): OutboxEntry[] {\n return Object.values(entries).sort((a, b) =>\n (a.order ?? a.createdAt) - (b.order ?? b.createdAt) || a.createdAt - b.createdAt || (a.intent < b.intent ? -1 : 1));\n}\n\n/** Shared swap engine; carrier subclasses only provide the atomic replace. */\nexport class PersistentRangeStore implements RangeStore {\n private state = emptyState();\n private partition?: PrincipalPartition;\n private tail: Promise<void> = Promise.resolve();\n\n readonly outbox: OutboxStore = {\n all: async () => this.read(() => {\n this.ensureUnsealed();\n return clone(outboxOrder(this.state.outbox));\n }),\n get: async (intent) => this.read(() => {\n this.ensureUnsealed();\n return this.state.outbox[intent] && clone(this.state.outbox[intent]);\n }),\n put: async (entry) => this.commit({ outbox: { put: [entry] } }),\n remove: async (intent) => this.commit({ outbox: { remove: [intent] } }),\n grant: async () => this.read(() => {\n this.ensureUnsealed();\n const current = this.state.currentGrant === undefined ? undefined : this.state.grants[this.state.currentGrant];\n return current && clone(current);\n }),\n grants: async () => this.read(() => {\n this.ensureUnsealed();\n return clone(Object.values(this.state.grants));\n }),\n bounds: async () => this.read(() => {\n this.ensureUnsealed();\n return clone(this.state.bounds);\n }),\n overlay: async () => this.read(() => {\n this.ensureUnsealed();\n return clone(this.state.overlay);\n }),\n programs: async () => this.read(() => {\n this.ensureUnsealed();\n return clone(this.state.programs);\n }),\n };\n\n constructor(private readonly backend: RangeStoreBackend) {}\n\n async open(partition: PrincipalPartition): Promise<void> {\n if (typeof partition !== \"string\" || partition.length === 0) {\n throw new OfflineStoreFailure(\"E_OFFLINE_CARRIER\", \"range store partition must be a principal id\");\n }\n await this.enqueue(async () => {\n if (this.partition === partition) return;\n if (this.partition !== undefined && this.partition !== partition) await this.backend.close();\n this.partition = partition;\n this.state = normalizeState(await this.backend.open(partition));\n });\n }\n\n async unseal(): Promise<void> {\n await this.enqueue(async () => {\n this.ensureOpen();\n if (!this.state.sealed) return;\n const next = { ...clone(this.state), sealed: false };\n await this.backend.replace(next, NO_BYTES);\n this.state = next;\n });\n }\n\n async seal(): Promise<void> {\n await this.enqueue(async () => {\n this.ensureOpen();\n const next = { ...clone(this.state), sealed: true };\n await this.backend.replace(next, NO_BYTES);\n this.state = next;\n });\n }\n\n async wipe(partition: PrincipalPartition): Promise<void> {\n await this.enqueue(async () => {\n await this.backend.wipe(partition);\n if (this.partition === partition) {\n this.partition = undefined;\n this.state = emptyState();\n }\n });\n }\n\n async answer<Result = unknown>(op: string, args: unknown): Promise<HeldAnswer<Result> | undefined> {\n return this.read(() => {\n if (this.state.sealed) return undefined;\n const key = canonicalAnswerKey(op, args);\n const stored = this.state.answers[key];\n if (!stored) return undefined;\n const watermark = this.state.watermarks[key];\n const { refs: _refs, order: _order, fingerprint: _fingerprint, cursorArg: _cursorArg, data, ...answer } = clone(stored);\n return {\n ...answer,\n // A viewed view-once row reads as absent: the view was its one delivery (LLP 1012 \u00A79).\n ...(data === undefined ? {} : { data: expand(data, this.state.rows, this.state.viewed) as Result }),\n ...(watermark === undefined ? {} : { caughtUp: true, watermark: watermark.watermark }),\n };\n });\n }\n\n async coverage(): Promise<Coverage> {\n return this.read(() => {\n if (this.state.sealed) return { rows: [], ranges: [], absences: [], verdicts: [], watermarks: [], viewed: [], evicted: [] };\n const ranges = new Map<string, ReceiptRange>();\n const absences = new Map<string, Receipt[\"absences\"][number]>();\n const verdicts = new Map<string, unknown>();\n for (const answer of Object.values(this.state.answers)) {\n for (const range of answer.receipt?.ranges ?? []) {\n ranges.set(`${range.site}\\u0000${canonical(range.prefix)}\\u0000${canonical([\n range.order, range.after, range.before, range.gt, range.gte, range.lt, range.lte,\n ])}`, clone(range));\n }\n for (const absence of answer.receipt?.absences ?? []) absences.set(canonical(absence), clone(absence));\n for (const verdict of answer.receipt?.verdicts ?? []) verdicts.set(canonical(verdict), clone(verdict));\n }\n // A viewed view-once row is absent to the twin: not a row, and a byId absence (LLP 1012 \u00A79).\n const viewed = Object.keys(this.state.viewed).map(viewedRef);\n for (const ref of viewed) {\n const absence: Receipt[\"absences\"][number] = [ref.table, \"byId\", [ref.id]];\n absences.set(canonical(absence), absence);\n }\n let deliveredAt: number | undefined;\n for (const answer of Object.values(this.state.answers)) {\n if (deliveredAt === undefined || answer.deliveredAt > deliveredAt) deliveredAt = answer.deliveredAt;\n }\n return {\n rows: clone(Object.entries(this.state.rows).filter(([key]) => !this.state.viewed[key]).map(([, row]) => row)),\n ranges: [...ranges.values()],\n absences: [...absences.values()],\n verdicts: [...verdicts.values()],\n watermarks: clone(Object.values(this.state.watermarks)),\n viewed,\n evicted: Object.keys(this.state.negative).map(viewedRef),\n ...(this.state.facts === undefined ? {} : { facts: clone(this.state.facts) }),\n ...(this.state.superseded === undefined ? {} : { superseded: clone(this.state.superseded) }),\n ...(deliveredAt === undefined ? {} : { deliveredAt }),\n };\n });\n }\n\n async commit(swap: StoreSwap): Promise<void> {\n await this.enqueue(async () => {\n this.ensureOpen();\n // Byte payloads are not cloned: they can be megabytes and the swap never mutates them.\n const { bytes, ...rest } = swap;\n const delta: ByteDelta = { put: [], remove: [] };\n // Normalize before deriving answer keys/fingerprints, then normalize the state we publish.\n const next = normalizeState(this.applySwap(clone(this.state), { ...jsonState(rest), ...(bytes === undefined ? {} : { bytes }) }, delta));\n await this.backend.replace(next, delta);\n this.state = next;\n });\n }\n\n /** The cached rendition for an asset at a width; nothing when unheld, sealed, or the payload is gone. */\n async readBytes(assetId: string, width: number | null): Promise<{ bytes: Uint8Array; type: string } | undefined> {\n return this.read(async () => {\n if (this.state.sealed) return undefined;\n const key = byteKey(assetId, width);\n const entry = this.state.assets[key];\n if (!entry) return undefined;\n const bytes = await this.backend.readBytes?.(key);\n return bytes && bytes.byteLength === entry.size ? { bytes, type: entry.type } : undefined;\n });\n }\n\n async bytes(): Promise<ByteCacheStatus> {\n return this.read(() => {\n if (this.state.sealed) return { entries: [], totalBytes: 0, viewed: [] };\n const entries = clone(Object.values(this.state.assets));\n return {\n entries,\n totalBytes: entries.reduce((sum, entry) => sum + entry.size, 0),\n viewed: Object.keys(this.state.viewed).map(viewedRef),\n };\n });\n }\n\n /** Held rows whose values carry this asset record: the lease under which its bytes may be cached. */\n async rowsReferencing(assetId: string): Promise<StoredRow[]> {\n return this.read(() => this.state.sealed\n ? []\n : clone(Object.values(this.state.rows).filter((row) => assetIdsIn(row.row).has(assetId))));\n }\n\n /** True while every held row carrying this asset is a viewed view-once row (per row, LLP 1012 \u00A79). */\n async viewedAsset(assetId: string): Promise<boolean> {\n return this.read(() => !this.state.sealed && viewedOnlyAssets(this.state).has(assetId));\n }\n\n /** The viewed view-once rows; a live frame nulls them exactly as a held answer does. */\n async viewedRows(): Promise<RowRef[]> {\n return this.read(() => this.state.sealed ? [] : Object.keys(this.state.viewed).map(viewedRef));\n }\n\n /**\n * LRU read stamps, coalesced per swap: a read stamps the entry in memory and the next\n * swap's `replace` persists it, so a read never rewrites the carrier (LLP 1012 \u00A79).\n */\n async touchBytes(keys: string[]): Promise<void> {\n await this.enqueue(async () => {\n if (this.partition === undefined || this.state.sealed) return;\n for (const key of keys) {\n const entry = this.state.assets[key];\n if (entry) entry.lastRead = ++this.state.clock;\n }\n });\n }\n\n async close(): Promise<void> {\n await this.enqueue(async () => {\n this.partition = undefined;\n this.state = emptyState();\n await this.backend.close();\n });\n }\n\n private applySwap(state: PersistedRangeState, swap: StoreSwap, bytes: ByteDelta): PersistedRangeState {\n if (state.sealed) throw new OfflineStoreFailure(\"E_OFFLINE_CARRIER\", \"range store is sealed\");\n if (swap.resetCoverage) {\n state.rows = {};\n // Sequence guards belong to this generation's coverage, just like rows.\n // A query-only successor can deliver the same row at the same data seq.\n state.rowSeq = {};\n state.negative = {};\n state.answers = {};\n state.watermarks = {};\n // These describe coverage, unlike the overlay and its replay entry.\n state.overlayWatermarks = Object.fromEntries(Object.keys(state.overlay).map((intent) => [intent, null]));\n state.overlayMisses = {};\n delete state.facts;\n }\n if (swap.superseded === null) delete state.superseded;\n if (swap.resumeSeq !== undefined && (!Number.isSafeInteger(swap.resumeSeq) || swap.resumeSeq < 0)) {\n throw new TypeError(\"store resume seq must be a non-negative safe integer\");\n }\n if (swap.facts) state.facts = clone(swap.facts);\n if (swap.superseded) state.superseded = clone(swap.superseded);\n const explicitEvictions = new Map<string, StoreTombstone>();\n // Keep provenance distinct from hidden-row and extent evictions. These facts\n // join each matching overlay below, even while its response is still queued.\n const authoritativeNegatives = new Map<string, { seq: number; source: \"absence\" | \"tombstone\" }>();\n const recordNegative = (ref: StoreTombstone, source: \"absence\" | \"tombstone\") => {\n const key = rowKey(ref);\n if ((authoritativeNegatives.get(key)?.seq ?? -1) <= ref.seq) {\n authoritativeNegatives.set(key, { seq: ref.seq, source });\n }\n recordEviction(explicitEvictions, ref);\n };\n const recordAbsences = (answer: Pick<StoredAnswer, \"receipt\" | \"seq\">) => {\n for (const [table, index, key] of answer.receipt?.absences ?? []) {\n if (index !== \"byId\" || key.length !== 1) {\n throw new TypeError(\"store receipts may evict only a primary byId absence\");\n }\n if (typeof key[0] === \"string\") recordNegative({ table, id: key[0], seq: answer.seq }, \"absence\");\n }\n };\n for (const key of swap.dropAnswers ?? []) delete state.answers[key];\n for (const refresh of swap.refreshes ?? []) {\n const answer = state.answers[canonicalAnswerKey(refresh.op, refresh.args)];\n if (!answer || refresh.seq < answer.seq) continue;\n if (answer.validator !== undefined && answer.validator !== refresh.validator) {\n throw new TypeError(`conditional validator changed for ${refresh.op}`);\n }\n if (refresh.seq === answer.seq) continue;\n answer.nextSeq ??= answer.seq;\n answer.seq = refresh.seq;\n answer.validator = refresh.validator;\n answer.deliveredAt = refresh.deliveredAt ?? Date.now();\n answer.order = ++state.clock;\n recordAbsences(answer);\n }\n const before = clone(state.answers);\n const freshRanges: Array<{ range: ReceiptRange; seq: number }> = [];\n for (const ref of swap.tombstones ?? []) {\n recordNegative(ref, \"tombstone\");\n }\n for (const delivery of swap.deliveries ?? []) {\n if (!Number.isSafeInteger(delivery.seq) || delivery.seq < 0) {\n throw new TypeError(\"store delivery seq must be a non-negative safe integer\");\n }\n const key = canonicalAnswerKey(delivery.op, delivery.args);\n const old = before[key];\n const fingerprint = canonical({\n op: delivery.op, args: delivery.args, state: delivery.state, data: delivery.data,\n next: delivery.next, seq: delivery.seq, validator: delivery.validator,\n receipt: delivery.receipt, rows: delivery.rows, reason: delivery.reason, rule: delivery.rule,\n });\n if (old && delivery.seq < old.seq) continue;\n if (old && delivery.seq === old.seq) {\n if (old.fingerprint === fingerprint) continue;\n throw new TypeError(`conflicting deliveries for ${delivery.op} at seq ${delivery.seq}`);\n }\n for (const row of delivery.rows ?? []) {\n if (!row.table || !row.id || !row.row || typeof row.row !== \"object\") {\n throw new TypeError(\"store delivery row is malformed\");\n }\n const storageKey = rowKey(row);\n if ((state.negative[storageKey] ?? -1) >= delivery.seq) {\n recordEviction(explicitEvictions, { table: row.table, id: row.id, seq: state.negative[storageKey]! });\n continue;\n }\n if (state.rowSeq[storageKey] === delivery.seq\n && canonical(state.rows[storageKey]) !== canonical(row)) {\n throw new TypeError(`conflicting row ${row.table}/${row.id} at seq ${delivery.seq}`);\n }\n if ((state.rowSeq[storageKey] ?? -1) > delivery.seq) continue;\n state.rows[storageKey] = clone(row);\n state.rowSeq[storageKey] = delivery.seq;\n }\n let data = clone(delivery.data);\n let answerState = delivery.state;\n let retained = false;\n const hidden = delivery.state === \"denied\" && old\n ? old.refs\n : old ? hiddenRefs(old.data, data) : [];\n const retainedRefs = new Set<string>();\n for (const ref of hidden) {\n if ((swap.retention?.[ref.table] ?? \"until-revoked\") === \"delivered-history\") {\n retainedRefs.add(rowKey(ref));\n retained = true;\n } else recordEviction(explicitEvictions, { ...ref, seq: delivery.seq });\n }\n if (delivery.state === \"denied\" && old && retainedRefs.size > 0) {\n data = clone(old.data);\n answerState = old.state;\n } else if (old && retainedRefs.size > 0) {\n data = restoreRetained(old.data, data, retainedRefs);\n }\n const refs = collectRefs(data);\n for (const range of delivery.receipt?.ranges ?? []) {\n for (const id of [...range.rowIds, ...(range.haloId ? [range.haloId] : [])]) {\n if (!refs.some((ref) => ref.table === range.table && ref.id === id)) refs.push({ table: range.table, id });\n }\n }\n // The pool is the answer's closure: halo and rule-input bodies (the\n // membership a message's read rule probed) are delivered content the\n // twin evaluates over, so an answer keeps every row it was delivered with.\n for (const pooled of delivery.rows ?? []) {\n if (!refs.some((ref) => ref.table === pooled.table && ref.id === pooled.id)) refs.push({ table: pooled.table, id: pooled.id });\n }\n const stored: StoredAnswer = {\n op: delivery.op,\n ...(delivery.cursorArg === undefined ? {} : { cursorArg: delivery.cursorArg }),\n args: clone(delivery.args),\n state: answerState,\n ...(data === undefined ? {} : { data }),\n ...(delivery.next === undefined ? {} : { next: delivery.next }),\n nextSeq: delivery.seq,\n seq: delivery.seq,\n ...(delivery.validator === undefined ? {} : { validator: delivery.validator }),\n ...(delivery.receipt === undefined ? {} : { receipt: clone(delivery.receipt) }),\n deliveredAt: delivery.deliveredAt ?? Date.now(),\n ...(retained ? { retained: true } : {}),\n ...(delivery.reason === undefined ? {} : { reason: delivery.reason }),\n ...(delivery.rule === undefined ? {} : { rule: delivery.rule }),\n refs,\n order: ++state.clock,\n fingerprint,\n };\n state.answers[key] = stored;\n freshRanges.push(...(delivery.receipt?.ranges ?? []).map((range) => ({ range, seq: delivery.seq })));\n recordAbsences(stored);\n }\n\n const heldRanges = Object.values(before).flatMap((answer) => answer.receipt?.ranges ?? []);\n for (const held of heldRanges) {\n const matching = freshRanges.filter(({ range: fresh }) => sameRange(held, fresh));\n if (matching.length === 0) continue;\n const present = new Set(matching.flatMap(({ range: fresh }) => [\n ...fresh.rowIds,\n ...(fresh.haloId ? [fresh.haloId] : []),\n ]));\n for (const id of held.rowIds) {\n if (present.has(id)) continue;\n const seq = matching\n .filter(({ range: fresh }) => inFreshExtent(id, held, fresh, state.rows, swap.schema))\n .reduce((latest, item) => Math.max(latest, item.seq), -1);\n if (seq >= 0) recordEviction(explicitEvictions, { table: held.table, id, seq });\n }\n }\n\n const appliedEvictions = new Set<string>();\n for (const [key, eviction] of explicitEvictions) {\n if ((state.negative[key] ?? -1) > eviction.seq) continue;\n if ((state.rowSeq[key] ?? -1) > eviction.seq) continue;\n state.negative[key] = eviction.seq;\n appliedEvictions.add(key);\n delete state.rows[key];\n delete state.rowSeq[key];\n for (const answer of Object.values(state.answers)) {\n for (const range of answer.receipt?.ranges ?? []) {\n if (range.table !== eviction.table) continue;\n const id = eviction.id;\n if (range.rowIds.includes(id)) {\n range.rowIds = range.rowIds.filter((rowId) => rowId !== id);\n // The page remembers what it lost: an interior eviction leaves a hole\n // the twin must not paper over with \"complete\" (LLP 1012 \u00A76).\n range.evictedIds = [...(range.evictedIds ?? []), id];\n }\n if (range.haloId === id) delete range.haloId;\n }\n if (!answer.refs.some((ref) => rowKey(ref) === key)) continue;\n answer.refs = answer.refs.filter((ref) => rowKey(ref) !== key);\n if (!answer.retained && answer.state !== \"denied\") {\n answer.state = \"partial\";\n answer.reason = \"evicted\";\n delete answer.next;\n }\n }\n }\n\n for (const answer of Object.values(state.answers)) {\n if (!answer.receipt) continue;\n answer.receipt.absences = answer.receipt.absences.filter(([table, index, key]) => {\n const id = index === \"byId\" && key.length === 1 ? key[0] : undefined;\n const storageKey = typeof id === \"string\" ? rowKey({ table, id }) : undefined;\n return storageKey === undefined || (state.rowSeq[storageKey] ?? -1) < 0 || appliedEvictions.has(storageKey);\n });\n }\n\n const referenced = new Set(Object.values(state.answers).flatMap((answer) => answer.refs.map(rowKey)));\n // Every pooled row joins its answer's refs above, so nothing arrives unused;\n // a row leaves here when no answer references it any more \u2014 its answer was\n // dropped, or replaced by a delivery whose closure no longer pools it.\n for (const key of Object.keys(state.rows)) if (!referenced.has(key)) {\n delete state.rows[key];\n delete state.rowSeq[key];\n }\n\n // Bytes join the swap by row lease: whatever left `state.rows` above takes its bytes with it.\n const byteDelta = applyByteSwap(state, swap, leasedAssets(Object.values(state.rows), Object.values(state.answers)));\n bytes.put.push(...byteDelta.put);\n bytes.remove.push(...byteDelta.remove);\n\n const previousTail = tailWatermark(Object.values(state.watermarks));\n if (swap.watermark) {\n const key = canonicalAnswerKey(swap.watermark.op, swap.watermark.args);\n // The order is the store's: first recorded, kept across re-marks (LLP 1012 \u00A77's tail chooser).\n const order = state.watermarks[key]?.order ?? ++state.clock;\n state.watermarks[key] = { ...clone(swap.watermark), order };\n }\n const tail = tailWatermark(Object.values(state.watermarks));\n // The outbox, its grants, its write bounds, and the prediction overlay are\n // custody of unsent work: a coverage reset above never touches them.\n for (const intent of swap.outbox?.remove ?? []) {\n delete state.outbox[intent];\n delete state.overlayMisses[intent];\n delete state.overlay[intent];\n delete state.overlayWatermarks[intent];\n delete state.overlayNegatives[intent];\n }\n const committedNow = new Set<string>();\n for (const entry of swap.outbox?.put ?? []) {\n if (typeof entry.intent !== \"string\" || entry.intent.length === 0) throw new TypeError(\"outbox entry needs an intent\");\n const previous = state.outbox[entry.intent];\n if (entry.state === \"committed\" && previous?.state !== \"committed\") committedNow.add(entry.intent);\n const order = previous?.order ?? entry.order ?? ++state.clock;\n state.outbox[entry.intent] = { ...clone(entry), order };\n }\n if (swap.bounds) state.bounds = clone(swap.bounds);\n if (swap.programs) state.programs = clone(swap.programs);\n for (const id of swap.grants?.remove ?? []) {\n delete state.grants[id];\n if (state.currentGrant === id) delete state.currentGrant;\n }\n for (const grant of swap.grants?.put ?? []) state.grants[grant.id] = clone(grant);\n if (swap.grants?.current === null) delete state.currentGrant;\n else if (typeof swap.grants?.current === \"string\") {\n if (!state.grants[swap.grants.current]) throw new TypeError(\"current grant must be a held grant\");\n state.currentGrant = swap.grants.current;\n }\n for (const intent of swap.overlay?.remove ?? []) {\n delete state.overlay[intent];\n delete state.overlayMisses[intent];\n delete state.overlayWatermarks[intent];\n delete state.overlayNegatives[intent];\n }\n for (const [intent, rows] of Object.entries(swap.overlay?.put ?? {})) {\n state.overlay[intent] = clone(rows);\n delete state.overlayMisses[intent];\n delete state.overlayWatermarks[intent];\n delete state.overlayNegatives[intent];\n }\n // @ref LLP 1012#7-writes-offline \u2014 retire on authoritative row/negative\n // evidence, a non-empty page reached by a post-commit next-cursor chain,\n // or two misses (proven forward marks or successful resumes, once per swap).\n // A reset rebases the snapshot at the new drain's current head; opaque cursor names\n // and positions from the former coverage cannot order the new log.\n const answers = Object.keys(state.overlay).some((intent) => state.outbox[intent]?.state === \"committed\")\n ? Object.values(state.answers) : [];\n const pages = answers.filter((answer) => {\n const nonempty = Array.isArray(answer.data) ? answer.data.length > 0 : collectRefs(answer.data).length > 0;\n return (answer.state === \"complete\" || answer.state === \"capped\") && answer.receipt !== undefined\n && !answer.receipt.ranges.some((range) => (range.evictedIds?.length ?? 0) > 0)\n && nonempty && answer.refs.length > 0 && answer.refs.every((ref) => state.rows[rowKey(ref)] !== undefined);\n });\n const chains = new Map<string, { chain: string[]; reached: Set<string | null | undefined> }>();\n for (const intent of Object.keys(state.overlay)) {\n const entry = state.outbox[intent];\n if (entry === undefined || entry.state === \"rejected\" || entry.state === \"expired\") {\n delete state.overlay[intent];\n delete state.overlayMisses[intent];\n delete state.overlayWatermarks[intent];\n delete state.overlayNegatives[intent];\n if (entry) delete entry.predicted;\n continue;\n }\n for (const row of state.overlay[intent]!) {\n const key = rowKey(row);\n const evidence = authoritativeNegatives.get(key);\n if (evidence !== undefined && evidence.seq >= (state.overlayNegatives[intent]?.[key]?.seq ?? -1)) {\n (state.overlayNegatives[intent] ??= {})[key] = evidence;\n }\n }\n if (entry.state !== \"committed\") continue;\n if (state.overlayWatermarks[intent] == null && tail !== undefined) {\n const snapshot = committedNow.has(intent) && state.overlayWatermarks[intent] !== null ? previousTail ?? tail : tail;\n state.overlayWatermarks[intent] = {\n op: snapshot.op, args: clone(snapshot.args), cursorArg: snapshot.cursorArg ?? \"c\",\n watermark: snapshot.watermark,\n };\n }\n const committedSeq = (entry.response as { seq?: unknown } | undefined)?.seq;\n if (!Number.isSafeInteger(committedSeq)) {\n delete state.overlay[intent];\n delete state.overlayMisses[intent];\n delete state.overlayWatermarks[intent];\n delete state.overlayNegatives[intent];\n delete entry.predicted;\n continue;\n }\n const overlay = state.overlay[intent]!;\n const seq = Number(committedSeq);\n // A deletion is confirmed by absence, never by a still-present row.\n const predicted = new Set(overlay.filter((row) => !row.removed).map(rowKey));\n const committedWatermark = state.overlayWatermarks[intent] ?? undefined;\n const chainKey = committedWatermark ? canonical({ op: committedWatermark.op, args: committedWatermark.args,\n cursorArg: committedWatermark.cursorArg, watermark: committedWatermark.watermark, seq }) : \"\";\n if (!chains.has(chainKey)) {\n const chain = committedWatermark ? cursorChain(pages, committedWatermark, seq) : [];\n chains.set(chainKey, { chain, reached: new Set(chain) });\n }\n const { chain, reached } = chains.get(chainKey)!;\n const negative = overlay.some((row) => {\n const evidence = state.overlayNegatives[intent]?.[rowKey(row)];\n return evidence !== undefined && evidence.seq >= seq && (state.rowSeq[rowKey(row)] ?? -1) <= evidence.seq;\n });\n // The closure's pooled halo/rule-input row is authoritative arrival too.\n const arrived = negative || answers.some((answer) => answer.seq >= seq && !answer.retained && answer.state !== \"denied\"\n && answer.refs.some((ref) => predicted.has(rowKey(ref)) && state.rows[rowKey(ref)] !== undefined))\n || (predicted.size > 0 && committedWatermark !== undefined && pages.some((page) => page.seq >= seq\n && reached.has(pagePosition(page, committedWatermark))));\n const advanced = committedWatermark !== undefined && swap.watermark !== undefined\n && tail !== undefined && canonicalAnswerKey(tail.op, tail.args) === canonicalAnswerKey(swap.watermark.op, swap.watermark.args)\n && advanceOverlay(committedWatermark, tail, chain);\n const moved = advanced || (swap.resumeSeq !== undefined && swap.resumeSeq > seq);\n const misses = arrived ? 0 : (state.overlayMisses[intent] ?? 0)\n + (moved && !committedNow.has(intent) ? 1 : 0);\n if (!arrived && misses < OVERLAY_PATIENCE) {\n if (misses > 0) state.overlayMisses[intent] = misses;\n continue;\n }\n delete state.overlay[intent];\n delete state.overlayMisses[intent];\n delete state.overlayWatermarks[intent];\n delete state.overlayNegatives[intent];\n delete entry.predicted;\n }\n return state;\n }\n\n private ensureOpen(): void {\n if (this.partition === undefined) {\n throw new OfflineStoreFailure(\"E_OFFLINE_CARRIER\", `${this.backend.carrier} range store is not open`);\n }\n }\n\n private ensureUnsealed(): void {\n if (this.state.sealed) throw new OfflineStoreFailure(\"E_OFFLINE_CARRIER\", \"range store is sealed\");\n }\n\n private enqueue<T>(action: () => Promise<T>): Promise<T> {\n const run = this.tail.then(action);\n this.tail = run.then(() => undefined, () => undefined);\n return run;\n }\n\n private async read<T>(action: () => T): Promise<T> {\n await this.tail;\n this.ensureOpen();\n return action();\n }\n}\n", "import { OfflineStoreFailure } from \"./range-store.js\";\n\nexport interface StoreLocks {\n request<T>(name: string, options: { ifAvailable: true }, callback: (lock: { readonly name?: string } | null) => T | Promise<T>): Promise<T>;\n}\n\n// @ref LLP 1013#4-locks-the-token-store-and-the-partition \u2014 a global symbol\n// keeps the one-writer table shared even across separately emitted bundles.\n// Deliberate pre-publication rename from snapback2.offline.locks for the new scoped value shape.\nconst key = Symbol.for(\"snapback2.offline.storeLocks\");\ntype LockScope = string | object;\nconst scopes = ((globalThis as Record<PropertyKey, unknown>)[key] ??= new Map()) as Map<LockScope, Map<string, object>>;\n\nexport function inProcessLocks(scope: LockScope = \"default\"): StoreLocks {\n return {\n async request(name, _options, callback) {\n const held = scopes.get(scope) ?? new Map<string, object>();\n if (held.has(name)) return callback(null);\n scopes.set(scope, held);\n const lock = { name };\n held.set(name, lock);\n try { return await callback(lock); }\n finally {\n if (held.get(name) === lock) held.delete(name);\n if (held.size === 0) scopes.delete(scope);\n }\n },\n };\n}\n\nexport async function acquireStoreLock(locks: StoreLocks, partition: string): Promise<() => Promise<void>> {\n let accept!: () => void;\n let refuse!: (error: unknown) => void;\n let release!: () => void;\n const acquired = new Promise<void>((resolve, reject) => { accept = resolve; refuse = reject; });\n const released = new Promise<void>((resolve) => { release = resolve; });\n const request = locks.request(`snapback2:${partition}`, { ifAvailable: true }, async (lock) => {\n if (!lock) {\n refuse(new OfflineStoreFailure(\"E_OFFLINE_LOCK\", \"this account is open in another client; close it and try again\"));\n return;\n }\n accept();\n await released;\n });\n void request.catch(refuse);\n await acquired;\n return async () => { release(); await request; };\n}\n", "import { emptyState, jsonState, type PersistedRangeState } from \"./range-store.js\";\n\nexport type StateEntry = { key: string; value: unknown };\nexport type StateProjection = Record<\"rows\" | \"answers\" | \"outbox\" | \"meta\", StateEntry[]>;\n\n// @ref LLP 1013#3-the-sqlite-carrier \u2014 one projection for both database carriers;\n// the rest carries future metadata fields without a second list to keep in sync.\nexport function projectState(state: PersistedRangeState): StateProjection {\n // State has the JSON wire form on every carrier: omit undefined object fields,\n // preserve null, and turn undefined array slots into null. Bytes travel separately.\n const { rows = {}, answers = {}, outbox = {}, ...meta } = jsonState(state);\n const entries = (value: object) => Object.entries(value).map(([key, value]) => ({ key, value }));\n return { rows: entries(rows), answers: entries(answers), outbox: entries(outbox), meta: [{ key: \"state\", value: meta }] };\n}\n\nexport function unprojectState(projected: StateProjection): PersistedRangeState | undefined {\n const meta = projected.meta.find(({ key }) => key === \"state\");\n if (!meta && !projected.rows.length && !projected.answers.length && !projected.outbox.length) return undefined;\n const record = (entries: StateEntry[]) => Object.fromEntries(entries.map(({ key, value }) => [key, value]));\n return {\n ...emptyState(),\n ...meta?.value as Omit<PersistedRangeState, \"rows\" | \"answers\" | \"outbox\">,\n rows: record(projected.rows) as PersistedRangeState[\"rows\"],\n answers: record(projected.answers) as PersistedRangeState[\"answers\"],\n outbox: record(projected.outbox) as PersistedRangeState[\"outbox\"],\n };\n}\n\n/** Split only the first separator: a row id may itself contain NUL. */\nexport function encodeStateKey(key: string, tuple: boolean): string {\n const at = tuple ? key.indexOf(\"\\u0000\") : -1;\n return JSON.stringify(at < 0 ? [key] : [key.slice(0, at), key.slice(at + 1)]);\n}\n\nexport function decodeStateKey(key: string): string {\n const parts: unknown = JSON.parse(key);\n if (!Array.isArray(parts) || parts.length < 1 || parts.length > 2 || parts.some((part) => typeof part !== \"string\")) {\n throw new Error(\"invalid sqlite state key\");\n }\n return parts.join(\"\\u0000\");\n}\n", "import {\n OfflineStoreFailure, PersistentRangeStore,\n type PersistedRangeState, type RangeStoreBackend, type RangeStoreFactory,\n} from \"./range-store.js\";\nimport type { ByteDelta } from \"./byte-cache.js\";\nimport { acquireStoreLock, inProcessLocks, type StoreLocks } from \"./locks.js\";\nimport { decodeStateKey, encodeStateKey, projectState, unprojectState, type StateEntry } from \"./projection.js\";\nimport type { SqliteDriver } from \"./sqlite-driver.js\";\n\nexport type { SqliteDriver, SqliteExecutor, SqliteParams } from \"./sqlite-driver.js\";\nexport { inProcessLocks } from \"./locks.js\";\n\nexport interface SqliteRangeStoreOptions {\n locks?: StoreLocks;\n /** Witness barrier, after all DML and inside the transaction, before COMMIT. */\n beforeCommit?: (state: PersistedRangeState, bytes: ByteDelta) => void | Promise<void>;\n}\n\nconst STATE_TABLES = [\"state\", \"rows\", \"answers\", \"outbox\"] as const;\nconst TABLES = [...STATE_TABLES, \"bytes\"] as const;\nconst SCHEMA = `\nCREATE TABLE IF NOT EXISTS state (partition TEXT NOT NULL PRIMARY KEY, value TEXT NOT NULL);\nCREATE TABLE IF NOT EXISTS rows (partition TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (partition, key));\nCREATE TABLE IF NOT EXISTS answers (partition TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (partition, key));\nCREATE TABLE IF NOT EXISTS outbox (partition TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (partition, key));\nCREATE TABLE IF NOT EXISTS bytes (partition TEXT NOT NULL, key TEXT NOT NULL, value BLOB NOT NULL, PRIMARY KEY (partition, key));\n`;\ntype DriverSource = SqliteDriver | (() => SqliteDriver | Promise<SqliteDriver>);\n\n/** Public backend seam: byte deltas share replace's transaction; wipe deletes all five tables. */\nexport class SqliteBackend implements RangeStoreBackend {\n readonly carrier = \"SQLite\";\n private driver?: SqliteDriver;\n private partition?: string;\n private release?: () => Promise<void>;\n private locks?: StoreLocks;\n\n constructor(private readonly source: DriverSource, private readonly options: SqliteRangeStoreOptions = {}) {}\n\n private async guard<T>(body: () => Promise<T>): Promise<T> {\n try { return await body(); }\n catch (error) {\n if (error instanceof OfflineStoreFailure) throw error;\n const message = error instanceof Error ? error.message : String(error);\n const busy = /SQLITE_BUSY|SQLITE_LOCKED|database (?:is )?(?:busy|locked)/i.test(message);\n const rewrite = busy ? \"another writer holds the store; close it or wait\" : \"open a writable database with expo-sqlite ^16\";\n throw new OfflineStoreFailure(\"E_OFFLINE_CARRIER\", `SQLite carrier: ${message}; ${rewrite}`, rewrite);\n }\n }\n\n async open(partition: string): Promise<PersistedRangeState | undefined> {\n await this.close();\n return this.guard(async () => {\n const driver = typeof this.source === \"function\" ? await this.source() : this.source;\n try {\n const identity = driver.identity;\n if (typeof identity !== \"string\" || !identity.trim()) {\n throw new OfflineStoreFailure(\"E_OFFLINE_CARRIER\", \"driver has no database identity\",\n \"supply a stable database identity on the SQLite driver\");\n }\n this.locks = this.options.locks ?? inProcessLocks(identity);\n this.release = await acquireStoreLock(this.locks, partition);\n }\n catch (error) {\n // A factory may open eagerly; a refused client owns that fresh connection.\n // A caller-supplied driver may belong to the client holding the lock.\n if (typeof this.source === \"function\") await driver.close().catch(() => undefined);\n throw error;\n }\n try {\n this.driver = driver;\n this.partition = partition;\n const mode = await this.driver.get<{ journal_mode: string }>(\"PRAGMA journal_mode=WAL\");\n if (mode?.journal_mode.toLowerCase() !== \"wal\") throw new Error(`journal_mode is ${mode?.journal_mode ?? \"missing\"}, expected wal`);\n await this.driver.exec(SCHEMA);\n return await this.driver.transaction(async (tx) => {\n const meta = await tx.get<{ value: string }>(\"SELECT value FROM state WHERE partition = ?\", [partition]);\n const read = async (table: \"rows\" | \"answers\" | \"outbox\"): Promise<StateEntry[]> =>\n (await tx.all<{ key: string; value: string }>(`SELECT key, value FROM ${table} WHERE partition = ?`, [partition]))\n .map(({ key, value }) => ({ key: decodeStateKey(key), value: JSON.parse(value) }));\n return unprojectState({ rows: await read(\"rows\"), answers: await read(\"answers\"), outbox: await read(\"outbox\"),\n meta: meta ? [{ key: \"state\", value: JSON.parse(meta.value) }] : [] });\n });\n } catch (error) {\n await this.close().catch(() => undefined);\n throw error;\n }\n });\n }\n\n // @ref LLP 1013#3-the-sqlite-carrier \u2014 state rewrite plus byte delta in one\n // transaction; the byte table is never rewritten wholesale and has no MIME column.\n async replace(state: PersistedRangeState, bytes: ByteDelta): Promise<void> {\n return this.guard(async () => {\n if (!this.driver || this.partition === undefined) throw new Error(\"not open\");\n const partition = this.partition;\n const projected = projectState(state);\n await this.driver.transaction(async (tx) => {\n for (const table of STATE_TABLES) await tx.run(`DELETE FROM ${table} WHERE partition = ?`, [partition]);\n await tx.run(\"INSERT INTO state (partition, value) VALUES (?, ?)\", [partition, JSON.stringify(projected.meta[0].value)]);\n for (const table of [\"rows\", \"answers\", \"outbox\"] as const) {\n for (const { key, value } of projected[table]) {\n await tx.run(`INSERT INTO ${table} (partition, key, value) VALUES (?, ?, ?)`,\n [partition, encodeStateKey(key, table !== \"outbox\"), JSON.stringify(value)]);\n }\n }\n for (const item of bytes.put) {\n await tx.run(\"INSERT OR REPLACE INTO bytes (partition, key, value) VALUES (?, ?, ?)\",\n [partition, encodeStateKey(item.key, false), item.bytes]);\n }\n for (const key of bytes.remove) await tx.run(\"DELETE FROM bytes WHERE partition = ? AND key = ?\", [partition, encodeStateKey(key, false)]);\n await this.options.beforeCommit?.(state, bytes);\n });\n });\n }\n\n async readBytes(key: string): Promise<Uint8Array | undefined> {\n return this.guard(async () => {\n if (!this.driver || this.partition === undefined) return undefined;\n const row = await this.driver.get<{ value: Uint8Array }>(\"SELECT value FROM bytes WHERE partition = ? AND key = ?\",\n [this.partition, encodeStateKey(key, false)]);\n return row?.value;\n });\n }\n\n async wipe(partition: string): Promise<void> {\n if (!this.driver) {\n await this.open(partition);\n return this.wipe(partition);\n }\n if (this.partition !== partition) {\n const release = await acquireStoreLock(this.locks!, partition);\n try {\n await this.guard(() => this.driver!.transaction(async (tx) => {\n for (const table of TABLES) await tx.run(`DELETE FROM ${table} WHERE partition = ?`, [partition]);\n }));\n } finally { await release(); }\n return;\n }\n await this.guard(async () => {\n await this.driver!.transaction(async (tx) => {\n for (const table of TABLES) await tx.run(`DELETE FROM ${table} WHERE partition = ?`, [partition]);\n });\n });\n await this.close();\n }\n\n async close(): Promise<void> {\n const driver = this.driver;\n const release = this.release;\n this.driver = undefined;\n this.partition = undefined;\n this.release = undefined;\n try { if (driver) await this.guard(() => driver.close()); }\n finally { await release?.(); }\n }\n}\n\n/** Pass a driver factory when this factory will construct multiple clients. */\nexport function sqliteRangeStore(driver: DriverSource, options: SqliteRangeStoreOptions = {}): RangeStoreFactory {\n const factory = (() => new PersistentRangeStore(new SqliteBackend(driver, options))) as RangeStoreFactory;\n Object.defineProperty(factory, \"carrier\", { value: \"SQLite\" });\n return factory;\n}\n", "import type { SqliteDriver } from \"./sqlite-driver.js\";\n\nexport interface SqliteConformanceResult { journalMode: string; checks: string[] }\n\n/** Portable: the witness passes two independently opened connections to the same scratch database. */\nexport async function runSqliteDriverConformance(open: () => SqliteDriver | Promise<SqliteDriver>): Promise<SqliteConformanceResult> {\n const first = await open();\n const second = await open();\n const checks: string[] = [];\n const check = (condition: unknown, message: string) => { if (!condition) throw new Error(`sqlite conformance: ${message}`); };\n try {\n const mode = await first.get<{ journal_mode: string }>(\"PRAGMA journal_mode=WAL\");\n const readback = await first.get<{ journal_mode: string }>(\"PRAGMA journal_mode\");\n check(mode?.journal_mode === readback?.journal_mode, \"journal_mode readback\");\n checks.push(\"journal_mode readback\");\n await first.exec(\"CREATE TABLE IF NOT EXISTS conformance (key TEXT PRIMARY KEY, value BLOB NOT NULL); DELETE FROM conformance;\");\n for (const length of [1, 1024 * 1024, 0]) {\n const bytes = new Uint8Array(length);\n for (let index = 0; index < length; index++) bytes[index] = index % 251;\n await first.run(\"INSERT INTO conformance VALUES (?, ?)\", [String(length), bytes]);\n const held = await first.get<{ value: Uint8Array }>(\"SELECT value FROM conformance WHERE key = ?\", [String(length)]);\n check(held?.value instanceof Uint8Array && held.value.length === length && held.value.every((value, index) => value === bytes[index]), `BLOB ${length}`);\n checks.push(`BLOB ${length}`);\n }\n const keys = [[\"messages\", \"m\\0x\"], [\"messages\", \"m\\0y\"], [\"messages\", \"\"], [\"messages\", \"quote\\\",\u96EA\"],\n [\"thread\", JSON.stringify({ nested: { words: [\"a\", \"b\"], empty: null } })]];\n for (const key of keys) await first.run(\"INSERT INTO conformance VALUES (?, ?)\", [JSON.stringify(key), new Uint8Array([9])]);\n for (const key of keys) {\n const held = await first.get<{ key: string }>(\"SELECT key FROM conformance WHERE key = ?\", [JSON.stringify(key)]);\n check(held?.key === JSON.stringify(key), \"JSON tuple key round trip\");\n }\n checks.push(\"JSON tuple key round trip\");\n const absent = await first.get(\"SELECT key FROM conformance WHERE key = ?\", [\"missing\"]);\n check(absent === undefined, \"missing row is undefined\");\n checks.push(\"missing row is undefined\");\n const marker = new Error(\"rollback marker\");\n try {\n await first.transaction(async (tx) => {\n await tx.run(\"INSERT INTO conformance VALUES (?, ?)\", [\"rollback\", new Uint8Array([1])]);\n await Promise.resolve();\n throw marker;\n });\n throw new Error(\"transaction swallowed throw\");\n } catch (error) { check(error === marker, \"rollback propagates the body error\"); }\n check(await first.get(\"SELECT key FROM conformance WHERE key = ?\", [\"rollback\"]) === undefined, \"rollback on throw\");\n checks.push(\"rollback on throw\");\n // The body ends its transaction. This proves error propagation and reuse,\n // not recovery from a COMMIT failure that leaves a live transaction.\n let commitFailed = false;\n await first.transaction(async (tx) => {\n await tx.run(\"INSERT INTO conformance VALUES (?, ?)\", [\"failed-commit\", new Uint8Array([7])]);\n await tx.run(\"ROLLBACK\");\n }).catch(() => { commitFailed = true; });\n check(commitFailed, \"COMMIT after rollback must fail\");\n check(await first.get(\"SELECT key FROM conformance WHERE key = ?\", [\"failed-commit\"]) === undefined, \"failed COMMIT leaves no row\");\n await first.transaction((tx) => tx.run(\"INSERT INTO conformance VALUES (?, ?)\", [\"after-failed-commit\", new Uint8Array([8])]));\n check(await first.get(\"SELECT key FROM conformance WHERE key = ?\", [\"after-failed-commit\"]) !== undefined, \"next transaction after failed COMMIT succeeds\");\n checks.push(\"body-ended transaction rejects and next transaction succeeds\");\n let release!: () => void;\n let reached!: () => void;\n let committed = false;\n let interleaved = false;\n const barrier = new Promise<void>((resolve) => { release = resolve; });\n const atBarrier = new Promise<void>((resolve) => { reached = resolve; });\n const write = first.transaction(async (tx) => {\n await tx.run(\"INSERT INTO conformance VALUES (?, ?)\", [\"barrier\", new Uint8Array([2])]);\n reached();\n await barrier;\n return 42;\n }).then((value) => { committed = true; return value; });\n await atBarrier;\n const competing = second.run(\"INSERT INTO conformance VALUES (?, ?)\", [\"competing\", new Uint8Array([3])])\n .then(() => { if (!committed) interleaved = true; }, (error) => {\n check(/busy|locked/i.test(String(error)), `competing writer must busy or wait: ${error}`);\n });\n // Also prove that an outer operation on this driver cannot enter its suspended transaction.\n let outerFinished = false;\n const outer = first.run(\"INSERT INTO conformance VALUES (?, ?)\", [\"outer\", new Uint8Array([4])]).then(() => { outerFinished = true; });\n await new Promise((resolve) => setTimeout(resolve, 25));\n const prematureOuter = outerFinished;\n release();\n check(await write === 42, \"transaction result\");\n await Promise.all([competing, outer]);\n check(!interleaved && !prematureOuter, \"late beforeCommit holds transaction\");\n checks.push(\"late beforeCommit holds transaction\", \"transaction result\");\n return { journalMode: readback!.journal_mode, checks };\n } finally {\n await first.close();\n await second.close();\n }\n}\n", "import type { PersistedRangeState } from \"../src/store/range-store.js\";\n\nexport const fixtureAsset = \"s2id-00000000000000000000000000000006-0000000000000001\";\n\n/** All state fields, with nonempty metadata; JSON values are the wire's value domain. */\nexport function sqliteState(clock = 1): PersistedRangeState {\n const id = `m\\u0000${clock}`;\n const row = { table: \"messages\", id, row: { id, body: `hello ${clock}`, photo: { id: fixtureAsset, width: 8, height: 8 } } };\n const args = { nested: { a: [1, \"\u96EA\", null], quote: \"\\\"\" } };\n const answerKey = `thread\\u0000${JSON.stringify(args)}`;\n const facts = { generation: \"g\", schemaHash: \"s\", authEpoch: 2 };\n const intent = `grant:${clock}`;\n return {\n version: 1, sealed: false, clock,\n rows: { [`messages\\u0000${id}`]: row, \"messages\\u0000plain\": { table: \"messages\", id: \"plain\", row: { id: \"plain\" } } },\n answers: { [answerKey]: { op: \"thread\", args, state: \"complete\", data: { $row: { table: \"messages\", id } },\n next: null, seq: clock, validator: \"v\", receipt: { ranges: [], absences: [[\"messages\", \"byId\", [\"absent\"]]], verdicts: [true] },\n deliveredAt: 100, refs: [{ table: \"messages\", id }], order: 1, fingerprint: \"fp\", retained: true, caughtUp: true, watermark: null } },\n watermarks: { [answerKey]: { op: \"thread\", args, watermark: null, validator: \"v\", ...facts, updatedAt: 100, order: 1 } },\n outbox: { [intent]: { intent, grant: \"grant\", offset: clock, count: 2, ids: [id], op: \"send\", args: { body: \"queued\" },\n issuedSeq: clock, state: \"queued\", predicted: true, trace: { points: [], verdicts: [] }, createdAt: 100, updatedAt: 100, order: 1 } },\n grants: { grant: { id: \"grant\", from: \"start\", count: 100, mintedAt: 100, expiresAt: 200, used: clock } },\n currentGrant: \"grant\", overlay: { [intent]: [row] }, overlayMisses: { [intent]: clock },\n // Lane T1's commit-time tail snapshot (null after a reset) and T2's scoped negatives ride the same projection.\n overlayWatermarks: { [intent]: { op: \"inbox\", args: { c: null }, watermark: `cursor-${clock}`, cursorArg: \"c\", progress: `cursor-${clock}`, consumed: [\"cursor-0\"] }, \"grant:0\": null },\n overlayNegatives: { [intent]: { \"messages\\u0000absent\": { seq: clock, source: \"absence\" }, \"messages\\u0000gone\": { seq: clock, source: \"tombstone\" } } },\n bounds: { send: 1 },\n programs: { g: { generation: \"g\", schemaHash: \"s\", schema: { tables: {} }, programs: {\n thread: { kind: \"query\", planHash: \"p\", ir: { result: null }, certificate: { maxNewIds: 0 } },\n } } },\n facts, superseded: { ...facts, generation: \"new\" }, negative: { \"messages\\u0000absent\": clock }, rowSeq: { [`messages\\u0000${id}`]: clock },\n assets: { [fixtureAsset]: { assetId: fixtureAsset, width: null, type: \"image/jpeg\", size: 3, lastRead: clock } },\n viewed: { \"messages\\u0000viewed\": { at: 100, assets: [\"viewed-asset\"] } },\n };\n}\n", "// @ref LLP 1013#2-decisions \u2014 native files are derivatives; permission is always the cache's.\nimport type { AssetCache, ByteCache, ByteDelta } from \"../store/byte-cache.js\";\nimport { ASSET_ID, assetIdsIn, byteKey } from \"../store/byte-cache.js\";\nimport type { PersistedRangeState, RangeStore, RangeStoreBackend } from \"../store/range-store.js\";\nimport type { SnapbackClient } from \"../types.js\";\n\nexport interface NativeFileSystem {\n readonly root: string;\n list(directory: string): Promise<string[]>;\n exists?(uri: string): Promise<boolean>;\n write(uri: string, bytes: Uint8Array): Promise<void>;\n remove(uri: string): Promise<void>;\n}\nconst FILES = Symbol.for(\"snapback2.native.assetFiles\");\ntype FileStore = RangeStore & { [FILES]?: NativeAssetFiles };\n\nexport function attachAssetFiles(store: RangeStore, files: NativeAssetFiles): void {\n Object.defineProperty(store, FILES, { value: files });\n}\nexport function nativeAssetFiles(client: SnapbackClient): NativeAssetFiles | undefined {\n return ((client.assetCache as ByteCache | undefined)?.store as FileStore | undefined)?.[FILES];\n}\n\n/** Encoded even for adversarial principal strings; no partition can escape its directory. */\nexport function partitionDirectory(root: string, partition: string): string {\n return `${root.replace(/\\/$/, \"\")}/${encodeURIComponent(partition).replace(/\\./g, \"%2E\")}/`;\n}\n\nexport class NativeAssetFiles {\n private partition?: string;\n private state?: PersistedRangeState;\n private revision = 0;\n private custody = 0;\n private readonly assetRevisions = new Map<string, number>();\n private readonly listeners = new Set<() => void>();\n private readonly materialized = new Set<string>();\n // Serialize file writes and removals; a late write cannot resurrect an evicted file.\n private tail: Promise<unknown> = Promise.resolve();\n constructor(readonly fs: NativeFileSystem) {}\n getRevision = (): number => this.revision;\n getAssetRevision = (id: string): string => `${this.custody}:${this.assetRevisions.get(id) ?? 0}`;\n getCustody = (): number => this.custody;\n available = (): boolean => this.partition !== undefined && !this.state?.sealed;\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => { this.listeners.delete(listener); };\n };\n private changed(custody = false): void {\n this.revision++;\n if (custody) this.custody++;\n for (const listener of this.listeners) {\n try { listener(); } catch { /* Observers cannot undo a committed carrier swap. */ }\n }\n }\n private enqueue<T>(body: () => Promise<T>): Promise<T> {\n const result = this.tail.then(body);\n this.tail = result.catch(() => undefined);\n return result;\n }\n private remove(uri: string): Promise<void> {\n this.materialized.delete(uri);\n // A failed derivative delete must not turn an already committed SQLite swap\n // into a failed swap. It remains garbage, refused below and swept next open.\n return this.fs.remove(uri).catch(() => undefined);\n }\n private path(key: string, partition = this.partition): string | undefined {\n return partition === undefined ? undefined : partitionDirectory(this.fs.root, partition) + key;\n }\n private eligible(assetId: string, width: number | null): boolean {\n return this.partition !== undefined && !this.state?.sealed && this.state?.assets[byteKey(assetId, width)] !== undefined;\n }\n\n async get(cache: AssetCache, assetId: string, width: number | null): Promise<string | undefined> {\n if (!ASSET_ID.test(assetId)) return undefined;\n if (width !== null && (!Number.isSafeInteger(width) || width <= 0)) throw new TypeError(\"asset width must be a positive integer\");\n const revision = this.getAssetRevision(assetId);\n const uri = this.path(byteKey(assetId, width));\n if (!uri) return undefined;\n // The carrier read checks seal, lease, viewed set, payload existence and length.\n const once = await cache.viewOnce(assetId) || await cache.viewed(assetId);\n const held = once ? undefined : await cache.getBytes(assetId, width);\n return this.enqueue(async () => {\n // Recheck after acquiring the queue: viewed custody can move while a\n // preceding materialization holds it, even without a byte delta.\n if (!held || revision !== this.getAssetRevision(assetId) || !this.eligible(assetId, width)\n || await cache.viewOnce(assetId) || await cache.viewed(assetId)) {\n await this.remove(uri);\n return undefined;\n }\n if (!this.materialized.has(uri) || !await this.fs.exists?.(uri)) await this.fs.write(uri, held.bytes);\n if (revision !== this.getAssetRevision(assetId) || !this.eligible(assetId, width)\n || await cache.viewOnce(assetId) || await cache.viewed(assetId)) {\n await this.remove(uri);\n return undefined;\n }\n this.materialized.add(uri);\n return uri;\n });\n }\n\n /** Only backend success is a commit notification; never call this from beforeCommit. */\n async opened(partition: string, state: PersistedRangeState | undefined): Promise<void> {\n this.materialized.clear();\n this.partition = partition;\n this.state = state;\n this.changed(true);\n const directory = partitionDirectory(this.fs.root, partition);\n await this.enqueue(async () => {\n for (const name of await this.fs.list(directory)) {\n if (!state?.assets[name]) await this.remove(directory + name);\n }\n });\n }\n async replaced(state: PersistedRangeState, bytes: ByteDelta): Promise<void> {\n const sealed = this.state?.sealed !== state.sealed;\n const before = assetLeases(this.state), after = assetLeases(state);\n const changed = new Set([...before.keys(), ...after.keys()].filter((id) => before.get(id) !== after.get(id)));\n for (const key of [...bytes.remove, ...bytes.put.map((put) => put.key)]) changed.add(key.split(\".w\")[0]);\n for (const id of changed) this.assetRevisions.set(id, (this.assetRevisions.get(id) ?? 0) + 1);\n this.state = state;\n this.changed(sealed);\n const partition = this.partition;\n // A queued get rechecks the carrier, whose swap is awaiting this notification.\n // Publish custody now; cleanup follows asynchronously, never holding that swap.\n void this.enqueue(async () => {\n for (const key of [...bytes.remove, ...bytes.put.map((put) => put.key)]) {\n const uri = this.path(key, partition);\n if (uri) await this.remove(uri);\n }\n }).catch(() => undefined);\n }\n async wiped(partition: string): Promise<void> {\n if (this.partition === partition) this.closed();\n await this.enqueue(() => this.remove(partitionDirectory(this.fs.root, partition)));\n }\n closed(): void {\n this.materialized.clear();\n this.partition = undefined;\n this.state = undefined;\n this.changed(true);\n }\n}\n\n/** A message/grant/watermark swap that leaves a clip's lease unchanged keeps its player. */\nfunction assetLeases(state: PersistedRangeState | undefined): Map<string, string> {\n const refs = new Map<string, string[]>();\n for (const [key, row] of Object.entries(state?.rows ?? {})) {\n for (const id of assetIdsIn(row.row)) {\n const leases = refs.get(id) ?? [];\n leases.push(JSON.stringify([key, row.row, Boolean(state?.viewed[key])]));\n refs.set(id, leases);\n }\n }\n return new Map([...refs].map(([id, leases]) => [id, leases.sort().join(\"\\n\")]));\n}\n\nexport function fileBackend(backend: RangeStoreBackend, files: NativeAssetFiles): RangeStoreBackend {\n return {\n carrier: backend.carrier,\n async open(partition) {\n const state = await backend.open(partition);\n // Sweep errors leave unusable derivatives, never a substituted memory carrier.\n try { await files.opened(partition, state); }\n catch (error) { files.closed(); await backend.close(); throw error; }\n return state;\n },\n async replace(state, bytes) {\n await backend.replace(state, bytes);\n await files.replaced(state, bytes);\n },\n readBytes: backend.readBytes ? (key) => backend.readBytes!(key) : undefined,\n async wipe(partition) {\n await backend.wipe(partition); // Wiping the open partition also closes SQLite.\n await files.wiped(partition);\n },\n async close() {\n files.closed();\n await backend.close();\n },\n };\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;;;ACgBpB,SAAS,cAAyD;AACvE,MAAI,OAAO,QAAQ,QAAQ;AAC3B,SAAO,CAAC,SAAS;AACf,UAAM,SAAS,KAAK,KAAK,IAAI;AAC7B,WAAO,OAAO,KAAK,MAAM,QAAW,MAAM,MAAS;AACnD,WAAO;AAAA,EACT;AACF;;;ADnBO,SAAS,iBAAiB,MAA4B;AAC3D,MAAI;AACJ,MAAI;AACJ,QAAM,KAAK,MAAM,aAAa,IAAI,aAAa,IAAI;AACnD,QAAM,QAAQ,YAAY;AAC1B,QAAM,WAA2B;AAAA,IAC/B,MAAM,IAAI,KAAK,SAAS,CAAC,GAAG;AAAE,SAAG,EAAE,QAAQ,GAAG,EAAE,IAAI,GAAG,MAAM;AAAA,IAAG;AAAA,IAChE,MAAM,IAAO,KAAa,SAAS,CAAC,GAAG;AAAE,aAAQ,GAAG,EAAE,QAAQ,GAAG,EAAE,IAAI,GAAG,MAAM,KAAK;AAAA,IAA6B;AAAA,IAClH,MAAM,IAAO,KAAa,SAAS,CAAC,GAAG;AAAE,aAAO,GAAG,EAAE,QAAQ,GAAG,EAAE,IAAI,GAAG,MAAM;AAAA,IAAU;AAAA,EAC3F;AACA,SAAO;AAAA,IACL,IAAI,WAAW;AACb,SAAG;AACH,aAAO,aAAa,SAAS,cAAc,SAAS,KAChD,oBAAoB,WAAW,CAAC,KAAK,UAAU,aAAa,IAAI,CAAC;AAAA,IACvE;AAAA,IACA,KAAK,CAAC,KAAK,WAAW,MAAM,MAAM,SAAS,IAAI,KAAK,MAAM,CAAC;AAAA,IAC3D,KAAK,CAAC,KAAK,WAAW,MAAM,MAAM,SAAS,IAAI,KAAK,MAAM,CAAC;AAAA,IAC3D,KAAK,CAAC,KA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M,QAAQ,OAAO,OAAO;AAC1B,YAAM,QAAQ,QAAQ,OAAO,KAAK;AAClC,YAAM,MAAM,SAAS,OAAO,KAAK;AAAA,IACnC;AAAA,IACA,WAAW,QAAQ,YAAY,CAACA,SAAQ,QAAQ,UAAWA,IAAG,IAAI;AAAA,IAClE,MAAM,KAAK,WAAW;AACpB,YAAM,QAAQ,KAAK,SAAS;AAC5B,YAAM,MAAM,MAAM,SAAS;AAAA,IAC7B;AAAA,IACA,MAAM,QAAQ;AACZ,YAAM,OAAO;AACb,YAAM,QAAQ,MAAM;AAAA,IACtB;AAAA,EACF;AACF;",
|
|
6
|
+
"names": ["key", "held", "key", "position", "rowKey", "key", "rowKey", "key", "ref", "chain", "key", "value", "key", "key", "key"]
|
|
7
|
+
}
|
package/dist/sse.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Subscription } from "./types.js";
|
|
2
|
+
interface ParsedEvent {
|
|
3
|
+
id?: string;
|
|
4
|
+
data: string;
|
|
5
|
+
}
|
|
6
|
+
interface ErrorDecision<Event> {
|
|
7
|
+
event?: Event;
|
|
8
|
+
failure?: Error;
|
|
9
|
+
retry: boolean;
|
|
10
|
+
}
|
|
11
|
+
export interface ReconnectingSseOptions<Event> {
|
|
12
|
+
open(lastEventId: string | undefined, signal: AbortSignal): Promise<Response>;
|
|
13
|
+
decode(event: ParsedEvent, current: () => boolean): Event | Promise<Event>;
|
|
14
|
+
bufferedTerminal?(event: ParsedEvent): Error | undefined;
|
|
15
|
+
onError(error: unknown, hadDelivery: boolean): Promise<ErrorDecision<Event>> | ErrorDecision<Event>;
|
|
16
|
+
onLoss(last: Event | undefined): Event | undefined;
|
|
17
|
+
terminal?(event: Event): Error | undefined;
|
|
18
|
+
onEvent?: (event: Event) => void;
|
|
19
|
+
}
|
|
20
|
+
export declare class ReconnectingSse<Event> implements Subscription<Event> {
|
|
21
|
+
private readonly options;
|
|
22
|
+
private readonly controller;
|
|
23
|
+
private readonly waiters;
|
|
24
|
+
private last;
|
|
25
|
+
private lastEventId;
|
|
26
|
+
private terminalFailure;
|
|
27
|
+
private closed;
|
|
28
|
+
private activeAttempt?;
|
|
29
|
+
private retryNow?;
|
|
30
|
+
private resets;
|
|
31
|
+
private running?;
|
|
32
|
+
constructor(options: ReconnectingSseOptions<Event>);
|
|
33
|
+
close(): void;
|
|
34
|
+
/** Interrupt only the current attempt; the reconnecting subscription stays mounted. */
|
|
35
|
+
reconnect(): void;
|
|
36
|
+
/** A successor starts a new stream, with no predecessor event id or answer. */
|
|
37
|
+
reset(): void;
|
|
38
|
+
until(predicate: (event: Event) => boolean, timeoutMs?: number): Promise<Event>;
|
|
39
|
+
private deliver;
|
|
40
|
+
private fail;
|
|
41
|
+
private start;
|
|
42
|
+
private run;
|
|
43
|
+
}
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import type { RangeStore, RowRef, StoredRow } from "./range-store.js";
|
|
2
|
+
/** One cached rendition: what a component fetched at the width it asked for. */
|
|
3
|
+
export interface ByteCacheEntry {
|
|
4
|
+
assetId: string;
|
|
5
|
+
width: number | null;
|
|
6
|
+
size: number;
|
|
7
|
+
type: string;
|
|
8
|
+
/** Logical last-read stamp on the range store's clock; the LRU orders by it. */
|
|
9
|
+
lastRead: number;
|
|
10
|
+
}
|
|
11
|
+
/** A view-once row that was viewed, with the asset ids it carried at that moment. */
|
|
12
|
+
export interface ViewedRecord {
|
|
13
|
+
at: number;
|
|
14
|
+
assets: string[];
|
|
15
|
+
}
|
|
16
|
+
export interface ByteCachePut {
|
|
17
|
+
assetId: string;
|
|
18
|
+
width: number | null;
|
|
19
|
+
bytes: Uint8Array;
|
|
20
|
+
type: string;
|
|
21
|
+
}
|
|
22
|
+
export interface ByteSwapRequest {
|
|
23
|
+
put?: ByteCachePut[];
|
|
24
|
+
touch?: string[];
|
|
25
|
+
ceiling?: number;
|
|
26
|
+
}
|
|
27
|
+
/** What a carrier persists beside the state in the same swap: payloads to write and keys to drop. */
|
|
28
|
+
export interface ByteDelta {
|
|
29
|
+
put: Array<{
|
|
30
|
+
key: string;
|
|
31
|
+
bytes: Uint8Array;
|
|
32
|
+
}>;
|
|
33
|
+
remove: string[];
|
|
34
|
+
}
|
|
35
|
+
export interface ByteCacheStatus {
|
|
36
|
+
entries: ByteCacheEntry[];
|
|
37
|
+
totalBytes: number;
|
|
38
|
+
viewed: RowRef[];
|
|
39
|
+
}
|
|
40
|
+
export interface AssetBytes {
|
|
41
|
+
bytes: Uint8Array;
|
|
42
|
+
type: string;
|
|
43
|
+
}
|
|
44
|
+
/** An opaque identity held by one mounted viewing instance, never shared by asset id. */
|
|
45
|
+
export interface AssetFetchOptions {
|
|
46
|
+
signal?: AbortSignal;
|
|
47
|
+
viewing?: object;
|
|
48
|
+
}
|
|
49
|
+
export type ByteCacheOutcome = "cached" | "viewed" | "unleased" | "refused";
|
|
50
|
+
export type ViewOncePredicate = (table: string, row: Record<string, unknown>) => boolean;
|
|
51
|
+
/** The byte surface the swap engine exposes beside `RangeStore`; only the carriers implement it. */
|
|
52
|
+
export interface ByteCarrier {
|
|
53
|
+
readBytes(assetId: string, width: number | null): Promise<{
|
|
54
|
+
bytes: Uint8Array;
|
|
55
|
+
type: string;
|
|
56
|
+
} | undefined>;
|
|
57
|
+
bytes(): Promise<ByteCacheStatus>;
|
|
58
|
+
rowsReferencing(assetId: string): Promise<StoredRow[]>;
|
|
59
|
+
viewedAsset(assetId: string): Promise<boolean>;
|
|
60
|
+
viewedRows(): Promise<RowRef[]>;
|
|
61
|
+
/** LRU read stamps, coalesced: stamped in memory now, persisted by the next swap. */
|
|
62
|
+
touchBytes(keys: string[]): Promise<void>;
|
|
63
|
+
commit(swap: {
|
|
64
|
+
bytes?: ByteSwapRequest;
|
|
65
|
+
viewed?: RowRef[];
|
|
66
|
+
}): Promise<void>;
|
|
67
|
+
}
|
|
68
|
+
/** The client-facing byte cache: `client.assetCache` when the client has an offline store. */
|
|
69
|
+
export interface AssetCache {
|
|
70
|
+
/** Session custody changes revoke mounted object URLs. */
|
|
71
|
+
subscribeCustody?(listener: () => void): () => void;
|
|
72
|
+
getCustody?(): number;
|
|
73
|
+
getBytes(assetId: string, width: number | null, viewing?: object): Promise<AssetBytes | undefined>;
|
|
74
|
+
putBytes(assetId: string, width: number | null, value: AssetBytes, viewing?: object): Promise<ByteCacheOutcome>;
|
|
75
|
+
canServe(assetId: string, viewing?: object): Promise<boolean>;
|
|
76
|
+
/** The held bytes for an asset at a width, or nothing: never fetched, evicted with its row, viewed, or sealed. */
|
|
77
|
+
get(assetId: string, width: number | null, viewing?: object): Promise<Blob | undefined>;
|
|
78
|
+
/** True once a view-once row carrying this asset was viewed on this partition. */
|
|
79
|
+
viewed(assetId: string): Promise<boolean>;
|
|
80
|
+
/** True while a held row carrying this asset is view-once (`offline.viewOnce`) and not yet viewed. */
|
|
81
|
+
viewOnce(assetId: string): Promise<boolean>;
|
|
82
|
+
/** Marks the held view-once rows carrying this asset viewed: what a player calls when playback starts. */
|
|
83
|
+
markViewed(assetId: string): Promise<boolean>;
|
|
84
|
+
status(): Promise<ByteCacheStatus>;
|
|
85
|
+
}
|
|
86
|
+
export declare const ASSET_ID: RegExp;
|
|
87
|
+
export declare function byteKey(assetId: string, width: number | null): string;
|
|
88
|
+
/** The closed asset record shape (LLP 1006 §1): exactly id, width, height, and duration for video. */
|
|
89
|
+
export declare function assetRecordId(value: unknown): string | undefined;
|
|
90
|
+
export declare function assetIdsIn(value: unknown, output?: Set<string>): Set<string>;
|
|
91
|
+
/** Assets a held delivery references: through pooled rows and through inline answer data. */
|
|
92
|
+
export declare function leasedAssets(rows: Iterable<StoredRow>, answers: Iterable<{
|
|
93
|
+
data?: unknown;
|
|
94
|
+
}>): Set<string>;
|
|
95
|
+
export interface ByteSwapState {
|
|
96
|
+
clock: number;
|
|
97
|
+
rows: Record<string, StoredRow>;
|
|
98
|
+
assets: Record<string, ByteCacheEntry>;
|
|
99
|
+
viewed: Record<string, ViewedRecord>;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* View-once is tracked per row, never per asset id: an asset is refused only while
|
|
103
|
+
* every held row carrying it was viewed. A row that is not viewed keeps its lease,
|
|
104
|
+
* so one shared id never poisons an ordinary row's bytes.
|
|
105
|
+
*/
|
|
106
|
+
export declare function viewedOnlyAssets(state: Pick<ByteSwapState, "rows" | "viewed">): Set<string>;
|
|
107
|
+
/**
|
|
108
|
+
* The byte half of one swap, run after the row rules settled `state.rows`: viewed
|
|
109
|
+
* marks, the lease purge, read touches, puts, then the ceiling. Returns what the
|
|
110
|
+
* carrier must write and drop in the same transaction.
|
|
111
|
+
*/
|
|
112
|
+
export declare function applyByteSwap(state: ByteSwapState, swap: {
|
|
113
|
+
bytes?: ByteSwapRequest;
|
|
114
|
+
viewed?: RowRef[];
|
|
115
|
+
}, leased: Set<string>): ByteDelta;
|
|
116
|
+
/**
|
|
117
|
+
* Bytes a component fetched, kept under the owning row's lease in the same
|
|
118
|
+
* partition as the rows. A store without a byte carrier caches nothing.
|
|
119
|
+
*/
|
|
120
|
+
export declare class ByteCache implements AssetCache {
|
|
121
|
+
readonly store: RangeStore;
|
|
122
|
+
private readonly options;
|
|
123
|
+
/**
|
|
124
|
+
* View-once bytes stay renderable inside the instance that viewed them, keyed by
|
|
125
|
+
* the partition that viewed them; nothing here is durable. The runtime forgets it
|
|
126
|
+
* on seal, wipe, partition change, and close, and `get` serves it only under the
|
|
127
|
+
* custody the carrier path applies: this partition, unsealed, the row still held.
|
|
128
|
+
*/
|
|
129
|
+
private readonly session;
|
|
130
|
+
private partition?;
|
|
131
|
+
private custody;
|
|
132
|
+
private readonly custodyListeners;
|
|
133
|
+
readonly getCustody: () => number;
|
|
134
|
+
readonly subscribeCustody: (listener: () => void) => () => void;
|
|
135
|
+
private admissions;
|
|
136
|
+
constructor(store: RangeStore, options: {
|
|
137
|
+
maxAssetBytes: number;
|
|
138
|
+
viewOnce?: ViewOncePredicate;
|
|
139
|
+
});
|
|
140
|
+
/** The partition the runtime opened; a change drops every session blob. */
|
|
141
|
+
bind(partition: string | undefined): void;
|
|
142
|
+
/** Drops the session blobs: seal, close, and wipe call this. */
|
|
143
|
+
forget(): void;
|
|
144
|
+
get(assetId: string, width: number | null, viewing?: object): Promise<Blob | undefined>;
|
|
145
|
+
getBytes(assetId: string, width: number | null, viewing?: object): Promise<AssetBytes | undefined>;
|
|
146
|
+
/** Completion fence for both a cached source and an uncached ordinary source. */
|
|
147
|
+
canServe(assetId: string, viewing?: object): Promise<boolean>;
|
|
148
|
+
viewed(assetId: string): Promise<boolean>;
|
|
149
|
+
viewOnce(assetId: string): Promise<boolean>;
|
|
150
|
+
markViewed(assetId: string): Promise<boolean>;
|
|
151
|
+
/** After a network fetch: cache under the row's lease, or mark the view-once rows viewed and cache nothing. */
|
|
152
|
+
put(assetId: string, width: number | null, blob: Blob, viewing?: object): Promise<ByteCacheOutcome>;
|
|
153
|
+
putBytes(assetId: string, width: number | null, value: AssetBytes, viewing?: object): Promise<ByteCacheOutcome>;
|
|
154
|
+
private admit;
|
|
155
|
+
status(): Promise<ByteCacheStatus>;
|
|
156
|
+
/** Nothing is served, marked, or cached without an open partition and a byte carrier. */
|
|
157
|
+
private carrier;
|
|
158
|
+
private sessionKey;
|
|
159
|
+
/** The session blob, only while the row that was viewed is still held on this partition. */
|
|
160
|
+
private sessionBytes;
|
|
161
|
+
private viewOnceRows;
|
|
162
|
+
}
|