@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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"syncAttemptPlanning.js","sourceRoot":"","sources":["syncAttemptPlanning.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,qDAAqD,CAAC;AAC1G,OAAO,EAAE,sCAAsC,EAAE,MAAM,wCAAwC,CAAC;AAChG,OAAO,EAEL,6BAA6B,GAC9B,MAAM,+CAA+C,CAAC;AAEvD,OAAO,EAAE,+BAA+B,EAAE,MAAM,8CAA8C,CAAC;AAC/F,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AAErC,OAAO,EACL,oCAAoC,EACpC,oCAAoC,GACrC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,iCAAiC,EAAE,MAAM,6CAA6C,CAAC;AAChG,OAAO,EAAE,2BAA2B,EAAE,MAAM,mCAAmC,CAAC;AAGhF;;;;;;;;;GASG;AACH,MAAM,UAAU,wBAAwB,CACtC,KAA8B,EAC9B,yBAAkC;IAElC,OAAO,yBAAyB;QAC9B,CAAC,CAAC,KAAK,CAAC,uBAAuB;QAC/B,CAAC,CAAC,KAAK,CAAC,2BAA2B,CAAC;AACxC,CAAC;AACD,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,KAO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BAAgB,EAAE,MAAM;gBAC1C,UAAU;gBACV,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;gBAC9D,IAAI,EAAE,KAAK,CAAC,IAAI;aACjB,CAAC;YACJ,UAAU,EAAE,KAAK,CAAC,IAAI,CAAC,UAAU;YACjC,uBAAuB,EAAE,KAAK,CAAC,IAAI,CAAC,uBAAuB;YAC3D,eAAe,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe;YAC3C,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;YACnC,iBAAiB,EAAE,wBAAwB,CACzC,KAAK,CAAC,IAAI,EACV,KAAK,CAAC,yBAAyB,CAChC;YACD,YAAY,EAAE,KAAK,CAAC,IAAI,CAAC,YAAY;YACrC,gBAAgB,EAAE,QAAQ,CAAC,UAAU;SACtC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,oCAAoC;YACvD,OAAO,OAAgB,CAAC;QAC1B,IAAI,KAAK,YAAY,oCAAoC,EAAE,CAAC;YAC1D,OAAO,qBAAqB,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAClD,CAAC;QACD,IAAI,KAAK,YAAY,mCAAmC,EAAE,CAAC;YACzD,OAAO,iCAAiC,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC9D,CAAC;QACD,IAAI,CAAC,+BAA+B,CAAC,KAAK,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 { retrySyncPlanOrAbandon } from \"../syncFailures\";\nimport {\n abandonAncestorRepair,\n abandonBlockedSync,\n abandonInaccessibleAncestorRepair,\n abandonOversizedSyncPlan,\n} from \"../syncFailures/syncAbandon\";\nimport type { TerminalSubmitFailureHandler } from \"../syncFailures/syncFailureClassification\";\nimport {\n DocumentAncestorRepairAbandonedError,\n DocumentSyncPreparationRequiredError,\n} from \"../syncFailures/syncRepairAbandon\";\nimport { prepareSyncAttemptContainerRekeys } from \"../syncRekeys/syncContainerRekeyPreparation\";\nimport { buildRemoteDocumentSyncPlan } from \"../syncRekeys/syncContainerRekeys\";\nimport type { SyncRemoteDocumentInput } from \"./readOnlySync\";\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,8 +1,8 @@
1
- import type { DocumentWriterProjectionResponse } from "../../internal/validators/response/index.js";
2
- import type { MaterializedContainerRekeyPlan } from "../../data/containers/shared/types.js";
3
- import type { DocumentSyncPullContinuation } from "../../data/documents/shared/syncPagination.js";
4
- import type { SyncRemoteDocumentResult } from "../../data/documents/shared/types.js";
5
- import type { PendingUpdateRecord } from "../../data/sqlite/documentPersistence.js";
1
+ import type { DocumentWriterProjectionResponse } from "../../../internal/validators/response/index.js";
2
+ import type { MaterializedContainerRekeyPlan } from "../../../data/containers/shared/types.js";
3
+ import type { DocumentSyncPullContinuation } from "../../../data/documents/shared/syncPagination.js";
4
+ import type { SyncRemoteDocumentResult } from "../../../data/documents/shared/types.js";
5
+ import type { PendingUpdateRecord } from "../../../data/sqlite/documentPersistence.js";
6
6
  export type DocumentSyncContainerRekeyBuilder = (writerProjection: DocumentWriterProjectionResponse, verification: {
7
7
  readonly persistVerificationCheckpoints: false;
8
8
  }) => Promise<readonly MaterializedContainerRekeyPlan[]>;
@@ -0,0 +1 @@
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,6 +1,6 @@
1
- import type { DomainScope } from "../../data/shared/domainScope.js";
2
- import { type SyncLane } from "../../data/sync/syncCoordinator.js";
3
- export { sequenceUnchanged } from "../../data/sync/sequence.js";
1
+ import type { DomainScope } from "../../../data/shared/domainScope.js";
2
+ import { type SyncLane } from "../../../data/sync/syncCoordinator.js";
3
+ export { sequenceUnchanged } from "../../../data/sync/sequence.js";
4
4
  export type DocumentSyncLane = SyncLane;
5
5
  export declare function registerDocumentSyncLane(input: {
6
6
  readonly domainScope: DomainScope;
@@ -1,7 +1,7 @@
1
- import { getOrCreateDomainSyncCoordinator, isDatabaseUnavailableError, } from "../../data/sync/syncCoordinator.js";
1
+ import { getOrCreateDomainSyncCoordinator, isDatabaseUnavailableError, } from "../../../data/sync/syncCoordinator.js";
2
2
  // Facade re-export: document stores must reach this shared sync helper
3
3
  // through this workflow boundary, not by importing data/sync directly.
4
- export { sequenceUnchanged } from "../../data/sync/sequence.js";
4
+ export { sequenceUnchanged } from "../../../data/sync/sequence.js";
5
5
  function getDocumentSyncLaneKey(localId) {
6
6
  return `documents:${localId}`;
7
7
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"syncLane.js","sourceRoot":"","sources":["syncLane.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gCAAgC,EAChC,0BAA0B,GAE3B,MAAM,oCAAoC,CAAC;AAE5C,uEAAuE;AACvE,uEAAuE;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAIhE,SAAS,sBAAsB,CAAC,OAAe;IAC7C,OAAO,aAAa,OAAO,EAAE,CAAC;AAChC,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,KAOxC;IACC,OAAO,gCAAgC,CAAC,KAAK,CAAC,WAA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C,OAAO,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;gBACxE,OAAO;YACT,CAAC;YACD,IAAI,IAAI,CAAC,UAAU,KAAK,WAAW,IAAI,IAAI,CAAC,UAAU,KAAK,QAAQ,EAAE,CAAC;gBACpE,MAAM,CAAC,IAAI,CAAC,UAAU,KAAK,WAAW,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC,CAAC;YACxE,CAAC;QACH,CAAC,CAAC;QACF,WAAW,GAAG,WAAW,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QAC7C,KAAK,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QACrE,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;YAC1B,WAAW,EAAE,CAAC;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"]}
@@ -1,12 +1,12 @@
1
- import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
- import { decryptDocumentSyncUpdatesByEpoch } from "../../data/documents/shared/crypto.js";
3
- import { isolateDocumentSyncBatchError, } from "../../data/documents/shared/documentSyncUpdateIsolation.js";
4
- import { assertDocumentWriterProjectionConsistent } from "../../data/documents/shared/projection.js";
5
- import { DocumentSyncResponseUpdateContentKeyError, persistedDocumentSyncStateFromResponse, } from "../../data/documents/shared/responses.js";
6
- import { projectionVerificationOptions } from "../../data/documents/shared/types.js";
7
- import { unwrapDocumentSyncResponseContentKeys } from "./syncContentKeys.js";
8
- import { acceptedHeldBackPendingUpdateIds, responseAcceptedRecoveryBaseline, } from "./syncPlanRequestBounds.js";
9
- import { rekeyAndReportUnsettledRecoveryPendingUpdates, settledPendingUpdateIdsFromSync, } from "./syncRecoveryRekey.js";
1
+ import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
+ import { decryptDocumentSyncUpdatesByEpoch } from "../../../data/documents/shared/crypto.js";
3
+ import { isolateDocumentSyncBatchError, } from "../../../data/documents/shared/documentSyncUpdateIsolation.js";
4
+ import { assertDocumentWriterProjectionConsistent } from "../../../data/documents/shared/projection.js";
5
+ import { DocumentSyncResponseUpdateContentKeyError, persistedDocumentSyncStateFromResponse, } from "../../../data/documents/shared/responses.js";
6
+ import { projectionVerificationOptions } from "../../../data/documents/shared/types.js";
7
+ import { unwrapDocumentSyncResponseContentKeys } from "../syncPlan/syncContentKeys.js";
8
+ import { acceptedHeldBackPendingUpdateIds, responseAcceptedRecoveryBaseline, } from "../syncPlan/syncPlanRequestBounds.js";
9
+ import { rekeyAndReportUnsettledRecoveryPendingUpdates, settledPendingUpdateIdsFromSync, } from "../syncRekeys/syncRecoveryRekey.js";
10
10
  function isolateContentKeyResponseFailure(error, response) {
11
11
  if (!(error instanceof DocumentSyncResponseUpdateContentKeyError) ||
12
12
  response.updates.length === 0) {
@@ -0,0 +1 @@
1
+ {"version":3,"file":"syncResponseResult.js","sourceRoot":"","sources":["syncResponseResult.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAEL,6BAA6B,GAC9B,MAAM,4DAA4D,CAAC;AACpE,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EACL,yCAAyC,EACzC,sCAAsC,GACvC,MAAM,0CAA0C,CAAC;AAMlD,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AAQrF,OAAO,EAAE,qCAAqC,EAAE,MAAM,6BAA6B,CAAC;AACpF,OAAO,EACL,gCAAgC,EAChC,gCAAgC,GACjC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAEL,6CAA6C,EAC7C,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AAEzC,SAAS,gCAAgC,CACvC,KAAc,EACd,QAA8B;IAE9B,IACE,CAAC,CAAC,KAAK,YAAY,yCAAyC,CAAC;QAC7D,QAAQ,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,EAC7B,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;IACD,MAAM,6BAA6B,CAAC;QAClC,KAAK,EAAE,IAAI,uBAAuB,CAAC,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC;QAClE,KAAK,EAAE,aAAa;QACpB,SAAS,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC;KACvD,CAAC,CAAC;AACL,CAAC;AAkBD,sFAAsF;AACtF,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,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AwB;QACxB,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;KACzC,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { decryptDocumentSyncUpdatesByEpoch } from \"../../../data/documents/shared/crypto\";\nimport {\n type IncomingDocumentSyncUpdateValidator,\n isolateDocumentSyncBatchError,\n} from \"../../../data/documents/shared/documentSyncUpdateIsolation\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport {\n DocumentSyncResponseUpdateContentKeyError,\n persistedDocumentSyncStateFromResponse,\n} from \"../../../data/documents/shared/responses\";\nimport type {\n DocumentWriterPublicKeyResolver,\n MaterializedDocumentSyncPlan,\n SyncRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/types\";\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 type { TerminalSubmitFailureHandler } from \"../syncFailures/syncFailureClassification\";\nimport { unwrapDocumentSyncResponseContentKeys } from \"../syncPlan/syncContentKeys\";\nimport {\n acceptedHeldBackPendingUpdateIds,\n responseAcceptedRecoveryBaseline,\n} from \"../syncPlan/syncPlanRequestBounds\";\nimport {\n type RekeyPendingUpdate,\n rekeyAndReportUnsettledRecoveryPendingUpdates,\n settledPendingUpdateIdsFromSync,\n} from \"../syncRekeys/syncRecoveryRekey\";\n\nfunction isolateContentKeyResponseFailure(\n error: unknown,\n response: DocumentSyncResponse,\n): never {\n if (\n !(error instanceof DocumentSyncResponseUpdateContentKeyError) ||\n response.updates.length === 0\n ) {\n throw error;\n }\n throw isolateDocumentSyncBatchError({\n cause: new KeyingVerificationError(\"invalid_shape\", error.message),\n stage: \"content_key\",\n updateIds: response.updates.map((update) => update.id),\n });\n}\n\ntype SyncRemoteDocumentResultInput = {\n execSql: ExecSql;\n materializedPlan: MaterializedDocumentSyncPlan;\n onTerminalSubmitFailure?: TerminalSubmitFailureHandler | undefined;\n recoveryPendingUpdatesById: ReadonlyMap<string, PendingUpdateRecord>;\n rekeyPendingUpdate?: RekeyPendingUpdate | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n response: DocumentSyncResponse;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n validateIncomingUpdates: IncomingDocumentSyncUpdateValidator;\n writerProjection: DocumentWriterProjectionResponse;\n};\n\n/** @internal Exercises poison precedence for the decryptable subset of a raw page. */\nexport async function validateDecryptableRawHistorySiblings(input: {\n contentKeysByEpoch: ReadonlyMap<number, Uint8Array>;\n documentId: string;\n organizationId: string;\n response: DocumentSyncResponse;\n updates: readonly DocumentSyncResponse[\"updates\"][number][];\n validateIncomingUpdates: IncomingDocumentSyncUpdateValidator;\n}): Promise<void> {\n if (input.updates.length === 0) return;\n const decryptedUpdates = await decryptDocumentSyncUpdatesByEpoch({\n contentKeysByEpoch: input.contentKeysByEpoch,\n documentId: input.documentId,\n organizationId: input.organizationId,\n updates: input.updates,\n });\n // The current wire contract authenticates each update's operation range but\n // not its exact dependency set. An unresolved import therefore cannot prove\n // that the missing parent belongs to an unavailable sibling; preserve the\n // isolation failure instead of downgrading unrelated poison to availability.\n await input.validateIncomingUpdates({\n decryptedUpdates,\n response: { ...input.response, updates: [...input.updates] },\n });\n}\n\nasync function resolveVerifiedResponseState(\n input: SyncRemoteDocumentResultInput,\n) {\n const { plan } = input.materializedPlan;\n let persistedState: Awaited<\n ReturnType<typeof persistedDocumentSyncStateFromResponse>\n >;\n try {\n persistedState = await persistedDocumentSyncStateFromResponse(\n plan,\n input.response,\n {\n resolveWriterPublicKey: input.resolveWriterPublicKey,\n },\n );\n } catch (error) {\n // Missing or future bundles are response-integrity failures. They must be\n // poison-isolated before key availability is considered, because the\n // referenced update has not yet authenticated against a bundle.\n isolateContentKeyResponseFailure(error, input.response);\n }\n if ((plan.request.containerRekeys?.length ?? 0) > 0) {\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n allowStaleContentKeyBundle: true,\n execSql: input.execSql,\n stillCurrent: input.stillCurrent,\n ...projectionVerificationOptions(input),\n });\n }\n const contentKeysByEpoch = await unwrapDocumentSyncResponseContentKeys({\n currentContentKey: input.materializedPlan.contentKey,\n currentContentKeyEpoch: plan.contentKeyEpoch,\n execSql: input.execSql,\n historyMode: plan.request.historyMode,\n onRawHistoryUnavailable: async ({ contentKeysByEpoch, updates }) =>\n validateDecryptableRawHistorySiblings({\n contentKeysByEpoch,\n documentId: plan.documentId,\n organizationId: plan.organizationId,\n response: input.response,\n updates,\n validateIncomingUpdates: input.validateIncomingUpdates,\n }),\n response: input.response,\n targetSecretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n return { contentKeysByEpoch, persistedState };\n}\n\nexport async function syncRemoteDocumentResultFromResponse(\n input: SyncRemoteDocumentResultInput,\n): Promise<SyncRemoteDocumentResult> {\n const { plan } = input.materializedPlan;\n const { contentKeysByEpoch, persistedState } =\n await resolveVerifiedResponseState(input);\n const decryptedUpdates = await decryptDocumentSyncUpdatesByEpoch({\n contentKeysByEpoch,\n documentId: plan.documentId,\n organizationId: plan.organizationId,\n updates: input.response.updates,\n });\n await input.validateIncomingUpdates({\n decryptedUpdates,\n response: input.response,\n });\n const recoveryBaselineId =\n input.materializedPlan.staleRecoveryBaselineUpdateId;\n const acceptedRecoveryBaseline = responseAcceptedRecoveryBaseline(\n input.materializedPlan,\n input.response,\n );\n // Two heal-specific corrections: the synthetic heal baseline matches no\n // pending-queue row, so its ack must not count as a settled pending update;\n // and checkpoints the heal held back ARE settled by it — the committed\n // covering baseline subsumes their full-history content, and resubmitting\n // them post-heal could become the LATEST baseline at the healed epoch and\n // shrink the redirect's coverage below the pre-heal frontier.\n const settledPendingUpdateIds = [\n ...settledPendingUpdateIdsFromSync({\n decryptedUpdates,\n recoveryPendingUpdatesById: input.recoveryPendingUpdatesById,\n response: input.response,\n }).filter((updateId) => updateId !== recoveryBaselineId),\n ...acceptedHeldBackPendingUpdateIds(input.materializedPlan, input.response),\n ];\n const { exhaustedPendingUpdateCount, rekeyedPendingUpdateIds } =\n await rekeyAndReportUnsettledRecoveryPendingUpdates({\n execSql: input.execSql,\n onTerminalSubmitFailure: input.onTerminalSubmitFailure,\n recoveryPendingUpdatesById: input.recoveryPendingUpdatesById,\n rekeyPendingUpdate: input.rekeyPendingUpdate,\n settledPendingUpdateIds,\n stillCurrent: input.stillCurrent,\n });\n\n return {\n exhaustedPendingUpdateCount,\n contentKey: input.materializedPlan.contentKey,\n decryptedUpdates,\n hasDeferredPendingUpdates: false,\n hasIncompletePull: false,\n persistedState,\n plan,\n rekeyedPendingUpdateIds,\n response: input.response,\n settledPendingUpdateIds,\n acceptedRecoveryBaseline,\n writerProjection: input.writerProjection,\n };\n}\n"]}
@@ -1,9 +1,9 @@
1
- import { projectionVerificationOptions } from "../../data/documents/shared/types.js";
2
- import { verifyDocumentWriterProjectionAuthorization, } from "../../data/keyingProjectionVerification/index.js";
3
- import { isKeyingVerificationError } from "../../data/keyingProjectionVerification/error.js";
4
- import { DocumentRawHistoryUnavailableError } from "./syncContentKeys.js";
5
- import { refreshSyncAttemptWriterProjection } from "./syncFailures.js";
6
- import { hasDeferredPendingUpdatesAfterSubmit, responseAcceptedRecoveryBaseline, } from "./syncPlanRequestBounds.js";
1
+ import { projectionVerificationOptions } from "../../../data/documents/shared/types.js";
2
+ import { verifyDocumentWriterProjectionAuthorization, } from "../../../data/keyingProjectionVerification/index.js";
3
+ import { isKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
4
+ import { refreshSyncAttemptWriterProjection } from "../syncFailures/index.js";
5
+ import { DocumentRawHistoryUnavailableError } from "../syncPlan/syncContentKeys.js";
6
+ import { hasDeferredPendingUpdatesAfterSubmit, responseAcceptedRecoveryBaseline, } from "../syncPlan/syncPlanRequestBounds.js";
7
7
  import { syncRemoteDocumentResultFromResponse } from "./syncResponseResult.js";
8
8
  import { traceHealed } from "./syncTrace.js";
9
9
  /** @internal Applies post-verification heal effects under the sync generation. */
@@ -0,0 +1 @@
1
+ {"version":3,"file":"syncSubmittedResult.js","sourceRoot":"","sources":["syncSubmittedResult.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AACrF,OAAO,EAEL,2CAA2C,GAC5C,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,kDAAkD,CAAC;AAE7F,OAAO,EAAE,kCAAkC,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,kCAAkC,EAAE,MAAM,6BAA6B,CAAC;AACjF,OAAO,EACL,oCAAoC,EACpC,gCAAgC,GACjC,MAAM,mCAAmC,CAAC;AAE3C,OAAO,EAAE,oCAAoC,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAa1C,kFAAkF;AAClF,MAAM,UAAU,4BAA4B,CAAC,KAO5C;IACC,IACE,CAAC,KAAK,CAAC,gBAAgB,CAAC,2BAA2B;QACnD,CAAC,gCAAgC,CAAC,KAAK,CAAC,gBAAgB,EAAE,KAAK,CAAC,QAAQ,CAAC;QACzE,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,EAChC,CAAC;QACD,OAAO;IACT,CAAC;IACD,KAAK,CAAC,qBAAqB,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAChD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QACrC,O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KAAK,YAAY,kCAAkC,CAAC,CAAC,EACzD,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,yCAAyC,CAC9C,KAAK,EACL,KAAK,EACL,iBAAiB,CAClB,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type {\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type {\n MaterializedDocumentSyncPlan,\n SyncRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/types\";\nimport {\n type ProjectionUserKeyResolver,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../data/keyingProjectionVerification\";\nimport { isKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport type { PendingUpdateRecord } from \"../../../data/sqlite/documentPersistence\";\nimport { refreshSyncAttemptWriterProjection } from \"../syncFailures\";\nimport { DocumentRawHistoryUnavailableError } from \"../syncPlan/syncContentKeys\";\nimport {\n hasDeferredPendingUpdatesAfterSubmit,\n responseAcceptedRecoveryBaseline,\n} from \"../syncPlan/syncPlanRequestBounds\";\nimport type { SyncRemoteDocumentInput } from \"./readOnlySync\";\nimport { syncRemoteDocumentResultFromResponse } from \"./syncResponseResult\";\nimport { traceHealed } from \"./syncTrace\";\n\ntype SubmittedDocumentSyncResultInput = {\n materializedPlan: MaterializedDocumentSyncPlan;\n pendingUpdateIds: readonly string[];\n pullComplete: boolean;\n recoveryPendingUpdatesById: ReadonlyMap<string, PendingUpdateRecord>;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n response: DocumentSyncResponse;\n sync: SyncRemoteDocumentInput;\n writerProjection: DocumentWriterProjectionResponse;\n};\n\n/** @internal Applies post-verification heal effects under the sync generation. */\nexport function applyAcceptedHealSideEffects(input: {\n documentId: string;\n evictWriterProjection?: ((documentId: string) => void) | undefined;\n materializedPlan: MaterializedDocumentSyncPlan;\n onSyncTrace: SyncRemoteDocumentInput[\"onSyncTrace\"];\n response: DocumentSyncResponse;\n stillCurrent: SyncRemoteDocumentInput[\"stillCurrent\"];\n}): void {\n if (\n !input.materializedPlan.healedStaleContentKeyBundle ||\n !responseAcceptedRecoveryBaseline(input.materializedPlan, input.response) ||\n input.stillCurrent?.() === false\n ) {\n return;\n }\n input.evictWriterProjection?.(input.documentId);\n if (input.stillCurrent?.() === false) {\n return;\n }\n traceHealed(input.onSyncTrace, {\n accepted: input.response.acceptedOutgoingUpdateIds.length,\n documentId: input.materializedPlan.plan.documentId,\n epoch: input.materializedPlan.plan.contentKeyEpoch,\n });\n}\n\nasync function submittedDocumentSyncResult(\n input: SubmittedDocumentSyncResultInput,\n): Promise<SyncRemoteDocumentResult> {\n const result = await syncRemoteDocumentResultFromResponse({\n ...projectionVerificationOptions(input.sync),\n execSql: input.sync.execSql,\n materializedPlan: input.materializedPlan,\n onTerminalSubmitFailure: input.sync.onTerminalSubmitFailure,\n recoveryPendingUpdatesById: input.recoveryPendingUpdatesById,\n rekeyPendingUpdate: input.sync.rekeyPendingUpdate,\n resolveWriterPublicKey: input.sync.resolveWriterPublicKey,\n response: input.response,\n stillCurrent: input.sync.stillCurrent,\n targetSecretKey: input.sync.targetSecretKey,\n validateIncomingUpdates: input.sync.validateIncomingUpdates,\n writerProjection: input.writerProjection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n });\n if (\n (input.materializedPlan.plan.request.containerRekeys?.length ?? 0) > 0 &&\n input.sync.stillCurrent?.() !== false\n ) {\n input.sync.apiClient.clearWriterProjectionCaches?.();\n }\n applyAcceptedHealSideEffects({\n documentId: input.sync.documentId,\n evictWriterProjection:\n input.sync.apiClient.evictDocumentWriterProjection?.bind(\n input.sync.apiClient,\n ),\n materializedPlan: input.materializedPlan,\n onSyncTrace: input.sync.onSyncTrace,\n response: input.response,\n stillCurrent: input.sync.stillCurrent,\n });\n return {\n ...result,\n hasDeferredPendingUpdates:\n (input.materializedPlan.plan.request.pullCursor !== undefined &&\n input.pendingUpdateIds.length > 0 &&\n result.exhaustedPendingUpdateCount === 0) ||\n hasDeferredPendingUpdatesAfterSubmit({\n acceptedRecoveryBaseline: result.acceptedRecoveryBaseline,\n exhaustedPendingUpdateCount: result.exhaustedPendingUpdateCount,\n pendingUpdateIds: input.pendingUpdateIds,\n rekeyedPendingUpdateIds: result.rekeyedPendingUpdateIds,\n settledPendingUpdateIds: result.settledPendingUpdateIds,\n }),\n hasIncompletePull: !input.pullComplete,\n };\n}\n\nasync function retrySubmittedResponseWithFreshProjection(\n input: SubmittedDocumentSyncResultInput,\n unavailableError: unknown,\n refreshAuthorization: boolean,\n): Promise<SyncRemoteDocumentResult | null> {\n const writerProjection = await refreshSyncAttemptWriterProjection({\n apiClient: input.sync.apiClient,\n documentId: input.sync.documentId,\n onRemoteDocumentDeleted: input.sync.onRemoteDocumentDeleted,\n onSyncAbandoned: input.sync.onSyncAbandoned,\n onSyncTrace: input.sync.onSyncTrace,\n onTerminalFailure: input.sync.onReadOnlyProjectionFailure,\n stillCurrent: input.sync.stillCurrent,\n unavailableError,\n });\n if (!writerProjection) return null;\n const materializedPlan = refreshAuthorization\n ? {\n ...input.materializedPlan,\n plan: {\n ...input.materializedPlan.plan,\n documentWriterAuthorization:\n await verifyDocumentWriterProjectionAuthorization({\n execSql: input.sync.execSql,\n projection: writerProjection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.sync.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.sync.warmReferencedPrincipalPolicies,\n }),\n },\n }\n : input.materializedPlan;\n // Keep the submitted request, keys, and response frozen. Only refreshed,\n // verified evidence may be added; this retry never resubmits outgoing edits.\n return submittedDocumentSyncResult({\n ...input,\n materializedPlan,\n writerProjection,\n });\n}\n\nexport async function resolveSubmittedDocumentSyncResult(\n input: SubmittedDocumentSyncResultInput,\n): Promise<SyncRemoteDocumentResult | null> {\n try {\n return await submittedDocumentSyncResult(input);\n } catch (error) {\n const missingDependency =\n isKeyingVerificationError(error) && error.code === \"missing_dependency\";\n if (\n !missingDependency &&\n (input.sync.historyMode !== \"raw\" ||\n !(error instanceof DocumentRawHistoryUnavailableError))\n ) {\n throw error;\n }\n return retrySubmittedResponseWithFreshProjection(\n input,\n error,\n missingDependency,\n );\n }\n}\n"]}
@@ -10,7 +10,7 @@
10
10
  * emitter-side sanitization. The format tests assert emitter output and
11
11
  * pattern stay in lockstep, including that leaks fail closed.
12
12
  */
13
- import { DOCUMENT_NOT_FOUND_ERROR_CODE, DOCUMENT_PROJECTION_ERROR_CODES, DOCUMENT_SYNC_ERROR_CODES, } from "../../internal/validators/response/index.js";
13
+ import { DOCUMENT_NOT_FOUND_ERROR_CODE, DOCUMENT_PROJECTION_ERROR_CODES, DOCUMENT_SYNC_ERROR_CODES, } from "../../../internal/validators/response/index.js";
14
14
  /**
15
15
  * Enumerated, clipboard-safe reasons an ancestor repair abandons a pass. The
16
16
  * emitter maps to these rather than passing the error's prose through, so the
@@ -1,9 +1,9 @@
1
- import { DOCUMENT_SYNC_ERROR_CODES, } from "../../internal/validators/response/index.js";
2
- import { isUpstreamDeletedDocumentSyncFailure, submitDocumentSync, } from "../../data/documents/shared/responses.js";
3
- import { InvalidDocumentSyncPullContinuationError, } from "../../data/documents/shared/syncPagination.js";
1
+ import { DOCUMENT_SYNC_ERROR_CODES, } from "../../../internal/validators/response/index.js";
2
+ import { isUpstreamDeletedDocumentSyncFailure, submitDocumentSync, } from "../../../data/documents/shared/responses.js";
3
+ import { InvalidDocumentSyncPullContinuationError, } from "../../../data/documents/shared/syncPagination.js";
4
+ import { traceProjectionFailed, traceSubmitFailed, } from "../sync/syncTrace.js";
4
5
  import { canRecoverDocumentUpdateIdConflict, canRetryDocumentSyncConflict, handleUpstreamDeletedDocumentSyncFailure, isCheckpointCoverageConflict, shouldRetrySyncWithFreshWriterProjection, } from "./syncFailureClassification.js";
5
6
  import { recoverDocumentSyncPolicyRepair } from "./syncPolicyRepair.js";
6
- import { traceProjectionFailed, traceSubmitFailed, } from "./syncTrace.js";
7
7
  const REMOTE_DOCUMENT_DELETED = Symbol("remoteDocumentDeleted");
8
8
  export function assertRawContinuationCanRetry(historyMode, pullContinuation) {
9
9
  if (historyMode === "raw" && pullContinuation !== undefined) {
@@ -249,4 +249,4 @@ export async function retrySyncPlanOrAbandon(input) {
249
249
  }
250
250
  return planned;
251
251
  }
252
- //# sourceMappingURL=syncFailures.js.map
252
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,GAG1B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,oCAAoC,EACpC,kBAAkB,GACnB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAGL,wCAAwC,GACzC,MAAM,+CAA+C,CAAC;AASvD,OAAO,EAEL,qBAAqB,EACrB,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,kCAAkC,EAClC,4BAA4B,EAC5B,wCAAwC,EACxC,4BAA4B,EAE5B,wCAAwC,GAEzC,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AAErE,MAAM,uBAAuB,GAAG,MAAM,CAAC,uBAAuB,CAAC,CAAC;AAEhE,MAAM,UAAU,6BAA6B,CAC3C,WAA8B,EAC9B,gBAA0D;IAE1D,IAAI,WAAW,KAAK,KAAK,IAAI,gBAAgB,KAAK,SAAS,EAAE,CAAC;QAC5D,MAAM,IAAI,wCAAwC,CAChD,gDAAgD,CACjD,CAAC;IACJ,CAAC;AACH,CAAC;AA0BD,KAAK,UAAU,+BAA+B,CAAC,KAW9C;IACC,MAAM,MAAM,GAAG,MAAM,gCAAgC,CAAC,KAAK,CAAC,CAAC;IAC7D,iBAAiB,CAAC,KAAK,CAAC,WAAW,EAAE;QACnC,MAAM,EACJ,MAAM,KAAK,OAAO,IAAI,MAAM,KAAK,MAAM;YACrC,CAAC,CAAC,MAA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AM,gBAAgB,GAAG,MAAM,kCAAkC,CAAC;QAChE,GAAG,eAAe;QAClB,uBAAuB,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;YACzC,qBAAqB,GAAG,IAAI,CAAC;YAC7B,MAAM,uBAAuB,EAAE,CAAC,OAAO,CAAC,CAAC;QAC3C,CAAC;QACD,wBAAwB,EAAE,IAAI;KAC/B,CAAC,CAAC;IACH,IACE,CAAC,gBAAgB;QACjB,gBAAgB,KAAK,SAAS;QAC9B,CAAC,qBAAqB;QACtB,KAAK,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 type DocumentSyncTraceEmitter,\n traceProjectionFailed,\n traceSubmitFailed,\n} from \"../sync/syncTrace\";\nimport {\n canRecoverDocumentUpdateIdConflict,\n canRetryDocumentSyncConflict,\n handleUpstreamDeletedDocumentSyncFailure,\n isCheckpointCoverageConflict,\n type RemoteDocumentDeletionHandler,\n shouldRetrySyncWithFreshWriterProjection,\n type TerminalSubmitFailureHandler,\n} from \"./syncFailureClassification\";\nimport { recoverDocumentSyncPolicyRepair } from \"./syncPolicyRepair\";\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,5 +1,5 @@
1
+ import { traceAncestorRepairAbandoned } from "../sync/syncTrace.js";
1
2
  import { DocumentAncestorRepairAbandonedError } from "./syncRepairAbandon.js";
2
- import { traceAncestorRepairAbandoned } from "./syncTrace.js";
3
3
  export function abandonBlockedSync(input) {
4
4
  input.onSyncTrace?.(`document sync blocked document=${input.documentId}`);
5
5
  input.onSyncAbandoned?.("blocked");
@@ -0,0 +1 @@
1
+ {"version":3,"file":"syncAbandon.js","sourceRoot":"","sources":["syncAbandon.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EAAE,oCAAoC,EAAE,MAAM,qBAAqB,CAAC;AAQ3E,MAAM,UAAU,kBAAkB,CAAC,KAAyB;IAC1D,KAAK,CAAC,WAAW,EAAE,CAAC,kCAAkC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;IAC1E,KAAK,CAAC,e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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 \"../sync/readOnlySync\";\nimport { traceAncestorRepairAbandoned } from \"../sync/syncTrace\";\nimport { DocumentAncestorRepairAbandonedError } from \"./syncRepairAbandon\";\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,5 +1,5 @@
1
- import type { DocumentSyncSubmitFailure } from "../../data/documents/shared/types.js";
2
- import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
1
+ import type { DocumentSyncSubmitFailure } from "../../../data/documents/shared/types.js";
2
+ import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
3
3
  export type RemoteDocumentDeletionHandler = (input: {
4
4
  /** Present only after the SDK has verified the signed terminal purge proof. */
5
5
  readonly commitPurgeProof?: ((transactionExecSql: ExecSql) => Promise<void>) | undefined;
@@ -1,9 +1,9 @@
1
- import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
- import { DOCUMENT_MUTATION_ERROR_CODES, DOCUMENT_SYNC_ERROR_CODES, } from "../../internal/validators/response/index.js";
3
- import { ContainerKekRepairRequiredError } from "../../data/documents/shared/containerKekCurrency.js";
4
- import { isRetryableDocumentSyncConflict, isUpstreamDeletedDocumentSyncFailure, } from "../../data/documents/shared/responses.js";
5
- import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
6
- import { isKeyingVerificationError } from "../../data/keyingProjectionVerification/error.js";
1
+ import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
+ import { DOCUMENT_MUTATION_ERROR_CODES, DOCUMENT_SYNC_ERROR_CODES, } from "../../../internal/validators/response/index.js";
3
+ import { ContainerKekRepairRequiredError } from "../../../data/documents/shared/containerKekCurrency.js";
4
+ import { isRetryableDocumentSyncConflict, isUpstreamDeletedDocumentSyncFailure, } from "../../../data/documents/shared/responses.js";
5
+ import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
6
+ import { isKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
7
7
  /**
8
8
  * Read-only counterpart to describeDocumentSyncSubmitFailure: names a refused
9
9
  * revalidation without implying a blocked write. 403s never reach this — a
@@ -0,0 +1 @@
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,qDAAqD,CAAC;AACtG,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,GACrC,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,yBAAyB,EAAE,MAAM,kDAAkD,CAAC;AAqB7F;;;;;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,GAAG,CAAC;IACrE,OAAO,+BAA+B,MAAM,GAAG,MAAM,EAAE,CAAC;AAC1D,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,iCAAiC,CAC/C,OAA8D;IAE9D,IAAI,OAAO,CAAC,MAAM,KAAK,GAA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6B,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,6 +1,6 @@
1
- import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
- import { isRetryableDocumentSyncConflict } from "../../data/documents/shared/responses.js";
3
- import { recoverPrincipalPolicyRepair } from "../principals/policyRepair.js";
1
+ import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
+ import { isRetryableDocumentSyncConflict } from "../../../data/documents/shared/responses.js";
3
+ import { recoverPrincipalPolicyRepair } from "../../principals/policyRepair.js";
4
4
  function principalIdentityKey(principalType, principalId) {
5
5
  return `${principalType}:${principalId}`;
6
6
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"syncPolicyRepair.js","sourceRoot":"","sources":["syncPolicyRepair.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,+BAA+B,EAAE,MAAM,0CAA0C,CAAC;AAO3F,OAAO,EAAE,4BAA4B,EAAE,MAAM,+BAA+B,CAAC;AAI7E,SAAS,oBAAoB,CAC3B,aAAmC,EACnC,WAAmB;IAEnB,OAAO,GAAG,aAAa,IAAI,WAAW,EAAE,CAAC;AAC3C,CAAC;AAED,SAAS,kCAAkC,CACzC,IAAsB;IAEtB,MAAM,UAAU,GAAG,IAAI,GAAG,EAAU,CAAC;IACrC,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,OAAO,CAAC,eAAe,IAAI,EAAE,EAAE,CAAC;QACvD,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,iBAAiB,EAAE,CAAC;YAC7C,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;YAC3D,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;YACvD,IACE,CAAC,aAAa,KAAK,OAAO,IAAI,aAAa,KAAK,cAAc,CAAC;gBAC/D,OAAO,WAAW,KAAK,QAAQ;gBAC/B,WAAW,CAAC,MAAM,GAAG,CAAC,EACtB,CAAC;gBACD,UAAU,CAAC,GAAG,CAAC,oBAAoB,CAAC,aAAa,EAAE,WAAW,CAAC,CAAC,CAAC;YACnE,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,SAAS,4CAA4C,CAAC,KAGrD;IACC,MAAM,SAAS,GAAG,kCAAkC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACjE,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;QAC/B,MAAM,EAAE,WAAW,EAAE,aAAa,EAAE,GAAG,IAAI,CAAC;QAC5C,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,oBAAoB,CAAC,aAAa,EAAE,WAAW,CAAC,CAAC,EAAE,CAAC;YACrE,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAKrD;IACC,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,mBAAmB,CAAC;IAChD,MAAM,OAAO,GAAG,KAAK,CAAC,+BAA+B,EAAE,gBAAgB,CAAC;IACxE,IACE,CAAC,+BAA+B,CAAC,KAAK,CAAC,OAAO,CAAC;QAC/C,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe,EAAE,MAAM,IAAI,CAAC,CAAC,KAAK,CAAC;QACvD,CAAC,KAAK;QACN,KAAK,CAAC,MAAM,KAAK,CAAC;QAClB,CAAC,OAAO;QACR,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,EAChC,CAAC;QACD,OAAO;IACT,CAAC;IAED,4CAA4C,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;IAC1E,MAAM,4BAA4B,CAAC;QACjC,KAAK;QACL,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;QACtE,cAAc,EAAE,KAAK,CAAC,IAAI,CAAC,cAAc;QACzC,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { ReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport { isRetryableDocumentSyncConflict } from \"../../../data/documents/shared/responses\";\nimport type {\n DocumentSyncPlan,\n DocumentSyncSubmitFailure,\n} from \"../../../data/documents/shared/types\";\nimport type { ReferencedPrincipalPolicyWarmer } from \"../../../data/keyingProjectionVerification\";\n\nimport { recoverPrincipalPolicyRepair } from \"../../principals/policyRepair\";\n\ntype ManagedPrincipalType = \"group\" | \"organization\";\n\nfunction principalIdentityKey(\n principalType: ManagedPrincipalType,\n principalId: string,\n): string {\n return `${principalType}:${principalId}`;\n}\n\nfunction requestedRepairPrincipalIdentities(\n plan: DocumentSyncPlan,\n): Set<string> {\n const identities = new Set<string>();\n for (const rekey of plan.request.containerRekeys ?? []) {\n for (const policy of rekey.principalPolicies) {\n const principalType = Reflect.get(policy, \"principalType\");\n const principalId = Reflect.get(policy, \"principalId\");\n if (\n (principalType === \"group\" || principalType === \"organization\") &&\n typeof principalId === \"string\" &&\n principalId.length > 0\n ) {\n identities.add(principalIdentityKey(principalType, principalId));\n }\n }\n }\n return identities;\n}\n\nfunction assertDocumentSyncPolicyRepairHeadsRequested(input: {\n readonly heads: readonly ReferencedPrincipalStateResponse[];\n readonly plan: DocumentSyncPlan;\n}): void {\n const requested = requestedRepairPrincipalIdentities(input.plan);\n for (const head of input.heads) {\n const { principalId, principalType } = head;\n if (!requested.has(principalIdentityKey(principalType, principalId))) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document sync policy repair head principal was not requested\",\n );\n }\n }\n}\n\nexport async function recoverDocumentSyncPolicyRepair(input: {\n failure: DocumentSyncSubmitFailure;\n plan: DocumentSyncPlan;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<void> {\n const heads = input.failure.stalePrincipalHeads;\n const resolve = input.warmReferencedPrincipalPolicies?.resolveReference;\n if (\n !isRetryableDocumentSyncConflict(input.failure) ||\n (input.plan.request.containerRekeys?.length ?? 0) === 0 ||\n !heads ||\n heads.length === 0 ||\n !resolve ||\n input.stillCurrent?.() === false\n ) {\n return;\n }\n\n assertDocumentSyncPolicyRepairHeadsRequested({ heads, plan: input.plan });\n await recoverPrincipalPolicyRepair({\n heads,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n organizationId: input.plan.organizationId,\n stillCurrent: input.stillCurrent,\n });\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"syncRepairAbandon.js","sourceRoot":"","sources":["syncRepairAbandon.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;GAUG;AACH,MAAM,OAAO,oCAAqC,SAAQ,KAAK;IACxC;IAArB,YAAqB,MAAmC;QACtD,KAAK,CAAC,uCAAuC,MAAM,EAAE,CAAC,CAAC;QADpC,WAAM,GAAN,MAAM,CAA6B;QAEtD,IAAI,CAAC,IAAI,GAAG,sCAAsC,CAAC;IACrD,CAAC;CACF;AAED,iFAAiF;AACjF,MAAM,OAAO,oCAAqC,SAAQ,KAAK;IAC7D;QACE,KAAK,CAAC,wDAAwD,CAAC,CAAC;QAChE,IAAI,CAAC,IAAI,GAAG,sCAAsC,CAAC;IACrD,CAAC;CACF","sourcesContent":["import type { AncestorRepairAbandonReason } from \"../sync/syncTrace\";\n\n/**\n * A repair that cannot proceed for a routine reason: the organization's writes\n * are gated, the server refused the rekey, a peer rotated an ancestor mid-pass,\n * the refreshed projection was unavailable, or the pass exhausted its repair\n * budget. None is a defect, so the sync lane abandons the attempt rather than\n * reporting a failed run; the next trigger re-plans from a fresh projection.\n *\n * Lives apart from both the planner and the preparation loop: each throws it,\n * and preparation already imports the planner, so declaring it in either would\n * close a dependency cycle.\n */\nexport class DocumentAncestorRepairAbandonedError extends Error {\n constructor(readonly reason: AncestorRepairAbandonReason) {\n super(`Document ancestor repair abandoned: ${reason}`);\n this.name = \"DocumentAncestorRepairAbandonedError\";\n }\n}\n\n/** A refreshed projection needs durable preparation before another pure plan. */\nexport class DocumentSyncPreparationRequiredError extends Error {\n constructor() {\n super(\"Document sync requires a new ancestor preparation step\");\n this.name = \"DocumentSyncPreparationRequiredError\";\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { resolveContainerPathUserAccessLevel } from "../../internal/crypto/index.js";
2
- import { requireProjectionUserKeyResolver, verifyDocumentWriterProjectionAuthorization, } from "../../data/keyingProjectionVerification/index.js";
1
+ import { resolveContainerPathUserAccessLevel } from "../../../internal/crypto/index.js";
2
+ import { requireProjectionUserKeyResolver, verifyDocumentWriterProjectionAuthorization, } from "../../../data/keyingProjectionVerification/index.js";
3
3
  /** A repair refusal on one link does not revoke write access through another. */
4
4
  export async function hasOtherLinkedWriteAccess(sync, projection, inaccessibleContainerId) {
5
5
  if (projection.authorizingContainerPaths.length < 2)
@@ -0,0 +1 @@
1
+ {"version":3,"file":"syncRepairAccess.js","sourceRoot":"","sources":["syncRepairAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AAExE,OAAO,EACL,gCAAgC,EAChC,2CAA2C,GAC5C,MAAM,4CAA4C,CAAC;AAGpD,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,IAA6B,EAC7B,UAA4C,EAC5C,uBAA+B;IAE/B,IAAI,UAAU,CAAC,yBAAyB,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,KAAK,CAAC;IAClE,MAAM,QAAQ,GAAG,MAAM,2CAA2C,CAAC;QACjE,OAAO,EAAE,IAAI,CAAC,OAAO;QACrB,8BAA8B,EAAE,KAAK;QACrC,UAAU;QACV,cAAc,EAAE,gCAAgC,CAC9C,IAAI,CAAC,wBAAwB,EAC7B,+BAA+B,CAChC;QACD,YAAY,EAAE,IAAI,CAAC,YAAY;QAC/B,+BAA+B,EAAE,IAAI,CAAC,+BAA+B;KACtE,CAAC,CAAC;IACH,MAAM,QAAQ,GAAG,QAAQ,CAAC,sBAAsB,CAAC,GAAG,CAClD,UAAU,CAAC,gBAAgB,CAAC,YAAY,CACzC,CAAC;IACF,IACE,CAAC,QAAQ;QACT,QAAQ,CAAC,KAAK,CAAC,UAAU,KAAK,IAAI,CAAC,UAAU;QAC7C,QAAQ,CAAC,KAAK,CAAC,cAAc,KAAK,IAAI,CAAC,MAAM,CAAC,cAAc;QAE5D,OAAO,KAAK,CAAC;IACf,0EAA0E;IAC1E,kEAAkE;IAClE,OAAO,UAAU,CAAC,yBAAyB,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE;QAC7D,MAAM,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,YAAY,CAAC;QACrD,MAAM,IAAI,GAAG,QAAQ;YACnB,CAAC,CAAC,QAAQ,CAAC,2BAA2B,CAAC,GAAG,CAAC,QAAQ,CAAC;YACpD,CAAC,CAAC,SAAS,CAAC;QACd,MAAM,IAAI,GAAG,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC1B,IACE,CAAC,IAAI;YACL,CAAC,IAAI;YACL,IAAI,CAAC,KAAK,CAAC,WAAW,KAAK,uBAAuB;YAClD,IAAI,CAAC,KAAK,CAAC,cAAc,KAAK,QAAQ,CAAC,KAAK,CAAC,cAAc;YAC3D,CAAC,QAAQ,CAAC,KAAK,CAAC,kBAAkB,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC;YAEnE,OAAO,KAAK,CAAC;QACf,MAAM,MAAM,GAAG,mCAAmC,CAAC;YACjD,IAAI;YACJ,iBAAiB,EAAE,QAAQ,CAAC,iBAAiB;YAC7C,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,YAAY;SACjC,CAAC,CAAC;QACH,OAAO,MAAM,KAAK,OAAO,IAAI,MAAM,KAAK,OAAO,CAAC;IAClD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { resolveContainerPathUserAccessLevel } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n requireProjectionUserKeyResolver,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { SyncRemoteDocumentInput } from \"../sync/readOnlySync\";\n\n/** A repair refusal on one link does not revoke write access through another. */\nexport async function hasOtherLinkedWriteAccess(\n sync: SyncRemoteDocumentInput,\n projection: DocumentWriterProjectionResponse,\n inaccessibleContainerId: string,\n): Promise<boolean> {\n if (projection.authorizingContainerPaths.length < 2) return false;\n const verified = await verifyDocumentWriterProjectionAuthorization({\n execSql: sync.execSql,\n persistVerificationCheckpoints: false,\n projection,\n resolveUserKey: requireProjectionUserKeyResolver(\n sync.resolveProjectionUserKey,\n \"Document linked repair access\",\n ),\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n });\n const document = verified.documentManifestByHash.get(\n projection.documentManifest.manifestHash,\n );\n if (\n !document ||\n document.state.documentId !== sync.documentId ||\n document.state.organizationId !== sync.author.organizationId\n )\n return false;\n // The map also contains historical paths. Only the verified current paths\n // named by this projection may establish present write authority.\n return projection.authorizingContainerPaths.some((candidate) => {\n const headHash = candidate.path.at(-1)?.manifestHash;\n const path = headHash\n ? verified.containerPathByManifestHash.get(headHash)\n : undefined;\n const leaf = path?.at(-1);\n if (\n !path ||\n !leaf ||\n leaf.state.containerId === inaccessibleContainerId ||\n leaf.state.organizationId !== document.state.organizationId ||\n !document.state.linkedContainerIds.includes(leaf.state.containerId)\n )\n return false;\n const access = resolveContainerPathUserAccessLevel({\n path,\n principalPolicies: verified.principalPolicies,\n userId: sync.author.signerUserId,\n });\n return access === \"write\" || access === \"admin\";\n });\n}\n"]}
@@ -1,7 +1,7 @@
1
- import type { DocumentSyncResponse, DocumentWriterProjectionResponse } from "../../internal/validators/response/index.js";
2
- import type { DocumentSyncPreparedUpdate, ProjectionVerificationOptions } from "../../data/documents/shared/types.js";
3
- import type { PendingUpdateRecord } from "../../data/sqlite/documentPersistence.js";
4
- import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
1
+ import type { DocumentSyncResponse, DocumentWriterProjectionResponse } from "../../../internal/validators/response/index.js";
2
+ import type { DocumentSyncPreparedUpdate, ProjectionVerificationOptions } from "../../../data/documents/shared/types.js";
3
+ import type { PendingUpdateRecord } from "../../../data/sqlite/documentPersistence.js";
4
+ import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
5
5
  type SyncResponseUpdate = DocumentSyncResponse["updates"][number];
6
6
  type RawHistoryUnavailableValidator = (input: {
7
7
  contentKeysByEpoch: ReadonlyMap<number, Uint8Array>;
@@ -1,11 +1,11 @@
1
- import { importContentKeyMaterial } from "../../data/documents/shared/contentRecordKeys.js";
2
- import { encryptDocumentPendingUpdate } from "../../data/documents/shared/crypto.js";
3
- import { assertDocumentSyncUpdateEncryptedRecord } from "../../data/documents/shared/documentSyncUpdateDecryption.js";
4
- import { isDocumentSyncUpdateIsolationError, isolateDocumentSyncBatchError, isolateDocumentSyncUpdateError, } from "../../data/documents/shared/documentSyncUpdateIsolation.js";
5
- import { ContainerKekHistoryUnavailableError, collectContainerKeksForDocumentSync, DocumentContentKeyUnavailableError, DocumentHistoryUnavailableError, unwrapDocumentContentKeyFromBundle, } from "../../data/documents/shared/projection.js";
6
- import { readWriteHeader } from "../../data/documents/shared/readers.js";
7
- import { projectionVerificationOptions } from "../../data/documents/shared/types.js";
8
- import { isKeyingVerificationError } from "../../data/keyingProjectionVerification/error.js";
1
+ import { importContentKeyMaterial } from "../../../data/documents/shared/contentRecordKeys.js";
2
+ import { encryptDocumentPendingUpdate } from "../../../data/documents/shared/crypto.js";
3
+ import { assertDocumentSyncUpdateEncryptedRecord } from "../../../data/documents/shared/documentSyncUpdateDecryption.js";
4
+ import { isDocumentSyncUpdateIsolationError, isolateDocumentSyncBatchError, isolateDocumentSyncUpdateError, } from "../../../data/documents/shared/documentSyncUpdateIsolation.js";
5
+ import { ContainerKekHistoryUnavailableError, collectContainerKeksForDocumentSync, DocumentContentKeyUnavailableError, DocumentHistoryUnavailableError, unwrapDocumentContentKeyFromBundle, } from "../../../data/documents/shared/projection.js";
6
+ import { readWriteHeader } from "../../../data/documents/shared/readers.js";
7
+ import { projectionVerificationOptions } from "../../../data/documents/shared/types.js";
8
+ import { isKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
9
9
  function isRawHistoryUnavailableCause(error) {
10
10
  return (error instanceof DocumentContentKeyUnavailableError ||
11
11
  (error instanceof DocumentHistoryUnavailableError &&
@@ -0,0 +1 @@
1
+ {"version":3,"file":"syncContentKeys.js","sourceRoot":"","sources":["syncContentKeys.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAC5F,OAAO,EAAE,4BAA4B,EAAE,MAAM,uCAAuC,CAAC;AACrF,OAAO,EAAE,uCAAuC,EAAE,MAAM,6DAA6D,CAAC;AACtH,OAAO,EACL,kCAAkC,EAClC,6BAA6B,EAC7B,8BAA8B,GAC/B,MAAM,4DAA4D,CAAC;AACpE,OAAO,EACL,mCAAmC,EACnC,mCAAmC,EACnC,kCAAkC,EAClC,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AAKzE,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AACrF,OAAO,EAAE,yBAAyB,EAAE,MAAM,kDAAkD,CAAC;AAS7F,SAAS,4BAA4B,CACnC,KAAc;IAEd,OAAO,CACL,KAAK,YAAY,kCAAkC;QACnD,CAAC,KAAK,YAAY,+BAA+B;YAC/C,KAAK,CAAC,YAAY,YAAY,mCAAmC,CAAC,CACrE,CAAC;AACJ,CAAC;AAOD,6EAA6E;AAC7E,MAAM,OAAO,kCAAmC,SAAQ,KAAK;IAIhD;IAHF,IAAI,GAAG,wCAAwC,CAAC;IAEzD,YACW,eAAuB,EAChC,KAAc;QAEd,KAAK,CACH,kEAAkE,eAAe,EAAE,EACnF,EAAE,KAAK,EAAE,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qB,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,6 +1,6 @@
1
- import { CONTENT_RECORD_ENCRYPTION_SUITE, computeContentRecordNonceDomainHash, computeDocumentContentKeyTargetHash, signWriteHeader, } from "../../internal/crypto/index.js";
2
- import { assertDocumentManifestBundleConsistent, normalizeDocumentKekTargetResponse, serializeCanonical, sortDocumentTargets, targetEnvelopeReference, } from "../../data/documents/shared/readers.js";
3
- import { readCanonicalRecord } from "../../data/keying/canonicalJson.js";
1
+ import { CONTENT_RECORD_ENCRYPTION_SUITE, computeContentRecordNonceDomainHash, computeDocumentContentKeyTargetHash, signWriteHeader, } from "../../../internal/crypto/index.js";
2
+ import { assertDocumentManifestBundleConsistent, normalizeDocumentKekTargetResponse, serializeCanonical, sortDocumentTargets, targetEnvelopeReference, } from "../../../data/documents/shared/readers.js";
3
+ import { readCanonicalRecord } from "../../../data/keying/canonicalJson.js";
4
4
  function contentKeyBundleForSyncRequest(input) {
5
5
  const { documentId: _omit, ...bundle } = input;
6
6
  return bundle;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"syncPlanIdentity.js","sourceRoot":"","sources":["syncPlanIdentity.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,mCAAmC,EACnC,mCAAmC,EACnC,eAAe,GAEhB,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EACL,sCAAsC,EACtC,kCAAkC,EAClC,kBAAkB,EAClB,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,wCAAwC,CAAC;AAOhD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAEzE,SAAS,8BAA8B,CACrC,KAAiD;I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eDocumentContentKeyTargetHash,\n signWriteHeader,\n type UnsignedWriteHeader,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerManifestRef,\n DocumentOutgoingUpdate,\n DocumentSyncRequest,\n} from \"@tearleads/validators/request\";\nimport type { DocumentCreateResponse } from \"@tearleads/validators/response\";\nimport {\n assertDocumentManifestBundleConsistent,\n normalizeDocumentKekTargetResponse,\n serializeCanonical,\n sortDocumentTargets,\n targetEnvelopeReference,\n} from \"../../../data/documents/shared/readers\";\nimport type {\n BuildDocumentSyncPlanInput,\n DocumentCreateAuthor,\n DocumentSyncPlan,\n DocumentSyncPreparedUpdate,\n} from \"../../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\n\nfunction contentKeyBundleForSyncRequest(\n input: DocumentCreateResponse[\"contentKeyBundle\"],\n): NonNullable<DocumentSyncRequest[\"contentKeyBundle\"]> {\n const { documentId: _omit, ...bundle } = input;\n return bundle;\n}\n\nasync function resolveDocumentSyncIdentity(\n input: BuildDocumentSyncPlanInput,\n): Promise<{\n documentId: string;\n expectedLinkSetManifestHash: string;\n expectedTargetHash: string;\n organizationId: string;\n}> {\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: input.documentManifest,\n label: \"Document sync manifest\",\n });\n const documentId = input.documentId ?? input.contentKeyBundle.documentId;\n if (documentId.length === 0) {\n throw new Error(\"Document sync document id is empty\");\n }\n if (\n input.contentKeyBundle.documentId !== documentId ||\n input.documentKekTargets.documentId !== documentId ||\n manifestIdentity.documentId !== documentId\n ) {\n throw new Error(\"Document sync state document id mismatch\");\n }\n if (manifestIdentity.organizationId !== input.author.organizationId) {\n throw new Error(\"Document sync author organization mismatch\");\n }\n if (\n input.documentManifest.manifestHash !==\n input.contentKeyBundle.linkSetManifestHash ||\n input.documentKekTargets.linkSetManifestHash !==\n input.contentKeyBundle.linkSetManifestHash\n ) {\n throw new Error(\"Document sync link manifest mismatch\");\n }\n if (\n input.documentKekTargets.documentKeyTargetHash !==\n input.contentKeyBundle.targetHash\n ) {\n throw new Error(\"Document sync target hash mismatch\");\n }\n\n const kekTargets = normalizeDocumentKekTargetResponse(\n input.documentKekTargets,\n );\n const contentKeyTargets = sortDocumentTargets(\n input.contentKeyBundle.targets.map(targetEnvelopeReference),\n );\n if (\n serializeCanonical(kekTargets, \"KEK targets\") !==\n serializeCanonical(contentKeyTargets, \"content-key targets\")\n ) {\n throw new Error(\"Document sync content-key targets mismatch\");\n }\n\n const targetHash = await computeDocumentContentKeyTargetHash(kekTargets);\n if (targetHash !== input.contentKeyBundle.targetHash) {\n throw new Error(\"Document sync target hash is not canonical\");\n }\n\n return {\n documentId,\n expectedLinkSetManifestHash: input.contentKeyBundle.linkSetManifestHash,\n expectedTargetHash: input.contentKeyBundle.targetHash,\n organizationId: manifestIdentity.organizationId,\n };\n}\n\nfunction normalizeAuthorizingContainerPathRefs(\n refs: readonly (readonly ContainerManifestRef[])[] | undefined,\n): ContainerManifestRef[][] {\n if (!refs || refs.length === 0) {\n throw new Error(\"Document sync write authorization path refs are missing\");\n }\n\n return refs.map((path, pathIndex) => {\n if (path.length === 0) {\n throw new Error(\n `Document sync write authorization path[${pathIndex}] is empty`,\n );\n }\n return [...path];\n });\n}\n\nexport async function signDocumentOutgoingUpdate(input: {\n authorizingContainerPathRefs: readonly (readonly ContainerManifestRef[])[];\n author: DocumentCreateAuthor;\n contentKeyEpoch: number;\n documentId: string;\n expectedLinkSetManifestHash: string;\n expectedTargetHash: string;\n organizationId: string;\n signedAt: string;\n update: DocumentSyncPreparedUpdate;\n}): Promise<DocumentOutgoingUpdate> {\n const contentRecordId = input.update.contentRecordId ?? input.update.id;\n const nonceDomain = {\n version: 1,\n organizationId: input.organizationId,\n objectKind: \"document\",\n objectId: input.documentId,\n contentKeyEpoch: input.contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId,\n } as const;\n const unsignedHeader: UnsignedWriteHeader = {\n ...nonceDomain,\n dependencyManifestHashes: [\n ...new Set(\n input.authorizingContainerPathRefs.flatMap((path) =>\n path.map((ref) => ref.manifestHash),\n ),\n ),\n ].sort(),\n accessManifestHash: input.expectedLinkSetManifestHash,\n targetHash: input.expectedTargetHash,\n nonceDomainHash: await computeContentRecordNonceDomainHash(nonceDomain),\n metadataHash: input.update.metadataHash,\n ciphertextHash: input.update.ciphertextHash,\n writerUserId: input.author.signerUserId,\n writerDeviceId: input.author.signerDeviceId,\n writerKeyFingerprint: input.author.signerKeyFingerprint,\n signedAt: input.update.signedAt ?? input.signedAt,\n };\n const writeHeader = await signWriteHeader(\n unsignedHeader,\n input.author.signerPrivateKey,\n );\n\n return {\n ...(input.update.checkpointKind === undefined\n ? {}\n : { checkpointKind: input.update.checkpointKind }),\n ...(input.update.checkpointPayloadKind === undefined\n ? {}\n : { checkpointPayloadKind: input.update.checkpointPayloadKind }),\n id: input.update.id,\n encryptedData: input.update.encryptedData,\n partialStartVersionVector: input.update.partialStartVersionVector,\n partialEndVersionVector: input.update.partialEndVersionVector,\n plaintextHash: input.update.plaintextHash,\n ...(input.update.sourceVersionVector === undefined\n ? {}\n : { sourceVersionVector: input.update.sourceVersionVector }),\n writeHeader: readCanonicalRecord(\n writeHeader,\n \"Document outgoing write header\",\n ),\n };\n}\n\nfunction assertUniqueDocumentOutgoingUpdates(\n updates: readonly DocumentSyncPreparedUpdate[],\n): void {\n const updateIds = new Set<string>();\n const contentRecordIds = new Set<string>();\n for (const update of updates) {\n if (updateIds.has(update.id)) {\n throw new Error(\"Document sync update id is duplicated\");\n }\n updateIds.add(update.id);\n\n const contentRecordId = (update.contentRecordId ?? update.id).toLowerCase();\n if (contentRecordIds.has(contentRecordId)) {\n throw new Error(\"Document sync content record id is duplicated\");\n }\n contentRecordIds.add(contentRecordId);\n }\n}\n\nfunction assertDocumentSyncRequestMode(\n input: BuildDocumentSyncPlanInput,\n hasContainerRekeys: boolean,\n hasOutgoingUpdates: boolean,\n): void {\n if (input.historyMode === \"raw\" && input.localVersionVector !== null) {\n throw new Error(\n \"Document raw-history sync must start from a null version vector\",\n );\n }\n const hasWrites = hasOutgoingUpdates || hasContainerRekeys;\n if (input.historyMode === \"raw\" && hasWrites) {\n throw new Error(\"Document raw-history sync must be read-only\");\n }\n if (input.pullCursor !== undefined && hasWrites) {\n throw new Error(\"Document sync continuation must be read-only\");\n }\n if (hasContainerRekeys && !hasOutgoingUpdates) {\n throw new Error(\n \"Document sync container rekeys require an outgoing update\",\n );\n }\n if (hasContainerRekeys !== (input.inlineRekeyCommitId !== undefined)) {\n throw new Error(\n \"Document sync inline rekey commit id must accompany container rekeys\",\n );\n }\n}\n\nexport async function buildDocumentSyncPlan(\n input: BuildDocumentSyncPlanInput,\n): Promise<DocumentSyncPlan> {\n const {\n documentId,\n expectedLinkSetManifestHash,\n expectedTargetHash,\n organizationId,\n } = await resolveDocumentSyncIdentity(input);\n const containerRekeys = [...(input.containerRekeys ?? [])];\n const outgoingUpdateInputs = [...(input.outgoingUpdates ?? [])];\n assertDocumentSyncRequestMode(\n input,\n containerRekeys.length > 0,\n outgoingUpdateInputs.length > 0,\n );\n const signedAt = input.signedAt ?? new Date().toISOString();\n assertUniqueDocumentOutgoingUpdates(outgoingUpdateInputs);\n\n const outgoingUpdates = await Promise.all(\n outgoingUpdateInputs.map((update) =>\n signDocumentOutgoingUpdate({\n authorizingContainerPathRefs: normalizeAuthorizingContainerPathRefs(\n input.authorizingContainerPathRefs,\n ),\n author: input.author,\n contentKeyEpoch: input.contentKeyBundle.contentKeyEpoch,\n documentId,\n expectedLinkSetManifestHash,\n expectedTargetHash,\n organizationId,\n signedAt,\n update,\n }),\n ),\n );\n // Writes always carry the verified current content-key bundle so the server\n // can validate and materialize the current wrapping material in the same\n // request. Read-only syncs omit it because they do not update server state.\n const shouldIncludeContentKeyBundle = outgoingUpdates.length > 0;\n const request: DocumentSyncRequest = {\n ...(shouldIncludeContentKeyBundle\n ? {\n contentKeyBundle: contentKeyBundleForSyncRequest(\n input.contentKeyBundle,\n ),\n }\n : {}),\n ...(containerRekeys.length === 0 ? {} : { containerRekeys }),\n contentKeyEpoch: input.contentKeyBundle.contentKeyEpoch,\n ...(outgoingUpdates.length === 0\n ? {}\n : {\n authorizingContainerPathRefs: normalizeAuthorizingContainerPathRefs(\n input.authorizingContainerPathRefs,\n ),\n }),\n expectedLinkSetManifestHash,\n expectedTargetHash,\n ...(input.historyMode === undefined\n ? {}\n : { historyMode: input.historyMode }),\n ...(input.inlineRekeyCommitId === undefined\n ? {}\n : { inlineRekeyCommitId: input.inlineRekeyCommitId }),\n localVersionVector: input.localVersionVector,\n ...(input.minLsn === undefined ? {} : { minLsn: input.minLsn }),\n outgoingUpdates,\n ...(input.pullCursor === undefined ? {} : { pullCursor: input.pullCursor }),\n supportsPullPagination: true,\n };\n\n return {\n contentKeyEpoch: input.contentKeyBundle.contentKeyEpoch,\n documentId,\n documentKekTargets: input.documentKekTargets,\n documentManifest: input.documentManifest,\n expectedLinkSetManifestHash,\n expectedTargetHash,\n minLsn: input.minLsn,\n organizationId,\n request,\n sourceContentKeyBundle: input.contentKeyBundle,\n };\n}\n"]}