@tearleads/client-sdk 0.1.244 → 0.1.246

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/data/persistence/container-contents/containerContentsPersistence.js +2 -0
  2. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  3. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -1
  4. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  5. package/data/persistence/container-contents/containerMetadataRevalidations.d.ts +22 -0
  6. package/data/persistence/container-contents/containerMetadataRevalidations.js +52 -0
  7. package/data/persistence/container-contents/containerMetadataRevalidations.js.map +1 -0
  8. package/data/sqlite/schema/containerSchema.d.ts +173 -0
  9. package/data/sqlite/schema/containerSchema.js +18 -0
  10. package/data/sqlite/schema/containerSchema.js.map +1 -1
  11. package/data/sqlite/schema/index.d.ts +84 -1
  12. package/data/sqlite/schema/index.js +1 -1
  13. package/data/sqlite/schema/index.js.map +1 -1
  14. package/internal/api-client/ApiClient.d.ts +1 -8
  15. package/internal/api-client/client/apiClientContext.d.ts +1 -0
  16. package/internal/api-client/client/containerReads.d.ts +1 -0
  17. package/internal/crypto/keying/accessManifestVerificationTypes.d.ts +8 -2
  18. package/internal/crypto/keying/accessManifestVerificationTypes.js.map +1 -1
  19. package/internal/crypto/keying/containerAccess.js +1 -1
  20. package/internal/crypto/keying/containerAccess.js.map +1 -1
  21. package/internal/crypto/keying/documentAccess.js +1 -1
  22. package/internal/crypto/keying/documentAccess.js.map +1 -1
  23. package/internal/crypto/organizationReplacement.js +5 -6
  24. package/internal/crypto/organizationReplacement.js.map +1 -1
  25. package/internal/loro/document.d.ts +5 -0
  26. package/internal/loro/document.js +17 -0
  27. package/internal/loro/document.js.map +1 -1
  28. package/internal/loro/index.d.ts +1 -1
  29. package/internal/loro/index.js +1 -1
  30. package/internal/loro/index.js.map +1 -1
  31. package/internal/validators/operation/attachments.d.ts +0 -12
  32. package/internal/validators/operation/auth.d.ts +0 -76
  33. package/internal/validators/operation/containerMutations.d.ts +1 -49
  34. package/internal/validators/operation/containerMutations.js +1 -1
  35. package/internal/validators/operation/containerMutations.js.map +1 -1
  36. package/internal/validators/operation/containerReads.d.ts +2 -0
  37. package/internal/validators/operation/documentMutations.d.ts +0 -24
  38. package/internal/validators/operation/documentSync.d.ts +0 -4
  39. package/internal/validators/operation/organizations.d.ts +0 -88
  40. package/internal/validators/operation/principals.d.ts +0 -16
  41. package/internal/validators/request/blob.d.ts +0 -12
  42. package/internal/validators/request/container.d.ts +0 -16
  43. package/internal/validators/request/container.js +0 -2
  44. package/internal/validators/request/container.js.map +1 -1
  45. package/internal/validators/request/containerMetadata.d.ts +0 -20
  46. package/internal/validators/request/document.d.ts +0 -22
  47. package/internal/validators/request/document.js +0 -1
  48. package/internal/validators/request/document.js.map +1 -1
  49. package/internal/validators/request/documentSyncSchema.d.ts +0 -4
  50. package/internal/validators/request/documentSyncSchema.js +0 -1
  51. package/internal/validators/request/documentSyncSchema.js.map +1 -1
  52. package/internal/validators/request/organization.d.ts +0 -16
  53. package/internal/validators/request/organizationProvisioning.d.ts +0 -242
  54. package/internal/validators/request/principal.d.ts +0 -20
  55. package/internal/validators/request/registration.d.ts +0 -76
  56. package/internal/validators/response/container.d.ts +8 -0
  57. package/internal/validators/response/container.js +1 -0
  58. package/internal/validators/response/container.js.map +1 -1
  59. package/internal/validators/response/containerParentLanes.d.ts +2 -0
  60. package/package.json +1 -1
  61. package/stores/container-contents/containerContentsStore.js +2 -0
  62. package/stores/container-contents/containerContentsStore.js.map +1 -1
  63. package/stores/container-contents/hydration/startupHydration.js +6 -2
  64. package/stores/container-contents/hydration/startupHydration.js.map +1 -1
  65. package/stores/container-contents/state.js +5 -1
  66. package/stores/container-contents/state.js.map +1 -1
  67. package/stores/container-contents/syncAgent/metadataRevalidation.js +79 -0
  68. package/stores/container-contents/syncAgent/metadataRevalidation.js.map +1 -0
  69. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +6 -0
  70. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  71. package/stores/container-contents/syncAgent/syncLaneIteration.js +110 -23
  72. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  73. package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js +3 -0
  74. package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js.map +1 -1
  75. package/workflows/container-contents/container-state/remote.js +3 -0
  76. package/workflows/container-contents/container-state/remote.js.map +1 -1
  77. package/workflows/container-contents/containerPersistence.d.ts +1 -0
  78. package/workflows/container-contents/containerPersistence.js.map +1 -1
  79. package/workflows/container-contents/metadata/index.js +4 -1
  80. package/workflows/container-contents/metadata/index.js.map +1 -1
  81. package/workflows/container-contents/metadata/metadataSyncFollowup.js +9 -0
  82. package/workflows/container-contents/metadata/metadataSyncFollowup.js.map +1 -1
  83. package/workflows/container-contents/metadata/metadataTypes.d.ts +2 -0
  84. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  85. package/workflows/container-contents/remoteHydration/index.js +9 -0
  86. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  87. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +31 -0
  88. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  89. package/workflows/container-contents/remoteHydration/types.d.ts +9 -1
  90. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  91. package/workflows/containers/child/mutationRequestCore.js +1 -1
  92. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  93. package/workflows/containers/child/recitePlan.js +0 -1
  94. package/workflows/containers/child/recitePlan.js.map +1 -1
  95. package/workflows/containers/root/create.js +0 -1
  96. package/workflows/containers/root/create.js.map +1 -1
  97. package/workflows/documents/linkSet/index.js +0 -1
  98. package/workflows/documents/linkSet/index.js.map +1 -1
  99. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +17 -10
  100. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
  101. package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAI7E,OAAO,EAAE,gCAAgC,EAAE,MAAM,6CAA6C,CAAC;AAC/F,OAAO,EACL,oBAAoB,EACpB,uCAAuC,GACxC,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAC1F,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,EACpC,8BAA8B,EAC9B,wCAAwC,GACzC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAGL,2BAA2B,GAC5B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,oCAAoC,EACpC,qCAAqC,GACtC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,sCAAsC,EAAE,MAAM,wBAAwB,CAAC;AAEhF,OAAO,EACL,uCAAuC,EACvC,sCAAsC,GACvC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,8BAA8B,EAC9B,wCAAwC,EACxC,uCAAuC,EACvC,wCAAwC,GACzC,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,2CAA2C,EAAE,MAAM,wCAAwC,CAAC;AACrG,OAAO,EACL,8CAA8C,EAC9C,2CAA2C,EAC3C,iDAAiD,GAClD,MAAM,6BAA6B,CAAC;AAOrC,OAAO,EACL,8CAA8C,EAC9C,iDAAiD,GAClD,MAAM,6BAA6B,CAAC;AAGrC,MAAM,UAAU,mCAAmC,CACjD,aAAqC,EACrC,OAAqC;IAErC,MAAM,mBAAmB,GAAG,gCAAgC,CAAC,aAAa,EAAE;QAC1E,2BAA2B,EAAE,OAAO,CAAC,M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BAAoB,CAAC,MAAM,CAAC,QAAQ,CAAC;SACxD;QACD,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,YAAY,EAAE,KAAK,CAAC,SAAS;KAC9B,CAAC,CAAC;IACH,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;QACvB,2CAA2C,CACzC,KAAK,CAAC,wBAAwB,EAC9B,KAAK,CAAC,aAAa,EACnB,EAAE,CACH,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,2CAA2C,CACzC,KAAK,CAAC,wBAAwB,EAC9B,KAAK,CAAC,aAAa,EACnB,EAAE,CACH,CAAC;QACF,aAAa,CAAC,wBAAwB,GAAG,IAAI,CAAC;QAC9C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC3B,CAAC;IACD,aAAa,CAAC,SAAS,GAAG,SAAS,CAAC,SAAS,CAAC;IAC9C,8BAA8B,CAAC,aAAa,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC;IAChE,IAAI,SAAS,CAAC,0BAA0B,EAAE,CAAC;QACzC,oEAAoE;QACpE,2EAA2E;QAC3E,6CAA6C;QAC7C,2CAA2C,CACzC,KAAK,CAAC,wBAAwB,EAC9B,KAAK,CAAC,aAAa,EACnB,EAAE,CACH,CAAC;QACF,aAAa,CAAC,wBAAwB,GAAG,IAAI,CAAC;IAChD,CAAC;IAED,OAAO;QACL,GAAG,SAAS;QACZ,yBAAyB,EAAE,sCAAsC,CAAC;YAChE,SAAS;YACT,kBAAkB,EAAE,GAAG,EAAE,CACvB,mCAAmC,CAAC,aAAa,EAAE,WAAW,CAAC;SAClE,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { isRejectedDecodedProjection } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { ContainerContentsPersistence } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { settleOutgoingPassAndDecideReArm } from \"../../../data/sync/outgoingUpdateSettlement\";\nimport {\n readPullContinuation,\n shouldClearDocumentSyncFailureAfterPass,\n} from \"../../documents\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\nimport { applyIncomingContainerMetadataUpdates } from \"./metadataIncomingUpdateIsolation\";\nimport {\n currentMetadataPullContinuation,\n hasCurrentContainerMetadataReadState,\n installContainerMetadataRecord,\n persistContainerMetadataStateFromRuntime,\n} from \"./metadataPersistence\";\nimport {\n type ContainerMetadataSyncAttempt,\n type ContainerMetadataSyncRuntime,\n syncRemoteContainerMetadata,\n} from \"./metadataRemoteSync\";\nimport {\n createDetachedContainerMetadataState,\n installDetachedContainerMetadataState,\n} from \"./metadataStateIsolation\";\nimport { shouldRequestContainerMetadataFollowup } from \"./metadataSyncFollowup\";\n\nexport {\n hasContainerMetadataDocumentUpdateEvent,\n listContainerMetadataDocumentUpdateIds,\n} from \"./metadataEvents\";\nexport {\n installContainerMetadataRecord,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n setContainerIconMetadataStateFromRuntime,\n} from \"./metadataPersistence\";\n\nimport { invalidateContainerMetadataPullContinuation } from \"./metadataPullContinuationInvalidation\";\nimport {\n cleanupContainerMetadataRegistrationsOnFailure,\n discardUnacceptedContainerMetadataUpdateIds,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"./metadataSyncRegistrations\";\nimport type {\n ContainerMetadataState,\n MissingContainerMetadataState,\n SyncedContainerMetadataState,\n} from \"./metadataTypes\";\n\nexport {\n cleanupContainerMetadataRegistrationsOnFailure,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"./metadataSyncRegistrations\";\nexport type { ContainerMetadataPatch } from \"./metadataTypes\";\n\nexport function settleContainerMetadataOutgoingPass(\n metadataState: ContainerMetadataState,\n attempt: ContainerMetadataSyncAttempt,\n): boolean {\n const shouldReArmOutgoing = settleOutgoingPassAndDecideReArm(metadataState, {\n exhaustedPendingUpdateCount: attempt.synced.exhaustedPendingUpdateCount,\n outgoingUpdateCount: attempt.outgoingUpdateCount,\n rekeyedUpdateCount: attempt.synced.rekeyedPendingUpdateIds.length,\n settledUpdateCount: attempt.synced.settledPendingUpdateIds.length,\n acceptedRecoveryBaseline: attempt.synced.acceptedRecoveryBaseline,\n });\n return (\n attempt.synced.hasDeferredPendingUpdates ||\n shouldReArmOutgoing ||\n attempt.synced.hasIncompletePull\n );\n}\n\nfunction documentWriterProjectionMatchesMetadataSyncResponse(\n writerProjection: DocumentWriterProjectionResponse,\n synced: ContainerMetadataSyncAttempt[\"synced\"],\n): boolean {\n return (\n writerProjection.contentKeyBundle.contentKeyEpoch ===\n synced.plan.sourceContentKeyBundle.contentKeyEpoch &&\n writerProjection.contentKeyBundle.linkSetManifestHash ===\n synced.plan.sourceContentKeyBundle.linkSetManifestHash &&\n writerProjection.contentKeyBundle.targetHash ===\n synced.plan.sourceContentKeyBundle.targetHash &&\n writerProjection.documentKekTargets.linkSetManifestHash ===\n synced.plan.documentKekTargets.linkSetManifestHash &&\n writerProjection.documentKekTargets.documentKeyTargetHash ===\n synced.plan.documentKekTargets.documentKeyTargetHash\n );\n}\n\nfunction resolveSyncedContainerMetadataWriterProjection(\n metadataState: ContainerMetadataState,\n synced: ContainerMetadataSyncAttempt[\"synced\"],\n): DocumentWriterProjectionResponse | null {\n const writerProjection =\n synced.writerProjection ??\n (metadataState.metadataWriterProjection?.documentId ===\n synced.plan.documentId &&\n !isRejectedDecodedProjection(metadataState.metadataWriterProjection)\n ? metadataState.metadataWriterProjection\n : null);\n return writerProjection &&\n documentWriterProjectionMatchesMetadataSyncResponse(\n writerProjection,\n synced,\n )\n ? writerProjection\n : null;\n}\n\n/**\n * Heals a stale metadata content-key bundle by rotating to a fresh content\n * key anchored by this full-history snapshot.\n */\nfunction metadataRotationSnapshotProvider(\n metadataState: ContainerMetadataState,\n): () => Promise<Uint8Array | null> {\n return async () => exportFullHistorySnapshot(metadataState.doc);\n}\n\ninterface SyncContainerMetadataStateInput {\n forceReadSync?: boolean | undefined;\n isCurrent: () => boolean;\n /**\n * Register sent ids before the network await so early self echoes cannot arm\n * a redundant read-sync. Shared with {@link listContainerMetadataDocumentUpdateIds}.\n */\n locallyAcceptedUpdateIds?: Set<string> | undefined;\n metadataState: ContainerMetadataState;\n onDurableStateNeedsReload?: (() => void) | undefined;\n persistence: ContainerContentsPersistence;\n /** The sync pass's operation; its policy reads share one directory view. */\n policyOperation: PrincipalPolicyOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerMetadataSyncRuntime;\n targetSecretKey: Uint8Array;\n}\n\nasync function requestContainerMetadataSync(input: {\n documentId: string;\n metadataState: ContainerMetadataState;\n pendingUpdates: readonly PendingUpdateRecord[];\n sentUpdateIds: string[];\n syncInput: SyncContainerMetadataStateInput;\n}): Promise<ContainerMetadataSyncAttempt | null> {\n const { metadataState, sentUpdateIds, syncInput } = input;\n const { isCurrent, persistence, runtime } = syncInput;\n return cleanupContainerMetadataRegistrationsOnFailure(\n syncInput.locallyAcceptedUpdateIds,\n sentUpdateIds,\n () =>\n syncRemoteContainerMetadata({\n buildRotationSnapshot: metadataRotationSnapshotProvider(metadataState),\n containerId: metadataState.container.id,\n currentDocument: metadataState.doc,\n documentId: input.documentId,\n isCurrent,\n lastCommitLsn: metadataState.record.lastCommitLsn,\n localVersionVector: encodeVersionVector(metadataState.doc),\n onOutgoingUpdatesMaterialized: (updateIds) => {\n if (isCurrent()) {\n preRegisterMaterializedContainerMetadataUpdateIds(\n syncInput.locallyAcceptedUpdateIds,\n sentUpdateIds,\n updateIds,\n );\n }\n },\n onPullContinuationInvalidated: (continuation) =>\n invalidateContainerMetadataPullContinuation({\n continuation,\n isCurrent,\n metadataState,\n persistence,\n runtime,\n }),\n pendingUpdates: input.pendingUpdates,\n persistedState: metadataState.record,\n policyOperation: syncInput.policyOperation,\n pullContinuation:\n currentMetadataPullContinuation(metadataState) ?? undefined,\n rekeyPendingUpdate: persistence.rekeyPendingUpdate,\n resolveProjectionUserKey: syncInput.resolveProjectionUserKey,\n runtime,\n targetSecretKey: syncInput.targetSecretKey,\n writerProjection:\n metadataState.metadataWriterProjection?.documentId ===\n input.documentId &&\n !isRejectedDecodedProjection(metadataState.metadataWriterProjection)\n ? metadataState.metadataWriterProjection\n : undefined,\n }),\n );\n}\n\nexport async function syncContainerMetadataState(\n input: SyncContainerMetadataStateInput,\n): Promise<\n SyncedContainerMetadataState | MissingContainerMetadataState | null\n> {\n const { persistence, runtime } = input;\n const liveMetadataState = input.metadataState;\n const { isCurrent } = input;\n if (!isCurrent()) {\n return null;\n }\n const { documentId } = liveMetadataState.record;\n if (!documentId) {\n return null;\n }\n const execSql = runtime.infra.execSql;\n\n const pendingUpdates = await persistence.listPendingUpdates(\n execSql,\n liveMetadataState.container.id,\n );\n if (!isCurrent()) {\n return null;\n }\n if (\n pendingUpdates.length === 0 &&\n currentMetadataPullContinuation(liveMetadataState) === null &&\n !liveMetadataState.record.pullContinuationRecoveryRequired &&\n !input.forceReadSync &&\n hasCurrentContainerMetadataReadState(liveMetadataState.record)\n ) {\n return null;\n }\n const metadataState =\n await createDetachedContainerMetadataState(liveMetadataState);\n if (!isCurrent()) {\n return null;\n }\n\n const sentUpdateIds: string[] = [];\n\n const syncAttempt = await requestContainerMetadataSync({\n documentId,\n metadataState,\n pendingUpdates,\n sentUpdateIds,\n syncInput: input,\n });\n if (!syncAttempt) {\n return null;\n }\n if (!isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n sentUpdateIds,\n [],\n );\n return null;\n }\n const finalized = await finalizeContainerMetadataSync({\n documentId,\n isCurrent,\n locallyAcceptedUpdateIds: input.locallyAcceptedUpdateIds,\n metadataState,\n onDurableStateNeedsReload: input.onDurableStateNeedsReload,\n persistence,\n runtime,\n sentUpdateIds,\n syncAttempt,\n });\n if (!isCurrent() || !finalized) {\n return null;\n }\n if (!(\"missing\" in finalized)) {\n installDetachedContainerMetadataState(liveMetadataState, metadataState, {\n preserveConcurrentMetadataEdit: true,\n });\n }\n return finalized;\n}\n\nasync function finalizeContainerMetadataSync(input: {\n documentId: string;\n isCurrent: () => boolean;\n locallyAcceptedUpdateIds: Set<string> | undefined;\n metadataState: ContainerMetadataState;\n onDurableStateNeedsReload?: (() => void) | undefined;\n persistence: ContainerContentsPersistence;\n runtime: ContainerMetadataSyncRuntime;\n sentUpdateIds: readonly string[];\n syncAttempt: ContainerMetadataSyncAttempt;\n}): Promise<\n SyncedContainerMetadataState | MissingContainerMetadataState | null\n> {\n const { metadataState, syncAttempt } = input;\n const { outgoingUpdateCount, synced } = syncAttempt;\n if (!input.isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n return null;\n }\n // An id sent but not accepted will never be echoed. Accepted ids stay\n // registered until their realtime echo consumes them.\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n synced.response.acceptedOutgoingUpdateIds,\n );\n metadataState.metadataWriterProjection =\n resolveSyncedContainerMetadataWriterProjection(metadataState, synced);\n if (synced.decryptedUpdates.length > 0) {\n applyIncomingContainerMetadataUpdates(metadataState.doc, synced);\n }\n const persisted = await persistContainerMetadataStateFromRuntime({\n acceptedPendingUpdateIds: synced.settledPendingUpdateIds,\n clearSyncFailure: shouldClearDocumentSyncFailureAfterPass(\n synced,\n outgoingUpdateCount,\n ),\n expectedSyncState: {\n pullContinuation: syncAttempt.consumedPullContinuation ?? null,\n record: syncAttempt.requestRecord,\n },\n metadataState,\n onDurableStateNeedsReload: input.onDurableStateNeedsReload,\n patch: {\n ...synced.persistedState,\n documentId: input.documentId,\n lastCommitLsn:\n synced.response.commitLsn ?? metadataState.record.lastCommitLsn ?? null,\n metadataDocumentId: input.documentId,\n pullContinuation: readPullContinuation(synced.response),\n },\n persistence: input.persistence,\n runtime: input.runtime,\n stillCurrent: input.isCurrent,\n });\n if (!input.isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n return null;\n }\n if (!persisted) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n metadataState.metadataWriterProjection = null;\n return { missing: true };\n }\n metadataState.container = persisted.container;\n installContainerMetadataRecord(metadataState, persisted.record);\n if (persisted.pullContinuationSuperseded) {\n // The response's accepted IDs were not durably settled. Treat every\n // pre-registration as unapplied so an early echo cannot hide work that the\n // forced follow-up still needs to reconcile.\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n metadataState.metadataWriterProjection = null;\n }\n\n return {\n ...persisted,\n shouldRequestFollowupSync: shouldRequestContainerMetadataFollowup({\n persisted,\n settleOutgoingPass: () =>\n settleContainerMetadataOutgoingPass(metadataState, syncAttempt),\n }),\n };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAI7E,OAAO,EAAE,gCAAgC,EAAE,MAAM,6CAA6C,CAAC;AAC/F,OAAO,EACL,oBAAoB,EACpB,uCAAuC,GACxC,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAC1F,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,EACpC,8BAA8B,EAC9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wB,GAAG,IAAI,CAAC;QAC9C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC3B,CAAC;IACD,aAAa,CAAC,SAAS,GAAG,SAAS,CAAC,SAAS,CAAC;IAC9C,8BAA8B,CAAC,aAAa,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC;IAChE,IAAI,SAAS,CAAC,0BAA0B,EAAE,CAAC;QACzC,oEAAoE;QACpE,2EAA2E;QAC3E,6CAA6C;QAC7C,2CAA2C,CACzC,KAAK,CAAC,wBAAwB,EAC9B,KAAK,CAAC,aAAa,EACnB,EAAE,CACH,CAAC;QACF,aAAa,CAAC,wBAAwB,GAAG,IAAI,CAAC;IAChD,CAAC;IAED,OAAO;QACL,GAAG,SAAS;QACZ,GAAG,CAAC,0BAA0B,CAAC,WAAW,CAAC;YACzC,CAAC,CAAC,EAAE,kBAAkB,EAAE,IAAa,EAAE;YACvC,CAAC,CAAC,EAAE,CAAC;QACP,yBAAyB,EAAE,sCAAsC,CAAC;YAChE,SAAS;YACT,kBAAkB,EAAE,GAAG,EAAE,CACvB,mCAAmC,CAAC,aAAa,EAAE,WAAW,CAAC;SAClE,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { isRejectedDecodedProjection } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { ContainerContentsPersistence } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { settleOutgoingPassAndDecideReArm } from \"../../../data/sync/outgoingUpdateSettlement\";\nimport {\n readPullContinuation,\n shouldClearDocumentSyncFailureAfterPass,\n} from \"../../documents\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\nimport { applyIncomingContainerMetadataUpdates } from \"./metadataIncomingUpdateIsolation\";\nimport {\n currentMetadataPullContinuation,\n hasCurrentContainerMetadataReadState,\n installContainerMetadataRecord,\n persistContainerMetadataStateFromRuntime,\n} from \"./metadataPersistence\";\nimport {\n type ContainerMetadataSyncAttempt,\n type ContainerMetadataSyncRuntime,\n syncRemoteContainerMetadata,\n} from \"./metadataRemoteSync\";\nimport {\n createDetachedContainerMetadataState,\n installDetachedContainerMetadataState,\n} from \"./metadataStateIsolation\";\nimport {\n resumedEarlierMetadataPull,\n shouldRequestContainerMetadataFollowup,\n} from \"./metadataSyncFollowup\";\n\nexport {\n hasContainerMetadataDocumentUpdateEvent,\n listContainerMetadataDocumentUpdateIds,\n} from \"./metadataEvents\";\nexport {\n installContainerMetadataRecord,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n setContainerIconMetadataStateFromRuntime,\n} from \"./metadataPersistence\";\n\nimport { invalidateContainerMetadataPullContinuation } from \"./metadataPullContinuationInvalidation\";\nimport {\n cleanupContainerMetadataRegistrationsOnFailure,\n discardUnacceptedContainerMetadataUpdateIds,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"./metadataSyncRegistrations\";\nimport type {\n ContainerMetadataState,\n MissingContainerMetadataState,\n SyncedContainerMetadataState,\n} from \"./metadataTypes\";\n\nexport {\n cleanupContainerMetadataRegistrationsOnFailure,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"./metadataSyncRegistrations\";\nexport type { ContainerMetadataPatch } from \"./metadataTypes\";\n\nexport function settleContainerMetadataOutgoingPass(\n metadataState: ContainerMetadataState,\n attempt: ContainerMetadataSyncAttempt,\n): boolean {\n const shouldReArmOutgoing = settleOutgoingPassAndDecideReArm(metadataState, {\n exhaustedPendingUpdateCount: attempt.synced.exhaustedPendingUpdateCount,\n outgoingUpdateCount: attempt.outgoingUpdateCount,\n rekeyedUpdateCount: attempt.synced.rekeyedPendingUpdateIds.length,\n settledUpdateCount: attempt.synced.settledPendingUpdateIds.length,\n acceptedRecoveryBaseline: attempt.synced.acceptedRecoveryBaseline,\n });\n return (\n attempt.synced.hasDeferredPendingUpdates ||\n shouldReArmOutgoing ||\n attempt.synced.hasIncompletePull\n );\n}\n\nfunction documentWriterProjectionMatchesMetadataSyncResponse(\n writerProjection: DocumentWriterProjectionResponse,\n synced: ContainerMetadataSyncAttempt[\"synced\"],\n): boolean {\n return (\n writerProjection.contentKeyBundle.contentKeyEpoch ===\n synced.plan.sourceContentKeyBundle.contentKeyEpoch &&\n writerProjection.contentKeyBundle.linkSetManifestHash ===\n synced.plan.sourceContentKeyBundle.linkSetManifestHash &&\n writerProjection.contentKeyBundle.targetHash ===\n synced.plan.sourceContentKeyBundle.targetHash &&\n writerProjection.documentKekTargets.linkSetManifestHash ===\n synced.plan.documentKekTargets.linkSetManifestHash &&\n writerProjection.documentKekTargets.documentKeyTargetHash ===\n synced.plan.documentKekTargets.documentKeyTargetHash\n );\n}\n\nfunction resolveSyncedContainerMetadataWriterProjection(\n metadataState: ContainerMetadataState,\n synced: ContainerMetadataSyncAttempt[\"synced\"],\n): DocumentWriterProjectionResponse | null {\n const writerProjection =\n synced.writerProjection ??\n (metadataState.metadataWriterProjection?.documentId ===\n synced.plan.documentId &&\n !isRejectedDecodedProjection(metadataState.metadataWriterProjection)\n ? metadataState.metadataWriterProjection\n : null);\n return writerProjection &&\n documentWriterProjectionMatchesMetadataSyncResponse(\n writerProjection,\n synced,\n )\n ? writerProjection\n : null;\n}\n\n/**\n * Heals a stale metadata content-key bundle by rotating to a fresh content\n * key anchored by this full-history snapshot.\n */\nfunction metadataRotationSnapshotProvider(\n metadataState: ContainerMetadataState,\n): () => Promise<Uint8Array | null> {\n return async () => exportFullHistorySnapshot(metadataState.doc);\n}\n\ninterface SyncContainerMetadataStateInput {\n forceReadSync?: boolean | undefined;\n isCurrent: () => boolean;\n /**\n * Register sent ids before the network await so early self echoes cannot arm\n * a redundant read-sync. Shared with {@link listContainerMetadataDocumentUpdateIds}.\n */\n locallyAcceptedUpdateIds?: Set<string> | undefined;\n metadataState: ContainerMetadataState;\n onDurableStateNeedsReload?: (() => void) | undefined;\n persistence: ContainerContentsPersistence;\n /** The sync pass's operation; its policy reads share one directory view. */\n policyOperation: PrincipalPolicyOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerMetadataSyncRuntime;\n targetSecretKey: Uint8Array;\n}\n\nasync function requestContainerMetadataSync(input: {\n documentId: string;\n metadataState: ContainerMetadataState;\n pendingUpdates: readonly PendingUpdateRecord[];\n sentUpdateIds: string[];\n syncInput: SyncContainerMetadataStateInput;\n}): Promise<ContainerMetadataSyncAttempt | null> {\n const { metadataState, sentUpdateIds, syncInput } = input;\n const { isCurrent, persistence, runtime } = syncInput;\n return cleanupContainerMetadataRegistrationsOnFailure(\n syncInput.locallyAcceptedUpdateIds,\n sentUpdateIds,\n () =>\n syncRemoteContainerMetadata({\n buildRotationSnapshot: metadataRotationSnapshotProvider(metadataState),\n containerId: metadataState.container.id,\n currentDocument: metadataState.doc,\n documentId: input.documentId,\n isCurrent,\n lastCommitLsn: metadataState.record.lastCommitLsn,\n localVersionVector: encodeVersionVector(metadataState.doc),\n onOutgoingUpdatesMaterialized: (updateIds) => {\n if (isCurrent()) {\n preRegisterMaterializedContainerMetadataUpdateIds(\n syncInput.locallyAcceptedUpdateIds,\n sentUpdateIds,\n updateIds,\n );\n }\n },\n onPullContinuationInvalidated: (continuation) =>\n invalidateContainerMetadataPullContinuation({\n continuation,\n isCurrent,\n metadataState,\n persistence,\n runtime,\n }),\n pendingUpdates: input.pendingUpdates,\n persistedState: metadataState.record,\n policyOperation: syncInput.policyOperation,\n pullContinuation:\n currentMetadataPullContinuation(metadataState) ?? undefined,\n rekeyPendingUpdate: persistence.rekeyPendingUpdate,\n resolveProjectionUserKey: syncInput.resolveProjectionUserKey,\n runtime,\n targetSecretKey: syncInput.targetSecretKey,\n writerProjection:\n metadataState.metadataWriterProjection?.documentId ===\n input.documentId &&\n !isRejectedDecodedProjection(metadataState.metadataWriterProjection)\n ? metadataState.metadataWriterProjection\n : undefined,\n }),\n );\n}\n\nexport async function syncContainerMetadataState(\n input: SyncContainerMetadataStateInput,\n): Promise<\n SyncedContainerMetadataState | MissingContainerMetadataState | null\n> {\n const { persistence, runtime } = input;\n const liveMetadataState = input.metadataState;\n const { isCurrent } = input;\n if (!isCurrent()) {\n return null;\n }\n const { documentId } = liveMetadataState.record;\n if (!documentId) {\n return null;\n }\n const execSql = runtime.infra.execSql;\n\n const pendingUpdates = await persistence.listPendingUpdates(\n execSql,\n liveMetadataState.container.id,\n );\n if (!isCurrent()) {\n return null;\n }\n if (\n pendingUpdates.length === 0 &&\n currentMetadataPullContinuation(liveMetadataState) === null &&\n !liveMetadataState.record.pullContinuationRecoveryRequired &&\n !input.forceReadSync &&\n hasCurrentContainerMetadataReadState(liveMetadataState.record)\n ) {\n return null;\n }\n const metadataState =\n await createDetachedContainerMetadataState(liveMetadataState);\n if (!isCurrent()) {\n return null;\n }\n\n const sentUpdateIds: string[] = [];\n\n const syncAttempt = await requestContainerMetadataSync({\n documentId,\n metadataState,\n pendingUpdates,\n sentUpdateIds,\n syncInput: input,\n });\n if (!syncAttempt) {\n return null;\n }\n if (!isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n sentUpdateIds,\n [],\n );\n return null;\n }\n const finalized = await finalizeContainerMetadataSync({\n documentId,\n isCurrent,\n locallyAcceptedUpdateIds: input.locallyAcceptedUpdateIds,\n metadataState,\n onDurableStateNeedsReload: input.onDurableStateNeedsReload,\n persistence,\n runtime,\n sentUpdateIds,\n syncAttempt,\n });\n if (!isCurrent() || !finalized) {\n return null;\n }\n if (!(\"missing\" in finalized)) {\n installDetachedContainerMetadataState(liveMetadataState, metadataState, {\n preserveConcurrentMetadataEdit: true,\n });\n }\n return finalized;\n}\n\nasync function finalizeContainerMetadataSync(input: {\n documentId: string;\n isCurrent: () => boolean;\n locallyAcceptedUpdateIds: Set<string> | undefined;\n metadataState: ContainerMetadataState;\n onDurableStateNeedsReload?: (() => void) | undefined;\n persistence: ContainerContentsPersistence;\n runtime: ContainerMetadataSyncRuntime;\n sentUpdateIds: readonly string[];\n syncAttempt: ContainerMetadataSyncAttempt;\n}): Promise<\n SyncedContainerMetadataState | MissingContainerMetadataState | null\n> {\n const { metadataState, syncAttempt } = input;\n const { outgoingUpdateCount, synced } = syncAttempt;\n if (!input.isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n return null;\n }\n // An id sent but not accepted will never be echoed. Accepted ids stay\n // registered until their realtime echo consumes them.\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n synced.response.acceptedOutgoingUpdateIds,\n );\n metadataState.metadataWriterProjection =\n resolveSyncedContainerMetadataWriterProjection(metadataState, synced);\n if (synced.decryptedUpdates.length > 0) {\n applyIncomingContainerMetadataUpdates(metadataState.doc, synced);\n }\n const persisted = await persistContainerMetadataStateFromRuntime({\n acceptedPendingUpdateIds: synced.settledPendingUpdateIds,\n clearSyncFailure: shouldClearDocumentSyncFailureAfterPass(\n synced,\n outgoingUpdateCount,\n ),\n expectedSyncState: {\n pullContinuation: syncAttempt.consumedPullContinuation ?? null,\n record: syncAttempt.requestRecord,\n },\n metadataState,\n onDurableStateNeedsReload: input.onDurableStateNeedsReload,\n patch: {\n ...synced.persistedState,\n documentId: input.documentId,\n lastCommitLsn:\n synced.response.commitLsn ?? metadataState.record.lastCommitLsn ?? null,\n metadataDocumentId: input.documentId,\n pullContinuation: readPullContinuation(synced.response),\n },\n persistence: input.persistence,\n runtime: input.runtime,\n stillCurrent: input.isCurrent,\n });\n if (!input.isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n return null;\n }\n if (!persisted) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n metadataState.metadataWriterProjection = null;\n return { missing: true };\n }\n metadataState.container = persisted.container;\n installContainerMetadataRecord(metadataState, persisted.record);\n if (persisted.pullContinuationSuperseded) {\n // The response's accepted IDs were not durably settled. Treat every\n // pre-registration as unapplied so an early echo cannot hide work that the\n // forced follow-up still needs to reconcile.\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n metadataState.metadataWriterProjection = null;\n }\n\n return {\n ...persisted,\n ...(resumedEarlierMetadataPull(syncAttempt)\n ? { resumedEarlierPull: true as const }\n : {}),\n shouldRequestFollowupSync: shouldRequestContainerMetadataFollowup({\n persisted,\n settleOutgoingPass: () =>\n settleContainerMetadataOutgoingPass(metadataState, syncAttempt),\n }),\n };\n}\n"]}
