@tearleads/client-sdk 0.1.58 → 0.1.60

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 (477) hide show
  1. package/Tearleads.d.ts +17 -17
  2. package/Tearleads.js +15 -15
  3. package/Tearleads.js.map +1 -1
  4. package/client/{blobs.d.ts → blobs/index.d.ts} +1 -1
  5. package/client/{blobs.js → blobs/index.js} +3 -3
  6. package/client/blobs/index.js.map +1 -0
  7. package/client/{containerDocumentDiscovery.js → containerContents/documentDiscovery.js} +11 -11
  8. package/client/containerContents/documentDiscovery.js.map +1 -0
  9. package/client/{containerContents.d.ts → containerContents/index.d.ts} +13 -13
  10. package/client/{containerContents.js → containerContents/index.js} +18 -18
  11. package/client/containerContents/index.js.map +1 -0
  12. package/client/{containerContentsTypes.d.ts → containerContents/types.d.ts} +14 -14
  13. package/client/containerContents/types.js +2 -0
  14. package/client/containerContents/types.js.map +1 -0
  15. package/client/{deviceFirst.d.ts → deviceFirst/index.d.ts} +7 -7
  16. package/client/{deviceFirst.js → deviceFirst/index.js} +11 -11
  17. package/client/deviceFirst/index.js.map +1 -0
  18. package/client/{reconciledDocumentContentPull.js → deviceFirst/reconciledDocumentContentPull.js} +1 -1
  19. package/client/deviceFirst/reconciledDocumentContentPull.js.map +1 -0
  20. package/client/{documents.d.ts → documents/index.d.ts} +5 -5
  21. package/client/{documents.js → documents/index.js} +5 -5
  22. package/client/documents/index.js.map +1 -0
  23. package/client/{identity.d.ts → identity/index.d.ts} +2 -2
  24. package/client/{identity.js → identity/index.js} +5 -5
  25. package/client/identity/index.js.map +1 -0
  26. package/client/{identityKeyPackage.d.ts → identity/keyPackage.d.ts} +1 -1
  27. package/client/{identityKeyPackage.js → identity/keyPackage.js} +4 -4
  28. package/client/identity/keyPackage.js.map +1 -0
  29. package/client/{userIdentities.d.ts → identity/userIdentities.d.ts} +2 -2
  30. package/client/{userIdentities.js → identity/userIdentities.js} +4 -4
  31. package/client/identity/userIdentities.js.map +1 -0
  32. package/client/index.d.ts +18 -18
  33. package/client/index.js +9 -9
  34. package/client/index.js.map +1 -1
  35. package/client/organizations/currentPrincipalMutations.js.map +1 -1
  36. package/client/organizations/index.d.ts +2 -2
  37. package/client/organizations/index.js.map +1 -1
  38. package/client/organizations/organizationAccessRestoration.js.map +1 -1
  39. package/client/organizations/organizationDataUsage.d.ts +1 -1
  40. package/client/organizations/organizationDataUsage.js.map +1 -1
  41. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  42. package/client/organizations/organizationGroupPresentation.d.ts +1 -1
  43. package/client/organizations/organizationGroupPresentation.js.map +1 -1
  44. package/client/organizations/organizationMetadataProfileSync.js +1 -1
  45. package/client/organizations/organizationMetadataProfileSync.js.map +1 -1
  46. package/client/organizations/organizationReadModels.d.ts +1 -1
  47. package/client/organizations/organizationReadModels.js.map +1 -1
  48. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  49. package/client/organizations/organizationsTypes.d.ts +1 -1
  50. package/client/organizations/organizationsTypes.js.map +1 -1
  51. package/client/organizations/principalContainerMutations.js.map +1 -1
  52. package/client/organizations/principalMutationRecovery.d.ts +1 -1
  53. package/client/organizations/principalMutationRecovery.js.map +1 -1
  54. package/client/organizations/principalMutationScope.js.map +1 -1
  55. package/client/organizations/principalMutations.d.ts +2 -2
  56. package/client/organizations/principalMutations.js.map +1 -1
  57. package/client/root/index.d.ts +1 -1
  58. package/client/root/index.js.map +1 -1
  59. package/client/{database.d.ts → runtime/database.d.ts} +1 -1
  60. package/client/{database.js → runtime/database.js} +1 -1
  61. package/client/runtime/database.js.map +1 -0
  62. package/client/{principalHistoryProtection.d.ts → runtime/principalHistoryProtection.d.ts} +1 -1
  63. package/client/{principalHistoryProtection.js → runtime/principalHistoryProtection.js} +2 -2
  64. package/client/runtime/principalHistoryProtection.js.map +1 -0
  65. package/client/{principalMutationApi.d.ts → runtime/principalMutationApi.d.ts} +4 -4
  66. package/client/{principalMutationApi.js → runtime/principalMutationApi.js} +2 -2
  67. package/client/runtime/principalMutationApi.js.map +1 -0
  68. package/client/{principalMutationDispatch.js → runtime/principalMutationDispatch.js} +2 -2
  69. package/client/runtime/principalMutationDispatch.js.map +1 -0
  70. package/client/runtime/rootContainerAdoption.js.map +1 -0
  71. package/client/{workflowRuntime.d.ts → runtime/workflowRuntime.d.ts} +12 -12
  72. package/client/{workflowRuntime.js → runtime/workflowRuntime.js} +5 -5
  73. package/client/runtime/workflowRuntime.js.map +1 -0
  74. package/client/{securityIncidents.d.ts → securityIncidents/index.d.ts} +3 -3
  75. package/client/{securityIncidents.js → securityIncidents/index.js} +5 -5
  76. package/client/securityIncidents/index.js.map +1 -0
  77. package/client/session/index.js +1 -1
  78. package/client/session/index.js.map +1 -1
  79. package/client/session/sessionIdentityTrust.d.ts +1 -1
  80. package/client/session/sessionLoginRefusal.js.map +1 -1
  81. package/client/session/sessionOrganizationCreation.js.map +1 -1
  82. package/client/session/sessionPurgeRecovery.js.map +1 -1
  83. package/client/session/sessionRootAuthority.js.map +1 -1
  84. package/client/session/sessionTypes.d.ts +3 -3
  85. package/client/session/sessionTypes.js.map +1 -1
  86. package/data/blobs/createBlobStore.d.ts +1 -1
  87. package/data/blobs/createBlobStore.js.map +1 -1
  88. package/data/blobs/encryptedBlobByteSource.js +1 -1
  89. package/data/blobs/encryptedBlobByteSource.js.map +1 -1
  90. package/data/blobs/encryptedBlobEnvelope.d.ts +1 -1
  91. package/data/blobs/encryptedBlobEnvelope.js +2 -2
  92. package/data/blobs/encryptedBlobEnvelope.js.map +1 -1
  93. package/data/blobs/encryptedBlobStore.d.ts +1 -1
  94. package/data/blobs/encryptedBlobStore.js +1 -1
  95. package/data/blobs/encryptedBlobStore.js.map +1 -1
  96. package/data/blobs/memoryBlobStore.d.ts +1 -1
  97. package/data/blobs/memoryBlobStore.js +1 -1
  98. package/data/blobs/memoryBlobStore.js.map +1 -1
  99. package/data/blobs/opfsBlobStore.d.ts +1 -1
  100. package/data/blobs/opfsBlobStore.js +1 -1
  101. package/data/blobs/opfsBlobStore.js.map +1 -1
  102. package/data/containers/containerMetadataDocument.js +1 -1
  103. package/data/containers/containerMetadataDocument.js.map +1 -1
  104. package/data/containers/shared/events.js +1 -1
  105. package/data/containers/shared/events.js.map +1 -1
  106. package/data/containers/shared/heldContainerHeads.js +1 -1
  107. package/data/containers/shared/heldContainerHeads.js.map +1 -1
  108. package/data/containers/shared/mutationAcknowledgement.js +1 -1
  109. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  110. package/data/containers/shared/principalPolicies.js +1 -1
  111. package/data/containers/shared/principalPolicies.js.map +1 -1
  112. package/data/containers/shared/readers.js +2 -2
  113. package/data/containers/shared/readers.js.map +1 -1
  114. package/data/documents/attachmentContentIdentity.js +1 -1
  115. package/data/documents/attachmentContentIdentity.js.map +1 -1
  116. package/data/documents/blob/shared/blobEnvelopeStream.js.map +1 -1
  117. package/data/documents/blob/shared/blobSourceSnapshot.d.ts +1 -1
  118. package/data/documents/blob/shared/blobSourceSnapshot.js.map +1 -1
  119. package/data/documents/blob/shared/chunkedBlobCrypto.js.map +1 -1
  120. package/data/documents/blob/shared/encryptedUploadParts.js.map +1 -1
  121. package/data/documents/blob/shared/events.js +1 -1
  122. package/data/documents/blob/shared/events.js.map +1 -1
  123. package/data/documents/blob/shared/types.d.ts +2 -2
  124. package/data/documents/blob/shared/types.js.map +1 -1
  125. package/data/documents/shared/containerKekPathHistory.js +1 -1
  126. package/data/documents/shared/containerKekPathHistory.js.map +1 -1
  127. package/data/documents/shared/containerKekPathVerification.d.ts +1 -1
  128. package/data/documents/shared/containerKekPathVerification.js +1 -1
  129. package/data/documents/shared/events.js +1 -1
  130. package/data/documents/shared/events.js.map +1 -1
  131. package/data/documents/shared/manifestBundleReaders.js +2 -2
  132. package/data/documents/shared/manifestBundleReaders.js.map +1 -1
  133. package/data/documents/shared/projection.d.ts +1 -1
  134. package/data/documents/shared/projection.js +2 -2
  135. package/data/documents/shared/projection.js.map +1 -1
  136. package/data/documents/shared/projectionContentKeys.d.ts +1 -1
  137. package/data/documents/shared/readers.js +3 -3
  138. package/data/documents/shared/readers.js.map +1 -1
  139. package/data/documents/shared/stableDocumentId.js +1 -1
  140. package/data/documents/shared/stableDocumentId.js.map +1 -1
  141. package/data/documents/shared/types.d.ts +1 -1
  142. package/data/documents/shared/types.js +1 -1
  143. package/data/{keyingCanonicalJson.js → keying/canonicalJson.js} +3 -3
  144. package/data/keying/canonicalJson.js.map +1 -0
  145. package/data/keyingProjectionVerification/bundleVerification.js +1 -1
  146. package/data/keyingProjectionVerification/bundleVerification.js.map +1 -1
  147. package/data/keyingProjectionVerification/containerAncestorCitations.js +1 -1
  148. package/data/keyingProjectionVerification/containerAncestorCitations.js.map +1 -1
  149. package/data/keyingProjectionVerification/containerManifestVerification.js +1 -1
  150. package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
  151. package/data/keyingProjectionVerification/documentManifestVerification.js +1 -1
  152. package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
  153. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js +1 -1
  154. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js.map +1 -1
  155. package/data/keyingProjectionVerification/error.js +1 -1
  156. package/data/keyingProjectionVerification/error.js.map +1 -1
  157. package/data/keyingProjectionVerification/index.d.ts +9 -0
  158. package/data/{keyingProjectionVerification.js → keyingProjectionVerification/index.js} +8 -8
  159. package/data/keyingProjectionVerification/index.js.map +1 -0
  160. package/data/keyingProjectionVerification/principalPolicyCache.js +1 -1
  161. package/data/keyingProjectionVerification/principalPolicyCache.js.map +1 -1
  162. package/data/keyingProjectionVerification/principalPolicyVerification.js +1 -1
  163. package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
  164. package/data/keyingProjectionVerification/readers.d.ts +1 -1
  165. package/data/keyingProjectionVerification/readers.js +3 -3
  166. package/data/keyingProjectionVerification/readers.js.map +1 -1
  167. package/data/keyingProjectionVerification/userKeyResolver.d.ts +1 -1
  168. package/data/keyingProjectionVerification/userKeyResolver.js.map +1 -1
  169. package/data/persistence/containers/containerPersistence.js +1 -1
  170. package/data/persistence/containers/containerPersistence.js.map +1 -1
  171. package/data/persistence/documents/documentDiscoveryCandidate.js +1 -1
  172. package/data/persistence/documents/documentDiscoveryCandidate.js.map +1 -1
  173. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +1 -1
  174. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  175. package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
  176. package/data/persistence/documents/internal/documentProjectionRows.js.map +1 -1
  177. package/data/persistence/documents/internal/documentRows.js +1 -1
  178. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  179. package/data/persistence/principalPolicyBundleIntegrity.js +1 -1
  180. package/data/persistence/principalPolicyBundleIntegrity.js.map +1 -1
  181. package/data/persistence/principalPolicyReferenceCheckpoint.js +1 -1
  182. package/data/persistence/principalPolicyReferenceCheckpoint.js.map +1 -1
  183. package/data/persistence/principalPolicyReferenceIndexPersistence.js +1 -1
  184. package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +1 -1
  185. package/data/persistence/principalPolicyReferencePersistence.js +1 -1
  186. package/data/persistence/principalPolicyReferencePersistence.js.map +1 -1
  187. package/data/persistence/securityIncidentPersistence.js.map +1 -1
  188. package/data/persistence/verifiedPrincipalPolicyBundle.js +1 -1
  189. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +1 -1
  190. package/data/persistence/verifiedPrincipalPolicyCurrent.js +1 -1
  191. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +1 -1
  192. package/data/principals/principalMutationJournal.js +1 -1
  193. package/data/principals/principalMutationJournal.js.map +1 -1
  194. package/data/{securityIncidents.d.ts → shared/securityIncidents.d.ts} +1 -1
  195. package/data/sqlite/documentRecordPersistence.js +1 -1
  196. package/data/sqlite/documentRecordPersistence.js.map +1 -1
  197. package/data/sync/crdtPeerSeed.d.ts +18 -0
  198. package/data/sync/originatedDocuments.d.ts +1 -1
  199. package/data/sync/originatedDocuments.js.map +1 -1
  200. package/data/sync/syncCoordinator.d.ts +1 -1
  201. package/data/sync/syncCoordinator.js.map +1 -1
  202. package/package.json +1 -1
  203. package/stores/container-contents/backgroundHydration.js +1 -1
  204. package/stores/container-contents/backgroundHydration.js.map +1 -1
  205. package/stores/container-contents/containerContentsStore.d.ts +1 -1
  206. package/stores/container-contents/containerContentsStore.js.map +1 -1
  207. package/stores/container-contents/localRefresh.js +1 -1
  208. package/stores/container-contents/localRefresh.js.map +1 -1
  209. package/stores/container-contents/remoteContainerIngestion.js +1 -1
  210. package/stores/container-contents/remoteContainerIngestion.js.map +1 -1
  211. package/stores/container-contents/remoteWriteQueue.js +1 -1
  212. package/stores/container-contents/remoteWriteQueue.js.map +1 -1
  213. package/stores/container-contents/systemContainerHydration.js +1 -1
  214. package/stores/container-contents/systemContainerHydration.js.map +1 -1
  215. package/stores/container-contents/utils.js +1 -1
  216. package/stores/container-contents/utils.js.map +1 -1
  217. package/stores/documents/documentStore/attachmentIntents.js +1 -1
  218. package/stores/documents/documentStore/attachmentIntents.js.map +1 -1
  219. package/stores/documents/documentStore/attachmentSourceUpload.js.map +1 -1
  220. package/stores/documents/documentStore/attachmentStaging.js +1 -1
  221. package/stores/documents/documentStore/attachmentStaging.js.map +1 -1
  222. package/stores/documents/documentStore/attachmentUploadLane.js.map +1 -1
  223. package/stores/documents/documentStore/persistence.js +2 -2
  224. package/stores/documents/documentStore/persistence.js.map +1 -1
  225. package/stores/documents/documentStore/state.js +1 -1
  226. package/stores/documents/documentStore/state.js.map +1 -1
  227. package/stores/documents/documentStore/storedDocument.js +1 -1
  228. package/stores/documents/documentStore/storedDocument.js.map +1 -1
  229. package/stores/documents/documentStore/syncAttachments.js.map +1 -1
  230. package/stores/documents/documentStore.d.ts +1 -1
  231. package/stores/documents/documentStore.js.map +1 -1
  232. package/stores/documents/registry.d.ts +1 -1
  233. package/stores/documents/registry.js.map +1 -1
  234. package/stores/documents/types.d.ts +1 -1
  235. package/stores/documents/types.js.map +1 -1
  236. package/stores/local-projection/registry.d.ts +1 -1
  237. package/stores/local-projection/registry.js.map +1 -1
  238. package/sync/reconciliation/serviceTypes.d.ts +1 -1
  239. package/sync/reconciliation/serviceTypes.js.map +1 -1
  240. package/sync/reconciliation/triggers.d.ts +1 -1
  241. package/sync/reconciliation/triggers.js.map +1 -1
  242. package/workflows/blobs/attachmentBindingVerification.js +2 -2
  243. package/workflows/blobs/attachmentBindingVerification.js.map +1 -1
  244. package/workflows/blobs/blobChunkDecryption.js.map +1 -1
  245. package/workflows/blobs/decrypt.d.ts +1 -1
  246. package/workflows/blobs/decrypt.js +2 -2
  247. package/workflows/blobs/decrypt.js.map +1 -1
  248. package/workflows/blobs/detach.js +2 -2
  249. package/workflows/blobs/detach.js.map +1 -1
  250. package/workflows/blobs/hydrate.d.ts +3 -3
  251. package/workflows/blobs/hydrate.js +1 -1
  252. package/workflows/blobs/hydrate.js.map +1 -1
  253. package/workflows/blobs/hydrationResults.js.map +1 -1
  254. package/workflows/blobs/index.d.ts +2 -2
  255. package/workflows/blobs/index.js +1 -1
  256. package/workflows/blobs/index.js.map +1 -1
  257. package/workflows/blobs/multipartFirstParts.js.map +1 -1
  258. package/workflows/blobs/retainedAttachmentVerification.js +1 -1
  259. package/workflows/blobs/upload.js +3 -3
  260. package/workflows/blobs/upload.js.map +1 -1
  261. package/workflows/container-contents/container-state/createAdoption.js +1 -1
  262. package/workflows/container-contents/container-state/createAdoption.js.map +1 -1
  263. package/workflows/container-contents/container-state/createChild.js +1 -1
  264. package/workflows/container-contents/container-state/createChild.js.map +1 -1
  265. package/workflows/container-contents/container-state/createIntentSync.js +1 -1
  266. package/workflows/container-contents/container-state/createIntentSync.js.map +1 -1
  267. package/workflows/container-contents/container-state/groupGrantVerification.js +1 -1
  268. package/workflows/container-contents/container-state/moveIntentSync.js +1 -1
  269. package/workflows/container-contents/container-state/moveIntentSync.js.map +1 -1
  270. package/workflows/container-contents/container-state/purgeTreeScope.js +1 -1
  271. package/workflows/container-contents/container-state/purgeTreeScope.js.map +1 -1
  272. package/workflows/container-contents/container-state/share.js +1 -1
  273. package/workflows/container-contents/documentDiscoveryInputs.js +1 -1
  274. package/workflows/container-contents/documentDiscoveryInputs.js.map +1 -1
  275. package/workflows/container-contents/documentInfo.d.ts +1 -1
  276. package/workflows/container-contents/documentInfo.js.map +1 -1
  277. package/workflows/container-contents/documentLinks.d.ts +1 -1
  278. package/workflows/container-contents/documentLinks.js +1 -1
  279. package/workflows/container-contents/documentLinks.js.map +1 -1
  280. package/workflows/container-contents/documentMoveIntentSync.js +1 -1
  281. package/workflows/container-contents/documentMoveIntentSync.js.map +1 -1
  282. package/workflows/container-contents/documentPurge.d.ts +1 -1
  283. package/workflows/container-contents/documentPurge.js +1 -1
  284. package/workflows/container-contents/documentPurge.js.map +1 -1
  285. package/workflows/container-contents/documentQueries/rows.js +1 -1
  286. package/workflows/container-contents/documentQueries/rows.js.map +1 -1
  287. package/workflows/container-contents/metadata.d.ts +1 -1
  288. package/workflows/container-contents/metadataMutationPreparation.js +1 -1
  289. package/workflows/container-contents/metadataMutationPreparation.js.map +1 -1
  290. package/workflows/container-contents/metadataRemoteSync.d.ts +1 -1
  291. package/workflows/container-contents/metadataSyncErrors.js.map +1 -1
  292. package/workflows/container-contents/projectionKeys.d.ts +1 -1
  293. package/workflows/container-contents/syncLane.d.ts +1 -1
  294. package/workflows/container-contents/syncLane.js.map +1 -1
  295. package/workflows/containers/child/carriedDescendantRekeys.js +1 -1
  296. package/workflows/containers/child/create.d.ts +1 -1
  297. package/workflows/containers/child/create.js +2 -2
  298. package/workflows/containers/child/create.js.map +1 -1
  299. package/workflows/containers/child/createProjection.js +1 -1
  300. package/workflows/containers/child/createProjection.js.map +1 -1
  301. package/workflows/containers/child/createSubmission.d.ts +2 -2
  302. package/workflows/containers/child/createSubmission.js.map +1 -1
  303. package/workflows/containers/child/move.d.ts +2 -2
  304. package/workflows/containers/child/move.js +2 -2
  305. package/workflows/containers/child/move.js.map +1 -1
  306. package/workflows/containers/child/moveWraps.js +1 -1
  307. package/workflows/containers/child/mutationRequestCore.js +1 -1
  308. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  309. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  310. package/workflows/containers/child/recite.js.map +1 -1
  311. package/workflows/containers/child/recitePlan.js +1 -1
  312. package/workflows/containers/child/recitePlan.js.map +1 -1
  313. package/workflows/containers/child/rekey.d.ts +1 -1
  314. package/workflows/containers/child/rekey.js +2 -2
  315. package/workflows/containers/child/rekey.js.map +1 -1
  316. package/workflows/containers/child/rekeyProjection.js +1 -1
  317. package/workflows/containers/child/rekeyProjection.js.map +1 -1
  318. package/workflows/containers/child/rekeyRemote.d.ts +2 -2
  319. package/workflows/containers/child/rekeyRemote.js.map +1 -1
  320. package/workflows/containers/child/revoke.d.ts +2 -2
  321. package/workflows/containers/child/revoke.js +2 -2
  322. package/workflows/containers/child/revoke.js.map +1 -1
  323. package/workflows/containers/child/rotationPrincipalPolicies.js +1 -1
  324. package/workflows/containers/child/runtimeCurrentGroupShare.js +1 -1
  325. package/workflows/containers/child/share.d.ts +2 -2
  326. package/workflows/containers/child/share.js +1 -1
  327. package/workflows/containers/child/share.js.map +1 -1
  328. package/workflows/containers/child/shareAncestorRepair.js.map +1 -1
  329. package/workflows/containers/child/shareMaterialization.d.ts +1 -1
  330. package/workflows/containers/child/sharePlanCore.d.ts +1 -1
  331. package/workflows/containers/child/sharePlanCore.js +1 -1
  332. package/workflows/containers/root/create.js +1 -1
  333. package/workflows/containers/root/create.js.map +1 -1
  334. package/workflows/containers/root/initialGroupPolicy.js +1 -1
  335. package/workflows/containers/root/initialGroupPolicy.js.map +1 -1
  336. package/workflows/documents/create.d.ts +1 -1
  337. package/workflows/documents/create.js +1 -1
  338. package/workflows/documents/documentMutationPreparation.js +1 -1
  339. package/workflows/documents/documentMutationPreparation.js.map +1 -1
  340. package/workflows/documents/historyContent.js +1 -1
  341. package/workflows/documents/historyContent.js.map +1 -1
  342. package/workflows/documents/linkSet.js +1 -1
  343. package/workflows/documents/linkSet.js.map +1 -1
  344. package/workflows/documents/linkSetAuthority.js +1 -1
  345. package/workflows/documents/linkSetBlobRewraps.js +2 -2
  346. package/workflows/documents/linkSetBlobRewraps.js.map +1 -1
  347. package/workflows/documents/linkSetRemote.d.ts +1 -1
  348. package/workflows/documents/linkSetRemote.js +1 -1
  349. package/workflows/documents/orphanBlobReclaims.js +1 -1
  350. package/workflows/documents/orphanBlobReclaims.js.map +1 -1
  351. package/workflows/documents/projectionKeys.d.ts +1 -1
  352. package/workflows/documents/purge.d.ts +1 -1
  353. package/workflows/documents/purge.js +2 -2
  354. package/workflows/documents/purge.js.map +1 -1
  355. package/workflows/documents/readOnlySync.d.ts +1 -1
  356. package/workflows/documents/readOnlySync.js +1 -1
  357. package/workflows/documents/readOnlySync.js.map +1 -1
  358. package/workflows/documents/sync.js +1 -1
  359. package/workflows/documents/syncContainerRekeyPreparation.js +1 -1
  360. package/workflows/documents/syncLane.d.ts +1 -1
  361. package/workflows/documents/syncLane.js.map +1 -1
  362. package/workflows/documents/syncPlanIdentity.js +1 -1
  363. package/workflows/documents/syncPlanIdentity.js.map +1 -1
  364. package/workflows/documents/syncRepairAccess.js +1 -1
  365. package/workflows/documents/syncSubmittedResult.js +1 -1
  366. package/workflows/organizations/authoredPrincipalPolicyWarmer.js +1 -1
  367. package/workflows/organizations/authoredPrincipalPolicyWarmer.js.map +1 -1
  368. package/workflows/organizations/containerGrantRevocation.d.ts +2 -2
  369. package/workflows/organizations/containerGrantRevocation.js.map +1 -1
  370. package/workflows/organizations/createCurrentOrganizationGroup.js.map +1 -1
  371. package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -1
  372. package/workflows/organizations/currentPolicyMutationAcknowledgement.js +1 -1
  373. package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +1 -1
  374. package/workflows/organizations/groupCreation.d.ts +1 -1
  375. package/workflows/organizations/groupCreation.js.map +1 -1
  376. package/workflows/organizations/groupMetadataAccess.d.ts +1 -1
  377. package/workflows/organizations/groupMetadataContainerAuthority.js.map +1 -1
  378. package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
  379. package/workflows/organizations/groupNameUniqueness.js.map +1 -1
  380. package/workflows/organizations/groupPolicyMutationAcknowledgement.js +1 -1
  381. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
  382. package/workflows/organizations/groupPolicyRequests.js.map +1 -1
  383. package/workflows/organizations/loadPolicyHistoryDetails.js.map +1 -1
  384. package/workflows/organizations/organizationGroupDirectory.js.map +1 -1
  385. package/workflows/organizations/organizationProfile.js +1 -1
  386. package/workflows/organizations/organizationProfile.js.map +1 -1
  387. package/workflows/organizations/policyHistoryCache.js.map +1 -1
  388. package/workflows/organizations/principalContainerRematerialization.js +1 -1
  389. package/workflows/organizations/principalContainerRematerializationPlanning.js.map +1 -1
  390. package/workflows/organizations/principalMutationJournalManagement.js +1 -1
  391. package/workflows/organizations/principalMutationJournalManagement.js.map +1 -1
  392. package/workflows/organizations/principalMutationReceipt.js +1 -1
  393. package/workflows/organizations/principalMutationReceipt.js.map +1 -1
  394. package/workflows/organizations/principalPolicy.d.ts +1 -1
  395. package/workflows/organizations/principalPolicy.js.map +1 -1
  396. package/workflows/organizations/principalPolicyReceiptArtifacts.js +1 -1
  397. package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +1 -1
  398. package/workflows/organizations/rosterProfileContainer.js +1 -1
  399. package/workflows/organizations/rosterProfileContainer.js.map +1 -1
  400. package/workflows/principals/policyCache.d.ts +1 -1
  401. package/workflows/principals/policyCache.js +2 -2
  402. package/workflows/principals/policyCache.js.map +1 -1
  403. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  404. package/workflows/principals/runtimePolicyWarmer.js +1 -1
  405. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
  406. package/workflows/registration/persistRegistrationBootstrap.js +1 -1
  407. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  408. package/workflows/runtimeInput.d.ts +3 -3
  409. package/workflows/runtimeInput.js.map +1 -1
  410. package/workflows/sync/index.d.ts +2 -1
  411. package/workflows/sync/index.js +2 -1
  412. package/workflows/sync/index.js.map +1 -1
  413. package/client/blobs.js.map +0 -1
  414. package/client/containerContents.js.map +0 -1
  415. package/client/containerContentsTypes.js +0 -2
  416. package/client/containerContentsTypes.js.map +0 -1
  417. package/client/containerDocumentDiscovery.js.map +0 -1
  418. package/client/database.js.map +0 -1
  419. package/client/deviceFirst.js.map +0 -1
  420. package/client/documents.js.map +0 -1
  421. package/client/identity.js.map +0 -1
  422. package/client/identityKeyPackage.js.map +0 -1
  423. package/client/principalHistoryProtection.js.map +0 -1
  424. package/client/principalMutationApi.js.map +0 -1
  425. package/client/principalMutationDispatch.js.map +0 -1
  426. package/client/reconciledDocumentContentPull.js.map +0 -1
  427. package/client/rootContainerAdoption.js.map +0 -1
  428. package/client/securityIncidents.js.map +0 -1
  429. package/client/userIdentities.js.map +0 -1
  430. package/client/workflowRuntime.js.map +0 -1
  431. package/data/keyingCanonicalJson.js.map +0 -1
  432. package/data/keyingProjectionVerification.d.ts +0 -9
  433. package/data/keyingProjectionVerification.js.map +0 -1
  434. /package/client/{fileSaver.d.ts → host/fileSaver.d.ts} +0 -0
  435. /package/client/{fileSaver.js → host/fileSaver.js} +0 -0
  436. /package/client/{fileSaver.js.map → host/fileSaver.js.map} +0 -0
  437. /package/client/{logger.d.ts → host/logger.d.ts} +0 -0
  438. /package/client/{logger.js → host/logger.js} +0 -0
  439. /package/client/{logger.js.map → host/logger.js.map} +0 -0
  440. /package/client/{apiVersion.d.ts → runtime/apiVersion.d.ts} +0 -0
  441. /package/client/{apiVersion.js → runtime/apiVersion.js} +0 -0
  442. /package/client/{apiVersion.js.map → runtime/apiVersion.js.map} +0 -0
  443. /package/client/{events.d.ts → runtime/events.d.ts} +0 -0
  444. /package/client/{events.js → runtime/events.js} +0 -0
  445. /package/client/{events.js.map → runtime/events.js.map} +0 -0
  446. /package/client/{listenerSet.js → runtime/listenerSet.js} +0 -0
  447. /package/client/{listenerSet.js.map → runtime/listenerSet.js.map} +0 -0
  448. /package/client/{network.d.ts → runtime/network.d.ts} +0 -0
  449. /package/client/{network.js → runtime/network.js} +0 -0
  450. /package/client/{network.js.map → runtime/network.js.map} +0 -0
  451. /package/client/{principalMutationDeadline.js → runtime/principalMutationDeadline.js} +0 -0
  452. /package/client/{principalMutationDeadline.js.map → runtime/principalMutationDeadline.js.map} +0 -0
  453. /package/client/{rootContainerAdoption.js → runtime/rootContainerAdoption.js} +0 -0
  454. /package/client/{syncBillingGate.d.ts → runtime/syncBillingGate.d.ts} +0 -0
  455. /package/client/{syncBillingGate.js → runtime/syncBillingGate.js} +0 -0
  456. /package/client/{syncBillingGate.js.map → runtime/syncBillingGate.js.map} +0 -0
  457. /package/data/{blobContracts.d.ts → blobs/blobContracts.d.ts} +0 -0
  458. /package/data/{blobContracts.js → blobs/blobContracts.js} +0 -0
  459. /package/data/{blobContracts.js.map → blobs/blobContracts.js.map} +0 -0
  460. /package/data/{accessLevel.js → keying/accessLevel.js} +0 -0
  461. /package/data/{accessLevel.js.map → keying/accessLevel.js.map} +0 -0
  462. /package/data/{stableUuid.js → keying/stableUuid.js} +0 -0
  463. /package/data/{stableUuid.js.map → keying/stableUuid.js.map} +0 -0
  464. /package/data/{principalPolicyStates.js → principals/principalPolicyStates.js} +0 -0
  465. /package/data/{principalPolicyStates.js.map → principals/principalPolicyStates.js.map} +0 -0
  466. /package/data/{domainScope.d.ts → shared/domainScope.d.ts} +0 -0
  467. /package/data/{domainScope.js → shared/domainScope.js} +0 -0
  468. /package/data/{domainScope.js.map → shared/domainScope.js.map} +0 -0
  469. /package/data/{errorMessage.js → shared/errorMessage.js} +0 -0
  470. /package/data/{errorMessage.js.map → shared/errorMessage.js.map} +0 -0
  471. /package/data/{recordReaders.d.ts → shared/recordReaders.d.ts} +0 -0
  472. /package/data/{recordReaders.js → shared/recordReaders.js} +0 -0
  473. /package/data/{recordReaders.js.map → shared/recordReaders.js.map} +0 -0
  474. /package/data/{securityIncidents.js → shared/securityIncidents.js} +0 -0
  475. /package/data/{securityIncidents.js.map → shared/securityIncidents.js.map} +0 -0
  476. /package/data/{crdtPeerSeed.js → sync/crdtPeerSeed.js} +0 -0
  477. /package/data/{crdtPeerSeed.js.map → sync/crdtPeerSeed.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeInput.js","sourceRoot":"","sources":["runtimeInput.ts"],"names":[],"mappings":"","sourcesContent":["import type { EncapsulationKeyPair, SigningKeyPair } from \"@tearleads/crypto\";\nimport type { BlobStore } from \"../data/blobContracts\";\nimport type { DocumentProjectorRegistry } from \"../data/documents/documentKinds\";\nimport type { DomainScope } from \"../data/domainScope\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport type { ExecSql } from \"../data/sqlite/sqlSchema\";\n\nexport type WorkflowRuntimeDatabaseStatus =\n | \"idle\"\n | \"ready\"\n | \"error\"\n | \"terminated\";\n\nexport interface WorkflowRuntimeAuthInput {\n /** Server-backed personal organization; independent of organizationId. */\n readonly defaultOrganizationId?: string | null;\n /** Session root identity, independent of a document/pane target. */\n readonly rootContainerId?: string | null | undefined;\n readonly isAuthenticated: boolean;\n /** Platform-operator flag from the server; the API enforces root access. */\n readonly isRoot?: boolean | undefined;\n readonly organizationId: string | null;\n readonly userId: string | null;\n}\n\nexport interface WorkflowRuntimeCryptoInput {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n readonly signingFingerprint: string | null;\n readonly signingKeyPair: SigningKeyPair | null;\n}\n\nexport interface WorkflowRuntimeStateInput {\n readonly containerId: string | null;\n readonly domainScope: DomainScope;\n readonly events: ReadonlyArray<unknown>;\n readonly online: boolean;\n /**\n * Increments after each acknowledged server-events interest declaration.\n * Unlike a boolean connection edge, this survives coalesced runtime\n * notifications and document stores retained while their host provider is\n * unmounted.\n */\n readonly serverEventsConnectionGeneration?: number | undefined;\n /**\n * Per-pane CRDT peer-seed discriminator (e.g. the pane's local identity\n * namespace). Documents in distinct panes must derive distinct Loro peer ids;\n * absent/`null` means single-pane (bare scope). The document runtime factory\n * always populates it; other runtimes and test fixtures may omit it.\n */\n readonly peerScope?: string | null;\n}\n\nexport interface WorkflowRuntimeInfraInput {\n readonly blobStore: BlobStore;\n readonly dbStatus: WorkflowRuntimeDatabaseStatus;\n readonly documentProjectors: DocumentProjectorRegistry;\n readonly execSql: ExecSql;\n}\n\nexport interface WorkflowRuntimeUtilInput {\n readonly isRemoteSyncBlocked?:\n | ((organizationId: string) => boolean)\n | undefined;\n readonly log: (message: string) => void;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n}\n\nexport interface WorkflowRuntimeGroups {\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: WorkflowRuntimeCryptoInput;\n readonly infra: WorkflowRuntimeInfraInput;\n readonly state: WorkflowRuntimeStateInput;\n readonly util: WorkflowRuntimeUtilInput;\n}\n"]}
