loro-repo 0.26.0 → 0.27.0

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.
@@ -255,6 +255,19 @@ var FlockPersistenceJournal = class {
255
255
  if (keys === this.keys && batch.events.length) this.onDirty();
256
256
  });
257
257
  }
258
+ /**
259
+ * Applies changes that are already durable at their owner: the replica
260
+ * records no payload or key for them.
261
+ */
262
+ absorb(apply) {
263
+ const previousKeys = this.remoteKeys;
264
+ this.remoteKeys = /* @__PURE__ */ new Set();
265
+ try {
266
+ return apply();
267
+ } finally {
268
+ this.remoteKeys = previousKeys;
269
+ }
270
+ }
258
271
  get hasPending() {
259
272
  return this.keys.size > 0 || this.payloads.length > 0;
260
273
  }
@@ -1 +1 @@
1
- {"version":3,"file":"flock-persistence-journal.cjs","names":["arr: JsonValue[]","obj: JsonObject","patch: JsonObject","flock: Flock","onDirty: () => void","result: T","outcome: Awaited<T>","payload","exportFlockFileSnapshot","bundle: ExportBundle","encodeMetaJsonUpdate"],"sources":["../src/internal/resource-ownership.ts","../src/utils.ts","../src/internal/flock-persistence-journal.ts"],"sourcesContent":["/**\n * Ownership and identity bookkeeping for one class of repository-managed\n * replicas (Loro documents, or named Flock documents).\n *\n * The invariant this exists to hold: **one resource id has at most one live\n * repository-managed replica at a time**. Without it, `unloadDoc()` could\n * evict the cached instance while a live transport room still held it, and\n * the next open would materialize a *second* replica — the caller editing one\n * copy while the room synchronized the other, with neither converging.\n *\n * Two pieces of state per id:\n *\n * - **owners** — every consumer currently holding the instance. Owners split\n * into two roles, because they need different eviction behaviour:\n * - `\"lease\"` owners are explicit `acquire*()` callers. They *block*\n * eviction: the caller promised to `release()`, so evicting under them\n * would hand them a replica the repository no longer tracks.\n * - `\"room\"` owners are live transport rooms. They do *not* block eviction,\n * because the repository can detach and rebind them itself — that\n * detach → evict → invalidate → reattach sequence is precisely what keeps\n * unload from forking the replica.\n * - **generation** — bumped whenever the instance backing an id is dropped.\n * Anything still referring to an older generation is stale by definition,\n * which lets rooms detect that they must rebind rather than keep\n * synchronizing a replica the repository no longer considers current.\n */\nexport type ResourceOwnerRole = \"lease\" | \"room\";\n\ninterface OwnerRecord {\n readonly role: ResourceOwnerRole;\n readonly label: string;\n}\n\nexport class ResourceOwnership {\n private readonly owners = new Map<string, Map<symbol, OwnerRecord>>();\n private readonly generations = new Map<string, number>();\n /**\n * Ids currently being evicted, with a count of overlapping evictions. New\n * leases are refused while an id is here, which closes the window between a\n * purge's pre-flight check and its destructive steps: `forgetFlockDoc`\n * deletes the durable remote cursor before the final check runs, so a lease\n * taken in between would fail the purge only *after* that cursor was\n * already gone. Counted rather than a set so one purge finishing cannot\n * drop the fence a concurrent purge of the same id still relies on.\n */\n private readonly evicting = new Map<string, number>();\n\n /** Current generation for `id`. Ids never dropped are generation 0. */\n generation(id: string): number {\n return this.generations.get(id) ?? 0;\n }\n\n /** Total live owners of `id`, in both roles. */\n ownerCount(id: string): number {\n return this.owners.get(id)?.size ?? 0;\n }\n\n /**\n * Registers one owner of `id` and returns its release callback. The token\n * is per-acquisition, so releasing twice only decrements once and one\n * owner's release cannot cancel another's.\n */\n acquire(id: string, role: ResourceOwnerRole, label: string): () => void {\n if (role === \"lease\" && this.evicting.has(id)) {\n throw new ResourceBusyError(\n \"resource\",\n id,\n [\"eviction in progress\"],\n `Cannot acquire resource \"${id}\": it is currently being evicted ` +\n `(unload or purge in progress). Retry after the eviction settles.`,\n );\n }\n const token = Symbol(label);\n let map = this.owners.get(id);\n if (!map) {\n map = new Map();\n this.owners.set(id, map);\n }\n map.set(token, { role, label });\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = this.owners.get(id);\n if (!current) return;\n current.delete(token);\n if (current.size === 0) this.owners.delete(id);\n };\n }\n\n /**\n * Labels of the owners that block eviction (explicit leases), for error\n * messages that need to tell a caller *why* an unload or purge was refused.\n * Live rooms are deliberately excluded: the repository detaches those\n * itself rather than failing the call.\n */\n blockingOwners(id: string): string[] {\n const map = this.owners.get(id);\n if (!map) return [];\n return [...map.values()]\n .filter((owner) => owner.role === \"lease\")\n .map((owner) => owner.label);\n }\n\n /**\n * Invalidates the instance currently bound to `id`: bumps the generation so\n * holders of the previous one can tell that the replica they reference is\n * no longer the repository's current replica. Called when the instance\n * backing an id is dropped (unload, purge) — never on ordinary edits.\n */\n invalidate(id: string): number {\n const next = this.generation(id) + 1;\n this.generations.set(id, next);\n return next;\n }\n\n /**\n * Marks `id` as being evicted, refusing new leases until the returned\n * callback runs. Call it in a `finally`.\n */\n beginEviction(id: string): () => void {\n this.evicting.set(id, (this.evicting.get(id) ?? 0) + 1);\n let ended = false;\n return () => {\n if (ended) return;\n ended = true;\n const count = this.evicting.get(id);\n if (count === undefined) return;\n if (count <= 1) {\n this.evicting.delete(id);\n } else {\n this.evicting.set(id, count - 1);\n }\n };\n }\n\n clear(): void {\n this.owners.clear();\n this.generations.clear();\n this.evicting.clear();\n }\n}\n\n/**\n * Raised when an unload or purge would evict a replica that an explicit lease\n * still holds. Carrying the owner labels makes the failure actionable — the\n * usual cause is an `acquire*()` the caller forgot to `release()`.\n */\nexport class ResourceBusyError extends Error {\n readonly resourceId: string;\n readonly owners: ReadonlyArray<string>;\n\n constructor(\n kind: string,\n resourceId: string,\n owners: ReadonlyArray<string>,\n message?: string,\n ) {\n super(\n message ??\n `Cannot evict ${kind} \"${resourceId}\": ${owners.length} active ` +\n `lease(s) still hold it (${owners.join(\", \")}). Release them ` +\n `first, or pass { force: true } to evict anyway and invalidate ` +\n `the replica.`,\n );\n this.name = \"ResourceBusyError\";\n this.resourceId = resourceId;\n this.owners = owners;\n }\n}\n\n/**\n * Raised when a durability barrier is asked to persist a replica the\n * repository has already replaced.\n *\n * Surfacing this rather than returning quietly is what keeps a remote cursor\n * from advancing past state nothing wrote: the barrier fails, so the cursor\n * save fails with it.\n */\nexport class StaleReplicaError extends Error {\n readonly resourceId: string;\n\n constructor(kind: string, resourceId: string) {\n super(\n `Cannot persist ${kind} \"${resourceId}\": the repository has replaced ` +\n `this replica, so the state held here is no longer the one it tracks.`,\n );\n this.name = \"StaleReplicaError\";\n this.resourceId = resourceId;\n }\n}\n","import type {\n JsonObject,\n JsonValue,\n ListDocQuery,\n} from \"./types\";\n\n/**\n * Throws an AbortError if the signal is aborted.\n * Use this to check for cancellation at safe points in long-running operations.\n */\nexport function throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n const error = new Error(\"Operation was aborted\");\n error.name = \"AbortError\";\n throw error;\n }\n}\n\nexport function cloneJsonValue(value: unknown): JsonValue | undefined {\n if (value === null) return null;\n if (typeof value === \"string\" || typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined;\n }\n if (Array.isArray(value)) {\n const arr: JsonValue[] = [];\n for (const entry of value) {\n const cloned = cloneJsonValue(entry);\n if (cloned !== undefined) {\n arr.push(cloned);\n }\n }\n return arr;\n }\n if (value && typeof value === \"object\") {\n const input = value as Record<string, unknown>;\n const obj: JsonObject = {};\n for (const [key, entry] of Object.entries(input)) {\n const cloned = cloneJsonValue(entry);\n if (cloned !== undefined) {\n obj[key] = cloned;\n }\n }\n return obj;\n }\n return undefined;\n}\n\nexport function cloneJsonObject(value: JsonObject): JsonObject {\n const cloned = cloneJsonValue(value);\n if (cloned && typeof cloned === \"object\" && !Array.isArray(cloned)) {\n return cloned;\n }\n return {};\n}\n\nexport function asJsonObject(value: unknown): JsonObject | undefined {\n const cloned = cloneJsonValue(value);\n if (cloned && typeof cloned === \"object\" && !Array.isArray(cloned)) {\n return cloned;\n }\n return undefined;\n}\n\nexport function jsonEquals(a?: JsonValue, b?: JsonValue): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n if (a === null || b === null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return a === b;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a)) {\n const bArr = b as JsonValue[];\n if (a.length !== bArr.length) return false;\n return a.every((v, i) => jsonEquals(v, bArr[i]));\n }\n const aObj = a as JsonObject;\n const bObj = b as JsonObject;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every((k) => jsonEquals(aObj[k], bObj[k]));\n}\n\nexport function diffJsonObjects(\n previous: JsonObject | undefined,\n next: JsonObject,\n): JsonObject {\n const patch: JsonObject = {};\n const keys = new Set<string>();\n if (previous) {\n for (const key of Object.keys(previous)) keys.add(key);\n }\n for (const key of Object.keys(next)) keys.add(key);\n for (const key of keys) {\n const prevValue = previous ? previous[key] : undefined;\n const nextValue = next[key];\n if (!jsonEquals(prevValue, nextValue)) {\n if (nextValue === undefined && previous && key in previous) {\n patch[key] = null;\n continue;\n }\n const cloned = cloneJsonValue(nextValue);\n if (cloned !== undefined) {\n patch[key] = cloned;\n }\n }\n }\n return patch;\n}\n\nexport function matchesQuery(\n docId: string,\n _metadata: JsonObject,\n query?: ListDocQuery,\n): boolean {\n if (!query) return true;\n if (query.prefix && !docId.startsWith(query.prefix)) return false;\n if (query.start && docId < query.start) return false;\n if (query.end && docId > query.end) return false;\n return true;\n}\n","import type {\n ExportBundle,\n Flock,\n KeyPart,\n VersionVector,\n} from \"@loro-dev/flock-wasm\";\nimport { encodeMetaJsonUpdate } from \"../storage/meta-snapshot\";\nimport { exportFlockFileSnapshot } from \"./flock-snapshot\";\n\n// The repo and transport are separate package entry points (and may use\n// different ESM/CJS module instances). Attach the journal to the replica,\n// rather than relying on a module-local WeakMap shared by both entry points.\nconst journalKey = Symbol.for(\"loro-repo.flock-persistence-journal.v1\");\ntype JournalledFlock = Flock & { [journalKey]?: FlockPersistenceJournal };\n\ninterface PendingPayload {\n readonly bytes: Uint8Array;\n failures: number;\n}\n\nconst MAX_EXACT_PAYLOAD_SAVE_ATTEMPTS = 3;\n\n/**\n * Persists `updates` in order. Reports how many leading updates are durable\n * and, if not all of them are, the failure. It must not reject.\n */\nexport type JournalWrite = (\n updates: readonly Uint8Array[],\n) => Promise<{ readonly durable: number; readonly error?: unknown }>;\n\nfunction versionsEqual(left: VersionVector, right: VersionVector): boolean {\n const leftPeers = Object.keys(left);\n const rightPeers = Object.keys(right);\n if (leftPeers.length !== rightPeers.length) return false;\n return leftPeers.every((peer) => {\n const a = left[peer];\n const b = right[peer];\n return (\n a?.physicalTime === b?.physicalTime &&\n a?.logicalCounter === b?.logicalCounter\n );\n });\n}\n\n/** Pending exact records and received payloads, acknowledged only after save. */\nexport class FlockPersistenceJournal {\n private readonly keys = new Set<string>();\n private readonly payloads: PendingPayload[] = [];\n private readonly unsubscribe: () => void;\n private remoteKeys?: Set<string>;\n /**\n * An inclusive version vector observed with no Flock event since. Exporting\n * a version vector from wasm costs time proportional to the number of\n * peers, and Streams delivers many batches that change nothing (echoes of\n * our own appends, replayed catch-ups). Reusing the vector read after the\n * previous import keeps such a batch to a single read.\n */\n private knownVersion?: VersionVector;\n\n constructor(\n private readonly flock: Flock,\n private readonly onDirty: () => void,\n ) {\n (flock as JournalledFlock)[journalKey] = this;\n this.unsubscribe = flock.subscribe((batch) => {\n // Local commits can be emitted by beforeImport(), even inside a remote\n // import. They must survive alongside the received payload.\n const keys =\n batch.source !== \"local\" && this.remoteKeys ? this.remoteKeys : this.keys;\n for (const event of batch.events) {\n keys.add(JSON.stringify(event.key));\n }\n if (batch.events.length) this.knownVersion = undefined;\n if (keys === this.keys && batch.events.length) this.onDirty();\n });\n }\n\n get hasPending(): boolean {\n return this.keys.size > 0 || this.payloads.length > 0;\n }\n\n async receive<T>(\n payloads: readonly Uint8Array[],\n apply: () => T,\n ): Promise<Awaited<T>> {\n const copies = payloads\n .filter((bytes) => bytes.length > 0)\n .map((bytes) => bytes.slice());\n // Existing Flock adapter imports are synchronous. Only suppress their\n // synchronous remote events; unrelated work after an await is observable.\n let result: T;\n const previousKeys = this.remoteKeys;\n const remoteKeys = new Set<string>();\n // The inclusive vector only grows during the process lifetime, so a\n // cached vector that is stale because of an untracked import can only\n // cause a redundant save, never a skipped one.\n const previousVersion = this.knownVersion ?? this.flock.inclusiveVersion();\n this.remoteKeys = remoteKeys;\n try {\n result = apply();\n } catch (error) {\n // A batch import can partially succeed before throwing. Retain its\n // accepted records without persisting a possibly malformed payload.\n this.retainChangedKeys(remoteKeys);\n throw error;\n } finally {\n this.remoteKeys = previousKeys;\n }\n let outcome: Awaited<T>;\n try {\n outcome = await result;\n } catch (error) {\n this.retainChangedKeys(remoteKeys);\n throw error;\n }\n // Streams can echo an append back to its producer, and a bootstrap can\n // repeat state already hydrated locally. Flock emits no remote events in\n // either case, so there is no newly accepted state to journal. A genuine\n // same-VV hole does emit the missing key and still records the exact\n // received bytes. An import can also advance the version without\n // emitting events (an entry that loses last-writer-wins), so compare.\n if (remoteKeys.size > 0 || !this.versionUnchangedSince(previousVersion)) {\n this.payloads.push(...copies.map((bytes) => ({ bytes, failures: 0 })));\n if (copies.length) this.onDirty();\n }\n return outcome;\n }\n\n private versionUnchangedSince(previous: VersionVector): boolean {\n const current = this.flock.inclusiveVersion();\n this.knownVersion = current;\n return versionsEqual(previous, current);\n }\n\n private retainChangedKeys(keys: ReadonlySet<string>): void {\n for (const key of keys) this.keys.add(key);\n if (keys.size) this.onDirty();\n }\n\n /**\n * Called within the owner's serialized persistence queue.\n *\n * Each round hands every pending payload to `write` at once, so a storage\n * adapter can commit them in one transaction. Only the prefix `write`\n * reports durable is acknowledged.\n */\n async flush(write: JournalWrite): Promise<void> {\n this.flock.commit();\n while (this.hasPending) {\n if (this.keys.size) {\n await this.stageChangedKeys();\n }\n\n const { durable, error: exactError } = await write(\n this.payloads.map((payload) => payload.bytes),\n );\n // Only this loop removes payloads, so the written ones are still the\n // queue's prefix. New imports/local changes during the write remain\n // behind them.\n this.payloads.splice(0, durable);\n if (exactError === undefined) continue;\n\n const payload = this.payloads[0]!;\n payload.failures += 1;\n // One failing barrier must still block its remote cursor. Repeated\n // barriers retry the exact bytes up to a bounded count before using\n // the mergeable full-state fallback below.\n if (payload.failures < MAX_EXACT_PAYLOAD_SAVE_ATTEMPTS) {\n throw exactError;\n }\n // A storage adapter can reject one otherwise accepted encoding\n // forever. A full file is another mergeable representation of the\n // current CRDT state, so it can safely cover that queue item. Never\n // advance past the item unless this fallback itself is durable.\n // The exported file covers every payload that was queued when the\n // export began, not just the failing head. Payloads received while\n // the incremental export or save awaits are appended after this\n // boundary and must remain pending.\n const coveredPayloads = this.payloads.length;\n const snapshot = await exportFlockFileSnapshot(this.flock);\n const fallback = await write([snapshot]);\n if (fallback.error !== undefined) {\n throw new AggregateError(\n [exactError, fallback.error],\n \"Failed to persist a Flock update and its snapshot fallback\",\n );\n }\n this.payloads.splice(0, coveredPayloads);\n }\n }\n\n private async stageChangedKeys(): Promise<void> {\n const capturedKeys = [...this.keys];\n for (const key of capturedKeys) this.keys.delete(key);\n try {\n const bundle: ExportBundle = { version: 0, entries: {} };\n let useSnapshot = false;\n for (const key of capturedKeys) {\n let entry;\n try {\n entry = this.flock.getEntry(JSON.parse(key) as KeyPart[]);\n } catch {\n useSnapshot = true;\n break;\n }\n if (!entry) {\n useSnapshot = true;\n break;\n }\n const { physicalTime, logicalCounter, peerId } = entry.clock;\n bundle.entries[key] = {\n c: `${physicalTime},${logicalCounter},${peerId}`,\n ...(entry.data === undefined ? {} : { d: entry.data }),\n ...(Object.keys(entry.metadata).length ? { m: entry.metadata } : {}),\n };\n }\n const bytes = useSnapshot\n ? await exportFlockFileSnapshot(this.flock)\n : encodeMetaJsonUpdate(bundle);\n this.payloads.push({ bytes, failures: 0 });\n } catch (error) {\n // The current state has not been represented in the payload queue.\n // Restore the captured markers without disturbing newer events.\n for (const key of capturedKeys) this.keys.add(key);\n throw error;\n }\n }\n\n destroy(): void {\n this.unsubscribe();\n if ((this.flock as JournalledFlock)[journalKey] === this) {\n delete (this.flock as JournalledFlock)[journalKey];\n }\n }\n}\n\n/** Preserve plaintext CRDT bytes at the public Streams adapter boundary. */\nexport async function receiveFlockPayloads<T>(\n flock: Flock,\n payloads: readonly Uint8Array[],\n apply: () => T,\n): Promise<Awaited<T>> {\n const journal = (flock as JournalledFlock)[journalKey];\n return journal ? journal.receive(payloads, apply) : await apply();\n}\n"],"mappings":";;;;AAiCA,IAAa,oBAAb,MAA+B;CAC7B,AAAiB,yBAAS,IAAI,KAAuC;CACrE,AAAiB,8BAAc,IAAI,KAAqB;;;;;;;;;;CAUxD,AAAiB,2BAAW,IAAI,KAAqB;;CAGrD,WAAW,IAAoB;AAC7B,SAAO,KAAK,YAAY,IAAI,GAAG,IAAI;;;CAIrC,WAAW,IAAoB;AAC7B,SAAO,KAAK,OAAO,IAAI,GAAG,EAAE,QAAQ;;;;;;;CAQtC,QAAQ,IAAY,MAAyB,OAA2B;AACtE,MAAI,SAAS,WAAW,KAAK,SAAS,IAAI,GAAG,CAC3C,OAAM,IAAI,kBACR,YACA,IACA,CAAC,uBAAuB,EACxB,4BAA4B,GAAG,mGAEhC;EAEH,MAAM,QAAQ,OAAO,MAAM;EAC3B,IAAI,MAAM,KAAK,OAAO,IAAI,GAAG;AAC7B,MAAI,CAAC,KAAK;AACR,yBAAM,IAAI,KAAK;AACf,QAAK,OAAO,IAAI,IAAI,IAAI;;AAE1B,MAAI,IAAI,OAAO;GAAE;GAAM;GAAO,CAAC;EAC/B,IAAI,WAAW;AACf,eAAa;AACX,OAAI,SAAU;AACd,cAAW;GACX,MAAM,UAAU,KAAK,OAAO,IAAI,GAAG;AACnC,OAAI,CAAC,QAAS;AACd,WAAQ,OAAO,MAAM;AACrB,OAAI,QAAQ,SAAS,EAAG,MAAK,OAAO,OAAO,GAAG;;;;;;;;;CAUlD,eAAe,IAAsB;EACnC,MAAM,MAAM,KAAK,OAAO,IAAI,GAAG;AAC/B,MAAI,CAAC,IAAK,QAAO,EAAE;AACnB,SAAO,CAAC,GAAG,IAAI,QAAQ,CAAC,CACrB,QAAQ,UAAU,MAAM,SAAS,QAAQ,CACzC,KAAK,UAAU,MAAM,MAAM;;;;;;;;CAShC,WAAW,IAAoB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mBAAc;AACd;;AAEF,QAAI,CAAC,OAAO;AACV,mBAAc;AACd;;IAEF,MAAM,EAAE,cAAc,gBAAgB,WAAW,MAAM;AACvD,WAAO,QAAQ,OAAO;KACpB,GAAG,GAAG,aAAa,GAAG,eAAe,GAAG;KACxC,GAAI,MAAM,SAAS,SAAY,EAAE,GAAG,EAAE,GAAG,MAAM,MAAM;KACrD,GAAI,OAAO,KAAK,MAAM,SAAS,CAAC,SAAS,EAAE,GAAG,MAAM,UAAU,GAAG,EAAE;KACpE;;GAEH,MAAM,QAAQ,cACV,MAAMD,+CAAwB,KAAK,MAAM,GACzCE,2CAAqB,OAAO;AAChC,QAAK,SAAS,KAAK;IAAE;IAAO,UAAU;IAAG,CAAC;WACnC,OAAO;AAGd,QAAK,MAAM,OAAO,aAAc,MAAK,KAAK,IAAI,IAAI;AAClD,SAAM;;;CAIV,UAAgB;AACd,OAAK,aAAa;AAClB,MAAK,KAAK,MAA0B,gBAAgB,KAClD,QAAQ,KAAK,MAA0B;;;;AAM7C,eAAsB,qBACpB,OACA,UACA,OACqB;CACrB,MAAM,UAAW,MAA0B;AAC3C,QAAO,UAAU,QAAQ,QAAQ,UAAU,MAAM,GAAG,MAAM,OAAO"}
1
+ {"version":3,"file":"flock-persistence-journal.cjs","names":["arr: JsonValue[]","obj: JsonObject","patch: JsonObject","flock: Flock","onDirty: () => void","result: T","outcome: Awaited<T>","payload","exportFlockFileSnapshot","bundle: ExportBundle","encodeMetaJsonUpdate"],"sources":["../src/internal/resource-ownership.ts","../src/utils.ts","../src/internal/flock-persistence-journal.ts"],"sourcesContent":["/**\n * Ownership and identity bookkeeping for one class of repository-managed\n * replicas (Loro documents, or named Flock documents).\n *\n * The invariant this exists to hold: **one resource id has at most one live\n * repository-managed replica at a time**. Without it, `unloadDoc()` could\n * evict the cached instance while a live transport room still held it, and\n * the next open would materialize a *second* replica — the caller editing one\n * copy while the room synchronized the other, with neither converging.\n *\n * Two pieces of state per id:\n *\n * - **owners** — every consumer currently holding the instance. Owners split\n * into two roles, because they need different eviction behaviour:\n * - `\"lease\"` owners are explicit `acquire*()` callers. They *block*\n * eviction: the caller promised to `release()`, so evicting under them\n * would hand them a replica the repository no longer tracks.\n * - `\"room\"` owners are live transport rooms. They do *not* block eviction,\n * because the repository can detach and rebind them itself — that\n * detach → evict → invalidate → reattach sequence is precisely what keeps\n * unload from forking the replica.\n * - **generation** — bumped whenever the instance backing an id is dropped.\n * Anything still referring to an older generation is stale by definition,\n * which lets rooms detect that they must rebind rather than keep\n * synchronizing a replica the repository no longer considers current.\n */\nexport type ResourceOwnerRole = \"lease\" | \"room\";\n\ninterface OwnerRecord {\n readonly role: ResourceOwnerRole;\n readonly label: string;\n}\n\nexport class ResourceOwnership {\n private readonly owners = new Map<string, Map<symbol, OwnerRecord>>();\n private readonly generations = new Map<string, number>();\n /**\n * Ids currently being evicted, with a count of overlapping evictions. New\n * leases are refused while an id is here, which closes the window between a\n * purge's pre-flight check and its destructive steps: `forgetFlockDoc`\n * deletes the durable remote cursor before the final check runs, so a lease\n * taken in between would fail the purge only *after* that cursor was\n * already gone. Counted rather than a set so one purge finishing cannot\n * drop the fence a concurrent purge of the same id still relies on.\n */\n private readonly evicting = new Map<string, number>();\n\n /** Current generation for `id`. Ids never dropped are generation 0. */\n generation(id: string): number {\n return this.generations.get(id) ?? 0;\n }\n\n /** Total live owners of `id`, in both roles. */\n ownerCount(id: string): number {\n return this.owners.get(id)?.size ?? 0;\n }\n\n /**\n * Registers one owner of `id` and returns its release callback. The token\n * is per-acquisition, so releasing twice only decrements once and one\n * owner's release cannot cancel another's.\n */\n acquire(id: string, role: ResourceOwnerRole, label: string): () => void {\n if (role === \"lease\" && this.evicting.has(id)) {\n throw new ResourceBusyError(\n \"resource\",\n id,\n [\"eviction in progress\"],\n `Cannot acquire resource \"${id}\": it is currently being evicted ` +\n `(unload or purge in progress). Retry after the eviction settles.`,\n );\n }\n const token = Symbol(label);\n let map = this.owners.get(id);\n if (!map) {\n map = new Map();\n this.owners.set(id, map);\n }\n map.set(token, { role, label });\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = this.owners.get(id);\n if (!current) return;\n current.delete(token);\n if (current.size === 0) this.owners.delete(id);\n };\n }\n\n /**\n * Labels of the owners that block eviction (explicit leases), for error\n * messages that need to tell a caller *why* an unload or purge was refused.\n * Live rooms are deliberately excluded: the repository detaches those\n * itself rather than failing the call.\n */\n blockingOwners(id: string): string[] {\n const map = this.owners.get(id);\n if (!map) return [];\n return [...map.values()]\n .filter((owner) => owner.role === \"lease\")\n .map((owner) => owner.label);\n }\n\n /**\n * Invalidates the instance currently bound to `id`: bumps the generation so\n * holders of the previous one can tell that the replica they reference is\n * no longer the repository's current replica. Called when the instance\n * backing an id is dropped (unload, purge) — never on ordinary edits.\n */\n invalidate(id: string): number {\n const next = this.generation(id) + 1;\n this.generations.set(id, next);\n return next;\n }\n\n /**\n * Marks `id` as being evicted, refusing new leases until the returned\n * callback runs. Call it in a `finally`.\n */\n beginEviction(id: string): () => void {\n this.evicting.set(id, (this.evicting.get(id) ?? 0) + 1);\n let ended = false;\n return () => {\n if (ended) return;\n ended = true;\n const count = this.evicting.get(id);\n if (count === undefined) return;\n if (count <= 1) {\n this.evicting.delete(id);\n } else {\n this.evicting.set(id, count - 1);\n }\n };\n }\n\n clear(): void {\n this.owners.clear();\n this.generations.clear();\n this.evicting.clear();\n }\n}\n\n/**\n * Raised when an unload or purge would evict a replica that an explicit lease\n * still holds. Carrying the owner labels makes the failure actionable — the\n * usual cause is an `acquire*()` the caller forgot to `release()`.\n */\nexport class ResourceBusyError extends Error {\n readonly resourceId: string;\n readonly owners: ReadonlyArray<string>;\n\n constructor(\n kind: string,\n resourceId: string,\n owners: ReadonlyArray<string>,\n message?: string,\n ) {\n super(\n message ??\n `Cannot evict ${kind} \"${resourceId}\": ${owners.length} active ` +\n `lease(s) still hold it (${owners.join(\", \")}). Release them ` +\n `first, or pass { force: true } to evict anyway and invalidate ` +\n `the replica.`,\n );\n this.name = \"ResourceBusyError\";\n this.resourceId = resourceId;\n this.owners = owners;\n }\n}\n\n/**\n * Raised when a durability barrier is asked to persist a replica the\n * repository has already replaced.\n *\n * Surfacing this rather than returning quietly is what keeps a remote cursor\n * from advancing past state nothing wrote: the barrier fails, so the cursor\n * save fails with it.\n */\nexport class StaleReplicaError extends Error {\n readonly resourceId: string;\n\n constructor(kind: string, resourceId: string) {\n super(\n `Cannot persist ${kind} \"${resourceId}\": the repository has replaced ` +\n `this replica, so the state held here is no longer the one it tracks.`,\n );\n this.name = \"StaleReplicaError\";\n this.resourceId = resourceId;\n }\n}\n","import type {\n JsonObject,\n JsonValue,\n ListDocQuery,\n} from \"./types\";\n\n/**\n * Throws an AbortError if the signal is aborted.\n * Use this to check for cancellation at safe points in long-running operations.\n */\nexport function throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n const error = new Error(\"Operation was aborted\");\n error.name = \"AbortError\";\n throw error;\n }\n}\n\nexport function cloneJsonValue(value: unknown): JsonValue | undefined {\n if (value === null) return null;\n if (typeof value === \"string\" || typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined;\n }\n if (Array.isArray(value)) {\n const arr: JsonValue[] = [];\n for (const entry of value) {\n const cloned = cloneJsonValue(entry);\n if (cloned !== undefined) {\n arr.push(cloned);\n }\n }\n return arr;\n }\n if (value && typeof value === \"object\") {\n const input = value as Record<string, unknown>;\n const obj: JsonObject = {};\n for (const [key, entry] of Object.entries(input)) {\n const cloned = cloneJsonValue(entry);\n if (cloned !== undefined) {\n obj[key] = cloned;\n }\n }\n return obj;\n }\n return undefined;\n}\n\nexport function cloneJsonObject(value: JsonObject): JsonObject {\n const cloned = cloneJsonValue(value);\n if (cloned && typeof cloned === \"object\" && !Array.isArray(cloned)) {\n return cloned;\n }\n return {};\n}\n\nexport function asJsonObject(value: unknown): JsonObject | undefined {\n const cloned = cloneJsonValue(value);\n if (cloned && typeof cloned === \"object\" && !Array.isArray(cloned)) {\n return cloned;\n }\n return undefined;\n}\n\nexport function jsonEquals(a?: JsonValue, b?: JsonValue): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n if (a === null || b === null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return a === b;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a)) {\n const bArr = b as JsonValue[];\n if (a.length !== bArr.length) return false;\n return a.every((v, i) => jsonEquals(v, bArr[i]));\n }\n const aObj = a as JsonObject;\n const bObj = b as JsonObject;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every((k) => jsonEquals(aObj[k], bObj[k]));\n}\n\nexport function diffJsonObjects(\n previous: JsonObject | undefined,\n next: JsonObject,\n): JsonObject {\n const patch: JsonObject = {};\n const keys = new Set<string>();\n if (previous) {\n for (const key of Object.keys(previous)) keys.add(key);\n }\n for (const key of Object.keys(next)) keys.add(key);\n for (const key of keys) {\n const prevValue = previous ? previous[key] : undefined;\n const nextValue = next[key];\n if (!jsonEquals(prevValue, nextValue)) {\n if (nextValue === undefined && previous && key in previous) {\n patch[key] = null;\n continue;\n }\n const cloned = cloneJsonValue(nextValue);\n if (cloned !== undefined) {\n patch[key] = cloned;\n }\n }\n }\n return patch;\n}\n\nexport function matchesQuery(\n docId: string,\n _metadata: JsonObject,\n query?: ListDocQuery,\n): boolean {\n if (!query) return true;\n if (query.prefix && !docId.startsWith(query.prefix)) return false;\n if (query.start && docId < query.start) return false;\n if (query.end && docId > query.end) return false;\n return true;\n}\n","import type {\n ExportBundle,\n Flock,\n KeyPart,\n VersionVector,\n} from \"@loro-dev/flock-wasm\";\nimport { encodeMetaJsonUpdate } from \"../storage/meta-snapshot\";\nimport { exportFlockFileSnapshot } from \"./flock-snapshot\";\n\n// The repo and transport are separate package entry points (and may use\n// different ESM/CJS module instances). Attach the journal to the replica,\n// rather than relying on a module-local WeakMap shared by both entry points.\nconst journalKey = Symbol.for(\"loro-repo.flock-persistence-journal.v1\");\ntype JournalledFlock = Flock & { [journalKey]?: FlockPersistenceJournal };\n\ninterface PendingPayload {\n readonly bytes: Uint8Array;\n failures: number;\n}\n\nconst MAX_EXACT_PAYLOAD_SAVE_ATTEMPTS = 3;\n\n/**\n * Persists `updates` in order. Reports how many leading updates are durable\n * and, if not all of them are, the failure. It must not reject.\n */\nexport type JournalWrite = (\n updates: readonly Uint8Array[],\n) => Promise<{ readonly durable: number; readonly error?: unknown }>;\n\nfunction versionsEqual(left: VersionVector, right: VersionVector): boolean {\n const leftPeers = Object.keys(left);\n const rightPeers = Object.keys(right);\n if (leftPeers.length !== rightPeers.length) return false;\n return leftPeers.every((peer) => {\n const a = left[peer];\n const b = right[peer];\n return (\n a?.physicalTime === b?.physicalTime &&\n a?.logicalCounter === b?.logicalCounter\n );\n });\n}\n\n/** Pending exact records and received payloads, acknowledged only after save. */\nexport class FlockPersistenceJournal {\n private readonly keys = new Set<string>();\n private readonly payloads: PendingPayload[] = [];\n private readonly unsubscribe: () => void;\n private remoteKeys?: Set<string>;\n /**\n * An inclusive version vector observed with no Flock event since. Exporting\n * a version vector from wasm costs time proportional to the number of\n * peers, and Streams delivers many batches that change nothing (echoes of\n * our own appends, replayed catch-ups). Reusing the vector read after the\n * previous import keeps such a batch to a single read.\n */\n private knownVersion?: VersionVector;\n\n constructor(\n private readonly flock: Flock,\n private readonly onDirty: () => void,\n ) {\n (flock as JournalledFlock)[journalKey] = this;\n this.unsubscribe = flock.subscribe((batch) => {\n // Local commits can be emitted by beforeImport(), even inside a remote\n // import. They must survive alongside the received payload.\n const keys =\n batch.source !== \"local\" && this.remoteKeys ? this.remoteKeys : this.keys;\n for (const event of batch.events) {\n keys.add(JSON.stringify(event.key));\n }\n if (batch.events.length) this.knownVersion = undefined;\n if (keys === this.keys && batch.events.length) this.onDirty();\n });\n }\n\n /**\n * Applies changes that are already durable at their owner: the replica\n * records no payload or key for them.\n */\n absorb<T>(apply: () => T): T {\n const previousKeys = this.remoteKeys;\n this.remoteKeys = new Set<string>();\n try {\n return apply();\n } finally {\n this.remoteKeys = previousKeys;\n }\n }\n\n get hasPending(): boolean {\n return this.keys.size > 0 || this.payloads.length > 0;\n }\n\n async receive<T>(\n payloads: readonly Uint8Array[],\n apply: () => T,\n ): Promise<Awaited<T>> {\n const copies = payloads\n .filter((bytes) => bytes.length > 0)\n .map((bytes) => bytes.slice());\n // Existing Flock adapter imports are synchronous. Only suppress their\n // synchronous remote events; unrelated work after an await is observable.\n let result: T;\n const previousKeys = this.remoteKeys;\n const remoteKeys = new Set<string>();\n // The inclusive vector only grows during the process lifetime, so a\n // cached vector that is stale because of an untracked import can only\n // cause a redundant save, never a skipped one.\n const previousVersion = this.knownVersion ?? this.flock.inclusiveVersion();\n this.remoteKeys = remoteKeys;\n try {\n result = apply();\n } catch (error) {\n // A batch import can partially succeed before throwing. Retain its\n // accepted records without persisting a possibly malformed payload.\n this.retainChangedKeys(remoteKeys);\n throw error;\n } finally {\n this.remoteKeys = previousKeys;\n }\n let outcome: Awaited<T>;\n try {\n outcome = await result;\n } catch (error) {\n this.retainChangedKeys(remoteKeys);\n throw error;\n }\n // Streams can echo an append back to its producer, and a bootstrap can\n // repeat state already hydrated locally. Flock emits no remote events in\n // either case, so there is no newly accepted state to journal. A genuine\n // same-VV hole does emit the missing key and still records the exact\n // received bytes. An import can also advance the version without\n // emitting events (an entry that loses last-writer-wins), so compare.\n if (remoteKeys.size > 0 || !this.versionUnchangedSince(previousVersion)) {\n this.payloads.push(...copies.map((bytes) => ({ bytes, failures: 0 })));\n if (copies.length) this.onDirty();\n }\n return outcome;\n }\n\n private versionUnchangedSince(previous: VersionVector): boolean {\n const current = this.flock.inclusiveVersion();\n this.knownVersion = current;\n return versionsEqual(previous, current);\n }\n\n private retainChangedKeys(keys: ReadonlySet<string>): void {\n for (const key of keys) this.keys.add(key);\n if (keys.size) this.onDirty();\n }\n\n /**\n * Called within the owner's serialized persistence queue.\n *\n * Each round hands every pending payload to `write` at once, so a storage\n * adapter can commit them in one transaction. Only the prefix `write`\n * reports durable is acknowledged.\n */\n async flush(write: JournalWrite): Promise<void> {\n this.flock.commit();\n while (this.hasPending) {\n if (this.keys.size) {\n await this.stageChangedKeys();\n }\n\n const { durable, error: exactError } = await write(\n this.payloads.map((payload) => payload.bytes),\n );\n // Only this loop removes payloads, so the written ones are still the\n // queue's prefix. New imports/local changes during the write remain\n // behind them.\n this.payloads.splice(0, durable);\n if (exactError === undefined) continue;\n\n const payload = this.payloads[0]!;\n payload.failures += 1;\n // One failing barrier must still block its remote cursor. Repeated\n // barriers retry the exact bytes up to a bounded count before using\n // the mergeable full-state fallback below.\n if (payload.failures < MAX_EXACT_PAYLOAD_SAVE_ATTEMPTS) {\n throw exactError;\n }\n // A storage adapter can reject one otherwise accepted encoding\n // forever. A full file is another mergeable representation of the\n // current CRDT state, so it can safely cover that queue item. Never\n // advance past the item unless this fallback itself is durable.\n // The exported file covers every payload that was queued when the\n // export began, not just the failing head. Payloads received while\n // the incremental export or save awaits are appended after this\n // boundary and must remain pending.\n const coveredPayloads = this.payloads.length;\n const snapshot = await exportFlockFileSnapshot(this.flock);\n const fallback = await write([snapshot]);\n if (fallback.error !== undefined) {\n throw new AggregateError(\n [exactError, fallback.error],\n \"Failed to persist a Flock update and its snapshot fallback\",\n );\n }\n this.payloads.splice(0, coveredPayloads);\n }\n }\n\n private async stageChangedKeys(): Promise<void> {\n const capturedKeys = [...this.keys];\n for (const key of capturedKeys) this.keys.delete(key);\n try {\n const bundle: ExportBundle = { version: 0, entries: {} };\n let useSnapshot = false;\n for (const key of capturedKeys) {\n let entry;\n try {\n entry = this.flock.getEntry(JSON.parse(key) as KeyPart[]);\n } catch {\n useSnapshot = true;\n break;\n }\n if (!entry) {\n useSnapshot = true;\n break;\n }\n const { physicalTime, logicalCounter, peerId } = entry.clock;\n bundle.entries[key] = {\n c: `${physicalTime},${logicalCounter},${peerId}`,\n ...(entry.data === undefined ? {} : { d: entry.data }),\n ...(Object.keys(entry.metadata).length ? { m: entry.metadata } : {}),\n };\n }\n const bytes = useSnapshot\n ? await exportFlockFileSnapshot(this.flock)\n : encodeMetaJsonUpdate(bundle);\n this.payloads.push({ bytes, failures: 0 });\n } catch (error) {\n // The current state has not been represented in the payload queue.\n // Restore the captured markers without disturbing newer events.\n for (const key of capturedKeys) this.keys.add(key);\n throw error;\n }\n }\n\n destroy(): void {\n this.unsubscribe();\n if ((this.flock as JournalledFlock)[journalKey] === this) {\n delete (this.flock as JournalledFlock)[journalKey];\n }\n }\n}\n\n/** Preserve plaintext CRDT bytes at the public Streams adapter boundary. */\nexport async function receiveFlockPayloads<T>(\n flock: Flock,\n payloads: readonly Uint8Array[],\n apply: () => T,\n): Promise<Awaited<T>> {\n const journal = (flock as JournalledFlock)[journalKey];\n return journal ? journal.receive(payloads, apply) : await apply();\n}\n"],"mappings":";;;;AAiCA,IAAa,oBAAb,MAA+B;CAC7B,AAAiB,yBAAS,IAAI,KAAuC;CACrE,AAAiB,8BAAc,IAAI,KAAqB;;;;;;;;;;CAUxD,AAAiB,2BAAW,IAAI,KAAqB;;CAGrD,WAAW,IAAoB;AAC7B,SAAO,KAAK,YAAY,IAAI,GAAG,IAAI;;;CAIrC,WAAW,IAAoB;AAC7B,SAAO,KAAK,OAAO,IAAI,GAAG,EAAE,QAAQ;;;;;;;CAQtC,QAAQ,IAAY,MAAyB,OAA2B;AACtE,MAAI,SAAS,WAAW,KAAK,SAAS,IAAI,GAAG,CAC3C,OAAM,IAAI,kBACR,YACA,IACA,CAAC,uBAAuB,EACxB,4BAA4B,GAAG,mGAEhC;EAEH,MAAM,QAAQ,OAAO,MAAM;EAC3B,IAAI,MAAM,KAAK,OAAO,IAAI,GAAG;AAC7B,MAAI,CAAC,KAAK;AACR,yBAAM,IAAI,KAAK;AACf,QAAK,OAAO,IAAI,IAAI,IAAI;;AAE1B,MAAI,IAAI,OAAO;GAAE;GAAM;GAAO,CAAC;EAC/B,IA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,OACqB;CACrB,MAAM,UAAW,MAA0B;AAC3C,QAAO,UAAU,QAAQ,QAAQ,UAAU,MAAM,GAAG,MAAM,OAAO"}
@@ -255,6 +255,19 @@ var FlockPersistenceJournal = class {
255
255
  if (keys === this.keys && batch.events.length) this.onDirty();
256
256
  });
