@nicia-ai/typegraph 0.43.0 → 0.45.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 (307) hide show
  1. package/dist/backend/drizzle/indexes.cjs +9 -9
  2. package/dist/backend/drizzle/indexes.d.cts +1 -1
  3. package/dist/backend/drizzle/indexes.d.ts +1 -1
  4. package/dist/backend/drizzle/indexes.js +5 -5
  5. package/dist/backend/index.cjs +50 -50
  6. package/dist/backend/index.d.cts +3 -3
  7. package/dist/backend/index.d.ts +3 -3
  8. package/dist/backend/index.js +11 -11
  9. package/dist/backend/postgres/index.cjs +26 -26
  10. package/dist/backend/postgres/index.d.cts +6 -5
  11. package/dist/backend/postgres/index.d.ts +6 -5
  12. package/dist/backend/postgres/index.js +13 -13
  13. package/dist/backend/postgres/pglite-store.cjs +32 -33
  14. package/dist/backend/postgres/pglite-store.cjs.map +1 -1
  15. package/dist/backend/postgres/pglite-store.d.cts +7 -7
  16. package/dist/backend/postgres/pglite-store.d.ts +7 -7
  17. package/dist/backend/postgres/pglite-store.js +28 -29
  18. package/dist/backend/postgres/pglite-store.js.map +1 -1
  19. package/dist/backend/postgres/pglite.cjs +15 -15
  20. package/dist/backend/postgres/pglite.d.cts +3 -2
  21. package/dist/backend/postgres/pglite.d.ts +3 -2
  22. package/dist/backend/postgres/pglite.js +14 -14
  23. package/dist/backend/sqlite/index.cjs +23 -23
  24. package/dist/backend/sqlite/index.d.cts +7 -6
  25. package/dist/backend/sqlite/index.d.ts +7 -6
  26. package/dist/backend/sqlite/index.js +11 -11
  27. package/dist/backend/sqlite/libsql.cjs +17 -17
  28. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  29. package/dist/backend/sqlite/libsql.d.cts +3 -2
  30. package/dist/backend/sqlite/libsql.d.ts +3 -2
  31. package/dist/backend/sqlite/libsql.js +13 -13
  32. package/dist/backend/sqlite/libsql.js.map +1 -1
  33. package/dist/backend/sqlite/local-store.cjs +33 -34
  34. package/dist/backend/sqlite/local-store.cjs.map +1 -1
  35. package/dist/backend/sqlite/local-store.d.cts +8 -7
  36. package/dist/backend/sqlite/local-store.d.ts +8 -7
  37. package/dist/backend/sqlite/local-store.js +29 -30
  38. package/dist/backend/sqlite/local-store.js.map +1 -1
  39. package/dist/backend/sqlite/local.cjs +16 -16
  40. package/dist/backend/sqlite/local.d.cts +3 -2
  41. package/dist/backend/sqlite/local.d.ts +3 -2
  42. package/dist/backend/sqlite/local.js +14 -14
  43. package/dist/{chunk-2OOY4OYT.js → chunk-2L54C2C2.js} +4 -4
  44. package/dist/{chunk-2OOY4OYT.js.map → chunk-2L54C2C2.js.map} +1 -1
  45. package/dist/{chunk-4WYFRACU.js → chunk-42PYUGLS.js} +58 -4
  46. package/dist/chunk-42PYUGLS.js.map +1 -0
  47. package/dist/{chunk-EQOQOT55.js → chunk-4GUBTVPV.js} +4 -5
  48. package/dist/chunk-4GUBTVPV.js.map +1 -0
  49. package/dist/{chunk-ZIRC2U6G.js → chunk-4GUTQPVO.js} +102 -16
  50. package/dist/chunk-4GUTQPVO.js.map +1 -0
  51. package/dist/{chunk-OYJSYDIH.js → chunk-4MB3AQAQ.js} +13 -3
  52. package/dist/chunk-4MB3AQAQ.js.map +1 -0
  53. package/dist/{chunk-5Q3P6OIC.cjs → chunk-4MEWSUVM.cjs} +12 -12
  54. package/dist/chunk-4MEWSUVM.cjs.map +1 -0
  55. package/dist/{chunk-VC26BUNP.js → chunk-4QIKLIGG.js} +17 -5
  56. package/dist/chunk-4QIKLIGG.js.map +1 -0
  57. package/dist/chunk-4SZ6XPTG.cjs +12 -0
  58. package/dist/{chunk-VGMNGWBR.cjs.map → chunk-4SZ6XPTG.cjs.map} +1 -1
  59. package/dist/{chunk-UZLEQFTV.js → chunk-55ITBQJI.js} +4 -4
  60. package/dist/chunk-55ITBQJI.js.map +1 -0
  61. package/dist/{chunk-JOYPNY33.js → chunk-5EKPX6QU.js} +9 -9
  62. package/dist/{chunk-JOYPNY33.js.map → chunk-5EKPX6QU.js.map} +1 -1
  63. package/dist/{chunk-TRC646QQ.cjs → chunk-5GAONX5G.cjs} +7 -7
  64. package/dist/{chunk-TRC646QQ.cjs.map → chunk-5GAONX5G.cjs.map} +1 -1
  65. package/dist/{chunk-M4GYQF2H.js → chunk-6DCB664D.js} +7 -4
  66. package/dist/chunk-6DCB664D.js.map +1 -0
  67. package/dist/{chunk-64LERBFM.cjs → chunk-6RYPD3NJ.cjs} +75 -65
  68. package/dist/chunk-6RYPD3NJ.cjs.map +1 -0
  69. package/dist/{chunk-5AERZSHC.cjs → chunk-7PF2L3H6.cjs} +4 -4
  70. package/dist/{chunk-5AERZSHC.cjs.map → chunk-7PF2L3H6.cjs.map} +1 -1
  71. package/dist/chunk-B3F2D3SP.cjs +12 -0
  72. package/dist/{chunk-U3YRCZ5L.cjs.map → chunk-B3F2D3SP.cjs.map} +1 -1
  73. package/dist/{chunk-Z3WIL6S3.js → chunk-BGYJW37L.js} +5 -5
  74. package/dist/{chunk-Z3WIL6S3.js.map → chunk-BGYJW37L.js.map} +1 -1
  75. package/dist/{chunk-DMZEVJGL.cjs → chunk-BNS75YNF.cjs} +12 -13
  76. package/dist/chunk-BNS75YNF.cjs.map +1 -0
  77. package/dist/{chunk-KTBTSHU6.cjs → chunk-C4F7VJ5D.cjs} +13 -3
  78. package/dist/chunk-C4F7VJ5D.cjs.map +1 -0
  79. package/dist/{chunk-L2BYRYHC.js → chunk-CBKG6HEP.js} +43 -33
  80. package/dist/chunk-CBKG6HEP.js.map +1 -0
  81. package/dist/{chunk-CVK4T34X.cjs → chunk-CPEL3YIR.cjs} +22 -22
  82. package/dist/{chunk-CVK4T34X.cjs.map → chunk-CPEL3YIR.cjs.map} +1 -1
  83. package/dist/{chunk-O2GZM7UK.cjs → chunk-D54WH24V.cjs} +62 -7
  84. package/dist/chunk-D54WH24V.cjs.map +1 -0
  85. package/dist/{chunk-33PAKPED.cjs → chunk-D56XG4EI.cjs} +53 -41
  86. package/dist/chunk-D56XG4EI.cjs.map +1 -0
  87. package/dist/{chunk-O3USVVWS.js → chunk-DK2S42XB.js} +3 -3
  88. package/dist/{chunk-O3USVVWS.js.map → chunk-DK2S42XB.js.map} +1 -1
  89. package/dist/{chunk-HHBKGPEI.js → chunk-DXEEHSGN.js} +517 -26
  90. package/dist/chunk-DXEEHSGN.js.map +1 -0
  91. package/dist/{chunk-UJRWOV5B.js → chunk-EFEOOCJ3.js} +5 -5
  92. package/dist/{chunk-UJRWOV5B.js.map → chunk-EFEOOCJ3.js.map} +1 -1
  93. package/dist/{chunk-ECU53PMN.cjs → chunk-EKFUG4G7.cjs} +5 -5
  94. package/dist/chunk-EKFUG4G7.cjs.map +1 -0
  95. package/dist/{chunk-FSCJOTHF.cjs → chunk-EQ7JKLZO.cjs} +10 -10
  96. package/dist/{chunk-FSCJOTHF.cjs.map → chunk-EQ7JKLZO.cjs.map} +1 -1
  97. package/dist/{chunk-AQR6BHB3.cjs → chunk-F4NHQHEZ.cjs} +10 -10
  98. package/dist/{chunk-AQR6BHB3.cjs.map → chunk-F4NHQHEZ.cjs.map} +1 -1
  99. package/dist/{chunk-2G6ZEGYO.js → chunk-FL5UQRES.js} +4 -4
  100. package/dist/{chunk-2G6ZEGYO.js.map → chunk-FL5UQRES.js.map} +1 -1
  101. package/dist/{chunk-ZP2KPDNN.js → chunk-FLEQ2HBK.js} +3 -3
  102. package/dist/{chunk-ZP2KPDNN.js.map → chunk-FLEQ2HBK.js.map} +1 -1
  103. package/dist/{chunk-RAWG2FEU.js → chunk-FQ7ZPOTZ.js} +264 -18
  104. package/dist/chunk-FQ7ZPOTZ.js.map +1 -0
  105. package/dist/{chunk-O7XVCLXW.cjs → chunk-H7VE3FL4.cjs} +577 -82
  106. package/dist/chunk-H7VE3FL4.cjs.map +1 -0
  107. package/dist/{chunk-JNXZQBN3.js → chunk-ID4WXTKL.js} +1039 -482
  108. package/dist/chunk-ID4WXTKL.js.map +1 -0
  109. package/dist/{chunk-ZGOUVMVS.js → chunk-ISLPNELU.js} +17 -5
  110. package/dist/chunk-ISLPNELU.js.map +1 -0
  111. package/dist/{chunk-I73ATSAH.cjs → chunk-IX64T5OL.cjs} +4 -4
  112. package/dist/{chunk-I73ATSAH.cjs.map → chunk-IX64T5OL.cjs.map} +1 -1
  113. package/dist/{chunk-XDMPDUKL.cjs → chunk-J2ICGNHO.cjs} +8 -9
  114. package/dist/chunk-J2ICGNHO.cjs.map +1 -0
  115. package/dist/{chunk-KDRF3NR2.cjs → chunk-J7LXTUTP.cjs} +295 -201
  116. package/dist/chunk-J7LXTUTP.cjs.map +1 -0
  117. package/dist/{chunk-AO2WPYFZ.cjs → chunk-JQXSZHF2.cjs} +14 -4
  118. package/dist/chunk-JQXSZHF2.cjs.map +1 -0
  119. package/dist/{chunk-UTTW2Q3M.cjs → chunk-JXUTCSXX.cjs} +197 -133
  120. package/dist/chunk-JXUTCSXX.cjs.map +1 -0
  121. package/dist/{chunk-GT7NEXSU.js → chunk-KCO5EFJU.js} +3 -3
  122. package/dist/{chunk-GT7NEXSU.js.map → chunk-KCO5EFJU.js.map} +1 -1
  123. package/dist/{chunk-ARN3ZODS.cjs → chunk-KKYELPZ2.cjs} +6 -6
  124. package/dist/{chunk-ARN3ZODS.cjs.map → chunk-KKYELPZ2.cjs.map} +1 -1
  125. package/dist/{chunk-7Y6BV3TK.cjs → chunk-KMXWZLQX.cjs} +100 -100
  126. package/dist/{chunk-7Y6BV3TK.cjs.map → chunk-KMXWZLQX.cjs.map} +1 -1
  127. package/dist/{chunk-CDYRPI5U.js → chunk-MIJKEVV7.js} +4 -4
  128. package/dist/{chunk-CDYRPI5U.js.map → chunk-MIJKEVV7.js.map} +1 -1
  129. package/dist/{chunk-FFQGI67R.cjs → chunk-NAAMUYMS.cjs} +56 -44
  130. package/dist/chunk-NAAMUYMS.cjs.map +1 -0
  131. package/dist/{chunk-6TJ6PKPS.cjs → chunk-OOA273IJ.cjs} +27 -27
  132. package/dist/{chunk-6TJ6PKPS.cjs.map → chunk-OOA273IJ.cjs.map} +1 -1
  133. package/dist/{chunk-F2KVJ6FF.cjs → chunk-P7GTYOLB.cjs} +203 -117
  134. package/dist/chunk-P7GTYOLB.cjs.map +1 -0
  135. package/dist/{chunk-42XYPKZU.js → chunk-PVUI6KGR.js} +67 -3
  136. package/dist/chunk-PVUI6KGR.js.map +1 -0
  137. package/dist/{chunk-L5AUCL5P.js → chunk-Q6EDCUXV.js} +274 -14
  138. package/dist/chunk-Q6EDCUXV.js.map +1 -0
  139. package/dist/{chunk-ZPCKPLMX.cjs → chunk-QB6VMOJ2.cjs} +8 -8
  140. package/dist/{chunk-ZPCKPLMX.cjs.map → chunk-QB6VMOJ2.cjs.map} +1 -1
  141. package/dist/{chunk-3RPQDGUE.cjs → chunk-QC4MCOFV.cjs} +5 -5
  142. package/dist/{chunk-3RPQDGUE.cjs.map → chunk-QC4MCOFV.cjs.map} +1 -1
  143. package/dist/{chunk-4XRP2N6B.js → chunk-QLUXRWKL.js} +3 -3
  144. package/dist/{chunk-4XRP2N6B.js.map → chunk-QLUXRWKL.js.map} +1 -1
  145. package/dist/{chunk-OM6RIOA5.cjs → chunk-QR24DJDF.cjs} +13 -13
  146. package/dist/{chunk-OM6RIOA5.cjs.map → chunk-QR24DJDF.cjs.map} +1 -1
  147. package/dist/{chunk-YPVQYM3L.js → chunk-QRNYDV5Z.js} +138 -31
  148. package/dist/chunk-QRNYDV5Z.js.map +1 -0
  149. package/dist/{chunk-ZOHCFYXE.js → chunk-QT6V3YRH.js} +3 -3
  150. package/dist/{chunk-ZOHCFYXE.js.map → chunk-QT6V3YRH.js.map} +1 -1
  151. package/dist/{chunk-5C75HQYQ.js → chunk-RFRM3Q5K.js} +17 -5
  152. package/dist/chunk-RFRM3Q5K.js.map +1 -0
  153. package/dist/{chunk-NXIZL7ZZ.js → chunk-RUQS6M7G.js} +6 -6
  154. package/dist/chunk-RUQS6M7G.js.map +1 -0
  155. package/dist/{chunk-CI5NPLXX.js → chunk-S3ZRKJHY.js} +3 -3
  156. package/dist/{chunk-CI5NPLXX.js.map → chunk-S3ZRKJHY.js.map} +1 -1
  157. package/dist/{chunk-3V6D5DEC.js → chunk-S4KQ5LV4.js} +3 -3
  158. package/dist/{chunk-3V6D5DEC.js.map → chunk-S4KQ5LV4.js.map} +1 -1
  159. package/dist/{chunk-CTWZPYJW.js → chunk-TKORQCG4.js} +108 -15
  160. package/dist/chunk-TKORQCG4.js.map +1 -0
  161. package/dist/{chunk-2HKIID5K.js → chunk-TKP5T34P.js} +4 -5
  162. package/dist/chunk-TKP5T34P.js.map +1 -0
  163. package/dist/{chunk-X2XOQZT3.cjs → chunk-U5W4LKZV.cjs} +13 -9
  164. package/dist/chunk-U5W4LKZV.cjs.map +1 -0
  165. package/dist/{chunk-BLBG2VZ5.cjs → chunk-UCQ3BFSY.cjs} +372 -110
  166. package/dist/chunk-UCQ3BFSY.cjs.map +1 -0
  167. package/dist/{chunk-CUPJL6TS.js → chunk-V34A6R5V.js} +13 -4
  168. package/dist/chunk-V34A6R5V.js.map +1 -0
  169. package/dist/{chunk-LQLVJWUH.js → chunk-VTN3C3CH.js} +7 -7
  170. package/dist/chunk-VTN3C3CH.js.map +1 -0
  171. package/dist/{chunk-FY4VY5EV.cjs → chunk-VVQM4CZD.cjs} +20 -20
  172. package/dist/chunk-VVQM4CZD.cjs.map +1 -0
  173. package/dist/{chunk-LDCWO5B6.js → chunk-WDAVPX46.js} +3 -3
  174. package/dist/{chunk-LDCWO5B6.js.map → chunk-WDAVPX46.js.map} +1 -1
  175. package/dist/{chunk-5GV4JQNA.cjs → chunk-WDBXJOU5.cjs} +55 -43
  176. package/dist/chunk-WDBXJOU5.cjs.map +1 -0
  177. package/dist/{chunk-FMPZPOUD.js → chunk-WUFASQUO.js} +3 -3
  178. package/dist/{chunk-FMPZPOUD.js.map → chunk-WUFASQUO.js.map} +1 -1
  179. package/dist/{chunk-5ZPRE4CV.cjs → chunk-YDWLUT5V.cjs} +237 -130
  180. package/dist/chunk-YDWLUT5V.cjs.map +1 -0
  181. package/dist/{chunk-CVNGKTHO.js → chunk-YMTXMPV6.js} +4 -4
  182. package/dist/{chunk-CVNGKTHO.js.map → chunk-YMTXMPV6.js.map} +1 -1
  183. package/dist/{chunk-NDQLPKBX.cjs → chunk-YOALGKRE.cjs} +2092 -1535
  184. package/dist/chunk-YOALGKRE.cjs.map +1 -0
  185. package/dist/{chunk-OMQ2NBOR.cjs → chunk-Z3WO6MND.cjs} +27 -27
  186. package/dist/{chunk-OMQ2NBOR.cjs.map → chunk-Z3WO6MND.cjs.map} +1 -1
  187. package/dist/{chunk-V2GZBPY2.cjs → chunk-ZI6VQSZA.cjs} +310 -61
  188. package/dist/chunk-ZI6VQSZA.cjs.map +1 -0
  189. package/dist/{chunk-ZBV4LQD2.cjs → chunk-ZTAJL4DT.cjs} +4 -4
  190. package/dist/{chunk-ZBV4LQD2.cjs.map → chunk-ZTAJL4DT.cjs.map} +1 -1
  191. package/dist/core/index.cjs +27 -28
  192. package/dist/core/index.d.cts +5 -5
  193. package/dist/core/index.d.ts +5 -5
  194. package/dist/core/index.js +7 -8
  195. package/dist/{ddl-3unqC-kg.d.cts → ddl-BG4J805L.d.cts} +3 -3
  196. package/dist/{ddl-Bc4Dl8fu.d.ts → ddl-CgiS9QLj.d.ts} +3 -3
  197. package/dist/{define-graph-DBFnc7u_.d.ts → define-graph-BGrJahvp.d.ts} +1 -1
  198. package/dist/{define-graph-Byslw2OO.d.cts → define-graph-alREY2wj.d.cts} +1 -1
  199. package/dist/graph-extension/index.cjs +19 -20
  200. package/dist/graph-extension/index.d.cts +4 -4
  201. package/dist/graph-extension/index.d.ts +4 -4
  202. package/dist/graph-extension/index.js +4 -5
  203. package/dist/graph-merge/index.cjs +103 -104
  204. package/dist/graph-merge/index.cjs.map +1 -1
  205. package/dist/graph-merge/index.d.cts +9 -8
  206. package/dist/graph-merge/index.d.ts +9 -8
  207. package/dist/graph-merge/index.js +23 -24
  208. package/dist/graph-merge/index.js.map +1 -1
  209. package/dist/{index-DHXw7QAl.d.cts → index-BBxZCUdu.d.ts} +37 -7
  210. package/dist/{index-DQzVJBHa.d.ts → index-C3y_98iN.d.cts} +37 -7
  211. package/dist/index.cjs +209 -202
  212. package/dist/index.cjs.map +1 -1
  213. package/dist/index.d.cts +13 -13
  214. package/dist/index.d.ts +13 -13
  215. package/dist/index.js +33 -34
  216. package/dist/index.js.map +1 -1
  217. package/dist/indexes/index.cjs +13 -13
  218. package/dist/indexes/index.d.cts +4 -4
  219. package/dist/indexes/index.d.ts +4 -4
  220. package/dist/indexes/index.js +6 -6
  221. package/dist/interchange/index.cjs +50 -41
  222. package/dist/interchange/index.cjs.map +1 -1
  223. package/dist/interchange/index.d.cts +11 -11
  224. package/dist/interchange/index.d.ts +11 -11
  225. package/dist/interchange/index.js +24 -15
  226. package/dist/interchange/index.js.map +1 -1
  227. package/dist/{manager-U9_zopqr.d.cts → manager-KS7CGQQT.d.cts} +44 -6
  228. package/dist/{manager-Dl0-er1G.d.ts → manager-YoLEfcc1.d.ts} +44 -6
  229. package/dist/{materialize-indexes-BM3u0aXE.d.ts → materialize-indexes-Bhhyb1B3.d.ts} +1 -1
  230. package/dist/{materialize-indexes-DzMCetZe.d.cts → materialize-indexes-OHRWypW6.d.cts} +1 -1
  231. package/dist/{postgres-DpJqtbSX.d.cts → postgres-DpkW3R5Y.d.cts} +1 -1
  232. package/dist/{postgres-C5-WMKFA.d.ts → postgres-DwqyIniy.d.ts} +1 -1
  233. package/dist/profiler/index.d.cts +10 -9
  234. package/dist/profiler/index.d.ts +10 -9
  235. package/dist/provenance/index.cjs +38 -38
  236. package/dist/provenance/index.cjs.map +1 -1
  237. package/dist/provenance/index.d.cts +7 -7
  238. package/dist/provenance/index.d.ts +7 -7
  239. package/dist/provenance/index.js +8 -8
  240. package/dist/provenance/index.js.map +1 -1
  241. package/dist/schema/index.cjs +40 -41
  242. package/dist/schema/index.d.cts +7 -7
  243. package/dist/schema/index.d.ts +7 -7
  244. package/dist/schema/index.js +13 -14
  245. package/dist/{searchable-B4mUXZT6.d.cts → searchable-CIZL8Hyw.d.cts} +2 -2
  246. package/dist/{searchable-C7jmPNLT.d.ts → searchable-DLWEfC4a.d.ts} +2 -2
  247. package/dist/{sqlite-Ch5tSYQY.d.ts → sqlite-DY0WODUK.d.cts} +1 -1
  248. package/dist/{sqlite-Da7jiYu9.d.cts → sqlite-L-VIRzqA.d.ts} +1 -1
  249. package/dist/{store-view-DdwBNjZQ.d.ts → store-view-66p92IPi.d.ts} +1974 -1751
  250. package/dist/{store-view-D1F6KqsE.d.cts → store-view-A85FFRnk.d.cts} +1974 -1751
  251. package/dist/{temporal-CMpigMCW.d.cts → temporal-BNbjXqer.d.cts} +1 -1
  252. package/dist/{temporal-BtrTYTiB.d.ts → temporal-Bob6Nfbp.d.ts} +1 -1
  253. package/dist/{types-Dh-EgT-w.d.cts → types-Ch9a0Dx6.d.cts} +483 -20
  254. package/dist/{types-Dh-EgT-w.d.ts → types-Ch9a0Dx6.d.ts} +483 -20
  255. package/dist/{types-D2rU5Taq.d.ts → types-ClCzT-dT.d.ts} +1 -1
  256. package/dist/{types-G4sVM-76.d.cts → types-DeORZhxn.d.cts} +1 -1
  257. package/dist/{where-DbZ9XDOI.d.cts → where-DPw52ksb.d.cts} +1 -1
  258. package/dist/{where-B8Y21kig.d.ts → where-kWUZPvEA.d.ts} +1 -1
  259. package/package.json +1 -1
  260. package/dist/chunk-2HKIID5K.js.map +0 -1
  261. package/dist/chunk-33PAKPED.cjs.map +0 -1
  262. package/dist/chunk-42XYPKZU.js.map +0 -1
  263. package/dist/chunk-4WYFRACU.js.map +0 -1
  264. package/dist/chunk-5C75HQYQ.js.map +0 -1
  265. package/dist/chunk-5GV4JQNA.cjs.map +0 -1
  266. package/dist/chunk-5Q3P6OIC.cjs.map +0 -1
  267. package/dist/chunk-5ZPRE4CV.cjs.map +0 -1
  268. package/dist/chunk-64LERBFM.cjs.map +0 -1
  269. package/dist/chunk-AO2WPYFZ.cjs.map +0 -1
  270. package/dist/chunk-BLBG2VZ5.cjs.map +0 -1
  271. package/dist/chunk-CTWZPYJW.js.map +0 -1
  272. package/dist/chunk-CUPJL6TS.js.map +0 -1
  273. package/dist/chunk-DMZEVJGL.cjs.map +0 -1
  274. package/dist/chunk-ECU53PMN.cjs.map +0 -1
  275. package/dist/chunk-EQOQOT55.js.map +0 -1
  276. package/dist/chunk-F2KVJ6FF.cjs.map +0 -1
  277. package/dist/chunk-F7TDKSVB.cjs +0 -61
  278. package/dist/chunk-F7TDKSVB.cjs.map +0 -1
  279. package/dist/chunk-FFQGI67R.cjs.map +0 -1
  280. package/dist/chunk-FY4VY5EV.cjs.map +0 -1
  281. package/dist/chunk-HHBKGPEI.js.map +0 -1
  282. package/dist/chunk-JNXZQBN3.js.map +0 -1
  283. package/dist/chunk-KDRF3NR2.cjs.map +0 -1
  284. package/dist/chunk-KTBTSHU6.cjs.map +0 -1
  285. package/dist/chunk-L2BYRYHC.js.map +0 -1
  286. package/dist/chunk-L5AUCL5P.js.map +0 -1
  287. package/dist/chunk-LQLVJWUH.js.map +0 -1
  288. package/dist/chunk-M4GYQF2H.js.map +0 -1
  289. package/dist/chunk-NDQLPKBX.cjs.map +0 -1
  290. package/dist/chunk-NXIZL7ZZ.js.map +0 -1
  291. package/dist/chunk-O2GZM7UK.cjs.map +0 -1
  292. package/dist/chunk-O7XVCLXW.cjs.map +0 -1
  293. package/dist/chunk-OYJSYDIH.js.map +0 -1
  294. package/dist/chunk-RAWG2FEU.js.map +0 -1
  295. package/dist/chunk-RXOAXO3R.js +0 -59
  296. package/dist/chunk-RXOAXO3R.js.map +0 -1
  297. package/dist/chunk-U3YRCZ5L.cjs +0 -12
  298. package/dist/chunk-UTTW2Q3M.cjs.map +0 -1
  299. package/dist/chunk-UZLEQFTV.js.map +0 -1
  300. package/dist/chunk-V2GZBPY2.cjs.map +0 -1
  301. package/dist/chunk-VC26BUNP.js.map +0 -1
  302. package/dist/chunk-VGMNGWBR.cjs +0 -12
  303. package/dist/chunk-X2XOQZT3.cjs.map +0 -1
  304. package/dist/chunk-XDMPDUKL.cjs.map +0 -1
  305. package/dist/chunk-YPVQYM3L.js.map +0 -1
  306. package/dist/chunk-ZGOUVMVS.js.map +0 -1
  307. package/dist/chunk-ZIRC2U6G.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backend/types.ts"],"names":[],"mappings":";;;AA+NO,SAAS,oCACd,YAAA,EACqB;AACrB,EAAA,IACE,YAAA,CAAa,cAAA,EAAgB,SAAA,KAAc,IAAA,IAC1C,YAAA,CAAa,gBACZ,YAAA,CAAa,eAAA,IACb,YAAA,CAAa,SAAA,KAAc,KAAA,EAC7B;AACA,IAAA,OAAO,YAAA;AAAA,EACT;AACA,EAAA,OAAO;AAAA,IACL,GAAG,YAAA;AAAA,IACH,gBAAgB,EAAE,GAAG,YAAA,CAAa,cAAA,EAAgB,WAAW,KAAA;AAAM,GACrE;AACF;AAiBO,SAAS,iBAAiB,KAAA,EAA0C;AACzE,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,GACnB,IAAA,CAAK,KAAA,CAAM,KAAK,CAAA,GACjB,KAAA;AACN;AAGO,SAAS,mBAAmB,KAAA,EAAyB;AAC1D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,GAAW,KAAA,GAAQ,IAAA,CAAK,UAAU,KAAK,CAAA;AACjE;AAkCO,SAAS,cAAc,GAAA,EAAkC;AAC9D,EAAA,OAAO,IAAI,UAAA,KAAe,MAAA;AAC5B;AAEO,SAAS,oBAAoB,GAAA,EAAwC;AAC1E,EAAA,OAAO,IAAI,UAAA,KAAe,MAAA;AAC5B;AAq4BO,IAAM,yBAAA,GAA2C,qBAAA;AAAA,EACtD;AACF;AA8oCO,SAAS,6BACd,OAAA,EACwB;AACxB,EAAA,MAAM,WAAW,OAAA,CAAQ,QAAA;AACzB,EAAA,MAAM,WAAW,OAAA,CAAQ,QAAA;AACzB,EAAA,MAAM,aAAa,OAAA,CAA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EAAc,IAAA;AAAA;AAAA,EACd,eAAA,EAAiB,IAAA;AAAA;AAAA,EACjB,SAAA,EAAW,IAAA;AAAA;AAAA,EACX,iBAAA,EAAmB,4BAAA;AAAA,EACnB,cAAA,EAAgB,OAAO,MAAA,CAAO,EAAE,WAAW,IAAA,EAAM,aAAA,EAAe,MAAM;AACxE,CAAC","file":"chunk-55ITBQJI.js","sourcesContent":["/**\n * Backend interface types for TypeGraph storage.\n *\n * The backend abstracts database operations, allowing different\n * SQL implementations (SQLite, PostgreSQL) behind a common interface.\n */\nimport {\n type IndexEntity,\n type JsonValue,\n type KindEntity,\n type TemporalMode,\n} from \"../core/types\";\nimport { type SqlTableNames } from \"../query/compiler/schema\";\nimport { type FulltextStrategy } from \"../query/dialect/fulltext-strategy\";\nimport {\n type VectorSlot,\n type VectorStrategy,\n} from \"../query/dialect/vector-strategy\";\nimport { type SqlFragment } from \"../query/sql-fragment\";\nimport {\n type CompiledRowsSql,\n type CompiledSelectSql,\n type CompiledStatementSql,\n type CompiledTemporaryStatementSql,\n} from \"../query/sql-intent\";\nimport { type SerializedSchema } from \"../schema/types\";\nimport { typeGraphGlobalSymbol } from \"../utils/global-symbol\";\n\n// ============================================================\n// Vector Search Types\n// ============================================================\n\n/**\n * Supported vector similarity metrics.\n */\nexport type VectorMetric = \"cosine\" | \"l2\" | \"inner_product\";\n\n/**\n * Supported vector index types.\n */\nexport type VectorIndexType = \"hnsw\" | \"ivfflat\" | \"none\";\n\n/**\n * The mechanism a strategy uses to combine a row filter with an *approximate*\n * (ANN) vector search.\n *\n * Every approximate search TypeGraph issues carries at least one filter: the\n * liveness predicate that excludes soft-deleted and out-of-validity rows. Add\n * a `.where(...)` predicate and it narrows further. Engines differ in where\n * they apply it relative to the index traversal:\n *\n * - `\"filter-pushdown\"` — the filter constrains the ANN candidate set itself.\n * sqlite-vec's `vec0` KNN accepts primary-key `IN (SELECT …)` pushdown.\n * - `\"iterative-scan\"` — the engine re-enters the index, gathering more\n * candidates until `LIMIT` rows survive the filter *or* it hits its own scan\n * bound. pgvector >= 0.8 (`hnsw.iterative_scan` / `ivfflat.iterative_scan`,\n * applied automatically by the backend).\n * - `\"post-filter\"` — the engine retrieves a fixed multiple of the page from\n * the ANN index and applies the filter afterwards. libSQL's DiskANN\n * `vector_top_k` is a table function with no filter pushdown, so this is the\n * only shape available to it.\n *\n * This names what the strategy *asks the engine to do*. Whether the engine can\n * honor it — and whether honoring it is enough to fill a page — is\n * {@link FilteredApproximateSearch.guaranteesFullPage}.\n */\nexport type FilteredApproximateSearchMode =\n \"filter-pushdown\" | \"iterative-scan\" | \"post-filter\";\n\n/**\n * How a filtered approximate (ANN) vector search behaves, and whether it can\n * silently return fewer rows than `limit` while more matches exist.\n *\n * Read `guaranteesFullPage` — not `mode` — to decide whether a short page is\n * possible. Only `\"filter-pushdown\"` guarantees a full page:\n *\n * - **sqlite-vec** pushes the filter into the KNN. Exact.\n * - **pgvector** re-enters the index, but the iterative scan stops at\n * `hnsw.max_scan_tuples` / `ivfflat.max_probes`, and on **pgvector < 0.8**\n * there is no iterative scan at all — the backend detects that at runtime,\n * warns once, and the search stays `ef_search`-bounded, behaving like\n * `\"post-filter\"`. Neither case is visible in a statically-declared `mode`,\n * which is exactly why the guarantee is a separate field.\n * - **libSQL** over-fetches a fixed multiple of the page and filters\n * afterwards, so it under-fills once more than that headroom is filtered out.\n *\n * A store with heavy tombstone drift — routine in a temporal store — is what\n * turns a short page from a theoretical caveat into an observed one. Exact\n * (`approximate: false`) searches are unaffected on every engine: they scan, so\n * the filter reaches every row.\n */\nexport type FilteredApproximateSearch = Readonly<{\n mode: FilteredApproximateSearchMode;\n /**\n * `true` only when a filtered approximate search is guaranteed to return\n * `limit` rows whenever `limit` matching rows exist — no engine-side scan\n * bound, no version dependence, no over-fetch headroom to exhaust.\n */\n guaranteesFullPage: boolean;\n}>;\n\n/**\n * Vector search capabilities.\n */\nexport type VectorCapabilities = Readonly<{\n /** Whether the backend supports vector operations */\n supported: boolean;\n /** Supported similarity metrics */\n metrics: readonly VectorMetric[];\n /** Supported index types */\n indexTypes: readonly VectorIndexType[];\n /** Maximum dimensions supported */\n maxDimensions: number;\n /**\n * How a filtered approximate search bounds recall — and whether it can\n * silently return a short page. See {@link FilteredApproximateSearch}.\n *\n * Required, so a new vector strategy cannot omit the declaration and inherit\n * an engine promise it does not keep.\n */\n filteredApproximateSearch: FilteredApproximateSearch;\n}>;\n\n// ============================================================\n// Fulltext Search Types\n// ============================================================\n\n/**\n * Query modes for fulltext search.\n *\n * - \"websearch\": Google-style syntax (quoted phrases, +required, -excluded).\n * Postgres: `websearch_to_tsquery`. SQLite: translated to FTS5 MATCH.\n * - \"phrase\": treats the whole query as a phrase.\n * Postgres: `phraseto_tsquery`. SQLite: FTS5 `\"...\"` phrase.\n * - \"plain\": splits on whitespace and ANDs terms.\n * Postgres: `plainto_tsquery`. SQLite: default FTS5 AND.\n * - \"raw\": dialect-native syntax passed through unchanged.\n */\nexport type FulltextQueryMode = \"websearch\" | \"phrase\" | \"plain\" | \"raw\";\n\n/**\n * Fulltext search capabilities declared by a backend.\n */\nexport type FulltextCapabilities = Readonly<{\n /** Whether the backend supports fulltext operations */\n supported: boolean;\n /**\n * Language / tokenizer names understood by this backend.\n * Postgres: installed regconfigs (english, simple, ...).\n * SQLite FTS5: tokenizer names (unicode61, porter, trigram).\n */\n languages: readonly string[];\n /** Whether phrase queries are supported. */\n phraseQueries: boolean;\n /** Whether prefix (`foo*`) queries are supported. */\n prefixQueries: boolean;\n /** Whether highlighting / snippets are supported. */\n highlighting: boolean;\n}>;\n\n/**\n * Whole-graph analytics capabilities declared by a backend.\n *\n * `supported` means the backend can pin one transactional connection while\n * an algorithm creates, updates, and drops session-local temporary state.\n * `mathFunctions` records whether transcendental SQL functions needed by\n * deferred algorithms such as MCL/spectral are available; exact WCC does not\n * require them.\n */\nexport type GraphAnalyticsCapabilities = Readonly<{\n supported: boolean;\n mathFunctions: boolean;\n}>;\n\n// ============================================================\n// SQL Dialect & Capabilities\n// ============================================================\n\nimport { type SqlDialect } from \"../query/dialect/types\";\n\nexport type { SqlDialect } from \"../query/dialect/types\";\n\n/**\n * Backend capabilities that vary by dialect.\n */\nexport type BackendCapabilities = Readonly<{\n /** Whether the backend supports atomic transactions (D1 does not) */\n transactions: boolean;\n /** Whether the backend supports SQL window functions such as ROW_NUMBER() */\n windowFunctions: boolean;\n /**\n * Whether the backend's `execute()` supports `UPDATE … RETURNING`. Absent or\n * `true` means supported (every engine TypeGraph ships — SQLite ≥ 3.35,\n * PostgreSQL ≥ 8.2 — supports it). A custom backend whose engine cannot run\n * `RETURNING` must set this to `false` so recorded-time history capture\n * (`history: true`), which relies on `UPDATE … RETURNING` on its hot path,\n * is refused up front instead of failing mid-flush.\n */\n returning?: boolean;\n /**\n * Maximum number of bound parameters the engine accepts in one statement.\n * SQLite defaults to 999 (raisable at compile time via\n * `SQLITE_MAX_VARIABLE_NUMBER`), while hosted SQLite runtimes may impose a\n * lower platform ceiling. PostgreSQL's wire protocol encodes a 65535-count,\n * but postgres.js accepts at most 65533 bound values, so the bundled\n * PostgreSQL capability advertises that lower shared-driver ceiling.\n * Recorded-time capture and recorded point reads size their multi-row\n * statements to this ceiling — the same budget the backend's own batched\n * inserts use — instead of a conservative dialect-blind constant. Custom\n * runtimes can override a detected or probed limit here, but hosted platform\n * hard ceilings may only be lowered. Absent means the recorded-time fallback\n * budget applies.\n */\n maxBindParameters?: number;\n /** Vector search capabilities (undefined if not configured) */\n vector?: VectorCapabilities | undefined;\n /** Fulltext search capabilities (undefined if not configured) */\n fulltext?: FulltextCapabilities | undefined;\n /** Whole-graph analytics capabilities (undefined when unavailable). */\n graphAnalytics?: GraphAnalyticsCapabilities | undefined;\n}>;\n\n/** Keeps session-scoped analytics honest when a required SQL feature is absent. */\nexport function normalizeGraphAnalyticsCapabilities(\n capabilities: BackendCapabilities,\n): BackendCapabilities {\n if (\n capabilities.graphAnalytics?.supported !== true ||\n (capabilities.transactions &&\n capabilities.windowFunctions &&\n capabilities.returning !== false)\n ) {\n return capabilities;\n }\n return {\n ...capabilities,\n graphAnalytics: { ...capabilities.graphAnalytics, supported: false },\n };\n}\n\n// ============================================================\n// Row Types (Database Records)\n// ============================================================\n\n/**\n * A node/edge row's `props` column as the driver returned it: SQLite always\n * yields the JSON text; PostgreSQL drivers yield the jsonb value already\n * parsed. Keeping the driver's shape avoids a per-row\n * parse→stringify→re-parse round trip on the PostgreSQL read path —\n * consumers normalize through {@link rowPropsToObject} /\n * {@link rowPropsToJsonText} at the point of use.\n */\nexport type RowProps = string | Readonly<Record<string, unknown>>;\n\n/** The row's props as an object, parsing only when the driver gave text. */\nexport function rowPropsToObject(props: RowProps): Record<string, unknown> {\n return typeof props === \"string\" ?\n (JSON.parse(props) as Record<string, unknown>)\n : props;\n}\n\n/** The row's props as JSON text, serializing only when the driver gave an object. */\nexport function rowPropsToJsonText(props: RowProps): string {\n return typeof props === \"string\" ? props : JSON.stringify(props);\n}\n\n/**\n * A row from the typegraph_nodes table.\n */\nexport type NodeRow = Readonly<{\n graph_id: string;\n kind: string;\n id: string;\n props: RowProps;\n version: number;\n valid_from: string | undefined;\n valid_to: string | undefined;\n created_at: string;\n updated_at: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A {@link NodeRow} proven live (not soft-deleted). Functions that must only\n * ever touch live rows — the live-row update pipeline, soft delete — take\n * this type so a caller holding a possibly-tombstoned row is forced through\n * {@link isLiveNodeRow} first, instead of silently running live-row side\n * effects (uniqueness reservations, embedding/fulltext sync) for a row that\n * stays invisible.\n */\nexport type LiveNodeRow = NodeRow & Readonly<{ deleted_at: undefined }>;\n\n/**\n * A {@link NodeRow} proven soft-deleted. A resurrect targets exactly this\n * shape; see {@link isTombstonedNodeRow}.\n */\nexport type TombstonedNodeRow = NodeRow & Readonly<{ deleted_at: string }>;\n\nexport function isLiveNodeRow(row: NodeRow): row is LiveNodeRow {\n return row.deleted_at === undefined;\n}\n\nexport function isTombstonedNodeRow(row: NodeRow): row is TombstonedNodeRow {\n return row.deleted_at !== undefined;\n}\n\n/**\n * The read-only slice of a backend. Give this type to code that is\n * semantically a read — probes, gates, support-graph loads — so a read path\n * structurally CANNOT open a write transaction, mutate rows, or execute raw\n * SQL: those members do not exist on the type. Extend the pick as read paths\n * need more of the read surface.\n */\nexport type GraphReadBackend = Pick<\n GraphBackend,\n | \"dialect\"\n | \"getNode\"\n | \"getEdge\"\n | \"findNodesByKind\"\n | \"findEdgesByKind\"\n | \"findEdgesConnectedTo\"\n>;\n\n/**\n * A row from the typegraph_edges table.\n */\nexport type EdgeRow = Readonly<{\n graph_id: string;\n id: string;\n kind: string;\n from_kind: string;\n from_id: string;\n to_kind: string;\n to_id: string;\n props: RowProps;\n valid_from: string | undefined;\n valid_to: string | undefined;\n created_at: string;\n updated_at: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_node_uniques table.\n */\nexport type UniqueRow = Readonly<{\n graph_id: string;\n node_kind: string;\n constraint_name: string;\n key: string;\n node_id: string;\n concrete_kind: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_schema_versions table.\n */\nexport type SchemaVersionRow = Readonly<{\n graph_id: string;\n version: number;\n schema_hash: string;\n schema_doc: string; // JSON string\n created_at: string;\n is_active: boolean;\n}>;\n\n// ============================================================\n// Insert Parameters\n// ============================================================\n\n/**\n * Parameters for inserting a node.\n */\nexport type InsertNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n /**\n * Omitted (`undefined`): defaults to the insert's creation timestamp.\n * `null`: preserves an explicit open-left validity window (no lower\n * bound) — used by interchange import to round-trip a row that was\n * already NULL, instead of re-stamping it to the import's own timestamp.\n */\n validFrom?: string | null;\n validTo?: string;\n}>;\n\n/**\n * Parameters for updating a node.\n */\nexport type UpdateNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validTo?: string;\n incrementVersion?: boolean;\n /** If true, clears deleted_at (un-deletes the node). Used by upsert. */\n clearDeleted?: boolean;\n}>;\n\n/**\n * Parameters for updating a set of live nodes selected by a compiled\n * TypeGraph query.\n *\n * The candidate query must expose the named node-id column from the same graph\n * and kind. The backend independently fences the rows it writes to\n * `graphId` and `kind`; constructing the matching candidate query remains the\n * caller's responsibility.\n * Property values replace top-level keys, including preserving an explicit\n * JSON `null` value.\n *\n * This is a storage primitive: callers that expose it as a graph mutation are\n * responsible for schema validation and for synchronizing uniqueness,\n * fulltext, and vector sidecars. The result contains after-images only; callers\n * that need previous property values must freeze the candidate set and retain\n * its before-images in the same transaction before invoking this method.\n */\nexport type UpdateNodeSetParams = Readonly<{\n graphId: string;\n kind: string;\n patch: Readonly<Record<string, JsonValue>>;\n /** Top-level properties to remove (the storage form of an `undefined` patch value). */\n unsetProperties?: readonly string[];\n candidateIds: CompiledSelectSql;\n /** Projected SQL column holding the candidate node id (for example `n_id`). */\n candidateIdColumn: string;\n}>;\n\n/** The after-images changed by {@link GraphBackend.updateNodeSet}. */\nexport type UpdateNodeSetResult = Readonly<{\n affectedCount: number;\n rows: readonly NodeRow[];\n}>;\n\n/**\n * Parameters for deleting a node (soft delete).\n */\nexport type DeleteNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n}>;\n\n/**\n * Parameters for inserting an edge.\n */\nexport type InsertEdgeParams = Readonly<{\n graphId: string;\n id: string;\n kind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: Readonly<Record<string, unknown>>;\n /**\n * Omitted (`undefined`): defaults to the insert's creation timestamp.\n * `null`: preserves an explicit open-left validity window (no lower\n * bound) — used by interchange import to round-trip a row that was\n * already NULL, instead of re-stamping it to the import's own timestamp.\n */\n validFrom?: string | null;\n validTo?: string;\n}>;\n\n/**\n * Write-only session exposed inside {@link GraphBackend.trustedImport}.\n *\n * The caller has accepted the trusted-import contract: properties, endpoint\n * references, uniqueness, and cardinality are not validated. Backends may\n * therefore use engine-native ingestion primitives that bypass the normal\n * store write pipeline.\n */\nexport type TrustedImportSession = Readonly<{\n insertNodes: (params: readonly InsertNodeParams[]) => Promise<void>;\n insertEdges: (params: readonly InsertEdgeParams[]) => Promise<void>;\n}>;\n\n/**\n * Parameters for updating an edge.\n */\nexport type UpdateEdgeParams = Readonly<{\n graphId: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validTo?: string;\n clearDeleted?: boolean;\n}>;\n\n/**\n * Parameters for deleting an edge (soft delete).\n */\nexport type DeleteEdgeParams = Readonly<{\n graphId: string;\n id: string;\n}>;\n\n/**\n * Parameters for hard deleting a node (permanent removal).\n */\nexport type HardDeleteNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n}>;\n\n/**\n * Parameters for hard deleting an edge (permanent removal).\n */\nexport type HardDeleteEdgeParams = Readonly<{\n graphId: string;\n id: string;\n}>;\n\n/** Parameters for a batched edge delete (soft or hard). */\nexport type DeleteEdgesBatchParams = Readonly<{\n graphId: string;\n ids: readonly string[];\n}>;\n\n// ============================================================\n// Embedding Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating an embedding.\n *\n * `dimensions`, `metric`, and `indexType` together resolve the slot's\n * typed per-`(nodeKind, fieldPath)` storage (the strategy needs the fixed\n * dimension for the column type, and the metric/index type to address the\n * right ANN structure). The store populates them from the schema's\n * `embedding()` declaration via `getEmbeddingDimensions()` /\n * `getEmbeddingIndex()`; the backend constructs a `VectorSlot` from them\n * and stays graph-agnostic.\n */\nexport type UpsertEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n embedding: readonly number[];\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * One row of a batched embedding upsert.\n */\nexport type UpsertEmbeddingBatchRow = Readonly<{\n nodeId: string;\n embedding: readonly number[];\n}>;\n\n/**\n * Parameters for a batched embedding upsert. Homogeneous per vector slot:\n * one graph, one node kind, one field, many nodes. Duplicate `nodeId`\n * values within a batch are deduplicated last-write-wins by the backend\n * (a multi-row upsert cannot affect one row twice).\n */\nexport type UpsertEmbeddingBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n rows: readonly UpsertEmbeddingBatchRow[];\n}>;\n\n/**\n * Parameters for deleting an embedding.\n *\n * `dimensions` / `metric` / `indexType` mirror {@link UpsertEmbeddingParams}\n * so the backend can resolve the slot's typed per-`(nodeKind, fieldPath)`\n * storage and idempotently ensure it exists before the DELETE. That\n * matters because a delete can run before any embedding was ever written\n * (e.g. a node hard-deleted having never carried one), and on Postgres a\n * DELETE against a missing relation inside a transaction aborts the whole\n * transaction. The store populates them from the schema's `embedding()`\n * declaration, exactly as for upserts.\n */\nexport type DeleteEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * Parameters for vector similarity search.\n */\nexport type VectorSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n queryEmbedding: readonly number[];\n metric: VectorMetric;\n /**\n * Fixed vector dimension `N` for the searched `(nodeKind, fieldPath)`\n * slot. The store populates it from the schema's `embedding()`\n * declaration via `getEmbeddingDimensions()`; the backend uses it to\n * construct the `VectorSlot` whose typed storage the strategy scans.\n */\n dimensions: number;\n /**\n * Index type materialized for this slot. `\"none\"` means brute-force\n * only; otherwise the strategy may route through its ANN structure.\n * The store populates it from `getEmbeddingIndex()`.\n */\n indexType: VectorIndexType;\n limit: number;\n minScore?: number;\n /**\n * Subquery of eligible node ids (single column, exposed as `node_id`).\n * When present, the search statement computes top-k over this candidate\n * set — the store passes its compiled current-read query here so\n * `where` predicates push down into the search SQL. Exact on engines\n * whose search form takes the filter inside retrieval (pgvector,\n * sqlite-vec, tsvector, FTS5); libSQL's DiskANN cannot pre-filter, so\n * it post-filters an over-fetched ANN set and recall against the\n * candidate set is bounded by that headroom. When absent, the backend\n * restricts to CURRENT nodes of the kind — non-tombstoned AND inside\n * their validity window — matching a `current` read.\n */\n candidates?: SqlFragment;\n /**\n * Rows to skip AFTER ranking (pagination). The engine fetches\n * `limit + offset` ranked candidates and discards the first `offset`.\n */\n offset?: number;\n /**\n * HNSW search frontier for this query (pgvector `hnsw.ef_search`).\n * Sizes the dynamic candidate list the index scan maintains: higher\n * trades latency for recall. The floor for the over-fetch to fill its\n * candidate set is `efSearch >= limit`; ~2–4× is the high-recall\n * target. Applied transaction-locally (`SET LOCAL`) on the Postgres\n * HNSW path only. No-op on backends without an HNSW frontier knob\n * (sqlite-vec) and ignored — with a one-time warning — on Postgres\n * backends without transactions (e.g. `drizzle-orm/neon-http`).\n */\n efSearch?: number;\n}>;\n\n/**\n * Result from a vector similarity search.\n */\nexport type VectorSearchResult = Readonly<{\n nodeId: string;\n /**\n * Cosine metric returns similarity score (higher is better).\n * L2 and inner_product return raw distance (lower is better).\n */\n score: number;\n}>;\n\n/**\n * Parameters for a single-statement hybrid (vector + fulltext, RRF-fused)\n * search. The store facade resolves every default before calling — the\n * per-source candidate depths (`k`), the fusion constants, and the shared\n * `candidates` subquery — so the backend composes `SqlFragment` values without policy.\n */\nexport type HybridSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n vector: Readonly<{\n fieldPath: string;\n queryEmbedding: readonly number[];\n metric: VectorMetric;\n dimensions: number;\n indexType: VectorIndexType;\n /** Candidate depth of the vector source (rows entering fusion). */\n k: number;\n minScore?: number;\n efSearch?: number;\n }>;\n fulltext: Readonly<{\n query: string;\n mode?: FulltextQueryMode;\n language?: string;\n /** Candidate depth of the fulltext source (rows entering fusion). */\n k: number;\n minScore?: number;\n includeSnippets?: boolean;\n }>;\n fusion: Readonly<{\n /** RRF rank constant (`1 / (k + rank)`). */\n k: number;\n vectorWeight: number;\n fulltextWeight: number;\n }>;\n /** Fused rows to return after `offset`. */\n limit: number;\n /** Fused rows to skip (rank-relative pagination). */\n offset?: number;\n /** See {@link VectorSearchParams.candidates}; applies to both sources. */\n candidates?: SqlFragment;\n}>;\n\n/**\n * One fused hybrid hit, hydrated in the same statement: the node row\n * rides along so the caller needs no follow-up id fetch.\n */\nexport type HybridSearchRow = Readonly<{\n node: NodeRow;\n fusedScore: number;\n vectorRank?: number;\n vectorScore?: number;\n fulltextRank?: number;\n fulltextScore?: number;\n snippet?: string;\n}>;\n\n/**\n * Parameters for creating a vector index.\n */\nexport type CreateVectorIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n /** Index-specific parameters */\n indexParams?: Readonly<{\n /** HNSW: max connections per layer */\n m?: number;\n /** HNSW: construction search depth */\n efConstruction?: number;\n /** IVFFlat: number of lists */\n lists?: number;\n }>;\n /**\n * Build the index without taking an `AccessExclusiveLock` on live\n * tables (Postgres `CREATE INDEX CONCURRENTLY`). Mirrors the\n * `concurrent` flag the relational DDL path uses inside\n * `materializeIndexes()`. Cannot be set inside a transaction —\n * callers (`materializeIndexes()`) run at top level. Backends that\n * don't have a CONCURRENTLY equivalent (SQLite) ignore this flag.\n */\n concurrent?: boolean;\n}>;\n\n/**\n * Parameters for dropping a vector index.\n */\nexport type DropVectorIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n}>;\n\n// ============================================================\n// Fulltext Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating a fulltext entry.\n *\n * One row per node. Callers concatenate the searchable fields into\n * `content` so a single MATCH query can find terms spread across fields.\n *\n * Note: `createFulltextIndex` / `dropFulltextIndex` were removed as\n * dead code in #PR_E. The fulltext table's canonical index (Postgres\n * GIN on `tsv`, SQLite FTS5 virtual table) is created with the table\n * itself by `bootstrapTables` per the active `FulltextStrategy`;\n * per-kind fulltext indexes are an \"advanced strategy\" surface that\n * doesn't fit the relational-style declaration model and is reserved\n * for future work.\n */\nexport type UpsertFulltextParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n content: string;\n language: string;\n}>;\n\n/**\n * Parameters for deleting a single fulltext entry.\n */\nexport type DeleteFulltextParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * A single row in a fulltext batch upsert.\n */\nexport type FulltextBatchRow = Readonly<{\n nodeId: string;\n content: string;\n language: string;\n}>;\n\n/**\n * Parameters for a batched fulltext upsert.\n *\n * Homogeneous: one graph, one node kind, many nodes. Duplicate `nodeId`\n * values within a single batch are deduplicated last-write-wins by the\n * builders before SQL generation — Postgres `ON CONFLICT` errors on\n * repeated conflict keys in one statement, and SQLite `DELETE + INSERT`\n * would create duplicate virtual-table rows otherwise.\n */\nexport type UpsertFulltextBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n rows: readonly FulltextBatchRow[];\n}>;\n\n/**\n * Parameters for a batched fulltext delete.\n */\nexport type DeleteFulltextBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeIds: readonly string[];\n}>;\n\n/**\n * Parameters for fulltext search.\n */\nexport type FulltextSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n /** The user-supplied query string. */\n query: string;\n /** How to parse `query`. Default: \"websearch\". */\n mode?: FulltextQueryMode;\n /**\n * Language for query parsing. The store facade resolves the kind's\n * declared language and passes it here, so the tsquery is a plan-time\n * constant (GIN-servable); when absent the backend falls back to the\n * per-row language column.\n * Postgres: passed as the regconfig to `to_tsquery` / `websearch_to_tsquery`.\n * SQLite: informational only (FTS5 tokenizer is fixed at table-create time).\n */\n language?: string;\n /** Max rows to return. */\n limit: number;\n /** Minimum rank to include (backend-dependent units). */\n minScore?: number;\n /** Whether to return a highlighted snippet per match. */\n includeSnippets?: boolean;\n /**\n * Subquery of eligible node ids (single column). When present, the\n * search statement computes top-k over this candidate set — the store\n * passes its compiled current-read query here so `where` predicates,\n * subclass expansion, and valid-time currency all push down into the\n * search SQL. Exact on engines whose search form takes the filter\n * inside retrieval (pgvector, sqlite-vec, tsvector, FTS5); libSQL's\n * DiskANN cannot pre-filter, so it post-filters an over-fetched ANN\n * set and recall against the candidate set is bounded by that\n * headroom. When absent, the backend restricts to CURRENT nodes of\n * the kind — non-tombstoned AND inside their validity window —\n * matching a `current` read.\n */\n candidates?: SqlFragment;\n /**\n * Rows to skip AFTER ranking (pagination). The engine fetches\n * `limit + offset` ranked candidates and discards the first `offset`.\n */\n offset?: number;\n}>;\n\n/**\n * Result from a fulltext search.\n *\n * Score semantics differ by backend; prefer `rank` (1-based) when fusing\n * with another source via RRF.\n */\nexport type FulltextSearchResult = Readonly<{\n nodeId: string;\n /**\n * Backend-native relevance score.\n * Postgres: `ts_rank_cd` (higher is better).\n * SQLite FTS5: negated `bm25()` (higher is better; FTS5 returns lower-is-better).\n */\n score: number;\n /** 1-based rank within the result set, suitable for RRF. */\n rank: number;\n /** Highlighted snippet of the content (if `includeSnippets` was set). */\n snippet?: string;\n}>;\n\n/**\n * Parameters for creating a fulltext index.\n *\n * The canonical index (Postgres GIN on `tsv`, SQLite FTS5 virtual table)\n * is created when the fulltext table itself is created. This is reserved\n * for advanced per-kind specializations.\n */\n\n// ============================================================\n// Index Materialization Status\n// ============================================================\n\n/**\n * Per-deployment record for a single declared index.\n *\n * Identified by `indexName` because SQL index names are physical,\n * database-global identifiers — `graphId` is provenance, not identity.\n * `materializedAt` is null until the first successful CREATE INDEX\n * completes; `lastAttemptedAt` is always set, even on failure.\n */\n/**\n * Parameters for atomically claiming an index build (see\n * `claimIndexMaterialization`). The declaration fields ride along so a\n * fresh claim row is honest while the build is in flight.\n */\nexport type ClaimIndexMaterializationParams = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n /** Opaque claim identity; release is token-guarded. */\n token: string;\n /** A claim older than this is stale and may be taken over. */\n leaseMs: number;\n}>;\n\n/** Parameters for releasing a build claim (token-guarded). */\nexport type ReleaseIndexMaterializationClaimParams = Readonly<{\n indexName: string;\n token: string;\n}>;\n\nexport type IndexMaterializationRow = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n materializedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a materialization attempt.\n *\n * On success: pass `materializedAt` (ISO timestamp) and undefined `error`.\n * On failure: pass undefined `materializedAt` (preserve any existing\n * timestamp from a prior success) and the error message.\n */\nexport type RecordIndexMaterializationParams = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n attemptedAt: string;\n /** ISO timestamp on success; undefined on failure (preserves existing). */\n materializedAt: string | undefined;\n /** Error message on failure; undefined on success (clears existing). */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Contribution Materializations (#135 — durable strategy-owned\n// storage marker, sibling of index materializations)\n// ============================================================\n\n/**\n * Durable identity of a strategy-owned table contribution (#129),\n * scoped to a graph. This is the primary key of\n * `typegraph_contribution_materializations`.\n *\n * `logicalName` is the stable slot (\"fulltext\"); `owner` is the\n * producing strategy (\"tsvector\" / \"fts5\"); `tableName` is the resolved\n * physical name (custom per-deployment names must be distinguishable).\n * `graphId` is part of identity here — unlike the index status table\n * where the physical index name is database-global, two graphs can each\n * own a logically-identical fulltext contribution.\n */\nexport type ContributionMaterializationIdentity = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n}>;\n\n/**\n * Per-deployment record that a strategy-owned contribution has been\n * durably materialized against this database.\n *\n * `signature` is intentionally NOT part of the identity: a row with the\n * same identity but a different signature means \"materialized artifact\n * is stale/drifted\" — a loud error on the hot path, never a silent\n * re-materialize. `materializedAt` is undefined until the first\n * successful materialization; `lastAttemptedAt` is always set.\n */\nexport type ContributionMaterializationRow = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n signature: string;\n materializedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a contribution-materialization attempt.\n * Same success/failure contract as\n * {@link RecordIndexMaterializationParams}: on failure pass undefined\n * `materializedAt` so a prior successful timestamp is preserved via\n * COALESCE, and the error message.\n */\nexport type RecordContributionMaterializationParams = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n signature: string;\n attemptedAt: string;\n /** ISO timestamp on success; undefined on failure (preserves existing). */\n materializedAt: string | undefined;\n /** Error message on failure; undefined on success (clears existing). */\n error: string | undefined;\n}>;\n\n/**\n * Why a contribution is not usable. Most members are a disagreement\n * between the durable marker and the physical catalog; one\n * (`failed-materialization`) is a state the two agree on and that is\n * broken anyway. A contribution that is genuinely healthy — or that was\n * simply never attempted — is not reported at all.\n *\n * - `orphaned-marker` — the marker records a successful materialization\n * but the physical table is gone (a partial restore, an out-of-band\n * `DROP`, a schema-scoped restore that missed the contribution\n * tables). The state {@link GraphBackend.verifyContributions} exists\n * to surface: nothing on the open path probes the catalog, so this\n * database opens clean and fails at the first read of the slot.\n * - `missing-marker` — the physical table exists but no marker attests\n * it as initialized (no row, no recorded success, or a recorded\n * failure). Reads and writes are refused with\n * `StoreNotInitializedError` even though storage is present. These\n * three causes share one state because they share one repair; check\n * {@link ContributionDiagnostic.lastError} to tell them apart.\n * - `failed-materialization` — the marker records a *failed* attempt\n * and no table was produced. Marker and catalog agree here, so this\n * is not a disagreement — but it is where a contribution lands when\n * provisioning genuinely broke (the `fts5` module is absent, the role\n * lacks `CREATE`, the extension was never loaded), and calling it\n * healthy on the grounds that both sides agree would be the one\n * answer this method must never give. Distinguished from a\n * contribution that was never attempted, which has no marker row and\n * is correctly silent. {@link ContributionDiagnostic.lastError}\n * carries the reason it failed.\n * - `stale` — the table exists and the marker records a prior success\n * at a different signature (a strategy swap, or a declared embedding\n * dimension that has moved ahead of the provisioned table).\n *\n * **Do not re-frame this union as \"how the marker disagrees with the\n * catalog.\"** It was described that way once, and the description was\n * load-bearing in the wrong direction: under it, a marker recording a\n * failed attempt with no table looks like agreement, therefore not a\n * disagreement, therefore correctly silent — and a contribution that\n * had genuinely broken was reported as healthy. The gap read as\n * principled rather than as an oversight precisely because the framing\n * endorsed it. \"Why the contribution is unusable\" is the question that\n * makes `failed-materialization` obviously belong, and any future\n * tidy-up that narrows the framing back will re-open the same hole.\n */\nexport type ContributionDiagnosticState =\n \"orphaned-marker\" | \"missing-marker\" | \"failed-materialization\" | \"stale\";\n\n/**\n * One contribution that is not usable, reported by\n * {@link GraphBackend.verifyContributions}.\n *\n * The identity fields come from the active contribution declaration and\n * match the durable-marker identity contract, so a caller can route an entry\n * to its repair without reconstructing any internal naming contract. A\n * `missing-marker` entry may have no marker row at all.\n *\n * **Route on {@link ContributionDiagnosticState}, not on whether the\n * entry is a vector slot.** The repair differs per state and the wrong\n * choice destroys data: `store.reembedVectorField` drops and recreates\n * storage, so applying it to a `missing-marker` — where the table is\n * intact and only the bookkeeping is wrong — discards every embedding\n * to fix a marker, and without an `embed` callback it leaves the field\n * empty. Prefer `store.repairContributions()` for `missing-marker` and\n * `failed-materialization`; it resolves the current strategy declarations\n * internally and keeps the normal signature-drift guard enabled. It reports\n * `stale` and `orphaned-marker` as `requires-rebuild`. See the per-state\n * repair table in the troubleshooting guide.\n */\nexport type ContributionDiagnostic = Readonly<{\n /** Producing strategy, e.g. `\"fts5\"` / `\"tsvector\"` / `\"pgvector\"`. */\n owner: string;\n /** Stable logical slot, e.g. `\"fulltext\"`. Never the SQL name. */\n logicalName: string;\n /** Resolved physical table name that was probed. */\n physicalName: string;\n /** Node kind — vector slots only. */\n kind?: string;\n /** Embedding field path — vector slots only. */\n fieldPath?: string;\n state: ContributionDiagnosticState;\n /**\n * The error the marker recorded against its last attempt, when it\n * recorded one. Absent otherwise.\n *\n * This is the part of the picture the catalog cannot supply. `state`\n * says what to do — the states are chosen so that each maps to one\n * repair — while this says *why it broke*, which is a different\n * question and often a different investigation. A failed attempt with no\n * table surfaces as `failed-materialization`; when the table exists but\n * the marker does not attest a successful materialization, it surfaces as\n * `missing-marker`. This field distinguishes only failures whose marker\n * recorded a reason; a missing row has no `lastError`. Present on any state\n * whose marker row carries an error, not just those two states.\n */\n lastError?: string;\n}>;\n\n/**\n * Outcome of one contribution considered by\n * {@link GraphBackend.repairContributions}.\n *\n * Repair targets are always resolved from the backend's current strategy\n * declarations. The diagnostic is returned for operator context only; callers\n * never pass diagnostics or physical DDL back into the repair API.\n */\nexport type ContributionRepairEntry =\n | Readonly<{\n diagnostic: ContributionDiagnostic;\n status: \"repaired\";\n }>\n | Readonly<{\n diagnostic: ContributionDiagnostic;\n status: \"requires-rebuild\";\n }>\n | Readonly<{\n diagnostic: ContributionDiagnostic;\n status: \"failed\";\n error: string;\n }>;\n\n/** Result of a contribution repair pass followed by a fresh verification. */\nexport type ContributionRepairResult = Readonly<{\n results: readonly ContributionRepairEntry[];\n remaining: readonly ContributionDiagnostic[];\n}>;\n\n// ============================================================\n// Kind Removals (data-cleanup status)\n// ============================================================\n\n/**\n * One row of the per-deployment `typegraph_kind_removals` table:\n * a graph-extension kind that has been removed from the schema and whose\n * data may or may not have been cleaned up yet.\n */\nexport type KindRemovalRow = Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n /** ISO timestamp when the data-cleanup pass succeeded; undefined while pending. */\n removedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Upsert payload for a kind-removal status row. On removal-commit:\n * pass `removedAt: undefined` (the pending state). On successful\n * data-cleanup: pass `removedAt` set and `error: undefined`. On\n * cleanup failure: pass `removedAt: undefined` (preserves any prior\n * timestamp from a partial success on a different replica) and the\n * error message.\n */\nexport type RecordKindRemovalParams = Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n attemptedAt: string;\n /** ISO timestamp on success; undefined while pending or on failure. */\n removedAt: string | undefined;\n /** Error message on failure; undefined on success or while pending. */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Query Types\n// ============================================================\n\n/** @internal Capability token for connection-local temporary writes. */\nexport const INTERNAL_TEMPORARY_WRITES: unique symbol = typeGraphGlobalSymbol(\n \"internal-temporary-writes-v1\",\n);\n\n/**\n * Transaction options.\n */\nexport type TransactionOptions = Readonly<{\n /** Transaction isolation level (if supported) */\n isolationLevel?:\n \"read_uncommitted\" | \"read_committed\" | \"repeatable_read\" | \"serializable\";\n /**\n * Transaction access mode (if supported). `read_only` is intended for\n * multi-statement reads that need one snapshot and must not perform writes.\n */\n accessMode?: \"read_only\" | \"read_write\";\n}>;\n\n/** @internal Transaction options available only to TypeGraph-owned execution. */\nexport type InternalTransactionOptions = TransactionOptions &\n Readonly<{\n /**\n * Permit writes only to connection-local temporary state. The iterative\n * operation primitive uses this when an engine rejects temporary DDL in a\n * read-only transaction.\n */\n temporaryWrites?: typeof INTERNAL_TEMPORARY_WRITES;\n }>;\n\n// ============================================================\n// Backend Interface\n// ============================================================\n\n/**\n * The GraphBackend interface abstracts database operations.\n *\n * Implementations should provide:\n * - SQLite backend via better-sqlite3 or libsql\n * - PostgreSQL backend via pg or postgres\n *\n * Every function is receiver-free (`this: void`). Implementations must close\n * over their state instead of reading `this`, which makes saved optional\n * capabilities and other detached port calls safe by construction.\n */\nexport type GraphBackend = Readonly<{\n /** The SQL dialect */\n dialect: SqlDialect;\n /** Backend capabilities */\n capabilities: BackendCapabilities;\n /** Table names used by this backend (for query schema auto-derivation) */\n tableNames?: SqlTableNames | undefined;\n /**\n * Optional fulltext strategy override. When present, both the compiler\n * (for `$fulltext.matches()` in query builder) and backend-direct\n * search paths use this instead of the dialect's default strategy —\n * allowing a Postgres backend to ship pg_trgm, ParadeDB, pgroonga etc.\n * When absent, the dialect's default strategy is used.\n */\n fulltextStrategy?: FulltextStrategy | undefined;\n /**\n * Optional vector strategy this backend is wired with. The query\n * compiler reads it (via `compileQuery` options) to emit per-`(kind,\n * field)` relevance scans for `field.similarTo(...)` predicates, and\n * the index-materialization / removal paths read its deterministic\n * `tableName(...)` to address the right physical per-field storage.\n * `undefined` when the backend has no vector support (e.g. a generic\n * SQLite backend without sqlite-vec).\n */\n vectorStrategy?: VectorStrategy | undefined;\n\n // === Node Operations ===\n insertNode: (this: void, params: InsertNodeParams) => Promise<NodeRow>;\n insertNodeNoReturn?: (this: void, params: InsertNodeParams) => Promise<void>;\n insertNodesBatch?: (\n this: void,\n params: readonly InsertNodeParams[],\n ) => Promise<void>;\n insertNodesBatchReturning?: (\n this: void,\n params: readonly InsertNodeParams[],\n ) => Promise<readonly NodeRow[]>;\n updateNode: (this: void, params: UpdateNodeParams) => Promise<NodeRow>;\n updateNodeSet?: (\n this: void,\n params: UpdateNodeSetParams,\n ) => Promise<UpdateNodeSetResult>;\n deleteNode: (this: void, params: DeleteNodeParams) => Promise<void>;\n hardDeleteNode: (this: void, params: HardDeleteNodeParams) => Promise<void>;\n getNode: (\n this: void,\n graphId: string,\n kind: string,\n id: string,\n ) => Promise<NodeRow | undefined>;\n getNodes?: (\n this: void,\n graphId: string,\n kind: string,\n ids: readonly string[],\n ) => Promise<readonly NodeRow[]>;\n\n // === Edge Operations ===\n insertEdge: (this: void, params: InsertEdgeParams) => Promise<EdgeRow>;\n insertEdgeNoReturn?: (this: void, params: InsertEdgeParams) => Promise<void>;\n insertEdgesBatch?: (\n this: void,\n params: readonly InsertEdgeParams[],\n ) => Promise<void>;\n insertEdgesBatchReturning?: (\n this: void,\n params: readonly InsertEdgeParams[],\n ) => Promise<readonly EdgeRow[]>;\n updateEdge: (this: void, params: UpdateEdgeParams) => Promise<EdgeRow>;\n deleteEdge: (this: void, params: DeleteEdgeParams) => Promise<void>;\n hardDeleteEdge: (this: void, params: HardDeleteEdgeParams) => Promise<void>;\n /**\n * Batched {@link deleteEdge}: one soft-delete statement per bind-budget\n * chunk instead of one per edge. Optional — cascade deletes fall back to\n * the per-edge form when unset. Same per-row semantics (idempotent on\n * already-tombstoned rows).\n */\n deleteEdgesBatch?: (\n this: void,\n params: DeleteEdgesBatchParams,\n ) => Promise<void>;\n /** Batched {@link hardDeleteEdge}; see {@link deleteEdgesBatch}. */\n hardDeleteEdgesBatch?: (\n this: void,\n params: DeleteEdgesBatchParams,\n ) => Promise<void>;\n getEdge: (\n this: void,\n graphId: string,\n id: string,\n ) => Promise<EdgeRow | undefined>;\n getEdges?: (\n this: void,\n graphId: string,\n ids: readonly string[],\n ) => Promise<readonly EdgeRow[]>;\n\n // === Edge Cardinality Operations ===\n countEdgesFrom: (this: void, params: CountEdgesFromParams) => Promise<number>;\n edgeExistsBetween: (\n this: void,\n params: EdgeExistsBetweenParams,\n ) => Promise<boolean>;\n\n // === Edge Query Operations ===\n findEdgesConnectedTo: (\n this: void,\n params: FindEdgesConnectedToParams,\n ) => Promise<readonly EdgeRow[]>;\n\n // === Collection Query Operations ===\n findNodesByKind: (\n this: void,\n params: FindNodesByKindParams,\n ) => Promise<readonly NodeRow[]>;\n countNodesByKind: (\n this: void,\n params: CountNodesByKindParams,\n ) => Promise<number>;\n findEdgesByKind: (\n this: void,\n params: FindEdgesByKindParams,\n ) => Promise<readonly EdgeRow[]>;\n /**\n * Reads the edges of a SET of endpoints in one statement per bind-budget\n * chunk — see {@link FindEdgesByEndpointSetParams}.\n *\n * **Optional, and its absence is the capability signal.** `store.edges.<kind>\n * .bulkFindFrom` / `.bulkFindTo` check for this method before issuing any\n * read and refuse with a typed `ConfigurationError` when it is missing,\n * rather than degrading to a per-endpoint loop. A caller reaching for a bulk\n * endpoint read is asking for set-oriented statements; quietly giving them N\n * singleton statements is the surprise the method exists to prevent.\n *\n * Both bundled Drizzle backends implement it. A custom backend that does not\n * simply omits it and the bulk reads refuse; the singleton `findEdgesByKind`\n * path is unaffected.\n */\n findEdgesByEndpointSet?: (\n this: void,\n params: FindEdgesByEndpointSetParams,\n ) => Promise<readonly EdgeRow[]>;\n /**\n * Reads several edge kinds from a heterogeneous set of endpoints without\n * issuing one statement per licensed `(edge kind, endpoint kind)` pair.\n *\n * Optional for custom backends. Store-level heterogeneous bulk reads refuse\n * when it is absent rather than hiding a per-kind/per-endpoint fallback.\n */\n findEdgesByHeterogeneousEndpointSet?: (\n this: void,\n params: FindEdgesByHeterogeneousEndpointSetParams,\n ) => Promise<readonly EdgeRow[]>;\n countEdgesByKind: (\n this: void,\n params: CountEdgesByKindParams,\n ) => Promise<number>;\n\n // === Unique Constraint Operations ===\n insertUnique: (this: void, params: InsertUniqueParams) => Promise<void>;\n /**\n * Batched variant of `insertUnique`: one multi-row statement per chunk\n * with the same per-entry conflict semantics (throws `UniquenessError`\n * for the first entry whose key a different live node holds). Optional —\n * callers fall back to per-entry `insertUnique` when unset.\n */\n insertUniqueBatch?: (\n this: void,\n entries: readonly InsertUniqueParams[],\n ) => Promise<void>;\n deleteUnique: (this: void, params: DeleteUniqueParams) => Promise<void>;\n /**\n * Permanently removes every uniqueness sidecar owned by the specified\n * concrete nodes. Optional capability used by set-based updates before they\n * rebuild reservations from the returned node after-images.\n */\n hardDeleteUniquesByNodeIds?: (\n this: void,\n params: HardDeleteUniquesByNodeIdsParams,\n ) => Promise<void>;\n checkUnique: (\n this: void,\n params: CheckUniqueParams,\n ) => Promise<UniqueRow | undefined>;\n checkUniqueBatch?: (\n this: void,\n params: CheckUniqueBatchParams,\n ) => Promise<readonly UniqueRow[]>;\n\n // === Schema Operations ===\n getActiveSchema: (\n this: void,\n graphId: string,\n ) => Promise<SchemaVersionRow | undefined>;\n getSchemaVersion: (\n this: void,\n graphId: string,\n version: number,\n ) => Promise<SchemaVersionRow | undefined>;\n /**\n * Atomically inserts a new schema version and activates it as a single\n * transactional unit, with optimistic compare-and-swap on the currently\n * active version.\n *\n * - If `expected.kind === \"active\"` and the actual active version\n * differs, throws `StaleVersionError` (caller should refetch and\n * retry).\n * - If a row already exists at `params.version` with the same\n * `schemaHash`, returns it idempotently — reactivating it if it was\n * left inactive by an earlier crashed commit.\n * - If a row already exists at `params.version` with a different\n * `schemaHash`, throws `SchemaContentConflictError`.\n *\n * Requires `capabilities.transactions === true`. On non-transactional\n * backends (e.g. Cloudflare D1, drizzle-orm/neon-http) this method\n * throws `ConfigurationError` rather than running with degraded\n * atomicity that would silently re-introduce the orphan-row crash\n * window the primitive exists to eliminate.\n */\n commitSchemaVersion: (\n this: void,\n params: CommitSchemaVersionParams,\n ) => Promise<SchemaVersionRow>;\n /**\n * Commit a schema version only if every requested kind is empty. The probes\n * and schema CAS run under one backend-owned write fence, preventing a\n * participating schema-managed Store write from landing between the final\n * count and commit. Raw Stores and direct backend writes are not fenced.\n */\n commitSchemaVersionIfKindsEmpty?: (\n this: void,\n params: CommitSchemaVersionParams,\n probes: readonly Readonly<{\n entity: \"node\" | \"edge\";\n kind: string;\n }>[],\n ) => Promise<\n | Readonly<{ status: \"committed\"; row: SchemaVersionRow }>\n | Readonly<{\n status: \"populated\";\n kinds: readonly Readonly<{\n entity: \"node\" | \"edge\";\n kind: string;\n count: number;\n }>[];\n }>\n >;\n /**\n * Acquire the transaction-scoped shared fence for a schema-managed graph\n * write, then verify that the active schema still matches the Store that is\n * issuing it. Official transactional backends provide this method; custom\n * backends may omit it, in which case schema-managed Store writes fail\n * closed rather than racing a schema change. This method must be called on a\n * transaction-scoped backend. PostgreSQL locks the active schema row, so a\n * concurrent change either becomes visible at read committed or raises the\n * database's native serialization failure at stronger isolation.\n */\n lockSchemaVersionForWrite?: (\n this: void,\n params: Readonly<{ graphId: string; expectedVersion: number }>,\n ) => Promise<void>;\n /**\n * Atomically flips the active schema pointer to an existing version,\n * with optimistic compare-and-swap on the currently active version.\n * Used by `rollbackSchema` and any other \"promote/demote existing\n * version\" workflow. Throws `StaleVersionError` on CAS mismatch and\n * `MigrationError` if the target version row does not exist.\n *\n * Same transactional requirements as `commitSchemaVersion`.\n */\n setActiveVersion: (\n this: void,\n params: SetActiveVersionParams,\n ) => Promise<void>;\n\n /**\n * Run an administrative callback while holding the same per-graph lock as\n * schema commits. The callback receives the transaction-scoped backend, so\n * its reads, DML, and DDL are committed atomically before another schema\n * writer can proceed.\n *\n * This is intentionally absent from {@link TransactionBackend}: nesting a\n * schema-write lock from an already-open transaction can deadlock. It is an\n * optional backend capability so custom backends can decline operations\n * that require a schema fence rather than silently running them unsafely.\n */\n schemaWriteTransaction?: <T>(\n this: void,\n graphId: string,\n fn: (\n tx: TransactionBackend &\n Readonly<{\n executeStatement: NonNullable<TransactionBackend[\"executeStatement\"]>;\n tableExists: (this: void, tableName: string) => Promise<boolean>;\n executeSchemaDdl: (this: void, ddl: string) => Promise<void>;\n deleteSchemaVectorSlotContribution: (\n this: void,\n slot: VectorSlot,\n ) => Promise<void>;\n }>,\n ) => Promise<T>,\n ) => Promise<T>;\n\n // === Embedding Operations (optional - depends on vector capabilities) ===\n upsertEmbedding?: (\n this: void,\n params: UpsertEmbeddingParams,\n ) => Promise<void>;\n /**\n * Batched variant of `upsertEmbedding` for one vector slot. Optional —\n * callers fall back to per-row `upsertEmbedding` when unset.\n */\n upsertEmbeddingBatch?: (\n this: void,\n params: UpsertEmbeddingBatchParams,\n ) => Promise<void>;\n deleteEmbedding?: (\n this: void,\n params: DeleteEmbeddingParams,\n ) => Promise<void>;\n deleteEmbeddingBatch?: (\n this: void,\n params: Omit<DeleteEmbeddingParams, \"nodeId\"> &\n Readonly<{ nodeIds: readonly string[] }>,\n ) => Promise<void>;\n /**\n * KNN search over one `(nodeKind, fieldPath)` slot. Top-k is computed\n * over CURRENT nodes only — non-tombstoned AND inside their validity\n * window, matching a `current` read — so index drift (embedding rows\n * whose node was deleted or expired outside the store pipeline) can\n * neither surface nor crowd current rows out of the top-k. Custom\n * backends implementing this member must honor the same contract. Exact on pgvector >= 0.8 (HNSW via\n * `hnsw.iterative_scan = strict_order`; IVFFlat via\n * `ivfflat.iterative_scan = relaxed_order` plus a re-sort of the\n * bounded set; probe-bounded below 0.8) and sqlite-vec;\n * libSQL's DiskANN over-fetches 4x and post-filters (recall bounded by\n * that headroom).\n */\n vectorSearch?: (\n this: void,\n params: VectorSearchParams,\n ) => Promise<readonly VectorSearchResult[]>;\n createVectorIndex?: (\n this: void,\n params: CreateVectorIndexParams,\n ) => Promise<void>;\n dropVectorIndex?: (\n this: void,\n params: DropVectorIndexParams,\n ) => Promise<void>;\n /**\n * Single-statement hybrid search: both sources, RRF fusion, liveness\n * join, and node hydration composed into ONE statement — replacing the\n * facade's two search round trips plus id-hydration fetch. Optional;\n * the store falls back to the multi-statement path when unset (custom\n * backends, engines without window functions). Same liveness contract\n * as `vectorSearch` / `fulltextSearch`.\n */\n hybridSearch?: (\n this: void,\n params: HybridSearchParams,\n ) => Promise<readonly HybridSearchRow[]>;\n\n // === Fulltext Operations (optional - depends on fulltext capabilities) ===\n upsertFulltext?: (this: void, params: UpsertFulltextParams) => Promise<void>;\n deleteFulltext?: (this: void, params: DeleteFulltextParams) => Promise<void>;\n /**\n * Batched variant of `upsertFulltext`. Optional — callers fall back to\n * per-row `upsertFulltext` when unset.\n */\n upsertFulltextBatch?: (\n this: void,\n params: UpsertFulltextBatchParams,\n ) => Promise<void>;\n /**\n * Batched variant of `deleteFulltext`. Optional — callers fall back to\n * per-row `deleteFulltext` when unset.\n */\n deleteFulltextBatch?: (\n this: void,\n params: DeleteFulltextBatchParams,\n ) => Promise<void>;\n /**\n * Ranked fulltext search over one node kind. Like `vectorSearch`, top-k\n * is computed over CURRENT nodes only — non-tombstoned AND inside their\n * validity window (exact on both engines — plain WHERE, no top-k table\n * function involved). Custom backends implementing this member must\n * honor the same contract.\n */\n fulltextSearch?: (\n this: void,\n params: FulltextSearchParams,\n ) => Promise<readonly FulltextSearchResult[]>;\n\n // === Index Materialization (used by store.materializeIndexes) ===\n /**\n * Idempotently ensure ONLY the `typegraph_index_materializations`\n * table exists — separate from `bootstrapTables` so that\n * `materializeIndexes` doesn't pull in the full base-table DDL set\n * just to access the status table.\n *\n * Why focused: `bootstrapTables` issues 20+ `CREATE TABLE / CREATE\n * INDEX IF NOT EXISTS` statements covering every base table. Two\n * concurrent calls (e.g. two replicas of the same `schema_doc` both\n * starting up and calling `materializeIndexes`) race on\n * Postgres SHARE locks and DEADLOCK. Restricting the ensure-step to\n * the single status table eliminates the cross-table race entirely\n * — concurrent `CREATE TABLE IF NOT EXISTS` for one specific table\n * is well-behaved on Postgres.\n */\n ensureIndexMaterializationsTable?: (this: void) => Promise<void>;\n\n /**\n * Idempotently ensure ONLY the `typegraph_revision_origins` table exists.\n *\n * Revision-tracked stores use this per-graph, durable random origin together\n * with the recorded clock to prevent two independent stores with coincident\n * timestamps from sharing a merge base anchor. It is focused rather than\n * using `bootstrapTables` so existing deployments can adopt revision anchors\n * without replaying all base-table DDL during a merge read.\n */\n ensureRevisionOriginsTable?: (this: void) => Promise<void>;\n\n /**\n * Look up a recorded materialization for a declared index by its\n * physical SQL index name. Returns `undefined` if no row exists.\n */\n getIndexMaterialization?: (\n this: void,\n indexName: string,\n ) => Promise<IndexMaterializationRow | undefined>;\n /**\n * Bulk variant of `getIndexMaterialization`: load every recorded\n * materialization whose `indexName` (status key) is in `statusKeys`,\n * in a single round-trip. Returned rows are unordered — callers index\n * by `indexName`. Optional; consumers fall back to per-key\n * `getIndexMaterialization` when unset.\n */\n getIndexMaterializations?: (\n this: void,\n statusKeys: readonly string[],\n ) => Promise<readonly IndexMaterializationRow[]>;\n /**\n * Upsert a materialization attempt — success or failure. Failure rows\n * preserve any prior `materializedAt` so the historical successful\n * timestamp survives across error windows.\n */\n recordIndexMaterialization?: (\n this: void,\n params: RecordIndexMaterializationParams,\n ) => Promise<void>;\n /**\n * Atomically claims the build of one index across every materializer\n * (process- and pool-safe: the status row's own atomicity is the mutex).\n * Returns true when this caller now holds the claim. Backends whose\n * index builds cannot deadlock across callers (SQLite: engine-level\n * write serialization, no CONCURRENTLY) omit it; `materializeIndexes`\n * then builds without a claim, exactly as before.\n */\n claimIndexMaterialization?: (\n this: void,\n params: ClaimIndexMaterializationParams,\n ) => Promise<boolean>;\n /** Releases a claim taken by `claimIndexMaterialization` (token-guarded). */\n releaseIndexMaterializationClaim?: (\n this: void,\n params: ReleaseIndexMaterializationClaimParams,\n ) => Promise<void>;\n\n // === Contribution Materialization (#135 — durable strategy-owned\n // storage marker, sibling of the index status table) ===\n\n /**\n * Idempotently ensure ONLY the\n * `typegraph_contribution_materializations` table exists. Same\n * focused-bootstrap rationale as `ensureIndexMaterializationsTable`:\n * a single `CREATE TABLE IF NOT EXISTS` is concurrency-safe under\n * replica startup, where the full `bootstrapTables` set risks a\n * Postgres SHARE-lock deadlock.\n */\n ensureContributionMaterializationsTable?: (this: void) => Promise<void>;\n\n /**\n * Look up the durable materialization marker for one strategy-owned\n * contribution identity. Returns `undefined` when no row exists\n * (\"never initialized\").\n */\n getContributionMaterialization?: (\n this: void,\n identity: ContributionMaterializationIdentity,\n ) => Promise<ContributionMaterializationRow | undefined>;\n\n /**\n * Upsert a contribution-materialization attempt — success or failure.\n * Failure rows preserve any prior `materializedAt` via COALESCE so a\n * later failed re-attempt doesn't erase the historical success.\n */\n recordContributionMaterialization?: (\n this: void,\n params: RecordContributionMaterializationParams,\n ) => Promise<void>;\n\n /**\n * Resolve (once per backend instance, cached) and assert the durable\n * materialization markers for every `runtimeEnsure` contribution this\n * backend's strategy declares, for `graphId`. Throws\n * `StoreNotInitializedError` when a marker is missing, stale\n * (signature drift), or recorded a failed last attempt.\n *\n * This is the single read-side gate the fulltext hot-path wrappers\n * and `store.transaction()` consult. It performs ZERO DDL and ZERO\n * marker writes — initialization is the exclusive job of the async\n * boot path (`createStoreWithSchema` → `ensureRuntimeContributions`).\n */\n assertRuntimeContributionsInitialized?: (\n this: void,\n graphId: string,\n ) => Promise<void>;\n\n // === Kind Removal Status ===\n\n /**\n * Bootstraps the per-deployment `typegraph_kind_removals` table so\n * `store.evolve()` can check pending removals and the removal verbs can\n * persist and materialize removal status. Mirrors the focused-bootstrap\n * rationale documented on `ensureIndexMaterializationsTable` — the full\n * `bootstrapTables` touches every base table and risks Postgres SHARE-lock\n * deadlock under concurrent replica startup.\n */\n ensureKindRemovalsTable?: (this: void) => Promise<void>;\n\n /**\n * List graph-extension kind removals whose data-cleanup pass has not yet\n * succeeded for this `graphId`. Returns rows with\n * `removedAt: undefined`. Order is unspecified; callers materialize\n * one-at-a-time and don't depend on it.\n */\n getPendingKindRemovals?: (\n this: void,\n graphId: string,\n ) => Promise<readonly KindRemovalRow[]>;\n\n /**\n * List ALL kind-removal rows for a `graphId` — pending and completed.\n * Used by `materializeRemovals()` reconciliation to detect rows that\n * are missing entirely (the `removeKinds()` crash window) versus\n * already completed. Without this distinction the reconciler would\n * have to upsert every expected historical removal on every call,\n * churning `last_attempted_at` on rows that long since succeeded.\n * Order is unspecified.\n */\n getAllKindRemovals?: (\n this: void,\n graphId: string,\n ) => Promise<readonly KindRemovalRow[]>;\n\n /**\n * Upsert a kind-removal status row. `removedAt: undefined` records\n * the pending state at schema-commit time; `removedAt: <iso>`\n * marks the data cleanup successful. The COALESCE rule on `removedAt`\n * mirrors `recordIndexMaterialization` so a later failure doesn't\n * clobber the historical successful timestamp from another replica.\n */\n recordKindRemoval?: (\n this: void,\n params: RecordKindRemovalParams,\n ) => Promise<void>;\n\n // === Reconciliation Watermark ===\n\n /**\n * Bootstraps the per-deployment `typegraph_reconciliation_markers`\n * table so `materializeRemovals()` can persist reconciliation\n * progress. Same focused-bootstrap rationale as the other status\n * tables — full `bootstrapTables` risks Postgres SHARE-lock\n * deadlock under concurrent replica startup.\n */\n ensureReconciliationMarkersTable?: (this: void) => Promise<void>;\n\n // === Table Contributions (#129) ===\n\n /**\n * Materializes every contribution flagged `runtimeEnsure` — the\n * strategy-owned runtime tables (fulltext today) that drizzle-kit-\n * managed setups don't create. Called once after a successful schema\n * load. Deliberately scoped: base/drizzle-visible tables are\n * `runtimeEnsure: false`, so this does not regress startup into\n * broad DDL/probing across every table.\n *\n * The canonical durable-marker writer (#135): for each runtime\n * contribution it short-circuits when the marker already records a\n * matching signature, otherwise runs the idempotent `createDdl` and\n * records the marker (success or failure) keyed by `graphId`.\n */\n ensureRuntimeContributions?: (this: void, graphId: string) => Promise<void>;\n\n /**\n * Privileged materializer for one embedding `(kind, field)` slot's\n * `ownedTables` contribution(s): creates the per-field vector table and\n * records its durable marker, idempotently. The vector counterpart of\n * `ensureRuntimeContributions` — vectors are per-`(kind, field)` and\n * graph-derived, so the store enumerates slots (via\n * `resolveEmbeddingFields`) and uses the batch counterpart at boot under\n * the privileged role. Pass `{ force: true }` to overwrite the marker\n * at the current signature, bypassing the drift-guard — the sanctioned\n * path `store.reembedVectorField()` uses after recreating storage at a\n * new dimension. Pass `{ onDrift: \"skip\" }` to leave an\n * already-provisioned slot whose shape has since changed untouched\n * (warn + no-op) instead of refusing — the boot/evolve path, so a\n * declared dimension change never blocks startup before the operator\n * can run `reembedVectorField`. Present only on backends wired with a\n * vector strategy.\n */\n ensureVectorSlotContribution?: (\n this: void,\n slot: VectorSlot,\n options?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n ) => Promise<void>;\n\n /**\n * Batch form of `ensureVectorSlotContribution`, used by privileged boot to\n * resolve every slot's durable markers with one graph-scoped query. The\n * singular method remains available for re-embedding and compatibility.\n */\n ensureVectorSlotContributions?: (\n this: void,\n slots: readonly VectorSlot[],\n options?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n ) => Promise<void>;\n\n /**\n * SELECT-only gate for one embedding `(kind, field)` slot: asserts the\n * durable marker(s) for the slot's `ownedTables` contribution(s),\n * cached per backend instance. Throws `StoreNotInitializedError` when\n * the slot is missing, stale (signature drift), or recorded a failed\n * last attempt. The vector counterpart of\n * `assertRuntimeContributionsInitialized`, consulted by the verified\n * runtime attach. Performs ZERO DDL and ZERO writes. Present only on\n * backends wired with a vector strategy.\n */\n assertVectorSlotInitialized?: (this: void, slot: VectorSlot) => Promise<void>;\n\n /**\n * Batch form of `assertVectorSlotInitialized`, used by verified attach to\n * resolve every slot's durable markers with one graph-scoped query.\n */\n assertVectorSlotsInitialized?: (\n this: void,\n slots: readonly VectorSlot[],\n ) => Promise<void>;\n\n /**\n * Forget one embedding `(kind, field)` slot's durable contribution\n * marker(s). Called after the slot's per-field table is dropped\n * (vector-field reclaim) so a later `ensureVectorSlotContribution`\n * re-creates the table instead of trusting an orphaned \"initialized\"\n * marker. Does NOT drop the table itself (the caller already did).\n * Present only on backends wired with a vector strategy.\n */\n deleteVectorSlotContribution?: (\n this: void,\n slot: VectorSlot,\n ) => Promise<void>;\n\n /**\n * Diagnostic: compare each contribution currently expected for `graphId`\n * against its durable marker and the physical catalog.\n *\n * Covers the strategy-owned `runtimeEnsure` contributions (fulltext)\n * plus the `ownedTables` contribution(s) of each supplied vector slot.\n * Returns one {@link ContributionDiagnostic} per detected unusable\n * contribution. A recorded failed materialization is unusable even when\n * marker and catalog agree that no table was produced. A contribution with\n * neither a marker nor a table is treated as never attempted and omitted;\n * marker rows outside the current declaration set are not audited. An empty\n * array therefore is not proof that storage was initialized.\n *\n * Deliberately NOT part of the open path. `ensureRuntimeContributions`\n * and `assertRuntimeContributionsInitialized` short-circuit on a\n * per-instance signature cache and then on the marker row alone, which\n * is the right default for a hot path but leaves a database whose\n * contribution tables were dropped out of band opening clean and\n * failing at the first read. This method is the explicit, operator-\n * invoked catalog probe that fills that gap: it issues one uncached\n * existence query per distinct physical table and performs ZERO DDL\n * and ZERO writes, so it is safe under a least-privilege runtime role.\n *\n * Present only on backends that can probe their own catalog.\n */\n verifyContributions?: (\n this: void,\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ) => Promise<readonly ContributionDiagnostic[]>;\n\n /**\n * Re-audit current contribution declarations and non-destructively repair\n * `missing-marker` and `failed-materialization` findings. The backend must\n * resolve every target itself; it must not accept caller-provided physical\n * identities or DDL. `stale` and `orphaned-marker` findings are returned as\n * `requires-rebuild` because repairing either can require destructive data\n * reconstruction.\n *\n * Present only on backends that can both probe their catalog and run the\n * strategy-owned contribution DDL.\n */\n repairContributions?: (\n this: void,\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ) => Promise<ContributionRepairResult>;\n\n /**\n * Bootstraps the fulltext storage table the active `FulltextStrategy`\n * owns. Same focused-bootstrap rationale as the other `ensure*Table`\n * methods: idempotent and concurrency-safe under replica startup.\n *\n * Superseded by `ensureRuntimeContributions()` (#129); retained as\n * a thin back-compat wrapper for backends/callers predating #129. Not\n * machine-`@deprecated` because the manager still calls it as the\n * pre-#129 fallback. #135 removed the remaining hot-path callers and\n * routed this through the durable-marker writer.\n */\n ensureFulltextTable?: (this: void, graphId: string) => Promise<void>;\n\n /**\n * Read the high-water mark schema version for which\n * `materializeRemovals` reconciliation has already verified history\n * for `graphId`. Returns `undefined` when no marker has been\n * recorded yet. Used to skip already-checked transitions in the\n * recovery walk.\n */\n getReconciliationMarker?: (\n this: void,\n graphId: string,\n ) => Promise<number | undefined>;\n\n /**\n * Persist the reconciliation high-water mark for `graphId`. Called\n * after `materializeRemovals` completes a clean walk; subsequent\n * calls walk only versions newer than this marker. Idempotent\n * upsert by `graphId`.\n */\n setReconciliationMarker?: (\n this: void,\n graphId: string,\n version: number,\n ) => Promise<void>;\n\n // === Graph Lifecycle ===\n /**\n * Hard-deletes all data for a graph (nodes, edges, uniques, embeddings, schema versions).\n * Intended for import-replacement workflows. No hooks, no per-row logic.\n */\n clearGraph: (this: void, graphId: string) => Promise<void>;\n\n /**\n * Creates the base TypeGraph tables if they don't already exist.\n *\n * Called automatically by `createStoreWithSchema()` when a fresh database\n * is detected. Users who manage DDL themselves via `createStore()` never\n * hit this path.\n */\n bootstrapTables?: (this: void) => Promise<void>;\n\n /**\n * Refreshes the backend's query-planner statistics.\n *\n * Call this once after a large initial import or bulk backfill. Without\n * up-to-date statistics, the planner can pick suboptimal execution plans\n * — on PostgreSQL this is the difference between a 0.5ms and a 5ms\n * forward traversal; on SQLite it's the difference between 0.9ms and\n * 23ms fulltext search. Autovacuum / background statistics collection\n * will catch up eventually, but calling this explicitly after a bulk\n * load gives you correct latencies immediately.\n *\n * Implementations:\n * - SQLite runs `ANALYZE`, which populates `sqlite_stat1`\n * - PostgreSQL runs `ANALYZE` on the TypeGraph-managed tables\n *\n * Safe to call at any time; costs a few tens of milliseconds on the\n * sizes this library is designed for.\n */\n refreshStatistics: (this: void) => Promise<void>;\n\n /**\n * Runs an intentionally trusted, all-or-nothing initial import.\n *\n * Optional because only backends that can pin one transaction and use a\n * native high-throughput write path expose it. Implementations must reject\n * a database whose TypeGraph node or edge tables already contain rows. They\n * may temporarily remove rebuildable secondary indexes, but must restore\n * them before committing. Any callback, insert, or rebuild failure rolls the\n * entire operation back.\n *\n * This is a top-level-only lifecycle operation and is deliberately absent\n * from {@link TransactionBackend}. When `schemaWrite` is supplied, the\n * import acquires and validates that Store version's managed-write fence\n * before checking emptiness or writing. Omitting it retains the raw,\n * unversioned import behavior.\n */\n trustedImport?: <T>(\n this: void,\n fn: (session: TrustedImportSession) => Promise<T>,\n options?: Readonly<{\n schemaWrite?: Readonly<{ graphId: string; expectedVersion: number }>;\n }>,\n ) => Promise<T>;\n\n // === Query Execution ===\n execute: <T>(this: void, query: CompiledRowsSql) => Promise<readonly T[]>;\n\n /**\n * Execute a non-row-returning SQL statement bound to this backend or\n * transaction. Optional because custom backends may only expose the public\n * row-returning query path; features that need statement execution must\n * capability-check and fail loudly.\n */\n executeStatement?: (this: void, query: CompiledStatementSql) => Promise<void>;\n\n /**\n * Execute an internally compiled statement against connection-local\n * temporary state. History wrappers preserve this path because it cannot\n * mutate graph or history tables; callers cannot construct its branded\n * input through the public API.\n */\n executeTemporaryStatement?: (\n this: void,\n query: CompiledTemporaryStatementSql,\n ) => Promise<void>;\n\n /** Execute pre-compiled SQL text with bound parameters. Available on sync SQLite and pg backends. */\n executeRaw?: <T>(\n this: void,\n sqlText: string,\n params: readonly unknown[],\n ) => Promise<readonly T[]>;\n\n /** Compile a TypeGraph `SqlFragment` to `{ sql, params }` without executing. */\n compileSql?: (\n this: void,\n query: SqlFragment,\n ) => Readonly<{ sql: string; params: readonly unknown[] }>;\n\n /**\n * Execute a DDL statement that returns no rows (CREATE INDEX,\n * CREATE TABLE, ALTER TABLE, etc.). Separate from `executeRaw`\n * because some drivers (better-sqlite3) require `.run()` for DDL\n * and `.all()` for queries — the ambiguity can't be resolved by\n * inspecting the SQL string portably.\n *\n * Postgres path can use this for `CREATE INDEX CONCURRENTLY`, which\n * cannot run inside a transaction. Implementations must execute the\n * statement outside `transaction(...)`.\n */\n executeDdl?: (this: void, ddl: string) => Promise<void>;\n\n // === Transaction ===\n /** Runs TypeGraph operations inside a backend-owned transaction. */\n transaction: <T>(\n this: void,\n fn: (tx: TransactionBackend) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\n\n // === Lifecycle ===\n close: (this: void) => Promise<void>;\n}>;\n\n/**\n * Adapter-native transaction interoperability layered on top of the portable\n * TypeGraph backend. Only adapter entrypoints expose this capability.\n */\nexport type AdapterBackend<TNativeTransaction> = GraphBackend &\n Readonly<{\n /**\n * Runs TypeGraph operations and exposes the exact adapter-native handle\n * bound to the same transaction.\n */\n transactionWithNative: <T>(\n this: void,\n fn: (\n tx: TransactionBackend,\n nativeTransaction: TNativeTransaction,\n ) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\n /** Adopts a caller-owned, already-open adapter transaction. */\n adoptTransaction: (\n this: void,\n externalTransaction: TNativeTransaction,\n ) => TransactionBackend;\n }>;\n\nexport type BackendIdentity = Pick<\n GraphBackend,\n | \"dialect\"\n | \"capabilities\"\n | \"tableNames\"\n | \"fulltextStrategy\"\n | \"vectorStrategy\"\n>;\n\nexport type NodeEntityReadBackend = Pick<\n GraphBackend,\n \"getNode\" | \"getNodes\" | \"findNodesByKind\" | \"countNodesByKind\"\n>;\n\nexport type NodeEntityWriteBackend = Pick<\n GraphBackend,\n | \"insertNode\"\n | \"insertNodeNoReturn\"\n | \"insertNodesBatch\"\n | \"insertNodesBatchReturning\"\n | \"updateNode\"\n | \"updateNodeSet\"\n | \"deleteNode\"\n | \"hardDeleteNode\"\n>;\n\nexport type EdgeEntityReadBackend = Pick<\n GraphBackend,\n | \"getEdge\"\n | \"getEdges\"\n | \"countEdgesFrom\"\n | \"edgeExistsBetween\"\n | \"findEdgesConnectedTo\"\n | \"findEdgesByKind\"\n | \"findEdgesByEndpointSet\"\n | \"findEdgesByHeterogeneousEndpointSet\"\n | \"countEdgesByKind\"\n>;\n\nexport type EdgeEntityWriteBackend = Pick<\n GraphBackend,\n | \"insertEdge\"\n | \"insertEdgeNoReturn\"\n | \"insertEdgesBatch\"\n | \"insertEdgesBatchReturning\"\n | \"updateEdge\"\n | \"deleteEdge\"\n | \"deleteEdgesBatch\"\n | \"hardDeleteEdge\"\n | \"hardDeleteEdgesBatch\"\n>;\n\nexport type GraphEntityReadBackend = NodeEntityReadBackend &\n EdgeEntityReadBackend;\n\nexport type GraphEntityWriteBackend = NodeEntityWriteBackend &\n EdgeEntityWriteBackend;\n\nexport type UniqueConstraintBackend = Pick<\n GraphBackend,\n | \"insertUnique\"\n | \"insertUniqueBatch\"\n | \"deleteUnique\"\n | \"hardDeleteUniquesByNodeIds\"\n | \"checkUnique\"\n | \"checkUniqueBatch\"\n>;\n\nexport type SchemaReadBackend = Pick<\n GraphBackend,\n \"getActiveSchema\" | \"getSchemaVersion\"\n>;\n\nexport type SchemaCommitBackend = Pick<\n GraphBackend,\n \"commitSchemaVersion\" | \"commitSchemaVersionIfKindsEmpty\" | \"setActiveVersion\"\n>;\n\nexport type SchemaWriteFenceBackend = Pick<\n GraphBackend,\n \"lockSchemaVersionForWrite\"\n>;\n\nexport type VectorOperationBackend = Pick<\n GraphBackend,\n | \"upsertEmbedding\"\n | \"upsertEmbeddingBatch\"\n | \"deleteEmbedding\"\n | \"deleteEmbeddingBatch\"\n | \"vectorSearch\"\n | \"createVectorIndex\"\n | \"dropVectorIndex\"\n>;\n\nexport type FulltextOperationBackend = Pick<\n GraphBackend,\n | \"upsertFulltext\"\n | \"deleteFulltext\"\n | \"upsertFulltextBatch\"\n | \"deleteFulltextBatch\"\n | \"fulltextSearch\"\n>;\n\nexport type IndexMaterializationBackend = Pick<\n GraphBackend,\n | \"ensureIndexMaterializationsTable\"\n | \"getIndexMaterialization\"\n | \"getIndexMaterializations\"\n | \"recordIndexMaterialization\"\n>;\n\nexport type ContributionMaterializationBackend = Pick<\n GraphBackend,\n | \"ensureContributionMaterializationsTable\"\n | \"getContributionMaterialization\"\n | \"recordContributionMaterialization\"\n | \"assertRuntimeContributionsInitialized\"\n | \"ensureRuntimeContributions\"\n | \"ensureFulltextTable\"\n>;\n\nexport type RemovalMaterializationBackend = Pick<\n GraphBackend,\n | \"ensureKindRemovalsTable\"\n | \"getPendingKindRemovals\"\n | \"getAllKindRemovals\"\n | \"recordKindRemoval\"\n | \"ensureReconciliationMarkersTable\"\n | \"getReconciliationMarker\"\n | \"setReconciliationMarker\"\n>;\n\nexport type GraphLifecycleBackend = Pick<\n GraphBackend,\n \"clearGraph\" | \"bootstrapTables\"\n>;\n\nexport type QueryExecutionBackend = Pick<GraphBackend, \"execute\">;\n\nexport type RawQueryExecutionBackend = Pick<\n GraphBackend,\n \"executeRaw\" | \"compileSql\"\n>;\n\nexport type SqlCompilationBackend = Pick<GraphBackend, \"compileSql\">;\n\nexport type RawStatementExecutionBackend = Pick<\n GraphBackend,\n \"executeStatement\" | \"executeTemporaryStatement\" | \"executeDdl\"\n>;\n\nexport type BackendMaintenance = Pick<GraphBackend, \"refreshStatistics\">;\n\nexport type BackendTransactions = Pick<GraphBackend, \"transaction\">;\n\nexport type AdapterBackendTransactions<TNativeTransaction> = Pick<\n AdapterBackend<TNativeTransaction>,\n \"transactionWithNative\" | \"adoptTransaction\"\n>;\n\nexport type BackendLifecycle = Pick<GraphBackend, \"close\">;\n\n/**\n * Read-oriented transaction projection exposed by portable transaction\n * contexts. It preserves snapshot-aware graph reads and TypeGraph-compiled\n * row queries while excluding graph writes, arbitrary raw SQL, DDL,\n * transaction adoption, and lifecycle control.\n */\nexport type TransactionReadBackend = Readonly<\n BackendIdentity &\n GraphEntityReadBackend &\n SchemaReadBackend &\n QueryExecutionBackend &\n SqlCompilationBackend\n>;\n\n/**\n * Transaction backend — a backend scoped to a transaction.\n *\n * This is an explicit facet composition, not `Omit<GraphBackend, ...>`.\n * New top-level-only backend methods therefore do not silently appear on\n * transaction-scoped backends. `commitSchemaVersion`, `setActiveVersion`,\n * `refreshStatistics`, `transaction`, `adoptTransaction`, and `close` stay\n * deliberately absent: their guarantees depend on the top-level backend or\n * lifecycle owner rather than an already-open transaction.\n */\nexport type TransactionBackend = Readonly<\n BackendIdentity &\n GraphEntityReadBackend &\n GraphEntityWriteBackend &\n UniqueConstraintBackend &\n SchemaReadBackend &\n Pick<GraphBackend, \"lockSchemaVersionForWrite\"> &\n VectorOperationBackend &\n FulltextOperationBackend &\n IndexMaterializationBackend &\n ContributionMaterializationBackend &\n RemovalMaterializationBackend &\n GraphLifecycleBackend &\n QueryExecutionBackend &\n RawQueryExecutionBackend &\n RawStatementExecutionBackend\n>;\n\n/**\n * Transaction backend exposed only while the backend's schema-write lock is\n * held. Unlike the ordinary top-level `executeDdl` port, this DDL primitive is\n * explicitly transaction-scoped and must use the callback's transaction.\n *\n * @internal\n */\nexport type SchemaWriteTransactionBackend = TransactionBackend &\n Readonly<{\n executeStatement: NonNullable<TransactionBackend[\"executeStatement\"]>;\n tableExists: (this: void, tableName: string) => Promise<boolean>;\n executeSchemaDdl: (this: void, ddl: string) => Promise<void>;\n deleteSchemaVectorSlotContribution: (\n this: void,\n slot: VectorSlot,\n ) => Promise<void>;\n }>;\n\n/**\n * Builds the actual runtime projection exposed as `TransactionContext.backend`.\n * This is an explicit object rather than a type-only narrowing so portable\n * callers cannot discover write or arbitrary-SQL methods on the underlying\n * transaction backend at runtime.\n *\n * @internal\n */\nexport function createTransactionReadBackend(\n backend: TransactionBackend,\n): TransactionReadBackend {\n const getNodes = backend.getNodes;\n const getEdges = backend.getEdges;\n const compileSql = backend.compileSql;\n\n return Object.freeze({\n dialect: backend.dialect,\n capabilities: backend.capabilities,\n ...(backend.tableNames === undefined ?\n {}\n : { tableNames: backend.tableNames }),\n ...(backend.fulltextStrategy === undefined ?\n {}\n : { fulltextStrategy: backend.fulltextStrategy }),\n ...(backend.vectorStrategy === undefined ?\n {}\n : { vectorStrategy: backend.vectorStrategy }),\n getNode: (graphId, kind, id) => backend.getNode(graphId, kind, id),\n ...(getNodes === undefined ?\n {}\n : {\n getNodes: (graphId: string, kind: string, ids: readonly string[]) =>\n getNodes(graphId, kind, ids),\n }),\n getEdge: (graphId, id) => backend.getEdge(graphId, id),\n ...(getEdges === undefined ?\n {}\n : {\n getEdges: (graphId: string, ids: readonly string[]) =>\n getEdges(graphId, ids),\n }),\n countEdgesFrom: (params) => backend.countEdgesFrom(params),\n edgeExistsBetween: (params) => backend.edgeExistsBetween(params),\n findEdgesConnectedTo: (params) => backend.findEdgesConnectedTo(params),\n findNodesByKind: (params) => backend.findNodesByKind(params),\n countNodesByKind: (params) => backend.countNodesByKind(params),\n findEdgesByKind: (params) => backend.findEdgesByKind(params),\n countEdgesByKind: (params) => backend.countEdgesByKind(params),\n getActiveSchema: (graphId) => backend.getActiveSchema(graphId),\n getSchemaVersion: (graphId, version) =>\n backend.getSchemaVersion(graphId, version),\n execute: <T>(query: CompiledRowsSql) => backend.execute<T>(query),\n ...(compileSql === undefined ?\n {}\n : { compileSql: (query: SqlFragment) => compileSql(query) }),\n });\n}\n\ntype ExactBackendOverlay<T extends object, O extends Partial<T>> = O &\n Readonly<Record<Exclude<keyof O, keyof T>, never>>;\n\n// ============================================================\n// Managed Backend Helper\n// ============================================================\n\n/**\n * Overlays selected backend methods without copying the backend object.\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. GraphBackend functions are receiver-free\n * by contract, so delegated methods are returned unchanged.\n */\nexport function createBackendOverlay<\n T extends GraphBackend | TransactionBackend,\n const O extends Partial<T> = Partial<T>,\n>(target: T, overlay: ExactBackendOverlay<T, O>): T {\n function hasOverlayProperty(property: PropertyKey): boolean {\n return Object.hasOwn(overlay, property);\n }\n\n return new Proxy(target, {\n get(targetObject, property) {\n if (hasOverlayProperty(property)) {\n return Reflect.get(overlay, property, overlay);\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(overlay),\n ]),\n ];\n },\n\n getOwnPropertyDescriptor(targetObject, property) {\n if (hasOverlayProperty(property)) {\n const descriptor = Reflect.getOwnPropertyDescriptor(overlay, property);\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(overlay, property, value, overlay);\n }\n return Reflect.set(targetObject, property, value, targetObject);\n },\n\n defineProperty(targetObject, property, attributes) {\n if (hasOverlayProperty(property)) {\n return Reflect.defineProperty(overlay, property, attributes);\n }\n return Reflect.defineProperty(targetObject, property, attributes);\n },\n\n deleteProperty(targetObject, property) {\n if (hasOverlayProperty(property)) {\n return Reflect.deleteProperty(overlay, property);\n }\n return Reflect.deleteProperty(targetObject, property);\n },\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 createBackendOverlay(backend, closeOverlay);\n}\n\n/**\n * Closes an owned resource after provisioning fails without replacing the\n * original domain error with a secondary cleanup failure.\n */\nexport async function closeAfterFailure(\n resource: Readonly<{ close: () => void | Promise<void> }>,\n provisioningError: unknown,\n): Promise<never> {\n try {\n await resource.close();\n } catch {\n // The provisioning failure remains the actionable error. Managed close is\n // retryable when the resource is returned, but a failed factory has no\n // handle it can safely expose for a second attempt.\n }\n throw provisioningError;\n}\n\n/**\n * Runs `fn` inside a transaction when given a top-level backend that supports\n * one, falling through to a direct invocation otherwise. Lets call sites benefit\n * from atomicity on backends that have transactions while staying functional on\n * backends that don't (Cloudflare D1, `drizzle-orm/neon-http` over HTTP), and\n * avoids opening nested transactions when the caller already holds a\n * transaction-scoped backend. The single-statement race window is already\n * implicit on any backend that reports `transactions: false`; callers that\n * cannot tolerate it must branch on the capability themselves.\n *\n * Pass `fallback` only when the toplevel backend method would recurse\n * — pass the operation-level backend so the no-tx path doesn't loop\n * back through the same toplevel method.\n */\nexport async function runOptionallyInTransaction<T>(\n backend: GraphBackend | TransactionBackend,\n fn: (target: GraphBackend | TransactionBackend) => Promise<T>,\n fallback?: GraphBackend | TransactionBackend,\n): Promise<T> {\n if (\"transaction\" in backend && backend.capabilities.transactions) {\n return backend.transaction((tx) => fn(tx));\n }\n return fn(fallback ?? backend);\n}\n\n// ============================================================\n// Additional Parameter Types\n// ============================================================\n\n/**\n * Parameters for inserting a unique constraint entry.\n */\nexport type InsertUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n nodeId: string;\n concreteKind: string;\n}>;\n\n/**\n * Parameters for deleting a unique constraint entry.\n */\nexport type DeleteUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n}>;\n\n/** Parameters for permanently clearing uniqueness sidecars by node identity. */\nexport type HardDeleteUniquesByNodeIdsParams = Readonly<{\n graphId: string;\n concreteKind: string;\n nodeIds: readonly string[];\n}>;\n\n/**\n * Parameters for checking a unique constraint.\n */\nexport type CheckUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for batch-checking unique constraints.\n */\nexport type CheckUniqueBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n keys: readonly string[];\n /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for inserting a schema version.\n *\n * Used internally by backend implementations. Public callers go through\n * `commitSchemaVersion`, which handles the insert + activate atomically\n * with CAS guarantees.\n */\nexport type InsertSchemaParams = Readonly<{\n graphId: string;\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n isActive: boolean;\n}>;\n\n/**\n * The caller's claim about the currently-active schema version, used as\n * the optimistic compare-and-swap guard for `commitSchemaVersion`.\n *\n * - `{ kind: \"initial\" }` — caller is committing the first-ever version\n * for this graph and asserts no active version exists yet.\n * - `{ kind: \"active\", version: N }` — caller observed version N as\n * active and is committing version N+1 against that baseline. The\n * commit fails with `StaleVersionError` if some other writer has\n * advanced or rolled back the pointer in the meantime.\n *\n * Tagged-union form (rather than a magic `version: 0` sentinel) because\n * the two cases have materially different semantics: the initial path\n * skips the \"deactivate prior\" UPDATE, and the no-active-row state is\n * a *valid* expected state, not an out-of-band signal.\n */\nexport type CommitSchemaVersionExpected =\n Readonly<{ kind: \"initial\" }> | Readonly<{ kind: \"active\"; version: number }>;\n\n/**\n * Parameters for `commitSchemaVersion`.\n */\nexport type CommitSchemaVersionParams = Readonly<{\n graphId: string;\n /** CAS guard — see `CommitSchemaVersionExpected`. */\n expected: CommitSchemaVersionExpected;\n /** The new version to insert and activate. */\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n}>;\n\nexport type SchemaKindEmptinessProbe = Readonly<{\n entity: \"node\" | \"edge\";\n kind: string;\n}>;\n\nexport type PopulatedSchemaKind = SchemaKindEmptinessProbe &\n Readonly<{ count: number }>;\n\nexport type CommitSchemaVersionIfKindsEmptyResult =\n | Readonly<{ status: \"committed\"; row: SchemaVersionRow }>\n | Readonly<{\n status: \"populated\";\n kinds: readonly PopulatedSchemaKind[];\n }>;\n\nexport type LockSchemaVersionForWriteParams = Readonly<{\n graphId: string;\n expectedVersion: number;\n}>;\n\n/**\n * Optional schema-managed write identity for a trusted import. Supplying it\n * acquires and validates the Store version's transaction-scoped schema fence;\n * omitting it leaves the import outside the versioned guarantee.\n */\nexport type TrustedImportOptions = Readonly<{\n schemaWrite?: Readonly<{ graphId: string; expectedVersion: number }>;\n}>;\n\n/**\n * Parameters for `setActiveVersion`.\n *\n * Flips the active pointer from `expected` to `version` for an existing\n * row. CAS prevents overwriting a concurrent rollback or commit.\n */\nexport type SetActiveVersionParams = Readonly<{\n graphId: string;\n /** CAS guard. Same semantics as `commitSchemaVersion.expected`. */\n expected: CommitSchemaVersionExpected;\n /** The version to mark active. Must already exist. */\n version: number;\n}>;\n\n/**\n * Parameters for counting edges from a source node.\n */\nexport type CountEdgesFromParams = Readonly<{\n graphId: string;\n edgeKind: string;\n fromKind: string;\n fromId: string;\n /** If true, only count edges where valid_to IS NULL */\n activeOnly?: boolean;\n}>;\n\n/**\n * Parameters for checking if an edge exists between two nodes.\n */\nexport type EdgeExistsBetweenParams = Readonly<{\n graphId: string;\n edgeKind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n}>;\n\n/**\n * Parameters for finding edges connected to a node.\n */\nexport type FindEdgesConnectedToParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * Parameters for finding nodes by kind.\n */\nexport type FindNodesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n /** Max rows to return. */\n limit?: number;\n /** Offset. Present for backward compat; rebuild uses `after` instead. */\n offset?: number;\n /** If true, exclude deleted nodes. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n /**\n * Stable ordering for keyset pagination. Default: \"created_at\" (existing\n * behavior). Rebuild should use \"id\" for iteration that is stable under\n * concurrent writes and shared timestamps.\n */\n orderBy?: \"id\" | \"created_at\";\n /**\n * Keyset cursor. Returns rows strictly greater (by `orderBy`) than this\n * value. When `orderBy: \"id\"`, compared lexicographically. Mutually\n * exclusive with `offset` — callers pick one.\n */\n after?: string;\n}>;\n\n/**\n * Parameters for counting nodes by kind.\n */\nexport type CountNodesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n /** If true, exclude deleted nodes. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n/**\n * Parameters for finding edges by kind.\n */\nexport type FindEdgesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n limit?: number;\n offset?: number;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n /**\n * Stable ordering for keyset pagination. Default: \"created_at\" (existing\n * behavior). Use \"id\" for iteration that is stable under shared `created_at`\n * timestamps — the offset path orders by the NON-unique `created_at`, so a\n * full enumeration must page by the unique `id` to avoid skipping a row at a\n * page boundary. Mirrors {@link FindNodesByKindParams.orderBy}.\n */\n orderBy?: \"id\" | \"created_at\";\n /**\n * Keyset cursor. Returns rows strictly greater (by `orderBy`) than this value.\n * When `orderBy: \"id\"`, compared lexicographically. Mutually exclusive with\n * `offset` — callers pick one. Mirrors {@link FindNodesByKindParams.after}.\n */\n after?: string;\n}>;\n\n/**\n * The endpoint side a {@link FindEdgesByEndpointSetParams} read fans out over.\n */\nexport type EdgeEndpointSide = \"from\" | \"to\";\n\n/**\n * Parameters for reading the edges of a SET of endpoints in one statement per\n * bind-budget chunk — the widened form of {@link FindEdgesByKindParams}'s\n * scalar `fromId` / `toId`.\n *\n * Deliberately a SEPARATE parameter type on a separate operation rather than\n * optional fields on `FindEdgesByKindParams`. A backend that did not implement\n * set membership would still type-check while ignoring the id list, and would\n * then return every edge of the kind — which the caller would rebucket into a\n * correct-looking answer at unbounded cost. Splitting the operation makes that\n * failure unreachable: support is detected by the method's presence, before any\n * read is issued.\n *\n * The shape also makes the previously-validated illegal states\n * unrepresentable. One `side` instead of two independent id lists means both\n * endpoints can never fan out at once; no scalar `fromId` / `toId` field means\n * a scalar and a set can never disagree; no `limit` / `offset` / `after` means\n * a global slice can never be requested across a read the backend splits into\n * bind-budget chunks.\n */\nexport type FindEdgesByEndpointSetParams = Readonly<{\n graphId: string;\n kind: string;\n /** Which endpoint column the id set constrains. */\n side: EdgeEndpointSide;\n /**\n * Kind of the fanned-out endpoint. Required: it is the index prefix that\n * makes the set a seek rather than a scan, so a set is always scoped to one\n * endpoint kind and a heterogeneous page costs one read per distinct kind.\n */\n endpointKind: string;\n /**\n * Endpoint NODE ids to match — deliberately not named `ids`, which in the\n * backend params vocabulary means edge ids (see\n * {@link DeleteEdgesBatchParams}); the write-surface assertion in\n * `recorded-capture/write-surface.ts` classifies params structurally and a\n * `{ graphId, ids }` read would be misread as a write.\n *\n * The backend deduplicates before splitting the list across bind-budget\n * chunks — a repeated id spanning two chunks would return its edges twice.\n * An empty list reads nothing and yields no rows.\n */\n endpointIds: readonly string[];\n /**\n * Maximum rows per distinct endpoint id, applied inside the statement (via\n * `ROW_NUMBER()` over the read's own ordering) rather than by the caller.\n * Only meaningful on a backend whose `capabilities.windowFunctions` is true;\n * callers must still cap client-side, so a backend that ignores this returns\n * a superset rather than a wrong answer. Unlike a global `limit`, a\n * per-endpoint cap composes with chunking: each endpoint's rows fall\n * entirely within one chunk.\n */\n limitPerEndpoint?: number;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n/**\n * Parameters for reading several edge kinds from several endpoint kinds.\n *\n * The endpoint pairs are joined as a relation, so round trips are independent\n * of the number of licensed edge-kind/endpoint-kind combinations. Large source\n * sets may still be split to respect the backend's bind-parameter budget.\n */\nexport type FindEdgesByHeterogeneousEndpointSetParams = Readonly<{\n graphId: string;\n side: EdgeEndpointSide;\n endpoints: readonly Readonly<{ kind: string; id: string }>[];\n edgeKinds: readonly string[];\n limitPerEndpoint?: number;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n/**\n * Parameters for counting edges by kind.\n */\nexport type CountEdgesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n// ============================================================\n// Default Capabilities\n// ============================================================\n\n/**\n * Conservative per-statement bound-parameter floor for SQLite. The\n * compiled-in `SQLITE_MAX_VARIABLE_NUMBER` defaulted to 999 before SQLite\n * 3.32.0; drivers whose real ceiling cannot be probed (async/remote\n * connections) keep this floor. Single source of truth for\n * {@link SQLITE_CAPABILITIES} and the SQLite backend's batch math fallback.\n */\nexport const SQLITE_MAX_BIND_PARAMETERS = 999;\n\n/**\n * `SQLITE_MAX_VARIABLE_NUMBER` default since SQLite 3.32.0 (better-sqlite3\n * also compiles it in explicitly). Used when a synchronous driver's probe\n * confirms a modern build.\n */\nexport const MODERN_SQLITE_MAX_BIND_PARAMETERS = 32_766;\n\n/**\n * Cloudflare D1's documented per-statement bound-parameter ceiling. Far\n * below the classic SQLite floor, so D1 detection must cap the budget or\n * batched writes fail at runtime.\n */\nexport const D1_MAX_BIND_PARAMETERS = 100;\n\n/**\n * Cloudflare SQLite-backed Durable Objects' documented per-statement\n * bound-parameter ceiling. The resolved `do-sqlite` execution profile must\n * advertise this limit so every capability-driven batch path stays below it.\n */\nexport const DURABLE_OBJECT_MAX_BIND_PARAMETERS = 100;\n\n/**\n * Safe bound-parameter ceiling shared by every bundled PostgreSQL driver.\n * The protocol count can represent 65535, but postgres.js rejects a statement\n * with 65534 bound values, so backend batch math uses the lower portable limit.\n */\nexport const POSTGRES_MAX_BIND_PARAMETERS = 65_533;\n\n/**\n * Default capabilities for SQLite.\n */\nexport const SQLITE_CAPABILITIES: BackendCapabilities = Object.freeze({\n transactions: true, // SQLite supports transactions\n windowFunctions: true, // SQLite has supported window functions since 3.25.0\n returning: true, // SQLite has supported RETURNING since 3.35.0\n maxBindParameters: SQLITE_MAX_BIND_PARAMETERS,\n // Generic SQLite builds do not guarantee ENABLE_MATH_FUNCTIONS. The local\n // better-sqlite3 factory overrides this flag for its bundled build contract.\n graphAnalytics: Object.freeze({ supported: true, mathFunctions: false }),\n});\n\n/**\n * Default capabilities for PostgreSQL.\n */\nexport const POSTGRES_CAPABILITIES: BackendCapabilities = Object.freeze({\n transactions: true, // PostgreSQL supports transactions\n windowFunctions: true, // PostgreSQL supports ROW_NUMBER() and related windows\n returning: true, // PostgreSQL has supported RETURNING since 8.2\n maxBindParameters: POSTGRES_MAX_BIND_PARAMETERS,\n graphAnalytics: Object.freeze({ supported: true, mathFunctions: true }),\n});\n"]}
