@tearleads/client-sdk 0.1.64 → 0.1.66

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 (646) hide show
  1. package/client/organizations/organizationAccessRestoration.js +1 -1
  2. package/data/containers/shared/mutationAcknowledgement.js +1 -1
  3. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  4. package/data/documents/blob/shared/projection.js +3 -3
  5. package/data/documents/blob/shared/projection.js.map +1 -1
  6. package/data/documents/shared/{containerKekCurrency.d.ts → containerKek/containerKekCurrency.d.ts} +1 -1
  7. package/data/documents/shared/{containerKekEntryVerification.js → containerKek/containerKekEntryVerification.js} +1 -1
  8. package/data/documents/shared/{containerKekLogFetch.d.ts → containerKek/containerKekLogFetch.d.ts} +1 -1
  9. package/data/documents/shared/{containerKekLogFetch.js → containerKek/containerKekLogFetch.js} +1 -1
  10. package/data/documents/shared/{containerKekPath.js → containerKek/containerKekPath.js} +3 -3
  11. package/data/documents/shared/containerKek/containerKekPath.js.map +1 -0
  12. package/data/documents/shared/{containerKekPathHistory.d.ts → containerKek/containerKekPathHistory.d.ts} +3 -3
  13. package/data/documents/shared/{containerKekPathHistory.js → containerKek/containerKekPathHistory.js} +4 -4
  14. package/data/documents/shared/containerKek/containerKekPathHistory.js.map +1 -0
  15. package/data/documents/shared/{containerKekPathVerification.d.ts → containerKek/containerKekPathVerification.d.ts} +5 -5
  16. package/data/documents/shared/{containerKekPathVerification.js → containerKek/containerKekPathVerification.js} +2 -2
  17. package/data/documents/shared/containerKek/containerKekPathVerification.js.map +1 -0
  18. package/data/documents/shared/{containerKekWrapping.js → containerKek/containerKekWrapping.js} +3 -3
  19. package/data/documents/shared/containerKek/containerKekWrapping.js.map +1 -0
  20. package/data/documents/shared/{keyringLogWalk.d.ts → containerKek/keyringLogWalk.d.ts} +2 -2
  21. package/data/documents/shared/{keyringLogWalk.js → containerKek/keyringLogWalk.js} +1 -1
  22. package/data/documents/shared/{keyringRebuild.d.ts → containerKek/keyringRebuild.d.ts} +3 -3
  23. package/data/documents/shared/{keyringRebuild.js → containerKek/keyringRebuild.js} +3 -3
  24. package/data/documents/shared/containerKek/keyringRebuild.js.map +1 -0
  25. package/data/documents/shared/crypto.js +2 -2
  26. package/data/documents/shared/crypto.js.map +1 -1
  27. package/data/documents/shared/events.js +1 -1
  28. package/data/documents/shared/{projection.d.ts → projection/index.d.ts} +7 -7
  29. package/data/documents/shared/{projection.js → projection/index.js} +9 -9
  30. package/data/documents/shared/projection/index.js.map +1 -0
  31. package/data/documents/shared/{projectionContentKeys.d.ts → projection/projectionContentKeys.d.ts} +6 -6
  32. package/data/documents/shared/{projectionContentKeys.js → projection/projectionContentKeys.js} +9 -9
  33. package/data/documents/shared/projection/projectionContentKeys.js.map +1 -0
  34. package/data/documents/shared/{projectionTargets.d.ts → projection/projectionTargets.d.ts} +4 -4
  35. package/data/documents/shared/{projectionTargets.js → projection/projectionTargets.js} +3 -3
  36. package/data/documents/shared/projection/projectionTargets.js.map +1 -0
  37. package/data/documents/shared/responses.d.ts +1 -1
  38. package/data/documents/shared/responses.js +1 -1
  39. package/data/documents/shared/responses.js.map +1 -1
  40. package/data/documents/shared/{documentSyncUpdateDecryption.js → sync/documentSyncUpdateDecryption.js} +10 -10
  41. package/data/documents/shared/sync/documentSyncUpdateDecryption.js.map +1 -0
  42. package/data/documents/shared/{documentSyncUpdateIsolation.d.ts → sync/documentSyncUpdateIsolation.d.ts} +3 -3
  43. package/data/documents/shared/{documentSyncUpdateIsolation.js → sync/documentSyncUpdateIsolation.js} +1 -1
  44. package/data/documents/shared/sync/documentSyncUpdateIsolation.js.map +1 -0
  45. package/data/documents/shared/{mutationAcknowledgement.js → sync/mutationAcknowledgement.js} +1 -1
  46. package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -0
  47. package/data/documents/shared/{pullContinuation.js → sync/pullContinuation.js} +1 -1
  48. package/data/documents/shared/{syncPagination.d.ts → sync/syncPagination.d.ts} +2 -2
  49. package/data/documents/shared/{syncPagination.js → sync/syncPagination.js} +1 -1
  50. package/data/documents/shared/sync/syncPagination.js.map +1 -0
  51. package/data/documents/shared/{syncResponseAuthorization.js → sync/syncResponseAuthorization.js} +3 -3
  52. package/data/documents/shared/sync/syncResponseAuthorization.js.map +1 -0
  53. package/data/documents/shared/{syncResponses.d.ts → sync/syncResponses.d.ts} +2 -2
  54. package/data/documents/shared/{syncResponses.js → sync/syncResponses.js} +6 -6
  55. package/data/documents/shared/sync/syncResponses.js.map +1 -0
  56. package/data/documents/shared/{syncSubmitFailure.d.ts → sync/syncSubmitFailure.d.ts} +1 -1
  57. package/data/documents/shared/types.d.ts +3 -3
  58. package/data/documents/shared/types.js.map +1 -1
  59. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js +1 -1
  60. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js.map +1 -1
  61. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +1 -1
  62. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
  63. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  64. package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js +1 -1
  65. package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js.map +1 -1
  66. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +4 -4
  67. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  68. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js +1 -1
  69. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js.map +1 -1
  70. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js +1 -1
  71. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js.map +1 -1
  72. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js +1 -1
  73. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js.map +1 -1
  74. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +3 -3
  75. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  76. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +4 -4
  77. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  78. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js +2 -2
  79. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js.map +1 -1
  80. package/data/persistence/container-contents/containerContentsPersistence.js +3 -3
  81. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  82. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -2
  83. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  84. package/data/persistence/container-contents/containerCreateIntentSettlement.js +1 -1
  85. package/data/persistence/container-contents/containerDeletionPersistence.js +2 -2
  86. package/data/persistence/container-contents/containerDocumentReassignment.js +2 -2
  87. package/data/persistence/container-contents/containerDocumentReassignment.js.map +1 -1
  88. package/data/persistence/container-contents/containerHydrationPersistence.js +3 -3
  89. package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
  90. package/data/persistence/container-contents/containerIntentPersistence.js +1 -1
  91. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +5 -5
  92. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  93. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +1 -1
  94. package/data/persistence/container-contents/containerMetadataRows.js +3 -3
  95. package/data/persistence/container-contents/containerMetadataRows.js.map +1 -1
  96. package/data/persistence/container-contents/containerMoveAbandonPersistence.js +1 -1
  97. package/data/persistence/container-contents/containerMoveIntentRows.js +1 -1
  98. package/data/persistence/container-contents/containerPendingUpdatePersistence.js +3 -3
  99. package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
  100. package/data/persistence/container-contents/containerRebindPersistence.js +1 -1
  101. package/data/persistence/container-contents/containerReconcilePersistence.js +2 -2
  102. package/data/persistence/container-contents/containerRecoveryPersistence.js +1 -1
  103. package/data/persistence/container-contents/containerRemovalWork.js +3 -3
  104. package/data/persistence/container-contents/containerRemovalWork.js.map +1 -1
  105. package/data/persistence/container-contents/containerStructuralRepair.js +1 -1
  106. package/data/persistence/container-contents/documentLinkRemovalRepair.js +2 -2
  107. package/data/persistence/container-contents/documentLinkRemovalRepair.js.map +1 -1
  108. package/data/persistence/container-contents/documentMoveIntentPersistence.js +2 -2
  109. package/data/persistence/container-contents/documentMoveIntentPersistence.js.map +1 -1
  110. package/data/persistence/container-contents/documentPlacementIntentEnqueue.js +2 -2
  111. package/data/persistence/container-contents/documentPlacementIntentEnqueue.js.map +1 -1
  112. package/data/persistence/container-contents/documentPurgePlacement.js +14 -1
  113. package/data/persistence/container-contents/documentPurgePlacement.js.map +1 -1
  114. package/data/persistence/container-contents/dormantContainerMetadata.js +1 -1
  115. package/data/persistence/container-contents/dormantMetadataSweep.js +1 -1
  116. package/data/persistence/container-contents/pendingContainerCreate.js +1 -1
  117. package/data/persistence/container-contents/supersededContainerBindings.js +1 -1
  118. package/data/persistence/containers/containerPersistence.js +1 -1
  119. package/data/persistence/containers/containerSyncWatermarkPersistence.js +1 -1
  120. package/data/persistence/containers/documentContainerProjectionPersistence.js +1 -1
  121. package/data/persistence/containers/documentPlacement.js +1 -1
  122. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js +1 -1
  123. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +3 -3
  124. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  125. package/data/persistence/documents/documentDiscoveryReset.js +1 -1
  126. package/data/persistence/documents/documentDiscoveryReset.js.map +1 -1
  127. package/data/persistence/documents/documentsPersistence.js +3 -3
  128. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  129. package/data/persistence/documents/internal/attachmentStagingPersistence.js +1 -1
  130. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
  131. package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
  132. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +2 -2
  133. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  134. package/data/persistence/documents/internal/discardDocument.js +3 -3
  135. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  136. package/data/persistence/documents/internal/documentDeletionPersistence.js +4 -4
  137. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  138. package/data/persistence/documents/internal/documentMutationPersistence.js +5 -5
  139. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  140. package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
  141. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
  142. package/data/persistence/documents/internal/documentRows.js +2 -2
  143. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  144. package/data/persistence/documents/internal/documentSummaryQueries.js +1 -1
  145. package/data/persistence/documents/internal/ensureDocumentsSchema.js +2 -2
  146. package/data/persistence/documents/internal/hydratedAttachmentPersistence.js +1 -1
  147. package/data/persistence/documents/internal/orphanSideRows.js +2 -2
  148. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  149. package/data/persistence/documents/internal/pendingCreateAdoption.js +1 -1
  150. package/data/persistence/documents/internal/rowQueryPersistence.js +2 -2
  151. package/data/persistence/documents/internal/syncQueuePersistence.js +3 -3
  152. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  153. package/data/persistence/documents/types.d.ts +3 -3
  154. package/data/persistence/documents/types.js.map +1 -1
  155. package/data/persistence/{documentPurgeCheckpointPersistence.d.ts → keyingCheckpoints/documentPurgeCheckpointPersistence.d.ts} +2 -2
  156. package/data/persistence/{documentPurgeCheckpointPersistence.js → keyingCheckpoints/documentPurgeCheckpointPersistence.js} +4 -4
  157. package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js.map +1 -0
  158. package/data/persistence/{keyingCheckpointAdvancePersistence.js → keyingCheckpoints/keyingCheckpointAdvancePersistence.js} +9 -9
  159. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -0
  160. package/data/persistence/{keyingCheckpointEvidence.js → keyingCheckpoints/keyingCheckpointEvidence.js} +1 -1
  161. package/data/persistence/{keyingCheckpointPersistence.js → keyingCheckpoints/keyingCheckpointPersistence.js} +5 -5
  162. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js.map +1 -0
  163. package/data/persistence/{locallyAcknowledgedCheckpointPersistence.d.ts → keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts} +4 -4
  164. package/data/persistence/{locallyAcknowledgedCheckpointPersistence.js → keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js} +7 -7
  165. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -0
  166. package/data/persistence/{organizationReplacementCheckpointPersistence.js → keyingCheckpoints/organizationReplacementCheckpointPersistence.js} +6 -6
  167. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js.map +1 -0
  168. package/data/persistence/{principalAuthorizationCheckpoints.js → keyingCheckpoints/principalAuthorizationCheckpoints.js} +1 -1
  169. package/data/persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js.map +1 -0
  170. package/data/persistence/organizationFounderPersistence.js +2 -2
  171. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  172. package/data/persistence/organizations/organizationAccessRevocationPersistence.js +3 -3
  173. package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +1 -1
  174. package/data/persistence/organizations/organizationDataUsagePersistence.js +2 -2
  175. package/data/persistence/organizations/organizationDataUsagePersistence.js.map +1 -1
  176. package/data/persistence/organizations/organizationGroupNamePersistence.js +2 -2
  177. package/data/persistence/organizations/organizationGroupNamePersistence.js.map +1 -1
  178. package/data/persistence/organizations/organizationPresentationDenialPersistence.js +2 -2
  179. package/data/persistence/organizations/organizationPresentationDenialPersistence.js.map +1 -1
  180. package/data/persistence/organizations/organizationProfileDocumentPointers.js +2 -2
  181. package/data/persistence/organizations/organizationProfileDocumentPointers.js.map +1 -1
  182. package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js +1 -1
  183. package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js.map +1 -1
  184. package/data/persistence/organizations/organizationReadModelGrantPersistence.js +1 -1
  185. package/data/persistence/organizations/organizationReadModelGrantPersistence.js.map +1 -1
  186. package/data/persistence/organizations/organizationReadModelMemberLoad.js +1 -1
  187. package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
  188. package/data/persistence/organizations/organizationReadModelMembershipPersistence.js +1 -1
  189. package/data/persistence/organizations/organizationReadModelMembershipPersistence.js.map +1 -1
  190. package/data/persistence/organizations/organizationReadModelPersistence.js +3 -3
  191. package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
  192. package/data/persistence/organizations/organizationReadModelProjection.js +1 -1
  193. package/data/persistence/organizations/organizationReadModelProjection.js.map +1 -1
  194. package/data/persistence/organizations/organizationReadModelPurge.js +3 -3
  195. package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
  196. package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +3 -3
  197. package/data/persistence/principalCurrentAcknowledgementPersistence.js +10 -10
  198. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
  199. package/data/persistence/{principalHistoryEvidencePersistence.d.ts → principalHistory/principalHistoryEvidencePersistence.d.ts} +4 -4
  200. package/data/persistence/{principalHistoryEvidencePersistence.js → principalHistory/principalHistoryEvidencePersistence.js} +7 -7
  201. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js.map +1 -0
  202. package/data/persistence/{principalHistoryIncompleteRetention.js → principalHistory/principalHistoryIncompleteRetention.js} +1 -1
  203. package/data/persistence/principalHistory/principalHistoryIncompleteRetention.js.map +1 -0
  204. package/data/persistence/{principalHistoryNodeRetention.js → principalHistory/principalHistoryNodeRetention.js} +4 -4
  205. package/data/persistence/principalHistory/principalHistoryNodeRetention.js.map +1 -0
  206. package/data/persistence/{principalHistoryPrefixPersistence.d.ts → principalHistory/principalHistoryPrefixPersistence.d.ts} +2 -2
  207. package/data/persistence/{principalHistoryPrefixPersistence.js → principalHistory/principalHistoryPrefixPersistence.js} +6 -6
  208. package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js.map +1 -0
  209. package/data/persistence/{principalHistoryRootOwnership.js → principalHistory/principalHistoryRootOwnership.js} +1 -1
  210. package/data/persistence/principalHistory/principalHistoryRootOwnership.js.map +1 -0
  211. package/data/persistence/{principalHistoryStagePersistence.d.ts → principalHistory/principalHistoryStagePersistence.d.ts} +2 -2
  212. package/data/persistence/{principalHistoryStagePersistence.js → principalHistory/principalHistoryStagePersistence.js} +6 -6
  213. package/data/persistence/principalHistory/principalHistoryStagePersistence.js.map +1 -0
  214. package/data/persistence/{principalHistoryStageRetention.js → principalHistory/principalHistoryStageRetention.js} +2 -2
  215. package/data/persistence/principalHistory/principalHistoryStageRetention.js.map +1 -0
  216. package/data/persistence/{principalHistoryUnpublishedRetention.js → principalHistory/principalHistoryUnpublishedRetention.js} +3 -3
  217. package/data/persistence/principalHistory/principalHistoryUnpublishedRetention.js.map +1 -0
  218. package/data/persistence/{principalGrantRetirementPersistence.d.ts → principalKeys/principalGrantRetirementPersistence.d.ts} +2 -2
  219. package/data/persistence/{principalGrantRetirementPersistence.js → principalKeys/principalGrantRetirementPersistence.js} +2 -2
  220. package/data/persistence/principalKeys/principalGrantRetirementPersistence.js.map +1 -0
  221. package/data/persistence/{principalKeyEnvelopeArchivePersistence.js → principalKeys/principalKeyEnvelopeArchivePersistence.js} +3 -3
  222. package/data/persistence/principalKeys/principalKeyEnvelopeArchivePersistence.js.map +1 -0
  223. package/data/persistence/{principalKeyEnvelopeCandidates.js → principalKeys/principalKeyEnvelopeCandidates.js} +9 -9
  224. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -0
  225. package/data/persistence/principalMutationJournalPersistence.d.ts +1 -1
  226. package/data/persistence/principalMutationJournalPersistence.js +1 -1
  227. package/data/persistence/principalMutationJournalPersistence.js.map +1 -1
  228. package/data/persistence/{principalPolicyBundleIntegrity.js → principalPolicy/principalPolicyBundleIntegrity.js} +3 -3
  229. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js.map +1 -0
  230. package/data/persistence/{principalPolicyCheckpointSelection.js → principalPolicy/principalPolicyCheckpointSelection.js} +2 -2
  231. package/data/persistence/principalPolicy/principalPolicyCheckpointSelection.js.map +1 -0
  232. package/data/persistence/{principalPolicyOrganizationPersistence.js → principalPolicy/principalPolicyOrganizationPersistence.js} +2 -2
  233. package/data/persistence/principalPolicy/principalPolicyOrganizationPersistence.js.map +1 -0
  234. package/data/persistence/{principalPolicyPersistence.js → principalPolicy/principalPolicyPersistence.js} +5 -5
  235. package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -0
  236. package/data/persistence/{principalPolicyReferenceCheckpoint.js → principalPolicy/principalPolicyReferenceCheckpoint.js} +3 -3
  237. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js.map +1 -0
  238. package/data/persistence/{principalPolicyReferenceIndexPersistence.js → principalPolicy/principalPolicyReferenceIndexPersistence.js} +4 -4
  239. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js.map +1 -0
  240. package/data/persistence/{principalPolicyReferencePersistence.js → principalPolicy/principalPolicyReferencePersistence.js} +5 -5
  241. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -0
  242. package/data/persistence/{verifiedPrincipalPolicyBundle.js → principalPolicy/verifiedPrincipalPolicyBundle.js} +2 -2
  243. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundle.js.map +1 -0
  244. package/data/persistence/{verifiedPrincipalPolicyCurrent.js → principalPolicy/verifiedPrincipalPolicyCurrent.js} +2 -2
  245. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js.map +1 -0
  246. package/data/persistence/{verifiedPrincipalPolicyRetentionPersistence.js → principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js} +1 -1
  247. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +1 -0
  248. package/data/persistence/securityIncidentPersistence.js +1 -1
  249. package/data/persistence/securityIncidentPersistence.js.map +1 -1
  250. package/data/persistence/trustedUserIdentityPinPersistence.js +1 -1
  251. package/data/persistence/verifiedManifestBundlePersistence.d.ts +1 -1
  252. package/data/persistence/verifiedManifestBundlePersistence.js +4 -4
  253. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  254. package/data/principals/organizationGroupRoles.js +2 -2
  255. package/data/principals/organizationGroupRoles.js.map +1 -1
  256. package/data/principals/principalHistoryPrefixProtection.js.map +1 -1
  257. package/data/principals/principalHistoryStageProtection.js.map +1 -1
  258. package/data/principals/principalPolicyCrypto.js +1 -1
  259. package/data/principals/principalPolicyCrypto.js.map +1 -1
  260. package/data/sqlite/{documentHistoryPersistence.d.ts → documentPersistence/documentHistoryPersistence.d.ts} +1 -1
  261. package/data/sqlite/{documentHistoryPersistence.js → documentPersistence/documentHistoryPersistence.js} +5 -5
  262. package/data/sqlite/documentPersistence/documentHistoryPersistence.js.map +1 -0
  263. package/data/sqlite/{documentOrphanBlobReclaims.js → documentPersistence/documentOrphanBlobReclaims.js} +1 -1
  264. package/data/sqlite/documentPersistence/documentOrphanBlobReclaims.js.map +1 -0
  265. package/data/sqlite/{documentPendingUpdatePersistence.d.ts → documentPersistence/documentPendingUpdatePersistence.d.ts} +2 -2
  266. package/data/sqlite/{documentPendingUpdatePersistence.js → documentPersistence/documentPendingUpdatePersistence.js} +2 -2
  267. package/data/sqlite/documentPersistence/documentPendingUpdatePersistence.js.map +1 -0
  268. package/data/sqlite/{documentPersistenceTypes.d.ts → documentPersistence/documentPersistenceTypes.d.ts} +2 -2
  269. package/data/sqlite/documentPersistence/documentPersistenceTypes.js.map +1 -0
  270. package/data/sqlite/{documentRecordPersistence.d.ts → documentPersistence/documentRecordPersistence.d.ts} +1 -1
  271. package/data/sqlite/{documentRecordPersistence.js → documentPersistence/documentRecordPersistence.js} +4 -4
  272. package/data/sqlite/documentPersistence/documentRecordPersistence.js.map +1 -0
  273. package/data/sqlite/{documentSyncFailurePersistence.d.ts → documentPersistence/documentSyncFailurePersistence.d.ts} +2 -2
  274. package/data/sqlite/{documentSyncFailurePersistence.js → documentPersistence/documentSyncFailurePersistence.js} +3 -3
  275. package/data/sqlite/documentPersistence/documentSyncFailurePersistence.js.map +1 -0
  276. package/data/sqlite/{documentPersistence.d.ts → documentPersistence/index.d.ts} +2 -2
  277. package/data/sqlite/{documentPersistence.js → documentPersistence/index.js} +5 -5
  278. package/data/sqlite/documentPersistence/index.js.map +1 -0
  279. package/data/sqlite/{containerSchema.d.ts → schema/containerSchema.d.ts} +1 -1
  280. package/data/sqlite/{containerSchema.js → schema/containerSchema.js} +1 -1
  281. package/data/sqlite/schema/containerSchema.js.map +1 -0
  282. package/data/sqlite/{schema.d.ts → schema/index.d.ts} +1 -1
  283. package/data/sqlite/{schema.js → schema/index.js} +3 -3
  284. package/data/sqlite/schema/index.js.map +1 -0
  285. package/data/sqlite/{organizationDataUsageSchema.js → schema/organizationDataUsageSchema.js} +1 -1
  286. package/data/sqlite/schema/organizationDataUsageSchema.js.map +1 -0
  287. package/data/sqlite/{organizationProvisioningAttemptSchema.js → schema/organizationProvisioningAttemptSchema.js} +1 -1
  288. package/data/sqlite/schema/organizationProvisioningAttemptSchema.js.map +1 -0
  289. package/data/sqlite/{organizationReadModelTableRegistry.d.ts → schema/organizationReadModelTableRegistry.d.ts} +1 -1
  290. package/data/sqlite/{organizationReadModelTableRegistry.js → schema/organizationReadModelTableRegistry.js} +1 -1
  291. package/data/sqlite/schema/organizationReadModelTableRegistry.js.map +1 -0
  292. package/data/sqlite/{principalHistoryEvidenceSchema.d.ts → schema/principalHistoryEvidenceSchema.d.ts} +1 -1
  293. package/data/sqlite/{principalHistoryEvidenceSchema.js → schema/principalHistoryEvidenceSchema.js} +2 -2
  294. package/data/sqlite/schema/principalHistoryEvidenceSchema.js.map +1 -0
  295. package/data/sqlite/{principalHistoryNodeRetentionSchema.js → schema/principalHistoryNodeRetentionSchema.js} +1 -1
  296. package/data/sqlite/schema/principalHistoryNodeRetentionSchema.js.map +1 -0
  297. package/data/sqlite/{principalHistoryRetentionSchema.js → schema/principalHistoryRetentionSchema.js} +1 -1
  298. package/data/sqlite/{principalHistoryRetentionSchema.js.map → schema/principalHistoryRetentionSchema.js.map} +1 -1
  299. package/data/sqlite/{principalHistoryStageSchema.d.ts → schema/principalHistoryStageSchema.d.ts} +1 -1
  300. package/data/sqlite/{principalHistoryStageSchema.js → schema/principalHistoryStageSchema.js} +2 -2
  301. package/data/sqlite/schema/principalHistoryStageSchema.js.map +1 -0
  302. package/data/sqlite/{principalMutationJournalSchema.d.ts → schema/principalMutationJournalSchema.d.ts} +1 -1
  303. package/data/sqlite/{principalMutationJournalSchema.js → schema/principalMutationJournalSchema.js} +1 -1
  304. package/data/sqlite/{principalMutationJournalSchema.js.map → schema/principalMutationJournalSchema.js.map} +1 -1
  305. package/data/sqlite/{principalPolicySchema.js → schema/principalPolicySchema.js} +1 -1
  306. package/data/sqlite/schema/principalPolicySchema.js.map +1 -0
  307. package/data/sqlite/{securityIncidentSchema.d.ts → schema/securityIncidentSchema.d.ts} +1 -1
  308. package/data/sqlite/{securityIncidentSchema.js → schema/securityIncidentSchema.js} +1 -1
  309. package/data/sqlite/schema/securityIncidentSchema.js.map +1 -0
  310. package/data/sqlite/{verifiedManifestBundleSchema.d.ts → schema/verifiedManifestBundleSchema.d.ts} +1 -1
  311. package/data/sqlite/{verifiedManifestBundleSchema.js → schema/verifiedManifestBundleSchema.js} +1 -1
  312. package/data/sqlite/schema/verifiedManifestBundleSchema.js.map +1 -0
  313. package/data/sqlite/sqlitePersistenceRuntime.d.ts +1 -1
  314. package/data/sqlite/sqlitePersistenceRuntime.js +1 -1
  315. package/index.d.ts +1 -1
  316. package/index.js.map +1 -1
  317. package/package.json +1 -1
  318. package/sqlite/index.d.ts +1 -1
  319. package/sqlite/index.js +1 -1
  320. package/stores/container-contents/containerContentsStore.js +3 -2
  321. package/stores/container-contents/containerContentsStore.js.map +1 -1
  322. package/stores/container-contents/index.d.ts +1 -1
  323. package/stores/container-contents/index.js.map +1 -1
  324. package/stores/container-contents/operations/purgeMoveSettlementOperation.js +71 -0
  325. package/stores/container-contents/operations/purgeMoveSettlementOperation.js.map +1 -0
  326. package/stores/documents/documentStore/history/historyRebuild.js +1 -1
  327. package/stores/documents/documentStore/history/historyRebuild.js.map +1 -1
  328. package/stores/documents/documentStore/state.js.map +1 -1
  329. package/stores/documents/documentStore/sync/syncFinalize.js +1 -1
  330. package/stores/documents/documentStore/sync/syncFinalize.js.map +1 -1
  331. package/stores/documents/documentStore/sync/syncUpdateImport.js +1 -1
  332. package/stores/documents/documentStore/sync/syncUpdateImport.js.map +1 -1
  333. package/workflows/blobs/detach.js +1 -1
  334. package/workflows/blobs/hydration/decrypt.js +1 -1
  335. package/workflows/blobs/upload/index.js +1 -1
  336. package/workflows/blobs/verification/retainedAttachmentVerification.js +1 -1
  337. package/workflows/blobs/verification/writerProjection.js +1 -1
  338. package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
  339. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  340. package/workflows/container-contents/container-state/moveIntentSync.js +43 -5
  341. package/workflows/container-contents/container-state/moveIntentSync.js.map +1 -1
  342. package/workflows/container-contents/container-state/purge/purgeMoveSettlement.js +119 -0
  343. package/workflows/container-contents/container-state/purge/purgeMoveSettlement.js.map +1 -0
  344. package/workflows/container-contents/container-state/purge/purgeProgress.d.ts +8 -0
  345. package/workflows/container-contents/container-state/purge/purgeProgress.js.map +1 -1
  346. package/workflows/container-contents/container-state/remote.js +1 -0
  347. package/workflows/container-contents/container-state/remote.js.map +1 -1
  348. package/workflows/container-contents/container-state/share/index.js +1 -1
  349. package/workflows/container-contents/documentLinks/index.js +1 -1
  350. package/workflows/container-contents/documentMove/documentMoveVanishedRefresh.js +1 -1
  351. package/workflows/container-contents/documentPriming/documentHydrationProbe.js +1 -1
  352. package/workflows/container-contents/documentPriming/index.js +1 -1
  353. package/workflows/container-contents/documentQueries/index.js +1 -1
  354. package/workflows/container-contents/documentQueries/sql.js +1 -1
  355. package/workflows/container-contents/info/blobInfo.js +1 -1
  356. package/workflows/container-contents/info/containerInfo.js +1 -1
  357. package/workflows/container-contents/info/documentInfo.js +1 -1
  358. package/workflows/container-contents/metadata/index.js +1 -1
  359. package/workflows/container-contents/metadata/index.js.map +1 -1
  360. package/workflows/container-contents/metadata/metadataEvents.d.ts +1 -1
  361. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
  362. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  363. package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
  364. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
  365. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js +1 -1
  366. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js.map +1 -1
  367. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +1 -1
  368. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  369. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  370. package/workflows/container-contents/metadata/metadataSyncSettlement.d.ts +1 -1
  371. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
  372. package/workflows/container-contents/metadata/metadataTypes.d.ts +1 -1
  373. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  374. package/workflows/container-contents/pendingWrites/index.js +2 -2
  375. package/workflows/container-contents/pendingWrites/sources.js +1 -1
  376. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +1 -1
  377. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -1
  378. package/workflows/container-contents/remoteHydration/reattachMetadata.js.map +1 -1
  379. package/workflows/container-contents/syncLane.d.ts +2 -0
  380. package/workflows/container-contents/syncLane.js +7 -0
  381. package/workflows/container-contents/syncLane.js.map +1 -1
  382. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +2 -2
  383. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  384. package/workflows/containers/child/create/index.js +2 -2
  385. package/workflows/containers/child/create/index.js.map +1 -1
  386. package/workflows/containers/child/move/index.d.ts +1 -0
  387. package/workflows/containers/child/move/index.js +2 -1
  388. package/workflows/containers/child/move/index.js.map +1 -1
  389. package/workflows/containers/child/move/moveRotation.js +1 -1
  390. package/workflows/containers/child/move/moveRotation.js.map +1 -1
  391. package/workflows/containers/child/move/moveWraps.js +1 -1
  392. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  393. package/workflows/containers/child/mutationSubmit.js +3 -1
  394. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  395. package/workflows/containers/child/recite.js +2 -2
  396. package/workflows/containers/child/recite.js.map +1 -1
  397. package/workflows/containers/child/rotation/rotationContext.js +3 -3
  398. package/workflows/containers/child/rotation/rotationContext.js.map +1 -1
  399. package/workflows/containers/child/share/currentSharePrincipalPolicy.js +1 -1
  400. package/workflows/containers/child/share/currentSharePrincipalPolicy.js.map +1 -1
  401. package/workflows/containers/child/share/index.js +1 -1
  402. package/workflows/containers/child/share/index.js.map +1 -1
  403. package/workflows/containers/child/share/shareAncestorRepair.js +2 -2
  404. package/workflows/containers/child/share/shareAncestorRepair.js.map +1 -1
  405. package/workflows/containers/child/share/shareMaterialization.js +1 -1
  406. package/workflows/containers/child/share/sharePrincipalPolicy.js +5 -5
  407. package/workflows/containers/child/share/sharePrincipalPolicy.js.map +1 -1
  408. package/workflows/containers/index.d.ts +3 -3
  409. package/workflows/containers/index.js +2 -2
  410. package/workflows/containers/index.js.map +1 -1
  411. package/workflows/containers/writeRefusal.js +1 -1
  412. package/workflows/containers/writeRefusal.js.map +1 -1
  413. package/workflows/documents/create/createAdoption.js +1 -1
  414. package/workflows/documents/create/createResponse.js +2 -2
  415. package/workflows/documents/create/createResponse.js.map +1 -1
  416. package/workflows/documents/create/index.js +1 -1
  417. package/workflows/documents/documentMutationCommit.d.ts +1 -1
  418. package/workflows/documents/documentMutationPreparation.d.ts +1 -1
  419. package/workflows/documents/documentMutationPreparation.js +1 -1
  420. package/workflows/documents/documentMutationPreparation.js.map +1 -1
  421. package/workflows/documents/index.d.ts +5 -5
  422. package/workflows/documents/index.js +5 -5
  423. package/workflows/documents/index.js.map +1 -1
  424. package/workflows/documents/linkSet/index.js +2 -2
  425. package/workflows/documents/linkSet/index.js.map +1 -1
  426. package/workflows/documents/linkSet/linkSetAuthority.js +1 -1
  427. package/workflows/documents/linkSet/linkSetBlobRewraps.js +1 -1
  428. package/workflows/documents/linkSet/linkSetProjectionSeed.js +1 -1
  429. package/workflows/documents/linkSet/linkSetRemote.js +1 -1
  430. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
  431. package/workflows/documents/purge/index.js +1 -1
  432. package/workflows/documents/sync/index.js +2 -2
  433. package/workflows/documents/sync/index.js.map +1 -1
  434. package/workflows/documents/sync/initialSync.js +1 -1
  435. package/workflows/documents/sync/readOnlyProjectionFailure.js +1 -1
  436. package/workflows/documents/sync/readOnlyProjectionFailure.js.map +1 -1
  437. package/workflows/documents/sync/readOnlySync.d.ts +3 -3
  438. package/workflows/documents/sync/readOnlySync.js +1 -1
  439. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  440. package/workflows/documents/sync/reportDocumentSyncQuarantine.js.map +1 -1
  441. package/workflows/documents/sync/syncAttemptPlanning.js +2 -2
  442. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  443. package/workflows/documents/sync/syncAttemptState.d.ts +2 -2
  444. package/workflows/documents/sync/syncAttemptState.js.map +1 -1
  445. package/workflows/documents/sync/syncResponseResult.js +2 -2
  446. package/workflows/documents/sync/syncResponseResult.js.map +1 -1
  447. package/workflows/documents/syncFailures/index.js +1 -1
  448. package/workflows/documents/syncFailures/index.js.map +1 -1
  449. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
  450. package/workflows/documents/syncFailures/syncFailureClassification.js +1 -1
  451. package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -1
  452. package/workflows/documents/syncPlan/syncContentKeys.d.ts +1 -1
  453. package/workflows/documents/syncPlan/syncContentKeys.js +3 -3
  454. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
  455. package/workflows/documents/syncPlan/syncPlanMaterial.js +2 -2
  456. package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -1
  457. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +2 -2
  458. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  459. package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js +1 -1
  460. package/workflows/documents/syncRekeys/syncRecoveryRekey.d.ts +1 -1
  461. package/workflows/documents/syncRekeys/syncRecoveryRekey.js +1 -1
  462. package/workflows/organizations/currentOrganizationAuthority.js +2 -2
  463. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  464. package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
  465. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  466. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +1 -1
  467. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  468. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +1 -1
  469. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
  470. package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -3
  471. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  472. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  473. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  474. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js +1 -1
  475. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  476. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +2 -2
  477. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  478. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js +1 -1
  479. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js.map +1 -1
  480. package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
  481. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
  482. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  483. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  484. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -1
  485. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  486. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  487. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  488. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +1 -1
  489. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
  490. package/workflows/organizations/provisioning/organizationReplacementVerification.js +1 -1
  491. package/workflows/organizations/provisioning/organizationReplacementVerification.js.map +1 -1
  492. package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
  493. package/workflows/organizations/readModel/localReadModelDetails.js +1 -1
  494. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  495. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +1 -1
  496. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
  497. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.d.ts +1 -1
  498. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +1 -1
  499. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
  500. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
  501. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
  502. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +2 -2
  503. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
  504. package/workflows/principals/externalAdminPolicy.js +2 -2
  505. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  506. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js +2 -2
  507. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -1
  508. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js +1 -1
  509. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js.map +1 -1
  510. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +1 -1
  511. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
  512. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js +1 -1
  513. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js.map +1 -1
  514. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +3 -3
  515. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
  516. package/workflows/principals/policyCache/index.js +3 -3
  517. package/workflows/principals/policyCache/index.js.map +1 -1
  518. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +1 -1
  519. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  520. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +3 -3
  521. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  522. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -1
  523. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +2 -2
  524. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
  525. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +3 -3
  526. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
  527. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.d.ts +2 -2
  528. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.js.map +1 -1
  529. package/workflows/principals/publicHistory/publicProjectionPrincipal.js +1 -1
  530. package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -1
  531. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +1 -1
  532. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  533. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +1 -1
  534. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
  535. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +1 -1
  536. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
  537. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js +1 -1
  538. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js.map +1 -1
  539. package/workflows/registration/persistRegistrationBootstrap.d.ts +2 -2
  540. package/workflows/registration/persistRegistrationBootstrap.js +2 -2
  541. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  542. package/workflows/registration/provisioningAcknowledgement.js +1 -1
  543. package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
  544. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -1
  545. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  546. package/workflows/sync/remoteReset.js +7 -7
  547. package/workflows/sync/remoteReset.js.map +1 -1
  548. package/workflows/sync/remoteResetAttachments.js +1 -1
  549. package/workflows/sync/remoteResetCursorScope.js +1 -1
  550. package/workflows/sync/remoteResetPlans.js +1 -1
  551. package/workflows/sync/remoteResetPrincipalScope.js +5 -5
  552. package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
  553. package/workflows/sync/remoteResetScope.js +1 -1
  554. package/data/documents/shared/containerKekPath.js.map +0 -1
  555. package/data/documents/shared/containerKekPathHistory.js.map +0 -1
  556. package/data/documents/shared/containerKekPathVerification.js.map +0 -1
  557. package/data/documents/shared/containerKekWrapping.js.map +0 -1
  558. package/data/documents/shared/documentSyncUpdateDecryption.js.map +0 -1
  559. package/data/documents/shared/documentSyncUpdateIsolation.js.map +0 -1
  560. package/data/documents/shared/keyringRebuild.js.map +0 -1
  561. package/data/documents/shared/mutationAcknowledgement.js.map +0 -1
  562. package/data/documents/shared/projection.js.map +0 -1
  563. package/data/documents/shared/projectionContentKeys.js.map +0 -1
  564. package/data/documents/shared/projectionTargets.js.map +0 -1
  565. package/data/documents/shared/syncPagination.js.map +0 -1
  566. package/data/documents/shared/syncResponseAuthorization.js.map +0 -1
  567. package/data/documents/shared/syncResponses.js.map +0 -1
  568. package/data/persistence/documentPurgeCheckpointPersistence.js.map +0 -1
  569. package/data/persistence/keyingCheckpointAdvancePersistence.js.map +0 -1
  570. package/data/persistence/keyingCheckpointPersistence.js.map +0 -1
  571. package/data/persistence/locallyAcknowledgedCheckpointPersistence.js.map +0 -1
  572. package/data/persistence/organizationReplacementCheckpointPersistence.js.map +0 -1
  573. package/data/persistence/principalAuthorizationCheckpoints.js.map +0 -1
  574. package/data/persistence/principalGrantRetirementPersistence.js.map +0 -1
  575. package/data/persistence/principalHistoryEvidencePersistence.js.map +0 -1
  576. package/data/persistence/principalHistoryIncompleteRetention.js.map +0 -1
  577. package/data/persistence/principalHistoryNodeRetention.js.map +0 -1
  578. package/data/persistence/principalHistoryPrefixPersistence.js.map +0 -1
  579. package/data/persistence/principalHistoryRootOwnership.js.map +0 -1
  580. package/data/persistence/principalHistoryStagePersistence.js.map +0 -1
  581. package/data/persistence/principalHistoryStageRetention.js.map +0 -1
  582. package/data/persistence/principalHistoryUnpublishedRetention.js.map +0 -1
  583. package/data/persistence/principalKeyEnvelopeArchivePersistence.js.map +0 -1
  584. package/data/persistence/principalKeyEnvelopeCandidates.js.map +0 -1
  585. package/data/persistence/principalPolicyBundleIntegrity.js.map +0 -1
  586. package/data/persistence/principalPolicyCheckpointSelection.js.map +0 -1
  587. package/data/persistence/principalPolicyOrganizationPersistence.js.map +0 -1
  588. package/data/persistence/principalPolicyPersistence.js.map +0 -1
  589. package/data/persistence/principalPolicyReferenceCheckpoint.js.map +0 -1
  590. package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +0 -1
  591. package/data/persistence/principalPolicyReferencePersistence.js.map +0 -1
  592. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +0 -1
  593. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +0 -1
  594. package/data/persistence/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
  595. package/data/sqlite/containerSchema.js.map +0 -1
  596. package/data/sqlite/documentHistoryPersistence.js.map +0 -1
  597. package/data/sqlite/documentOrphanBlobReclaims.js.map +0 -1
  598. package/data/sqlite/documentPendingUpdatePersistence.js.map +0 -1
  599. package/data/sqlite/documentPersistence.js.map +0 -1
  600. package/data/sqlite/documentPersistenceTypes.js.map +0 -1
  601. package/data/sqlite/documentRecordPersistence.js.map +0 -1
  602. package/data/sqlite/documentSyncFailurePersistence.js.map +0 -1
  603. package/data/sqlite/organizationDataUsageSchema.js.map +0 -1
  604. package/data/sqlite/organizationProvisioningAttemptSchema.js.map +0 -1
  605. package/data/sqlite/organizationReadModelTableRegistry.js.map +0 -1
  606. package/data/sqlite/principalHistoryEvidenceSchema.js.map +0 -1
  607. package/data/sqlite/principalHistoryNodeRetentionSchema.js.map +0 -1
  608. package/data/sqlite/principalHistoryStageSchema.js.map +0 -1
  609. package/data/sqlite/principalPolicySchema.js.map +0 -1
  610. package/data/sqlite/schema.js.map +0 -1
  611. package/data/sqlite/securityIncidentSchema.js.map +0 -1
  612. package/data/sqlite/verifiedManifestBundleSchema.js.map +0 -1
  613. /package/data/documents/shared/{containerKekCurrency.js → containerKek/containerKekCurrency.js} +0 -0
  614. /package/data/documents/shared/{containerKekCurrency.js.map → containerKek/containerKekCurrency.js.map} +0 -0
  615. /package/data/documents/shared/{containerKekEntryVerification.js.map → containerKek/containerKekEntryVerification.js.map} +0 -0
  616. /package/data/documents/shared/{containerKekLogFetch.js.map → containerKek/containerKekLogFetch.js.map} +0 -0
  617. /package/data/documents/shared/{containerKekPath.d.ts → containerKek/containerKekPath.d.ts} +0 -0
  618. /package/data/documents/shared/{keyringLogWalk.js.map → containerKek/keyringLogWalk.js.map} +0 -0
  619. /package/data/documents/shared/{pullContinuation.d.ts → sync/pullContinuation.d.ts} +0 -0
  620. /package/data/documents/shared/{pullContinuation.js.map → sync/pullContinuation.js.map} +0 -0
  621. /package/data/documents/shared/{syncSubmitFailure.js → sync/syncSubmitFailure.js} +0 -0
  622. /package/data/documents/shared/{syncSubmitFailure.js.map → sync/syncSubmitFailure.js.map} +0 -0
  623. /package/data/persistence/{keyingCheckpointEvidence.js.map → keyingCheckpoints/keyingCheckpointEvidence.js.map} +0 -0
  624. /package/data/persistence/{storedPrincipalPolicyBundle.js → principalPolicy/storedPrincipalPolicyBundle.js} +0 -0
  625. /package/data/persistence/{storedPrincipalPolicyBundle.js.map → principalPolicy/storedPrincipalPolicyBundle.js.map} +0 -0
  626. /package/data/sqlite/{documentPersistenceTypes.js → documentPersistence/documentPersistenceTypes.js} +0 -0
  627. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.d.ts → schema/containerDocumentTombstoneHoldSchema.d.ts} +0 -0
  628. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js → schema/containerDocumentTombstoneHoldSchema.js} +0 -0
  629. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js.map → schema/containerDocumentTombstoneHoldSchema.js.map} +0 -0
  630. /package/data/sqlite/{documentAttachmentSchema.d.ts → schema/documentAttachmentSchema.d.ts} +0 -0
  631. /package/data/sqlite/{documentAttachmentSchema.js → schema/documentAttachmentSchema.js} +0 -0
  632. /package/data/sqlite/{documentAttachmentSchema.js.map → schema/documentAttachmentSchema.js.map} +0 -0
  633. /package/data/sqlite/{documentDiscoveryEvidenceSchema.js → schema/documentDiscoveryEvidenceSchema.js} +0 -0
  634. /package/data/sqlite/{documentDiscoveryEvidenceSchema.js.map → schema/documentDiscoveryEvidenceSchema.js.map} +0 -0
  635. /package/data/sqlite/{documentPlacementIntentSchema.js → schema/documentPlacementIntentSchema.js} +0 -0
  636. /package/data/sqlite/{documentPlacementIntentSchema.js.map → schema/documentPlacementIntentSchema.js.map} +0 -0
  637. /package/data/sqlite/{localIntentSchema.d.ts → schema/localIntentSchema.d.ts} +0 -0
  638. /package/data/sqlite/{localIntentSchema.js → schema/localIntentSchema.js} +0 -0
  639. /package/data/sqlite/{localIntentSchema.js.map → schema/localIntentSchema.js.map} +0 -0
  640. /package/data/sqlite/{organizationFounderSchema.js → schema/organizationFounderSchema.js} +0 -0
  641. /package/data/sqlite/{organizationFounderSchema.js.map → schema/organizationFounderSchema.js.map} +0 -0
  642. /package/data/sqlite/{organizationReadModelSchema.js → schema/organizationReadModelSchema.js} +0 -0
  643. /package/data/sqlite/{organizationReadModelSchema.js.map → schema/organizationReadModelSchema.js.map} +0 -0
  644. /package/data/sqlite/{principalGrantRetirementSchema.js → schema/principalGrantRetirementSchema.js} +0 -0
  645. /package/data/sqlite/{principalGrantRetirementSchema.js.map → schema/principalGrantRetirementSchema.js.map} +0 -0
  646. /package/data/sqlite/{principalPolicySchema.d.ts → schema/principalPolicySchema.d.ts} +0 -0
