@tearleads/client-sdk 0.1.223 → 0.1.225

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 (89) hide show
  1. package/client/organizations/organizationMemberships.d.ts +1 -1
  2. package/client/organizations/organizationMemberships.js +1 -1
  3. package/client/organizations/organizationMemberships.js.map +1 -1
  4. package/data/documents/shared/containerKek/containerKekPathVerification.js +2 -0
  5. package/data/documents/shared/containerKek/containerKekPathVerification.js.map +1 -1
  6. package/data/documents/shared/projection/index.js +2 -0
  7. package/data/documents/shared/projection/index.js.map +1 -1
  8. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +3 -0
  9. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +2 -1
  10. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  11. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +2 -1
  12. package/data/keyingProjectionVerification/container/containerDestinationVerification.js +1 -0
  13. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
  14. package/data/keyingProjectionVerification/container/containerProjectionVerification.d.ts +3 -2
  15. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +2 -0
  16. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  17. package/data/keyingProjectionVerification/document/documentProjectionVerification.d.ts +2 -1
  18. package/data/keyingProjectionVerification/document/documentProjectionVerification.js +2 -0
  19. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
  20. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +3 -2
  21. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  22. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.d.ts +2 -1
  23. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js +7 -3
  24. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js.map +1 -1
  25. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +3 -2
  26. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  27. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +17 -6
  28. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  29. package/data/keyingProjectionVerification/types.d.ts +20 -2
  30. package/data/keyingProjectionVerification/types.js.map +1 -1
  31. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js +2 -0
  32. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -1
  33. package/package.json +1 -1
  34. package/stores/container-contents/operations/forgetOrganizationContentOperation.js +1 -1
  35. package/stores/container-contents/operations/forgetOrganizationContentOperation.js.map +1 -1
  36. package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js +1 -1
  37. package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js.map +1 -1
  38. package/stores/documents/documentStore/initialization/index.js +1 -1
  39. package/stores/documents/documentStore/initialization/index.js.map +1 -1
  40. package/stores/documents/documentStore/storedDocument.js +1 -1
  41. package/stores/documents/documentStore/storedDocument.js.map +1 -1
  42. package/stores/documents/documentStore/sync/syncAttachments.js +1 -1
  43. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  44. package/workflows/container-contents/container-state/create/createAdoption.js +2 -0
  45. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  46. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +2 -0
  47. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  48. package/workflows/container-contents/container-state/share/groupGrantVerification.js +2 -0
  49. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  50. package/workflows/container-contents/container-state/share/index.js +2 -0
  51. package/workflows/container-contents/container-state/share/index.js.map +1 -1
  52. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +2 -0
  53. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  54. package/workflows/container-contents/syncPause/documentRemoval.js +1 -1
  55. package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
  56. package/workflows/containers/child/create/index.d.ts +1 -1
  57. package/workflows/containers/child/create/index.js +2 -0
  58. package/workflows/containers/child/create/index.js.map +1 -1
  59. package/workflows/containers/child/move/moveWraps.js +3 -0
  60. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  61. package/workflows/containers/child/rekey/carriedDescendantRekeys.js +2 -0
  62. package/workflows/containers/child/rekey/carriedDescendantRekeys.js.map +1 -1
  63. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js +2 -0
  64. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js.map +1 -1
  65. package/workflows/containers/child/share/sharePlanCore.js +2 -0
  66. package/workflows/containers/child/share/sharePlanCore.js.map +1 -1
  67. package/workflows/containers/rematerialization/principalContainerRematerialization.js +2 -0
  68. package/workflows/containers/rematerialization/principalContainerRematerialization.js.map +1 -1
  69. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js +2 -0
  70. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js.map +1 -1
  71. package/workflows/documents/create/index.js +2 -0
  72. package/workflows/documents/create/index.js.map +1 -1
  73. package/workflows/documents/linkSet/linkSetAuthority.js +2 -0
  74. package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -1
  75. package/workflows/documents/purge/index.js +6 -0
  76. package/workflows/documents/purge/index.js.map +1 -1
  77. package/workflows/documents/sync/syncSubmittedResult.js +2 -0
  78. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
  79. package/workflows/documents/syncFailures/syncRepairAccess.js +2 -0
  80. package/workflows/documents/syncFailures/syncRepairAccess.js.map +1 -1
  81. package/workflows/organizations/memberships/organizationMemberships.d.ts +1 -1
  82. package/workflows/organizations/memberships/organizationMemberships.js +1 -1
  83. package/workflows/organizations/memberships/organizationMemberships.js.map +1 -1
  84. package/workflows/sync/coordination.d.ts +6 -0
  85. package/workflows/sync/coordination.js +6 -0
  86. package/workflows/sync/coordination.js.map +1 -0
  87. package/workflows/sync/index.d.ts +1 -6
  88. package/workflows/sync/index.js +1 -5
  89. package/workflows/sync/index.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAqEA,MAAM,OAAO,oCAAqC,SAAQ,KAAK;IAC7D;QACE,KAAK,CAAC,4CAA4C,CAAC,CAAC;QACpD,IAAI,CAAC,IAAI,GAAG,sCAAsC,CAAC;IACrD,CAAC;CACF;AAED,MAAM,kCAAkC,GACtC,IAAI,oCAAoC,EAAE,CAAC;AAE7C,MAAM,UAAU,sCAAsC,CACpD,KAAc;IAEd,OAAO,KAAK,KAAK,kCAAkC,CAAC;AACtD,CAAC;AAED,MAAM,UAAU,sCAAsC,CAAC,KAAc;IACnE,IAAI,sCAAsC,CAAC,KAAK,CAAC;QAAE,MAAM,KAAK,CAAC;AACjE,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,SAA2B;IAE3B,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,EAAE,CAAC;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,sCAAsC,CAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAC/D,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,UAAU,mCAAmC,CACjD,YAAyC;IAEzC,IAAI,YAAY,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QAC/B,MAAM,kCAAkC,CAAC;IAC3C,CAAC;AACH,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,MAAmD,EACnD,YAAyC;IAEzC,IAAI,CAAC,MAAM,IAAI,CAAC,YAAY;QAAE,OAAO,MAAM,CAAC;IAC5C,MAAM,KAAK,GACT,CAAC,SAA0C,EAAE,EAAE,CAC/C,KAAK,EAAE,KAA2C,EAAE,EAAE;QACpD,mCAAmC,CAAC,YAAY,CAAC,CAAC;Q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OAAO,CAAC,CAAC;wBAC7C,OAAO,MAAM,CAAC;oBAChB,CAAC;iBACF;gBACH,CAAC,CAAC,EAAE,CAAC;SACR,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACvC,CAAC;AAED,MAAM,UAAU,iCAAiC,CAO/C,KAAY;IACZ,OAAO;QACL,GAAG,KAAK;QACR,+BAA+B,EAAE,sCAAsC,CACrE,KAAK,CAAC,+BAA+B,EACrC,KAAK,CAAC,YAAY,CACnB;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicyCurrent,\n VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { TrustedUserIdentity } from \"../trustedUserIdentity\";\n\nexport type ProjectionUserKey = TrustedUserIdentity;\n\nexport type ProjectionUserKeyResolver = (\n userId: string,\n) => Promise<ProjectionUserKey | null>;\n\nexport type PrincipalPolicyCache = Map<string, PrincipalPolicyCurrentEvidence>;\n\nexport interface PrincipalPolicyResolveRequest {\n /** Reuse authenticated local ancestry before an authorized online recovery. */\n readonly preferLocalHistory?: boolean | undefined;\n /** One recovery view: the warmer's operation unless a caller supplies its own. */\n readonly recoveryBatch?: object | undefined;\n readonly organizationId: string;\n readonly reference: ReferencedPrincipalHead;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ResolvedPrincipalPolicyEvidence {\n readonly stillCurrent: () => boolean;\n readonly organizationId: string;\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];\n}\n\nexport interface ReferencedPrincipalPolicyWarmRequest {\n readonly organizationId: string;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ProjectionPolicyHistoryResolveRequest {\n /** Authenticate terminal evidence first; its consumer must validate durable currency. */\n readonly historicalProof?: boolean | undefined;\n readonly organizationId: string;\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ResolvedProjectionPolicyHistory {\n readonly policies: readonly VerifiedPrincipalPolicySelection[];\n readonly stillCurrent: () => boolean;\n}\n\nexport type ReferencedPrincipalPolicyWarmer = ((\n input: ReferencedPrincipalPolicyWarmRequest,\n) => Promise<void>) & {\n readonly resolveProjectionHistory?:\n | ((\n input: ProjectionPolicyHistoryResolveRequest,\n ) => Promise<ResolvedProjectionPolicyHistory>)\n | undefined;\n readonly resolveReference?:\n | ((\n input: PrincipalPolicyResolveRequest,\n ) => Promise<ResolvedPrincipalPolicyEvidence>)\n | undefined;\n};\n\nexport class ProjectionVerificationCancelledError extends Error {\n constructor() {\n super(\"Projection verification generation expired\");\n this.name = \"ProjectionVerificationCancelledError\";\n }\n}\n\nconst projectionVerificationCancellation =\n new ProjectionVerificationCancelledError();\n\nexport function isProjectionVerificationCancelledError(\n error: unknown,\n): error is ProjectionVerificationCancelledError {\n return error === projectionVerificationCancellation;\n}\n\nexport function rethrowProjectionVerificationCancelled(error: unknown): void {\n if (isProjectionVerificationCancelledError(error)) throw error;\n}\n\nexport async function nullOnProjectionVerificationCancellation<T>(\n operation: () => Promise<T>,\n): Promise<T | null> {\n try {\n return await operation();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return null;\n throw error;\n }\n}\n\nexport function assertProjectionVerificationCurrent(\n stillCurrent: (() => boolean) | undefined,\n): void {\n if (stillCurrent?.() === false) {\n throw projectionVerificationCancellation;\n }\n}\n\nexport function generationGuardedPrincipalPolicyWarmer(\n warmer: ReferencedPrincipalPolicyWarmer | undefined,\n stillCurrent: (() => boolean) | undefined,\n): ReferencedPrincipalPolicyWarmer | undefined {\n if (!warmer || !stillCurrent) return warmer;\n const guard =\n (operation: ReferencedPrincipalPolicyWarmer) =>\n async (input: ReferencedPrincipalPolicyWarmRequest) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await operation({ ...input, stillCurrent });\n assertProjectionVerificationCurrent(stillCurrent);\n };\n const guardWithCapabilities = (\n operation: ReferencedPrincipalPolicyWarmer,\n ): ReferencedPrincipalPolicyWarmer => {\n const guarded = guard(operation);\n const resolve = operation.resolveReference;\n const resolveProjectionHistory = operation.resolveProjectionHistory;\n return Object.assign(guarded, {\n ...(resolveProjectionHistory\n ? {\n resolveProjectionHistory: async (\n input: ProjectionPolicyHistoryResolveRequest,\n ) => {\n const current = () =>\n stillCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(current);\n const result = await resolveProjectionHistory({\n ...input,\n stillCurrent: current,\n });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n }\n : {}),\n ...(resolve\n ? {\n resolveReference: async (input: PrincipalPolicyResolveRequest) => {\n const current = () =>\n stillCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(current);\n const result = await resolve({ ...input, stillCurrent: current });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n }\n : {}),\n });\n };\n return guardWithCapabilities(warmer);\n}\n\nexport function withGenerationGuardedPolicyWarmer<\n Input extends {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n },\n>(input: Input): Input {\n return {\n ...input,\n warmReferencedPrincipalPolicies: generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n ),\n };\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAsGA,MAAM,OAAO,oCAAqC,SAAQ,KAAK;IAC7D;QACE,KAAK,CAAC,4CAA4C,CAAC,CAAC;QACpD,IAAI,CAAC,IAAI,GAAG,sCAAsC,CAAC;IACrD,CAAC;CACF;A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ACnB;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n PrincipalPolicyCheckpoint,\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicyCurrent,\n VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n ProjectionPolicyEvidenceResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport type { TrustedUserIdentity } from \"../trustedUserIdentity\";\n\nexport type ProjectionUserKey = TrustedUserIdentity;\n\nexport type ProjectionUserKeyResolver = (\n userId: string,\n) => Promise<ProjectionUserKey | null>;\n\nexport type PrincipalPolicyCache = Map<string, PrincipalPolicyCurrentEvidence>;\n\n/**\n * The cached principal policy bundles verification reads, supplied by the\n * caller so verification does not depend on Principal Policy's store. Each\n * method ensures the principal policy tables on the executor it was opened on.\n */\nexport interface PrincipalPolicyBundleReader {\n ensurePrincipalPolicyTables(): Promise<void>;\n loadPrincipalPolicyBundle(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<PrincipalPolicyBundleResponse | null>;\n /** The newest stored bundle containing exactly `reference`, never a guess. */\n loadPrincipalPolicyBundleForReference(\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n ): Promise<PrincipalPolicyBundleResponse | null>;\n}\n\n/**\n * Opens the bundle reader on one executor. Verification opens it on the\n * executor each read runs on, a locked transaction handle included, so every\n * read sees that executor's snapshot.\n */\nexport type OpenPrincipalPolicyBundleReader = (\n execSql: ExecSql,\n) => PrincipalPolicyBundleReader;\n\nexport interface PrincipalPolicyResolveRequest {\n /** Reuse authenticated local ancestry before an authorized online recovery. */\n readonly preferLocalHistory?: boolean | undefined;\n /** One recovery view: the warmer's operation unless a caller supplies its own. */\n readonly recoveryBatch?: object | undefined;\n readonly organizationId: string;\n readonly reference: ReferencedPrincipalHead;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ResolvedPrincipalPolicyEvidence {\n readonly stillCurrent: () => boolean;\n readonly organizationId: string;\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];\n}\n\nexport interface ReferencedPrincipalPolicyWarmRequest {\n readonly organizationId: string;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ProjectionPolicyHistoryResolveRequest {\n /** Authenticate terminal evidence first; its consumer must validate durable currency. */\n readonly historicalProof?: boolean | undefined;\n readonly organizationId: string;\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ResolvedProjectionPolicyHistory {\n readonly policies: readonly VerifiedPrincipalPolicySelection[];\n readonly stillCurrent: () => boolean;\n}\n\nexport type ReferencedPrincipalPolicyWarmer = ((\n input: ReferencedPrincipalPolicyWarmRequest,\n) => Promise<void>) & {\n readonly resolveProjectionHistory?:\n | ((\n input: ProjectionPolicyHistoryResolveRequest,\n ) => Promise<ResolvedProjectionPolicyHistory>)\n | undefined;\n readonly resolveReference?:\n | ((\n input: PrincipalPolicyResolveRequest,\n ) => Promise<ResolvedPrincipalPolicyEvidence>)\n | undefined;\n};\n\nexport class ProjectionVerificationCancelledError extends Error {\n constructor() {\n super(\"Projection verification generation expired\");\n this.name = \"ProjectionVerificationCancelledError\";\n }\n}\n\nconst projectionVerificationCancellation =\n new ProjectionVerificationCancelledError();\n\nexport function isProjectionVerificationCancelledError(\n error: unknown,\n): error is ProjectionVerificationCancelledError {\n return error === projectionVerificationCancellation;\n}\n\nexport function rethrowProjectionVerificationCancelled(error: unknown): void {\n if (isProjectionVerificationCancelledError(error)) throw error;\n}\n\nexport async function nullOnProjectionVerificationCancellation<T>(\n operation: () => Promise<T>,\n): Promise<T | null> {\n try {\n return await operation();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return null;\n throw error;\n }\n}\n\nexport function assertProjectionVerificationCurrent(\n stillCurrent: (() => boolean) | undefined,\n): void {\n if (stillCurrent?.() === false) {\n throw projectionVerificationCancellation;\n }\n}\n\nexport function generationGuardedPrincipalPolicyWarmer(\n warmer: ReferencedPrincipalPolicyWarmer | undefined,\n stillCurrent: (() => boolean) | undefined,\n): ReferencedPrincipalPolicyWarmer | undefined {\n if (!warmer || !stillCurrent) return warmer;\n const guard =\n (operation: ReferencedPrincipalPolicyWarmer) =>\n async (input: ReferencedPrincipalPolicyWarmRequest) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await operation({ ...input, stillCurrent });\n assertProjectionVerificationCurrent(stillCurrent);\n };\n const guardWithCapabilities = (\n operation: ReferencedPrincipalPolicyWarmer,\n ): ReferencedPrincipalPolicyWarmer => {\n const guarded = guard(operation);\n const resolve = operation.resolveReference;\n const resolveProjectionHistory = operation.resolveProjectionHistory;\n return Object.assign(guarded, {\n ...(resolveProjectionHistory\n ? {\n resolveProjectionHistory: async (\n input: ProjectionPolicyHistoryResolveRequest,\n ) => {\n const current = () =>\n stillCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(current);\n const result = await resolveProjectionHistory({\n ...input,\n stillCurrent: current,\n });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n }\n : {}),\n ...(resolve\n ? {\n resolveReference: async (input: PrincipalPolicyResolveRequest) => {\n const current = () =>\n stillCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(current);\n const result = await resolve({ ...input, stillCurrent: current });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n }\n : {}),\n });\n };\n return guardWithCapabilities(warmer);\n}\n\nexport function withGenerationGuardedPolicyWarmer<\n Input extends {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n },\n>(input: Input): Input {\n return {\n ...input,\n warmReferencedPrincipalPolicies: generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n ),\n };\n}\n"]}