@@ -1,10 +1,10 @@
1
- import { createSqliteTables, sqliteContributions, createPostgresTables, postgresContributions } from './chunk-Z3WIL6S3.js';
2
- import { createSqlSchema } from './chunk-CDYRPI5U.js';
3
- import { asRecordedInstant, createRecordedInstant, RECORDED_MAX_REVISION } from './chunk-2OOY4OYT.js';
4
- import { canonicalizeDatabaseTimestamp } from './chunk-GT7NEXSU.js';
5
- import { shortHash } from './chunk-42XYPKZU.js';
6
- import { asCompiledRowsSql, sql, asCompiledStatementSql } from './chunk-M4GYQF2H.js';
7
- import { ConfigurationError, ValidationError } from './chunk-OYJSYDIH.js';
1
+ import { createSqliteTables, sqliteContributions, createPostgresTables, postgresContributions } from './chunk-BGYJW37L.js';
2
+ import { createSqlSchema } from './chunk-MIJKEVV7.js';
3
+ import { asRecordedInstant, createRecordedInstant, RECORDED_MAX_REVISION } from './chunk-2L54C2C2.js';
4
+ import { canonicalizeDatabaseTimestamp } from './chunk-KCO5EFJU.js';
5
+ import { shortHash } from './chunk-PVUI6KGR.js';
6
+ import { asCompiledRowsSql, sql, asCompiledStatementSql } from './chunk-6DCB664D.js';
7
+ import { ConfigurationError, ValidationError } from './chunk-4MB3AQAQ.js';
8
8
 
