@tearleads/client-sdk 0.1.63 → 0.1.65

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 (1432) hide show
  1. package/client/organizations/organizationAccessRestoration.js +1 -1
  2. package/data/containers/shared/mutationAcknowledgement.js +1 -1
  3. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  4. package/data/documents/blob/shared/projection.js +4 -4
  5. package/data/documents/blob/shared/projection.js.map +1 -1
  6. package/data/documents/shared/containerKek/containerKekCurrency.d.ts +22 -0
  7. package/data/documents/shared/containerKek/containerKekEntryVerification.js +15 -0
  8. package/data/documents/shared/containerKek/containerKekLogFetch.d.ts +18 -0
  9. package/data/documents/shared/containerKek/containerKekLogFetch.js +76 -0
  10. package/data/documents/shared/containerKek/containerKekPath.js +265 -0
  11. package/data/documents/shared/containerKek/containerKekPath.js.map +1 -0
  12. package/data/documents/shared/containerKek/containerKekPathHistory.d.ts +61 -0
  13. package/data/documents/shared/containerKek/containerKekPathHistory.js +223 -0
  14. package/data/documents/shared/containerKek/containerKekPathHistory.js.map +1 -0
  15. package/data/documents/shared/containerKek/containerKekPathVerification.d.ts +15 -0
  16. package/data/documents/shared/containerKek/containerKekPathVerification.js +23 -0
  17. package/data/documents/shared/containerKek/containerKekPathVerification.js.map +1 -0
  18. package/data/documents/shared/containerKek/containerKekWrapping.js +61 -0
  19. package/data/documents/shared/containerKek/containerKekWrapping.js.map +1 -0
  20. package/data/documents/shared/containerKek/keyringLogWalk.d.ts +45 -0
  21. package/data/documents/shared/containerKek/keyringLogWalk.js +204 -0
  22. package/data/documents/shared/containerKek/keyringRebuild.d.ts +60 -0
  23. package/data/documents/shared/containerKek/keyringRebuild.js +242 -0
  24. package/data/documents/shared/containerKek/keyringRebuild.js.map +1 -0
  25. package/data/documents/shared/crypto.js +2 -2
  26. package/data/documents/shared/crypto.js.map +1 -1
  27. package/data/documents/shared/events.js +1 -1
  28. package/data/documents/shared/projection/index.d.ts +25 -0
  29. package/data/documents/shared/projection/index.js +132 -0
  30. package/data/documents/shared/projection/index.js.map +1 -0
  31. package/data/documents/shared/projection/projectionContentKeys.d.ts +90 -0
  32. package/data/documents/shared/projection/projectionContentKeys.js +262 -0
  33. package/data/documents/shared/projection/projectionContentKeys.js.map +1 -0
  34. package/data/documents/shared/projection/projectionTargets.d.ts +38 -0
  35. package/data/documents/shared/projection/projectionTargets.js +164 -0
  36. package/data/documents/shared/projection/projectionTargets.js.map +1 -0
  37. package/data/documents/shared/responses.d.ts +1 -1
  38. package/data/documents/shared/responses.js +1 -1
  39. package/data/documents/shared/responses.js.map +1 -1
  40. package/data/documents/shared/sync/documentSyncUpdateDecryption.js +238 -0
  41. package/data/documents/shared/sync/documentSyncUpdateDecryption.js.map +1 -0
  42. package/data/documents/shared/sync/documentSyncUpdateIsolation.d.ts +55 -0
  43. package/data/documents/shared/sync/documentSyncUpdateIsolation.js +298 -0
  44. package/data/documents/shared/sync/documentSyncUpdateIsolation.js.map +1 -0
  45. package/data/documents/shared/sync/mutationAcknowledgement.js +10 -0
  46. package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -0
  47. package/data/documents/shared/sync/pullContinuation.js +53 -0
  48. package/data/documents/shared/sync/syncPagination.d.ts +20 -0
  49. package/data/documents/shared/sync/syncPagination.js +109 -0
  50. package/data/documents/shared/sync/syncPagination.js.map +1 -0
  51. package/data/documents/shared/sync/syncResponseAuthorization.js +63 -0
  52. package/data/documents/shared/sync/syncResponseAuthorization.js.map +1 -0
  53. package/data/documents/shared/sync/syncResponses.d.ts +11 -0
  54. package/data/documents/shared/sync/syncResponses.js +285 -0
  55. package/data/documents/shared/sync/syncResponses.js.map +1 -0
  56. package/data/documents/shared/sync/syncSubmitFailure.d.ts +9 -0
  57. package/data/documents/shared/types.d.ts +3 -3
  58. package/data/documents/shared/types.js.map +1 -1
  59. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js +61 -0
  60. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js.map +1 -0
  61. package/data/keyingProjectionVerification/checkpoints/bundleVerification.js +61 -0
  62. package/data/keyingProjectionVerification/checkpoints/bundleVerification.js.map +1 -0
  63. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +45 -0
  64. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +120 -0
  65. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -0
  66. package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js +64 -0
  67. package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js.map +1 -0
  68. package/data/keyingProjectionVerification/container/containerAncestorCitations.js +164 -0
  69. package/data/keyingProjectionVerification/container/containerAncestorCitations.js.map +1 -0
  70. package/data/keyingProjectionVerification/container/containerCreateManifest.js +28 -0
  71. package/data/keyingProjectionVerification/container/containerDestinationVerification.js +51 -0
  72. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -0
  73. package/data/keyingProjectionVerification/container/containerManifestVerification.js +285 -0
  74. package/data/keyingProjectionVerification/container/containerManifestVerification.js.map +1 -0
  75. package/data/keyingProjectionVerification/container/containerPathVerification.js +51 -0
  76. package/data/keyingProjectionVerification/container/containerPathVerification.js.map +1 -0
  77. package/data/keyingProjectionVerification/container/containerProjectionVerification.d.ts +25 -0
  78. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +254 -0
  79. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -0
  80. package/data/keyingProjectionVerification/document/documentDependencyPaths.d.ts +17 -0
  81. package/data/keyingProjectionVerification/document/documentDependencyPaths.js +70 -0
  82. package/data/keyingProjectionVerification/document/documentDependencyPaths.js.map +1 -0
  83. package/data/keyingProjectionVerification/document/documentManifestPolicies.js +32 -0
  84. package/data/keyingProjectionVerification/document/documentManifestPolicies.js.map +1 -0
  85. package/data/keyingProjectionVerification/document/documentManifestPredecessor.js +12 -0
  86. package/data/keyingProjectionVerification/document/documentManifestVerification.js +135 -0
  87. package/data/keyingProjectionVerification/document/documentManifestVerification.js.map +1 -0
  88. package/data/keyingProjectionVerification/document/documentProjectionVerification.d.ts +24 -0
  89. package/data/keyingProjectionVerification/document/documentProjectionVerification.js +172 -0
  90. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -0
  91. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +100 -0
  92. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -0
  93. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js +8 -0
  94. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js.map +1 -0
  95. package/data/keyingProjectionVerification/documentPurge/documentPurgeDocumentChainVerification.js +177 -0
  96. package/data/keyingProjectionVerification/documentPurge/documentPurgeDocumentChainVerification.js.map +1 -0
  97. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js +17 -0
  98. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js.map +1 -0
  99. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js +55 -0
  100. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js.map +1 -0
  101. package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js +116 -0
  102. package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js.map +1 -0
  103. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.d.ts +34 -0
  104. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js +208 -0
  105. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js.map +1 -0
  106. package/data/keyingProjectionVerification/index.d.ts +4 -4
  107. package/data/keyingProjectionVerification/index.js +4 -4
  108. package/data/keyingProjectionVerification/index.js.map +1 -1
  109. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js +45 -0
  110. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js.map +1 -0
  111. package/data/keyingProjectionVerification/principalPolicy/organizationFounderBinding.js +41 -0
  112. package/data/keyingProjectionVerification/principalPolicy/organizationFounderBinding.js.map +1 -0
  113. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +76 -0
  114. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -0
  115. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +252 -0
  116. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -0
  117. package/data/keyingProjectionVerification/principalPolicy/projectionAuthorizationEvidence.js +63 -0
  118. package/data/keyingProjectionVerification/principalPolicy/projectionAuthorizationEvidence.js.map +1 -0
  119. package/data/keyingProjectionVerification/principalPolicy/projectionPolicyEvidence.js +23 -0
  120. package/data/keyingProjectionVerification/principalPolicy/projectionPolicyEvidence.js.map +1 -0
  121. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js +72 -0
  122. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js.map +1 -0
  123. package/data/persistence/container-contents/containerContentsPersistence.js +3 -3
  124. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  125. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -2
  126. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  127. package/data/persistence/container-contents/containerCreateIntentSettlement.js +1 -1
  128. package/data/persistence/container-contents/containerDeletionPersistence.js +2 -2
  129. package/data/persistence/container-contents/containerDocumentReassignment.js +2 -2
  130. package/data/persistence/container-contents/containerDocumentReassignment.js.map +1 -1
  131. package/data/persistence/container-contents/containerHydrationPersistence.js +3 -3
  132. package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
  133. package/data/persistence/container-contents/containerIntentPersistence.js +1 -1
  134. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +5 -5
  135. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  136. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +1 -1
  137. package/data/persistence/container-contents/containerMetadataRows.js +3 -3
  138. package/data/persistence/container-contents/containerMetadataRows.js.map +1 -1
  139. package/data/persistence/container-contents/containerMoveAbandonPersistence.js +1 -1
  140. package/data/persistence/container-contents/containerMoveIntentRows.js +1 -1
  141. package/data/persistence/container-contents/containerPendingUpdatePersistence.js +3 -3
  142. package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
  143. package/data/persistence/container-contents/containerRebindPersistence.js +1 -1
  144. package/data/persistence/container-contents/containerReconcilePersistence.js +2 -2
  145. package/data/persistence/container-contents/containerRecoveryPersistence.js +1 -1
  146. package/data/persistence/container-contents/containerRemovalWork.js +3 -3
  147. package/data/persistence/container-contents/containerRemovalWork.js.map +1 -1
  148. package/data/persistence/container-contents/containerStructuralRepair.js +1 -1
  149. package/data/persistence/container-contents/documentLinkRemovalRepair.js +2 -2
  150. package/data/persistence/container-contents/documentLinkRemovalRepair.js.map +1 -1
  151. package/data/persistence/container-contents/documentMoveIntentPersistence.js +2 -2
  152. package/data/persistence/container-contents/documentMoveIntentPersistence.js.map +1 -1
  153. package/data/persistence/container-contents/documentPlacementIntentEnqueue.js +2 -2
  154. package/data/persistence/container-contents/documentPlacementIntentEnqueue.js.map +1 -1
  155. package/data/persistence/container-contents/documentPurgePlacement.js +1 -1
  156. package/data/persistence/container-contents/dormantContainerMetadata.js +1 -1
  157. package/data/persistence/container-contents/dormantMetadataSweep.js +1 -1
  158. package/data/persistence/container-contents/pendingContainerCreate.js +1 -1
  159. package/data/persistence/container-contents/supersededContainerBindings.js +1 -1
  160. package/data/persistence/containers/containerPersistence.js +1 -1
  161. package/data/persistence/containers/containerSyncWatermarkPersistence.js +1 -1
  162. package/data/persistence/containers/documentContainerProjectionPersistence.js +1 -1
  163. package/data/persistence/containers/documentPlacement.js +1 -1
  164. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js +1 -1
  165. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +3 -3
  166. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  167. package/data/persistence/documents/documentDiscoveryReset.js +1 -1
  168. package/data/persistence/documents/documentDiscoveryReset.js.map +1 -1
  169. package/data/persistence/documents/documentsPersistence.js +3 -3
  170. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  171. package/data/persistence/documents/internal/attachmentStagingPersistence.js +1 -1
  172. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
  173. package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
  174. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +2 -2
  175. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  176. package/data/persistence/documents/internal/discardDocument.js +3 -3
  177. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  178. package/data/persistence/documents/internal/documentDeletionPersistence.js +4 -4
  179. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  180. package/data/persistence/documents/internal/documentMutationPersistence.js +5 -5
  181. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  182. package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
  183. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
  184. package/data/persistence/documents/internal/documentRows.js +2 -2
  185. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  186. package/data/persistence/documents/internal/documentSummaryQueries.js +1 -1
  187. package/data/persistence/documents/internal/ensureDocumentsSchema.js +2 -2
  188. package/data/persistence/documents/internal/hydratedAttachmentPersistence.js +1 -1
  189. package/data/persistence/documents/internal/orphanSideRows.js +2 -2
  190. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  191. package/data/persistence/documents/internal/pendingCreateAdoption.js +1 -1
  192. package/data/persistence/documents/internal/rowQueryPersistence.js +2 -2
  193. package/data/persistence/documents/internal/syncQueuePersistence.js +3 -3
  194. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  195. package/data/persistence/documents/types.d.ts +3 -3
  196. package/data/persistence/documents/types.js.map +1 -1
  197. package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.d.ts +10 -0
  198. package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js +43 -0
  199. package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js.map +1 -0
  200. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js +222 -0
  201. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -0
  202. package/data/persistence/keyingCheckpoints/keyingCheckpointEvidence.js +32 -0
  203. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js +133 -0
  204. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js.map +1 -0
  205. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +53 -0
  206. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +167 -0
  207. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -0
  208. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js +72 -0
  209. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js.map +1 -0
  210. package/data/persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js +29 -0
  211. package/data/persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js.map +1 -0
  212. package/data/persistence/organizationFounderPersistence.js +2 -2
  213. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  214. package/data/persistence/organizations/organizationAccessRevocationPersistence.js +3 -3
  215. package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +1 -1
  216. package/data/persistence/organizations/organizationDataUsagePersistence.js +2 -2
  217. package/data/persistence/organizations/organizationDataUsagePersistence.js.map +1 -1
  218. package/data/persistence/organizations/organizationGroupNamePersistence.js +2 -2
  219. package/data/persistence/organizations/organizationGroupNamePersistence.js.map +1 -1
  220. package/data/persistence/organizations/organizationPresentationDenialPersistence.js +2 -2
  221. package/data/persistence/organizations/organizationPresentationDenialPersistence.js.map +1 -1
  222. package/data/persistence/organizations/organizationProfileDocumentPointers.js +2 -2
  223. package/data/persistence/organizations/organizationProfileDocumentPointers.js.map +1 -1
  224. package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js +1 -1
  225. package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js.map +1 -1
  226. package/data/persistence/organizations/organizationReadModelGrantPersistence.js +1 -1
  227. package/data/persistence/organizations/organizationReadModelGrantPersistence.js.map +1 -1
  228. package/data/persistence/organizations/organizationReadModelMemberLoad.js +1 -1
  229. package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
  230. package/data/persistence/organizations/organizationReadModelMembershipPersistence.js +1 -1
  231. package/data/persistence/organizations/organizationReadModelMembershipPersistence.js.map +1 -1
  232. package/data/persistence/organizations/organizationReadModelPersistence.js +3 -3
  233. package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
  234. package/data/persistence/organizations/organizationReadModelProjection.js +1 -1
  235. package/data/persistence/organizations/organizationReadModelProjection.js.map +1 -1
  236. package/data/persistence/organizations/organizationReadModelPurge.js +3 -3
  237. package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
  238. package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +3 -3
  239. package/data/persistence/principalCurrentAcknowledgementPersistence.js +10 -10
  240. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
  241. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.d.ts +32 -0
  242. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js +92 -0
  243. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js.map +1 -0
  244. package/data/persistence/principalHistory/principalHistoryIncompleteRetention.js +26 -0
  245. package/data/persistence/principalHistory/principalHistoryIncompleteRetention.js.map +1 -0
  246. package/data/persistence/principalHistory/principalHistoryNodeRetention.js +201 -0
  247. package/data/persistence/principalHistory/principalHistoryNodeRetention.js.map +1 -0
  248. package/data/persistence/principalHistory/principalHistoryPrefixPersistence.d.ts +29 -0
  249. package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js +102 -0
  250. package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js.map +1 -0
  251. package/data/persistence/principalHistory/principalHistoryRootOwnership.js +71 -0
  252. package/data/persistence/principalHistory/principalHistoryRootOwnership.js.map +1 -0
  253. package/data/persistence/principalHistory/principalHistoryStagePersistence.d.ts +15 -0
  254. package/data/persistence/principalHistory/principalHistoryStagePersistence.js +96 -0
  255. package/data/persistence/principalHistory/principalHistoryStagePersistence.js.map +1 -0
  256. package/data/persistence/principalHistory/principalHistoryStageRetention.js +45 -0
  257. package/data/persistence/principalHistory/principalHistoryStageRetention.js.map +1 -0
  258. package/data/persistence/principalHistory/principalHistoryUnpublishedRetention.js +64 -0
  259. package/data/persistence/principalHistory/principalHistoryUnpublishedRetention.js.map +1 -0
  260. package/data/persistence/principalKeys/principalGrantRetirementPersistence.d.ts +9 -0
  261. package/data/persistence/principalKeys/principalGrantRetirementPersistence.js +43 -0
  262. package/data/persistence/principalKeys/principalGrantRetirementPersistence.js.map +1 -0
  263. package/data/persistence/principalKeys/principalKeyEnvelopeArchivePersistence.js +63 -0
  264. package/data/persistence/principalKeys/principalKeyEnvelopeArchivePersistence.js.map +1 -0
  265. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js +87 -0
  266. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -0
  267. package/data/persistence/principalMutationJournalPersistence.d.ts +1 -1
  268. package/data/persistence/principalMutationJournalPersistence.js +1 -1
  269. package/data/persistence/principalMutationJournalPersistence.js.map +1 -1
  270. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js +49 -0
  271. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js.map +1 -0
  272. package/data/persistence/principalPolicy/principalPolicyCheckpointSelection.js +26 -0
  273. package/data/persistence/principalPolicy/principalPolicyCheckpointSelection.js.map +1 -0
  274. package/data/persistence/principalPolicy/principalPolicyOrganizationPersistence.js +42 -0
  275. package/data/persistence/principalPolicy/principalPolicyOrganizationPersistence.js.map +1 -0
  276. package/data/persistence/principalPolicy/principalPolicyPersistence.js +279 -0
  277. package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -0
  278. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js +27 -0
  279. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js.map +1 -0
  280. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js +115 -0
  281. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js.map +1 -0
  282. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js +215 -0
  283. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -0
  284. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundle.js +33 -0
  285. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundle.js.map +1 -0
  286. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js +56 -0
  287. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js.map +1 -0
  288. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js +18 -0
  289. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +1 -0
  290. package/data/persistence/securityIncidentPersistence.js +1 -1
  291. package/data/persistence/securityIncidentPersistence.js.map +1 -1
  292. package/data/persistence/trustedUserIdentityPinPersistence.js +1 -1
  293. package/data/persistence/verifiedManifestBundlePersistence.d.ts +1 -1
  294. package/data/persistence/verifiedManifestBundlePersistence.js +4 -4
  295. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  296. package/data/principals/organizationGroupRoles.js +2 -2
  297. package/data/principals/organizationGroupRoles.js.map +1 -1
  298. package/data/principals/principalHistoryPrefixProtection.js.map +1 -1
  299. package/data/principals/principalHistoryStageProtection.js.map +1 -1
  300. package/data/principals/principalPolicyCrypto.js +1 -1
  301. package/data/principals/principalPolicyCrypto.js.map +1 -1
  302. package/data/sqlite/documentPersistence/documentHistoryPersistence.d.ts +86 -0
  303. package/data/sqlite/documentPersistence/documentHistoryPersistence.js +304 -0
  304. package/data/sqlite/documentPersistence/documentHistoryPersistence.js.map +1 -0
  305. package/data/sqlite/documentPersistence/documentOrphanBlobReclaims.js +6 -0
  306. package/data/sqlite/documentPersistence/documentOrphanBlobReclaims.js.map +1 -0
  307. package/data/sqlite/documentPersistence/documentPendingUpdatePersistence.d.ts +103 -0
  308. package/data/sqlite/documentPersistence/documentPendingUpdatePersistence.js +243 -0
  309. package/data/sqlite/documentPersistence/documentPendingUpdatePersistence.js.map +1 -0
  310. package/data/sqlite/documentPersistence/documentPersistenceTypes.d.ts +79 -0
  311. package/data/sqlite/documentPersistence/documentPersistenceTypes.js.map +1 -0
  312. package/data/sqlite/documentPersistence/documentRecordPersistence.d.ts +275 -0
  313. package/data/sqlite/documentPersistence/documentRecordPersistence.js +103 -0
  314. package/data/sqlite/documentPersistence/documentRecordPersistence.js.map +1 -0
  315. package/data/sqlite/documentPersistence/documentSyncFailurePersistence.d.ts +39 -0
  316. package/data/sqlite/documentPersistence/documentSyncFailurePersistence.js +81 -0
  317. package/data/sqlite/documentPersistence/documentSyncFailurePersistence.js.map +1 -0
  318. package/data/sqlite/documentPersistence/index.d.ts +22 -0
  319. package/data/sqlite/documentPersistence/index.js +35 -0
  320. package/data/sqlite/documentPersistence/index.js.map +1 -0
  321. package/data/sqlite/schema/containerSchema.d.ts +1193 -0
  322. package/data/sqlite/schema/containerSchema.js +103 -0
  323. package/data/sqlite/schema/containerSchema.js.map +1 -0
  324. package/data/sqlite/schema/index.d.ts +8055 -0
  325. package/data/sqlite/schema/index.js +525 -0
  326. package/data/sqlite/schema/index.js.map +1 -0
  327. package/data/sqlite/schema/organizationDataUsageSchema.js +34 -0
  328. package/data/sqlite/schema/organizationDataUsageSchema.js.map +1 -0
  329. package/data/sqlite/schema/organizationProvisioningAttemptSchema.js +23 -0
  330. package/data/sqlite/schema/organizationProvisioningAttemptSchema.js.map +1 -0
  331. package/data/sqlite/schema/organizationReadModelTableRegistry.d.ts +1332 -0
  332. package/data/sqlite/schema/organizationReadModelTableRegistry.js +31 -0
  333. package/data/sqlite/schema/organizationReadModelTableRegistry.js.map +1 -0
  334. package/data/sqlite/schema/principalHistoryEvidenceSchema.d.ts +308 -0
  335. package/data/sqlite/schema/principalHistoryEvidenceSchema.js +48 -0
  336. package/data/sqlite/schema/principalHistoryEvidenceSchema.js.map +1 -0
  337. package/data/sqlite/schema/principalHistoryNodeRetentionSchema.js +30 -0
  338. package/data/sqlite/schema/principalHistoryNodeRetentionSchema.js.map +1 -0
  339. package/data/sqlite/schema/principalHistoryRetentionSchema.js +25 -0
  340. package/data/sqlite/schema/principalHistoryRetentionSchema.js.map +1 -0
  341. package/data/sqlite/schema/principalHistoryStageSchema.d.ts +161 -0
  342. package/data/sqlite/schema/principalHistoryStageSchema.js +34 -0
  343. package/data/sqlite/schema/principalHistoryStageSchema.js.map +1 -0
  344. package/data/sqlite/schema/principalMutationJournalSchema.d.ts +85 -0
  345. package/data/sqlite/schema/principalMutationJournalSchema.js +13 -0
  346. package/data/sqlite/schema/principalMutationJournalSchema.js.map +1 -0
  347. package/data/sqlite/schema/principalPolicySchema.js +72 -0
  348. package/data/sqlite/schema/principalPolicySchema.js.map +1 -0
  349. package/data/sqlite/schema/securityIncidentSchema.d.ts +224 -0
  350. package/data/sqlite/schema/securityIncidentSchema.js +28 -0
  351. package/data/sqlite/schema/securityIncidentSchema.js.map +1 -0
  352. package/data/sqlite/schema/verifiedManifestBundleSchema.d.ts +174 -0
  353. package/data/sqlite/schema/verifiedManifestBundleSchema.js +36 -0
  354. package/data/sqlite/schema/verifiedManifestBundleSchema.js.map +1 -0
  355. package/data/sqlite/sqlitePersistenceRuntime.d.ts +1 -1
  356. package/data/sqlite/sqlitePersistenceRuntime.js +1 -1
  357. package/package.json +1 -1
  358. package/sqlite/index.d.ts +1 -1
  359. package/sqlite/index.js +1 -1
  360. package/stores/container-contents/accessRestorationSweep.js +1 -1
  361. package/stores/container-contents/accessRestorationSweep.js.map +1 -1
  362. package/stores/container-contents/containerContentsStore.d.ts +1 -1
  363. package/stores/container-contents/containerContentsStore.js +12 -12
  364. package/stores/container-contents/containerContentsStore.js.map +1 -1
  365. package/stores/container-contents/containerState/containerStateMap.js.map +1 -0
  366. package/stores/container-contents/containerState/containerStatePersistence.js +57 -0
  367. package/stores/container-contents/containerState/containerStatePersistence.js.map +1 -0
  368. package/stores/container-contents/containerState/missingContainerState.js +10 -0
  369. package/stores/container-contents/containerState/missingContainerState.js.map +1 -0
  370. package/stores/container-contents/containerState/missingSyncedContainerState.js.map +1 -0
  371. package/stores/container-contents/containerState/reconcilableContainer.d.ts +48 -0
  372. package/stores/container-contents/containerState/reconcilableContainer.js.map +1 -0
  373. package/stores/container-contents/documentWork/documentRecovery.js +114 -0
  374. package/stores/container-contents/documentWork/documentRecovery.js.map +1 -0
  375. package/stores/container-contents/documentWork/documentRotation.js +13 -0
  376. package/stores/container-contents/documentWork/documentRotation.js.map +1 -0
  377. package/stores/container-contents/documentWork/index.js +29 -0
  378. package/stores/container-contents/documentWork/index.js.map +1 -0
  379. package/stores/container-contents/hydration/backgroundHydration.js +32 -0
  380. package/stores/container-contents/hydration/backgroundHydration.js.map +1 -0
  381. package/stores/container-contents/hydration/remoteHydrationRequest.js +245 -0
  382. package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -0
  383. package/stores/container-contents/hydration/startupHydration.js +110 -0
  384. package/stores/container-contents/hydration/startupHydration.js.map +1 -0
  385. package/stores/container-contents/index.d.ts +3 -3
  386. package/stores/container-contents/index.js +2 -2
  387. package/stores/container-contents/index.js.map +1 -1
  388. package/stores/container-contents/localRefresh.js +2 -2
  389. package/stores/container-contents/localRefresh.js.map +1 -1
  390. package/stores/container-contents/operations/containerPurgeCore.js +98 -0
  391. package/stores/container-contents/operations/containerPurgeCore.js.map +1 -0
  392. package/stores/container-contents/operations/emptyTrashOperation.js.map +1 -0
  393. package/stores/container-contents/operations/groupRewrapOperation.js +52 -0
  394. package/stores/container-contents/operations/groupRewrapOperation.js.map +1 -0
  395. package/stores/container-contents/operations/index.js +301 -0
  396. package/stores/container-contents/operations/index.js.map +1 -0
  397. package/stores/container-contents/operations/purgeContainerOperation.js.map +1 -0
  398. package/stores/container-contents/operations/reportShareFailure.js +44 -0
  399. package/stores/container-contents/operations/reportShareFailure.js.map +1 -0
  400. package/stores/container-contents/operations/setContainerIconOperation.js +47 -0
  401. package/stores/container-contents/operations/setContainerIconOperation.js.map +1 -0
  402. package/stores/container-contents/operations/shareOperations.js +90 -0
  403. package/stores/container-contents/operations/shareOperations.js.map +1 -0
  404. package/stores/container-contents/remoteEvents/remoteBackedContainerState.js.map +1 -0
  405. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js +59 -0
  406. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js.map +1 -0
  407. package/stores/container-contents/remoteEvents/remoteEventProjectionInvalidation.js +36 -0
  408. package/stores/container-contents/remoteEvents/remoteEventProjectionInvalidation.js.map +1 -0
  409. package/stores/container-contents/remoteEvents/remoteEventSync.js +38 -0
  410. package/stores/container-contents/remoteEvents/remoteEventSync.js.map +1 -0
  411. package/stores/container-contents/remoteWrites/remoteWriteGuards.js +54 -0
  412. package/stores/container-contents/remoteWrites/remoteWriteGuards.js.map +1 -0
  413. package/stores/container-contents/remoteWrites/remoteWriteQueue.js +51 -0
  414. package/stores/container-contents/remoteWrites/remoteWriteQueue.js.map +1 -0
  415. package/stores/container-contents/remoteWrites/writeGeneration.js.map +1 -0
  416. package/stores/container-contents/state.d.ts +1 -1
  417. package/stores/container-contents/state.js +2 -2
  418. package/stores/container-contents/state.js.map +1 -1
  419. package/stores/container-contents/syncAgent/index.d.ts +8 -0
  420. package/stores/container-contents/syncAgent/index.js +241 -0
  421. package/stores/container-contents/syncAgent/index.js.map +1 -0
  422. package/stores/container-contents/syncAgent/metadataSyncSignal.js +37 -0
  423. package/stores/container-contents/syncAgent/metadataSyncSignal.js.map +1 -0
  424. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +81 -0
  425. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -0
  426. package/stores/container-contents/syncAgent/syncLaneIteration.js +237 -0
  427. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -0
  428. package/stores/container-contents/systemContainers/existingSystemContainer.js +58 -0
  429. package/stores/container-contents/systemContainers/existingSystemContainer.js.map +1 -0
  430. package/stores/container-contents/systemContainers/organizationMetadataSystemContainer.js +44 -0
  431. package/stores/container-contents/systemContainers/organizationMetadataSystemContainer.js.map +1 -0
  432. package/stores/container-contents/systemContainers/systemContainerHydration.js +30 -0
  433. package/stores/container-contents/systemContainers/systemContainerHydration.js.map +1 -0
  434. package/stores/container-contents/systemContainers/systemContainerIcon.js +42 -0
  435. package/stores/container-contents/systemContainers/systemContainerIcon.js.map +1 -0
  436. package/stores/container-contents/systemContainers/systemContainerLookup.js.map +1 -0
  437. package/stores/container-contents/systemContainers/systemContainerPostCreate.js +109 -0
  438. package/stores/container-contents/systemContainers/systemContainerPostCreate.js.map +1 -0
  439. package/stores/container-contents/systemContainers/systemContainerPromotion.js +49 -0
  440. package/stores/container-contents/systemContainers/systemContainerPromotion.js.map +1 -0
  441. package/stores/container-contents/types.d.ts +2 -2
  442. package/stores/container-contents/types.js.map +1 -1
  443. package/stores/documents/documentStore/attachmentUpload/attachmentSourceUpload.js +39 -0
  444. package/stores/documents/documentStore/attachmentUpload/attachmentSourceUpload.js.map +1 -0
  445. package/stores/documents/documentStore/attachmentUpload/attachmentStaging.js +84 -0
  446. package/stores/documents/documentStore/attachmentUpload/attachmentStaging.js.map +1 -0
  447. package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js +97 -0
  448. package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js.map +1 -0
  449. package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js +49 -0
  450. package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js.map +1 -0
  451. package/stores/documents/documentStore/attachmentUpload/attachmentUploadResume.js +95 -0
  452. package/stores/documents/documentStore/attachmentUpload/attachmentUploadResume.js.map +1 -0
  453. package/stores/documents/documentStore/attachments/attachmentDetachState.js +54 -0
  454. package/stores/documents/documentStore/attachments/attachmentDetachState.js.map +1 -0
  455. package/stores/documents/documentStore/attachments/attachmentHydration.js +90 -0
  456. package/stores/documents/documentStore/attachments/attachmentHydration.js.map +1 -0
  457. package/stores/documents/documentStore/attachments/attachmentHydrationCommit.js +53 -0
  458. package/stores/documents/documentStore/attachments/attachmentHydrationCommit.js.map +1 -0
  459. package/stores/documents/documentStore/attachments/attachmentIntents.js +39 -0
  460. package/stores/documents/documentStore/attachments/attachmentIntents.js.map +1 -0
  461. package/stores/documents/documentStore/attachments/attachmentMutationPersistence.js +37 -0
  462. package/stores/documents/documentStore/attachments/attachmentMutationPersistence.js.map +1 -0
  463. package/stores/documents/documentStore/attachments/attachmentPersistFollowup.js.map +1 -0
  464. package/stores/documents/documentStore/attachments/attachmentPersistence.js +106 -0
  465. package/stores/documents/documentStore/attachments/attachmentPersistence.js.map +1 -0
  466. package/stores/documents/documentStore/attachments/attachmentRemoval.js +136 -0
  467. package/stores/documents/documentStore/attachments/attachmentRemoval.js.map +1 -0
  468. package/stores/documents/documentStore/attachments/attachmentSnapshot.js.map +1 -0
  469. package/stores/documents/documentStore/attachments/attachmentWriteGeneration.js +32 -0
  470. package/stores/documents/documentStore/attachments/attachmentWriteGeneration.js.map +1 -0
  471. package/stores/documents/documentStore/attachments/index.js +241 -0
  472. package/stores/documents/documentStore/attachments/index.js.map +1 -0
  473. package/stores/documents/documentStore/history/documentHistoryCompaction.js +67 -0
  474. package/stores/documents/documentStore/history/documentHistoryCompaction.js.map +1 -0
  475. package/stores/documents/documentStore/history/durableDocumentReload.js +79 -0
  476. package/stores/documents/documentStore/history/durableDocumentReload.js.map +1 -0
  477. package/stores/documents/documentStore/history/historyRebuild.js +75 -0
  478. package/stores/documents/documentStore/history/historyRebuild.js.map +1 -0
  479. package/stores/documents/documentStore/index.d.ts +8 -0
  480. package/stores/documents/documentStore/index.js +215 -0
  481. package/stores/documents/documentStore/index.js.map +1 -0
  482. package/stores/documents/documentStore/initialization/deferredInitialUpdate.js +116 -0
  483. package/stores/documents/documentStore/initialization/deferredInitialUpdate.js.map +1 -0
  484. package/stores/documents/documentStore/initialization/index.js +330 -0
  485. package/stores/documents/documentStore/initialization/index.js.map +1 -0
  486. package/stores/documents/documentStore/initialization/initializationAttachments.js +9 -0
  487. package/stores/documents/documentStore/initialization/initializationAttachments.js.map +1 -0
  488. package/stores/documents/documentStore/initialization/initializationHistory.js +33 -0
  489. package/stores/documents/documentStore/initialization/initializationHistory.js.map +1 -0
  490. package/stores/documents/documentStore/initialization/initializationRecovery.js +107 -0
  491. package/stores/documents/documentStore/initialization/initializationRecovery.js.map +1 -0
  492. package/stores/documents/documentStore/mutationIdentityRevalidation.js.map +1 -1
  493. package/stores/documents/documentStore/mutations.js +2 -2
  494. package/stores/documents/documentStore/mutations.js.map +1 -1
  495. package/stores/documents/documentStore/pendingUpdateRefusal.js +1 -1
  496. package/stores/documents/documentStore/pendingUpdateRefusal.js.map +1 -1
  497. package/stores/documents/documentStore/persistence.js +3 -3
  498. package/stores/documents/documentStore/persistence.js.map +1 -1
  499. package/stores/documents/documentStore/rotation/index.js +307 -0
  500. package/stores/documents/documentStore/rotation/index.js.map +1 -0
  501. package/stores/documents/documentStore/rotation/rotationProvenance.js +52 -0
  502. package/stores/documents/documentStore/rotation/rotationProvenance.js.map +1 -0
  503. package/stores/documents/documentStore/rotation/rotationSettlement.js +222 -0
  504. package/stores/documents/documentStore/rotation/rotationSettlement.js.map +1 -0
  505. package/stores/documents/documentStore/rows.js +2 -2
  506. package/stores/documents/documentStore/rows.js.map +1 -1
  507. package/stores/documents/documentStore/state.js +1 -1
  508. package/stores/documents/documentStore/state.js.map +1 -1
  509. package/stores/documents/documentStore/sync/index.js +299 -0
  510. package/stores/documents/documentStore/sync/index.js.map +1 -0
  511. package/stores/documents/documentStore/sync/pullContinuationInvalidation.js +61 -0
  512. package/stores/documents/documentStore/sync/pullContinuationInvalidation.js.map +1 -0
  513. package/stores/documents/documentStore/sync/remoteRevalidationTelemetry.js +15 -0
  514. package/stores/documents/documentStore/sync/remoteRevalidationTelemetry.js.map +1 -0
  515. package/stores/documents/documentStore/sync/remoteWork.js.map +1 -0
  516. package/stores/documents/documentStore/sync/syncAcceptedUpdateIds.js.map +1 -0
  517. package/stores/documents/documentStore/sync/syncAttachmentSettlement.js +72 -0
  518. package/stores/documents/documentStore/sync/syncAttachmentSettlement.js.map +1 -0
  519. package/stores/documents/documentStore/sync/syncAttachments.js +323 -0
  520. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -0
  521. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +129 -0
  522. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -0
  523. package/stores/documents/documentStore/sync/syncFinalize.js +204 -0
  524. package/stores/documents/documentStore/sync/syncFinalize.js.map +1 -0
  525. package/stores/documents/documentStore/sync/syncGeneration.js.map +1 -0
  526. package/stores/documents/documentStore/sync/syncOutgoingCoverage.js +96 -0
  527. package/stores/documents/documentStore/sync/syncOutgoingCoverage.js.map +1 -0
  528. package/stores/documents/documentStore/sync/syncRemoteSignals.js +67 -0
  529. package/stores/documents/documentStore/sync/syncRemoteSignals.js.map +1 -0
  530. package/stores/documents/documentStore/sync/syncRequest.js +157 -0
  531. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -0
  532. package/stores/documents/documentStore/sync/syncShared.js +211 -0
  533. package/stores/documents/documentStore/sync/syncShared.js.map +1 -0
  534. package/stores/documents/documentStore/sync/syncUpdateImport.js +62 -0
  535. package/stores/documents/documentStore/sync/syncUpdateImport.js.map +1 -0
  536. package/stores/documents/documentStore/sync/versionCoverage.js +45 -0
  537. package/stores/documents/index.d.ts +1 -1
  538. package/stores/documents/index.js +1 -1
  539. package/stores/local-projection/localProjectionStore.d.ts +1 -1
  540. package/stores/local-projection/localProjectionStore.js +1 -1
  541. package/stores/local-projection/localProjectionStore.js.map +1 -1
  542. package/stores/local-projection/registry.d.ts +1 -1
  543. package/stores/local-projection/types.d.ts +1 -1
  544. package/workflows/blobs/detach.js +1 -1
  545. package/workflows/blobs/hydration/decrypt.js +2 -2
  546. package/workflows/blobs/hydration/decrypt.js.map +1 -1
  547. package/workflows/blobs/upload/index.js +1 -1
  548. package/workflows/blobs/verification/retainedAttachmentVerification.js +1 -1
  549. package/workflows/blobs/verification/writerProjection.js +1 -1
  550. package/workflows/container-contents/container-state/create/createAdoption.js +193 -0
  551. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -0
  552. package/workflows/container-contents/container-state/create/createChild.js +217 -0
  553. package/workflows/container-contents/container-state/create/createChild.js.map +1 -0
  554. package/workflows/container-contents/container-state/create/createIntentDepth.js +36 -0
  555. package/workflows/container-contents/container-state/create/createIntentDepth.js.map +1 -0
  556. package/workflows/container-contents/container-state/create/createIntentSettlement.js.map +1 -0
  557. package/workflows/container-contents/container-state/create/createIntentSync.js +354 -0
  558. package/workflows/container-contents/container-state/create/createIntentSync.js.map +1 -0
  559. package/workflows/container-contents/container-state/create/createTerminalFailure.js +19 -0
  560. package/workflows/container-contents/container-state/create/createTerminalFailure.js.map +1 -0
  561. package/workflows/container-contents/container-state/create/createWithMetadata.js +270 -0
  562. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -0
  563. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js +68 -0
  564. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -0
  565. package/workflows/container-contents/container-state/purge/localPurgeScope.js +49 -0
  566. package/workflows/container-contents/container-state/purge/localPurgeScope.js.map +1 -0
  567. package/workflows/container-contents/container-state/purge/purgeTree.js +298 -0
  568. package/workflows/container-contents/container-state/purge/purgeTree.js.map +1 -0
  569. package/workflows/container-contents/container-state/purge/purgeTreeCollection.js.map +1 -0
  570. package/workflows/container-contents/container-state/purge/purgeTreeContainerDeletion.js +75 -0
  571. package/workflows/container-contents/container-state/purge/purgeTreeContainerDeletion.js.map +1 -0
  572. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +175 -0
  573. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -0
  574. package/workflows/container-contents/container-state/purge/readLocalPurgeScope.js +18 -0
  575. package/workflows/container-contents/container-state/purge/readLocalPurgeScope.js.map +1 -0
  576. package/workflows/container-contents/container-state/remote.js +2 -2
  577. package/workflows/container-contents/container-state/remote.js.map +1 -1
  578. package/workflows/container-contents/container-state/share/groupGrantVerification.js +71 -0
  579. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -0
  580. package/workflows/container-contents/container-state/share/groupShareEpoch.js +16 -0
  581. package/workflows/container-contents/container-state/share/groupShareEpoch.js.map +1 -0
  582. package/workflows/container-contents/container-state/share/index.js +283 -0
  583. package/workflows/container-contents/container-state/share/index.js.map +1 -0
  584. package/workflows/container-contents/container-state/share/sharePersistence.js +136 -0
  585. package/workflows/container-contents/container-state/share/sharePersistence.js.map +1 -0
  586. package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js +1 -1
  587. package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js.map +1 -1
  588. package/workflows/container-contents/documentDiscovery/index.js +1 -1
  589. package/workflows/container-contents/documentDiscovery/index.js.map +1 -1
  590. package/workflows/container-contents/documentLinks/index.js +1 -1
  591. package/workflows/container-contents/documentMove/documentMoveVanishedRefresh.js +1 -1
  592. package/workflows/container-contents/documentPriming/documentHydrationProbe.js +1 -1
  593. package/workflows/container-contents/documentPriming/index.js +1 -1
  594. package/workflows/container-contents/documentQueries/index.js +1 -1
  595. package/workflows/container-contents/documentQueries/sql.js +1 -1
  596. package/workflows/container-contents/info/blobInfo.js +1 -1
  597. package/workflows/container-contents/info/containerInfo.js +1 -1
  598. package/workflows/container-contents/info/documentInfo.js +1 -1
  599. package/workflows/container-contents/metadata/index.js +1 -1
  600. package/workflows/container-contents/metadata/index.js.map +1 -1
  601. package/workflows/container-contents/metadata/metadataEvents.d.ts +1 -1
  602. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
  603. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  604. package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
  605. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
  606. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js +1 -1
  607. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js.map +1 -1
  608. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +1 -1
  609. package/workflows/container-contents/metadata/metadataSyncErrors.js +2 -2
  610. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  611. package/workflows/container-contents/metadata/metadataSyncSettlement.d.ts +1 -1
  612. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
  613. package/workflows/container-contents/metadata/metadataTypes.d.ts +1 -1
  614. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  615. package/workflows/container-contents/pendingWrites/index.js +2 -2
  616. package/workflows/container-contents/pendingWrites/sources.js +1 -1
  617. package/workflows/container-contents/remoteHydration/destination/destinationPrefetch.js.map +1 -0
  618. package/workflows/container-contents/remoteHydration/destination/destinationRoleCache.js.map +1 -0
  619. package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js +10 -0
  620. package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js.map +1 -0
  621. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +75 -0
  622. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -0
  623. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +296 -0
  624. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -0
  625. package/workflows/container-contents/remoteHydration/index.js +4 -4
  626. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  627. package/workflows/container-contents/remoteHydration/lanes/childIndex.js.map +1 -0
  628. package/workflows/container-contents/remoteHydration/lanes/laneFetchMarkers.js +21 -0
  629. package/workflows/container-contents/remoteHydration/lanes/laneFetchMarkers.js.map +1 -0
  630. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js +61 -0
  631. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js.map +1 -0
  632. package/workflows/container-contents/remoteHydration/lanes/parentLaneQueue.js.map +1 -0
  633. package/workflows/container-contents/remoteHydration/principalPolicyCache.js +1 -1
  634. package/workflows/container-contents/remoteHydration/principalPolicyCache.js.map +1 -1
  635. package/workflows/container-contents/remoteHydration/reattachMetadata.js.map +1 -1
  636. package/workflows/container-contents/remoteHydration/reconciliation.js +2 -2
  637. package/workflows/container-contents/remoteHydration/reconciliation.js.map +1 -1
  638. package/workflows/container-contents/remoteHydration/remoteContainers/containerStateFingerprint.js.map +1 -0
  639. package/workflows/container-contents/remoteHydration/remoteContainers/insertRemoteContainer.js +135 -0
  640. package/workflows/container-contents/remoteHydration/remoteContainers/insertRemoteContainer.js.map +1 -0
  641. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +244 -0
  642. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -0
  643. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +263 -0
  644. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -0
  645. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerTimestamps.js.map +1 -0
  646. package/workflows/container-contents/remoteHydration/tombstoneApplication.js +2 -2
  647. package/workflows/container-contents/remoteHydration/tombstoneApplication.js.map +1 -1
  648. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +2 -2
  649. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  650. package/workflows/containers/child/create/createProjection.d.ts +6 -0
  651. package/workflows/containers/child/create/createProjection.js +43 -0
  652. package/workflows/containers/child/create/createProjection.js.map +1 -0
  653. package/workflows/containers/child/create/createSubmission.d.ts +56 -0
  654. package/workflows/containers/child/create/createSubmission.js +43 -0
  655. package/workflows/containers/child/create/createSubmission.js.map +1 -0
  656. package/workflows/containers/child/create/index.d.ts +24 -0
  657. package/workflows/containers/child/create/index.js +335 -0
  658. package/workflows/containers/child/create/index.js.map +1 -0
  659. package/workflows/containers/child/move/index.d.ts +23 -0
  660. package/workflows/containers/child/move/index.js +268 -0
  661. package/workflows/containers/child/move/index.js.map +1 -0
  662. package/workflows/containers/child/move/moveArtifacts.js +102 -0
  663. package/workflows/containers/child/move/moveArtifacts.js.map +1 -0
  664. package/workflows/containers/child/move/moveRotation.js +88 -0
  665. package/workflows/containers/child/move/moveRotation.js.map +1 -0
  666. package/workflows/containers/child/move/moveWraps.js +49 -0
  667. package/workflows/containers/child/move/moveWraps.js.map +1 -0
  668. package/workflows/containers/child/mutationSubmit.js +1 -1
  669. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  670. package/workflows/containers/child/recite.js +2 -2
  671. package/workflows/containers/child/recite.js.map +1 -1
  672. package/workflows/containers/child/rekey/carriedDescendantRekeys.js +126 -0
  673. package/workflows/containers/child/rekey/carriedDescendantRekeys.js.map +1 -0
  674. package/workflows/containers/child/rekey/index.d.ts +32 -0
  675. package/workflows/containers/child/rekey/index.js +227 -0
  676. package/workflows/containers/child/rekey/index.js.map +1 -0
  677. package/workflows/containers/child/rekey/keyringOverrideLineage.d.ts +22 -0
  678. package/workflows/containers/child/rekey/keyringOverrideLineage.js +39 -0
  679. package/workflows/containers/child/rekey/rekeyProjection.d.ts +46 -0
  680. package/workflows/containers/child/rekey/rekeyProjection.js +151 -0
  681. package/workflows/containers/child/rekey/rekeyProjection.js.map +1 -0
  682. package/workflows/containers/child/rekey/rekeyRemote.d.ts +24 -0
  683. package/workflows/containers/child/rekey/rekeyRemote.js +64 -0
  684. package/workflows/containers/child/rekey/rekeyRemote.js.map +1 -0
  685. package/workflows/containers/child/revoke.js +5 -5
  686. package/workflows/containers/child/revoke.js.map +1 -1
  687. package/workflows/containers/child/rotation/replacementPrincipalPolicyReferences.js +19 -0
  688. package/workflows/containers/child/rotation/replacementPrincipalPolicyReferences.js.map +1 -0
  689. package/workflows/containers/child/rotation/rotationContext.js +64 -0
  690. package/workflows/containers/child/rotation/rotationContext.js.map +1 -0
  691. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js +19 -0
  692. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js.map +1 -0
  693. package/workflows/containers/child/rotation/rotationWraps.js +85 -0
  694. package/workflows/containers/child/rotation/rotationWraps.js.map +1 -0
  695. package/workflows/containers/child/share/currentShareGrantMutation.js +82 -0
  696. package/workflows/containers/child/share/currentShareGrantMutation.js.map +1 -0
  697. package/workflows/containers/child/share/currentSharePrincipalPolicy.js +83 -0
  698. package/workflows/containers/child/share/currentSharePrincipalPolicy.js.map +1 -0
  699. package/workflows/containers/child/share/index.d.ts +65 -0
  700. package/workflows/containers/child/share/index.js +256 -0
  701. package/workflows/containers/child/share/index.js.map +1 -0
  702. package/workflows/containers/child/share/runtimeCurrentGroupShare.js +79 -0
  703. package/workflows/containers/child/share/runtimeCurrentGroupShare.js.map +1 -0
  704. package/workflows/containers/child/share/shareAncestorRepair.js +95 -0
  705. package/workflows/containers/child/share/shareAncestorRepair.js.map +1 -0
  706. package/workflows/containers/child/share/shareMaterialization.d.ts +25 -0
  707. package/workflows/containers/child/share/shareMaterialization.js +164 -0
  708. package/workflows/containers/child/share/shareMaterialization.js.map +1 -0
  709. package/workflows/containers/child/share/sharePlanCore.d.ts +82 -0
  710. package/workflows/containers/child/share/sharePlanCore.js +191 -0
  711. package/workflows/containers/child/share/sharePlanCore.js.map +1 -0
  712. package/workflows/containers/child/share/sharePrincipalPolicy.d.ts +51 -0
  713. package/workflows/containers/child/share/sharePrincipalPolicy.js +194 -0
  714. package/workflows/containers/child/share/sharePrincipalPolicy.js.map +1 -0
  715. package/workflows/containers/child/share/shareProjection.js.map +1 -0
  716. package/workflows/containers/index.d.ts +13 -13
  717. package/workflows/containers/index.js +12 -12
  718. package/workflows/containers/index.js.map +1 -1
  719. package/workflows/containers/writeRefusal.js +1 -1
  720. package/workflows/containers/writeRefusal.js.map +1 -1
  721. package/workflows/documents/create/createAdoption.js +1 -1
  722. package/workflows/documents/create/createResponse.js +2 -2
  723. package/workflows/documents/create/createResponse.js.map +1 -1
  724. package/workflows/documents/create/index.js +1 -1
  725. package/workflows/documents/documentMutationCommit.d.ts +1 -1
  726. package/workflows/documents/documentMutationPreparation.d.ts +1 -1
  727. package/workflows/documents/documentMutationPreparation.js +1 -1
  728. package/workflows/documents/documentMutationPreparation.js.map +1 -1
  729. package/workflows/documents/index.d.ts +5 -5
  730. package/workflows/documents/index.js +5 -5
  731. package/workflows/documents/index.js.map +1 -1
  732. package/workflows/documents/linkSet/index.js +2 -2
  733. package/workflows/documents/linkSet/index.js.map +1 -1
  734. package/workflows/documents/linkSet/linkSetAuthority.js +2 -2
  735. package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -1
  736. package/workflows/documents/linkSet/linkSetBlobRewraps.js +2 -2
  737. package/workflows/documents/linkSet/linkSetBlobRewraps.js.map +1 -1
  738. package/workflows/documents/linkSet/linkSetProjectionSeed.js +2 -2
  739. package/workflows/documents/linkSet/linkSetProjectionSeed.js.map +1 -1
  740. package/workflows/documents/linkSet/linkSetRemote.js +1 -1
  741. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
  742. package/workflows/documents/purge/index.js +2 -2
  743. package/workflows/documents/purge/index.js.map +1 -1
  744. package/workflows/documents/sync/index.js +2 -2
  745. package/workflows/documents/sync/index.js.map +1 -1
  746. package/workflows/documents/sync/initialSync.js +1 -1
  747. package/workflows/documents/sync/readOnlyProjectionFailure.js +1 -1
  748. package/workflows/documents/sync/readOnlyProjectionFailure.js.map +1 -1
  749. package/workflows/documents/sync/readOnlySync.d.ts +3 -3
  750. package/workflows/documents/sync/readOnlySync.js +1 -1
  751. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  752. package/workflows/documents/sync/reportDocumentSyncQuarantine.js.map +1 -1
  753. package/workflows/documents/sync/syncAttemptPlanning.js +2 -2
  754. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  755. package/workflows/documents/sync/syncAttemptState.d.ts +2 -2
  756. package/workflows/documents/sync/syncAttemptState.js.map +1 -1
  757. package/workflows/documents/sync/syncResponseResult.js +2 -2
  758. package/workflows/documents/sync/syncResponseResult.js.map +1 -1
  759. package/workflows/documents/syncFailures/index.js +1 -1
  760. package/workflows/documents/syncFailures/index.js.map +1 -1
  761. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
  762. package/workflows/documents/syncFailures/syncFailureClassification.js +1 -1
  763. package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -1
  764. package/workflows/documents/syncPlan/syncContentKeys.d.ts +1 -1
  765. package/workflows/documents/syncPlan/syncContentKeys.js +3 -3
  766. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
  767. package/workflows/documents/syncPlan/syncPlanMaterial.js +2 -2
  768. package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -1
  769. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +4 -4
  770. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  771. package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js +1 -1
  772. package/workflows/documents/syncRekeys/syncRecoveryRekey.d.ts +1 -1
  773. package/workflows/documents/syncRekeys/syncRecoveryRekey.js +1 -1
  774. package/workflows/organizations/currentOrganizationAuthority.js +2 -2
  775. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  776. package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
  777. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  778. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +1 -1
  779. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  780. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +1 -1
  781. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
  782. package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -3
  783. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  784. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  785. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  786. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js +1 -1
  787. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  788. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +2 -2
  789. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  790. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js +1 -1
  791. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js.map +1 -1
  792. package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
  793. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
  794. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  795. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  796. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -1
  797. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  798. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  799. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  800. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +1 -1
  801. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
  802. package/workflows/organizations/provisioning/organizationReplacementVerification.js +1 -1
  803. package/workflows/organizations/provisioning/organizationReplacementVerification.js.map +1 -1
  804. package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
  805. package/workflows/organizations/readModel/localReadModelDetails.js +1 -1
  806. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  807. package/workflows/organizations/rematerialization/precedingPrincipalRematerialization.js +1 -1
  808. package/workflows/organizations/rematerialization/precedingPrincipalRematerialization.js.map +1 -1
  809. package/workflows/organizations/rematerialization/principalContainerRematerialization.js +5 -5
  810. package/workflows/organizations/rematerialization/principalContainerRematerialization.js.map +1 -1
  811. package/workflows/organizations/rematerialization/principalContainerRematerializationPlanning.js +1 -1
  812. package/workflows/organizations/rematerialization/principalContainerRematerializationPlanning.js.map +1 -1
  813. package/workflows/organizations/rematerialization/principalContainerRematerializationTargets.js +1 -1
  814. package/workflows/organizations/rematerialization/principalContainerRematerializationTargets.js.map +1 -1
  815. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +1 -1
  816. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
  817. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.d.ts +1 -1
  818. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +1 -1
  819. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
  820. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
  821. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
  822. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +2 -2
  823. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
  824. package/workflows/principals/externalAdminPolicy.js +2 -2
  825. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  826. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js +2 -2
  827. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -1
  828. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js +1 -1
  829. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js.map +1 -1
  830. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +1 -1
  831. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
  832. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js +1 -1
  833. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js.map +1 -1
  834. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +3 -3
  835. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
  836. package/workflows/principals/policyCache/index.js +4 -4
  837. package/workflows/principals/policyCache/index.js.map +1 -1
  838. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +1 -1
  839. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  840. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +3 -3
  841. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  842. package/workflows/principals/policyRepair.js +1 -1
  843. package/workflows/principals/policyRepair.js.map +1 -1
  844. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -1
  845. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +2 -2
  846. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
  847. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +3 -3
  848. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
  849. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.d.ts +2 -2
  850. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.js.map +1 -1
  851. package/workflows/principals/publicHistory/publicProjectionPrincipal.js +1 -1
  852. package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -1
  853. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +1 -1
  854. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  855. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +1 -1
  856. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
  857. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +1 -1
  858. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
  859. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js +1 -1
  860. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js.map +1 -1
  861. package/workflows/registration/organizationProvisioningArtifacts.d.ts +1 -1
  862. package/workflows/registration/persistRegistrationBootstrap.d.ts +2 -2
  863. package/workflows/registration/persistRegistrationBootstrap.js +2 -2
  864. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  865. package/workflows/registration/provisioningAcknowledgement.js +1 -1
  866. package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
  867. package/workflows/registration/provisioningBootstrapBuilders.js +1 -1
  868. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -1
  869. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  870. package/workflows/sync/remoteReset.js +7 -7
  871. package/workflows/sync/remoteReset.js.map +1 -1
  872. package/workflows/sync/remoteResetAttachments.js +1 -1
  873. package/workflows/sync/remoteResetCursorScope.js +1 -1
  874. package/workflows/sync/remoteResetPlans.js +1 -1
  875. package/workflows/sync/remoteResetPrincipalScope.js +5 -5
  876. package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
  877. package/workflows/sync/remoteResetScope.js +1 -1
  878. package/data/documents/shared/containerKekCurrency.d.ts +0 -22
  879. package/data/documents/shared/containerKekEntryVerification.js +0 -15
  880. package/data/documents/shared/containerKekLogFetch.d.ts +0 -18
  881. package/data/documents/shared/containerKekLogFetch.js +0 -76
  882. package/data/documents/shared/containerKekPath.js +0 -265
  883. package/data/documents/shared/containerKekPath.js.map +0 -1
  884. package/data/documents/shared/containerKekPathHistory.d.ts +0 -61
  885. package/data/documents/shared/containerKekPathHistory.js +0 -223
  886. package/data/documents/shared/containerKekPathHistory.js.map +0 -1
  887. package/data/documents/shared/containerKekPathVerification.d.ts +0 -15
  888. package/data/documents/shared/containerKekPathVerification.js +0 -23
  889. package/data/documents/shared/containerKekPathVerification.js.map +0 -1
  890. package/data/documents/shared/containerKekWrapping.js +0 -61
  891. package/data/documents/shared/containerKekWrapping.js.map +0 -1
  892. package/data/documents/shared/documentSyncUpdateDecryption.js +0 -238
  893. package/data/documents/shared/documentSyncUpdateDecryption.js.map +0 -1
  894. package/data/documents/shared/documentSyncUpdateIsolation.d.ts +0 -55
  895. package/data/documents/shared/documentSyncUpdateIsolation.js +0 -298
  896. package/data/documents/shared/documentSyncUpdateIsolation.js.map +0 -1
  897. package/data/documents/shared/keyringLogWalk.d.ts +0 -45
  898. package/data/documents/shared/keyringLogWalk.js +0 -204
  899. package/data/documents/shared/keyringRebuild.d.ts +0 -60
  900. package/data/documents/shared/keyringRebuild.js +0 -242
  901. package/data/documents/shared/keyringRebuild.js.map +0 -1
  902. package/data/documents/shared/mutationAcknowledgement.js +0 -10
  903. package/data/documents/shared/mutationAcknowledgement.js.map +0 -1
  904. package/data/documents/shared/projection.d.ts +0 -25
  905. package/data/documents/shared/projection.js +0 -132
  906. package/data/documents/shared/projection.js.map +0 -1
  907. package/data/documents/shared/projectionContentKeys.d.ts +0 -90
  908. package/data/documents/shared/projectionContentKeys.js +0 -262
  909. package/data/documents/shared/projectionContentKeys.js.map +0 -1
  910. package/data/documents/shared/projectionTargets.d.ts +0 -38
  911. package/data/documents/shared/projectionTargets.js +0 -164
  912. package/data/documents/shared/projectionTargets.js.map +0 -1
  913. package/data/documents/shared/pullContinuation.js +0 -53
  914. package/data/documents/shared/syncPagination.d.ts +0 -20
  915. package/data/documents/shared/syncPagination.js +0 -109
  916. package/data/documents/shared/syncPagination.js.map +0 -1
  917. package/data/documents/shared/syncResponseAuthorization.js +0 -63
  918. package/data/documents/shared/syncResponseAuthorization.js.map +0 -1
  919. package/data/documents/shared/syncResponses.d.ts +0 -11
  920. package/data/documents/shared/syncResponses.js +0 -285
  921. package/data/documents/shared/syncResponses.js.map +0 -1
  922. package/data/documents/shared/syncSubmitFailure.d.ts +0 -9
  923. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js +0 -61
  924. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +0 -1
  925. package/data/keyingProjectionVerification/bundleVerification.js +0 -61
  926. package/data/keyingProjectionVerification/bundleVerification.js.map +0 -1
  927. package/data/keyingProjectionVerification/checkpointContext.d.ts +0 -45
  928. package/data/keyingProjectionVerification/checkpointContext.js +0 -120
  929. package/data/keyingProjectionVerification/checkpointContext.js.map +0 -1
  930. package/data/keyingProjectionVerification/containerAncestorCitations.js +0 -164
  931. package/data/keyingProjectionVerification/containerAncestorCitations.js.map +0 -1
  932. package/data/keyingProjectionVerification/containerCreateManifest.js +0 -28
  933. package/data/keyingProjectionVerification/containerDestinationVerification.js +0 -51
  934. package/data/keyingProjectionVerification/containerDestinationVerification.js.map +0 -1
  935. package/data/keyingProjectionVerification/containerManifestVerification.js +0 -285
  936. package/data/keyingProjectionVerification/containerManifestVerification.js.map +0 -1
  937. package/data/keyingProjectionVerification/containerPathVerification.js +0 -51
  938. package/data/keyingProjectionVerification/containerPathVerification.js.map +0 -1
  939. package/data/keyingProjectionVerification/containerProjectionVerification.d.ts +0 -25
  940. package/data/keyingProjectionVerification/containerProjectionVerification.js +0 -254
  941. package/data/keyingProjectionVerification/containerProjectionVerification.js.map +0 -1
  942. package/data/keyingProjectionVerification/documentDependencyPaths.d.ts +0 -17
  943. package/data/keyingProjectionVerification/documentDependencyPaths.js +0 -70
  944. package/data/keyingProjectionVerification/documentDependencyPaths.js.map +0 -1
  945. package/data/keyingProjectionVerification/documentManifestPolicies.js +0 -32
  946. package/data/keyingProjectionVerification/documentManifestPolicies.js.map +0 -1
  947. package/data/keyingProjectionVerification/documentManifestPredecessor.js +0 -12
  948. package/data/keyingProjectionVerification/documentManifestVerification.js +0 -135
  949. package/data/keyingProjectionVerification/documentManifestVerification.js.map +0 -1
  950. package/data/keyingProjectionVerification/documentProjectionVerification.d.ts +0 -24
  951. package/data/keyingProjectionVerification/documentProjectionVerification.js +0 -172
  952. package/data/keyingProjectionVerification/documentProjectionVerification.js.map +0 -1
  953. package/data/keyingProjectionVerification/documentPurgeCheckpointCurrency.js +0 -100
  954. package/data/keyingProjectionVerification/documentPurgeCheckpointCurrency.js.map +0 -1
  955. package/data/keyingProjectionVerification/documentPurgeCheckpointEnforcement.js +0 -8
  956. package/data/keyingProjectionVerification/documentPurgeCheckpointEnforcement.js.map +0 -1
  957. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js +0 -177
  958. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js.map +0 -1
  959. package/data/keyingProjectionVerification/documentPurgePolicyCheckpoints.js +0 -17
  960. package/data/keyingProjectionVerification/documentPurgePolicyCheckpoints.js.map +0 -1
  961. package/data/keyingProjectionVerification/documentPurgePolicyCurrency.js +0 -55
  962. package/data/keyingProjectionVerification/documentPurgePolicyCurrency.js.map +0 -1
  963. package/data/keyingProjectionVerification/documentPurgePrincipalEvidence.js +0 -116
  964. package/data/keyingProjectionVerification/documentPurgePrincipalEvidence.js.map +0 -1
  965. package/data/keyingProjectionVerification/documentPurgeProofVerification.d.ts +0 -34
  966. package/data/keyingProjectionVerification/documentPurgeProofVerification.js +0 -208
  967. package/data/keyingProjectionVerification/documentPurgeProofVerification.js.map +0 -1
  968. package/data/keyingProjectionVerification/manifestCheckpointVerification.js +0 -64
  969. package/data/keyingProjectionVerification/manifestCheckpointVerification.js.map +0 -1
  970. package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js +0 -45
  971. package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js.map +0 -1
  972. package/data/keyingProjectionVerification/organizationFounderBinding.js +0 -41
  973. package/data/keyingProjectionVerification/organizationFounderBinding.js.map +0 -1
  974. package/data/keyingProjectionVerification/principalPolicyCache.js +0 -76
  975. package/data/keyingProjectionVerification/principalPolicyCache.js.map +0 -1
  976. package/data/keyingProjectionVerification/principalPolicyVerification.js +0 -252
  977. package/data/keyingProjectionVerification/principalPolicyVerification.js.map +0 -1
  978. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js +0 -63
  979. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js.map +0 -1
  980. package/data/keyingProjectionVerification/projectionPolicyEvidence.js +0 -23
  981. package/data/keyingProjectionVerification/projectionPolicyEvidence.js.map +0 -1
  982. package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js +0 -72
  983. package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js.map +0 -1
  984. package/data/persistence/documentPurgeCheckpointPersistence.d.ts +0 -10
  985. package/data/persistence/documentPurgeCheckpointPersistence.js +0 -43
  986. package/data/persistence/documentPurgeCheckpointPersistence.js.map +0 -1
  987. package/data/persistence/keyingCheckpointAdvancePersistence.js +0 -222
  988. package/data/persistence/keyingCheckpointAdvancePersistence.js.map +0 -1
  989. package/data/persistence/keyingCheckpointEvidence.js +0 -32
  990. package/data/persistence/keyingCheckpointPersistence.js +0 -133
  991. package/data/persistence/keyingCheckpointPersistence.js.map +0 -1
  992. package/data/persistence/locallyAcknowledgedCheckpointPersistence.d.ts +0 -53
  993. package/data/persistence/locallyAcknowledgedCheckpointPersistence.js +0 -167
  994. package/data/persistence/locallyAcknowledgedCheckpointPersistence.js.map +0 -1
  995. package/data/persistence/organizationReplacementCheckpointPersistence.js +0 -72
  996. package/data/persistence/organizationReplacementCheckpointPersistence.js.map +0 -1
  997. package/data/persistence/principalAuthorizationCheckpoints.js +0 -29
  998. package/data/persistence/principalAuthorizationCheckpoints.js.map +0 -1
  999. package/data/persistence/principalGrantRetirementPersistence.d.ts +0 -9
  1000. package/data/persistence/principalGrantRetirementPersistence.js +0 -43
  1001. package/data/persistence/principalGrantRetirementPersistence.js.map +0 -1
  1002. package/data/persistence/principalHistoryEvidencePersistence.d.ts +0 -32
  1003. package/data/persistence/principalHistoryEvidencePersistence.js +0 -92
  1004. package/data/persistence/principalHistoryEvidencePersistence.js.map +0 -1
  1005. package/data/persistence/principalHistoryIncompleteRetention.js +0 -26
  1006. package/data/persistence/principalHistoryIncompleteRetention.js.map +0 -1
  1007. package/data/persistence/principalHistoryNodeRetention.js +0 -201
  1008. package/data/persistence/principalHistoryNodeRetention.js.map +0 -1
  1009. package/data/persistence/principalHistoryPrefixPersistence.d.ts +0 -29
  1010. package/data/persistence/principalHistoryPrefixPersistence.js +0 -102
  1011. package/data/persistence/principalHistoryPrefixPersistence.js.map +0 -1
  1012. package/data/persistence/principalHistoryRootOwnership.js +0 -71
  1013. package/data/persistence/principalHistoryRootOwnership.js.map +0 -1
  1014. package/data/persistence/principalHistoryStagePersistence.d.ts +0 -15
  1015. package/data/persistence/principalHistoryStagePersistence.js +0 -96
  1016. package/data/persistence/principalHistoryStagePersistence.js.map +0 -1
  1017. package/data/persistence/principalHistoryStageRetention.js +0 -45
  1018. package/data/persistence/principalHistoryStageRetention.js.map +0 -1
  1019. package/data/persistence/principalHistoryUnpublishedRetention.js +0 -64
  1020. package/data/persistence/principalHistoryUnpublishedRetention.js.map +0 -1
  1021. package/data/persistence/principalKeyEnvelopeArchivePersistence.js +0 -63
  1022. package/data/persistence/principalKeyEnvelopeArchivePersistence.js.map +0 -1
  1023. package/data/persistence/principalKeyEnvelopeCandidates.js +0 -87
  1024. package/data/persistence/principalKeyEnvelopeCandidates.js.map +0 -1
  1025. package/data/persistence/principalPolicyBundleIntegrity.js +0 -49
  1026. package/data/persistence/principalPolicyBundleIntegrity.js.map +0 -1
  1027. package/data/persistence/principalPolicyCheckpointSelection.js +0 -26
  1028. package/data/persistence/principalPolicyCheckpointSelection.js.map +0 -1
  1029. package/data/persistence/principalPolicyOrganizationPersistence.js +0 -42
  1030. package/data/persistence/principalPolicyOrganizationPersistence.js.map +0 -1
  1031. package/data/persistence/principalPolicyPersistence.js +0 -279
  1032. package/data/persistence/principalPolicyPersistence.js.map +0 -1
  1033. package/data/persistence/principalPolicyReferenceCheckpoint.js +0 -27
  1034. package/data/persistence/principalPolicyReferenceCheckpoint.js.map +0 -1
  1035. package/data/persistence/principalPolicyReferenceIndexPersistence.js +0 -115
  1036. package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +0 -1
  1037. package/data/persistence/principalPolicyReferencePersistence.js +0 -215
  1038. package/data/persistence/principalPolicyReferencePersistence.js.map +0 -1
  1039. package/data/persistence/verifiedPrincipalPolicyBundle.js +0 -33
  1040. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +0 -1
  1041. package/data/persistence/verifiedPrincipalPolicyCurrent.js +0 -56
  1042. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +0 -1
  1043. package/data/persistence/verifiedPrincipalPolicyRetentionPersistence.js +0 -18
  1044. package/data/persistence/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
  1045. package/data/sqlite/containerSchema.d.ts +0 -1193
  1046. package/data/sqlite/containerSchema.js +0 -103
  1047. package/data/sqlite/containerSchema.js.map +0 -1
  1048. package/data/sqlite/documentHistoryPersistence.d.ts +0 -86
  1049. package/data/sqlite/documentHistoryPersistence.js +0 -304
  1050. package/data/sqlite/documentHistoryPersistence.js.map +0 -1
  1051. package/data/sqlite/documentOrphanBlobReclaims.js +0 -6
  1052. package/data/sqlite/documentOrphanBlobReclaims.js.map +0 -1
  1053. package/data/sqlite/documentPendingUpdatePersistence.d.ts +0 -103
  1054. package/data/sqlite/documentPendingUpdatePersistence.js +0 -243
  1055. package/data/sqlite/documentPendingUpdatePersistence.js.map +0 -1
  1056. package/data/sqlite/documentPersistence.d.ts +0 -22
  1057. package/data/sqlite/documentPersistence.js +0 -35
  1058. package/data/sqlite/documentPersistence.js.map +0 -1
  1059. package/data/sqlite/documentPersistenceTypes.d.ts +0 -79
  1060. package/data/sqlite/documentPersistenceTypes.js.map +0 -1
  1061. package/data/sqlite/documentRecordPersistence.d.ts +0 -275
  1062. package/data/sqlite/documentRecordPersistence.js +0 -103
  1063. package/data/sqlite/documentRecordPersistence.js.map +0 -1
  1064. package/data/sqlite/documentSyncFailurePersistence.d.ts +0 -39
  1065. package/data/sqlite/documentSyncFailurePersistence.js +0 -81
  1066. package/data/sqlite/documentSyncFailurePersistence.js.map +0 -1
  1067. package/data/sqlite/organizationDataUsageSchema.js +0 -34
  1068. package/data/sqlite/organizationDataUsageSchema.js.map +0 -1
  1069. package/data/sqlite/organizationProvisioningAttemptSchema.js +0 -23
  1070. package/data/sqlite/organizationProvisioningAttemptSchema.js.map +0 -1
  1071. package/data/sqlite/organizationReadModelTableRegistry.d.ts +0 -1332
  1072. package/data/sqlite/organizationReadModelTableRegistry.js +0 -31
  1073. package/data/sqlite/organizationReadModelTableRegistry.js.map +0 -1
  1074. package/data/sqlite/principalHistoryEvidenceSchema.d.ts +0 -308
  1075. package/data/sqlite/principalHistoryEvidenceSchema.js +0 -48
  1076. package/data/sqlite/principalHistoryEvidenceSchema.js.map +0 -1
  1077. package/data/sqlite/principalHistoryNodeRetentionSchema.js +0 -30
  1078. package/data/sqlite/principalHistoryNodeRetentionSchema.js.map +0 -1
  1079. package/data/sqlite/principalHistoryRetentionSchema.js +0 -25
  1080. package/data/sqlite/principalHistoryRetentionSchema.js.map +0 -1
  1081. package/data/sqlite/principalHistoryStageSchema.d.ts +0 -161
  1082. package/data/sqlite/principalHistoryStageSchema.js +0 -34
  1083. package/data/sqlite/principalHistoryStageSchema.js.map +0 -1
  1084. package/data/sqlite/principalMutationJournalSchema.d.ts +0 -85
  1085. package/data/sqlite/principalMutationJournalSchema.js +0 -13
  1086. package/data/sqlite/principalMutationJournalSchema.js.map +0 -1
  1087. package/data/sqlite/principalPolicySchema.js +0 -72
  1088. package/data/sqlite/principalPolicySchema.js.map +0 -1
  1089. package/data/sqlite/schema.d.ts +0 -8055
  1090. package/data/sqlite/schema.js +0 -525
  1091. package/data/sqlite/schema.js.map +0 -1
  1092. package/data/sqlite/securityIncidentSchema.d.ts +0 -224
  1093. package/data/sqlite/securityIncidentSchema.js +0 -28
  1094. package/data/sqlite/securityIncidentSchema.js.map +0 -1
  1095. package/data/sqlite/verifiedManifestBundleSchema.d.ts +0 -174
  1096. package/data/sqlite/verifiedManifestBundleSchema.js +0 -36
  1097. package/data/sqlite/verifiedManifestBundleSchema.js.map +0 -1
  1098. package/stores/container-contents/backgroundHydration.js +0 -32
  1099. package/stores/container-contents/backgroundHydration.js.map +0 -1
  1100. package/stores/container-contents/containerPurgeCore.js +0 -98
  1101. package/stores/container-contents/containerPurgeCore.js.map +0 -1
  1102. package/stores/container-contents/containerStateMap.js.map +0 -1
  1103. package/stores/container-contents/containerStatePersistence.js +0 -57
  1104. package/stores/container-contents/containerStatePersistence.js.map +0 -1
  1105. package/stores/container-contents/documentRecovery.js +0 -114
  1106. package/stores/container-contents/documentRecovery.js.map +0 -1
  1107. package/stores/container-contents/documentRotation.js +0 -13
  1108. package/stores/container-contents/documentRotation.js.map +0 -1
  1109. package/stores/container-contents/documentWork.js +0 -29
  1110. package/stores/container-contents/documentWork.js.map +0 -1
  1111. package/stores/container-contents/emptyTrashOperation.js.map +0 -1
  1112. package/stores/container-contents/existingSystemContainer.js +0 -58
  1113. package/stores/container-contents/existingSystemContainer.js.map +0 -1
  1114. package/stores/container-contents/groupRewrapOperation.js +0 -52
  1115. package/stores/container-contents/groupRewrapOperation.js.map +0 -1
  1116. package/stores/container-contents/metadataSyncSignal.js +0 -37
  1117. package/stores/container-contents/metadataSyncSignal.js.map +0 -1
  1118. package/stores/container-contents/missingContainerState.js +0 -10
  1119. package/stores/container-contents/missingContainerState.js.map +0 -1
  1120. package/stores/container-contents/missingSyncedContainerState.js.map +0 -1
  1121. package/stores/container-contents/operations.js +0 -301
  1122. package/stores/container-contents/operations.js.map +0 -1
  1123. package/stores/container-contents/organizationMetadataSystemContainer.js +0 -44
  1124. package/stores/container-contents/organizationMetadataSystemContainer.js.map +0 -1
  1125. package/stores/container-contents/purgeContainerOperation.js.map +0 -1
  1126. package/stores/container-contents/reconcilableContainer.d.ts +0 -48
  1127. package/stores/container-contents/reconcilableContainer.js.map +0 -1
  1128. package/stores/container-contents/remoteBackedContainerState.js.map +0 -1
  1129. package/stores/container-contents/remoteContainerIngestion.js +0 -59
  1130. package/stores/container-contents/remoteContainerIngestion.js.map +0 -1
  1131. package/stores/container-contents/remoteEventProjectionInvalidation.js +0 -36
  1132. package/stores/container-contents/remoteEventProjectionInvalidation.js.map +0 -1
  1133. package/stores/container-contents/remoteEventSync.js +0 -38
  1134. package/stores/container-contents/remoteEventSync.js.map +0 -1
  1135. package/stores/container-contents/remoteHydrationRequest.js +0 -245
  1136. package/stores/container-contents/remoteHydrationRequest.js.map +0 -1
  1137. package/stores/container-contents/remoteWriteGuards.js +0 -54
  1138. package/stores/container-contents/remoteWriteGuards.js.map +0 -1
  1139. package/stores/container-contents/remoteWriteQueue.js +0 -51
  1140. package/stores/container-contents/remoteWriteQueue.js.map +0 -1
  1141. package/stores/container-contents/reportShareFailure.js +0 -44
  1142. package/stores/container-contents/reportShareFailure.js.map +0 -1
  1143. package/stores/container-contents/setContainerIconOperation.js +0 -47
  1144. package/stores/container-contents/setContainerIconOperation.js.map +0 -1
  1145. package/stores/container-contents/shareOperations.js +0 -90
  1146. package/stores/container-contents/shareOperations.js.map +0 -1
  1147. package/stores/container-contents/startupHydration.js +0 -110
  1148. package/stores/container-contents/startupHydration.js.map +0 -1
  1149. package/stores/container-contents/syncAgent.d.ts +0 -8
  1150. package/stores/container-contents/syncAgent.js +0 -241
  1151. package/stores/container-contents/syncAgent.js.map +0 -1
  1152. package/stores/container-contents/syncAgentTypes.d.ts +0 -81
  1153. package/stores/container-contents/syncAgentTypes.js.map +0 -1
  1154. package/stores/container-contents/syncLaneIteration.js +0 -237
  1155. package/stores/container-contents/syncLaneIteration.js.map +0 -1
  1156. package/stores/container-contents/systemContainerHydration.js +0 -30
  1157. package/stores/container-contents/systemContainerHydration.js.map +0 -1
  1158. package/stores/container-contents/systemContainerIcon.js +0 -42
  1159. package/stores/container-contents/systemContainerIcon.js.map +0 -1
  1160. package/stores/container-contents/systemContainerLookup.js.map +0 -1
  1161. package/stores/container-contents/systemContainerPostCreate.js +0 -109
  1162. package/stores/container-contents/systemContainerPostCreate.js.map +0 -1
  1163. package/stores/container-contents/systemContainerPromotion.js +0 -49
  1164. package/stores/container-contents/systemContainerPromotion.js.map +0 -1
  1165. package/stores/container-contents/writeGeneration.js.map +0 -1
  1166. package/stores/documents/documentStore/attachmentDetachState.js +0 -54
  1167. package/stores/documents/documentStore/attachmentDetachState.js.map +0 -1
  1168. package/stores/documents/documentStore/attachmentHydration.js +0 -90
  1169. package/stores/documents/documentStore/attachmentHydration.js.map +0 -1
  1170. package/stores/documents/documentStore/attachmentHydrationCommit.js +0 -53
  1171. package/stores/documents/documentStore/attachmentHydrationCommit.js.map +0 -1
  1172. package/stores/documents/documentStore/attachmentIntents.js +0 -39
  1173. package/stores/documents/documentStore/attachmentIntents.js.map +0 -1
  1174. package/stores/documents/documentStore/attachmentMutationPersistence.js +0 -37
  1175. package/stores/documents/documentStore/attachmentMutationPersistence.js.map +0 -1
  1176. package/stores/documents/documentStore/attachmentPersistFollowup.js.map +0 -1
  1177. package/stores/documents/documentStore/attachmentPersistence.js +0 -106
  1178. package/stores/documents/documentStore/attachmentPersistence.js.map +0 -1
  1179. package/stores/documents/documentStore/attachmentRemoval.js +0 -136
  1180. package/stores/documents/documentStore/attachmentRemoval.js.map +0 -1
  1181. package/stores/documents/documentStore/attachmentSnapshot.js.map +0 -1
  1182. package/stores/documents/documentStore/attachmentSourceUpload.js +0 -39
  1183. package/stores/documents/documentStore/attachmentSourceUpload.js.map +0 -1
  1184. package/stores/documents/documentStore/attachmentStaging.js +0 -84
  1185. package/stores/documents/documentStore/attachmentStaging.js.map +0 -1
  1186. package/stores/documents/documentStore/attachmentUploadAttempt.js +0 -97
  1187. package/stores/documents/documentStore/attachmentUploadAttempt.js.map +0 -1
  1188. package/stores/documents/documentStore/attachmentUploadLane.js +0 -49
  1189. package/stores/documents/documentStore/attachmentUploadLane.js.map +0 -1
  1190. package/stores/documents/documentStore/attachmentUploadResume.js +0 -95
  1191. package/stores/documents/documentStore/attachmentUploadResume.js.map +0 -1
  1192. package/stores/documents/documentStore/attachmentWriteGeneration.js +0 -32
  1193. package/stores/documents/documentStore/attachmentWriteGeneration.js.map +0 -1
  1194. package/stores/documents/documentStore/attachments.js +0 -241
  1195. package/stores/documents/documentStore/attachments.js.map +0 -1
  1196. package/stores/documents/documentStore/deferredInitialUpdate.js +0 -116
  1197. package/stores/documents/documentStore/deferredInitialUpdate.js.map +0 -1
  1198. package/stores/documents/documentStore/documentHistoryCompaction.js +0 -67
  1199. package/stores/documents/documentStore/documentHistoryCompaction.js.map +0 -1
  1200. package/stores/documents/documentStore/durableDocumentReload.js +0 -79
  1201. package/stores/documents/documentStore/durableDocumentReload.js.map +0 -1
  1202. package/stores/documents/documentStore/historyRebuild.js +0 -75
  1203. package/stores/documents/documentStore/historyRebuild.js.map +0 -1
  1204. package/stores/documents/documentStore/initialization.js +0 -330
  1205. package/stores/documents/documentStore/initialization.js.map +0 -1
  1206. package/stores/documents/documentStore/initializationAttachments.js +0 -9
  1207. package/stores/documents/documentStore/initializationAttachments.js.map +0 -1
  1208. package/stores/documents/documentStore/initializationHistory.js +0 -33
  1209. package/stores/documents/documentStore/initializationHistory.js.map +0 -1
  1210. package/stores/documents/documentStore/initializationRecovery.js +0 -107
  1211. package/stores/documents/documentStore/initializationRecovery.js.map +0 -1
  1212. package/stores/documents/documentStore/pullContinuationInvalidation.js +0 -61
  1213. package/stores/documents/documentStore/pullContinuationInvalidation.js.map +0 -1
  1214. package/stores/documents/documentStore/remoteRevalidationTelemetry.js +0 -15
  1215. package/stores/documents/documentStore/remoteRevalidationTelemetry.js.map +0 -1
  1216. package/stores/documents/documentStore/remoteWork.js.map +0 -1
  1217. package/stores/documents/documentStore/rotation.js +0 -307
  1218. package/stores/documents/documentStore/rotation.js.map +0 -1
  1219. package/stores/documents/documentStore/rotationProvenance.js +0 -52
  1220. package/stores/documents/documentStore/rotationProvenance.js.map +0 -1
  1221. package/stores/documents/documentStore/rotationSettlement.js +0 -222
  1222. package/stores/documents/documentStore/rotationSettlement.js.map +0 -1
  1223. package/stores/documents/documentStore/sync.js +0 -299
  1224. package/stores/documents/documentStore/sync.js.map +0 -1
  1225. package/stores/documents/documentStore/syncAcceptedUpdateIds.js.map +0 -1
  1226. package/stores/documents/documentStore/syncAttachmentSettlement.js +0 -72
  1227. package/stores/documents/documentStore/syncAttachmentSettlement.js.map +0 -1
  1228. package/stores/documents/documentStore/syncAttachments.js +0 -323
  1229. package/stores/documents/documentStore/syncAttachments.js.map +0 -1
  1230. package/stores/documents/documentStore/syncDetachedAttachments.js +0 -129
  1231. package/stores/documents/documentStore/syncDetachedAttachments.js.map +0 -1
  1232. package/stores/documents/documentStore/syncFinalize.js +0 -204
  1233. package/stores/documents/documentStore/syncFinalize.js.map +0 -1
  1234. package/stores/documents/documentStore/syncGeneration.js.map +0 -1
  1235. package/stores/documents/documentStore/syncOutgoingCoverage.js +0 -96
  1236. package/stores/documents/documentStore/syncOutgoingCoverage.js.map +0 -1
  1237. package/stores/documents/documentStore/syncRemoteSignals.js +0 -67
  1238. package/stores/documents/documentStore/syncRemoteSignals.js.map +0 -1
  1239. package/stores/documents/documentStore/syncRequest.js +0 -157
  1240. package/stores/documents/documentStore/syncRequest.js.map +0 -1
  1241. package/stores/documents/documentStore/syncShared.js +0 -211
  1242. package/stores/documents/documentStore/syncShared.js.map +0 -1
  1243. package/stores/documents/documentStore/syncUpdateImport.js +0 -62
  1244. package/stores/documents/documentStore/syncUpdateImport.js.map +0 -1
  1245. package/stores/documents/documentStore/versionCoverage.js +0 -45
  1246. package/stores/documents/documentStore.d.ts +0 -8
  1247. package/stores/documents/documentStore.js +0 -215
  1248. package/stores/documents/documentStore.js.map +0 -1
  1249. package/workflows/container-contents/container-state/createAdoption.js +0 -193
  1250. package/workflows/container-contents/container-state/createAdoption.js.map +0 -1
  1251. package/workflows/container-contents/container-state/createChild.js +0 -217
  1252. package/workflows/container-contents/container-state/createChild.js.map +0 -1
  1253. package/workflows/container-contents/container-state/createIntentDepth.js +0 -36
  1254. package/workflows/container-contents/container-state/createIntentDepth.js.map +0 -1
  1255. package/workflows/container-contents/container-state/createIntentSettlement.js.map +0 -1
  1256. package/workflows/container-contents/container-state/createIntentSync.js +0 -354
  1257. package/workflows/container-contents/container-state/createIntentSync.js.map +0 -1
  1258. package/workflows/container-contents/container-state/createTerminalFailure.js +0 -19
  1259. package/workflows/container-contents/container-state/createTerminalFailure.js.map +0 -1
  1260. package/workflows/container-contents/container-state/createWithMetadata.js +0 -270
  1261. package/workflows/container-contents/container-state/createWithMetadata.js.map +0 -1
  1262. package/workflows/container-contents/container-state/createWithMetadataPlan.js +0 -68
  1263. package/workflows/container-contents/container-state/createWithMetadataPlan.js.map +0 -1
  1264. package/workflows/container-contents/container-state/groupGrantVerification.js +0 -71
  1265. package/workflows/container-contents/container-state/groupGrantVerification.js.map +0 -1
  1266. package/workflows/container-contents/container-state/groupShareEpoch.js +0 -16
  1267. package/workflows/container-contents/container-state/groupShareEpoch.js.map +0 -1
  1268. package/workflows/container-contents/container-state/localPurgeScope.js +0 -49
  1269. package/workflows/container-contents/container-state/localPurgeScope.js.map +0 -1
  1270. package/workflows/container-contents/container-state/purgeTree.js +0 -298
  1271. package/workflows/container-contents/container-state/purgeTree.js.map +0 -1
  1272. package/workflows/container-contents/container-state/purgeTreeCollection.js.map +0 -1
  1273. package/workflows/container-contents/container-state/purgeTreeContainerDeletion.js +0 -75
  1274. package/workflows/container-contents/container-state/purgeTreeContainerDeletion.js.map +0 -1
  1275. package/workflows/container-contents/container-state/purgeTreeScope.js +0 -175
  1276. package/workflows/container-contents/container-state/purgeTreeScope.js.map +0 -1
  1277. package/workflows/container-contents/container-state/readLocalPurgeScope.js +0 -18
  1278. package/workflows/container-contents/container-state/readLocalPurgeScope.js.map +0 -1
  1279. package/workflows/container-contents/container-state/share.js +0 -283
  1280. package/workflows/container-contents/container-state/share.js.map +0 -1
  1281. package/workflows/container-contents/container-state/sharePersistence.js +0 -136
  1282. package/workflows/container-contents/container-state/sharePersistence.js.map +0 -1
  1283. package/workflows/container-contents/remoteHydration/childIndex.js.map +0 -1
  1284. package/workflows/container-contents/remoteHydration/containerStateFingerprint.js.map +0 -1
  1285. package/workflows/container-contents/remoteHydration/destinationPrefetch.js.map +0 -1
  1286. package/workflows/container-contents/remoteHydration/destinationRoleCache.js.map +0 -1
  1287. package/workflows/container-contents/remoteHydration/destinationRootReload.js +0 -10
  1288. package/workflows/container-contents/remoteHydration/destinationRootReload.js.map +0 -1
  1289. package/workflows/container-contents/remoteHydration/insertRemoteContainer.js +0 -135
  1290. package/workflows/container-contents/remoteHydration/insertRemoteContainer.js.map +0 -1
  1291. package/workflows/container-contents/remoteHydration/laneFetchMarkers.js +0 -21
  1292. package/workflows/container-contents/remoteHydration/laneFetchMarkers.js.map +0 -1
  1293. package/workflows/container-contents/remoteHydration/parentLaneFetch.js +0 -61
  1294. package/workflows/container-contents/remoteHydration/parentLaneFetch.js.map +0 -1
  1295. package/workflows/container-contents/remoteHydration/parentLaneQueue.js.map +0 -1
  1296. package/workflows/container-contents/remoteHydration/remoteContainerPageHydration.js +0 -244
  1297. package/workflows/container-contents/remoteHydration/remoteContainerPageHydration.js.map +0 -1
  1298. package/workflows/container-contents/remoteHydration/remoteContainerState.js +0 -263
  1299. package/workflows/container-contents/remoteHydration/remoteContainerState.js.map +0 -1
  1300. package/workflows/container-contents/remoteHydration/remoteContainerTimestamps.js.map +0 -1
  1301. package/workflows/container-contents/remoteHydration/replacementBinding.js +0 -75
  1302. package/workflows/container-contents/remoteHydration/replacementBinding.js.map +0 -1
  1303. package/workflows/container-contents/remoteHydration/verifiedDestination.js +0 -296
  1304. package/workflows/container-contents/remoteHydration/verifiedDestination.js.map +0 -1
  1305. package/workflows/containers/child/carriedDescendantRekeys.js +0 -126
  1306. package/workflows/containers/child/carriedDescendantRekeys.js.map +0 -1
  1307. package/workflows/containers/child/create.d.ts +0 -24
  1308. package/workflows/containers/child/create.js +0 -335
  1309. package/workflows/containers/child/create.js.map +0 -1
  1310. package/workflows/containers/child/createProjection.d.ts +0 -6
  1311. package/workflows/containers/child/createProjection.js +0 -43
  1312. package/workflows/containers/child/createProjection.js.map +0 -1
  1313. package/workflows/containers/child/createSubmission.d.ts +0 -56
  1314. package/workflows/containers/child/createSubmission.js +0 -43
  1315. package/workflows/containers/child/createSubmission.js.map +0 -1
  1316. package/workflows/containers/child/currentShareGrantMutation.js +0 -82
  1317. package/workflows/containers/child/currentShareGrantMutation.js.map +0 -1
  1318. package/workflows/containers/child/currentSharePrincipalPolicy.js +0 -83
  1319. package/workflows/containers/child/currentSharePrincipalPolicy.js.map +0 -1
  1320. package/workflows/containers/child/keyringOverrideLineage.d.ts +0 -22
  1321. package/workflows/containers/child/keyringOverrideLineage.js +0 -39
  1322. package/workflows/containers/child/move.d.ts +0 -23
  1323. package/workflows/containers/child/move.js +0 -268
  1324. package/workflows/containers/child/move.js.map +0 -1
  1325. package/workflows/containers/child/moveArtifacts.js +0 -102
  1326. package/workflows/containers/child/moveArtifacts.js.map +0 -1
  1327. package/workflows/containers/child/moveRotation.js +0 -88
  1328. package/workflows/containers/child/moveRotation.js.map +0 -1
  1329. package/workflows/containers/child/moveWraps.js +0 -49
  1330. package/workflows/containers/child/moveWraps.js.map +0 -1
  1331. package/workflows/containers/child/rekey.d.ts +0 -32
  1332. package/workflows/containers/child/rekey.js +0 -227
  1333. package/workflows/containers/child/rekey.js.map +0 -1
  1334. package/workflows/containers/child/rekeyProjection.d.ts +0 -46
  1335. package/workflows/containers/child/rekeyProjection.js +0 -151
  1336. package/workflows/containers/child/rekeyProjection.js.map +0 -1
  1337. package/workflows/containers/child/rekeyRemote.d.ts +0 -24
  1338. package/workflows/containers/child/rekeyRemote.js +0 -64
  1339. package/workflows/containers/child/rekeyRemote.js.map +0 -1
  1340. package/workflows/containers/child/replacementPrincipalPolicyReferences.js +0 -19
  1341. package/workflows/containers/child/replacementPrincipalPolicyReferences.js.map +0 -1
  1342. package/workflows/containers/child/rotationContext.js +0 -64
  1343. package/workflows/containers/child/rotationContext.js.map +0 -1
  1344. package/workflows/containers/child/rotationPrincipalPolicies.js +0 -19
  1345. package/workflows/containers/child/rotationPrincipalPolicies.js.map +0 -1
  1346. package/workflows/containers/child/rotationWraps.js +0 -85
  1347. package/workflows/containers/child/rotationWraps.js.map +0 -1
  1348. package/workflows/containers/child/runtimeCurrentGroupShare.js +0 -79
  1349. package/workflows/containers/child/runtimeCurrentGroupShare.js.map +0 -1
  1350. package/workflows/containers/child/share.d.ts +0 -65
  1351. package/workflows/containers/child/share.js +0 -256
  1352. package/workflows/containers/child/share.js.map +0 -1
  1353. package/workflows/containers/child/shareAncestorRepair.js +0 -95
  1354. package/workflows/containers/child/shareAncestorRepair.js.map +0 -1
  1355. package/workflows/containers/child/shareMaterialization.d.ts +0 -25
  1356. package/workflows/containers/child/shareMaterialization.js +0 -164
  1357. package/workflows/containers/child/shareMaterialization.js.map +0 -1
  1358. package/workflows/containers/child/sharePlanCore.d.ts +0 -82
  1359. package/workflows/containers/child/sharePlanCore.js +0 -191
  1360. package/workflows/containers/child/sharePlanCore.js.map +0 -1
  1361. package/workflows/containers/child/sharePrincipalPolicy.d.ts +0 -51
  1362. package/workflows/containers/child/sharePrincipalPolicy.js +0 -194
  1363. package/workflows/containers/child/sharePrincipalPolicy.js.map +0 -1
  1364. package/workflows/containers/child/shareProjection.js.map +0 -1
  1365. /package/data/documents/shared/{containerKekCurrency.js → containerKek/containerKekCurrency.js} +0 -0
  1366. /package/data/documents/shared/{containerKekCurrency.js.map → containerKek/containerKekCurrency.js.map} +0 -0
  1367. /package/data/documents/shared/{containerKekEntryVerification.js.map → containerKek/containerKekEntryVerification.js.map} +0 -0
  1368. /package/data/documents/shared/{containerKekLogFetch.js.map → containerKek/containerKekLogFetch.js.map} +0 -0
  1369. /package/data/documents/shared/{containerKekPath.d.ts → containerKek/containerKekPath.d.ts} +0 -0
  1370. /package/data/documents/shared/{keyringLogWalk.js.map → containerKek/keyringLogWalk.js.map} +0 -0
  1371. /package/data/documents/shared/{pullContinuation.d.ts → sync/pullContinuation.d.ts} +0 -0
  1372. /package/data/documents/shared/{pullContinuation.js.map → sync/pullContinuation.js.map} +0 -0
  1373. /package/data/documents/shared/{syncSubmitFailure.js → sync/syncSubmitFailure.js} +0 -0
  1374. /package/data/documents/shared/{syncSubmitFailure.js.map → sync/syncSubmitFailure.js.map} +0 -0
  1375. /package/data/keyingProjectionVerification/{containerCreateManifest.js.map → container/containerCreateManifest.js.map} +0 -0
  1376. /package/data/keyingProjectionVerification/{documentContainerProjections.js → document/documentContainerProjections.js} +0 -0
  1377. /package/data/keyingProjectionVerification/{documentContainerProjections.js.map → document/documentContainerProjections.js.map} +0 -0
  1378. /package/data/keyingProjectionVerification/{documentManifestPredecessor.js.map → document/documentManifestPredecessor.js.map} +0 -0
  1379. /package/data/persistence/{keyingCheckpointEvidence.js.map → keyingCheckpoints/keyingCheckpointEvidence.js.map} +0 -0
  1380. /package/data/persistence/{storedPrincipalPolicyBundle.js → principalPolicy/storedPrincipalPolicyBundle.js} +0 -0
  1381. /package/data/persistence/{storedPrincipalPolicyBundle.js.map → principalPolicy/storedPrincipalPolicyBundle.js.map} +0 -0
  1382. /package/data/sqlite/{documentPersistenceTypes.js → documentPersistence/documentPersistenceTypes.js} +0 -0
  1383. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.d.ts → schema/containerDocumentTombstoneHoldSchema.d.ts} +0 -0
  1384. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js → schema/containerDocumentTombstoneHoldSchema.js} +0 -0
  1385. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js.map → schema/containerDocumentTombstoneHoldSchema.js.map} +0 -0
  1386. /package/data/sqlite/{documentAttachmentSchema.d.ts → schema/documentAttachmentSchema.d.ts} +0 -0
  1387. /package/data/sqlite/{documentAttachmentSchema.js → schema/documentAttachmentSchema.js} +0 -0
  1388. /package/data/sqlite/{documentAttachmentSchema.js.map → schema/documentAttachmentSchema.js.map} +0 -0
  1389. /package/data/sqlite/{documentDiscoveryEvidenceSchema.js → schema/documentDiscoveryEvidenceSchema.js} +0 -0
  1390. /package/data/sqlite/{documentDiscoveryEvidenceSchema.js.map → schema/documentDiscoveryEvidenceSchema.js.map} +0 -0
  1391. /package/data/sqlite/{documentPlacementIntentSchema.js → schema/documentPlacementIntentSchema.js} +0 -0
  1392. /package/data/sqlite/{documentPlacementIntentSchema.js.map → schema/documentPlacementIntentSchema.js.map} +0 -0
  1393. /package/data/sqlite/{localIntentSchema.d.ts → schema/localIntentSchema.d.ts} +0 -0
  1394. /package/data/sqlite/{localIntentSchema.js → schema/localIntentSchema.js} +0 -0
  1395. /package/data/sqlite/{localIntentSchema.js.map → schema/localIntentSchema.js.map} +0 -0
  1396. /package/data/sqlite/{organizationFounderSchema.js → schema/organizationFounderSchema.js} +0 -0
  1397. /package/data/sqlite/{organizationFounderSchema.js.map → schema/organizationFounderSchema.js.map} +0 -0
  1398. /package/data/sqlite/{organizationReadModelSchema.js → schema/organizationReadModelSchema.js} +0 -0
  1399. /package/data/sqlite/{organizationReadModelSchema.js.map → schema/organizationReadModelSchema.js.map} +0 -0
  1400. /package/data/sqlite/{principalGrantRetirementSchema.js → schema/principalGrantRetirementSchema.js} +0 -0
  1401. /package/data/sqlite/{principalGrantRetirementSchema.js.map → schema/principalGrantRetirementSchema.js.map} +0 -0
  1402. /package/data/sqlite/{principalPolicySchema.d.ts → schema/principalPolicySchema.d.ts} +0 -0
  1403. /package/stores/container-contents/{containerStateMap.js → containerState/containerStateMap.js} +0 -0
  1404. /package/stores/container-contents/{missingSyncedContainerState.js → containerState/missingSyncedContainerState.js} +0 -0
  1405. /package/stores/container-contents/{reconcilableContainer.js → containerState/reconcilableContainer.js} +0 -0
  1406. /package/stores/container-contents/{remoteHydrationRefresh.js → hydration/remoteHydrationRefresh.js} +0 -0
  1407. /package/stores/container-contents/{remoteHydrationRefresh.js.map → hydration/remoteHydrationRefresh.js.map} +0 -0
  1408. /package/stores/container-contents/{emptyTrashOperation.js → operations/emptyTrashOperation.js} +0 -0
  1409. /package/stores/container-contents/{purgeContainerOperation.js → operations/purgeContainerOperation.js} +0 -0
  1410. /package/stores/container-contents/{remoteBackedContainerState.js → remoteEvents/remoteBackedContainerState.js} +0 -0
  1411. /package/stores/container-contents/{writeGeneration.js → remoteWrites/writeGeneration.js} +0 -0
  1412. /package/stores/container-contents/{syncAgentTypes.js → syncAgent/syncAgentTypes.js} +0 -0
  1413. /package/stores/container-contents/{systemContainerLookup.js → systemContainers/systemContainerLookup.js} +0 -0
  1414. /package/stores/documents/documentStore/{attachmentPersistFollowup.js → attachments/attachmentPersistFollowup.js} +0 -0
  1415. /package/stores/documents/documentStore/{attachmentSnapshot.js → attachments/attachmentSnapshot.js} +0 -0
  1416. /package/stores/documents/documentStore/{remoteWork.js → sync/remoteWork.js} +0 -0
  1417. /package/stores/documents/documentStore/{syncAcceptedUpdateIds.js → sync/syncAcceptedUpdateIds.js} +0 -0
  1418. /package/stores/documents/documentStore/{syncGeneration.js → sync/syncGeneration.js} +0 -0
  1419. /package/stores/documents/documentStore/{versionCoverage.js.map → sync/versionCoverage.js.map} +0 -0
  1420. /package/workflows/container-contents/container-state/{createIntentSettlement.js → create/createIntentSettlement.js} +0 -0
  1421. /package/workflows/container-contents/container-state/{purgeProgress.d.ts → purge/purgeProgress.d.ts} +0 -0
  1422. /package/workflows/container-contents/container-state/{purgeProgress.js → purge/purgeProgress.js} +0 -0
  1423. /package/workflows/container-contents/container-state/{purgeProgress.js.map → purge/purgeProgress.js.map} +0 -0
  1424. /package/workflows/container-contents/container-state/{purgeTreeCollection.js → purge/purgeTreeCollection.js} +0 -0
  1425. /package/workflows/container-contents/remoteHydration/{destinationPrefetch.js → destination/destinationPrefetch.js} +0 -0
  1426. /package/workflows/container-contents/remoteHydration/{destinationRoleCache.js → destination/destinationRoleCache.js} +0 -0
  1427. /package/workflows/container-contents/remoteHydration/{childIndex.js → lanes/childIndex.js} +0 -0
  1428. /package/workflows/container-contents/remoteHydration/{parentLaneQueue.js → lanes/parentLaneQueue.js} +0 -0
  1429. /package/workflows/container-contents/remoteHydration/{containerStateFingerprint.js → remoteContainers/containerStateFingerprint.js} +0 -0
  1430. /package/workflows/container-contents/remoteHydration/{remoteContainerTimestamps.js → remoteContainers/remoteContainerTimestamps.js} +0 -0
  1431. /package/workflows/containers/child/{keyringOverrideLineage.js.map → rekey/keyringOverrideLineage.js.map} +0 -0
  1432. /package/workflows/containers/child/{shareProjection.js → share/shareProjection.js} +0 -0
