@nicia-ai/typegraph 0.50.0 → 0.51.1

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 (326) hide show
  1. package/README.md +12 -0
  2. package/dist/backend/drizzle/indexes.cjs +10 -8
  3. package/dist/backend/drizzle/indexes.d.cts +1 -1
  4. package/dist/backend/drizzle/indexes.d.ts +1 -1
  5. package/dist/backend/drizzle/indexes.js +6 -4
  6. package/dist/backend/index.cjs +183 -50
  7. package/dist/backend/index.d.cts +90 -4
  8. package/dist/backend/index.d.ts +90 -4
  9. package/dist/backend/index.js +6 -9
  10. package/dist/backend/postgres/index.cjs +30 -28
  11. package/dist/backend/postgres/index.d.cts +7 -7
  12. package/dist/backend/postgres/index.d.ts +7 -7
  13. package/dist/backend/postgres/index.js +16 -14
  14. package/dist/backend/postgres/pglite-store.cjs +6 -62
  15. package/dist/backend/postgres/pglite-store.cjs.map +1 -1
  16. package/dist/backend/postgres/pglite-store.d.cts +8 -8
  17. package/dist/backend/postgres/pglite-store.d.ts +8 -8
  18. package/dist/backend/postgres/pglite-store.js +6 -62
  19. package/dist/backend/postgres/pglite-store.js.map +1 -1
  20. package/dist/backend/postgres/pglite.cjs +18 -16
  21. package/dist/backend/postgres/pglite.d.cts +3 -3
  22. package/dist/backend/postgres/pglite.d.ts +3 -3
  23. package/dist/backend/postgres/pglite.js +17 -15
  24. package/dist/backend/sqlite/index.cjs +27 -25
  25. package/dist/backend/sqlite/index.d.cts +7 -7
  26. package/dist/backend/sqlite/index.d.ts +7 -7
  27. package/dist/backend/sqlite/index.js +14 -12
  28. package/dist/backend/sqlite/libsql.cjs +21 -19
  29. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  30. package/dist/backend/sqlite/libsql.d.cts +3 -3
  31. package/dist/backend/sqlite/libsql.d.ts +3 -3
  32. package/dist/backend/sqlite/libsql.js +16 -14
  33. package/dist/backend/sqlite/libsql.js.map +1 -1
  34. package/dist/backend/sqlite/local-store.cjs +8 -64
  35. package/dist/backend/sqlite/local-store.cjs.map +1 -1
  36. package/dist/backend/sqlite/local-store.d.cts +8 -8
  37. package/dist/backend/sqlite/local-store.d.ts +8 -8
  38. package/dist/backend/sqlite/local-store.js +7 -64
  39. package/dist/backend/sqlite/local-store.js.map +1 -1
  40. package/dist/backend/sqlite/local.cjs +22 -19
  41. package/dist/backend/sqlite/local.d.cts +3 -3
  42. package/dist/backend/sqlite/local.d.ts +3 -3
  43. package/dist/backend/sqlite/local.js +18 -15
  44. package/dist/{chunk-TUVD4DFR.cjs → chunk-2CVDZCXH.cjs} +122 -51
  45. package/dist/chunk-2CVDZCXH.cjs.map +1 -0
  46. package/dist/{chunk-I5C6OTKR.js → chunk-2DWTBNSH.js} +3 -3
  47. package/dist/{chunk-I5C6OTKR.js.map → chunk-2DWTBNSH.js.map} +1 -1
  48. package/dist/{chunk-C76WFIVZ.cjs → chunk-2KCTP3U2.cjs} +180 -127
  49. package/dist/chunk-2KCTP3U2.cjs.map +1 -0
  50. package/dist/{chunk-BYBDM423.cjs → chunk-322TBTOQ.cjs} +48 -48
  51. package/dist/{chunk-BYBDM423.cjs.map → chunk-322TBTOQ.cjs.map} +1 -1
  52. package/dist/chunk-36SX6QXP.cjs +186 -0
  53. package/dist/chunk-36SX6QXP.cjs.map +1 -0
  54. package/dist/{chunk-H3XP6BAV.js → chunk-36VYWVQU.js} +3 -3
  55. package/dist/{chunk-H3XP6BAV.js.map → chunk-36VYWVQU.js.map} +1 -1
  56. package/dist/{chunk-VTJVMP4I.js → chunk-4DKY6RIU.js} +102 -31
  57. package/dist/chunk-4DKY6RIU.js.map +1 -0
  58. package/dist/chunk-4QKOZYMV.js +9 -0
  59. package/dist/chunk-4QKOZYMV.js.map +1 -0
  60. package/dist/{chunk-U3Z7XKAG.js → chunk-57JM6NW3.js} +8 -18
  61. package/dist/chunk-57JM6NW3.js.map +1 -0
  62. package/dist/{chunk-WCLMKNQE.cjs → chunk-5FVZSE3B.cjs} +1356 -1108
  63. package/dist/chunk-5FVZSE3B.cjs.map +1 -0
  64. package/dist/{chunk-XMY2SXOH.cjs → chunk-5WWEYV4H.cjs} +2208 -579
  65. package/dist/chunk-5WWEYV4H.cjs.map +1 -0
  66. package/dist/{chunk-WQBAQZHR.js → chunk-6NLYIMJO.js} +4 -4
  67. package/dist/{chunk-WQBAQZHR.js.map → chunk-6NLYIMJO.js.map} +1 -1
  68. package/dist/{chunk-G2TLHH6T.cjs → chunk-7B7I7YAW.cjs} +6 -6
  69. package/dist/{chunk-G2TLHH6T.cjs.map → chunk-7B7I7YAW.cjs.map} +1 -1
  70. package/dist/{chunk-EDLKIQRI.js → chunk-7G5IYROL.js} +6 -548
  71. package/dist/chunk-7G5IYROL.js.map +1 -0
  72. package/dist/{chunk-46UGOVRW.js → chunk-7QFRK6PU.js} +3 -7
  73. package/dist/chunk-7QFRK6PU.js.map +1 -0
  74. package/dist/chunk-A4C4NJ5U.cjs +12 -0
  75. package/dist/chunk-A4C4NJ5U.cjs.map +1 -0
  76. package/dist/{chunk-7CCMCMJO.cjs → chunk-AOGOC6JF.cjs} +77 -68
  77. package/dist/chunk-AOGOC6JF.cjs.map +1 -0
  78. package/dist/{chunk-TYGGUWMS.cjs → chunk-B3MN7EJR.cjs} +177 -137
  79. package/dist/chunk-B3MN7EJR.cjs.map +1 -0
  80. package/dist/{chunk-K6VKTBST.cjs → chunk-BZ5MVITP.cjs} +4 -4
  81. package/dist/{chunk-K6VKTBST.cjs.map → chunk-BZ5MVITP.cjs.map} +1 -1
  82. package/dist/{chunk-ZAQUKCUC.js → chunk-CBOD7TXH.js} +5 -5
  83. package/dist/{chunk-ZAQUKCUC.js.map → chunk-CBOD7TXH.js.map} +1 -1
  84. package/dist/{chunk-LLVOQOWE.cjs → chunk-CRZ56SZU.cjs} +6 -5
  85. package/dist/chunk-CRZ56SZU.cjs.map +1 -0
  86. package/dist/{chunk-ON47CBE4.cjs → chunk-D3GWARN7.cjs} +47 -47
  87. package/dist/{chunk-ON47CBE4.cjs.map → chunk-D3GWARN7.cjs.map} +1 -1
  88. package/dist/{chunk-W5SOCUBL.js → chunk-D3OUDFU7.js} +5 -5
  89. package/dist/{chunk-W5SOCUBL.js.map → chunk-D3OUDFU7.js.map} +1 -1
  90. package/dist/chunk-EKG2UXNX.cjs +23 -0
  91. package/dist/chunk-EKG2UXNX.cjs.map +1 -0
  92. package/dist/{chunk-2Q45FAIE.js → chunk-EVYW3532.js} +28 -19
  93. package/dist/chunk-EVYW3532.js.map +1 -0
  94. package/dist/{chunk-7PRMDZIA.cjs → chunk-FMMW3KX7.cjs} +21 -55
  95. package/dist/chunk-FMMW3KX7.cjs.map +1 -0
  96. package/dist/chunk-H2VWDQWC.cjs +571 -0
  97. package/dist/chunk-H2VWDQWC.cjs.map +1 -0
  98. package/dist/chunk-H4FY6OZK.js +13 -0
  99. package/dist/chunk-H4FY6OZK.js.map +1 -0
  100. package/dist/{chunk-OJHD3LXJ.cjs → chunk-H5IJSROF.cjs} +2 -8
  101. package/dist/chunk-H5IJSROF.cjs.map +1 -0
  102. package/dist/{chunk-U5EL6JUV.js → chunk-I5IOSA27.js} +101 -103
  103. package/dist/chunk-I5IOSA27.js.map +1 -0
  104. package/dist/{chunk-SHC7BCG5.cjs → chunk-I7YAY2VQ.cjs} +7 -7
  105. package/dist/{chunk-SHC7BCG5.cjs.map → chunk-I7YAY2VQ.cjs.map} +1 -1
  106. package/dist/chunk-IRCWIA3R.js +20 -0
  107. package/dist/chunk-IRCWIA3R.js.map +1 -0
  108. package/dist/chunk-IVQBLXBK.cjs +55 -0
  109. package/dist/chunk-IVQBLXBK.cjs.map +1 -0
  110. package/dist/{chunk-5PP4KRPV.js → chunk-IZD4HTCP.js} +5 -5
  111. package/dist/{chunk-5PP4KRPV.js.map → chunk-IZD4HTCP.js.map} +1 -1
  112. package/dist/{chunk-RDP6ZRSM.cjs → chunk-JQKMEKKW.cjs} +261 -204
  113. package/dist/chunk-JQKMEKKW.cjs.map +1 -0
  114. package/dist/chunk-JVA3KDEA.cjs +691 -0
  115. package/dist/chunk-JVA3KDEA.cjs.map +1 -0
  116. package/dist/{chunk-JG5XIJDY.js → chunk-K67P5DLL.js} +62 -22
  117. package/dist/chunk-K67P5DLL.js.map +1 -0
  118. package/dist/{chunk-MX7EKQPM.js → chunk-K6OZIHKI.js} +345 -97
  119. package/dist/chunk-K6OZIHKI.js.map +1 -0
  120. package/dist/{chunk-CS6JTQQ2.cjs → chunk-KACEYDYV.cjs} +94 -62
  121. package/dist/chunk-KACEYDYV.cjs.map +1 -0
  122. package/dist/{chunk-5OWHU7Z7.cjs → chunk-L6EVYIID.cjs} +248 -210
  123. package/dist/chunk-L6EVYIID.cjs.map +1 -0
  124. package/dist/{chunk-7OWE7WD6.js → chunk-LI4K2KEJ.js} +4 -4
  125. package/dist/{chunk-7OWE7WD6.js.map → chunk-LI4K2KEJ.js.map} +1 -1
  126. package/dist/chunk-LKZDQ2B4.js +1581 -0
  127. package/dist/chunk-LKZDQ2B4.js.map +1 -0
  128. package/dist/{chunk-45YZXI6X.cjs → chunk-LLFPQOBA.cjs} +27 -27
  129. package/dist/{chunk-45YZXI6X.cjs.map → chunk-LLFPQOBA.cjs.map} +1 -1
  130. package/dist/{chunk-ZRJTM7MT.js → chunk-LZMQ3SFK.js} +3 -3
  131. package/dist/{chunk-ZRJTM7MT.js.map → chunk-LZMQ3SFK.js.map} +1 -1
  132. package/dist/{chunk-DI6VC62F.js → chunk-M3VTS3F6.js} +3 -3
  133. package/dist/{chunk-DI6VC62F.js.map → chunk-M3VTS3F6.js.map} +1 -1
  134. package/dist/{chunk-MZ34E2GN.js → chunk-NBOS7BY3.js} +60 -21
  135. package/dist/chunk-NBOS7BY3.js.map +1 -0
  136. package/dist/{chunk-YA36ABIL.js → chunk-NGQDGL5X.js} +14 -48
  137. package/dist/chunk-NGQDGL5X.js.map +1 -0
  138. package/dist/{chunk-ZBFZGLZE.cjs → chunk-NLX5OWK7.cjs} +6 -2
  139. package/dist/chunk-NLX5OWK7.cjs.map +1 -0
  140. package/dist/chunk-NUQ2YFFH.cjs +1637 -0
  141. package/dist/chunk-NUQ2YFFH.cjs.map +1 -0
  142. package/dist/{chunk-TTCOPKUL.cjs → chunk-OGL4X4PH.cjs} +182 -184
  143. package/dist/chunk-OGL4X4PH.cjs.map +1 -0
  144. package/dist/{chunk-HY5BNOUN.cjs → chunk-OTNTGEXR.cjs} +4 -4
  145. package/dist/{chunk-HY5BNOUN.cjs.map → chunk-OTNTGEXR.cjs.map} +1 -1
  146. package/dist/chunk-OTWE63BW.js +53 -0
  147. package/dist/chunk-OTWE63BW.js.map +1 -0
  148. package/dist/chunk-PC5NGH5A.js +549 -0
  149. package/dist/chunk-PC5NGH5A.js.map +1 -0
  150. package/dist/{chunk-IPRP6TDL.cjs → chunk-PS3TUWJM.cjs} +7 -7
  151. package/dist/{chunk-IPRP6TDL.cjs.map → chunk-PS3TUWJM.cjs.map} +1 -1
  152. package/dist/{chunk-V76FGHY3.js → chunk-PVFFH7TL.js} +5 -5
  153. package/dist/{chunk-V76FGHY3.js.map → chunk-PVFFH7TL.js.map} +1 -1
  154. package/dist/chunk-QCD5JKU4.cjs +15 -0
  155. package/dist/chunk-QCD5JKU4.cjs.map +1 -0
  156. package/dist/{chunk-IRPYOHRC.js → chunk-QG5VEOKX.js} +6 -2
  157. package/dist/chunk-QG5VEOKX.js.map +1 -0
  158. package/dist/{chunk-2CYI5HRH.js → chunk-RI7RJH4G.js} +49 -17
  159. package/dist/chunk-RI7RJH4G.js.map +1 -0
  160. package/dist/{chunk-5LKOVCPP.js → chunk-RVUL2HXY.js} +6 -5
  161. package/dist/chunk-RVUL2HXY.js.map +1 -0
  162. package/dist/{chunk-WK23PGTP.cjs → chunk-S5GU4LUN.cjs} +11 -11
  163. package/dist/{chunk-WK23PGTP.cjs.map → chunk-S5GU4LUN.cjs.map} +1 -1
  164. package/dist/{chunk-S33YQEL7.js → chunk-SDPWO2Z5.js} +6 -6
  165. package/dist/{chunk-S33YQEL7.js.map → chunk-SDPWO2Z5.js.map} +1 -1
  166. package/dist/{chunk-6S3PTHL4.js → chunk-SLGGT2XD.js} +3 -3
  167. package/dist/{chunk-6S3PTHL4.js.map → chunk-SLGGT2XD.js.map} +1 -1
  168. package/dist/{chunk-HSEZ7X6Y.cjs → chunk-TIJUA4I6.cjs} +45 -45
  169. package/dist/{chunk-HSEZ7X6Y.cjs.map → chunk-TIJUA4I6.cjs.map} +1 -1
  170. package/dist/{chunk-CSNOYIB4.cjs → chunk-TM54OBHX.cjs} +13 -13
  171. package/dist/{chunk-CSNOYIB4.cjs.map → chunk-TM54OBHX.cjs.map} +1 -1
  172. package/dist/{chunk-MM3JHVKZ.cjs → chunk-TUWSVL6I.cjs} +4 -4
  173. package/dist/{chunk-MM3JHVKZ.cjs.map → chunk-TUWSVL6I.cjs.map} +1 -1
  174. package/dist/{chunk-2GIV5X4P.js → chunk-TYEYRCXL.js} +86 -33
  175. package/dist/chunk-TYEYRCXL.js.map +1 -0
  176. package/dist/{chunk-MJPZNEJZ.js → chunk-UKOVGCRN.js} +2095 -496
  177. package/dist/chunk-UKOVGCRN.js.map +1 -0
  178. package/dist/chunk-UYKDYE5D.cjs +12 -0
  179. package/dist/{chunk-KWNWG4RC.cjs.map → chunk-UYKDYE5D.cjs.map} +1 -1
  180. package/dist/{chunk-FX5ZW6PN.js → chunk-VAAC7L57.js} +95 -40
  181. package/dist/chunk-VAAC7L57.js.map +1 -0
  182. package/dist/{chunk-ISKCIQF2.cjs → chunk-VKHXYVN7.cjs} +14 -25
  183. package/dist/chunk-VKHXYVN7.cjs.map +1 -0
  184. package/dist/chunk-VUQZNUHU.js +171 -0
  185. package/dist/chunk-VUQZNUHU.js.map +1 -0
  186. package/dist/{chunk-K2XYLVVB.cjs → chunk-WDM5WQK4.cjs} +175 -136
  187. package/dist/chunk-WDM5WQK4.cjs.map +1 -0
  188. package/dist/{chunk-GVYVGGPJ.js → chunk-WFSYYU4W.js} +66 -28
  189. package/dist/chunk-WFSYYU4W.js.map +1 -0
  190. package/dist/{chunk-R7MRFE5P.js → chunk-WS5MT2UJ.js} +3 -3
  191. package/dist/{chunk-R7MRFE5P.js.map → chunk-WS5MT2UJ.js.map} +1 -1
  192. package/dist/chunk-XORONCV3.js +202 -0
  193. package/dist/chunk-XORONCV3.js.map +1 -0
  194. package/dist/chunk-ZGVTNKTX.cjs +217 -0
  195. package/dist/chunk-ZGVTNKTX.cjs.map +1 -0
  196. package/dist/core/index.cjs +20 -20
  197. package/dist/core/index.d.cts +4 -4
  198. package/dist/core/index.d.ts +4 -4
  199. package/dist/core/index.js +4 -4
  200. package/dist/{ddl-B49O7dB_.d.ts → ddl-BvcbgzHo.d.ts} +3 -3
  201. package/dist/{ddl-DcZG660s.d.cts → ddl-Ufebz5q5.d.cts} +3 -3
  202. package/dist/graph-extension/index.d.cts +2 -4
  203. package/dist/graph-extension/index.d.ts +2 -4
  204. package/dist/graph-merge/index.cjs +140 -125
  205. package/dist/graph-merge/index.cjs.map +1 -1
  206. package/dist/graph-merge/index.d.cts +8 -9
  207. package/dist/graph-merge/index.d.ts +8 -9
  208. package/dist/graph-merge/index.js +42 -27
  209. package/dist/graph-merge/index.js.map +1 -1
  210. package/dist/index.cjs +144 -143
  211. package/dist/index.cjs.map +1 -1
  212. package/dist/index.d.cts +11 -12
  213. package/dist/index.d.ts +11 -12
  214. package/dist/index.js +30 -29
  215. package/dist/index.js.map +1 -1
  216. package/dist/indexes/index.cjs +14 -12
  217. package/dist/indexes/index.d.cts +4 -4
  218. package/dist/indexes/index.d.ts +4 -4
  219. package/dist/indexes/index.js +7 -5
  220. package/dist/{ingestion-import-target-CI8OWIkM.d.ts → ingestion-import-target-CAs1OX-l.d.cts} +1 -1
  221. package/dist/{ingestion-import-target-DCpfM1PX.d.cts → ingestion-import-target-DCQSPfNx.d.ts} +1 -1
  222. package/dist/interchange/index.cjs +41 -39
  223. package/dist/interchange/index.cjs.map +1 -1
  224. package/dist/interchange/index.d.cts +8 -8
  225. package/dist/interchange/index.d.ts +8 -8
  226. package/dist/interchange/index.js +16 -14
  227. package/dist/interchange/index.js.map +1 -1
  228. package/dist/local-store-impl-JC7OBRAW.js +75 -0
  229. package/dist/local-store-impl-JC7OBRAW.js.map +1 -0
  230. package/dist/local-store-impl-UOS2LUIG.cjs +77 -0
  231. package/dist/local-store-impl-UOS2LUIG.cjs.map +1 -0
  232. package/dist/{manager-Cfg1ENj1.d.ts → manager-B68OrPR2.d.ts} +1 -2
  233. package/dist/{manager-D348fa6W.d.cts → manager-D_t7oK69.d.cts} +1 -2
  234. package/dist/pglite-store-impl-J5J5AA52.cjs +75 -0
  235. package/dist/pglite-store-impl-J5J5AA52.cjs.map +1 -0
  236. package/dist/pglite-store-impl-LDRH2DUH.js +73 -0
  237. package/dist/pglite-store-impl-LDRH2DUH.js.map +1 -0
  238. package/dist/{postgres-UStOycLI.d.ts → postgres-BPLSVyHM.d.ts} +1 -1
  239. package/dist/{postgres-CH1kkM5J.d.cts → postgres-CqvtFC2y.d.cts} +1 -1
  240. package/dist/profiler/index.d.cts +9 -9
  241. package/dist/profiler/index.d.ts +9 -9
  242. package/dist/provenance/index.cjs +33 -20
  243. package/dist/provenance/index.cjs.map +1 -1
  244. package/dist/provenance/index.d.cts +7 -7
  245. package/dist/provenance/index.d.ts +7 -7
  246. package/dist/provenance/index.js +24 -11
  247. package/dist/provenance/index.js.map +1 -1
  248. package/dist/{repair-validity-windows-aWX7VNvv.d.cts → repair-validity-windows-DEzCKAdy.d.cts} +7 -3
  249. package/dist/{repair-validity-windows-BtOEe2pS.d.ts → repair-validity-windows-GMdaS2AH.d.ts} +7 -3
  250. package/dist/resolve-D_H8MHtq.d.ts +1805 -0
  251. package/dist/resolve-WEW8gWws.d.cts +1805 -0
  252. package/dist/schema/index.cjs +42 -40
  253. package/dist/schema/index.d.cts +4 -6
  254. package/dist/schema/index.d.ts +4 -6
  255. package/dist/schema/index.js +15 -13
  256. package/dist/{searchable-z4BiFfHI.d.ts → searchable-C_UREI9K.d.ts} +1 -1
  257. package/dist/{searchable-C8-RrL3l.d.cts → searchable-ClgET_i7.d.cts} +1 -1
  258. package/dist/{sqlite-axLw5Lo5.d.ts → sqlite-D1mXO9Kp.d.cts} +2 -1
  259. package/dist/{sqlite-Cyx9j9o6.d.cts → sqlite-MZA3oZNB.d.ts} +2 -1
  260. package/dist/{store-CTfQ9taw.d.ts → store-CuFX7fCx.d.cts} +38 -41
  261. package/dist/{store-DR9J7JVB.d.cts → store-D-ZjXQpW.d.ts} +38 -41
  262. package/dist/{temporal-CBOrERz5.d.ts → temporal-CpyEiRY8.d.cts} +1 -1
  263. package/dist/{temporal-B4Ky4wzh.d.cts → temporal-y0Aep9Su.d.ts} +1 -1
  264. package/dist/{types-CWg4dTjj.d.ts → types-6yf0Vv-_.d.cts} +1672 -1
  265. package/dist/{types-CWg4dTjj.d.cts → types-6yf0Vv-_.d.ts} +1672 -1
  266. package/dist/{types-BScHXVM7.d.ts → types-DzJ4dlzk.d.cts} +1 -1
  267. package/dist/{types-BE921wRl.d.cts → types-_vVSB9k-.d.ts} +1 -1
  268. package/dist/{where-BWXUPV3C.d.ts → where-DuG2LCLe.d.ts} +1 -1
  269. package/dist/{where-CNtx1aLc.d.cts → where-Mhf_yyKX.d.cts} +1 -1
  270. package/package.json +5 -1
  271. package/dist/chunk-2CYI5HRH.js.map +0 -1
  272. package/dist/chunk-2GIV5X4P.js.map +0 -1
  273. package/dist/chunk-2Q45FAIE.js.map +0 -1
  274. package/dist/chunk-46UGOVRW.js.map +0 -1
  275. package/dist/chunk-5LKOVCPP.js.map +0 -1
  276. package/dist/chunk-5OWHU7Z7.cjs.map +0 -1
  277. package/dist/chunk-6LEOAIIB.js +0 -1160
  278. package/dist/chunk-6LEOAIIB.js.map +0 -1
  279. package/dist/chunk-7CCMCMJO.cjs.map +0 -1
  280. package/dist/chunk-7PRMDZIA.cjs.map +0 -1
  281. package/dist/chunk-C76WFIVZ.cjs.map +0 -1
  282. package/dist/chunk-CS6JTQQ2.cjs.map +0 -1
  283. package/dist/chunk-EDLKIQRI.js.map +0 -1
  284. package/dist/chunk-EH3JZJUM.cjs +0 -567
  285. package/dist/chunk-EH3JZJUM.cjs.map +0 -1
  286. package/dist/chunk-FX5ZW6PN.js.map +0 -1
  287. package/dist/chunk-GHZPZNFC.cjs +0 -132
  288. package/dist/chunk-GHZPZNFC.cjs.map +0 -1
  289. package/dist/chunk-GVYVGGPJ.js.map +0 -1
  290. package/dist/chunk-IHK5KA2Q.cjs +0 -262
  291. package/dist/chunk-IHK5KA2Q.cjs.map +0 -1
  292. package/dist/chunk-IRPYOHRC.js.map +0 -1
  293. package/dist/chunk-ISKCIQF2.cjs.map +0 -1
  294. package/dist/chunk-JG5XIJDY.js.map +0 -1
  295. package/dist/chunk-K2XYLVVB.cjs.map +0 -1
  296. package/dist/chunk-KWNWG4RC.cjs +0 -12
  297. package/dist/chunk-LLVOQOWE.cjs.map +0 -1
  298. package/dist/chunk-MJPZNEJZ.js.map +0 -1
  299. package/dist/chunk-MX7EKQPM.js.map +0 -1
  300. package/dist/chunk-MZ34E2GN.js.map +0 -1
  301. package/dist/chunk-OJHD3LXJ.cjs.map +0 -1
  302. package/dist/chunk-PALYTHGM.js +0 -114
  303. package/dist/chunk-PALYTHGM.js.map +0 -1
  304. package/dist/chunk-RDP6ZRSM.cjs.map +0 -1
  305. package/dist/chunk-S3SDEQMC.js +0 -532
  306. package/dist/chunk-S3SDEQMC.js.map +0 -1
  307. package/dist/chunk-TEC24ZDA.cjs +0 -1254
  308. package/dist/chunk-TEC24ZDA.cjs.map +0 -1
  309. package/dist/chunk-TP4NJTI3.cjs +0 -1192
  310. package/dist/chunk-TP4NJTI3.cjs.map +0 -1
  311. package/dist/chunk-TTCOPKUL.cjs.map +0 -1
  312. package/dist/chunk-TUVD4DFR.cjs.map +0 -1
  313. package/dist/chunk-TYGGUWMS.cjs.map +0 -1
  314. package/dist/chunk-U3Z7XKAG.js.map +0 -1
  315. package/dist/chunk-U5EL6JUV.js.map +0 -1
  316. package/dist/chunk-VTJVMP4I.js.map +0 -1
  317. package/dist/chunk-WCLMKNQE.cjs.map +0 -1
  318. package/dist/chunk-XMY2SXOH.cjs.map +0 -1
  319. package/dist/chunk-Y55DLLEG.js +0 -247
  320. package/dist/chunk-Y55DLLEG.js.map +0 -1
  321. package/dist/chunk-YA36ABIL.js.map +0 -1
  322. package/dist/chunk-ZBFZGLZE.cjs.map +0 -1
  323. package/dist/index-B0PrmE3K.d.cts +0 -1146
  324. package/dist/index-CwcXsL5R.d.ts +0 -1146
  325. package/dist/materialize-indexes-C9GG3O3C.d.ts +0 -266
  326. package/dist/materialize-indexes-CrSiW_lT.d.cts +0 -266
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/drizzle/execution/sqlite-execution.ts","../src/backend/drizzle/sqlite.ts"],"names":["sql","DURABLE_OBJECT_MAX_BIND_PARAMETERS","D1_MAX_BIND_PARAMETERS","SQLITE_MAX_BIND_PARAMETERS","MODERN_SQLITE_MAX_BIND_PARAMETERS","getOrCreateLru","compileQueryWithDialect","executeCompiled","executeCompiledRun","executePreparedRunBatch","isSqlFragment","toDrizzleSql","EMBEDDING_UPSERT_PARAM_COUNT","FIND_EDGES_ENDPOINT_FIXED_PARAM_COUNT","createNodeRowMapper","SQLITE_ROW_MAPPER_CONFIG","createEdgeRowMapper","createUniqueRowMapper","createSchemaVersionRowMapper","ConfigurationError","BackendDisposedError","SQLITE_CAPABILITIES","buildFulltextCapabilities","buildVectorCapabilities","rows","createCommonOperationBackend","nowIso","vectorSlotFromParams","mapVectorWriteError","chunk","assertVectorSearchLimit","resolveEfSearchOverride","vectorSearchFrontierTuning","buildLiveNodeCandidates","mapHybridSearchRow","assertActiveSchemaVersion","vectorSlotFromCreateIndexParams","vectorSlotFromDropIndexParams","isMissingTableError","coerceNumericScore","resolveDeclaredBackendResource","tables","fts5Strategy","normalizeGraphAnalyticsCapabilities","contributionRebuildSupported","getTableName","createSqliteOperationStrategy","generateSqliteCreateTableSQL","and","eq","mapContributionMaterializationRow","SQLITE_CONTRIBUTION_MAT_TIMESTAMPS","buildContributionInsertValues","buildContributionOnConflictSet","tableExistsFromRow","createSqliteTables","sqliteContributions","createContributionMaterializer","gateFulltext","requireDefined","assertTrustedImportDatabaseEmpty","suspendSqliteSecondaryIndexes","createSqliteTrustedImportSession","restoreSecondaryIndexes","analyzeImportedTables","generateSqliteDDL","options","gateFulltextMethods","mapMaterializationRow","SQLITE_INDEX_MAT_TIMESTAMPS","inArray","buildMaterializationInsertValues","buildMaterializationOnConflictSet","isNull","mapKindRemovalRow","SQLITE_KIND_REMOVAL_TIMESTAMPS","buildKindRemovalInsertValues","buildKindRemovalOnConflictSet","isSqliteNotAuthorizedError","commitSchemaVersionIfKindsEmpty","INTERNAL_TEMPORARY_WRITES","assertAdoptedDialect","BaseSQLiteDatabase","auditBackendResource"],"mappings":";;;;;;;;;;;;;;;AAoBA,IAAM,oCAAA,GAAuC,GAAA;AA8H7C,SAAS,eAAe,EAAA,EAA2C;AACjE,EAAA,MAAM,mBAAA,GAAsB,EAAA;AAC5B,EAAA,MAAM,kBAAA,GAAqB,mBAAA,CAAoB,OAAA,EAAS,WAAA,EAAa,IAAA;AACrE,EAAA,IAAI,uBAAuB,MAAA,EAAW;AACpC,IAAA,OAAO,kBAAA;AAAA,EACT;AAEA,EAAA,OAAO,mBAAA,CAAoB,CAAA,EAAG,OAAA,EAAS,WAAA,EAAa,IAAA;AACtD;AAEA,SAAS,0BAA0B,EAAA,EAAgC;AACjE,EAAA,OAAO,cAAA,CAAe,EAAE,CAAA,KAAM,iBAAA;AAChC;AAEA,SAAS,6BAA6B,EAAA,EAAgC;AACpE,EAAA,MAAM,WAAA,GAAc,eAAe,EAAE,CAAA;AAIrC,EAAA,OACE,WAAA,KAAgB,qBAChB,WAAA,KAAgB,4BAAA;AAEpB;AAEA,SAAS,6BACP,KAAA,EACqC;AACrC,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,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Ac,OAAA,CAAQ;AAAA,GACvB,CAAA;AAQH,EAAA,OAAO,4BAAA,CAA6B;AAAA,IAClC,cAAc,OAAA,CAAQ,YAAA;AAAA,IACtB,IAAI,OAAA,CAAQ,EAAA;AAAA,IACZ,gBAAA,EAAkB,kBAAA;AAAA,IAClB,mBAAmB,OAAA,CAAQ,iBAAA;AAAA,IAC3B,YAAY,OAAA,CAAQ,UAAA;AAAA,IACpB,kBAAkB,OAAA,CAAQ,gBAAA;AAAA,IAC1B,gBAAgB,OAAA,CAAQ,cAAA;AAAA,IACxB,0BAA0B,OAAA,CAAQ,wBAAA;AAAA,IAClC,iBAAA,EAAmB;AAAA,GACpB,CAAA;AACH","file":"chunk-K2XYLVVB.cjs","sourcesContent":["import { type SQL as DrizzleSql, sql } from \"drizzle-orm\";\nimport { type BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport { isSqlFragment } from \"../../../query/sql-fragment\";\nimport {\n D1_MAX_BIND_PARAMETERS,\n DURABLE_OBJECT_MAX_BIND_PARAMETERS,\n MODERN_SQLITE_MAX_BIND_PARAMETERS,\n SQLITE_MAX_BIND_PARAMETERS,\n} from \"../../types\";\nimport { getOrCreateLru } from \"./lru\";\nimport {\n type CompiledSqlQuery,\n compileQueryWithDialect,\n type ExecutableSql,\n type PreparedSqlStatement,\n type SqlExecutionAdapter,\n toDrizzleSql,\n} from \"./types\";\n\nconst DEFAULT_PREPARED_STATEMENT_CACHE_MAX = 256;\n\ntype PreparedAllStatement = Readonly<{\n all: (...params: readonly unknown[]) => readonly unknown[];\n /**\n * Executes a statement that returns no rows. better-sqlite3 and\n * bun:sqlite both expose it; better-sqlite3 additionally REQUIRES it for\n * non-reader statements (`all()` on those throws).\n */\n run?: (...params: readonly unknown[]) => unknown;\n /**\n * better-sqlite3's \"does this statement return rows\" flag. bun:sqlite\n * has no equivalent; `undefined` is treated as non-reader on the run\n * path (bun's `run()` accepts any statement).\n */\n reader?: boolean;\n}>;\n\ntype SqliteClientWithPrepare = Readonly<{\n prepare: (sqlText: string) => PreparedAllStatement;\n}>;\n\ntype SqliteClientCarrier = Readonly<{ $client?: unknown }>;\n\ntype DurableObjectSqlApi = Readonly<{\n exec: (...args: readonly unknown[]) => unknown;\n}>;\n\n/**\n * Runtime shape of the Durable Object storage client exposed as\n * `drizzle(ctx.storage).$client`. Structural because Drizzle does not export\n * this client type and constructor names are not stable under bundling.\n */\nexport type DurableObjectStorageClient = Readonly<{\n sql: DurableObjectSqlApi;\n transaction: <Result>(run: () => Promise<Result>) => Promise<Result>;\n transactionSync: <Result>(run: () => Result) => Result;\n}>;\n\ntype SqliteHostedPlatform = \"d1\" | \"durable-object\";\n\ntype SessionLike = Readonly<{\n constructor?: Readonly<{\n name?: string;\n }>;\n}>;\n\ntype DatabaseWithSession = Readonly<{\n _?: Readonly<{\n session?: SessionLike;\n }>;\n session?: SessionLike;\n}>;\n\n/**\n * Controls how the backend manages SQLite transactions.\n *\n * - `\"sql\"`: TypeGraph issues BEGIN / COMMIT / ROLLBACK SQL directly on\n * the connection. Default for sync drivers (better-sqlite3,\n * bun:sqlite); also selected by `createLibsqlBackend` for\n * local `@libsql/client` connections (`file:` / `:memory:`),\n * whose `client.transaction()` permanently abandons the\n * current connection — fatal for an in-memory database.\n * - `\"drizzle\"`: Delegates to Drizzle's `db.transaction()` method.\n * Default for async drivers (remote libsql/Turso, sql.js).\n * - `\"do-sqlite\"`: Delegates to the Cloudflare Durable Objects async\n * storage transaction runner (`db.$client.transaction`,\n * i.e. `ctx.storage.transaction(async ...)`). Drizzle's\n * own `db.transaction()` on DO is\n * `ctx.storage.transactionSync` and cannot span `await`,\n * so it is deliberately not used. Auto-detected for\n * `drizzle(ctx.storage)` (#140).\n * - `\"none\"`: Transactions disabled. Default for Cloudflare D1\n * (`D1Database.batch` is transactional but not an\n * interactive runner — tracked separately).\n */\nexport type SqliteTransactionMode = \"sql\" | \"drizzle\" | \"none\" | \"do-sqlite\";\n\nexport type SqliteExecutionProfileHints = Readonly<{\n isSync?: boolean;\n transactionMode?: SqliteTransactionMode;\n}>;\n\ntype SqliteExecutionAdapterOptions = Readonly<{\n profileHints?: SqliteExecutionProfileHints;\n statementCacheMax?: number;\n}>;\n\nexport type AnySqliteDatabase = BaseSQLiteDatabase<\"sync\" | \"async\", unknown>;\n\nexport type SqliteExecutionProfile = Readonly<{\n /** Hosted runtime detected independently of caller-supplied hints. */\n hostedPlatform?: SqliteHostedPlatform;\n /** Platform ceiling that capability overrides may lower but never raise. */\n hardMaxBindParameters?: number;\n isSync: boolean;\n /**\n * Detected per-statement bound-parameter ceiling for this connection:\n * Cloudflare's documented D1 / Durable Objects cap, the probed\n * `SQLITE_MAX_VARIABLE_NUMBER` on synchronous drivers, or the conservative\n * 999 floor when the limit cannot be probed (async/remote drivers).\n */\n maxBindParameters: number;\n supportsCompiledExecution: boolean;\n transactionMode: SqliteTransactionMode;\n}>;\n\nexport type SqliteExecutionAdapter = Readonly<\n SqlExecutionAdapter & {\n clearStatementCache: () => void;\n profile: SqliteExecutionProfile;\n /**\n * Executes a compiled statement that returns no rows through the\n * prepared-statement cache. Present only on synchronous drivers with a\n * preparable client — the CRUD write path falls back to drizzle's\n * `db.run()` when absent.\n */\n executeCompiledRun?: (compiledQuery: CompiledSqlQuery) => Promise<void>;\n /** Rebinds one cached non-reader statement for every parameter row. */\n executePreparedRunBatch?: (\n sqlText: string,\n params: readonly (readonly unknown[])[],\n ) => Promise<void>;\n }\n>;\n\nfunction getSessionName(db: AnySqliteDatabase): string | undefined {\n const databaseWithSession = db as DatabaseWithSession;\n const primarySessionName = databaseWithSession.session?.constructor?.name;\n if (primarySessionName !== undefined) {\n return primarySessionName;\n }\n\n return databaseWithSession._?.session?.constructor?.name;\n}\n\nfunction isD1DatabaseBySessionName(db: AnySqliteDatabase): boolean {\n return getSessionName(db) === \"SQLiteD1Session\";\n}\n\nfunction isDurableObjectBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n // drizzle-orm/durable-sqlite's session class is `SQLiteDOSession`\n // (verified drizzle 0.45.x). `SQLiteDurableObjectSession` is kept as\n // a defensive alias against future drizzle renames.\n return (\n sessionName === \"SQLiteDOSession\" ||\n sessionName === \"SQLiteDurableObjectSession\"\n );\n}\n\nfunction isDurableObjectStorageClient(\n value: unknown,\n): value is DurableObjectStorageClient {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as Record<string, unknown>;\n const sqlApi = candidate[\"sql\"];\n return (\n typeof candidate[\"transaction\"] === \"function\" &&\n typeof candidate[\"transactionSync\"] === \"function\" &&\n typeof sqlApi === \"object\" &&\n sqlApi !== null &&\n typeof (sqlApi as Record<string, unknown>)[\"exec\"] === \"function\"\n );\n}\n\n/**\n * Returns the real Durable Object storage client when the Drizzle connection\n * exposes its distinctive async + sync transaction runners and SQL API.\n * Requiring the full shape avoids mistaking better-sqlite3's transaction\n * wrapper factory for the Durable Object async runner.\n */\nexport function getDurableObjectStorageClient(\n db: AnySqliteDatabase,\n): DurableObjectStorageClient | undefined {\n const client = (db as SqliteClientCarrier).$client;\n return isDurableObjectStorageClient(client) ? client : undefined;\n}\n\nfunction detectHostedPlatform(\n db: AnySqliteDatabase,\n): SqliteHostedPlatform | undefined {\n if (\n getDurableObjectStorageClient(db) !== undefined ||\n isDurableObjectBySessionName(db)\n ) {\n return \"durable-object\";\n }\n if (isD1DatabaseBySessionName(db)) return \"d1\";\n return undefined;\n}\n\nfunction isSyncDatabaseBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n return (\n sessionName === \"BetterSQLiteSession\" || sessionName === \"BunSQLiteSession\"\n );\n}\n\nfunction detectSyncProfile(\n db: AnySqliteDatabase,\n profileHints: SqliteExecutionProfileHints,\n hostedPlatform: SqliteHostedPlatform | undefined,\n): boolean {\n if (hostedPlatform === \"durable-object\") return true;\n if (hostedPlatform === \"d1\") return false;\n if (profileHints.isSync !== undefined) {\n return profileHints.isSync;\n }\n\n const sessionName = getSessionName(db);\n if (\n sessionName === \"BetterSQLiteSession\" ||\n sessionName === \"BunSQLiteSession\"\n ) {\n return true;\n }\n\n try {\n const probeResult = db.get(sql`SELECT 1 AS __typegraph_sync_probe__`);\n return !(probeResult instanceof Promise);\n } catch {\n return isSyncDatabaseBySessionName(db);\n }\n}\n\nfunction detectTransactionMode(\n profileHints: SqliteExecutionProfileHints,\n isSync: boolean,\n hostedPlatform: SqliteHostedPlatform | undefined,\n): SqliteTransactionMode {\n // Hosted platform identity is authoritative. A stale hint must not disable\n // Durable Object rollback or opt D1 into unsupported interactive writes.\n if (hostedPlatform === \"durable-object\") return \"do-sqlite\";\n if (hostedPlatform === \"d1\") return \"none\";\n if (profileHints.transactionMode !== undefined) {\n return profileHints.transactionMode;\n }\n // Neither D1 nor Durable Object SQLite supports raw BEGIN/COMMIT SQL\n // through Drizzle's db.run(), and Drizzle's own db.transaction() on\n // Durable Objects is `ctx.storage.transactionSync` (cannot span an\n // await). Durable Objects expose an async storage transaction runner\n // (`ctx.storage.transaction(async ...)`, surfaced by Drizzle as\n // `db.$client.transaction`) — route those through \"do-sqlite\" (#140).\n // D1 has no equivalent interactive runner (only batch); it stays\n // \"none\" pending a separate batch-mode investigation.\n if (isSync) return \"sql\";\n return \"drizzle\";\n}\n\n// SQLITE_MAX_VARIABLE_NUMBER's compiled-in default rose from 999 to 32,766\n// in SQLite 3.32.0. Builds that override the default list it in\n// `PRAGMA compile_options`; builds that keep it do not, so the version\n// decides the fallback.\nconst MAX_VARIABLE_NUMBER_COMPILE_OPTION = /^MAX_VARIABLE_NUMBER=(\\d+)$/;\nconst FIRST_MODERN_BIND_LIMIT_MAJOR = 3;\nconst FIRST_MODERN_BIND_LIMIT_MINOR = 32;\n\nfunction parseCompiledMaxVariableNumber(\n rows: readonly unknown[],\n): number | undefined {\n for (const row of rows) {\n if (typeof row !== \"object\" || row === null) continue;\n const option = (row as Record<string, unknown>)[\"compile_options\"];\n if (typeof option !== \"string\") continue;\n const match = MAX_VARIABLE_NUMBER_COMPILE_OPTION.exec(option);\n if (match !== null) return Number(match[1]);\n }\n return undefined;\n}\n\nfunction hasModernBindLimitByVersion(rows: readonly unknown[]): boolean {\n const first = rows[0];\n if (typeof first !== \"object\" || first === null) return false;\n const version = (first as Record<string, unknown>)[\"version\"];\n if (typeof version !== \"string\") return false;\n const [major = 0, minor = 0] = version.split(\".\").map(Number);\n if (!Number.isFinite(major) || !Number.isFinite(minor)) return false;\n return (\n major > FIRST_MODERN_BIND_LIMIT_MAJOR ||\n (major === FIRST_MODERN_BIND_LIMIT_MAJOR &&\n minor >= FIRST_MODERN_BIND_LIMIT_MINOR)\n );\n}\n\n/**\n * Resolves the connection's per-statement bound-parameter ceiling. Batch\n * chunk math derives from this value, so too high breaks batched writes at\n * runtime and too low wastes round trips (999 vs 32,766 is ~33× more\n * chunks per bulk insert).\n */\nfunction detectHardMaxBindParameters(\n transactionMode: SqliteTransactionMode,\n hostedPlatform: SqliteHostedPlatform | undefined,\n): number | undefined {\n if (hostedPlatform === \"durable-object\" || transactionMode === \"do-sqlite\") {\n return DURABLE_OBJECT_MAX_BIND_PARAMETERS;\n }\n if (hostedPlatform === \"d1\") return D1_MAX_BIND_PARAMETERS;\n return undefined;\n}\n\nfunction detectMaxBindParameters(\n sqliteClient: SqliteClientWithPrepare | undefined,\n hardMaxBindParameters: number | undefined,\n): number {\n if (hardMaxBindParameters !== undefined) return hardMaxBindParameters;\n if (sqliteClient === undefined) return SQLITE_MAX_BIND_PARAMETERS;\n try {\n const compiled = parseCompiledMaxVariableNumber(\n sqliteClient.prepare(\"PRAGMA compile_options\").all(),\n );\n if (compiled !== undefined) return compiled;\n const isModern = hasModernBindLimitByVersion(\n sqliteClient.prepare(\"SELECT sqlite_version() AS version\").all(),\n );\n return isModern ?\n MODERN_SQLITE_MAX_BIND_PARAMETERS\n : SQLITE_MAX_BIND_PARAMETERS;\n } catch {\n // A client that can't answer the probes keeps the conservative floor.\n return SQLITE_MAX_BIND_PARAMETERS;\n }\n}\n\n/**\n * The single spelling of \"this object prepares statements\": returns it as a\n * property bag when it does, `undefined` otherwise. Every driver predicate\n * below and {@link resolveSqliteClient} read it, so \"prepare-capable\" cannot\n * drift between the execution path and the serialized-resource marking.\n */\nfunction preparingClient(\n client: unknown,\n): Readonly<Record<string, unknown>> | undefined {\n if (typeof client !== \"object\" || client === null) return undefined;\n const candidate = client as Readonly<Record<string, unknown>>;\n return typeof candidate[\"prepare\"] === \"function\" ? candidate : undefined;\n}\n\n/** Whether every named member of `client` is a function. */\nfunction hasMethods(\n client: Readonly<Record<string, unknown>>,\n methods: readonly string[],\n): boolean {\n return methods.every((method) => typeof client[method] === \"function\");\n}\n\n/**\n * Whether a driver client is better-sqlite3's `Database`.\n *\n * `pragma` is the discriminator: better-sqlite3 exposes it as a method, and\n * none of the other prepare-capable SQLite clients (bun:sqlite, sql.js,\n * node:sqlite) has any counterpart. Duck-typed rather than `instanceof`, so\n * the native addon is never imported by this bundler-friendly module.\n */\nexport function isBetterSqlite3Client(client: unknown): boolean {\n const candidate = preparingClient(client);\n return candidate !== undefined && hasMethods(candidate, [\"pragma\"]);\n}\n\n/**\n * Whether a driver client is a `bun:sqlite` `Database` — what\n * `drizzle-orm/bun-sqlite` exposes as `$client`.\n *\n * ONE synchronous connection: every statement from every wrapper over it runs\n * on it, in order, exactly like better-sqlite3.\n *\n * Structural, never the session's constructor name (which bundlers rename):\n * verified against `bun-types` 1.3.x `bun:sqlite`, a `Database` carries\n * `query` (the cached-statement factory better-sqlite3 does not have),\n * `prepare`, `run`/`exec`, `serialize`, and a `filename` string — where\n * better-sqlite3 names that property `name` and sql.js has neither. The\n * combination is not satisfied by any other client this package can meet.\n */\nexport function isBunSqliteClient(client: unknown): boolean {\n const candidate = preparingClient(client);\n return (\n candidate !== undefined &&\n hasMethods(candidate, [\"query\", \"run\", \"exec\", \"serialize\"]) &&\n typeof candidate[\"filename\"] === \"string\"\n );\n}\n\n/**\n * Whether a driver client is a `sql.js` `Database` — what\n * `drizzle-orm/sql-js` takes as its client.\n *\n * ONE in-WASM database handle, executed synchronously in-process, so two\n * wrappers over it serialize exactly as two wrappers over one better-sqlite3\n * handle do.\n *\n * Structural evidence (verified against `@types/sql.js` 1.4.x): `export`\n * (dump the database to bytes) and `getRowsModified` are sql.js's own API and\n * exist on no other SQLite client — better-sqlite3 and bun:sqlite spell the\n * dump `serialize` and have no rows-modified method at all — alongside the\n * `prepare`/`exec`/`run` trio every driver has.\n */\nexport function isSqlJsClient(client: unknown): boolean {\n const candidate = preparingClient(client);\n return (\n candidate !== undefined &&\n hasMethods(candidate, [\"exec\", \"run\", \"export\", \"getRowsModified\"])\n );\n}\n\n/**\n * Returns the driver client a Drizzle SQLite database prepares statements on\n * for TypeGraph's COMPILED execution path, or `undefined` when it has none it\n * can drive.\n *\n * sql.js is excluded deliberately: its `prepare` returns a sql.js `Statement`\n * (`bind`/`step`/`getAsObject`/`free`) with no `all()`, so the compiled path's\n * `prepared.all(...params)` would throw on the first statement. Drizzle's own\n * sql-js session drives that statement shape correctly, so an excluded client\n * falls back to the Drizzle path and works instead of failing — the abstention\n * is what makes the advertised sql.js support real. Every other\n * prepare-capable client returns statements with `all()` (better-sqlite3,\n * bun:sqlite).\n */\nfunction resolveSqliteClient(\n db: AnySqliteDatabase,\n): SqliteClientWithPrepare | undefined {\n const sqliteClient = (db as SqliteClientCarrier).$client;\n if (preparingClient(sqliteClient) === undefined) return;\n if (isSqlJsClient(sqliteClient)) return;\n return sqliteClient as SqliteClientWithPrepare;\n}\n\nfunction getOrCreatePreparedStatement(\n cache: Map<string, PreparedAllStatement>,\n sqliteClient: SqliteClientWithPrepare,\n sqlText: string,\n cacheMax: number,\n): PreparedAllStatement {\n return getOrCreateLru(cache, sqlText, cacheMax, () =>\n sqliteClient.prepare(sqlText),\n );\n}\n\n// Uses unconditional `await` because Drizzle returns SQLiteRaw thenables\n// that fail `instanceof Promise` checks (drizzle-team/drizzle-orm#2275).\nasync function executeDrizzleQuery<TRow>(\n db: AnySqliteDatabase,\n query: DrizzleSql,\n): Promise<readonly TRow[]> {\n return await db.all(query);\n}\n\nfunction createPreparedStatementExecutor(\n sqliteClient: SqliteClientWithPrepare,\n cache: Map<string, PreparedAllStatement>,\n sqlText: string,\n cacheMax: number,\n): PreparedSqlStatement {\n return {\n execute<TRow>(params: readonly unknown[]): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n cache,\n sqliteClient,\n sqlText,\n cacheMax,\n );\n const rows = preparedStatement.all(...params);\n return Promise.resolve(rows as readonly TRow[]);\n },\n };\n}\n\nexport function createSqliteExecutionAdapter(\n db: AnySqliteDatabase,\n statementCacheMaxOrOptions: number | SqliteExecutionAdapterOptions = {},\n): SqliteExecutionAdapter {\n const options: SqliteExecutionAdapterOptions =\n typeof statementCacheMaxOrOptions === \"number\" ?\n { statementCacheMax: statementCacheMaxOrOptions }\n : statementCacheMaxOrOptions;\n const statementCacheMax =\n options.statementCacheMax ?? DEFAULT_PREPARED_STATEMENT_CACHE_MAX;\n const profileHints = options.profileHints ?? {};\n\n const hostedPlatform = detectHostedPlatform(db);\n const isSync = detectSyncProfile(db, profileHints, hostedPlatform);\n const sqliteClient = isSync ? resolveSqliteClient(db) : undefined;\n const transactionMode = detectTransactionMode(\n profileHints,\n isSync,\n hostedPlatform,\n );\n const hardMaxBindParameters = detectHardMaxBindParameters(\n transactionMode,\n hostedPlatform,\n );\n const maxBindParameters = detectMaxBindParameters(\n sqliteClient,\n hardMaxBindParameters,\n );\n\n const profile: SqliteExecutionProfile = {\n ...(hostedPlatform === undefined ? {} : { hostedPlatform }),\n ...(hardMaxBindParameters === undefined ? {} : { hardMaxBindParameters }),\n isSync,\n maxBindParameters,\n supportsCompiledExecution: sqliteClient !== undefined,\n transactionMode,\n };\n\n const compile = (query: ExecutableSql): CompiledSqlQuery =>\n compileQueryWithDialect(db, query, \"SQLite\");\n\n if (sqliteClient !== undefined) {\n const client = sqliteClient;\n const statementCache = new Map<string, PreparedAllStatement>();\n\n function executeCompiled<TRow>(\n compiledQuery: CompiledSqlQuery,\n ): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n compiledQuery.sql,\n statementCacheMax,\n );\n const rows = preparedStatement.all(...compiledQuery.params);\n return Promise.resolve(rows as readonly TRow[]);\n }\n\n function executeCompiledRun(\n compiledQuery: CompiledSqlQuery,\n ): Promise<void> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n compiledQuery.sql,\n statementCacheMax,\n );\n // better-sqlite3 rejects run() on reader statements and all() on\n // non-reader statements, so pick by the statement's own flag; a\n // client without run() (or without the reader flag but returning\n // rows) drains through all() and discards.\n if (\n preparedStatement.run === undefined ||\n preparedStatement.reader === true\n ) {\n preparedStatement.all(...compiledQuery.params);\n } else {\n preparedStatement.run(...compiledQuery.params);\n }\n return Promise.resolve();\n }\n\n function executePreparedRunBatch(\n sqlText: string,\n parameterRows: readonly (readonly unknown[])[],\n ): Promise<void> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n sqlText,\n statementCacheMax,\n );\n if (preparedStatement.run === undefined) {\n throw new Error(\n \"Trusted SQLite import requires a prepared statement run() method.\",\n );\n }\n for (const params of parameterRows) {\n preparedStatement.run(...params);\n }\n return Promise.resolve();\n }\n\n return {\n clearStatementCache() {\n statementCache.clear();\n },\n compile,\n execute<TRow>(query: ExecutableSql): Promise<readonly TRow[]> {\n const compiledQuery = compile(query);\n return executeCompiled<TRow>(compiledQuery);\n },\n executeCompiled,\n executeCompiledRun,\n executePreparedRunBatch,\n prepare(sqlText: string): PreparedSqlStatement {\n return createPreparedStatementExecutor(\n client,\n statementCache,\n sqlText,\n statementCacheMax,\n );\n },\n profile,\n };\n }\n\n return {\n clearStatementCache() {\n // No-op: no statement cache in async/D1 mode\n },\n compile,\n execute<TRow>(query: ExecutableSql): Promise<readonly TRow[]> {\n return executeDrizzleQuery<TRow>(\n db,\n isSqlFragment(query) ? toDrizzleSql(query, \"sqlite\") : query,\n );\n },\n profile,\n };\n}\n","/**\n * SQLite backend adapter for TypeGraph.\n *\n * Works with any Drizzle SQLite database instance:\n * - better-sqlite3\n * - libsql / Turso\n * - Cloudflare D1\n * - bun:sqlite\n * - sql.js\n *\n * @example\n * ```typescript\n * import { drizzle } from \"drizzle-orm/better-sqlite3\";\n * import Database from \"better-sqlite3\";\n * import { createSqliteBackend, tables } from \"@nicia-ai/typegraph/adapters/drizzle/sqlite\";\n *\n * const sqlite = new Database(\"app.db\");\n * const db = drizzle(sqlite);\n * const backend = createSqliteBackend(db, { tables });\n * ```\n */\nimport {\n and,\n eq,\n getTableName,\n inArray,\n isNull,\n type SQL,\n sql,\n} from \"drizzle-orm\";\nimport { BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport { BackendDisposedError, ConfigurationError } from \"../../errors\";\nimport type { ResolvedSqlTableNames } from \"../../query/compiler/schema\";\nimport {\n buildFulltextCapabilities,\n fts5Strategy,\n type FulltextStrategy,\n} from \"../../query/dialect/fulltext-strategy\";\nimport {\n assertVectorSearchLimit,\n buildVectorCapabilities,\n resolveEfSearchOverride,\n vectorSearchFrontierTuning,\n type VectorSlot,\n type VectorStrategy,\n} from \"../../query/dialect/vector-strategy\";\nimport {\n isSqlFragment,\n sql as portableSql,\n type SqlFragment,\n} from \"../../query/sql-fragment\";\nimport { type CompiledRowsSql } from \"../../query/sql-intent\";\nimport { chunk as chunkArray } from \"../../utils/array\";\nimport { requireDefined } from \"../../utils/presence\";\nimport {\n isMissingTableError,\n isSqliteNotAuthorizedError,\n} from \"../../utils/sql-errors\";\nimport { FIND_EDGES_ENDPOINT_FIXED_PARAM_COUNT } from \"../edge-endpoint-sets\";\nimport { buildLiveNodeCandidates } from \"../live-node-candidates\";\nimport {\n type AdapterBackend,\n type BackendCapabilities,\n type CommitSchemaVersionIfKindsEmptyResult,\n type CommitSchemaVersionParams,\n type ContributionDiagnostic,\n type ContributionMaterializationIdentity,\n type ContributionMaterializationRow,\n type ContributionProbeEntry,\n type ContributionRebuildResult,\n type ContributionRebuildScope,\n type ContributionRepairResult,\n type ContributionRepopulationStats,\n type CreateVectorIndexParams,\n type DeleteEmbeddingParams,\n type DeleteFulltextBatchParams,\n type DeleteFulltextParams,\n type DropVectorIndexParams,\n type FulltextSearchParams,\n type FulltextSearchResult,\n type GraphAnalyticsCapabilities,\n type GraphBackend,\n type HybridSearchParams,\n type HybridSearchRow,\n type IdentityTableNames,\n type IndexMaterializationRow,\n INTERNAL_TEMPORARY_WRITES,\n type InternalTransactionOptions,\n type KindRemovalRow,\n type LockSchemaVersionForWriteParams,\n normalizeGraphAnalyticsCapabilities,\n type RecordContributionMaterializationParams,\n type RecordIndexMaterializationParams,\n type RecordKindRemovalParams,\n type SchemaKindEmptinessProbe,\n type SchemaVersionRow,\n type SchemaWriteTransactionBackend,\n type SetActiveVersionParams,\n SQLITE_CAPABILITIES,\n SQLITE_MAX_BIND_PARAMETERS,\n type TransactionBackend,\n type TrustedImportOptions,\n type TrustedImportSession,\n type UpsertEmbeddingBatchParams,\n type UpsertEmbeddingParams,\n type UpsertFulltextBatchParams,\n type UpsertFulltextParams,\n type VectorSearchParams,\n type VectorSearchResult,\n} from \"../types\";\nimport {\n type AnySqliteDatabase,\n createSqliteExecutionAdapter,\n getDurableObjectStorageClient,\n isBetterSqlite3Client,\n isBunSqliteClient,\n isSqlJsClient,\n type SqliteExecutionAdapter,\n type SqliteExecutionProfile,\n type SqliteExecutionProfileHints,\n} from \"./execution/sqlite-execution\";\nimport { type ExecutableSql, toDrizzleSql } from \"./execution/types\";\nimport {\n EMBEDDING_UPSERT_PARAM_COUNT,\n mapVectorWriteError,\n vectorSlotFromCreateIndexParams,\n vectorSlotFromDropIndexParams,\n vectorSlotFromParams,\n} from \"./vector-runtime\";\nexport type { SqliteTransactionMode } from \"./execution/sqlite-execution\";\nimport {\n coerceNumericScore,\n createEdgeRowMapper,\n createNodeRowMapper,\n createSchemaVersionRowMapper,\n createUniqueRowMapper,\n nowIso,\n SQLITE_ROW_MAPPER_CONFIG,\n} from \"../row-mappers\";\nimport {\n auditBackendResource,\n resolveDeclaredBackendResource,\n type SerializedResourceDeclaration,\n} from \"../transaction-resource\";\nimport {\n buildContributionInsertValues,\n buildContributionOnConflictSet,\n type ContributionMaterializer,\n contributionRebuildSupported,\n createContributionMaterializer,\n gateFulltext,\n gateFulltextMethods,\n mapContributionMaterializationRow,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS,\n} from \"./contribution-materializations\";\nimport {\n generateSqliteCreateTableSQL,\n generateSqliteDDL,\n sqliteContributions,\n} from \"./ddl\";\nimport {\n buildMaterializationInsertValues,\n buildMaterializationOnConflictSet,\n mapMaterializationRow,\n SQLITE_INDEX_MAT_TIMESTAMPS,\n} from \"./index-materializations\";\nimport {\n buildKindRemovalInsertValues,\n buildKindRemovalOnConflictSet,\n mapKindRemovalRow,\n SQLITE_KIND_REMOVAL_TIMESTAMPS,\n} from \"./kind-removals\";\nimport {\n assertActiveSchemaVersion,\n assertAdoptedDialect,\n commitSchemaVersionIfKindsEmpty,\n createCommonOperationBackend,\n type InternalOperationBackend,\n} from \"./operation-backend-core\";\nimport { mapHybridSearchRow } from \"./operations/hybrid\";\nimport {\n createSqliteOperationStrategy,\n tableExistsFromRow,\n} from \"./operations/strategy\";\nimport {\n createSqliteTables as buildSqliteTables,\n type SqliteTables,\n tables as defaultTables,\n} from \"./schema/sqlite\";\nimport {\n analyzeImportedTables,\n assertTrustedImportDatabaseEmpty,\n createSqliteTrustedImportSession,\n restoreSecondaryIndexes,\n suspendSqliteSecondaryIndexes,\n} from \"./trusted-import\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a SQLite backend.\n */\nexport type SqliteBackendOptions = Readonly<{\n /**\n * Custom table definitions. Use createSqliteTables() to customize table names.\n * Defaults to standard TypeGraph table names.\n */\n tables?: SqliteTables;\n /**\n * Optional execution profile hints used to avoid runtime driver reflection.\n * Set `transactionMode: \"none\"` for drivers without transactions (e.g.\n * Cloudflare D1). Durable Objects (`drizzle(ctx.storage)`) auto-detect\n * `transactionMode: \"do-sqlite\"` and do not need a hint. Hosted platform\n * identity is authoritative when it conflicts with a stale hint.\n */\n executionProfile?: SqliteExecutionProfileHints;\n /**\n * Fulltext strategy override. Defaults to `fts5Strategy` (SQLite's\n * built-in FTS5 virtual table). Most users should leave this alone.\n */\n fulltext?: FulltextStrategy;\n /**\n * Vector strategy override. When present, the backend owns per-`(kind,\n * field)` typed storage through this strategy (DDL, upsert, delete,\n * similarity search, ANN index lifecycle) and advertises\n * `strategy.capabilities` as `capabilities.vector`. `createLibsqlBackend`\n * passes `libsqlVectorStrategy` unconditionally; `createLocalSqliteBackend`\n * passes `sqliteVecStrategy` when the extension loads. When absent the\n * backend exposes no vector capability and embedding values pass through\n * writes without being indexed — matching existing behavior for SQLite\n * connections without a vector extension.\n */\n vector?: VectorStrategy;\n /**\n * Override specific backend capabilities. Useful for custom SQLite builds\n * or tests that need to simulate an engine-level capability gap. Overrides\n * may lower, but cannot raise, a hosted platform's hard parameter ceiling.\n */\n capabilities?: Partial<BackendCapabilities>;\n /**\n * Declare the connection this backend serializes every statement onto, when\n * TypeGraph's driver predicates cannot see it (`expo-sqlite`, `op-sqlite`,\n * `sqlite-proxy`, a bespoke adapter) — or declare that it serializes on\n * nothing, when detection is wrong for your topology.\n *\n * Defaults to `{ mode: \"detect\" }`. See\n * {@link SerializedResourceDeclaration} for what each mode means and for the\n * one refusal it cannot lift (`same-sqlite-backend`: one backend object\n * exporting into itself).\n */\n serializedResource?: SerializedResourceDeclaration;\n}>;\n\nconst NODE_INSERT_PARAM_COUNT = 9;\nconst EDGE_INSERT_PARAM_COUNT = 12;\nconst GET_NODES_FIXED_PARAM_COUNT = 2;\nconst GET_EDGES_FIXED_PARAM_COUNT = 1;\nconst CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT = 3;\nconst FULLTEXT_UPSERT_PARAM_COUNT = 6;\nconst FULLTEXT_DELETE_FIXED_PARAM_COUNT = 2;\nconst UNIQUE_DELETE_FIXED_PARAM_COUNT = 2;\nconst UNIQUE_INSERT_PARAM_COUNT = 6;\n\n/**\n * `PRAGMA analysis_limit` value `refreshStatistics()` sets before running\n * `ANALYZE`. Unlike Postgres (whose `ANALYZE` always examines a bounded\n * sample sized off `default_statistics_target`), SQLite's `ANALYZE`\n * defaults to a full table/index scan — O(table size) per call. A caller\n * streaming a bulk load through repeated `bulkInsert()` calls (the only\n * practical pattern for a multi-million-row load) re-triggers\n * `refreshStatistics()` on every batch once that batch's row count crosses\n * `AUTO_REFRESH_STATISTICS_ROW_THRESHOLD`; without this bound, per-call\n * cost grows with total table size, integrating to O(n²) total load time.\n * 1000 is SQLite's own documented suggestion for large databases.\n */\nexport const SQLITE_ANALYZE_ROW_LIMIT = 1000;\n\n/**\n * Barrel keys (contribution logical names) of the four relations that hold\n * Operational Identity state: current assertions, recorded-time assertions,\n * the derived closure, and the derived separation relation.\n * `ensureIdentityTables()` scopes its idempotent CREATE TABLE / CREATE INDEX\n * to exactly these when identity is first enabled on an existing database.\n */\nconst IDENTITY_TABLE_LOGICAL_NAMES: ReadonlySet<string> = new Set([\n \"identityAssertions\",\n \"recordedIdentityAssertions\",\n \"identityClosure\",\n \"identitySeparation\",\n]);\n\n/**\n * Batch chunk sizes for the SQLite operation backend, derived from the\n * connection's bound-parameter budget. Keys mirror the operation backend's\n * `batchConfig`.\n */\nexport type SqliteBatchChunkSizes = Readonly<{\n checkUniqueBatchChunkSize: number;\n edgeInsertBatchSize: number;\n /** Rows per embedding batch upsert (5 binds per row). */\n embeddingUpsertBatchSize: number;\n /** Rows per fulltext batch upsert (6 binds per row on FTS5). */\n fulltextUpsertBatchSize: number;\n /** Node ids per fulltext batch delete (2 fixed binds + one per id). */\n fulltextDeleteChunkSize: number;\n /** Endpoint ids per `findEdgesByKind` `fromIds` / `toIds` statement. */\n findEdgesEndpointChunkSize: number;\n getEdgesChunkSize: number;\n getNodesChunkSize: number;\n nodeInsertBatchSize: number;\n /** Node ids per uniqueness-sidecar hard delete. */\n uniqueDeleteChunkSize: number;\n uniqueInsertBatchSize: number;\n}>;\n\n/**\n * Derives batch chunk sizes from a per-statement bound-parameter budget.\n * The budget varies by driver — better-sqlite3 compiles in 32,766, D1 caps\n * at ~100, undetectable async drivers keep the 999 floor — so chunk math is\n * computed per backend instance rather than fixed at module scope.\n */\nexport function computeSqliteBatchChunkSizes(\n maxBindParameters: number,\n): SqliteBatchChunkSizes {\n return {\n checkUniqueBatchChunkSize: Math.max(\n 1,\n maxBindParameters - CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT,\n ),\n embeddingUpsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / EMBEDDING_UPSERT_PARAM_COUNT),\n ),\n fulltextUpsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / FULLTEXT_UPSERT_PARAM_COUNT),\n ),\n fulltextDeleteChunkSize: Math.max(\n 1,\n maxBindParameters - FULLTEXT_DELETE_FIXED_PARAM_COUNT,\n ),\n edgeInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / EDGE_INSERT_PARAM_COUNT),\n ),\n findEdgesEndpointChunkSize: Math.max(\n 1,\n maxBindParameters - FIND_EDGES_ENDPOINT_FIXED_PARAM_COUNT,\n ),\n getEdgesChunkSize: Math.max(\n 1,\n maxBindParameters - GET_EDGES_FIXED_PARAM_COUNT,\n ),\n getNodesChunkSize: Math.max(\n 1,\n maxBindParameters - GET_NODES_FIXED_PARAM_COUNT,\n ),\n nodeInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / NODE_INSERT_PARAM_COUNT),\n ),\n uniqueDeleteChunkSize: Math.max(\n 1,\n maxBindParameters - UNIQUE_DELETE_FIXED_PARAM_COUNT,\n ),\n uniqueInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / UNIQUE_INSERT_PARAM_COUNT),\n ),\n };\n}\n\ntype SerializedExecutionQueue = Readonly<{\n dispose: () => void;\n runExclusive: <T>(task: () => Promise<T>) => Promise<T>;\n}>;\n\n// ============================================================\n// Utilities\n// ============================================================\n\nconst toNodeRow = createNodeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toEdgeRow = createEdgeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toUniqueRow = createUniqueRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toSchemaVersionRow = createSchemaVersionRowMapper(\n SQLITE_ROW_MAPPER_CONFIG,\n);\n\n/** A shared promise that never settles — used to absorb post-dispose work. */\nconst PENDING_FOREVER: Promise<never> = new Promise<never>(noop);\n\nfunction pendingForever<T>(): Promise<T> {\n return PENDING_FOREVER;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noop(): void {}\n\n/**\n * Tracks which serialized queue (if any) the current async execution is\n * running a task for, so a re-entrant submission — a root-backend operation\n * awaited from inside a transaction already occupying the same queue — can be\n * rejected with a typed error instead of deadlocking (the enclosing task holds\n * the queue slot until it completes, so the inner operation can never run).\n *\n * AsyncLocalStorage is loaded lazily and optionally: it is available on Node\n * and on Cloudflare workers with the `nodejs_als` compatibility flag, and a\n * runtime without it simply skips the detection (the queue behaves as before).\n */\ntype QueueTaskContext = Readonly<{\n getStore: () => unknown;\n run: <T>(store: object, callback: () => T) => T;\n}>;\n\nlet queueTaskContext: QueueTaskContext | undefined;\n\nasync function loadQueueTaskContext(): Promise<void> {\n try {\n const asyncHooks = await import(\"node:async_hooks\");\n queueTaskContext = new asyncHooks.AsyncLocalStorage<object>();\n } catch {\n // AsyncLocalStorage unavailable on this runtime: re-entrant submissions\n // stay undetected, matching the queue's previous behavior.\n }\n}\n\n// eslint-disable-next-line unicorn/prefer-top-level-await -- the dual CJS/ESM build cannot use top-level await\nvoid loadQueueTaskContext();\n\nfunction rejectReentrantQueueSubmission(): Promise<never> {\n return Promise.reject(\n new ConfigurationError(\n \"This operation was awaited from inside a transaction running on the \" +\n \"same SQLite backend and would deadlock: the transaction holds the \" +\n \"backend's serialized execution slot until it completes, so the \" +\n \"operation could never run.\",\n { backend: \"sqlite\", capability: \"concurrentRootAccess\" },\n {\n suggestion:\n \"Inside a store.transaction callback, use the transaction-scoped \" +\n \"context (tx.nodes / tx.edges / tx.backend) instead of the root \" +\n \"store or backend, or move the operation outside the transaction.\",\n },\n ),\n );\n}\n\nfunction createSerializedExecutionQueue(): SerializedExecutionQueue {\n let tail: Promise<unknown> = Promise.resolve();\n let disposed = false;\n // Unique per queue: a task running on THIS queue must not submit back to it,\n // but may freely submit to a different backend's queue.\n const taskMarker: object = {};\n\n function isDisposed(): boolean {\n return disposed;\n }\n\n return {\n dispose() {\n disposed = true;\n },\n\n runExclusive<T>(task: () => Promise<T>): Promise<T> {\n if (isDisposed()) return Promise.reject(new BackendDisposedError());\n if (queueTaskContext?.getStore() === taskMarker) {\n return rejectReentrantQueueSubmission();\n }\n\n // When disposed, runTask returns a never-settling promise so that no\n // rejection propagates through the 7+ async wrappers between this\n // queue and the store-level caller. A rejection here would become an\n // unhandled rejection if the caller abandoned the promise during\n // teardown — and JavaScript offers no way to `.catch()` a rejection\n // at the bottom of a chain without every async wrapper above it also\n // creating an independently-unhandled rejected promise.\n //\n // The tradeoff: an active caller whose operation was queued before\n // dispose() will see a permanently-pending promise rather than a\n // BackendDisposedError. Post-dispose submissions (the check above)\n // still reject immediately since the caller actively holds that\n // promise.\n const runTask = async (): Promise<T> => {\n if (isDisposed()) return pendingForever<T>();\n try {\n const context = queueTaskContext;\n return context === undefined ?\n await task()\n : await context.run(taskMarker, () => task());\n } catch (error) {\n if (isDisposed()) return pendingForever<T>();\n throw error;\n }\n };\n const result = tail.then(runTask, runTask);\n tail = result.then(\n () => 0,\n () => 0,\n );\n return result;\n },\n };\n}\n\nfunction runWithSerializedQueue<T>(\n queue: SerializedExecutionQueue | undefined,\n task: () => Promise<T>,\n): Promise<T> {\n if (queue === undefined) return task();\n return queue.runExclusive(task);\n}\n\n/** Every SQLite \"atomic transactions unavailable\" refusal shares this shape. */\nfunction throwSqliteTransactionsDisabled(message: string): never {\n throw new ConfigurationError(message, {\n backend: \"sqlite\",\n capability: \"transactions\",\n supportsTransactions: false,\n });\n}\n\nfunction buildSqliteCapabilities(\n options: Readonly<{\n fulltextStrategy: FulltextStrategy;\n vectorStrategy: VectorStrategy | undefined;\n transactionMode: SqliteExecutionAdapter[\"profile\"][\"transactionMode\"];\n maxBindParameters: number;\n }>,\n): BackendCapabilities {\n const base =\n options.transactionMode === \"none\" ?\n {\n ...SQLITE_CAPABILITIES,\n transactions: false,\n graphAnalytics: {\n ...(SQLITE_CAPABILITIES.graphAnalytics ?? {\n mathFunctions: false,\n }),\n supported: false,\n },\n }\n : SQLITE_CAPABILITIES;\n return {\n ...base,\n maxBindParameters: options.maxBindParameters,\n fulltext: buildFulltextCapabilities(options.fulltextStrategy),\n ...(options.vectorStrategy === undefined ?\n {}\n : { vector: buildVectorCapabilities(options.vectorStrategy) }),\n };\n}\n\nfunction resolveMaxBindParametersCapability(\n profile: SqliteExecutionProfile,\n override: number | undefined,\n): number {\n const requested = override ?? profile.maxBindParameters;\n return profile.hardMaxBindParameters === undefined ?\n requested\n : Math.min(requested, profile.hardMaxBindParameters);\n}\n\nfunction resolveSqliteGraphAnalyticsCapabilities(\n profile: SqliteExecutionProfile,\n override: GraphAnalyticsCapabilities | undefined,\n): GraphAnalyticsCapabilities {\n const requested = override ??\n SQLITE_CAPABILITIES.graphAnalytics ?? {\n supported: false,\n mathFunctions: false,\n };\n if (\n profile.transactionMode !== \"do-sqlite\" &&\n profile.transactionMode !== \"none\"\n ) {\n return requested;\n }\n return { ...requested, supported: false };\n}\n\n// ============================================================\n// Backend Factory\n// ============================================================\n\n/**\n * Creates a TypeGraph backend for SQLite databases.\n *\n * Works with any Drizzle SQLite instance regardless of the underlying driver.\n *\n * @param db - A Drizzle SQLite database instance\n * @param options - Backend configuration\n * @returns A GraphBackend implementation\n */\ntype CreateSqliteOperationBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n serializedQueue?: SerializedExecutionQueue;\n tableNames: ResolvedSqlTableNames;\n fulltextStrategy: FulltextStrategy;\n /**\n * Active vector strategy, or `undefined` when the connection has no\n * vector extension. When present, the backend exposes upsertEmbedding /\n * deleteEmbedding / vectorSearch / createVectorIndex / dropVectorIndex,\n * all routed through this strategy's per-`(kind, field)` storage.\n */\n vectorStrategy?: VectorStrategy | undefined;\n /**\n * Shared durable-marker materializer. The vector methods assert a\n * slot's marker (SELECT, never DDL) on the hot path and `createVectorIndex`\n * ensures it (privileged) — replacing the old in-process ensure-latch.\n * Shared across the outer backend and every transaction-scoped backend\n * so a slot's marker is resolved at most once per process.\n */\n contributionMaterializer: ContributionMaterializer;\n /** Whether this operation backend is bound to an explicit transaction. */\n transactionScoped: boolean;\n}>;\n\ntype CreateSqliteTransactionBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter?: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n profileHints: SqliteExecutionProfileHints;\n tableNames: ResolvedSqlTableNames;\n fulltextStrategy: FulltextStrategy;\n /** Active vector strategy. See {@link CreateSqliteOperationBackendOptions}. */\n vectorStrategy?: VectorStrategy | undefined;\n /** Shared durable-marker materializer. See {@link CreateSqliteOperationBackendOptions}. */\n contributionMaterializer: ContributionMaterializer;\n}>;\n\nfunction createSqliteOperationBackend(\n options: CreateSqliteOperationBackendOptions,\n): InternalOperationBackend {\n const {\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n serializedQueue,\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n transactionScoped,\n } = options;\n\n // CRUD statements route through the execution adapter's compiled path on\n // synchronous drivers so a repeated operation shape re-binds parameters\n // against a cached prepared statement instead of re-preparing through\n // drizzle's session on every call. Async drivers (remote libsql, D1)\n // have no statement cache and keep the drizzle fallback.\n const compiledExecute = executionAdapter.executeCompiled;\n const compiledRun = executionAdapter.executeCompiledRun;\n\n function execGet<T>(query: ExecutableSql): Promise<T | undefined> {\n // Fallback uses db.all()[0], not db.get(): drizzle-team/drizzle-orm#1049\n // — db.get() crashes with the libsql driver when no rows match\n // (normalizeRow receives undefined).\n //\n // The fallback branches use `await` unconditionally rather than\n // `instanceof Promise` because Drizzle returns SQLiteRaw thenables\n // that are NOT Promise instances (drizzle-team/drizzle-orm#2275).\n return runWithSerializedQueue(serializedQueue, async () => {\n if (compiledExecute === undefined) {\n const rows = await executionAdapter.execute<T>(query);\n return rows[0];\n }\n const rows = await compiledExecute<T>(executionAdapter.compile(query));\n return rows[0];\n });\n }\n\n function execAll<T>(query: ExecutableSql): Promise<T[]> {\n return runWithSerializedQueue(serializedQueue, async () => {\n if (compiledExecute === undefined) {\n return [...(await executionAdapter.execute<T>(query))];\n }\n return [...(await compiledExecute<T>(executionAdapter.compile(query)))];\n });\n }\n\n function execRun(query: ExecutableSql): Promise<void> {\n return runWithSerializedQueue(serializedQueue, async () => {\n if (compiledRun === undefined) {\n await db.run(\n isSqlFragment(query) ? toDrizzleSql(query, \"sqlite\") : query,\n );\n return;\n }\n await compiledRun(executionAdapter.compile(query));\n });\n }\n\n const batchConfig = computeSqliteBatchChunkSizes(\n capabilities.maxBindParameters ?? SQLITE_MAX_BIND_PARAMETERS,\n );\n const commonOperationMembers = createCommonOperationBackend({\n batchConfig,\n execution: {\n execAll,\n execGet,\n execRun,\n },\n nowIso,\n maxBindParameters:\n capabilities.maxBindParameters ?? SQLITE_MAX_BIND_PARAMETERS,\n operationStrategy,\n rowMappers: {\n toEdgeRow,\n toNodeRow,\n toSchemaVersionRow,\n toUniqueRow,\n },\n });\n\n const executeCompiled = executionAdapter.executeCompiled;\n const executeRawMethod: Pick<TransactionBackend, \"executeRaw\"> =\n executeCompiled === undefined ?\n {}\n : {\n executeRaw<T>(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executeCompiled<T>({ params, sql: sqlText }),\n );\n },\n };\n\n const vectorEmbeddingMethods =\n vectorStrategy === undefined ?\n {}\n : {\n async upsertEmbedding(params: UpsertEmbeddingParams): Promise<void> {\n const slot = vectorSlotFromParams(params);\n // Assert the slot's durable marker (SELECT, cached) — never DDL.\n // The per-field table is provisioned by the privileged migrator\n // (`createStoreWithSchema` → `materializeVectorContributions`).\n await contributionMaterializer.assertVectorSlot(slot);\n const statements = vectorStrategy.buildUpsert(slot, params, nowIso());\n try {\n for (const statement of statements) {\n await execRun(statement);\n }\n } catch (error) {\n throw mapVectorWriteError(error, params);\n }\n },\n async upsertEmbeddingBatch(\n params: UpsertEmbeddingBatchParams,\n ): Promise<void> {\n if (params.rows.length === 0) return;\n const slot = vectorSlotFromParams(params);\n // Same SELECT-only marker assert as the single-row path — never DDL.\n await contributionMaterializer.assertVectorSlot(slot);\n // Last-write-wins dedupe: a multi-row upsert cannot affect one\n // row twice.\n const rowsById = new Map(\n params.rows.map((row) => [row.nodeId, row] as const),\n );\n const rows = [...rowsById.values()];\n const timestamp = nowIso();\n try {\n for (const chunk of chunkArray(\n rows,\n batchConfig.embeddingUpsertBatchSize,\n )) {\n const statements =\n vectorStrategy.buildUpsertBatch === undefined ?\n chunk.flatMap((row) =>\n vectorStrategy.buildUpsert(\n slot,\n {\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n nodeId: row.nodeId,\n fieldPath: params.fieldPath,\n embedding: row.embedding,\n dimensions: params.dimensions,\n metric: params.metric,\n indexType: params.indexType,\n },\n timestamp,\n ),\n )\n : vectorStrategy.buildUpsertBatch(\n slot,\n { ...params, rows: chunk },\n timestamp,\n );\n for (const statement of statements) {\n await execRun(statement);\n }\n }\n } catch (error) {\n throw mapVectorWriteError(error, params);\n }\n },\n async deleteEmbedding(params: DeleteEmbeddingParams): Promise<void> {\n // Assert the slot's durable marker before deleting. A delete can\n // run before any embedding was ever written for the field (e.g. a\n // node hard-deleted having never carried one); the per-field table\n // was provisioned at boot, so the DELETE is a clean no-op against\n // an existing (possibly empty) table, matching the Postgres path\n // (where a DELETE on a missing relation would abort an enclosing\n // transaction). SELECT-only assert, never DDL.\n const slot = vectorSlotFromParams(params);\n await contributionMaterializer.assertVectorSlot(slot);\n const statements = vectorStrategy.buildDelete(slot, params);\n for (const statement of statements) {\n await execRun(statement);\n }\n },\n async deleteEmbeddingBatch(\n params: Omit<DeleteEmbeddingParams, \"nodeId\"> &\n Readonly<{ nodeIds: readonly string[] }>,\n ): Promise<void> {\n if (params.nodeIds.length === 0) return;\n const slot = vectorSlotFromParams(params);\n await contributionMaterializer.assertVectorSlot(slot);\n for (const nodeIds of chunkArray(\n [...new Set(params.nodeIds)],\n batchConfig.embeddingUpsertBatchSize,\n )) {\n const statements = vectorStrategy.buildDeleteBatch(slot, {\n ...params,\n nodeIds,\n });\n for (const statement of statements) await execRun(statement);\n }\n },\n async vectorSearch(\n params: VectorSearchParams,\n ): Promise<readonly VectorSearchResult[]> {\n assertVectorSearchLimit(params.limit);\n // Apply-or-refuse for the per-search ANN frontier. No SQLite engine\n // TypeGraph bundles has one (sqlite-vec's vec0 takes only `k`;\n // libSQL's `vector_top_k` takes only (index, query, k)), so the\n // shared predicate refuses `efSearch` here with the engine's own\n // reason instead of accepting it and searching as if it were never\n // passed. `undefined` — the overwhelmingly common case — returns\n // without touching anything.\n resolveEfSearchOverride({\n efSearch: params.efSearch,\n indexType: params.indexType,\n tuning: vectorSearchFrontierTuning(vectorStrategy),\n transactions: capabilities.transactions,\n dialect: \"SQLite\",\n engine: vectorStrategy.name,\n });\n // Deliberately NOT marker-gated: search is read-only (no DDL\n // hazard to gate), and its params carry the caller's runtime\n // metric override, which legitimately diverges from the\n // provisioned shape on strategies that bake the metric into the\n // DDL (sqlite-vec). An unprovisioned slot surfaces the engine's\n // missing-relation error — the same contract as a query-builder\n // `similarTo()` predicate; `createVerifiedStore` catches both at\n // attach.\n const slot = vectorSlotFromParams(params);\n const query = vectorStrategy.buildSearch(\n slot,\n params,\n // Store-compiled candidates (predicates + subclass + currency)\n // take precedence; the live-node default covers direct backend use.\n params.candidates ??\n buildLiveNodeCandidates(\n tableNames.nodes,\n params.graphId,\n params.nodeKind,\n nowIso(),\n ),\n );\n let rows: readonly { node_id: string; score: number }[];\n try {\n rows = await execAll<{ node_id: string; score: number }>(query);\n } catch (error) {\n // A query vector whose dimension no longer matches the stored\n // column surfaces the same typed error as the write path.\n throw mapVectorWriteError(error, params);\n }\n return rows.map((row) => ({\n nodeId: row.node_id,\n score: row.score,\n }));\n },\n // Single-statement hybrid needs ROW_NUMBER(); a capability profile\n // that disables window functions keeps the store's multi-statement\n // fallback by simply not exposing the member.\n ...(capabilities.windowFunctions ?\n {\n async hybridSearch(\n params: HybridSearchParams,\n ): Promise<readonly HybridSearchRow[]> {\n assertVectorSearchLimit(params.limit);\n // Source depths get the same boundary validation the\n // fallback path applies (vectorSearch validates its limit;\n // the fulltext depth is validated inside\n // buildFulltextSearch).\n assertVectorSearchLimit(params.vector.k);\n // The hybrid statement's vector leg carries the same option on\n // the same engine, so it takes the same refusal. This path built\n // its own `VectorSearchParams` and dropped\n // `params.vector.efSearch` while doing so — the silent ignore in\n // its second location.\n resolveEfSearchOverride({\n efSearch: params.vector.efSearch,\n indexType: params.vector.indexType,\n tuning: vectorSearchFrontierTuning(vectorStrategy),\n transactions: capabilities.transactions,\n dialect: \"SQLite\",\n engine: vectorStrategy.name,\n });\n const slot = vectorSlotFromParams({\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n fieldPath: params.vector.fieldPath,\n dimensions: params.vector.dimensions,\n metric: params.vector.metric,\n indexType: params.vector.indexType,\n });\n // Read-only, not marker-gated — see vectorSearch above.\n const candidates =\n params.candidates ??\n buildLiveNodeCandidates(\n tableNames.nodes,\n params.graphId,\n params.nodeKind,\n nowIso(),\n );\n const vectorParams: VectorSearchParams = {\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n fieldPath: params.vector.fieldPath,\n queryEmbedding: params.vector.queryEmbedding,\n metric: params.vector.metric,\n dimensions: params.vector.dimensions,\n indexType: params.vector.indexType,\n limit: params.vector.k,\n ...(params.vector.minScore === undefined ?\n {}\n : { minScore: params.vector.minScore }),\n };\n // The vector leg references the statement's shared\n // tg_hybrid_cand CTE; the actual candidates SQL is emitted\n // once by buildHybridSearch.\n const vectorSql = vectorStrategy.buildSearch(\n slot,\n vectorParams,\n portableSql.raw(\"SELECT node_id FROM tg_hybrid_cand\"),\n );\n const statement = operationStrategy.buildHybridSearch(\n { ...params, candidates },\n toDrizzleSql(vectorSql, \"sqlite\"),\n params.vector.metric === \"cosine\",\n );\n let raw: readonly Record<string, unknown>[];\n try {\n raw = await execAll<Record<string, unknown>>(statement);\n } catch (error) {\n throw mapVectorWriteError(error, vectorParams);\n }\n return raw.map((row) => mapHybridSearchRow(row, toNodeRow));\n },\n }\n : {}),\n };\n\n const operationBackend: InternalOperationBackend = {\n ...commonOperationMembers,\n ...executeRawMethod,\n ...vectorEmbeddingMethods,\n /**\n * Transaction-scoped contribution marker stamp. Present so the\n * destructive rebuild can commit its marker with the DDL that\n * produced it; without it the stamp would land outside the\n * transaction and could survive a rolled-back drop.\n *\n * States the row outright rather than reusing the top-level upsert,\n * whose `materialized_at` COALESCE preserves an earlier success so a\n * failed re-attempt cannot erase it. A completed rebuild replaced the\n * storage, so the recorded timestamp must be the rebuild's.\n */\n async recordContributionMaterialization(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await execRun(\n operationStrategy.buildInsertContributionMaterialization(params),\n );\n },\n\n async deleteSchemaVectorSlotContribution(slot: VectorSlot): Promise<void> {\n if (vectorStrategy === undefined) return;\n for (const contribution of vectorStrategy.ownedTables(slot)) {\n await execRun(\n operationStrategy.buildDeleteContributionMaterialization({\n graphId: slot.graphId,\n logicalName: contribution.logicalName,\n owner: contribution.owner,\n tableName: contribution.tableName,\n }),\n );\n }\n contributionMaterializer.evictVectorSlot(slot);\n },\n capabilities,\n dialect: \"sqlite\",\n tableNames,\n fulltextStrategy,\n ...(vectorStrategy === undefined ? {} : { vectorStrategy }),\n\n async lockSchemaVersionForWrite(\n params: LockSchemaVersionForWriteParams,\n ): Promise<void> {\n if (!transactionScoped) {\n throw new ConfigurationError(\n \"The schema write fence requires an explicit SQLite transaction.\",\n {\n code: \"SCHEMA_WRITE_FENCE_TRANSACTION_REQUIRED\",\n graphId: params.graphId,\n },\n );\n }\n // An ordinary read suffices, unlike Postgres' `FOR SHARE` fence: SQLite\n // serializes writers through BEGIN IMMEDIATE, so no schema commit can be\n // mid-flight while this transaction holds the writer slot, and a SQLite\n // read has no post-wait row recheck that could drop the active row from\n // its own snapshot. An absent row here therefore always means the graph\n // genuinely has no active schema.\n const active = await commonOperationMembers.getActiveSchema(\n params.graphId,\n );\n assertActiveSchemaVersion(\n params.graphId,\n params.expectedVersion,\n active?.version ?? 0,\n );\n },\n\n async createVectorIndex(params: CreateVectorIndexParams): Promise<void> {\n if (vectorStrategy === undefined) return;\n const slot = vectorSlotFromCreateIndexParams(params);\n // Ensure the per-field table + its durable marker first (privileged,\n // idempotent), then create its ANN index. `ownedTables` already folds\n // the index DDL in, so the explicit `buildCreateIndex` step is\n // belt-and-suspenders for slots whose index intent changed after the\n // table was first materialized.\n await contributionMaterializer.ensureVectorSlot(slot);\n const indexStatement = vectorStrategy.buildCreateIndex?.(slot);\n if (indexStatement !== undefined) {\n await execRun(indexStatement);\n }\n },\n\n async dropVectorIndex(params: DropVectorIndexParams): Promise<void> {\n if (vectorStrategy === undefined) return;\n const slot = vectorSlotFromDropIndexParams(params);\n const dropStatement = vectorStrategy.buildDropIndex?.(slot);\n if (dropStatement === undefined) return;\n try {\n await execRun(dropStatement);\n } catch (error) {\n // The per-field table (and thus its index) may never have been\n // materialized; DROP INDEX IF EXISTS against a missing table errors\n // on some drivers, so treat that as already-dropped.\n if (!isMissingTableError(error)) throw error;\n }\n },\n\n // === Fulltext Operations ===\n\n async upsertFulltext(params: UpsertFulltextParams): Promise<void> {\n const timestamp = nowIso();\n const statements = operationStrategy.buildUpsertFulltext(\n params,\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async deleteFulltext(params: DeleteFulltextParams): Promise<void> {\n const statements = operationStrategy.buildDeleteFulltext(params);\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async upsertFulltextBatch(\n params: UpsertFulltextBatchParams,\n ): Promise<void> {\n if (params.rows.length === 0) return;\n const timestamp = nowIso();\n // The strategy emits ONE statement over every row it is given, so\n // the bind budget is enforced here — same contract as node/edge\n // batch inserts.\n for (const rows of chunkArray(\n params.rows,\n batchConfig.fulltextUpsertBatchSize,\n )) {\n const statements = operationStrategy.buildUpsertFulltextBatch(\n { ...params, rows },\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n }\n },\n\n async deleteFulltextBatch(\n params: DeleteFulltextBatchParams,\n ): Promise<void> {\n if (params.nodeIds.length === 0) return;\n for (const nodeIds of chunkArray(\n params.nodeIds,\n batchConfig.fulltextDeleteChunkSize,\n )) {\n const statements = operationStrategy.buildDeleteFulltextBatch({\n ...params,\n nodeIds,\n });\n for (const stmt of statements) {\n await execRun(stmt);\n }\n }\n },\n\n async fulltextSearch(\n params: FulltextSearchParams,\n ): Promise<readonly FulltextSearchResult[]> {\n const query = operationStrategy.buildFulltextSearch(params);\n const rows = await execAll<{\n node_id: string;\n score: number | string;\n snippet: string | null;\n }>(query);\n return rows.map((row, index) => ({\n nodeId: row.node_id,\n score: coerceNumericScore(row.score),\n rank: index + 1,\n ...(row.snippet === null ? {} : { snippet: row.snippet }),\n }));\n },\n\n // === Query Execution ===\n\n async execute<T>(query: CompiledRowsSql): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executionAdapter.execute<T>(query),\n );\n },\n\n compileSql(\n query: SqlFragment,\n ): Readonly<{ sql: string; params: readonly unknown[] }> {\n return executionAdapter.compile(query);\n },\n };\n\n return operationBackend;\n}\n\n/**\n * Whether a driver client is a LOCAL `@libsql/client`: one stable connection\n * that every statement from every wrapper over it runs on, in order.\n *\n * `protocol === \"file\"` is the client's own answer to \"am I local?\" — it covers\n * `file:` paths, `:memory:` databases, and an embedded replica's local file. An\n * embedded replica (`protocol: \"file\"` PLUS a `syncUrl`) is deliberately marked\n * on the same evidence as any other local client: `syncUrl` names where the\n * replica pulls FROM, while every statement this client executes still routes\n * through the one local handle, so an open export snapshot on one wrapper still\n * holds the connection another wrapper's import needs. A REMOTE client\n * (`http` / `ws`) opens an independent stream per transaction and\n * must never be treated as one serialized resource; refusing concurrent work\n * there would refuse work that succeeds. The libsql methods are required\n * alongside the protocol so an unrelated object that happens to carry\n * `protocol: \"file\"` is not adopted, and none of it imports `@libsql/client`,\n * which this bundler-friendly module must not depend on.\n *\n * Single owner of the local/remote distinction: `../sqlite/libsql.ts` picks its\n * transaction framing (raw BEGIN/COMMIT on the one local connection vs Drizzle's\n * per-stream `db.transaction()`) by asking here, so the framing and the\n * serialized-resource mark cannot drift apart.\n */\nexport function isLocalLibsqlClient(client: unknown): boolean {\n if (typeof client !== \"object\" || client === null) return false;\n const candidate = client as Readonly<Record<string, unknown>>;\n return (\n candidate[\"protocol\"] === \"file\" &&\n typeof candidate[\"execute\"] === \"function\" &&\n typeof candidate[\"batch\"] === \"function\" &&\n typeof candidate[\"executeMultiple\"] === \"function\"\n );\n}\n\n/**\n * Returns the single connection a Drizzle database serializes every statement\n * onto, if its driver is one we can positively identify as such.\n *\n * Five drivers qualify, each by its own named predicate — a driver is marked on\n * evidence of WHAT IT IS, never on the absence of a disqualifier:\n *\n * - **better-sqlite3** ({@link isBetterSqlite3Client}): a single, synchronous\n * connection, so an open transaction on one wrapper is an open transaction\n * for all of them.\n * - **bun:sqlite** ({@link isBunSqliteClient}): the same one synchronous\n * connection, reached through `drizzle-orm/bun-sqlite`.\n * - **sql.js** ({@link isSqlJsClient}): one in-WASM database handle; every\n * wrapper's statements run on it in order.\n * - **Cloudflare Durable Object storage** (`drizzle(ctx.storage)`): one storage\n * connection whose transaction frame is AMBIENT on the storage object rather\n * than a handle passed to the callback (see `runDoSqliteStorageTransaction`:\n * `transactionMode: \"do-sqlite\"` binds the OUTER `db`). A second wrapper's\n * writes therefore land inside the first\n * wrapper's open export snapshot, and because the DO backend reports\n * `capabilities.transactions: true` nothing else abstains for it. Identified by\n * {@link getDurableObjectStorageClient}, the same full-shape evidence the\n * transaction runner requires, so the framing and the mark cannot drift apart.\n * - **a local `@libsql/client`**: also one stable connection — which is exactly\n * why local clients frame transactions as raw BEGIN/COMMIT on it (see\n * {@link isLocalLibsqlClient}). libsql clients expose no `prepare`, so no\n * prepare-capable predicate can see them and the driver client is read\n * directly here.\n *\n * Unrecognized clients stay unmarked: SEPARATE connections to the same file are\n * genuinely concurrent under WAL and must not be treated as one serialized\n * resource, and a driver whose dispatch we cannot attribute proves nothing.\n * The full classification — marked, deliberately unmarked, and the remaining\n * gaps — is the inventory in `../transaction-resource.ts`.\n */\nfunction getSerializedSqliteConnection(\n db: AnySqliteDatabase,\n): object | undefined {\n const client = (db as Readonly<{ $client?: unknown }>).$client;\n if (\n isBetterSqlite3Client(client) ||\n isBunSqliteClient(client) ||\n isSqlJsClient(client)\n ) {\n return client as object;\n }\n // The storage object IS the serialized resource: every wrapper built over the\n // same `ctx.storage` shares its one connection and its ambient transaction.\n const storageClient = getDurableObjectStorageClient(db);\n if (storageClient !== undefined) return storageClient;\n return isLocalLibsqlClient(client) ? (client as object) : undefined;\n}\n\n/**\n * Whether two backends built over `client` would be treated as one serialized\n * connection. The marking predicate itself, exposed for the driver-shape unit\n * tests (mirrors `isSerializedPostgresClient`); production code reaches it only\n * through {@link createSqliteBackend}.\n */\nexport function isSerializedSqliteClient(client: unknown): boolean {\n return (\n getSerializedSqliteConnection({\n $client: client,\n } as unknown as AnySqliteDatabase) !== undefined\n );\n}\n\nexport function createSqliteBackend(\n db: AnySqliteDatabase,\n options: SqliteBackendOptions = {},\n): AdapterBackend<AnySqliteDatabase> {\n // Resolved before the backend exists so marking below is a lookup, never\n // work that could fail after wrappers already observed an unmarked backend.\n // A `serializedResource` declaration that contradicts detection is refused\n // here too, before any object a caller could hold has been built.\n const resourceAudit = resolveDeclaredBackendResource(\n getSerializedSqliteConnection(db),\n options.serializedResource,\n );\n const tables = options.tables ?? defaultTables;\n const fulltextStrategy = options.fulltext ?? fts5Strategy;\n const profileHints = options.executionProfile ?? {};\n const executionAdapter = createSqliteExecutionAdapter(db, { profileHints });\n const { isSync, transactionMode } = executionAdapter.profile;\n // The active vector strategy gates upsertEmbedding / deleteEmbedding /\n // vectorSearch and supplies the per-`(kind, field)` storage. Passed by\n // the caller that knows the connection's vector capability\n // (`createLibsqlBackend` always; `createLocalSqliteBackend` when the\n // extension loads); absent for plain SQLite drivers with no extension.\n const vectorStrategy = options.vector;\n const capabilityOverrides = options.capabilities ?? {};\n const declaredCapabilities = normalizeGraphAnalyticsCapabilities({\n ...buildSqliteCapabilities({\n fulltextStrategy,\n vectorStrategy,\n transactionMode,\n maxBindParameters: executionAdapter.profile.maxBindParameters,\n }),\n ...capabilityOverrides,\n maxBindParameters: resolveMaxBindParametersCapability(\n executionAdapter.profile,\n capabilityOverrides.maxBindParameters,\n ),\n graphAnalytics: resolveSqliteGraphAnalyticsCapabilities(\n executionAdapter.profile,\n capabilityOverrides.graphAnalytics,\n ),\n });\n // Derived last and not overridable: how far up the contribution health\n // ladder this backend goes is a structural fact about the wiring below\n // (durable markers, a catalog probe, a strategy that declares teardown\n // DDL, a transactional schema fence), and a caller who declared a\n // rebuild this backend cannot perform would be advertising a lie.\n const capabilities: BackendCapabilities = {\n ...declaredCapabilities,\n contributions: {\n supported: true,\n probe: true,\n rebuild: contributionRebuildSupported(\n fulltextStrategy,\n tables.fulltextTableName,\n declaredCapabilities.transactions,\n ),\n },\n };\n\n const tableNames: ResolvedSqlTableNames = {\n nodes: getTableName(tables.nodes),\n edges: getTableName(tables.edges),\n recordedNodes: getTableName(tables.recordedNodes),\n recordedEdges: getTableName(tables.recordedEdges),\n recordedClock: getTableName(tables.recordedClock),\n revisionOrigins: getTableName(tables.revisionOrigins),\n identityAssertions: getTableName(tables.identityAssertions),\n recordedIdentityAssertions: getTableName(tables.recordedIdentityAssertions),\n identityClosure: getTableName(tables.identityClosure),\n identitySeparation: getTableName(tables.identitySeparation),\n fulltext: tables.fulltextTableName,\n uniques: getTableName(tables.uniques),\n edgeClaims: getTableName(tables.edgeClaims),\n };\n // refreshStatistics() scopes ANALYZE to these — matching the Postgres\n // backend, which never touches unrelated tables sharing the database.\n // The recorded and identity relations are ANALYZEd separately under a\n // missing-table guard: a schema created before recorded-time history or\n // Operational Identity landed (bring-your-own-connection, no DDL re-run)\n // has no recorded_* / identity_* tables.\n const coreAnalyzeTables = [\n tableNames.nodes,\n tableNames.edges,\n tableNames.uniques,\n tableNames.fulltext,\n ];\n const guardedAnalyzeTables = [\n tableNames.recordedNodes,\n tableNames.recordedEdges,\n tableNames.recordedClock,\n tableNames.recordedIdentityAssertions,\n tableNames.identityAssertions,\n tableNames.identityClosure,\n tableNames.identitySeparation,\n ] as const;\n const operationStrategy = createSqliteOperationStrategy(\n tables,\n fulltextStrategy,\n );\n // Serialize top-level operations per backend on every transaction-capable\n // mode (\"sql\", \"drizzle\", \"do-sqlite\"). SQLite is single-writer, and two\n // concurrent `transaction()` calls on one connection open overlapping BEGINs\n // and collide with SQLITE_BUSY; the queue makes each top-level operation —\n // including a whole transaction — run to completion before the next starts.\n // A transaction's inner reads/writes run on the tx-scoped backend, which\n // does not carry the queue (see CreateSqliteTransactionBackendOptions);\n // awaiting a ROOT-backend operation from inside the transaction callback\n // would deadlock, so the queue rejects such re-entrant submissions with a\n // typed error (see rejectReentrantQueueSubmission). `none` drivers (D1 /\n // neon-http) have no transactions and manage their own concurrency, so they\n // stay unqueued.\n const serializedQueue =\n transactionMode === \"none\" ? undefined : createSerializedExecutionQueue();\n\n // Durable fulltext + vector materialization (#135): the dialect-specific\n // marker-table primitives. Orchestration (materialize / assert /\n // per-instance cache) lives once in `createContributionMaterializer`,\n // shared by the outer backend and every transaction-scoped backend so a\n // slot's marker is resolved at most once per process. Built before\n // `operations` so the operation backend's vector methods can assert/\n // ensure through it instead of issuing DDL on the hot path.\n const matTable = tables.contributionMaterializations;\n\n async function ensureContributionMaterializationsTableImpl(): Promise<void> {\n await db.run(sql.raw(generateSqliteCreateTableSQL(matTable)));\n }\n\n async function getContributionMaterializationRow(\n identity: ContributionMaterializationIdentity,\n ): Promise<ContributionMaterializationRow | undefined> {\n const rows = await db\n .select()\n .from(matTable)\n .where(\n and(\n eq(matTable.graphId, identity.graphId),\n eq(matTable.logicalName, identity.logicalName),\n eq(matTable.owner, identity.owner),\n eq(matTable.tableName, identity.tableName),\n ),\n );\n const row = rows[0];\n if (row === undefined) return undefined;\n return mapContributionMaterializationRow(\n row,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS.decode,\n );\n }\n\n async function getContributionMaterializationRows(\n graphId: string,\n ): Promise<readonly ContributionMaterializationRow[]> {\n const rows = await db\n .select()\n .from(matTable)\n .where(eq(matTable.graphId, graphId));\n return rows.map((row) =>\n mapContributionMaterializationRow(\n row,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS.decode,\n ),\n );\n }\n\n async function recordContributionMaterializationRow(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await db\n .insert(matTable)\n .values(\n buildContributionInsertValues(\n params,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: [\n matTable.graphId,\n matTable.logicalName,\n matTable.owner,\n matTable.tableName,\n ],\n set: buildContributionOnConflictSet(\n matTable.materializedAt,\n params.materializedAt,\n ),\n });\n }\n\n async function deleteContributionMaterializationRow(\n identity: ContributionMaterializationIdentity,\n ): Promise<void> {\n await db\n .delete(matTable)\n .where(\n and(\n eq(matTable.graphId, identity.graphId),\n eq(matTable.logicalName, identity.logicalName),\n eq(matTable.owner, identity.owner),\n eq(matTable.tableName, identity.tableName),\n ),\n );\n }\n\n /**\n * Uncached catalog probe backing `verifyContributions`. The shared\n * `createCachedTableExistence` wrapper is deliberately NOT used: this\n * diagnostic's whole job is to notice that a table confirmed present\n * earlier has since been dropped.\n */\n async function contributionTableExists(tableName: string): Promise<boolean> {\n const rows = await executionAdapter.execute<Record<string, unknown>>(\n operationStrategy.buildTableExists(tableName),\n );\n return tableExistsFromRow(rows[0]);\n }\n\n /**\n * The contribution descriptors for exactly the identity relations, under\n * caller-supplied physical names. Pure — nothing is executed here — and the\n * single owner of \"which DDL belongs to the identity relations\", shared by\n * `ensureIdentityTables` (which runs it) and `identityTableDdl` (which hands\n * it to a transaction).\n */\n function identityContributionsFor(\n identityTableNames: IdentityTableNames,\n ): ReturnType<typeof sqliteContributions> {\n const identityTables = buildSqliteTables({\n identityAssertions: identityTableNames.identityAssertions,\n recordedIdentityAssertions: identityTableNames.recordedIdentityAssertions,\n identityClosure: identityTableNames.identityClosure,\n identitySeparation: identityTableNames.identitySeparation,\n });\n return sqliteContributions(identityTables, fulltextStrategy).filter(\n (contribution) =>\n IDENTITY_TABLE_LOGICAL_NAMES.has(contribution.logicalName),\n );\n }\n\n const contributionMaterializer = createContributionMaterializer({\n dialect: \"sqlite\",\n fulltextStrategy,\n fulltextTableName: tables.fulltextTableName,\n vectorStrategy,\n execDdl: async (statement) => {\n await db.run(sql.raw(statement));\n },\n ensureMarkerTable: ensureContributionMaterializationsTableImpl,\n getMarkers: getContributionMaterializationRows,\n recordMarker: recordContributionMaterializationRow,\n deleteMarker: deleteContributionMaterializationRow,\n tableExists: contributionTableExists,\n // Withheld rather than wired-and-throwing when transactions are\n // disabled: the rebuild must refuse with its own typed error naming\n // the absent fence, matching `capabilities.contributions.rebuild`.\n // The graph id the materializer passes is unused — this backend's\n // schema lock is per connection, not per graph.\n ...(capabilities.transactions ?\n {\n schemaWriteTransaction: <T>(\n _graphId: string,\n fn: (tx: SchemaWriteTransactionBackend) => Promise<T>,\n ) => runSchemaWriteTransaction((target) => fn(target)),\n }\n : {}),\n });\n\n const operations = createSqliteOperationBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n transactionScoped: false,\n ...(serializedQueue === undefined ? {} : { serializedQueue }),\n });\n\n /**\n * #140: the `transactionMode: \"do-sqlite\"` primitive. Cloudflare\n * Durable Objects expose an async storage transaction runner —\n * `ctx.storage.transaction(async () => ...)`, surfaced by Drizzle as\n * `db.$client.transaction` — that rolls back SQL writes across\n * `await`. There is no Drizzle tx handle on DO: the storage\n * transaction is ambient on the object, so callers bind the *outer*\n * `db` (as the \"sql\" path binds the outer connection). Drizzle's own\n * `db.transaction()` here is `ctx.storage.transactionSync` and cannot\n * span an await, so it is deliberately not used. Shared by\n * `transaction()` (business writes) and `runSchemaWriteTransaction()`.\n * Ordinary schema-version commits are data-only; administrative removal\n * cleanup may execute transaction-scoped DDL.\n */\n function runDoSqliteStorageTransaction<T>(run: () => Promise<T>): Promise<T> {\n const storage = getDurableObjectStorageClient(db);\n if (storage === undefined) {\n throwSqliteTransactionsDisabled(\n \"transactionMode 'do-sqlite' requires a Drizzle Durable Objects \" +\n \"database (drizzle(ctx.storage)) whose `$client` exposes the SQL, \" +\n \"transactionSync, and async transaction runners.\",\n );\n }\n return runWithSerializedQueue(serializedQueue, () =>\n storage.transaction(run),\n );\n }\n\n /**\n * Executes a transaction-frame statement (BEGIN IMMEDIATE / COMMIT /\n * ROLLBACK) through the prepared-statement cache when the driver has one.\n * These are the hottest statements on the per-write path (every single\n * write is its own transaction). Local libsql also uses \"sql\" transaction\n * mode but is async (no compiled path) and keeps the drizzle fallback.\n */\n async function runFrameStatement(query: SQL): Promise<void> {\n const compiledRun = executionAdapter.executeCompiledRun;\n if (compiledRun === undefined) {\n await db.run(query);\n return;\n }\n await compiledRun(executionAdapter.compile(query));\n }\n\n /**\n * Rolls the manually framed transaction back on the failure path WITHOUT ever\n * throwing: the caller rethrows the original error immediately after.\n *\n * SQLite rolls a transaction back by itself on some errors (SQLITE_FULL,\n * SQLITE_IOERR, SQLITE_NOMEM), so by the time this runs the frame can already\n * be gone and the ROLLBACK fails with \"cannot rollback - no transaction is\n * active\". A bare `await ROLLBACK; throw error` replaces the caller's\n * actionable failure (\"disk image is malformed\") with that secondary one and\n * never reaches its own rethrow — the masking that `closeAfterFailure` and the\n * index-materialization claim release exist to prevent, applied here too.\n *\n * The two reasons a ROLLBACK can fail are NOT told apart here, deliberately.\n * SQLite reports the already-closed frame only as a message (\"cannot rollback\n * - no transaction is active\"), with no result code that distinguishes it, so\n * a classifier would have to match text through whatever wrapper the driver\n * applied — and it would buy nothing, because the handling is identical\n * either way: never mask the caller's error, always report. The report\n * therefore states both possibilities rather than asserting the benign one,\n * so an operator reading the log is not told \"nothing is leaked\" about a\n * failure that did leave the frame open. When it did, nothing here can close\n * it (the statement that would is the one that just failed) and the next\n * BEGIN on this connection fails loudly rather than silently joining it.\n */\n async function rollbackFrameQuietly(): Promise<void> {\n try {\n await runFrameStatement(sql`ROLLBACK`);\n } catch (rollbackError) {\n console.warn(\n \"typegraph: ROLLBACK failed while unwinding a failed SQLite \" +\n \"transaction; the original failure is the one thrown. Either the \" +\n \"frame was already closed (SQLite auto-rolls-back on SQLITE_FULL / \" +\n \"SQLITE_IOERR / SQLITE_NOMEM) and nothing is leaked, or it is still \" +\n \"open on this connection, in which case the next BEGIN here fails.\",\n rollbackError,\n );\n }\n }\n\n /**\n * Runs `fn` inside a SQLite write transaction (BEGIN IMMEDIATE) so that\n * the read-then-write inside `commitSchemaVersion` / `setActiveVersion`\n * is serialized against concurrent writers — a deferred BEGIN would let\n * two transactions race past the CAS read and one would later fail\n * with SQLITE_BUSY instead of producing a clean StaleVersionError.\n *\n * Refuses on `transactionMode: \"none\"`. The orphan-row crash window\n * cannot be eliminated without atomicity.\n */\n function runSchemaWriteTransaction<T>(\n fn: (tx: InternalOperationBackend) => Promise<T>,\n ): Promise<T> {\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"Schema writes and removal cleanup require atomic transactions, \" +\n \"but this SQLite backend has transactions disabled. Configure a \" +\n \"driver that supports transactions (better-sqlite3, libsql, \" +\n \"bun:sqlite) to use schema commits.\",\n );\n }\n\n if (transactionMode === \"sql\") {\n return runWithSerializedQueue(serializedQueue, async () => {\n // Write-lock is held here, so the schema-write-capable\n // InternalOperationBackend is used intentionally (see its type).\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n await runFrameStatement(sql`BEGIN IMMEDIATE`);\n try {\n const result = await fn(txBackend);\n await runFrameStatement(sql`COMMIT`);\n return result;\n } catch (error) {\n await rollbackFrameQuietly();\n throw error;\n }\n });\n }\n\n if (transactionMode === \"do-sqlite\") {\n // No interactive lock-mode control on the DO storage runner; the\n // serialized queue (always present — DO is sync) provides the\n // single-writer ordering that \"immediate\" gives the other paths.\n // Raw txBackend (no `gateFulltext`, unlike the business\n // `transaction()` do-sqlite branch). Schema-version commits remain\n // data-only; administrative removal cleanup may use the target's\n // transaction-scoped DDL primitive.\n return runDoSqliteStorageTransaction(async () => {\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n return fn(txBackend);\n });\n }\n\n // transactionMode === \"drizzle\". Drizzle's sqlite-core transaction\n // accepts a `behavior` option that maps to BEGIN / BEGIN IMMEDIATE /\n // BEGIN EXCLUSIVE; \"immediate\" is what we need to acquire a reserved\n // write lock at the start of the transaction.\n return runWithSerializedQueue(\n serializedQueue,\n async () =>\n db.transaction(\n async (tx) => {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n return fn(txBackend);\n },\n { behavior: \"immediate\" },\n ) as Promise<T>,\n );\n }\n\n // Shared by the \"drizzle\" branch of `transaction()` (TypeGraph opens\n // the tx) and `adoptTransaction()` (#134 — the caller already opened\n // it): bind a tx-scoped backend to the *literal* `tx` client and gate\n // fulltext on the durable marker (a cached SELECT, never DDL).\n function bindTransactionBackend(tx: AnySqliteDatabase): TransactionBackend {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n return gateFulltext(\n txBackend,\n contributionMaterializer.assertInitialized,\n contributionMaterializer.refuseUnavailableFulltext,\n );\n }\n\n const backend: AdapterBackend<AnySqliteDatabase> = {\n ...operations,\n\n ...((\n isSync &&\n transactionMode === \"sql\" &&\n executionAdapter.executePreparedRunBatch !== undefined\n ) ?\n {\n async trustedImport<T>(\n fn: (session: TrustedImportSession) => Promise<T>,\n options_?: TrustedImportOptions,\n ): Promise<T> {\n return backend.transaction(async (tx) => {\n if (options_?.schemaWrite !== undefined) {\n await requireDefined(tx.lockSchemaVersionForWrite)({\n ...options_.schemaWrite,\n });\n }\n await assertTrustedImportDatabaseEmpty(tx, tableNames);\n const indexDefinitions = await suspendSqliteSecondaryIndexes(\n tx,\n tableNames,\n );\n const result = await fn(\n createSqliteTrustedImportSession(executionAdapter, tableNames),\n );\n await restoreSecondaryIndexes(tx, indexDefinitions);\n await analyzeImportedTables(tx, tableNames);\n return result;\n });\n },\n }\n : {}),\n\n async bootstrapTables(): Promise<void> {\n const statements = generateSqliteDDL(tables, fulltextStrategy);\n for (const statement of statements) {\n await db.run(sql.raw(statement));\n }\n },\n\n async ensureRevisionOriginsTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.revisionOrigins)),\n );\n },\n\n async ensureIdentityTables(\n identityTableNames,\n options,\n ): Promise<readonly string[]> {\n // First enablement of Operational Identity on an existing populated\n // database: createStore / createSqliteBackend run no DDL, so the four\n // identity relations the enablement preflight reads/writes may not\n // exist yet. Ensure them (and their indexes and CHECK constraints)\n // idempotently — CREATE TABLE / CREATE INDEX IF NOT EXISTS — reusing the same contribution\n // DDL bootstrapTables emits, scoped to the identity relations.\n const identityContributions =\n identityContributionsFor(identityTableNames);\n const missing = [] as string[];\n for (const contribution of identityContributions) {\n if (!(await contributionTableExists(contribution.tableName))) {\n missing.push(contribution.logicalName);\n }\n }\n // Preserve missing ledger storage on already-enabled graphs so a retry\n // cannot silently accept tables created empty by an earlier failed open.\n // First enablement opts into provisioning; when every table exists,\n // idempotent DDL still repairs missing secondary indexes.\n if (missing.length === 0 || options.provisionMissing) {\n for (const contribution of identityContributions) {\n for (const ddl of contribution.createDdl) {\n await db.run(sql.raw(ddl));\n }\n }\n }\n return missing;\n },\n\n identityTableDdl(identityTableNames): readonly string[] {\n return identityContributionsFor(identityTableNames).flatMap(\n (contribution) => [...contribution.createDdl],\n );\n },\n\n // Every fulltext-touching method asserts the durable marker instead\n // of lazily emitting DDL. Steady state performs zero ensure; an\n // uninitialized database throws `StoreNotInitializedError` rather\n // than self-healing (#135). Shared verbatim with the tx-scoped gate\n // via `gateFulltextMethods`.\n ...gateFulltextMethods(\n operations,\n contributionMaterializer.assertInitialized,\n contributionMaterializer.refuseUnavailableFulltext,\n ),\n\n async executeDdl(ddl: string): Promise<void> {\n await db.run(sql.raw(ddl));\n },\n\n async ensureIndexMaterializationsTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.indexMaterializations)),\n );\n },\n\n async getIndexMaterialization(\n indexName: string,\n ): Promise<IndexMaterializationRow | undefined> {\n const t = tables.indexMaterializations;\n const rows = await db.select().from(t).where(eq(t.indexName, indexName));\n const row = rows[0];\n if (row === undefined) return undefined;\n return mapMaterializationRow(row, SQLITE_INDEX_MAT_TIMESTAMPS.decode);\n },\n\n async getIndexMaterializations(\n statusKeys: readonly string[],\n ): Promise<readonly IndexMaterializationRow[]> {\n if (statusKeys.length === 0) return [];\n const t = tables.indexMaterializations;\n const rows = await db\n .select()\n .from(t)\n .where(inArray(t.indexName, [...statusKeys]));\n return rows.map((row) =>\n mapMaterializationRow(row, SQLITE_INDEX_MAT_TIMESTAMPS.decode),\n );\n },\n\n async recordIndexMaterialization(\n params: RecordIndexMaterializationParams,\n ): Promise<void> {\n const t = tables.indexMaterializations;\n await db\n .insert(t)\n .values(\n buildMaterializationInsertValues(\n params,\n SQLITE_INDEX_MAT_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: t.indexName,\n set: buildMaterializationOnConflictSet(params.materializedAt),\n });\n },\n\n async ensureContributionMaterializationsTable(): Promise<void> {\n await ensureContributionMaterializationsTableImpl();\n },\n\n async getContributionMaterialization(\n identity: ContributionMaterializationIdentity,\n ): Promise<ContributionMaterializationRow | undefined> {\n return getContributionMaterializationRow(identity);\n },\n\n async recordContributionMaterialization(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await recordContributionMaterializationRow(params);\n },\n\n async assertRuntimeContributionsInitialized(\n graphId: string,\n ): Promise<void> {\n await contributionMaterializer.assertInitialized(graphId);\n },\n\n async ensureKindRemovalsTable(): Promise<void> {\n await db.run(sql.raw(generateSqliteCreateTableSQL(tables.kindRemovals)));\n },\n\n async getPendingKindRemovals(\n graphId: string,\n ): Promise<readonly KindRemovalRow[]> {\n const t = tables.kindRemovals;\n const rows = await db\n .select()\n .from(t)\n .where(and(eq(t.graphId, graphId), isNull(t.removedAt)));\n return rows.map((row) =>\n mapKindRemovalRow(row, SQLITE_KIND_REMOVAL_TIMESTAMPS.decode),\n );\n },\n\n async getAllKindRemovals(\n graphId: string,\n ): Promise<readonly KindRemovalRow[]> {\n const t = tables.kindRemovals;\n const rows = await db.select().from(t).where(eq(t.graphId, graphId));\n return rows.map((row) =>\n mapKindRemovalRow(row, SQLITE_KIND_REMOVAL_TIMESTAMPS.decode),\n );\n },\n\n async recordKindRemoval(params: RecordKindRemovalParams): Promise<void> {\n const t = tables.kindRemovals;\n await db\n .insert(t)\n .values(\n buildKindRemovalInsertValues(\n params,\n SQLITE_KIND_REMOVAL_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: [t.graphId, t.kindName, t.entity, t.schemaVersion],\n set: buildKindRemovalOnConflictSet(t.removedAt, params.removedAt),\n });\n },\n\n async ensureReconciliationMarkersTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.reconciliationMarkers)),\n );\n },\n\n async ensureRuntimeContributions(graphId: string): Promise<void> {\n await contributionMaterializer.ensureRuntimeContributions(graphId);\n },\n\n /**\n * Superseded by `ensureRuntimeContributions(graphId)` (#129).\n * Retained as a thin back-compat wrapper for callers predating\n * #129; #135 routed it through the durable-marker writer.\n */\n async ensureFulltextTable(graphId: string): Promise<void> {\n await contributionMaterializer.ensureRuntimeContributions(graphId);\n },\n\n async verifyContributions(\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ): Promise<readonly ContributionDiagnostic[]> {\n return contributionMaterializer.verifyContributions(graphId, vectorSlots);\n },\n\n async repairContributions(\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ): Promise<ContributionRepairResult> {\n return contributionMaterializer.repairContributions(graphId, vectorSlots);\n },\n\n async probeContributions(\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ): Promise<readonly ContributionProbeEntry[]> {\n return contributionMaterializer.probeContributions(graphId, vectorSlots);\n },\n\n async rebuildContribution(\n graphId: string,\n scope: ContributionRebuildScope,\n repopulate: (\n target: TransactionBackend,\n ) => Promise<ContributionRepopulationStats>,\n ): Promise<ContributionRebuildResult> {\n return contributionMaterializer.rebuildContribution(\n graphId,\n scope,\n repopulate,\n );\n },\n\n // Vector counterparts of the runtime-contribution methods. Present\n // only when a vector strategy is wired (omitted on a plain SQLite\n // connection with no vector extension), mirroring the embedding/\n // search methods.\n ...(vectorStrategy === undefined ?\n {}\n : {\n async ensureVectorSlotContribution(\n slot: VectorSlot,\n options_?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n ): Promise<void> {\n await contributionMaterializer.ensureVectorSlot(slot, options_);\n },\n\n async ensureVectorSlotContributions(\n slots: readonly VectorSlot[],\n options_?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n ): Promise<void> {\n await contributionMaterializer.ensureVectorSlots(slots, options_);\n },\n\n async assertVectorSlotInitialized(slot: VectorSlot): Promise<void> {\n await contributionMaterializer.assertVectorSlot(slot);\n },\n\n async assertVectorSlotsInitialized(\n slots: readonly VectorSlot[],\n ): Promise<void> {\n await contributionMaterializer.assertVectorSlots(slots);\n },\n\n async deleteVectorSlotContribution(slot: VectorSlot): Promise<void> {\n await contributionMaterializer.dropVectorSlot(slot);\n },\n }),\n\n async getReconciliationMarker(\n graphId: string,\n ): Promise<number | undefined> {\n const t = tables.reconciliationMarkers;\n const rows = await db.select().from(t).where(eq(t.graphId, graphId));\n return rows[0]?.reconciledToVersion;\n },\n\n async setReconciliationMarker(\n graphId: string,\n version: number,\n ): Promise<void> {\n const t = tables.reconciliationMarkers;\n await db\n .insert(t)\n .values({ graphId, reconciledToVersion: version })\n .onConflictDoUpdate({\n target: t.graphId,\n set: { reconciledToVersion: version },\n });\n },\n\n async refreshStatistics(): Promise<void> {\n // `ANALYZE` populates `sqlite_stat1`. With no stat table, the\n // planner falls back to heuristics that, at least for FTS5\n // virtual-table queries and multi-column index selection, can be\n // an order of magnitude slower. Running it explicitly makes the\n // planner data-driven.\n //\n // Scoped to TypeGraph-managed tables only (matching the Postgres\n // backend) — a bare `ANALYZE` touches every table in the database\n // file, including unrelated ones sharing it. Bounded by\n // `analysis_limit` (see its doc comment) so cost stays roughly\n // constant per call regardless of table size — the value is a\n // fixed internal constant, not user input, so inlining it via\n // `sql.raw` is safe; SQLite's `PRAGMA` does not accept bound\n // parameters for its value.\n try {\n await db.run(\n toDrizzleSql(\n portableSql`PRAGMA analysis_limit = ${portableSql.raw(String(SQLITE_ANALYZE_ROW_LIMIT))}`,\n \"sqlite\",\n ),\n );\n } catch (error) {\n // Cloudflare D1 and Durable Object SQLite reject this performance-only\n // tuning PRAGMA through their authorizer. Continue with scoped ANALYZE,\n // which workerd permits, but keep every unexpected failure loud.\n if (!isSqliteNotAuthorizedError(error)) throw error;\n }\n for (const tableName of coreAnalyzeTables) {\n await db.run(\n toDrizzleSql(\n portableSql`ANALYZE ${portableSql.identifier(tableName)}`,\n \"sqlite\",\n ),\n );\n }\n // The recorded and identity relations may be absent on a schema\n // created before recorded-time history or Operational Identity landed\n // (bring-your-own-connection, no DDL re-run); ANALYZE on a missing\n // table errors, so skip those.\n for (const tableName of guardedAnalyzeTables) {\n try {\n await db.run(\n toDrizzleSql(\n portableSql`ANALYZE ${portableSql.identifier(tableName)}`,\n \"sqlite\",\n ),\n );\n } catch (error) {\n if (!isMissingTableError(error)) throw error;\n }\n }\n },\n\n async commitSchemaVersion(\n params: CommitSchemaVersionParams,\n ): Promise<SchemaVersionRow> {\n return runSchemaWriteTransaction((target) =>\n target.commitSchemaVersion(params),\n );\n },\n\n async commitSchemaVersionIfKindsEmpty(\n params: CommitSchemaVersionParams,\n probes: readonly SchemaKindEmptinessProbe[],\n ): Promise<CommitSchemaVersionIfKindsEmptyResult> {\n // BEGIN IMMEDIATE already owns SQLite's serialized writer slot, so the\n // counts and schema CAS below share the same ordinary-write fence.\n return runSchemaWriteTransaction((target) =>\n commitSchemaVersionIfKindsEmpty(target, params, probes),\n );\n },\n\n async commitSchemaVersionWithPreflight(\n params: CommitSchemaVersionParams,\n // The schema-write target, not the narrowed transaction backend: a\n // preflight may have to CREATE the storage it then fills, and that DDL\n // belongs in this transaction rather than before it.\n preflight: (target: SchemaWriteTransactionBackend) => Promise<void>,\n ): Promise<SchemaVersionRow> {\n return runSchemaWriteTransaction(async (target) => {\n await preflight(target);\n return target.commitSchemaVersion(params);\n });\n },\n\n async setActiveVersion(params: SetActiveVersionParams): Promise<void> {\n await runSchemaWriteTransaction((target) =>\n target.setActiveVersion(params),\n );\n },\n\n async schemaWriteTransaction<T>(\n _graphId: string,\n fn: (tx: SchemaWriteTransactionBackend) => Promise<T>,\n ): Promise<T> {\n return runSchemaWriteTransaction((target) => fn(target));\n },\n\n async transaction<T>(\n fn: (tx: TransactionBackend) => Promise<T>,\n options?: InternalTransactionOptions,\n ): Promise<T> {\n return backend.transactionWithNative((tx) => fn(tx), options);\n },\n\n async transactionWithNative<T>(\n fn: (tx: TransactionBackend, sql: AnySqliteDatabase) => Promise<T>,\n options?: InternalTransactionOptions,\n ): Promise<T> {\n const temporaryWrites =\n options?.temporaryWrites === INTERNAL_TEMPORARY_WRITES;\n if (temporaryWrites && options.accessMode !== \"read_only\") {\n throw new ConfigurationError(\n \"Temporary-write transactions must be semantically read-only.\",\n { dialect: \"sqlite\" },\n );\n }\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"This SQLite backend does not support atomic transactions. \" +\n \"Operations within a transaction are not rolled back on failure. \" +\n \"Use backend.capabilities.transactions to check for transaction support, \" +\n \"or use individual operations with manual error handling.\",\n );\n }\n\n // #134/#135: NO DDL or ensure here. The tx-scoped backend\n // exposes raw fulltext methods without self-ensure wrappers; the\n // single gate is `Store.transaction()`, which asserts the durable\n // contribution marker (one cached SELECT) before this method is\n // reached. The caller's BEGIN never carries CREATE statements.\n if (transactionMode === \"sql\") {\n return runWithSerializedQueue(serializedQueue, async () => {\n // Not `bindTransactionBackend(...)`: this path frames the tx\n // with manual BEGIN/COMMIT on the *outer* `db`, so it must\n // reuse that connection's already-built `executionAdapter`\n // rather than synthesize a fresh one for a distinct handle.\n // Serves sync drivers AND local libsql connections: both keep\n // one stable connection, where raw BEGIN/COMMIT composes and\n // Drizzle's `db.transaction()` (which for libsql abandons the\n // client's connection — fatal for `:memory:`) must be avoided.\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n // Read-only multi-statement operations need one snapshot but must not\n // reserve SQLite's single writer slot. Business transactions retain\n // BEGIN IMMEDIATE so read-then-write cannot lose a lock-upgrade race.\n await runFrameStatement(\n options?.accessMode === \"read_only\" || temporaryWrites ?\n sql`BEGIN`\n : sql`BEGIN IMMEDIATE`,\n );\n\n try {\n const result = await fn(\n gateFulltext(\n txBackend,\n contributionMaterializer.assertInitialized,\n contributionMaterializer.refuseUnavailableFulltext,\n ),\n db,\n );\n await runFrameStatement(sql`COMMIT`);\n return result;\n } catch (error) {\n await rollbackFrameQuietly();\n throw error;\n }\n });\n }\n\n if (transactionMode === \"do-sqlite\") {\n return runDoSqliteStorageTransaction(async () =>\n fn(bindTransactionBackend(db), db),\n );\n }\n\n // transactionMode === \"drizzle\". Read-only work uses a deferred snapshot;\n // business transactions retain BEGIN IMMEDIATE for safe lock upgrades.\n return runWithSerializedQueue(\n serializedQueue,\n async () =>\n db.transaction(async (tx) => fn(bindTransactionBackend(tx), tx), {\n behavior:\n options?.accessMode === \"read_only\" || temporaryWrites ?\n \"deferred\"\n : \"immediate\",\n }) as Promise<T>,\n );\n },\n\n adoptTransaction(externalTx: AnySqliteDatabase): TransactionBackend {\n // #134: parity with Postgres. Cross-store atomicity needs real\n // rollback; on a \"none\" driver the caller's relational write\n // would commit with no way to undo the graph write. Refuse\n // loudly rather than silently degrade.\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"Cross-store atomicity is unavailable on this SQLite backend: \" +\n \"transactions are disabled (transactionMode: 'none'). Adopting \" +\n \"an external transaction here would let the caller's relational \" +\n \"write commit with no way to roll back the graph write. \" +\n \"Configure a driver that supports transactions (better-sqlite3, \" +\n \"libsql, bun:sqlite).\",\n );\n }\n assertAdoptedDialect<AnySqliteDatabase>(\n externalTx,\n BaseSQLiteDatabase,\n \"sqlite\",\n );\n // serializedQueue is deliberately NOT applied to an adopted tx: a\n // sync better-sqlite3 driver runs the adopted statements on the\n // caller's stack, so wrapping a caller-driven tx in our queue\n // could deadlock against the caller's outer `db.transaction(...)`.\n return bindTransactionBackend(externalTx);\n },\n\n close(): Promise<void> {\n serializedQueue?.dispose();\n return Promise.resolve();\n },\n };\n\n // INVARIANT: audit before any wrapper can observe this backend — see\n // transaction-resource.ts. Unconditional: an abstention recorded as\n // \"independent\" is a verdict the guards can tell apart from a backend nobody\n // looked at.\n auditBackendResource(backend, resourceAudit);\n\n return backend;\n}\n\nfunction createTransactionBackend(\n options: CreateSqliteTransactionBackendOptions,\n): InternalOperationBackend {\n const txExecutionAdapter =\n options.executionAdapter ??\n createSqliteExecutionAdapter(options.db, {\n profileHints: options.profileHints,\n });\n\n // The transaction-scoped backend shares the outer backend's\n // contribution materializer: the per-field vector table is provisioned\n // (DDL) only by the privileged outer backend, so a tx-scoped vector op\n // only ASSERTS the durable marker (SELECT, never DDL) and can't poison\n // anything on rollback. The shared per-instance cache means a slot\n // confirmed once stays a pure `Set.has` inside every later transaction.\n return createSqliteOperationBackend({\n capabilities: options.capabilities,\n db: options.db,\n executionAdapter: txExecutionAdapter,\n operationStrategy: options.operationStrategy,\n tableNames: options.tableNames,\n fulltextStrategy: options.fulltextStrategy,\n vectorStrategy: options.vectorStrategy,\n contributionMaterializer: options.contributionMaterializer,\n transactionScoped: true,\n });\n}\n\n// Re-export schema utilities\nexport type { SqliteTableNames, SqliteTables } from \"./schema/sqlite\";\nexport { createSqliteTables, tables } from \"./schema/sqlite\";\n"]}
@@ -1,12 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkOJHD3LXJ_cjs = require('./chunk-OJHD3LXJ.cjs');
4
-
5
- // src/query/dialect/vector/pagination.ts
6
- function vectorPageClause(limit, offset) {
7
- return offset === void 0 || offset === 0 ? chunkOJHD3LXJ_cjs.sql`LIMIT ${limit}` : chunkOJHD3LXJ_cjs.sql`LIMIT ${limit} OFFSET ${offset}`;
8
- }
9
-
10
- exports.vectorPageClause = vectorPageClause;
11
- //# sourceMappingURL=chunk-KWNWG4RC.cjs.map
12
- //# sourceMappingURL=chunk-KWNWG4RC.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/constraints/index.ts","../src/utils/tuple-key.ts","../src/store/claims/axis.ts"],"names":["readOwnProperty","ConfigurationError","hasOwnKey","isPresent","CardinalityError","EndpointError","DisjointError","compareStrings","sql"],"mappings":";;;;;;;;AAeA,IAAM,oBAAA,GAAuB,GAAA;AAG7B,IAAM,sBAAA,GAAyB,GAAA;AAuCxB,SAAS,gBAAA,CACd,KAAA,EACA,MAAA,EACA,SAAA,EACQ;AACR,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,GAAA,CAAI,CAAC,KAAA,KAAU;AACnC,IAAA,MAAM,KAAA,GAAQA,iCAAA,CAAgB,KAAA,EAAO,KAAK,CAAA;AAC1C,IAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AACzC,MAAA,OAAO,sBAAA;AAAA,IACT;AAEA,IAAA,MAAM,cACJ,OAAO,KAAA,KAAU,QAAA,GAAW,KAAA,GAC1B,OAAO,KAAA,KAAU,QAAA,IAAY,OAAO,KAAA,KAAU,YAC9C,KAAA,CAAM,QAAA,EAAS,GACf,IAAA,CAAK,UAAU,KAAK,CAAA;AACxB,IAAA,OAAO,SAAA,KAAc,iBAAA,GACjB,WAAA,CAAY,WAAA,EAAY,GACxB,WAAA;AAAA,EACN,CAAC,CAAA;AACD,EAAA,OAAO,MAAA,CAAO,KAAK,oBAAoB,CAAA;AACzC;AAqBO,SAAS,mBAAA,CACd,YACA,KAAA,EACS;AACT,EAAA,IAAI,CAAC,WAAW,KAAA,EAAO;AACrB,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,SAAA,GAAY,qBAAA,CAAsB,UAAA,CAAW,KAAK,CAAA;AACxD,EAAA,IAAI,cAAc,MAAA,EAAW;AAC3B,IAAA,MAAM,IAAIC,oCAAA;AAAA,MACR,CAAA,mBAAA,EAAsB,W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AA,IAAkB,EAAE,CAAA,IACpEA,gCAAA,CAAe,IAAA,CAAK,GAAA,EAAK,MAAM,GAAG,CAAA;AAEtC;AAiBO,SAAS,gBAAA,CAAiB,MAAkB,KAAA,EAA4B;AAC7E,EAAA,OACE,KAAK,MAAA,KAAW,KAAA,CAAM,MAAA,IAAU,IAAA,CAAK,iBAAiB,KAAA,CAAM,YAAA;AAEhE;AAaO,SAAS,cAAc,KAAA,EAA2B;AACvD,EAAA,OAAO,eAAe,CAAC,KAAA,CAAM,YAAA,EAAc,KAAA,CAAM,MAAM,CAAC,CAAA;AAC1D;AAmBO,SAAS,oBAAA,CACd,QAAA,EACA,QAAA,EACA,OAAA,EACK;AACL,EAAA,OAAOC,iBAAM,QAAA,CAAS,OAAA,CAAQ,MAAM,CAAC,CAAA,GAAA,EAAM,SAAS,OAAA,CAAQ,MAAM,CAAC,CAAA,KAAA,EAAQ,QAAA,CAAS,QAAQ,YAAY,CAAC,MAAM,QAAA,CAAS,OAAA,CAAQ,YAAY,CAAC,CAAA,CAAA;AAC/I","file":"chunk-LLVOQOWE.cjs","sourcesContent":["/**\n * Constraint validation module.\n *\n * Provides validation functions for enforcing graph constraints:\n * - Uniqueness constraints on node properties\n * - Cardinality constraints on edges\n * - Endpoint type constraints on edges\n * - Disjointness constraints between node kinds\n */\n\n/**\n * Separator used between field values in composite unique keys.\n * Uses ASCII Record Separator (0x1E) — valid UTF-8 and safe for PostgreSQL\n * TEXT columns (unlike \\0 which PostgreSQL rejects).\n */\nconst UNIQUE_KEY_SEPARATOR = \"\\u001E\";\n\n/** Marker for undefined/null field values in unique keys. */\nconst UNIQUE_KEY_NULL_MARKER = \"\\u001F\"; // ASCII Unit Separator\nimport {\n type Cardinality,\n type Collation,\n type EdgeRegistration,\n type NullCheckOp,\n type UniqueConstraint,\n type UniquenessScope,\n} from \"../core/types\";\nimport {\n CardinalityError,\n ConfigurationError,\n DisjointError,\n EndpointError,\n UniquenessError,\n} from \"../errors\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport { hasOwnKey, readOwnProperty } from \"../utils/object\";\nimport { isPresent } from \"../utils/presence\";\n\n// ============================================================\n// Uniqueness Validation\n// ============================================================\n\n/**\n * Computes the unique key for a node's uniqueness constraint.\n *\n * The key is built by concatenating the specified field values,\n * optionally normalized for case-insensitive comparison.\n *\n * Field values are read by declared OWN key ({@link readOwnProperty}): a\n * constraint may name a field that a props bag does not carry (an absent\n * optional field), and a plain `props[field]` read would answer such a field\n * with the inherited `Object.prototype` member when the field is named after\n * one. A constraint over a field named `toString` then keyed on the inherited\n * function — `\"\"` under `binary` (the function stringified and dropped by\n * `JSON.stringify`) and a `TypeError` under `caseInsensitive` — instead of the\n * null marker every other absent value gets.\n */\nexport function computeUniqueKey(\n props: Record<string, unknown>,\n fields: readonly string[],\n collation: Collation,\n): string {\n const values = fields.map((field) => {\n const value = readOwnProperty(props, field);\n if (value === undefined || value === null) {\n return UNIQUE_KEY_NULL_MARKER;\n }\n // Convert to string, handling primitives safely\n const stringValue =\n typeof value === \"string\" ? value\n : typeof value === \"number\" || typeof value === \"boolean\" ?\n value.toString()\n : JSON.stringify(value);\n return collation === \"caseInsensitive\" ?\n stringValue.toLowerCase()\n : stringValue;\n });\n return values.join(UNIQUE_KEY_SEPARATOR);\n}\n\n/**\n * Checks if a uniqueness constraint's where predicate passes.\n *\n * A `where` callback that does not return a predicate is REFUSED here, not\n * treated as \"the constraint always applies\". The same malformed clause is a\n * hard `ConfigurationError` at definition time ({@link assertWhereFieldDeclared})\n * and at persistence time (`serializeWherePredicate`); a third reading that\n * silently widened a partial constraint to a total one would let the three\n * sites disagree about the same clause — the divergence\n * {@link captureWherePredicate} exists to prevent.\n *\n * The arm SHOULD be unreachable: `defineGraph` refuses a non-predicate callback\n * before any write can evaluate it, `validateGraphExtension` refuses the\n * document form, and a constraint reconstructed from a persisted schema carries\n * a callback this module built itself. It is reachable only by handing the\n * store a constraint object that never passed a definition gate — for which\n * failing loudly is the correct answer, since the alternative is enforcing\n * uniqueness over rows the author meant to exclude.\n */\nexport function checkWherePredicate(\n constraint: UniqueConstraint,\n props: Record<string, unknown>,\n): boolean {\n if (!constraint.where) {\n return true; // No where clause, always applies\n }\n\n const predicate = captureWherePredicate(constraint.where);\n if (predicate === undefined) {\n throw new ConfigurationError(\n `Unique constraint \"${constraint.name}\" has a \\`where\\` callback that does not return a predicate.`,\n { constraintName: constraint.name, fields: [...constraint.fields] },\n {\n suggestion: `Return a field predicate, e.g. \\`where: (fields) => fields.${constraint.fields[0] ?? \"someField\"}.isNotNull()\\`. A constraint built outside \\`defineGraph\\` bypasses the definition-time check that normally reports this.`,\n },\n );\n }\n\n return evaluatePredicate(predicate, props);\n}\n\ntype UniquePredicate = Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: NullCheckOp;\n}>;\n\n/**\n * The `where` callback as every caller of {@link captureWherePredicate} sees it:\n * a per-field builder in, whatever the author returned out.\n *\n * Deliberately looser than `UniqueConstraint[\"where\"]`, whose builder type is\n * generic in the kind's schema — the capture is the same operation whether the\n * callback came from a typed `defineGraph` registration, a compiled\n * graph-extension document, or an untyped JavaScript caller.\n */\ntype UniqueWhereCallback = (\n builder: Readonly<\n Record<\n string,\n Readonly<{\n isNull: () => UniquePredicate;\n isNotNull: () => UniquePredicate;\n }>\n >\n >,\n) => unknown;\n\n/**\n * Runs a `where` callback against the shared builder and returns the predicate\n * it named, or `undefined` when the callback returned something that is not a\n * predicate.\n *\n * The single owner of \"what does this `where` clause say\": constraint\n * EVALUATION ({@link checkWherePredicate}), definition-time VALIDATION\n * ({@link assertWhereFieldDeclared}), and persistence-time CAPTURE\n * (`serializeWherePredicate` in src/schema/serializer.ts) all read the clause\n * through this one function, so a persisted `where`, a validated `where`, and\n * an evaluated `where` cannot disagree about which field the author named.\n */\nexport function captureWherePredicate(\n where: UniqueWhereCallback,\n): UniquePredicate | undefined {\n const predicate = where(buildPredicateContext());\n if (\n typeof predicate !== \"object\" ||\n predicate === null ||\n !(\"__type\" in predicate)\n ) {\n return undefined;\n }\n\n const candidate = predicate as {\n __type: unknown;\n field: unknown;\n op: unknown;\n };\n if (\n candidate.__type !== \"unique_predicate\" ||\n typeof candidate.field !== \"string\" ||\n (candidate.op !== \"isNull\" && candidate.op !== \"isNotNull\")\n ) {\n return undefined;\n }\n\n return {\n __type: \"unique_predicate\",\n field: candidate.field,\n op: candidate.op,\n };\n}\n\n/**\n * Refuses a uniqueness constraint whose `where` clause names a field the kind\n * does not declare.\n *\n * The runtime half of the builder's guard. {@link buildPredicateContext} is\n * total by design — it must answer for a DECLARED-but-absent field, which is\n * the whole point of a partial constraint — so a typo'd name cannot be caught\n * there, and the type system catches it only for typed callers\n * (`UniqueConstraintPredicateBuilder` declares exactly the schema's fields and\n * has no index signature). An untyped caller naming an undeclared field\n * otherwise gets a predicate that quietly never applies.\n *\n * Called once per constraint at graph-definition time — the single point every\n * constraint passes through before any write can evaluate it — rather than at\n * each of the write paths' `checkWherePredicate` call sites, so the refusal\n * covers every path uniformly and costs nothing per write. Mirrors\n * `validateGraphExtension`'s `UNKNOWN_UNIQUE_WHERE_FIELD` refusal, which\n * already holds the same invariant for kinds declared as JSON documents.\n */\nexport function assertWhereFieldDeclared(\n kind: string,\n constraint: UniqueConstraint,\n shape: Readonly<Record<string, unknown>>,\n): void {\n if (!constraint.where) return;\n\n const predicate = captureWherePredicate(constraint.where);\n if (predicate === undefined) {\n throw new ConfigurationError(\n `Unique constraint \"${constraint.name}\" on node kind \"${kind}\" has a \\`where\\` callback that does not return a predicate.`,\n { kind, constraintName: constraint.name },\n {\n suggestion: `Return a field predicate, e.g. \\`where: (fields) => fields.${Object.keys(shape)[0] ?? \"someField\"}.isNotNull()\\`.`,\n },\n );\n }\n\n if (!hasOwnKey(shape, predicate.field)) {\n throw new ConfigurationError(\n `Unique constraint \"${constraint.name}\" on node kind \"${kind}\" has a \\`where\\` clause on field \"${predicate.field}\", which is not declared in the kind's schema.`,\n {\n kind,\n constraintName: constraint.name,\n field: predicate.field,\n declaredFields: Object.keys(shape),\n },\n {\n suggestion: `Name a declared field (${Object.keys(shape).join(\", \")}) or add \"${predicate.field}\" to the schema.`,\n },\n );\n }\n}\n\ntype PredicateContext = Readonly<\n Record<\n string,\n Readonly<{\n isNull: () => UniquePredicate;\n isNotNull: () => UniquePredicate;\n }>\n >\n>;\n\n/**\n * Builds the context a constraint's `where` callback names fields on.\n *\n * EVERY field name gets a member, because the builder type declares every\n * schema field as required (`-?` in `UniqueConstraintPredicateBuilder`) —\n * precisely so a partial constraint can ask whether an OPTIONAL field is\n * present. Populating the context from the props bag's own keys instead left a\n * declared-but-absent field with no member, and the callback's access then hit\n * whatever the context's prototype offered: `Object.prototype.toString` for a\n * field named `toString` (so naming it threw \"isNull is not a function\"), and\n * `undefined` for an ordinary field (so the everyday partial constraint over\n * `externalId` threw — \"Cannot read properties of undefined\", or \"Expected a\n * defined value\" through `requireDefined` — for every node written without it).\n *\n * Answering every name is safe because a name comes from the predicate author\n * (the code), never from data, and the field's VALUE is still read from the\n * props bag by own key when the predicate is evaluated — so an absent field\n * evaluates as null, which is what a partial constraint means by absent. Every\n * reader of a `where` clause goes through {@link captureWherePredicate}, which\n * builds this one context, so a persisted `where`, a validated `where`, and an\n * evaluated `where` cannot see different builders.\n *\n * The guard against a TYPO'D field name is NOT this Proxy — it must stay total\n * or a declared-but-absent field loses its member. It is\n * {@link assertWhereFieldDeclared}, which every constraint passes at\n * graph-definition time: an undeclared name is refused there with a typed\n * `ConfigurationError`, so no `where` clause naming one ever reaches\n * evaluation, from a typed or an untyped caller.\n */\nfunction buildPredicateContext(): PredicateContext {\n return new Proxy<PredicateContext>(\n {},\n {\n get(_target, property) {\n if (typeof property === \"symbol\") return;\n return {\n isNull: () => ({\n __type: \"unique_predicate\" as const,\n field: property,\n op: \"isNull\" as const,\n }),\n isNotNull: () => ({\n __type: \"unique_predicate\" as const,\n field: property,\n op: \"isNotNull\" as const,\n }),\n };\n },\n },\n );\n}\n\n/**\n * Evaluates a uniqueness predicate.\n *\n * Takes a CAPTURED predicate, not an `unknown`: the \"is this really a\n * predicate?\" question belongs to {@link captureWherePredicate}, which is its\n * single owner. The defensive `return true` arms this function used to carry\n * were a second, quieter answer to that question — and they answered it the\n * opposite way, widening a partial constraint into a total one where the owner\n * refuses.\n */\nfunction evaluatePredicate(\n pred: UniquePredicate,\n props: Record<string, unknown>,\n): boolean {\n // Own-key read: `pred.field` is a schema field name, and a props bag that\n // does not carry it must read as absent rather than as the inherited\n // `Object.prototype` member a field named after one would otherwise find\n // (which reads as present, inverting both `isNull` and `isNotNull`).\n const value = readOwnProperty(props, pred.field);\n if (pred.op === \"isNull\") {\n return value === null || value === undefined;\n }\n return isPresent(value);\n}\n\n/**\n * Gets all kinds that should be checked for a uniqueness constraint.\n *\n * For \"kindWithSubClasses\" scope, includes the entire subclass hierarchy:\n * - The kind itself\n * - All ancestors (parent classes)\n * - All descendants of those ancestors (sibling classes)\n *\n * For \"kind\" scope, only the specific kind.\n */\nexport function getKindsForUniquenessCheck(\n baseKind: string,\n scope: UniquenessScope,\n registry: KindRegistry,\n): readonly string[] {\n if (scope === \"kind\") {\n return [baseKind];\n }\n\n // Get the entire connected subclass hierarchy by finding the root ancestor\n const root = findRootAncestor(baseKind, registry);\n\n // Return the root and all its descendants (which includes baseKind and siblings)\n return registry.expandSubClasses(root);\n}\n\n/**\n * THE definition of \"which kinds a `kindWithSubClasses` scope covers\": the\n * registry's precomputed connected component of the UNDIRECTED `subClassOf`\n * graph containing `kind`, in code-point order.\n *\n * Kind-independent by construction — every member of a component computes the\n * same set — which is what makes a claim axis folded from it deterministic: two\n * writers of two different kinds in one hierarchy reserve the SAME row, so the\n * uniques primary key fences them against each other.\n *\n * {@link getKindsForUniquenessCheck} is deliberately NOT folded into this: it\n * walks one root's descendants, so on a multi-root hierarchy (`Employee`\n * subclassing both `Alpha` and `Zeta`) it answers differently depending on which\n * member asks, and a fold of a kind-dependent set cannot be a canonical axis.\n * This is the documented intent of that function, so the component is a superset\n * of the set it walks: the fence is never weaker than the probe, and is stronger\n * in exactly the multi-root case where the probe is inconsistent.\n */\nexport function subClassComponent(\n kind: string,\n registry: KindRegistry,\n): readonly string[] {\n return registry.getSubClassComponent(kind);\n}\n\n/**\n * Finds the topmost ancestor of a kind, or the kind itself if it has no ancestors.\n */\nfunction findRootAncestor(kind: string, registry: KindRegistry): string {\n const ancestors = registry.getAncestors(kind);\n\n if (ancestors.size === 0) {\n return kind;\n }\n\n // Find an ancestor with no ancestors (the root)\n for (const ancestor of ancestors) {\n if (registry.getAncestors(ancestor).size === 0) {\n return ancestor;\n }\n }\n\n // If all ancestors have ancestors, recurse up\n const firstAncestor = [...ancestors][0];\n return firstAncestor ? findRootAncestor(firstAncestor, registry) : kind;\n}\n\n/**\n * Creates a uniqueness error.\n */\nexport function createUniquenessError(\n constraintName: string,\n kind: string,\n existingId: string,\n newId: string,\n fields: readonly string[],\n): UniquenessError {\n return new UniquenessError({\n constraintName,\n kind,\n existingId,\n newId,\n fields: [...fields],\n });\n}\n\n// ============================================================\n// Cardinality Validation\n// ============================================================\n\n/**\n * Checks if adding an edge would violate cardinality constraints.\n *\n * @param edgeKind - The edge kind being added\n * @param fromKind - The source node kind\n * @param fromId - The source node ID\n * @param cardinality - The cardinality constraint\n * @param existingEdgeCount - Number of existing edges of this kind from this source\n * @param hasActiveEdge - Whether there's an active (valid_to IS NULL) edge\n * @returns Error if violation, undefined if valid\n */\nexport function checkCardinality(\n edgeKind: string,\n fromKind: string,\n fromId: string,\n cardinality: Cardinality,\n existingEdgeCount: number,\n hasActiveEdge: boolean,\n): CardinalityError | undefined {\n switch (cardinality) {\n case \"many\": {\n // No constraint\n return undefined;\n }\n case \"one\": {\n // At most one edge of this kind from any source node\n if (existingEdgeCount > 0) {\n return new CardinalityError({\n edgeKind,\n fromKind,\n fromId,\n cardinality: \"one\",\n existingCount: existingEdgeCount,\n });\n }\n return undefined;\n }\n case \"unique\": {\n // unique is checked separately per (source, target) pair\n return undefined;\n }\n case \"oneActive\": {\n // At most one edge with valid_to IS NULL from any source\n if (hasActiveEdge) {\n return new CardinalityError({\n edgeKind,\n fromKind,\n fromId,\n cardinality: \"oneActive\",\n existingCount: 1,\n });\n }\n return undefined;\n }\n }\n}\n\n/**\n * Checks unique edge constraint (at most one edge between any source-target pair).\n */\nexport function checkUniqueEdge(\n edgeKind: string,\n fromKind: string,\n fromId: string,\n _toKind: string,\n _toId: string,\n existingCount: number,\n): CardinalityError | undefined {\n if (existingCount > 0) {\n return new CardinalityError({\n edgeKind,\n fromKind,\n fromId,\n cardinality: \"unique\",\n existingCount,\n });\n }\n return undefined;\n}\n\n// ============================================================\n// Endpoint Validation\n// ============================================================\n\n/**\n * Validates that an edge's endpoints are valid node kinds.\n */\nexport function validateEdgeEndpoints(\n edgeKind: string,\n fromKind: string,\n toKind: string,\n registration: EdgeRegistration,\n registry: KindRegistry,\n): EndpointError | undefined {\n // Check from kinds\n const validFromKinds = registration.from.map((node) => node.kind);\n if (!registry.isAssignableToAny(fromKind, validFromKinds)) {\n return new EndpointError({\n edgeKind,\n endpoint: \"from\",\n actualKind: fromKind,\n expectedKinds: validFromKinds,\n });\n }\n\n // Check to kinds\n const validToKinds = registration.to.map((node) => node.kind);\n if (!registry.isAssignableToAny(toKind, validToKinds)) {\n return new EndpointError({\n edgeKind,\n endpoint: \"to\",\n actualKind: toKind,\n expectedKinds: validToKinds,\n });\n }\n\n return undefined;\n}\n\n// ============================================================\n// Disjointness Validation\n// ============================================================\n\n/**\n * Checks if creating a node would violate disjointness constraints.\n *\n * @param nodeId - The node ID being created\n * @param nodeKind - The kind of the new node\n * @param existingKinds - Kinds of existing nodes with the same ID\n * @param registry - The kind registry for disjointness checks\n * @returns Error if disjoint violation, undefined if valid\n */\nexport function checkDisjointness(\n nodeId: string,\n nodeKind: string,\n existingKinds: readonly string[],\n registry: KindRegistry,\n): DisjointError | undefined {\n for (const existingKind of existingKinds) {\n if (registry.areDisjoint(nodeKind, existingKind)) {\n return new DisjointError({\n nodeId,\n attemptedKind: nodeKind,\n conflictingKind: existingKind,\n });\n }\n }\n return undefined;\n}\n\n/**\n * Gets all disjoint kinds for a given kind.\n */\nexport function getDisjointKinds(\n kind: string,\n registry: KindRegistry,\n): readonly string[] {\n return registry.getDisjointKinds(kind);\n}\n","/**\n * Encodes an ordered tuple of strings as an injective map key.\n *\n * Delimiter joins are unsafe because every delimiter is also a legal value\n * character. JSON's string-array grammar preserves both field boundaries and\n * string contents, so distinct tuples cannot collapse onto the same key.\n */\nexport function encodeTupleKey(values: readonly string[]): string {\n return JSON.stringify(values);\n}\n","/**\n * Claim axis vocabulary.\n *\n * A declared constraint is a CLAIM on an AXIS: the value bound to a claim row's\n * `node_kind` column, which is what the relation's primary key fences on. The\n * axis is not always a kind — it is whatever set of kinds the constraint spans —\n * and deciding it is this module's only job, so no write path spells its own.\n *\n * The other half of a claim row is its OWNER, `(concrete_kind, node_id)`. Ids\n * are unique only per kind, so an id alone cannot answer \"is this row mine?\":\n * `Employee \"X\"` and `Contractor \"X\"` are two rows under the nodes primary key\n * and would read as one owner. The predicate lives here once, in the two\n * renderings the code needs (TypeScript and SQL), so a claim's accept/refuse\n * verdict cannot differ between the layer that probes it and the layer that\n * writes it.\n */\nimport { type Column, type SQL, sql } from \"drizzle-orm\";\n\nimport { subClassComponent } from \"../../constraints\";\nimport { type UniquenessScope } from \"../../core/types\";\nimport { ConfigurationError } from \"../../errors\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport { compareStrings } from \"../../utils/compare\";\nimport { encodeTupleKey } from \"../../utils/tuple-key\";\n\n/**\n * The one code point an axis component may not contain, written as an escape\n * so it can never be mistaken for whitespace in a diff.\n *\n * Axes that are not kinds are built by joining with it — the disjointness pair\n * axis below is the first — so a kind or constraint name containing it could\n * spell a reserved axis and take a claim row the fence assigns to something\n * else. {@link assertClaimAxisSafe} is what makes that unspellable, at\n * graph-definition time.\n */\nconst AXIS_SEPARATOR = \"\\u001E\";\n\n/** The prefix marking an axis as a disjoint PAIR rather than as a kind. */\nconst DISJOINT_AXIS_PREFIX = `${AXIS_SEPARATOR}disjoint${AXIS_SEPARATOR}`;\n\n/**\n * The `constraint_name` every disjointness claim is written under.\n *\n * Reserved rather than derived: it is what tells the claim seam that a refusal\n * on this row is a `DisjointError` and not a `UniquenessError`, and what tells\n * a reader of the relation that this row's `node_kind` is a pair label rather\n * than a kind. {@link assertClaimAxisSafe} is what guarantees no declared\n * constraint can carry the same name.\n */\nexport const DISJOINT_CONSTRAINT_NAME = `${AXIS_SEPARATOR}disjointWith`;\n\n/**\n * THE axis a disjointness claim is written at: the registry's own canonical\n * pair label, prefixed so it cannot collide with a kind.\n *\n * A fold of `KindRegistry.disjointPairLabel` rather than a second\n * normalization of the same pair — the two kinds of one disjoint pair must\n * compute ONE string, or their claims sit on two rows that can never collide\n * and the fence refuses nothing.\n *\n * Pairwise, and deliberately not per component: the registry's disjoint pairs\n * are literal unordered pairs and disjointness is not transitive here, so an\n * axis keyed on a connected component would refuse an `A`/`C` pair under\n * `A⊥B, B⊥C` that the graph never declared disjoint.\n */\nexport function disjointnessClaimAxis(\n kind: string,\n otherKind: string,\n registry: KindRegistry,\n): string {\n return `${DISJOINT_AXIS_PREFIX}${registry.disjointPairLabel(kind, otherKind)}`;\n}\n\n/**\n * Refuses a kind name or constraint name that could spell a reserved claim\n * axis or the reserved disjointness constraint name.\n *\n * Runs at graph-definition time, the one gate every kind and every declared\n * constraint passes before a claim can be written for it — so the reserved\n * vocabulary is unspellable by construction rather than re-checked at each\n * write, and the claim seam can read \"this refusal is a disjointness refusal\"\n * off the reserved constraint name without a caller being able to forge it. A\n * new refusal, on an input no real schema carries.\n *\n * `subject` names the ROLE (`Node kind`, `Unique constraint`); the name itself\n * is quoted through `JSON.stringify` so the offending code point reads as an\n * escape instead of as an invisible character.\n */\nexport function assertClaimAxisSafe(name: string, subject: string): void {\n if (!name.includes(AXIS_SEPARATOR)) return;\n throw new ConfigurationError(\n `${subject} name ${JSON.stringify(name)} contains U+001E, which TypeGraph reserves for claim axes.`,\n { name },\n {\n suggestion: `Rename it without the U+001E (record separator) character.`,\n },\n );\n}\n\n/**\n * WHERE a uniqueness claim for this kind and scope is written, and whether that\n * target spans kinds beyond the writer's own.\n *\n * Both facts come out of one computation on purpose. The axis is the code-point\n * minimum of the set the scope covers, and \"does this site also need the\n * per-graph write lock?\" is that same set having more than one member — so a\n * caller cannot pick up one without the other, and the lock trigger cannot\n * drift away from the claim target. Asking the covered SET rather than the\n * scope token is what keeps a `kindWithSubClasses` constraint on a kind with no\n * hierarchy classified like the `kind` scope it is equivalent to.\n */\nexport type UniquenessClaimTarget = Readonly<{\n axis: string;\n crossKind: boolean;\n}>;\n\n/** The kinds one uniqueness claim axis spans, in canonical order. */\nfunction uniquenessClaimKinds(\n kind: string,\n scope: UniquenessScope,\n registry: KindRegistry,\n): readonly string[] {\n return scope === \"kind\" ? [kind] : subClassComponent(kind, registry);\n}\n\n/** THE decision above — the one owner of both readings. */\nexport function uniquenessClaimTarget(\n kind: string,\n scope: UniquenessScope,\n registry: KindRegistry,\n): UniquenessClaimTarget {\n const kinds = uniquenessClaimKinds(kind, scope, registry);\n return { axis: kinds[0] ?? kind, crossKind: kinds.length > 1 };\n}\n\n/**\n * THE axis a uniqueness claim is written at: the kind itself for\n * `scope: \"kind\"`, and the code-point minimum of the subclass component for\n * `scope: \"kindWithSubClasses\"`.\n *\n * The minimum is a fold of a kind-independent set, so every kind in one\n * hierarchy folds to the same axis and their claims collide on the uniques\n * primary key — which is the whole fence. Reserving under each writer's own\n * kind (what this replaces) put sibling kinds in rows that can never collide.\n */\nexport function uniquenessClaimAxis(\n kind: string,\n scope: UniquenessScope,\n registry: KindRegistry,\n): string {\n return uniquenessClaimTarget(kind, scope, registry).axis;\n}\n\n/**\n * THE order a uniqueness probe reads claim rows in: the axis first, then every\n * remaining kind the scope covers, in code-point order.\n *\n * Two things make this list wider than the axis alone and narrower than\n * arbitrary:\n *\n * - The axis is where this version writes, so it is read first.\n * - Rows written before the axis move sit under their own concrete kind, so the\n * probe visits the full undirected component, including every root of a\n * multi-root hierarchy. That is what makes the axis move need no data\n * migration.\n *\n * The remainder is sorted rather than left in registry-iteration order so two\n * processes reading the same scope read it in the same order.\n */\nexport function uniquenessProbeKinds(\n kind: string,\n scope: UniquenessScope,\n registry: KindRegistry,\n): readonly string[] {\n const axis = uniquenessClaimAxis(kind, scope, registry);\n const coveredKinds = uniquenessClaimKinds(kind, scope, registry);\n const rest = coveredKinds\n .filter((candidate) => candidate !== axis)\n .toSorted((left, right) => compareStrings(left, right));\n return [axis, ...rest];\n}\n\n/**\n * THE axis an edge cardinality claim is written at: the declared cardinality\n * and the edge kind, which together name the population the constraint counts.\n *\n * `one` and `oneActive` on one kind are DIFFERENT axes on purpose — they count\n * different populations (every live edge from a source vs every active one) —\n * so a kind whose declaration changed cannot inherit rows the old declaration\n * wrote. The cardinality tokens contain no `:`, so the pair is injective over\n * arbitrary edge kind names.\n */\nexport function edgeCardinalityAxis(\n cardinality: string,\n edgeKind: string,\n): string {\n return `${cardinality}:${edgeKind}`;\n}\n\n/** The relation a claim row lives in. */\ntype ClaimRelation = \"uniques\" | \"edgeClaims\";\n\n/** A claim row named in full — the row a statement is about to lock. */\nexport type ClaimTarget = Readonly<{\n relation: ClaimRelation;\n graphId: string;\n axis: string;\n /**\n * `uniques.constraint_name`. The edge claim relation keys on\n * `(graph_id, axis, key)` and has no such column, so its targets omit it and\n * sort as the empty string. Absent means \"this relation does not key on a\n * constraint name\", never \"not known yet\".\n */\n constraintName?: string;\n key: string;\n}>;\n\n/**\n * THE canonical order claims are acquired in: code-point compare on\n * `(relation, graphId, axis, constraintName, key)`.\n *\n * Two writers that take the same two claim rows in opposite orders deadlock,\n * and PostgreSQL resolves that by aborting one with `40P01` — which would turn\n * an import's per-row recovery into a whole-batch abort. Sorting every claim\n * statement's entries by one comparator removes the commonest cycle, exactly as\n * multi-graph lock acquisition already does (see `recorded-capture.ts`, whose\n * comment states the same rule: every process must acquire in the same order).\n *\n * The order it establishes is per claim SET and per statement, not per\n * transaction: rows and batches inside one import claim in input order, so two\n * concurrent lock-free imports into one graph can still deadlock. That residual\n * is declared out of contract rather than fenced here.\n */\nexport function compareClaimTargets(\n left: ClaimTarget,\n right: ClaimTarget,\n): number {\n return (\n compareStrings(left.relation, right.relation) ||\n compareStrings(left.graphId, right.graphId) ||\n compareStrings(left.axis, right.axis) ||\n compareStrings(left.constraintName ?? \"\", right.constraintName ?? \"\") ||\n compareStrings(left.key, right.key)\n );\n}\n\n/**\n * WHO holds a claim. A node, not an id: ids are unique only per kind, so\n * `(concrete_kind, node_id)` is the smallest thing that identifies a claimant.\n */\nexport type ClaimOwner = Readonly<{ concreteKind: string; nodeId: string }>;\n\n/**\n * THE ownership predicate. Every reader of \"is this claim row mine?\" calls it —\n * the probe, the single-row upsert's verdict, the batch upsert's verdict, and\n * the batch-validation cache's pending answer.\n *\n * Comparing ids alone accepts a claim held by a namesake under another kind,\n * which is precisely the collision `disjointWith` forbids and precisely the one\n * a shared uniqueness scope exists to catch.\n */\nexport function isSameClaimOwner(left: ClaimOwner, right: ClaimOwner): boolean {\n return (\n left.nodeId === right.nodeId && left.concreteKind === right.concreteKind\n );\n}\n\n/**\n * THE Set/Map key rendering of {@link isSameClaimOwner}, for a path that decides\n * ownership against MANY owners at once rather than pairwise.\n *\n * `encodeTupleKey`, not a delimiter join: kind names are constrained but node\n * ids are arbitrary caller data, and a delimiter a value may contain would make\n * two different owners collapse onto one key — which, where this is used, would\n * silently whitelist a foreign owner. Third rendering of one predicate, in the\n * module that owns it and beside {@link claimOwnerMatchesSql}: keys are equal\n * exactly when `isSameClaimOwner` holds and exactly when the SQL matches.\n */\nexport function claimOwnerKey(owner: ClaimOwner): string {\n return encodeTupleKey([owner.concreteKind, owner.nodeId]);\n}\n\n/** The owner columns of the uniques relation, as the SQL renderer needs them. */\nexport type ClaimOwnerColumns = Readonly<{\n nodeId: Column;\n concreteKind: Column;\n}>;\n\n/**\n * THE SQL rendering of {@link isSameClaimOwner}, for the two upsert builders.\n *\n * `existing` qualifies a column of the conflicting row the way the dialect\n * requires (PostgreSQL needs the table name, SQLite takes the bare quoted\n * column); `proposed` renders the value being claimed — a bound parameter for\n * the single-row builder, an `excluded.` reference for the batch one. Two\n * renderings, one definition: the arms both builders decide ownership with are\n * this fragment, so a builder cannot quietly compare fewer columns than the\n * TypeScript predicate does.\n */\nexport function claimOwnerMatchesSql(\n existing: (column: Column) => SQL,\n proposed: (column: Column) => SQL,\n columns: ClaimOwnerColumns,\n): SQL {\n return sql`${existing(columns.nodeId)} = ${proposed(columns.nodeId)} AND ${existing(columns.concreteKind)} = ${proposed(columns.concreteKind)}`;\n}\n"]}