@tearleads/client-sdk 0.1.206 → 0.1.208

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.
Files changed (50) hide show
  1. package/client/documents/index.d.ts +8 -0
  2. package/client/documents/index.js +14 -1
  3. package/client/documents/index.js.map +1 -1
  4. package/client/index.d.ts +1 -1
  5. package/client/index.js.map +1 -1
  6. package/data/documents/documentRestore.d.ts +30 -0
  7. package/data/documents/documentRestore.js +77 -0
  8. package/data/documents/documentRestore.js.map +1 -0
  9. package/data/documents/documentRowList.d.ts +6 -0
  10. package/data/documents/documentRowList.js +31 -0
  11. package/data/documents/documentRowList.js.map +1 -1
  12. package/data/documents/index.d.ts +1 -0
  13. package/data/documents/index.js.map +1 -1
  14. package/data/persistence/organizations/organizationDataUsagePersistence.js +90 -82
  15. package/data/persistence/organizations/organizationDataUsagePersistence.js.map +1 -1
  16. package/index.d.ts +3 -3
  17. package/index.js +1 -1
  18. package/index.js.map +1 -1
  19. package/internal/loro/historyTimeline.d.ts +57 -0
  20. package/internal/loro/historyTimeline.js +271 -0
  21. package/internal/loro/historyTimeline.js.map +1 -0
  22. package/internal/loro/index.d.ts +1 -0
  23. package/internal/loro/index.js +1 -0
  24. package/internal/loro/index.js.map +1 -1
  25. package/package.json +1 -1
  26. package/stores/documents/documentStore/history/restoreContent.js +127 -0
  27. package/stores/documents/documentStore/history/restoreContent.js.map +1 -0
  28. package/stores/documents/documentStore/index.js +4 -4
  29. package/stores/documents/documentStore/index.js.map +1 -1
  30. package/stores/documents/documentStore/mutations.js +1 -1
  31. package/stores/documents/documentStore/mutations.js.map +1 -1
  32. package/stores/documents/documentStore/rows/index.js +8 -0
  33. package/stores/documents/documentStore/rows/index.js.map +1 -1
  34. package/stores/documents/registry.js +1 -0
  35. package/stores/documents/registry.js.map +1 -1
  36. package/stores/documents/removedDocumentStore.js +1 -0
  37. package/stores/documents/removedDocumentStore.js.map +1 -1
  38. package/stores/documents/types.d.ts +10 -1
  39. package/stores/documents/types.js.map +1 -1
  40. package/workflows/documents/history/documentHistory.d.ts +72 -0
  41. package/workflows/documents/history/documentHistory.js +103 -0
  42. package/workflows/documents/history/documentHistory.js.map +1 -0
  43. package/workflows/documents/history/documentHistoryChange.d.ts +51 -0
  44. package/workflows/documents/history/documentHistoryChange.js +110 -0
  45. package/workflows/documents/history/documentHistoryChange.js.map +1 -0
  46. package/workflows/documents/index.d.ts +2 -0
  47. package/workflows/documents/index.js +2 -0
  48. package/workflows/documents/index.js.map +1 -1
  49. package/workflows/organizations/readModel/dataUsageReadModel.js +4 -5
  50. package/workflows/organizations/readModel/dataUsageReadModel.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAGlF,OAAO,EACL,uCAAuC,EAEvC,2BAA2B,EAC3B,qCAAqC,EACrC,0BAA0B,EAC1B,8BAA8B,GAC/B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,gCAAgC,EAChC,qBAAqB,EACrB,6BAA6B,EAC7B,wBAAwB,EACxB,uBAAuB,EACvB,2BAA2B,GAC5B,MAAM,aAAa,CAAC;AAQrB,OAAO,EACL,0BAA0B,EAC1B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,EACxB,mBAAmB,GACpB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,4BAA4B,EAAE,MAAM,iCAAiC,CAAC;AAC/E,OAAO,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,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,aAAa,CAAC,OAAO,CAAC,CAAC;IAC7B,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../../data/documents/documentKinds\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n createDocumentProjectionUserKeyResolver,\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n didDocumentProjectionKeyRuntimeChange,\n didRegainSyncPrerequisites,\n requestDocumentSyncLaneAndWait,\n} from \"../../../workflows/documents\";\nimport {\n createDocumentStoreFacade,\n emitPersistedDocument,\n getOrCreateDocumentStoreRegistry,\n registerDocumentStore,\n registerDocumentStoreIdentity,\n requestDocumentStoreSync,\n resolveDocumentStoreKey,\n takeRegisteredDocumentStore,\n} from \"../registry\";\nimport type {\n DocumentAttachmentUpload,\n DocumentStore,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentsRuntime,\n} from \"../types\";\nimport {\n attachFilesToDocumentStore,\n replaceAttachmentInDocumentStore,\n} from \"./attachments\";\nimport { removeAttachmentFromDocumentStore } from \"./attachments/attachmentRemoval\";\nimport { discardDocumentStoreLocalState } from \"./discard\";\nimport {\n ensureDocumentStoreInitialized,\n ensureDocumentStoreReady,\n relinkDocumentStore,\n} from \"./initialization\";\nimport { assertInitialContentFitsKind } from \"./initialization/initialContent\";\nimport { registerInternalDocumentRelink } from \"./internalRelink\";\nimport { countQueuedWrite } from \"./localWriteQueue\";\nimport { setDocumentStructuredFields, setDocumentText } from \"./mutations\";\nimport { assertLoadedDocumentStoreCanRotate } from \"./rotation/rotationPreflight\";\nimport {\n addRowToDocumentStore,\n removeRowFromDocumentStore,\n updateRowInDocumentStore,\n} from \"./rows\";\nimport {\n createDocumentStoreState,\n type DocumentStoreState,\n refreshAttachabilitySnapshot,\n resetDocumentStore,\n subscribeToDocumentStore,\n} from \"./state\";\nimport { registerDocumentStoreSyncLane } from \"./sync\";\nimport { logRevalidationScheduled } from \"./sync/remoteRevalidationTelemetry\";\nimport { settleDeferredStartupProbe } from \"./sync/startupProbeDeferral\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreRemoteSyncRequestGeneration,\n captureDocumentStoreSyncLaneGeneration,\n type DocumentStoreRemoteSyncRequestGeneration,\n type DocumentStoreSyncLaneGeneration,\n didDocumentStoreRemoteSyncRequestComplete,\n hasPendingIndependentDocumentStoreRemoteSync,\n invalidateDocumentStoreRemoteSync,\n invalidateDocumentStoreSyncLane,\n isDocumentStoreRemoteSyncBlocked,\n isDocumentStoreRemoteSyncRequestGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n registerDocumentStoreRemoteSyncWaiter,\n} from \"./sync/syncGeneration\";\nimport { handleDocumentRemoteEvents } from \"./sync/syncRemoteSignals\";\n\nexport {\n discardRegisteredDocumentLocalState,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"../registry\";\n\nfunction refreshDocumentStoreSyncLane(\n state: DocumentStoreState,\n force = false,\n): void {\n if (!force && state.syncLane && !state.syncLane.isDisposed?.()) {\n return;\n }\n if (state.syncLane) {\n invalidateDocumentStoreSyncLane(state);\n }\n let syncLaneGeneration: DocumentStoreSyncLaneGeneration | null = null;\n state.syncLane = registerDocumentStoreSyncLane(\n state,\n () => syncLaneGeneration,\n );\n syncLaneGeneration = captureDocumentStoreSyncLaneGeneration(state);\n}\n\nfunction updateDocumentStoreRuntime(\n state: DocumentStoreState,\n nextRuntime: DocumentsRuntime,\n scheduleSync: () => void,\n) {\n const previousRuntime = state.runtime;\n const serverEventsReconnected =\n (nextRuntime.state.serverEventsConnectionGeneration ?? 0) >\n (previousRuntime.state.serverEventsConnectionGeneration ?? 0);\n const domainScopeChanged =\n previousRuntime.state.domainScope !== nextRuntime.state.domainScope;\n const projectionKeyRuntimeChanged = didDocumentProjectionKeyRuntimeChange(\n previousRuntime,\n nextRuntime,\n );\n if (projectionKeyRuntimeChanged) {\n state.resolveProjectionUserKey =\n createDocumentProjectionUserKeyResolver(nextRuntime);\n state.writerProjection = null;\n }\n state.runtime = nextRuntime;\n refreshDocumentStoreSyncLane(state, domainScopeChanged);\n if (domainScopeChanged) {\n state.locallyAcceptedUpdateIds = new Set();\n state.remoteUpdatePending = false;\n state.writerProjection = null;\n }\n\n if (nextRuntime.infra.dbStatus !== \"ready\") {\n if (state.snapshot.ready || state.initialized || state.initializePromise) {\n resetDocumentStore(state);\n }\n state.lastEventCount = nextRuntime.state.events.length;\n return;\n }\n\n refreshAttachabilitySnapshot(state);\n ensureDocumentStoreInitialized(state, scheduleSync);\n handleDocumentRemoteEvents(state, scheduleSync);\n\n if (state.snapshot.ready) {\n settleDeferredStartupProbe(state, serverEventsReconnected, scheduleSync);\n if (serverEventsReconnected) {\n // The invalidation stream is lossy while disconnected. Once the server\n // has acknowledged this socket's authoritative interest declaration,\n // every already-open remote document needs one HTTP probe to cover peer\n // writes made during the gap. This also closes iOS background/resume reconnects where the\n // native network source remained online throughout.\n requestRemoteDocumentStoreSync(state, scheduleSync);\n logRevalidationScheduled(state.runtime, \"reconnect\");\n } else if (didRegainSyncPrerequisites(previousRuntime, state.runtime)) {\n scheduleSync();\n }\n }\n}\n\nfunction requestRemoteDocumentStoreSync(\n state: DocumentStoreState,\n scheduleSync: () => void,\n owner: \"independent\" | \"waiter\" = \"independent\",\n): number {\n allowDocumentStoreRemoteSync(state);\n const signalSequence = markDocumentStoreRemoteSyncPending(state, owner);\n scheduleSync();\n return signalSequence;\n}\n\nfunction requestOrdinaryDocumentStoreSync(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): void {\n // A normal UI reopen is a fresh owner for remote-only work. It may recover\n // a probe that an earlier, now-unmounted owner aborted.\n if (isDocumentStoreRemoteSyncBlocked(state)) {\n requestRemoteDocumentStoreSync(state, scheduleSync);\n return;\n }\n scheduleSync();\n}\n\nfunction requestRemoteDocumentStoreSyncAndWait(\n state: DocumentStoreState,\n scheduleSync: () => void,\n signal?: AbortSignal,\n): Promise<boolean> {\n let requestGeneration: DocumentStoreRemoteSyncRequestGeneration | null = null;\n let requestedSignalSequence = 0;\n let releaseWaiter: (() => boolean) | null = null;\n const releaseRemoteSyncWaiter = (invalidate: boolean) => {\n const releasedLastWaiter = releaseWaiter?.() ?? false;\n if (\n invalidate &&\n releasedLastWaiter &&\n requestGeneration !== null &&\n isDocumentStoreRemoteSyncRequestGenerationCurrent(\n state,\n requestGeneration,\n ) &&\n !hasPendingIndependentDocumentStoreRemoteSync(state)\n ) {\n invalidateDocumentStoreRemoteSync(state);\n }\n };\n // A coordinator can be disposed and recreated while this same-scope store\n // remains registered. Refresh its handle before requesting work.\n refreshDocumentStoreSyncLane(state);\n return requestDocumentSyncLaneAndWait({\n didCompleteRequest: () =>\n requestGeneration !== null &&\n didDocumentStoreRemoteSyncRequestComplete(\n state,\n requestGeneration,\n requestedSignalSequence,\n ),\n domainScope: state.runtime.state.domainScope,\n localId: state.localId,\n request: () => {\n requestGeneration =\n captureDocumentStoreRemoteSyncRequestGeneration(state);\n releaseWaiter = registerDocumentStoreRemoteSyncWaiter(\n state,\n requestGeneration,\n );\n requestedSignalSequence = requestRemoteDocumentStoreSync(\n state,\n scheduleSync,\n \"waiter\",\n );\n },\n onInvalidated: () => releaseRemoteSyncWaiter(true),\n signal,\n }).then(\n (completed) => {\n releaseRemoteSyncWaiter(!completed);\n return completed;\n },\n (error: unknown) => {\n releaseRemoteSyncWaiter(true);\n throw error;\n },\n );\n}\n\nasync function discardBackingDocumentStoreLocalState(\n state: DocumentStoreState,\n scheduleSync: () => void,\n expectedDocumentId: string,\n) {\n try {\n return await discardDocumentStoreLocalState(state, expectedDocumentId);\n } finally {\n // Restart hydration whenever the attempt reset the store. This runs outside\n // its identity-chained task because initialization also chains writes.\n ensureDocumentStoreInitialized(state, scheduleSync);\n scheduleSync();\n }\n}\n\nfunction createLiveSyncLaneRequest(state: DocumentStoreState) {\n return <Result>(request: () => Result): Result => {\n refreshDocumentStoreSyncLane(state);\n return request();\n };\n}\n\nfunction registerBackingStoreInternalRelink(input: {\n scheduleSync: () => void;\n state: DocumentStoreState;\n store: DocumentStore;\n withLiveSyncLane: ReturnType<typeof createLiveSyncLaneRequest>;\n}): DocumentStore {\n registerInternalDocumentRelink(input.store, (relinkInput, commitSideEffect) =>\n input.withLiveSyncLane(() =>\n relinkDocumentStore(\n input.state,\n relinkInput,\n input.scheduleSync,\n commitSideEffect,\n ),\n ),\n );\n return input.store;\n}\n\nfunction createBackingStoreContext(\n localId: string,\n runtime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n documentId: string | null,\n text: string,\n documentKind: StoredDocumentKind,\n options: DocumentStoreOpenOptions,\n) {\n const state = createDocumentStoreState(\n localId,\n runtime,\n persistence,\n {\n emitPersistedDocument,\n registerDocumentIdentity: registerDocumentStoreIdentity,\n },\n documentId,\n text,\n documentKind,\n (options.remoteSyncMode ?? \"startup\") === \"startup\",\n );\n if (options.deferInitialUpdate) state.deferInitialUpdate = true;\n const { initialRows, initialStructuredFields } = options;\n assertInitialContentFitsKind({ initialStructuredFields }, documentKind);\n state.initialContent = { initialRows, initialStructuredFields };\n refreshDocumentStoreSyncLane(state);\n const scheduleSync = () => requestDocumentStoreSync(state);\n return {\n scheduleSync,\n state,\n withLiveSyncLane: createLiveSyncLaneRequest(state),\n };\n}\n\nfunction createBackingDocumentStore(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n openOptions: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const context = createBackingStoreContext(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n openOptions,\n );\n\n const { scheduleSync, state, withLiveSyncLane } = context;\n // Local writes count as queued from the call, readiness wait included.\n const liveWrite = <Result>(write: () => Promise<Result>) =>\n withLiveSyncLane(() => countQueuedWrite(state, write()));\n const store: DocumentStore = {\n addRow: (fields, options) =>\n liveWrite(() =>\n addRowToDocumentStore(state, scheduleSync, fields, options),\n ),\n assertCanRotateContentKey: (proof) =>\n withLiveSyncLane(() =>\n assertLoadedDocumentStoreCanRotate(state, scheduleSync, proof),\n ),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n liveWrite(() => attachFilesToDocumentStore(state, scheduleSync, files)),\n discardLocalState: (expectedDocumentId: string) =>\n withLiveSyncLane(() =>\n discardBackingDocumentStoreLocalState(\n state,\n scheduleSync,\n expectedDocumentId,\n ),\n ),\n ensureInitialized: () =>\n withLiveSyncLane(() => ensureDocumentStoreReady(state, scheduleSync)),\n getSnapshot: () => state.snapshot,\n hasQueuedWrites: () => state.queuedWrites > 0,\n hasUnsavedLocalEdits: () => state.unsavedLocalEdits,\n removeAttachment: (slotId: string) =>\n liveWrite(() =>\n removeAttachmentFromDocumentStore(state, scheduleSync, slotId),\n ),\n removeRow: (id, options) =>\n liveWrite(() =>\n removeRowFromDocumentStore(state, scheduleSync, id, options),\n ),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n liveWrite(() =>\n replaceAttachmentInDocumentStore(state, scheduleSync, slotId, file),\n ),\n requestRemoteSync: () =>\n withLiveSyncLane(() =>\n requestRemoteDocumentStoreSync(state, scheduleSync),\n ),\n requestRemoteSyncAndWait: (signal) =>\n requestRemoteDocumentStoreSyncAndWait(state, scheduleSync, signal),\n requestSync: () =>\n withLiveSyncLane(() =>\n requestOrdinaryDocumentStoreSync(state, scheduleSync),\n ),\n relink: (input) =>\n withLiveSyncLane(() => relinkDocumentStore(state, input, scheduleSync)),\n setStructuredFields: (kind, patch, options) =>\n liveWrite(() =>\n setDocumentStructuredFields(state, scheduleSync, kind, patch, options),\n ),\n setText: (value: string) =>\n liveWrite(() => setDocumentText(state, scheduleSync, value)),\n subscribe: (listener) => subscribeToDocumentStore(state, listener),\n updateRowFields: (id, patch, options) =>\n liveWrite(() =>\n updateRowInDocumentStore(state, scheduleSync, id, patch, options),\n ),\n updateRuntime: (runtime: DocumentsRuntime) =>\n updateDocumentStoreRuntime(state, runtime, scheduleSync),\n };\n return registerBackingStoreInternalRelink({ ...context, store });\n}\n\nexport function createDocumentStore(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStoreFacade {\n return createDocumentStoreFacade(\n createBackingDocumentStore(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n ),\n );\n}\n\nexport function getOrCreateDocumentStore(\n domainScope: DomainScope,\n localId: string,\n runtime: DocumentsRuntime,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const createBacking = () =>\n createBackingDocumentStore(\n localId,\n runtime,\n defaultDocumentsPersistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\n const existingStore = takeRegisteredDocumentStore(\n registry,\n resolveDocumentStoreKey(registry, localId, initialDocumentId),\n createBacking,\n );\n if (existingStore) {\n registerDocumentStore(\n domainScope,\n localId,\n existingStore,\n initialDocumentId,\n );\n return existingStore;\n }\n\n const nextStore = createDocumentStoreFacade(createBacking());\n registerDocumentStore(domainScope, localId, nextStore, initialDocumentId);\n return nextStore;\n}\n\nexport function openDocumentStore(\n domainScope: DomainScope,\n localId: string,\n runtime: DocumentsRuntime,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const store = getOrCreateDocumentStore(\n domainScope,\n localId,\n runtime,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\n store.updateRuntime(runtime);\n return store;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAGlF,OAAO,EACL,uCAAuC,EAEvC,2BAA2B,EAC3B,qCAAqC,EACrC,0BAA0B,EAC1B,8BAA8B,GAC/B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,gCAAgC,EAChC,qBAAqB,EACrB,6BAA6B,EAC7B,wBAAwB,EACxB,uBAAuB,EACvB,2BAA2B,GAC5B,MAAM,aAAa,CAAC;AAQrB,OAAO,EACL,0BAA0B,EAC1B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,EACxB,mBAAmB,GACpB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,4BAA4B,EAAE,MAAM,iCAAiC,CAAC;AAC/E,OAAO,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,2BAA2B,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC3E,OAAO,EAAE,kCAAkC,EAAE,MAAM,8BAA8B,CAAC;AAClF,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AACzC,OAAO,EACL,wBAAwB,EAExB,4BAA4B,EAC5B,kBAAkB,EAClB,wBAAwB,GACzB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,6BAA6B,EAAE,MAAM,QAAQ,CAAC;AACvD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CAAC;IACF,IAAI,aAAa,EAAE,CAAC;QAClB,qBAAqB,CACnB,WAAW,EACX,OAAO,EACP,aAAa,EACb,iBAAiB,CAClB,CAAC;QACF,OAAO,aAAa,CAAC;IACvB,CAAC;IAED,MAAM,SAAS,GAAG,yBAAyB,CAAC,aAAa,EAAE,CAAC,CAAC;IAC7D,qBAAqB,CAAC,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,iBAAiB,CAAC,CAAC;IAC1E,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,WAAwB,EACxB,OAAe,EACf,OAAyB,EACzB,oBAAmC,IAAI,EACvC,WAAW,GAAG,EAAE,EAChB,sBAA0C,qBAAqB,EAC/D,UAAoC,EAAE;IAEtC,MAAM,KAAK,GAAG,wBAAwB,CACpC,WAAW,EACX,OAAO,EACP,OAAO,EACP,iBAAiB,EACjB,WAAW,EACX,mBAAmB,EACnB,OAAO,CACR,CAAC;IACF,KAAK,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;IAC7B,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../../data/documents/documentKinds\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n createDocumentProjectionUserKeyResolver,\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n didDocumentProjectionKeyRuntimeChange,\n didRegainSyncPrerequisites,\n requestDocumentSyncLaneAndWait,\n} from \"../../../workflows/documents\";\nimport {\n createDocumentStoreFacade,\n emitPersistedDocument,\n getOrCreateDocumentStoreRegistry,\n registerDocumentStore,\n registerDocumentStoreIdentity,\n requestDocumentStoreSync,\n resolveDocumentStoreKey,\n takeRegisteredDocumentStore,\n} from \"../registry\";\nimport type {\n DocumentAttachmentUpload,\n DocumentStore,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentsRuntime,\n} from \"../types\";\nimport {\n attachFilesToDocumentStore,\n replaceAttachmentInDocumentStore,\n} from \"./attachments\";\nimport { removeAttachmentFromDocumentStore } from \"./attachments/attachmentRemoval\";\nimport { discardDocumentStoreLocalState } from \"./discard\";\nimport { restoreDocumentStoreContent } from \"./history/restoreContent\";\nimport {\n ensureDocumentStoreInitialized,\n ensureDocumentStoreReady,\n relinkDocumentStore,\n} from \"./initialization\";\nimport { assertInitialContentFitsKind } from \"./initialization/initialContent\";\nimport { registerInternalDocumentRelink } from \"./internalRelink\";\nimport { countQueuedWrite } from \"./localWriteQueue\";\nimport { setDocumentStructuredFields, setDocumentText } from \"./mutations\";\nimport { assertLoadedDocumentStoreCanRotate } from \"./rotation/rotationPreflight\";\nimport { createRowWrites } from \"./rows\";\nimport {\n createDocumentStoreState,\n type DocumentStoreState,\n refreshAttachabilitySnapshot,\n resetDocumentStore,\n subscribeToDocumentStore,\n} from \"./state\";\nimport { registerDocumentStoreSyncLane } from \"./sync\";\nimport { logRevalidationScheduled } from \"./sync/remoteRevalidationTelemetry\";\nimport { settleDeferredStartupProbe } from \"./sync/startupProbeDeferral\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreRemoteSyncRequestGeneration,\n captureDocumentStoreSyncLaneGeneration,\n type DocumentStoreRemoteSyncRequestGeneration,\n type DocumentStoreSyncLaneGeneration,\n didDocumentStoreRemoteSyncRequestComplete,\n hasPendingIndependentDocumentStoreRemoteSync,\n invalidateDocumentStoreRemoteSync,\n invalidateDocumentStoreSyncLane,\n isDocumentStoreRemoteSyncBlocked,\n isDocumentStoreRemoteSyncRequestGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n registerDocumentStoreRemoteSyncWaiter,\n} from \"./sync/syncGeneration\";\nimport { handleDocumentRemoteEvents } from \"./sync/syncRemoteSignals\";\n\nexport {\n discardRegisteredDocumentLocalState,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"../registry\";\n\nfunction refreshDocumentStoreSyncLane(\n state: DocumentStoreState,\n force = false,\n): void {\n if (!force && state.syncLane && !state.syncLane.isDisposed?.()) {\n return;\n }\n if (state.syncLane) {\n invalidateDocumentStoreSyncLane(state);\n }\n let syncLaneGeneration: DocumentStoreSyncLaneGeneration | null = null;\n state.syncLane = registerDocumentStoreSyncLane(\n state,\n () => syncLaneGeneration,\n );\n syncLaneGeneration = captureDocumentStoreSyncLaneGeneration(state);\n}\n\nfunction updateDocumentStoreRuntime(\n state: DocumentStoreState,\n nextRuntime: DocumentsRuntime,\n scheduleSync: () => void,\n) {\n const previousRuntime = state.runtime;\n const serverEventsReconnected =\n (nextRuntime.state.serverEventsConnectionGeneration ?? 0) >\n (previousRuntime.state.serverEventsConnectionGeneration ?? 0);\n const domainScopeChanged =\n previousRuntime.state.domainScope !== nextRuntime.state.domainScope;\n const projectionKeyRuntimeChanged = didDocumentProjectionKeyRuntimeChange(\n previousRuntime,\n nextRuntime,\n );\n if (projectionKeyRuntimeChanged) {\n state.resolveProjectionUserKey =\n createDocumentProjectionUserKeyResolver(nextRuntime);\n state.writerProjection = null;\n }\n state.runtime = nextRuntime;\n refreshDocumentStoreSyncLane(state, domainScopeChanged);\n if (domainScopeChanged) {\n state.locallyAcceptedUpdateIds = new Set();\n state.remoteUpdatePending = false;\n state.writerProjection = null;\n }\n\n if (nextRuntime.infra.dbStatus !== \"ready\") {\n if (state.snapshot.ready || state.initialized || state.initializePromise) {\n resetDocumentStore(state);\n }\n state.lastEventCount = nextRuntime.state.events.length;\n return;\n }\n\n refreshAttachabilitySnapshot(state);\n ensureDocumentStoreInitialized(state, scheduleSync);\n handleDocumentRemoteEvents(state, scheduleSync);\n\n if (state.snapshot.ready) {\n settleDeferredStartupProbe(state, serverEventsReconnected, scheduleSync);\n if (serverEventsReconnected) {\n // The invalidation stream is lossy while disconnected. Once the server\n // has acknowledged this socket's authoritative interest declaration,\n // every already-open remote document needs one HTTP probe to cover peer\n // writes made during the gap. This also closes iOS background/resume reconnects where the\n // native network source remained online throughout.\n requestRemoteDocumentStoreSync(state, scheduleSync);\n logRevalidationScheduled(state.runtime, \"reconnect\");\n } else if (didRegainSyncPrerequisites(previousRuntime, state.runtime)) {\n scheduleSync();\n }\n }\n}\n\nfunction requestRemoteDocumentStoreSync(\n state: DocumentStoreState,\n scheduleSync: () => void,\n owner: \"independent\" | \"waiter\" = \"independent\",\n): number {\n allowDocumentStoreRemoteSync(state);\n const signalSequence = markDocumentStoreRemoteSyncPending(state, owner);\n scheduleSync();\n return signalSequence;\n}\n\nfunction requestOrdinaryDocumentStoreSync(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): void {\n // A normal UI reopen is a fresh owner for remote-only work. It may recover\n // a probe that an earlier, now-unmounted owner aborted.\n if (isDocumentStoreRemoteSyncBlocked(state)) {\n requestRemoteDocumentStoreSync(state, scheduleSync);\n return;\n }\n scheduleSync();\n}\n\nfunction requestRemoteDocumentStoreSyncAndWait(\n state: DocumentStoreState,\n scheduleSync: () => void,\n signal?: AbortSignal,\n): Promise<boolean> {\n let requestGeneration: DocumentStoreRemoteSyncRequestGeneration | null = null;\n let requestedSignalSequence = 0;\n let releaseWaiter: (() => boolean) | null = null;\n const releaseRemoteSyncWaiter = (invalidate: boolean) => {\n const releasedLastWaiter = releaseWaiter?.() ?? false;\n if (\n invalidate &&\n releasedLastWaiter &&\n requestGeneration !== null &&\n isDocumentStoreRemoteSyncRequestGenerationCurrent(\n state,\n requestGeneration,\n ) &&\n !hasPendingIndependentDocumentStoreRemoteSync(state)\n ) {\n invalidateDocumentStoreRemoteSync(state);\n }\n };\n // A coordinator can be disposed and recreated while this same-scope store\n // remains registered. Refresh its handle before requesting work.\n refreshDocumentStoreSyncLane(state);\n return requestDocumentSyncLaneAndWait({\n didCompleteRequest: () =>\n requestGeneration !== null &&\n didDocumentStoreRemoteSyncRequestComplete(\n state,\n requestGeneration,\n requestedSignalSequence,\n ),\n domainScope: state.runtime.state.domainScope,\n localId: state.localId,\n request: () => {\n requestGeneration =\n captureDocumentStoreRemoteSyncRequestGeneration(state);\n releaseWaiter = registerDocumentStoreRemoteSyncWaiter(\n state,\n requestGeneration,\n );\n requestedSignalSequence = requestRemoteDocumentStoreSync(\n state,\n scheduleSync,\n \"waiter\",\n );\n },\n onInvalidated: () => releaseRemoteSyncWaiter(true),\n signal,\n }).then(\n (completed) => {\n releaseRemoteSyncWaiter(!completed);\n return completed;\n },\n (error: unknown) => {\n releaseRemoteSyncWaiter(true);\n throw error;\n },\n );\n}\n\nasync function discardBackingDocumentStoreLocalState(\n state: DocumentStoreState,\n scheduleSync: () => void,\n expectedDocumentId: string,\n) {\n try {\n return await discardDocumentStoreLocalState(state, expectedDocumentId);\n } finally {\n // Restart hydration whenever the attempt reset the store. This runs outside\n // its identity-chained task because initialization also chains writes.\n ensureDocumentStoreInitialized(state, scheduleSync);\n scheduleSync();\n }\n}\n\nfunction createLiveSyncLaneRequest(state: DocumentStoreState) {\n return <Result>(request: () => Result): Result => {\n refreshDocumentStoreSyncLane(state);\n return request();\n };\n}\n\nfunction registerBackingStoreInternalRelink(input: {\n scheduleSync: () => void;\n state: DocumentStoreState;\n store: DocumentStore;\n withLiveSyncLane: ReturnType<typeof createLiveSyncLaneRequest>;\n}): DocumentStore {\n registerInternalDocumentRelink(input.store, (relinkInput, commitSideEffect) =>\n input.withLiveSyncLane(() =>\n relinkDocumentStore(\n input.state,\n relinkInput,\n input.scheduleSync,\n commitSideEffect,\n ),\n ),\n );\n return input.store;\n}\n\nfunction createBackingStoreContext(\n localId: string,\n runtime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n documentId: string | null,\n text: string,\n documentKind: StoredDocumentKind,\n options: DocumentStoreOpenOptions,\n) {\n const state = createDocumentStoreState(\n localId,\n runtime,\n persistence,\n {\n emitPersistedDocument,\n registerDocumentIdentity: registerDocumentStoreIdentity,\n },\n documentId,\n text,\n documentKind,\n (options.remoteSyncMode ?? \"startup\") === \"startup\",\n );\n if (options.deferInitialUpdate) state.deferInitialUpdate = true;\n const { initialRows, initialStructuredFields } = options;\n assertInitialContentFitsKind({ initialStructuredFields }, documentKind);\n state.initialContent = { initialRows, initialStructuredFields };\n refreshDocumentStoreSyncLane(state);\n const scheduleSync = () => requestDocumentStoreSync(state);\n return {\n scheduleSync,\n state,\n withLiveSyncLane: createLiveSyncLaneRequest(state),\n };\n}\n\nfunction createBackingDocumentStore(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n openOptions: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const context = createBackingStoreContext(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n openOptions,\n );\n\n const { scheduleSync, state, withLiveSyncLane } = context;\n // Local writes count as queued from the call, readiness wait included.\n const liveWrite = <Result>(write: () => Promise<Result>) =>\n withLiveSyncLane(() => countQueuedWrite(state, write()));\n const store: DocumentStore = {\n ...createRowWrites(state, scheduleSync, liveWrite),\n assertCanRotateContentKey: (proof) =>\n withLiveSyncLane(() =>\n assertLoadedDocumentStoreCanRotate(state, scheduleSync, proof),\n ),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n liveWrite(() => attachFilesToDocumentStore(state, scheduleSync, files)),\n discardLocalState: (expectedDocumentId: string) =>\n withLiveSyncLane(() =>\n discardBackingDocumentStoreLocalState(\n state,\n scheduleSync,\n expectedDocumentId,\n ),\n ),\n ensureInitialized: () =>\n withLiveSyncLane(() => ensureDocumentStoreReady(state, scheduleSync)),\n getSnapshot: () => state.snapshot,\n hasQueuedWrites: () => state.queuedWrites > 0,\n hasUnsavedLocalEdits: () => state.unsavedLocalEdits,\n removeAttachment: (slotId: string) =>\n liveWrite(() =>\n removeAttachmentFromDocumentStore(state, scheduleSync, slotId),\n ),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n liveWrite(() =>\n replaceAttachmentInDocumentStore(state, scheduleSync, slotId, file),\n ),\n requestRemoteSync: () =>\n withLiveSyncLane(() =>\n requestRemoteDocumentStoreSync(state, scheduleSync),\n ),\n restoreContent: (content, options) =>\n liveWrite(() =>\n restoreDocumentStoreContent(state, scheduleSync, content, options),\n ),\n requestRemoteSyncAndWait: (signal) =>\n requestRemoteDocumentStoreSyncAndWait(state, scheduleSync, signal),\n requestSync: () =>\n withLiveSyncLane(() =>\n requestOrdinaryDocumentStoreSync(state, scheduleSync),\n ),\n relink: (input) =>\n withLiveSyncLane(() => relinkDocumentStore(state, input, scheduleSync)),\n setStructuredFields: (kind, patch, options) =>\n liveWrite(() =>\n setDocumentStructuredFields(state, scheduleSync, kind, patch, options),\n ),\n setText: (value: string) =>\n liveWrite(() => setDocumentText(state, scheduleSync, value)),\n subscribe: (listener) => subscribeToDocumentStore(state, listener),\n updateRuntime: (runtime: DocumentsRuntime) =>\n updateDocumentStoreRuntime(state, runtime, scheduleSync),\n };\n return registerBackingStoreInternalRelink({ ...context, store });\n}\n\nexport function createDocumentStore(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStoreFacade {\n return createDocumentStoreFacade(\n createBackingDocumentStore(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n ),\n );\n}\n\nexport function getOrCreateDocumentStore(\n domainScope: DomainScope,\n localId: string,\n runtime: DocumentsRuntime,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const createBacking = () =>\n createBackingDocumentStore(\n localId,\n runtime,\n defaultDocumentsPersistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\n const existingStore = takeRegisteredDocumentStore(\n registry,\n resolveDocumentStoreKey(registry, localId, initialDocumentId),\n createBacking,\n );\n if (existingStore) {\n registerDocumentStore(\n domainScope,\n localId,\n existingStore,\n initialDocumentId,\n );\n return existingStore;\n }\n\n const nextStore = createDocumentStoreFacade(createBacking());\n registerDocumentStore(domainScope, localId, nextStore, initialDocumentId);\n return nextStore;\n}\n\nexport function openDocumentStore(\n domainScope: DomainScope,\n localId: string,\n runtime: DocumentsRuntime,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const store = getOrCreateDocumentStore(\n domainScope,\n localId,\n runtime,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\n store.updateRuntime(runtime);\n return store;\n}\n"]}