9
9
  // src/backend/migrate-recorded-time.ts
10
10
  var LEGACY_RECORDED_MAX = "9999-12-31T23:59:59.999Z";
@@ -597,5 +597,5 @@ async function deleteLegacyRecordedAnchorMap(options) {
597
597
  }
598
598
 
599
599
  export { deleteLegacyRecordedAnchorMap, migrateLegacyRecordedTime, migrateRecordedAnchor };
600
- //# sourceMappingURL=chunk-JOYPNY33.js.map
601
- //# sourceMappingURL=chunk-JOYPNY33.js.map
600
+ //# sourceMappingURL=chunk-5EKPX6QU.js.map
601
+ //# sourceMappingURL=chunk-5EKPX6QU.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/backend/migrate-recorded-time.ts"],"names":["temporaryTables","finalTables"],"mappings":";;;;;;;;;AA0BA,IAAM,mBAAA,GAAsB,0BAAA;AAC5B,IAAM,gBAAA,GAAmB,yBAAA;AAEzB,IAAM,qBAAA,GAAwB;AAAA,EAC5B,YAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA,IAAA;AAAA,EACA,OAAA;AAAA,EACA,SAAA;AAAA,EACA,YAAA;AAAA,EACA,UAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,eAAA;AAAA,EACA,aAAA;AAAA,EACA,IAAA;AAAA,EACA,gBAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA;AAEA,IAAM,qBAAA,GAAwB;AAAA,EAC5B,YAAA;AAAA,EACA,UAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA;AAAA,EACA,SAAA;AAAA,EACA,OAAA;AAAA,EACA,OAAA;AAAA,EACA,YAAA;AAAA,EACA,UAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,eAAA;AAAA,EACA,aAAA;AAAA,EACA,IAAA;AAAA,EACA,gBAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA;AA0DA,SAAS,kBAAA,CACP,SACA,QAAA,EACuB;AACvB,EAAA,OAAO,gBAAgB,QAAA,IAAY,OAAA,CAAQ,UAAA,IAAc,EAAE,CAAA,CAAE,MAAA;AAC/D;AAEA,SAAS,oBAAoB,KAAA,EAAuB;AAClD,EAAA,IAAI,KAAA,CAAM,MAAA,IAAU,EAAA,EAAI,OAAO,KAAA;AAC/B,EAAA,OAAO,CAAA,EAAG,MAAM,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA,CAA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M;AACpC,IAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,OAAA;AAAA,MACxB,iBAAA,CAAkB,GAAA;AAAA;AAAA,aAAA,EAET,GAAA,CAAI,UAAA,CAAW,QAAQ,CAAC;AAAA,MAAA,CAChC;AAAA,KACH;AACA,IAAA,MAAM,YAAY,mBAAA,CAAoB,IAAA,CAAK,CAAC,CAAA,EAAG,SAAS,QAAQ,CAAA;AAChE,IAAA,IAAI,cAAc,CAAA,EAAG;AACnB,MAAA,MAAM,gBAAA;AAAA,QACJ,MAAA;AAAA,QACA,GAAA,CAAA,WAAA,EAAiB,GAAA,CAAI,UAAA,CAAW,QAAQ,CAAC,CAAA;AAAA,OAC3C;AAAA,IACF;AAAA,EACF,CAAC,CAAA;AACH","file":"chunk-JOYPNY33.js","sourcesContent":["/**\n * One-time offline migration from timestamp-only recorded relations to numeric\n * revisions. The durable remap table lets applications translate checkpoints\n * stored outside TypeGraph before deleting the migration metadata.\n */\nimport {\n asRecordedInstant,\n createRecordedInstant,\n RECORDED_MAX_REVISION,\n type RecordedInstant,\n} from \"../core/temporal\";\nimport { ConfigurationError, ValidationError } from \"../errors\";\nimport {\n createSqlSchema,\n type ResolvedSqlTableNames,\n type SqlTableNames,\n} from \"../query/compiler/schema\";\nimport { shortHash } from \"../query/dialect/vector-strategy\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql, asCompiledStatementSql } from \"../query/sql-intent\";\nimport { canonicalizeDatabaseTimestamp } from \"../utils/date\";\nimport { postgresContributions, sqliteContributions } from \"./drizzle/ddl\";\nimport { createPostgresTables } from \"./drizzle/schema/postgres\";\nimport { createSqliteTables } from \"./drizzle/schema/sqlite\";\nimport { type GraphBackend, type TransactionBackend } from \"./types\";\n\nconst LEGACY_RECORDED_MAX = \"9999-12-31T23:59:59.999Z\";\nconst MIGRATION_SUFFIX = \"legacy_recorded_anchors\";\n\nconst RECORDED_NODE_COLUMNS = [\n \"history_id\",\n \"graph_id\",\n \"kind\",\n \"id\",\n \"props\",\n \"version\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n \"recorded_from\",\n \"recorded_to\",\n \"op\",\n \"schema_version\",\n \"tx_id\",\n \"meta\",\n] as const;\n\nconst RECORDED_EDGE_COLUMNS = [\n \"history_id\",\n \"graph_id\",\n \"id\",\n \"kind\",\n \"from_kind\",\n \"from_id\",\n \"to_kind\",\n \"to_id\",\n \"props\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n \"recorded_from\",\n \"recorded_to\",\n \"op\",\n \"schema_version\",\n \"tx_id\",\n \"meta\",\n] as const;\n\ntype LegacyInstantRow = Readonly<{\n graph_id: unknown;\n recorded_at: unknown;\n}>;\n\ntype MappingRow = Readonly<{\n graphId: string;\n legacyRecordedAt: string;\n recordedAt: string;\n revision: number;\n}>;\n\ntype RemapRow = Readonly<{ recorded_at: unknown; revision: unknown }>;\ntype MappingCountRow = Readonly<{ anchors: unknown; graphs: unknown }>;\ntype MissingMappingRow = Readonly<{ missing: unknown }>;\ntype ColumnRow = Readonly<{ name: unknown }>;\n\nexport type MigrateLegacyRecordedTimeOptions = Readonly<{\n backend: GraphBackend;\n /** Override the backend's recorded table names. */\n tableNames?: Partial<SqlTableNames> | undefined;\n /** Override the durable legacy-anchor mapping table name. */\n mappingTableName?: string | undefined;\n}>;\n\nexport type MigrateLegacyRecordedTimeResult = Readonly<{\n /** `true` when timestamp columns were rewritten during this call. */\n migrated: boolean;\n /** Number of graphs represented in the legacy commit order. */\n graphs: number;\n /** Number of distinct legacy anchors available for remapping. */\n anchors: number;\n /** Physical table retaining the old-anchor → revision mapping. */\n mappingTableName: string;\n}>;\n\nexport type MigrateRecordedAnchorOptions = Readonly<{\n backend: Pick<GraphBackend, \"dialect\" | \"execute\" | \"tableNames\">;\n graphId: string;\n anchor: string;\n tableNames?: Partial<SqlTableNames> | undefined;\n mappingTableName?: string | undefined;\n}>;\n\nexport type DeleteLegacyRecordedAnchorMapOptions = Readonly<{\n backend: Pick<\n GraphBackend,\n \"dialect\" | \"execute\" | \"executeStatement\" | \"tableNames\" | \"transaction\"\n >;\n graphId: string;\n tableNames?: Partial<SqlTableNames> | undefined;\n mappingTableName?: string | undefined;\n /** Drop the mapping table when this deletion leaves it empty. */\n dropWhenEmpty?: boolean | undefined;\n}>;\n\nfunction resolvedTableNames(\n backend: Pick<GraphBackend, \"tableNames\">,\n override: Partial<SqlTableNames> | undefined,\n): ResolvedSqlTableNames {\n return createSqlSchema(override ?? backend.tableNames ?? {}).tables;\n}\n\nfunction shortenedIdentifier(value: string): string {\n if (value.length <= 63) return value;\n return `${value.slice(0, 50)}_${shortHash(value)}`;\n}\n\nfunction mappingTableName(\n tables: ResolvedSqlTableNames,\n override: string | undefined,\n): string {\n const candidate = override ?? `${tables.recordedClock}_${MIGRATION_SUFFIX}`;\n return createSqlSchema({\n recordedClock: shortenedIdentifier(candidate),\n }).tables.recordedClock;\n}\n\nfunction temporaryTableName(tableName: string, role: string): string {\n return shortenedIdentifier(`__tg_${role}_${shortHash(tableName)}`);\n}\n\nfunction requireStatements(\n target: Pick<TransactionBackend, \"dialect\" | \"executeStatement\">,\n): NonNullable<TransactionBackend[\"executeStatement\"]> {\n if (target.executeStatement === undefined) {\n throw new ConfigurationError(\n \"Recorded-time migration requires executeStatement support.\",\n { dialect: target.dialect },\n { suggestion: \"Use a built-in SQLite or PostgreSQL backend.\" },\n );\n }\n return target.executeStatement;\n}\n\nasync function executeStatement(\n target: Pick<TransactionBackend, \"dialect\" | \"executeStatement\">,\n statement: SqlFragment,\n): Promise<void> {\n await requireStatements(target)(asCompiledStatementSql(statement));\n}\n\nasync function executeDdl(\n target: Pick<TransactionBackend, \"dialect\" | \"executeStatement\">,\n ddl: string,\n): Promise<void> {\n await executeStatement(target, sql.raw(ddl));\n}\n\nfunction canonicalLegacyInstant(value: unknown): string {\n const canonical = canonicalizeDatabaseTimestamp(value);\n if (canonical === undefined) {\n throw new ConfigurationError(\n \"Legacy recorded-time relation contained an invalid timestamp.\",\n { value },\n );\n }\n return canonical;\n}\n\nfunction safeRevision(value: unknown): number {\n const revision =\n typeof value === \"bigint\" ? Number(value)\n : typeof value === \"string\" && /^\\d+$/.test(value) ? Number(value)\n : value;\n if (\n typeof revision !== \"number\" ||\n !Number.isSafeInteger(revision) ||\n revision < 1 ||\n revision >= RECORDED_MAX_REVISION\n ) {\n throw new ConfigurationError(\n \"Recorded anchor mapping contained an invalid revision.\",\n { value },\n );\n }\n return revision;\n}\n\nasync function columnNames(\n target: TransactionBackend,\n tableName: string,\n): Promise<ReadonlySet<string>> {\n const rows =\n target.dialect === \"sqlite\" ?\n await target.execute<ColumnRow>(\n asCompiledRowsSql(sql`PRAGMA table_info(${sql.identifier(tableName)})`),\n )\n : await target.execute<ColumnRow>(\n asCompiledRowsSql(sql`\n SELECT column_name AS name\n FROM information_schema.columns\n WHERE table_schema = current_schema()\n AND table_name = ${tableName}\n `),\n );\n return new Set(\n rows.flatMap((row) => (typeof row.name === \"string\" ? [row.name] : [])),\n );\n}\n\nasync function readLegacyInstants(\n target: TransactionBackend,\n tables: ResolvedSqlTableNames,\n): Promise<readonly MappingRow[]> {\n const rows = await target.execute<LegacyInstantRow>(\n asCompiledRowsSql(sql`\n SELECT graph_id, recorded_from AS recorded_at\n FROM ${sql.identifier(tables.recordedNodes)}\n UNION\n SELECT graph_id, recorded_to AS recorded_at\n FROM ${sql.identifier(tables.recordedNodes)}\n WHERE recorded_to <> ${LEGACY_RECORDED_MAX}\n UNION\n SELECT graph_id, recorded_from AS recorded_at\n FROM ${sql.identifier(tables.recordedEdges)}\n UNION\n SELECT graph_id, recorded_to AS recorded_at\n FROM ${sql.identifier(tables.recordedEdges)}\n WHERE recorded_to <> ${LEGACY_RECORDED_MAX}\n UNION\n SELECT graph_id, recorded_at\n FROM ${sql.identifier(tables.recordedClock)}\n `),\n );\n const instants = rows.map((row) => {\n if (typeof row.graph_id !== \"string\") {\n throw new ConfigurationError(\n \"Legacy recorded-time relation contained an invalid graph id.\",\n { graphId: row.graph_id },\n );\n }\n return {\n graphId: row.graph_id,\n recordedAt: canonicalLegacyInstant(row.recorded_at),\n };\n });\n instants.sort((left, right) => {\n if (left.graphId < right.graphId) return -1;\n if (left.graphId > right.graphId) return 1;\n if (left.recordedAt < right.recordedAt) return -1;\n if (left.recordedAt > right.recordedAt) return 1;\n return 0;\n });\n\n const mapping: MappingRow[] = [];\n let graphId: string | undefined;\n let revision = 0;\n let previousInstant: string | undefined;\n for (const instant of instants) {\n if (instant.graphId !== graphId) {\n graphId = instant.graphId;\n revision = 0;\n previousInstant = undefined;\n }\n if (instant.recordedAt === previousInstant) continue;\n revision += 1;\n mapping.push({\n graphId: instant.graphId,\n legacyRecordedAt: instant.recordedAt,\n recordedAt: instant.recordedAt,\n revision,\n });\n previousInstant = instant.recordedAt;\n }\n return mapping;\n}\n\nfunction migrationMapDdl(\n dialect: GraphBackend[\"dialect\"],\n table: string,\n): string {\n const revisionType = dialect === \"postgres\" ? \"BIGINT\" : \"INTEGER\";\n const recordedAtType = dialect === \"postgres\" ? \"TIMESTAMPTZ\" : \"TEXT\";\n return `CREATE TABLE IF NOT EXISTS \"${table}\" (\n graph_id TEXT NOT NULL,\n legacy_recorded_at TEXT NOT NULL,\n revision ${revisionType} NOT NULL,\n recorded_at ${recordedAtType} NOT NULL,\n PRIMARY KEY (graph_id, legacy_recorded_at)\n);`;\n}\n\nasync function writeMappingRows(\n target: TransactionBackend,\n tableName: string,\n rows: readonly MappingRow[],\n): Promise<void> {\n await executeStatement(target, sql`DELETE FROM ${sql.identifier(tableName)}`);\n const rowsPerStatement = Math.max(\n 1,\n Math.floor((target.capabilities.maxBindParameters ?? 900) / 4),\n );\n for (let start = 0; start < rows.length; start += rowsPerStatement) {\n const values = rows\n .slice(start, start + rowsPerStatement)\n .map(\n (row) =>\n sql`(${row.graphId}, ${row.legacyRecordedAt}, ${row.revision}, ${row.recordedAt})`,\n );\n await executeStatement(\n target,\n sql`\n INSERT INTO ${sql.identifier(tableName)}\n (graph_id, legacy_recorded_at, revision, recorded_at)\n VALUES ${sql.join(values, sql`, `)}\n `,\n );\n }\n}\n\nfunction tableDdl(\n dialect: GraphBackend[\"dialect\"],\n tables: ResolvedSqlTableNames,\n temporary: Readonly<{\n recordedClock: string;\n recordedEdges: string;\n recordedNodes: string;\n }>,\n): Readonly<{\n clock: readonly string[];\n edges: readonly string[];\n nodes: readonly string[];\n}> {\n if (dialect === \"sqlite\") {\n const temporaryTables = createSqliteTables(temporary);\n const finalTables = createSqliteTables(tables);\n const temporaryContributions = sqliteContributions(temporaryTables);\n const finalContributions = sqliteContributions(finalTables);\n return ddlForRecordedTables(temporaryContributions, finalContributions);\n }\n const temporaryTables = createPostgresTables(temporary);\n const finalTables = createPostgresTables(tables);\n return ddlForRecordedTables(\n postgresContributions(temporaryTables),\n postgresContributions(finalTables),\n );\n}\n\nfunction ddlForRecordedTables(\n temporary: readonly Readonly<{\n createDdl: readonly string[];\n logicalName: string;\n }>[],\n final: readonly Readonly<{\n createDdl: readonly string[];\n logicalName: string;\n }>[],\n): Readonly<{\n clock: readonly string[];\n edges: readonly string[];\n nodes: readonly string[];\n}> {\n function statements(\n logicalName: \"recordedClock\" | \"recordedEdges\" | \"recordedNodes\",\n ): readonly string[] {\n const temporaryDdl = temporary.find(\n (entry) => entry.logicalName === logicalName,\n )?.createDdl;\n const finalDdl = final.find(\n (entry) => entry.logicalName === logicalName,\n )?.createDdl;\n if (temporaryDdl === undefined || finalDdl === undefined) {\n throw new ConfigurationError(\n `Could not generate migration DDL for ${logicalName}.`,\n );\n }\n const createTable = temporaryDdl[0];\n if (createTable === undefined) {\n throw new ConfigurationError(\n `Could not generate migration table DDL for ${logicalName}.`,\n );\n }\n return [createTable, ...finalDdl.slice(1)];\n }\n return {\n clock: statements(\"recordedClock\"),\n edges: statements(\"recordedEdges\"),\n nodes: statements(\"recordedNodes\"),\n };\n}\n\nfunction migratedColumn(column: string, legacyAlias: string): SqlFragment {\n if (column === \"recorded_from\") return sql`from_map.revision`;\n if (column === \"recorded_to\") {\n return sql`\n CASE\n WHEN ${sql.raw(legacyAlias)}.recorded_to = ${LEGACY_RECORDED_MAX}\n THEN ${RECORDED_MAX_REVISION}\n ELSE to_map.revision\n END\n `;\n }\n return sql`${sql.raw(legacyAlias)}.${sql.identifier(column)}`;\n}\n\nfunction mappingMatch(\n dialect: GraphBackend[\"dialect\"],\n mappingAlias: \"anchor_map\" | \"from_map\" | \"to_map\",\n legacyColumn: \"recorded_at\" | \"recorded_from\" | \"recorded_to\",\n): SqlFragment {\n const mapping = sql.raw(mappingAlias);\n const legacy = sql.raw(`legacy.${legacyColumn}`);\n return dialect === \"postgres\" ?\n sql`${mapping}.recorded_at = ${legacy}`\n : sql`${mapping}.legacy_recorded_at = ${legacy}`;\n}\n\nfunction missingMappingCount(value: unknown, legacyTable: string): number {\n const count = Number(value);\n if (!Number.isSafeInteger(count) || count < 0) {\n throw new ConfigurationError(\n \"Recorded-time migration returned an invalid integrity-check count.\",\n { legacyTable, value },\n );\n }\n return count;\n}\n\nasync function assertRecordedRelationMappings(\n target: TransactionBackend,\n options: Readonly<{ legacyTable: string; mappingTable: string }>,\n): Promise<void> {\n const fromMatch = mappingMatch(target.dialect, \"from_map\", \"recorded_from\");\n const toMatch = mappingMatch(target.dialect, \"to_map\", \"recorded_to\");\n const rows = await target.execute<MissingMappingRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS missing\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS from_map\n ON from_map.graph_id = legacy.graph_id AND ${fromMatch}\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS to_map\n ON to_map.graph_id = legacy.graph_id AND ${toMatch}\n WHERE from_map.revision IS NULL\n OR (\n legacy.recorded_to <> ${LEGACY_RECORDED_MAX}\n AND to_map.revision IS NULL\n )\n `),\n );\n const missing = missingMappingCount(rows[0]?.missing, options.legacyTable);\n if (missing === 0) return;\n throw new ConfigurationError(\n \"Legacy recorded-time boundaries could not be mapped exactly.\",\n { legacyTable: options.legacyTable, missingRows: missing },\n {\n suggestion:\n \"Ensure every legacy boundary is a valid millisecond-precision timestamp produced by the preview recorded clock before retrying the offline migration.\",\n },\n );\n}\n\nasync function assertRecordedClockMappings(\n target: TransactionBackend,\n options: Readonly<{ legacyTable: string; mappingTable: string }>,\n): Promise<void> {\n const match = mappingMatch(target.dialect, \"anchor_map\", \"recorded_at\");\n const rows = await target.execute<MissingMappingRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS missing\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS anchor_map\n ON anchor_map.graph_id = legacy.graph_id AND ${match}\n WHERE anchor_map.revision IS NULL\n `),\n );\n const missing = missingMappingCount(rows[0]?.missing, options.legacyTable);\n if (missing === 0) return;\n throw new ConfigurationError(\n \"Legacy recorded clock values could not be mapped exactly.\",\n { legacyTable: options.legacyTable, missingRows: missing },\n {\n suggestion:\n \"Ensure every legacy clock value is a valid millisecond-precision timestamp produced by the preview recorded clock before retrying the offline migration.\",\n },\n );\n}\n\nasync function copyRecordedRelation(\n target: TransactionBackend,\n options: Readonly<{\n columns: readonly string[];\n legacyTable: string;\n mappingTable: string;\n temporaryTable: string;\n }>,\n): Promise<void> {\n const columnList = options.columns.map((column) => sql.identifier(column));\n const values = options.columns.map((column) =>\n migratedColumn(column, \"legacy\"),\n );\n await assertRecordedRelationMappings(target, options);\n const fromMatch = mappingMatch(target.dialect, \"from_map\", \"recorded_from\");\n const toMatch = mappingMatch(target.dialect, \"to_map\", \"recorded_to\");\n await executeStatement(\n target,\n sql`\n INSERT INTO ${sql.identifier(options.temporaryTable)}\n (${sql.join(columnList, sql`, `)})\n SELECT ${sql.join(values, sql`, `)}\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n -- LEFT JOIN is deliberate: a missing mapping reaches the NOT NULL\n -- revision columns and fails loud instead of silently dropping history.\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS from_map\n ON from_map.graph_id = legacy.graph_id AND ${fromMatch}\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS to_map\n ON to_map.graph_id = legacy.graph_id AND ${toMatch}\n `,\n );\n}\n\nasync function copyRecordedClock(\n target: TransactionBackend,\n options: Readonly<{\n legacyTable: string;\n mappingTable: string;\n temporaryTable: string;\n }>,\n): Promise<void> {\n await assertRecordedClockMappings(target, options);\n const match = mappingMatch(target.dialect, \"anchor_map\", \"recorded_at\");\n await executeStatement(\n target,\n sql`\n INSERT INTO ${sql.identifier(options.temporaryTable)}\n (graph_id, revision, recorded_at)\n SELECT legacy.graph_id, anchor_map.revision, legacy.recorded_at\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n -- Preserve fail-loud behavior if the preflight invariant changes later.\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS anchor_map\n ON anchor_map.graph_id = legacy.graph_id AND ${match}\n `,\n );\n}\n\nasync function replaceLegacyTables(\n target: TransactionBackend,\n tables: ResolvedSqlTableNames,\n mappingTable: string,\n): Promise<void> {\n const temporary = {\n recordedNodes: temporaryTableName(tables.recordedNodes, \"rn\"),\n recordedEdges: temporaryTableName(tables.recordedEdges, \"re\"),\n recordedClock: temporaryTableName(tables.recordedClock, \"rc\"),\n };\n const ddl = tableDdl(target.dialect, tables, temporary);\n for (const table of Object.values(temporary)) {\n await executeStatement(\n target,\n sql`DROP TABLE IF EXISTS ${sql.identifier(table)}`,\n );\n }\n await executeDdl(target, requireCreateTable(ddl.nodes));\n await executeDdl(target, requireCreateTable(ddl.edges));\n await executeDdl(target, requireCreateTable(ddl.clock));\n await copyRecordedRelation(target, {\n columns: RECORDED_NODE_COLUMNS,\n legacyTable: tables.recordedNodes,\n mappingTable,\n temporaryTable: temporary.recordedNodes,\n });\n await copyRecordedRelation(target, {\n columns: RECORDED_EDGE_COLUMNS,\n legacyTable: tables.recordedEdges,\n mappingTable,\n temporaryTable: temporary.recordedEdges,\n });\n await copyRecordedClock(target, {\n legacyTable: tables.recordedClock,\n mappingTable,\n temporaryTable: temporary.recordedClock,\n });\n\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(tables.recordedNodes)}`,\n );\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(tables.recordedEdges)}`,\n );\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(tables.recordedClock)}`,\n );\n await renameTable(target, temporary.recordedNodes, tables.recordedNodes);\n await renameTable(target, temporary.recordedEdges, tables.recordedEdges);\n await renameTable(target, temporary.recordedClock, tables.recordedClock);\n await renamePrimaryKeyConstraint(\n target,\n temporary.recordedNodes,\n tables.recordedNodes,\n );\n await renamePrimaryKeyConstraint(\n target,\n temporary.recordedEdges,\n tables.recordedEdges,\n );\n await renamePrimaryKeyConstraint(\n target,\n temporary.recordedClock,\n tables.recordedClock,\n );\n for (const statement of [\n ...ddl.nodes.slice(1),\n ...ddl.edges.slice(1),\n ...ddl.clock.slice(1),\n ]) {\n await executeDdl(target, statement);\n }\n}\n\nasync function renamePrimaryKeyConstraint(\n target: TransactionBackend,\n temporaryTable: string,\n finalTable: string,\n): Promise<void> {\n if (target.dialect !== \"postgres\") return;\n await executeStatement(\n target,\n sql`\n ALTER TABLE ${sql.identifier(finalTable)}\n RENAME CONSTRAINT ${sql.identifier(`${temporaryTable}_pkey`)}\n TO ${sql.identifier(shortenedIdentifier(`${finalTable}_pkey`))}\n `,\n );\n}\n\nfunction requireCreateTable(statements: readonly string[]): string {\n const statement = statements[0];\n if (statement === undefined) {\n throw new ConfigurationError(\"Recorded migration table DDL was empty.\");\n }\n return statement;\n}\n\nasync function renameTable(\n target: TransactionBackend,\n from: string,\n to: string,\n): Promise<void> {\n try {\n await executeStatement(\n target,\n sql`ALTER TABLE ${sql.identifier(from)} RENAME TO ${sql.identifier(to)}`,\n );\n } catch (error) {\n throw new ConfigurationError(\n \"Could not rename a migrated recorded-time table.\",\n { from, to },\n { cause: error },\n );\n }\n}\n\n/**\n * Rewrites timestamp-only recorded relations to numeric revisions.\n *\n * Run offline before opening a Store with the new schema. The durable mapping\n * table is retained so external checkpoint stores can call\n * {@link migrateRecordedAnchor}; delete each graph's rows after its downstream\n * checkpoints have been rewritten.\n */\nexport async function migrateLegacyRecordedTime(\n options: MigrateLegacyRecordedTimeOptions,\n): Promise<MigrateLegacyRecordedTimeResult> {\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const mapTable = mappingTableName(tables, options.mappingTableName);\n return options.backend.transaction(async (target) => {\n const clockColumns = await columnNames(target, tables.recordedClock);\n if (clockColumns.size === 0) {\n return {\n migrated: false,\n graphs: 0,\n anchors: 0,\n mappingTableName: mapTable,\n };\n }\n if (clockColumns.has(\"revision\")) {\n const mapColumns = await columnNames(target, mapTable);\n if (mapColumns.size === 0) {\n return {\n migrated: false,\n graphs: 0,\n anchors: 0,\n mappingTableName: mapTable,\n };\n }\n const rows = await target.execute<MappingCountRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS anchors, COUNT(DISTINCT graph_id) AS graphs\n FROM ${sql.identifier(mapTable)}\n `),\n );\n const anchors = Number(rows[0]?.anchors ?? 0);\n const graphs = Number(rows[0]?.graphs ?? 0);\n return {\n migrated: false,\n graphs: Number.isSafeInteger(graphs) ? graphs : 0,\n anchors: Number.isSafeInteger(anchors) ? anchors : 0,\n mappingTableName: mapTable,\n };\n }\n const nodeColumns = await columnNames(target, tables.recordedNodes);\n const edgeColumns = await columnNames(target, tables.recordedEdges);\n if (\n !nodeColumns.has(\"recorded_from\") ||\n !edgeColumns.has(\"recorded_from\")\n ) {\n throw new ConfigurationError(\n \"Legacy recorded-time schema is incomplete.\",\n { tables },\n );\n }\n\n await executeDdl(target, migrationMapDdl(target.dialect, mapTable));\n const mapping = await readLegacyInstants(target, tables);\n await writeMappingRows(target, mapTable, mapping);\n await replaceLegacyTables(target, tables, mapTable);\n return {\n migrated: true,\n graphs: new Set(mapping.map((row) => row.graphId)).size,\n anchors: mapping.length,\n mappingTableName: mapTable,\n };\n });\n}\n\n/** Remaps one timestamp-only checkpoint after {@link migrateLegacyRecordedTime}. */\nexport async function migrateRecordedAnchor(\n options: MigrateRecordedAnchorOptions,\n): Promise<RecordedInstant> {\n try {\n return asRecordedInstant(options.anchor);\n } catch (error) {\n if (!(error instanceof ValidationError)) throw error;\n }\n const legacyRecordedAt = canonicalLegacyInstant(options.anchor);\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const mapTable = mappingTableName(tables, options.mappingTableName);\n const rows = await options.backend.execute<RemapRow>(\n asCompiledRowsSql(sql`\n SELECT revision, recorded_at\n FROM ${sql.identifier(mapTable)}\n WHERE graph_id = ${options.graphId}\n AND legacy_recorded_at = ${legacyRecordedAt}\n `),\n );\n const row = rows[0];\n if (row === undefined) {\n throw new ConfigurationError(\n \"No migrated recorded anchor matches this graph and legacy timestamp.\",\n { anchor: options.anchor, graphId: options.graphId },\n {\n suggestion:\n \"Run migrateLegacyRecordedTime() before deleting its mapping rows, and pass the graph that produced the checkpoint.\",\n },\n );\n }\n return createRecordedInstant(\n safeRevision(row.revision),\n canonicalLegacyInstant(row.recorded_at),\n );\n}\n\n/**\n * Deletes one graph's legacy remap rows after downstream checkpoints migrate.\n * Set `dropWhenEmpty` to remove the migration table after the final graph.\n */\nexport async function deleteLegacyRecordedAnchorMap(\n options: DeleteLegacyRecordedAnchorMapOptions,\n): Promise<void> {\n if (options.backend.executeStatement === undefined) {\n throw new ConfigurationError(\n \"Deleting a recorded anchor migration map requires executeStatement support.\",\n { dialect: options.backend.dialect },\n );\n }\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const mapTable = mappingTableName(tables, options.mappingTableName);\n await options.backend.transaction(async (target) => {\n await executeStatement(\n target,\n sql`\n DELETE FROM ${sql.identifier(mapTable)}\n WHERE graph_id = ${options.graphId}\n `,\n );\n if (options.dropWhenEmpty !== true) return;\n const rows = await target.execute<MappingCountRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS anchors, COUNT(DISTINCT graph_id) AS graphs\n FROM ${sql.identifier(mapTable)}\n `),\n );\n const remaining = missingMappingCount(rows[0]?.anchors, mapTable);\n if (remaining === 0) {\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(mapTable)}`,\n );\n }\n });\n}\n"]}
1
+ {"version":3,"sources":["../src/backend/migrate-recorded-time.ts"],"names":["temporaryTables","finalTables"],"mappings":";;;;;;;;;AA0BA,IAAM,mBAAA,GAAsB,0BAAA;AAC5B,IAAM,gBAAA,GAAmB,yBAAA;AAEzB,IAAM,qBAAA,GAAwB;AAAA,EAC5B,YAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA,IAAA;AAAA,EACA,OAAA;AAAA,EACA,SAAA;AAAA,EACA,YAAA;AAAA,EACA,UAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,eAAA;AAAA,EACA,aAAA;AAAA,EACA,IAAA;AAAA,EACA,gBAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA;AAEA,IAAM,qBAAA,GAAwB;AAAA,EAC5B,YAAA;AAAA,EACA,UAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA;AAAA,EACA,SAAA;AAAA,EACA,OAAA;AAAA,EACA,OAAA;AAAA,EACA,YAAA;AAAA,EACA,UAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,eAAA;AAAA,EACA,aAAA;AAAA,EACA,IAAA;AAAA,EACA,gBAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA;AA0DA,SAAS,kBAAA,CACP,SACA,QAAA,EACuB;AACvB,EAAA,OAAO,gBAAgB,QAAA,IAAY,OAAA,CAAQ,UAAA,IAAc,EAAE,CAAA,CAAE,MAAA;AAC/D;AAEA,SAAS,oBAAoB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;AAAA,oBAAA,EACgB,GAAA,CAAI,UAAA,CAAW,QAAQ,CAAC;AAAA,yBAAA,EACnB,QAAQ,OAAO;AAAA,MAAA;AAAA,KAEtC;AACA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,IAAA,EAAM;AACpC,IAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,OAAA;AAAA,MACxB,iBAAA,CAAkB,GAAA;AAAA;AAAA,aAAA,EAET,GAAA,CAAI,UAAA,CAAW,QAAQ,CAAC;AAAA,MAAA,CAChC;AAAA,KACH;AACA,IAAA,MAAM,YAAY,mBAAA,CAAoB,IAAA,CAAK,CAAC,CAAA,EAAG,SAAS,QAAQ,CAAA;AAChE,IAAA,IAAI,cAAc,CAAA,EAAG;AACnB,MAAA,MAAM,gBAAA;AAAA,QACJ,MAAA;AAAA,QACA,GAAA,CAAA,WAAA,EAAiB,GAAA,CAAI,UAAA,CAAW,QAAQ,CAAC,CAAA;AAAA,OAC3C;AAAA,IACF;AAAA,EACF,CAAC,CAAA;AACH","file":"chunk-5EKPX6QU.js","sourcesContent":["/**\n * One-time offline migration from timestamp-only recorded relations to numeric\n * revisions. The durable remap table lets applications translate checkpoints\n * stored outside TypeGraph before deleting the migration metadata.\n */\nimport {\n asRecordedInstant,\n createRecordedInstant,\n RECORDED_MAX_REVISION,\n type RecordedInstant,\n} from \"../core/temporal\";\nimport { ConfigurationError, ValidationError } from \"../errors\";\nimport {\n createSqlSchema,\n type ResolvedSqlTableNames,\n type SqlTableNames,\n} from \"../query/compiler/schema\";\nimport { shortHash } from \"../query/dialect/vector-strategy\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql, asCompiledStatementSql } from \"../query/sql-intent\";\nimport { canonicalizeDatabaseTimestamp } from \"../utils/date\";\nimport { postgresContributions, sqliteContributions } from \"./drizzle/ddl\";\nimport { createPostgresTables } from \"./drizzle/schema/postgres\";\nimport { createSqliteTables } from \"./drizzle/schema/sqlite\";\nimport { type GraphBackend, type TransactionBackend } from \"./types\";\n\nconst LEGACY_RECORDED_MAX = \"9999-12-31T23:59:59.999Z\";\nconst MIGRATION_SUFFIX = \"legacy_recorded_anchors\";\n\nconst RECORDED_NODE_COLUMNS = [\n \"history_id\",\n \"graph_id\",\n \"kind\",\n \"id\",\n \"props\",\n \"version\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n \"recorded_from\",\n \"recorded_to\",\n \"op\",\n \"schema_version\",\n \"tx_id\",\n \"meta\",\n] as const;\n\nconst RECORDED_EDGE_COLUMNS = [\n \"history_id\",\n \"graph_id\",\n \"id\",\n \"kind\",\n \"from_kind\",\n \"from_id\",\n \"to_kind\",\n \"to_id\",\n \"props\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n \"recorded_from\",\n \"recorded_to\",\n \"op\",\n \"schema_version\",\n \"tx_id\",\n \"meta\",\n] as const;\n\ntype LegacyInstantRow = Readonly<{\n graph_id: unknown;\n recorded_at: unknown;\n}>;\n\ntype MappingRow = Readonly<{\n graphId: string;\n legacyRecordedAt: string;\n recordedAt: string;\n revision: number;\n}>;\n\ntype RemapRow = Readonly<{ recorded_at: unknown; revision: unknown }>;\ntype MappingCountRow = Readonly<{ anchors: unknown; graphs: unknown }>;\ntype MissingMappingRow = Readonly<{ missing: unknown }>;\ntype ColumnRow = Readonly<{ name: unknown }>;\n\nexport type MigrateLegacyRecordedTimeOptions = Readonly<{\n backend: GraphBackend;\n /** Override the backend's recorded table names. */\n tableNames?: Partial<SqlTableNames> | undefined;\n /** Override the durable legacy-anchor mapping table name. */\n mappingTableName?: string | undefined;\n}>;\n\nexport type MigrateLegacyRecordedTimeResult = Readonly<{\n /** `true` when timestamp columns were rewritten during this call. */\n migrated: boolean;\n /** Number of graphs represented in the legacy commit order. */\n graphs: number;\n /** Number of distinct legacy anchors available for remapping. */\n anchors: number;\n /** Physical table retaining the old-anchor → revision mapping. */\n mappingTableName: string;\n}>;\n\nexport type MigrateRecordedAnchorOptions = Readonly<{\n backend: Pick<GraphBackend, \"dialect\" | \"execute\" | \"tableNames\">;\n graphId: string;\n anchor: string;\n tableNames?: Partial<SqlTableNames> | undefined;\n mappingTableName?: string | undefined;\n}>;\n\nexport type DeleteLegacyRecordedAnchorMapOptions = Readonly<{\n backend: Pick<\n GraphBackend,\n \"dialect\" | \"execute\" | \"executeStatement\" | \"tableNames\" | \"transaction\"\n >;\n graphId: string;\n tableNames?: Partial<SqlTableNames> | undefined;\n mappingTableName?: string | undefined;\n /** Drop the mapping table when this deletion leaves it empty. */\n dropWhenEmpty?: boolean | undefined;\n}>;\n\nfunction resolvedTableNames(\n backend: Pick<GraphBackend, \"tableNames\">,\n override: Partial<SqlTableNames> | undefined,\n): ResolvedSqlTableNames {\n return createSqlSchema(override ?? backend.tableNames ?? {}).tables;\n}\n\nfunction shortenedIdentifier(value: string): string {\n if (value.length <= 63) return value;\n return `${value.slice(0, 50)}_${shortHash(value)}`;\n}\n\nfunction mappingTableName(\n tables: ResolvedSqlTableNames,\n override: string | undefined,\n): string {\n const candidate = override ?? `${tables.recordedClock}_${MIGRATION_SUFFIX}`;\n return createSqlSchema({\n recordedClock: shortenedIdentifier(candidate),\n }).tables.recordedClock;\n}\n\nfunction temporaryTableName(tableName: string, role: string): string {\n return shortenedIdentifier(`__tg_${role}_${shortHash(tableName)}`);\n}\n\nfunction requireStatements(\n target: Pick<TransactionBackend, \"dialect\" | \"executeStatement\">,\n): NonNullable<TransactionBackend[\"executeStatement\"]> {\n if (target.executeStatement === undefined) {\n throw new ConfigurationError(\n \"Recorded-time migration requires executeStatement support.\",\n { dialect: target.dialect },\n { suggestion: \"Use a built-in SQLite or PostgreSQL backend.\" },\n );\n }\n return target.executeStatement;\n}\n\nasync function executeStatement(\n target: Pick<TransactionBackend, \"dialect\" | \"executeStatement\">,\n statement: SqlFragment,\n): Promise<void> {\n await requireStatements(target)(asCompiledStatementSql(statement));\n}\n\nasync function executeDdl(\n target: Pick<TransactionBackend, \"dialect\" | \"executeStatement\">,\n ddl: string,\n): Promise<void> {\n await executeStatement(target, sql.raw(ddl));\n}\n\nfunction canonicalLegacyInstant(value: unknown): string {\n const canonical = canonicalizeDatabaseTimestamp(value);\n if (canonical === undefined) {\n throw new ConfigurationError(\n \"Legacy recorded-time relation contained an invalid timestamp.\",\n { value },\n );\n }\n return canonical;\n}\n\nfunction safeRevision(value: unknown): number {\n const revision =\n typeof value === \"bigint\" ? Number(value)\n : typeof value === \"string\" && /^\\d+$/.test(value) ? Number(value)\n : value;\n if (\n typeof revision !== \"number\" ||\n !Number.isSafeInteger(revision) ||\n revision < 1 ||\n revision >= RECORDED_MAX_REVISION\n ) {\n throw new ConfigurationError(\n \"Recorded anchor mapping contained an invalid revision.\",\n { value },\n );\n }\n return revision;\n}\n\nasync function columnNames(\n target: TransactionBackend,\n tableName: string,\n): Promise<ReadonlySet<string>> {\n const rows =\n target.dialect === \"sqlite\" ?\n await target.execute<ColumnRow>(\n asCompiledRowsSql(sql`PRAGMA table_info(${sql.identifier(tableName)})`),\n )\n : await target.execute<ColumnRow>(\n asCompiledRowsSql(sql`\n SELECT column_name AS name\n FROM information_schema.columns\n WHERE table_schema = current_schema()\n AND table_name = ${tableName}\n `),\n );\n return new Set(\n rows.flatMap((row) => (typeof row.name === \"string\" ? [row.name] : [])),\n );\n}\n\nasync function readLegacyInstants(\n target: TransactionBackend,\n tables: ResolvedSqlTableNames,\n): Promise<readonly MappingRow[]> {\n const rows = await target.execute<LegacyInstantRow>(\n asCompiledRowsSql(sql`\n SELECT graph_id, recorded_from AS recorded_at\n FROM ${sql.identifier(tables.recordedNodes)}\n UNION\n SELECT graph_id, recorded_to AS recorded_at\n FROM ${sql.identifier(tables.recordedNodes)}\n WHERE recorded_to <> ${LEGACY_RECORDED_MAX}\n UNION\n SELECT graph_id, recorded_from AS recorded_at\n FROM ${sql.identifier(tables.recordedEdges)}\n UNION\n SELECT graph_id, recorded_to AS recorded_at\n FROM ${sql.identifier(tables.recordedEdges)}\n WHERE recorded_to <> ${LEGACY_RECORDED_MAX}\n UNION\n SELECT graph_id, recorded_at\n FROM ${sql.identifier(tables.recordedClock)}\n `),\n );\n const instants = rows.map((row) => {\n if (typeof row.graph_id !== \"string\") {\n throw new ConfigurationError(\n \"Legacy recorded-time relation contained an invalid graph id.\",\n { graphId: row.graph_id },\n );\n }\n return {\n graphId: row.graph_id,\n recordedAt: canonicalLegacyInstant(row.recorded_at),\n };\n });\n instants.sort((left, right) => {\n if (left.graphId < right.graphId) return -1;\n if (left.graphId > right.graphId) return 1;\n if (left.recordedAt < right.recordedAt) return -1;\n if (left.recordedAt > right.recordedAt) return 1;\n return 0;\n });\n\n const mapping: MappingRow[] = [];\n let graphId: string | undefined;\n let revision = 0;\n let previousInstant: string | undefined;\n for (const instant of instants) {\n if (instant.graphId !== graphId) {\n graphId = instant.graphId;\n revision = 0;\n previousInstant = undefined;\n }\n if (instant.recordedAt === previousInstant) continue;\n revision += 1;\n mapping.push({\n graphId: instant.graphId,\n legacyRecordedAt: instant.recordedAt,\n recordedAt: instant.recordedAt,\n revision,\n });\n previousInstant = instant.recordedAt;\n }\n return mapping;\n}\n\nfunction migrationMapDdl(\n dialect: GraphBackend[\"dialect\"],\n table: string,\n): string {\n const revisionType = dialect === \"postgres\" ? \"BIGINT\" : \"INTEGER\";\n const recordedAtType = dialect === \"postgres\" ? \"TIMESTAMPTZ\" : \"TEXT\";\n return `CREATE TABLE IF NOT EXISTS \"${table}\" (\n graph_id TEXT NOT NULL,\n legacy_recorded_at TEXT NOT NULL,\n revision ${revisionType} NOT NULL,\n recorded_at ${recordedAtType} NOT NULL,\n PRIMARY KEY (graph_id, legacy_recorded_at)\n);`;\n}\n\nasync function writeMappingRows(\n target: TransactionBackend,\n tableName: string,\n rows: readonly MappingRow[],\n): Promise<void> {\n await executeStatement(target, sql`DELETE FROM ${sql.identifier(tableName)}`);\n const rowsPerStatement = Math.max(\n 1,\n Math.floor((target.capabilities.maxBindParameters ?? 900) / 4),\n );\n for (let start = 0; start < rows.length; start += rowsPerStatement) {\n const values = rows\n .slice(start, start + rowsPerStatement)\n .map(\n (row) =>\n sql`(${row.graphId}, ${row.legacyRecordedAt}, ${row.revision}, ${row.recordedAt})`,\n );\n await executeStatement(\n target,\n sql`\n INSERT INTO ${sql.identifier(tableName)}\n (graph_id, legacy_recorded_at, revision, recorded_at)\n VALUES ${sql.join(values, sql`, `)}\n `,\n );\n }\n}\n\nfunction tableDdl(\n dialect: GraphBackend[\"dialect\"],\n tables: ResolvedSqlTableNames,\n temporary: Readonly<{\n recordedClock: string;\n recordedEdges: string;\n recordedNodes: string;\n }>,\n): Readonly<{\n clock: readonly string[];\n edges: readonly string[];\n nodes: readonly string[];\n}> {\n if (dialect === \"sqlite\") {\n const temporaryTables = createSqliteTables(temporary);\n const finalTables = createSqliteTables(tables);\n const temporaryContributions = sqliteContributions(temporaryTables);\n const finalContributions = sqliteContributions(finalTables);\n return ddlForRecordedTables(temporaryContributions, finalContributions);\n }\n const temporaryTables = createPostgresTables(temporary);\n const finalTables = createPostgresTables(tables);\n return ddlForRecordedTables(\n postgresContributions(temporaryTables),\n postgresContributions(finalTables),\n );\n}\n\nfunction ddlForRecordedTables(\n temporary: readonly Readonly<{\n createDdl: readonly string[];\n logicalName: string;\n }>[],\n final: readonly Readonly<{\n createDdl: readonly string[];\n logicalName: string;\n }>[],\n): Readonly<{\n clock: readonly string[];\n edges: readonly string[];\n nodes: readonly string[];\n}> {\n function statements(\n logicalName: \"recordedClock\" | \"recordedEdges\" | \"recordedNodes\",\n ): readonly string[] {\n const temporaryDdl = temporary.find(\n (entry) => entry.logicalName === logicalName,\n )?.createDdl;\n const finalDdl = final.find(\n (entry) => entry.logicalName === logicalName,\n )?.createDdl;\n if (temporaryDdl === undefined || finalDdl === undefined) {\n throw new ConfigurationError(\n `Could not generate migration DDL for ${logicalName}.`,\n );\n }\n const createTable = temporaryDdl[0];\n if (createTable === undefined) {\n throw new ConfigurationError(\n `Could not generate migration table DDL for ${logicalName}.`,\n );\n }\n return [createTable, ...finalDdl.slice(1)];\n }\n return {\n clock: statements(\"recordedClock\"),\n edges: statements(\"recordedEdges\"),\n nodes: statements(\"recordedNodes\"),\n };\n}\n\nfunction migratedColumn(column: string, legacyAlias: string): SqlFragment {\n if (column === \"recorded_from\") return sql`from_map.revision`;\n if (column === \"recorded_to\") {\n return sql`\n CASE\n WHEN ${sql.raw(legacyAlias)}.recorded_to = ${LEGACY_RECORDED_MAX}\n THEN ${RECORDED_MAX_REVISION}\n ELSE to_map.revision\n END\n `;\n }\n return sql`${sql.raw(legacyAlias)}.${sql.identifier(column)}`;\n}\n\nfunction mappingMatch(\n dialect: GraphBackend[\"dialect\"],\n mappingAlias: \"anchor_map\" | \"from_map\" | \"to_map\",\n legacyColumn: \"recorded_at\" | \"recorded_from\" | \"recorded_to\",\n): SqlFragment {\n const mapping = sql.raw(mappingAlias);\n const legacy = sql.raw(`legacy.${legacyColumn}`);\n return dialect === \"postgres\" ?\n sql`${mapping}.recorded_at = ${legacy}`\n : sql`${mapping}.legacy_recorded_at = ${legacy}`;\n}\n\nfunction missingMappingCount(value: unknown, legacyTable: string): number {\n const count = Number(value);\n if (!Number.isSafeInteger(count) || count < 0) {\n throw new ConfigurationError(\n \"Recorded-time migration returned an invalid integrity-check count.\",\n { legacyTable, value },\n );\n }\n return count;\n}\n\nasync function assertRecordedRelationMappings(\n target: TransactionBackend,\n options: Readonly<{ legacyTable: string; mappingTable: string }>,\n): Promise<void> {\n const fromMatch = mappingMatch(target.dialect, \"from_map\", \"recorded_from\");\n const toMatch = mappingMatch(target.dialect, \"to_map\", \"recorded_to\");\n const rows = await target.execute<MissingMappingRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS missing\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS from_map\n ON from_map.graph_id = legacy.graph_id AND ${fromMatch}\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS to_map\n ON to_map.graph_id = legacy.graph_id AND ${toMatch}\n WHERE from_map.revision IS NULL\n OR (\n legacy.recorded_to <> ${LEGACY_RECORDED_MAX}\n AND to_map.revision IS NULL\n )\n `),\n );\n const missing = missingMappingCount(rows[0]?.missing, options.legacyTable);\n if (missing === 0) return;\n throw new ConfigurationError(\n \"Legacy recorded-time boundaries could not be mapped exactly.\",\n { legacyTable: options.legacyTable, missingRows: missing },\n {\n suggestion:\n \"Ensure every legacy boundary is a valid millisecond-precision timestamp produced by the preview recorded clock before retrying the offline migration.\",\n },\n );\n}\n\nasync function assertRecordedClockMappings(\n target: TransactionBackend,\n options: Readonly<{ legacyTable: string; mappingTable: string }>,\n): Promise<void> {\n const match = mappingMatch(target.dialect, \"anchor_map\", \"recorded_at\");\n const rows = await target.execute<MissingMappingRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS missing\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS anchor_map\n ON anchor_map.graph_id = legacy.graph_id AND ${match}\n WHERE anchor_map.revision IS NULL\n `),\n );\n const missing = missingMappingCount(rows[0]?.missing, options.legacyTable);\n if (missing === 0) return;\n throw new ConfigurationError(\n \"Legacy recorded clock values could not be mapped exactly.\",\n { legacyTable: options.legacyTable, missingRows: missing },\n {\n suggestion:\n \"Ensure every legacy clock value is a valid millisecond-precision timestamp produced by the preview recorded clock before retrying the offline migration.\",\n },\n );\n}\n\nasync function copyRecordedRelation(\n target: TransactionBackend,\n options: Readonly<{\n columns: readonly string[];\n legacyTable: string;\n mappingTable: string;\n temporaryTable: string;\n }>,\n): Promise<void> {\n const columnList = options.columns.map((column) => sql.identifier(column));\n const values = options.columns.map((column) =>\n migratedColumn(column, \"legacy\"),\n );\n await assertRecordedRelationMappings(target, options);\n const fromMatch = mappingMatch(target.dialect, \"from_map\", \"recorded_from\");\n const toMatch = mappingMatch(target.dialect, \"to_map\", \"recorded_to\");\n await executeStatement(\n target,\n sql`\n INSERT INTO ${sql.identifier(options.temporaryTable)}\n (${sql.join(columnList, sql`, `)})\n SELECT ${sql.join(values, sql`, `)}\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n -- LEFT JOIN is deliberate: a missing mapping reaches the NOT NULL\n -- revision columns and fails loud instead of silently dropping history.\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS from_map\n ON from_map.graph_id = legacy.graph_id AND ${fromMatch}\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS to_map\n ON to_map.graph_id = legacy.graph_id AND ${toMatch}\n `,\n );\n}\n\nasync function copyRecordedClock(\n target: TransactionBackend,\n options: Readonly<{\n legacyTable: string;\n mappingTable: string;\n temporaryTable: string;\n }>,\n): Promise<void> {\n await assertRecordedClockMappings(target, options);\n const match = mappingMatch(target.dialect, \"anchor_map\", \"recorded_at\");\n await executeStatement(\n target,\n sql`\n INSERT INTO ${sql.identifier(options.temporaryTable)}\n (graph_id, revision, recorded_at)\n SELECT legacy.graph_id, anchor_map.revision, legacy.recorded_at\n FROM ${sql.identifier(options.legacyTable)} AS legacy\n -- Preserve fail-loud behavior if the preflight invariant changes later.\n LEFT JOIN ${sql.identifier(options.mappingTable)} AS anchor_map\n ON anchor_map.graph_id = legacy.graph_id AND ${match}\n `,\n );\n}\n\nasync function replaceLegacyTables(\n target: TransactionBackend,\n tables: ResolvedSqlTableNames,\n mappingTable: string,\n): Promise<void> {\n const temporary = {\n recordedNodes: temporaryTableName(tables.recordedNodes, \"rn\"),\n recordedEdges: temporaryTableName(tables.recordedEdges, \"re\"),\n recordedClock: temporaryTableName(tables.recordedClock, \"rc\"),\n };\n const ddl = tableDdl(target.dialect, tables, temporary);\n for (const table of Object.values(temporary)) {\n await executeStatement(\n target,\n sql`DROP TABLE IF EXISTS ${sql.identifier(table)}`,\n );\n }\n await executeDdl(target, requireCreateTable(ddl.nodes));\n await executeDdl(target, requireCreateTable(ddl.edges));\n await executeDdl(target, requireCreateTable(ddl.clock));\n await copyRecordedRelation(target, {\n columns: RECORDED_NODE_COLUMNS,\n legacyTable: tables.recordedNodes,\n mappingTable,\n temporaryTable: temporary.recordedNodes,\n });\n await copyRecordedRelation(target, {\n columns: RECORDED_EDGE_COLUMNS,\n legacyTable: tables.recordedEdges,\n mappingTable,\n temporaryTable: temporary.recordedEdges,\n });\n await copyRecordedClock(target, {\n legacyTable: tables.recordedClock,\n mappingTable,\n temporaryTable: temporary.recordedClock,\n });\n\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(tables.recordedNodes)}`,\n );\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(tables.recordedEdges)}`,\n );\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(tables.recordedClock)}`,\n );\n await renameTable(target, temporary.recordedNodes, tables.recordedNodes);\n await renameTable(target, temporary.recordedEdges, tables.recordedEdges);\n await renameTable(target, temporary.recordedClock, tables.recordedClock);\n await renamePrimaryKeyConstraint(\n target,\n temporary.recordedNodes,\n tables.recordedNodes,\n );\n await renamePrimaryKeyConstraint(\n target,\n temporary.recordedEdges,\n tables.recordedEdges,\n );\n await renamePrimaryKeyConstraint(\n target,\n temporary.recordedClock,\n tables.recordedClock,\n );\n for (const statement of [\n ...ddl.nodes.slice(1),\n ...ddl.edges.slice(1),\n ...ddl.clock.slice(1),\n ]) {\n await executeDdl(target, statement);\n }\n}\n\nasync function renamePrimaryKeyConstraint(\n target: TransactionBackend,\n temporaryTable: string,\n finalTable: string,\n): Promise<void> {\n if (target.dialect !== \"postgres\") return;\n await executeStatement(\n target,\n sql`\n ALTER TABLE ${sql.identifier(finalTable)}\n RENAME CONSTRAINT ${sql.identifier(`${temporaryTable}_pkey`)}\n TO ${sql.identifier(shortenedIdentifier(`${finalTable}_pkey`))}\n `,\n );\n}\n\nfunction requireCreateTable(statements: readonly string[]): string {\n const statement = statements[0];\n if (statement === undefined) {\n throw new ConfigurationError(\"Recorded migration table DDL was empty.\");\n }\n return statement;\n}\n\nasync function renameTable(\n target: TransactionBackend,\n from: string,\n to: string,\n): Promise<void> {\n try {\n await executeStatement(\n target,\n sql`ALTER TABLE ${sql.identifier(from)} RENAME TO ${sql.identifier(to)}`,\n );\n } catch (error) {\n throw new ConfigurationError(\n \"Could not rename a migrated recorded-time table.\",\n { from, to },\n { cause: error },\n );\n }\n}\n\n/**\n * Rewrites timestamp-only recorded relations to numeric revisions.\n *\n * Run offline before opening a Store with the new schema. The durable mapping\n * table is retained so external checkpoint stores can call\n * {@link migrateRecordedAnchor}; delete each graph's rows after its downstream\n * checkpoints have been rewritten.\n */\nexport async function migrateLegacyRecordedTime(\n options: MigrateLegacyRecordedTimeOptions,\n): Promise<MigrateLegacyRecordedTimeResult> {\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const mapTable = mappingTableName(tables, options.mappingTableName);\n return options.backend.transaction(async (target) => {\n const clockColumns = await columnNames(target, tables.recordedClock);\n if (clockColumns.size === 0) {\n return {\n migrated: false,\n graphs: 0,\n anchors: 0,\n mappingTableName: mapTable,\n };\n }\n if (clockColumns.has(\"revision\")) {\n const mapColumns = await columnNames(target, mapTable);\n if (mapColumns.size === 0) {\n return {\n migrated: false,\n graphs: 0,\n anchors: 0,\n mappingTableName: mapTable,\n };\n }\n const rows = await target.execute<MappingCountRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS anchors, COUNT(DISTINCT graph_id) AS graphs\n FROM ${sql.identifier(mapTable)}\n `),\n );\n const anchors = Number(rows[0]?.anchors ?? 0);\n const graphs = Number(rows[0]?.graphs ?? 0);\n return {\n migrated: false,\n graphs: Number.isSafeInteger(graphs) ? graphs : 0,\n anchors: Number.isSafeInteger(anchors) ? anchors : 0,\n mappingTableName: mapTable,\n };\n }\n const nodeColumns = await columnNames(target, tables.recordedNodes);\n const edgeColumns = await columnNames(target, tables.recordedEdges);\n if (\n !nodeColumns.has(\"recorded_from\") ||\n !edgeColumns.has(\"recorded_from\")\n ) {\n throw new ConfigurationError(\n \"Legacy recorded-time schema is incomplete.\",\n { tables },\n );\n }\n\n await executeDdl(target, migrationMapDdl(target.dialect, mapTable));\n const mapping = await readLegacyInstants(target, tables);\n await writeMappingRows(target, mapTable, mapping);\n await replaceLegacyTables(target, tables, mapTable);\n return {\n migrated: true,\n graphs: new Set(mapping.map((row) => row.graphId)).size,\n anchors: mapping.length,\n mappingTableName: mapTable,\n };\n });\n}\n\n/** Remaps one timestamp-only checkpoint after {@link migrateLegacyRecordedTime}. */\nexport async function migrateRecordedAnchor(\n options: MigrateRecordedAnchorOptions,\n): Promise<RecordedInstant> {\n try {\n return asRecordedInstant(options.anchor);\n } catch (error) {\n if (!(error instanceof ValidationError)) throw error;\n }\n const legacyRecordedAt = canonicalLegacyInstant(options.anchor);\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const mapTable = mappingTableName(tables, options.mappingTableName);\n const rows = await options.backend.execute<RemapRow>(\n asCompiledRowsSql(sql`\n SELECT revision, recorded_at\n FROM ${sql.identifier(mapTable)}\n WHERE graph_id = ${options.graphId}\n AND legacy_recorded_at = ${legacyRecordedAt}\n `),\n );\n const row = rows[0];\n if (row === undefined) {\n throw new ConfigurationError(\n \"No migrated recorded anchor matches this graph and legacy timestamp.\",\n { anchor: options.anchor, graphId: options.graphId },\n {\n suggestion:\n \"Run migrateLegacyRecordedTime() before deleting its mapping rows, and pass the graph that produced the checkpoint.\",\n },\n );\n }\n return createRecordedInstant(\n safeRevision(row.revision),\n canonicalLegacyInstant(row.recorded_at),\n );\n}\n\n/**\n * Deletes one graph's legacy remap rows after downstream checkpoints migrate.\n * Set `dropWhenEmpty` to remove the migration table after the final graph.\n */\nexport async function deleteLegacyRecordedAnchorMap(\n options: DeleteLegacyRecordedAnchorMapOptions,\n): Promise<void> {\n if (options.backend.executeStatement === undefined) {\n throw new ConfigurationError(\n \"Deleting a recorded anchor migration map requires executeStatement support.\",\n { dialect: options.backend.dialect },\n );\n }\n const tables = resolvedTableNames(options.backend, options.tableNames);\n const mapTable = mappingTableName(tables, options.mappingTableName);\n await options.backend.transaction(async (target) => {\n await executeStatement(\n target,\n sql`\n DELETE FROM ${sql.identifier(mapTable)}\n WHERE graph_id = ${options.graphId}\n `,\n );\n if (options.dropWhenEmpty !== true) return;\n const rows = await target.execute<MappingCountRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS anchors, COUNT(DISTINCT graph_id) AS graphs\n FROM ${sql.identifier(mapTable)}\n `),\n );\n const remaining = missingMappingCount(rows[0]?.anchors, mapTable);\n if (remaining === 0) {\n await executeStatement(\n target,\n sql`DROP TABLE ${sql.identifier(mapTable)}`,\n );\n }\n });\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkUTTW2Q3M_cjs = require('./chunk-UTTW2Q3M.cjs');
3
+ var chunkJXUTCSXX_cjs = require('./chunk-JXUTCSXX.cjs');
4
4
 
5
5
  // src/indexes/system.ts
6
6
  var SYSTEM_INDEX_DECLARATIONS = [
@@ -175,7 +175,7 @@ var MAX_SQL_IDENTIFIER_LENGTH = 63;
175
175
  function systemIndexName(physicalTableName, suffix) {
176
176
  const full = `${physicalTableName}_${suffix}`;
177
177
  if (full.length <= MAX_SQL_IDENTIFIER_LENGTH) return full;
178
- const hash = chunkUTTW2Q3M_cjs.shortHash(JSON.stringify([physicalTableName, suffix]));
178
+ const hash = chunkJXUTCSXX_cjs.shortHash(JSON.stringify([physicalTableName, suffix]));
179
179
  return `${full.slice(0, MAX_SQL_IDENTIFIER_LENGTH - 1 - hash.length)}_${hash}`;
180
180
  }
181
181
  function resolveSystemIndexNames(overrides) {
@@ -200,11 +200,11 @@ function assertNoSystemIndexNameCollision(indexes, overrides) {
200
200
  }
201
201
  }
202
202
  function generateSystemIndexDDL(declaration, physicalTableName, options) {
203
- const name = chunkUTTW2Q3M_cjs.quoteIdentifier(
203
+ const name = chunkJXUTCSXX_cjs.quoteIdentifier(
204
204
  systemIndexName(physicalTableName, declaration.suffix)
205
205
  );
206
- const table = chunkUTTW2Q3M_cjs.quoteIdentifier(physicalTableName);
207
- const columns = declaration.columns.map((column) => chunkUTTW2Q3M_cjs.quoteIdentifier(column)).join(", ");
206
+ const table = chunkJXUTCSXX_cjs.quoteIdentifier(physicalTableName);
207
+ const columns = declaration.columns.map((column) => chunkJXUTCSXX_cjs.quoteIdentifier(column)).join(", ");
208
208
  const concurrently = options.concurrent ? "CONCURRENTLY " : "";
209
209
  return `CREATE INDEX ${concurrently}IF NOT EXISTS ${name} ON ${table} (${columns});`;
210
210
  }
@@ -215,5 +215,5 @@ exports.generateSystemIndexDDL = generateSystemIndexDDL;
215
215
  exports.resolveSystemIndexNames = resolveSystemIndexNames;
216
216
  exports.resolveSystemIndexTableName = resolveSystemIndexTableName;
217
217
  exports.systemIndexName = systemIndexName;
218
- //# sourceMappingURL=chunk-TRC646QQ.cjs.map
219
- //# sourceMappingURL=chunk-TRC646QQ.cjs.map
218
+ //# sourceMappingURL=chunk-5GAONX5G.cjs.map
219
+ //# sourceMappingURL=chunk-5GAONX5G.cjs.map