@@ -1 +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,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AAC,UAAU,CAAC,CAAC;IAClE,CAAC;SAAM,CAAC;QACN,KAAK,CAAC,SAAS,CAAC,2BAA2B,EAAE,EAAE,CAAC;IAClD,CAAC;IACD,IAAI,qBAAqB,GAAG,KAAK,CAAC;IAClC,MAAM,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
+ {"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,oDAAoD,CAAC;AAS5D,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,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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/sync/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 +1 @@
1
- {"version":3,"file":"syncAbandon.js","sourceRo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,UAAU,wBAAwB,CAC5C,KAAyB,EACzB,KAAY;IAEZ,MAAM,OAAO,GAA8B;QACzC,IAAI,EAAE,iCAAiC;QACvC,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,EAAE,EAAE,KAAK;QACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;QACvB,MAAM,EAAE,IAAI;KACb,CAAC;IACF,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC,OAAO,CAAC,CAAC;IAC/C,KAAK,CAAC,eAAe,EAAE,CACrB,mEAAmE,CACpE,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKekCurrency\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/types\";\nimport type { SyncRemoteDocumentInput } from \"../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
+ {"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,eAAe,EAAE,CAAC,SAAS,CAAC,CAAC;IACnC,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,UAAU,qBAAqB,CACnC,KAAyB,EACzB,KAA2C;IAE3C,uEAAuE;IACvE,yEAAyE;IACzE,yEAAyE;IACzE,4BAA4B,CAAC,KAAK,CAAC,WAAW,EAAE;QAC9C,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;IACH,KAAK,CAAC,eAAe,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACtC,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,KAAyB,EACzB,KAA0C;IAE1C,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC;QACpC,IAAI,EAAE,uCAAuC;QAC7C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,EAAE,EAAE,KAAK;QACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;QACvB,MAAM,EAAE,IAAI;KACb,CAAC,CAAC;IACH,OAAO,qBAAqB,CAC1B,KAAK,EACL,IAAI,oCAAoC,CAAC,cAAc,CAAC,CACzD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,KAAyB;IAEzB,KAAK,CAAC,eAAe,EAAE,CAAC,6CAA6C,CAAC,CAAC;IACvE,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,KAAyB,EACzB,KAAY;IAEZ,MAAM,OAAO,GAA8B;QACzC,IAAI,EAAE,iCAAiC;QACvC,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,EAAE,EAAE,KAAK;QACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;QACvB,MAAM,EAAE,IAAI;KACb,CAAC;IACF,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC,OAAO,CAAC,CAAC;IAC/C,KAAK,CAAC,eAAe,EAAE,CACrB,mEAAmE,CACpE,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/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,6 +1,6 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
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";
3
+ import { ContainerKekRepairRequiredError } from "../../../data/documents/shared/containerKek/containerKekCurrency.js";
4
4
  import { isRetryableDocumentSyncConflict, isUpstreamDeletedDocumentSyncFailure, } from "../../../data/documents/shared/responses.js";
5
5
  import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
6
6
  import { isKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
@@ -1 +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,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C;IAElC,OAAO,CACL,OAAO,CAAC,MAAM,KAAK,GAAG;QACtB,OAAO,CAAC,IAAI,KAAK,yBAAyB,CAAC,0BAA0B,CACtE,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,uCAAuC,CAAC,OAIvD;IACC,OAAO,CACL,OAAO,CAAC,MAAM,KAAK,GAAG;QACtB,OAAO,CAAC,IAAI,KAAK,6BAA6B,CAAC,qBAAqB,CACrE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,KAI5C;IACC,OAAO,CACL,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,WAAW;QACjC,+BAA+B,CAAC,KAAK,CAAC,OAAO,CAAC,CAC/C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kCAAkC,CAAC,KAKlD;IACC,OAAO,CACL,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,WAAW;QACjC,KAAK,CAAC,kBAAkB,GAAG,CAAC;QAC5B,qCAAqC,CAAC,KAAK,CAAC,OAAO,CAAC,CACrD,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAAC,KAI9D;IACC,IAAI,CAAC,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QACzD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;IACxE,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n DOCUMENT_MUTATION_ERROR_CODES,\n DOCUMENT_SYNC_ERROR_CODES,\n} from \"@tearleads/validators/response\";\nimport { ContainerKekRepairRequiredError } from \"../../../data/documents/shared/containerKekCurrency\";\nimport {\n isRetryableDocumentSyncConflict,\n isUpstreamDeletedDocumentSyncFailure,\n} from \"../../../data/documents/shared/responses\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { isKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\nexport type RemoteDocumentDeletionHandler = (input: {\n /** Present only after the SDK has verified the signed terminal purge proof. */\n readonly commitPurgeProof?:\n | ((transactionExecSql: ExecSql) => Promise<void>)\n | undefined;\n readonly documentId: string;\n}) => Promise<void> | void;\n\n/**\n * Invoked when a submission fails terminally — the failure is neither a\n * retryable conflict nor a recoverable update-id conflict, so the sync pass\n * stops and the pending writes stay queued (e.g. a 403 after write access was\n * revoked). Callers persist the failure so the write queue can surface it.\n */\nexport type TerminalSubmitFailureHandler = (\n failure: DocumentSyncSubmitFailure,\n) => Promise<void> | void;\n\n/**\n * Read-only counterpart to describeDocumentSyncSubmitFailure: names a refused\n * revalidation without implying a blocked write. 403s never reach this — a\n * read-only 403 is deliberately suppressed (edge-case row 9) so unattempted\n * local edits are never flagged.\n */\nexport function describeDocumentRevalidationFailure(\n failure: Pick<DocumentSyncSubmitFailure, \"message\" | \"status\">,\n): string {\n const detail =\n failure.message.trim().length > 0\n ? failure.message.trim()\n : \"the server refused the read\";\n const suffix = failure.status === null ? \"\" : ` (${failure.status})`;\n return `Remote revalidation failed: ${detail}${suffix}`;\n}\n\n/** Human-readable description of a terminal submit failure for queue display. */\nexport function describeDocumentSyncSubmitFailure(\n failure: Pick<DocumentSyncSubmitFailure, \"message\" | \"status\">,\n): string {\n if (failure.status === 403) {\n return \"Write access denied by the server (403)\";\n }\n const message =\n failure.message.trim().length > 0 ? failure.message.trim() : \"Sync failed\";\n return failure.status === null ? message : `${message} (${failure.status})`;\n}\n\ntype ProjectionIntegrityErrorCode =\n | \"equivocation\"\n | \"rollback\"\n | \"stale_predecessor\";\n\nfunction keyingVerificationErrorCode(error: unknown): string | null {\n if (!isKeyingVerificationError(error) || !(error instanceof Error)) {\n return null;\n }\n const code = Reflect.get(error, \"code\");\n return typeof code === \"string\" ? code : null;\n}\n\nexport function projectionIntegrityErrorCode(\n error: unknown,\n): ProjectionIntegrityErrorCode | null {\n if (\n !(error instanceof KeyingVerificationError) &&\n !(error instanceof Error && error.name === \"KeyingVerificationError\")\n ) {\n return null;\n }\n\n const code = keyingVerificationErrorCode(error);\n return code === \"rollback\" ||\n code === \"equivocation\" ||\n code === \"stale_predecessor\"\n ? code\n : null;\n}\n\n/**\n * Shared shell for the stale-projection retry classifiers. A cached\n * projection older than a checkpoint we already recorded (\"rollback\") —\n * typical right after a peer shared/rotated a linked container — is resolved\n * by refetching the current projection. The refetch is safe: it cannot\n * bypass the anti-rollback check, because a genuinely rolled-back server\n * response re-throws on the rebuilt plan. Any other keying-verification\n * failure is terminal; anything else defers to the caller's message\n * predicate for its unwrap-failure shape.\n */\nexport function shouldRetryWithFreshProjection(\n error: unknown,\n messageMatches: (message: string) => boolean,\n): boolean {\n // A peer may already have repaired the chain. Refetch once; the same guard\n // rejects a still-stale response before any new ciphertext is produced.\n if (\n error instanceof ContainerKekRepairRequiredError ||\n error instanceof ProjectionDependencyUnavailableError\n )\n return true;\n const integrityErrorCode = projectionIntegrityErrorCode(error);\n if (integrityErrorCode) {\n return integrityErrorCode === \"rollback\";\n }\n if (keyingVerificationErrorCode(error) === \"invalid_shape\") {\n // Verification boundaries normalize malformed/stale projection data to a\n // terminal error. One cache eviction is still safe: a dishonest or broken\n // fresh response fails again outside this retry boundary.\n return true;\n }\n if (isKeyingVerificationError(error)) {\n return false;\n }\n\n return error instanceof Error && messageMatches(error.message);\n}\n\nexport function shouldRetrySyncWithFreshWriterProjection(\n error: unknown,\n): boolean {\n return shouldRetryWithFreshProjection(\n error,\n (message) =>\n message.startsWith(\n \"Document authorizing container KEK path could not be unwrapped\",\n ) && message.includes(\"Container writer projection KEK\"),\n );\n}\n\nexport function isRecoverableDocumentUpdateIdConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.updateIdConflict\n );\n}\n\n/**\n * The server's covering-baseline gate refused a queued rotation checkpoint\n * (e.g. a leftover from an interrupted recovery or a lost heal ack) because\n * it no longer covers the committed frontier. The pass can repair itself by\n * regenerating a fresh covering baseline from the live document instead of\n * resubmitting the stale payload — which would fail terminally forever.\n */\nexport function isCheckpointCoverageConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.checkpointCoverageConflict\n );\n}\n\n/**\n * A create submitted with a stable documentId whose first attempt already\n * committed server-side comes back as this 409 (see the server's\n * `assertCreateCanAdvanceDocumentHead`). It is not a failure — the caller adopts\n * the existing remote document instead of creating a duplicate.\n */\nexport function isDocumentManifestAlreadyExistsConflict(failure: {\n readonly code?: string | undefined;\n readonly message: string;\n readonly status: number | null;\n}): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_MUTATION_ERROR_CODES.manifestAlreadyExists\n );\n}\n\nexport function canRetryDocumentSyncConflict(input: {\n attempt: number;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n}): boolean {\n return (\n input.attempt < input.maxAttempts &&\n isRetryableDocumentSyncConflict(input.failure)\n );\n}\n\nexport function canRecoverDocumentUpdateIdConflict(input: {\n attempt: number;\n failure: DocumentSyncSubmitFailure;\n maxAttempts: number;\n pendingUpdateCount: number;\n}): boolean {\n return (\n input.attempt < input.maxAttempts &&\n input.pendingUpdateCount > 0 &&\n isRecoverableDocumentUpdateIdConflict(input.failure)\n );\n}\n\nexport async function handleUpstreamDeletedDocumentSyncFailure(input: {\n documentId: string;\n failure: DocumentSyncSubmitFailure;\n onRemoteDocumentDeleted?: RemoteDocumentDeletionHandler | undefined;\n}): Promise<boolean> {\n if (!isUpstreamDeletedDocumentSyncFailure(input.failure)) {\n return false;\n }\n\n await input.onRemoteDocumentDeleted?.({ documentId: input.documentId });\n return true;\n}\n"]}
1
+ {"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,kEAAkE,CAAC;AACnH,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,GAAG,EAAE,CAAC;QAC3B,OAAO,yCAAyC,CAAC;IACnD,CAAC;IACD,MAAM,OAAO,GACX,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC;IAC7E,OAAO,OAAO,CAAC,MAAM,KAAK,IAAI,C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AK,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/containerKek/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
1
  import type { DocumentSyncResponse, DocumentWriterProjectionResponse } from "../../../internal/validators/response/index.js";
2
2
  import type { DocumentSyncPreparedUpdate, ProjectionVerificationOptions } from "../../../data/documents/shared/types.js";
3
- import type { PendingUpdateRecord } from "../../../data/sqlite/documentPersistence.js";
3
+ import type { PendingUpdateRecord } from "../../../data/sqlite/documentPersistence/index.js";
4
4
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
5
5
  type SyncResponseUpdate = DocumentSyncResponse["updates"][number];
6
6
  type RawHistoryUnavailableValidator = (input: {
@@ -1,9 +1,9 @@
1
1
  import { importContentKeyMaterial } from "../../../data/documents/shared/contentRecordKeys.js";
2
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";
3
+ import { ContainerKekHistoryUnavailableError, collectContainerKeksForDocumentSync, DocumentContentKeyUnavailableError, DocumentHistoryUnavailableError, unwrapDocumentContentKeyFromBundle, } from "../../../data/documents/shared/projection/index.js";
6
4
  import { readWriteHeader } from "../../../data/documents/shared/readers.js";
5
+ import { assertDocumentSyncUpdateEncryptedRecord } from "../../../data/documents/shared/sync/documentSyncUpdateDecryption.js";
6
+ import { isDocumentSyncUpdateIsolationError, isolateDocumentSyncBatchError, isolateDocumentSyncUpdateError, } from "../../../data/documents/shared/sync/documentSyncUpdateIsolation.js";
7
7
  import { projectionVerificationOptions } from "../../../data/documents/shared/types.js";
8
8
  import { isKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
9
9
  function isRawHistoryUnavailableCause(error) {
@@ -1 +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,EAA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M,0BAA0B,CAAC;gBAC/B,MAAM;gBACN,aAAa;gBACb,UAAU,EAAE,KAAK,CAAC,gBAAgB,CAAC,UAAU;gBAC7C,OAAO,EAAE,eAAe;aACzB,CAAC,CACH,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,CAAC,WAAW,KAAK,KAAK,IAAI,4BAA4B,CAAC,KAAK,CAAC,EAAE,CAAC;gBACvE,qBAAqB,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC;gBAC5D,SAAS;YACX,CAAC;YACD,kCAAkC,CAAC;gBACjC,KAAK,EAAE,KAAK;gBACZ,OAAO,EAAE,eAAe;aACzB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,IAAI,qBAAqB,EAAE,CAAC;QAC1B,MAAM,0BAA0B,CAAC;YAC/B,kBAAkB;YAClB,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,WAAW,EAAE,qBAAqB;YAClC,QAAQ,EAAE,KAAK,CAAC,uBAAuB;SACxC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,kBAAkB,CAAC;AAC5B,CAAC","sourcesContent":["import type {\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { importContentKeyMaterial } from \"../../../data/documents/shared/contentRecordKeys\";\nimport { encryptDocumentPendingUpdate } from \"../../../data/documents/shared/crypto\";\nimport { assertDocumentSyncUpdateEncryptedRecord } from \"../../../data/documents/shared/documentSyncUpdateDecryption\";\nimport {\n isDocumentSyncUpdateIsolationError,\n isolateDocumentSyncBatchError,\n isolateDocumentSyncUpdateError,\n} from \"../../../data/documents/shared/documentSyncUpdateIsolation\";\nimport {\n ContainerKekHistoryUnavailableError,\n collectContainerKeksForDocumentSync,\n DocumentContentKeyUnavailableError,\n DocumentHistoryUnavailableError,\n unwrapDocumentContentKeyFromBundle,\n} from \"../../../data/documents/shared/projection\";\nimport { readWriteHeader } from \"../../../data/documents/shared/readers\";\nimport type {\n DocumentSyncPreparedUpdate,\n ProjectionVerificationOptions,\n} from \"../../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/types\";\nimport { isKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport type { PendingUpdateRecord } from \"../../../data/sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\ntype SyncResponseUpdate = DocumentSyncResponse[\"updates\"][number];\ntype RawHistoryUnavailableCause =\n | DocumentContentKeyUnavailableError\n | DocumentHistoryUnavailableError;\n\nfunction isRawHistoryUnavailableCause(\n error: unknown,\n): error is RawHistoryUnavailableCause {\n return (\n error instanceof DocumentContentKeyUnavailableError ||\n (error instanceof DocumentHistoryUnavailableError &&\n error.historyCause instanceof ContainerKekHistoryUnavailableError)\n );\n}\n\ntype RawHistoryUnavailableValidator = (input: {\n contentKeysByEpoch: ReadonlyMap<number, Uint8Array>;\n updates: readonly SyncResponseUpdate[];\n}) => void | Promise<void>;\n\n/** A raw recovery cannot reconstruct history without this retained epoch. */\nexport class DocumentRawHistoryUnavailableError extends Error {\n readonly code = \"document_raw_history_epoch_unavailable\";\n\n constructor(\n readonly contentKeyEpoch: number,\n cause: unknown,\n ) {\n super(\n `Document raw-history recovery cannot decrypt content-key epoch ${contentKeyEpoch}`,\n { cause },\n );\n this.name = \"DocumentRawHistoryUnavailableError\";\n }\n}\n\nasync function assertResponseEncryptedRecords(\n updates: readonly SyncResponseUpdate[],\n): Promise<void> {\n const inspections = await Promise.allSettled(\n updates.map(assertDocumentSyncUpdateEncryptedRecord),\n );\n const failures = inspections.flatMap((inspection, index) =>\n inspection.status === \"rejected\"\n ? [{ index, reason: inspection.reason }]\n : [],\n );\n const firstFailure = failures[0];\n if (failures.length === 1 && firstFailure) {\n throw firstFailure.reason;\n }\n if (failures.length > 1 && firstFailure) {\n const stage =\n isDocumentSyncUpdateIsolationError(firstFailure.reason) &&\n failures.every(\n ({ reason }) =>\n isDocumentSyncUpdateIsolationError(reason) &&\n reason.stage === firstFailure.reason.stage,\n )\n ? firstFailure.reason.stage\n : \"encrypted_record\";\n throw isolateDocumentSyncBatchError({\n cause: new Error(\"Multiple document encrypted records are invalid\"),\n stage,\n updateIds: failures.map(({ index }) => updates[index]?.id ?? \"unknown\"),\n });\n }\n}\n\nasync function throwRawHistoryUnavailable(input: {\n contentKeysByEpoch: ReadonlyMap<number, Uint8Array>;\n response: DocumentSyncResponse;\n unavailable: { cause: RawHistoryUnavailableCause; contentKeyEpoch: number };\n validate?: RawHistoryUnavailableValidator | undefined;\n}): Promise<never> {\n await assertResponseEncryptedRecords(input.response.updates);\n await input.validate?.({\n contentKeysByEpoch: input.contentKeysByEpoch,\n updates: input.response.updates.filter((update) =>\n input.contentKeysByEpoch.has(\n readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n ).contentKeyEpoch,\n ),\n ),\n });\n throw new DocumentRawHistoryUnavailableError(\n input.unavailable.contentKeyEpoch,\n input.unavailable.cause,\n );\n}\n\nexport async function prepareDocumentOutgoingUpdates(input: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n organizationId: string;\n pendingUpdates: readonly PendingUpdateRecord[];\n}): Promise<DocumentSyncPreparedUpdate[]> {\n if (input.pendingUpdates.length === 0) {\n return [];\n }\n const contentKeyMaterial = await importContentKeyMaterial(input.contentKey);\n\n return Promise.all(\n input.pendingUpdates.map(async (update) => {\n const encrypted = await encryptDocumentPendingUpdate({\n contentKeyMaterial,\n contentKeyEpoch: input.contentKeyEpoch,\n documentId: input.documentId,\n organizationId: input.organizationId,\n update,\n });\n\n return {\n contentRecordId: encrypted.contentRecordId,\n encryptedData: encrypted.encryptedData,\n id: update.id,\n partialStartVersionVector: update.partialStartVersionVector,\n partialEndVersionVector: update.partialEndVersionVector,\n metadataHash: encrypted.metadataHash,\n ciphertextHash: encrypted.ciphertextHash,\n plaintextHash: encrypted.plaintextHash,\n ...(update.sourceVersionVector\n ? {\n checkpointKind: \"rotate_baseline\" as const,\n checkpointPayloadKind: \"full_history_snapshot\" as const,\n sourceVersionVector: update.sourceVersionVector,\n }\n : {}),\n };\n }),\n );\n}\n\nfunction syncResponseContentKeyBundlesByEpoch(\n response: DocumentSyncResponse,\n): ReadonlyMap<number, DocumentSyncResponse[\"contentKeyBundle\"]> {\n const byEpoch = new Map<number, DocumentSyncResponse[\"contentKeyBundle\"]>();\n\n for (const bundle of [\n response.contentKeyBundle,\n ...response.contentKeyBundles,\n ]) {\n if (byEpoch.has(bundle.contentKeyEpoch)) {\n throw new Error(\"Document sync response repeats a content-key epoch\");\n }\n byEpoch.set(bundle.contentKeyEpoch, bundle);\n }\n\n return byEpoch;\n}\n\nfunction syncResponseUpdatesByContentKeyEpoch(\n response: DocumentSyncResponse,\n): ReadonlyMap<number, readonly SyncResponseUpdate[]> {\n const updatesByEpoch = new Map<number, SyncResponseUpdate[]>();\n for (const update of response.updates) {\n let contentKeyEpoch: number;\n try {\n contentKeyEpoch = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n ).contentKeyEpoch;\n } catch (error) {\n throw isolateDocumentSyncUpdateError({\n cause: error,\n responseUpdate: update,\n stage: \"write_header\",\n updateId: update.id,\n });\n }\n const epochUpdates = updatesByEpoch.get(contentKeyEpoch);\n if (epochUpdates) epochUpdates.push(update);\n else updatesByEpoch.set(contentKeyEpoch, [update]);\n }\n return updatesByEpoch;\n}\n\nfunction assertBundleMatchesUpdateHeaders(input: {\n bundle: DocumentSyncResponse[\"contentKeyBundle\"];\n requireOriginalTargets: boolean;\n updates: readonly SyncResponseUpdate[];\n}): void {\n for (const update of input.updates) {\n const header = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n );\n if (\n header.objectId !== input.bundle.documentId ||\n header.contentKeyEpoch !== input.bundle.contentKeyEpoch ||\n (input.requireOriginalTargets &&\n (header.accessManifestHash !== input.bundle.linkSetManifestHash ||\n header.targetHash !== input.bundle.targetHash))\n ) {\n throw new Error(\n input.requireOriginalTargets\n ? \"Document sync response content key is unavailable and its bundle differs from the original update headers\"\n : \"Document sync response content-key bundle does not match its update headers\",\n );\n }\n }\n}\n\n/**\n * Linking can rewrap a retained key at the same content epoch. Its latest bundle\n * then has newer targets than older signed updates. A usable key is validated\n * by the caller's authenticated record decryption; the update's own historical\n * manifest, targets and signature are verified independently before this step.\n *\n * If the key cannot be recovered, require the original target commitments before\n * calling that an availability failure. Substituted unavailable targets must\n * still be quarantined, never disguised as legitimate missing history.\n */\nasync function unwrapHistoricalContentKey(input: {\n bundle: DocumentSyncResponse[\"contentKeyBundle\"];\n documentId: string;\n collectedKeks: Awaited<\n ReturnType<typeof collectContainerKeksForDocumentSync>\n >;\n updates: readonly SyncResponseUpdate[];\n}): Promise<Uint8Array> {\n assertBundleMatchesUpdateHeaders({ ...input, requireOriginalTargets: false });\n try {\n return await unwrapDocumentContentKeyFromBundle(\n input.bundle,\n input.documentId,\n input.collectedKeks.keksByEpochId,\n input.collectedKeks.predecessorFailuresByEpochId,\n input.collectedKeks.unattributedPredecessorFailuresByContainerId,\n );\n } catch (error) {\n if (isRawHistoryUnavailableCause(error)) {\n assertBundleMatchesUpdateHeaders({\n ...input,\n requireOriginalTargets: true,\n });\n }\n throw error;\n }\n}\n\n/** @internal Keeps epoch-wide failures anonymous and integrity failures typed. */\nexport function throwDocumentSyncContentKeyFailure(input: {\n cause: unknown;\n updates: readonly SyncResponseUpdate[];\n}): never {\n if (isKeyingVerificationError(input.cause)) {\n throw input.cause;\n }\n if (\n input.cause instanceof DocumentHistoryUnavailableError &&\n isKeyingVerificationError(input.cause.historyCause)\n ) {\n throw input.cause.historyCause;\n }\n throw isolateDocumentSyncBatchError({\n cause: input.cause,\n stage: \"content_key\",\n updateIds: input.updates.map((update) => update.id),\n });\n}\n\nexport async function unwrapDocumentSyncResponseContentKeys(\n input: {\n currentContentKey: Uint8Array;\n currentContentKeyEpoch: number;\n execSql?: ExecSql | undefined;\n historyMode?: \"raw\" | undefined;\n /** @internal Validate every decryptable sibling before raw availability wins. */\n onRawHistoryUnavailable?: RawHistoryUnavailableValidator | undefined;\n response: DocumentSyncResponse;\n targetSecretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<ReadonlyMap<number, Uint8Array>> {\n // A stale read-only pass can carry an empty placeholder when none of its\n // authorizing paths reaches the bundle target. Do not mark that epoch as\n // resolved: every served update must instead unwrap its bundle through the\n // verified predecessor KEK chain or fail with an honest error.\n const contentKeysByEpoch = new Map<number, Uint8Array>(\n input.currentContentKey.byteLength > 0\n ? [[input.currentContentKeyEpoch, input.currentContentKey]]\n : [],\n );\n const updatesByContentKeyEpoch = syncResponseUpdatesByContentKeyEpoch(\n input.response,\n );\n const missingContentKeyEpochs = [...updatesByContentKeyEpoch.keys()].filter(\n (contentKeyEpoch) => !contentKeysByEpoch.has(contentKeyEpoch),\n );\n missingContentKeyEpochs.sort((left, right) => left - right);\n if (missingContentKeyEpochs.length === 0) {\n return contentKeysByEpoch;\n }\n const missingUpdates = missingContentKeyEpochs.flatMap(\n (contentKeyEpoch) => updatesByContentKeyEpoch.get(contentKeyEpoch) ?? [],\n );\n let bundlesByEpoch: ReturnType<typeof syncResponseContentKeyBundlesByEpoch>;\n try {\n bundlesByEpoch = syncResponseContentKeyBundlesByEpoch(input.response);\n } catch (error) {\n throwDocumentSyncContentKeyFailure({\n cause: error,\n updates: missingUpdates,\n });\n }\n const absentBundleEpoch = missingContentKeyEpochs.find(\n (contentKeyEpoch) => !bundlesByEpoch.has(contentKeyEpoch),\n );\n if (absentBundleEpoch !== undefined) {\n throwDocumentSyncContentKeyFailure({\n cause: new Error(\"Document sync response content-key bundle missing\"),\n updates:\n updatesByContentKeyEpoch.get(absentBundleEpoch) ?? missingUpdates,\n });\n }\n const collectedKeks = await collectContainerKeksForDocumentSync({\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n let unavailableRawHistory:\n | { cause: RawHistoryUnavailableCause; contentKeyEpoch: number }\n | undefined;\n\n for (const contentKeyEpoch of missingContentKeyEpochs) {\n const bundle = bundlesByEpoch.get(contentKeyEpoch);\n const responseUpdates =\n updatesByContentKeyEpoch.get(contentKeyEpoch) ?? missingUpdates;\n if (!bundle) {\n const error = new Error(\n \"Document sync response content-key bundle missing\",\n );\n throwDocumentSyncContentKeyFailure({\n cause: error,\n updates: responseUpdates,\n });\n }\n try {\n contentKeysByEpoch.set(\n bundle.contentKeyEpoch,\n await unwrapHistoricalContentKey({\n bundle,\n collectedKeks,\n documentId: input.writerProjection.documentId,\n updates: responseUpdates,\n }),\n );\n } catch (error) {\n if (input.historyMode === \"raw\" && isRawHistoryUnavailableCause(error)) {\n unavailableRawHistory ??= { cause: error, contentKeyEpoch };\n continue;\n }\n throwDocumentSyncContentKeyFailure({\n cause: error,\n updates: responseUpdates,\n });\n }\n }\n\n if (unavailableRawHistory) {\n await throwRawHistoryUnavailable({\n contentKeysByEpoch,\n response: input.response,\n unavailable: unavailableRawHistory,\n validate: input.onRawHistoryUnavailable,\n });\n }\n\n return contentKeysByEpoch;\n}\n"]}
1
+ {"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,EACL,mCAAmC,EACnC,mCAAmC,EACnC,kCAAkC,EAClC,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AACzE,OAAO,EAAE,uCAAuC,EAAE,MAAM,kEAAkE,CAAC;AAC3H,OAAO,EACL,kCAAkC,EAClC,6BAA6B,EAC7B,8BAA8B,GAC/B,MAAM,iEAAiE,CAAC;AAKzE,OAAO,EAAE,6BAA6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,UAAU,EAAE,KAAK,CAAC,gBAAgB,CAAC,UAAU;gBAC7C,OAAO,EAAE,eAAe;aACzB,CAAC,CACH,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,CAAC,WAAW,KAAK,KAAK,IAAI,4BAA4B,CAAC,KAAK,CAAC,EAAE,CAAC;gBACvE,qBAAqB,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC;gBAC5D,SAAS;YACX,CAAC;YACD,kCAAkC,CAAC;gBACjC,KAAK,EAAE,KAAK;gBACZ,OAAO,EAAE,eAAe;aACzB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,IAAI,qBAAqB,EAAE,CAAC;QAC1B,MAAM,0BAA0B,CAAC;YAC/B,kBAAkB;YAClB,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,WAAW,EAAE,qBAAqB;YAClC,QAAQ,EAAE,KAAK,CAAC,uBAAuB;SACxC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,kBAAkB,CAAC;AAC5B,CAAC","sourcesContent":["import type {\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { importContentKeyMaterial } from \"../../../data/documents/shared/contentRecordKeys\";\nimport { encryptDocumentPendingUpdate } from \"../../../data/documents/shared/crypto\";\nimport {\n ContainerKekHistoryUnavailableError,\n collectContainerKeksForDocumentSync,\n DocumentContentKeyUnavailableError,\n DocumentHistoryUnavailableError,\n unwrapDocumentContentKeyFromBundle,\n} from \"../../../data/documents/shared/projection\";\nimport { readWriteHeader } from \"../../../data/documents/shared/readers\";\nimport { assertDocumentSyncUpdateEncryptedRecord } from \"../../../data/documents/shared/sync/documentSyncUpdateDecryption\";\nimport {\n isDocumentSyncUpdateIsolationError,\n isolateDocumentSyncBatchError,\n isolateDocumentSyncUpdateError,\n} from \"../../../data/documents/shared/sync/documentSyncUpdateIsolation\";\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,8 +1,8 @@
1
1
  import { emptyVersionVector, getImportBlobMetadata, satisfiesVersionVector, versionVectorsEqual, } from "../../../internal/loro/index.js";
2
2
  import { documentKekTargetsFromContentKeyBundle } from "../../../internal/validators/response/index.js";
3
3
  import { createPendingUpdateFields } from "../../../data/documents/documentSync.js";
4
- import { assertDocumentKekPathsCurrent } from "../../../data/documents/shared/containerKekCurrency.js";
5
- import { assertDocumentWriterProjectionConsistent, authorizingContainerPathRefs, buildRotatedDocumentContentKeyBundle, ContainerKekHistoryUnavailableError, collectContainerKeksForDocumentSync, DocumentHistoryUnavailableError, unwrapDocumentContentKeyFromBundle, } from "../../../data/documents/shared/projection.js";
4
+ import { assertDocumentKekPathsCurrent } from "../../../data/documents/shared/containerKek/containerKekCurrency.js";
5
+ import { assertDocumentWriterProjectionConsistent, authorizingContainerPathRefs, buildRotatedDocumentContentKeyBundle, ContainerKekHistoryUnavailableError, collectContainerKeksForDocumentSync, DocumentHistoryUnavailableError, unwrapDocumentContentKeyFromBundle, } from "../../../data/documents/shared/projection/index.js";
6
6
  import { assertDocumentManifestBundleConsistent } from "../../../data/documents/shared/readers.js";
7
7
  import { projectionVerificationOptions } from "../../../data/documents/shared/types.js";
8
8
  import { selectDocumentSyncOutgoingBatch } from "../../../data/sync/documentSyncOutgoingBatch.js";
@@ -1 +1 @@
1
- {"version":3,"file":"syncPlanMaterial.js","sourceRoot":"","sources":["syncPlanMaterial.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,sBAAsB,EACtB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AAMzB,OAAO,EAAE,sCAAsC,EAAE,MAAM,gCAAgC,CAAC;AACxF,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AACpG,OAAO,EACL,wCAAwC,EACxC,4BAA4B,EAC5B,oCAAoC,EACpC,mCAAmC,EACnC,mCAAmC,EACnC,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,sCAAsC,EAAE,MAAM,wCAAwC,CAAC;AAOhG,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AAIrF,OAAO,EAAE,+BAA+B,EAAE,MAAM,8CAA8C,CAAC;AAC/F,OAAO,EAEL,2BAA2B,EAC3B,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,oCAAoC,EAAE,MAAM,sBAAsB,CAAC;AAE5E;;;;;;GAMG;AACH,KAAK,UAAU,uCAAuC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C7C,KAAK;aACN,CAAC,CAAC;QACL,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;IACD,MAAM,EACJ,UAAU,EACV,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,GACf,GAAG,QAAQ,CAAC;IACb,MAAM,eAAe,GAAG,MAAM,8BAA8B,CAAC;QAC3D,UAAU;QACV,eAAe,EAAE,gBAAgB,CAAC,eAAe;QACjD,UAAU;QACV,cAAc,EAAE,gBAAgB,CAAC,cAAc;QAC/C,cAAc;KACf,CAAC,CAAC;IACH,MAAM,QAAQ,GAAG,MAAM,qBAAqB,CAAC;QAC3C,MAAM,EAAE;YACN,GAAG,KAAK,CAAC,MAAM;YACf,cAAc,EAAE,gBAAgB,CAAC,cAAc;SAChD;QACD,4BAA4B,EAAE,4BAA4B,CACxD,KAAK,CAAC,gBAAgB,CACvB;QACD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB;QAChB,UAAU;QACV,kBAAkB;QAClB,gBAAgB;QAChB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,eAAe;QACf,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,QAAQ,EAAE,KAAK,CAAC,QAAQ;KACzB,CAAC,CAAC;IACH,OAAO,oCAAoC,CAAC;QAC1C,QAAQ;QACR,QAAQ;QACR,mBAAmB;QACnB,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;KACzC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n VerifiedContainerAccessManifest,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport {\n emptyVersionVector,\n getImportBlobMetadata,\n satisfiesVersionVector,\n versionVectorsEqual,\n} from \"@tearleads/loro\";\nimport type {\n DocumentCreateResponse,\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { documentKekTargetsFromContentKeyBundle } from \"@tearleads/validators/response\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport { assertDocumentKekPathsCurrent } from \"../../../data/documents/shared/containerKekCurrency\";\nimport {\n assertDocumentWriterProjectionConsistent,\n authorizingContainerPathRefs,\n buildRotatedDocumentContentKeyBundle,\n ContainerKekHistoryUnavailableError,\n collectContainerKeksForDocumentSync,\n DocumentHistoryUnavailableError,\n unwrapDocumentContentKeyFromBundle,\n} from \"../../../data/documents/shared/projection\";\nimport { assertDocumentManifestBundleConsistent } from \"../../../data/documents/shared/readers\";\nimport type {\n BuildDocumentSyncPlanInput,\n DocumentCreateAuthor,\n MaterializedDocumentSyncPlan,\n ProjectionVerificationOptions,\n} from \"../../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/types\";\nimport type { DocumentWriterProjectionAuthorization } from \"../../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../../data/sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { selectDocumentSyncOutgoingBatch } from \"../../../data/sync/documentSyncOutgoingBatch\";\nimport {\n type DocumentSyncTraceEmitter,\n traceCheckpointRegeneration,\n traceHealBlocked,\n traceHealPlanned,\n traceStaleBundle,\n traceStaleRead,\n} from \"../sync/syncTrace\";\nimport { prepareDocumentOutgoingUpdates } from \"./syncContentKeys\";\nimport { buildDocumentSyncPlan } from \"./syncPlanIdentity\";\nimport { finalizeMaterializedDocumentSyncPlan } from \"./syncPlanProjection\";\n\n/**\n * Builds the rotation baseline that anchors a stale-bundle heal: a full\n * history snapshot of the local document, re-encrypted under the fresh\n * content key so every current member (including post-rotation newcomers)\n * has an efficient current-epoch redirect. Predecessor KEKs remain the\n * correctness path when no covering baseline exists.\n */\nasync function buildStaleRecoveryBaselinePendingUpdate(\n buildRotationSnapshot: (() => Promise<Uint8Array | null>) | undefined,\n): Promise<PendingUpdateRecord> {\n const snapshot = buildRotationSnapshot ? await buildRotationSnapshot() : null;\n if (!snapshot) {\n throw new Error(\n \"Document content-key bundle is stale and no rotation snapshot is available to heal it\",\n );\n }\n const metadata = getImportBlobMetadata(snapshot);\n if (\n metadata.mode !== \"snapshot\" ||\n !versionVectorsEqual(\n metadata.partialStartVersionVector,\n emptyVersionVector(),\n )\n ) {\n throw new Error(\n \"Document stale-bundle recovery requires a full-history rotation snapshot\",\n );\n }\n const pendingFields = createPendingUpdateFields(\n snapshot,\n metadata.partialEndVersionVector,\n );\n if (!pendingFields) {\n throw new Error(\"Document stale-bundle recovery snapshot is empty\");\n }\n\n return {\n id: crypto.randomUUID(),\n ...pendingFields,\n };\n}\n\n/**\n * Resolves the content material a sync plan encrypts and carries. A stale\n * bundle names predecessor KEK targets while the document's current targets\n * name successor epochs, so it splits by intent: a write-bearing pass heals\n * the document with a FRESH content key at the next epoch, anchored by a\n * covering rotation baseline, while a read-only pass keeps the stale pair and\n * unwraps it through predecessor KEKs so the server can settle a complete pull.\n */\n/**\n * The manifest bundle a stale read-only plan must pair with: the one the\n * stale content-key bundle actually references. A stale bundle normally\n * still carries the current link-set manifest hash (KEK rotations do not\n * advance the document manifest), but the projection consistency check\n * defensively admits a bundle lagging the head as long as it appears in the\n * manifest history — pair with that historical bundle so the plan's own\n * identity checks hold.\n */\nfunction staleBundleDocumentManifest(\n writerProjection: DocumentWriterProjectionResponse,\n): DocumentCreateResponse[\"accessManifest\"] {\n const { contentKeyBundle, documentManifest } = writerProjection;\n if (contentKeyBundle.linkSetManifestHash === documentManifest.manifestHash) {\n return documentManifest;\n }\n const historicalManifest = writerProjection.documentManifestHistory.find(\n (bundle) => bundle.manifestHash === contentKeyBundle.linkSetManifestHash,\n );\n if (!historicalManifest) {\n throw new Error(\n \"Document stale bundle manifest is missing from the projection history\",\n );\n }\n return historicalManifest;\n}\n\n/**\n * Settling a superseded checkpoint deletes its queue row, so the fresh\n * baseline must PROVABLY subsume it — assumed coverage would silently drop\n * any ops the checkpoint alone carried.\n */\nfunction assertRecoveryBaselineCoversCheckpoints(\n recoveryBaseline: PendingUpdateRecord,\n checkpoints: readonly PendingUpdateRecord[],\n): void {\n for (const checkpoint of checkpoints) {\n if (\n !satisfiesVersionVector(\n recoveryBaseline.partialEndVersionVector,\n checkpoint.partialEndVersionVector,\n )\n ) {\n throw new Error(\n \"Document stale-bundle recovery snapshot does not cover a queued rotation checkpoint\",\n );\n }\n }\n}\n\ninterface ResolvedSyncPlanContentMaterial {\n contentKey: Uint8Array;\n contentKeyBundle: DocumentCreateResponse[\"contentKeyBundle\"];\n documentKekTargets: DocumentSyncResponse[\"documentKekTargets\"];\n documentManifest: DocumentCreateResponse[\"accessManifest\"];\n healedStaleContentKeyBundle: boolean;\n heldBackPendingUpdateIds: readonly string[];\n pendingUpdates: readonly PendingUpdateRecord[];\n staleRecoveryBaselineUpdateId?: string;\n}\n\nasync function resolveStaleHealMaterial(\n input: Parameters<typeof buildMaterializedDocumentSyncPlan>[0],\n containerKeksByEpochId: ReadonlyMap<string, Uint8Array>,\n pendingUpdates: readonly PendingUpdateRecord[],\n): Promise<ResolvedSyncPlanContentMaterial> {\n const contentKey = crypto.getRandomValues(new Uint8Array(32));\n // A rotation checkpoint left in the queue by an interrupted earlier\n // recovery is superseded by the fresh covering baseline built below:\n // submitting it alongside would trip the server's covering-baseline gate,\n // and resubmitting it after the heal could become the latest baseline at\n // the healed epoch and mask the covering one. Hold it out of the request;\n // on heal success its id is reported settled (the committed baseline\n // subsumes its full-history content) so the queue row is removed.\n //\n // A heal whose OWN baseline does not cover the committed frontier is\n // rejected by that same gate and surfaces as a terminal queue failure.\n // This write-bearing pass does not pull first. A device missing committed\n // history can independently rematerialize it through predecessor KEKs on a\n // read-only pass, then retry with a covering snapshot. The coverage proof\n // prevents a partial local view from becoming the redirect baseline.\n const ordinaryPendingUpdates = pendingUpdates.filter(\n (update) => update.sourceVersionVector == null,\n );\n const heldBackCheckpoints = pendingUpdates.filter(\n (update) => update.sourceVersionVector != null,\n );\n const recoveryBaseline = await buildStaleRecoveryBaselinePendingUpdate(\n input.buildRotationSnapshot,\n );\n const selectedOrdinaryPendingUpdates = selectDocumentSyncOutgoingBatch(\n ordinaryPendingUpdates,\n {\n reservedDataCharacters: recoveryBaseline.updateData.length,\n reservedUpdateCount: 1,\n },\n );\n assertRecoveryBaselineCoversCheckpoints(\n recoveryBaseline,\n heldBackCheckpoints,\n );\n const staleEpoch = input.writerProjection.contentKeyBundle.contentKeyEpoch;\n const contentKeyBundle = await buildRotatedDocumentContentKeyBundle({\n containerKeksByEpochId,\n contentKey,\n writerProjection: input.writerProjection,\n });\n traceHealPlanned(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n fromEpoch: staleEpoch,\n heldBack: heldBackCheckpoints.length,\n toEpoch: contentKeyBundle.contentKeyEpoch,\n updates: selectedOrdinaryPendingUpdates.length,\n });\n return {\n contentKey,\n contentKeyBundle,\n documentKekTargets: input.writerProjection.documentKekTargets,\n documentManifest: input.writerProjection.documentManifest,\n healedStaleContentKeyBundle: true,\n heldBackPendingUpdateIds: heldBackCheckpoints.map((update) => update.id),\n pendingUpdates: [recoveryBaseline, ...selectedOrdinaryPendingUpdates],\n staleRecoveryBaselineUpdateId: recoveryBaseline.id,\n };\n}\n\n/**\n * Reactive repair for a healthy-projection pass whose queued rotation\n * checkpoint the server rejected via the covering-baseline gate (a leftover\n * from an interrupted recovery, a heal whose ack was lost, or a lost heal\n * race). Queued checkpoints normally pass through untouched — reset and\n * rotation flows legitimately submit them — but a rejected one would strand\n * the whole queue, and committing it could shrink redirect coverage. Replace\n * the stale checkpoints with one freshly regenerated covering baseline and\n * settle them on success (coverage proven above).\n */\nasync function resolveCheckpointRegenerationMaterial(\n input: Parameters<typeof buildMaterializedDocumentSyncPlan>[0],\n base: ResolvedSyncPlanContentMaterial,\n pendingUpdates: readonly PendingUpdateRecord[],\n): Promise<ResolvedSyncPlanContentMaterial> {\n const ordinaryPendingUpdates = pendingUpdates.filter(\n (update) => update.sourceVersionVector == null,\n );\n const queuedCheckpoints = pendingUpdates.filter(\n (update) => update.sourceVersionVector != null,\n );\n const recoveryBaseline = await buildStaleRecoveryBaselinePendingUpdate(\n input.buildRotationSnapshot,\n );\n const selectedOrdinaryPendingUpdates = selectDocumentSyncOutgoingBatch(\n ordinaryPendingUpdates,\n {\n reservedDataCharacters: recoveryBaseline.updateData.length,\n reservedUpdateCount: 1,\n },\n );\n assertRecoveryBaselineCoversCheckpoints(recoveryBaseline, queuedCheckpoints);\n traceCheckpointRegeneration(input.onSyncTrace, {\n checkpoints: queuedCheckpoints.length,\n documentId: input.writerProjection.documentId,\n updates: selectedOrdinaryPendingUpdates.length,\n });\n return {\n ...base,\n heldBackPendingUpdateIds: queuedCheckpoints.map((update) => update.id),\n pendingUpdates: [recoveryBaseline, ...selectedOrdinaryPendingUpdates],\n staleRecoveryBaselineUpdateId: recoveryBaseline.id,\n };\n}\n\nasync function resolveSyncPlanContentMaterial(\n input: Parameters<typeof buildMaterializedDocumentSyncPlan>[0],\n collectedKeks: Awaited<\n ReturnType<typeof collectContainerKeksForDocumentSync>\n >,\n): Promise<ResolvedSyncPlanContentMaterial> {\n const allPendingUpdates = input.pendingUpdates ?? [];\n if (allPendingUpdates.length > 0 || input.regenerateQueuedCheckpoints) {\n assertDocumentKekPathsCurrent(input.writerProjection);\n }\n const staleContentKeyBundle =\n input.writerProjection.contentKeyBundleStale === true;\n\n if (staleContentKeyBundle && allPendingUpdates.length > 0) {\n traceStaleBundle(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n epoch: input.writerProjection.contentKeyBundle.contentKeyEpoch,\n pending: allPendingUpdates.length,\n });\n return resolveStaleHealMaterial(\n input,\n collectedKeks.keksByEpochId,\n allPendingUpdates,\n );\n }\n\n const pendingUpdates = selectDocumentSyncOutgoingBatch(allPendingUpdates);\n\n if (staleContentKeyBundle) {\n traceStaleRead(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n epoch: input.writerProjection.contentKeyBundle.contentKeyEpoch,\n });\n // Current access includes every predecessor KEK. If damaged history makes\n // this old bundle unreachable, preserve the bridge-integrity failure: this\n // read actually needs that historical epoch and cannot safely continue.\n let staleContentKey: Uint8Array;\n try {\n staleContentKey = await unwrapDocumentContentKeyFromBundle(\n input.writerProjection.contentKeyBundle,\n input.writerProjection.documentId,\n collectedKeks.keksByEpochId,\n collectedKeks.predecessorFailuresByEpochId,\n collectedKeks.unattributedPredecessorFailuresByContainerId,\n );\n } catch (error) {\n if (error instanceof DocumentHistoryUnavailableError) {\n if (\n input.historyMode !== \"raw\" ||\n !(error.historyCause instanceof ContainerKekHistoryUnavailableError)\n ) {\n throw error;\n }\n }\n // A stale bundle can predate the requester's current authorizing links.\n // Keep the read-only pass alive; served updates that need this absent key\n // remain undecryptable until a spanning member heals the bundle.\n staleContentKey = new Uint8Array();\n }\n return {\n contentKey: staleContentKey,\n contentKeyBundle: input.writerProjection.contentKeyBundle,\n documentKekTargets: documentKekTargetsFromContentKeyBundle(\n input.writerProjection.contentKeyBundle,\n ),\n documentManifest: staleBundleDocumentManifest(input.writerProjection),\n healedStaleContentKeyBundle: false,\n heldBackPendingUpdateIds: [],\n pendingUpdates,\n };\n }\n\n const normalMaterial: ResolvedSyncPlanContentMaterial = {\n contentKey: await unwrapDocumentContentKeyFromBundle(\n input.writerProjection.contentKeyBundle,\n input.writerProjection.documentId,\n collectedKeks.keksByEpochId,\n collectedKeks.predecessorFailuresByEpochId,\n collectedKeks.unattributedPredecessorFailuresByContainerId,\n ),\n contentKeyBundle: input.writerProjection.contentKeyBundle,\n documentKekTargets: input.writerProjection.documentKekTargets,\n documentManifest: input.writerProjection.documentManifest,\n healedStaleContentKeyBundle: false,\n heldBackPendingUpdateIds: [],\n pendingUpdates,\n };\n if (\n input.regenerateQueuedCheckpoints === true &&\n allPendingUpdates.some((update) => update.sourceVersionVector != null)\n ) {\n return resolveCheckpointRegenerationMaterial(\n input,\n normalMaterial,\n allPendingUpdates,\n );\n }\n\n return normalMaterial;\n}\n\nexport async function buildMaterializedDocumentSyncPlan(\n input: {\n author: DocumentCreateAuthor;\n /**\n * Supplies a full-history Loro snapshot of the local document when a\n * stale content-key bundle must be healed, or when a leftover queued\n * rotation checkpoint must be regenerated as a covering baseline.\n * Without it those passes fail with a descriptive error instead.\n */\n buildRotationSnapshot?: (() => Promise<Uint8Array | null>) | undefined;\n containerRekeys?: BuildDocumentSyncPlanInput[\"containerRekeys\"];\n execSql?: ExecSql | undefined;\n historyMode?: \"raw\" | undefined;\n inlineRekeyCommitId?: string | undefined;\n localVersionVector: string | null;\n minLsn?: string | undefined;\n pullCursor?: string | undefined;\n /** Clipboard-safe trace sink (see syncTrace.ts); never receives content. */\n onSyncTrace?: DocumentSyncTraceEmitter | undefined;\n pendingUpdates?: readonly PendingUpdateRecord[] | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n /**\n * Replace queued rotation checkpoints with a freshly regenerated covering\n * baseline instead of passing them through. Set by the sync loop after\n * the server rejected a pass via the covering-baseline gate.\n */\n regenerateQueuedCheckpoints?: boolean | undefined;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<MaterializedDocumentSyncPlan> {\n // Reuse verification across consistency and unwrap passes; unwrap still\n // binds the key material independently.\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache = new Map<string, VerifiedPrincipalPolicy>();\n let writerAuthorization: DocumentWriterProjectionAuthorization | undefined;\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n allowStaleContentKeyBundle: true,\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n onVerifiedAuthorization: (authorization) => {\n writerAuthorization = authorization;\n },\n principalPolicyCache,\n verifiedByHash,\n ...projectionVerificationOptions(input),\n });\n const collectedKeks = await collectContainerKeksForDocumentSync({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache,\n secretKey: input.targetSecretKey,\n verifiedByHash,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n const documentId = input.writerProjection.documentId;\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document sync manifest\",\n });\n let material: ResolvedSyncPlanContentMaterial;\n try {\n material = await resolveSyncPlanContentMaterial(input, collectedKeks);\n } catch (error) {\n // Only a stale-bundle HEAL (write-bearing) or a checkpoint regeneration\n // counts as a blocked recovery; an ordinary pass or a stale READ failing\n // here must not read as one in a support report. Enumerated reason only;\n // unknown errors emit nothing (fail closed).\n if (\n (input.writerProjection.contentKeyBundleStale === true &&\n (input.pendingUpdates ?? []).length > 0) ||\n input.regenerateQueuedCheckpoints === true\n ) {\n traceHealBlocked(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n error,\n });\n }\n throw error;\n }\n const {\n contentKey,\n contentKeyBundle,\n documentKekTargets,\n documentManifest,\n pendingUpdates,\n } = material;\n const outgoingUpdates = await prepareDocumentOutgoingUpdates({\n contentKey,\n contentKeyEpoch: contentKeyBundle.contentKeyEpoch,\n documentId,\n organizationId: manifestIdentity.organizationId,\n pendingUpdates,\n });\n const basePlan = await buildDocumentSyncPlan({\n author: {\n ...input.author,\n organizationId: manifestIdentity.organizationId,\n },\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.writerProjection,\n ),\n containerRekeys: input.containerRekeys,\n contentKeyBundle,\n documentId,\n documentKekTargets,\n documentManifest,\n historyMode: input.historyMode,\n inlineRekeyCommitId: input.inlineRekeyCommitId,\n localVersionVector: input.localVersionVector,\n minLsn: input.minLsn,\n outgoingUpdates,\n pullCursor: input.pullCursor,\n signedAt: input.signedAt,\n });\n return finalizeMaterializedDocumentSyncPlan({\n basePlan,\n material,\n writerAuthorization,\n writerProjection: input.writerProjection,\n });\n}\n"]}
1
+ {"version":3,"file":"syncPlanMaterial.js","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;QAC/C,cAAc;KACf,CAAC,CAAC;IACH,MAAM,QAAQ,GAAG,MAAM,qBAAqB,CAAC;QAC3C,MAAM,EAAE;YACN,GAAG,KAAK,CAAC,MAAM;YACf,cAAc,EAAE,gBAAgB,CAAC,cAAc;SAChD;QACD,4BAA4B,EAAE,4BAA4B,CACxD,KAAK,CAAC,gBAAgB,CACvB;QACD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB;QAChB,UAAU;QACV,kBAAkB;QAClB,gBAAgB;QAChB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,eAAe;QACf,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,QAAQ,EAAE,KAAK,CAAC,QAAQ;KACzB,CAAC,CAAC;IACH,OAAO,oCAAoC,CAAC;QAC1C,QAAQ;QACR,QAAQ;QACR,mBAAmB;QACnB,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;KACzC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n VerifiedContainerAccessManifest,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport {\n emptyVersionVector,\n getImportBlobMetadata,\n satisfiesVersionVector,\n versionVectorsEqual,\n} from \"@tearleads/loro\";\nimport type {\n DocumentCreateResponse,\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { documentKekTargetsFromContentKeyBundle } from \"@tearleads/validators/response\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport { assertDocumentKekPathsCurrent } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport {\n assertDocumentWriterProjectionConsistent,\n authorizingContainerPathRefs,\n buildRotatedDocumentContentKeyBundle,\n ContainerKekHistoryUnavailableError,\n collectContainerKeksForDocumentSync,\n DocumentHistoryUnavailableError,\n unwrapDocumentContentKeyFromBundle,\n} from \"../../../data/documents/shared/projection\";\nimport { assertDocumentManifestBundleConsistent } from \"../../../data/documents/shared/readers\";\nimport type {\n BuildDocumentSyncPlanInput,\n DocumentCreateAuthor,\n MaterializedDocumentSyncPlan,\n ProjectionVerificationOptions,\n} from \"../../../data/documents/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/types\";\nimport type { DocumentWriterProjectionAuthorization } from \"../../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../../data/sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { selectDocumentSyncOutgoingBatch } from \"../../../data/sync/documentSyncOutgoingBatch\";\nimport {\n type DocumentSyncTraceEmitter,\n traceCheckpointRegeneration,\n traceHealBlocked,\n traceHealPlanned,\n traceStaleBundle,\n traceStaleRead,\n} from \"../sync/syncTrace\";\nimport { prepareDocumentOutgoingUpdates } from \"./syncContentKeys\";\nimport { buildDocumentSyncPlan } from \"./syncPlanIdentity\";\nimport { finalizeMaterializedDocumentSyncPlan } from \"./syncPlanProjection\";\n\n/**\n * Builds the rotation baseline that anchors a stale-bundle heal: a full\n * history snapshot of the local document, re-encrypted under the fresh\n * content key so every current member (including post-rotation newcomers)\n * has an efficient current-epoch redirect. Predecessor KEKs remain the\n * correctness path when no covering baseline exists.\n */\nasync function buildStaleRecoveryBaselinePendingUpdate(\n buildRotationSnapshot: (() => Promise<Uint8Array | null>) | undefined,\n): Promise<PendingUpdateRecord> {\n const snapshot = buildRotationSnapshot ? await buildRotationSnapshot() : null;\n if (!snapshot) {\n throw new Error(\n \"Document content-key bundle is stale and no rotation snapshot is available to heal it\",\n );\n }\n const metadata = getImportBlobMetadata(snapshot);\n if (\n metadata.mode !== \"snapshot\" ||\n !versionVectorsEqual(\n metadata.partialStartVersionVector,\n emptyVersionVector(),\n )\n ) {\n throw new Error(\n \"Document stale-bundle recovery requires a full-history rotation snapshot\",\n );\n }\n const pendingFields = createPendingUpdateFields(\n snapshot,\n metadata.partialEndVersionVector,\n );\n if (!pendingFields) {\n throw new Error(\"Document stale-bundle recovery snapshot is empty\");\n }\n\n return {\n id: crypto.randomUUID(),\n ...pendingFields,\n };\n}\n\n/**\n * Resolves the content material a sync plan encrypts and carries. A stale\n * bundle names predecessor KEK targets while the document's current targets\n * name successor epochs, so it splits by intent: a write-bearing pass heals\n * the document with a FRESH content key at the next epoch, anchored by a\n * covering rotation baseline, while a read-only pass keeps the stale pair and\n * unwraps it through predecessor KEKs so the server can settle a complete pull.\n */\n/**\n * The manifest bundle a stale read-only plan must pair with: the one the\n * stale content-key bundle actually references. A stale bundle normally\n * still carries the current link-set manifest hash (KEK rotations do not\n * advance the document manifest), but the projection consistency check\n * defensively admits a bundle lagging the head as long as it appears in the\n * manifest history — pair with that historical bundle so the plan's own\n * identity checks hold.\n */\nfunction staleBundleDocumentManifest(\n writerProjection: DocumentWriterProjectionResponse,\n): DocumentCreateResponse[\"accessManifest\"] {\n const { contentKeyBundle, documentManifest } = writerProjection;\n if (contentKeyBundle.linkSetManifestHash === documentManifest.manifestHash) {\n return documentManifest;\n }\n const historicalManifest = writerProjection.documentManifestHistory.find(\n (bundle) => bundle.manifestHash === contentKeyBundle.linkSetManifestHash,\n );\n if (!historicalManifest) {\n throw new Error(\n \"Document stale bundle manifest is missing from the projection history\",\n );\n }\n return historicalManifest;\n}\n\n/**\n * Settling a superseded checkpoint deletes its queue row, so the fresh\n * baseline must PROVABLY subsume it — assumed coverage would silently drop\n * any ops the checkpoint alone carried.\n */\nfunction assertRecoveryBaselineCoversCheckpoints(\n recoveryBaseline: PendingUpdateRecord,\n checkpoints: readonly PendingUpdateRecord[],\n): void {\n for (const checkpoint of checkpoints) {\n if (\n !satisfiesVersionVector(\n recoveryBaseline.partialEndVersionVector,\n checkpoint.partialEndVersionVector,\n )\n ) {\n throw new Error(\n \"Document stale-bundle recovery snapshot does not cover a queued rotation checkpoint\",\n );\n }\n }\n}\n\ninterface ResolvedSyncPlanContentMaterial {\n contentKey: Uint8Array;\n contentKeyBundle: DocumentCreateResponse[\"contentKeyBundle\"];\n documentKekTargets: DocumentSyncResponse[\"documentKekTargets\"];\n documentManifest: DocumentCreateResponse[\"accessManifest\"];\n healedStaleContentKeyBundle: boolean;\n heldBackPendingUpdateIds: readonly string[];\n pendingUpdates: readonly PendingUpdateRecord[];\n staleRecoveryBaselineUpdateId?: string;\n}\n\nasync function resolveStaleHealMaterial(\n input: Parameters<typeof buildMaterializedDocumentSyncPlan>[0],\n containerKeksByEpochId: ReadonlyMap<string, Uint8Array>,\n pendingUpdates: readonly PendingUpdateRecord[],\n): Promise<ResolvedSyncPlanContentMaterial> {\n const contentKey = crypto.getRandomValues(new Uint8Array(32));\n // A rotation checkpoint left in the queue by an interrupted earlier\n // recovery is superseded by the fresh covering baseline built below:\n // submitting it alongside would trip the server's covering-baseline gate,\n // and resubmitting it after the heal could become the latest baseline at\n // the healed epoch and mask the covering one. Hold it out of the request;\n // on heal success its id is reported settled (the committed baseline\n // subsumes its full-history content) so the queue row is removed.\n //\n // A heal whose OWN baseline does not cover the committed frontier is\n // rejected by that same gate and surfaces as a terminal queue failure.\n // This write-bearing pass does not pull first. A device missing committed\n // history can independently rematerialize it through predecessor KEKs on a\n // read-only pass, then retry with a covering snapshot. The coverage proof\n // prevents a partial local view from becoming the redirect baseline.\n const ordinaryPendingUpdates = pendingUpdates.filter(\n (update) => update.sourceVersionVector == null,\n );\n const heldBackCheckpoints = pendingUpdates.filter(\n (update) => update.sourceVersionVector != null,\n );\n const recoveryBaseline = await buildStaleRecoveryBaselinePendingUpdate(\n input.buildRotationSnapshot,\n );\n const selectedOrdinaryPendingUpdates = selectDocumentSyncOutgoingBatch(\n ordinaryPendingUpdates,\n {\n reservedDataCharacters: recoveryBaseline.updateData.length,\n reservedUpdateCount: 1,\n },\n );\n assertRecoveryBaselineCoversCheckpoints(\n recoveryBaseline,\n heldBackCheckpoints,\n );\n const staleEpoch = input.writerProjection.contentKeyBundle.contentKeyEpoch;\n const contentKeyBundle = await buildRotatedDocumentContentKeyBundle({\n containerKeksByEpochId,\n contentKey,\n writerProjection: input.writerProjection,\n });\n traceHealPlanned(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n fromEpoch: staleEpoch,\n heldBack: heldBackCheckpoints.length,\n toEpoch: contentKeyBundle.contentKeyEpoch,\n updates: selectedOrdinaryPendingUpdates.length,\n });\n return {\n contentKey,\n contentKeyBundle,\n documentKekTargets: input.writerProjection.documentKekTargets,\n documentManifest: input.writerProjection.documentManifest,\n healedStaleContentKeyBundle: true,\n heldBackPendingUpdateIds: heldBackCheckpoints.map((update) => update.id),\n pendingUpdates: [recoveryBaseline, ...selectedOrdinaryPendingUpdates],\n staleRecoveryBaselineUpdateId: recoveryBaseline.id,\n };\n}\n\n/**\n * Reactive repair for a healthy-projection pass whose queued rotation\n * checkpoint the server rejected via the covering-baseline gate (a leftover\n * from an interrupted recovery, a heal whose ack was lost, or a lost heal\n * race). Queued checkpoints normally pass through untouched — reset and\n * rotation flows legitimately submit them — but a rejected one would strand\n * the whole queue, and committing it could shrink redirect coverage. Replace\n * the stale checkpoints with one freshly regenerated covering baseline and\n * settle them on success (coverage proven above).\n */\nasync function resolveCheckpointRegenerationMaterial(\n input: Parameters<typeof buildMaterializedDocumentSyncPlan>[0],\n base: ResolvedSyncPlanContentMaterial,\n pendingUpdates: readonly PendingUpdateRecord[],\n): Promise<ResolvedSyncPlanContentMaterial> {\n const ordinaryPendingUpdates = pendingUpdates.filter(\n (update) => update.sourceVersionVector == null,\n );\n const queuedCheckpoints = pendingUpdates.filter(\n (update) => update.sourceVersionVector != null,\n );\n const recoveryBaseline = await buildStaleRecoveryBaselinePendingUpdate(\n input.buildRotationSnapshot,\n );\n const selectedOrdinaryPendingUpdates = selectDocumentSyncOutgoingBatch(\n ordinaryPendingUpdates,\n {\n reservedDataCharacters: recoveryBaseline.updateData.length,\n reservedUpdateCount: 1,\n },\n );\n assertRecoveryBaselineCoversCheckpoints(recoveryBaseline, queuedCheckpoints);\n traceCheckpointRegeneration(input.onSyncTrace, {\n checkpoints: queuedCheckpoints.length,\n documentId: input.writerProjection.documentId,\n updates: selectedOrdinaryPendingUpdates.length,\n });\n return {\n ...base,\n heldBackPendingUpdateIds: queuedCheckpoints.map((update) => update.id),\n pendingUpdates: [recoveryBaseline, ...selectedOrdinaryPendingUpdates],\n staleRecoveryBaselineUpdateId: recoveryBaseline.id,\n };\n}\n\nasync function resolveSyncPlanContentMaterial(\n input: Parameters<typeof buildMaterializedDocumentSyncPlan>[0],\n collectedKeks: Awaited<\n ReturnType<typeof collectContainerKeksForDocumentSync>\n >,\n): Promise<ResolvedSyncPlanContentMaterial> {\n const allPendingUpdates = input.pendingUpdates ?? [];\n if (allPendingUpdates.length > 0 || input.regenerateQueuedCheckpoints) {\n assertDocumentKekPathsCurrent(input.writerProjection);\n }\n const staleContentKeyBundle =\n input.writerProjection.contentKeyBundleStale === true;\n\n if (staleContentKeyBundle && allPendingUpdates.length > 0) {\n traceStaleBundle(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n epoch: input.writerProjection.contentKeyBundle.contentKeyEpoch,\n pending: allPendingUpdates.length,\n });\n return resolveStaleHealMaterial(\n input,\n collectedKeks.keksByEpochId,\n allPendingUpdates,\n );\n }\n\n const pendingUpdates = selectDocumentSyncOutgoingBatch(allPendingUpdates);\n\n if (staleContentKeyBundle) {\n traceStaleRead(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n epoch: input.writerProjection.contentKeyBundle.contentKeyEpoch,\n });\n // Current access includes every predecessor KEK. If damaged history makes\n // this old bundle unreachable, preserve the bridge-integrity failure: this\n // read actually needs that historical epoch and cannot safely continue.\n let staleContentKey: Uint8Array;\n try {\n staleContentKey = await unwrapDocumentContentKeyFromBundle(\n input.writerProjection.contentKeyBundle,\n input.writerProjection.documentId,\n collectedKeks.keksByEpochId,\n collectedKeks.predecessorFailuresByEpochId,\n collectedKeks.unattributedPredecessorFailuresByContainerId,\n );\n } catch (error) {\n if (error instanceof DocumentHistoryUnavailableError) {\n if (\n input.historyMode !== \"raw\" ||\n !(error.historyCause instanceof ContainerKekHistoryUnavailableError)\n ) {\n throw error;\n }\n }\n // A stale bundle can predate the requester's current authorizing links.\n // Keep the read-only pass alive; served updates that need this absent key\n // remain undecryptable until a spanning member heals the bundle.\n staleContentKey = new Uint8Array();\n }\n return {\n contentKey: staleContentKey,\n contentKeyBundle: input.writerProjection.contentKeyBundle,\n documentKekTargets: documentKekTargetsFromContentKeyBundle(\n input.writerProjection.contentKeyBundle,\n ),\n documentManifest: staleBundleDocumentManifest(input.writerProjection),\n healedStaleContentKeyBundle: false,\n heldBackPendingUpdateIds: [],\n pendingUpdates,\n };\n }\n\n const normalMaterial: ResolvedSyncPlanContentMaterial = {\n contentKey: await unwrapDocumentContentKeyFromBundle(\n input.writerProjection.contentKeyBundle,\n input.writerProjection.documentId,\n collectedKeks.keksByEpochId,\n collectedKeks.predecessorFailuresByEpochId,\n collectedKeks.unattributedPredecessorFailuresByContainerId,\n ),\n contentKeyBundle: input.writerProjection.contentKeyBundle,\n documentKekTargets: input.writerProjection.documentKekTargets,\n documentManifest: input.writerProjection.documentManifest,\n healedStaleContentKeyBundle: false,\n heldBackPendingUpdateIds: [],\n pendingUpdates,\n };\n if (\n input.regenerateQueuedCheckpoints === true &&\n allPendingUpdates.some((update) => update.sourceVersionVector != null)\n ) {\n return resolveCheckpointRegenerationMaterial(\n input,\n normalMaterial,\n allPendingUpdates,\n );\n }\n\n return normalMaterial;\n}\n\nexport async function buildMaterializedDocumentSyncPlan(\n input: {\n author: DocumentCreateAuthor;\n /**\n * Supplies a full-history Loro snapshot of the local document when a\n * stale content-key bundle must be healed, or when a leftover queued\n * rotation checkpoint must be regenerated as a covering baseline.\n * Without it those passes fail with a descriptive error instead.\n */\n buildRotationSnapshot?: (() => Promise<Uint8Array | null>) | undefined;\n containerRekeys?: BuildDocumentSyncPlanInput[\"containerRekeys\"];\n execSql?: ExecSql | undefined;\n historyMode?: \"raw\" | undefined;\n inlineRekeyCommitId?: string | undefined;\n localVersionVector: string | null;\n minLsn?: string | undefined;\n pullCursor?: string | undefined;\n /** Clipboard-safe trace sink (see syncTrace.ts); never receives content. */\n onSyncTrace?: DocumentSyncTraceEmitter | undefined;\n pendingUpdates?: readonly PendingUpdateRecord[] | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n /**\n * Replace queued rotation checkpoints with a freshly regenerated covering\n * baseline instead of passing them through. Set by the sync loop after\n * the server rejected a pass via the covering-baseline gate.\n */\n regenerateQueuedCheckpoints?: boolean | undefined;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<MaterializedDocumentSyncPlan> {\n // Reuse verification across consistency and unwrap passes; unwrap still\n // binds the key material independently.\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache = new Map<string, VerifiedPrincipalPolicy>();\n let writerAuthorization: DocumentWriterProjectionAuthorization | undefined;\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n allowStaleContentKeyBundle: true,\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n onVerifiedAuthorization: (authorization) => {\n writerAuthorization = authorization;\n },\n principalPolicyCache,\n verifiedByHash,\n ...projectionVerificationOptions(input),\n });\n const collectedKeks = await collectContainerKeksForDocumentSync({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache,\n secretKey: input.targetSecretKey,\n verifiedByHash,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n const documentId = input.writerProjection.documentId;\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document sync manifest\",\n });\n let material: ResolvedSyncPlanContentMaterial;\n try {\n material = await resolveSyncPlanContentMaterial(input, collectedKeks);\n } catch (error) {\n // Only a stale-bundle HEAL (write-bearing) or a checkpoint regeneration\n // counts as a blocked recovery; an ordinary pass or a stale READ failing\n // here must not read as one in a support report. Enumerated reason only;\n // unknown errors emit nothing (fail closed).\n if (\n (input.writerProjection.contentKeyBundleStale === true &&\n (input.pendingUpdates ?? []).length > 0) ||\n input.regenerateQueuedCheckpoints === true\n ) {\n traceHealBlocked(input.onSyncTrace, {\n documentId: input.writerProjection.documentId,\n error,\n });\n }\n throw error;\n }\n const {\n contentKey,\n contentKeyBundle,\n documentKekTargets,\n documentManifest,\n pendingUpdates,\n } = material;\n const outgoingUpdates = await prepareDocumentOutgoingUpdates({\n contentKey,\n contentKeyEpoch: contentKeyBundle.contentKeyEpoch,\n documentId,\n organizationId: manifestIdentity.organizationId,\n pendingUpdates,\n });\n const basePlan = await buildDocumentSyncPlan({\n author: {\n ...input.author,\n organizationId: manifestIdentity.organizationId,\n },\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.writerProjection,\n ),\n containerRekeys: input.containerRekeys,\n contentKeyBundle,\n documentId,\n documentKekTargets,\n documentManifest,\n historyMode: input.historyMode,\n inlineRekeyCommitId: input.inlineRekeyCommitId,\n localVersionVector: input.localVersionVector,\n minLsn: input.minLsn,\n outgoingUpdates,\n pullCursor: input.pullCursor,\n signedAt: input.signedAt,\n });\n return finalizeMaterializedDocumentSyncPlan({\n basePlan,\n material,\n writerAuthorization,\n writerProjection: input.writerProjection,\n });\n}\n"]}
@@ -1,11 +1,11 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
2
  import { MAX_INLINE_CONTAINER_REKEYS } from "../../../internal/validators/util/index.js";
3
3
  import { ContainerAuthorAccessError } from "../../../data/containers/shared/authorAccess.js";
4
- import { ContainerKekRepairInaccessibleError } from "../../../data/documents/shared/containerKekCurrency.js";
5
- import { ContainerKekTargetUnreachableError } from "../../../data/documents/shared/containerKekPath.js";
6
- import { documentContainerProjections } from "../../../data/keyingProjectionVerification/documentContainerProjections.js";
4
+ import { ContainerKekRepairInaccessibleError } from "../../../data/documents/shared/containerKek/containerKekCurrency.js";
5
+ import { ContainerKekTargetUnreachableError } from "../../../data/documents/shared/containerKek/containerKekPath.js";
6
+ import { documentContainerProjections } from "../../../data/keyingProjectionVerification/document/documentContainerProjections.js";
7
7
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
8
- import { buildMaterializedContainerRekeyPlan } from "../../containers/child/rekey.js";
8
+ import { buildMaterializedContainerRekeyPlan } from "../../containers/child/rekey/index.js";
9
9
  import { DocumentAncestorRepairAbandonedError } from "../syncFailures/syncRepairAbandon.js";
10
10
  import { hasOtherLinkedWriteAccess } from "../syncFailures/syncRepairAccess.js";
11
11
  import { applyContainerRekeyPlan } from "./syncContainerRekeyProjection.js";
@@ -1 +1 @@
1
- {"version":3,"file":"syncAutomaticContainerRekeys.js","sourceRoot":"","sources":["syncAutomaticContainerRekeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAE1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,qDAAqD,CAAC;AAC1G,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AACrG,OAAO,EAAE,4BAA4B,EAAE,MAAM,yEAAyE,CAAC;AACvH,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,8BAA8B,CAAC;AAEnF,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAQzE,SAAS,mBAAmB,CAC1B,UAA4C;IAE5C,KAAK,MAAM,IAAI,IA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wBAAwB;YACvD,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,+BAA+B,EAAE,IAAI,CAAC,+BAA+B;YACrE,OAAO,EAAE,IAAI,CAAC,OAAO;SACtB,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,KAAc,EAAE,EAAE;YAChC,IAAI,KAAK,YAAY,0BAA0B,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;gBACtE,IACE,MAAM,yBAAyB,CAC7B,IAAI,EACJ,iBAAiB,EACjB,kBAAkB,CAAC,WAAW,CAC/B,EACD,CAAC;oBACD,MAAM,IAAI,mCAAmC,CAC3C,kBAAkB,CAAC,WAAW,CAC/B,CAAC;gBACJ,CAAC;gBACD,MAAM,IAAI,CAAC,uBAAuB,EAAE,CAAC;oBACnC,IAAI,EAAE,KAAK,CAAC,IAAI;oBAChB,OAAO,EAAE,KAAK,CAAC,OAAO;oBACtB,EAAE,EAAE,KAAK;oBACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;oBACvB,MAAM,EAAE,KAAK,CAAC,MAAM;iBACrB,CAAC,CAAC;gBACH,MAAM,IAAI,oCAAoC,CAAC,SAAS,CAAC,CAAC;YAC5D,CAAC;YACD,qEAAqE;YACrE,uEAAuE;YACvE,uEAAuE;YACvE,MAAM,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC;gBACtC,CAAC,CAAC,IAAI,mCAAmC,CACrC,kBAAkB,CAAC,WAAW,CAC/B;gBACH,CAAC,CAAC,KAAK,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,UAAU,CAAC,GAAG,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAC/C,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpB,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKekPath\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../../containers/child/rekey\";\nimport type { SyncRemoteDocumentInput } from \"../sync/readOnlySync\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"../syncFailures/syncRepairAccess\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n },\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: SyncRemoteDocumentInput,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}
1
+ {"version":3,"file":"syncAutomaticContainerRekeys.js","sourceRoot":"","sources":["syncAutomaticContainerRekeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAE1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kEAAkE,CAAC;AACvH,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,8BAA8B,CAAC;AAEnF,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,yBAAyB,EAAE,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,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../../containers/child/rekey\";\nimport type { SyncRemoteDocumentInput } from \"../sync/readOnlySync\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"../syncFailures/syncRepairAccess\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n },\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: SyncRemoteDocumentInput,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}