@tearleads/client-sdk 0.1.211 → 0.1.214

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 (107) hide show
  1. package/client/containerContents/documentDiscovery.js +2 -2
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/client/organizations/organizationReadModels.js +3 -3
  4. package/client/organizations/organizationReadModels.js.map +1 -1
  5. package/data/persistence/container-contents/containerContentsPersistence.js +2 -2
  6. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  7. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +2 -2
  8. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  9. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +2 -2
  10. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js.map +1 -1
  11. package/data/persistence/container-contents/containerPendingUpdatePersistence.js +6 -6
  12. package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
  13. package/data/persistence/documents/documentDiscoveryEvidencePersistence.d.ts +11 -2
  14. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +89 -77
  15. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  16. package/data/persistence/documents/internal/discardDocument.js +4 -4
  17. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  18. package/data/persistence/documents/internal/discoveredDocumentUpsert.js +3 -3
  19. package/data/persistence/documents/internal/discoveredDocumentUpsert.js.map +1 -1
  20. package/data/persistence/documents/internal/documentDeletionPersistence.js +8 -8
  21. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  22. package/data/persistence/documents/internal/documentMutationPersistence.js +4 -3
  23. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  24. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +2 -2
  25. package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
  26. package/data/persistence/documents/internal/rowQueryPersistence.js +3 -3
  27. package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
  28. package/data/persistence/documents/internal/syncQueuePersistence.js +12 -13
  29. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  30. package/data/persistence/documents/records/documentHistoryPersistence.d.ts +24 -20
  31. package/data/persistence/documents/records/documentHistoryPersistence.js +59 -90
  32. package/data/persistence/documents/records/documentHistoryPersistence.js.map +1 -1
  33. package/data/persistence/documents/records/documentPendingUpdatePersistence.d.ts +10 -25
  34. package/data/persistence/documents/records/documentPendingUpdatePersistence.js +19 -79
  35. package/data/persistence/documents/records/documentPendingUpdatePersistence.js.map +1 -1
  36. package/data/persistence/documents/records/documentQueuedUpdateReplacement.d.ts +4 -14
  37. package/data/persistence/documents/records/documentQueuedUpdateReplacement.js +27 -42
  38. package/data/persistence/documents/records/documentQueuedUpdateReplacement.js.map +1 -1
  39. package/data/persistence/documents/records/documentRecordPersistence.d.ts +5 -8
  40. package/data/persistence/documents/records/documentRecordPersistence.js +2 -55
  41. package/data/persistence/documents/records/documentRecordPersistence.js.map +1 -1
  42. package/data/persistence/documents/records/documentRecordRepository.d.ts +133 -0
  43. package/data/persistence/documents/records/documentRecordRepository.js +286 -0
  44. package/data/persistence/documents/records/documentRecordRepository.js.map +1 -0
  45. package/data/persistence/documents/records/documentSyncFailurePersistence.d.ts +9 -12
  46. package/data/persistence/documents/records/documentSyncFailurePersistence.js +19 -34
  47. package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -1
  48. package/data/persistence/documents/records/index.d.ts +4 -19
  49. package/data/persistence/documents/records/index.js +5 -29
  50. package/data/persistence/documents/records/index.js.map +1 -1
  51. package/data/persistence/organizations/organizationPresentationDenialPersistence.js +0 -43
  52. package/data/persistence/organizations/organizationPresentationDenialPersistence.js.map +1 -1
  53. package/data/persistence/organizations/organizationReadModelMemberLoad.d.ts +7 -2
  54. package/data/persistence/organizations/organizationReadModelMemberLoad.js +22 -27
  55. package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
  56. package/data/persistence/organizations/organizationReadModelPersistence.js +38 -81
  57. package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
  58. package/data/persistence/organizations/organizationReadModelPurge.js +0 -38
  59. package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
  60. package/data/persistence/organizations/organizationReadModelRepository.js +264 -0
  61. package/data/persistence/organizations/organizationReadModelRepository.js.map +1 -0
  62. package/package.json +1 -1
  63. package/stores/documents/documentStore/sync/attachmentUploadFailure.js +2 -2
  64. package/stores/documents/documentStore/sync/attachmentUploadFailure.js.map +1 -1
  65. package/stores/documents/documentStore/sync/syncAttachments.js +2 -2
  66. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  67. package/stores/documents/documentStore/sync/syncShared.js +2 -2
  68. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  69. package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js.map +1 -1
  70. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
  71. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  72. package/workflows/container-contents/pendingWrites/index.js +4 -3
  73. package/workflows/container-contents/pendingWrites/index.js.map +1 -1
  74. package/workflows/container-contents/recovery/accessRestoration.js +2 -2
  75. package/workflows/container-contents/recovery/accessRestoration.js.map +1 -1
  76. package/workflows/documents/index.d.ts +1 -1
  77. package/workflows/documents/index.js +1 -1
  78. package/workflows/documents/index.js.map +1 -1
  79. package/workflows/documents/syncRekeys/syncRecoveryRekey.js +3 -2
  80. package/workflows/documents/syncRekeys/syncRecoveryRekey.js.map +1 -1
  81. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +6 -2
  82. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
  83. package/workflows/organizations/index.d.ts +0 -1
  84. package/workflows/organizations/index.js +0 -1
  85. package/workflows/organizations/index.js.map +1 -1
  86. package/workflows/organizations/policyHistory/policyHistoryAccessDenial.js +7 -4
  87. package/workflows/organizations/policyHistory/policyHistoryAccessDenial.js.map +1 -1
  88. package/workflows/organizations/readModel/dataUsageReadModel.js +2 -2
  89. package/workflows/organizations/readModel/dataUsageReadModel.js.map +1 -1
  90. package/workflows/organizations/readModel/listLocalOrganizations.js +6 -4
  91. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
  92. package/workflows/organizations/readModel/localReadModelDetails.js +8 -9
  93. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  94. package/workflows/organizations/readModel/organizationPresentationAccessState.js +2 -2
  95. package/workflows/organizations/readModel/organizationPresentationAccessState.js.map +1 -1
  96. package/workflows/organizations/readModel/readModelProjection.d.ts +1 -1
  97. package/workflows/organizations/readModel/readModelProjection.js +12 -13
  98. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
  99. package/data/persistence/organizations/organizationAccessRevocationPersistence.js +0 -49
  100. package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +0 -1
  101. package/data/persistence/organizations/organizationGroupNamePersistence.js +0 -33
  102. package/data/persistence/organizations/organizationGroupNamePersistence.js.map +0 -1
  103. package/data/persistence/organizations/organizationProfileDocumentPointers.js +0 -32
  104. package/data/persistence/organizations/organizationProfileDocumentPointers.js.map +0 -1
  105. package/data/persistence/organizations/organizationReadModelCursorPersistence.d.ts +0 -15
  106. package/data/persistence/organizations/organizationReadModelCursorPersistence.js +0 -25
  107. package/data/persistence/organizations/organizationReadModelCursorPersistence.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"documentDiscoveryEvidence.js","sourceRoot":"","sources":["documentDiscoveryEvidence.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,8BAA8B,EAC9B,2BAA2B,GAC5B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAEhF,OAAO,EAAE,+BAA+B,EAAE,MAAM,qBAAqB,CAAC;AAEtE,wEAAwE;AACxE,yEAAyE;AACzE,SA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CAAC;QACF,MAAM,OAAO,CAAC,GAAG,CACf,KAAK,CAAC,IAAI,CACR,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,8BAA8B,EAAE,UAAU,CAAC,MAAM,CAAC,EAAE,EACvE,MAAM,CACP,CACF,CAAC;QACF,OAAO;YACL,MAAM,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC;YAC9B,SAAS;YACT,MAAM,EAAE,KAAK,IAAI,EAAE;gBACjB,MAAM,KAAK,CAAC,WAAW,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;gBAC7C,MAAM,UAAU,GAAG,MAAM,KAAK,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;gBACxD,IAAI,UAAU,KAAK,IAAI;oBAAE,kBAAkB,EAAE,CAAC,UAAU,CAAC,CAAC;gBAC1D,OAAO,UAAU,KAAK,IAAI,CAAC;YAC7B,CAAC;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { DiscoveredDocumentInput } from \"../../../data/documents/documentSummary\";\nimport type {\n DiscoveredDocumentCandidate,\n DocumentDiscoveryEvidenceStore,\n} from \"../../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport type {\n DocumentHeadLinkSetLoader,\n LocalDocumentAccessEpochLoader,\n VerifiedDocumentHeadLinkSet,\n} from \"../tombstones/documentTombstoneEvidence\";\nimport {\n HEAD_LINK_SET_LOAD_CONCURRENCY,\n HEAD_LINK_SET_LOADS_PER_RUN,\n} from \"../tombstones/documentTombstoneEvidence\";\nimport { groupPendingDocumentDiscoveries } from \"./documentDiscoveryCandidates\";\nimport type { DiscoverContainerDocumentsOptions } from \"./documentDiscoveryTypes\";\nimport { documentHeadMatchesOrganization } from \"./documentHeadScope\";\n\n// A same-epoch head can predate a link addition. Only the named head or\n// terminal signed purge evidence can settle a candidate without a retry.\nfunction unlistedHeadVerdict(\n head: VerifiedDocumentHeadLinkSet,\n input: DiscoveredDocumentCandidate,\n): null | \"unavailable\" {\n return head.accessEpoch > input.accessEpoch ||\n head.accessStateHash === input.accessStateHash ||\n (!head.accessStateHash && head.accessEpoch === Number.MAX_SAFE_INTEGER)\n ? null\n : \"unavailable\";\n}\n\nasync function verifyInput(\n input: DiscoveredDocumentCandidate,\n loadHead: DocumentHeadLinkSetLoader,\n loadLocalEpoch: LocalDocumentAccessEpochLoader,\n store: DocumentDiscoveryEvidenceStore,\n generation: number,\n organizationId: string | undefined,\n): Promise<DiscoveredDocumentInput | null | \"unavailable\"> {\n const localEpoch = await loadLocalEpoch(input.documentId).catch(\n () => Number.MAX_SAFE_INTEGER,\n );\n const cached = await store.loadHead(input.documentId, input.accessStateHash);\n const minimumEpoch = Math.max(localEpoch, input.accessEpoch);\n const head =\n cached && cached.accessEpoch >= minimumEpoch\n ? cached\n : await loadHead(\n input.documentId,\n input.accessEpoch >= localEpoch\n ? (input.accessStateHash ?? undefined)\n : undefined,\n );\n if (head === \"not-found\") return null;\n if (!head || head.accessEpoch < Math.max(localEpoch, input.accessEpoch))\n return \"unavailable\";\n if (!documentHeadMatchesOrganization(head, organizationId))\n return \"unavailable\";\n // A stale first lane must not hide a document present in another listed lane.\n const containerId = input.listedContainerIds.find((id) =>\n head.linkedContainerIds.includes(id),\n );\n if (!containerId) return unlistedHeadVerdict(head, input);\n if (!head.accessStateHash) return \"unavailable\";\n if (!(await store.saveHead(input.documentId, head, generation)))\n return \"unavailable\";\n const { listedContainerIds: _listedContainerIds, ...document } = input;\n return {\n ...document,\n containerId,\n accessEpoch: head.accessEpoch,\n accessStateHash: head.accessStateHash,\n linkedContainerIds: head.linkedContainerIds,\n };\n}\n\n/**\n * Persist untrusted candidates before advancing listing watermarks. Each pass\n * checks a bounded batch; unavailable heads back off independently while verified\n * siblings and tombstones still settle. Acknowledgement follows local apply so\n * a crash cannot lose a candidate behind an already advanced listing watermark.\n */\nexport function createDiscoveredDocumentVerifier(\n organizationId: string | undefined,\n loadHead: DocumentHeadLinkSetLoader,\n loadLocalEpoch: LocalDocumentAccessEpochLoader,\n store: DocumentDiscoveryEvidenceStore,\n onPendingDiscovery?: ((delayMs: number) => void) | undefined,\n): DiscoverContainerDocumentsOptions[\"verifyDiscoveredDocuments\"] {\n return async (inputs, containerIds, generation, tombstones = []) => {\n const isCurrent = () => store.isCurrent(generation);\n const lanes = new Set(containerIds);\n const removed = tombstones.filter((row) => lanes.has(row.containerId));\n if (!(await store.stage(inputs, generation, removed)))\n return { inputs: [], isCurrent, commit: async () => true };\n const candidates = groupPendingDocumentDiscoveries(\n await store.pending(containerIds, HEAD_LINK_SET_LOADS_PER_RUN),\n );\n const verified = new Map<string, DiscoveredDocumentInput>();\n const settled: DiscoveredDocumentCandidate[] = [];\n let next = 0;\n const worker = async () => {\n while (next < candidates.length) {\n const group = candidates[next++];\n if (!group) break;\n const { input, rows } = group;\n const result = await verifyInput(\n input,\n loadHead,\n loadLocalEpoch,\n store,\n generation,\n organizationId,\n );\n if (result === \"unavailable\") {\n await Promise.all(rows.map((row) => store.defer(row, generation)));\n continue;\n }\n if (result) verified.set(result.documentId, result);\n settled.push(...rows);\n }\n };\n await Promise.all(\n Array.from(\n { length: Math.min(HEAD_LINK_SET_LOAD_CONCURRENCY, candidates.length) },\n worker,\n ),\n );\n return {\n inputs: [...verified.values()],\n isCurrent,\n commit: async () => {\n await store.acknowledge(settled, generation);\n const retryDelay = await store.retryDelay(containerIds);\n if (retryDelay !== null) onPendingDiscovery?.(retryDelay);\n return retryDelay === null;\n },\n };\n };\n}\n"]}