package/sqlite/index.d.ts CHANGED
@@ -12,7 +12,7 @@ export { createModuleDatabaseRuntime as createSQLiteRuntime } from "../internal/
12
12
  export declare function createSQLiteRuntimeFromWorker(worker: SQLiteRuntimeWorker): SQLiteRuntime;
13
13
  export { purgeOpfsSqliteDatabase } from "../internal/sqlite-worker/purgeOpfsDatabase.js";
14
14
  export type { DatabasePersistenceMode } from "../internal/sqlite-worker/types.js";
15
- export { clientSQLiteSchema } from "../data/sqlite/schema.js";
15
+ export { clientSQLiteSchema } from "../data/sqlite/schema/index.js";
16
16
  export { type ClientSQLiteDatabase as SQLiteDatabase, type ClientSQLitePersistenceRuntime as SQLitePersistenceRuntime, type ClientSQLiteTransactionScope as SQLiteTransaction, getClientSQLitePersistenceRuntime as getSQLitePersistenceRuntime, } from "../data/sqlite/sqlitePersistenceRuntime.js";
17
17
  export { createExecSql, defineSqlTableSchema, type ExecSql, type ExecSqlClientLike, ensureSqlTables, resetConnectionSchemaMemo, runSerializedSqlMutation, type SqlArrayRow, type SqlBind, type SqlRow, type SqlRowMode, type SqlRowValue, type SqlTableSchema, unavailableExecSql, } from "../data/sqlite/sqlSchema.js";