1
+ {"version":3,"file":"runtimeInput.js","sourceRoot":"","sources":["runtimeInput.ts"],"names":[],"mappings":"","sourcesContent":["import type { EncapsulationKeyPair, SigningKeyPair } from \"@tearleads/crypto\";\nimport type { BlobStore } from \"../data/blobs/blobContracts\";\nimport type { DocumentProjectorRegistry } from \"../data/documents/documentKinds\";\nimport type { DomainScope } from \"../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../data/sqlite/sqlSchema\";\n\nexport type WorkflowRuntimeDatabaseStatus =\n | \"idle\"\n | \"ready\"\n | \"error\"\n | \"terminated\";\n\nexport interface WorkflowRuntimeAuthInput {\n /** Server-backed personal organization; independent of organizationId. */\n readonly defaultOrganizationId?: string | null;\n /** Session root identity, independent of a document/pane target. */\n readonly rootContainerId?: string | null | undefined;\n readonly isAuthenticated: boolean;\n /** Platform-operator flag from the server; the API enforces root access. */\n readonly isRoot?: boolean | undefined;\n readonly organizationId: string | null;\n readonly userId: string | null;\n}\n\nexport interface WorkflowRuntimeCryptoInput {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n readonly signingFingerprint: string | null;\n readonly signingKeyPair: SigningKeyPair | null;\n}\n\nexport interface WorkflowRuntimeStateInput {\n readonly containerId: string | null;\n readonly domainScope: DomainScope;\n readonly events: ReadonlyArray<unknown>;\n readonly online: boolean;\n /**\n * Increments after each acknowledged server-events interest declaration.\n * Unlike a boolean connection edge, this survives coalesced runtime\n * notifications and document stores retained while their host provider is\n * unmounted.\n */\n readonly serverEventsConnectionGeneration?: number | undefined;\n /**\n * Per-pane CRDT peer-seed discriminator (e.g. the pane's local identity\n * namespace). Documents in distinct panes must derive distinct Loro peer ids;\n * absent/`null` means single-pane (bare scope). The document runtime factory\n * always populates it; other runtimes and test fixtures may omit it.\n */\n readonly peerScope?: string | null;\n}\n\nexport interface WorkflowRuntimeInfraInput {\n readonly blobStore: BlobStore;\n readonly dbStatus: WorkflowRuntimeDatabaseStatus;\n readonly documentProjectors: DocumentProjectorRegistry;\n readonly execSql: ExecSql;\n}\n\nexport interface WorkflowRuntimeUtilInput {\n readonly isRemoteSyncBlocked?:\n | ((organizationId: string) => boolean)\n | undefined;\n readonly log: (message: string) => void;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n}\n\nexport interface WorkflowRuntimeGroups {\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: WorkflowRuntimeCryptoInput;\n readonly infra: WorkflowRuntimeInfraInput;\n readonly state: WorkflowRuntimeStateInput;\n readonly util: WorkflowRuntimeUtilInput;\n}\n"]}
@@ -1,4 +1,5 @@
1
- export { createDomainScope, type DomainScope, } from "../../data/domainScope.js";
1
+ export { createDomainScope, type DomainScope, } from "../../data/shared/domainScope.js";
2
+ export { getRuntimePeerSeed } from "../../data/sync/crdtPeerSeed.js";
2
3
  export { markOriginatedDocuments } from "../../data/sync/originatedDocuments.js";
3
4
  export type { DomainSyncCoordinator, DomainSyncSnapshot, SyncIdleOptions, SyncLane, SyncLaneConfig, SyncLaneLastAction, SyncLanePhase, SyncLaneProgress, SyncLaneSnapshot, SyncLaneStatus, UploadSyncLane, UploadSyncLaneOptions, } from "../../data/sync/syncCoordinator.js";