257
257
  }
258
+ /**
259
+ * Applies changes that are already durable at their owner: the replica
260
+ * records no payload or key for them.
261
+ */
262
+ absorb(apply) {
263
+ const previousKeys = this.remoteKeys;
264
+ this.remoteKeys = /* @__PURE__ */ new Set();
265
+ try {
266
+ return apply();
267
+ } finally {
268
+ this.remoteKeys = previousKeys;
269
+ }
270
+ }
258
271
  get hasPending() {
259
272
  return this.keys.size > 0 || this.payloads.length > 0;
260
273
  }
@@ -1 +1 @@
1
- {"version":3,"file":"flock-persistence-journal.js","names":["arr: JsonValue[]","obj: JsonObject","patch: JsonObject","flock: Flock","onDirty: () => void","result: T","outcome: Awaited<T>","payload","bundle: ExportBundle"],"sources":["../src/internal/resource-ownership.ts","../src/utils.ts","../src/internal/flock-persistence-journal.ts"],"sourcesContent":["/**\n * Ownership and identity bookkeeping for one class of repository-managed\n * replicas (Loro documents, or named Flock documents).\n *\n * The invariant this exists to hold: **one resource id has at most one live\n * repository-managed replica at a time**. Without it, `unloadDoc()` could\n * evict the cached instance while a live transport room still held it, and\n * the next open would materialize a *second* replica — the caller editing one\n * copy while the room synchronized the other, with neither converging.\n *\n * Two pieces of state per id:\n *\n * - **owners** — every consumer currently holding the instance. Owners split\n * into two roles, because they need different eviction behaviour:\n * - `\"lease\"` owners are explicit `acquire*()` callers. They *block*\n * eviction: the caller promised to `release()`, so evicting under them\n * would hand them a replica the repository no longer tracks.\n * - `\"room\"` owners are live transport rooms. They do *not* block eviction,\n * because the repository can detach and rebind them itself — that\n * detach → evict → invalidate → reattach sequence is precisely what keeps\n * unload from forking the replica.\n * - **generation** — bumped whenever the instance backing an id is dropped.\n * Anything still referring to an older generation is stale by definition,\n * which lets rooms detect that they must rebind rather than keep\n * synchronizing a replica the repository no longer considers current.\n */\nexport type ResourceOwnerRole = \"lease\" | \"room\";\n\ninterface OwnerRecord {\n readonly role: ResourceOwnerRole;\n readonly label: string;\n}\n\nexport class ResourceOwnership {\n private readonly owners = new Map<string, Map<symbol, OwnerRecord>>();\n private readonly generations = new Map<string, number>();\n /**\n * Ids currently being evicted, with a count of overlapping evictions. New\n * leases are refused while an id is here, which closes the window between a\n * purge's pre-flight check and its destructive steps: `forgetFlockDoc`\n * deletes the durable remote cursor before the final check runs, so a lease\n * taken in between would fail the purge only *after* that cursor was\n * already gone. Counted rather than a set so one purge finishing cannot\n * drop the fence a concurrent purge of the same id still relies on.\n */\n private readonly evicting = new Map<string, number>();\n\n /** Current generation for `id`. Ids never dropped are generation 0. */\n generation(id: string): number {\n return this.generations.get(id) ?? 0;\n }\n\n /** Total live owners of `id`, in both roles. */\n ownerCount(id: string): number {\n return this.owners.get(id)?.size ?? 0;\n }\n\n /**\n * Registers one owner of `id` and returns its release callback. The token\n * is per-acquisition, so releasing twice only decrements once and one\n * owner's release cannot cancel another's.\n */\n acquire(id: string, role: ResourceOwnerRole, label: string): () => void {\n if (role === \"lease\" && this.evicting.has(id)) {\n throw new ResourceBusyError(\n \"resource\",\n id,\n [\"eviction in progress\"],\n `Cannot acquire resource \"${id}\": it is currently being evicted ` +\n `(unload or purge in progress). Retry after the eviction settles.`,\n );\n }\n const token = Symbol(label);\n let map = this.owners.get(id);\n if (!map) {\n map = new Map();\n this.owners.set(id, map);\n }\n map.set(token, { role, label });\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = this.owners.get(id);\n if (!current) return;\n current.delete(token);\n if (current.size === 0) this.owners.delete(id);\n };\n }\n\n /**\n * Labels of the owners that block eviction (explicit leases), for error\n * messages that need to tell a caller *why* an unload or purge was refused.\n * Live rooms are deliberately excluded: the repository detaches those\n * itself rather than failing the call.\n */\n blockingOwners(id: string): string[] {\n const map = this.owners.get(id);\n if (!map) return [];\n return [...map.values()]\n .filter((owner) => owner.role === \"lease\")\n .map((owner) => owner.label);\n }\n\n /**\n * Invalidates the instance currently bound to `id`: bumps the generation so\n * holders of the previous one can tell that the replica they reference is\n * no longer the repository's current replica. Called when the instance\n * backing an id is dropped (unload, purge) — never on ordinary edits.\n */\n invalidate(id: string): number {\n const next = this.generation(id) + 1;\n this.generations.set(id, next);\n return next;\n }\n\n /**\n * Marks `id` as being evicted, refusing new leases until the returned\n * callback runs. Call it in a `finally`.\n */\n beginEviction(id: string): () => void {\n this.evicting.set(id, (this.evicting.get(id) ?? 0) + 1);\n let ended = false;\n return () => {\n if (ended) return;\n ended = true;\n const count = this.evicting.get(id);\n if (count === undefined) return;\n if (count <= 1) {\n this.evicting.delete(id);\n } else {\n this.evicting.set(id, count - 1);\n }\n };\n }\n\n clear(): void {\n this.owners.clear();\n this.generations.clear();\n this.evicting.clear();\n }\n}\n\n/**\n * Raised when an unload or purge would evict a replica that an explicit lease\n * still holds. Carrying the owner labels makes the failure actionable — the\n * usual cause is an `acquire*()` the caller forgot to `release()`.\n */\nexport class ResourceBusyError extends Error {\n readonly resourceId: string;\n readonly owners: ReadonlyArray<string>;\n\n constructor(\n kind: string,\n resourceId: string,\n owners: ReadonlyArray<string>,\n message?: string,\n ) {\n super(\n message ??\n `Cannot evict ${kind} \"${resourceId}\": ${owners.length} active ` +\n `lease(s) still hold it (${owners.join(\", \")}). Release them ` +\n `first, or pass { force: true } to evict anyway and invalidate ` +\n `the replica.`,\n );\n this.name = \"ResourceBusyError\";\n this.resourceId = resourceId;\n this.owners = owners;\n }\n}\n\n/**\n * Raised when a durability barrier is asked to persist a replica the\n * repository has already replaced.\n *\n * Surfacing this rather than returning quietly is what keeps a remote cursor\n * from advancing past state nothing wrote: the barrier fails, so the cursor\n * save fails with it.\n */\nexport class StaleReplicaError extends Error {\n readonly resourceId: string;\n\n constructor(kind: string, resourceId: string) {\n super(\n `Cannot persist ${kind} \"${resourceId}\": the repository has replaced ` +\n `this replica, so the state held here is no longer the one it tracks.`,\n );\n this.name = \"StaleReplicaError\";\n this.resourceId = resourceId;\n }\n}\n","import type {\n JsonObject,\n JsonValue,\n ListDocQuery,\n} from \"./types\";\n\n/**\n * Throws an AbortError if the signal is aborted.\n * Use this to check for cancellation at safe points in long-running operations.\n */\nexport function throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n const error = new Error(\"Operation was aborted\");\n error.name = \"AbortError\";\n throw error;\n }\n}\n\nexport function cloneJsonValue(value: unknown): JsonValue | undefined {\n if (value === null) return null;\n if (typeof value === \"string\" || typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined;\n }\n if (Array.isArray(value)) {\n const arr: JsonValue[] = [];\n for (const entry of value) {\n const cloned = cloneJsonValue(entry);\n if (cloned !== undefined) {\n arr.push(cloned);\n }\n }\n return arr;\n }\n if (value && typeof value === \"object\") {\n const input = value as Record<string, unknown>;\n const obj: JsonObject = {};\n for (const [key, entry] of Object.entries(input)) {\n const cloned = cloneJsonValue(entry);\n if (cloned !== undefined) {\n obj[key] = cloned;\n }\n }\n return obj;\n }\n return undefined;\n}\n\nexport function cloneJsonObject(value: JsonObject): JsonObject {\n const cloned = cloneJsonValue(value);\n if (cloned && typeof cloned === \"object\" && !Array.isArray(cloned)) {\n return cloned;\n }\n return {};\n}\n\nexport function asJsonObject(value: unknown): JsonObject | undefined {\n const cloned = cloneJsonValue(value);\n if (cloned && typeof cloned === \"object\" && !Array.isArray(cloned)) {\n return cloned;\n }\n return undefined;\n}\n\nexport function jsonEquals(a?: JsonValue, b?: JsonValue): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n if (a === null || b === null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return a === b;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a)) {\n const bArr = b as JsonValue[];\n if (a.length !== bArr.length) return false;\n return a.every((v, i) => jsonEquals(v, bArr[i]));\n }\n const aObj = a as JsonObject;\n const bObj = b as JsonObject;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every((k) => jsonEquals(aObj[k], bObj[k]));\n}\n\nexport function diffJsonObjects(\n previous: JsonObject | undefined,\n next: JsonObject,\n): JsonObject {\n const patch: JsonObject = {};\n const keys = new Set<string>();\n if (previous) {\n for (const key of Object.keys(previous)) keys.add(key);\n }\n for (const key of Object.keys(next)) keys.add(key);\n for (const key of keys) {\n const prevValue = previous ? previous[key] : undefined;\n const nextValue = next[key];\n if (!jsonEquals(prevValue, nextValue)) {\n if (nextValue === undefined && previous && key in previous) {\n patch[key] = null;\n continue;\n }\n const cloned = cloneJsonValue(nextValue);\n if (cloned !== undefined) {\n patch[key] = cloned;\n }\n }\n }\n return patch;\n}\n\nexport function matchesQuery(\n docId: string,\n _metadata: JsonObject,\n query?: ListDocQuery,\n): boolean {\n if (!query) return true;\n if (query.prefix && !docId.startsWith(query.prefix)) return false;\n if (query.start && docId < query.start) return false;\n if (query.end && docId > query.end) return false;\n return true;\n}\n","import type {\n ExportBundle,\n Flock,\n KeyPart,\n VersionVector,\n} from \"@loro-dev/flock-wasm\";\nimport { encodeMetaJsonUpdate } from \"../storage/meta-snapshot\";\nimport { exportFlockFileSnapshot } from \"./flock-snapshot\";\n\n// The repo and transport are separate package entry points (and may use\n// different ESM/CJS module instances). Attach the journal to the replica,\n// rather than relying on a module-local WeakMap shared by both entry points.\nconst journalKey = Symbol.for(\"loro-repo.flock-persistence-journal.v1\");\ntype JournalledFlock = Flock & { [journalKey]?: FlockPersistenceJournal };\n\ninterface PendingPayload {\n readonly bytes: Uint8Array;\n failures: number;\n}\n\nconst MAX_EXACT_PAYLOAD_SAVE_ATTEMPTS = 3;\n\n/**\n * Persists `updates` in order. Reports how many leading updates are durable\n * and, if not all of them are, the failure. It must not reject.\n */\nexport type JournalWrite = (\n updates: readonly Uint8Array[],\n) => Promise<{ readonly durable: number; readonly error?: unknown }>;\n\nfunction versionsEqual(left: VersionVector, right: VersionVector): boolean {\n const leftPeers = Object.keys(left);\n const rightPeers = Object.keys(right);\n if (leftPeers.length !== rightPeers.length) return false;\n return leftPeers.every((peer) => {\n const a = left[peer];\n const b = right[peer];\n return (\n a?.physicalTime === b?.physicalTime &&\n a?.logicalCounter === b?.logicalCounter\n );\n });\n}\n\n/** Pending exact records and received payloads, acknowledged only after save. */\nexport class FlockPersistenceJournal {\n private readonly keys = new Set<string>();\n private readonly payloads: PendingPayload[] = [];\n private readonly unsubscribe: () => void;\n private remoteKeys?: Set<string>;\n /**\n * An inclusive version vector observed with no Flock event since. Exporting\n * a version vector from wasm costs time proportional to the number of\n * peers, and Streams delivers many batches that change nothing (echoes of\n * our own appends, replayed catch-ups). Reusing the vector read after the\n * previous import keeps such a batch to a single read.\n */\n private knownVersion?: VersionVector;\n\n constructor(\n private readonly flock: Flock,\n private readonly onDirty: () => void,\n ) {\n (flock as JournalledFlock)[journalKey] = this;\n this.unsubscribe = flock.subscribe((batch) => {\n // Local commits can be emitted by beforeImport(), even inside a remote\n // import. They must survive alongside the received payload.\n const keys =\n batch.source !== \"local\" && this.remoteKeys ? this.remoteKeys : this.keys;\n for (const event of batch.events) {\n keys.add(JSON.stringify(event.key));\n }\n if (batch.events.length) this.knownVersion = undefined;\n if (keys === this.keys && batch.events.length) this.onDirty();\n });\n }\n\n get hasPending(): boolean {\n return this.keys.size > 0 || this.payloads.length > 0;\n }\n\n async receive<T>(\n payloads: readonly Uint8Array[],\n apply: () => T,\n ): Promise<Awaited<T>> {\n const copies = payloads\n .filter((bytes) => bytes.length > 0)\n .map((bytes) => bytes.slice());\n // Existing Flock adapter imports are synchronous. Only suppress their\n // synchronous remote events; unrelated work after an await is observable.\n let result: T;\n const previousKeys = this.remoteKeys;\n const remoteKeys = new Set<string>();\n // The inclusive vector only grows during the process lifetime, so a\n // cached vector that is stale because of an untracked import can only\n // cause a redundant save, never a skipped one.\n const previousVersion = this.knownVersion ?? this.flock.inclusiveVersion();\n this.remoteKeys = remoteKeys;\n try {\n result = apply();\n } catch (error) {\n // A batch import can partially succeed before throwing. Retain its\n // accepted records without persisting a possibly malformed payload.\n this.retainChangedKeys(remoteKeys);\n throw error;\n } finally {\n this.remoteKeys = previousKeys;\n }\n let outcome: Awaited<T>;\n try {\n outcome = await result;\n } catch (error) {\n this.retainChangedKeys(remoteKeys);\n throw error;\n }\n // Streams can echo an append back to its producer, and a bootstrap can\n // repeat state already hydrated locally. Flock emits no remote events in\n // either case, so there is no newly accepted state to journal. A genuine\n // same-VV hole does emit the missing key and still records the exact\n // received bytes. An import can also advance the version without\n // emitting events (an entry that loses last-writer-wins), so compare.\n if (remoteKeys.size > 0 || !this.versionUnchangedSince(previousVersion)) {\n this.payloads.push(...copies.map((bytes) => ({ bytes, failures: 0 })));\n if (copies.length) this.onDirty();\n }\n return outcome;\n }\n\n private versionUnchangedSince(previous: VersionVector): boolean {\n const current = this.flock.inclusiveVersion();\n this.knownVersion = current;\n return versionsEqual(previous, current);\n }\n\n private retainChangedKeys(keys: ReadonlySet<string>): void {\n for (const key of keys) this.keys.add(key);\n if (keys.size) this.onDirty();\n }\n\n /**\n * Called within the owner's serialized persistence queue.\n *\n * Each round hands every pending payload to `write` at once, so a storage\n * adapter can commit them in one transaction. Only the prefix `write`\n * reports durable is acknowledged.\n */\n async flush(write: JournalWrite): Promise<void> {\n this.flock.commit();\n while (this.hasPending) {\n if (this.keys.size) {\n await this.stageChangedKeys();\n }\n\n const { durable, error: exactError } = await write(\n this.payloads.map((payload) => payload.bytes),\n );\n // Only this loop removes payloads, so the written ones are still the\n // queue's prefix. New imports/local changes during the write remain\n // behind them.\n this.payloads.splice(0, durable);\n if (exactError === undefined) continue;\n\n const payload = this.payloads[0]!;\n payload.failures += 1;\n // One failing barrier must still block its remote cursor. Repeated\n // barriers retry the exact bytes up to a bounded count before using\n // the mergeable full-state fallback below.\n if (payload.failures < MAX_EXACT_PAYLOAD_SAVE_ATTEMPTS) {\n throw exactError;\n }\n // A storage adapter can reject one otherwise accepted encoding\n // forever. A full file is another mergeable representation of the\n // current CRDT state, so it can safely cover that queue item. Never\n // advance past the item unless this fallback itself is durable.\n // The exported file covers every payload that was queued when the\n // export began, not just the failing head. Payloads received while\n // the incremental export or save awaits are appended after this\n // boundary and must remain pending.\n const coveredPayloads = this.payloads.length;\n const snapshot = await exportFlockFileSnapshot(this.flock);\n const fallback = await write([snapshot]);\n if (fallback.error !== undefined) {\n throw new AggregateError(\n [exactError, fallback.error],\n \"Failed to persist a Flock update and its snapshot fallback\",\n );\n }\n this.payloads.splice(0, coveredPayloads);\n }\n }\n\n private async stageChangedKeys(): Promise<void> {\n const capturedKeys = [...this.keys];\n for (const key of capturedKeys) this.keys.delete(key);\n try {\n const bundle: ExportBundle = { version: 0, entries: {} };\n let useSnapshot = false;\n for (const key of capturedKeys) {\n let entry;\n try {\n entry = this.flock.getEntry(JSON.parse(key) as KeyPart[]);\n } catch {\n useSnapshot = true;\n break;\n }\n if (!entry) {\n useSnapshot = true;\n break;\n }\n const { physicalTime, logicalCounter, peerId } = entry.clock;\n bundle.entries[key] = {\n c: `${physicalTime},${logicalCounter},${peerId}`,\n ...(entry.data === undefined ? {} : { d: entry.data }),\n ...(Object.keys(entry.metadata).length ? { m: entry.metadata } : {}),\n };\n }\n const bytes = useSnapshot\n ? await exportFlockFileSnapshot(this.flock)\n : encodeMetaJsonUpdate(bundle);\n this.payloads.push({ bytes, failures: 0 });\n } catch (error) {\n // The current state has not been represented in the payload queue.\n // Restore the captured markers without disturbing newer events.\n for (const key of capturedKeys) this.keys.add(key);\n throw error;\n }\n }\n\n destroy(): void {\n this.unsubscribe();\n if ((this.flock as JournalledFlock)[journalKey] === this) {\n delete (this.flock as JournalledFlock)[journalKey];\n }\n }\n}\n\n/** Preserve plaintext CRDT bytes at the public Streams adapter boundary. */\nexport async function receiveFlockPayloads<T>(\n flock: Flock,\n payloads: readonly Uint8Array[],\n apply: () => T,\n): Promise<Awaited<T>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AAc;AACd;;IAEF,MAAM,EAAE,cAAc,gBAAgB,WAAW,MAAM;AACvD,WAAO,QAAQ,OAAO;KACpB,GAAG,GAAG,aAAa,GAAG,eAAe,GAAG;KACxC,GAAI,MAAM,SAAS,SAAY,EAAE,GAAG,EAAE,GAAG,MAAM,MAAM;KACrD,GAAI,OAAO,KAAK,MAAM,SAAS,CAAC,SAAS,EAAE,GAAG,MAAM,UAAU,GAAG,EAAE;KACpE;;GAEH,MAAM,QAAQ,cACV,MAAM,wBAAwB,KAAK,MAAM,GACzC,qBAAqB,OAAO;AAChC,QAAK,SAAS,KAAK;IAAE;IAAO,UAAU;IAAG,CAAC;WACnC,OAAO;AAGd,QAAK,MAAM,OAAO,aAAc,MAAK,KAAK,IAAI,IAAI;AAClD,SAAM;;;CAIV,UAAgB;AACd,OAAK,aAAa;AAClB,MAAK,KAAK,MAA0B,gBAAgB,KAClD,QAAQ,KAAK,MAA0B;;;;AAM7C,eAAsB,qBACpB,OACA,UACA,OACqB;CACrB,MAAM,UAAW,MAA0B;AAC3C,QAAO,UAAU,QAAQ,QAAQ,UAAU,MAAM,GAAG,MAAM,OAAO"}
1
+ {"version":3,"file":"flock-persistence-journal.js","names":["arr: JsonValue[]","obj: JsonObject","patch: JsonObject","flock: Flock","onDirty: () => void","result: T","outcome: Awaited<T>","payload","bundle: ExportBundle"],"sources":["../src/internal/resource-ownership.ts","../src/utils.ts","../src/internal/flock-persistence-journal.ts"],"sourcesContent":["/**\n * Ownership and identity bookkeeping for one class of repository-managed\n * replicas (Loro documents, or named Flock documents).\n *\n * The invariant this exists to hold: **one resource id has at most one live\n * repository-managed replica at a time**. Without it, `unloadDoc()` could\n * evict the cached instance while a live transport room still held it, and\n * the next open would materialize a *second* replica — the caller editing one\n * copy while the room synchronized the other, with neither converging.\n *\n * Two pieces of state per id:\n *\n * - **owners** — every consumer currently holding the instance. Owners split\n * into two roles, because they need different eviction behaviour:\n * - `\"lease\"` owners are explicit `acquire*()` callers. They *block*\n * eviction: the caller promised to `release()`, so evicting under them\n * would hand them a replica the repository no longer tracks.\n * - `\"room\"` owners are live transport rooms. They do *not* block eviction,\n * because the repository can detach and rebind them itself — that\n * detach → evict → invalidate → reattach sequence is precisely what keeps\n * unload from forking the replica.\n * - **generation** — bumped whenever the instance backing an id is dropped.\n * Anything still referring to an older generation is stale by definition,\n * which lets rooms detect that they must rebind rather than keep\n * synchronizing a replica the repository no longer considers current.\n */\nexport type ResourceOwnerRole = \"lease\" | \"room\";\n\ninterface OwnerRecord {\n readonly role: ResourceOwnerRole;\n readonly label: string;\n}\n\nexport class ResourceOwnership {\n private readonly owners = new Map<string, Map<symbol, OwnerRecord>>();\n private readonly generations = new Map<string, number>();\n /**\n * Ids currently being evicted, with a count of overlapping evictions. New\n * leases are refused while an id is here, which closes the window between a\n * purge's pre-flight check and its destructive steps: `forgetFlockDoc`\n * deletes the durable remote cursor before the final check runs, so a lease\n * taken in between would fail the purge only *after* that cursor was\n * already gone. Counted rather than a set so one purge finishing cannot\n * drop the fence a concurrent purge of the same id still relies on.\n */\n private readonly evicting = new Map<string, number>();\n\n /** Current generation for `id`. Ids never dropped are generation 0. */\n generation(id: string): number {\n return this.generations.get(id) ?? 0;\n }\n\n /** Total live owners of `id`, in both roles. */\n ownerCount(id: string): number {\n return this.owners.get(id)?.size ?? 0;\n }\n\n /**\n * Registers one owner of `id` and returns its release callback. The token\n * is per-acquisition, so releasing twice only decrements once and one\n * owner's release cannot cancel another's.\n */\n acquire(id: string, role: ResourceOwnerRole, label: string): () => void {\n if (role === \"lease\" && this.evicting.has(id)) {\n throw new ResourceBusyError(\n \"resource\",\n id,\n [\"eviction in progress\"],\n `Cannot acquire resource \"${id}\": it is currently being evicted ` +\n `(unload or purge in progress). Retry after the eviction settles.`,\n );\n }\n const token = Symbol(label);\n let map = this.owners.get(id);\n if (!map) {\n map = new Map();\n this.owners.set(id, map);\n }\n map.set(token, { role, label });\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = this.owners.get(id);\n if (!current) return;\n current.delete(token);\n if (current.size === 0) this.owners.delete(id);\n };\n }\n\n /**\n * Labels of the owners that block eviction (explicit leases), for error\n * messages that need to tell a caller *why* an unload or purge was refused.\n * Live rooms are deliberately excluded: the repository detaches those\n * itself rather than failing the call.\n */\n blockingOwners(id: string): string[] {\n const map = this.owners.get(id);\n if (!map) return [];\n return [...map.values()]\n .filter((owner) => owner.role === \"lease\")\n .map((owner) => owner.label);\n }\n\n /**\n * Invalidates the instance currently bound to `id`: bumps the generation so\n * holders of the previous one can tell that the replica they reference is\n * no longer the repository's current replica. Called when the instance\n * backing an id is dropped (unload, purge) — never on ordinary edits.\n */\n invalidate(id: string): number {\n const next = this.generation(id) + 1;\n this.generations.set(id, next);\n return next;\n }\n\n /**\n * Marks `id` as being evicted, refusing new leases until the returned\n * callback runs. Call it in a `finally`.\n */\n beginEviction(id: string): () => void {\n this.evicting.set(id, (this.evicting.get(id) ?? 0) + 1);\n let ended = false;\n return () => {\n if (ended) return;\n ended = true;\n const count = this.evicting.get(id);\n if (count === undefined) return;\n if (count <= 1) {\n this.evicting.delete(id);\n } else {\n this.evicting.set(id, count - 1);\n }\n };\n }\n\n clear(): void {\n this.owners.clear();\n this.generations.clear();\n this.evicting.clear();\n }\n}\n\n/**\n * Raised when an unload or purge would evict a replica that an explicit lease\n * still holds. Carrying the owner labels makes the failure actionable — the\n * usual cause is an `acquire*()` the caller forgot to `release()`.\n */\nexport class ResourceBusyError extends Error {\n readonly resourceId: string;\n readonly owners: ReadonlyArray<string>;\n\n constructor(\n kind: string,\n resourceId: string,\n owners: ReadonlyArray<string>,\n message?: string,\n ) {\n super(\n message ??\n `Cannot evict ${kind} \"${resourceId}\": ${owners.length} active ` +\n `lease(s) still hold it (${owners.join(\", \")}). Release them ` +\n `first, or pass { force: true } to evict anyway and invalidate ` +\n `the replica.`,\n );\n this.name = \"ResourceBusyError\";\n this.resourceId = resourceId;\n this.owners = owners;\n }\n}\n\n/**\n * Raised when a durability barrier is asked to persist a replica the\n * repository has already replaced.\n *\n * Surfacing this rather than returning quietly is what keeps a remote cursor\n * from advancing past state nothing wrote: the barrier fails, so the cursor\n * save fails with it.\n */\nexport class StaleReplicaError extends Error {\n readonly resourceId: string;\n\n constructor(kind: string, resourceId: string) {\n super(\n `Cannot persist ${kind} \"${resourceId}\": the repository has replaced ` +\n `this replica, so the state held here is no longer the one it tracks.`,\n );\n this.name = \"StaleReplicaError\";\n this.resourceId = resourceId;\n }\n}\n","import type {\n JsonObject,\n JsonValue,\n ListDocQuery,\n} from \"./types\";\n\n/**\n * Throws an AbortError if the signal is aborted.\n * Use this to check for cancellation at safe points in long-running operations.\n */\nexport function throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n const error = new Error(\"Operation was aborted\");\n error.name = \"AbortError\";\n throw error;\n }\n}\n\nexport function cloneJsonValue(value: unknown): JsonValue | undefined {\n if (value === null) return null;\n if (typeof value === \"string\" || typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined;\n }\n if (Array.isArray(value)) {\n const arr: JsonValue[] = [];\n for (const entry of value) {\n const cloned = cloneJsonValue(entry);\n if (cloned !== undefined) {\n arr.push(cloned);\n }\n }\n return arr;\n }\n if (value && typeof value === \"object\") {\n const input = value as Record<string, unknown>;\n const obj: JsonObject = {};\n for (const [key, entry] of Object.entries(input)) {\n const cloned = cloneJsonValue(entry);\n if (cloned !== undefined) {\n obj[key] = cloned;\n }\n }\n return obj;\n }\n return undefined;\n}\n\nexport function cloneJsonObject(value: JsonObject): JsonObject {\n const cloned = cloneJsonValue(value);\n if (cloned && typeof cloned === \"object\" && !Array.isArray(cloned)) {\n return cloned;\n }\n return {};\n}\n\nexport function asJsonObject(value: unknown): JsonObject | undefined {\n const cloned = cloneJsonValue(value);\n if (cloned && typeof cloned === \"object\" && !Array.isArray(cloned)) {\n return cloned;\n }\n return undefined;\n}\n\nexport function jsonEquals(a?: JsonValue, b?: JsonValue): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n if (a === null || b === null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return a === b;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a)) {\n const bArr = b as JsonValue[];\n if (a.length !== bArr.length) return false;\n return a.every((v, i) => jsonEquals(v, bArr[i]));\n }\n const aObj = a as JsonObject;\n const bObj = b as JsonObject;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every((k) => jsonEquals(aObj[k], bObj[k]));\n}\n\nexport function diffJsonObjects(\n previous: JsonObject | undefined,\n next: JsonObject,\n): JsonObject {\n const patch: JsonObject = {};\n const keys = new Set<string>();\n if (previous) {\n for (const key of Object.keys(previous)) keys.add(key);\n }\n for (const key of Object.keys(next)) keys.add(key);\n for (const key of keys) {\n const prevValue = previous ? previous[key] : undefined;\n const nextValue = next[key];\n if (!jsonEquals(prevValue, nextValue)) {\n if (nextValue === undefined && previous && key in previous) {\n patch[key] = null;\n continue;\n }\n const cloned = cloneJsonValue(nextValue);\n if (cloned !== undefined) {\n patch[key] = cloned;\n }\n }\n }\n return patch;\n}\n\nexport function matchesQuery(\n docId: string,\n _metadata: JsonObject,\n query?: ListDocQuery,\n): boolean {\n if (!query) return true;\n if (query.prefix && !docId.startsWith(query.prefix)) return false;\n if (query.start && docId < query.start) return false;\n if (query.end && docId > query.end) return false;\n return true;\n}\n","import type {\n ExportBundle,\n Flock,\n KeyPart,\n VersionVector,\n} from \"@loro-dev/flock-wasm\";\nimport { encodeMetaJsonUpdate } from \"../storage/meta-snapshot\";\nimport { exportFlockFileSnapshot } from \"./flock-snapshot\";\n\n// The repo and transport are separate package entry points (and may use\n// different ESM/CJS module instances). Attach the journal to the replica,\n// rather than relying on a module-local WeakMap shared by both entry points.\nconst journalKey = Symbol.for(\"loro-repo.flock-persistence-journal.v1\");\ntype JournalledFlock = Flock & { [journalKey]?: FlockPersistenceJournal };\n\ninterface PendingPayload {\n readonly bytes: Uint8Array;\n failures: number;\n}\n\nconst MAX_EXACT_PAYLOAD_SAVE_ATTEMPTS = 3;\n\n/**\n * Persists `updates` in order. Reports how many leading updates are durable\n * and, if not all of them are, the failure. It must not reject.\n */\nexport type JournalWrite = (\n updates: readonly Uint8Array[],\n) => Promise<{ readonly durable: number; readonly error?: unknown }>;\n\nfunction versionsEqual(left: VersionVector, right: VersionVector): boolean {\n const leftPeers = Object.keys(left);\n const rightPeers = Object.keys(right);\n if (leftPeers.length !== rightPeers.length) return false;\n return leftPeers.every((peer) => {\n const a = left[peer];\n const b = right[peer];\n return (\n a?.physicalTime === b?.physicalTime &&\n a?.logicalCounter === b?.logicalCounter\n );\n });\n}\n\n/** Pending exact records and received payloads, acknowledged only after save. */\nexport class FlockPersistenceJournal {\n private readonly keys = new Set<string>();\n private readonly payloads: PendingPayload[] = [];\n private readonly unsubscribe: () => void;\n private remoteKeys?: Set<string>;\n /**\n * An inclusive version vector observed with no Flock event since. Exporting\n * a version vector from wasm costs time proportional to the number of\n * peers, and Streams delivers many batches that change nothing (echoes of\n * our own appends, replayed catch-ups). Reusing the vector read after the\n * previous import keeps such a batch to a single read.\n */\n private knownVersion?: VersionVector;\n\n constructor(\n private readonly flock: Flock,\n private readonly onDirty: () => void,\n ) {\n (flock as JournalledFlock)[journalKey] = this;\n this.unsubscribe = flock.subscribe((batch) => {\n // Local commits can be emitted by beforeImport(), even inside a remote\n // import. They must survive alongside the received payload.\n const keys =\n batch.source !== \"local\" && this.remoteKeys ? this.remoteKeys : this.keys;\n for (const event of batch.events) {\n keys.add(JSON.stringify(event.key));\n }\n if (batch.events.length) this.knownVersion = undefined;\n if (keys === this.keys && batch.events.length) this.onDirty();\n });\n }\n\n /**\n * Applies changes that are already durable at their owner: the replica\n * records no payload or key for them.\n */\n absorb<T>(apply: () => T): T {\n const previousKeys = this.remoteKeys;\n this.remoteKeys = new Set<string>();\n try {\n return apply();\n } finally {\n this.remoteKeys = previousKeys;\n }\n }\n\n get hasPending(): boolean {\n return this.keys.size > 0 || this.payloads.length > 0;\n }\n\n async receive<T>(\n payloads: readonly Uint8Array[],\n apply: () => T,\n ): Promise<Awaited<T>> {\n const copies = payloads\n .filter((bytes) => bytes.length > 0)\n .map((bytes) => bytes.slice());\n // Existing Flock adapter imports are synchronous. Only suppress their\n // synchronous remote events; unrelated work after an await is observable.\n let result: T;\n const previousKeys = this.remoteKeys;\n const remoteKeys = new Set<string>();\n // The inclusive vector only grows during the process lifetime, so a\n // cached vector that is stale because of an untracked import can only\n // cause a redundant save, never a skipped one.\n const previousVersion = this.knownVersion ?? this.flock.inclusiveVersion();\n this.remoteKeys = remoteKeys;\n try {\n result = apply();\n } catch (error) {\n // A batch import can partially succeed before throwing. Retain its\n // accepted records without persisting a possibly malformed payload.\n this.retainChangedKeys(remoteKeys);\n throw error;\n } finally {\n this.remoteKeys = previousKeys;\n }\n let outcome: Awaited<T>;\n try {\n outcome = await result;\n } catch (error) {\n this.retainChangedKeys(remoteKeys);\n throw error;\n }\n // Streams can echo an append back to its producer, and a bootstrap can\n // repeat state already hydrated locally. Flock emits no remote events in\n // either case, so there is no newly accepted state to journal. A genuine\n // same-VV hole does emit the missing key and still records the exact\n // received bytes. An import can also advance the version without\n // emitting events (an entry that loses last-writer-wins), so compare.\n if (remoteKeys.size > 0 || !this.versionUnchangedSince(previousVersion)) {\n this.payloads.push(...copies.map((bytes) => ({ bytes, failures: 0 })));\n if (copies.length) this.onDirty();\n }\n return outcome;\n }\n\n private versionUnchangedSince(previous: VersionVector): boolean {\n const current = this.flock.inclusiveVersion();\n this.knownVersion = current;\n return versionsEqual(previous, current);\n }\n\n private retainChangedKeys(keys: ReadonlySet<string>): void {\n for (const key of keys) this.keys.add(key);\n if (keys.size) this.onDirty();\n }\n\n /**\n * Called within the owner's serialized persistence queue.\n *\n * Each round hands every pending payload to `write` at once, so a storage\n * adapter can commit them in one transaction. Only the prefix `write`\n * reports durable is acknowledged.\n */\n async flush(write: JournalWrite): Promise<void> {\n this.flock.commit();\n while (this.hasPending) {\n if (this.keys.size) {\n await this.stageChangedKeys();\n }\n\n const { durable, error: exactError } = await write(\n this.payloads.map((payload) => payload.bytes),\n );\n // Only this loop removes payloads, so the written ones are still the\n // queue's prefix. New imports/local changes during the write remain\n // behind them.\n this.payloads.splice(0, durable);\n if (exactError === undefined) continue;\n\n const payload = this.payloads[0]!;\n payload.failures += 1;\n // One failing barrier must still block its remote cursor. Repeated\n // barriers retry the exact bytes up to a bounded count before using\n // the mergeable full-state fallback below.\n if (payload.failures < MAX_EXACT_PAYLOAD_SAVE_ATTEMPTS) {\n throw exactError;\n }\n // A storage adapter can reject one otherwise accepted encoding\n // forever. A full file is another mergeable representation of the\n // current CRDT state, so it can safely cover that queue item. Never\n // advance past the item unless this fallback itself is durable.\n // The exported file covers every payload that was queued when the\n // export began, not just the failing head. Payloads received while\n // the incremental export or save awaits are appended after this\n // boundary and must remain pending.\n const coveredPayloads = this.payloads.length;\n const snapshot = await exportFlockFileSnapshot(this.flock);\n const fallback = await write([snapshot]);\n if (fallback.error !== undefined) {\n throw new AggregateError(\n [exactError, fallback.error],\n \"Failed to persist a Flock update and its snapshot fallback\",\n );\n }\n this.payloads.splice(0, coveredPayloads);\n }\n }\n\n private async stageChangedKeys(): Promise<void> {\n const capturedKeys = [...this.keys];\n for (const key of capturedKeys) this.keys.delete(key);\n try {\n const bundle: ExportBundle = { version: 0, entries: {} };\n let useSnapshot = false;\n for (const key of capturedKeys) {\n let entry;\n try {\n entry = this.flock.getEntry(JSON.parse(key) as KeyPart[]);\n } catch {\n useSnapshot = true;\n break;\n }\n if (!entry) {\n useSnapshot = true;\n break;\n }\n const { physicalTime, logicalCounter, peerId } = entry.clock;\n bundle.entries[key] = {\n c: `${physicalTime},${logicalCounter},${peerId}`,\n ...(entry.data === undefined ? {} : { d: entry.data }),\n ...(Object.keys(entry.metadata).length ? { m: entry.metadata } : {}),\n };\n }\n const bytes = useSnapshot\n ? await exportFlockFileSnapshot(this.flock)\n : encodeMetaJsonUpdate(bundle);\n this.payloads.push({ bytes, failures: 0 });\n } catch (error) {\n // The current state has not been represented in the payload queue.\n // Restore the captured markers without disturbing newer events.\n for (const key of capturedKeys) this.keys.add(key);\n throw error;\n }\n }\n\n destroy(): void {\n this.unsubscribe();\n if ((this.flock as JournalledFlock)[journalKey] === this) {\n delete (this.flock as JournalledFlock)[journalKey];\n }\n }\n}\n\n/** Preserve plaintext CRDT bytes at the public Streams adapter boundary. */\nexport async function receiveFlockPayloads<T>(\n flock: Flock,\n payloads: readonly Uint8Array[],\n apply: () => T,\n): Promise<Awaited<T>> {\n const journal = (flock as JournalledFlock)[journalKey];\n return journal ? journal.receive(payloads, apply) : await apply();\n}\n"],"mappings":";;;;AAiCA,IAAa,oBAAb,MAA+B;CAC7B,AAAiB,yBAAS,IAAI,KAAuC;CACrE,AAAiB,8BAAc,IAAI,KAAqB;;;;;;;;;;CAUxD,AAAiB,2BAAW,IAAI,KAAqB;;CAGrD,WAAW,IAAoB;AAC7B,SAAO,KAAK,YAAY,IAAI,GAAG,IAAI;;;CAIrC,WAAW,IAAoB;AAC7B,SAAO,KAAK,OAAO,IAAI,GAAG,EAAE,QAAQ;;;;;;;CAQtC,QAAQ,IAAY,MAAyB,OAA2B;AACtE,MAAI,SAAS,WAAW,KAAK,SAAS,IAAI,GAAG,CAC3C,OAAM,IAAI,kBACR,YACA,IACA,CAAC,uBAAuB,EACxB,4BAA4B,GAAG,mGAEhC;EAEH,MAAM,QAAQ,OAAO,MAAM;EAC3B,IAAI,MAAM,KAAK,OAAO,IAAI,GAAG;AAC7B,MAAI,CAAC,KAAK;AACR,yBAAM,IAAI,KAAK;AACf,QAAK,OAAO,IAAI,IAAI,IAAI;;AAE1B,MAAI,IAAI,OAAO;GAAE;GAAM;GAAO,CAAC;EAC/B,IAAI,WAAW;AACf,eAAa;AACX,OAAI,SAAU;AACd,cAAW;GACX,MAAM,UAAU,KAAK,OAAO,IAAI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