@tearleads/client-sdk 0.1.243 → 0.1.246

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 (200) hide show
  1. package/client/organizations/principalMutations.d.ts +5 -0
  2. package/data/containers/shared/mutationAcknowledgement.d.ts +1 -1
  3. package/data/containers/shared/mutationAcknowledgement.js +3 -8
  4. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  5. package/data/documents/shared/sync/mutationAcknowledgement.js +11 -2
  6. package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -1
  7. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.d.ts +26 -0
  8. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js +46 -0
  9. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js.map +1 -0
  10. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +7 -4
  11. package/data/keyingProjectionVerification/container/containerDestinationVerification.js +5 -1
  12. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
  13. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +9 -2
  14. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  15. package/data/keyingProjectionVerification/document/documentContainerProjections.js +2 -1
  16. package/data/keyingProjectionVerification/document/documentContainerProjections.js.map +1 -1
  17. package/data/keyingProjectionVerification/document/documentProjectionVerification.js +9 -2
  18. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
  19. package/data/keyingProjectionVerification/index.d.ts +1 -0
  20. package/data/keyingProjectionVerification/index.js +1 -0
  21. package/data/keyingProjectionVerification/index.js.map +1 -1
  22. package/data/persistence/container-contents/containerContentsPersistence.js +2 -0
  23. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  24. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -1
  25. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  26. package/data/persistence/container-contents/containerMetadataRevalidations.d.ts +22 -0
  27. package/data/persistence/container-contents/containerMetadataRevalidations.js +52 -0
  28. package/data/persistence/container-contents/containerMetadataRevalidations.js.map +1 -0
  29. package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js +16 -4
  30. package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js.map +1 -1
  31. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +13 -0
  32. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +11 -0
  33. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  34. package/data/persistence/verifiedCitations/authoredBundleCitation.d.ts +20 -0
  35. package/data/persistence/verifiedCitations/authoredBundleCitation.js +32 -0
  36. package/data/persistence/verifiedCitations/authoredBundleCitation.js.map +1 -0
  37. package/data/persistence/verifiedManifestBundlePersistence.d.ts +10 -0
  38. package/data/persistence/verifiedManifestBundlePersistence.js +95 -9
  39. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  40. package/data/sqlite/schema/containerSchema.d.ts +173 -0
  41. package/data/sqlite/schema/containerSchema.js +18 -0
  42. package/data/sqlite/schema/containerSchema.js.map +1 -1
  43. package/data/sqlite/schema/index.d.ts +84 -1
  44. package/data/sqlite/schema/index.js +1 -1
  45. package/data/sqlite/schema/index.js.map +1 -1
  46. package/internal/api-client/ApiClient.d.ts +56 -8
  47. package/internal/api-client/client/apiClientContext.d.ts +1 -0
  48. package/internal/api-client/client/containerMutations.d.ts +11 -0
  49. package/internal/api-client/client/containerReads.d.ts +1 -0
  50. package/internal/api-client/client/documents.d.ts +5 -0
  51. package/internal/api-client/client/organizations.d.ts +20 -0
  52. package/internal/api-client/client/principalPolicies.d.ts +9 -0
  53. package/internal/api-client/client/session.d.ts +10 -0
  54. package/internal/api-client/principalPolicyRequests.d.ts +7 -0
  55. package/internal/api-client/writerProjectionCitations.d.ts +3 -0
  56. package/internal/api-client/writerProjectionCitations.js +12 -0
  57. package/internal/api-client/writerProjectionCitations.js.map +1 -1
  58. package/internal/crypto/index.d.ts +1 -1
  59. package/internal/crypto/index.js +1 -1
  60. package/internal/crypto/index.js.map +1 -1
  61. package/internal/crypto/keying/accessManifestVerificationTypes.d.ts +8 -2
  62. package/internal/crypto/keying/accessManifestVerificationTypes.js.map +1 -1
  63. package/internal/crypto/keying/canonicalJsonGuard.d.ts +13 -0
  64. package/internal/crypto/keying/canonicalJsonGuard.js +23 -0
  65. package/internal/crypto/keying/canonicalJsonGuard.js.map +1 -1
  66. package/internal/crypto/keying/containerAccess.js +1 -1
  67. package/internal/crypto/keying/containerAccess.js.map +1 -1
  68. package/internal/crypto/keying/documentAccess.js +1 -1
  69. package/internal/crypto/keying/documentAccess.js.map +1 -1
  70. package/internal/crypto/keying/index.d.ts +1 -1
  71. package/internal/crypto/keying/index.js +1 -1
  72. package/internal/crypto/keying/index.js.map +1 -1
  73. package/internal/crypto/keying/keyingHashDomains.d.ts +1 -1
  74. package/internal/crypto/keying/keyingHashDomains.js.map +1 -1
  75. package/internal/crypto/organizationReplacement.js +5 -6
  76. package/internal/crypto/organizationReplacement.js.map +1 -1
  77. package/internal/loro/document.d.ts +5 -0
  78. package/internal/loro/document.js +17 -0
  79. package/internal/loro/document.js.map +1 -1
  80. package/internal/loro/index.d.ts +1 -1
  81. package/internal/loro/index.js +1 -1
  82. package/internal/loro/index.js.map +1 -1
  83. package/internal/validators/operation/attachments.d.ts +0 -12
  84. package/internal/validators/operation/auth.d.ts +40 -76
  85. package/internal/validators/operation/containerMutations.d.ts +45 -49
  86. package/internal/validators/operation/containerMutations.js +1 -1
  87. package/internal/validators/operation/containerMutations.js.map +1 -1
  88. package/internal/validators/operation/containerReads.d.ts +2 -0
  89. package/internal/validators/operation/documentMutations.d.ts +12 -24
  90. package/internal/validators/operation/documentSync.d.ts +0 -4
  91. package/internal/validators/operation/organizations.d.ts +48 -88
  92. package/internal/validators/operation/principals.d.ts +16 -16
  93. package/internal/validators/request/blob.d.ts +0 -12
  94. package/internal/validators/request/container.d.ts +0 -16
  95. package/internal/validators/request/container.js +0 -2
  96. package/internal/validators/request/container.js.map +1 -1
  97. package/internal/validators/request/containerMetadata.d.ts +0 -20
  98. package/internal/validators/request/document.d.ts +0 -22
  99. package/internal/validators/request/document.js +0 -1
  100. package/internal/validators/request/document.js.map +1 -1
  101. package/internal/validators/request/documentSyncSchema.d.ts +0 -4
  102. package/internal/validators/request/documentSyncSchema.js +0 -1
  103. package/internal/validators/request/documentSyncSchema.js.map +1 -1
  104. package/internal/validators/request/organization.d.ts +0 -16
  105. package/internal/validators/request/organizationProvisioning.d.ts +0 -242
  106. package/internal/validators/request/principal.d.ts +0 -20
  107. package/internal/validators/request/registration.d.ts +0 -76
  108. package/internal/validators/response/areas/containers.d.ts +1 -1
  109. package/internal/validators/response/areas/containers.js +1 -1
  110. package/internal/validators/response/areas/containers.js.map +1 -1
  111. package/internal/validators/response/container.d.ts +24 -0
  112. package/internal/validators/response/container.js +4 -0
  113. package/internal/validators/response/container.js.map +1 -1
  114. package/internal/validators/response/containerMetadata.d.ts +8 -0
  115. package/internal/validators/response/containerParentLanes.d.ts +2 -0
  116. package/internal/validators/response/documentMutation.d.ts +8 -0
  117. package/internal/validators/response/documentMutation.js +2 -1
  118. package/internal/validators/response/documentMutation.js.map +1 -1
  119. package/internal/validators/response/organization.d.ts +8 -0
  120. package/internal/validators/response/organizationProvisioning.d.ts +113 -0
  121. package/internal/validators/response/organizationProvisioning.js +2 -1
  122. package/internal/validators/response/organizationProvisioning.js.map +1 -1
  123. package/internal/validators/response/principal.d.ts +16 -0
  124. package/internal/validators/response/registration.d.ts +40 -0
  125. package/internal/validators/response/writerProjectionWire.d.ts +25 -0
  126. package/internal/validators/response/writerProjectionWire.js +109 -3
  127. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  128. package/package.json +1 -1
  129. package/stores/container-contents/containerContentsStore.js +2 -0
  130. package/stores/container-contents/containerContentsStore.js.map +1 -1
  131. package/stores/container-contents/hydration/startupHydration.js +6 -2
  132. package/stores/container-contents/hydration/startupHydration.js.map +1 -1
  133. package/stores/container-contents/state.js +5 -1
  134. package/stores/container-contents/state.js.map +1 -1
  135. package/stores/container-contents/syncAgent/metadataRevalidation.js +79 -0
  136. package/stores/container-contents/syncAgent/metadataRevalidation.js.map +1 -0
  137. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +6 -0
  138. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  139. package/stores/container-contents/syncAgent/syncLaneIteration.js +110 -23
  140. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  141. package/stores/documents/documentStore/rotation/index.js +3 -1
  142. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  143. package/stores/documents/documentStore/sync/syncAttachments.js +4 -1
  144. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  145. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -1
  146. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
  147. package/stores/documents/documentStore/sync/syncRequest.js +3 -1
  148. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  149. package/workflows/container-contents/container-state/create/createAdoption.js +11 -3
  150. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  151. package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
  152. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  153. package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js +3 -0
  154. package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js.map +1 -1
  155. package/workflows/container-contents/container-state/projectionCache.js +3 -0
  156. package/workflows/container-contents/container-state/projectionCache.js.map +1 -1
  157. package/workflows/container-contents/container-state/remote.js +3 -0
  158. package/workflows/container-contents/container-state/remote.js.map +1 -1
  159. package/workflows/container-contents/containerPersistence.d.ts +1 -0
  160. package/workflows/container-contents/containerPersistence.js.map +1 -1
  161. package/workflows/container-contents/metadata/index.js +9 -3
  162. package/workflows/container-contents/metadata/index.js.map +1 -1
  163. package/workflows/container-contents/metadata/metadataSyncFollowup.js +9 -0
  164. package/workflows/container-contents/metadata/metadataSyncFollowup.js.map +1 -1
  165. package/workflows/container-contents/metadata/metadataTypes.d.ts +2 -0
  166. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  167. package/workflows/container-contents/remoteHydration/index.js +9 -0
  168. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  169. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +31 -0
  170. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  171. package/workflows/container-contents/remoteHydration/types.d.ts +9 -1
  172. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  173. package/workflows/containers/child/mutationRequestCore.js +1 -1
  174. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  175. package/workflows/containers/child/recite.js +4 -2
  176. package/workflows/containers/child/recite.js.map +1 -1
  177. package/workflows/containers/child/recitePlan.js +0 -1
  178. package/workflows/containers/child/recitePlan.js.map +1 -1
  179. package/workflows/containers/root/create.js +0 -1
  180. package/workflows/containers/root/create.js.map +1 -1
  181. package/workflows/documents/create/createAdoption.js +11 -2
  182. package/workflows/documents/create/createAdoption.js.map +1 -1
  183. package/workflows/documents/create/createResponse.js +1 -0
  184. package/workflows/documents/create/createResponse.js.map +1 -1
  185. package/workflows/documents/linkSet/index.js +0 -1
  186. package/workflows/documents/linkSet/index.js.map +1 -1
  187. package/workflows/documents/linkSet/linkSetRemote.js +1 -0
  188. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
  189. package/workflows/documents/sync/syncAttemptPlanning.js +8 -2
  190. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  191. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +3 -2
  192. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  193. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js +3 -2
  194. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js.map +1 -1
  195. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +17 -10
  196. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
  197. package/workflows/registration/organizationCreation/organizationCreationIntent.d.ts +10 -0
  198. package/workflows/registration/provisioningAcknowledgement.js +16 -11
  199. package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
  200. package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"documentProjectionVerification.js","sourceRoot":"","sources":["documentProjectionVerification.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,wBAAwB,EACxB,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EACL,mCAAmC,EACnC,oCAAoC,EACpC,0CAA0C,GAC3C,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,8BAA8B,EAAE,MAAM,qDAAqD,CAAC;AACrG,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAOhD,OAAO,EAAE,iCAAiC,EAAE,MAAM,UAAU,CAAC;AAC7D,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,EAAE,iCAAiC,EAAE,MAAM,gCAAgC,CAAC;AAKnF,SAAS,oCAAoC,CAC3C,UAA4C;IAE5C,OAAO;QACL,GAAG,UAAU,CAAC,8BAA8B;QAC5C,GAAG,UAAU,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAA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AAK,CAAC,EACxC,iBAAiB,CAClB,CAAC;QACF,wCAAwC,CACtC,iBAAiB,EACjB,KAAK,CAAC,UAAU,EAChB,QAAQ,CAAC,aAAa,CACvB,CAAC;QACF,MAAM,6BAA6B,CAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;QAC9D,OAAO,QAAQ,CAAC,aAAa,CAAC;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC","sourcesContent":["import type {\n PrincipalPolicyAuthorization,\n VerifiedContainerAccessManifest,\n VerifiedDocumentLinkSetManifest,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyContainerManifestPath } from \"../container/containerPathVerification\";\nimport {\n addContainerWriterProjectionBundles,\n verifiedContainerManifestsForBundles,\n verifyContainerWriterProjectionWithContext,\n} from \"../container/containerProjectionVerification\";\nimport { rejectPurgedDocumentProjection } from \"../documentPurge/documentPurgeCheckpointEnforcement\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport { readAccessManifest } from \"../readers\";\nimport type {\n OpenPrincipalPolicyBundleReader,\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport { withGenerationGuardedPolicyWarmer } from \"../types\";\nimport { documentContainerProjections } from \"./documentContainerProjections\";\nimport { verifyDocumentProjectionManifests } from \"./documentManifestVerification\";\n\ntype VerifiedManifestMap = Map<string, VerifiedContainerAccessManifest>;\ntype PolicyWarmer = ReferencedPrincipalPolicyWarmer | undefined;\n\nfunction readDocumentProjectionContainerPaths(\n projection: DocumentWriterProjectionResponse,\n): AccessManifestBundleWireResponse[][] {\n return [\n ...projection.documentManifestContainerPaths,\n ...projection.authorizingContainerPaths.map((path) => path.path),\n ];\n}\n\nfunction collectDocumentProjectionContainerBundles(\n projection: DocumentWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n for (const [index, authorizing] of documentContainerProjections(\n projection,\n ).entries()) {\n addContainerWriterProjectionBundles(\n bundlesByHash,\n authorizing,\n `Document writer projection authorizing path[${index}]`,\n );\n }\n for (const [index, path] of readDocumentProjectionContainerPaths(\n projection,\n ).entries()) {\n for (const [pathIndex, bundle] of path.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection dependency path[${index}][${pathIndex}]`,\n );\n }\n }\n for (const [\n index,\n bundle,\n ] of projection.documentContainerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection container history[${index}]`,\n );\n }\n return bundlesByHash;\n}\n\nasync function verifyProjectionContainerPaths(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly projection: DocumentWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedByHash?: VerifiedManifestMap | undefined;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}): Promise<Map<string, readonly VerifiedContainerAccessManifest[]>> {\n const bundlesByHash = collectDocumentProjectionContainerBundles(\n input.projection,\n );\n const containerPathByManifestHash = new Map<\n string,\n readonly VerifiedContainerAccessManifest[]\n >();\n // Reuse a caller-supplied cache when provided so a later unwrap pass over the\n // same authorizing container paths does not re-verify identical manifests.\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n for (const projection of documentContainerProjections(input.projection)) {\n const path = await verifyContainerWriterProjectionWithContext(\n {\n authorizationEvidence: input.authorizationEvidence,\n principalPolicyCache: input.principalPolicyCache,\n projection,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n },\n input.checkpointContext,\n );\n const leaf = path.at(-1);\n if (leaf) {\n containerPathByManifestHash.set(leaf.manifestHash, path);\n }\n for (const manifest of path) {\n verifiedByHash.set(manifest.manifestHash, manifest);\n }\n }\n // Grouping supplies evidence only; each signed artifact selects its citations.\n for (const [\n index,\n path,\n ] of input.projection.documentManifestContainerPaths.entries()) {\n // Historical dependency evidence is verified without current checkpoint\n // enforcement. Its grouping cannot substitute an uncited ancestor into\n // document or content-write authorization.\n const verifiedPath = await verifyContainerManifestPath({\n authorizationEvidence: input.authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: false,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n enforceLocalCheckpoints: false,\n label: `Document writer projection dependency path[${index}]`,\n path,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // The authorizing path recorded for the same leaf takes precedence.\n const leaf = verifiedPath.at(-1);\n if (leaf && !containerPathByManifestHash.has(leaf.manifestHash)) {\n containerPathByManifestHash.set(leaf.manifestHash, verifiedPath);\n }\n }\n\n // Keep every verified head as evidence. Events and content headers select\n // their own signed paths through resolveEventContainerPaths.\n for (const [hash, manifest] of verifiedByHash) {\n if (!containerPathByManifestHash.has(hash))\n containerPathByManifestHash.set(hash, [manifest]);\n }\n\n observeAccessManifestCheckpoints(input.checkpointContext, {\n verifiedHeads: [],\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n return containerPathByManifestHash;\n}\n\ninterface DocumentWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: DocumentWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?: VerifiedManifestMap | undefined;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}\nexport interface DocumentWriterProjectionAuthorization {\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly documentManifestByHash: ReadonlyMap<\n string,\n VerifiedDocumentLinkSetManifest\n >;\n readonly principalPolicies: readonly PrincipalPolicyAuthorization[];\n}\n\ninterface VerifiedDocumentWriterProjectionResult {\n readonly authorization: DocumentWriterProjectionAuthorization;\n readonly headManifest: VerifiedDocumentLinkSetManifest;\n}\n\nasync function verifyDocumentWriterProjectionWithContext(\n input: Omit<DocumentWriterProjectionVerificationInput, \"execSql\">,\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedDocumentWriterProjectionResult> {\n const principalPolicyCache =\n input.principalPolicyCache ?? new Map<string, VerifiedPrincipalPolicy>();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [\n input.projection.documentManifest,\n ...input.projection.documentManifestHistory,\n ...collectDocumentProjectionContainerBundles(input.projection).values(),\n ],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: readAccessManifest(\n input.projection.documentManifest.manifest,\n \"Document projection manifest\",\n ).organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const containerPathByManifestHash = await verifyProjectionContainerPaths({\n authorizationEvidence,\n checkpointContext,\n principalPolicyCache,\n projection: input.projection,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const { headManifest, verifiedByHash } =\n await verifyDocumentProjectionManifests({\n authorizationEvidence,\n checkpointContext,\n containerPathByManifestHash,\n principalPolicyCache,\n projection: input.projection,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await rejectPurgedDocumentProjection(\n headManifest.state.documentId,\n checkpointContext.execSql,\n );\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: [headManifest],\n verifiedManifests: [...verifiedByHash.values()],\n });\n\n return {\n authorization: {\n containerPathByManifestHash,\n documentManifestByHash: verifiedByHash,\n principalPolicies: authorizationEvidence,\n },\n headManifest,\n };\n}\n\n/** Each served bundle, document and container, whose manifest verified. */\nfunction observeVerifiedDocumentProjectionBundles(\n checkpointContext: ProjectionCheckpointContext,\n projection: DocumentWriterProjectionResponse,\n authorization: DocumentWriterProjectionAuthorization,\n): void {\n observeVerifiedProjectionBundles(\n checkpointContext,\n new Map(\n [projection.documentManifest, ...projection.documentManifestHistory].map(\n (bundle) => [bundle.manifestHash, bundle],\n ),\n ),\n authorization.documentManifestByHash,\n );\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectDocumentProjectionContainerBundles(projection),\n new Map(\n [...authorization.containerPathByManifestHash.values()]\n .flat()\n .map((manifest) => [manifest.manifestHash, manifest]),\n ),\n );\n observeVerifiedKekLevels(\n checkpointContext,\n projection.authorizingContainerPaths,\n );\n}\n\nexport async function verifyDocumentWriterProjection(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<VerifiedDocumentLinkSetManifest> {\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n });\n const verified = await verifyDocumentWriterProjectionWithContext(\n withGenerationGuardedPolicyWarmer(input),\n checkpointContext,\n );\n observeVerifiedDocumentProjectionBundles(\n checkpointContext,\n input.projection,\n verified.authorization,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n return verified.headManifest;\n}\n\nexport async function verifyDocumentWriterProjectionAuthorization(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<DocumentWriterProjectionAuthorization> {\n try {\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n });\n const verified = await verifyDocumentWriterProjectionWithContext(\n withGenerationGuardedPolicyWarmer(input),\n checkpointContext,\n );\n observeVerifiedDocumentProjectionBundles(\n checkpointContext,\n input.projection,\n verified.authorization,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n return verified.authorization;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]}
1
+ {"version":3,"file":"documentProjectionVerification.js","sourceRoot":"","sources":["documentProjectionVerification.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,wBAAwB,EACxB,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EACL,mCAAmC,EACnC,oCAAoC,EACpC,0CAA0C,GAC3C,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,8BAA8B,EAAE,MAAM,qDAAqD,CAAC;AACrG,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAOhD,OAAO,EAAE,iCAAi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,CAAC,UAAU,EAChB,QAAQ,CAAC,aAAa,CACvB,CAAC;IACF,MAAM,6BAA6B,CAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;IAC9D,OAAO,QAAQ,CAAC,YAAY,CAAC;AAC/B,CAAC;AAED,MAAM,UAAU,2CAA2C,CACzD,KAAgD;IAEhD,OAAO,4BAA4B,CAAC,KAAK,EAAE,GAAG,EAAE,CAC9C,+CAA+C,CAAC,KAAK,CAAC,CACvD,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,+CAA+C,CAC5D,KAAgD;IAEhD,IAAI,CAAC;QACH,MAAM,iBAAiB,GAAG,iCAAiC,CAAC;YAC1D,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;SACvE,CAAC,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,yCAAyC,CAC9D,iCAAiC,CAAC,KAAK,CAAC,EACxC,iBAAiB,CAClB,CAAC;QACF,wCAAwC,CACtC,iBAAiB,EACjB,KAAK,CAAC,UAAU,EAChB,QAAQ,CAAC,aAAa,CACvB,CAAC;QACF,MAAM,6BAA6B,CAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;QAC9D,OAAO,QAAQ,CAAC,aAAa,CAAC;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC","sourcesContent":["import type {\n PrincipalPolicyAuthorization,\n VerifiedContainerAccessManifest,\n VerifiedDocumentLinkSetManifest,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyWithHeldBundleRecovery } from \"../checkpoints/heldBundleRecovery\";\nimport { verifyContainerManifestPath } from \"../container/containerPathVerification\";\nimport {\n addContainerWriterProjectionBundles,\n verifiedContainerManifestsForBundles,\n verifyContainerWriterProjectionWithContext,\n} from \"../container/containerProjectionVerification\";\nimport { rejectPurgedDocumentProjection } from \"../documentPurge/documentPurgeCheckpointEnforcement\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport { readAccessManifest } from \"../readers\";\nimport type {\n OpenPrincipalPolicyBundleReader,\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport { withGenerationGuardedPolicyWarmer } from \"../types\";\nimport { documentContainerProjections } from \"./documentContainerProjections\";\nimport { verifyDocumentProjectionManifests } from \"./documentManifestVerification\";\n\ntype VerifiedManifestMap = Map<string, VerifiedContainerAccessManifest>;\ntype PolicyWarmer = ReferencedPrincipalPolicyWarmer | undefined;\n\nfunction readDocumentProjectionContainerPaths(\n projection: DocumentWriterProjectionResponse,\n): AccessManifestBundleWireResponse[][] {\n return [\n ...projection.documentManifestContainerPaths,\n ...projection.authorizingContainerPaths.map((path) => path.path),\n ];\n}\n\nfunction collectDocumentProjectionContainerBundles(\n projection: DocumentWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n for (const [index, authorizing] of documentContainerProjections(\n projection,\n ).entries()) {\n addContainerWriterProjectionBundles(\n bundlesByHash,\n authorizing,\n `Document writer projection authorizing path[${index}]`,\n );\n }\n for (const [index, path] of readDocumentProjectionContainerPaths(\n projection,\n ).entries()) {\n for (const [pathIndex, bundle] of path.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection dependency path[${index}][${pathIndex}]`,\n );\n }\n }\n for (const [\n index,\n bundle,\n ] of projection.documentContainerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection container history[${index}]`,\n );\n }\n return bundlesByHash;\n}\n\nasync function verifyProjectionContainerPaths(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly projection: DocumentWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedByHash?: VerifiedManifestMap | undefined;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}): Promise<Map<string, readonly VerifiedContainerAccessManifest[]>> {\n const bundlesByHash = collectDocumentProjectionContainerBundles(\n input.projection,\n );\n const containerPathByManifestHash = new Map<\n string,\n readonly VerifiedContainerAccessManifest[]\n >();\n // Reuse a caller-supplied cache when provided so a later unwrap pass over the\n // same authorizing container paths does not re-verify identical manifests.\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n for (const projection of documentContainerProjections(input.projection)) {\n const path = await verifyContainerWriterProjectionWithContext(\n {\n authorizationEvidence: input.authorizationEvidence,\n principalPolicyCache: input.principalPolicyCache,\n projection,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n },\n input.checkpointContext,\n );\n const leaf = path.at(-1);\n if (leaf) {\n containerPathByManifestHash.set(leaf.manifestHash, path);\n }\n for (const manifest of path) {\n verifiedByHash.set(manifest.manifestHash, manifest);\n }\n }\n // Grouping supplies evidence only; each signed artifact selects its citations.\n for (const [\n index,\n path,\n ] of input.projection.documentManifestContainerPaths.entries()) {\n // Historical dependency evidence is verified without current checkpoint\n // enforcement. Its grouping cannot substitute an uncited ancestor into\n // document or content-write authorization.\n const verifiedPath = await verifyContainerManifestPath({\n authorizationEvidence: input.authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: false,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n enforceLocalCheckpoints: false,\n label: `Document writer projection dependency path[${index}]`,\n path,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // The authorizing path recorded for the same leaf takes precedence.\n const leaf = verifiedPath.at(-1);\n if (leaf && !containerPathByManifestHash.has(leaf.manifestHash)) {\n containerPathByManifestHash.set(leaf.manifestHash, verifiedPath);\n }\n }\n\n // Keep every verified head as evidence. Events and content headers select\n // their own signed paths through resolveEventContainerPaths.\n for (const [hash, manifest] of verifiedByHash) {\n if (!containerPathByManifestHash.has(hash))\n containerPathByManifestHash.set(hash, [manifest]);\n }\n\n observeAccessManifestCheckpoints(input.checkpointContext, {\n verifiedHeads: [],\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n return containerPathByManifestHash;\n}\n\ninterface DocumentWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: DocumentWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?: VerifiedManifestMap | undefined;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}\nexport interface DocumentWriterProjectionAuthorization {\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly documentManifestByHash: ReadonlyMap<\n string,\n VerifiedDocumentLinkSetManifest\n >;\n readonly principalPolicies: readonly PrincipalPolicyAuthorization[];\n}\n\ninterface VerifiedDocumentWriterProjectionResult {\n readonly authorization: DocumentWriterProjectionAuthorization;\n readonly headManifest: VerifiedDocumentLinkSetManifest;\n}\n\nasync function verifyDocumentWriterProjectionWithContext(\n input: Omit<DocumentWriterProjectionVerificationInput, \"execSql\">,\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedDocumentWriterProjectionResult> {\n const principalPolicyCache =\n input.principalPolicyCache ?? new Map<string, VerifiedPrincipalPolicy>();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [\n input.projection.documentManifest,\n ...input.projection.documentManifestHistory,\n ...collectDocumentProjectionContainerBundles(input.projection).values(),\n ],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: readAccessManifest(\n input.projection.documentManifest.manifest,\n \"Document projection manifest\",\n ).organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const containerPathByManifestHash = await verifyProjectionContainerPaths({\n authorizationEvidence,\n checkpointContext,\n principalPolicyCache,\n projection: input.projection,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const { headManifest, verifiedByHash } =\n await verifyDocumentProjectionManifests({\n authorizationEvidence,\n checkpointContext,\n containerPathByManifestHash,\n principalPolicyCache,\n projection: input.projection,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await rejectPurgedDocumentProjection(\n headManifest.state.documentId,\n checkpointContext.execSql,\n );\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: [headManifest],\n verifiedManifests: [...verifiedByHash.values()],\n });\n\n return {\n authorization: {\n containerPathByManifestHash,\n documentManifestByHash: verifiedByHash,\n principalPolicies: authorizationEvidence,\n },\n headManifest,\n };\n}\n\n/** Each served bundle, document and container, whose manifest verified. */\nfunction observeVerifiedDocumentProjectionBundles(\n checkpointContext: ProjectionCheckpointContext,\n projection: DocumentWriterProjectionResponse,\n authorization: DocumentWriterProjectionAuthorization,\n): void {\n observeVerifiedProjectionBundles(\n checkpointContext,\n new Map(\n [projection.documentManifest, ...projection.documentManifestHistory].map(\n (bundle) => [bundle.manifestHash, bundle],\n ),\n ),\n authorization.documentManifestByHash,\n );\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectDocumentProjectionContainerBundles(projection),\n new Map(\n [...authorization.containerPathByManifestHash.values()]\n .flat()\n .map((manifest) => [manifest.manifestHash, manifest]),\n ),\n );\n observeVerifiedKekLevels(\n checkpointContext,\n projection.authorizingContainerPaths,\n );\n}\n\nexport function verifyDocumentWriterProjection(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<VerifiedDocumentLinkSetManifest> {\n return verifyWithHeldBundleRecovery(input, () =>\n verifyDocumentWriterProjectionOnce(input),\n );\n}\n\nasync function verifyDocumentWriterProjectionOnce(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<VerifiedDocumentLinkSetManifest> {\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n });\n const verified = await verifyDocumentWriterProjectionWithContext(\n withGenerationGuardedPolicyWarmer(input),\n checkpointContext,\n );\n observeVerifiedDocumentProjectionBundles(\n checkpointContext,\n input.projection,\n verified.authorization,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n return verified.headManifest;\n}\n\nexport function verifyDocumentWriterProjectionAuthorization(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<DocumentWriterProjectionAuthorization> {\n return verifyWithHeldBundleRecovery(input, () =>\n verifyDocumentWriterProjectionAuthorizationOnce(input),\n );\n}\n\nasync function verifyDocumentWriterProjectionAuthorizationOnce(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<DocumentWriterProjectionAuthorization> {\n try {\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n });\n const verified = await verifyDocumentWriterProjectionWithContext(\n withGenerationGuardedPolicyWarmer(input),\n checkpointContext,\n );\n observeVerifiedDocumentProjectionBundles(\n checkpointContext,\n input.projection,\n verified.authorization,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n return verified.authorization;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]}
@@ -4,6 +4,7 @@ export { readAccessEvent, readRecordString, readRequiredRecordValue, } from "./r
4
4
  export type { PrincipalPolicyCache, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer, } from "./types.js";
5
5
  export { isProjectionVerificationCancelledError, nullOnProjectionVerificationCancellation, } from "./types.js";
6
6
  export declare function requireProjectionUserKeyResolver(resolveProjectionUserKey: ProjectionUserKeyResolver | null | undefined, label: string): ProjectionUserKeyResolver;
7
+ export { checkWithHeldBundleRecovery } from "./checkpoints/heldBundleRecovery.js";
7
8
  export { verifiedContainerCreateManifest } from "./container/containerCreateManifest.js";
8
9
  export { verifyContainerDestinationProjection } from "./container/containerDestinationVerification.js";
9
10
  export { collectContainerWriterProjectionPrincipalPolicies, verifyContainerWriterProjection, } from "./container/containerProjectionVerification.js";
@@ -10,6 +10,7 @@ export function requireProjectionUserKeyResolver(resolveProjectionUserKey, label
10
10
  // provides the untrusted-shape and wrong-user guards (with identity caching).
11
11
  return requireTrustedUserIdentityResolver(resolveProjectionUserKey);
12
12
  }
13
+ export { checkWithHeldBundleRecovery } from "./checkpoints/heldBundleRecovery.js";
13
14
  export { verifiedContainerCreateManifest } from "./container/containerCreateManifest.js";
14
15
  export { verifyContainerDestinationProjection } from "./container/containerDestinationVerification.js";
15
16
  export { collectContainerWriterProjectionPrincipalPolicies, verifyContainerWriterProjection, } from "./container/containerProjectionVerification.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wBAAwB,CAAC;AAG5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AAChF,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,WAAW,CAAC;AAOnB,OAAO,EACL,sCAAsC,EACtC,wCAAwC,GACzC,MAAM,SAAS,CAAC;AAEjB,MAAM,UAAU,gCAAgC,CAC9C,wBAAsE,EACtE,KAAa;IAEb,IAAI,CAAC,wBAAwB,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,uCAAuC,CAAC,CAAC;IACnE,CAAC;IAED,sEAAsE;IACtE,8EAA8E;IAC9E,OAAO,kCAAkC,CAAC,wBAAwB,CAAC,CAAC;AACtE,CAAC;AAED,OAAO,EAAE,+BAA+B,EAAE,MAAM,qCAAqC,CAAC;AACtF,OAAO,EAAE,oCAAoC,EAAE,MAAM,8CAA8C,CAAC;AACpG,OAAO,EACL,iDAAiD,EACjD,+BAA+B,GAChC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAEL,8BAA8B,EAC9B,2CAA2C,GAC5C,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,wBAAwB,EACxB,gCAAgC,GACjC,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,6BAA6B,EAAE,MAAM,iDAAiD,CAAC;AAChG,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAC1G,OAAO,EAAE,+BAA+B,EAAE,MAAM,+CAA+C,CAAC","sourcesContent":["import { requireTrustedUserIdentityResolver } from \"../trustedUserIdentity\";\nimport type { ProjectionUserKeyResolver } from \"./types\";\n\nexport { resolveEventContainerPaths } from \"./document/documentDependencyPaths\";\nexport {\n readAccessEvent,\n readRecordString,\n readRequiredRecordValue,\n} from \"./readers\";\n\nexport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nexport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n} from \"./types\";\n\nexport function requireProjectionUserKeyResolver(\n resolveProjectionUserKey: ProjectionUserKeyResolver | null | undefined,\n label: string,\n): ProjectionUserKeyResolver {\n if (!resolveProjectionUserKey) {\n throw new Error(`${label} requires projection key verification`);\n }\n\n // A ProjectionUserKey is a TrustedUserIdentity, so the shared adapter\n // provides the untrusted-shape and wrong-user guards (with identity caching).\n return requireTrustedUserIdentityResolver(resolveProjectionUserKey);\n}\n\nexport { verifiedContainerCreateManifest } from \"./container/containerCreateManifest\";\nexport { verifyContainerDestinationProjection } from \"./container/containerDestinationVerification\";\nexport {\n collectContainerWriterProjectionPrincipalPolicies,\n verifyContainerWriterProjection,\n} from \"./container/containerProjectionVerification\";\nexport {\n type DocumentWriterProjectionAuthorization,\n verifyDocumentWriterProjection,\n verifyDocumentWriterProjectionAuthorization,\n} from \"./document/documentProjectionVerification\";\nexport {\n verifyDocumentPurgeProof,\n verifyDocumentPurgeProofBaseline,\n} from \"./documentPurge/documentPurgeProofVerification\";\nexport { mergeProjectionPolicyEvidence } from \"./principalPolicy/mergeProjectionPolicyEvidence\";\nexport { principalPolicyHeadMeetsCheckpoint } from \"./principalPolicy/principalPolicyCheckpointSelection\";\nexport { isPrincipalPolicyNotCachedError } from \"./principalPolicy/principalPolicyVerification\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wBAAwB,CAAC;AAG5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AAChF,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,WAAW,CAAC;AAOnB,OAAO,EACL,sCAAsC,EACtC,wCAAwC,GACzC,MAAM,SAAS,CAAC;AAEjB,MAAM,UAAU,gCAAgC,CAC9C,wBAAsE,EACtE,KAAa;IAEb,IAAI,CAAC,wBAAwB,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,uCAAuC,CAAC,CAAC;IACnE,CAAC;IAED,sEAAsE;IACtE,8EAA8E;IAC9E,OAAO,kCAAkC,CAAC,wBAAwB,CAAC,CAAC;AACtE,CAAC;AAED,OAAO,EAAE,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AAC/E,OAAO,EAAE,+BAA+B,EAAE,MAAM,qCAAqC,CAAC;AACtF,OAAO,EAAE,oCAAoC,EAAE,MAAM,8CAA8C,CAAC;AACpG,OAAO,EACL,iDAAiD,EACjD,+BAA+B,GAChC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAEL,8BAA8B,EAC9B,2CAA2C,GAC5C,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,wBAAwB,EACxB,gCAAgC,GACjC,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,6BAA6B,EAAE,MAAM,iDAAiD,CAAC;AAChG,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAC1G,OAAO,EAAE,+BAA+B,EAAE,MAAM,+CAA+C,CAAC","sourcesContent":["import { requireTrustedUserIdentityResolver } from \"../trustedUserIdentity\";\nimport type { ProjectionUserKeyResolver } from \"./types\";\n\nexport { resolveEventContainerPaths } from \"./document/documentDependencyPaths\";\nexport {\n readAccessEvent,\n readRecordString,\n readRequiredRecordValue,\n} from \"./readers\";\n\nexport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nexport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n} from \"./types\";\n\nexport function requireProjectionUserKeyResolver(\n resolveProjectionUserKey: ProjectionUserKeyResolver | null | undefined,\n label: string,\n): ProjectionUserKeyResolver {\n if (!resolveProjectionUserKey) {\n throw new Error(`${label} requires projection key verification`);\n }\n\n // A ProjectionUserKey is a TrustedUserIdentity, so the shared adapter\n // provides the untrusted-shape and wrong-user guards (with identity caching).\n return requireTrustedUserIdentityResolver(resolveProjectionUserKey);\n}\n\nexport { checkWithHeldBundleRecovery } from \"./checkpoints/heldBundleRecovery\";\nexport { verifiedContainerCreateManifest } from \"./container/containerCreateManifest\";\nexport { verifyContainerDestinationProjection } from \"./container/containerDestinationVerification\";\nexport {\n collectContainerWriterProjectionPrincipalPolicies,\n verifyContainerWriterProjection,\n} from \"./container/containerProjectionVerification\";\nexport {\n type DocumentWriterProjectionAuthorization,\n verifyDocumentWriterProjection,\n verifyDocumentWriterProjectionAuthorization,\n} from \"./document/documentProjectionVerification\";\nexport {\n verifyDocumentPurgeProof,\n verifyDocumentPurgeProofBaseline,\n} from \"./documentPurge/documentPurgeProofVerification\";\nexport { mergeProjectionPolicyEvidence } from \"./principalPolicy/mergeProjectionPolicyEvidence\";\nexport { principalPolicyHeadMeetsCheckpoint } from \"./principalPolicy/principalPolicyCheckpointSelection\";\nexport { isPrincipalPolicyNotCachedError } from \"./principalPolicy/principalPolicyVerification\";\n"]}
@@ -9,6 +9,7 @@ import { ensureSqlTables, runOncePerConnection, runSerializedSqlMutation, } from
9
9
  import { DocumentRecordRepository } from "../documents/records/index.js";
10
10
  import { hasQueuedDocumentUpdates, settleQueuedDocumentUpdatesInTransaction, } from "../documents/records/documentPendingUpdatePersistence.js";
11
11
  import { getLatestTimestamp } from "../latestTimestamp.js";
12
+ import { containerMetadataRevalidationPersistence } from "./containerMetadataRevalidations.js";
12
13
  import { loadContainerById } from "./containerPersistence.js";
13
14
  import { claimDormantMetadataSweepAttempt, completeDormantMetadataSweepRequest, listDormantMetadataSweepRequests, } from "./dormantMetadataSweep.js";
14
15
  export { CONTAINER_METADATA_APP_KIND } from "./dormantContainerMetadata.js";
@@ -54,6 +55,7 @@ async function saveStoredContainer(execSql, container, record, options) {
54
55
  }
55
56
  export const sqlContainerContentsPersistence = {
56
57
  ...containerIntentPersistence,
58
+ ...containerMetadataRevalidationPersistence,
57
59
  ...containerMetadataPullContinuationPersistence,
58
60
  commitHydratedContainer: commitStoredHydratedContainer,
59
61
  commitMetadataMutation: commitStoredMetadataMutation,
@@ -1 +1 @@
1
- {"version":3,"file":"containerContentsPersistence.js","sourceRoot":"","sources":["containerContentsPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,4BAA4B,EAC5B,UAAU,EACV,eAAe,EACf,iBAAiB,GAClB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAChG,OAAO,EACL,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EACL,wBAAwB,EACxB,wCAAwC,GACzC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,gCAAgC,EAChC,mCAAmC,EACnC,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AAWhC,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAQzE,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EACL,6BAA6B,EAC7B,8BAA8B,GAC/B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,GACnC,MAAM,wCAAwC,CAAC;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Ae,GAAG,0BAA0B;oBAChD,CAAC,CAAC,SAAS;oBACX,CAAC,CAAC;wBACE,GAAG,SAAS;wBACZ,eAAe,EAAE,kBAAkB,CACjC,SAAS,CAAC,eAAe,EACzB,cAAc,CACf;qBACF,CAAC;gBAEN,OAAO,kCAAkC,CAAC;oBACxC,SAAS,EAAE,eAAe;oBAC1B,MAAM;oBACN,EAAE;oBACF,cAAc;iBACf,CAAC,CAAC;YACL,CAAC,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { eq } from \"drizzle-orm\";\nimport {\n containerHydrationTombstones,\n containers,\n containerTables,\n localIntentTables,\n} from \"../../sqlite/schema\";\nimport { containerSyncWatermarkTables } from \"../../sqlite/schema/containerSyncWatermarkSchema\";\nimport {\n documentContainerProjectionTables,\n documentProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documentTables } from \"../../sqlite/schema/documentRecordSchema\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n ensureSqlTables,\n runOncePerConnection,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../documents/records\";\nimport {\n hasQueuedDocumentUpdates,\n settleQueuedDocumentUpdatesInTransaction,\n} from \"../documents/records/documentPendingUpdatePersistence\";\nimport { getLatestTimestamp } from \"../latestTimestamp\";\nimport { loadContainerById } from \"./containerPersistence\";\nimport {\n claimDormantMetadataSweepAttempt,\n completeDormantMetadataSweepRequest,\n listDormantMetadataSweepRequests,\n} from \"./dormantMetadataSweep\";\n\nexport type {\n ContainerContentsPersistence,\n ContainerCreateIntentRecord,\n ContainerHydrationTombstone,\n ContainerMetadataRecord,\n ContainerMoveIntentRecord,\n LocalRootDescendantReparentInput,\n StoredContainerState,\n} from \"./containerContentsPersistenceTypes\";\nexport { CONTAINER_METADATA_APP_KIND } from \"./dormantContainerMetadata\";\n\nimport type {\n ContainerContentsPersistence,\n ContainerMetadataRecord,\n SaveContainerOptions,\n SaveContainerWithPendingUpdateOptions,\n} from \"./containerContentsPersistenceTypes\";\nimport { deleteStoredContainers } from \"./containerDeletionPersistence\";\nimport {\n commitStoredHydratedContainer,\n loadStoredHeldContainerBinding,\n} from \"./containerHydrationPersistence\";\nimport { containerIntentPersistence } from \"./containerIntentPersistence\";\nimport {\n commitStoredMetadataMutation,\n settleStoredMetadataPendingUpdates,\n} from \"./containerMetadataMutationPersistence\";\nimport { containerMetadataPullContinuationPersistence } from \"./containerMetadataPullContinuationPersistence\";\nimport {\n getContainerMetadataScope,\n saveContainerContentsContainerRows,\n selectContainerMetadataRecord,\n selectContainersWithMetadataRecords,\n} from \"./containerMetadataRows\";\nimport { abandonStoredMoveIntentRevision } from \"./containerMoveAbandonPersistence\";\nimport { containerPendingUpdatePersistence } from \"./containerPendingUpdatePersistence\";\nimport { rebindStoredHeldContainer } from \"./containerRebindPersistence\";\nimport { containerReconcilePersistence } from \"./containerReconcilePersistence\";\nimport { isSupersededContainerBinding } from \"./supersededContainerBindings\";\n\nasync function saveStoredContainer(\n execSql: Parameters<ContainerContentsPersistence[\"saveContainer\"]>[0],\n container: Parameters<ContainerContentsPersistence[\"saveContainer\"]>[1],\n record: ContainerMetadataRecord | null,\n options?:\n | SaveContainerOptions\n | SaveContainerWithPendingUpdateOptions\n | undefined,\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const localUpdatedAt =\n options?.localUpdatedAt ?? options?.updatedAt ?? new Date().toISOString();\n const runtime = getClientSQLitePersistenceRuntime(lockedExecSql);\n const save = async (tx: ClientSQLiteTransactionScope) => {\n const saved = await saveContainerContentsContainerRows({\n container,\n createIntent: options?.createIntent,\n moveIntent: options?.moveIntent,\n record,\n serverTimestamps: options?.serverTimestamps,\n tx,\n localUpdatedAt,\n });\n if (options && \"pendingUpdate\" in options) {\n await new DocumentRecordRepository(\n lockedExecSql,\n ).enqueueDocumentPendingUpdate(\n getContainerMetadataScope(container.id),\n options.pendingUpdate,\n );\n }\n return saved;\n };\n if (!options?.stillCurrent) {\n return runtime.transaction(save);\n }\n const outcome = await runtime.guardedTransaction(\n save,\n options.stillCurrent,\n { behavior: \"immediate\" },\n );\n // Guarded callers recheck the same monotonic generation immediately after\n // this await. Returning the untouched candidate keeps the long-standing\n // non-null save contract while the transaction itself remains rolled back.\n return outcome.result ?? container;\n });\n}\n\nexport const sqlContainerContentsPersistence: ContainerContentsPersistence = {\n ...containerIntentPersistence,\n ...containerMetadataPullContinuationPersistence,\n commitHydratedContainer: commitStoredHydratedContainer,\n commitMetadataMutation: commitStoredMetadataMutation,\n settleAcceptedMetadataPendingUpdates: settleStoredMetadataPendingUpdates,\n listDormantMetadataSweepRequests,\n ...containerPendingUpdatePersistence,\n ...containerReconcilePersistence,\n claimDormantMetadataSweepAttempt,\n completeDormantMetadataSweepRequest,\n async containerExists(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ id: containers.id })\n .from(containers)\n .where(eq(containers.id, containerId))\n .limit(1);\n return rows.length > 0;\n },\n async deleteContainer(execSql, containerId, options) {\n await sqlContainerContentsPersistence.deleteContainers(execSql, [\n {\n containerId,\n reason: options?.reason ?? \"deleted\",\n updatedAt: options?.updatedAt ?? new Date().toISOString(),\n },\n ]);\n },\n async deleteContainers(execSql, removals, options) {\n return deleteStoredContainers(execSql, removals, options);\n },\n async ensureSchema(execSql) {\n // Once ensured on this connection, skip the outer mutation lock entirely:\n // ensureSchema runs on every query path, and re-acquiring the lock just to\n // no-op would queue reads behind unrelated writes.\n await runOncePerConnection(execSql, \"ensure:container-contents\", () =>\n // One ensure, so a cold connection sends three DDL messages in total.\n ensureSqlTables(execSql, [\n ...containerTables,\n ...documentTables,\n ...localIntentTables,\n // Metadata rows consult document purge checkpoints before writing.\n ...keyingCheckpointTables,\n ...documentContainerProjectionTables,\n ...documentProjectionTables,\n ...containerSyncWatermarkTables,\n ]),\n );\n },\n async loadHeldContainerBinding(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return loadStoredHeldContainerBinding(execSql, containerId);\n },\n async isSupersededContainerBinding(execSql, input) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return isSupersededContainerBinding(execSql, input);\n },\n async abandonMoveIntentRevision(execSql, input) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return abandonStoredMoveIntentRevision(execSql, input);\n },\n async rebindHeldContainer(execSql, input) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return rebindStoredHeldContainer(execSql, input);\n },\n async loadContainerMetadataRecord(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return selectContainerMetadataRecord(execSql, containerId);\n },\n async loadContainerHydrationTombstones(execSql) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n containerId: containerHydrationTombstones.containerId,\n generation: containerHydrationTombstones.generation,\n reason: containerHydrationTombstones.reason,\n updatedAt: containerHydrationTombstones.updatedAt,\n })\n .from(containerHydrationTombstones)\n .where(eq(containerHydrationTombstones.cleared, false));\n return rows.flatMap((row) =>\n row.reason === \"access_revoked\" || row.reason === \"deleted\"\n ? [{ ...row, reason: row.reason }]\n : [],\n );\n },\n async loadContainers(execSql) {\n return selectContainersWithMetadataRecords(execSql);\n },\n async loadContainerMetadataState(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const container = await loadContainerById(execSql, containerId);\n if (!container) {\n return null;\n }\n return {\n container,\n record: await selectContainerMetadataRecord(execSql, containerId),\n };\n },\n async saveContainer(execSql, container, record, options) {\n return saveStoredContainer(execSql, container, record, options);\n },\n async saveContainerWithPendingUpdate(execSql, container, record, options) {\n return saveStoredContainer(execSql, container, record, options);\n },\n async saveContainerAndDeletePendingUpdates(\n execSql,\n container,\n record,\n pendingUpdateIds,\n ) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const localUpdatedAt = new Date().toISOString();\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const scope = getContainerMetadataScope(container.id);\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n scope,\n pendingUpdateIds,\n );\n const hasRemainingPendingUpdates = await hasQueuedDocumentUpdates(\n tx,\n scope,\n );\n const containerToSave = hasRemainingPendingUpdates\n ? container\n : {\n ...container,\n serverUpdatedAt: getLatestTimestamp(\n container.serverUpdatedAt,\n localUpdatedAt,\n ),\n };\n\n return saveContainerContentsContainerRows({\n container: containerToSave,\n record,\n tx,\n localUpdatedAt,\n });\n },\n );\n });\n },\n};\n"]}
1
+ {"version":3,"file":"containerContentsPersistence.js","sourceRoot":"","sources":["containerContentsPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,4BAA4B,EAC5B,UAAU,EACV,eAAe,EACf,iBAAiB,GAClB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAChG,OAAO,EACL,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EACL,wBAAwB,EACxB,wCAAwC,GACzC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,kBA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C;IAClE,CAAC;IACD,KAAK,CAAC,oCAAoC,CACxC,OAAO,EACP,SAAS,EACT,MAAM,EACN,gBAAgB;QAEhB,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;YAC/D,MAAM,cAAc,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;YAChD,OAAO,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CACjE,KAAK,EAAE,EAAE,EAAE,EAAE;gBACX,MAAM,KAAK,GAAG,yBAAyB,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;gBACtD,MAAM,wCAAwC,CAC5C,EAAE,EACF,KAAK,EACL,gBAAgB,CACjB,CAAC;gBACF,MAAM,0BAA0B,GAAG,MAAM,wBAAwB,CAC/D,EAAE,EACF,KAAK,CACN,CAAC;gBACF,MAAM,eAAe,GAAG,0BAA0B;oBAChD,CAAC,CAAC,SAAS;oBACX,CAAC,CAAC;wBACE,GAAG,SAAS;wBACZ,eAAe,EAAE,kBAAkB,CACjC,SAAS,CAAC,eAAe,EACzB,cAAc,CACf;qBACF,CAAC;gBAEN,OAAO,kCAAkC,CAAC;oBACxC,SAAS,EAAE,eAAe;oBAC1B,MAAM;oBACN,EAAE;oBACF,cAAc;iBACf,CAAC,CAAC;YACL,CAAC,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { eq } from \"drizzle-orm\";\nimport {\n containerHydrationTombstones,\n containers,\n containerTables,\n localIntentTables,\n} from \"../../sqlite/schema\";\nimport { containerSyncWatermarkTables } from \"../../sqlite/schema/containerSyncWatermarkSchema\";\nimport {\n documentContainerProjectionTables,\n documentProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documentTables } from \"../../sqlite/schema/documentRecordSchema\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n ensureSqlTables,\n runOncePerConnection,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../documents/records\";\nimport {\n hasQueuedDocumentUpdates,\n settleQueuedDocumentUpdatesInTransaction,\n} from \"../documents/records/documentPendingUpdatePersistence\";\nimport { getLatestTimestamp } from \"../latestTimestamp\";\nimport { containerMetadataRevalidationPersistence } from \"./containerMetadataRevalidations\";\nimport { loadContainerById } from \"./containerPersistence\";\nimport {\n claimDormantMetadataSweepAttempt,\n completeDormantMetadataSweepRequest,\n listDormantMetadataSweepRequests,\n} from \"./dormantMetadataSweep\";\n\nexport type {\n ContainerContentsPersistence,\n ContainerCreateIntentRecord,\n ContainerHydrationTombstone,\n ContainerMetadataRecord,\n ContainerMoveIntentRecord,\n LocalRootDescendantReparentInput,\n StoredContainerState,\n} from \"./containerContentsPersistenceTypes\";\nexport { CONTAINER_METADATA_APP_KIND } from \"./dormantContainerMetadata\";\n\nimport type {\n ContainerContentsPersistence,\n ContainerMetadataRecord,\n SaveContainerOptions,\n SaveContainerWithPendingUpdateOptions,\n} from \"./containerContentsPersistenceTypes\";\nimport { deleteStoredContainers } from \"./containerDeletionPersistence\";\nimport {\n commitStoredHydratedContainer,\n loadStoredHeldContainerBinding,\n} from \"./containerHydrationPersistence\";\nimport { containerIntentPersistence } from \"./containerIntentPersistence\";\nimport {\n commitStoredMetadataMutation,\n settleStoredMetadataPendingUpdates,\n} from \"./containerMetadataMutationPersistence\";\nimport { containerMetadataPullContinuationPersistence } from \"./containerMetadataPullContinuationPersistence\";\nimport {\n getContainerMetadataScope,\n saveContainerContentsContainerRows,\n selectContainerMetadataRecord,\n selectContainersWithMetadataRecords,\n} from \"./containerMetadataRows\";\nimport { abandonStoredMoveIntentRevision } from \"./containerMoveAbandonPersistence\";\nimport { containerPendingUpdatePersistence } from \"./containerPendingUpdatePersistence\";\nimport { rebindStoredHeldContainer } from \"./containerRebindPersistence\";\nimport { containerReconcilePersistence } from \"./containerReconcilePersistence\";\nimport { isSupersededContainerBinding } from \"./supersededContainerBindings\";\n\nasync function saveStoredContainer(\n execSql: Parameters<ContainerContentsPersistence[\"saveContainer\"]>[0],\n container: Parameters<ContainerContentsPersistence[\"saveContainer\"]>[1],\n record: ContainerMetadataRecord | null,\n options?:\n | SaveContainerOptions\n | SaveContainerWithPendingUpdateOptions\n | undefined,\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const localUpdatedAt =\n options?.localUpdatedAt ?? options?.updatedAt ?? new Date().toISOString();\n const runtime = getClientSQLitePersistenceRuntime(lockedExecSql);\n const save = async (tx: ClientSQLiteTransactionScope) => {\n const saved = await saveContainerContentsContainerRows({\n container,\n createIntent: options?.createIntent,\n moveIntent: options?.moveIntent,\n record,\n serverTimestamps: options?.serverTimestamps,\n tx,\n localUpdatedAt,\n });\n if (options && \"pendingUpdate\" in options) {\n await new DocumentRecordRepository(\n lockedExecSql,\n ).enqueueDocumentPendingUpdate(\n getContainerMetadataScope(container.id),\n options.pendingUpdate,\n );\n }\n return saved;\n };\n if (!options?.stillCurrent) {\n return runtime.transaction(save);\n }\n const outcome = await runtime.guardedTransaction(\n save,\n options.stillCurrent,\n { behavior: \"immediate\" },\n );\n // Guarded callers recheck the same monotonic generation immediately after\n // this await. Returning the untouched candidate keeps the long-standing\n // non-null save contract while the transaction itself remains rolled back.\n return outcome.result ?? container;\n });\n}\n\nexport const sqlContainerContentsPersistence: ContainerContentsPersistence = {\n ...containerIntentPersistence,\n ...containerMetadataRevalidationPersistence,\n ...containerMetadataPullContinuationPersistence,\n commitHydratedContainer: commitStoredHydratedContainer,\n commitMetadataMutation: commitStoredMetadataMutation,\n settleAcceptedMetadataPendingUpdates: settleStoredMetadataPendingUpdates,\n listDormantMetadataSweepRequests,\n ...containerPendingUpdatePersistence,\n ...containerReconcilePersistence,\n claimDormantMetadataSweepAttempt,\n completeDormantMetadataSweepRequest,\n async containerExists(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ id: containers.id })\n .from(containers)\n .where(eq(containers.id, containerId))\n .limit(1);\n return rows.length > 0;\n },\n async deleteContainer(execSql, containerId, options) {\n await sqlContainerContentsPersistence.deleteContainers(execSql, [\n {\n containerId,\n reason: options?.reason ?? \"deleted\",\n updatedAt: options?.updatedAt ?? new Date().toISOString(),\n },\n ]);\n },\n async deleteContainers(execSql, removals, options) {\n return deleteStoredContainers(execSql, removals, options);\n },\n async ensureSchema(execSql) {\n // Once ensured on this connection, skip the outer mutation lock entirely:\n // ensureSchema runs on every query path, and re-acquiring the lock just to\n // no-op would queue reads behind unrelated writes.\n await runOncePerConnection(execSql, \"ensure:container-contents\", () =>\n // One ensure, so a cold connection sends three DDL messages in total.\n ensureSqlTables(execSql, [\n ...containerTables,\n ...documentTables,\n ...localIntentTables,\n // Metadata rows consult document purge checkpoints before writing.\n ...keyingCheckpointTables,\n ...documentContainerProjectionTables,\n ...documentProjectionTables,\n ...containerSyncWatermarkTables,\n ]),\n );\n },\n async loadHeldContainerBinding(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return loadStoredHeldContainerBinding(execSql, containerId);\n },\n async isSupersededContainerBinding(execSql, input) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return isSupersededContainerBinding(execSql, input);\n },\n async abandonMoveIntentRevision(execSql, input) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return abandonStoredMoveIntentRevision(execSql, input);\n },\n async rebindHeldContainer(execSql, input) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return rebindStoredHeldContainer(execSql, input);\n },\n async loadContainerMetadataRecord(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return selectContainerMetadataRecord(execSql, containerId);\n },\n async loadContainerHydrationTombstones(execSql) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n containerId: containerHydrationTombstones.containerId,\n generation: containerHydrationTombstones.generation,\n reason: containerHydrationTombstones.reason,\n updatedAt: containerHydrationTombstones.updatedAt,\n })\n .from(containerHydrationTombstones)\n .where(eq(containerHydrationTombstones.cleared, false));\n return rows.flatMap((row) =>\n row.reason === \"access_revoked\" || row.reason === \"deleted\"\n ? [{ ...row, reason: row.reason }]\n : [],\n );\n },\n async loadContainers(execSql) {\n return selectContainersWithMetadataRecords(execSql);\n },\n async loadContainerMetadataState(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const container = await loadContainerById(execSql, containerId);\n if (!container) {\n return null;\n }\n return {\n container,\n record: await selectContainerMetadataRecord(execSql, containerId),\n };\n },\n async saveContainer(execSql, container, record, options) {\n return saveStoredContainer(execSql, container, record, options);\n },\n async saveContainerWithPendingUpdate(execSql, container, record, options) {\n return saveStoredContainer(execSql, container, record, options);\n },\n async saveContainerAndDeletePendingUpdates(\n execSql,\n container,\n record,\n pendingUpdateIds,\n ) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const localUpdatedAt = new Date().toISOString();\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const scope = getContainerMetadataScope(container.id);\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n scope,\n pendingUpdateIds,\n );\n const hasRemainingPendingUpdates = await hasQueuedDocumentUpdates(\n tx,\n scope,\n );\n const containerToSave = hasRemainingPendingUpdates\n ? container\n : {\n ...container,\n serverUpdatedAt: getLatestTimestamp(\n container.serverUpdatedAt,\n localUpdatedAt,\n ),\n };\n\n return saveContainerContentsContainerRows({\n container: containerToSave,\n record,\n tx,\n localUpdatedAt,\n });\n },\n );\n });\n },\n};\n"]}
@@ -4,6 +4,7 @@ import type { CONTAINER_CREATE_INTENT_TYPE } from "../../sqlite/schema/index.js"
4
4
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
5
5
  import type { DocumentRecord, PendingUpdateFields, PendingUpdateRecord } from "../documents/records/index.js";
6
6
  import type { HeldContainerBinding } from "./containerBinding.js";
7
+ import type { ContainerMetadataRevalidationPersistence } from "./containerMetadataRevalidations.js";
7
8
  import type { ContainerRecord } from "./containerPersistence.js";
8
9
  import type { DormantMetadataSweepPersistence } from "./dormantMetadataSweep.js";
9
10
  export declare const CONTAINER_MOVE_INTENT_TYPE = "container.move";
@@ -117,7 +118,7 @@ export interface SaveContainerOptions {
117
118
  export interface SaveContainerWithPendingUpdateOptions extends SaveContainerOptions {
118
119
  pendingUpdate: PendingUpdateFields;
119
120
  }
120
- export interface ContainerContentsPersistence extends DormantMetadataSweepPersistence {
121
+ export interface ContainerContentsPersistence extends DormantMetadataSweepPersistence, ContainerMetadataRevalidationPersistence {
121
122
  containerExists: (execSql: ExecSql, containerId: string) => Promise<boolean>;
122
123
  /**
123
124
  * Create an absent remotely hydrated container only when no newer durable
@@ -1 +1 @@
1
- {"version":3,"file":"containerContentsPersistenceTypes.js","sourceRoot":"","sources":["containerContentsPersistenceTypes.ts"],"names":[],"mappings":"AAaA,MAAM,CAAC,MAAM,0BAA0B,GAAG,gBAAgB,CAAC","sourcesContent":["import type { AccessManifestCheckpoint } from \"@tearleads/crypto\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/sync/pullContinuation\";\nimport type { CONTAINER_CREATE_INTENT_TYPE } from \"../../sqlite/schema\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type {\n DocumentRecord,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"../documents/records\";\nimport type { HeldContainerBinding } from \"./containerBinding\";\nimport type { ContainerRecord } from \"./containerPersistence\";\nimport type { DormantMetadataSweepPersistence } from \"./dormantMetadataSweep\";\n\nexport const CONTAINER_MOVE_INTENT_TYPE = \"container.move\";\n\nexport type ContainerCreateIntentSyncStatus = \"pending\" | \"synced\";\nexport type ContainerMoveIntentSyncStatus = \"pending\" | \"blocked\";\n\nexport interface ContainerCreateIntentRecord {\n id: string;\n containerId: string;\n parentContainerId: string;\n intentType: typeof CONTAINER_CREATE_INTENT_TYPE;\n syncStatus: ContainerCreateIntentSyncStatus;\n remoteContainerId: string | null;\n remoteMetadataDocumentId: string | null;\n remoteMetadataAccessStateHash: string | null;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ContainerMoveIntentRecord {\n id: string;\n containerId: string;\n parentContainerId: string;\n previousParentContainerId: string | null;\n intentType: typeof CONTAINER_MOVE_INTENT_TYPE;\n syncStatus: ContainerMoveIntentSyncStatus;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ContainerCreateIntentInput {\n id?: string;\n parentContainerId: string;\n}\n\nexport interface ContainerMoveIntentInput {\n id?: string;\n parentContainerId: string;\n previousParentContainerId?: string | null | undefined;\n}\n\nexport interface ContainerCreateIntentErrorInput {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport type ContainerCreateIntentErrorInputRecorder = (\n execSql: ExecSql,\n input: ContainerCreateIntentErrorInput,\n) => Promise<void>;\n\nexport interface ContainerMoveIntentRevisionInput {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n stillCurrent: () => boolean;\n}\n\nexport interface ContainerCreateIntentRevisionInput\n extends ContainerMoveIntentRevisionInput {\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n /** The remote parent now; a move settlement queues cites it as previous. */\n supersededMovePreviousParentId?: string | undefined;\n /**\n * The parent the create committed under. A desired parent equal to it, or\n * to the current one, owes no move: the user never moved the folder away,\n * and a later remote move by another writer stands.\n */\n createdParentContainerId?: string | undefined;\n /** The parent the settled intent wants. */\n desiredParentContainerId?: string | undefined;\n}\n\nexport interface LocalRootDescendantReparentInput {\n containerId: string;\n parentContainerId: string | null;\n updateCreateIntent?: boolean | undefined;\n}\n\n/**\n * A container's metadata document record plus its durable content: the full\n * Loro updates export of the metadata document, stored in the shared\n * history-checkpoint table under the container-metadata app kind. Metadata\n * documents are tiny registries, so the whole update log is the checkpoint.\n */\nexport interface ContainerMetadataRecord extends DocumentRecord {\n metadataUpdates: string;\n}\n\nexport interface StoredContainerState {\n container: ContainerRecord;\n record: ContainerMetadataRecord | null;\n}\n\nexport interface ContainerRemoval {\n containerId: string;\n reason: \"access_revoked\" | \"deleted\";\n updatedAt: string;\n}\n\nexport interface ContainerHydrationTombstone extends ContainerRemoval {\n generation: number;\n}\n\nexport interface ContainerDeletionGuard {\n containerId: string;\n expectedContainer: ContainerRecord | null;\n}\n\nexport interface SaveContainerOptions {\n createIntent?: ContainerCreateIntentInput;\n stillCurrent?: (() => boolean) | undefined;\n localUpdatedAt?: string;\n moveIntent?: ContainerMoveIntentInput | undefined;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n updatedAt?: string;\n}\n\nexport interface SaveContainerWithPendingUpdateOptions\n extends SaveContainerOptions {\n pendingUpdate: PendingUpdateFields;\n}\n\nexport interface ContainerContentsPersistence\n extends DormantMetadataSweepPersistence {\n containerExists: (execSql: ExecSql, containerId: string) => Promise<boolean>;\n /**\n * Create an absent remotely hydrated container only when no newer durable\n * tombstone or concurrent container/dormant-metadata mutation won first.\n */\n commitHydratedContainer: (\n execSql: ExecSql,\n input: {\n container: ContainerRecord;\n expectedDormantRecord: ContainerMetadataRecord | null;\n /** Tombstone observed before the remote request began, or null. */\n expectedHydrationTombstone?:\n | ContainerHydrationTombstone\n | null\n | undefined;\n /** Current placement verified and pinned before recovery insertion. */\n expectedPlacementCheckpoint?: AccessManifestCheckpoint | undefined;\n record: ContainerMetadataRecord;\n remoteUpdatedAt: string;\n saveOptions: {\n localUpdatedAt?: string;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n };\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<\n { committed: true; container: ContainerRecord } | { committed: false }\n >;\n /** Capture anti-resurrection fences immediately before a remote fetch. */\n loadContainerHydrationTombstones: (\n execSql: ExecSql,\n ) => Promise<ReadonlyArray<ContainerHydrationTombstone>>;\n deleteContainer: (\n execSql: ExecSql,\n containerId: string,\n options?: {\n reason?: ContainerRemoval[\"reason\"];\n updatedAt?: string;\n },\n ) => Promise<void>;\n deleteContainers: (\n execSql: ExecSql,\n removals: ReadonlyArray<ContainerRemoval>,\n options?: {\n /** Must run inside the deletion transaction before any row is removed. */\n beforeDeleteInTransaction?:\n | ((transactionExecSql: ExecSql) => Promise<boolean>)\n | undefined;\n /** Unsigned discovery removes listings but preserves metadata and local intent. */\n discoveryOnly?: boolean;\n /**\n * Request-time states rechecked inside the deletion transaction. An\n * absent or changed row means another pane won and aborts the cascade.\n */\n expectedContainers?: ReadonlyArray<ContainerDeletionGuard>;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<ReadonlyArray<string>>;\n deletePendingUpdates: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n enqueuePendingUpdate: (\n execSql: ExecSql,\n input: PendingUpdateFields & { containerId: string },\n ) => Promise<string>;\n listPendingCreateIntents: (\n execSql: ExecSql,\n ) => Promise<ContainerCreateIntentRecord[]>;\n // Every move intent that has not yet synced, regardless of syncStatus —\n // a blocked move (destination parent not synced yet) is still unsynced, and\n // synced moves are deleted (see markMoveIntentRevisionSynced), so every surviving\n // row qualifies. Blocked intents replay too: \"blocked\" names the reason the\n // last attempt could not proceed, not a terminal verdict.\n listUnsyncedMoveIntents: (\n execSql: ExecSql,\n ) => Promise<ContainerMoveIntentRecord[]>;\n listContainerIdsWithPendingUpdates: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<string[]>;\n listContainerIdsWithPullContinuations: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<string[]>;\n listPendingUpdates: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<PendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n /** Revision-CAS error recorder used by asynchronous create replay. */\n recordCreateIntentRevisionError: ContainerCreateIntentErrorInputRecorder;\n recordMoveIntentError: (\n execSql: ExecSql,\n input: {\n blocked?: boolean | undefined;\n containerId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt?: string | undefined;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<void>;\n reassignContainerDocuments: (\n execSql: ExecSql,\n input: {\n fromContainerId: string;\n stillCurrent?: (() => boolean) | undefined;\n toContainerId: string;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n reconcileLocalRootContainer: (\n execSql: ExecSql,\n input: {\n descendantReparents: ReadonlyArray<LocalRootDescendantReparentInput>;\n localRootContainerId: string;\n remoteOrganizationId: string;\n remoteRootContainerId: string;\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n reconcileLocalSystemContainer: (\n execSql: ExecSql,\n input: {\n localContainerId: string;\n remoteContainerId: string;\n remoteOrganizationId: string;\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n loadContainers: (\n execSql: ExecSql,\n ) => Promise<ReadonlyArray<StoredContainerState>>;\n loadContainerMetadataState: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<StoredContainerState | null>;\n /**\n * The organization and metadata target this device holds for a container,\n * from its live row or retained dormant metadata; null when never held.\n */\n loadHeldContainerBinding: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<HeldContainerBinding | null>;\n /** Whether a held folder was re-homed away from this organization. */\n isSupersededContainerBinding: (\n execSql: ExecSql,\n input: { containerId: string; organizationId: string },\n ) => Promise<boolean>;\n /**\n * Move a held folder to the binding its own user re-created it under,\n * resetting the metadata record's remote stream; false if the held binding\n * changed since it was read.\n */\n rebindHeldContainer: (\n execSql: ExecSql,\n input: {\n containerId: string;\n expected: HeldContainerBinding;\n next: { metadataDocumentId: string; organizationId: string };\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<boolean>;\n /**\n * Load a container-metadata record by container id alone, without\n * requiring a containers row — the dormant shape row 4's access_revoked\n * branch leaves behind, re-attached on rehydration.\n */\n loadContainerMetadataRecord: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<ContainerMetadataRecord | null>;\n /**\n * Atomically replace the exact rejected metadata pull continuation with its\n * durable recovery marker and return the authoritative current record.\n */\n invalidateMetadataPullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n containerId: string;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<ContainerMetadataRecord | null>;\n /**\n * Conditionally commit metadata content, its outgoing row, accepted queue\n * settlement, container fields, and the canonical record in one transaction.\n */\n commitMetadataMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n clearSyncFailure?: boolean | undefined;\n container: ContainerRecord;\n expectedContainer: ContainerRecord;\n expectedRecord: ContainerMetadataRecord;\n createIntentSettlement?:\n | {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n /**\n * When present, an overtaking create revision is adopted as the\n * desired local parent and converted to a move from this remotely\n * committed parent instead of rejecting the remote identity.\n */\n supersededMovePreviousParentId?: string | undefined;\n }\n | undefined;\n moveIntentSettlement?:\n | {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n }\n | undefined;\n /** Present only for an explicit local primary change; null clears it. */\n primaryDocumentId?: string | null | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n preserveDurableStructureWhenPending?: boolean | undefined;\n record: ContainerMetadataRecord;\n saveOptions?:\n | {\n createIntent?: ContainerCreateIntentInput;\n localUpdatedAt?: string;\n moveIntent?: ContainerMoveIntentInput | undefined;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n updatedAt?: string;\n }\n | undefined;\n settleAcceptedPendingOnConflict: boolean;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<\n | {\n committed: true;\n container: ContainerRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | {\n committed: false;\n currentState: StoredContainerState | null;\n staleServerState?: true;\n }\n >;\n settleAcceptedMetadataPendingUpdates: (\n execSql: ExecSql,\n input: {\n containerId: string;\n expectedRecord: ContainerMetadataRecord;\n pendingUpdateIds: readonly string[];\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<StoredContainerState | null>;\n saveContainer: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord | null,\n options?: SaveContainerOptions,\n ) => Promise<ContainerRecord>;\n /**\n * Atomically saves a container and enqueues its first metadata update.\n * Host adapters must implement the compound write in their own transaction.\n */\n saveContainerWithPendingUpdate: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord,\n options: SaveContainerWithPendingUpdateOptions,\n ) => Promise<ContainerRecord>;\n saveContainerAndDeletePendingUpdates: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord,\n pendingUpdateIds: readonly string[],\n ) => Promise<ContainerRecord>;\n /**\n * Revision-CAS settlement used by asynchronous create replay. Invalid\n * adapters are rejected before the remote mutation begins.\n */\n markCreateIntentRevisionSynced: (\n execSql: ExecSql,\n input: ContainerCreateIntentRevisionInput,\n ) => Promise<boolean>;\n /**\n * Explicit revision-CAS settlement. Move replay instead settles inside\n * commitMetadataMutation and requires its atomic acknowledgment.\n */\n markMoveIntentRevisionSynced: (\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput,\n ) => Promise<boolean>;\n /**\n * Drop a move revision the server refuses for good and restore the\n * folder's previous parent in the same transaction; false if superseded.\n */\n abandonMoveIntentRevision: (\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput & {\n previousParentContainerId: string;\n },\n ) => Promise<boolean>;\n}\n"]}
1
+ {"version":3,"file":"containerContentsPersistenceTypes.js","sourceRoot":"","sources":["containerContentsPersistenceTypes.ts"],"names":[],"mappings":"AAcA,MAAM,CAAC,MAAM,0BAA0B,GAAG,gBAAgB,CAAC","sourcesContent":["import type { AccessManifestCheckpoint } from \"@tearleads/crypto\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/sync/pullContinuation\";\nimport type { CONTAINER_CREATE_INTENT_TYPE } from \"../../sqlite/schema\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type {\n DocumentRecord,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"../documents/records\";\nimport type { HeldContainerBinding } from \"./containerBinding\";\nimport type { ContainerMetadataRevalidationPersistence } from \"./containerMetadataRevalidations\";\nimport type { ContainerRecord } from \"./containerPersistence\";\nimport type { DormantMetadataSweepPersistence } from \"./dormantMetadataSweep\";\n\nexport const CONTAINER_MOVE_INTENT_TYPE = \"container.move\";\n\nexport type ContainerCreateIntentSyncStatus = \"pending\" | \"synced\";\nexport type ContainerMoveIntentSyncStatus = \"pending\" | \"blocked\";\n\nexport interface ContainerCreateIntentRecord {\n id: string;\n containerId: string;\n parentContainerId: string;\n intentType: typeof CONTAINER_CREATE_INTENT_TYPE;\n syncStatus: ContainerCreateIntentSyncStatus;\n remoteContainerId: string | null;\n remoteMetadataDocumentId: string | null;\n remoteMetadataAccessStateHash: string | null;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ContainerMoveIntentRecord {\n id: string;\n containerId: string;\n parentContainerId: string;\n previousParentContainerId: string | null;\n intentType: typeof CONTAINER_MOVE_INTENT_TYPE;\n syncStatus: ContainerMoveIntentSyncStatus;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ContainerCreateIntentInput {\n id?: string;\n parentContainerId: string;\n}\n\nexport interface ContainerMoveIntentInput {\n id?: string;\n parentContainerId: string;\n previousParentContainerId?: string | null | undefined;\n}\n\nexport interface ContainerCreateIntentErrorInput {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport type ContainerCreateIntentErrorInputRecorder = (\n execSql: ExecSql,\n input: ContainerCreateIntentErrorInput,\n) => Promise<void>;\n\nexport interface ContainerMoveIntentRevisionInput {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n stillCurrent: () => boolean;\n}\n\nexport interface ContainerCreateIntentRevisionInput\n extends ContainerMoveIntentRevisionInput {\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n /** The remote parent now; a move settlement queues cites it as previous. */\n supersededMovePreviousParentId?: string | undefined;\n /**\n * The parent the create committed under. A desired parent equal to it, or\n * to the current one, owes no move: the user never moved the folder away,\n * and a later remote move by another writer stands.\n */\n createdParentContainerId?: string | undefined;\n /** The parent the settled intent wants. */\n desiredParentContainerId?: string | undefined;\n}\n\nexport interface LocalRootDescendantReparentInput {\n containerId: string;\n parentContainerId: string | null;\n updateCreateIntent?: boolean | undefined;\n}\n\n/**\n * A container's metadata document record plus its durable content: the full\n * Loro updates export of the metadata document, stored in the shared\n * history-checkpoint table under the container-metadata app kind. Metadata\n * documents are tiny registries, so the whole update log is the checkpoint.\n */\nexport interface ContainerMetadataRecord extends DocumentRecord {\n metadataUpdates: string;\n}\n\nexport interface StoredContainerState {\n container: ContainerRecord;\n record: ContainerMetadataRecord | null;\n}\n\nexport interface ContainerRemoval {\n containerId: string;\n reason: \"access_revoked\" | \"deleted\";\n updatedAt: string;\n}\n\nexport interface ContainerHydrationTombstone extends ContainerRemoval {\n generation: number;\n}\n\nexport interface ContainerDeletionGuard {\n containerId: string;\n expectedContainer: ContainerRecord | null;\n}\n\nexport interface SaveContainerOptions {\n createIntent?: ContainerCreateIntentInput;\n stillCurrent?: (() => boolean) | undefined;\n localUpdatedAt?: string;\n moveIntent?: ContainerMoveIntentInput | undefined;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n updatedAt?: string;\n}\n\nexport interface SaveContainerWithPendingUpdateOptions\n extends SaveContainerOptions {\n pendingUpdate: PendingUpdateFields;\n}\n\nexport interface ContainerContentsPersistence\n extends DormantMetadataSweepPersistence,\n ContainerMetadataRevalidationPersistence {\n containerExists: (execSql: ExecSql, containerId: string) => Promise<boolean>;\n /**\n * Create an absent remotely hydrated container only when no newer durable\n * tombstone or concurrent container/dormant-metadata mutation won first.\n */\n commitHydratedContainer: (\n execSql: ExecSql,\n input: {\n container: ContainerRecord;\n expectedDormantRecord: ContainerMetadataRecord | null;\n /** Tombstone observed before the remote request began, or null. */\n expectedHydrationTombstone?:\n | ContainerHydrationTombstone\n | null\n | undefined;\n /** Current placement verified and pinned before recovery insertion. */\n expectedPlacementCheckpoint?: AccessManifestCheckpoint | undefined;\n record: ContainerMetadataRecord;\n remoteUpdatedAt: string;\n saveOptions: {\n localUpdatedAt?: string;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n };\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<\n { committed: true; container: ContainerRecord } | { committed: false }\n >;\n /** Capture anti-resurrection fences immediately before a remote fetch. */\n loadContainerHydrationTombstones: (\n execSql: ExecSql,\n ) => Promise<ReadonlyArray<ContainerHydrationTombstone>>;\n deleteContainer: (\n execSql: ExecSql,\n containerId: string,\n options?: {\n reason?: ContainerRemoval[\"reason\"];\n updatedAt?: string;\n },\n ) => Promise<void>;\n deleteContainers: (\n execSql: ExecSql,\n removals: ReadonlyArray<ContainerRemoval>,\n options?: {\n /** Must run inside the deletion transaction before any row is removed. */\n beforeDeleteInTransaction?:\n | ((transactionExecSql: ExecSql) => Promise<boolean>)\n | undefined;\n /** Unsigned discovery removes listings but preserves metadata and local intent. */\n discoveryOnly?: boolean;\n /**\n * Request-time states rechecked inside the deletion transaction. An\n * absent or changed row means another pane won and aborts the cascade.\n */\n expectedContainers?: ReadonlyArray<ContainerDeletionGuard>;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<ReadonlyArray<string>>;\n deletePendingUpdates: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n enqueuePendingUpdate: (\n execSql: ExecSql,\n input: PendingUpdateFields & { containerId: string },\n ) => Promise<string>;\n listPendingCreateIntents: (\n execSql: ExecSql,\n ) => Promise<ContainerCreateIntentRecord[]>;\n // Every move intent that has not yet synced, regardless of syncStatus —\n // a blocked move (destination parent not synced yet) is still unsynced, and\n // synced moves are deleted (see markMoveIntentRevisionSynced), so every surviving\n // row qualifies. Blocked intents replay too: \"blocked\" names the reason the\n // last attempt could not proceed, not a terminal verdict.\n listUnsyncedMoveIntents: (\n execSql: ExecSql,\n ) => Promise<ContainerMoveIntentRecord[]>;\n listContainerIdsWithPendingUpdates: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<string[]>;\n listContainerIdsWithPullContinuations: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<string[]>;\n listPendingUpdates: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<PendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n /** Revision-CAS error recorder used by asynchronous create replay. */\n recordCreateIntentRevisionError: ContainerCreateIntentErrorInputRecorder;\n recordMoveIntentError: (\n execSql: ExecSql,\n input: {\n blocked?: boolean | undefined;\n containerId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt?: string | undefined;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<void>;\n reassignContainerDocuments: (\n execSql: ExecSql,\n input: {\n fromContainerId: string;\n stillCurrent?: (() => boolean) | undefined;\n toContainerId: string;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n reconcileLocalRootContainer: (\n execSql: ExecSql,\n input: {\n descendantReparents: ReadonlyArray<LocalRootDescendantReparentInput>;\n localRootContainerId: string;\n remoteOrganizationId: string;\n remoteRootContainerId: string;\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n reconcileLocalSystemContainer: (\n execSql: ExecSql,\n input: {\n localContainerId: string;\n remoteContainerId: string;\n remoteOrganizationId: string;\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n loadContainers: (\n execSql: ExecSql,\n ) => Promise<ReadonlyArray<StoredContainerState>>;\n loadContainerMetadataState: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<StoredContainerState | null>;\n /**\n * The organization and metadata target this device holds for a container,\n * from its live row or retained dormant metadata; null when never held.\n */\n loadHeldContainerBinding: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<HeldContainerBinding | null>;\n /** Whether a held folder was re-homed away from this organization. */\n isSupersededContainerBinding: (\n execSql: ExecSql,\n input: { containerId: string; organizationId: string },\n ) => Promise<boolean>;\n /**\n * Move a held folder to the binding its own user re-created it under,\n * resetting the metadata record's remote stream; false if the held binding\n * changed since it was read.\n */\n rebindHeldContainer: (\n execSql: ExecSql,\n input: {\n containerId: string;\n expected: HeldContainerBinding;\n next: { metadataDocumentId: string; organizationId: string };\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<boolean>;\n /**\n * Load a container-metadata record by container id alone, without\n * requiring a containers row — the dormant shape row 4's access_revoked\n * branch leaves behind, re-attached on rehydration.\n */\n loadContainerMetadataRecord: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<ContainerMetadataRecord | null>;\n /**\n * Atomically replace the exact rejected metadata pull continuation with its\n * durable recovery marker and return the authoritative current record.\n */\n invalidateMetadataPullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n containerId: string;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<ContainerMetadataRecord | null>;\n /**\n * Conditionally commit metadata content, its outgoing row, accepted queue\n * settlement, container fields, and the canonical record in one transaction.\n */\n commitMetadataMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n clearSyncFailure?: boolean | undefined;\n container: ContainerRecord;\n expectedContainer: ContainerRecord;\n expectedRecord: ContainerMetadataRecord;\n createIntentSettlement?:\n | {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n /**\n * When present, an overtaking create revision is adopted as the\n * desired local parent and converted to a move from this remotely\n * committed parent instead of rejecting the remote identity.\n */\n supersededMovePreviousParentId?: string | undefined;\n }\n | undefined;\n moveIntentSettlement?:\n | {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n }\n | undefined;\n /** Present only for an explicit local primary change; null clears it. */\n primaryDocumentId?: string | null | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n preserveDurableStructureWhenPending?: boolean | undefined;\n record: ContainerMetadataRecord;\n saveOptions?:\n | {\n createIntent?: ContainerCreateIntentInput;\n localUpdatedAt?: string;\n moveIntent?: ContainerMoveIntentInput | undefined;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n updatedAt?: string;\n }\n | undefined;\n settleAcceptedPendingOnConflict: boolean;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<\n | {\n committed: true;\n container: ContainerRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | {\n committed: false;\n currentState: StoredContainerState | null;\n staleServerState?: true;\n }\n >;\n settleAcceptedMetadataPendingUpdates: (\n execSql: ExecSql,\n input: {\n containerId: string;\n expectedRecord: ContainerMetadataRecord;\n pendingUpdateIds: readonly string[];\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<StoredContainerState | null>;\n saveContainer: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord | null,\n options?: SaveContainerOptions,\n ) => Promise<ContainerRecord>;\n /**\n * Atomically saves a container and enqueues its first metadata update.\n * Host adapters must implement the compound write in their own transaction.\n */\n saveContainerWithPendingUpdate: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord,\n options: SaveContainerWithPendingUpdateOptions,\n ) => Promise<ContainerRecord>;\n saveContainerAndDeletePendingUpdates: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord,\n pendingUpdateIds: readonly string[],\n ) => Promise<ContainerRecord>;\n /**\n * Revision-CAS settlement used by asynchronous create replay. Invalid\n * adapters are rejected before the remote mutation begins.\n */\n markCreateIntentRevisionSynced: (\n execSql: ExecSql,\n input: ContainerCreateIntentRevisionInput,\n ) => Promise<boolean>;\n /**\n * Explicit revision-CAS settlement. Move replay instead settles inside\n * commitMetadataMutation and requires its atomic acknowledgment.\n */\n markMoveIntentRevisionSynced: (\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput,\n ) => Promise<boolean>;\n /**\n * Drop a move revision the server refuses for good and restore the\n * folder's previous parent in the same transaction; false if superseded.\n */\n abandonMoveIntentRevision: (\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput & {\n previousParentContainerId: string;\n },\n ) => Promise<boolean>;\n}\n"]}
@@ -0,0 +1,22 @@
1
+ import type { ExecSql } from "../../sqlite/sqlSchema.js";
2
+ /** A metadata document owed a remote read, and the request's revision. */
3
+ export interface ContainerMetadataRevalidation {
4
+ readonly advertisedVersionVector: string;
5
+ readonly documentId: string;
6
+ readonly revision: string;
7
+ }
8
+ export interface ContainerMetadataRevalidationPersistence {
9
+ /** Record, or renew, a request that a metadata document be read. */
10
+ requestContainerMetadataRevalidation: (execSql: ExecSql, request: {
11
+ readonly advertisedVersionVector: string;
12
+ readonly documentId: string;
13
+ }) => Promise<void>;
14
+ /** Requests still owed, in document id order. */
15
+ listContainerMetadataRevalidations: (execSql: ExecSql) => Promise<readonly ContainerMetadataRevalidation[]>;
16
+ /**
17
+ * Settle the request a read observed. A newer request, from this tab or
18
+ * another sharing the database, carries another revision and stays.
19
+ */
20
+ settleContainerMetadataRevalidation: (execSql: ExecSql, revalidation: ContainerMetadataRevalidation) => Promise<void>;
21
+ }
22
+ export declare const containerMetadataRevalidationPersistence: ContainerMetadataRevalidationPersistence;
@@ -0,0 +1,52 @@
1
+ import { and, eq, sql } from "drizzle-orm";
2
+ import { containerMetadataRevalidations } from "../../sqlite/schema/index.js";
3
+ import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
4
+ import { ensureContainerTables } from "./containerPersistence.js";
5
+ async function requestContainerMetadataRevalidation(execSql, request) {
6
+ await ensureContainerTables(execSql);
7
+ await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {
8
+ await db
9
+ .insert(containerMetadataRevalidations)
10
+ .values({
11
+ advertisedVersionVector: request.advertisedVersionVector,
12
+ documentId: request.documentId,
13
+ requestedAt: new Date().toISOString(),
14
+ revision: crypto.randomUUID(),
15
+ })
16
+ .onConflictDoUpdate({
17
+ target: containerMetadataRevalidations.documentId,
18
+ set: {
19
+ advertisedVersionVector: sql `excluded.advertised_version_vector`,
20
+ requestedAt: sql `excluded.requested_at`,
21
+ revision: sql `excluded.revision`,
22
+ },
23
+ })
24
+ .run();
25
+ });
26
+ }
27
+ async function listContainerMetadataRevalidations(execSql) {
28
+ await ensureContainerTables(execSql);
29
+ return getClientSQLitePersistenceRuntime(execSql)
30
+ .db.select({
31
+ advertisedVersionVector: containerMetadataRevalidations.advertisedVersionVector,
32
+ documentId: containerMetadataRevalidations.documentId,
33
+ revision: containerMetadataRevalidations.revision,
34
+ })
35
+ .from(containerMetadataRevalidations)
36
+ .orderBy(containerMetadataRevalidations.documentId);
37
+ }
38
+ async function settleContainerMetadataRevalidation(execSql, revalidation) {
39
+ await ensureContainerTables(execSql);
40
+ await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {
41
+ await db
42
+ .delete(containerMetadataRevalidations)
43
+ .where(and(eq(containerMetadataRevalidations.documentId, revalidation.documentId), eq(containerMetadataRevalidations.revision, revalidation.revision)))
44
+ .run();
45
+ });
46
+ }
47
+ export const containerMetadataRevalidationPersistence = {
48
+ listContainerMetadataRevalidations,
49
+ requestContainerMetadataRevalidation,
50
+ settleContainerMetadataRevalidation,
51
+ };
52
+ //# sourceMappingURL=containerMetadataRevalidations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"containerMetadataRevalidations.js","sourceRoot":"","sources":["containerMetadataRevalidations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAE1F,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAgC/D,KAAK,UAAU,oCAAoC,CACjD,OAAgB,EAChB,OAGC;IAED,MAAM,qBAAqB,CAAC,OAAO,CAAC,CAAC;IACrC,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,EAAE;aACL,MAAM,CAAC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AQ,EAAE,YAAY,CAAC,QAAQ,CAAC,CACnE,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,MAAM,wCAAwC,GACnD;IACE,kCAAkC;IAClC,oCAAoC;IACpC,mCAAmC;CACpC,CAAC","sourcesContent":["import { and, eq, sql } from \"drizzle-orm\";\nimport { containerMetadataRevalidations } from \"../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { ensureContainerTables } from \"./containerPersistence\";\n\n/** A metadata document owed a remote read, and the request's revision. */\nexport interface ContainerMetadataRevalidation {\n readonly advertisedVersionVector: string;\n readonly documentId: string;\n readonly revision: string;\n}\n\nexport interface ContainerMetadataRevalidationPersistence {\n /** Record, or renew, a request that a metadata document be read. */\n requestContainerMetadataRevalidation: (\n execSql: ExecSql,\n request: {\n readonly advertisedVersionVector: string;\n readonly documentId: string;\n },\n ) => Promise<void>;\n /** Requests still owed, in document id order. */\n listContainerMetadataRevalidations: (\n execSql: ExecSql,\n ) => Promise<readonly ContainerMetadataRevalidation[]>;\n /**\n * Settle the request a read observed. A newer request, from this tab or\n * another sharing the database, carries another revision and stays.\n */\n settleContainerMetadataRevalidation: (\n execSql: ExecSql,\n revalidation: ContainerMetadataRevalidation,\n ) => Promise<void>;\n}\n\nasync function requestContainerMetadataRevalidation(\n execSql: ExecSql,\n request: {\n readonly advertisedVersionVector: string;\n readonly documentId: string;\n },\n): Promise<void> {\n await ensureContainerTables(execSql);\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .insert(containerMetadataRevalidations)\n .values({\n advertisedVersionVector: request.advertisedVersionVector,\n documentId: request.documentId,\n requestedAt: new Date().toISOString(),\n revision: crypto.randomUUID(),\n })\n .onConflictDoUpdate({\n target: containerMetadataRevalidations.documentId,\n set: {\n advertisedVersionVector: sql`excluded.advertised_version_vector`,\n requestedAt: sql`excluded.requested_at`,\n revision: sql`excluded.revision`,\n },\n })\n .run();\n });\n}\n\nasync function listContainerMetadataRevalidations(\n execSql: ExecSql,\n): Promise<readonly ContainerMetadataRevalidation[]> {\n await ensureContainerTables(execSql);\n return getClientSQLitePersistenceRuntime(execSql)\n .db.select({\n advertisedVersionVector:\n containerMetadataRevalidations.advertisedVersionVector,\n documentId: containerMetadataRevalidations.documentId,\n revision: containerMetadataRevalidations.revision,\n })\n .from(containerMetadataRevalidations)\n .orderBy(containerMetadataRevalidations.documentId);\n}\n\nasync function settleContainerMetadataRevalidation(\n execSql: ExecSql,\n revalidation: ContainerMetadataRevalidation,\n): Promise<void> {\n await ensureContainerTables(execSql);\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .delete(containerMetadataRevalidations)\n .where(\n and(\n eq(\n containerMetadataRevalidations.documentId,\n revalidation.documentId,\n ),\n eq(containerMetadataRevalidations.revision, revalidation.revision),\n ),\n )\n .run();\n });\n}\n\nexport const containerMetadataRevalidationPersistence: ContainerMetadataRevalidationPersistence =\n {\n listContainerMetadataRevalidations,\n requestContainerMetadataRevalidation,\n settleContainerMetadataRevalidation,\n };\n"]}
@@ -1,9 +1,10 @@
1
1
  import { eq } from "drizzle-orm";
2
2
  import { documentPurgeCheckpoints, keyingCheckpointTables, } from "../../sqlite/schema/keyingCheckpointSchema.js";
3
3
  import { principalPolicyTables } from "../../sqlite/schema/principalPolicySchema.js";
4
+ import { verifiedManifestBundleTables } from "../../sqlite/schema/verifiedManifestBundleSchema.js";
4
5
  import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
5
6
  import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
6
- import { verifiedManifestBundleRows, } from "../verifiedManifestBundlePersistence.js";
7
+ import { verifiedManifestBundleRows, writeVerifiedManifestBundlesInTransaction, } from "../verifiedManifestBundlePersistence.js";
7
8
  import { advanceKeyingCheckpointsInTransaction, keyingCheckpointBatchTables, validateKeyingCheckpointsInTransaction, } from "./keyingCheckpointAdvancePersistence.js";
8
9
  import { loadAccessManifestCheckpointRow, loadPrincipalPolicyCheckpointRow, } from "./keyingCheckpointPersistence.js";
9
10
  import { acknowledgeLocallyAuthoredHeadsInTransaction, } from "./locallyAcknowledgedCheckpointPersistence.js";
@@ -86,12 +87,23 @@ export class KeyingCheckpointRepository {
86
87
  }
87
88
  await runtime.transaction(advance, { behavior: "immediate" });
88
89
  }
89
- /** Whether the heads committed; false only when `stillCurrent` turned false. */
90
+ /**
91
+ * Whether the heads committed; false only when `stillCurrent` turned false.
92
+ * A head's authored bundle, when its acknowledgement matched, is stored for
93
+ * citation in the same transaction, so it commits only with its pin.
94
+ */
90
95
  async advanceLocallyAcknowledgedAccessManifestHeadsAtomically(advance) {
91
- await ensureSqlTables(this.execSql, keyingCheckpointTables);
96
+ const bundleRows = await verifiedManifestBundleRows(advance.heads.flatMap(({ checkpoint, servedBundle }) => servedBundle ? [{ bundle: servedBundle, checkpoint }] : []));
97
+ await ensureSqlTables(this.execSql, [
98
+ ...keyingCheckpointTables,
99
+ ...(bundleRows.length > 0 ? verifiedManifestBundleTables : []),
100
+ ]);
92
101
  const updatedAt = this.now().toISOString();
93
102
  const runtime = getClientSQLitePersistenceRuntime(this.execSql);
94
- const acknowledge = (tx) => acknowledgeLocallyAuthoredHeadsInTransaction(tx, advance, updatedAt);
103
+ const acknowledge = async (tx) => {
104
+ await acknowledgeLocallyAuthoredHeadsInTransaction(tx, advance, updatedAt);
105
+ await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, updatedAt);
106
+ };
95
107
  if (advance.stillCurrent) {
96
108
  return (await runtime.guardedTransaction(acknowledge, advance.stillCurrent, {
97
109
  behavior: "immediate",
@@ -1 +1 @@
1
- {"version":3,"file":"keyingCheckpointRepository.js","sourceRoot":"","sources":["keyingCheckpointRepository.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAA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K,CAAC,YAAY,CACxB,KAA4B;QAE5B,MAAM,UAAU,GAAG,MAAM,0BAA0B,CACjD,KAAK,CAAC,eAAe,IAAI,EAAE,CAC5B,CAAC;QACF,MAAM,eAAe,CACnB,IAAI,CAAC,OAAO,EACZ,2BAA2B,CAAC,KAAK,EAAE,UAAU,CAAC,CAC/C,CAAC;QACF,OAAO,UAAU,CAAC;IACpB,CAAC;CACF","sourcesContent":["import type {\n AccessManifestCheckpoint,\n AccessObjectKind,\n ManagedPrincipalKind,\n PrincipalPolicyCheckpoint,\n VerifiedOrganizationReplacementAuthorization,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport {\n documentPurgeCheckpoints,\n keyingCheckpointTables,\n} from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalPolicyTables } from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n type VerifiedManifestBundleRow,\n verifiedManifestBundleRows,\n} from \"../verifiedManifestBundlePersistence\";\nimport type { DocumentPurgeCheckpoint } from \"./documentPurgeCheckpointPersistence\";\nimport {\n advanceKeyingCheckpointsInTransaction,\n type KeyingCheckpointAdvanceBatch,\n type KeyingCheckpointBatch,\n keyingCheckpointBatchTables,\n validateKeyingCheckpointsInTransaction,\n} from \"./keyingCheckpointAdvancePersistence\";\nimport {\n loadAccessManifestCheckpointRow,\n loadPrincipalPolicyCheckpointRow,\n} from \"./keyingCheckpointPersistence\";\nimport {\n acknowledgeLocallyAuthoredHeadsInTransaction,\n type LocallyAcknowledgedAdvance,\n} from \"./locallyAcknowledgedCheckpointPersistence\";\nimport { seedOrganizationReplacementCheckpointsInTransaction } from \"./organizationReplacementCheckpointPersistence\";\n\n/**\n * The durable keying pins projection verification compares against: access\n * manifest, principal policy, and document purge checkpoints, bound to one\n * executor and clock. Each method ensures its tables and runs its own\n * immediate transaction. Work inside a caller's transaction takes the locked\n * handle per call through the `*InTransaction` functions instead.\n */\nexport class KeyingCheckpointRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n async loadAccessManifestCheckpoint(\n objectKind: AccessObjectKind,\n organizationId: string,\n objectId: string,\n ): Promise<AccessManifestCheckpoint | null> {\n await ensureSqlTables(this.execSql, keyingCheckpointTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const row = await loadAccessManifestCheckpointRow(db, {\n objectKind,\n organizationId,\n objectId,\n });\n return row ? { objectKind, objectId, organizationId, ...row } : null;\n }\n\n async loadPrincipalPolicyCheckpoint(\n principalType: ManagedPrincipalKind,\n principalId: string,\n ): Promise<PrincipalPolicyCheckpoint | null> {\n await ensureSqlTables(this.execSql, keyingCheckpointTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const row = await loadPrincipalPolicyCheckpointRow(db, {\n principalType,\n principalId,\n });\n return row ? { principalType, principalId, ...row } : null;\n }\n\n async loadDocumentPurgeCheckpoint(\n documentId: string,\n ): Promise<DocumentPurgeCheckpoint | null> {\n await ensureSqlTables(this.execSql, keyingCheckpointTables);\n const [row] = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({\n documentId: documentPurgeCheckpoints.documentId,\n documentManifestHash: documentPurgeCheckpoints.documentManifestHash,\n organizationId: documentPurgeCheckpoints.organizationId,\n purgeEventHash: documentPurgeCheckpoints.purgeEventHash,\n })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, documentId))\n .limit(1);\n return row ?? null;\n }\n\n /**\n * Re-checks verified candidates against durable pins without advancing\n * them; only the verified bundles' citation rows are written.\n */\n async validateKeyingCheckpointsAtomically(\n batch: KeyingCheckpointBatch,\n ): Promise<void> {\n const bundleRows = await this.prepareBatch(batch);\n const verifiedAt = this.now().toISOString();\n const validate = (tx: ClientSQLiteTransactionScope) =>\n validateKeyingCheckpointsInTransaction(tx, batch, bundleRows, verifiedAt);\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n if (batch.stillCurrent) {\n await runtime.guardedTransaction(validate, batch.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(validate, { behavior: \"immediate\" });\n }\n\n /** Advances the complete verified batch in one immediate transaction. */\n async advanceKeyingCheckpointsAtomically(\n batch: KeyingCheckpointAdvanceBatch,\n ): Promise<void> {\n const bundleRows = await this.prepareBatch(batch);\n const updatedAt = this.now().toISOString();\n const advance = (tx: ClientSQLiteTransactionScope) =>\n advanceKeyingCheckpointsInTransaction(tx, batch, bundleRows, updatedAt);\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n if (batch.stillCurrent) {\n await runtime.guardedTransaction(advance, batch.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(advance, { behavior: \"immediate\" });\n }\n\n /** Whether the heads committed; false only when `stillCurrent` turned false. */\n async advanceLocallyAcknowledgedAccessManifestHeadsAtomically(\n advance: LocallyAcknowledgedAdvance,\n ): Promise<boolean> {\n await ensureSqlTables(this.execSql, keyingCheckpointTables);\n const updatedAt = this.now().toISOString();\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const acknowledge = (tx: ClientSQLiteTransactionScope) =>\n acknowledgeLocallyAuthoredHeadsInTransaction(tx, advance, updatedAt);\n if (advance.stillCurrent) {\n return (\n await runtime.guardedTransaction(acknowledge, advance.stillCurrent, {\n behavior: \"immediate\",\n })\n ).committed;\n }\n await runtime.transaction(acknowledge, { behavior: \"immediate\" });\n return true;\n }\n\n /** Seeds a replacement organization's genesis pins; false if superseded. */\n async persistOrganizationReplacementCheckpoints(input: {\n readonly authorization: VerifiedOrganizationReplacementAuthorization;\n readonly stillCurrent?: (() => boolean) | undefined;\n }): Promise<boolean> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const result = await runtime.guardedTransaction(\n (tx) =>\n seedOrganizationReplacementCheckpointsInTransaction(\n tx,\n input.authorization,\n this.now().toISOString(),\n ),\n input.stillCurrent ?? (() => true),\n { behavior: \"immediate\" },\n );\n return result.committed;\n }\n\n /**\n * Digests the verified bundles and ensures every table the batch touches,\n * all before its transaction begins.\n */\n private async prepareBatch(\n batch: KeyingCheckpointBatch,\n ): Promise<VerifiedManifestBundleRow[]> {\n const bundleRows = await verifiedManifestBundleRows(\n batch.verifiedBundles ?? [],\n );\n await ensureSqlTables(\n this.execSql,\n keyingCheckpointBatchTables(batch, bundleRows),\n );\n return bundleRows;\n }\n}\n"]}
1
+ {"version":3,"file":"keyingCheckpointRepository.js","sourceRoot":"","sources":["keyingCheckpointRepository.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAChG,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAEL,0BAA0B,EAC1B,yCAAyC,GAC1C,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EACL,qCAAqC,EAGrC,2BAA2B,EAC3B,sCAAsC,GACvC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,+BAA+B,EAC/B,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,4CAA4C,GAE7C,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,mDAAmD,EAAE,MAAM,gDAAgD,CAAC;AAErH;;;;;;GAMG;AACH,M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EAAE,CAC5B,CAAC;QACF,MAAM,eAAe,CACnB,IAAI,CAAC,OAAO,EACZ,2BAA2B,CAAC,KAAK,EAAE,UAAU,CAAC,CAC/C,CAAC;QACF,OAAO,UAAU,CAAC;IACpB,CAAC;CACF","sourcesContent":["import type {\n AccessManifestCheckpoint,\n AccessObjectKind,\n ManagedPrincipalKind,\n PrincipalPolicyCheckpoint,\n VerifiedOrganizationReplacementAuthorization,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport {\n documentPurgeCheckpoints,\n keyingCheckpointTables,\n} from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalPolicyTables } from \"../../sqlite/schema/principalPolicySchema\";\nimport { verifiedManifestBundleTables } from \"../../sqlite/schema/verifiedManifestBundleSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n type VerifiedManifestBundleRow,\n verifiedManifestBundleRows,\n writeVerifiedManifestBundlesInTransaction,\n} from \"../verifiedManifestBundlePersistence\";\nimport type { DocumentPurgeCheckpoint } from \"./documentPurgeCheckpointPersistence\";\nimport {\n advanceKeyingCheckpointsInTransaction,\n type KeyingCheckpointAdvanceBatch,\n type KeyingCheckpointBatch,\n keyingCheckpointBatchTables,\n validateKeyingCheckpointsInTransaction,\n} from \"./keyingCheckpointAdvancePersistence\";\nimport {\n loadAccessManifestCheckpointRow,\n loadPrincipalPolicyCheckpointRow,\n} from \"./keyingCheckpointPersistence\";\nimport {\n acknowledgeLocallyAuthoredHeadsInTransaction,\n type LocallyAcknowledgedAdvance,\n} from \"./locallyAcknowledgedCheckpointPersistence\";\nimport { seedOrganizationReplacementCheckpointsInTransaction } from \"./organizationReplacementCheckpointPersistence\";\n\n/**\n * The durable keying pins projection verification compares against: access\n * manifest, principal policy, and document purge checkpoints, bound to one\n * executor and clock. Each method ensures its tables and runs its own\n * immediate transaction. Work inside a caller's transaction takes the locked\n * handle per call through the `*InTransaction` functions instead.\n */\nexport class KeyingCheckpointRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n async loadAccessManifestCheckpoint(\n objectKind: AccessObjectKind,\n organizationId: string,\n objectId: string,\n ): Promise<AccessManifestCheckpoint | null> {\n await ensureSqlTables(this.execSql, keyingCheckpointTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const row = await loadAccessManifestCheckpointRow(db, {\n objectKind,\n organizationId,\n objectId,\n });\n return row ? { objectKind, objectId, organizationId, ...row } : null;\n }\n\n async loadPrincipalPolicyCheckpoint(\n principalType: ManagedPrincipalKind,\n principalId: string,\n ): Promise<PrincipalPolicyCheckpoint | null> {\n await ensureSqlTables(this.execSql, keyingCheckpointTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const row = await loadPrincipalPolicyCheckpointRow(db, {\n principalType,\n principalId,\n });\n return row ? { principalType, principalId, ...row } : null;\n }\n\n async loadDocumentPurgeCheckpoint(\n documentId: string,\n ): Promise<DocumentPurgeCheckpoint | null> {\n await ensureSqlTables(this.execSql, keyingCheckpointTables);\n const [row] = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({\n documentId: documentPurgeCheckpoints.documentId,\n documentManifestHash: documentPurgeCheckpoints.documentManifestHash,\n organizationId: documentPurgeCheckpoints.organizationId,\n purgeEventHash: documentPurgeCheckpoints.purgeEventHash,\n })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, documentId))\n .limit(1);\n return row ?? null;\n }\n\n /**\n * Re-checks verified candidates against durable pins without advancing\n * them; only the verified bundles' citation rows are written.\n */\n async validateKeyingCheckpointsAtomically(\n batch: KeyingCheckpointBatch,\n ): Promise<void> {\n const bundleRows = await this.prepareBatch(batch);\n const verifiedAt = this.now().toISOString();\n const validate = (tx: ClientSQLiteTransactionScope) =>\n validateKeyingCheckpointsInTransaction(tx, batch, bundleRows, verifiedAt);\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n if (batch.stillCurrent) {\n await runtime.guardedTransaction(validate, batch.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(validate, { behavior: \"immediate\" });\n }\n\n /** Advances the complete verified batch in one immediate transaction. */\n async advanceKeyingCheckpointsAtomically(\n batch: KeyingCheckpointAdvanceBatch,\n ): Promise<void> {\n const bundleRows = await this.prepareBatch(batch);\n const updatedAt = this.now().toISOString();\n const advance = (tx: ClientSQLiteTransactionScope) =>\n advanceKeyingCheckpointsInTransaction(tx, batch, bundleRows, updatedAt);\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n if (batch.stillCurrent) {\n await runtime.guardedTransaction(advance, batch.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(advance, { behavior: \"immediate\" });\n }\n\n /**\n * Whether the heads committed; false only when `stillCurrent` turned false.\n * A head's authored bundle, when its acknowledgement matched, is stored for\n * citation in the same transaction, so it commits only with its pin.\n */\n async advanceLocallyAcknowledgedAccessManifestHeadsAtomically(\n advance: LocallyAcknowledgedAdvance,\n ): Promise<boolean> {\n const bundleRows = await verifiedManifestBundleRows(\n advance.heads.flatMap(({ checkpoint, servedBundle }) =>\n servedBundle ? [{ bundle: servedBundle, checkpoint }] : [],\n ),\n );\n await ensureSqlTables(this.execSql, [\n ...keyingCheckpointTables,\n ...(bundleRows.length > 0 ? verifiedManifestBundleTables : []),\n ]);\n const updatedAt = this.now().toISOString();\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const acknowledge = async (tx: ClientSQLiteTransactionScope) => {\n await acknowledgeLocallyAuthoredHeadsInTransaction(\n tx,\n advance,\n updatedAt,\n );\n await writeVerifiedManifestBundlesInTransaction(\n tx,\n bundleRows,\n updatedAt,\n );\n };\n if (advance.stillCurrent) {\n return (\n await runtime.guardedTransaction(acknowledge, advance.stillCurrent, {\n behavior: \"immediate\",\n })\n ).committed;\n }\n await runtime.transaction(acknowledge, { behavior: \"immediate\" });\n return true;\n }\n\n /** Seeds a replacement organization's genesis pins; false if superseded. */\n async persistOrganizationReplacementCheckpoints(input: {\n readonly authorization: VerifiedOrganizationReplacementAuthorization;\n readonly stillCurrent?: (() => boolean) | undefined;\n }): Promise<boolean> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const result = await runtime.guardedTransaction(\n (tx) =>\n seedOrganizationReplacementCheckpointsInTransaction(\n tx,\n input.authorization,\n this.now().toISOString(),\n ),\n input.stillCurrent ?? (() => true),\n { behavior: \"immediate\" },\n );\n return result.committed;\n }\n\n /**\n * Digests the verified bundles and ensures every table the batch touches,\n * all before its transaction begins.\n */\n private async prepareBatch(\n batch: KeyingCheckpointBatch,\n ): Promise<VerifiedManifestBundleRow[]> {\n const bundleRows = await verifiedManifestBundleRows(\n batch.verifiedBundles ?? [],\n );\n await ensureSqlTables(\n this.execSql,\n keyingCheckpointBatchTables(batch, bundleRows),\n );\n return bundleRows;\n }\n}\n"]}
@@ -1,13 +1,26 @@
1
1
  import { type AccessManifest, type AccessManifestCheckpoint, type PrincipalPolicyCheckpoint } from "../../../internal/crypto/index.js";
2
+ import type { ServedAccessManifestBundleWireResponse } from "../../../internal/validators/util/index.js";
2
3
  import type { ClientSQLiteTransactionScope } from "../../sqlite/sqlitePersistenceRuntime.js";
4
+ import { type AuthoredManifestBundle } from "../verifiedCitations/authoredBundleCitation.js";
5
+ export type { AuthoredManifestBundle } from "../verifiedCitations/authoredBundleCitation.js";
3
6
  export interface LocallyAcknowledgedAccessManifestHead {
4
7
  readonly checkpoint: AccessManifestCheckpoint;
5
8
  readonly previousManifestHash: string | null;
9
+ /**
10
+ * The head's bundle as a projection serves it, when the acknowledgement's
11
+ * digest matched the plan; stored for citation with the checkpoint.
12
+ */
13
+ readonly servedBundle?: ServedAccessManifestBundleWireResponse | null;
6
14
  }
7
15
  export declare function locallyAuthoredAccessManifestHead(plan: {
8
16
  readonly manifest: AccessManifest;
9
17
  readonly manifestHash: string;
10
18
  }): LocallyAcknowledgedAccessManifestHead;
19
+ /**
20
+ * An authored head with its served bundle for citation, when the
21
+ * acknowledgement's digest names exactly the bundle the plan builds.
22
+ */
23
+ export declare function locallyAcknowledgedAuthoredHead(plan: AuthoredManifestBundle, bundleDigest: string): Promise<LocallyAcknowledgedAccessManifestHead>;
11
24
  /** Heads this client authored, with the pins its plan read. */
12
25
  export interface LocallyAcknowledgedAdvance {
13
26
  readonly heads: readonly LocallyAcknowledgedAccessManifestHead[];
@@ -1,4 +1,5 @@
1
1
  import { accessManifestCheckpointFromManifest, KeyingVerificationError, verifyAccessManifestLocalCheckpoint, } from "../../../internal/crypto/index.js";
2
+ import { acknowledgedAuthoredBundle, } from "../verifiedCitations/authoredBundleCitation.js";
2
3
  import { loadContainerRetirementCheck } from "../principalContracts/principalGrantRetirementPersistence.js";
3
4
  import { accessManifestObjectKey, loadAccessManifestCheckpointRows, loadPrincipalPolicyCheckpointRows, principalPolicyKey, storedPrincipalPolicyPin, upsertAccessManifestCheckpointsInTransaction, } from "./keyingCheckpointPersistence.js";
4
5
  export function locallyAuthoredAccessManifestHead(plan) {
@@ -10,6 +11,16 @@ export function locallyAuthoredAccessManifestHead(plan) {
10
11
  previousManifestHash: plan.manifest.previousManifestHash,
11
12
  };
12
13
  }
14
+ /**
15
+ * An authored head with its served bundle for citation, when the
16
+ * acknowledgement's digest names exactly the bundle the plan builds.
17
+ */
18
+ export async function locallyAcknowledgedAuthoredHead(plan, bundleDigest) {
19
+ return {
20
+ ...locallyAuthoredAccessManifestHead(plan),
21
+ servedBundle: await acknowledgedAuthoredBundle(plan, bundleDigest),
22
+ };
23
+ }
13
24
  function validateAcknowledgedHead(head, localCheckpoint) {
14
25
  if (!localCheckpoint) {
15
26
  if (head.checkpoint.epoch !== 1 || head.previousManifestHash !== null) {