@nicia-ai/typegraph 0.47.0 → 0.48.0

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 (207) hide show
  1. package/dist/backend/drizzle/indexes.d.cts +1 -1
  2. package/dist/backend/drizzle/indexes.d.ts +1 -1
  3. package/dist/backend/index.cjs +27 -19
  4. package/dist/backend/index.d.cts +37 -55
  5. package/dist/backend/index.d.ts +37 -55
  6. package/dist/backend/index.js +4 -4
  7. package/dist/backend/postgres/index.cjs +7 -7
  8. package/dist/backend/postgres/index.d.cts +21 -7
  9. package/dist/backend/postgres/index.d.ts +21 -7
  10. package/dist/backend/postgres/index.js +6 -6
  11. package/dist/backend/postgres/pglite-store.cjs +17 -17
  12. package/dist/backend/postgres/pglite-store.d.cts +8 -8
  13. package/dist/backend/postgres/pglite-store.d.ts +8 -8
  14. package/dist/backend/postgres/pglite-store.js +14 -14
  15. package/dist/backend/postgres/pglite.cjs +8 -8
  16. package/dist/backend/postgres/pglite.d.cts +3 -3
  17. package/dist/backend/postgres/pglite.d.ts +3 -3
  18. package/dist/backend/postgres/pglite.js +7 -7
  19. package/dist/backend/sqlite/index.cjs +7 -7
  20. package/dist/backend/sqlite/index.d.cts +20 -7
  21. package/dist/backend/sqlite/index.d.ts +20 -7
  22. package/dist/backend/sqlite/index.js +6 -6
  23. package/dist/backend/sqlite/libsql.cjs +8 -8
  24. package/dist/backend/sqlite/libsql.d.cts +3 -3
  25. package/dist/backend/sqlite/libsql.d.ts +3 -3
  26. package/dist/backend/sqlite/libsql.js +6 -6
  27. package/dist/backend/sqlite/local-store.cjs +18 -18
  28. package/dist/backend/sqlite/local-store.d.cts +8 -8
  29. package/dist/backend/sqlite/local-store.d.ts +8 -8
  30. package/dist/backend/sqlite/local-store.js +15 -15
  31. package/dist/backend/sqlite/local.cjs +9 -9
  32. package/dist/backend/sqlite/local.d.cts +3 -3
  33. package/dist/backend/sqlite/local.d.ts +3 -3
  34. package/dist/backend/sqlite/local.js +7 -7
  35. package/dist/{chunk-EMIB2RXD.cjs → chunk-2HIYYMWY.cjs} +99 -96
  36. package/dist/chunk-2HIYYMWY.cjs.map +1 -0
  37. package/dist/{chunk-6KFLYYOC.cjs → chunk-2QGYQBS2.cjs} +5 -5
  38. package/dist/{chunk-6KFLYYOC.cjs.map → chunk-2QGYQBS2.cjs.map} +1 -1
  39. package/dist/{chunk-5FT3TLPK.js → chunk-2SYZXD54.js} +16 -13
  40. package/dist/chunk-2SYZXD54.js.map +1 -0
  41. package/dist/{chunk-XYBQI6LE.js → chunk-2TYSSBU5.js} +6 -6
  42. package/dist/{chunk-XYBQI6LE.js.map → chunk-2TYSSBU5.js.map} +1 -1
  43. package/dist/{chunk-6JVZSOHQ.cjs → chunk-3FPR224C.cjs} +26 -26
  44. package/dist/{chunk-6JVZSOHQ.cjs.map → chunk-3FPR224C.cjs.map} +1 -1
  45. package/dist/{chunk-MFZR4QKM.cjs → chunk-3KOY4FH3.cjs} +181 -4
  46. package/dist/chunk-3KOY4FH3.cjs.map +1 -0
  47. package/dist/{chunk-6FWSNSRE.js → chunk-4WMMBDS5.js} +4 -4
  48. package/dist/chunk-4WMMBDS5.js.map +1 -0
  49. package/dist/{chunk-NG2RB5WL.js → chunk-5K2BKEBD.js} +18 -3
  50. package/dist/chunk-5K2BKEBD.js.map +1 -0
  51. package/dist/chunk-5PRKMB24.cjs +124 -0
  52. package/dist/chunk-5PRKMB24.cjs.map +1 -0
  53. package/dist/chunk-6LN7FIVU.js +107 -0
  54. package/dist/chunk-6LN7FIVU.js.map +1 -0
  55. package/dist/{chunk-I4G3SQPF.cjs → chunk-7XUYFFR4.cjs} +7 -7
  56. package/dist/chunk-7XUYFFR4.cjs.map +1 -0
  57. package/dist/{chunk-KH7XW7VV.js → chunk-ACGSAMD3.js} +24 -27
  58. package/dist/chunk-ACGSAMD3.js.map +1 -0
  59. package/dist/{chunk-QS3NQZVC.js → chunk-AX6JGVTZ.js} +16 -11
  60. package/dist/chunk-AX6JGVTZ.js.map +1 -0
  61. package/dist/{chunk-DJZTXBWY.js → chunk-BRRP76WO.js} +71 -30
  62. package/dist/chunk-BRRP76WO.js.map +1 -0
  63. package/dist/{chunk-5UMTUOM5.js → chunk-CT3ZKTOF.js} +5 -4
  64. package/dist/chunk-CT3ZKTOF.js.map +1 -0
  65. package/dist/{chunk-XY5OMOJD.js → chunk-DZAICA5J.js} +3 -3
  66. package/dist/{chunk-XY5OMOJD.js.map → chunk-DZAICA5J.js.map} +1 -1
  67. package/dist/{chunk-OIFSOPSR.cjs → chunk-EZEEWCFJ.cjs} +38 -156
  68. package/dist/chunk-EZEEWCFJ.cjs.map +1 -0
  69. package/dist/{chunk-AMMWA76F.cjs → chunk-FA2AFWLP.cjs} +6 -6
  70. package/dist/{chunk-AMMWA76F.cjs.map → chunk-FA2AFWLP.cjs.map} +1 -1
  71. package/dist/{chunk-FNOMT74T.js → chunk-I4GAZH5Z.js} +180 -5
  72. package/dist/chunk-I4GAZH5Z.js.map +1 -0
  73. package/dist/{chunk-WGX7JH7E.cjs → chunk-JB6T4GLL.cjs} +106 -134
  74. package/dist/chunk-JB6T4GLL.cjs.map +1 -0
  75. package/dist/{chunk-MX4DHSQP.cjs → chunk-JFRT7S3B.cjs} +92 -98
  76. package/dist/chunk-JFRT7S3B.cjs.map +1 -0
  77. package/dist/{chunk-SE6EGQSD.js → chunk-KF6K7TGH.js} +38 -66
  78. package/dist/chunk-KF6K7TGH.js.map +1 -0
  79. package/dist/{chunk-ZHNXLS3C.js → chunk-NACVVDWB.js} +208 -8
  80. package/dist/chunk-NACVVDWB.js.map +1 -0
  81. package/dist/{chunk-M35DF33T.js → chunk-OD4SSY2U.js} +29 -16
  82. package/dist/chunk-OD4SSY2U.js.map +1 -0
  83. package/dist/{chunk-U5EDAVOJ.cjs → chunk-OTUPEF2W.cjs} +54 -49
  84. package/dist/chunk-OTUPEF2W.cjs.map +1 -0
  85. package/dist/{chunk-BCQ76AXA.cjs → chunk-PFBRJBUL.cjs} +107 -94
  86. package/dist/chunk-PFBRJBUL.cjs.map +1 -0
  87. package/dist/{chunk-AVGUJWVX.js → chunk-S5TERQVW.js} +15 -132
  88. package/dist/chunk-S5TERQVW.js.map +1 -0
  89. package/dist/chunk-SIT26LAZ.cjs +614 -0
  90. package/dist/chunk-SIT26LAZ.cjs.map +1 -0
  91. package/dist/{chunk-BR7SHKGM.cjs → chunk-SR725PWF.cjs} +548 -507
  92. package/dist/chunk-SR725PWF.cjs.map +1 -0
  93. package/dist/{chunk-5FBRVORR.cjs → chunk-TKZXMWQF.cjs} +8 -7
  94. package/dist/chunk-TKZXMWQF.cjs.map +1 -0
  95. package/dist/{chunk-425IZOQ5.cjs → chunk-TQHGE7UC.cjs} +20 -2
  96. package/dist/chunk-TQHGE7UC.cjs.map +1 -0
  97. package/dist/{chunk-GYUJZARH.cjs → chunk-TUNPBZY3.cjs} +4 -4
  98. package/dist/{chunk-GYUJZARH.cjs.map → chunk-TUNPBZY3.cjs.map} +1 -1
  99. package/dist/chunk-UGHG7PGX.js +592 -0
  100. package/dist/chunk-UGHG7PGX.js.map +1 -0
  101. package/dist/{chunk-KABFHAL7.cjs → chunk-UMGZDVOA.cjs} +213 -12
  102. package/dist/chunk-UMGZDVOA.cjs.map +1 -0
  103. package/dist/{chunk-UPAJHMW3.cjs → chunk-WCCATHMB.cjs} +54 -57
  104. package/dist/chunk-WCCATHMB.cjs.map +1 -0
  105. package/dist/{chunk-LEWHMOUY.js → chunk-YIURNGXI.js} +4 -4
  106. package/dist/{chunk-LEWHMOUY.js.map → chunk-YIURNGXI.js.map} +1 -1
  107. package/dist/{chunk-EP4RUYD6.js → chunk-YVF2EM7B.js} +3 -3
  108. package/dist/{chunk-EP4RUYD6.js.map → chunk-YVF2EM7B.js.map} +1 -1
  109. package/dist/{chunk-NNQ6A3RM.js → chunk-ZFMCDJGB.js} +7 -12
  110. package/dist/chunk-ZFMCDJGB.js.map +1 -0
  111. package/dist/core/index.cjs +6 -6
  112. package/dist/core/index.d.cts +4 -4
  113. package/dist/core/index.d.ts +4 -4
  114. package/dist/core/index.js +2 -2
  115. package/dist/ddl-BL1NZLMY.d.cts +78 -0
  116. package/dist/ddl-D_oW-EVO.d.ts +78 -0
  117. package/dist/graph-extension/index.d.cts +4 -4
  118. package/dist/graph-extension/index.d.ts +4 -4
  119. package/dist/graph-merge/index.cjs +334 -191
  120. package/dist/graph-merge/index.cjs.map +1 -1
  121. package/dist/graph-merge/index.d.cts +65 -15
  122. package/dist/graph-merge/index.d.ts +65 -15
  123. package/dist/graph-merge/index.js +174 -32
  124. package/dist/graph-merge/index.js.map +1 -1
  125. package/dist/{index-CHTv4XMZ.d.cts → index-COs_z6nV.d.cts} +2 -2
  126. package/dist/{index-CzoJ3MUw.d.ts → index-D7d1u2gr.d.ts} +2 -2
  127. package/dist/index.cjs +90 -86
  128. package/dist/index.d.cts +12 -12
  129. package/dist/index.d.ts +12 -12
  130. package/dist/index.js +13 -13
  131. package/dist/indexes/index.d.cts +4 -4
  132. package/dist/indexes/index.d.ts +4 -4
  133. package/dist/interchange/index.cjs +38 -38
  134. package/dist/interchange/index.d.cts +7 -7
  135. package/dist/interchange/index.d.ts +7 -7
  136. package/dist/interchange/index.js +10 -10
  137. package/dist/{manager-DlY1vlla.d.cts → manager-CYaff3n3.d.cts} +2 -2
  138. package/dist/{manager-B6sOQzcQ.d.ts → manager-D9eRT_ns.d.ts} +2 -2
  139. package/dist/{materialize-indexes-DQL4xcpf.d.ts → materialize-indexes-DJ3ykH59.d.ts} +1 -1
  140. package/dist/{materialize-indexes-sskhp-c_.d.cts → materialize-indexes-DTtAnvfY.d.cts} +1 -1
  141. package/dist/{postgres-BXy_nyMs.d.cts → postgres-CcL4bAHS.d.ts} +1 -1
  142. package/dist/{postgres-B6YOUcaK.d.ts → postgres-DMj39MEu.d.cts} +1 -1
  143. package/dist/profiler/index.d.cts +9 -9
  144. package/dist/profiler/index.d.ts +9 -9
  145. package/dist/provenance/index.cjs +25 -26
  146. package/dist/provenance/index.cjs.map +1 -1
  147. package/dist/provenance/index.d.cts +7 -7
  148. package/dist/provenance/index.d.ts +7 -7
  149. package/dist/provenance/index.js +9 -10
  150. package/dist/provenance/index.js.map +1 -1
  151. package/dist/repair-validity-windows-BFNZvd_H.d.cts +166 -0
  152. package/dist/repair-validity-windows-DlUSqwCg.d.ts +166 -0
  153. package/dist/schema/index.cjs +35 -35
  154. package/dist/schema/index.d.cts +6 -6
  155. package/dist/schema/index.d.ts +6 -6
  156. package/dist/schema/index.js +8 -8
  157. package/dist/{searchable-D9gMiwcS.d.ts → searchable-DHJMh_nj.d.cts} +1 -1
  158. package/dist/{searchable-0Cn_lY8U.d.cts → searchable-bpE1bBfc.d.ts} +1 -1
  159. package/dist/{sqlite-DioSxaPe.d.cts → sqlite-D7Oz0SQh.d.ts} +1 -1
  160. package/dist/{sqlite-ClXuBYAj.d.ts → sqlite-YppHrNFb.d.cts} +1 -1
  161. package/dist/{store-5j-w5onJ.d.ts → store-JUVvtmR4.d.cts} +113 -26
  162. package/dist/{store-CFedKGU5.d.cts → store-UzrGvZOo.d.ts} +113 -26
  163. package/dist/{temporal-CjO9FH1l.d.ts → temporal-5GqpYCk2.d.cts} +1 -1
  164. package/dist/{temporal-Ce1pG0S1.d.cts → temporal-CbnLzTmM.d.ts} +1 -1
  165. package/dist/{types-DKkMJZjR.d.cts → types-BqFZTQmV.d.cts} +29 -4
  166. package/dist/{types-DKkMJZjR.d.ts → types-BqFZTQmV.d.ts} +29 -4
  167. package/dist/{types-BrdOFu48.d.ts → types-Bx74kaTt.d.ts} +1 -1
  168. package/dist/{types-oj_OGAaZ.d.cts → types-CXAhpW-c.d.cts} +1 -1
  169. package/dist/{where-D1wKCJ4Q.d.cts → where-DI_Fqz-X.d.cts} +1 -1
  170. package/dist/{where-C8w2627G.d.ts → where-O-k2wgYm.d.ts} +1 -1
  171. package/package.json +1 -1
  172. package/dist/chunk-3HGRTCDU.cjs +0 -269
  173. package/dist/chunk-3HGRTCDU.cjs.map +0 -1
  174. package/dist/chunk-425IZOQ5.cjs.map +0 -1
  175. package/dist/chunk-5FBRVORR.cjs.map +0 -1
  176. package/dist/chunk-5FT3TLPK.js.map +0 -1
  177. package/dist/chunk-5UMTUOM5.js.map +0 -1
  178. package/dist/chunk-6FWSNSRE.js.map +0 -1
  179. package/dist/chunk-AVGUJWVX.js.map +0 -1
  180. package/dist/chunk-BCQ76AXA.cjs.map +0 -1
  181. package/dist/chunk-BR7SHKGM.cjs.map +0 -1
  182. package/dist/chunk-DJZTXBWY.js.map +0 -1
  183. package/dist/chunk-EMIB2RXD.cjs.map +0 -1
  184. package/dist/chunk-FNOMT74T.js.map +0 -1
  185. package/dist/chunk-I4G3SQPF.cjs.map +0 -1
  186. package/dist/chunk-JR6SX5RH.cjs +0 -268
  187. package/dist/chunk-JR6SX5RH.cjs.map +0 -1
  188. package/dist/chunk-KABFHAL7.cjs.map +0 -1
  189. package/dist/chunk-KH7XW7VV.js.map +0 -1
  190. package/dist/chunk-M35DF33T.js.map +0 -1
  191. package/dist/chunk-MFZR4QKM.cjs.map +0 -1
  192. package/dist/chunk-MX4DHSQP.cjs.map +0 -1
  193. package/dist/chunk-NAZ2RA4L.js +0 -254
  194. package/dist/chunk-NAZ2RA4L.js.map +0 -1
  195. package/dist/chunk-NG2RB5WL.js.map +0 -1
  196. package/dist/chunk-NNQ6A3RM.js.map +0 -1
  197. package/dist/chunk-OIFSOPSR.cjs.map +0 -1
  198. package/dist/chunk-QS3NQZVC.js.map +0 -1
  199. package/dist/chunk-SE6EGQSD.js.map +0 -1
  200. package/dist/chunk-SHSSRCFR.js +0 -246
  201. package/dist/chunk-SHSSRCFR.js.map +0 -1
  202. package/dist/chunk-U5EDAVOJ.cjs.map +0 -1
  203. package/dist/chunk-UPAJHMW3.cjs.map +0 -1
  204. package/dist/chunk-WGX7JH7E.cjs.map +0 -1
  205. package/dist/chunk-ZHNXLS3C.js.map +0 -1
  206. package/dist/ddl-CprnMXJ-.d.ts +0 -38
  207. package/dist/ddl-DJA7Lci5.d.cts +0 -38
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backend/graph-backend-keys.ts","../src/backend/transaction-resource.ts","../src/backend/derive-backend.ts","../src/utils/sql-errors.ts","../src/utils/array.ts"],"names":[],"mappings":";;;AAgBO,IAAM,6BAAA,GAAgC;AAAA,EAC3C,SAAA;AAAA,EACA,cAAA;AAAA,EACA,YAAA;AAAA,EACA,kBAAA;AAAA,EACA,gBAAA;AAAA,EACA,YAAA;AAAA,EACA,oBAAA;AAAA,EACA,kBAAA;AAAA,EACA,2BAAA;AAAA,EACA,YAAA;AAAA,EACA,eAAA;AAAA,EACA,YAAA;AAAA,EACA,gBAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,YAAA;AAAA,EACA,oBAAA;AAAA,EACA,kBAAA;AAAA,EACA,2BAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,gBAAA;AAAA,EACA,kBAAA;AAAA,EACA,sBAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,gBAAA;AAAA,EACA,mBAAA;AAAA,EACA,sBAAA;AAAA,EACA,iBAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA,wBAAA;AAAA,EACA,qCAAA;AAAA,EACA,kBAAA;AAAA,EACA,cAAA;AAAA,EACA,mBAAA;AAAA,EACA,cAAA;AAAA,EACA,4BAAA;AAAA,EACA,aAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA,kBAAA;AAAA,EACA,qBAAA;AAAA,EACA,iCAAA;AAAA,EACA,2BAAA;AAAA,EACA,kCAAA;AAAA,EACA,kBAAA;AAAA,EACA,wBAAA;AAAA,EACA,iBAAA;AAAA,EACA,sBAAA;AAAA,EACA,iBAAA;AAAA,EACA,sBAAA;AAAA,EACA,cAAA;AAAA,EACA,mBAAA;AAAA,EACA,iBAAA;AAAA,EACA,cAAA;AAAA,EACA,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AAA,EAAY;AAC/B,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,MAAM,GAAA,GAAM,OAAO,IAAI,CAAA;AACvB,IAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,GAAA,CAAI,GAAG,KAAK,EAAC;AAClC,IAAA,KAAA,CAAM,KAAK,IAAI,CAAA;AACf,IAAA,MAAA,CAAO,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,EACvB;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-UGHG7PGX.js","sourcesContent":["import { type GraphBackend } from \"./types\";\n\n/**\n * Runtime allowlist for the portable GraphBackend port.\n *\n * Data only: the projection constructors that consume this allowlist live in\n * `derive-backend.ts`, the one seam that carries a backend's\n * serialized-resource audit.\n *\n * `satisfies` rejects misspelled/non-port keys. The coverage record below\n * rejects every newly added GraphBackend key until it is deliberately added\n * here, so a port expansion can neither leak through structural forwarding nor\n * silently disappear from a narrowed backend.\n *\n * @internal\n */\nexport const GRAPH_BACKEND_PROJECTION_KEYS = [\n \"dialect\",\n \"capabilities\",\n \"tableNames\",\n \"fulltextStrategy\",\n \"vectorStrategy\",\n \"insertNode\",\n \"insertNodeNoReturn\",\n \"insertNodesBatch\",\n \"insertNodesBatchReturning\",\n \"updateNode\",\n \"updateNodeSet\",\n \"deleteNode\",\n \"hardDeleteNode\",\n \"getNode\",\n \"getNodes\",\n \"insertEdge\",\n \"insertEdgeNoReturn\",\n \"insertEdgesBatch\",\n \"insertEdgesBatchReturning\",\n \"updateEdge\",\n \"deleteEdge\",\n \"hardDeleteEdge\",\n \"deleteEdgesBatch\",\n \"hardDeleteEdgesBatch\",\n \"getEdge\",\n \"getEdges\",\n \"countEdgesFrom\",\n \"edgeExistsBetween\",\n \"findEdgesConnectedTo\",\n \"findNodesByKind\",\n \"countNodesByKind\",\n \"findEdgesByKind\",\n \"findEdgesByEndpointSet\",\n \"findEdgesByHeterogeneousEndpointSet\",\n \"countEdgesByKind\",\n \"insertUnique\",\n \"insertUniqueBatch\",\n \"deleteUnique\",\n \"hardDeleteUniquesByNodeIds\",\n \"checkUnique\",\n \"checkUniqueBatch\",\n \"getActiveSchema\",\n \"getSchemaVersion\",\n \"commitSchemaVersion\",\n \"commitSchemaVersionIfKindsEmpty\",\n \"lockSchemaVersionForWrite\",\n \"commitSchemaVersionWithPreflight\",\n \"setActiveVersion\",\n \"schemaWriteTransaction\",\n \"upsertEmbedding\",\n \"upsertEmbeddingBatch\",\n \"deleteEmbedding\",\n \"deleteEmbeddingBatch\",\n \"vectorSearch\",\n \"createVectorIndex\",\n \"dropVectorIndex\",\n \"hybridSearch\",\n \"upsertFulltext\",\n \"deleteFulltext\",\n \"upsertFulltextBatch\",\n \"deleteFulltextBatch\",\n \"fulltextSearch\",\n \"ensureIndexMaterializationsTable\",\n \"ensureTrigramExtension\",\n \"ensureRevisionOriginsTable\",\n \"getIndexMaterialization\",\n \"getIndexMaterializations\",\n \"recordIndexMaterialization\",\n \"claimIndexMaterialization\",\n \"releaseIndexMaterializationClaim\",\n \"ensureContributionMaterializationsTable\",\n \"getContributionMaterialization\",\n \"recordContributionMaterialization\",\n \"assertRuntimeContributionsInitialized\",\n \"ensureKindRemovalsTable\",\n \"getPendingKindRemovals\",\n \"getAllKindRemovals\",\n \"recordKindRemoval\",\n \"ensureReconciliationMarkersTable\",\n \"ensureRuntimeContributions\",\n \"ensureVectorSlotContribution\",\n \"ensureVectorSlotContributions\",\n \"assertVectorSlotInitialized\",\n \"assertVectorSlotsInitialized\",\n \"deleteVectorSlotContribution\",\n \"verifyContributions\",\n \"repairContributions\",\n \"probeContributions\",\n \"rebuildContribution\",\n \"ensureFulltextTable\",\n \"ensureIdentityTables\",\n \"identityTableDdl\",\n \"getReconciliationMarker\",\n \"setReconciliationMarker\",\n \"clearGraph\",\n \"bootstrapTables\",\n \"refreshStatistics\",\n \"trustedImport\",\n \"execute\",\n \"executeStatement\",\n \"executeTemporaryStatement\",\n \"executeRaw\",\n \"compileSql\",\n \"executeDdl\",\n \"transaction\",\n \"close\",\n] as const satisfies readonly (keyof GraphBackend)[];\n\n/** @internal */\nexport type ProjectedGraphBackendKey =\n (typeof GRAPH_BACKEND_PROJECTION_KEYS)[number];\n\nconst MISSING_GRAPH_BACKEND_PROJECTION_KEYS: Record<\n Exclude<keyof GraphBackend, ProjectedGraphBackendKey>,\n never\n> = {};\nvoid MISSING_GRAPH_BACKEND_PROJECTION_KEYS;\n","/**\n * Ownership tracking for backends that serialize every statement onto ONE\n * database connection.\n *\n * Two facts are recorded here, and only these two:\n *\n * 1. **Which serialized resource a backend wrapper belongs to.** Distinct\n * `GraphBackend` objects (a second `createPostgresBackend(...)` over the same\n * client, a projection, an overlay, a managed-close wrapper) are not `===`,\n * yet their statements land on the same connection. Marking a backend with\n * the underlying client object — and inheriting that mark through every\n * decorator — makes \"these two wrappers cannot run a read transaction and a\n * write transaction at the same time\" answerable.\n *\n * Only backends whose driver is known to be single-connection are marked;\n * everything else is deliberately left unmarked, because a pooled connection\n * hands out an independent connection per checkout and refusing concurrent\n * work there would refuse legitimate work. The complete classification —\n * marked, deliberately unmarked, and known gaps — is the inventory at the\n * bottom of this doc.\n *\n * 2. **Which long-lived interchange stream currently holds that resource.** A\n * streaming export holds a read-only transaction on its connection for the\n * whole stream; a streaming import opens a write transaction per chunk on\n * that same connection for the whole stream. Any second long-lived stream on\n * the resource therefore either nests a transaction inside the first one\n * (`cannot start a transaction within a transaction`) or waits for a\n * connection that is never released — and that is true of ALL FOUR pairings,\n * not only the two cross-kind ones:\n *\n * | holder | second stream | outcome without the lease |\n * | --------------- | ---------------- | ---------------------------------- |\n * | export snapshot | import stream | import's chunk waits on the reader |\n * | import stream | export snapshot | export's read strands the import |\n * | import stream | import stream | nested BEGIN |\n * | export snapshot | export snapshot | nested BEGIN |\n *\n * So the lease is EXCLUSIVE, not refcounted: at most one stream of any kind\n * holds a given serialized resource, and at most one holds a transactional\n * SQLite backend object even when its resource is declared independent. The\n * second stream is refused with the holder's kind named (see\n * {@link acquireSerializedStreamLease}). Refcounting admitted the two\n * same-kind rows above, which then failed on the driver after chunks had\n * already committed.\n *\n * `\"import-stream\"` is the kind of EVERY long-lived import, not only the\n * chunk-streaming one: an in-memory `importGraph` and a `trustedImport`\n * session write through the same one connection over the same kind of window,\n * so they claim the same lease and are refused by the same holders.\n *\n * The check and the registration happen in ONE synchronous section inside\n * {@link acquireSerializedStreamLease} — there is no way for a caller to check\n * without claiming, so there is no window to get wrong. On a single-threaded\n * event loop a check with no `await` before its registration is atomic: two\n * long-lived streams cannot both observe a free resource, so no interleaving is\n * left where each waits for the other.\n *\n * Neither fact is a general concurrency model:\n *\n * - No attempt is made to detect shared connections we cannot see (two `pg`\n * Clients dialed at the same server, two better-sqlite3 handles on one file).\n * Those are genuinely independent connections and are correctly not refused.\n * - RESIDUAL GAP: the lease is keyed by serialized resource, so an UNMARKED\n * backend registers nothing and can hold nothing. A driver we cannot\n * positively identify as single-connection therefore keeps exactly today's\n * protection — the identity-based pre-flight in `importGraphStream`, which\n * only sees a stream that still names its own source backend — and an\n * export/import pair interleaved on such a connection can still wedge. Closing\n * that requires recognizing the driver, not more bookkeeping here.\n * - RESIDUAL GAP: a `transactions: false` export abstains entirely — it opens no\n * snapshot transaction, so `exportGraphStream` neither claims the lease nor\n * consults it: such an export is never refused and never refuses anyone.\n * A streaming import claims the lease whatever its backend reports,\n * because its writes still have to land somewhere an open snapshot is not.\n * The visible cost of that asymmetry is one conservative refusal: two\n * streaming imports through a MARKED but deliberately `transactionMode:\n * \"none\"` connection frame nothing and would in fact interleave harmlessly,\n * yet the second is refused. That is the deliberate trade — the alternative\n * (gating the import's claim on `capabilities.transactions` too) would stop a\n * real snapshot export from being refused mid-import on a mixed-profile\n * connection, which is the far likelier pairing.\n * - RESIDUAL GAP: the lease's population is INTERCHANGE STREAMS. Ordinary\n * long-lived frames on the same serialized connection — a `store.transaction`\n * held across awaits by application code, `schemaWriteTransaction` (the\n * provenance claim, the identity DDL fence), `store.evolve()` — neither hold\n * nor consult it, so one of those opening while an export snapshot is live\n * on the same connection blocks or wedges without a typed error, exactly as\n * any two of them always have. Representing every long-lived frame here is a\n * different, larger contract (a connection-wide frame lease); the streams\n * are covered because they are the pairing users actually compose.\n *\n * ## Inventory of serialized resources\n *\n * Every `GraphBackend` in this package is built by `createSqliteBackend` or\n * `createPostgresBackend` (the batteries-included factories — local\n * better-sqlite3, libSQL, PGlite — and every decorator go through one of them),\n * so those two factories are the only places a mark is applied, and this list is\n * the whole population. Predicates are named rather than line-cited so the\n * inventory stays greppable as the files move.\n *\n * MARKED — the factory resolves the resource before the backend object exists,\n * so no wrapper can observe it unmarked:\n *\n * - better-sqlite3 `Database` (`prepare` + `pragma`) — `createSqliteBackend` via\n * `getSerializedSqliteConnection`, which asks one named predicate per driver.\n * - bun:sqlite `Database` (`prepare` + `query` + `run`/`exec` + `serialize` +\n * a `filename` string) — same site, via `isBunSqliteClient`. One synchronous\n * connection, like better-sqlite3; `query` and `filename` are what separate\n * it structurally from better-sqlite3 (`pragma`, `name`), so the mark never\n * rests on a session's constructor name, which bundlers rename.\n * - sql.js `Database` (`prepare` + `exec` + `run` + `export` +\n * `getRowsModified`) — same site, via `isSqlJsClient`. One in-WASM handle\n * executed in-process; `export` and `getRowsModified` are sql.js's own API\n * and exist on no other SQLite client.\n * - Local `@libsql/client` (`protocol === \"file\"`: `file:` paths, `:memory:`,\n * an embedded replica's local file) — same site, via `isLocalLibsqlClient`.\n * - PGlite — `createPostgresBackend` via `getPgliteClient` (`query` +\n * `dumpDataDir`).\n * - Bare `pg` / `@neondatabase/serverless` `Client`, including a checked-out\n * `PoolClient` — same site, via `isBarePgClient`.\n * - `pg` / neon-serverless `Pool` capped at one connection — same site, via\n * `isSingleConnectionPgPool`, which asks `isSingleConnectionPgPoolCap` what a\n * cap of one looks like. pg-pool normalizes `max` (and the legacy `poolSize`)\n * into `options` without coercing either, so `{ max: 1 }`, `{ max: \"1\" }` and\n * `{ poolSize: \"1\" }` are one and the same one-connection pool, and all three\n * are marked.\n * - postgres-js capped at one connection — same site, via\n * `isSingleConnectionCallablePgClient`, which asks\n * `isSingleConnectionPostgresJsCap`. The client is CALLABLE, so it needed a\n * resolver arm of its own; `begin` reserves the sole connection, making an\n * export snapshot hold the connection every other wrapper writes through.\n * postgres-js resolves `max` from the options object, the URL query string and\n * `PGMAX` and coerces none of them, so `{ max: 1 }`, `?max=1` and `PGMAX=1`\n * are all marked. Requires postgres-js identity (`isPostgresJsClient`) as well\n * as the cap: a cap on a callable we cannot attribute to a known driver is not\n * evidence.\n * - Cloudflare Durable Object storage (`drizzle(ctx.storage)`) —\n * `createSqliteBackend` via `getDurableObjectStorageClient`, the same\n * full-shape evidence `transactionMode: \"do-sqlite\"` requires to run a\n * transaction. The storage transaction frame is AMBIENT on the storage object\n * (no tx handle exists on DO), so a second wrapper's writes land inside the\n * first wrapper's export snapshot; nothing else abstains, since the DO backend\n * reports `capabilities.transactions: true`.\n *\n * DELIBERATELY UNMARKED, by class — marking these would refuse work that\n * succeeds:\n *\n * - Pooled connections: a default-size `pg` / neon-serverless / `@vercel/postgres`\n * pool, postgres-js or Bun `SQL` at default size. Each checkout is an\n * independent connection.\n * - Session-less HTTP drivers: `neon-http`, Cloudflare D1, RDS Data API. Nothing\n * is held between statements, and the two that report\n * `capabilities.transactions: false` are additionally short-circuited by\n * {@link snapshotExportContention} before marking is consulted.\n * - Remote `@libsql/client` (`http` / `ws`): an independent stream per\n * transaction.\n * - Separate handles on one database (two `pg` Clients at one server, two\n * better-sqlite3 handles on one file): genuinely concurrent connections.\n * - Transaction-scoped backends (`transaction()`, `adoptTransaction`): the\n * caller's transaction already owns the connection and opens no second frame,\n * and the guards run on the root backend a Store holds. Decorators over a root\n * backend DO carry the verdict, via\n * {@link carryBackendResourceAudit}.\n *\n * KNOWN GAPS — serialized in fact, unmarked, so they keep only the\n * identity-based pre-flight in `importGraphStream` (which a `history: true`\n * store's overlay already defeats). Each is a coverage extension needing\n * positive evidence of the client shape, never a silent no-op. Every one of\n * them has the SAME sanctioned workaround until its shape is recognized: the\n * caller declares the connection with\n * `{ serializedResource: { mode: \"shared\", resource: client } }` (see\n * {@link SerializedResourceDeclaration}), which is a claim the caller can make\n * and this package cannot.\n *\n * - React Native / Expo SQLite drivers — `expo-sqlite` and `op-sqlite`. One\n * connection each, and both are genuinely serialized, but neither exposes a\n * plain `prepare` (`prepareAsync` / `prepareSync`, `prepareStatement`), so\n * none of the predicates above can see them and neither driver is installable\n * here to derive the shape from rather than guess it. Remaining #434 scope:\n * each needs its own positive shape, taken from the driver's own typings.\n * - `node:sqlite` `DatabaseSync`: UNREACHABLE through Drizzle today —\n * drizzle-orm 0.45.2 ships `bun-sqlite`, `sql-js`, `durable-sqlite`,\n * `expo-sqlite`, `op-sqlite`, `sqlite-proxy` and `better-sqlite3`, and no\n * `node-sqlite` entrypoint, so no `createSqliteBackend` call can be handed\n * one. Re-check when the Drizzle floor moves; nothing to mark until then.\n * - postgres-js given a NON-NUMERIC string cap other than one, e.g.\n * `postgres(url + \"?max=5\")`: `[...Array(options.max)]` (postgres@3.4.9\n * `src/index.js:65`) yields length 1 for any such string, so that client\n * really does open exactly one connection today and really can wedge a stream\n * pair. Unmarked on purpose — marking it would be marking on an upstream bug,\n * and the day postgres-js coerces `max` the same configuration becomes a\n * five-connection pool whose concurrent work we would then refuse. A caller on\n * that shape materializes the export or imports into an independent backend,\n * exactly as before this guard existed.\n * - Bun `SQL` (Postgres) built with `{ max: 1 }`: genuinely serialized, but\n * nothing in this package positively identifies that driver — there is no\n * Postgres equivalent of the SQLite driver shapes above — so `options.max`\n * there cannot be attributed to a driver whose dispatch we know. Marking it\n * needs a Bun-`SQL` discriminator first. Remaining #434 scope.\n * - Drivers we cannot identify at all (`sqlite-proxy`, `pg-proxy`, a bespoke\n * adapter): whether the far side serializes is unknowable from here, so they\n * fall under the residual gap above.\n */\nimport { ConfigurationError } from \"../errors\";\nimport { type GraphBackend } from \"./types\";\n\n/**\n * What we know about the connection a backend's statements land on.\n *\n * `independent` is a POSITIVE verdict — a factory looked and found statements\n * that can run on independent connections. It is not the same runtime state as\n * a backend nobody audited, which carries no record at all.\n */\nexport type BackendResourceAudit =\n | Readonly<{ kind: \"serialized\"; resource: object }>\n | Readonly<{\n kind: \"independent\";\n /** Stable key for the SQLite identity arm of an explicit declaration. */\n identityLeaseResource?: object;\n }>;\n\n/**\n * Declare the connection this backend serializes on, when TypeGraph cannot\n * detect it (Bun `SQL`, `expo-sqlite`, `op-sqlite`, `sqlite-proxy`, `pg-proxy`,\n * a postgres-js pool capped through a string the driver does not coerce — the\n * KNOWN GAPS in this module's inventory). Two wrappers that pass the same\n * object are treated as one serialized resource, exactly as two wrappers over a\n * detected client are.\n *\n * - `\"detect\"` (the default, and the same behavior as omitting the option):\n * whatever the factory's driver predicates find, and nothing else.\n * - `\"shared\"`: the given object IS the serialized resource. Refused with a\n * {@link ConfigurationError} when the factory detected a DIFFERENT resource —\n * silently overriding would let two wrappers over one handle be given two\n * different sentinels and quietly de-serialize a pair that really does share.\n * - `\"independent\"`: statements can run on independent connections. The\n * documented escape hatch for a mis-detection, so a user surprised by a\n * refusal is never stuck.\n *\n * SCOPE — read this before using `\"independent\"`: this option controls the\n * SHARED-RESOURCE arm of {@link snapshotExportContention} only. It cannot lift\n * the object-identity arm, under which ONE SQLite backend object exporting into\n * ITSELF is refused with `same-sqlite-backend`. That arm is a driver fact (one\n * handle, one open snapshot transaction), not a claim about connection\n * topology, so no declaration can make it false.\n *\n * That surviving arm is SQLITE-ONLY, deliberately: it is gated on\n * `dialect === \"sqlite\"`, so on Postgres a backend declared `\"independent\"`\n * exporting into ITSELF is not refused either — a Postgres client that hands\n * out independent connections is exactly what the declaration claims, and the\n * snapshot and the writes it contends with land on different ones.\n */\nexport type SerializedResourceDeclaration =\n | Readonly<{ mode: \"detect\" }>\n | Readonly<{ mode: \"shared\"; resource: object }>\n | Readonly<{ mode: \"independent\" }>;\n\nconst BACKEND_RESOURCE_AUDITS = new WeakMap<object, BackendResourceAudit>();\n\n/**\n * The kinds of long-lived interchange stream that hold a serialized connection\n * across many statements — the population the lease is exclusive over.\n */\nexport type SerializedStreamKind = \"export-snapshot\" | \"import-stream\";\n\n/**\n * The outcome of claiming a serialized resource for a long-lived stream: the\n * (idempotent) release and the resource the claim was registered under when it\n * succeeded, or the kind of stream already holding it when it did not.\n *\n * `resource` is the decision itself rather than a flag a caller re-derives\n * from the backend: `undefined` means nothing was registered, because the\n * backend runs on no known serialized resource.\n */\nexport type SerializedStreamLease =\n | Readonly<{\n acquired: true;\n resource: object | undefined;\n release: () => void;\n }>\n | Readonly<{ acquired: false; heldBy: SerializedStreamKind }>;\n\n/**\n * The one long-lived stream holding each serialized resource. An entry exists\n * only while that stream is in flight; its release deletes the key, so a\n * finished stream retains nothing and refuses nobody.\n */\nconst ACTIVE_SERIALIZED_STREAMS = new Map<object, SerializedStreamKind>();\n\n/** Whether two audits are the same verdict about the same connection. */\nfunction auditsAgree(\n left: BackendResourceAudit,\n right: BackendResourceAudit,\n): boolean {\n if (left.kind === \"serialized\") {\n return right.kind === \"serialized\" && left.resource === right.resource;\n }\n return (\n right.kind === \"independent\" &&\n left.identityLeaseResource === right.identityLeaseResource\n );\n}\n\n/** Names a verdict for the write-once refusal below. */\nfunction formatAudit(audit: BackendResourceAudit): string {\n return audit.kind === \"serialized\" ? \"serialized\" : \"independent\";\n}\n\n/**\n * The two objects a refused `\"shared\"` declaration could not reconcile: the one\n * the caller named and the one this package detected.\n */\nexport type SerializedResourceConflict = Readonly<{\n declared: object;\n detected: object;\n}>;\n\n/**\n * The handles behind each refusal, held OFF the error object on purpose.\n *\n * `TypeGraphError.toLogString()` `JSON.stringify`s `details`, and the\n * documented handler pattern is `console.error(error.toLogString())` — so a\n * driver handle in `details` writes whatever that driver stores into the\n * caller's logs, and a `pg.Pool` stores its `connectionString`, password\n * included. The refusal therefore carries only a DESCRIPTION of each side\n * (`declaredKind` / `detectedKind`), while the identities live here, reachable\n * by asking for them and by nothing that walks an error's own properties.\n */\nconst SERIALIZED_RESOURCE_CONFLICTS = new WeakMap<\n Error,\n SerializedResourceConflict\n>();\n\n/**\n * The two objects a serialized-resource refusal could not reconcile, or\n * `undefined` for any other error.\n *\n * @internal\n */\nexport function serializedResourceConflict(\n error: unknown,\n): SerializedResourceConflict | undefined {\n return error instanceof ConfigurationError ?\n SERIALIZED_RESOURCE_CONFLICTS.get(error)\n : undefined;\n}\n\n/**\n * How a refusal names one side of a conflict without publishing the handle:\n * the constructor name (`\"Database\"`, `\"BoundPool\"`, `\"Object\"`), which says\n * what KIND of thing each side is and carries no connection string.\n */\nfunction describeSerializedResource(resource: object): string {\n const constructorName = (\n resource as Readonly<{ constructor?: Readonly<{ name?: unknown }> }>\n ).constructor?.name;\n return typeof constructorName === \"string\" && constructorName !== \"\" ?\n constructorName\n : \"Object\";\n}\n\n/**\n * The verdict a backend factory records, from what its driver predicates\n * detected and what the caller declared.\n *\n * The single owner of \"what a {@link SerializedResourceDeclaration} means\":\n * both drizzle factories call it, so the two cannot drift about whether a\n * declaration wins, loses, or is refused.\n *\n * Applied or refused, never ignored:\n *\n * - `\"shared\"` naming the resource detection already found, or naming one on a\n * backend detection could not classify → recorded as that resource.\n * - `\"shared\"` naming a DIFFERENT resource than detection found → refused, so\n * two wrappers over one handle cannot be handed two different sentinels and\n * silently de-serialized.\n * - `\"independent\"` → recorded, whatever detection found. This is the escape\n * hatch, not a conflict: detection is a duck-type over driver internals and\n * the caller knows their topology.\n * - `\"detect\"` or absent → exactly what detection found.\n *\n * Called INSIDE the factory body before the backend object exists, so a\n * refusal happens before any object is published (CTA-3) and a caller can never\n * hold a backend whose declaration was rejected.\n *\n * @throws {ConfigurationError} `details.reason: \"serialized-resource-conflict\"`\n * when a `\"shared\"` declaration names a resource detection disagrees with. Its\n * `details` describe the two sides (`declaredKind` / `detectedKind`) rather\n * than carrying them, because `details` is logged verbatim; the handles\n * themselves come from {@link serializedResourceConflict}.\n * @internal\n */\nexport function resolveDeclaredBackendResource(\n detected: object | undefined,\n declaration: SerializedResourceDeclaration | undefined,\n): BackendResourceAudit {\n switch (declaration?.mode) {\n case \"shared\": {\n if (detected !== undefined && detected !== declaration.resource) {\n const refusal = new ConfigurationError(\n `serializedResource declared { mode: \"shared\" } naming an object ` +\n `that is not the connection this backend was detected to run on. ` +\n `Two wrappers over one connection must name the SAME object, or ` +\n `the guards that refuse a concurrent export/import pair on it stop ` +\n `seeing them as one resource.`,\n {\n reason: \"serialized-resource-conflict\",\n declaredKind: describeSerializedResource(declaration.resource),\n detectedKind: describeSerializedResource(detected),\n },\n {\n suggestion:\n `Declare the client TypeGraph already detected (or drop the ` +\n `declaration and let detection stand). Use ` +\n `{ mode: \"independent\" } if the detection is wrong and this ` +\n `backend really does run on its own connection.`,\n },\n );\n SERIALIZED_RESOURCE_CONFLICTS.set(refusal, {\n declared: declaration.resource,\n detected,\n });\n throw refusal;\n }\n return { kind: \"serialized\", resource: declaration.resource };\n }\n case \"independent\": {\n return { kind: \"independent\", identityLeaseResource: {} };\n }\n case \"detect\":\n case undefined: {\n return detected === undefined ?\n { kind: \"independent\" }\n : { kind: \"serialized\", resource: detected };\n }\n }\n}\n\n/**\n * Records what a backend factory found about the connection its backend runs\n * on.\n *\n * INVARIANT: recorded ONCE per backend, by the factory that built it, BEFORE\n * the backend object escapes the factory body. Derived backends (deriveBackend,\n * projectBackend, projectBackendWithout, projectGraphBackend,\n * wrapWithManagedClose) carry the verdict at construction time, so a wrapper\n * built before the audit lands is silently unaudited and evades the\n * import/clone guards.\n *\n * A second call with an equal verdict is a no-op. A second call with a\n * DIFFERENT verdict throws: the stream lease reads this value and closes over\n * the resource it claimed, so a verdict that changes under a live lease\n * de-serializes a pair that really does share a connection.\n *\n * The throw is an INTERNAL invariant assertion — no library path re-audits and\n * a user cannot reach this function — so it is a plain `TypeError` naming both\n * verdicts, matching the repo's internal-assertion spelling (`requireDefined`,\n * src/utils/presence.ts). Deliberately not a `ConfigurationError`: that type is\n * user-category and would route a library bug into user-facing handling.\n *\n * @internal\n */\nexport function auditBackendResource(\n backend: GraphBackend,\n audit: BackendResourceAudit,\n): void {\n const recorded = BACKEND_RESOURCE_AUDITS.get(backend);\n if (recorded !== undefined) {\n if (auditsAgree(recorded, audit)) return;\n throw new TypeError(\n `A backend's serialized-resource audit is written once: this backend ` +\n `was audited \"${formatAudit(recorded)}\" and a conflicting audit ` +\n `\"${formatAudit(audit)}\"${\n recorded.kind === \"serialized\" && audit.kind === \"serialized\" ?\n \" naming a different connection\"\n : \"\"\n } was attempted. The stream lease closes over the resource it claimed, ` +\n `so a verdict that changes under a live lease de-serializes a pair ` +\n `that really does share a connection.`,\n );\n }\n BACKEND_RESOURCE_AUDITS.set(backend, audit);\n}\n\n/**\n * Copies a base backend's verdict onto a backend derived from it, or nothing\n * when the base carries none.\n *\n * @internal The construction seam's carry. `src/backend/derive-backend.ts` is\n * the only module allowed to import it.\n */\nexport function carryBackendResourceAudit(derived: object, base: object): void {\n const audit = BACKEND_RESOURCE_AUDITS.get(base);\n if (audit !== undefined) BACKEND_RESOURCE_AUDITS.set(derived, audit);\n}\n\n/**\n * The verdict recorded for `backend`, or `undefined` when nobody audited it.\n *\n * A pure map read: the value is written once at construction, so two reads can\n * never disagree and a lease cannot have its premise changed under it.\n *\n * @internal\n */\nexport function resolveBackendAudit(\n backend: object,\n): BackendResourceAudit | undefined {\n return BACKEND_RESOURCE_AUDITS.get(backend);\n}\n\n/**\n * How a backend's connection was classified, as a single value.\n *\n * `\"unaudited\"` is NOT a verdict about the connection: it says nobody looked.\n * Two populations are legitimately unaudited and always will be —\n * transaction-scoped backends (`transaction()`, `adoptTransaction`), which are\n * built from an operations fragment rather than derived from a root backend,\n * and `GraphBackend`s users implement themselves. So `\"unaudited\"` on an\n * arbitrary object proves nothing; on a backend one of this package's factories\n * built, or on one derived from such a backend through `derive-backend.ts`, it\n * proves the construction bypassed the seam.\n */\nexport type BackendResourceProvenance =\n \"serialized\" | \"independent\" | \"unaudited\";\n\n/**\n * The classification of `backend`'s connection — the decision itself rather\n * than a flag every caller re-derives from {@link resolveBackendAudit}.\n *\n * @internal\n */\nexport function backendResourceProvenance(\n backend: object,\n): BackendResourceProvenance {\n return resolveBackendAudit(backend)?.kind ?? \"unaudited\";\n}\n\n/** Whether two backend wrappers cannot make snapshot reads and writes concurrently. */\nexport function sharesSerializedTransactionResource(\n left: GraphBackend,\n right: GraphBackend,\n): boolean {\n const leftAudit = resolveBackendAudit(left);\n if (leftAudit?.kind !== \"serialized\") return false;\n const rightAudit = resolveBackendAudit(right);\n // Resource identity, not audit-record identity: two audits naming the same\n // client object are the same connection however they were recorded.\n return (\n rightAudit?.kind === \"serialized\" &&\n leftAudit.resource === rightAudit.resource\n );\n}\n\n/** How a snapshot export on one backend contends with a write on another. */\nexport type SnapshotExportContention =\n \"same-sqlite-backend\" | \"shared-resource\";\n\n/**\n * Whether a snapshot export on `source` would hold the one connection `target`\n * writes through, and via which detector. `undefined` means no contention.\n *\n * The single owner of \"a snapshot export blocks this write\": the streaming\n * import guard, and the working-copy cloner that exists to pre-empt it, both\n * ask here rather than re-deriving the arms.\n *\n * - A `transactions: false` source (SQLite `transactionMode: \"none\"`, HTTP-only\n * Postgres drivers) exports statement by statement with nothing held open, so\n * sharing its connection is merely interleaving and is never contention.\n * - Object identity on a SQLite backend is checked FIRST, so a marked\n * better-sqlite3 backend exporting into itself reports the more specific\n * detector even though the shared-resource arm would also match.\n */\nexport function snapshotExportContention(\n source: GraphBackend,\n target: GraphBackend,\n): SnapshotExportContention | undefined {\n if (!source.capabilities.transactions) return undefined;\n if (source === target && source.dialect === \"sqlite\") {\n return \"same-sqlite-backend\";\n }\n if (sharesSerializedTransactionResource(source, target)) {\n return \"shared-resource\";\n }\n return undefined;\n}\n\n/**\n * Claims the serialized resource `backend` runs on for a long-lived stream of\n * `kind`, or reports which kind of stream already holds it.\n *\n * EXCLUSIVE: one stream per serialized resource, whatever its kind. Two exports\n * nest their snapshot transactions on the one connection exactly as an export\n * and an import do, so \"is a stream already running here\" — not \"is a stream of\n * the OTHER kind already running here\" — is the question the holder registry\n * answers.\n *\n * ONE SYNCHRONOUS SECTION, by construction: the lookup and the registration are\n * in this function's body with no `await` between them, and there is no separate\n * \"is it free?\" query a caller could read and then act on later. On a\n * single-threaded event loop that makes \"no other stream held this connection\n * when this one claimed it\" true for the whole stream, in whichever order two\n * streams start — the second one always finds the first's registration.\n *\n * A known serialized resource is the normal lease key. A transactional SQLite\n * backend audited `independent` instead uses its own identity: the declaration\n * can separate distinct wrappers, but cannot make two streams on ONE backend\n * object use different handles. An unaudited backend, and an independent\n * Postgres backend, registers nothing (see the residual gap in the module doc).\n *\n * The acquired arm reports the resource it registered under, so a caller reads\n * the decision instead of re-deriving it from the backend; `undefined` is the\n * no-op arm. The returned release is idempotent and deletes only its own\n * registration, so an already-released stream can never evict the next\n * stream's lease.\n */\nfunction streamLeaseResource(backend: GraphBackend): object | undefined {\n const audit = resolveBackendAudit(backend);\n if (audit?.kind === \"serialized\") return audit.resource;\n if (\n audit?.kind === \"independent\" &&\n audit.identityLeaseResource !== undefined &&\n backend.dialect === \"sqlite\" &&\n backend.capabilities.transactions\n ) {\n return audit.identityLeaseResource;\n }\n return undefined;\n}\n\nexport function acquireSerializedStreamLease(\n backend: GraphBackend,\n kind: SerializedStreamKind,\n): SerializedStreamLease {\n const resource = streamLeaseResource(backend);\n if (resource === undefined) {\n return {\n acquired: true,\n resource: undefined,\n release: () => {\n // Nothing was registered: this backend has no known serialized\n // resource, so there is nothing to give back.\n },\n };\n }\n const holder = ACTIVE_SERIALIZED_STREAMS.get(resource);\n if (holder !== undefined) return { acquired: false, heldBy: holder };\n ACTIVE_SERIALIZED_STREAMS.set(resource, kind);\n let released = false;\n return {\n acquired: true,\n resource,\n release: () => {\n if (released) return;\n released = true;\n ACTIVE_SERIALIZED_STREAMS.delete(resource);\n },\n };\n}\n","/**\n * The one construction seam for derived backends.\n *\n * Every backend the library builds FROM another backend — an overlay, an\n * allowlist projection, a narrowing-by-omission, a managed-close wrapper — is\n * built here, and every constructor in this module carries the source's\n * serialized-resource audit onto the object it returns. Raw `{ ...backend }`,\n * `Object.assign` and rest-omission construction build a NEW object the audit\n * does not follow, which is the defect this module exists to make unreachable:\n * a derived backend that lost its mark reads as unowned, and the import/clone\n * guards then let a read-and-write-through-one-connection stream proceed into a\n * deadlock.\n *\n * This is the only module that imports {@link carryBackendResourceAudit}.\n *\n * Naming convention this module's ratchet depends on: an identifier ending in\n * `Backend` denotes a whole backend object; a members fragment is named\n * `*Members`.\n */\nimport {\n GRAPH_BACKEND_PROJECTION_KEYS,\n type ProjectedGraphBackendKey,\n} from \"./graph-backend-keys\";\nimport { carryBackendResourceAudit } from \"./transaction-resource\";\nimport {\n type AdapterBackend,\n type GraphBackend,\n type TransactionBackend,\n} from \"./types\";\n\n/**\n * Rejects overlay members that are not members of the decorated backend, so a\n * misspelled override cannot silently add a property nothing forwards to.\n *\n * @internal\n */\nexport type ExactBackendOverlay<T extends object, O extends Partial<T>> = O &\n Readonly<Record<Exclude<keyof O, keyof T>, never>>;\n\n/**\n * Decorates a backend with overlay members without copying it.\n *\n * This is a decoration primitive: every non-overridden target property remains\n * reachable. Never use it to narrow a capability surface; construct an\n * explicit allowlist projection first, then decorate that projection.\n *\n * Backend wrappers use this instead of object spread so proxy backends keep\n * getters and non-enumerable members, and so the derived object carries the\n * source's serialized-resource audit. GraphBackend functions are receiver-free\n * by contract, so delegated methods are returned unchanged.\n */\nexport function deriveBackend<\n T extends GraphBackend | TransactionBackend,\n const O extends Partial<T> = Partial<T>,\n>(base: T, overrides: ExactBackendOverlay<T, O>): T {\n function hasOverlayProperty(property: PropertyKey): boolean {\n return Object.hasOwn(overrides, property);\n }\n\n const decoratedBackend = new Proxy(base, {\n get(targetObject, property) {\n if (hasOverlayProperty(property)) {\n return Reflect.get(overrides, property, overrides);\n }\n return Reflect.get(targetObject, property, targetObject);\n },\n\n has(targetObject, property) {\n return (\n hasOverlayProperty(property) || Reflect.has(targetObject, property)\n );\n },\n\n ownKeys(targetObject) {\n return [\n ...new Set([\n ...Reflect.ownKeys(targetObject),\n ...Reflect.ownKeys(overrides),\n ]),\n ];\n },\n\n getOwnPropertyDescriptor(targetObject, property) {\n if (hasOverlayProperty(property)) {\n const descriptor = Reflect.getOwnPropertyDescriptor(\n overrides,\n property,\n );\n if (descriptor === undefined) return;\n return { ...descriptor, configurable: true };\n }\n return Reflect.getOwnPropertyDescriptor(targetObject, property);\n },\n\n set(targetObject, property, value) {\n if (hasOverlayProperty(property)) {\n return Reflect.set(overrides, property, value, overrides);\n }\n return Reflect.set(targetObject, property, value, targetObject);\n },\n\n defineProperty(targetObject, property, attributes) {\n if (hasOverlayProperty(property)) {\n return Reflect.defineProperty(overrides, property, attributes);\n }\n return Reflect.defineProperty(targetObject, property, attributes);\n },\n\n deleteProperty(targetObject, property) {\n if (hasOverlayProperty(property)) {\n return Reflect.deleteProperty(overrides, property);\n }\n return Reflect.deleteProperty(targetObject, property);\n },\n });\n carryBackendResourceAudit(decoratedBackend, base);\n return decoratedBackend;\n}\n\n/**\n * Copies exactly `keys` off `base` into a fresh object.\n *\n * Generic over the SOURCE's own type, so a structurally wider input keeps the\n * declared types of the members it does provide. Keys the source does not\n * carry stay absent rather than becoming `undefined` members.\n *\n * @internal\n */\nexport function projectBackend<\n TBackend extends object,\n const TKey extends keyof TBackend,\n>(base: TBackend, keys: readonly TKey[]): Readonly<Pick<TBackend, TKey>> {\n const entries = keys.flatMap((key) => {\n if (!Reflect.has(base, key)) return [];\n return [[key, Reflect.get(base, key)] as const];\n });\n\n // Keys are constrained to TBackend and values are copied from that same\n // object without reshaping. Optional members remain absent.\n const projection = Object.fromEntries(entries) as Readonly<\n Pick<TBackend, TKey>\n >;\n // A projection forwards every statement to the SAME connection as its source,\n // so it owns the same serialized transaction resource. Carrying here rather\n // than at each call site keeps the verdict attached through the projections\n // built deep inside the store (recorded-time capture, hooked query backends),\n // where an import guard would otherwise see an unaudited backend and let a\n // read-and-write-through-one-connection stream proceed into a deadlock.\n carryBackendResourceAudit(projection, base);\n return projection;\n}\n\n/**\n * Every key a derived backend must retain: the source's own keys — enumerable\n * or not, string or symbol — plus every key on its prototype chain up to, but\n * not including, `Object.prototype`.\n *\n * A class-implemented GraphBackend is a supported shape and keeps its methods\n * on the prototype, so `Reflect.ownKeys` alone would silently drop them.\n */\nfunction backendKeys<TBackend extends object>(\n base: TBackend,\n): readonly (keyof TBackend)[] {\n const keys = new Set<PropertyKey>();\n let current: object | undefined = base;\n while (current !== undefined && current !== Object.prototype) {\n for (const key of Reflect.ownKeys(current)) keys.add(key);\n current = Reflect.getPrototypeOf(current) ?? undefined;\n }\n // Every key was enumerated off `base` itself, so each one is a key of\n // TBackend at runtime; the compiler cannot narrow `PropertyKey` against an\n // unresolved type parameter.\n return [...keys] as unknown as readonly (keyof TBackend)[];\n}\n\n/**\n * Narrows a backend by omission — the seam replacement for\n * `const { omitted, ...rest } = backend`.\n *\n * Omits from the SOURCE's keys, so a structurally wider input (an\n * `AdapterBackend` with `transactionWithNative` / `adoptTransaction`) keeps\n * every member it had except the named ones.\n *\n * KEY RULE, deliberately NOT the rest destructure's rule: the retained set is\n * every own key (enumerable or not, string or symbol) PLUS every key on the\n * prototype chain up to — not including — `Object.prototype`, minus `omitted`.\n * A rest destructure copies only own ENUMERABLE keys and drops prototype\n * members; the declared `Omit<TBackend, TKey>` promises they survive, and\n * enumerating the prototype chain is what makes that promise true. Retaining\n * non-enumerable own keys is the other deliberate difference: a member hidden\n * behind a non-enumerable descriptor is still a member the wrapper forwards.\n *\n * @internal\n */\nexport function projectBackendWithout<\n TBackend extends object,\n const TKey extends keyof TBackend,\n>(base: TBackend, omitted: readonly TKey[]): Omit<TBackend, TKey> {\n const excluded = new Set<PropertyKey>(omitted);\n const retained = backendKeys(base).filter((key) => !excluded.has(key));\n return projectBackend(base, retained);\n}\n\n/**\n * Creates a runtime GraphBackend projection.\n *\n * Structurally wider inputs (for example AdapterBackend) lose every property\n * not named by the portable GraphBackend allowlist. Optional port members stay\n * absent when the source does not provide them.\n *\n * @internal\n */\nexport function projectGraphBackend(base: GraphBackend): GraphBackend {\n return projectBackend<GraphBackend, ProjectedGraphBackendKey>(\n base,\n GRAPH_BACKEND_PROJECTION_KEYS,\n );\n}\n\n/**\n * Wraps a GraphBackend with idempotent close that also runs a teardown\n * callback (e.g. closing the underlying database connection).\n */\nexport function wrapWithManagedClose<TNativeTransaction>(\n backend: AdapterBackend<TNativeTransaction>,\n teardown: () => void | Promise<void>,\n): AdapterBackend<TNativeTransaction>;\nexport function wrapWithManagedClose(\n backend: GraphBackend,\n teardown: () => void | Promise<void>,\n): GraphBackend;\nexport function wrapWithManagedClose(\n backend: GraphBackend,\n teardown: () => void | Promise<void>,\n): GraphBackend {\n let backendClosed = false;\n let teardownComplete = false;\n let closeInFlight: Promise<void> | undefined;\n\n async function closeManagedResources(): Promise<void> {\n const errors: unknown[] = [];\n if (!backendClosed) {\n try {\n await backend.close();\n backendClosed = true;\n } catch (error) {\n errors.push(error);\n }\n }\n if (!teardownComplete) {\n try {\n await teardown();\n teardownComplete = true;\n } catch (error) {\n errors.push(error);\n }\n }\n\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) {\n throw new AggregateError(\n errors,\n \"The backend and its managed resource both failed to close.\",\n );\n }\n }\n\n const closeOverlay: Pick<GraphBackend, \"close\"> = {\n async close(): Promise<void> {\n if (backendClosed && teardownComplete) return;\n closeInFlight ??= closeManagedResources().finally(() => {\n closeInFlight = undefined;\n });\n await closeInFlight;\n },\n };\n return deriveBackend(backend, closeOverlay);\n}\n","/**\n * Cross-dialect detection of \"this relation does not exist yet\" errors.\n *\n * Shared so the schema bootstrap (`loadActiveSchemaWithBootstrap`) and\n * the durable contribution-materialization gate (#135) agree on what a\n * missing-table failure looks like, and — critically — so neither one\n * swallows a genuine system fault (connection/permission/driver error)\n * as a benign \"not bootstrapped yet\".\n *\n * Detection walks the error's `cause` chain because Drizzle (>= the\n * `DrizzleQueryError` era, drizzle-orm ≥ 0.36) wraps every failure from a\n * query-builder call (`db.select()`, `db.insert()`, …): the wrapper's\n * `.message` becomes the failed query text and the real driver error —\n * which carries both the missing-relation text and the SQLSTATE — is\n * preserved on `.cause`. node-postgres / postgres-js nest the pg error\n * one link deep; better-sqlite3 throws it unwrapped; raw `client.query()`\n * fast paths surface it directly. Walking the chain makes the check\n * wrapper- and driver-agnostic instead of only matching the outermost\n * `.message`, which on Postgres is just the SQL string.\n */\n\nimport { ConfigurationError } from \"../errors\";\n\nconst SQLITE_MISSING_TABLE_PATTERN = \"no such table\";\nconst SQLITE_GENERIC_ERROR_CODE = \"SQLITE_ERROR\";\nconst SQLITE_NOT_AUTHORIZED_CODE = \"SQLITE_AUTH\";\n\n/**\n * SQLite's EXTENDED result code for \"this read transaction cannot become a\n * write transaction\": the connection began a DEFERRED transaction, took a read\n * snapshot, and another connection has committed since. SQLite refuses the\n * upgrade because honoring it would let the writer act on a stale view; the\n * only recovery is `ROLLBACK` and a fresh transaction (SQLite's own rule — the\n * failure is not retryable in place).\n *\n * It is the one code that names the DEFERRED frame itself. A transaction opened\n * `BEGIN IMMEDIATE` holds the writer slot from the start and can never produce\n * it, and plain `SQLITE_BUSY` says something else entirely (\"another writer\n * holds the slot right now\"), so this code alone can be attributed to how the\n * transaction was begun. The numeric spelling is accepted for libSQL, which\n * surfaces only `rawCode`/`extendedCode` over a remote connection.\n */\nconst SQLITE_STALE_SNAPSHOT_CODE = \"SQLITE_BUSY_SNAPSHOT\";\nconst SQLITE_STALE_SNAPSHOT_EXTENDED_CODE = 517;\nconst DRIZZLE_QUERY_ERROR_PREFIX = \"Failed query:\";\nconst POSTGRES_UNDEFINED_RELATION_PATTERN =\n /\\b(?:relation|table)\\s+\"[^\"]+\"\\s+does not exist\\b/i;\n\n/**\n * SQLSTATE for PostgreSQL `undefined_table`. Preferred over the\n * human-readable message: it is locale-independent (the \"... does not\n * exist\" text is translated under a non-English `lc_messages`) and is\n * preserved on the underlying driver error even when Drizzle overwrites\n * `.message` with the query text.\n */\nconst POSTGRES_UNDEFINED_TABLE_CODE = \"42P01\";\nconst POSTGRES_UNIQUE_VIOLATION_CODE = \"23505\";\n\n/**\n * SQLSTATEs a racing IDEMPOTENT DDL statement loses with — the ones that mean\n * \"another session is committing the very thing this statement asks for\", not\n * \"this statement is wrong\".\n *\n * PostgreSQL's `IF NOT EXISTS` is not a concurrency primitive: the existence\n * check cannot see another session's uncommitted catalog rows, so the loser\n * waits for the winner and is then handed the conflict the winner's commit\n * produced — `unique_violation` (23505) from `pg_type`/`pg_class` for a racing\n * CREATE, `duplicate_column` (42701) for a racing `ALTER TABLE ... ADD COLUMN\n * IF NOT EXISTS`. Retrying once after that wait observes the committed object\n * and succeeds; a failure the retry cannot clear stays loud.\n */\nconst POSTGRES_CONCURRENT_DDL_RACE_SQL_STATES = [\n POSTGRES_UNIQUE_VIOLATION_CODE,\n \"42701\",\n] as const;\n\n/**\n * The one concurrent-DDL race PostgreSQL reports with no SQLSTATE of its own:\n * `heap_update` losing a catalog row to a concurrent updater raises\n * `elog(ERROR, \"tuple concurrently updated\")`, which carries the catch-all\n * `internal_error` (XX000).\n *\n * XX000 alone is far too broad to retry on — it covers genuine server faults —\n * so this shape is identified by SQLSTATE AND message together. Matching the\n * message is sound here specifically because `elog` emits it through\n * `errmsg_internal`, which is NOT run through gettext: unlike an `ereport`\n * message, it reads identically under every `lc_messages`.\n */\nconst POSTGRES_INTERNAL_ERROR_CODE = \"XX000\";\nconst POSTGRES_CONCURRENT_TUPLE_UPDATE_MESSAGE = \"tuple concurrently updated\";\n\n/**\n * PostgreSQL failures that mean a temporary table cannot be created here:\n * `read_only_sql_transaction` (a replica or otherwise read-only execution\n * context) and `insufficient_privilege` (a role without the database `TEMP`\n * privilege).\n */\nconst POSTGRES_TEMPORARY_TABLE_UNAVAILABLE_SQL_STATES = [\n \"25006\",\n \"42501\",\n] as const;\n\n/**\n * PostgreSQL failures that mean the read-write transaction hosting temporary\n * tables cannot even start. A standby rejects the read-write access mode in\n * the `BEGIN` itself with `feature_not_supported` (\"cannot set transaction\n * read-write mode during recovery\"), so the failure never reaches a\n * `CREATE TEMP TABLE`; a session pinned read-only by a proxy or by\n * `default_transaction_read_only` reports `read_only_sql_transaction`.\n */\nconst POSTGRES_READ_WRITE_REFUSED_SQL_STATES = [\"0A000\", \"25006\"] as const;\n\nexport type PostgresTemporaryTableUnavailableSqlState =\n (typeof POSTGRES_TEMPORARY_TABLE_UNAVAILABLE_SQL_STATES)[number];\n\nexport type PostgresReadWriteRefusedSqlState =\n (typeof POSTGRES_READ_WRITE_REFUSED_SQL_STATES)[number];\n\n/**\n * Yields an error and each error reachable by following `.cause`,\n * outermost first. `seen` guards the pathological cyclic-cause case so a\n * self-referential chain can't spin forever.\n *\n * The walk intentionally follows `.cause` through *non-`Error`* links, not just\n * `Error` instances: postgres-js surfaces its driver error as a plain object\n * (message + SQLSTATE `code`) on a Drizzle wrapper's `.cause`, so stopping at\n * the first non-`Error` link would miss it (see the postgres-js test). A plain\n * object is classified by its locale-independent SQLSTATE alone\n * ({@link isPostgresUndefinedTable}); the looser SQLite message substring is\n * consulted only for `Error` instances and raw strings\n * ({@link missingTableMessage}), so an unrelated object in a cause chain that\n * merely mentions one of those phrases is not mistaken for a missing table.\n */\nexport function* errorChain(error: unknown): Generator<unknown, void, void> {\n const seen = new Set<unknown>();\n let current: unknown = error;\n while (current !== undefined && current !== null && !seen.has(current)) {\n seen.add(current);\n yield current;\n current =\n canReadProperty(current) ? Reflect.get(current, \"cause\") : undefined;\n }\n}\n\nfunction canReadProperty(value: unknown): value is object {\n return (\n (typeof value === \"object\" && value !== null) || typeof value === \"function\"\n );\n}\n\n/**\n * Whether a single chain link is a PostgreSQL `undefined_table` failure,\n * identified by its SQLSTATE rather than a message substring.\n */\nfunction isPostgresUndefinedTable(link: unknown): boolean {\n return (\n canReadProperty(link) &&\n Reflect.get(link, \"code\") === POSTGRES_UNDEFINED_TABLE_CODE\n );\n}\n\nfunction messageProperty(link: unknown): string | undefined {\n if (typeof link === \"string\") return link;\n if (link instanceof Error) return link.message;\n const message =\n canReadProperty(link) ?\n (Reflect.get(link, \"message\") as unknown)\n : undefined;\n return typeof message === \"string\" ? message : undefined;\n}\n\nfunction errorMessage(link: unknown): string {\n return messageProperty(link) ?? String(link);\n}\n\n/**\n * The message a SQLite missing-table substring match may be tested against — but\n * only for `Error` instances and raw `string` links, never an arbitrary plain\n * object.\n *\n * Generic \"does not exist\" is deliberately not substring-matched: PostgreSQL uses\n * that phrase for undefined columns, functions, types, and relations. PostgreSQL\n * missing tables are classified by SQLSTATE 42P01 when available, or by the\n * narrower driver-message shape `relation/table \"...\" does not exist` when a\n * bring-your-own driver omits SQLSTATE. SQLite does not expose a portable\n * SQLSTATE here, so the narrow \"no such table\" engine message is still accepted.\n */\nfunction missingTableMessage(link: unknown): string | undefined {\n return typeof link === \"string\" || link instanceof Error ?\n messageProperty(link)\n : undefined;\n}\n\nfunction sqliteErrorCode(link: unknown): unknown {\n if (!canReadProperty(link)) return undefined;\n return Reflect.get(link, \"code\");\n}\n\n/**\n * Cloudflare D1 / Durable Objects may surface a missing-table failure as the\n * generic SQLite code with no detail. Accept the bare marker, but do not\n * substring-match detailed `SQLITE_ERROR: ...` failures: those include syntax\n * errors and bind-limit faults that must stay loud.\n */\nfunction isBareSqliteErrorMarker(link: unknown): boolean {\n const message = messageProperty(link);\n if (message === SQLITE_GENERIC_ERROR_CODE) return true;\n if (sqliteErrorCode(link) !== SQLITE_GENERIC_ERROR_CODE) return false;\n return (\n message === undefined ||\n message === SQLITE_GENERIC_ERROR_CODE ||\n message.includes(SQLITE_MISSING_TABLE_PATTERN)\n );\n}\n\nfunction isPostgresUndefinedRelationMessage(link: unknown): boolean {\n const message = errorMessage(link);\n if (message.startsWith(DRIZZLE_QUERY_ERROR_PREFIX)) return false;\n return POSTGRES_UNDEFINED_RELATION_PATTERN.test(message);\n}\n\n/**\n * Whether any link in the cause chain is a PostgreSQL \"insufficient\n * resources\" failure (SQLSTATE class 53: disk_full, out_of_memory,\n * configuration_limit_exceeded, ...). Parallel index builds surface\n * shared-memory exhaustion this way (53100 from dsm_impl_posix on hosts\n * with a small /dev/shm); callers retry such work with parallelism\n * disabled. Identified by the locale-independent 5-character SQLSTATE\n * prefix only — never by message text.\n */\nexport function isInsufficientResourcesError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (!canReadProperty(link)) continue;\n const code: unknown = Reflect.get(link, \"code\");\n if (typeof code === \"string\" && code.length === 5 && code.startsWith(\"53\"))\n return true;\n }\n return false;\n}\n\nexport function isMissingTableError(error: unknown): boolean {\n // SQLSTATE 42P01 is locale-independent and structural, so it is honored on\n // *every* link — including a plain driver-error object reached only by walking\n // through a non-`Error` `.cause` (postgres-js).\n //\n // The SQLite message substring is honored only while every prior link in the\n // chain was an `Error` (or the top-level string) — the reach of the\n // pre-broadening walk, which stopped at the first non-`Error` `.cause`.\n let everyPriorLinkWasError = true;\n for (const link of errorChain(error)) {\n if (isPostgresUndefinedTable(link)) return true;\n if (isPostgresUndefinedRelationMessage(link)) return true;\n if (isBareSqliteErrorMarker(link)) return true;\n if (everyPriorLinkWasError) {\n const message = missingTableMessage(link);\n if (message?.includes(SQLITE_MISSING_TABLE_PATTERN) === true) {\n return true;\n }\n }\n if (!(link instanceof Error)) everyPriorLinkWasError = false;\n }\n return false;\n}\n\n/** Whether one chain link is the un-coded `tuple concurrently updated` race. */\nfunction isPostgresConcurrentTupleUpdate(link: unknown): boolean {\n if (!canReadProperty(link)) return false;\n if (Reflect.get(link, \"code\") !== POSTGRES_INTERNAL_ERROR_CODE) return false;\n return (\n messageProperty(link)?.includes(\n POSTGRES_CONCURRENT_TUPLE_UPDATE_MESSAGE,\n ) === true\n );\n}\n\n/**\n * Whether PostgreSQL refused an IDEMPOTENT DDL statement because another\n * session was concurrently committing the same catalog change — the single\n * owner of \"this DDL lost a race and is worth one retry\".\n *\n * Every idempotent-DDL site in the codebase classifies through this one\n * function: the Postgres backend's `executeConcurrentCreateDdl` (bootstrap\n * tables, contribution materialization, identity relations, the index\n * materialization table and its additive columns) and the identity\n * schema-transition retry. A second copy of the predicate would drift the\n * moment one site learned about a new race SQLSTATE — as `ALTER TABLE ... ADD\n * COLUMN IF NOT EXISTS` (42701) did (#445).\n *\n * Callers MUST use it only around DDL that is a no-op when the object already\n * exists. On any other statement 23505/42701 are real defects, and retrying\n * them would hide a duplicate write.\n */\nexport function isPostgresConcurrentDdlRaceError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (!canReadProperty(link)) continue;\n if (\n isSqlStateIn(\n Reflect.get(link, \"code\"),\n POSTGRES_CONCURRENT_DDL_RACE_SQL_STATES,\n )\n ) {\n return true;\n }\n if (isPostgresConcurrentTupleUpdate(link)) return true;\n }\n return false;\n}\n\n/**\n * The PostgreSQL error fields naming the violated constraint and its relation.\n * Both spellings are read because the drivers disagree: node-postgres and\n * PGlite expose the protocol fields as `constraint` / `table`, while\n * postgres-js exposes them as `constraint_name` / `table_name`. Reading only\n * one spelling would silently classify nothing on the other driver.\n */\nconst POSTGRES_CONSTRAINT_FIELDS = [\"constraint\", \"constraint_name\"] as const;\nconst POSTGRES_RELATION_FIELDS = [\"table\", \"table_name\"] as const;\n\n/**\n * SQLite's EXTENDED result code for a primary-key duplicate, in both spellings a\n * driver reports it: the symbolic name (better-sqlite3 `code`, and the\n * `SqliteError` the libSQL client nests on its own error's `.cause`) and the\n * numeric value (libSQL `rawCode` / `extendedCode`, the only form a remote\n * connection surfaces).\n *\n * The extended code — not the base `SQLITE_CONSTRAINT` — is what makes the\n * classification possible at all: SQLite distinguishes a PRIMARY KEY duplicate\n * (1555) from any other unique-index duplicate (`SQLITE_CONSTRAINT_UNIQUE`,\n * 2067) in the code itself, so nothing has to read the message, which names the\n * columns rather than the constraint.\n */\nconst SQLITE_PRIMARY_KEY_VIOLATION_CODE = \"SQLITE_CONSTRAINT_PRIMARYKEY\";\nconst SQLITE_PRIMARY_KEY_VIOLATION_EXTENDED_CODE = 1555;\nconst SQLITE_EXTENDED_CODE_FIELDS = [\"rawCode\", \"extendedCode\"] as const;\n\n/**\n * A relation plus the names its PRIMARY KEY constraint can carry — how far a\n * duplicate-key classification is allowed to reach on an engine that reports the\n * violated constraint by name. See {@link isDuplicatePrimaryKeyError}.\n */\nexport type PrimaryKeyRelation = Readonly<{\n table: string;\n constraintNames: readonly string[];\n}>;\n\nfunction firstStringField(\n link: object,\n fields: readonly string[],\n): string | undefined {\n for (const field of fields) {\n const value: unknown = Reflect.get(link, field);\n if (typeof value === \"string\") return value;\n }\n return undefined;\n}\n\n/**\n * Whether PostgreSQL reported this link as a duplicate of `relation`'s PRIMARY\n * KEY: SQLSTATE, relation, and constraint name must all agree on the SAME link\n * (the driver error), so a 23505 raised by an unrelated statement deeper in the\n * chain cannot be attributed to this relation.\n */\nfunction isPostgresPrimaryKeyViolation(\n link: object,\n relation: PrimaryKeyRelation,\n): boolean {\n if (Reflect.get(link, \"code\") !== POSTGRES_UNIQUE_VIOLATION_CODE)\n return false;\n if (firstStringField(link, POSTGRES_RELATION_FIELDS) !== relation.table) {\n return false;\n }\n const constraint = firstStringField(link, POSTGRES_CONSTRAINT_FIELDS);\n return (\n constraint !== undefined && relation.constraintNames.includes(constraint)\n );\n}\n\n/**\n * Whether SQLite reported this link as a PRIMARY KEY duplicate. The relation is\n * not checked because SQLite does not report one — see\n * {@link isDuplicatePrimaryKeyError} for why the call site supplies that scope.\n */\nfunction isSqlitePrimaryKeyViolation(link: object): boolean {\n if (Reflect.get(link, \"code\") === SQLITE_PRIMARY_KEY_VIOLATION_CODE) {\n return true;\n }\n for (const field of SQLITE_EXTENDED_CODE_FIELDS) {\n const value: unknown = Reflect.get(link, field);\n if (\n typeof value === \"number\" &&\n value === SQLITE_PRIMARY_KEY_VIOLATION_EXTENDED_CODE\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Whether the engine refused a statement because it duplicated a PRIMARY KEY —\n * on PostgreSQL, `relation`'s specifically.\n *\n * Classification is structural: SQLSTATE and SQLite extended result codes, plus\n * the PostgreSQL protocol's own constraint and relation fields. Never message\n * text, which is translated under a non-English `lc_messages`, is overwritten\n * with the query string by Drizzle's wrapper, and on SQLite names the key's\n * COLUMNS rather than the constraint. The `.cause` chain is walked because every\n * driver here nests the real error under at least one wrapper.\n *\n * Narrowing to the primary key is the whole point. A `unique: true` index\n * declaration materializes a UNIQUE INDEX on the same relation, and violating\n * THAT is a declared-uniqueness failure about the row's VALUES, not a duplicate\n * identity. PostgreSQL reports it under the index's own name and SQLite under a\n * different extended code, so it never matches here and keeps surfacing as it\n * did before.\n *\n * `relation` scopes the PostgreSQL arm, which is the one that can see a\n * constraint name. SQLite reports no relation at all, so its scope comes from\n * the CALL SITE instead: callers must invoke this only for a statement that\n * writes exactly one relation — the node or edge insert — where a primary-key\n * duplicate can only be that relation's. Applying it to a multi-relation\n * statement would attribute the wrong table's collision.\n */\nexport function isDuplicatePrimaryKeyError(\n error: unknown,\n relation: PrimaryKeyRelation,\n): boolean {\n for (const link of errorChain(error)) {\n if (!canReadProperty(link)) continue;\n if (isPostgresPrimaryKeyViolation(link, relation)) return true;\n if (isSqlitePrimaryKeyViolation(link)) return true;\n }\n return false;\n}\n\nfunction isSqlStateIn<SqlState extends string>(\n code: unknown,\n states: readonly SqlState[],\n): code is SqlState {\n const known: readonly string[] = states;\n return typeof code === \"string\" && known.includes(code);\n}\n\n/**\n * The first SQLSTATE in the error's cause chain that belongs to `states`. The\n * walk handles both direct driver errors and wrappers such as\n * DrizzleQueryError, which keeps the SQLSTATE-bearing error on `.cause`.\n */\nfunction matchSqlState<SqlState extends string>(\n error: unknown,\n states: readonly SqlState[],\n): SqlState | undefined {\n for (const link of errorChain(error)) {\n if (!canReadProperty(link)) continue;\n const code: unknown = Reflect.get(link, \"code\");\n if (isSqlStateIn(code, states)) return code;\n }\n return undefined;\n}\n\n/**\n * Returns the PostgreSQL SQLSTATE that prevented temporary-table creation.\n *\n * Callers must use this only at a `CREATE TEMP TABLE` execution seam: 42501\n * is otherwise a generic permission failure, and translating it elsewhere\n * would hide a different authorization problem.\n */\nexport function postgresTemporaryTableUnavailableSqlState(\n error: unknown,\n): PostgresTemporaryTableUnavailableSqlState | undefined {\n return matchSqlState(error, POSTGRES_TEMPORARY_TABLE_UNAVAILABLE_SQL_STATES);\n}\n\n/**\n * Returns the PostgreSQL SQLSTATE with which the server refused to open a\n * read-write transaction.\n *\n * Callers must use this only for a failure raised while opening such a\n * transaction — 0A000 is otherwise a generic \"unsupported feature\" report\n * that any statement can raise.\n */\nexport function postgresReadWriteRefusedSqlState(\n error: unknown,\n): PostgresReadWriteRefusedSqlState | undefined {\n return matchSqlState(error, POSTGRES_READ_WRITE_REFUSED_SQL_STATES);\n}\n\n/**\n * Whether SQLite rejected a statement through its authorizer. Cloudflare D1\n * and Durable Objects surface this as `not authorized: SQLITE_AUTH`, usually on\n * a Drizzle wrapper's `.cause`; native drivers may instead expose\n * `code: \"SQLITE_AUTH\"`. Both shapes are structural enough to distinguish from\n * an unrelated permission or connection failure.\n */\nexport function isSqliteNotAuthorizedError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (sqliteErrorCode(link) === SQLITE_NOT_AUTHORIZED_CODE) return true;\n const message = messageProperty(link);\n if (\n message?.includes(SQLITE_NOT_AUTHORIZED_CODE) === true &&\n message.toLowerCase().includes(\"not authorized\")\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Whether SQLite refused a write because the enclosing DEFERRED transaction's\n * read snapshot went stale before it could take the writer slot\n * ({@link SQLITE_STALE_SNAPSHOT_CODE}).\n *\n * Classified structurally — the extended result code in either spelling a\n * driver reports it (better-sqlite3's symbolic `code`, libSQL's numeric\n * `rawCode`/`extendedCode`) — and never by message: SQLite renders this as the\n * bare, indistinguishable \"database is locked\".\n */\nexport function isSqliteStaleSnapshotError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (sqliteErrorCode(link) === SQLITE_STALE_SNAPSHOT_CODE) return true;\n if (!canReadProperty(link)) continue;\n for (const field of SQLITE_EXTENDED_CODE_FIELDS) {\n if (Reflect.get(link, field) === SQLITE_STALE_SNAPSHOT_EXTENDED_CODE) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction historyMissingRecordedRelationsError(\n details: Record<string, unknown>,\n cause: unknown,\n): ConfigurationError {\n return new ConfigurationError(\n \"history: true requires the recorded-time relations to exist, but a recorded relation is missing.\",\n details,\n {\n cause,\n suggestion:\n \"Create the recorded-time relations (typegraph_recorded_nodes, typegraph_recorded_edges, typegraph_recorded_clock) — e.g. re-run the generated migration SQL — on this database before enabling history capture.\",\n },\n );\n}\n\n/**\n * Converts missing recorded-relation failures into the actionable precondition\n * error used by construction-time history checks. Capture paths use this after\n * the live write has already succeeded inside the same transaction; recorded\n * read paths use it when query/schema swapping reaches a recorded table that\n * has not been materialized yet.\n */\nexport async function withRecordedRelationsPrecondition<T>(\n promise: Promise<T>,\n details: Record<string, unknown>,\n): Promise<T> {\n try {\n return await promise;\n } catch (error) {\n if (!isMissingTableError(error)) throw error;\n throw historyMissingRecordedRelationsError(\n { ...details, code: \"RECORDED_RELATIONS_MISSING\" },\n error,\n );\n }\n}\n\n/**\n * Engine \"vector dimension mismatch\" message shapes. pgvector:\n * `expected 384 dimensions, not 512`; libSQL / sqlite-vec surface a similar\n * `expected N … got/not M`. The first capture is the dimension the *stored*\n * column expects; the optional second is the dimension that was *attempted*.\n */\nconst DIMENSION_MISMATCH_PATTERN =\n /expected (\\d+) dimensions(?:[,\\s]+(?:not|got|but got|but)\\s*(\\d+))?/i;\n\n/**\n * Parses an engine vector-dimension-mismatch error into `{ expected, actual }`\n * by walking the `.cause` chain (drivers wrap the real error). `expected` is\n * the stored column's dimension; `actual` (when the message includes it) is the\n * attempted vector's dimension. Returns `undefined` for unrelated errors.\n */\nexport function parseDimensionMismatch(\n error: unknown,\n): { expected: number; actual: number | undefined } | undefined {\n for (const link of errorChain(error)) {\n const message = errorMessage(link);\n const match = DIMENSION_MISMATCH_PATTERN.exec(message);\n if (match) {\n return {\n expected: Number(match[1]),\n actual: match[2] === undefined ? undefined : Number(match[2]),\n };\n }\n }\n return undefined;\n}\n","/**\n * Splits `items` into consecutive chunks of at most `size` elements.\n *\n * An empty input yields no chunks (`[]`), and an input that already fits in a\n * single chunk is returned without copying. Callers rely on the empty-input\n * behavior to skip work entirely rather than issue a statement with an empty\n * `IN ()` list.\n */\nexport function chunk<T>(\n items: readonly T[],\n size: number,\n): readonly (readonly T[])[] {\n // A non-positive, non-finite, or fractional size would make the slice loop\n // fail to advance correctly; fail loud rather than spin or emit empty chunks.\n // All current callers derive size from a positive integer bind-parameter\n // budget, so this only guards against a future regression.\n if (!Number.isSafeInteger(size) || size < 1) {\n throw new RangeError(`chunk size must be a positive integer, got: ${size}`);\n }\n if (items.length === 0) return [];\n if (items.length <= size) return [items];\n const chunks: T[][] = [];\n for (let start = 0; start < items.length; start += size) {\n chunks.push(items.slice(start, start + size));\n }\n return chunks;\n}\n\n/**\n * Groups items by a caller-supplied key while preserving input order within\n * each group.\n */\nexport function groupBy<T, K>(\n items: Iterable<T>,\n keyFor: (item: T) => K,\n): Map<K, T[]> {\n const groups = new Map<K, T[]>();\n for (const item of items) {\n const key = keyFor(item);\n const group = groups.get(key) ?? [];\n group.push(item);\n groups.set(key, group);\n }\n return groups;\n}\n"]}
@@ -2,12 +2,27 @@
2
2
 
