@tearleads/client-sdk 0.1.82 → 0.1.84

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 (157) hide show
  1. package/data/documents/documentSync.js.map +1 -1
  2. package/data/documents/shared/crypto.js.map +1 -1
  3. package/data/documents/shared/types.d.ts +1 -1
  4. package/data/documents/shared/types.js.map +1 -1
  5. package/data/persistence/container-contents/containerContentsPersistence.js +2 -2
  6. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  7. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +1 -1
  8. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  9. package/data/persistence/container-contents/containerDeletionPersistence.js +1 -1
  10. package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
  11. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +3 -3
  12. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  13. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +1 -1
  14. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js.map +1 -1
  15. package/data/persistence/container-contents/containerMetadataRows.js +1 -1
  16. package/data/persistence/container-contents/containerMetadataRows.js.map +1 -1
  17. package/data/persistence/container-contents/containerPendingUpdatePersistence.js +2 -2
  18. package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
  19. package/data/persistence/container-contents/containerReconcilePersistence.js +1 -1
  20. package/data/persistence/container-contents/containerReconcilePersistence.js.map +1 -1
  21. package/data/persistence/container-contents/containerRemovalWork.js +1 -1
  22. package/data/persistence/container-contents/containerRemovalWork.js.map +1 -1
  23. package/data/persistence/documents/documentDiscoveryReset.d.ts +6 -0
  24. package/data/persistence/documents/documentsPersistence.js +2 -2
  25. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  26. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +1 -1
  27. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  28. package/data/persistence/documents/internal/discardDocument.js +2 -2
  29. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  30. package/data/persistence/documents/internal/documentDeletionPersistence.js +2 -2
  31. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  32. package/data/persistence/documents/internal/documentMutationPersistence.js +3 -3
  33. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  34. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
  35. package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
  36. package/data/persistence/documents/internal/documentRecordIdentity.js.map +1 -1
  37. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  38. package/data/persistence/documents/internal/ensureDocumentsSchema.js +1 -1
  39. package/data/persistence/documents/internal/ensureDocumentsSchema.js.map +1 -1
  40. package/data/persistence/documents/internal/orphanSideRows.js +1 -1
  41. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  42. package/data/persistence/documents/internal/rowQueryPersistence.js +1 -1
  43. package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
  44. package/data/persistence/documents/internal/syncQueuePersistence.js +2 -2
  45. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  46. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentHistoryPersistence.d.ts +1 -1
  47. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentHistoryPersistence.js +5 -5
  48. package/data/persistence/documents/records/documentHistoryPersistence.js.map +1 -0
  49. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentPendingUpdatePersistence.d.ts +2 -2
  50. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentPendingUpdatePersistence.js +2 -2
  51. package/data/persistence/documents/records/documentPendingUpdatePersistence.js.map +1 -0
  52. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentPersistenceTypes.d.ts +2 -2
  53. package/data/persistence/documents/records/documentPersistenceTypes.js.map +1 -0
  54. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentRecordPersistence.d.ts +1 -1
  55. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentRecordPersistence.js +4 -4
  56. package/data/persistence/documents/records/documentRecordPersistence.js.map +1 -0
  57. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentSyncFailurePersistence.d.ts +2 -2
  58. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentSyncFailurePersistence.js +3 -3
  59. package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -0
  60. package/data/{sqlite/documentPersistence → persistence/documents/records}/index.d.ts +2 -2
  61. package/data/{sqlite/documentPersistence → persistence/documents/records}/index.js +4 -4
  62. package/data/persistence/documents/records/index.js.map +1 -0
  63. package/data/persistence/documents/types.d.ts +2 -2
  64. package/data/persistence/documents/types.js.map +1 -1
  65. package/{workflows/sync/remoteResetPrincipalScope.d.ts → data/persistence/principalPolicy/principalPolicyRemoteReset.d.ts} +1 -1
  66. package/{workflows/sync/remoteResetPrincipalScope.js → data/persistence/principalPolicy/principalPolicyRemoteReset.js} +7 -7
  67. package/data/persistence/principalPolicy/principalPolicyRemoteReset.js.map +1 -0
  68. package/data/persistence/verifiedManifestBundlePersistence.d.ts +2 -0
  69. package/data/persistence/verifiedManifestBundlePersistence.js +7 -0
  70. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  71. package/data/sqlite/{documentPersistence/documentOrphanBlobReclaims.js → schema/documentOrphanBlobReclaimSchema.js} +1 -1
  72. package/data/sqlite/schema/documentOrphanBlobReclaimSchema.js.map +1 -0
  73. package/data/sqlite/schema/index.js +1 -1
  74. package/data/sqlite/schema/index.js.map +1 -1
  75. package/data/sqlite/sqliteBindBudget.js +12 -0
  76. package/data/sqlite/sqliteBindBudget.js.map +1 -1
  77. package/package.json +1 -1
  78. package/workflows/container-contents/container-state/create/createIntentSeed.js.map +1 -1
  79. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
  80. package/workflows/container-contents/container-state/types.js.map +1 -1
  81. package/workflows/container-contents/metadata/index.js.map +1 -1
  82. package/workflows/container-contents/metadata/metadataEvents.d.ts +1 -1
  83. package/workflows/container-contents/metadata/metadataEvents.js.map +1 -1
  84. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +1 -1
  85. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  86. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +1 -1
  87. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  88. package/workflows/container-contents/pendingWrites/index.js +1 -1
  89. package/workflows/container-contents/pendingWrites/index.js.map +1 -1
  90. package/workflows/container-contents/recovery/accessRestoration.js +1 -1
  91. package/workflows/container-contents/recovery/accessRestoration.js.map +1 -1
  92. package/workflows/container-contents/remoteReset/containerRemoteReset.d.ts +185 -0
  93. package/workflows/container-contents/remoteReset/containerRemoteReset.js +174 -0
  94. package/workflows/container-contents/remoteReset/containerRemoteReset.js.map +1 -0
  95. package/workflows/container-contents/remoteReset/remoteResetCursorScope.d.ts +14 -0
  96. package/workflows/{sync → container-contents/remoteReset}/remoteResetCursorScope.js +2 -2
  97. package/workflows/container-contents/remoteReset/remoteResetCursorScope.js.map +1 -0
  98. package/workflows/documents/create/documentCreationPersistence.js.map +1 -1
  99. package/workflows/documents/create/index.d.ts +1 -1
  100. package/workflows/documents/create/index.js.map +1 -1
  101. package/workflows/documents/documentMutationCommit.d.ts +1 -1
  102. package/workflows/documents/documentMutationCommit.js.map +1 -1
  103. package/workflows/documents/index.d.ts +2 -2
  104. package/workflows/documents/index.js +2 -2
  105. package/workflows/documents/index.js.map +1 -1
  106. package/workflows/documents/remoteReset/documentRemoteReset.d.ts +56 -0
  107. package/workflows/documents/remoteReset/documentRemoteReset.js +135 -0
  108. package/workflows/documents/remoteReset/documentRemoteReset.js.map +1 -0
  109. package/workflows/{sync → documents/remoteReset}/remoteResetAttachments.js +3 -3
  110. package/workflows/documents/remoteReset/remoteResetAttachments.js.map +1 -0
  111. package/workflows/{sync → documents/remoteReset}/remoteResetPlans.d.ts +1 -1
  112. package/workflows/{sync → documents/remoteReset}/remoteResetPlans.js +7 -7
  113. package/workflows/documents/remoteReset/remoteResetPlans.js.map +1 -0
  114. package/workflows/documents/sync/index.js.map +1 -1
  115. package/workflows/documents/sync/initialSync.d.ts +1 -1
  116. package/workflows/documents/sync/initialSync.js.map +1 -1
  117. package/workflows/documents/sync/readOnlySync.d.ts +1 -1
  118. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  119. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  120. package/workflows/documents/sync/syncAttemptState.d.ts +1 -1
  121. package/workflows/documents/sync/syncAttemptState.js.map +1 -1
  122. package/workflows/documents/sync/syncResponseResult.js.map +1 -1
  123. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
  124. package/workflows/documents/syncFailures/index.js.map +1 -1
  125. package/workflows/documents/syncPlan/syncContentKeys.d.ts +1 -1
  126. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
  127. package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -1
  128. package/workflows/documents/syncPlan/syncPlanRequestBounds.js.map +1 -1
  129. package/workflows/documents/syncRekeys/syncContainerRekeys.js.map +1 -1
  130. package/workflows/documents/syncRekeys/syncRecoveryRekey.d.ts +1 -1
  131. package/workflows/documents/syncRekeys/syncRecoveryRekey.js +1 -1
  132. package/workflows/documents/syncRekeys/syncRecoveryRekey.js.map +1 -1
  133. package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
  134. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
  135. package/workflows/organizations/readModel/organizationRemoteReset.js +25 -0
  136. package/workflows/organizations/readModel/organizationRemoteReset.js.map +1 -0
  137. package/workflows/registration/persistRegistrationBootstrap.d.ts +1 -1
  138. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  139. package/workflows/sync/remoteReset.js +60 -229
  140. package/workflows/sync/remoteReset.js.map +1 -1
  141. package/workflows/sync/remoteResetScope.d.ts +7 -10
  142. package/workflows/sync/remoteResetScope.js +26 -108
  143. package/workflows/sync/remoteResetScope.js.map +1 -1
  144. package/data/sqlite/documentPersistence/documentHistoryPersistence.js.map +0 -1
  145. package/data/sqlite/documentPersistence/documentOrphanBlobReclaims.js.map +0 -1
  146. package/data/sqlite/documentPersistence/documentPendingUpdatePersistence.js.map +0 -1
  147. package/data/sqlite/documentPersistence/documentPersistenceTypes.js.map +0 -1
  148. package/data/sqlite/documentPersistence/documentRecordPersistence.js.map +0 -1
  149. package/data/sqlite/documentPersistence/documentSyncFailurePersistence.js.map +0 -1
  150. package/data/sqlite/documentPersistence/index.js.map +0 -1
  151. package/workflows/sync/remoteResetAttachments.js.map +0 -1
  152. package/workflows/sync/remoteResetBatches.js +0 -13
  153. package/workflows/sync/remoteResetBatches.js.map +0 -1
  154. package/workflows/sync/remoteResetCursorScope.js.map +0 -1
  155. package/workflows/sync/remoteResetPlans.js.map +0 -1
  156. package/workflows/sync/remoteResetPrincipalScope.js.map +0 -1
  157. /package/data/{sqlite/documentPersistence → persistence/documents/records}/documentPersistenceTypes.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,8BAA8B,GAC/B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,wCAAwC,EAAE,MAAM,uCAAuC,CAAC;AACjG,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAC7G,OAAO,EAGL,kCAAkC,EAClC,iCAAiC,GAClC,MAAM,8DAA8D,CAAC;AACtE,OAAO,EAEL,kCAAkC,EAClC,oBAAoB,GACrB,MAAM,iDAAiD,CAAC;AAOzD,OAAO,EACL,wBAAwB,EACxB,sCAAsC,EACtC,yBAAyB,GAC1B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,qCAAqC,EACrC,oCAAoC,GACrC,MAAM,kEAAkE,CAA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EAEL,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,mCAAmC,EACnC,iCAAiC,GAElC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uCAAuC,EAAE,MAAM,qCAAqC,CAAC;AAC9F,OAAO,EAAE,kCAAkC,EAAE,MAAM,4BAA4B,CAAC;AAEhF,OAAO,EAAE,qCAAqC,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export {\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n} from \"../../data/documents/shared/projection\";\nexport { persistedDocumentCreateStateFromResponse } from \"../../data/documents/shared/responses\";\nexport { selectDocumentSyncOutgoingBatch } from \"../../data/documents/shared/sync/documentSyncOutgoingBatch\";\nexport {\n type DocumentSyncUpdateIsolationError,\n type IncomingDocumentSyncUpdateValidator,\n isDocumentSyncUpdateIsolationError,\n validateDocumentSyncUpdateImports,\n} from \"../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nexport {\n type DocumentSyncPullContinuation,\n documentSyncPullContinuationsEqual,\n readPullContinuation,\n} from \"../../data/documents/shared/sync/syncPagination\";\nexport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationFailure,\n RelinkRemoteDocumentResult,\n} from \"../../data/documents/shared/types\";\nexport {\n clearDocumentSyncFailure,\n invalidateDocumentSyncPullContinuation,\n recordDocumentSyncFailure,\n} from \"../../data/sqlite/documentPersistence\";\nexport {\n DOCUMENT_HISTORY_COMPACTION_MAX_BYTES,\n DOCUMENT_HISTORY_COMPACTION_MAX_ROWS,\n} from \"../../data/sqlite/documentPersistence/documentHistoryPersistence\";\nexport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nexport { settleOutgoingPassAndDecideReArm } from \"../../data/sync/outgoingUpdateSettlement\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n deleteLocalDocumentAttachment,\n deletePendingDocumentAttachment,\n markLocalDocumentAttachmentDetached,\n saveLocalDocumentAttachments,\n savePendingDocumentAttachment,\n} from \"./attachments/attachmentPersistence\";\nexport { runSerializedDocumentBlobMutation } from \"./attachments/blobMutationLock\";\nexport { reclaimDocumentOrphanBlobs } from \"./attachments/orphanBlobReclaims\";\nexport { resolveDocumentCreateAuthor } from \"./author\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createRemoteDocument,\n documentWriterProjectionFromCreateResponse,\n} from \"./create\";\nexport {\n importDocumentHistoryTailUpdates,\n loadPersistedDocumentContent,\n mergePersistedDocumentHistory,\n} from \"./historyContent\";\nexport { buildMaterializedDocumentLinkSetMutationPlan } from \"./linkSet\";\nexport { relinkRemoteDocument } from \"./linkSet/linkSetRemote\";\nexport {\n enqueuePendingDocumentUpdate,\n listPendingDocumentUpdates,\n} from \"./pendingUpdatePersistence\";\nexport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n type LocalAttachmentRecord,\n loadPersistedDocumentStoreState,\n type PendingAttachmentRecord,\n type PendingAttachmentUploadIdentity,\n type PendingUpdateInsert,\n type PendingUpdateRecord,\n persistDocumentState,\n type RelinkPersistedDocumentInput,\n runSerializedSqlMutation,\n} from \"./persistence\";\nexport {\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionKeyRuntime,\n type DocumentProjectionUserKeyResolver,\n didDocumentProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport {\n buildDocumentPurgeRequest,\n purgeRemoteDocument,\n} from \"./purge\";\nexport {\n type DiscardedDocumentShellResult,\n deletePersistedDocument,\n discardPersistedDocumentToShell,\n} from \"./purge/persistedDocumentRemoval\";\nexport {\n createDocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntimeGroups,\n type DocumentsWorkflowRuntimeInfra,\n type DocumentsWorkflowRuntimeInput,\n type DocumentsWorkflowRuntimeInputGroups,\n} from \"./runtime\";\nexport {\n hasDocumentUpdateEvent,\n syncRemoteDocument,\n} from \"./sync\";\nexport { documentCreateSeedCandidate } from \"./sync/initialSync\";\nexport type { SyncRemoteDocumentInput } from \"./sync/readOnlySync\";\nexport type { DocumentSyncContainerRekeyBuilder } from \"./sync/syncAttemptState\";\nexport {\n type DocumentSyncLane,\n registerDocumentSyncLane,\n requestDocumentSyncLaneAndWait,\n} from \"./sync/syncLane\";\nexport {\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n} from \"./sync/syncTrace\";\nexport {\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type TerminalSubmitFailureHandler,\n} from \"./syncFailures/syncFailureClassification\";\nexport { shouldClearDocumentSyncFailureAfterPass } from \"./syncFailures/syncFailureClearance\";\nexport { DocumentRawHistoryUnavailableError } from \"./syncPlan/syncContentKeys\";\nexport type { RekeyPendingUpdate } from \"./syncRekeys/syncRecoveryRekey\";\nexport { createDocumentWriterPublicKeyResolver } from \"./writerKeys\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,8BAA8B,GAC/B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,wCAAwC,EAAE,MAAM,uCAAuC,CAAC;AACjG,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAC7G,OAAO,EAGL,kCAAkC,EAClC,iCAAiC,GAClC,MAAM,8DAA8D,CAAC;AACtE,OAAO,EAEL,kCAAkC,EAClC,oBAAoB,GACrB,MAAM,iDAAiD,CAAC;AAOzD,OAAO,EACL,wBAAwB,EACxB,sCAAsC,EACtC,yBAAyB,GAC1B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,qCAAqC,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AAE,MAAM,oBAAoB,CAAC;AAGjE,OAAO,EAEL,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,mCAAmC,EACnC,iCAAiC,GAElC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uCAAuC,EAAE,MAAM,qCAAqC,CAAC;AAC9F,OAAO,EAAE,kCAAkC,EAAE,MAAM,4BAA4B,CAAC;AAEhF,OAAO,EAAE,qCAAqC,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export {\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n} from \"../../data/documents/shared/projection\";\nexport { persistedDocumentCreateStateFromResponse } from \"../../data/documents/shared/responses\";\nexport { selectDocumentSyncOutgoingBatch } from \"../../data/documents/shared/sync/documentSyncOutgoingBatch\";\nexport {\n type DocumentSyncUpdateIsolationError,\n type IncomingDocumentSyncUpdateValidator,\n isDocumentSyncUpdateIsolationError,\n validateDocumentSyncUpdateImports,\n} from \"../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nexport {\n type DocumentSyncPullContinuation,\n documentSyncPullContinuationsEqual,\n readPullContinuation,\n} from \"../../data/documents/shared/sync/syncPagination\";\nexport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationFailure,\n RelinkRemoteDocumentResult,\n} from \"../../data/documents/shared/types\";\nexport {\n clearDocumentSyncFailure,\n invalidateDocumentSyncPullContinuation,\n recordDocumentSyncFailure,\n} from \"../../data/persistence/documents/records\";\nexport {\n DOCUMENT_HISTORY_COMPACTION_MAX_BYTES,\n DOCUMENT_HISTORY_COMPACTION_MAX_ROWS,\n} from \"../../data/persistence/documents/records/documentHistoryPersistence\";\nexport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nexport { settleOutgoingPassAndDecideReArm } from \"../../data/sync/outgoingUpdateSettlement\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n deleteLocalDocumentAttachment,\n deletePendingDocumentAttachment,\n markLocalDocumentAttachmentDetached,\n saveLocalDocumentAttachments,\n savePendingDocumentAttachment,\n} from \"./attachments/attachmentPersistence\";\nexport { runSerializedDocumentBlobMutation } from \"./attachments/blobMutationLock\";\nexport { reclaimDocumentOrphanBlobs } from \"./attachments/orphanBlobReclaims\";\nexport { resolveDocumentCreateAuthor } from \"./author\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createRemoteDocument,\n documentWriterProjectionFromCreateResponse,\n} from \"./create\";\nexport {\n importDocumentHistoryTailUpdates,\n loadPersistedDocumentContent,\n mergePersistedDocumentHistory,\n} from \"./historyContent\";\nexport { buildMaterializedDocumentLinkSetMutationPlan } from \"./linkSet\";\nexport { relinkRemoteDocument } from \"./linkSet/linkSetRemote\";\nexport {\n enqueuePendingDocumentUpdate,\n listPendingDocumentUpdates,\n} from \"./pendingUpdatePersistence\";\nexport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n type LocalAttachmentRecord,\n loadPersistedDocumentStoreState,\n type PendingAttachmentRecord,\n type PendingAttachmentUploadIdentity,\n type PendingUpdateInsert,\n type PendingUpdateRecord,\n persistDocumentState,\n type RelinkPersistedDocumentInput,\n runSerializedSqlMutation,\n} from \"./persistence\";\nexport {\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionKeyRuntime,\n type DocumentProjectionUserKeyResolver,\n didDocumentProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport {\n buildDocumentPurgeRequest,\n purgeRemoteDocument,\n} from \"./purge\";\nexport {\n type DiscardedDocumentShellResult,\n deletePersistedDocument,\n discardPersistedDocumentToShell,\n} from \"./purge/persistedDocumentRemoval\";\nexport {\n createDocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntimeGroups,\n type DocumentsWorkflowRuntimeInfra,\n type DocumentsWorkflowRuntimeInput,\n type DocumentsWorkflowRuntimeInputGroups,\n} from \"./runtime\";\nexport {\n hasDocumentUpdateEvent,\n syncRemoteDocument,\n} from \"./sync\";\nexport { documentCreateSeedCandidate } from \"./sync/initialSync\";\nexport type { SyncRemoteDocumentInput } from \"./sync/readOnlySync\";\nexport type { DocumentSyncContainerRekeyBuilder } from \"./sync/syncAttemptState\";\nexport {\n type DocumentSyncLane,\n registerDocumentSyncLane,\n requestDocumentSyncLaneAndWait,\n} from \"./sync/syncLane\";\nexport {\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n} from \"./sync/syncTrace\";\nexport {\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type TerminalSubmitFailureHandler,\n} from \"./syncFailures/syncFailureClassification\";\nexport { shouldClearDocumentSyncFailureAfterPass } from \"./syncFailures/syncFailureClearance\";\nexport { DocumentRawHistoryUnavailableError } from \"./syncPlan/syncContentKeys\";\nexport type { RekeyPendingUpdate } from \"./syncRekeys/syncRecoveryRekey\";\nexport { createDocumentWriterPublicKeyResolver } from \"./writerKeys\";\n"]}