4
5
  export { beginDomainSyncUploadLane, getDomainSyncCoordinatorSnapshot, getOrCreateDomainSyncCoordinator, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../data/sync/syncCoordinator.js";
@@ -1,4 +1,5 @@
1
- export { createDomainScope, } from "../../data/domainScope.js";
1
+ export { createDomainScope, } from "../../data/shared/domainScope.js";
2
+ export { getRuntimePeerSeed } from "../../data/sync/crdtPeerSeed.js";
2
3
  export { markOriginatedDocuments } from "../../data/sync/originatedDocuments.js";
3
4
  export { beginDomainSyncUploadLane, getDomainSyncCoordinatorSnapshot, getOrCreateDomainSyncCoordinator, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../data/sync/syncCoordinator.js";
4
5
  export { clearRemoteSyncState, } from "./remoteReset.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,GAElB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAe9E,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,oBAAoB,GAGrB,MAAM,eAAe,CAAC","sourcesContent":["export {\n createDomainScope,\n type DomainScope,\n} from \"../../data/domainScope\";\nexport { markOriginatedDocuments } from \"../../data/sync/originatedDocuments\";\nexport type {\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneProgress,\n SyncLaneSnapshot,\n SyncLaneStatus,\n UploadSyncLane,\n UploadSyncLaneOptions,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n beginDomainSyncUploadLane,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n type ClearRemoteSyncStateResult,\n clearRemoteSyncState,\n type RemoteResetInput,\n type RemoteResetReplacement,\n} from \"./remoteReset\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,GAElB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAe9E,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,oBAAoB,GAGrB,MAAM,eAAe,CAAC","sourcesContent":["export {\n createDomainScope,\n type DomainScope,\n} from \"../../data/shared/domainScope\";\nexport { getRuntimePeerSeed } from \"../../data/sync/crdtPeerSeed\";\nexport { markOriginatedDocuments } from \"../../data/sync/originatedDocuments\";\nexport type {\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneProgress,\n SyncLaneSnapshot,\n SyncLaneStatus,\n UploadSyncLane,\n UploadSyncLaneOptions,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n beginDomainSyncUploadLane,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n type ClearRemoteSyncStateResult,\n clearRemoteSyncState,\n type RemoteResetInput,\n type RemoteResetReplacement,\n} from \"./remoteReset\";\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"blobs.js","sourceRoot":"","sources":["blobs.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAItE,MAAM,OAAO,KAAK;IACC,cAAc,GAAG,qBAAqB,EAAE,CAAC;IAClD,cAAc,GAAG,KAAK,CAAC;IACd,mBAAmB,CAAmB;IAC/C,UAAU,CAAY;IAE9B,YACE,KAA6B,EAC7B,sBAAwC,eAAe;QAEvD,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;QAC/C,IAAI,CAAC,UAAU,GAAG,KAAK,IAAI,IAAI,CAAC,cAAc,CAAC;IACjD,CAAC;IAED,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAED,iBAAiB;QACf,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;QAC5B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,cAAc,CAAC;IACxC,CAAC;IAED,oBAAoB,CAAC,kBAA0B;QAC7C,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC3B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,mBAAmB,CAAC,kBAAkB,CAAC,CAAC;IACjE,CAAC;IAED,uBAAuB,CAAC,kBAAiC;QACvD,IAAI,IAAI,CAAC,cAAc,IAAI,IAAI,CAAC,UAAU,KAAK,IAAI,CAAC,cAAc,EAAE,CAAC;YACnE,IAAI,kBAAkB,EAAE,CAAC;gBACvB,IAAI,CAAC,oBAAoB,CAAC,kBAAkB,CAAC,CAAC;gBAC9C,OAAO;YACT,CAAC;YAED,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAC3B,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { BlobStore } from \"../data/blobContracts\";\nimport { createBlobStore } from \"../data/blobs/createBlobStore\";\nimport { createMemoryBlobStore } from \"../data/blobs/memoryBlobStore\";\n\nexport type BlobStoreFactory = (namespace: string) => BlobStore;\n\nexport class Blobs {\n private readonly ephemeralStore = createMemoryBlobStore();\n private identityScoped = false;\n private readonly createIdentityStore: BlobStoreFactory;\n private storeValue: BlobStore;\n\n constructor(\n store?: BlobStore | undefined,\n createIdentityStore: BlobStoreFactory = createBlobStore,\n ) {\n this.createIdentityStore = createIdentityStore;\n this.storeValue = store ?? this.ephemeralStore;\n }\n\n get store(): BlobStore {\n return this.storeValue;\n }\n\n useEphemeralStore(): void {\n this.identityScoped = false;\n this.storeValue = this.ephemeralStore;\n }\n\n useIdentityNamespace(signingFingerprint: string): void {\n this.identityScoped = true;\n this.storeValue = this.createIdentityStore(signingFingerprint);\n }\n\n updateIdentityNamespace(signingFingerprint: string | null): void {\n if (this.identityScoped || this.storeValue === this.ephemeralStore) {\n if (signingFingerprint) {\n this.useIdentityNamespace(signingFingerprint);\n return;\n }\n\n this.useEphemeralStore();\n }\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"containerContents.js","sourceRoot":"","sources":["containerContents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAE5E,OAAO,EAAE,iCAAiC,EAAE,MAAM,4CAA4C,CAAC;AAC/F,OAAO,EAGL,iCAAiC,GAClC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAA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} from \"../data/documents/documentConstants\";\nimport type { DocumentSummary } from \"../data/documents/documentSummary\";\nimport { inheritPrincipalHistoryProtection } from \"../data/principals/principalHistoryRuntime\";\nimport {\n type ContainerContentsStore,\n type ContainerContentsStoreOptions,\n getOrCreateContainerContentsStore,\n} from \"../stores/container-contents\";\nimport { openDocumentStore } from \"../stores/documents\";\nimport { relinkDocumentStoreWithCommitSideEffect } from \"../stores/documents/documentStore/internalRelink\";\nimport {\n type BlobInfoInput,\n type BlobInfoList,\n listBlobInfo,\n} from \"../workflows/container-contents/blobInfo\";\nimport {\n type ContainerInfo,\n loadContainerInfo,\n} from \"../workflows/container-contents/containerInfo\";\nimport {\n type DocumentAttributionRangesInput,\n type DocumentAttributionRangesPage,\n loadDocumentAttributionRanges,\n} from \"../workflows/container-contents/documentAttributionRanges\";\nimport {\n type DocumentInfo,\n loadDocumentInfo,\n} from \"../workflows/container-contents/documentInfo\";\nimport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"../workflows/container-contents/documentPurge\";\nimport {\n type ContainerDocumentQueries,\n createContainerDocumentQueriesFromRuntime,\n} from \"../workflows/container-contents/documentQueries\";\nimport {\n activateDocumentLink,\n addDocumentLink,\n canMutateDocumentLink,\n canMutateLocalDocumentLink,\n type DocumentStructuralMutationHost,\n moveDocumentLink,\n removeDocumentLink,\n} from \"../workflows/container-contents/documentStructure\";\nimport { createContainerContentsDocumentProjectionUserKeyResolver } from \"../workflows/container-contents/projectionKeys\";\nimport {\n type ContainerContentsStoreWorkflowRuntime,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n} from \"../workflows/container-contents/runtime\";\nimport { createContainerDocumentObjectSyncState } from \"../workflows/container-contents/syncState\";\nimport type { DocumentsWorkflowRuntime } from \"../workflows/documents\";\nimport type {\n ContainerContents,\n ContainerDocumentLinks,\n ContainerInfoInput,\n DocumentInfoInput,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n OpenContainerDocumentInput,\n} from \"./containerContentsTypes\";\nimport { discoverContainerDocumentsForRuntime } from \"./containerDocumentDiscovery\";\nimport {\n createOrganizationReadModelCoordinator,\n type OrganizationReadModelCoordinator,\n} from \"./organizations/organizationReadModels\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"./workflowRuntime\";\n\nexport type {\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerNode,\n} from \"../stores/container-contents\";\nexport type {\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n} from \"../workflows/container-contents/blobInfo\";\nexport type {\n ContainerInfo,\n ContainerShareAccessLevel,\n} from \"../workflows/container-contents/containerInfo\";\nexport type {\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n} from \"../workflows/container-contents/documentAttributionRanges\";\nexport type { DocumentInfo } from \"../workflows/container-contents/documentInfo\";\nexport type {\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n} from \"../workflows/container-contents/documentQueries\";\nexport type { SetLinkedContainerIdsForDocument } from \"../workflows/container-contents/documentStructure\";\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"../workflows/container-contents/pendingWrites\";\nexport type {\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n} from \"../workflows/container-contents/syncState\";\nexport type {\n ContainerContents,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerInfoInput,\n DocumentInfoInput,\n LinkDocumentToContainerInput,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n OpenContainerDocumentInput,\n PurgeDocumentInput,\n PurgeDocumentResult,\n SetActiveDocumentContainerInput,\n UnlinkDocumentFromContainerInput,\n} from \"./containerContentsTypes\";\n\nexport { createContainerDocumentObjectSyncState };\n\nexport function createContainerContents(\n runtime: InternalRuntime,\n): ContainerContents {\n return new ContainerContentsService(runtime);\n}\n\nfunction createDocumentLinkHost(\n runtime: ContainerDocumentLinks,\n mergeDocumentSummary: MergeDocumentSummary,\n): DocumentStructuralMutationHost<DocumentsWorkflowRuntime> {\n return {\n documentWorkflowRuntime: runtime.documentRuntime,\n mergeDocumentSummary,\n openDocumentStore: (input) => {\n const store = runtime.openDocument({\n containerId: input.containerId,\n documentId: input.documentId,\n localId: input.localId,\n });\n return {\n ...store,\n relink: ({ commitSideEffect, ...relinkInput }) =>\n commitSideEffect\n ? relinkDocumentStoreWithCommitSideEffect(\n store,\n relinkInput,\n commitSideEffect,\n )\n : store.relink(relinkInput),\n };\n },\n };\n}\n\nfunction moveDocumentLinkNote(\n input: Pick<MoveDocumentToContainerInput, \"note\" | \"sourceContainerId\">,\n): DocumentSummary {\n if (\n input.note.documentId &&\n input.sourceContainerId &&\n input.sourceContainerId !== input.note.containerId\n ) {\n return { ...input.note, containerId: input.sourceContainerId };\n }\n\n return input.note;\n}\n\ninterface ContainerInfoOrganizationScope {\n readonly domainScope: InternalWorkflowRuntimeInput[\"state\"][\"domainScope\"];\n readonly organizationId: string;\n readonly userId: string;\n}\n\nfunction readyExecSql(\n runtime: InternalWorkflowRuntimeInput,\n): InternalWorkflowRuntimeInput[\"infra\"][\"execSql\"] | null {\n return runtime.infra.dbStatus === \"ready\" ? runtime.infra.execSql : null;\n}\n\nfunction isActiveContainerInfoOrganizationScope(\n runtime: InternalWorkflowRuntimeInput,\n scope: ContainerInfoOrganizationScope,\n): boolean {\n return (\n runtime.auth.isAuthenticated &&\n runtime.auth.organizationId === scope.organizationId &&\n runtime.auth.userId === scope.userId &&\n runtime.state.domainScope === scope.domainScope\n );\n}\n\nfunction purgeDocumentFromLinks(input: {\n readonly document: Parameters<ContainerDocumentLinks[\"purgeDocument\"]>[0];\n readonly resolveProjectionUserKey: ContainerDocumentLinks[\"resolveProjectionUserKey\"];\n readonly runtime: ContainerDocumentLinks;\n}) {\n const { note } = input.document;\n if (!note.documentId) {\n return purgeLocalContainerDocument({\n noteId: note.id,\n runtime: input.runtime,\n });\n }\n return purgeRemoteContainerDocument({\n documentId: note.documentId,\n documentKind: note.documentKind ?? DEFAULT_DOCUMENT_KIND,\n noteId: note.id,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n });\n}\n\nclass ContainerContentsService implements ContainerContents {\n private readonly organizationReadModels: OrganizationReadModelCoordinator;\n\n constructor(private readonly runtimeService: InternalRuntime) {\n this.organizationReadModels =\n createOrganizationReadModelCoordinator(runtimeService);\n }\n\n openTree(\n options?: ContainerContentsStoreOptions | undefined,\n ): ContainerContentsStore {\n const runtime = this.workflowRuntime();\n const store = getOrCreateContainerContentsStore(\n runtime.state.domainScope,\n runtime,\n options,\n );\n return store;\n }\n\n documentQueries(): ContainerDocumentQueries {\n return createContainerDocumentQueriesFromRuntime(this.workflowRuntime());\n }\n\n documentLinks(): ContainerDocumentLinks {\n const runtime = this.workflowRuntime();\n const resolveProjectionUserKey =\n createContainerContentsDocumentProjectionUserKeyResolver(runtime);\n const documentRuntime = (containerId: string | null) =>\n createContainerContentsDocumentsRuntime(runtime, containerId);\n const openContainerDocument = (input: OpenContainerDocumentInput) =>\n openDocumentStore(\n runtime.state.domainScope,\n input.localId,\n documentRuntime(input.containerId),\n input.documentId ?? null,\n input.initialText,\n input.initialDocumentKind,\n { deferInitialUpdate: input.deferInitialUpdate },\n );\n const documentLinks: ContainerDocumentLinks = {\n ...runtime,\n documentRuntime,\n openDocument: openContainerDocument,\n setActiveDocumentContainer: (input) =>\n activateDocumentLink({\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: input.note,\n runtime: documentLinks,\n targetContainerId: input.targetContainerId,\n }),\n canMutateDocumentLinks: canMutateDocumentLink(runtime),\n canMutateUnsyncedDocumentLinks: canMutateLocalDocumentLink(runtime),\n linkDocumentToContainer: (input) =>\n addDocumentLink({\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: input.note,\n runtime: documentLinks,\n scheduleSync: () => this.openTree().requestSync(),\n setLinkedContainerIdsForDocument:\n input.setLinkedContainerIdsForDocument,\n targetContainerId: input.targetContainerId,\n }),\n moveDocumentToContainer: (input) =>\n moveDocumentLink({\n expandNode: input.expandNode,\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: moveDocumentLinkNote(input),\n replaceLinkedContainers: input.replaceLinkedContainers,\n runtime: documentLinks,\n scheduleSync: () => this.openTree().requestSync(),\n setLinkedContainerIdsForDocument:\n input.setLinkedContainerIdsForDocument,\n targetContainerId: input.targetContainerId,\n }),\n purgeDocument: (document) =>\n purgeDocumentFromLinks({\n document,\n resolveProjectionUserKey,\n runtime: documentLinks,\n }),\n resolveProjectionUserKey,\n unlinkDocumentFromContainer: (input) =>\n removeDocumentLink({\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: input.note,\n removedContainerId: input.removedContainerId,\n runtime: documentLinks,\n scheduleSync: () => this.openTree().requestSync(),\n setLinkedContainerIdsForDocument:\n input.setLinkedContainerIdsForDocument,\n }),\n };\n\n return inheritPrincipalHistoryProtection(runtime, documentLinks);\n }\n\n discoverContainerDocuments(\n containerId: string,\n ): Promise<ReadonlyArray<DocumentSummary> | null> {\n return discoverContainerDocumentsForRuntime({\n containerId,\n runtimeService: this.runtimeService,\n });\n }\n\n pullDocumentContent(input: {\n containerId: string;\n localId: string;\n documentId?: string | null | undefined;\n }): void {\n const runtime = this.workflowRuntime();\n const store = openDocumentStore(\n runtime.state.domainScope,\n input.localId,\n createContainerContentsDocumentsRuntime(runtime, input.containerId),\n input.documentId ?? null,\n );\n store.requestRemoteSync();\n }\n\n loadContainerInfo(input: ContainerInfoInput): Promise<ContainerInfo> {\n const runtime = this.runtimeService.workflowInput();\n const organizationScope =\n runtime.auth.isAuthenticated &&\n runtime.auth.organizationId &&\n runtime.auth.userId\n ? {\n domainScope: runtime.state.domainScope,\n organizationId: runtime.auth.organizationId,\n userId: runtime.auth.userId,\n }\n : null;\n const cachedContainerProjection =\n input.remoteInfoMode === \"always\"\n ? null\n : this.openTree().getCachedContainerWriterProjection(input.containerId);\n return loadContainerInfo({\n ...input,\n apiClient: runtime.apiClient,\n containerProjection: cachedContainerProjection,\n execSql: readyExecSql(runtime),\n loadOrganizationGroups: async () => {\n if (\n !organizationScope ||\n !isActiveContainerInfoOrganizationScope(\n this.runtimeService.workflowInput(),\n organizationScope,\n )\n ) {\n return [];\n }\n // Organization groups are disposable presentation data. Container\n // writer projections remain the authority for grants and access.\n const projection = await this.organizationReadModels.loadLocal(\n organizationScope.organizationId,\n );\n return isActiveContainerInfoOrganizationScope(\n this.runtimeService.workflowInput(),\n organizationScope,\n )\n ? (projection?.groups ?? [])\n : [];\n },\n parentId: input.parentId ?? null,\n });\n }\n\n loadDocumentInfo(input: DocumentInfoInput): Promise<DocumentInfo> {\n const runtime = this.runtimeService.workflowInput();\n return loadDocumentInfo({\n ...input,\n apiClient: runtime.apiClient,\n execSql: readyExecSql(runtime),\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n });\n }\n\n loadDocumentEditAttribution(\n documentId: string,\n ): ReturnType<ContainerContents[\"loadDocumentEditAttribution\"]> {\n return this.runtimeService\n .workflowInput()\n .apiClient.getDocumentEditAttribution(documentId);\n }\n\n loadDocumentAttributionRanges(\n input: DocumentAttributionRangesInput,\n ): Promise<DocumentAttributionRangesPage> {\n return loadDocumentAttributionRanges({\n apiClient: this.runtimeService.workflowInput().apiClient,\n query: input,\n });\n }\n\n listBlobInfo(input: BlobInfoInput = {}): Promise<BlobInfoList> {\n const runtime = this.runtimeService.workflowInput();\n return listBlobInfo({\n ...input,\n execSql: readyExecSql(runtime),\n });\n }\n\n workflowRuntime(): ContainerContentsStoreWorkflowRuntime {\n return createContainerContentsStoreWorkflowRuntime(\n this.runtimeService.workflowInput(),\n this.runtimeService.adoptRootContainer,\n );\n }\n}\n"]}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=containerContentsTypes.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"containerContentsTypes.js","sourceRoot":"","sources":["containerContentsTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentEditAttributionResponse } from \"@tearleads/validators/response\";\nimport type { StoredDocumentKind } from \"../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../data/documents/documentSummary\";\nimport type {\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerContentsStoreRuntime,\n} from \"../stores/container-contents\";\nimport type { DocumentStore } from \"../stores/documents\";\nimport type {\n BlobInfoInput,\n BlobInfoList,\n} from \"../workflows/container-contents/blobInfo\";\nimport type {\n ContainerInfo,\n ContainerInfoRemoteMode,\n} from \"../workflows/container-contents/containerInfo\";\nimport type {\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n} from \"../workflows/container-contents/documentAttributionRanges\";\nimport type {\n DocumentInfo,\n DocumentInfoRemoteMode,\n} from \"../workflows/container-contents/documentInfo\";\nimport type { ContainerDocumentQueries } from \"../workflows/container-contents/documentQueries\";\nimport type { SetLinkedContainerIdsForDocument } from \"../workflows/container-contents/documentStructure\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../workflows/container-contents/projectionKeys\";\nimport type { ContainerContentsWorkflowRuntime } from \"../workflows/container-contents/runtime\";\nimport type { DocumentsWorkflowRuntime } from \"../workflows/documents\";\n\n/**\n * Selects the container to inspect.\n *\n * Container info combines local SQLite timestamps with optional remote writer\n * projection details. Remote details include direct and inherited grants,\n * organization groups, security-path metadata, and sync watermarks for the\n * parent, child-container, and document lanes.\n *\n * Fields:\n * - `containerId`: Container id to inspect.\n * - `parentId`: Known parent id used when the container has not been synced\n * locally yet. Synced local state wins when available.\n * - `remoteInfoMode`: Controls whether remote projection details are fetched.\n */\nexport interface ContainerInfoInput {\n containerId: string;\n parentId?: string | null | undefined;\n remoteInfoMode?: ContainerInfoRemoteMode | undefined;\n}\n\n/**\n * Selects the document to inspect.\n *\n * Document info combines local document state, local and pending attachment\n * rows, and optional remote writer projection details.\n *\n * Fields:\n * - `attributionRequestKey`: Optional freshness generation used to coalesce\n * duplicate attribution reads without joining requests across invalidation.\n * - `localId`: Local document id stored in the client database.\n * - `remoteInfoMode`: Controls whether remote projection details are fetched.\n */\nexport interface DocumentInfoInput {\n attributionRequestKey?: string | undefined;\n localId: string;\n remoteInfoMode?: DocumentInfoRemoteMode | undefined;\n}\n\nexport type MergeDocumentSummary = (nextDocument: DocumentSummary) => void;\n\nexport interface OpenContainerDocumentInput {\n readonly containerId: string | null;\n /** A file attach follows creation and carries the birth; see the store. */\n readonly deferInitialUpdate?: boolean | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n readonly initialText?: string | undefined;\n readonly localId: string;\n}\n\nexport interface ContainerDocumentLinkInput {\n readonly mergeDocumentSummary: MergeDocumentSummary;\n readonly note: DocumentSummary;\n}\n\nexport interface MoveDocumentToContainerInput\n extends ContainerDocumentLinkInput {\n readonly expandNode: (nodeId: string) => void;\n readonly replaceLinkedContainers?: boolean | undefined;\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n readonly sourceContainerId?: string | null | undefined;\n readonly targetContainerId: string;\n}\n\nexport interface LinkDocumentToContainerInput\n extends ContainerDocumentLinkInput {\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n readonly targetContainerId: string;\n}\n\nexport interface UnlinkDocumentFromContainerInput\n extends ContainerDocumentLinkInput {\n readonly removedContainerId: string;\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n}\n\nexport interface SetActiveDocumentContainerInput\n extends ContainerDocumentLinkInput {\n readonly targetContainerId: string;\n}\n\nexport interface PurgeDocumentInput {\n /** The current local summary of the document to destroy. */\n readonly note: DocumentSummary;\n}\n\nexport interface PurgeDocumentResult {\n readonly documentId: string;\n readonly purgedAt: string;\n readonly reclaimedBlobStorageKeys: ReadonlyArray<string>;\n}\n\nexport interface ContainerDocumentLinks\n extends ContainerContentsWorkflowRuntime {\n documentRuntime(containerId: string | null): DocumentsWorkflowRuntime;\n openDocument(input: OpenContainerDocumentInput): DocumentStore;\n setActiveDocumentContainer(\n input: SetActiveDocumentContainerInput,\n ): Promise<DocumentSummary | null>;\n readonly canMutateDocumentLinks: boolean;\n readonly canMutateUnsyncedDocumentLinks: boolean;\n linkDocumentToContainer(\n input: LinkDocumentToContainerInput,\n ): Promise<DocumentSummary | null>;\n moveDocumentToContainer(\n input: MoveDocumentToContainerInput,\n ): Promise<{ linksChanged: boolean; note: DocumentSummary | null }>;\n /**\n * Permanently destroy a local-only document, or submit and verify a signed\n * terminal purge for a remote document. Remote purge requires exactly one\n * remaining container link and returns null on refusal or verification\n * failure.\n */\n purgeDocument(input: PurgeDocumentInput): Promise<PurgeDocumentResult | null>;\n readonly resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n unlinkDocumentFromContainer(\n input: UnlinkDocumentFromContainerInput,\n ): Promise<DocumentSummary | null>;\n}\n\n/**\n * High-level container-content service for tree state, document lists, document\n * links, discovery, and diagnostics.\n *\n * The facade owns the normal SDK protocol: it supplies the API client,\n * referenced-principal policy cache, local document query helpers, link\n * projection, tombstone handling, and sync watermarks. Consumers that need a\n * custom persistence protocol can call the lower-level workflows directly from\n * `@tearleads/client-sdk`.\n */\nexport interface ContainerContents {\n /**\n * Open the container tree state store for the current SDK runtime.\n *\n * The store is cached per domain scope and created from the current runtime\n * snapshot. Long-lived hosts should call `updateRuntime` after runtime\n * changes, such as from a React effect.\n */\n openTree(\n options?: ContainerContentsStoreOptions | undefined,\n ): ContainerContentsStore;\n\n /**\n * Create local document query helpers for container contents.\n *\n * The facade is bound to the current SDK runtime snapshot, including the\n * active SQLite executor. Recreate it when the SDK runtime version changes.\n */\n documentQueries(): ContainerDocumentQueries;\n\n /**\n * Create the default document-link workflow helper.\n *\n * The returned object includes the current container-contents runtime,\n * the document projection-key resolver, mutation readiness, document store\n * priming, and container document-link mutations. Product stores can pass\n * this bundle around without rebuilding SDK runtime plumbing themselves.\n */\n documentLinks(): ContainerDocumentLinks;\n\n /**\n * Discover remote documents linked to one container.\n *\n * The method pages the remote container-document lane, writes discovered\n * document summaries into local SQLite, replaces the local link projection for\n * each discovered document, applies applicable tombstones, caches referenced\n * principal policies needed by newly visible documents, and advances the\n * container-document watermark after the local apply completes.\n *\n * One call verifies a bounded batch. Pending evidence is durable; a later\n * explicit call or background reconciliation resumes it.\n *\n * Returns the summaries touched by the apply, or `null` when the database or\n * listing is unavailable, a trust reset cancels the pass, or all evidence is\n * pending. Pending evidence may advance the watermark after durable staging.\n *\n * Parameters:\n * - `containerId`: Remote container id whose document lane should be listed.\n */\n discoverContainerDocuments(\n containerId: string,\n ): Promise<ReadonlyArray<DocumentSummary> | null>;\n\n /**\n * Sync the content of a single document that no mini-app has opened.\n *\n * Discovery only records a document's metadata + an empty content shell, and a\n * document's locally authored content is only pushed once its store syncs; both\n * normally happen lazily when a mini-app opens the document. Some documents are\n * never opened yet still need to sync — notably the organization profile\n * document, which lives in an org's Members-granted metadata container and\n * holds the org display name. This opens a transient document store (registered\n * under the container's keys, so it can decrypt) and schedules a remote sync\n * pass. The pass both pushes the store's pending updates and merges + persists\n * any remote body, so the same call lets an owning device publish its profile\n * content and a member device pull it. `documentId` may be omitted; the store\n * then resolves it from the persisted record (the owning device keys the\n * document under a local alias, not its server id).\n */\n pullDocumentContent(input: {\n containerId: string;\n localId: string;\n documentId?: string | null | undefined;\n }): void;\n\n /**\n * Load diagnostic information for one local document.\n *\n * Local details are available when SQLite is ready. Remote details are loaded\n * from the document writer projection according to `remoteInfoMode`; the\n * default is `\"if-synced\"`.\n */\n loadDocumentInfo(input: DocumentInfoInput): Promise<DocumentInfo>;\n\n /**\n * Fetch a synced document's compact edit-attribution segments (peer -> writer\n * intervals) on their own, without the writer-projection/attachment work\n * `loadDocumentInfo` also does. Resolves to `null` on any request failure.\n * Callers must ignore the segments when `truncated` is set — a truncated\n * interval list can drop a peer's segments and mis-resolve it.\n */\n loadDocumentEditAttribution(\n documentId: string,\n ): Promise<DocumentEditAttributionResponse | null>;\n\n /** Load one revision-bound page of detailed per-upload edit attribution. */\n loadDocumentAttributionRanges(\n input: DocumentAttributionRangesInput,\n ): Promise<DocumentAttributionRangesPage>;\n\n /**\n * List local blob projections and pending attachment bytes grouped by blob.\n *\n * This is a reverse lookup query: callers can search by server blob id,\n * local storage key, document id/title, attachment slot, or MIME metadata and\n * then traverse matching blobs back to their owning local documents.\n */\n listBlobInfo(input?: BlobInfoInput | undefined): Promise<BlobInfoList>;\n\n /**\n * Load diagnostic information for one container.\n *\n * Local details include synced timestamps. Remote details are loaded from the\n * container writer projection according to `remoteInfoMode`; the default is\n * `\"always\"`. Pass `parentId` when inspecting a container before its local row\n * has been synced.\n */\n loadContainerInfo(input: ContainerInfoInput): Promise<ContainerInfo>;\n\n /**\n * Create a workflow runtime for advanced container-content workflows.\n *\n * Prefer the high-level methods on this service for the default SDK protocol.\n * Use this when constructing lower-level stores or custom workflows that need\n * access to the current runtime snapshot.\n */\n workflowRuntime(): ContainerContentsStoreRuntime;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"containerDocumentDiscovery.js","sourceRoot":"","sources":["containerDocumentDiscovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,+BAA+B,EAAE,MAAM,qEAAqE,CAAC;AACtH,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,EACpC,4CAA4C,EAC5C,4BAA4B,EAC5B,qCAAqC,GACtC,MAAM,0EAA0E,CAAC;AAClF,OAAO,EAAE,oCAAoC,EAAE,MAAM,oEAAoE,CAAC;AAC1H,OAAO,EAAE,iCAAiC,EAAE,MAAM,0DAA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CAAC","sourcesContent":["import type { DocumentSummary } from \"../data/documents/documentSummary\";\nimport { sqlContainerContentsPersistence } from \"../data/persistence/container-contents/containerContentsPersistence\";\nimport {\n holdContainerDocumentTombstones,\n listKnownContainerDocumentPlacements,\n listRetryableHeldContainerDocumentTombstones,\n loadLocalDocumentAccessEpoch,\n refuteContainerDocumentTombstoneHolds,\n} from \"../data/persistence/documents/containerDocumentTombstoneHoldsPersistence\";\nimport { createDocumentDiscoveryEvidenceStore } from \"../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport { listContainerDocumentLanesFromApi } from \"../workflows/container-contents/containerDocumentListing\";\nimport { createDiscoveredDocumentVerifier } from \"../workflows/container-contents/documentDiscoveryEvidence\";\nimport {\n type ContainerDocumentDiscoveryLane,\n type ContainerDocumentDiscoveryOutcome,\n type ContainerDocumentDiscoveryOutcomeHandler,\n discoverContainerDocumentLanes,\n} from \"../workflows/container-contents/documentDiscoveryLanes\";\nimport { createContainerDocumentQueriesFromRuntime } from \"../workflows/container-contents/documentQueries\";\nimport {\n createContainerDocumentTombstoneVerifier,\n createDocumentHeadLinkSetLoader,\n} from \"../workflows/container-contents/documentTombstoneEvidence\";\nimport {\n type ContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntime,\n} from \"../workflows/container-contents/runtime\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../workflows/principals/runtimePolicyWarmer\";\nimport type { InternalRuntime } from \"./workflowRuntime\";\n\nexport type { ContainerDocumentDiscoveryOutcome } from \"../workflows/container-contents/documentDiscoveryLanes\";\n\n/** One container to discover, with the reconciler's per-lane callbacks. */\nexport interface ContainerDocumentDiscoveryRequest {\n readonly containerId: string;\n readonly onFullListing?:\n | ((documentIds: ReadonlyArray<string>) => void)\n | undefined;\n readonly onPendingDiscovery?: ((delayMs: number) => void) | undefined;\n}\n\ntype ExecSql = ReturnType<InternalRuntime[\"workflowInput\"]>[\"infra\"][\"execSql\"];\n\nfunction createDiscoveryLane(input: {\n readonly containerOrganizationId: string | undefined;\n readonly evidenceStore: ReturnType<\n typeof createDocumentDiscoveryEvidenceStore\n >;\n readonly execSql: ExecSql;\n readonly queries: ReturnType<\n typeof createContainerDocumentQueriesFromRuntime\n >;\n readonly request: ContainerDocumentDiscoveryRequest;\n readonly runtime: ContainerContentsWorkflowRuntime;\n}): ContainerDocumentDiscoveryLane {\n const { containerOrganizationId, execSql, request, runtime } = input;\n const warmReferencedPrincipalPolicies =\n createRuntimePrincipalPolicyWarmer(runtime);\n const loadHead = createDocumentHeadLinkSetLoader(runtime);\n const loadEpoch = (documentId: string) =>\n loadLocalDocumentAccessEpoch(execSql, documentId);\n return {\n ...input.queries,\n cacheReferencedPrincipalPolicies: (references) =>\n containerOrganizationId\n ? warmReferencedPrincipalPolicies({\n organizationId: containerOrganizationId,\n references,\n })\n : Promise.resolve(),\n containerId: request.containerId,\n holdContainerDocumentTombstones: (tombstones) =>\n holdContainerDocumentTombstones(execSql, tombstones),\n listHeldContainerDocumentTombstones: (containerIds) =>\n listRetryableHeldContainerDocumentTombstones(execSql, containerIds),\n listKnownContainerDocumentPlacements: (placements) =>\n listKnownContainerDocumentPlacements(execSql, placements),\n onFullListing: request.onFullListing,\n refuteContainerDocumentTombstoneHolds: (placements) =>\n refuteContainerDocumentTombstoneHolds(execSql, placements),\n verifyContainerDocumentTombstones: createContainerDocumentTombstoneVerifier(\n containerOrganizationId,\n loadHead,\n loadEpoch,\n ),\n verifyDiscoveredDocuments: createDiscoveredDocumentVerifier(\n containerOrganizationId,\n loadHead,\n loadEpoch,\n input.evidenceStore,\n request.onPendingDiscovery,\n ),\n };\n}\n\n/**\n * Internal adapter shared by explicit discovery and background reconciliation:\n * one batched listing for every requested container, then per-container\n * verification scoped to each container's durable organization.\n */\nexport async function discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n}: {\n readonly onOutcome?: ContainerDocumentDiscoveryOutcomeHandler | undefined;\n readonly requests: ReadonlyArray<ContainerDocumentDiscoveryRequest>;\n readonly runtimeService: InternalRuntime;\n}): Promise<ReadonlyArray<ContainerDocumentDiscoveryOutcome>> {\n const unlisted = (\n containerId: string,\n ): ContainerDocumentDiscoveryOutcome => ({\n containerId,\n status: \"fulfilled\",\n value: null,\n });\n const input = runtimeService.workflowInput();\n if (input.infra.dbStatus !== \"ready\") {\n return requests.map(({ containerId }) => unlisted(containerId));\n }\n const runtime = createContainerContentsWorkflowRuntime(input);\n const execSql = input.infra.execSql;\n const evidenceStore = createDocumentDiscoveryEvidenceStore(execSql);\n const queries = createContainerDocumentQueriesFromRuntime(runtime);\n // Capture the reset fence before reading any lane's scope, so a reset\n // between these reads and the listing cannot publish old-organization\n // evidence into its replacement.\n const generation = await evidenceStore.begin();\n const lanes: ContainerDocumentDiscoveryLane[] = [];\n for (const request of requests) {\n const stored =\n await sqlContainerContentsPersistence.loadContainerMetadataState(\n execSql,\n request.containerId,\n );\n if (stored)\n lanes.push(\n createDiscoveryLane({\n containerOrganizationId: stored.container.organizationId,\n evidenceStore,\n execSql,\n queries,\n request,\n runtime,\n }),\n );\n }\n const outcomes = await discoverContainerDocumentLanes({\n generation,\n lanes,\n listContainerDocumentLanes: (listed) =>\n listContainerDocumentLanesFromApi(runtime.apiClient, listed),\n loadContainerDocumentWatermark: queries.loadContainerDocumentWatermark,\n onOutcome,\n });\n const outcomeByContainerId = new Map(\n outcomes.map((outcome) => [outcome.containerId, outcome]),\n );\n return requests.map(\n ({ containerId }) =>\n outcomeByContainerId.get(containerId) ?? unlisted(containerId),\n );\n}\n\n/** Discovers one container; a rejected lane rethrows its failure. */\nexport async function discoverContainerDocumentsForRuntime({\n runtimeService,\n ...request\n}: ContainerDocumentDiscoveryRequest & {\n readonly runtimeService: InternalRuntime;\n}): Promise<ReadonlyArray<DocumentSummary> | null> {\n const [outcome] = await discoverContainerDocumentLanesForRuntime({\n requests: [request],\n runtimeService,\n });\n if (outcome?.status === \"rejected\") throw outcome.reason;\n return outcome?.value ?? null;\n}\n"]}
