@tearleads/client-sdk 0.1.41 → 0.1.43

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 (235) hide show
  1. package/client/Tearleads.js +3 -0
  2. package/client/Tearleads.js.map +1 -1
  3. package/data/blobs/transferPool.js +35 -8
  4. package/data/blobs/transferPool.js.map +1 -1
  5. package/data/containers/shared/projection.js +12 -0
  6. package/data/containers/shared/projection.js.map +1 -1
  7. package/data/documents/blob/shared/types.d.ts +2 -3
  8. package/data/documents/blob/shared/types.js.map +1 -1
  9. package/data/documents/shared/events.js +0 -1
  10. package/data/documents/shared/events.js.map +1 -1
  11. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js +2 -0
  12. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +1 -1
  13. package/data/keyingProjectionVerification/checkpointContext.d.ts +12 -0
  14. package/data/keyingProjectionVerification/checkpointContext.js +16 -0
  15. package/data/keyingProjectionVerification/checkpointContext.js.map +1 -1
  16. package/data/keyingProjectionVerification/containerDestinationVerification.js +3 -1
  17. package/data/keyingProjectionVerification/containerDestinationVerification.js.map +1 -1
  18. package/data/keyingProjectionVerification/containerProjectionVerification.js +12 -6
  19. package/data/keyingProjectionVerification/containerProjectionVerification.js.map +1 -1
  20. package/data/keyingProjectionVerification/documentProjectionVerification.js +10 -4
  21. package/data/keyingProjectionVerification/documentProjectionVerification.js.map +1 -1
  22. package/data/persistence/container-contents/containerContentsPersistence.js +6 -22
  23. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  24. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +5 -15
  25. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  26. package/data/persistence/container-contents/containerPendingUpdatePersistence.js +6 -15
  27. package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
  28. package/data/persistence/container-contents/containerRecoveryPersistence.js +3 -4
  29. package/data/persistence/container-contents/containerRecoveryPersistence.js.map +1 -1
  30. package/data/persistence/container-contents/containerRemovalWork.js +3 -5
  31. package/data/persistence/container-contents/containerRemovalWork.js.map +1 -1
  32. package/data/persistence/container-contents/dormantContainerMetadata.js +1 -5
  33. package/data/persistence/container-contents/dormantContainerMetadata.js.map +1 -1
  34. package/data/persistence/documents/documentsPersistence.js +4 -9
  35. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  36. package/data/persistence/documents/internal/discardDocument.js +1 -2
  37. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  38. package/data/persistence/documents/internal/documentDeletionPersistence.js +1 -2
  39. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  40. package/data/persistence/documents/internal/documentMutationPersistence.js +17 -25
  41. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  42. package/data/persistence/documents/internal/orphanSideRows.js +2 -14
  43. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  44. package/data/persistence/documents/internal/syncQueuePersistence.js +3 -3
  45. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  46. package/data/persistence/keyingCheckpointAdvancePersistence.js +27 -8
  47. package/data/persistence/keyingCheckpointAdvancePersistence.js.map +1 -1
  48. package/data/persistence/verifiedManifestBundlePersistence.d.ts +45 -0
  49. package/data/persistence/verifiedManifestBundlePersistence.js +282 -0
  50. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -0
  51. package/data/sqlite/documentHistoryPersistence.d.ts +9 -3
  52. package/data/sqlite/documentHistoryPersistence.js +31 -8
  53. package/data/sqlite/documentHistoryPersistence.js.map +1 -1
  54. package/data/sqlite/documentPendingUpdatePersistence.d.ts +58 -11
  55. package/data/sqlite/documentPendingUpdatePersistence.js +137 -63
  56. package/data/sqlite/documentPendingUpdatePersistence.js.map +1 -1
  57. package/data/sqlite/documentPersistence.d.ts +1 -1
  58. package/data/sqlite/documentPersistence.js +1 -1
  59. package/data/sqlite/documentPersistence.js.map +1 -1
  60. package/data/sqlite/documentPersistenceTypes.d.ts +2 -2
  61. package/data/sqlite/documentPersistenceTypes.js.map +1 -1
  62. package/data/sqlite/documentRecordPersistence.js +5 -4
  63. package/data/sqlite/documentRecordPersistence.js.map +1 -1
  64. package/data/sqlite/schema.d.ts +350 -443
  65. package/data/sqlite/schema.js +49 -47
  66. package/data/sqlite/schema.js.map +1 -1
  67. package/data/sqlite/verifiedManifestBundleSchema.d.ts +174 -0
  68. package/data/sqlite/verifiedManifestBundleSchema.js +36 -0
  69. package/data/sqlite/verifiedManifestBundleSchema.js.map +1 -0
  70. package/internal/api-client/ApiClient.d.ts +17 -19
  71. package/internal/api-client/ApiClient.js +10 -11
  72. package/internal/api-client/ApiClient.js.map +1 -1
  73. package/internal/api-client/binaryRequestOperationTransport.d.ts +18 -0
  74. package/internal/api-client/index.d.ts +2 -1
  75. package/internal/api-client/index.js +1 -1
  76. package/internal/api-client/index.js.map +1 -1
  77. package/internal/api-client/operationTransportFactory.d.ts +6 -0
  78. package/internal/api-client/principalHistoryRequest.js +8 -2
  79. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  80. package/internal/api-client/principalHistoryRequestContext.js +15 -5
  81. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  82. package/internal/api-client/routes/blobs/get.d.ts +7 -0
  83. package/internal/api-client/routes/blobs/get.js.map +1 -1
  84. package/internal/api-client/routes/blobs/multipart.js +1 -11
  85. package/internal/api-client/routes/blobs/multipart.js.map +1 -1
  86. package/internal/api-client/routes/blobs/multipartUpload.d.ts +14 -0
  87. package/internal/api-client/routes/blobs/multipartUpload.js +94 -43
  88. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  89. package/internal/api-client/routes/writerProjections.js +6 -3
  90. package/internal/api-client/routes/writerProjections.js.map +1 -1
  91. package/internal/api-client/verifiedManifestCitations.d.ts +23 -0
  92. package/internal/api-client/verifiedManifestCitations.js +60 -0
  93. package/internal/api-client/verifiedManifestCitations.js.map +1 -0
  94. package/internal/api-client/writerProjectionRequests.js +75 -14
  95. package/internal/api-client/writerProjectionRequests.js.map +1 -1
  96. package/internal/crypto/index.d.ts +0 -1
  97. package/internal/crypto/index.js +0 -1
  98. package/internal/crypto/index.js.map +1 -1
  99. package/internal/validators/knownManifestsRefinements.js +5 -0
  100. package/internal/validators/knownManifestsRefinements.js.map +1 -0
  101. package/internal/validators/operation/attachments.d.ts +80 -160
  102. package/internal/validators/operation/auth.d.ts +760 -1664
  103. package/internal/validators/operation/blobDownloads.js +1 -1
  104. package/internal/validators/operation/blobDownloads.js.map +1 -1
  105. package/internal/validators/operation/containerMutations.d.ts +416 -856
  106. package/internal/validators/operation/documentMutations.d.ts +120 -264
  107. package/internal/validators/operation/documentSync.d.ts +40 -80
  108. package/internal/validators/operation/index.d.ts +1 -1
  109. package/internal/validators/operation/index.js +1 -1
  110. package/internal/validators/operation/index.js.map +1 -1
  111. package/internal/validators/operation/multipartBlobs.d.ts +70 -190
  112. package/internal/validators/operation/multipartBlobs.js +2 -24
  113. package/internal/validators/operation/multipartBlobs.js.map +1 -1
  114. package/internal/validators/operation/multipartPartUploads.d.ts +5 -5
  115. package/internal/validators/operation/multipartPartUploads.js +6 -20
  116. package/internal/validators/operation/multipartPartUploads.js.map +1 -1
  117. package/internal/validators/operation/organizations.d.ts +882 -1906
  118. package/internal/validators/operation/principals.d.ts +120 -240
  119. package/internal/validators/operation/registry.d.ts +1 -2
  120. package/internal/validators/operation/registry.js +1 -2
  121. package/internal/validators/operation/registry.js.map +1 -1
  122. package/internal/validators/operation/writerProjections.d.ts +85 -319
  123. package/internal/validators/operation/writerProjections.js +11 -11
  124. package/internal/validators/operation/writerProjections.js.map +1 -1
  125. package/internal/validators/request/blob.d.ts +100 -201
  126. package/internal/validators/request/blob.js +6 -13
  127. package/internal/validators/request/blob.js.map +1 -1
  128. package/internal/validators/request/container.d.ts +136 -272
  129. package/internal/validators/request/container.js +16 -10
  130. package/internal/validators/request/container.js.map +1 -1
  131. package/internal/validators/request/containerManifestRef.d.ts +54 -0
  132. package/internal/validators/request/containerManifestRef.js +28 -0
  133. package/internal/validators/request/containerManifestRef.js.map +1 -0
  134. package/internal/validators/request/containerMetadata.d.ts +160 -368
  135. package/internal/validators/request/document.d.ts +100 -245
  136. package/internal/validators/request/document.js +1 -2
  137. package/internal/validators/request/document.js.map +1 -1
  138. package/internal/validators/request/documentSyncSchema.d.ts +42 -109
  139. package/internal/validators/request/documentSyncSchema.js +8 -25
  140. package/internal/validators/request/documentSyncSchema.js.map +1 -1
  141. package/internal/validators/request/index.d.ts +1 -1
  142. package/internal/validators/request/index.js +1 -1
  143. package/internal/validators/request/index.js.map +1 -1
  144. package/internal/validators/request/organization.d.ts +160 -320
  145. package/internal/validators/request/organizationProvisioning.d.ts +2424 -5312
  146. package/internal/validators/request/principal.d.ts +160 -320
  147. package/internal/validators/request/registration.d.ts +760 -1664
  148. package/internal/validators/response/blob.d.ts +48 -27
  149. package/internal/validators/response/blob.js +3 -10
  150. package/internal/validators/response/blob.js.map +1 -1
  151. package/internal/validators/response/container.d.ts +429 -20
  152. package/internal/validators/response/container.js +40 -5
  153. package/internal/validators/response/container.js.map +1 -1
  154. package/internal/validators/response/documentMutation.d.ts +440 -20
  155. package/internal/validators/response/documentMutation.js +33 -3
  156. package/internal/validators/response/documentMutation.js.map +1 -1
  157. package/internal/validators/response/index.d.ts +4 -3
  158. package/internal/validators/response/index.js +4 -3
  159. package/internal/validators/response/index.js.map +1 -1
  160. package/internal/validators/response/manifestBundleReferences.js +79 -0
  161. package/internal/validators/response/manifestBundleReferences.js.map +1 -0
  162. package/internal/validators/response/writerProjectionWire.d.ts +19 -0
  163. package/internal/validators/response/writerProjectionWire.js +132 -0
  164. package/internal/validators/response/writerProjectionWire.js.map +1 -0
  165. package/internal/validators/schema.js +20 -0
  166. package/internal/validators/schema.js.map +1 -1
  167. package/internal/validators/util/blob.d.ts +7 -0
  168. package/internal/validators/util/blob.js +7 -0
  169. package/internal/validators/util/blob.js.map +1 -1
  170. package/internal/validators/util/blobTransferSchemas.d.ts +41 -0
  171. package/internal/validators/util/blobTransferSchemas.js +39 -0
  172. package/internal/validators/util/blobTransferSchemas.js.map +1 -0
  173. package/internal/validators/util/containerLimits.d.ts +7 -0
  174. package/internal/validators/util/containerLimits.js +7 -0
  175. package/internal/validators/util/containerLimits.js.map +1 -1
  176. package/internal/validators/util/index.d.ts +3 -2
  177. package/internal/validators/util/index.js +3 -2
  178. package/internal/validators/util/index.js.map +1 -1
  179. package/internal/validators/util/knownManifestWire.d.ts +11 -0
  180. package/internal/validators/util/knownManifestWire.js +28 -0
  181. package/internal/validators/util/knownManifestWire.js.map +1 -0
  182. package/internal/validators/writerProjectionRefinements.js +5 -0
  183. package/internal/validators/writerProjectionRefinements.js.map +1 -1
  184. package/package.json +1 -1
  185. package/workflows/blobs/multipartFirstParts.js +82 -0
  186. package/workflows/blobs/multipartFirstParts.js.map +1 -0
  187. package/workflows/blobs/multipartStageResolution.js +83 -0
  188. package/workflows/blobs/multipartStageResolution.js.map +1 -0
  189. package/workflows/blobs/multipartUpload.js +45 -89
  190. package/workflows/blobs/multipartUpload.js.map +1 -1
  191. package/workflows/container-contents/documentPriming.js +2 -1
  192. package/workflows/container-contents/documentPriming.js.map +1 -1
  193. package/workflows/container-contents/documentQueries/sql.js +4 -4
  194. package/workflows/container-contents/documentQueries/sql.js.map +1 -1
  195. package/workflows/container-contents/pendingWrites/deferredTails.js +6 -3
  196. package/workflows/container-contents/pendingWrites/deferredTails.js.map +1 -1
  197. package/workflows/container-contents/pendingWrites/sources.js +2 -1
  198. package/workflows/container-contents/pendingWrites/sources.js.map +1 -1
  199. package/workflows/container-contents/pendingWrites.js +2 -1
  200. package/workflows/container-contents/pendingWrites.js.map +1 -1
  201. package/workflows/containers/child/create.js +3 -3
  202. package/workflows/containers/child/create.js.map +1 -1
  203. package/workflows/containers/child/move.js +2 -2
  204. package/workflows/containers/child/move.js.map +1 -1
  205. package/workflows/containers/child/mutationRequestCore.js +5 -4
  206. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  207. package/workflows/containers/child/recitePlan.js +3 -2
  208. package/workflows/containers/child/recitePlan.js.map +1 -1
  209. package/workflows/containers/child/sharePlanCore.js +2 -2
  210. package/workflows/containers/child/sharePlanCore.js.map +1 -1
  211. package/workflows/containers/root/create.js +2 -2
  212. package/workflows/containers/root/create.js.map +1 -1
  213. package/workflows/registration/provisioningBootstrapBuilders.d.ts +20 -51
  214. package/workflows/sync/remoteReset.js +11 -9
  215. package/workflows/sync/remoteReset.js.map +1 -1
  216. package/workflows/sync/remoteResetPlans.js +6 -3
  217. package/workflows/sync/remoteResetPlans.js.map +1 -1
  218. package/internal/api-client/projectionHistoryTransport.js +0 -107
  219. package/internal/api-client/projectionHistoryTransport.js.map +0 -1
  220. package/internal/api-client/verifiedProjectionHistory.d.ts +0 -4
  221. package/internal/api-client/verifiedProjectionHistory.js +0 -12
  222. package/internal/api-client/verifiedProjectionHistory.js.map +0 -1
  223. package/internal/crypto/projectionHistory.d.ts +0 -14
  224. package/internal/crypto/projectionHistory.js +0 -90
  225. package/internal/crypto/projectionHistory.js.map +0 -1
  226. package/internal/crypto/projectionHistorySlots.d.ts +0 -13
  227. package/internal/crypto/projectionHistorySlots.js +0 -81
  228. package/internal/crypto/projectionHistorySlots.js.map +0 -1
  229. package/internal/validators/operation/blobTransferSchemas.js +0 -11
  230. package/internal/validators/operation/blobTransferSchemas.js.map +0 -1
  231. package/internal/validators/projectionHistoryRefinements.js +0 -5
  232. package/internal/validators/projectionHistoryRefinements.js.map +0 -1
  233. package/internal/validators/util/projectionHistoryWire.d.ts +0 -23
  234. package/internal/validators/util/projectionHistoryWire.js +0 -33
  235. package/internal/validators/util/projectionHistoryWire.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"remoteReset.js","sourceRoot":"","sources":["remoteReset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,O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AM,QAAQ,GAAG,MAAM,2BAA2B,CAChD,EAAE,EACF,KAAK,CAAC,cAAc,CACrB,CAAC;YACF,MAAM,KAAK,GAAG,MAAM,eAAe,CAAC,EAAE,EAAE,QAAQ,CAAC,YAAY,CAAC,CAAC;YAC/D,OAAO,iCAAiC,CAAC;gBACvC,KAAK;gBACL,KAAK;gBACL,QAAQ;gBACR,EAAE;aACH,CAAC,CAAC;QACL,CAAC,CAAC;QACF,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,OAAO,OAAO,CAAC,WAAW,CAAC,kBAAkB,CAAC,CAAC;QACjD,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAC9C,kBAAkB,EAClB,SAAS,CACV,CAAC;QACF,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;YAC1C,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,CAAC;QACD,OAAO,OAAO,CAAC,MAAM,CAAC;IACxB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { and, eq, inArray, or } from \"drizzle-orm\";\nimport { recordSupersededContainerBindingsInTransaction } from \"../../data/persistence/container-contents/supersededContainerBindings\";\nimport {\n deleteDocumentPlacementRowsByContainerIds,\n deleteDocumentPlacementRowsByDocumentIds,\n} from \"../../data/persistence/containers/documentContainerProjectionPersistence\";\nimport { clearDocumentDiscoveryEvidenceOnRemoteReset } from \"../../data/persistence/documents/documentDiscoveryReset\";\nimport { documentIntentLinkTargets } from \"../../data/sqlite/documentPlacementIntentSchema\";\nimport {\n organizationDataUsageCategories,\n organizationDataUsageSnapshots,\n} from \"../../data/sqlite/organizationDataUsageSchema\";\nimport {\n organizationPresentationDenials,\n organizationReadModelContainerGrants,\n organizationReadModelDirectoryUsers,\n organizationReadModelGroupMembers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../data/sqlite/organizationReadModelSchema\";\nimport {\n clientSqlTables,\n containerCreateIntents,\n containerHydrationTombstones,\n containerMoveIntents,\n containers,\n documentAttachmentBlobProjection,\n documentMoveIntents,\n documentPendingAttachments,\n documentPendingUpdates,\n documentProjection,\n documentSyncFailures,\n documents,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n} from \"../../data/sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../data/sqlite/sqlTableSchema\";\nimport { runOrganizationPresentationReset } from \"../organizations/organizationPresentationAccessState\";\nimport { clearResetPendingAttachments } from \"./remoteResetAttachments\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\nimport { clearRemoteResetSyncCursors } from \"./remoteResetCursorScope\";\nimport {\n buildResetPlans,\n type ResetAttachmentUpload,\n type ResetDocumentUpdate,\n} from \"./remoteResetPlans\";\nimport { clearRemoteResetPrincipalRows } from \"./remoteResetPrincipalScope\";\nimport {\n type RemoteResetInput,\n type RemoteSyncStateSnapshot,\n readRemoteSyncStateSnapshot,\n} from \"./remoteResetScope\";\n\nexport type {\n RemoteResetInput,\n RemoteResetReplacement,\n} from \"./remoteResetScope\";\n\nconst CONTAINER_CREATE_INTENT_TYPE = \"container.create\";\n\nexport interface ClearRemoteSyncStateResult {\n readonly clearedContainerCreateIntentCount: number;\n readonly clearedContainerMoveIntentCount: number;\n readonly clearedDocumentMoveIntentCount: number;\n readonly clearedPrincipalPolicyCount: number;\n readonly clearedSyncCursorCount: number;\n readonly queuedAttachmentUploadCount: number;\n readonly queuedContainerCreateCount: number;\n readonly queuedDocumentUpdateCount: number;\n readonly resetContainerCount: number;\n readonly resetDocumentCount: number;\n}\n\nasync function clearOrganizationPresentationRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n for (const table of [\n organizationDataUsageCategories,\n organizationDataUsageSnapshots,\n organizationReadModelContainerGrants,\n organizationReadModelGroupMembers,\n organizationReadModelDirectoryUsers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n organizationPresentationDenials,\n ] as const) {\n await tx\n .delete(table)\n .where(eq(table.organizationId, organizationId))\n .run();\n }\n}\n\ninterface ScopedRemoteRowsInput {\n attachmentUploads: readonly ResetAttachmentUpload[];\n organizationId: string;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}\n\nasync function clearScopedContainerRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n for (const containerBatch of remoteResetBatches(\n input.snapshot.containerIds,\n )) {\n await deleteDocumentPlacementRowsByContainerIds(input.tx, containerBatch);\n await input.tx\n .delete(containerMoveIntents)\n .where(inArray(containerMoveIntents.containerId, containerBatch))\n .run();\n await input.tx\n .delete(containerCreateIntents)\n .where(inArray(containerCreateIntents.containerId, containerBatch))\n .run();\n await input.tx\n .delete(containerHydrationTombstones)\n .where(inArray(containerHydrationTombstones.containerId, containerBatch))\n .run();\n }\n}\n\nasync function clearScopedDocumentRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n const { snapshot, tx } = input;\n for (const documentIdBatch of remoteResetBatches(snapshot.oldDocumentIds)) {\n await deleteDocumentPlacementRowsByDocumentIds(tx, documentIdBatch);\n }\n await clearResetPendingAttachments({\n attachmentUploads: input.attachmentUploads,\n documentLocalIds: snapshot.documentLocalIds,\n tx,\n });\n for (const localIdBatch of remoteResetBatches(snapshot.documentLocalIds)) {\n await tx\n .delete(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n tx\n .select({ id: documentMoveIntents.id })\n .from(documentMoveIntents)\n .where(inArray(documentMoveIntents.localId, localIdBatch)),\n ),\n )\n .run();\n await tx\n .delete(documentMoveIntents)\n .where(inArray(documentMoveIntents.localId, localIdBatch))\n .run();\n }\n for (const documentBatch of remoteResetBatches(snapshot.documentRows)) {\n await tx\n .delete(documentPendingUpdates)\n .where(\n or(\n ...documentBatch.map((row) =>\n and(\n eq(documentPendingUpdates.appKind, row.appKind),\n eq(documentPendingUpdates.localId, row.localId),\n ),\n ),\n ),\n )\n .run();\n await tx\n .delete(documentSyncFailures)\n .where(\n or(\n ...documentBatch.map((row) =>\n and(\n eq(documentSyncFailures.appKind, row.appKind),\n eq(documentSyncFailures.localId, row.localId),\n ),\n ),\n ),\n )\n .run();\n }\n}\n\nasync function clearScopedRemoteRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n const { organizationId, tx } = input;\n await clearOrganizationPresentationRows(tx, organizationId);\n for (const table of [\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n ] as const) {\n await tx\n .delete(table)\n .where(eq(table.organizationId, organizationId))\n .run();\n }\n await clearDocumentDiscoveryEvidenceOnRemoteReset(tx, {\n containerIds: input.snapshot.containerIds,\n documentIds: input.snapshot.oldDocumentIds,\n });\n await clearRemoteResetPrincipalRows(input);\n await clearScopedContainerRows(input);\n await clearScopedDocumentRows(input);\n await clearRemoteResetSyncCursors({\n containerIds: input.snapshot.containerIds,\n tx,\n });\n}\n\nasync function resetRemoteColumns(input: {\n now: string;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { now, reset, snapshot, tx } = input;\n for (const row of snapshot.documentRows) {\n await tx\n .update(documents)\n .set({\n accessEpoch: 1,\n accessStateHash: null,\n contentKeyBundle: null,\n documentId: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n lastCommitLsn: null,\n pullContinuation: null,\n recoveryDocumentId: row.documentId ?? row.recoveryDocumentId,\n updatedAt: now,\n })\n .where(\n and(\n eq(documents.appKind, row.appKind),\n eq(documents.localId, row.localId),\n ),\n )\n .run();\n }\n for (const localIdBatch of remoteResetBatches(snapshot.documentLocalIds)) {\n await tx\n .update(documentProjection)\n .set({\n documentId: null,\n organizationId:\n reset.replacement?.organizationId ?? reset.organizationId,\n })\n .where(inArray(documentProjection.localId, localIdBatch))\n .run();\n }\n // Replacement re-homes folders under their ids; the purged organization\n // can never bind them again on this device.\n for (const containerIds of reset.replacement\n ? remoteResetBatches(snapshot.containerIds)\n : []) {\n await recordSupersededContainerBindingsInTransaction(tx, {\n containerIds,\n organizationId: reset.organizationId,\n supersededAt: now,\n });\n }\n for (const row of snapshot.containerRows) {\n await tx\n .update(containers)\n .set({\n metadataDocumentId: null,\n organizationId:\n reset.replacement?.organizationId ?? reset.organizationId,\n parentId:\n reset.replacement && row.parentId === null\n ? reset.replacement.rootContainerId\n : row.parentId,\n serverCreatedAt: null,\n serverUpdatedAt: null,\n ...(reset.replacement ? { systemSlot: null } : {}),\n localUpdatedAt: now,\n })\n .where(eq(containers.id, row.id))\n .run();\n }\n}\n\nasync function queueResetDocumentUpdates(input: {\n documentUpdates: readonly ResetDocumentUpdate[];\n now: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const updateBatch of remoteResetBatches(input.documentUpdates)) {\n await input.tx\n .insert(documentPendingUpdates)\n .values(\n updateBatch.map((update) => ({\n ...update,\n id: crypto.randomUUID(),\n createdAt: input.now,\n })),\n )\n .run();\n }\n}\n\nasync function queueResetContainerCreates(input: {\n now: string;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<number> {\n const rows = input.snapshot.containerRows.flatMap((row) => {\n const parentId =\n row.parentId ?? input.reset.replacement?.rootContainerId ?? null;\n return parentId ? [{ id: row.id, parentId }] : [];\n });\n if (rows.length === 0) return 0;\n for (const rowBatch of remoteResetBatches(rows)) {\n await input.tx\n .insert(containerCreateIntents)\n .values(\n rowBatch.map((row) => ({\n id: crypto.randomUUID(),\n containerId: row.id,\n parentContainerId: row.parentId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\" as const,\n remoteContainerId: null,\n remoteMetadataAccessStateHash: null,\n remoteMetadataDocumentId: null,\n lastError: null,\n createdAt: input.now,\n updatedAt: input.now,\n })),\n )\n .run();\n }\n return rows.length;\n}\n\nasync function queueResetAttachmentUploads(input: {\n attachmentUploads: readonly ResetAttachmentUpload[];\n now: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const attachmentBatch of remoteResetBatches(input.attachmentUploads)) {\n await input.tx\n .insert(documentPendingAttachments)\n .values(\n attachmentBatch.map((attachment) => ({\n ...attachment,\n createdAt: input.now,\n })),\n )\n .run();\n await input.tx\n .delete(documentAttachmentBlobProjection)\n .where(\n or(\n ...attachmentBatch.map((attachment) =>\n and(\n eq(documentAttachmentBlobProjection.localId, attachment.localId),\n eq(documentAttachmentBlobProjection.slotId, attachment.slotId),\n ),\n ),\n ),\n )\n .run();\n }\n}\n\nasync function clearRemoteSyncStateInTransaction(input: {\n plans: Awaited<ReturnType<typeof buildResetPlans>>;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<ClearRemoteSyncStateResult> {\n const now = new Date().toISOString();\n const { snapshot } = input;\n await clearScopedRemoteRows({\n attachmentUploads: input.plans.attachmentUploads,\n organizationId: input.reset.organizationId,\n snapshot,\n tx: input.tx,\n });\n await resetRemoteColumns({ now, reset: input.reset, snapshot, tx: input.tx });\n await queueResetDocumentUpdates({\n documentUpdates: input.plans.documentUpdates,\n now,\n tx: input.tx,\n });\n const queuedContainerCreateCount = await queueResetContainerCreates({\n now,\n reset: input.reset,\n snapshot,\n tx: input.tx,\n });\n await queueResetAttachmentUploads({\n attachmentUploads: input.plans.attachmentUploads,\n now,\n tx: input.tx,\n });\n return {\n clearedContainerCreateIntentCount:\n snapshot.clearedContainerCreateIntentCount,\n clearedContainerMoveIntentCount: snapshot.clearedContainerMoveIntentCount,\n clearedDocumentMoveIntentCount: snapshot.clearedDocumentMoveIntentCount,\n clearedPrincipalPolicyCount: snapshot.clearedPrincipalPolicyCount,\n clearedSyncCursorCount: snapshot.clearedSyncCursorCount,\n queuedAttachmentUploadCount: input.plans.attachmentUploads.length,\n queuedContainerCreateCount,\n queuedDocumentUpdateCount: input.plans.documentUpdates.length,\n resetContainerCount: snapshot.containerRows.length,\n resetDocumentCount: snapshot.documentRows.length,\n };\n}\n\nexport async function clearRemoteSyncState(\n execSql: ExecSql,\n reset: RemoteResetInput,\n canCommit?: (() => boolean) | undefined,\n): Promise<ClearRemoteSyncStateResult> {\n return runOrganizationPresentationReset(\n execSql,\n reset.organizationId,\n async () => {\n await ensureSqlTables(execSql, clientSqlTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const resetInTransaction = async (tx: ClientSQLiteTransactionScope) => {\n if (canCommit && !canCommit()) {\n throw new Error(\n \"Remote sync reset aborted: session identity changed\",\n );\n }\n const snapshot = await readRemoteSyncStateSnapshot(\n tx,\n reset.organizationId,\n );\n const plans = await buildResetPlans(tx, snapshot.documentRows);\n return clearRemoteSyncStateInTransaction({\n plans,\n reset,\n snapshot,\n tx,\n });\n };\n if (!canCommit) {\n return runtime.transaction(resetInTransaction);\n }\n const outcome = await runtime.guardedTransaction(\n resetInTransaction,\n canCommit,\n );\n if (!outcome.committed || !outcome.result) {\n throw new Error(\"Remote sync reset aborted: session identity changed\");\n }\n return outcome.result;\n },\n );\n}\n"]}