@@ -23,7 +23,7 @@ function structuredMutationDurabilityOptions(options, update) {
23
23
  function isDocumentLocalWriteCurrent(state, writeGeneration, writeDoc) {
24
24
  return (state.localWriteGeneration === writeGeneration && state.doc === writeDoc);
25
25
  }
26
- function settleDocumentLocalWrite(state, writeGeneration) {
26
+ export function settleDocumentLocalWrite(state, writeGeneration) {
27
27
  // Reset/reinitialization owns the new generation's counter. A write queued
28
28
  // against the prior document must touch neither it nor the replacement doc.
29
29
  if (state.localWriteGeneration !== writeGeneration) {
@@ -1 +1 @@
1
- {"version":3,"file":"mutations.js","sourceRoot":"","sources":["mutations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpE,OAAO,EACL,0BAA0B,EAE1B,yBAAyB,GAC1B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EAAE,wBAAwB,EAAE,MA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AAC,CAAC;AACxE,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport { encodeVersionVector, getTextValue } from \"@tearleads/loro\";\nimport {\n projectStoredDocumentState,\n type StoredDocumentKind,\n writeStoredDocumentFields,\n} from \"../../../data/documents/documentKinds\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport type {\n DocumentMutationOptions,\n DocumentStructuredFieldPatch,\n} from \"../types\";\nimport {\n ensureDocumentStoreInitialized,\n ensureDocumentStoreReady,\n} from \"./initialization\";\nimport {\n chainQueuedWrite,\n isLocalWriteSuperseded,\n issueLocalWriteTicket,\n type LocalWriteKey,\n type LocalWriteTicket,\n} from \"./localWriteQueue\";\nimport { revalidateDocumentMutationIdentity } from \"./mutationIdentityRevalidation\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"./persistence\";\nimport { reportDocumentStoreWriteFailure } from \"./reportWriteFailure\";\nimport {\n canWriteDocument,\n type DocumentState,\n type DocumentStoreState,\n type SaveDocumentRecordOptions,\n setDocumentSnapshot,\n setReadySnapshot,\n} from \"./state\";\nimport { captureDocumentStoreSyncGeneration } from \"./sync/syncGeneration\";\n\n// Fixed literals: a reported message must never carry document text or ids.\nconst TEXT_FAILURE_MESSAGE = \"Documents: local text persist failed\";\nconst FIELD_FAILURE_MESSAGE = \"Documents: local field persist failed\";\n\nfunction structuredMutationDurabilityOptions(\n options: DocumentMutationOptions,\n update: Uint8Array,\n): Pick<SaveDocumentRecordOptions, \"historyUpdates\" | \"pendingUpdate\"> | null {\n if (options.deferRemoteSync) {\n return { historyUpdates: [bytesToBase64(update)] };\n }\n const pendingUpdate = createPendingUpdateFields(update);\n return pendingUpdate ? { pendingUpdate } : null;\n}\n\nfunction isDocumentLocalWriteCurrent(\n state: DocumentStoreState,\n writeGeneration: number,\n writeDoc: DocumentState,\n): boolean {\n return (\n state.localWriteGeneration === writeGeneration && state.doc === writeDoc\n );\n}\n\nfunction settleDocumentLocalWrite(\n state: DocumentStoreState,\n writeGeneration: number,\n): void {\n // Reset/reinitialization owns the new generation's counter. A write queued\n // against the prior document must touch neither it nor the replacement doc.\n if (state.localWriteGeneration !== writeGeneration) {\n return;\n }\n\n state.pendingLocalWrites = Math.max(0, state.pendingLocalWrites - 1);\n if (state.pendingLocalWrites !== 0 || !state.doc) {\n return;\n }\n\n // A sync pass or rotation may merge remote content while preserving the\n // controlled editor value. Publish the authoritative doc once typing drains;\n // setReadySnapshot is a no-op when the optimistic projection already matches.\n setReadySnapshot(state, state.doc, state.snapshot.syncing);\n}\n\nfunction publishDocumentTextSnapshot(\n state: DocumentStoreState,\n value: string,\n): void {\n setDocumentSnapshot(state, {\n ...state.snapshot,\n text: value,\n title: projectStoredDocumentState(\n {\n documentKind: state.snapshot.documentKind,\n structuredFields: state.snapshot.structuredFields,\n text: value,\n rows: state.snapshot.rows.map((row) => ({\n id: row.id,\n fields: row.fields,\n })),\n },\n state.runtime.infra.documentProjectors,\n ).title,\n });\n}\n\nasync function writeDocumentText(\n state: DocumentStoreState,\n writeGeneration: number,\n ticket: LocalWriteTicket,\n value: string,\n): Promise<void> {\n // A newer queued setText carries the whole latest value, and its persist\n // exports every op since pendingBaseVersion: this one has nothing to add.\n if (\n isLocalWriteSuperseded(state, ticket) ||\n state.localWriteGeneration !== writeGeneration ||\n !state.doc ||\n !canWriteDocument(state)\n ) {\n return;\n }\n const writeDoc = state.doc;\n const syncGeneration = captureDocumentStoreSyncGeneration(state, writeDoc);\n if (!syncGeneration) {\n return;\n }\n\n const textChanged = getTextValue(writeDoc) !== value;\n // Equal text still persists when an earlier write applied ops that never\n // became durable (its save failed, and the write in between was superseded):\n // this write is the last one queued to carry them. Without such edits it\n // only revalidates, so a deferred birth keeps riding the next real edit.\n if (!textChanged && !state.unsavedLocalEdits) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n if (textChanged) {\n writeDoc.getText(\"text\").update(value);\n }\n const update = pendingDeltaSinceBase(state, writeDoc);\n // Captured at delta time: the enqueued row proves durable coverage up\n // to exactly this version, so this is the frontier the persist may\n // publish (a raced later edit publishes its own on its own persist).\n const coveredVersion = encodeVersionVector(writeDoc);\n const pendingUpdate = createPendingUpdateFields(update);\n if (!pendingUpdate) {\n // Nothing outstanding to enqueue: still adopt a relinked identity.\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n const persisted = await persistDocument(\n state,\n writeDoc,\n { snapshotEndVersion: coveredVersion },\n { pendingUpdate, preserveSnapshotText: true },\n syncGeneration,\n );\n if (\n !persisted ||\n !isDocumentLocalWriteCurrent(state, writeGeneration, writeDoc)\n ) {\n return;\n }\n advancePendingBaseVersion(state, writeDoc);\n requestDocumentStoreSync(state);\n}\n\nfunction queueDocumentTextWrite(\n state: DocumentStoreState,\n value: string,\n): Promise<void> {\n if (!state.doc) {\n return Promise.resolve();\n }\n const writeGeneration = state.localWriteGeneration;\n // Supersedes every text write still queued: only the newest reaches SQLite.\n // Field, row, and attachment writes never supersede a text write.\n const ticket = issueLocalWriteTicket(state, [\"text\"]);\n\n // Mark a local edit as in flight SYNCHRONOUSLY, before chaining, so a sync\n // pass that runs during this burst sees pendingLocalWrites > 0 and preserves\n // the optimistic snapshot instead of regressing it to a stale doc read.\n state.pendingLocalWrites += 1;\n return chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(() => writeDocumentText(state, writeGeneration, ticket, value))\n // The user is already looking at this text: publishDocumentTextSnapshot ran\n // before the chain, and nothing downstream surfaces a failed persist.\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, TEXT_FAILURE_MESSAGE, error);\n })\n // Always settle, even on supersession, the value-equality short-circuit,\n // or a throw, so the current document's counter cannot stick non-zero.\n // The generation guard keeps a reset write from decrementing a\n // replacement generation.\n .finally(() => {\n settleDocumentLocalWrite(state, writeGeneration);\n }),\n );\n}\n\nfunction publishDocumentStructuredFieldSnapshot(\n state: DocumentStoreState,\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n): void {\n const nextStructuredFields: Record<string, unknown> = {\n ...state.snapshot.structuredFields,\n };\n for (const [field, value] of Object.entries(patch)) {\n if (value === undefined) {\n delete nextStructuredFields[field];\n } else {\n nextStructuredFields[field] = value;\n }\n }\n const projectedState = projectStoredDocumentState(\n {\n documentKind: kind,\n structuredFields: nextStructuredFields,\n text: state.snapshot.text,\n rows: state.snapshot.rows.map((row) => ({\n id: row.id,\n fields: row.fields,\n })),\n },\n state.runtime.infra.documentProjectors,\n );\n\n setDocumentSnapshot(state, {\n ...state.snapshot,\n documentKind: projectedState.documentKind,\n fieldValidationIssues: projectedState.fieldValidationIssues,\n structuredFields: projectedState.structuredFields,\n title: projectedState.title,\n });\n}\n\ninterface StructuredFieldWrite {\n readonly kind: Exclude<StoredDocumentKind, \"note\">;\n readonly options: DocumentMutationOptions;\n readonly patch: DocumentStructuredFieldPatch;\n /** Deferred or guarded writes neither supersede nor coalesce. */\n readonly ticket: LocalWriteTicket | null;\n readonly writeGeneration: number;\n}\n\nasync function writeDocumentStructuredFields(\n state: DocumentStoreState,\n write: StructuredFieldWrite,\n): Promise<void> {\n const { kind, options, patch, ticket, writeGeneration } = write;\n // Newer queued patches set every field of this one, and the one persisting\n // them exports every op since pendingBaseVersion: nothing to add here.\n if (\n isLocalWriteSuperseded(state, ticket) ||\n state.localWriteGeneration !== writeGeneration ||\n !state.doc ||\n !canWriteDocument(state)\n ) {\n return;\n }\n const writeDoc = state.doc;\n const syncGeneration = captureDocumentStoreSyncGeneration(state, writeDoc);\n if (!syncGeneration) {\n return;\n }\n\n if (options.stillCurrent?.() === false) return;\n writeStoredDocumentFields(\n writeDoc,\n kind,\n patch,\n state.runtime.infra.documentProjectors,\n );\n const update = pendingDeltaSinceBase(state, writeDoc);\n if (update.byteLength === 0) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n // Captured at delta time: the durable row written below (queue\n // dual-write or in-mutation tail append) proves coverage up to exactly\n // this version, so it is the frontier this persist may publish.\n const coveredVersion = encodeVersionVector(writeDoc);\n const durabilityOptions = structuredMutationDurabilityOptions(\n options,\n update,\n );\n if (!durabilityOptions) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n // A deferred write advances the record's content frontier AHEAD of the\n // outgoing queue (the op is re-derived by the next edit). Its delta\n // rides in the persist's own claimed mutation as a durable-history tail\n // row written before the record — the tail is the only content store,\n // so the record frontier must never durably lead the tail row that\n // holds its content. Passed as an option (no pre-persist await) so this\n // write adds no extra hop that would change cross-store interleaving.\n const persisted = await persistDocument(\n state,\n writeDoc,\n { snapshotEndVersion: coveredVersion },\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n ...durabilityOptions,\n },\n syncGeneration,\n );\n if (\n !persisted ||\n !isDocumentLocalWriteCurrent(state, writeGeneration, writeDoc)\n ) {\n return;\n }\n if (options.deferRemoteSync) {\n // The history tail now holds the delta; the next edit enqueues it.\n state.unsavedLocalEdits = false;\n return;\n }\n advancePendingBaseVersion(state, writeDoc);\n requestDocumentStoreSync(state);\n}\n\nfunction queueDocumentStructuredFieldWrite(\n state: DocumentStoreState,\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options: DocumentMutationOptions = {},\n): Promise<void> {\n if (!state.doc) {\n return Promise.resolve();\n }\n try {\n if (options.stillCurrent?.() === false) return Promise.resolve();\n } catch (error) {\n reportDocumentStoreWriteFailure(state, FIELD_FAILURE_MESSAGE, error);\n return Promise.resolve();\n }\n // Guarded writes publish only after admission, never while still queued.\n if (!options.stillCurrent) {\n publishDocumentStructuredFieldSnapshot(state, kind, patch);\n }\n const write: StructuredFieldWrite = {\n kind,\n options,\n patch,\n // A guarded write may later refuse, and a deferred persist is history-only:\n // neither can stand in for another write's enqueue or be coalesced away.\n ticket:\n options.deferRemoteSync || options.stillCurrent\n ? null\n : issueLocalWriteTicket(\n state,\n Object.keys(patch).map((field): LocalWriteKey => `field:${field}`),\n ),\n writeGeneration: state.localWriteGeneration,\n };\n\n // See queueDocumentTextWrite: gate sync-lane text/field republish on the same\n // in-flight-write counter so structured edits get the identical protection.\n state.pendingLocalWrites += 1;\n return chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(() => writeDocumentStructuredFields(state, write))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, FIELD_FAILURE_MESSAGE, error);\n })\n // See queueDocumentTextWrite: the final current-generation write also\n // republishes any remote content that was held during the optimistic burst.\n .finally(() => {\n settleDocumentLocalWrite(state, write.writeGeneration);\n }),\n );\n}\n\nexport function setDocumentText(\n state: DocumentStoreState,\n scheduleSync: () => void,\n value: string,\n): Promise<void> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (!state.initialized || !state.doc) {\n return ensureDocumentStoreReady(state, scheduleSync).then((ready) => {\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n publishDocumentTextSnapshot(state, value);\n return queueDocumentTextWrite(state, value);\n });\n }\n\n if (!canWriteDocument(state)) {\n return Promise.resolve();\n }\n\n publishDocumentTextSnapshot(state, value);\n return queueDocumentTextWrite(state, value);\n}\n\nexport function setDocumentStructuredFields(\n state: DocumentStoreState,\n scheduleSync: () => void,\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options: DocumentMutationOptions = {},\n): Promise<void> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (!state.initialized || !state.doc) {\n return ensureDocumentStoreReady(state, scheduleSync).then((ready) => {\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n return queueDocumentStructuredFieldWrite(state, kind, patch, options);\n });\n }\n\n if (!canWriteDocument(state)) {\n return Promise.resolve();\n }\n\n return queueDocumentStructuredFieldWrite(state, kind, patch, options);\n}\n"]}
1
+ {"version":3,"file":"mutations.js","sourceRoot":"","sources":["mutations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpE,OAAO,EACL,0BAA0B,EAE1B,yBAAyB,GAC1B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAKvD,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,GACzB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,GAGtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AACpF,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,eAAe,GAChB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,+BAA+B,EAAE,MAAM,sBAAsB,CAAC;AACvE,OAAO,EACL,gBAAgB,EAIhB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,kCAAkC,EAAE,MAAM,uBAAuB,CAAC;AAE3E,4EAA4E;AAC5E,MAAM,oBAAoB,GAAG,sCAAsC,CAAC;AACpE,MAAM,qBAAqB,GAAG,uCAAuC,CAAC;AAEtE,SAAS,mCAAmC,CAC1C,OAAgC,EAChC,MAAkB;IAElB,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;QAC5B,OAAO,EAAE,cAAc,EAAE,CAAC,aAAa,CAAC,MAAM,CAA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,wBAAwB,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE;YAClE,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;gBACrD,OAAO;YACT,CAAC;YAED,OAAO,iCAAiC,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;QACxE,CAAC,CAAC,CAAC;IACL,CAAC;IAED,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;QAC7B,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,OAAO,iCAAiC,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;AACxE,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport { encodeVersionVector, getTextValue } from \"@tearleads/loro\";\nimport {\n projectStoredDocumentState,\n type StoredDocumentKind,\n writeStoredDocumentFields,\n} from \"../../../data/documents/documentKinds\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport type {\n DocumentMutationOptions,\n DocumentStructuredFieldPatch,\n} from \"../types\";\nimport {\n ensureDocumentStoreInitialized,\n ensureDocumentStoreReady,\n} from \"./initialization\";\nimport {\n chainQueuedWrite,\n isLocalWriteSuperseded,\n issueLocalWriteTicket,\n type LocalWriteKey,\n type LocalWriteTicket,\n} from \"./localWriteQueue\";\nimport { revalidateDocumentMutationIdentity } from \"./mutationIdentityRevalidation\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"./persistence\";\nimport { reportDocumentStoreWriteFailure } from \"./reportWriteFailure\";\nimport {\n canWriteDocument,\n type DocumentState,\n type DocumentStoreState,\n type SaveDocumentRecordOptions,\n setDocumentSnapshot,\n setReadySnapshot,\n} from \"./state\";\nimport { captureDocumentStoreSyncGeneration } from \"./sync/syncGeneration\";\n\n// Fixed literals: a reported message must never carry document text or ids.\nconst TEXT_FAILURE_MESSAGE = \"Documents: local text persist failed\";\nconst FIELD_FAILURE_MESSAGE = \"Documents: local field persist failed\";\n\nfunction structuredMutationDurabilityOptions(\n options: DocumentMutationOptions,\n update: Uint8Array,\n): Pick<SaveDocumentRecordOptions, \"historyUpdates\" | \"pendingUpdate\"> | null {\n if (options.deferRemoteSync) {\n return { historyUpdates: [bytesToBase64(update)] };\n }\n const pendingUpdate = createPendingUpdateFields(update);\n return pendingUpdate ? { pendingUpdate } : null;\n}\n\nfunction isDocumentLocalWriteCurrent(\n state: DocumentStoreState,\n writeGeneration: number,\n writeDoc: DocumentState,\n): boolean {\n return (\n state.localWriteGeneration === writeGeneration && state.doc === writeDoc\n );\n}\n\nexport function settleDocumentLocalWrite(\n state: DocumentStoreState,\n writeGeneration: number,\n): void {\n // Reset/reinitialization owns the new generation's counter. A write queued\n // against the prior document must touch neither it nor the replacement doc.\n if (state.localWriteGeneration !== writeGeneration) {\n return;\n }\n\n state.pendingLocalWrites = Math.max(0, state.pendingLocalWrites - 1);\n if (state.pendingLocalWrites !== 0 || !state.doc) {\n return;\n }\n\n // A sync pass or rotation may merge remote content while preserving the\n // controlled editor value. Publish the authoritative doc once typing drains;\n // setReadySnapshot is a no-op when the optimistic projection already matches.\n setReadySnapshot(state, state.doc, state.snapshot.syncing);\n}\n\nfunction publishDocumentTextSnapshot(\n state: DocumentStoreState,\n value: string,\n): void {\n setDocumentSnapshot(state, {\n ...state.snapshot,\n text: value,\n title: projectStoredDocumentState(\n {\n documentKind: state.snapshot.documentKind,\n structuredFields: state.snapshot.structuredFields,\n text: value,\n rows: state.snapshot.rows.map((row) => ({\n id: row.id,\n fields: row.fields,\n })),\n },\n state.runtime.infra.documentProjectors,\n ).title,\n });\n}\n\nasync function writeDocumentText(\n state: DocumentStoreState,\n writeGeneration: number,\n ticket: LocalWriteTicket,\n value: string,\n): Promise<void> {\n // A newer queued setText carries the whole latest value, and its persist\n // exports every op since pendingBaseVersion: this one has nothing to add.\n if (\n isLocalWriteSuperseded(state, ticket) ||\n state.localWriteGeneration !== writeGeneration ||\n !state.doc ||\n !canWriteDocument(state)\n ) {\n return;\n }\n const writeDoc = state.doc;\n const syncGeneration = captureDocumentStoreSyncGeneration(state, writeDoc);\n if (!syncGeneration) {\n return;\n }\n\n const textChanged = getTextValue(writeDoc) !== value;\n // Equal text still persists when an earlier write applied ops that never\n // became durable (its save failed, and the write in between was superseded):\n // this write is the last one queued to carry them. Without such edits it\n // only revalidates, so a deferred birth keeps riding the next real edit.\n if (!textChanged && !state.unsavedLocalEdits) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n if (textChanged) {\n writeDoc.getText(\"text\").update(value);\n }\n const update = pendingDeltaSinceBase(state, writeDoc);\n // Captured at delta time: the enqueued row proves durable coverage up\n // to exactly this version, so this is the frontier the persist may\n // publish (a raced later edit publishes its own on its own persist).\n const coveredVersion = encodeVersionVector(writeDoc);\n const pendingUpdate = createPendingUpdateFields(update);\n if (!pendingUpdate) {\n // Nothing outstanding to enqueue: still adopt a relinked identity.\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n const persisted = await persistDocument(\n state,\n writeDoc,\n { snapshotEndVersion: coveredVersion },\n { pendingUpdate, preserveSnapshotText: true },\n syncGeneration,\n );\n if (\n !persisted ||\n !isDocumentLocalWriteCurrent(state, writeGeneration, writeDoc)\n ) {\n return;\n }\n advancePendingBaseVersion(state, writeDoc);\n requestDocumentStoreSync(state);\n}\n\nfunction queueDocumentTextWrite(\n state: DocumentStoreState,\n value: string,\n): Promise<void> {\n if (!state.doc) {\n return Promise.resolve();\n }\n const writeGeneration = state.localWriteGeneration;\n // Supersedes every text write still queued: only the newest reaches SQLite.\n // Field, row, and attachment writes never supersede a text write.\n const ticket = issueLocalWriteTicket(state, [\"text\"]);\n\n // Mark a local edit as in flight SYNCHRONOUSLY, before chaining, so a sync\n // pass that runs during this burst sees pendingLocalWrites > 0 and preserves\n // the optimistic snapshot instead of regressing it to a stale doc read.\n state.pendingLocalWrites += 1;\n return chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(() => writeDocumentText(state, writeGeneration, ticket, value))\n // The user is already looking at this text: publishDocumentTextSnapshot ran\n // before the chain, and nothing downstream surfaces a failed persist.\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, TEXT_FAILURE_MESSAGE, error);\n })\n // Always settle, even on supersession, the value-equality short-circuit,\n // or a throw, so the current document's counter cannot stick non-zero.\n // The generation guard keeps a reset write from decrementing a\n // replacement generation.\n .finally(() => {\n settleDocumentLocalWrite(state, writeGeneration);\n }),\n );\n}\n\nfunction publishDocumentStructuredFieldSnapshot(\n state: DocumentStoreState,\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n): void {\n const nextStructuredFields: Record<string, unknown> = {\n ...state.snapshot.structuredFields,\n };\n for (const [field, value] of Object.entries(patch)) {\n if (value === undefined) {\n delete nextStructuredFields[field];\n } else {\n nextStructuredFields[field] = value;\n }\n }\n const projectedState = projectStoredDocumentState(\n {\n documentKind: kind,\n structuredFields: nextStructuredFields,\n text: state.snapshot.text,\n rows: state.snapshot.rows.map((row) => ({\n id: row.id,\n fields: row.fields,\n })),\n },\n state.runtime.infra.documentProjectors,\n );\n\n setDocumentSnapshot(state, {\n ...state.snapshot,\n documentKind: projectedState.documentKind,\n fieldValidationIssues: projectedState.fieldValidationIssues,\n structuredFields: projectedState.structuredFields,\n title: projectedState.title,\n });\n}\n\ninterface StructuredFieldWrite {\n readonly kind: Exclude<StoredDocumentKind, \"note\">;\n readonly options: DocumentMutationOptions;\n readonly patch: DocumentStructuredFieldPatch;\n /** Deferred or guarded writes neither supersede nor coalesce. */\n readonly ticket: LocalWriteTicket | null;\n readonly writeGeneration: number;\n}\n\nasync function writeDocumentStructuredFields(\n state: DocumentStoreState,\n write: StructuredFieldWrite,\n): Promise<void> {\n const { kind, options, patch, ticket, writeGeneration } = write;\n // Newer queued patches set every field of this one, and the one persisting\n // them exports every op since pendingBaseVersion: nothing to add here.\n if (\n isLocalWriteSuperseded(state, ticket) ||\n state.localWriteGeneration !== writeGeneration ||\n !state.doc ||\n !canWriteDocument(state)\n ) {\n return;\n }\n const writeDoc = state.doc;\n const syncGeneration = captureDocumentStoreSyncGeneration(state, writeDoc);\n if (!syncGeneration) {\n return;\n }\n\n if (options.stillCurrent?.() === false) return;\n writeStoredDocumentFields(\n writeDoc,\n kind,\n patch,\n state.runtime.infra.documentProjectors,\n );\n const update = pendingDeltaSinceBase(state, writeDoc);\n if (update.byteLength === 0) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n // Captured at delta time: the durable row written below (queue\n // dual-write or in-mutation tail append) proves coverage up to exactly\n // this version, so it is the frontier this persist may publish.\n const coveredVersion = encodeVersionVector(writeDoc);\n const durabilityOptions = structuredMutationDurabilityOptions(\n options,\n update,\n );\n if (!durabilityOptions) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n // A deferred write advances the record's content frontier AHEAD of the\n // outgoing queue (the op is re-derived by the next edit). Its delta\n // rides in the persist's own claimed mutation as a durable-history tail\n // row written before the record — the tail is the only content store,\n // so the record frontier must never durably lead the tail row that\n // holds its content. Passed as an option (no pre-persist await) so this\n // write adds no extra hop that would change cross-store interleaving.\n const persisted = await persistDocument(\n state,\n writeDoc,\n { snapshotEndVersion: coveredVersion },\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n ...durabilityOptions,\n },\n syncGeneration,\n );\n if (\n !persisted ||\n !isDocumentLocalWriteCurrent(state, writeGeneration, writeDoc)\n ) {\n return;\n }\n if (options.deferRemoteSync) {\n // The history tail now holds the delta; the next edit enqueues it.\n state.unsavedLocalEdits = false;\n return;\n }\n advancePendingBaseVersion(state, writeDoc);\n requestDocumentStoreSync(state);\n}\n\nfunction queueDocumentStructuredFieldWrite(\n state: DocumentStoreState,\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options: DocumentMutationOptions = {},\n): Promise<void> {\n if (!state.doc) {\n return Promise.resolve();\n }\n try {\n if (options.stillCurrent?.() === false) return Promise.resolve();\n } catch (error) {\n reportDocumentStoreWriteFailure(state, FIELD_FAILURE_MESSAGE, error);\n return Promise.resolve();\n }\n // Guarded writes publish only after admission, never while still queued.\n if (!options.stillCurrent) {\n publishDocumentStructuredFieldSnapshot(state, kind, patch);\n }\n const write: StructuredFieldWrite = {\n kind,\n options,\n patch,\n // A guarded write may later refuse, and a deferred persist is history-only:\n // neither can stand in for another write's enqueue or be coalesced away.\n ticket:\n options.deferRemoteSync || options.stillCurrent\n ? null\n : issueLocalWriteTicket(\n state,\n Object.keys(patch).map((field): LocalWriteKey => `field:${field}`),\n ),\n writeGeneration: state.localWriteGeneration,\n };\n\n // See queueDocumentTextWrite: gate sync-lane text/field republish on the same\n // in-flight-write counter so structured edits get the identical protection.\n state.pendingLocalWrites += 1;\n return chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(() => writeDocumentStructuredFields(state, write))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, FIELD_FAILURE_MESSAGE, error);\n })\n // See queueDocumentTextWrite: the final current-generation write also\n // republishes any remote content that was held during the optimistic burst.\n .finally(() => {\n settleDocumentLocalWrite(state, write.writeGeneration);\n }),\n );\n}\n\nexport function setDocumentText(\n state: DocumentStoreState,\n scheduleSync: () => void,\n value: string,\n): Promise<void> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (!state.initialized || !state.doc) {\n return ensureDocumentStoreReady(state, scheduleSync).then((ready) => {\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n publishDocumentTextSnapshot(state, value);\n return queueDocumentTextWrite(state, value);\n });\n }\n\n if (!canWriteDocument(state)) {\n return Promise.resolve();\n }\n\n publishDocumentTextSnapshot(state, value);\n return queueDocumentTextWrite(state, value);\n}\n\nexport function setDocumentStructuredFields(\n state: DocumentStoreState,\n scheduleSync: () => void,\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options: DocumentMutationOptions = {},\n): Promise<void> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (!state.initialized || !state.doc) {\n return ensureDocumentStoreReady(state, scheduleSync).then((ready) => {\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n return queueDocumentStructuredFieldWrite(state, kind, patch, options);\n });\n }\n\n if (!canWriteDocument(state)) {\n return Promise.resolve();\n }\n\n return queueDocumentStructuredFieldWrite(state, kind, patch, options);\n}\n"]}
@@ -131,4 +131,12 @@ export async function removeRowFromDocumentStore(state, scheduleSync, id, option
131
131
  }
132
132
  await queueRowMutation(state, (doc) => removeDocumentRow(doc, id), options);
133
133
  }
134
+ /** The store's row writes, each counted and run on the live sync lane. */
135
+ export function createRowWrites(state, scheduleSync, liveWrite) {
136
+ return {
137
+ addRow: (fields, options) => liveWrite(() => addRowToDocumentStore(state, scheduleSync, fields, options)),
138
+ removeRow: (id, options) => liveWrite(() => removeRowFromDocumentStore(state, scheduleSync, id, options)),
139
+ updateRowFields: (id, patch, options) => liveWrite(() => updateRowInDocumentStore(state, scheduleSync, id, patch, options)),
140
+ };
141
+ }
134
142
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO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AAO,KAAK,EAAE,CAAC;QACf,+BAA+B,CAAC,KAAK,EAAE,mBAAmB,EAAE,KAAK,CAAC,CAAC;QACnE,OAAO;IACT,CAAC;IAED,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;QACrD,OAAO;IACT,CAAC;IAED,MAAM,gBAAgB,CAAC,KAAK,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,iBAAiB,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport {\n addDocumentRow,\n createDocumentRowId,\n removeDocumentRow,\n setDocumentRowFields,\n} from \"../../../../data/documents/documentRowList\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport type { DocumentMutationGuard } from \"../../types\";\nimport { ensureDocumentStoreReady } from \"../initialization\";\nimport { chainQueuedWrite } from \"../localWriteQueue\";\nimport { revalidateDocumentMutationIdentity } from \"../mutationIdentityRevalidation\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"../persistence\";\nimport { reportDocumentStoreWriteFailure } from \"../reportWriteFailure\";\nimport {\n canWriteDocument,\n type DocumentState,\n type DocumentStoreState,\n} from \"../state\";\nimport {\n captureDocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { resolveRowAttribution } from \"./rowAttribution\";\n\n// Fixed literal: a reported message must never carry row ids or field values.\nconst ROW_FAILURE_MESSAGE = \"Documents: row mutation failed\";\n\nasync function persistRowMutation(\n state: DocumentStoreState,\n expectedLocalWriteGeneration: number,\n mutate: (doc: DocumentState) => boolean,\n options: DocumentMutationGuard,\n): Promise<void> {\n if (state.localWriteGeneration !== expectedLocalWriteGeneration) {\n return;\n }\n const currentDoc = state.doc;\n if (!currentDoc || !canWriteDocument(state)) {\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n if (options.stillCurrent?.() === false) return;\n if (!mutate(currentDoc)) {\n await revalidateDocumentMutationIdentity({ currentDoc, generation, state });\n return;\n }\n\n const update = pendingDeltaSinceBase(state, currentDoc);\n if (update.byteLength === 0) {\n await revalidateDocumentMutationIdentity({ currentDoc, generation, state });\n return;\n }\n // Captured at delta time: the enqueued row proves coverage up to exactly\n // this version, so it is the frontier the persist below may publish.\n const coveredVersion = encodeVersionVector(currentDoc);\n\n const pendingUpdate = createPendingUpdateFields(update);\n if (!pendingUpdate) {\n await revalidateDocumentMutationIdentity({ currentDoc, generation, state });\n return;\n }\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n // Row writes change neither prose nor structured fields; setReadySnapshot\n // always re-derives rows from the doc, so preserve the text/structured fields\n // in case this write overlaps an in-flight keystroke elsewhere.\n const persisted = await persistDocument(\n state,\n currentDoc,\n { snapshotEndVersion: coveredVersion },\n {\n pendingUpdate,\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n generation,\n );\n if (\n !persisted ||\n persisted.pullContinuationSuperseded ||\n persisted.syncIdentitySuperseded ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n // Refused: the document was deleted while this persist was queued\n // and the store is cleared — no state advance, no sync request.\n return;\n }\n advancePendingBaseVersion(state, currentDoc);\n requestDocumentStoreSync(state);\n}\n\nfunction queueRowMutation(\n state: DocumentStoreState,\n mutate: (doc: DocumentState) => boolean,\n options: DocumentMutationGuard,\n): Promise<void> {\n const writeGeneration = state.localWriteGeneration;\n // Unlike text/structured-field writes, row writes intentionally do NOT bump\n // `state.pendingLocalWrites`: rows are never in the optimistic-preserve set —\n // `setReadySnapshot` always re-derives them from the doc — so there is no\n // optimistic snapshot for a concurrent sync pass to clobber. Input smoothness\n // during rapid edits is handled in the app layer (useDocumentRowEditing).\n return chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(() => persistRowMutation(state, writeGeneration, mutate, options))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n }),\n );\n}\n\nexport async function addRowToDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n fields: Readonly<Record<string, string>>,\n options: DocumentMutationGuard = {},\n): Promise<string> {\n const id = createDocumentRowId();\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n return id;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return id;\n }\n\n await queueRowMutation(\n state,\n (doc) => {\n addDocumentRow(doc, id, fields, resolveRowAttribution(state));\n return true;\n },\n options,\n );\n return id;\n}\n\nexport async function updateRowInDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n id: string,\n patch: Readonly<Record<string, string>>,\n options: DocumentMutationGuard = {},\n): Promise<void> {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n await queueRowMutation(\n state,\n (doc) => setDocumentRowFields(doc, id, patch, resolveRowAttribution(state)),\n options,\n );\n}\n\nexport async function removeRowFromDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n id: string,\n options: DocumentMutationGuard = {},\n): Promise<void> {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n await queueRowMutation(state, (doc) => removeDocumentRow(doc, id), options);\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,GACrB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAE1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,kCAAkC,EAAE,MAAM,iCAAiC,CAAC;AACrF,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,eAAe,GAChB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,+BAA+B,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,EACL,gBAAgB,GAGjB,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,kCAAkC,EAClC,oCAAoC,GACrC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,8EAA8E;AAC9E,MAAM,mBAAmB,GAAG,gCAAgC,CAAC;AAE7D,KAAK,UAAU,kBAAkB,CAC/B,KAAyB,EACzB,4BAAoC,EACpC,MAAuC,EACvC,OAA8B;IAE9B,IAAI,KAAK,CAAC,oBAAoB,KAAK,4BAA4B,EAAE,CAAC;QAChE,OAAO;IACT,CAAC;IACD,MAAM,UAAU,GAAG,KAAK,CAAC,GAAG,CAAC;IAC7B,IAAI,CAAC,UAAU,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5C,OAAO;IACT,CAAC;IACD,MAAM,UAAU,GA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n addDocumentRow,\n createDocumentRowId,\n removeDocumentRow,\n setDocumentRowFields,\n} from \"../../../../data/documents/documentRowList\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport type { DocumentMutationGuard, DocumentStore } from \"../../types\";\nimport { ensureDocumentStoreReady } from \"../initialization\";\nimport { chainQueuedWrite } from \"../localWriteQueue\";\nimport { revalidateDocumentMutationIdentity } from \"../mutationIdentityRevalidation\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"../persistence\";\nimport { reportDocumentStoreWriteFailure } from \"../reportWriteFailure\";\nimport {\n canWriteDocument,\n type DocumentState,\n type DocumentStoreState,\n} from \"../state\";\nimport {\n captureDocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { resolveRowAttribution } from \"./rowAttribution\";\n\n// Fixed literal: a reported message must never carry row ids or field values.\nconst ROW_FAILURE_MESSAGE = \"Documents: row mutation failed\";\n\nasync function persistRowMutation(\n state: DocumentStoreState,\n expectedLocalWriteGeneration: number,\n mutate: (doc: DocumentState) => boolean,\n options: DocumentMutationGuard,\n): Promise<void> {\n if (state.localWriteGeneration !== expectedLocalWriteGeneration) {\n return;\n }\n const currentDoc = state.doc;\n if (!currentDoc || !canWriteDocument(state)) {\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n if (options.stillCurrent?.() === false) return;\n if (!mutate(currentDoc)) {\n await revalidateDocumentMutationIdentity({ currentDoc, generation, state });\n return;\n }\n\n const update = pendingDeltaSinceBase(state, currentDoc);\n if (update.byteLength === 0) {\n await revalidateDocumentMutationIdentity({ currentDoc, generation, state });\n return;\n }\n // Captured at delta time: the enqueued row proves coverage up to exactly\n // this version, so it is the frontier the persist below may publish.\n const coveredVersion = encodeVersionVector(currentDoc);\n\n const pendingUpdate = createPendingUpdateFields(update);\n if (!pendingUpdate) {\n await revalidateDocumentMutationIdentity({ currentDoc, generation, state });\n return;\n }\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n // Row writes change neither prose nor structured fields; setReadySnapshot\n // always re-derives rows from the doc, so preserve the text/structured fields\n // in case this write overlaps an in-flight keystroke elsewhere.\n const persisted = await persistDocument(\n state,\n currentDoc,\n { snapshotEndVersion: coveredVersion },\n {\n pendingUpdate,\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n generation,\n );\n if (\n !persisted ||\n persisted.pullContinuationSuperseded ||\n persisted.syncIdentitySuperseded ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n // Refused: the document was deleted while this persist was queued\n // and the store is cleared — no state advance, no sync request.\n return;\n }\n advancePendingBaseVersion(state, currentDoc);\n requestDocumentStoreSync(state);\n}\n\nfunction queueRowMutation(\n state: DocumentStoreState,\n mutate: (doc: DocumentState) => boolean,\n options: DocumentMutationGuard,\n): Promise<void> {\n const writeGeneration = state.localWriteGeneration;\n // Unlike text/structured-field writes, row writes intentionally do NOT bump\n // `state.pendingLocalWrites`: rows are never in the optimistic-preserve set —\n // `setReadySnapshot` always re-derives them from the doc — so there is no\n // optimistic snapshot for a concurrent sync pass to clobber. Input smoothness\n // during rapid edits is handled in the app layer (useDocumentRowEditing).\n return chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(() => persistRowMutation(state, writeGeneration, mutate, options))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n }),\n );\n}\n\nexport async function addRowToDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n fields: Readonly<Record<string, string>>,\n options: DocumentMutationGuard = {},\n): Promise<string> {\n const id = createDocumentRowId();\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n return id;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return id;\n }\n\n await queueRowMutation(\n state,\n (doc) => {\n addDocumentRow(doc, id, fields, resolveRowAttribution(state));\n return true;\n },\n options,\n );\n return id;\n}\n\nexport async function updateRowInDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n id: string,\n patch: Readonly<Record<string, string>>,\n options: DocumentMutationGuard = {},\n): Promise<void> {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n await queueRowMutation(\n state,\n (doc) => setDocumentRowFields(doc, id, patch, resolveRowAttribution(state)),\n options,\n );\n}\n\nexport async function removeRowFromDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n id: string,\n options: DocumentMutationGuard = {},\n): Promise<void> {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n await queueRowMutation(state, (doc) => removeDocumentRow(doc, id), options);\n}\n\n/** The store's row writes, each counted and run on the live sync lane. */\nexport function createRowWrites(\n state: DocumentStoreState,\n scheduleSync: () => void,\n liveWrite: <Result>(write: () => Promise<Result>) => Promise<Result>,\n): Pick<DocumentStore, \"addRow\" | \"removeRow\" | \"updateRowFields\"> {\n return {\n addRow: (fields, options) =>\n liveWrite(() =>\n addRowToDocumentStore(state, scheduleSync, fields, options),\n ),\n removeRow: (id, options) =>\n liveWrite(() =>\n removeRowFromDocumentStore(state, scheduleSync, id, options),\n ),\n updateRowFields: (id, patch, options) =>\n liveWrite(() =>\n updateRowInDocumentStore(state, scheduleSync, id, patch, options),\n ),\n };\n}\n"]}
@@ -207,6 +207,7 @@ export function createDocumentStoreFacade(initialStore) {
207
207
  requestSync: () => targetStore.requestSync(),
208
208
  relink: (input) => targetStore.relink(input),
209
209
  rebindTo: (store) => connectTarget(store),
210
+ restoreContent: (content, options) => targetStore.restoreContent(content, options),
210
211
  setStructuredFields: (kind, patch, options) => targetStore.setStructuredFields(kind, patch, options),
211
212
  setText: (value) => targetStore.setText(value),
212
213
  subscribe: (listener) => {
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","sourceRoot":"","sources":["registry.ts"],"names":[],"mappings":"AACA,OAAO,EACL,8BAA8B,EAC9B,uCAAuC,GACxC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AAwBpE,MAAM,8BAA8B,GAAG,IAAI,OAAO,EAG/C,CAAC;AAGJ,mEAAmE;AACnE,qEAAqE;AACrE,wEAAwE;AACxE,SAAS,4BAA4B;IAGnC,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAA8B,CAAC;IAEnE,OAAO;QACL,IAAI,EAAE,CAAC,WAAwB,EAAE,GAAG,IAA0B,EAAQ,EAAE;YACtE,MAAM,SAAS,GAAG,gBAAgB,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;YACpD,IAAI,CAAC,SAAS,EAAE,CAAC;gBACf,OAAO;YACT,CAAC;YAED,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;gBACjC,QAAQ,CAAC,GAAG,IAAI,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;QACD,SAAS,EAAE,CAAC,WAAwB,EAAE,QAAkB,EAAgB,EAAE;YACxE,MAAM,SAAS,GACb,gBAAgB,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,IAAI,GAAG,EAAY,CAAC;YAC3D,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxB,gBAAgB,CAAC,GAAG,C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IAAI,CAAC,YAAY,EAAE,EAAE,CAAC;QAC7C,QAAQ,CAAC,aAAa,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACxC,KAAK,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n registerInternalDocumentRelink,\n relinkDocumentStoreWithCommitSideEffect,\n} from \"./documentStore/internalRelink\";\nimport { createRemovedDocumentStore } from \"./removedDocumentStore\";\nimport type {\n DocumentAttachmentUpload,\n DocumentStore,\n DocumentStoreFacade,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"./types\";\n\ninterface DocumentStoreRegistry {\n /** How the last open built each store's backing store, by store key. */\n freshStoreFactories: Map<string, () => DocumentStore>;\n /** Each backing store's way to stop its sync lane, by local id. */\n retireHandlersByLocalId: Map<string, () => void>;\n /**\n * Stores whose document was removed under them, each with whether its\n * removal still holds; see retireDocumentStore.\n */\n retiredStores: Map<string, () => boolean>;\n storeKeysByDocumentId: Map<string, string>;\n storeKeysByLocalId: Map<string, string>;\n storesByKey: Map<string, DocumentStoreFacade>;\n}\n\nconst documentStoreRegistriesByScope = new WeakMap<\n DomainScope,\n DocumentStoreRegistry\n>();\ntype PersistedDocumentDeletionListener = (localId: string) => void;\n\n// Per-scope listener plumbing shared by the persisted-document and\n// persisted-document-deletion channels: emit fans out to the scope's\n// listeners, and unsubscribing the last listener drops the scope entry.\nfunction createScopedListenerRegistry<\n Listener extends (...args: never[]) => void,\n>() {\n const listenersByScope = new WeakMap<DomainScope, Set<Listener>>();\n\n return {\n emit: (domainScope: DomainScope, ...args: Parameters<Listener>): void => {\n const listeners = listenersByScope.get(domainScope);\n if (!listeners) {\n return;\n }\n\n for (const listener of listeners) {\n listener(...args);\n }\n },\n subscribe: (domainScope: DomainScope, listener: Listener): (() => void) => {\n const listeners =\n listenersByScope.get(domainScope) ?? new Set<Listener>();\n listeners.add(listener);\n listenersByScope.set(domainScope, listeners);\n\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n listenersByScope.delete(domainScope);\n }\n };\n },\n };\n}\n\nconst persistedDocumentListeners =\n createScopedListenerRegistry<PersistedDocumentListener>();\nconst persistedDocumentDeletionListeners =\n createScopedListenerRegistry<PersistedDocumentDeletionListener>();\n\nexport function getOrCreateDocumentStoreRegistry(\n domainScope: DomainScope,\n): DocumentStoreRegistry {\n const existingRegistry = documentStoreRegistriesByScope.get(domainScope);\n if (existingRegistry) {\n return existingRegistry;\n }\n\n const nextRegistry: DocumentStoreRegistry = {\n freshStoreFactories: new Map(),\n retireHandlersByLocalId: new Map(),\n retiredStores: new Map(),\n storeKeysByDocumentId: new Map(),\n storeKeysByLocalId: new Map(),\n storesByKey: new Map(),\n };\n documentStoreRegistriesByScope.set(domainScope, nextRegistry);\n return nextRegistry;\n}\n\nexport function resolveDocumentStoreKey(\n registry: DocumentStoreRegistry,\n localId: string,\n documentId: string | null,\n): string {\n return (\n (documentId ? registry.storeKeysByDocumentId.get(documentId) : undefined) ??\n registry.storeKeysByLocalId.get(localId) ??\n localId\n );\n}\n\nexport function registerDocumentStore(\n domainScope: DomainScope,\n localId: string,\n store: DocumentStoreFacade,\n documentId: string | null,\n) {\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const storeKey = resolveDocumentStoreKey(registry, localId, documentId);\n registry.storeKeysByLocalId.set(localId, storeKey);\n if (documentId) {\n registry.storeKeysByDocumentId.set(documentId, storeKey);\n }\n registry.storesByKey.set(storeKey, store);\n}\n\nexport function registerDocumentStoreIdentity(\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n) {\n if (!documentId) {\n return;\n }\n\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const localStoreKey = registry.storeKeysByLocalId.get(localId) ?? localId;\n const documentStoreKey =\n registry.storeKeysByDocumentId.get(documentId) ?? documentId;\n\n registry.storeKeysByLocalId.set(localId, documentStoreKey);\n registry.storeKeysByDocumentId.set(documentId, documentStoreKey);\n\n if (documentStoreKey === localStoreKey) {\n return;\n }\n\n const localStore = registry.storesByKey.get(localStoreKey);\n const documentStore = registry.storesByKey.get(documentStoreKey);\n if (localStore) {\n documentStore?.rebindTo(localStore);\n registry.storesByKey.set(documentStoreKey, localStore);\n // The store's retirement and how to rebuild it move with it.\n moveKeyedEntry(\n registry.freshStoreFactories,\n localStoreKey,\n documentStoreKey,\n );\n moveKeyedEntry(registry.retiredStores, localStoreKey, documentStoreKey);\n }\n registry.storesByKey.delete(localStoreKey);\n}\n\nfunction moveKeyedEntry<Value>(\n entries: Map<string, Value>,\n fromKey: string,\n toKey: string,\n): void {\n const value = entries.get(fromKey);\n entries.delete(fromKey);\n if (value !== undefined) entries.set(toKey, value);\n}\n\n/**\n * Whether an open store holds local writes for the document that have not\n * reached SQLite yet, which no persisted-write scan can see.\n */\nexport function hasQueuedDocumentStoreWrites(\n domainScope: DomainScope,\n localId: string,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n return registry?.storesByKey.get(storeKey)?.hasQueuedWrites() ?? false;\n}\n\n/**\n * Whether any open store in `domainScope` holds local edits that have not\n * reached SQLite yet — queued writes, or applied edits whose save failed — so\n * a host can warn before an unload loses them. A retired store reads through\n * its removed stand-in, which holds none: the document it stood for is gone.\n */\nexport function hasPendingLocalDocumentWrites(\n domainScope: DomainScope,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) return false;\n for (const store of registry.storesByKey.values()) {\n if (store.hasQueuedWrites() || store.hasUnsavedLocalEdits()) return true;\n }\n return false;\n}\n\nexport function requestDocumentStoreSync(state: {\n syncLane: {\n requestSync: () => void;\n } | null;\n}) {\n state.syncLane?.requestSync();\n}\n\nexport function requestRegisteredDocumentRemoteSync(\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return false;\n }\n\n const storeKey = resolveDocumentStoreKey(registry, localId, documentId);\n const store = registry.storesByKey.get(storeKey);\n if (!store || registry.retiredStores.has(storeKey)) {\n return false;\n }\n\n // Explicit refresh uses this path to recover missed websocket invalidations\n // without instantiating every unopened document discovered in the container.\n store.requestRemoteSync();\n return true;\n}\n\n/**\n * Discard a registered document's local edits through its store, so the\n * teardown serializes on the store's write machinery instead of racing an\n * in-flight persist that would resurrect the deleted rows. Only registered\n * stores qualify — an unregistered document has no lane submitting its queue,\n * so there is nothing this escape hatch could unstick. No deletion is\n * emitted: the document survives as a re-seeded shell that keeps its listing\n * entry, and the re-pull's own persist announces the restored content.\n *\n * Resolution is strict, unlike the read-side lookups: a destructive action\n * must never run against whichever store won a lookup priority. Both\n * identifiers must map to the SAME registered store — an unknown or stale\n * documentId refuses rather than trusting the localId alone — and the store\n * revalidates the expected documentId against its persisted record inside\n * the teardown's serialized mutation, so even a stale registry mapping\n * cannot discard a different identity's edits.\n */\nexport async function discardRegisteredDocumentLocalState(\n domainScope: DomainScope,\n localId: string,\n documentId: string,\n): Promise<boolean> {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return false;\n }\n\n const localStoreKey = registry.storeKeysByLocalId.get(localId);\n const documentStoreKey = registry.storeKeysByDocumentId.get(documentId);\n if (\n !localStoreKey ||\n !documentStoreKey ||\n documentStoreKey !== localStoreKey\n ) {\n return false;\n }\n const store = registry.storesByKey.get(localStoreKey);\n if (!store) {\n return false;\n }\n\n return store.discardLocalState(documentId);\n}\n\nexport function createDocumentStoreFacade(\n initialStore: DocumentStore,\n): DocumentStoreFacade {\n let targetStore = initialStore;\n const listeners = new Set<() => void>();\n\n const emitFacade = () => {\n for (const listener of listeners) {\n listener();\n }\n };\n\n let unsubscribeTarget = targetStore.subscribe(() => {\n emitFacade();\n });\n\n const connectTarget = (nextStore: DocumentStore) => {\n if (targetStore === nextStore) {\n return;\n }\n\n unsubscribeTarget();\n targetStore = nextStore;\n unsubscribeTarget = targetStore.subscribe(() => {\n emitFacade();\n });\n emitFacade();\n };\n\n const facade: DocumentStoreFacade = {\n addRow: (fields, options) => targetStore.addRow(fields, options),\n assertCanRotateContentKey: (proof) =>\n targetStore.assertCanRotateContentKey(proof),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n targetStore.attachFiles(files),\n discardLocalState: (expectedDocumentId: string) =>\n targetStore.discardLocalState(expectedDocumentId),\n ensureInitialized: () => targetStore.ensureInitialized(),\n getSnapshot: () => targetStore.getSnapshot(),\n hasQueuedWrites: () => targetStore.hasQueuedWrites(),\n hasUnsavedLocalEdits: () => targetStore.hasUnsavedLocalEdits(),\n removeAttachment: (slotId: string) => targetStore.removeAttachment(slotId),\n removeRow: (id, options) => targetStore.removeRow(id, options),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n targetStore.replaceAttachment(slotId, file),\n requestRemoteSync: () => targetStore.requestRemoteSync(),\n requestRemoteSyncAndWait: (signal) =>\n targetStore.requestRemoteSyncAndWait(signal),\n requestSync: () => targetStore.requestSync(),\n relink: (input) => targetStore.relink(input),\n rebindTo: (store) => connectTarget(store),\n setStructuredFields: (kind, patch, options) =>\n targetStore.setStructuredFields(kind, patch, options),\n setText: (value: string) => targetStore.setText(value),\n subscribe: (listener: () => void) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n updateRowFields: (id, patch, options) =>\n targetStore.updateRowFields(id, patch, options),\n updateRuntime: (runtime: DocumentsRuntime) =>\n targetStore.updateRuntime(runtime),\n };\n registerInternalDocumentRelink(facade, (input, commitSideEffect) =>\n relinkDocumentStoreWithCommitSideEffect(\n targetStore,\n input,\n commitSideEffect,\n ),\n );\n return facade;\n}\n\nexport function emitPersistedDocument(\n domainScope: DomainScope,\n persistedDocument: Parameters<PersistedDocumentListener>[0],\n placementChanged = false,\n): void {\n persistedDocumentListeners.emit(domainScope, persistedDocument, {\n placementChanged,\n });\n}\n\nexport function subscribeToPersistedDocuments(\n domainScope: DomainScope,\n listener: PersistedDocumentListener,\n): () => void {\n return persistedDocumentListeners.subscribe(domainScope, listener);\n}\n\nexport function emitPersistedDocumentDeletion(\n domainScope: DomainScope,\n localId: string,\n): void {\n persistedDocumentDeletionListeners.emit(domainScope, localId);\n}\n\nexport function subscribeToPersistedDocumentDeletions(\n domainScope: DomainScope,\n listener: PersistedDocumentDeletionListener,\n): () => void {\n return persistedDocumentDeletionListeners.subscribe(domainScope, listener);\n}\n\nexport function requestDomainDocumentSync(domainScope: DomainScope): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return;\n }\n\n for (const [storeKey, store] of registry.storesByKey) {\n if (!registry.retiredStores.has(storeKey)) store.requestSync();\n }\n}\n\n/** Lets the backing store for `localId` stop its sync lane when retired. */\nexport function onDocumentStoreRetired(\n domainScope: DomainScope,\n localId: string,\n stopSyncLane: () => void,\n): void {\n getOrCreateDocumentStoreRegistry(domainScope).retireHandlersByLocalId.set(\n localId,\n stopSyncLane,\n );\n}\n\n/**\n * Retires the store of a document a paused organization's cleanup removed.\n * Its backing store's sync lane stops and the facade an editor may hold\n * switches to a read-only stand-in, so nothing recreates or downloads the\n * document. While `stillRemoved()` holds, reopening returns the stand-in;\n * after that, the next open rebinds the facade to a fresh backing store that\n * loads whatever SQLite holds by then, such as a copy rediscovered on resume.\n */\nexport function retireDocumentStore(\n domainScope: DomainScope,\n localId: string,\n stillRemoved: () => boolean,\n): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n const store = registry?.storesByKey.get(storeKey);\n if (!registry || !store || registry.retiredStores.has(storeKey)) return;\n registry.retireHandlersByLocalId.get(localId)?.();\n store.rebindTo(createRemovedDocumentStore(store.getSnapshot()));\n registry.retiredStores.set(storeKey, stillRemoved);\n}\n\n/**\n * Undoes a retirement whose deletion did not commit: the document survives,\n * so its facade gets a fresh backing store again.\n */\nexport function restoreDocumentStore(\n domainScope: DomainScope,\n localId: string,\n): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n const store = registry?.storesByKey.get(storeKey);\n if (!registry || !store || !registry.retiredStores.delete(storeKey)) return;\n const createFresh = registry.freshStoreFactories.get(storeKey);\n // Without a factory the next open rebinds it instead.\n if (createFresh) store.rebindTo(createFresh());\n else registry.retiredStores.set(storeKey, () => false);\n}\n\n/** The registered store for a key, rebound once its removal has lifted. */\nexport function takeRegisteredDocumentStore(\n registry: DocumentStoreRegistry,\n storeKey: string,\n createFresh: () => DocumentStore,\n): DocumentStoreFacade | undefined {\n registry.freshStoreFactories.set(storeKey, createFresh);\n const store = registry.storesByKey.get(storeKey);\n const stillRemoved = registry.retiredStores.get(storeKey);\n if (store && stillRemoved && !stillRemoved()) {\n registry.retiredStores.delete(storeKey);\n store.rebindTo(createFresh());\n }\n return store;\n}\n"]}
1
+ {"version":3,"file":"registry.js","sourceRoot":"","sources":["registry.ts"],"names":[],"mappings":"AACA,OAAO,EACL,8BAA8B,EAC9B,uCAAuC,GACxC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AAwBpE,MAAM,8BAA8B,GAAG,IAAI,OAAO,EAG/C,CAAC;AAGJ,mEAAmE;AACnE,qEAAqE;AACrE,wEAAwE;AACxE,SAAS,4BAA4B;IAGnC,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAA8B,CAAC;IAEnE,OAAO;QACL,IAAI,EAAE,CAAC,WAAwB,EAAE,GAAG,IAA0B,EAAQ,EAAE;YACtE,MAAM,SAAS,GAAG,gBAAgB,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;YACpD,IAAI,CAAC,SAAS,EAAE,CAAC;gBACf,OAAO;YACT,CAAC;YAED,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;gBACjC,QAAQ,CAAC,GAAG,IAAI,CA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AC;AACzD,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,2BAA2B,CACzC,QAA+B,EAC/B,QAAgB,EAChB,WAAgC;IAEhC,QAAQ,CAAC,mBAAmB,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;IACxD,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACjD,MAAM,YAAY,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC1D,IAAI,KAAK,IAAI,YAAY,IAAI,CAAC,YAAY,EAAE,EAAE,CAAC;QAC7C,QAAQ,CAAC,aAAa,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACxC,KAAK,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n registerInternalDocumentRelink,\n relinkDocumentStoreWithCommitSideEffect,\n} from \"./documentStore/internalRelink\";\nimport { createRemovedDocumentStore } from \"./removedDocumentStore\";\nimport type {\n DocumentAttachmentUpload,\n DocumentStore,\n DocumentStoreFacade,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"./types\";\n\ninterface DocumentStoreRegistry {\n /** How the last open built each store's backing store, by store key. */\n freshStoreFactories: Map<string, () => DocumentStore>;\n /** Each backing store's way to stop its sync lane, by local id. */\n retireHandlersByLocalId: Map<string, () => void>;\n /**\n * Stores whose document was removed under them, each with whether its\n * removal still holds; see retireDocumentStore.\n */\n retiredStores: Map<string, () => boolean>;\n storeKeysByDocumentId: Map<string, string>;\n storeKeysByLocalId: Map<string, string>;\n storesByKey: Map<string, DocumentStoreFacade>;\n}\n\nconst documentStoreRegistriesByScope = new WeakMap<\n DomainScope,\n DocumentStoreRegistry\n>();\ntype PersistedDocumentDeletionListener = (localId: string) => void;\n\n// Per-scope listener plumbing shared by the persisted-document and\n// persisted-document-deletion channels: emit fans out to the scope's\n// listeners, and unsubscribing the last listener drops the scope entry.\nfunction createScopedListenerRegistry<\n Listener extends (...args: never[]) => void,\n>() {\n const listenersByScope = new WeakMap<DomainScope, Set<Listener>>();\n\n return {\n emit: (domainScope: DomainScope, ...args: Parameters<Listener>): void => {\n const listeners = listenersByScope.get(domainScope);\n if (!listeners) {\n return;\n }\n\n for (const listener of listeners) {\n listener(...args);\n }\n },\n subscribe: (domainScope: DomainScope, listener: Listener): (() => void) => {\n const listeners =\n listenersByScope.get(domainScope) ?? new Set<Listener>();\n listeners.add(listener);\n listenersByScope.set(domainScope, listeners);\n\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n listenersByScope.delete(domainScope);\n }\n };\n },\n };\n}\n\nconst persistedDocumentListeners =\n createScopedListenerRegistry<PersistedDocumentListener>();\nconst persistedDocumentDeletionListeners =\n createScopedListenerRegistry<PersistedDocumentDeletionListener>();\n\nexport function getOrCreateDocumentStoreRegistry(\n domainScope: DomainScope,\n): DocumentStoreRegistry {\n const existingRegistry = documentStoreRegistriesByScope.get(domainScope);\n if (existingRegistry) {\n return existingRegistry;\n }\n\n const nextRegistry: DocumentStoreRegistry = {\n freshStoreFactories: new Map(),\n retireHandlersByLocalId: new Map(),\n retiredStores: new Map(),\n storeKeysByDocumentId: new Map(),\n storeKeysByLocalId: new Map(),\n storesByKey: new Map(),\n };\n documentStoreRegistriesByScope.set(domainScope, nextRegistry);\n return nextRegistry;\n}\n\nexport function resolveDocumentStoreKey(\n registry: DocumentStoreRegistry,\n localId: string,\n documentId: string | null,\n): string {\n return (\n (documentId ? registry.storeKeysByDocumentId.get(documentId) : undefined) ??\n registry.storeKeysByLocalId.get(localId) ??\n localId\n );\n}\n\nexport function registerDocumentStore(\n domainScope: DomainScope,\n localId: string,\n store: DocumentStoreFacade,\n documentId: string | null,\n) {\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const storeKey = resolveDocumentStoreKey(registry, localId, documentId);\n registry.storeKeysByLocalId.set(localId, storeKey);\n if (documentId) {\n registry.storeKeysByDocumentId.set(documentId, storeKey);\n }\n registry.storesByKey.set(storeKey, store);\n}\n\nexport function registerDocumentStoreIdentity(\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n) {\n if (!documentId) {\n return;\n }\n\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const localStoreKey = registry.storeKeysByLocalId.get(localId) ?? localId;\n const documentStoreKey =\n registry.storeKeysByDocumentId.get(documentId) ?? documentId;\n\n registry.storeKeysByLocalId.set(localId, documentStoreKey);\n registry.storeKeysByDocumentId.set(documentId, documentStoreKey);\n\n if (documentStoreKey === localStoreKey) {\n return;\n }\n\n const localStore = registry.storesByKey.get(localStoreKey);\n const documentStore = registry.storesByKey.get(documentStoreKey);\n if (localStore) {\n documentStore?.rebindTo(localStore);\n registry.storesByKey.set(documentStoreKey, localStore);\n // The store's retirement and how to rebuild it move with it.\n moveKeyedEntry(\n registry.freshStoreFactories,\n localStoreKey,\n documentStoreKey,\n );\n moveKeyedEntry(registry.retiredStores, localStoreKey, documentStoreKey);\n }\n registry.storesByKey.delete(localStoreKey);\n}\n\nfunction moveKeyedEntry<Value>(\n entries: Map<string, Value>,\n fromKey: string,\n toKey: string,\n): void {\n const value = entries.get(fromKey);\n entries.delete(fromKey);\n if (value !== undefined) entries.set(toKey, value);\n}\n\n/**\n * Whether an open store holds local writes for the document that have not\n * reached SQLite yet, which no persisted-write scan can see.\n */\nexport function hasQueuedDocumentStoreWrites(\n domainScope: DomainScope,\n localId: string,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n return registry?.storesByKey.get(storeKey)?.hasQueuedWrites() ?? false;\n}\n\n/**\n * Whether any open store in `domainScope` holds local edits that have not\n * reached SQLite yet — queued writes, or applied edits whose save failed — so\n * a host can warn before an unload loses them. A retired store reads through\n * its removed stand-in, which holds none: the document it stood for is gone.\n */\nexport function hasPendingLocalDocumentWrites(\n domainScope: DomainScope,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) return false;\n for (const store of registry.storesByKey.values()) {\n if (store.hasQueuedWrites() || store.hasUnsavedLocalEdits()) return true;\n }\n return false;\n}\n\nexport function requestDocumentStoreSync(state: {\n syncLane: {\n requestSync: () => void;\n } | null;\n}) {\n state.syncLane?.requestSync();\n}\n\nexport function requestRegisteredDocumentRemoteSync(\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return false;\n }\n\n const storeKey = resolveDocumentStoreKey(registry, localId, documentId);\n const store = registry.storesByKey.get(storeKey);\n if (!store || registry.retiredStores.has(storeKey)) {\n return false;\n }\n\n // Explicit refresh uses this path to recover missed websocket invalidations\n // without instantiating every unopened document discovered in the container.\n store.requestRemoteSync();\n return true;\n}\n\n/**\n * Discard a registered document's local edits through its store, so the\n * teardown serializes on the store's write machinery instead of racing an\n * in-flight persist that would resurrect the deleted rows. Only registered\n * stores qualify — an unregistered document has no lane submitting its queue,\n * so there is nothing this escape hatch could unstick. No deletion is\n * emitted: the document survives as a re-seeded shell that keeps its listing\n * entry, and the re-pull's own persist announces the restored content.\n *\n * Resolution is strict, unlike the read-side lookups: a destructive action\n * must never run against whichever store won a lookup priority. Both\n * identifiers must map to the SAME registered store — an unknown or stale\n * documentId refuses rather than trusting the localId alone — and the store\n * revalidates the expected documentId against its persisted record inside\n * the teardown's serialized mutation, so even a stale registry mapping\n * cannot discard a different identity's edits.\n */\nexport async function discardRegisteredDocumentLocalState(\n domainScope: DomainScope,\n localId: string,\n documentId: string,\n): Promise<boolean> {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return false;\n }\n\n const localStoreKey = registry.storeKeysByLocalId.get(localId);\n const documentStoreKey = registry.storeKeysByDocumentId.get(documentId);\n if (\n !localStoreKey ||\n !documentStoreKey ||\n documentStoreKey !== localStoreKey\n ) {\n return false;\n }\n const store = registry.storesByKey.get(localStoreKey);\n if (!store) {\n return false;\n }\n\n return store.discardLocalState(documentId);\n}\n\nexport function createDocumentStoreFacade(\n initialStore: DocumentStore,\n): DocumentStoreFacade {\n let targetStore = initialStore;\n const listeners = new Set<() => void>();\n\n const emitFacade = () => {\n for (const listener of listeners) {\n listener();\n }\n };\n\n let unsubscribeTarget = targetStore.subscribe(() => {\n emitFacade();\n });\n\n const connectTarget = (nextStore: DocumentStore) => {\n if (targetStore === nextStore) {\n return;\n }\n\n unsubscribeTarget();\n targetStore = nextStore;\n unsubscribeTarget = targetStore.subscribe(() => {\n emitFacade();\n });\n emitFacade();\n };\n\n const facade: DocumentStoreFacade = {\n addRow: (fields, options) => targetStore.addRow(fields, options),\n assertCanRotateContentKey: (proof) =>\n targetStore.assertCanRotateContentKey(proof),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n targetStore.attachFiles(files),\n discardLocalState: (expectedDocumentId: string) =>\n targetStore.discardLocalState(expectedDocumentId),\n ensureInitialized: () => targetStore.ensureInitialized(),\n getSnapshot: () => targetStore.getSnapshot(),\n hasQueuedWrites: () => targetStore.hasQueuedWrites(),\n hasUnsavedLocalEdits: () => targetStore.hasUnsavedLocalEdits(),\n removeAttachment: (slotId: string) => targetStore.removeAttachment(slotId),\n removeRow: (id, options) => targetStore.removeRow(id, options),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n targetStore.replaceAttachment(slotId, file),\n requestRemoteSync: () => targetStore.requestRemoteSync(),\n requestRemoteSyncAndWait: (signal) =>\n targetStore.requestRemoteSyncAndWait(signal),\n requestSync: () => targetStore.requestSync(),\n relink: (input) => targetStore.relink(input),\n rebindTo: (store) => connectTarget(store),\n restoreContent: (content, options) =>\n targetStore.restoreContent(content, options),\n setStructuredFields: (kind, patch, options) =>\n targetStore.setStructuredFields(kind, patch, options),\n setText: (value: string) => targetStore.setText(value),\n subscribe: (listener: () => void) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n updateRowFields: (id, patch, options) =>\n targetStore.updateRowFields(id, patch, options),\n updateRuntime: (runtime: DocumentsRuntime) =>\n targetStore.updateRuntime(runtime),\n };\n registerInternalDocumentRelink(facade, (input, commitSideEffect) =>\n relinkDocumentStoreWithCommitSideEffect(\n targetStore,\n input,\n commitSideEffect,\n ),\n );\n return facade;\n}\n\nexport function emitPersistedDocument(\n domainScope: DomainScope,\n persistedDocument: Parameters<PersistedDocumentListener>[0],\n placementChanged = false,\n): void {\n persistedDocumentListeners.emit(domainScope, persistedDocument, {\n placementChanged,\n });\n}\n\nexport function subscribeToPersistedDocuments(\n domainScope: DomainScope,\n listener: PersistedDocumentListener,\n): () => void {\n return persistedDocumentListeners.subscribe(domainScope, listener);\n}\n\nexport function emitPersistedDocumentDeletion(\n domainScope: DomainScope,\n localId: string,\n): void {\n persistedDocumentDeletionListeners.emit(domainScope, localId);\n}\n\nexport function subscribeToPersistedDocumentDeletions(\n domainScope: DomainScope,\n listener: PersistedDocumentDeletionListener,\n): () => void {\n return persistedDocumentDeletionListeners.subscribe(domainScope, listener);\n}\n\nexport function requestDomainDocumentSync(domainScope: DomainScope): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return;\n }\n\n for (const [storeKey, store] of registry.storesByKey) {\n if (!registry.retiredStores.has(storeKey)) store.requestSync();\n }\n}\n\n/** Lets the backing store for `localId` stop its sync lane when retired. */\nexport function onDocumentStoreRetired(\n domainScope: DomainScope,\n localId: string,\n stopSyncLane: () => void,\n): void {\n getOrCreateDocumentStoreRegistry(domainScope).retireHandlersByLocalId.set(\n localId,\n stopSyncLane,\n );\n}\n\n/**\n * Retires the store of a document a paused organization's cleanup removed.\n * Its backing store's sync lane stops and the facade an editor may hold\n * switches to a read-only stand-in, so nothing recreates or downloads the\n * document. While `stillRemoved()` holds, reopening returns the stand-in;\n * after that, the next open rebinds the facade to a fresh backing store that\n * loads whatever SQLite holds by then, such as a copy rediscovered on resume.\n */\nexport function retireDocumentStore(\n domainScope: DomainScope,\n localId: string,\n stillRemoved: () => boolean,\n): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n const store = registry?.storesByKey.get(storeKey);\n if (!registry || !store || registry.retiredStores.has(storeKey)) return;\n registry.retireHandlersByLocalId.get(localId)?.();\n store.rebindTo(createRemovedDocumentStore(store.getSnapshot()));\n registry.retiredStores.set(storeKey, stillRemoved);\n}\n\n/**\n * Undoes a retirement whose deletion did not commit: the document survives,\n * so its facade gets a fresh backing store again.\n */\nexport function restoreDocumentStore(\n domainScope: DomainScope,\n localId: string,\n): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n const store = registry?.storesByKey.get(storeKey);\n if (!registry || !store || !registry.retiredStores.delete(storeKey)) return;\n const createFresh = registry.freshStoreFactories.get(storeKey);\n // Without a factory the next open rebinds it instead.\n if (createFresh) store.rebindTo(createFresh());\n else registry.retiredStores.set(storeKey, () => false);\n}\n\n/** The registered store for a key, rebound once its removal has lifted. */\nexport function takeRegisteredDocumentStore(\n registry: DocumentStoreRegistry,\n storeKey: string,\n createFresh: () => DocumentStore,\n): DocumentStoreFacade | undefined {\n registry.freshStoreFactories.set(storeKey, createFresh);\n const store = registry.storesByKey.get(storeKey);\n const stillRemoved = registry.retiredStores.get(storeKey);\n if (store && stillRemoved && !stillRemoved()) {\n registry.retiredStores.delete(storeKey);\n store.rebindTo(createFresh());\n }\n return store;\n}\n"]}
@@ -29,6 +29,7 @@ export function createRemovedDocumentStore(lastSnapshot) {
29
29
  requestRemoteSyncAndWait: async () => false,
30
30
  requestSync: () => undefined,
31
31
  relink: async () => null,
32
+ restoreContent: async () => false,
32
33
  setStructuredFields: refuse,
33
34
  setText: refuse,
34
35
  subscribe: () => () => undefined,
@@ -1 +1 @@
1
- {"version":3,"file":"removedDocum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ot, DocumentStore } from \"./types\";\n\nconst REMOVED_DOCUMENT_MESSAGE =\n \"This document was removed while its organization's sync is paused\";\n\n/**\n * Stands in for a store whose document a paused organization's cleanup\n * removed. It keeps showing the last snapshot, read-only, and does nothing\n * else, so an open editor neither recreates the document nor downloads it\n * while the pause lasts.\n */\nexport function createRemovedDocumentStore(\n lastSnapshot: DocumentSnapshot,\n): DocumentStore {\n const snapshot: DocumentSnapshot = {\n ...lastSnapshot,\n canAttach: false,\n canWrite: false,\n syncing: false,\n };\n const refuse = () => Promise.reject(new Error(REMOVED_DOCUMENT_MESSAGE));\n return {\n addRow: refuse,\n assertCanRotateContentKey: refuse,\n attachFiles: () => undefined,\n discardLocalState: async () => false,\n ensureInitialized: async () => false,\n getSnapshot: () => snapshot,\n hasQueuedWrites: () => false,\n hasUnsavedLocalEdits: () => false,\n removeAttachment: () => undefined,\n removeRow: refuse,\n replaceAttachment: refuse,\n requestRemoteSync: () => undefined,\n requestRemoteSyncAndWait: async () => false,\n requestSync: () => undefined,\n relink: async () => null,\n setStructuredFields: refuse,\n setText: refuse,\n subscribe: () => () => undefined,\n updateRowFields: refuse,\n updateRuntime: () => undefined,\n };\n}\n"]}
1
+ {"version":3,"file":"removedDocumentStore.js","sourceRoot":"","sources":["removedDocumentStore.ts"],"names":[],"mappings":"AAEA,MAAM,wBAAwB,GAC5B,mEAAmE,CAAC;AAEtE;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACxC,YAA8B;IAE9B,MAAM,QAAQ,GAAqB;QACjC,GAAG,YAAY;QACf,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,KAAK;QACf,OAAO,EAAE,KAAK;KACf,CAAC;IACF,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACzE,OAAO;QACL,MAAM,EAAE,MAAM;QACd,yBAAyB,EAAE,MAAM;QACjC,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,iBAAiB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACpC,iBAAiB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACpC,WAAW,EAAE,GAAG,EAAE,CAAC,QAAQ;QAC3B,eAAe,EAAE,GAAG,EAAE,CAAC,KAAK;QAC5B,oBAAoB,EAAE,GAAG,EAAE,CAAC,KAAK;QACjC,gBAAgB,EAAE,GAAG,EAAE,CAAC,SAAS;QACjC,SAAS,EAAE,MAAM;QACjB,iBAAiB,EAAE,MAAM;QACzB,iBAAiB,EAAE,GAAG,EAAE,CAAC,SAAS;QAClC,wBAAwB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QAC3C,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,IAAI;QACxB,cAAc,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACjC,mBAAmB,EAAE,MAAM;QAC3B,OAAO,EAAE,MAAM;QACf,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,SAAS;QAChC,eAAe,EAAE,MAAM;QACvB,aAAa,EAAE,GAAG,EAAE,CAAC,SAAS;KAC/B,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentSnapshot, DocumentStore } from \"./types\";\n\nconst REMOVED_DOCUMENT_MESSAGE =\n \"This document was removed while its organization's sync is paused\";\n\n/**\n * Stands in for a store whose document a paused organization's cleanup\n * removed. It keeps showing the last snapshot, read-only, and does nothing\n * else, so an open editor neither recreates the document nor downloads it\n * while the pause lasts.\n */\nexport function createRemovedDocumentStore(\n lastSnapshot: DocumentSnapshot,\n): DocumentStore {\n const snapshot: DocumentSnapshot = {\n ...lastSnapshot,\n canAttach: false,\n canWrite: false,\n syncing: false,\n };\n const refuse = () => Promise.reject(new Error(REMOVED_DOCUMENT_MESSAGE));\n return {\n addRow: refuse,\n assertCanRotateContentKey: refuse,\n attachFiles: () => undefined,\n discardLocalState: async () => false,\n ensureInitialized: async () => false,\n getSnapshot: () => snapshot,\n hasQueuedWrites: () => false,\n hasUnsavedLocalEdits: () => false,\n removeAttachment: () => undefined,\n removeRow: refuse,\n replaceAttachment: refuse,\n requestRemoteSync: () => undefined,\n requestRemoteSyncAndWait: async () => false,\n requestSync: () => undefined,\n relink: async () => null,\n restoreContent: async () => false,\n setStructuredFields: refuse,\n setText: refuse,\n subscribe: () => () => undefined,\n updateRowFields: refuse,\n updateRuntime: () => undefined,\n };\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import type { ContainerAccessLevel } from "../../internal/crypto/index.js";
2
2
  import type { DocumentAttachment } from "../../data/documents/documentContent.js";
3
3
  import type { DocumentFieldValidationIssue, StoredDocumentKind } from "../../data/documents/documentKinds.js";
4
+ import type { DocumentRestoreContent } from "../../data/documents/documentRestore.js";
4
5
  import type { DocumentRow } from "../../data/documents/documentRowList.js";
5
6
  import type { DocumentSummary } from "../../data/documents/documentSummary.js";
6
7
  import type { BlobByteSourceInput } from "../../workflows/blobs/index.js";
@@ -46,7 +47,7 @@ export type DocumentAttachmentStatus = "syncing" | "intent-mismatch";
46
47
  export type AddDocumentRow = (fields: Readonly<Record<string, string>>, options?: DocumentMutationGuard | undefined) => Promise<string>;
47
48
  export type UpdateDocumentRowFields = (id: string, patch: Readonly<Record<string, string>>, options?: DocumentMutationGuard | undefined) => Promise<void>;
48
49
  export type RemoveDocumentRow = (id: string, options?: DocumentMutationGuard | undefined) => Promise<void>;
49
- export type DocumentContextValue = DocumentSnapshot & Pick<DocumentStore, "addRow" | "attachFiles" | "relink" | "removeAttachment" | "removeRow" | "replaceAttachment" | "requestSync" | "setStructuredFields" | "setText" | "updateRowFields">;
50
+ export type DocumentContextValue = DocumentSnapshot & Pick<DocumentStore, "addRow" | "attachFiles" | "relink" | "removeAttachment" | "removeRow" | "replaceAttachment" | "requestSync" | "restoreContent" | "setStructuredFields" | "setText" | "updateRowFields">;
50
51
  export interface DocumentSnapshot {
51
52
  attachments: ReadonlyArray<DocumentAttachment>;
52
53
  attachmentStatusBySlotId: Readonly<Record<string, DocumentAttachmentStatus>>;
@@ -92,6 +93,14 @@ export interface DocumentStore {
92
93
  removeAttachment: (slotId: string) => void;
93
94
  removeRow: RemoveDocumentRow;
94
95
  replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) => Promise<void>;
96
+ /**
97
+ * Write a past version's text, structured fields, and rows back as one
98
+ * ordinary local edit; attachments are left as they are. Nothing is rewound:
99
+ * the restore is new operations that sync and merge like any other write.
100
+ * Resolves true when the document durably holds the content, false when
101
+ * the restore was refused or did not persist.
102
+ */
103
+ restoreContent: (content: DocumentRestoreContent, options?: DocumentMutationGuard | undefined) => Promise<boolean>;
95
104
  /** Pull remote document updates even when no websocket event marked it dirty. */
96
105
  requestRemoteSync: () => void;
97
106
  /** Pull remote updates and report whether the requested sync pass completed. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAeA,MAAM,CAAC,MAAM,mBAAmB,GAAG,SAAS,CAAC","sourcesContent":["import type { ContainerAccessLevel } from \"@tearleads/crypto\";\nimport type { DocumentAttachment } from \"../../data/documents/documentContent\";\nimport type {\n DocumentFieldValidationIssue,\n StoredDocumentKind,\n} from \"../../data/documents/documentKinds\";\nimport type { DocumentRow } from \"../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type { BlobByteSourceInput } from \"../../workflows/blobs\";\nimport type {\n DocumentRotationProofMode,\n DocumentsWorkflowRuntime,\n RelinkPersistedDocumentInput,\n} from \"../../workflows/documents\";\n\nexport const DEFAULT_DOCUMENT_ID = \"default\";\n\nexport type DocumentsRuntime = DocumentsWorkflowRuntime;\nexport type DocumentStructuredFieldPatch = Readonly<\n Record<string, string | undefined>\n>;\n\n/**\n * Host admission checked after readiness and again at local queue execution.\n * The predicate must be synchronous and side-effect-free. False is a no-op;\n * a throw is reported as a write failure and also refuses the mutation.\n * This does not cancel initialization or roll back an already admitted write.\n */\nexport interface DocumentMutationGuard {\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface DocumentMutationOptions extends DocumentMutationGuard {\n deferRemoteSync?: boolean | undefined;\n}\n\nexport interface DocumentStoreOpenOptions {\n /**\n * The caller attaches a file immediately after creating the document. The\n * birth commits locally without its own pending update, so the attach's\n * delta carries it; a failed attach enqueues the birth on its own.\n */\n deferInitialUpdate?: boolean | undefined;\n /**\n * Rows and structured fields a newly created record starts with. They are\n * written into its birth update with the initial kind and text, so a\n * document whose content is known up front queues one update. Fields need a\n * non-note `initialDocumentKind`. Both are ignored when the record exists.\n */\n initialRows?: ReadonlyArray<Readonly<Record<string, string>>> | undefined;\n initialStructuredFields?: DocumentStructuredFieldPatch | undefined;\n remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n}\n\nexport interface DocumentAttachmentUpload {\n bytes: BlobByteSourceInput;\n name: string;\n mimeType: string | null;\n}\n\n// `syncing`: the slot's upload is still queued. `intent-mismatch`: the held\n// bytes are a validly signed served binding whose digest differs from the one\n// the document content records (its content update has not arrived).\nexport type DocumentAttachmentStatus = \"syncing\" | \"intent-mismatch\";\n\n// Add a row to the document's repeated-row list, returning the new row id.\nexport type AddDocumentRow = (\n fields: Readonly<Record<string, string>>,\n options?: DocumentMutationGuard | undefined,\n) => Promise<string>;\n// Patch one or more cells of a single row (merges per-cell).\nexport type UpdateDocumentRowFields = (\n id: string,\n patch: Readonly<Record<string, string>>,\n options?: DocumentMutationGuard | undefined,\n) => Promise<void>;\nexport type RemoveDocumentRow = (\n id: string,\n options?: DocumentMutationGuard | undefined,\n) => Promise<void>;\n\n// The store surface exposed through context: the snapshot fields plus the\n// store's mutation methods, spelled as a Pick so the two can't drift.\nexport type DocumentContextValue = DocumentSnapshot &\n Pick<\n DocumentStore,\n | \"addRow\"\n | \"attachFiles\"\n | \"relink\"\n | \"removeAttachment\"\n | \"removeRow\"\n | \"replaceAttachment\"\n | \"requestSync\"\n | \"setStructuredFields\"\n | \"setText\"\n | \"updateRowFields\"\n >;\n\nexport interface DocumentSnapshot {\n attachments: ReadonlyArray<DocumentAttachment>;\n attachmentStatusBySlotId: Readonly<Record<string, DocumentAttachmentStatus>>;\n attachmentStorageKeyBySlotId: Readonly<Record<string, string>>;\n canAttach: boolean;\n canWrite: boolean;\n currentAuthorId: string | null;\n documentId: string | null;\n documentKind: StoredDocumentKind;\n effectiveAccessLevel: ContainerAccessLevel;\n fieldValidationIssues: ReadonlyArray<DocumentFieldValidationIssue>;\n ready: boolean;\n rows: ReadonlyArray<DocumentRow>;\n structuredFields: Readonly<Record<string, string>>;\n text: string;\n title: string;\n syncing: boolean;\n}\n\nexport interface DocumentStore {\n addRow: AddDocumentRow;\n /** Fail unless this store can produce a mergeable full-history checkpoint. */\n assertCanRotateContentKey: (\n proof: DocumentRotationProofMode,\n ) => Promise<Uint8Array>;\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) => void;\n /**\n * Convert this document's persisted local state to the discovered-share\n * shell so the store re-pulls the server copy — the escape hatch for\n * queued local writes that can no longer sync. `expectedDocumentId` is\n * revalidated against the persisted record inside the teardown's\n * serialized mutation, so a stale caller can never discard a different\n * identity's edits. Refuses (returns false) local-only, unlinked,\n * move-pending, and identity-mismatched documents.\n */\n discardLocalState: (expectedDocumentId: string) => Promise<boolean>;\n ensureInitialized: () => Promise<boolean>;\n getSnapshot: () => DocumentSnapshot;\n /** Whether local writes are queued that have not reached SQLite yet. */\n hasQueuedWrites: () => boolean;\n /**\n * Whether applied local edits have not reached SQLite, e.g. after a failed\n * save, even though no write is queued any more.\n */\n hasUnsavedLocalEdits: () => boolean;\n removeAttachment: (slotId: string) => void;\n removeRow: RemoveDocumentRow;\n replaceAttachment: (\n slotId: string,\n file: DocumentAttachmentUpload,\n ) => Promise<void>;\n /** Pull remote document updates even when no websocket event marked it dirty. */\n requestRemoteSync: () => void;\n /** Pull remote updates and report whether the requested sync pass completed. */\n requestRemoteSyncAndWait: (\n signal?: AbortSignal | undefined,\n ) => Promise<boolean>;\n requestSync: () => void;\n relink: (input: DocumentStoreRelinkInput) => Promise<DocumentSummary | null>;\n setStructuredFields: (\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options?: DocumentMutationOptions | undefined,\n ) => Promise<void>;\n setText: (value: string) => Promise<void>;\n subscribe: (listener: () => void) => () => void;\n updateRowFields: UpdateDocumentRowFields;\n updateRuntime: (runtime: DocumentsRuntime) => void;\n}\n\nexport interface DocumentStoreFacade extends DocumentStore {\n rebindTo: (store: DocumentStore) => void;\n}\n\nexport type PersistedDocumentListener = (\n document: DocumentSummary,\n change: { readonly placementChanged: boolean },\n) => void;\n\nexport interface DocumentStoreRelinkInput extends RelinkPersistedDocumentInput {\n contentKeyBundle?: string | null | undefined;\n documentKekTargets?: string | null | undefined;\n documentManifestBundle?: string | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAgBA,MAAM,CAAC,MAAM,mBAAmB,GAAG,SAAS,CAAC","sourcesContent":["import type { ContainerAccessLevel } from \"@tearleads/crypto\";\nimport type { DocumentAttachment } from \"../../data/documents/documentContent\";\nimport type {\n DocumentFieldValidationIssue,\n StoredDocumentKind,\n} from \"../../data/documents/documentKinds\";\nimport type { DocumentRestoreContent } from \"../../data/documents/documentRestore\";\nimport type { DocumentRow } from \"../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type { BlobByteSourceInput } from \"../../workflows/blobs\";\nimport type {\n DocumentRotationProofMode,\n DocumentsWorkflowRuntime,\n RelinkPersistedDocumentInput,\n} from \"../../workflows/documents\";\n\nexport const DEFAULT_DOCUMENT_ID = \"default\";\n\nexport type DocumentsRuntime = DocumentsWorkflowRuntime;\nexport type DocumentStructuredFieldPatch = Readonly<\n Record<string, string | undefined>\n>;\n\n/**\n * Host admission checked after readiness and again at local queue execution.\n * The predicate must be synchronous and side-effect-free. False is a no-op;\n * a throw is reported as a write failure and also refuses the mutation.\n * This does not cancel initialization or roll back an already admitted write.\n */\nexport interface DocumentMutationGuard {\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface DocumentMutationOptions extends DocumentMutationGuard {\n deferRemoteSync?: boolean | undefined;\n}\n\nexport interface DocumentStoreOpenOptions {\n /**\n * The caller attaches a file immediately after creating the document. The\n * birth commits locally without its own pending update, so the attach's\n * delta carries it; a failed attach enqueues the birth on its own.\n */\n deferInitialUpdate?: boolean | undefined;\n /**\n * Rows and structured fields a newly created record starts with. They are\n * written into its birth update with the initial kind and text, so a\n * document whose content is known up front queues one update. Fields need a\n * non-note `initialDocumentKind`. Both are ignored when the record exists.\n */\n initialRows?: ReadonlyArray<Readonly<Record<string, string>>> | undefined;\n initialStructuredFields?: DocumentStructuredFieldPatch | undefined;\n remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n}\n\nexport interface DocumentAttachmentUpload {\n bytes: BlobByteSourceInput;\n name: string;\n mimeType: string | null;\n}\n\n// `syncing`: the slot's upload is still queued. `intent-mismatch`: the held\n// bytes are a validly signed served binding whose digest differs from the one\n// the document content records (its content update has not arrived).\nexport type DocumentAttachmentStatus = \"syncing\" | \"intent-mismatch\";\n\n// Add a row to the document's repeated-row list, returning the new row id.\nexport type AddDocumentRow = (\n fields: Readonly<Record<string, string>>,\n options?: DocumentMutationGuard | undefined,\n) => Promise<string>;\n// Patch one or more cells of a single row (merges per-cell).\nexport type UpdateDocumentRowFields = (\n id: string,\n patch: Readonly<Record<string, string>>,\n options?: DocumentMutationGuard | undefined,\n) => Promise<void>;\nexport type RemoveDocumentRow = (\n id: string,\n options?: DocumentMutationGuard | undefined,\n) => Promise<void>;\n\n// The store surface exposed through context: the snapshot fields plus the\n// store's mutation methods, spelled as a Pick so the two can't drift.\nexport type DocumentContextValue = DocumentSnapshot &\n Pick<\n DocumentStore,\n | \"addRow\"\n | \"attachFiles\"\n | \"relink\"\n | \"removeAttachment\"\n | \"removeRow\"\n | \"replaceAttachment\"\n | \"requestSync\"\n | \"restoreContent\"\n | \"setStructuredFields\"\n | \"setText\"\n | \"updateRowFields\"\n >;\n\nexport interface DocumentSnapshot {\n attachments: ReadonlyArray<DocumentAttachment>;\n attachmentStatusBySlotId: Readonly<Record<string, DocumentAttachmentStatus>>;\n attachmentStorageKeyBySlotId: Readonly<Record<string, string>>;\n canAttach: boolean;\n canWrite: boolean;\n currentAuthorId: string | null;\n documentId: string | null;\n documentKind: StoredDocumentKind;\n effectiveAccessLevel: ContainerAccessLevel;\n fieldValidationIssues: ReadonlyArray<DocumentFieldValidationIssue>;\n ready: boolean;\n rows: ReadonlyArray<DocumentRow>;\n structuredFields: Readonly<Record<string, string>>;\n text: string;\n title: string;\n syncing: boolean;\n}\n\nexport interface DocumentStore {\n addRow: AddDocumentRow;\n /** Fail unless this store can produce a mergeable full-history checkpoint. */\n assertCanRotateContentKey: (\n proof: DocumentRotationProofMode,\n ) => Promise<Uint8Array>;\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) => void;\n /**\n * Convert this document's persisted local state to the discovered-share\n * shell so the store re-pulls the server copy — the escape hatch for\n * queued local writes that can no longer sync. `expectedDocumentId` is\n * revalidated against the persisted record inside the teardown's\n * serialized mutation, so a stale caller can never discard a different\n * identity's edits. Refuses (returns false) local-only, unlinked,\n * move-pending, and identity-mismatched documents.\n */\n discardLocalState: (expectedDocumentId: string) => Promise<boolean>;\n ensureInitialized: () => Promise<boolean>;\n getSnapshot: () => DocumentSnapshot;\n /** Whether local writes are queued that have not reached SQLite yet. */\n hasQueuedWrites: () => boolean;\n /**\n * Whether applied local edits have not reached SQLite, e.g. after a failed\n * save, even though no write is queued any more.\n */\n hasUnsavedLocalEdits: () => boolean;\n removeAttachment: (slotId: string) => void;\n removeRow: RemoveDocumentRow;\n replaceAttachment: (\n slotId: string,\n file: DocumentAttachmentUpload,\n ) => Promise<void>;\n /**\n * Write a past version's text, structured fields, and rows back as one\n * ordinary local edit; attachments are left as they are. Nothing is rewound:\n * the restore is new operations that sync and merge like any other write.\n * Resolves true when the document durably holds the content, false when\n * the restore was refused or did not persist.\n */\n restoreContent: (\n content: DocumentRestoreContent,\n options?: DocumentMutationGuard | undefined,\n ) => Promise<boolean>;\n /** Pull remote document updates even when no websocket event marked it dirty. */\n requestRemoteSync: () => void;\n /** Pull remote updates and report whether the requested sync pass completed. */\n requestRemoteSyncAndWait: (\n signal?: AbortSignal | undefined,\n ) => Promise<boolean>;\n requestSync: () => void;\n relink: (input: DocumentStoreRelinkInput) => Promise<DocumentSummary | null>;\n setStructuredFields: (\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options?: DocumentMutationOptions | undefined,\n ) => Promise<void>;\n setText: (value: string) => Promise<void>;\n subscribe: (listener: () => void) => () => void;\n updateRowFields: UpdateDocumentRowFields;\n updateRuntime: (runtime: DocumentsRuntime) => void;\n}\n\nexport interface DocumentStoreFacade extends DocumentStore {\n rebindTo: (store: DocumentStore) => void;\n}\n\nexport type PersistedDocumentListener = (\n document: DocumentSummary,\n change: { readonly placementChanged: boolean },\n) => void;\n\nexport interface DocumentStoreRelinkInput extends RelinkPersistedDocumentInput {\n contentKeyBundle?: string | null | undefined;\n documentKekTargets?: string | null | undefined;\n documentManifestBundle?: string | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\n"]}