@tearleads/client-sdk 0.1.222 → 0.1.224

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 (103) hide show
  1. package/data/documents/shared/containerKek/containerKekPathVerification.js +2 -0
  2. package/data/documents/shared/containerKek/containerKekPathVerification.js.map +1 -1
  3. package/data/documents/shared/projection/index.js +2 -0
  4. package/data/documents/shared/projection/index.js.map +1 -1
  5. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +3 -0
  6. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +2 -1
  7. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  8. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +2 -1
  9. package/data/keyingProjectionVerification/container/containerDestinationVerification.js +1 -0
  10. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
  11. package/data/keyingProjectionVerification/container/containerProjectionVerification.d.ts +3 -2
  12. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +2 -0
  13. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  14. package/data/keyingProjectionVerification/document/documentProjectionVerification.d.ts +2 -1
  15. package/data/keyingProjectionVerification/document/documentProjectionVerification.js +2 -0
  16. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
  17. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +3 -2
  18. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  19. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.d.ts +2 -1
  20. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js +7 -3
  21. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js.map +1 -1
  22. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +3 -2
  23. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  24. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +17 -6
  25. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  26. package/data/keyingProjectionVerification/types.d.ts +20 -2
  27. package/data/keyingProjectionVerification/types.js.map +1 -1
  28. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +1 -1
  29. package/data/persistence/container-contents/containerContentsPersistenceTypes.js +0 -1
  30. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  31. package/data/persistence/container-contents/containerCreateIntentSettlement.js +2 -2
  32. package/data/persistence/container-contents/containerCreateIntentSettlement.js.map +1 -1
  33. package/data/persistence/container-contents/containerIntentPersistence.js +2 -2
  34. package/data/persistence/container-contents/containerIntentPersistence.js.map +1 -1
  35. package/data/persistence/container-contents/documentContainerProjectionPersistence.d.ts +10 -9
  36. package/data/persistence/container-contents/documentContainerProjectionPersistence.js +14 -3
  37. package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
  38. package/data/persistence/documents/documentsPersistence.d.ts +2 -1
  39. package/data/persistence/documents/documentsPersistence.js +3 -3
  40. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  41. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
  42. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js.map +1 -1
  43. package/data/persistence/documents/internal/containerDocumentTombstones.d.ts +10 -0
  44. package/data/persistence/documents/internal/containerDocumentTombstones.js +3 -14
  45. package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
  46. package/data/persistence/documents/internal/discoveredDocumentPlacement.js +1 -1
  47. package/data/persistence/documents/internal/discoveredDocumentPlacement.js.map +1 -1
  48. package/data/persistence/documents/internal/discoveredDocumentUpsert.js +1 -1
  49. package/data/persistence/documents/internal/discoveredDocumentUpsert.js.map +1 -1
  50. package/data/persistence/{container-contents → documents}/pendingContainerCreate.js +1 -2
  51. package/data/persistence/documents/pendingContainerCreate.js.map +1 -0
  52. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js +2 -0
  53. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -1
  54. package/data/sqlite/schema/index.d.ts +1 -1
  55. package/data/sqlite/schema/index.js +1 -1
  56. package/data/sqlite/schema/index.js.map +1 -1
  57. package/data/sqlite/schema/localIntentSchema.d.ts +6 -0
  58. package/data/sqlite/schema/localIntentSchema.js +6 -0
  59. package/data/sqlite/schema/localIntentSchema.js.map +1 -1
  60. package/package.json +1 -1
  61. package/workflows/container-contents/container-state/create/createAdoption.js +2 -0
  62. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  63. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +2 -0
  64. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  65. package/workflows/container-contents/container-state/share/groupGrantVerification.js +2 -0
  66. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  67. package/workflows/container-contents/container-state/share/index.js +2 -0
  68. package/workflows/container-contents/container-state/share/index.js.map +1 -1
  69. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js +1 -1
  70. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js.map +1 -1
  71. package/workflows/container-contents/documentQueries/index.js +2 -2
  72. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  73. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +2 -0
  74. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  75. package/workflows/containers/child/create/index.d.ts +1 -1
  76. package/workflows/containers/child/create/index.js +2 -0
  77. package/workflows/containers/child/create/index.js.map +1 -1
  78. package/workflows/containers/child/move/moveWraps.js +3 -0
  79. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  80. package/workflows/containers/child/rekey/carriedDescendantRekeys.js +2 -0
  81. package/workflows/containers/child/rekey/carriedDescendantRekeys.js.map +1 -1
  82. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js +2 -0
  83. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js.map +1 -1
  84. package/workflows/containers/child/share/sharePlanCore.js +2 -0
  85. package/workflows/containers/child/share/sharePlanCore.js.map +1 -1
  86. package/workflows/containers/rematerialization/principalContainerRematerialization.js +2 -0
  87. package/workflows/containers/rematerialization/principalContainerRematerialization.js.map +1 -1
  88. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js +2 -0
  89. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js.map +1 -1
  90. package/workflows/documents/create/index.js +3 -1
  91. package/workflows/documents/create/index.js.map +1 -1
  92. package/workflows/documents/linkSet/linkSetAuthority.js +2 -0
  93. package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -1
  94. package/workflows/documents/purge/index.js +6 -0
  95. package/workflows/documents/purge/index.js.map +1 -1
  96. package/workflows/documents/sync/syncSubmittedResult.js +2 -0
  97. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
  98. package/workflows/documents/syncFailures/syncRepairAccess.js +2 -0
  99. package/workflows/documents/syncFailures/syncRepairAccess.js.map +1 -1
  100. package/data/persistence/container-contents/pendingContainerCreate.js.map +0 -1
  101. /package/data/persistence/{container-contents → documents}/documentPlacement.d.ts +0 -0
  102. /package/data/persistence/{container-contents → documents}/documentPlacement.js +0 -0
  103. /package/data/persistence/{container-contents → documents}/documentPlacement.js.map +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"containerDocumentTombstoneHolds.js","sourceRoot":"","sources":["containerDocumentTombstoneHolds.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAY,GAAG,EAAE,MAAM,aAAa,CAAC;AAEvE,OAAO,EAAE,+BAA+B,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,kCAAkC,CAAC;AAE1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,GAAG,CAAC,+BAA+B,CAAC,UAAU,CAAC,EAC/C,GAAG,CAAC,+BAA+B,CAAC,WAAW,CAAC,CACjD,CAAC,CACL,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,MAAoC,EACpC,KAAuD;IAKvD,MAAM,KAAK,GAAG,IAAI,GAAG,CACnB,CACE,MAAM,iDAAiD,CAAC,MAAM,EAAE,KAAK,CAAC,CACvE,CAAC,GAAG,CAAC,YAAY,CAAC,CACpB,CAAC;IACF,OAAO;QACL,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;QAC3D,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;KACjE,CAAC;AACJ,CAAC","sourcesContent":["import { and, asc, eq, inArray, or, type SQL, sql } from \"drizzle-orm\";\nimport type { SQLiteColumn } from \"drizzle-orm/sqlite-core\";\nimport { containerDocumentTombstoneHolds } from \"../../../sqlite/schema\";\nimport {\n documentContainerProjection,\n documentProjection,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport {\n remoteResetBatches,\n sqliteRowsPerStatement,\n} from \"../../../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { filterWritableDocumentPlacements } from \"../../container-contents/documentPlacement\";\nimport type { ContainerDocumentTombstoneInput } from \"../types\";\n\nexport interface ContainerDocumentPlacementKey {\n readonly containerId: string;\n readonly documentId: string;\n}\n\nexport type HeldContainerDocumentTombstone = Omit<\n ContainerDocumentTombstoneInput,\n \"accessEpoch\" | \"linkedContainerIds\"\n> & {\n /** Held without a verification attempt; the backoff does not advance. */\n readonly deferred?: boolean | undefined;\n /** A verified head still links it; retry the tombstone while keeping it visible. */\n readonly refuted?: boolean | undefined;\n};\n\n/** Keep `IN (...)` lists well under SQLite's bound-parameter limit. */\nconst HOLD_SQL_ID_BATCH_SIZE = 400;\n\nfunction batches<T>(values: ReadonlyArray<T>): T[][] {\n const unique = Array.from(new Set(values));\n const result: T[][] = [];\n for (let index = 0; index < unique.length; index += HOLD_SQL_ID_BATCH_SIZE) {\n result.push(unique.slice(index, index + HOLD_SQL_ID_BATCH_SIZE));\n }\n return result;\n}\n\nexport function containerDocumentPlacementKey(\n placement: ContainerDocumentPlacementKey,\n): string {\n return `${placement.documentId}\\u0000${placement.containerId}`;\n}\nconst placementKey = containerDocumentPlacementKey;\n\n/**\n * Matches the listed (document, container) placements by primary key. An\n * empty list matches nothing: `or()` of no terms is no condition at all, and\n * a delete filtered by it would remove every row.\n */\nexport function placementPairsMatch(\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n documentIdColumn: SQLiteColumn,\n containerIdColumn: SQLiteColumn,\n): SQL {\n return (\n or(\n ...placements.map((placement) =>\n and(\n eq(documentIdColumn, placement.documentId),\n eq(containerIdColumn, placement.containerId),\n ),\n ),\n ) ?? sql`0`\n );\n}\n\nfunction uniquePlacements(\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n): ContainerDocumentPlacementKey[] {\n return Array.from(\n new Map(\n placements.map((placement) => [placementKey(placement), placement]),\n ).values(),\n );\n}\n\nexport async function deleteContainerDocumentTombstoneHoldRows(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n): Promise<void> {\n for (const batch of remoteResetBatches(uniquePlacements(placements))) {\n await tx\n .delete(containerDocumentTombstoneHolds)\n .where(\n placementPairsMatch(\n batch,\n containerDocumentTombstoneHolds.documentId,\n containerDocumentTombstoneHolds.containerId,\n ),\n )\n .run();\n }\n}\n\n/**\n * A local move takes ownership of a document's placement: the intent, not a\n * server listing, now says where it lives, so every hold that was hiding one\n * of its placements is released with the link rewrite.\n */\nexport async function deleteContainerDocumentTombstoneHoldsForDocuments(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<void> {\n for (const batch of batches(documentIds)) {\n await tx\n .delete(containerDocumentTombstoneHolds)\n .where(inArray(containerDocumentTombstoneHolds.documentId, batch))\n .run();\n }\n}\n\n/** Holds on containers whose link rows are being removed locally. */\nexport async function deleteContainerDocumentTombstoneHoldsForContainers(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n for (const batch of batches(containerIds)) {\n await tx\n .delete(containerDocumentTombstoneHolds)\n .where(inArray(containerDocumentTombstoneHolds.containerId, batch))\n .run();\n }\n}\n\n/**\n * The placements among `placements` that exist locally: a link row, or a\n * document projection row whose primary container is the named container.\n * A tombstone for any other placement has nothing to remove or hide, so it\n * is not worth fetching and verifying the document head for.\n */\nexport async function listKnownContainerDocumentPlacementsInTransaction(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n): Promise<ContainerDocumentPlacementKey[]> {\n const known = new Set<string>();\n for (const batch of batches(placements.map((entry) => entry.documentId))) {\n const [linkRows, projectionRows] = await Promise.all([\n tx\n .select({\n containerId: documentContainerProjection.containerId,\n documentId: documentContainerProjection.documentId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, batch)),\n tx\n .select({\n containerId: documentProjection.containerId,\n documentId: documentProjection.documentId,\n })\n .from(documentProjection)\n .where(inArray(documentProjection.documentId, batch)),\n ]);\n for (const row of [...linkRows, ...projectionRows]) {\n if (row.documentId !== null && row.containerId !== null) {\n known.add(\n placementKey({\n containerId: row.containerId,\n documentId: row.documentId,\n }),\n );\n }\n }\n }\n return placements.filter((placement) => known.has(placementKey(placement)));\n}\n\n// Preserve input order when one placement occurs in both attempt modes.\n// A deferred conflict changes only tombstonedAt, never recency or attempts.\nfunction* holdWriteBatches(\n tombstones: ReadonlyArray<HeldContainerDocumentTombstone>,\n) {\n const size = sqliteRowsPerStatement(6);\n let batch: HeldContainerDocumentTombstone[] = [];\n for (const tombstone of tombstones) {\n if (\n batch.length &&\n (batch.length === size ||\n Boolean(batch[0]?.deferred) !== Boolean(tombstone.deferred))\n ) {\n yield batch;\n batch = [];\n }\n batch.push(tombstone);\n }\n if (batch.length) yield batch;\n}\n\n/**\n * Hold listing tombstones whose signed evidence is unavailable. A placement a\n * pending move intent owns is never held: the intent, not the listing, decides\n * where the document lives until it settles (`ProtectPendingTombstones`).\n */\nexport async function holdContainerDocumentTombstonesInTransaction(\n tx: ClientSQLiteTransactionScope,\n tombstones: ReadonlyArray<HeldContainerDocumentTombstone>,\n now: string,\n): Promise<void> {\n const writable = new Set(\n (\n await filterWritableDocumentPlacements(\n tx,\n tombstones.map((tombstone) => ({\n documentId: tombstone.documentId,\n containerIds: [],\n })),\n )\n ).map((input) => input.documentId),\n );\n const applicable = tombstones.filter((tombstone) =>\n writable.has(tombstone.documentId),\n );\n for (const batch of holdWriteBatches(applicable)) {\n const deferred = Boolean(batch[0]?.deferred);\n await tx\n .insert(containerDocumentTombstoneHolds)\n .values(\n batch.map((tombstone) => ({\n containerId: tombstone.containerId,\n documentId: tombstone.documentId,\n tombstonedAt: tombstone.updatedAt,\n hidden: !tombstone.refuted,\n updatedAt: now,\n attempts: deferred ? 0 : 1,\n })),\n )\n .onConflictDoUpdate({\n target: [\n containerDocumentTombstoneHolds.documentId,\n containerDocumentTombstoneHolds.containerId,\n ],\n set: deferred\n ? { tombstonedAt: sql`excluded.tombstoned_at` }\n : {\n tombstonedAt: sql`excluded.tombstoned_at`,\n updatedAt: sql`excluded.updated_at`,\n hidden: sql`min(${containerDocumentTombstoneHolds.hidden}, excluded.hidden)`,\n attempts: sql`${containerDocumentTombstoneHolds.attempts} + 1`,\n },\n })\n .run();\n }\n}\n\n/** Release the holds on placements a listing has re-asserted as linked. */\nexport async function deleteContainerDocumentTombstoneHoldRowsForLinks(\n tx: ClientSQLiteTransactionScope,\n links: ReadonlyArray<{\n readonly containerIds: ReadonlyArray<string>;\n readonly documentId: string;\n }>,\n): Promise<void> {\n await deleteContainerDocumentTombstoneHoldRows(\n tx,\n links.flatMap((link) =>\n link.containerIds.map((containerId) => ({\n containerId,\n documentId: link.documentId,\n })),\n ),\n );\n}\n\nexport interface ContainerDocumentTombstoneHoldRow\n extends ContainerDocumentPlacementKey {\n readonly attempts: number;\n readonly hidden: boolean;\n readonly tombstonedAt: string;\n readonly updatedAt: string;\n}\n\nconst holdRowSelection = {\n attempts: containerDocumentTombstoneHolds.attempts,\n hidden: containerDocumentTombstoneHolds.hidden,\n containerId: containerDocumentTombstoneHolds.containerId,\n documentId: containerDocumentTombstoneHolds.documentId,\n tombstonedAt: containerDocumentTombstoneHolds.tombstonedAt,\n updatedAt: containerDocumentTombstoneHolds.updatedAt,\n};\n\n/** Every hold on the given containers, including visible refuted retries. */\nexport async function listContainerDocumentTombstoneHoldsInTransaction(\n handle: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<ContainerDocumentTombstoneHoldRow[]> {\n const holds: ContainerDocumentTombstoneHoldRow[] = [];\n for (const batch of batches(containerIds)) {\n holds.push(\n ...(await handle\n .select(holdRowSelection)\n .from(containerDocumentTombstoneHolds)\n .where(inArray(containerDocumentTombstoneHolds.containerId, batch))\n .orderBy(\n asc(containerDocumentTombstoneHolds.containerId),\n asc(containerDocumentTombstoneHolds.documentId),\n )),\n );\n }\n return holds;\n}\n\n/** Every hidden hold on the given documents, in any container. */\nexport async function listContainerDocumentTombstoneHoldsForDocumentsInTransaction(\n handle: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<ContainerDocumentTombstoneHoldRow[]> {\n const holds: ContainerDocumentTombstoneHoldRow[] = [];\n for (const batch of batches(documentIds)) {\n holds.push(\n ...(await handle\n .select(holdRowSelection)\n .from(containerDocumentTombstoneHolds)\n .where(\n and(\n inArray(containerDocumentTombstoneHolds.documentId, batch),\n eq(containerDocumentTombstoneHolds.hidden, true),\n ),\n )\n .orderBy(\n asc(containerDocumentTombstoneHolds.documentId),\n asc(containerDocumentTombstoneHolds.containerId),\n )),\n );\n }\n return holds;\n}\n\n/**\n * Split the holds on the given containers into those whose placement is gone\n * (the document was purged, reset, or relinked locally: nothing left to hide,\n * so the hold is dropped) and those still hiding a placement.\n */\nexport async function partitionContainerDocumentTombstoneHolds(\n handle: ClientSQLiteTransactionScope,\n holds: ReadonlyArray<ContainerDocumentTombstoneHoldRow>,\n): Promise<{\n live: ContainerDocumentTombstoneHoldRow[];\n orphaned: ContainerDocumentTombstoneHoldRow[];\n}> {\n const known = new Set(\n (\n await listKnownContainerDocumentPlacementsInTransaction(handle, holds)\n ).map(placementKey),\n );\n return {\n live: holds.filter((hold) => known.has(placementKey(hold))),\n orphaned: holds.filter((hold) => !known.has(placementKey(hold))),\n };\n}\n"]}