18
18
  export { EPHEMERAL_STORAGE_POLICY, isPersistentStorageSupported, PERSISTENT_STORAGE_POLICY, type RequestPersistentStorageResult, requestPersistentStorage, resolveStoragePersistencePolicy, type StoragePersistencePolicy, } from "../data/sqlite/storagePersistence.js";
package/sqlite/index.js CHANGED
@@ -4,7 +4,7 @@ export function createSQLiteRuntimeFromWorker(worker) {
4
4
  return createDatabaseRuntime(worker);
5
5
  }
6
6
  export { purgeOpfsSqliteDatabase } from "../internal/sqlite-worker/purgeOpfsDatabase.js";
7
- export { clientSQLiteSchema } from "../data/sqlite/schema.js";
7
+ export { clientSQLiteSchema } from "../data/sqlite/schema/index.js";
8
8
  export { getClientSQLitePersistenceRuntime as getSQLitePersistenceRuntime, } from "../data/sqlite/sqlitePersistenceRuntime.js";
9
9
  export { createExecSql, defineSqlTableSchema, ensureSqlTables, resetConnectionSchemaMemo, runSerializedSqlMutation, unavailableExecSql, } from "../data/sqlite/sqlSchema.js";
10
10
  export { EPHEMERAL_STORAGE_POLICY, isPersistentStorageSupported, PERSISTENT_STORAGE_POLICY, requestPersistentStorage, resolveStoragePersistencePolicy, } from "../data/sqlite/storagePersistence.js";
