@tearleads/client-sdk 0.1.63 → 0.1.64

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 (616) hide show
  1. package/data/documents/blob/shared/projection.js +1 -1
  2. package/data/documents/blob/shared/projection.js.map +1 -1
  3. package/data/documents/shared/projectionContentKeys.js +1 -1
  4. package/data/documents/shared/projectionContentKeys.js.map +1 -1
  5. package/data/documents/shared/syncResponseAuthorization.js +1 -1
  6. package/data/documents/shared/syncResponseAuthorization.js.map +1 -1
  7. package/data/keyingProjectionVerification/{accessManifestCheckpointEnforcement.js → checkpoints/accessManifestCheckpointEnforcement.js} +2 -2
  8. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js.map +1 -0
  9. package/data/keyingProjectionVerification/{bundleVerification.js → checkpoints/bundleVerification.js} +5 -5
  10. package/data/keyingProjectionVerification/checkpoints/bundleVerification.js.map +1 -0
  11. package/data/keyingProjectionVerification/{checkpointContext.d.ts → checkpoints/checkpointContext.d.ts} +6 -6
  12. package/data/keyingProjectionVerification/{checkpointContext.js → checkpoints/checkpointContext.js} +6 -6
  13. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -0
  14. package/data/keyingProjectionVerification/{manifestCheckpointVerification.js → checkpoints/manifestCheckpointVerification.js} +2 -2
  15. package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js.map +1 -0
  16. package/data/keyingProjectionVerification/{containerAncestorCitations.js → container/containerAncestorCitations.js} +4 -4
  17. package/data/keyingProjectionVerification/container/containerAncestorCitations.js.map +1 -0
  18. package/data/keyingProjectionVerification/{containerCreateManifest.js → container/containerCreateManifest.js} +1 -1
  19. package/data/keyingProjectionVerification/{containerDestinationVerification.js → container/containerDestinationVerification.js} +4 -4
  20. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -0
  21. package/data/keyingProjectionVerification/{containerManifestVerification.js → container/containerManifestVerification.js} +7 -7
  22. package/data/keyingProjectionVerification/container/containerManifestVerification.js.map +1 -0
  23. package/data/keyingProjectionVerification/{containerPathVerification.js → container/containerPathVerification.js} +2 -2
  24. package/data/keyingProjectionVerification/container/containerPathVerification.js.map +1 -0
  25. package/data/keyingProjectionVerification/{containerProjectionVerification.d.ts → container/containerProjectionVerification.d.ts} +7 -7
  26. package/data/keyingProjectionVerification/{containerProjectionVerification.js → container/containerProjectionVerification.js} +9 -9
  27. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -0
  28. package/data/keyingProjectionVerification/{documentDependencyPaths.d.ts → document/documentDependencyPaths.d.ts} +1 -1
  29. package/data/keyingProjectionVerification/{documentDependencyPaths.js → document/documentDependencyPaths.js} +3 -3
  30. package/data/keyingProjectionVerification/document/documentDependencyPaths.js.map +1 -0
  31. package/data/keyingProjectionVerification/{documentManifestPolicies.js → document/documentManifestPolicies.js} +2 -2
  32. package/data/keyingProjectionVerification/document/documentManifestPolicies.js.map +1 -0
  33. package/data/keyingProjectionVerification/{documentManifestPredecessor.js → document/documentManifestPredecessor.js} +1 -1
  34. package/data/keyingProjectionVerification/{documentManifestVerification.js → document/documentManifestVerification.js} +5 -5
  35. package/data/keyingProjectionVerification/document/documentManifestVerification.js.map +1 -0
  36. package/data/keyingProjectionVerification/{documentProjectionVerification.d.ts → document/documentProjectionVerification.d.ts} +4 -4
  37. package/data/keyingProjectionVerification/{documentProjectionVerification.js → document/documentProjectionVerification.js} +9 -9
  38. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -0
  39. package/data/keyingProjectionVerification/{documentPurgeCheckpointCurrency.js → documentPurge/documentPurgeCheckpointCurrency.js} +12 -12
  40. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -0
  41. package/data/keyingProjectionVerification/{documentPurgeCheckpointEnforcement.js → documentPurge/documentPurgeCheckpointEnforcement.js} +2 -2
  42. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js.map +1 -0
  43. package/data/keyingProjectionVerification/{documentPurgeDocumentChainVerification.js → documentPurge/documentPurgeDocumentChainVerification.js} +8 -8
  44. package/data/keyingProjectionVerification/documentPurge/documentPurgeDocumentChainVerification.js.map +1 -0
  45. package/data/keyingProjectionVerification/{documentPurgePolicyCheckpoints.js → documentPurge/documentPurgePolicyCheckpoints.js} +2 -2
  46. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js.map +1 -0
  47. package/data/keyingProjectionVerification/{documentPurgePolicyCurrency.js → documentPurge/documentPurgePolicyCurrency.js} +4 -4
  48. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js.map +1 -0
  49. package/data/keyingProjectionVerification/{documentPurgePrincipalEvidence.js → documentPurge/documentPurgePrincipalEvidence.js} +3 -3
  50. package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js.map +1 -0
  51. package/data/keyingProjectionVerification/{documentPurgeProofVerification.d.ts → documentPurge/documentPurgeProofVerification.d.ts} +5 -5
  52. package/data/keyingProjectionVerification/{documentPurgeProofVerification.js → documentPurge/documentPurgeProofVerification.js} +10 -10
  53. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js.map +1 -0
  54. package/data/keyingProjectionVerification/index.d.ts +4 -4
  55. package/data/keyingProjectionVerification/index.js +4 -4
  56. package/data/keyingProjectionVerification/index.js.map +1 -1
  57. package/data/keyingProjectionVerification/{mergeProjectionPolicyEvidence.js → principalPolicy/mergeProjectionPolicyEvidence.js} +2 -2
  58. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js.map +1 -0
  59. package/data/keyingProjectionVerification/{organizationFounderBinding.js → principalPolicy/organizationFounderBinding.js} +3 -3
  60. package/data/keyingProjectionVerification/principalPolicy/organizationFounderBinding.js.map +1 -0
  61. package/data/keyingProjectionVerification/{principalPolicyCache.js → principalPolicy/principalPolicyCache.js} +6 -6
  62. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -0
  63. package/data/keyingProjectionVerification/{principalPolicyVerification.js → principalPolicy/principalPolicyVerification.js} +12 -12
  64. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -0
  65. package/data/keyingProjectionVerification/{projectionAuthorizationEvidence.js → principalPolicy/projectionAuthorizationEvidence.js} +3 -3
  66. package/data/keyingProjectionVerification/principalPolicy/projectionAuthorizationEvidence.js.map +1 -0
  67. package/data/keyingProjectionVerification/{projectionPolicyEvidence.js → principalPolicy/projectionPolicyEvidence.js} +3 -3
  68. package/data/keyingProjectionVerification/principalPolicy/projectionPolicyEvidence.js.map +1 -0
  69. package/data/keyingProjectionVerification/{resolvedPrincipalPolicy.js → principalPolicy/resolvedPrincipalPolicy.js} +6 -6
  70. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js.map +1 -0
  71. package/package.json +1 -1
  72. package/stores/container-contents/accessRestorationSweep.js +1 -1
  73. package/stores/container-contents/accessRestorationSweep.js.map +1 -1
  74. package/stores/container-contents/containerContentsStore.d.ts +1 -1
  75. package/stores/container-contents/containerContentsStore.js +12 -12
  76. package/stores/container-contents/containerContentsStore.js.map +1 -1
  77. package/stores/container-contents/containerState/containerStateMap.js.map +1 -0
  78. package/stores/container-contents/{containerStatePersistence.js → containerState/containerStatePersistence.js} +2 -2
  79. package/stores/container-contents/containerState/containerStatePersistence.js.map +1 -0
  80. package/stores/container-contents/{missingContainerState.js → containerState/missingContainerState.js} +1 -1
  81. package/stores/container-contents/containerState/missingContainerState.js.map +1 -0
  82. package/stores/container-contents/containerState/missingSyncedContainerState.js.map +1 -0
  83. package/stores/container-contents/{reconcilableContainer.d.ts → containerState/reconcilableContainer.d.ts} +1 -1
  84. package/stores/container-contents/containerState/reconcilableContainer.js.map +1 -0
  85. package/stores/container-contents/{documentRecovery.js → documentWork/documentRecovery.js} +6 -6
  86. package/stores/container-contents/documentWork/documentRecovery.js.map +1 -0
  87. package/stores/container-contents/{documentRotation.js → documentWork/documentRotation.js} +2 -2
  88. package/stores/container-contents/documentWork/documentRotation.js.map +1 -0
  89. package/stores/container-contents/{documentWork.js → documentWork/index.js} +1 -1
  90. package/stores/container-contents/documentWork/index.js.map +1 -0
  91. package/stores/container-contents/{backgroundHydration.js → hydration/backgroundHydration.js} +3 -3
  92. package/stores/container-contents/hydration/backgroundHydration.js.map +1 -0
  93. package/stores/container-contents/{remoteHydrationRequest.js → hydration/remoteHydrationRequest.js} +3 -3
  94. package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -0
  95. package/stores/container-contents/{startupHydration.js → hydration/startupHydration.js} +3 -3
  96. package/stores/container-contents/hydration/startupHydration.js.map +1 -0
  97. package/stores/container-contents/index.d.ts +3 -3
  98. package/stores/container-contents/index.js +2 -2
  99. package/stores/container-contents/index.js.map +1 -1
  100. package/stores/container-contents/localRefresh.js +2 -2
  101. package/stores/container-contents/localRefresh.js.map +1 -1
  102. package/stores/container-contents/{containerPurgeCore.js → operations/containerPurgeCore.js} +4 -4
  103. package/stores/container-contents/operations/containerPurgeCore.js.map +1 -0
  104. package/stores/container-contents/operations/emptyTrashOperation.js.map +1 -0
  105. package/stores/container-contents/{groupRewrapOperation.js → operations/groupRewrapOperation.js} +2 -2
  106. package/stores/container-contents/operations/groupRewrapOperation.js.map +1 -0
  107. package/stores/container-contents/{operations.js → operations/index.js} +18 -18
  108. package/stores/container-contents/operations/index.js.map +1 -0
  109. package/stores/container-contents/operations/purgeContainerOperation.js.map +1 -0
  110. package/stores/container-contents/{reportShareFailure.js → operations/reportShareFailure.js} +4 -4
  111. package/stores/container-contents/operations/reportShareFailure.js.map +1 -0
  112. package/stores/container-contents/{setContainerIconOperation.js → operations/setContainerIconOperation.js} +6 -6
  113. package/stores/container-contents/operations/setContainerIconOperation.js.map +1 -0
  114. package/stores/container-contents/{shareOperations.js → operations/shareOperations.js} +6 -6
  115. package/stores/container-contents/operations/shareOperations.js.map +1 -0
  116. package/stores/container-contents/remoteEvents/remoteBackedContainerState.js.map +1 -0
  117. package/stores/container-contents/{remoteContainerIngestion.js → remoteEvents/remoteContainerIngestion.js} +4 -4
  118. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js.map +1 -0
  119. package/stores/container-contents/{remoteEventProjectionInvalidation.js → remoteEvents/remoteEventProjectionInvalidation.js} +1 -1
  120. package/stores/container-contents/remoteEvents/remoteEventProjectionInvalidation.js.map +1 -0
  121. package/stores/container-contents/{remoteEventSync.js → remoteEvents/remoteEventSync.js} +4 -4
  122. package/stores/container-contents/remoteEvents/remoteEventSync.js.map +1 -0
  123. package/stores/container-contents/{remoteWriteGuards.js → remoteWrites/remoteWriteGuards.js} +2 -2
  124. package/stores/container-contents/remoteWrites/remoteWriteGuards.js.map +1 -0
  125. package/stores/container-contents/{remoteWriteQueue.js → remoteWrites/remoteWriteQueue.js} +1 -1
  126. package/stores/container-contents/remoteWrites/remoteWriteQueue.js.map +1 -0
  127. package/stores/container-contents/remoteWrites/writeGeneration.js.map +1 -0
  128. package/stores/container-contents/state.d.ts +1 -1
  129. package/stores/container-contents/state.js +2 -2
  130. package/stores/container-contents/state.js.map +1 -1
  131. package/stores/container-contents/{syncAgent.d.ts → syncAgent/index.d.ts} +2 -2
  132. package/stores/container-contents/{syncAgent.js → syncAgent/index.js} +14 -14
  133. package/stores/container-contents/syncAgent/index.js.map +1 -0
  134. package/stores/container-contents/{metadataSyncSignal.js → syncAgent/metadataSyncSignal.js} +1 -1
  135. package/stores/container-contents/{metadataSyncSignal.js.map → syncAgent/metadataSyncSignal.js.map} +1 -1
  136. package/stores/container-contents/{syncAgentTypes.d.ts → syncAgent/syncAgentTypes.d.ts} +5 -5
  137. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -0
  138. package/stores/container-contents/{syncLaneIteration.js → syncAgent/syncLaneIteration.js} +11 -11
  139. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -0
  140. package/stores/container-contents/{existingSystemContainer.js → systemContainers/existingSystemContainer.js} +4 -4
  141. package/stores/container-contents/systemContainers/existingSystemContainer.js.map +1 -0
  142. package/stores/container-contents/{organizationMetadataSystemContainer.js → systemContainers/organizationMetadataSystemContainer.js} +2 -2
  143. package/stores/container-contents/systemContainers/organizationMetadataSystemContainer.js.map +1 -0
  144. package/stores/container-contents/{systemContainerHydration.js → systemContainers/systemContainerHydration.js} +3 -3
  145. package/stores/container-contents/systemContainers/systemContainerHydration.js.map +1 -0
  146. package/stores/container-contents/{systemContainerIcon.js → systemContainers/systemContainerIcon.js} +5 -5
  147. package/stores/container-contents/systemContainers/systemContainerIcon.js.map +1 -0
  148. package/stores/container-contents/systemContainers/systemContainerLookup.js.map +1 -0
  149. package/stores/container-contents/{systemContainerPostCreate.js → systemContainers/systemContainerPostCreate.js} +2 -2
  150. package/stores/container-contents/systemContainers/systemContainerPostCreate.js.map +1 -0
  151. package/stores/container-contents/{systemContainerPromotion.js → systemContainers/systemContainerPromotion.js} +1 -1
  152. package/stores/container-contents/systemContainers/systemContainerPromotion.js.map +1 -0
  153. package/stores/container-contents/types.d.ts +2 -2
  154. package/stores/container-contents/types.js.map +1 -1
  155. package/stores/documents/documentStore/{attachmentSourceUpload.js → attachmentUpload/attachmentSourceUpload.js} +4 -4
  156. package/stores/documents/documentStore/attachmentUpload/attachmentSourceUpload.js.map +1 -0
  157. package/stores/documents/documentStore/{attachmentStaging.js → attachmentUpload/attachmentStaging.js} +5 -5
  158. package/stores/documents/documentStore/attachmentUpload/attachmentStaging.js.map +1 -0
  159. package/stores/documents/documentStore/{attachmentUploadAttempt.js → attachmentUpload/attachmentUploadAttempt.js} +2 -2
  160. package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js.map +1 -0
  161. package/stores/documents/documentStore/{attachmentUploadLane.js → attachmentUpload/attachmentUploadLane.js} +1 -1
  162. package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js.map +1 -0
  163. package/stores/documents/documentStore/{attachmentUploadResume.js → attachmentUpload/attachmentUploadResume.js} +4 -4
  164. package/stores/documents/documentStore/attachmentUpload/attachmentUploadResume.js.map +1 -0
  165. package/stores/documents/documentStore/{attachmentDetachState.js → attachments/attachmentDetachState.js} +1 -1
  166. package/stores/documents/documentStore/attachments/attachmentDetachState.js.map +1 -0
  167. package/stores/documents/documentStore/{attachmentHydration.js → attachments/attachmentHydration.js} +5 -5
  168. package/stores/documents/documentStore/attachments/attachmentHydration.js.map +1 -0
  169. package/stores/documents/documentStore/{attachmentHydrationCommit.js → attachments/attachmentHydrationCommit.js} +3 -3
  170. package/stores/documents/documentStore/attachments/attachmentHydrationCommit.js.map +1 -0
  171. package/stores/documents/documentStore/{attachmentIntents.js → attachments/attachmentIntents.js} +2 -2
  172. package/stores/documents/documentStore/attachments/attachmentIntents.js.map +1 -0
  173. package/stores/documents/documentStore/{attachmentMutationPersistence.js → attachments/attachmentMutationPersistence.js} +4 -4
  174. package/stores/documents/documentStore/attachments/attachmentMutationPersistence.js.map +1 -0
  175. package/stores/documents/documentStore/attachments/attachmentPersistFollowup.js.map +1 -0
  176. package/stores/documents/documentStore/{attachmentPersistence.js → attachments/attachmentPersistence.js} +4 -4
  177. package/stores/documents/documentStore/attachments/attachmentPersistence.js.map +1 -0
  178. package/stores/documents/documentStore/{attachmentRemoval.js → attachments/attachmentRemoval.js} +11 -11
  179. package/stores/documents/documentStore/attachments/attachmentRemoval.js.map +1 -0
  180. package/stores/documents/documentStore/attachments/attachmentSnapshot.js.map +1 -0
  181. package/stores/documents/documentStore/{attachmentWriteGeneration.js → attachments/attachmentWriteGeneration.js} +2 -2
  182. package/stores/documents/documentStore/attachments/attachmentWriteGeneration.js.map +1 -0
  183. package/stores/documents/documentStore/{attachments.js → attachments/index.js} +11 -11
  184. package/stores/documents/documentStore/attachments/index.js.map +1 -0
  185. package/stores/documents/documentStore/{documentHistoryCompaction.js → history/documentHistoryCompaction.js} +4 -4
  186. package/stores/documents/documentStore/history/documentHistoryCompaction.js.map +1 -0
  187. package/stores/documents/documentStore/{durableDocumentReload.js → history/durableDocumentReload.js} +6 -6
  188. package/stores/documents/documentStore/history/durableDocumentReload.js.map +1 -0
  189. package/stores/documents/documentStore/{historyRebuild.js → history/historyRebuild.js} +6 -6
  190. package/stores/documents/documentStore/history/historyRebuild.js.map +1 -0
  191. package/stores/documents/{documentStore.d.ts → documentStore/index.d.ts} +5 -5
  192. package/stores/documents/{documentStore.js → documentStore/index.js} +18 -18
  193. package/stores/documents/documentStore/index.js.map +1 -0
  194. package/stores/documents/documentStore/{deferredInitialUpdate.js → initialization/deferredInitialUpdate.js} +9 -9
  195. package/stores/documents/documentStore/initialization/deferredInitialUpdate.js.map +1 -0
  196. package/stores/documents/documentStore/{initialization.js → initialization/index.js} +14 -14
  197. package/stores/documents/documentStore/initialization/index.js.map +1 -0
  198. package/stores/documents/documentStore/{initializationAttachments.js → initialization/initializationAttachments.js} +1 -1
  199. package/stores/documents/documentStore/initialization/initializationAttachments.js.map +1 -0
  200. package/stores/documents/documentStore/{initializationHistory.js → initialization/initializationHistory.js} +3 -3
  201. package/stores/documents/documentStore/initialization/initializationHistory.js.map +1 -0
  202. package/stores/documents/documentStore/{initializationRecovery.js → initialization/initializationRecovery.js} +7 -7
  203. package/stores/documents/documentStore/initialization/initializationRecovery.js.map +1 -0
  204. package/stores/documents/documentStore/mutationIdentityRevalidation.js.map +1 -1
  205. package/stores/documents/documentStore/mutations.js +2 -2
  206. package/stores/documents/documentStore/mutations.js.map +1 -1
  207. package/stores/documents/documentStore/pendingUpdateRefusal.js +1 -1
  208. package/stores/documents/documentStore/pendingUpdateRefusal.js.map +1 -1
  209. package/stores/documents/documentStore/persistence.js +3 -3
  210. package/stores/documents/documentStore/persistence.js.map +1 -1
  211. package/stores/documents/documentStore/{rotation.js → rotation/index.js} +14 -14
  212. package/stores/documents/documentStore/rotation/index.js.map +1 -0
  213. package/stores/documents/documentStore/{rotationProvenance.js → rotation/rotationProvenance.js} +2 -2
  214. package/stores/documents/documentStore/rotation/rotationProvenance.js.map +1 -0
  215. package/stores/documents/documentStore/{rotationSettlement.js → rotation/rotationSettlement.js} +9 -9
  216. package/stores/documents/documentStore/rotation/rotationSettlement.js.map +1 -0
  217. package/stores/documents/documentStore/rows.js +2 -2
  218. package/stores/documents/documentStore/rows.js.map +1 -1
  219. package/stores/documents/documentStore/state.js +1 -1
  220. package/stores/documents/documentStore/state.js.map +1 -1
  221. package/stores/documents/documentStore/{sync.js → sync/index.js} +7 -7
  222. package/stores/documents/documentStore/sync/index.js.map +1 -0
  223. package/stores/documents/documentStore/{pullContinuationInvalidation.js → sync/pullContinuationInvalidation.js} +3 -3
  224. package/stores/documents/documentStore/sync/pullContinuationInvalidation.js.map +1 -0
  225. package/stores/documents/documentStore/{remoteRevalidationTelemetry.js → sync/remoteRevalidationTelemetry.js} +1 -1
  226. package/stores/documents/documentStore/sync/remoteRevalidationTelemetry.js.map +1 -0
  227. package/stores/documents/documentStore/sync/remoteWork.js.map +1 -0
  228. package/stores/documents/documentStore/sync/syncAcceptedUpdateIds.js.map +1 -0
  229. package/stores/documents/documentStore/{syncAttachmentSettlement.js → sync/syncAttachmentSettlement.js} +3 -3
  230. package/stores/documents/documentStore/sync/syncAttachmentSettlement.js.map +1 -0
  231. package/stores/documents/documentStore/{syncAttachments.js → sync/syncAttachments.js} +7 -7
  232. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -0
  233. package/stores/documents/documentStore/{syncDetachedAttachments.js → sync/syncDetachedAttachments.js} +7 -7
  234. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -0
  235. package/stores/documents/documentStore/{syncFinalize.js → sync/syncFinalize.js} +9 -9
  236. package/stores/documents/documentStore/sync/syncFinalize.js.map +1 -0
  237. package/stores/documents/documentStore/sync/syncGeneration.js.map +1 -0
  238. package/stores/documents/documentStore/{syncOutgoingCoverage.js → sync/syncOutgoingCoverage.js} +4 -4
  239. package/stores/documents/documentStore/sync/syncOutgoingCoverage.js.map +1 -0
  240. package/stores/documents/documentStore/{syncRemoteSignals.js → sync/syncRemoteSignals.js} +4 -4
  241. package/stores/documents/documentStore/sync/syncRemoteSignals.js.map +1 -0
  242. package/stores/documents/documentStore/{syncRequest.js → sync/syncRequest.js} +8 -8
  243. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -0
  244. package/stores/documents/documentStore/{syncShared.js → sync/syncShared.js} +8 -8
  245. package/stores/documents/documentStore/sync/syncShared.js.map +1 -0
  246. package/stores/documents/documentStore/{syncUpdateImport.js → sync/syncUpdateImport.js} +3 -3
  247. package/stores/documents/documentStore/sync/syncUpdateImport.js.map +1 -0
  248. package/stores/documents/documentStore/{versionCoverage.js → sync/versionCoverage.js} +1 -1
  249. package/stores/documents/index.d.ts +1 -1
  250. package/stores/documents/index.js +1 -1
  251. package/stores/local-projection/localProjectionStore.d.ts +1 -1
  252. package/stores/local-projection/localProjectionStore.js +1 -1
  253. package/stores/local-projection/localProjectionStore.js.map +1 -1
  254. package/stores/local-projection/registry.d.ts +1 -1
  255. package/stores/local-projection/types.d.ts +1 -1
  256. package/workflows/blobs/hydration/decrypt.js +1 -1
  257. package/workflows/blobs/hydration/decrypt.js.map +1 -1
  258. package/workflows/container-contents/container-state/{createAdoption.js → create/createAdoption.js} +6 -6
  259. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -0
  260. package/workflows/container-contents/container-state/{createChild.js → create/createChild.js} +7 -7
  261. package/workflows/container-contents/container-state/create/createChild.js.map +1 -0
  262. package/workflows/container-contents/container-state/{createIntentDepth.js → create/createIntentDepth.js} +2 -2
  263. package/workflows/container-contents/container-state/create/createIntentDepth.js.map +1 -0
  264. package/workflows/container-contents/container-state/create/createIntentSettlement.js.map +1 -0
  265. package/workflows/container-contents/container-state/{createIntentSync.js → create/createIntentSync.js} +7 -7
  266. package/workflows/container-contents/container-state/create/createIntentSync.js.map +1 -0
  267. package/workflows/container-contents/container-state/{createTerminalFailure.js → create/createTerminalFailure.js} +2 -2
  268. package/workflows/container-contents/container-state/create/createTerminalFailure.js.map +1 -0
  269. package/workflows/container-contents/container-state/{createWithMetadata.js → create/createWithMetadata.js} +9 -9
  270. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -0
  271. package/workflows/container-contents/container-state/{createWithMetadataPlan.js → create/createWithMetadataPlan.js} +4 -4
  272. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -0
  273. package/workflows/container-contents/container-state/{localPurgeScope.js → purge/localPurgeScope.js} +1 -1
  274. package/workflows/container-contents/container-state/purge/localPurgeScope.js.map +1 -0
  275. package/workflows/container-contents/container-state/{purgeTree.js → purge/purgeTree.js} +5 -5
  276. package/workflows/container-contents/container-state/purge/purgeTree.js.map +1 -0
  277. package/workflows/container-contents/container-state/purge/purgeTreeCollection.js.map +1 -0
  278. package/workflows/container-contents/container-state/{purgeTreeContainerDeletion.js → purge/purgeTreeContainerDeletion.js} +1 -1
  279. package/workflows/container-contents/container-state/purge/purgeTreeContainerDeletion.js.map +1 -0
  280. package/workflows/container-contents/container-state/{purgeTreeScope.js → purge/purgeTreeScope.js} +8 -8
  281. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -0
  282. package/workflows/container-contents/container-state/{readLocalPurgeScope.js → purge/readLocalPurgeScope.js} +3 -3
  283. package/workflows/container-contents/container-state/purge/readLocalPurgeScope.js.map +1 -0
  284. package/workflows/container-contents/container-state/remote.js +2 -2
  285. package/workflows/container-contents/container-state/remote.js.map +1 -1
  286. package/workflows/container-contents/container-state/{groupGrantVerification.js → share/groupGrantVerification.js} +8 -8
  287. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -0
  288. package/workflows/container-contents/container-state/{groupShareEpoch.js → share/groupShareEpoch.js} +2 -2
  289. package/workflows/container-contents/container-state/share/groupShareEpoch.js.map +1 -0
  290. package/workflows/container-contents/container-state/{share.js → share/index.js} +8 -8
  291. package/workflows/container-contents/container-state/share/index.js.map +1 -0
  292. package/workflows/container-contents/container-state/{sharePersistence.js → share/sharePersistence.js} +3 -3
  293. package/workflows/container-contents/container-state/share/sharePersistence.js.map +1 -0
  294. package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js +1 -1
  295. package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js.map +1 -1
  296. package/workflows/container-contents/documentDiscovery/index.js +1 -1
  297. package/workflows/container-contents/documentDiscovery/index.js.map +1 -1
  298. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  299. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  300. package/workflows/container-contents/remoteHydration/destination/destinationPrefetch.js.map +1 -0
  301. package/workflows/container-contents/remoteHydration/destination/destinationRoleCache.js.map +1 -0
  302. package/workflows/container-contents/remoteHydration/{destinationRootReload.js → destination/destinationRootReload.js} +1 -1
  303. package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js.map +1 -0
  304. package/workflows/container-contents/remoteHydration/{replacementBinding.js → destination/replacementBinding.js} +5 -5
  305. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -0
  306. package/workflows/container-contents/remoteHydration/{verifiedDestination.js → destination/verifiedDestination.js} +9 -9
  307. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -0
  308. package/workflows/container-contents/remoteHydration/index.js +4 -4
  309. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  310. package/workflows/container-contents/remoteHydration/lanes/childIndex.js.map +1 -0
  311. package/workflows/container-contents/remoteHydration/{laneFetchMarkers.js → lanes/laneFetchMarkers.js} +1 -1
  312. package/workflows/container-contents/remoteHydration/lanes/laneFetchMarkers.js.map +1 -0
  313. package/workflows/container-contents/remoteHydration/{parentLaneFetch.js → lanes/parentLaneFetch.js} +2 -2
  314. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js.map +1 -0
  315. package/workflows/container-contents/remoteHydration/lanes/parentLaneQueue.js.map +1 -0
  316. package/workflows/container-contents/remoteHydration/principalPolicyCache.js +1 -1
  317. package/workflows/container-contents/remoteHydration/principalPolicyCache.js.map +1 -1
  318. package/workflows/container-contents/remoteHydration/reconciliation.js +2 -2
  319. package/workflows/container-contents/remoteHydration/reconciliation.js.map +1 -1
  320. package/workflows/container-contents/remoteHydration/remoteContainers/containerStateFingerprint.js.map +1 -0
  321. package/workflows/container-contents/remoteHydration/{insertRemoteContainer.js → remoteContainers/insertRemoteContainer.js} +6 -6
  322. package/workflows/container-contents/remoteHydration/remoteContainers/insertRemoteContainer.js.map +1 -0
  323. package/workflows/container-contents/remoteHydration/{remoteContainerPageHydration.js → remoteContainers/remoteContainerPageHydration.js} +7 -7
  324. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -0
  325. package/workflows/container-contents/remoteHydration/{remoteContainerState.js → remoteContainers/remoteContainerState.js} +9 -9
  326. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -0
  327. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerTimestamps.js.map +1 -0
  328. package/workflows/container-contents/remoteHydration/tombstoneApplication.js +2 -2
  329. package/workflows/container-contents/remoteHydration/tombstoneApplication.js.map +1 -1
  330. package/workflows/containers/child/{createProjection.d.ts → create/createProjection.d.ts} +2 -2
  331. package/workflows/containers/child/{createProjection.js → create/createProjection.js} +2 -2
  332. package/workflows/containers/child/create/createProjection.js.map +1 -0
  333. package/workflows/containers/child/{createSubmission.d.ts → create/createSubmission.d.ts} +7 -7
  334. package/workflows/containers/child/{createSubmission.js → create/createSubmission.js} +2 -2
  335. package/workflows/containers/child/create/createSubmission.js.map +1 -0
  336. package/workflows/containers/child/{create.d.ts → create/index.d.ts} +5 -5
  337. package/workflows/containers/child/{create.js → create/index.js} +15 -15
  338. package/workflows/containers/child/create/index.js.map +1 -0
  339. package/workflows/containers/child/{move.d.ts → move/index.d.ts} +5 -5
  340. package/workflows/containers/child/{move.js → move/index.js} +12 -12
  341. package/workflows/containers/child/move/index.js.map +1 -0
  342. package/workflows/containers/child/{moveArtifacts.js → move/moveArtifacts.js} +3 -3
  343. package/workflows/containers/child/move/moveArtifacts.js.map +1 -0
  344. package/workflows/containers/child/{moveRotation.js → move/moveRotation.js} +3 -3
  345. package/workflows/containers/child/move/moveRotation.js.map +1 -0
  346. package/workflows/containers/child/{moveWraps.js → move/moveWraps.js} +5 -5
  347. package/workflows/containers/child/move/moveWraps.js.map +1 -0
  348. package/workflows/containers/child/mutationSubmit.js +1 -1
  349. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  350. package/workflows/containers/child/{carriedDescendantRekeys.js → rekey/carriedDescendantRekeys.js} +4 -4
  351. package/workflows/containers/child/rekey/carriedDescendantRekeys.js.map +1 -0
  352. package/workflows/containers/child/{rekey.d.ts → rekey/index.d.ts} +6 -6
  353. package/workflows/containers/child/{rekey.js → rekey/index.js} +13 -13
  354. package/workflows/containers/child/rekey/index.js.map +1 -0
  355. package/workflows/containers/child/{keyringOverrideLineage.d.ts → rekey/keyringOverrideLineage.d.ts} +1 -1
  356. package/workflows/containers/child/{keyringOverrideLineage.js → rekey/keyringOverrideLineage.js} +1 -1
  357. package/workflows/containers/child/{rekeyProjection.d.ts → rekey/rekeyProjection.d.ts} +2 -2
  358. package/workflows/containers/child/{rekeyProjection.js → rekey/rekeyProjection.js} +3 -3
  359. package/workflows/containers/child/rekey/rekeyProjection.js.map +1 -0
  360. package/workflows/containers/child/{rekeyRemote.d.ts → rekey/rekeyRemote.d.ts} +6 -6
  361. package/workflows/containers/child/{rekeyRemote.js → rekey/rekeyRemote.js} +2 -2
  362. package/workflows/containers/child/rekey/rekeyRemote.js.map +1 -0
  363. package/workflows/containers/child/revoke.js +5 -5
  364. package/workflows/containers/child/revoke.js.map +1 -1
  365. package/workflows/containers/child/{replacementPrincipalPolicyReferences.js → rotation/replacementPrincipalPolicyReferences.js} +2 -2
  366. package/workflows/containers/child/rotation/replacementPrincipalPolicyReferences.js.map +1 -0
  367. package/workflows/containers/child/{rotationContext.js → rotation/rotationContext.js} +5 -5
  368. package/workflows/containers/child/rotation/rotationContext.js.map +1 -0
  369. package/workflows/containers/child/{rotationPrincipalPolicies.js → rotation/rotationPrincipalPolicies.js} +2 -2
  370. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js.map +1 -0
  371. package/workflows/containers/child/{rotationWraps.js → rotation/rotationWraps.js} +1 -1
  372. package/workflows/containers/child/rotation/rotationWraps.js.map +1 -0
  373. package/workflows/containers/child/{currentShareGrantMutation.js → share/currentShareGrantMutation.js} +6 -6
  374. package/workflows/containers/child/share/currentShareGrantMutation.js.map +1 -0
  375. package/workflows/containers/child/{currentSharePrincipalPolicy.js → share/currentSharePrincipalPolicy.js} +10 -10
  376. package/workflows/containers/child/share/currentSharePrincipalPolicy.js.map +1 -0
  377. package/workflows/containers/child/{share.d.ts → share/index.d.ts} +8 -8
  378. package/workflows/containers/child/{share.js → share/index.js} +10 -10
  379. package/workflows/containers/child/share/index.js.map +1 -0
  380. package/workflows/containers/child/{runtimeCurrentGroupShare.js → share/runtimeCurrentGroupShare.js} +6 -6
  381. package/workflows/containers/child/share/runtimeCurrentGroupShare.js.map +1 -0
  382. package/workflows/containers/child/{shareAncestorRepair.js → share/shareAncestorRepair.js} +4 -4
  383. package/workflows/containers/child/share/shareAncestorRepair.js.map +1 -0
  384. package/workflows/containers/child/{shareMaterialization.d.ts → share/shareMaterialization.d.ts} +5 -5
  385. package/workflows/containers/child/{shareMaterialization.js → share/shareMaterialization.js} +7 -7
  386. package/workflows/containers/child/share/shareMaterialization.js.map +1 -0
  387. package/workflows/containers/child/{sharePlanCore.d.ts → share/sharePlanCore.d.ts} +7 -7
  388. package/workflows/containers/child/{sharePlanCore.js → share/sharePlanCore.js} +6 -6
  389. package/workflows/containers/child/share/sharePlanCore.js.map +1 -0
  390. package/workflows/containers/child/{sharePrincipalPolicy.d.ts → share/sharePrincipalPolicy.d.ts} +9 -9
  391. package/workflows/containers/child/{sharePrincipalPolicy.js → share/sharePrincipalPolicy.js} +13 -13
  392. package/workflows/containers/child/share/sharePrincipalPolicy.js.map +1 -0
  393. package/workflows/containers/child/share/shareProjection.js.map +1 -0
  394. package/workflows/containers/index.d.ts +10 -10
  395. package/workflows/containers/index.js +10 -10
  396. package/workflows/containers/index.js.map +1 -1
  397. package/workflows/documents/linkSet/linkSetAuthority.js +1 -1
  398. package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -1
  399. package/workflows/documents/linkSet/linkSetBlobRewraps.js +1 -1
  400. package/workflows/documents/linkSet/linkSetBlobRewraps.js.map +1 -1
  401. package/workflows/documents/linkSet/linkSetProjectionSeed.js +1 -1
  402. package/workflows/documents/linkSet/linkSetProjectionSeed.js.map +1 -1
  403. package/workflows/documents/purge/index.js +1 -1
  404. package/workflows/documents/purge/index.js.map +1 -1
  405. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +2 -2
  406. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  407. package/workflows/organizations/rematerialization/precedingPrincipalRematerialization.js +1 -1
  408. package/workflows/organizations/rematerialization/precedingPrincipalRematerialization.js.map +1 -1
  409. package/workflows/organizations/rematerialization/principalContainerRematerialization.js +5 -5
  410. package/workflows/organizations/rematerialization/principalContainerRematerialization.js.map +1 -1
  411. package/workflows/organizations/rematerialization/principalContainerRematerializationPlanning.js +1 -1
  412. package/workflows/organizations/rematerialization/principalContainerRematerializationPlanning.js.map +1 -1
  413. package/workflows/organizations/rematerialization/principalContainerRematerializationTargets.js +1 -1
  414. package/workflows/organizations/rematerialization/principalContainerRematerializationTargets.js.map +1 -1
  415. package/workflows/principals/policyCache/index.js +1 -1
  416. package/workflows/principals/policyCache/index.js.map +1 -1
  417. package/workflows/principals/policyRepair.js +1 -1
  418. package/workflows/principals/policyRepair.js.map +1 -1
  419. package/workflows/registration/organizationProvisioningArtifacts.d.ts +1 -1
  420. package/workflows/registration/provisioningBootstrapBuilders.js +1 -1
  421. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +0 -1
  422. package/data/keyingProjectionVerification/bundleVerification.js.map +0 -1
  423. package/data/keyingProjectionVerification/checkpointContext.js.map +0 -1
  424. package/data/keyingProjectionVerification/containerAncestorCitations.js.map +0 -1
  425. package/data/keyingProjectionVerification/containerDestinationVerification.js.map +0 -1
  426. package/data/keyingProjectionVerification/containerManifestVerification.js.map +0 -1
  427. package/data/keyingProjectionVerification/containerPathVerification.js.map +0 -1
  428. package/data/keyingProjectionVerification/containerProjectionVerification.js.map +0 -1
  429. package/data/keyingProjectionVerification/documentDependencyPaths.js.map +0 -1
  430. package/data/keyingProjectionVerification/documentManifestPolicies.js.map +0 -1
  431. package/data/keyingProjectionVerification/documentManifestVerification.js.map +0 -1
  432. package/data/keyingProjectionVerification/documentProjectionVerification.js.map +0 -1
  433. package/data/keyingProjectionVerification/documentPurgeCheckpointCurrency.js.map +0 -1
  434. package/data/keyingProjectionVerification/documentPurgeCheckpointEnforcement.js.map +0 -1
  435. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js.map +0 -1
  436. package/data/keyingProjectionVerification/documentPurgePolicyCheckpoints.js.map +0 -1
  437. package/data/keyingProjectionVerification/documentPurgePolicyCurrency.js.map +0 -1
  438. package/data/keyingProjectionVerification/documentPurgePrincipalEvidence.js.map +0 -1
  439. package/data/keyingProjectionVerification/documentPurgeProofVerification.js.map +0 -1
  440. package/data/keyingProjectionVerification/manifestCheckpointVerification.js.map +0 -1
  441. package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js.map +0 -1
  442. package/data/keyingProjectionVerification/organizationFounderBinding.js.map +0 -1
  443. package/data/keyingProjectionVerification/principalPolicyCache.js.map +0 -1
  444. package/data/keyingProjectionVerification/principalPolicyVerification.js.map +0 -1
  445. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js.map +0 -1
  446. package/data/keyingProjectionVerification/projectionPolicyEvidence.js.map +0 -1
  447. package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js.map +0 -1
  448. package/stores/container-contents/backgroundHydration.js.map +0 -1
  449. package/stores/container-contents/containerPurgeCore.js.map +0 -1
  450. package/stores/container-contents/containerStateMap.js.map +0 -1
  451. package/stores/container-contents/containerStatePersistence.js.map +0 -1
  452. package/stores/container-contents/documentRecovery.js.map +0 -1
  453. package/stores/container-contents/documentRotation.js.map +0 -1
  454. package/stores/container-contents/documentWork.js.map +0 -1
  455. package/stores/container-contents/emptyTrashOperation.js.map +0 -1
  456. package/stores/container-contents/existingSystemContainer.js.map +0 -1
  457. package/stores/container-contents/groupRewrapOperation.js.map +0 -1
  458. package/stores/container-contents/missingContainerState.js.map +0 -1
  459. package/stores/container-contents/missingSyncedContainerState.js.map +0 -1
  460. package/stores/container-contents/operations.js.map +0 -1
  461. package/stores/container-contents/organizationMetadataSystemContainer.js.map +0 -1
  462. package/stores/container-contents/purgeContainerOperation.js.map +0 -1
  463. package/stores/container-contents/reconcilableContainer.js.map +0 -1
  464. package/stores/container-contents/remoteBackedContainerState.js.map +0 -1
  465. package/stores/container-contents/remoteContainerIngestion.js.map +0 -1
  466. package/stores/container-contents/remoteEventProjectionInvalidation.js.map +0 -1
  467. package/stores/container-contents/remoteEventSync.js.map +0 -1
  468. package/stores/container-contents/remoteHydrationRequest.js.map +0 -1
  469. package/stores/container-contents/remoteWriteGuards.js.map +0 -1
  470. package/stores/container-contents/remoteWriteQueue.js.map +0 -1
  471. package/stores/container-contents/reportShareFailure.js.map +0 -1
  472. package/stores/container-contents/setContainerIconOperation.js.map +0 -1
  473. package/stores/container-contents/shareOperations.js.map +0 -1
  474. package/stores/container-contents/startupHydration.js.map +0 -1
  475. package/stores/container-contents/syncAgent.js.map +0 -1
  476. package/stores/container-contents/syncAgentTypes.js.map +0 -1
  477. package/stores/container-contents/syncLaneIteration.js.map +0 -1
  478. package/stores/container-contents/systemContainerHydration.js.map +0 -1
  479. package/stores/container-contents/systemContainerIcon.js.map +0 -1
  480. package/stores/container-contents/systemContainerLookup.js.map +0 -1
  481. package/stores/container-contents/systemContainerPostCreate.js.map +0 -1
  482. package/stores/container-contents/systemContainerPromotion.js.map +0 -1
  483. package/stores/container-contents/writeGeneration.js.map +0 -1
  484. package/stores/documents/documentStore/attachmentDetachState.js.map +0 -1
  485. package/stores/documents/documentStore/attachmentHydration.js.map +0 -1
  486. package/stores/documents/documentStore/attachmentHydrationCommit.js.map +0 -1
  487. package/stores/documents/documentStore/attachmentIntents.js.map +0 -1
  488. package/stores/documents/documentStore/attachmentMutationPersistence.js.map +0 -1
  489. package/stores/documents/documentStore/attachmentPersistFollowup.js.map +0 -1
  490. package/stores/documents/documentStore/attachmentPersistence.js.map +0 -1
  491. package/stores/documents/documentStore/attachmentRemoval.js.map +0 -1
  492. package/stores/documents/documentStore/attachmentSnapshot.js.map +0 -1
  493. package/stores/documents/documentStore/attachmentSourceUpload.js.map +0 -1
  494. package/stores/documents/documentStore/attachmentStaging.js.map +0 -1
  495. package/stores/documents/documentStore/attachmentUploadAttempt.js.map +0 -1
  496. package/stores/documents/documentStore/attachmentUploadLane.js.map +0 -1
  497. package/stores/documents/documentStore/attachmentUploadResume.js.map +0 -1
  498. package/stores/documents/documentStore/attachmentWriteGeneration.js.map +0 -1
  499. package/stores/documents/documentStore/attachments.js.map +0 -1
  500. package/stores/documents/documentStore/deferredInitialUpdate.js.map +0 -1
  501. package/stores/documents/documentStore/documentHistoryCompaction.js.map +0 -1
  502. package/stores/documents/documentStore/durableDocumentReload.js.map +0 -1
  503. package/stores/documents/documentStore/historyRebuild.js.map +0 -1
  504. package/stores/documents/documentStore/initialization.js.map +0 -1
  505. package/stores/documents/documentStore/initializationAttachments.js.map +0 -1
  506. package/stores/documents/documentStore/initializationHistory.js.map +0 -1
  507. package/stores/documents/documentStore/initializationRecovery.js.map +0 -1
  508. package/stores/documents/documentStore/pullContinuationInvalidation.js.map +0 -1
  509. package/stores/documents/documentStore/remoteRevalidationTelemetry.js.map +0 -1
  510. package/stores/documents/documentStore/remoteWork.js.map +0 -1
  511. package/stores/documents/documentStore/rotation.js.map +0 -1
  512. package/stores/documents/documentStore/rotationProvenance.js.map +0 -1
  513. package/stores/documents/documentStore/rotationSettlement.js.map +0 -1
  514. package/stores/documents/documentStore/sync.js.map +0 -1
  515. package/stores/documents/documentStore/syncAcceptedUpdateIds.js.map +0 -1
  516. package/stores/documents/documentStore/syncAttachmentSettlement.js.map +0 -1
  517. package/stores/documents/documentStore/syncAttachments.js.map +0 -1
  518. package/stores/documents/documentStore/syncDetachedAttachments.js.map +0 -1
  519. package/stores/documents/documentStore/syncFinalize.js.map +0 -1
  520. package/stores/documents/documentStore/syncGeneration.js.map +0 -1
  521. package/stores/documents/documentStore/syncOutgoingCoverage.js.map +0 -1
  522. package/stores/documents/documentStore/syncRemoteSignals.js.map +0 -1
  523. package/stores/documents/documentStore/syncRequest.js.map +0 -1
  524. package/stores/documents/documentStore/syncShared.js.map +0 -1
  525. package/stores/documents/documentStore/syncUpdateImport.js.map +0 -1
  526. package/stores/documents/documentStore.js.map +0 -1
  527. package/workflows/container-contents/container-state/createAdoption.js.map +0 -1
  528. package/workflows/container-contents/container-state/createChild.js.map +0 -1
  529. package/workflows/container-contents/container-state/createIntentDepth.js.map +0 -1
  530. package/workflows/container-contents/container-state/createIntentSettlement.js.map +0 -1
  531. package/workflows/container-contents/container-state/createIntentSync.js.map +0 -1
  532. package/workflows/container-contents/container-state/createTerminalFailure.js.map +0 -1
  533. package/workflows/container-contents/container-state/createWithMetadata.js.map +0 -1
  534. package/workflows/container-contents/container-state/createWithMetadataPlan.js.map +0 -1
  535. package/workflows/container-contents/container-state/groupGrantVerification.js.map +0 -1
  536. package/workflows/container-contents/container-state/groupShareEpoch.js.map +0 -1
  537. package/workflows/container-contents/container-state/localPurgeScope.js.map +0 -1
  538. package/workflows/container-contents/container-state/purgeTree.js.map +0 -1
  539. package/workflows/container-contents/container-state/purgeTreeCollection.js.map +0 -1
  540. package/workflows/container-contents/container-state/purgeTreeContainerDeletion.js.map +0 -1
  541. package/workflows/container-contents/container-state/purgeTreeScope.js.map +0 -1
  542. package/workflows/container-contents/container-state/readLocalPurgeScope.js.map +0 -1
  543. package/workflows/container-contents/container-state/share.js.map +0 -1
  544. package/workflows/container-contents/container-state/sharePersistence.js.map +0 -1
  545. package/workflows/container-contents/remoteHydration/childIndex.js.map +0 -1
  546. package/workflows/container-contents/remoteHydration/containerStateFingerprint.js.map +0 -1
  547. package/workflows/container-contents/remoteHydration/destinationPrefetch.js.map +0 -1
  548. package/workflows/container-contents/remoteHydration/destinationRoleCache.js.map +0 -1
  549. package/workflows/container-contents/remoteHydration/destinationRootReload.js.map +0 -1
  550. package/workflows/container-contents/remoteHydration/insertRemoteContainer.js.map +0 -1
  551. package/workflows/container-contents/remoteHydration/laneFetchMarkers.js.map +0 -1
  552. package/workflows/container-contents/remoteHydration/parentLaneFetch.js.map +0 -1
  553. package/workflows/container-contents/remoteHydration/parentLaneQueue.js.map +0 -1
  554. package/workflows/container-contents/remoteHydration/remoteContainerPageHydration.js.map +0 -1
  555. package/workflows/container-contents/remoteHydration/remoteContainerState.js.map +0 -1
  556. package/workflows/container-contents/remoteHydration/remoteContainerTimestamps.js.map +0 -1
  557. package/workflows/container-contents/remoteHydration/replacementBinding.js.map +0 -1
  558. package/workflows/container-contents/remoteHydration/verifiedDestination.js.map +0 -1
  559. package/workflows/containers/child/carriedDescendantRekeys.js.map +0 -1
  560. package/workflows/containers/child/create.js.map +0 -1
  561. package/workflows/containers/child/createProjection.js.map +0 -1
  562. package/workflows/containers/child/createSubmission.js.map +0 -1
  563. package/workflows/containers/child/currentShareGrantMutation.js.map +0 -1
  564. package/workflows/containers/child/currentSharePrincipalPolicy.js.map +0 -1
  565. package/workflows/containers/child/move.js.map +0 -1
  566. package/workflows/containers/child/moveArtifacts.js.map +0 -1
  567. package/workflows/containers/child/moveRotation.js.map +0 -1
  568. package/workflows/containers/child/moveWraps.js.map +0 -1
  569. package/workflows/containers/child/rekey.js.map +0 -1
  570. package/workflows/containers/child/rekeyProjection.js.map +0 -1
  571. package/workflows/containers/child/rekeyRemote.js.map +0 -1
  572. package/workflows/containers/child/replacementPrincipalPolicyReferences.js.map +0 -1
  573. package/workflows/containers/child/rotationContext.js.map +0 -1
  574. package/workflows/containers/child/rotationPrincipalPolicies.js.map +0 -1
  575. package/workflows/containers/child/rotationWraps.js.map +0 -1
  576. package/workflows/containers/child/runtimeCurrentGroupShare.js.map +0 -1
  577. package/workflows/containers/child/share.js.map +0 -1
  578. package/workflows/containers/child/shareAncestorRepair.js.map +0 -1
  579. package/workflows/containers/child/shareMaterialization.js.map +0 -1
  580. package/workflows/containers/child/sharePlanCore.js.map +0 -1
  581. package/workflows/containers/child/sharePrincipalPolicy.js.map +0 -1
  582. package/workflows/containers/child/shareProjection.js.map +0 -1
  583. /package/data/keyingProjectionVerification/{containerCreateManifest.js.map → container/containerCreateManifest.js.map} +0 -0
  584. /package/data/keyingProjectionVerification/{documentContainerProjections.js → document/documentContainerProjections.js} +0 -0
  585. /package/data/keyingProjectionVerification/{documentContainerProjections.js.map → document/documentContainerProjections.js.map} +0 -0
  586. /package/data/keyingProjectionVerification/{documentManifestPredecessor.js.map → document/documentManifestPredecessor.js.map} +0 -0
  587. /package/stores/container-contents/{containerStateMap.js → containerState/containerStateMap.js} +0 -0
  588. /package/stores/container-contents/{missingSyncedContainerState.js → containerState/missingSyncedContainerState.js} +0 -0
  589. /package/stores/container-contents/{reconcilableContainer.js → containerState/reconcilableContainer.js} +0 -0
  590. /package/stores/container-contents/{remoteHydrationRefresh.js → hydration/remoteHydrationRefresh.js} +0 -0
  591. /package/stores/container-contents/{remoteHydrationRefresh.js.map → hydration/remoteHydrationRefresh.js.map} +0 -0
  592. /package/stores/container-contents/{emptyTrashOperation.js → operations/emptyTrashOperation.js} +0 -0
  593. /package/stores/container-contents/{purgeContainerOperation.js → operations/purgeContainerOperation.js} +0 -0
  594. /package/stores/container-contents/{remoteBackedContainerState.js → remoteEvents/remoteBackedContainerState.js} +0 -0
  595. /package/stores/container-contents/{writeGeneration.js → remoteWrites/writeGeneration.js} +0 -0
  596. /package/stores/container-contents/{syncAgentTypes.js → syncAgent/syncAgentTypes.js} +0 -0
  597. /package/stores/container-contents/{systemContainerLookup.js → systemContainers/systemContainerLookup.js} +0 -0
  598. /package/stores/documents/documentStore/{attachmentPersistFollowup.js → attachments/attachmentPersistFollowup.js} +0 -0
  599. /package/stores/documents/documentStore/{attachmentSnapshot.js → attachments/attachmentSnapshot.js} +0 -0
  600. /package/stores/documents/documentStore/{remoteWork.js → sync/remoteWork.js} +0 -0
  601. /package/stores/documents/documentStore/{syncAcceptedUpdateIds.js → sync/syncAcceptedUpdateIds.js} +0 -0
  602. /package/stores/documents/documentStore/{syncGeneration.js → sync/syncGeneration.js} +0 -0
  603. /package/stores/documents/documentStore/{versionCoverage.js.map → sync/versionCoverage.js.map} +0 -0
  604. /package/workflows/container-contents/container-state/{createIntentSettlement.js → create/createIntentSettlement.js} +0 -0
  605. /package/workflows/container-contents/container-state/{purgeProgress.d.ts → purge/purgeProgress.d.ts} +0 -0
  606. /package/workflows/container-contents/container-state/{purgeProgress.js → purge/purgeProgress.js} +0 -0
  607. /package/workflows/container-contents/container-state/{purgeProgress.js.map → purge/purgeProgress.js.map} +0 -0
  608. /package/workflows/container-contents/container-state/{purgeTreeCollection.js → purge/purgeTreeCollection.js} +0 -0
  609. /package/workflows/container-contents/remoteHydration/{destinationPrefetch.js → destination/destinationPrefetch.js} +0 -0
  610. /package/workflows/container-contents/remoteHydration/{destinationRoleCache.js → destination/destinationRoleCache.js} +0 -0
  611. /package/workflows/container-contents/remoteHydration/{childIndex.js → lanes/childIndex.js} +0 -0
  612. /package/workflows/container-contents/remoteHydration/{parentLaneQueue.js → lanes/parentLaneQueue.js} +0 -0
  613. /package/workflows/container-contents/remoteHydration/{containerStateFingerprint.js → remoteContainers/containerStateFingerprint.js} +0 -0
  614. /package/workflows/container-contents/remoteHydration/{remoteContainerTimestamps.js → remoteContainers/remoteContainerTimestamps.js} +0 -0
  615. /package/workflows/containers/child/{keyringOverrideLineage.js.map → rekey/keyringOverrideLineage.js.map} +0 -0
  616. /package/workflows/containers/child/{shareProjection.js → share/shareProjection.js} +0 -0