@@ -1,3 +1,12 @@
1
+ /**
2
+ * Whether a metadata read resumed an earlier pull's pages, so it stopped at
3
+ * that pull's upper bound, which can predate a signal raised since. Decided
4
+ * from the continuation the read consumed, not one observed before it.
5
+ */
6
+ export function resumedEarlierMetadataPull(attempt) {
7
+ return (attempt.consumedPullContinuation != null ||
8
+ attempt.requestRecord.pullContinuationRecoveryRequired === true);
9
+ }
1
10
  export function shouldRequestContainerMetadataFollowup(input) {
2
11
  const { persisted } = input;
3
12
  if (persisted.syncIdentitySuperseded === true ||
@@ -1 +1 @@
1
- {"version":3,"file":"metadataSyncFollowup.js","sourceRoot":"","sources":["metadataSyncFollowup.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,sCAAsC,CAAC,KAMtD;IACC,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC;IAC5B,IACE,SAAS,CAAC,sBAAsB,KAAK,IAAI;QACzC,SAAS,CAAC,0BAA0B,KAAK,IAAI;QAC7C,SAAS,CAAC,MAAM,CAAC,gBAAgB,IAAI,IAAI;QACzC,SAAS,CAAC,MAAM,CAAC,gCAAgC,KAAK,IAAI,EAC1D,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,KAAK,CAAC,kBAAkB,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import type { SyncedContainerMetadataState } from \"./metadataTypes\";\n\nexport function shouldRequestContainerMetadataFollowup(input: {\n persisted: Pick<\n SyncedContainerMetadataState,\n \"pullContinuationSuperseded\" | \"record\" | \"syncIdentitySuperseded\"\n >;\n settleOutgoingPass: () => boolean;\n}): boolean {\n const { persisted } = input;\n if (\n persisted.syncIdentitySuperseded === true ||\n persisted.pullContinuationSuperseded === true ||\n persisted.record.pullContinuation != null ||\n persisted.record.pullContinuationRecoveryRequired === true\n ) {\n return true;\n }\n return input.settleOutgoingPass();\n}\n"]}
1
+ {"version":3,"file":"metadataSyncFollowup.js","sourceRoot":"","sources":["metadataSyncFollowup.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CACxC,OAGC;IAED,OAAO,CACL,OAAO,CAAC,wBAAwB,IAAI,IAAI;QACxC,OAAO,CAAC,aAAa,CAAC,gCAAgC,KAAK,IAAI,CAChE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,sCAAsC,CAAC,KAMtD;IACC,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC;IAC5B,IACE,SAAS,CAAC,sBAAsB,KAAK,IAAI;QACzC,SAAS,CAAC,0BAA0B,KAAK,IAAI;QAC7C,SAAS,CAAC,MAAM,CAAC,gBAAgB,IAAI,IAAI;QACzC,SAAS,CAAC,MAAM,CAAC,gCAAgC,KAAK,IAAI,EAC1D,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,KAAK,CAAC,kBAAkB,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import type { ContainerMetadataSyncAttempt } from \"./metadataRemoteSync\";\nimport type { SyncedContainerMetadataState } from \"./metadataTypes\";\n\n/**\n * Whether a metadata read resumed an earlier pull's pages, so it stopped at\n * that pull's upper bound, which can predate a signal raised since. Decided\n * from the continuation the read consumed, not one observed before it.\n */\nexport function resumedEarlierMetadataPull(\n attempt: Pick<\n ContainerMetadataSyncAttempt,\n \"consumedPullContinuation\" | \"requestRecord\"\n >,\n): boolean {\n return (\n attempt.consumedPullContinuation != null ||\n attempt.requestRecord.pullContinuationRecoveryRequired === true\n );\n}\n\nexport function shouldRequestContainerMetadataFollowup(input: {\n persisted: Pick<\n SyncedContainerMetadataState,\n \"pullContinuationSuperseded\" | \"record\" | \"syncIdentitySuperseded\"\n >;\n settleOutgoingPass: () => boolean;\n}): boolean {\n const { persisted } = input;\n if (\n persisted.syncIdentitySuperseded === true ||\n persisted.pullContinuationSuperseded === true ||\n persisted.record.pullContinuation != null ||\n persisted.record.pullContinuationRecoveryRequired === true\n ) {\n return true;\n }\n return input.settleOutgoingPass();\n}\n"]}
@@ -48,6 +48,8 @@ export interface PersistedContainerMetadataState {
48
48
  syncIdentitySuperseded?: true;
49
49
  }
50
50
  export interface SyncedContainerMetadataState extends PersistedContainerMetadataState {
51
+ /** The read resumed an earlier pull's pages and stopped at its bound. */
52
+ resumedEarlierPull?: true;
51
53
  shouldRequestFollowupSync: boolean;
52
54
  }
53
55
  export interface MissingContainerMetadataState {
@@ -1 +1 @@
1
- {"version":3,"file":"metadataTypes.js","sourceRoot":"","sources":["metadataTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ContainerMetadataRecord } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport type { ContainerRecord } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport type { DocumentSyncPullContinuation } from \"../../documents\";\nimport type { ContainerMetadataDocument } from \"./containerMetadataDocument\";\n\nexport interface ContainerMetadataState {\n container: ContainerRecord;\n doc: ContainerMetadataDocument;\n metadataWriterProjection?:\n | DocumentWriterProjectionResponse\n | null\n | undefined;\n /** See `ContainerState.writerProjectionGeneration`; shared by both caches. */\n writerProjectionGeneration?: number | undefined;\n /** Durable continuation mirrored from the metadata document record. */\n pullContinuation?: DocumentSyncPullContinuation | null | undefined;\n record: ContainerMetadataRecord;\n /**\n * Consecutive completed sync passes that re-keyed conflicted pending updates\n * without settling anything; bounds the rekey-driven follow-up sync. See\n * shouldReArmAfterOutgoingSettlement.\n */\n rekeyOnlyPassCount?: number | undefined;\n}\n\nexport interface ContainerMetadataPatch {\n accessEpoch: number;\n accessStateHash: string | null;\n effectiveAccessLevel: ContainerRecord[\"effectiveAccessLevel\"];\n documentId: string | null;\n icon: string | null;\n primaryDocumentId: string | null;\n lastCommitLsn: string | null;\n metadataDocumentId: string | null;\n systemSlot: ContainerRecord[\"systemSlot\"];\n metadataUpdates: string;\n name: string;\n organizationId: string;\n parentId: string | null;\n pullContinuation: DocumentSyncPullContinuation | null;\n contentKeyBundle: string | null;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n}\n\nexport interface PersistedContainerMetadataState {\n container: ContainerRecord;\n createIntentSettled?: true;\n moveIntentSettled?: true;\n mutationSuperseded?: true;\n pullContinuationSuperseded?: true;\n record: ContainerMetadataRecord;\n syncIdentitySuperseded?: true;\n}\n\nexport interface SyncedContainerMetadataState\n extends PersistedContainerMetadataState {\n shouldRequestFollowupSync: boolean;\n}\n\nexport interface MissingContainerMetadataState {\n missing: true;\n}\n"]}
1
+ {"version":3,"file":"metadataTypes.js","sourceRoot":"","sources":["metadataTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ContainerMetadataRecord } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport type { ContainerRecord } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport type { DocumentSyncPullContinuation } from \"../../documents\";\nimport type { ContainerMetadataDocument } from \"./containerMetadataDocument\";\n\nexport interface ContainerMetadataState {\n container: ContainerRecord;\n doc: ContainerMetadataDocument;\n metadataWriterProjection?:\n | DocumentWriterProjectionResponse\n | null\n | undefined;\n /** See `ContainerState.writerProjectionGeneration`; shared by both caches. */\n writerProjectionGeneration?: number | undefined;\n /** Durable continuation mirrored from the metadata document record. */\n pullContinuation?: DocumentSyncPullContinuation | null | undefined;\n record: ContainerMetadataRecord;\n /**\n * Consecutive completed sync passes that re-keyed conflicted pending updates\n * without settling anything; bounds the rekey-driven follow-up sync. See\n * shouldReArmAfterOutgoingSettlement.\n */\n rekeyOnlyPassCount?: number | undefined;\n}\n\nexport interface ContainerMetadataPatch {\n accessEpoch: number;\n accessStateHash: string | null;\n effectiveAccessLevel: ContainerRecord[\"effectiveAccessLevel\"];\n documentId: string | null;\n icon: string | null;\n primaryDocumentId: string | null;\n lastCommitLsn: string | null;\n metadataDocumentId: string | null;\n systemSlot: ContainerRecord[\"systemSlot\"];\n metadataUpdates: string;\n name: string;\n organizationId: string;\n parentId: string | null;\n pullContinuation: DocumentSyncPullContinuation | null;\n contentKeyBundle: string | null;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n}\n\nexport interface PersistedContainerMetadataState {\n container: ContainerRecord;\n createIntentSettled?: true;\n moveIntentSettled?: true;\n mutationSuperseded?: true;\n pullContinuationSuperseded?: true;\n record: ContainerMetadataRecord;\n syncIdentitySuperseded?: true;\n}\n\nexport interface SyncedContainerMetadataState\n extends PersistedContainerMetadataState {\n /** The read resumed an earlier pull's pages and stopped at its bound. */\n resumedEarlierPull?: true;\n shouldRequestFollowupSync: boolean;\n}\n\nexport interface MissingContainerMetadataState {\n missing: true;\n}\n"]}
@@ -33,6 +33,15 @@ export function createGenerationGuardedHydrationHost(input) {
33
33
  },
34
34
  }
35
35
  : {}),
36
+ ...(input.host.requestMetadataRevalidation
37
+ ? {
38
+ requestMetadataRevalidation: async (request) => {
39
+ assertCurrent();
40
+ await input.host.requestMetadataRevalidation?.(request);
41
+ assertCurrent();
42
+ },
43
+ }
44
+ : {}),
36
45
  updateSnapshot: () => {
37
46
  if (input.isCurrent()) {
38
47
  input.host.updateSnapshot();
@@ -1 +1 @@
1
- {"version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\";\nimport { createContainerChildIndex } from \"./lanes/childIndex\";\nimport { createContainerParentHydrationQueue } from \"./lanes/parentLaneQueue\";\nimport { cacheRemoteContainerPrincipalPolicies } from \"./principalPolicyCache\";\nimport { loadPausedContainerFilter } from \"./remoteContainers/organizationSyncPauseFilter\";\nimport {\n canHydrateRemoteContainers,\n hydrateContainerParentLanes,\n} from \"./remoteContainers/remoteContainerPageHydration\";\nimport {\n listRemoteContainerIdsWithPendingMetadataUpdates,\n listRemoteContainerIdsWithPendingStructuralIntents,\n upsertIsolatedRemoteContainerState,\n} from \"./remoteContainers/remoteContainerState\";\nimport type {\n QueueContainerParentLane,\n RemoteContainer,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n RemoteContainerIngestQueue,\n} from \"./types\";\n\nexport type {\n ContainerState,\n PersistContainerStateResult,\n RemoteContainer,\n RemoteContainerHydrationHost,\n} from \"./types\";\n\nexport class StaleRemoteHydrationError extends Error {}\n\nexport function createGenerationGuardedHydrationHost(input: {\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n}): RemoteContainerHydrationHost {\n const assertCurrent = () => {\n if (!input.isCurrent()) {\n throw new StaleRemoteHydrationError();\n }\n };\n\n return {\n persistContainerState: async (\n containerState,\n patch,\n updateView,\n saveOptions,\n mutationOptions,\n ) => {\n const callerIsCurrent = mutationOptions?.isCurrent;\n const isCurrent = callerIsCurrent\n ? () => input.isCurrent() && callerIsCurrent()\n : input.isCurrent;\n assertCurrent();\n const record = await input.host.persistContainerState(\n containerState,\n patch,\n updateView,\n saveOptions,\n { ...mutationOptions, isCurrent },\n );\n assertCurrent();\n return record;\n },\n ...(input.host.requestDocumentPriming\n ? {\n requestDocumentPriming: () => {\n if (input.isCurrent()) {\n input.host.requestDocumentPriming?.();\n }\n },\n }\n : {}),\n updateSnapshot: () => {\n if (input.isCurrent()) {\n input.host.updateSnapshot();\n }\n },\n };\n}\n\ninterface RemoteContainerIngestGeneration {\n readonly lifecycle: number | undefined;\n readonly structural: number | undefined;\n}\ntype RemoteContainerIngestGenerationMap = Map<\n string,\n RemoteContainerIngestGeneration\n>;\n\nfunction remoteContainerIngestGeneration(\n state: RemoteContainerHydrationState,\n): RemoteContainerIngestGeneration {\n return {\n lifecycle: state.lifecycleGeneration,\n structural: state.structuralGeneration,\n };\n}\n\nfunction remoteContainerIngestGenerationsMatch(\n left: RemoteContainerIngestGeneration | undefined,\n right: RemoteContainerIngestGeneration,\n): boolean {\n return (\n left !== undefined &&\n left.lifecycle === right.lifecycle &&\n left.structural === right.structural\n );\n}\n\nfunction isCurrentQueuedRemoteContainer(\n generation: RemoteContainerIngestGeneration,\n generationByContainerId: RemoteContainerIngestGenerationMap,\n queue: RemoteContainerIngestQueue,\n remoteContainer: RemoteContainer,\n): boolean {\n return (\n queue.get(remoteContainer.id) === remoteContainer &&\n remoteContainerIngestGenerationsMatch(\n generationByContainerId.get(remoteContainer.id),\n generation,\n )\n );\n}\n\nasync function upsertQueuedRemoteContainer(input: {\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n generation: RemoteContainerIngestGeneration;\n generationByContainerId: RemoteContainerIngestGenerationMap;\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n queue: RemoteContainerIngestQueue;\n queuedRemoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): Promise<boolean> {\n const {\n containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents,\n generation,\n generationByContainerId,\n host,\n queue,\n queuedRemoteContainer,\n state,\n } = input;\n if (\n !input.isCurrent() ||\n !isCurrentQueuedRemoteContainer(\n generation,\n generationByContainerId,\n queue,\n queuedRemoteContainer,\n )\n ) {\n return false;\n }\n\n // A paused organization's container is acknowledged without being applied,\n // including when the pause lands while the commit is in flight.\n const isPaused = await loadPausedContainerFilter(state);\n if (isPaused(queuedRemoteContainer)) return true;\n const tombstones = await state.persistence.loadContainerHydrationTombstones(\n state.runtime.infra.execSql,\n );\n // A refused folder is reported and acknowledged; the batch continues.\n const upserted = await upsertIsolatedRemoteContainerState({\n expectedHydrationTombstone:\n tombstones.find((row) => row.containerId === queuedRemoteContainer.id) ??\n null,\n containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents,\n host,\n isCurrent: () => input.isCurrent() && !isPaused(queuedRemoteContainer),\n remoteContainer: queuedRemoteContainer,\n state,\n });\n if (!upserted) {\n return false;\n }\n return true;\n}\n\nfunction acknowledgeRemoteContainerIngestBatch(input: {\n generation: RemoteContainerIngestGeneration;\n generationByContainerId: RemoteContainerIngestGenerationMap;\n isCurrent: () => boolean;\n queue: RemoteContainerIngestQueue;\n queuedRemoteContainers: ReadonlyArray<RemoteContainer>;\n}): void {\n if (!input.isCurrent()) {\n return;\n }\n for (const queuedRemoteContainer of input.queuedRemoteContainers) {\n if (\n isCurrentQueuedRemoteContainer(\n input.generation,\n input.generationByContainerId,\n input.queue,\n queuedRemoteContainer,\n )\n ) {\n input.queue.delete(queuedRemoteContainer.id);\n input.generationByContainerId.delete(queuedRemoteContainer.id);\n }\n }\n}\n\nasync function drainRemoteContainerIngestQueue(input: {\n generation: RemoteContainerIngestGeneration;\n generationByContainerId: RemoteContainerIngestGenerationMap;\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n queue: RemoteContainerIngestQueue;\n state: RemoteContainerHydrationState;\n}) {\n const { generation, generationByContainerId, host, queue, state } = input;\n let shouldUpdateSnapshot = false;\n\n try {\n while (input.isCurrent()) {\n const queuedRemoteContainers = Array.from(queue.values()).filter(\n (remoteContainer) =>\n remoteContainerIngestGenerationsMatch(\n generationByContainerId.get(remoteContainer.id),\n generation,\n ),\n );\n if (queuedRemoteContainers.length === 0) {\n return;\n }\n await cacheRemoteContainerPrincipalPolicies({\n cacheReferencedPrincipalPolicies:\n state.runtime.principalPolicies.createWarmer(),\n remoteContainers: queuedRemoteContainers,\n stillCurrent: input.isCurrent,\n });\n if (!input.isCurrent()) {\n return;\n }\n const [\n containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents,\n ] = await Promise.all([\n listRemoteContainerIdsWithPendingMetadataUpdates({\n remoteContainers: queuedRemoteContainers,\n state,\n }),\n listRemoteContainerIdsWithPendingStructuralIntents({\n remoteContainers: queuedRemoteContainers,\n state,\n }),\n ]);\n if (!input.isCurrent()) {\n return;\n }\n\n for (const queuedRemoteContainer of queuedRemoteContainers) {\n shouldUpdateSnapshot =\n (await upsertQueuedRemoteContainer({\n containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents,\n generation,\n generationByContainerId,\n host,\n isCurrent: input.isCurrent,\n queue,\n queuedRemoteContainer,\n state,\n })) || shouldUpdateSnapshot;\n }\n acknowledgeRemoteContainerIngestBatch({\n generation,\n generationByContainerId,\n isCurrent: input.isCurrent,\n queue,\n queuedRemoteContainers,\n });\n\n if (shouldUpdateSnapshot) {\n host.updateSnapshot();\n shouldUpdateSnapshot = false;\n }\n }\n } catch (error) {\n if (shouldUpdateSnapshot) {\n host.updateSnapshot();\n }\n throw error;\n }\n}\n\nfunction isRemoteContainerIngestGenerationCurrent(\n state: RemoteContainerHydrationState,\n generation: RemoteContainerIngestGeneration,\n): boolean {\n return remoteContainerIngestGenerationsMatch(\n remoteContainerIngestGeneration(state),\n generation,\n );\n}\n\nfunction settleStaleRemoteContainerIngestGeneration(input: {\n generation: RemoteContainerIngestGeneration;\n generationByContainerId: RemoteContainerIngestGenerationMap;\n queue: RemoteContainerIngestQueue;\n state: RemoteContainerHydrationState;\n}): void {\n const currentGeneration = remoteContainerIngestGeneration(input.state);\n const shouldReplay =\n currentGeneration.lifecycle !== input.generation.lifecycle &&\n currentGeneration.structural === input.generation.structural;\n for (const [containerId, generation] of input.generationByContainerId) {\n if (!remoteContainerIngestGenerationsMatch(generation, input.generation)) {\n continue;\n }\n if (shouldReplay) {\n input.generationByContainerId.set(containerId, currentGeneration);\n } else {\n input.generationByContainerId.delete(containerId);\n input.queue.delete(containerId);\n }\n }\n}\n\ninterface RemoteContainerIngestor {\n (remoteContainer: RemoteContainer): Promise<void>;\n hasPending: () => boolean;\n resume: () => Promise<void>;\n}\n\nexport function createRemoteContainerIngestor(input: {\n getSerializationBarrier?: (() => Promise<void> | null) | undefined;\n host: RemoteContainerHydrationHost;\n state: RemoteContainerHydrationState;\n}): RemoteContainerIngestor {\n const { host, state } = input;\n const pendingRemoteContainersById: RemoteContainerIngestQueue = new Map();\n const generationByContainerId: RemoteContainerIngestGenerationMap = new Map();\n let ingestRemoteContainersPromise: Promise<void> | null = null;\n\n const runNextGeneration = (): Promise<void> => {\n if (ingestRemoteContainersPromise) {\n return ingestRemoteContainersPromise.then(\n runNextGeneration,\n runNextGeneration,\n );\n }\n if (\n state.runtime.infra.dbStatus !== undefined &&\n state.runtime.infra.dbStatus !== \"ready\"\n ) {\n return Promise.resolve();\n }\n const serializationBarrier = input.getSerializationBarrier?.();\n if (serializationBarrier) {\n return serializationBarrier.then(runNextGeneration);\n }\n const nextContainerId = pendingRemoteContainersById.keys().next().value;\n if (typeof nextContainerId !== \"string\") {\n return Promise.resolve();\n }\n const generation = generationByContainerId.get(nextContainerId);\n if (!generation) {\n pendingRemoteContainersById.delete(nextContainerId);\n return runNextGeneration();\n }\n const isCurrent = () =>\n isRemoteContainerIngestGenerationCurrent(state, generation);\n const guardedHost = createGenerationGuardedHydrationHost({\n host,\n isCurrent,\n });\n const nextPromise = Promise.resolve()\n .then(() =>\n drainRemoteContainerIngestQueue({\n generation,\n generationByContainerId,\n host: guardedHost,\n isCurrent,\n queue: pendingRemoteContainersById,\n state,\n }),\n )\n .then(() => {\n if (!isCurrent()) {\n settleStaleRemoteContainerIngestGeneration({\n generation,\n generationByContainerId,\n queue: pendingRemoteContainersById,\n state,\n });\n }\n })\n .catch((error: unknown) => {\n if (!isCurrent() || error instanceof StaleRemoteHydrationError) {\n settleStaleRemoteContainerIngestGeneration({\n generation,\n generationByContainerId,\n queue: pendingRemoteContainersById,\n state,\n });\n return;\n }\n throw error;\n })\n .finally(() => {\n if (ingestRemoteContainersPromise === nextPromise) {\n ingestRemoteContainersPromise = null;\n }\n });\n ingestRemoteContainersPromise = nextPromise;\n return nextPromise.then(() =>\n pendingRemoteContainersById.size > 0 ? runNextGeneration() : undefined,\n );\n };\n\n const ingestRemoteContainer = (remoteContainer: RemoteContainer) => {\n pendingRemoteContainersById.set(remoteContainer.id, remoteContainer);\n generationByContainerId.set(\n remoteContainer.id,\n remoteContainerIngestGeneration(state),\n );\n return runNextGeneration();\n };\n ingestRemoteContainer.hasPending = () => pendingRemoteContainersById.size > 0;\n ingestRemoteContainer.resume = runNextGeneration;\n return ingestRemoteContainer;\n}\n\nexport async function hydrateRemoteContainers(input: {\n followDiscoveredParentLanes?: boolean | undefined;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n onFullyHydrated?: (() => Promise<void> | void) | undefined;\n parentIds?: ReadonlyArray<string | null> | undefined;\n resetAllLaneWatermarks?: boolean | undefined;\n resetRootLaneWatermark?: boolean | undefined;\n state: RemoteContainerHydrationState;\n}): Promise<number> {\n const { host, state } = input;\n if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {\n return 0;\n }\n\n const seenContainerIds = new Set<string>();\n const containerIdsBeforeHydration = new Set(state.containersById.keys());\n const childIdsByParentId = createContainerChildIndex(state.containersById);\n const { lanes, queueParentLane } = createContainerParentHydrationQueue({\n containerIds: state.containersById.keys(),\n parentIds: input.parentIds,\n resetAllLaneWatermarks: input.resetAllLaneWatermarks,\n resetRootLaneWatermark: input.resetRootLaneWatermark,\n });\n // Follow child lanes during an explicit recursive crawl or for containers first\n // discovered in this pass. The latter lets a newly authorized root populate its\n // descendants immediately, while routine ticks keep known subtrees cache-first.\n const queueDiscoveredParentLane: QueueContainerParentLane = (containerId) => {\n if (\n input.followDiscoveredParentLanes ||\n (containerId !== null && !containerIdsBeforeHydration.has(containerId))\n ) {\n queueParentLane(containerId);\n }\n };\n const result = await hydrateContainerParentLanes({\n childIdsByParentId,\n host,\n isCurrent: input.isCurrent,\n lanes,\n queueParentLane: queueDiscoveredParentLane,\n seenContainerIds,\n state,\n });\n const { changedCount } = result;\n await finishRemoteHydration({\n changedCount,\n complete:\n result.complete &&\n canHydrateRemoteContainers(state) &&\n input.isCurrent?.() !== false,\n containerIdsBeforeHydration,\n host,\n isCurrent: input.isCurrent,\n onFullyHydrated: input.onFullyHydrated,\n seenContainerIds,\n state,\n });\n return changedCount;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,mCAAmC,EAAE,MAAM,yBAAyB,CAAC;AAC9E,OAAO,EAAE,qCAAqC,EAAE,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,yBAAyB,EAAE,MAAM,gDAAgD,CAAC;AAC3F,OAAO,EACL,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EACL,gDAAgD,EAChD,kDAAkD,EAClD,kCAAkC,GACnC,MAAM,yCAAyC,CAAC;AAgBjD,MAAM,OAAO,yBAA0B,SAAQ,KAAK;CAAG;AAEvD,MAAM,UAAU,oCAAoC,CAAC,KAGpD;IACC,MAAM,aAAa,GAAG,GAAG,EAAE;QACzB,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;YACvB,MAAM,IAAI,yBAAyB,EAAE,CAAC;QACxC,CAAC;IACH,CAAC,CAAC;IAEF,OAAO;QACL,qBAAqB,EAAE,KAAK,EAC1B,cAAc,EACd,KAAK,EACL,UAAU,EACV,WAAW,EACX,eAAe,EACf,EAAE;YACF,MAAM,eAAe,GAAG,eAAe,EAAE,SAAS,CAAC;YACnD,MAAM,SAAS,GAAG,eAAe;gBAC/B,CAAC,CAAC,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ACF,MAAM,MAAM,GAAG,MAAM,2BAA2B,CAAC;QAC/C,kBAAkB;QAClB,IAAI;QACJ,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,KAAK;QACL,eAAe,EAAE,yBAAyB;QAC1C,gBAAgB;QAChB,KAAK;KACN,CAAC,CAAC;IACH,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,CAAC;IAChC,MAAM,qBAAqB,CAAC;QAC1B,YAAY;QACZ,QAAQ,EACN,MAAM,CAAC,QAAQ;YACf,0BAA0B,CAAC,KAAK,CAAC;YACjC,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;QAC/B,2BAA2B;QAC3B,IAAI;QACJ,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB;QAChB,KAAK;KACN,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import { finishRemoteHydration } from \"./completeHydration\";\nimport { createContainerChildIndex } from \"./lanes/childIndex\";\nimport { createContainerParentHydrationQueue } from \"./lanes/parentLaneQueue\";\nimport { cacheRemoteContainerPrincipalPolicies } from \"./principalPolicyCache\";\nimport { loadPausedContainerFilter } from \"./remoteContainers/organizationSyncPauseFilter\";\nimport {\n canHydrateRemoteContainers,\n hydrateContainerParentLanes,\n} from \"./remoteContainers/remoteContainerPageHydration\";\nimport {\n listRemoteContainerIdsWithPendingMetadataUpdates,\n listRemoteContainerIdsWithPendingStructuralIntents,\n upsertIsolatedRemoteContainerState,\n} from \"./remoteContainers/remoteContainerState\";\nimport type {\n QueueContainerParentLane,\n RemoteContainer,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n RemoteContainerIngestQueue,\n} from \"./types\";\n\nexport type {\n ContainerState,\n PersistContainerStateResult,\n RemoteContainer,\n RemoteContainerHydrationHost,\n} from \"./types\";\n\nexport class StaleRemoteHydrationError extends Error {}\n\nexport function createGenerationGuardedHydrationHost(input: {\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n}): RemoteContainerHydrationHost {\n const assertCurrent = () => {\n if (!input.isCurrent()) {\n throw new StaleRemoteHydrationError();\n }\n };\n\n return {\n persistContainerState: async (\n containerState,\n patch,\n updateView,\n saveOptions,\n mutationOptions,\n ) => {\n const callerIsCurrent = mutationOptions?.isCurrent;\n const isCurrent = callerIsCurrent\n ? () => input.isCurrent() && callerIsCurrent()\n : input.isCurrent;\n assertCurrent();\n const record = await input.host.persistContainerState(\n containerState,\n patch,\n updateView,\n saveOptions,\n { ...mutationOptions, isCurrent },\n );\n assertCurrent();\n return record;\n },\n ...(input.host.requestDocumentPriming\n ? {\n requestDocumentPriming: () => {\n if (input.isCurrent()) {\n input.host.requestDocumentPriming?.();\n }\n },\n }\n : {}),\n ...(input.host.requestMetadataRevalidation\n ? {\n requestMetadataRevalidation: async (request) => {\n assertCurrent();\n await input.host.requestMetadataRevalidation?.(request);\n assertCurrent();\n },\n }\n : {}),\n updateSnapshot: () => {\n if (input.isCurrent()) {\n input.host.updateSnapshot();\n }\n },\n };\n}\n\ninterface RemoteContainerIngestGeneration {\n readonly lifecycle: number | undefined;\n readonly structural: number | undefined;\n}\ntype RemoteContainerIngestGenerationMap = Map<\n string,\n RemoteContainerIngestGeneration\n>;\n\nfunction remoteContainerIngestGeneration(\n state: RemoteContainerHydrationState,\n): RemoteContainerIngestGeneration {\n return {\n lifecycle: state.lifecycleGeneration,\n structural: state.structuralGeneration,\n };\n}\n\nfunction remoteContainerIngestGenerationsMatch(\n left: RemoteContainerIngestGeneration | undefined,\n right: RemoteContainerIngestGeneration,\n): boolean {\n return (\n left !== undefined &&\n left.lifecycle === right.lifecycle &&\n left.structural === right.structural\n );\n}\n\nfunction isCurrentQueuedRemoteContainer(\n generation: RemoteContainerIngestGeneration,\n generationByContainerId: RemoteContainerIngestGenerationMap,\n queue: RemoteContainerIngestQueue,\n remoteContainer: RemoteContainer,\n): boolean {\n return (\n queue.get(remoteContainer.id) === remoteContainer &&\n remoteContainerIngestGenerationsMatch(\n generationByContainerId.get(remoteContainer.id),\n generation,\n )\n );\n}\n\nasync function upsertQueuedRemoteContainer(input: {\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n generation: RemoteContainerIngestGeneration;\n generationByContainerId: RemoteContainerIngestGenerationMap;\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n queue: RemoteContainerIngestQueue;\n queuedRemoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): Promise<boolean> {\n const {\n containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents,\n generation,\n generationByContainerId,\n host,\n queue,\n queuedRemoteContainer,\n state,\n } = input;\n if (\n !input.isCurrent() ||\n !isCurrentQueuedRemoteContainer(\n generation,\n generationByContainerId,\n queue,\n queuedRemoteContainer,\n )\n ) {\n return false;\n }\n\n // A paused organization's container is acknowledged without being applied,\n // including when the pause lands while the commit is in flight.\n const isPaused = await loadPausedContainerFilter(state);\n if (isPaused(queuedRemoteContainer)) return true;\n const tombstones = await state.persistence.loadContainerHydrationTombstones(\n state.runtime.infra.execSql,\n );\n // A refused folder is reported and acknowledged; the batch continues.\n const upserted = await upsertIsolatedRemoteContainerState({\n expectedHydrationTombstone:\n tombstones.find((row) => row.containerId === queuedRemoteContainer.id) ??\n null,\n containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents,\n host,\n isCurrent: () => input.isCurrent() && !isPaused(queuedRemoteContainer),\n remoteContainer: queuedRemoteContainer,\n state,\n });\n if (!upserted) {\n return false;\n }\n return true;\n}\n\nfunction acknowledgeRemoteContainerIngestBatch(input: {\n generation: RemoteContainerIngestGeneration;\n generationByContainerId: RemoteContainerIngestGenerationMap;\n isCurrent: () => boolean;\n queue: RemoteContainerIngestQueue;\n queuedRemoteContainers: ReadonlyArray<RemoteContainer>;\n}): void {\n if (!input.isCurrent()) {\n return;\n }\n for (const queuedRemoteContainer of input.queuedRemoteContainers) {\n if (\n isCurrentQueuedRemoteContainer(\n input.generation,\n input.generationByContainerId,\n input.queue,\n queuedRemoteContainer,\n )\n ) {\n input.queue.delete(queuedRemoteContainer.id);\n input.generationByContainerId.delete(queuedRemoteContainer.id);\n }\n }\n}\n\nasync function drainRemoteContainerIngestQueue(input: {\n generation: RemoteContainerIngestGeneration;\n generationByContainerId: RemoteContainerIngestGenerationMap;\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n queue: RemoteContainerIngestQueue;\n state: RemoteContainerHydrationState;\n}) {\n const { generation, generationByContainerId, host, queue, state } = input;\n let shouldUpdateSnapshot = false;\n\n try {\n while (input.isCurrent()) {\n const queuedRemoteContainers = Array.from(queue.values()).filter(\n (remoteContainer) =>\n remoteContainerIngestGenerationsMatch(\n generationByContainerId.get(remoteContainer.id),\n generation,\n ),\n );\n if (queuedRemoteContainers.length === 0) {\n return;\n }\n await cacheRemoteContainerPrincipalPolicies({\n cacheReferencedPrincipalPolicies:\n state.runtime.principalPolicies.createWarmer(),\n remoteContainers: queuedRemoteContainers,\n stillCurrent: input.isCurrent,\n });\n if (!input.isCurrent()) {\n return;\n }\n const [\n containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents,\n ] = await Promise.all([\n listRemoteContainerIdsWithPendingMetadataUpdates({\n remoteContainers: queuedRemoteContainers,\n state,\n }),\n listRemoteContainerIdsWithPendingStructuralIntents({\n remoteContainers: queuedRemoteContainers,\n state,\n }),\n ]);\n if (!input.isCurrent()) {\n return;\n }\n\n for (const queuedRemoteContainer of queuedRemoteContainers) {\n shouldUpdateSnapshot =\n (await upsertQueuedRemoteContainer({\n containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents,\n generation,\n generationByContainerId,\n host,\n isCurrent: input.isCurrent,\n queue,\n queuedRemoteContainer,\n state,\n })) || shouldUpdateSnapshot;\n }\n acknowledgeRemoteContainerIngestBatch({\n generation,\n generationByContainerId,\n isCurrent: input.isCurrent,\n queue,\n queuedRemoteContainers,\n });\n\n if (shouldUpdateSnapshot) {\n host.updateSnapshot();\n shouldUpdateSnapshot = false;\n }\n }\n } catch (error) {\n if (shouldUpdateSnapshot) {\n host.updateSnapshot();\n }\n throw error;\n }\n}\n\nfunction isRemoteContainerIngestGenerationCurrent(\n state: RemoteContainerHydrationState,\n generation: RemoteContainerIngestGeneration,\n): boolean {\n return remoteContainerIngestGenerationsMatch(\n remoteContainerIngestGeneration(state),\n generation,\n );\n}\n\nfunction settleStaleRemoteContainerIngestGeneration(input: {\n generation: RemoteContainerIngestGeneration;\n generationByContainerId: RemoteContainerIngestGenerationMap;\n queue: RemoteContainerIngestQueue;\n state: RemoteContainerHydrationState;\n}): void {\n const currentGeneration = remoteContainerIngestGeneration(input.state);\n const shouldReplay =\n currentGeneration.lifecycle !== input.generation.lifecycle &&\n currentGeneration.structural === input.generation.structural;\n for (const [containerId, generation] of input.generationByContainerId) {\n if (!remoteContainerIngestGenerationsMatch(generation, input.generation)) {\n continue;\n }\n if (shouldReplay) {\n input.generationByContainerId.set(containerId, currentGeneration);\n } else {\n input.generationByContainerId.delete(containerId);\n input.queue.delete(containerId);\n }\n }\n}\n\ninterface RemoteContainerIngestor {\n (remoteContainer: RemoteContainer): Promise<void>;\n hasPending: () => boolean;\n resume: () => Promise<void>;\n}\n\nexport function createRemoteContainerIngestor(input: {\n getSerializationBarrier?: (() => Promise<void> | null) | undefined;\n host: RemoteContainerHydrationHost;\n state: RemoteContainerHydrationState;\n}): RemoteContainerIngestor {\n const { host, state } = input;\n const pendingRemoteContainersById: RemoteContainerIngestQueue = new Map();\n const generationByContainerId: RemoteContainerIngestGenerationMap = new Map();\n let ingestRemoteContainersPromise: Promise<void> | null = null;\n\n const runNextGeneration = (): Promise<void> => {\n if (ingestRemoteContainersPromise) {\n return ingestRemoteContainersPromise.then(\n runNextGeneration,\n runNextGeneration,\n );\n }\n if (\n state.runtime.infra.dbStatus !== undefined &&\n state.runtime.infra.dbStatus !== \"ready\"\n ) {\n return Promise.resolve();\n }\n const serializationBarrier = input.getSerializationBarrier?.();\n if (serializationBarrier) {\n return serializationBarrier.then(runNextGeneration);\n }\n const nextContainerId = pendingRemoteContainersById.keys().next().value;\n if (typeof nextContainerId !== \"string\") {\n return Promise.resolve();\n }\n const generation = generationByContainerId.get(nextContainerId);\n if (!generation) {\n pendingRemoteContainersById.delete(nextContainerId);\n return runNextGeneration();\n }\n const isCurrent = () =>\n isRemoteContainerIngestGenerationCurrent(state, generation);\n const guardedHost = createGenerationGuardedHydrationHost({\n host,\n isCurrent,\n });\n const nextPromise = Promise.resolve()\n .then(() =>\n drainRemoteContainerIngestQueue({\n generation,\n generationByContainerId,\n host: guardedHost,\n isCurrent,\n queue: pendingRemoteContainersById,\n state,\n }),\n )\n .then(() => {\n if (!isCurrent()) {\n settleStaleRemoteContainerIngestGeneration({\n generation,\n generationByContainerId,\n queue: pendingRemoteContainersById,\n state,\n });\n }\n })\n .catch((error: unknown) => {\n if (!isCurrent() || error instanceof StaleRemoteHydrationError) {\n settleStaleRemoteContainerIngestGeneration({\n generation,\n generationByContainerId,\n queue: pendingRemoteContainersById,\n state,\n });\n return;\n }\n throw error;\n })\n .finally(() => {\n if (ingestRemoteContainersPromise === nextPromise) {\n ingestRemoteContainersPromise = null;\n }\n });\n ingestRemoteContainersPromise = nextPromise;\n return nextPromise.then(() =>\n pendingRemoteContainersById.size > 0 ? runNextGeneration() : undefined,\n );\n };\n\n const ingestRemoteContainer = (remoteContainer: RemoteContainer) => {\n pendingRemoteContainersById.set(remoteContainer.id, remoteContainer);\n generationByContainerId.set(\n remoteContainer.id,\n remoteContainerIngestGeneration(state),\n );\n return runNextGeneration();\n };\n ingestRemoteContainer.hasPending = () => pendingRemoteContainersById.size > 0;\n ingestRemoteContainer.resume = runNextGeneration;\n return ingestRemoteContainer;\n}\n\nexport async function hydrateRemoteContainers(input: {\n followDiscoveredParentLanes?: boolean | undefined;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n onFullyHydrated?: (() => Promise<void> | void) | undefined;\n parentIds?: ReadonlyArray<string | null> | undefined;\n resetAllLaneWatermarks?: boolean | undefined;\n resetRootLaneWatermark?: boolean | undefined;\n state: RemoteContainerHydrationState;\n}): Promise<number> {\n const { host, state } = input;\n if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {\n return 0;\n }\n\n const seenContainerIds = new Set<string>();\n const containerIdsBeforeHydration = new Set(state.containersById.keys());\n const childIdsByParentId = createContainerChildIndex(state.containersById);\n const { lanes, queueParentLane } = createContainerParentHydrationQueue({\n containerIds: state.containersById.keys(),\n parentIds: input.parentIds,\n resetAllLaneWatermarks: input.resetAllLaneWatermarks,\n resetRootLaneWatermark: input.resetRootLaneWatermark,\n });\n // Follow child lanes during an explicit recursive crawl or for containers first\n // discovered in this pass. The latter lets a newly authorized root populate its\n // descendants immediately, while routine ticks keep known subtrees cache-first.\n const queueDiscoveredParentLane: QueueContainerParentLane = (containerId) => {\n if (\n input.followDiscoveredParentLanes ||\n (containerId !== null && !containerIdsBeforeHydration.has(containerId))\n ) {\n queueParentLane(containerId);\n }\n };\n const result = await hydrateContainerParentLanes({\n childIdsByParentId,\n host,\n isCurrent: input.isCurrent,\n lanes,\n queueParentLane: queueDiscoveredParentLane,\n seenContainerIds,\n state,\n });\n const { changedCount } = result;\n await finishRemoteHydration({\n changedCount,\n complete:\n result.complete &&\n canHydrateRemoteContainers(state) &&\n input.isCurrent?.() !== false,\n containerIdsBeforeHydration,\n host,\n isCurrent: input.isCurrent,\n onFullyHydrated: input.onFullyHydrated,\n seenContainerIds,\n state,\n });\n return changedCount;\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { decodeVersionVector, encodeVersionVector, satisfiesVersionVector, } from "../../../../internal/loro/index.js";
1
2
  import { isProjectionVerificationCancelledError } from "../../../../data/keyingProjectionVerification/types.js";
2
3
  import { heldContainerBinding, listingRepeatsHeldOrdinaryBinding, } from "../../../../data/persistence/container-contents/containerBinding.js";
3
4
  import { isKeyingVerificationError, runWithSecurityIncidentReporting, } from "../../../../data/shared/securityIncidents.js";
@@ -94,6 +95,35 @@ function installUpdatedRemoteContainerState(existingState, nextState, host) {
94
95
  if (wasLocalOnly && existingState.container.serverCreatedAt != null)
95
96
  host.requestDocumentPriming?.();
96
97
  }
98
+ /**
99
+ * A clean metadata document is read only when a hint names it, and a hint sent
100
+ * while this client was offline or not yet subscribed is lost. The listing
101
+ * reports the version vector of every update the server holds for the metadata
102
+ * document; when this client's copy does not cover it, an edit is unread. Owe
103
+ * the read before this hydration advances the lane watermark past the row.
104
+ */
105
+ function coversMetadataVersion(existingState, remoteContainer) {
106
+ const listed = remoteContainer.metadataVersionVector;
107
+ try {
108
+ // A document with no stored update is covered by any copy.
109
+ if (decodeVersionVector(listed).toJSON().size === 0)
110
+ return true;
111
+ return satisfiesVersionVector(encodeVersionVector(existingState.doc), listed);
112
+ }
113
+ catch {
114
+ // An unreadable version proves nothing: owe the read, which pulls the
115
+ // truth, and let the rest of the page hydrate.
116
+ return false;
117
+ }
118
+ }
119
+ async function oweMetadataReadIfBehind(host, existingState, remoteContainer) {
120
+ if (!coversMetadataVersion(existingState, remoteContainer)) {
121
+ await host.requestMetadataRevalidation?.({
122
+ advertisedVersionVector: remoteContainer.metadataVersionVector,
123
+ documentId: remoteContainer.metadataDocumentId,
124
+ });
125
+ }
126
+ }
97
127
  async function updateExistingRemoteContainerState(input) {
98
128
  const { childIdsByParentId, existingState, host, remoteContainer, state } = input;
99
129
  const previousParentId = existingState.container.parentId;
@@ -112,6 +142,7 @@ async function updateExistingRemoteContainerState(input) {
112
142
  previousLocalUpdatedAt,
113
143
  remoteContainer,
114
144
  });
145
+ await oweMetadataReadIfBehind(host, existingState, remoteContainer);
115
146
  const nextState = createUpdatedRemoteContainerState(existingState, remoteContainer);
116
147
  const persistenceResult = await host.persistContainerState(nextState, {
117
148
  accessEpoch: remoteContainer.metadataAccessEpoch,
@@ -1 +1 @@
1
- {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jD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IACE,CAAC,yBAAyB,CAAC,KAAK,CAAC;YACjC,CAAC,sCAAsC,CAAC,KAAK,CAAC;YAE9C,MAAM,KAAK,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,8BAA8B,CACrC,KAGC;IAED,MAAM,EAAE,aAAa,EAAE,2BAA2B,EAAE,GAAG,KAAK,CAAC;IAC7D,OAAO,aAAa;QAClB,CAAC,CAAC,kCAAkC,CAAC;YACjC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,sCAAsC,EACpC,KAAK,CAAC,sCAAsC;YAC9C,wCAAwC,EACtC,KAAK,CAAC,wCAAwC;YAChD,aAAa;YACb,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,KAAK,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC;QACJ,CAAC,CAAC,0BAA0B,CAAC;YACzB,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,0BAA0B,EAAE,KAAK,CAAC,0BAA0B,IAAI,IAAI;YACpE,2BAA2B;YAC3B,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,KAAK,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC,CAAC;AACT,CAAC","sourcesContent":["import type { AccessManifestCheckpoint } from \"@tearleads/crypto\";\nimport { isProjectionVerificationCancelledError } from \"../../../../data/keyingProjectionVerification/types\";\nimport {\n heldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../../data/persistence/container-contents/containerBinding\";\nimport {\n isKeyingVerificationError,\n runWithSecurityIncidentReporting,\n} from \"../../../../data/shared/securityIncidents\";\nimport { invalidateContainerProjectionCaches } from \"../../container-state/projectionCache\";\nimport type { ContainerHydrationTombstone } from \"../../containerPersistence\";\nimport { installContainerMetadataRecord } from \"../../metadata/metadataPersistence\";\nimport { projectionGeneration } from \"../../projectionGeneration\";\nimport type { PrefetchedDestinationProjection } from \"../destination/destinationPrefetch\";\nimport { verifyRemoteContainerDestination } from \"../destination/verifiedDestination\";\nimport { rebindReHomedContainer } from \"../heldContainerRebind\";\nimport {\n moveIndexedContainerChild,\n removeIndexedContainerChild,\n} from \"../lanes/childIndex\";\nimport {\n reconcileLocalOnlyRootContainers,\n reconcileLocalOnlySystemContainers,\n} from \"../reconciliation\";\nimport type {\n ContainerChildIndex,\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n} from \"../types\";\nimport { insertRemoteContainerState } from \"./insertRemoteContainer\";\nimport {\n applyRemoteContainerTimestamps,\n remoteContainerHydrationSaveOptions,\n resolveRemoteContainerHydrationLocalUpdatedAt,\n} from \"./remoteContainerTimestamps\";\n\n// Container ids (restricted to the inbound page) that carry an unsynced local\n// create or move intent. Such a container's parent and local-edit timestamp are\n// owned by its structural-intent lane until that lane reconciles, so inbound\n// hydration must not revert parentId to the server value nor collapse\n// localUpdatedAt — doing so silently undoes a queued move and falsely reads\n// \"synced\". Move intents are read via listUnsyncedMoveIntents so a blocked\n// move — one whose destination parent has not synced yet, the common boot-time\n// case — is protected too. Pending *metadata*\n// updates are handled separately (listRemoteContainerIdsWithPendingMetadataUpdates);\n// structural intents live in the local outbox's container lanes, which that\n// query does not cover.\nexport async function listRemoteContainerIdsWithPendingStructuralIntents(input: {\n remoteContainers: ReadonlyArray<RemoteContainer>;\n state: RemoteContainerHydrationState;\n}): Promise<Set<string>> {\n if (input.remoteContainers.length === 0) {\n return new Set();\n }\n const remoteContainerIds = new Set(\n input.remoteContainers.map((remoteContainer) => remoteContainer.id),\n );\n\n const execSql = input.state.runtime.infra.execSql;\n const [pendingCreateIntents, unsyncedMoveIntents] = await Promise.all([\n input.state.persistence.listPendingCreateIntents(execSql),\n input.state.persistence.listUnsyncedMoveIntents(execSql),\n ]);\n const containerIdsWithPendingStructuralIntents = new Set<string>();\n for (const intent of pendingCreateIntents) {\n if (remoteContainerIds.has(intent.containerId)) {\n containerIdsWithPendingStructuralIntents.add(intent.containerId);\n }\n }\n for (const intent of unsyncedMoveIntents) {\n if (remoteContainerIds.has(intent.containerId)) {\n containerIdsWithPendingStructuralIntents.add(intent.containerId);\n }\n }\n return containerIdsWithPendingStructuralIntents;\n}\n\nexport async function listRemoteContainerIdsWithPendingMetadataUpdates(input: {\n remoteContainers: ReadonlyArray<RemoteContainer>;\n state: RemoteContainerHydrationState;\n}): Promise<Set<string>> {\n const containerIds = input.remoteContainers.flatMap((remoteContainer) => {\n const previousLocalUpdatedAt = input.state.containersById.get(\n remoteContainer.id,\n )?.container.localUpdatedAt;\n\n return previousLocalUpdatedAt &&\n previousLocalUpdatedAt.localeCompare(remoteContainer.updatedAt) > 0\n ? [remoteContainer.id]\n : [];\n });\n if (containerIds.length === 0) {\n return new Set();\n }\n\n const execSql = input.state.runtime.infra.execSql;\n return new Set(\n await input.state.persistence.listContainerIdsWithPendingUpdates(\n execSql,\n containerIds,\n ),\n );\n}\n\nfunction removeMissingHydratedContainer(input: {\n childIdsByParentId?: ContainerChildIndex | undefined;\n existingState: ContainerState;\n host: RemoteContainerHydrationHost;\n previousParentId: string | null;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): void {\n const { existingState, remoteContainer, state } = input;\n if (state.containersById.get(remoteContainer.id) !== existingState) {\n return;\n }\n\n state.containersById.delete(remoteContainer.id);\n if (input.childIdsByParentId) {\n removeIndexedContainerChild(\n input.childIdsByParentId,\n remoteContainer.id,\n input.previousParentId,\n );\n input.childIdsByParentId.delete(remoteContainer.id);\n }\n input.host.updateSnapshot();\n}\n\nfunction createUpdatedRemoteContainerState(\n existingState: ContainerState,\n remoteContainer: RemoteContainer,\n): ContainerState {\n return {\n ...existingState,\n container: applyRemoteContainerTimestamps(\n existingState.container,\n remoteContainer,\n ),\n containerWriterProjection: null,\n metadataReferencedPrincipals: remoteContainer.metadataReferencedPrincipals,\n };\n}\n\nfunction installUpdatedRemoteContainerState(\n existingState: ContainerState,\n nextState: ContainerState,\n host: RemoteContainerHydrationHost,\n): void {\n const wasLocalOnly = existingState.container.serverCreatedAt == null;\n existingState.container = nextState.container;\n existingState.containerWriterProjection = nextState.containerWriterProjection;\n existingState.metadataReferencedPrincipals =\n nextState.metadataReferencedPrincipals;\n // The snapshot copied the live generation when it was taken; a hint that\n // landed during the persist leaves the live metadata projection dropped.\n if (projectionGeneration(existingState) === projectionGeneration(nextState))\n existingState.metadataWriterProjection = nextState.metadataWriterProjection;\n installContainerMetadataRecord(existingState, nextState.record);\n // A document pass may have deferred while this root was awaiting proof.\n // The first durable remote acknowledgement makes its pending creates runnable.\n if (wasLocalOnly && existingState.container.serverCreatedAt != null)\n host.requestDocumentPriming?.();\n}\n\nasync function updateExistingRemoteContainerState(input: {\n childIdsByParentId?: ContainerChildIndex | undefined;\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n existingState: ContainerState;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): Promise<ContainerState | null> {\n const { childIdsByParentId, existingState, host, remoteContainer, state } =\n input;\n const previousParentId = existingState.container.parentId;\n const previousLocalUpdatedAt = existingState.container.localUpdatedAt;\n // A queued, not-yet-synced local move/create owns this container's parent\n // until its intent lane reconciles. Omit the remote parent when the page scan\n // saw one; persistence also rechecks the intent transactionally so a move\n // created after that scan wins. Both paths preserve the durable local clock.\n const hasPendingStructuralIntent =\n input.containerIdsWithPendingStructuralIntents.has(remoteContainer.id);\n const nextParentId = hasPendingStructuralIntent\n ? undefined\n : remoteContainer.parentId;\n const localUpdatedAt = resolveRemoteContainerHydrationLocalUpdatedAt({\n containerIdsWithPendingMetadataUpdates:\n input.containerIdsWithPendingMetadataUpdates,\n hasPendingStructuralIntent,\n previousLocalUpdatedAt,\n remoteContainer,\n });\n const nextState = createUpdatedRemoteContainerState(\n existingState,\n remoteContainer,\n );\n const persistenceResult = await host.persistContainerState(\n nextState,\n {\n accessEpoch: remoteContainer.metadataAccessEpoch,\n accessStateHash: remoteContainer.metadataAccessStateHash,\n documentId: remoteContainer.metadataDocumentId,\n effectiveAccessLevel: remoteContainer.effectiveAccessLevel,\n metadataDocumentId: remoteContainer.metadataDocumentId,\n systemSlot: remoteContainer.systemSlot ?? null,\n organizationId: remoteContainer.organizationId,\n ...(nextParentId !== undefined ? { parentId: nextParentId } : {}),\n },\n false,\n remoteContainerHydrationSaveOptions({\n localUpdatedAt,\n remoteContainer,\n }),\n {\n preserveDurableStructureWhenPending: true,\n },\n );\n if (persistenceResult.status === \"missing\") {\n // Hydration persists a detached candidate so an in-flight response cannot\n // mutate mapped state before its guards settle. Retire the exact state this\n // hydration read because store-level reference cleanup cannot see the clone.\n removeMissingHydratedContainer({\n childIdsByParentId,\n existingState,\n host,\n previousParentId,\n remoteContainer,\n state,\n });\n return null;\n }\n if (persistenceResult.status !== \"persisted\") return null;\n const { record: nextRecord } = persistenceResult;\n installContainerMetadataRecord(nextState, nextRecord);\n if (input.isCurrent?.() === false) {\n return existingState;\n }\n nextState.container = {\n ...nextState.container,\n metadataDocumentId: remoteContainer.metadataDocumentId,\n organizationId: remoteContainer.organizationId,\n parentId: nextState.container.parentId,\n };\n\n installUpdatedRemoteContainerState(existingState, nextState, host);\n moveIndexedContainerChild(\n childIdsByParentId,\n remoteContainer.id,\n previousParentId,\n existingState.container.parentId,\n );\n await reconcileLocalOnlyRootContainers({\n childIdsByParentId,\n isCurrent: input.isCurrent,\n remoteRootState: existingState,\n requestDocumentPriming: host.requestDocumentPriming,\n state,\n });\n return existingState;\n}\n\ninterface UpsertRemoteContainerStateInput {\n childIdsByParentId?: ContainerChildIndex | undefined;\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n host: RemoteContainerHydrationHost;\n expectedHydrationTombstone?: ContainerHydrationTombstone | null | undefined;\n isCurrent?: (() => boolean) | undefined;\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}\n\n/** A pull can observe the same manifest change as a missed realtime hint. */\nfunction invalidateListedProjectionCaches(\n input: UpsertRemoteContainerStateInput,\n) {\n const held = input.state.containersById.get(input.remoteContainer.id);\n if (\n held &&\n (held.record.accessStateHash !==\n input.remoteContainer.metadataAccessStateHash ||\n (held.container.effectiveAccessLevel ?? \"read\") !==\n input.remoteContainer.effectiveAccessLevel)\n ) {\n // Eviction admits no remote state. Drop citations before verification can\n // advance local checkpoints past those cached container/document paths.\n invalidateContainerProjectionCaches(input.state, [\n input.remoteContainer.id,\n ]);\n }\n}\n\nexport async function upsertRemoteContainerState(\n input: UpsertRemoteContainerStateInput,\n): Promise<ContainerState | null> {\n let expectedPlacementCheckpoint: AccessManifestCheckpoint | undefined;\n const heldState = input.state.containersById.get(input.remoteContainer.id);\n const heldBinding = heldState\n ? heldContainerBinding(heldState)\n : await input.state.persistence.loadHeldContainerBinding(\n input.state.runtime.infra.execSql,\n input.remoteContainer.id,\n );\n const listed = input.remoteContainer;\n // A folder re-homed away from the listed organization never returns there,\n // whatever binding (possibly none, after a reset) the device holds now.\n const supersededListing =\n !listingRepeatsHeldOrdinaryBinding(heldBinding, listed) &&\n (await input.state.persistence.isSupersededContainerBinding(\n input.state.runtime.infra.execSql,\n { containerId: listed.id, organizationId: listed.organizationId },\n ));\n if (input.isCurrent?.() === false) return null;\n invalidateListedProjectionCaches(input);\n const verified = await verifyRemoteContainerDestination({\n ...input,\n heldBinding,\n supersededListing,\n refresh: !!input.expectedHydrationTombstone,\n onVerifiedCheckpoint: (checkpoint) => {\n expectedPlacementCheckpoint = checkpoint;\n },\n });\n if (!verified || input.isCurrent?.() === false) return null;\n input = { ...input, remoteContainer: verified };\n const existingState = input.state.containersById.get(\n input.remoteContainer.id,\n );\n const remoteState = await runWithSecurityIncidentReporting(\n input.state.runtime.util.reportSecurityIncident,\n {\n objectId: verified.id,\n objectKind: \"container\",\n operation: \"container.binding.persist\",\n organizationId: verified.organizationId,\n },\n async () =>\n (await rebindReHomedContainer({\n existingState,\n heldBinding,\n isCurrent: input.isCurrent,\n state: input.state,\n verified,\n }))\n ? persistVerifiedRemoteContainer({\n ...input,\n existingState,\n expectedPlacementCheckpoint,\n })\n : null,\n );\n if (!remoteState) {\n return null;\n }\n await reconcileLocalOnlySystemContainers({\n childIdsByParentId: input.childIdsByParentId,\n isCurrent: input.isCurrent,\n requestDocumentPriming: input.host.requestDocumentPriming,\n remoteSystemState: remoteState,\n state: input.state,\n });\n return remoteState;\n}\n\n/**\n * Upsert one listed folder, isolating a rejected proof or binding. The refusal\n * was already reported; returning no state leaves the item unapplied without\n * blocking independent folders.\n */\nexport async function upsertIsolatedRemoteContainerState(\n input: UpsertRemoteContainerStateInput,\n): Promise<ContainerState | null> {\n try {\n return await upsertRemoteContainerState(input);\n } catch (error) {\n if (\n !isKeyingVerificationError(error) &&\n !isProjectionVerificationCancelledError(error)\n )\n throw error;\n return null;\n }\n}\n\nfunction persistVerifiedRemoteContainer(\n input: UpsertRemoteContainerStateInput & {\n existingState: ContainerState | undefined;\n expectedPlacementCheckpoint: AccessManifestCheckpoint | undefined;\n },\n): Promise<ContainerState | null> {\n const { existingState, expectedPlacementCheckpoint } = input;\n return existingState\n ? updateExistingRemoteContainerState({\n childIdsByParentId: input.childIdsByParentId,\n containerIdsWithPendingMetadataUpdates:\n input.containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents:\n input.containerIdsWithPendingStructuralIntents,\n existingState,\n host: input.host,\n isCurrent: input.isCurrent,\n remoteContainer: input.remoteContainer,\n state: input.state,\n })\n : insertRemoteContainerState({\n childIdsByParentId: input.childIdsByParentId,\n host: input.host,\n expectedHydrationTombstone: input.expectedHydrationTombstone ?? null,\n expectedPlacementCheckpoint,\n isCurrent: input.isCurrent,\n remoteContainer: input.remoteContainer,\n state: input.state,\n });\n}\n"]}
1
+ {"version":3,"file":"remoteContainerState.js","sourceRoot":"","sources":["remoteContainerState.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,sCAAsC,EAAE,MAAM,qDAAqD,CAAC;AAC7G,OAAO,EACL,oBAAoB,EACpB,iCAAiC,GAClC,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EACL,yBAAyB,EACzB,gCAAgC,GACjC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAE5F,OAAO,EAAE,8BAA8B,EAAE,MAAM,oCAAoC,CAAC;AACpF,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAElE,OAAO,EAAE,gCAAgC,EAAE,MAAM,oCAAoC,CAAC;AACtF,OAAO,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,EACL,yBAAyB,EACzB,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,gCAAgC,EAChC,kCAAkC,GACnC,MAAM,mBAAmB,CAAC;AAQ3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AACrE,OAAO,EACL,8BAA8B,EAC9B,mCAAmC,EACnC,6CAA6C,GAC9C,MAAM,6BAA6B,CAAC;AAErC,8EAA8E;AAC9E,gFAAgF;AAChF,6EAA6E;AAC7E,sEAAsE;AACtE,4EAA4E;AAC5E,2EAA2E;AAC3E,+EAA+E;AAC/E,8CAA8C;AAC9C,qFAAqF;AACrF,4EAA4E;AAC5E,wBAAwB;AACxB,MAAM,CAAC,KAAK,UAAU,kDAAkD,CAAC,KAGxE;I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ED,SAAS,8BAA8B,CACrC,KAGC;IAED,MAAM,EAAE,aAAa,EAAE,2BAA2B,EAAE,GAAG,KAAK,CAAC;IAC7D,OAAO,aAAa;QAClB,CAAC,CAAC,kCAAkC,CAAC;YACjC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,sCAAsC,EACpC,KAAK,CAAC,sCAAsC;YAC9C,wCAAwC,EACtC,KAAK,CAAC,wCAAwC;YAChD,aAAa;YACb,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,KAAK,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC;QACJ,CAAC,CAAC,0BAA0B,CAAC;YACzB,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,0BAA0B,EAAE,KAAK,CAAC,0BAA0B,IAAI,IAAI;YACpE,2BAA2B;YAC3B,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,KAAK,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC,CAAC;AACT,CAAC","sourcesContent":["import type { AccessManifestCheckpoint } from \"@tearleads/crypto\";\nimport {\n decodeVersionVector,\n encodeVersionVector,\n satisfiesVersionVector,\n} from \"@tearleads/loro\";\nimport { isProjectionVerificationCancelledError } from \"../../../../data/keyingProjectionVerification/types\";\nimport {\n heldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../../data/persistence/container-contents/containerBinding\";\nimport {\n isKeyingVerificationError,\n runWithSecurityIncidentReporting,\n} from \"../../../../data/shared/securityIncidents\";\nimport { invalidateContainerProjectionCaches } from \"../../container-state/projectionCache\";\nimport type { ContainerHydrationTombstone } from \"../../containerPersistence\";\nimport { installContainerMetadataRecord } from \"../../metadata/metadataPersistence\";\nimport { projectionGeneration } from \"../../projectionGeneration\";\nimport type { PrefetchedDestinationProjection } from \"../destination/destinationPrefetch\";\nimport { verifyRemoteContainerDestination } from \"../destination/verifiedDestination\";\nimport { rebindReHomedContainer } from \"../heldContainerRebind\";\nimport {\n moveIndexedContainerChild,\n removeIndexedContainerChild,\n} from \"../lanes/childIndex\";\nimport {\n reconcileLocalOnlyRootContainers,\n reconcileLocalOnlySystemContainers,\n} from \"../reconciliation\";\nimport type {\n ContainerChildIndex,\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n} from \"../types\";\nimport { insertRemoteContainerState } from \"./insertRemoteContainer\";\nimport {\n applyRemoteContainerTimestamps,\n remoteContainerHydrationSaveOptions,\n resolveRemoteContainerHydrationLocalUpdatedAt,\n} from \"./remoteContainerTimestamps\";\n\n// Container ids (restricted to the inbound page) that carry an unsynced local\n// create or move intent. Such a container's parent and local-edit timestamp are\n// owned by its structural-intent lane until that lane reconciles, so inbound\n// hydration must not revert parentId to the server value nor collapse\n// localUpdatedAt — doing so silently undoes a queued move and falsely reads\n// \"synced\". Move intents are read via listUnsyncedMoveIntents so a blocked\n// move — one whose destination parent has not synced yet, the common boot-time\n// case — is protected too. Pending *metadata*\n// updates are handled separately (listRemoteContainerIdsWithPendingMetadataUpdates);\n// structural intents live in the local outbox's container lanes, which that\n// query does not cover.\nexport async function listRemoteContainerIdsWithPendingStructuralIntents(input: {\n remoteContainers: ReadonlyArray<RemoteContainer>;\n state: RemoteContainerHydrationState;\n}): Promise<Set<string>> {\n if (input.remoteContainers.length === 0) {\n return new Set();\n }\n const remoteContainerIds = new Set(\n input.remoteContainers.map((remoteContainer) => remoteContainer.id),\n );\n\n const execSql = input.state.runtime.infra.execSql;\n const [pendingCreateIntents, unsyncedMoveIntents] = await Promise.all([\n input.state.persistence.listPendingCreateIntents(execSql),\n input.state.persistence.listUnsyncedMoveIntents(execSql),\n ]);\n const containerIdsWithPendingStructuralIntents = new Set<string>();\n for (const intent of pendingCreateIntents) {\n if (remoteContainerIds.has(intent.containerId)) {\n containerIdsWithPendingStructuralIntents.add(intent.containerId);\n }\n }\n for (const intent of unsyncedMoveIntents) {\n if (remoteContainerIds.has(intent.containerId)) {\n containerIdsWithPendingStructuralIntents.add(intent.containerId);\n }\n }\n return containerIdsWithPendingStructuralIntents;\n}\n\nexport async function listRemoteContainerIdsWithPendingMetadataUpdates(input: {\n remoteContainers: ReadonlyArray<RemoteContainer>;\n state: RemoteContainerHydrationState;\n}): Promise<Set<string>> {\n const containerIds = input.remoteContainers.flatMap((remoteContainer) => {\n const previousLocalUpdatedAt = input.state.containersById.get(\n remoteContainer.id,\n )?.container.localUpdatedAt;\n\n return previousLocalUpdatedAt &&\n previousLocalUpdatedAt.localeCompare(remoteContainer.updatedAt) > 0\n ? [remoteContainer.id]\n : [];\n });\n if (containerIds.length === 0) {\n return new Set();\n }\n\n const execSql = input.state.runtime.infra.execSql;\n return new Set(\n await input.state.persistence.listContainerIdsWithPendingUpdates(\n execSql,\n containerIds,\n ),\n );\n}\n\nfunction removeMissingHydratedContainer(input: {\n childIdsByParentId?: ContainerChildIndex | undefined;\n existingState: ContainerState;\n host: RemoteContainerHydrationHost;\n previousParentId: string | null;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): void {\n const { existingState, remoteContainer, state } = input;\n if (state.containersById.get(remoteContainer.id) !== existingState) {\n return;\n }\n\n state.containersById.delete(remoteContainer.id);\n if (input.childIdsByParentId) {\n removeIndexedContainerChild(\n input.childIdsByParentId,\n remoteContainer.id,\n input.previousParentId,\n );\n input.childIdsByParentId.delete(remoteContainer.id);\n }\n input.host.updateSnapshot();\n}\n\nfunction createUpdatedRemoteContainerState(\n existingState: ContainerState,\n remoteContainer: RemoteContainer,\n): ContainerState {\n return {\n ...existingState,\n container: applyRemoteContainerTimestamps(\n existingState.container,\n remoteContainer,\n ),\n containerWriterProjection: null,\n metadataReferencedPrincipals: remoteContainer.metadataReferencedPrincipals,\n };\n}\n\nfunction installUpdatedRemoteContainerState(\n existingState: ContainerState,\n nextState: ContainerState,\n host: RemoteContainerHydrationHost,\n): void {\n const wasLocalOnly = existingState.container.serverCreatedAt == null;\n existingState.container = nextState.container;\n existingState.containerWriterProjection = nextState.containerWriterProjection;\n existingState.metadataReferencedPrincipals =\n nextState.metadataReferencedPrincipals;\n // The snapshot copied the live generation when it was taken; a hint that\n // landed during the persist leaves the live metadata projection dropped.\n if (projectionGeneration(existingState) === projectionGeneration(nextState))\n existingState.metadataWriterProjection = nextState.metadataWriterProjection;\n installContainerMetadataRecord(existingState, nextState.record);\n // A document pass may have deferred while this root was awaiting proof.\n // The first durable remote acknowledgement makes its pending creates runnable.\n if (wasLocalOnly && existingState.container.serverCreatedAt != null)\n host.requestDocumentPriming?.();\n}\n\n/**\n * A clean metadata document is read only when a hint names it, and a hint sent\n * while this client was offline or not yet subscribed is lost. The listing\n * reports the version vector of every update the server holds for the metadata\n * document; when this client's copy does not cover it, an edit is unread. Owe\n * the read before this hydration advances the lane watermark past the row.\n */\nfunction coversMetadataVersion(\n existingState: ContainerState,\n remoteContainer: RemoteContainer,\n): boolean {\n const listed = remoteContainer.metadataVersionVector;\n try {\n // A document with no stored update is covered by any copy.\n if (decodeVersionVector(listed).toJSON().size === 0) return true;\n return satisfiesVersionVector(\n encodeVersionVector(existingState.doc),\n listed,\n );\n } catch {\n // An unreadable version proves nothing: owe the read, which pulls the\n // truth, and let the rest of the page hydrate.\n return false;\n }\n}\n\nasync function oweMetadataReadIfBehind(\n host: RemoteContainerHydrationHost,\n existingState: ContainerState,\n remoteContainer: RemoteContainer,\n): Promise<void> {\n if (!coversMetadataVersion(existingState, remoteContainer)) {\n await host.requestMetadataRevalidation?.({\n advertisedVersionVector: remoteContainer.metadataVersionVector,\n documentId: remoteContainer.metadataDocumentId,\n });\n }\n}\n\nasync function updateExistingRemoteContainerState(input: {\n childIdsByParentId?: ContainerChildIndex | undefined;\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n existingState: ContainerState;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): Promise<ContainerState | null> {\n const { childIdsByParentId, existingState, host, remoteContainer, state } =\n input;\n const previousParentId = existingState.container.parentId;\n const previousLocalUpdatedAt = existingState.container.localUpdatedAt;\n // A queued, not-yet-synced local move/create owns this container's parent\n // until its intent lane reconciles. Omit the remote parent when the page scan\n // saw one; persistence also rechecks the intent transactionally so a move\n // created after that scan wins. Both paths preserve the durable local clock.\n const hasPendingStructuralIntent =\n input.containerIdsWithPendingStructuralIntents.has(remoteContainer.id);\n const nextParentId = hasPendingStructuralIntent\n ? undefined\n : remoteContainer.parentId;\n const localUpdatedAt = resolveRemoteContainerHydrationLocalUpdatedAt({\n containerIdsWithPendingMetadataUpdates:\n input.containerIdsWithPendingMetadataUpdates,\n hasPendingStructuralIntent,\n previousLocalUpdatedAt,\n remoteContainer,\n });\n await oweMetadataReadIfBehind(host, existingState, remoteContainer);\n const nextState = createUpdatedRemoteContainerState(\n existingState,\n remoteContainer,\n );\n const persistenceResult = await host.persistContainerState(\n nextState,\n {\n accessEpoch: remoteContainer.metadataAccessEpoch,\n accessStateHash: remoteContainer.metadataAccessStateHash,\n documentId: remoteContainer.metadataDocumentId,\n effectiveAccessLevel: remoteContainer.effectiveAccessLevel,\n metadataDocumentId: remoteContainer.metadataDocumentId,\n systemSlot: remoteContainer.systemSlot ?? null,\n organizationId: remoteContainer.organizationId,\n ...(nextParentId !== undefined ? { parentId: nextParentId } : {}),\n },\n false,\n remoteContainerHydrationSaveOptions({\n localUpdatedAt,\n remoteContainer,\n }),\n {\n preserveDurableStructureWhenPending: true,\n },\n );\n if (persistenceResult.status === \"missing\") {\n // Hydration persists a detached candidate so an in-flight response cannot\n // mutate mapped state before its guards settle. Retire the exact state this\n // hydration read because store-level reference cleanup cannot see the clone.\n removeMissingHydratedContainer({\n childIdsByParentId,\n existingState,\n host,\n previousParentId,\n remoteContainer,\n state,\n });\n return null;\n }\n if (persistenceResult.status !== \"persisted\") return null;\n const { record: nextRecord } = persistenceResult;\n installContainerMetadataRecord(nextState, nextRecord);\n if (input.isCurrent?.() === false) {\n return existingState;\n }\n nextState.container = {\n ...nextState.container,\n metadataDocumentId: remoteContainer.metadataDocumentId,\n organizationId: remoteContainer.organizationId,\n parentId: nextState.container.parentId,\n };\n\n installUpdatedRemoteContainerState(existingState, nextState, host);\n moveIndexedContainerChild(\n childIdsByParentId,\n remoteContainer.id,\n previousParentId,\n existingState.container.parentId,\n );\n await reconcileLocalOnlyRootContainers({\n childIdsByParentId,\n isCurrent: input.isCurrent,\n remoteRootState: existingState,\n requestDocumentPriming: host.requestDocumentPriming,\n state,\n });\n return existingState;\n}\n\ninterface UpsertRemoteContainerStateInput {\n childIdsByParentId?: ContainerChildIndex | undefined;\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n host: RemoteContainerHydrationHost;\n expectedHydrationTombstone?: ContainerHydrationTombstone | null | undefined;\n isCurrent?: (() => boolean) | undefined;\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}\n\n/** A pull can observe the same manifest change as a missed realtime hint. */\nfunction invalidateListedProjectionCaches(\n input: UpsertRemoteContainerStateInput,\n) {\n const held = input.state.containersById.get(input.remoteContainer.id);\n if (\n held &&\n (held.record.accessStateHash !==\n input.remoteContainer.metadataAccessStateHash ||\n (held.container.effectiveAccessLevel ?? \"read\") !==\n input.remoteContainer.effectiveAccessLevel)\n ) {\n // Eviction admits no remote state. Drop citations before verification can\n // advance local checkpoints past those cached container/document paths.\n invalidateContainerProjectionCaches(input.state, [\n input.remoteContainer.id,\n ]);\n }\n}\n\nexport async function upsertRemoteContainerState(\n input: UpsertRemoteContainerStateInput,\n): Promise<ContainerState | null> {\n let expectedPlacementCheckpoint: AccessManifestCheckpoint | undefined;\n const heldState = input.state.containersById.get(input.remoteContainer.id);\n const heldBinding = heldState\n ? heldContainerBinding(heldState)\n : await input.state.persistence.loadHeldContainerBinding(\n input.state.runtime.infra.execSql,\n input.remoteContainer.id,\n );\n const listed = input.remoteContainer;\n // A folder re-homed away from the listed organization never returns there,\n // whatever binding (possibly none, after a reset) the device holds now.\n const supersededListing =\n !listingRepeatsHeldOrdinaryBinding(heldBinding, listed) &&\n (await input.state.persistence.isSupersededContainerBinding(\n input.state.runtime.infra.execSql,\n { containerId: listed.id, organizationId: listed.organizationId },\n ));\n if (input.isCurrent?.() === false) return null;\n invalidateListedProjectionCaches(input);\n const verified = await verifyRemoteContainerDestination({\n ...input,\n heldBinding,\n supersededListing,\n refresh: !!input.expectedHydrationTombstone,\n onVerifiedCheckpoint: (checkpoint) => {\n expectedPlacementCheckpoint = checkpoint;\n },\n });\n if (!verified || input.isCurrent?.() === false) return null;\n input = { ...input, remoteContainer: verified };\n const existingState = input.state.containersById.get(\n input.remoteContainer.id,\n );\n const remoteState = await runWithSecurityIncidentReporting(\n input.state.runtime.util.reportSecurityIncident,\n {\n objectId: verified.id,\n objectKind: \"container\",\n operation: \"container.binding.persist\",\n organizationId: verified.organizationId,\n },\n async () =>\n (await rebindReHomedContainer({\n existingState,\n heldBinding,\n isCurrent: input.isCurrent,\n state: input.state,\n verified,\n }))\n ? persistVerifiedRemoteContainer({\n ...input,\n existingState,\n expectedPlacementCheckpoint,\n })\n : null,\n );\n if (!remoteState) {\n return null;\n }\n await reconcileLocalOnlySystemContainers({\n childIdsByParentId: input.childIdsByParentId,\n isCurrent: input.isCurrent,\n requestDocumentPriming: input.host.requestDocumentPriming,\n remoteSystemState: remoteState,\n state: input.state,\n });\n return remoteState;\n}\n\n/**\n * Upsert one listed folder, isolating a rejected proof or binding. The refusal\n * was already reported; returning no state leaves the item unapplied without\n * blocking independent folders.\n */\nexport async function upsertIsolatedRemoteContainerState(\n input: UpsertRemoteContainerStateInput,\n): Promise<ContainerState | null> {\n try {\n return await upsertRemoteContainerState(input);\n } catch (error) {\n if (\n !isKeyingVerificationError(error) &&\n !isProjectionVerificationCancelledError(error)\n )\n throw error;\n return null;\n }\n}\n\nfunction persistVerifiedRemoteContainer(\n input: UpsertRemoteContainerStateInput & {\n existingState: ContainerState | undefined;\n expectedPlacementCheckpoint: AccessManifestCheckpoint | undefined;\n },\n): Promise<ContainerState | null> {\n const { existingState, expectedPlacementCheckpoint } = input;\n return existingState\n ? updateExistingRemoteContainerState({\n childIdsByParentId: input.childIdsByParentId,\n containerIdsWithPendingMetadataUpdates:\n input.containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents:\n input.containerIdsWithPendingStructuralIntents,\n existingState,\n host: input.host,\n isCurrent: input.isCurrent,\n remoteContainer: input.remoteContainer,\n state: input.state,\n })\n : insertRemoteContainerState({\n childIdsByParentId: input.childIdsByParentId,\n host: input.host,\n expectedHydrationTombstone: input.expectedHydrationTombstone ?? null,\n expectedPlacementCheckpoint,\n isCurrent: input.isCurrent,\n remoteContainer: input.remoteContainer,\n state: input.state,\n });\n}\n"]}
@@ -14,7 +14,7 @@ export type QueueContainerParentLane = (parentId: string | null) => void;
14
14
  export type RemoteContainerIngestQueue = Map<string, RemoteContainer>;
15
15
  export type SaveContainerOptions = Parameters<ContainerContentsPersistence["saveContainer"]>[3];
16
16
  export type ContainerMetadataDocumentState = Awaited<ReturnType<typeof createContainerMetadataDocument>>;
17
- export type RemoteContainer = Pick<ContainerSummary, "createdAt" | "effectiveAccessLevel" | "systemSlot" | "id" | "metadataAccessEpoch" | "metadataAccessStateHash" | "metadataDocumentId" | "metadataReferencedPrincipals" | "organizationId" | "parentId" | "updatedAt">;
17
+ export type RemoteContainer = Pick<ContainerSummary, "createdAt" | "effectiveAccessLevel" | "systemSlot" | "id" | "metadataAccessEpoch" | "metadataAccessStateHash" | "metadataDocumentId" | "metadataReferencedPrincipals" | "metadataVersionVector" | "organizationId" | "parentId" | "updatedAt">;
18
18
  export interface ContainerState {
19
19
  containerWriterProjection?: ContainerWriterProjectionResponse | null | undefined;
20
20
  /**
@@ -81,6 +81,14 @@ export interface RemoteContainerHydrationHost {
81
81
  preserveDurableStructureWhenPending?: boolean | undefined;
82
82
  }) => Promise<PersistContainerStateResult>;
83
83
  requestDocumentPriming?: (() => void) | undefined;
84
+ /**
85
+ * Owe a metadata document one remote read, durably, before hydration
86
+ * advances the timestamps and lane watermark that revealed it.
87
+ */
88
+ requestMetadataRevalidation?: ((request: {
89
+ readonly advertisedVersionVector: string;
90
+ readonly documentId: string;
91
+ }) => Promise<void>) | undefined;
84
92
  updateSnapshot: () => void;
85
93
  }
86
94
  export interface ContainerParentHydrationLane {
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n RequestResult,\n WriterProjectionListing,\n} from \"@tearleads/api-client\";\nimport type { ContainerReplacementAuthorizationsResponse } from \"@tearleads/validators/operation\";\nimport type { ListContainerParentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n ListContainerParentLanesResponse,\n ListContainersResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord,\n ContainerHydrationTombstone,\n ContainerRecord,\n createContainerParentSyncLane,\n} from \"../containerPersistence\";\nimport type { ContainerMetadataPatch } from \"../metadata\";\nimport type { createContainerMetadataDocument } from \"../metadata/containerMetadataDocument\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ListedRemoteContainerPageItem =\n ListContainersResponse[\"items\"][number];\nexport type ContainerChildIndex = Map<string, Set<string>>;\nexport type QueueContainerParentLane = (parentId: string | null) => void;\nexport type RemoteContainerIngestQueue = Map<string, RemoteContainer>;\nexport type SaveContainerOptions = Parameters<\n ContainerContentsPersistence[\"saveContainer\"]\n>[3];\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createContainerMetadataDocument>\n>;\nexport type RemoteContainer = Pick<\n ContainerSummary,\n | \"createdAt\"\n | \"effectiveAccessLevel\"\n | \"systemSlot\"\n | \"id\"\n | \"metadataAccessEpoch\"\n | \"metadataAccessStateHash\"\n | \"metadataDocumentId\"\n | \"metadataReferencedPrincipals\"\n | \"organizationId\"\n | \"parentId\"\n | \"updatedAt\"\n>;\n\nexport interface ContainerState {\n containerWriterProjection?:\n | ContainerWriterProjectionResponse\n | null\n | undefined;\n /**\n * Bumped whenever a realtime hint or a pull drops this container's cached writer\n * projections (container and metadata document alike); an operation that\n * fetched or carried a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration?: number | undefined;\n metadataReferencedPrincipals?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n container: ContainerRecord;\n doc: ContainerMetadataDocumentState;\n metadataWriterProjection?:\n | DocumentWriterProjectionResponse\n | null\n | undefined;\n /** Durable pull progress mirrored from the metadata document record. */\n pullContinuation?: ContainerDocumentRecord[\"pullContinuation\"] | undefined;\n record: ContainerDocumentRecord;\n}\n\ninterface RemoteContainerHydrationApi\n extends Partial<PrincipalPolicyHistoryReader>,\n CurrentPrincipalPolicyReader {\n getContainerReplacementAuthorizationsResult(\n containerId: string,\n replacesOrganizationId: string,\n ): Promise<RequestResult<ContainerReplacementAuthorizationsResponse>>;\n evictContainerWriterProjection(containerId: string): void;\n evictWriterProjectionsCiting(containerIds: readonly string[]): void;\n getContainerWriterProjection(\n containerId: string,\n listing?: WriterProjectionListing,\n ): Promise<ContainerWriterProjectionResponse | null>;\n listContainerParentLanes(\n input: ListContainerParentLanesRequest,\n ): Promise<ListContainerParentLanesResponse | null>;\n}\n\ninterface RemoteContainerHydrationRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"adoptRootContainer\"\n | \"crypto\"\n | \"infra\"\n | \"organizations\"\n | \"principalPolicies\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: RemoteContainerHydrationApi;\n}\n\nexport interface RemoteContainerHydrationState {\n /**\n * Container listing requests that failed or timed out, in a current crawl.\n * An explicit refresh compares it across its wait to tell whether a listing\n * fell short while it ran.\n */\n containerListingFailures?: number | undefined;\n containersById: Map<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n persistence: ContainerContentsPersistence;\n rootLaneHydrated?: boolean | undefined;\n runtime: RemoteContainerHydrationRuntime;\n structuralGeneration?: number | undefined;\n}\n\nexport type PersistContainerStateResult =\n | { status: \"identity-superseded\"; record: ContainerDocumentRecord }\n | { status: \"missing\" }\n | {\n status: \"persisted\";\n record: ContainerDocumentRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | { status: \"stale-generation\" };\n\nexport interface RemoteContainerHydrationHost {\n persistContainerState: (\n containerState: ContainerState,\n patch?: Partial<ContainerMetadataPatch>,\n updateView?: boolean,\n saveOptions?: SaveContainerOptions,\n mutationOptions?: {\n /** Queued metadata rows the server committed, settled in this write. */\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedStateWhenMissing?: ContainerState | undefined;\n isCurrent?: (() => boolean) | undefined;\n createIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"createIntentSettlement\"];\n moveIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"moveIntentSettlement\"];\n preserveDurableStructureWhenPending?: boolean | undefined;\n },\n ) => Promise<PersistContainerStateResult>;\n requestDocumentPriming?: (() => void) | undefined;\n updateSnapshot: () => void;\n}\n\nexport interface ContainerParentHydrationLane {\n parentId: string | null;\n watermark?: ListContainersResponse[\"nextWatermark\"];\n}\n\nexport interface ExpectedContainerState {\n container: ContainerRecord;\n fingerprint: string;\n}\n\nexport interface FetchedContainerParentLanePage {\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n expectedHydrationTombstones: ReadonlyMap<string, ContainerHydrationTombstone>;\n lane: ContainerParentHydrationLane;\n response: ListContainersResponse;\n syncLane: ReturnType<typeof createContainerParentSyncLane>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n RequestResult,\n WriterProjectionListing,\n} from \"@tearleads/api-client\";\nimport type { ContainerReplacementAuthorizationsResponse } from \"@tearleads/validators/operation\";\nimport type { ListContainerParentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n ListContainerParentLanesResponse,\n ListContainersResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord,\n ContainerHydrationTombstone,\n ContainerRecord,\n createContainerParentSyncLane,\n} from \"../containerPersistence\";\nimport type { ContainerMetadataPatch } from \"../metadata\";\nimport type { createContainerMetadataDocument } from \"../metadata/containerMetadataDocument\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ListedRemoteContainerPageItem =\n ListContainersResponse[\"items\"][number];\nexport type ContainerChildIndex = Map<string, Set<string>>;\nexport type QueueContainerParentLane = (parentId: string | null) => void;\nexport type RemoteContainerIngestQueue = Map<string, RemoteContainer>;\nexport type SaveContainerOptions = Parameters<\n ContainerContentsPersistence[\"saveContainer\"]\n>[3];\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createContainerMetadataDocument>\n>;\nexport type RemoteContainer = Pick<\n ContainerSummary,\n | \"createdAt\"\n | \"effectiveAccessLevel\"\n | \"systemSlot\"\n | \"id\"\n | \"metadataAccessEpoch\"\n | \"metadataAccessStateHash\"\n | \"metadataDocumentId\"\n | \"metadataReferencedPrincipals\"\n | \"metadataVersionVector\"\n | \"organizationId\"\n | \"parentId\"\n | \"updatedAt\"\n>;\n\nexport interface ContainerState {\n containerWriterProjection?:\n | ContainerWriterProjectionResponse\n | null\n | undefined;\n /**\n * Bumped whenever a realtime hint or a pull drops this container's cached writer\n * projections (container and metadata document alike); an operation that\n * fetched or carried a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration?: number | undefined;\n metadataReferencedPrincipals?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n container: ContainerRecord;\n doc: ContainerMetadataDocumentState;\n metadataWriterProjection?:\n | DocumentWriterProjectionResponse\n | null\n | undefined;\n /** Durable pull progress mirrored from the metadata document record. */\n pullContinuation?: ContainerDocumentRecord[\"pullContinuation\"] | undefined;\n record: ContainerDocumentRecord;\n}\n\ninterface RemoteContainerHydrationApi\n extends Partial<PrincipalPolicyHistoryReader>,\n CurrentPrincipalPolicyReader {\n getContainerReplacementAuthorizationsResult(\n containerId: string,\n replacesOrganizationId: string,\n ): Promise<RequestResult<ContainerReplacementAuthorizationsResponse>>;\n evictContainerWriterProjection(containerId: string): void;\n evictWriterProjectionsCiting(containerIds: readonly string[]): void;\n getContainerWriterProjection(\n containerId: string,\n listing?: WriterProjectionListing,\n ): Promise<ContainerWriterProjectionResponse | null>;\n listContainerParentLanes(\n input: ListContainerParentLanesRequest,\n ): Promise<ListContainerParentLanesResponse | null>;\n}\n\ninterface RemoteContainerHydrationRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"adoptRootContainer\"\n | \"crypto\"\n | \"infra\"\n | \"organizations\"\n | \"principalPolicies\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: RemoteContainerHydrationApi;\n}\n\nexport interface RemoteContainerHydrationState {\n /**\n * Container listing requests that failed or timed out, in a current crawl.\n * An explicit refresh compares it across its wait to tell whether a listing\n * fell short while it ran.\n */\n containerListingFailures?: number | undefined;\n containersById: Map<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n persistence: ContainerContentsPersistence;\n rootLaneHydrated?: boolean | undefined;\n runtime: RemoteContainerHydrationRuntime;\n structuralGeneration?: number | undefined;\n}\n\nexport type PersistContainerStateResult =\n | { status: \"identity-superseded\"; record: ContainerDocumentRecord }\n | { status: \"missing\" }\n | {\n status: \"persisted\";\n record: ContainerDocumentRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | { status: \"stale-generation\" };\n\nexport interface RemoteContainerHydrationHost {\n persistContainerState: (\n containerState: ContainerState,\n patch?: Partial<ContainerMetadataPatch>,\n updateView?: boolean,\n saveOptions?: SaveContainerOptions,\n mutationOptions?: {\n /** Queued metadata rows the server committed, settled in this write. */\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedStateWhenMissing?: ContainerState | undefined;\n isCurrent?: (() => boolean) | undefined;\n createIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"createIntentSettlement\"];\n moveIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"moveIntentSettlement\"];\n preserveDurableStructureWhenPending?: boolean | undefined;\n },\n ) => Promise<PersistContainerStateResult>;\n requestDocumentPriming?: (() => void) | undefined;\n /**\n * Owe a metadata document one remote read, durably, before hydration\n * advances the timestamps and lane watermark that revealed it.\n */\n requestMetadataRevalidation?:\n | ((request: {\n readonly advertisedVersionVector: string;\n readonly documentId: string;\n }) => Promise<void>)\n | undefined;\n updateSnapshot: () => void;\n}\n\nexport interface ContainerParentHydrationLane {\n parentId: string | null;\n watermark?: ListContainersResponse[\"nextWatermark\"];\n}\n\nexport interface ExpectedContainerState {\n container: ContainerRecord;\n fingerprint: string;\n}\n\nexport interface FetchedContainerParentLanePage {\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n expectedHydrationTombstones: ReadonlyMap<string, ContainerHydrationTombstone>;\n lane: ContainerParentHydrationLane;\n response: ListContainersResponse;\n syncLane: ReturnType<typeof createContainerParentSyncLane>;\n}\n"]}
@@ -29,8 +29,8 @@ export function containerMutationRequestCore(operation, input) {
29
29
  return {
30
30
  event: readCanonicalRecord(input.event, `${label} event`),
31
31
  body: readCanonicalRecord(input.body, `${label} body`),
32
+ // The API derives the manifest; the request commits to it by hash.
32
33
  expectedManifestHash: input.manifestHash,
33
- manifest: readCanonicalRecord(input.manifest, `${label} manifest`),
34
34
  principalPolicyRefs: input.principalPolicies.map(principalPolicyRef),
35
35
  keyEpoch: readCanonicalRecord(input.keyEpoch, `${label} key epoch`),
36
36
  wraps: readCanonicalRecords(input.wraps, `${label} wraps`),
@@ -1 +1 @@
1
- {"version":3,"file":"mutationRequestCore.js","sourceRoot":"","sources":["mutationRequestCore.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,kBAAkB,EAAE,MAAM,mDAAmD,CAAC;AACvF,OAAO,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AAClF,OAAO,EACL,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,oCAAoC,CAAC;AAG5C,MAAM,UAAU,yBAAyB,CACvC,KAAc,EACd,KAAa;IAEb,OAAO,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;QAC1C,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,mBAAmB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AACxC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CACvC,gBAA0C,EAC1C,kBAAqD;IAKrD,OAAO;QACL,mBAAmB,EAAE,oBAAoB,CAAC,gBAAgB,CAAC;QAC3D,yBAAyB,EACvB,kBAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,oBAAoB,CAAC;KACpD,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,4BAA4B,CAC1C,SAAiB,EACjB,KASC;IAYD,MAAM,KAAK,GAAG,aAAa,SAAS,EAAE,CAAC;IACvC,OAAO;QACL,KAAK,EAAE,mBAAmB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK,QAAQ,CAAC;QACzD,IAAI,EAAE,mBAAmB,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC;QACtD,oBAAoB,EAAE,KAAK,CAAC,YAAY;QACxC,QAAQ,EAAE,mBAAmB,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,KAAK,WAAW,CAAC;QAClE,mBAAmB,EAAE,KAAK,CAAC,iBAAiB,CAAC,GAAG,CAAC,kBAAkB,CAAC;QACpE,QAAQ,EAAE,mBAAmB,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,KAAK,YAAY,CAAC;QACnE,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK,QAAQ,CAAC;QAC1D,iBAAiB,EAAE,oBAAoB,CACrC,KAAK,CAAC,iBAAiB,EACvB,GAAG,KAAK,sBAAsB,CAC/B;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerMutationRequest,\n} from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyRef } from \"../../../data/containers/shared/principalPolicies\";\nimport { containerManifestRef } from \"../../../data/containers/shared/projection\";\nimport {\n readCanonicalRecord,\n readCanonicalRecords,\n} from \"../../../data/keying/canonicalJson\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principalContracts/principalPolicyEvidence\";\n\nexport function readCanonicalRecordOrNull(\n value: unknown,\n label: string,\n): Record<string, unknown> | null {\n return value === null || value === undefined\n ? null\n : readCanonicalRecord(value, label);\n}\n\n/**\n * The previous-manifest identity every non-create mutation\n * (share/rekey/revoke/move) sends alongside the core request fields: the\n * previous head and the current path, cited by hash rather than echoed.\n */\nexport function previousPathRequestFields(\n previousManifest: AccessManifestBundleWire,\n previousProjection: ContainerWriterProjectionResponse,\n): Pick<\n ContainerMutationRequest,\n \"previousManifestRef\" | \"previousContainerPathRefs\"\n> {\n return {\n previousManifestRef: containerManifestRef(previousManifest),\n previousContainerPathRefs:\n previousProjection.path.map(containerManifestRef),\n };\n}\n\n/**\n * The eight ContainerMutationRequest fields every child-container mutation\n * (create/share/rekey/revoke/move) assembles identically, labeled by\n * operation. The identity fields — previous manifest/path, manifest history,\n * predecessor bridge, keyring, and the parent KEK — genuinely differ per\n * operation and stay with each builder.\n */\nexport function containerMutationRequestCore(\n operation: string,\n input: {\n body: unknown;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n },\n): Pick<\n ContainerMutationRequest,\n | \"event\"\n | \"body\"\n | \"expectedManifestHash\"\n | \"manifest\"\n | \"principalPolicyRefs\"\n | \"keyEpoch\"\n | \"wraps\"\n | \"userRecipientKeys\"\n> {\n const label = `Container ${operation}`;\n return {\n event: readCanonicalRecord(input.event, `${label} event`),\n body: readCanonicalRecord(input.body, `${label} body`),\n expectedManifestHash: input.manifestHash,\n manifest: readCanonicalRecord(input.manifest, `${label} manifest`),\n principalPolicyRefs: input.principalPolicies.map(principalPolicyRef),\n keyEpoch: readCanonicalRecord(input.keyEpoch, `${label} key epoch`),\n wraps: readCanonicalRecords(input.wraps, `${label} wraps`),\n userRecipientKeys: readCanonicalRecords(\n input.userRecipientKeys,\n `${label} user recipient keys`,\n ),\n };\n}\n"]}
1
+ {"version":3,"file":"mutationRequestCore.js","sourceRoot":"","sources":["mutationRequestCore.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,kBAAkB,EAAE,MAAM,mDAAmD,CAAC;AACvF,OAAO,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AAClF,OAAO,EACL,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,oCAAoC,CAAC;AAG5C,MAAM,UAAU,yBAAyB,CACvC,KAAc,EACd,KAAa;IAEb,OAAO,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;QAC1C,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,mBAAmB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AACxC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CACvC,gBAA0C,EAC1C,kBAAqD;IAKrD,OAAO;QACL,mBAAmB,EAAE,oBAAoB,CAAC,gBAAgB,CAAC;QAC3D,yBAAyB,EACvB,kBAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,oBAAoB,CAAC;KACpD,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,4BAA4B,CAC1C,SAAiB,EACjB,KASC;IAWD,MAAM,KAAK,GAAG,aAAa,SAAS,EAAE,CAAC;IACvC,OAAO;QACL,KAAK,EAAE,mBAAmB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK,QAAQ,CAAC;QACzD,IAAI,EAAE,mBAAmB,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC;QACtD,mEAAmE;QACnE,oBAAoB,EAAE,KAAK,CAAC,YAAY;QACxC,mBAAmB,EAAE,KAAK,CAAC,iBAAiB,CAAC,GAAG,CAAC,kBAAkB,CAAC;QACpE,QAAQ,EAAE,mBAAmB,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,KAAK,YAAY,CAAC;QACnE,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK,QAAQ,CAAC;QAC1D,iBAAiB,EAAE,oBAAoB,CACrC,KAAK,CAAC,iBAAiB,EACvB,GAAG,KAAK,sBAAsB,CAC/B;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerMutationRequest,\n} from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyRef } from \"../../../data/containers/shared/principalPolicies\";\nimport { containerManifestRef } from \"../../../data/containers/shared/projection\";\nimport {\n readCanonicalRecord,\n readCanonicalRecords,\n} from \"../../../data/keying/canonicalJson\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principalContracts/principalPolicyEvidence\";\n\nexport function readCanonicalRecordOrNull(\n value: unknown,\n label: string,\n): Record<string, unknown> | null {\n return value === null || value === undefined\n ? null\n : readCanonicalRecord(value, label);\n}\n\n/**\n * The previous-manifest identity every non-create mutation\n * (share/rekey/revoke/move) sends alongside the core request fields: the\n * previous head and the current path, cited by hash rather than echoed.\n */\nexport function previousPathRequestFields(\n previousManifest: AccessManifestBundleWire,\n previousProjection: ContainerWriterProjectionResponse,\n): Pick<\n ContainerMutationRequest,\n \"previousManifestRef\" | \"previousContainerPathRefs\"\n> {\n return {\n previousManifestRef: containerManifestRef(previousManifest),\n previousContainerPathRefs:\n previousProjection.path.map(containerManifestRef),\n };\n}\n\n/**\n * The eight ContainerMutationRequest fields every child-container mutation\n * (create/share/rekey/revoke/move) assembles identically, labeled by\n * operation. The identity fields — previous manifest/path, manifest history,\n * predecessor bridge, keyring, and the parent KEK — genuinely differ per\n * operation and stay with each builder.\n */\nexport function containerMutationRequestCore(\n operation: string,\n input: {\n body: unknown;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n },\n): Pick<\n ContainerMutationRequest,\n | \"event\"\n | \"body\"\n | \"expectedManifestHash\"\n | \"principalPolicyRefs\"\n | \"keyEpoch\"\n | \"wraps\"\n | \"userRecipientKeys\"\n> {\n const label = `Container ${operation}`;\n return {\n event: readCanonicalRecord(input.event, `${label} event`),\n body: readCanonicalRecord(input.body, `${label} body`),\n // The API derives the manifest; the request commits to it by hash.\n expectedManifestHash: input.manifestHash,\n principalPolicyRefs: input.principalPolicies.map(principalPolicyRef),\n keyEpoch: readCanonicalRecord(input.keyEpoch, `${label} key epoch`),\n wraps: readCanonicalRecords(input.wraps, `${label} wraps`),\n userRecipientKeys: readCanonicalRecords(\n input.userRecipientKeys,\n `${label} user recipient keys`,\n ),\n };\n}\n"]}
@@ -49,7 +49,6 @@ export async function buildContainerRecitePlan(input) {
49
49
  const request = {
50
50
  body,
51
51
  event: readCanonicalRecord(event, "Recitation event"),
52
- manifest: readCanonicalRecord(manifest, "Recitation manifest"),
53
52
  expectedManifestHash: manifestHash,
54
53
  previousManifestRef: containerManifestRef(previous.bundle),
55
54
  previousContainerPathRefs: input.path.map((head) => containerManifestRef(head.bundle)),