1
+ {"version":3,"file":"containerDocumentTombstoneHolds.js","sourceRoot":"","sources":["containerDocumentTombstoneHolds.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAY,GAAG,EAAE,MAAM,aAAa,CAAC;AAEvE,OAAO,EAAE,+BAA+B,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAkBxE,uEAAuE;AACvE,MAAM,sBAAsB,GAAG,GAAG,CAAC;AAEnC,SAAS,OAAO,CAAI,MAAwB;IAC1C,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IAC3C,MAA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,MAAM,KAAK,GAAG,IAAI,GAAG,CACnB,CACE,MAAM,iDAAiD,CAAC,MAAM,EAAE,KAAK,CAAC,CACvE,CAAC,GAAG,CAAC,YAAY,CAAC,CACpB,CAAC;IACF,OAAO;QACL,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;QAC3D,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;KACjE,CAAC;AACJ,CAAC","sourcesContent":["import { and, asc, eq, inArray, or, type SQL, sql } from \"drizzle-orm\";\nimport type { SQLiteColumn } from \"drizzle-orm/sqlite-core\";\nimport { containerDocumentTombstoneHolds } from \"../../../sqlite/schema\";\nimport {\n documentContainerProjection,\n documentProjection,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport {\n remoteResetBatches,\n sqliteRowsPerStatement,\n} from \"../../../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { filterWritableDocumentPlacements } from \"../documentPlacement\";\nimport type { ContainerDocumentTombstoneInput } from \"../types\";\n\nexport interface ContainerDocumentPlacementKey {\n readonly containerId: string;\n readonly documentId: string;\n}\n\nexport type HeldContainerDocumentTombstone = Omit<\n ContainerDocumentTombstoneInput,\n \"accessEpoch\" | \"linkedContainerIds\"\n> & {\n /** Held without a verification attempt; the backoff does not advance. */\n readonly deferred?: boolean | undefined;\n /** A verified head still links it; retry the tombstone while keeping it visible. */\n readonly refuted?: boolean | undefined;\n};\n\n/** Keep `IN (...)` lists well under SQLite's bound-parameter limit. */\nconst HOLD_SQL_ID_BATCH_SIZE = 400;\n\nfunction batches<T>(values: ReadonlyArray<T>): T[][] {\n const unique = Array.from(new Set(values));\n const result: T[][] = [];\n for (let index = 0; index < unique.length; index += HOLD_SQL_ID_BATCH_SIZE) {\n result.push(unique.slice(index, index + HOLD_SQL_ID_BATCH_SIZE));\n }\n return result;\n}\n\nexport function containerDocumentPlacementKey(\n placement: ContainerDocumentPlacementKey,\n): string {\n return `${placement.documentId}\\u0000${placement.containerId}`;\n}\nconst placementKey = containerDocumentPlacementKey;\n\n/**\n * Matches the listed (document, container) placements by primary key. An\n * empty list matches nothing: `or()` of no terms is no condition at all, and\n * a delete filtered by it would remove every row.\n */\nexport function placementPairsMatch(\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n documentIdColumn: SQLiteColumn,\n containerIdColumn: SQLiteColumn,\n): SQL {\n return (\n or(\n ...placements.map((placement) =>\n and(\n eq(documentIdColumn, placement.documentId),\n eq(containerIdColumn, placement.containerId),\n ),\n ),\n ) ?? sql`0`\n );\n}\n\nfunction uniquePlacements(\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n): ContainerDocumentPlacementKey[] {\n return Array.from(\n new Map(\n placements.map((placement) => [placementKey(placement), placement]),\n ).values(),\n );\n}\n\nexport async function deleteContainerDocumentTombstoneHoldRows(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n): Promise<void> {\n for (const batch of remoteResetBatches(uniquePlacements(placements))) {\n await tx\n .delete(containerDocumentTombstoneHolds)\n .where(\n placementPairsMatch(\n batch,\n containerDocumentTombstoneHolds.documentId,\n containerDocumentTombstoneHolds.containerId,\n ),\n )\n .run();\n }\n}\n\n/**\n * A local move takes ownership of a document's placement: the intent, not a\n * server listing, now says where it lives, so every hold that was hiding one\n * of its placements is released with the link rewrite.\n */\nexport async function deleteContainerDocumentTombstoneHoldsForDocuments(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<void> {\n for (const batch of batches(documentIds)) {\n await tx\n .delete(containerDocumentTombstoneHolds)\n .where(inArray(containerDocumentTombstoneHolds.documentId, batch))\n .run();\n }\n}\n\n/** Holds on containers whose link rows are being removed locally. */\nexport async function deleteContainerDocumentTombstoneHoldsForContainers(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n for (const batch of batches(containerIds)) {\n await tx\n .delete(containerDocumentTombstoneHolds)\n .where(inArray(containerDocumentTombstoneHolds.containerId, batch))\n .run();\n }\n}\n\n/**\n * The placements among `placements` that exist locally: a link row, or a\n * document projection row whose primary container is the named container.\n * A tombstone for any other placement has nothing to remove or hide, so it\n * is not worth fetching and verifying the document head for.\n */\nexport async function listKnownContainerDocumentPlacementsInTransaction(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n): Promise<ContainerDocumentPlacementKey[]> {\n const known = new Set<string>();\n for (const batch of batches(placements.map((entry) => entry.documentId))) {\n const [linkRows, projectionRows] = await Promise.all([\n tx\n .select({\n containerId: documentContainerProjection.containerId,\n documentId: documentContainerProjection.documentId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, batch)),\n tx\n .select({\n containerId: documentProjection.containerId,\n documentId: documentProjection.documentId,\n })\n .from(documentProjection)\n .where(inArray(documentProjection.documentId, batch)),\n ]);\n for (const row of [...linkRows, ...projectionRows]) {\n if (row.documentId !== null && row.containerId !== null) {\n known.add(\n placementKey({\n containerId: row.containerId,\n documentId: row.documentId,\n }),\n );\n }\n }\n }\n return placements.filter((placement) => known.has(placementKey(placement)));\n}\n\n// Preserve input order when one placement occurs in both attempt modes.\n// A deferred conflict changes only tombstonedAt, never recency or attempts.\nfunction* holdWriteBatches(\n tombstones: ReadonlyArray<HeldContainerDocumentTombstone>,\n) {\n const size = sqliteRowsPerStatement(6);\n let batch: HeldContainerDocumentTombstone[] = [];\n for (const tombstone of tombstones) {\n if (\n batch.length &&\n (batch.length === size ||\n Boolean(batch[0]?.deferred) !== Boolean(tombstone.deferred))\n ) {\n yield batch;\n batch = [];\n }\n batch.push(tombstone);\n }\n if (batch.length) yield batch;\n}\n\n/**\n * Hold listing tombstones whose signed evidence is unavailable. A placement a\n * pending move intent owns is never held: the intent, not the listing, decides\n * where the document lives until it settles (`ProtectPendingTombstones`).\n */\nexport async function holdContainerDocumentTombstonesInTransaction(\n tx: ClientSQLiteTransactionScope,\n tombstones: ReadonlyArray<HeldContainerDocumentTombstone>,\n now: string,\n): Promise<void> {\n const writable = new Set(\n (\n await filterWritableDocumentPlacements(\n tx,\n tombstones.map((tombstone) => ({\n documentId: tombstone.documentId,\n containerIds: [],\n })),\n )\n ).map((input) => input.documentId),\n );\n const applicable = tombstones.filter((tombstone) =>\n writable.has(tombstone.documentId),\n );\n for (const batch of holdWriteBatches(applicable)) {\n const deferred = Boolean(batch[0]?.deferred);\n await tx\n .insert(containerDocumentTombstoneHolds)\n .values(\n batch.map((tombstone) => ({\n containerId: tombstone.containerId,\n documentId: tombstone.documentId,\n tombstonedAt: tombstone.updatedAt,\n hidden: !tombstone.refuted,\n updatedAt: now,\n attempts: deferred ? 0 : 1,\n })),\n )\n .onConflictDoUpdate({\n target: [\n containerDocumentTombstoneHolds.documentId,\n containerDocumentTombstoneHolds.containerId,\n ],\n set: deferred\n ? { tombstonedAt: sql`excluded.tombstoned_at` }\n : {\n tombstonedAt: sql`excluded.tombstoned_at`,\n updatedAt: sql`excluded.updated_at`,\n hidden: sql`min(${containerDocumentTombstoneHolds.hidden}, excluded.hidden)`,\n attempts: sql`${containerDocumentTombstoneHolds.attempts} + 1`,\n },\n })\n .run();\n }\n}\n\n/** Release the holds on placements a listing has re-asserted as linked. */\nexport async function deleteContainerDocumentTombstoneHoldRowsForLinks(\n tx: ClientSQLiteTransactionScope,\n links: ReadonlyArray<{\n readonly containerIds: ReadonlyArray<string>;\n readonly documentId: string;\n }>,\n): Promise<void> {\n await deleteContainerDocumentTombstoneHoldRows(\n tx,\n links.flatMap((link) =>\n link.containerIds.map((containerId) => ({\n containerId,\n documentId: link.documentId,\n })),\n ),\n );\n}\n\nexport interface ContainerDocumentTombstoneHoldRow\n extends ContainerDocumentPlacementKey {\n readonly attempts: number;\n readonly hidden: boolean;\n readonly tombstonedAt: string;\n readonly updatedAt: string;\n}\n\nconst holdRowSelection = {\n attempts: containerDocumentTombstoneHolds.attempts,\n hidden: containerDocumentTombstoneHolds.hidden,\n containerId: containerDocumentTombstoneHolds.containerId,\n documentId: containerDocumentTombstoneHolds.documentId,\n tombstonedAt: containerDocumentTombstoneHolds.tombstonedAt,\n updatedAt: containerDocumentTombstoneHolds.updatedAt,\n};\n\n/** Every hold on the given containers, including visible refuted retries. */\nexport async function listContainerDocumentTombstoneHoldsInTransaction(\n handle: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<ContainerDocumentTombstoneHoldRow[]> {\n const holds: ContainerDocumentTombstoneHoldRow[] = [];\n for (const batch of batches(containerIds)) {\n holds.push(\n ...(await handle\n .select(holdRowSelection)\n .from(containerDocumentTombstoneHolds)\n .where(inArray(containerDocumentTombstoneHolds.containerId, batch))\n .orderBy(\n asc(containerDocumentTombstoneHolds.containerId),\n asc(containerDocumentTombstoneHolds.documentId),\n )),\n );\n }\n return holds;\n}\n\n/** Every hidden hold on the given documents, in any container. */\nexport async function listContainerDocumentTombstoneHoldsForDocumentsInTransaction(\n handle: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<ContainerDocumentTombstoneHoldRow[]> {\n const holds: ContainerDocumentTombstoneHoldRow[] = [];\n for (const batch of batches(documentIds)) {\n holds.push(\n ...(await handle\n .select(holdRowSelection)\n .from(containerDocumentTombstoneHolds)\n .where(\n and(\n inArray(containerDocumentTombstoneHolds.documentId, batch),\n eq(containerDocumentTombstoneHolds.hidden, true),\n ),\n )\n .orderBy(\n asc(containerDocumentTombstoneHolds.documentId),\n asc(containerDocumentTombstoneHolds.containerId),\n )),\n );\n }\n return holds;\n}\n\n/**\n * Split the holds on the given containers into those whose placement is gone\n * (the document was purged, reset, or relinked locally: nothing left to hide,\n * so the hold is dropped) and those still hiding a placement.\n */\nexport async function partitionContainerDocumentTombstoneHolds(\n handle: ClientSQLiteTransactionScope,\n holds: ReadonlyArray<ContainerDocumentTombstoneHoldRow>,\n): Promise<{\n live: ContainerDocumentTombstoneHoldRow[];\n orphaned: ContainerDocumentTombstoneHoldRow[];\n}> {\n const known = new Set(\n (\n await listKnownContainerDocumentPlacementsInTransaction(handle, holds)\n ).map(placementKey),\n );\n return {\n live: holds.filter((hold) => known.has(placementKey(hold))),\n orphaned: holds.filter((hold) => !known.has(placementKey(hold))),\n };\n}\n"]}
@@ -0,0 +1,10 @@
1
+ import { type ClientSQLiteTransactionScope } from "../../../sqlite/sqlitePersistenceRuntime.js";
2
+ import type { ExecSql } from "../../../sqlite/sqlSchema.js";
3
+ import type { ContainerDocumentTombstoneInput } from "../types.js";
4
+ /**
5
+ * Container Contents owns the link rows: it removes the tombstoned placement
6
+ * and, with the head now verified, every remaining local link row the head
7
+ * does not link, inside the tombstone transaction.
8
+ */
9
+ export type ContainerDocumentTombstonePlacementRemoval = (tx: ClientSQLiteTransactionScope, tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>, verifiedLinkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>) => Promise<void>;
10
+ export declare function applyContainerDocumentTombstonesWithExec(execSql: ExecSql, tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>, removePlacementRows: ContainerDocumentTombstonePlacementRemoval): Promise<import("../../../documents/index.js").DocumentSummary[]>;
@@ -4,9 +4,8 @@ import { documentContainerProjection, documentProjection, } from "../../../sqlit
4
4
  import { documents } from "../../../sqlite/schema/documentRecordSchema.js";
5
5
  import { sqliteRowsPerStatement } from "../../../sqlite/sqliteBindBudget.js";
6
6
  import { getClientSQLitePersistenceRuntime, } from "../../../sqlite/sqlitePersistenceRuntime.js";
7
- import { deleteDocumentPlacementRowsInTransaction, deleteUnlinkedDocumentPlacementRowsInTransaction, } from "../../container-contents/documentContainerProjectionPersistence.js";
8
- import { filterWritableDocumentPlacements } from "../../container-contents/documentPlacement.js";
9
7
  import { getLatestTimestamp } from "../../latestTimestamp.js";
8
+ import { filterWritableDocumentPlacements } from "../documentPlacement.js";
10
9
  import { deleteContainerDocumentTombstoneHoldRows } from "./containerDocumentTombstoneHolds.js";
11
10
  import { documentSummaryJoin, documentSummarySelection, mapDocumentSummary, } from "./documentProjectionRows.js";
12
11
  import { repointTombstonedDocumentProjections } from "./tombstoneProjectionRepoint.js";
@@ -33,16 +32,6 @@ function buildContainerDocumentTombstoneState(uniqueTombstones) {
33
32
  verifiedLinkedContainerIdsByDocumentId,
34
33
  };
35
34
  }