@@ -1 +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AAM,KAAK,IAAI,CAAC,MAAM,EAC/B,CAAC;YACD,OAAO;QACT,CAAC;QAED,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n} from \"../data/sqlite/sqlSchema\";\nimport { createListenerSet } from \"./listenerSet\";\n\nexport type DatabaseStatus = \"idle\" | \"ready\" | \"error\" | \"terminated\";\n\nexport interface DatabaseSnapshot {\n client: ExecSqlClientLike | null;\n execSql: ExecSql | null;\n id: string | null;\n status: DatabaseStatus;\n}\n\nexport type DatabaseListener = () => void;\n\nexport interface DatabaseOptions {\n client?: ExecSqlClientLike | null | undefined;\n execSql?: ExecSql | null | undefined;\n id?: string | null | undefined;\n status?: DatabaseStatus | undefined;\n}\n\nexport class Database {\n private readonly listeners = createListenerSet();\n private snapshotValue: DatabaseSnapshot = {\n client: null,\n execSql: null,\n id: null,\n status: \"idle\",\n };\n\n constructor(options?: DatabaseOptions | undefined) {\n if (options) {\n this.configure(options);\n }\n }\n\n get client(): ExecSqlClientLike | null {\n return this.snapshotValue.client;\n }\n\n get execSql(): ExecSql | null {\n return this.snapshotValue.execSql;\n }\n\n get id(): string | null {\n return this.snapshotValue.id;\n }\n\n get snapshot(): DatabaseSnapshot {\n return this.snapshotValue;\n }\n\n get status(): DatabaseStatus {\n return this.snapshotValue.status;\n }\n\n clear(status: DatabaseStatus = \"idle\"): void {\n this.setSnapshot({\n client: null,\n execSql: null,\n id: null,\n status,\n });\n }\n\n configure(options: DatabaseOptions): void {\n const client = options.client ?? null;\n const execSql = options.execSql ?? (client ? createExecSql(client) : null);\n if (options.status === \"ready\" && !execSql) {\n throw new Error(\n \"A ready SQLite database requires a configured executor or client.\",\n );\n }\n\n this.setSnapshot({\n client,\n execSql,\n id: options.id ?? null,\n status: options.status ?? (execSql ? \"ready\" : \"idle\"),\n });\n }\n\n requireExecSql(operation = \"This operation\"): ExecSql {\n if (!this.snapshotValue.execSql) {\n throw new Error(`${operation} requires a configured SQLite executor.`);\n }\n\n return this.snapshotValue.execSql;\n }\n\n setClient(\n client: ExecSqlClientLike,\n options: Omit<DatabaseOptions, \"client\" | \"execSql\"> = {},\n ): void {\n this.configure({ ...options, client });\n }\n\n setExecSql(\n execSql: ExecSql,\n options: Omit<DatabaseOptions, \"client\" | \"execSql\"> = {},\n ): void {\n this.configure({ ...options, execSql });\n }\n\n subscribe = (listener: DatabaseListener): (() => void) =>\n this.listeners.subscribe(listener);\n\n private setSnapshot(next: DatabaseSnapshot): void {\n const previous = this.snapshotValue;\n if (\n previous.client === next.client &&\n previous.execSql === next.execSql &&\n previous.id === next.id &&\n previous.status === next.status\n ) {\n return;\n }\n\n this.snapshotValue = next;\n this.listeners.notify();\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"deviceFirst.js","sourceRoot":"","sources":["deviceFirst.ts"],"names":[],"mappings":"AACA,OAAO,EACL,4BAA4B,EAC5B,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAGL,mCAAmC,EACnC,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EACL,mCAAmC,EACnC,qCAAqC,EACrC,6BAA6B,GAC9B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,+BAA+B,GAGhC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,6BAA6B,EAC7B,2BAA2B,EAG3B,yBAAyB,GAC1B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,kCAAkC,EAAE,MAAM,0DAA0D,CAAC;AAC9G,OAAO,EAAE,oCAAoC,EAAE,MAAM,wDAAwD,CAAC;AAC9G,OAAO,EAEL,uCAAuC,EACvC,2CAA2C,GAC5C,MAAM,yCAAyC,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KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,eAAe,CAAC,KAAK,CAAC;YACxD,0BAA0B;YAC1B,GAAG,8BAA8B,CAAC,cAAc,EAAE,WAAW,CAAC;YAC9D,WAAW,EAAE,KAAK,IAAI,EAAE;gBACtB,MAAM,KAAK,CAAC,iBAAiB,EAAE,CAAC,OAAO,EAAE,CAAC;YAC5C,CAAC;YACD,eAAe,EAAE,KAAK,IAAI,EAAE;gBAC1B,MAAM,KAAK,CAAC,iBAAiB,EAAE,CAAC,eAAe,EAAE,CAAC;YACpD,CAAC;YACD,gBAAgB,EAAE,0BAA0B;YAC5C,qEAAqE;YACrE,wEAAwE;YACxE,QAAQ,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,CAC3B,wBAAwB,CAAC,IAAI,CAAC,eAAe,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC;SACnE,CAAC;IACJ,CAAC;CACF;AAED,8EAA8E;AAC9E,sEAAsE;AACtE,SAAS,wBAAwB,CAC/B,OAA8C,EAC9C,OAAe,EACf,KAAc;IAEd,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IACvC,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,cAA+B;IAE/B,OAAO,2CAA2C,CAChD,cAAc,CAAC,aAAa,EAAE,EAC9B,cAAc,CAAC,kBAAkB,CAClC,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../data/domainScope\";\nimport {\n disposeDomainSyncCoordinator,\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n} from \"../data/sync/syncCoordinator\";\nimport {\n type ContainerContentsStore,\n type ContainerContentsStoreOptions,\n isAutomaticRootCatchupContainerNode,\n isReconcilableContainerNode,\n isRemoteBackedContainerNode,\n} from \"../stores/container-contents\";\nimport { openDocumentStore } from \"../stores/documents\";\nimport {\n requestRegisteredDocumentRemoteSync,\n subscribeToPersistedDocumentDeletions,\n subscribeToPersistedDocuments,\n} from \"../stores/documents/registry\";\nimport {\n getOrCreateLocalProjectionStore,\n type LocalProjectionStore,\n type LocalProjectionView,\n} from \"../stores/local-projection\";\nimport {\n connectReconciliationTriggers,\n createReconciliationService,\n type ReconciliationHost,\n type ReconciliationService,\n systemReconciliationClock,\n} from \"../sync/reconciliation\";\nimport { listAllContainerDocumentIdsFromApi } from \"../workflows/container-contents/containerDocumentListing\";\nimport { probeUndiscoveredRemoteDocumentBatch } from \"../workflows/container-contents/documentHydrationProbe\";\nimport {\n type ContainerContentsStoreWorkflowRuntime,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n} from \"../workflows/container-contents/runtime\";\nimport type { ContainerContents } from \"./containerContents\";\nimport { discoverContainerDocumentLanesForRuntime } from \"./containerDocumentDiscovery\";\nimport { createReconciledDocumentContentPuller } from \"./reconciledDocumentContentPull\";\nimport type { InternalRuntime } from \"./workflowRuntime\";\n\nexport type { LocalProjectionView } from \"../stores/local-projection\";\n\n/** One domain scope's local read, local-write, and reconciliation handles. */\nexport interface DeviceFirstContainerContents {\n /**\n * Locally durable container tree and mutation store. Ordinary tree writes\n * update this store after local persistence and queue remote convergence in\n * the background; security-sensitive remote operations keep their explicit\n * online requirements.\n */\n readonly containerStore: ContainerContentsStore;\n /** Background remote reconciliation; never awaited for first paint. */\n readonly reconciler: ReconciliationService;\n /** Synchronously readable container/document projection. */\n readonly view: LocalProjectionView;\n}\n\n/**\n * Device-first facade. Opens a shared scope that pairs immediate local reads\n * and locally durable writes with background remote convergence.\n */\nexport interface DeviceFirst {\n /** Open all device-first handles for the current domain scope. */\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents;\n /** Stop the current scope's reconciler (if one was created) on teardown. */\n dispose(): void;\n}\n\nexport function createDeviceFirst(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n): DeviceFirst {\n return new DeviceFirstService(runtimeService, containerContents);\n}\n\ninterface DeviceFirstScopeEntry {\n contents: DeviceFirstContainerContents;\n disconnectReconciliationTriggers: () => void;\n unsubscribePersistedDocumentDeletions: () => void;\n unsubscribePersistedDocuments: () => void;\n}\n\nfunction createInitialDocumentProbeHost(\n runtimeService: InternalRuntime,\n domainScope: ReconciliationHost[\"domainScope\"],\n): Pick<\n ReconciliationHost,\n | \"listContainerDocumentIds\"\n | \"probeUndiscoveredDocumentsBatch\"\n | \"reportInitialDocumentProbeComplete\"\n> {\n return {\n listContainerDocumentIds: (containerId) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return listAllContainerDocumentIdsFromApi({\n apiClient: runtime.apiClient,\n containerId,\n reportErrors: false,\n });\n },\n probeUndiscoveredDocumentsBatch: async (input) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return probeUndiscoveredRemoteDocumentBatch({\n ...input,\n host: {\n documentWorkflowRuntime: (containerId) =>\n createContainerContentsDocumentsRuntime(runtime, containerId),\n openDocumentStore: (target) =>\n openDocumentStore(\n domainScope,\n target.localId,\n target.runtime,\n target.documentId,\n ),\n },\n runtime,\n });\n },\n reportInitialDocumentProbeComplete: (requestedCount) => {\n runtimeService\n .workflowInput()\n .util.log(\n `Initial document hydration probe requested ${requestedCount} syncs`,\n );\n },\n };\n}\n\nclass DeviceFirstService implements DeviceFirst {\n // A real Map (not WeakMap) so dispose() can iterate every scope seen this\n // session. A running reconciler holds event subscriptions that keep an idle,\n // stale-scope service (and its scope) reachable anyway, so WeakMap bought no\n // GC here; the entries are released explicitly on dispose().\n private readonly entriesByScope = new Map<\n DomainScope,\n DeviceFirstScopeEntry\n >();\n\n constructor(\n private readonly runtimeService: InternalRuntime,\n private readonly containerContents: ContainerContents,\n ) {}\n\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents {\n return this.getOrCreateEntry(options).contents;\n }\n\n dispose(): void {\n // Stop every reconciler created this session — not just the current\n // scope's. A scope change (e.g. anonymous -> authenticated) leaves the old\n // scope's reconciler subscribed and its coordinator pump live; tear them\n // all down. Force-stop each scope's coordinator (which runs the reconciler\n // lane) alongside stopping the service.\n for (const [domainScope, entry] of this.entriesByScope) {\n entry.contents.reconciler.stop();\n entry.disconnectReconciliationTriggers();\n entry.unsubscribePersistedDocumentDeletions();\n entry.unsubscribePersistedDocuments();\n disposeDomainSyncCoordinator(domainScope);\n }\n this.entriesByScope.clear();\n }\n\n private workflowRuntime(): ContainerContentsStoreWorkflowRuntime {\n return createDeviceFirstWorkflowRuntime(this.runtimeService);\n }\n\n private getOrCreateEntry(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstScopeEntry {\n const runtime = this.workflowRuntime();\n const domainScope = runtime.state.domainScope;\n const existing = this.entriesByScope.get(domainScope);\n if (existing) {\n // Do not call updateRuntime here: facade selectors run during React\n // render, and updateRuntime emits synchronously. Hosts drive runtime\n // updates through view.updateRuntime() from an effect instead.\n return existing;\n }\n\n const store = getOrCreateLocalProjectionStore({\n domainScope,\n runtime,\n options,\n });\n const service = createReconciliationService(\n this.createReconciliationHost(store, domainScope),\n );\n const disconnectReconciliationTriggers = connectReconciliationTriggers({\n service,\n store,\n });\n const unsubscribePersistedDocumentDeletions =\n subscribeToPersistedDocumentDeletions(domainScope, (localId) => {\n store.removePersistedDocument(localId);\n });\n const unsubscribePersistedDocuments = subscribeToPersistedDocuments(\n domainScope,\n (document, change) =>\n store.refreshPersistedDocument(document, change.placementChanged),\n );\n service.start();\n\n const view: LocalProjectionView = {\n getSnapshot: () => store.getSnapshot(),\n subscribe: (listener) => store.subscribe(listener),\n setActiveContainer: (containerId) =>\n store.setActiveContainer(containerId),\n updateRuntime: (nextRuntime) => store.updateRuntime(nextRuntime),\n };\n\n const entry: DeviceFirstScopeEntry = {\n contents: {\n containerStore: store.getContainerStore(),\n reconciler: service,\n view,\n },\n disconnectReconciliationTriggers,\n unsubscribePersistedDocumentDeletions,\n unsubscribePersistedDocuments,\n };\n this.entriesByScope.set(domainScope, entry);\n return entry;\n }\n\n private createReconciliationHost(\n store: LocalProjectionStore,\n domainScope: ReconciliationHost[\"domainScope\"],\n ): ReconciliationHost {\n const runtimeService = this.runtimeService;\n const containerContents = this.containerContents;\n const requestDocumentContentPull = createReconciledDocumentContentPuller({\n getContainer: (containerId) =>\n store\n .getSnapshot()\n .containers.find((container) => container.id === containerId) ?? null,\n pullDocumentContent: (input) =>\n containerContents.pullDocumentContent(input),\n requestRegisteredDocumentRemoteSync: (localId, documentId) =>\n requestRegisteredDocumentRemoteSync(domainScope, localId, documentId),\n });\n const canDiscoverContainerDocuments = (containerId: string) => {\n const container = store\n .getSnapshot()\n .containers.find((node) => node.id === containerId);\n return container ? isRemoteBackedContainerNode(container) : false;\n };\n const listKnownContainerIds = () => {\n // A local-first id is not listable yet and may still be racing its create\n // request. Once remote-backed, it participates normally; system contents\n // are especially important during rematerialization because this device\n // may not have authored them.\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isReconcilableContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n const listAutomaticRootCatchupContainerIds = () => {\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isAutomaticRootCatchupContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n return {\n clock: systemReconciliationClock,\n domainScope,\n registerLane: (key, config) =>\n getOrCreateDomainSyncCoordinator(domainScope).registerLane(key, config),\n canDiscoverContainerDocuments,\n getRuntimeStatus: () => {\n const input = runtimeService.workflowInput();\n return {\n dbStatus: input.infra.dbStatus,\n isAuthenticated: input.auth.isAuthenticated,\n online: input.state.online,\n };\n },\n listKnownContainerIds,\n // Root discovery can surface directly granted non-root containers, so\n // retain every regular container. Exclude only this identity's own system\n // children; cold/auth backfill and explicit full Refresh cover those.\n listAutomaticRootCatchupContainerIds,\n discoverContainerDocuments: (requests, onOutcome) =>\n discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n }),\n loadContainerDelta: (containerId) =>\n store.loadContainerDelta(containerId),\n applyReconciled: (delta) => store.applyReconciled(delta),\n requestDocumentContentPull,\n ...createInitialDocumentProbeHost(runtimeService, domainScope),\n refreshTree: async () => {\n await store.getContainerStore().refresh();\n },\n refreshRootTree: async () => {\n await store.getContainerStore().refreshRootLane();\n },\n isIgnorableError: isDatabaseUnavailableError,\n // Resolve the runtime per call: it is rebuilt as the active identity\n // changes, and a reference captured here would report into a dead host.\n logError: (message, error) =>\n logReconciliationFailure(this.workflowRuntime(), message, error),\n };\n }\n}\n\n// Returns the host's result: both callbacks are declared `=> void` but may be\n// async, and the lane reporter only catches a rejection it is handed.\nfunction logReconciliationFailure(\n runtime: ContainerContentsStoreWorkflowRuntime,\n message: string,\n error: unknown,\n): unknown {\n const { log, logError } = runtime.util;\n return logError ? logError(message, error) : log(message);\n}\n\nexport function createDeviceFirstWorkflowRuntime(\n runtimeService: InternalRuntime,\n): ContainerContentsStoreWorkflowRuntime {\n return createContainerContentsStoreWorkflowRuntime(\n runtimeService.workflowInput(),\n runtimeService.adoptRootContainer,\n );\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"documents.js","sourceRoot":"","sources":["documents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAU5E,OAAO,EACL,mBAAmB,IAAI,yBAAyB,EAGhD,iBAAiB,EAEjB,6BAA6B,GAC9B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AAC7E,OAAO,EACL,8BAA8B,EAC9B,2BAA2B,EAC3B,uBAAuB,EACvB,0BAA0B,GAC3B,MAAM,wBAAwB,CAAC;AAqBhC,OAA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,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,KAAK;aAC/D,WAAW,EACd,QAAQ,CACT,CAAC;IACJ,CAAC;IAEO,YAAY,CAAC,OAAgB;QACnC,MAAM,QAAQ,GAAG,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC1D,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,QAAQ,CAAC;QAClB,CAAC;QAED,MAAM,MAAM,GAAG,2BAA2B;aACvC,YAAY,CAAC,OAAO,CAAC;aACrB,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YACxB,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YAC5C,MAAM,KAAK,CAAC;QACd,CAAC,CAAC,CAAC;QACL,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACjD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../data/documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../data/documents/documentKinds\";\nimport type {\n DocumentSummaryList,\n DocumentSummarySort,\n DocumentSummarySortDirection,\n DocumentSummarySortKey,\n ListDocumentSummariesInput,\n} from \"../data/persistence/documents/types\";\nimport type { ExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n DEFAULT_DOCUMENT_ID as DEFAULT_LOCAL_DOCUMENT_ID,\n type DocumentStore,\n type DocumentsRuntime,\n openDocumentStore,\n type PersistedDocumentListener,\n subscribeToPersistedDocuments,\n} from \"../stores/documents\";\nimport { emitPersistedDocumentDeletion } from \"../stores/documents/registry\";\nimport {\n createDocumentsWorkflowRuntime,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n reclaimDocumentOrphanBlobs,\n} from \"../workflows/documents\";\nimport type { InternalRuntime } from \"./workflowRuntime\";\n\nexport type {\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentContextValue,\n DocumentStore,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"../stores/documents\";\n\nexport type DocumentSortDirection = DocumentSummarySortDirection;\nexport type DocumentSortKey = DocumentSummarySortKey;\n\nexport type DocumentSort = DocumentSummarySort;\n\nexport interface ListDocumentsInput extends ListDocumentSummariesInput {}\n\nexport type DocumentList = DocumentSummaryList;\n\nexport { DEFAULT_LOCAL_DOCUMENT_ID as DEFAULT_DOCUMENT_ID };\n\nexport interface OpenDocumentInput {\n readonly containerId?: string | null | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n readonly initialText?: string | undefined;\n readonly localId?: string | undefined;\n}\n\nexport interface OpenDocumentOptions {\n readonly remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n readonly workflowRuntime?: DocumentsRuntime | undefined;\n}\n\nexport interface DocumentSubscriptionOptions {\n readonly containerId?: string | null | undefined;\n}\n\nexport interface Documents {\n delete(localId: string): Promise<boolean>;\n findLocalIdByDocumentId(documentId: string): Promise<string | null>;\n list(input?: ListDocumentsInput | undefined): Promise<DocumentList | null>;\n open(\n input?: OpenDocumentInput | undefined,\n options?: OpenDocumentOptions | undefined,\n ): DocumentStore;\n subscribe(\n listener: PersistedDocumentListener,\n options?: DocumentSubscriptionOptions | undefined,\n ): () => void;\n workflowRuntime(containerId?: string | null | undefined): DocumentsRuntime;\n}\n\ninterface DocumentsDependencies {\n getDefaultContainerId: () => string | null;\n runtime: InternalRuntime;\n}\n\nexport function createDocuments(\n dependencies: DocumentsDependencies,\n): Documents {\n return new DocumentsService(dependencies);\n}\n\nclass DocumentsService implements Documents {\n private readonly schemaEnsuresByExecSql = new WeakMap<\n ExecSql,\n Promise<void>\n >();\n\n constructor(private readonly dependencies: DocumentsDependencies) {}\n\n async delete(localId: string): Promise<boolean> {\n const runtime = this.workflowRuntime();\n if (runtime.infra.dbStatus !== \"ready\") {\n return false;\n }\n\n const deleted = await deletePersistedDocument({\n documentProjectors: runtime.infra.documentProjectors,\n execSql: runtime.infra.execSql,\n localId,\n persistence: defaultDocumentsPersistence,\n });\n if (!deleted) return false;\n void reclaimDocumentOrphanBlobs(runtime);\n emitPersistedDocumentDeletion(runtime.state.domainScope, localId);\n return true;\n }\n\n async findLocalIdByDocumentId(documentId: string): Promise<string | null> {\n const runtime = this.dependencies.runtime.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return defaultDocumentsPersistence.findLocalIdByDocumentId(\n runtime.infra.execSql,\n documentId,\n );\n }\n\n async list(input: ListDocumentsInput = {}): Promise<DocumentList | null> {\n const runtime = this.dependencies.runtime.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return defaultDocumentsPersistence.listDocumentSummaries(\n runtime.infra.execSql,\n input,\n );\n }\n\n workflowRuntime(\n containerId = this.dependencies.getDefaultContainerId(),\n ): DocumentsRuntime {\n const input = this.dependencies.runtime.workflowInput(containerId);\n return createDocumentsWorkflowRuntime(input);\n }\n\n open(\n input: OpenDocumentInput = {},\n options: OpenDocumentOptions = {},\n ): DocumentStore {\n const {\n containerId,\n documentId = null,\n initialDocumentKind = DEFAULT_DOCUMENT_KIND,\n initialText = \"\",\n localId = DEFAULT_LOCAL_DOCUMENT_ID,\n } = input;\n const runtime =\n options.workflowRuntime ?? this.workflowRuntime(containerId);\n return openDocumentStore(\n runtime.state.domainScope,\n localId,\n runtime,\n documentId,\n initialText,\n initialDocumentKind,\n { remoteSyncMode: options.remoteSyncMode },\n );\n }\n\n subscribe(\n listener: PersistedDocumentListener,\n options: DocumentSubscriptionOptions = {},\n ): () => void {\n return subscribeToPersistedDocuments(\n this.dependencies.runtime.workflowInput(options.containerId).state\n .domainScope,\n listener,\n );\n }\n\n private ensureSchema(execSql: ExecSql): Promise<void> {\n const existing = this.schemaEnsuresByExecSql.get(execSql);\n if (existing) {\n return existing;\n }\n\n const ensure = defaultDocumentsPersistence\n .ensureSchema(execSql)\n .catch((error: unknown) => {\n this.schemaEnsuresByExecSql.delete(execSql);\n throw error;\n });\n this.schemaEnsuresByExecSql.set(execSql, ensure);\n return ensure;\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"identity.js","sourceRoot":"","sources":["identity.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EAExB,sCAAsC,EAEtC,aAAa,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EACL,wBAAwB,EAExB,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AA2DlD,MAAM,UAAU,cAAc,CAC5B,UAA2B,EAAE,EAC7B,iBAA8D,EAC9D,GAA8B,EAC9B,eAAqC,EAAE;IAEvC,OAAO,IAAI,eAAe,CAAC,OAAO,EAAE,iBAAiB,EAAE,GAAG,EAAE,YAAY,CAAC,CAAC;AAC5E,CAAC;AAED,MAAM,eAAe;IAUA;IAGA;IACA;IAbX,yBAAyB,CAA8B;IAC9C,SAAS,GAAG,iBAAiB,EAAE,CAAC;IACzC,eAAe,CAAgB;IAC/B,uBAAuB,CAAgB;IACvC,mBAAmB,CAAwB;IAC3C,aAAa,CAAmB;IAExC,YACE,UAA2B,EAAE,EACZ,iBAER,EACQ,GAA8B,EAC9B,YAAkC;QAJlC,sBAAiB,GAAjB,iBAAiB,CAEzB;QACQ,QAAG,GAAH,GAAG,CAA2B;QAC9B,iBAAY,GAAZ,YAAY,CAAsB;QAEnD,IAAI,CAAC,yBAAyB,GAAG,OAAO,CAAC,oBAAoB,IAAI,IAAI,CAAC;QACtE,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,UAAU,IAAI,IAAI,CAAC;QAClD,IAAI,CAAC,uBAAuB,GAAG,OAAO,CAA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;YACvE,gBAAgB,CAAC,cAAc,KAAK,YAAY,CAAC,cAAc,EAC/D,CAAC;YACD,OAAO;QACT,CAAC;QAED,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;QAClC,IAAI,CAAC,iBAAiB,CAAC,YAAY,CAAC,kBAAkB,CAAC,CAAC;QACxD,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import {\n createIdentitySeedPhrase,\n type EncapsulationKeyPair,\n generateIdentityKeyPairsFromSeedPhrase,\n type SigningKeyPair,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport { errorMessage } from \"../data/errorMessage\";\nimport {\n createIdentityKeyPackage,\n type IdentityKeyPackage,\n parseIdentityKeyPackage,\n} from \"./identityKeyPackage\";\nimport { createListenerSet } from \"./listenerSet\";\n\nexport interface IdentityOptions {\n encapsulationKeyPair?: EncapsulationKeyPair | null | undefined;\n seedPhrase?: string | null | undefined;\n signingFingerprint?: string | null | undefined;\n signingKeyPair?: SigningKeyPair | null | undefined;\n}\n\nexport interface IdentitySnapshot {\n encapsulationKeyPair: EncapsulationKeyPair | null;\n seedPhrase: string | null;\n signingFingerprint: string | null;\n signingKeyPair: SigningKeyPair | null;\n}\n\nexport interface IdentityGenerationResult extends IdentitySnapshot {\n rootContainerCreated: boolean;\n rootContainerId: string;\n userId: string | null;\n}\n\nexport type IdentityListener = () => void;\n\nexport interface Identity {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n readonly seedPhrase: string | null;\n readonly signingFingerprint: string | null;\n readonly signingKeyPair: SigningKeyPair | null;\n readonly snapshot: IdentitySnapshot;\n destroy(): void;\n exportKeyPackage(): Promise<IdentityKeyPackage>;\n generate(): Promise<IdentityGenerationResult>;\n importKeyPackage(keyPackage: unknown): Promise<IdentitySnapshot>;\n importSeedPhrase(seedPhrase: string): Promise<IdentitySnapshot>;\n requireSigningKeyPair(operation?: string): SigningKeyPair;\n refreshSigningFingerprint(): Promise<string | null>;\n setKeyPairs(options: {\n encapsulationKeyPair: EncapsulationKeyPair | null;\n seedPhrase?: string | null | undefined;\n signingFingerprint?: string | null | undefined;\n signingKeyPair: SigningKeyPair | null;\n }): Promise<IdentitySnapshot>;\n subscribe(listener: IdentityListener): () => void;\n}\n\ninterface IdentityGenerationContext {\n rootContainerCreated: boolean;\n rootContainerId: string;\n userId: string | null;\n}\n\ninterface IdentityRuntimeHooks {\n bootstrapLocalRootContainer?:\n | (() => Promise<{ containerId: string; created: boolean }>)\n | undefined;\n getUserId?: (() => string | null) | undefined;\n}\n\nexport function createIdentity(\n options: IdentityOptions = {},\n onIdentityChanged: (signingFingerprint: string | null) => void,\n log: (message: string) => void,\n runtimeHooks: IdentityRuntimeHooks = {},\n): Identity {\n return new IdentityService(options, onIdentityChanged, log, runtimeHooks);\n}\n\nclass IdentityService implements Identity {\n private encapsulationKeyPairValue: EncapsulationKeyPair | null;\n private readonly listeners = createListenerSet();\n private seedPhraseValue: string | null;\n private signingFingerprintValue: string | null;\n private signingKeyPairValue: SigningKeyPair | null;\n private snapshotValue: IdentitySnapshot;\n\n constructor(\n options: IdentityOptions = {},\n private readonly onIdentityChanged: (\n signingFingerprint: string | null,\n ) => void,\n private readonly log: (message: string) => void,\n private readonly runtimeHooks: IdentityRuntimeHooks,\n ) {\n this.encapsulationKeyPairValue = options.encapsulationKeyPair ?? null;\n this.seedPhraseValue = options.seedPhrase ?? null;\n this.signingFingerprintValue = options.signingFingerprint ?? null;\n this.signingKeyPairValue = options.signingKeyPair ?? null;\n this.snapshotValue = this.createSnapshot();\n this.onIdentityChanged(this.signingFingerprintValue);\n }\n\n get encapsulationKeyPair(): EncapsulationKeyPair | null {\n return this.encapsulationKeyPairValue;\n }\n\n get seedPhrase(): string | null {\n return this.seedPhraseValue;\n }\n\n get signingFingerprint(): string | null {\n return this.signingFingerprintValue;\n }\n\n get signingKeyPair(): SigningKeyPair | null {\n return this.signingKeyPairValue;\n }\n\n get snapshot(): IdentitySnapshot {\n return this.snapshotValue;\n }\n\n destroy(): void {\n this.encapsulationKeyPairValue = null;\n this.seedPhraseValue = null;\n this.signingFingerprintValue = null;\n this.signingKeyPairValue = null;\n this.publishSnapshot();\n this.log(\"Key pair destroyed\");\n }\n\n exportKeyPackage(): Promise<IdentityKeyPackage> {\n return createIdentityKeyPackage(this.snapshot);\n }\n\n async generate(): Promise<IdentityGenerationResult> {\n const seedPhrase = createIdentitySeedPhrase();\n const { encapsulationKeyPair, signingKeyPair } =\n generateIdentityKeyPairsFromSeedPhrase(seedPhrase);\n const signingFingerprint = await toFingerprint(\n signingKeyPair.signingPublicKey,\n );\n const generationContext = await this.createGenerationContext();\n\n this.signingKeyPairValue = signingKeyPair;\n this.encapsulationKeyPairValue = encapsulationKeyPair;\n this.seedPhraseValue = seedPhrase;\n this.signingFingerprintValue = signingFingerprint;\n this.publishSnapshot();\n this.log(\"Key pair generated\");\n return {\n ...this.snapshot,\n ...generationContext,\n };\n }\n\n async importKeyPackage(keyPackage: unknown): Promise<IdentitySnapshot> {\n const parsed = await parseIdentityKeyPackage(keyPackage);\n this.encapsulationKeyPairValue = parsed.encapsulationKeyPair;\n this.seedPhraseValue = parsed.package.seedPhrase ?? null;\n this.signingKeyPairValue = parsed.signingKeyPair;\n this.signingFingerprintValue = parsed.package.signingFingerprint;\n this.publishSnapshot();\n this.log(\"Key package imported\");\n return this.snapshot;\n }\n\n async importSeedPhrase(seedPhrase: string): Promise<IdentitySnapshot> {\n const derived = generateIdentityKeyPairsFromSeedPhrase(seedPhrase);\n this.encapsulationKeyPairValue = derived.encapsulationKeyPair;\n this.seedPhraseValue = derived.seedPhrase;\n this.signingKeyPairValue = derived.signingKeyPair;\n this.signingFingerprintValue = await toFingerprint(\n derived.signingKeyPair.signingPublicKey,\n );\n this.publishSnapshot();\n this.log(\"Seed phrase imported\");\n return this.snapshot;\n }\n\n requireSigningKeyPair(operation = \"This operation\"): SigningKeyPair {\n if (!this.signingKeyPairValue) {\n throw new Error(`${operation} requires a signing key pair.`);\n }\n\n return this.signingKeyPairValue;\n }\n\n async refreshSigningFingerprint(): Promise<string | null> {\n if (!this.signingKeyPairValue) {\n this.signingFingerprintValue = null;\n this.publishSnapshot();\n return null;\n }\n\n this.signingFingerprintValue = await toFingerprint(\n this.signingKeyPairValue.signingPublicKey,\n );\n this.publishSnapshot();\n return this.signingFingerprintValue;\n }\n\n async setKeyPairs(options: {\n encapsulationKeyPair: EncapsulationKeyPair | null;\n seedPhrase?: string | null | undefined;\n signingFingerprint?: string | null | undefined;\n signingKeyPair: SigningKeyPair | null;\n }): Promise<IdentitySnapshot> {\n this.encapsulationKeyPairValue = options.encapsulationKeyPair;\n this.seedPhraseValue = options.seedPhrase ?? null;\n this.signingKeyPairValue = options.signingKeyPair;\n this.signingFingerprintValue = options.signingFingerprint ?? null;\n\n if (!this.signingFingerprintValue) {\n await this.refreshSigningFingerprint();\n } else {\n this.publishSnapshot();\n }\n\n return this.snapshot;\n }\n\n subscribe = (listener: IdentityListener): (() => void) =>\n this.listeners.subscribe(listener);\n\n private createSnapshot(): IdentitySnapshot {\n return {\n encapsulationKeyPair: this.encapsulationKeyPairValue,\n seedPhrase: this.seedPhraseValue,\n signingFingerprint: this.signingFingerprintValue,\n signingKeyPair: this.signingKeyPairValue,\n };\n }\n\n private async createGenerationContext(): Promise<IdentityGenerationContext> {\n try {\n const bootstrapLocalRootContainer =\n this.runtimeHooks.bootstrapLocalRootContainer;\n if (!bootstrapLocalRootContainer) {\n throw new Error(\n \"identity.generate requires local root container bootstrap.\",\n );\n }\n\n const rootContainer = await bootstrapLocalRootContainer();\n\n return {\n rootContainerCreated: rootContainer.created,\n rootContainerId: rootContainer.containerId,\n userId: this.runtimeHooks.getUserId?.() ?? null,\n };\n } catch (error: unknown) {\n const message = errorMessage(error);\n this.log(`Root container bootstrap failed: ${message}`);\n throw error;\n }\n }\n\n private publishSnapshot(): void {\n const nextSnapshot = this.createSnapshot();\n const previousSnapshot = this.snapshotValue;\n if (\n previousSnapshot.encapsulationKeyPair ===\n nextSnapshot.encapsulationKeyPair &&\n previousSnapshot.seedPhrase === nextSnapshot.seedPhrase &&\n previousSnapshot.signingFingerprint === nextSnapshot.signingFingerprint &&\n previousSnapshot.signingKeyPair === nextSnapshot.signingKeyPair\n ) {\n return;\n }\n\n this.snapshotValue = nextSnapshot;\n this.onIdentityChanged(nextSnapshot.signingFingerprint);\n this.listeners.notify();\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"identityKeyPackage.js","sourceRoot":"","sources":["identityKeyPackage.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAElB,oBAAoB,EACpB,sCAAsC,EACtC,yBAAyB,EACzB,yBAAyB,EACzB,2BAA2B,EAC3B,2BAA2B,EAE3B,IAAI,EACJ,aAAa,EACb,MAAM,GACP,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAEpE,MAAM,CAAC,MAAM,2BAA2B,GAAG,gCAAgC,CAAC;AAE5E,MAAM,yBAAyB,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CACxD,sCAAsC,CACvC,CAAC;AAwBF,SAAS,kBAAkB,CACzB,KAAa,EACb,QAAgB,EAChB,KAAa;IAEb,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAC9C,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1D,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,eAAe,CAAC,CAAC;IACzE,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,SAAS,0BAA0B,CACjC,KAAa,EACb,QAAgB,EAChB,KAAa;IAEb,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,E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AAM,0BAA0B,GAAG,MAAM,aAAa,CACpD,cAAc,CAAC,gBAAgB,CAChC,CAAC;IACF,IAAI,0BAA0B,KAAK,kBAAkB,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CACb,kFAAkF,CACnF,CAAC;IACJ,CAAC;IACD,2BAA2B,CAAC,cAAc,CAAC,CAAC;IAE5C,MAAM,oBAAoB,GAAG,wBAAwB,CACnD,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,sBAAsB,CAAC,CAC3C,CAAC;IACF,MAAM,iCAAiC,CAAC,oBAAoB,CAAC,CAAC;IAC9D,MAAM,UAAU,GAAG,sBAAsB,CAAC;QACxC,oBAAoB;QACpB,UAAU,EAAE,0BAA0B,CAAC,KAAK,EAAE,YAAY,EAAE,aAAa,CAAC;QAC1E,cAAc;KACf,CAAC,CAAC;IAEH,OAAO;QACL,oBAAoB;QACpB,OAAO,EAAE;YACP,SAAS,EAAE,kBAAkB,CAAC,KAAK,EAAE,WAAW,EAAE,YAAY,CAAC;YAC/D,oBAAoB,EAAE;gBACpB,SAAS,EAAE,aAAa,CAAC,oBAAoB,CAAC,SAAS,CAAC;gBACxD,SAAS,EAAE,aAAa,CAAC,oBAAoB,CAAC,SAAS,CAAC;aACzD;YACD,MAAM;YACN,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACrC,kBAAkB;YAClB,cAAc,EAAE;gBACd,iBAAiB,EAAE,aAAa,CAAC,cAAc,CAAC,iBAAiB,CAAC;gBAClE,gBAAgB,EAAE,aAAa,CAAC,cAAc,CAAC,gBAAgB,CAAC;aACjE;YACD,OAAO;SACR;QACD,cAAc;KACf,CAAC;AACJ,CAAC","sourcesContent":["import {\n decryptAsRecipient,\n type EncapsulationKeyPair,\n encryptForRecipients,\n generateIdentityKeyPairsFromSeedPhrase,\n ML_DSA87_PUBLIC_KEY_BYTES,\n ML_DSA87_SECRET_KEY_BYTES,\n ML_KEM1024_PUBLIC_KEY_BYTES,\n ML_KEM1024_SECRET_KEY_BYTES,\n type SigningKeyPair,\n sign,\n toFingerprint,\n verify,\n} from \"@tearleads/crypto\";\nimport { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { isPlainObject } from \"@tearleads/validators/isPlainObject\";\n\nexport const IDENTITY_KEY_PACKAGE_FORMAT = \"tearleads.identity-key-package\";\n\nconst KEY_PACKAGE_PROBE_MESSAGE = new TextEncoder().encode(\n \"tearleads.identity-key-package.probe\",\n);\n\nexport interface IdentityKeyPackage {\n readonly createdAt: string;\n readonly encapsulationKeyPair: {\n readonly publicKey: string;\n readonly secretKey: string;\n };\n readonly format: typeof IDENTITY_KEY_PACKAGE_FORMAT;\n readonly seedPhrase?: string | undefined;\n readonly signingFingerprint: string;\n readonly signingKeyPair: {\n readonly signingPrivateKey: string;\n readonly signingPublicKey: string;\n };\n readonly version: 1;\n}\n\ninterface ParsedIdentityKeyPackage {\n readonly encapsulationKeyPair: EncapsulationKeyPair;\n readonly package: IdentityKeyPackage;\n readonly signingKeyPair: SigningKeyPair;\n}\n\nfunction readStringProperty(\n value: object,\n property: string,\n label: string,\n): string {\n const rawValue = Reflect.get(value, property);\n if (typeof rawValue !== \"string\" || rawValue.length === 0) {\n throw new Error(`Invalid identity key package: ${label} is required.`);\n }\n\n return rawValue;\n}\n\nfunction readOptionalStringProperty(\n value: object,\n property: string,\n label: string,\n): string | null {\n const rawValue = Reflect.get(value, property);\n if (rawValue === undefined || rawValue === null) {\n return null;\n }\n if (typeof rawValue !== \"string\" || rawValue.length === 0) {\n throw new Error(`Invalid identity key package: ${label} must be a string.`);\n }\n\n return rawValue;\n}\n\nfunction readBase64Bytes(input: {\n expectedLength: number;\n label: string;\n value: string;\n}): Uint8Array {\n let bytes: Uint8Array;\n try {\n bytes = base64ToBytes(input.value);\n } catch (error) {\n throw new Error(\n `Invalid identity key package: ${input.label} must be base64.`,\n { cause: error },\n );\n }\n\n if (bytes.length !== input.expectedLength) {\n throw new Error(\n `Invalid identity key package: ${input.label} has ${bytes.length} bytes, expected ${input.expectedLength}.`,\n );\n }\n\n return bytes;\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n let result = 0;\n for (let index = 0; index < left.length; index += 1) {\n result |= (left[index] ?? 0) ^ (right[index] ?? 0);\n }\n return result === 0;\n}\n\nfunction readMatchingSeedPhrase(input: {\n encapsulationKeyPair: EncapsulationKeyPair;\n seedPhrase: string | null;\n signingKeyPair: SigningKeyPair;\n}): string | undefined {\n if (!input.seedPhrase) {\n return undefined;\n }\n\n let derived: ReturnType<typeof generateIdentityKeyPairsFromSeedPhrase>;\n try {\n derived = generateIdentityKeyPairsFromSeedPhrase(input.seedPhrase);\n } catch (error) {\n throw new Error(\"Invalid identity key package: seed phrase is invalid.\", {\n cause: error,\n });\n }\n\n if (\n !bytesEqual(\n derived.signingKeyPair.signingPrivateKey,\n input.signingKeyPair.signingPrivateKey,\n ) ||\n !bytesEqual(\n derived.signingKeyPair.signingPublicKey,\n input.signingKeyPair.signingPublicKey,\n ) ||\n !bytesEqual(\n derived.encapsulationKeyPair.secretKey,\n input.encapsulationKeyPair.secretKey,\n ) ||\n !bytesEqual(\n derived.encapsulationKeyPair.publicKey,\n input.encapsulationKeyPair.publicKey,\n )\n ) {\n throw new Error(\n \"Invalid identity key package: seed phrase does not match the key pairs.\",\n );\n }\n\n return derived.seedPhrase;\n}\n\nfunction readSigningKeyPair(value: unknown): SigningKeyPair {\n if (!isPlainObject(value)) {\n throw new Error(\n \"Invalid identity key package: signingKeyPair is required.\",\n );\n }\n\n return {\n signingPrivateKey: readBase64Bytes({\n expectedLength: ML_DSA87_SECRET_KEY_BYTES,\n label: \"signing private key\",\n value: readStringProperty(\n value,\n \"signingPrivateKey\",\n \"signing private key\",\n ),\n }),\n signingPublicKey: readBase64Bytes({\n expectedLength: ML_DSA87_PUBLIC_KEY_BYTES,\n label: \"signing public key\",\n value: readStringProperty(\n value,\n \"signingPublicKey\",\n \"signing public key\",\n ),\n }),\n };\n}\n\nfunction readEncapsulationKeyPair(value: unknown): EncapsulationKeyPair {\n if (!isPlainObject(value)) {\n throw new Error(\n \"Invalid identity key package: encapsulationKeyPair is required.\",\n );\n }\n\n return {\n publicKey: readBase64Bytes({\n expectedLength: ML_KEM1024_PUBLIC_KEY_BYTES,\n label: \"encapsulation public key\",\n value: readStringProperty(value, \"publicKey\", \"encapsulation public key\"),\n }),\n secretKey: readBase64Bytes({\n expectedLength: ML_KEM1024_SECRET_KEY_BYTES,\n label: \"encapsulation secret key\",\n value: readStringProperty(value, \"secretKey\", \"encapsulation secret key\"),\n }),\n };\n}\n\nfunction assertSigningKeyPairMatches(signingKeyPair: SigningKeyPair): void {\n let signature: Uint8Array;\n try {\n signature = sign(\n KEY_PACKAGE_PROBE_MESSAGE,\n signingKeyPair.signingPrivateKey,\n );\n } catch (error) {\n throw new Error(\n \"Invalid identity key package: signing private key could not sign.\",\n { cause: error },\n );\n }\n\n if (\n !verify(\n signature,\n KEY_PACKAGE_PROBE_MESSAGE,\n signingKeyPair.signingPublicKey,\n )\n ) {\n throw new Error(\n \"Invalid identity key package: signing private key does not match the public key.\",\n );\n }\n}\n\nasync function assertEncapsulationKeyPairMatches(\n encapsulationKeyPair: EncapsulationKeyPair,\n): Promise<void> {\n try {\n const envelope = await encryptForRecipients(KEY_PACKAGE_PROBE_MESSAGE, [\n encapsulationKeyPair.publicKey,\n ]);\n const decrypted = await decryptAsRecipient(\n envelope,\n encapsulationKeyPair.secretKey,\n );\n\n if (\n decrypted.length !== KEY_PACKAGE_PROBE_MESSAGE.length ||\n decrypted.some((byte, index) => byte !== KEY_PACKAGE_PROBE_MESSAGE[index])\n ) {\n throw new Error(\"probe plaintext mismatch\");\n }\n } catch (error) {\n throw new Error(\n \"Invalid identity key package: encapsulation secret key does not match the public key.\",\n { cause: error },\n );\n }\n}\n\nexport async function createIdentityKeyPackage(input: {\n encapsulationKeyPair: EncapsulationKeyPair | null;\n seedPhrase?: string | null | undefined;\n signingFingerprint: string | null;\n signingKeyPair: SigningKeyPair | null;\n}): Promise<IdentityKeyPackage> {\n if (!input.signingKeyPair || !input.encapsulationKeyPair) {\n throw new Error(\"Cannot export an identity key package without key pairs.\");\n }\n\n const signingFingerprint =\n input.signingFingerprint ??\n (await toFingerprint(input.signingKeyPair.signingPublicKey));\n const seedPhrase = readMatchingSeedPhrase({\n encapsulationKeyPair: input.encapsulationKeyPair,\n seedPhrase: input.seedPhrase ?? null,\n signingKeyPair: input.signingKeyPair,\n });\n\n return {\n createdAt: new Date().toISOString(),\n encapsulationKeyPair: {\n publicKey: bytesToBase64(input.encapsulationKeyPair.publicKey),\n secretKey: bytesToBase64(input.encapsulationKeyPair.secretKey),\n },\n format: IDENTITY_KEY_PACKAGE_FORMAT,\n ...(seedPhrase ? { seedPhrase } : {}),\n signingFingerprint,\n signingKeyPair: {\n signingPrivateKey: bytesToBase64(input.signingKeyPair.signingPrivateKey),\n signingPublicKey: bytesToBase64(input.signingKeyPair.signingPublicKey),\n },\n version: 1,\n };\n}\n\nexport async function parseIdentityKeyPackage(\n value: unknown,\n): Promise<ParsedIdentityKeyPackage> {\n if (!isPlainObject(value)) {\n throw new Error(\"Invalid identity key package: expected an object.\");\n }\n\n const format = readStringProperty(value, \"format\", \"format\");\n if (format !== IDENTITY_KEY_PACKAGE_FORMAT) {\n throw new Error(\"Invalid identity key package: unsupported format.\");\n }\n\n const version = Reflect.get(value, \"version\");\n if (version !== 1) {\n throw new Error(\"Invalid identity key package: unsupported version.\");\n }\n\n const signingFingerprint = readStringProperty(\n value,\n \"signingFingerprint\",\n \"signing fingerprint\",\n );\n const signingKeyPair = readSigningKeyPair(\n Reflect.get(value, \"signingKeyPair\"),\n );\n const computedSigningFingerprint = await toFingerprint(\n signingKeyPair.signingPublicKey,\n );\n if (computedSigningFingerprint !== signingFingerprint) {\n throw new Error(\n \"Invalid identity key package: signing fingerprint does not match the public key.\",\n );\n }\n assertSigningKeyPairMatches(signingKeyPair);\n\n const encapsulationKeyPair = readEncapsulationKeyPair(\n Reflect.get(value, \"encapsulationKeyPair\"),\n );\n await assertEncapsulationKeyPairMatches(encapsulationKeyPair);\n const seedPhrase = readMatchingSeedPhrase({\n encapsulationKeyPair,\n seedPhrase: readOptionalStringProperty(value, \"seedPhrase\", \"seed phrase\"),\n signingKeyPair,\n });\n\n return {\n encapsulationKeyPair,\n package: {\n createdAt: readStringProperty(value, \"createdAt\", \"created at\"),\n encapsulationKeyPair: {\n publicKey: bytesToBase64(encapsulationKeyPair.publicKey),\n secretKey: bytesToBase64(encapsulationKeyPair.secretKey),\n },\n format,\n ...(seedPhrase ? { seedPhrase } : {}),\n signingFingerprint,\n signingKeyPair: {\n signingPrivateKey: bytesToBase64(signingKeyPair.signingPrivateKey),\n signingPublicKey: bytesToBase64(signingKeyPair.signingPublicKey),\n },\n version,\n },\n signingKeyPair,\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalHistoryProtection.js","sourceRoot":"","sources":["principalHistoryProtection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,4CAA4C,CAAC;AAkBjG,SAAS,YAAY,CACnB,CAAgC,EAChC,CAAyB;IAEzB,OAAO,CACL,CAAC,EAAE,QAAQ,KAAK,CAAC,CAAC,QAAQ;QAC1B,CAAC,CAAC,mBAAmB,KAAK,CAAC,CAAC,mBAAmB;QAC/C,CAAC,CAAC,kBAAkB,KAAK,CAAC,CAAC,kBAAkB,CAC9C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,uCAAuC,CAAC,KAGvD;IACC,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,IAAI,SAAS,GACX,IAAI,CAAC;IACP,MAAM,cAAc,GAAG,GAAG,EAAE;QAC1B,SAAS,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC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SAAS,KAAK;4BACZ,KAAK;4BACL,GAAG,EAAE,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;yBAChD,CAAC;wBACF,GAAG,GAAG,IAAI,UAAU,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;oBACtC,CAAC;oBACD,IAAI,CAAC,CAAC,GAAG,YAAY,UAAU,CAAC,IAAI,GAAG,CAAC,UAAU,KAAK,EAAE;wBACvD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,6DAA6D,CAC9D,CAAC;oBACJ,mCAAmC,CAAC,YAAY,CAAC,CAAC;oBAClD,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC;wBAC7B,UAAU,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE;wBACtC,YAAY;qBACb,CAAC,CAAC;oBACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;oBAClD,OAAO,MAAM,CAAC;gBAChB,CAAC;wBAAS,CAAC;oBACT,IAAI,GAAG,YAAY,UAAU;wBAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBAC7C,CAAC;YACH,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../data/principals/principalHistoryProtection\";\n\nexport interface PrincipalHistoryKeyScope {\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n}\n\n/** Return a fresh owned 32-byte key. The SDK clears it after each operation. */\nexport type PrincipalHistoryKeyProvider = (\n scope: PrincipalHistoryKeyScope,\n) => Promise<Uint8Array>;\n\ninterface RuntimeProtectionScope extends PrincipalHistoryKeyScope {\n readonly database: object;\n readonly generation: number;\n}\n\nfunction sameKeyScope(\n a: RuntimeProtectionScope | null,\n b: RuntimeProtectionScope,\n): boolean {\n return (\n a?.database === b.database &&\n a.identityTrustDomain === b.identityTrustDomain &&\n a.signingFingerprint === b.signingFingerprint\n );\n}\n\nexport function createPrincipalHistoryProtectionCustody(input: {\n readonly readScope: () => RuntimeProtectionScope | null;\n readonly keyProvider?: PrincipalHistoryKeyProvider | undefined;\n}) {\n let retirement = 0;\n let ephemeral: { scope: RuntimeProtectionScope; key: Uint8Array } | null =\n null;\n const clearEphemeral = () => {\n ephemeral?.key.fill(0);\n ephemeral = null;\n };\n return {\n retire() {\n retirement += 1;\n clearEphemeral();\n },\n bind(): PrincipalHistoryProtectionLease | undefined {\n const scope = input.readScope();\n if (!scope) {\n clearEphemeral();\n return undefined;\n }\n if (ephemeral && !sameKeyScope(ephemeral.scope, scope)) clearEphemeral();\n const boundRetirement = retirement;\n const boundGeneration = scope.generation;\n const stillCurrent = () => {\n const current = input.readScope();\n return (\n retirement === boundRetirement &&\n current?.generation === boundGeneration &&\n sameKeyScope(current, scope)\n );\n };\n const context = JSON.stringify([\n \"tearleads.sdk.principal-history.runtime.v1\",\n scope.identityTrustDomain,\n scope.signingFingerprint,\n ]);\n return async (operation) => {\n assertProjectionVerificationCurrent(stillCurrent);\n let key: Uint8Array | undefined;\n try {\n if (input.keyProvider) {\n key = await input.keyProvider({\n identityTrustDomain: scope.identityTrustDomain,\n signingFingerprint: scope.signingFingerprint,\n });\n } else {\n ephemeral ??= {\n scope,\n key: crypto.getRandomValues(new Uint8Array(32)),\n };\n key = new Uint8Array(ephemeral.key);\n }\n if (!(key instanceof Uint8Array) || key.byteLength !== 32)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Principal history key provider must return 32 private bytes\",\n );\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await operation({\n protection: { localKey: key, context },\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n } finally {\n if (key instanceof Uint8Array) key.fill(0);\n }\n };\n },\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalMutationApi.js","sourceRoot":"","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AG,CAAC,QAAQ,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YACrD,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC,CAAC;IACH,6EAA6E;IAC7E,uEAAuE;IACvE,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,kBAAkB,CAAC,GAAc;IACxC,OAAO,CACL,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,8BAA8B,CAAC,KAAK,UAAU;QACtE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,oCAAoC,CAAC,KAAK,UAAU,CAC7E,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n type PrincipalMutationRecoveryApi,\n readJournaledPrincipalMutation,\n} from \"../workflows/organizations/principalMutationJournalManagement\";\nimport { recoverJournaledPrincipalMutation } from \"../workflows/organizations/principalMutationJournalSession\";\nimport { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\nimport {\n createJournaledPrincipalMutations,\n dispatchAuthoredPrincipalMutation,\n type JournaledPrincipalMutationMethods,\n} from \"./principalMutationDispatch\";\n\nexport interface PrincipalMutationRuntimeScope {\n readonly database: object;\n readonly execSql: ExecSql;\n readonly generation: number;\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}\n\nfunction sameScope(\n current: PrincipalMutationRuntimeScope | null,\n bound: PrincipalMutationRuntimeScope | null,\n): boolean {\n if (!current || !bound) return current === bound;\n return (\n current.database === bound.database &&\n current.execSql === bound.execSql &&\n current.generation === bound.generation &&\n current.identityTrustDomain === bound.identityTrustDomain &&\n current.signingFingerprint === bound.signingFingerprint &&\n current.signingKeyPair === bound.signingKeyPair &&\n current.userId === bound.userId\n );\n}\n\nexport type PrincipalMutationApi = ApiClient & PrincipalMutationRecoveryApi;\ntype MutationOverrides = JournaledPrincipalMutationMethods &\n PrincipalMutationRecoveryApi;\n\ninterface PrincipalMutationApiCustodyInput {\n readonly api: ApiClient;\n readonly readScope: () => PrincipalMutationRuntimeScope | null;\n readonly principalMutationTimeoutMs?: number | undefined;\n}\n\nfunction mutationContext(\n input: PrincipalMutationApiCustodyInput,\n scope: PrincipalMutationRuntimeScope | null,\n organizationId: string,\n) {\n if (!scope)\n throw new Error(\n \"Principal mutations require an authenticated signing identity, a trusted API origin and durable local storage\",\n );\n return {\n execSql: scope.execSql,\n signingKeyPair: scope.signingKeyPair,\n scope: {\n identityTrustDomain: scope.identityTrustDomain,\n organizationId,\n signingFingerprint: scope.signingFingerprint,\n userId: scope.userId,\n },\n stillCurrent: () => sameScope(input.readScope(), scope),\n };\n}\n\n/** Keep API methods bound to their real receiver and journal principal policy and group lifecycle writes. */\nexport function createPrincipalMutationApiCustody(\n input: PrincipalMutationApiCustodyInput,\n) {\n const dispatch = createPrincipalMutationDispatcher(\n input.principalMutationTimeoutMs,\n );\n let cached: {\n scope: PrincipalMutationRuntimeScope | null;\n api: PrincipalMutationApi;\n } | null = null;\n return {\n bind(): PrincipalMutationApi {\n const scope = input.readScope();\n if (cached && sameScope(scope, cached.scope)) return cached.api;\n const context = (organizationId: string) =>\n mutationContext(input, scope, organizationId);\n const read: PrincipalMutationRecoveryApi[\"readPendingPrincipalMutation\"] =\n async (organizationId) =>\n scope\n ? readJournaledPrincipalMutation(context(organizationId))\n : null;\n const abandon: PrincipalMutationRecoveryApi[\"abandonPendingPrincipalMutation\"] =\n async (organizationId, mutation, acknowledgeUnknownOutcome) =>\n abandonJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n acknowledgeUnknownOutcome,\n });\n const methods = {\n ...createJournaledPrincipalMutations(input.api, context, dispatch),\n discardUnreadablePrincipalMutation: async (\n organizationId,\n recordId,\n acknowledgeUnknownOutcome,\n ) =>\n discardUnreadableJournaledPrincipalMutation({\n ...context(organizationId),\n recordId,\n acknowledgeUnknownOutcome,\n }),\n readPendingPrincipalMutation: read,\n abandonPendingPrincipalMutation: abandon,\n recoverPendingPrincipalMutation: async (organizationId) => {\n await recoverJournaledPrincipalMutation({\n ...context(organizationId),\n submit: (mutation) =>\n dispatch({ reportErrors: false }, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n input.api,\n organizationId,\n mutation,\n dispatchOptions,\n ),\n ),\n });\n },\n } satisfies MutationOverrides;\n const api = bindMutationMethods(input.api, methods);\n cached = { scope, api };\n return api;\n },\n };\n}\n\nfunction bindMutationMethods(\n api: ApiClient,\n methods: MutationOverrides,\n): PrincipalMutationApi {\n const boundMethods = new Map<\n PropertyKey,\n { source: unknown; bound: unknown }\n >();\n const bound = new Proxy(api, {\n get(target, property) {\n if (Object.hasOwn(methods, property))\n return Reflect.get(methods, property);\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n const previous = boundMethods.get(property);\n if (previous?.source === value) return previous.bound;\n const bound = value.bind(target);\n boundMethods.set(property, { source: value, bound });\n return bound;\n },\n });\n // The checked overrides supply the signatures; verify their presence through\n // the reflective boundary before exposing the extended API to callers.\n if (!hasRecoveryMethods(bound))\n throw new Error(\"Principal mutation recovery methods are unavailable\");\n return bound;\n}\n\nfunction hasRecoveryMethods(api: ApiClient): api is PrincipalMutationApi {\n return (\n typeof Reflect.get(api, \"readPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"recoverPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"abandonPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"discardUnreadablePrincipalMutation\") === \"function\"\n );\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"principalMutationDispatch.js","sourceRoot":"","sources":["principalMutationDispatch.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,uCAAuC,EACvC,iCAAiC,EACjC,iCAAiC,EACjC,iCAAiC,GAClC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAEL,gCAAgC,GACjC,MAAM,4DAA4D,CAAC;AAiBpE,mFAAmF;AACnF,MAAM,UAAU,iCAAiC,CAC/C,GAAc,EACd,cAAsB,EACtB,QAAmC,EACnC,UAAgC,EAAE;IAElC,QAAQ,QAAQ,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,wBAAwB,CACjC,cAAc,EACd,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,UAAU;YACb,OAAO,GAAG,CAAC,mCAAmC,CAC5C,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ;YACE,OAAO,mBAAmB,CAAC,QAAQ,CAAC,CAAC;IACzC,CAAC;AACH,CAAC;AAED,SAAS,mBAAmB,CAAC,SAAgB;IAC3C,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,GAAc,EACd,OAEoD,EACpD,QA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AAE,EAC1C,iCAAiC,EACjC,OAAO,CACR,CAAC;IACJ,MAAM,GAAG,GAA0C,CACjD,KAAK,EACL,cAAc,EACd,OAAO,EACP,OAAO,EACP,EAAE,CACF,MAAM,CACJ,cAAc,EACd,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,EAChD,iCAAiC,EACjC,OAAO,CACR,CAAC;IACJ,OAAO;QACL,mCAAmC,EAAE,MAAM;QAC3C,6BAA6B,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAC/C,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QACjC,6BAA6B,EAAE,MAAM;QACrC,uBAAuB,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3E,6BAA6B,EAAE,MAAM;QACrC,uBAAuB,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3E,wBAAwB,EAAE,GAAG;QAC7B,kBAAkB,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;KACpE,CAAC;AACJ,CAAC;AAED,SAAS,QAAQ,CAAI,MAAwB;IAC3C,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;AACxC,CAAC","sourcesContent":["import type {\n ApiClient,\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n isCommitOrganizationGroupPolicyResponse,\n isCreateOrganizationGroupResponse,\n isDeleteOrganizationGroupResponse,\n isPrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport type { AuthoredPrincipalMutation } from \"../data/principals/principalMutationJournal\";\nimport {\n type PrincipalMutationJournalContext,\n submitJournaledPrincipalMutation,\n} from \"../workflows/organizations/principalMutationJournalSession\";\nimport type { PrincipalMutationResponse } from \"../workflows/organizations/principalOperationReceipt\";\n\nimport type { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\n\nexport type JournaledPrincipalMutationMethods = Pick<\n ApiClient,\n | \"commitOrganizationGroupPolicy\"\n | \"commitOrganizationGroupPolicyResult\"\n | \"createOrganizationGroup\"\n | \"createOrganizationGroupResult\"\n | \"deleteOrganizationGroup\"\n | \"deleteOrganizationGroupResult\"\n | \"putPrincipalPolicy\"\n | \"putPrincipalPolicyResult\"\n>;\n\n/** Dispatch the authenticated operation, with no application planning callback. */\nexport function dispatchAuthoredPrincipalMutation(\n api: ApiClient,\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n options: RequestResultOptions = {},\n): Promise<RequestResult<PrincipalMutationResponse>> {\n switch (mutation.kind) {\n case \"organization\":\n return api.putPrincipalPolicyResult(\n \"organization\",\n organizationId,\n mutation.request,\n options,\n );\n case \"group-create\":\n return api.createOrganizationGroupResult(\n organizationId,\n mutation.request,\n options,\n );\n case \"group-delete\":\n return api.deleteOrganizationGroupResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n case \"compound\":\n return api.commitOrganizationGroupPolicyResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n default:\n return unsupportedMutation(mutation);\n }\n}\n\nfunction unsupportedMutation(_mutation: never): never {\n throw new Error(\"Unsupported principal mutation operation\");\n}\n\nexport function createJournaledPrincipalMutations(\n api: ApiClient,\n context: (\n organizationId: string,\n ) => Omit<PrincipalMutationJournalContext, \"submit\">,\n dispatch: ReturnType<typeof createPrincipalMutationDispatcher>,\n): JournaledPrincipalMutationMethods {\n async function submit<T extends PrincipalMutationResponse>(\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n validator: (value: unknown) => value is T,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<T>> {\n const result = await submitJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n submit: (saved) =>\n dispatch(options, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n api,\n organizationId,\n saved,\n dispatchOptions,\n ),\n ),\n });\n if (!result.ok) return result;\n // The session already verified this operation before clearing its row.\n // This check narrows the union for each existing public API signature.\n if (!validator(result.data))\n throw new Error(\"Unexpected principal receipt operation\");\n return { ok: true, data: result.data };\n }\n const commit: ApiClient[\"commitOrganizationGroupPolicyResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"compound\", groupId, request },\n isCommitOrganizationGroupPolicyResponse,\n options,\n );\n const create: ApiClient[\"createOrganizationGroupResult\"] = (\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-create\", groupId: request.groupId, request },\n isCreateOrganizationGroupResponse,\n options,\n );\n const remove: ApiClient[\"deleteOrganizationGroupResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-delete\", groupId, request },\n isDeleteOrganizationGroupResponse,\n options,\n );\n const put: ApiClient[\"putPrincipalPolicyResult\"] = (\n _type,\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"organization\", groupId: null, request },\n isPrincipalPolicyMutationResponse,\n options,\n );\n return {\n commitOrganizationGroupPolicyResult: commit,\n commitOrganizationGroupPolicy: async (...args) =>\n nullable(await commit(...args)),\n createOrganizationGroupResult: create,\n createOrganizationGroup: async (...args) => nullable(await create(...args)),\n deleteOrganizationGroupResult: remove,\n deleteOrganizationGroup: async (...args) => nullable(await remove(...args)),\n putPrincipalPolicyResult: put,\n putPrincipalPolicy: async (...args) => nullable(await put(...args)),\n };\n}\n\nfunction nullable<T>(result: RequestResult<T>): T | null {\n return result.ok ? result.data : null;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reconciledDocumentContentPull.js","sourceRoot":"","sources":["re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AC,WAAW,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC;gBACpE,CAAC;qBAAM,IAAI,aAAa,EAAE,CAAC;oBACzB,oEAAoE;oBACpE,qEAAqE;oBACrE,oEAAoE;oBACpE,qBAAqB;oBACrB,IAAI,CAAC,mCAAmC,CACtC,QAAQ,CAAC,EAAE,EACX,QAAQ,CAAC,UAAU,CACpB,CAAC;gBACJ,CAAC;gBACD,SAAS;YACX,CAAC;YAED,IAAI,aAAa,EAAE,CAAC;gBAClB,IAAI,CAAC,mCAAmC,CACtC,QAAQ,CAAC,EAAE,EACX,QAAQ,CAAC,UAAU,CACpB,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerNode } from \"../stores/container-contents\";\nimport { isSystemContainerNode } from \"../stores/container-contents\";\nimport type { ReconciliationHost } from \"../sync/reconciliation\";\n\ninterface ReconciledDocumentContentPullHost {\n readonly getContainer: (containerId: string) => ContainerNode | null;\n readonly pullDocumentContent: (input: {\n readonly containerId: string;\n readonly documentId: string;\n readonly localId: string;\n }) => void;\n readonly requestRegisteredDocumentRemoteSync: (\n localId: string,\n documentId: string,\n ) => void;\n}\n\nfunction shouldForceDocument(\n force: boolean,\n documentIds: ReadonlySet<string> | undefined,\n documentId: string,\n): boolean {\n return force && (!documentIds || documentIds.has(documentId));\n}\n\n/**\n * Routes reconciled summaries into the appropriate content-sync policy.\n *\n * System-container contents cannot rely on a mini-app opening them on this\n * device, especially during identity recovery. Pull each remote version once.\n * Ordinary documents stay lazy unless an explicit refresh asks an already-open\n * store to revalidate.\n */\nexport function createReconciledDocumentContentPuller(\n host: ReconciledDocumentContentPullHost,\n): ReconciliationHost[\"requestDocumentContentPull\"] {\n // Retain only the last observed version for each system-container document.\n // Keeping the version in the key would grow this cache for every historical\n // updatedAt value over the reconciler's lifetime.\n const pulledSystemDocumentVersions = new Map<string, string>();\n\n return (containerId, documents, force, documentIds) => {\n const systemContainer = isSystemContainerNode(\n host.getContainer(containerId) ?? { systemSlot: null },\n );\n\n for (const document of documents) {\n if (!document.documentId) {\n continue;\n }\n\n const forceDocument = shouldForceDocument(\n force,\n documentIds,\n document.documentId,\n );\n\n if (systemContainer) {\n // Container scope is significant: the same document can be linked into\n // multiple system containers whose keys establish different decryption\n // contexts for the transient store.\n const documentKey = `${containerId}:${document.documentId}`;\n if (\n pulledSystemDocumentVersions.get(documentKey) !== document.updatedAt\n ) {\n host.pullDocumentContent({\n containerId,\n documentId: document.documentId,\n localId: document.id,\n });\n pulledSystemDocumentVersions.set(documentKey, document.updatedAt);\n } else if (forceDocument) {\n // The first eager pull registers a document store before scheduling\n // its async sync. If that sync failed, a later explicit Refresh must\n // be able to retry the same server version without defeating normal\n // background dedupe.\n host.requestRegisteredDocumentRemoteSync(\n document.id,\n document.documentId,\n );\n }\n continue;\n }\n\n if (forceDocument) {\n host.requestRegisteredDocumentRemoteSync(\n document.id,\n document.documentId,\n );\n }\n }\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"rootContainerAdoption.js","sourceRoot":"","sources":["rootContainerAdoption.ts"],"names":[],"mappings":"AAmBA,MAAM,UAAU,yBAAyB,CACvC,YAA+C,EAC/C,KAAyC;IAEzC,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC;IACrC,IACE,YAAY,CAAC,cAAc,EAAE,KAAK,KAAK,CAAC,WAAW;QACnD,CAAC,OAAO,CAAC,eAAe;QACxB,OAAO,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC/C,OAAO,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,EAC/B,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC,eAAe,EAAE,CAAC;QAClD,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IACD,IAAI,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC,mBAAmB,EAAE,CAAC;QACtD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;IAC9C,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { DomainScope } from \"../data/domainScope\";\nimport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n} from \"../workflows/container-contents/runtime\";\nimport type { Session } from \"./session/sessionTypes\";\n\ninterface RootContainerAdoptionDependencies {\n readonly getDomainScope: () => DomainScope;\n readonly session: Pick<\n Session,\n | \"containerId\"\n | \"isAuthenticated\"\n | \"organizationId\"\n | \"setContainerId\"\n | \"userId\"\n >;\n}\n\nexport function adoptSessionRootContainer(\n dependencies: RootContainerAdoptionDependencies,\n input: ContainerContentsRootAdoptionInput,\n): ReturnType<ContainerContentsRootAdopter> {\n const session = dependencies.session;\n if (\n dependencies.getDomainScope() !== input.domainScope ||\n !session.isAuthenticated ||\n session.organizationId !== input.organizationId ||\n session.userId !== input.userId\n ) {\n return false;\n }\n if (session.containerId === input.nextContainerId) {\n return \"already-adopted\";\n }\n if (session.containerId !== input.expectedContainerId) {\n return false;\n }\n\n session.setContainerId(input.nextContainerId);\n return true;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"securityIncidents.js","sourceRoot":"","sources":["securityIncidents.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,wBAAwB,GAEzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,4CAA4C,CAAC;AACvF,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,iDAAiD,CAAC;AAQzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAclD,MAAM,+BAA+B,GAAG,GAAG,CAAC;AAC5C,MAAM,uBAAuB,GAAG,EAAE,CAAC;AACnC,MAAM,4BAA4B,GAAG,EAAE,CAAC;AACxC,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAC3C,MAAM,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O;QACL,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE;QAC7B,SAAS,EAAE;YACT,KAAK,CAAC,IAAI;gBACR,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;gBACnB,MAAM,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;gBACzC,OAAO,OAAO,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO,IAAI,OAAO;oBACnD,CAAC,CAAC,qBAAqB,CAAC,OAAO,EAAE,OAAO,CAAC,WAAW,CAAC;oBACrD,CAAC,CAAC,IAAI,CAAC;YACX,CAAC;YACD,MAAM;YACN,SAAS,EAAE,SAAS,CAAC,SAAS;SAC/B;QACD,MAAM;KACP,CAAC;AACJ,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n isKeyingVerificationCode,\n type KeyingVerificationError,\n} from \"@tearleads/crypto\";\nimport { isKeyingVerificationError } from \"../data/keyingProjectionVerification/error\";\nimport {\n appendSecurityIncident,\n listSecurityIncidents,\n} from \"../data/persistence/securityIncidentPersistence\";\nimport type {\n SecurityIncident,\n SecurityIncidentContext,\n SecurityIncidentObjectKind,\n SecurityIncidentReporter,\n} from \"../data/securityIncidents\";\nimport type { Database } from \"./database\";\nimport { createListenerSet } from \"./listenerSet\";\n\nexport type { SecurityIncident, SecurityIncidentObjectKind };\n\nexport type SecurityIncidentListener = (incident: SecurityIncident) => void;\n\n/**\n * Where a reported incident ended up: `recorded` rows are durable in the local\n * ledger, `buffered` ones wait in memory for a retried write, and `failed`\n * ones were dropped, so only `recorded` justifies telling a user it was kept.\n * Hosts name it as `Awaited<ReturnType<SecurityIncidents[\"record\"]>>`.\n */\ntype SecurityIncidentRecordingStatus = \"buffered\" | \"failed\" | \"recorded\";\n\nconst MAX_BUFFERED_SECURITY_INCIDENTS = 100;\nconst MAX_EVIDENCE_HASH_COUNT = 32;\nconst MAX_EVIDENCE_HASH_KEY_LENGTH = 64;\nconst MAX_EVIDENCE_HASH_VALUE_LENGTH = 256;\nconst MAX_INCIDENT_IDENTIFIER_LENGTH = 256;\nconst MAX_INCIDENT_OPERATION_LENGTH = 128;\nconst SECURITY_INCIDENT_RETRY_DELAY_MS = 250;\nconst SECURITY_INCIDENT_MAX_RETRY_DELAY_MS = 30_000;\n\nexport interface SecurityIncidents {\n /** Returns null while the local database is unavailable. */\n list(): Promise<ReadonlyArray<SecurityIncident> | null>;\n /**\n * Durably record a terminal verification failure the host detected itself,\n * such as conflicting purge proofs found while merging a local backup. The\n * report is redacted, coalesced, retained, and buffered exactly like an\n * SDK-detected incident; one error instance is recorded at most once, and\n * repeats of it resolve with the status of the first report.\n */\n record(\n error: KeyingVerificationError,\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus>;\n subscribe(listener: SecurityIncidentListener): () => void;\n}\n\ninterface SecurityIncidentServiceOptions {\n readonly database: Database;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly onIncident?: SecurityIncidentListener | undefined;\n readonly trustDomain: string | null;\n}\n\ninterface SecurityIncidentServiceResult {\n readonly dispose: () => void;\n readonly incidents: SecurityIncidents;\n readonly report: SecurityIncidentReporter;\n}\n\nfunction verificationCode(error: unknown): SecurityIncident[\"code\"] | null {\n if (!isKeyingVerificationError(error)) return null;\n const code = Reflect.get(error, \"code\");\n return isKeyingVerificationCode(code)\n ? code\n : \"unrecognized_verification_code\";\n}\n\ninterface RedactedIncident {\n readonly code: SecurityIncident[\"code\"];\n readonly context: SecurityIncidentContext;\n readonly detectedAt: string;\n readonly lastDetectedAt: string;\n readonly occurrenceCount: number;\n}\n\nfunction boundIncidentText(value: string, maxLength: number): string {\n return value.slice(0, maxLength);\n}\n\nfunction boundNullableIncidentText(value: string | null): string | null {\n return value === null\n ? null\n : boundIncidentText(value, MAX_INCIDENT_IDENTIFIER_LENGTH);\n}\n\nfunction redactIncidentContext(\n context: SecurityIncidentContext,\n): SecurityIncidentContext {\n return {\n evidenceHashes: Object.fromEntries(\n Object.entries(context.evidenceHashes ?? {})\n .filter(\n ([key, value]) =>\n key.length > 0 &&\n key.length <= MAX_EVIDENCE_HASH_KEY_LENGTH &&\n value.length <= MAX_EVIDENCE_HASH_VALUE_LENGTH,\n )\n // Code-unit order: the retained keys feed the incident id hash, so\n // truncation must pick the same keys on every runtime and locale.\n .sort(([left], [right]) => compareCanonicalStrings(left, right))\n .slice(0, MAX_EVIDENCE_HASH_COUNT),\n ),\n objectId: boundNullableIncidentText(context.objectId),\n objectKind: context.objectKind,\n operation: boundIncidentText(\n context.operation,\n MAX_INCIDENT_OPERATION_LENGTH,\n ),\n organizationId: boundNullableIncidentText(context.organizationId ?? null),\n };\n}\n\nfunction redactedIncidentKey(incident: RedactedIncident): string {\n return JSON.stringify([\n incident.code,\n incident.context.operation,\n incident.context.objectKind,\n incident.context.objectId,\n incident.context.organizationId ?? null,\n incident.context.evidenceHashes,\n ]);\n}\n\ntype SecurityIncidentListeners = ReturnType<\n typeof createListenerSet<[SecurityIncident]>\n>;\n\nclass SecurityIncidentSink {\n private readonly bufferedIncidents = new Map<string, RedactedIncident>();\n private flushPromise: Promise<boolean> | null = null;\n private retryDelayMs = SECURITY_INCIDENT_RETRY_DELAY_MS;\n private retryTimeout: ReturnType<typeof setTimeout> | null = null;\n private readonly unsubscribeDatabase: () => void;\n private disposed = false;\n\n constructor(\n private readonly options: SecurityIncidentServiceOptions,\n private readonly listeners: SecurityIncidentListeners,\n ) {\n this.unsubscribeDatabase = options.database.subscribe(() => {\n void this.flush();\n });\n }\n\n dispose(): void {\n this.disposed = true;\n this.unsubscribeDatabase();\n if (this.retryTimeout) clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n this.bufferedIncidents.clear();\n }\n\n async persist(\n code: SecurityIncident[\"code\"],\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus> {\n if (this.disposed) return \"failed\";\n const detectedAt = new Date().toISOString();\n const incident: RedactedIncident = {\n code,\n context: redactIncidentContext(context),\n detectedAt,\n lastDetectedAt: detectedAt,\n occurrenceCount: 1,\n };\n const execSql = this.options.database.execSql;\n if (this.options.database.status !== \"ready\" || !execSql) {\n return this.bufferStatus(incident);\n }\n\n try {\n const persisted = await this.append(execSql, incident);\n if (this.bufferedIncidents.size === 0) this.resetFlushRetry();\n if (!persisted) {\n this.options.logError(\n \"Security incident was dropped by the local retention limit\",\n );\n return \"failed\";\n }\n this.notify(persisted);\n return \"recorded\";\n } catch (persistenceError) {\n const status = this.bufferStatus(incident);\n if (status === \"buffered\") this.scheduleFlushRetry();\n this.options.logError(\n \"Security incident could not be persisted\",\n persistenceError,\n );\n return status;\n }\n }\n\n private bufferStatus(\n incident: RedactedIncident,\n ): SecurityIncidentRecordingStatus {\n return this.buffer(incident) ? \"buffered\" : \"failed\";\n }\n\n async flush(): Promise<void> {\n if (this.disposed) return;\n for (;;) {\n const activeFlush = this.flushPromise ?? this.startFlushBatch();\n if (!activeFlush) return;\n const succeeded = await activeFlush;\n if (succeeded) this.resetFlushRetry();\n if (this.flushPromise && this.flushPromise !== activeFlush) continue;\n if (this.flushPromise === activeFlush) this.flushPromise = null;\n if (\n !succeeded ||\n this.bufferedIncidents.size === 0 ||\n this.options.database.status !== \"ready\"\n ) {\n return;\n }\n }\n }\n\n private startFlushBatch(): Promise<boolean> | null {\n const execSql = this.options.database.execSql;\n if (this.options.database.status !== \"ready\" || !execSql) return null;\n\n const pending = [...this.bufferedIncidents.values()];\n if (pending.length === 0) return null;\n this.bufferedIncidents.clear();\n const flush = this.flushPending(execSql, pending);\n this.flushPromise = flush;\n return flush;\n }\n\n private append(\n execSql: NonNullable<Database[\"execSql\"]>,\n incident: RedactedIncident,\n ): Promise<SecurityIncident | null> {\n return appendSecurityIncident(execSql, {\n code: incident.code,\n detectedAt: incident.detectedAt,\n evidenceHashes: incident.context.evidenceHashes,\n lastDetectedAt: incident.lastDetectedAt,\n objectId: incident.context.objectId,\n objectKind: incident.context.objectKind,\n occurrenceCount: incident.occurrenceCount,\n operation: incident.context.operation,\n organizationId: incident.context.organizationId,\n trustDomain: this.options.trustDomain,\n });\n }\n\n private buffer(incident: RedactedIncident): boolean {\n if (this.disposed) return false;\n const key = redactedIncidentKey(incident);\n const existing = this.bufferedIncidents.get(key);\n if (existing) {\n this.bufferedIncidents.set(key, {\n ...existing,\n lastDetectedAt: incident.lastDetectedAt,\n occurrenceCount: existing.occurrenceCount + incident.occurrenceCount,\n });\n return true;\n }\n if (this.bufferedIncidents.size >= MAX_BUFFERED_SECURITY_INCIDENTS) {\n this.options.logError(\n \"Security incident could not be buffered because the startup buffer is full\",\n );\n return false;\n }\n this.bufferedIncidents.set(key, incident);\n return true;\n }\n\n private async flushPending(\n execSql: NonNullable<Database[\"execSql\"]>,\n pending: ReadonlyArray<RedactedIncident>,\n ): Promise<boolean> {\n let succeeded = true;\n for (const incident of pending) {\n try {\n const persisted = await this.append(execSql, incident);\n if (persisted) this.notify(persisted);\n } catch (persistenceError) {\n succeeded = false;\n if (this.buffer(incident)) this.scheduleFlushRetry();\n this.options.logError(\n \"Buffered security incident could not be persisted\",\n persistenceError,\n );\n }\n }\n return succeeded;\n }\n\n private notify(incident: SecurityIncident): void {\n if (this.disposed) return;\n this.listeners.notify(incident);\n try {\n this.options.onIncident?.(incident);\n } catch (callbackError) {\n this.options.logError(\"Security incident callback failed\", callbackError);\n }\n }\n\n private scheduleFlushRetry(): void {\n if (this.disposed || this.retryTimeout) return;\n const retryDelayMs = this.retryDelayMs;\n this.retryDelayMs = Math.min(\n this.retryDelayMs * 2,\n SECURITY_INCIDENT_MAX_RETRY_DELAY_MS,\n );\n this.retryTimeout = setTimeout(() => {\n this.retryTimeout = null;\n if (this.disposed) return;\n void this.flush();\n }, retryDelayMs);\n }\n\n private resetFlushRetry(): void {\n this.retryDelayMs = SECURITY_INCIDENT_RETRY_DELAY_MS;\n if (!this.retryTimeout) return;\n clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n }\n}\n\nexport function createSecurityIncidentService(\n options: SecurityIncidentServiceOptions,\n): SecurityIncidentServiceResult {\n const listeners = createListenerSet<[SecurityIncident]>();\n const recordedErrors = new WeakMap<object, SecurityIncidentRecordingStatus>();\n const incidentReports = new WeakMap<\n object,\n Promise<SecurityIncidentRecordingStatus>\n >();\n const sink = new SecurityIncidentSink(options, listeners);\n\n const persistIncident = async (\n error: unknown,\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus> => {\n const code = verificationCode(error);\n if (!code) {\n return \"failed\";\n }\n if (code === \"unrecognized_verification_code\") {\n options.logError(\n \"Security incident used the fallback code because its verification code is unrecognized\",\n );\n }\n\n return sink.persist(code, context);\n };\n\n const record = async (\n error: unknown,\n context: SecurityIncidentContext,\n ): Promise<SecurityIncidentRecordingStatus> => {\n if (typeof error !== \"object\" || error === null) {\n return \"failed\";\n }\n const recorded = recordedErrors.get(error);\n if (recorded) return recorded;\n const inFlight = incidentReports.get(error);\n if (inFlight) return inFlight;\n const pending = persistIncident(error, context)\n .then((status) => {\n if (status !== \"failed\") recordedErrors.set(error, status);\n return status;\n })\n .finally(() => {\n incidentReports.delete(error);\n });\n incidentReports.set(error, pending);\n return pending;\n };\n const report: SecurityIncidentReporter = async (error, context) => {\n await record(error, context);\n };\n\n return {\n dispose: () => sink.dispose(),\n incidents: {\n async list() {\n await sink.flush();\n const execSql = options.database.execSql;\n return options.database.status === \"ready\" && execSql\n ? listSecurityIncidents(execSql, options.trustDomain)\n : null;\n },\n record,\n subscribe: listeners.subscribe,\n },\n report,\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"userIdentities.js","sourceRoot":"","sources":["userIdentities.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,oCAAoC,EAAE,MAAM,4DAA4D,CAAC;AAClH,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAE9F,OAAO,EACL,iBAAiB,EACjB,kCAAkC,GAInC,MAAM,6BAA6B,C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C,GAAG,CAAC,qCAAqC,MAAM,EAAE,CAAC,CAAC;YACzD,IAAI,QAA0D,CAAC;YAC/D,IAAI,CAAC;gBACH,QAAQ,GAAG,MAAM,0BAA0B,CAAC,MAAM,CAAC,CAAC;YACtD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,CAAC,CAAC,KAAK,YAAY,oCAAoC,CAAC;oBAC1D,MAAM,KAAK,CAAC;gBACd,KAAK,CAAC,GAAG,CACP,qBAAqB,MAAM,oBAAoB,KAAK,CAAC,OAAO,EAAE,CAC/D,CAAC;gBACF,OAAO,IAAI,CAAC;YACd,CAAC;YACD,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,OAAO,IAAI,CAAC;YACd,CAAC;YAED,OAAO,kBAAkB,CAAC,QAAQ,CAAC,CAAC;QACtC,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport { ProjectionDependencyUnavailableError } from \"../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../data/keyingProjectionVerification/error\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport {\n parseIdentityLink,\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../data/trustedUserIdentity\";\n\nexport interface ResolvedUserIdentity {\n encapsulationKeyFingerprint: string;\n encapsulationPublicKey: string;\n signingKeyFingerprint: string;\n signingPublicKey: string;\n userId: string;\n}\n\nexport interface UserIdentities {\n /** Share a stable link derived exclusively from this user's local keys. */\n createLink(appUrl: string): Promise<string>;\n /** Compare an independently received link before durably pinning either key. */\n verifyLink(link: string): Promise<ResolvedUserIdentity>;\n /** Read an existing durable pin without fetching or trusting a new identity. */\n resolvePinned(userId: string): Promise<ResolvedUserIdentity | null>;\n /** `null` when the user is unknown or currently unresolvable; integrity failures throw. */\n resolve(userId: string): Promise<ResolvedUserIdentity | null>;\n}\n\nfunction toResolvedIdentity(\n identity: TrustedUserIdentity,\n): ResolvedUserIdentity {\n return {\n encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),\n signingKeyFingerprint: identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(identity.signingPublicKey),\n userId: identity.userId,\n };\n}\n\nexport function createUserIdentities(input: {\n getOrganizationId: () => string | null;\n reportSecurityIncident: SecurityIncidentReporter;\n identityLinks: Pick<\n TrustedUserIdentityService,\n \"createLink\" | \"verifyLink\" | \"resolvePinned\"\n >;\n log: (message: string) => void;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}): UserIdentities {\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n );\n return {\n createLink: (appUrl) => input.identityLinks.createLink(appUrl),\n async verifyLink(link) {\n const { userId } = parseIdentityLink(link);\n return runWithSecurityIncidentReporting(\n input.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.verify_link\",\n organizationId: input.getOrganizationId(),\n },\n async () =>\n toResolvedIdentity(await input.identityLinks.verifyLink(link)),\n );\n },\n async resolvePinned(userId) {\n const identity = await input.identityLinks.resolvePinned(userId);\n return identity ? toResolvedIdentity(identity) : null;\n },\n async resolve(userId) {\n input.log(`Loading user identity for userId: ${userId}`);\n let identity: Awaited<ReturnType<TrustedUserIdentityResolver>>;\n try {\n identity = await resolveTrustedUserIdentity(userId);\n } catch (error) {\n if (!(error instanceof ProjectionDependencyUnavailableError))\n throw error;\n input.log(\n `User identity for ${userId} is unavailable: ${error.message}`,\n );\n return null;\n }\n if (!identity) {\n return null;\n }\n\n return toResolvedIdentity(identity);\n },\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gCAAgC,EAAE,MA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AC,QAAQ,EAAE;gBACvC,mBAAmB,EAAE,YAAY,CAAC,mBAAmB;gBACrD,GAAG,EAAE,YAAY,CAAC,GAAG;gBACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;aAChC,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAC1B,OAAsB,EACtB,IAAO;IAEP,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../data/documents/documentKinds\";\nimport type { DomainScope } from \"../data/domainScope\";\nimport { runWithSecurityIncidentReporting } from \"../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../data/principals/principalHistoryProtection\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../workflows/container-contents/runtime\";\nimport {\n createProvisionedPrincipalHistoryPrimer,\n type ProvisionedPrincipalHistoryPrimer,\n} from \"../workflows/registration/provisionedPrincipalHistory\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../workflows/runtimeInput\";\nimport type { Blobs } from \"./blobs\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Identity } from \"./identity\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { acknowledgedSessionRoot } from \"./session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"./session/sessionTypes\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n identityLinks: Pick<\n TrustedUserIdentityService,\n \"createLink\" | \"verifyLink\" | \"resolvePinned\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedPrincipalHistory: ProvisionedPrincipalHistoryPrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\nfunction localIdentityCandidate(\n identity: Identity,\n): LocalUserIdentityCandidate | null {\n const { encapsulationKeyPair, signingKeyPair } = identity;\n if (!encapsulationKeyPair || !signingKeyPair) return null;\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedPrincipalHistoryPrimer {\n return createProvisionedPrincipalHistoryPrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: readyExecSql,\n getLocalIdentity: () => localIdentityCandidate(dependencies.identity),\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedPrincipalHistory: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}