@@ -0,0 +1,56 @@
1
+ import type { ClientSQLiteTransactionScope } from "../../../data/sqlite/sqlitePersistenceRuntime.js";
2
+ import type { ResetAttachmentUpload, ResetDocumentScope, ResetDocumentUpdate } from "./remoteResetPlans.js";
3
+ export { clearDocumentDiscoveryEvidenceOnRemoteReset } from "../../../data/persistence/documents/documentDiscoveryReset.js";
4
+ export { buildResetPlans, type ResetAttachmentUpload, type ResetDocumentUpdate, } from "./remoteResetPlans.js";
5
+ export interface ResetDocumentRow extends ResetDocumentScope {
6
+ readonly documentId: string | null;
7
+ readonly recoveryDocumentId: string | null;
8
+ }
9
+ interface DocumentPlacementRow {
10
+ readonly containerId: string;
11
+ readonly documentId: string;
12
+ }
13
+ /**
14
+ * The documents a reset covers: metadata documents of its folders, documents
15
+ * projected into the organization or its folders, and documents placed in them.
16
+ */
17
+ export declare function loadDocumentResetScope(input: {
18
+ containerIds: readonly string[];
19
+ organizationId: string;
20
+ placementRows: readonly DocumentPlacementRow[];
21
+ tx: ClientSQLiteTransactionScope;
22
+ }): Promise<{
23
+ documentLocalIds: string[];
24
+ documentRows: ResetDocumentRow[];
25
+ oldDocumentIds: string[];
26
+ }>;
27
+ /** Clears pending attachments (keeping re-queued bytes) and queued updates. */
28
+ export declare function clearDocumentRowsForRemoteReset(input: {
29
+ attachmentUploads: readonly ResetAttachmentUpload[];
30
+ documentLocalIds: readonly string[];
31
+ documentRows: readonly ResetDocumentRow[];
32
+ tx: ClientSQLiteTransactionScope;
33
+ }): Promise<void>;
34
+ /**
35
+ * Drops each document's server id, keys, manifest, and sync position, keeping
36
+ * the old id for recovery, and moves its projection to `organizationId`.
37
+ */
38
+ export declare function resetDocumentServerIdentity(input: {
39
+ documentLocalIds: readonly string[];
40
+ documentRows: readonly ResetDocumentRow[];
41
+ now: string;
42
+ organizationId: string;
43
+ tx: ClientSQLiteTransactionScope;
44
+ }): Promise<void>;
45
+ /** Queues each document's rebuilt local history as one outbox update. */
46
+ export declare function queueDocumentRepublishForRemoteReset(input: {
47
+ documentUpdates: readonly ResetDocumentUpdate[];
48
+ now: string;
49
+ tx: ClientSQLiteTransactionScope;
50
+ }): Promise<void>;
51
+ /** Queues the attachments the documents still advertise for upload. */
52
+ export declare function queueAttachmentReuploadsForRemoteReset(input: {
53
+ attachmentUploads: readonly ResetAttachmentUpload[];
54
+ now: string;
55
+ tx: ClientSQLiteTransactionScope;
56
+ }): Promise<void>;
@@ -0,0 +1,135 @@
1
+ import { and, eq, inArray, or } from "drizzle-orm";
2
+ import { queuedUpdateRow, unqueueDocumentScopesInTransaction, } from "../../../data/persistence/documents/records/documentPendingUpdatePersistence.js";
3
+ import { CLEARED_DOCUMENT_SYNC_FAILURE } from "../../../data/persistence/documents/records/documentSyncFailurePersistence.js";
4
+ import { documentAttachmentBlobProjection, documentHistoryUpdates, documentPendingAttachments, documentProjection, documents, } from "../../../data/sqlite/schema/index.js";
5
+ import { remoteResetBatches } from "../../../data/sqlite/sqliteBindBudget.js";
6
+ import { clearResetPendingAttachments } from "./remoteResetAttachments.js";
7
+ // Document Store's part of a remote reset. The sync remote reset calls these in
8
+ // one transaction: it forgets what the server held for the organization's
9
+ // documents, strips their server identity, and queues their local history and
10
+ // attachments to be published again.
11
+ export { clearDocumentDiscoveryEvidenceOnRemoteReset } from "../../../data/persistence/documents/documentDiscoveryReset.js";
12
+ export { buildResetPlans, } from "./remoteResetPlans.js";
13
+ /**
14
+ * The documents a reset covers: metadata documents of its folders, documents
15
+ * projected into the organization or its folders, and documents placed in them.
16
+ */
17
+ export async function loadDocumentResetScope(input) {
18
+ const { organizationId, tx } = input;
19
+ const containerIdSet = new Set(input.containerIds);
20
+ const [allDocuments, projectionRows] = await Promise.all([
21
+ tx
22
+ .select({
23
+ appKind: documents.appKind,
24
+ documentId: documents.documentId,
25
+ localId: documents.localId,
26
+ recoveryDocumentId: documents.recoveryDocumentId,
27
+ })
28
+ .from(documents),
29
+ tx.select().from(documentProjection),
30
+ ]);
31
+ const linkedDocumentIds = new Set(input.placementRows
32
+ .filter((row) => containerIdSet.has(row.containerId))
33
+ .map((row) => row.documentId));
34
+ const projectedLocalIds = new Set(projectionRows
35
+ .filter((row) => (row.containerId !== null && containerIdSet.has(row.containerId)) ||
36
+ row.organizationId === organizationId ||
37
+ (row.documentId !== null && linkedDocumentIds.has(row.documentId)))
38
+ .flatMap((row) => (row.localId ? [row.localId] : [])));
39
+ const documentRows = allDocuments.filter((row) => (row.appKind === "container-metadata" &&
40
+ containerIdSet.has(row.localId)) ||
41
+ (row.appKind === "documents" && projectedLocalIds.has(row.localId)) ||
42
+ (row.documentId !== null && linkedDocumentIds.has(row.documentId)));
43
+ return {
44
+ documentLocalIds: [
45
+ ...new Set(documentRows
46
+ .filter((row) => row.appKind === "documents")
47
+ .map((row) => row.localId)),
48
+ ],
49
+ documentRows,
50
+ oldDocumentIds: [
51
+ ...new Set(documentRows.flatMap((row) => (row.documentId ? [row.documentId] : []))),
52
+ ],
53
+ };
54
+ }
55
+ /** Clears pending attachments (keeping re-queued bytes) and queued updates. */
56
+ export async function clearDocumentRowsForRemoteReset(input) {
57
+ const { tx } = input;
58
+ await clearResetPendingAttachments({
59
+ attachmentUploads: input.attachmentUploads,
60
+ documentLocalIds: input.documentLocalIds,
61
+ tx,
62
+ });
63
+ // Sync failures clear with the document columns in resetDocumentServerIdentity.
64
+ for (const documentBatch of remoteResetBatches(input.documentRows)) {
65
+ await unqueueDocumentScopesInTransaction(tx, documentBatch);
66
+ }
67
+ }
68
+ /**
69
+ * Drops each document's server id, keys, manifest, and sync position, keeping
70
+ * the old id for recovery, and moves its projection to `organizationId`.
71
+ */
72
+ export async function resetDocumentServerIdentity(input) {
73
+ const { now, tx } = input;
74
+ for (const row of input.documentRows) {
75
+ await tx
76
+ .update(documents)
77
+ .set({
78
+ accessEpoch: 1,
79
+ accessStateHash: null,
80
+ contentKeyBundle: null,
81
+ documentId: null,
82
+ documentKekTargets: null,
83
+ documentManifestBundle: null,
84
+ lastCommitLsn: null,
85
+ pullContinuation: null,
86
+ recoveryDocumentId: row.documentId ?? row.recoveryDocumentId,
87
+ ...CLEARED_DOCUMENT_SYNC_FAILURE,
88
+ updatedAt: now,
89
+ })
90
+ .where(and(eq(documents.appKind, row.appKind), eq(documents.localId, row.localId)))
91
+ .run();
92
+ }
93
+ for (const localIdBatch of remoteResetBatches(input.documentLocalIds)) {
94
+ await tx
95
+ .update(documentProjection)
96
+ .set({
97
+ documentId: null,
98
+ organizationId: input.organizationId,
99
+ })
100
+ .where(inArray(documentProjection.localId, localIdBatch))
101
+ .run();
102
+ }
103
+ }
104
+ /** Queues each document's rebuilt local history as one outbox update. */
105
+ export async function queueDocumentRepublishForRemoteReset(input) {
106
+ for (const updateBatch of remoteResetBatches(input.documentUpdates)) {
107
+ await input.tx
108
+ .insert(documentHistoryUpdates)
109
+ .values(updateBatch.map((update) => queuedUpdateRow({
110
+ createdAt: input.now,
111
+ origin: "outbox",
112
+ pendingUpdate: update,
113
+ scope: update,
114
+ updateId: crypto.randomUUID(),
115
+ })))
116
+ .run();
117
+ }
118
+ }
119
+ /** Queues the attachments the documents still advertise for upload. */
120
+ export async function queueAttachmentReuploadsForRemoteReset(input) {
121
+ for (const attachmentBatch of remoteResetBatches(input.attachmentUploads)) {
122
+ await input.tx
123
+ .insert(documentPendingAttachments)
124
+ .values(attachmentBatch.map((attachment) => ({
125
+ ...attachment,
126
+ createdAt: input.now,
127
+ })))
128
+ .run();
129
+ await input.tx
130
+ .delete(documentAttachmentBlobProjection)
131
+ .where(or(...attachmentBatch.map((attachment) => and(eq(documentAttachmentBlobProjection.localId, attachment.localId), eq(documentAttachmentBlobProjection.slotId, attachment.slotId)))))
132
+ .run();
133
+ }
134
+ }
135
+ //# sourceMappingURL=documentRemoteReset.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"documentRemoteReset.js","sourceRoot":"","sources":["documentRemoteReset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EACL,eAAe,EACf,kCAAkC,GACnC,MAAM,8EAA8E,CAAC;AACtF,OAAO,EAAE,6BAA6B,EAAE,MAAM,4EAA4E,CAAC;AAC3H,OAAO,EACL,gCAAgC,EAChC,sBAAsB,EACtB,0BAA0B,EAC1B,kBAAkB,EAClB,SAAS,GACV,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAE3E,OAAO,EAAE,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAOxE,gFAAgF;AAChF,0EAA0E;AAC1E,8EAA8E;AAC9E,qCAAqC;AACrC,OAAO,EAAE,2CAA2C,EAAE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,OAAO,CAAC,EAChE,EAAE,CAAC,gCAAgC,CAAC,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC,CAC/D,CACF,CACF,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC;AACH,CAAC","sourcesContent":["import { and, eq, inArray, or } from \"drizzle-orm\";\nimport {\n queuedUpdateRow,\n unqueueDocumentScopesInTransaction,\n} from \"../../../data/persistence/documents/records/documentPendingUpdatePersistence\";\nimport { CLEARED_DOCUMENT_SYNC_FAILURE } from \"../../../data/persistence/documents/records/documentSyncFailurePersistence\";\nimport {\n documentAttachmentBlobProjection,\n documentHistoryUpdates,\n documentPendingAttachments,\n documentProjection,\n documents,\n} from \"../../../data/sqlite/schema\";\nimport { remoteResetBatches } from \"../../../data/sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport { clearResetPendingAttachments } from \"./remoteResetAttachments\";\nimport type {\n ResetAttachmentUpload,\n ResetDocumentScope,\n ResetDocumentUpdate,\n} from \"./remoteResetPlans\";\n\n// Document Store's part of a remote reset. The sync remote reset calls these in\n// one transaction: it forgets what the server held for the organization's\n// documents, strips their server identity, and queues their local history and\n// attachments to be published again.\nexport { clearDocumentDiscoveryEvidenceOnRemoteReset } from \"../../../data/persistence/documents/documentDiscoveryReset\";\nexport {\n buildResetPlans,\n type ResetAttachmentUpload,\n type ResetDocumentUpdate,\n} from \"./remoteResetPlans\";\n\nexport interface ResetDocumentRow extends ResetDocumentScope {\n readonly documentId: string | null;\n readonly recoveryDocumentId: string | null;\n}\n\ninterface DocumentPlacementRow {\n readonly containerId: string;\n readonly documentId: string;\n}\n\n/**\n * The documents a reset covers: metadata documents of its folders, documents\n * projected into the organization or its folders, and documents placed in them.\n */\nexport async function loadDocumentResetScope(input: {\n containerIds: readonly string[];\n organizationId: string;\n placementRows: readonly DocumentPlacementRow[];\n tx: ClientSQLiteTransactionScope;\n}): Promise<{\n documentLocalIds: string[];\n documentRows: ResetDocumentRow[];\n oldDocumentIds: string[];\n}> {\n const { organizationId, tx } = input;\n const containerIdSet = new Set(input.containerIds);\n const [allDocuments, projectionRows] = await Promise.all([\n tx\n .select({\n appKind: documents.appKind,\n documentId: documents.documentId,\n localId: documents.localId,\n recoveryDocumentId: documents.recoveryDocumentId,\n })\n .from(documents),\n tx.select().from(documentProjection),\n ]);\n const linkedDocumentIds = new Set(\n input.placementRows\n .filter((row) => containerIdSet.has(row.containerId))\n .map((row) => row.documentId),\n );\n const projectedLocalIds = new Set(\n projectionRows\n .filter(\n (row) =>\n (row.containerId !== null && containerIdSet.has(row.containerId)) ||\n row.organizationId === organizationId ||\n (row.documentId !== null && linkedDocumentIds.has(row.documentId)),\n )\n .flatMap((row) => (row.localId ? [row.localId] : [])),\n );\n const documentRows = allDocuments.filter(\n (row) =>\n (row.appKind === \"container-metadata\" &&\n containerIdSet.has(row.localId)) ||\n (row.appKind === \"documents\" && projectedLocalIds.has(row.localId)) ||\n (row.documentId !== null && linkedDocumentIds.has(row.documentId)),\n );\n return {\n documentLocalIds: [\n ...new Set(\n documentRows\n .filter((row) => row.appKind === \"documents\")\n .map((row) => row.localId),\n ),\n ],\n documentRows,\n oldDocumentIds: [\n ...new Set(\n documentRows.flatMap((row) => (row.documentId ? [row.documentId] : [])),\n ),\n ],\n };\n}\n\n/** Clears pending attachments (keeping re-queued bytes) and queued updates. */\nexport async function clearDocumentRowsForRemoteReset(input: {\n attachmentUploads: readonly ResetAttachmentUpload[];\n documentLocalIds: readonly string[];\n documentRows: readonly ResetDocumentRow[];\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { tx } = input;\n await clearResetPendingAttachments({\n attachmentUploads: input.attachmentUploads,\n documentLocalIds: input.documentLocalIds,\n tx,\n });\n // Sync failures clear with the document columns in resetDocumentServerIdentity.\n for (const documentBatch of remoteResetBatches(input.documentRows)) {\n await unqueueDocumentScopesInTransaction(tx, documentBatch);\n }\n}\n\n/**\n * Drops each document's server id, keys, manifest, and sync position, keeping\n * the old id for recovery, and moves its projection to `organizationId`.\n */\nexport async function resetDocumentServerIdentity(input: {\n documentLocalIds: readonly string[];\n documentRows: readonly ResetDocumentRow[];\n now: string;\n organizationId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { now, tx } = input;\n for (const row of input.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 ...CLEARED_DOCUMENT_SYNC_FAILURE,\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(input.documentLocalIds)) {\n await tx\n .update(documentProjection)\n .set({\n documentId: null,\n organizationId: input.organizationId,\n })\n .where(inArray(documentProjection.localId, localIdBatch))\n .run();\n }\n}\n\n/** Queues each document's rebuilt local history as one outbox update. */\nexport async function queueDocumentRepublishForRemoteReset(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\n/** Queues the attachments the documents still advertise for upload. */\nexport async function queueAttachmentReuploadsForRemoteReset(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"]}
@@ -1,7 +1,7 @@
1
1
  import { inArray } from "drizzle-orm";