36
- /**
37
- * Remove the tombstoned placement and, with the head now verified, every
38
- * remaining local link row the head does not link: those are listing-seeded
39
- * rows, and leaving one would keep showing the document in a container the
40
- * signed link set never named. Rows the head links are kept as they are.
41
- */
42
- async function deleteContainerDocumentTombstoneRows(tx, uniqueTombstones, verifiedLinkedContainerIdsByDocumentId) {
43
- await deleteDocumentPlacementRowsInTransaction(tx, uniqueTombstones);
44
- await deleteUnlinkedDocumentPlacementRowsInTransaction(tx, verifiedLinkedContainerIdsByDocumentId);
45
- }
46
35
  /**
47
36
  * The primary container after a removal: the first remaining local row the
48
37
  * verified head links. A remaining row the head does not link is a
@@ -183,7 +172,7 @@ async function loadChangedDocumentSummaries(tx, localIds) {
183
172
  });
184
173
  return rows.map(mapDocumentSummary);
185
174
  }
186
- export async function applyContainerDocumentTombstonesWithExec(execSql, tombstones) {
175
+ export async function applyContainerDocumentTombstonesWithExec(execSql, tombstones, removePlacementRows) {
187
176
  const uniqueTombstones = dedupeContainerDocumentTombstones(tombstones);
188
177
  if (uniqueTombstones.length === 0) {
189
178
  return [];
@@ -201,7 +190,7 @@ export async function applyContainerDocumentTombstonesWithExec(execSql, tombston
201
190
  const writableIds = new Set(writable.map((input) => input.documentId));
202
191
  const applicable = uniqueTombstones.filter((tombstone) => writableIds.has(tombstone.documentId));
203
192
  const { removedContainerIdsByDocumentId, tombstoneUpdatedAtByDocumentId, verifiedLinkedContainerIdsByDocumentId, } = buildContainerDocumentTombstoneState(applicable);
204
- await deleteContainerDocumentTombstoneRows(tx, applicable, verifiedLinkedContainerIdsByDocumentId);
193
+ await removePlacementRows(tx, applicable, verifiedLinkedContainerIdsByDocumentId);
205
194
  await deleteContainerDocumentTombstoneHoldRows(tx, applicable);
206
195
  const reads = await loadTombstoneRepairReads(tx, [
207
196
  ...removedContainerIdsByDocumentId.keys(),
@@ -1 +1 @@
1
- {"version":3,"file":"containerDocumentTombstones.js","sourceRoot":"","sources":["containerDocumentTombstones.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,6CAA6C,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAElD,OAAO,EACL,wCAAwC,EACxC,gDAAgD,GACjD,MAAM,iEAAiE,CAAC;AACzE,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAC9F,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,wCAAwC,EAAE,MAAM,mCAAmC,CAAC;AAC7F,OAAO,EACL,mBAAmB,EACnB,wBAAwB,EACxB,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,oCAAoC,EAAE,MAAM,8BAA8B,CAAC;AAEpF,SAAS,iCAAiC,CACxC,UAA0D;IAE1D,OAAO,KAAK,CAAC,IAAI,CACf,IAAI,GAAG,CACL,UAAU,CAAC,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CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,IAAI,GAAG,EAAE;aACtE,CAAC,CACH,CAAC;QACJ,CAAC;QACD,MAAM,oCAAoC,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;QACzD,MAAM,eAAe,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAE3D,IAAI,eAAe,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACjC,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,OAAO,4BAA4B,CAAC,EAAE,EAAE,eAAe,CAAC,CAAC;IAC3D,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, asc, desc, eq, inArray, sql } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport {\n documentContainerProjection,\n documentProjection,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport { sqliteRowsPerStatement } from \"../../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n deleteDocumentPlacementRowsInTransaction,\n deleteUnlinkedDocumentPlacementRowsInTransaction,\n} from \"../../container-contents/documentContainerProjectionPersistence\";\nimport { filterWritableDocumentPlacements } from \"../../container-contents/documentPlacement\";\nimport { getLatestTimestamp } from \"../../latestTimestamp\";\nimport type { ContainerDocumentTombstoneInput } from \"../types\";\nimport { deleteContainerDocumentTombstoneHoldRows } from \"./containerDocumentTombstoneHolds\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n mapDocumentSummary,\n} from \"./documentProjectionRows\";\nimport { repointTombstonedDocumentProjections } from \"./tombstoneProjectionRepoint\";\n\nfunction dedupeContainerDocumentTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n): ContainerDocumentTombstoneInput[] {\n return Array.from(\n new Map(\n tombstones.map((tombstone) => [\n `${tombstone.documentId}\\u0000${tombstone.containerId}`,\n tombstone,\n ]),\n ).values(),\n );\n}\n\nfunction buildContainerDocumentTombstoneState(\n uniqueTombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n): {\n removedContainerIdsByDocumentId: Map<string, Set<string>>;\n tombstoneUpdatedAtByDocumentId: Map<string, string>;\n verifiedLinkedContainerIdsByDocumentId: Map<string, ReadonlySet<string>>;\n} {\n const removedContainerIdsByDocumentId = new Map<string, Set<string>>();\n const tombstoneUpdatedAtByDocumentId = new Map<string, string>();\n const verifiedLinkedContainerIdsByDocumentId = new Map<\n string,\n ReadonlySet<string>\n >();\n\n for (const tombstone of uniqueTombstones) {\n verifiedLinkedContainerIdsByDocumentId.set(\n tombstone.documentId,\n new Set(tombstone.linkedContainerIds),\n );\n const removedContainerIds =\n removedContainerIdsByDocumentId.get(tombstone.documentId) ?? new Set();\n removedContainerIds.add(tombstone.containerId);\n removedContainerIdsByDocumentId.set(\n tombstone.documentId,\n removedContainerIds,\n );\n tombstoneUpdatedAtByDocumentId.set(\n tombstone.documentId,\n getLatestTimestamp(\n tombstoneUpdatedAtByDocumentId.get(tombstone.documentId),\n tombstone.updatedAt,\n ),\n );\n }\n\n return {\n removedContainerIdsByDocumentId,\n tombstoneUpdatedAtByDocumentId,\n verifiedLinkedContainerIdsByDocumentId,\n };\n}\n\n/**\n * Remove the tombstoned placement and, with the head now verified, every\n * remaining local link row the head does not link: those are listing-seeded\n * rows, and leaving one would keep showing the document in a container the\n * signed link set never named. Rows the head links are kept as they are.\n */\nasync function deleteContainerDocumentTombstoneRows(\n tx: ClientSQLiteTransactionScope,\n uniqueTombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n verifiedLinkedContainerIdsByDocumentId: ReadonlyMap<\n string,\n ReadonlySet<string>\n >,\n): Promise<void> {\n await deleteDocumentPlacementRowsInTransaction(tx, uniqueTombstones);\n await deleteUnlinkedDocumentPlacementRowsInTransaction(\n tx,\n verifiedLinkedContainerIdsByDocumentId,\n );\n}\n\n/**\n * The primary container after a removal: the first remaining local row the\n * verified head links. A remaining row the head does not link is a\n * listing-seeded row and never becomes the primary, so a listing cannot\n * re-home the document. With no such row the document is unplaced (`null`)\n * and reachable through orphan recovery, rather than pointed at a head\n * container this device may not be able to read.\n */\nfunction selectNextContainerId(\n remainingContainerIds: ReadonlyArray<string>,\n verifiedLinkedContainerIds: ReadonlySet<string>,\n): string | null {\n return (\n remainingContainerIds.find((containerId) =>\n verifiedLinkedContainerIds.has(containerId),\n ) ?? null\n );\n}\n\ninterface TombstoneRepairReads {\n /** Local ids per document id. */\n readonly localIdsByDocumentId: ReadonlyMap<string, string[]>;\n readonly projectionByLocalId: ReadonlyMap<\n string,\n { containerId: string | null; updatedAt: string | null }\n >;\n /** Remaining link containers per document, in container id order. */\n readonly remainingLinksByDocumentId: ReadonlyMap<string, string[]>;\n}\n\nfunction pushGrouped(\n map: Map<string, string[]>,\n key: string,\n value: string,\n): void {\n const values = map.get(key);\n if (values) values.push(value);\n else map.set(key, [value]);\n}\n\n/**\n * Every row the repair reads, for all tombstoned documents at once. The\n * deletes above have already run, and the repair below writes only\n * projection rows of the document it repairs, so reading before any repair\n * sees what each per-document read saw.\n */\nasync function loadTombstoneRepairReads(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<TombstoneRepairReads> {\n const localIdsByDocumentId = new Map<string, string[]>();\n const projectionByLocalId = new Map<\n string,\n { containerId: string | null; updatedAt: string | null }\n >();\n const remainingLinksByDocumentId = new Map<string, string[]>();\n // The app kind binds one value; the rest carry ids.\n const chunkSize = sqliteRowsPerStatement(1, 1);\n for (let offset = 0; offset < documentIds.length; offset += chunkSize) {\n const batch = documentIds.slice(offset, offset + chunkSize);\n const localRows = await tx\n .select({ documentId: documents.documentId, localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n inArray(documents.documentId, batch),\n ),\n );\n for (const row of localRows) {\n if (row.documentId !== null) {\n pushGrouped(localIdsByDocumentId, row.documentId, row.localId);\n }\n }\n const linkRows = await tx\n .select({\n containerId: documentContainerProjection.containerId,\n documentId: documentContainerProjection.documentId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, batch))\n .orderBy(\n asc(documentContainerProjection.documentId),\n asc(documentContainerProjection.containerId),\n );\n for (const row of linkRows) {\n pushGrouped(remainingLinksByDocumentId, row.documentId, row.containerId);\n }\n }\n const localIds = [...localIdsByDocumentId.values()].flat();\n for (let offset = 0; offset < localIds.length; offset += chunkSize) {\n const projectionRows = await tx\n .select({\n localId: documentProjection.localId,\n containerId: documentProjection.containerId,\n updatedAt: documentProjection.updatedAt,\n })\n .from(documentProjection)\n .where(\n inArray(\n documentProjection.localId,\n localIds.slice(offset, offset + chunkSize),\n ),\n );\n for (const row of projectionRows) {\n if (row.localId !== null) {\n projectionByLocalId.set(row.localId, {\n containerId: row.containerId,\n updatedAt: row.updatedAt,\n });\n }\n }\n }\n return {\n localIdsByDocumentId,\n projectionByLocalId,\n remainingLinksByDocumentId,\n };\n}\n\nfunction selectedContainerRepointsForDocumentTombstones(input: {\n documentId: string;\n reads: TombstoneRepairReads;\n removedContainerIds: ReadonlySet<string>;\n tombstoneUpdatedAt: string | undefined;\n verifiedLinkedContainerIds: ReadonlySet<string>;\n}) {\n const { documentId, reads, removedContainerIds, tombstoneUpdatedAt } = input;\n // A server document can own more than one local projection row: identity\n // recovery legitimately rematerializes a second projection for the same\n // documentId before semantic convergence completes. The link delete above is\n // keyed by (documentId, containerId) and the container item view surfaces a\n // document by its primary container_id, so EVERY projection row still pointing\n // at a removed container must be repaired here — resolving a single localId\n // left a duplicate row stranded at the source, keeping a moved document\n // visible in the container it was unlinked from.\n const localIds = reads.localIdsByDocumentId.get(documentId) ?? [];\n // Every projection row whose primary container is tombstoned OR outside the\n // verified link set is repointed: a primary at a listing-seeded row would\n // otherwise keep showing the document in a container the head never named.\n const rowsAtRemovedContainer = localIds.flatMap((localId) => {\n const row = reads.projectionByLocalId.get(localId);\n return row !== undefined &&\n row.containerId !== null &&\n (removedContainerIds.has(row.containerId) ||\n !input.verifiedLinkedContainerIds.has(row.containerId))\n ? [{ localId, updatedAt: row.updatedAt ?? undefined }]\n : [];\n });\n if (rowsAtRemovedContainer.length === 0) {\n return [];\n }\n\n const nextContainerId = selectNextContainerId(\n reads.remainingLinksByDocumentId.get(documentId) ?? [],\n input.verifiedLinkedContainerIds,\n );\n\n return rowsAtRemovedContainer.map((row) => ({\n localId: row.localId,\n containerId: nextContainerId,\n updatedAt: getLatestTimestamp(row.updatedAt, tombstoneUpdatedAt),\n }));\n}\n\nasync function loadChangedDocumentSummaries(\n tx: ClientSQLiteTransactionScope,\n localIds: readonly string[],\n) {\n const rows: Array<\n Parameters<typeof mapDocumentSummary>[0] & {\n updatedAtOrder: string;\n localIdOrder: string;\n }\n > = [];\n // The summary join also binds the app kind.\n const chunkSize = sqliteRowsPerStatement(1, 1);\n for (let offset = 0; offset < localIds.length; offset += chunkSize) {\n rows.push(\n ...(await tx\n .select({\n ...documentSummarySelection,\n // Merge batches in SQLite BINARY order, not JS UTF-16 or locale order.\n // Hex preserves the byte ordering, including non-ASCII local ids.\n updatedAtOrder: sql<string>`hex(${documentProjection.updatedAt})`,\n localIdOrder: sql<string>`hex(${documentProjection.localId})`,\n })\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n inArray(\n documentProjection.localId,\n localIds.slice(offset, offset + chunkSize),\n ),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n )),\n );\n }\n rows.sort((left, right) => {\n const a =\n left.updatedAtOrder === right.updatedAtOrder\n ? left.localIdOrder\n : left.updatedAtOrder;\n const b =\n left.updatedAtOrder === right.updatedAtOrder\n ? right.localIdOrder\n : right.updatedAtOrder;\n return a > b ? -1 : a < b ? 1 : 0;\n });\n return rows.map(mapDocumentSummary);\n}\n\nexport async function applyContainerDocumentTombstonesWithExec(\n execSql: ExecSql,\n tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n) {\n const uniqueTombstones = dedupeContainerDocumentTombstones(tombstones);\n if (uniqueTombstones.length === 0) {\n return [];\n }\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n\n return db.transaction(async (tx) => {\n // Besides the pending-intent guard, the verified head must not be older\n // than local document state: a lagging or replayed head must never\n // delete rows a newer listing or settled move wrote (`CheckEpoch`).\n const writable = await filterWritableDocumentPlacements(\n tx,\n uniqueTombstones.map((tombstone) => ({\n accessEpoch: tombstone.accessEpoch,\n documentId: tombstone.documentId,\n containerIds: [],\n })),\n );\n const writableIds = new Set(writable.map((input) => input.documentId));\n const applicable = uniqueTombstones.filter((tombstone) =>\n writableIds.has(tombstone.documentId),\n );\n const {\n removedContainerIdsByDocumentId,\n tombstoneUpdatedAtByDocumentId,\n verifiedLinkedContainerIdsByDocumentId,\n } = buildContainerDocumentTombstoneState(applicable);\n await deleteContainerDocumentTombstoneRows(\n tx,\n applicable,\n verifiedLinkedContainerIdsByDocumentId,\n );\n await deleteContainerDocumentTombstoneHoldRows(tx, applicable);\n\n const reads = await loadTombstoneRepairReads(tx, [\n ...removedContainerIdsByDocumentId.keys(),\n ]);\n const repoints = [];\n for (const [\n documentId,\n removedContainerIds,\n ] of removedContainerIdsByDocumentId) {\n repoints.push(\n ...selectedContainerRepointsForDocumentTombstones({\n documentId,\n reads,\n removedContainerIds,\n tombstoneUpdatedAt: tombstoneUpdatedAtByDocumentId.get(documentId),\n verifiedLinkedContainerIds:\n verifiedLinkedContainerIdsByDocumentId.get(documentId) ?? new Set(),\n }),\n );\n }\n await repointTombstonedDocumentProjections(tx, repoints);\n const changedLocalIds = repoints.map((row) => row.localId);\n\n if (changedLocalIds.length === 0) {\n return [];\n }\n\n return loadChangedDocumentSummaries(tx, changedLocalIds);\n });\n}\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G,CAAC,SAAS,CAAC,UAAU,CAAC,CACtC,CAAC;QACF,MAAM,EACJ,+BAA+B,EAC/B,8BAA8B,EAC9B,sCAAsC,GACvC,GAAG,oCAAoC,CAAC,UAAU,CAAC,CAAC;QACrD,MAAM,mBAAmB,CACvB,EAAE,EACF,UAAU,EACV,sCAAsC,CACvC,CAAC;QACF,MAAM,wCAAwC,CAAC,EAAE,EAAE,UAAU,CAAC,CAAC;QAE/D,MAAM,KAAK,GAAG,MAAM,wBAAwB,CAAC,EAAE,EAAE;YAC/C,GAAG,+BAA+B,CAAC,IAAI,EAAE;SAC1C,CAAC,CAAC;QACH,MAAM,QAAQ,GAAG,EAAE,CAAC;QACpB,KAAK,MAAM,CACT,UAAU,EACV,mBAAmB,EACpB,IAAI,+BAA+B,EAAE,CAAC;YACrC,QAAQ,CAAC,IAAI,CACX,GAAG,8CAA8C,CAAC;gBAChD,UAAU;gBACV,KAAK;gBACL,mBAAmB;gBACnB,kBAAkB,EAAE,8BAA8B,CAAC,GAAG,CAAC,UAAU,CAAC;gBAClE,0BAA0B,EACxB,sCAAsC,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,IAAI,GAAG,EAAE;aACtE,CAAC,CACH,CAAC;QACJ,CAAC;QACD,MAAM,oCAAoC,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;QACzD,MAAM,eAAe,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAE3D,IAAI,eAAe,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACjC,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,OAAO,4BAA4B,CAAC,EAAE,EAAE,eAAe,CAAC,CAAC;IAC3D,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, asc, desc, eq, inArray, sql } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport {\n documentContainerProjection,\n documentProjection,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport { sqliteRowsPerStatement } from \"../../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport { getLatestTimestamp } from \"../../latestTimestamp\";\nimport { filterWritableDocumentPlacements } from \"../documentPlacement\";\nimport type { ContainerDocumentTombstoneInput } from \"../types\";\nimport { deleteContainerDocumentTombstoneHoldRows } from \"./containerDocumentTombstoneHolds\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n mapDocumentSummary,\n} from \"./documentProjectionRows\";\nimport { repointTombstonedDocumentProjections } from \"./tombstoneProjectionRepoint\";\n\nfunction dedupeContainerDocumentTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n): ContainerDocumentTombstoneInput[] {\n return Array.from(\n new Map(\n tombstones.map((tombstone) => [\n `${tombstone.documentId}\\u0000${tombstone.containerId}`,\n tombstone,\n ]),\n ).values(),\n );\n}\n\nfunction buildContainerDocumentTombstoneState(\n uniqueTombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n): {\n removedContainerIdsByDocumentId: Map<string, Set<string>>;\n tombstoneUpdatedAtByDocumentId: Map<string, string>;\n verifiedLinkedContainerIdsByDocumentId: Map<string, ReadonlySet<string>>;\n} {\n const removedContainerIdsByDocumentId = new Map<string, Set<string>>();\n const tombstoneUpdatedAtByDocumentId = new Map<string, string>();\n const verifiedLinkedContainerIdsByDocumentId = new Map<\n string,\n ReadonlySet<string>\n >();\n\n for (const tombstone of uniqueTombstones) {\n verifiedLinkedContainerIdsByDocumentId.set(\n tombstone.documentId,\n new Set(tombstone.linkedContainerIds),\n );\n const removedContainerIds =\n removedContainerIdsByDocumentId.get(tombstone.documentId) ?? new Set();\n removedContainerIds.add(tombstone.containerId);\n removedContainerIdsByDocumentId.set(\n tombstone.documentId,\n removedContainerIds,\n );\n tombstoneUpdatedAtByDocumentId.set(\n tombstone.documentId,\n getLatestTimestamp(\n tombstoneUpdatedAtByDocumentId.get(tombstone.documentId),\n tombstone.updatedAt,\n ),\n );\n }\n\n return {\n removedContainerIdsByDocumentId,\n tombstoneUpdatedAtByDocumentId,\n verifiedLinkedContainerIdsByDocumentId,\n };\n}\n\n/**\n * Container Contents owns the link rows: it removes the tombstoned placement\n * and, with the head now verified, every remaining local link row the head\n * does not link, inside the tombstone transaction.\n */\nexport type ContainerDocumentTombstonePlacementRemoval = (\n tx: ClientSQLiteTransactionScope,\n tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n verifiedLinkedContainerIdsByDocumentId: ReadonlyMap<\n string,\n ReadonlySet<string>\n >,\n) => Promise<void>;\n\n/**\n * The primary container after a removal: the first remaining local row the\n * verified head links. A remaining row the head does not link is a\n * listing-seeded row and never becomes the primary, so a listing cannot\n * re-home the document. With no such row the document is unplaced (`null`)\n * and reachable through orphan recovery, rather than pointed at a head\n * container this device may not be able to read.\n */\nfunction selectNextContainerId(\n remainingContainerIds: ReadonlyArray<string>,\n verifiedLinkedContainerIds: ReadonlySet<string>,\n): string | null {\n return (\n remainingContainerIds.find((containerId) =>\n verifiedLinkedContainerIds.has(containerId),\n ) ?? null\n );\n}\n\ninterface TombstoneRepairReads {\n /** Local ids per document id. */\n readonly localIdsByDocumentId: ReadonlyMap<string, string[]>;\n readonly projectionByLocalId: ReadonlyMap<\n string,\n { containerId: string | null; updatedAt: string | null }\n >;\n /** Remaining link containers per document, in container id order. */\n readonly remainingLinksByDocumentId: ReadonlyMap<string, string[]>;\n}\n\nfunction pushGrouped(\n map: Map<string, string[]>,\n key: string,\n value: string,\n): void {\n const values = map.get(key);\n if (values) values.push(value);\n else map.set(key, [value]);\n}\n\n/**\n * Every row the repair reads, for all tombstoned documents at once. The\n * deletes above have already run, and the repair below writes only\n * projection rows of the document it repairs, so reading before any repair\n * sees what each per-document read saw.\n */\nasync function loadTombstoneRepairReads(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<TombstoneRepairReads> {\n const localIdsByDocumentId = new Map<string, string[]>();\n const projectionByLocalId = new Map<\n string,\n { containerId: string | null; updatedAt: string | null }\n >();\n const remainingLinksByDocumentId = new Map<string, string[]>();\n // The app kind binds one value; the rest carry ids.\n const chunkSize = sqliteRowsPerStatement(1, 1);\n for (let offset = 0; offset < documentIds.length; offset += chunkSize) {\n const batch = documentIds.slice(offset, offset + chunkSize);\n const localRows = await tx\n .select({ documentId: documents.documentId, localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n inArray(documents.documentId, batch),\n ),\n );\n for (const row of localRows) {\n if (row.documentId !== null) {\n pushGrouped(localIdsByDocumentId, row.documentId, row.localId);\n }\n }\n const linkRows = await tx\n .select({\n containerId: documentContainerProjection.containerId,\n documentId: documentContainerProjection.documentId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, batch))\n .orderBy(\n asc(documentContainerProjection.documentId),\n asc(documentContainerProjection.containerId),\n );\n for (const row of linkRows) {\n pushGrouped(remainingLinksByDocumentId, row.documentId, row.containerId);\n }\n }\n const localIds = [...localIdsByDocumentId.values()].flat();\n for (let offset = 0; offset < localIds.length; offset += chunkSize) {\n const projectionRows = await tx\n .select({\n localId: documentProjection.localId,\n containerId: documentProjection.containerId,\n updatedAt: documentProjection.updatedAt,\n })\n .from(documentProjection)\n .where(\n inArray(\n documentProjection.localId,\n localIds.slice(offset, offset + chunkSize),\n ),\n );\n for (const row of projectionRows) {\n if (row.localId !== null) {\n projectionByLocalId.set(row.localId, {\n containerId: row.containerId,\n updatedAt: row.updatedAt,\n });\n }\n }\n }\n return {\n localIdsByDocumentId,\n projectionByLocalId,\n remainingLinksByDocumentId,\n };\n}\n\nfunction selectedContainerRepointsForDocumentTombstones(input: {\n documentId: string;\n reads: TombstoneRepairReads;\n removedContainerIds: ReadonlySet<string>;\n tombstoneUpdatedAt: string | undefined;\n verifiedLinkedContainerIds: ReadonlySet<string>;\n}) {\n const { documentId, reads, removedContainerIds, tombstoneUpdatedAt } = input;\n // A server document can own more than one local projection row: identity\n // recovery legitimately rematerializes a second projection for the same\n // documentId before semantic convergence completes. The link delete above is\n // keyed by (documentId, containerId) and the container item view surfaces a\n // document by its primary container_id, so EVERY projection row still pointing\n // at a removed container must be repaired here — resolving a single localId\n // left a duplicate row stranded at the source, keeping a moved document\n // visible in the container it was unlinked from.\n const localIds = reads.localIdsByDocumentId.get(documentId) ?? [];\n // Every projection row whose primary container is tombstoned OR outside the\n // verified link set is repointed: a primary at a listing-seeded row would\n // otherwise keep showing the document in a container the head never named.\n const rowsAtRemovedContainer = localIds.flatMap((localId) => {\n const row = reads.projectionByLocalId.get(localId);\n return row !== undefined &&\n row.containerId !== null &&\n (removedContainerIds.has(row.containerId) ||\n !input.verifiedLinkedContainerIds.has(row.containerId))\n ? [{ localId, updatedAt: row.updatedAt ?? undefined }]\n : [];\n });\n if (rowsAtRemovedContainer.length === 0) {\n return [];\n }\n\n const nextContainerId = selectNextContainerId(\n reads.remainingLinksByDocumentId.get(documentId) ?? [],\n input.verifiedLinkedContainerIds,\n );\n\n return rowsAtRemovedContainer.map((row) => ({\n localId: row.localId,\n containerId: nextContainerId,\n updatedAt: getLatestTimestamp(row.updatedAt, tombstoneUpdatedAt),\n }));\n}\n\nasync function loadChangedDocumentSummaries(\n tx: ClientSQLiteTransactionScope,\n localIds: readonly string[],\n) {\n const rows: Array<\n Parameters<typeof mapDocumentSummary>[0] & {\n updatedAtOrder: string;\n localIdOrder: string;\n }\n > = [];\n // The summary join also binds the app kind.\n const chunkSize = sqliteRowsPerStatement(1, 1);\n for (let offset = 0; offset < localIds.length; offset += chunkSize) {\n rows.push(\n ...(await tx\n .select({\n ...documentSummarySelection,\n // Merge batches in SQLite BINARY order, not JS UTF-16 or locale order.\n // Hex preserves the byte ordering, including non-ASCII local ids.\n updatedAtOrder: sql<string>`hex(${documentProjection.updatedAt})`,\n localIdOrder: sql<string>`hex(${documentProjection.localId})`,\n })\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n inArray(\n documentProjection.localId,\n localIds.slice(offset, offset + chunkSize),\n ),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n )),\n );\n }\n rows.sort((left, right) => {\n const a =\n left.updatedAtOrder === right.updatedAtOrder\n ? left.localIdOrder\n : left.updatedAtOrder;\n const b =\n left.updatedAtOrder === right.updatedAtOrder\n ? right.localIdOrder\n : right.updatedAtOrder;\n return a > b ? -1 : a < b ? 1 : 0;\n });\n return rows.map(mapDocumentSummary);\n}\n\nexport async function applyContainerDocumentTombstonesWithExec(\n execSql: ExecSql,\n tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n removePlacementRows: ContainerDocumentTombstonePlacementRemoval,\n) {\n const uniqueTombstones = dedupeContainerDocumentTombstones(tombstones);\n if (uniqueTombstones.length === 0) {\n return [];\n }\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n\n return db.transaction(async (tx) => {\n // Besides the pending-intent guard, the verified head must not be older\n // than local document state: a lagging or replayed head must never\n // delete rows a newer listing or settled move wrote (`CheckEpoch`).\n const writable = await filterWritableDocumentPlacements(\n tx,\n uniqueTombstones.map((tombstone) => ({\n accessEpoch: tombstone.accessEpoch,\n documentId: tombstone.documentId,\n containerIds: [],\n })),\n );\n const writableIds = new Set(writable.map((input) => input.documentId));\n const applicable = uniqueTombstones.filter((tombstone) =>\n writableIds.has(tombstone.documentId),\n );\n const {\n removedContainerIdsByDocumentId,\n tombstoneUpdatedAtByDocumentId,\n verifiedLinkedContainerIdsByDocumentId,\n } = buildContainerDocumentTombstoneState(applicable);\n await removePlacementRows(\n tx,\n applicable,\n verifiedLinkedContainerIdsByDocumentId,\n );\n await deleteContainerDocumentTombstoneHoldRows(tx, applicable);\n\n const reads = await loadTombstoneRepairReads(tx, [\n ...removedContainerIdsByDocumentId.keys(),\n ]);\n const repoints = [];\n for (const [\n documentId,\n removedContainerIds,\n ] of removedContainerIdsByDocumentId) {\n repoints.push(\n ...selectedContainerRepointsForDocumentTombstones({\n documentId,\n reads,\n removedContainerIds,\n tombstoneUpdatedAt: tombstoneUpdatedAtByDocumentId.get(documentId),\n verifiedLinkedContainerIds:\n verifiedLinkedContainerIdsByDocumentId.get(documentId) ?? new Set(),\n }),\n );\n }\n await repointTombstonedDocumentProjections(tx, repoints);\n const changedLocalIds = repoints.map((row) => row.localId);\n\n if (changedLocalIds.length === 0) {\n return [];\n }\n\n return loadChangedDocumentSummaries(tx, changedLocalIds);\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { DEFAULT_DOCUMENT_ACCESS_EPOCH } from "../../../documents/documentConstants.js";
2
- import { loadDocumentMovePlacement, } from "../../container-contents/documentPlacement.js";
2
+ import { loadDocumentMovePlacement, } from "../documentPlacement.js";
3
3
  import { resolvePersistedAccessStateHash } from "./documentRuntimeState.js";
4
4
  export async function resolveDiscoveredDocumentPlacement(tx, existing, input) {
5
5
  return discoveredDocumentPlacement(existing, input, await loadDocumentMovePlacement(tx, input.documentId));
@@ -1 +1 @@
1
- {"version":3,"file":"discoveredDocumentPlacement.js","sourceRoot":"","sources":["discoveredDocumentPlacement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AAGrF,OAAO,EAEL,yBAAyB,GAC1B,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,+BAA+B,EAAE,MAAM,wBAAwB,CAAC;AAEzE,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,EAAgC,EAChC,QAAqC,EACrC,KAA8B;IAE9B,OAAO,2BAA2B,CAChC,QAAQ,EACR,KAAK,EACL,MAAM,yBAAyB,CAAC,EAAE,EAAE,KAAK,CAAC,UAAU,CAAC,CACtD,CAAC;AACJ,CAA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POCH } from \"../../../documents/documentConstants\";\nimport type { DiscoveredDocumentInput } from \"../../../documents/documentSummary\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type DocumentMovePlacement,\n loadDocumentMovePlacement,\n} from \"../../container-contents/documentPlacement\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { resolvePersistedAccessStateHash } from \"./documentRuntimeState\";\n\nexport async function resolveDiscoveredDocumentPlacement(\n tx: ClientSQLiteTransactionScope,\n existing: StoredDocumentRecord | null,\n input: DiscoveredDocumentInput,\n) {\n return discoveredDocumentPlacement(\n existing,\n input,\n await loadDocumentMovePlacement(tx, input.documentId),\n );\n}\n\n/** The placement discovery writes, given the document's pending move intent. */\nexport function discoveredDocumentPlacement(\n existing: StoredDocumentRecord | null,\n input: DiscoveredDocumentInput,\n intent: DocumentMovePlacement | undefined,\n) {\n const stale = existing !== null && existing.accessEpoch > input.accessEpoch;\n const accessEpoch = Math.max(\n existing?.accessEpoch ?? DEFAULT_DOCUMENT_ACCESS_EPOCH,\n input.accessEpoch,\n );\n const pendingContainerId =\n intent?.intentType === \"document.link\"\n ? (existing?.containerId ?? intent.targetContainerId)\n : intent?.targetContainerId;\n const containerId =\n pendingContainerId ??\n (stale\n ? existing.containerId\n : existing?.containerId &&\n input.linkedContainerIds.includes(existing.containerId)\n ? existing.containerId\n : (input.linkedContainerIds.find((id) => id === input.containerId) ??\n input.linkedContainerIds[0] ??\n input.containerId));\n return {\n accessEpoch,\n containerId,\n accessStateHash: resolvePersistedAccessStateHash(existing, {\n accessEpoch,\n accessStateHash: stale ? existing.accessStateHash : input.accessStateHash,\n documentId: input.documentId,\n }),\n };\n}\n"]}
1
+ {"version":3,"file":"discoveredDocumentPlacement.js","sourceRoot":"","sources":["discoveredDocumentPlacement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AAGrF,OAAO,EAEL,yBAAyB,GAC1B,MAA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AAW;QACX,WAAW;QACX,eAAe,EAAE,+BAA+B,CAAC,QAAQ,EAAE;YACzD,WAAW;YACX,eAAe,EAAE,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC,eAAe;YACzE,UAAU,EAAE,KAAK,CAAC,UAAU;SAC7B,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import { DEFAULT_DOCUMENT_ACCESS_EPOCH } from \"../../../documents/documentConstants\";\nimport type { DiscoveredDocumentInput } from \"../../../documents/documentSummary\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type DocumentMovePlacement,\n loadDocumentMovePlacement,\n} from \"../documentPlacement\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { resolvePersistedAccessStateHash } from \"./documentRuntimeState\";\n\nexport async function resolveDiscoveredDocumentPlacement(\n tx: ClientSQLiteTransactionScope,\n existing: StoredDocumentRecord | null,\n input: DiscoveredDocumentInput,\n) {\n return discoveredDocumentPlacement(\n existing,\n input,\n await loadDocumentMovePlacement(tx, input.documentId),\n );\n}\n\n/** The placement discovery writes, given the document's pending move intent. */\nexport function discoveredDocumentPlacement(\n existing: StoredDocumentRecord | null,\n input: DiscoveredDocumentInput,\n intent: DocumentMovePlacement | undefined,\n) {\n const stale = existing !== null && existing.accessEpoch > input.accessEpoch;\n const accessEpoch = Math.max(\n existing?.accessEpoch ?? DEFAULT_DOCUMENT_ACCESS_EPOCH,\n input.accessEpoch,\n );\n const pendingContainerId =\n intent?.intentType === \"document.link\"\n ? (existing?.containerId ?? intent.targetContainerId)\n : intent?.targetContainerId;\n const containerId =\n pendingContainerId ??\n (stale\n ? existing.containerId\n : existing?.containerId &&\n input.linkedContainerIds.includes(existing.containerId)\n ? existing.containerId\n : (input.linkedContainerIds.find((id) => id === input.containerId) ??\n input.linkedContainerIds[0] ??\n input.containerId));\n return {\n accessEpoch,\n containerId,\n accessStateHash: resolvePersistedAccessStateHash(existing, {\n accessEpoch,\n accessStateHash: stale ? existing.accessStateHash : input.accessStateHash,\n documentId: input.documentId,\n }),\n };\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { KeyingVerificationError } from "../../../../internal/crypto/index.js";
2
2
  import { DEFAULT_DOCUMENT_KIND, DOCUMENTS_APP_KIND, } from "../../../documents/documentConstants.js";
3
- import { loadDocumentMovePlacements, } from "../../container-contents/documentPlacement.js";
4
3
  import { hasDocumentPurgeCheckpointInTransaction, listPurgedDocumentIdsInTransaction, } from "../../keyingCheckpoints/documentPurgeCheckpointPersistence.js";
4
+ import { loadDocumentMovePlacements, } from "../documentPlacement.js";
5
5
  import { DocumentRecordRepository } from "../records/index.js";
6
6
  import { discoveredDocumentPlacement, resolveDiscoveredDocumentPlacement, } from "./discoveredDocumentPlacement.js";
7
7
  import { toDocumentSummary } from "./documentProjectionRows.js";
@@ -1 +1 @@
1
- {"version":3,"file":"discoveredDocumentUpsert.js","sourceRoot":"","sources":["discoveredDocumentUpsert.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,sCAAsC,CAAC;AAO9C,OAAO,EAEL,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,uCAAuC,EACvC,kCAAkC,GACnC,MAAM,4DAA4D,CAAC;AACpE,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAEtD,OAAO,EACL,2BAA2B,EAC3B,kCAAkC,GACnC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EACL,yBAAyB,EACzB,4BAA4B,EAC5B,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,oCAAoC,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE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GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;QAC9B,EAAE;KACH,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,CAAC,IAAI;QAAE,MAAM,iBAAiB,EAAE,CAAC;IAC3D,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;QAC5B,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS;YAAE,OAAO,MAAM,CAAC,OAAO,CAAC;QACrD,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAC1C,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;QACpE,OAAO,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IAC5D,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n DEFAULT_DOCUMENT_KIND,\n DOCUMENTS_APP_KIND,\n} from \"../../../documents/documentConstants\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../../documents/documentSummary\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n type DocumentMovePlacement,\n loadDocumentMovePlacements,\n} from \"../../container-contents/documentPlacement\";\nimport {\n hasDocumentPurgeCheckpointInTransaction,\n listPurgedDocumentIdsInTransaction,\n} from \"../../keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport {\n discoveredDocumentPlacement,\n resolveDiscoveredDocumentPlacement,\n} from \"./discoveredDocumentPlacement\";\nimport { toDocumentSummary } from \"./documentProjectionRows\";\nimport {\n documentSaveTimestampFrom,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n saveDocumentRowsBatch,\n} from \"./documentRows\";\nimport { resolvePersistedDocumentRuntimeState } from \"./documentRuntimeState\";\nimport { loadPendingCreateSummary } from \"./pendingCreateAdoption\";\nimport {\n loadStoredDocumentState,\n loadStoredDocumentStates,\n type StoredDocumentState,\n} from \"./rowQueryPersistence\";\n\nconst DISCOVERED_DOCUMENT_PLACEHOLDER_TITLE = \"Syncing document...\";\n\nfunction purgedDocumentError(): KeyingVerificationError {\n return new KeyingVerificationError(\n \"rollback\",\n \"Document discovery targets a permanently purged document\",\n );\n}\n\nfunction fenceSkippedError(): Error {\n return new Error(\"Document recovery generation changed during discovery\");\n}\n\nfunction nextDiscoveredDocument(\n localId: string,\n input: DiscoveredDocumentInput,\n existingDocument: StoredDocumentRecord | null,\n placement: ReturnType<typeof discoveredDocumentPlacement>,\n): StoredDocumentRecord {\n return {\n id: localId,\n documentId: input.documentId,\n documentKind: existingDocument?.documentKind ?? DEFAULT_DOCUMENT_KIND,\n text: existingDocument?.text ?? \"\",\n title: existingDocument?.title ?? DISCOVERED_DOCUMENT_PLACEHOLDER_TITLE,\n snapshotEndVersion: existingDocument?.snapshotEndVersion ?? \"\",\n recoveryGeneration: existingDocument?.recoveryGeneration ?? 0,\n ...placement,\n effectiveAccessLevel:\n input.effectiveAccessLevel ??\n existingDocument?.effectiveAccessLevel ??\n null,\n ...resolvePersistedDocumentRuntimeState(existingDocument, {\n accessEpoch: placement.accessEpoch,\n documentId: input.documentId,\n }),\n };\n}\n\n/** One discovered document, read and written on its own (the per-row path). */\nasync function upsertDiscoveredDocumentWithExec(\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary> {\n if (await hasDocumentPurgeCheckpointInTransaction(tx, input.documentId)) {\n throw purgedDocumentError();\n }\n const existingLocalId = await new DocumentRecordRepository(\n execSql,\n ).findLocalIdByDocumentId(DOCUMENTS_APP_KIND, input.documentId);\n const localId = existingLocalId ?? input.documentId;\n const pendingLocalId = pendingCreates.get(input.documentId);\n if (!existingLocalId && pendingLocalId) {\n const pending = await loadPendingCreateSummary(execSql, pendingLocalId);\n if (!pending) throw new Error(\"Pending create projection is unavailable\");\n return pending;\n }\n const existingDocument =\n (await loadStoredDocumentState(execSql, localId))?.record ?? null;\n const placement = await resolveDiscoveredDocumentPlacement(\n tx,\n existingDocument,\n input,\n );\n const nextDocument = nextDiscoveredDocument(\n localId,\n input,\n existingDocument,\n placement,\n );\n const updatedAt = await resolveDocumentSaveTimestamp({\n document: nextDocument,\n options: existingDocument ? undefined : { updatedAt: input.createdAt },\n tx,\n });\n if (!(await saveDocumentRows({ document: nextDocument, tx, updatedAt }))) {\n throw fenceSkippedError();\n }\n return toDocumentSummary(nextDocument, updatedAt);\n}\n\nasync function upsertDiscoveredDocumentsPerRow(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary[]> {\n const summaries: DocumentSummary[] = [];\n for (const input of inputs) {\n summaries.push(\n await upsertDiscoveredDocumentWithExec(\n execSql,\n input,\n pendingCreates,\n tx,\n ),\n );\n }\n return summaries;\n}\n\ntype DiscoveryTarget =\n | { kind: \"pending\"; summary: DocumentSummary }\n | { input: DiscoveredDocumentInput; kind: \"write\"; localId: string };\n\n/**\n * Resolves every input to its pending-create summary or its target local id,\n * in input order, so the first purged or unavailable input throws exactly as\n * the per-row walk would. Returns null when one input's write could change\n * another input's reads, which only the per-row walk handles.\n */\nasync function resolveDiscoveryTargets(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DiscoveryTarget[] | null> {\n const documentIds = inputs.map((input) => input.documentId);\n const purged = await listPurgedDocumentIdsInTransaction(tx, documentIds);\n const existingLocalIds = await new DocumentRecordRepository(\n execSql,\n ).findLocalIdsByDocumentIds(DOCUMENTS_APP_KIND, documentIds);\n const targets: DiscoveryTarget[] = [];\n const pendingLocalIds = new Set<string>();\n for (const input of inputs) {\n if (purged.has(input.documentId)) throw purgedDocumentError();\n const existingLocalId = existingLocalIds.get(input.documentId);\n const pendingLocalId = pendingCreates.get(input.documentId);\n if (!existingLocalId && pendingLocalId) {\n const pending = await loadPendingCreateSummary(execSql, pendingLocalId);\n if (!pending) throw new Error(\"Pending create projection is unavailable\");\n pendingLocalIds.add(pendingLocalId);\n targets.push({ kind: \"pending\", summary: pending });\n continue;\n }\n targets.push({\n input,\n kind: \"write\",\n localId: existingLocalId ?? input.documentId,\n });\n }\n const writeLocalIds = targets.flatMap((target) =>\n target.kind === \"write\" ? [target.localId] : [],\n );\n const independent =\n new Set(writeLocalIds).size === writeLocalIds.length &&\n !writeLocalIds.some((localId) => pendingLocalIds.has(localId));\n return independent ? targets : null;\n}\n\n/**\n * Whether writing each target leaves every other target's reads unchanged: a\n * stored row at a target local id that carries a different document id would\n * be re-pointed by its write, which another input's lookup could have read.\n */\nfunction targetsReadDisjointRows(\n targets: ReadonlyArray<DiscoveryTarget>,\n states: ReadonlyMap<string, StoredDocumentState>,\n): boolean {\n return targets.every(\n (target) =>\n target.kind !== \"write\" ||\n (states.get(target.localId)?.record.documentId ??\n target.input.documentId) === target.input.documentId,\n );\n}\n\nfunction plannedDiscoveryWrite(\n target: Extract<DiscoveryTarget, { kind: \"write\" }>,\n state: StoredDocumentState | undefined,\n intent: DocumentMovePlacement | undefined,\n) {\n const existingDocument = state?.record ?? null;\n const document = nextDiscoveredDocument(\n target.localId,\n target.input,\n existingDocument,\n discoveredDocumentPlacement(existingDocument, target.input, intent),\n );\n // The joined state read is the row and projection the per-row walk reads\n // again for its timestamp; nothing earlier in this transaction writes it.\n const updatedAt = state\n ? documentSaveTimestampFrom(\n {\n projection: state.projection,\n snapshotEndVersion: state.record.snapshotEndVersion,\n },\n document,\n )\n : target.input.createdAt;\n return { document, updatedAt };\n}\n\n/**\n * Discovery as set statements: one read per table for every input, then\n * multi-row upserts. Inputs whose rows could interact (a repeated document\n * id, a shared local id, or a row another input would re-point) keep the\n * per-row walk, which reads each input after the previous one's writes.\n */\nexport async function upsertDiscoveredDocumentsInTransaction(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary[]> {\n const documentIds = inputs.map((input) => input.documentId);\n if (new Set(documentIds).size !== documentIds.length) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const targets = await resolveDiscoveryTargets(\n execSql,\n inputs,\n pendingCreates,\n tx,\n );\n if (!targets) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const writes = targets.flatMap((target) =>\n target.kind === \"write\" ? [target] : [],\n );\n if (writes.length === 0) {\n return targets.flatMap((target) =>\n target.kind === \"pending\" ? [target.summary] : [],\n );\n }\n const states = await loadStoredDocumentStates(\n execSql,\n writes.map((target) => target.localId),\n );\n if (!targetsReadDisjointRows(targets, states)) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const intents = await loadDocumentMovePlacements(\n tx,\n writes.map((target) => target.input.documentId),\n );\n const planned = new Map(\n writes.map((target) => [\n target.localId,\n plannedDiscoveryWrite(\n target,\n states.get(target.localId),\n intents.get(target.input.documentId),\n ),\n ]),\n );\n const saved = await saveDocumentRowsBatch({\n entries: [...planned.values()],\n tx,\n });\n if (saved.size !== planned.size) throw fenceSkippedError();\n return targets.map((target) => {\n if (target.kind === \"pending\") return target.summary;\n const write = planned.get(target.localId);\n if (!write) throw new Error(\"Discovered document write is missing\");\n return toDocumentSummary(write.document, write.updatedAt);\n });\n}\n"]}
1
+ {"version":3,"file":"discoveredDocumentUpsert.js","sourceRoot":"","sources":["discoveredDocumentUpsert.ts"],"names":[],"mappings":"AAAA,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IND,\n} from \"../../../documents/documentConstants\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../../documents/documentSummary\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n hasDocumentPurgeCheckpointInTransaction,\n listPurgedDocumentIdsInTransaction,\n} from \"../../keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport {\n type DocumentMovePlacement,\n loadDocumentMovePlacements,\n} from \"../documentPlacement\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport {\n discoveredDocumentPlacement,\n resolveDiscoveredDocumentPlacement,\n} from \"./discoveredDocumentPlacement\";\nimport { toDocumentSummary } from \"./documentProjectionRows\";\nimport {\n documentSaveTimestampFrom,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n saveDocumentRowsBatch,\n} from \"./documentRows\";\nimport { resolvePersistedDocumentRuntimeState } from \"./documentRuntimeState\";\nimport { loadPendingCreateSummary } from \"./pendingCreateAdoption\";\nimport {\n loadStoredDocumentState,\n loadStoredDocumentStates,\n type StoredDocumentState,\n} from \"./rowQueryPersistence\";\n\nconst DISCOVERED_DOCUMENT_PLACEHOLDER_TITLE = \"Syncing document...\";\n\nfunction purgedDocumentError(): KeyingVerificationError {\n return new KeyingVerificationError(\n \"rollback\",\n \"Document discovery targets a permanently purged document\",\n );\n}\n\nfunction fenceSkippedError(): Error {\n return new Error(\"Document recovery generation changed during discovery\");\n}\n\nfunction nextDiscoveredDocument(\n localId: string,\n input: DiscoveredDocumentInput,\n existingDocument: StoredDocumentRecord | null,\n placement: ReturnType<typeof discoveredDocumentPlacement>,\n): StoredDocumentRecord {\n return {\n id: localId,\n documentId: input.documentId,\n documentKind: existingDocument?.documentKind ?? DEFAULT_DOCUMENT_KIND,\n text: existingDocument?.text ?? \"\",\n title: existingDocument?.title ?? DISCOVERED_DOCUMENT_PLACEHOLDER_TITLE,\n snapshotEndVersion: existingDocument?.snapshotEndVersion ?? \"\",\n recoveryGeneration: existingDocument?.recoveryGeneration ?? 0,\n ...placement,\n effectiveAccessLevel:\n input.effectiveAccessLevel ??\n existingDocument?.effectiveAccessLevel ??\n null,\n ...resolvePersistedDocumentRuntimeState(existingDocument, {\n accessEpoch: placement.accessEpoch,\n documentId: input.documentId,\n }),\n };\n}\n\n/** One discovered document, read and written on its own (the per-row path). */\nasync function upsertDiscoveredDocumentWithExec(\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary> {\n if (await hasDocumentPurgeCheckpointInTransaction(tx, input.documentId)) {\n throw purgedDocumentError();\n }\n const existingLocalId = await new DocumentRecordRepository(\n execSql,\n ).findLocalIdByDocumentId(DOCUMENTS_APP_KIND, input.documentId);\n const localId = existingLocalId ?? input.documentId;\n const pendingLocalId = pendingCreates.get(input.documentId);\n if (!existingLocalId && pendingLocalId) {\n const pending = await loadPendingCreateSummary(execSql, pendingLocalId);\n if (!pending) throw new Error(\"Pending create projection is unavailable\");\n return pending;\n }\n const existingDocument =\n (await loadStoredDocumentState(execSql, localId))?.record ?? null;\n const placement = await resolveDiscoveredDocumentPlacement(\n tx,\n existingDocument,\n input,\n );\n const nextDocument = nextDiscoveredDocument(\n localId,\n input,\n existingDocument,\n placement,\n );\n const updatedAt = await resolveDocumentSaveTimestamp({\n document: nextDocument,\n options: existingDocument ? undefined : { updatedAt: input.createdAt },\n tx,\n });\n if (!(await saveDocumentRows({ document: nextDocument, tx, updatedAt }))) {\n throw fenceSkippedError();\n }\n return toDocumentSummary(nextDocument, updatedAt);\n}\n\nasync function upsertDiscoveredDocumentsPerRow(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary[]> {\n const summaries: DocumentSummary[] = [];\n for (const input of inputs) {\n summaries.push(\n await upsertDiscoveredDocumentWithExec(\n execSql,\n input,\n pendingCreates,\n tx,\n ),\n );\n }\n return summaries;\n}\n\ntype DiscoveryTarget =\n | { kind: \"pending\"; summary: DocumentSummary }\n | { input: DiscoveredDocumentInput; kind: \"write\"; localId: string };\n\n/**\n * Resolves every input to its pending-create summary or its target local id,\n * in input order, so the first purged or unavailable input throws exactly as\n * the per-row walk would. Returns null when one input's write could change\n * another input's reads, which only the per-row walk handles.\n */\nasync function resolveDiscoveryTargets(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DiscoveryTarget[] | null> {\n const documentIds = inputs.map((input) => input.documentId);\n const purged = await listPurgedDocumentIdsInTransaction(tx, documentIds);\n const existingLocalIds = await new DocumentRecordRepository(\n execSql,\n ).findLocalIdsByDocumentIds(DOCUMENTS_APP_KIND, documentIds);\n const targets: DiscoveryTarget[] = [];\n const pendingLocalIds = new Set<string>();\n for (const input of inputs) {\n if (purged.has(input.documentId)) throw purgedDocumentError();\n const existingLocalId = existingLocalIds.get(input.documentId);\n const pendingLocalId = pendingCreates.get(input.documentId);\n if (!existingLocalId && pendingLocalId) {\n const pending = await loadPendingCreateSummary(execSql, pendingLocalId);\n if (!pending) throw new Error(\"Pending create projection is unavailable\");\n pendingLocalIds.add(pendingLocalId);\n targets.push({ kind: \"pending\", summary: pending });\n continue;\n }\n targets.push({\n input,\n kind: \"write\",\n localId: existingLocalId ?? input.documentId,\n });\n }\n const writeLocalIds = targets.flatMap((target) =>\n target.kind === \"write\" ? [target.localId] : [],\n );\n const independent =\n new Set(writeLocalIds).size === writeLocalIds.length &&\n !writeLocalIds.some((localId) => pendingLocalIds.has(localId));\n return independent ? targets : null;\n}\n\n/**\n * Whether writing each target leaves every other target's reads unchanged: a\n * stored row at a target local id that carries a different document id would\n * be re-pointed by its write, which another input's lookup could have read.\n */\nfunction targetsReadDisjointRows(\n targets: ReadonlyArray<DiscoveryTarget>,\n states: ReadonlyMap<string, StoredDocumentState>,\n): boolean {\n return targets.every(\n (target) =>\n target.kind !== \"write\" ||\n (states.get(target.localId)?.record.documentId ??\n target.input.documentId) === target.input.documentId,\n );\n}\n\nfunction plannedDiscoveryWrite(\n target: Extract<DiscoveryTarget, { kind: \"write\" }>,\n state: StoredDocumentState | undefined,\n intent: DocumentMovePlacement | undefined,\n) {\n const existingDocument = state?.record ?? null;\n const document = nextDiscoveredDocument(\n target.localId,\n target.input,\n existingDocument,\n discoveredDocumentPlacement(existingDocument, target.input, intent),\n );\n // The joined state read is the row and projection the per-row walk reads\n // again for its timestamp; nothing earlier in this transaction writes it.\n const updatedAt = state\n ? documentSaveTimestampFrom(\n {\n projection: state.projection,\n snapshotEndVersion: state.record.snapshotEndVersion,\n },\n document,\n )\n : target.input.createdAt;\n return { document, updatedAt };\n}\n\n/**\n * Discovery as set statements: one read per table for every input, then\n * multi-row upserts. Inputs whose rows could interact (a repeated document\n * id, a shared local id, or a row another input would re-point) keep the\n * per-row walk, which reads each input after the previous one's writes.\n */\nexport async function upsertDiscoveredDocumentsInTransaction(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary[]> {\n const documentIds = inputs.map((input) => input.documentId);\n if (new Set(documentIds).size !== documentIds.length) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const targets = await resolveDiscoveryTargets(\n execSql,\n inputs,\n pendingCreates,\n tx,\n );\n if (!targets) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const writes = targets.flatMap((target) =>\n target.kind === \"write\" ? [target] : [],\n );\n if (writes.length === 0) {\n return targets.flatMap((target) =>\n target.kind === \"pending\" ? [target.summary] : [],\n );\n }\n const states = await loadStoredDocumentStates(\n execSql,\n writes.map((target) => target.localId),\n );\n if (!targetsReadDisjointRows(targets, states)) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const intents = await loadDocumentMovePlacements(\n tx,\n writes.map((target) => target.input.documentId),\n );\n const planned = new Map(\n writes.map((target) => [\n target.localId,\n plannedDiscoveryWrite(\n target,\n states.get(target.localId),\n intents.get(target.input.documentId),\n ),\n ]),\n );\n const saved = await saveDocumentRowsBatch({\n entries: [...planned.values()],\n tx,\n });\n if (saved.size !== planned.size) throw fenceSkippedError();\n return targets.map((target) => {\n if (target.kind === \"pending\") return target.summary;\n const write = planned.get(target.localId);\n if (!write) throw new Error(\"Discovered document write is missing\");\n return toDocumentSummary(write.document, write.updatedAt);\n });\n}\n"]}
@@ -1,8 +1,7 @@
1
1
  import { and, eq } from "drizzle-orm";
2
- import { inLocalIntentLane, LOCAL_INTENT_LANES, localIntents, localIntentTables, } from "../../sqlite/schema/index.js";
2
+ import { CONTAINER_CREATE_INTENT_TYPE, inLocalIntentLane, LOCAL_INTENT_LANES, localIntents, localIntentTables, } from "../../sqlite/schema/index.js";
3
3
  import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
4
4
  import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
5
- import { CONTAINER_CREATE_INTENT_TYPE } from "./containerContentsPersistenceTypes.js";
6
5
  /**
7
6
  * A folder whose create has not settled can carry a listed identity that
8
7
  * adoption has not verified, or has refused; nothing is created inside it
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pendingContainerCreate.js","sourceRoot":"","sources":["pendingContainerCreate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,4BAA4B,EAC5B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,GAClB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEvE;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,OAAgB,EAChB,WAAmB;IAEnB,MAAM,eAAe,CAAC,OAAO,EAAE,iBAAiB,CAAC,CAAC;IAClD,MAAM,EAAE,EAAE,EAAE,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;IAC1D,MAAM,CAAC,OAAO,CAAC,GAAG,MAAM,EAAE;SACvB,MAAM,CAAC,EAAE,WAAW,EAAE,YAAY,CAAC,SAAS,EAAE,CAAC;SAC/C,IAAI,CAAC,YAAY,CAAC;SAClB,KAAK,CACJ,GAAG,CACD,iBAAiB,CAAC,kBAAkB,CAAC,eAAe,CAAC,EACrD,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,WAAW,CAAC,EACvC,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,4BAA4B,CAAC,EACzD,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,SAAS,CAAC,CACvC,CACF;SACA,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,OAAO,OAAO,KAAK,SAAS,CAAC;AAC/B,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport {\n CONTAINER_CREATE_INTENT_TYPE,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n localIntentTables,\n} from \"../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\n\n/**\n * A folder whose create has not settled can carry a listed identity that\n * adoption has not verified, or has refused; nothing is created inside it\n * until the create settles.\n */\nexport async function isContainerCreatePending(\n execSql: ExecSql,\n containerId: string,\n): Promise<boolean> {\n await ensureSqlTables(execSql, localIntentTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [pending] = await db\n .select({ containerId: localIntents.subjectId })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, containerId),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.syncStatus, \"pending\"),\n ),\n )\n .limit(1);\n return pending !== undefined;\n}\n"]}
@@ -177,4 +177,6 @@ export class PrincipalPolicyBundleRepository {
177
177
  await runtime.transaction(body, { behavior: "immediate" });
178
178
  }
179
179
  }
180
+ /** The bundle store Keying Verification reads, opened on one executor. */
181
+ export const openPrincipalPolicyBundleReader = (execSql) => new PrincipalPolicyBundleRepository(execSql);
180
182
  //# sourceMappingURL=principalPolicyBundleRepository.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyBundleRepository.js","sourceRoot":"","sources":["principalPolicyBundleRepository.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAAE,8BAA8B,EAAE,MAAM,oDAAoD,CAAC;AACpG,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEvE,OAAO,EAEL,oCAAoC,GACrC,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EACL,+CAA+C,EAI/C,2DAA2D,GAC5D,MAAM,iDAAiD,CAAC;AACzD,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAC9B,wCAAwC,EACxC,2BAA2B,EAC3B,uCAAuC,GACxC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,oBAAoB,EACpB,qCAAqC,GACtC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE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AK,CAAC,OAAO,CAAC,CAAC;QACrE,MAAM,eAAe,CAAC,IAAI,CAAC,OAAO,EAAE;YAClC,GAAG,qBAAqB;YACxB,GAAG,sBAAsB;SAC1B,CAAC,CAAC;QACH,MAAM,IAAI,CAAC,YAAY,CACrB,CAAC,EAAE,EAAE,EAAE,CACL,2DAA2D,CACzD,EAAE,EACF,KAAK,EACL,IAAI,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CACzB,EACH,KAAK,CAAC,YAAY,CACnB,CAAC;IACJ,CAAC;IAED,8EAA8E;IACtE,KAAK,CAAC,YAAY,CACxB,IAAyD,EACzD,YAAyC;QAEzC,MAAM,OAAO,GAAG,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAChE,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,OAAO,CAAC,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE;gBACnD,QAAQ,EAAE,WAAW;aACtB,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF","sourcesContent":["import type {\n PrincipalPolicyCheckpoint,\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { asc, desc } from \"drizzle-orm\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalHistoryEvidenceTables } from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport {\n principalPolicyBundles,\n principalPolicyTables,\n} from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalGrantRetirements } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n type PrincipalKeyEnvelopeCandidate,\n selectPrincipalKeyEnvelopeCandidates,\n} from \"../principalKeys/principalKeyEnvelopeCandidates\";\nimport { selectHeldPrincipalState } from \"./heldPrincipalState\";\nimport {\n assertLocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyBundle,\n type LocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyStore,\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction,\n} from \"./locallyAcknowledgedPrincipalPolicyPersistence\";\nimport {\n parseSelectedPrincipalPolicyBundle,\n principalPolicyBundleSelection,\n retainPrincipalPolicyBundleInTransaction,\n wherePrincipalPolicyCurrent,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport {\n assertReferenceShape,\n selectReferencedPrincipalPolicyBundle,\n} from \"./principalPolicyReferencePersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\nimport {\n assertVerifiedPrincipalPolicyBundles,\n persistVerifiedPrincipalPolicyBundlesInTransaction,\n type VerifiedPrincipalPolicyBundleEntry,\n} from \"./verifiedPrincipalPolicyBundlePersistence\";\n\n/**\n * The cached principal policy bundles, current heads and retained epochs, and\n * the member key envelopes they carry, bound to one executor and clock. Each\n * method ensures its tables; each writer runs its own immediate transaction\n * and silently skips a commit its `stillCurrent` refuses. Work inside a\n * caller's transaction takes the locked handle per call through the\n * `*InTransaction` functions instead.\n */\nexport class PrincipalPolicyBundleRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n async ensurePrincipalPolicyTables(): Promise<void> {\n await ensureSqlTables(this.execSql, principalPolicyTables);\n }\n\n async loadPrincipalPolicyBundle(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row ? parseSelectedPrincipalPolicyBundle(row) : null;\n }\n\n /** Current heads first, then retained bundles. */\n async loadAllPrincipalPolicyBundles(): Promise<\n PrincipalPolicyBundleResponse[]\n > {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .orderBy(\n desc(principalPolicyBundles.isCurrent),\n asc(principalPolicyBundles.principalType),\n asc(principalPolicyBundles.principalId),\n asc(principalPolicyBundles.stateHash),\n );\n const bundles: PrincipalPolicyBundleResponse[] = [];\n for (const row of rows) {\n const bundle = parseSelectedPrincipalPolicyBundle(row);\n if (bundle) bundles.push(bundle);\n }\n return bundles;\n }\n\n async loadPrincipalPolicyStateHash(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<string | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select({ stateHash: principalPolicyBundles.stateHash })\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row?.stateHash ?? null;\n }\n\n /** The newest stored bundle containing exactly `reference`, never a guess. */\n async loadPrincipalPolicyBundleForReference(\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectReferencedPrincipalPolicyBundle(db, reference, checkpoint);\n }\n\n /**\n * A signed state this device stored for exactly `head`: history evidence it\n * verified or acknowledged, or a cached policy bundle chain. It is untrusted;\n * the caller verifies it as it would a served copy, and a miss only means the\n * server sends one.\n */\n async loadHeldPrincipalState(\n head: ReferencedPrincipalHead,\n ): Promise<PrincipalStateResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectHeldPrincipalState(db, head);\n }\n\n /**\n * Untrusted encrypted key candidates, never authorization evidence. The actual\n * private key must open the requested recipient wrap; the projection verifier\n * separately checks the signed KEK material identity and all policy authority.\n * Read only envelopes for the requested fingerprints, never signed histories.\n */\n async loadPrincipalKeyEnvelopeCandidates(\n fingerprints: readonly string[],\n ): Promise<PrincipalKeyEnvelopeCandidate[]> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...principalHistoryEvidenceTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectPrincipalKeyEnvelopeCandidates(db, fingerprints);\n }\n\n async savePrincipalPolicyBundle(\n bundle: PrincipalPolicyBundleResponse,\n organizationId: string,\n options?: { stillCurrent?: (() => boolean) | undefined } | undefined,\n ): Promise<void> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n writePrincipalPolicyBundleInTransaction(\n tx,\n bundle,\n this.now().toISOString(),\n organizationId,\n ),\n options?.stillCurrent,\n );\n }\n\n /**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\n async persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n }): Promise<void> {\n await assertVerifiedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n persistVerifiedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /**\n * Retains a just-verified epoch without promoting it to the mutable head.\n * `updatedAt` stays explicit: callers stamp a whole retention walk at once.\n */\n async retainVerifiedPrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly organizationId?: string | undefined;\n readonly policy: VerifiedPrincipalPolicy;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n }): Promise<void> {\n await assertBundleMatchesVerifiedPolicy(input);\n await this.ensurePrincipalPolicyTables();\n await this.runImmediate(\n (tx) =>\n retainPrincipalPolicyBundleInTransaction(\n tx,\n input.bundle,\n input.updatedAt,\n input.organizationId,\n ),\n input.stillCurrent,\n );\n }\n\n /** Atomically pins and caches exact full policy bundles acknowledged by the API. */\n persistLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"current\",\n });\n }\n\n persistLocallyAcknowledgedPrincipalPolicyBundle(\n input: LocallyAcknowledgedPrincipalPolicyBundle & {\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n return this.persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input],\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n }\n\n /**\n * Seed a provisioning acknowledgement without making genesis current again.\n * The cache writer still checks ownership, equal-version forks and retained\n * same-hash bundle integrity, and preserves any newer cached policy head.\n */\n seedLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"genesis\",\n });\n }\n\n retainLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles & {\n readonly retiredContainers?:\n | AcknowledgedPrincipalGrantRetirements\n | undefined;\n },\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"history\",\n });\n }\n\n private async storeLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyStore & {\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n await assertLocallyAcknowledgedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /** Guarded when `stillCurrent` is given; a refused commit is not an error. */\n private async runImmediate(\n body: (tx: ClientSQLiteTransactionScope) => Promise<void>,\n stillCurrent: (() => boolean) | undefined,\n ): Promise<void> {\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n if (stillCurrent) {\n await runtime.guardedTransaction(body, stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(body, { behavior: \"immediate\" });\n }\n}\n"]}
1
+ {"version":3,"file":"principalPolicyBundleRepository.js","sourceRoot":"","sources":["principalPolicyBundleRepository.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAAE,8BAA8B,EAAE,MAAM,oDAAoD,CAAC;AACpG,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEvE,OAAO,EAEL,oCAAoC,GACrC,MAAM,iDAAiD,CAAC;AACzD,OA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olicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { asc, desc } from \"drizzle-orm\";\nimport type { OpenPrincipalPolicyBundleReader } from \"../../keyingProjectionVerification/types\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalHistoryEvidenceTables } from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport {\n principalPolicyBundles,\n principalPolicyTables,\n} from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalGrantRetirements } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n type PrincipalKeyEnvelopeCandidate,\n selectPrincipalKeyEnvelopeCandidates,\n} from \"../principalKeys/principalKeyEnvelopeCandidates\";\nimport { selectHeldPrincipalState } from \"./heldPrincipalState\";\nimport {\n assertLocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyBundle,\n type LocallyAcknowledgedPrincipalPolicyBundles,\n type LocallyAcknowledgedPrincipalPolicyStore,\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction,\n} from \"./locallyAcknowledgedPrincipalPolicyPersistence\";\nimport {\n parseSelectedPrincipalPolicyBundle,\n principalPolicyBundleSelection,\n retainPrincipalPolicyBundleInTransaction,\n wherePrincipalPolicyCurrent,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport {\n assertReferenceShape,\n selectReferencedPrincipalPolicyBundle,\n} from \"./principalPolicyReferencePersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\nimport {\n assertVerifiedPrincipalPolicyBundles,\n persistVerifiedPrincipalPolicyBundlesInTransaction,\n type VerifiedPrincipalPolicyBundleEntry,\n} from \"./verifiedPrincipalPolicyBundlePersistence\";\n\n/**\n * The cached principal policy bundles, current heads and retained epochs, and\n * the member key envelopes they carry, bound to one executor and clock. Each\n * method ensures its tables; each writer runs its own immediate transaction\n * and silently skips a commit its `stillCurrent` refuses. Work inside a\n * caller's transaction takes the locked handle per call through the\n * `*InTransaction` functions instead.\n */\nexport class PrincipalPolicyBundleRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n async ensurePrincipalPolicyTables(): Promise<void> {\n await ensureSqlTables(this.execSql, principalPolicyTables);\n }\n\n async loadPrincipalPolicyBundle(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row ? parseSelectedPrincipalPolicyBundle(row) : null;\n }\n\n /** Current heads first, then retained bundles. */\n async loadAllPrincipalPolicyBundles(): Promise<\n PrincipalPolicyBundleResponse[]\n > {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select(principalPolicyBundleSelection)\n .from(principalPolicyBundles)\n .orderBy(\n desc(principalPolicyBundles.isCurrent),\n asc(principalPolicyBundles.principalType),\n asc(principalPolicyBundles.principalId),\n asc(principalPolicyBundles.stateHash),\n );\n const bundles: PrincipalPolicyBundleResponse[] = [];\n for (const row of rows) {\n const bundle = parseSelectedPrincipalPolicyBundle(row);\n if (bundle) bundles.push(bundle);\n }\n return bundles;\n }\n\n async loadPrincipalPolicyStateHash(\n principalType: PrincipalStateResponse[\"principalType\"],\n principalId: string,\n ): Promise<string | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const [row] = await db\n .select({ stateHash: principalPolicyBundles.stateHash })\n .from(principalPolicyBundles)\n .where(wherePrincipalPolicyCurrent({ principalType, principalId }))\n .limit(1);\n return row?.stateHash ?? null;\n }\n\n /** The newest stored bundle containing exactly `reference`, never a guess. */\n async loadPrincipalPolicyBundleForReference(\n reference: ReferencedPrincipalHead,\n checkpoint: PrincipalPolicyCheckpoint | null,\n ): Promise<PrincipalPolicyBundleResponse | null> {\n assertReferenceShape(reference);\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectReferencedPrincipalPolicyBundle(db, reference, checkpoint);\n }\n\n /**\n * A signed state this device stored for exactly `head`: history evidence it\n * verified or acknowledged, or a cached policy bundle chain. It is untrusted;\n * the caller verifies it as it would a served copy, and a miss only means the\n * server sends one.\n */\n async loadHeldPrincipalState(\n head: ReferencedPrincipalHead,\n ): Promise<PrincipalStateResponse | null> {\n await this.ensurePrincipalPolicyTables();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectHeldPrincipalState(db, head);\n }\n\n /**\n * Untrusted encrypted key candidates, never authorization evidence. The actual\n * private key must open the requested recipient wrap; the projection verifier\n * separately checks the signed KEK material identity and all policy authority.\n * Read only envelopes for the requested fingerprints, never signed histories.\n */\n async loadPrincipalKeyEnvelopeCandidates(\n fingerprints: readonly string[],\n ): Promise<PrincipalKeyEnvelopeCandidate[]> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...principalHistoryEvidenceTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectPrincipalKeyEnvelopeCandidates(db, fingerprints);\n }\n\n async savePrincipalPolicyBundle(\n bundle: PrincipalPolicyBundleResponse,\n organizationId: string,\n options?: { stillCurrent?: (() => boolean) | undefined } | undefined,\n ): Promise<void> {\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n writePrincipalPolicyBundleInTransaction(\n tx,\n bundle,\n this.now().toISOString(),\n organizationId,\n ),\n options?.stillCurrent,\n );\n }\n\n /**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\n async persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n }): Promise<void> {\n await assertVerifiedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n persistVerifiedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /**\n * Retains a just-verified epoch without promoting it to the mutable head.\n * `updatedAt` stays explicit: callers stamp a whole retention walk at once.\n */\n async retainVerifiedPrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly organizationId?: string | undefined;\n readonly policy: VerifiedPrincipalPolicy;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n }): Promise<void> {\n await assertBundleMatchesVerifiedPolicy(input);\n await this.ensurePrincipalPolicyTables();\n await this.runImmediate(\n (tx) =>\n retainPrincipalPolicyBundleInTransaction(\n tx,\n input.bundle,\n input.updatedAt,\n input.organizationId,\n ),\n input.stillCurrent,\n );\n }\n\n /** Atomically pins and caches exact full policy bundles acknowledged by the API. */\n persistLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"current\",\n });\n }\n\n persistLocallyAcknowledgedPrincipalPolicyBundle(\n input: LocallyAcknowledgedPrincipalPolicyBundle & {\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n return this.persistLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input],\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n }\n\n /**\n * Seed a provisioning acknowledgement without making genesis current again.\n * The cache writer still checks ownership, equal-version forks and retained\n * same-hash bundle integrity, and preserves any newer cached policy head.\n */\n seedLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles,\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"genesis\",\n });\n }\n\n retainLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyBundles & {\n readonly retiredContainers?:\n | AcknowledgedPrincipalGrantRetirements\n | undefined;\n },\n ): Promise<void> {\n return this.storeLocallyAcknowledgedPrincipalPolicyBundles({\n ...input,\n placement: \"history\",\n });\n }\n\n private async storeLocallyAcknowledgedPrincipalPolicyBundles(\n input: LocallyAcknowledgedPrincipalPolicyStore & {\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n ): Promise<void> {\n await assertLocallyAcknowledgedPrincipalPolicyBundles(input.entries);\n await ensureSqlTables(this.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n await this.runImmediate(\n (tx) =>\n storeLocallyAcknowledgedPrincipalPolicyBundlesInTransaction(\n tx,\n input,\n this.now().toISOString(),\n ),\n input.stillCurrent,\n );\n }\n\n /** Guarded when `stillCurrent` is given; a refused commit is not an error. */\n private async runImmediate(\n body: (tx: ClientSQLiteTransactionScope) => Promise<void>,\n stillCurrent: (() => boolean) | undefined,\n ): Promise<void> {\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n if (stillCurrent) {\n await runtime.guardedTransaction(body, stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(body, { behavior: \"immediate\" });\n }\n}\n\n/** The bundle store Keying Verification reads, opened on one executor. */\nexport const openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader =\n (execSql) => new PrincipalPolicyBundleRepository(execSql);\n"]}
@@ -3,7 +3,7 @@ import { containerDocumentTombstoneHolds } from "./containerDocumentTombstoneHol
3
3
  import { organizationReadModelTables } from "./organizationReadModelTableRegistry.js";
4
4
  export { containerHydrationTombstones, containers, dormantContainerMetadata, dormantMetadataSweepRequests, supersededContainerBindings, } from "./containerSchema.js";
5
5
  export { documentAttachmentBlobProjection, documentPendingAttachments, } from "./documentAttachmentSchema.js";
6
- export { inContainerIntentLanes, inLocalIntentLane, LOCAL_INTENT_LANES, LOCAL_INTENT_SUBJECT, localIntents, } from "./localIntentSchema.js";
6
+ export { CONTAINER_CREATE_INTENT_TYPE, inContainerIntentLanes, inLocalIntentLane, LOCAL_INTENT_LANES, LOCAL_INTENT_SUBJECT, localIntents, } from "./localIntentSchema.js";
7
7
  export { principalPolicyBundleReferences, principalPolicyBundles, principalPolicyCheckpoints, } from "./principalPolicySchema.js";
8
8
  export { securityIncidents } from "./securityIncidentSchema.js";
9
9
  export { containerDocumentTombstoneHolds, organizationReadModelTables };
@@ -25,7 +25,7 @@ import { trustedUserIdentityPins, trustedUserIdentityPinTables, } from "./truste
25
25
  import { verifiedAccessManifestBundles, verifiedManifestBundleTables, } from "./verifiedManifestBundleSchema.js";
26
26
  export { containerHydrationTombstones, containers, dormantContainerMetadata, dormantMetadataSweepRequests, supersededContainerBindings, } from "./containerSchema.js";
27
27
  export { documentAttachmentBlobProjection, documentPendingAttachments, } from "./documentAttachmentSchema.js";
28
- export { inContainerIntentLanes, inLocalIntentLane, LOCAL_INTENT_LANES, LOCAL_INTENT_SUBJECT, localIntents, } from "./localIntentSchema.js";
28
+ export { CONTAINER_CREATE_INTENT_TYPE, inContainerIntentLanes, inLocalIntentLane, LOCAL_INTENT_LANES, LOCAL_INTENT_SUBJECT, localIntents, } from "./localIntentSchema.js";
29
29
  export { principalPolicyBundleReferences, principalPolicyBundles, principalPolicyCheckpoints, } from "./principalPolicySchema.js";
30
30
  export { securityIncidents } from "./securityIncidentSchema.js";
31
31
  export { containerDocumentTombstoneHolds, organizationReadModelTables };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAuB,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,+BAA+B,EAAE,MAAM,wCAAwC,CAAC;AACzF,OAAO,EACL,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAC;AAC/E,OAAO,EAAE,yBAAyB,EAAE,MAAM,iCAAiC,CAAC;AAC5E,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,EACjC,kBAAkB,EAClB,wBAAwB,GACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EACL,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,qBAAqB,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,mBAAmB,MAAM,yCAAyC,CAAC;AAC/E,OAAO,EACL,iCAAiC,EACjC,2BAA2B,GAC5B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,KAAK,qBAAqB,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,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chema\";\nimport { containerDocumentTombstoneHolds } from \"./containerDocumentTombstoneHoldSchema\";\nimport {\n containerSQLiteSchema,\n containerTableSchemas,\n} from \"./containerSchema\";\nimport {\n containerSyncWatermarks,\n containerSyncWatermarkTables,\n} from \"./containerSyncWatermarkSchema\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"./documentAttachmentSchema\";\nimport { documentOrphanBlobReclaims } from \"./documentOrphanBlobReclaimSchema\";\nimport { documentIntentLinkTargets } from \"./documentPlacementIntentSchema\";\nimport {\n documentContainerProjection,\n documentContainerProjectionTables,\n documentProjection,\n documentProjectionTables,\n} from \"./documentProjectionSchema\";\nimport { documents, documentTables } from \"./documentRecordSchema\";\nimport {\n accessManifestCheckpoints,\n documentPurgeCheckpoints,\n keyingCheckpointTables,\n} from \"./keyingCheckpointSchema\";\nimport { localIntents } from \"./localIntentSchema\";\nimport * as organizationDataUsage from \"./organizationDataUsageSchema\";\nimport { organizationFounders } from \"./organizationFounderSchema\";\nimport * as provisioningAttempt from \"./organizationProvisioningAttemptSchema\";\nimport {\n organizationReadModelSQLiteSchema,\n organizationReadModelTables,\n} from \"./organizationReadModelTableRegistry\";\nimport * as organizationSyncPause from \"./organizationSyncPauseSchema\";\nimport { principalGrantRetirements } from \"./principalGrantRetirementSchema\";\nimport {\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n} from \"./principalHistoryEvidenceSchema\";\nimport { principalKeyEnvelopeArchive } from \"./principalHistoryRetentionSchema\";\nimport { principalHistoryStages } from \"./principalHistoryStageSchema\";\nimport {\n principalMutationJournal,\n principalMutationJournalTables,\n} from \"./principalMutationJournalSchema\";\nimport {\n principalPolicyBundleReferences,\n principalPolicyBundles,\n principalPolicyCheckpoints,\n principalPolicyCheckpointTable,\n principalPolicyTables,\n} from \"./principalPolicySchema\";\nimport {\n securityIncidents,\n securityIncidentTable,\n} from \"./securityIncidentSchema\";\nimport {\n trustedUserIdentityPins,\n trustedUserIdentityPinTables,\n} from \"./trustedUserIdentityPinSchema\";\nimport {\n verifiedAccessManifestBundles,\n verifiedManifestBundleTables,\n} from \"./verifiedManifestBundleSchema\";\n\nexport {\n containerHydrationTombstones,\n containers,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n supersededContainerBindings,\n} from \"./containerSchema\";\nexport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"./documentAttachmentSchema\";\nexport {\n inContainerIntentLanes,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n LOCAL_INTENT_SUBJECT,\n localIntents,\n} from \"./localIntentSchema\";\nexport {\n principalPolicyBundleReferences,\n principalPolicyBundles,\n principalPolicyCheckpoints,\n} from \"./principalPolicySchema\";\nexport { securityIncidents } from \"./securityIncidentSchema\";\nexport { containerDocumentTombstoneHolds, organizationReadModelTables };\n\nconst securityIncidentTables: ReadonlyArray<SqlTableSchema> = [\n securityIncidentTable,\n];\n\nexport const containerTables = containerTableSchemas;\n\nexport const localIntentTables: ReadonlyArray<SqlTableSchema> = [\n defineSqlTableSchema(localIntents),\n];\n\nexport const documentPlacementIntentTables: ReadonlyArray<SqlTableSchema> = [\n ...localIntentTables,\n defineSqlTableSchema(documentIntentLinkTargets),\n];\n\nexport const clientSqlTables: ReadonlyArray<SqlTableSchema> = [\n ...principalMutationJournalTables,\n ...documentTables,\n ...principalPolicyTables,\n ...keyingCheckpointTables.filter((t) => t !== principalPolicyCheckpointTable),\n ...verifiedManifestBundleTables,\n ...trustedUserIdentityPinTables,\n ...securityIncidentTables,\n ...containerTables,\n ...documentContainerProjectionTables,\n ...documentPlacementIntentTables,\n ...documentProjectionTables,\n ...containerSyncWatermarkTables,\n ...organizationReadModelTables,\n ...organizationDataUsage.organizationDataUsageTables,\n ...provisioningAttempt.organizationProvisioningAttemptTables,\n ...organizationSyncPause.organizationSyncPauseTables,\n];\n\nexport const clientSQLiteSchema = {\n principalKeyEnvelopeArchive,\n principalMutationJournal,\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n principalHistoryStages,\n organizationFounders,\n principalGrantRetirements,\n documents,\n principalPolicyBundles,\n principalPolicyBundleReferences,\n accessManifestCheckpoints,\n documentPurgeCheckpoints,\n principalPolicyCheckpoints,\n verifiedAccessManifestBundles,\n trustedUserIdentityPins,\n securityIncidents,\n ...containerSQLiteSchema,\n documentContainerProjection,\n localIntents,\n documentIntentLinkTargets,\n documentProjection,\n documentPendingAttachments,\n documentAttachmentBlobProjection,\n documentOrphanBlobReclaims: documentOrphanBlobReclaims,\n containerSyncWatermarks,\n ...organizationReadModelSQLiteSchema,\n ...organizationDataUsage.organizationDataUsageSQLiteSchema,\n ...provisioningAttempt.organizationProvisioningAttemptSQLiteSchema,\n ...organizationSyncPause.organizationSyncPauseSQLiteSchema,\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAuB,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,+BAA+B,EAAE,MAAM,wCAAwC,CAAC;AACzF,OAAO,EACL,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAC;AAC/E,OAAO,EAAE,yBAAyB,EAAE,MAAM,iCAAiC,CAAC;AAC5E,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,EACjC,kBAAkB,EAClB,wBAAwB,GACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EACL,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,YAAY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C7B,uBAAuB;IACvB,iBAAiB;IACjB,GAAG,qBAAqB;IACxB,2BAA2B;IAC3B,YAAY;IACZ,yBAAyB;IACzB,kBAAkB;IAClB,0BAA0B;IAC1B,gCAAgC;IAChC,0BAA0B,EAAE,0BAA0B;IACtD,uBAAuB;IACvB,GAAG,iCAAiC;IACpC,GAAG,qBAAqB,CAAC,iCAAiC;IAC1D,GAAG,mBAAmB,CAAC,2CAA2C;IAClE,GAAG,qBAAqB,CAAC,iCAAiC;CAC3D,CAAC","sourcesContent":["import { defineSqlTableSchema, type SqlTableSchema } from \"../sqlTableSchema\";\nimport { containerDocumentTombstoneHolds } from \"./containerDocumentTombstoneHoldSchema\";\nimport {\n containerSQLiteSchema,\n containerTableSchemas,\n} from \"./containerSchema\";\nimport {\n containerSyncWatermarks,\n containerSyncWatermarkTables,\n} from \"./containerSyncWatermarkSchema\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"./documentAttachmentSchema\";\nimport { documentOrphanBlobReclaims } from \"./documentOrphanBlobReclaimSchema\";\nimport { documentIntentLinkTargets } from \"./documentPlacementIntentSchema\";\nimport {\n documentContainerProjection,\n documentContainerProjectionTables,\n documentProjection,\n documentProjectionTables,\n} from \"./documentProjectionSchema\";\nimport { documents, documentTables } from \"./documentRecordSchema\";\nimport {\n accessManifestCheckpoints,\n documentPurgeCheckpoints,\n keyingCheckpointTables,\n} from \"./keyingCheckpointSchema\";\nimport { localIntents } from \"./localIntentSchema\";\nimport * as organizationDataUsage from \"./organizationDataUsageSchema\";\nimport { organizationFounders } from \"./organizationFounderSchema\";\nimport * as provisioningAttempt from \"./organizationProvisioningAttemptSchema\";\nimport {\n organizationReadModelSQLiteSchema,\n organizationReadModelTables,\n} from \"./organizationReadModelTableRegistry\";\nimport * as organizationSyncPause from \"./organizationSyncPauseSchema\";\nimport { principalGrantRetirements } from \"./principalGrantRetirementSchema\";\nimport {\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n} from \"./principalHistoryEvidenceSchema\";\nimport { principalKeyEnvelopeArchive } from \"./principalHistoryRetentionSchema\";\nimport { principalHistoryStages } from \"./principalHistoryStageSchema\";\nimport {\n principalMutationJournal,\n principalMutationJournalTables,\n} from \"./principalMutationJournalSchema\";\nimport {\n principalPolicyBundleReferences,\n principalPolicyBundles,\n principalPolicyCheckpoints,\n principalPolicyCheckpointTable,\n principalPolicyTables,\n} from \"./principalPolicySchema\";\nimport {\n securityIncidents,\n securityIncidentTable,\n} from \"./securityIncidentSchema\";\nimport {\n trustedUserIdentityPins,\n trustedUserIdentityPinTables,\n} from \"./trustedUserIdentityPinSchema\";\nimport {\n verifiedAccessManifestBundles,\n verifiedManifestBundleTables,\n} from \"./verifiedManifestBundleSchema\";\n\nexport {\n containerHydrationTombstones,\n containers,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n supersededContainerBindings,\n} from \"./containerSchema\";\nexport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"./documentAttachmentSchema\";\nexport {\n CONTAINER_CREATE_INTENT_TYPE,\n inContainerIntentLanes,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n LOCAL_INTENT_SUBJECT,\n localIntents,\n} from \"./localIntentSchema\";\nexport {\n principalPolicyBundleReferences,\n principalPolicyBundles,\n principalPolicyCheckpoints,\n} from \"./principalPolicySchema\";\nexport { securityIncidents } from \"./securityIncidentSchema\";\nexport { containerDocumentTombstoneHolds, organizationReadModelTables };\n\nconst securityIncidentTables: ReadonlyArray<SqlTableSchema> = [\n securityIncidentTable,\n];\n\nexport const containerTables = containerTableSchemas;\n\nexport const localIntentTables: ReadonlyArray<SqlTableSchema> = [\n defineSqlTableSchema(localIntents),\n];\n\nexport const documentPlacementIntentTables: ReadonlyArray<SqlTableSchema> = [\n ...localIntentTables,\n defineSqlTableSchema(documentIntentLinkTargets),\n];\n\nexport const clientSqlTables: ReadonlyArray<SqlTableSchema> = [\n ...principalMutationJournalTables,\n ...documentTables,\n ...principalPolicyTables,\n ...keyingCheckpointTables.filter((t) => t !== principalPolicyCheckpointTable),\n ...verifiedManifestBundleTables,\n ...trustedUserIdentityPinTables,\n ...securityIncidentTables,\n ...containerTables,\n ...documentContainerProjectionTables,\n ...documentPlacementIntentTables,\n ...documentProjectionTables,\n ...containerSyncWatermarkTables,\n ...organizationReadModelTables,\n ...organizationDataUsage.organizationDataUsageTables,\n ...provisioningAttempt.organizationProvisioningAttemptTables,\n ...organizationSyncPause.organizationSyncPauseTables,\n];\n\nexport const clientSQLiteSchema = {\n principalKeyEnvelopeArchive,\n principalMutationJournal,\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n principalHistoryStages,\n organizationFounders,\n principalGrantRetirements,\n documents,\n principalPolicyBundles,\n principalPolicyBundleReferences,\n accessManifestCheckpoints,\n documentPurgeCheckpoints,\n principalPolicyCheckpoints,\n verifiedAccessManifestBundles,\n trustedUserIdentityPins,\n securityIncidents,\n ...containerSQLiteSchema,\n documentContainerProjection,\n localIntents,\n documentIntentLinkTargets,\n documentProjection,\n documentPendingAttachments,\n documentAttachmentBlobProjection,\n documentOrphanBlobReclaims: documentOrphanBlobReclaims,\n containerSyncWatermarks,\n ...organizationReadModelSQLiteSchema,\n ...organizationDataUsage.organizationDataUsageSQLiteSchema,\n ...provisioningAttempt.organizationProvisioningAttemptSQLiteSchema,\n ...organizationSyncPause.organizationSyncPauseSQLiteSchema,\n};\n"]}