@@ -177,4 +177,6 @@ export class PrincipalPolicyBundleRepository {
177
177
  await runtime.transaction(body, { behavior: "immediate" });
178
178
  }
179
179
  }
180
+ /** The bundle store Keying Verification reads, opened on one executor. */
181
+ export const openPrincipalPolicyBundleReader = (execSql) => new PrincipalPolicyBundleRepository(execSql);
180
182
  //# sourceMappingURL=principalPolicyBundleRepository.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyBundleRepository.js","sourceRoot":"","sources":["principalPolicyBundleRepository.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAAE,8BAA8B,EAAE,MAAM,oDAAoD,CAAC;AACpG,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEvE,OAAO,EAEL,oCAAoC,GACrC,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EACL,+CAA+C,EAI/C,2DAA2D,GAC5D,MAAM,iDAAiD,CAAC;AACzD,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAC9B,wCAAwC,EACxC,2BAA2B,EAC3B,uCAAuC,GACxC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,oBAAoB,EACpB,qCAAqC,GACtC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EACL,oCAAoC,EACpC,kDAAkD,GAEnD,MAAM,4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AAqB;YACxB,GAAG,sBAAsB;SAC1B,CAAC,CAAC;QACH,MAAM,IAAI,CAAC,YAAY,CACrB,CAAC,EAAE,EAAE,EAAE,CACL,2DAA2D,CACzD,EAAE,EACF,KAAK,EACL,IAAI,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CACzB,EACH,KAAK,CAAC,YAAY,CACnB,CAAC;IACJ,CAAC;IAED,8EAA8E;IACtE,KAAK,CAAC,YAAY,CACxB,IAAyD,EACzD,YAAyC;QAEzC,MAAM,OAAO,GAAG,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAChE,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,OAAO,CAAC,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE;gBACnD,QAAQ,EAAE,WAAW;aACtB,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF","sourcesContent":["import type {\n PrincipalPolicyCheckpoint,\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { asc, desc } from \"drizzle-orm\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalHistoryEvidenceTables } from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport {\n principalPolicyBundles,\n principalPolicyTables,\n} from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalGrantRetirements } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n type PrincipalKeyEnvelopeCandidate,\n selectPrincipalKeyEnvelopeCandidates,\n} from \"../principalKeys/principalKeyEnvelopeCandidates\";\nimport { selectHeldPrincipalState } from \"./heldPrincipalState\";\nimport {\n assertLocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyBundle,\n type LocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyStore,\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction,\n} from \"./locallyAcknowledgedPrincipalPolicyPersistence\";\nimport {\n parseSelectedPrincipalPolicyBundle,\n principalPolicyBundleSelection,\n retainPrincipalPolicyBundleInTransaction,\n wherePrincipalPolicyCurrent,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport {\n assertReferenceShape,\n selectReferencedPrincipalPolicyBundle,\n} from \"./principalPolicyReferencePersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\nimport {\n assertVerifiedPrincipalPolicyBundles,\n persistVerifiedPrincipalPolicyBundlesInTransaction,\n type VerifiedPrincipalPolicyBundleEntry,\n} from \"./verifiedPrincipalPolicyBundlePersistence\";\n\n/**\n * The cached principal policy bundles, current heads and retained epochs, and\n * the member key envelopes they carry, bound to one executor and clock. Each\n * method ensures its tables; each writer runs its own immediate transaction\n * and silently skips a commit its `stillCurrent` refuses. Work inside a\n * caller's transaction takes the locked handle per call through the\n * `*InTransaction` functions instead.\n */\nexport class PrincipalPolicyBundleRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n async ensurePrincipalPolicyTables(): Promise<void> {\n await ensureSqlTables(this.execSql, principalPolicyTables);\n }\n\n async loadPrincipalPolicyBundle(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row ? parseSelectedPrincipalPolicyBundle(row) : null;\n }\n\n /** Current heads first, then retained bundles. */\n async loadAllPrincipalPolicyBundles(): Promise<\n PrincipalPolicyBundleResponse[]\n > {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .orderBy(\n desc(principalPolicyBundles.isCurrent),\n asc(principalPolicyBundles.principalType),\n asc(principalPolicyBundles.principalId),\n asc(principalPolicyBundles.stateHash),\n );\n const bundles: PrincipalPolicyBundleResponse[] = [];\n for (const row of rows) {\n const bundle = parseSelectedPrincipalPolicyBundle(row);\n if (bundle) bundles.push(bundle);\n }\n return bundles;\n }\n\n async loadPrincipalPolicyStateHash(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<string | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select({ stateHash: principalPolicyBundles.stateHash })\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row?.stateHash ?? null;\n }\n\n /** The newest stored bundle containing exactly `reference`, never a guess. */\n async loadPrincipalPolicyBundleForReference(\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectReferencedPrincipalPolicyBundle(db, reference, checkpoint);\n }\n\n /**\n * A signed state this device stored for exactly `head`: history evidence it\n * verified or acknowledged, or a cached policy bundle chain. It is untrusted;\n * the caller verifies it as it would a served copy, and a miss only means the\n * server sends one.\n */\n async loadHeldPrincipalState(\n head: ReferencedPrincipalHead,\n ): Promise<PrincipalStateResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectHeldPrincipalState(db, head);\n }\n\n /**\n * Untrusted encrypted key candidates, never authorization evidence. The actual\n * private key must open the requested recipient wrap; the projection verifier\n * separately checks the signed KEK material identity and all policy authority.\n * Read only envelopes for the requested fingerprints, never signed histories.\n */\n async loadPrincipalKeyEnvelopeCandidates(\n fingerprints: readonly string[],\n ): Promise<PrincipalKeyEnvelopeCandidate[]> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...principalHistoryEvidenceTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectPrincipalKeyEnvelopeCandidates(db, fingerprints);\n }\n\n async savePrincipalPolicyBundle(\n bundle: PrincipalPolicyBundleResponse,\n organizationId: string,\n options?: { stillCurrent?: (() => boolean) | undefined } | undefined,\n ): Promise<void> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n writePrincipalPolicyBundleInTransaction(\n tx,\n bundle,\n this.now().toISOString(),\n organizationId,\n ),\n options?.stillCurrent,\n );\n }\n\n /**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\n async persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n }): Promise<void> {\n await assertVerifiedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n persistVerifiedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /**\n * Retains a just-verified epoch without promoting it to the mutable head.\n * `updatedAt` stays explicit: callers stamp a whole retention walk at once.\n */\n async retainVerifiedPrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly organizationId?: string | undefined;\n readonly policy: VerifiedPrincipalPolicy;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n }): Promise<void> {\n await assertBundleMatchesVerifiedPolicy(input);\n await this.ensurePrincipalPolicyTables();\n await this.runImmediate(\n (tx) =>\n retainPrincipalPolicyBundleInTransaction(\n tx,\n input.bundle,\n input.updatedAt,\n input.organizationId,\n ),\n input.stillCurrent,\n );\n }\n\n /** Atomically pins and caches exact full policy bundles acknowledged by the API. */\n persistLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"current\",\n });\n }\n\n persistLocallyAcknowledgedPrincipalPolicyBundle(\n input: LocallyAcknowledgedPrincipalPolicyBundle & {\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n return this.persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input],\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n }\n\n /**\n * Seed a provisioning acknowledgement without making genesis current again.\n * The cache writer still checks ownership, equal-version forks and retained\n * same-hash bundle integrity, and preserves any newer cached policy head.\n */\n seedLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"genesis\",\n });\n }\n\n retainLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles & {\n readonly retiredContainers?:\n | AcknowledgedPrincipalGrantRetirements\n | undefined;\n },\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"history\",\n });\n }\n\n private async storeLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyStore & {\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n await assertLocallyAcknowledgedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /** Guarded when `stillCurrent` is given; a refused commit is not an error. */\n private async runImmediate(\n body: (tx: ClientSQLiteTransactionScope) => Promise<void>,\n stillCurrent: (() => boolean) | undefined,\n ): Promise<void> {\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n if (stillCurrent) {\n await runtime.guardedTransaction(body, stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(body, { behavior: \"immediate\" });\n }\n}\n"]}