3
3
  var chunkHDL2ARHX_cjs = require('./chunk-HDL2ARHX.cjs');
4
4
  var chunk3U5ABFDW_cjs = require('./chunk-3U5ABFDW.cjs');
5
- var chunk6KFLYYOC_cjs = require('./chunk-6KFLYYOC.cjs');
6
- var chunk425IZOQ5_cjs = require('./chunk-425IZOQ5.cjs');
5
+ var chunk5PRKMB24_cjs = require('./chunk-5PRKMB24.cjs');
6
+ var chunk2QGYQBS2_cjs = require('./chunk-2QGYQBS2.cjs');
7
+ var chunkTQHGE7UC_cjs = require('./chunk-TQHGE7UC.cjs');
7
8
  var chunkL3LQNR34_cjs = require('./chunk-L3LQNR34.cjs');
8
9
  var chunkEDN4Y4ZG_cjs = require('./chunk-EDN4Y4ZG.cjs');
9
10
  var chunkMRDBBHIZ_cjs = require('./chunk-MRDBBHIZ.cjs');
10
11
 
12
+ // src/backend/table-names.ts
13
+ function definedTableNameOverrides(override) {
14
+ if (override === void 0) return {};
15
+ return Object.fromEntries(
16
+ Object.entries(override).filter(([, tableName]) => tableName !== void 0)
17
+ );
18
+ }
19
+ function resolvedTableNames(backend, override) {
20
+ return chunk3U5ABFDW_cjs.createSqlSchema({
21
+ ...backend.tableNames,
22
+ ...definedTableNameOverrides(override)
23
+ }).tables;
24
+ }
25
+
11
26
  // src/backend/migrate-recorded-time.ts