2
- import { queueDocumentAttachmentStorageKeys } from "../../data/persistence/documents/internal/orphanSideRows.js";
3
- import { documentPendingAttachments } from "../../data/sqlite/schema/index.js";
4
- import { remoteResetBatches } from "./remoteResetBatches.js";
2
+ import { queueDocumentAttachmentStorageKeys } from "../../../data/persistence/documents/internal/orphanSideRows.js";
3
+ import { documentPendingAttachments } from "../../../data/sqlite/schema/index.js";
4
+ import { remoteResetBatches } from "../../../data/sqlite/sqliteBindBudget.js";
5
5
  /** Delete reset-scoped pending rows without abandoning dropped local bytes. */
6
6
  export async function clearResetPendingAttachments(input) {
7
7
  const requeuedKeys = new Set(input.attachmentUploads.map((attachment) => `${attachment.localId}\0${attachment.slotId}`));
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remoteResetAttachments.js","sourceRoot":"","sources":["remoteResetAttachments.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,kCAAkC,EAAE,MAAM,6DAA6D,CAAC;AACjH,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAI3E,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAAC,KAIlD;IACC,MAAM,YAAY,GAAG,IAAI,GAAG,CAC1B,KAAK,CAAC,iBAAiB,CAAC,GAAG,CACzB,CAAC,UAAU,EAAE,EAAE,CAAC,GAAG,UAAU,CAAC,OAAO,KAAK,UAAU,CAAC,MAAM,EAAE,CAC9D,CACF,CAAC;IACF,KAAK,MAAM,YAAY,IAAI,kBAAkB,CAAC,KAAK,CAAC,gBAAgB,CAAC,EAAE,CAAC;QACtE,MAAM,IAAI,GAAG,MAAM,KAAK,CAAC,EAAE;aACxB,MAAM,CAAC;YACN,OAAO,EAAE,0BAA0B,CAAC,OAAO;YAC3C,MAAM,EAAE,0BAA0B,CAAC,MAAM;YACzC,UAAU,EAAE,0BAA0B,CAAC,UAAU;SAClD,CAAC;aACD,IAAI,CAAC,0BAA0B,CAAC;aAChC,KAAK,CAAC,OAAO,CAAC,0BAA0B,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC;QACpE,MAAM,kCAAkC,CACtC,KAAK,CAAC,EAAE,EACR,IAAI;aACD,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,OAAO,KAAK,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;aACnE,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,CAChC,CAAC;QACF,MAAM,KAAK,CAAC,EAAE;aACX,MAAM,CAAC,0BAA0B,CAAC;aAClC,KAAK,CAAC,OAAO,CAAC,0BAA0B,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;aAChE,GAAG,EAAE,CAAC;IACX,CAAC;AACH,CAAC","sourcesContent":["import { inArray } from \"drizzle-orm\";\nimport { queueDocumentAttachmentStorageKeys } from \"../../../data/persistence/documents/internal/orphanSideRows\";\nimport { documentPendingAttachments } from \"../../../data/sqlite/schema\";\nimport { remoteResetBatches } from \"../../../data/sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ResetAttachmentUpload } from \"./remoteResetPlans\";\n\n/** Delete reset-scoped pending rows without abandoning dropped local bytes. */\nexport async function clearResetPendingAttachments(input: {\n readonly attachmentUploads: readonly ResetAttachmentUpload[];\n readonly documentLocalIds: readonly string[];\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const requeuedKeys = new Set(\n input.attachmentUploads.map(\n (attachment) => `${attachment.localId}\\0${attachment.slotId}`,\n ),\n );\n for (const localIdBatch of remoteResetBatches(input.documentLocalIds)) {\n const rows = await input.tx\n .select({\n localId: documentPendingAttachments.localId,\n slotId: documentPendingAttachments.slotId,\n storageKey: documentPendingAttachments.storageKey,\n })\n .from(documentPendingAttachments)\n .where(inArray(documentPendingAttachments.localId, localIdBatch));\n await queueDocumentAttachmentStorageKeys(\n input.tx,\n rows\n .filter((row) => !requeuedKeys.has(`${row.localId}\\0${row.slotId}`))\n .map((row) => row.storageKey),\n );\n await input.tx\n .delete(documentPendingAttachments)\n .where(inArray(documentPendingAttachments.localId, localIdBatch))\n .run();\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { ClientSQLiteTransactionScope } from "../../data/sqlite/sqlitePersistenceRuntime.js";
1
+ import type { ClientSQLiteTransactionScope } from "../../../data/sqlite/sqlitePersistenceRuntime.js";
2
2
  export interface ResetDocumentUpdate {
3
3
  readonly appKind: string;
4
4
  readonly localId: string;
@@ -1,11 +1,11 @@
1
- import { createDocument, exportAllUpdates } from "../../internal/loro/index.js";
1
+ import { createDocument, exportAllUpdates } from "../../../internal/loro/index.js";
2
2
  import { and, eq, ne, or, sql } from "drizzle-orm";
3
- import { getDocumentAttachments, } from "../../data/documents/index.js";
4
- import { createPendingUpdateFields } from "../../data/documents/documentSync.js";
5
- import { DOCUMENTS_APP_KIND } from "../../data/persistence/documents/documentsPersistence.js";
6
- import { documentAttachmentBlobProjection, documentHistoryCheckpoints, documentHistoryUpdates, documentPendingAttachments, documents, } from "../../data/sqlite/schema/index.js";
7
- import { importDocumentHistoryTailUpdates } from "../documents/index.js";
8
- import { remoteResetBatches } from "./remoteResetBatches.js";
3
+ import { getDocumentAttachments, } from "../../../data/documents/index.js";
4
+ import { createPendingUpdateFields } from "../../../data/documents/documentSync.js";
5
+ import { DOCUMENTS_APP_KIND } from "../../../data/persistence/documents/documentsPersistence.js";
6
+ import { documentAttachmentBlobProjection, documentHistoryCheckpoints, documentHistoryUpdates, documentPendingAttachments, documents, } from "../../../data/sqlite/schema/index.js";
7
+ import { remoteResetBatches } from "../../../data/sqlite/sqliteBindBudget.js";
8
+ import { importDocumentHistoryTailUpdates } from "../historyContent.js";
9
9
  function historyScopeKey(appKind, localId) {
10
10
  return `${appKind} ${localId}`;
11
11
  }
@@ -0,0 +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,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAEL,sBAAsB,GACvB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EAAE,kBAAkB,EAAE,MAAM,0DAA0D,CAAC;AAC9F,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,sBAAsB,EACtB,0BAA0B,EAC1B,SAAS,GACV,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAE3E,OAAO,EAAE,gCAAgC,EAAE,MAAM,mBAAmB,CAAC;AAuBrE,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,GAA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BACjC,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\";\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 { remoteResetBatches } from \"../../../data/sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport { importDocumentHistoryTailUpdates } from \"../historyContent\";\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 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AACpF,OAAO,EAAE,kCAAkC,EAAE,MAAM,iEAAiE,CAAC;AACrH,OAAO,EAEL,wCAAwC,GACzC,MAAM,oDAAoD,CAAC;AAK5D,OAAO,EACL,sCAAsC,EAEtC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,2CAA2C,EAAE,MAAM,UAAU,CAAC;AACvE,OAAO,EACL,6BAA6B,EAC7B,kCAAkC,EAClC,kCAAkC,GACnC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,8BAA8B,EAC9B,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAAE,gCAAgC,EAAE,MAAM,6CAA6C,CAAC;AAC/F,OAAO,EAEL,gCAAgC,GACjC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,uBAAuB,EACvB,wBAAwB,GACzB,MAAM,uBAAuB,CAAC;AAK/B,OAAO,EAAE,kCAAkC,EAAE,MAAM,uBAAuB,CAAC;AAE3E,MAAM,UAAU,sBAAsB,CACpC,MAA8B,EAC9B,UAAqC;IAErC,IAAI,CAAC,UAAU;QAAE,OAAO,KAAK,CAAC;IAC9B,OAAO,MAAM,CAAC,IAAI,CAChB,CAAC,KAAK,EAAE,EAAE,CACR,4BAA4B,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,UAAU,K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AI,sCAAsC,CAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAC/D,IACE,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;YAChC,kCAAkC,CAAC,KAAK,CAAC,EACzC,CAAC;YACD,MAAM,KAAK,CAAC,gCAAgC,EAAE,CAAC,KAAK,CAAC,CAAC;QACxD,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { isDocumentUpdateCreatedEvent } from \"../../../data/documents/documentSync\";\nimport { isDocumentSyncUpdateIsolationError } from \"../../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nimport {\n type DocumentSyncPullContinuation,\n InvalidDocumentSyncPullContinuationError,\n} from \"../../../data/documents/shared/sync/syncPagination\";\nimport type {\n MaterializedDocumentSyncPlan,\n SyncRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport {\n isProjectionVerificationCancelledError,\n type ProjectionUserKeyResolver,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../../data/sqlite/documentPersistence\";\nimport { createVerifiedRemoteDocumentDeletionHandler } from \"../purge\";\nimport {\n assertRawContinuationCanRetry,\n resolveSyncAttemptWriterProjection,\n submitDocumentSyncAttemptIfAllowed,\n} from \"../syncFailures\";\nimport {\n abandonAfterRetryableConflicts,\n abandonBlockedSync,\n} from \"../syncFailures/syncAbandon\";\nimport { recoverablePendingUpdates } from \"../syncPlan/syncPlanRequestBounds\";\nimport { requireStandaloneAncestorRepairs } from \"../syncRekeys/syncContainerRekeyPreparation\";\nimport {\n type SyncRemoteDocumentInput,\n tryPersistedReadOnlyDocumentSync,\n} from \"./readOnlySync\";\nimport {\n planDocumentSyncAttempt,\n projectionFailureHandler,\n} from \"./syncAttemptPlanning\";\nimport type {\n RemoteDocumentSyncAttemptOutcome,\n RemoteDocumentSyncAttemptState,\n} from \"./syncAttemptState\";\nimport { resolveSubmittedDocumentSyncResult } from \"./syncSubmittedResult\";\n\nexport function hasDocumentUpdateEvent(\n events: ReadonlyArray<unknown>,\n documentId: string | null | undefined,\n): boolean {\n if (!documentId) return false;\n return events.some(\n (event) =>\n isDocumentUpdateCreatedEvent(event) && event.documentId === documentId,\n );\n}\n/**\n * A retryable stale-projection conflict means this writer projection is behind\n * the server. Evict only this document so the next attempt re-derives targets.\n */\nfunction evictStaleProjectionForRetry(input: SyncRemoteDocumentInput): void {\n input.apiClient.evictDocumentWriterProjection?.(input.documentId);\n}\n\n/**\n * A pass may repair a covering-baseline rejection by regenerating queued\n * rotation checkpoints — but only when there is something to regenerate FROM\n * (a snapshot provider and queued checkpoint rows), the failed pass was not\n * already a heal or a regeneration (whose fresh baseline proves this device\n * is simply behind), and an attempt remains.\n */\nfunction canRegenerateQueuedCheckpoints(input: {\n materializedPlan: MaterializedDocumentSyncPlan;\n pendingUpdates: readonly PendingUpdateRecord[];\n regenerateQueuedCheckpoints: boolean;\n sync: SyncRemoteDocumentInput;\n}): boolean {\n return (\n !input.regenerateQueuedCheckpoints &&\n !input.materializedPlan.healedStaleContentKeyBundle &&\n input.sync.buildRotationSnapshot !== undefined &&\n input.pendingUpdates.some((update) => update.sourceVersionVector != null)\n );\n}\n\nasync function submitPlannedSyncAttempt(args: {\n attempt: number;\n materializedPlan: MaterializedDocumentSyncPlan;\n maxAttempts: number;\n pendingUpdates: readonly PendingUpdateRecord[];\n pullContinuation?: DocumentSyncPullContinuation | undefined;\n regenerateQueuedCheckpoints: boolean;\n sync: SyncRemoteDocumentInput;\n failureBlocksQueuedWrites: boolean;\n}) {\n try {\n return await submitDocumentSyncAttemptIfAllowed({\n apiClient: args.sync.apiClient,\n attempt: args.attempt,\n canRegenerateQueuedCheckpoints: canRegenerateQueuedCheckpoints({\n materializedPlan: args.materializedPlan,\n pendingUpdates: args.pendingUpdates,\n regenerateQueuedCheckpoints: args.regenerateQueuedCheckpoints,\n sync: args.sync,\n }),\n documentId: args.sync.documentId,\n expectedCommitLsnMode: args.pullContinuation?.commitLsnMode,\n isRemoteSyncBlocked: args.sync.isRemoteSyncBlocked,\n maxAttempts: args.maxAttempts,\n onInlineRepairRefused: () => requireStandaloneAncestorRepairs(args.sync),\n onRemoteDocumentDeleted: args.sync.onRemoteDocumentDeleted,\n onOutgoingUpdatesMaterialized: args.sync.onOutgoingUpdatesMaterialized,\n onSyncTrace: args.sync.onSyncTrace,\n onTerminalSubmitFailure: args.sync.onTerminalSubmitFailure,\n pendingUpdates: args.pendingUpdates,\n plan: args.materializedPlan.plan,\n failureBlocksQueuedWrites: args.failureBlocksQueuedWrites,\n stillCurrent: args.sync.stillCurrent,\n warmReferencedPrincipalPolicies:\n args.sync.warmReferencedPrincipalPolicies,\n });\n } catch (error) {\n if (\n error instanceof InvalidDocumentSyncPullContinuationError &&\n args.pullContinuation !== undefined &&\n args.sync.historyMode !== \"raw\"\n ) {\n return \"retry\" as const;\n }\n throw error;\n }\n}\n\nfunction resolveAttemptProjection(\n input: SyncRemoteDocumentInput,\n failureBlocksQueuedWrites: boolean,\n reusableWriterProjection: DocumentWriterProjectionResponse | null,\n) {\n return resolveSyncAttemptWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n onRemoteDocumentDeleted: input.onRemoteDocumentDeleted,\n onSyncAbandoned: input.onSyncAbandoned,\n onSyncTrace: input.onSyncTrace,\n onTerminalFailure: projectionFailureHandler(\n input,\n failureBlocksQueuedWrites,\n ),\n reusableWriterProjection,\n stillCurrent: input.stillCurrent,\n });\n}\nfunction resolveRemoteSyncProjectionUserKey(input: SyncRemoteDocumentInput) {\n return requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document sync\",\n );\n}\n\nasync function invalidatePullCursor(\n input: SyncRemoteDocumentInput,\n pullContinuation: DocumentSyncPullContinuation | undefined,\n): Promise<undefined> {\n if (pullContinuation !== undefined) {\n await input.onPullContinuationInvalidated?.(pullContinuation);\n }\n return undefined;\n}\n\nasync function preparePersistedDocumentSync(\n input: SyncRemoteDocumentInput,\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n): Promise<\n | { readonly kind: \"completed\"; result: SyncRemoteDocumentResult | null }\n | {\n readonly kind: \"continue\";\n pullContinuation: DocumentSyncPullContinuation | undefined;\n }\n> {\n let pullContinuation = input.pullContinuation;\n try {\n const persisted = await tryPersistedReadOnlyDocumentSync(\n input,\n resolveProjectionUserKey,\n );\n if (persisted?.kind === \"completed\") return persisted;\n if (persisted?.kind === \"not_completed\" && input.historyMode !== \"raw\") {\n pullContinuation = await invalidatePullCursor(input, pullContinuation);\n }\n } catch (error) {\n if (\n !(error instanceof InvalidDocumentSyncPullContinuationError) ||\n pullContinuation === undefined ||\n input.historyMode === \"raw\"\n ) {\n throw error;\n }\n pullContinuation = await invalidatePullCursor(input, pullContinuation);\n }\n return { kind: \"continue\", pullContinuation };\n}\n\nfunction failureBlocksQueuedWrites(input: {\n readonly pendingUpdates: readonly PendingUpdateRecord[];\n readonly recoveryPendingUpdateCount: number;\n}): boolean {\n return (\n input.pendingUpdates.length > 0 || input.recoveryPendingUpdateCount > 0\n );\n}\n\nasync function retryRemoteSyncAttempt(\n sync: SyncRemoteDocumentInput,\n continuation: DocumentSyncPullContinuation | undefined,\n): Promise<RemoteDocumentSyncAttemptOutcome> {\n evictStaleProjectionForRetry(sync);\n return {\n kind: \"retry\",\n pullContinuation: await invalidatePullCursor(sync, continuation),\n };\n}\n\nasync function runRemoteDocumentSyncAttempt(input: {\n attempt: number;\n maxAttempts: number;\n pendingUpdateIds: readonly string[];\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n state: RemoteDocumentSyncAttemptState;\n sync: SyncRemoteDocumentInput;\n}): Promise<RemoteDocumentSyncAttemptOutcome> {\n if (input.sync.stillCurrent?.() === false) {\n return { kind: \"complete\", result: null };\n }\n const blocksQueuedWrites = failureBlocksQueuedWrites({\n pendingUpdates: input.state.pendingUpdates,\n recoveryPendingUpdateCount: input.state.recoveryPendingUpdatesById.size,\n });\n const writerProjection = await resolveAttemptProjection(\n input.sync,\n blocksQueuedWrites,\n input.state.reusableWriterProjection,\n );\n if (input.sync.stillCurrent?.() === false || !writerProjection) {\n return { kind: \"complete\", result: null };\n }\n const planned = await planDocumentSyncAttempt({\n pendingUpdates: input.state.pendingUpdates,\n pullContinuation: input.state.pullContinuation,\n regenerateQueuedCheckpoints: input.state.regenerateQueuedCheckpoints,\n sync: input.sync,\n failureBlocksQueuedWrites: blocksQueuedWrites,\n writerProjection,\n });\n if (planned === \"retry\") {\n return retryRemoteSyncAttempt(input.sync, input.state.pullContinuation);\n }\n if (!planned || input.sync.stillCurrent?.() === false) {\n return { kind: \"complete\", result: null };\n }\n const [materializedPlan] = planned;\n const submitted = await submitPlannedSyncAttempt({\n attempt: input.attempt,\n materializedPlan,\n maxAttempts: input.maxAttempts,\n pendingUpdates: recoverablePendingUpdates(\n input.state.pendingUpdates,\n materializedPlan,\n ),\n pullContinuation: input.state.pullContinuation,\n regenerateQueuedCheckpoints: input.state.regenerateQueuedCheckpoints,\n sync: input.sync,\n failureBlocksQueuedWrites: blocksQueuedWrites,\n });\n if (input.sync.stillCurrent?.() === false || submitted === \"cancelled\") {\n return { kind: \"complete\", result: null };\n }\n if (submitted === \"retry\") {\n assertRawContinuationCanRetry(\n input.sync.historyMode,\n input.state.pullContinuation,\n );\n return retryRemoteSyncAttempt(input.sync, input.state.pullContinuation);\n }\n if (submitted === \"blocked\") {\n abandonBlockedSync(input.sync);\n return { kind: \"complete\", result: null };\n }\n if (submitted === \"stop\") {\n input.sync.onSyncAbandoned?.(\"the sync submit failed terminally\");\n return { kind: \"complete\", result: null };\n }\n if (submitted.kind === \"regenerate_queued_checkpoints\") {\n return { kind: \"regenerate\" };\n }\n if (submitted.kind === \"recover_update_id_conflict\") {\n // A lost response may mean the server committed both this update id and an\n // inline container rekey. Force the read-only recovery pass to observe that\n // committed successor projection instead of reusing a cached predecessor.\n evictStaleProjectionForRetry(input.sync);\n return { kind: \"recover\", updates: submitted.recoveryPendingUpdatesById };\n }\n const result = await resolveSubmittedDocumentSyncResult({\n materializedPlan,\n pendingUpdateIds: input.pendingUpdateIds,\n pullComplete: submitted.pullComplete,\n recoveryPendingUpdatesById: input.state.recoveryPendingUpdatesById,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n response: submitted.response,\n sync: input.sync,\n writerProjection: materializedPlan.writerProjection,\n });\n return {\n kind: \"complete\",\n result: input.sync.stillCurrent?.() === false ? null : result,\n };\n}\n\nasync function syncRemoteDocumentInternal(\n input: SyncRemoteDocumentInput,\n): Promise<SyncRemoteDocumentResult | null> {\n if (input.stillCurrent?.() === false) return null;\n const resolveProjectionUserKey = resolveRemoteSyncProjectionUserKey(input);\n const maxAttempts = 3;\n let pendingUpdates = input.pendingUpdates ?? [];\n const pendingUpdateIds = pendingUpdates.map((update) => update.id);\n let recoveryPendingUpdatesById = new Map<string, PendingUpdateRecord>();\n let regenerateQueuedCheckpoints = false;\n let reusableWriterProjection = input.writerProjection ?? null;\n const persistedSync = await preparePersistedDocumentSync(\n input,\n resolveProjectionUserKey,\n );\n if (input.stillCurrent?.() === false) return null;\n if (persistedSync.kind === \"completed\") return persistedSync.result;\n let pullContinuation = persistedSync.pullContinuation;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const outcome = await runRemoteDocumentSyncAttempt({\n attempt,\n maxAttempts,\n pendingUpdateIds,\n resolveProjectionUserKey,\n state: {\n pendingUpdates,\n pullContinuation,\n recoveryPendingUpdatesById,\n regenerateQueuedCheckpoints,\n reusableWriterProjection,\n },\n sync: input,\n });\n reusableWriterProjection = null;\n if (outcome.kind === \"complete\") return outcome.result;\n if (outcome.kind === \"retry\") {\n pullContinuation = outcome.pullContinuation;\n if (input.stillCurrent?.() === false) return null;\n continue;\n }\n if (outcome.kind === \"regenerate\") {\n regenerateQueuedCheckpoints = true;\n continue;\n }\n recoveryPendingUpdatesById = outcome.updates;\n pendingUpdates = [];\n }\n return abandonAfterRetryableConflicts(input);\n}\n\nexport async function syncRemoteDocument(\n input: SyncRemoteDocumentInput,\n): Promise<SyncRemoteDocumentResult | null> {\n try {\n return await syncRemoteDocumentInternal({\n ...input,\n onRemoteDocumentDeleted: createVerifiedRemoteDocumentDeletionHandler({\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedOrganizationId: input.author.organizationId,\n onVerifiedDeletion: ({ commitPurgeProof, documentId }) => {\n if (input.stillCurrent?.() === false) return;\n if (!input.onRemoteDocumentDeleted) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Remote document deletion requires atomic local teardown\",\n );\n }\n return input.onRemoteDocumentDeleted({\n commitPurgeProof,\n documentId,\n });\n },\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }),\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return null;\n if (\n input.stillCurrent?.() !== false &&\n isDocumentSyncUpdateIsolationError(error)\n ) {\n await input.onIncomingUpdateIsolationFailure?.(error);\n }\n throw error;\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AACpF,OAAO,EAAE,kCAAkC,EAAE,MAAM,iEAAiE,CAAC;AACrH,OAAO,EAEL,wCAAwC,GACzC,MAAM,oDAAoD,CAAC;AAK5D,OAAO,EACL,sCAAsC,EAEtC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,2CAA2C,EAAE,MAAM,UAAU,CAAC;AACvE,OAAO,EACL,6BAA6B,EAC7B,kCAAkC,EAClC,kCAAkC,GACnC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,8BAA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AC,EAAE,gBAAgB,EAAE,UAAU,EAAE,EAAE,EAAE;oBACvD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;wBAAE,OAAO;oBAC7C,IAAI,CAAC,KAAK,CAAC,uBAAuB,EAAE,CAAC;wBACnC,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,yDAAyD,CAC1D,CAAC;oBACJ,CAAC;oBACD,OAAO,KAAK,CAAC,uBAAuB,CAAC;wBACnC,gBAAgB;wBAChB,UAAU;qBACX,CAAC,CAAC;gBACL,CAAC;gBACD,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;gBACxD,YAAY,EAAE,KAAK,CAAC,YAAY;gBAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;aACvE,CAAC;SACH,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,sCAAsC,CAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAC/D,IACE,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;YAChC,kCAAkC,CAAC,KAAK,CAAC,EACzC,CAAC;YACD,MAAM,KAAK,CAAC,gCAAgC,EAAE,CAAC,KAAK,CAAC,CAAC;QACxD,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { isDocumentUpdateCreatedEvent } from \"../../../data/documents/documentSync\";\nimport { isDocumentSyncUpdateIsolationError } from \"../../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nimport {\n type DocumentSyncPullContinuation,\n InvalidDocumentSyncPullContinuationError,\n} from \"../../../data/documents/shared/sync/syncPagination\";\nimport type {\n MaterializedDocumentSyncPlan,\n SyncRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport {\n isProjectionVerificationCancelledError,\n type ProjectionUserKeyResolver,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { createVerifiedRemoteDocumentDeletionHandler } from \"../purge\";\nimport {\n assertRawContinuationCanRetry,\n resolveSyncAttemptWriterProjection,\n submitDocumentSyncAttemptIfAllowed,\n} from \"../syncFailures\";\nimport {\n abandonAfterRetryableConflicts,\n abandonBlockedSync,\n} from \"../syncFailures/syncAbandon\";\nimport { recoverablePendingUpdates } from \"../syncPlan/syncPlanRequestBounds\";\nimport { requireStandaloneAncestorRepairs } from \"../syncRekeys/syncContainerRekeyPreparation\";\nimport {\n type SyncRemoteDocumentInput,\n tryPersistedReadOnlyDocumentSync,\n} from \"./readOnlySync\";\nimport {\n planDocumentSyncAttempt,\n projectionFailureHandler,\n} from \"./syncAttemptPlanning\";\nimport type {\n RemoteDocumentSyncAttemptOutcome,\n RemoteDocumentSyncAttemptState,\n} from \"./syncAttemptState\";\nimport { resolveSubmittedDocumentSyncResult } from \"./syncSubmittedResult\";\n\nexport function hasDocumentUpdateEvent(\n events: ReadonlyArray<unknown>,\n documentId: string | null | undefined,\n): boolean {\n if (!documentId) return false;\n return events.some(\n (event) =>\n isDocumentUpdateCreatedEvent(event) && event.documentId === documentId,\n );\n}\n/**\n * A retryable stale-projection conflict means this writer projection is behind\n * the server. Evict only this document so the next attempt re-derives targets.\n */\nfunction evictStaleProjectionForRetry(input: SyncRemoteDocumentInput): void {\n input.apiClient.evictDocumentWriterProjection?.(input.documentId);\n}\n\n/**\n * A pass may repair a covering-baseline rejection by regenerating queued\n * rotation checkpoints — but only when there is something to regenerate FROM\n * (a snapshot provider and queued checkpoint rows), the failed pass was not\n * already a heal or a regeneration (whose fresh baseline proves this device\n * is simply behind), and an attempt remains.\n */\nfunction canRegenerateQueuedCheckpoints(input: {\n materializedPlan: MaterializedDocumentSyncPlan;\n pendingUpdates: readonly PendingUpdateRecord[];\n regenerateQueuedCheckpoints: boolean;\n sync: SyncRemoteDocumentInput;\n}): boolean {\n return (\n !input.regenerateQueuedCheckpoints &&\n !input.materializedPlan.healedStaleContentKeyBundle &&\n input.sync.buildRotationSnapshot !== undefined &&\n input.pendingUpdates.some((update) => update.sourceVersionVector != null)\n );\n}\n\nasync function submitPlannedSyncAttempt(args: {\n attempt: number;\n materializedPlan: MaterializedDocumentSyncPlan;\n maxAttempts: number;\n pendingUpdates: readonly PendingUpdateRecord[];\n pullContinuation?: DocumentSyncPullContinuation | undefined;\n regenerateQueuedCheckpoints: boolean;\n sync: SyncRemoteDocumentInput;\n failureBlocksQueuedWrites: boolean;\n}) {\n try {\n return await submitDocumentSyncAttemptIfAllowed({\n apiClient: args.sync.apiClient,\n attempt: args.attempt,\n canRegenerateQueuedCheckpoints: canRegenerateQueuedCheckpoints({\n materializedPlan: args.materializedPlan,\n pendingUpdates: args.pendingUpdates,\n regenerateQueuedCheckpoints: args.regenerateQueuedCheckpoints,\n sync: args.sync,\n }),\n documentId: args.sync.documentId,\n expectedCommitLsnMode: args.pullContinuation?.commitLsnMode,\n isRemoteSyncBlocked: args.sync.isRemoteSyncBlocked,\n maxAttempts: args.maxAttempts,\n onInlineRepairRefused: () => requireStandaloneAncestorRepairs(args.sync),\n onRemoteDocumentDeleted: args.sync.onRemoteDocumentDeleted,\n onOutgoingUpdatesMaterialized: args.sync.onOutgoingUpdatesMaterialized,\n onSyncTrace: args.sync.onSyncTrace,\n onTerminalSubmitFailure: args.sync.onTerminalSubmitFailure,\n pendingUpdates: args.pendingUpdates,\n plan: args.materializedPlan.plan,\n failureBlocksQueuedWrites: args.failureBlocksQueuedWrites,\n stillCurrent: args.sync.stillCurrent,\n warmReferencedPrincipalPolicies:\n args.sync.warmReferencedPrincipalPolicies,\n });\n } catch (error) {\n if (\n error instanceof InvalidDocumentSyncPullContinuationError &&\n args.pullContinuation !== undefined &&\n args.sync.historyMode !== \"raw\"\n ) {\n return \"retry\" as const;\n }\n throw error;\n }\n}\n\nfunction resolveAttemptProjection(\n input: SyncRemoteDocumentInput,\n failureBlocksQueuedWrites: boolean,\n reusableWriterProjection: DocumentWriterProjectionResponse | null,\n) {\n return resolveSyncAttemptWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n onRemoteDocumentDeleted: input.onRemoteDocumentDeleted,\n onSyncAbandoned: input.onSyncAbandoned,\n onSyncTrace: input.onSyncTrace,\n onTerminalFailure: projectionFailureHandler(\n input,\n failureBlocksQueuedWrites,\n ),\n reusableWriterProjection,\n stillCurrent: input.stillCurrent,\n });\n}\nfunction resolveRemoteSyncProjectionUserKey(input: SyncRemoteDocumentInput) {\n return requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document sync\",\n );\n}\n\nasync function invalidatePullCursor(\n input: SyncRemoteDocumentInput,\n pullContinuation: DocumentSyncPullContinuation | undefined,\n): Promise<undefined> {\n if (pullContinuation !== undefined) {\n await input.onPullContinuationInvalidated?.(pullContinuation);\n }\n return undefined;\n}\n\nasync function preparePersistedDocumentSync(\n input: SyncRemoteDocumentInput,\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n): Promise<\n | { readonly kind: \"completed\"; result: SyncRemoteDocumentResult | null }\n | {\n readonly kind: \"continue\";\n pullContinuation: DocumentSyncPullContinuation | undefined;\n }\n> {\n let pullContinuation = input.pullContinuation;\n try {\n const persisted = await tryPersistedReadOnlyDocumentSync(\n input,\n resolveProjectionUserKey,\n );\n if (persisted?.kind === \"completed\") return persisted;\n if (persisted?.kind === \"not_completed\" && input.historyMode !== \"raw\") {\n pullContinuation = await invalidatePullCursor(input, pullContinuation);\n }\n } catch (error) {\n if (\n !(error instanceof InvalidDocumentSyncPullContinuationError) ||\n pullContinuation === undefined ||\n input.historyMode === \"raw\"\n ) {\n throw error;\n }\n pullContinuation = await invalidatePullCursor(input, pullContinuation);\n }\n return { kind: \"continue\", pullContinuation };\n}\n\nfunction failureBlocksQueuedWrites(input: {\n readonly pendingUpdates: readonly PendingUpdateRecord[];\n readonly recoveryPendingUpdateCount: number;\n}): boolean {\n return (\n input.pendingUpdates.length > 0 || input.recoveryPendingUpdateCount > 0\n );\n}\n\nasync function retryRemoteSyncAttempt(\n sync: SyncRemoteDocumentInput,\n continuation: DocumentSyncPullContinuation | undefined,\n): Promise<RemoteDocumentSyncAttemptOutcome> {\n evictStaleProjectionForRetry(sync);\n return {\n kind: \"retry\",\n pullContinuation: await invalidatePullCursor(sync, continuation),\n };\n}\n\nasync function runRemoteDocumentSyncAttempt(input: {\n attempt: number;\n maxAttempts: number;\n pendingUpdateIds: readonly string[];\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n state: RemoteDocumentSyncAttemptState;\n sync: SyncRemoteDocumentInput;\n}): Promise<RemoteDocumentSyncAttemptOutcome> {\n if (input.sync.stillCurrent?.() === false) {\n return { kind: \"complete\", result: null };\n }\n const blocksQueuedWrites = failureBlocksQueuedWrites({\n pendingUpdates: input.state.pendingUpdates,\n recoveryPendingUpdateCount: input.state.recoveryPendingUpdatesById.size,\n });\n const writerProjection = await resolveAttemptProjection(\n input.sync,\n blocksQueuedWrites,\n input.state.reusableWriterProjection,\n );\n if (input.sync.stillCurrent?.() === false || !writerProjection) {\n return { kind: \"complete\", result: null };\n }\n const planned = await planDocumentSyncAttempt({\n pendingUpdates: input.state.pendingUpdates,\n pullContinuation: input.state.pullContinuation,\n regenerateQueuedCheckpoints: input.state.regenerateQueuedCheckpoints,\n sync: input.sync,\n failureBlocksQueuedWrites: blocksQueuedWrites,\n writerProjection,\n });\n if (planned === \"retry\") {\n return retryRemoteSyncAttempt(input.sync, input.state.pullContinuation);\n }\n if (!planned || input.sync.stillCurrent?.() === false) {\n return { kind: \"complete\", result: null };\n }\n const [materializedPlan] = planned;\n const submitted = await submitPlannedSyncAttempt({\n attempt: input.attempt,\n materializedPlan,\n maxAttempts: input.maxAttempts,\n pendingUpdates: recoverablePendingUpdates(\n input.state.pendingUpdates,\n materializedPlan,\n ),\n pullContinuation: input.state.pullContinuation,\n regenerateQueuedCheckpoints: input.state.regenerateQueuedCheckpoints,\n sync: input.sync,\n failureBlocksQueuedWrites: blocksQueuedWrites,\n });\n if (input.sync.stillCurrent?.() === false || submitted === \"cancelled\") {\n return { kind: \"complete\", result: null };\n }\n if (submitted === \"retry\") {\n assertRawContinuationCanRetry(\n input.sync.historyMode,\n input.state.pullContinuation,\n );\n return retryRemoteSyncAttempt(input.sync, input.state.pullContinuation);\n }\n if (submitted === \"blocked\") {\n abandonBlockedSync(input.sync);\n return { kind: \"complete\", result: null };\n }\n if (submitted === \"stop\") {\n input.sync.onSyncAbandoned?.(\"the sync submit failed terminally\");\n return { kind: \"complete\", result: null };\n }\n if (submitted.kind === \"regenerate_queued_checkpoints\") {\n return { kind: \"regenerate\" };\n }\n if (submitted.kind === \"recover_update_id_conflict\") {\n // A lost response may mean the server committed both this update id and an\n // inline container rekey. Force the read-only recovery pass to observe that\n // committed successor projection instead of reusing a cached predecessor.\n evictStaleProjectionForRetry(input.sync);\n return { kind: \"recover\", updates: submitted.recoveryPendingUpdatesById };\n }\n const result = await resolveSubmittedDocumentSyncResult({\n materializedPlan,\n pendingUpdateIds: input.pendingUpdateIds,\n pullComplete: submitted.pullComplete,\n recoveryPendingUpdatesById: input.state.recoveryPendingUpdatesById,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n response: submitted.response,\n sync: input.sync,\n writerProjection: materializedPlan.writerProjection,\n });\n return {\n kind: \"complete\",\n result: input.sync.stillCurrent?.() === false ? null : result,\n };\n}\n\nasync function syncRemoteDocumentInternal(\n input: SyncRemoteDocumentInput,\n): Promise<SyncRemoteDocumentResult | null> {\n if (input.stillCurrent?.() === false) return null;\n const resolveProjectionUserKey = resolveRemoteSyncProjectionUserKey(input);\n const maxAttempts = 3;\n let pendingUpdates = input.pendingUpdates ?? [];\n const pendingUpdateIds = pendingUpdates.map((update) => update.id);\n let recoveryPendingUpdatesById = new Map<string, PendingUpdateRecord>();\n let regenerateQueuedCheckpoints = false;\n let reusableWriterProjection = input.writerProjection ?? null;\n const persistedSync = await preparePersistedDocumentSync(\n input,\n resolveProjectionUserKey,\n );\n if (input.stillCurrent?.() === false) return null;\n if (persistedSync.kind === \"completed\") return persistedSync.result;\n let pullContinuation = persistedSync.pullContinuation;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const outcome = await runRemoteDocumentSyncAttempt({\n attempt,\n maxAttempts,\n pendingUpdateIds,\n resolveProjectionUserKey,\n state: {\n pendingUpdates,\n pullContinuation,\n recoveryPendingUpdatesById,\n regenerateQueuedCheckpoints,\n reusableWriterProjection,\n },\n sync: input,\n });\n reusableWriterProjection = null;\n if (outcome.kind === \"complete\") return outcome.result;\n if (outcome.kind === \"retry\") {\n pullContinuation = outcome.pullContinuation;\n if (input.stillCurrent?.() === false) return null;\n continue;\n }\n if (outcome.kind === \"regenerate\") {\n regenerateQueuedCheckpoints = true;\n continue;\n }\n recoveryPendingUpdatesById = outcome.updates;\n pendingUpdates = [];\n }\n return abandonAfterRetryableConflicts(input);\n}\n\nexport async function syncRemoteDocument(\n input: SyncRemoteDocumentInput,\n): Promise<SyncRemoteDocumentResult | null> {\n try {\n return await syncRemoteDocumentInternal({\n ...input,\n onRemoteDocumentDeleted: createVerifiedRemoteDocumentDeletionHandler({\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedOrganizationId: input.author.organizationId,\n onVerifiedDeletion: ({ commitPurgeProof, documentId }) => {\n if (input.stillCurrent?.() === false) return;\n if (!input.onRemoteDocumentDeleted) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Remote document deletion requires atomic local teardown\",\n );\n }\n return input.onRemoteDocumentDeleted({\n commitPurgeProof,\n documentId,\n });\n },\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }),\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return null;\n if (\n input.stillCurrent?.() !== false &&\n isDocumentSyncUpdateIsolationError(error)\n ) {\n await input.onIncomingUpdateIsolationFailure?.(error);\n }\n throw error;\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import type { DocumentSyncRequest } from "../../../internal/validators/request/index.js";
2
2
  import type { ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
3
3
  import type { DocumentCreateAuthor, MaterializedDocumentCreatePlan } from "../../../data/documents/shared/types.js";
4
- import type { PendingUpdateRecord } from "../../../data/sqlite/documentPersistence/index.js";
4
+ import type { PendingUpdateRecord } from "../../../data/persistence/documents/records/index.js";
5
5
  /**
6
6
  * Builds the single encrypted initial write for a provisioned document. The
7
7
  * server commits it with the organization and document manifest transaction.
@@ -1 +1 @@
1
- {"version":3,"file":"initialSync.js","sourceRoot":"","sources":["initialSync.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,sBAAsB,EACtB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,+BAA+B,EAAE,MAAM,4BAA4B,CAAC;AAC7E,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAC5F,OAAO,EAAE,4BAA4B,EAAE,MAAM,uCAAuC,CAAC;AACrF,OAAO,EAAE,iBAAiB,EAAE,MAAM,2CAA2C,CAAC;AAM9E,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAE1E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAKrD;IACC,MAAM,aAAa,GAAG,yBAAyB,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IACrE,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IAC3D,CAAC;IACD,OAAO,8BAA8B,CAAC;QACpC,GAAG,KAAK;QACR,aAAa,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,UAAU,EAAE,EAAE,GAAG,aAAa,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n satisfiesVersionVector,\n versionVectorsEqual,\n} from \"@tearleads/loro\";\nimport type { DocumentSyncRequest } from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_DOCUMENT_SYNC_REQUEST_BYTES } from \"@tearleads/validators/util\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport { importContentKeyMaterial } from \"../../../data/documents/shared/contentRecordKeys\";\nimport { encryptDocumentPendingUpdate } from \"../../../data/documents/shared/crypto\";\nimport { containerPathRefs } from \"../../../data/documents/shared/projection\";\nimport type {\n DocumentCreateAuthor,\n MaterializedDocumentCreatePlan,\n} from \"../../../data/documents/shared/types\";\nimport type { PendingUpdateRecord } from \"../../../data/sqlite/documentPersistence\";\nimport { signDocumentOutgoingUpdate } from \"../syncPlan/syncPlanIdentity\";\n\n/**\n * Builds the single encrypted initial write for a provisioned document. The\n * server commits it with the organization and document manifest transaction.\n */\nexport async function buildInitialDocumentSyncRequest(input: {\n readonly author: DocumentCreateAuthor;\n readonly containerProjection: ContainerWriterProjectionResponse;\n readonly initialUpdate: Uint8Array;\n readonly materializedDocument: MaterializedDocumentCreatePlan;\n}): Promise<DocumentSyncRequest> {\n const pendingFields = createPendingUpdateFields(input.initialUpdate);\n if (!pendingFields) {\n throw new Error(\"Initial document sync update is empty\");\n }\n return buildDocumentCreateSeedRequest({\n ...input,\n pendingUpdate: { id: crypto.randomUUID(), ...pendingFields },\n });\n}\n\n/**\n * Builds a create's seed: the one queued update that holds a new document's\n * whole content, signed against the create plan, so the create commits it and\n * no follow-up sync is needed. The update keeps its queue row id.\n */\nexport async function buildDocumentCreateSeedRequest(input: {\n readonly author: DocumentCreateAuthor;\n readonly containerProjection: ContainerWriterProjectionResponse;\n readonly materializedDocument: MaterializedDocumentCreatePlan;\n readonly pendingUpdate: PendingUpdateRecord;\n}): Promise<DocumentSyncRequest> {\n const { pendingUpdate } = input;\n const documentId = input.materializedDocument.plan.documentId;\n const contentKeyBundle =\n input.materializedDocument.plan.request.contentKeyBundle;\n const encrypted = await encryptDocumentPendingUpdate({\n contentKeyMaterial: await importContentKeyMaterial(\n input.materializedDocument.contentKey,\n ),\n contentKeyEpoch: contentKeyBundle.contentKeyEpoch,\n documentId,\n organizationId: input.containerProjection.organizationId,\n update: pendingUpdate,\n });\n const outgoingUpdate = await signDocumentOutgoingUpdate({\n authorizingContainerPathRefs: [\n containerPathRefs(input.containerProjection.path),\n ],\n author: input.author,\n contentKeyEpoch: contentKeyBundle.contentKeyEpoch,\n documentId,\n expectedLinkSetManifestHash: contentKeyBundle.linkSetManifestHash,\n expectedTargetHash: contentKeyBundle.targetHash,\n organizationId: input.containerProjection.organizationId,\n signedAt: new Date().toISOString(),\n update: {\n contentRecordId: encrypted.contentRecordId,\n encryptedData: encrypted.encryptedData,\n id: pendingUpdate.id,\n partialEndVersionVector: pendingUpdate.partialEndVersionVector,\n partialStartVersionVector: pendingUpdate.partialStartVersionVector,\n metadataHash: encrypted.metadataHash,\n ciphertextHash: encrypted.ciphertextHash,\n plaintextHash: encrypted.plaintextHash,\n },\n });\n\n return {\n authorizingContainerPathRefs: [\n containerPathRefs(input.containerProjection.path),\n ],\n contentKeyBundle,\n contentKeyEpoch: contentKeyBundle.contentKeyEpoch,\n expectedLinkSetManifestHash: contentKeyBundle.linkSetManifestHash,\n expectedTargetHash: contentKeyBundle.targetHash,\n // The creating device already holds this exact content, so it does not\n // need the transaction response to echo the update back.\n localVersionVector: pendingUpdate.partialEndVersionVector,\n outgoingUpdates: [outgoingUpdate],\n supportsPullPagination: true,\n };\n}\n\n/**\n * The queued row that may seed a create: the only row, a plain update (not a\n * rotation baseline) that holds the document's whole content. Anything else\n * syncs after the create as before.\n */\nexport function documentCreateSeedCandidate(input: {\n readonly documentVersion: string;\n readonly pendingUpdates: readonly PendingUpdateRecord[];\n}): PendingUpdateRecord | null {\n const [row, ...rest] = input.pendingUpdates;\n if (!row || rest.length > 0 || row.sourceVersionVector != null) return null;\n // The start may name peers at counter zero; the server checks it the same way.\n return satisfiesVersionVector(\n emptyVersionVector(),\n row.partialStartVersionVector,\n ) && versionVectorsEqual(row.partialEndVersionVector, input.documentVersion)\n ? row\n : null;\n}\n\nconst TEXT_ENCODER = new TextEncoder();\n\n/**\n * A seed is held to the sync request limit (the API refuses a larger one), so\n * a seed that does not fit is left out and the row syncs in ordinary batches.\n */\nexport function documentCreateSeedFits(seed: DocumentSyncRequest): boolean {\n return (\n TEXT_ENCODER.encode(JSON.stringify(seed)).byteLength <=\n MAX_DOCUMENT_SYNC_REQUEST_BYTES\n );\n}\n"]}
1
+ {"version":3,"file":"initialSync.js","sourceRoot":"","sources":["initialSync.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,sBAAsB,EACtB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,+BAA+B,EAAE,MAAM,4BAA4B,CAAC;AAC7E,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAC5F,OAAO,EAAE,4BAA4B,EAAE,MAAM,uCAAuC,CAAC;AACrF,OAAO,EAAE,iBAAiB,EAAE,MAAM,2CAA2C,CAAC;AAM9E,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAE1E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAKrD;IACC,MAAM,aAAa,GAAG,yBAAyB,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IACrE,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IAC3D,CAAC;IACD,OAAO,8BAA8B,CAAC;QACpC,GAAG,KAAK;QACR,aAAa,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,UAAU,EAAE,EAAE,GAAG,aAAa,EAAE;KAC7D,CAAC,CAAC;AACL,CAAC;AA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earleads/loro\";\nimport type { DocumentSyncRequest } from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_DOCUMENT_SYNC_REQUEST_BYTES } from \"@tearleads/validators/util\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport { importContentKeyMaterial } from \"../../../data/documents/shared/contentRecordKeys\";\nimport { encryptDocumentPendingUpdate } from \"../../../data/documents/shared/crypto\";\nimport { containerPathRefs } from \"../../../data/documents/shared/projection\";\nimport type {\n DocumentCreateAuthor,\n MaterializedDocumentCreatePlan,\n} from \"../../../data/documents/shared/types\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { signDocumentOutgoingUpdate } from \"../syncPlan/syncPlanIdentity\";\n\n/**\n * Builds the single encrypted initial write for a provisioned document. The\n * server commits it with the organization and document manifest transaction.\n */\nexport async function buildInitialDocumentSyncRequest(input: {\n readonly author: DocumentCreateAuthor;\n readonly containerProjection: ContainerWriterProjectionResponse;\n readonly initialUpdate: Uint8Array;\n readonly materializedDocument: MaterializedDocumentCreatePlan;\n}): Promise<DocumentSyncRequest> {\n const pendingFields = createPendingUpdateFields(input.initialUpdate);\n if (!pendingFields) {\n throw new Error(\"Initial document sync update is empty\");\n }\n return buildDocumentCreateSeedRequest({\n ...input,\n pendingUpdate: { id: crypto.randomUUID(), ...pendingFields },\n });\n}\n\n/**\n * Builds a create's seed: the one queued update that holds a new document's\n * whole content, signed against the create plan, so the create commits it and\n * no follow-up sync is needed. The update keeps its queue row id.\n */\nexport async function buildDocumentCreateSeedRequest(input: {\n readonly author: DocumentCreateAuthor;\n readonly containerProjection: ContainerWriterProjectionResponse;\n readonly materializedDocument: MaterializedDocumentCreatePlan;\n readonly pendingUpdate: PendingUpdateRecord;\n}): Promise<DocumentSyncRequest> {\n const { pendingUpdate } = input;\n const documentId = input.materializedDocument.plan.documentId;\n const contentKeyBundle =\n input.materializedDocument.plan.request.contentKeyBundle;\n const encrypted = await encryptDocumentPendingUpdate({\n contentKeyMaterial: await importContentKeyMaterial(\n input.materializedDocument.contentKey,\n ),\n contentKeyEpoch: contentKeyBundle.contentKeyEpoch,\n documentId,\n organizationId: input.containerProjection.organizationId,\n update: pendingUpdate,\n });\n const outgoingUpdate = await signDocumentOutgoingUpdate({\n authorizingContainerPathRefs: [\n containerPathRefs(input.containerProjection.path),\n ],\n author: input.author,\n contentKeyEpoch: contentKeyBundle.contentKeyEpoch,\n documentId,\n expectedLinkSetManifestHash: contentKeyBundle.linkSetManifestHash,\n expectedTargetHash: contentKeyBundle.targetHash,\n organizationId: input.containerProjection.organizationId,\n signedAt: new Date().toISOString(),\n update: {\n contentRecordId: encrypted.contentRecordId,\n encryptedData: encrypted.encryptedData,\n id: pendingUpdate.id,\n partialEndVersionVector: pendingUpdate.partialEndVersionVector,\n partialStartVersionVector: pendingUpdate.partialStartVersionVector,\n metadataHash: encrypted.metadataHash,\n ciphertextHash: encrypted.ciphertextHash,\n plaintextHash: encrypted.plaintextHash,\n },\n });\n\n return {\n authorizingContainerPathRefs: [\n containerPathRefs(input.containerProjection.path),\n ],\n contentKeyBundle,\n contentKeyEpoch: contentKeyBundle.contentKeyEpoch,\n expectedLinkSetManifestHash: contentKeyBundle.linkSetManifestHash,\n expectedTargetHash: contentKeyBundle.targetHash,\n // The creating device already holds this exact content, so it does not\n // need the transaction response to echo the update back.\n localVersionVector: pendingUpdate.partialEndVersionVector,\n outgoingUpdates: [outgoingUpdate],\n supportsPullPagination: true,\n };\n}\n\n/**\n * The queued row that may seed a create: the only row, a plain update (not a\n * rotation baseline) that holds the document's whole content. Anything else\n * syncs after the create as before.\n */\nexport function documentCreateSeedCandidate(input: {\n readonly documentVersion: string;\n readonly pendingUpdates: readonly PendingUpdateRecord[];\n}): PendingUpdateRecord | null {\n const [row, ...rest] = input.pendingUpdates;\n if (!row || rest.length > 0 || row.sourceVersionVector != null) return null;\n // The start may name peers at counter zero; the server checks it the same way.\n return satisfiesVersionVector(\n emptyVersionVector(),\n row.partialStartVersionVector,\n ) && versionVectorsEqual(row.partialEndVersionVector, input.documentVersion)\n ? row\n : null;\n}\n\nconst TEXT_ENCODER = new TextEncoder();\n\n/**\n * A seed is held to the sync request limit (the API refuses a larger one), so\n * a seed that does not fit is left out and the row syncs in ordinary batches.\n */\nexport function documentCreateSeedFits(seed: DocumentSyncRequest): boolean {\n return (\n TEXT_ENCODER.encode(JSON.stringify(seed)).byteLength <=\n MAX_DOCUMENT_SYNC_REQUEST_BYTES\n );\n}\n"]}
@@ -3,7 +3,7 @@ import type { DocumentSyncUpdateIsolationError, IncomingDocumentSyncUpdateValida
3
3
  import { type DocumentSyncPullContinuation } from "../../../data/documents/shared/sync/syncPagination.js";
4
4
  import type { DocumentCreateAuthor, DocumentSyncApi, DocumentWriterPublicKeyResolver, PersistedDocumentSyncState, SyncRemoteDocumentResult } from "../../../data/documents/shared/types.js";
5
5
  import type { ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../../../data/keyingProjectionVerification/index.js";
6
- import type { PendingUpdateRecord } from "../../../data/sqlite/documentPersistence/index.js";
6
+ import type { PendingUpdateRecord } from "../../../data/persistence/documents/records/index.js";
7
7
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
8
8
  import { type RemoteDocumentDeletionHandler, type TerminalSubmitFailureHandler } from "../syncFailures/syncFailureClassification.js";
9
9
  import type { RekeyPendingUpdate } from "../syncRekeys/syncRecoveryRekey.js";