@@ -5,6 +5,7 @@ import { createChildContainer, deleteContainer, ensureSystemContainer, moveConta
5
5
  import { emptyTrash } from "./operations/emptyTrashOperation.js";
6
6
  import { prepareContainerGroupRewrap, verifyContainerGroupRewrapCurrent, } from "./operations/groupRewrapOperation.js";
7
7
  import { purgeContainer } from "./operations/purgeContainerOperation.js";
8
+ import { chainPurgeAfterScopeMoves } from "./operations/purgeMoveSettlementOperation.js";
8
9
  import { setContainerIcon } from "./operations/setContainerIconOperation.js";
9
10
  import { shareContainerWithGroup, shareContainerWithUser, } from "./operations/shareOperations.js";
10
11
  import { invalidateRemoteContainerWrites } from "./remoteWrites/remoteWriteGuards.js";
@@ -116,8 +117,8 @@ export function createContainerWriteMethods(state, syncAgent) {
116
117
  ...createContainerSharingMethods(state, syncAgent),
117
118
  createChild: (parentId, name) => chainContainerWrite(state, (isCurrent) => createChildContainer(state, syncAgent, parentId, name, isCurrent), [parentId]),
118
119
  deleteContainer: createDeleteContainerMethod(state, syncAgent),
119
- purgeContainer: (containerId, options) => chainRemoteContainerTask(state, syncAgent, false, (isCurrent) => purgeContainer(state, syncAgent, containerId, options, isCurrent), containerId),
120
- emptyTrash: (trashContainerId, options) => chainRemoteContainerTask(state, syncAgent, false, (isCurrent) => emptyTrash(state, syncAgent, trashContainerId, options, isCurrent), trashContainerId),
120
+ purgeContainer: (containerId, options) => chainPurgeAfterScopeMoves(state, syncAgent, containerId, options, (isCurrent) => purgeContainer(state, syncAgent, containerId, options, isCurrent)),
121
+ emptyTrash: (trashContainerId, options) => chainPurgeAfterScopeMoves(state, syncAgent, trashContainerId, options, (isCurrent) => emptyTrash(state, syncAgent, trashContainerId, options, isCurrent)),
121
122
  ensureSystemContainer: createEnsureSystemContainerMethod(state, syncAgent),
122
123
  moveContainer: (containerId, parentId) => chainContainerWrite(state, (isCurrent) => moveContainer(state, syncAgent, containerId, parentId, isCurrent), [containerId, parentId], containerId),
123
124
  prepareGroupRewrap: createPrepareGroupRewrapMethod(state, syncAgent),
@@ -1 +1 @@
1
- {"version":3,"file":"containerContentsStore.js","sourceRoot":"","sources":["containerContentsStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kCAAkC,EAAE,MAAM,oEAAoE,CAAC;AACxH,OAAO,EAEL,mC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AAO,EACP,mCAAmC,EACnC,OAAO,CACR,CAAC;IACF,8BAA8B,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IAC3D,OAAO,SAAS,CAAC,KAAK,CAAC;AACzB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,uCAAuC,CACrD,WAAwB;IAExB,MAAM,KAAK,GAAG,8BAA8B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC9D,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,KAAK,CAAC;IACf,CAAC;IAED,KAAK,CAAC,sBAAsB,EAAE,CAAC;IAC/B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport { getCachedContainerWriterProjection } from \"../../workflows/container-contents/container-state/projectionCache\";\nimport {\n type ContainerContentsPersistence,\n defaultContainerContentsPersistence,\n} from \"../../workflows/container-contents/containerPersistence\";\nimport { persistContainerState } from \"./containerState/containerStatePersistence\";\nimport {\n createChildContainer,\n deleteContainer,\n ensureSystemContainer,\n moveContainer,\n renameContainer,\n} from \"./operations\";\nimport { emptyTrash } from \"./operations/emptyTrashOperation\";\nimport {\n prepareContainerGroupRewrap,\n verifyContainerGroupRewrapCurrent,\n} from \"./operations/groupRewrapOperation\";\nimport { purgeContainer } from \"./operations/purgeContainerOperation\";\nimport { setContainerIcon } from \"./operations/setContainerIconOperation\";\nimport {\n shareContainerWithGroup,\n shareContainerWithUser,\n} from \"./operations/shareOperations\";\nimport { invalidateRemoteContainerWrites } from \"./remoteWrites/remoteWriteGuards\";\nimport { chainRemoteContainerTask } from \"./remoteWrites/remoteWriteQueue\";\nimport { captureContainerWriteGeneration } from \"./remoteWrites/writeGeneration\";\nimport {\n createContainerContentsStoreState,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStorePersistence,\n updateContainerContentsStoreRuntime,\n} from \"./state\";\nimport {\n type ContainerContentsStoreRuntime,\n type ContainerContentsStoreSyncAgent,\n createContainerContentsStoreSyncAgent,\n} from \"./syncAgent\";\nimport { findRootContainerState } from \"./systemContainers/systemContainerLookup\";\nimport type {\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerContentsStoreState,\n} from \"./types\";\n\nconst containerContentsStoresByScope = new WeakMap<\n DomainScope,\n ContainerContentsStoreEntry\n>();\n\ninterface ContainerContentsStoreEntry {\n requestDocumentPriming: () => void;\n store: ContainerContentsStore;\n updateOptions: (options: ContainerContentsStoreOptions) => void;\n}\n\nfunction applyContainerContentsStoreOptions(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n options: ContainerContentsStoreOptions,\n): void {\n if (\"logLabel\" in options) {\n state.logLabel = options.logLabel;\n }\n\n if (\"persistence\" in options) {\n updateContainerContentsStorePersistence(\n state,\n options.persistence ?? defaultContainerContentsPersistence,\n syncAgent,\n );\n }\n}\n\nfunction getCachedContainerWriterProjectionForStore(\n state: ContainerContentsStoreState,\n containerId: string,\n) {\n const containerState = state.containersById.get(containerId);\n return containerState\n ? getCachedContainerWriterProjection(containerState)\n : null;\n}\n\nfunction createContainerContentsStoreSyncHost(\n state: ContainerContentsStoreState,\n): Parameters<typeof createContainerContentsStoreSyncAgent>[0][\"host\"] {\n return {\n persistContainerState: (\n containerState,\n patch,\n updateView,\n saveOptions,\n mutationOptions,\n ) =>\n persistContainerState(state, containerState, {\n patch,\n updateView,\n saveOptions,\n ...mutationOptions,\n }),\n requestDocumentPriming: () => {\n state.documentStoresNeedPriming = true;\n },\n updateSnapshot: () => updateContainerContentsSnapshot(state),\n };\n}\n\n// null marks an unknown mutation scope; [] delegates invalidation to actual writes.\nfunction chainContainerWrite(\n state: ContainerContentsStoreState,\n work: (isCurrent: () => boolean) => ContainerContentsStoreState[\"writeChain\"],\n changedIds: readonly string[] | null = null,\n movedId?: string,\n): ContainerContentsStoreState[\"writeChain\"] {\n const isCurrent = captureContainerWriteGeneration(state);\n invalidateRemoteContainerWrites(state, changedIds, movedId);\n state.writeChain = state.writeChain\n .catch(() => null)\n .then(() => {\n if (!isCurrent()) return null;\n invalidateRemoteContainerWrites(state, changedIds, movedId);\n return work(isCurrent);\n })\n .then((node) => (isCurrent() ? node : null));\n return state.writeChain;\n}\n\ntype ContainerWriteMethods = Pick<\n ContainerContentsStore,\n | \"createChild\"\n | \"deleteContainer\"\n | \"emptyTrash\"\n | \"ensureSystemContainer\"\n | \"moveContainer\"\n | \"prepareGroupRewrap\"\n | \"purgeContainer\"\n | \"renameContainer\"\n | \"setContainerIcon\"\n | \"shareWithGroup\"\n | \"shareWithUser\"\n>;\n\n// The group-rewrap builder verifies any required existing grant before capturing\n// the container KEK, then returns a check/rewrap pair. A verified non-match is\n// distinct from an unavailable preparation so security-critical callers can\n// no-op unrelated groups without failing open for a real grant.\nfunction createPrepareGroupRewrapMethod(\n state: ContainerContentsStoreState,\n syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>,\n): ContainerContentsStore[\"prepareGroupRewrap\"] {\n return async (containerId, groupId, accessLevel, options) => {\n const preparation = await chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n (isCurrent) =>\n prepareContainerGroupRewrap(\n state,\n containerId,\n groupId,\n accessLevel,\n options,\n isCurrent,\n ),\n containerId,\n );\n return preparation?.status === \"prepared\"\n ? {\n isCurrent: (\n expectedGroupHead,\n expectedContainerId,\n expectedOrganizationId,\n ) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n verifyContainerGroupRewrapCurrent(\n state,\n containerId,\n groupId,\n accessLevel,\n expectedGroupHead,\n expectedContainerId,\n expectedOrganizationId,\n isCurrent,\n ),\n containerId,\n ),\n rewrap: () =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithGroup(\n state,\n syncAgent,\n containerId,\n groupId,\n accessLevel,\n {\n ...options,\n knownContainerKeks: preparation.knownContainerKeks,\n // A prepared re-wrap is grant-preserving by definition, so\n // it never mints a grant and never needs the chosen name.\n requireExistingGrant: true,\n },\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n status: \"prepared\" as const,\n }\n : (preparation ?? null);\n };\n}\n\nfunction createContainerSharingMethods(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): Pick<ContainerWriteMethods, \"shareWithUser\" | \"shareWithGroup\"> {\n return {\n shareWithUser: (containerId, userId) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithUser(\n state,\n syncAgent,\n containerId,\n userId,\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n shareWithGroup: (containerId, groupId, accessLevel, options) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithGroup(\n state,\n syncAgent,\n containerId,\n groupId,\n accessLevel,\n options,\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n };\n}\n\nfunction createDeleteContainerMethod(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): ContainerContentsStore[\"deleteContainer\"] {\n return (containerId) => {\n const current = captureContainerWriteGeneration(state);\n const remoteDelete = () =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n (isCurrent) =>\n deleteContainer(state, syncAgent, containerId, isCurrent),\n containerId,\n ).then((node) => node !== null);\n if (state.containersById.get(containerId)?.record.documentId)\n return remoteDelete();\n let promoted = false;\n return chainContainerWrite(\n state,\n (isCurrent) => {\n // Promotion can win while this local operation was queued. Hand it to\n // the remote queue after releasing the local chain, before any HTTP I/O.\n promoted = Boolean(\n state.containersById.get(containerId)?.record.documentId,\n );\n return promoted\n ? Promise.resolve(null)\n : deleteContainer(state, syncAgent, containerId, isCurrent);\n },\n [containerId],\n ).then((node) => (promoted && current() ? remoteDelete() : node !== null));\n };\n}\n\nfunction createEnsureSystemContainerMethod(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): ContainerContentsStore[\"ensureSystemContainer\"] {\n return (systemSlot, name, options) => {\n const work = (isCurrent: () => boolean) =>\n ensureSystemContainer(\n state,\n syncAgent,\n systemSlot,\n name,\n options,\n isCurrent,\n );\n const rootId = findRootContainerState(state)?.container.id;\n return options?.deferRemoteBootstrap\n ? chainContainerWrite(state, work, [])\n : chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n work,\n rootId ? { rootId, systemSlot } : undefined,\n );\n };\n}\n\nexport function createContainerWriteMethods(\n state: ContainerContentsStoreState,\n syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>,\n): ContainerWriteMethods {\n return {\n ...createContainerSharingMethods(state, syncAgent),\n createChild: (parentId, name) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n createChildContainer(state, syncAgent, parentId, name, isCurrent),\n [parentId],\n ),\n deleteContainer: createDeleteContainerMethod(state, syncAgent),\n purgeContainer: (containerId, options) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n purgeContainer(state, syncAgent, containerId, options, isCurrent),\n containerId,\n ),\n emptyTrash: (trashContainerId, options) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n emptyTrash(state, syncAgent, trashContainerId, options, isCurrent),\n trashContainerId,\n ),\n ensureSystemContainer: createEnsureSystemContainerMethod(state, syncAgent),\n moveContainer: (containerId, parentId) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n moveContainer(state, syncAgent, containerId, parentId, isCurrent),\n [containerId, parentId],\n containerId,\n ),\n prepareGroupRewrap: createPrepareGroupRewrapMethod(state, syncAgent),\n renameContainer: (containerId, name) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n renameContainer(state, syncAgent, containerId, name, isCurrent),\n [containerId],\n ),\n setContainerIcon: (containerId, icon) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n setContainerIcon(state, syncAgent, containerId, icon, isCurrent),\n [containerId],\n ),\n };\n}\n\nfunction createContainerContentsStoreEntry(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence = defaultContainerContentsPersistence,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStoreEntry {\n const state = createContainerContentsStoreState(\n initialRuntime,\n options.persistence ?? persistence,\n options.logLabel,\n );\n const syncAgent = createContainerContentsStoreSyncAgent({\n host: createContainerContentsStoreSyncHost(state),\n state,\n });\n const writeMethods = createContainerWriteMethods(state, syncAgent);\n\n return {\n requestDocumentPriming: () => {\n state.documentStoresNeedPriming = true;\n syncAgent.scheduleSync();\n },\n store: {\n ...writeMethods,\n refresh: () => syncAgent.refresh({ resetAllLaneWatermarks: true }),\n refreshRootLane: (options) => syncAgent.refreshRootLane(options),\n // Force an on-demand local SQLite re-read (see the interface doc): arm the\n // gate refreshLocalContainerStates otherwise requires, which the runtime\n // auto-arms only on a context transition an on-demand caller cannot rely on.\n refreshLocalContainers: () => {\n state.localContainersNeedRefresh = true;\n return syncAgent.refreshLocalContainers();\n },\n requestSync: () => syncAgent.scheduleSync(),\n getCachedContainerWriterProjection: (containerId) =>\n getCachedContainerWriterProjectionForStore(state, containerId),\n getSnapshot: () => state.snapshot,\n subscribe: (listener) =>\n subscribeToContainerContentsStore(state, listener),\n updateRuntime: (runtime) =>\n updateContainerContentsStoreRuntime(state, runtime, syncAgent),\n },\n updateOptions: (nextOptions) =>\n applyContainerContentsStoreOptions(state, syncAgent, nextOptions),\n };\n}\n\nexport function createContainerContentsStore(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence = defaultContainerContentsPersistence,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStore {\n return createContainerContentsStoreEntry(initialRuntime, persistence, options)\n .store;\n}\n\nexport function getOrCreateContainerContentsStore(\n domainScope: DomainScope,\n runtime: ContainerContentsStoreRuntime,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStore {\n const existingEntry = containerContentsStoresByScope.get(domainScope);\n if (existingEntry) {\n existingEntry.updateOptions(options);\n return existingEntry.store;\n }\n\n const nextEntry = createContainerContentsStoreEntry(\n runtime,\n defaultContainerContentsPersistence,\n options,\n );\n containerContentsStoresByScope.set(domainScope, nextEntry);\n return nextEntry.store;\n}\n\n/**\n * Arm the next structural pass's document-priming scan for a domain scope.\n * Priming normally re-arms only on store creation and topology changes, so a\n * caller that just tore down a document's local state uses this to have the\n * still-listed server document re-created without waiting for an app\n * restart. Returns false when the scope has no container-contents store yet;\n * the startup priming pass covers that case.\n */\nexport function requestContainerContentsDocumentPriming(\n domainScope: DomainScope,\n): boolean {\n const entry = containerContentsStoresByScope.get(domainScope);\n if (!entry) {\n return false;\n }\n\n entry.requestDocumentPriming();\n return true;\n}\n"]}
1
+ {"version":3,"file":"containerContentsStore.js","sourceRoot":"","sources":["containerContentsStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kCAAkC,EAAE,MAAM,oEAAoE,CAAC;AACxH,OAAO,EAEL,mCAAmC,GACpC,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AACnF,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,qBAAqB,EACrB,aAAa,EACb,eAAe,GAChB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAC;AAC9D,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,2CAA2C,CAAC;AACtF,OAAO,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAC1E,OAAO,EACL,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,+BAA+B,EAAE,MAAM,kCAAkC,CAAC;AACnF,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAA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AmC,CAAC,KAAK,EAAE,OAAO,EAAE,SAAS,CAAC;SACjE;QACD,aAAa,EAAE,CAAC,WAAW,EAAE,EAAE,CAC7B,kCAAkC,CAAC,KAAK,EAAE,SAAS,EAAE,WAAW,CAAC;KACpE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,cAA6C,EAC7C,cAA4C,mCAAmC,EAC/E,UAAyC,EAAE;IAE3C,OAAO,iCAAiC,CAAC,cAAc,EAAE,WAAW,EAAE,OAAO,CAAC;SAC3E,KAAK,CAAC;AACX,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,WAAwB,EACxB,OAAsC,EACtC,UAAyC,EAAE;IAE3C,MAAM,aAAa,GAAG,8BAA8B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IACtE,IAAI,aAAa,EAAE,CAAC;QAClB,aAAa,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;QACrC,OAAO,aAAa,CAAC,KAAK,CAAC;IAC7B,CAAC;IAED,MAAM,SAAS,GAAG,iCAAiC,CACjD,OAAO,EACP,mCAAmC,EACnC,OAAO,CACR,CAAC;IACF,8BAA8B,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IAC3D,OAAO,SAAS,CAAC,KAAK,CAAC;AACzB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,uCAAuC,CACrD,WAAwB;IAExB,MAAM,KAAK,GAAG,8BAA8B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC9D,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,KAAK,CAAC;IACf,CAAC;IAED,KAAK,CAAC,sBAAsB,EAAE,CAAC;IAC/B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport { getCachedContainerWriterProjection } from \"../../workflows/container-contents/container-state/projectionCache\";\nimport {\n type ContainerContentsPersistence,\n defaultContainerContentsPersistence,\n} from \"../../workflows/container-contents/containerPersistence\";\nimport { persistContainerState } from \"./containerState/containerStatePersistence\";\nimport {\n createChildContainer,\n deleteContainer,\n ensureSystemContainer,\n moveContainer,\n renameContainer,\n} from \"./operations\";\nimport { emptyTrash } from \"./operations/emptyTrashOperation\";\nimport {\n prepareContainerGroupRewrap,\n verifyContainerGroupRewrapCurrent,\n} from \"./operations/groupRewrapOperation\";\nimport { purgeContainer } from \"./operations/purgeContainerOperation\";\nimport { chainPurgeAfterScopeMoves } from \"./operations/purgeMoveSettlementOperation\";\nimport { setContainerIcon } from \"./operations/setContainerIconOperation\";\nimport {\n shareContainerWithGroup,\n shareContainerWithUser,\n} from \"./operations/shareOperations\";\nimport { invalidateRemoteContainerWrites } from \"./remoteWrites/remoteWriteGuards\";\nimport { chainRemoteContainerTask } from \"./remoteWrites/remoteWriteQueue\";\nimport { captureContainerWriteGeneration } from \"./remoteWrites/writeGeneration\";\nimport {\n createContainerContentsStoreState,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStorePersistence,\n updateContainerContentsStoreRuntime,\n} from \"./state\";\nimport {\n type ContainerContentsStoreRuntime,\n type ContainerContentsStoreSyncAgent,\n createContainerContentsStoreSyncAgent,\n} from \"./syncAgent\";\nimport { findRootContainerState } from \"./systemContainers/systemContainerLookup\";\nimport type {\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerContentsStoreState,\n} from \"./types\";\n\nconst containerContentsStoresByScope = new WeakMap<\n DomainScope,\n ContainerContentsStoreEntry\n>();\n\ninterface ContainerContentsStoreEntry {\n requestDocumentPriming: () => void;\n store: ContainerContentsStore;\n updateOptions: (options: ContainerContentsStoreOptions) => void;\n}\n\nfunction applyContainerContentsStoreOptions(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n options: ContainerContentsStoreOptions,\n): void {\n if (\"logLabel\" in options) {\n state.logLabel = options.logLabel;\n }\n\n if (\"persistence\" in options) {\n updateContainerContentsStorePersistence(\n state,\n options.persistence ?? defaultContainerContentsPersistence,\n syncAgent,\n );\n }\n}\n\nfunction getCachedContainerWriterProjectionForStore(\n state: ContainerContentsStoreState,\n containerId: string,\n) {\n const containerState = state.containersById.get(containerId);\n return containerState\n ? getCachedContainerWriterProjection(containerState)\n : null;\n}\n\nfunction createContainerContentsStoreSyncHost(\n state: ContainerContentsStoreState,\n): Parameters<typeof createContainerContentsStoreSyncAgent>[0][\"host\"] {\n return {\n persistContainerState: (\n containerState,\n patch,\n updateView,\n saveOptions,\n mutationOptions,\n ) =>\n persistContainerState(state, containerState, {\n patch,\n updateView,\n saveOptions,\n ...mutationOptions,\n }),\n requestDocumentPriming: () => {\n state.documentStoresNeedPriming = true;\n },\n updateSnapshot: () => updateContainerContentsSnapshot(state),\n };\n}\n\n// null marks an unknown mutation scope; [] delegates invalidation to actual writes.\nfunction chainContainerWrite(\n state: ContainerContentsStoreState,\n work: (isCurrent: () => boolean) => ContainerContentsStoreState[\"writeChain\"],\n changedIds: readonly string[] | null = null,\n movedId?: string,\n): ContainerContentsStoreState[\"writeChain\"] {\n const isCurrent = captureContainerWriteGeneration(state);\n invalidateRemoteContainerWrites(state, changedIds, movedId);\n state.writeChain = state.writeChain\n .catch(() => null)\n .then(() => {\n if (!isCurrent()) return null;\n invalidateRemoteContainerWrites(state, changedIds, movedId);\n return work(isCurrent);\n })\n .then((node) => (isCurrent() ? node : null));\n return state.writeChain;\n}\n\ntype ContainerWriteMethods = Pick<\n ContainerContentsStore,\n | \"createChild\"\n | \"deleteContainer\"\n | \"emptyTrash\"\n | \"ensureSystemContainer\"\n | \"moveContainer\"\n | \"prepareGroupRewrap\"\n | \"purgeContainer\"\n | \"renameContainer\"\n | \"setContainerIcon\"\n | \"shareWithGroup\"\n | \"shareWithUser\"\n>;\n\n// The group-rewrap builder verifies any required existing grant before capturing\n// the container KEK, then returns a check/rewrap pair. A verified non-match is\n// distinct from an unavailable preparation so security-critical callers can\n// no-op unrelated groups without failing open for a real grant.\nfunction createPrepareGroupRewrapMethod(\n state: ContainerContentsStoreState,\n syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>,\n): ContainerContentsStore[\"prepareGroupRewrap\"] {\n return async (containerId, groupId, accessLevel, options) => {\n const preparation = await chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n (isCurrent) =>\n prepareContainerGroupRewrap(\n state,\n containerId,\n groupId,\n accessLevel,\n options,\n isCurrent,\n ),\n containerId,\n );\n return preparation?.status === \"prepared\"\n ? {\n isCurrent: (\n expectedGroupHead,\n expectedContainerId,\n expectedOrganizationId,\n ) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n verifyContainerGroupRewrapCurrent(\n state,\n containerId,\n groupId,\n accessLevel,\n expectedGroupHead,\n expectedContainerId,\n expectedOrganizationId,\n isCurrent,\n ),\n containerId,\n ),\n rewrap: () =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithGroup(\n state,\n syncAgent,\n containerId,\n groupId,\n accessLevel,\n {\n ...options,\n knownContainerKeks: preparation.knownContainerKeks,\n // A prepared re-wrap is grant-preserving by definition, so\n // it never mints a grant and never needs the chosen name.\n requireExistingGrant: true,\n },\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n status: \"prepared\" as const,\n }\n : (preparation ?? null);\n };\n}\n\nfunction createContainerSharingMethods(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): Pick<ContainerWriteMethods, \"shareWithUser\" | \"shareWithGroup\"> {\n return {\n shareWithUser: (containerId, userId) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithUser(\n state,\n syncAgent,\n containerId,\n userId,\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n shareWithGroup: (containerId, groupId, accessLevel, options) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithGroup(\n state,\n syncAgent,\n containerId,\n groupId,\n accessLevel,\n options,\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n };\n}\n\nfunction createDeleteContainerMethod(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): ContainerContentsStore[\"deleteContainer\"] {\n return (containerId) => {\n const current = captureContainerWriteGeneration(state);\n const remoteDelete = () =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n (isCurrent) =>\n deleteContainer(state, syncAgent, containerId, isCurrent),\n containerId,\n ).then((node) => node !== null);\n if (state.containersById.get(containerId)?.record.documentId)\n return remoteDelete();\n let promoted = false;\n return chainContainerWrite(\n state,\n (isCurrent) => {\n // Promotion can win while this local operation was queued. Hand it to\n // the remote queue after releasing the local chain, before any HTTP I/O.\n promoted = Boolean(\n state.containersById.get(containerId)?.record.documentId,\n );\n return promoted\n ? Promise.resolve(null)\n : deleteContainer(state, syncAgent, containerId, isCurrent);\n },\n [containerId],\n ).then((node) => (promoted && current() ? remoteDelete() : node !== null));\n };\n}\n\nfunction createEnsureSystemContainerMethod(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): ContainerContentsStore[\"ensureSystemContainer\"] {\n return (systemSlot, name, options) => {\n const work = (isCurrent: () => boolean) =>\n ensureSystemContainer(\n state,\n syncAgent,\n systemSlot,\n name,\n options,\n isCurrent,\n );\n const rootId = findRootContainerState(state)?.container.id;\n return options?.deferRemoteBootstrap\n ? chainContainerWrite(state, work, [])\n : chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n work,\n rootId ? { rootId, systemSlot } : undefined,\n );\n };\n}\n\nexport function createContainerWriteMethods(\n state: ContainerContentsStoreState,\n syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>,\n): ContainerWriteMethods {\n return {\n ...createContainerSharingMethods(state, syncAgent),\n createChild: (parentId, name) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n createChildContainer(state, syncAgent, parentId, name, isCurrent),\n [parentId],\n ),\n deleteContainer: createDeleteContainerMethod(state, syncAgent),\n purgeContainer: (containerId, options) =>\n chainPurgeAfterScopeMoves(\n state,\n syncAgent,\n containerId,\n options,\n (isCurrent) =>\n purgeContainer(state, syncAgent, containerId, options, isCurrent),\n ),\n emptyTrash: (trashContainerId, options) =>\n chainPurgeAfterScopeMoves(\n state,\n syncAgent,\n trashContainerId,\n options,\n (isCurrent) =>\n emptyTrash(state, syncAgent, trashContainerId, options, isCurrent),\n ),\n ensureSystemContainer: createEnsureSystemContainerMethod(state, syncAgent),\n moveContainer: (containerId, parentId) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n moveContainer(state, syncAgent, containerId, parentId, isCurrent),\n [containerId, parentId],\n containerId,\n ),\n prepareGroupRewrap: createPrepareGroupRewrapMethod(state, syncAgent),\n renameContainer: (containerId, name) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n renameContainer(state, syncAgent, containerId, name, isCurrent),\n [containerId],\n ),\n setContainerIcon: (containerId, icon) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n setContainerIcon(state, syncAgent, containerId, icon, isCurrent),\n [containerId],\n ),\n };\n}\n\nfunction createContainerContentsStoreEntry(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence = defaultContainerContentsPersistence,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStoreEntry {\n const state = createContainerContentsStoreState(\n initialRuntime,\n options.persistence ?? persistence,\n options.logLabel,\n );\n const syncAgent = createContainerContentsStoreSyncAgent({\n host: createContainerContentsStoreSyncHost(state),\n state,\n });\n const writeMethods = createContainerWriteMethods(state, syncAgent);\n\n return {\n requestDocumentPriming: () => {\n state.documentStoresNeedPriming = true;\n syncAgent.scheduleSync();\n },\n store: {\n ...writeMethods,\n refresh: () => syncAgent.refresh({ resetAllLaneWatermarks: true }),\n refreshRootLane: (options) => syncAgent.refreshRootLane(options),\n // Force an on-demand local SQLite re-read (see the interface doc): arm the\n // gate refreshLocalContainerStates otherwise requires, which the runtime\n // auto-arms only on a context transition an on-demand caller cannot rely on.\n refreshLocalContainers: () => {\n state.localContainersNeedRefresh = true;\n return syncAgent.refreshLocalContainers();\n },\n requestSync: () => syncAgent.scheduleSync(),\n getCachedContainerWriterProjection: (containerId) =>\n getCachedContainerWriterProjectionForStore(state, containerId),\n getSnapshot: () => state.snapshot,\n subscribe: (listener) =>\n subscribeToContainerContentsStore(state, listener),\n updateRuntime: (runtime) =>\n updateContainerContentsStoreRuntime(state, runtime, syncAgent),\n },\n updateOptions: (nextOptions) =>\n applyContainerContentsStoreOptions(state, syncAgent, nextOptions),\n };\n}\n\nexport function createContainerContentsStore(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence = defaultContainerContentsPersistence,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStore {\n return createContainerContentsStoreEntry(initialRuntime, persistence, options)\n .store;\n}\n\nexport function getOrCreateContainerContentsStore(\n domainScope: DomainScope,\n runtime: ContainerContentsStoreRuntime,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStore {\n const existingEntry = containerContentsStoresByScope.get(domainScope);\n if (existingEntry) {\n existingEntry.updateOptions(options);\n return existingEntry.store;\n }\n\n const nextEntry = createContainerContentsStoreEntry(\n runtime,\n defaultContainerContentsPersistence,\n options,\n );\n containerContentsStoresByScope.set(domainScope, nextEntry);\n return nextEntry.store;\n}\n\n/**\n * Arm the next structural pass's document-priming scan for a domain scope.\n * Priming normally re-arms only on store creation and topology changes, so a\n * caller that just tore down a document's local state uses this to have the\n * still-listed server document re-created without waiting for an app\n * restart. Returns false when the scope has no container-contents store yet;\n * the startup priming pass covers that case.\n */\nexport function requestContainerContentsDocumentPriming(\n domainScope: DomainScope,\n): boolean {\n const entry = containerContentsStoresByScope.get(domainScope);\n if (!entry) {\n return false;\n }\n\n entry.requestDocumentPriming();\n return true;\n}\n"]}
@@ -1,4 +1,4 @@
1
- export type { PurgeOptions, PurgeProgress, } from "../../workflows/container-contents/container-state/purge/purgeProgress.js";
1
+ export type { PurgeMoveSettlement, PurgeOptions, PurgeProgress, } from "../../workflows/container-contents/container-state/purge/purgeProgress.js";
2
2
  export * from "./containerContentsStore.js";
3
3
  export { isAutomaticRootCatchupContainerNode, isForeignSystemContainerNode, isReconcilableContainerNode, isRemoteBackedContainerNode, isSystemContainerNode, } from "./containerState/reconcilableContainer.js";
4
4
  export * from "./state.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,cAAc,0BAA0B,CAAC;AACzC,OAAO,EACL,mCAAmC,EACnC,4BAA4B,EAC5B,2BAA2B,EAC3B,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,wCAAwC,CAAC;AAChD,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC;AAC5B,cAAc,SAAS,CAAC","sourcesContent":["export type {\n PurgeOptions,\n PurgeProgress,\n} from \"../../workflows/container-contents/container-state/purge/purgeProgress\";\nexport * from \"./containerContentsStore\";\nexport {\n isAutomaticRootCatchupContainerNode,\n isForeignSystemContainerNode,\n isReconcilableContainerNode,\n isRemoteBackedContainerNode,\n isSystemContainerNode,\n} from \"./containerState/reconcilableContainer\";\nexport * from \"./state\";\nexport * from \"./syncAgent\";\nexport * from \"./types\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAKA,cAAc,0BAA0B,CAAC;AACzC,OAAO,EACL,mCAAmC,EACnC,4BAA4B,EAC5B,2BAA2B,EAC3B,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,wCAAwC,CAAC;AAChD,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC;AAC5B,cAAc,SAAS,CAAC","sourcesContent":["export type {\n PurgeMoveSettlement,\n PurgeOptions,\n PurgeProgress,\n} from \"../../workflows/container-contents/container-state/purge/purgeProgress\";\nexport * from \"./containerContentsStore\";\nexport {\n isAutomaticRootCatchupContainerNode,\n isForeignSystemContainerNode,\n isReconcilableContainerNode,\n isRemoteBackedContainerNode,\n isSystemContainerNode,\n} from \"./containerState/reconcilableContainer\";\nexport * from \"./state\";\nexport * from \"./syncAgent\";\nexport * from \"./types\";\n"]}
@@ -0,0 +1,71 @@
1
+ import { settlePurgeScopeMoves } from "../../../workflows/container-contents/container-state/purge/purgeMoveSettlement.js";
2
+ import { readContainerContentsSyncLane } from "../../../workflows/container-contents/syncLane.js";
3
+ import { trackRemoteContainerWrite } from "../remoteWrites/remoteWriteGuards.js";
4
+ import { chainRemoteContainerTask } from "../remoteWrites/remoteWriteQueue.js";
5
+ import { captureContainerWriteGeneration, } from "../remoteWrites/writeGeneration.js";
6
+ function reportPurgeMoveSettlement(state, message, error) {
7
+ const { log, logError } = state.runtime.util;
8
+ try {
9
+ // A host logger that throws or rejects must not change the purge result.
10
+ if (logError)
11
+ void Promise.resolve(logError(message, error)).catch(() => { });
12
+ else
13
+ log(message);
14
+ }
15
+ catch {
16
+ // Hosts may throw synchronously or return a rejected promise.
17
+ }
18
+ }
19
+ /**
20
+ * Delete Forever and Empty Trash often follow a Move to Trash within seconds,
21
+ * before its sync pass reaches the server. Wait for the scope's queued moves
22
+ * before joining the remote write queue, so the wait holds up no other remote
23
+ * task. The purge keeps its own readiness and online gates.
24
+ *
25
+ * The purge's own guards start only when it runs, so the selection is guarded
26
+ * from the click instead: a local edit in the subtree, or a new identity or
27
+ * database, cancels the purge, and it starts only while the selected folder
28
+ * still sits where it was selected, whichever device moved it.
29
+ */
30
+ export async function chainPurgeAfterScopeMoves(state, syncAgent, containerId, options, purge) {
31
+ const runtime = state.runtime;
32
+ if (runtime.infra.dbStatus !== "ready" ||
33
+ !state.snapshot.ready ||
34
+ !runtime.auth.isAuthenticated ||
35
+ !runtime.state.online ||
36
+ !state.containersById.has(containerId)) {
37
+ return chainRemoteContainerTask(state, syncAgent, false, purge, containerId);
38
+ }
39
+ const writeCurrent = captureContainerWriteGeneration(state);
40
+ const tracked = trackRemoteContainerWrite(state, containerId);
41
+ const selectedParentId = state.containersById.get(containerId)?.container.parentId;
42
+ const selectionCurrent = () => writeCurrent() && !tracked.changed();
43
+ const placementCurrent = () => state.containersById.get(containerId)?.container.parentId ===
44
+ selectedParentId;
45
+ try {
46
+ const domainScope = runtime.state.domainScope;
47
+ const settlement = await settlePurgeScopeMoves({
48
+ containersById: state.containersById,
49
+ execSql: runtime.infra.execSql,
50
+ lane: {
51
+ read: () => readContainerContentsSyncLane(domainScope),
52
+ request: () => syncAgent.scheduleSync(),
53
+ },
54
+ onMoveSettlement: options?.onMoveSettlement,
55
+ persistence: state.persistence,
56
+ report: (message, error) => reportPurgeMoveSettlement(state, message, error),
57
+ rootContainerId: containerId,
58
+ signal: options?.signal,
59
+ stillCurrent: () => selectionCurrent() && placementCurrent(),
60
+ });
61
+ if (settlement !== "settled" || !selectionCurrent())
62
+ return false;
63
+ return await chainRemoteContainerTask(state, syncAgent, false, (isCurrent) => selectionCurrent() && placementCurrent()
64
+ ? purge(() => isCurrent() && selectionCurrent())
65
+ : Promise.resolve(false), containerId);
66
+ }
67
+ finally {
68
+ tracked.dispose();
69
+ }
70
+ }
71
+ //# sourceMappingURL=purgeMoveSettlementOperation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"purgeMoveSettlementOperation.js","sourceRoot":"","sources":["purgeMoveSettlementOperation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,iFAAiF,CAAC;AAExH,OAAO,EAAE,6BAA6B,EAAE,MAAM,gDAAgD,CAAC;AAC/F,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,OAAO,EAEL,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AAIzC,SAAS,yBAAyB,CAChC,KAAkC,EAClC,OAAe,EACf,KAAY;IAEZ,MAAM,EAAE,GAAG,EAA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C,OAAO,EAAE,CAAC;IACpB,CAAC;AACH,CAAC","sourcesContent":["import { settlePurgeScopeMoves } from \"../../../workflows/container-contents/container-state/purge/purgeMoveSettlement\";\nimport type { PurgeOptions } from \"../../../workflows/container-contents/container-state/purge/purgeProgress\";\nimport { readContainerContentsSyncLane } from \"../../../workflows/container-contents/syncLane\";\nimport { trackRemoteContainerWrite } from \"../remoteWrites/remoteWriteGuards\";\nimport { chainRemoteContainerTask } from \"../remoteWrites/remoteWriteQueue\";\nimport {\n type ContainerWriteGuard,\n captureContainerWriteGeneration,\n} from \"../remoteWrites/writeGeneration\";\nimport type { ContainerContentsStoreSyncAgent } from \"../syncAgent\";\nimport type { ContainerContentsStoreState } from \"../types\";\n\nfunction reportPurgeMoveSettlement(\n state: ContainerContentsStoreState,\n message: string,\n error: Error,\n): void {\n const { log, logError } = state.runtime.util;\n try {\n // A host logger that throws or rejects must not change the purge result.\n if (logError)\n void Promise.resolve(logError(message, error)).catch(() => {});\n else log(message);\n } catch {\n // Hosts may throw synchronously or return a rejected promise.\n }\n}\n\n/**\n * Delete Forever and Empty Trash often follow a Move to Trash within seconds,\n * before its sync pass reaches the server. Wait for the scope's queued moves\n * before joining the remote write queue, so the wait holds up no other remote\n * task. The purge keeps its own readiness and online gates.\n *\n * The purge's own guards start only when it runs, so the selection is guarded\n * from the click instead: a local edit in the subtree, or a new identity or\n * database, cancels the purge, and it starts only while the selected folder\n * still sits where it was selected, whichever device moved it.\n */\nexport async function chainPurgeAfterScopeMoves(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n containerId: string,\n options: PurgeOptions | undefined,\n purge: (isCurrent: ContainerWriteGuard) => Promise<boolean>,\n): Promise<boolean> {\n const runtime = state.runtime;\n if (\n runtime.infra.dbStatus !== \"ready\" ||\n !state.snapshot.ready ||\n !runtime.auth.isAuthenticated ||\n !runtime.state.online ||\n !state.containersById.has(containerId)\n ) {\n return chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n purge,\n containerId,\n );\n }\n const writeCurrent = captureContainerWriteGeneration(state);\n const tracked = trackRemoteContainerWrite(state, containerId);\n const selectedParentId =\n state.containersById.get(containerId)?.container.parentId;\n const selectionCurrent = () => writeCurrent() && !tracked.changed();\n const placementCurrent = () =>\n state.containersById.get(containerId)?.container.parentId ===\n selectedParentId;\n try {\n const domainScope = runtime.state.domainScope;\n const settlement = await settlePurgeScopeMoves({\n containersById: state.containersById,\n execSql: runtime.infra.execSql,\n lane: {\n read: () => readContainerContentsSyncLane(domainScope),\n request: () => syncAgent.scheduleSync(),\n },\n onMoveSettlement: options?.onMoveSettlement,\n persistence: state.persistence,\n report: (message, error) =>\n reportPurgeMoveSettlement(state, message, error),\n rootContainerId: containerId,\n signal: options?.signal,\n stillCurrent: () => selectionCurrent() && placementCurrent(),\n });\n if (settlement !== \"settled\" || !selectionCurrent()) return false;\n return await chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n selectionCurrent() && placementCurrent()\n ? purge(() => isCurrent() && selectionCurrent())\n : Promise.resolve(false),\n containerId,\n );\n } finally {\n tracked.dispose();\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { bytesToBase64 } from "../../../../internal/encoding/index.js";
2
2
  import { encodeVersionVector, exportFullHistorySnapshot, } from "../../../../internal/loro/index.js";
3
- import { readPullContinuation } from "../../../../data/documents/shared/syncPagination.js";
3
+ import { readPullContinuation } from "../../../../data/documents/shared/sync/syncPagination.js";
4
4
  import { persistDocument } from "../persistence.js";
5
5
  import { isDocumentStoreSyncGenerationCurrent, } from "../sync/syncGeneration.js";
6
6
  import { installDocumentWriterProjection } from "../writerProjectionGeneration.js";
@@ -1 +1 @@
1
- {"version":3,"file":"historyRebuild.js","sourceRoot":"","sources":["historyRebuild.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CA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BAA0B,KAAK,IAAI;YAC7C,SAAS,CAAC,sBAAsB,KAAK,IAAI;YACzC,SAAS,CAAC,MAAM,CAAC,gBAAgB,IAAI,IAAI;YACzC,SAAS,CAAC,MAAM,CAAC,gCAAgC,KAAK,IAAI;KAC7D,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport { readPullContinuation } from \"../../../../data/documents/shared/syncPagination\";\nimport type {\n DocumentSyncPullContinuation,\n syncRemoteDocument,\n} from \"../../../../workflows/documents\";\nimport { persistDocument } from \"../persistence\";\nimport type { DocumentState, DocumentStoreState } from \"../state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\n\n/**\n * Machinery for reconstructing a full-history document from a verified remote\n * pull. Used by the rotation preflight (rotation.ts): it pulls the remote op\n * log, replays it into a fresh document alongside the durable local queue,\n * and installs the rebuilt document — preserving op identity end to end.\n */\n\nexport async function installRebuiltDocument(input: {\n consumedPullContinuation: DocumentSyncPullContinuation | null;\n currentRecord: NonNullable<DocumentStoreState[\"record\"]>;\n generation: DocumentStoreSyncGeneration;\n rebuiltDoc: DocumentState;\n state: DocumentStoreState;\n synced: NonNullable<Awaited<ReturnType<typeof syncRemoteDocument>>>;\n /** `state.writerProjectionGeneration` when the recovery pull started. */\n writerProjectionGeneration: number;\n}): Promise<{\n fullHistorySnapshot: Uint8Array;\n settlementRequiresRetry: boolean;\n}> {\n // The guarded persist makes the recovered history durable BEFORE publishing\n // the newer record. Checkpoint-ahead is the safe crash direction: restore\n // reads the checkpoint and the record catches up on the next persist.\n const fullHistorySnapshot = exportFullHistorySnapshot(input.rebuiltDoc);\n const rebuiltEndVersion = encodeVersionVector(input.rebuiltDoc);\n const persisted = await persistDocument(\n input.state,\n input.rebuiltDoc,\n {\n ...input.synced.persistedState,\n lastCommitLsn:\n input.synced.response.commitLsn ??\n input.currentRecord.lastCommitLsn ??\n null,\n pullContinuation: readPullContinuation(input.synced.response),\n recoveryGeneration: (input.currentRecord.recoveryGeneration ?? 0) + 1,\n // The guarded checkpoint below covers exactly this frontier.\n snapshotEndVersion: rebuiltEndVersion,\n },\n {\n acceptedPendingUpdateIds: input.synced.settledPendingUpdateIds,\n expectedSyncState: {\n pullContinuation: input.consumedPullContinuation,\n record: input.currentRecord,\n },\n historyCheckpoint: {\n coveredTailIds: [],\n endVersionVector: rebuiltEndVersion,\n pruneCoveredLocalState: true,\n snapshot: bytesToBase64(fullHistorySnapshot),\n },\n pendingBaseVersionOverride: rebuiltEndVersion,\n preserveSnapshotStructuredFields: input.state.pendingLocalWrites > 0,\n preserveSnapshotText: input.state.pendingLocalWrites > 0,\n },\n input.generation,\n );\n if (!persisted) {\n if (!isDocumentStoreSyncGenerationCurrent(input.state, input.generation)) {\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n // The resurrect guard refused: another subsystem deleted this document\n // while the rebuild was in flight, and saveDocumentRecord cleared the\n // zombie store — pendingBaseVersion included. Restoring the rebuilt doc,\n // projection, or the captured base version here would resurrect state\n // over that clearing.\n throw new Error(\n \"Document was deleted while its history rebuild was in flight\",\n );\n }\n if (\n !persisted.pullContinuationSuperseded &&\n !persisted.syncIdentitySuperseded\n ) {\n input.state.pendingBaseVersion = rebuiltEndVersion;\n input.state.doc = input.rebuiltDoc;\n }\n if (persisted.pullContinuationSuperseded) input.state.writerProjection = null;\n else\n installDocumentWriterProjection(\n input.state,\n input.synced.writerProjection ?? input.state.writerProjection,\n input.writerProjectionGeneration,\n );\n const installedDoc = input.state.doc ?? input.rebuiltDoc;\n return {\n fullHistorySnapshot: persisted.pullContinuationSuperseded\n ? exportFullHistorySnapshot(installedDoc)\n : fullHistorySnapshot,\n settlementRequiresRetry:\n persisted.pullContinuationSuperseded === true ||\n persisted.syncIdentitySuperseded === true ||\n persisted.record.pullContinuation != null ||\n persisted.record.pullContinuationRecoveryRequired === true,\n };\n}\n"]}
1
+ {"version":3,"file":"historyRebuild.js","sourceRoot":"","sources":["historyRebuild.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,oBAAoB,EAAE,MAAM,uDAAuD,CAAC;AAK7F,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAEjD,OAAO,EAEL,oCAAoC,GACrC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAEhF;;;;;GAKG;AAEH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,KAS5C;IAIC,4EAA4E;IAC5E,0EAA0E;IAC1E,sEAAsE;IACtE,MAAM,mBAAmB,GAAG,yBAAyB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACxE,MAAM,iBAAiB,GAAG,mBAAmB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAChE,MAAM,SAAS,GAAG,MAAM,eAAe,CACrC,KAAK,CAAC,KAAK,EACX,KAAK,CAAC,UAAU,EAChB;QACE,GAAG,KAAK,CAAC,MAAM,CAAC,cAAc;QAC9B,aAAa,EACX,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS;YAC/B,KAAK,CAAC,aAAa,CAAC,aAAa;YACjC,IAAI;QACN,gBAAgB,EAAE,oBAAoB,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC;QAC7D,kBAAkB,EAAE,CAAC,KAAK,CAAC,aAAa,CAAC,kBAAkB,IAAI,CAAC,CAAC,GAAG,CAAC;QACrE,6DAA6D;QAC7D,kBAAkB,EAAE,iBAAiB;KACtC,EACD;QACE,wBAAwB,EAAE,KAAK,CAAC,MAAM,CAAC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BAA0B,CACjC,CAAC;IACJ,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,IAAI,KAAK,CAAC,UAAU,CAAC;IACzD,OAAO;QACL,mBAAmB,EAAE,SAAS,CAAC,0BAA0B;YACvD,CAAC,CAAC,yBAAyB,CAAC,YAAY,CAAC;YACzC,CAAC,CAAC,mBAAmB;QACvB,uBAAuB,EACrB,SAAS,CAAC,0BAA0B,KAAK,IAAI;YAC7C,SAAS,CAAC,sBAAsB,KAAK,IAAI;YACzC,SAAS,CAAC,MAAM,CAAC,gBAAgB,IAAI,IAAI;YACzC,SAAS,CAAC,MAAM,CAAC,gCAAgC,KAAK,IAAI;KAC7D,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport { readPullContinuation } from \"../../../../data/documents/shared/sync/syncPagination\";\nimport type {\n DocumentSyncPullContinuation,\n syncRemoteDocument,\n} from \"../../../../workflows/documents\";\nimport { persistDocument } from \"../persistence\";\nimport type { DocumentState, DocumentStoreState } from \"../state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\n\n/**\n * Machinery for reconstructing a full-history document from a verified remote\n * pull. Used by the rotation preflight (rotation.ts): it pulls the remote op\n * log, replays it into a fresh document alongside the durable local queue,\n * and installs the rebuilt document — preserving op identity end to end.\n */\n\nexport async function installRebuiltDocument(input: {\n consumedPullContinuation: DocumentSyncPullContinuation | null;\n currentRecord: NonNullable<DocumentStoreState[\"record\"]>;\n generation: DocumentStoreSyncGeneration;\n rebuiltDoc: DocumentState;\n state: DocumentStoreState;\n synced: NonNullable<Awaited<ReturnType<typeof syncRemoteDocument>>>;\n /** `state.writerProjectionGeneration` when the recovery pull started. */\n writerProjectionGeneration: number;\n}): Promise<{\n fullHistorySnapshot: Uint8Array;\n settlementRequiresRetry: boolean;\n}> {\n // The guarded persist makes the recovered history durable BEFORE publishing\n // the newer record. Checkpoint-ahead is the safe crash direction: restore\n // reads the checkpoint and the record catches up on the next persist.\n const fullHistorySnapshot = exportFullHistorySnapshot(input.rebuiltDoc);\n const rebuiltEndVersion = encodeVersionVector(input.rebuiltDoc);\n const persisted = await persistDocument(\n input.state,\n input.rebuiltDoc,\n {\n ...input.synced.persistedState,\n lastCommitLsn:\n input.synced.response.commitLsn ??\n input.currentRecord.lastCommitLsn ??\n null,\n pullContinuation: readPullContinuation(input.synced.response),\n recoveryGeneration: (input.currentRecord.recoveryGeneration ?? 0) + 1,\n // The guarded checkpoint below covers exactly this frontier.\n snapshotEndVersion: rebuiltEndVersion,\n },\n {\n acceptedPendingUpdateIds: input.synced.settledPendingUpdateIds,\n expectedSyncState: {\n pullContinuation: input.consumedPullContinuation,\n record: input.currentRecord,\n },\n historyCheckpoint: {\n coveredTailIds: [],\n endVersionVector: rebuiltEndVersion,\n pruneCoveredLocalState: true,\n snapshot: bytesToBase64(fullHistorySnapshot),\n },\n pendingBaseVersionOverride: rebuiltEndVersion,\n preserveSnapshotStructuredFields: input.state.pendingLocalWrites > 0,\n preserveSnapshotText: input.state.pendingLocalWrites > 0,\n },\n input.generation,\n );\n if (!persisted) {\n if (!isDocumentStoreSyncGenerationCurrent(input.state, input.generation)) {\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n // The resurrect guard refused: another subsystem deleted this document\n // while the rebuild was in flight, and saveDocumentRecord cleared the\n // zombie store — pendingBaseVersion included. Restoring the rebuilt doc,\n // projection, or the captured base version here would resurrect state\n // over that clearing.\n throw new Error(\n \"Document was deleted while its history rebuild was in flight\",\n );\n }\n if (\n !persisted.pullContinuationSuperseded &&\n !persisted.syncIdentitySuperseded\n ) {\n input.state.pendingBaseVersion = rebuiltEndVersion;\n input.state.doc = input.rebuiltDoc;\n }\n if (persisted.pullContinuationSuperseded) input.state.writerProjection = null;\n else\n installDocumentWriterProjection(\n input.state,\n input.synced.writerProjection ?? input.state.writerProjection,\n input.writerProjectionGeneration,\n );\n const installedDoc = input.state.doc ?? input.rebuiltDoc;\n return {\n fullHistorySnapshot: persisted.pullContinuationSuperseded\n ? exportFullHistorySnapshot(installedDoc)\n : fullHistorySnapshot,\n settlementRequiresRetry:\n persisted.pullContinuationSuperseded === true ||\n persisted.syncIdentitySuperseded === true ||\n persisted.record.pullContinuation != null ||\n persisted.record.pullContinuationRecoveryRequired === true,\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,0BAA0B,EAC1B,uBAAuB,GAExB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,yCAAyC,CAAC;AAIjD,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAGL,uCAAuC,EAOvC,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,kCAAkC,CAAC;AAgJ1C,MAAM,uBAAuB,GAAqB;IAChD,WAAW,EAAE,EAAE;IACf,wBAAwB,EAAE,EAAE;IAC5B,4BAA4B,EAAE,EAAE;IAChC,SAAS,EAAE,KAAK;IAChB,QAAQ,EAAE,IAAI;IACd,eAAe,EAAE,IAAI;IACrB,UAAU,EAAE,IAAI;IAChB,YAAY,EAAE,qBAAqB;IACnC,oBAAoB,EAAE,OAAO;IAC7B,qBAAqB,EAAE,EAAE;IACzB,KAAK,EAAE,KAAK;IACZ,IAAI,EAAE,EAAE;IACR,gBAAgB,EAAE,EAAE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,QAAQ,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import type { createDocument } from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport {\n type DocumentAttachment,\n getDocumentAttachments,\n sameDocumentAttachments,\n} from \"../../../data/documents/documentContent\";\nimport {\n projectStoredDocumentState,\n readStoredDocumentState,\n type StoredDocumentKind,\n} from \"../../../data/documents/documentKinds\";\nimport {\n type DocumentRow,\n listDocumentRows,\n sameDocumentRows,\n} from \"../../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport type { DocumentSyncPullContinuation } from \"../../../data/documents/shared/syncPagination\";\nimport type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/types\";\nimport {\n canWriteEffectiveAccessLevel,\n normalizeEffectiveAccessLevel,\n} from \"../../../data/keying/accessLevel\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionUserKeyResolver,\n type DocumentRecord,\n type DocumentSyncLane,\n type DocumentsPersistence,\n type PendingAttachmentRecord,\n type PendingUpdateInsert,\n resolveDocumentCreateAuthor,\n} from \"../../../workflows/documents\";\nimport type { DocumentSnapshot, DocumentsRuntime } from \"../types\";\nimport {\n getAttachmentStatuses,\n getAttachmentStorageKeys,\n} from \"./attachments/attachmentSnapshot\";\nexport type DocumentState = Awaited<ReturnType<typeof createDocument>>;\nexport type EncapsulationKeyPair = NonNullable<\n DocumentsRuntime[\"crypto\"][\"encapsulationKeyPair\"]\n>;\nexport type DocumentAttachmentBinding = NonNullable<\n Awaited<ReturnType<DocumentsRuntime[\"apiClient\"][\"listDocumentAttachments\"]>>\n>[number];\nexport type PendingMutationSyncResult = {\n completed: boolean;\n nextRecord: DocumentRecord;\n};\nexport interface PersistedDocumentRecord {\n creationSuperseded?: true;\n historyRestoreState?:\n | Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n | undefined;\n pullContinuationSuperseded?: true;\n record: DocumentRecord;\n syncIdentitySuperseded?: true;\n updatedAt?: string | undefined;\n}\nexport interface SaveDocumentRecordOptions {\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedSyncState?:\n | {\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord;\n }\n | undefined;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: Omit<PendingUpdateInsert, \"localId\"> | undefined;\n pendingBaseVersionOverride?: string | null | undefined;\n preserveSnapshotStructuredFields?: boolean | undefined;\n preserveSnapshotText?: boolean | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\nexport interface DocumentSyncAttempt {\n consumedPullContinuation: DocumentSyncPullContinuation | null;\n outgoingUpdateCount: number;\n requestRecord: DocumentRecord;\n synced: SyncRemoteDocumentResult;\n /** `writerProjectionGeneration` when the request left; gates the install. */\n writerProjectionGeneration: number;\n}\nexport interface DocumentStorePersistenceEffects {\n emitPersistedDocument: (\n domainScope: DomainScope,\n persistedDocument: DocumentSummary,\n placementChanged?: boolean | undefined,\n ) => void;\n registerDocumentIdentity: (\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n ) => void;\n}\nexport interface DocumentStoreState {\n attachmentBlobIdBySlotId: Record<string, string | null>;\n /** Plaintext digest of the held bytes per slot; see `getAttachmentStatuses`. */\n attachmentContentSha256BySlotId: Record<string, string>;\n attachmentStorageKeyBySlotId: Record<string, string>;\n /** Creation's birth rides the first attach; see `deferredInitialUpdate.ts`. */\n deferInitialUpdate?: boolean;\n doc: DocumentState | null;\n effects: DocumentStorePersistenceEffects;\n initialDocumentId: string | null;\n initialDocumentKind: StoredDocumentKind;\n initialText: string;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n lastEventCount: number;\n /** Invalidates queued local-write closures when this store is cleared. */\n localWriteGeneration: number;\n locallyAcceptedUpdateIds: Set<string>;\n localId: string;\n listeners: Set<() => void>;\n pendingAttachments: PendingAttachmentRecord[];\n /**\n * Oplog version through which every op in `doc` is already durably enqueued as\n * a pending update or synced from a remote peer. It advances only after an\n * edit's enqueue+persist succeeds, so a later edit can recover any orphaned\n * delta left by a failed write instead of silently dropping it from sync.\n * `null` only before initialization sets it to the loaded doc's version.\n */\n pendingBaseVersion: string | null;\n /**\n * Local text/structured writes queued on `writeChain` but not yet drained.\n * While positive, sync MUST preserve the optimistic text/fields because `doc`\n * can lag the latest keystroke. Remote merges remain in `doc` and publish when\n * the final write settles.\n */\n pendingLocalWrites: number;\n persistence: DocumentsPersistence;\n /**\n * Durable continuation for a bounded remote pull, mirrored from the document\n * record so the live lane can advance it without re-reading SQLite.\n */\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord | null;\n /** Served bindings hydration refused for a held copy; see `hydrate.ts`. */\n rejectedServedAttachmentBindings: Set<string>;\n /**\n * Consecutive completed sync passes that re-keyed conflicted pending updates\n * without settling anything. Bounds the rekey-driven self re-arm so a server\n * that keeps conflicting fresh ids cannot drive a network-speed loop; see\n * shouldReArmAfterOutgoingSettlement.\n */\n rekeyOnlyPassCount: number;\n resolveProjectionUserKey: DocumentProjectionUserKeyResolver;\n /** Latest remote-update sequence durably applied by a completed probe. */\n remoteUpdateCompletedSignalSeq: number;\n /** A cancelled remote-only owner blocks late responses until fresh work. */\n remoteSyncBlocked: boolean;\n scheduleStartupRemoteSync: boolean;\n remoteUpdatePending: boolean;\n /** Sequence used to keep an older pass from clearing a newer remote event. */\n remoteUpdateSignalSeq: number;\n runtime: DocumentsRuntime;\n snapshot: DocumentSnapshot;\n syncLane: DocumentSyncLane | null;\n /** Parked behind another member's ancestor repair; a path hint re-runs. */\n awaitingAncestorRepair: boolean;\n writeChain: Promise<void>;\n writerProjection: DocumentWriterProjectionResponse | null;\n /**\n * Bumped whenever a realtime hint drops `writerProjection`; an operation that\n * fetched or was handed a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration: number;\n}\nconst EMPTY_DOCUMENT_SNAPSHOT: DocumentSnapshot = {\n attachments: [],\n attachmentStatusBySlotId: {},\n attachmentStorageKeyBySlotId: {},\n canAttach: false,\n canWrite: true,\n currentAuthorId: null,\n documentId: null,\n documentKind: DEFAULT_DOCUMENT_KIND,\n effectiveAccessLevel: \"admin\",\n fieldValidationIssues: [],\n ready: false,\n rows: [],\n structuredFields: {},\n text: \"\",\n title: \"\",\n syncing: false,\n};\nfunction shallowEqualRecord<Value>(\n left: Readonly<Record<string, Value>>,\n right: Readonly<Record<string, Value>>,\n): boolean {\n let leftKeyCount = 0;\n for (const key in left) {\n if (!Object.hasOwn(left, key)) continue;\n\n leftKeyCount += 1;\n if (!Object.hasOwn(right, key) || !Object.is(left[key], right[key])) {\n return false;\n }\n }\n\n let rightKeyCount = 0;\n for (const key in right) {\n if (Object.hasOwn(right, key)) {\n rightKeyCount += 1;\n }\n }\n\n return leftKeyCount === rightKeyCount;\n}\n\nfunction sameValidationIssues(\n left: DocumentSnapshot[\"fieldValidationIssues\"],\n right: DocumentSnapshot[\"fieldValidationIssues\"],\n): boolean {\n return (\n left.length === right.length &&\n left.every((issue, index) => {\n const nextIssue = right[index];\n return (\n nextIssue !== undefined &&\n issue.field === nextIssue.field &&\n issue.message === nextIssue.message &&\n Object.is(issue.value, nextIssue.value)\n );\n })\n );\n}\n\nexport function createDocumentStoreState(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n effects: DocumentStorePersistenceEffects,\n initialDocumentId: string | null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n scheduleStartupRemoteSync = true,\n): DocumentStoreState {\n return {\n attachmentBlobIdBySlotId: {},\n attachmentContentSha256BySlotId: {},\n attachmentStorageKeyBySlotId: {},\n doc: null,\n effects,\n initialDocumentId,\n initialDocumentKind,\n initialText,\n initializePromise: null,\n initialized: false,\n lastEventCount: 0,\n localWriteGeneration: 0,\n locallyAcceptedUpdateIds: new Set(),\n localId,\n listeners: new Set(),\n pendingAttachments: [],\n pendingBaseVersion: null,\n pendingLocalWrites: 0,\n persistence,\n pullContinuation: null,\n record: null,\n rejectedServedAttachmentBindings: new Set(),\n rekeyOnlyPassCount: 0,\n resolveProjectionUserKey:\n createDocumentProjectionUserKeyResolver(initialRuntime),\n remoteUpdateCompletedSignalSeq: 0,\n remoteSyncBlocked: !scheduleStartupRemoteSync,\n scheduleStartupRemoteSync,\n awaitingAncestorRepair: false,\n remoteUpdatePending: false,\n remoteUpdateSignalSeq: 0,\n runtime: initialRuntime,\n snapshot: { ...EMPTY_DOCUMENT_SNAPSHOT },\n syncLane: null,\n writeChain: Promise.resolve(),\n writerProjection: null,\n writerProjectionGeneration: 0,\n };\n}\n\nfunction emitDocumentStore(state: DocumentStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nexport function setDocumentSnapshot(\n state: DocumentStoreState,\n next: DocumentSnapshot,\n) {\n if (\n sameDocumentAttachments(state.snapshot.attachments, next.attachments) &&\n shallowEqualRecord(\n state.snapshot.attachmentStatusBySlotId,\n next.attachmentStatusBySlotId,\n ) &&\n shallowEqualRecord(\n state.snapshot.attachmentStorageKeyBySlotId,\n next.attachmentStorageKeyBySlotId,\n ) &&\n state.snapshot.canAttach === next.canAttach &&\n state.snapshot.canWrite === next.canWrite &&\n state.snapshot.currentAuthorId === next.currentAuthorId &&\n state.snapshot.documentId === next.documentId &&\n state.snapshot.documentKind === next.documentKind &&\n state.snapshot.effectiveAccessLevel === next.effectiveAccessLevel &&\n sameValidationIssues(\n state.snapshot.fieldValidationIssues,\n next.fieldValidationIssues,\n ) &&\n state.snapshot.ready === next.ready &&\n sameDocumentRows(state.snapshot.rows, next.rows) &&\n shallowEqualRecord(\n state.snapshot.structuredFields,\n next.structuredFields,\n ) &&\n state.snapshot.text === next.text &&\n state.snapshot.title === next.title &&\n state.snapshot.syncing === next.syncing\n ) {\n return;\n }\n\n state.snapshot = next;\n emitDocumentStore(state);\n}\n\nfunction clearDocumentStoreState(\n state: DocumentStoreState,\n { initialized }: { initialized: boolean },\n) {\n state.deferInitialUpdate = false;\n state.doc = null;\n state.localWriteGeneration += 1;\n state.record = null;\n state.pendingAttachments = [];\n state.pendingBaseVersion = null;\n state.pendingLocalWrites = 0;\n state.pullContinuation = null;\n state.attachmentBlobIdBySlotId = {};\n state.attachmentContentSha256BySlotId = {};\n state.attachmentStorageKeyBySlotId = {};\n state.locallyAcceptedUpdateIds = new Set();\n state.rejectedServedAttachmentBindings = new Set();\n state.remoteUpdateCompletedSignalSeq = 0;\n state.remoteSyncBlocked = !state.scheduleStartupRemoteSync;\n state.awaitingAncestorRepair = false;\n state.remoteUpdatePending = false;\n state.remoteUpdateSignalSeq = 0;\n state.writerProjection = null;\n state.initialized = initialized;\n state.initializePromise = null;\n state.writeChain = Promise.resolve();\n setDocumentSnapshot(state, { ...EMPTY_DOCUMENT_SNAPSHOT });\n}\n\nexport function resetDocumentStore(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: false });\n}\n\nexport function markDocumentStoreRemoved(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: true });\n}\n\nexport function canAttachFiles(state: DocumentStoreState): boolean {\n return (\n canWriteDocument(state) &&\n state.runtime.infra.dbStatus === \"ready\" &&\n !!state.runtime.crypto.encapsulationKeyPair\n );\n}\n\nexport function canWriteDocument(state: DocumentStoreState): boolean {\n return canWriteEffectiveAccessLevel(state.record?.effectiveAccessLevel);\n}\n\nfunction getSnapshotAttachments(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentAttachment[] {\n return currentDoc ? getDocumentAttachments(currentDoc) : [];\n}\n\nfunction getSnapshotRows(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentRow[] {\n return currentDoc ? listDocumentRows(currentDoc) : [];\n}\n\nfunction resolveCurrentAuthorId(state: DocumentStoreState): string | null {\n return resolveDocumentCreateAuthor(state.runtime)?.signerUserId ?? null;\n}\n\nexport function setReadySnapshot(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n syncing: boolean,\n textOverride?: string,\n structuredFieldsOverride?: DocumentSnapshot[\"structuredFields\"],\n) {\n const attachments = getSnapshotAttachments(state, currentDoc);\n const rows = getSnapshotRows(state, currentDoc);\n const documentState = readStoredDocumentState(\n currentDoc,\n state.runtime.infra.documentProjectors,\n );\n const text = textOverride ?? documentState.text;\n const structuredFields =\n structuredFieldsOverride ?? documentState.structuredFields;\n const projectedState =\n textOverride === undefined && structuredFieldsOverride === undefined\n ? documentState\n : projectStoredDocumentState(\n {\n documentKind: documentState.documentKind,\n structuredFields,\n text,\n rows: rows.map((row) => ({ id: row.id, fields: row.fields })),\n },\n state.runtime.infra.documentProjectors,\n );\n\n setDocumentSnapshot(state, {\n attachments,\n attachmentStatusBySlotId: getAttachmentStatuses({\n attachments,\n contentSha256BySlotId: state.attachmentContentSha256BySlotId,\n pendingSlotIds: new Set(\n state.pendingAttachments.map((attachment) => attachment.slotId),\n ),\n }),\n attachmentStorageKeyBySlotId: getAttachmentStorageKeys(\n state.attachmentStorageKeyBySlotId,\n attachments,\n ),\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n currentAuthorId: resolveCurrentAuthorId(state),\n documentId: state.record?.documentId ?? null,\n documentKind: projectedState.documentKind,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n fieldValidationIssues: projectedState.fieldValidationIssues,\n ready: true,\n rows,\n structuredFields: projectedState.structuredFields,\n text,\n title: projectedState.title,\n syncing,\n });\n}\n\nexport function setDocumentSyncing(\n state: DocumentStoreState,\n syncing: boolean,\n) {\n setDocumentSnapshot(state, { ...state.snapshot, syncing });\n}\n\nexport function refreshAttachabilitySnapshot(state: DocumentStoreState) {\n if (!state.snapshot.ready) {\n return;\n }\n\n setDocumentSnapshot(state, {\n ...state.snapshot,\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n });\n}\n\nexport function subscribeToDocumentStore(\n state: DocumentStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => void state.listeners.delete(listener);\n}\n"]}
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,0BAA0B,EAC1B,uBAAuB,GAExB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,yCAAyC,CAAC;AAIjD,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAGL,uCAAuC,EAOvC,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,kCAAkC,CAAC;AAgJ1C,MAAM,uBAAuB,GAAqB;IAChD,WAAW,EAAE,EAAE;IACf,wBAAwB,EAAE,EAAE;IAC5B,4BAA4B,EAAE,EAAE;IAChC,SAAS,EAAE,KAAK;IAChB,QAAQ,EAAE,IAAI;IACd,eAAe,EAAE,IAAI;IACrB,UAAU,EAAE,IAAI;IAChB,YAAY,EAAE,qBAAqB;IACnC,oBAAoB,EAAE,OAAO;IAC7B,qBAAqB,EAAE,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CAAC;IAC9B,OAAO,GAAG,EAAE,CAAC,KAAK,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import type { createDocument } from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport {\n type DocumentAttachment,\n getDocumentAttachments,\n sameDocumentAttachments,\n} from \"../../../data/documents/documentContent\";\nimport {\n projectStoredDocumentState,\n readStoredDocumentState,\n type StoredDocumentKind,\n} from \"../../../data/documents/documentKinds\";\nimport {\n type DocumentRow,\n listDocumentRows,\n sameDocumentRows,\n} from \"../../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport type { DocumentSyncPullContinuation } from \"../../../data/documents/shared/sync/syncPagination\";\nimport type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/types\";\nimport {\n canWriteEffectiveAccessLevel,\n normalizeEffectiveAccessLevel,\n} from \"../../../data/keying/accessLevel\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionUserKeyResolver,\n type DocumentRecord,\n type DocumentSyncLane,\n type DocumentsPersistence,\n type PendingAttachmentRecord,\n type PendingUpdateInsert,\n resolveDocumentCreateAuthor,\n} from \"../../../workflows/documents\";\nimport type { DocumentSnapshot, DocumentsRuntime } from \"../types\";\nimport {\n getAttachmentStatuses,\n getAttachmentStorageKeys,\n} from \"./attachments/attachmentSnapshot\";\nexport type DocumentState = Awaited<ReturnType<typeof createDocument>>;\nexport type EncapsulationKeyPair = NonNullable<\n DocumentsRuntime[\"crypto\"][\"encapsulationKeyPair\"]\n>;\nexport type DocumentAttachmentBinding = NonNullable<\n Awaited<ReturnType<DocumentsRuntime[\"apiClient\"][\"listDocumentAttachments\"]>>\n>[number];\nexport type PendingMutationSyncResult = {\n completed: boolean;\n nextRecord: DocumentRecord;\n};\nexport interface PersistedDocumentRecord {\n creationSuperseded?: true;\n historyRestoreState?:\n | Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n | undefined;\n pullContinuationSuperseded?: true;\n record: DocumentRecord;\n syncIdentitySuperseded?: true;\n updatedAt?: string | undefined;\n}\nexport interface SaveDocumentRecordOptions {\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedSyncState?:\n | {\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord;\n }\n | undefined;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: Omit<PendingUpdateInsert, \"localId\"> | undefined;\n pendingBaseVersionOverride?: string | null | undefined;\n preserveSnapshotStructuredFields?: boolean | undefined;\n preserveSnapshotText?: boolean | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\nexport interface DocumentSyncAttempt {\n consumedPullContinuation: DocumentSyncPullContinuation | null;\n outgoingUpdateCount: number;\n requestRecord: DocumentRecord;\n synced: SyncRemoteDocumentResult;\n /** `writerProjectionGeneration` when the request left; gates the install. */\n writerProjectionGeneration: number;\n}\nexport interface DocumentStorePersistenceEffects {\n emitPersistedDocument: (\n domainScope: DomainScope,\n persistedDocument: DocumentSummary,\n placementChanged?: boolean | undefined,\n ) => void;\n registerDocumentIdentity: (\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n ) => void;\n}\nexport interface DocumentStoreState {\n attachmentBlobIdBySlotId: Record<string, string | null>;\n /** Plaintext digest of the held bytes per slot; see `getAttachmentStatuses`. */\n attachmentContentSha256BySlotId: Record<string, string>;\n attachmentStorageKeyBySlotId: Record<string, string>;\n /** Creation's birth rides the first attach; see `deferredInitialUpdate.ts`. */\n deferInitialUpdate?: boolean;\n doc: DocumentState | null;\n effects: DocumentStorePersistenceEffects;\n initialDocumentId: string | null;\n initialDocumentKind: StoredDocumentKind;\n initialText: string;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n lastEventCount: number;\n /** Invalidates queued local-write closures when this store is cleared. */\n localWriteGeneration: number;\n locallyAcceptedUpdateIds: Set<string>;\n localId: string;\n listeners: Set<() => void>;\n pendingAttachments: PendingAttachmentRecord[];\n /**\n * Oplog version through which every op in `doc` is already durably enqueued as\n * a pending update or synced from a remote peer. It advances only after an\n * edit's enqueue+persist succeeds, so a later edit can recover any orphaned\n * delta left by a failed write instead of silently dropping it from sync.\n * `null` only before initialization sets it to the loaded doc's version.\n */\n pendingBaseVersion: string | null;\n /**\n * Local text/structured writes queued on `writeChain` but not yet drained.\n * While positive, sync MUST preserve the optimistic text/fields because `doc`\n * can lag the latest keystroke. Remote merges remain in `doc` and publish when\n * the final write settles.\n */\n pendingLocalWrites: number;\n persistence: DocumentsPersistence;\n /**\n * Durable continuation for a bounded remote pull, mirrored from the document\n * record so the live lane can advance it without re-reading SQLite.\n */\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord | null;\n /** Served bindings hydration refused for a held copy; see `hydrate.ts`. */\n rejectedServedAttachmentBindings: Set<string>;\n /**\n * Consecutive completed sync passes that re-keyed conflicted pending updates\n * without settling anything. Bounds the rekey-driven self re-arm so a server\n * that keeps conflicting fresh ids cannot drive a network-speed loop; see\n * shouldReArmAfterOutgoingSettlement.\n */\n rekeyOnlyPassCount: number;\n resolveProjectionUserKey: DocumentProjectionUserKeyResolver;\n /** Latest remote-update sequence durably applied by a completed probe. */\n remoteUpdateCompletedSignalSeq: number;\n /** A cancelled remote-only owner blocks late responses until fresh work. */\n remoteSyncBlocked: boolean;\n scheduleStartupRemoteSync: boolean;\n remoteUpdatePending: boolean;\n /** Sequence used to keep an older pass from clearing a newer remote event. */\n remoteUpdateSignalSeq: number;\n runtime: DocumentsRuntime;\n snapshot: DocumentSnapshot;\n syncLane: DocumentSyncLane | null;\n /** Parked behind another member's ancestor repair; a path hint re-runs. */\n awaitingAncestorRepair: boolean;\n writeChain: Promise<void>;\n writerProjection: DocumentWriterProjectionResponse | null;\n /**\n * Bumped whenever a realtime hint drops `writerProjection`; an operation that\n * fetched or was handed a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration: number;\n}\nconst EMPTY_DOCUMENT_SNAPSHOT: DocumentSnapshot = {\n attachments: [],\n attachmentStatusBySlotId: {},\n attachmentStorageKeyBySlotId: {},\n canAttach: false,\n canWrite: true,\n currentAuthorId: null,\n documentId: null,\n documentKind: DEFAULT_DOCUMENT_KIND,\n effectiveAccessLevel: \"admin\",\n fieldValidationIssues: [],\n ready: false,\n rows: [],\n structuredFields: {},\n text: \"\",\n title: \"\",\n syncing: false,\n};\nfunction shallowEqualRecord<Value>(\n left: Readonly<Record<string, Value>>,\n right: Readonly<Record<string, Value>>,\n): boolean {\n let leftKeyCount = 0;\n for (const key in left) {\n if (!Object.hasOwn(left, key)) continue;\n\n leftKeyCount += 1;\n if (!Object.hasOwn(right, key) || !Object.is(left[key], right[key])) {\n return false;\n }\n }\n\n let rightKeyCount = 0;\n for (const key in right) {\n if (Object.hasOwn(right, key)) {\n rightKeyCount += 1;\n }\n }\n\n return leftKeyCount === rightKeyCount;\n}\n\nfunction sameValidationIssues(\n left: DocumentSnapshot[\"fieldValidationIssues\"],\n right: DocumentSnapshot[\"fieldValidationIssues\"],\n): boolean {\n return (\n left.length === right.length &&\n left.every((issue, index) => {\n const nextIssue = right[index];\n return (\n nextIssue !== undefined &&\n issue.field === nextIssue.field &&\n issue.message === nextIssue.message &&\n Object.is(issue.value, nextIssue.value)\n );\n })\n );\n}\n\nexport function createDocumentStoreState(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n effects: DocumentStorePersistenceEffects,\n initialDocumentId: string | null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n scheduleStartupRemoteSync = true,\n): DocumentStoreState {\n return {\n attachmentBlobIdBySlotId: {},\n attachmentContentSha256BySlotId: {},\n attachmentStorageKeyBySlotId: {},\n doc: null,\n effects,\n initialDocumentId,\n initialDocumentKind,\n initialText,\n initializePromise: null,\n initialized: false,\n lastEventCount: 0,\n localWriteGeneration: 0,\n locallyAcceptedUpdateIds: new Set(),\n localId,\n listeners: new Set(),\n pendingAttachments: [],\n pendingBaseVersion: null,\n pendingLocalWrites: 0,\n persistence,\n pullContinuation: null,\n record: null,\n rejectedServedAttachmentBindings: new Set(),\n rekeyOnlyPassCount: 0,\n resolveProjectionUserKey:\n createDocumentProjectionUserKeyResolver(initialRuntime),\n remoteUpdateCompletedSignalSeq: 0,\n remoteSyncBlocked: !scheduleStartupRemoteSync,\n scheduleStartupRemoteSync,\n awaitingAncestorRepair: false,\n remoteUpdatePending: false,\n remoteUpdateSignalSeq: 0,\n runtime: initialRuntime,\n snapshot: { ...EMPTY_DOCUMENT_SNAPSHOT },\n syncLane: null,\n writeChain: Promise.resolve(),\n writerProjection: null,\n writerProjectionGeneration: 0,\n };\n}\n\nfunction emitDocumentStore(state: DocumentStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nexport function setDocumentSnapshot(\n state: DocumentStoreState,\n next: DocumentSnapshot,\n) {\n if (\n sameDocumentAttachments(state.snapshot.attachments, next.attachments) &&\n shallowEqualRecord(\n state.snapshot.attachmentStatusBySlotId,\n next.attachmentStatusBySlotId,\n ) &&\n shallowEqualRecord(\n state.snapshot.attachmentStorageKeyBySlotId,\n next.attachmentStorageKeyBySlotId,\n ) &&\n state.snapshot.canAttach === next.canAttach &&\n state.snapshot.canWrite === next.canWrite &&\n state.snapshot.currentAuthorId === next.currentAuthorId &&\n state.snapshot.documentId === next.documentId &&\n state.snapshot.documentKind === next.documentKind &&\n state.snapshot.effectiveAccessLevel === next.effectiveAccessLevel &&\n sameValidationIssues(\n state.snapshot.fieldValidationIssues,\n next.fieldValidationIssues,\n ) &&\n state.snapshot.ready === next.ready &&\n sameDocumentRows(state.snapshot.rows, next.rows) &&\n shallowEqualRecord(\n state.snapshot.structuredFields,\n next.structuredFields,\n ) &&\n state.snapshot.text === next.text &&\n state.snapshot.title === next.title &&\n state.snapshot.syncing === next.syncing\n ) {\n return;\n }\n\n state.snapshot = next;\n emitDocumentStore(state);\n}\n\nfunction clearDocumentStoreState(\n state: DocumentStoreState,\n { initialized }: { initialized: boolean },\n) {\n state.deferInitialUpdate = false;\n state.doc = null;\n state.localWriteGeneration += 1;\n state.record = null;\n state.pendingAttachments = [];\n state.pendingBaseVersion = null;\n state.pendingLocalWrites = 0;\n state.pullContinuation = null;\n state.attachmentBlobIdBySlotId = {};\n state.attachmentContentSha256BySlotId = {};\n state.attachmentStorageKeyBySlotId = {};\n state.locallyAcceptedUpdateIds = new Set();\n state.rejectedServedAttachmentBindings = new Set();\n state.remoteUpdateCompletedSignalSeq = 0;\n state.remoteSyncBlocked = !state.scheduleStartupRemoteSync;\n state.awaitingAncestorRepair = false;\n state.remoteUpdatePending = false;\n state.remoteUpdateSignalSeq = 0;\n state.writerProjection = null;\n state.initialized = initialized;\n state.initializePromise = null;\n state.writeChain = Promise.resolve();\n setDocumentSnapshot(state, { ...EMPTY_DOCUMENT_SNAPSHOT });\n}\n\nexport function resetDocumentStore(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: false });\n}\n\nexport function markDocumentStoreRemoved(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: true });\n}\n\nexport function canAttachFiles(state: DocumentStoreState): boolean {\n return (\n canWriteDocument(state) &&\n state.runtime.infra.dbStatus === \"ready\" &&\n !!state.runtime.crypto.encapsulationKeyPair\n );\n}\n\nexport function canWriteDocument(state: DocumentStoreState): boolean {\n return canWriteEffectiveAccessLevel(state.record?.effectiveAccessLevel);\n}\n\nfunction getSnapshotAttachments(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentAttachment[] {\n return currentDoc ? getDocumentAttachments(currentDoc) : [];\n}\n\nfunction getSnapshotRows(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentRow[] {\n return currentDoc ? listDocumentRows(currentDoc) : [];\n}\n\nfunction resolveCurrentAuthorId(state: DocumentStoreState): string | null {\n return resolveDocumentCreateAuthor(state.runtime)?.signerUserId ?? null;\n}\n\nexport function setReadySnapshot(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n syncing: boolean,\n textOverride?: string,\n structuredFieldsOverride?: DocumentSnapshot[\"structuredFields\"],\n) {\n const attachments = getSnapshotAttachments(state, currentDoc);\n const rows = getSnapshotRows(state, currentDoc);\n const documentState = readStoredDocumentState(\n currentDoc,\n state.runtime.infra.documentProjectors,\n );\n const text = textOverride ?? documentState.text;\n const structuredFields =\n structuredFieldsOverride ?? documentState.structuredFields;\n const projectedState =\n textOverride === undefined && structuredFieldsOverride === undefined\n ? documentState\n : projectStoredDocumentState(\n {\n documentKind: documentState.documentKind,\n structuredFields,\n text,\n rows: rows.map((row) => ({ id: row.id, fields: row.fields })),\n },\n state.runtime.infra.documentProjectors,\n );\n\n setDocumentSnapshot(state, {\n attachments,\n attachmentStatusBySlotId: getAttachmentStatuses({\n attachments,\n contentSha256BySlotId: state.attachmentContentSha256BySlotId,\n pendingSlotIds: new Set(\n state.pendingAttachments.map((attachment) => attachment.slotId),\n ),\n }),\n attachmentStorageKeyBySlotId: getAttachmentStorageKeys(\n state.attachmentStorageKeyBySlotId,\n attachments,\n ),\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n currentAuthorId: resolveCurrentAuthorId(state),\n documentId: state.record?.documentId ?? null,\n documentKind: projectedState.documentKind,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n fieldValidationIssues: projectedState.fieldValidationIssues,\n ready: true,\n rows,\n structuredFields: projectedState.structuredFields,\n text,\n title: projectedState.title,\n syncing,\n });\n}\n\nexport function setDocumentSyncing(\n state: DocumentStoreState,\n syncing: boolean,\n) {\n setDocumentSnapshot(state, { ...state.snapshot, syncing });\n}\n\nexport function refreshAttachabilitySnapshot(state: DocumentStoreState) {\n if (!state.snapshot.ready) {\n return;\n }\n\n setDocumentSnapshot(state, {\n ...state.snapshot,\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n });\n}\n\nexport function subscribeToDocumentStore(\n state: DocumentStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => void state.listeners.delete(listener);\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { bytesToBase64 } from "../../../../internal/encoding/index.js";
2
2
  import { emptyVersionVector, encodeVersionVector, getImportBlobMetadata, mergeVersionVectors, } from "../../../../internal/loro/index.js";
3
- import { readPullContinuation } from "../../../../data/documents/shared/syncPagination.js";
3
+ import { readPullContinuation } from "../../../../data/documents/shared/sync/syncPagination.js";
4
4
  import { settleOutgoingPassAndDecideReArm, shouldClearDocumentSyncFailureAfterPass, } from "../../../../workflows/documents/index.js";
5
5
  import { requestDocumentStoreSync } from "../../registry.js";
6
6
  import { hydrateAttachmentBlobs } from "../attachments/attachmentHydration.js";
@@ -1 +1 @@
1
- {"version":3,"file":"syncFinalize.js","sourceRoot":"","sources":["syncFinalize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,oBAAoB,EAAE,MAAM,kDAAkD,CAAC;AACxF,OAAO,EAEL,gCAAgC,EAChC,uCAAuC,GACxC,MA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I,CAAC,MAAM,CAAC,iBAAiB,EAAE,CAAC;QAC9B,+BAA+B,CAAC,KAAK,EAAE,6BAA6B,CAAC,CAAC;IACxE,CAAC;IAED,IAAI,uBAAuB,CAAC,KAAK,EAAE,WAAW,CAAC,EAAE,CAAC;QAChD,wBAAwB,CAAC,KAAK,CAAC,CAAC;IAClC,CAAC;IAED,MAAM,sBAAsB,CAAC,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC;IACxE,UAAU,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAC9E,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n emptyVersionVector,\n encodeVersionVector,\n getImportBlobMetadata,\n mergeVersionVectors,\n} from \"@tearleads/loro\";\nimport { readPullContinuation } from \"../../../../data/documents/shared/syncPagination\";\nimport {\n type DocumentRecord,\n settleOutgoingPassAndDecideReArm,\n shouldClearDocumentSyncFailureAfterPass,\n} from \"../../../../workflows/documents\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport { hydrateAttachmentBlobs } from \"../attachments/attachmentHydration\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { publishPersistedDocument, saveDocumentRecord } from \"../persistence\";\nimport type {\n DocumentState,\n DocumentStoreState,\n DocumentSyncAttempt,\n SaveDocumentRecordOptions,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport { logRevalidationApplied as logApplied } from \"./remoteRevalidationTelemetry\";\nimport {\n discardPreRegisteredUpdateIds,\n discardUnacceptedPreRegisteredUpdateIds,\n} from \"./syncAcceptedUpdateIds\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { clearConsumedRemoteUpdateSignal } from \"./syncRemoteSignals\";\nimport {\n applyIncomingSyncedUpdates,\n documentSyncContextMatches,\n importSyncedDocumentUpdates,\n} from \"./syncUpdateImport\";\nimport { extendDocumentVersionCoverage } from \"./versionCoverage\";\n\nfunction documentWriterProjectionMatchesSyncResponse(\n writerProjection: NonNullable<\n DocumentSyncAttempt[\"synced\"][\"writerProjection\"]\n >,\n synced: DocumentSyncAttempt[\"synced\"],\n): boolean {\n return (\n writerProjection.contentKeyBundle.contentKeyEpoch ===\n synced.response.contentKeyBundle.contentKeyEpoch &&\n writerProjection.contentKeyBundle.linkSetManifestHash ===\n synced.response.contentKeyBundle.linkSetManifestHash &&\n writerProjection.contentKeyBundle.targetHash ===\n synced.response.contentKeyBundle.targetHash &&\n writerProjection.documentKekTargets.linkSetManifestHash ===\n synced.response.documentKekTargets.linkSetManifestHash &&\n writerProjection.documentKekTargets.documentKeyTargetHash ===\n synced.response.documentKekTargets.documentKeyTargetHash\n );\n}\n\nfunction resolveSyncedDocumentWriterProjection(\n state: DocumentStoreState,\n synced: DocumentSyncAttempt[\"synced\"],\n) {\n const writerProjection =\n synced.writerProjection ??\n (state.writerProjection?.documentId === synced.plan.documentId\n ? state.writerProjection\n : null);\n return writerProjection &&\n documentWriterProjectionMatchesSyncResponse(writerProjection, synced)\n ? writerProjection\n : null;\n}\n\n/**\n * Durable-history tail: append pulled updates BEFORE the record persist so\n * the tail stays a superset of what the snapshot covers (duplicates are\n * idempotent by op identity; a crash between the writes can only leave the\n * safe superset).\n */\nfunction pulledHistoryUpdates(synced: DocumentSyncAttempt[\"synced\"]): string[] {\n return synced.decryptedUpdates.map((update) =>\n bytesToBase64(update.updateData),\n );\n}\n\n/**\n * The frontier a finalize persist may publish: the stored frontier advanced\n * by exactly the pulled updates just appended to the durable tail — never the\n * live document's version, which can transiently include an in-flight local\n * edit whose durable row has not landed yet.\n */\nfunction coveredSyncFrontier(\n state: DocumentStoreState,\n currentRecord: DocumentRecord,\n synced: DocumentSyncAttempt[\"synced\"],\n): { snapshotEndVersion: string } | Record<string, never> {\n const liveFrontier = (state.record ?? currentRecord).snapshotEndVersion;\n if (synced.decryptedUpdates.length === 0) {\n // A completed empty pull distinguishes a real blank note from discovery.\n // An intermediate page cannot establish that no content exists yet.\n return liveFrontier === \"\" && !synced.hasIncompletePull\n ? { snapshotEndVersion: emptyVersionVector() }\n : {};\n }\n return {\n snapshotEndVersion: mergeVersionVectors([\n ...(liveFrontier.length > 0 ? [liveFrontier] : []),\n ...synced.decryptedUpdates.map(\n (update) =>\n getImportBlobMetadata(update.updateData).partialEndVersionVector,\n ),\n ]),\n };\n}\n\nfunction documentSyncSaveOptions(\n syncAttempt: DocumentSyncAttempt,\n): SaveDocumentRecordOptions {\n return {\n acceptedPendingUpdateIds: syncAttempt.synced.settledPendingUpdateIds,\n clearSyncFailure: shouldClearDocumentSyncFailureAfterPass(\n syncAttempt.synced,\n syncAttempt.outgoingUpdateCount,\n ),\n expectedSyncState: {\n pullContinuation: syncAttempt.consumedPullContinuation,\n record: syncAttempt.requestRecord,\n },\n historyUpdateOrigin: \"remote\",\n historyUpdates: pulledHistoryUpdates(syncAttempt.synced),\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n };\n}\n\nasync function persistSyncedDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n currentRecord: DocumentRecord,\n syncAttempt: DocumentSyncAttempt,\n generation: DocumentStoreSyncGeneration,\n) {\n const { synced } = syncAttempt;\n const updates = synced.decryptedUpdates;\n const candidate = currentDoc.fork();\n const previousDocumentId = state.record?.documentId ?? null;\n const options = documentSyncSaveOptions(syncAttempt);\n const isCurrent = () =>\n isDocumentStoreSyncGenerationCurrent(state, generation);\n try {\n importSyncedDocumentUpdates(candidate, updates);\n if (state.pendingBaseVersion === null) {\n throw new Error(\"Document sync requires an initialized pending base\");\n }\n const persisted = await saveDocumentRecord(\n state,\n candidate,\n {\n ...synced.persistedState,\n lastCommitLsn:\n synced.response.commitLsn ?? currentRecord.lastCommitLsn ?? null,\n pullContinuation: readPullContinuation(synced.response),\n ...coveredSyncFrontier(state, currentRecord, synced),\n },\n {\n ...options,\n pendingBaseVersionOverride: extendDocumentVersionCoverage({\n baseVersion: state.pendingBaseVersion,\n documentVersion: encodeVersionVector(candidate),\n spans: updates,\n }),\n },\n generation,\n );\n if (\n persisted &&\n isCurrent() &&\n !persisted.pullContinuationSuperseded &&\n !persisted.syncIdentitySuperseded\n ) {\n // Publish a remote edit only once its history and continuation commit.\n // Importing earlier lets a losing CAS expose text that the next local\n // write authors against an older, reloaded CRDT history.\n // The durable CAS already checked the request's complete context. The\n // successful row is now live, so publication uses that committed context\n // (which may contain refreshed keying metadata) and the same generation.\n applyIncomingSyncedUpdates(\n state,\n currentDoc,\n persisted.record,\n syncAttempt,\n generation,\n );\n }\n return await publishPersistedDocument(\n state,\n currentDoc,\n persisted,\n previousDocumentId,\n options,\n isCurrent,\n );\n } finally {\n candidate.free();\n }\n}\n\nexport function shouldReArmDocumentSync(\n state: DocumentStoreState,\n syncAttempt: DocumentSyncAttempt,\n): boolean {\n const { synced } = syncAttempt;\n const shouldReArmOutgoing = settleOutgoingPassAndDecideReArm(state, {\n exhaustedPendingUpdateCount: synced.exhaustedPendingUpdateCount,\n outgoingUpdateCount: syncAttempt.outgoingUpdateCount,\n rekeyedUpdateCount: synced.rekeyedPendingUpdateIds.length,\n settledUpdateCount: synced.settledPendingUpdateIds.length,\n acceptedRecoveryBaseline: synced.acceptedRecoveryBaseline,\n });\n return (\n synced.hasDeferredPendingUpdates ||\n synced.hasIncompletePull ||\n shouldReArmOutgoing\n );\n}\n\nexport async function finalizeDocumentSync(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n currentRecord: DocumentRecord,\n syncAttempt: DocumentSyncAttempt,\n consumedRemoteUpdateSignalSeq: number,\n generation: DocumentStoreSyncGeneration,\n sentUpdateIds: readonly string[],\n wasRemoteProbe: boolean,\n): Promise<DocumentRecord> {\n const { synced } = syncAttempt;\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n requestDocumentStoreSync(state);\n return state.record ?? currentRecord;\n }\n\n // The sent IDs were pre-registered as self-authored before the network call so\n // the redis echo can never beat us. Reconcile against what the server actually\n // accepted: an ID we sent but the server did not accept will never be echoed,\n // so drop it to keep locallyAcceptedUpdateIds from leaking. Accepted IDs (a\n // subset of what we sent) stay registered until their echo consumes them.\n discardUnacceptedPreRegisteredUpdateIds(\n state,\n sentUpdateIds,\n synced.response.acceptedOutgoingUpdateIds,\n );\n // Persist on the identity-write chain: synced.persistedState carries this\n // pass's documentId, so it would clobber a relink that landed mid-pass. If\n // the identity moved, the response describes the OLD document — skip every\n // response-derived in-memory mutation and let the new identity's own sync\n // pass take over.\n let responseApplied = false;\n const { record: nextRecord } = await chainIdentityWrite(state, async () => {\n const liveRecord = state.record;\n if (\n !isDocumentStoreSyncGenerationCurrent(state, generation) ||\n !documentSyncContextMatches(\n liveRecord,\n currentRecord,\n synced.plan.documentId,\n )\n ) {\n return { record: liveRecord ?? currentRecord };\n }\n\n installDocumentWriterProjection(\n state,\n resolveSyncedDocumentWriterProjection(state, synced),\n syncAttempt.writerProjectionGeneration,\n );\n const persisted = await persistSyncedDocument(\n state,\n currentDoc,\n currentRecord,\n syncAttempt,\n generation,\n );\n if (\n !persisted ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return { record: state.record ?? currentRecord };\n }\n\n state.pullContinuation = persisted.record.pullContinuation ?? null;\n if (persisted.pullContinuationSuperseded) {\n state.writerProjection = null;\n }\n // A CAS loss means neither this response's acknowledgements nor its\n // continuation were committed. Keep the pass unapplied so its signals and\n // accepted-id registrations cannot be cleared without a follow-up.\n responseApplied = !persisted.pullContinuationSuperseded;\n return persisted;\n });\n if (!responseApplied) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n requestDocumentStoreSync(state);\n return nextRecord;\n }\n\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n requestDocumentStoreSync(state);\n return state.record ?? nextRecord;\n }\n\n // A bounded pull request owns the whole page chain. Completing the signal on\n // an intermediate page would let a failed/null continuation pass report the\n // original request as successful even though the server frontier was never\n // drained.\n if (!synced.hasIncompletePull) {\n clearConsumedRemoteUpdateSignal(state, consumedRemoteUpdateSignalSeq);\n }\n\n if (shouldReArmDocumentSync(state, syncAttempt)) {\n requestDocumentStoreSync(state);\n }\n\n await hydrateAttachmentBlobs(state, currentDoc, nextRecord, generation);\n logApplied(state, currentDoc, synced.decryptedUpdates.length, wasRemoteProbe);\n return nextRecord;\n}\n"]}
1
+ {"version":3,"file":"syncFinalize.js","sourceRoot":"","sources":["syncFinalize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,oBAAoB,EAAE,MAAM,uDAAuD,CAAC;AAC7F,OAAO,EAEL,gCAAgC,EAChC,uCAAuC,GACxC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,oCAAoC,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,wBAAwB,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAO9E,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,EAAE,sBAAsB,IAAI,UAAU,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EACL,6BAA6B,EAC7B,uCAAuC,GACxC,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,+BAA+B,EAAE,MAAM,qBAAqB,CAAC;AACtE,OAAO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AAI,SAAS,CAAC,0BAA0B,EAAE,CAAC;YACzC,KAAK,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAChC,CAAC;QACD,oEAAoE;QACpE,0EAA0E;QAC1E,mEAAmE;QACnE,eAAe,GAAG,CAAC,SAAS,CAAC,0BAA0B,CAAC;QACxD,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;IACH,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,6BAA6B,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QACpD,wBAAwB,CAAC,KAAK,CAAC,CAAC;QAChC,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,IAAI,CAAC,oCAAoC,CAAC,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC;QAC7D,6BAA6B,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QACpD,wBAAwB,CAAC,KAAK,CAAC,CAAC;QAChC,OAAO,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACpC,CAAC;IAED,6EAA6E;IAC7E,4EAA4E;IAC5E,2EAA2E;IAC3E,WAAW;IACX,IAAI,CAAC,MAAM,CAAC,iBAAiB,EAAE,CAAC;QAC9B,+BAA+B,CAAC,KAAK,EAAE,6BAA6B,CAAC,CAAC;IACxE,CAAC;IAED,IAAI,uBAAuB,CAAC,KAAK,EAAE,WAAW,CAAC,EAAE,CAAC;QAChD,wBAAwB,CAAC,KAAK,CAAC,CAAC;IAClC,CAAC;IAED,MAAM,sBAAsB,CAAC,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC;IACxE,UAAU,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAC9E,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n emptyVersionVector,\n encodeVersionVector,\n getImportBlobMetadata,\n mergeVersionVectors,\n} from \"@tearleads/loro\";\nimport { readPullContinuation } from \"../../../../data/documents/shared/sync/syncPagination\";\nimport {\n type DocumentRecord,\n settleOutgoingPassAndDecideReArm,\n shouldClearDocumentSyncFailureAfterPass,\n} from \"../../../../workflows/documents\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport { hydrateAttachmentBlobs } from \"../attachments/attachmentHydration\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { publishPersistedDocument, saveDocumentRecord } from \"../persistence\";\nimport type {\n DocumentState,\n DocumentStoreState,\n DocumentSyncAttempt,\n SaveDocumentRecordOptions,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport { logRevalidationApplied as logApplied } from \"./remoteRevalidationTelemetry\";\nimport {\n discardPreRegisteredUpdateIds,\n discardUnacceptedPreRegisteredUpdateIds,\n} from \"./syncAcceptedUpdateIds\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { clearConsumedRemoteUpdateSignal } from \"./syncRemoteSignals\";\nimport {\n applyIncomingSyncedUpdates,\n documentSyncContextMatches,\n importSyncedDocumentUpdates,\n} from \"./syncUpdateImport\";\nimport { extendDocumentVersionCoverage } from \"./versionCoverage\";\n\nfunction documentWriterProjectionMatchesSyncResponse(\n writerProjection: NonNullable<\n DocumentSyncAttempt[\"synced\"][\"writerProjection\"]\n >,\n synced: DocumentSyncAttempt[\"synced\"],\n): boolean {\n return (\n writerProjection.contentKeyBundle.contentKeyEpoch ===\n synced.response.contentKeyBundle.contentKeyEpoch &&\n writerProjection.contentKeyBundle.linkSetManifestHash ===\n synced.response.contentKeyBundle.linkSetManifestHash &&\n writerProjection.contentKeyBundle.targetHash ===\n synced.response.contentKeyBundle.targetHash &&\n writerProjection.documentKekTargets.linkSetManifestHash ===\n synced.response.documentKekTargets.linkSetManifestHash &&\n writerProjection.documentKekTargets.documentKeyTargetHash ===\n synced.response.documentKekTargets.documentKeyTargetHash\n );\n}\n\nfunction resolveSyncedDocumentWriterProjection(\n state: DocumentStoreState,\n synced: DocumentSyncAttempt[\"synced\"],\n) {\n const writerProjection =\n synced.writerProjection ??\n (state.writerProjection?.documentId === synced.plan.documentId\n ? state.writerProjection\n : null);\n return writerProjection &&\n documentWriterProjectionMatchesSyncResponse(writerProjection, synced)\n ? writerProjection\n : null;\n}\n\n/**\n * Durable-history tail: append pulled updates BEFORE the record persist so\n * the tail stays a superset of what the snapshot covers (duplicates are\n * idempotent by op identity; a crash between the writes can only leave the\n * safe superset).\n */\nfunction pulledHistoryUpdates(synced: DocumentSyncAttempt[\"synced\"]): string[] {\n return synced.decryptedUpdates.map((update) =>\n bytesToBase64(update.updateData),\n );\n}\n\n/**\n * The frontier a finalize persist may publish: the stored frontier advanced\n * by exactly the pulled updates just appended to the durable tail — never the\n * live document's version, which can transiently include an in-flight local\n * edit whose durable row has not landed yet.\n */\nfunction coveredSyncFrontier(\n state: DocumentStoreState,\n currentRecord: DocumentRecord,\n synced: DocumentSyncAttempt[\"synced\"],\n): { snapshotEndVersion: string } | Record<string, never> {\n const liveFrontier = (state.record ?? currentRecord).snapshotEndVersion;\n if (synced.decryptedUpdates.length === 0) {\n // A completed empty pull distinguishes a real blank note from discovery.\n // An intermediate page cannot establish that no content exists yet.\n return liveFrontier === \"\" && !synced.hasIncompletePull\n ? { snapshotEndVersion: emptyVersionVector() }\n : {};\n }\n return {\n snapshotEndVersion: mergeVersionVectors([\n ...(liveFrontier.length > 0 ? [liveFrontier] : []),\n ...synced.decryptedUpdates.map(\n (update) =>\n getImportBlobMetadata(update.updateData).partialEndVersionVector,\n ),\n ]),\n };\n}\n\nfunction documentSyncSaveOptions(\n syncAttempt: DocumentSyncAttempt,\n): SaveDocumentRecordOptions {\n return {\n acceptedPendingUpdateIds: syncAttempt.synced.settledPendingUpdateIds,\n clearSyncFailure: shouldClearDocumentSyncFailureAfterPass(\n syncAttempt.synced,\n syncAttempt.outgoingUpdateCount,\n ),\n expectedSyncState: {\n pullContinuation: syncAttempt.consumedPullContinuation,\n record: syncAttempt.requestRecord,\n },\n historyUpdateOrigin: \"remote\",\n historyUpdates: pulledHistoryUpdates(syncAttempt.synced),\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n };\n}\n\nasync function persistSyncedDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n currentRecord: DocumentRecord,\n syncAttempt: DocumentSyncAttempt,\n generation: DocumentStoreSyncGeneration,\n) {\n const { synced } = syncAttempt;\n const updates = synced.decryptedUpdates;\n const candidate = currentDoc.fork();\n const previousDocumentId = state.record?.documentId ?? null;\n const options = documentSyncSaveOptions(syncAttempt);\n const isCurrent = () =>\n isDocumentStoreSyncGenerationCurrent(state, generation);\n try {\n importSyncedDocumentUpdates(candidate, updates);\n if (state.pendingBaseVersion === null) {\n throw new Error(\"Document sync requires an initialized pending base\");\n }\n const persisted = await saveDocumentRecord(\n state,\n candidate,\n {\n ...synced.persistedState,\n lastCommitLsn:\n synced.response.commitLsn ?? currentRecord.lastCommitLsn ?? null,\n pullContinuation: readPullContinuation(synced.response),\n ...coveredSyncFrontier(state, currentRecord, synced),\n },\n {\n ...options,\n pendingBaseVersionOverride: extendDocumentVersionCoverage({\n baseVersion: state.pendingBaseVersion,\n documentVersion: encodeVersionVector(candidate),\n spans: updates,\n }),\n },\n generation,\n );\n if (\n persisted &&\n isCurrent() &&\n !persisted.pullContinuationSuperseded &&\n !persisted.syncIdentitySuperseded\n ) {\n // Publish a remote edit only once its history and continuation commit.\n // Importing earlier lets a losing CAS expose text that the next local\n // write authors against an older, reloaded CRDT history.\n // The durable CAS already checked the request's complete context. The\n // successful row is now live, so publication uses that committed context\n // (which may contain refreshed keying metadata) and the same generation.\n applyIncomingSyncedUpdates(\n state,\n currentDoc,\n persisted.record,\n syncAttempt,\n generation,\n );\n }\n return await publishPersistedDocument(\n state,\n currentDoc,\n persisted,\n previousDocumentId,\n options,\n isCurrent,\n );\n } finally {\n candidate.free();\n }\n}\n\nexport function shouldReArmDocumentSync(\n state: DocumentStoreState,\n syncAttempt: DocumentSyncAttempt,\n): boolean {\n const { synced } = syncAttempt;\n const shouldReArmOutgoing = settleOutgoingPassAndDecideReArm(state, {\n exhaustedPendingUpdateCount: synced.exhaustedPendingUpdateCount,\n outgoingUpdateCount: syncAttempt.outgoingUpdateCount,\n rekeyedUpdateCount: synced.rekeyedPendingUpdateIds.length,\n settledUpdateCount: synced.settledPendingUpdateIds.length,\n acceptedRecoveryBaseline: synced.acceptedRecoveryBaseline,\n });\n return (\n synced.hasDeferredPendingUpdates ||\n synced.hasIncompletePull ||\n shouldReArmOutgoing\n );\n}\n\nexport async function finalizeDocumentSync(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n currentRecord: DocumentRecord,\n syncAttempt: DocumentSyncAttempt,\n consumedRemoteUpdateSignalSeq: number,\n generation: DocumentStoreSyncGeneration,\n sentUpdateIds: readonly string[],\n wasRemoteProbe: boolean,\n): Promise<DocumentRecord> {\n const { synced } = syncAttempt;\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n requestDocumentStoreSync(state);\n return state.record ?? currentRecord;\n }\n\n // The sent IDs were pre-registered as self-authored before the network call so\n // the redis echo can never beat us. Reconcile against what the server actually\n // accepted: an ID we sent but the server did not accept will never be echoed,\n // so drop it to keep locallyAcceptedUpdateIds from leaking. Accepted IDs (a\n // subset of what we sent) stay registered until their echo consumes them.\n discardUnacceptedPreRegisteredUpdateIds(\n state,\n sentUpdateIds,\n synced.response.acceptedOutgoingUpdateIds,\n );\n // Persist on the identity-write chain: synced.persistedState carries this\n // pass's documentId, so it would clobber a relink that landed mid-pass. If\n // the identity moved, the response describes the OLD document — skip every\n // response-derived in-memory mutation and let the new identity's own sync\n // pass take over.\n let responseApplied = false;\n const { record: nextRecord } = await chainIdentityWrite(state, async () => {\n const liveRecord = state.record;\n if (\n !isDocumentStoreSyncGenerationCurrent(state, generation) ||\n !documentSyncContextMatches(\n liveRecord,\n currentRecord,\n synced.plan.documentId,\n )\n ) {\n return { record: liveRecord ?? currentRecord };\n }\n\n installDocumentWriterProjection(\n state,\n resolveSyncedDocumentWriterProjection(state, synced),\n syncAttempt.writerProjectionGeneration,\n );\n const persisted = await persistSyncedDocument(\n state,\n currentDoc,\n currentRecord,\n syncAttempt,\n generation,\n );\n if (\n !persisted ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return { record: state.record ?? currentRecord };\n }\n\n state.pullContinuation = persisted.record.pullContinuation ?? null;\n if (persisted.pullContinuationSuperseded) {\n state.writerProjection = null;\n }\n // A CAS loss means neither this response's acknowledgements nor its\n // continuation were committed. Keep the pass unapplied so its signals and\n // accepted-id registrations cannot be cleared without a follow-up.\n responseApplied = !persisted.pullContinuationSuperseded;\n return persisted;\n });\n if (!responseApplied) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n requestDocumentStoreSync(state);\n return nextRecord;\n }\n\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n requestDocumentStoreSync(state);\n return state.record ?? nextRecord;\n }\n\n // A bounded pull request owns the whole page chain. Completing the signal on\n // an intermediate page would let a failed/null continuation pass report the\n // original request as successful even though the server frontier was never\n // drained.\n if (!synced.hasIncompletePull) {\n clearConsumedRemoteUpdateSignal(state, consumedRemoteUpdateSignalSeq);\n }\n\n if (shouldReArmDocumentSync(state, syncAttempt)) {\n requestDocumentStoreSync(state);\n }\n\n await hydrateAttachmentBlobs(state, currentDoc, nextRecord, generation);\n logApplied(state, currentDoc, synced.decryptedUpdates.length, wasRemoteProbe);\n return nextRecord;\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { encodeVersionVector } from "../../../../internal/loro/index.js";
2
- import { importDecryptedDocumentSyncUpdates } from "../../../../data/documents/shared/documentSyncUpdateIsolation.js";
2
+ import { importDecryptedDocumentSyncUpdates } from "../../../../data/documents/shared/sync/documentSyncUpdateIsolation.js";
3
3
  import { setReadySnapshot, } from "../state.js";
4
4
  import { isDocumentStoreSyncGenerationCurrent, } from "./syncGeneration.js";
5
5
  import { extendDocumentVersionCoverage } from "./versionCoverage.js";
@@ -1 +1 @@
1
- {"version":3,"file":"syncUpdateImport.js","sourceRoot":"","sources":["syncUpdateImport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,kCAAkC,EAAE,MAAM,+DAA+D,CAAC;AAInH,OAAO,EAGL,gBAAgB,GACjB,MAAM,UAAU,CAAC;AAClB,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAC;AAElE,SAAS,iBAAiB,CACxB,IAA+B,EAC/B,KAAgC;IAEhC,OAAO,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;AAC5C,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACxC,UAAiC,EACjC,aAA6B,EAC7B,kBAAiC;IAEjC,OAAO,CACL,UAAU,KAAK,IAAI;QACnB,UAAU,CAAC,EAAE,KAAK,aAAa,CAAC,EAAE;QAClC,UAAU,CAAC,UAAU,KAAK,aAAa,CAAC,UAAU;QAClD,UAAU,CAAC,UAAU,KAAK,kBAAkB;QAC5C,UAAU,CAAC,WAAW,KAAK,aAAa,CAAC,WAAW;QACpD,UAAU,CAAC,WAAW,KAAK,aAAa,CAAC,WAAW;QACpD,iBAAiB,CACf,UAAU,CAAC,eAAe,EAC1B,aAAa,CAAC,eAAe,CAC9B;QACD,CAAC,UAAU,CAAC,oBAAoB,IAAI,IAAI,CAAC;YACvC,CAAC,aAAa,CAAC,oBAAoB,IAAI,IAAI,CAAC;QAC9C,iBAAiB,CACf,UAAU,CAAC,gBAAgB,EAC3B,aAAa,CAAC,gBAAgB,CAC/B;QACD,iBAAi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C,gBAAgB,CACd,KAAK,EACL,SAAS,EACT,IAAI,EACJ,KAAK,CAAC,QAAQ,CAAC,IAAI,EACnB,KAAK,CAAC,QAAQ,CAAC,gBAAgB,CAChC,CAAC;QACF,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,gBAAgB,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IACzC,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport { importDecryptedDocumentSyncUpdates } from \"../../../../data/documents/shared/documentSyncUpdateIsolation\";\nimport type { DecryptedDocumentSyncUpdate } from \"../../../../data/documents/shared/types\";\nimport type { DocumentRecord } from \"../../../../workflows/documents\";\nimport type { DocumentSyncAttempt } from \"../state\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"../state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { extendDocumentVersionCoverage } from \"./versionCoverage\";\n\nfunction sameNullableValue(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n return (left ?? null) === (right ?? null);\n}\n\n/**\n * A response may mutate document content only while the identity and access\n * context used to create its request are still live. Local content fields and\n * the pending marker are deliberately excluded because edits may advance them\n * while the request is in flight.\n */\nexport function documentSyncContextMatches(\n liveRecord: DocumentRecord | null,\n requestRecord: DocumentRecord,\n responseDocumentId: string | null,\n): boolean {\n return (\n liveRecord !== null &&\n liveRecord.id === requestRecord.id &&\n liveRecord.documentId === requestRecord.documentId &&\n liveRecord.documentId === responseDocumentId &&\n liveRecord.containerId === requestRecord.containerId &&\n liveRecord.accessEpoch === requestRecord.accessEpoch &&\n sameNullableValue(\n liveRecord.accessStateHash,\n requestRecord.accessStateHash,\n ) &&\n (liveRecord.effectiveAccessLevel ?? null) ===\n (requestRecord.effectiveAccessLevel ?? null) &&\n sameNullableValue(\n liveRecord.contentKeyBundle,\n requestRecord.contentKeyBundle,\n ) &&\n sameNullableValue(\n liveRecord.documentKekTargets,\n requestRecord.documentKekTargets,\n ) &&\n sameNullableValue(\n liveRecord.documentManifestBundle,\n requestRecord.documentManifestBundle,\n )\n );\n}\n\nexport function importSyncedDocumentUpdates(\n currentDoc: DocumentState,\n updates: readonly DecryptedDocumentSyncUpdate[],\n): DocumentState {\n importDecryptedDocumentSyncUpdates(currentDoc, updates);\n return currentDoc;\n}\n\nexport function applyIncomingSyncedUpdates(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n requestRecord: DocumentRecord,\n syncAttempt: DocumentSyncAttempt,\n expectedGeneration?: DocumentStoreSyncGeneration,\n): DocumentState {\n if (\n (expectedGeneration &&\n !isDocumentStoreSyncGenerationCurrent(state, expectedGeneration)) ||\n !documentSyncContextMatches(\n state.record,\n requestRecord,\n syncAttempt.synced.plan.documentId,\n )\n ) {\n return currentDoc;\n }\n\n const updates = syncAttempt.synced.decryptedUpdates;\n if (updates.length === 0) return currentDoc;\n\n const mergedDoc = importSyncedDocumentUpdates(currentDoc, updates);\n const baseVersion = state.pendingBaseVersion;\n if (baseVersion === null) {\n throw new Error(\"Document sync requires an initialized pending base\");\n }\n // Promote only through update spans proven to be remote. Advancing to the\n // whole merged document would also cross a concurrent deferRemoteSync edit\n // and could permanently classify that local-only operation as synced.\n state.pendingBaseVersion = extendDocumentVersionCoverage({\n baseVersion,\n documentVersion: encodeVersionVector(mergedDoc),\n spans: updates,\n });\n\n if (state.pendingLocalWrites > 0) {\n setReadySnapshot(\n state,\n mergedDoc,\n true,\n state.snapshot.text,\n state.snapshot.structuredFields,\n );\n return mergedDoc;\n }\n\n setReadySnapshot(state, mergedDoc, true);\n return mergedDoc;\n}\n"]}
1
+ {"version":3,"file":"syncUpdateImport.js","sourceRoot":"","sources":["syncUpdateImport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,kCAAkC,EAAE,MAAM,oEA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{ importDecryptedDocumentSyncUpdates } from \"../../../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nimport type { DecryptedDocumentSyncUpdate } from \"../../../../data/documents/shared/types\";\nimport type { DocumentRecord } from \"../../../../workflows/documents\";\nimport type { DocumentSyncAttempt } from \"../state\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"../state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { extendDocumentVersionCoverage } from \"./versionCoverage\";\n\nfunction sameNullableValue(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n return (left ?? null) === (right ?? null);\n}\n\n/**\n * A response may mutate document content only while the identity and access\n * context used to create its request are still live. Local content fields and\n * the pending marker are deliberately excluded because edits may advance them\n * while the request is in flight.\n */\nexport function documentSyncContextMatches(\n liveRecord: DocumentRecord | null,\n requestRecord: DocumentRecord,\n responseDocumentId: string | null,\n): boolean {\n return (\n liveRecord !== null &&\n liveRecord.id === requestRecord.id &&\n liveRecord.documentId === requestRecord.documentId &&\n liveRecord.documentId === responseDocumentId &&\n liveRecord.containerId === requestRecord.containerId &&\n liveRecord.accessEpoch === requestRecord.accessEpoch &&\n sameNullableValue(\n liveRecord.accessStateHash,\n requestRecord.accessStateHash,\n ) &&\n (liveRecord.effectiveAccessLevel ?? null) ===\n (requestRecord.effectiveAccessLevel ?? null) &&\n sameNullableValue(\n liveRecord.contentKeyBundle,\n requestRecord.contentKeyBundle,\n ) &&\n sameNullableValue(\n liveRecord.documentKekTargets,\n requestRecord.documentKekTargets,\n ) &&\n sameNullableValue(\n liveRecord.documentManifestBundle,\n requestRecord.documentManifestBundle,\n )\n );\n}\n\nexport function importSyncedDocumentUpdates(\n currentDoc: DocumentState,\n updates: readonly DecryptedDocumentSyncUpdate[],\n): DocumentState {\n importDecryptedDocumentSyncUpdates(currentDoc, updates);\n return currentDoc;\n}\n\nexport function applyIncomingSyncedUpdates(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n requestRecord: DocumentRecord,\n syncAttempt: DocumentSyncAttempt,\n expectedGeneration?: DocumentStoreSyncGeneration,\n): DocumentState {\n if (\n (expectedGeneration &&\n !isDocumentStoreSyncGenerationCurrent(state, expectedGeneration)) ||\n !documentSyncContextMatches(\n state.record,\n requestRecord,\n syncAttempt.synced.plan.documentId,\n )\n ) {\n return currentDoc;\n }\n\n const updates = syncAttempt.synced.decryptedUpdates;\n if (updates.length === 0) return currentDoc;\n\n const mergedDoc = importSyncedDocumentUpdates(currentDoc, updates);\n const baseVersion = state.pendingBaseVersion;\n if (baseVersion === null) {\n throw new Error(\"Document sync requires an initialized pending base\");\n }\n // Promote only through update spans proven to be remote. Advancing to the\n // whole merged document would also cross a concurrent deferRemoteSync edit\n // and could permanently classify that local-only operation as synced.\n state.pendingBaseVersion = extendDocumentVersionCoverage({\n baseVersion,\n documentVersion: encodeVersionVector(mergedDoc),\n spans: updates,\n });\n\n if (state.pendingLocalWrites > 0) {\n setReadySnapshot(\n state,\n mergedDoc,\n true,\n state.snapshot.text,\n state.snapshot.structuredFields,\n );\n return mergedDoc;\n }\n\n setReadySnapshot(state, mergedDoc, true);\n return mergedDoc;\n}\n"]}