@@ -0,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G,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} 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 { registerInternalDocumentRelink } from \"./internalRelink\";\nimport { setDocumentStructuredFields, setDocumentText } from \"./mutations\";\nimport { assertDocumentStoreCanRotateContentKey } from \"./rotation\";\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 {\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 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 assertBackingDocumentStoreCanRotate(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (!(await ensureDocumentStoreReady(state, scheduleSync)) || !state.doc) {\n throw new Error(\n \"Document must finish loading before its content key can rotate\",\n );\n }\n return assertDocumentStoreCanRotateContentKey(state);\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 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 { scheduleSync, state, withLiveSyncLane } = createBackingStoreContext(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n openOptions,\n );\n\n const store: DocumentStore = {\n addRow: (fields) =>\n withLiveSyncLane(() =>\n addRowToDocumentStore(state, scheduleSync, fields),\n ),\n assertCanRotateContentKey: () =>\n withLiveSyncLane(() =>\n assertBackingDocumentStoreCanRotate(state, scheduleSync),\n ),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n withLiveSyncLane(() =>\n attachFilesToDocumentStore(state, scheduleSync, files),\n ),\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 removeAttachment: (slotId: string) =>\n withLiveSyncLane(() =>\n removeAttachmentFromDocumentStore(state, scheduleSync, slotId),\n ),\n removeRow: (id) =>\n withLiveSyncLane(() =>\n removeRowFromDocumentStore(state, scheduleSync, id),\n ),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n withLiveSyncLane(() =>\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 withLiveSyncLane(() =>\n setDocumentStructuredFields(state, scheduleSync, kind, patch, options),\n ),\n setText: (value: string) =>\n withLiveSyncLane(() => setDocumentText(state, scheduleSync, value)),\n subscribe: (listener) => subscribeToDocumentStore(state, listener),\n updateRowFields: (id, patch) =>\n withLiveSyncLane(() =>\n updateRowInDocumentStore(state, scheduleSync, id, patch),\n ),\n updateRuntime: (runtime: DocumentsRuntime) =>\n updateDocumentStoreRuntime(state, runtime, scheduleSync),\n };\n return registerBackingStoreInternalRelink({\n scheduleSync,\n state,\n store,\n withLiveSyncLane,\n });\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 existingStore = registry.storesByKey.get(\n resolveDocumentStoreKey(registry, localId, initialDocumentId),\n );\n if (existingStore) {\n registerDocumentStore(\n domainScope,\n localId,\n existingStore,\n initialDocumentId,\n );\n return existingStore;\n }\n\n const nextStore = createDocumentStore(\n localId,\n runtime,\n defaultDocumentsPersistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\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,12 +1,12 @@
1
- import { encodeVersionVector, satisfiesVersionVector } from "../../../internal/loro/index.js";
2
- import { createPendingUpdateFields } from "../../../data/documents/documentSync.js";
3
- import { requestDocumentStoreSync } from "../registry.js";
4
- import { captureAttachmentWriteGeneration, isAttachmentWriteGenerationCurrent, } from "./attachmentWriteGeneration.js";
5
- import { reloadDocumentFromDurableHistory } from "./durableDocumentReload.js";
6
- import { ensureDocumentStoreInitialized } from "./initialization.js";
7
- import { advancePendingBaseVersion, pendingDeltaSinceBase, persistDocument, } from "./persistence.js";
8
- import { resetDocumentStore } from "./state.js";
9
- import { captureDocumentStoreSyncGeneration, isDocumentStoreSyncGenerationCurrent, } from "./syncGeneration.js";
1
+ import { encodeVersionVector, satisfiesVersionVector } from "../../../../internal/loro/index.js";
2
+ import { createPendingUpdateFields } from "../../../../data/documents/documentSync.js";
3
+ import { requestDocumentStoreSync } from "../../registry.js";
4
+ import { captureAttachmentWriteGeneration, isAttachmentWriteGenerationCurrent, } from "../attachments/attachmentWriteGeneration.js";
5
+ import { reloadDocumentFromDurableHistory } from "../history/durableDocumentReload.js";
6
+ import { advancePendingBaseVersion, pendingDeltaSinceBase, persistDocument, } from "../persistence.js";
7
+ import { resetDocumentStore } from "../state.js";
8
+ import { captureDocumentStoreSyncGeneration, isDocumentStoreSyncGenerationCurrent, } from "../sync/syncGeneration.js";
9
+ import { ensureDocumentStoreInitialized } from "./index.js";
10
10
  /**
11
11
  * Runs after the first attach on a store opened with `deferInitialUpdate`.
12
12
  * Creation committed the birth without a pending update, leaving the marker at
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deferredInitialUpdate.js","sourceRoot":"","sources":["deferredInitialUpdate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAC9E,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,C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CAAC,kBAAkB,CAAC;IAC7C,IAAI,CAAC,UAAU,IAAI,WAAW,KAAK,IAAI;QAAE,OAAO;IAChD,MAAM,eAAe,GAAG,mBAAmB,CAAC,UAAU,CAAC,CAAC;IACxD,wEAAwE;IACxE,IAAI,sBAAsB,CAAC,WAAW,EAAE,eAAe,CAAC;QAAE,OAAO;IACjE,MAAM,cAAc,GAAG,kCAAkC,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;IAC7E,IAAI,CAAC,cAAc;QAAE,OAAO;IAC5B,MAAM,aAAa,GAAG,yBAAyB,CAC7C,qBAAqB,CAAC,KAAK,EAAE,UAAU,CAAC,CACzC,CAAC;IACF,IAAI,CAAC,aAAa;QAAE,OAAO;IAC3B,MAAM,SAAS,GAAG,MAAM,eAAe,CACrC,KAAK,EACL,UAAU,EACV,EAAE,kBAAkB,EAAE,eAAe,EAAE,EACvC;QACE,aAAa;QACb,gCAAgC,EAAE,IAAI;QACtC,oBAAoB,EAAE,IAAI;KAC3B,EACD,cAAc,CACf,CAAC;IACF,IACE,CAAC,SAAS;QACV,CAAC,oCAAoC,CAAC,KAAK,EAAE,cAAc,CAAC,EAC5D,CAAC;QACD,OAAO;IACT,CAAC;IACD,yBAAyB,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import { encodeVersionVector, satisfiesVersionVector } from \"@tearleads/loro\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport {\n type AttachmentWriteGeneration,\n captureAttachmentWriteGeneration,\n isAttachmentWriteGenerationCurrent,\n} from \"../attachments/attachmentWriteGeneration\";\nimport { reloadDocumentFromDurableHistory } from \"../history/durableDocumentReload\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"../persistence\";\nimport { type DocumentStoreState, resetDocumentStore } from \"../state\";\nimport {\n captureDocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { ensureDocumentStoreInitialized } from \"./index\";\n\n/**\n * Runs after the first attach on a store opened with `deferInitialUpdate`.\n * Creation committed the birth without a pending update, leaving the marker at\n * the empty version so that attach's delta would carry it, and scheduled sync\n * passes wait meanwhile (see `canRunScheduledSync`) so none ships the birth on\n * its own. When the attach did not land (staging failed or returned null, its\n * persist was refused, or the store could not attach), enqueue the deferred\n * tail now so the document still syncs, without its attachment. Either way,\n * lift the hold and request the pass it skipped.\n */\nexport async function settleDeferredInitialUpdate(\n state: DocumentStoreState,\n writeGeneration: AttachmentWriteGeneration | null,\n): Promise<void> {\n if (!state.deferInitialUpdate) return;\n // Before initialization finishes no attach has touched a live doc, and a\n // reload here would install one behind initialization's back (or mark a\n // not-yet-created document removed). Lift the hold; initialization then\n // restores the empty marker and schedules the pass that ships the birth.\n if (!state.initialized) {\n state.deferInitialUpdate = false;\n return;\n }\n // A pass exports the live doc, so it must hold only durable content (see\n // restoreDurableLiveDocument) before the hold lifts. When that cannot be\n // shown, even after a transient failure, reinitialize from durable history\n // rather than latch the hold: the reset lifts it and drops the live doc.\n let durable = false;\n try {\n durable = await restoreDurableLiveDocument(state);\n } finally {\n if (!durable && state.deferInitialUpdate && state.doc) {\n resetDocumentStore(state);\n ensureDocumentStoreInitialized(state, () =>\n requestDocumentStoreSync(state),\n );\n } else if (!durable) {\n // No live doc remains to leak (a concurrent removal): just lift it.\n state.deferInitialUpdate = false;\n }\n }\n if (!durable) return;\n state.deferInitialUpdate = false;\n try {\n await enqueueDeferredTail(state, writeGeneration);\n } finally {\n requestDocumentStoreSync(state);\n }\n}\n\nfunction isLiveDocumentDurable(state: DocumentStoreState): boolean {\n return (\n state.doc !== null &&\n state.record !== null &&\n satisfiesVersionVector(\n state.record.snapshotEndVersion,\n encodeVersionVector(state.doc),\n )\n );\n}\n\n/**\n * A failed attach whose rollback reload could not run (its generation went\n * stale mid-stage) leaves the uncommitted slot in the live doc, and that slot\n * must never sync without its staged bytes. Reload durable history under a\n * fresh generation before trusting the live doc.\n */\nasync function restoreDurableLiveDocument(\n state: DocumentStoreState,\n): Promise<boolean> {\n if (isLiveDocumentDurable(state)) return true;\n const generation = captureDocumentStoreSyncGeneration(state, state.doc);\n if (generation) {\n await reloadDocumentFromDurableHistory({\n expectedGeneration: generation,\n preserveQueuedWritesWhenIdentityMatches: true,\n state,\n });\n }\n return isLiveDocumentDurable(state);\n}\n\nasync function enqueueDeferredTail(\n state: DocumentStoreState,\n writeGeneration: AttachmentWriteGeneration | null,\n): Promise<void> {\n // A reset or relink owns the replacement store; its deferred tail stays\n // durable and the next write or sync pass materializes it. With no attach\n // (nothing to attach, or the store was not writable) the live store owns it.\n const generation = writeGeneration ?? captureAttachmentWriteGeneration(state);\n if (!generation || !isAttachmentWriteGenerationCurrent(state, generation)) {\n return;\n }\n const currentDoc = state.doc;\n const baseVersion = state.pendingBaseVersion;\n if (!currentDoc || baseVersion === null) return;\n const documentVersion = encodeVersionVector(currentDoc);\n // Settled: the attach (or an earlier write) already enqueued the birth.\n if (satisfiesVersionVector(baseVersion, documentVersion)) return;\n const syncGeneration = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!syncGeneration) return;\n const pendingUpdate = createPendingUpdateFields(\n pendingDeltaSinceBase(state, currentDoc),\n );\n if (!pendingUpdate) return;\n const persisted = await persistDocument(\n state,\n currentDoc,\n { snapshotEndVersion: documentVersion },\n {\n pendingUpdate,\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n syncGeneration,\n );\n if (\n !persisted ||\n !isDocumentStoreSyncGenerationCurrent(state, syncGeneration)\n ) {\n return;\n }\n advancePendingBaseVersion(state, currentDoc);\n}\n"]}
@@ -1,19 +1,19 @@
1
- import { bytesToBase64 } from "../../../internal/encoding/index.js";
2
- import { emptyVersionVector, encodeVersionVector, exportAllUpdates, exportFullHistorySnapshot, mergeVersionVectors, } from "../../../internal/loro/index.js";
3
- import { DEFAULT_DOCUMENT_ACCESS_EPOCH, DEFAULT_DOCUMENT_KIND, } from "../../../data/documents/documentConstants.js";
4
- import { initializeStoredDocumentKind, readStoredDocumentState, } from "../../../data/documents/documentKinds.js";
5
- import { createPendingUpdateFields } from "../../../data/documents/documentSync.js";
6
- import { isDatabaseUnavailableError, loadPersistedDocumentStoreState, } from "../../../workflows/documents/index.js";
7
- import { chainIdentityWrite } from "./identityWriteChain.js";
1
+ import { bytesToBase64 } from "../../../../internal/encoding/index.js";
2
+ import { emptyVersionVector, encodeVersionVector, exportAllUpdates, exportFullHistorySnapshot, mergeVersionVectors, } from "../../../../internal/loro/index.js";
3
+ import { DEFAULT_DOCUMENT_ACCESS_EPOCH, DEFAULT_DOCUMENT_KIND, } from "../../../../data/documents/documentConstants.js";
4
+ import { initializeStoredDocumentKind, readStoredDocumentState, } from "../../../../data/documents/documentKinds.js";
5
+ import { createPendingUpdateFields } from "../../../../data/documents/documentSync.js";
6
+ import { isDatabaseUnavailableError, loadPersistedDocumentStoreState, } from "../../../../workflows/documents/index.js";
7
+ import { chainIdentityWrite } from "../identityWriteChain.js";
8
+ import { runDocumentOrphanMaintenance } from "../orphanMaintenance.js";
9
+ import { advancePendingBaseVersion, documentSummaryFromRecord, persistDocument, saveDocumentRecord, } from "../persistence.js";
10
+ import { setReadySnapshot, } from "../state.js";
11
+ import { createStoredDocument } from "../storedDocument.js";
12
+ import { logRevalidationScheduled } from "../sync/remoteRevalidationTelemetry.js";
13
+ import { allowDocumentStoreRemoteSync, captureDocumentStoreSyncGeneration, invalidateDocumentStoreRemoteSync, isDocumentStoreSyncGenerationCurrent, markDocumentStoreRemoteSyncPending, } from "../sync/syncGeneration.js";
8
14
  import { installPersistedAttachments, } from "./initializationAttachments.js";
9
15
  import { restoredRemoteTailCoverage, restorePersistedDocumentContent, } from "./initializationHistory.js";
10
16
  import { healLocalAttachmentDetachState, recoverDroppedAttachmentSlots, } from "./initializationRecovery.js";
11
- import { runDocumentOrphanMaintenance } from "./orphanMaintenance.js";
12
- import { advancePendingBaseVersion, documentSummaryFromRecord, persistDocument, saveDocumentRecord, } from "./persistence.js";
13
- import { logRevalidationScheduled } from "./remoteRevalidationTelemetry.js";
14
- import { setReadySnapshot, } from "./state.js";
15
- import { createStoredDocument } from "./storedDocument.js";
16
- import { allowDocumentStoreRemoteSync, captureDocumentStoreSyncGeneration, invalidateDocumentStoreRemoteSync, isDocumentStoreSyncGenerationCurrent, markDocumentStoreRemoteSyncPending, } from "./syncGeneration.js";
17
17
  async function createInitialDocumentRecord(state, nextDoc) {
18
18
  initializeStoredDocumentKind(nextDoc, state.initialDocumentKind, state.runtime.infra.documentProjectors);
19
19
  if (state.initialText.length > 0) {
@@ -327,4 +327,4 @@ export async function relinkDocumentStore(state, input, scheduleSync, commitSide
327
327
  }
328
328
  return documentSummaryFromRecord(persisted.record, persisted.updatedAt, state.runtime.infra.documentProjectors);
329
329
  }
330
- //# sourceMappingURL=initialization.js.map
330
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,GACxB,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAEL,0BAA0B,EAC1B,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EACL,yBAAyB,EACzB,yBAAyB,E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AC;IACd,CAAC;IACD,OAAO,yBAAyB,CAC9B,SAAS,CAAC,MAAM,EAChB,SAAS,CAAC,SAAS,EACnB,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,kBAAkB,CACvC,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n emptyVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistorySnapshot,\n mergeVersionVectors,\n} from \"@tearleads/loro\";\nimport {\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n} from \"../../../../data/documents/documentConstants\";\nimport {\n initializeStoredDocumentKind,\n readStoredDocumentState,\n} from \"../../../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../../../data/documents/documentSummary\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport {\n type DocumentRecord,\n isDatabaseUnavailableError,\n loadPersistedDocumentStoreState,\n} from \"../../../../workflows/documents\";\nimport type { DocumentStoreRelinkInput } from \"../../types\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport type { DocumentRelinkCommitSideEffect } from \"../internalRelink\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport {\n advancePendingBaseVersion,\n documentSummaryFromRecord,\n persistDocument,\n saveDocumentRecord,\n} from \"../persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"../state\";\nimport { createStoredDocument } from \"../storedDocument\";\nimport { logRevalidationScheduled } from \"../sync/remoteRevalidationTelemetry\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreSyncGeneration,\n invalidateDocumentStoreRemoteSync,\n isDocumentStoreSyncGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n} from \"../sync/syncGeneration\";\nimport {\n installPersistedAttachments,\n type LoadedDocumentStoreState,\n} from \"./initializationAttachments\";\nimport {\n type RestoredHistoryState,\n restoredRemoteTailCoverage,\n restorePersistedDocumentContent,\n} from \"./initializationHistory\";\nimport {\n healLocalAttachmentDetachState,\n recoverDroppedAttachmentSlots,\n} from \"./initializationRecovery\";\n\nasync function createInitialDocumentRecord(\n state: DocumentStoreState,\n nextDoc: DocumentState,\n): ReturnType<typeof saveDocumentRecord> {\n initializeStoredDocumentKind(\n nextDoc,\n state.initialDocumentKind,\n state.runtime.infra.documentProjectors,\n );\n if (state.initialText.length > 0) {\n nextDoc.getText(\"text\").update(state.initialText);\n }\n const initialDocumentState = readStoredDocumentState(\n nextDoc,\n state.runtime.infra.documentProjectors,\n );\n const hasInitialContent =\n state.initialText.length > 0 ||\n state.initialDocumentKind !== DEFAULT_DOCUMENT_KIND;\n const initialUpdate = hasInitialContent\n ? createPendingUpdateFields(exportAllUpdates(nextDoc))\n : null;\n // A deferred birth still commits its checkpoint, but leaves the marker at the\n // empty version with nothing queued: the promised attach exports every op\n // since that marker, so one update carries the birth and the attachment.\n const birthDurability = !initialUpdate\n ? {}\n : state.deferInitialUpdate\n ? { pendingBaseVersionOverride: emptyVersionVector() }\n : { pendingUpdate: initialUpdate };\n\n const created: DocumentRecord = {\n id: state.localId,\n containerId: state.runtime.state.containerId ?? null,\n documentId: state.initialDocumentId,\n documentKind: initialDocumentState.documentKind,\n text: initialDocumentState.text,\n title: initialDocumentState.title,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n accessEpoch: DEFAULT_DOCUMENT_ACCESS_EPOCH,\n accessStateHash: null,\n effectiveAccessLevel: \"admin\",\n lastCommitLsn: null,\n contentKeyBundle: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n };\n // The create-only persistence primitive commits the canonical row and birth\n // checkpoint together. A concurrent initializer either wins both or adopts\n // both, so it cannot replace another pane's history or keying state.\n const persisted = await saveDocumentRecord(\n state,\n nextDoc,\n {\n ...created,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n },\n {\n historyCheckpoint: {\n coveredTailIds: [],\n endVersionVector: encodeVersionVector(nextDoc),\n pruneCoveredLocalState: false,\n snapshot: bytesToBase64(exportFullHistorySnapshot(nextDoc)),\n },\n ...birthDurability,\n },\n );\n return persisted;\n}\n\nfunction installPersistedDocumentRecord(\n state: DocumentStoreState,\n record: NonNullable<DocumentStoreState[\"record\"]>,\n): void {\n state.record = record;\n state.pullContinuation = record.pullContinuation ?? null;\n}\n\ninterface RestoredInitialDocumentState {\n activePersistedState: LoadedDocumentStoreState;\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n}\n\nasync function restoreLoadedInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n const record = persistedState.document;\n if (!record) return null;\n const history = await restorePersistedDocumentContent(\n input.nextDoc,\n persistedState.historyRestoreState,\n );\n if (state.localWriteGeneration !== initializeGeneration) return null;\n installPersistedDocumentRecord(state, record);\n return {\n activePersistedState: persistedState,\n activeRecord: record,\n doc: input.nextDoc,\n history,\n };\n}\n\nasync function restoreOrCreateInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n if (persistedState.document) {\n return restoreLoadedInitialDocument(input);\n }\n\n const created = await createInitialDocumentRecord(state, input.nextDoc);\n if (!created || state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n const activePersistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n if (!activePersistedState.document) {\n throw new Error(\"Document creation completed without a durable record\");\n }\n const replacementDoc = await createStoredDocument(state);\n return restoreLoadedInitialDocument({\n initializeGeneration,\n nextDoc: replacementDoc,\n persistedState: activePersistedState,\n state,\n });\n}\n\nfunction restorePendingBaseVersion(input: {\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n state: DocumentStoreState;\n}): void {\n const { activeRecord, doc, history, state } = input;\n const markerBase =\n activeRecord.pendingBaseVersion ??\n (activeRecord.snapshotEndVersion.length > 0\n ? activeRecord.snapshotEndVersion\n : null);\n if (markerBase === null) {\n advancePendingBaseVersion(state, doc);\n return;\n }\n\n const remoteCoverage = restoredRemoteTailCoverage(history);\n state.pendingBaseVersion =\n remoteCoverage.length > 0\n ? mergeVersionVectors([markerBase, ...remoteCoverage])\n : markerBase;\n}\n\nasync function initializeDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (state.runtime.infra.dbStatus !== \"ready\") {\n return;\n }\n\n // A store reset while this fire-and-forget initialization is loading (a\n // runtime swap, or a local-edits discard that re-seeds the persisted rows)\n // must win: assigning the state loaded BEFORE the reset would bring the\n // replaced record and doc back to life. Every reset bumps the local write\n // generation, so a stale capture here aborts before each assignment batch.\n const initializeGeneration = state.localWriteGeneration;\n\n const nextDoc = await createStoredDocument(state);\n const persistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n const restored = await restoreOrCreateInitialDocument({\n initializeGeneration,\n nextDoc,\n persistedState,\n state,\n });\n if (!restored) {\n return;\n }\n const activePersistedState = restored.activePersistedState;\n installPersistedAttachments(state, activePersistedState);\n\n state.doc = restored.doc;\n // Restore the durable outgoing-delta marker. Re-seeding it to the restored\n // document's version would move it PAST any device-first `deferRemoteSync`\n // op (persisted into the durable history but deliberately left un-enqueued\n // and behind the marker), permanently dropping that op from sync across a\n // restart. When a marker was persisted, restore it so the next edit still\n // re-derives the deferred delta. Only seed for rows that never persisted\n // one, from the RECORD's persisted frontier rather than the restored\n // document: a crash between the tail append and the queue/marker writes can\n // resurrect ops the outgoing queue never durably received, and seeding from\n // the restored document would classify those as covered and orphan them\n // from sync forever.\n restorePendingBaseVersion({\n activeRecord: restored.activeRecord,\n doc: restored.doc,\n history: restored.history,\n state,\n });\n // Heal attachment slots lost to an interrupted attach write before marking\n // ready, so the recovered slots are in the snapshot the editor first renders\n // and are queued for sync. recoverDroppedAttachmentSlots advances the marker\n // again for whatever it re-derives. Both helpers gate every durable write\n // on this generation (validated inside the writes' serialized mutations),\n // so a reset mid-helper cannot repopulate discarded state.\n const writeGeneration = captureDocumentStoreSyncGeneration(\n state,\n restored.doc,\n );\n if (!writeGeneration) {\n return;\n }\n await recoverDroppedAttachmentSlots(state, restored.doc, writeGeneration);\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n await healLocalAttachmentDetachState(\n state,\n restored.doc,\n activePersistedState,\n writeGeneration,\n );\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n state.initialized = true;\n state.initializePromise = null;\n setReadySnapshot(state, restored.doc, false);\n\n if (restored.activeRecord.documentId && state.scheduleStartupRemoteSync) {\n // Websocket invalidations are intentionally session-local. A process can\n // stop before receiving a peer device's update event, and no event survives\n // the restart to distinguish a clean local snapshot from a stale one. Probe\n // each opened remote document once after loading it; unopened documents stay\n // lazy, while body and attachment state for a restored window converges.\n allowDocumentStoreRemoteSync(state);\n markDocumentStoreRemoteSyncPending(state, \"independent\");\n logRevalidationScheduled(state.runtime, \"startup\");\n }\n scheduleSync();\n void runDocumentOrphanMaintenance(state);\n}\n\nexport function ensureDocumentStoreInitialized(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (\n state.initialized ||\n state.initializePromise ||\n state.runtime.infra.dbStatus !== \"ready\"\n ) {\n return;\n }\n\n const initializePromise = initializeDocumentStore(state, scheduleSync).catch(\n (error: unknown) => {\n state.initializePromise = null;\n // A caller that deferred the birth for its attach may give up once\n // opening fails; never leave its durable birth holding sync. No attach\n // has reached a live doc yet, so lifting the hold ships nothing unsafe.\n state.deferInitialUpdate = false;\n\n if (isDatabaseUnavailableError(error)) {\n return;\n }\n\n throw error;\n },\n );\n state.initializePromise = initializePromise;\n void initializePromise.catch(() => undefined);\n}\n\nexport async function awaitInitializationForSync(state: DocumentStoreState) {\n if (!state.initializePromise) {\n return true;\n }\n\n try {\n await state.initializePromise;\n return true;\n } catch (error) {\n if (isDatabaseUnavailableError(error)) {\n return false;\n }\n\n throw error;\n }\n}\n\nexport async function ensureDocumentStoreReady(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): Promise<boolean> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (state.initialized) {\n return true;\n }\n\n if (!state.initializePromise) {\n return false;\n }\n\n return awaitInitializationForSync(state);\n}\n\nexport async function relinkDocumentStore(\n state: DocumentStoreState,\n input: DocumentStoreRelinkInput,\n scheduleSync: () => void,\n commitSideEffect?: DocumentRelinkCommitSideEffect,\n): Promise<DocumentSummary | null> {\n if (\n input.stillCurrent?.() === false ||\n !(await ensureDocumentStoreReady(state, scheduleSync)) ||\n input.stillCurrent?.() === false ||\n !state.doc\n ) {\n return null;\n }\n const currentDoc = state.doc;\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) return null;\n // Read the record and persist on the identity-write chain so an in-flight\n // eager create cannot interleave: a create that captured a null identity\n // before its network round trip would otherwise write the derived documentId\n // over the one this relink assigns.\n const persisted = await chainIdentityWrite(state, async () => {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n const currentDocumentId = state.record?.documentId ?? null;\n const currentAccessEpoch =\n state.record?.accessEpoch ?? DEFAULT_DOCUMENT_ACCESS_EPOCH;\n const patch: Partial<DocumentRecord> = {\n accessEpoch: Math.max(currentAccessEpoch, input.accessEpoch),\n accessStateHash:\n input.accessStateHash === undefined\n ? (state.record?.accessStateHash ?? null)\n : input.accessStateHash,\n containerId: input.containerId,\n documentId: input.documentId,\n };\n if (input.contentKeyBundle !== undefined) {\n patch.contentKeyBundle = input.contentKeyBundle;\n }\n if (input.documentKekTargets !== undefined) {\n patch.documentKekTargets = input.documentKekTargets;\n }\n if (input.documentManifestBundle !== undefined) {\n patch.documentManifestBundle = input.documentManifestBundle;\n }\n\n // Relink rewrites access/identity metadata, not content. If it lands while\n // the user is mid-edit, re-deriving text/structured fields from the\n // (possibly lagging) doc would republish a stale read over the live\n // optimistic snapshot and drop in-flight keystrokes; preserve the snapshot\n // like the keystroke and sync persists do.\n // A prior chained write may have cleared this store (resurrect-guard\n // refusal): persisting the captured doc against a null record would\n // resurrect the document as a create. The identity check runs inside\n // the chain, after every earlier write settled.\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n return null;\n }\n const result = await persistDocument(\n state,\n currentDoc,\n patch,\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n stillCurrent: input.stillCurrent,\n },\n generation,\n commitSideEffect,\n );\n if (result && currentDocumentId !== input.documentId) {\n state.writerProjection = null;\n invalidateDocumentStoreRemoteSync(state);\n }\n return result;\n });\n // A refused persist means the durable row vanished mid-relink (resurrect\n // guard); there is no summary to report.\n if (!persisted) {\n return null;\n }\n if (persisted.updatedAt === undefined) {\n return null;\n }\n return documentSummaryFromRecord(\n persisted.record,\n persisted.updatedAt,\n state.runtime.infra.documentProjectors,\n );\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { assignLocalAttachmentSlots } from "./attachmentPersistence.js";
1
+ import { assignLocalAttachmentSlots } from "../attachments/attachmentPersistence.js";
2
2
  export function installPersistedAttachments(state, persistedState) {
3
3
  state.pendingAttachments = persistedState.pendingAttachments;
4
4
  state.attachmentBlobIdBySlotId = {};
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initializationAttachments.js","sourceRoot":"","sources":["initializationAttachments.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,0BAA0B,EAAE,MAAM,sCAAsC,CAAC;AAOlF,MAAM,UAAU,2BAA2B,CACzC,KAAyB,EACzB,cAAwC;IAExC,KAAK,CAAC,kBAAkB,GAAG,cAAc,CAAC,kBAAkB,CAAC;IAC7D,KAAK,CAAC,wBAAwB,GAAG,EAAE,CAAC;IACpC,KAAK,CAAC,+BAA+B,GAAG,EAAE,CAAC;IAC3C,KAAK,CAAC,4BAA4B,GAAG,EAAE,CAAC;IACxC,0BAA0B,CAAC,KAAK,EAAE,cAAc,CAAC,gBAAgB,CAAC,CAAC;AACrE,CAAC","sourcesContent":["import type { loadPersistedDocumentStoreState } from \"../../../../workflows/documents\";\nimport { assignLocalAttachmentSlots } from \"../attachments/attachmentPersistence\";\nimport type { DocumentStoreState } from \"../state\";\n\nexport type LoadedDocumentStoreState = Awaited<\n ReturnType<typeof loadPersistedDocumentStoreState>\n>;\n\nexport function installPersistedAttachments(\n state: DocumentStoreState,\n persistedState: LoadedDocumentStoreState,\n): void {\n state.pendingAttachments = persistedState.pendingAttachments;\n state.attachmentBlobIdBySlotId = {};\n state.attachmentContentSha256BySlotId = {};\n state.attachmentStorageKeyBySlotId = {};\n assignLocalAttachmentSlots(state, persistedState.localAttachments);\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { base64ToBytes } from "../../../internal/encoding/index.js";
2
- import { getImportBlobMetadata, importSnapshot } from "../../../internal/loro/index.js";
3
- import { importDocumentHistoryTailUpdates, } from "../../../workflows/documents/index.js";
1
+ import { base64ToBytes } from "../../../../internal/encoding/index.js";
2
+ import { getImportBlobMetadata, importSnapshot } from "../../../../internal/loro/index.js";
3
+ import { importDocumentHistoryTailUpdates, } from "../../../../workflows/documents/index.js";
4
4
  function installRestoredDocumentContent(nextDoc, history) {
5
5
  if (history.snapshot.length > 0) {
6
6
  importSnapshot(nextDoc, base64ToBytes(history.snapshot));
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initializationHistory.js","sourceRoot":"","sources":["initializationHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACxE,OAAO,EAEL,gCAAgC,GACjC,MAAM,iCAAiC,CAAC;AAOzC,SAAS,8BAA8B,CACrC,OAAsB,EACtB,OAA6B;IAE7B,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAChC,cAAc,CAAC,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC3D,CAAC;IACD,gCAAgC,CAC9B,OAAO,EACP,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CACvD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,+BAA+B,CAC7C,OAAsB,EACtB,OAAoC;IAEpC,IAAI,CAAC,OAAO;QAAE,OAAO,IAAI,CAAC;IAC1B,8BAA8B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACjD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,MAAM,UAAU,0BAA0B,CACxC,OAAoC;IAEpC,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC;IACxB,OAAO,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;QAC5C,IAAI,MAAM,CAAC,MAAM,KAAK,QAAQ;YAAE,OAAO,EAAE,CAAC;QAC1C,IAAI,CAAC;YACH,OAAO;gBACL,qBAAqB,CAAC,aAAa,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;qBACpD,uBAAuB;aAC3B,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport { getImportBlobMetadata, importSnapshot } from \"@tearleads/loro\";\nimport {\n type DocumentsPersistence,\n importDocumentHistoryTailUpdates,\n} from \"../../../../workflows/documents\";\nimport type { DocumentState } from \"../state\";\n\nexport type RestoredHistoryState = NonNullable<\n Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n>;\n\nfunction installRestoredDocumentContent(\n nextDoc: DocumentState,\n history: RestoredHistoryState,\n): void {\n if (history.snapshot.length > 0) {\n importSnapshot(nextDoc, base64ToBytes(history.snapshot));\n }\n importDocumentHistoryTailUpdates(\n nextDoc,\n history.tailUpdates.map((update) => update.updateData),\n );\n}\n\nexport function restorePersistedDocumentContent(\n nextDoc: DocumentState,\n history: RestoredHistoryState | null,\n): RestoredHistoryState | null {\n if (!history) return null;\n installRestoredDocumentContent(nextDoc, history);\n return history;\n}\n\nexport function restoredRemoteTailCoverage(\n history: RestoredHistoryState | null,\n): string[] {\n if (!history) return [];\n return history.tailUpdates.flatMap((update) => {\n if (update.origin !== \"remote\") return [];\n try {\n return [\n getImportBlobMetadata(base64ToBytes(update.updateData))\n .partialEndVersionVector,\n ];\n } catch {\n return [];\n }\n });\n}\n"]}
@@ -1,10 +1,10 @@
1
- import { encodeVersionVector } from "../../../internal/loro/index.js";
2
- import { addDocumentAttachments, getDocumentAttachments, } from "../../../data/documents/documentContent.js";
3
- import { reconcileLocalAttachmentDetachState } from "./attachmentDetachState.js";
4
- import { saveLocalAttachmentRecord } from "./attachmentPersistence.js";
5
- import { rebaseDocumentAfterPendingUpdateRefusal } from "./pendingUpdateRefusal.js";
6
- import { advancePendingBaseVersion, enqueuePendingUpdate, pendingDeltaSinceBase, persistDocument, } from "./persistence.js";
7
- import { isDocumentStoreSyncGenerationCurrent } from "./syncGeneration.js";
1
+ import { encodeVersionVector } from "../../../../internal/loro/index.js";
2
+ import { addDocumentAttachments, getDocumentAttachments, } from "../../../../data/documents/documentContent.js";
3
+ import { reconcileLocalAttachmentDetachState } from "../attachments/attachmentDetachState.js";
4
+ import { saveLocalAttachmentRecord } from "../attachments/attachmentPersistence.js";
5
+ import { rebaseDocumentAfterPendingUpdateRefusal } from "../pendingUpdateRefusal.js";
6
+ import { advancePendingBaseVersion, enqueuePendingUpdate, pendingDeltaSinceBase, persistDocument, } from "../persistence.js";
7
+ import { isDocumentStoreSyncGenerationCurrent } from "../sync/syncGeneration.js";
8
8
  // Re-derive any attachment slot that lives in a durable pending-upload row but
9
9
  // is missing (or stale) in the loaded snapshot. The attach write path persists
10
10
  // the blob bytes + pending-attachment row BEFORE it enqueues the slot's CRDT op
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initializationRecovery.js","sourceRoot":"","sources":["initializationRecovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EACL,sBAAsB,EAEtB,sBAAsB,GACvB,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,mCAAmC,EAAE,MAAM,sCAAsC,CAAC;AAC3F,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EAAE,uCAAuC,EAAE,MAAM,yBAAyB,CAAC;AAClF,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,qBAAqB,EACrB,eAAe,GAChB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EAAE,oCAAoC,EAAE,MAAM,wBAAwB,CAAC;AAE9E,+EAA+E;AAC/E,+EAA+E;AAC/E,gFAAgF;AAChF,gFAAgF;AAChF,gFAAgF;AAChF,8EAA8E;AAC9E,gFAAgF;AAChF,kFAAkF;AAClF,6EAA6E;AAC7E,8DAA8D;AAC9D,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,KAAyB,EACzB,GAA8B,EAC9B,eAA4C;IAE5C,IAAI,CAAC,GAAG,IAAI,KAAK,CAAC,kBAAkB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAClD,OAAO;IACT,CAAC;IAED,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAC9B,sBAAsB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC;QAC9C,UAAU,CAAC,MAAM;QACjB,UAAU;KACX,CAAC,CACH,CA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,IAAI,CAAC,GAAG,CACpB,wBAAwB,MAAM,CAAC,MAAM,wDAAwD,CAC9F,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport {\n addDocumentAttachments,\n type DocumentAttachment,\n getDocumentAttachments,\n} from \"../../../../data/documents/documentContent\";\nimport type { LocalAttachmentRecord } from \"../../../../workflows/documents\";\nimport { reconcileLocalAttachmentDetachState } from \"../attachments/attachmentDetachState\";\nimport { saveLocalAttachmentRecord } from \"../attachments/attachmentPersistence\";\nimport { rebaseDocumentAfterPendingUpdateRefusal } from \"../pendingUpdateRefusal\";\nimport {\n advancePendingBaseVersion,\n enqueuePendingUpdate,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"../persistence\";\nimport type { DocumentState, DocumentStoreState } from \"../state\";\nimport type { DocumentStoreSyncGeneration } from \"../sync/syncGeneration\";\nimport { isDocumentStoreSyncGenerationCurrent } from \"../sync/syncGeneration\";\n\n// Re-derive any attachment slot that lives in a durable pending-upload row but\n// is missing (or stale) in the loaded snapshot. The attach write path persists\n// the blob bytes + pending-attachment row BEFORE it enqueues the slot's CRDT op\n// and persists the snapshot, so a crash in that window leaves bytes+row durable\n// but the slot gone from the document — the attachment would otherwise silently\n// disappear on restart while its bytes upload to a binding nothing references\n// (and a slot replace would keep stale metadata). Because the pending row still\n// carries the slot's metadata and staging digest, we can rebuild the slot without\n// opening bytes; normal upload reports missing sources. Runs on init only; a\n// no-op when every pending attachment already matches a slot.\nexport async function recoverDroppedAttachmentSlots(\n state: DocumentStoreState,\n doc: DocumentStoreState[\"doc\"],\n writeGeneration: DocumentStoreSyncGeneration,\n): Promise<void> {\n if (!doc || state.pendingAttachments.length === 0) {\n return;\n }\n\n const existingBySlotId = new Map(\n getDocumentAttachments(doc).map((attachment) => [\n attachment.slotId,\n attachment,\n ]),\n );\n const recovered: DocumentAttachment[] = [];\n for (const pending of state.pendingAttachments) {\n const mimeType = pending.mimeType ?? null;\n const existing = existingBySlotId.get(pending.slotId);\n const contentSha256 = pending.contentSha256;\n if (!isDocumentStoreSyncGenerationCurrent(state, writeGeneration)) return;\n if (\n existing &&\n existing.name === pending.name &&\n existing.byteLength === pending.byteLength &&\n existing.mimeType === mimeType &&\n existing.contentSha256 === contentSha256\n ) {\n continue;\n }\n recovered.push({\n contentSha256,\n byteLength: pending.byteLength,\n mimeType,\n name: pending.name,\n slotId: pending.slotId,\n });\n }\n if (recovered.length === 0) {\n return;\n }\n\n addDocumentAttachments(doc, recovered);\n const update = pendingDeltaSinceBase(state, doc);\n // Every durable write is gated on the captured generation — the enqueue\n // validates it INSIDE its serialized mutation, and the persist re-checks\n // via its expectedGeneration overload — so a store reset (e.g. a\n // local-edits discard) racing this recovery cannot see it re-enqueue or\n // re-persist the state the teardown just removed.\n if (update.byteLength > 0) {\n const enqueued = await enqueuePendingUpdate(\n state,\n update,\n undefined,\n writeGeneration,\n );\n if (!enqueued) {\n const rebased = await rebaseDocumentAfterPendingUpdateRefusal(\n state,\n writeGeneration,\n );\n if (rebased) {\n // Initialization captured the losing identity and must restart from\n // the winner, including its attachment rows and detach markers.\n throw new Error(\n \"Document identity changed during attachment recovery; retry initialization\",\n );\n }\n return;\n }\n }\n // Derive the snapshot from the loaded doc (do NOT preserve the snapshot). This\n // runs during init, before the store is ready, so state.snapshot is still the\n // empty initial snapshot — preserving it would publish a ready snapshot with\n // empty text/structured fields (a flash of empty content) over the real loaded\n // content. There is no in-flight user edit to protect here. The doc is\n // private to initialization and the enqueue above dual-wrote its delta, so\n // its version is a durably covered frontier.\n const persisted = await persistDocument(\n state,\n doc,\n { snapshotEndVersion: encodeVersionVector(doc) },\n {},\n writeGeneration,\n );\n if (\n !persisted ||\n persisted.pullContinuationSuperseded ||\n persisted.syncIdentitySuperseded\n ) {\n return;\n }\n advancePendingBaseVersion(state, doc);\n state.runtime.util.log(\n `Documents: recovered ${recovered.length} attachment slot(s) from pending uploads after an interrupted write.`,\n );\n}\n\n/**\n * Realign detach markers with the loaded document.\n *\n * Removing an attachment marks its row detached and then persists the document;\n * a stop between those two writes leaves the halves disagreeing, and neither\n * the sync detach pass (which reads the document) nor the read models (which\n * read the marker) can resolve that on their own. The loaded document is the\n * durable truth, so the marker follows it.\n */\nexport async function healLocalAttachmentDetachState(\n state: DocumentStoreState,\n doc: DocumentState,\n persistedState: { localAttachments: ReadonlyArray<LocalAttachmentRecord> },\n writeGeneration: DocumentStoreSyncGeneration,\n): Promise<void> {\n const healed = reconcileLocalAttachmentDetachState(\n persistedState.localAttachments,\n doc,\n );\n for (const attachment of healed) {\n // The save validates the generation inside its serialized mutation, so a\n // concurrent store reset can never see this heal rewrite rows the\n // teardown just removed.\n await saveLocalAttachmentRecord(state, attachment, doc, writeGeneration);\n }\n if (healed.length > 0) {\n state.runtime.util.log(\n `Documents: realigned ${healed.length} attachment detach marker(s) with the loaded document.`,\n );\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"mutationIdentityRevalidation.js","sourceRoot":"","sources":["mutationIdentityRevalidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAIhD,MAAM,CAAC,KAAK,UAAU,kCAAkC,CAAC,KAIxD;IACC,MAAM,eAAe,CACnB,KAAK,CAAC,KAAK,EACX,KAAK,CAAC,UAAU,EAChB,EAAE,EACF;QACE,gCAAgC,EAAE,IAAI;QACtC,oBAAoB,EAAE,IAAI;KAC3B,EACD,KAAK,CAAC,UAAU,CACjB,CAAC;AACJ,CAAC","sourcesContent":["import { persistDocument } from \"./persistence\";\nimport type { DocumentState, DocumentStoreState } from \"./state\";\nimport type { DocumentStoreSyncGeneration } from \"./syncGeneration\";\n\nexport async function revalidateDocumentMutationIdentity(input: {\n currentDoc: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}): Promise<void> {\n await persistDocument(\n input.state,\n input.currentDoc,\n {},\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n input.generation,\n );\n}\n"]}
1
+ {"version":3,"file":"mutationIdentityRevalidation.js","sourceRoot":"","sources":["mutationIdentityRevalidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAIhD,MAAM,CAAC,KAAK,UAAU,kCAAkC,CAAC,KAIxD;IACC,MAAM,eAAe,CACnB,KAAK,CAAC,KAAK,EACX,KAAK,CAAC,UAAU,EAChB,EAAE,EACF;QACE,gCAAgC,EAAE,IAAI;QACtC,oBAAoB,EAAE,IAAI;KAC3B,EACD,KAAK,CAAC,UAAU,CACjB,CAAC;AACJ,CAAC","sourcesContent":["import { persistDocument } from \"./persistence\";\nimport type { DocumentState, DocumentStoreState } from \"./state\";\nimport type { DocumentStoreSyncGeneration } from \"./sync/syncGeneration\";\n\nexport async function revalidateDocumentMutationIdentity(input: {\n currentDoc: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}): Promise<void> {\n await persistDocument(\n input.state,\n input.currentDoc,\n {},\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n input.generation,\n );\n}\n"]}
@@ -3,12 +3,12 @@ import { encodeVersionVector, getTextValue } from "../../../internal/loro/index.
3
3
  import { projectStoredDocumentState, writeStoredDocumentFields, } from "../../../data/documents/documentKinds.js";
4
4
  import { createPendingUpdateFields } from "../../../data/documents/documentSync.js";
5
5
  import { requestDocumentStoreSync } from "../registry.js";
6
- import { ensureDocumentStoreInitialized, ensureDocumentStoreReady, } from "./initialization.js";
6
+ import { ensureDocumentStoreInitialized, ensureDocumentStoreReady, } from "./initialization/index.js";
7
7
  import { revalidateDocumentMutationIdentity } from "./mutationIdentityRevalidation.js";
8
8
  import { advancePendingBaseVersion, pendingDeltaSinceBase, persistDocument, } from "./persistence.js";
9
9
  import { reportDocumentStoreWriteFailure } from "./reportWriteFailure.js";
10
10
  import { canWriteDocument, setDocumentSnapshot, setReadySnapshot, } from "./state.js";
11
- import { captureDocumentStoreSyncGeneration } from "./syncGeneration.js";
11
+ import { captureDocumentStoreSyncGeneration } from "./sync/syncGeneration.js";
12
12
  // Fixed literals: a reported message must never carry document text or ids.
13
13
  const TEXT_FAILURE_MESSAGE = "Documents: local text persist failed";
14
14
  const FIELD_FAILURE_MESSAGE = "Documents: local field persist failed";
@@ -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,MAAM,aAAa,CAAC;AAKvD,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,GACzB,MAAM,kBAAkB,CAAC;AAC1B,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,kBAAkB,CAAC;AAEtE,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,CAAC,CAAC,EAAE,CAAC;IACrD,CAAC;I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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 { 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 \"./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\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\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 state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () => {\n if (\n state.localWriteGeneration !== writeGeneration ||\n !state.doc ||\n !canWriteDocument(state)\n ) {\n return;\n }\n const writeDoc = state.doc;\n const syncGeneration = captureDocumentStoreSyncGeneration(\n state,\n writeDoc,\n );\n if (!syncGeneration) {\n return;\n }\n\n if (getTextValue(writeDoc) === value) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n\n writeDoc.getText(\"text\").update(value);\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 return;\n }\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 // 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 the value-equality short-circuit or a throw, so the\n // current document's counter cannot stick non-zero. The generation guard\n // keeps a reset write from decrementing a replacement generation.\n .finally(() => {\n settleDocumentLocalWrite(state, writeGeneration);\n });\n return state.writeChain;\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\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 const writeGeneration = state.localWriteGeneration;\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 state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () => {\n if (\n state.localWriteGeneration !== writeGeneration ||\n !state.doc ||\n !canWriteDocument(state)\n ) {\n return;\n }\n const writeDoc = state.doc;\n const syncGeneration = captureDocumentStoreSyncGeneration(\n state,\n writeDoc,\n );\n if (!syncGeneration) {\n return;\n }\n\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 // 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 advancePendingBaseVersion(state, writeDoc);\n requestDocumentStoreSync(state);\n }\n })\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, writeGeneration);\n });\n return state.writeChain;\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 publishDocumentStructuredFieldSnapshot(state, kind, patch);\n return queueDocumentStructuredFieldWrite(state, kind, patch, options);\n });\n }\n\n if (!canWriteDocument(state)) {\n return Promise.resolve();\n }\n\n publishDocumentStructuredFieldSnapshot(state, kind, patch);\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,E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,EAAE;IAErC,8BAA8B,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;IAEpD,IAAI,CAAC,KAAK,CAAC,WAAW,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC;QACrC,OAAO,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,sCAAsC,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;YAC3D,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,sCAAsC,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAC3D,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 { 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\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\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 state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () => {\n if (\n state.localWriteGeneration !== writeGeneration ||\n !state.doc ||\n !canWriteDocument(state)\n ) {\n return;\n }\n const writeDoc = state.doc;\n const syncGeneration = captureDocumentStoreSyncGeneration(\n state,\n writeDoc,\n );\n if (!syncGeneration) {\n return;\n }\n\n if (getTextValue(writeDoc) === value) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n\n writeDoc.getText(\"text\").update(value);\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 return;\n }\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 // 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 the value-equality short-circuit or a throw, so the\n // current document's counter cannot stick non-zero. The generation guard\n // keeps a reset write from decrementing a replacement generation.\n .finally(() => {\n settleDocumentLocalWrite(state, writeGeneration);\n });\n return state.writeChain;\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\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 const writeGeneration = state.localWriteGeneration;\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 state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () => {\n if (\n state.localWriteGeneration !== writeGeneration ||\n !state.doc ||\n !canWriteDocument(state)\n ) {\n return;\n }\n const writeDoc = state.doc;\n const syncGeneration = captureDocumentStoreSyncGeneration(\n state,\n writeDoc,\n );\n if (!syncGeneration) {\n return;\n }\n\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 // 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 advancePendingBaseVersion(state, writeDoc);\n requestDocumentStoreSync(state);\n }\n })\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, writeGeneration);\n });\n return state.writeChain;\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 publishDocumentStructuredFieldSnapshot(state, kind, patch);\n return queueDocumentStructuredFieldWrite(state, kind, patch, options);\n });\n }\n\n if (!canWriteDocument(state)) {\n return Promise.resolve();\n }\n\n publishDocumentStructuredFieldSnapshot(state, kind, patch);\n return queueDocumentStructuredFieldWrite(state, kind, patch, options);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { reloadDocumentFromDurableHistory } from "./durableDocumentReload.js";
1
+ import { reloadDocumentFromDurableHistory } from "./history/durableDocumentReload.js";
2
2
  /**
3
3
  * An enqueue identity CAS can lose before the following record persist gets a
4
4
  * chance to observe the replacement. Rebuild from durable history immediately
@@ -1 +1 @@
1
- {"version":3,"file":"pendingUpdateRefusal.js","sourceRoot":"","sources":["pendingUpdateRefusal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,yBAAyB,CAAC;AAI3E;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,uCAAuC,CAC3D,KAAyB,EACzB,kBAA+C;IAE/C,OAAO,gCAAgC,CAAC;QACtC,kBAAkB;QAClB,uCAAuC,EAAE,KAAK;QAC9C,KAAK;KACN,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { reloadDocumentFromDurableHistory } from \"./durableDocumentReload\";\nimport type { DocumentStoreState } from \"./state\";\nimport type { DocumentStoreSyncGeneration } from \"./syncGeneration\";\n\n/**\n * An enqueue identity CAS can lose before the following record persist gets a\n * chance to observe the replacement. Rebuild from durable history immediately\n * and invalidate every local write that was queued against the old live doc;\n * none of those mutations may be replayed into the replacement identity.\n */\nexport async function rebaseDocumentAfterPendingUpdateRefusal(\n state: DocumentStoreState,\n expectedGeneration: DocumentStoreSyncGeneration,\n): Promise<boolean> {\n return reloadDocumentFromDurableHistory({\n expectedGeneration,\n preserveQueuedWritesWhenIdentityMatches: false,\n state,\n });\n}\n"]}
1
+ {"version":3,"file":"pendingUpdateRefusal.js","sourceRoot":"","sources":["pendingUpdateRefusal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AAInF;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,uCAAuC,CAC3D,KAAyB,EACzB,kBAA+C;IAE/C,OAAO,gCAAgC,CAAC;QACtC,kBAAkB;QAClB,uCAAuC,EAAE,KAAK;QAC9C,KAAK;KACN,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { reloadDocumentFromDurableHistory } from \"./history/durableDocumentReload\";\nimport type { DocumentStoreState } from \"./state\";\nimport type { DocumentStoreSyncGeneration } from \"./sync/syncGeneration\";\n\n/**\n * An enqueue identity CAS can lose before the following record persist gets a\n * chance to observe the replacement. Rebuild from durable history immediately\n * and invalidate every local write that was queued against the old live doc;\n * none of those mutations may be replayed into the replacement identity.\n */\nexport async function rebaseDocumentAfterPendingUpdateRefusal(\n state: DocumentStoreState,\n expectedGeneration: DocumentStoreSyncGeneration,\n): Promise<boolean> {\n return reloadDocumentFromDurableHistory({\n expectedGeneration,\n preserveQueuedWritesWhenIdentityMatches: false,\n state,\n });\n}\n"]}
@@ -5,12 +5,12 @@ import { normalizeEffectiveAccessLevel } from "../../../data/keying/accessLevel.
5
5
  import { errorMessage } from "../../../data/shared/errorMessage.js";
6
6
  import { enqueuePendingDocumentUpdate, listPendingDocumentUpdates, persistDocumentState, runSerializedSqlMutation, } from "../../../workflows/documents/index.js";
7
7
  import { requestDocumentStoreSync } from "../registry.js";
8
- import { maybeCompactDocumentHistory } from "./documentHistoryCompaction.js";
9
- import { importDurableDocumentHistory, installDurableDocumentReload, } from "./durableDocumentReload.js";
8
+ import { maybeCompactDocumentHistory } from "./history/documentHistoryCompaction.js";
9
+ import { importDurableDocumentHistory, installDurableDocumentReload, } from "./history/durableDocumentReload.js";
10
10
  import { runDocumentOrphanMaintenance } from "./orphanMaintenance.js";
11
11
  import { markDocumentStoreRemoved, setReadySnapshot, } from "./state.js";
12
12
  import { createFreshPeerStoredDocument } from "./storedDocument.js";
13
- import { isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent, } from "./syncGeneration.js";
13
+ import { isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent, } from "./sync/syncGeneration.js";
14
14
  export function documentSummaryFromRecord(record, updatedAt, documentProjectors) {
15
15
  return {
16
16
  accessStateHash: record.accessStateHash ?? null,
@@ -1 +1 @@
1
- {"version":3,"file":"persistence.js","sourceRoot":"","sources":["persistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,0BAA0B,GAC3B,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,kCAAkC,CAAC;AACjF,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAGL,4BAA4B,EAC5B,0BAA0B,EAE1B,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EACL,4BAA4B,EAC5B,4BAA4B,GAC7B,MAAM,yBAA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zB,MAAkB,EAClB,mBAAmC,EACnC,kBAAgD;IAEhD,MAAM,kBAAkB,GAAG,KAAK,CAAC,MAAM,EAAE,UAAU,CAAC;IACpD,MAAM,0BAA0B,GAAG,KAAK,CAAC,MAAM,EAAE,kBAAkB,IAAI,CAAC,CAAC;IACzE,IAAI,kBAAkB,KAAK,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,MAAM,GAAG,GAAG,MAAM,6BAA6B,CAC7C,KAAK,EACL,kBAAkB,EAClB,KAAK,EAAE,OAAO,EAAE,EAAE;QAChB,QAAQ,GAAG,MAAM,4BAA4B,CAAC;YAC5C,OAAO;YACP,kBAAkB;YAClB,0BAA0B;YAC1B,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,GAAG,CAAC,mBAAmB,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,mBAAmB,EAAE,CAAC;YACrE,MAAM;SACP,CAAC,CAAC;IACL,CAAC,CACF,CAAC;IACF,OAAO,GAAG,IAAI,QAAQ,CAAC;AACzB,CAAC","sourcesContent":["import { encodeVersionVector, exportUpdatesSince } from \"@tearleads/loro\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport {\n type DocumentProjectorRegistry,\n projectStoredDocumentState,\n} from \"../../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport { normalizeEffectiveAccessLevel } from \"../../../data/keying/accessLevel\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n type DocumentRecord,\n type ExecSql,\n enqueuePendingDocumentUpdate,\n listPendingDocumentUpdates,\n type PendingUpdateRecord,\n persistDocumentState,\n runSerializedSqlMutation,\n} from \"../../../workflows/documents\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport { maybeCompactDocumentHistory } from \"./documentHistoryCompaction\";\nimport {\n importDurableDocumentHistory,\n installDurableDocumentReload,\n} from \"./durableDocumentReload\";\nimport { runDocumentOrphanMaintenance } from \"./orphanMaintenance\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n markDocumentStoreRemoved,\n type PersistedDocumentRecord,\n type SaveDocumentRecordOptions,\n setReadySnapshot,\n} from \"./state\";\nimport { createFreshPeerStoredDocument } from \"./storedDocument\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\nexport function documentSummaryFromRecord(\n record: DocumentRecord,\n updatedAt: string,\n documentProjectors: DocumentProjectorRegistry,\n): DocumentSummary {\n return {\n accessStateHash: record.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n record.effectiveAccessLevel,\n ),\n id: record.id,\n containerId: record.containerId,\n documentKind: record.documentKind ?? DEFAULT_DOCUMENT_KIND,\n documentId: record.documentId,\n title:\n record.title ??\n projectStoredDocumentState(\n {\n documentKind: record.documentKind ?? DEFAULT_DOCUMENT_KIND,\n structuredFields: {},\n text: record.text,\n },\n documentProjectors,\n ).title,\n updatedAt,\n };\n}\n\nfunction toPersistedDocumentRecord(\n persisted: NonNullable<Awaited<ReturnType<typeof persistDocumentState>>>,\n): PersistedDocumentRecord {\n const { record, updatedAt } = persisted;\n return {\n ...(persisted.creationSuperseded\n ? { creationSuperseded: true as const }\n : {}),\n historyRestoreState: persisted.historyRestoreState,\n ...(persisted.pullContinuationSuperseded\n ? { pullContinuationSuperseded: true as const }\n : {}),\n record,\n ...(persisted.syncIdentitySuperseded\n ? { syncIdentitySuperseded: true as const }\n : {}),\n ...(updatedAt !== undefined ? { updatedAt } : {}),\n };\n}\n\n// Nullable without a generation too: an update-persist refuses (returns\n// null) when the durable row was deleted while the persist was queued — the\n// resurrect guard in persistDocumentState — so callers must stop follow-up\n// state changes on null.\nexport async function saveDocumentRecord(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n patch: Partial<DocumentRecord> = {},\n options: SaveDocumentRecordOptions = {},\n expectedGeneration?: DocumentStoreSyncGeneration,\n commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<PersistedDocumentRecord | null> {\n const isCurrent = () =>\n (!expectedGeneration ||\n isSyncGenerationCurrent(state, expectedGeneration)) &&\n options.stillCurrent?.() !== false;\n const createsPlacement = state.record === null;\n const previousDocumentId = state.record?.documentId ?? null;\n const pendingBaseVersion =\n options.pendingBaseVersionOverride === undefined\n ? state.pendingBaseVersion\n : options.pendingBaseVersionOverride;\n const persistenceInput = {\n acceptedPendingUpdateIds: options.acceptedPendingUpdateIds,\n attachmentRemoval: options.attachmentRemoval,\n attachmentStaging: options.attachmentStaging,\n clearSyncFailure: options.clearSyncFailure,\n ...(commitSideEffect ? { commitSideEffect } : {}),\n containerId: state.runtime.state.containerId,\n currentDoc,\n currentRecord: state.record,\n documentProjectors: state.runtime.infra.documentProjectors,\n execSql: state.runtime.infra.execSql,\n expectedSyncState: options.expectedSyncState,\n historyCheckpoint: options.historyCheckpoint,\n historyUpdateOrigin: options.historyUpdateOrigin,\n historyUpdates: options.historyUpdates,\n pendingUpdate: options.pendingUpdate,\n localId: state.localId,\n // Persist the durable outgoing-delta marker with every snapshot write so a\n // restart restores it (see initializeDocumentStore). A device-first\n // deferRemoteSync write leaves it BEHIND the snapshot version on purpose;\n // capturing state.pendingBaseVersion here is what lets the next edit\n // re-derive that deferred op after a restart instead of dropping it.\n patch: { ...patch, pendingBaseVersion },\n persistence: state.persistence,\n };\n const persistedDocumentState =\n expectedGeneration || options.stillCurrent\n ? await persistDocumentState({\n ...persistenceInput,\n // persistDocumentState rechecks after its own pre-save awaits and then\n // immediately claims the executor mutation queue. A reset before that\n // point aborts; a reset afterward cannot let replacement writes overtake.\n canStartDurableMutation: isCurrent,\n })\n : await persistDocumentState(persistenceInput);\n if (!persistedDocumentState) {\n // With a stale generation the teardown that invalidated it owns the\n // state. With a current (or absent) generation, the refusal means the\n // durable row was deleted by ANOTHER subsystem while this persist was\n // queued (the resurrect guard): this store is a zombie — clear it so\n // callers that ignore the result stop advancing state or scheduling\n // sync against a document that no longer exists.\n if (isCurrent()) {\n markDocumentStoreRemoved(state);\n }\n void runDocumentOrphanMaintenance(state);\n return null;\n }\n const { record: nextRecord, updatedAt } = persistedDocumentState;\n if (!isCurrent()) {\n return null;\n }\n\n state.record = persistedDocumentState.record;\n state.pullContinuation = nextRecord.pullContinuation ?? null;\n if (persistedDocumentState.pullContinuationSuperseded) {\n state.pendingBaseVersion =\n nextRecord.pendingBaseVersion ?? nextRecord.snapshotEndVersion;\n }\n if (previousDocumentId !== nextRecord.documentId) {\n state.effects.registerDocumentIdentity(\n state.runtime.state.domainScope,\n nextRecord.id,\n nextRecord.documentId,\n );\n }\n if (updatedAt !== undefined) {\n state.effects.emitPersistedDocument(\n state.runtime.state.domainScope,\n documentSummaryFromRecord(\n nextRecord,\n updatedAt,\n state.runtime.infra.documentProjectors,\n ),\n createsPlacement ||\n Object.hasOwn(patch, \"containerId\") ||\n previousDocumentId !== nextRecord.documentId,\n );\n }\n return toPersistedDocumentRecord(persistedDocumentState);\n}\n\nasync function reloadSupersededDocumentState(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n historyRestoreState: PersistedDocumentRecord[\"historyRestoreState\"],\n previousDocumentId: string | null,\n durableRecord: DocumentRecord,\n): Promise<DocumentState | null> {\n if (historyRestoreState === undefined) {\n throw new Error(\"Superseded document state omitted its durable history\");\n }\n const replacementDoc = await createFreshPeerStoredDocument();\n importDurableDocumentHistory(replacementDoc, historyRestoreState);\n if (!isCurrent()) {\n return null;\n }\n installDurableDocumentReload({\n durableRecord,\n previousDocumentId,\n preserveQueuedWritesWhenIdentityMatches: true,\n registerIdentityChange: false,\n replacementDoc,\n state,\n });\n return replacementDoc;\n}\n\nexport async function persistDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n patch: Partial<DocumentRecord> = {},\n options: SaveDocumentRecordOptions = {},\n expectedGeneration?: DocumentStoreSyncGeneration,\n commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<PersistedDocumentRecord | null> {\n const isCurrent = () =>\n (!expectedGeneration ||\n isSyncGenerationCurrent(state, expectedGeneration)) &&\n options.stillCurrent?.() !== false;\n const previousDocumentId = state.record?.documentId ?? null;\n const persistedRecord = await saveDocumentRecord(\n state,\n currentDoc,\n patch,\n options,\n expectedGeneration,\n commitSideEffect,\n );\n return publishPersistedDocument(\n state,\n currentDoc,\n persistedRecord,\n previousDocumentId,\n options,\n isCurrent,\n );\n}\n\n/** Publish only after the durable claim succeeds and its live context remains. */\nexport async function publishPersistedDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n persistedRecord: PersistedDocumentRecord | null,\n previousDocumentId: string | null,\n options: SaveDocumentRecordOptions,\n isCurrent: () => boolean,\n): Promise<PersistedDocumentRecord | null> {\n if (!persistedRecord) return null;\n if (!isCurrent()) return null;\n\n if (\n persistedRecord.syncIdentitySuperseded ||\n persistedRecord.pullContinuationSuperseded\n ) {\n // Reload the winning durable checkpoint/tail on every CAS loss, including\n // another pane's history or security-context changes. A rejected sync\n // candidate remains isolated from the live document and editor.\n const replacementDoc = await reloadSupersededDocumentState(\n state,\n isCurrent,\n persistedRecord.historyRestoreState,\n previousDocumentId,\n persistedRecord.record,\n );\n if (!replacementDoc) return null;\n return persistedRecord;\n }\n\n setReadySnapshot(\n state,\n currentDoc,\n state.snapshot.syncing,\n options.preserveSnapshotText && !persistedRecord.pullContinuationSuperseded\n ? state.snapshot.text\n : persistedRecord.record.text,\n options.preserveSnapshotStructuredFields &&\n !persistedRecord.pullContinuationSuperseded\n ? state.snapshot.structuredFields\n : undefined,\n );\n // Compaction never fails the persist that triggered it: an unexpected\n // compaction error simply keeps the tail growing until a later pass\n // succeeds, and the content stays durable either way.\n try {\n await maybeCompactDocumentHistory(state, currentDoc, options.stillCurrent);\n } catch (error) {\n state.runtime.util.log(\n `Documents: history compaction skipped: ${errorMessage(error)}`,\n );\n }\n return persistedRecord;\n}\n\nexport async function listPendingUpdates(\n state: DocumentStoreState,\n): Promise<PendingUpdateRecord[]> {\n return listPendingDocumentUpdates({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n}\n\n/**\n * Export the outgoing delta for the current edit. The base is `pendingBaseVersion`\n * (the version through which ops are already durably enqueued or synced), NOT the\n * live doc version, so any delta orphaned by a prior failed enqueue is folded back\n * in here. In the success path the marker equals the pre-edit version, so this is\n * identical to exporting \"since the last edit\".\n *\n * Initialization sets `pendingBaseVersion` whenever it sets `doc`, and every\n * caller checks `doc` first, so the marker is non-null here. Assert that rather\n * than falling back to the live version: callers invoke this AFTER mutating the\n * doc, so a live-version fallback would export an empty (post-mutation) delta and\n * silently drop the edit.\n */\nexport function pendingDeltaSinceBase(\n state: DocumentStoreState,\n doc: DocumentState,\n): Uint8Array {\n if (state.pendingBaseVersion === null) {\n throw new Error(\n \"pendingDeltaSinceBase requires an initialized pendingBaseVersion\",\n );\n }\n return exportUpdatesSince(doc, state.pendingBaseVersion);\n}\n\n/**\n * Advance the durable marker to the doc's current version. Call this ONLY after\n * an edit's delta has been durably enqueued and persisted, or after remote\n * updates have been imported (those ops are already on the server).\n */\nexport function advancePendingBaseVersion(\n state: DocumentStoreState,\n doc: DocumentState,\n): void {\n state.pendingBaseVersion = encodeVersionVector(doc);\n // Every op through here is enqueued or remote, so a deferred birth is now\n // covered: lift its scheduled-sync hold and request the pass it skipped.\n if (state.deferInitialUpdate) {\n state.deferInitialUpdate = false;\n requestDocumentStoreSync(state);\n }\n}\n\n/**\n * Runs a durable write either ungated — no generation: the caller serializes\n * with teardown via the write-chain drain, and the persistence implementation\n * may legitimately park inside the write WITHOUT holding the global mutation\n * mutex — or inside the serialized mutation with an in-mutex currency check:\n * a teardown (reset/discard) that already ran was ordered strictly before the\n * mutation claim and invalidated the generation, so a stale caller can no\n * longer slip its write in after the teardown's wipe; a write that wins the\n * ordering instead lands before the teardown and is wiped by it. Returns\n * whether the write ran.\n */\nexport async function withGenerationGuardedMutation(\n state: DocumentStoreState,\n expectedGeneration: DocumentStoreSyncGeneration | undefined,\n write: (execSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n if (!expectedGeneration) {\n await write(state.runtime.infra.execSql);\n return true;\n }\n\n let ran = false;\n await runSerializedSqlMutation(\n state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (!isSyncGenerationCurrent(state, expectedGeneration)) {\n return;\n }\n await write(lockedExecSql);\n ran = true;\n },\n );\n return ran;\n}\n\nexport async function enqueuePendingUpdate(\n state: DocumentStoreState,\n update: Uint8Array,\n sourceVersionVector?: string | null,\n expectedGeneration?: DocumentStoreSyncGeneration,\n): Promise<boolean> {\n const expectedDocumentId = state.record?.documentId;\n const expectedRecoveryGeneration = state.record?.recoveryGeneration ?? 0;\n if (expectedDocumentId === undefined) {\n return false;\n }\n let enqueued = false;\n const ran = await withGenerationGuardedMutation(\n state,\n expectedGeneration,\n async (execSql) => {\n enqueued = await enqueuePendingDocumentUpdate({\n execSql,\n expectedDocumentId,\n expectedRecoveryGeneration,\n localId: state.localId,\n persistence: state.persistence,\n ...(sourceVersionVector === undefined ? {} : { sourceVersionVector }),\n update,\n });\n },\n );\n return ran && enqueued;\n}\n"]}
1
+ {"version":3,"file":"persistence.js","sourceRoot":"","sources":["persistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,0BAA0B,GAC3B,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,kCAAkC,CAAC;AACjF,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAGL,4BAA4B,EAC5B,0BAA0B,EAE1B,oBAAoB,EACp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D,OAAO;QACT,CAAC;QACD,MAAM,KAAK,CAAC,aAAa,CAAC,CAAC;QAC3B,GAAG,GAAG,IAAI,CAAC;IACb,CAAC,CACF,CAAC;IACF,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,KAAyB,EACzB,MAAkB,EAClB,mBAAmC,EACnC,kBAAgD;IAEhD,MAAM,kBAAkB,GAAG,KAAK,CAAC,MAAM,EAAE,UAAU,CAAC;IACpD,MAAM,0BAA0B,GAAG,KAAK,CAAC,MAAM,EAAE,kBAAkB,IAAI,CAAC,CAAC;IACzE,IAAI,kBAAkB,KAAK,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,MAAM,GAAG,GAAG,MAAM,6BAA6B,CAC7C,KAAK,EACL,kBAAkB,EAClB,KAAK,EAAE,OAAO,EAAE,EAAE;QAChB,QAAQ,GAAG,MAAM,4BAA4B,CAAC;YAC5C,OAAO;YACP,kBAAkB;YAClB,0BAA0B;YAC1B,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,GAAG,CAAC,mBAAmB,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,mBAAmB,EAAE,CAAC;YACrE,MAAM;SACP,CAAC,CAAC;IACL,CAAC,CACF,CAAC;IACF,OAAO,GAAG,IAAI,QAAQ,CAAC;AACzB,CAAC","sourcesContent":["import { encodeVersionVector, exportUpdatesSince } from \"@tearleads/loro\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport {\n type DocumentProjectorRegistry,\n projectStoredDocumentState,\n} from \"../../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport { normalizeEffectiveAccessLevel } from \"../../../data/keying/accessLevel\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n type DocumentRecord,\n type ExecSql,\n enqueuePendingDocumentUpdate,\n listPendingDocumentUpdates,\n type PendingUpdateRecord,\n persistDocumentState,\n runSerializedSqlMutation,\n} from \"../../../workflows/documents\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport { maybeCompactDocumentHistory } from \"./history/documentHistoryCompaction\";\nimport {\n importDurableDocumentHistory,\n installDurableDocumentReload,\n} from \"./history/durableDocumentReload\";\nimport { runDocumentOrphanMaintenance } from \"./orphanMaintenance\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n markDocumentStoreRemoved,\n type PersistedDocumentRecord,\n type SaveDocumentRecordOptions,\n setReadySnapshot,\n} from \"./state\";\nimport { createFreshPeerStoredDocument } from \"./storedDocument\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent,\n} from \"./sync/syncGeneration\";\n\nexport function documentSummaryFromRecord(\n record: DocumentRecord,\n updatedAt: string,\n documentProjectors: DocumentProjectorRegistry,\n): DocumentSummary {\n return {\n accessStateHash: record.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n record.effectiveAccessLevel,\n ),\n id: record.id,\n containerId: record.containerId,\n documentKind: record.documentKind ?? DEFAULT_DOCUMENT_KIND,\n documentId: record.documentId,\n title:\n record.title ??\n projectStoredDocumentState(\n {\n documentKind: record.documentKind ?? DEFAULT_DOCUMENT_KIND,\n structuredFields: {},\n text: record.text,\n },\n documentProjectors,\n ).title,\n updatedAt,\n };\n}\n\nfunction toPersistedDocumentRecord(\n persisted: NonNullable<Awaited<ReturnType<typeof persistDocumentState>>>,\n): PersistedDocumentRecord {\n const { record, updatedAt } = persisted;\n return {\n ...(persisted.creationSuperseded\n ? { creationSuperseded: true as const }\n : {}),\n historyRestoreState: persisted.historyRestoreState,\n ...(persisted.pullContinuationSuperseded\n ? { pullContinuationSuperseded: true as const }\n : {}),\n record,\n ...(persisted.syncIdentitySuperseded\n ? { syncIdentitySuperseded: true as const }\n : {}),\n ...(updatedAt !== undefined ? { updatedAt } : {}),\n };\n}\n\n// Nullable without a generation too: an update-persist refuses (returns\n// null) when the durable row was deleted while the persist was queued — the\n// resurrect guard in persistDocumentState — so callers must stop follow-up\n// state changes on null.\nexport async function saveDocumentRecord(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n patch: Partial<DocumentRecord> = {},\n options: SaveDocumentRecordOptions = {},\n expectedGeneration?: DocumentStoreSyncGeneration,\n commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<PersistedDocumentRecord | null> {\n const isCurrent = () =>\n (!expectedGeneration ||\n isSyncGenerationCurrent(state, expectedGeneration)) &&\n options.stillCurrent?.() !== false;\n const createsPlacement = state.record === null;\n const previousDocumentId = state.record?.documentId ?? null;\n const pendingBaseVersion =\n options.pendingBaseVersionOverride === undefined\n ? state.pendingBaseVersion\n : options.pendingBaseVersionOverride;\n const persistenceInput = {\n acceptedPendingUpdateIds: options.acceptedPendingUpdateIds,\n attachmentRemoval: options.attachmentRemoval,\n attachmentStaging: options.attachmentStaging,\n clearSyncFailure: options.clearSyncFailure,\n ...(commitSideEffect ? { commitSideEffect } : {}),\n containerId: state.runtime.state.containerId,\n currentDoc,\n currentRecord: state.record,\n documentProjectors: state.runtime.infra.documentProjectors,\n execSql: state.runtime.infra.execSql,\n expectedSyncState: options.expectedSyncState,\n historyCheckpoint: options.historyCheckpoint,\n historyUpdateOrigin: options.historyUpdateOrigin,\n historyUpdates: options.historyUpdates,\n pendingUpdate: options.pendingUpdate,\n localId: state.localId,\n // Persist the durable outgoing-delta marker with every snapshot write so a\n // restart restores it (see initializeDocumentStore). A device-first\n // deferRemoteSync write leaves it BEHIND the snapshot version on purpose;\n // capturing state.pendingBaseVersion here is what lets the next edit\n // re-derive that deferred op after a restart instead of dropping it.\n patch: { ...patch, pendingBaseVersion },\n persistence: state.persistence,\n };\n const persistedDocumentState =\n expectedGeneration || options.stillCurrent\n ? await persistDocumentState({\n ...persistenceInput,\n // persistDocumentState rechecks after its own pre-save awaits and then\n // immediately claims the executor mutation queue. A reset before that\n // point aborts; a reset afterward cannot let replacement writes overtake.\n canStartDurableMutation: isCurrent,\n })\n : await persistDocumentState(persistenceInput);\n if (!persistedDocumentState) {\n // With a stale generation the teardown that invalidated it owns the\n // state. With a current (or absent) generation, the refusal means the\n // durable row was deleted by ANOTHER subsystem while this persist was\n // queued (the resurrect guard): this store is a zombie — clear it so\n // callers that ignore the result stop advancing state or scheduling\n // sync against a document that no longer exists.\n if (isCurrent()) {\n markDocumentStoreRemoved(state);\n }\n void runDocumentOrphanMaintenance(state);\n return null;\n }\n const { record: nextRecord, updatedAt } = persistedDocumentState;\n if (!isCurrent()) {\n return null;\n }\n\n state.record = persistedDocumentState.record;\n state.pullContinuation = nextRecord.pullContinuation ?? null;\n if (persistedDocumentState.pullContinuationSuperseded) {\n state.pendingBaseVersion =\n nextRecord.pendingBaseVersion ?? nextRecord.snapshotEndVersion;\n }\n if (previousDocumentId !== nextRecord.documentId) {\n state.effects.registerDocumentIdentity(\n state.runtime.state.domainScope,\n nextRecord.id,\n nextRecord.documentId,\n );\n }\n if (updatedAt !== undefined) {\n state.effects.emitPersistedDocument(\n state.runtime.state.domainScope,\n documentSummaryFromRecord(\n nextRecord,\n updatedAt,\n state.runtime.infra.documentProjectors,\n ),\n createsPlacement ||\n Object.hasOwn(patch, \"containerId\") ||\n previousDocumentId !== nextRecord.documentId,\n );\n }\n return toPersistedDocumentRecord(persistedDocumentState);\n}\n\nasync function reloadSupersededDocumentState(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n historyRestoreState: PersistedDocumentRecord[\"historyRestoreState\"],\n previousDocumentId: string | null,\n durableRecord: DocumentRecord,\n): Promise<DocumentState | null> {\n if (historyRestoreState === undefined) {\n throw new Error(\"Superseded document state omitted its durable history\");\n }\n const replacementDoc = await createFreshPeerStoredDocument();\n importDurableDocumentHistory(replacementDoc, historyRestoreState);\n if (!isCurrent()) {\n return null;\n }\n installDurableDocumentReload({\n durableRecord,\n previousDocumentId,\n preserveQueuedWritesWhenIdentityMatches: true,\n registerIdentityChange: false,\n replacementDoc,\n state,\n });\n return replacementDoc;\n}\n\nexport async function persistDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n patch: Partial<DocumentRecord> = {},\n options: SaveDocumentRecordOptions = {},\n expectedGeneration?: DocumentStoreSyncGeneration,\n commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<PersistedDocumentRecord | null> {\n const isCurrent = () =>\n (!expectedGeneration ||\n isSyncGenerationCurrent(state, expectedGeneration)) &&\n options.stillCurrent?.() !== false;\n const previousDocumentId = state.record?.documentId ?? null;\n const persistedRecord = await saveDocumentRecord(\n state,\n currentDoc,\n patch,\n options,\n expectedGeneration,\n commitSideEffect,\n );\n return publishPersistedDocument(\n state,\n currentDoc,\n persistedRecord,\n previousDocumentId,\n options,\n isCurrent,\n );\n}\n\n/** Publish only after the durable claim succeeds and its live context remains. */\nexport async function publishPersistedDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n persistedRecord: PersistedDocumentRecord | null,\n previousDocumentId: string | null,\n options: SaveDocumentRecordOptions,\n isCurrent: () => boolean,\n): Promise<PersistedDocumentRecord | null> {\n if (!persistedRecord) return null;\n if (!isCurrent()) return null;\n\n if (\n persistedRecord.syncIdentitySuperseded ||\n persistedRecord.pullContinuationSuperseded\n ) {\n // Reload the winning durable checkpoint/tail on every CAS loss, including\n // another pane's history or security-context changes. A rejected sync\n // candidate remains isolated from the live document and editor.\n const replacementDoc = await reloadSupersededDocumentState(\n state,\n isCurrent,\n persistedRecord.historyRestoreState,\n previousDocumentId,\n persistedRecord.record,\n );\n if (!replacementDoc) return null;\n return persistedRecord;\n }\n\n setReadySnapshot(\n state,\n currentDoc,\n state.snapshot.syncing,\n options.preserveSnapshotText && !persistedRecord.pullContinuationSuperseded\n ? state.snapshot.text\n : persistedRecord.record.text,\n options.preserveSnapshotStructuredFields &&\n !persistedRecord.pullContinuationSuperseded\n ? state.snapshot.structuredFields\n : undefined,\n );\n // Compaction never fails the persist that triggered it: an unexpected\n // compaction error simply keeps the tail growing until a later pass\n // succeeds, and the content stays durable either way.\n try {\n await maybeCompactDocumentHistory(state, currentDoc, options.stillCurrent);\n } catch (error) {\n state.runtime.util.log(\n `Documents: history compaction skipped: ${errorMessage(error)}`,\n );\n }\n return persistedRecord;\n}\n\nexport async function listPendingUpdates(\n state: DocumentStoreState,\n): Promise<PendingUpdateRecord[]> {\n return listPendingDocumentUpdates({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n}\n\n/**\n * Export the outgoing delta for the current edit. The base is `pendingBaseVersion`\n * (the version through which ops are already durably enqueued or synced), NOT the\n * live doc version, so any delta orphaned by a prior failed enqueue is folded back\n * in here. In the success path the marker equals the pre-edit version, so this is\n * identical to exporting \"since the last edit\".\n *\n * Initialization sets `pendingBaseVersion` whenever it sets `doc`, and every\n * caller checks `doc` first, so the marker is non-null here. Assert that rather\n * than falling back to the live version: callers invoke this AFTER mutating the\n * doc, so a live-version fallback would export an empty (post-mutation) delta and\n * silently drop the edit.\n */\nexport function pendingDeltaSinceBase(\n state: DocumentStoreState,\n doc: DocumentState,\n): Uint8Array {\n if (state.pendingBaseVersion === null) {\n throw new Error(\n \"pendingDeltaSinceBase requires an initialized pendingBaseVersion\",\n );\n }\n return exportUpdatesSince(doc, state.pendingBaseVersion);\n}\n\n/**\n * Advance the durable marker to the doc's current version. Call this ONLY after\n * an edit's delta has been durably enqueued and persisted, or after remote\n * updates have been imported (those ops are already on the server).\n */\nexport function advancePendingBaseVersion(\n state: DocumentStoreState,\n doc: DocumentState,\n): void {\n state.pendingBaseVersion = encodeVersionVector(doc);\n // Every op through here is enqueued or remote, so a deferred birth is now\n // covered: lift its scheduled-sync hold and request the pass it skipped.\n if (state.deferInitialUpdate) {\n state.deferInitialUpdate = false;\n requestDocumentStoreSync(state);\n }\n}\n\n/**\n * Runs a durable write either ungated — no generation: the caller serializes\n * with teardown via the write-chain drain, and the persistence implementation\n * may legitimately park inside the write WITHOUT holding the global mutation\n * mutex — or inside the serialized mutation with an in-mutex currency check:\n * a teardown (reset/discard) that already ran was ordered strictly before the\n * mutation claim and invalidated the generation, so a stale caller can no\n * longer slip its write in after the teardown's wipe; a write that wins the\n * ordering instead lands before the teardown and is wiped by it. Returns\n * whether the write ran.\n */\nexport async function withGenerationGuardedMutation(\n state: DocumentStoreState,\n expectedGeneration: DocumentStoreSyncGeneration | undefined,\n write: (execSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n if (!expectedGeneration) {\n await write(state.runtime.infra.execSql);\n return true;\n }\n\n let ran = false;\n await runSerializedSqlMutation(\n state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (!isSyncGenerationCurrent(state, expectedGeneration)) {\n return;\n }\n await write(lockedExecSql);\n ran = true;\n },\n );\n return ran;\n}\n\nexport async function enqueuePendingUpdate(\n state: DocumentStoreState,\n update: Uint8Array,\n sourceVersionVector?: string | null,\n expectedGeneration?: DocumentStoreSyncGeneration,\n): Promise<boolean> {\n const expectedDocumentId = state.record?.documentId;\n const expectedRecoveryGeneration = state.record?.recoveryGeneration ?? 0;\n if (expectedDocumentId === undefined) {\n return false;\n }\n let enqueued = false;\n const ran = await withGenerationGuardedMutation(\n state,\n expectedGeneration,\n async (execSql) => {\n enqueued = await enqueuePendingDocumentUpdate({\n execSql,\n expectedDocumentId,\n expectedRecoveryGeneration,\n localId: state.localId,\n persistence: state.persistence,\n ...(sourceVersionVector === undefined ? {} : { sourceVersionVector }),\n update,\n });\n },\n );\n return ran && enqueued;\n}\n"]}