1
+ {"version":3,"file":"documentDiscoveryEvidence.js","sourceRoot":"","sources":["documentDiscoveryEvidence.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,8BAA8B,EAC9B,2BAA2B,GAC5B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAEhF,OAAO,EAAE,+BAA+B,EAAE,MAAM,qBAAqB,CAAC;AAEtE,wEAAwE;AACxE,yEAAyE;AACzE,S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AC,CAAC;QACF,MAAM,OAAO,CAAC,GAAG,CACf,KAAK,CAAC,IAAI,CACR,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,8BAA8B,EAAE,UAAU,CAAC,MAAM,CAAC,EAAE,EACvE,MAAM,CACP,CACF,CAAC;QACF,OAAO;YACL,MAAM,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC;YAC9B,SAAS;YACT,MAAM,EAAE,KAAK,IAAI,EAAE;gBACjB,MAAM,KAAK,CAAC,WAAW,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;gBAC7C,MAAM,UAAU,GAAG,MAAM,KAAK,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;gBACxD,IAAI,UAAU,KAAK,IAAI;oBAAE,kBAAkB,EAAE,CAAC,UAAU,CAAC,CAAC;gBAC1D,OAAO,UAAU,KAAK,IAAI,CAAC;YAC7B,CAAC;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { DiscoveredDocumentInput } from \"../../../data/documents/documentSummary\";\nimport type {\n DiscoveredDocumentCandidate,\n DocumentDiscoveryEvidenceRepository,\n} from \"../../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport type {\n DocumentHeadLinkSetLoader,\n LocalDocumentAccessEpochLoader,\n VerifiedDocumentHeadLinkSet,\n} from \"../tombstones/documentTombstoneEvidence\";\nimport {\n HEAD_LINK_SET_LOAD_CONCURRENCY,\n HEAD_LINK_SET_LOADS_PER_RUN,\n} from \"../tombstones/documentTombstoneEvidence\";\nimport { groupPendingDocumentDiscoveries } from \"./documentDiscoveryCandidates\";\nimport type { DiscoverContainerDocumentsOptions } from \"./documentDiscoveryTypes\";\nimport { documentHeadMatchesOrganization } from \"./documentHeadScope\";\n\n// A same-epoch head can predate a link addition. Only the named head or\n// terminal signed purge evidence can settle a candidate without a retry.\nfunction unlistedHeadVerdict(\n head: VerifiedDocumentHeadLinkSet,\n input: DiscoveredDocumentCandidate,\n): null | \"unavailable\" {\n return head.accessEpoch > input.accessEpoch ||\n head.accessStateHash === input.accessStateHash ||\n (!head.accessStateHash && head.accessEpoch === Number.MAX_SAFE_INTEGER)\n ? null\n : \"unavailable\";\n}\n\nasync function verifyInput(\n input: DiscoveredDocumentCandidate,\n loadHead: DocumentHeadLinkSetLoader,\n loadLocalEpoch: LocalDocumentAccessEpochLoader,\n store: DocumentDiscoveryEvidenceRepository,\n generation: number,\n organizationId: string | undefined,\n): Promise<DiscoveredDocumentInput | null | \"unavailable\"> {\n const localEpoch = await loadLocalEpoch(input.documentId).catch(\n () => Number.MAX_SAFE_INTEGER,\n );\n const cached = await store.loadHead(input.documentId, input.accessStateHash);\n const minimumEpoch = Math.max(localEpoch, input.accessEpoch);\n const head =\n cached && cached.accessEpoch >= minimumEpoch\n ? cached\n : await loadHead(\n input.documentId,\n input.accessEpoch >= localEpoch\n ? (input.accessStateHash ?? undefined)\n : undefined,\n );\n if (head === \"not-found\") return null;\n if (!head || head.accessEpoch < Math.max(localEpoch, input.accessEpoch))\n return \"unavailable\";\n if (!documentHeadMatchesOrganization(head, organizationId))\n return \"unavailable\";\n // A stale first lane must not hide a document present in another listed lane.\n const containerId = input.listedContainerIds.find((id) =>\n head.linkedContainerIds.includes(id),\n );\n if (!containerId) return unlistedHeadVerdict(head, input);\n if (!head.accessStateHash) return \"unavailable\";\n if (!(await store.saveHead(input.documentId, head, generation)))\n return \"unavailable\";\n const { listedContainerIds: _listedContainerIds, ...document } = input;\n return {\n ...document,\n containerId,\n accessEpoch: head.accessEpoch,\n accessStateHash: head.accessStateHash,\n linkedContainerIds: head.linkedContainerIds,\n };\n}\n\n/**\n * Persist untrusted candidates before advancing listing watermarks. Each pass\n * checks a bounded batch; unavailable heads back off independently while verified\n * siblings and tombstones still settle. Acknowledgement follows local apply so\n * a crash cannot lose a candidate behind an already advanced listing watermark.\n */\nexport function createDiscoveredDocumentVerifier(\n organizationId: string | undefined,\n loadHead: DocumentHeadLinkSetLoader,\n loadLocalEpoch: LocalDocumentAccessEpochLoader,\n store: DocumentDiscoveryEvidenceRepository,\n onPendingDiscovery?: ((delayMs: number) => void) | undefined,\n): DiscoverContainerDocumentsOptions[\"verifyDiscoveredDocuments\"] {\n return async (inputs, containerIds, generation, tombstones = []) => {\n const isCurrent = () => store.isCurrent(generation);\n const lanes = new Set(containerIds);\n const removed = tombstones.filter((row) => lanes.has(row.containerId));\n if (!(await store.stage(inputs, generation, removed)))\n return { inputs: [], isCurrent, commit: async () => true };\n const candidates = groupPendingDocumentDiscoveries(\n await store.pending(containerIds, HEAD_LINK_SET_LOADS_PER_RUN),\n );\n const verified = new Map<string, DiscoveredDocumentInput>();\n const settled: DiscoveredDocumentCandidate[] = [];\n let next = 0;\n const worker = async () => {\n while (next < candidates.length) {\n const group = candidates[next++];\n if (!group) break;\n const { input, rows } = group;\n const result = await verifyInput(\n input,\n loadHead,\n loadLocalEpoch,\n store,\n generation,\n organizationId,\n );\n if (result === \"unavailable\") {\n await Promise.all(rows.map((row) => store.defer(row, generation)));\n continue;\n }\n if (result) verified.set(result.documentId, result);\n settled.push(...rows);\n }\n };\n await Promise.all(\n Array.from(\n { length: Math.min(HEAD_LINK_SET_LOAD_CONCURRENCY, candidates.length) },\n worker,\n ),\n );\n return {\n inputs: [...verified.values()],\n isCurrent,\n commit: async () => {\n await store.acknowledge(settled, generation);\n const retryDelay = await store.retryDelay(containerIds);\n if (retryDelay !== null) onPendingDiscovery?.(retryDelay);\n return retryDelay === null;\n },\n };\n };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { importDecryptedDocumentSyncUpdates, validateDocumentSyncUpdateImports, } from "../../../data/documents/shared/sync/documentSyncUpdateIsolation.js";
2
- import { recordDocumentSyncFailure } from "../../../data/persistence/documents/records/index.js";
2
+ import { DocumentRecordRepository } from "../../../data/persistence/documents/records/index.js";
3
3
  import { getClientSQLitePersistenceRuntime } from "../../../data/sqlite/sqlitePersistenceRuntime.js";
4
4
  import { runSerializedSqlMutation, } from "../../../data/sqlite/sqlSchema.js";
5
5
  import { reportDocumentSyncQuarantine } from "../../documents/sync/reportDocumentSyncQuarantine.js";
@@ -8,7 +8,7 @@ export async function recordCurrentMetadataSyncFailure(input) {
8
8
  await getClientSQLitePersistenceRuntime(lockedExecSql).guardedTransaction(async () => {
9
9
  if (input.isCurrent?.() === false)
10
10
  return;
11
- await recordDocumentSyncFailure(lockedExecSql, input.metadataScope, input.failure);
11
+ await new DocumentRecordRepository(lockedExecSql).recordDocumentSyncFailure(input.metadataScope, input.failure);
12
12
  }, () => input.isCurrent?.() !== false);
13
13
  });
14
14
  }
