@tearleads/client-sdk 0.1.64 → 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 (622) hide show
  1. package/client/organizations/organizationAccessRestoration.js +1 -1
  2. package/data/containers/shared/mutationAcknowledgement.js +1 -1
  3. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  4. package/data/documents/blob/shared/projection.js +3 -3
  5. package/data/documents/blob/shared/projection.js.map +1 -1
  6. package/data/documents/shared/{containerKekCurrency.d.ts → containerKek/containerKekCurrency.d.ts} +1 -1
  7. package/data/documents/shared/{containerKekEntryVerification.js → containerKek/containerKekEntryVerification.js} +1 -1
  8. package/data/documents/shared/{containerKekLogFetch.d.ts → containerKek/containerKekLogFetch.d.ts} +1 -1
  9. package/data/documents/shared/{containerKekLogFetch.js → containerKek/containerKekLogFetch.js} +1 -1
  10. package/data/documents/shared/{containerKekPath.js → containerKek/containerKekPath.js} +3 -3
  11. package/data/documents/shared/containerKek/containerKekPath.js.map +1 -0
  12. package/data/documents/shared/{containerKekPathHistory.d.ts → containerKek/containerKekPathHistory.d.ts} +3 -3
  13. package/data/documents/shared/{containerKekPathHistory.js → containerKek/containerKekPathHistory.js} +4 -4
  14. package/data/documents/shared/containerKek/containerKekPathHistory.js.map +1 -0
  15. package/data/documents/shared/{containerKekPathVerification.d.ts → containerKek/containerKekPathVerification.d.ts} +5 -5
  16. package/data/documents/shared/{containerKekPathVerification.js → containerKek/containerKekPathVerification.js} +2 -2
  17. package/data/documents/shared/containerKek/containerKekPathVerification.js.map +1 -0
  18. package/data/documents/shared/{containerKekWrapping.js → containerKek/containerKekWrapping.js} +3 -3
  19. package/data/documents/shared/containerKek/containerKekWrapping.js.map +1 -0
  20. package/data/documents/shared/{keyringLogWalk.d.ts → containerKek/keyringLogWalk.d.ts} +2 -2
  21. package/data/documents/shared/{keyringLogWalk.js → containerKek/keyringLogWalk.js} +1 -1
  22. package/data/documents/shared/{keyringRebuild.d.ts → containerKek/keyringRebuild.d.ts} +3 -3
  23. package/data/documents/shared/{keyringRebuild.js → containerKek/keyringRebuild.js} +3 -3
  24. package/data/documents/shared/containerKek/keyringRebuild.js.map +1 -0
  25. package/data/documents/shared/crypto.js +2 -2
  26. package/data/documents/shared/crypto.js.map +1 -1
  27. package/data/documents/shared/events.js +1 -1
  28. package/data/documents/shared/{projection.d.ts → projection/index.d.ts} +7 -7
  29. package/data/documents/shared/{projection.js → projection/index.js} +9 -9
  30. package/data/documents/shared/projection/index.js.map +1 -0
  31. package/data/documents/shared/{projectionContentKeys.d.ts → projection/projectionContentKeys.d.ts} +6 -6
  32. package/data/documents/shared/{projectionContentKeys.js → projection/projectionContentKeys.js} +9 -9
  33. package/data/documents/shared/projection/projectionContentKeys.js.map +1 -0
  34. package/data/documents/shared/{projectionTargets.d.ts → projection/projectionTargets.d.ts} +4 -4
  35. package/data/documents/shared/{projectionTargets.js → projection/projectionTargets.js} +3 -3
  36. package/data/documents/shared/projection/projectionTargets.js.map +1 -0
  37. package/data/documents/shared/responses.d.ts +1 -1
  38. package/data/documents/shared/responses.js +1 -1
  39. package/data/documents/shared/responses.js.map +1 -1
  40. package/data/documents/shared/{documentSyncUpdateDecryption.js → sync/documentSyncUpdateDecryption.js} +10 -10
  41. package/data/documents/shared/sync/documentSyncUpdateDecryption.js.map +1 -0
  42. package/data/documents/shared/{documentSyncUpdateIsolation.d.ts → sync/documentSyncUpdateIsolation.d.ts} +3 -3
  43. package/data/documents/shared/{documentSyncUpdateIsolation.js → sync/documentSyncUpdateIsolation.js} +1 -1
  44. package/data/documents/shared/sync/documentSyncUpdateIsolation.js.map +1 -0
  45. package/data/documents/shared/{mutationAcknowledgement.js → sync/mutationAcknowledgement.js} +1 -1
  46. package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -0
  47. package/data/documents/shared/{pullContinuation.js → sync/pullContinuation.js} +1 -1
  48. package/data/documents/shared/{syncPagination.d.ts → sync/syncPagination.d.ts} +2 -2
  49. package/data/documents/shared/{syncPagination.js → sync/syncPagination.js} +1 -1
  50. package/data/documents/shared/sync/syncPagination.js.map +1 -0
  51. package/data/documents/shared/{syncResponseAuthorization.js → sync/syncResponseAuthorization.js} +3 -3
  52. package/data/documents/shared/sync/syncResponseAuthorization.js.map +1 -0
  53. package/data/documents/shared/{syncResponses.d.ts → sync/syncResponses.d.ts} +2 -2
  54. package/data/documents/shared/{syncResponses.js → sync/syncResponses.js} +6 -6
  55. package/data/documents/shared/sync/syncResponses.js.map +1 -0
  56. package/data/documents/shared/{syncSubmitFailure.d.ts → sync/syncSubmitFailure.d.ts} +1 -1
  57. package/data/documents/shared/types.d.ts +3 -3
  58. package/data/documents/shared/types.js.map +1 -1
  59. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js +1 -1
  60. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js.map +1 -1
  61. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +1 -1
  62. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
  63. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  64. package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js +1 -1
  65. package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js.map +1 -1
  66. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +4 -4
  67. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  68. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js +1 -1
  69. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js.map +1 -1
  70. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js +1 -1
  71. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js.map +1 -1
  72. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js +1 -1
  73. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js.map +1 -1
  74. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +3 -3
  75. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  76. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +4 -4
  77. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  78. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js +2 -2
  79. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js.map +1 -1
  80. package/data/persistence/container-contents/containerContentsPersistence.js +3 -3
  81. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  82. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -2
  83. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  84. package/data/persistence/container-contents/containerCreateIntentSettlement.js +1 -1
  85. package/data/persistence/container-contents/containerDeletionPersistence.js +2 -2
  86. package/data/persistence/container-contents/containerDocumentReassignment.js +2 -2
  87. package/data/persistence/container-contents/containerDocumentReassignment.js.map +1 -1
  88. package/data/persistence/container-contents/containerHydrationPersistence.js +3 -3
  89. package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
  90. package/data/persistence/container-contents/containerIntentPersistence.js +1 -1
  91. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +5 -5
  92. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  93. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +1 -1
  94. package/data/persistence/container-contents/containerMetadataRows.js +3 -3
  95. package/data/persistence/container-contents/containerMetadataRows.js.map +1 -1
  96. package/data/persistence/container-contents/containerMoveAbandonPersistence.js +1 -1
  97. package/data/persistence/container-contents/containerMoveIntentRows.js +1 -1
  98. package/data/persistence/container-contents/containerPendingUpdatePersistence.js +3 -3
  99. package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
  100. package/data/persistence/container-contents/containerRebindPersistence.js +1 -1
  101. package/data/persistence/container-contents/containerReconcilePersistence.js +2 -2
  102. package/data/persistence/container-contents/containerRecoveryPersistence.js +1 -1
  103. package/data/persistence/container-contents/containerRemovalWork.js +3 -3
  104. package/data/persistence/container-contents/containerRemovalWork.js.map +1 -1
  105. package/data/persistence/container-contents/containerStructuralRepair.js +1 -1
  106. package/data/persistence/container-contents/documentLinkRemovalRepair.js +2 -2
  107. package/data/persistence/container-contents/documentLinkRemovalRepair.js.map +1 -1
  108. package/data/persistence/container-contents/documentMoveIntentPersistence.js +2 -2
  109. package/data/persistence/container-contents/documentMoveIntentPersistence.js.map +1 -1
  110. package/data/persistence/container-contents/documentPlacementIntentEnqueue.js +2 -2
  111. package/data/persistence/container-contents/documentPlacementIntentEnqueue.js.map +1 -1
  112. package/data/persistence/container-contents/documentPurgePlacement.js +1 -1
  113. package/data/persistence/container-contents/dormantContainerMetadata.js +1 -1
  114. package/data/persistence/container-contents/dormantMetadataSweep.js +1 -1
  115. package/data/persistence/container-contents/pendingContainerCreate.js +1 -1
  116. package/data/persistence/container-contents/supersededContainerBindings.js +1 -1
  117. package/data/persistence/containers/containerPersistence.js +1 -1
  118. package/data/persistence/containers/containerSyncWatermarkPersistence.js +1 -1
  119. package/data/persistence/containers/documentContainerProjectionPersistence.js +1 -1
  120. package/data/persistence/containers/documentPlacement.js +1 -1
  121. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js +1 -1
  122. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +3 -3
  123. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  124. package/data/persistence/documents/documentDiscoveryReset.js +1 -1
  125. package/data/persistence/documents/documentDiscoveryReset.js.map +1 -1
  126. package/data/persistence/documents/documentsPersistence.js +3 -3
  127. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  128. package/data/persistence/documents/internal/attachmentStagingPersistence.js +1 -1
  129. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
  130. package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
  131. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +2 -2
  132. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  133. package/data/persistence/documents/internal/discardDocument.js +3 -3
  134. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  135. package/data/persistence/documents/internal/documentDeletionPersistence.js +4 -4
  136. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  137. package/data/persistence/documents/internal/documentMutationPersistence.js +5 -5
  138. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  139. package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
  140. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
  141. package/data/persistence/documents/internal/documentRows.js +2 -2
  142. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  143. package/data/persistence/documents/internal/documentSummaryQueries.js +1 -1
  144. package/data/persistence/documents/internal/ensureDocumentsSchema.js +2 -2
  145. package/data/persistence/documents/internal/hydratedAttachmentPersistence.js +1 -1
  146. package/data/persistence/documents/internal/orphanSideRows.js +2 -2
  147. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  148. package/data/persistence/documents/internal/pendingCreateAdoption.js +1 -1
  149. package/data/persistence/documents/internal/rowQueryPersistence.js +2 -2
  150. package/data/persistence/documents/internal/syncQueuePersistence.js +3 -3
  151. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  152. package/data/persistence/documents/types.d.ts +3 -3
  153. package/data/persistence/documents/types.js.map +1 -1
  154. package/data/persistence/{documentPurgeCheckpointPersistence.d.ts → keyingCheckpoints/documentPurgeCheckpointPersistence.d.ts} +2 -2
  155. package/data/persistence/{documentPurgeCheckpointPersistence.js → keyingCheckpoints/documentPurgeCheckpointPersistence.js} +4 -4
  156. package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js.map +1 -0
  157. package/data/persistence/{keyingCheckpointAdvancePersistence.js → keyingCheckpoints/keyingCheckpointAdvancePersistence.js} +9 -9
  158. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -0
  159. package/data/persistence/{keyingCheckpointEvidence.js → keyingCheckpoints/keyingCheckpointEvidence.js} +1 -1
  160. package/data/persistence/{keyingCheckpointPersistence.js → keyingCheckpoints/keyingCheckpointPersistence.js} +5 -5
  161. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js.map +1 -0
  162. package/data/persistence/{locallyAcknowledgedCheckpointPersistence.d.ts → keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts} +4 -4
  163. package/data/persistence/{locallyAcknowledgedCheckpointPersistence.js → keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js} +7 -7
  164. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -0
  165. package/data/persistence/{organizationReplacementCheckpointPersistence.js → keyingCheckpoints/organizationReplacementCheckpointPersistence.js} +6 -6
  166. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js.map +1 -0
  167. package/data/persistence/{principalAuthorizationCheckpoints.js → keyingCheckpoints/principalAuthorizationCheckpoints.js} +1 -1
  168. package/data/persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js.map +1 -0
  169. package/data/persistence/organizationFounderPersistence.js +2 -2
  170. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  171. package/data/persistence/organizations/organizationAccessRevocationPersistence.js +3 -3
  172. package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +1 -1
  173. package/data/persistence/organizations/organizationDataUsagePersistence.js +2 -2
  174. package/data/persistence/organizations/organizationDataUsagePersistence.js.map +1 -1
  175. package/data/persistence/organizations/organizationGroupNamePersistence.js +2 -2
  176. package/data/persistence/organizations/organizationGroupNamePersistence.js.map +1 -1
  177. package/data/persistence/organizations/organizationPresentationDenialPersistence.js +2 -2
  178. package/data/persistence/organizations/organizationPresentationDenialPersistence.js.map +1 -1
  179. package/data/persistence/organizations/organizationProfileDocumentPointers.js +2 -2
  180. package/data/persistence/organizations/organizationProfileDocumentPointers.js.map +1 -1
  181. package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js +1 -1
  182. package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js.map +1 -1
  183. package/data/persistence/organizations/organizationReadModelGrantPersistence.js +1 -1
  184. package/data/persistence/organizations/organizationReadModelGrantPersistence.js.map +1 -1
  185. package/data/persistence/organizations/organizationReadModelMemberLoad.js +1 -1
  186. package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
  187. package/data/persistence/organizations/organizationReadModelMembershipPersistence.js +1 -1
  188. package/data/persistence/organizations/organizationReadModelMembershipPersistence.js.map +1 -1
  189. package/data/persistence/organizations/organizationReadModelPersistence.js +3 -3
  190. package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
  191. package/data/persistence/organizations/organizationReadModelProjection.js +1 -1
  192. package/data/persistence/organizations/organizationReadModelProjection.js.map +1 -1
  193. package/data/persistence/organizations/organizationReadModelPurge.js +3 -3
  194. package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
  195. package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +3 -3
  196. package/data/persistence/principalCurrentAcknowledgementPersistence.js +10 -10
  197. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
  198. package/data/persistence/{principalHistoryEvidencePersistence.d.ts → principalHistory/principalHistoryEvidencePersistence.d.ts} +4 -4
  199. package/data/persistence/{principalHistoryEvidencePersistence.js → principalHistory/principalHistoryEvidencePersistence.js} +7 -7
  200. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js.map +1 -0
  201. package/data/persistence/{principalHistoryIncompleteRetention.js → principalHistory/principalHistoryIncompleteRetention.js} +1 -1
  202. package/data/persistence/principalHistory/principalHistoryIncompleteRetention.js.map +1 -0
  203. package/data/persistence/{principalHistoryNodeRetention.js → principalHistory/principalHistoryNodeRetention.js} +4 -4
  204. package/data/persistence/principalHistory/principalHistoryNodeRetention.js.map +1 -0
  205. package/data/persistence/{principalHistoryPrefixPersistence.d.ts → principalHistory/principalHistoryPrefixPersistence.d.ts} +2 -2
  206. package/data/persistence/{principalHistoryPrefixPersistence.js → principalHistory/principalHistoryPrefixPersistence.js} +6 -6
  207. package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js.map +1 -0
  208. package/data/persistence/{principalHistoryRootOwnership.js → principalHistory/principalHistoryRootOwnership.js} +1 -1
  209. package/data/persistence/principalHistory/principalHistoryRootOwnership.js.map +1 -0
  210. package/data/persistence/{principalHistoryStagePersistence.d.ts → principalHistory/principalHistoryStagePersistence.d.ts} +2 -2
  211. package/data/persistence/{principalHistoryStagePersistence.js → principalHistory/principalHistoryStagePersistence.js} +6 -6
  212. package/data/persistence/principalHistory/principalHistoryStagePersistence.js.map +1 -0
  213. package/data/persistence/{principalHistoryStageRetention.js → principalHistory/principalHistoryStageRetention.js} +2 -2
  214. package/data/persistence/principalHistory/principalHistoryStageRetention.js.map +1 -0
  215. package/data/persistence/{principalHistoryUnpublishedRetention.js → principalHistory/principalHistoryUnpublishedRetention.js} +3 -3
  216. package/data/persistence/principalHistory/principalHistoryUnpublishedRetention.js.map +1 -0
  217. package/data/persistence/{principalGrantRetirementPersistence.d.ts → principalKeys/principalGrantRetirementPersistence.d.ts} +2 -2
  218. package/data/persistence/{principalGrantRetirementPersistence.js → principalKeys/principalGrantRetirementPersistence.js} +2 -2
  219. package/data/persistence/principalKeys/principalGrantRetirementPersistence.js.map +1 -0
  220. package/data/persistence/{principalKeyEnvelopeArchivePersistence.js → principalKeys/principalKeyEnvelopeArchivePersistence.js} +3 -3
  221. package/data/persistence/principalKeys/principalKeyEnvelopeArchivePersistence.js.map +1 -0
  222. package/data/persistence/{principalKeyEnvelopeCandidates.js → principalKeys/principalKeyEnvelopeCandidates.js} +9 -9
  223. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -0
  224. package/data/persistence/principalMutationJournalPersistence.d.ts +1 -1
  225. package/data/persistence/principalMutationJournalPersistence.js +1 -1
  226. package/data/persistence/principalMutationJournalPersistence.js.map +1 -1
  227. package/data/persistence/{principalPolicyBundleIntegrity.js → principalPolicy/principalPolicyBundleIntegrity.js} +3 -3
  228. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js.map +1 -0
  229. package/data/persistence/{principalPolicyCheckpointSelection.js → principalPolicy/principalPolicyCheckpointSelection.js} +2 -2
  230. package/data/persistence/principalPolicy/principalPolicyCheckpointSelection.js.map +1 -0
  231. package/data/persistence/{principalPolicyOrganizationPersistence.js → principalPolicy/principalPolicyOrganizationPersistence.js} +2 -2
  232. package/data/persistence/principalPolicy/principalPolicyOrganizationPersistence.js.map +1 -0
  233. package/data/persistence/{principalPolicyPersistence.js → principalPolicy/principalPolicyPersistence.js} +5 -5
  234. package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -0
  235. package/data/persistence/{principalPolicyReferenceCheckpoint.js → principalPolicy/principalPolicyReferenceCheckpoint.js} +3 -3
  236. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js.map +1 -0
  237. package/data/persistence/{principalPolicyReferenceIndexPersistence.js → principalPolicy/principalPolicyReferenceIndexPersistence.js} +4 -4
  238. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js.map +1 -0
  239. package/data/persistence/{principalPolicyReferencePersistence.js → principalPolicy/principalPolicyReferencePersistence.js} +5 -5
  240. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -0
  241. package/data/persistence/{verifiedPrincipalPolicyBundle.js → principalPolicy/verifiedPrincipalPolicyBundle.js} +2 -2
  242. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundle.js.map +1 -0
  243. package/data/persistence/{verifiedPrincipalPolicyCurrent.js → principalPolicy/verifiedPrincipalPolicyCurrent.js} +2 -2
  244. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js.map +1 -0
  245. package/data/persistence/{verifiedPrincipalPolicyRetentionPersistence.js → principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js} +1 -1
  246. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +1 -0
  247. package/data/persistence/securityIncidentPersistence.js +1 -1
  248. package/data/persistence/securityIncidentPersistence.js.map +1 -1
  249. package/data/persistence/trustedUserIdentityPinPersistence.js +1 -1
  250. package/data/persistence/verifiedManifestBundlePersistence.d.ts +1 -1
  251. package/data/persistence/verifiedManifestBundlePersistence.js +4 -4
  252. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  253. package/data/principals/organizationGroupRoles.js +2 -2
  254. package/data/principals/organizationGroupRoles.js.map +1 -1
  255. package/data/principals/principalHistoryPrefixProtection.js.map +1 -1
  256. package/data/principals/principalHistoryStageProtection.js.map +1 -1
  257. package/data/principals/principalPolicyCrypto.js +1 -1
  258. package/data/principals/principalPolicyCrypto.js.map +1 -1
  259. package/data/sqlite/{documentHistoryPersistence.d.ts → documentPersistence/documentHistoryPersistence.d.ts} +1 -1
  260. package/data/sqlite/{documentHistoryPersistence.js → documentPersistence/documentHistoryPersistence.js} +5 -5
  261. package/data/sqlite/documentPersistence/documentHistoryPersistence.js.map +1 -0
  262. package/data/sqlite/{documentOrphanBlobReclaims.js → documentPersistence/documentOrphanBlobReclaims.js} +1 -1
  263. package/data/sqlite/documentPersistence/documentOrphanBlobReclaims.js.map +1 -0
  264. package/data/sqlite/{documentPendingUpdatePersistence.d.ts → documentPersistence/documentPendingUpdatePersistence.d.ts} +2 -2
  265. package/data/sqlite/{documentPendingUpdatePersistence.js → documentPersistence/documentPendingUpdatePersistence.js} +2 -2
  266. package/data/sqlite/documentPersistence/documentPendingUpdatePersistence.js.map +1 -0
  267. package/data/sqlite/{documentPersistenceTypes.d.ts → documentPersistence/documentPersistenceTypes.d.ts} +2 -2
  268. package/data/sqlite/documentPersistence/documentPersistenceTypes.js.map +1 -0
  269. package/data/sqlite/{documentRecordPersistence.d.ts → documentPersistence/documentRecordPersistence.d.ts} +1 -1
  270. package/data/sqlite/{documentRecordPersistence.js → documentPersistence/documentRecordPersistence.js} +4 -4
  271. package/data/sqlite/documentPersistence/documentRecordPersistence.js.map +1 -0
  272. package/data/sqlite/{documentSyncFailurePersistence.d.ts → documentPersistence/documentSyncFailurePersistence.d.ts} +2 -2
  273. package/data/sqlite/{documentSyncFailurePersistence.js → documentPersistence/documentSyncFailurePersistence.js} +3 -3
  274. package/data/sqlite/documentPersistence/documentSyncFailurePersistence.js.map +1 -0
  275. package/data/sqlite/{documentPersistence.d.ts → documentPersistence/index.d.ts} +2 -2
  276. package/data/sqlite/{documentPersistence.js → documentPersistence/index.js} +5 -5
  277. package/data/sqlite/documentPersistence/index.js.map +1 -0
  278. package/data/sqlite/{containerSchema.d.ts → schema/containerSchema.d.ts} +1 -1
  279. package/data/sqlite/{containerSchema.js → schema/containerSchema.js} +1 -1
  280. package/data/sqlite/schema/containerSchema.js.map +1 -0
  281. package/data/sqlite/{schema.d.ts → schema/index.d.ts} +1 -1
  282. package/data/sqlite/{schema.js → schema/index.js} +3 -3
  283. package/data/sqlite/schema/index.js.map +1 -0
  284. package/data/sqlite/{organizationDataUsageSchema.js → schema/organizationDataUsageSchema.js} +1 -1
  285. package/data/sqlite/schema/organizationDataUsageSchema.js.map +1 -0
  286. package/data/sqlite/{organizationProvisioningAttemptSchema.js → schema/organizationProvisioningAttemptSchema.js} +1 -1
  287. package/data/sqlite/schema/organizationProvisioningAttemptSchema.js.map +1 -0
  288. package/data/sqlite/{organizationReadModelTableRegistry.d.ts → schema/organizationReadModelTableRegistry.d.ts} +1 -1
  289. package/data/sqlite/{organizationReadModelTableRegistry.js → schema/organizationReadModelTableRegistry.js} +1 -1
  290. package/data/sqlite/schema/organizationReadModelTableRegistry.js.map +1 -0
  291. package/data/sqlite/{principalHistoryEvidenceSchema.d.ts → schema/principalHistoryEvidenceSchema.d.ts} +1 -1
  292. package/data/sqlite/{principalHistoryEvidenceSchema.js → schema/principalHistoryEvidenceSchema.js} +2 -2
  293. package/data/sqlite/schema/principalHistoryEvidenceSchema.js.map +1 -0
  294. package/data/sqlite/{principalHistoryNodeRetentionSchema.js → schema/principalHistoryNodeRetentionSchema.js} +1 -1
  295. package/data/sqlite/schema/principalHistoryNodeRetentionSchema.js.map +1 -0
  296. package/data/sqlite/{principalHistoryRetentionSchema.js → schema/principalHistoryRetentionSchema.js} +1 -1
  297. package/data/sqlite/{principalHistoryRetentionSchema.js.map → schema/principalHistoryRetentionSchema.js.map} +1 -1
  298. package/data/sqlite/{principalHistoryStageSchema.d.ts → schema/principalHistoryStageSchema.d.ts} +1 -1
  299. package/data/sqlite/{principalHistoryStageSchema.js → schema/principalHistoryStageSchema.js} +2 -2
  300. package/data/sqlite/schema/principalHistoryStageSchema.js.map +1 -0
  301. package/data/sqlite/{principalMutationJournalSchema.d.ts → schema/principalMutationJournalSchema.d.ts} +1 -1
  302. package/data/sqlite/{principalMutationJournalSchema.js → schema/principalMutationJournalSchema.js} +1 -1
  303. package/data/sqlite/{principalMutationJournalSchema.js.map → schema/principalMutationJournalSchema.js.map} +1 -1
  304. package/data/sqlite/{principalPolicySchema.js → schema/principalPolicySchema.js} +1 -1
  305. package/data/sqlite/schema/principalPolicySchema.js.map +1 -0
  306. package/data/sqlite/{securityIncidentSchema.d.ts → schema/securityIncidentSchema.d.ts} +1 -1
  307. package/data/sqlite/{securityIncidentSchema.js → schema/securityIncidentSchema.js} +1 -1
  308. package/data/sqlite/schema/securityIncidentSchema.js.map +1 -0
  309. package/data/sqlite/{verifiedManifestBundleSchema.d.ts → schema/verifiedManifestBundleSchema.d.ts} +1 -1
  310. package/data/sqlite/{verifiedManifestBundleSchema.js → schema/verifiedManifestBundleSchema.js} +1 -1
  311. package/data/sqlite/schema/verifiedManifestBundleSchema.js.map +1 -0
  312. package/data/sqlite/sqlitePersistenceRuntime.d.ts +1 -1
  313. package/data/sqlite/sqlitePersistenceRuntime.js +1 -1
  314. package/package.json +1 -1
  315. package/sqlite/index.d.ts +1 -1
  316. package/sqlite/index.js +1 -1
  317. package/stores/documents/documentStore/history/historyRebuild.js +1 -1
  318. package/stores/documents/documentStore/history/historyRebuild.js.map +1 -1
  319. package/stores/documents/documentStore/state.js.map +1 -1
  320. package/stores/documents/documentStore/sync/syncFinalize.js +1 -1
  321. package/stores/documents/documentStore/sync/syncFinalize.js.map +1 -1
  322. package/stores/documents/documentStore/sync/syncUpdateImport.js +1 -1
  323. package/stores/documents/documentStore/sync/syncUpdateImport.js.map +1 -1
  324. package/workflows/blobs/detach.js +1 -1
  325. package/workflows/blobs/hydration/decrypt.js +1 -1
  326. package/workflows/blobs/upload/index.js +1 -1
  327. package/workflows/blobs/verification/retainedAttachmentVerification.js +1 -1
  328. package/workflows/blobs/verification/writerProjection.js +1 -1
  329. package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
  330. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  331. package/workflows/container-contents/container-state/share/index.js +1 -1
  332. package/workflows/container-contents/documentLinks/index.js +1 -1
  333. package/workflows/container-contents/documentMove/documentMoveVanishedRefresh.js +1 -1
  334. package/workflows/container-contents/documentPriming/documentHydrationProbe.js +1 -1
  335. package/workflows/container-contents/documentPriming/index.js +1 -1
  336. package/workflows/container-contents/documentQueries/index.js +1 -1
  337. package/workflows/container-contents/documentQueries/sql.js +1 -1
  338. package/workflows/container-contents/info/blobInfo.js +1 -1
  339. package/workflows/container-contents/info/containerInfo.js +1 -1
  340. package/workflows/container-contents/info/documentInfo.js +1 -1
  341. package/workflows/container-contents/metadata/index.js +1 -1
  342. package/workflows/container-contents/metadata/index.js.map +1 -1
  343. package/workflows/container-contents/metadata/metadataEvents.d.ts +1 -1
  344. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
  345. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  346. package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
  347. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
  348. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js +1 -1
  349. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js.map +1 -1
  350. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +1 -1
  351. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  352. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  353. package/workflows/container-contents/metadata/metadataSyncSettlement.d.ts +1 -1
  354. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
  355. package/workflows/container-contents/metadata/metadataTypes.d.ts +1 -1
  356. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  357. package/workflows/container-contents/pendingWrites/index.js +2 -2
  358. package/workflows/container-contents/pendingWrites/sources.js +1 -1
  359. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +1 -1
  360. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -1
  361. package/workflows/container-contents/remoteHydration/reattachMetadata.js.map +1 -1
  362. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +2 -2
  363. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  364. package/workflows/containers/child/create/index.js +2 -2
  365. package/workflows/containers/child/create/index.js.map +1 -1
  366. package/workflows/containers/child/move/index.js +1 -1
  367. package/workflows/containers/child/move/moveRotation.js +1 -1
  368. package/workflows/containers/child/move/moveRotation.js.map +1 -1
  369. package/workflows/containers/child/move/moveWraps.js +1 -1
  370. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  371. package/workflows/containers/child/recite.js +2 -2
  372. package/workflows/containers/child/recite.js.map +1 -1
  373. package/workflows/containers/child/rotation/rotationContext.js +3 -3
  374. package/workflows/containers/child/rotation/rotationContext.js.map +1 -1
  375. package/workflows/containers/child/share/currentSharePrincipalPolicy.js +1 -1
  376. package/workflows/containers/child/share/currentSharePrincipalPolicy.js.map +1 -1
  377. package/workflows/containers/child/share/index.js +1 -1
  378. package/workflows/containers/child/share/index.js.map +1 -1
  379. package/workflows/containers/child/share/shareAncestorRepair.js +2 -2
  380. package/workflows/containers/child/share/shareAncestorRepair.js.map +1 -1
  381. package/workflows/containers/child/share/shareMaterialization.js +1 -1
  382. package/workflows/containers/child/share/sharePrincipalPolicy.js +5 -5
  383. package/workflows/containers/child/share/sharePrincipalPolicy.js.map +1 -1
  384. package/workflows/containers/index.d.ts +3 -3
  385. package/workflows/containers/index.js +2 -2
  386. package/workflows/containers/index.js.map +1 -1
  387. package/workflows/containers/writeRefusal.js +1 -1
  388. package/workflows/containers/writeRefusal.js.map +1 -1
  389. package/workflows/documents/create/createAdoption.js +1 -1
  390. package/workflows/documents/create/createResponse.js +2 -2
  391. package/workflows/documents/create/createResponse.js.map +1 -1
  392. package/workflows/documents/create/index.js +1 -1
  393. package/workflows/documents/documentMutationCommit.d.ts +1 -1
  394. package/workflows/documents/documentMutationPreparation.d.ts +1 -1
  395. package/workflows/documents/documentMutationPreparation.js +1 -1
  396. package/workflows/documents/documentMutationPreparation.js.map +1 -1
  397. package/workflows/documents/index.d.ts +5 -5
  398. package/workflows/documents/index.js +5 -5
  399. package/workflows/documents/index.js.map +1 -1
  400. package/workflows/documents/linkSet/index.js +2 -2
  401. package/workflows/documents/linkSet/index.js.map +1 -1
  402. package/workflows/documents/linkSet/linkSetAuthority.js +1 -1
  403. package/workflows/documents/linkSet/linkSetBlobRewraps.js +1 -1
  404. package/workflows/documents/linkSet/linkSetProjectionSeed.js +1 -1
  405. package/workflows/documents/linkSet/linkSetRemote.js +1 -1
  406. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
  407. package/workflows/documents/purge/index.js +1 -1
  408. package/workflows/documents/sync/index.js +2 -2
  409. package/workflows/documents/sync/index.js.map +1 -1
  410. package/workflows/documents/sync/initialSync.js +1 -1
  411. package/workflows/documents/sync/readOnlyProjectionFailure.js +1 -1
  412. package/workflows/documents/sync/readOnlyProjectionFailure.js.map +1 -1
  413. package/workflows/documents/sync/readOnlySync.d.ts +3 -3
  414. package/workflows/documents/sync/readOnlySync.js +1 -1
  415. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  416. package/workflows/documents/sync/reportDocumentSyncQuarantine.js.map +1 -1
  417. package/workflows/documents/sync/syncAttemptPlanning.js +2 -2
  418. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  419. package/workflows/documents/sync/syncAttemptState.d.ts +2 -2
  420. package/workflows/documents/sync/syncAttemptState.js.map +1 -1
  421. package/workflows/documents/sync/syncResponseResult.js +2 -2
  422. package/workflows/documents/sync/syncResponseResult.js.map +1 -1
  423. package/workflows/documents/syncFailures/index.js +1 -1
  424. package/workflows/documents/syncFailures/index.js.map +1 -1
  425. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
  426. package/workflows/documents/syncFailures/syncFailureClassification.js +1 -1
  427. package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -1
  428. package/workflows/documents/syncPlan/syncContentKeys.d.ts +1 -1
  429. package/workflows/documents/syncPlan/syncContentKeys.js +3 -3
  430. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
  431. package/workflows/documents/syncPlan/syncPlanMaterial.js +2 -2
  432. package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -1
  433. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +2 -2
  434. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  435. package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js +1 -1
  436. package/workflows/documents/syncRekeys/syncRecoveryRekey.d.ts +1 -1
  437. package/workflows/documents/syncRekeys/syncRecoveryRekey.js +1 -1
  438. package/workflows/organizations/currentOrganizationAuthority.js +2 -2
  439. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  440. package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
  441. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  442. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +1 -1
  443. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  444. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +1 -1
  445. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
  446. package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -3
  447. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  448. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  449. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  450. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js +1 -1
  451. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  452. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +2 -2
  453. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  454. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js +1 -1
  455. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js.map +1 -1
  456. package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
  457. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
  458. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  459. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  460. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -1
  461. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  462. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  463. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  464. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +1 -1
  465. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
  466. package/workflows/organizations/provisioning/organizationReplacementVerification.js +1 -1
  467. package/workflows/organizations/provisioning/organizationReplacementVerification.js.map +1 -1
  468. package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
  469. package/workflows/organizations/readModel/localReadModelDetails.js +1 -1
  470. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  471. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +1 -1
  472. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
  473. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.d.ts +1 -1
  474. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +1 -1
  475. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
  476. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
  477. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
  478. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +2 -2
  479. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
  480. package/workflows/principals/externalAdminPolicy.js +2 -2
  481. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  482. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js +2 -2
  483. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -1
  484. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js +1 -1
  485. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js.map +1 -1
  486. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +1 -1
  487. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
  488. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js +1 -1
  489. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js.map +1 -1
  490. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +3 -3
  491. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
  492. package/workflows/principals/policyCache/index.js +3 -3
  493. package/workflows/principals/policyCache/index.js.map +1 -1
  494. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +1 -1
  495. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  496. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +3 -3
  497. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  498. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -1
  499. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +2 -2
  500. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
  501. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +3 -3
  502. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
  503. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.d.ts +2 -2
  504. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.js.map +1 -1
  505. package/workflows/principals/publicHistory/publicProjectionPrincipal.js +1 -1
  506. package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -1
  507. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +1 -1
  508. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  509. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +1 -1
  510. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
  511. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +1 -1
  512. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
  513. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js +1 -1
  514. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js.map +1 -1
  515. package/workflows/registration/persistRegistrationBootstrap.d.ts +2 -2
  516. package/workflows/registration/persistRegistrationBootstrap.js +2 -2
  517. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  518. package/workflows/registration/provisioningAcknowledgement.js +1 -1
  519. package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
  520. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -1
  521. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  522. package/workflows/sync/remoteReset.js +7 -7
  523. package/workflows/sync/remoteReset.js.map +1 -1
  524. package/workflows/sync/remoteResetAttachments.js +1 -1
  525. package/workflows/sync/remoteResetCursorScope.js +1 -1
  526. package/workflows/sync/remoteResetPlans.js +1 -1
  527. package/workflows/sync/remoteResetPrincipalScope.js +5 -5
  528. package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
  529. package/workflows/sync/remoteResetScope.js +1 -1
  530. package/data/documents/shared/containerKekPath.js.map +0 -1
  531. package/data/documents/shared/containerKekPathHistory.js.map +0 -1
  532. package/data/documents/shared/containerKekPathVerification.js.map +0 -1
  533. package/data/documents/shared/containerKekWrapping.js.map +0 -1
  534. package/data/documents/shared/documentSyncUpdateDecryption.js.map +0 -1
  535. package/data/documents/shared/documentSyncUpdateIsolation.js.map +0 -1
  536. package/data/documents/shared/keyringRebuild.js.map +0 -1
  537. package/data/documents/shared/mutationAcknowledgement.js.map +0 -1
  538. package/data/documents/shared/projection.js.map +0 -1
  539. package/data/documents/shared/projectionContentKeys.js.map +0 -1
  540. package/data/documents/shared/projectionTargets.js.map +0 -1
  541. package/data/documents/shared/syncPagination.js.map +0 -1
  542. package/data/documents/shared/syncResponseAuthorization.js.map +0 -1
  543. package/data/documents/shared/syncResponses.js.map +0 -1
  544. package/data/persistence/documentPurgeCheckpointPersistence.js.map +0 -1
  545. package/data/persistence/keyingCheckpointAdvancePersistence.js.map +0 -1
  546. package/data/persistence/keyingCheckpointPersistence.js.map +0 -1
  547. package/data/persistence/locallyAcknowledgedCheckpointPersistence.js.map +0 -1
  548. package/data/persistence/organizationReplacementCheckpointPersistence.js.map +0 -1
  549. package/data/persistence/principalAuthorizationCheckpoints.js.map +0 -1
  550. package/data/persistence/principalGrantRetirementPersistence.js.map +0 -1
  551. package/data/persistence/principalHistoryEvidencePersistence.js.map +0 -1
  552. package/data/persistence/principalHistoryIncompleteRetention.js.map +0 -1
  553. package/data/persistence/principalHistoryNodeRetention.js.map +0 -1
  554. package/data/persistence/principalHistoryPrefixPersistence.js.map +0 -1
  555. package/data/persistence/principalHistoryRootOwnership.js.map +0 -1
  556. package/data/persistence/principalHistoryStagePersistence.js.map +0 -1
  557. package/data/persistence/principalHistoryStageRetention.js.map +0 -1
  558. package/data/persistence/principalHistoryUnpublishedRetention.js.map +0 -1
  559. package/data/persistence/principalKeyEnvelopeArchivePersistence.js.map +0 -1
  560. package/data/persistence/principalKeyEnvelopeCandidates.js.map +0 -1
  561. package/data/persistence/principalPolicyBundleIntegrity.js.map +0 -1
  562. package/data/persistence/principalPolicyCheckpointSelection.js.map +0 -1
  563. package/data/persistence/principalPolicyOrganizationPersistence.js.map +0 -1
  564. package/data/persistence/principalPolicyPersistence.js.map +0 -1
  565. package/data/persistence/principalPolicyReferenceCheckpoint.js.map +0 -1
  566. package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +0 -1
  567. package/data/persistence/principalPolicyReferencePersistence.js.map +0 -1
  568. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +0 -1
  569. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +0 -1
  570. package/data/persistence/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
  571. package/data/sqlite/containerSchema.js.map +0 -1
  572. package/data/sqlite/documentHistoryPersistence.js.map +0 -1
  573. package/data/sqlite/documentOrphanBlobReclaims.js.map +0 -1
  574. package/data/sqlite/documentPendingUpdatePersistence.js.map +0 -1
  575. package/data/sqlite/documentPersistence.js.map +0 -1
  576. package/data/sqlite/documentPersistenceTypes.js.map +0 -1
  577. package/data/sqlite/documentRecordPersistence.js.map +0 -1
  578. package/data/sqlite/documentSyncFailurePersistence.js.map +0 -1
  579. package/data/sqlite/organizationDataUsageSchema.js.map +0 -1
  580. package/data/sqlite/organizationProvisioningAttemptSchema.js.map +0 -1
  581. package/data/sqlite/organizationReadModelTableRegistry.js.map +0 -1
  582. package/data/sqlite/principalHistoryEvidenceSchema.js.map +0 -1
  583. package/data/sqlite/principalHistoryNodeRetentionSchema.js.map +0 -1
  584. package/data/sqlite/principalHistoryStageSchema.js.map +0 -1
  585. package/data/sqlite/principalPolicySchema.js.map +0 -1
  586. package/data/sqlite/schema.js.map +0 -1
  587. package/data/sqlite/securityIncidentSchema.js.map +0 -1
  588. package/data/sqlite/verifiedManifestBundleSchema.js.map +0 -1
  589. /package/data/documents/shared/{containerKekCurrency.js → containerKek/containerKekCurrency.js} +0 -0
  590. /package/data/documents/shared/{containerKekCurrency.js.map → containerKek/containerKekCurrency.js.map} +0 -0
  591. /package/data/documents/shared/{containerKekEntryVerification.js.map → containerKek/containerKekEntryVerification.js.map} +0 -0
  592. /package/data/documents/shared/{containerKekLogFetch.js.map → containerKek/containerKekLogFetch.js.map} +0 -0
  593. /package/data/documents/shared/{containerKekPath.d.ts → containerKek/containerKekPath.d.ts} +0 -0
  594. /package/data/documents/shared/{keyringLogWalk.js.map → containerKek/keyringLogWalk.js.map} +0 -0
  595. /package/data/documents/shared/{pullContinuation.d.ts → sync/pullContinuation.d.ts} +0 -0
  596. /package/data/documents/shared/{pullContinuation.js.map → sync/pullContinuation.js.map} +0 -0
  597. /package/data/documents/shared/{syncSubmitFailure.js → sync/syncSubmitFailure.js} +0 -0
  598. /package/data/documents/shared/{syncSubmitFailure.js.map → sync/syncSubmitFailure.js.map} +0 -0
  599. /package/data/persistence/{keyingCheckpointEvidence.js.map → keyingCheckpoints/keyingCheckpointEvidence.js.map} +0 -0
  600. /package/data/persistence/{storedPrincipalPolicyBundle.js → principalPolicy/storedPrincipalPolicyBundle.js} +0 -0
  601. /package/data/persistence/{storedPrincipalPolicyBundle.js.map → principalPolicy/storedPrincipalPolicyBundle.js.map} +0 -0
  602. /package/data/sqlite/{documentPersistenceTypes.js → documentPersistence/documentPersistenceTypes.js} +0 -0
  603. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.d.ts → schema/containerDocumentTombstoneHoldSchema.d.ts} +0 -0
  604. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js → schema/containerDocumentTombstoneHoldSchema.js} +0 -0
  605. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js.map → schema/containerDocumentTombstoneHoldSchema.js.map} +0 -0
  606. /package/data/sqlite/{documentAttachmentSchema.d.ts → schema/documentAttachmentSchema.d.ts} +0 -0
  607. /package/data/sqlite/{documentAttachmentSchema.js → schema/documentAttachmentSchema.js} +0 -0
  608. /package/data/sqlite/{documentAttachmentSchema.js.map → schema/documentAttachmentSchema.js.map} +0 -0
  609. /package/data/sqlite/{documentDiscoveryEvidenceSchema.js → schema/documentDiscoveryEvidenceSchema.js} +0 -0
  610. /package/data/sqlite/{documentDiscoveryEvidenceSchema.js.map → schema/documentDiscoveryEvidenceSchema.js.map} +0 -0
  611. /package/data/sqlite/{documentPlacementIntentSchema.js → schema/documentPlacementIntentSchema.js} +0 -0
  612. /package/data/sqlite/{documentPlacementIntentSchema.js.map → schema/documentPlacementIntentSchema.js.map} +0 -0
  613. /package/data/sqlite/{localIntentSchema.d.ts → schema/localIntentSchema.d.ts} +0 -0
  614. /package/data/sqlite/{localIntentSchema.js → schema/localIntentSchema.js} +0 -0
  615. /package/data/sqlite/{localIntentSchema.js.map → schema/localIntentSchema.js.map} +0 -0
  616. /package/data/sqlite/{organizationFounderSchema.js → schema/organizationFounderSchema.js} +0 -0
  617. /package/data/sqlite/{organizationFounderSchema.js.map → schema/organizationFounderSchema.js.map} +0 -0
  618. /package/data/sqlite/{organizationReadModelSchema.js → schema/organizationReadModelSchema.js} +0 -0
  619. /package/data/sqlite/{organizationReadModelSchema.js.map → schema/organizationReadModelSchema.js.map} +0 -0
  620. /package/data/sqlite/{principalGrantRetirementSchema.js → schema/principalGrantRetirementSchema.js} +0 -0
  621. /package/data/sqlite/{principalGrantRetirementSchema.js.map → schema/principalGrantRetirementSchema.js.map} +0 -0
  622. /package/data/sqlite/{principalPolicySchema.d.ts → schema/principalPolicySchema.d.ts}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Q,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC;IACzC,KAAK,MAAM,EAAE,IAAI,GAAG;QAAE,MAAM,2BAA2B,CAAC,EAAE,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC;IAC3E,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAC7B,MAAM,EAAE;SACL,MAAM,CAAC,sBAAsB,CAAC;SAC9B,KAAK,CAAC,OAAO,CAAC,sBAAsB,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;SAC9C,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { and, asc, desc, eq, inArray, ne } from \"drizzle-orm\";\nimport { principalHistoryStages } from \"../sqlite/principalHistoryStageSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { releasePrincipalHistoryRoot } from \"./principalHistoryRootOwnership\";\n\nconst INCOMPLETE_STAGE_LIMIT = 8;\nconst RECLAIM_BATCH_LIMIT = 16;\n\n/** Disposable work only: completed artifacts and trust pins are unaffected. */\nexport async function reclaimIncompletePrincipalHistoryStages(\n tx: ClientSQLiteTransactionScope,\n current: {\n readonly id: string;\n readonly scopeId: string;\n readonly organizationId: string;\n readonly complete: boolean;\n },\n) {\n const obsolete = await tx\n .select({ id: principalHistoryStages.id })\n .from(principalHistoryStages)\n .where(\n and(\n eq(principalHistoryStages.scopeId, current.scopeId),\n eq(principalHistoryStages.organizationId, current.organizationId),\n eq(principalHistoryStages.complete, false),\n ne(principalHistoryStages.id, current.id),\n ),\n )\n .orderBy(\n desc(principalHistoryStages.touchedAt),\n asc(principalHistoryStages.id),\n )\n // The writer always keeps its own stage, even when recency hints tie.\n .offset(INCOMPLETE_STAGE_LIMIT - (current.complete ? 0 : 1))\n .limit(RECLAIM_BATCH_LIMIT);\n const ids = obsolete.map(({ id }) => id);\n for (const id of ids) await releasePrincipalHistoryRoot(tx, `stage:${id}`);\n if (ids.length === 0) return;\n await tx\n .delete(principalHistoryStages)\n .where(inArray(principalHistoryStages.id, ids))\n .run();\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalHistoryNodeRetention.js","sourceRoot":"","sources":["principalHistoryNodeRetention.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,0CAA0C,CAAC;AACjF,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EACL,sCAAsC,GAEvC,MAAM,iCAAiC,CAAC;AAKzC,MAAM,0BAA0B,GAAG,qBAAqB,CACtD,8BAA8B,CAC/B,CAAC;AACF,MAAM,qBAAqB,GAAG,qBAAqB,CAAC,qBAAqB,CAAC,CAAC;AAC3E,sCAAsC;AACtC,MAAM,sBAAsB,GAAG,sBAAsB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAE5D,SAAS,OAAO,CAAI,KAAmB,EAAE,IAAY;IACnD,MAAM,MAAM,GAAU,EAAE,CAAC;IACzB,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,IAAI;QACrD,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC;IAChD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,KAAK,UAAU,kBAAkB,CAC/B,EAAgC,EAChC,KAAgC,EAChC,MAAyB,EACzB,IAAuD;IAEvD,MAAM,OAAO,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CA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AAC,qBAAqB,CAAC;iBAC7B,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,qBAAqB,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EAChD,EAAE,CAAC,qBAAqB,CAAC,cAAc,EAAE,KAAK,CAAC,cAAc,CAAC,EAC9D,EAAE,CAAC,qBAAqB,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAC1C,CACF;iBACA,GAAG,EAAE,CAAC;YACT,MAAM,EAAE;iBACL,MAAM,CAAC,8BAA8B,CAAC;iBACtC,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,8BAA8B,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACzD,EAAE,CAAC,8BAA8B,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CACnD,CACF;iBACA,GAAG,EAAE,CAAC;YACT,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC;gBAChD,IAAI,IAAI;oBAAE,MAAM,sCAAsC,CAAC,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;YAC1E,SAAS,IAAI,CAAC,CAAC;QACjB,CAAC;IACH,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type { PrincipalHistoryIndexNode } from \"@tearleads/crypto\";\nimport { and, asc, eq, inArray } from \"drizzle-orm\";\nimport { principalHistoryNodes } from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryNodeReferences } from \"../sqlite/principalHistoryNodeRetentionSchema\";\nimport {\n sqliteInsertBatchSize,\n sqliteRowsPerStatement,\n} from \"../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../sqlite/sqliteUpsert\";\nimport {\n decrementPrincipalHistoryNodeReference,\n type PrincipalHistoryNodeScope,\n} from \"./principalHistoryRootOwnership\";\n\ntype PrincipalHistoryNodeReference =\n typeof principalHistoryNodeReferences.$inferSelect;\n\nconst REFERENCE_WRITE_BATCH_SIZE = sqliteInsertBatchSize(\n principalHistoryNodeReferences,\n);\nconst NODE_WRITE_BATCH_SIZE = sqliteInsertBatchSize(principalHistoryNodes);\n// The scope id binds once per lookup.\nconst HASH_LOOKUP_BATCH_SIZE = sqliteRowsPerStatement(1, 1);\n\nfunction batches<T>(items: readonly T[], size: number): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < items.length; index += size)\n result.push(items.slice(index, index + size));\n return result;\n}\n\nasync function loadNodeReferences(\n tx: ClientSQLiteTransactionScope,\n scope: PrincipalHistoryNodeScope,\n hashes: readonly string[],\n into: Map<string, PrincipalHistoryNodeReference | null>,\n): Promise<void> {\n const missing = [...new Set(hashes)].filter((hash) => !into.has(hash));\n for (const batch of batches(missing, HASH_LOOKUP_BATCH_SIZE)) {\n for (const hash of batch) into.set(hash, null);\n const rows = await tx\n .select()\n .from(principalHistoryNodeReferences)\n .where(\n and(\n eq(principalHistoryNodeReferences.scopeId, scope.scopeId),\n inArray(principalHistoryNodeReferences.hash, batch),\n ),\n );\n for (const row of rows) into.set(row.hash, row);\n }\n}\n\nasync function loadStoredNodeHashes(\n tx: ClientSQLiteTransactionScope,\n scope: PrincipalHistoryNodeScope,\n hashes: readonly string[],\n): Promise<Set<string>> {\n const stored = new Set<string>();\n for (const batch of batches([...new Set(hashes)], HASH_LOOKUP_BATCH_SIZE)) {\n const rows = await tx\n .select({ hash: principalHistoryNodes.hash })\n .from(principalHistoryNodes)\n .where(\n and(\n eq(principalHistoryNodes.scopeId, scope.scopeId),\n inArray(principalHistoryNodes.hash, batch),\n ),\n );\n for (const row of rows) stored.add(row.hash);\n }\n return stored;\n}\n\n/**\n * Replays the per-node edge bookkeeping in memory: increment inserts or adds\n * one, decrement floors at zero within the scope's organization, and an edge\n * change keeps the count while marking nodes first stored here as managed.\n */\nfunction replayNodeEdges(\n scope: PrincipalHistoryNodeScope,\n nodes: readonly PrincipalHistoryIndexNode[],\n loaded: ReadonlyMap<string, PrincipalHistoryNodeReference | null>,\n storedNodeHashes: Set<string>,\n): Map<string, PrincipalHistoryNodeReference | null> {\n const references = new Map(loaded);\n const read = (hash: string) => {\n const reference = references.get(hash);\n if (reference === undefined)\n throw new Error(\"Principal history node reference was not loaded\");\n return reference;\n };\n const increment = (hash: string) => {\n const reference = read(hash);\n references.set(\n hash,\n reference\n ? { ...reference, referenceCount: reference.referenceCount + 1 }\n : {\n ...scope,\n hash,\n referenceCount: 1,\n managed: false,\n leftHash: null,\n rightHash: null,\n },\n );\n };\n const decrement = (hash: string) => {\n const reference = read(hash);\n if (reference?.organizationId === scope.organizationId)\n references.set(hash, {\n ...reference,\n referenceCount: Math.max(reference.referenceCount - 1, 0),\n });\n };\n for (const node of nodes) {\n const previous = read(node.hash);\n if (\n previous?.leftHash !== node.leftHash ||\n previous.rightHash !== node.rightHash\n ) {\n const managed = previous?.managed || !storedNodeHashes.has(node.hash);\n increment(node.leftHash);\n increment(node.rightHash);\n const current = read(node.hash);\n references.set(node.hash, {\n ...(current ?? {\n ...scope,\n hash: node.hash,\n referenceCount: previous?.referenceCount ?? 0,\n }),\n leftHash: node.leftHash,\n rightHash: node.rightHash,\n managed,\n });\n for (const hash of [previous?.leftHash, previous?.rightHash])\n if (hash) decrement(hash);\n }\n storedNodeHashes.add(node.hash);\n }\n return references;\n}\n\nfunction isSameNodeReference(\n left: PrincipalHistoryNodeReference,\n right: PrincipalHistoryNodeReference,\n): boolean {\n return (\n left.organizationId === right.organizationId &&\n left.referenceCount === right.referenceCount &&\n left.managed === right.managed &&\n left.leftHash === right.leftHash &&\n left.rightHash === right.rightHash\n );\n}\n\n/**\n * Register edges and store proof nodes in the given order, with the same\n * result as recording each node's edges and then upserting it. Reads the\n * touched liveness rows once, replays the bookkeeping, and writes the changed\n * rows and the nodes as multi-row upserts.\n */\nexport async function writePrincipalHistoryNodes(\n tx: ClientSQLiteTransactionScope,\n scope: PrincipalHistoryNodeScope,\n nodes: readonly PrincipalHistoryIndexNode[],\n): Promise<void> {\n if (nodes.length === 0) return;\n const loaded = new Map<string, PrincipalHistoryNodeReference | null>();\n await loadNodeReferences(\n tx,\n scope,\n nodes.flatMap((node) => [node.hash, node.leftHash, node.rightHash]),\n loaded,\n );\n // An edge change releases the stored row's previous children.\n await loadNodeReferences(\n tx,\n scope,\n nodes.flatMap((node) => {\n const stored = loaded.get(node.hash);\n return [stored?.leftHash, stored?.rightHash].filter(\n (hash): hash is string => Boolean(hash),\n );\n }),\n loaded,\n );\n const replayed = replayNodeEdges(\n scope,\n nodes,\n loaded,\n await loadStoredNodeHashes(\n tx,\n scope,\n nodes.map((node) => node.hash),\n ),\n );\n const changed = [...replayed].flatMap(([hash, reference]) => {\n const before = loaded.get(hash);\n return reference && !(before && isSameNodeReference(before, reference))\n ? [reference]\n : [];\n });\n for (const batch of batches(changed, REFERENCE_WRITE_BATCH_SIZE))\n await tx\n .insert(principalHistoryNodeReferences)\n .values(batch)\n .onConflictDoUpdate({\n target: [\n principalHistoryNodeReferences.scopeId,\n principalHistoryNodeReferences.hash,\n ],\n set: {\n referenceCount: excludedValue(\n principalHistoryNodeReferences.referenceCount,\n ),\n managed: excludedValue(principalHistoryNodeReferences.managed),\n leftHash: excludedValue(principalHistoryNodeReferences.leftHash),\n rightHash: excludedValue(principalHistoryNodeReferences.rightHash),\n },\n })\n .run();\n const nodeRows = new Map(\n nodes.map((node) => [\n node.hash,\n {\n ...scope,\n hash: node.hash,\n leftHash: node.leftHash,\n rightHash: node.rightHash,\n },\n ]),\n );\n for (const batch of batches([...nodeRows.values()], NODE_WRITE_BATCH_SIZE))\n await tx\n .insert(principalHistoryNodes)\n .values(batch)\n .onConflictDoUpdate({\n target: [principalHistoryNodes.scopeId, principalHistoryNodes.hash],\n set: {\n organizationId: excludedValue(principalHistoryNodes.organizationId),\n leftHash: excludedValue(principalHistoryNodes.leftHash),\n rightHash: excludedValue(principalHistoryNodes.rightHash),\n },\n })\n .run();\n}\n\n/** A bounded cascade releases only managed proof nodes with no live incoming edge. */\nexport async function reclaimPrincipalHistoryNodes(\n tx: ClientSQLiteTransactionScope,\n scope: PrincipalHistoryNodeScope,\n): Promise<number> {\n let reclaimed = 0;\n while (reclaimed < 64) {\n const obsolete = await tx\n .select()\n .from(principalHistoryNodeReferences)\n .where(\n and(\n eq(principalHistoryNodeReferences.scopeId, scope.scopeId),\n eq(\n principalHistoryNodeReferences.organizationId,\n scope.organizationId,\n ),\n eq(principalHistoryNodeReferences.managed, true),\n eq(principalHistoryNodeReferences.referenceCount, 0),\n ),\n )\n .orderBy(asc(principalHistoryNodeReferences.hash))\n .limit(64 - reclaimed);\n if (obsolete.length === 0) break;\n for (const node of obsolete) {\n await tx\n .delete(principalHistoryNodes)\n .where(\n and(\n eq(principalHistoryNodes.scopeId, scope.scopeId),\n eq(principalHistoryNodes.organizationId, scope.organizationId),\n eq(principalHistoryNodes.hash, node.hash),\n ),\n )\n .run();\n await tx\n .delete(principalHistoryNodeReferences)\n .where(\n and(\n eq(principalHistoryNodeReferences.scopeId, scope.scopeId),\n eq(principalHistoryNodeReferences.hash, node.hash),\n ),\n )\n .run();\n for (const hash of [node.leftHash, node.rightHash])\n if (hash) await decrementPrincipalHistoryNodeReference(tx, scope, hash);\n reclaimed += 1;\n }\n }\n return reclaimed;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalHistoryPrefixPersistence.js","sourceRoot":"","sources":["principalHistoryPrefixPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,GACzB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,2BAA2B,EAAE,MAAM,uCAAuC,CAAC;AACpF,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AAC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,EAAE,UAAU,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;QAClE,MAAM,EAAE;aACL,MAAM,CAAC,wBAAwB,CAAC;aAChC,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,wBAAwB,CAAC,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,EACpD,EAAE,CAAC,wBAAwB,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,CACvD,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC,EACD,KAAK,CAAC,YAAY,EAClB,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACF,mCAAmC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { assertProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport {\n principalHistoryEvidenceTables,\n principalHistoryPrefixes,\n} from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryStageTables } from \"../sqlite/principalHistoryStageSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { reclaimPrincipalHistoryNodes } from \"./principalHistoryNodeRetention\";\nimport {\n releasePrincipalHistoryRoot,\n retainPrincipalHistoryRoot,\n} from \"./principalHistoryRootOwnership\";\nimport { reclaimCompletedPrincipalHistoryStages } from \"./principalHistoryStageRetention\";\nimport { archivePrincipalHistoryKeyEnvelopes } from \"./principalKeyEnvelopeArchivePersistence\";\n\nexport type PrincipalHistoryPrefix =\n typeof principalHistoryPrefixes.$inferSelect;\n\nexport async function loadPrincipalHistoryPrefix(\n execSql: ExecSql,\n scopeId: string,\n) {\n await ensureSqlTables(execSql, principalHistoryEvidenceTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [prefix] = await db\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, scopeId))\n .limit(1);\n return prefix ?? null;\n}\n\n/**\n * Preserve identical completed progress; this sink does not authenticate hints.\n * Callers must discard an unreadable prefix or identify it with rejectedPrefix\n * before publishing a repair of the same head and current artifacts.\n */\nexport async function savePrincipalHistoryPrefix(input: {\n readonly execSql: ExecSql;\n readonly prefix: PrincipalHistoryPrefix;\n readonly indexRootHash: string;\n readonly stillCurrent: () => boolean;\n readonly rejectedPrefix?: PrincipalHistoryPrefix | null;\n}): Promise<void> {\n const prefix = { ...input.prefix };\n const indexRootHash = input.indexRootHash;\n const rejected = input.rejectedPrefix ? { ...input.rejectedPrefix } : null;\n await ensureSqlTables(input.execSql, [\n ...principalHistoryEvidenceTables,\n ...principalHistoryStageTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const [previous] = await tx\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, prefix.scopeId))\n .limit(1);\n const replacesRejected =\n previous &&\n rejected?.scopeId === previous.scopeId &&\n rejected.progress === previous.progress;\n if (previous && previous.version > prefix.version && !replacesRejected)\n return;\n if (\n previous &&\n previous.version === prefix.version &&\n previous.organizationId === prefix.organizationId &&\n previous.headJson === prefix.headJson &&\n previous.currentJson === prefix.currentJson &&\n !replacesRejected\n ) {\n // Resealing an unchanged prefix would invalidate an acknowledgement's\n // progress CAS even though its authenticated predecessor is unchanged.\n // Still refresh authenticated root ownership and retention below.\n // Reuse authenticates this opaque progress; rejected hints are removed\n // or explicitly replaced before repair can rely on the new prefix.\n prefix.progress = previous.progress;\n }\n if (previous) await archivePrincipalHistoryKeyEnvelopes(tx, previous);\n await archivePrincipalHistoryKeyEnvelopes(tx, prefix);\n await tx\n .insert(principalHistoryPrefixes)\n .values(prefix)\n .onConflictDoUpdate({\n target: principalHistoryPrefixes.scopeId,\n set: prefix,\n })\n .run();\n await reclaimCompletedPrincipalHistoryStages(tx, prefix);\n await retainPrincipalHistoryRoot(tx, {\n id: `prefix:${prefix.scopeId}`,\n scopeId: prefix.scopeId,\n organizationId: prefix.organizationId,\n rootHash: indexRootHash,\n });\n await reclaimPrincipalHistoryNodes(tx, prefix);\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n}\n\n/** Invalid hints are disposable, but a losing reader must preserve a newer hint. */\nexport async function discardPrincipalHistoryPrefix(input: {\n readonly execSql: ExecSql;\n readonly prefix: PrincipalHistoryPrefix;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const prefix = { ...input.prefix };\n await ensureSqlTables(input.execSql, principalHistoryEvidenceTables);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const [current] = await tx\n .select({ progress: principalHistoryPrefixes.progress })\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, prefix.scopeId))\n .limit(1);\n if (current?.progress !== prefix.progress) return;\n await releasePrincipalHistoryRoot(tx, `prefix:${prefix.scopeId}`);\n await tx\n .delete(principalHistoryPrefixes)\n .where(\n and(\n eq(principalHistoryPrefixes.scopeId, prefix.scopeId),\n eq(principalHistoryPrefixes.progress, prefix.progress),\n ),\n )\n .run();\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalHistoryRootOwnership.js","sourceRoot":"","sources":["principalHistoryRootOwnership.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,GAC3B,MAAM,+CAA+C,CAAC;AASvD,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAC1D,EAAgC,EAChC,KAAgC,EAChC,IAAY;IAEZ,MAAM,EAAE;SACL,MAAM,CAAC,8BAA8B,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AC,cAAc,KAAK,KAAK,CAAC,cAAc;QAChD,QAAQ,CAAC,QAAQ,KAAK,KAAK,CAAC,QAAQ;QAEpC,OAAO;IACT,MAAM,sCAAsC,CAAC,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IACxE,MAAM,EAAE;SACL,MAAM,CAAC,0BAA0B,CAAC;SAClC,MAAM,CAAC,KAAK,CAAC;SACb,kBAAkB,CAAC;QAClB,MAAM,EAAE,0BAA0B,CAAC,EAAE;QACrC,GAAG,EAAE,KAAK;KACX,CAAC;SACD,GAAG,EAAE,CAAC;IACT,IAAI,QAAQ;QACV,MAAM,sCAAsC,CAC1C,EAAE,EACF,QAAQ,EACR,QAAQ,CAAC,QAAQ,CAClB,CAAC;AACN,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,EAAgC,EAChC,EAAU;IAEV,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,EAAE;SACxB,MAAM,EAAE;SACR,IAAI,CAAC,0BAA0B,CAAC;SAChC,KAAK,CAAC,EAAE,CAAC,0BAA0B,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;SAC5C,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,CAAC,QAAQ;QAAE,OAAO;IACtB,MAAM,EAAE;SACL,MAAM,CAAC,0BAA0B,CAAC;SAClC,KAAK,CAAC,EAAE,CAAC,0BAA0B,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;SAC5C,GAAG,EAAE,CAAC;IACT,MAAM,sCAAsC,CAAC,EAAE,EAAE,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import { and, eq, sql } from \"drizzle-orm\";\nimport {\n principalHistoryNodeReferences,\n principalHistoryRootOwners,\n} from \"../sqlite/principalHistoryNodeRetentionSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\n\nexport interface PrincipalHistoryNodeScope {\n /** Evidence scope hashes include organizationId; one scope belongs to one organization. */\n readonly scopeId: string;\n readonly organizationId: string;\n}\n\nexport async function incrementPrincipalHistoryNodeReference(\n tx: ClientSQLiteTransactionScope,\n scope: PrincipalHistoryNodeScope,\n hash: string,\n) {\n await tx\n .insert(principalHistoryNodeReferences)\n .values({\n ...scope,\n hash,\n referenceCount: 1,\n managed: false,\n leftHash: null,\n rightHash: null,\n })\n .onConflictDoUpdate({\n target: [\n principalHistoryNodeReferences.scopeId,\n principalHistoryNodeReferences.hash,\n ],\n set: {\n referenceCount: sql`${principalHistoryNodeReferences.referenceCount} + 1`,\n },\n })\n .run();\n}\n\nexport async function decrementPrincipalHistoryNodeReference(\n tx: ClientSQLiteTransactionScope,\n scope: PrincipalHistoryNodeScope,\n hash: string,\n) {\n await tx\n .update(principalHistoryNodeReferences)\n .set({\n referenceCount: sql`max(${principalHistoryNodeReferences.referenceCount} - 1, 0)`,\n })\n .where(\n and(\n eq(principalHistoryNodeReferences.scopeId, scope.scopeId),\n eq(principalHistoryNodeReferences.organizationId, scope.organizationId),\n eq(principalHistoryNodeReferences.hash, hash),\n ),\n )\n .run();\n}\n\n/** Caller commits ownership together with the exact saved progress it describes. */\nexport async function retainPrincipalHistoryRoot(\n tx: ClientSQLiteTransactionScope,\n input: PrincipalHistoryNodeScope & {\n readonly id: string;\n readonly rootHash: string;\n },\n) {\n const [previous] = await tx\n .select()\n .from(principalHistoryRootOwners)\n .where(eq(principalHistoryRootOwners.id, input.id))\n .limit(1);\n if (\n previous?.scopeId === input.scopeId &&\n previous.organizationId === input.organizationId &&\n previous.rootHash === input.rootHash\n )\n return;\n await incrementPrincipalHistoryNodeReference(tx, input, input.rootHash);\n await tx\n .insert(principalHistoryRootOwners)\n .values(input)\n .onConflictDoUpdate({\n target: principalHistoryRootOwners.id,\n set: input,\n })\n .run();\n if (previous)\n await decrementPrincipalHistoryNodeReference(\n tx,\n previous,\n previous.rootHash,\n );\n}\n\nexport async function releasePrincipalHistoryRoot(\n tx: ClientSQLiteTransactionScope,\n id: string,\n) {\n const [previous] = await tx\n .select()\n .from(principalHistoryRootOwners)\n .where(eq(principalHistoryRootOwners.id, id))\n .limit(1);\n if (!previous) return;\n await tx\n .delete(principalHistoryRootOwners)\n .where(eq(principalHistoryRootOwners.id, id))\n .run();\n await decrementPrincipalHistoryNodeReference(tx, previous, previous.rootHash);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalHistoryStagePersistence.js","sourceRoot":"","sources":["principalHistoryStagePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EAAE,8BAA8B,EAAE,MAAM,0CAA0C,CAAC;AAC1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EACL,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,uCAAuC,EAAE,MAAM,uCAAuC,CAAC;AAChG,OAAO,EAAE,4BAA4B,EAAE,MAAM,iCAAiC,CAAC;AAC/E,OAAO,EACL,2BAA2B,EAC3B,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAQlG,MAAM,4BAA4B,GAAG;IACnC,EAAE,EAAE,sBAAsB,CAAC,EAAE;IAC7B,cAAc,EAAE,sBAAsB,CAAC,cAAc;IACrD,WAAW,EAAE,sBAAsB,CAAC,WAAW;IAC/C,YAAY,EAAE,sBAAsB,CAAC,YAAY;IACjD,QAAQ,EAAE,sBAA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ectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport { principalHistoryEvidenceTables } from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryNodeRetentionTables } from \"../sqlite/principalHistoryNodeRetentionSchema\";\nimport {\n principalHistoryStages,\n principalHistoryStageTables,\n} from \"../sqlite/principalHistoryStageSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n type PrincipalHistoryEvidencePage,\n writePrincipalHistoryEvidencePage,\n} from \"./principalHistoryEvidencePersistence\";\nimport { reclaimIncompletePrincipalHistoryStages } from \"./principalHistoryIncompleteRetention\";\nimport { reclaimPrincipalHistoryNodes } from \"./principalHistoryNodeRetention\";\nimport {\n releasePrincipalHistoryRoot,\n retainPrincipalHistoryRoot,\n} from \"./principalHistoryRootOwnership\";\nimport { reclaimUnpublishedPrincipalHistoryStages } from \"./principalHistoryUnpublishedRetention\";\n\n/** A stage's verification work; its retention hints are written by persistence. */\nexport type PrincipalHistoryStage = Omit<\n typeof principalHistoryStages.$inferSelect,\n \"scopeId\" | \"touchedAt\"\n>;\n\nconst principalHistoryStageColumns = {\n id: principalHistoryStages.id,\n organizationId: principalHistoryStages.organizationId,\n currentJson: principalHistoryStages.currentJson,\n afterVersion: principalHistoryStages.afterVersion,\n complete: principalHistoryStages.complete,\n progress: principalHistoryStages.progress,\n};\n\nclass PrincipalHistoryStageChangedError extends Error {\n readonly code = \"principal_history_stage_changed\";\n constructor() {\n super(\n \"Another operation changed the saved principal history; resume from its current state\",\n );\n this.name = \"PrincipalHistoryStageChangedError\";\n }\n}\n\nexport async function loadPrincipalHistoryStage(\n execSql: ExecSql,\n id: string,\n): Promise<PrincipalHistoryStage | null> {\n await ensureSqlTables(execSql, principalHistoryStageTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [row] = await db\n .select(principalHistoryStageColumns)\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, id))\n .limit(1);\n return row ?? null;\n}\n\n/** Publish accepted entries and index nodes atomically with authenticated progress. */\nexport async function savePrincipalHistoryStage(input: {\n readonly execSql: ExecSql;\n readonly stage: PrincipalHistoryStage;\n readonly evidence: PrincipalHistoryEvidencePage;\n readonly previousProgress: string | null;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const evidence = structuredClone(input.evidence);\n const stage = { ...input.stage, scopeId: evidence.scopeId };\n await ensureSqlTables(input.execSql, [\n ...principalHistoryStageTables,\n ...principalHistoryEvidenceTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const saved = await runtime.guardedTransaction(\n async (tx) => {\n const [previous] = await tx\n .select({ progress: principalHistoryStages.progress })\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, stage.id))\n .limit(1);\n if ((previous?.progress ?? null) !== input.previousProgress)\n throw new PrincipalHistoryStageChangedError();\n await writePrincipalHistoryEvidencePage(tx, evidence);\n const row = { ...stage, touchedAt: Date.now() };\n await tx\n .insert(principalHistoryStages)\n .values(row)\n .onConflictDoUpdate({ target: principalHistoryStages.id, set: row })\n .run();\n await retainPrincipalHistoryRoot(tx, {\n id: `stage:${stage.id}`,\n scopeId: evidence.scopeId,\n organizationId: stage.organizationId,\n rootHash: evidence.indexRootHash,\n });\n await reclaimIncompletePrincipalHistoryStages(tx, stage);\n await reclaimUnpublishedPrincipalHistoryStages(tx, stage);\n await reclaimPrincipalHistoryNodes(tx, evidence);\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => saved.committed);\n}\n\nexport async function discardPrincipalHistoryStage(\n execSql: ExecSql,\n stage: PrincipalHistoryStage,\n stillCurrent: () => boolean,\n) {\n await ensureSqlTables(execSql, [\n ...principalHistoryStageTables,\n ...principalHistoryNodeRetentionTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const discarded = await runtime.guardedTransaction(\n async (db) => {\n const [current] = await db\n .select({ progress: principalHistoryStages.progress })\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, stage.id))\n .limit(1);\n if (current?.progress !== stage.progress) return;\n await releasePrincipalHistoryRoot(db, `stage:${stage.id}`);\n await db\n .delete(principalHistoryStages)\n .where(\n and(\n eq(principalHistoryStages.id, stage.id),\n eq(principalHistoryStages.progress, stage.progress),\n ),\n )\n .run();\n },\n stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => discarded.committed);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalHistoryStageRetention.js","sourceRoot":"","sources":["principalHistoryStageRetention.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAE/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAC9E,OAAO,EAAE,mCAAmC,EAAE,MAAM,0CAA0C,CAAC;AAE/F,4EAA4E;AAC5E,MAAM,CAAC,MAAM,qCAAqC,GAAG,EAAE,CAAC;AAExD,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,EAAgC,EAChC,KAAwD;IAExD,MAAM,EAAE;SACL,MAAM,CAAC,sBAAsB,CAAC;SAC9B,GAAG,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;SACtD,KAAK,CAAC,EAAE,CAAC,sBAAsB,CAAC,EAAE,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;SAC9C,GAAG,EAAE,CAAC;AACX,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAC1D,EAAgC,EAChC,MAIC;IAED,MAAM,QAAQ,GAAG,MAAM,EAAE;SACtB,MA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import { and, asc, desc, eq, lt } from \"drizzle-orm\";\nimport { principalHistoryStages } from \"../sqlite/principalHistoryStageSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { releasePrincipalHistoryRoot } from \"./principalHistoryRootOwnership\";\nimport { archivePrincipalHistoryKeyEnvelopes } from \"./principalKeyEnvelopeArchivePersistence\";\n\n/** Each publication reclaims at most this many obsolete completed heads. */\nexport const PRINCIPAL_HISTORY_STAGE_RECLAIM_LIMIT = 16;\n\n/** Mark a stored stage as just used by a writer for its principal history. */\nexport async function touchPrincipalHistoryStage(\n tx: ClientSQLiteTransactionScope,\n input: { readonly id: string; readonly scopeId: string },\n) {\n await tx\n .update(principalHistoryStages)\n .set({ scopeId: input.scopeId, touchedAt: Date.now() })\n .where(eq(principalHistoryStages.id, input.id))\n .run();\n}\n\n/** The prefix and its key candidates must be published in this transaction. */\nexport async function reclaimCompletedPrincipalHistoryStages(\n tx: ClientSQLiteTransactionScope,\n prefix: {\n readonly scopeId: string;\n readonly organizationId: string;\n readonly version: number;\n },\n) {\n const obsolete = await tx\n .select({\n stage: {\n id: principalHistoryStages.id,\n organizationId: principalHistoryStages.organizationId,\n currentJson: principalHistoryStages.currentJson,\n afterVersion: principalHistoryStages.afterVersion,\n },\n })\n .from(principalHistoryStages)\n .where(\n and(\n eq(principalHistoryStages.scopeId, prefix.scopeId),\n eq(principalHistoryStages.organizationId, prefix.organizationId),\n eq(principalHistoryStages.complete, true),\n lt(principalHistoryStages.afterVersion, prefix.version),\n ),\n )\n .orderBy(\n desc(principalHistoryStages.afterVersion),\n desc(principalHistoryStages.touchedAt),\n asc(principalHistoryStages.id),\n )\n // Keep the current completed head and its newest completed predecessor.\n // This also preserves the prefix-only predecessor restored after an ack.\n .offset(2)\n .limit(PRINCIPAL_HISTORY_STAGE_RECLAIM_LIMIT);\n for (const { stage } of obsolete) {\n await releasePrincipalHistoryRoot(tx, `stage:${stage.id}`);\n await archivePrincipalHistoryKeyEnvelopes(tx, {\n ...stage,\n version: stage.afterVersion + 1,\n });\n await tx\n .delete(principalHistoryStages)\n .where(eq(principalHistoryStages.id, stage.id))\n .run();\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalHistoryUnpublishedRetention.js","sourceRoot":"","sources":["principalHistoryUnpublishedRetention.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACpF,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAE/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAC9E,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EAAE,mCAAmC,EAAE,MAAM,0CAA0C,CAAC;AAE/F,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAShC,SAAS,uBAAuB,CAAC,OAAwB;IACvD,OAAO,GAAG,CACR,EAAE,CAAC,sBAAsB,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,EACnD,EAAE,CAAC,sBAAsB,CAAC,cAAc,EAAE,OAAO,CAAC,cAAc,CAAC,EACjE,EAAE,CAAC,sBAAsB,CAAC,QAAQ,EAAE,IAAI,CAAC,CAC1C,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,wBAAwB,CACrC,EAAgC,EAChC,OAAwB;IAExB,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE;SACtB,MAAM,CAAC,EAAE,OAAO,EAAE,wBAAwB,CAAC,OAAO,EAAE,CAAC;SACrD,IAAI,CAAC,wBAAwB,CAAC;SAC9B,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,wBAAwB,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,EACrD,EAAE,C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ACF,CAAC;SACD,IAAI,CAAC,sBAAsB,CAAC;SAC5B,KAAK,CACJ,GAAG,CACD,uBAAuB,CAAC,OAAO,CAAC,EAChC,UAAU,CAAC,sBAAsB,CAAC,EAAE,EAAE,YAAY,CAAC,CACpD,CACF;QACD,wEAAwE;SACvE,OAAO,CACN,IAAI,CAAC,sBAAsB,CAAC,SAAS,CAAC,EACtC,GAAG,CAAC,sBAAsB,CAAC,EAAE,CAAC,CAC/B;SACA,MAAM,CAAC,qBAAqB,GAAG,YAAY,CAAC,MAAM,CAAC;SACnD,KAAK,CAAC,qCAAqC,CAAC,CAAC;IAChD,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAClC,KAAK,MAAM,EAAE,KAAK,EAAE,IAAI,QAAQ;QAC9B,MAAM,mCAAmC,CAAC,EAAE,EAAE;YAC5C,GAAG,KAAK;YACR,OAAO,EAAE,KAAK,CAAC,YAAY,GAAG,CAAC;SAChC,CAAC,CAAC;IACL,MAAM,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAClD,KAAK,MAAM,EAAE,IAAI,GAAG;QAAE,MAAM,2BAA2B,CAAC,EAAE,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC;IAC3E,MAAM,EAAE;SACL,MAAM,CAAC,sBAAsB,CAAC;SAC9B,KAAK,CAAC,OAAO,CAAC,sBAAsB,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;SAC9C,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { and, asc, desc, eq, inArray, lt, notInArray } from \"drizzle-orm\";\nimport { principalHistoryPrefixes } from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryStages } from \"../sqlite/principalHistoryStageSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { releasePrincipalHistoryRoot } from \"./principalHistoryRootOwnership\";\nimport { PRINCIPAL_HISTORY_STAGE_RECLAIM_LIMIT } from \"./principalHistoryStageRetention\";\nimport { archivePrincipalHistoryKeyEnvelopes } from \"./principalKeyEnvelopeArchivePersistence\";\n\nconst COMPLETED_STAGE_LIMIT = 8;\n\ninterface CompletedWriter {\n readonly id: string;\n readonly scopeId: string;\n readonly organizationId: string;\n readonly complete: boolean;\n}\n\nfunction matchingCompletedStages(current: CompletedWriter) {\n return and(\n eq(principalHistoryStages.scopeId, current.scopeId),\n eq(principalHistoryStages.organizationId, current.organizationId),\n eq(principalHistoryStages.complete, true),\n );\n}\n\nasync function protectedPublishedStages(\n tx: ClientSQLiteTransactionScope,\n current: CompletedWriter,\n) {\n const [prefix] = await tx\n .select({ version: principalHistoryPrefixes.version })\n .from(principalHistoryPrefixes)\n .where(\n and(\n eq(principalHistoryPrefixes.scopeId, current.scopeId),\n eq(principalHistoryPrefixes.organizationId, current.organizationId),\n ),\n )\n .limit(1);\n if (!prefix) return [];\n return tx\n .select({ id: principalHistoryStages.id })\n .from(principalHistoryStages)\n .where(\n and(\n matchingCompletedStages(current),\n lt(principalHistoryStages.afterVersion, prefix.version),\n ),\n )\n .orderBy(\n desc(principalHistoryStages.afterVersion),\n desc(principalHistoryStages.touchedAt),\n asc(principalHistoryStages.id),\n )\n .limit(2);\n}\n\n/** Bound completed attempts even when current-artifact verification never publishes. */\nexport async function reclaimUnpublishedPrincipalHistoryStages(\n tx: ClientSQLiteTransactionScope,\n current: CompletedWriter,\n) {\n if (!current.complete) return;\n const published = await protectedPublishedStages(tx, current);\n const protectedIds = [\n ...new Set([current.id, ...published.map(({ id }) => id)]),\n ];\n const obsolete = await tx\n .select({\n stage: {\n id: principalHistoryStages.id,\n organizationId: principalHistoryStages.organizationId,\n currentJson: principalHistoryStages.currentJson,\n afterVersion: principalHistoryStages.afterVersion,\n },\n })\n .from(principalHistoryStages)\n .where(\n and(\n matchingCompletedStages(current),\n notInArray(principalHistoryStages.id, protectedIds),\n ),\n )\n // The existing \"incomplete\" index also covers completed scoped recency.\n .orderBy(\n desc(principalHistoryStages.touchedAt),\n asc(principalHistoryStages.id),\n )\n .offset(COMPLETED_STAGE_LIMIT - protectedIds.length)\n .limit(PRINCIPAL_HISTORY_STAGE_RECLAIM_LIMIT);\n if (obsolete.length === 0) return;\n for (const { stage } of obsolete)\n await archivePrincipalHistoryKeyEnvelopes(tx, {\n ...stage,\n version: stage.afterVersion + 1,\n });\n const ids = obsolete.map(({ stage }) => stage.id);\n for (const id of ids) await releasePrincipalHistoryRoot(tx, `stage:${id}`);\n await tx\n .delete(principalHistoryStages)\n .where(inArray(principalHistoryStages.id, ids))\n .run();\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalKeyEnvelopeArchivePersistence.js","sourceRoot":"","sources":["principalKeyEnvelopeArchivePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,2BAA2B,EAAE,MAAM,2CAA2C,CAAC;AAGxF;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,EAAgC,EAChC,KAIC;IAED,IAAI,OAAgB,CAAC;IACrB,IAAI,CAAC;QACH,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAC1C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO;IACT,CAAC;IACD,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;QAAE,OAAO;IAC9E,MAAM,IAAI,GAAG;QACX,GAAG,OAAO;QACV,cAAc,EAAE,EAAE;QAClB,WAAW,EAAE,EAAE,YAAY,EAAE,KAAK,CAAC,OAAO,GAAG,CAAC,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AAG;QACR,QAAQ,EAAE,GAAG,CAAC,2BAA2B,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC;KAChE,CAAC;SACD,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { computePrincipalMemberEnvelopesRoot } from \"@tearleads/crypto\";\nimport { isPrincipalPolicyPageResponse } from \"@tearleads/validators/response\";\nimport { lte } from \"drizzle-orm\";\nimport { principalKeyEnvelopeArchive } from \"../sqlite/principalHistoryRetentionSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\n\n/**\n * Preserve untrusted encrypted candidates, never history or authorization.\n * The caller replaces progress in this same transaction. Public-history hints\n * carry no private artifacts and deliberately contribute no candidates.\n */\nexport async function archivePrincipalHistoryKeyEnvelopes(\n tx: ClientSQLiteTransactionScope,\n input: {\n readonly organizationId: string;\n readonly currentJson: string;\n readonly version: number;\n },\n) {\n let current: unknown;\n try {\n current = JSON.parse(input.currentJson);\n } catch {\n return;\n }\n if (!current || typeof current !== \"object\" || Array.isArray(current)) return;\n const page = {\n ...current,\n previousStates: [],\n historyPage: { afterVersion: input.version - 1, nextAfterVersion: null },\n };\n if (\n !isPrincipalPolicyPageResponse(page) ||\n page.currentState.version !== input.version ||\n page.currentState.stateHash !== page.currentMemberEnvelopes.stateHash ||\n page.currentState.principalId !== page.currentMemberEnvelopes.principalId ||\n page.currentState.principalType !==\n page.currentMemberEnvelopes.principalType ||\n page.currentState.keyEpoch !== page.currentMemberEnvelopes.epoch\n )\n return;\n try {\n if (\n (await computePrincipalMemberEnvelopesRoot(\n page.currentMemberEnvelopes.envelopes,\n )) !== page.currentState.memberEnvelopesRoot\n )\n return;\n } catch {\n return;\n }\n const row = {\n organizationId: input.organizationId,\n principalId: page.currentState.principalId,\n principalType: page.currentState.principalType,\n keyFingerprint: page.currentState.keyFingerprint,\n version: input.version,\n envelopesJson: JSON.stringify(page.currentMemberEnvelopes),\n };\n await tx\n .insert(principalKeyEnvelopeArchive)\n .values(row)\n .onConflictDoUpdate({\n target: [\n principalKeyEnvelopeArchive.organizationId,\n principalKeyEnvelopeArchive.principalType,\n principalKeyEnvelopeArchive.principalId,\n principalKeyEnvelopeArchive.keyFingerprint,\n ],\n set: row,\n setWhere: lte(principalKeyEnvelopeArchive.version, row.version),\n })\n .run();\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalKeyEnvelopeCandidates.js","sourceRoot":"","sources":["principalKeyEnvelopeCandidates.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,yCAAyC,GAC1C,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,GACzB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,2BAA2B,EAAE,MAAM,2CAA2C,CAAC;AACxF,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAC/E,OAAO,EACL,+BAA+B,EAC/B,6BAA6B,GAC9B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,iBAAiB,EACjB,4BAA4B,GAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAYpE;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,OAAgB,EAChB,YAA+B;IAE/B,MAAM,eAAe,CAAC,OAAO,EAAE;QAC7B,GAAG,qBAAqB;QACxB,GAAG,8BAA8B;KAClC,CAAC,CAAC;IACH,MAAM,EAAE,EAAE,EAAE,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;IAC1D,MAAM,UAAU,GAAoC,EAAE,CAAC;IACvD,KAAK,MAAM,WAAW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B,EAAE,SAAS;aAClC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import {\n type CurrentPrincipalMemberEnvelopesResponse,\n isCurrentPrincipalMemberEnvelopesResponse,\n} from \"@tearleads/validators/response\";\nimport { and, desc, eq, sql } from \"drizzle-orm\";\nimport {\n principalHistoryEvidenceTables,\n principalHistoryPrefixes,\n} from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalKeyEnvelopeArchive } from \"../sqlite/principalHistoryRetentionSchema\";\nimport { principalHistoryStages } from \"../sqlite/principalHistoryStageSchema\";\nimport {\n principalCurrentFingerprintJson,\n principalStateFingerprintJson,\n} from \"../sqlite/principalKeyFingerprintJson\";\nimport {\n principalPolicies,\n principalPolicyBundleHistory,\n} from \"../sqlite/principalPolicySchema\";\nimport { principalPolicyTables } from \"../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\nexport interface PrincipalKeyEnvelopeCandidate {\n readonly currentState: {\n readonly principalType: \"group\" | \"organization\";\n readonly principalId: string;\n readonly stateHash: string;\n readonly keyFingerprint: string;\n };\n readonly currentMemberEnvelopes: CurrentPrincipalMemberEnvelopesResponse;\n}\n\n/**\n * Untrusted encrypted key candidates, never authorization evidence. The actual\n * private key must open the requested recipient wrap; the projection verifier\n * separately checks the signed KEK material identity and all policy authority.\n * Read only envelopes for the requested fingerprints, never signed histories.\n */\nexport async function loadPrincipalKeyEnvelopeCandidates(\n execSql: ExecSql,\n fingerprints: readonly string[],\n): Promise<PrincipalKeyEnvelopeCandidate[]> {\n await ensureSqlTables(execSql, [\n ...principalPolicyTables,\n ...principalHistoryEvidenceTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const candidates: PrincipalKeyEnvelopeCandidate[] = [];\n for (const fingerprint of new Set(fingerprints)) {\n const encoded: string[] = [];\n const [archived] = await db\n .select({ envelopes: principalKeyEnvelopeArchive.envelopesJson })\n .from(principalKeyEnvelopeArchive)\n .where(eq(principalKeyEnvelopeArchive.keyFingerprint, fingerprint))\n .orderBy(desc(principalKeyEnvelopeArchive.version))\n .limit(1);\n if (archived) encoded.push(archived.envelopes);\n for (const table of [principalPolicies, principalPolicyBundleHistory]) {\n const [row] = await db\n .select({ envelopes: table.currentMemberEnvelopesJson })\n .from(table)\n .where(\n eq(\n principalStateFingerprintJson(table.currentStateJson),\n fingerprint,\n ),\n )\n .orderBy(desc(table.updatedAt))\n .limit(1);\n if (row) encoded.push(row.envelopes);\n }\n const [prefix] = await db\n .select({\n envelopes: sql<string>`json_extract(${principalHistoryPrefixes.currentJson}, '$.currentMemberEnvelopes')`,\n })\n .from(principalHistoryPrefixes)\n .where(\n eq(\n principalCurrentFingerprintJson(principalHistoryPrefixes.currentJson),\n fingerprint,\n ),\n )\n .orderBy(desc(principalHistoryPrefixes.version))\n .limit(1);\n if (prefix) encoded.push(prefix.envelopes);\n const [stage] = await db\n .select({\n envelopes: sql<string>`json_extract(${principalHistoryStages.currentJson}, '$.currentMemberEnvelopes')`,\n })\n .from(principalHistoryStages)\n .where(\n and(\n eq(\n principalCurrentFingerprintJson(principalHistoryStages.currentJson),\n fingerprint,\n ),\n eq(principalHistoryStages.complete, true),\n ),\n )\n .orderBy(desc(principalHistoryStages.afterVersion))\n .limit(1);\n if (stage) encoded.push(stage.envelopes);\n for (const json of new Set(encoded)) {\n let envelopes: unknown;\n try {\n envelopes = JSON.parse(json);\n } catch {\n continue;\n }\n if (!isCurrentPrincipalMemberEnvelopesResponse(envelopes)) continue;\n candidates.push({\n currentState: {\n principalType: envelopes.principalType,\n principalId: envelopes.principalId,\n stateHash: envelopes.stateHash,\n keyFingerprint: fingerprint,\n },\n currentMemberEnvelopes: envelopes,\n });\n }\n }\n return candidates;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalPolicyBundleIntegrity.js","source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a,EAAE,iCAAiC,CAAC,MAAM,CAAC,aAAa,CAAC;QACtE,YAAY,EAAE,gBAAgB,CAAC,MAAM,CAAC,YAAY,CAAC;QACnD,cAAc,EAAE,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YACpD,UAAU,EAAE,mCAAmC,CAAC,KAAK,CAAC,UAAU,CAAC;YACjE,MAAM,EAAE,iCAAiC,CAAC,KAAK,CAAC,MAAM,CAAC;YACvD,KAAK,EAAE,gBAAgB,CAAC,KAAK,CAAC,KAAK,CAAC;SACrC,CAAC,CAAC;KACJ,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,mCAAmC,CACjD,MAAuC,EACvC,QAAyC;IAEzC,IAAI,CAAC;QACH,IACE,SAAS,CAAC,eAAe,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;YAC/C,SAAS,CAAC,eAAe,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC,EACjD,CAAC;YACD,OAAO;QACT,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,2EAA2E;QAC3E,2EAA2E;IAC7E,CAAC;IACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,mFAAmF,CACpF,CAAC;AACJ,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { isPrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../keying/canonicalJson\";\nimport {\n type StoredPrincipalPolicyBundleJson,\n storedPrincipalPolicyBundleFromJson,\n} from \"./storedPrincipalPolicyBundle\";\n\nfunction parseBundle(\n row: StoredPrincipalPolicyBundleJson,\n): PrincipalPolicyBundleResponse {\n const bundle = storedPrincipalPolicyBundleFromJson(row);\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new Error(\"Stored principal policy bundle is invalid\");\n }\n return bundle;\n}\n\nfunction canonical(value: unknown): string {\n return canonicalKeyingJsonString(\n value,\n \"principal policy bundle security content\",\n );\n}\n\nfunction withoutCreatedAt<T extends { readonly createdAt: string }>(\n value: T,\n): Omit<T, \"createdAt\"> {\n const { createdAt: _createdAt, ...content } = value;\n return content;\n}\n\nfunction securityContent(bundle: PrincipalPolicyBundleResponse) {\n return {\n currentMemberEnvelopes: {\n ...bundle.currentMemberEnvelopes,\n envelopes: [...bundle.currentMemberEnvelopes.envelopes].sort((a, b) =>\n compareCanonicalStrings(canonical(a), canonical(b)),\n ),\n },\n currentPayload: withoutCreatedAt(bundle.currentPayload),\n currentProjection: normalizePrincipalProjectionMembers(\n bundle.currentProjection,\n ),\n currentGrants: normalizePrincipalContainerGrants(bundle.currentGrants),\n currentState: withoutCreatedAt(bundle.currentState),\n previousStates: bundle.previousStates.map((entry) => ({\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n state: withoutCreatedAt(entry.state),\n })),\n };\n}\n\nexport function assertSameHeadPrincipalPolicyBundle(\n stored: StoredPrincipalPolicyBundleJson,\n incoming: StoredPrincipalPolicyBundleJson,\n): void {\n try {\n if (\n canonical(securityContent(parseBundle(stored))) ===\n canonical(securityContent(parseBundle(incoming)))\n ) {\n return;\n }\n } catch {\n // Invalid same-head cache content is also an integrity conflict: replacing\n // it would erase the only durable evidence that the head was inconsistent.\n }\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy bundle content conflicts with the cached bundle at the same head\",\n );\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalPolicyCheckpointSelection.js","sourceRoot":"","sources":["principalPolicyCheckpointSelection.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,+BAA+B,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,oCAAoC,EAAE,MAAM,+BAA+B,CAAC;AAErF,MAAM,UAAU,kCAAkC,CAChD,IAA8D,EAC9D,UAA4C;IAE5C,OAAO,CACL,CAAC,UAAU;QACX,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO;QACjC,CAAC,IAAI,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO;YAClC,IAAI,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS,CAAC,CAC3C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,MAAoC,EACpC,UAA4C;IAE5C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,oCAAoC,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IACzD,IAAI,MAAM,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,EAAE,CAAC;QACxC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,+BAA+B,CAAC;QAC9B,KAAK,EACH,iBAAiB,IAAI,MAAM;YACzB,CAAC,CAAC,MAAM,CAAC,eAAe;YACxB,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC;QAC5B,YAAY,EAAE,MAAM,CAAC,KAAK;QAC1B,eAAe,EAAE,UAAU;KAC5B,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type {\n PrincipalPolicyAuthorization,\n PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { verifyPrincipalPolicyCheckpoint } from \"@tearleads/crypto\";\nimport { assertPrincipalPolicyCheckpointShape } from \"./keyingCheckpointPersistence\";\n\nexport function principalPolicyHeadMeetsCheckpoint(\n head: { readonly stateHash: string; readonly version: number },\n checkpoint: PrincipalPolicyCheckpoint | null,\n): boolean {\n return (\n !checkpoint ||\n head.version > checkpoint.version ||\n (head.version === checkpoint.version &&\n head.stateHash === checkpoint.stateHash)\n );\n}\n\nexport function verifiedPrincipalPolicyMeetsCheckpoint(\n policy: PrincipalPolicyAuthorization,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): boolean {\n if (!checkpoint) {\n return true;\n }\n assertPrincipalPolicyCheckpointShape(checkpoint, policy);\n if (policy.version < checkpoint.version) {\n return false;\n }\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in policy\n ? policy.retainedHistory\n : (policy.history ?? []),\n currentState: policy.state,\n localCheckpoint: checkpoint,\n });\n return true;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalPolicyOrganizationPersistence.js","sourceRoot":"","sources":["principalPolicyOrganizationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,4BAA4B,EAAE,MAAM,kBAAkB,CAAC;AAShE,SAAS,qBAAqB,CAC5B,KAAuC;IAEvC,IAAI,KAAK,CAAC,aAAa,KAAK,cAAc,EAAE,CAAC;QAC3C,IACE,KAAK,CAAC,cAAc,KAAK,SAAS;YAClC,KAAK,CAAC,cAAc,KAAK,KAAK,CAAC,WAAW,EAC1C,CAAC;YACD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,kEAAkE,CACnE,CAAC;QACJ,CAAC;QACD,OAAO,KAAK,CAAC,WAAW,CAAC;IAC3B,CAAC;IACD,IAAI,CAAC,KAAK,CAAC,cAAc,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,OAAO,KAAK,CAAC,cAAc,CAAC;AAC9B,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,8CAA8C,CAClE,EAAgC,EAChC,KAAuC;IAEvC,MAAM,cAAc,GAAG,qBAAqB,CAAC,KAAK,CAAC,CAAC;IACpD,MAAM,cAAc,GAAG,GAAG,CACxB,EAAE,CAAC,4BAA4B,CAAC,aAAa,EAAE,KAAK,CAAC,aAAa,CAAC,EACnE,EAAE,CAAC,4BAA4B,CAAC,WAAW,EAAE,KAAK,CAAC,WAAW,CAAC,CAChE,CAAC;IACF,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE;SACtB,MAAM,CAAC,EAAE,cAAc,EAAE,4BAA4B,CAAC,cAAc,EAAE,CAAC;SACvE,IAAI,CAAC,4BAA4B,CAAC;SAClC,KAAK,CAAC,cAAc,CAAC;SACrB,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,MAAM,IAAI,MAAM,CAAC,cAAc,KAAK,cAAc,EAAE,CAAC;QACvD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,iEAAiE,CAClE,CAAC;IACJ,CAAC;IACD,MAAM,EAAE;SACL,MAAM,CAAC,4BAA4B,CAAC;SACpC,MAAM,CAAC,EAAE,GAAG,KAAK,EAAE,cAAc,EAAE,CAAC;SACpC,mBAAmB,EAAE;SACrB,GAAG,EAAE,CAAC;AACX,CAAC;AAED,MAAM,UAAU,oDAAoD,CAClE,EAAgC,EAChC,MAAyD,EACzD,cAAmC;IAEnC,OAAO,8CAA8C,CAAC,EAAE,EAAE;QACxD,cAAc;QACd,WAAW,EAAE,MAAM,CAAC,YAAY,CAAC,WAAW;QAC5C,aAAa,EAAE,MAAM,CAAC,YAAY,CAAC,aAAa;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { PrincipalStateResponse } from \"@tearleads/validators/response\";\nimport { and, eq } from \"drizzle-orm\";\nimport { principalPolicyOrganizations } from \"../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\n\ninterface PrincipalPolicyOrganizationInput {\n readonly organizationId?: string | undefined;\n readonly principalId: string;\n readonly principalType: PrincipalStateResponse[\"principalType\"];\n}\n\nfunction resolveOrganizationId(\n input: PrincipalPolicyOrganizationInput,\n): string {\n if (input.principalType === \"organization\") {\n if (\n input.organizationId !== undefined &&\n input.organizationId !== input.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization policy cache ownership targets another organization\",\n );\n }\n return input.principalId;\n }\n if (!input.organizationId) {\n throw new Error(\"Group policy cache writes require an organization ID\");\n }\n return input.organizationId;\n}\n\n/** Pins cache ownership in the same transaction as the cached policy state. */\nexport async function recordPrincipalPolicyOrganizationInTransaction(\n tx: ClientSQLiteTransactionScope,\n input: PrincipalPolicyOrganizationInput,\n): Promise<void> {\n const organizationId = resolveOrganizationId(input);\n const wherePrincipal = and(\n eq(principalPolicyOrganizations.principalType, input.principalType),\n eq(principalPolicyOrganizations.principalId, input.principalId),\n );\n const [stored] = await tx\n .select({ organizationId: principalPolicyOrganizations.organizationId })\n .from(principalPolicyOrganizations)\n .where(wherePrincipal)\n .limit(1);\n if (stored && stored.organizationId !== organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"principal policy cache is already owned by another organization\",\n );\n }\n await tx\n .insert(principalPolicyOrganizations)\n .values({ ...input, organizationId })\n .onConflictDoNothing()\n .run();\n}\n\nexport function recordPrincipalPolicyBundleOrganizationInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: { readonly currentState: PrincipalStateResponse },\n organizationId?: string | undefined,\n): Promise<void> {\n return recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: bundle.currentState.principalId,\n principalType: bundle.currentState.principalType,\n });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalPolicyPersistence.js","sourceRoot":"","sources":["principalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,sBAAsB,EACtB,iBAAiB,EACjB,4BAA4B,EAC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AC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isPrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { and, asc, eq } from \"drizzle-orm\";\nimport {\n keyingCheckpointTables,\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyCheckpoints,\n principalPolicyTables,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport {\n recordPrincipalPolicyBundleOrganizationInTransaction,\n recordPrincipalPolicyOrganizationInTransaction,\n} from \"./principalPolicyOrganizationPersistence\";\nimport { indexPrincipalPolicyBundleInTransaction } from \"./principalPolicyReferenceIndexPersistence\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface PrincipalPolicyRow {\n principalType: \"group\" | \"organization\";\n principalId: string;\n stateHash: string;\n currentStateJson: string;\n currentPayloadJson: string;\n currentProjectionJson: string;\n currentGrantsJson: string;\n currentMemberEnvelopesJson: string;\n previousStatesJson: string;\n updatedAt: string;\n}\n\nexport interface SelectedPrincipalPolicyRow {\n principalType: string;\n principalId: string;\n stateHash: string;\n currentStateJson: string;\n currentPayloadJson: string;\n currentProjectionJson: string;\n currentGrantsJson: string;\n currentMemberEnvelopesJson: string;\n previousStatesJson: string;\n updatedAt: string;\n}\n\ninterface StoredPrincipalPolicyHead {\n readonly stateHash: string;\n readonly version: number;\n}\n\nfunction isManagedPrincipalType(\n value: string,\n): value is PrincipalStateResponse[\"principalType\"] {\n return value === \"group\" || value === \"organization\";\n}\n\nfunction parsePrincipalPolicyRow(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyRow | null {\n if (!isManagedPrincipalType(row.principalType)) {\n return null;\n }\n\n return {\n principalType: row.principalType,\n principalId: row.principalId,\n stateHash: row.stateHash,\n currentStateJson: row.currentStateJson,\n currentPayloadJson: row.currentPayloadJson,\n currentProjectionJson: row.currentProjectionJson,\n currentGrantsJson: row.currentGrantsJson,\n currentMemberEnvelopesJson: row.currentMemberEnvelopesJson,\n previousStatesJson: row.previousStatesJson,\n updatedAt: row.updatedAt,\n };\n}\n\nfunction parseStoredPrincipalPolicyHead(\n currentStateJson: string,\n): StoredPrincipalPolicyHead | null {\n try {\n const value: unknown = JSON.parse(currentStateJson);\n if (!value || typeof value !== \"object\") {\n return null;\n }\n const stateHash = Reflect.get(value, \"stateHash\");\n const version = Reflect.get(value, \"version\");\n return typeof stateHash === \"string\" && typeof version === \"number\"\n ? { stateHash, version }\n : null;\n } catch {\n return null;\n }\n}\n\nfunction parsePrincipalPolicyBundle(\n row: PrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n const bundle = storedPrincipalPolicyBundleFromJson(row);\n\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new Error(\"Stored principal policy bundle is invalid\");\n }\n\n return bundle;\n}\n\nexport async function ensurePrincipalPolicyTables(\n execSql: ExecSql,\n): Promise<void> {\n await ensureSqlTables(execSql, principalPolicyTables);\n}\n\ntype PrincipalPolicyBundleTable =\n | typeof principalPolicies\n | typeof principalPolicyBundleHistory;\n\n/**\n * The ONE select shape for a stored principal-policy bundle row, over either\n * the mutable-head table or the retained-history table.\n */\nexport function principalPolicyBundleSelection(\n table: PrincipalPolicyBundleTable,\n) {\n return {\n principalType: table.principalType,\n principalId: table.principalId,\n stateHash: table.stateHash,\n currentStateJson: table.currentStateJson,\n currentPayloadJson: table.currentPayloadJson,\n currentProjectionJson: table.currentProjectionJson,\n currentGrantsJson: table.currentGrantsJson,\n currentMemberEnvelopesJson: table.currentMemberEnvelopesJson,\n previousStatesJson: table.previousStatesJson,\n updatedAt: table.updatedAt,\n };\n}\n\nexport async function loadPrincipalPolicyBundle(\n execSql: ExecSql,\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n): Promise<PrincipalPolicyBundleResponse | null> {\n await ensurePrincipalPolicyTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .where(\n and(\n eq(principalPolicies.principalType, principalType),\n eq(principalPolicies.principalId, principalId),\n ),\n )\n .limit(1);\n\n const row = rows[0] ? parsePrincipalPolicyRow(rows[0]) : null;\n return row ? parsePrincipalPolicyBundle(row) : null;\n}\n\nexport async function loadAllPrincipalPolicyBundles(\n execSql: ExecSql,\n): Promise<PrincipalPolicyBundleResponse[]> {\n await ensurePrincipalPolicyTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .orderBy(\n asc(principalPolicies.principalType),\n asc(principalPolicies.principalId),\n );\n const historyRows = await db\n .select(principalPolicyBundleSelection(principalPolicyBundleHistory))\n .from(principalPolicyBundleHistory)\n .orderBy(\n asc(principalPolicyBundleHistory.principalType),\n asc(principalPolicyBundleHistory.principalId),\n asc(principalPolicyBundleHistory.stateHash),\n );\n\n const bundles: PrincipalPolicyBundleResponse[] = [];\n\n for (const rawRow of [...rows, ...historyRows]) {\n const row = parsePrincipalPolicyRow(rawRow);\n\n if (!row) {\n continue;\n }\n\n bundles.push(parsePrincipalPolicyBundle(row));\n }\n\n return bundles;\n}\n\nexport async function loadPrincipalPolicyStateHash(\n execSql: ExecSql,\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n): Promise<string | null> {\n await ensurePrincipalPolicyTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ stateHash: principalPolicies.stateHash })\n .from(principalPolicies)\n .where(\n and(\n eq(principalPolicies.principalType, principalType),\n eq(principalPolicies.principalId, principalId),\n ),\n )\n .limit(1);\n\n return rows[0]?.stateHash ?? null;\n}\n\nfunction policyBundleRow(\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n): PrincipalPolicyRow {\n return {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n stateHash: bundle.currentState.stateHash,\n currentStateJson: JSON.stringify(bundle.currentState),\n currentPayloadJson: JSON.stringify(bundle.currentPayload),\n currentProjectionJson: JSON.stringify(bundle.currentProjection),\n currentGrantsJson: JSON.stringify(bundle.currentGrants),\n currentMemberEnvelopesJson: JSON.stringify(bundle.currentMemberEnvelopes),\n previousStatesJson: JSON.stringify(bundle.previousStates),\n updatedAt,\n };\n}\n\nfunction assertNoHeadConflict(\n incoming: StoredPrincipalPolicyHead,\n checkpoint: StoredPrincipalPolicyHead | null,\n): void {\n if (\n checkpoint &&\n incoming.version === checkpoint.version &&\n incoming.stateHash !== checkpoint.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy bundle conflicts with the cached head at one version\",\n );\n }\n}\n\nasync function archiveOlderPolicyBundle(\n tx: ClientSQLiteTransactionScope,\n storedPolicy: SelectedPrincipalPolicyRow | undefined,\n storedHead: StoredPrincipalPolicyHead | null,\n incomingHead: StoredPrincipalPolicyHead,\n): Promise<void> {\n if (\n !storedPolicy ||\n !storedHead ||\n storedHead.version >= incomingHead.version\n ) {\n return;\n }\n const archiveRow = parsePrincipalPolicyRow(storedPolicy);\n if (!archiveRow) {\n return;\n }\n try {\n parsePrincipalPolicyBundle(archiveRow);\n await tx\n .insert(principalPolicyBundleHistory)\n .values(archiveRow)\n .onConflictDoNothing()\n .run();\n } catch {\n // A corrupt cache row is replaced, never retained as key material.\n }\n}\n\nasync function writePrincipalPolicyBundle(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n nextRow: PrincipalPolicyRow,\n incomingHead: StoredPrincipalPolicyHead,\n): Promise<void> {\n const wherePrincipal = and(\n eq(principalPolicies.principalType, nextRow.principalType),\n eq(principalPolicies.principalId, nextRow.principalId),\n );\n const [storedPolicy] = await tx\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .where(wherePrincipal)\n .limit(1);\n const [durableCheckpoint] = await tx\n .select({\n stateHash: principalPolicyCheckpoints.stateHash,\n version: principalPolicyCheckpoints.version,\n })\n .from(principalPolicyCheckpoints)\n .where(\n and(\n eq(principalPolicyCheckpoints.principalType, nextRow.principalType),\n eq(principalPolicyCheckpoints.principalId, nextRow.principalId),\n ),\n )\n .limit(1);\n const storedHead = storedPolicy\n ? parseStoredPrincipalPolicyHead(storedPolicy.currentStateJson)\n : null;\n if (\n storedPolicy &&\n storedHead?.version === incomingHead.version &&\n storedHead.stateHash === incomingHead.stateHash\n ) {\n assertSameHeadPrincipalPolicyBundle(storedPolicy, nextRow);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n const [retainedPolicy] = await tx\n .select(principalPolicyBundleSelection(principalPolicyBundleHistory))\n .from(principalPolicyBundleHistory)\n .where(\n and(\n eq(principalPolicyBundleHistory.principalType, nextRow.principalType),\n eq(principalPolicyBundleHistory.principalId, nextRow.principalId),\n eq(principalPolicyBundleHistory.stateHash, nextRow.stateHash),\n ),\n )\n .limit(1);\n if (retainedPolicy) {\n assertSameHeadPrincipalPolicyBundle(retainedPolicy, nextRow);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n }\n const effectiveHead =\n durableCheckpoint &&\n (!storedHead || durableCheckpoint.version >= storedHead.version)\n ? durableCheckpoint\n : storedHead;\n assertNoHeadConflict(incomingHead, storedHead);\n assertNoHeadConflict(incomingHead, durableCheckpoint ?? null);\n if (effectiveHead && incomingHead.version < effectiveHead.version) {\n return;\n }\n\n await archiveOlderPolicyBundle(tx, storedPolicy, storedHead, incomingHead);\n await tx\n .insert(principalPolicies)\n .values(nextRow)\n .onConflictDoUpdate({\n target: [principalPolicies.principalType, principalPolicies.principalId],\n set: nextRow,\n })\n .run();\n await tx\n .delete(principalPolicyBundleHistory)\n .where(\n and(\n eq(principalPolicyBundleHistory.principalType, nextRow.principalType),\n eq(principalPolicyBundleHistory.principalId, nextRow.principalId),\n eq(principalPolicyBundleHistory.stateHash, nextRow.stateHash),\n ),\n )\n .run();\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n}\n\nexport async function writePrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n await recordPrincipalPolicyBundleOrganizationInTransaction(\n tx,\n bundle,\n organizationId,\n );\n await writePrincipalPolicyBundle(\n tx,\n bundle,\n policyBundleRow(bundle, updatedAt),\n bundle.currentState,\n );\n}\n\nexport async function assertPrincipalPolicyBundleStoredInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const expected = policyBundleRow(bundle, bundle.currentState.createdAt);\n const [stored] = await tx\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .where(\n and(\n eq(principalPolicies.principalType, expected.principalType),\n eq(principalPolicies.principalId, expected.principalId),\n ),\n )\n .limit(1);\n if (!stored) {\n throw new Error(\"Verified principal policy bundle was not persisted\");\n }\n assertSameHeadPrincipalPolicyBundle(stored, expected);\n}\n\nexport async function retainPrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n const row = policyBundleRow(bundle, updatedAt);\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: row.principalId,\n principalType: row.principalType,\n });\n const [current] = await tx\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .where(\n and(\n eq(principalPolicies.principalType, row.principalType),\n eq(principalPolicies.principalId, row.principalId),\n ),\n )\n .limit(1);\n if (current?.stateHash === row.stateHash) {\n assertSameHeadPrincipalPolicyBundle(current, row);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n const [retained] = await tx\n .select(principalPolicyBundleSelection(principalPolicyBundleHistory))\n .from(principalPolicyBundleHistory)\n .where(\n and(\n eq(principalPolicyBundleHistory.principalType, row.principalType),\n eq(principalPolicyBundleHistory.principalId, row.principalId),\n eq(principalPolicyBundleHistory.stateHash, row.stateHash),\n ),\n )\n .limit(1);\n if (retained) {\n assertSameHeadPrincipalPolicyBundle(retained, row);\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n return;\n }\n await tx.insert(principalPolicyBundleHistory).values(row).run();\n await indexPrincipalPolicyBundleInTransaction(tx, bundle);\n}\n\nexport async function savePrincipalPolicyBundle(\n execSql: ExecSql,\n bundle: PrincipalPolicyBundleResponse,\n updatedAt: string,\n organizationId: string,\n options?: { stillCurrent?: (() => boolean) | undefined } | undefined,\n): Promise<void> {\n await ensureSqlTables(execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const save = (tx: ClientSQLiteTransactionScope) =>\n writePrincipalPolicyBundleInTransaction(\n tx,\n bundle,\n updatedAt,\n organizationId,\n );\n if (options?.stillCurrent) {\n await runtime.guardedTransaction(save, options.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(save, { behavior: \"immediate\" });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalPolicyReferenceCheckpoint.js","sourceRoot":"","sources":["principalPolicyReferenceCheckpoint.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,EAAE,oCAAoC,EAAE,MAAM,+BAA+B,CAAC;AAErF,MAAM,UAAU,uCAAuC,CACrD,MAAqC,EACrC,UAA4C;IAE5C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,oCAAoC,CAAC,UAAU,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC;IACtE,IAAI,MAAM,CAAC,YAAY,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,EAAE,CAAC;QACrD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,MAAM,CAAC,YAAY,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,EAAE,CAAC;QACvD,IAAI,MAAM,CAAC,YAAY,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS,EAAE,CAAC;YAC3D,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,2DAA2D,CAC5D,CAAC;QACJ,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,MAAM,gBAAgB,GAAG,2BAA2B,CAAC,MAAM,CAAC,CAAC,MAAM,CACjE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,CAChD,CAAC;IACF,IAAI,gBAAgB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,uBAAuB,CAC/B,mBAAmB,EACnB,6DAA6D,CAC9D,CAAC;IACJ,CAAC;IACD,IACE,gBAAgB,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS,CAAC,EAC1E,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,4DAA4D,CAC7D,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyBundleStates } from \"../principals/principalPolicyStates\";\nimport { assertPrincipalPolicyCheckpointShape } from \"./keyingCheckpointPersistence\";\n\nexport function applyPrincipalPolicyReferenceCheckpoint(\n bundle: PrincipalPolicyBundleResponse,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): PrincipalPolicyBundleResponse | null {\n if (!checkpoint) {\n return bundle;\n }\n assertPrincipalPolicyCheckpointShape(checkpoint, bundle.currentState);\n if (bundle.currentState.version < checkpoint.version) {\n return null;\n }\n if (bundle.currentState.version === checkpoint.version) {\n if (bundle.currentState.stateHash !== checkpoint.stateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy head conflicts with the local checkpoint\",\n );\n }\n return bundle;\n }\n const checkpointStates = principalPolicyBundleStates(bundle).filter(\n (state) => state.version === checkpoint.version,\n );\n if (checkpointStates.length === 0) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"principal policy chain does not extend the local checkpoint\",\n );\n }\n if (\n checkpointStates.some((state) => state.stateHash !== checkpoint.stateHash)\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy chain conflicts with the local checkpoint\",\n );\n }\n return bundle;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalPolicyReferenceIndexPersistence.js","sourceRoot":"","sources":["principalPolicyReferenceIndexPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,EAAE,+BAA+B,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,4BAA4B,CAAC;AAgBpC,MAAM,2BAA2B,GAAG,qBAAqB,CACvD,+BAA+B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I,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,CAAC;IACnE,IAAI,OAAO;QAAE,MAAM,OAAO,CAAC;AAC7B,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { and, eq, inArray, or } from \"drizzle-orm\";\nimport { principalPolicyBundleStates } from \"../principals/principalPolicyStates\";\nimport { principalPolicyBundleReferences } from \"../sqlite/schema\";\nimport {\n sqliteInsertBatchSize,\n sqliteRowsPerStatement,\n} from \"../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\n\ntype PrincipalPolicyReferenceRow =\n typeof principalPolicyBundleReferences.$inferInsert;\n\ntype StoredPrincipalPolicyReference = Pick<\n typeof principalPolicyBundleReferences.$inferSelect,\n | \"version\"\n | \"stateHash\"\n | \"keyEpoch\"\n | \"keyFingerprint\"\n | \"bundleVersion\"\n | \"bundleStateHash\"\n>;\n\nconst REFERENCE_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n principalPolicyBundleReferences,\n);\n// Principal type and id plus the bundle version and state hash bind once.\nconst REFERENCE_LOOKUP_VERSIONS = sqliteRowsPerStatement(1, 4);\n\n/** The exact six-field match; the lookup already fixes the principal. */\nfunction isSameReference(\n stored: StoredPrincipalPolicyReference,\n row: PrincipalPolicyReferenceRow,\n): boolean {\n return (\n stored.version === row.version &&\n stored.stateHash === row.stateHash &&\n stored.keyEpoch === row.keyEpoch &&\n stored.keyFingerprint === row.keyFingerprint\n );\n}\n\n/** The table's primary key within one principal. */\nfunction referenceKey(\n row: Pick<\n StoredPrincipalPolicyReference,\n \"version\" | \"stateHash\" | \"keyEpoch\" | \"keyFingerprint\" | \"bundleStateHash\"\n >,\n): string {\n return JSON.stringify([\n row.version,\n row.stateHash,\n row.keyEpoch,\n row.keyFingerprint,\n row.bundleStateHash,\n ]);\n}\n\n/** Rows either equivocation check can match, read before this bundle's writes. */\nasync function loadStoredReferences(\n tx: ClientSQLiteTransactionScope,\n head: PrincipalPolicyBundleResponse[\"currentState\"],\n versions: readonly number[],\n): Promise<StoredPrincipalPolicyReference[]> {\n const stored: StoredPrincipalPolicyReference[] = [];\n for (\n let index = 0;\n index < versions.length;\n index += REFERENCE_LOOKUP_VERSIONS\n ) {\n stored.push(\n ...(await tx\n .select({\n version: principalPolicyBundleReferences.version,\n stateHash: principalPolicyBundleReferences.stateHash,\n keyEpoch: principalPolicyBundleReferences.keyEpoch,\n keyFingerprint: principalPolicyBundleReferences.keyFingerprint,\n bundleVersion: principalPolicyBundleReferences.bundleVersion,\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(\n principalPolicyBundleReferences.principalType,\n head.principalType,\n ),\n eq(principalPolicyBundleReferences.principalId, head.principalId),\n inArray(\n principalPolicyBundleReferences.version,\n versions.slice(index, index + REFERENCE_LOOKUP_VERSIONS),\n ),\n or(\n eq(principalPolicyBundleReferences.bundleVersion, head.version),\n eq(\n principalPolicyBundleReferences.bundleStateHash,\n head.stateHash,\n ),\n ),\n ),\n )),\n );\n }\n return stored;\n}\n\n/**\n * Rows written earlier in the same bundle all carry its head, so neither\n * check can match them: each state's outcome depends only on stored rows.\n */\nfunction referenceConflict(\n row: PrincipalPolicyReferenceRow,\n stored: readonly StoredPrincipalPolicyReference[],\n): KeyingVerificationError | null {\n const sameReference = stored.filter((candidate) =>\n isSameReference(candidate, row),\n );\n if (\n sameReference.some(\n (candidate) =>\n candidate.bundleVersion === row.bundleVersion &&\n candidate.bundleStateHash !== row.bundleStateHash,\n )\n )\n return new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference has conflicting bundle heads at one version\",\n );\n const indexed = sameReference.find(\n (candidate) => candidate.bundleStateHash === row.bundleStateHash,\n );\n if (indexed && indexed.bundleVersion !== row.bundleVersion)\n return new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index conflicts with the bundle head\",\n );\n return null;\n}\n\nasync function insertMissingReferences(\n tx: ClientSQLiteTransactionScope,\n rows: readonly PrincipalPolicyReferenceRow[],\n stored: readonly StoredPrincipalPolicyReference[],\n): Promise<void> {\n const present = new Set(stored.map(referenceKey));\n const missing = new Map<string, PrincipalPolicyReferenceRow>();\n for (const row of rows) {\n const key = referenceKey(row);\n if (!present.has(key) && !missing.has(key)) missing.set(key, row);\n }\n const values = [...missing.values()];\n for (\n let index = 0;\n index < values.length;\n index += REFERENCE_INSERT_BATCH_SIZE\n ) {\n await tx\n .insert(principalPolicyBundleReferences)\n .values(values.slice(index, index + REFERENCE_INSERT_BATCH_SIZE))\n .onConflictDoNothing()\n .run();\n }\n}\n\n/**\n * Index every state of a verified bundle under its head. Fails in state order\n * with the per-state checks' errors, keeping the states indexed before the\n * first failure.\n */\nexport async function indexPrincipalPolicyBundleInTransaction(\n tx: ClientSQLiteTransactionScope,\n bundle: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const head = bundle.currentState;\n const states = principalPolicyBundleStates(bundle);\n const foreignIndex = states.findIndex(\n (state) =>\n state.principalType !== head.principalType ||\n state.principalId !== head.principalId,\n );\n const rows: PrincipalPolicyReferenceRow[] = (\n foreignIndex === -1 ? states : states.slice(0, foreignIndex)\n ).map((state) => ({\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n bundleVersion: head.version,\n bundleStateHash: head.stateHash,\n }));\n const stored =\n rows.length === 0\n ? []\n : await loadStoredReferences(tx, head, [\n ...new Set(rows.map((row) => row.version)),\n ]);\n let failure: KeyingVerificationError | null = null;\n let accepted = rows.length;\n for (const [index, row] of rows.entries()) {\n failure = referenceConflict(row, stored);\n if (failure) {\n accepted = index;\n break;\n }\n }\n if (!failure && foreignIndex !== -1)\n failure = new KeyingVerificationError(\n \"object_mismatch\",\n \"principal policy bundle reference belongs to another principal\",\n );\n await insertMissingReferences(tx, rows.slice(0, accepted), stored);\n if (failure) throw failure;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalPolicyReferencePersistence.js","sourceRoot":"","sources":["principalPolicyReferencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EACL,sCAAsC,EACtC,2BAA2B,GAC5B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,iBAAiB,EACjB,4BAA4B,EAC5B,+BAA+B,GAChC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AAEvF,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC;AACvF,OAAO,EACL,2BAA2B,EAC3B,8BAA8B,GAE/B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,uCAAuC,EAAE,MAAM,sCAAsC,CAAC;AAC/F,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AAOpF,SAAS,4BAA4B,CACnC,MAAqC;IAErC,MAAM,MAAM,GAAG,2BAA2B,CAAC,MAAM,CAAC,CAAC;IACnD,IAAI,MAAM,CAAC,MAAM,KAAK,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC;QAClD,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,qEAAqE,CACtE,CAAC;IACJ,CAAC;IACD,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC3C,KAAK,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC;QAC9C,IACE,KAAK,CAAC,aAAa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E,CAAC;YACtE,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,wEAAwE,CACzE,CAAC;QACJ,CAAC;QACD,YAAY,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;IACxC,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,OAAgB,EAChB,SAAkC,EAClC,UAA4C;IAE5C,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAChC,MAAM,2BAA2B,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,CAAC,UAAU,EAAE,YAAY,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACnD,cAAc,CAAC,OAAO,EAAE,SAAS,CAAC;QAClC,gBAAgB,CAAC,OAAO,EAAE,SAAS,CAAC;KACrC,CAAC,CAAC;IACH,MAAM,aAAa,GAAG,gBAAgB,CAAC,YAAY,CAAC,CAAC;IACrD,MAAM,YAAY,GAAG,MAAM,gBAAgB,CACzC,OAAO,EACP,SAAS,EACT,UAAU,EACV,aAAa,CACd,CAAC;IACF,MAAM,UAAU,GAAG,iBAAiB,CAClC,UAAU,EACV,YAAY,EACZ,aAAa,EACb,SAAS,CACV,CAAC;IACF,MAAM,QAAQ,GAAG,qBAAqB,CAAC,UAAU,CAAC,CAAC;IACnD,OAAO,QAAQ;QACb,CAAC,CAAC,uCAAuC,CAAC,QAAQ,EAAE,UAAU,CAAC;QAC/D,CAAC,CAAC,IAAI,CAAC;AACX,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n isPrincipalPolicyBundleResponse,\n isReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray } from \"drizzle-orm\";\nimport {\n principalPolicyBundleContainsReference,\n principalPolicyBundleStates,\n} from \"../principals/principalPolicyStates\";\nimport {\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n} from \"../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { assertSameHeadPrincipalPolicyBundle } from \"./principalPolicyBundleIntegrity\";\nimport {\n ensurePrincipalPolicyTables,\n principalPolicyBundleSelection,\n type SelectedPrincipalPolicyRow,\n} from \"./principalPolicyPersistence\";\nimport { applyPrincipalPolicyReferenceCheckpoint } from \"./principalPolicyReferenceCheckpoint\";\nimport { storedPrincipalPolicyBundleFromJson } from \"./storedPrincipalPolicyBundle\";\n\ninterface IndexedBundleHead {\n readonly bundleStateHash: string;\n readonly bundleVersion: number;\n}\n\nfunction assertUnambiguousBundleChain(\n bundle: PrincipalPolicyBundleResponse,\n): void {\n const states = principalPolicyBundleStates(bundle);\n if (states.length !== bundle.currentState.version) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"stored principal policy bundle chain length does not match its head\",\n );\n }\n const versions = new Map<number, string>();\n for (const [index, state] of states.entries()) {\n if (\n state.principalType !== bundle.currentState.principalType ||\n state.principalId !== bundle.currentState.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle chain belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(state.version) ||\n state.version !== index + 1 ||\n !Number.isSafeInteger(state.keyEpoch) ||\n state.keyEpoch < 1 ||\n state.principalId.length === 0 ||\n state.stateHash.length === 0 ||\n state.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle chain has an invalid version or epoch\",\n );\n }\n if (versions.has(state.version)) {\n const previousHash = versions.get(state.version);\n throw new KeyingVerificationError(\n previousHash === state.stateHash ? \"duplicate_entry\" : \"equivocation\",\n \"stored principal policy bundle chain repeats a version\",\n );\n }\n versions.set(state.version, state.stateHash);\n }\n}\n\nfunction parseBoundBundle(\n row: SelectedPrincipalPolicyRow,\n): PrincipalPolicyBundleResponse {\n let bundle: unknown;\n try {\n bundle = storedPrincipalPolicyBundleFromJson(row);\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle contains malformed JSON\",\n );\n }\n if (!isPrincipalPolicyBundleResponse(bundle)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"stored principal policy bundle is invalid\",\n );\n }\n if (\n bundle.currentState.principalType !== row.principalType ||\n bundle.currentState.principalId !== row.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"stored principal policy bundle row belongs to another principal\",\n );\n }\n if (bundle.currentState.stateHash !== row.stateHash) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle row has a different head hash\",\n );\n }\n assertUnambiguousBundleChain(bundle);\n return bundle;\n}\n\nfunction assertIndexedBundle(\n bundle: PrincipalPolicyBundleResponse,\n indexed: IndexedBundleHead,\n reference: ReferencedPrincipalHead,\n): void {\n if (\n bundle.currentState.stateHash !== indexed.bundleStateHash ||\n bundle.currentState.version !== indexed.bundleVersion\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index conflicts with its bundle head\",\n );\n }\n if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"indexed principal policy bundle does not contain the exact reference\",\n );\n }\n}\n\nfunction addCandidate(\n candidates: Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >,\n bundle: PrincipalPolicyBundleResponse,\n row: SelectedPrincipalPolicyRow,\n): void {\n const existing = candidates.get(bundle.currentState.stateHash);\n if (existing) {\n assertSameHeadPrincipalPolicyBundle(existing.row, row);\n return;\n }\n candidates.set(bundle.currentState.stateHash, { bundle, row });\n}\n\nfunction assertCurrentDoesNotConflict(\n bundle: PrincipalPolicyBundleResponse,\n reference: ReferencedPrincipalHead,\n): void {\n if (bundle.currentState.version < reference.version) {\n return;\n }\n const stateAtReference = principalPolicyBundleStates(bundle).find(\n (state) => state.version === reference.version,\n );\n if (!stateAtReference) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"current principal policy chain omits the referenced version\",\n );\n }\n if (stateAtReference.stateHash !== reference.stateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"current principal policy chain conflicts with the referenced version\",\n );\n }\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"current principal policy state does not match the exact reference\",\n );\n}\n\nfunction selectNewestCandidate(\n candidates: ReadonlyMap<\n string,\n { readonly bundle: PrincipalPolicyBundleResponse }\n >,\n): PrincipalPolicyBundleResponse | null {\n let selected: PrincipalPolicyBundleResponse | null = null;\n const stateHashByVersion = new Map<number, string>();\n for (const { bundle } of candidates.values()) {\n const existingHash = stateHashByVersion.get(bundle.currentState.version);\n if (\n existingHash !== undefined &&\n existingHash !== bundle.currentState.stateHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"stored principal policy bundles conflict at one version\",\n );\n }\n stateHashByVersion.set(\n bundle.currentState.version,\n bundle.currentState.stateHash,\n );\n if (\n !selected ||\n bundle.currentState.version > selected.currentState.version\n ) {\n selected = bundle;\n }\n }\n return selected;\n}\n\nfunction assertReferenceShape(reference: ReferencedPrincipalHead): void {\n if (!isReferencedPrincipalStateResponse(reference)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n if (\n !Number.isInteger(reference.version) ||\n reference.version < 1 ||\n !Number.isSafeInteger(reference.keyEpoch) ||\n reference.keyEpoch < 1 ||\n reference.principalId.length === 0 ||\n reference.stateHash.length === 0 ||\n reference.keyFingerprint.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference is malformed\",\n );\n }\n}\n\nasync function loadCurrentRow(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n): Promise<SelectedPrincipalPolicyRow | undefined> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [row] = await db\n .select(principalPolicyBundleSelection(principalPolicies))\n .from(principalPolicies)\n .where(\n and(\n eq(principalPolicies.principalType, reference.principalType),\n eq(principalPolicies.principalId, reference.principalId),\n ),\n )\n .limit(1);\n return row;\n}\n\nasync function loadIndexedHeads(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n): Promise<IndexedBundleHead[]> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select({\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n bundleVersion: principalPolicyBundleReferences.bundleVersion,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(\n principalPolicyBundleReferences.principalType,\n reference.principalType,\n ),\n eq(principalPolicyBundleReferences.principalId, reference.principalId),\n eq(principalPolicyBundleReferences.version, reference.version),\n eq(principalPolicyBundleReferences.stateHash, reference.stateHash),\n eq(principalPolicyBundleReferences.keyEpoch, reference.keyEpoch),\n eq(\n principalPolicyBundleReferences.keyFingerprint,\n reference.keyFingerprint,\n ),\n ),\n );\n}\n\nfunction indexHeadsByHash(\n heads: readonly IndexedBundleHead[],\n): Map<string, IndexedBundleHead> {\n const stateHashByVersion = new Map<number, string>();\n for (const head of heads) {\n if (\n !Number.isInteger(head.bundleVersion) ||\n head.bundleVersion < 1 ||\n head.bundleStateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy reference index is malformed\",\n );\n }\n const indexedHash = stateHashByVersion.get(head.bundleVersion);\n if (indexedHash !== undefined && indexedHash !== head.bundleStateHash) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"principal policy reference index has conflicting bundle heads at one version\",\n );\n }\n stateHashByVersion.set(head.bundleVersion, head.bundleStateHash);\n }\n return new Map(heads.map((head) => [head.bundleStateHash, head]));\n}\n\nasync function loadRetainedRows(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n currentRow: SelectedPrincipalPolicyRow | undefined,\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n): Promise<SelectedPrincipalPolicyRow[]> {\n const hashes = new Set([reference.stateHash, ...indexedByHash.keys()]);\n if (currentRow) {\n hashes.delete(currentRow.stateHash);\n }\n if (hashes.size === 0) {\n return [];\n }\n // Remote reset deliberately clears mutable heads while retaining historical\n // key material, so an index target can outlive its bundle row. Such a target\n // is only a selection hint; rows that still exist remain authoritative.\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select(principalPolicyBundleSelection(principalPolicyBundleHistory))\n .from(principalPolicyBundleHistory)\n .where(\n and(\n eq(principalPolicyBundleHistory.principalType, reference.principalType),\n eq(principalPolicyBundleHistory.principalId, reference.principalId),\n inArray(principalPolicyBundleHistory.stateHash, [...hashes]),\n ),\n );\n}\n\nfunction collectCandidates(\n currentRow: SelectedPrincipalPolicyRow | undefined,\n retainedRows: readonly SelectedPrincipalPolicyRow[],\n indexedByHash: ReadonlyMap<string, IndexedBundleHead>,\n reference: ReferencedPrincipalHead,\n) {\n const candidates = new Map<\n string,\n { bundle: PrincipalPolicyBundleResponse; row: SelectedPrincipalPolicyRow }\n >();\n if (currentRow) {\n const bundle = parseBoundBundle(currentRow);\n const indexed = indexedByHash.get(currentRow.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n }\n if (principalPolicyBundleContainsReference(bundle, reference)) {\n addCandidate(candidates, bundle, currentRow);\n } else {\n assertCurrentDoesNotConflict(bundle, reference);\n }\n }\n for (const row of retainedRows) {\n const bundle = parseBoundBundle(row);\n const indexed = indexedByHash.get(row.stateHash);\n if (indexed) {\n assertIndexedBundle(bundle, indexed, reference);\n } else if (!principalPolicyBundleContainsReference(bundle, reference)) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"stored principal policy bundle head does not match the exact reference\",\n );\n }\n addCandidate(candidates, bundle, row);\n }\n return candidates;\n}\n\nexport async function loadPrincipalPolicyBundleForReference(\n execSql: ExecSql,\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await ensurePrincipalPolicyTables(execSql);\n const [currentRow, indexedHeads] = await Promise.all([\n loadCurrentRow(execSql, reference),\n loadIndexedHeads(execSql, reference),\n ]);\n const indexedByHash = indexHeadsByHash(indexedHeads);\n const retainedRows = await loadRetainedRows(\n execSql,\n reference,\n currentRow,\n indexedByHash,\n );\n const candidates = collectCandidates(\n currentRow,\n retainedRows,\n indexedByHash,\n reference,\n );\n const selected = selectNewestCandidate(candidates);\n return selected\n ? applyPrincipalPolicyReferenceCheckpoint(selected, checkpoint)\n : null;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"verifiedPrincipalPolicyBundle.js","sourceRoot":"","sources":["verifiedPrincipalPolicyBundle.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,GAEpC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,kCAAkC,EAAE,MAAM,kCAAkC,CAAC;AAEtF,MAAM,CAAC,KAAK,UAAU,iCAAiC,CAAC,KAGvD;IACC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IACjC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC;IACrC,MAAM,aAAa,GAAG;QACpB,GAAG,MAAM,CAAC,cAAc;QACxB;YACE,KAAK,EAAE,MAAM,CAAC,YAAY;YAC1B,UAAU,EAAE,MAAM,CAAC,iBAAiB;YACpC,MAAM,EAAE,MAAM,CAAC,aAAa;SAC7B;KACF,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAChB,GAAG,KAAK;QACR,UAAU,EAAE,mCAAmC,CAAC,KAAK,CAAC,UAAU,CAAC;QACjE,MAAM,EAAE,iCAAiC,CAAC,KAAK,CAAC,MAAM,CAAC;KACxD,CAAC,CAAC,CAAC;IACJ,MAAM,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAC9C,GAAG,KAAK;QACR,UAAU,EAAE,mCAAmC,CAAC,KAAK,CAAC,UAAU,CAAC;QACjE,MAAM,EAAE,iCAAiC,CAAC,KAAK,CAAC,MAAM,CAAC;KACxD,CAAC,CAAC,CAAC;IACJ,IACE,yBAAyB,CACvB,aAAa,EACb,iCAAiC,CAClC;QACD,yBAAyB,CACvB,eAAe,EACf,mCAAmC,CACpC,EACD,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,mDAAmD,CACpD,CAAC;IACJ,CAAC;IACD,MAAM,kCAAkC,CAAC;QACvC,OAAO,EAAE,KAAK,CAAC,MAAM;QACrB,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../keying/canonicalJson\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyCurrent\";\n\nexport async function assertBundleMatchesVerifiedPolicy(input: {\n bundle: PrincipalPolicyBundleResponse;\n policy: VerifiedPrincipalPolicy;\n}): Promise<void> {\n const { bundle, policy } = input;\n const history = policy.history ?? [];\n const expectedChain = [\n ...bundle.previousStates,\n {\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n },\n ].map((entry) => ({\n ...entry,\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n }));\n const verifiedHistory = history.map((entry) => ({\n ...entry,\n projection: normalizePrincipalProjectionMembers(entry.projection),\n grants: normalizePrincipalContainerGrants(entry.grants),\n }));\n if (\n canonicalKeyingJsonString(\n expectedChain,\n \"principal policy bundle history\",\n ) !==\n canonicalKeyingJsonString(\n verifiedHistory,\n \"verified principal policy history\",\n )\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Verified principal policy bundle history mismatch\",\n );\n }\n await assertCurrentMatchesVerifiedPolicy({\n current: input.bundle,\n policy: input.policy,\n });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"verifiedPrincipalPolicyCurrent.js","sourceRoot":"","sources":["verifiedPrincipalPolicyCurrent.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mCAAmC,EACnC,0CAA0C,EAC1C,uBAAuB,EACvB,iCAAiC,EACjC,mCAAmC,EACnC,sCAAsC,GAGvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAMpE,SAAS,eAAe,CAAC,OAAe;IACtC,MAAM,IAAI,uBAAuB,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;AAC7D,CAAC;AAED,KAAK,UAAU,mBAAmB,CAChC,OAAmC;IAEnC,IAAI,CAAC;QACH,OAAO,MAAM,mCAAmC,CAC9C,OAAO,CAAC,sBAAsB,CAAC,SAAS,CACzC,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,sCAAsC,EAAE,CAAC;YAC5D,MAAM,IAAI,uBAAuB,CAAC,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QACpE,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,KAAK,UAAU,2BAA2B,CAAC,KAG1C;IACC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAClC,MAAM,WAAW,GAAG,MAAM,0CAA0C,CAClE,OAAO,CAAC,cAAc,CAAC,UAAU,CAClC,CAAC;IACF,MAAM,aAAa,GAAG,MAAM,mBAA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CAAC,SAAS,EAChD,CAAC;QACD,eAAe,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;IACD,IACE,yBAAyB,CACvB,OAAO,CAAC,YAAY,EACpB,gCAAgC,CACjC;QACC,yBAAyB,CACvB,MAAM,CAAC,KAAK,EACZ,iCAAiC,CAClC;QACH,yBAAyB,CACvB,mCAAmC,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAC9D,qCAAqC,CACtC;YACC,yBAAyB,CACvB,mCAAmC,CAAC,MAAM,CAAC,UAAU,CAAC,EACtD,sCAAsC,CACvC;QACH,yBAAyB,CACvB,iCAAiC,CAAC,OAAO,CAAC,aAAa,CAAC,EACxD,iCAAiC,CAClC;YACC,yBAAyB,CACvB,iCAAiC,CAAC,MAAM,CAAC,MAAM,CAAC,EAChD,kCAAkC,CACnC,EACH,CAAC;QACD,eAAe,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,2BAA2B,CAAC,KAAK,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n computePrincipalMemberEnvelopesRoot,\n computePrincipalStatePayloadCiphertextHash,\n KeyingVerificationError,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n PrincipalMemberEnvelopeValidationError,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { canonicalKeyingJsonString } from \"../keying/canonicalJson\";\n\ntype VerifiedCurrentPolicy =\n | VerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\nfunction currentMismatch(message: string): never {\n throw new KeyingVerificationError(\"equivocation\", message);\n}\n\nasync function memberEnvelopesRoot(\n current: PrincipalPolicyPageCurrent,\n): Promise<string> {\n try {\n return await computePrincipalMemberEnvelopesRoot(\n current.currentMemberEnvelopes.envelopes,\n );\n } catch (error) {\n if (error instanceof PrincipalMemberEnvelopeValidationError) {\n throw new KeyingVerificationError(\"invalid_shape\", error.message);\n }\n throw error;\n }\n}\n\nasync function assertCurrentPayloadMatches(input: {\n current: PrincipalPolicyPageCurrent;\n policy: VerifiedCurrentPolicy;\n}): Promise<void> {\n const { current, policy } = input;\n const payloadHash = await computePrincipalStatePayloadCiphertextHash(\n current.currentPayload.ciphertext,\n );\n const envelopesRoot = await memberEnvelopesRoot(current);\n if (\n current.currentPayload.principalType !== policy.principalType ||\n current.currentPayload.principalId !== policy.principalId ||\n current.currentPayload.stateHash !== policy.stateHash ||\n current.currentPayload.ciphertextHash !== payloadHash ||\n policy.state.payloadCiphertextHash !== payloadHash ||\n current.currentMemberEnvelopes.principalType !== policy.principalType ||\n current.currentMemberEnvelopes.principalId !== policy.principalId ||\n current.currentMemberEnvelopes.stateHash !== policy.stateHash ||\n current.currentMemberEnvelopes.epoch !== policy.keyEpoch ||\n envelopesRoot !== policy.state.memberEnvelopesRoot\n ) {\n currentMismatch(\"Verified principal policy current payload mismatch\");\n }\n}\n\n/** Bind current wire artifacts to already verified policy evidence; never authenticate history. */\nexport async function assertCurrentMatchesVerifiedPolicy(input: {\n current: PrincipalPolicyPageCurrent;\n policy: VerifiedCurrentPolicy;\n}): Promise<void> {\n const { current, policy } = input;\n if (\n current.currentState.principalType !== policy.principalType ||\n current.currentState.principalId !== policy.principalId ||\n current.currentState.version !== policy.version ||\n current.currentState.keyEpoch !== policy.keyEpoch ||\n current.currentState.stateHash !== policy.stateHash ||\n policy.checkpoint.version !== policy.version ||\n policy.checkpoint.stateHash !== policy.stateHash\n ) {\n currentMismatch(\"Verified principal policy current head mismatch\");\n }\n if (\n canonicalKeyingJsonString(\n current.currentState,\n \"principal policy current state\",\n ) !==\n canonicalKeyingJsonString(\n policy.state,\n \"verified principal policy state\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(current.currentProjection),\n \"principal policy current projection\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(policy.projection),\n \"verified principal policy projection\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(current.currentGrants),\n \"principal policy current grants\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(policy.grants),\n \"verified principal policy grants\",\n )\n ) {\n currentMismatch(\"Verified principal policy current content mismatch\");\n }\n\n await assertCurrentPayloadMatches(input);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"verifiedPrincipalPolicyRetentionPersistence.js","sourceRoot":"","sources":["verifiedPrincipalPolicyRetentionPersistence.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AAEvF,OAAO,EACL,2BAA2B,EAC3B,wCAAwC,GACzC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AAEpF,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAOzD;IACC,MAAM,iCAAiC,CAAC,KAAK,CAAC,CAAC;IAC/C,MAAM,2BAA2B,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACjD,MAAM,OAAO,GAAG,iCAAiC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACjE,MAAM,MAAM,GAAG,CACb,EAAkE,EAClE,EAAE,CACF,wCAAwC,CACtC,EAAE,EACF,KAAK,CAAC,MAAM,EACZ,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,MAAM,EAAE,KAAK,CAAC,YAAY,EAAE;YAC3D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport {\n ensurePrincipalPolicyTables,\n retainPrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\n/** Retains a just-verified epoch without promoting it to the mutable head. */\nexport async function retainVerifiedPrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly policy: VerifiedPrincipalPolicy;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n await assertBundleMatchesVerifiedPolicy(input);\n await ensurePrincipalPolicyTables(input.execSql);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const retain = (\n tx: Parameters<typeof retainPrincipalPolicyBundleInTransaction>[0],\n ) =>\n retainPrincipalPolicyBundleInTransaction(\n tx,\n input.bundle,\n input.updatedAt,\n input.organizationId,\n );\n if (input.stillCurrent) {\n await runtime.guardedTransaction(retain, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(retain, { behavior: \"immediate\" });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"containerSchema.js","sourceRoot":"","sources":["containerSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,OAAO,EACP,UAAU,EACV,WAAW,EACX,IAAI,GACL,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAuB,MAAM,kBAAkB,CAAC;AAE7E,MAAM,iBAAiB,GAAG,wBAAwB,CAAC;AAEnD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,WAAW,CACnC,YAAY,EACZ;IACE,EAAE,EAAE,IAAI,CAAC,IA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AAC,OAAO,EAAE;IACpD,UAAU,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IACtD,YAAY,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IAC3D,eAAe,EAAE,IAAI,CAAC,mBAAmB,CAAC;IAC1C,WAAW,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC,OAAO,EAAE;CAC5C,EACD,CAAC,KAAK,EAAE,EAAE,CAAC;IACT,UAAU,CAAC,EAAE,OAAO,EAAE,CAAC,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,eAAe,CAAC,EAAE,CAAC;CACvE,CACF,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAkC;IAClE;QACE,GAAG,oBAAoB,CAAC,UAAU,CAAC;QACnC,eAAe,EAAE,CAAC,cAAc,EAAE,MAAM,CAAC;KAC1C;IACD;QACE,GAAG,oBAAoB,CAAC,4BAA4B,CAAC;QACrD,eAAe,EAAE,CAAC,SAAS,CAAC;KAC7B;IACD,oBAAoB,CAAC,wBAAwB,CAAC;IAC9C,oBAAoB,CAAC,4BAA4B,CAAC;IAClD,oBAAoB,CAAC,2BAA2B,CAAC;CAClD,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,UAAU;IACV,4BAA4B;IAC5B,wBAAwB;IACxB,4BAA4B;IAC5B,2BAA2B;CAC5B,CAAC","sourcesContent":["import {\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n} from \"drizzle-orm/sqlite-core\";\nimport { defineSqlTableSchema, type SqlTableSchema } from \"./sqlTableSchema\";\n\nconst accessLevelColumn = \"effective_access_level\";\n\n/**\n * Materialized local container tree.\n *\n * Container rows describe the tree and its encrypted metadata document;\n * metadata rows live in `documents`. `id` is the primary key for structural\n * lookups. `metadataDocumentId` is the server metadata-document id when known;\n * `systemSlot` is an optional opaque app-owned slot. `displayName` and `icon`\n * are the decrypted metadata projection lists read: `displayName` stays\n * nullable so presentation falls back to `/` for a root and `Untitled`\n * otherwise. Local timestamps track client storage/structural changes, while\n * server timestamps are populated once the container has synced.\n */\nexport const containers = sqliteTable(\n \"containers\",\n {\n id: text(\"id\"),\n organizationId: text(\"organization_id\").notNull(),\n parentId: text(\"parent_id\"),\n metadataDocumentId: text(\"metadata_document_id\"),\n systemSlot: text(\"system_slot\"),\n displayName: text(\"display_name\"),\n icon: text(\"icon\"),\n effectiveAccessLevel: text(accessLevelColumn).notNull().default(\"read\"),\n localCreatedAt: text(\"local_created_at\").notNull(),\n localUpdatedAt: text(\"local_updated_at\").notNull(),\n serverCreatedAt: text(\"server_created_at\"),\n serverUpdatedAt: text(\"server_updated_at\"),\n },\n (table) => [primaryKey({ columns: [table.id] })],\n);\n\n/**\n * Latest removal observed for each container. Hydration must observe the same\n * generation before fetching verified restoration evidence; unsigned clocks\n * never establish a terminal deletion or bypass a concurrent removal. Cleared\n * observations retain their generation so remove/restore/remove cannot reuse it.\n */\nexport const containerHydrationTombstones = sqliteTable(\n \"container_hydration_tombstones\",\n {\n containerId: text(\"container_id\").notNull(),\n generation: integer(\"generation\").notNull().default(1),\n cleared: integer(\"cleared\", { mode: \"boolean\" }).notNull().default(false),\n reason: text(\"reason\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.containerId] })],\n);\n\n/**\n * Organization attribution for container metadata retained after access loss.\n * The container row is removed on revocation, so this marker retains the\n * organization scope needed by a later access-restoration sweep.\n */\nexport const dormantContainerMetadata = sqliteTable(\n \"dormant_container_metadata\",\n {\n containerId: text(\"container_id\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n retainedAt: text(\"retained_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.containerId] }),\n index(\"dormant_container_metadata_organization_idx\").on(\n table.organizationId,\n table.containerId,\n ),\n ],\n);\n\n/**\n * Organizations a held folder was re-homed away from. Purged-organization\n * recovery re-creates folders under their existing ids and a purged\n * organization never returns, so a later proof binding the folder back to one\n * of these organizations is a replay. Retained across remote resets.\n */\nexport const supersededContainerBindings = sqliteTable(\n \"superseded_container_bindings\",\n {\n containerId: text(\"container_id\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n supersededAt: text(\"superseded_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.containerId, table.organizationId] }),\n ],\n);\n\n/**\n * Durable request for a post-access-restoration crawl and sweep. Attempt state\n * enforces exponential backoff and a bounded retry budget across restarts.\n */\nexport const dormantMetadataSweepRequests = sqliteTable(\n \"dormant_metadata_sweep_requests\",\n {\n organizationId: text(\"organization_id\").notNull(),\n requesterUserId: text(\"requester_user_id\").notNull(),\n generation: integer(\"generation\").notNull().default(1),\n attemptCount: integer(\"attempt_count\").notNull().default(0),\n lastAttemptedAt: text(\"last_attempted_at\"),\n requestedAt: text(\"requested_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.organizationId, table.requesterUserId] }),\n ],\n);\n\nexport const containerTableSchemas: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(containers),\n requiredColumns: [\"display_name\", \"icon\"],\n },\n {\n ...defineSqlTableSchema(containerHydrationTombstones),\n requiredColumns: [\"cleared\"],\n },\n defineSqlTableSchema(dormantContainerMetadata),\n defineSqlTableSchema(dormantMetadataSweepRequests),\n defineSqlTableSchema(supersededContainerBindings),\n];\n\nexport const containerSQLiteSchema = {\n containers,\n containerHydrationTombstones,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n supersededContainerBindings,\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"documentHistoryPersistence.js","sourceRoot":"","sources":["documentHistoryPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,cAAc,EACd,yBAAyB,EACzB,cAAc,EACd,sBAAsB,GACvB,MAAM,iBAAiB,CAAC;AAC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E,cAAc,CAAC,CAAC;IAC/C,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,EAAE;aACL,MAAM,CAAC,0BAA0B,CAAC;aAClC,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,0BAA0B,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACrD,EAAE,CAAC,0BAA0B,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CACtD,CACF,CAAC;QACJ,MAAM,EAAE;aACL,MAAM,CAAC,sBAAsB,CAAC;aAC9B,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACjD,EAAE,CAAC,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CAClD,CACF,CAAC;IACN,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport {\n createDocument,\n exportFullHistoryIdentity,\n importSnapshot,\n satisfiesVersionVector,\n} from \"@tearleads/loro\";\nimport { and, eq, inArray, isNull, ne, sql } from \"drizzle-orm\";\nimport type { DocumentScope } from \"./documentPersistenceTypes\";\nimport {\n documentHistoryCheckpoints,\n documentHistoryUpdates,\n documentTables,\n} from \"./schema\";\nimport { getClientSQLitePersistenceRuntime } from \"./sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"./sqlSchema\";\n\n/**\n * Compaction thresholds: once the tail carries this many rows or bytes, the\n * next persist of a full-history-capable document exports a fresh checkpoint\n * and clears the tail. Small enough to keep restore replay short, large\n * enough that a full-history export (O(history)) happens once per burst of\n * edits instead of per keystroke.\n */\nexport const DOCUMENT_HISTORY_COMPACTION_MAX_ROWS = 200;\nexport const DOCUMENT_HISTORY_COMPACTION_MAX_BYTES = 512 * 1024;\n\n/**\n * Row provenance: \"local\" for updates authored on this device, \"remote\" for\n * decrypted pulled updates. Restores advance the outgoing-delta marker across\n * remote rows (already server-side); local rows never advance it.\n */\ntype DocumentHistoryUpdateOrigin = \"local\" | \"remote\";\n\n/**\n * Rows of the update log that are history tail: every row except an \"outbox\"\n * row, which only waits to be sent (see `documentHistoryUpdates`).\n */\nfunction tailInScope(scope: DocumentScope) {\n return and(\n eq(documentHistoryUpdates.appKind, scope.appKind),\n eq(documentHistoryUpdates.localId, scope.localId),\n ne(documentHistoryUpdates.origin, \"outbox\"),\n );\n}\n\n/**\n * Tail rows compaction may fold into a checkpoint and delete: a queued row is\n * the only durable copy of an unsent update, so it waits for settlement even\n * when a checkpoint already covers its operations.\n */\nfunction compactableTailInScope(scope: DocumentScope) {\n return and(tailInScope(scope), isNull(documentHistoryUpdates.updateId));\n}\n\ninterface DocumentHistoryTailUpdate {\n readonly origin: DocumentHistoryUpdateOrigin;\n readonly updateData: string;\n}\n\ninterface DocumentHistoryRestoreState {\n readonly snapshot: string;\n readonly tailUpdates: readonly DocumentHistoryTailUpdate[];\n}\n\nexport async function appendDocumentHistoryUpdates(\n execSql: ExecSql,\n scope: DocumentScope,\n updates: readonly string[],\n origin: DocumentHistoryUpdateOrigin,\n): Promise<void> {\n if (updates.length === 0) {\n return;\n }\n await ensureSqlTables(execSql, documentTables);\n const createdAt = new Date().toISOString();\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n // Chunked: a catch-up pull can carry thousands of updates, and a single\n // multi-row insert would exceed SQLite's bound-variable limit.\n for (let index = 0; index < updates.length; index += HISTORY_ROW_CHUNK) {\n await db.insert(documentHistoryUpdates).values(\n updates.slice(index, index + HISTORY_ROW_CHUNK).map((updateData) => ({\n id: crypto.randomUUID(),\n appKind: scope.appKind,\n localId: scope.localId,\n updateData,\n origin,\n createdAt,\n })),\n );\n }\n });\n}\n\n/**\n * The checkpoint + ordered tail for a scope, or null when NEITHER exists (a\n * discovered shell that has not hydrated content yet; the caller starts the\n * document empty and the remote pull supplies the content). A tail WITHOUT a\n * checkpoint — a crash between the first enqueued edit's tail append and the\n * birth-checkpoint seed — restores as tail-only (`snapshot: \"\"`): those tail\n * rows can be the only durable copy of a local edit, so they must never be\n * silently ignored.\n */\nexport async function loadDocumentHistoryRestoreState(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<DocumentHistoryRestoreState | null> {\n await ensureSqlTables(execSql, documentTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n // Read the TAIL before the (full) checkpoint: if another pane compacts\n // between the two reads, this order yields old-tail + new-checkpoint — a\n // safe superset (the new checkpoint subsumes the old tail, and replay is\n // idempotent by op identity). The reverse order could yield old-checkpoint\n // + already-emptied tail, a torn read that silently drops the compacted\n // ops for the whole session.\n const tail = await db\n .select({\n id: documentHistoryUpdates.id,\n origin: documentHistoryUpdates.origin,\n updateData: documentHistoryUpdates.updateData,\n })\n .from(documentHistoryUpdates)\n .where(tailInScope(scope))\n // Insertion order: same-millisecond appends make createdAt tie and a\n // random-uuid tiebreak would replay out of order. importUpdates tolerates\n // out-of-order batches, but replay should still be deterministic.\n .orderBy(sql`rowid`);\n\n const [checkpoint] = await db\n .select({ snapshot: documentHistoryCheckpoints.snapshot })\n .from(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n ),\n )\n .limit(1);\n if (!checkpoint && tail.length === 0) {\n return null;\n }\n\n return {\n snapshot: checkpoint?.snapshot ?? \"\",\n tailUpdates: tail.map((row) => ({\n // Fail toward re-sending: an unrecognized origin never advances the\n // marker, which is the recoverable direction (a redundant re-submit\n // is idempotent; a skipped local op would be orphaned from sync).\n origin:\n row.origin === \"remote\" ? (\"remote\" as const) : (\"local\" as const),\n updateData: row.updateData,\n })),\n };\n}\n\n/**\n * Size of the tail compaction can shrink. Queued rows are excluded: they stay\n * until settlement, so counting them would re-export full history on every\n * persist while offline edits wait to sync.\n */\nexport async function readDocumentHistoryTailSize(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<{ byteLength: number; hasCheckpoint: boolean; rowCount: number }> {\n await ensureSqlTables(execSql, documentTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [totals] = await db\n .select({\n byteLength: sql<number>`coalesce(sum(length(${documentHistoryUpdates.updateData})), 0)`,\n rowCount: sql<number>`count(*)`,\n })\n .from(documentHistoryUpdates)\n .where(compactableTailInScope(scope));\n const [checkpoint] = await db\n .select({ localId: documentHistoryCheckpoints.localId })\n .from(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n ),\n )\n .limit(1);\n return {\n byteLength: Number(totals?.byteLength ?? 0),\n hasCheckpoint: checkpoint !== undefined,\n rowCount: Number(totals?.rowCount ?? 0),\n };\n}\n\ninterface DocumentHistoryTailEntry {\n readonly id: string;\n readonly updateData: string;\n}\n\n/**\n * The current compactable tail rows WITH their payloads, so a compactor can\n * prove each row's ops are covered by the snapshot it is about to install\n * (another pane's append may carry ops this pane's document has not merged\n * yet). Queued rows are never candidates.\n */\nexport async function listDocumentHistoryTailEntries(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<DocumentHistoryTailEntry[]> {\n await ensureSqlTables(execSql, documentTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n id: documentHistoryUpdates.id,\n updateData: documentHistoryUpdates.updateData,\n })\n .from(documentHistoryUpdates)\n .where(compactableTailInScope(scope));\n return rows.flatMap((row) =>\n row.id === null ? [] : [{ id: row.id, updateData: row.updateData }],\n );\n}\n\nconst HISTORY_ROW_CHUNK = 400;\n\n/**\n * Replace the scope's checkpoint with a fresh full-history snapshot and\n * delete ONLY the tail rows the caller captured before exporting it. Every\n * append path writes its tail row after the ops are already in the live\n * document, so any row captured before the export is provably covered by\n * the snapshot — while a row appended concurrently (between export and this\n * delete) survives for the next compaction instead of being lost.\n */\nexport async function replaceDocumentHistoryCheckpoint(\n execSql: ExecSql,\n scope: DocumentScope,\n input: {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n /**\n * Skip the monotonic version gate. Only for document CREATION, where any\n * existing checkpoint under this localId is the orphan of a failed prior\n * attempt (checkpoint written, record row never committed) — a retry's\n * fresh document need not dominate that orphan to replace it.\n */\n force?: boolean;\n snapshot: string;\n /**\n * Re-checked after acquiring the serialized mutation slot (like the\n * record-save path): a store reset/recreation that happened while this\n * call waited in the queue must abort the write, or a stale compactor\n * could install the OLD document's checkpoint over the new identity's.\n */\n stillCurrent?: () => boolean;\n },\n): Promise<boolean> {\n await ensureSqlTables(execSql, documentTables);\n // Sequential (non-transactional) so callers already inside a transaction\n // can nest this. Crash between the statements leaves the new checkpoint\n // plus covered tail rows — a safe superset, since tail replay is\n // idempotent by op identity. The replacement itself is a compare-and-swap\n // on the stored revision, so the version gate cannot be bypassed by a\n // concurrent compactor between the read and the write: whoever loses the\n // CAS re-reads and re-evaluates the gate against the winner's checkpoint.\n return getClientSQLitePersistenceRuntime(execSql).runMutation(async (tx) => {\n if (input.stillCurrent?.() === false) {\n return false;\n }\n for (let attempt = 0; attempt < CHECKPOINT_CAS_ATTEMPTS; attempt += 1) {\n let replaced: boolean;\n try {\n replaced = await tryReplaceCheckpointOnce(tx, scope, input);\n } catch (error) {\n if (error instanceof CheckpointGateRejected) {\n // A fresher checkpoint dominates this candidate: no write, and\n // the caller's covered rows must stay for the covering pane.\n return false;\n }\n throw error;\n }\n if (!replaced) {\n // CAS lost to a concurrent writer — re-read and re-evaluate the\n // gate against the winner's checkpoint.\n continue;\n }\n for (\n let index = 0;\n index < input.coveredTailIds.length;\n index += HISTORY_ROW_CHUNK\n ) {\n // Never a queued row, even if a caller names one: its operations may\n // be in the checkpoint, but it is still the unsent update itself.\n await tx\n .delete(documentHistoryUpdates)\n .where(\n and(\n compactableTailInScope(scope),\n inArray(\n documentHistoryUpdates.id,\n input.coveredTailIds.slice(index, index + HISTORY_ROW_CHUNK),\n ),\n ),\n );\n }\n return true;\n }\n // Exhaustion must not read as durable success: creation and rebuild\n // callers persist record rows assuming the checkpoint landed.\n throw new Error(\n \"Document history checkpoint replacement lost every CAS attempt\",\n );\n });\n}\n\nconst CHECKPOINT_CAS_ATTEMPTS = 16;\n\ntype MutationDb = Parameters<\n Parameters<\n ReturnType<typeof getClientSQLitePersistenceRuntime>[\"runMutation\"]\n >[0]\n>[0];\n\n/**\n * One compare-and-swap attempt. Returns true when this caller's checkpoint\n * became the stored one, false when a concurrent writer won the CAS (the\n * caller re-reads and retries), and throws CheckpointGateRejected when a\n * fresher stored checkpoint dominates the candidate.\n */\nasync function tryReplaceCheckpointOnce(\n tx: MutationDb,\n scope: DocumentScope,\n input: {\n endVersionVector: string;\n force?: boolean;\n snapshot: string;\n },\n): Promise<boolean> {\n const updatedAt = new Date().toISOString();\n const revision = crypto.randomUUID();\n const [stored] = await tx\n .select({\n endVersionVector: documentHistoryCheckpoints.endVersionVector,\n revision: documentHistoryCheckpoints.revision,\n snapshot: documentHistoryCheckpoints.snapshot,\n })\n .from(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n ),\n )\n .limit(1);\n\n if (!stored) {\n const inserted = await tx\n .insert(documentHistoryCheckpoints)\n .values({\n appKind: scope.appKind,\n localId: scope.localId,\n snapshot: input.snapshot,\n endVersionVector: input.endVersionVector,\n revision,\n updatedAt,\n })\n .onConflictDoNothing({\n target: [\n documentHistoryCheckpoints.appKind,\n documentHistoryCheckpoints.localId,\n ],\n })\n .returning({ localId: documentHistoryCheckpoints.localId });\n // Conflict means a concurrent writer inserted first — retry the gate.\n return inserted.length > 0;\n }\n\n // A stale compactor (a pane whose document has not merged another pane's\n // ops) must never replace a checkpoint it does not cover: the covered\n // pane may already have deleted its tail rows, so regressing the\n // checkpoint would leave those ops with no durable copy at all. Vector\n // dominance proves counter coverage; the retained-prefix identity also\n // proves the candidate carries the exact stored operations at those\n // counters rather than a same-frontier fork.\n if (input.force !== true) {\n if (\n !satisfiesVersionVector(input.endVersionVector, stored.endVersionVector)\n ) {\n throw new CheckpointGateRejected();\n }\n if (\n input.snapshot !== stored.snapshot &&\n !(await candidateContainsStoredCheckpointHistory({\n candidateSnapshot: input.snapshot,\n storedEndVersion: stored.endVersionVector,\n storedSnapshot: stored.snapshot,\n }))\n ) {\n throw new CheckpointGateRejected();\n }\n }\n\n const replaced = await tx\n .update(documentHistoryCheckpoints)\n .set({\n snapshot: input.snapshot,\n endVersionVector: input.endVersionVector,\n revision,\n updatedAt,\n })\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n eq(documentHistoryCheckpoints.revision, stored.revision),\n ),\n )\n .returning({ localId: documentHistoryCheckpoints.localId });\n return replaced.length > 0;\n}\n\nasync function candidateContainsStoredCheckpointHistory(input: {\n candidateSnapshot: string;\n storedEndVersion: string;\n storedSnapshot: string;\n}): Promise<boolean> {\n const [candidateDocument, storedDocument] = await Promise.all([\n createDocument(\"checkpoint-candidate-history-gate\"),\n createDocument(\"checkpoint-stored-history-gate\"),\n ]);\n try {\n importSnapshot(candidateDocument, base64ToBytes(input.candidateSnapshot));\n importSnapshot(storedDocument, base64ToBytes(input.storedSnapshot));\n return (\n exportFullHistoryIdentity(candidateDocument, input.storedEndVersion) ===\n exportFullHistoryIdentity(storedDocument)\n );\n } finally {\n candidateDocument.free();\n storedDocument.free();\n }\n}\n\nclass CheckpointGateRejected extends Error {\n constructor() {\n super(\"checkpoint gate rejected\");\n this.name = \"CheckpointGateRejected\";\n }\n}\n\nexport async function deleteDocumentHistory(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await ensureSqlTables(execSql, documentTables);\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (tx) => {\n await tx\n .delete(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n ),\n );\n await tx\n .delete(documentHistoryUpdates)\n .where(\n and(\n eq(documentHistoryUpdates.appKind, scope.appKind),\n eq(documentHistoryUpdates.localId, scope.localId),\n ),\n );\n });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"documentOrphanBlobReclaims.js","sourceRoot":"","sources":["documentOrphanBlobReclaims.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAExD,iFAAiF;AACjF,MAAM,CAAC,MAAM,0BAA0B,GAAG,WAAW,CACnD,+BAA+B,EAC/B,EAAE,UAAU,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,UAAU,EAAE,EAAE,CACjD,CAAC;AAEF,MAAM,CAAC,MAAM,8BAA8B,GAAG,oBAAoB,CAChE,0BAA0B,CAC3B,CAAC","sourcesContent":["import { sqliteTable, text } from \"drizzle-orm/sqlite-core\";\nimport { defineSqlTableSchema } from \"./sqlTableSchema\";\n\n/** Durable byte-reclamation queue populated before orphan attachment rows go. */\nexport const documentOrphanBlobReclaims = sqliteTable(\n \"document_orphan_blob_reclaims\",\n { storageKey: text(\"storage_key\").primaryKey() },\n);\n\nexport const documentOrphanBlobReclaimTable = defineSqlTableSchema(\n documentOrphanBlobReclaims,\n);\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"documentPendingUpdatePersistence.js","sourceRoot":"","sources":["documentPendingUpdatePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,GAAG,EACH,EAAE,EACF,OAAO,EACP,SAAS,EACT,EAAE,EACF,EAAE,EAEF,GAAG,GACJ,MAAM,aAAa,CAAC;AAOrB,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAE7D,OAAO,EAAE,iCAAiC,EAAE,MAAM,4BAA4B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1D,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,OAAgB,EAChB,EAAU;IAEV,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,sBAAsB,CAAC,EAAE,EAAE,EAAE,CAAC,sBAAsB,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,EAAkB,EAClB,MAAgC;IAEhC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAChC,MAAM,sBAAsB,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;AACrE,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAgB,EAChB,KAAoB;IAEpB,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,kCAAkC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;IACxD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n and,\n asc,\n eq,\n inArray,\n isNotNull,\n lt,\n or,\n type SQL,\n sql,\n} from \"drizzle-orm\";\nimport type {\n DocumentScope,\n PendingUpdateFields,\n PendingUpdateRecord,\n SelectedPendingUpdateRow,\n} from \"./documentPersistenceTypes\";\nimport { documentHistoryUpdates, documents } from \"./schema\";\nimport type { ClientSQLiteTransactionScope } from \"./sqlitePersistenceRuntime\";\nimport { getClientSQLitePersistenceRuntime } from \"./sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"./sqlSchema\";\n\n/**\n * Queued updates are the rows of the local update log that carry an\n * `updateId`. A tail row (origin \"local\") stays in the log after settlement as\n * history until compaction; an \"outbox\" row has no tail role and settlement\n * deletes it.\n */\nconst OUTBOX_ORIGIN = \"outbox\";\n\ntype QueueStatement = Pick<ClientSQLiteTransactionScope, \"delete\" | \"update\">;\ntype QueueRead = Pick<ClientSQLiteTransactionScope, \"selectDistinct\">;\n\nfunction queuedInScope(scope: DocumentScope) {\n return and(\n eq(documentHistoryUpdates.appKind, scope.appKind),\n eq(documentHistoryUpdates.localId, scope.localId),\n isNotNull(documentHistoryUpdates.updateId),\n );\n}\n\nfunction mapSelectedPendingUpdate(\n row: SelectedPendingUpdateRow,\n): PendingUpdateRecord {\n // A queued row always carries its submission vectors; a row without them\n // cannot be submitted and must fail closed rather than send empty ranges.\n if (\n row.partialStartVersionVector === null ||\n row.partialEndVersionVector === null\n ) {\n throw new Error(\"Queued document update is missing its version vectors\");\n }\n return {\n id: String(row.id ?? \"\"),\n updateData: row.updateData,\n partialStartVersionVector: row.partialStartVersionVector,\n partialEndVersionVector: row.partialEndVersionVector,\n sourceVersionVector: row.sourceVersionVector,\n rekeyCount: row.rekeyCount,\n };\n}\n\n/** The ids among `localIds` (one app kind) with at least one queued update. */\nexport async function listLocalIdsWithQueuedUpdates(\n db: QueueRead,\n appKind: string,\n localIds: readonly string[],\n): Promise<string[]> {\n const uniqueIds = [...new Set(localIds)];\n if (uniqueIds.length === 0) return [];\n const rows = await db\n .selectDistinct({ localId: documentHistoryUpdates.localId })\n .from(documentHistoryUpdates)\n .where(\n and(\n eq(documentHistoryUpdates.appKind, appKind),\n inArray(documentHistoryUpdates.localId, uniqueIds),\n isNotNull(documentHistoryUpdates.updateId),\n ),\n )\n .orderBy(asc(documentHistoryUpdates.localId));\n return rows.map((row) => row.localId);\n}\n\nexport async function hasQueuedDocumentUpdates(\n db: QueueRead,\n scope: DocumentScope,\n): Promise<boolean> {\n const ids = await listLocalIdsWithQueuedUpdates(db, scope.appKind, [\n scope.localId,\n ]);\n return ids.length > 0;\n}\n\nexport async function listDocumentPendingUpdates(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<PendingUpdateRecord[]> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n id: documentHistoryUpdates.updateId,\n updateData: documentHistoryUpdates.updateData,\n partialStartVersionVector:\n documentHistoryUpdates.partialStartVersionVector,\n partialEndVersionVector: documentHistoryUpdates.partialEndVersionVector,\n sourceVersionVector: documentHistoryUpdates.sourceVersionVector,\n rekeyCount: documentHistoryUpdates.rekeyCount,\n })\n .from(documentHistoryUpdates)\n .where(queuedInScope(scope))\n .orderBy(asc(documentHistoryUpdates.createdAt), asc(sql`rowid`));\n\n return rows.map(mapSelectedPendingUpdate);\n}\n\n/** One log row for a queued update; `origin` decides its tail role. */\nexport function queuedUpdateRow(input: {\n createdAt: string;\n origin: \"local\" | typeof OUTBOX_ORIGIN;\n pendingUpdate: PendingUpdateFields;\n scope: DocumentScope;\n updateId: string;\n}) {\n return {\n id: crypto.randomUUID(),\n appKind: input.scope.appKind,\n localId: input.scope.localId,\n updateData: input.pendingUpdate.updateData,\n origin: input.origin,\n createdAt: input.createdAt,\n updateId: input.updateId,\n partialStartVersionVector: input.pendingUpdate.partialStartVersionVector,\n partialEndVersionVector: input.pendingUpdate.partialEndVersionVector,\n sourceVersionVector: input.pendingUpdate.sourceVersionVector ?? null,\n };\n}\n\n/**\n * Queue an update that has no history-tail role: container metadata (its\n * content is its checkpoint) and full-state re-uploads after a remote reset.\n */\nexport async function enqueueDocumentPendingUpdate(\n execSql: ExecSql,\n scope: DocumentScope,\n pendingUpdate: PendingUpdateFields,\n): Promise<string> {\n const updateId = crypto.randomUUID();\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .insert(documentHistoryUpdates)\n .values(\n queuedUpdateRow({\n createdAt: new Date().toISOString(),\n origin: OUTBOX_ORIGIN,\n pendingUpdate,\n scope,\n updateId,\n }),\n )\n .run();\n });\n return updateId;\n}\n\n/**\n * Append a locally authored update to the history tail AND queue it, as one\n * row in one transaction. A crash can therefore never leave the op restorable\n * from history while missing from the outgoing queue, where a null-marker\n * restore would classify it as covered and never send it.\n */\nexport async function enqueueDocumentPendingUpdateWithHistory(\n execSql: ExecSql,\n scope: DocumentScope,\n pendingUpdate: PendingUpdateFields,\n options?: {\n expectedDocumentId: string | null;\n expectedRecoveryGeneration: number;\n },\n): Promise<string | null> {\n const createdAt = new Date().toISOString();\n return getClientSQLitePersistenceRuntime(execSql).transaction(\n async (tx) => {\n if (options) {\n const matchingDocuments = await tx\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n sql`${documents.documentId} IS ${options.expectedDocumentId}`,\n eq(\n documents.recoveryGeneration,\n options.expectedRecoveryGeneration,\n ),\n ),\n )\n .limit(1);\n if (matchingDocuments.length === 0) {\n return null;\n }\n }\n\n return insertDocumentPendingUpdateWithHistoryInTransaction({\n createdAt,\n pendingUpdate,\n scope,\n tx,\n });\n },\n { behavior: \"immediate\" },\n );\n}\n\nexport async function insertDocumentPendingUpdateWithHistoryInTransaction(input: {\n createdAt: string;\n pendingUpdate: PendingUpdateFields;\n scope: DocumentScope;\n tx: ClientSQLiteTransactionScope;\n}): Promise<string> {\n const updateId = crypto.randomUUID();\n await input.tx\n .insert(documentHistoryUpdates)\n .values(\n queuedUpdateRow({\n createdAt: input.createdAt,\n origin: \"local\",\n pendingUpdate: input.pendingUpdate,\n scope: input.scope,\n updateId,\n }),\n )\n .run();\n return updateId;\n}\n\n/**\n * Assign a fresh id to a queued update, keeping every other column. A lost\n * sync ack leaves the server holding the update under the original id with\n * ciphertext a rebuilt submission can never reproduce (each rebuild encrypts\n * with a fresh IV), so the id is permanently poisoned: every resubmission\n * 409s and the whole outgoing batch rolls back. Re-keying lets the next sync\n * pass submit the same ops under a conflict-free id; the server-side copy is\n * harmless because CRDT update import is idempotent.\n *\n * Returns null when no row carries the id, so callers never report progress\n * for a row that lives in some other queue (or nowhere). The UPDATE's own\n * RETURNING row is the progress signal — a pre-flight SELECT would race a\n * second tab sharing the SQLite file, which can settle the row between the\n * read and the write and turn \"rekeyed\" into a spurious re-arm.\n *\n * The persisted per-row bound is enforced here as well: a row already at\n * MAX_PENDING_UPDATE_REKEYS is left untouched and reported as no progress.\n * The in-memory lane counter bounds a busy-loop within one session; this\n * bound survives restarts, so a poisoned row cannot re-key forever at three\n * passes per launch.\n */\nexport const MAX_PENDING_UPDATE_REKEYS = 5;\n\n/**\n * Reset the durable re-key budget for every queued update in a scope. The\n * cap exists to stop a server that keeps conflicting fresh ids from driving\n * a network-speed loop — but a budget burned during an unrelated outage\n * (e.g. yesterday's stale-bundle deadlock 409ing every submit) should not be\n * terminal forever. An explicit manual retry is the deliberate, rate-limited\n * signal that conditions changed, so it gets a fresh budget.\n */\nexport async function resetDocumentPendingUpdateRekeyBudget(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .update(documentHistoryUpdates)\n .set({ rekeyCount: 0 })\n .where(queuedInScope(scope));\n });\n}\n\nexport async function rekeyDocumentPendingUpdate(\n execSql: ExecSql,\n id: string,\n): Promise<string | null> {\n const nextId = crypto.randomUUID();\n let rekeyed = false;\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n const updated = await db\n .update(documentHistoryUpdates)\n .set({\n updateId: nextId,\n rekeyCount: sql`${documentHistoryUpdates.rekeyCount} + 1`,\n })\n .where(\n and(\n eq(documentHistoryUpdates.updateId, id),\n lt(documentHistoryUpdates.rekeyCount, MAX_PENDING_UPDATE_REKEYS),\n ),\n )\n .returning({ id: documentHistoryUpdates.updateId });\n rekeyed = updated.length > 0;\n });\n return rekeyed ? nextId : null;\n}\n\n/**\n * Settle queued updates: an outbox row is deleted, and a tail row stops being\n * queued but stays as history until compaction folds it into a checkpoint.\n */\nexport async function settleQueuedDocumentUpdatesInTransaction(\n tx: QueueStatement,\n scope: DocumentScope,\n updateIds: readonly string[],\n): Promise<void> {\n const uniqueIds = [...new Set(updateIds)];\n if (uniqueIds.length === 0) return;\n const selected = and(\n eq(documentHistoryUpdates.appKind, scope.appKind),\n eq(documentHistoryUpdates.localId, scope.localId),\n inArray(documentHistoryUpdates.updateId, uniqueIds),\n );\n await unqueueSelectedUpdates(tx, selected);\n}\n\nasync function unqueueSelectedUpdates(\n tx: QueueStatement,\n selected: SQL | undefined,\n): Promise<void> {\n await tx\n .delete(documentHistoryUpdates)\n .where(and(selected, eq(documentHistoryUpdates.origin, OUTBOX_ORIGIN)))\n .run();\n await tx\n .update(documentHistoryUpdates)\n .set({\n updateId: null,\n partialStartVersionVector: null,\n partialEndVersionVector: null,\n sourceVersionVector: null,\n rekeyCount: 0,\n })\n .where(selected)\n .run();\n}\n\n/** Settle one queued update by id, whatever its scope. */\nexport async function settleDocumentPendingUpdate(\n execSql: ExecSql,\n id: string,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await unqueueSelectedUpdates(db, eq(documentHistoryUpdates.updateId, id));\n });\n}\n\n/**\n * Stop queueing every update in the given scopes: outbox rows are dropped,\n * and local tail rows keep their content as history (it is already in the\n * document).\n */\nexport async function unqueueDocumentScopesInTransaction(\n tx: QueueStatement,\n scopes: readonly DocumentScope[],\n): Promise<void> {\n if (scopes.length === 0) return;\n await unqueueSelectedUpdates(tx, or(...scopes.map(queuedInScope)));\n}\n\nexport async function unqueueDocumentPendingUpdates(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await unqueueDocumentScopesInTransaction(db, [scope]);\n });\n}\n"]}