1
+ {"version":3,"file":"remoteReset.js","sourceRoot":"","sources":["remoteReset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,8CAA8C,EAAE,MAAM,uEAAuE,CAAC;AACvI,OAAO,EACL,yCAAyC,EACzC,wCAAwC,GACzC,MAAM,0EAA0E,CAAC;AAClF,OAAO,EAAE,2CAA2C,EAAE,MAAM,yDAAyD,CAAC;AACtH,OAAO,EACL,eAAe,EACf,kCAAkC,GACnC,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,iDAAiD,C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CAAC,CAAC;QACjD,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAC9C,kBAAkB,EAClB,SAAS,CACV,CAAC;QACF,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;YAC1C,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,CAAC;QACD,OAAO,OAAO,CAAC,MAAM,CAAC;IACxB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { and, eq, inArray, or } from \"drizzle-orm\";\nimport { recordSupersededContainerBindingsInTransaction } from \"../../data/persistence/container-contents/supersededContainerBindings\";\nimport {\n deleteDocumentPlacementRowsByContainerIds,\n deleteDocumentPlacementRowsByDocumentIds,\n} from \"../../data/persistence/containers/documentContainerProjectionPersistence\";\nimport { clearDocumentDiscoveryEvidenceOnRemoteReset } from \"../../data/persistence/documents/documentDiscoveryReset\";\nimport {\n queuedUpdateRow,\n unqueueDocumentScopesInTransaction,\n} from \"../../data/sqlite/documentPendingUpdatePersistence\";\nimport { documentIntentLinkTargets } from \"../../data/sqlite/documentPlacementIntentSchema\";\nimport {\n organizationDataUsageCategories,\n organizationDataUsageSnapshots,\n} from \"../../data/sqlite/organizationDataUsageSchema\";\nimport {\n organizationPresentationDenials,\n organizationReadModelContainerGrants,\n organizationReadModelDirectoryUsers,\n organizationReadModelGroupMembers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../data/sqlite/organizationReadModelSchema\";\nimport {\n clientSqlTables,\n containerCreateIntents,\n containerHydrationTombstones,\n containerMoveIntents,\n containers,\n documentAttachmentBlobProjection,\n documentHistoryUpdates,\n documentMoveIntents,\n documentPendingAttachments,\n documentProjection,\n documentSyncFailures,\n documents,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n} from \"../../data/sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../data/sqlite/sqlTableSchema\";\nimport { verifiedAccessManifestBundles } from \"../../data/sqlite/verifiedManifestBundleSchema\";\nimport { runOrganizationPresentationReset } from \"../organizations/organizationPresentationAccessState\";\nimport { clearResetPendingAttachments } from \"./remoteResetAttachments\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\nimport { clearRemoteResetSyncCursors } from \"./remoteResetCursorScope\";\nimport {\n buildResetPlans,\n type ResetAttachmentUpload,\n type ResetDocumentUpdate,\n} from \"./remoteResetPlans\";\nimport { clearRemoteResetPrincipalRows } from \"./remoteResetPrincipalScope\";\nimport {\n type RemoteResetInput,\n type RemoteSyncStateSnapshot,\n readRemoteSyncStateSnapshot,\n} from \"./remoteResetScope\";\n\nexport type {\n RemoteResetInput,\n RemoteResetReplacement,\n} from \"./remoteResetScope\";\n\nconst CONTAINER_CREATE_INTENT_TYPE = \"container.create\";\n\nexport interface ClearRemoteSyncStateResult {\n readonly clearedContainerCreateIntentCount: number;\n readonly clearedContainerMoveIntentCount: number;\n readonly clearedDocumentMoveIntentCount: number;\n readonly clearedPrincipalPolicyCount: number;\n readonly clearedSyncCursorCount: number;\n readonly queuedAttachmentUploadCount: number;\n readonly queuedContainerCreateCount: number;\n readonly queuedDocumentUpdateCount: number;\n readonly resetContainerCount: number;\n readonly resetDocumentCount: number;\n}\n\nasync function clearOrganizationPresentationRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n for (const table of [\n organizationDataUsageCategories,\n organizationDataUsageSnapshots,\n organizationReadModelContainerGrants,\n organizationReadModelGroupMembers,\n organizationReadModelDirectoryUsers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n organizationPresentationDenials,\n ] as const) {\n await tx\n .delete(table)\n .where(eq(table.organizationId, organizationId))\n .run();\n }\n}\n\ninterface ScopedRemoteRowsInput {\n attachmentUploads: readonly ResetAttachmentUpload[];\n organizationId: string;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}\n\nasync function clearScopedContainerRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n for (const containerBatch of remoteResetBatches(\n input.snapshot.containerIds,\n )) {\n await deleteDocumentPlacementRowsByContainerIds(input.tx, containerBatch);\n await input.tx\n .delete(containerMoveIntents)\n .where(inArray(containerMoveIntents.containerId, containerBatch))\n .run();\n await input.tx\n .delete(containerCreateIntents)\n .where(inArray(containerCreateIntents.containerId, containerBatch))\n .run();\n await input.tx\n .delete(containerHydrationTombstones)\n .where(inArray(containerHydrationTombstones.containerId, containerBatch))\n .run();\n }\n}\n\nasync function clearScopedDocumentRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n const { snapshot, tx } = input;\n for (const documentIdBatch of remoteResetBatches(snapshot.oldDocumentIds)) {\n await deleteDocumentPlacementRowsByDocumentIds(tx, documentIdBatch);\n }\n await clearResetPendingAttachments({\n attachmentUploads: input.attachmentUploads,\n documentLocalIds: snapshot.documentLocalIds,\n tx,\n });\n for (const localIdBatch of remoteResetBatches(snapshot.documentLocalIds)) {\n await tx\n .delete(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n tx\n .select({ id: documentMoveIntents.id })\n .from(documentMoveIntents)\n .where(inArray(documentMoveIntents.localId, localIdBatch)),\n ),\n )\n .run();\n await tx\n .delete(documentMoveIntents)\n .where(inArray(documentMoveIntents.localId, localIdBatch))\n .run();\n }\n for (const documentBatch of remoteResetBatches(snapshot.documentRows)) {\n await unqueueDocumentScopesInTransaction(tx, documentBatch);\n await tx\n .delete(documentSyncFailures)\n .where(\n or(\n ...documentBatch.map((row) =>\n and(\n eq(documentSyncFailures.appKind, row.appKind),\n eq(documentSyncFailures.localId, row.localId),\n ),\n ),\n ),\n )\n .run();\n }\n}\n\nasync function clearScopedRemoteRows(\n input: ScopedRemoteRowsInput,\n): Promise<void> {\n const { organizationId, tx } = input;\n await clearOrganizationPresentationRows(tx, organizationId);\n for (const table of [\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n verifiedAccessManifestBundles,\n ] as const) {\n await tx\n .delete(table)\n .where(eq(table.organizationId, organizationId))\n .run();\n }\n await clearDocumentDiscoveryEvidenceOnRemoteReset(tx, {\n containerIds: input.snapshot.containerIds,\n documentIds: input.snapshot.oldDocumentIds,\n });\n await clearRemoteResetPrincipalRows(input);\n await clearScopedContainerRows(input);\n await clearScopedDocumentRows(input);\n await clearRemoteResetSyncCursors({\n containerIds: input.snapshot.containerIds,\n tx,\n });\n}\n\nasync function resetRemoteColumns(input: {\n now: string;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { now, reset, snapshot, tx } = input;\n for (const row of snapshot.documentRows) {\n await tx\n .update(documents)\n .set({\n accessEpoch: 1,\n accessStateHash: null,\n contentKeyBundle: null,\n documentId: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n lastCommitLsn: null,\n pullContinuation: null,\n recoveryDocumentId: row.documentId ?? row.recoveryDocumentId,\n updatedAt: now,\n })\n .where(\n and(\n eq(documents.appKind, row.appKind),\n eq(documents.localId, row.localId),\n ),\n )\n .run();\n }\n for (const localIdBatch of remoteResetBatches(snapshot.documentLocalIds)) {\n await tx\n .update(documentProjection)\n .set({\n documentId: null,\n organizationId:\n reset.replacement?.organizationId ?? reset.organizationId,\n })\n .where(inArray(documentProjection.localId, localIdBatch))\n .run();\n }\n // Replacement re-homes folders under their ids; the purged organization\n // can never bind them again on this device.\n for (const containerIds of reset.replacement\n ? remoteResetBatches(snapshot.containerIds)\n : []) {\n await recordSupersededContainerBindingsInTransaction(tx, {\n containerIds,\n organizationId: reset.organizationId,\n supersededAt: now,\n });\n }\n for (const row of snapshot.containerRows) {\n await tx\n .update(containers)\n .set({\n metadataDocumentId: null,\n organizationId:\n reset.replacement?.organizationId ?? reset.organizationId,\n parentId:\n reset.replacement && row.parentId === null\n ? reset.replacement.rootContainerId\n : row.parentId,\n serverCreatedAt: null,\n serverUpdatedAt: null,\n ...(reset.replacement ? { systemSlot: null } : {}),\n localUpdatedAt: now,\n })\n .where(eq(containers.id, row.id))\n .run();\n }\n}\n\nasync function queueResetDocumentUpdates(input: {\n documentUpdates: readonly ResetDocumentUpdate[];\n now: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const updateBatch of remoteResetBatches(input.documentUpdates)) {\n await input.tx\n .insert(documentHistoryUpdates)\n .values(\n updateBatch.map((update) =>\n queuedUpdateRow({\n createdAt: input.now,\n origin: \"outbox\",\n pendingUpdate: update,\n scope: update,\n updateId: crypto.randomUUID(),\n }),\n ),\n )\n .run();\n }\n}\n\nasync function queueResetContainerCreates(input: {\n now: string;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<number> {\n const rows = input.snapshot.containerRows.flatMap((row) => {\n const parentId =\n row.parentId ?? input.reset.replacement?.rootContainerId ?? null;\n return parentId ? [{ id: row.id, parentId }] : [];\n });\n if (rows.length === 0) return 0;\n for (const rowBatch of remoteResetBatches(rows)) {\n await input.tx\n .insert(containerCreateIntents)\n .values(\n rowBatch.map((row) => ({\n id: crypto.randomUUID(),\n containerId: row.id,\n parentContainerId: row.parentId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\" as const,\n remoteContainerId: null,\n remoteMetadataAccessStateHash: null,\n remoteMetadataDocumentId: null,\n lastError: null,\n createdAt: input.now,\n updatedAt: input.now,\n })),\n )\n .run();\n }\n return rows.length;\n}\n\nasync function queueResetAttachmentUploads(input: {\n attachmentUploads: readonly ResetAttachmentUpload[];\n now: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const attachmentBatch of remoteResetBatches(input.attachmentUploads)) {\n await input.tx\n .insert(documentPendingAttachments)\n .values(\n attachmentBatch.map((attachment) => ({\n ...attachment,\n createdAt: input.now,\n })),\n )\n .run();\n await input.tx\n .delete(documentAttachmentBlobProjection)\n .where(\n or(\n ...attachmentBatch.map((attachment) =>\n and(\n eq(documentAttachmentBlobProjection.localId, attachment.localId),\n eq(documentAttachmentBlobProjection.slotId, attachment.slotId),\n ),\n ),\n ),\n )\n .run();\n }\n}\n\nasync function clearRemoteSyncStateInTransaction(input: {\n plans: Awaited<ReturnType<typeof buildResetPlans>>;\n reset: RemoteResetInput;\n snapshot: RemoteSyncStateSnapshot;\n tx: ClientSQLiteTransactionScope;\n}): Promise<ClearRemoteSyncStateResult> {\n const now = new Date().toISOString();\n const { snapshot } = input;\n await clearScopedRemoteRows({\n attachmentUploads: input.plans.attachmentUploads,\n organizationId: input.reset.organizationId,\n snapshot,\n tx: input.tx,\n });\n await resetRemoteColumns({ now, reset: input.reset, snapshot, tx: input.tx });\n await queueResetDocumentUpdates({\n documentUpdates: input.plans.documentUpdates,\n now,\n tx: input.tx,\n });\n const queuedContainerCreateCount = await queueResetContainerCreates({\n now,\n reset: input.reset,\n snapshot,\n tx: input.tx,\n });\n await queueResetAttachmentUploads({\n attachmentUploads: input.plans.attachmentUploads,\n now,\n tx: input.tx,\n });\n return {\n clearedContainerCreateIntentCount:\n snapshot.clearedContainerCreateIntentCount,\n clearedContainerMoveIntentCount: snapshot.clearedContainerMoveIntentCount,\n clearedDocumentMoveIntentCount: snapshot.clearedDocumentMoveIntentCount,\n clearedPrincipalPolicyCount: snapshot.clearedPrincipalPolicyCount,\n clearedSyncCursorCount: snapshot.clearedSyncCursorCount,\n queuedAttachmentUploadCount: input.plans.attachmentUploads.length,\n queuedContainerCreateCount,\n queuedDocumentUpdateCount: input.plans.documentUpdates.length,\n resetContainerCount: snapshot.containerRows.length,\n resetDocumentCount: snapshot.documentRows.length,\n };\n}\n\nexport async function clearRemoteSyncState(\n execSql: ExecSql,\n reset: RemoteResetInput,\n canCommit?: (() => boolean) | undefined,\n): Promise<ClearRemoteSyncStateResult> {\n return runOrganizationPresentationReset(\n execSql,\n reset.organizationId,\n async () => {\n await ensureSqlTables(execSql, clientSqlTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const resetInTransaction = async (tx: ClientSQLiteTransactionScope) => {\n if (canCommit && !canCommit()) {\n throw new Error(\n \"Remote sync reset aborted: session identity changed\",\n );\n }\n const snapshot = await readRemoteSyncStateSnapshot(\n tx,\n reset.organizationId,\n );\n const plans = await buildResetPlans(tx, snapshot.documentRows);\n return clearRemoteSyncStateInTransaction({\n plans,\n reset,\n snapshot,\n tx,\n });\n };\n if (!canCommit) {\n return runtime.transaction(resetInTransaction);\n }\n const outcome = await runtime.guardedTransaction(\n resetInTransaction,\n canCommit,\n );\n if (!outcome.committed || !outcome.result) {\n throw new Error(\"Remote sync reset aborted: session identity changed\");\n }\n return outcome.result;\n },\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { createDocument, exportAllUpdates } from "../../internal/loro/index.js";
2
- import { and, eq, or, sql } from "drizzle-orm";
2
+ import { and, eq, ne, or, sql } from "drizzle-orm";
3
3
  import { getDocumentAttachments, } from "../../data/documents/documentContent.js";
4
4
  import { createPendingUpdateFields } from "../../data/documents/documentSync.js";
5
5
  import { DOCUMENTS_APP_KIND } from "../../data/persistence/documents/documentsPersistence.js";
@@ -37,9 +37,12 @@ async function loadResetHistoryRows(db, documentScopes) {
37
37
  ]
38
38
  : null;
39
39
  for (const scopeBatch of scopes ? remoteResetBatches(scopes) : [null]) {
40
+ // An outbox row only waits to be sent; the content lives in the
41
+ // checkpoint and tail rows (see `documentHistoryUpdates`).
42
+ const notOutbox = ne(documentHistoryUpdates.origin, "outbox");
40
43
  const scopeTail = scopeBatch
41
- ? or(...scopeBatch.map((scope) => and(eq(documentHistoryUpdates.appKind, scope.appKind), eq(documentHistoryUpdates.localId, scope.localId))))
42
- : undefined;
44
+ ? and(notOutbox, or(...scopeBatch.map((scope) => and(eq(documentHistoryUpdates.appKind, scope.appKind), eq(documentHistoryUpdates.localId, scope.localId)))))
45
+ : notOutbox;
43
46
  const scopeCheckpoints = scopeBatch
44
47
  ? or(...scopeBatch.map((scope) => and(eq(documentHistoryCheckpoints.appKind, scope.appKind), eq(documentHistoryCheckpoints.localId, scope.localId))))
45
48
  : undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"remoteResetPlans.js","sourceRoot":"","sources":["remoteResetPlans.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAEL,sBAAsB,GACvB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAAE,kBAAkB,EAAE,MAAM,uDAAuD,CAAC;AAC3F,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,sBAAsB,EACtB,0BAA0B,EAC1B,SAAS,GACV,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAuB1D,SAAS,eAAe,CAAC,OAAe,EAAE,OAAe;IACvD,OAAO,GAAG,OAAO,IAAI,OAAO,EAAE,CAAC;AACjC,CAAC;AAED,SAAS,kBAAkB,CAAC,OAAe,EAAE,MAAc;IACzD,OAAO,GAAG,OAAO,KAAK,MAAM,EAAE,CAAC;AACjC,CAAC;AAED,SAAS,gBAAgB,CAAC,KAIzB;IACC,MAAM,MAAM,GAAG,yBAAyB,CAAC,gBAAgB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IACtE,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,OAAO,EAAE,KAAK,CAAC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AEH,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,CAAC;AAChD,CAAC","sourcesContent":["import { createDocument, exportAllUpdates } from \"@tearleads/loro\";\nimport { and, eq, or, sql } from \"drizzle-orm\";\nimport {\n type DocumentAttachment,\n getDocumentAttachments,\n} from \"../../data/documents/documentContent\";\nimport { createPendingUpdateFields } from \"../../data/documents/documentSync\";\nimport { DOCUMENTS_APP_KIND } from \"../../data/persistence/documents/documentsPersistence\";\nimport {\n documentAttachmentBlobProjection,\n documentHistoryCheckpoints,\n documentHistoryUpdates,\n documentPendingAttachments,\n documents,\n} from \"../../data/sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport { importDocumentHistoryTailUpdates } from \"../documents/historyContent\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\n\nexport interface ResetDocumentUpdate {\n readonly appKind: string;\n readonly localId: string;\n readonly updateData: string;\n readonly partialStartVersionVector: string;\n readonly partialEndVersionVector: string;\n readonly sourceVersionVector: string | null;\n}\n\nexport interface ResetAttachmentUpload {\n readonly byteLength: number;\n readonly contentSha256: string;\n readonly localId: string;\n readonly mimeType: string | null;\n readonly name: string;\n readonly slotId: string;\n readonly storageKey: string;\n}\n\ntype ResetContentDoc = Awaited<ReturnType<typeof createDocument>>;\n\nfunction historyScopeKey(appKind: string, localId: string): string {\n return `${appKind} ${localId}`;\n}\n\nfunction attachmentScopeKey(localId: string, slotId: string): string {\n return `${localId}\\0${slotId}`;\n}\n\nfunction buildResetUpdate(input: {\n appKind: string;\n doc: ResetContentDoc;\n localId: string;\n}): ResetDocumentUpdate | null {\n const fields = createPendingUpdateFields(exportAllUpdates(input.doc));\n if (!fields) {\n return null;\n }\n\n return {\n appKind: input.appKind,\n localId: input.localId,\n updateData: fields.updateData,\n partialStartVersionVector: fields.partialStartVersionVector,\n partialEndVersionVector: fields.partialEndVersionVector,\n sourceVersionVector: fields.sourceVersionVector ?? null,\n };\n}\n\ninterface ResetHistoryRows {\n checkpointRows: Array<{\n appKind: string;\n localId: string;\n snapshot: string;\n }>;\n tailRows: Array<{\n appKind: string;\n localId: string;\n updateData: string;\n }>;\n}\n\nasync function loadResetHistoryRows(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n): Promise<ResetHistoryRows> {\n const rows: ResetHistoryRows = { checkpointRows: [], tailRows: [] };\n const scopes = documentScopes\n ? [\n ...new Map(\n documentScopes.map((scope) => [\n historyScopeKey(scope.appKind, scope.localId),\n scope,\n ]),\n ).values(),\n ]\n : null;\n for (const scopeBatch of scopes ? remoteResetBatches(scopes) : [null]) {\n const scopeTail = scopeBatch\n ? or(\n ...scopeBatch.map((scope) =>\n and(\n eq(documentHistoryUpdates.appKind, scope.appKind),\n eq(documentHistoryUpdates.localId, scope.localId),\n ),\n ),\n )\n : undefined;\n const scopeCheckpoints = scopeBatch\n ? or(\n ...scopeBatch.map((scope) =>\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n ),\n ),\n )\n : undefined;\n const tailBatch = await db\n .select({\n appKind: documentHistoryUpdates.appKind,\n localId: documentHistoryUpdates.localId,\n updateData: documentHistoryUpdates.updateData,\n })\n .from(documentHistoryUpdates)\n .where(scopeTail)\n .orderBy(sql`rowid`);\n const checkpointBatch = await db\n .select({\n appKind: documentHistoryCheckpoints.appKind,\n localId: documentHistoryCheckpoints.localId,\n snapshot: documentHistoryCheckpoints.snapshot,\n })\n .from(documentHistoryCheckpoints)\n .where(scopeCheckpoints);\n rows.tailRows.push(...tailBatch);\n rows.checkpointRows.push(...checkpointBatch);\n }\n return rows;\n}\n\n/**\n * Reconstruct every persisted document's content from the durable-history\n * tables (checkpoint + tail) — the only content source. A scope without a\n * checkpoint (a discovered shell that never hydrated) gets no doc: it has no\n * content to republish and no attachments to requeue. The mode-sniffing tail\n * import handles both content kinds — full-history snapshots (documents) and\n * exported-updates blobs (container metadata).\n */\nasync function buildResetContentDocs(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n): Promise<Map<string, ResetContentDoc>> {\n // Read the TAIL before the checkpoints (the same order the restore path\n // uses): a compaction landing between the two reads then yields old-tail +\n // new-checkpoint — a safe superset, since replay is idempotent by op\n // identity — whereas the reverse order could yield an old checkpoint plus\n // an already-emptied tail and republish stale content.\n const { checkpointRows, tailRows } = await loadResetHistoryRows(\n db,\n documentScopes,\n );\n\n const tailByScope = new Map<string, string[]>();\n for (const row of tailRows) {\n const key = historyScopeKey(row.appKind, row.localId);\n const tail = tailByScope.get(key);\n if (tail) {\n tail.push(row.updateData);\n } else {\n tailByScope.set(key, [row.updateData]);\n }\n }\n\n // Rebuild the UNION of checkpoint and tail scopes: a tail-only scope (a\n // crash landed the first edit's tail row before the birth checkpoint) may\n // hold the only durable copy of that edit, and dropping it from the reset\n // would discard it.\n const checkpointByScope = new Map(\n checkpointRows.map((row) => [\n historyScopeKey(row.appKind, row.localId),\n row,\n ]),\n );\n const historyScopes = new Map<string, { appKind: string; localId: string }>();\n for (const row of [...checkpointRows, ...tailRows]) {\n historyScopes.set(historyScopeKey(row.appKind, row.localId), {\n appKind: row.appKind,\n localId: row.localId,\n });\n }\n\n const contentDocByScope = new Map<string, ResetContentDoc>();\n await Promise.all(\n [...historyScopes.entries()].map(async ([key, scope]) => {\n const doc = await createDocument(\n `remote-reset:${scope.appKind}:${scope.localId}`,\n );\n const checkpoint = checkpointByScope.get(key);\n // An empty checkpoint blob (e.g. container metadata saved before any\n // update existed) carries no ops — importing it would throw and fail\n // the whole reset.\n importDocumentHistoryTailUpdates(\n doc,\n [\n ...(checkpoint ? [checkpoint.snapshot] : []),\n ...(tailByScope.get(key) ?? []),\n ].filter((blob) => blob.length > 0),\n );\n contentDocByScope.set(key, doc);\n }),\n );\n return contentDocByScope;\n}\n\nexport interface ResetDocumentScope {\n readonly appKind: string;\n readonly localId: string;\n}\n\nasync function loadResetPlanRows(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n) {\n const selectedScopeKeys = documentScopes\n ? new Set(\n documentScopes.map((scope) =>\n historyScopeKey(scope.appKind, scope.localId),\n ),\n )\n : null;\n const allDocumentRows = await db\n .select({ appKind: documents.appKind, localId: documents.localId })\n .from(documents);\n const documentRows = selectedScopeKeys\n ? allDocumentRows.filter((row) =>\n selectedScopeKeys.has(historyScopeKey(row.appKind, row.localId)),\n )\n : allDocumentRows;\n const [allAttachmentRows, pendingAttachmentRows] = await Promise.all([\n db\n .select({\n byteLength: documentAttachmentBlobProjection.byteLength,\n localId: documentAttachmentBlobProjection.localId,\n mimeType: documentAttachmentBlobProjection.mimeType,\n slotId: documentAttachmentBlobProjection.slotId,\n storageKey: documentAttachmentBlobProjection.storageKey,\n })\n .from(documentAttachmentBlobProjection),\n db\n .select({\n byteLength: documentPendingAttachments.byteLength,\n localId: documentPendingAttachments.localId,\n mimeType: documentPendingAttachments.mimeType,\n slotId: documentPendingAttachments.slotId,\n storageKey: documentPendingAttachments.storageKey,\n })\n .from(documentPendingAttachments),\n ]);\n const selectedDocumentLocalIds = new Set(\n documentRows\n .filter((row) => row.appKind === DOCUMENTS_APP_KIND)\n .map((row) => row.localId),\n );\n const attachmentRows = new Map(\n allAttachmentRows\n .filter((row) => selectedDocumentLocalIds.has(row.localId))\n .map((row) => [attachmentScopeKey(row.localId, row.slotId), row]),\n );\n for (const row of pendingAttachmentRows) {\n if (selectedDocumentLocalIds.has(row.localId)) {\n attachmentRows.set(attachmentScopeKey(row.localId, row.slotId), row);\n }\n }\n return {\n attachmentRows: [...attachmentRows.values()],\n documentRows,\n };\n}\n\nexport async function buildResetPlans(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n): Promise<{\n readonly attachmentUploads: ResetAttachmentUpload[];\n readonly documentUpdates: ResetDocumentUpdate[];\n}> {\n const { attachmentRows, documentRows } = await loadResetPlanRows(\n db,\n documentScopes,\n );\n const contentDocByScope = await buildResetContentDocs(db, documentScopes);\n const documentUpdates = documentRows.flatMap((row) => {\n const doc = contentDocByScope.get(\n historyScopeKey(row.appKind, row.localId),\n );\n if (!doc) {\n return [];\n }\n const update = buildResetUpdate({\n appKind: row.appKind,\n doc,\n localId: row.localId,\n });\n return update ? [update] : [];\n });\n const attachmentIntentMaps = new Map<\n string,\n Map<string, DocumentAttachment>\n >();\n const attachmentLocalIds = [\n ...new Set(attachmentRows.map((attachment) => attachment.localId)),\n ];\n for (const localId of attachmentLocalIds) {\n const doc = contentDocByScope.get(\n historyScopeKey(DOCUMENTS_APP_KIND, localId),\n );\n if (!doc) {\n continue;\n }\n attachmentIntentMaps.set(\n localId,\n new Map(\n getDocumentAttachments(doc).map((attachment) => [\n attachment.slotId,\n attachment,\n ]),\n ),\n );\n }\n\n // A reset re-uploads the local attachments as pending work, and the durable\n // document decides which rows those are: a row whose slot the snapshot no\n // longer advertises belongs to an unlink, and re-queueing it would resurrect\n // an attachment the document dropped. Reading the snapshot rather than the\n // detach marker keeps the two halves of an interrupted unlink consistent —\n // there the marker is set but the snapshot still advertises the slot, and the\n // reset has to upload it to match the document it is about to republish.\n const attachmentUploads = attachmentRows.flatMap((attachment) => {\n const intent = attachmentIntentMaps\n .get(attachment.localId)\n ?.get(attachment.slotId);\n if (intent === undefined) {\n return [];\n }\n\n return [\n {\n byteLength: attachment.byteLength,\n contentSha256: intent.contentSha256,\n localId: attachment.localId,\n mimeType: attachment.mimeType,\n name: intent.name,\n slotId: attachment.slotId,\n storageKey: attachment.storageKey,\n },\n ];\n });\n\n return { attachmentUploads, documentUpdates };\n}\n"]}
1
+ {"version":3,"file":"remoteResetPlans.js","sourceRoot":"","sources":["remoteResetPlans.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAA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,GAAG,EAAE,CAAC;YACT,SAAS;QACX,CAAC;QACD,oBAAoB,CAAC,GAAG,CACtB,OAAO,EACP,IAAI,GAAG,CACL,sBAAsB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC;YAC9C,UAAU,CAAC,MAAM;YACjB,UAAU;SACX,CAAC,CACH,CACF,CAAC;IACJ,CAAC;IAED,4EAA4E;IAC5E,0EAA0E;IAC1E,6EAA6E;IAC7E,2EAA2E;IAC3E,2EAA2E;IAC3E,8EAA8E;IAC9E,yEAAyE;IACzE,MAAM,iBAAiB,GAAG,cAAc,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE;QAC9D,MAAM,MAAM,GAAG,oBAAoB;aAChC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC;YACxB,EAAE,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QAC3B,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACzB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,OAAO;YACL;gBACE,UAAU,EAAE,UAAU,CAAC,UAAU;gBACjC,aAAa,EAAE,MAAM,CAAC,aAAa;gBACnC,OAAO,EAAE,UAAU,CAAC,OAAO;gBAC3B,QAAQ,EAAE,UAAU,CAAC,QAAQ;gBAC7B,IAAI,EAAE,MAAM,CAAC,IAAI;gBACjB,MAAM,EAAE,UAAU,CAAC,MAAM;gBACzB,UAAU,EAAE,UAAU,CAAC,UAAU;aAClC;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,CAAC;AAChD,CAAC","sourcesContent":["import { createDocument, exportAllUpdates } from \"@tearleads/loro\";\nimport { and, eq, ne, or, sql } from \"drizzle-orm\";\nimport {\n type DocumentAttachment,\n getDocumentAttachments,\n} from \"../../data/documents/documentContent\";\nimport { createPendingUpdateFields } from \"../../data/documents/documentSync\";\nimport { DOCUMENTS_APP_KIND } from \"../../data/persistence/documents/documentsPersistence\";\nimport {\n documentAttachmentBlobProjection,\n documentHistoryCheckpoints,\n documentHistoryUpdates,\n documentPendingAttachments,\n documents,\n} from \"../../data/sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport { importDocumentHistoryTailUpdates } from \"../documents/historyContent\";\nimport { remoteResetBatches } from \"./remoteResetBatches\";\n\nexport interface ResetDocumentUpdate {\n readonly appKind: string;\n readonly localId: string;\n readonly updateData: string;\n readonly partialStartVersionVector: string;\n readonly partialEndVersionVector: string;\n readonly sourceVersionVector: string | null;\n}\n\nexport interface ResetAttachmentUpload {\n readonly byteLength: number;\n readonly contentSha256: string;\n readonly localId: string;\n readonly mimeType: string | null;\n readonly name: string;\n readonly slotId: string;\n readonly storageKey: string;\n}\n\ntype ResetContentDoc = Awaited<ReturnType<typeof createDocument>>;\n\nfunction historyScopeKey(appKind: string, localId: string): string {\n return `${appKind} ${localId}`;\n}\n\nfunction attachmentScopeKey(localId: string, slotId: string): string {\n return `${localId}\\0${slotId}`;\n}\n\nfunction buildResetUpdate(input: {\n appKind: string;\n doc: ResetContentDoc;\n localId: string;\n}): ResetDocumentUpdate | null {\n const fields = createPendingUpdateFields(exportAllUpdates(input.doc));\n if (!fields) {\n return null;\n }\n\n return {\n appKind: input.appKind,\n localId: input.localId,\n updateData: fields.updateData,\n partialStartVersionVector: fields.partialStartVersionVector,\n partialEndVersionVector: fields.partialEndVersionVector,\n sourceVersionVector: fields.sourceVersionVector ?? null,\n };\n}\n\ninterface ResetHistoryRows {\n checkpointRows: Array<{\n appKind: string;\n localId: string;\n snapshot: string;\n }>;\n tailRows: Array<{\n appKind: string;\n localId: string;\n updateData: string;\n }>;\n}\n\nasync function loadResetHistoryRows(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n): Promise<ResetHistoryRows> {\n const rows: ResetHistoryRows = { checkpointRows: [], tailRows: [] };\n const scopes = documentScopes\n ? [\n ...new Map(\n documentScopes.map((scope) => [\n historyScopeKey(scope.appKind, scope.localId),\n scope,\n ]),\n ).values(),\n ]\n : null;\n for (const scopeBatch of scopes ? remoteResetBatches(scopes) : [null]) {\n // An outbox row only waits to be sent; the content lives in the\n // checkpoint and tail rows (see `documentHistoryUpdates`).\n const notOutbox = ne(documentHistoryUpdates.origin, \"outbox\");\n const scopeTail = scopeBatch\n ? and(\n notOutbox,\n or(\n ...scopeBatch.map((scope) =>\n and(\n eq(documentHistoryUpdates.appKind, scope.appKind),\n eq(documentHistoryUpdates.localId, scope.localId),\n ),\n ),\n ),\n )\n : notOutbox;\n const scopeCheckpoints = scopeBatch\n ? or(\n ...scopeBatch.map((scope) =>\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n ),\n ),\n )\n : undefined;\n const tailBatch = await db\n .select({\n appKind: documentHistoryUpdates.appKind,\n localId: documentHistoryUpdates.localId,\n updateData: documentHistoryUpdates.updateData,\n })\n .from(documentHistoryUpdates)\n .where(scopeTail)\n .orderBy(sql`rowid`);\n const checkpointBatch = await db\n .select({\n appKind: documentHistoryCheckpoints.appKind,\n localId: documentHistoryCheckpoints.localId,\n snapshot: documentHistoryCheckpoints.snapshot,\n })\n .from(documentHistoryCheckpoints)\n .where(scopeCheckpoints);\n rows.tailRows.push(...tailBatch);\n rows.checkpointRows.push(...checkpointBatch);\n }\n return rows;\n}\n\n/**\n * Reconstruct every persisted document's content from the durable-history\n * tables (checkpoint + tail) — the only content source. A scope without a\n * checkpoint (a discovered shell that never hydrated) gets no doc: it has no\n * content to republish and no attachments to requeue. The mode-sniffing tail\n * import handles both content kinds — full-history snapshots (documents) and\n * exported-updates blobs (container metadata).\n */\nasync function buildResetContentDocs(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n): Promise<Map<string, ResetContentDoc>> {\n // Read the TAIL before the checkpoints (the same order the restore path\n // uses): a compaction landing between the two reads then yields old-tail +\n // new-checkpoint — a safe superset, since replay is idempotent by op\n // identity — whereas the reverse order could yield an old checkpoint plus\n // an already-emptied tail and republish stale content.\n const { checkpointRows, tailRows } = await loadResetHistoryRows(\n db,\n documentScopes,\n );\n\n const tailByScope = new Map<string, string[]>();\n for (const row of tailRows) {\n const key = historyScopeKey(row.appKind, row.localId);\n const tail = tailByScope.get(key);\n if (tail) {\n tail.push(row.updateData);\n } else {\n tailByScope.set(key, [row.updateData]);\n }\n }\n\n // Rebuild the UNION of checkpoint and tail scopes: a tail-only scope (a\n // crash landed the first edit's tail row before the birth checkpoint) may\n // hold the only durable copy of that edit, and dropping it from the reset\n // would discard it.\n const checkpointByScope = new Map(\n checkpointRows.map((row) => [\n historyScopeKey(row.appKind, row.localId),\n row,\n ]),\n );\n const historyScopes = new Map<string, { appKind: string; localId: string }>();\n for (const row of [...checkpointRows, ...tailRows]) {\n historyScopes.set(historyScopeKey(row.appKind, row.localId), {\n appKind: row.appKind,\n localId: row.localId,\n });\n }\n\n const contentDocByScope = new Map<string, ResetContentDoc>();\n await Promise.all(\n [...historyScopes.entries()].map(async ([key, scope]) => {\n const doc = await createDocument(\n `remote-reset:${scope.appKind}:${scope.localId}`,\n );\n const checkpoint = checkpointByScope.get(key);\n // An empty checkpoint blob (e.g. container metadata saved before any\n // update existed) carries no ops — importing it would throw and fail\n // the whole reset.\n importDocumentHistoryTailUpdates(\n doc,\n [\n ...(checkpoint ? [checkpoint.snapshot] : []),\n ...(tailByScope.get(key) ?? []),\n ].filter((blob) => blob.length > 0),\n );\n contentDocByScope.set(key, doc);\n }),\n );\n return contentDocByScope;\n}\n\nexport interface ResetDocumentScope {\n readonly appKind: string;\n readonly localId: string;\n}\n\nasync function loadResetPlanRows(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n) {\n const selectedScopeKeys = documentScopes\n ? new Set(\n documentScopes.map((scope) =>\n historyScopeKey(scope.appKind, scope.localId),\n ),\n )\n : null;\n const allDocumentRows = await db\n .select({ appKind: documents.appKind, localId: documents.localId })\n .from(documents);\n const documentRows = selectedScopeKeys\n ? allDocumentRows.filter((row) =>\n selectedScopeKeys.has(historyScopeKey(row.appKind, row.localId)),\n )\n : allDocumentRows;\n const [allAttachmentRows, pendingAttachmentRows] = await Promise.all([\n db\n .select({\n byteLength: documentAttachmentBlobProjection.byteLength,\n localId: documentAttachmentBlobProjection.localId,\n mimeType: documentAttachmentBlobProjection.mimeType,\n slotId: documentAttachmentBlobProjection.slotId,\n storageKey: documentAttachmentBlobProjection.storageKey,\n })\n .from(documentAttachmentBlobProjection),\n db\n .select({\n byteLength: documentPendingAttachments.byteLength,\n localId: documentPendingAttachments.localId,\n mimeType: documentPendingAttachments.mimeType,\n slotId: documentPendingAttachments.slotId,\n storageKey: documentPendingAttachments.storageKey,\n })\n .from(documentPendingAttachments),\n ]);\n const selectedDocumentLocalIds = new Set(\n documentRows\n .filter((row) => row.appKind === DOCUMENTS_APP_KIND)\n .map((row) => row.localId),\n );\n const attachmentRows = new Map(\n allAttachmentRows\n .filter((row) => selectedDocumentLocalIds.has(row.localId))\n .map((row) => [attachmentScopeKey(row.localId, row.slotId), row]),\n );\n for (const row of pendingAttachmentRows) {\n if (selectedDocumentLocalIds.has(row.localId)) {\n attachmentRows.set(attachmentScopeKey(row.localId, row.slotId), row);\n }\n }\n return {\n attachmentRows: [...attachmentRows.values()],\n documentRows,\n };\n}\n\nexport async function buildResetPlans(\n db: ClientSQLiteTransactionScope,\n documentScopes?: readonly ResetDocumentScope[],\n): Promise<{\n readonly attachmentUploads: ResetAttachmentUpload[];\n readonly documentUpdates: ResetDocumentUpdate[];\n}> {\n const { attachmentRows, documentRows } = await loadResetPlanRows(\n db,\n documentScopes,\n );\n const contentDocByScope = await buildResetContentDocs(db, documentScopes);\n const documentUpdates = documentRows.flatMap((row) => {\n const doc = contentDocByScope.get(\n historyScopeKey(row.appKind, row.localId),\n );\n if (!doc) {\n return [];\n }\n const update = buildResetUpdate({\n appKind: row.appKind,\n doc,\n localId: row.localId,\n });\n return update ? [update] : [];\n });\n const attachmentIntentMaps = new Map<\n string,\n Map<string, DocumentAttachment>\n >();\n const attachmentLocalIds = [\n ...new Set(attachmentRows.map((attachment) => attachment.localId)),\n ];\n for (const localId of attachmentLocalIds) {\n const doc = contentDocByScope.get(\n historyScopeKey(DOCUMENTS_APP_KIND, localId),\n );\n if (!doc) {\n continue;\n }\n attachmentIntentMaps.set(\n localId,\n new Map(\n getDocumentAttachments(doc).map((attachment) => [\n attachment.slotId,\n attachment,\n ]),\n ),\n );\n }\n\n // A reset re-uploads the local attachments as pending work, and the durable\n // document decides which rows those are: a row whose slot the snapshot no\n // longer advertises belongs to an unlink, and re-queueing it would resurrect\n // an attachment the document dropped. Reading the snapshot rather than the\n // detach marker keeps the two halves of an interrupted unlink consistent —\n // there the marker is set but the snapshot still advertises the slot, and the\n // reset has to upload it to match the document it is about to republish.\n const attachmentUploads = attachmentRows.flatMap((attachment) => {\n const intent = attachmentIntentMaps\n .get(attachment.localId)\n ?.get(attachment.slotId);\n if (intent === undefined) {\n return [];\n }\n\n return [\n {\n byteLength: attachment.byteLength,\n contentSha256: intent.contentSha256,\n localId: attachment.localId,\n mimeType: attachment.mimeType,\n name: intent.name,\n slotId: attachment.slotId,\n storageKey: attachment.storageKey,\n },\n ];\n });\n\n return { attachmentUploads, documentUpdates };\n}\n"]}
@@ -1,107 +0,0 @@
1
- import { captureProjectionHistory, restoreProjectionHistory, } from "../crypto/index.js";
2
- import { isContainerWriterProjectionResponse, isDocumentWriterProjectionResponse, } from "../validators/response/index.js";
3
- import { PROJECTION_HISTORY_HINT_CHARACTERS, ProjectionHistoryPrefixesSchema, } from "../validators/util/index.js";
4
- import { registerProjectionHistoryAdmission } from "./verifiedProjectionHistory.js";
5
- const MAX_HISTORY_CHARACTERS = 16_000_000;
6
- const MAX_PROJECTIONS = 16;
7
- /** Session-scoped evidence cache, independent of the short-lived current-head cache. */
8
- export class ProjectionHistoryTransport {
9
- retained = new Map();
10
- characters = 0;
11
- generation = 0;
12
- clear() {
13
- this.generation += 1;
14
- this.characters = 0;
15
- this.retained.clear();
16
- }
17
- remember(path, entries) {
18
- const characters = JSON.stringify(entries).length;
19
- if (characters > MAX_HISTORY_CHARACTERS)
20
- return;
21
- this.characters -= this.retained.get(path)?.characters ?? 0;
22
- this.retained.delete(path);
23
- this.retained.set(path, { entries, characters });
24
- this.characters += characters;
25
- while (this.characters > MAX_HISTORY_CHARACTERS ||
26
- this.retained.size > MAX_PROJECTIONS) {
27
- const oldest = this.retained.entries().next().value;
28
- if (!oldest)
29
- break;
30
- this.characters -= oldest[1].characters;
31
- this.retained.delete(oldest[0]);
32
- }
33
- }
34
- prepare(path, validator, method, options, operation) {
35
- if (method !== "GET" ||
36
- ![
37
- "containers.writerProjection.get",
38
- "documents.writerProjection.get",
39
- ].includes(operation.id))
40
- return { options, validator };
41
- const generation = this.generation;
42
- const mayRetain = options?.headers === undefined;
43
- const candidates = mayRetain
44
- ? (this.retained.get(path)?.entries ?? [])
45
- : [];
46
- const requested = [];
47
- for (const entry of candidates) {
48
- const prefixes = [...requested, entry].map((item) => item.prefix);
49
- if (!ProjectionHistoryPrefixesSchema.safeParse(prefixes).success)
50
- continue;
51
- // Bound negotiation headers; deep paths merely omit fewer hints.
52
- if (encodeURIComponent(JSON.stringify(prefixes)).length <=
53
- PROJECTION_HISTORY_HINT_CHARACTERS)
54
- requested.push(entry);
55
- }
56
- const hint = JSON.stringify(requested.map((entry) => entry.prefix));
57
- const requestOptions = requested.length
58
- ? {
59
- ...options,
60
- headers: { "x-projection-history": encodeURIComponent(hint) },
61
- }
62
- : options;
63
- return {
64
- options: requestOptions,
65
- validator: (value) => {
66
- if (!validator(value))
67
- return false;
68
- let projection;
69
- if (isContainerWriterProjectionResponse(value) ||
70
- isDocumentWriterProjectionResponse(value))
71
- projection = value;
72
- else
73
- return false;
74
- // A transparent token-refresh retry still holds its requested bytes.
75
- // Restore them here; the admission guard below preserves auth clearing.
76
- if (!restoreProjectionHistory(projection, requested) ||
77
- !validator(value))
78
- return false;
79
- const captured = JSON.stringify(captureProjectionHistory(projection).map((entry) => entry.prefix));
80
- registerProjectionHistoryAdmission(projection, () => {
81
- if (!mayRetain || generation !== this.generation)
82
- return;
83
- // A consumer may mutate a decoded object. Never retain bytes other
84
- // than the exact evidence that passed through the verification call.
85
- const observed = captureProjectionHistory(projection);
86
- if (JSON.stringify(observed.map((entry) => entry.prefix)) !== captured)
87
- return;
88
- this.remember(path, observed);
89
- });
90
- return true;
91
- },
92
- };
93
- }
94
- wrapRequest(request) {
95
- return (path, validator, method, body, options, operation) => {
96
- const prepared = this.prepare(path, validator, method, options, operation);
97
- return request(path, prepared.validator, method, body, prepared.options, operation);
98
- };
99
- }
100
- wrapRequestResult(request) {
101
- return (path, validator, method, body, options, operation) => {
102
- const prepared = this.prepare(path, validator, method, options, operation);
103
- return request(path, prepared.validator, method, body, prepared.options, operation);
104
- };
105
- }
106
- }
107
- //# sourceMappingURL=projectionHistoryTransport.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"projectionHistoryTransport.js","sourceRoot":"","sources":["projectionHistoryTransport.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EAGxB,wBAAwB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,mCAAmC,EACnC,kCAAkC,GACnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,kCAAkC,EAClC,+BAA+B,GAChC,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,kCAAkC,EAAE,MAAM,6BAA6B,CAAC;AAEjF,MAAM,sBAAsB,GAAG,UAAU,CAAC;AAC1C,MAAM,eAAe,GAAG,EAAE,CAAC;AAM3B,wFAAwF;AACxF,MAAM,OAAO,0BAA0B;IACpB,QAAQ,GAAG,IAAI,GAAG,EAA2B,CAAC;IACvD,UAAU,GAAG,CAAC,CAAC;IACf,UAAU,GAAG,CAAC,CAAC;IAEvB,KAAK;QACH,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ACV,CAAC;YACF,OAAO,OAAO,CACZ,IAAI,EACJ,QAAQ,CAAC,SAAS,EAClB,MAAM,EACN,IAAI,EACJ,QAAQ,CAAC,OAAO,EAChB,SAAS,CACV,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;IAED,iBAAiB,CACf,OAAiC;QAEjC,OAAO,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,EAAE;YAC3D,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAC3B,IAAI,EACJ,SAAS,EACT,MAAM,EACN,OAAO,EACP,SAAS,CACV,CAAC;YACF,OAAO,OAAO,CACZ,IAAI,EACJ,QAAQ,CAAC,SAAS,EAClB,MAAM,EACN,IAAI,EACJ,QAAQ,CAAC,OAAO,EAChB,SAAS,CACV,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n captureProjectionHistory,\n type HistoryProjection,\n type RetainedProjectionHistory,\n restoreProjectionHistory,\n} from \"@tearleads/crypto\";\nimport {\n isContainerWriterProjectionResponse,\n isDocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n PROJECTION_HISTORY_HINT_CHARACTERS,\n ProjectionHistoryPrefixesSchema,\n} from \"@tearleads/validators/util\";\nimport type { OperationRequestFn, OperationRequestResultFn } from \"./types\";\nimport { registerProjectionHistoryAdmission } from \"./verifiedProjectionHistory\";\n\nconst MAX_HISTORY_CHARACTERS = 16_000_000;\nconst MAX_PROJECTIONS = 16;\ninterface RetainedHistory {\n readonly entries: RetainedProjectionHistory[];\n readonly characters: number;\n}\n\n/** Session-scoped evidence cache, independent of the short-lived current-head cache. */\nexport class ProjectionHistoryTransport {\n private readonly retained = new Map<string, RetainedHistory>();\n private characters = 0;\n private generation = 0;\n\n clear(): void {\n this.generation += 1;\n this.characters = 0;\n this.retained.clear();\n }\n\n private remember(path: string, entries: RetainedProjectionHistory[]): void {\n const characters = JSON.stringify(entries).length;\n if (characters > MAX_HISTORY_CHARACTERS) return;\n this.characters -= this.retained.get(path)?.characters ?? 0;\n this.retained.delete(path);\n this.retained.set(path, { entries, characters });\n this.characters += characters;\n while (\n this.characters > MAX_HISTORY_CHARACTERS ||\n this.retained.size > MAX_PROJECTIONS\n ) {\n const oldest = this.retained.entries().next().value;\n if (!oldest) break;\n this.characters -= oldest[1].characters;\n this.retained.delete(oldest[0]);\n }\n }\n\n private prepare<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: Parameters<OperationRequestFn>[2],\n options: Parameters<OperationRequestFn>[4],\n operation: Parameters<OperationRequestFn>[5],\n ): {\n options: Parameters<OperationRequestFn>[4];\n validator: (value: unknown) => value is T;\n } {\n if (\n method !== \"GET\" ||\n ![\n \"containers.writerProjection.get\",\n \"documents.writerProjection.get\",\n ].includes(operation.id)\n )\n return { options, validator };\n const generation = this.generation;\n const mayRetain = options?.headers === undefined;\n const candidates = mayRetain\n ? (this.retained.get(path)?.entries ?? [])\n : [];\n const requested: RetainedProjectionHistory[] = [];\n for (const entry of candidates) {\n const prefixes = [...requested, entry].map((item) => item.prefix);\n if (!ProjectionHistoryPrefixesSchema.safeParse(prefixes).success)\n continue;\n // Bound negotiation headers; deep paths merely omit fewer hints.\n if (\n encodeURIComponent(JSON.stringify(prefixes)).length <=\n PROJECTION_HISTORY_HINT_CHARACTERS\n )\n requested.push(entry);\n }\n const hint = JSON.stringify(requested.map((entry) => entry.prefix));\n const requestOptions = requested.length\n ? {\n ...options,\n headers: { \"x-projection-history\": encodeURIComponent(hint) },\n }\n : options;\n return {\n options: requestOptions,\n validator: (value: unknown): value is T => {\n if (!validator(value)) return false;\n let projection: HistoryProjection;\n if (\n isContainerWriterProjectionResponse(value) ||\n isDocumentWriterProjectionResponse(value)\n )\n projection = value;\n else return false;\n // A transparent token-refresh retry still holds its requested bytes.\n // Restore them here; the admission guard below preserves auth clearing.\n if (\n !restoreProjectionHistory(projection, requested) ||\n !validator(value)\n )\n return false;\n const captured = JSON.stringify(\n captureProjectionHistory(projection).map((entry) => entry.prefix),\n );\n registerProjectionHistoryAdmission(projection, () => {\n if (!mayRetain || generation !== this.generation) return;\n // A consumer may mutate a decoded object. Never retain bytes other\n // than the exact evidence that passed through the verification call.\n const observed = captureProjectionHistory(projection);\n if (\n JSON.stringify(observed.map((entry) => entry.prefix)) !== captured\n )\n return;\n this.remember(path, observed);\n });\n return true;\n },\n };\n }\n\n wrapRequest(request: OperationRequestFn): OperationRequestFn {\n return (path, validator, method, body, options, operation) => {\n const prepared = this.prepare(\n path,\n validator,\n method,\n options,\n operation,\n );\n return request(\n path,\n prepared.validator,\n method,\n body,\n prepared.options,\n operation,\n );\n };\n }\n\n wrapRequestResult(\n request: OperationRequestResultFn,\n ): OperationRequestResultFn {\n return (path, validator, method, body, options, operation) => {\n const prepared = this.prepare(\n path,\n validator,\n method,\n options,\n operation,\n );\n return request(\n path,\n prepared.validator,\n method,\n body,\n prepared.options,\n operation,\n );\n };\n }\n}\n"]}
@@ -1,4 +0,0 @@
1
- /** Transport registers immutable candidates; only successful SDK verification admits one. */
2
- export declare function registerProjectionHistoryAdmission(projection: object, admit: () => void): void;
3
- /** Does not grant access or advance a security checkpoint. */
4
- export declare function retainVerifiedProjectionHistory(projection: object): void;
@@ -1,12 +0,0 @@
1
- const admissions = new WeakMap();
2
- /** Transport registers immutable candidates; only successful SDK verification admits one. */
3
- export function registerProjectionHistoryAdmission(projection, admit) {
4
- admissions.set(projection, admit);
5
- }
6
- /** Does not grant access or advance a security checkpoint. */
7
- export function retainVerifiedProjectionHistory(projection) {
8
- const admit = admissions.get(projection);
9
- admissions.delete(projection);
10
- admit?.();
11
- }
12
- //# sourceMappingURL=verifiedProjectionHistory.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"verifiedProjectionHistory.js","sourceRoot":"","sources":["verifiedProjectionHistory.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,GAAG,IAAI,OAAO,EAAsB,CAAC;AAErD,6FAA6F;AAC7F,MAAM,UAAU,kCAAkC,CAChD,UAAkB,EAClB,KAAiB;IAEjB,UAAU,CAAC,GAAG,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;AACpC,CAAC;AAED,8DAA8D;AAC9D,MAAM,UAAU,+BAA+B,CAAC,UAAkB;IAChE,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACzC,UAAU,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAC9B,KAAK,EAAE,EAAE,CAAC;AACZ,CAAC","sourcesContent":["const admissions = new WeakMap<object, () => void>();\n\n/** Transport registers immutable candidates; only successful SDK verification admits one. */\nexport function registerProjectionHistoryAdmission(\n projection: object,\n admit: () => void,\n): void {\n admissions.set(projection, admit);\n}\n\n/** Does not grant access or advance a security checkpoint. */\nexport function retainVerifiedProjectionHistory(projection: object): void {\n const admit = admissions.get(projection);\n admissions.delete(projection);\n admit?.();\n}\n"]}
@@ -1,14 +0,0 @@
1
- import type { ProjectionHistoryPrefix } from "../validators/util/index.js";
2
- import { type HistoryProjection } from "./projectionHistorySlots.js";
3
- export type { HistoryProjection } from "./projectionHistorySlots.js";
4
- export interface RetainedProjectionHistory {
5
- readonly prefix: ProjectionHistoryPrefix;
6
- readonly arrayKey: string;
7
- readonly values: readonly unknown[];
8
- }
9
- /** Byte commitments describe evidence, not an authorization or verification result. */
10
- export declare function captureProjectionHistory(projection: HistoryProjection): RetainedProjectionHistory[];
11
- /** Call only after normal server authorization and stored-evidence verification. */
12
- export declare function omitProjectionHistory<T extends HistoryProjection>(projection: T, hints: readonly ProjectionHistoryPrefix[]): T;
13
- /** Rebuild exact cached evidence before the caller performs all ordinary checks. */
14
- export declare function restoreProjectionHistory(projection: HistoryProjection, requested: readonly RetainedProjectionHistory[]): boolean;
@@ -1,90 +0,0 @@
1
- import { bytesToHex } from "./hex.js";
2
- import { createIncrementalSha256 } from "./incrementalSha256.js";
3
- import { projectionHistoryArrays, } from "./projectionHistorySlots.js";
4
- function historyDigest(key, values) {
5
- const hash = createIncrementalSha256();
6
- hash.update(new TextEncoder().encode(JSON.stringify(["tearleads.projection-history", key, values])));
7
- return bytesToHex(hash.digest());
8
- }
9
- /** Byte commitments describe evidence, not an authorization or verification result. */
10
- export function captureProjectionHistory(projection) {
11
- return projectionHistoryArrays(projection).flatMap((array) => array.chains.flatMap((chain) => {
12
- if (chain.values.length === 0)
13
- return [];
14
- const values = structuredClone(chain.values);
15
- return [
16
- {
17
- arrayKey: array.key,
18
- values,
19
- prefix: {
20
- key: chain.key,
21
- count: values.length,
22
- digest: historyDigest(chain.key, values),
23
- },
24
- },
25
- ];
26
- }));
27
- }
28
- /** Call only after normal server authorization and stored-evidence verification. */
29
- export function omitProjectionHistory(projection, hints) {
30
- if (hints.length === 0)
31
- return projection;
32
- // Server loaders may share arrays and objects between paths. JSON wire
33
- // locations are independent: trimming one must not change another slot.
34
- const result = JSON.parse(JSON.stringify(projection));
35
- const requested = new Map(hints.map((hint) => [hint.key, hint]));
36
- const omitted = [];
37
- for (const array of projectionHistoryArrays(result)) {
38
- const removed = new Map();
39
- for (const chain of array.chains) {
40
- const hint = requested.get(chain.key);
41
- if (!hint || hint.count > chain.values.length)
42
- continue;
43
- const prefix = chain.values.slice(0, hint.count);
44
- if (historyDigest(chain.key, prefix) !== hint.digest)
45
- continue;
46
- for (const item of prefix)
47
- removed.set(item, (removed.get(item) ?? 0) + 1);
48
- omitted.push(hint);
49
- }
50
- const retained = array.values.filter((value) => {
51
- const remaining = removed.get(value) ?? 0;
52
- if (remaining === 0)
53
- return true;
54
- removed.set(value, remaining - 1);
55
- return false;
56
- });
57
- array.values.length = 0;
58
- for (const value of retained)
59
- array.values.push(value);
60
- }
61
- if (omitted.length)
62
- result.historyPrefixes = omitted;
63
- return result;
64
- }
65
- /** Rebuild exact cached evidence before the caller performs all ordinary checks. */
66
- export function restoreProjectionHistory(projection, requested) {
67
- const arrays = new Map(projectionHistoryArrays(projection).map((array) => [array.key, array]));
68
- const available = new Map(requested.map((entry) => [entry.prefix.key, entry]));
69
- for (const prefix of projection.historyPrefixes ?? []) {
70
- const entry = available.get(prefix.key);
71
- if (!entry ||
72
- entry.prefix.count !== prefix.count ||
73
- entry.prefix.digest !== prefix.digest)
74
- return false;
75
- const target = arrays.get(entry.arrayKey);
76
- if (!target || historyDigest(prefix.key, entry.values) !== prefix.digest)
77
- return false;
78
- const suffix = target.values.slice();
79
- target.values.length = 0;
80
- for (const value of structuredClone(entry.values))
81
- target.values.push(value);
82
- for (const value of suffix)
83
- target.values.push(value);
84
- target.restoreOrder?.();
85
- available.delete(prefix.key);
86
- }
87
- delete projection.historyPrefixes;
88
- return true;
89
- }
90
- //# sourceMappingURL=projectionHistory.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"projectionHistory.js","sourceRoot":"","sources":["projectionHistory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AACnC,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAEL,uBAAuB,GACxB,MAAM,0BAA0B,CAAC;AASlC,SAAS,aAAa,CAAC,GAAW,EAAE,MAA0B;IAC5D,MAAM,IAAI,GAAG,uBAAuB,EAAE,CAAC;IACvC,IAAI,CAAC,MAAM,CACT,IAAI,WAAW,EAAE,CAAC,MAAM,CACtB,IAAI,CAAC,SAAS,CAAC,CAAC,8BAA8B,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC,CAC9D,CACF,CAAC;IACF,OAAO,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;AACnC,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,wBAAwB,CACtC,UAA6B;IAE7B,OAAO,uBAAuB,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAC3D,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;QAC7B,IAAI,KAAK,CA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AClC,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { ProjectionHistoryPrefix } from \"@tearleads/validators/util\";\nimport { bytesToHex } from \"./hex\";\nimport { createIncrementalSha256 } from \"./incrementalSha256\";\nimport {\n type HistoryProjection,\n projectionHistoryArrays,\n} from \"./projectionHistorySlots\";\n\nexport type { HistoryProjection } from \"./projectionHistorySlots\";\nexport interface RetainedProjectionHistory {\n readonly prefix: ProjectionHistoryPrefix;\n readonly arrayKey: string;\n readonly values: readonly unknown[];\n}\n\nfunction historyDigest(key: string, values: readonly unknown[]): string {\n const hash = createIncrementalSha256();\n hash.update(\n new TextEncoder().encode(\n JSON.stringify([\"tearleads.projection-history\", key, values]),\n ),\n );\n return bytesToHex(hash.digest());\n}\n\n/** Byte commitments describe evidence, not an authorization or verification result. */\nexport function captureProjectionHistory(\n projection: HistoryProjection,\n): RetainedProjectionHistory[] {\n return projectionHistoryArrays(projection).flatMap((array) =>\n array.chains.flatMap((chain) => {\n if (chain.values.length === 0) return [];\n const values = structuredClone(chain.values);\n return [\n {\n arrayKey: array.key,\n values,\n prefix: {\n key: chain.key,\n count: values.length,\n digest: historyDigest(chain.key, values),\n },\n },\n ];\n }),\n );\n}\n\n/** Call only after normal server authorization and stored-evidence verification. */\nexport function omitProjectionHistory<T extends HistoryProjection>(\n projection: T,\n hints: readonly ProjectionHistoryPrefix[],\n): T {\n if (hints.length === 0) return projection;\n // Server loaders may share arrays and objects between paths. JSON wire\n // locations are independent: trimming one must not change another slot.\n const result: T = JSON.parse(JSON.stringify(projection));\n const requested = new Map(hints.map((hint) => [hint.key, hint]));\n const omitted: ProjectionHistoryPrefix[] = [];\n for (const array of projectionHistoryArrays(result)) {\n const removed = new Map<unknown, number>();\n for (const chain of array.chains) {\n const hint = requested.get(chain.key);\n if (!hint || hint.count > chain.values.length) continue;\n const prefix = chain.values.slice(0, hint.count);\n if (historyDigest(chain.key, prefix) !== hint.digest) continue;\n for (const item of prefix)\n removed.set(item, (removed.get(item) ?? 0) + 1);\n omitted.push(hint);\n }\n const retained = array.values.filter((value) => {\n const remaining = removed.get(value) ?? 0;\n if (remaining === 0) return true;\n removed.set(value, remaining - 1);\n return false;\n });\n array.values.length = 0;\n for (const value of retained) array.values.push(value);\n }\n if (omitted.length) result.historyPrefixes = omitted;\n return result;\n}\n\n/** Rebuild exact cached evidence before the caller performs all ordinary checks. */\nexport function restoreProjectionHistory(\n projection: HistoryProjection,\n requested: readonly RetainedProjectionHistory[],\n): boolean {\n const arrays = new Map(\n projectionHistoryArrays(projection).map((array) => [array.key, array]),\n );\n const available = new Map(\n requested.map((entry) => [entry.prefix.key, entry]),\n );\n for (const prefix of projection.historyPrefixes ?? []) {\n const entry = available.get(prefix.key);\n if (\n !entry ||\n entry.prefix.count !== prefix.count ||\n entry.prefix.digest !== prefix.digest\n )\n return false;\n const target = arrays.get(entry.arrayKey);\n if (!target || historyDigest(prefix.key, entry.values) !== prefix.digest)\n return false;\n const suffix = target.values.slice();\n target.values.length = 0;\n for (const value of structuredClone(entry.values))\n target.values.push(value);\n for (const value of suffix) target.values.push(value);\n target.restoreOrder?.();\n available.delete(prefix.key);\n }\n delete projection.historyPrefixes;\n return true;\n}\n"]}
@@ -1,13 +0,0 @@
1
- import type { ContainerWriterProjectionResponse, DocumentWriterProjectionResponse } from "../validators/response/index.js";
2
- export type HistoryProjection = ContainerWriterProjectionResponse | DocumentWriterProjectionResponse;
3
- export interface ProjectionHistoryArray {
4
- readonly key: string;
5
- readonly values: unknown[];
6
- readonly restoreOrder?: (() => void) | undefined;
7
- readonly chains: readonly {
8
- readonly key: string;
9
- readonly values: unknown[];
10
- }[];
11
- }
12
- /** Only these evidence arrays can be omitted. Current heads and keys always travel. */
13
- export declare function projectionHistoryArrays(projection: HistoryProjection): ProjectionHistoryArray[];
@@ -1,81 +0,0 @@
1
- import { compareCanonicalStrings } from "./canonicalOrdering.js";
2
- function manifestEpoch(bundle) {
3
- const epoch = Reflect.get(bundle.manifest, "epoch");
4
- return typeof epoch === "number" && Number.isFinite(epoch) ? epoch : 0;
5
- }
6
- function isDocumentProjection(projection) {
7
- return "documentId" in projection && "documentManifest" in projection;
8
- }
9
- function unambiguousArrays(arrays) {
10
- const occurrences = new Map();
11
- for (const array of arrays)
12
- occurrences.set(array.key, (occurrences.get(array.key) ?? 0) + 1);
13
- // Ambiguous locations cannot safely negotiate an omission. Deliver them full.
14
- return arrays.filter((array) => occurrences.get(array.key) === 1);
15
- }
16
- function manifestHistoryArray(key, values, newestFirst) {
17
- const groups = new Map();
18
- for (const value of values) {
19
- const chain = JSON.stringify([
20
- key,
21
- Reflect.get(value.manifest, "organizationId"),
22
- Reflect.get(value.manifest, "objectKind"),
23
- Reflect.get(value.manifest, "objectId"),
24
- ]);
25
- const entries = groups.get(chain) ?? [];
26
- entries.push(value);
27
- groups.set(chain, entries);
28
- }
29
- return {
30
- key,
31
- values,
32
- restoreOrder: newestFirst
33
- ? () => {
34
- values.sort((a, b) => manifestEpoch(b) - manifestEpoch(a));
35
- }
36
- : undefined,
37
- chains: [...groups].map(([chain, entries]) => ({
38
- key: chain,
39
- values: entries.sort((a, b) => manifestEpoch(a) - manifestEpoch(b) ||
40
- compareCanonicalStrings(a.manifestHash, b.manifestHash)),
41
- })),
42
- };
43
- }
44
- /** Only these evidence arrays can be omitted. Current heads and keys always travel. */
45
- export function projectionHistoryArrays(projection) {
46
- const arrays = [];
47
- const identity = isDocumentProjection(projection)
48
- ? [
49
- "document",
50
- Reflect.get(projection.documentManifest.manifest, "organizationId"),
51
- projection.documentId,
52
- ]
53
- : ["container", projection.organizationId, projection.containerId];
54
- const add = (name, values) => {
55
- const key = JSON.stringify([...identity, name]);
56
- arrays.push({ key, values, chains: [{ key, values }] });
57
- };
58
- const manifests = (name, values, newestFirst = false) => {
59
- const key = JSON.stringify([...identity, name]);
60
- arrays.push(manifestHistoryArray(key, values, newestFirst));
61
- };
62
- const path = (name, value) => {
63
- for (const [index, kek] of value.containerKeks.entries())
64
- manifests(`${name}:kek:${index}:${kek.containerId}`, kek.containerManifestHistory);
65
- };
66
- const evidence = projection.policyEvidence;
67
- add("organizationPayloads", evidence.organizationPayloads);
68
- if (!isDocumentProjection(projection))
69
- path("container", projection);
70
- else {
71
- for (const [index, value] of projection.authorizingContainerPaths.entries())
72
- path(`path:${index}:${value.containerId}`, value);
73
- // A dependency path is ordered root-to-leaf, not an unordered history.
74
- for (const [index, values,] of projection.documentManifestContainerPaths.entries())
75
- add(`documentManifestContainerPaths:${index}`, values);
76
- manifests("documentContainerManifestHistory", projection.documentContainerManifestHistory);
77
- manifests("documentManifestHistory", projection.documentManifestHistory, true);
78
- }
79
- return unambiguousArrays(arrays);
80
- }
81
- //# sourceMappingURL=projectionHistorySlots.js.map