@tearleads/client-sdk 0.1.62 → 0.1.63

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 (653) hide show
  1. package/client/organizations/currentPrincipalMutations.js +5 -5
  2. package/client/organizations/currentPrincipalMutations.js.map +1 -1
  3. package/client/organizations/organizationDataUsage.js +1 -1
  4. package/client/organizations/organizationDataUsage.js.map +1 -1
  5. package/client/organizations/organizationGroupHistory.js +1 -1
  6. package/client/organizations/organizationGroupHistory.js.map +1 -1
  7. package/client/organizations/organizationGroupNameHydration.js +3 -3
  8. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  9. package/client/organizations/organizationHistory.js +2 -2
  10. package/client/organizations/organizationHistory.js.map +1 -1
  11. package/client/organizations/organizationReadModels.js +1 -1
  12. package/client/organizations/organizationReadModels.js.map +1 -1
  13. package/client/organizations/principalContainerMutations.js +1 -1
  14. package/client/organizations/principalContainerMutations.js.map +1 -1
  15. package/client/organizations/principalMutationRecovery.js.map +1 -1
  16. package/client/organizations/principalMutations.js +5 -5
  17. package/client/organizations/principalMutations.js.map +1 -1
  18. package/client/runtime/principalMutationApi.d.ts +1 -1
  19. package/client/runtime/principalMutationApi.js +2 -2
  20. package/client/runtime/principalMutationApi.js.map +1 -1
  21. package/client/runtime/principalMutationDispatch.js +1 -1
  22. package/client/runtime/principalMutationDispatch.js.map +1 -1
  23. package/client/session/index.js +1 -1
  24. package/client/session/index.js.map +1 -1
  25. package/client/session/sessionOrganizationCreation.js +1 -1
  26. package/client/session/sessionOrganizationCreation.js.map +1 -1
  27. package/client/session/sessionPurgeRecovery.js +2 -2
  28. package/client/session/sessionPurgeRecovery.js.map +1 -1
  29. package/package.json +1 -1
  30. package/stores/documents/documentStore/attachmentHydrationCommit.js +1 -1
  31. package/stores/documents/documentStore/attachmentHydrationCommit.js.map +1 -1
  32. package/stores/documents/documentStore/attachmentUploadAttempt.js +1 -1
  33. package/stores/documents/documentStore/syncRemoteSignals.js +1 -1
  34. package/stores/documents/documentStore/syncRemoteSignals.js.map +1 -1
  35. package/stores/documents/documentStore/syncShared.js +1 -1
  36. package/stores/documents/documentStore/syncShared.js.map +1 -1
  37. package/workflows/blobs/detach.js +1 -1
  38. package/workflows/blobs/detach.js.map +1 -1
  39. package/workflows/blobs/{blobChunkDecryption.js → hydration/blobChunkDecryption.js} +3 -3
  40. package/workflows/blobs/hydration/blobChunkDecryption.js.map +1 -0
  41. package/workflows/blobs/{decrypt.d.ts → hydration/decrypt.d.ts} +2 -2
  42. package/workflows/blobs/{decrypt.js → hydration/decrypt.js} +14 -14
  43. package/workflows/blobs/hydration/decrypt.js.map +1 -0
  44. package/workflows/blobs/{hydrate.d.ts → hydration/hydrate.d.ts} +7 -7
  45. package/workflows/blobs/{hydrate.js → hydration/hydrate.js} +5 -5
  46. package/workflows/blobs/hydration/hydrate.js.map +1 -0
  47. package/workflows/blobs/{hydrationResults.js → hydration/hydrationResults.js} +2 -2
  48. package/workflows/blobs/hydration/hydrationResults.js.map +1 -0
  49. package/workflows/blobs/index.d.ts +3 -3
  50. package/workflows/blobs/index.js +3 -3
  51. package/workflows/blobs/index.js.map +1 -1
  52. package/workflows/blobs/{automaticMultipartUpload.js → upload/automaticMultipartUpload.js} +1 -1
  53. package/workflows/blobs/upload/automaticMultipartUpload.js.map +1 -0
  54. package/workflows/blobs/{upload.d.ts → upload/index.d.ts} +2 -2
  55. package/workflows/blobs/{upload.js → upload/index.js} +14 -14
  56. package/workflows/blobs/upload/index.js.map +1 -0
  57. package/workflows/blobs/{multipartFirstParts.js → upload/multipartFirstParts.js} +4 -4
  58. package/workflows/blobs/upload/multipartFirstParts.js.map +1 -0
  59. package/workflows/blobs/{multipartStageFailures.js → upload/multipartStageFailures.js} +1 -1
  60. package/workflows/blobs/upload/multipartStageFailures.js.map +1 -0
  61. package/workflows/blobs/upload/multipartStageResolution.js.map +1 -0
  62. package/workflows/blobs/{multipartUpload.js → upload/multipartUpload.js} +3 -3
  63. package/workflows/blobs/upload/multipartUpload.js.map +1 -0
  64. package/workflows/blobs/{attachmentBindingVerification.js → verification/attachmentBindingVerification.js} +3 -3
  65. package/workflows/blobs/verification/attachmentBindingVerification.js.map +1 -0
  66. package/workflows/blobs/{attachmentDecryptor.js → verification/attachmentDecryptor.js} +3 -3
  67. package/workflows/blobs/verification/attachmentDecryptor.js.map +1 -0
  68. package/workflows/blobs/{attachmentKeyAuthenticator.js → verification/attachmentKeyAuthenticator.js} +5 -5
  69. package/workflows/blobs/verification/attachmentKeyAuthenticator.js.map +1 -0
  70. package/workflows/blobs/{retainedAttachmentVerification.js → verification/retainedAttachmentVerification.js} +5 -5
  71. package/workflows/blobs/verification/retainedAttachmentVerification.js.map +1 -0
  72. package/workflows/blobs/{verifiedWrapScope.js → verification/verifiedWrapScope.js} +2 -2
  73. package/workflows/blobs/verification/verifiedWrapScope.js.map +1 -0
  74. package/workflows/blobs/{writerProjection.js → verification/writerProjection.js} +3 -3
  75. package/workflows/blobs/verification/writerProjection.js.map +1 -0
  76. package/workflows/container-contents/container-state/purgeTree.js.map +1 -1
  77. package/workflows/container-contents/container-state/purgeTreeContainerDeletion.js.map +1 -1
  78. package/workflows/container-contents/container-state/remote.js +1 -1
  79. package/workflows/container-contents/container-state/remote.js.map +1 -1
  80. package/workflows/container-contents/documentLinks/index.d.ts +1 -1
  81. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  82. package/workflows/container-contents/info/containerInfo.d.ts +1 -1
  83. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +1 -1
  84. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  85. package/workflows/container-contents/remoteHydration/destinationRootReload.js +1 -1
  86. package/workflows/container-contents/remoteHydration/destinationRootReload.js.map +1 -1
  87. package/workflows/container-contents/remoteHydration/verifiedDestination.js +1 -1
  88. package/workflows/container-contents/remoteHydration/verifiedDestination.js.map +1 -1
  89. package/workflows/container-contents/tombstones/documentPurge.d.ts +1 -1
  90. package/workflows/container-contents/tombstones/documentPurge.js.map +1 -1
  91. package/workflows/containers/child/currentShareGrantMutation.js +5 -5
  92. package/workflows/containers/child/currentShareGrantMutation.js.map +1 -1
  93. package/workflows/containers/child/currentSharePrincipalPolicy.js +5 -5
  94. package/workflows/containers/child/currentSharePrincipalPolicy.js.map +1 -1
  95. package/workflows/containers/child/runtimeCurrentGroupShare.js +1 -1
  96. package/workflows/containers/child/runtimeCurrentGroupShare.js.map +1 -1
  97. package/workflows/containers/child/share.d.ts +1 -1
  98. package/workflows/containers/child/share.js +4 -4
  99. package/workflows/containers/child/share.js.map +1 -1
  100. package/workflows/containers/child/sharePrincipalPolicy.d.ts +1 -1
  101. package/workflows/containers/child/sharePrincipalPolicy.js +2 -2
  102. package/workflows/containers/child/sharePrincipalPolicy.js.map +1 -1
  103. package/workflows/documents/{attachmentPersistence.d.ts → attachments/attachmentPersistence.d.ts} +2 -2
  104. package/workflows/documents/attachments/attachmentPersistence.js.map +1 -0
  105. package/workflows/documents/{blobMutationLock.d.ts → attachments/blobMutationLock.d.ts} +1 -1
  106. package/workflows/documents/{blobMutationLock.js → attachments/blobMutationLock.js} +1 -1
  107. package/workflows/documents/attachments/blobMutationLock.js.map +1 -0
  108. package/workflows/documents/attachments/orphanBlobReclaimState.js.map +1 -0
  109. package/workflows/documents/{orphanBlobReclaims.d.ts → attachments/orphanBlobReclaims.d.ts} +2 -2
  110. package/workflows/documents/{orphanBlobReclaims.js → attachments/orphanBlobReclaims.js} +3 -3
  111. package/workflows/documents/attachments/orphanBlobReclaims.js.map +1 -0
  112. package/workflows/documents/authorAccessFailure.js.map +1 -1
  113. package/workflows/documents/{createAdoption.js → create/createAdoption.js} +5 -5
  114. package/workflows/documents/create/createAdoption.js.map +1 -0
  115. package/workflows/documents/{createProjection.d.ts → create/createProjection.d.ts} +1 -1
  116. package/workflows/documents/{createProjectionFetch.d.ts → create/createProjectionFetch.d.ts} +2 -2
  117. package/workflows/documents/create/createProjectionFetch.js.map +1 -0
  118. package/workflows/documents/{createResponse.js → create/createResponse.js} +5 -5
  119. package/workflows/documents/create/createResponse.js.map +1 -0
  120. package/workflows/documents/{documentCreationPersistence.js → create/documentCreationPersistence.js} +2 -2
  121. package/workflows/documents/create/documentCreationPersistence.js.map +1 -0
  122. package/workflows/documents/{create.d.ts → create/index.d.ts} +4 -4
  123. package/workflows/documents/{create.js → create/index.js} +10 -10
  124. package/workflows/documents/create/index.js.map +1 -0
  125. package/workflows/documents/documentMutationCommit.js +1 -1
  126. package/workflows/documents/documentMutationCommit.js.map +1 -1
  127. package/workflows/documents/index.d.ts +17 -17
  128. package/workflows/documents/index.js +14 -14
  129. package/workflows/documents/index.js.map +1 -1
  130. package/workflows/documents/{linkSet.d.ts → linkSet/index.d.ts} +5 -5
  131. package/workflows/documents/{linkSet.js → linkSet/index.js} +12 -12
  132. package/workflows/documents/linkSet/index.js.map +1 -0
  133. package/workflows/documents/{linkSetAuthority.js → linkSet/linkSetAuthority.js} +6 -6
  134. package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -0
  135. package/workflows/documents/{linkSetBlobRewraps.js → linkSet/linkSetBlobRewraps.js} +13 -13
  136. package/workflows/documents/linkSet/linkSetBlobRewraps.js.map +1 -0
  137. package/workflows/documents/{linkSetProjectionSeed.js → linkSet/linkSetProjectionSeed.js} +2 -2
  138. package/workflows/documents/linkSet/linkSetProjectionSeed.js.map +1 -0
  139. package/workflows/documents/{linkSetRemote.d.ts → linkSet/linkSetRemote.d.ts} +4 -4
  140. package/workflows/documents/{linkSetRemote.js → linkSet/linkSetRemote.js} +6 -6
  141. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -0
  142. package/workflows/documents/{purge.d.ts → purge/index.d.ts} +5 -5
  143. package/workflows/documents/{purge.js → purge/index.js} +9 -9
  144. package/workflows/documents/purge/index.js.map +1 -0
  145. package/workflows/documents/{persistedDocumentRemoval.d.ts → purge/persistedDocumentRemoval.d.ts} +3 -3
  146. package/workflows/documents/{persistedDocumentRemoval.js → purge/persistedDocumentRemoval.js} +4 -4
  147. package/workflows/documents/purge/persistedDocumentRemoval.js.map +1 -0
  148. package/workflows/documents/{subtreePurgeScope.d.ts → purge/subtreePurgeScope.d.ts} +1 -1
  149. package/workflows/documents/{subtreePurgeScope.js → purge/subtreePurgeScope.js} +2 -2
  150. package/workflows/documents/purge/subtreePurgeScope.js.map +1 -0
  151. package/workflows/documents/rotationBaseline.js +1 -1
  152. package/workflows/documents/rotationBaseline.js.map +1 -1
  153. package/workflows/documents/{sync.d.ts → sync/index.d.ts} +1 -1
  154. package/workflows/documents/{sync.js → sync/index.js} +11 -11
  155. package/workflows/documents/sync/index.js.map +1 -0
  156. package/workflows/documents/{initialSync.js → sync/initialSync.js} +5 -5
  157. package/workflows/documents/sync/initialSync.js.map +1 -0
  158. package/workflows/documents/{readOnlyProjectionFailure.js → sync/readOnlyProjectionFailure.js} +5 -5
  159. package/workflows/documents/sync/readOnlyProjectionFailure.js.map +1 -0
  160. package/workflows/documents/{readOnlySync.d.ts → sync/readOnlySync.d.ts} +9 -9
  161. package/workflows/documents/{readOnlySync.js → sync/readOnlySync.js} +11 -11
  162. package/workflows/documents/sync/readOnlySync.js.map +1 -0
  163. package/workflows/documents/sync/reportDocumentSyncQuarantine.js.map +1 -0
  164. package/workflows/documents/{syncAttemptPlanning.js → sync/syncAttemptPlanning.js} +9 -9
  165. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -0
  166. package/workflows/documents/{syncAttemptState.d.ts → sync/syncAttemptState.d.ts} +5 -5
  167. package/workflows/documents/sync/syncAttemptState.js.map +1 -0
  168. package/workflows/documents/{syncLane.d.ts → sync/syncLane.d.ts} +3 -3
  169. package/workflows/documents/{syncLane.js → sync/syncLane.js} +2 -2
  170. package/workflows/documents/sync/syncLane.js.map +1 -0
  171. package/workflows/documents/{syncResponseResult.js → sync/syncResponseResult.js} +9 -9
  172. package/workflows/documents/sync/syncResponseResult.js.map +1 -0
  173. package/workflows/documents/{syncSubmittedResult.js → sync/syncSubmittedResult.js} +6 -6
  174. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -0
  175. package/workflows/documents/{syncTrace.js → sync/syncTrace.js} +1 -1
  176. package/workflows/documents/{syncFailures.js → syncFailures/index.js} +5 -5
  177. package/workflows/documents/syncFailures/index.js.map +1 -0
  178. package/workflows/documents/{syncAbandon.js → syncFailures/syncAbandon.js} +1 -1
  179. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -0
  180. package/workflows/documents/{syncFailureClassification.d.ts → syncFailures/syncFailureClassification.d.ts} +2 -2
  181. package/workflows/documents/{syncFailureClassification.js → syncFailures/syncFailureClassification.js} +6 -6
  182. package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -0
  183. package/workflows/documents/{syncPolicyRepair.js → syncFailures/syncPolicyRepair.js} +3 -3
  184. package/workflows/documents/syncFailures/syncPolicyRepair.js.map +1 -0
  185. package/workflows/documents/syncFailures/syncRepairAbandon.js.map +1 -0
  186. package/workflows/documents/{syncRepairAccess.js → syncFailures/syncRepairAccess.js} +2 -2
  187. package/workflows/documents/syncFailures/syncRepairAccess.js.map +1 -0
  188. package/workflows/documents/{syncContentKeys.d.ts → syncPlan/syncContentKeys.d.ts} +4 -4
  189. package/workflows/documents/{syncContentKeys.js → syncPlan/syncContentKeys.js} +8 -8
  190. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -0
  191. package/workflows/documents/{syncPlanIdentity.js → syncPlan/syncPlanIdentity.js} +3 -3
  192. package/workflows/documents/syncPlan/syncPlanIdentity.js.map +1 -0
  193. package/workflows/documents/{syncPlanMaterial.js → syncPlan/syncPlanMaterial.js} +9 -9
  194. package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -0
  195. package/workflows/documents/syncPlan/syncPlanProjection.js.map +1 -0
  196. package/workflows/documents/{syncPlanRequestBounds.js → syncPlan/syncPlanRequestBounds.js} +1 -1
  197. package/workflows/documents/syncPlan/syncPlanRequestBounds.js.map +1 -0
  198. package/workflows/documents/{syncAutomaticContainerRekeys.js → syncRekeys/syncAutomaticContainerRekeys.js} +10 -10
  199. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -0
  200. package/workflows/documents/{syncContainerRekeyPreparation.js → syncRekeys/syncContainerRekeyPreparation.js} +11 -11
  201. package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js.map +1 -0
  202. package/workflows/documents/{syncContainerRekeyProjection.js → syncRekeys/syncContainerRekeyProjection.js} +2 -2
  203. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js.map +1 -0
  204. package/workflows/documents/{syncContainerRekeys.js → syncRekeys/syncContainerRekeys.js} +3 -3
  205. package/workflows/documents/syncRekeys/syncContainerRekeys.js.map +1 -0
  206. package/workflows/documents/{syncRecoveryRekey.d.ts → syncRekeys/syncRecoveryRekey.d.ts} +4 -4
  207. package/workflows/documents/{syncRecoveryRekey.js → syncRekeys/syncRecoveryRekey.js} +4 -4
  208. package/workflows/documents/syncRekeys/syncRecoveryRekey.js.map +1 -0
  209. package/workflows/documents/{syncRekeyCommit.js → syncRekeys/syncRekeyCommit.js} +1 -1
  210. package/workflows/organizations/{currentGroupMetadataAuthority.js → groupMetadata/currentGroupMetadataAuthority.js} +5 -5
  211. package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js.map +1 -0
  212. package/workflows/organizations/{groupMetadataAccess.d.ts → groupMetadata/groupMetadataAccess.d.ts} +5 -5
  213. package/workflows/organizations/{groupMetadataAccess.js → groupMetadata/groupMetadataAccess.js} +6 -6
  214. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -0
  215. package/workflows/organizations/{groupMetadataBinding.js → groupMetadata/groupMetadataBinding.js} +1 -1
  216. package/workflows/organizations/groupMetadata/groupMetadataBinding.js.map +1 -0
  217. package/workflows/organizations/{groupMetadataContainerAuthority.js → groupMetadata/groupMetadataContainerAuthority.js} +6 -6
  218. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -0
  219. package/workflows/organizations/{groupMetadataErrors.js → groupMetadata/groupMetadataErrors.js} +1 -1
  220. package/workflows/organizations/{groupMetadataRootBinding.js → groupMetadata/groupMetadataRootBinding.js} +3 -3
  221. package/workflows/organizations/groupMetadata/groupMetadataRootBinding.js.map +1 -0
  222. package/workflows/organizations/{groupMetadataRuntime.js → groupMetadata/groupMetadataRuntime.js} +4 -4
  223. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js.map +1 -0
  224. package/workflows/organizations/{runtimeGroupMetadataAuthority.js → groupMetadata/runtimeGroupMetadataAuthority.js} +2 -2
  225. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js.map +1 -0
  226. package/workflows/organizations/{currentOrganizationGroupNames.js → groupNames/currentOrganizationGroupNames.js} +8 -8
  227. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -0
  228. package/workflows/organizations/{groupMembershipName.d.ts → groupNames/groupMembershipName.d.ts} +3 -3
  229. package/workflows/organizations/{groupMembershipName.js → groupNames/groupMembershipName.js} +2 -2
  230. package/workflows/organizations/groupNames/groupMembershipName.js.map +1 -0
  231. package/workflows/organizations/{groupNameUniqueness.js → groupNames/groupNameUniqueness.js} +11 -11
  232. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -0
  233. package/workflows/organizations/{organizationGroupNamePolicies.js → groupNames/organizationGroupNamePolicies.js} +5 -5
  234. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -0
  235. package/workflows/organizations/{organizationGroupNames.js → groupNames/organizationGroupNames.js} +1 -1
  236. package/workflows/organizations/groupNames/organizationGroupNames.js.map +1 -0
  237. package/workflows/organizations/{commitCurrentGroupPolicyMutation.js → groupPolicy/commitCurrentGroupPolicyMutation.js} +4 -4
  238. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -0
  239. package/workflows/organizations/{currentGroupPolicyMutationContext.js → groupPolicy/currentGroupPolicyMutationContext.js} +7 -7
  240. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -0
  241. package/workflows/organizations/{currentPolicyMutationAcknowledgement.js → groupPolicy/currentPolicyMutationAcknowledgement.js} +3 -3
  242. package/workflows/organizations/groupPolicy/currentPolicyMutationAcknowledgement.js.map +1 -0
  243. package/workflows/organizations/{groupPolicyMutationAcknowledgement.js → groupPolicy/groupPolicyMutationAcknowledgement.js} +4 -4
  244. package/workflows/organizations/groupPolicy/groupPolicyMutationAcknowledgement.js.map +1 -0
  245. package/workflows/organizations/{groupPolicyMutationContext.d.ts → groupPolicy/groupPolicyMutationContext.d.ts} +8 -8
  246. package/workflows/organizations/{groupPolicyMutationContext.js → groupPolicy/groupPolicyMutationContext.js} +5 -5
  247. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -0
  248. package/workflows/organizations/{groupPolicyMutationEvidence.d.ts → groupPolicy/groupPolicyMutationEvidence.d.ts} +4 -4
  249. package/workflows/organizations/{groupPolicyMutationEvidence.js → groupPolicy/groupPolicyMutationEvidence.js} +3 -3
  250. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js.map +1 -0
  251. package/workflows/organizations/{groupPolicyMutationHead.js → groupPolicy/groupPolicyMutationHead.js} +1 -1
  252. package/workflows/organizations/{groupPolicyRequests.js → groupPolicy/groupPolicyRequests.js} +5 -5
  253. package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -0
  254. package/workflows/organizations/{groupPolicyVerification.js → groupPolicy/groupPolicyVerification.js} +5 -5
  255. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -0
  256. package/workflows/organizations/{submitGroupPolicyCommit.d.ts → groupPolicy/submitGroupPolicyCommit.d.ts} +3 -3
  257. package/workflows/organizations/{submitGroupPolicyCommit.js → groupPolicy/submitGroupPolicyCommit.js} +1 -1
  258. package/workflows/organizations/groupPolicy/submitGroupPolicyCommit.js.map +1 -0
  259. package/workflows/organizations/{createCurrentOrganizationGroup.js → groups/createCurrentOrganizationGroup.js} +9 -9
  260. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -0
  261. package/workflows/organizations/{deleteCurrentOrganizationGroup.js → groups/deleteCurrentOrganizationGroup.js} +2 -2
  262. package/workflows/organizations/groups/deleteCurrentOrganizationGroup.js.map +1 -0
  263. package/workflows/organizations/{deleteOrganizationGroup.d.ts → groups/deleteOrganizationGroup.d.ts} +6 -6
  264. package/workflows/organizations/{deleteOrganizationGroup.js → groups/deleteOrganizationGroup.js} +6 -6
  265. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -0
  266. package/workflows/organizations/{groupCreation.d.ts → groups/groupCreation.d.ts} +7 -7
  267. package/workflows/organizations/{groupCreation.js → groups/groupCreation.js} +4 -4
  268. package/workflows/organizations/groups/groupCreation.js.map +1 -0
  269. package/workflows/organizations/{organizationGroupDirectory.js → groups/organizationGroupDirectory.js} +10 -10
  270. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -0
  271. package/workflows/organizations/index.d.ts +13 -13
  272. package/workflows/organizations/index.js +12 -12
  273. package/workflows/organizations/index.js.map +1 -1
  274. package/workflows/organizations/policyHistory/groupPolicyHistoryPage.js.map +1 -0
  275. package/workflows/organizations/{loadPolicyHistoryDetails.js → policyHistory/loadPolicyHistoryDetails.js} +5 -5
  276. package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js.map +1 -0
  277. package/workflows/organizations/{organizationPolicyHistoryDetails.js → policyHistory/organizationPolicyHistoryDetails.js} +2 -2
  278. package/workflows/organizations/policyHistory/organizationPolicyHistoryDetails.js.map +1 -0
  279. package/workflows/organizations/{organizationPolicyHistoryVerification.js → policyHistory/organizationPolicyHistoryVerification.js} +2 -2
  280. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js.map +1 -0
  281. package/workflows/organizations/{policyHistoryAccessDenial.js → policyHistory/policyHistoryAccessDenial.js} +3 -3
  282. package/workflows/organizations/policyHistory/policyHistoryAccessDenial.js.map +1 -0
  283. package/workflows/organizations/{policyHistoryCache.js → policyHistory/policyHistoryCache.js} +1 -1
  284. package/workflows/organizations/policyHistory/policyHistoryCache.js.map +1 -0
  285. package/workflows/organizations/{policyHistoryReadModel.d.ts → policyHistory/policyHistoryReadModel.d.ts} +1 -1
  286. package/workflows/organizations/{policyHistoryTypes.d.ts → policyHistory/policyHistoryTypes.d.ts} +1 -1
  287. package/workflows/organizations/{acknowledgedDirectoryBindings.js → principalMutations/acknowledgedDirectoryBindings.js} +2 -2
  288. package/workflows/organizations/principalMutations/acknowledgedDirectoryBindings.js.map +1 -0
  289. package/workflows/organizations/{currentGroupMutationReferences.js → principalMutations/currentGroupMutationReferences.js} +2 -2
  290. package/workflows/organizations/principalMutations/currentGroupMutationReferences.js.map +1 -0
  291. package/workflows/organizations/{currentOrganizationMutationAuthority.js → principalMutations/currentOrganizationMutationAuthority.js} +3 -3
  292. package/workflows/organizations/principalMutations/currentOrganizationMutationAuthority.js.map +1 -0
  293. package/workflows/organizations/{currentOrganizationMutationRetention.js → principalMutations/currentOrganizationMutationRetention.js} +4 -4
  294. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -0
  295. package/workflows/organizations/{currentPrincipalMutationLease.js → principalMutations/currentPrincipalMutationLease.js} +6 -6
  296. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js.map +1 -0
  297. package/workflows/organizations/{principalMutationJournalManagement.d.ts → principalMutations/principalMutationJournalManagement.d.ts} +1 -1
  298. package/workflows/organizations/{principalMutationJournalManagement.js → principalMutations/principalMutationJournalManagement.js} +7 -7
  299. package/workflows/organizations/principalMutations/principalMutationJournalManagement.js.map +1 -0
  300. package/workflows/organizations/{principalMutationJournalSession.d.ts → principalMutations/principalMutationJournalSession.d.ts} +4 -4
  301. package/workflows/organizations/{principalMutationJournalSession.js → principalMutations/principalMutationJournalSession.js} +4 -4
  302. package/workflows/organizations/principalMutations/principalMutationJournalSession.js.map +1 -0
  303. package/workflows/organizations/{principalMutationReceipt.js → principalMutations/principalMutationReceipt.js} +3 -3
  304. package/workflows/organizations/principalMutations/principalMutationReceipt.js.map +1 -0
  305. package/workflows/organizations/{principalOperationReceipt.d.ts → principalMutations/principalOperationReceipt.d.ts} +2 -2
  306. package/workflows/organizations/{principalOperationReceipt.js → principalMutations/principalOperationReceipt.js} +3 -3
  307. package/workflows/organizations/principalMutations/principalOperationReceipt.js.map +1 -0
  308. package/workflows/organizations/principalMutations/retainAcknowledgedPrincipalCurrents.d.ts +6 -0
  309. package/workflows/organizations/{retainAcknowledgedPrincipalCurrents.js → principalMutations/retainAcknowledgedPrincipalCurrents.js} +4 -4
  310. package/workflows/organizations/principalMutations/retainAcknowledgedPrincipalCurrents.js.map +1 -0
  311. package/workflows/organizations/{runtimeCurrentGroupMutation.js → principalMutations/runtimeCurrentGroupMutation.js} +5 -5
  312. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -0
  313. package/workflows/organizations/{runtimeCurrentOrganizationMutation.js → principalMutations/runtimeCurrentOrganizationMutation.js} +2 -2
  314. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -0
  315. package/workflows/organizations/{principalPolicy.d.ts → principalPolicy/index.d.ts} +8 -8
  316. package/workflows/organizations/{principalPolicy.js → principalPolicy/index.js} +9 -9
  317. package/workflows/organizations/principalPolicy/index.js.map +1 -0
  318. package/workflows/organizations/{principalPolicyApi.d.ts → principalPolicy/principalPolicyApi.d.ts} +4 -4
  319. package/workflows/organizations/principalPolicy/principalPolicyApi.js.map +1 -0
  320. package/workflows/organizations/{principalPolicyReceiptArtifacts.js → principalPolicy/principalPolicyReceiptArtifacts.js} +2 -2
  321. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -0
  322. package/workflows/organizations/{principalPolicyRecipients.js → principalPolicy/principalPolicyRecipients.js} +2 -2
  323. package/workflows/organizations/principalPolicy/principalPolicyRecipients.js.map +1 -0
  324. package/workflows/organizations/{principalPolicyRequest.d.ts → principalPolicy/principalPolicyRequest.d.ts} +3 -3
  325. package/workflows/organizations/{principalPolicyRequest.js → principalPolicy/principalPolicyRequest.js} +2 -2
  326. package/workflows/organizations/{createOrganization.d.ts → provisioning/createOrganization.d.ts} +7 -7
  327. package/workflows/organizations/{createOrganization.js → provisioning/createOrganization.js} +3 -3
  328. package/workflows/organizations/provisioning/createOrganization.js.map +1 -0
  329. package/workflows/organizations/{organizationProvisioningAttempt.d.ts → provisioning/organizationProvisioningAttempt.d.ts} +3 -3
  330. package/workflows/organizations/{organizationProvisioningAttempt.js → provisioning/organizationProvisioningAttempt.js} +6 -6
  331. package/workflows/organizations/provisioning/organizationProvisioningAttempt.js.map +1 -0
  332. package/workflows/organizations/{organizationReplacementVerification.js → provisioning/organizationReplacementVerification.js} +2 -2
  333. package/workflows/organizations/provisioning/organizationReplacementVerification.js.map +1 -0
  334. package/workflows/organizations/{dataUsageReadModel.d.ts → readModel/dataUsageReadModel.d.ts} +3 -3
  335. package/workflows/organizations/{dataUsageReadModel.js → readModel/dataUsageReadModel.js} +2 -2
  336. package/workflows/organizations/readModel/dataUsageReadModel.js.map +1 -0
  337. package/workflows/organizations/{readModel.d.ts → readModel/index.d.ts} +5 -5
  338. package/workflows/organizations/{readModel.js → readModel/index.js} +2 -2
  339. package/workflows/organizations/readModel/index.js.map +1 -0
  340. package/workflows/organizations/{listLocalOrganizations.d.ts → readModel/listLocalOrganizations.d.ts} +1 -1
  341. package/workflows/organizations/{listLocalOrganizations.js → readModel/listLocalOrganizations.js} +8 -8
  342. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -0
  343. package/workflows/organizations/{localReadModelDetails.d.ts → readModel/localReadModelDetails.d.ts} +3 -3
  344. package/workflows/organizations/{localReadModelDetails.js → readModel/localReadModelDetails.js} +6 -6
  345. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -0
  346. package/workflows/organizations/{organizationPresentationAccessState.js → readModel/organizationPresentationAccessState.js} +1 -1
  347. package/workflows/organizations/readModel/organizationPresentationAccessState.js.map +1 -0
  348. package/workflows/organizations/{organizationPresentationFailures.js → readModel/organizationPresentationFailures.js} +1 -1
  349. package/workflows/organizations/{readModelProjection.d.ts → readModel/readModelProjection.d.ts} +5 -5
  350. package/workflows/organizations/{readModelProjection.js → readModel/readModelProjection.js} +6 -6
  351. package/workflows/organizations/readModel/readModelProjection.js.map +1 -0
  352. package/workflows/organizations/{authoredPrincipalPolicyWarmer.js → rematerialization/authoredPrincipalPolicyWarmer.js} +2 -2
  353. package/workflows/organizations/rematerialization/authoredPrincipalPolicyWarmer.js.map +1 -0
  354. package/workflows/organizations/{precedingPrincipalRematerialization.js → rematerialization/precedingPrincipalRematerialization.js} +1 -1
  355. package/workflows/organizations/rematerialization/precedingPrincipalRematerialization.js.map +1 -0
  356. package/workflows/organizations/{principalContainerRematerialization.js → rematerialization/principalContainerRematerialization.js} +13 -13
  357. package/workflows/organizations/rematerialization/principalContainerRematerialization.js.map +1 -0
  358. package/workflows/organizations/{principalContainerRematerializationPlanning.js → rematerialization/principalContainerRematerializationPlanning.js} +2 -2
  359. package/workflows/organizations/rematerialization/principalContainerRematerializationPlanning.js.map +1 -0
  360. package/workflows/organizations/{principalContainerRematerializationTargets.js → rematerialization/principalContainerRematerializationTargets.js} +3 -3
  361. package/workflows/organizations/rematerialization/principalContainerRematerializationTargets.js.map +1 -0
  362. package/workflows/principals/{acknowledgedPrincipalCurrents.d.ts → acknowledgements/acknowledgedPrincipalCurrents.d.ts} +6 -6
  363. package/workflows/principals/{acknowledgedPrincipalCurrents.js → acknowledgements/acknowledgedPrincipalCurrents.js} +7 -7
  364. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -0
  365. package/workflows/principals/{acknowledgedPrincipalPredecessor.d.ts → acknowledgements/acknowledgedPrincipalPredecessor.d.ts} +10 -10
  366. package/workflows/principals/{acknowledgedPrincipalPredecessor.js → acknowledgements/acknowledgedPrincipalPredecessor.js} +9 -9
  367. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -0
  368. package/workflows/principals/{initialPrincipalCurrentPublication.js → acknowledgements/initialPrincipalCurrentPublication.js} +7 -7
  369. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -0
  370. package/workflows/principals/{principalAcknowledgementChecks.d.ts → acknowledgements/principalAcknowledgementChecks.d.ts} +3 -3
  371. package/workflows/principals/{principalCurrentPublicationSeal.js → acknowledgements/principalCurrentPublicationSeal.js} +3 -3
  372. package/workflows/principals/acknowledgements/principalCurrentPublicationSeal.js.map +1 -0
  373. package/workflows/principals/{reconcileAcknowledgedPrincipalCurrent.js → acknowledgements/reconcileAcknowledgedPrincipalCurrent.js} +6 -6
  374. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -0
  375. package/workflows/principals/{loadRecoveredPrincipalHistoryPage.d.ts → historyRecovery/loadRecoveredPrincipalHistoryPage.d.ts} +1 -1
  376. package/workflows/principals/{loadRecoveredPrincipalHistoryPage.js → historyRecovery/loadRecoveredPrincipalHistoryPage.js} +7 -7
  377. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -0
  378. package/workflows/principals/{principalHistoryRecoveryAuthority.js → historyRecovery/principalHistoryRecoveryAuthority.js} +2 -2
  379. package/workflows/principals/historyRecovery/principalHistoryRecoveryAuthority.js.map +1 -0
  380. package/workflows/principals/{principalHistoryRecoveryPrefix.js → historyRecovery/principalHistoryRecoveryPrefix.js} +5 -5
  381. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js.map +1 -0
  382. package/workflows/principals/{principalHistoryRecoveryReferences.js → historyRecovery/principalHistoryRecoveryReferences.js} +4 -4
  383. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -0
  384. package/workflows/principals/{principalHistoryRecoveryStage.js → historyRecovery/principalHistoryRecoveryStage.js} +4 -4
  385. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js.map +1 -0
  386. package/workflows/principals/{principalHistoryRecoveryTypes.d.ts → historyRecovery/principalHistoryRecoveryTypes.d.ts} +5 -5
  387. package/workflows/principals/{principalHistoryRecoveryTypes.js → historyRecovery/principalHistoryRecoveryTypes.js} +1 -1
  388. package/workflows/principals/historyRecovery/principalHistoryRecoveryTypes.js.map +1 -0
  389. package/workflows/principals/{principalHistoryRecoveryVerification.js → historyRecovery/principalHistoryRecoveryVerification.js} +1 -1
  390. package/workflows/principals/{recoverCurrentOrganizationPolicy.js → historyRecovery/recoverCurrentOrganizationPolicy.js} +4 -4
  391. package/workflows/principals/historyRecovery/recoverCurrentOrganizationPolicy.js.map +1 -0
  392. package/workflows/principals/{recoverPrincipalHistoryPage.js → historyRecovery/recoverPrincipalHistoryPage.js} +2 -2
  393. package/workflows/principals/{recoverPrincipalPolicyHistory.js → historyRecovery/recoverPrincipalPolicyHistory.js} +8 -8
  394. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -0
  395. package/workflows/principals/{recoverScopedPrincipalPolicyHistory.d.ts → historyRecovery/recoverScopedPrincipalPolicyHistory.d.ts} +3 -3
  396. package/workflows/principals/{recoverScopedPrincipalPolicyHistory.js → historyRecovery/recoverScopedPrincipalPolicyHistory.js} +7 -7
  397. package/workflows/principals/historyRecovery/recoverScopedPrincipalPolicyHistory.js.map +1 -0
  398. package/workflows/principals/index.d.ts +6 -6
  399. package/workflows/principals/index.js +6 -6
  400. package/workflows/principals/index.js.map +1 -1
  401. package/workflows/principals/{policyCache.d.ts → policyCache/index.d.ts} +5 -5
  402. package/workflows/principals/{policyCache.js → policyCache/index.js} +10 -10
  403. package/workflows/principals/policyCache/index.js.map +1 -0
  404. package/workflows/principals/{principalPolicyCacheAdvance.js → policyCache/principalPolicyCacheAdvance.js} +2 -2
  405. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -0
  406. package/workflows/principals/{principalPolicyCacheValidation.js → policyCache/principalPolicyCacheValidation.js} +3 -3
  407. package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -0
  408. package/workflows/principals/{principalPolicyOrganizationScope.js → policyCache/principalPolicyOrganizationScope.js} +7 -7
  409. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -0
  410. package/workflows/principals/{publicPrincipalHistoryAuthority.js → publicHistory/publicPrincipalHistoryAuthority.js} +3 -3
  411. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -0
  412. package/workflows/principals/{publicPrincipalHistoryPage.js → publicHistory/publicPrincipalHistoryPage.js} +6 -6
  413. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -0
  414. package/workflows/principals/{publicPrincipalHistoryProgress.js → publicHistory/publicPrincipalHistoryProgress.js} +8 -8
  415. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -0
  416. package/workflows/principals/{publicPrincipalHistoryTypes.d.ts → publicHistory/publicPrincipalHistoryTypes.d.ts} +7 -7
  417. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.js.map +1 -0
  418. package/workflows/principals/{publicProjectionDirectory.js → publicHistory/publicProjectionDirectory.js} +2 -2
  419. package/workflows/principals/publicHistory/publicProjectionDirectory.js.map +1 -0
  420. package/workflows/principals/{publicProjectionPrincipal.js → publicHistory/publicProjectionPrincipal.js} +4 -4
  421. package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -0
  422. package/workflows/principals/{recoverProjectionPolicyHistory.d.ts → publicHistory/recoverProjectionPolicyHistory.d.ts} +2 -2
  423. package/workflows/principals/{recoverProjectionPolicyHistory.js → publicHistory/recoverProjectionPolicyHistory.js} +3 -3
  424. package/workflows/principals/publicHistory/recoverProjectionPolicyHistory.js.map +1 -0
  425. package/workflows/principals/{recoverPublicPrincipalHistory.js → publicHistory/recoverPublicPrincipalHistory.js} +7 -7
  426. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -0
  427. package/workflows/principals/{selectPublicPrincipalHistory.js → publicHistory/selectPublicPrincipalHistory.js} +5 -5
  428. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -0
  429. package/workflows/principals/{principalCurrentRecoveryBatch.js → recoveryOperation/principalCurrentRecoveryBatch.js} +2 -2
  430. package/workflows/principals/recoveryOperation/principalCurrentRecoveryBatch.js.map +1 -0
  431. package/workflows/principals/{principalRecoveryDirectory.d.ts → recoveryOperation/principalRecoveryDirectory.d.ts} +3 -3
  432. package/workflows/principals/{principalRecoveryDirectory.js → recoveryOperation/principalRecoveryDirectory.js} +9 -9
  433. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -0
  434. package/workflows/principals/recoveryOperation/principalRecoveryDiscoveryPage.js.map +1 -0
  435. package/workflows/principals/{principalRecoveryLocalPreference.js → recoveryOperation/principalRecoveryLocalPreference.js} +4 -4
  436. package/workflows/principals/recoveryOperation/principalRecoveryLocalPreference.js.map +1 -0
  437. package/workflows/principals/{principalRecoveryMemo.d.ts → recoveryOperation/principalRecoveryMemo.d.ts} +2 -2
  438. package/workflows/principals/{principalRecoveryMemo.js → recoveryOperation/principalRecoveryMemo.js} +4 -4
  439. package/workflows/principals/recoveryOperation/principalRecoveryMemo.js.map +1 -0
  440. package/workflows/principals/{principalRecoveryMemoValidity.js → recoveryOperation/principalRecoveryMemoValidity.js} +2 -2
  441. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js.map +1 -0
  442. package/workflows/principals/{principalRecoveryOutage.js → recoveryOperation/principalRecoveryOutage.js} +5 -5
  443. package/workflows/principals/recoveryOperation/principalRecoveryOutage.js.map +1 -0
  444. package/workflows/principals/runtimePolicyRecovery.js +3 -3
  445. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  446. package/workflows/principals/runtimeProjectionPolicyRecovery.js +3 -3
  447. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  448. package/workflows/registration/organizationProvisioningArtifacts.d.ts +1 -1
  449. package/workflows/registration/provisionedPrincipalHistory.js +1 -1
  450. package/workflows/registration/provisionedPrincipalHistory.js.map +1 -1
  451. package/workflows/registration/provisionedProfileDocument.js +1 -1
  452. package/workflows/registration/provisionedProfileDocument.js.map +1 -1
  453. package/workflows/registration/provisioningBootstrapBuilders.js +2 -2
  454. package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
  455. package/workflows/registration/registerIdentity.js +2 -2
  456. package/workflows/registration/registerIdentity.js.map +1 -1
  457. package/workflows/sync/remoteReset.js +1 -1
  458. package/workflows/sync/remoteReset.js.map +1 -1
  459. package/workflows/blobs/attachmentBindingVerification.js.map +0 -1
  460. package/workflows/blobs/attachmentDecryptor.js.map +0 -1
  461. package/workflows/blobs/attachmentKeyAuthenticator.js.map +0 -1
  462. package/workflows/blobs/automaticMultipartUpload.js.map +0 -1
  463. package/workflows/blobs/blobChunkDecryption.js.map +0 -1
  464. package/workflows/blobs/decrypt.js.map +0 -1
  465. package/workflows/blobs/hydrate.js.map +0 -1
  466. package/workflows/blobs/hydrationResults.js.map +0 -1
  467. package/workflows/blobs/multipartFirstParts.js.map +0 -1
  468. package/workflows/blobs/multipartStageFailures.js.map +0 -1
  469. package/workflows/blobs/multipartStageResolution.js.map +0 -1
  470. package/workflows/blobs/multipartUpload.js.map +0 -1
  471. package/workflows/blobs/retainedAttachmentVerification.js.map +0 -1
  472. package/workflows/blobs/upload.js.map +0 -1
  473. package/workflows/blobs/verifiedWrapScope.js.map +0 -1
  474. package/workflows/blobs/writerProjection.js.map +0 -1
  475. package/workflows/documents/attachmentPersistence.js.map +0 -1
  476. package/workflows/documents/blobMutationLock.js.map +0 -1
  477. package/workflows/documents/create.js.map +0 -1
  478. package/workflows/documents/createAdoption.js.map +0 -1
  479. package/workflows/documents/createProjectionFetch.js.map +0 -1
  480. package/workflows/documents/createResponse.js.map +0 -1
  481. package/workflows/documents/documentCreationPersistence.js.map +0 -1
  482. package/workflows/documents/initialSync.js.map +0 -1
  483. package/workflows/documents/linkSet.js.map +0 -1
  484. package/workflows/documents/linkSetAuthority.js.map +0 -1
  485. package/workflows/documents/linkSetBlobRewraps.js.map +0 -1
  486. package/workflows/documents/linkSetProjectionSeed.js.map +0 -1
  487. package/workflows/documents/linkSetRemote.js.map +0 -1
  488. package/workflows/documents/orphanBlobReclaimState.js.map +0 -1
  489. package/workflows/documents/orphanBlobReclaims.js.map +0 -1
  490. package/workflows/documents/persistedDocumentRemoval.js.map +0 -1
  491. package/workflows/documents/purge.js.map +0 -1
  492. package/workflows/documents/readOnlyProjectionFailure.js.map +0 -1
  493. package/workflows/documents/readOnlySync.js.map +0 -1
  494. package/workflows/documents/reportDocumentSyncQuarantine.js.map +0 -1
  495. package/workflows/documents/subtreePurgeScope.js.map +0 -1
  496. package/workflows/documents/sync.js.map +0 -1
  497. package/workflows/documents/syncAbandon.js.map +0 -1
  498. package/workflows/documents/syncAttemptPlanning.js.map +0 -1
  499. package/workflows/documents/syncAttemptState.js.map +0 -1
  500. package/workflows/documents/syncAutomaticContainerRekeys.js.map +0 -1
  501. package/workflows/documents/syncContainerRekeyPreparation.js.map +0 -1
  502. package/workflows/documents/syncContainerRekeyProjection.js.map +0 -1
  503. package/workflows/documents/syncContainerRekeys.js.map +0 -1
  504. package/workflows/documents/syncContentKeys.js.map +0 -1
  505. package/workflows/documents/syncFailureClassification.js.map +0 -1
  506. package/workflows/documents/syncFailures.js.map +0 -1
  507. package/workflows/documents/syncLane.js.map +0 -1
  508. package/workflows/documents/syncPlanIdentity.js.map +0 -1
  509. package/workflows/documents/syncPlanMaterial.js.map +0 -1
  510. package/workflows/documents/syncPlanProjection.js.map +0 -1
  511. package/workflows/documents/syncPlanRequestBounds.js.map +0 -1
  512. package/workflows/documents/syncPolicyRepair.js.map +0 -1
  513. package/workflows/documents/syncRecoveryRekey.js.map +0 -1
  514. package/workflows/documents/syncRepairAbandon.js.map +0 -1
  515. package/workflows/documents/syncRepairAccess.js.map +0 -1
  516. package/workflows/documents/syncResponseResult.js.map +0 -1
  517. package/workflows/documents/syncSubmittedResult.js.map +0 -1
  518. package/workflows/organizations/acknowledgedDirectoryBindings.js.map +0 -1
  519. package/workflows/organizations/authoredPrincipalPolicyWarmer.js.map +0 -1
  520. package/workflows/organizations/commitCurrentGroupPolicyMutation.js.map +0 -1
  521. package/workflows/organizations/createCurrentOrganizationGroup.js.map +0 -1
  522. package/workflows/organizations/createOrganization.js.map +0 -1
  523. package/workflows/organizations/currentGroupMetadataAuthority.js.map +0 -1
  524. package/workflows/organizations/currentGroupMutationReferences.js.map +0 -1
  525. package/workflows/organizations/currentGroupPolicyMutationContext.js.map +0 -1
  526. package/workflows/organizations/currentOrganizationGroupNames.js.map +0 -1
  527. package/workflows/organizations/currentOrganizationMutationAuthority.js.map +0 -1
  528. package/workflows/organizations/currentOrganizationMutationRetention.js.map +0 -1
  529. package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +0 -1
  530. package/workflows/organizations/currentPrincipalMutationLease.js.map +0 -1
  531. package/workflows/organizations/dataUsageReadModel.js.map +0 -1
  532. package/workflows/organizations/deleteCurrentOrganizationGroup.js.map +0 -1
  533. package/workflows/organizations/deleteOrganizationGroup.js.map +0 -1
  534. package/workflows/organizations/groupCreation.js.map +0 -1
  535. package/workflows/organizations/groupMembershipName.js.map +0 -1
  536. package/workflows/organizations/groupMetadataAccess.js.map +0 -1
  537. package/workflows/organizations/groupMetadataBinding.js.map +0 -1
  538. package/workflows/organizations/groupMetadataContainerAuthority.js.map +0 -1
  539. package/workflows/organizations/groupMetadataRootBinding.js.map +0 -1
  540. package/workflows/organizations/groupMetadataRuntime.js.map +0 -1
  541. package/workflows/organizations/groupNameUniqueness.js.map +0 -1
  542. package/workflows/organizations/groupPolicyHistoryPage.js.map +0 -1
  543. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +0 -1
  544. package/workflows/organizations/groupPolicyMutationContext.js.map +0 -1
  545. package/workflows/organizations/groupPolicyMutationEvidence.js.map +0 -1
  546. package/workflows/organizations/groupPolicyRequests.js.map +0 -1
  547. package/workflows/organizations/groupPolicyVerification.js.map +0 -1
  548. package/workflows/organizations/listLocalOrganizations.js.map +0 -1
  549. package/workflows/organizations/loadPolicyHistoryDetails.js.map +0 -1
  550. package/workflows/organizations/localReadModelDetails.js.map +0 -1
  551. package/workflows/organizations/organizationGroupDirectory.js.map +0 -1
  552. package/workflows/organizations/organizationGroupNamePolicies.js.map +0 -1
  553. package/workflows/organizations/organizationGroupNames.js.map +0 -1
  554. package/workflows/organizations/organizationPolicyHistoryDetails.js.map +0 -1
  555. package/workflows/organizations/organizationPolicyHistoryVerification.js.map +0 -1
  556. package/workflows/organizations/organizationPresentationAccessState.js.map +0 -1
  557. package/workflows/organizations/organizationProvisioningAttempt.js.map +0 -1
  558. package/workflows/organizations/organizationReplacementVerification.js.map +0 -1
  559. package/workflows/organizations/policyHistoryAccessDenial.js.map +0 -1
  560. package/workflows/organizations/policyHistoryCache.js.map +0 -1
  561. package/workflows/organizations/precedingPrincipalRematerialization.js.map +0 -1
  562. package/workflows/organizations/principalContainerRematerialization.js.map +0 -1
  563. package/workflows/organizations/principalContainerRematerializationPlanning.js.map +0 -1
  564. package/workflows/organizations/principalContainerRematerializationTargets.js.map +0 -1
  565. package/workflows/organizations/principalMutationJournalManagement.js.map +0 -1
  566. package/workflows/organizations/principalMutationJournalSession.js.map +0 -1
  567. package/workflows/organizations/principalMutationReceipt.js.map +0 -1
  568. package/workflows/organizations/principalOperationReceipt.js.map +0 -1
  569. package/workflows/organizations/principalPolicy.js.map +0 -1
  570. package/workflows/organizations/principalPolicyApi.js.map +0 -1
  571. package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +0 -1
  572. package/workflows/organizations/principalPolicyRecipients.js.map +0 -1
  573. package/workflows/organizations/readModel.js.map +0 -1
  574. package/workflows/organizations/readModelProjection.js.map +0 -1
  575. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +0 -6
  576. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +0 -1
  577. package/workflows/organizations/runtimeCurrentGroupMutation.js.map +0 -1
  578. package/workflows/organizations/runtimeCurrentOrganizationMutation.js.map +0 -1
  579. package/workflows/organizations/runtimeGroupMetadataAuthority.js.map +0 -1
  580. package/workflows/organizations/submitGroupPolicyCommit.js.map +0 -1
  581. package/workflows/principals/acknowledgedPrincipalCurrents.js.map +0 -1
  582. package/workflows/principals/acknowledgedPrincipalPredecessor.js.map +0 -1
  583. package/workflows/principals/initialPrincipalCurrentPublication.js.map +0 -1
  584. package/workflows/principals/loadRecoveredPrincipalHistoryPage.js.map +0 -1
  585. package/workflows/principals/policyCache.js.map +0 -1
  586. package/workflows/principals/principalCurrentPublicationSeal.js.map +0 -1
  587. package/workflows/principals/principalCurrentRecoveryBatch.js.map +0 -1
  588. package/workflows/principals/principalHistoryRecoveryAuthority.js.map +0 -1
  589. package/workflows/principals/principalHistoryRecoveryPrefix.js.map +0 -1
  590. package/workflows/principals/principalHistoryRecoveryReferences.js.map +0 -1
  591. package/workflows/principals/principalHistoryRecoveryStage.js.map +0 -1
  592. package/workflows/principals/principalHistoryRecoveryTypes.js.map +0 -1
  593. package/workflows/principals/principalPolicyCacheAdvance.js.map +0 -1
  594. package/workflows/principals/principalPolicyCacheValidation.js.map +0 -1
  595. package/workflows/principals/principalPolicyOrganizationScope.js.map +0 -1
  596. package/workflows/principals/principalRecoveryDirectory.js.map +0 -1
  597. package/workflows/principals/principalRecoveryDiscoveryPage.js.map +0 -1
  598. package/workflows/principals/principalRecoveryLocalPreference.js.map +0 -1
  599. package/workflows/principals/principalRecoveryMemo.js.map +0 -1
  600. package/workflows/principals/principalRecoveryMemoValidity.js.map +0 -1
  601. package/workflows/principals/principalRecoveryOutage.js.map +0 -1
  602. package/workflows/principals/publicPrincipalHistoryAuthority.js.map +0 -1
  603. package/workflows/principals/publicPrincipalHistoryPage.js.map +0 -1
  604. package/workflows/principals/publicPrincipalHistoryProgress.js.map +0 -1
  605. package/workflows/principals/publicPrincipalHistoryTypes.js.map +0 -1
  606. package/workflows/principals/publicProjectionDirectory.js.map +0 -1
  607. package/workflows/principals/publicProjectionPrincipal.js.map +0 -1
  608. package/workflows/principals/reconcileAcknowledgedPrincipalCurrent.js.map +0 -1
  609. package/workflows/principals/recoverCurrentOrganizationPolicy.js.map +0 -1
  610. package/workflows/principals/recoverPrincipalPolicyHistory.js.map +0 -1
  611. package/workflows/principals/recoverProjectionPolicyHistory.js.map +0 -1
  612. package/workflows/principals/recoverPublicPrincipalHistory.js.map +0 -1
  613. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +0 -1
  614. package/workflows/principals/selectPublicPrincipalHistory.js.map +0 -1
  615. /package/workflows/blobs/{readAttachmentTransfer.js → hydration/readAttachmentTransfer.js} +0 -0
  616. /package/workflows/blobs/{readAttachmentTransfer.js.map → hydration/readAttachmentTransfer.js.map} +0 -0
  617. /package/workflows/blobs/{multipartStageResolution.js → upload/multipartStageResolution.js} +0 -0
  618. /package/workflows/documents/{attachmentPersistence.js → attachments/attachmentPersistence.js} +0 -0
  619. /package/workflows/documents/{orphanBlobReclaimState.js → attachments/orphanBlobReclaimState.js} +0 -0
  620. /package/workflows/documents/{createProjection.js → create/createProjection.js} +0 -0
  621. /package/workflows/documents/{createProjection.js.map → create/createProjection.js.map} +0 -0
  622. /package/workflows/documents/{createProjectionFetch.js → create/createProjectionFetch.js} +0 -0
  623. /package/workflows/documents/{reportDocumentSyncQuarantine.js → sync/reportDocumentSyncQuarantine.js} +0 -0
  624. /package/workflows/documents/{syncAttemptState.js → sync/syncAttemptState.js} +0 -0
  625. /package/workflows/documents/{syncTrace.d.ts → sync/syncTrace.d.ts} +0 -0
  626. /package/workflows/documents/{syncTrace.js.map → sync/syncTrace.js.map} +0 -0
  627. /package/workflows/documents/{syncFailureClearance.d.ts → syncFailures/syncFailureClearance.d.ts} +0 -0
  628. /package/workflows/documents/{syncFailureClearance.js → syncFailures/syncFailureClearance.js} +0 -0
  629. /package/workflows/documents/{syncFailureClearance.js.map → syncFailures/syncFailureClearance.js.map} +0 -0
  630. /package/workflows/documents/{syncRepairAbandon.js → syncFailures/syncRepairAbandon.js} +0 -0
  631. /package/workflows/documents/{syncPlanProjection.js → syncPlan/syncPlanProjection.js} +0 -0
  632. /package/workflows/documents/{syncRekeyCommit.js.map → syncRekeys/syncRekeyCommit.js.map} +0 -0
  633. /package/workflows/organizations/{groupMetadataErrors.js.map → groupMetadata/groupMetadataErrors.js.map} +0 -0
  634. /package/workflows/organizations/{groupMutationAuthorization.js → groupPolicy/groupMutationAuthorization.js} +0 -0
  635. /package/workflows/organizations/{groupMutationAuthorization.js.map → groupPolicy/groupMutationAuthorization.js.map} +0 -0
  636. /package/workflows/organizations/{groupPolicyMutationHead.js.map → groupPolicy/groupPolicyMutationHead.js.map} +0 -0
  637. /package/workflows/organizations/{groupPolicyHistoryPage.js → policyHistory/groupPolicyHistoryPage.js} +0 -0
  638. /package/workflows/organizations/{policyHistoryReadModel.js → policyHistory/policyHistoryReadModel.js} +0 -0
  639. /package/workflows/organizations/{policyHistoryReadModel.js.map → policyHistory/policyHistoryReadModel.js.map} +0 -0
  640. /package/workflows/organizations/{policyHistoryTypes.js → policyHistory/policyHistoryTypes.js} +0 -0
  641. /package/workflows/organizations/{policyHistoryTypes.js.map → policyHistory/policyHistoryTypes.js.map} +0 -0
  642. /package/workflows/organizations/{principalPolicyApi.js → principalPolicy/principalPolicyApi.js} +0 -0
  643. /package/workflows/organizations/{principalPolicyRequest.js.map → principalPolicy/principalPolicyRequest.js.map} +0 -0
  644. /package/workflows/organizations/{organizationPresentationFailures.js.map → readModel/organizationPresentationFailures.js.map} +0 -0
  645. /package/workflows/principals/{principalAcknowledgementChecks.js → acknowledgements/principalAcknowledgementChecks.js} +0 -0
  646. /package/workflows/principals/{principalAcknowledgementChecks.js.map → acknowledgements/principalAcknowledgementChecks.js.map} +0 -0
  647. /package/workflows/principals/{principalHistoryRecoveryVerification.js.map → historyRecovery/principalHistoryRecoveryVerification.js.map} +0 -0
  648. /package/workflows/principals/{recoverPrincipalHistoryPage.js.map → historyRecovery/recoverPrincipalHistoryPage.js.map} +0 -0
  649. /package/workflows/principals/{recoverPrincipalPolicyHistory.d.ts → historyRecovery/recoverPrincipalPolicyHistory.d.ts} +0 -0
  650. /package/workflows/principals/{principalPolicyCacheScope.js → policyCache/principalPolicyCacheScope.js} +0 -0
  651. /package/workflows/principals/{principalPolicyCacheScope.js.map → policyCache/principalPolicyCacheScope.js.map} +0 -0
  652. /package/workflows/principals/{publicPrincipalHistoryTypes.js → publicHistory/publicPrincipalHistoryTypes.js} +0 -0
  653. /package/workflows/principals/{principalRecoveryDiscoveryPage.js → recoveryOperation/principalRecoveryDiscoveryPage.js} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"orphanBlobReclaims.js","sourceRoot":"","sources":["orphanBlobReclaims.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAC9D,OAAO,EAEL,uBAAuB,EACvB,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iCAAiC,EAAE,MAAM,oBAAoB,CAAC;AACvE,OAAO,EAEL,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAG5D,MAAM,8BAA8B,GAAG,EAAE,CAAC;AAC1C,MAAM,kCAAkC,GAAG,GAAG,CAAC;AAC/C,MAAM,kCAAkC,GAAG,MAAM,CAAC;AAClD,MAAM,mCAAmC,GAAG,CAAC,CAAC;AAC9C,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAOxC,SAAS,+BAA+B,CACtC,mBAAwC,EACxC,GAAW;IAEX,KAAK,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,mBAAmB,EAAE,CAAC;QACxD,IAAI,OAAO,IAAI,GAAG;YAAE,mBAAmB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAC7D,CAAC;AACH,CAAC;AAED,SAAS,uBAAuB;IAC9B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EA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AC;AACH,CAAC","sourcesContent":["import type { DocumentsPersistence } from \"../../data/persistence/documents/types\";\nimport { errorMessage } from \"../../data/shared/errorMessage\";\nimport {\n type ExecSql,\n resolveCanonicalExecSql,\n runOncePerConnection,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\nimport { runSerializedDocumentBlobMutation } from \"./blobMutationLock\";\nimport {\n type OrphanBlobReclaimState,\n orphanBlobReclaimState,\n} from \"./orphanBlobReclaimState\";\nimport { defaultDocumentsPersistence } from \"./persistence\";\nimport type { DocumentsWorkflowRuntimeGroups } from \"./runtime\";\n\nconst ORPHAN_BLOB_RECLAIM_BATCH_SIZE = 16;\nconst ORPHAN_BLOB_RECLAIM_TIME_BUDGET_MS = 250;\nconst ORPHAN_BLOB_RECLAIM_RETRY_DELAY_MS = 30_000;\nconst ORPHAN_BLOB_RECLAIM_LOG_SAMPLE_SIZE = 3;\nconst ORPHAN_BLOB_RECLAIM_YIELD_MS = 16;\n\ntype DocumentOrphanBlobReclaimRuntime = Pick<\n DocumentsWorkflowRuntimeGroups,\n \"infra\" | \"util\"\n>;\n\nfunction clearExpiredDeferredStorageKeys(\n deferredStorageKeys: Map<string, number>,\n now: number,\n): void {\n for (const [storageKey, retryAt] of deferredStorageKeys) {\n if (retryAt <= now) deferredStorageKeys.delete(storageKey);\n }\n}\n\nfunction waitForMaintenanceYield(): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ORPHAN_BLOB_RECLAIM_YIELD_MS);\n });\n}\n\nasync function sweepAgedDocumentOrphans(\n execSql: ExecSql,\n persistence: DocumentsPersistence,\n state: OrphanBlobReclaimState,\n): Promise<boolean> {\n let swept = false;\n await runOncePerConnection(execSql, state.sweepKey, async () => {\n swept = true;\n while (await persistence.orphanBlobs.sweep(execSql)) {\n await waitForMaintenanceYield();\n }\n });\n return swept;\n}\n\nasync function reclaimQueuedBlobs(\n runtime: DocumentOrphanBlobReclaimRuntime,\n persistence: DocumentsPersistence,\n state: OrphanBlobReclaimState,\n): Promise<boolean> {\n const execSql = runtime.infra.execSql;\n await persistence.ensureSchema(execSql);\n let shouldContinue = false;\n\n const startedAt = Date.now();\n const { deferredStorageKeys } = state;\n const failedStorageKeys: string[] = [];\n let warmedBlobStore = false;\n let sweptAgedOrphans = false;\n\n reclaimQueue: while (true) {\n clearExpiredDeferredStorageKeys(deferredStorageKeys, Date.now());\n const queuedStorageKeys = await persistence.orphanBlobs.list(\n execSql,\n ORPHAN_BLOB_RECLAIM_BATCH_SIZE + deferredStorageKeys.size,\n );\n const storageKeys = queuedStorageKeys\n .filter((storageKey) => !deferredStorageKeys.has(storageKey))\n .slice(0, ORPHAN_BLOB_RECLAIM_BATCH_SIZE);\n if (storageKeys.length === 0) {\n // Explicit delete paths get priority. Once their queue is drained, sweep\n // crash residue once per connection and immediately drain what it queues.\n if (\n !sweptAgedOrphans &&\n (await sweepAgedDocumentOrphans(execSql, persistence, state))\n ) {\n sweptAgedOrphans = true;\n continue;\n }\n break;\n }\n\n const firstStorageKey = storageKeys[0];\n if (!warmedBlobStore && firstStorageKey) {\n // Initialize lazy keyring/OPFS-backed stores before taking any blob-key\n // lock. A failed preview is harmless: deletion can still reclaim the key.\n await runtime.infra.blobStore\n .openByteSource(firstStorageKey)\n .catch(() => undefined);\n warmedBlobStore = true;\n }\n\n for (const storageKey of storageKeys) {\n await runSerializedDocumentBlobMutation(execSql, storageKey, async () => {\n const shouldDelete = await runSerializedSqlMutation(\n execSql,\n async (lockedExecSql) => {\n if (\n await persistence.orphanBlobs.isReferenced(\n lockedExecSql,\n storageKey,\n )\n ) {\n await persistence.orphanBlobs.acknowledge(\n lockedExecSql,\n storageKey,\n );\n return false;\n }\n return true;\n },\n );\n if (!shouldDelete) return;\n try {\n await runtime.infra.blobStore.deleteBytes(storageKey);\n await runSerializedSqlMutation(execSql, (lockedExecSql) =>\n persistence.orphanBlobs.acknowledge(lockedExecSql, storageKey),\n );\n } catch {\n failedStorageKeys.push(storageKey);\n deferredStorageKeys.set(\n storageKey,\n Date.now() + ORPHAN_BLOB_RECLAIM_RETRY_DELAY_MS,\n );\n }\n });\n if (Date.now() - startedAt >= ORPHAN_BLOB_RECLAIM_TIME_BUDGET_MS) {\n shouldContinue = true;\n break reclaimQueue;\n }\n }\n }\n\n if (failedStorageKeys.length > 0) {\n const sample = failedStorageKeys\n .slice(0, ORPHAN_BLOB_RECLAIM_LOG_SAMPLE_SIZE)\n .join(\", \");\n runtime.util.log(\n `Documents: orphan maintenance deferred ${failedStorageKeys.length} blob(s): ${sample}`,\n );\n }\n return shouldContinue;\n}\n\nfunction runDocumentOrphanReclaims(\n runtime: DocumentOrphanBlobReclaimRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n): Promise<void> {\n if (runtime.infra.dbStatus !== \"ready\") {\n return Promise.resolve();\n }\n const state = orphanBlobReclaimState(\n persistence.orphanBlobs,\n resolveCanonicalExecSql(runtime.infra.execSql),\n );\n if (state.running) {\n state.rerun = true;\n return state.running;\n }\n\n const reclaim = (async () => {\n try {\n let hasMore: boolean;\n do {\n state.rerun = false;\n hasMore = false;\n try {\n hasMore = await reclaimQueuedBlobs(runtime, persistence, state);\n } catch (error) {\n const message = errorMessage(error);\n runtime.util.log(`Documents: orphan maintenance failed: ${message}`);\n }\n if (hasMore || state.rerun) await waitForMaintenanceYield();\n } while (hasMore || state.rerun);\n } finally {\n state.running = undefined;\n state.rerun = false;\n }\n })();\n state.running = reclaim;\n return reclaim;\n}\n\n/** Await all requested batches; maintenance failures never fail committed writes. */\nexport async function reclaimDocumentOrphanBlobs(\n runtime: DocumentOrphanBlobReclaimRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n): Promise<void> {\n try {\n await runDocumentOrphanReclaims(runtime, persistence);\n } catch (error) {\n runtime.util.log(\n `Documents: orphan maintenance failed: ${errorMessage(error)}`,\n );\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"persistedDocumentRemoval.js","sourceRoot":"","sources":["persistedDocum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T_KIND } from \"../../data/documents/documentConstants\";\nimport {\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../../data/documents/documentKinds\";\nimport type {\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport {\n type ExecSql,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\nimport { ensureDocumentClientProjectionTables } from \"./persistence\";\n\nexport async function deletePersistedDocument(input: {\n /**\n * Runs in the same SQLite transaction as the matched document teardown.\n * Used to atomically pin a verified terminal purge proof.\n */\n beforeDeleteInTransaction?:\n | ((transactionExecSql: ExecSql) => Promise<void>)\n | undefined;\n canStartDurableMutation?: (() => boolean) | undefined;\n documentProjectors: DocumentProjectorRegistryInput;\n execSql: ExecSql;\n expectedRecord?: StoredDocumentRecord | undefined;\n localId: string;\n /**\n * Runs INSIDE the serialized mutation, after the deletes commit: callers\n * invalidate their in-memory store generation here so any failure handler\n * queued behind this mutation observes the invalidation and cannot\n * resurrect a row the deletion just removed.\n */\n onDeletedInMutation?: (() => void) | undefined;\n persistence: DocumentsPersistence;\n}): Promise<boolean> {\n const documentProjectors = resolveDocumentProjectorRegistry(\n input.documentProjectors,\n );\n await input.persistence.ensureSchema(input.execSql);\n await ensureDocumentClientProjectionTables({\n documentProjectors,\n execSql: input.execSql,\n });\n let deleted = false;\n await runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n // The guard runs INSIDE the claimed mutation: the pre-claim answer can go\n // stale while the deletion waits behind another mutation (a store reset,\n // a replacement generation's persist), and deleting on the stale answer\n // would wipe rows the newer generation just wrote.\n if (input.canStartDurableMutation && !input.canStartDurableMutation()) {\n return;\n }\n if (input.expectedRecord) {\n const identityMatched = await input.persistence.deleteDocumentIfMatches(\n lockedExecSql,\n input.expectedRecord,\n (transactionExecSql) =>\n (async () => {\n await documentProjectors.deleteStoredDocumentClientProjection({\n documentKind:\n input.expectedRecord?.documentKind ?? DEFAULT_DOCUMENT_KIND,\n execSql: transactionExecSql,\n localId: input.localId,\n });\n await input.beforeDeleteInTransaction?.(transactionExecSql);\n })(),\n );\n if (!identityMatched) return;\n } else {\n if (input.beforeDeleteInTransaction) {\n throw new Error(\n \"Atomic document purge checkpointing requires an expected document record\",\n );\n }\n const existing = await input.persistence.loadDocument(\n lockedExecSql,\n input.localId,\n );\n await input.persistence.deleteDocument(lockedExecSql, input.localId);\n await documentProjectors.deleteStoredDocumentClientProjection({\n documentKind: existing?.documentKind ?? DEFAULT_DOCUMENT_KIND,\n execSql: lockedExecSql,\n localId: input.localId,\n });\n }\n input.onDeletedInMutation?.();\n deleted = true;\n });\n return deleted;\n}\n\nexport type DiscardedDocumentShellResult = DiscardDocumentToShellResult;\n\n/**\n * Convert a stuck document's local state to the freshly-discovered-share\n * shell. The persistence implementation owns the whole sequence — the\n * eligibility checks (local-only, unlinked, or move-pending documents are\n * refused), the row teardown, the document-kind client-projection clear, and\n * the shell upsert — and commits it as ONE transaction, so an interruption\n * leaves either the fully old or the fully shelled document (never, e.g., a\n * discarded contact whose projected fields stay visible). Implementations\n * without the full document schema do not offer the operation and refuse.\n *\n * Returns the reclaimable storage keys on success — the deleted rows were\n * the only durable pointers to those bytes, so the caller reclaims them.\n */\nexport async function discardPersistedDocumentToShell(input: {\n documentProjectors: DocumentProjectorRegistryInput;\n execSql: ExecSql;\n expectedDocumentId: string;\n localId: string;\n persistence: DocumentsPersistence;\n}): Promise<DiscardedDocumentShellResult> {\n await input.persistence.ensureSchema(input.execSql);\n if (!input.persistence.discardDocumentToShell) {\n return { discarded: false };\n }\n return input.persistence.discardDocumentToShell(\n input.execSql,\n input.localId,\n input.expectedDocumentId,\n input.documentProjectors,\n );\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"purge.js","sourceRoot":"","sources":["purge.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0BAA0B,EAE1B,uBAAuB,EACvB,eAAe,GAEhB,MAAM,mBAAmB,C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,cAAc;KACnE,CACF,CAAC;IACF,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,QAAQ,GAAG,MAAM,wBAAwB,CAAC;QAC9C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,kBAAkB,EAAE,KAAK,CAAC,UAAU;QACpC,sBAAsB,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;QACnD,KAAK,EAAE,QAAQ;QACf,cAAc,EAAE,KAAK,CAAC,wBAAwB;QAC9C,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACH,MAAM,KAAK,CAAC,eAAe,CAAC;QAC1B,gBAAgB,EAAE,QAAQ,CAAC,iBAAiB;KAC7C,CAAC,CAAC;IACH,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n computeAccessEventBodyHash,\n type DocumentPurgeAccessEventBody,\n KeyingVerificationError,\n signAccessEvent,\n type UnsignedAccessEvent,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeRequest } from \"@tearleads/validators/request\";\nimport {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentPurgeProofResponse,\n type DocumentPurgeResponse,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n containerPathRefs,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"../../data/documents/shared/projection\";\nimport {\n assertDocumentManifestBundleConsistent,\n readManifestContainerId,\n} from \"../../data/documents/shared/readers\";\nimport type {\n DocumentCreateAuthor,\n DocumentSyncApi,\n} from \"../../data/documents/shared/types\";\nimport {\n readCanonicalJson,\n readCanonicalRecord,\n} from \"../../data/keying/canonicalJson\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification\";\nimport {\n verifyDocumentPurgeProof,\n verifyDocumentPurgeProofBaseline,\n verifyDocumentWriterProjection,\n} from \"../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { documentContainerProjections } from \"../../data/keyingProjectionVerification/documentContainerProjections\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n assertSubtreePurgePath,\n type SubtreePurgeRoot,\n} from \"./subtreePurgeScope\";\n\ninterface DocumentPurgeApi {\n getDocumentPurgeProof(\n documentId: string,\n options?: {\n readonly documentCheckpointManifestHash?: string;\n },\n requestOptions?: {\n readonly expectedPaymentRequiredOrganizationId?: string;\n },\n ): Promise<DocumentPurgeProofResponse | null>;\n getDocumentWriterProjectionResult: NonNullable<\n DocumentSyncApi[\"getDocumentWriterProjectionResult\"]\n >;\n purgeDocument(\n documentId: string,\n request: DocumentPurgeRequest,\n options?: {\n readonly expectedPaymentRequiredOrganizationId?: string;\n },\n ): Promise<DocumentPurgeResponse | null>;\n}\n\nconst REMOTE_DOCUMENT_ALREADY_PURGED = Symbol(\"remoteDocumentAlreadyPurged\");\n\nasync function loadAuthenticatedDocumentPurgeProof(input: {\n readonly apiClient: Pick<DocumentSyncApi, \"getDocumentPurgeProof\">;\n readonly documentId: string;\n readonly execSql: ExecSql;\n readonly expectedOrganizationId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<DocumentPurgeProofResponse | null> {\n if (!input.apiClient.getDocumentPurgeProof) {\n throw new ProjectionDependencyUnavailableError(\n \"Remote document deletion is missing a purge-proof endpoint\",\n );\n }\n const initialProof = await input.apiClient.getDocumentPurgeProof(\n input.documentId,\n undefined,\n {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n },\n );\n if (!initialProof) {\n // ApiClient returns null for transport, HTTP and response-shape failures.\n // Even after a deletion hint, absence cannot prove signed-data tampering.\n // Keep local data and defer deletion until an actual proof verifies.\n return null;\n }\n await verifyDocumentPurgeProofBaseline({\n execSql: input.execSql,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.expectedOrganizationId,\n proof: initialProof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // The current API returns complete history to recorded readers. Otherwise\n // its terminal snapshot needs an exact local pin; a floor refetch cannot\n // grant missing observation authority.\n return initialProof;\n}\n\nasync function resolveDocumentPurgeWriterProjection(input: {\n readonly apiClient: DocumentPurgeApi;\n readonly documentId: string;\n}): Promise<\n | DocumentWriterProjectionResponse\n | typeof REMOTE_DOCUMENT_ALREADY_PURGED\n | null\n> {\n const result = await input.apiClient.getDocumentWriterProjectionResult(\n input.documentId,\n { reportErrors: false },\n );\n if (result.ok) {\n return result.data;\n }\n if (result.status === 404 && result.code === DOCUMENT_NOT_FOUND_ERROR_CODE) {\n return REMOTE_DOCUMENT_ALREADY_PURGED;\n }\n result.report();\n return null;\n}\n\nexport async function buildDocumentPurgeRequest(input: {\n readonly author: DocumentCreateAuthor;\n readonly expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n readonly eventId?: string | undefined;\n readonly signedAt?: string | undefined;\n readonly writerProjection: DocumentWriterProjectionResponse;\n}): Promise<DocumentPurgeRequest> {\n const identity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document purge predecessor\",\n });\n if (identity.documentId !== input.writerProjection.documentId) {\n throw new Error(\"Document purge projection identity mismatch\");\n }\n if (identity.organizationId !== input.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document purge author organization mismatch\",\n );\n }\n const linkedContainerIds = readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n );\n if (linkedContainerIds.length !== 1) {\n throw new Error(\"Document purge requires exactly one linked container\");\n }\n const [containerId] = linkedContainerIds;\n const authorizingProjection = documentContainerProjections(\n input.writerProjection,\n ).find((projection) => {\n const leaf = projection.path.at(-1);\n return leaf && readManifestContainerId(leaf) === containerId;\n });\n const containerManifestHash =\n authorizingProjection?.path.at(-1)?.manifestHash;\n if (!authorizingProjection || !containerId || !containerManifestHash) {\n throw new Error(\"Document purge authorization path is unavailable\");\n }\n assertSubtreePurgePath(authorizingProjection.path, input.expectedSubtreeRoot);\n const authorizingContainerManifestHashes = authorizingProjection.path.map(\n (bundle) => bundle.manifestHash,\n );\n const body: DocumentPurgeAccessEventBody = {\n authorizingContainerManifestHashes,\n containerId,\n containerManifestHash,\n documentManifestHash: input.writerProjection.documentManifest.manifestHash,\n eventType: \"document.purge\",\n };\n const unsignedEvent: UnsignedAccessEvent = {\n version: 1,\n eventId: input.eventId ?? crypto.randomUUID(),\n eventType: \"document.purge\",\n objectKind: \"document\",\n objectId: input.writerProjection.documentId,\n organizationId: input.author.organizationId,\n previousManifestHash: input.writerProjection.documentManifest.manifestHash,\n dependencyManifestHashes: authorizingContainerManifestHashes,\n bodyHash: await computeAccessEventBodyHash(\n readCanonicalJson(body, \"Document purge body\"),\n ),\n signerUserId: input.author.signerUserId,\n signerDeviceId: input.author.signerDeviceId,\n signerKeyFingerprint: input.author.signerKeyFingerprint,\n signedAt: input.signedAt ?? new Date().toISOString(),\n };\n const event = await signAccessEvent(\n unsignedEvent,\n input.author.signerPrivateKey,\n );\n\n return {\n authorizingContainerPathRefs: containerPathRefs(authorizingProjection.path),\n body: readCanonicalRecord(body, \"Document purge body\"),\n event: readCanonicalRecord(event, \"Document purge event\"),\n };\n}\n\nexport function createVerifiedRemoteDocumentDeletionHandler(input: {\n readonly apiClient: Pick<DocumentSyncApi, \"getDocumentPurgeProof\">;\n readonly execSql: ExecSql;\n readonly expectedOrganizationId: string;\n readonly onVerifiedDeletion: (input: {\n readonly commitPurgeProof: (transactionExecSql: ExecSql) => Promise<void>;\n readonly documentId: string;\n }) => Promise<void> | void;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): (deleted: { readonly documentId: string }) => Promise<void> {\n return async ({ documentId }) => {\n const proof = await loadAuthenticatedDocumentPurgeProof({\n apiClient: input.apiClient,\n documentId,\n execSql: input.execSql,\n expectedOrganizationId: input.expectedOrganizationId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!proof) {\n throw new ProjectionDependencyUnavailableError(\n \"Remote document deletion is missing its signed purge proof\",\n );\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n expectedDocumentId: documentId,\n expectedOrganizationId: input.expectedOrganizationId,\n proof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedDeletion({\n commitPurgeProof: verified.commitCheckpoints,\n documentId,\n });\n };\n}\n\nexport async function purgeRemoteDocument(input: {\n readonly beforeSubmit?: (() => Promise<boolean>) | undefined;\n readonly apiClient: DocumentPurgeApi;\n readonly author: DocumentCreateAuthor;\n readonly documentId: string;\n readonly expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n readonly execSql: ExecSql;\n readonly onVerifiedPurge: (input: {\n readonly commitPurgeProof: (transactionExecSql: ExecSql) => Promise<void>;\n }) => Promise<void> | void;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<DocumentPurgeResponse | null> {\n const writerProjection = await resolveDocumentPurgeWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n });\n if (!writerProjection) {\n return null;\n }\n if (writerProjection === REMOTE_DOCUMENT_ALREADY_PURGED) {\n const proof = await loadAuthenticatedDocumentPurgeProof({\n apiClient: input.apiClient,\n documentId: input.documentId,\n execSql: input.execSql,\n expectedOrganizationId: input.author.organizationId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!proof) {\n throw new ProjectionDependencyUnavailableError(\n \"Purged remote document is missing its signed purge proof\",\n );\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.author.organizationId,\n proof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedPurge({\n commitPurgeProof: verified.commitCheckpoints,\n });\n return { ...proof, reclaimedBlobStorageKeys: [] };\n }\n await verifyDocumentWriterProjection({\n execSql: input.execSql,\n projection: writerProjection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const request = await buildDocumentPurgeRequest({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n writerProjection,\n });\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n if (input.stillCurrent?.() === false) return null;\n const response = await input.apiClient.purgeDocument(\n input.documentId,\n request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n );\n if (!response) {\n return null;\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.author.organizationId,\n proof: response,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedPurge({\n commitPurgeProof: verified.commitCheckpoints,\n });\n return response;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"readOnlyProjectionFailure.js","sourceRoot":"","sources":["readOnlyProjectionFailure.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,kCAAkC,EAAE,MAAM,yDAAyD,CAAC;AAC7G,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EAAE,kCAAkC,EAAE,MAAM,mBAAmB,CAAC;AACvE,OAAO,EAAE,4BAA4B,EAAE,MAAM,6BAA6B,CAAC;AAE3E,MAAM,CAAC,MAAM,yBAAyB,GAAG,MAAM,CAAC,2BAA2B,CAAC,CAAC;AAE7E,MAAM,UAAU,uCAAuC,CACrD,KAAc,EACd,KAGC;IAKD,IAAI,kCAAkC,CAAC,KAAK,CAAC,EAAE,CAAC;QAC9C,MAAM,KAAK,CAAC;IACd,CAAC;IACD,IAAI,KAAK,YAAY,kCAAkC,EAAE,CAAC;QACxD,IAAI,KAAK,CAAC,4BAA4B,EAAE,CAAC;YACvC,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;IACD,IACE,KAAK,CAAC,4BAA4B;QAClC,KAAK,YAAY,uBAAuB;QACxC,KAAK,CAAC,IAAI,KAAK,eAAe,EAC9B,CAAC;QACD,OAAO,yBAAyB,CAAC;IACnC,CAAC;IACD,2EAA2E;IAC3E,wEAAwE;IACxE,8BAA8B,CAAC,KAAK,CAAC,CAAC;IACtC,IAAI,4BAA4B,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,WAAW,KAAK,KAAK,EAAE,CAAC;QACvE,MAAM,KAAK,CAAC;IACd,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { isDocumentSyncUpdateIsolationError } from \"../../data/documents/shared/documentSyncUpdateIsolation\";\nimport { rethrowKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport { DocumentRawHistoryUnavailableError } from \"./syncContentKeys\";\nimport { projectionIntegrityErrorCode } from \"./syncFailureClassification\";\n\nexport const REFRESH_CACHED_PROJECTION = Symbol(\"refresh cached projection\");\n\nexport function handleReadOnlyProjectionCompletionError(\n error: unknown,\n input: {\n allowCachedProjectionRefresh: boolean;\n historyMode?: \"raw\" | undefined;\n },\n):\n | DocumentRawHistoryUnavailableError\n | null\n | typeof REFRESH_CACHED_PROJECTION {\n if (isDocumentSyncUpdateIsolationError(error)) {\n throw error;\n }\n if (error instanceof DocumentRawHistoryUnavailableError) {\n if (input.allowCachedProjectionRefresh) {\n return error;\n }\n throw error;\n }\n if (\n input.allowCachedProjectionRefresh &&\n error instanceof KeyingVerificationError &&\n error.code === \"invalid_shape\"\n ) {\n return REFRESH_CACHED_PROJECTION;\n }\n // The document-store `document.sync` boundary owns durable reporting; this\n // helper only decides whether an ordinary projection miss is retryable.\n rethrowKeyingVerificationError(error);\n if (projectionIntegrityErrorCode(error) || input.historyMode === \"raw\") {\n throw error;\n }\n return null;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"readOnlySync.js","sourceRoot":"","sources":["readOnlySync.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,kCAAkC,EAClC,kCAAkC,EAClC,4BAA4B,GAC7B,MAAM,gCAAgC,CAAC;AAKxC,OAAO,EACL,+BAA+B,EAC/B,sCAAsC,EACtC,kBAAkB,GACnB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,6BAA6B,GAC9B,MAAM,4CAA4C,CAAC;AASpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAClF,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAOtE,OAAO,EAAE,6BAA6B,EAAE,MAAM,2CAA2C,CAAC;AAC1F,OAAO,EACL,uCAAuC,EACvC,yBAAyB,GAC1B,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAAE,kCAAkC,EAAE,MAAM,mBAAmB,CAAC;AACv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AAiB,EAAE,CAAC,SAAS,CAAC,YAAY;gBAC1C,cAAc;gBACd,IAAI;gBACJ,uBAAuB,EAAE,EAAE;gBAC3B,QAAQ,EAAE,SAAS,CAAC,QAAQ;gBAC5B,uBAAuB,EAAE,EAAE;gBAC3B,wBAAwB,EAAE,KAAK;aAChC;SACF,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,CAAC,WAAW,KAAK,KAAK,EAAE,CAAC;YAChC,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,CAAC;IACnC,CAAC;AACH,CAAC;AA6DD,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAA8B,EAC9B,wBAAmD;IAEnD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAClD,IAAI,CAAC,KAAK,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IAEzD,OAAO,4CAA4C,CAAC;QAClD,GAAG,KAAK;QACR,wBAAwB;KACzB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n DocumentCreateResponse,\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n isAccessManifestBundleWireResponse,\n isDocumentContentKeyBundleResponse,\n isDocumentKekTargetsResponse,\n} from \"@tearleads/validators/response\";\nimport type {\n DocumentSyncUpdateIsolationError,\n IncomingDocumentSyncUpdateValidator,\n} from \"../../data/documents/shared/documentSyncUpdateIsolation\";\nimport {\n isRetryableDocumentSyncConflict,\n persistedDocumentSyncStateFromResponse,\n submitDocumentSync,\n} from \"../../data/documents/shared/responses\";\nimport {\n type DocumentSyncPullContinuation,\n resolvePullContinuationMinLsn,\n} from \"../../data/documents/shared/syncPagination\";\nimport type {\n DocumentCreateAuthor,\n DocumentSyncApi,\n DocumentSyncPlan,\n DocumentWriterPublicKeyResolver,\n PersistedDocumentSyncState,\n SyncRemoteDocumentResult,\n} from \"../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../data/keying/canonicalJson\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../data/sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { limitDocumentSyncRequestBytes } from \"../../data/sync/documentSyncOutgoingBatch\";\nimport {\n handleReadOnlyProjectionCompletionError,\n REFRESH_CACHED_PROJECTION,\n} from \"./readOnlyProjectionFailure\";\nimport type { DocumentSyncContainerRekeyBuilder } from \"./syncAttemptState\";\nimport { DocumentRawHistoryUnavailableError } from \"./syncContentKeys\";\nimport {\n handleUpstreamDeletedDocumentSyncFailure,\n projectionIntegrityErrorCode,\n type RemoteDocumentDeletionHandler,\n type TerminalSubmitFailureHandler,\n} from \"./syncFailureClassification\";\nimport {\n assertRawContinuationCanRetry,\n refreshSyncAttemptWriterProjection,\n resolveSyncAttemptWriterProjection,\n} from \"./syncFailures\";\nimport { buildDocumentSyncPlan } from \"./syncPlanIdentity\";\nimport { buildMaterializedDocumentSyncPlan } from \"./syncPlanMaterial\";\nimport type { RekeyPendingUpdate } from \"./syncRecoveryRekey\";\nimport { syncRemoteDocumentResultFromResponse } from \"./syncResponseResult\";\nimport { type DocumentSyncTraceEmitter, traceSubmitFailed } from \"./syncTrace\";\n\nasync function completeReadOnlyRemoteDocumentSyncWithProjection(\n input: Omit<ReadOnlyDocumentSyncCompletionInput, \"writerProjection\"> & {\n writerProjection: DocumentWriterProjectionResponse;\n },\n): Promise<SyncRemoteDocumentResult> {\n const materializedPlan = await buildMaterializedDocumentSyncPlan({\n author: input.author,\n execSql: input.execSql,\n historyMode: input.historyMode,\n localVersionVector: input.localVersionVector,\n minLsn: resolvePullContinuationMinLsn(input.pullContinuation, input.minLsn),\n pullCursor: input.pullContinuation?.cursor,\n onSyncTrace: input.onSyncTrace,\n pendingUpdates: [],\n signedAt: input.signedAt,\n targetSecretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n\n const result = await syncRemoteDocumentResultFromResponse({\n ...projectionVerificationOptions(input),\n execSql: input.execSql,\n materializedPlan,\n recoveryPendingUpdatesById: new Map(),\n resolveWriterPublicKey: input.resolveWriterPublicKey,\n response: input.response,\n targetSecretKey: input.targetSecretKey,\n validateIncomingUpdates: input.validateIncomingUpdates,\n writerProjection: input.writerProjection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n });\n return {\n ...result,\n hasIncompletePull: !input.pullComplete,\n };\n}\n\nfunction parsePersistedDocumentSyncRecord<T>(\n value: string | null | undefined,\n label: string,\n isRecord: (value: unknown) => value is T,\n): T | null {\n if (!value) {\n return null;\n }\n\n try {\n const record = readCanonicalRecord(JSON.parse(value), label);\n return isRecord(record) ? record : null;\n } catch {\n return null;\n }\n}\n\nfunction parsePersistedDocumentSyncState(\n persistedState: PersistedDocumentSyncState | null | undefined,\n documentId: string,\n): {\n contentKeyBundle: DocumentCreateResponse[\"contentKeyBundle\"];\n documentKekTargets: DocumentSyncResponse[\"documentKekTargets\"];\n documentManifest: DocumentCreateResponse[\"accessManifest\"];\n} | null {\n if (persistedState?.documentId !== documentId) {\n return null;\n }\n\n const contentKeyBundle = parsePersistedDocumentSyncRecord(\n persistedState.contentKeyBundle,\n \"Persisted document sync content-key bundle\",\n isDocumentContentKeyBundleResponse,\n );\n const documentKekTargets = parsePersistedDocumentSyncRecord(\n persistedState.documentKekTargets,\n \"Persisted document sync KEK targets\",\n isDocumentKekTargetsResponse,\n );\n const documentManifest = parsePersistedDocumentSyncRecord(\n persistedState.documentManifestBundle,\n \"Persisted document sync manifest\",\n isAccessManifestBundleWireResponse,\n );\n\n if (!contentKeyBundle || !documentKekTargets || !documentManifest) {\n return null;\n }\n\n return {\n contentKeyBundle,\n documentKekTargets,\n documentManifest,\n };\n}\n\nasync function buildReadOnlyDocumentSyncPlanFromPersistedState(input: {\n author: DocumentCreateAuthor;\n documentId: string;\n historyMode?: \"raw\" | undefined;\n localVersionVector: string | null;\n minLsn?: string | undefined;\n pullContinuation?: DocumentSyncPullContinuation | undefined;\n persistedState?: PersistedDocumentSyncState | null | undefined;\n signedAt?: string | undefined;\n}): Promise<DocumentSyncPlan | null> {\n const persisted = parsePersistedDocumentSyncState(\n input.persistedState,\n input.documentId,\n );\n if (!persisted) {\n return null;\n }\n\n const plan = await buildDocumentSyncPlan({\n author: input.author,\n contentKeyBundle: persisted.contentKeyBundle,\n documentId: input.documentId,\n documentKekTargets: persisted.documentKekTargets,\n documentManifest: persisted.documentManifest,\n historyMode: input.historyMode,\n localVersionVector: input.localVersionVector,\n minLsn: resolvePullContinuationMinLsn(input.pullContinuation, input.minLsn),\n outgoingUpdates: [],\n pullCursor: input.pullContinuation?.cursor,\n signedAt: input.signedAt,\n });\n const request = limitDocumentSyncRequestBytes(plan.request);\n return request === plan.request ? plan : { ...plan, request };\n}\n\ntype PersistedReadOnlyDocumentSyncResult =\n | {\n kind: \"completed\";\n result: SyncRemoteDocumentResult | null;\n }\n | {\n kind: \"not_completed\";\n };\n\ninterface ReadOnlyDocumentSyncCompletionInput {\n apiClient: DocumentSyncApi;\n author: DocumentCreateAuthor;\n documentId: string;\n execSql: ExecSql;\n historyMode?: \"raw\" | undefined;\n localVersionVector: string | null;\n minLsn?: string | undefined;\n pullContinuation?: DocumentSyncPullContinuation | undefined;\n onReadOnlyProjectionFailure?: TerminalSubmitFailureHandler | undefined;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n onSyncTrace?: DocumentSyncTraceEmitter | undefined;\n pullComplete: boolean;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n response: DocumentSyncResponse;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n validateIncomingUpdates: IncomingDocumentSyncUpdateValidator;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nasync function tryCompleteReadOnlyRemoteDocumentSyncWithProjection(input: {\n allowCachedProjectionRefresh: boolean;\n completion: ReadOnlyDocumentSyncCompletionInput;\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<\n | DocumentRawHistoryUnavailableError\n | SyncRemoteDocumentResult\n | null\n | typeof REFRESH_CACHED_PROJECTION\n> {\n try {\n return await completeReadOnlyRemoteDocumentSyncWithProjection({\n ...input.completion,\n writerProjection: input.writerProjection,\n });\n } catch (error) {\n return handleReadOnlyProjectionCompletionError(error, {\n allowCachedProjectionRefresh: input.allowCachedProjectionRefresh,\n historyMode: input.completion.historyMode,\n });\n }\n}\nasync function completeReadOnlyRemoteDocumentSyncWithUpdates(\n input: ReadOnlyDocumentSyncCompletionInput,\n): Promise<PersistedReadOnlyDocumentSyncResult> {\n const reusableWriterProjection =\n input.writerProjection?.documentId === input.documentId\n ? input.writerProjection\n : null;\n const writerProjection =\n reusableWriterProjection ??\n (await resolveSyncAttemptWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n onRemoteDocumentDeleted: input.onRemoteDocumentDeleted,\n onSyncTrace: input.onSyncTrace,\n onTerminalFailure: input.onReadOnlyProjectionFailure,\n reusableWriterProjection: null,\n stillCurrent: input.stillCurrent,\n }));\n if (!writerProjection) {\n return { kind: \"completed\", result: null };\n }\n const canRefreshProjection =\n input.historyMode === \"raw\" || Boolean(reusableWriterProjection);\n let result:\n | DocumentRawHistoryUnavailableError\n | SyncRemoteDocumentResult\n | null\n | typeof REFRESH_CACHED_PROJECTION = null;\n let retryAfterRollback = false;\n try {\n result = await tryCompleteReadOnlyRemoteDocumentSyncWithProjection({\n allowCachedProjectionRefresh: canRefreshProjection,\n completion: input,\n writerProjection,\n });\n } catch (error) {\n if (projectionIntegrityErrorCode(error) !== \"rollback\") {\n throw error;\n }\n retryAfterRollback = true;\n }\n if (\n !retryAfterRollback &&\n result !== REFRESH_CACHED_PROJECTION &&\n !(result instanceof DocumentRawHistoryUnavailableError) &&\n (result || !reusableWriterProjection)\n ) {\n return { kind: \"completed\", result };\n }\n const freshWriterProjection = await refreshSyncAttemptWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n onRemoteDocumentDeleted: input.onRemoteDocumentDeleted,\n onSyncTrace: input.onSyncTrace,\n onTerminalFailure: input.onReadOnlyProjectionFailure,\n stillCurrent: input.stillCurrent,\n unavailableError:\n result instanceof DocumentRawHistoryUnavailableError ? result : undefined,\n });\n if (!freshWriterProjection) {\n return { kind: \"completed\", result: null };\n }\n const freshResult = await tryCompleteReadOnlyRemoteDocumentSyncWithProjection(\n {\n allowCachedProjectionRefresh: false,\n completion: input,\n writerProjection: freshWriterProjection,\n },\n );\n if (\n freshResult === REFRESH_CACHED_PROJECTION ||\n freshResult instanceof DocumentRawHistoryUnavailableError\n ) {\n throw new Error(\"Fresh document projection unexpectedly requested refresh\");\n }\n return freshResult\n ? { kind: \"completed\", result: freshResult }\n : { kind: \"not_completed\" };\n}\nasync function syncReadOnlyRemoteDocumentFromPersistedState(\n input: Omit<\n ReadOnlyDocumentSyncCompletionInput,\n \"pullComplete\" | \"response\"\n > & {\n persistedState?: PersistedDocumentSyncState | null | undefined;\n },\n): Promise<PersistedReadOnlyDocumentSyncResult> {\n let plan: DocumentSyncPlan | null;\n try {\n plan = await buildReadOnlyDocumentSyncPlanFromPersistedState(input);\n } catch {\n plan = null;\n }\n if (!plan) {\n return { kind: \"not_completed\" };\n }\n if (input.stillCurrent?.() === false) {\n return { kind: \"completed\", result: null };\n }\n const submitted = await submitDocumentSync({\n apiClient: input.apiClient,\n expectedCommitLsnMode: input.pullContinuation?.commitLsnMode,\n plan,\n });\n if (input.stillCurrent?.() === false) {\n return { kind: \"completed\", result: null };\n }\n if (!submitted) {\n return { kind: \"completed\", result: null };\n }\n if (!submitted.ok) {\n if (\n await handleUpstreamDeletedDocumentSyncFailure({\n documentId: input.documentId,\n failure: submitted,\n onRemoteDocumentDeleted: input.onRemoteDocumentDeleted,\n })\n ) {\n return { kind: \"completed\", result: null };\n }\n\n if (isRetryableDocumentSyncConflict(submitted)) {\n traceSubmitFailed(input.onSyncTrace, {\n action: \"retry\",\n code: submitted.code,\n documentId: input.documentId,\n status: submitted.status,\n });\n assertRawContinuationCanRetry(input.historyMode, input.pullContinuation);\n return { kind: \"not_completed\" };\n }\n\n traceSubmitFailed(input.onSyncTrace, {\n action: \"stop\",\n code: submitted.code,\n documentId: input.documentId,\n status: submitted.status,\n });\n submitted.report();\n return { kind: \"completed\", result: null };\n }\n\n if (submitted.response.updates.length > 0) {\n return completeReadOnlyRemoteDocumentSyncWithUpdates({\n ...input,\n pullComplete: submitted.pullComplete,\n response: submitted.response,\n });\n }\n\n try {\n const persistedState = await persistedDocumentSyncStateFromResponse(\n plan,\n submitted.response,\n { resolveWriterPublicKey: input.resolveWriterPublicKey },\n );\n\n return {\n kind: \"completed\",\n result: {\n contentKey: new Uint8Array(),\n decryptedUpdates: [],\n exhaustedPendingUpdateCount: 0,\n hasDeferredPendingUpdates: false,\n hasIncompletePull: !submitted.pullComplete,\n persistedState,\n plan,\n rekeyedPendingUpdateIds: [],\n response: submitted.response,\n settledPendingUpdateIds: [],\n acceptedRecoveryBaseline: false,\n },\n };\n } catch (error) {\n if (input.historyMode === \"raw\") {\n throw error;\n }\n return { kind: \"not_completed\" };\n }\n}\n\nexport interface SyncRemoteDocumentInput {\n apiClient: DocumentSyncApi;\n author: DocumentCreateAuthor;\n /**\n * Supplies a full-history Loro snapshot of the local document so a\n * write-bearing pass can heal a stale content-key bundle by rotating to a\n * fresh content key anchored by a rotation baseline.\n */\n buildRotationSnapshot?: (() => Promise<Uint8Array | null>) | undefined;\n /** Overrides automatic ancestor repair for each submission's current projection. */\n buildContainerRekeys?: DocumentSyncContainerRekeyBuilder;\n documentId: string;\n execSql: ExecSql;\n /** Explicit read-only recovery that bypasses rotation-baseline redirect. */\n historyMode?: \"raw\" | undefined;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n localVersionVector: string | null;\n minLsn?: string | undefined;\n pullContinuation?: DocumentSyncPullContinuation | undefined;\n /** Atomically commits the verified purge proof with matching local teardown. */\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n onSyncAbandoned?: ((reason: string) => void) | undefined;\n /** Clipboard-safe trace sink (see syncTrace.ts); never receives content. */\n onSyncTrace?: DocumentSyncTraceEmitter | undefined;\n /**\n * Fires when a pass WITHOUT queued writes cannot resolve its writer\n * projection (e.g. a coded 409 from the projection route). Read-only\n * revalidation otherwise fails silently — one burned request and a trace\n * line — leaving the document permanently stale with nothing durable to\n * explain why (edge-case row 13).\n */\n onReadOnlyProjectionFailure?: TerminalSubmitFailureHandler | undefined;\n /** Records a verified response update that could not be decrypted/imported. */\n onIncomingUpdateIsolationFailure?:\n | ((failure: DocumentSyncUpdateIsolationError) => void | Promise<void>)\n | undefined;\n /** Fires immediately before a materialized outgoing batch is submitted. */\n onOutgoingUpdatesMaterialized?:\n | ((updateIds: readonly string[]) => void)\n | undefined;\n /** Invalidates continuation state after the server rejects its snapshot. */\n onPullContinuationInvalidated?:\n | ((continuation: DocumentSyncPullContinuation) => void | Promise<void>)\n | undefined;\n onTerminalSubmitFailure?: TerminalSubmitFailureHandler | undefined;\n pendingUpdates?: readonly PendingUpdateRecord[] | undefined;\n persistedState?: PersistedDocumentSyncState | null | undefined;\n rekeyPendingUpdate?: RekeyPendingUpdate | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n /** Validates decrypted updates against scratch state before callers persist. */\n validateIncomingUpdates: IncomingDocumentSyncUpdateValidator;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nexport async function tryPersistedReadOnlyDocumentSync(\n input: SyncRemoteDocumentInput,\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n): Promise<PersistedReadOnlyDocumentSyncResult | null> {\n if (input.stillCurrent?.() === false) return null;\n if ((input.pendingUpdates ?? []).length > 0) return null;\n\n return syncReadOnlyRemoteDocumentFromPersistedState({\n ...input,\n resolveProjectionUserKey,\n });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reportDocumentSyncQuarantine.js","sourceRoot":"","sources":["reportDocumentSyncQuarantine.ts"],"names":[],"mappings":"AAGA,MAAM,qBAAqB,GAAG,IAAI,OAAO,EAAkB,CAAC;AAE5D,4EAA4E;AAC5E,MAAM,UAAU,4BAA4B,CAC1C,KAAa,EACb,QAA0D,EAC1D,OAAyC;IAEzC,IAAI,CAAC,QAAQ;QAAE,OAAO;IACtB,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC;IAC5E,IAAI,qBAAqB,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,SAAS;QAAE,OAAO;IAC3D,4EAA4E;IAC5E,yEAAyE;IACzE,qBAAqB,CAAC,GAAG,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;IAC5C,IAAI,CAAC;QACH,KAAK,OAAO,CAAC,OAAO,CAClB,QAAQ,CAAC,qCAAqC,EAAE,OAAO,CAAC,CACzD,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC3B,CAAC;IAAC,MAAM,CAAC;QACP,8DAA8D;IAChE,CAAC;AACH,CAAC","sourcesContent":["import type { DocumentSyncUpdateIsolationError } from \"../../data/documents/shared/documentSyncUpdateIsolation\";\nimport type { WorkflowRuntimeUtilInput } from \"../shared/runtimeInput\";\n\nconst lastQuarantineByScope = new WeakMap<object, string>();\n\n/** Keep host diagnostics failures from replacing the durable quarantine. */\nexport function reportDocumentSyncQuarantine(\n scope: object,\n logError: WorkflowRuntimeUtilInput[\"logError\"] | undefined,\n failure: DocumentSyncUpdateIsolationError,\n): void {\n if (!logError) return;\n const signature = JSON.stringify([failure.message, failure.batchUpdateIds]);\n if (lastQuarantineByScope.get(scope) === signature) return;\n // Suppress repeats before the host appends local logs and breadcrumbs. Keep\n // only the last failure, and let discarded document scopes be collected.\n lastQuarantineByScope.set(scope, signature);\n try {\n void Promise.resolve(\n logError(\"Documents: sync updates quarantined\", failure),\n ).catch(() => undefined);\n } catch {\n // Hosts may throw synchronously or return a rejected promise.\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"subtreePurgeScope.js","sourceRoot":"","sources":["subtreePurgeScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAEpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAQ9E,SAAS,2BAA2B,CAClC,MAAwC;IAExC,OAAO,aAAa,CAAC,MAAM,CAAC,KAAK,CAAC;QAChC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,mBAAmB,CAAC;QAChD,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,sBAAsB,CACpC,IAAiD,EACjD,IAAkC;IAElC,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO;IAC/B,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAC1B,CAAC,MAAM,EAAE,EAAE,CAAC,uBAAuB,CAAC,MAAM,CAAC,KAAK,IAAI,CAAC,EAAE,CACxD,CAAC;IACF,wEAAwE;IACxE,qDAAqD;IACrD,IAAI,CAAC,UAAU,IAAI,2BAA2B,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,QAAQ;QAC1E,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;AACN,CAAC","sourcesContent":["import { isPlainObject } from \"@tearleads/validators/isPlainObject\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport { readManifestContainerId } from \"../../data/documents/shared/readers\";\n\n/** The selected purge root and the parent the user selected it under. */\nexport interface SubtreePurgeRoot {\n readonly id: string;\n readonly parentId: string | null;\n}\n\nfunction readSignedParentContainerId(\n bundle: AccessManifestBundleWireResponse,\n): unknown {\n return isPlainObject(bundle.state)\n ? Reflect.get(bundle.state, \"parentContainerId\")\n : undefined;\n}\n\n/** Check the exact verified path that the destructive request will cite. */\nexport function assertSubtreePurgePath(\n path: readonly AccessManifestBundleWireResponse[],\n root: SubtreePurgeRoot | undefined,\n): void {\n if (root === undefined) return;\n const rootBundle = path.find(\n (bundle) => readManifestContainerId(bundle) === root.id,\n );\n // A valid move out of the selected subtree, or a settled restore of the\n // selected root itself, is ordinary concurrent work.\n if (!rootBundle || readSignedParentContainerId(rootBundle) !== root.parentId)\n throw new Error(\n \"Document placement is outside the requested purge subtree\",\n );\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"sync.js","sourceRoot":"","sources":["sync.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAE,kCAAkC,EAAE,MAAM,yDAAyD,CAAC;AAC7G,OAAO,EAEL,wCAAwC,GACzC,MAAM,4CAA4C,CAAC;AAKpD,OAAO,EACL,sCAAsC,EAEtC,gCAAgC,GACjC,MAAM,yCAAyC,CAAC;AAEjD,OAAO,EAAE,2CAA2C,EAAE,MAAM,SAAS,CAAC;AACtE,OAAO,EAEL,gCAAgC,GACjC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,8BAA8B,EAC9B,kBAAkB,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E,CAAC,EAAE,gBAAgB,EAAE,UAAU,EAAE,EAAE,EAAE;oBACvD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;wBAAE,OAAO;oBAC7C,IAAI,CAAC,KAAK,CAAC,uBAAuB,EAAE,CAAC;wBACnC,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,yDAAyD,CAC1D,CAAC;oBACJ,CAAC;oBACD,OAAO,KAAK,CAAC,uBAAuB,CAAC;wBACnC,gBAAgB;wBAChB,UAAU;qBACX,CAAC,CAAC;gBACL,CAAC;gBACD,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;gBACxD,YAAY,EAAE,KAAK,CAAC,YAAY;gBAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;aACvE,CAAC;SACH,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,sCAAsC,CAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAC/D,IACE,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;YAChC,kCAAkC,CAAC,KAAK,CAAC,EACzC,CAAC;YACD,MAAM,KAAK,CAAC,gCAAgC,EAAE,CAAC,KAAK,CAAC,CAAC;QACxD,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { isDocumentUpdateCreatedEvent } from \"../../data/documents/documentSync\";\nimport { isDocumentSyncUpdateIsolationError } from \"../../data/documents/shared/documentSyncUpdateIsolation\";\nimport {\n type DocumentSyncPullContinuation,\n InvalidDocumentSyncPullContinuationError,\n} from \"../../data/documents/shared/syncPagination\";\nimport type {\n MaterializedDocumentSyncPlan,\n SyncRemoteDocumentResult,\n} from \"../../data/documents/shared/types\";\nimport {\n isProjectionVerificationCancelledError,\n type ProjectionUserKeyResolver,\n requireProjectionUserKeyResolver,\n} from \"../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../data/sqlite/documentPersistence\";\nimport { createVerifiedRemoteDocumentDeletionHandler } from \"./purge\";\nimport {\n type SyncRemoteDocumentInput,\n tryPersistedReadOnlyDocumentSync,\n} from \"./readOnlySync\";\nimport {\n abandonAfterRetryableConflicts,\n abandonBlockedSync,\n} from \"./syncAbandon\";\nimport {\n planDocumentSyncAttempt,\n projectionFailureHandler,\n} from \"./syncAttemptPlanning\";\nimport type {\n RemoteDocumentSyncAttemptOutcome,\n RemoteDocumentSyncAttemptState,\n} from \"./syncAttemptState\";\nimport { requireStandaloneAncestorRepairs } from \"./syncContainerRekeyPreparation\";\nimport {\n assertRawContinuationCanRetry,\n resolveSyncAttemptWriterProjection,\n submitDocumentSyncAttemptIfAllowed,\n} from \"./syncFailures\";\nimport { recoverablePendingUpdates } from \"./syncPlanRequestBounds\";\nimport { resolveSubmittedDocumentSyncResult } from \"./syncSubmittedResult\";\n\nexport function hasDocumentUpdateEvent(\n events: ReadonlyArray<unknown>,\n documentId: string | null | undefined,\n): boolean {\n if (!documentId) return false;\n return events.some(\n (event) =>\n isDocumentUpdateCreatedEvent(event) && event.documentId === documentId,\n );\n}\n/**\n * A retryable stale-projection conflict means this writer projection is behind\n * the server. Evict only this document so the next attempt re-derives targets.\n */\nfunction evictStaleProjectionForRetry(input: SyncRemoteDocumentInput): void {\n input.apiClient.evictDocumentWriterProjection?.(input.documentId);\n}\n\n/**\n * A pass may repair a covering-baseline rejection by regenerating queued\n * rotation checkpoints — but only when there is something to regenerate FROM\n * (a snapshot provider and queued checkpoint rows), the failed pass was not\n * already a heal or a regeneration (whose fresh baseline proves this device\n * is simply behind), and an attempt remains.\n */\nfunction canRegenerateQueuedCheckpoints(input: {\n materializedPlan: MaterializedDocumentSyncPlan;\n pendingUpdates: readonly PendingUpdateRecord[];\n regenerateQueuedCheckpoints: boolean;\n sync: SyncRemoteDocumentInput;\n}): boolean {\n return (\n !input.regenerateQueuedCheckpoints &&\n !input.materializedPlan.healedStaleContentKeyBundle &&\n input.sync.buildRotationSnapshot !== undefined &&\n input.pendingUpdates.some((update) => update.sourceVersionVector != null)\n );\n}\n\nasync function submitPlannedSyncAttempt(args: {\n attempt: number;\n materializedPlan: MaterializedDocumentSyncPlan;\n maxAttempts: number;\n pendingUpdates: readonly PendingUpdateRecord[];\n pullContinuation?: DocumentSyncPullContinuation | undefined;\n regenerateQueuedCheckpoints: boolean;\n sync: SyncRemoteDocumentInput;\n failureBlocksQueuedWrites: boolean;\n}) {\n try {\n return await submitDocumentSyncAttemptIfAllowed({\n apiClient: args.sync.apiClient,\n attempt: args.attempt,\n canRegenerateQueuedCheckpoints: canRegenerateQueuedCheckpoints({\n materializedPlan: args.materializedPlan,\n pendingUpdates: args.pendingUpdates,\n regenerateQueuedCheckpoints: args.regenerateQueuedCheckpoints,\n sync: args.sync,\n }),\n documentId: args.sync.documentId,\n expectedCommitLsnMode: args.pullContinuation?.commitLsnMode,\n isRemoteSyncBlocked: args.sync.isRemoteSyncBlocked,\n maxAttempts: args.maxAttempts,\n onInlineRepairRefused: () => requireStandaloneAncestorRepairs(args.sync),\n onRemoteDocumentDeleted: args.sync.onRemoteDocumentDeleted,\n onOutgoingUpdatesMaterialized: args.sync.onOutgoingUpdatesMaterialized,\n onSyncTrace: args.sync.onSyncTrace,\n onTerminalSubmitFailure: args.sync.onTerminalSubmitFailure,\n pendingUpdates: args.pendingUpdates,\n plan: args.materializedPlan.plan,\n failureBlocksQueuedWrites: args.failureBlocksQueuedWrites,\n stillCurrent: args.sync.stillCurrent,\n warmReferencedPrincipalPolicies:\n args.sync.warmReferencedPrincipalPolicies,\n });\n } catch (error) {\n if (\n error instanceof InvalidDocumentSyncPullContinuationError &&\n args.pullContinuation !== undefined &&\n args.sync.historyMode !== \"raw\"\n ) {\n return \"retry\" as const;\n }\n throw error;\n }\n}\n\nfunction resolveAttemptProjection(\n input: SyncRemoteDocumentInput,\n failureBlocksQueuedWrites: boolean,\n reusableWriterProjection: DocumentWriterProjectionResponse | null,\n) {\n return resolveSyncAttemptWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n onRemoteDocumentDeleted: input.onRemoteDocumentDeleted,\n onSyncAbandoned: input.onSyncAbandoned,\n onSyncTrace: input.onSyncTrace,\n onTerminalFailure: projectionFailureHandler(\n input,\n failureBlocksQueuedWrites,\n ),\n reusableWriterProjection,\n stillCurrent: input.stillCurrent,\n });\n}\nfunction resolveRemoteSyncProjectionUserKey(input: SyncRemoteDocumentInput) {\n return requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document sync\",\n );\n}\n\nasync function invalidatePullCursor(\n input: SyncRemoteDocumentInput,\n pullContinuation: DocumentSyncPullContinuation | undefined,\n): Promise<undefined> {\n if (pullContinuation !== undefined) {\n await input.onPullContinuationInvalidated?.(pullContinuation);\n }\n return undefined;\n}\n\nasync function preparePersistedDocumentSync(\n input: SyncRemoteDocumentInput,\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n): Promise<\n | { readonly kind: \"completed\"; result: SyncRemoteDocumentResult | null }\n | {\n readonly kind: \"continue\";\n pullContinuation: DocumentSyncPullContinuation | undefined;\n }\n> {\n let pullContinuation = input.pullContinuation;\n try {\n const persisted = await tryPersistedReadOnlyDocumentSync(\n input,\n resolveProjectionUserKey,\n );\n if (persisted?.kind === \"completed\") return persisted;\n if (persisted?.kind === \"not_completed\" && input.historyMode !== \"raw\") {\n pullContinuation = await invalidatePullCursor(input, pullContinuation);\n }\n } catch (error) {\n if (\n !(error instanceof InvalidDocumentSyncPullContinuationError) ||\n pullContinuation === undefined ||\n input.historyMode === \"raw\"\n ) {\n throw error;\n }\n pullContinuation = await invalidatePullCursor(input, pullContinuation);\n }\n return { kind: \"continue\", pullContinuation };\n}\n\nfunction failureBlocksQueuedWrites(input: {\n readonly pendingUpdates: readonly PendingUpdateRecord[];\n readonly recoveryPendingUpdateCount: number;\n}): boolean {\n return (\n input.pendingUpdates.length > 0 || input.recoveryPendingUpdateCount > 0\n );\n}\n\nasync function retryRemoteSyncAttempt(\n sync: SyncRemoteDocumentInput,\n continuation: DocumentSyncPullContinuation | undefined,\n): Promise<RemoteDocumentSyncAttemptOutcome> {\n evictStaleProjectionForRetry(sync);\n return {\n kind: \"retry\",\n pullContinuation: await invalidatePullCursor(sync, continuation),\n };\n}\n\nasync function runRemoteDocumentSyncAttempt(input: {\n attempt: number;\n maxAttempts: number;\n pendingUpdateIds: readonly string[];\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n state: RemoteDocumentSyncAttemptState;\n sync: SyncRemoteDocumentInput;\n}): Promise<RemoteDocumentSyncAttemptOutcome> {\n if (input.sync.stillCurrent?.() === false) {\n return { kind: \"complete\", result: null };\n }\n const blocksQueuedWrites = failureBlocksQueuedWrites({\n pendingUpdates: input.state.pendingUpdates,\n recoveryPendingUpdateCount: input.state.recoveryPendingUpdatesById.size,\n });\n const writerProjection = await resolveAttemptProjection(\n input.sync,\n blocksQueuedWrites,\n input.state.reusableWriterProjection,\n );\n if (input.sync.stillCurrent?.() === false || !writerProjection) {\n return { kind: \"complete\", result: null };\n }\n const planned = await planDocumentSyncAttempt({\n pendingUpdates: input.state.pendingUpdates,\n pullContinuation: input.state.pullContinuation,\n regenerateQueuedCheckpoints: input.state.regenerateQueuedCheckpoints,\n sync: input.sync,\n failureBlocksQueuedWrites: blocksQueuedWrites,\n writerProjection,\n });\n if (planned === \"retry\") {\n return retryRemoteSyncAttempt(input.sync, input.state.pullContinuation);\n }\n if (!planned || input.sync.stillCurrent?.() === false) {\n return { kind: \"complete\", result: null };\n }\n const [materializedPlan] = planned;\n const submitted = await submitPlannedSyncAttempt({\n attempt: input.attempt,\n materializedPlan,\n maxAttempts: input.maxAttempts,\n pendingUpdates: recoverablePendingUpdates(\n input.state.pendingUpdates,\n materializedPlan,\n ),\n pullContinuation: input.state.pullContinuation,\n regenerateQueuedCheckpoints: input.state.regenerateQueuedCheckpoints,\n sync: input.sync,\n failureBlocksQueuedWrites: blocksQueuedWrites,\n });\n if (input.sync.stillCurrent?.() === false || submitted === \"cancelled\") {\n return { kind: \"complete\", result: null };\n }\n if (submitted === \"retry\") {\n assertRawContinuationCanRetry(\n input.sync.historyMode,\n input.state.pullContinuation,\n );\n return retryRemoteSyncAttempt(input.sync, input.state.pullContinuation);\n }\n if (submitted === \"blocked\") {\n abandonBlockedSync(input.sync);\n return { kind: \"complete\", result: null };\n }\n if (submitted === \"stop\") {\n input.sync.onSyncAbandoned?.(\"the sync submit failed terminally\");\n return { kind: \"complete\", result: null };\n }\n if (submitted.kind === \"regenerate_queued_checkpoints\") {\n return { kind: \"regenerate\" };\n }\n if (submitted.kind === \"recover_update_id_conflict\") {\n // A lost response may mean the server committed both this update id and an\n // inline container rekey. Force the read-only recovery pass to observe that\n // committed successor projection instead of reusing a cached predecessor.\n evictStaleProjectionForRetry(input.sync);\n return { kind: \"recover\", updates: submitted.recoveryPendingUpdatesById };\n }\n const result = await resolveSubmittedDocumentSyncResult({\n materializedPlan,\n pendingUpdateIds: input.pendingUpdateIds,\n pullComplete: submitted.pullComplete,\n recoveryPendingUpdatesById: input.state.recoveryPendingUpdatesById,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n response: submitted.response,\n sync: input.sync,\n writerProjection: materializedPlan.writerProjection,\n });\n return {\n kind: \"complete\",\n result: input.sync.stillCurrent?.() === false ? null : result,\n };\n}\n\nasync function syncRemoteDocumentInternal(\n input: SyncRemoteDocumentInput,\n): Promise<SyncRemoteDocumentResult | null> {\n if (input.stillCurrent?.() === false) return null;\n const resolveProjectionUserKey = resolveRemoteSyncProjectionUserKey(input);\n const maxAttempts = 3;\n let pendingUpdates = input.pendingUpdates ?? [];\n const pendingUpdateIds = pendingUpdates.map((update) => update.id);\n let recoveryPendingUpdatesById = new Map<string, PendingUpdateRecord>();\n let regenerateQueuedCheckpoints = false;\n let reusableWriterProjection = input.writerProjection ?? null;\n const persistedSync = await preparePersistedDocumentSync(\n input,\n resolveProjectionUserKey,\n );\n if (input.stillCurrent?.() === false) return null;\n if (persistedSync.kind === \"completed\") return persistedSync.result;\n let pullContinuation = persistedSync.pullContinuation;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const outcome = await runRemoteDocumentSyncAttempt({\n attempt,\n maxAttempts,\n pendingUpdateIds,\n resolveProjectionUserKey,\n state: {\n pendingUpdates,\n pullContinuation,\n recoveryPendingUpdatesById,\n regenerateQueuedCheckpoints,\n reusableWriterProjection,\n },\n sync: input,\n });\n reusableWriterProjection = null;\n if (outcome.kind === \"complete\") return outcome.result;\n if (outcome.kind === \"retry\") {\n pullContinuation = outcome.pullContinuation;\n if (input.stillCurrent?.() === false) return null;\n continue;\n }\n if (outcome.kind === \"regenerate\") {\n regenerateQueuedCheckpoints = true;\n continue;\n }\n recoveryPendingUpdatesById = outcome.updates;\n pendingUpdates = [];\n }\n return abandonAfterRetryableConflicts(input);\n}\n\nexport async function syncRemoteDocument(\n input: SyncRemoteDocumentInput,\n): Promise<SyncRemoteDocumentResult | null> {\n try {\n return await syncRemoteDocumentInternal({\n ...input,\n onRemoteDocumentDeleted: createVerifiedRemoteDocumentDeletionHandler({\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedOrganizationId: input.author.organizationId,\n onVerifiedDeletion: ({ commitPurgeProof, documentId }) => {\n if (input.stillCurrent?.() === false) return;\n if (!input.onRemoteDocumentDeleted) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Remote document deletion requires atomic local teardown\",\n );\n }\n return input.onRemoteDocumentDeleted({\n commitPurgeProof,\n documentId,\n });\n },\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }),\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return null;\n if (\n input.stillCurrent?.() !== false &&\n isDocumentSyncUpdateIsolationError(error)\n ) {\n await input.onIncomingUpdateIsolationFailure?.(error);\n }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,CAAC,CAAC;IACvE,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,KAAyB,EACzB,KAAY;IAEZ,MAAM,OAAO,GAA8B;QACzC,IAAI,EAAE,iCAAiC;QACvC,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,EAAE,EAAE,KAAK;QACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;QACvB,MAAM,EAAE,IAAI;KACb,CAAC;IACF,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC,OAAO,CAAC,CAAC;IAC/C,KAAK,CAAC,eAAe,EAAE,CACrB,mEAAmE,CACpE,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { ContainerKekRepairInaccessibleError } from \"../../data/documents/shared/containerKekCurrency\";\nimport type { DocumentSyncSubmitFailure } from \"../../data/documents/shared/types\";\nimport type { SyncRemoteDocumentInput } from \"./readOnlySync\";\nimport { DocumentAncestorRepairAbandonedError } from \"./syncRepairAbandon\";\nimport { traceAncestorRepairAbandoned } from \"./syncTrace\";\n\n/** The ways a sync pass gives up without failing: writes stay queued. */\ntype AbandonedSyncInput = Pick<\n SyncRemoteDocumentInput,\n \"documentId\" | \"onSyncAbandoned\" | \"onSyncTrace\" | \"onTerminalSubmitFailure\"\n>;\n\nexport function abandonBlockedSync(input: AbandonedSyncInput): null {\n input.onSyncTrace?.(`document sync blocked document=${input.documentId}`);\n input.onSyncAbandoned?.(\"blocked\");\n return null;\n}\n\nexport function abandonAncestorRepair(\n input: AbandonedSyncInput,\n error: DocumentAncestorRepairAbandonedError,\n): null {\n // Trace as well as abandon: the store's onSyncAbandoned only parks the\n // document, and this path may already have issued server-side rekeys, so\n // abandoning untraced would leave a retrying loop with no way to see it.\n traceAncestorRepairAbandoned(input.onSyncTrace, {\n documentId: input.documentId,\n reason: error.reason,\n });\n input.onSyncAbandoned?.(error.reason);\n return null;\n}\n\n/**\n * The stale ancestor is one this writer can neither re-key nor be given the\n * key for, and one refetch has already confirmed nobody repaired it yet. The\n * writes stay queued; the durable row tells the write queue why, and the\n * dependent-path hint that follows the repair re-arms the pass.\n */\nexport async function abandonInaccessibleAncestorRepair(\n input: AbandonedSyncInput,\n error: ContainerKekRepairInaccessibleError,\n): Promise<null> {\n await input.onTerminalSubmitFailure?.({\n code: \"document_ancestor_repair_inaccessible\",\n message: error.message,\n ok: false,\n report: () => undefined,\n status: null,\n });\n return abandonAncestorRepair(\n input,\n new DocumentAncestorRepairAbandonedError(\"inaccessible\"),\n );\n}\n\nexport function abandonAfterRetryableConflicts(\n input: AbandonedSyncInput,\n): null {\n input.onSyncAbandoned?.(\"every sync attempt hit a retryable conflict\");\n return null;\n}\n\nexport async function abandonOversizedSyncPlan(\n input: AbandonedSyncInput,\n error: Error,\n): Promise<null> {\n const failure: DocumentSyncSubmitFailure = {\n code: \"document_sync_request_too_large\",\n message: error.message,\n ok: false,\n report: () => undefined,\n status: null,\n };\n await input.onTerminalSubmitFailure?.(failure);\n input.onSyncAbandoned?.(\n \"a queued update cannot fit within the document sync request limit\",\n );\n return null;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"syncAttemptPlanning.js","sourceRoot":"","sources":["syncAttemptPlanning.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,sCAAsC,EAAE,MAAM,qCAAqC,CAAC;AAC7F,OAAO,EAEL,6BAA6B,GAC9B,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,+BAA+B,EAAE,MAAM,2CAA2C,CAAC;AAE5F,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAC;AAEpE,OAAO,EAAE,sBAAs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AAK,CAAC,EAAE,CAAC;YAC5C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,wBAAwB,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACrD,CAAC;AACH,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { ContainerKekRepairInaccessibleError } from \"../../data/documents/shared/containerKekCurrency\";\nimport { assertDocumentManifestBundleConsistent } from \"../../data/documents/shared/readers\";\nimport {\n type DocumentSyncPullContinuation,\n resolvePullContinuationMinLsn,\n} from \"../../data/documents/shared/syncPagination\";\nimport type { PendingUpdateRecord } from \"../../data/sqlite/documentPersistence\";\nimport { isDocumentSyncRequestLimitError } from \"../../data/sync/documentSyncOutgoingBatch\";\nimport type { SyncRemoteDocumentInput } from \"./readOnlySync\";\nimport {\n abandonAncestorRepair,\n abandonBlockedSync,\n abandonInaccessibleAncestorRepair,\n abandonOversizedSyncPlan,\n} from \"./syncAbandon\";\nimport { prepareSyncAttemptContainerRekeys } from \"./syncContainerRekeyPreparation\";\nimport { buildRemoteDocumentSyncPlan } from \"./syncContainerRekeys\";\nimport type { TerminalSubmitFailureHandler } from \"./syncFailureClassification\";\nimport { retrySyncPlanOrAbandon } from \"./syncFailures\";\nimport {\n DocumentAncestorRepairAbandonedError,\n DocumentSyncPreparationRequiredError,\n} from \"./syncRepairAbandon\";\n\n/**\n * A write-bearing pass records through the submit handler (its queued writes\n * are what the failure blocks). A read-only pass records through the\n * revalidation handler so the refusal still leaves a durable trail instead\n * of silently never revalidating (edge-case row 13). A cursor continuation is\n * wire-level read-only, but its failure still blocks the queued writes it\n * deliberately deferred. Update-id recovery likewise empties the in-flight\n * batch while durable rows remain. Both keep the submit classification and\n * its 403 handling.\n */\nexport function projectionFailureHandler(\n input: SyncRemoteDocumentInput,\n failureBlocksQueuedWrites: boolean,\n): TerminalSubmitFailureHandler | undefined {\n return failureBlocksQueuedWrites\n ? input.onTerminalSubmitFailure\n : input.onReadOnlyProjectionFailure;\n}\nexport async function planDocumentSyncAttempt(input: {\n pendingUpdates: readonly PendingUpdateRecord[];\n pullContinuation?: DocumentSyncPullContinuation | undefined;\n regenerateQueuedCheckpoints: boolean;\n sync: SyncRemoteDocumentInput;\n failureBlocksQueuedWrites: boolean;\n writerProjection: DocumentWriterProjectionResponse;\n}) {\n try {\n const pendingUpdates =\n input.pullContinuation === undefined ? input.pendingUpdates : [];\n if (\n pendingUpdates.length &&\n input.sync.isRemoteSyncBlocked?.(\n (\n await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document sync manifest\",\n })\n ).organizationId,\n )\n ) {\n return abandonBlockedSync(input.sync);\n }\n // Durable repair happens once at this explicit attempt boundary. The\n // retryable builder below may only sign inline plans against its projection.\n const prepared =\n pendingUpdates.length &&\n !input.sync.buildContainerRekeys &&\n input.sync.buildRotationSnapshot\n ? await prepareSyncAttemptContainerRekeys(\n input.sync,\n input.writerProjection,\n )\n : { projection: input.writerProjection, plans: undefined };\n if (!prepared) return null;\n return await retrySyncPlanOrAbandon({\n apiClient: input.sync.apiClient,\n buildWithProjection: (projection) =>\n buildRemoteDocumentSyncPlan({\n pendingUpdates,\n preparedRekeys:\n projection === prepared.projection ? prepared.plans : undefined,\n minLsn: resolvePullContinuationMinLsn(\n input.pullContinuation,\n input.sync.minLsn,\n ),\n pullCursor: input.pullContinuation?.cursor,\n projection,\n regenerateQueuedCheckpoints: input.regenerateQueuedCheckpoints,\n sync: input.sync,\n }),\n documentId: input.sync.documentId,\n onRemoteDocumentDeleted: input.sync.onRemoteDocumentDeleted,\n onSyncAbandoned: input.sync.onSyncAbandoned,\n onSyncTrace: input.sync.onSyncTrace,\n onTerminalFailure: projectionFailureHandler(\n input.sync,\n input.failureBlocksQueuedWrites,\n ),\n stillCurrent: input.sync.stillCurrent,\n writerProjection: prepared.projection,\n });\n } catch (error) {\n if (error instanceof DocumentSyncPreparationRequiredError)\n return \"retry\" as const;\n if (error instanceof DocumentAncestorRepairAbandonedError) {\n return abandonAncestorRepair(input.sync, error);\n }\n if (error instanceof ContainerKekRepairInaccessibleError) {\n return abandonInaccessibleAncestorRepair(input.sync, error);\n }\n if (!isDocumentSyncRequestLimitError(error)) {\n throw error;\n }\n return abandonOversizedSyncPlan(input.sync, error);\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"syncAttemptState.js","sourceRoot":"","sources":["syncAttemptState.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { MaterializedContainerRekeyPlan } from \"../../data/containers/shared/types\";\nimport type { DocumentSyncPullContinuation } from \"../../data/documents/shared/syncPagination\";\nimport type { SyncRemoteDocumentResult } from \"../../data/documents/shared/types\";\nimport type { PendingUpdateRecord } from \"../../data/sqlite/documentPersistence\";\n\nexport type DocumentSyncContainerRekeyBuilder = (\n writerProjection: DocumentWriterProjectionResponse,\n verification: { readonly persistVerificationCheckpoints: false },\n) => Promise<readonly MaterializedContainerRekeyPlan[]>;\n\nexport interface RemoteDocumentSyncAttemptState {\n pendingUpdates: readonly PendingUpdateRecord[];\n pullContinuation: DocumentSyncPullContinuation | undefined;\n recoveryPendingUpdatesById: Map<string, PendingUpdateRecord>;\n regenerateQueuedCheckpoints: boolean;\n reusableWriterProjection: DocumentWriterProjectionResponse | null;\n}\n\nexport type RemoteDocumentSyncAttemptOutcome =\n | { kind: \"complete\"; result: SyncRemoteDocumentResult | null }\n | { kind: \"recover\"; updates: Map<string, PendingUpdateRecord> }\n | { kind: \"regenerate\" }\n | {\n kind: \"retry\";\n pullContinuation: DocumentSyncPullContinuation | undefined;\n };\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"syncAutomaticContainerRekeys.js","sourceRoot":"","sources":["syncAutomaticContainerRekeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,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;gBACH,MAAM,IAAI,oCAAoC,CAAC,SAAS,CAAC,CAAC;YAC5D,CAAC;YACD,qEAAqE;YACrE,uEAAuE;YACvE,uEAAuE;YACvE,MAAM,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC;gBACtC,CAAC,CAAC,IAAI,mCAAmC,CACrC,kBAAkB,CAAC,WAAW,CAC/B;gBACH,CAAC,CAAC,KAAK,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,UAAU,CAAC,GAAG,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAC/C,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpB,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../data/documents/shared/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../data/documents/shared/containerKekPath\";\nimport { documentContainerProjections } from \"../../data/keyingProjectionVerification/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../containers/child/rekey\";\nimport type { SyncRemoteDocumentInput } from \"./readOnlySync\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\nimport { DocumentAncestorRepairAbandonedError } from \"./syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"./syncRepairAccess\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n },\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: SyncRemoteDocumentInput,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"syncContainerRekeyPreparation.js","sourceRoot":"","sources":["sy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AO,MAAM,+BAA+B,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IACjE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IACE,CAAC,IAAI,CAAC,SAAS,CAAC,6BAA6B;YAC7C,CAAC,wCAAwC,CAAC,KAAK,CAAC;YAEhD,MAAM,KAAK,CAAC;IAChB,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC;QACrD,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;QACrD,eAAe,EAAE,IAAI,CAAC,eAAe;QACrC,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,iBAAiB,EAAE,IAAI,CAAC,uBAAuB;QAC/C,YAAY,EAAE,IAAI,CAAC,YAAY;KAChC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,CAAC,CAAC,+BAA+B,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport { acknowledgeContainerMutationBatch } from \"../../data/containers/shared/mutationAcknowledgement\";\nimport type { MaterializedContainerRekeyPlan } from \"../../data/containers/shared/types\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../data/documents/shared/projection\";\nimport { projectionVerificationOptions } from \"../../data/documents/shared/types\";\nimport { requireProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n submitContainerRotation,\n submitRotationCarryingDescendants,\n} from \"../containers/child/mutationSubmit\";\nimport type { SyncRemoteDocumentInput } from \"./readOnlySync\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\nimport { shouldRetrySyncWithFreshWriterProjection } from \"./syncFailureClassification\";\nimport { refreshSyncAttemptWriterProjection } from \"./syncFailures\";\nimport { DocumentAncestorRepairAbandonedError } from \"./syncRepairAbandon\";\n\n/**\n * Repairs committed during one sync pass, keyed by the pass's own input object\n * (stable across all three attempts). The sync loop explicitly prepares each\n * attempt, so a counter local to one call would not bound the whole pass.\n */\nconst passRepairTotals = new WeakMap<SyncRemoteDocumentInput, number>();\n\n/**\n * Passes whose inline repairs the server refused for stranding a level above a\n * directly granted container. The write's flat rekey list cannot say which\n * descendants each repair must carry; a standalone rekey can, so the rest of\n * the pass commits every repair standalone before writing.\n */\nconst standaloneRepairPasses = new WeakSet<SyncRemoteDocumentInput>();\n\nexport function requiresStandaloneAncestorRepairs(\n sync: SyncRemoteDocumentInput,\n): boolean {\n return standaloneRepairPasses.has(sync);\n}\n\nexport function requireStandaloneAncestorRepairs(\n sync: SyncRemoteDocumentInput,\n): void {\n standaloneRepairPasses.add(sync);\n}\n\n/** A refusal the writer cannot clear by retrying, as opposed to 5xx/offline. */\nfunction isTerminalRepairStatus(status: number | null): boolean {\n return status === 401 || status === 402 || status === 403;\n}\n\n/**\n * One standalone repair. Prefers the status-bearing rekey: a permanent refusal\n * (403 once ancestor write access is revoked, 402) must leave a durable record,\n * while a 5xx or an offline blip must not, and plain `rekeyContainer` collapses\n * both to null. It is also the only way to learn which descendant rekeys this\n * repair must carry. An adapter without it still repairs; its refusals are just\n * reported as an ordinary abandon.\n */\nfunction submitStandaloneRepair(\n sync: SyncRemoteDocumentInput,\n plan: MaterializedContainerRekeyPlan[\"plan\"],\n writerProjection: MaterializedContainerRekeyPlan[\"writerProjection\"],\n) {\n const options = {\n expectedPaymentRequiredOrganizationId: plan.state.organizationId,\n };\n const { getContainerWriterProjection, rekeyContainerResult } = sync.apiClient;\n return submitRotationCarryingDescendants({\n carriedRekeys: getContainerWriterProjection && {\n planning: {\n apiClient: {\n getContainerWriterProjection: getContainerWriterProjection.bind(\n sync.apiClient,\n ),\n },\n author: sync.author,\n execSql: sync.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n sync.resolveProjectionUserKey,\n \"Document ancestor repair\",\n ),\n stillCurrent: sync.stillCurrent,\n targetSecretKey: sync.targetSecretKey,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n },\n rotated: async () => writerProjection,\n },\n stillCurrent: sync.stillCurrent,\n submit: (carried) => {\n const request = carried.length\n ? { ...plan.request, containerRekeys: [...carried] }\n : plan.request;\n return submitContainerRotation({\n plain: () =>\n sync.apiClient.rekeyContainer(plan.containerId, request, options),\n result: rekeyContainerResult\n ? () =>\n rekeyContainerResult.call(\n sync.apiClient,\n plan.containerId,\n request,\n { ...options, reportErrors: false },\n )\n : undefined,\n });\n },\n });\n}\n\nasync function commitRepairPrefix(input: {\n plans: readonly MaterializedContainerRekeyPlan[];\n repairedIds: Set<string>;\n sync: SyncRemoteDocumentInput;\n}): Promise<number> {\n let committed = 0;\n for (const { plan, writerProjection } of input.plans) {\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n if (input.sync.isRemoteSyncBlocked?.(plan.state.organizationId)) {\n throw new DocumentAncestorRepairAbandonedError(\"blocked\");\n }\n if (input.repairedIds.has(plan.containerId)) {\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n const { carriedPlans, result } = await submitStandaloneRepair(\n input.sync,\n plan,\n writerProjection,\n );\n const response = result.ok ? result.data : null;\n // Deliberately not ContainerKekRepairRequiredError: that is classified as\n // retryable, so a handled refusal would re-sign the whole prefix before\n // failing again, and the retry never reaches onTerminalSubmitFailure\n // regardless, because this throws before submission.\n if (!response) {\n if (!result.ok && isTerminalRepairStatus(result.status)) {\n await input.sync.onTerminalSubmitFailure?.({\n code: \"document_ancestor_repair_refused\",\n message: `Ancestor repair refused for ${plan.containerId}`,\n ok: false,\n report: () => undefined,\n status: result.status,\n });\n }\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // What a repair carried committed with it, so the pins advance together.\n const acknowledged = await acknowledgeContainerMutationBatch({\n execSql: input.sync.execSql,\n plans: [plan, ...carriedPlans.map((carried) => carried.plan)],\n responses: [response, ...(response.containerRekeys ?? [])],\n stillCurrent: input.sync.stillCurrent,\n });\n if (!acknowledged) {\n // A refused guarded transaction is usually a generation flip; surface it\n // as the shared cancellation so syncRemoteDocument returns null instead\n // of reporting a routine flip as a sync failure.\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n throw new Error(\"Document ancestor repair was superseded\");\n }\n input.repairedIds.add(plan.containerId);\n for (const carried of carriedPlans) {\n input.repairedIds.add(carried.plan.containerId);\n }\n committed += 1 + carriedPlans.length;\n // The rest of this prefix was signed before the carry. A plan for a carried\n // container extends a superseded head, and one below it pins an epoch that\n // was never minted. Stop here; the caller refetches and re-plans.\n if (carriedPlans.length > 0) return committed;\n }\n return committed;\n}\n\n/**\n * Large repairs commit a bounded prefix; the last batch stays atomic with content.\n * A tighter local resource budget may be used, but never above the protocol cap.\n */\nexport async function prepareAutomaticContainerRekeys(\n sync: SyncRemoteDocumentInput,\n initialProjection: DocumentWriterProjectionResponse,\n maxRepairs = MAX_CONTAINER_PATH_LENGTH,\n): Promise<{\n plans: readonly MaterializedContainerRekeyPlan[];\n projection: DocumentWriterProjectionResponse;\n}> {\n if (initialProjection.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n let projection = initialProjection;\n const repairedIds = new Set<string>();\n // `repairedIds` only breaks a loop within one preparation. An explicit sync\n // retry starts another preparation with a fresh set. Bound the\n // work by the deepest authorizing path the protocol allows, counted across\n // the whole pass rather than per call: no honest chain needs more repairs\n // than that, so re-entry cannot multiply the budget.\n for (;;) {\n const batch = await buildAutomaticContainerRekeys(sync, projection);\n const commitsStandalone =\n batch.hasMore ||\n (batch.plans.length > 0 && standaloneRepairPasses.has(sync));\n if (!commitsStandalone) return { plans: batch.plans, projection };\n // Standalone mutations require authentic document scope before any request.\n // Persist the verified heads here, unlike the inline path: a committed\n // repair is acknowledged against the latest durable pin, and a repaired\n // ancestor is always past epoch 1, so a device that has never pinned it\n // would reject its own acknowledgement after the server already committed\n // the rekey. The inline path needs no pin because the sync response\n // re-verifies and pins before anything is acknowledged.\n await assertDocumentWriterProjectionConsistent(projection, {\n ...projectionVerificationOptions(sync),\n persistVerificationCheckpoints: true,\n allowStaleContentKeyBundle: true,\n });\n // Charge what this prefix can still commit, then settle to what it did: it\n // stops early after a repair that carried something, and charging the plans\n // it never submitted would spend the budget on work that did not happen.\n const committedBefore = passRepairTotals.get(sync) ?? 0;\n if (\n committedBefore + batch.plans.length >\n Math.min(maxRepairs, MAX_CONTAINER_PATH_LENGTH)\n ) {\n throw new DocumentAncestorRepairAbandonedError(\"depth-budget\");\n }\n passRepairTotals.set(\n sync,\n committedBefore +\n (await commitRepairPrefix({ plans: batch.plans, repairedIds, sync })),\n );\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n // Always a write-bearing pass, so a terminal projection failure (a 403\n // after revocation mid-repair) must leave the durable record that the\n // queued writes are blocked. onReadOnlyProjectionFailure is documented\n // for passes without queued writes and would not apply here.\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n if (!fresh) {\n // refreshSyncAttemptWriterProjection returns null on a generation flip.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n // It has already called onSyncAbandoned by this point, and on a coded 404\n // ran the verified local teardown, so a bare Error would double-signal as\n // an abandon plus a sync-lane crash.\n throw new DocumentAncestorRepairAbandonedError(\"unrefreshable\");\n }\n // The scope check above guards the first round only; a refetched projection\n // is server-supplied too, and nothing in the refresh path proves it names\n // the document this repair is for.\n if (fresh.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n projection = fresh;\n }\n}\n\n/** An explicit preparation retry may commit repairs; plan retries never do. */\nexport async function prepareSyncAttemptContainerRekeys(\n sync: SyncRemoteDocumentInput,\n projection: DocumentWriterProjectionResponse,\n) {\n try {\n return await prepareAutomaticContainerRekeys(sync, projection);\n } catch (error) {\n if (\n !sync.apiClient.evictDocumentWriterProjection ||\n !shouldRetrySyncWithFreshWriterProjection(error)\n )\n throw error;\n }\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n return fresh ? prepareAutomaticContainerRekeys(sync, fresh) : null;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"syncContainerRekeyProjection.js","sourceRoot":"","sources":["syncContainerRekeyProjection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AAGxE,OAAO,EACL,kCAAkC,EAClC,uBAAuB,GACxB,MAAM,qCAAqC,CAAC;AAE7C,SAAS,sBAAsB,CAAC,KAG/B;IACC,MAAM,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAC3C,CAAC,MAAM,EAAE,EAAE,CAAC,uBAAuB,CAAC,MAAM,CAAC,KAAK,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAC5E,CAAC;IACF,IAAI,KAAK,GAAG,CAAC;QAAE,OAAO,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IACxE,MAAM,gBAAgB,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACtD,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,CAAC,EAAE,qBAAqB,EAAE,IAAa,EAAE,CAAC;QAC7C,kBAAkB,EAAE;YAClB,GAAG,gBAAgB,CAAC,kBAAkB;YACtC,qBAAqB;YACrB,0BAA0B,EAAE,OAAO,CAAC,GAAG,CACrC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,mBAAmB,CACvC;YACD,6BAA6B,EAAE,OAAO,CAAC,GAAG,CACxC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,qBAAqB,CACzC;YACD,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;SAClD;KACF,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CAAC,KAGtD;IACC,IAAI,UAAU,GAAG,KAAK,CAAC,gBAAgB,CAAC;IACxC,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;QAC/B,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { computeDocumentContentKeyTargetHash } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { MaterializedContainerRekeyPlan } from \"../../data/containers/shared/types\";\nimport {\n normalizeDocumentKekTargetResponse,\n readManifestContainerId,\n} from \"../../data/documents/shared/readers\";\n\nfunction replaceRekeyedPathNode(input: {\n plan: MaterializedContainerRekeyPlan;\n projection: DocumentWriterProjectionResponse[\"authorizingContainerPaths\"][number];\n}) {\n const index = input.projection.path.findIndex(\n (bundle) => readManifestContainerId(bundle) === input.plan.plan.containerId,\n );\n if (index < 0) return { projection: input.projection, replaced: false };\n const previousManifest = input.projection.path[index];\n const previousKek = input.projection.containerKeks[index];\n const nextManifest = input.plan.writerProjection.path.at(-1);\n const nextKek = input.plan.writerProjection.containerKeks.at(-1);\n if (\n !previousManifest ||\n !previousKek ||\n !nextManifest ||\n !nextKek ||\n previousManifest.manifestHash !==\n input.plan.plan.previousManifest.manifestHash ||\n previousKek.accessManifestHash !== previousManifest.manifestHash\n ) {\n throw new Error(\"Document inline rekey projection predecessor mismatch\");\n }\n const path = [...input.projection.path];\n const containerKeks = [...input.projection.containerKeks];\n path[index] = nextManifest;\n containerKeks[index] = nextKek;\n return {\n projection: { ...input.projection, containerKeks, path },\n replaced: true,\n };\n}\n\nexport async function applyContainerRekeyPlan(\n writerProjection: DocumentWriterProjectionResponse,\n plan: MaterializedContainerRekeyPlan,\n): Promise<DocumentWriterProjectionResponse> {\n let replacedPath = false;\n const authorizingContainerPaths =\n writerProjection.authorizingContainerPaths.map((projection) => {\n const replaced = replaceRekeyedPathNode({ plan, projection });\n replacedPath ||= replaced.replaced;\n return replaced.projection;\n });\n const nextKek = plan.writerProjection.containerKeks.at(-1);\n const nextManifest = plan.writerProjection.path.at(-1);\n if (!nextKek || !nextManifest) {\n throw new Error(\"Document inline rekey projection is empty\");\n }\n let replacedTarget = false;\n const targets = normalizeDocumentKekTargetResponse(\n writerProjection.documentKekTargets,\n ).map((target) => {\n if (target.containerId !== plan.plan.containerId) return target;\n replacedTarget = true;\n return {\n ...target,\n containerKeyEpoch: nextKek.containerKeyEpoch,\n containerKeyEpochId: nextKek.containerKeyEpochId,\n containerManifestHash: nextManifest.manifestHash,\n };\n });\n if (!replacedPath && !replacedTarget) {\n throw new Error(\n \"Document inline rekey does not belong to its writer projection\",\n );\n }\n const documentKeyTargetHash =\n await computeDocumentContentKeyTargetHash(targets);\n return {\n ...writerProjection,\n authorizingContainerPaths,\n ...(documentKeyTargetHash === writerProjection.contentKeyBundle.targetHash\n ? {}\n : { contentKeyBundleStale: true as const }),\n documentKekTargets: {\n ...writerProjection.documentKekTargets,\n documentKeyTargetHash,\n linkedContainerKeyEpochIds: targets.map(\n (target) => target.containerKeyEpochId,\n ),\n linkedContainerManifestHashes: targets.map(\n (target) => target.containerManifestHash,\n ),\n targets: targets.map((target) => ({ ...target })),\n },\n };\n}\n\nexport async function applyDocumentSyncContainerRekeys(input: {\n plans: readonly MaterializedContainerRekeyPlan[];\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<DocumentWriterProjectionResponse> {\n let projection = input.writerProjection;\n for (const plan of input.plans) {\n projection = await applyContainerRekeyPlan(projection, plan);\n }\n return projection;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"syncContainerRekeys.js","sourceRoot":"","sources":["syncContainerRekeys.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAGlF,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EAAE,iCAAiC,EAAE,MAAM,oBAAoB,CAAC;AACvE,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,oCAAoC,EAAE,MAAM,qBAAqB,CAAC;AAE3E,6EAA6E;AAC7E,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,KAQjD;IACC,2EAA2E;IAC3E,4EAA4E;IAC5E,yEAAyE;IACzE,8EAA8E;IAC9E,8EAA8E;IAC9E,6EAA6E;IAC7E,4EAA4E;IAC5E,MAAM,kBAAkB,GAAG,KAAK,CAAC,IAAI,CAAC,qBAAqB,KAAK,SAAS,CAAC;IAC1E,IAAI,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IAC1C,IACE,KAAK,CAAC,cAAc,CAAC,MAAM;QAC3B,CAAC,KAAK,CAAC,IAAI,CAAC,oBAAoB;QAChC,kBAAkB;QAClB,cAAc,KAAK,SAAS,EAC5B,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,6BAA6B,CA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AAK,CAAC,IAAI,CAAC,qBAAqB;QACvD,eAAe,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC;QAC5D,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,OAAO;QAC3B,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;QACnC,mBAAmB;QACnB,kBAAkB,EAAE,KAAK,CAAC,IAAI,CAAC,kBAAkB;QACjD,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;QACnC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,8BAA8B,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;QACtE,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;QAC9D,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ;QAC7B,eAAe,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe;QAC3C,gBAAgB;QAChB,GAAG,6BAA6B,CAAC,KAAK,CAAC,IAAI,CAAC;KAC7C,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { MaterializedContainerRekeyPlan } from \"../../data/containers/shared/types\";\nimport { projectionVerificationOptions } from \"../../data/documents/shared/types\";\nimport type { PendingUpdateRecord } from \"../../data/sqlite/documentPersistence\";\nimport type { SyncRemoteDocumentInput } from \"./readOnlySync\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\nimport { requiresStandaloneAncestorRepairs } from \"./syncContainerRekeyPreparation\";\nimport { applyDocumentSyncContainerRekeys } from \"./syncContainerRekeyProjection\";\nimport { buildMaterializedDocumentSyncPlan } from \"./syncPlanMaterial\";\nimport { computeInlineRekeyCommitId } from \"./syncRekeyCommit\";\nimport { DocumentSyncPreparationRequiredError } from \"./syncRepairAbandon\";\n\n/** Plan only: standalone server repairs belong to the outer sync attempt. */\nexport async function buildRemoteDocumentSyncPlan(input: {\n preparedRekeys?: readonly MaterializedContainerRekeyPlan[] | undefined;\n minLsn?: string | undefined;\n pendingUpdates: readonly PendingUpdateRecord[];\n pullCursor?: string | undefined;\n projection: DocumentWriterProjectionResponse;\n regenerateQueuedCheckpoints: boolean;\n sync: SyncRemoteDocumentInput;\n}) {\n // Repairing this document's own container moves its key target hash, which\n // marks the content-key bundle stale. Only a pass that can build a rotation\n // snapshot is able to heal that; rotation settlement deliberately cannot\n // (`syncRequest.ts` omits the builder for `allowRecoveryBaseline: false`), so\n // repairing there would trade a classified \"ancestor repair required\" failure\n // for an unhealable bundle — after a standalone prefix may already have been\n // committed. Such a pass is left to fail as it did before automatic repair.\n const canHealStaleBundle = input.sync.buildRotationSnapshot !== undefined;\n let automaticPlans = input.preparedRekeys;\n if (\n input.pendingUpdates.length &&\n !input.sync.buildContainerRekeys &&\n canHealStaleBundle &&\n automaticPlans === undefined\n ) {\n const batch = await buildAutomaticContainerRekeys(\n input.sync,\n input.projection,\n );\n if (\n batch.hasMore ||\n (batch.plans.length > 0 && requiresStandaloneAncestorRepairs(input.sync))\n ) {\n throw new DocumentSyncPreparationRequiredError();\n }\n automaticPlans = batch.plans;\n }\n const rekeyPlans =\n input.pendingUpdates.length && input.sync.buildContainerRekeys\n ? await input.sync.buildContainerRekeys(input.projection, {\n persistVerificationCheckpoints: false,\n })\n : automaticPlans;\n const writerProjection = rekeyPlans?.length\n ? await applyDocumentSyncContainerRekeys({\n plans: rekeyPlans,\n writerProjection: input.projection,\n })\n : input.projection;\n let inlineRekeyCommitId: string | undefined;\n if (rekeyPlans?.length) {\n const headPendingUpdate = input.pendingUpdates[0];\n if (!headPendingUpdate) {\n throw new Error(\"Document inline rekey pending queue is empty\");\n }\n inlineRekeyCommitId = await computeInlineRekeyCommitId({\n headPendingUpdateId: headPendingUpdate.id,\n projection: input.projection,\n });\n }\n return buildMaterializedDocumentSyncPlan({\n author: input.sync.author,\n buildRotationSnapshot: input.sync.buildRotationSnapshot,\n containerRekeys: rekeyPlans?.map(({ plan }) => plan.request),\n execSql: input.sync.execSql,\n historyMode: input.sync.historyMode,\n inlineRekeyCommitId,\n localVersionVector: input.sync.localVersionVector,\n minLsn: input.minLsn,\n onSyncTrace: input.sync.onSyncTrace,\n pendingUpdates: input.pendingUpdates,\n persistVerificationCheckpoints: rekeyPlans?.length ? false : undefined,\n pullCursor: input.pullCursor,\n regenerateQueuedCheckpoints: input.regenerateQueuedCheckpoints,\n signedAt: input.sync.signedAt,\n targetSecretKey: input.sync.targetSecretKey,\n writerProjection,\n ...projectionVerificationOptions(input.sync),\n });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"syncContentKeys.js","sourceRoot":"","sources":["syncContentKeys.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,wBAAwB,EAAE,MAAM,+CAA+C,CAAC;AACzF,OAAO,EAAE,4BAA4B,EAAE,MAAM,oCAAoC,CAAC;AAClF,OAAO,EAAE,uCAAuC,EAAE,MAAM,0DAA0D,CAAC;AACnH,OAAO,EACL,kCAAkC,EAClC,6BAA6B,EAC7B,8BAA8B,GAC/B,MAAM,yDAAyD,CAAC;AACjE,OAAO,EACL,mCAAmC,EACnC,mCAAmC,EACnC,kCAAkC,EAClC,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAKtE,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAClF,OAAO,EAAE,yBAAyB,EAAE,MAAM,+CAA+C,CAAC;AAS1F,SAAS,4BAA4B,CACnC,KAAc;IAEd,OAAO,CACL,KAAK,YAAY,kCAAkC;QACnD,CAAC,KAAK,YAAY,+BAA+B;YAC/C,KAAK,CAAC,YAAY,YAAY,mCAAmC,CAA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,qBAAqB,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC;gBAC5D,SAAS;YACX,CAAC;YACD,kCAAkC,CAAC;gBACjC,KAAK,EAAE,KAAK;gBACZ,OAAO,EAAE,eAAe;aACzB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,IAAI,qBAAqB,EAAE,CAAC;QAC1B,MAAM,0BAA0B,CAAC;YAC/B,kBAAkB;YAClB,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,WAAW,EAAE,qBAAqB;YAClC,QAAQ,EAAE,KAAK,CAAC,uBAAuB;SACxC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,kBAAkB,CAAC;AAC5B,CAAC","sourcesContent":["import type {\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { importContentKeyMaterial } from \"../../data/documents/shared/contentRecordKeys\";\nimport { encryptDocumentPendingUpdate } from \"../../data/documents/shared/crypto\";\nimport { assertDocumentSyncUpdateEncryptedRecord } from \"../../data/documents/shared/documentSyncUpdateDecryption\";\nimport {\n isDocumentSyncUpdateIsolationError,\n isolateDocumentSyncBatchError,\n isolateDocumentSyncUpdateError,\n} from \"../../data/documents/shared/documentSyncUpdateIsolation\";\nimport {\n ContainerKekHistoryUnavailableError,\n collectContainerKeksForDocumentSync,\n DocumentContentKeyUnavailableError,\n DocumentHistoryUnavailableError,\n unwrapDocumentContentKeyFromBundle,\n} from \"../../data/documents/shared/projection\";\nimport { readWriteHeader } from \"../../data/documents/shared/readers\";\nimport type {\n DocumentSyncPreparedUpdate,\n ProjectionVerificationOptions,\n} from \"../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../data/documents/shared/types\";\nimport { isKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport type { PendingUpdateRecord } from \"../../data/sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\ntype SyncResponseUpdate = DocumentSyncResponse[\"updates\"][number];\ntype RawHistoryUnavailableCause =\n | DocumentContentKeyUnavailableError\n | DocumentHistoryUnavailableError;\n\nfunction isRawHistoryUnavailableCause(\n error: unknown,\n): error is RawHistoryUnavailableCause {\n return (\n error instanceof DocumentContentKeyUnavailableError ||\n (error instanceof DocumentHistoryUnavailableError &&\n error.historyCause instanceof ContainerKekHistoryUnavailableError)\n );\n}\n\ntype RawHistoryUnavailableValidator = (input: {\n contentKeysByEpoch: ReadonlyMap<number, Uint8Array>;\n updates: readonly SyncResponseUpdate[];\n}) => void | Promise<void>;\n\n/** A raw recovery cannot reconstruct history without this retained epoch. */\nexport class DocumentRawHistoryUnavailableError extends Error {\n readonly code = \"document_raw_history_epoch_unavailable\";\n\n constructor(\n readonly contentKeyEpoch: number,\n cause: unknown,\n ) {\n super(\n `Document raw-history recovery cannot decrypt content-key epoch ${contentKeyEpoch}`,\n { cause },\n );\n this.name = \"DocumentRawHistoryUnavailableError\";\n }\n}\n\nasync function assertResponseEncryptedRecords(\n updates: readonly SyncResponseUpdate[],\n): Promise<void> {\n const inspections = await Promise.allSettled(\n updates.map(assertDocumentSyncUpdateEncryptedRecord),\n );\n const failures = inspections.flatMap((inspection, index) =>\n inspection.status === \"rejected\"\n ? [{ index, reason: inspection.reason }]\n : [],\n );\n const firstFailure = failures[0];\n if (failures.length === 1 && firstFailure) {\n throw firstFailure.reason;\n }\n if (failures.length > 1 && firstFailure) {\n const stage =\n isDocumentSyncUpdateIsolationError(firstFailure.reason) &&\n failures.every(\n ({ reason }) =>\n isDocumentSyncUpdateIsolationError(reason) &&\n reason.stage === firstFailure.reason.stage,\n )\n ? firstFailure.reason.stage\n : \"encrypted_record\";\n throw isolateDocumentSyncBatchError({\n cause: new Error(\"Multiple document encrypted records are invalid\"),\n stage,\n updateIds: failures.map(({ index }) => updates[index]?.id ?? \"unknown\"),\n });\n }\n}\n\nasync function throwRawHistoryUnavailable(input: {\n contentKeysByEpoch: ReadonlyMap<number, Uint8Array>;\n response: DocumentSyncResponse;\n unavailable: { cause: RawHistoryUnavailableCause; contentKeyEpoch: number };\n validate?: RawHistoryUnavailableValidator | undefined;\n}): Promise<never> {\n await assertResponseEncryptedRecords(input.response.updates);\n await input.validate?.({\n contentKeysByEpoch: input.contentKeysByEpoch,\n updates: input.response.updates.filter((update) =>\n input.contentKeysByEpoch.has(\n readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n ).contentKeyEpoch,\n ),\n ),\n });\n throw new DocumentRawHistoryUnavailableError(\n input.unavailable.contentKeyEpoch,\n input.unavailable.cause,\n );\n}\n\nexport async function prepareDocumentOutgoingUpdates(input: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n organizationId: string;\n pendingUpdates: readonly PendingUpdateRecord[];\n}): Promise<DocumentSyncPreparedUpdate[]> {\n if (input.pendingUpdates.length === 0) {\n return [];\n }\n const contentKeyMaterial = await importContentKeyMaterial(input.contentKey);\n\n return Promise.all(\n input.pendingUpdates.map(async (update) => {\n const encrypted = await encryptDocumentPendingUpdate({\n contentKeyMaterial,\n contentKeyEpoch: input.contentKeyEpoch,\n documentId: input.documentId,\n organizationId: input.organizationId,\n update,\n });\n\n return {\n contentRecordId: encrypted.contentRecordId,\n encryptedData: encrypted.encryptedData,\n id: update.id,\n partialStartVersionVector: update.partialStartVersionVector,\n partialEndVersionVector: update.partialEndVersionVector,\n metadataHash: encrypted.metadataHash,\n ciphertextHash: encrypted.ciphertextHash,\n plaintextHash: encrypted.plaintextHash,\n ...(update.sourceVersionVector\n ? {\n checkpointKind: \"rotate_baseline\" as const,\n checkpointPayloadKind: \"full_history_snapshot\" as const,\n sourceVersionVector: update.sourceVersionVector,\n }\n : {}),\n };\n }),\n );\n}\n\nfunction syncResponseContentKeyBundlesByEpoch(\n response: DocumentSyncResponse,\n): ReadonlyMap<number, DocumentSyncResponse[\"contentKeyBundle\"]> {\n const byEpoch = new Map<number, DocumentSyncResponse[\"contentKeyBundle\"]>();\n\n for (const bundle of [\n response.contentKeyBundle,\n ...response.contentKeyBundles,\n ]) {\n if (byEpoch.has(bundle.contentKeyEpoch)) {\n throw new Error(\"Document sync response repeats a content-key epoch\");\n }\n byEpoch.set(bundle.contentKeyEpoch, bundle);\n }\n\n return byEpoch;\n}\n\nfunction syncResponseUpdatesByContentKeyEpoch(\n response: DocumentSyncResponse,\n): ReadonlyMap<number, readonly SyncResponseUpdate[]> {\n const updatesByEpoch = new Map<number, SyncResponseUpdate[]>();\n for (const update of response.updates) {\n let contentKeyEpoch: number;\n try {\n contentKeyEpoch = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n ).contentKeyEpoch;\n } catch (error) {\n throw isolateDocumentSyncUpdateError({\n cause: error,\n responseUpdate: update,\n stage: \"write_header\",\n updateId: update.id,\n });\n }\n const epochUpdates = updatesByEpoch.get(contentKeyEpoch);\n if (epochUpdates) epochUpdates.push(update);\n else updatesByEpoch.set(contentKeyEpoch, [update]);\n }\n return updatesByEpoch;\n}\n\nfunction assertBundleMatchesUpdateHeaders(input: {\n bundle: DocumentSyncResponse[\"contentKeyBundle\"];\n requireOriginalTargets: boolean;\n updates: readonly SyncResponseUpdate[];\n}): void {\n for (const update of input.updates) {\n const header = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n );\n if (\n header.objectId !== input.bundle.documentId ||\n header.contentKeyEpoch !== input.bundle.contentKeyEpoch ||\n (input.requireOriginalTargets &&\n (header.accessManifestHash !== input.bundle.linkSetManifestHash ||\n header.targetHash !== input.bundle.targetHash))\n ) {\n throw new Error(\n input.requireOriginalTargets\n ? \"Document sync response content key is unavailable and its bundle differs from the original update headers\"\n : \"Document sync response content-key bundle does not match its update headers\",\n );\n }\n }\n}\n\n/**\n * Linking can rewrap a retained key at the same content epoch. Its latest bundle\n * then has newer targets than older signed updates. A usable key is validated\n * by the caller's authenticated record decryption; the update's own historical\n * manifest, targets and signature are verified independently before this step.\n *\n * If the key cannot be recovered, require the original target commitments before\n * calling that an availability failure. Substituted unavailable targets must\n * still be quarantined, never disguised as legitimate missing history.\n */\nasync function unwrapHistoricalContentKey(input: {\n bundle: DocumentSyncResponse[\"contentKeyBundle\"];\n documentId: string;\n collectedKeks: Awaited<\n ReturnType<typeof collectContainerKeksForDocumentSync>\n >;\n updates: readonly SyncResponseUpdate[];\n}): Promise<Uint8Array> {\n assertBundleMatchesUpdateHeaders({ ...input, requireOriginalTargets: false });\n try {\n return await unwrapDocumentContentKeyFromBundle(\n input.bundle,\n input.documentId,\n input.collectedKeks.keksByEpochId,\n input.collectedKeks.predecessorFailuresByEpochId,\n input.collectedKeks.unattributedPredecessorFailuresByContainerId,\n );\n } catch (error) {\n if (isRawHistoryUnavailableCause(error)) {\n assertBundleMatchesUpdateHeaders({\n ...input,\n requireOriginalTargets: true,\n });\n }\n throw error;\n }\n}\n\n/** @internal Keeps epoch-wide failures anonymous and integrity failures typed. */\nexport function throwDocumentSyncContentKeyFailure(input: {\n cause: unknown;\n updates: readonly SyncResponseUpdate[];\n}): never {\n if (isKeyingVerificationError(input.cause)) {\n throw input.cause;\n }\n if (\n input.cause instanceof DocumentHistoryUnavailableError &&\n isKeyingVerificationError(input.cause.historyCause)\n ) {\n throw input.cause.historyCause;\n }\n throw isolateDocumentSyncBatchError({\n cause: input.cause,\n stage: \"content_key\",\n updateIds: input.updates.map((update) => update.id),\n });\n}\n\nexport async function unwrapDocumentSyncResponseContentKeys(\n input: {\n currentContentKey: Uint8Array;\n currentContentKeyEpoch: number;\n execSql?: ExecSql | undefined;\n historyMode?: \"raw\" | undefined;\n /** @internal Validate every decryptable sibling before raw availability wins. */\n onRawHistoryUnavailable?: RawHistoryUnavailableValidator | undefined;\n response: DocumentSyncResponse;\n targetSecretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<ReadonlyMap<number, Uint8Array>> {\n // A stale read-only pass can carry an empty placeholder when none of its\n // authorizing paths reaches the bundle target. Do not mark that epoch as\n // resolved: every served update must instead unwrap its bundle through the\n // verified predecessor KEK chain or fail with an honest error.\n const contentKeysByEpoch = new Map<number, Uint8Array>(\n input.currentContentKey.byteLength > 0\n ? [[input.currentContentKeyEpoch, input.currentContentKey]]\n : [],\n );\n const updatesByContentKeyEpoch = syncResponseUpdatesByContentKeyEpoch(\n input.response,\n );\n const missingContentKeyEpochs = [...updatesByContentKeyEpoch.keys()].filter(\n (contentKeyEpoch) => !contentKeysByEpoch.has(contentKeyEpoch),\n );\n missingContentKeyEpochs.sort((left, right) => left - right);\n if (missingContentKeyEpochs.length === 0) {\n return contentKeysByEpoch;\n }\n const missingUpdates = missingContentKeyEpochs.flatMap(\n (contentKeyEpoch) => updatesByContentKeyEpoch.get(contentKeyEpoch) ?? [],\n );\n let bundlesByEpoch: ReturnType<typeof syncResponseContentKeyBundlesByEpoch>;\n try {\n bundlesByEpoch = syncResponseContentKeyBundlesByEpoch(input.response);\n } catch (error) {\n throwDocumentSyncContentKeyFailure({\n cause: error,\n updates: missingUpdates,\n });\n }\n const absentBundleEpoch = missingContentKeyEpochs.find(\n (contentKeyEpoch) => !bundlesByEpoch.has(contentKeyEpoch),\n );\n if (absentBundleEpoch !== undefined) {\n throwDocumentSyncContentKeyFailure({\n cause: new Error(\"Document sync response content-key bundle missing\"),\n updates:\n updatesByContentKeyEpoch.get(absentBundleEpoch) ?? missingUpdates,\n });\n }\n const collectedKeks = await collectContainerKeksForDocumentSync({\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n let unavailableRawHistory:\n | { cause: RawHistoryUnavailableCause; contentKeyEpoch: number }\n | undefined;\n\n for (const contentKeyEpoch of missingContentKeyEpochs) {\n const bundle = bundlesByEpoch.get(contentKeyEpoch);\n const responseUpdates =\n updatesByContentKeyEpoch.get(contentKeyEpoch) ?? missingUpdates;\n if (!bundle) {\n const error = new Error(\n \"Document sync response content-key bundle missing\",\n );\n throwDocumentSyncContentKeyFailure({\n cause: error,\n updates: responseUpdates,\n });\n }\n try {\n contentKeysByEpoch.set(\n bundle.contentKeyEpoch,\n await unwrapHistoricalContentKey({\n bundle,\n collectedKeks,\n documentId: input.writerProjection.documentId,\n updates: responseUpdates,\n }),\n );\n } catch (error) {\n if (input.historyMode === \"raw\" && isRawHistoryUnavailableCause(error)) {\n unavailableRawHistory ??= { cause: error, contentKeyEpoch };\n continue;\n }\n throwDocumentSyncContentKeyFailure({\n cause: error,\n updates: responseUpdates,\n });\n }\n }\n\n if (unavailableRawHistory) {\n await throwRawHistoryUnavailable({\n contentKeysByEpoch,\n response: input.response,\n unavailable: unavailableRawHistory,\n validate: input.onRawHistoryUnavailable,\n });\n }\n\n return contentKeysByEpoch;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"syncFailureClassification.js","sourceRoot":"","sources":["syncFailureClassification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,6BAA6B,EAC7B,yBAAyB,GAC1B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,+BAA+B,EAAE,MAAM,kDAAkD,CAAC;AACnG,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,GACrC,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,yBAAyB,EAAE,MAAM,+CAA+C,CAAC;AAqB1F;;;;;GAKG;AACH,MAAM,UAAU,mCAAmC,CACjD,OAA8D;IAE9D,MAAM,MAAM,GACV,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;QAC/B,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE;QACxB,CAAC,CAAC,6BAA6B,CAAC;IACpC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,MAAM,GA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,0BAA0B,CACtE,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,uCAAuC,CAAC,OAIvD;IACC,OAAO,CACL,OAAO,CAAC,MAAM,KAAK,GAAG;QACtB,OAAO,CAAC,IAAI,KAAK,6BAA6B,CAAC,qBAAqB,CACrE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,KAI5C;IACC,OAAO,CACL,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,WAAW;QACjC,+BAA+B,CAAC,KAAK,CAAC,OAAO,CAAC,CAC/C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kCAAkC,CAAC,KAKlD;IACC,OAAO,CACL,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,WAAW;QACjC,KAAK,CAAC,kBAAkB,GAAG,CAAC;QAC5B,qCAAqC,CAAC,KAAK,CAAC,OAAO,CAAC,CACrD,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAAC,KAI9D;IACC,IAAI,CAAC,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QACzD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;IACxE,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n DOCUMENT_MUTATION_ERROR_CODES,\n DOCUMENT_SYNC_ERROR_CODES,\n} from \"@tearleads/validators/response\";\nimport { ContainerKekRepairRequiredError } from \"../../data/documents/shared/containerKekCurrency\";\nimport {\n isRetryableDocumentSyncConflict,\n isUpstreamDeletedDocumentSyncFailure,\n} from \"../../data/documents/shared/responses\";\nimport type { DocumentSyncSubmitFailure } from \"../../data/documents/shared/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { isKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nexport type RemoteDocumentDeletionHandler = (input: {\n /** Present only after the SDK has verified the signed terminal purge proof. */\n readonly commitPurgeProof?:\n | ((transactionExecSql: ExecSql) => Promise<void>)\n | undefined;\n readonly documentId: string;\n}) => Promise<void> | void;\n\n/**\n * Invoked when a submission fails terminally — the failure is neither a\n * retryable conflict nor a recoverable update-id conflict, so the sync pass\n * stops and the pending writes stay queued (e.g. a 403 after write access was\n * revoked). Callers persist the failure so the write queue can surface it.\n */\nexport type TerminalSubmitFailureHandler = (\n failure: DocumentSyncSubmitFailure,\n) => Promise<void> | void;\n\n/**\n * Read-only counterpart to describeDocumentSyncSubmitFailure: names a refused\n * revalidation without implying a blocked write. 403s never reach this — a\n * read-only 403 is deliberately suppressed (edge-case row 9) so unattempted\n * local edits are never flagged.\n */\nexport function describeDocumentRevalidationFailure(\n failure: Pick<DocumentSyncSubmitFailure, \"message\" | \"status\">,\n): string {\n const detail =\n failure.message.trim().length > 0\n ? failure.message.trim()\n : \"the server refused the read\";\n const suffix = failure.status === null ? \"\" : ` (${failure.status})`;\n return `Remote revalidation failed: ${detail}${suffix}`;\n}\n\n/** Human-readable description of a terminal submit failure for queue display. */\nexport function describeDocumentSyncSubmitFailure(\n failure: Pick<DocumentSyncSubmitFailure, \"message\" | \"status\">,\n): string {\n if (failure.status === 403) {\n return \"Write access denied by the server (403)\";\n }\n const message =\n failure.message.trim().length > 0 ? failure.message.trim() : \"Sync failed\";\n return failure.status === null ? message : `${message} (${failure.status})`;\n}\n\ntype ProjectionIntegrityErrorCode =\n | \"equivocation\"\n | \"rollback\"\n | \"stale_predecessor\";\n\nfunction keyingVerificationErrorCode(error: unknown): string | null {\n if (!isKeyingVerificationError(error) || !(error instanceof Error)) {\n return null;\n }\n const code = Reflect.get(error, \"code\");\n return typeof code === \"string\" ? code : null;\n}\n\nexport function projectionIntegrityErrorCode(\n error: unknown,\n): ProjectionIntegrityErrorCode | null {\n if (\n !(error instanceof KeyingVerificationError) &&\n !(error instanceof Error && error.name === \"KeyingVerificationError\")\n ) {\n return null;\n }\n\n const code = keyingVerificationErrorCode(error);\n return code === \"rollback\" ||\n code === \"equivocation\" ||\n code === \"stale_predecessor\"\n ? code\n : null;\n}\n\n/**\n * Shared shell for the stale-projection retry classifiers. A cached\n * projection older than a checkpoint we already recorded (\"rollback\") —\n * typical right after a peer shared/rotated a linked container — is resolved\n * by refetching the current projection. The refetch is safe: it cannot\n * bypass the anti-rollback check, because a genuinely rolled-back server\n * response re-throws on the rebuilt plan. Any other keying-verification\n * failure is terminal; anything else defers to the caller's message\n * predicate for its unwrap-failure shape.\n */\nexport function shouldRetryWithFreshProjection(\n error: unknown,\n messageMatches: (message: string) => boolean,\n): boolean {\n // A peer may already have repaired the chain. Refetch once; the same guard\n // rejects a still-stale response before any new ciphertext is produced.\n if (\n error instanceof ContainerKekRepairRequiredError ||\n error instanceof ProjectionDependencyUnavailableError\n )\n return true;\n const integrityErrorCode = projectionIntegrityErrorCode(error);\n if (integrityErrorCode) {\n return integrityErrorCode === \"rollback\";\n }\n if (keyingVerificationErrorCode(error) === \"invalid_shape\") {\n // Verification boundaries normalize malformed/stale projection data to a\n // terminal error. One cache eviction is still safe: a dishonest or broken\n // fresh response fails again outside this retry boundary.\n return true;\n }\n if (isKeyingVerificationError(error)) {\n return false;\n }\n\n return error instanceof Error && messageMatches(error.message);\n}\n\nexport function shouldRetrySyncWithFreshWriterProjection(\n error: unknown,\n): boolean {\n return shouldRetryWithFreshProjection(\n error,\n (message) =>\n message.startsWith(\n \"Document authorizing container KEK path could not be unwrapped\",\n ) && message.includes(\"Container writer projection KEK\"),\n );\n}\n\nexport function isRecoverableDocumentUpdateIdConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.updateIdConflict\n );\n}\n\n/**\n * The server's covering-baseline gate refused a queued rotation checkpoint\n * (e.g. a leftover from an interrupted recovery or a lost heal ack) because\n * it no longer covers the committed frontier. The pass can repair itself by\n * regenerating a fresh covering baseline from the live document instead of\n * resubmitting the stale payload — which would fail terminally forever.\n */\nexport function isCheckpointCoverageConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.checkpointCoverageConflict\n );\n}\n\n/**\n * A create submitted with a stable documentId whose first attempt already\n * committed server-side comes back as this 409 (see the server's\n * `assertCreateCanAdvanceDocumentHead`). It is not a failure — the caller adopts\n * the existing remote document instead of creating a duplicate.\n */\nexport function isDocumentManifestAlreadyExistsConflict(failure: {\n readonly code?: string | undefined;\n readonly message: string;\n readonly status: number | null;\n}): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_MUTATION_ERROR_CODES.manifestAlreadyExists\n );\n}\n\nexport function canRetryDocumentSyncConflict(input: {\n attempt: number;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n}): boolean {\n return (\n input.attempt < input.maxAttempts &&\n isRetryableDocumentSyncConflict(input.failure)\n );\n}\n\nexport function canRecoverDocumentUpdateIdConflict(input: {\n attempt: number;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n pendingUpdateCount: number;\n}): boolean {\n return (\n input.attempt < input.maxAttempts &&\n input.pendingUpdateCount > 0 &&\n isRecoverableDocumentUpdateIdConflict(input.failure)\n );\n}\n\nexport async function handleUpstreamDeletedDocumentSyncFailure(input: {\n documentId: string;\n failure: DocumentSyncSubmitFailure;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n}): Promise<boolean> {\n if (!isUpstreamDeletedDocumentSyncFailure(input.failure)) {\n return false;\n }\n\n await input.onRemoteDocumentDeleted?.({ documentId: input.documentId });\n return true;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"syncFailures.js","sourceRoot":"","sources":["syncFailures.ts"],"names":[],"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AAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,EAChC,CAAC;QACD,MAAM,gBAAgB,CAAC;IACzB,CAAC;IACD,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,KAY5C;IAIC,MAAM,OAAO,GAAG,MAAM,aAAa,CAAC,KAAK,CAAC,CAAC;IAC3C,IAAI,CAAC,OAAO,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QACjD,KAAK,CAAC,eAAe,EAAE,CACrB,+DAA+D,CAChE,CAAC;IACJ,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import {\n DOCUMENT_SYNC_ERROR_CODES,\n type DocumentSyncResponse,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n isUpstreamDeletedDocumentSyncFailure,\n submitDocumentSync,\n} from \"../../data/documents/shared/responses\";\nimport {\n type DocumentSyncCommitLsnMode,\n type DocumentSyncPullContinuation,\n InvalidDocumentSyncPullContinuationError,\n} from \"../../data/documents/shared/syncPagination\";\nimport type {\n DocumentSyncApi,\n DocumentSyncPlan,\n DocumentSyncSubmitFailure,\n MaterializedDocumentSyncPlan,\n} from \"../../data/documents/shared/types\";\nimport type { ReferencedPrincipalPolicyWarmer } from \"../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../data/sqlite/documentPersistence\";\nimport {\n canRecoverDocumentUpdateIdConflict,\n canRetryDocumentSyncConflict,\n handleUpstreamDeletedDocumentSyncFailure,\n isCheckpointCoverageConflict,\n type RemoteDocumentDeletionHandler,\n shouldRetrySyncWithFreshWriterProjection,\n type TerminalSubmitFailureHandler,\n} from \"./syncFailureClassification\";\nimport { recoverDocumentSyncPolicyRepair } from \"./syncPolicyRepair\";\nimport {\n type DocumentSyncTraceEmitter,\n traceProjectionFailed,\n traceSubmitFailed,\n} from \"./syncTrace\";\n\nconst REMOTE_DOCUMENT_DELETED = Symbol(\"remoteDocumentDeleted\");\n\nexport function assertRawContinuationCanRetry(\n historyMode: \"raw\" | undefined,\n pullContinuation: DocumentSyncPullContinuation | undefined,\n): void {\n if (historyMode === \"raw\" && pullContinuation !== undefined) {\n throw new InvalidDocumentSyncPullContinuationError(\n \"Document raw-history continuation became stale\",\n );\n }\n}\n\ntype DocumentWriterProjectionResolution =\n | DocumentWriterProjectionResponse\n | typeof REMOTE_DOCUMENT_DELETED\n | null;\n\ntype FailedDocumentSyncAction =\n | \"retry\"\n | \"stop\"\n | {\n readonly kind: \"recover_update_id_conflict\";\n readonly recoveryPendingUpdatesById: Map<string, PendingUpdateRecord>;\n }\n | { readonly kind: \"regenerate_queued_checkpoints\" };\n\ntype DocumentSyncAttemptSubmission =\n | {\n readonly kind: \"completed\";\n readonly pullComplete: boolean;\n readonly response: DocumentSyncResponse;\n }\n | FailedDocumentSyncAction\n | \"cancelled\"\n | \"blocked\";\n\nasync function resolveFailedDocumentSyncAction(input: {\n attempt: number;\n canRegenerateQueuedCheckpoints?: boolean | undefined;\n documentId: string;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n onInlineRepairRefused?: (() => void) | undefined;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n onSyncTrace?: DocumentSyncTraceEmitter | undefined;\n onTerminalSubmitFailure?: TerminalSubmitFailureHandler | undefined;\n pendingUpdates: readonly PendingUpdateRecord[];\n}): Promise<FailedDocumentSyncAction> {\n const action = await classifyFailedDocumentSyncAction(input);\n traceSubmitFailed(input.onSyncTrace, {\n action:\n action === \"retry\" || action === \"stop\"\n ? action\n : action.kind === \"recover_update_id_conflict\"\n ? \"recover-update-ids\"\n : \"regenerate-checkpoints\",\n code: input.failure.code,\n documentId: input.documentId,\n status: input.failure.status,\n });\n return action;\n}\n\nasync function classifyFailedDocumentSyncAction(input: {\n attempt: number;\n canRegenerateQueuedCheckpoints?: boolean | undefined;\n documentId: string;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n onInlineRepairRefused?: (() => void) | undefined;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n onTerminalSubmitFailure?: TerminalSubmitFailureHandler | undefined;\n pendingUpdates: readonly PendingUpdateRecord[];\n}): Promise<FailedDocumentSyncAction> {\n if (\n await handleUpstreamDeletedDocumentSyncFailure({\n documentId: input.documentId,\n failure: input.failure,\n onRemoteDocumentDeleted: input.onRemoteDocumentDeleted,\n })\n ) {\n return \"stop\";\n }\n\n if (\n canRetryDocumentSyncConflict({\n attempt: input.attempt,\n failure: input.failure,\n maxAttempts: input.maxAttempts,\n })\n ) {\n return \"retry\";\n }\n\n // The write rolled back whole. Its inline repairs would have stranded a\n // level above a directly granted container, and a flat rekey list cannot say\n // what each must carry: the retry commits them standalone instead.\n if (\n input.attempt < input.maxAttempts &&\n input.onInlineRepairRefused &&\n input.failure.code === DOCUMENT_SYNC_ERROR_CODES.descendantRekeysRequired\n ) {\n input.onInlineRepairRefused();\n return \"retry\";\n }\n\n if (\n canRecoverDocumentUpdateIdConflict({\n attempt: input.attempt,\n failure: input.failure,\n maxAttempts: input.maxAttempts,\n pendingUpdateCount: input.pendingUpdates.length,\n })\n ) {\n return {\n kind: \"recover_update_id_conflict\",\n recoveryPendingUpdatesById: new Map(\n input.pendingUpdates.map((update) => [update.id, update]),\n ),\n };\n }\n\n if (\n input.attempt < input.maxAttempts &&\n input.canRegenerateQueuedCheckpoints === true &&\n isCheckpointCoverageConflict(input.failure)\n ) {\n return { kind: \"regenerate_queued_checkpoints\" };\n }\n\n input.failure.report();\n await input.onTerminalSubmitFailure?.(input.failure);\n return \"stop\";\n}\n\nasync function submitDocumentSyncAttempt(input: {\n apiClient: DocumentSyncApi;\n attempt: number;\n canRegenerateQueuedCheckpoints?: boolean | undefined;\n documentId: string;\n expectedCommitLsnMode?: DocumentSyncCommitLsnMode | undefined;\n maxAttempts: number;\n onInlineRepairRefused?: (() => void) | undefined;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n onSyncTrace?: DocumentSyncTraceEmitter | undefined;\n onTerminalSubmitFailure?: TerminalSubmitFailureHandler | undefined;\n pendingUpdates: readonly PendingUpdateRecord[];\n plan: DocumentSyncPlan;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<DocumentSyncAttemptSubmission> {\n if (input.stillCurrent?.() === false) return \"cancelled\";\n const submitted = await submitDocumentSync({\n apiClient: input.apiClient,\n expectedCommitLsnMode: input.expectedCommitLsnMode,\n plan: input.plan,\n });\n if (input.stillCurrent?.() === false) return \"cancelled\";\n if (!submitted) {\n return \"stop\";\n }\n if (submitted.ok) {\n return {\n kind: \"completed\",\n pullComplete: submitted.pullComplete,\n response: submitted.response,\n };\n }\n\n await recoverDocumentSyncPolicyRepair({\n failure: submitted,\n plan: input.plan,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (input.stillCurrent?.() === false) return \"cancelled\";\n\n return resolveFailedDocumentSyncAction({\n attempt: input.attempt,\n canRegenerateQueuedCheckpoints: input.canRegenerateQueuedCheckpoints,\n documentId: input.documentId,\n failure: submitted,\n maxAttempts: input.maxAttempts,\n onInlineRepairRefused: input.onInlineRepairRefused,\n onRemoteDocumentDeleted: input.onRemoteDocumentDeleted,\n onSyncTrace: input.onSyncTrace,\n onTerminalSubmitFailure: input.onTerminalSubmitFailure,\n pendingUpdates: input.pendingUpdates,\n });\n}\n\nexport async function submitDocumentSyncAttemptIfAllowed(\n input: Parameters<typeof submitDocumentSyncAttempt>[0] & {\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n onOutgoingUpdatesMaterialized?:\n | ((updateIds: readonly string[]) => void)\n | undefined;\n failureBlocksQueuedWrites?: boolean | undefined;\n },\n): Promise<DocumentSyncAttemptSubmission> {\n const {\n failureBlocksQueuedWrites,\n isRemoteSyncBlocked,\n onOutgoingUpdatesMaterialized,\n ...submissionInput\n } = input;\n const hasRemoteWrites =\n input.plan.request.outgoingUpdates.length > 0 ||\n (input.plan.request.containerRekeys?.length ?? 0) > 0;\n if (hasRemoteWrites && isRemoteSyncBlocked?.(input.plan.organizationId)) {\n return \"blocked\";\n }\n if (input.stillCurrent?.() === false) return \"cancelled\";\n\n onOutgoingUpdatesMaterialized?.(\n input.plan.request.outgoingUpdates.map(({ id }) => id),\n );\n\n return submitDocumentSyncAttempt({\n ...submissionInput,\n // A read-only pass carries no writes, so a terminal failure describes a\n // pull, not queued local data — recording it would flag the next local\n // edit as failed before it was ever attempted. A cursor continuation and\n // update-id recovery both submit an empty request while durable rows still\n // exist; a terminal 403 there IS what blocks the queued edits.\n onTerminalSubmitFailure:\n hasRemoteWrites || failureBlocksQueuedWrites\n ? submissionInput.onTerminalSubmitFailure\n : undefined,\n });\n}\n\nasync function resolveDocumentSyncWriterProjection(input: {\n apiClient: DocumentSyncApi;\n documentId: string;\n onSyncTrace?: DocumentSyncTraceEmitter | undefined;\n /**\n * Invoked when the projection fetch fails terminally. Write-bearing sync\n * passes persist this: without a writer projection their queued writes can\n * never submit, so the failure (e.g. a 403 after access revocation) is what\n * the write queue should surface.\n */\n onTerminalFailure?: TerminalSubmitFailureHandler | undefined;\n reusableWriterProjection: DocumentWriterProjectionResponse | null;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<DocumentWriterProjectionResolution> {\n if (input.stillCurrent?.() === false) return null;\n if (input.reusableWriterProjection) {\n return input.reusableWriterProjection;\n }\n\n const result = await input.apiClient.getDocumentWriterProjectionResult(\n input.documentId,\n { reportErrors: false },\n );\n if (input.stillCurrent?.() === false) return null;\n if (result.ok) {\n return result.data;\n }\n if (isUpstreamDeletedDocumentSyncFailure(result)) {\n return REMOTE_DOCUMENT_DELETED;\n }\n traceProjectionFailed(input.onSyncTrace, {\n code: result.code,\n documentId: input.documentId,\n status: result.status,\n });\n result.report();\n await input.onTerminalFailure?.(result);\n return null;\n}\n\nexport async function retrySyncPlan(input: {\n apiClient: DocumentSyncApi;\n buildWithProjection: (\n projection: DocumentWriterProjectionResponse,\n ) => Promise<MaterializedDocumentSyncPlan>;\n documentId: string;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n onSyncTrace?: DocumentSyncTraceEmitter | undefined;\n onTerminalFailure?: TerminalSubmitFailureHandler | undefined;\n stillCurrent?: (() => boolean) | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<\n | readonly [MaterializedDocumentSyncPlan, DocumentWriterProjectionResponse]\n | null\n> {\n try {\n return [\n await input.buildWithProjection(input.writerProjection),\n input.writerProjection,\n ];\n } catch (error) {\n if (\n !input.apiClient.evictDocumentWriterProjection ||\n !shouldRetrySyncWithFreshWriterProjection(error)\n ) {\n throw error;\n }\n }\n if (input.stillCurrent?.() === false) return null;\n\n // Only this document's projection was stale; evict just it so unrelated\n // documents keep their warm cache instead of a global wipe.\n input.apiClient.evictDocumentWriterProjection?.(input.documentId);\n const writerProjection = await resolveDocumentSyncWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n onSyncTrace: input.onSyncTrace,\n onTerminalFailure: input.onTerminalFailure,\n reusableWriterProjection: null,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n if (writerProjection === REMOTE_DOCUMENT_DELETED) {\n await input.onRemoteDocumentDeleted?.({ documentId: input.documentId });\n return null;\n }\n if (!writerProjection) {\n return null;\n }\n\n return [await input.buildWithProjection(writerProjection), writerProjection];\n}\n\n/**\n * Resolves the writer projection for one sync attempt, converting the two\n * unrecoverable outcomes into an abandoned (null) result with a named reason\n * so callers that turn a null sync into their own error can surface the real\n * cause.\n */\nexport async function resolveSyncAttemptWriterProjection(input: {\n apiClient: DocumentSyncApi;\n documentId: string;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n onSyncAbandoned?: ((reason: string) => void) | undefined;\n onSyncTrace?: DocumentSyncTraceEmitter | undefined;\n onTerminalFailure?: TerminalSubmitFailureHandler | undefined;\n reusableWriterProjection: DocumentWriterProjectionResponse | null;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<DocumentWriterProjectionResponse | null> {\n const writerProjection = await resolveDocumentSyncWriterProjection(input);\n if (input.stillCurrent?.() === false) return null;\n if (writerProjection === REMOTE_DOCUMENT_DELETED) {\n await input.onRemoteDocumentDeleted?.({ documentId: input.documentId });\n if (input.stillCurrent?.() !== false) {\n input.onSyncAbandoned?.(\"the remote document was deleted\");\n }\n return null;\n }\n if (!writerProjection) {\n input.onSyncAbandoned?.(\n \"the document writer projection could not be fetched\",\n );\n return null;\n }\n return writerProjection;\n}\n\nexport async function refreshSyncAttemptWriterProjection(\n input: Omit<\n Parameters<typeof resolveSyncAttemptWriterProjection>[0],\n \"reusableWriterProjection\"\n > & { unavailableError?: unknown },\n): Promise<DocumentWriterProjectionResponse | null> {\n const { onRemoteDocumentDeleted, unavailableError, ...resolutionInput } =\n input;\n if (input.stillCurrent?.() === false) return null;\n if (input.apiClient.evictDocumentWriterProjection) {\n input.apiClient.evictDocumentWriterProjection(input.documentId);\n } else {\n input.apiClient.clearWriterProjectionCaches?.();\n }\n let remoteDocumentDeleted = false;\n const writerProjection = await resolveSyncAttemptWriterProjection({\n ...resolutionInput,\n onRemoteDocumentDeleted: async (deleted) => {\n remoteDocumentDeleted = true;\n await onRemoteDocumentDeleted?.(deleted);\n },\n reusableWriterProjection: null,\n });\n if (\n !writerProjection &&\n unavailableError !== undefined &&\n !remoteDocumentDeleted &&\n input.stillCurrent?.() !== false\n ) {\n throw unavailableError;\n }\n return writerProjection;\n}\n\nexport async function retrySyncPlanOrAbandon(input: {\n apiClient: DocumentSyncApi;\n buildWithProjection: (\n projection: DocumentWriterProjectionResponse,\n ) => Promise<MaterializedDocumentSyncPlan>;\n documentId: string;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n onSyncAbandoned?: ((reason: string) => void) | undefined;\n onSyncTrace?: DocumentSyncTraceEmitter | undefined;\n onTerminalFailure?: TerminalSubmitFailureHandler | undefined;\n stillCurrent?: (() => boolean) | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<\n | readonly [MaterializedDocumentSyncPlan, DocumentWriterProjectionResponse]\n | null\n> {\n const planned = await retrySyncPlan(input);\n if (!planned && input.stillCurrent?.() !== false) {\n input.onSyncAbandoned?.(\n \"a sync plan could not be built against the current projection\",\n );\n }\n return planned;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"syncLane.js","sourceRoot":"","sources":["syncLane.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gCAAgC,EAChC,0BAA0B,GAE3B,MAAM,iCAAiC,CAAC;AAEzC,uEAAuE;AACvE,uEAAuE;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAI7D,SAAS,sBAAsB,CAAC,OAAe;IAC7C,OAAO,aAAa,OAAO,EAAE,CAAC;AAChC,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,KAOxC;IACC,OAAO,gCAAgC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,YAAY,CACrE,sBAAsB,CAAC,KAAK,CAAC,OAAO,CAAC,EACrC;QACE,KAAK,EAAE,YAAY,KAAK,CAAC,OAAO,EAAE;QAClC,iBAAiB,EAAE,CAAC,KAAK,EAAE,EAAE;YAC3B,OAAO,CAAC,KAAK,CAAC,2BAA2B,KAAK,CAAC,OAAO,GAAG,EAAE,KAAK,CAAC,CAAC;QACpE,CAAC;QACD,KAAK,EAAE,UAAU;QACjB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,wEAAwE;QACxE,yEAAyE;QACzE,sEAAsE;QACtE,iEAAiE;QACjE,qBAAqB,EAAE,CAAC,KAAK,EAAE,EAAE,CAC/B,KAAK,CAAC,QAAQ,EAAE,CAAC,6BAA6B,EAAE,KAAK,CAAC;QACxD,GAAG,EAAE,KAAK,CAAC,GAAG;QACd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;YACd,OAAO;QACT,CAAC;QACD,KAAK,CAAC,OAAO,EAAE,CAAC;QAChB,OAAO,EAAE,CAAC;IACZ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n type SyncLane,\n} from \"../../data/sync/syncCoordinator\";\n\n// Facade re-export: document stores must reach this shared sync helper\n// through this workflow boundary, not by importing data/sync directly.\nexport { sequenceUnchanged } from \"../../data/sync/sequence\";\n\nexport type DocumentSyncLane = SyncLane;\n\nfunction getDocumentSyncLaneKey(localId: string): string {\n return `documents:${localId}`;\n}\n\nexport function registerDocumentSyncLane(input: {\n readonly domainScope: DomainScope;\n readonly localId: string;\n /** Host diagnostics sink; bare runtimes do not structure errors. */\n readonly logError?: ((message: string, error: unknown) => void) | undefined;\n readonly run: () => Promise<void>;\n readonly priority?: (() => number) | undefined;\n}): DocumentSyncLane {\n return getOrCreateDomainSyncCoordinator(input.domainScope).registerLane(\n getDocumentSyncLaneKey(input.localId),\n {\n label: `Document ${input.localId}`,\n onUnexpectedError: (error) => {\n console.error(`Failed to sync document ${input.localId}:`, error);\n },\n phase: \"document\",\n priority: input.priority,\n // Fixed literal: the local id stays in the console line above, never in\n // a report. The mapped stack identifies which lane body threw. Returning\n // the host's result hands a rejection to the lane reporter's wrapper;\n // discarding it would surface as an unhandled rejection instead.\n reportUnexpectedError: (error) =>\n input.logError?.(\"Documents: sync lane failed\", error),\n run: input.run,\n shouldIgnoreError: isDatabaseUnavailableError,\n },\n );\n}\n\nexport function requestDocumentSyncLaneAndWait(input: {\n readonly didCompleteRequest: () => boolean;\n readonly domainScope: DomainScope;\n readonly localId: string;\n readonly onInvalidated?: (() => void) | undefined;\n readonly request: () => void;\n readonly signal?: AbortSignal | undefined;\n}): Promise<boolean> {\n if (input.signal?.aborted) {\n input.onInvalidated?.();\n return Promise.resolve(false);\n }\n const coordinator = getOrCreateDomainSyncCoordinator(input.domainScope);\n const laneKey = getDocumentSyncLaneKey(input.localId);\n const initialLane = coordinator\n .getSnapshot()\n .lanes.find((lane) => lane.key === laneKey);\n if (!initialLane) {\n return Promise.resolve(false);\n }\n if (initialLane.runAbandoned) {\n return Promise.resolve(false);\n }\n const baselineRunCount = initialLane.runCount;\n return new Promise((resolve) => {\n let settled = false;\n let unsubscribe: () => void = () => undefined;\n const finish = (completed: boolean) => {\n if (settled) {\n return;\n }\n settled = true;\n unsubscribe();\n input.signal?.removeEventListener(\"abort\", handleAbort);\n resolve(completed);\n };\n const handleAbort = () => {\n if (settled) {\n return;\n }\n input.onInvalidated?.();\n finish(false);\n };\n const inspect = () => {\n if (coordinator.isDisposed()) {\n handleAbort();\n return;\n }\n const lane = coordinator\n .getSnapshot()\n .lanes.find((candidate) => candidate.key === laneKey);\n if (!lane) {\n handleAbort();\n return;\n }\n if (lane.runAbandoned) {\n handleAbort();\n return;\n }\n if (lane.runCount <= baselineRunCount || lane.running || lane.requested) {\n return;\n }\n if (lane.lastAction === \"completed\" || lane.lastAction === \"failed\") {\n finish(lane.lastAction === \"completed\" && input.didCompleteRequest());\n }\n };\n unsubscribe = coordinator.subscribe(inspect);\n input.signal?.addEventListener(\"abort\", handleAbort, { once: true });\n if (input.signal?.aborted) {\n handleAbort();\n return;\n }\n input.request();\n inspect();\n });\n}\n"]}