12
27
  var LEGACY_RECORDED_MAX = "9999-12-31T23:59:59.999Z";
13
28
  var MIGRATION_SUFFIX = "legacy_recorded_anchors";
@@ -52,9 +67,6 @@ var RECORDED_EDGE_COLUMNS = [
52
67
  "tx_id",
53
68
  "meta"
54
69
  ];
55
- function resolvedTableNames(backend, override) {
56
- return chunk3U5ABFDW_cjs.createSqlSchema(override ?? backend.tableNames ?? {}).tables;
57
- }
58
70
  function shortenedIdentifier(value) {
59
71
  if (value.length <= 63) return value;
60
72
  return `${value.slice(0, 50)}_${chunkL3LQNR34_cjs.shortHash(value)}`;
@@ -85,7 +97,7 @@ async function executeDdl(target, ddl) {
85
97
  await executeStatement(target, chunkEDN4Y4ZG_cjs.sql.raw(ddl));
86
98
  }
87
99
  function canonicalLegacyInstant(value) {
88
- const canonical = chunk425IZOQ5_cjs.canonicalizeDatabaseTimestamp(value);
100
+ const canonical = chunkTQHGE7UC_cjs.canonicalizeDatabaseTimestamp(value);
89
101
  if (canonical === void 0) {
90
102
  throw new chunkMRDBBHIZ_cjs.ConfigurationError(
91
103
  "Legacy recorded-time relation contained an invalid timestamp.",
@@ -96,7 +108,7 @@ function canonicalLegacyInstant(value) {
96
108
  }
97
109
  function safeRevision(value) {
98
110
  const revision = typeof value === "bigint" ? Number(value) : typeof value === "string" && /^\d+$/.test(value) ? Number(value) : value;
99
- if (typeof revision !== "number" || !Number.isSafeInteger(revision) || revision < 1 || revision >= chunk6KFLYYOC_cjs.RECORDED_MAX_REVISION) {
111
+ if (typeof revision !== "number" || !Number.isSafeInteger(revision) || revision < 1 || revision >= chunk2QGYQBS2_cjs.RECORDED_MAX_REVISION) {
100
112
  throw new chunkMRDBBHIZ_cjs.ConfigurationError(
101
113
  "Recorded anchor mapping contained an invalid revision.",
102
114
  { value }
@@ -260,7 +272,7 @@ function migratedColumn(column, legacyAlias) {
260
272
  return chunkEDN4Y4ZG_cjs.sql`
261
273
  CASE
262
274
  WHEN ${chunkEDN4Y4ZG_cjs.sql.raw(legacyAlias)}.recorded_to = ${LEGACY_RECORDED_MAX}
263
- THEN ${chunk6KFLYYOC_cjs.RECORDED_MAX_REVISION}
275
+ THEN ${chunk2QGYQBS2_cjs.RECORDED_MAX_REVISION}
264
276
  ELSE to_map.revision
265
277
  END
266
278
  `;
@@ -534,7 +546,7 @@ async function migrateLegacyRecordedTime(options) {
534
546
  }
535
547
  async function migrateRecordedAnchor(options) {
536
548
  try {
537
- return chunk6KFLYYOC_cjs.asRecordedInstant(options.anchor);
549
+ return chunk2QGYQBS2_cjs.asRecordedInstant(options.anchor);
538
550
  } catch (error) {
539
551
  if (!(error instanceof chunkMRDBBHIZ_cjs.ValidationError)) throw error;
540
552
  }
@@ -559,7 +571,7 @@ async function migrateRecordedAnchor(options) {
559
571
  }
560
572
  );
561
573
  }
562
- return chunk6KFLYYOC_cjs.createRecordedInstant(
574
+ return chunk2QGYQBS2_cjs.createRecordedInstant(
563
575
  safeRevision(row.revision),
564
576
  canonicalLegacyInstant(row.recorded_at)
565
577
  );
@@ -598,8 +610,197 @@ async function deleteLegacyRecordedAnchorMap(options) {
598
610
  });
599
611
  }
600
612
 
613
+ // src/backend/repair-validity-windows.ts
614
+ var LIVE_RELATIONS = [
615
+ "nodes",
616
+ "edges"
617
+ ];
618
+ var RECORDED_RELATIONS = [
619
+ "recordedNodes",
620
+ "recordedEdges"
621
+ ];
622
+ var CANONICAL_INSTANT_GLOB = "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z";
623
+ function scopedRelations(scope) {
624
+ return scope === "live" ? LIVE_RELATIONS : [...LIVE_RELATIONS, ...RECORDED_RELATIONS];
625
+ }
626
+ function relationTable(tables, relation) {
627
+ switch (relation) {
628
+ case "nodes": {
629
+ return tables.nodes;
630
+ }
631
+ case "edges": {
632
+ return tables.edges;
633
+ }
634
+ case "recordedNodes": {
635
+ return tables.recordedNodes;
636
+ }
637
+ case "recordedEdges": {
638
+ return tables.recordedEdges;
639
+ }
640
+ }
641
+ }
642
+ function graphScopeClauses(graphId) {
643
+ return graphId === void 0 ? [] : [chunkEDN4Y4ZG_cjs.sql`graph_id = ${graphId}`];
644
+ }
645
+ function canonicalBoundsClauses(dialect) {
646
+ if (dialect !== "sqlite") return [];
647
+ return [
648
+ chunkEDN4Y4ZG_cjs.sql`valid_from GLOB ${CANONICAL_INSTANT_GLOB}`,
649
+ chunkEDN4Y4ZG_cjs.sql`valid_to GLOB ${CANONICAL_INSTANT_GLOB}`
650
+ ];
651
+ }
652
+ function invertedValidityWindowPredicate(options) {
653
+ return chunkEDN4Y4ZG_cjs.sql.join(
654
+ [
655
+ chunkEDN4Y4ZG_cjs.sql`valid_from IS NOT NULL`,
656
+ chunkEDN4Y4ZG_cjs.sql`valid_to IS NOT NULL`,
657
+ ...canonicalBoundsClauses(options.dialect),
658
+ chunkEDN4Y4ZG_cjs.sql`valid_from > valid_to`,
659
+ ...graphScopeClauses(options.graphId)
660
+ ],
661
+ chunkEDN4Y4ZG_cjs.sql` AND `
662
+ );
663
+ }
664
+ function nonCanonicalWindowPredicate(graphId) {
665
+ return chunkEDN4Y4ZG_cjs.sql.join(
666
+ [
667
+ chunkEDN4Y4ZG_cjs.sql`valid_from IS NOT NULL`,
668
+ chunkEDN4Y4ZG_cjs.sql`valid_to IS NOT NULL`,
669
+ chunkEDN4Y4ZG_cjs.sql`(valid_from NOT GLOB ${CANONICAL_INSTANT_GLOB} OR valid_to NOT GLOB ${CANONICAL_INSTANT_GLOB})`,
670
+ ...graphScopeClauses(graphId)
671
+ ],
672
+ chunkEDN4Y4ZG_cjs.sql` AND `
673
+ );
674
+ }
675
+ function safeCount(value, table) {
676
+ const count = Number(value);
677
+ if (!Number.isSafeInteger(count) || count < 0) {
678
+ throw new chunkMRDBBHIZ_cjs.ConfigurationError(
679
+ "Validity-window repair returned an invalid row count.",
680
+ { table, value }
681
+ );
682
+ }
683
+ return count;
684
+ }
685
+ async function countMatching(target, table, predicate) {
686
+ const rows = await target.execute(
687
+ chunkEDN4Y4ZG_cjs.asCompiledRowsSql(chunkEDN4Y4ZG_cjs.sql`
688
+ SELECT COUNT(*) AS matches
689
+ FROM ${chunkEDN4Y4ZG_cjs.sql.identifier(table)}
690
+ WHERE ${predicate}
691
+ `)
692
+ );
693
+ return safeCount(rows[0]?.matches, table);
694
+ }
695
+ function requireStatements2(target) {
696
+ if (target.executeStatement === void 0) {
697
+ throw new chunkMRDBBHIZ_cjs.ConfigurationError(
698
+ "Repairing inverted validity windows requires executeStatement support.",
699
+ { dialect: target.dialect, mode: "apply" },
700
+ {
701
+ suggestion: 'Use a built-in SQLite or PostgreSQL backend to apply the repair. Detection needs no such support: call this with mode: "report" to count the affected rows on any backend.'
702
+ }
703
+ );
704
+ }
705
+ return target.executeStatement;
706
+ }
707
+ function translatedCaptureRefusal(error) {
708
+ if (!(error instanceof chunkMRDBBHIZ_cjs.ConfigurationError) || error.details["code"] !== "RECORDED_CAPTURE_RAW_SQL_DISABLED") {
709
+ return error;
710
+ }
711
+ return new chunkMRDBBHIZ_cjs.ConfigurationError(
712
+ "Repairing inverted validity windows cannot run against a history-capturing backend.",
713
+ { code: "RECORDED_CAPTURE_RAW_SQL_DISABLED", mode: "apply" },
714
+ {
715
+ cause: error,
716
+ suggestion: 'Pass the raw backend you constructed the history store from. The repair deliberately mints no revision \u2014 it normalizes storage for rows that were never visible at any coordinate \u2014 so bypassing recorded-time capture is the intended behavior, not a workaround. mode: "report" needs no such care: it runs against the capture-wrapped backend.'
717
+ }
718
+ );
719
+ }
720
+ async function repairRelation(target, table, predicate) {
721
+ try {
722
+ await requireStatements2(target)(
723
+ chunkEDN4Y4ZG_cjs.asCompiledStatementSql(chunkEDN4Y4ZG_cjs.sql`
724
+ UPDATE ${chunkEDN4Y4ZG_cjs.sql.identifier(table)}
725
+ SET valid_from = NULL
726
+ WHERE ${predicate}
727
+ `)
728
+ );
729
+ } catch (error) {
730
+ throw translatedCaptureRefusal(error);
731
+ }
732
+ }
733
+ function assertClassifiableBounds(nonCanonical) {
734
+ const unclassified = [...nonCanonical].filter(([, count]) => count > 0);
735
+ if (unclassified.length === 0) return;
736
+ throw new chunkMRDBBHIZ_cjs.ConfigurationError(
737
+ "Refusing to repair validity windows: some scanned rows store non-canonical bounds.",
738
+ { nonCanonical: Object.fromEntries(unclassified) },
739
+ {
740
+ suggestion: 'Normalize those bounds to canonical UTC ISO 8601 (YYYY-MM-DDTHH:MM:SS.mmmZ) and re-run, or narrow the call with graphId. Classifying them here would need a timestamp semantics this repair does not own, and skipping them silently would report a repair it did not make. mode: "report" still counts them.'
741
+ }
742
+ );
743
+ }
744
+ function transactionOptionsFor(mode) {
745
+ return mode === "report" ? { transaction: { accessMode: "read_only" } } : void 0;
746
+ }
747
+ function relationRecord(counts) {
748
+ return {
749
+ nodes: counts.get("nodes"),
750
+ edges: counts.get("edges"),
751
+ recordedNodes: counts.get("recordedNodes"),
752
+ recordedEdges: counts.get("recordedEdges")
753
+ };
754
+ }
755
+ async function repairInvertedValidityWindows(options) {
756
+ const tables = resolvedTableNames(options.backend, options.tableNames);
757
+ const relations = scopedRelations(options.relations);
758
+ if (options.mode === "apply") requireStatements2(options.backend);
759
+ return chunk5PRKMB24_cjs.runOptionallyInTransaction(
760
+ options.backend,
761
+ async (target, execution) => {
762
+ const predicate = invertedValidityWindowPredicate({
763
+ dialect: target.dialect,
764
+ graphId: options.graphId
765
+ });
766
+ const inverted = /* @__PURE__ */ new Map();
767
+ const nonCanonical = /* @__PURE__ */ new Map();
768
+ for (const relation of relations) {
769
+ const table = relationTable(tables, relation);
770
+ nonCanonical.set(
771
+ relation,
772
+ target.dialect === "sqlite" ? await countMatching(
773
+ target,
774
+ table,
775
+ nonCanonicalWindowPredicate(options.graphId)
776
+ ) : 0
777
+ );
778
+ inverted.set(relation, await countMatching(target, table, predicate));
779
+ }
780
+ if (options.mode === "apply") {
781
+ assertClassifiableBounds(nonCanonical);
782
+ for (const relation of relations) {
783
+ await repairRelation(
784
+ target,
785
+ relationTable(tables, relation),
786
+ predicate
787
+ );
788
+ }
789
+ }
790
+ return {
791
+ relations: options.relations,
792
+ counts: relationRecord(inverted),
793
+ nonCanonical: relationRecord(nonCanonical),
794
+ atomic: execution.atomic
795
+ };
796
+ },
797
+ transactionOptionsFor(options.mode)
798
+ );
799
+ }
800
+
601
801
  exports.deleteLegacyRecordedAnchorMap = deleteLegacyRecordedAnchorMap;
602
802
  exports.migrateLegacyRecordedTime = migrateLegacyRecordedTime;
603
803
  exports.migrateRecordedAnchor = migrateRecordedAnchor;
604
- //# sourceMappingURL=chunk-KABFHAL7.cjs.map
605
- //# sourceMappingURL=chunk-KABFHAL7.cjs.map
804
+ exports.repairInvertedValidityWindows = repairInvertedValidityWindows;
805
+ //# sourceMappingURL=chunk-UMGZDVOA.cjs.map
806
+ //# sourceMappingURL=chunk-UMGZDVOA.cjs.map