1
+ {"version":3,"file":"principalPolicyBundleRepository.js","sourceRoot":"","sources":["principalPolicyBundleRepository.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAAE,8BAA8B,EAAE,MAAM,oDAAoD,CAAC;AACpG,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEvE,OAAO,EAEL,oCAAoC,GACrC,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EACL,+CAA+C,EAI/C,2DAA2D,GAC5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,CAAC;IACL,CAAC;IAED,+CAA+C,CAC7C,KAIC;QAED,OAAO,IAAI,CAAC,8CAA8C,CAAC;YACzD,GAAG,KAAK;YACR,SAAS,EAAE,SAAS;SACrB,CAAC,CAAC;IACL,CAAC;IAEO,KAAK,CAAC,8CAA8C,CAC1D,KAEC;QAED,MAAM,+CAA+C,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACrE,MAAM,eAAe,CAAC,IAAI,CAAC,OAAO,EAAE;YAClC,GAAG,qBAAqB;YACxB,GAAG,sBAAsB;SAC1B,CAAC,CAAC;QACH,MAAM,IAAI,CAAC,YAAY,CACrB,CAAC,EAAE,EAAE,EAAE,CACL,2DAA2D,CACzD,EAAE,EACF,KAAK,EACL,IAAI,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CACzB,EACH,KAAK,CAAC,YAAY,CACnB,CAAC;IACJ,CAAC;IAED,8EAA8E;IACtE,KAAK,CAAC,YAAY,CACxB,IAAyD,EACzD,YAAyC;QAEzC,MAAM,OAAO,GAAG,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAChE,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,OAAO,CAAC,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE;gBACnD,QAAQ,EAAE,WAAW;aACtB,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF;AAED,0EAA0E;AAC1E,MAAM,CAAC,MAAM,+BAA+B,GAC1C,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,+BAA+B,CAAC,OAAO,CAAC,CAAC","sourcesContent":["import type {\n PrincipalPolicyCheckpoint,\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { asc, desc } from \"drizzle-orm\";\nimport type { OpenPrincipalPolicyBundleReader } from \"../../keyingProjectionVerification/types\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalHistoryEvidenceTables } from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport {\n principalPolicyBundles,\n principalPolicyTables,\n} from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalGrantRetirements } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n type PrincipalKeyEnvelopeCandidate,\n selectPrincipalKeyEnvelopeCandidates,\n} from \"../principalKeys/principalKeyEnvelopeCandidates\";\nimport { selectHeldPrincipalState } from \"./heldPrincipalState\";\nimport {\n assertLocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyBundle,\n type LocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyStore,\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction,\n} from \"./locallyAcknowledgedPrincipalPolicyPersistence\";\nimport {\n parseSelectedPrincipalPolicyBundle,\n principalPolicyBundleSelection,\n retainPrincipalPolicyBundleInTransaction,\n wherePrincipalPolicyCurrent,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport {\n assertReferenceShape,\n selectReferencedPrincipalPolicyBundle,\n} from \"./principalPolicyReferencePersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\nimport {\n assertVerifiedPrincipalPolicyBundles,\n persistVerifiedPrincipalPolicyBundlesInTransaction,\n type VerifiedPrincipalPolicyBundleEntry,\n} from \"./verifiedPrincipalPolicyBundlePersistence\";\n\n/**\n * The cached principal policy bundles, current heads and retained epochs, and\n * the member key envelopes they carry, bound to one executor and clock. Each\n * method ensures its tables; each writer runs its own immediate transaction\n * and silently skips a commit its `stillCurrent` refuses. Work inside a\n * caller's transaction takes the locked handle per call through the\n * `*InTransaction` functions instead.\n */\nexport class PrincipalPolicyBundleRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n async ensurePrincipalPolicyTables(): Promise<void> {\n await ensureSqlTables(this.execSql, principalPolicyTables);\n }\n\n async loadPrincipalPolicyBundle(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row ? parseSelectedPrincipalPolicyBundle(row) : null;\n }\n\n /** Current heads first, then retained bundles. */\n async loadAllPrincipalPolicyBundles(): Promise<\n PrincipalPolicyBundleResponse[]\n > {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .orderBy(\n desc(principalPolicyBundles.isCurrent),\n asc(principalPolicyBundles.principalType),\n asc(principalPolicyBundles.principalId),\n asc(principalPolicyBundles.stateHash),\n );\n const bundles: PrincipalPolicyBundleResponse[] = [];\n for (const row of rows) {\n const bundle = parseSelectedPrincipalPolicyBundle(row);\n if (bundle) bundles.push(bundle);\n }\n return bundles;\n }\n\n async loadPrincipalPolicyStateHash(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<string | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select({ stateHash: principalPolicyBundles.stateHash })\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row?.stateHash ?? null;\n }\n\n /** The newest stored bundle containing exactly `reference`, never a guess. */\n async loadPrincipalPolicyBundleForReference(\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectReferencedPrincipalPolicyBundle(db, reference, checkpoint);\n }\n\n /**\n * A signed state this device stored for exactly `head`: history evidence it\n * verified or acknowledged, or a cached policy bundle chain. It is untrusted;\n * the caller verifies it as it would a served copy, and a miss only means the\n * server sends one.\n */\n async loadHeldPrincipalState(\n head: ReferencedPrincipalHead,\n ): Promise<PrincipalStateResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectHeldPrincipalState(db, head);\n }\n\n /**\n * Untrusted encrypted key candidates, never authorization evidence. The actual\n * private key must open the requested recipient wrap; the projection verifier\n * separately checks the signed KEK material identity and all policy authority.\n * Read only envelopes for the requested fingerprints, never signed histories.\n */\n async loadPrincipalKeyEnvelopeCandidates(\n fingerprints: readonly string[],\n ): Promise<PrincipalKeyEnvelopeCandidate[]> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...principalHistoryEvidenceTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectPrincipalKeyEnvelopeCandidates(db, fingerprints);\n }\n\n async savePrincipalPolicyBundle(\n bundle: PrincipalPolicyBundleResponse,\n organizationId: string,\n options?: { stillCurrent?: (() => boolean) | undefined } | undefined,\n ): Promise<void> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n writePrincipalPolicyBundleInTransaction(\n tx,\n bundle,\n this.now().toISOString(),\n organizationId,\n ),\n options?.stillCurrent,\n );\n }\n\n /**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\n async persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n }): Promise<void> {\n await assertVerifiedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n persistVerifiedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /**\n * Retains a just-verified epoch without promoting it to the mutable head.\n * `updatedAt` stays explicit: callers stamp a whole retention walk at once.\n */\n async retainVerifiedPrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly organizationId?: string | undefined;\n readonly policy: VerifiedPrincipalPolicy;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n }): Promise<void> {\n await assertBundleMatchesVerifiedPolicy(input);\n await this.ensurePrincipalPolicyTables();\n await this.runImmediate(\n (tx) =>\n retainPrincipalPolicyBundleInTransaction(\n tx,\n input.bundle,\n input.updatedAt,\n input.organizationId,\n ),\n input.stillCurrent,\n );\n }\n\n /** Atomically pins and caches exact full policy bundles acknowledged by the API. */\n persistLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"current\",\n });\n }\n\n persistLocallyAcknowledgedPrincipalPolicyBundle(\n input: LocallyAcknowledgedPrincipalPolicyBundle & {\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n return this.persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input],\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n }\n\n /**\n * Seed a provisioning acknowledgement without making genesis current again.\n * The cache writer still checks ownership, equal-version forks and retained\n * same-hash bundle integrity, and preserves any newer cached policy head.\n */\n seedLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"genesis\",\n });\n }\n\n retainLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles & {\n readonly retiredContainers?:\n | AcknowledgedPrincipalGrantRetirements\n | undefined;\n },\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"history\",\n });\n }\n\n private async storeLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyStore & {\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n await assertLocallyAcknowledgedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /** Guarded when `stillCurrent` is given; a refused commit is not an error. */\n private async runImmediate(\n body: (tx: ClientSQLiteTransactionScope) => Promise<void>,\n stillCurrent: (() => boolean) | undefined,\n ): Promise<void> {\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n if (stillCurrent) {\n await runtime.guardedTransaction(body, stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(body, { behavior: \"immediate\" });\n }\n}\n\n/** The bundle store Keying Verification reads, opened on one executor. */\nexport const openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader =\n (execSql) => new PrincipalPolicyBundleRepository(execSql);\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.223",
3
+ "version": "0.1.225",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1,6 +1,6 @@
1
1
  import { removeOrganizationContentUnlessPending } from "../../../workflows/container-contents/syncPause/documentRemoval.js";
2
2
  import { reclaimDocumentOrphanBlobs } from "../../../workflows/documents/index.js";
3
- import { getOrCreateOrganizationSyncPauses, isRetainedWhileSyncPaused, } from "../../../workflows/sync/index.js";
3
+ import { getOrCreateOrganizationSyncPauses, isRetainedWhileSyncPaused, } from "../../../workflows/sync/coordination.js";
4
4
  import { emitPersistedDocumentDeletion, hasQueuedDocumentStoreWrites, restoreDocumentStore, retireDocumentStore, } from "../../documents/registry.js";
5
5
  import { updateContainerContentsSnapshot } from "../state.js";
6
6
  /** The local containers forgetting an organization's content removes. */
@@ -1 +1 @@
1
- {"version":3,"file":"forgetOrganizationContentOperation.js","sourceRoot":"","sources":["forgetOrganizationContentOperation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sCAAsC,EAAE,MAAM,iEAAiE,CAAC;AACzH,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EACL,iCAAiC,EACjC,yBAAyB,GAC1B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,EAC5B,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,+BAA+B,EAAE,MAAM,UAAU,CAAC;AAG3D,yEAAyE;AACzE,SAAS,uCAAuC,CAC9C,KAA0D,EAC1D,cAAsB;IAEtB,OAAO,CAAC,GAAG,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,EAAE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ACzC,KAAK,EACL,cAAc,EACd,SAAS,CACV,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC,EACD,uCAAuC,CAAC,KAAK,EAAE,cAAc,CAAC,CAC/D,CAAC;QACF,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { removeOrganizationContentUnlessPending } from \"../../../workflows/container-contents/syncPause/documentRemoval\";\nimport { reclaimDocumentOrphanBlobs } from \"../../../workflows/documents\";\nimport {\n getOrCreateOrganizationSyncPauses,\n isRetainedWhileSyncPaused,\n} from \"../../../workflows/sync\";\nimport {\n emitPersistedDocumentDeletion,\n hasQueuedDocumentStoreWrites,\n restoreDocumentStore,\n retireDocumentStore,\n} from \"../../documents/registry\";\nimport type { ContainerWriteGuard } from \"../remoteWrites/writeGeneration\";\nimport { updateContainerContentsSnapshot } from \"../state\";\nimport type { ContainerContentsStoreState } from \"../types\";\n\n/** The local containers forgetting an organization's content removes. */\nfunction listForgettableOrganizationContainerIds(\n state: Pick<ContainerContentsStoreState, \"containersById\">,\n organizationId: string,\n): string[] {\n return [...state.containersById.values()].flatMap(({ container }) =>\n container.organizationId === organizationId &&\n !isRetainedWhileSyncPaused(container)\n ? [container.id]\n : [],\n );\n}\n\n/**\n * Removes one organization's content from this device after its sync was\n * paused: every container except its retained metadata root, and every\n * document placed only in those containers. Nothing changes on the server, so\n * resuming downloads it again.\n *\n * Unsynced work is never removed: the removal refuses while any pending write\n * touches the organization, checked under the same lock as the deletions, and\n * while an open store holds edits for any of its documents that have not\n * reached SQLite. It also refuses the session's active organization, whose\n * root the session still writes to. Returns whether nothing is left to retry.\n */\nasync function forgetOrganizationContent(\n state: ContainerContentsStoreState,\n organizationId: string,\n isCurrent: ContainerWriteGuard,\n): Promise<boolean> {\n if (state.runtime.infra.dbStatus !== \"ready\" || !state.snapshot.ready) {\n return false;\n }\n if (state.runtime.auth.organizationId === organizationId) return false;\n const containerIds = listForgettableOrganizationContainerIds(\n state,\n organizationId,\n );\n const { documentProjectors, execSql } = state.runtime.infra;\n const { domainScope } = state.runtime.state;\n // Switching into the organization mid-removal stops it before any deletion.\n const stillCurrent = () =>\n isCurrent() && state.runtime.auth.organizationId !== organizationId;\n await state.persistence.ensureSchema(execSql);\n const pauses = getOrCreateOrganizationSyncPauses(domainScope);\n const removal = await removeOrganizationContentUnlessPending({\n containerIds,\n deleteContainers: (lockedExecSql, removals) =>\n state.persistence.deleteContainers(lockedExecSql, removals, {\n stillCurrent,\n }),\n documentProjectors,\n execSql,\n hasQueuedWrites: (localId) =>\n hasQueuedDocumentStoreWrites(domainScope, localId),\n organizationId,\n restoreDocument: (localId) => restoreDocumentStore(domainScope, localId),\n retireDocument: (localId) =>\n retireDocumentStore(domainScope, localId, () =>\n pauses.isOrganizationPaused(organizationId),\n ),\n stillCurrent,\n });\n for (const localId of removal.deletedLocalIds) {\n emitPersistedDocumentDeletion(domainScope, localId);\n }\n if (removal.deletedLocalIds.length > 0) {\n void reclaimDocumentOrphanBlobs(state.runtime);\n }\n for (const containerId of removal.deletedContainerIds) {\n state.containersById.delete(containerId);\n }\n if (removal.deletedContainerIds.length > 0 && state.initialized) {\n updateContainerContentsSnapshot(state);\n }\n return removal.status === \"removed\";\n}\n\ntype ContainerWriteChain = (\n state: ContainerContentsStoreState,\n work: (isCurrent: () => boolean) => ContainerContentsStoreState[\"writeChain\"],\n changedIds: readonly string[],\n) => ContainerContentsStoreState[\"writeChain\"];\n\n/** Runs `forgetOrganizationContent` in the store's container write chain. */\nexport function createForgetOrganizationContentMethod(\n state: ContainerContentsStoreState,\n chainContainerWrite: ContainerWriteChain,\n): (organizationId: string) => Promise<boolean> {\n return async (organizationId) => {\n let forgotten = false;\n await chainContainerWrite(\n state,\n async (isCurrent) => {\n forgotten = await forgetOrganizationContent(\n state,\n organizationId,\n isCurrent,\n );\n return null;\n },\n listForgettableOrganizationContainerIds(state, organizationId),\n );\n return forgotten;\n };\n}\n"]}
1
+ {"version":3,"file":"forgetOrganizationContentOperation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B,EAAE,CAAC;QACtD,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC3C,CAAC;IACD,IAAI,OAAO,CAAC,mBAAmB,CAAC,MAAM,GAAG,CAAC,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;QAChE,+BAA+B,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,OAAO,CAAC,MAAM,KAAK,SAAS,CAAC;AACtC,CAAC;AAQD,6EAA6E;AAC7E,MAAM,UAAU,qCAAqC,CACnD,KAAkC,EAClC,mBAAwC;IAExC,OAAO,KAAK,EAAE,cAAc,EAAE,EAAE;QAC9B,IAAI,SAAS,GAAG,KAAK,CAAC;QACtB,MAAM,mBAAmB,CACvB,KAAK,EACL,KAAK,EAAE,SAAS,EAAE,EAAE;YAClB,SAAS,GAAG,MAAM,yBAAyB,CACzC,KAAK,EACL,cAAc,EACd,SAAS,CACV,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC,EACD,uCAAuC,CAAC,KAAK,EAAE,cAAc,CAAC,CAC/D,CAAC;QACF,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { removeOrganizationContentUnlessPending } from \"../../../workflows/container-contents/syncPause/documentRemoval\";\nimport { reclaimDocumentOrphanBlobs } from \"../../../workflows/documents\";\nimport {\n getOrCreateOrganizationSyncPauses,\n isRetainedWhileSyncPaused,\n} from \"../../../workflows/sync/coordination\";\nimport {\n emitPersistedDocumentDeletion,\n hasQueuedDocumentStoreWrites,\n restoreDocumentStore,\n retireDocumentStore,\n} from \"../../documents/registry\";\nimport type { ContainerWriteGuard } from \"../remoteWrites/writeGeneration\";\nimport { updateContainerContentsSnapshot } from \"../state\";\nimport type { ContainerContentsStoreState } from \"../types\";\n\n/** The local containers forgetting an organization's content removes. */\nfunction listForgettableOrganizationContainerIds(\n state: Pick<ContainerContentsStoreState, \"containersById\">,\n organizationId: string,\n): string[] {\n return [...state.containersById.values()].flatMap(({ container }) =>\n container.organizationId === organizationId &&\n !isRetainedWhileSyncPaused(container)\n ? [container.id]\n : [],\n );\n}\n\n/**\n * Removes one organization's content from this device after its sync was\n * paused: every container except its retained metadata root, and every\n * document placed only in those containers. Nothing changes on the server, so\n * resuming downloads it again.\n *\n * Unsynced work is never removed: the removal refuses while any pending write\n * touches the organization, checked under the same lock as the deletions, and\n * while an open store holds edits for any of its documents that have not\n * reached SQLite. It also refuses the session's active organization, whose\n * root the session still writes to. Returns whether nothing is left to retry.\n */\nasync function forgetOrganizationContent(\n state: ContainerContentsStoreState,\n organizationId: string,\n isCurrent: ContainerWriteGuard,\n): Promise<boolean> {\n if (state.runtime.infra.dbStatus !== \"ready\" || !state.snapshot.ready) {\n return false;\n }\n if (state.runtime.auth.organizationId === organizationId) return false;\n const containerIds = listForgettableOrganizationContainerIds(\n state,\n organizationId,\n );\n const { documentProjectors, execSql } = state.runtime.infra;\n const { domainScope } = state.runtime.state;\n // Switching into the organization mid-removal stops it before any deletion.\n const stillCurrent = () =>\n isCurrent() && state.runtime.auth.organizationId !== organizationId;\n await state.persistence.ensureSchema(execSql);\n const pauses = getOrCreateOrganizationSyncPauses(domainScope);\n const removal = await removeOrganizationContentUnlessPending({\n containerIds,\n deleteContainers: (lockedExecSql, removals) =>\n state.persistence.deleteContainers(lockedExecSql, removals, {\n stillCurrent,\n }),\n documentProjectors,\n execSql,\n hasQueuedWrites: (localId) =>\n hasQueuedDocumentStoreWrites(domainScope, localId),\n organizationId,\n restoreDocument: (localId) => restoreDocumentStore(domainScope, localId),\n retireDocument: (localId) =>\n retireDocumentStore(domainScope, localId, () =>\n pauses.isOrganizationPaused(organizationId),\n ),\n stillCurrent,\n });\n for (const localId of removal.deletedLocalIds) {\n emitPersistedDocumentDeletion(domainScope, localId);\n }\n if (removal.deletedLocalIds.length > 0) {\n void reclaimDocumentOrphanBlobs(state.runtime);\n }\n for (const containerId of removal.deletedContainerIds) {\n state.containersById.delete(containerId);\n }\n if (removal.deletedContainerIds.length > 0 && state.initialized) {\n updateContainerContentsSnapshot(state);\n }\n return removal.status === \"removed\";\n}\n\ntype ContainerWriteChain = (\n state: ContainerContentsStoreState,\n work: (isCurrent: () => boolean) => ContainerContentsStoreState[\"writeChain\"],\n changedIds: readonly string[],\n) => ContainerContentsStoreState[\"writeChain\"];\n\n/** Runs `forgetOrganizationContent` in the store's container write chain. */\nexport function createForgetOrganizationContentMethod(\n state: ContainerContentsStoreState,\n chainContainerWrite: ContainerWriteChain,\n): (organizationId: string) => Promise<boolean> {\n return async (organizationId) => {\n let forgotten = false;\n await chainContainerWrite(\n state,\n async (isCurrent) => {\n forgotten = await forgetOrganizationContent(\n state,\n organizationId,\n isCurrent,\n );\n return null;\n },\n listForgettableOrganizationContainerIds(state, organizationId),\n );\n return forgotten;\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { beginDomainSyncUploadLane, } from "../../../../workflows/sync/index.js";
1
+ import { beginDomainSyncUploadLane, } from "../../../../workflows/sync/coordination.js";
2
2
  function getAttachmentUploadLaneLabel(name) {
3
3
  return name ? `Upload ${name}` : "Attachment upload";
4
4
  }
@@ -1 +1 @@
1
- {"version":3,"file":"attachmentUploadLane.js","sourceRoot":"","sources":["attachmentUploadLane.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,yBAAyB,GAE1B,MAAM,4BAA4B,CAAC;AASpC,SAAS,4BAA4B,CAAC,IAA+B;IACnE,OAAO,IAAI,CAAC,CAAC,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC,CAAC,mBAAmB,CAAC;AACvD,CAAC;AAED,SAAS,gCAAgC,CACvC,iBAA0C;IAE1C,OAAO,iBAAiB,CAAC,IAAI;QAC3B,CAAC,CAAC,GAAG,iBAAiB,CAAC,IAAI,UAAU,iBAAiB,CAAC,MAAM,GAAG;QAChE,CAAC,CAAC,QAAQ,iBAAiB,CAAC,MAAM,EAAE,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,iBAA0C,EAC1C,KAAc;IAEd,MAAM,KAAK,GAAG,IAAI,KAAK,CACrB,gCAAgC,gCAAgC,CAAC,iBAAiB,CAAC,GAAG,CACvF,CAAC;IACF,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IAE5D,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kCAAkC,CAAC,KAIlD;IACC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC;IACzD,MAAM,OAAO,GAAuC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAEtE,MAAM,UAAU,GAAG,GAAmB,EAAE;QACtC,OAAO,CAAC,OAAO,KAAK,yBAAyB,CAC3C,WAAW,EACX,eAAe,MAAM,EAAE,EACvB;YACE,cAAc,EAAE,iBAAiB,CAAC,UAAU;YAC5C,KAAK,EAAE,4BAA4B,CAAC,iBAAiB,CAAC,IAAI,CAAC;SAC5D,CACF,CAAC;QACF,OAAO,OAAO,CAAC,OAAO,CAAC;IACzB,CAAC,CAAC;IAEF,OAAO;QACL,QAAQ;YACN,oEAAoE;YACpE,8DAA8D;YAC9D,UAAU,EAAE,CAAC,QAAQ,EAAE,CAAC;QAC1B,CAAC;QACD,IAAI,CAAC,KAAc;YACjB,UAAU,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC3B,CAAC;QACD,aAAa,CAAC,KAAc;YAC1B,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAC/B,CAAC;QACD,mBAAmB,CAAC,QAAQ;YAC1B,UAAU,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;QACxC,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../../../data/shared/domainScope\";\nimport type { MultipartUploadProgressListener } from \"../../../../workflows/blobs\";\nimport type { PendingAttachmentRecord } from \"../../../../workflows/documents\";\nimport {\n beginDomainSyncUploadLane,\n type UploadSyncLane,\n} from \"../../../../workflows/sync\";\n\nexport interface AttachmentUploadLaneReporter {\n complete: () => void;\n fail: (error: unknown) => void;\n failIfStarted: (error: unknown) => void;\n onMultipartProgress: MultipartUploadProgressListener;\n}\n\nfunction getAttachmentUploadLaneLabel(name: string | null | undefined): string {\n return name ? `Upload ${name}` : \"Attachment upload\";\n}\n\nfunction getAttachmentUploadFailureTarget(\n pendingAttachment: PendingAttachmentRecord,\n): string {\n return pendingAttachment.name\n ? `${pendingAttachment.name} (slot ${pendingAttachment.slotId})`\n : `slot ${pendingAttachment.slotId}`;\n}\n\nexport function createAttachmentUploadFailedError(\n pendingAttachment: PendingAttachmentRecord,\n cause: unknown,\n): Error {\n const error = new Error(\n `Attachment upload failed for ${getAttachmentUploadFailureTarget(pendingAttachment)}.`,\n );\n if (cause !== undefined) Reflect.set(error, \"cause\", cause);\n\n return error;\n}\n\n/**\n * Surfaces attachment uploads as observational lanes. The persisted blob id is\n * the lane identity: slot ids repeat across documents, while a retry must keep\n * updating the same row. Lane creation stays lazy until progress, failure, or\n * completion so a billing block before any upload work does not add noise.\n */\nexport function createAttachmentUploadLaneReporter(input: {\n blobId: string;\n domainScope: DomainScope;\n pendingAttachment: PendingAttachmentRecord;\n}): AttachmentUploadLaneReporter {\n const { blobId, domainScope, pendingAttachment } = input;\n const laneRef: { current: UploadSyncLane | null } = { current: null };\n\n const ensureLane = (): UploadSyncLane => {\n laneRef.current ??= beginDomainSyncUploadLane(\n domainScope,\n `blob-upload:${blobId}`,\n {\n blobStorageKey: pendingAttachment.storageKey,\n label: getAttachmentUploadLaneLabel(pendingAttachment.name),\n },\n );\n return laneRef.current;\n };\n\n return {\n complete() {\n // Completion must create/re-begin the lane too: a resumed stage can\n // already be complete before it emits any per-part callbacks.\n ensureLane().complete();\n },\n fail(error: unknown) {\n ensureLane().fail(error);\n },\n failIfStarted(error: unknown) {\n laneRef.current?.fail(error);\n },\n onMultipartProgress(progress) {\n ensureLane().reportProgress(progress);\n },\n };\n}\n"]}
1
+ {"version":3,"file":"attachmentUploadLane.js","sourceRoot":"","sources":["attachmentUploadLane.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,yBAAyB,GAE1B,MAAM,yCAAyC,CAAC;AASjD,SAAS,4BAA4B,CAAC,IAA+B;IACnE,OAAO,IAAI,CAAC,CAAC,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC,CAAC,mBAAmB,CAAC;AACvD,CAAC;AAED,SAAS,gCAAgC,CACvC,iBAA0C;IAE1C,OAAO,iBAAiB,CAAC,IAAI;QAC3B,CAAC,CAAC,GAAG,iBAAiB,CAAC,IAAI,UAAU,iBAAiB,CAAC,MAAM,GAAG;QAChE,CAAC,CAAC,QAAQ,iBAAiB,CAAC,MAAM,EAAE,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,iBAA0C,EAC1C,KAAc;IAEd,MAAM,KAAK,GAAG,IAAI,KAAK,CACrB,gCAAgC,gCAAgC,CAAC,iBAAiB,CAAC,GAAG,CACvF,CAAC;IACF,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IAE5D,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kCAAkC,CAAC,KAIlD;IACC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC;IACzD,MAAM,OAAO,GAAuC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAEtE,MAAM,UAAU,GAAG,GAAmB,EAAE;QACtC,OAAO,CAAC,OAAO,KAAK,yBAAyB,CAC3C,WAAW,EACX,eAAe,MAAM,EAAE,EACvB;YACE,cAAc,EAAE,iBAAiB,CAAC,UAAU;YAC5C,KAAK,EAAE,4BAA4B,CAAC,iBAAiB,CAAC,IAAI,CAAC;SAC5D,CACF,CAAC;QACF,OAAO,OAAO,CAAC,OAAO,CAAC;IACzB,CAAC,CAAC;IAEF,OAAO;QACL,QAAQ;YACN,oEAAoE;YACpE,8DAA8D;YAC9D,UAAU,EAAE,CAAC,QAAQ,EAAE,CAAC;QAC1B,CAAC;QACD,IAAI,CAAC,KAAc;YACjB,UAAU,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC3B,CAAC;QACD,aAAa,CAAC,KAAc;YAC1B,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAC/B,CAAC;QACD,mBAAmB,CAAC,QAAQ;YAC1B,UAAU,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;QACxC,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../../../data/shared/domainScope\";\nimport type { MultipartUploadProgressListener } from \"../../../../workflows/blobs\";\nimport type { PendingAttachmentRecord } from \"../../../../workflows/documents\";\nimport {\n beginDomainSyncUploadLane,\n type UploadSyncLane,\n} from \"../../../../workflows/sync/coordination\";\n\nexport interface AttachmentUploadLaneReporter {\n complete: () => void;\n fail: (error: unknown) => void;\n failIfStarted: (error: unknown) => void;\n onMultipartProgress: MultipartUploadProgressListener;\n}\n\nfunction getAttachmentUploadLaneLabel(name: string | null | undefined): string {\n return name ? `Upload ${name}` : \"Attachment upload\";\n}\n\nfunction getAttachmentUploadFailureTarget(\n pendingAttachment: PendingAttachmentRecord,\n): string {\n return pendingAttachment.name\n ? `${pendingAttachment.name} (slot ${pendingAttachment.slotId})`\n : `slot ${pendingAttachment.slotId}`;\n}\n\nexport function createAttachmentUploadFailedError(\n pendingAttachment: PendingAttachmentRecord,\n cause: unknown,\n): Error {\n const error = new Error(\n `Attachment upload failed for ${getAttachmentUploadFailureTarget(pendingAttachment)}.`,\n );\n if (cause !== undefined) Reflect.set(error, \"cause\", cause);\n\n return error;\n}\n\n/**\n * Surfaces attachment uploads as observational lanes. The persisted blob id is\n * the lane identity: slot ids repeat across documents, while a retry must keep\n * updating the same row. Lane creation stays lazy until progress, failure, or\n * completion so a billing block before any upload work does not add noise.\n */\nexport function createAttachmentUploadLaneReporter(input: {\n blobId: string;\n domainScope: DomainScope;\n pendingAttachment: PendingAttachmentRecord;\n}): AttachmentUploadLaneReporter {\n const { blobId, domainScope, pendingAttachment } = input;\n const laneRef: { current: UploadSyncLane | null } = { current: null };\n\n const ensureLane = (): UploadSyncLane => {\n laneRef.current ??= beginDomainSyncUploadLane(\n domainScope,\n `blob-upload:${blobId}`,\n {\n blobStorageKey: pendingAttachment.storageKey,\n label: getAttachmentUploadLaneLabel(pendingAttachment.name),\n },\n );\n return laneRef.current;\n };\n\n return {\n complete() {\n // Completion must create/re-begin the lane too: a resumed stage can\n // already be complete before it emits any per-part callbacks.\n ensureLane().complete();\n },\n fail(error: unknown) {\n ensureLane().fail(error);\n },\n failIfStarted(error: unknown) {\n laneRef.current?.fail(error);\n },\n onMultipartProgress(progress) {\n ensureLane().reportProgress(progress);\n },\n };\n}\n"]}
@@ -4,7 +4,7 @@ import { DEFAULT_DOCUMENT_ACCESS_EPOCH, DEFAULT_DOCUMENT_KIND, } from "../../../
4
4
  import { initializeStoredDocumentKind, readStoredDocumentState, } from "../../../../data/documents/documentKinds.js";
5
5
  import { createPendingUpdateFields } from "../../../../data/documents/documentSync.js";
6
6
  import { isDatabaseUnavailableError, loadPersistedDocumentStoreState, } from "../../../../workflows/documents/index.js";
7
- import { OrganizationSyncPauseRepository } from "../../../../workflows/sync/index.js";
7
+ import { OrganizationSyncPauseRepository } from "../../../../workflows/sync/coordination.js";
8
8
  import { chainIdentityWrite } from "../identityWriteChain.js";
9
9
  import { runDocumentOrphanMaintenance } from "../orphanMaintenance.js";
10
10
  import { advancePendingBaseVersion, documentSummaryFromRecord, persistDocument, saveDocumentRecord, } from "../persistence.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[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UAAU,CAAC,EAAE,CAAC;YAC7D,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,eAAe,CAClC,KAAK,EACL,UAAU,EACV,KAAK,EACL;YACE,gCAAgC,EAAE,IAAI;YACtC,oBAAoB,EAAE,IAAI;YAC1B,YAAY,EAAE,KAAK,CAAC,YAAY;SACjC,EACD,UAAU,EACV,gBAAgB,CACjB,CAAC;QACF,IAAI,MAAM,IAAI,iBAAiB,KAAK,KAAK,CAAC,UAAU,EAAE,CAAC;YACrD,KAAK,CAAC,gBAAgB,GAAG,IAAI,CAAC;YAC9B,iCAAiC,CAAC,KAAK,CAAC,CAAC;QAC3C,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC,CAAC;IACH,yEAAyE;IACzE,yCAAyC;IACzC,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,SAAS,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,yBAAyB,CAC9B,SAAS,CAAC,MAAM,EAChB,SAAS,CAAC,SAAS,EACnB,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,kBAAkB,CACvC,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n emptyVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistorySnapshot,\n mergeVersionVectors,\n} from \"@tearleads/loro\";\nimport {\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n} from \"../../../../data/documents/documentConstants\";\nimport {\n initializeStoredDocumentKind,\n readStoredDocumentState,\n} from \"../../../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../../../data/documents/documentSummary\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport {\n type DocumentRecord,\n isDatabaseUnavailableError,\n loadPersistedDocumentStoreState,\n} from \"../../../../workflows/documents\";\nimport { OrganizationSyncPauseRepository } from \"../../../../workflows/sync\";\nimport type { DocumentStoreRelinkInput } from \"../../types\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport type { DocumentRelinkCommitSideEffect } from \"../internalRelink\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport {\n advancePendingBaseVersion,\n documentSummaryFromRecord,\n persistDocument,\n saveDocumentRecord,\n} from \"../persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"../state\";\nimport { createStoredDocument } from \"../storedDocument\";\nimport { logRevalidationScheduled } from \"../sync/remoteRevalidationTelemetry\";\nimport { deferStartupProbeToPendingConnect } from \"../sync/startupProbeDeferral\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreSyncGeneration,\n invalidateDocumentStoreRemoteSync,\n isDocumentStoreSyncGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n} from \"../sync/syncGeneration\";\nimport { writeInitialDocumentContent } from \"./initialContent\";\nimport {\n installPersistedAttachments,\n type LoadedDocumentStoreState,\n} from \"./initializationAttachments\";\nimport {\n type RestoredHistoryState,\n restoredRemoteTailCoverage,\n restorePersistedDocumentContent,\n} from \"./initializationHistory\";\nimport {\n healLocalAttachmentDetachState,\n recoverDroppedAttachmentSlots,\n} from \"./initializationRecovery\";\nimport { relinkRecordPatch } from \"./relinkRecordPatch\";\n\nasync function createInitialDocumentRecord(\n state: DocumentStoreState,\n nextDoc: DocumentState,\n): ReturnType<typeof saveDocumentRecord> {\n initializeStoredDocumentKind(\n nextDoc,\n state.initialDocumentKind,\n state.runtime.infra.documentProjectors,\n );\n if (state.initialText.length > 0) {\n nextDoc.getText(\"text\").update(state.initialText);\n }\n const wroteInitialContent = writeInitialDocumentContent(state, nextDoc);\n const initialDocumentState = readStoredDocumentState(\n nextDoc,\n state.runtime.infra.documentProjectors,\n );\n const hasInitialContent =\n wroteInitialContent ||\n state.initialText.length > 0 ||\n state.initialDocumentKind !== DEFAULT_DOCUMENT_KIND;\n const initialUpdate = hasInitialContent\n ? createPendingUpdateFields(exportAllUpdates(nextDoc))\n : null;\n // A deferred birth still commits its checkpoint, but leaves the marker at the\n // empty version with nothing queued: the promised attach exports every op\n // since that marker, so one update carries the birth and the attachment.\n const birthDurability = !initialUpdate\n ? {}\n : state.deferInitialUpdate\n ? { pendingBaseVersionOverride: emptyVersionVector() }\n : { pendingUpdate: initialUpdate };\n\n const created: DocumentRecord = {\n id: state.localId,\n containerId: state.runtime.state.containerId ?? null,\n documentId: state.initialDocumentId,\n documentKind: initialDocumentState.documentKind,\n text: initialDocumentState.text,\n title: initialDocumentState.title,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n accessEpoch: DEFAULT_DOCUMENT_ACCESS_EPOCH,\n accessStateHash: null,\n effectiveAccessLevel: \"admin\",\n lastCommitLsn: null,\n contentKeyBundle: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n };\n // The create-only persistence primitive commits the canonical row and birth\n // checkpoint together. A concurrent initializer either wins both or adopts\n // both, so it cannot replace another pane's history or keying state.\n const persisted = await saveDocumentRecord(\n state,\n nextDoc,\n {\n ...created,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n },\n {\n historyCheckpoint: {\n coveredTailIds: [],\n endVersionVector: encodeVersionVector(nextDoc),\n pruneCoveredLocalState: false,\n snapshot: bytesToBase64(exportFullHistorySnapshot(nextDoc)),\n },\n ...birthDurability,\n },\n );\n return persisted;\n}\n\nfunction installPersistedDocumentRecord(\n state: DocumentStoreState,\n record: NonNullable<DocumentStoreState[\"record\"]>,\n): void {\n state.record = record;\n state.pullContinuation = record.pullContinuation ?? null;\n}\n\ninterface RestoredInitialDocumentState {\n activePersistedState: LoadedDocumentStoreState;\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n}\n\nasync function restoreLoadedInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n const record = persistedState.document;\n if (!record) return null;\n const history = await restorePersistedDocumentContent(\n input.nextDoc,\n persistedState.historyRestoreState,\n );\n if (state.localWriteGeneration !== initializeGeneration) return null;\n installPersistedDocumentRecord(state, record);\n return {\n activePersistedState: persistedState,\n activeRecord: record,\n doc: input.nextDoc,\n history,\n };\n}\n\nasync function restoreOrCreateInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n if (persistedState.document) {\n return restoreLoadedInitialDocument(input);\n }\n const created = await createInitialDocumentRecord(state, input.nextDoc);\n if (!created || state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n const activePersistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n if (!activePersistedState.document) {\n throw new Error(\"Document creation completed without a durable record\");\n }\n const replacementDoc = await createStoredDocument(state);\n return restoreLoadedInitialDocument({\n initializeGeneration,\n nextDoc: replacementDoc,\n persistedState: activePersistedState,\n state,\n });\n}\n\nfunction restorePendingBaseVersion(input: {\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n state: DocumentStoreState;\n}): void {\n const { activeRecord, doc, history, state } = input;\n const markerBase =\n activeRecord.pendingBaseVersion ??\n (activeRecord.snapshotEndVersion.length > 0\n ? activeRecord.snapshotEndVersion\n : null);\n if (markerBase === null) {\n advancePendingBaseVersion(state, doc);\n return;\n }\n\n const remoteCoverage = restoredRemoteTailCoverage(history);\n state.pendingBaseVersion =\n remoteCoverage.length > 0\n ? mergeVersionVectors([markerBase, ...remoteCoverage])\n : markerBase;\n}\n\nasync function initializeDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (state.runtime.infra.dbStatus !== \"ready\") {\n return;\n }\n\n // A store reset while this fire-and-forget initialization is loading (a\n // runtime swap, or a local-edits discard that re-seeds the persisted rows)\n // must win: assigning the state loaded BEFORE the reset would bring the\n // replaced record and doc back to life. Every reset bumps the local write\n // generation, so a stale capture here aborts before each assignment batch.\n const initializeGeneration = state.localWriteGeneration;\n\n const nextDoc = await createStoredDocument(state);\n const persistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n // A paused organization's cleanup removed it; creating it again would\n // download the organization's content while the pause lasts. A later open\n // retries, so it loads once the organization resumes.\n if (\n !persistedState.document &&\n (await new OrganizationSyncPauseRepository(\n state.runtime.infra.execSql,\n ).isPauseRemovedDocument(state.localId))\n ) {\n state.initializePromise = null;\n return;\n }\n const restored = await restoreOrCreateInitialDocument({\n initializeGeneration,\n nextDoc,\n persistedState,\n state,\n });\n if (!restored) {\n if (state.localWriteGeneration === initializeGeneration) {\n state.initializePromise = null;\n }\n return;\n }\n const activePersistedState = restored.activePersistedState;\n installPersistedAttachments(state, activePersistedState);\n\n state.doc = restored.doc;\n // Restore the durable outgoing-delta marker. Re-seeding it to the restored\n // document's version would move it PAST any device-first `deferRemoteSync`\n // op (persisted into the durable history but deliberately left un-enqueued\n // and behind the marker), permanently dropping that op from sync across a\n // restart. When a marker was persisted, restore it so the next edit still\n // re-derives the deferred delta. Only seed for rows that never persisted\n // one, from the RECORD's persisted frontier rather than the restored\n // document: a crash between the tail append and the queue/marker writes can\n // resurrect ops the outgoing queue never durably received, and seeding from\n // the restored document would classify those as covered and orphan them\n // from sync forever.\n restorePendingBaseVersion({\n activeRecord: restored.activeRecord,\n doc: restored.doc,\n history: restored.history,\n state,\n });\n // Heal attachment slots lost to an interrupted attach write before marking\n // ready, so the recovered slots are in the snapshot the editor first renders\n // and are queued for sync. recoverDroppedAttachmentSlots advances the marker\n // again for whatever it re-derives. Both helpers gate every durable write\n // on this generation (validated inside the writes' serialized mutations),\n // so a reset mid-helper cannot repopulate discarded state.\n const writeGeneration = captureDocumentStoreSyncGeneration(\n state,\n restored.doc,\n );\n if (!writeGeneration) {\n return;\n }\n await recoverDroppedAttachmentSlots(state, restored.doc, writeGeneration);\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n await healLocalAttachmentDetachState(\n state,\n restored.doc,\n activePersistedState,\n writeGeneration,\n );\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n state.initialized = true;\n state.initializePromise = null;\n setReadySnapshot(state, restored.doc, false);\n\n // Websocket invalidations are intentionally session-local. A process can\n // stop before receiving a peer device's update event, and no event survives\n // the restart to distinguish a clean local snapshot from a stale one. Probe\n // each opened remote document once after loading it; unopened documents stay\n // lazy, while body and attachment state for a restored window converges.\n // A connect attempt in flight arms a later probe on its acknowledgement,\n // which covers this one, so the startup probe waits on that attempt.\n if (\n restored.activeRecord.documentId &&\n state.scheduleStartupRemoteSync &&\n !deferStartupProbeToPendingConnect(state)\n ) {\n allowDocumentStoreRemoteSync(state);\n markDocumentStoreRemoteSyncPending(state, \"independent\");\n logRevalidationScheduled(state.runtime, \"startup\");\n }\n scheduleSync();\n void runDocumentOrphanMaintenance(state);\n}\n\nexport function ensureDocumentStoreInitialized(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (\n state.initialized ||\n state.initializePromise ||\n state.runtime.infra.dbStatus !== \"ready\"\n ) {\n return;\n }\n\n const initializePromise = initializeDocumentStore(state, scheduleSync).catch(\n (error: unknown) => {\n state.initializePromise = null;\n // A caller that deferred the birth for its attach may give up once\n // opening fails; never leave its durable birth holding sync. No attach\n // has reached a live doc yet, so lifting the hold ships nothing unsafe.\n state.deferInitialUpdate = false;\n\n if (isDatabaseUnavailableError(error)) {\n return;\n }\n\n throw error;\n },\n );\n state.initializePromise = initializePromise;\n void initializePromise.catch(() => undefined);\n}\n\nexport async function awaitInitializationForSync(state: DocumentStoreState) {\n if (!state.initializePromise) {\n return state.initialized;\n }\n\n try {\n await state.initializePromise;\n return state.initialized;\n } catch (error) {\n if (isDatabaseUnavailableError(error)) {\n return false;\n }\n\n throw error;\n }\n}\n\nexport async function ensureDocumentStoreReady(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): Promise<boolean> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (state.initialized) {\n return true;\n }\n\n if (!state.initializePromise) {\n return false;\n }\n\n return awaitInitializationForSync(state);\n}\n\nexport async function relinkDocumentStore(\n state: DocumentStoreState,\n input: DocumentStoreRelinkInput,\n scheduleSync: () => void,\n commitSideEffect?: DocumentRelinkCommitSideEffect,\n): Promise<DocumentSummary | null> {\n if (\n input.stillCurrent?.() === false ||\n !(await ensureDocumentStoreReady(state, scheduleSync)) ||\n input.stillCurrent?.() === false ||\n !state.doc\n ) {\n return null;\n }\n const currentDoc = state.doc;\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) return null;\n // Read the record and persist on the identity-write chain so an in-flight\n // eager create cannot interleave: a create that captured a null identity\n // before its network round trip would otherwise write the derived documentId\n // over the one this relink assigns.\n const persisted = await chainIdentityWrite(state, async () => {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n const currentDocumentId = state.record?.documentId ?? null;\n const patch = relinkRecordPatch(state.record, input);\n\n // Relink rewrites access/identity metadata, not content. If it lands while\n // the user is mid-edit, re-deriving text/structured fields from the\n // (possibly lagging) doc would republish a stale read over the live\n // optimistic snapshot and drop in-flight keystrokes; preserve the snapshot\n // like the keystroke and sync persists do.\n // A prior chained write may have cleared this store (resurrect-guard\n // refusal): persisting the captured doc against a null record would\n // resurrect the document as a create. The identity check runs inside\n // the chain, after every earlier write settled.\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n return null;\n }\n const result = await persistDocument(\n state,\n currentDoc,\n patch,\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n stillCurrent: input.stillCurrent,\n },\n generation,\n commitSideEffect,\n );\n if (result && currentDocumentId !== input.documentId) {\n state.writerProjection = null;\n invalidateDocumentStoreRemoteSync(state);\n }\n return result;\n });\n // A refused persist means the durable row vanished mid-relink (resurrect\n // guard); there is no summary to report.\n if (!persisted) {\n return null;\n }\n if (persisted.updatedAt === undefined) {\n return null;\n }\n return documentSummaryFromRecord(\n persisted.record,\n persisted.updatedAt,\n state.runtime.infra.documentProjectors,\n );\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,GACxB,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAEL,0BAA0B,EAC1B,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAE1F,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EACL,yBAAyB,EACzB,yBAAyB,EACzB,eAAe,EACf,kBAAkB,GACnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAGL,gBAAgB,GACjB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,M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import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n emptyVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistorySnapshot,\n mergeVersionVectors,\n} from \"@tearleads/loro\";\nimport {\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n} from \"../../../../data/documents/documentConstants\";\nimport {\n initializeStoredDocumentKind,\n readStoredDocumentState,\n} from \"../../../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../../../data/documents/documentSummary\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport {\n type DocumentRecord,\n isDatabaseUnavailableError,\n loadPersistedDocumentStoreState,\n} from \"../../../../workflows/documents\";\nimport { OrganizationSyncPauseRepository } from \"../../../../workflows/sync/coordination\";\nimport type { DocumentStoreRelinkInput } from \"../../types\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport type { DocumentRelinkCommitSideEffect } from \"../internalRelink\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport {\n advancePendingBaseVersion,\n documentSummaryFromRecord,\n persistDocument,\n saveDocumentRecord,\n} from \"../persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"../state\";\nimport { createStoredDocument } from \"../storedDocument\";\nimport { logRevalidationScheduled } from \"../sync/remoteRevalidationTelemetry\";\nimport { deferStartupProbeToPendingConnect } from \"../sync/startupProbeDeferral\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreSyncGeneration,\n invalidateDocumentStoreRemoteSync,\n isDocumentStoreSyncGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n} from \"../sync/syncGeneration\";\nimport { writeInitialDocumentContent } from \"./initialContent\";\nimport {\n installPersistedAttachments,\n type LoadedDocumentStoreState,\n} from \"./initializationAttachments\";\nimport {\n type RestoredHistoryState,\n restoredRemoteTailCoverage,\n restorePersistedDocumentContent,\n} from \"./initializationHistory\";\nimport {\n healLocalAttachmentDetachState,\n recoverDroppedAttachmentSlots,\n} from \"./initializationRecovery\";\nimport { relinkRecordPatch } from \"./relinkRecordPatch\";\n\nasync function createInitialDocumentRecord(\n state: DocumentStoreState,\n nextDoc: DocumentState,\n): ReturnType<typeof saveDocumentRecord> {\n initializeStoredDocumentKind(\n nextDoc,\n state.initialDocumentKind,\n state.runtime.infra.documentProjectors,\n );\n if (state.initialText.length > 0) {\n nextDoc.getText(\"text\").update(state.initialText);\n }\n const wroteInitialContent = writeInitialDocumentContent(state, nextDoc);\n const initialDocumentState = readStoredDocumentState(\n nextDoc,\n state.runtime.infra.documentProjectors,\n );\n const hasInitialContent =\n wroteInitialContent ||\n state.initialText.length > 0 ||\n state.initialDocumentKind !== DEFAULT_DOCUMENT_KIND;\n const initialUpdate = hasInitialContent\n ? createPendingUpdateFields(exportAllUpdates(nextDoc))\n : null;\n // A deferred birth still commits its checkpoint, but leaves the marker at the\n // empty version with nothing queued: the promised attach exports every op\n // since that marker, so one update carries the birth and the attachment.\n const birthDurability = !initialUpdate\n ? {}\n : state.deferInitialUpdate\n ? { pendingBaseVersionOverride: emptyVersionVector() }\n : { pendingUpdate: initialUpdate };\n\n const created: DocumentRecord = {\n id: state.localId,\n containerId: state.runtime.state.containerId ?? null,\n documentId: state.initialDocumentId,\n documentKind: initialDocumentState.documentKind,\n text: initialDocumentState.text,\n title: initialDocumentState.title,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n accessEpoch: DEFAULT_DOCUMENT_ACCESS_EPOCH,\n accessStateHash: null,\n effectiveAccessLevel: \"admin\",\n lastCommitLsn: null,\n contentKeyBundle: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n };\n // The create-only persistence primitive commits the canonical row and birth\n // checkpoint together. A concurrent initializer either wins both or adopts\n // both, so it cannot replace another pane's history or keying state.\n const persisted = await saveDocumentRecord(\n state,\n nextDoc,\n {\n ...created,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n },\n {\n historyCheckpoint: {\n coveredTailIds: [],\n endVersionVector: encodeVersionVector(nextDoc),\n pruneCoveredLocalState: false,\n snapshot: bytesToBase64(exportFullHistorySnapshot(nextDoc)),\n },\n ...birthDurability,\n },\n );\n return persisted;\n}\n\nfunction installPersistedDocumentRecord(\n state: DocumentStoreState,\n record: NonNullable<DocumentStoreState[\"record\"]>,\n): void {\n state.record = record;\n state.pullContinuation = record.pullContinuation ?? null;\n}\n\ninterface RestoredInitialDocumentState {\n activePersistedState: LoadedDocumentStoreState;\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n}\n\nasync function restoreLoadedInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n const record = persistedState.document;\n if (!record) return null;\n const history = await restorePersistedDocumentContent(\n input.nextDoc,\n persistedState.historyRestoreState,\n );\n if (state.localWriteGeneration !== initializeGeneration) return null;\n installPersistedDocumentRecord(state, record);\n return {\n activePersistedState: persistedState,\n activeRecord: record,\n doc: input.nextDoc,\n history,\n };\n}\n\nasync function restoreOrCreateInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n if (persistedState.document) {\n return restoreLoadedInitialDocument(input);\n }\n const created = await createInitialDocumentRecord(state, input.nextDoc);\n if (!created || state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n const activePersistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n if (!activePersistedState.document) {\n throw new Error(\"Document creation completed without a durable record\");\n }\n const replacementDoc = await createStoredDocument(state);\n return restoreLoadedInitialDocument({\n initializeGeneration,\n nextDoc: replacementDoc,\n persistedState: activePersistedState,\n state,\n });\n}\n\nfunction restorePendingBaseVersion(input: {\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n state: DocumentStoreState;\n}): void {\n const { activeRecord, doc, history, state } = input;\n const markerBase =\n activeRecord.pendingBaseVersion ??\n (activeRecord.snapshotEndVersion.length > 0\n ? activeRecord.snapshotEndVersion\n : null);\n if (markerBase === null) {\n advancePendingBaseVersion(state, doc);\n return;\n }\n\n const remoteCoverage = restoredRemoteTailCoverage(history);\n state.pendingBaseVersion =\n remoteCoverage.length > 0\n ? mergeVersionVectors([markerBase, ...remoteCoverage])\n : markerBase;\n}\n\nasync function initializeDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (state.runtime.infra.dbStatus !== \"ready\") {\n return;\n }\n\n // A store reset while this fire-and-forget initialization is loading (a\n // runtime swap, or a local-edits discard that re-seeds the persisted rows)\n // must win: assigning the state loaded BEFORE the reset would bring the\n // replaced record and doc back to life. Every reset bumps the local write\n // generation, so a stale capture here aborts before each assignment batch.\n const initializeGeneration = state.localWriteGeneration;\n\n const nextDoc = await createStoredDocument(state);\n const persistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n // A paused organization's cleanup removed it; creating it again would\n // download the organization's content while the pause lasts. A later open\n // retries, so it loads once the organization resumes.\n if (\n !persistedState.document &&\n (await new OrganizationSyncPauseRepository(\n state.runtime.infra.execSql,\n ).isPauseRemovedDocument(state.localId))\n ) {\n state.initializePromise = null;\n return;\n }\n const restored = await restoreOrCreateInitialDocument({\n initializeGeneration,\n nextDoc,\n persistedState,\n state,\n });\n if (!restored) {\n if (state.localWriteGeneration === initializeGeneration) {\n state.initializePromise = null;\n }\n return;\n }\n const activePersistedState = restored.activePersistedState;\n installPersistedAttachments(state, activePersistedState);\n\n state.doc = restored.doc;\n // Restore the durable outgoing-delta marker. Re-seeding it to the restored\n // document's version would move it PAST any device-first `deferRemoteSync`\n // op (persisted into the durable history but deliberately left un-enqueued\n // and behind the marker), permanently dropping that op from sync across a\n // restart. When a marker was persisted, restore it so the next edit still\n // re-derives the deferred delta. Only seed for rows that never persisted\n // one, from the RECORD's persisted frontier rather than the restored\n // document: a crash between the tail append and the queue/marker writes can\n // resurrect ops the outgoing queue never durably received, and seeding from\n // the restored document would classify those as covered and orphan them\n // from sync forever.\n restorePendingBaseVersion({\n activeRecord: restored.activeRecord,\n doc: restored.doc,\n history: restored.history,\n state,\n });\n // Heal attachment slots lost to an interrupted attach write before marking\n // ready, so the recovered slots are in the snapshot the editor first renders\n // and are queued for sync. recoverDroppedAttachmentSlots advances the marker\n // again for whatever it re-derives. Both helpers gate every durable write\n // on this generation (validated inside the writes' serialized mutations),\n // so a reset mid-helper cannot repopulate discarded state.\n const writeGeneration = captureDocumentStoreSyncGeneration(\n state,\n restored.doc,\n );\n if (!writeGeneration) {\n return;\n }\n await recoverDroppedAttachmentSlots(state, restored.doc, writeGeneration);\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n await healLocalAttachmentDetachState(\n state,\n restored.doc,\n activePersistedState,\n writeGeneration,\n );\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n state.initialized = true;\n state.initializePromise = null;\n setReadySnapshot(state, restored.doc, false);\n\n // Websocket invalidations are intentionally session-local. A process can\n // stop before receiving a peer device's update event, and no event survives\n // the restart to distinguish a clean local snapshot from a stale one. Probe\n // each opened remote document once after loading it; unopened documents stay\n // lazy, while body and attachment state for a restored window converges.\n // A connect attempt in flight arms a later probe on its acknowledgement,\n // which covers this one, so the startup probe waits on that attempt.\n if (\n restored.activeRecord.documentId &&\n state.scheduleStartupRemoteSync &&\n !deferStartupProbeToPendingConnect(state)\n ) {\n allowDocumentStoreRemoteSync(state);\n markDocumentStoreRemoteSyncPending(state, \"independent\");\n logRevalidationScheduled(state.runtime, \"startup\");\n }\n scheduleSync();\n void runDocumentOrphanMaintenance(state);\n}\n\nexport function ensureDocumentStoreInitialized(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (\n state.initialized ||\n state.initializePromise ||\n state.runtime.infra.dbStatus !== \"ready\"\n ) {\n return;\n }\n\n const initializePromise = initializeDocumentStore(state, scheduleSync).catch(\n (error: unknown) => {\n state.initializePromise = null;\n // A caller that deferred the birth for its attach may give up once\n // opening fails; never leave its durable birth holding sync. No attach\n // has reached a live doc yet, so lifting the hold ships nothing unsafe.\n state.deferInitialUpdate = false;\n\n if (isDatabaseUnavailableError(error)) {\n return;\n }\n\n throw error;\n },\n );\n state.initializePromise = initializePromise;\n void initializePromise.catch(() => undefined);\n}\n\nexport async function awaitInitializationForSync(state: DocumentStoreState) {\n if (!state.initializePromise) {\n return state.initialized;\n }\n\n try {\n await state.initializePromise;\n return state.initialized;\n } catch (error) {\n if (isDatabaseUnavailableError(error)) {\n return false;\n }\n\n throw error;\n }\n}\n\nexport async function ensureDocumentStoreReady(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): Promise<boolean> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (state.initialized) {\n return true;\n }\n\n if (!state.initializePromise) {\n return false;\n }\n\n return awaitInitializationForSync(state);\n}\n\nexport async function relinkDocumentStore(\n state: DocumentStoreState,\n input: DocumentStoreRelinkInput,\n scheduleSync: () => void,\n commitSideEffect?: DocumentRelinkCommitSideEffect,\n): Promise<DocumentSummary | null> {\n if (\n input.stillCurrent?.() === false ||\n !(await ensureDocumentStoreReady(state, scheduleSync)) ||\n input.stillCurrent?.() === false ||\n !state.doc\n ) {\n return null;\n }\n const currentDoc = state.doc;\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) return null;\n // Read the record and persist on the identity-write chain so an in-flight\n // eager create cannot interleave: a create that captured a null identity\n // before its network round trip would otherwise write the derived documentId\n // over the one this relink assigns.\n const persisted = await chainIdentityWrite(state, async () => {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n const currentDocumentId = state.record?.documentId ?? null;\n const patch = relinkRecordPatch(state.record, input);\n\n // Relink rewrites access/identity metadata, not content. If it lands while\n // the user is mid-edit, re-deriving text/structured fields from the\n // (possibly lagging) doc would republish a stale read over the live\n // optimistic snapshot and drop in-flight keystrokes; preserve the snapshot\n // like the keystroke and sync persists do.\n // A prior chained write may have cleared this store (resurrect-guard\n // refusal): persisting the captured doc against a null record would\n // resurrect the document as a create. The identity check runs inside\n // the chain, after every earlier write settled.\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n return null;\n }\n const result = await persistDocument(\n state,\n currentDoc,\n patch,\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n stillCurrent: input.stillCurrent,\n },\n generation,\n commitSideEffect,\n );\n if (result && currentDocumentId !== input.documentId) {\n state.writerProjection = null;\n invalidateDocumentStoreRemoteSync(state);\n }\n return result;\n });\n // A refused persist means the durable row vanished mid-relink (resurrect\n // guard); there is no summary to report.\n if (!persisted) {\n return null;\n }\n if (persisted.updatedAt === undefined) {\n return null;\n }\n return documentSummaryFromRecord(\n persisted.record,\n persisted.updatedAt,\n state.runtime.infra.documentProjectors,\n );\n}\n"]}
@@ -2,7 +2,7 @@ import { createDocument } from "../../../internal/loro/index.js";
2
2
  import { ensureDocumentAttachmentStructure } from "../../../data/documents/documentContent.js";
3
3
  import { ensureDocumentRowsStructure } from "../../../data/documents/documentRowList.js";
4
4
  import { DOCUMENTS_APP_KIND } from "../../../workflows/documents/index.js";
5
- import { getRuntimePeerSeed } from "../../../workflows/sync/index.js";
5
+ import { getRuntimePeerSeed } from "../../../workflows/sync/coordination.js";
6
6
  async function createStoredDocumentWithSeed(peerSeed) {
7
7
  const createdDoc = await createDocument(peerSeed);
8
8
  ensureDocumentAttachmentStructure(createdDoc);
@@ -1 +1 @@
1
- {"version":3,"file":"storedDocument.js","sourceRoot":"","sources":["storedDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,iCAAiC,EAAE,MAAM,yCAAyC,CAAC;AAC5F,OAAO,EAAE,2BAA2B,EAAE,MAAM,yCAAyC,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAG7D,KAAK,UAAU,4BAA4B,CACzC,QAAgB;IAEhB,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,QAAQ,CAAC,CAAC;IAClD,iCAAiC,CAAC,UAAU,CAAC,CAAC;IAC9C,2BAA2B,CAAC,UAAU,CAAC,CAAC;IACxC,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,KAAyB;IAEzB,6EAA6E;IAC7E,4EAA4E;IAC5E,0EAA0E;IAC1E,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;IAChD,MAAM,KAAK,GAAG,SAAS;QACrB,CAAC,CAAC,GAAG,kBAAkB,IAAI,SAAS,EAAE;QACtC,CAAC,CAAC,kBAAkB,CAAC;IACvB,OAAO,4BAA4B,CACjC,MAAM,kBAAkB,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CACjE,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,6BAA6B;IAC3C,OAAO,4BAA4B,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { createDocument } from \"@tearleads/loro\";\nimport { ensureDocumentAttachmentStructure } from \"../../../data/documents/documentContent\";\nimport { ensureDocumentRowsStructure } from \"../../../data/documents/documentRowList\";\nimport { DOCUMENTS_APP_KIND } from \"../../../workflows/documents\";\nimport { getRuntimePeerSeed } from \"../../../workflows/sync\";\nimport type { DocumentState, DocumentStoreState } from \"./state\";\n\nasync function createStoredDocumentWithSeed(\n peerSeed: string,\n): Promise<DocumentState> {\n const createdDoc = await createDocument(peerSeed);\n ensureDocumentAttachmentStructure(createdDoc);\n ensureDocumentRowsStructure(createdDoc);\n return createdDoc;\n}\n\nexport async function createStoredDocument(\n state: DocumentStoreState,\n): Promise<DocumentState> {\n // Persistent pane namespaces retain stable seeds. Concurrent runtimes in one\n // namespace receive distinct memory-only seeds after the first owner, while\n // the usual single runtime can reuse its device seed after a page reload.\n const peerScope = state.runtime.state.peerScope;\n const scope = peerScope\n ? `${DOCUMENTS_APP_KIND}:${peerScope}`\n : DOCUMENTS_APP_KIND;\n return createStoredDocumentWithSeed(\n await getRuntimePeerSeed(scope, state.runtime.state.domainScope),\n );\n}\n\n/**\n * Rebuild after discarding non-durable local ops under a new peer. Reusing the\n * normal peer would reuse the discarded counters and corrupt the next edit.\n */\nexport function createFreshPeerStoredDocument(): Promise<DocumentState> {\n return createStoredDocumentWithSeed(crypto.randomUUID());\n}\n"]}
1
+ {"version":3,"file":"storedDocument.js","sourceRoot":"","sources":["storedDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,iCAAiC,EAAE,MAAM,yCAAyC,CAAC;AAC5F,OAAO,EAAE,2BAA2B,EAAE,MAAM,yCAAyC,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAG1E,KAAK,UAAU,4BAA4B,CACzC,QAAgB;IAEhB,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,QAAQ,CAAC,CAAC;IAClD,iCAAiC,CAAC,UAAU,CAAC,CAAC;IAC9C,2BAA2B,CAAC,UAAU,CAAC,CAAC;IACxC,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,KAAyB;IAEzB,6EAA6E;IAC7E,4EAA4E;IAC5E,0EAA0E;IAC1E,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;IAChD,MAAM,KAAK,GAAG,SAAS;QACrB,CAAC,CAAC,GAAG,kBAAkB,IAAI,SAAS,EAAE;QACtC,CAAC,CAAC,kBAAkB,CAAC;IACvB,OAAO,4BAA4B,CACjC,MAAM,kBAAkB,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CACjE,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,6BAA6B;IAC3C,OAAO,4BAA4B,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { createDocument } from \"@tearleads/loro\";\nimport { ensureDocumentAttachmentStructure } from \"../../../data/documents/documentContent\";\nimport { ensureDocumentRowsStructure } from \"../../../data/documents/documentRowList\";\nimport { DOCUMENTS_APP_KIND } from \"../../../workflows/documents\";\nimport { getRuntimePeerSeed } from \"../../../workflows/sync/coordination\";\nimport type { DocumentState, DocumentStoreState } from \"./state\";\n\nasync function createStoredDocumentWithSeed(\n peerSeed: string,\n): Promise<DocumentState> {\n const createdDoc = await createDocument(peerSeed);\n ensureDocumentAttachmentStructure(createdDoc);\n ensureDocumentRowsStructure(createdDoc);\n return createdDoc;\n}\n\nexport async function createStoredDocument(\n state: DocumentStoreState,\n): Promise<DocumentState> {\n // Persistent pane namespaces retain stable seeds. Concurrent runtimes in one\n // namespace receive distinct memory-only seeds after the first owner, while\n // the usual single runtime can reuse its device seed after a page reload.\n const peerScope = state.runtime.state.peerScope;\n const scope = peerScope\n ? `${DOCUMENTS_APP_KIND}:${peerScope}`\n : DOCUMENTS_APP_KIND;\n return createStoredDocumentWithSeed(\n await getRuntimePeerSeed(scope, state.runtime.state.domainScope),\n );\n}\n\n/**\n * Rebuild after discarding non-durable local ops under a new peer. Reusing the\n * normal peer would reuse the discarded counters and corrupt the next edit.\n */\nexport function createFreshPeerStoredDocument(): Promise<DocumentState> {\n return createStoredDocumentWithSeed(crypto.randomUUID());\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { DOCUMENTS_APP_KIND, DocumentRecordRepository, resolveDocumentCreateAuthor, } from "../../../../workflows/documents/index.js";
2
- import { markOriginatedDocuments } from "../../../../workflows/sync/index.js";
2
+ import { markOriginatedDocuments } from "../../../../workflows/sync/coordination.js";
3
3
  import { requestDocumentStoreSync } from "../../registry.js";
4
4
  import { dropUnavailablePendingAttachment, pendingAttachmentMatchesIntent, resolveAttachmentSourceUpload, } from "../attachmentUpload/attachmentSourceUpload.js";
5
5
  import { uploadAttachmentWithWriterProjectionRetry } from "../attachmentUpload/attachmentUploadAttempt.js";
@@ -1 +1 @@
1
- {"version":3,"file":"syncAttachments.js","sourceRoot":"","sources":["syncAttachments.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,kBAAkB,EAElB,wBAAwB,EAExB,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EACL,gCAAgC,EAChC,8BAA8B,EAC9B,6BAA6B,GAC9B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yCAAyC,EAAE,MAAM,6CAA6C,CAAC;AACxG,OAAO,EAEL,kCAAkC,GACnC,MAAM,0CAA0C,CAAC;AAQlD,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAC1E,OAAO,EAEL,uCAAuC,EACvC,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,0BAA0B,EAC1B,8BAA8B,EAC9B,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,oCAAoC,GACrC,MAAM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CAAC,MAAM;QACrB,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;QAC5C,iBAAiB;KAClB,CAAC,CAAC;IACH,MAAM,eAAe,GAAG,+BAA+B,CAAC;QACtD,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,MAAM;QACN,MAAM;QACN,cAAc,EAAE,QAAQ;QACxB,UAAU;KACX,CAAC,CAAC;IACH,OAAO,4BAA4B,CAAC;QAClC,eAAe;QACf,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,eAAe;QAC9C,aAAa,EAAE,KAAK;QACpB,UAAU;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n BlobAttachmentService,\n BlobByteSource,\n BlobSourceSnapshot,\n} from \"../../../../workflows/blobs\";\nimport type { PreparedUploadDocumentAttachmentRequest } from \"../../../../workflows/blobs/upload\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type PendingAttachmentRecord,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { markOriginatedDocuments } from \"../../../../workflows/sync\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport {\n dropUnavailablePendingAttachment,\n pendingAttachmentMatchesIntent,\n resolveAttachmentSourceUpload,\n} from \"../attachmentUpload/attachmentSourceUpload\";\nimport { uploadAttachmentWithWriterProjectionRetry } from \"../attachmentUpload/attachmentUploadAttempt\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadLaneReporter,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { AttachmentUploadResume } from \"../attachmentUpload/attachmentUploadResume\";\nimport type {\n DocumentAttachmentBinding,\n DocumentStoreState,\n EncapsulationKeyPair,\n PendingMutationSyncResult,\n} from \"../state\";\nimport { reportAttachmentUploadFailure } from \"./attachmentUploadFailure\";\nimport {\n type CarriedFirstUpdate,\n ensureRemoteDocumentCarryingFirstUpdate,\n uploadCarryingFirstUpdate,\n} from \"./carriedFirstUpdate\";\nimport {\n isNewPendingAttachmentSlot,\n removeSettledPendingAttachment,\n settleRecoveredAttachment,\n settleUploadedAttachment,\n} from \"./syncAttachmentSettlement\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\n// Preserve transient failures for retry. Drop irrecoverable missing bytes so a\n// pending attachment cannot wedge the document sync lane across restarts.\ntype PendingAttachmentUploadOutcome =\n | \"uploaded\"\n | \"recovered\"\n | \"retry\"\n | \"dropped\";\n\ninterface AttachmentSyncProgress {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n fetchedRemoteBindings: boolean;\n settledAttachment: boolean;\n uploadedAttachment: boolean;\n}\n\nfunction rearmStaleAttachmentSync(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n): void {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nexport async function syncPendingAttachments(\n state: DocumentStoreState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n attachmentGeneration: DocumentStoreSyncGeneration,\n policyOperation: PrincipalPolicyOperation,\n): Promise<PendingMutationSyncResult> {\n if (state.pendingAttachments.length === 0) {\n return { completed: false, nextRecord };\n }\n\n const currentDoc = state.doc;\n if (!currentDoc) {\n return { completed: false, nextRecord };\n }\n\n let carriedFirstUpdate: CarriedFirstUpdate | undefined;\n const currentRecord = nextRecord.documentId\n ? nextRecord\n : await ensureRemoteDocumentCarryingFirstUpdate({\n currentDoc,\n encapsulationKeyPair,\n generation: attachmentGeneration,\n nextRecord,\n onCarried: (carried) => {\n carriedFirstUpdate = carried;\n },\n policyOperation,\n state,\n });\n if (!currentRecord?.documentId) {\n return { completed: false, nextRecord };\n }\n const remoteDocumentId = currentRecord.documentId;\n\n const progress: AttachmentSyncProgress = {\n activeBindingBySlotId: new Map(),\n fetchedRemoteBindings: false,\n settledAttachment: false,\n uploadedAttachment: false,\n };\n\n for (const pendingAttachment of [...state.pendingAttachments]) {\n const step = await syncNextPendingAttachment(\n {\n attachmentGeneration,\n carriedFirstUpdate,\n encapsulationKeyPair,\n pendingAttachment,\n policyOperation,\n remoteDocumentId,\n state,\n },\n progress,\n currentDoc,\n );\n // Only the first bind may carry it; a failed one leaves the row queued.\n carriedFirstUpdate = undefined;\n if (step === \"stop\") {\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n }\n\n if (!progress.settledAttachment) {\n return { completed: false, nextRecord: currentRecord };\n }\n\n // Only record the origination once a write landed: the server echoes a\n // document_update_created for it, and this lets the reconciler skip\n // rediscovering a delta we already have locally rather than cycling its lane\n // per uploaded file. Marking here (not before the loop) avoids a dangling id\n // that would suppress the next genuine remote update if every upload failed.\n if (progress.uploadedAttachment) {\n markOriginatedDocuments(state.runtime.state.domainScope, [\n remoteDocumentId,\n ]);\n }\n\n // A settled attachment pass invalidates any recorded failure itself: a\n // retried upload with no pending CRDT update never reaches the document\n // submission that would otherwise clear it, and the stale row would flag the\n // next unrelated edit as failed before it was attempted.\n await new DocumentRecordRepository(\n state.runtime.infra.execSql,\n ).clearDocumentSyncFailure({\n appKind: DOCUMENTS_APP_KIND,\n localId: state.localId,\n });\n\n // The snapshot was already republished progressively inside the loop as each\n // attachment settled, so there is nothing left to publish here.\n return { completed: true, nextRecord: currentRecord };\n}\n\n/** Settles one queued attachment; \"stop\" ends this pass early. */\nasync function syncNextPendingAttachment(\n upload: Omit<PendingAttachmentUploadInput, \"activeBindingBySlotId\">,\n progress: AttachmentSyncProgress,\n currentDoc: NonNullable<DocumentStoreState[\"doc\"]>,\n): Promise<\"continue\" | \"stop\"> {\n const { attachmentGeneration, pendingAttachment, state } = upload;\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n if (!(await loadRemoteAttachmentBindings({ ...upload, progress }))) {\n return \"stop\";\n }\n const outcome = await syncPendingAttachmentUpload({\n ...upload,\n activeBindingBySlotId: progress.activeBindingBySlotId,\n });\n if (outcome === \"retry\") {\n rearmStaleAttachmentSync(state, attachmentGeneration);\n return \"stop\";\n }\n // Re-check after the upload's awaits: settling writes local rows, which a\n // teardown that happened mid-upload has just deleted on purpose.\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n removeSettledPendingAttachment(state, currentDoc, pendingAttachment);\n if (outcome === \"uploaded\" || outcome === \"recovered\") {\n progress.settledAttachment = true;\n }\n if (outcome === \"uploaded\") progress.uploadedAttachment = true;\n return \"continue\";\n}\n\nasync function loadRemoteAttachmentBindings(input: {\n pendingAttachment: PendingAttachmentRecord;\n progress: AttachmentSyncProgress;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}): Promise<boolean> {\n const { pendingAttachment, progress, state } = input;\n const freshUpload =\n pendingAttachment.upload == null &&\n isNewPendingAttachmentSlot(state, pendingAttachment);\n if (progress.fetchedRemoteBindings || freshUpload) {\n return true;\n }\n\n const remoteBindings = await state.runtime.apiClient.listDocumentAttachments(\n input.remoteDocumentId,\n );\n if (!remoteBindings) {\n return false;\n }\n\n progress.fetchedRemoteBindings = true;\n for (const binding of remoteBindings) {\n progress.activeBindingBySlotId.set(binding.slotId, binding);\n }\n return true;\n}\n\ninterface PendingAttachmentUploadInput {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n attachmentGeneration: DocumentStoreSyncGeneration;\n carriedFirstUpdate?: CarriedFirstUpdate | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n pendingAttachment: PendingAttachmentRecord;\n policyOperation: PrincipalPolicyOperation;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}\n\nasync function recoverCommittedAttachment(\n input: PendingAttachmentUploadInput,\n): Promise<boolean> {\n const { pendingAttachment, state } = input;\n const persistedUpload = pendingAttachment.upload;\n const activeBinding = input.activeBindingBySlotId.get(\n pendingAttachment.slotId,\n );\n if (!persistedUpload || activeBinding?.blobId !== persistedUpload.blobId) {\n return false;\n }\n\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: persistedUpload.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n try {\n await settleRecoveredAttachment({\n attachmentGeneration: input.attachmentGeneration,\n binding: activeBinding,\n pendingAttachment,\n remoteDocumentId: input.remoteDocumentId,\n state,\n uploadLane,\n });\n return true;\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane,\n });\n throw error;\n }\n}\n\nfunction createAttachmentBaseUploadInput(input: {\n author: PreparedUploadDocumentAttachmentRequest[\"author\"];\n pendingUpload: PendingAttachmentUploadInput;\n resume: AttachmentUploadResume;\n source: BlobByteSource;\n sourceSnapshot: BlobSourceSnapshot;\n uploadLane: AttachmentUploadLaneReporter;\n}): PreparedUploadDocumentAttachmentRequest {\n const { pendingAttachment, state } = input.pendingUpload;\n return {\n author: input.author,\n blobId: input.resume.blobId,\n bytes: input.source,\n contentKey: input.resume.contentKey,\n contentKeyEpoch: input.resume.contentKeyEpoch,\n documentId: input.pendingUpload.remoteDocumentId,\n documentSync: input.pendingUpload.carriedFirstUpdate?.request,\n expectedBindingId:\n input.pendingUpload.activeBindingBySlotId.get(pendingAttachment.slotId)\n ?.bindingId ?? null,\n nonceSeed: input.resume.nonceSeed,\n multipart: input.resume.multipart,\n onMultipartProgress: input.uploadLane.onMultipartProgress,\n onStageResolved: input.resume.onStageResolved,\n onStageUnavailable: async (stageId) => {\n await input.resume.onStageUnavailable(\n stageId,\n input.pendingUpload.remoteDocumentId,\n );\n requestDocumentStoreSync(state);\n },\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n slotId: pendingAttachment.slotId,\n sourceSnapshot: input.sourceSnapshot,\n warmReferencedPrincipalPolicies:\n state.runtime.principalPolicies.createWarmer({\n operation: input.pendingUpload.policyOperation,\n }),\n };\n}\n\nasync function uploadPendingAttachmentBytes(input: {\n baseUploadInput: PreparedUploadDocumentAttachmentRequest;\n /** Read from the runtime the base input was built from. */\n blobAttachments: BlobAttachmentService;\n pendingUpload: PendingAttachmentUploadInput;\n uploadLane: AttachmentUploadLaneReporter;\n}): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input.pendingUpload;\n const writerProjection =\n state.writerProjection?.documentId === input.pendingUpload.remoteDocumentId\n ? state.writerProjection\n : null;\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n try {\n const uploadAttempt = await uploadCarryingFirstUpdate({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n carried: input.pendingUpload.carriedFirstUpdate,\n committed: (attempt) => attempt.uploaded?.response.documentSync,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n upload: () =>\n uploadAttachmentWithWriterProjectionRetry({\n baseUploadInput: input.baseUploadInput,\n blobAttachments: input.blobAttachments,\n state,\n writerProjection,\n }),\n });\n const { error: uploadError, remoteSyncBlocked, uploaded } = uploadAttempt;\n if (!uploaded) {\n if (remoteSyncBlocked) {\n input.uploadLane.failIfStarted(\n new Error(\"Attachment upload paused because remote sync is blocked.\"),\n );\n return \"retry\";\n }\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error: uploadError,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n return \"retry\";\n }\n\n await settleUploadedAttachment({\n activeBindingBySlotId: input.pendingUpload.activeBindingBySlotId,\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n pendingAttachment,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n uploadLane: input.uploadLane,\n uploaded,\n writerProjectionGeneration,\n });\n return \"uploaded\";\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n throw error;\n }\n}\n\nasync function syncPendingAttachmentUpload(\n input: PendingAttachmentUploadInput,\n): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input;\n // The binding fetch before this call awaits; a teardown during it must not\n // let a brand-new upload start against rows that no longer exist.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!pendingAttachmentMatchesIntent(input)) {\n return dropUnavailablePendingAttachment(input);\n }\n if (await recoverCommittedAttachment(input)) {\n return \"recovered\";\n }\n\n const source = await state.runtime.infra.blobStore.openByteSource(\n pendingAttachment.storageKey,\n );\n if (!source) {\n return dropUnavailablePendingAttachment(input);\n }\n\n const author = resolveDocumentCreateAuthor(state.runtime);\n if (!author) {\n state.runtime.util.log(\n \"Documents: skipped attachment upload because the writer context is unavailable.\",\n );\n return \"retry\";\n }\n\n const prepared = await resolveAttachmentSourceUpload({\n attachmentGeneration: input.attachmentGeneration,\n pendingAttachment,\n source,\n state,\n });\n // Preparation awaited (byte-source open plus resume resolution); a teardown\n // during those awaits must not let the upload itself start — its remote\n // commit could not be recalled once sent.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!prepared) return dropUnavailablePendingAttachment(input);\n const { resume, snapshot } = prepared;\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: resume.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n const baseUploadInput = createAttachmentBaseUploadInput({\n author,\n pendingUpload: input,\n resume,\n source,\n sourceSnapshot: snapshot,\n uploadLane,\n });\n return uploadPendingAttachmentBytes({\n baseUploadInput,\n blobAttachments: state.runtime.blobAttachments,\n pendingUpload: input,\n uploadLane,\n });\n}\n"]}
1
+ {"version":3,"file":"syncAttachments.js","sourceRoot":"","sources":["syncAttachments.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,kBAAkB,EAElB,wBAAwB,EAExB,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AAE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B,iFAAiF,CAClF,CAAC;QACF,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,6BAA6B,CAAC;QACnD,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,iBAAiB;QACjB,MAAM;QACN,KAAK;KACN,CAAC,CAAC;IACH,4EAA4E;IAC5E,wEAAwE;IACxE,0CAA0C;IAC1C,IACE,CAAC,oCAAoC,CAAC,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,EACxE,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,IAAI,CAAC,QAAQ;QAAE,OAAO,gCAAgC,CAAC,KAAK,CAAC,CAAC;IAC9D,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC;IACtC,MAAM,UAAU,GAAG,kCAAkC,CAAC;QACpD,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;QAC5C,iBAAiB;KAClB,CAAC,CAAC;IACH,MAAM,eAAe,GAAG,+BAA+B,CAAC;QACtD,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,MAAM;QACN,MAAM;QACN,cAAc,EAAE,QAAQ;QACxB,UAAU;KACX,CAAC,CAAC;IACH,OAAO,4BAA4B,CAAC;QAClC,eAAe;QACf,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,eAAe;QAC9C,aAAa,EAAE,KAAK;QACpB,UAAU;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n BlobAttachmentService,\n BlobByteSource,\n BlobSourceSnapshot,\n} from \"../../../../workflows/blobs\";\nimport type { PreparedUploadDocumentAttachmentRequest } from \"../../../../workflows/blobs/upload\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type PendingAttachmentRecord,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { markOriginatedDocuments } from \"../../../../workflows/sync/coordination\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport {\n dropUnavailablePendingAttachment,\n pendingAttachmentMatchesIntent,\n resolveAttachmentSourceUpload,\n} from \"../attachmentUpload/attachmentSourceUpload\";\nimport { uploadAttachmentWithWriterProjectionRetry } from \"../attachmentUpload/attachmentUploadAttempt\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadLaneReporter,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { AttachmentUploadResume } from \"../attachmentUpload/attachmentUploadResume\";\nimport type {\n DocumentAttachmentBinding,\n DocumentStoreState,\n EncapsulationKeyPair,\n PendingMutationSyncResult,\n} from \"../state\";\nimport { reportAttachmentUploadFailure } from \"./attachmentUploadFailure\";\nimport {\n type CarriedFirstUpdate,\n ensureRemoteDocumentCarryingFirstUpdate,\n uploadCarryingFirstUpdate,\n} from \"./carriedFirstUpdate\";\nimport {\n isNewPendingAttachmentSlot,\n removeSettledPendingAttachment,\n settleRecoveredAttachment,\n settleUploadedAttachment,\n} from \"./syncAttachmentSettlement\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\n// Preserve transient failures for retry. Drop irrecoverable missing bytes so a\n// pending attachment cannot wedge the document sync lane across restarts.\ntype PendingAttachmentUploadOutcome =\n | \"uploaded\"\n | \"recovered\"\n | \"retry\"\n | \"dropped\";\n\ninterface AttachmentSyncProgress {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n fetchedRemoteBindings: boolean;\n settledAttachment: boolean;\n uploadedAttachment: boolean;\n}\n\nfunction rearmStaleAttachmentSync(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n): void {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nexport async function syncPendingAttachments(\n state: DocumentStoreState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n attachmentGeneration: DocumentStoreSyncGeneration,\n policyOperation: PrincipalPolicyOperation,\n): Promise<PendingMutationSyncResult> {\n if (state.pendingAttachments.length === 0) {\n return { completed: false, nextRecord };\n }\n\n const currentDoc = state.doc;\n if (!currentDoc) {\n return { completed: false, nextRecord };\n }\n\n let carriedFirstUpdate: CarriedFirstUpdate | undefined;\n const currentRecord = nextRecord.documentId\n ? nextRecord\n : await ensureRemoteDocumentCarryingFirstUpdate({\n currentDoc,\n encapsulationKeyPair,\n generation: attachmentGeneration,\n nextRecord,\n onCarried: (carried) => {\n carriedFirstUpdate = carried;\n },\n policyOperation,\n state,\n });\n if (!currentRecord?.documentId) {\n return { completed: false, nextRecord };\n }\n const remoteDocumentId = currentRecord.documentId;\n\n const progress: AttachmentSyncProgress = {\n activeBindingBySlotId: new Map(),\n fetchedRemoteBindings: false,\n settledAttachment: false,\n uploadedAttachment: false,\n };\n\n for (const pendingAttachment of [...state.pendingAttachments]) {\n const step = await syncNextPendingAttachment(\n {\n attachmentGeneration,\n carriedFirstUpdate,\n encapsulationKeyPair,\n pendingAttachment,\n policyOperation,\n remoteDocumentId,\n state,\n },\n progress,\n currentDoc,\n );\n // Only the first bind may carry it; a failed one leaves the row queued.\n carriedFirstUpdate = undefined;\n if (step === \"stop\") {\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n }\n\n if (!progress.settledAttachment) {\n return { completed: false, nextRecord: currentRecord };\n }\n\n // Only record the origination once a write landed: the server echoes a\n // document_update_created for it, and this lets the reconciler skip\n // rediscovering a delta we already have locally rather than cycling its lane\n // per uploaded file. Marking here (not before the loop) avoids a dangling id\n // that would suppress the next genuine remote update if every upload failed.\n if (progress.uploadedAttachment) {\n markOriginatedDocuments(state.runtime.state.domainScope, [\n remoteDocumentId,\n ]);\n }\n\n // A settled attachment pass invalidates any recorded failure itself: a\n // retried upload with no pending CRDT update never reaches the document\n // submission that would otherwise clear it, and the stale row would flag the\n // next unrelated edit as failed before it was attempted.\n await new DocumentRecordRepository(\n state.runtime.infra.execSql,\n ).clearDocumentSyncFailure({\n appKind: DOCUMENTS_APP_KIND,\n localId: state.localId,\n });\n\n // The snapshot was already republished progressively inside the loop as each\n // attachment settled, so there is nothing left to publish here.\n return { completed: true, nextRecord: currentRecord };\n}\n\n/** Settles one queued attachment; \"stop\" ends this pass early. */\nasync function syncNextPendingAttachment(\n upload: Omit<PendingAttachmentUploadInput, \"activeBindingBySlotId\">,\n progress: AttachmentSyncProgress,\n currentDoc: NonNullable<DocumentStoreState[\"doc\"]>,\n): Promise<\"continue\" | \"stop\"> {\n const { attachmentGeneration, pendingAttachment, state } = upload;\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n if (!(await loadRemoteAttachmentBindings({ ...upload, progress }))) {\n return \"stop\";\n }\n const outcome = await syncPendingAttachmentUpload({\n ...upload,\n activeBindingBySlotId: progress.activeBindingBySlotId,\n });\n if (outcome === \"retry\") {\n rearmStaleAttachmentSync(state, attachmentGeneration);\n return \"stop\";\n }\n // Re-check after the upload's awaits: settling writes local rows, which a\n // teardown that happened mid-upload has just deleted on purpose.\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n removeSettledPendingAttachment(state, currentDoc, pendingAttachment);\n if (outcome === \"uploaded\" || outcome === \"recovered\") {\n progress.settledAttachment = true;\n }\n if (outcome === \"uploaded\") progress.uploadedAttachment = true;\n return \"continue\";\n}\n\nasync function loadRemoteAttachmentBindings(input: {\n pendingAttachment: PendingAttachmentRecord;\n progress: AttachmentSyncProgress;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}): Promise<boolean> {\n const { pendingAttachment, progress, state } = input;\n const freshUpload =\n pendingAttachment.upload == null &&\n isNewPendingAttachmentSlot(state, pendingAttachment);\n if (progress.fetchedRemoteBindings || freshUpload) {\n return true;\n }\n\n const remoteBindings = await state.runtime.apiClient.listDocumentAttachments(\n input.remoteDocumentId,\n );\n if (!remoteBindings) {\n return false;\n }\n\n progress.fetchedRemoteBindings = true;\n for (const binding of remoteBindings) {\n progress.activeBindingBySlotId.set(binding.slotId, binding);\n }\n return true;\n}\n\ninterface PendingAttachmentUploadInput {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n attachmentGeneration: DocumentStoreSyncGeneration;\n carriedFirstUpdate?: CarriedFirstUpdate | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n pendingAttachment: PendingAttachmentRecord;\n policyOperation: PrincipalPolicyOperation;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}\n\nasync function recoverCommittedAttachment(\n input: PendingAttachmentUploadInput,\n): Promise<boolean> {\n const { pendingAttachment, state } = input;\n const persistedUpload = pendingAttachment.upload;\n const activeBinding = input.activeBindingBySlotId.get(\n pendingAttachment.slotId,\n );\n if (!persistedUpload || activeBinding?.blobId !== persistedUpload.blobId) {\n return false;\n }\n\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: persistedUpload.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n try {\n await settleRecoveredAttachment({\n attachmentGeneration: input.attachmentGeneration,\n binding: activeBinding,\n pendingAttachment,\n remoteDocumentId: input.remoteDocumentId,\n state,\n uploadLane,\n });\n return true;\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane,\n });\n throw error;\n }\n}\n\nfunction createAttachmentBaseUploadInput(input: {\n author: PreparedUploadDocumentAttachmentRequest[\"author\"];\n pendingUpload: PendingAttachmentUploadInput;\n resume: AttachmentUploadResume;\n source: BlobByteSource;\n sourceSnapshot: BlobSourceSnapshot;\n uploadLane: AttachmentUploadLaneReporter;\n}): PreparedUploadDocumentAttachmentRequest {\n const { pendingAttachment, state } = input.pendingUpload;\n return {\n author: input.author,\n blobId: input.resume.blobId,\n bytes: input.source,\n contentKey: input.resume.contentKey,\n contentKeyEpoch: input.resume.contentKeyEpoch,\n documentId: input.pendingUpload.remoteDocumentId,\n documentSync: input.pendingUpload.carriedFirstUpdate?.request,\n expectedBindingId:\n input.pendingUpload.activeBindingBySlotId.get(pendingAttachment.slotId)\n ?.bindingId ?? null,\n nonceSeed: input.resume.nonceSeed,\n multipart: input.resume.multipart,\n onMultipartProgress: input.uploadLane.onMultipartProgress,\n onStageResolved: input.resume.onStageResolved,\n onStageUnavailable: async (stageId) => {\n await input.resume.onStageUnavailable(\n stageId,\n input.pendingUpload.remoteDocumentId,\n );\n requestDocumentStoreSync(state);\n },\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n slotId: pendingAttachment.slotId,\n sourceSnapshot: input.sourceSnapshot,\n warmReferencedPrincipalPolicies:\n state.runtime.principalPolicies.createWarmer({\n operation: input.pendingUpload.policyOperation,\n }),\n };\n}\n\nasync function uploadPendingAttachmentBytes(input: {\n baseUploadInput: PreparedUploadDocumentAttachmentRequest;\n /** Read from the runtime the base input was built from. */\n blobAttachments: BlobAttachmentService;\n pendingUpload: PendingAttachmentUploadInput;\n uploadLane: AttachmentUploadLaneReporter;\n}): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input.pendingUpload;\n const writerProjection =\n state.writerProjection?.documentId === input.pendingUpload.remoteDocumentId\n ? state.writerProjection\n : null;\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n try {\n const uploadAttempt = await uploadCarryingFirstUpdate({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n carried: input.pendingUpload.carriedFirstUpdate,\n committed: (attempt) => attempt.uploaded?.response.documentSync,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n upload: () =>\n uploadAttachmentWithWriterProjectionRetry({\n baseUploadInput: input.baseUploadInput,\n blobAttachments: input.blobAttachments,\n state,\n writerProjection,\n }),\n });\n const { error: uploadError, remoteSyncBlocked, uploaded } = uploadAttempt;\n if (!uploaded) {\n if (remoteSyncBlocked) {\n input.uploadLane.failIfStarted(\n new Error(\"Attachment upload paused because remote sync is blocked.\"),\n );\n return \"retry\";\n }\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error: uploadError,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n return \"retry\";\n }\n\n await settleUploadedAttachment({\n activeBindingBySlotId: input.pendingUpload.activeBindingBySlotId,\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n pendingAttachment,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n uploadLane: input.uploadLane,\n uploaded,\n writerProjectionGeneration,\n });\n return \"uploaded\";\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n throw error;\n }\n}\n\nasync function syncPendingAttachmentUpload(\n input: PendingAttachmentUploadInput,\n): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input;\n // The binding fetch before this call awaits; a teardown during it must not\n // let a brand-new upload start against rows that no longer exist.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!pendingAttachmentMatchesIntent(input)) {\n return dropUnavailablePendingAttachment(input);\n }\n if (await recoverCommittedAttachment(input)) {\n return \"recovered\";\n }\n\n const source = await state.runtime.infra.blobStore.openByteSource(\n pendingAttachment.storageKey,\n );\n if (!source) {\n return dropUnavailablePendingAttachment(input);\n }\n\n const author = resolveDocumentCreateAuthor(state.runtime);\n if (!author) {\n state.runtime.util.log(\n \"Documents: skipped attachment upload because the writer context is unavailable.\",\n );\n return \"retry\";\n }\n\n const prepared = await resolveAttachmentSourceUpload({\n attachmentGeneration: input.attachmentGeneration,\n pendingAttachment,\n source,\n state,\n });\n // Preparation awaited (byte-source open plus resume resolution); a teardown\n // during those awaits must not let the upload itself start — its remote\n // commit could not be recalled once sent.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!prepared) return dropUnavailablePendingAttachment(input);\n const { resume, snapshot } = prepared;\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: resume.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n const baseUploadInput = createAttachmentBaseUploadInput({\n author,\n pendingUpload: input,\n resume,\n source,\n sourceSnapshot: snapshot,\n uploadLane,\n });\n return uploadPendingAttachmentBytes({\n baseUploadInput,\n blobAttachments: state.runtime.blobAttachments,\n pendingUpload: input,\n uploadLane,\n });\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { KeyingVerificationError, } from "../../../../internal/crypto/index.js";
2
2
  import { verifiedContainerCreateManifest, verifyContainerDestinationProjection, } from "../../../../data/keyingProjectionVerification/index.js";
3
3
  import { isKeyingVerificationError, reportKeyingVerificationErrorInCauseChain, } from "../../../../data/keyingProjectionVerification/error.js";
4
+ import { openPrincipalPolicyBundleReader } from "../../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
4
5
  import { errorMessage } from "../../../../data/shared/errorMessage.js";
5
6
  import { settleContainerCreateIntent } from "./createIntentSettlement.js";
6
7
  const LABEL = "Container create conflict";
@@ -26,6 +27,7 @@ async function verifyAdoptableProjection(input) {
26
27
  }
27
28
  const { path, verifiedByHash } = await verifyContainerDestinationProjection({
28
29
  execSql: input.state.runtime.infra.execSql,
30
+ openPrincipalPolicyBundleReader,
29
31
  projection,
30
32
  resolveUserKey: input.state.resolveProjectionUserKey,
31
33
  warmReferencedPrincipalPolicies: input.state.runtime.principalPolicies.createWarmer(),