@@ -1 +1 @@
1
- {"version":3,"file":"metadataIncomingUpdateIsolation.js","sourceRoot":"","sources":["metadataIncomingUpdateIsolation.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,kCAAkC,EAClC,iCAAiC,GAClC,MAAM,iEAAiE,CAAC;AACzE,OAAO,EAAE,yBAAyB,EAAE,MAAM,6CAA6C,CAAC;AACxF,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAClG,OAAO,EAEL,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,4BAA4B,EAAE,MAAM,mDAAmD,CAAC;AAIjG,MAAM,CAAC,KAAK,UAAU,gCAAgC,CAAC,KAStD;IACC,MAAM,wBAAwB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QACpE,MAAM,iCAAiC,CAAC,aAAa,CAAC,CAAC,kBAAkB,CACvE,KAAK,IAAI,EAAE;YACT,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;gBAAE,OAAO;YAC1C,MAAM,yBAAyB,CAC7B,aAAa,EACb,KAAK,CAAC,aAAa,EACnB,KAAK,CAAC,OAAO,CACd,CAAC;QACJ,CAAC,EACD,GAAG,EAAE,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK,CACpC,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,qCAAqC,CACnD,eAA8C,EAC9C,MAA0D;IAE1D,kCAAkC,CAAC,eAAe,EAAE,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAC/E,CAAC;AAED,MAAM,UAAU,+BAA+B,CAAC,KAM/C;IACC,OAAO;QACL,gCAAgC,EAAE,KAAK,EACrC,OAAyC,EACzC,EAAE;YACF,MAAM,gCAAgC,CAAC;gBACrC,GAAG,KAAK;gBACR,OAAO,EAAE;oBACP,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;oBACrC,OAAO,EAAE,OAAO,CAAC,OAAO;oBACxB,MAAM,EAAE,IAAI;iBACb;aACF,CAAC,CAAC;YACH,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;gBAAE,OAAO;YAC1C,4BAA4B,CAC1B,KAAK,CAAC,eAAe,EACrB,KAAK,CAAC,QAAQ,EACd,OAAO,CACR,CAAC;QACJ,CAAC;QACD,uBAAuB,EAAE,CACvB,MAAuE,EACvE,EAAE,CACF,iCAAiC,CAAC;YAChC,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;YACzC,eAAe,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO;SACzC,CAAC;KACL,CAAC;AACJ,CAAC","sourcesContent":["import type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport {\n type DocumentSyncUpdateIsolationError,\n importDecryptedDocumentSyncUpdates,\n validateDocumentSyncUpdateImports,\n} from \"../../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nimport { recordDocumentSyncFailure } from \"../../../data/persistence/documents/records\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n runSerializedSqlMutation,\n} from \"../../../data/sqlite/sqlSchema\";\nimport { reportDocumentSyncQuarantine } from \"../../documents/sync/reportDocumentSyncQuarantine\";\nimport type { WorkflowRuntimeUtilInput } from \"../../shared/runtimeInput\";\nimport type { ContainerMetadataState } from \"./metadataTypes\";\n\nexport async function recordCurrentMetadataSyncFailure(input: {\n execSql: ExecSql;\n failure: {\n readonly attemptedAt: string;\n readonly message: string;\n readonly status: number | null;\n };\n isCurrent?: (() => boolean) | undefined;\n metadataScope: { appKind: string; localId: string };\n}): Promise<void> {\n await runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n await getClientSQLitePersistenceRuntime(lockedExecSql).guardedTransaction(\n async () => {\n if (input.isCurrent?.() === false) return;\n await recordDocumentSyncFailure(\n lockedExecSql,\n input.metadataScope,\n input.failure,\n );\n },\n () => input.isCurrent?.() !== false,\n );\n });\n}\n\nexport function applyIncomingContainerMetadataUpdates(\n currentDocument: ContainerMetadataState[\"doc\"],\n result: Pick<SyncRemoteDocumentResult, \"decryptedUpdates\">,\n): void {\n importDecryptedDocumentSyncUpdates(currentDocument, result.decryptedUpdates);\n}\n\nexport function metadataIncomingUpdateIsolation(input: {\n currentDocument: ContainerMetadataState[\"doc\"];\n execSql: ExecSql;\n isCurrent?: (() => boolean) | undefined;\n logError?: WorkflowRuntimeUtilInput[\"logError\"] | undefined;\n metadataScope: { appKind: string; localId: string };\n}) {\n return {\n onIncomingUpdateIsolationFailure: async (\n failure: DocumentSyncUpdateIsolationError,\n ) => {\n await recordCurrentMetadataSyncFailure({\n ...input,\n failure: {\n attemptedAt: new Date().toISOString(),\n message: failure.message,\n status: null,\n },\n });\n if (input.isCurrent?.() === false) return;\n reportDocumentSyncQuarantine(\n input.currentDocument,\n input.logError,\n failure,\n );\n },\n validateIncomingUpdates: (\n result: Pick<SyncRemoteDocumentResult, \"decryptedUpdates\" | \"response\">,\n ) =>\n validateDocumentSyncUpdateImports({\n currentDocument: input.currentDocument,\n decryptedUpdates: result.decryptedUpdates,\n responseUpdates: result.response.updates,\n }),\n };\n}\n"]}
1
+ {"version":3,"file":"metadataIncomingUpdateIsolation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OAAO;oBACxB,MAAM,EAAE,IAAI;iBACb;aACF,CAAC,CAAC;YACH,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;gBAAE,OAAO;YAC1C,4BAA4B,CAC1B,KAAK,CAAC,eAAe,EACrB,KAAK,CAAC,QAAQ,EACd,OAAO,CACR,CAAC;QACJ,CAAC;QACD,uBAAuB,EAAE,CACvB,MAAuE,EACvE,EAAE,CACF,iCAAiC,CAAC;YAChC,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;YACzC,eAAe,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO;SACzC,CAAC;KACL,CAAC;AACJ,CAAC","sourcesContent":["import type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport {\n type DocumentSyncUpdateIsolationError,\n importDecryptedDocumentSyncUpdates,\n validateDocumentSyncUpdateImports,\n} from \"../../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nimport { DocumentRecordRepository } from \"../../../data/persistence/documents/records\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n runSerializedSqlMutation,\n} from \"../../../data/sqlite/sqlSchema\";\nimport { reportDocumentSyncQuarantine } from \"../../documents/sync/reportDocumentSyncQuarantine\";\nimport type { WorkflowRuntimeUtilInput } from \"../../shared/runtimeInput\";\nimport type { ContainerMetadataState } from \"./metadataTypes\";\n\nexport async function recordCurrentMetadataSyncFailure(input: {\n execSql: ExecSql;\n failure: {\n readonly attemptedAt: string;\n readonly message: string;\n readonly status: number | null;\n };\n isCurrent?: (() => boolean) | undefined;\n metadataScope: { appKind: string; localId: string };\n}): Promise<void> {\n await runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n await getClientSQLitePersistenceRuntime(lockedExecSql).guardedTransaction(\n async () => {\n if (input.isCurrent?.() === false) return;\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(input.metadataScope, input.failure);\n },\n () => input.isCurrent?.() !== false,\n );\n });\n}\n\nexport function applyIncomingContainerMetadataUpdates(\n currentDocument: ContainerMetadataState[\"doc\"],\n result: Pick<SyncRemoteDocumentResult, \"decryptedUpdates\">,\n): void {\n importDecryptedDocumentSyncUpdates(currentDocument, result.decryptedUpdates);\n}\n\nexport function metadataIncomingUpdateIsolation(input: {\n currentDocument: ContainerMetadataState[\"doc\"];\n execSql: ExecSql;\n isCurrent?: (() => boolean) | undefined;\n logError?: WorkflowRuntimeUtilInput[\"logError\"] | undefined;\n metadataScope: { appKind: string; localId: string };\n}) {\n return {\n onIncomingUpdateIsolationFailure: async (\n failure: DocumentSyncUpdateIsolationError,\n ) => {\n await recordCurrentMetadataSyncFailure({\n ...input,\n failure: {\n attemptedAt: new Date().toISOString(),\n message: failure.message,\n status: null,\n },\n });\n if (input.isCurrent?.() === false) return;\n reportDocumentSyncQuarantine(\n input.currentDocument,\n input.logError,\n failure,\n );\n },\n validateIncomingUpdates: (\n result: Pick<SyncRemoteDocumentResult, \"decryptedUpdates\" | \"response\">,\n ) =>\n validateDocumentSyncUpdateImports({\n currentDocument: input.currentDocument,\n decryptedUpdates: result.decryptedUpdates,\n responseUpdates: result.response.updates,\n }),\n };\n}\n"]}
@@ -2,7 +2,7 @@ import { DOCUMENTS_APP_KIND } from "../../../data/documents/documentConstants.js
2
2
  import { CONTAINER_METADATA_APP_KIND } from "../../../data/persistence/container-contents/containerContentsPersistence.js";
3
3
  import { DocumentMoveIntentRepository } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
4
4
  import { sqlDocumentsPersistence } from "../../../data/persistence/documents/documentsPersistence.js";
5
- import { clearDocumentSyncFailure, resetDocumentPendingUpdateRekeyBudget, } from "../../../data/persistence/documents/records/index.js";
5
+ import { DocumentRecordRepository } from "../../../data/persistence/documents/records/index.js";
6
6
  import { documentPlacementIntentTables, LOCAL_INTENT_LANES, } from "../../../data/sqlite/schema/index.js";
7
7
  import { documentTables } from "../../../data/sqlite/schema/documentRecordSchema.js";
8
8
  import { ensureSqlTables } from "../../../data/sqlite/sqlSchema.js";
@@ -54,7 +54,8 @@ export async function resetPendingWriteRetryState(execSql, input) {
54
54
  return;
55
55
  }
56
56
  const scope = { appKind, localId: input.localId };
57
- await resetDocumentPendingUpdateRekeyBudget(execSql, scope);
57
+ const records = new DocumentRecordRepository(execSql);
58
+ await records.resetDocumentPendingUpdateRekeyBudget(scope);
58
59
  if (appKind === DOCUMENTS_APP_KIND) {
59
60
  // A deliberate retry is the rate-limited signal that conditions changed:
60
61
  // a parked permission-denied move (row 7) replays once, like row 11's
@@ -69,7 +70,7 @@ export async function resetPendingWriteRetryState(execSql, input) {
69
70
  // priming ticket that re-drives the store, so it must survive the retry
70
71
  // and clear on the next clean pass instead of vanishing with no request.
71
72
  if (await hasQueuedScopeWork(execSql, scope)) {
72
- await clearDocumentSyncFailure(execSql, scope);
73
+ await records.clearDocumentSyncFailure(scope);
73
74
  }
74
75
  }
75
76
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,2EAA2E,CAAC;AACxH,OAAO,EAAE,4BAA4B,EAAE,MAAM,4EAA4E,CAAC;AAC1H,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EACL,wBAAwB,EACxB,qCAAqC,GACtC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EACL,6BAA6B,EAC7B,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,kDAAkD,CAAC;AAElF,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,yBAAyB,CAAC;AAC9E,OAAO,EA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sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../data/documents/documentConstants\";\nimport { CONTAINER_METADATA_APP_KIND } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { DocumentMoveIntentRepository } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n clearDocumentSyncFailure,\n resetDocumentPendingUpdateRekeyBudget,\n} from \"../../../data/persistence/documents/records\";\nimport {\n documentPlacementIntentTables,\n LOCAL_INTENT_LANES,\n} from \"../../../data/sqlite/schema\";\nimport { documentTables } from \"../../../data/sqlite/schema/documentRecordSchema\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport { defaultContainerContentsPersistence } from \"../containerPersistence\";\nimport { groupPendingWriteCandidates } from \"./aggregation\";\nimport {\n hasDeferredTailScopeWork,\n listDeferredPendingWriteCandidates,\n} from \"./deferredTails\";\nimport type { PendingWriteQueueItem } from \"./pendingWritesTypes\";\nimport { listPersistedPendingWriteCandidates } from \"./sources\";\n\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"./pendingWritesTypes\";\n\n/**\n * Whether an item holds local work that still has to upload. A revalidation\n * item only reports a failed read and carries no local writes.\n */\nexport function carriesLocalWrites(item: PendingWriteQueueItem): boolean {\n return item.operations.some((operation) => operation.kind !== \"revalidation\");\n}\n\n/**\n * List identity-wide local state that still requires a remote write. The\n * returned diagnostic contains only navigation/display metadata and aggregate\n * counts; serialized updates, local storage keys, and upload crypto stay below\n * the workflow boundary.\n */\nexport async function listPendingWrites(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingWriteQueueItem>> {\n await defaultContainerContentsPersistence.ensureSchema(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await new DocumentMoveIntentRepository(execSql).ensureSchema();\n\n const [persisted, deferred] = await Promise.all([\n listPersistedPendingWriteCandidates(execSql),\n listDeferredPendingWriteCandidates(execSql),\n ]);\n return groupPendingWriteCandidates([...persisted, ...deferred]);\n}\n\n/**\n * Explicit manual retry for one write-queue item: reset the durable re-key\n * budget for the item's ACTUAL pending-update scope (container metadata and\n * unknown document namespaces re-key through the same recovery path as\n * ordinary documents) and clear the recorded terminal failure — the next\n * pass re-records both if they still hold. The cap protects against a\n * server driving a network-speed re-key loop; a deliberate user retry is\n * the rate-limited signal that conditions have changed (e.g. an outage that\n * burned the budget has healed). The caller re-arms the sync lanes.\n */\nexport async function resetPendingWriteRetryState(\n execSql: ExecSql,\n input: {\n localId: string;\n /** The item's `namespace` — the unrecognized documents.app_kind, if any. */\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n },\n): Promise<void> {\n const appKind =\n input.objectKind === \"container\"\n ? CONTAINER_METADATA_APP_KIND\n : (input.namespace ??\n (input.objectKind === \"document\" ? DOCUMENTS_APP_KIND : null));\n if (appKind === null) {\n // An unknown object kind with no namespace: there is no scope to reset,\n // and guessing one could clear an unrelated scope sharing the localId.\n return;\n }\n const scope = { appKind, localId: input.localId };\n await resetDocumentPendingUpdateRekeyBudget(execSql, scope);\n if (appKind === DOCUMENTS_APP_KIND) {\n // A deliberate retry is the rate-limited signal that conditions changed:\n // a parked permission-denied move (row 7) replays once, like row 11's\n // re-key budget reset.\n await new DocumentMoveIntentRepository(execSql).resetDeniedMoveIntents({\n localId: input.localId,\n });\n }\n // Clearing the failure row is part of the re-key budget reset (edge-case\n // row 11) and only makes sense alongside queued work. A failure-only item\n // (a refused revalidation, row 13) has no queued work: its row is the\n // priming ticket that re-drives the store, so it must survive the retry\n // and clear on the next clean pass instead of vanishing with no request.\n if (await hasQueuedScopeWork(execSql, scope)) {\n await clearDocumentSyncFailure(execSql, scope);\n }\n}\n\n/**\n * Whether ANY durable outbound work exists for the scope — CRDT updates,\n * staged attachment uploads, move intents, a never-created local document, or\n * a deferred write whose only durable content is the history tail ahead of\n * its covered frontier. Mirrors the queue's own document candidate sources,\n * so \"failure-only\" here agrees with the item the panel rendered.\n */\nasync function hasQueuedScopeWork(\n execSql: ExecSql,\n scope: { appKind: string; localId: string },\n): Promise<boolean> {\n await ensureSqlTables(execSql, [\n ...documentTables,\n ...documentPlacementIntentTables,\n ]);\n const rows = await execSql(\n `SELECT 1 AS present\n WHERE EXISTS (\n SELECT 1 FROM document_history_updates pending\n WHERE pending.app_kind = ? AND pending.local_id = ?\n AND pending.update_id IS NOT NULL\n )\n OR EXISTS (\n SELECT 1 FROM document_pending_attachments attachment\n WHERE attachment.local_id = ?\n )\n OR EXISTS (\n SELECT 1 FROM local_intents intent\n WHERE intent.lane = '${LOCAL_INTENT_LANES.documentPlacement}'\n AND intent.local_id = ?\n AND intent.intent_type IN ('document.move', 'document.link')\n )\n OR EXISTS (\n SELECT 1 FROM documents stored\n WHERE stored.app_kind = ? AND stored.local_id = ?\n AND stored.document_id IS NULL\n )\n LIMIT 1`,\n [\n scope.appKind,\n scope.localId,\n scope.localId,\n scope.localId,\n scope.appKind,\n scope.localId,\n ],\n );\n if (rows.length > 0) {\n return true;\n }\n // The queue's deferred-update source has no queued rows to probe: the\n // write lives in the durable history tail, detectable only by the\n // version-vector coverage check.\n return hasDeferredTailScopeWork(execSql, scope);\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,2EAA2E,CAAC;AACxH,OAAO,EAAE,4BAA4B,EAAE,MAAM,4EAA4E,CAAC;AAC1H,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EAAE,wBAAwB,EAAE,MAAM,6CAA6C,CAAC;AACvF,OAAO,EACL,6BAA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KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;KACd,CACF,CAAC;IACF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,sEAAsE;IACtE,kEAAkE;IAClE,iCAAiC;IACjC,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../data/documents/documentConstants\";\nimport { CONTAINER_METADATA_APP_KIND } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { DocumentMoveIntentRepository } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport { DocumentRecordRepository } from \"../../../data/persistence/documents/records\";\nimport {\n documentPlacementIntentTables,\n LOCAL_INTENT_LANES,\n} from \"../../../data/sqlite/schema\";\nimport { documentTables } from \"../../../data/sqlite/schema/documentRecordSchema\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport { defaultContainerContentsPersistence } from \"../containerPersistence\";\nimport { groupPendingWriteCandidates } from \"./aggregation\";\nimport {\n hasDeferredTailScopeWork,\n listDeferredPendingWriteCandidates,\n} from \"./deferredTails\";\nimport type { PendingWriteQueueItem } from \"./pendingWritesTypes\";\nimport { listPersistedPendingWriteCandidates } from \"./sources\";\n\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"./pendingWritesTypes\";\n\n/**\n * Whether an item holds local work that still has to upload. A revalidation\n * item only reports a failed read and carries no local writes.\n */\nexport function carriesLocalWrites(item: PendingWriteQueueItem): boolean {\n return item.operations.some((operation) => operation.kind !== \"revalidation\");\n}\n\n/**\n * List identity-wide local state that still requires a remote write. The\n * returned diagnostic contains only navigation/display metadata and aggregate\n * counts; serialized updates, local storage keys, and upload crypto stay below\n * the workflow boundary.\n */\nexport async function listPendingWrites(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingWriteQueueItem>> {\n await defaultContainerContentsPersistence.ensureSchema(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await new DocumentMoveIntentRepository(execSql).ensureSchema();\n\n const [persisted, deferred] = await Promise.all([\n listPersistedPendingWriteCandidates(execSql),\n listDeferredPendingWriteCandidates(execSql),\n ]);\n return groupPendingWriteCandidates([...persisted, ...deferred]);\n}\n\n/**\n * Explicit manual retry for one write-queue item: reset the durable re-key\n * budget for the item's ACTUAL pending-update scope (container metadata and\n * unknown document namespaces re-key through the same recovery path as\n * ordinary documents) and clear the recorded terminal failure — the next\n * pass re-records both if they still hold. The cap protects against a\n * server driving a network-speed re-key loop; a deliberate user retry is\n * the rate-limited signal that conditions have changed (e.g. an outage that\n * burned the budget has healed). The caller re-arms the sync lanes.\n */\nexport async function resetPendingWriteRetryState(\n execSql: ExecSql,\n input: {\n localId: string;\n /** The item's `namespace` — the unrecognized documents.app_kind, if any. */\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n },\n): Promise<void> {\n const appKind =\n input.objectKind === \"container\"\n ? CONTAINER_METADATA_APP_KIND\n : (input.namespace ??\n (input.objectKind === \"document\" ? DOCUMENTS_APP_KIND : null));\n if (appKind === null) {\n // An unknown object kind with no namespace: there is no scope to reset,\n // and guessing one could clear an unrelated scope sharing the localId.\n return;\n }\n const scope = { appKind, localId: input.localId };\n const records = new DocumentRecordRepository(execSql);\n await records.resetDocumentPendingUpdateRekeyBudget(scope);\n if (appKind === DOCUMENTS_APP_KIND) {\n // A deliberate retry is the rate-limited signal that conditions changed:\n // a parked permission-denied move (row 7) replays once, like row 11's\n // re-key budget reset.\n await new DocumentMoveIntentRepository(execSql).resetDeniedMoveIntents({\n localId: input.localId,\n });\n }\n // Clearing the failure row is part of the re-key budget reset (edge-case\n // row 11) and only makes sense alongside queued work. A failure-only item\n // (a refused revalidation, row 13) has no queued work: its row is the\n // priming ticket that re-drives the store, so it must survive the retry\n // and clear on the next clean pass instead of vanishing with no request.\n if (await hasQueuedScopeWork(execSql, scope)) {\n await records.clearDocumentSyncFailure(scope);\n }\n}\n\n/**\n * Whether ANY durable outbound work exists for the scope — CRDT updates,\n * staged attachment uploads, move intents, a never-created local document, or\n * a deferred write whose only durable content is the history tail ahead of\n * its covered frontier. Mirrors the queue's own document candidate sources,\n * so \"failure-only\" here agrees with the item the panel rendered.\n */\nasync function hasQueuedScopeWork(\n execSql: ExecSql,\n scope: { appKind: string; localId: string },\n): Promise<boolean> {\n await ensureSqlTables(execSql, [\n ...documentTables,\n ...documentPlacementIntentTables,\n ]);\n const rows = await execSql(\n `SELECT 1 AS present\n WHERE EXISTS (\n SELECT 1 FROM document_history_updates pending\n WHERE pending.app_kind = ? AND pending.local_id = ?\n AND pending.update_id IS NOT NULL\n )\n OR EXISTS (\n SELECT 1 FROM document_pending_attachments attachment\n WHERE attachment.local_id = ?\n )\n OR EXISTS (\n SELECT 1 FROM local_intents intent\n WHERE intent.lane = '${LOCAL_INTENT_LANES.documentPlacement}'\n AND intent.local_id = ?\n AND intent.intent_type IN ('document.move', 'document.link')\n )\n OR EXISTS (\n SELECT 1 FROM documents stored\n WHERE stored.app_kind = ? AND stored.local_id = ?\n AND stored.document_id IS NULL\n )\n LIMIT 1`,\n [\n scope.appKind,\n scope.localId,\n scope.localId,\n scope.localId,\n scope.appKind,\n scope.localId,\n ],\n );\n if (rows.length > 0) {\n return true;\n }\n // The queue's deferred-update source has no queued rows to probe: the\n // write lives in the durable history tail, detectable only by the\n // version-vector coverage check.\n return hasDeferredTailScopeWork(execSql, scope);\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { DocumentMoveIntentRepository } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
2
2
  import { requestDormantMetadataRestorationSweeps } from "../../../data/persistence/container-contents/dormantMetadataSweep.js";
3
- import { hasRecordedTerminalSyncFailures } from "../../../data/persistence/documents/records/index.js";
3
+ import { DocumentRecordRepository } from "../../../data/persistence/documents/records/index.js";
4
4
  import { requestAllDomainSyncLanes, requestDomainSyncLane, } from "../../../data/sync/syncCoordinator.js";
5
5
  import { CONTAINER_CONTENTS_SYNC_LANE_KEY } from "../syncLane.js";
6
6
  /** Recover parked work before optional presentation hydration can fail. */
@@ -15,7 +15,7 @@ export async function recoverOrganizationAccess(input) {
15
15
  // denied flag, and re-arming then would race the startup sync passes.
16
16
  // A failed pass (`undefined`) proves nothing about restored access,
17
17
  // so it must not re-arm either.
18
- if (((await hasRecordedTerminalSyncFailures(execSql)) ||
18
+ if (((await new DocumentRecordRepository(execSql).hasRecordedTerminalSyncFailures()) ||
19
19
  (await moveIntents.hasDeniedMoveIntents({ organizationId }))) &&
20
20
  stillCurrent()) {
21
21
  // Parked permission-denied moves (row 7) only replay once flipped
@@ -1 +1 @@
1
- {"version":3,"file":"accessRestoration.js","sourceRoot":"","sources":["accessRestoration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,4EAA4E,CAAC;AAC1H,OAAO,EAAE,uCAAuC,EAAE,MAAM,mEAAmE,CAAC;AAC5H,OAAO,EAAE,+BAA+B,EAAE,MAAM,6CAA6C,CAAC;AAG9F,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,gCAAgC,EAAE,MAAM,aAAa,CAAC;AAE/D,2EAA2E;AAC3E,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,KAM/C;IACC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAC7E,IAAI,CAAC,YAAY,EAAE;QAAE,OAAO;IAC5B,MAAM,WAAW,GAAG,IAAI,4BAA4B,CAAC,OAAO,CAAC,CAAC;IAC9D,iEAAiE;IACjE,mEAAmE;IACnE,iEAAiE;IACjE,sEAAsE;IACtE,oEAAoE;IACpE,gCAAgC;IAChC,IACE,CAAC,CAAC,MAAM,+BAA+B,CAAC,OAAO,CAAC,CAAC;QAC/C,CAAC,MAAM,WAAW,CAAC,oBAAoB,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC;QAC/D,YAAY,EAAE,EACd,CAAC;QACD,kEAAkE;QAClE,4DAA4D;QAC5D,MAAM,WAAW,CAAC,sBAAsB,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC;QAC7D,IAAI,YAAY,EAAE;YAAE,yBAAyB,CAAC,WAAW,CAAC,CAAC;IAC7D,CAAC;IACD,sEAAsE;IACtE,+DAA+D;IAC/D,6DAA6D;IAC7D,IAAI,YAAY,EAAE,EAAE,CAAC;QACnB,MAAM,0BAA0B,GAC9B,MAAM,uCAAuC,CAAC,OAAO,EAAE;YACrD,eAAe,EAAE,MAAM;SACxB,CAAC,CAAC;QACL,IAAI,0BAA0B,GAAG,CAAC,IAAI,YAAY,EAAE,EAAE,CAAC;YACrD,qBAAqB,CAAC,WAAW,EAAE,gCAAgC,CAAC,CAAC;QACvE,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { DocumentMoveIntentRepository } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { requestDormantMetadataRestorationSweeps } from \"../../../data/persistence/container-contents/dormantMetadataSweep\";\nimport { hasRecordedTerminalSyncFailures } from \"../../../data/persistence/documents/records\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requestAllDomainSyncLanes,\n requestDomainSyncLane,\n} from \"../../../data/sync/syncCoordinator\";\nimport { CONTAINER_CONTENTS_SYNC_LANE_KEY } from \"../syncLane\";\n\n/** Recover parked work before optional presentation hydration can fail. */\nexport async function recoverOrganizationAccess(input: {\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n readonly userId: string;\n}): Promise<void> {\n const { domainScope, execSql, organizationId, stillCurrent, userId } = input;\n if (!stillCurrent()) return;\n const moveIntents = new DocumentMoveIntentRepository(execSql);\n // The evidence gate: re-arm only when some queued write actually\n // recorded a terminal failure. A transient denial during bootstrap\n // (e.g. a read-model 403 before grants propagate) also flips the\n // denied flag, and re-arming then would race the startup sync passes.\n // A failed pass (`undefined`) proves nothing about restored access,\n // so it must not re-arm either.\n if (\n ((await hasRecordedTerminalSyncFailures(execSql)) ||\n (await moveIntents.hasDeniedMoveIntents({ organizationId }))) &&\n stillCurrent()\n ) {\n // Parked permission-denied moves (row 7) only replay once flipped\n // back to pending; restore them before re-arming the lanes.\n await moveIntents.resetDeniedMoveIntents({ organizationId });\n if (stillCurrent()) requestAllDomainSyncLanes(domainScope);\n }\n // Keep dormant cleanup independent from the write-lane evidence gate,\n // but run it afterward so a SQLite failure cannot suppress the\n // pre-existing denied-write and move-intent recovery signal.\n if (stillCurrent()) {\n const requestedDormantSweepCount =\n await requestDormantMetadataRestorationSweeps(execSql, {\n requesterUserId: userId,\n });\n if (requestedDormantSweepCount > 0 && stillCurrent()) {\n requestDomainSyncLane(domainScope, CONTAINER_CONTENTS_SYNC_LANE_KEY);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"accessRestoration.js","sourceRoot":"","sources":["accessRestoration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,4EAA4E,CAAC;AAC1H,OAAO,EAAE,uCAAuC,EAAE,MAAM,mEAAmE,CAAC;AAC5H,OAAO,EAAE,wBAAwB,EAAE,MAAM,6CAA6C,CAAC;AAGvF,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,gCAAgC,EAAE,MAAM,aAAa,CAAC;AAE/D,2EAA2E;AAC3E,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,KAM/C;IACC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAC7E,IAAI,CAAC,YAAY,EAAE;QAAE,OAAO;IAC5B,MAAM,WAAW,GAAG,IAAI,4BAA4B,CAAC,OAAO,CAAC,CAAC;IAC9D,iEAAiE;IACjE,mEAAmE;IACnE,iEAAiE;IACjE,sEAAsE;IACtE,oEAAoE;IACpE,gCAAgC;IAChC,IACE,CAAC,CAAC,MAAM,IAAI,wBAAwB,CAClC,OAAO,CACR,CAAC,+BAA+B,EAAE,CAAC;QAClC,CAAC,MAAM,WAAW,CAAC,oBAAoB,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC;QAC/D,YAAY,EAAE,EACd,CAAC;QACD,kEAAkE;QAClE,4DAA4D;QAC5D,MAAM,WAAW,CAAC,sBAAsB,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC;QAC7D,IAAI,YAAY,EAAE;YAAE,yBAAyB,CAAC,WAAW,CAAC,CAAC;IAC7D,CAAC;IACD,sEAAsE;IACtE,+DAA+D;IAC/D,6DAA6D;IAC7D,IAAI,YAAY,EAAE,EAAE,CAAC;QACnB,MAAM,0BAA0B,GAC9B,MAAM,uCAAuC,CAAC,OAAO,EAAE;YACrD,eAAe,EAAE,MAAM;SACxB,CAAC,CAAC;QACL,IAAI,0BAA0B,GAAG,CAAC,IAAI,YAAY,EAAE,EAAE,CAAC;YACrD,qBAAqB,CAAC,WAAW,EAAE,gCAAgC,CAAC,CAAC;QACvE,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { DocumentMoveIntentRepository } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { requestDormantMetadataRestorationSweeps } from \"../../../data/persistence/container-contents/dormantMetadataSweep\";\nimport { DocumentRecordRepository } from \"../../../data/persistence/documents/records\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requestAllDomainSyncLanes,\n requestDomainSyncLane,\n} from \"../../../data/sync/syncCoordinator\";\nimport { CONTAINER_CONTENTS_SYNC_LANE_KEY } from \"../syncLane\";\n\n/** Recover parked work before optional presentation hydration can fail. */\nexport async function recoverOrganizationAccess(input: {\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n readonly userId: string;\n}): Promise<void> {\n const { domainScope, execSql, organizationId, stillCurrent, userId } = input;\n if (!stillCurrent()) return;\n const moveIntents = new DocumentMoveIntentRepository(execSql);\n // The evidence gate: re-arm only when some queued write actually\n // recorded a terminal failure. A transient denial during bootstrap\n // (e.g. a read-model 403 before grants propagate) also flips the\n // denied flag, and re-arming then would race the startup sync passes.\n // A failed pass (`undefined`) proves nothing about restored access,\n // so it must not re-arm either.\n if (\n ((await new DocumentRecordRepository(\n execSql,\n ).hasRecordedTerminalSyncFailures()) ||\n (await moveIntents.hasDeniedMoveIntents({ organizationId }))) &&\n stillCurrent()\n ) {\n // Parked permission-denied moves (row 7) only replay once flipped\n // back to pending; restore them before re-arming the lanes.\n await moveIntents.resetDeniedMoveIntents({ organizationId });\n if (stillCurrent()) requestAllDomainSyncLanes(domainScope);\n }\n // Keep dormant cleanup independent from the write-lane evidence gate,\n // but run it afterward so a SQLite failure cannot suppress the\n // pre-existing denied-write and move-intent recovery signal.\n if (stillCurrent()) {\n const requestedDormantSweepCount =\n await requestDormantMetadataRestorationSweeps(execSql, {\n requesterUserId: userId,\n });\n if (requestedDormantSweepCount > 0 && stillCurrent()) {\n requestDomainSyncLane(domainScope, CONTAINER_CONTENTS_SYNC_LANE_KEY);\n }\n }\n}\n"]}
@@ -5,7 +5,7 @@ export { selectDocumentSyncOutgoingBatch } from "../../data/documents/shared/syn
5
5
  export { type DocumentSyncUpdateIsolationError, type IncomingDocumentSyncUpdateValidator, isDocumentSyncUpdateIsolationError, validateDocumentSyncUpdateImports, } from "../../data/documents/shared/sync/documentSyncUpdateIsolation.js";
6
6
  export { type DocumentSyncPullContinuation, documentSyncPullContinuationsEqual, readPullContinuation, } from "../../data/documents/shared/sync/syncPagination.js";
7
7
  export type { DocumentCreateAuthor, DocumentLinkSetFailureHandler, DocumentLinkSetMutationFailure, DocumentRotationProofMode, RelinkRemoteDocumentResult, } from "../../data/documents/shared/types.js";
8
- export { clearDocumentSyncFailure, invalidateDocumentSyncPullContinuation, recordDocumentSyncFailure, } from "../../data/persistence/documents/records/index.js";
8
+ export { DocumentRecordRepository } from "../../data/persistence/documents/records/index.js";
9
9
  export { DOCUMENT_HISTORY_COMPACTION_MAX_BYTES, DOCUMENT_HISTORY_COMPACTION_MAX_ROWS, } from "../../data/persistence/documents/records/documentHistoryPersistence.js";
10
10
  export type { ExecSql } from "../../data/sqlite/sqlSchema.js";
11
11
  export { settleOutgoingPassAndDecideReArm } from "../../data/sync/outgoingUpdateSettlement.js";
@@ -4,7 +4,7 @@ export { deriveStableDocumentId } from "../../data/documents/shared/stableDocume
4
4
  export { selectDocumentSyncOutgoingBatch } from "../../data/documents/shared/sync/documentSyncOutgoingBatch.js";
5
5
  export { isDocumentSyncUpdateIsolationError, validateDocumentSyncUpdateImports, } from "../../data/documents/shared/sync/documentSyncUpdateIsolation.js";
6
6
  export { documentSyncPullContinuationsEqual, readPullContinuation, } from "../../data/documents/shared/sync/syncPagination.js";
7
- export { clearDocumentSyncFailure, invalidateDocumentSyncPullContinuation, recordDocumentSyncFailure, } from "../../data/persistence/documents/records/index.js";
7
+ export { DocumentRecordRepository } from "../../data/persistence/documents/records/index.js";
8
8
  export { DOCUMENT_HISTORY_COMPACTION_MAX_BYTES, DOCUMENT_HISTORY_COMPACTION_MAX_ROWS, } from "../../data/persistence/documents/records/documentHistoryPersistence.js";
9
9
  export { settleOutgoingPassAndDecideReArm } from "../../data/sync/outgoingUpdateSettlement.js";
10
10
  export { didRegainSyncPrerequisites, isDatabaseUnavailableError, } from "../../data/sync/syncCoordinator.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,8BAA8B,GAC/B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,wCAAwC,EAAE,MAAM,uCAAuC,CAAC;AACjG,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAC7G,OAAO,EAGL,kCAAkC,EAClC,iCAAiC,GAClC,MAAM,8DAA8D,CAAC;AACtE,OAAO,EAEL,kCAAkC,EAClC,oBAAoB,GACrB,MAAM,iDAAiD,CAAC;AAQzD,OAAO,EACL,wBAAwB,EACxB,sCAAsC,EACtC,yBAAyB,GAC1B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,qCAAqC,EACrC,oCAAoC,GACrC,MAAM,qEAAqE,CAAC;AAE7E,OAAO,EAAE,gCAAgC,EAAE,MAAM,0CAA0C,CAAC;AAC5F,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,6BAA6B,EAC7B,+BAA+B,EAC/B,mCAAmC,EACnC,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,iCAAiC,EAAE,MAAM,gCAAgC,CAAC;AACnF,OAAO,EAAE,0BAA0B,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,EAAE,2BAA2B,EAAE,MAAM,UAAU,CAAC;AACvD,OAAO,EACL,mCAAmC,EACnC,oBAAoB,EACpB,0CAA0C,GAC3C,MAAM,UAAU,CAAC;AAClB,OAAO,EAML,mBAAmB,GACpB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAIL,4BAA4B,GAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,gCAAgC,EAChC,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,4CAA4C,EAAE,MAAM,WAAW,CAAC;AACzE,OAAO,EACL,4BAA4B,GAE7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,4BAA4B,EAC5B,0BAA0B,GAC3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAGL,kBAAkB,EAIlB,2BAA2B,EAE3B,+BAA+B,EAK/B,oBAAoB,EAGpB,wBAAwB,GACzB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,uCAAuC,EAGvC,qCAAqC,GACtC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAEL,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,EACL,8BAA8B,GAM/B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAC5C,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAGjE,OAAO,EAEL,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,mCAAmC,EACnC,iCAAiC,GAElC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uCAAuC,EAAE,MAAM,qCAAqC,CAAC;AAC9F,OAAO,EAAE,kCAAkC,EAAE,MAAM,4BAA4B,CAAC;AAEhF,OAAO,EAAE,qCAAqC,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export {\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n} from \"../../data/documents/shared/projection\";\nexport { persistedDocumentCreateStateFromResponse } from \"../../data/documents/shared/responses\";\nexport { deriveStableDocumentId } from \"../../data/documents/shared/stableDocumentId\";\nexport { selectDocumentSyncOutgoingBatch } from \"../../data/documents/shared/sync/documentSyncOutgoingBatch\";\nexport {\n type DocumentSyncUpdateIsolationError,\n type IncomingDocumentSyncUpdateValidator,\n isDocumentSyncUpdateIsolationError,\n validateDocumentSyncUpdateImports,\n} from \"../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nexport {\n type DocumentSyncPullContinuation,\n documentSyncPullContinuationsEqual,\n readPullContinuation,\n} from \"../../data/documents/shared/sync/syncPagination\";\nexport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationFailure,\n DocumentRotationProofMode,\n RelinkRemoteDocumentResult,\n} from \"../../data/documents/shared/types\";\nexport {\n clearDocumentSyncFailure,\n invalidateDocumentSyncPullContinuation,\n recordDocumentSyncFailure,\n} from \"../../data/persistence/documents/records\";\nexport {\n DOCUMENT_HISTORY_COMPACTION_MAX_BYTES,\n DOCUMENT_HISTORY_COMPACTION_MAX_ROWS,\n} from \"../../data/persistence/documents/records/documentHistoryPersistence\";\nexport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nexport { settleOutgoingPassAndDecideReArm } from \"../../data/sync/outgoingUpdateSettlement\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n deleteLocalDocumentAttachment,\n deletePendingDocumentAttachment,\n markLocalDocumentAttachmentDetached,\n saveLocalDocumentAttachments,\n savePendingDocumentAttachment,\n} from \"./attachments/attachmentPersistence\";\nexport { runSerializedDocumentBlobMutation } from \"./attachments/blobMutationLock\";\nexport { reclaimDocumentOrphanBlobs } from \"./attachments/orphanBlobReclaims\";\nexport { resolveDocumentCreateAuthor } from \"./author\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createRemoteDocument,\n documentWriterProjectionFromCreateResponse,\n} from \"./create\";\nexport {\n type DocumentHistory,\n type DocumentHistoryStop,\n type DocumentHistoryVersion,\n type DocumentHistoryVersionEntry,\n type DocumentHistoryView,\n openDocumentHistory,\n} from \"./history/documentHistory\";\nexport {\n type DocumentHistoryChange,\n type DocumentHistoryRowChange,\n type DocumentHistoryTextChange,\n isEmptyDocumentHistoryChange,\n} from \"./history/documentHistoryChange\";\nexport {\n importDocumentHistoryTailUpdates,\n loadPersistedDocumentContent,\n mergePersistedDocumentHistory,\n} from \"./historyContent\";\nexport { buildMaterializedDocumentLinkSetMutationPlan } from \"./linkSet\";\nexport {\n createLinkSetAttachmentReuse,\n type LinkSetAttachmentReuse,\n} from \"./linkSet/linkSetBlobRewraps\";\nexport {\n enqueuePendingDocumentUpdate,\n listPendingDocumentUpdates,\n} from \"./pendingUpdatePersistence\";\nexport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n DOCUMENTS_APP_KIND,\n type DocumentBirthResult,\n type DocumentRecord,\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n type LocalAttachmentRecord,\n loadPersistedDocumentStoreState,\n type PendingAttachmentRecord,\n type PendingAttachmentUploadIdentity,\n type PendingUpdateInsert,\n type PendingUpdateRecord,\n persistDocumentState,\n type QueuedPendingUpdateRecord,\n type RelinkPersistedDocumentInput,\n runSerializedSqlMutation,\n} from \"./persistence\";\nexport {\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionKeyRuntime,\n type DocumentProjectionUserKeyResolver,\n didDocumentProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport { buildDocumentPurgeRequest } from \"./purge\";\nexport {\n type DiscardedDocumentShellResult,\n deletePersistedDocument,\n discardPersistedDocumentToShell,\n} from \"./purge/persistedDocumentRemoval\";\nexport type { RemoteDocumentServiceApi } from \"./remote/remoteDocumentCollaborators\";\nexport { RemoteDocumentService } from \"./remote/remoteDocumentService\";\nexport {\n createDocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntimeGroups,\n type DocumentsWorkflowRuntimeInfra,\n type DocumentsWorkflowRuntimeInput,\n type DocumentsWorkflowRuntimeInputGroups,\n} from \"./runtime\";\nexport { syncRemoteDocument } from \"./sync\";\nexport { documentCreateSeedCandidate } from \"./sync/initialSync\";\nexport type { SyncRemoteDocumentInput } from \"./sync/readOnlySync\";\nexport type { DocumentSyncContainerRekeyBuilder } from \"./sync/syncAttemptState\";\nexport {\n type DocumentSyncLane,\n registerDocumentSyncLane,\n requestDocumentSyncLaneAndWait,\n} from \"./sync/syncLane\";\nexport {\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n} from \"./sync/syncTrace\";\nexport {\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type TerminalSubmitFailureHandler,\n} from \"./syncFailures/syncFailureClassification\";\nexport { shouldClearDocumentSyncFailureAfterPass } from \"./syncFailures/syncFailureClearance\";\nexport { DocumentRawHistoryUnavailableError } from \"./syncPlan/syncContentKeys\";\nexport type { RekeyPendingUpdate } from \"./syncRekeys/syncRecoveryRekey\";\nexport { createDocumentWriterPublicKeyResolver } from \"./writerKeys\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,8BAA8B,GAC/B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,wCAAwC,EAAE,MAAM,uCAAuC,CAAC;AACjG,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAC7G,OAAO,EAGL,kCAAkC,EAClC,iCAAiC,GAClC,MAAM,8DAA8D,CAAC;AACtE,OAAO,EAEL,kCAAkC,EAClC,oBAAoB,GACrB,MAAM,iDAAiD,CAAC;AAQzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACpF,OAAO,EACL,qCAAqC,EACrC,oCAAoC,GACrC,MAAM,qEAAqE,CAAC;AAE7E,OAAO,EAAE,gCA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EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAC5C,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAGjE,OAAO,EAEL,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,mCAAmC,EACnC,iCAAiC,GAElC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uCAAuC,EAAE,MAAM,qCAAqC,CAAC;AAC9F,OAAO,EAAE,kCAAkC,EAAE,MAAM,4BAA4B,CAAC;AAEhF,OAAO,EAAE,qCAAqC,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export {\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n} from \"../../data/documents/shared/projection\";\nexport { persistedDocumentCreateStateFromResponse } from \"../../data/documents/shared/responses\";\nexport { deriveStableDocumentId } from \"../../data/documents/shared/stableDocumentId\";\nexport { selectDocumentSyncOutgoingBatch } from \"../../data/documents/shared/sync/documentSyncOutgoingBatch\";\nexport {\n type DocumentSyncUpdateIsolationError,\n type IncomingDocumentSyncUpdateValidator,\n isDocumentSyncUpdateIsolationError,\n validateDocumentSyncUpdateImports,\n} from \"../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nexport {\n type DocumentSyncPullContinuation,\n documentSyncPullContinuationsEqual,\n readPullContinuation,\n} from \"../../data/documents/shared/sync/syncPagination\";\nexport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationFailure,\n DocumentRotationProofMode,\n RelinkRemoteDocumentResult,\n} from \"../../data/documents/shared/types\";\nexport { DocumentRecordRepository } from \"../../data/persistence/documents/records\";\nexport {\n DOCUMENT_HISTORY_COMPACTION_MAX_BYTES,\n DOCUMENT_HISTORY_COMPACTION_MAX_ROWS,\n} from \"../../data/persistence/documents/records/documentHistoryPersistence\";\nexport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nexport { settleOutgoingPassAndDecideReArm } from \"../../data/sync/outgoingUpdateSettlement\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n deleteLocalDocumentAttachment,\n deletePendingDocumentAttachment,\n markLocalDocumentAttachmentDetached,\n saveLocalDocumentAttachments,\n savePendingDocumentAttachment,\n} from \"./attachments/attachmentPersistence\";\nexport { runSerializedDocumentBlobMutation } from \"./attachments/blobMutationLock\";\nexport { reclaimDocumentOrphanBlobs } from \"./attachments/orphanBlobReclaims\";\nexport { resolveDocumentCreateAuthor } from \"./author\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createRemoteDocument,\n documentWriterProjectionFromCreateResponse,\n} from \"./create\";\nexport {\n type DocumentHistory,\n type DocumentHistoryStop,\n type DocumentHistoryVersion,\n type DocumentHistoryVersionEntry,\n type DocumentHistoryView,\n openDocumentHistory,\n} from \"./history/documentHistory\";\nexport {\n type DocumentHistoryChange,\n type DocumentHistoryRowChange,\n type DocumentHistoryTextChange,\n isEmptyDocumentHistoryChange,\n} from \"./history/documentHistoryChange\";\nexport {\n importDocumentHistoryTailUpdates,\n loadPersistedDocumentContent,\n mergePersistedDocumentHistory,\n} from \"./historyContent\";\nexport { buildMaterializedDocumentLinkSetMutationPlan } from \"./linkSet\";\nexport {\n createLinkSetAttachmentReuse,\n type LinkSetAttachmentReuse,\n} from \"./linkSet/linkSetBlobRewraps\";\nexport {\n enqueuePendingDocumentUpdate,\n listPendingDocumentUpdates,\n} from \"./pendingUpdatePersistence\";\nexport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n DOCUMENTS_APP_KIND,\n type DocumentBirthResult,\n type DocumentRecord,\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n type LocalAttachmentRecord,\n loadPersistedDocumentStoreState,\n type PendingAttachmentRecord,\n type PendingAttachmentUploadIdentity,\n type PendingUpdateInsert,\n type PendingUpdateRecord,\n persistDocumentState,\n type QueuedPendingUpdateRecord,\n type RelinkPersistedDocumentInput,\n runSerializedSqlMutation,\n} from \"./persistence\";\nexport {\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionKeyRuntime,\n type DocumentProjectionUserKeyResolver,\n didDocumentProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport { buildDocumentPurgeRequest } from \"./purge\";\nexport {\n type DiscardedDocumentShellResult,\n deletePersistedDocument,\n discardPersistedDocumentToShell,\n} from \"./purge/persistedDocumentRemoval\";\nexport type { RemoteDocumentServiceApi } from \"./remote/remoteDocumentCollaborators\";\nexport { RemoteDocumentService } from \"./remote/remoteDocumentService\";\nexport {\n createDocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntimeGroups,\n type DocumentsWorkflowRuntimeInfra,\n type DocumentsWorkflowRuntimeInput,\n type DocumentsWorkflowRuntimeInputGroups,\n} from \"./runtime\";\nexport { syncRemoteDocument } from \"./sync\";\nexport { documentCreateSeedCandidate } from \"./sync/initialSync\";\nexport type { SyncRemoteDocumentInput } from \"./sync/readOnlySync\";\nexport type { DocumentSyncContainerRekeyBuilder } from \"./sync/syncAttemptState\";\nexport {\n type DocumentSyncLane,\n registerDocumentSyncLane,\n requestDocumentSyncLaneAndWait,\n} from \"./sync/syncLane\";\nexport {\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n} from \"./sync/syncTrace\";\nexport {\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type TerminalSubmitFailureHandler,\n} from \"./syncFailures/syncFailureClassification\";\nexport { shouldClearDocumentSyncFailureAfterPass } from \"./syncFailures/syncFailureClearance\";\nexport { DocumentRawHistoryUnavailableError } from \"./syncPlan/syncContentKeys\";\nexport type { RekeyPendingUpdate } from \"./syncRekeys/syncRecoveryRekey\";\nexport { createDocumentWriterPublicKeyResolver } from \"./writerKeys\";\n"]}
@@ -1,6 +1,6 @@
1
1
  import { base64ToBytes } from "../../../internal/encoding/index.js";
2
2
  import { minimumVersionVectors } from "../../../internal/loro/index.js";
3
- import { MAX_PENDING_UPDATE_REKEYS, rekeyDocumentPendingUpdate, } from "../../../data/persistence/documents/records/index.js";
3
+ import { DocumentRecordRepository, MAX_PENDING_UPDATE_REKEYS, } from "../../../data/persistence/documents/records/index.js";
4
4
  import { getClientSQLitePersistenceRuntime } from "../../../data/sqlite/sqlitePersistenceRuntime.js";
5
5
  import { runSerializedSqlMutation, } from "../../../data/sqlite/sqlSchema.js";
6
6
  function bytesEqual(left, right) {
@@ -70,7 +70,8 @@ export function recoveryLocalVersionVector(localVersionVector, recoveryPendingUp
70
70
  * restarts (each session's in-memory lane cap resets, this bound does not).
71
71
  */
72
72
  export async function rekeyUnsettledRecoveryPendingUpdates(input) {
73
- const rekeyPendingUpdate = input.rekeyPendingUpdate ?? rekeyDocumentPendingUpdate;
73
+ const rekeyPendingUpdate = input.rekeyPendingUpdate ??
74
+ ((lockedExecSql, id) => new DocumentRecordRepository(lockedExecSql).rekeyDocumentPendingUpdate(id));
74
75
  const settled = new Set(input.settledPendingUpdateIds);
75
76
  const rekeyedPendingUpdateIds = [];
76
77
  const exhaustedPendingUpdateIds = [];
@@ -1 +1 @@
1
- {"version":3,"file":"syncRecoveryRekey.js","sourceRoot":"","sources":["syncRecoveryRekey.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAGxD,OAAO,EACL,yBAAyB,EAEzB,0BAA0B,GAC3B,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAClG,OAAO,EAEL,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AAcxC,SAAS,UAAU,CAAC,IAAgB,EAAE,KAAiB;IACrD,OAAO,CACL,IAAI,CAAC,UAAU,KAAK,KAAK,C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,KAAK;QACT,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC;QAChB,MAAM,EAAE,IAAI;KACb,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport { minimumVersionVectors } from \"@tearleads/loro\";\nimport type { DocumentSyncResponse } from \"@tearleads/validators/response\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport {\n MAX_PENDING_UPDATE_REKEYS,\n type PendingUpdateRecord,\n rekeyDocumentPendingUpdate,\n} from \"../../../data/persistence/documents/records\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n runSerializedSqlMutation,\n} from \"../../../data/sqlite/sqlSchema\";\n\nexport type RekeyPendingUpdate = (\n execSql: ExecSql,\n id: string,\n) => Promise<string | null>;\n\ninterface DecryptedSyncUpdate {\n id: string;\n partialEndVersionVector: string;\n partialStartVersionVector: string;\n updateData: Uint8Array;\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n return (\n left.byteLength === right.byteLength &&\n left.every((value, index) => value === right[index])\n );\n}\n\nfunction pendingUpdateMatchesDecryptedUpdate(\n pendingUpdate: PendingUpdateRecord,\n decryptedUpdate: Omit<DecryptedSyncUpdate, \"id\">,\n): boolean {\n if (\n pendingUpdate.partialStartVersionVector !==\n decryptedUpdate.partialStartVersionVector ||\n pendingUpdate.partialEndVersionVector !==\n decryptedUpdate.partialEndVersionVector\n ) {\n return false;\n }\n\n return bytesEqual(\n base64ToBytes(pendingUpdate.updateData),\n decryptedUpdate.updateData,\n );\n}\n\nexport function settledPendingUpdateIdsFromSync(input: {\n decryptedUpdates: readonly DecryptedSyncUpdate[];\n recoveryPendingUpdatesById: ReadonlyMap<string, PendingUpdateRecord>;\n response: DocumentSyncResponse;\n}): string[] {\n const settled = new Set(input.response.acceptedOutgoingUpdateIds);\n\n for (const update of input.decryptedUpdates) {\n const pendingUpdate = input.recoveryPendingUpdatesById.get(update.id);\n if (\n pendingUpdate &&\n pendingUpdateMatchesDecryptedUpdate(pendingUpdate, update)\n ) {\n settled.add(update.id);\n }\n }\n\n return [...settled];\n}\n\n/**\n * The version a read-only recovery pass advertises after an update-id\n * conflict: the live version, lowered to the start of each conflicted row.\n * The server returns only updates with a span past the advertised frontier,\n * and every conflicted row is in the live version, so advertising the live\n * version would hide the server's copy of each row it already holds. Recovery\n * could then never settle a row by content and would re-key it, and the\n * server would store its operations twice. A null version (raw history, or a\n * document with nothing local) already covers nothing.\n */\nexport function recoveryLocalVersionVector(\n localVersionVector: string | null,\n recoveryPendingUpdatesById: ReadonlyMap<string, PendingUpdateRecord>,\n): string | null {\n if (localVersionVector === null || recoveryPendingUpdatesById.size === 0) {\n return localVersionVector;\n }\n return minimumVersionVectors([\n localVersionVector,\n ...[...recoveryPendingUpdatesById.values()].map(\n (update) => update.partialStartVersionVector,\n ),\n ]);\n}\n\n/**\n * A read-only recovery sync settles a conflicted pending update only when the\n * response carries the server's copy with the same content. It asks for those\n * copies (see recoveryLocalVersionVector), but a copy can still be missing:\n * the server holds different content under the id, or the copy is on a later\n * pull page. Left alone, the conflicted id is resubmitted (and 409s the whole\n * outgoing batch) forever: every rebuild encrypts with a fresh IV, so a\n * byte-identical retry can never be reproduced. Re-key what recovery could\n * not settle so the next sync pass submits the same ops under a\n * conflict-free id; a server-side copy stays harmless because CRDT update\n * import is idempotent.\n *\n * Re-keying goes through the caller's persistence implementation when given\n * (defaulting to the built-in pending-update table) and reports only ids\n * whose row actually changed, so a record living in some other queue never\n * counts as progress. Returns the fresh ids so callers can treat re-keying\n * as settlement-like progress and schedule the pass that submits them.\n *\n * A row whose persisted rekeyCount has reached the bound is not re-keyed\n * again: it is reported as exhausted so the caller can surface a terminal\n * failure instead of feeding an unbounded conflict loop that survives\n * restarts (each session's in-memory lane cap resets, this bound does not).\n */\nexport async function rekeyUnsettledRecoveryPendingUpdates(input: {\n execSql: ExecSql;\n recoveryPendingUpdatesById: ReadonlyMap<string, PendingUpdateRecord>;\n rekeyPendingUpdate?: RekeyPendingUpdate | undefined;\n settledPendingUpdateIds: readonly string[];\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<{\n exhaustedPendingUpdateIds: string[];\n rekeyedPendingUpdateIds: string[];\n}> {\n const rekeyPendingUpdate =\n input.rekeyPendingUpdate ?? rekeyDocumentPendingUpdate;\n const settled = new Set(input.settledPendingUpdateIds);\n const rekeyedPendingUpdateIds: string[] = [];\n const exhaustedPendingUpdateIds: string[] = [];\n for (const [pendingUpdateId, record] of input.recoveryPendingUpdatesById) {\n if (input.stillCurrent?.() === false) break;\n if (settled.has(pendingUpdateId)) {\n continue;\n }\n // Known multi-tab limitation: the count is the row as loaded at pass\n // start, so a sibling tab that settle-deleted the row can make this\n // record a failure for work that no longer exists. The stale failure is\n // transient — the document's next clean pass clears it.\n if ((record.rekeyCount ?? 0) >= MAX_PENDING_UPDATE_REKEYS) {\n exhaustedPendingUpdateIds.push(pendingUpdateId);\n continue;\n }\n const outcome = await runSerializedSqlMutation(\n input.execSql,\n (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).guardedTransaction(\n async () =>\n input.stillCurrent?.() === false\n ? null\n : rekeyPendingUpdate(lockedExecSql, pendingUpdateId),\n () => input.stillCurrent?.() !== false,\n ),\n );\n if (!outcome.committed) break;\n const nextId = outcome.result;\n if (nextId !== null) {\n rekeyedPendingUpdateIds.push(nextId);\n }\n }\n if (input.stillCurrent?.() === false) {\n return { exhaustedPendingUpdateIds: [], rekeyedPendingUpdateIds: [] };\n }\n return { exhaustedPendingUpdateIds, rekeyedPendingUpdateIds };\n}\n\n/**\n * Re-key what recovery could not settle and surface exhausted rows through\n * the caller's terminal-failure handler. The exhausted count is also\n * returned so the sync result can carry it: a pass that recorded this\n * failure must not read as clean to callers that clear recorded failures\n * on success.\n */\nexport async function rekeyAndReportUnsettledRecoveryPendingUpdates(\n input: Parameters<typeof rekeyUnsettledRecoveryPendingUpdates>[0] & {\n onTerminalSubmitFailure?:\n | ((failure: DocumentSyncSubmitFailure) => Promise<void> | void)\n | undefined;\n },\n): Promise<{\n exhaustedPendingUpdateCount: number;\n rekeyedPendingUpdateIds: string[];\n}> {\n const { exhaustedPendingUpdateIds, rekeyedPendingUpdateIds } =\n await rekeyUnsettledRecoveryPendingUpdates(input);\n if (input.stillCurrent?.() === false) {\n return { exhaustedPendingUpdateCount: 0, rekeyedPendingUpdateIds: [] };\n }\n if (exhaustedPendingUpdateIds.length > 0) {\n await input.onTerminalSubmitFailure?.(\n rekeyLimitSubmitFailure(exhaustedPendingUpdateIds.length),\n );\n }\n return {\n exhaustedPendingUpdateCount: exhaustedPendingUpdateIds.length,\n rekeyedPendingUpdateIds,\n };\n}\n\n/**\n * Terminal failure recorded when conflict recovery gives up on pending\n * updates whose persisted re-key bound is exhausted. Shaped like a submit\n * failure so the existing write-queue surface (recordDocumentSyncFailure via\n * onTerminalSubmitFailure) explains the stuck write without new plumbing.\n */\nexport function rekeyLimitSubmitFailure(\n exhaustedCount: number,\n): DocumentSyncSubmitFailure {\n return {\n message: `Update conflict recovery gave up after ${MAX_PENDING_UPDATE_REKEYS} re-key attempts (${exhaustedCount} update${exhaustedCount === 1 ? \"\" : \"s\"})`,\n ok: false,\n report: () => {},\n status: null,\n };\n}\n"]}
1
+ {"version":3,"file":"syncRecoveryRekey.js","sourceRoot":"","sources":["syncRecoveryRekey.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAGxD,OAAO,EACL,wBAAwB,EACxB,yBAAyB,GAE1B,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAClG,OAAO,EAEL,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AAcxC,SAAS,UAAU,CAAC,IAAgB,EAAE,K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AsB;IAEtB,OAAO;QACL,OAAO,EAAE,0CAA0C,yBAAyB,qBAAqB,cAAc,UAAU,cAAc,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG;QAC3J,EAAE,EAAE,KAAK;QACT,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC;QAChB,MAAM,EAAE,IAAI;KACb,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport { minimumVersionVectors } from \"@tearleads/loro\";\nimport type { DocumentSyncResponse } from \"@tearleads/validators/response\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport {\n DocumentRecordRepository,\n MAX_PENDING_UPDATE_REKEYS,\n type PendingUpdateRecord,\n} from \"../../../data/persistence/documents/records\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n runSerializedSqlMutation,\n} from \"../../../data/sqlite/sqlSchema\";\n\nexport type RekeyPendingUpdate = (\n execSql: ExecSql,\n id: string,\n) => Promise<string | null>;\n\ninterface DecryptedSyncUpdate {\n id: string;\n partialEndVersionVector: string;\n partialStartVersionVector: string;\n updateData: Uint8Array;\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n return (\n left.byteLength === right.byteLength &&\n left.every((value, index) => value === right[index])\n );\n}\n\nfunction pendingUpdateMatchesDecryptedUpdate(\n pendingUpdate: PendingUpdateRecord,\n decryptedUpdate: Omit<DecryptedSyncUpdate, \"id\">,\n): boolean {\n if (\n pendingUpdate.partialStartVersionVector !==\n decryptedUpdate.partialStartVersionVector ||\n pendingUpdate.partialEndVersionVector !==\n decryptedUpdate.partialEndVersionVector\n ) {\n return false;\n }\n\n return bytesEqual(\n base64ToBytes(pendingUpdate.updateData),\n decryptedUpdate.updateData,\n );\n}\n\nexport function settledPendingUpdateIdsFromSync(input: {\n decryptedUpdates: readonly DecryptedSyncUpdate[];\n recoveryPendingUpdatesById: ReadonlyMap<string, PendingUpdateRecord>;\n response: DocumentSyncResponse;\n}): string[] {\n const settled = new Set(input.response.acceptedOutgoingUpdateIds);\n\n for (const update of input.decryptedUpdates) {\n const pendingUpdate = input.recoveryPendingUpdatesById.get(update.id);\n if (\n pendingUpdate &&\n pendingUpdateMatchesDecryptedUpdate(pendingUpdate, update)\n ) {\n settled.add(update.id);\n }\n }\n\n return [...settled];\n}\n\n/**\n * The version a read-only recovery pass advertises after an update-id\n * conflict: the live version, lowered to the start of each conflicted row.\n * The server returns only updates with a span past the advertised frontier,\n * and every conflicted row is in the live version, so advertising the live\n * version would hide the server's copy of each row it already holds. Recovery\n * could then never settle a row by content and would re-key it, and the\n * server would store its operations twice. A null version (raw history, or a\n * document with nothing local) already covers nothing.\n */\nexport function recoveryLocalVersionVector(\n localVersionVector: string | null,\n recoveryPendingUpdatesById: ReadonlyMap<string, PendingUpdateRecord>,\n): string | null {\n if (localVersionVector === null || recoveryPendingUpdatesById.size === 0) {\n return localVersionVector;\n }\n return minimumVersionVectors([\n localVersionVector,\n ...[...recoveryPendingUpdatesById.values()].map(\n (update) => update.partialStartVersionVector,\n ),\n ]);\n}\n\n/**\n * A read-only recovery sync settles a conflicted pending update only when the\n * response carries the server's copy with the same content. It asks for those\n * copies (see recoveryLocalVersionVector), but a copy can still be missing:\n * the server holds different content under the id, or the copy is on a later\n * pull page. Left alone, the conflicted id is resubmitted (and 409s the whole\n * outgoing batch) forever: every rebuild encrypts with a fresh IV, so a\n * byte-identical retry can never be reproduced. Re-key what recovery could\n * not settle so the next sync pass submits the same ops under a\n * conflict-free id; a server-side copy stays harmless because CRDT update\n * import is idempotent.\n *\n * Re-keying goes through the caller's persistence implementation when given\n * (defaulting to the built-in pending-update table) and reports only ids\n * whose row actually changed, so a record living in some other queue never\n * counts as progress. Returns the fresh ids so callers can treat re-keying\n * as settlement-like progress and schedule the pass that submits them.\n *\n * A row whose persisted rekeyCount has reached the bound is not re-keyed\n * again: it is reported as exhausted so the caller can surface a terminal\n * failure instead of feeding an unbounded conflict loop that survives\n * restarts (each session's in-memory lane cap resets, this bound does not).\n */\nexport async function rekeyUnsettledRecoveryPendingUpdates(input: {\n execSql: ExecSql;\n recoveryPendingUpdatesById: ReadonlyMap<string, PendingUpdateRecord>;\n rekeyPendingUpdate?: RekeyPendingUpdate | undefined;\n settledPendingUpdateIds: readonly string[];\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<{\n exhaustedPendingUpdateIds: string[];\n rekeyedPendingUpdateIds: string[];\n}> {\n const rekeyPendingUpdate: RekeyPendingUpdate =\n input.rekeyPendingUpdate ??\n ((lockedExecSql, id) =>\n new DocumentRecordRepository(lockedExecSql).rekeyDocumentPendingUpdate(\n id,\n ));\n const settled = new Set(input.settledPendingUpdateIds);\n const rekeyedPendingUpdateIds: string[] = [];\n const exhaustedPendingUpdateIds: string[] = [];\n for (const [pendingUpdateId, record] of input.recoveryPendingUpdatesById) {\n if (input.stillCurrent?.() === false) break;\n if (settled.has(pendingUpdateId)) {\n continue;\n }\n // Known multi-tab limitation: the count is the row as loaded at pass\n // start, so a sibling tab that settle-deleted the row can make this\n // record a failure for work that no longer exists. The stale failure is\n // transient — the document's next clean pass clears it.\n if ((record.rekeyCount ?? 0) >= MAX_PENDING_UPDATE_REKEYS) {\n exhaustedPendingUpdateIds.push(pendingUpdateId);\n continue;\n }\n const outcome = await runSerializedSqlMutation(\n input.execSql,\n (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).guardedTransaction(\n async () =>\n input.stillCurrent?.() === false\n ? null\n : rekeyPendingUpdate(lockedExecSql, pendingUpdateId),\n () => input.stillCurrent?.() !== false,\n ),\n );\n if (!outcome.committed) break;\n const nextId = outcome.result;\n if (nextId !== null) {\n rekeyedPendingUpdateIds.push(nextId);\n }\n }\n if (input.stillCurrent?.() === false) {\n return { exhaustedPendingUpdateIds: [], rekeyedPendingUpdateIds: [] };\n }\n return { exhaustedPendingUpdateIds, rekeyedPendingUpdateIds };\n}\n\n/**\n * Re-key what recovery could not settle and surface exhausted rows through\n * the caller's terminal-failure handler. The exhausted count is also\n * returned so the sync result can carry it: a pass that recorded this\n * failure must not read as clean to callers that clear recorded failures\n * on success.\n */\nexport async function rekeyAndReportUnsettledRecoveryPendingUpdates(\n input: Parameters<typeof rekeyUnsettledRecoveryPendingUpdates>[0] & {\n onTerminalSubmitFailure?:\n | ((failure: DocumentSyncSubmitFailure) => Promise<void> | void)\n | undefined;\n },\n): Promise<{\n exhaustedPendingUpdateCount: number;\n rekeyedPendingUpdateIds: string[];\n}> {\n const { exhaustedPendingUpdateIds, rekeyedPendingUpdateIds } =\n await rekeyUnsettledRecoveryPendingUpdates(input);\n if (input.stillCurrent?.() === false) {\n return { exhaustedPendingUpdateCount: 0, rekeyedPendingUpdateIds: [] };\n }\n if (exhaustedPendingUpdateIds.length > 0) {\n await input.onTerminalSubmitFailure?.(\n rekeyLimitSubmitFailure(exhaustedPendingUpdateIds.length),\n );\n }\n return {\n exhaustedPendingUpdateCount: exhaustedPendingUpdateIds.length,\n rekeyedPendingUpdateIds,\n };\n}\n\n/**\n * Terminal failure recorded when conflict recovery gives up on pending\n * updates whose persisted re-key bound is exhausted. Shaped like a submit\n * failure so the existing write-queue surface (recordDocumentSyncFailure via\n * onTerminalSubmitFailure) explains the stuck write without new plumbing.\n */\nexport function rekeyLimitSubmitFailure(\n exhaustedCount: number,\n): DocumentSyncSubmitFailure {\n return {\n message: `Update conflict recovery gave up after ${MAX_PENDING_UPDATE_REKEYS} re-key attempts (${exhaustedCount} update${exhaustedCount === 1 ? \"\" : \"s\"})`,\n ok: false,\n report: () => {},\n status: null,\n };\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
3
3
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
- import { saveOrganizationGroupDisplayNames } from "../../../data/persistence/organizations/organizationGroupNamePersistence.js";
4
+ import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
5
5
  import { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
6
6
  import { GroupMetadataUnreadableError } from "../groupMetadata/groupMetadataAccess.js";
7
7
  import { assertGroupMetadataBinding } from "../groupMetadata/groupMetadataBinding.js";
@@ -39,7 +39,11 @@ export async function hydrateCurrentOrganizationGroupNames(input) {
39
39
  policies: [authority.directory.policy, authority.admins.policy],
40
40
  stillCurrent,
41
41
  });
42
- await saveOrganizationGroupDisplayNames({ ...input, names, stillCurrent });
42
+ await new OrganizationReadModelRepository(input.execSql).saveOrganizationGroupDisplayNames({
43
+ organizationId: input.organizationId,
44
+ names,
45
+ stillCurrent,
46
+ });
43
47
  assertProjectionVerificationCurrent(stillCurrent);
44
48
  const byId = new Map(names.map((entry) => [entry.groupId, entry.name]));
45
49
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"currentOrganizationGroupNames.js","sourceRoot":"","sources":["currentOrganizationGroupNames.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,iCAAiC,EAAE,MAAM,0EAA0E,CAAC;AAE7H,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AACpF,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAEL,0BAA0B,GAC3B,MAAM,2CAA2C,CAAC;AAcnD,gGAAgG;AAChG,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,KAAY;IAEZ,MAAM,SA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BAA0B,CAAC,OAAO,EAAE,KAAK,CAAC,iBAAiB,CAAC,CAAC;IAC5E,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,CAAC,KAAK,YAAY,4BAA4B,CAAC;YAAE,MAAM,KAAK,CAAC;QAClE,MAAM,KAAK,CAAC,sBAAsB,CAChC,IAAI,uBAAuB,CACzB,eAAe,EACf,8DAA8D,CAC/D,EACD;YACE,cAAc,EAAE,EAAE,SAAS,EAAE,OAAO,CAAC,YAAY,CAAC,SAAS,EAAE;YAC7D,QAAQ,EAAE,OAAO,CAAC,YAAY,CAAC,WAAW;YAC1C,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,wBAAwB;YACnC,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CACF,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { saveOrganizationGroupDisplayNames } from \"../../../data/persistence/organizations/organizationGroupNamePersistence\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { GroupMetadataUnreadableError } from \"../groupMetadata/groupMetadataAccess\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport {\n type GroupPolicyNameReader,\n readGroupPolicyPayloadName,\n} from \"../principalPolicy/principalPolicyRequest\";\nimport type { OrganizationDirectoryAndGroups } from \"../readModel\";\n\ntype Input = Parameters<typeof loadCurrentOrganizationAuthority>[0] & {\n readonly directory: OrganizationDirectoryAndGroups;\n readonly readEncryptedName?: GroupPolicyNameReader | undefined;\n readonly createCurrentNameReader?:\n | ((\n authority: Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>,\n ) => GroupPolicyNameReader)\n | undefined;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n};\n\n/** Names consume verified current artifacts; paged recovery retains their separate evidence. */\nexport async function hydrateCurrentOrganizationGroupNames(\n input: Input,\n): Promise<OrganizationDirectoryAndGroups> {\n const authority = await loadCurrentOrganizationAuthority(input);\n const nameInput = {\n ...input,\n readEncryptedName:\n input.createCurrentNameReader?.(authority) ?? input.readEncryptedName,\n };\n const names: { groupId: string; name: string; stateHash: string }[] = [];\n const unreadable = new Set<string>();\n const lifetimes: (() => boolean)[] = [authority.stillCurrent];\n for (const group of input.directory.groups) {\n const head = authority.descriptor.groupHeads.find(\n (head) => head.principalId === group.groupId,\n );\n if (!head || head.stateHash !== group.currentState?.stateHash)\n throw new Error(\"Group listing does not match the signed directory\");\n const verified = await authority.readGroup(group.groupId);\n lifetimes.push(verified.stillCurrent);\n assertGroupMetadataBinding(verified.current, authority.descriptor);\n const name = await readCurrentGroupName(nameInput, verified.current);\n if (name === null) unreadable.add(group.groupId);\n else\n names.push({ groupId: group.groupId, name, stateHash: head.stateHash });\n }\n const stillCurrent = () =>\n input.stillCurrent() && lifetimes.every((current) => current());\n assertProjectionVerificationCurrent(stillCurrent);\n // Match the authority admission performed by the full-bundle path. Group\n // name reads alone do not move group checkpoints.\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: [],\n organizationId: input.organizationId,\n policies: [authority.directory.policy, authority.admins.policy],\n stillCurrent,\n });\n await saveOrganizationGroupDisplayNames({ ...input, names, stillCurrent });\n assertProjectionVerificationCurrent(stillCurrent);\n const byId = new Map(names.map((entry) => [entry.groupId, entry.name]));\n return {\n ...input.directory,\n groups: input.directory.groups.map((group) => ({\n ...group,\n name: byId.get(group.groupId) ?? \"\",\n nameUnreadable: unreadable.has(group.groupId),\n })),\n };\n}\n\nasync function readCurrentGroupName(\n input: Input,\n current: Parameters<GroupPolicyNameReader>[0],\n) {\n try {\n return await readGroupPolicyPayloadName(current, input.readEncryptedName);\n } catch (error) {\n if (!(error instanceof GroupMetadataUnreadableError)) throw error;\n await input.reportSecurityIncident(\n new KeyingVerificationError(\n \"invalid_shape\",\n \"Signed group name does not open under the cited metadata key\",\n ),\n {\n evidenceHashes: { stateHash: current.currentState.stateHash },\n objectId: current.currentState.principalId,\n objectKind: \"principal\",\n operation: \"organization.groupName\",\n organizationId: input.organizationId,\n },\n );\n return null;\n }\n}\n"]}
1
+ {"version":3,"file":"currentOrganizationGroupNames.js","sourceRoot":"","sources":["currentOrganizationGroupNames.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAE1H,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AACpF,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAEL,0BAA0B,GAC3B,MAAM,2CAA2C,CAAC;AAcnD,gGAAgG;AAChG,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,KAAY;IAEZ,MAAM,SAAS,GAAG,MAAM,gCAAgC,CAAC,KAAK,CAAC,CAAC;IAChE,MAAM,SAAS,GAAG;QAChB,GAAG,KAAK;QACR,iBAAiB,EACf,KAAK,CAAC,uBAAuB,EAAE,CAAC,SAAS,CAAC,IAAI,KAAK,CAAC,iBAAiB;KACxE,CAAC;IACF,MAAM,KAAK,GAA2D,EAAE,CAAC;IACzE,MAAM,UAAU,GAAG,IAAI,GAAG,EAAU,CAAC;IACrC,MAAM,SAAS,GAAsB,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;IAC9D,KAAK,MAAM,KAAK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,OAAO,CAAC,YAAY,CAAC,SAAS,EAAE;YAC7D,QAAQ,EAAE,OAAO,CAAC,YAAY,CAAC,WAAW;YAC1C,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,wBAAwB;YACnC,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CACF,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { GroupMetadataUnreadableError } from \"../groupMetadata/groupMetadataAccess\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport {\n type GroupPolicyNameReader,\n readGroupPolicyPayloadName,\n} from \"../principalPolicy/principalPolicyRequest\";\nimport type { OrganizationDirectoryAndGroups } from \"../readModel\";\n\ntype Input = Parameters<typeof loadCurrentOrganizationAuthority>[0] & {\n readonly directory: OrganizationDirectoryAndGroups;\n readonly readEncryptedName?: GroupPolicyNameReader | undefined;\n readonly createCurrentNameReader?:\n | ((\n authority: Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>,\n ) => GroupPolicyNameReader)\n | undefined;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n};\n\n/** Names consume verified current artifacts; paged recovery retains their separate evidence. */\nexport async function hydrateCurrentOrganizationGroupNames(\n input: Input,\n): Promise<OrganizationDirectoryAndGroups> {\n const authority = await loadCurrentOrganizationAuthority(input);\n const nameInput = {\n ...input,\n readEncryptedName:\n input.createCurrentNameReader?.(authority) ?? input.readEncryptedName,\n };\n const names: { groupId: string; name: string; stateHash: string }[] = [];\n const unreadable = new Set<string>();\n const lifetimes: (() => boolean)[] = [authority.stillCurrent];\n for (const group of input.directory.groups) {\n const head = authority.descriptor.groupHeads.find(\n (head) => head.principalId === group.groupId,\n );\n if (!head || head.stateHash !== group.currentState?.stateHash)\n throw new Error(\"Group listing does not match the signed directory\");\n const verified = await authority.readGroup(group.groupId);\n lifetimes.push(verified.stillCurrent);\n assertGroupMetadataBinding(verified.current, authority.descriptor);\n const name = await readCurrentGroupName(nameInput, verified.current);\n if (name === null) unreadable.add(group.groupId);\n else\n names.push({ groupId: group.groupId, name, stateHash: head.stateHash });\n }\n const stillCurrent = () =>\n input.stillCurrent() && lifetimes.every((current) => current());\n assertProjectionVerificationCurrent(stillCurrent);\n // Match the authority admission performed by the full-bundle path. Group\n // name reads alone do not move group checkpoints.\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: [],\n organizationId: input.organizationId,\n policies: [authority.directory.policy, authority.admins.policy],\n stillCurrent,\n });\n await new OrganizationReadModelRepository(\n input.execSql,\n ).saveOrganizationGroupDisplayNames({\n organizationId: input.organizationId,\n names,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const byId = new Map(names.map((entry) => [entry.groupId, entry.name]));\n return {\n ...input.directory,\n groups: input.directory.groups.map((group) => ({\n ...group,\n name: byId.get(group.groupId) ?? \"\",\n nameUnreadable: unreadable.has(group.groupId),\n })),\n };\n}\n\nasync function readCurrentGroupName(\n input: Input,\n current: Parameters<GroupPolicyNameReader>[0],\n) {\n try {\n return await readGroupPolicyPayloadName(current, input.readEncryptedName);\n } catch (error) {\n if (!(error instanceof GroupMetadataUnreadableError)) throw error;\n await input.reportSecurityIncident(\n new KeyingVerificationError(\n \"invalid_shape\",\n \"Signed group name does not open under the cited metadata key\",\n ),\n {\n evidenceHashes: { stateHash: current.currentState.stateHash },\n objectId: current.currentState.principalId,\n objectKind: \"principal\",\n operation: \"organization.groupName\",\n organizationId: input.organizationId,\n },\n );\n return null;\n }\n}\n"]}
@@ -1,4 +1,3 @@
1
- export { loadAppliedOrganizationReadModelCursor } from "../../data/persistence/organizations/organizationReadModelCursorPersistence.js";
2
1
  export { type OrganizationReadModelInvalidationListener, subscribeOrganizationReadModelInvalidation, } from "../../data/persistence/organizations/organizationReadModelInvalidation.js";
3
2
  export { PendingPrincipalMutationError } from "../../data/persistence/principalMutationJournalPersistence.js";
4
3
  export type { AuthoredPrincipalMutation, PrincipalMutationJournalScope, } from "../../data/principals/principalMutationJournal.js";
@@ -1,4 +1,3 @@
1
- export { loadAppliedOrganizationReadModelCursor } from "../../data/persistence/organizations/organizationReadModelCursorPersistence.js";
2
1
  export { subscribeOrganizationReadModelInvalidation, } from "../../data/persistence/organizations/organizationReadModelInvalidation.js";
3
2
  export { PendingPrincipalMutationError } from "../../data/persistence/principalMutationJournalPersistence.js";
4
3
  export { UnreadablePrincipalMutationError } from "../../data/principals/principalMutationJournalRecord.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sCAAsC,EAAE,MAAM,6EAA6E,CAAC;AACrI,OAAO,EAEL,0CAA0C,GAC3C,MAAM,wEAAwE,CAAC;AAChF,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAK3G,OAAO,EAAE,gCAAgC,EAAE,MAAM,sDAAsD,CAAC;AACxG,OAAO,EACL,wBAAwB,EACxB,gBAAgB,EAChB,8BAA8B,EAC9B,mCAAmC,EACnC,oBAAoB,EACpB,2BAA2B,EAC3B,uBAAuB,EACvB,8BAA8B,EAC9B,oCAAoC,EACpC,yBAAyB,EAOzB,8BAA8B,EAG9B,sBAAsB,GACvB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,gCAAgC,EAAE,MAAM,4BAA4B,CAAC;AAC9E,OAAO,EAAE,gCAAgC,EAAE,MAAM,kCAAkC,CAAC;AACpF,OAAO,EACL,2BAA2B,EAC3B,6B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;AAC3C,OAAO,EACL,uCAAuC,EACvC,iCAAiC,EAEjC,uCAAuC,GACxC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,+BAA+B,EAC/B,sCAAsC,EACtC,6CAA6C,EAC7C,kDAAkD,EAClD,+BAA+B,EAC/B,oCAAoC,EACpC,0CAA0C,EAC1C,4BAA4B,GAC7B,MAAM,0BAA0B,CAAC","sourcesContent":["export { loadAppliedOrganizationReadModelCursor } from \"../../data/persistence/organizations/organizationReadModelCursorPersistence\";\nexport {\n type OrganizationReadModelInvalidationListener,\n subscribeOrganizationReadModelInvalidation,\n} from \"../../data/persistence/organizations/organizationReadModelInvalidation\";\nexport { PendingPrincipalMutationError } from \"../../data/persistence/principalMutationJournalPersistence\";\nexport type {\n AuthoredPrincipalMutation,\n PrincipalMutationJournalScope,\n} from \"../../data/principals/principalMutationJournal\";\nexport { UnreadablePrincipalMutationError } from \"../../data/principals/principalMutationJournalRecord\";\nexport {\n cancelStripeSubscription,\n changeStripePlan,\n checkNativePurchaseEligibility,\n claimNativeOrganizationSubscription,\n createStripeCheckout,\n createStripeCheckoutSession,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n loadStripeCheckoutOptions,\n type OrganizationBilling,\n type OrganizationBillingHistory,\n type OrganizationBillingHistoryEntry,\n type OrganizationBillingManagementUrl,\n type OrganizationBillingView,\n type OrganizationNativePurchaseEligibility,\n resolveOrganizationBillingView,\n type StripeCheckoutIntent,\n type StripeCheckoutOptions,\n startOrganizationTrial,\n} from \"./billing\";\nexport { revokeOrganizationContainerGrant } from \"./containerGrantRevocation\";\nexport { GroupMembershipNameMismatchError } from \"./groupNames/groupMembershipName\";\nexport {\n GroupShareNameMismatchError,\n shareRemoteContainerWithGroup,\n} from \"./groupShare\";\nexport { deleteOrganizationGroup } from \"./groups/deleteOrganizationGroup\";\nexport {\n type OrganizationLeaveRequestResult,\n setOrganizationLeaveRequested,\n} from \"./memberships/leaveRequest\";\nexport {\n withVerifiedDirectoryUser,\n withVerifiedLeaveRequests,\n withVerifiedUserLeaveRequest,\n} from \"./memberships/leaveRequestVerification\";\nexport {\n forgetPausedOrganizationContent,\n type OrganizationContentHost,\n type OrganizationMembership,\n type OrganizationMembershipApi,\n type OrganizationSyncPauseResult,\n refreshOrganizationMemberships,\n setOrganizationSyncPaused,\n} from \"./memberships/organizationMemberships\";\nexport {\n buildOrganizationProfileDocumentPatch,\n createInitializedOrganizationProfileDocument,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n getOrganizationProfileDocumentLocalId,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n readOrganizationProfileName,\n} from \"./organizationProfile\";\nexport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n readJournaledPrincipalMutation,\n} from \"./principalMutations/principalMutationJournalManagement\";\nexport {\n type PrincipalMutationJournalContext,\n PrincipalMutationOutcomeUnknownError,\n recoverJournaledPrincipalMutation,\n submitJournaledPrincipalMutation,\n} from \"./principalMutations/principalMutationJournalSession\";\nexport type { PrincipalMutationResponse } from \"./principalMutations/principalOperationReceipt\";\nexport {\n type AcknowledgedPrincipalCurrentInput,\n type AcknowledgedPrincipalCurrentRetirement,\n retainAcknowledgedPrincipalCurrents,\n} from \"./principalMutations/retainAcknowledgedPrincipalCurrents\";\nexport {\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n createOrganizationGroup,\n removeOrganizationGroupUser,\n rotateOrganizationGroupForAccessSetShrink,\n} from \"./principalPolicy\";\nexport {\n type CreateOrganizationApi,\n type CreateOrganizationInput,\n createOrganization,\n} from \"./provisioning/createOrganization\";\nexport {\n buildOrganizationGroupPolicyHistory,\n type OrganizationContainerGrant,\n type OrganizationContainerGrants,\n type OrganizationDirectory,\n type OrganizationDirectoryAndGroups,\n type OrganizationDirectoryUser,\n type OrganizationGroupContainer,\n type OrganizationGroupContainers,\n type OrganizationGroupDetails,\n type OrganizationGroupMember,\n type OrganizationGroupMembers,\n type OrganizationGroupPolicyHistory,\n type OrganizationGroupPolicyHistoryEntry,\n type OrganizationGroupSummary,\n type OrganizationPolicyGrantChange,\n type OrganizationPolicyGroupChange,\n type OrganizationPolicyHistory,\n type OrganizationPolicyHistoryEntry,\n type OrganizationPrincipalMemberChange,\n type OrganizationPrincipalMemberChangeType,\n type OrganizationPrincipalPolicyHistory,\n type OrganizationPrincipalPolicyHistoryEntry,\n type OrganizationProfile,\n type OrganizationUserDetail,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./readModel\";\nexport {\n loadLocalOrganizationDataUsage,\n type OrganizationDataUsage,\n type ReconcileOrganizationDataUsageInput,\n reconcileOrganizationDataUsage,\n} from \"./readModel/dataUsageReadModel\";\nexport {\n measureOrganizationDeviceDataUsage,\n ORGANIZATION_DOCUMENT_USAGE_CATEGORIES,\n type OrganizationDeviceDataUsage,\n type OrganizationDeviceDocumentUsageCategoryBreakdown,\n type OrganizationDocumentUsageCategory,\n} from \"./readModel/deviceDataUsage\";\nexport {\n type LocalOrganizationSummary,\n listLocalOrganizations,\n} from \"./readModel/listLocalOrganizations\";\nexport {\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupPolicyHistory,\n loadLocalOrganizationPolicyHistory,\n loadLocalOrganizationPolicyReference,\n loadLocalOrganizationUserDetail,\n} from \"./readModel/localReadModelDetails\";\nexport {\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupMembers,\n type ReconcileOrganizationDirectoryAndGroupsInput,\n reconcileOrganizationDirectoryAndGroups,\n} from \"./readModel/readModelProjection\";\nexport {\n buildRosterProfileDocumentPatch,\n createInitializedRosterProfileDocument,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n getRosterProfileDocumentLocalId,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n ROSTER_PROFILE_DOCUMENT_KIND,\n} from \"./rosterProfileContainer\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,0CAA0C,GAC3C,MAAM,wEAAwE,CAAC;AAChF,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAK3G,OAAO,EAAE,gCAAgC,EAAE,MAAM,sDAAsD,CAAC;AACxG,OAAO,EACL,wBAAwB,EACxB,gBAAgB,EAChB,8BAA8B,EAC9B,mCAAmC,EACnC,oBAAoB,EACpB,2BAA2B,EAC3B,uBAAuB,EACvB,8BAA8B,EAC9B,oCAAoC,EACpC,yBAAyB,EAOzB,8BAA8B,EAG9B,sBAAsB,GACvB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,gCAAgC,EAAE,MAAM,4BAA4B,CAAC;AAC9E,OAAO,EAAE,gCAAgC,EAAE,MAAM,kCAAkC,CAAC;AACpF,OAAO,EACL,2BAA2B,EAC3B,6BAA6B,GAC9B,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAC3E,OAAO,EAEL,6BAA6B,GAC9B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,yBAAyB,EACzB,yBAAyB,EACzB,4BAA4B,GAC7B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,+BAA+B,EAK/B,8BAA8B,EAC9B,yBAAyB,GAC1B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,qCAAqC,EACrC,4CAA4C,EAC5C,0CAA0C,EAC1C,qCAAqC,EACrC,kCAAkC,EAClC,2BAA2B,GAC5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,iCAAiC,EACjC,2CAA2C,EAC3C,8BAA8B,GAC/B,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAEL,oCAAoC,EACpC,iCAAiC,EACjC,gCAAgC,GACjC,MAAM,sDAAsD,CAAC;AAE9D,OAAO,EAGL,mCAAmC,GACpC,MAAM,0DAA0D,CAAC;AAClE,OAAO,EACL,wBAAwB,EACxB,8BAA8B,EAC9B,oCAAoC,EACpC,uBAAuB,EACvB,2BAA2B,EAC3B,yCAAyC,GAC1C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,kBAAkB,GACnB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,mCAAmC,EAwBnC,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,8BAA8B,EAG9B,8BAA8B,GAC/B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,kCAAkC,EAClC,sCAAsC,GAIvC,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAEL,sBAAsB,GACvB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,oCAAoC,EACpC,oCAAoC,EACpC,uCAAuC,EACvC,kCAAkC,EAClC,oCAAoC,EACpC,+BAA+B,GAChC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,uCAAuC,EACvC,iCAAiC,EAEjC,uCAAuC,GACxC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,+BAA+B,EAC/B,sCAAsC,EACtC,6CAA6C,EAC7C,kDAAkD,EAClD,+BAA+B,EAC/B,oCAAoC,EACpC,0CAA0C,EAC1C,4BAA4B,GAC7B,MAAM,0BAA0B,CAAC","sourcesContent":["export {\n type OrganizationReadModelInvalidationListener,\n subscribeOrganizationReadModelInvalidation,\n} from \"../../data/persistence/organizations/organizationReadModelInvalidation\";\nexport { PendingPrincipalMutationError } from \"../../data/persistence/principalMutationJournalPersistence\";\nexport type {\n AuthoredPrincipalMutation,\n PrincipalMutationJournalScope,\n} from \"../../data/principals/principalMutationJournal\";\nexport { UnreadablePrincipalMutationError } from \"../../data/principals/principalMutationJournalRecord\";\nexport {\n cancelStripeSubscription,\n changeStripePlan,\n checkNativePurchaseEligibility,\n claimNativeOrganizationSubscription,\n createStripeCheckout,\n createStripeCheckoutSession,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n loadStripeCheckoutOptions,\n type OrganizationBilling,\n type OrganizationBillingHistory,\n type OrganizationBillingHistoryEntry,\n type OrganizationBillingManagementUrl,\n type OrganizationBillingView,\n type OrganizationNativePurchaseEligibility,\n resolveOrganizationBillingView,\n type StripeCheckoutIntent,\n type StripeCheckoutOptions,\n startOrganizationTrial,\n} from \"./billing\";\nexport { revokeOrganizationContainerGrant } from \"./containerGrantRevocation\";\nexport { GroupMembershipNameMismatchError } from \"./groupNames/groupMembershipName\";\nexport {\n GroupShareNameMismatchError,\n shareRemoteContainerWithGroup,\n} from \"./groupShare\";\nexport { deleteOrganizationGroup } from \"./groups/deleteOrganizationGroup\";\nexport {\n type OrganizationLeaveRequestResult,\n setOrganizationLeaveRequested,\n} from \"./memberships/leaveRequest\";\nexport {\n withVerifiedDirectoryUser,\n withVerifiedLeaveRequests,\n withVerifiedUserLeaveRequest,\n} from \"./memberships/leaveRequestVerification\";\nexport {\n forgetPausedOrganizationContent,\n type OrganizationContentHost,\n type OrganizationMembership,\n type OrganizationMembershipApi,\n type OrganizationSyncPauseResult,\n refreshOrganizationMemberships,\n setOrganizationSyncPaused,\n} from \"./memberships/organizationMemberships\";\nexport {\n buildOrganizationProfileDocumentPatch,\n createInitializedOrganizationProfileDocument,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n getOrganizationProfileDocumentLocalId,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n readOrganizationProfileName,\n} from \"./organizationProfile\";\nexport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n readJournaledPrincipalMutation,\n} from \"./principalMutations/principalMutationJournalManagement\";\nexport {\n type PrincipalMutationJournalContext,\n PrincipalMutationOutcomeUnknownError,\n recoverJournaledPrincipalMutation,\n submitJournaledPrincipalMutation,\n} from \"./principalMutations/principalMutationJournalSession\";\nexport type { PrincipalMutationResponse } from \"./principalMutations/principalOperationReceipt\";\nexport {\n type AcknowledgedPrincipalCurrentInput,\n type AcknowledgedPrincipalCurrentRetirement,\n retainAcknowledgedPrincipalCurrents,\n} from \"./principalMutations/retainAcknowledgedPrincipalCurrents\";\nexport {\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n createOrganizationGroup,\n removeOrganizationGroupUser,\n rotateOrganizationGroupForAccessSetShrink,\n} from \"./principalPolicy\";\nexport {\n type CreateOrganizationApi,\n type CreateOrganizationInput,\n createOrganization,\n} from \"./provisioning/createOrganization\";\nexport {\n buildOrganizationGroupPolicyHistory,\n type OrganizationContainerGrant,\n type OrganizationContainerGrants,\n type OrganizationDirectory,\n type OrganizationDirectoryAndGroups,\n type OrganizationDirectoryUser,\n type OrganizationGroupContainer,\n type OrganizationGroupContainers,\n type OrganizationGroupDetails,\n type OrganizationGroupMember,\n type OrganizationGroupMembers,\n type OrganizationGroupPolicyHistory,\n type OrganizationGroupPolicyHistoryEntry,\n type OrganizationGroupSummary,\n type OrganizationPolicyGrantChange,\n type OrganizationPolicyGroupChange,\n type OrganizationPolicyHistory,\n type OrganizationPolicyHistoryEntry,\n type OrganizationPrincipalMemberChange,\n type OrganizationPrincipalMemberChangeType,\n type OrganizationPrincipalPolicyHistory,\n type OrganizationPrincipalPolicyHistoryEntry,\n type OrganizationProfile,\n type OrganizationUserDetail,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./readModel\";\nexport {\n loadLocalOrganizationDataUsage,\n type OrganizationDataUsage,\n type ReconcileOrganizationDataUsageInput,\n reconcileOrganizationDataUsage,\n} from \"./readModel/dataUsageReadModel\";\nexport {\n measureOrganizationDeviceDataUsage,\n ORGANIZATION_DOCUMENT_USAGE_CATEGORIES,\n type OrganizationDeviceDataUsage,\n type OrganizationDeviceDocumentUsageCategoryBreakdown,\n type OrganizationDocumentUsageCategory,\n} from \"./readModel/deviceDataUsage\";\nexport {\n type LocalOrganizationSummary,\n listLocalOrganizations,\n} from \"./readModel/listLocalOrganizations\";\nexport {\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupPolicyHistory,\n loadLocalOrganizationPolicyHistory,\n loadLocalOrganizationPolicyReference,\n loadLocalOrganizationUserDetail,\n} from \"./readModel/localReadModelDetails\";\nexport {\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupMembers,\n type ReconcileOrganizationDirectoryAndGroupsInput,\n reconcileOrganizationDirectoryAndGroups,\n} from \"./readModel/readModelProjection\";\nexport {\n buildRosterProfileDocumentPatch,\n createInitializedRosterProfileDocument,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n getRosterProfileDocumentLocalId,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n ROSTER_PROFILE_DOCUMENT_KIND,\n} from \"./rosterProfileContainer\";\n"]}
@@ -1,16 +1,19 @@
1
- import { purgeOrganizationAccessProjection } from "../../../data/persistence/organizations/organizationAccessRevocationPersistence.js";
2
- import { recordOrganizationPresentationDenials } from "../../../data/persistence/organizations/organizationPresentationDenialPersistence.js";
1
+ import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
3
2
  import { denyOrganizationPresentationAccess, runOrganizationPresentationMutation, } from "../readModel/organizationPresentationAccessState.js";
4
3
  export async function denyPolicyHistoryAccess(input) {
5
4
  denyOrganizationPresentationAccess(input, ["readModel", "usage"]);
5
+ const repository = new OrganizationReadModelRepository(input.execSql);
6
6
  try {
7
- await runOrganizationPresentationMutation(input.execSql, () => recordOrganizationPresentationDenials(input, ["readModel", "usage"]));
7
+ await runOrganizationPresentationMutation(input.execSql, () => repository.recordOrganizationPresentationDenials(input, [
8
+ "readModel",
9
+ "usage",
10
+ ]));
8
11
  }
9
12
  catch (error) {
10
13
  input.logError("Failed to record denied organization policy history", error);
11
14
  }
12
15
  try {
13
- await runOrganizationPresentationMutation(input.execSql, () => purgeOrganizationAccessProjection(input));
16
+ await runOrganizationPresentationMutation(input.execSql, () => repository.purgeOrganizationAccessProjection(input));
14
17
  }
15
18
  catch (error) {
16
19
  input.logError("Failed to purge denied organization policy history", error);
@@ -1 +1 @@
1
- {"version":3,"file":"policyHistoryAccessDenial.js","sourceRoot":"","sources":["policyHistoryAccessDenial.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,iFAAiF,CAAC;AACpI,OAAO,EAAE,qCAAqC,EAAE,MAAM,mFAAmF,CAAC;AAE1I,OAAO,EACL,kCAAkC,EAClC,mCAAmC,GACpC,MAAM,kDAAkD,CAAC;AAE1D,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,KAK7C;IACC,kCAAkC,CAAC,KAAK,EAAE,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC,CAAC;IAClE,IAAI,CAAC;QACH,MAAM,mCAAmC,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,CAC5D,qCAAqC,CAAC,KAAK,EAAE,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC,CACrE,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,KAAK,CAAC,QAAQ,CACZ,qDAAqD,EACrD,KAAK,CACN,CAAC;IACJ,CAAC;IACD,IAAI,CAAC;QACH,MAAM,mCAAmC,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,CAC5D,iCAAiC,CAAC,KAAK,CAAC,CACzC,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,KAAK,CAAC,QAAQ,CAAC,oDAAoD,EAAE,KAAK,CAAC,CAAC;IAC9E,CAAC;AACH,CAAC","sourcesContent":["import { purgeOrganizationAccessProjection } from \"../../../data/persistence/organizations/organizationAccessRevocationPersistence\";\nimport { recordOrganizationPresentationDenials } from \"../../../data/persistence/organizations/organizationPresentationDenialPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n denyOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n} from \"../readModel/organizationPresentationAccessState\";\n\nexport async function denyPolicyHistoryAccess(input: {\n execSql: ExecSql;\n organizationId: string;\n requesterUserId: string;\n logError: (message: string | Error, cause?: unknown) => void;\n}): Promise<void> {\n denyOrganizationPresentationAccess(input, [\"readModel\", \"usage\"]);\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n recordOrganizationPresentationDenials(input, [\"readModel\", \"usage\"]),\n );\n } catch (error) {\n input.logError(\n \"Failed to record denied organization policy history\",\n error,\n );\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n purgeOrganizationAccessProjection(input),\n );\n } catch (error) {\n input.logError(\"Failed to purge denied organization policy history\", error);\n }\n}\n"]}
1
+ {"version":3,"file":"policyHistoryAccessDenial.js","sourceRoot":"","sources":["policyHistoryAccessDenial.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAE1H,OAAO,EACL,kCAAkC,EAClC,mCAAmC,GACpC,MAAM,kDAAkD,CAAC;AAE1D,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,KAK7C;IACC,kCAAkC,CAAC,KAAK,EAAE,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC,CAAC;IAClE,MAAM,UAAU,GAAG,IAAI,+BAA+B,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACtE,IAAI,CAAC;QACH,MAAM,mCAAmC,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,CAC5D,UAAU,CAAC,qCAAqC,CAAC,KAAK,EAAE;YACtD,WAAW;YACX,OAAO;SACR,CAAC,CACH,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,KAAK,CAAC,QAAQ,CACZ,qDAAqD,EACrD,KAAK,CACN,CAAC;IACJ,CAAC;IACD,IAAI,CAAC;QACH,MAAM,mCAAmC,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,CAC5D,UAAU,CAAC,iCAAiC,CAAC,KAAK,CAAC,CACpD,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,KAAK,CAAC,QAAQ,CAAC,oDAAoD,EAAE,KAAK,CAAC,CAAC;IAC9E,CAAC;AACH,CAAC","sourcesContent":["import { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n denyOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n} from \"../readModel/organizationPresentationAccessState\";\n\nexport async function denyPolicyHistoryAccess(input: {\n execSql: ExecSql;\n organizationId: string;\n requesterUserId: string;\n logError: (message: string | Error, cause?: unknown) => void;\n}): Promise<void> {\n denyOrganizationPresentationAccess(input, [\"readModel\", \"usage\"]);\n const repository = new OrganizationReadModelRepository(input.execSql);\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.recordOrganizationPresentationDenials(input, [\n \"readModel\",\n \"usage\",\n ]),\n );\n } catch (error) {\n input.logError(\n \"Failed to record denied organization policy history\",\n error,\n );\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.purgeOrganizationAccessProjection(input),\n );\n } catch (error) {\n input.logError(\"Failed to purge denied organization policy history\", error);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { OrganizationDataUsageRepository } from "../../../data/persistence/organizations/organizationDataUsagePersistence.js";
2
- import { recordOrganizationPresentationDenials } from "../../../data/persistence/organizations/organizationPresentationDenialPersistence.js";
2
+ import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
3
3
  import { captureOrganizationPresentationAccessAttempt, denyOrganizationPresentationAccess, isOrganizationPresentationAccessAttemptCurrent, isOrganizationPresentationAccessReadable, restoreOrganizationPresentationAccess, runOrganizationPresentationMutation, runOrganizationPresentationRead, } from "./organizationPresentationAccessState.js";
4
4
  import { isOrganizationPresentationAccessDeniedFailure } from "./organizationPresentationFailures.js";
5
5
  export async function loadLocalOrganizationDataUsage(input) {
@@ -21,7 +21,7 @@ export async function reconcileOrganizationDataUsage(input) {
21
21
  // Durable marker first: a failed purge plus a restart must not serve
22
22
  // the revoked usage projection.
23
23
  try {
24
- await runOrganizationPresentationMutation(input.execSql, () => recordOrganizationPresentationDenials(input, ["usage"]));
24
+ await runOrganizationPresentationMutation(input.execSql, () => new OrganizationReadModelRepository(input.execSql).recordOrganizationPresentationDenials(input, ["usage"]));
25
25
  }
26
26
  catch (error) {
27
27
  input.logError?.("Failed to record denied organization data usage", error);
@@ -1 +1 @@
1
- {"version":3,"file":"dataUsageReadModel.js","sourceRoot":"","sources":["dataUsageReadModel.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,+BAA+B,EAAE,MAAM,0EAA0E,CAAC;AAC3H,OAAO,EAAE,qCAAqC,EAAE,MAAM,mFAAmF,CAAC;AAE1I,OAAO,EACL,4CAA4C,EAC5C,kCAAkC,EAClC,8CAA8C,EAC9C,wCAAwC,EAExC,qCAAqC,EACrC,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,6CAA6C,EAAE,MAAM,oCAAoC,CAAC;AAyBnG,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,KAA2C;IAE3C,OAAO,+BAA+B,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,CAC1D,IAAI,+BAA+B,CACjC,KAAK,CAAC,OAAO,CACd,CAAC,mCAAmC,CACnC,KAAK,CAAC,cAAc,EACpB,KAAK,CAAC,eAAe,CACtB,CACF,CAAC;AACJ,CAAC;AAED,SAAS,uBAAuB,CAC9B,KAA2C,EAC3C,OAA8C,EAC9C,KAAQ;IAER,OAAO,8CAA8C,CAAC,KAAK,EAAE,OAAO,CAAC;QACnE,wCAAwC,CAAC,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;QAED,MAAM,CAAC,MAAM,EAAE,CAAC;QAChB,OAAO,uBAAuB,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IACxD,CAAC;IAED,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc,EAAE,CAAC;QACxD,KAAK,CAAC,QAAQ,EAAE,CACd,yDAAyD,KAAK,CAAC,cAAc,EAAE,CAChF,CAAC;QACF,OAAO,uBAAuB,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IACxD,CAAC;IAED,OAAO,mCAAmC,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,IAAI,EAAE;QACnE,IAAI,CAAC,8CAA8C,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC;YACpE,OAAO,IAAI,CAAC;QACd,CAAC;QACD,IAAI,CAAC;YACH,MAAM,IAAI,+BAA+B,CACvC,KAAK,CAAC,OAAO,CACd,CAAC,mCAAmC,CAAC;gBACpC,eAAe,EAAE,KAAK,CAAC,eAAe;gBACtC,QAAQ,EAAE,MAAM,CAAC,IAAI;aACtB,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,KAAK,CAAC,QAAQ,EAAE,CAAC,2CAA2C,EAAE,KAAK,CAAC,CAAC;YACrE,OAAO,uBAAuB,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;QACxD,CAAC;QACD,OAAO,qCAAqC,CAAC,KAAK,EAAE,OAAO,CAAC;YAC1D,CAAC,CAAC,MAAM,CAAC,IAAI;YACb,CAAC,CAAC,IAAI,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport type { OrganizationDataUsageResponse } from \"@tearleads/validators/response\";\nimport { OrganizationDataUsageRepository } from \"../../../data/persistence/organizations/organizationDataUsagePersistence\";\nimport { recordOrganizationPresentationDenials } from \"../../../data/persistence/organizations/organizationPresentationDenialPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n denyOrganizationPresentationAccess,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n type OrganizationPresentationAccessAttempt,\n restoreOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n runOrganizationPresentationRead,\n} from \"./organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"./organizationPresentationFailures\";\n\nexport type OrganizationDataUsage = OrganizationDataUsageResponse;\n\ninterface OrganizationDataUsageApi {\n getOrganizationDataUsageResult(\n organizationId: string,\n options?: RequestResultOptions,\n ): Promise<RequestResult<OrganizationDataUsageResponse>>;\n}\n\ninterface OrganizationDataUsageProjectionInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly requesterUserId: string;\n}\n\nexport interface ReconcileOrganizationDataUsageInput\n extends OrganizationDataUsageProjectionInput {\n readonly apiClient: OrganizationDataUsageApi;\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n}\n\nexport async function loadLocalOrganizationDataUsage(\n input: OrganizationDataUsageProjectionInput,\n): Promise<OrganizationDataUsage | null> {\n return runOrganizationPresentationRead(input, \"usage\", () =>\n new OrganizationDataUsageRepository(\n input.execSql,\n ).loadOrganizationDataUsageProjection(\n input.organizationId,\n input.requesterUserId,\n ),\n );\n}\n\nfunction retainedIfUsageReadable<T>(\n input: OrganizationDataUsageProjectionInput,\n attempt: OrganizationPresentationAccessAttempt,\n value: T,\n): T | null {\n return isOrganizationPresentationAccessAttemptCurrent(input, attempt) &&\n isOrganizationPresentationAccessReadable(input, \"usage\")\n ? value\n : null;\n}\n\nexport async function reconcileOrganizationDataUsage(\n input: ReconcileOrganizationDataUsageInput,\n): Promise<OrganizationDataUsage | null> {\n const attempt = captureOrganizationPresentationAccessAttempt(input, \"usage\");\n const local = await loadLocalOrganizationDataUsage(input);\n const result = await input.apiClient.getOrganizationDataUsageResult(\n input.organizationId,\n { reportErrors: false },\n );\n if (!result.ok) {\n if (isOrganizationPresentationAccessDeniedFailure(result)) {\n denyOrganizationPresentationAccess(input, [\"usage\"]);\n // Durable marker first: a failed purge plus a restart must not serve\n // the revoked usage projection.\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n recordOrganizationPresentationDenials(input, [\"usage\"]),\n );\n } catch (error) {\n input.logError?.(\n \"Failed to record denied organization data usage\",\n error,\n );\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n new OrganizationDataUsageRepository(\n input.execSql,\n ).purgeOrganizationDataUsageProjection(\n input.organizationId,\n input.requesterUserId,\n ),\n );\n } catch (error) {\n input.logError?.(\n \"Failed to purge denied organization data usage\",\n error,\n );\n }\n return null;\n }\n\n result.report();\n return retainedIfUsageReadable(input, attempt, local);\n }\n\n if (result.data.organizationId !== input.organizationId) {\n input.logError?.(\n `Organization data-usage response scope does not match ${input.organizationId}`,\n );\n return retainedIfUsageReadable(input, attempt, local);\n }\n\n return runOrganizationPresentationMutation(input.execSql, async () => {\n if (!isOrganizationPresentationAccessAttemptCurrent(input, attempt)) {\n return null;\n }\n try {\n await new OrganizationDataUsageRepository(\n input.execSql,\n ).saveOrganizationDataUsageProjection({\n requesterUserId: input.requesterUserId,\n response: result.data,\n });\n } catch (error) {\n input.logError?.(\"Failed to persist organization data usage\", error);\n return retainedIfUsageReadable(input, attempt, local);\n }\n return restoreOrganizationPresentationAccess(input, attempt)\n ? result.data\n : null;\n });\n}\n"]}
1
+ {"version":3,"file":"dataUsageReadModel.js","sourceRoot":"","sources":["dataUsageReadModel.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,+BAA+B,EAAE,MAAM,0EAA0E,CAAC;AAC3H,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAE1H,OAAO,EACL,4CAA4C,EAC5C,kCAAkC,EAClC,8CAA8C,EAC9C,wCAAwC,EAExC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AE,MAAM,CAAC,IAAI;aACtB,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,KAAK,CAAC,QAAQ,EAAE,CAAC,2CAA2C,EAAE,KAAK,CAAC,CAAC;YACrE,OAAO,uBAAuB,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;QACxD,CAAC;QACD,OAAO,qCAAqC,CAAC,KAAK,EAAE,OAAO,CAAC;YAC1D,CAAC,CAAC,MAAM,CAAC,IAAI;YACb,CAAC,CAAC,IAAI,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport type { OrganizationDataUsageResponse } from \"@tearleads/validators/response\";\nimport { OrganizationDataUsageRepository } from \"../../../data/persistence/organizations/organizationDataUsagePersistence\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n denyOrganizationPresentationAccess,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n type OrganizationPresentationAccessAttempt,\n restoreOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n runOrganizationPresentationRead,\n} from \"./organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"./organizationPresentationFailures\";\n\nexport type OrganizationDataUsage = OrganizationDataUsageResponse;\n\ninterface OrganizationDataUsageApi {\n getOrganizationDataUsageResult(\n organizationId: string,\n options?: RequestResultOptions,\n ): Promise<RequestResult<OrganizationDataUsageResponse>>;\n}\n\ninterface OrganizationDataUsageProjectionInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly requesterUserId: string;\n}\n\nexport interface ReconcileOrganizationDataUsageInput\n extends OrganizationDataUsageProjectionInput {\n readonly apiClient: OrganizationDataUsageApi;\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n}\n\nexport async function loadLocalOrganizationDataUsage(\n input: OrganizationDataUsageProjectionInput,\n): Promise<OrganizationDataUsage | null> {\n return runOrganizationPresentationRead(input, \"usage\", () =>\n new OrganizationDataUsageRepository(\n input.execSql,\n ).loadOrganizationDataUsageProjection(\n input.organizationId,\n input.requesterUserId,\n ),\n );\n}\n\nfunction retainedIfUsageReadable<T>(\n input: OrganizationDataUsageProjectionInput,\n attempt: OrganizationPresentationAccessAttempt,\n value: T,\n): T | null {\n return isOrganizationPresentationAccessAttemptCurrent(input, attempt) &&\n isOrganizationPresentationAccessReadable(input, \"usage\")\n ? value\n : null;\n}\n\nexport async function reconcileOrganizationDataUsage(\n input: ReconcileOrganizationDataUsageInput,\n): Promise<OrganizationDataUsage | null> {\n const attempt = captureOrganizationPresentationAccessAttempt(input, \"usage\");\n const local = await loadLocalOrganizationDataUsage(input);\n const result = await input.apiClient.getOrganizationDataUsageResult(\n input.organizationId,\n { reportErrors: false },\n );\n if (!result.ok) {\n if (isOrganizationPresentationAccessDeniedFailure(result)) {\n denyOrganizationPresentationAccess(input, [\"usage\"]);\n // Durable marker first: a failed purge plus a restart must not serve\n // the revoked usage projection.\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n new OrganizationReadModelRepository(\n input.execSql,\n ).recordOrganizationPresentationDenials(input, [\"usage\"]),\n );\n } catch (error) {\n input.logError?.(\n \"Failed to record denied organization data usage\",\n error,\n );\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n new OrganizationDataUsageRepository(\n input.execSql,\n ).purgeOrganizationDataUsageProjection(\n input.organizationId,\n input.requesterUserId,\n ),\n );\n } catch (error) {\n input.logError?.(\n \"Failed to purge denied organization data usage\",\n error,\n );\n }\n return null;\n }\n\n result.report();\n return retainedIfUsageReadable(input, attempt, local);\n }\n\n if (result.data.organizationId !== input.organizationId) {\n input.logError?.(\n `Organization data-usage response scope does not match ${input.organizationId}`,\n );\n return retainedIfUsageReadable(input, attempt, local);\n }\n\n return runOrganizationPresentationMutation(input.execSql, async () => {\n if (!isOrganizationPresentationAccessAttemptCurrent(input, attempt)) {\n return null;\n }\n try {\n await new OrganizationDataUsageRepository(\n input.execSql,\n ).saveOrganizationDataUsageProjection({\n requesterUserId: input.requesterUserId,\n response: result.data,\n });\n } catch (error) {\n input.logError?.(\"Failed to persist organization data usage\", error);\n return retainedIfUsageReadable(input, attempt, local);\n }\n return restoreOrganizationPresentationAccess(input, attempt)\n ? result.data\n : null;\n });\n}\n"]}