@nicia-ai/typegraph 0.34.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/dist/backend/postgres/index.cjs +29 -29
  2. package/dist/backend/postgres/index.d.cts +39 -7
  3. package/dist/backend/postgres/index.d.ts +39 -7
  4. package/dist/backend/postgres/index.js +16 -16
  5. package/dist/backend/postgres/pglite.cjs +21 -21
  6. package/dist/backend/postgres/pglite.d.cts +4 -4
  7. package/dist/backend/postgres/pglite.d.ts +4 -4
  8. package/dist/backend/postgres/pglite.js +16 -16
  9. package/dist/backend/sqlite/index.cjs +25 -26
  10. package/dist/backend/sqlite/index.d.cts +8 -8
  11. package/dist/backend/sqlite/index.d.ts +8 -8
  12. package/dist/backend/sqlite/index.js +13 -14
  13. package/dist/backend/sqlite/libsql.cjs +19 -19
  14. package/dist/backend/sqlite/libsql.d.cts +4 -4
  15. package/dist/backend/sqlite/libsql.d.ts +4 -4
  16. package/dist/backend/sqlite/libsql.js +15 -15
  17. package/dist/backend/sqlite/local.cjs +101 -21
  18. package/dist/backend/sqlite/local.cjs.map +1 -1
  19. package/dist/backend/sqlite/local.d.cts +95 -5
  20. package/dist/backend/sqlite/local.d.ts +95 -5
  21. package/dist/backend/sqlite/local.js +95 -16
  22. package/dist/backend/sqlite/local.js.map +1 -1
  23. package/dist/{chunk-T6SPUYLX.cjs → chunk-2THZ3TQI.cjs} +116 -10
  24. package/dist/chunk-2THZ3TQI.cjs.map +1 -0
  25. package/dist/{chunk-UJLOZYKT.cjs → chunk-456Z2U7Y.cjs} +441 -115
  26. package/dist/chunk-456Z2U7Y.cjs.map +1 -0
  27. package/dist/chunk-4BCU6VFZ.cjs +100 -0
  28. package/dist/chunk-4BCU6VFZ.cjs.map +1 -0
  29. package/dist/chunk-4BMPGT35.cjs +12 -0
  30. package/dist/{chunk-HMFK4BXR.cjs.map → chunk-4BMPGT35.cjs.map} +1 -1
  31. package/dist/chunk-4CAXEB2F.cjs +1366 -0
  32. package/dist/chunk-4CAXEB2F.cjs.map +1 -0
  33. package/dist/{chunk-RY2VIWAM.js → chunk-4GX2JJXS.js} +355 -32
  34. package/dist/chunk-4GX2JJXS.js.map +1 -0
  35. package/dist/{chunk-GQANNXXT.cjs → chunk-5A6FNS6N.cjs} +75 -20
  36. package/dist/chunk-5A6FNS6N.cjs.map +1 -0
  37. package/dist/{chunk-3Z6TW3CT.cjs → chunk-5AQIKK56.cjs} +65 -25
  38. package/dist/chunk-5AQIKK56.cjs.map +1 -0
  39. package/dist/{chunk-WLRIWYHQ.js → chunk-5DIPR3L3.js} +2145 -1937
  40. package/dist/chunk-5DIPR3L3.js.map +1 -0
  41. package/dist/{chunk-BVTWD66D.js → chunk-5SEGFTZX.js} +3 -3
  42. package/dist/{chunk-BVTWD66D.js.map → chunk-5SEGFTZX.js.map} +1 -1
  43. package/dist/{chunk-A7SZZFAG.js → chunk-5VTR2F2K.js} +452 -109
  44. package/dist/chunk-5VTR2F2K.js.map +1 -0
  45. package/dist/{chunk-JJRCLAUN.cjs → chunk-5W4L6DLF.cjs} +116 -10
  46. package/dist/chunk-5W4L6DLF.cjs.map +1 -0
  47. package/dist/{chunk-6GNSY7AV.js → chunk-6FR2MMS6.js} +7 -7
  48. package/dist/chunk-6FR2MMS6.js.map +1 -0
  49. package/dist/{chunk-3BRVBQQD.cjs → chunk-7BQLPXK6.cjs} +2648 -2440
  50. package/dist/chunk-7BQLPXK6.cjs.map +1 -0
  51. package/dist/chunk-7YSP4V4R.cjs +69 -0
  52. package/dist/chunk-7YSP4V4R.cjs.map +1 -0
  53. package/dist/chunk-A42GCBGX.cjs +28 -0
  54. package/dist/chunk-A42GCBGX.cjs.map +1 -0
  55. package/dist/{chunk-ZV5N4DBG.js → chunk-BJVEU3ZL.js} +300 -58
  56. package/dist/chunk-BJVEU3ZL.js.map +1 -0
  57. package/dist/chunk-BYPOGQWK.js +25 -0
  58. package/dist/chunk-BYPOGQWK.js.map +1 -0
  59. package/dist/chunk-CUHM5CWJ.cjs +12 -0
  60. package/dist/chunk-CUHM5CWJ.cjs.map +1 -0
  61. package/dist/{chunk-2JXB3NYJ.cjs → chunk-D7ZEOS56.cjs} +25 -32
  62. package/dist/chunk-D7ZEOS56.cjs.map +1 -0
  63. package/dist/chunk-DFVLCOP6.js +10 -0
  64. package/dist/chunk-DFVLCOP6.js.map +1 -0
  65. package/dist/{chunk-JIEJCTDS.cjs → chunk-DIK74MXX.cjs} +37 -4
  66. package/dist/chunk-DIK74MXX.cjs.map +1 -0
  67. package/dist/chunk-DN5VP4JC.js +1343 -0
  68. package/dist/chunk-DN5VP4JC.js.map +1 -0
  69. package/dist/chunk-EOLERH7Y.cjs +40 -0
  70. package/dist/chunk-EOLERH7Y.cjs.map +1 -0
  71. package/dist/{chunk-TGJE22RM.cjs → chunk-FACJJWGF.cjs} +24 -6
  72. package/dist/chunk-FACJJWGF.cjs.map +1 -0
  73. package/dist/{chunk-WVC2Q2FD.cjs → chunk-FN35DLCN.cjs} +31 -9
  74. package/dist/chunk-FN35DLCN.cjs.map +1 -0
  75. package/dist/{chunk-KUTNI6SI.js → chunk-FPIZFYHE.js} +10 -18
  76. package/dist/chunk-FPIZFYHE.js.map +1 -0
  77. package/dist/{chunk-VCGO4V26.js → chunk-FRV5Q5IO.js} +64 -9
  78. package/dist/chunk-FRV5Q5IO.js.map +1 -0
  79. package/dist/{chunk-K5P5OZXS.js → chunk-G6Q5UM7U.js} +2 -2
  80. package/dist/{chunk-K5P5OZXS.js.map → chunk-G6Q5UM7U.js.map} +1 -1
  81. package/dist/{chunk-JQGIPGVL.cjs → chunk-H7YNSMA7.cjs} +43 -2
  82. package/dist/chunk-H7YNSMA7.cjs.map +1 -0
  83. package/dist/chunk-HW3LW7DH.cjs +1271 -0
  84. package/dist/chunk-HW3LW7DH.cjs.map +1 -0
  85. package/dist/{chunk-V3QNTB7Z.js → chunk-IU46OHVW.js} +194 -114
  86. package/dist/chunk-IU46OHVW.js.map +1 -0
  87. package/dist/{chunk-HK5SATYM.cjs → chunk-J3LEGNQB.cjs} +16 -109
  88. package/dist/chunk-J3LEGNQB.cjs.map +1 -0
  89. package/dist/{chunk-ZP5WHI4C.cjs → chunk-JFMEONLG.cjs} +358 -116
  90. package/dist/chunk-JFMEONLG.cjs.map +1 -0
  91. package/dist/{chunk-2MRAX3UE.js → chunk-JFUPDJXD.js} +47 -4
  92. package/dist/chunk-JFUPDJXD.js.map +1 -0
  93. package/dist/{chunk-Z5XBMDXU.js → chunk-KBGQIPRQ.js} +42 -3
  94. package/dist/chunk-KBGQIPRQ.js.map +1 -0
  95. package/dist/{chunk-K2TGS3EN.js → chunk-M75SUBFG.js} +138 -89
  96. package/dist/chunk-M75SUBFG.js.map +1 -0
  97. package/dist/chunk-OHMP6N2J.js +47 -0
  98. package/dist/chunk-OHMP6N2J.js.map +1 -0
  99. package/dist/{chunk-4DIBPQNJ.js → chunk-OR5ZA5WP.js} +135 -25
  100. package/dist/chunk-OR5ZA5WP.js.map +1 -0
  101. package/dist/{chunk-6HVOHZHS.cjs → chunk-PWGX5DF5.cjs} +213 -168
  102. package/dist/chunk-PWGX5DF5.cjs.map +1 -0
  103. package/dist/chunk-PZKNKG5M.js +1252 -0
  104. package/dist/chunk-PZKNKG5M.js.map +1 -0
  105. package/dist/{chunk-DEQFL35G.js → chunk-Q5TEXCTB.js} +61 -7
  106. package/dist/chunk-Q5TEXCTB.js.map +1 -0
  107. package/dist/{chunk-QV245VMN.js → chunk-RAXU3RMB.js} +100 -6
  108. package/dist/chunk-RAXU3RMB.js.map +1 -0
  109. package/dist/{chunk-RHZWOJVA.cjs → chunk-RSSQKPSZ.cjs} +52 -4
  110. package/dist/chunk-RSSQKPSZ.cjs.map +1 -0
  111. package/dist/{chunk-G6SOJEDI.cjs → chunk-S55OV6PW.cjs} +15 -15
  112. package/dist/chunk-S55OV6PW.cjs.map +1 -0
  113. package/dist/chunk-S5F7ZLP2.js +94 -0
  114. package/dist/chunk-S5F7ZLP2.js.map +1 -0
  115. package/dist/{chunk-3E7SNSIA.cjs → chunk-SJDMVITW.cjs} +4 -4
  116. package/dist/{chunk-3E7SNSIA.cjs.map → chunk-SJDMVITW.cjs.map} +1 -1
  117. package/dist/{chunk-CHXTTSC6.js → chunk-SKCOUWAX.js} +104 -5
  118. package/dist/chunk-SKCOUWAX.js.map +1 -0
  119. package/dist/{chunk-XLUNB2TZ.js → chunk-SNXVDZAJ.js} +3 -3
  120. package/dist/{chunk-XLUNB2TZ.js.map → chunk-SNXVDZAJ.js.map} +1 -1
  121. package/dist/{chunk-ZURTTSCM.js → chunk-SXGE7ITL.js} +6 -94
  122. package/dist/chunk-SXGE7ITL.js.map +1 -0
  123. package/dist/{chunk-RBV7YCQD.js → chunk-T2WUSPDA.js} +49 -9
  124. package/dist/chunk-T2WUSPDA.js.map +1 -0
  125. package/dist/{chunk-KGC4LY5T.cjs → chunk-TCOCYN2P.cjs} +75 -21
  126. package/dist/chunk-TCOCYN2P.cjs.map +1 -0
  127. package/dist/{chunk-FLRCVI2G.cjs → chunk-TDXIBCGY.cjs} +2 -2
  128. package/dist/{chunk-FLRCVI2G.cjs.map → chunk-TDXIBCGY.cjs.map} +1 -1
  129. package/dist/{chunk-ZY4GXIVN.cjs → chunk-TEDRJXOG.cjs} +5 -5
  130. package/dist/{chunk-ZY4GXIVN.cjs.map → chunk-TEDRJXOG.cjs.map} +1 -1
  131. package/dist/{chunk-WL2SG7ZV.cjs → chunk-UMDVATGY.cjs} +6 -6
  132. package/dist/{chunk-WL2SG7ZV.cjs.map → chunk-UMDVATGY.cjs.map} +1 -1
  133. package/dist/chunk-UT3S4SEN.js +31 -0
  134. package/dist/chunk-UT3S4SEN.js.map +1 -0
  135. package/dist/{chunk-RRKQAKD6.cjs → chunk-UUT7UN2N.cjs} +149 -39
  136. package/dist/chunk-UUT7UN2N.cjs.map +1 -0
  137. package/dist/{chunk-SHLY4MCM.js → chunk-UZV3AZKF.js} +21 -3
  138. package/dist/chunk-UZV3AZKF.js.map +1 -0
  139. package/dist/{chunk-CYX2JTDG.js → chunk-VHMPG6UL.js} +29 -7
  140. package/dist/chunk-VHMPG6UL.js.map +1 -0
  141. package/dist/{chunk-LANHCOXB.js → chunk-VQEXF5D4.js} +485 -83
  142. package/dist/chunk-VQEXF5D4.js.map +1 -0
  143. package/dist/{chunk-K34OPSJK.js → chunk-W63OVYY4.js} +3 -3
  144. package/dist/{chunk-K34OPSJK.js.map → chunk-W63OVYY4.js.map} +1 -1
  145. package/dist/{chunk-TQOYM4LN.js → chunk-WI7ISNQF.js} +35 -5
  146. package/dist/chunk-WI7ISNQF.js.map +1 -0
  147. package/dist/{chunk-UNNPKQUG.cjs → chunk-X4JBT642.cjs} +246 -155
  148. package/dist/chunk-X4JBT642.cjs.map +1 -0
  149. package/dist/chunk-ZAMFOJ5P.cjs +1176 -0
  150. package/dist/chunk-ZAMFOJ5P.cjs.map +1 -0
  151. package/dist/{chunk-T46GR2VY.js → chunk-ZIGXMKQQ.js} +3 -3
  152. package/dist/{chunk-T46GR2VY.js.map → chunk-ZIGXMKQQ.js.map} +1 -1
  153. package/dist/{chunk-5IQIX7LU.cjs → chunk-ZUNQ5BEP.cjs} +518 -172
  154. package/dist/chunk-ZUNQ5BEP.cjs.map +1 -0
  155. package/dist/{ddl-BrmPg61z.d.ts → ddl-C2rZ-Aen.d.ts} +4 -4
  156. package/dist/{ddl-j1-sH6lE.d.cts → ddl-CZz7a0E8.d.cts} +4 -4
  157. package/dist/{extension-types-YGFJPrzK.d.cts → extension-types-ixRpJVUp.d.cts} +24 -1
  158. package/dist/{extension-types-YGFJPrzK.d.ts → extension-types-ixRpJVUp.d.ts} +24 -1
  159. package/dist/{types-DkNnF-7K.d.cts → fulltext-strategy-B57yvC5Q.d.ts} +2562 -2133
  160. package/dist/{types-D1Sqeyxy.d.ts → fulltext-strategy-CDkSSYhq.d.cts} +2562 -2133
  161. package/dist/graph-extension/index.cjs +20 -19
  162. package/dist/graph-extension/index.d.cts +4 -4
  163. package/dist/graph-extension/index.d.ts +4 -4
  164. package/dist/graph-extension/index.js +5 -4
  165. package/dist/graph-merge/index.cjs +255 -164
  166. package/dist/graph-merge/index.cjs.map +1 -1
  167. package/dist/graph-merge/index.d.cts +63 -33
  168. package/dist/graph-merge/index.d.ts +63 -33
  169. package/dist/graph-merge/index.js +135 -44
  170. package/dist/graph-merge/index.js.map +1 -1
  171. package/dist/{index-DGX6D9j1.d.ts → index-BFvdmBPV.d.ts} +301 -93
  172. package/dist/{index-SEvUHDA6.d.cts → index-BLtQWKRj.d.cts} +301 -93
  173. package/dist/index.cjs +216 -188
  174. package/dist/index.d.cts +11 -11
  175. package/dist/index.d.ts +11 -11
  176. package/dist/index.js +33 -33
  177. package/dist/indexes/index.cjs +19 -20
  178. package/dist/indexes/index.d.cts +5 -5
  179. package/dist/indexes/index.d.ts +5 -5
  180. package/dist/indexes/index.js +10 -11
  181. package/dist/interchange/index.cjs +48 -26
  182. package/dist/interchange/index.d.cts +126 -12
  183. package/dist/interchange/index.d.ts +126 -12
  184. package/dist/interchange/index.js +15 -13
  185. package/dist/{manager-ms9cKdc6.d.cts → manager-DwQi8eV0.d.cts} +9 -2
  186. package/dist/{manager-BZUeN_BU.d.ts → manager-ejUCB52T.d.ts} +9 -2
  187. package/dist/{materialize-indexes-D20xNluI.d.cts → materialize-indexes-B4e9360H.d.cts} +20 -4
  188. package/dist/{materialize-indexes-CAkIYFV-.d.ts → materialize-indexes-te9TPMMJ.d.ts} +20 -4
  189. package/dist/{postgres-BhpxGMC5.d.cts → postgres-CfEqsRMp.d.cts} +152 -1
  190. package/dist/{postgres-CWHLwNl1.d.ts → postgres-DQ5R6rzV.d.ts} +152 -1
  191. package/dist/profiler/index.cjs +11 -11
  192. package/dist/profiler/index.d.cts +7 -7
  193. package/dist/profiler/index.d.ts +7 -7
  194. package/dist/profiler/index.js +4 -4
  195. package/dist/provenance/index.cjs +40 -41
  196. package/dist/provenance/index.cjs.map +1 -1
  197. package/dist/provenance/index.d.cts +5 -5
  198. package/dist/provenance/index.d.ts +5 -5
  199. package/dist/provenance/index.js +11 -12
  200. package/dist/provenance/index.js.map +1 -1
  201. package/dist/schema/index.cjs +53 -40
  202. package/dist/schema/index.cjs.map +1 -1
  203. package/dist/schema/index.d.cts +57 -57
  204. package/dist/schema/index.d.ts +57 -57
  205. package/dist/schema/index.js +28 -15
  206. package/dist/schema/index.js.map +1 -1
  207. package/dist/{sqlite-XrDxNaa7.d.cts → sqlite-D7zBinNR.d.cts} +92 -1
  208. package/dist/{sqlite-CGu5SLsw.d.ts → sqlite-DvQndLky.d.ts} +92 -1
  209. package/dist/{store-view-D09po4H6.d.cts → store-view-9KDOpZzF.d.cts} +643 -58
  210. package/dist/{store-view-BlgnhEYf.d.ts → store-view-DplHC3Nt.d.ts} +643 -58
  211. package/dist/{types-DiE1AO7p.d.cts → types-Bv9DcS_E.d.cts} +2 -2
  212. package/dist/{types-B1TbZJYS.d.ts → types-CoxuV7EJ.d.ts} +2 -2
  213. package/dist/{where-DKjuofPr.d.cts → where-7RKFOsXt.d.ts} +2 -2
  214. package/dist/{where-DrUIIWHb.d.ts → where-DdMIXOtH.d.cts} +2 -2
  215. package/package.json +14 -13
  216. package/dist/chunk-2EBMPJBO.js +0 -16
  217. package/dist/chunk-2EBMPJBO.js.map +0 -1
  218. package/dist/chunk-2JXB3NYJ.cjs.map +0 -1
  219. package/dist/chunk-2MRAX3UE.js.map +0 -1
  220. package/dist/chunk-3BRVBQQD.cjs.map +0 -1
  221. package/dist/chunk-3EUKJEQ3.js +0 -77
  222. package/dist/chunk-3EUKJEQ3.js.map +0 -1
  223. package/dist/chunk-3Z6TW3CT.cjs.map +0 -1
  224. package/dist/chunk-4DIBPQNJ.js.map +0 -1
  225. package/dist/chunk-4S2FXGBJ.js +0 -9
  226. package/dist/chunk-4S2FXGBJ.js.map +0 -1
  227. package/dist/chunk-5IQIX7LU.cjs.map +0 -1
  228. package/dist/chunk-6GNSY7AV.js.map +0 -1
  229. package/dist/chunk-6HVOHZHS.cjs.map +0 -1
  230. package/dist/chunk-6SCVW4AS.js +0 -20
  231. package/dist/chunk-6SCVW4AS.js.map +0 -1
  232. package/dist/chunk-A7SZZFAG.js.map +0 -1
  233. package/dist/chunk-CHXTTSC6.js.map +0 -1
  234. package/dist/chunk-CYX2JTDG.js.map +0 -1
  235. package/dist/chunk-DEQFL35G.js.map +0 -1
  236. package/dist/chunk-G6SOJEDI.cjs.map +0 -1
  237. package/dist/chunk-GQANNXXT.cjs.map +0 -1
  238. package/dist/chunk-GZCNZ7QW.js +0 -24
  239. package/dist/chunk-GZCNZ7QW.js.map +0 -1
  240. package/dist/chunk-HK5SATYM.cjs.map +0 -1
  241. package/dist/chunk-HMFK4BXR.cjs +0 -12
  242. package/dist/chunk-HTGDWIDE.cjs +0 -89
  243. package/dist/chunk-HTGDWIDE.cjs.map +0 -1
  244. package/dist/chunk-JIEJCTDS.cjs.map +0 -1
  245. package/dist/chunk-JJRCLAUN.cjs.map +0 -1
  246. package/dist/chunk-JQGIPGVL.cjs.map +0 -1
  247. package/dist/chunk-K2TGS3EN.js.map +0 -1
  248. package/dist/chunk-KGC4LY5T.cjs.map +0 -1
  249. package/dist/chunk-KNHYNQQ3.cjs +0 -663
  250. package/dist/chunk-KNHYNQQ3.cjs.map +0 -1
  251. package/dist/chunk-KUTNI6SI.js.map +0 -1
  252. package/dist/chunk-LANHCOXB.js.map +0 -1
  253. package/dist/chunk-N6WTUSBV.cjs +0 -23
  254. package/dist/chunk-N6WTUSBV.cjs.map +0 -1
  255. package/dist/chunk-NAUA4PW5.cjs +0 -28
  256. package/dist/chunk-NAUA4PW5.cjs.map +0 -1
  257. package/dist/chunk-QV245VMN.js.map +0 -1
  258. package/dist/chunk-RBV7YCQD.js.map +0 -1
  259. package/dist/chunk-RHZWOJVA.cjs.map +0 -1
  260. package/dist/chunk-RRKQAKD6.cjs.map +0 -1
  261. package/dist/chunk-RY2VIWAM.js.map +0 -1
  262. package/dist/chunk-SHLY4MCM.js.map +0 -1
  263. package/dist/chunk-T2DWPQNE.js +0 -649
  264. package/dist/chunk-T2DWPQNE.js.map +0 -1
  265. package/dist/chunk-T6SPUYLX.cjs.map +0 -1
  266. package/dist/chunk-TGJE22RM.cjs.map +0 -1
  267. package/dist/chunk-TOTPVGOG.cjs +0 -774
  268. package/dist/chunk-TOTPVGOG.cjs.map +0 -1
  269. package/dist/chunk-TQOYM4LN.js.map +0 -1
  270. package/dist/chunk-UJLOZYKT.cjs.map +0 -1
  271. package/dist/chunk-UNNPKQUG.cjs.map +0 -1
  272. package/dist/chunk-V3QNTB7Z.js.map +0 -1
  273. package/dist/chunk-VCGO4V26.js.map +0 -1
  274. package/dist/chunk-WLRIWYHQ.js.map +0 -1
  275. package/dist/chunk-WVC2Q2FD.cjs.map +0 -1
  276. package/dist/chunk-XXVEULWX.js +0 -39
  277. package/dist/chunk-XXVEULWX.js.map +0 -1
  278. package/dist/chunk-YAZE7QZR.cjs +0 -32
  279. package/dist/chunk-YAZE7QZR.cjs.map +0 -1
  280. package/dist/chunk-YC6PWTHY.cjs +0 -44
  281. package/dist/chunk-YC6PWTHY.cjs.map +0 -1
  282. package/dist/chunk-Z5HBYM7U.cjs +0 -11
  283. package/dist/chunk-Z5HBYM7U.cjs.map +0 -1
  284. package/dist/chunk-Z5XBMDXU.js.map +0 -1
  285. package/dist/chunk-ZP5WHI4C.cjs.map +0 -1
  286. package/dist/chunk-ZURTTSCM.js.map +0 -1
  287. package/dist/chunk-ZV5N4DBG.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backend/table-contribution.ts","../src/query/dialect/fulltext-strategy.ts","../src/query/dialect/vector-strategy.ts","../src/query/dialect/postgres.ts","../src/query/dialect/sqlite.ts","../src/query/dialect/index.ts","../src/indexes/compiler.ts"],"names":["sql","quotedTableName","quoteIdentifier","parseJsonPointer","likeEscapeClause","jsonPointer"],"mappings":";;;;;;;AA+CO,IAAM,0BAAA,GAA6B,UAA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Unified table-contribution contract (#129).\n *\n * Every table TypeGraph owns — whether modeled as a Drizzle table or\n * emitted as strategy-owned raw DDL — is described by a single\n * {@link TableContribution} shape. This is the one place that answers\n * \"what tables does this backend/strategy own?\", replacing the\n * previously split surfaces (Drizzle named exports, tables-factory\n * recursion, strategy raw DDL, per-table `ensureXTable` methods).\n *\n * Lives in the neutral `backend/` layer (sibling of `backend/types.ts`,\n * which `query/dialect` already depends on) and is deliberately\n * Drizzle-free, so declaring contributions does not pull the concrete\n * Drizzle backend runtime into the query/dialect layer.\n *\n * ## Identity vs. signature (prerequisite for #135)\n *\n * #135 (durable fulltext/contribution materialization) needs to make\n * \"not materialized\" vs. \"materialized but stale\" a decidable, durable\n * fact instead of an in-memory per-backend latch. That requires two\n * conceptually separate things, and #129's job is only to make both\n * *derivable* from the contract:\n *\n * - **Materialization identity** — `owner` + `logicalName` +\n * resolved physical `tableName`. Keying on `logicalName` alone is\n * insufficient: custom per-deployment table names must be\n * distinguishable, otherwise two deployments with different physical\n * names would collide on one durable marker. (#135 additionally\n * scopes this by `graphId` at persistence time.)\n * - **Drift signature** — a hash of the strategy identity/version,\n * the resolved table name(s), and the normalized `createDdl`. #129\n * guarantees `createDdl` is deterministic for a given resolved\n * configuration so the hash #135 computes is meaningful.\n *\n * The signature is intentionally **not** eagerly carried on the\n * contribution: hashing is async (Web Crypto, see `utils/hash`) and\n * #135 already owns signature persistence the same way\n * `materializeIndexes` does for declared indexes.\n */\n\n/**\n * `logicalName` of the strategy-owned fulltext slot. Used as a logic\n * discriminant (latch routing, runtime-ensure) across the strategies\n * and both backends — a shared constant so a strategy declaring a\n * different name fails loudly at the call site instead of silently\n * skipping the latched fulltext path.\n */\nexport const FULLTEXT_CONTRIBUTION_NAME = \"fulltext\";\n\n/** `owner` of core/base schema tables (not strategy-owned). */\nexport const BASE_CONTRIBUTION_OWNER = \"base\";\n\n/**\n * A single table TypeGraph owns.\n */\nexport type TableContribution = Readonly<{\n /**\n * Stable, graph- and deployment-independent identity for the logical\n * slot this contribution fills (e.g. `\"fulltext\"`). NOT the physical\n * table name. Stable across table-name overrides and across strategy\n * swaps of the *same* logical slot, so #135's durable marker can\n * survive both.\n */\n logicalName: string;\n /**\n * Identifies the producer of this contribution (e.g. a strategy id\n * like `\"tsvector\"` / `\"fts5\"`, or `\"base\"` for core schema tables).\n * Part of the #135 materialization identity and an input to the\n * drift signature — a strategy swap on the same `logicalName` is a\n * legitimate, detectable drift, not a silent reuse.\n */\n owner: string;\n /**\n * Resolved physical table name after any per-deployment name\n * override. Part of the #135 materialization identity (custom names\n * must be distinguishable) and used by diagnostics / the focused\n * bootstrap ensure.\n */\n tableName: string;\n /**\n * Idempotent (`CREATE ... IF NOT EXISTS`) statements that\n * materialize this contribution's table **and its supporting\n * indexes**. Running the full list is how the runtime ensure\n * self-heals partial states (table present, index missing) — it is\n * not a probe-and-skip. Deterministic for a given resolved\n * configuration: the canonical normalized input to #135's drift\n * signature.\n */\n createDdl: readonly string[];\n /**\n * When `true`, the post-schema-load focused ensure\n * (`loadActiveSchemaWithBootstrap`) materializes this contribution\n * on every successful schema load.\n *\n * **Invariant: only strategy-declared contributions may set this.**\n * Core/base tables are always `false` — they are created by\n * drizzle-kit / `bootstrapTables`. This is what lets the boot path\n * derive runtime contributions straight from the strategy\n * (`fulltextStrategy.ownedTables`) without walking — and generating\n * DDL for — every base table.\n */\n runtimeEnsure: boolean;\n}>;\n\n/**\n * A table a {@link FulltextStrategy} declares it owns. An alias, not a\n * distinct shape: a strategy's declaration is already authoritative\n * (no resolution step). The name documents the producer role.\n */\nexport type StrategyTableContribution = TableContribution;\n","/**\n * Fulltext Strategy — pluggable DDL + SQL generation for a dialect's\n * fulltext stack. A strategy owns every SQL statement that touches its\n * backing table: DDL, upsert (single + batch), delete (single + batch),\n * MATCH condition, rank expression, and snippet expression.\n *\n * A dialect picks one as its default; `createPostgresBackend` /\n * `createSqliteBackend` accept an override for alternate Postgres stacks\n * (pg_trgm, ParadeDB/pg_search, pgroonga) to swap the entire fulltext\n * pipeline without forking TypeGraph.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { quotedTableName } from \"../../backend/drizzle/operations/shared\";\nimport {\n FULLTEXT_CONTRIBUTION_NAME,\n type StrategyTableContribution,\n} from \"../../backend/table-contribution\";\nimport {\n type DeleteFulltextBatchParams,\n type DeleteFulltextParams,\n type FulltextBatchRow,\n type FulltextCapabilities,\n type FulltextQueryMode,\n type UpsertFulltextBatchParams,\n type UpsertFulltextParams,\n} from \"../../backend/types\";\n\n/**\n * Every `FulltextQueryMode` both shipped strategies accept.\n */\nexport const ALL_FULLTEXT_MODES: readonly FulltextQueryMode[] = [\n \"websearch\",\n \"phrase\",\n \"plain\",\n \"raw\",\n] as const;\n\n/**\n * Derives the `FulltextCapabilities` backends advertise from the active\n * strategy, so the two never drift.\n */\nexport function buildFulltextCapabilities(\n strategy: FulltextStrategy,\n): FulltextCapabilities {\n return {\n supported: true,\n languages: strategy.languages,\n phraseQueries: strategy.supportedModes.includes(\"phrase\"),\n prefixQueries: strategy.supportsPrefix,\n highlighting: strategy.supportsSnippets,\n };\n}\n\n/**\n * A pluggable fulltext implementation. Each strategy is expected to be\n * self-contained: given a table name, a query string, and a parse mode,\n * it emits every SQL statement the compiler and backend need — DDL,\n * reads, and writes. No out-of-band conventions across layers.\n */\nexport interface FulltextStrategy {\n /** Human-readable identifier used in error messages and telemetry. */\n readonly name: string;\n\n /**\n * Parse modes this strategy can translate. Callers validate against\n * this list before emitting SQL; a mode outside the set means the\n * strategy rejects the query at compile time.\n */\n readonly supportedModes: readonly FulltextQueryMode[];\n\n /**\n * Whether the strategy can emit a per-row highlighted snippet. When\n * false, `snippetExpression` returns a literal `NULL` so callers can\n * leave the `snippet` column in place without a branch.\n */\n readonly supportsSnippets: boolean;\n\n /**\n * Whether the strategy supports prefix queries (`foo*`). Used to\n * populate `BackendCapabilities.fulltext.prefixQueries`. A strategy\n * may support prefix queries via dedicated syntax without advertising\n * \"raw\" mode (and vice-versa).\n */\n readonly supportsPrefix: boolean;\n\n /**\n * Whether a per-query `language` override is honored. Postgres' tsvector\n * accepts any installed regconfig at query time; SQLite FTS5's tokenizer\n * is fixed at table-create time, so the override is silently ignored.\n * Callers may surface a warning when the user passes `language` to a\n * strategy that doesn't honor it.\n */\n readonly supportsLanguageOverride: boolean;\n\n /**\n * Languages / tokenizer names understood by the strategy. Advisory — a\n * runtime backend like Postgres may accept other installed regconfigs.\n * Used to populate `BackendCapabilities.fulltext.languages`.\n */\n readonly languages: readonly string[];\n\n /**\n * Emits the WHERE-side MATCH expression.\n *\n * @example\n * tsvector: `\"typegraph_node_fulltext\".\"tsv\" @@ websearch_to_tsquery('english', 'cats')`\n * fts5: `\"typegraph_node_fulltext\" MATCH '\"cats\"'`\n */\n matchCondition(\n tableName: string,\n query: string,\n mode: FulltextQueryMode,\n language?: string,\n ): SQL;\n\n /**\n * Emits the relevance expression. Higher values = more relevant. The\n * compiler orders by this expression DESC, and both builder and\n * backend-direct paths use the same form so their top-k results agree.\n */\n rankExpression(\n tableName: string,\n query: string,\n mode: FulltextQueryMode,\n language?: string,\n ): SQL;\n\n /**\n * Emits a per-row highlighted snippet expression, or `NULL` when\n * `supportsSnippets` is false. Snippet markup is `<mark>…</mark>` in\n * both shipped strategies so consumers can apply one stylesheet.\n */\n snippetExpression(\n tableName: string,\n query: string,\n mode: FulltextQueryMode,\n language?: string,\n ): SQL;\n\n /**\n * The tables this strategy owns, as Drizzle-free, already\n * authoritative `TableContribution`s (`logicalName`, `owner`,\n * resolved `tableName`, idempotent `createDdl` for the table **and\n * its supporting indexes**, `runtimeEnsure`). A strategy never\n * constructs a Drizzle table itself; drizzle-kit visibility, when\n * applicable, is the schema barrel's responsibility (the default\n * Postgres strategy's `schema/postgres.ts` exports a matching\n * `tables.fulltext` — a non-default strategy must export its own).\n *\n * Replaces the former `generateDdl(tableName)`: DDL is now one field\n * of a contribution rather than the strategy's whole storage\n * surface. (Public API change — see #129.)\n */\n ownedTables(primaryTableName: string): readonly StrategyTableContribution[];\n\n /**\n * Emits the statements that upsert a single fulltext row. Returns one\n * or more statements — some backends (SQLite FTS5) cannot emulate\n * upsert in a single statement and need DELETE + INSERT.\n */\n buildUpsert(\n tableName: string,\n params: UpsertFulltextParams,\n timestamp: string,\n ): readonly SQL[];\n\n /**\n * Emits the statements that upsert many fulltext rows at once. Input\n * rows are expected to be de-duplicated last-write-wins by the\n * strategy if the underlying SQL statement cannot tolerate duplicate\n * conflict keys. Returns `[]` when `params.rows` is empty.\n */\n buildBatchUpsert(\n tableName: string,\n params: UpsertFulltextBatchParams,\n timestamp: string,\n ): readonly SQL[];\n\n /**\n * Emits the statements that delete a single fulltext row. Normally a\n * single PK-scoped DELETE, but strategies that maintain auxiliary\n * indexes (delete-triggered external stores, ParadeDB-style secondary\n * structures) may need more.\n */\n buildDelete(tableName: string, params: DeleteFulltextParams): readonly SQL[];\n\n /**\n * Emits the statements that delete many fulltext rows at once. Returns\n * `[]` when `params.nodeIds` is empty.\n */\n buildBatchDelete(\n tableName: string,\n params: DeleteFulltextBatchParams,\n ): readonly SQL[];\n}\n\n// ============================================================\n// Internal helpers\n// ============================================================\n\nfunction quoteIdentifier(name: string): string {\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction tsvectorColumn(tableName: string): SQL {\n return sql`${quotedTableName(tableName)}.\"tsv\"`;\n}\n\n/**\n * Dedupes batch rows last-write-wins by nodeId. Returns a plain array\n * in insertion order of the last occurrence of each id. Shared by both\n * shipped strategies.\n */\nfunction dedupeFulltextBatchRows(\n rows: readonly FulltextBatchRow[],\n): FulltextBatchRow[] {\n const seen = new Map<string, FulltextBatchRow>();\n for (const row of rows) seen.set(row.nodeId, row);\n return [...seen.values()];\n}\n\nfunction buildPkScopedDelete(\n tableName: string,\n params: DeleteFulltextParams,\n): SQL {\n const table = quotedTableName(tableName);\n return sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId}\n AND \"node_kind\" = ${params.nodeKind}\n AND \"node_id\" = ${params.nodeId}\n `;\n}\n\nfunction buildPkScopedBatchDelete(\n tableName: string,\n params: DeleteFulltextBatchParams,\n): SQL | undefined {\n if (params.nodeIds.length === 0) return undefined;\n const unique = [...new Set(params.nodeIds)];\n const table = quotedTableName(tableName);\n return sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId}\n AND \"node_kind\" = ${params.nodeKind}\n AND \"node_id\" IN (${sql.join(\n unique.map((id) => sql`${id}`),\n sql`, `,\n )})\n `;\n}\n\n// ============================================================\n// tsvector strategy (PostgreSQL built-in)\n// ============================================================\n\nfunction postgresTsquery(\n mode: FulltextQueryMode,\n query: string,\n language: string | undefined,\n): SQL {\n // The `language` column is already `regconfig`, so the non-override\n // path references the column directly. The per-query override path\n // still arrives as a bound text parameter and needs the cast.\n const langExpr: SQL =\n language === undefined ? sql`\"language\"` : sql`${language}::regconfig`;\n switch (mode) {\n case \"websearch\": {\n return sql`websearch_to_tsquery(${langExpr}, ${query})`;\n }\n case \"phrase\": {\n return sql`phraseto_tsquery(${langExpr}, ${query})`;\n }\n case \"plain\": {\n return sql`plainto_tsquery(${langExpr}, ${query})`;\n }\n case \"raw\": {\n return sql`to_tsquery(${langExpr}, ${query})`;\n }\n default: {\n const _exhaustive: never = mode;\n throw new Error(`Unsupported fulltext mode: ${String(_exhaustive)}`);\n }\n }\n}\n\nexport const tsvectorStrategy: FulltextStrategy = {\n name: \"tsvector\",\n supportedModes: ALL_FULLTEXT_MODES,\n supportsSnippets: true,\n // `raw` mode exposes `foo:*` prefix-match syntax to callers.\n supportsPrefix: true,\n supportsLanguageOverride: true,\n // Canonical Postgres stemmers; every stock install ships these plus a\n // few others. Runtime `to_tsvector` accepts any installed regconfig\n // name — this list is advisory for capability discovery.\n languages: [\n \"simple\",\n \"english\",\n \"french\",\n \"german\",\n \"italian\",\n \"portuguese\",\n \"russian\",\n \"spanish\",\n \"swedish\",\n ] as const,\n\n matchCondition(tableName, query, mode, language) {\n const q = postgresTsquery(mode, query, language);\n return sql`${tsvectorColumn(tableName)} @@ ${q}`;\n },\n\n rankExpression(tableName, query, mode, language) {\n const q = postgresTsquery(mode, query, language);\n return sql`ts_rank_cd(${tsvectorColumn(tableName)}, ${q})`;\n },\n\n snippetExpression(_tableName, query, mode, language) {\n const langExpr: SQL =\n language === undefined ? sql`\"language\"` : sql`${language}::regconfig`;\n const q = postgresTsquery(mode, query, language);\n return sql`ts_headline(${langExpr}, \"content\", ${q}, 'StartSel=<mark>,StopSel=</mark>,MaxFragments=1,MinWords=5,MaxWords=30,ShortWord=3')`;\n },\n\n ownedTables(primaryTableName) {\n const name = quoteIdentifier(primaryTableName);\n const gin = quoteIdentifier(`${primaryTableName}_tsv_idx`);\n const kind = quoteIdentifier(`${primaryTableName}_kind_idx`);\n // `language` is `regconfig` so `to_tsvector(\"language\", \"content\")`\n // is an immutable expression — Postgres can then compute `tsv` as a\n // GENERATED STORED column and own the `content → tsv` invariant.\n // (The text→regconfig cast happens once at INSERT time against the\n // bound parameter, which is fine because it's not inside the\n // generated expression.)\n const createDdl = [\n `CREATE TABLE IF NOT EXISTS ${name} (\n \"graph_id\" TEXT NOT NULL,\n \"node_kind\" TEXT NOT NULL,\n \"node_id\" TEXT NOT NULL,\n \"content\" TEXT NOT NULL,\n \"language\" regconfig NOT NULL,\n \"tsv\" tsvector NOT NULL\n GENERATED ALWAYS AS (to_tsvector(\"language\", \"content\")) STORED,\n \"updated_at\" TIMESTAMPTZ NOT NULL,\n PRIMARY KEY (\"graph_id\", \"node_kind\", \"node_id\")\n);`,\n `CREATE INDEX IF NOT EXISTS ${gin} ON ${name} USING GIN (\"tsv\");`,\n `CREATE INDEX IF NOT EXISTS ${kind} ON ${name} (\"graph_id\", \"node_kind\");`,\n ];\n // drizzle-kit visibility for this default strategy comes from\n // `schema/postgres.ts` exporting the matching `tables.fulltext`\n // pgTable through the barrel — one object, not two. `runtimeEnsure`\n // because drizzle-kit-managed setups create every base table except\n // this strategy-owned one.\n return [\n {\n logicalName: FULLTEXT_CONTRIBUTION_NAME,\n owner: \"tsvector\",\n tableName: primaryTableName,\n createDdl,\n runtimeEnsure: true,\n },\n ];\n },\n\n buildUpsert(tableName, params, timestamp) {\n const table = quotedTableName(tableName);\n // `tsv` is a GENERATED STORED column — Postgres computes it from\n // `content` + `language`, so it must not appear in the column list\n // or the ON CONFLICT update set.\n return [\n sql`\n INSERT INTO ${table} (\"graph_id\", \"node_kind\", \"node_id\", \"content\", \"language\", \"updated_at\")\n VALUES (\n ${params.graphId}, ${params.nodeKind}, ${params.nodeId},\n ${params.content}, ${params.language}::regconfig,\n ${timestamp}\n )\n ON CONFLICT (\"graph_id\", \"node_kind\", \"node_id\")\n DO UPDATE SET\n \"content\" = EXCLUDED.\"content\",\n \"language\" = EXCLUDED.\"language\",\n \"updated_at\" = EXCLUDED.\"updated_at\"\n `,\n ];\n },\n\n buildBatchUpsert(tableName, params, timestamp) {\n const rows = dedupeFulltextBatchRows(params.rows);\n if (rows.length === 0) return [];\n\n const table = quotedTableName(tableName);\n const valueTuples = rows.map(\n (row) => sql`\n (\n ${params.graphId}, ${params.nodeKind}, ${row.nodeId},\n ${row.content}, ${row.language}::regconfig,\n ${timestamp}\n )\n `,\n );\n\n return [\n sql`\n INSERT INTO ${table} (\"graph_id\", \"node_kind\", \"node_id\", \"content\", \"language\", \"updated_at\")\n VALUES ${sql.join(valueTuples, sql`, `)}\n ON CONFLICT (\"graph_id\", \"node_kind\", \"node_id\")\n DO UPDATE SET\n \"content\" = EXCLUDED.\"content\",\n \"language\" = EXCLUDED.\"language\",\n \"updated_at\" = EXCLUDED.\"updated_at\"\n `,\n ];\n },\n\n buildDelete(tableName, params) {\n return [buildPkScopedDelete(tableName, params)];\n },\n\n buildBatchDelete(tableName, params) {\n const stmt = buildPkScopedBatchDelete(tableName, params);\n return stmt === undefined ? [] : [stmt];\n },\n};\n\n// ============================================================\n// FTS5 strategy (SQLite)\n// ============================================================\n\nfunction translateToFts5Query(query: string, mode: FulltextQueryMode): string {\n switch (mode) {\n case \"phrase\": {\n return `\"${query.replaceAll('\"', '\"\"')}\"`;\n }\n case \"plain\": {\n return query\n .trim()\n .split(/\\s+/u)\n .filter((token) => token.length > 0)\n .map((token) => `\"${token.replaceAll('\"', '\"\"')}\"`)\n .join(\" \");\n }\n case \"websearch\": {\n return translateWebsearchToFts5(query);\n }\n case \"raw\": {\n return query;\n }\n default: {\n const _exhaustive: never = mode;\n throw new Error(`Unsupported fulltext mode: ${String(_exhaustive)}`);\n }\n }\n}\n\nfunction translateWebsearchToFts5(query: string): string {\n const tokens: string[] = [];\n let index = 0;\n\n function skipWhitespace(): void {\n while (index < query.length && /\\s/u.test(query[index] ?? \"\")) {\n index += 1;\n }\n }\n\n function readPhrase(): string {\n index += 1;\n let content = \"\";\n while (index < query.length && query[index] !== '\"') {\n content += query[index] ?? \"\";\n index += 1;\n }\n if (query[index] === '\"') index += 1;\n return `\"${content.replaceAll('\"', '\"\"')}\"`;\n }\n\n function readBareTerm(): string {\n let term = \"\";\n while (index < query.length && !/\\s/u.test(query[index] ?? \"\")) {\n term += query[index] ?? \"\";\n index += 1;\n }\n return term;\n }\n\n while (index < query.length) {\n skipWhitespace();\n if (index >= query.length) break;\n const ch = query[index];\n if (ch === '\"') {\n tokens.push(readPhrase());\n continue;\n }\n if (ch === \"-\") {\n index += 1;\n const term =\n query[index] === '\"' ?\n readPhrase()\n : `\"${readBareTerm().replaceAll('\"', '\"\"')}\"`;\n tokens.push(`NOT ${term}`);\n continue;\n }\n if (ch === \"+\") {\n index += 1;\n continue;\n }\n const bare = readBareTerm();\n if (bare.length === 0) continue;\n if (bare.toUpperCase() === \"OR\") {\n tokens.push(\"OR\");\n continue;\n }\n tokens.push(`\"${bare.replaceAll('\"', '\"\"')}\"`);\n }\n\n if (tokens.length > 0 && tokens[0]?.startsWith(\"NOT \")) {\n tokens.shift();\n }\n\n return tokens.join(\" \");\n}\n\nexport const fts5Strategy: FulltextStrategy = {\n name: \"fts5\",\n supportedModes: ALL_FULLTEXT_MODES,\n supportsSnippets: true,\n // FTS5 supports `foo*` prefix matching natively.\n supportsPrefix: true,\n // FTS5 tokenizer is fixed at table-create time; per-row / per-query\n // language metadata is stored but not consulted.\n supportsLanguageOverride: false,\n // The built-in tokenizer is `porter unicode61 remove_diacritics 2`; the\n // `language` field on searchable() is recorded for future use but not\n // applied at query time.\n languages: [\"porter\", \"unicode61\", \"trigram\"] as const,\n\n matchCondition(tableName, query, mode, _language) {\n const matchExpression = translateToFts5Query(query, mode);\n return sql`${quotedTableName(tableName)} MATCH ${matchExpression}`;\n },\n\n rankExpression(tableName, _query, _mode, _language) {\n // FTS5 bm25() returns a negative score where lower = more relevant.\n // Negate so callers see higher = better (uniform with tsvector).\n return sql`-bm25(${quotedTableName(tableName)})`;\n },\n\n snippetExpression(tableName, _query, _mode, _language) {\n return sql`snippet(${quotedTableName(tableName)}, -1, '<mark>', '</mark>', '…', 20)`;\n },\n\n ownedTables(primaryTableName) {\n const name = quoteIdentifier(primaryTableName);\n // FTS5 virtual tables cannot be modeled as a Drizzle table, so this\n // contribution is raw-ddl: emitted verbatim and invisible to\n // drizzle-kit. `runtimeEnsure` because no drizzle-kit-managed setup\n // can create it.\n return [\n {\n logicalName: FULLTEXT_CONTRIBUTION_NAME,\n owner: \"fts5\",\n tableName: primaryTableName,\n createDdl: [\n `CREATE VIRTUAL TABLE IF NOT EXISTS ${name} USING fts5(\n graph_id UNINDEXED,\n node_kind UNINDEXED,\n node_id UNINDEXED,\n language UNINDEXED,\n updated_at UNINDEXED,\n content,\n tokenize='porter unicode61 remove_diacritics 2'\n);`,\n ],\n runtimeEnsure: true,\n },\n ];\n },\n\n buildUpsert(tableName, params, timestamp) {\n const table = quotedTableName(tableName);\n // FTS5 virtual tables don't support ON CONFLICT — emulate with\n // DELETE + INSERT, atomic under the caller's outer transaction.\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId}\n AND \"node_kind\" = ${params.nodeKind}\n AND \"node_id\" = ${params.nodeId}\n `,\n sql`\n INSERT INTO ${table} (graph_id, node_kind, node_id, content, language, updated_at)\n VALUES (${params.graphId}, ${params.nodeKind}, ${params.nodeId}, ${params.content}, ${params.language}, ${timestamp})\n `,\n ];\n },\n\n buildBatchUpsert(tableName, params, timestamp) {\n const rows = dedupeFulltextBatchRows(params.rows);\n if (rows.length === 0) return [];\n\n const table = quotedTableName(tableName);\n const nodeIds = rows.map((row) => row.nodeId);\n\n const deleteStmt = sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId}\n AND \"node_kind\" = ${params.nodeKind}\n AND \"node_id\" IN (${sql.join(\n nodeIds.map((id) => sql`${id}`),\n sql`, `,\n )})\n `;\n\n const valueTuples = rows.map(\n (row) => sql`\n (\n ${params.graphId}, ${params.nodeKind}, ${row.nodeId},\n ${row.content}, ${row.language}, ${timestamp}\n )\n `,\n );\n\n const insertStmt = sql`\n INSERT INTO ${table} (graph_id, node_kind, node_id, content, language, updated_at)\n VALUES ${sql.join(valueTuples, sql`, `)}\n `;\n\n return [deleteStmt, insertStmt];\n },\n\n buildDelete(tableName, params) {\n return [buildPkScopedDelete(tableName, params)];\n },\n\n buildBatchDelete(tableName, params) {\n const stmt = buildPkScopedBatchDelete(tableName, params);\n return stmt === undefined ? [] : [stmt];\n },\n};\n","/**\n * Vector Strategy — pluggable storage + SQL generation for a backend's\n * vector stack. The sibling of {@link FulltextStrategy}: a strategy owns\n * every statement that touches its embedding storage — the per-field DDL,\n * upsert, delete, similarity search, and (optional) ANN index lifecycle —\n * plus the capability advertisement and the distance/score expressions the\n * query compiler splices into its relevance CTE.\n *\n * ## Why a strategy, and why per-(kind, field) storage\n *\n * The spike behind #157 established that \"real\" ANN on every engine we\n * support converges on a\n * **typed, fixed-dimension structure per `(nodeKind, fieldPath)`**:\n *\n * - pgvector: a `vector(N)` column + HNSW/IVFFlat;\n * - libSQL native: an `F32_BLOB(N)` column + `libsql_vector_idx` +\n * `vector_top_k` (a plain `BLOB` or dimensionless `F32_BLOB` is rejected\n * by the index — the dimension must live in the column type);\n * - sqlite-vec: a `vec0(embedding float[N])` virtual table.\n *\n * The legacy single shared `typegraph_node_embeddings` table (one generic\n * column holding mixed-dimension vectors) can only ever be brute-forced;\n * pgvector was the sole engine that hid this, because its index supplies the\n * dimension via a `::vector(N)` cast expression. So storage is the\n * strategy's to own, slot by slot, rather than a fixed global table.\n *\n * Brute force remains a legitimate, capability-advertised mode (libSQL's\n * `vector_distance_cos` over a column with no index, sqlite-vec's\n * `vec_distance_cosine`): a strategy whose `capabilities.indexTypes` is\n * `[\"none\"]` simply never emits an ANN index and `buildSearch` always scans.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { type StrategyTableContribution } from \"../../backend/table-contribution\";\nimport {\n type DeleteEmbeddingParams,\n type UpsertEmbeddingBatchParams,\n type UpsertEmbeddingParams,\n type VectorCapabilities,\n type VectorIndexType,\n type VectorMetric,\n type VectorSearchParams,\n} from \"../../backend/types\";\n\n/**\n * `logicalName` prefix of a strategy-owned vector slot. Each\n * `(nodeKind, fieldPath)` pair fills one logical vector slot; the full\n * logical name is `${VECTOR_CONTRIBUTION_PREFIX}:${nodeKind}.${fieldPath}`,\n * stable across table-name overrides and strategy swaps so #135's durable\n * materialization marker survives both.\n */\nexport const VECTOR_CONTRIBUTION_PREFIX = \"vector\";\n\n/**\n * The resolved identity of one embedding field's storage in a graph —\n * everything a strategy needs to DDL, address, and index it.\n *\n * Graph-scoped: each `(graphId, nodeKind, fieldPath)` gets its own physical\n * table. TypeGraph supports many graphs per physical database, and the same\n * `(kind, field)` can carry different embedding dimensions across graphs — a\n * shared per-`(kind, field)` table would collide on the fixed column type\n * (`vector(N)` / `F32_BLOB(N)`). Graph-scoping also makes libSQL's\n * table-global `vector_top_k` per-graph-exact (no cross-graph recall bleed).\n */\nexport type VectorSlot = Readonly<{\n /** Graph the embedding belongs to — scopes the physical table. */\n graphId: string;\n /** Node kind owning the embedding field (e.g. `\"Document\"`). */\n nodeKind: string;\n /** Dot-path of the embedding field within the node props (e.g. `\"embedding\"`). */\n fieldPath: string;\n /** Fixed vector dimension `N` for this field — carried into the column type. */\n dimensions: number;\n /** Distance metric the field's index is built for. */\n metric: VectorMetric;\n /**\n * Index type to materialize. `\"none\"` means brute-force only (no ANN\n * index emitted); the strategy still stores and searches the field.\n */\n indexType: VectorIndexType;\n /**\n * Optional ANN index tuning carried into the index DDL (pgvector\n * `m`/`ef_construction`/`lists`). Present on the create-index / re-embed\n * paths (resolved from the field's `embedding()` declaration); omitted on\n * the write/search ensure paths, where the strategy falls back to defaults.\n */\n indexParams?: Readonly<{\n m?: number;\n efConstruction?: number;\n lists?: number;\n }>;\n}>;\n\n/**\n * Derives the `VectorCapabilities` a backend advertises from its active\n * strategy, so the two never drift (mirrors `buildFulltextCapabilities`).\n * The strategy is the single source of truth; there are no per-call-site\n * `SQLITE_VECTOR_*` constants.\n */\nexport function buildVectorCapabilities(\n strategy: VectorStrategy,\n): VectorCapabilities {\n return strategy.capabilities;\n}\n\n/**\n * A pluggable vector implementation. Each strategy is self-contained:\n * given a {@link VectorSlot}, it emits every statement the backend and\n * compiler need — per-field storage DDL, writes, similarity search, ANN\n * index lifecycle — and advertises exactly the metrics and index types it\n * can honor. Adding the Nth backend is one of these objects; no core edits.\n */\nexport interface VectorStrategy {\n /** Human-readable identifier used in error messages and telemetry. */\n readonly name: string;\n\n /**\n * The metrics, index types, and dimension ceiling this strategy honors —\n * advertised verbatim as `backend.capabilities.vector`. Asymmetry across\n * engines is legitimate and explicit here (pgvector has `inner_product`;\n * libSQL/sqlite-vec do not), never a silent runtime failure.\n */\n readonly capabilities: VectorCapabilities;\n\n /**\n * Deterministic physical table (or virtual-table) name backing a field in\n * a graph. The compiler references this to scan the right per-field storage,\n * and the backend uses it to route upserts/deletes. Must be a stable,\n * collision-safe SQL identifier derived from `(graphId, nodeKind, fieldPath)`.\n */\n tableName(graphId: string, nodeKind: string, fieldPath: string): string;\n\n /**\n * The per-field storage this strategy owns for `slot`, as Drizzle-free\n * `StrategyTableContribution`s (resolved `tableName`, deterministic\n * idempotent `createDdl` for the table **and** its ANN index when the\n * slot's `indexType` warrants one, `runtimeEnsure`). Rides the #129/#135\n * table-contribution + durable-materialization machinery exactly as the\n * FTS5 / tsvector virtual tables do — these are materialized per graph by\n * `materializeIndexes()`, not by global `bootstrapTables`.\n */\n ownedTables(slot: VectorSlot): readonly StrategyTableContribution[];\n\n /**\n * Emits the statement(s) that upsert a single embedding into the slot's\n * storage. Multiple statements are allowed for engines that cannot upsert\n * a vector in one statement (e.g. a `vec0` virtual table → DELETE+INSERT).\n */\n buildUpsert(\n slot: VectorSlot,\n params: UpsertEmbeddingParams,\n timestamp: string,\n ): readonly SQL[];\n\n /**\n * Emits the statement(s) that upsert MANY embeddings into the slot's\n * storage in multi-row form. Optional — the backend falls back to one\n * {@link buildUpsert} per row when unset. The backend guarantees the\n * rows carry distinct `nodeId`s and fit the connection's bound-parameter\n * budget (it chunks before calling).\n */\n buildUpsertBatch?(\n slot: VectorSlot,\n params: UpsertEmbeddingBatchParams,\n timestamp: string,\n ): readonly SQL[];\n\n /** Emits the statement(s) that delete a single embedding from the slot. */\n buildDelete(slot: VectorSlot, params: DeleteEmbeddingParams): readonly SQL[];\n\n /**\n * Raw DDL statement(s) that drop the slot's entire physical storage\n * (table + ANN index, and any engine-managed shadow tables). Used by the\n * destructive `store.reembedVectorField()` path to recreate a field's\n * storage at a new dimension. Returned as raw strings (like\n * `ownedTables(...).createDdl`) for `backend.executeDdl`; must be idempotent\n * (`IF EXISTS`).\n */\n buildDropStorage(slot: VectorSlot): readonly string[];\n\n /**\n * Emits the similarity-search query for the `backend.vectorSearch` path,\n * returning rows shaped `{ node_id, score }` ordered best-first. The\n * strategy picks brute-force vs ANN based on whether `slot.indexType`\n * materialized an index — the caller never branches. `score` follows the\n * shared convention (cosine → similarity `1 - distance`; l2 /\n * inner_product → raw distance), so `coerceVectorScore` / fusion stay\n * dialect-neutral.\n *\n * `candidates`, when provided, is a subquery yielding the node ids\n * eligible to appear in results (the backend passes its live-node-ids\n * subquery so top-k is computed over live rows in SQL — see\n * `liveNodeIdsSubquery`). Strategies whose ANN form cannot take the\n * filter directly must over-fetch and post-filter, documenting the\n * recall bound. A custom strategy that ignores the argument keeps the\n * pre-pushdown behavior: tombstoned ids are dropped after top-k during\n * hydration, so results can shrink below `limit` under index drift.\n */\n buildSearch(\n slot: VectorSlot,\n params: VectorSearchParams,\n candidates?: SQL,\n ): SQL;\n\n /**\n * True when {@link buildSearch} returns EXACT rankings — a brute-force\n * engine form, not an approximate index (sqlite-vec's vec0 KNN scans\n * every row in C). The query compiler then routes the NON-approximate\n * `.similarTo()` branch through `buildSearch` too: same results as the\n * SQL distance scan, at engine speed (measured 489ms -> 113ms at 50k\n * on the SQLite lane). Leave false/absent when the engine form is or\n * can be approximate (pgvector planner rewrites, libSQL DiskANN):\n * exactness of the default path is a semantic guarantee.\n */\n searchIsExact?: boolean;\n\n /**\n * The distance expression over the slot's embedding column, used by the\n * **query compiler** to splice vector relevance into its CTE. This is the\n * one genuinely engine-specific fragment (`vec_distance_cosine` vs\n * `<=>` vs `vector_distance_cos`); the surrounding score / minScore /\n * ORDER BY math is shared (see {@link vectorScoreExpression} etc.).\n *\n * `embeddingColumn` is the already-qualified column SQL; `queryEmbedding`\n * is formatted by the strategy into its engine's literal form.\n */\n distanceExpression(\n embeddingColumn: SQL,\n queryEmbedding: readonly number[],\n metric: VectorMetric,\n ): SQL;\n\n /**\n * Emits the ANN index creation statement for a slot, or `undefined` when\n * indexing is inline (vec0) or unsupported (brute-force-only strategies).\n * Invoked through `backend.createVectorIndex` during `materializeIndexes`.\n */\n buildCreateIndex?(\n slot: VectorSlot,\n options?: Readonly<{ concurrent?: boolean }>,\n ): SQL | undefined;\n\n /** Emits the ANN index drop statement, or `undefined` when not applicable. */\n buildDropIndex?(slot: VectorSlot): SQL | undefined;\n}\n\n// ============================================================\n// Shared, dialect-neutral expression math\n// ============================================================\n//\n// These transforms are identical across pgvector / sqlite-vec / libSQL —\n// only `distanceExpression` differs — so they live once here and are reused\n// by both `buildSearch` implementations and the compiler CTE builder.\n\n/**\n * Converts a distance expression into a score expression (higher = better).\n * Cosine distance is mapped to similarity (`1 - d`); l2 and inner_product\n * are returned as-is (lower distance already ranks better, ordered ASC).\n */\nexport function vectorScoreExpression(\n distanceExpression: SQL,\n metric: VectorMetric,\n): SQL {\n switch (metric) {\n case \"cosine\": {\n return sql`(1 - (${distanceExpression}))`;\n }\n case \"l2\":\n case \"inner_product\": {\n return distanceExpression;\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\n/**\n * Builds the `minScore` WHERE condition against a distance expression,\n * translating the score threshold back into the metric's distance space.\n */\nexport function vectorMinScoreCondition(\n distanceExpression: SQL,\n metric: VectorMetric,\n minScore: number,\n): SQL {\n // Validate against the RESOLVED metric — both the compiler's relevance CTE\n // and the backend search path funnel here, so an out-of-range floor (e.g. a\n // cosine minScore of 5 → `distance <= 1 - 5`, which matches nothing) is\n // rejected loudly instead of silently returning zero rows.\n assertVectorMinScore(minScore, metric);\n switch (metric) {\n case \"cosine\": {\n return sql`${distanceExpression} <= ${1 - minScore}`;\n }\n case \"l2\": {\n return sql`${distanceExpression} <= ${minScore}`;\n }\n case \"inner_product\": {\n return sql`${distanceExpression} <= ${-minScore}`;\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\n/**\n * Validates that every value in an embedding is a finite number. Shared by\n * strategies so a NaN/Infinity is reported with the offending index before\n * it reaches engine-specific literal formatting (which would mask it).\n */\nexport function assertFiniteEmbedding(\n embedding: readonly number[],\n name: string,\n): void {\n for (const [index, value] of embedding.entries()) {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new TypeError(\n `${name}[${index}] must be a finite number, got: ${value}`,\n );\n }\n }\n}\n\n/**\n * Validates a vector-search `limit` is a positive integer. Enforced by the\n * backend's `vectorSearch` (defense in depth — the store boundary also\n * checks) so a direct backend call with `limit: 0` fails loudly instead of\n * silently scanning nothing.\n */\nexport function assertVectorSearchLimit(limit: number): void {\n if (!Number.isInteger(limit) || limit <= 0) {\n throw new RangeError(\n `vectorSearch limit must be a positive integer, got: ${limit}`,\n );\n }\n}\n\n/**\n * Validates a `minScore` floor against its (resolved) metric: it must be finite,\n * and for cosine it must lie in [-1, 1] (a cosine score is the `1 - distance`\n * similarity). Shared by the store facade, the compiler's relevance CTE\n * ({@link vectorMinScoreCondition}), and the backend search path so every entry\n * point rejects the same out-of-range floor instead of silently returning none.\n */\nexport function assertVectorMinScore(\n minScore: number,\n metric: VectorMetric,\n label = \"minScore\",\n): void {\n if (!Number.isFinite(minScore)) {\n throw new RangeError(`${label} must be a finite number, got: ${minScore}`);\n }\n if (metric === \"cosine\" && Math.abs(minScore) > 1) {\n throw new RangeError(\n `${label} for the cosine metric must be between -1 and 1, got: ${minScore}`,\n );\n }\n}\n\n// ============================================================\n// Shared physical naming\n// ============================================================\n\n/**\n * pgvector inherits Postgres' 63-byte identifier ceiling; SQLite/libSQL are\n * far more generous, so the smallest common cap keeps one naming scheme\n * across every strategy.\n */\nconst MAX_VECTOR_IDENTIFIER_LENGTH = 63;\n\nfunction sanitizeIdentifierPart(value: string): string {\n return value.toLowerCase().replaceAll(/[^a-z0-9_]/g, \"_\");\n}\n\n/**\n * Deterministic 8-char hash for collision-safe truncation of over-long\n * identifiers. Self-contained so the strategy layer has no backend-runtime\n * dependency.\n */\nfunction shortHash(input: string): string {\n let h1 = 0xde_ad_be_ef;\n let h2 = 0x41_c6_ce_57;\n for (let index = 0; index < input.length; index++) {\n const ch = input.codePointAt(index)!;\n h1 = Math.imul(h1 ^ ch, 0x9e_37_79_b1);\n h2 = Math.imul(h2 ^ ch, 0x5f_35_64_95);\n }\n h1 =\n Math.imul(h1 ^ (h1 >>> 16), 0x85_eb_ca_6b) ^\n Math.imul(h2 ^ (h2 >>> 13), 0xc2_b2_ae_35);\n h2 =\n Math.imul(h2 ^ (h2 >>> 16), 0x85_eb_ca_6b) ^\n Math.imul(h1 ^ (h1 >>> 13), 0xc2_b2_ae_35);\n const hi = (h2 >>> 0).toString(16).padStart(8, \"0\");\n const lo = (h1 >>> 0).toString(16).padStart(8, \"0\");\n return `${hi}${lo}`.slice(0, 8);\n}\n\n/**\n * Deterministic per-`(graphId, nodeKind, fieldPath)` physical name. Shared by\n * every strategy's `tableName`, by index naming, and by the compiler's\n * per-field table resolution so all three agree on which physical object backs\n * a field in a graph. Truncated with a hash suffix past the 63-char ceiling;\n * the hash covers all three parts, so truncation stays collision-safe even\n * when long graph ids dominate the prefix.\n *\n * @example `vectorPhysicalName(\"tg_vec\", \"g1\", \"Document\", \"embedding\")`\n * → `\"tg_vec_g1_document_embedding_<hash8>\"`\n */\nexport function vectorPhysicalName(\n prefix: string,\n graphId: string,\n nodeKind: string,\n fieldPath: string,\n): string {\n const readable = `${prefix}_${sanitizeIdentifierPart(graphId)}_${sanitizeIdentifierPart(nodeKind)}_${sanitizeIdentifierPart(fieldPath)}`;\n // Always suffix a hash of the EXACT (graphId, nodeKind, fieldPath) tuple.\n // Sanitization is lossy (case-folding, every non-`[a-z0-9_]` char → `_`) and\n // the `_` join is ambiguous, so distinct fields can share a readable part —\n // e.g. (\"a_b\",\"c\") vs (\"a\",\"b_c\"), or \"Doc-A\" vs \"Doc_A\" vs \"doc\". The hash\n // keeps their physical tables distinct so writes/searches never cross fields.\n const hash = shortHash(JSON.stringify([graphId, nodeKind, fieldPath]));\n const full = `${readable}_${hash}`;\n if (full.length <= MAX_VECTOR_IDENTIFIER_LENGTH) return full;\n // Over the ceiling: truncate the readable part, always keep the hash.\n return `${readable.slice(0, MAX_VECTOR_IDENTIFIER_LENGTH - 1 - hash.length)}_${hash}`;\n}\n\n/**\n * Double-quote a SQL identifier, escaping embedded quotes. Dialect-neutral\n * (both SQLite and Postgres use `\"...\"`), so the three vector strategies share\n * one implementation for quoting their per-field table / index names.\n */\nexport function quoteIdentifier(name: string): string {\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n}\n","/**\n * PostgreSQL Dialect Adapter\n *\n * Implements dialect-specific SQL generation for PostgreSQL databases.\n * Uses PostgreSQL's native JSONB operators for JSON operations.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { type JsonPointer, parseJsonPointer } from \"../json-pointer\";\nimport { tsvectorStrategy } from \"./fulltext-strategy\";\nimport { likeEscapeClause } from \"./like-escape\";\nimport { type DialectAdapter } from \"./types\";\n\n/**\n * Escapes a string for use in a PostgreSQL string literal.\n * Uses single quotes and escapes embedded single quotes.\n */\nfunction escapePostgresLiteral(value: string): string {\n // PostgreSQL uses '' to escape single quotes inside string literals\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\n/**\n * Converts a JSON pointer to PostgreSQL's text array path.\n *\n * Uses raw SQL (non-parameterized) to ensure the same expression text\n * is generated when the same field is used in multiple clauses (SELECT, GROUP BY).\n * This is safe because JSON pointers come from schema definitions, not user input.\n *\n * @example\n * \"/name\" → ARRAY['name']\n * \"/items/0\" → ARRAY['items', '0']\n * \"/a/b/c\" → ARRAY['a', 'b', 'c']\n */\nfunction toPostgresPath(pointer: JsonPointer): SQL {\n if (!pointer || pointer === \"\" || pointer === \"/\") {\n return sql.raw(\"ARRAY[]::text[]\");\n }\n\n const segments = parseJsonPointer(pointer);\n if (segments.length === 0) {\n return sql.raw(\"ARRAY[]::text[]\");\n }\n\n // Use raw SQL for path segments to ensure identical SQL text\n // when the same field is used in multiple clauses (e.g., SELECT and GROUP BY)\n const escapedSegments = segments\n .map((segment) => escapePostgresLiteral(segment))\n .join(\", \");\n return sql.raw(`ARRAY[${escapedSegments}]`);\n}\n\n/**\n * PostgreSQL dialect adapter implementation.\n */\nexport const postgresDialect: DialectAdapter = {\n name: \"postgres\",\n capabilities: {\n standardQueryStrategy: \"cte_project\",\n recursiveQueryStrategy: \"recursive_cte\",\n materializeIntermediateTraversalCtes: false,\n emitNotMaterializedHint: true,\n forceRecursiveWorktableOuterJoinOrder: false,\n vectorPredicateStrategy: \"native\",\n vectorMetrics: [\"cosine\", \"l2\", \"inner_product\"] as const,\n supportsFulltext: true,\n },\n\n // ============================================================\n // JSON Path Operations\n // ============================================================\n\n compilePath(pointer) {\n return toPostgresPath(pointer);\n },\n\n jsonExtract(column, pointer) {\n // #> returns JSONB value at path\n const path = toPostgresPath(pointer);\n return sql`${column} #> ${path}`;\n },\n\n jsonExtractText(column, pointer) {\n // #>> returns text value at path\n const path = toPostgresPath(pointer);\n return sql`${column} #>> ${path}`;\n },\n\n jsonExtractNumber(column, pointer) {\n // Extract as text then cast to numeric\n const path = toPostgresPath(pointer);\n return sql`(${column} #>> ${path})::numeric`;\n },\n\n jsonExtractBoolean(column, pointer) {\n // Extract as text then cast to boolean\n const path = toPostgresPath(pointer);\n return sql`(${column} #>> ${path})::boolean`;\n },\n\n jsonExtractDate(column, pointer) {\n // Extract as text then cast to timestamptz\n const path = toPostgresPath(pointer);\n return sql`(${column} #>> ${path})::timestamptz`;\n },\n\n // ============================================================\n // JSON Array Operations\n // ============================================================\n\n jsonArrayLength(column) {\n return sql`jsonb_array_length(${column})`;\n },\n\n jsonArrayContains(column, value) {\n // @> checks if left contains right\n const jsonValue = JSON.stringify([value]);\n return sql`${column} @> ${jsonValue}::jsonb`;\n },\n\n jsonArrayContainsAll(column, values) {\n if (values.length === 0) {\n return sql.raw(\"1=1\");\n }\n\n // @> with full array checks all values\n const jsonValue = JSON.stringify(values);\n return sql`${column} @> ${jsonValue}::jsonb`;\n },\n\n jsonArrayContainsAny(column, values) {\n if (values.length === 0) {\n return sql.raw(\"1=0\");\n }\n\n // Check each value with @> and OR them together\n // PostgreSQL doesn't have a native \"overlaps\" for jsonb arrays\n const conditions = values.map((value) => {\n const jsonValue = JSON.stringify([value]);\n return sql`${column} @> ${jsonValue}::jsonb`;\n });\n return sql`(${sql.join(conditions, sql` OR `)})`;\n },\n\n // ============================================================\n // JSON Object Operations\n // ============================================================\n\n jsonHasPath(column, pointer) {\n const path = toPostgresPath(pointer);\n return sql`${column} #> ${path} IS NOT NULL`;\n },\n\n jsonPathIsNull(column, pointer) {\n const path = toPostgresPath(pointer);\n // Check both SQL NULL and JSON null literal\n return sql`(${column} #> ${path} IS NULL OR ${column} #>> ${path} = 'null')`;\n },\n\n jsonPathIsNotNull(column, pointer) {\n const path = toPostgresPath(pointer);\n return sql`(${column} #> ${path} IS NOT NULL AND ${column} #>> ${path} != 'null')`;\n },\n\n // ============================================================\n // Comparison Operations\n // ============================================================\n\n nullSafeEquals(left, right) {\n return sql`${left} IS NOT DISTINCT FROM ${right}`;\n },\n\n // ============================================================\n // String Operations\n // ============================================================\n\n ilike(column, pattern) {\n // PostgreSQL has native ILIKE operator. Declaring backslash as the escape\n // character is a no-op (it is the LIKE default) but keeps the emitted SQL\n // identical in intent to SQLite, which has no default escape character.\n return sql`${column} ILIKE ${pattern} ${likeEscapeClause}`;\n },\n\n // ============================================================\n // Set Operations\n // ============================================================\n\n wrapSetOperationOperand(inner) {\n // PostgreSQL allows a complete SELECT (incl. its own WITH) as a\n // parenthesized compound operand.\n return sql`(${inner})`;\n },\n\n // ============================================================\n // Recursive CTE Path Operations\n // ============================================================\n\n initializePath(nodeId) {\n // PostgreSQL uses text arrays: ARRAY[id]\n return sql`ARRAY[${nodeId}]`;\n },\n\n extendPath(currentPath, nodeId) {\n // Array concatenation: path || id\n return sql`${currentPath} || ${nodeId}`;\n },\n\n cycleCheck(nodeId, path) {\n // Check that id is NOT in array path\n // Returns TRUE if no cycle (id not in array)\n return sql`${nodeId} != ALL(${path})`;\n },\n\n // ============================================================\n // Value Binding & Literals\n // ============================================================\n\n bindValue(value) {\n // PostgreSQL supports native booleans, no conversion needed\n return value;\n },\n\n booleanLiteral(value) {\n return sql.raw(this.booleanLiteralString(value));\n },\n\n booleanLiteralString(value) {\n return value ? \"TRUE\" : \"FALSE\";\n },\n\n quoteIdentifier(name) {\n // PostgreSQL uses double quotes, escape embedded quotes by doubling\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n },\n\n // ============================================================\n // Vector Operations\n // ============================================================\n\n // Compile-time gate for `field.similarTo(...)`; the active\n // `VectorStrategy` (pgvector) owns the distance SQL.\n supportsVectors: true,\n\n // ============================================================\n // Fulltext Operations\n // ============================================================\n\n fulltext: tsvectorStrategy,\n};\n","/**\n * SQLite Dialect Adapter\n *\n * Implements dialect-specific SQL generation for SQLite databases.\n * Uses SQLite's JSON1 extension for JSON operations.\n */\nimport { sql } from \"drizzle-orm\";\n\nimport { type JsonPointer, parseJsonPointer } from \"../json-pointer\";\nimport { fts5Strategy } from \"./fulltext-strategy\";\nimport { likeEscapeClause } from \"./like-escape\";\nimport { type DialectAdapter } from \"./types\";\n\n/**\n * Escapes a string for use in a SQLite string literal.\n * SQLite uses single quotes and escapes embedded single quotes by doubling them.\n */\nfunction escapeSqliteLiteral(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\n/**\n * Converts a JSON pointer to SQLite's JSON path syntax.\n *\n * @example\n * \"/name\" → \"$.\\\"name\\\"\"\n * \"/items/0\" → \"$.\\\"items\\\"[0]\"\n * \"/a/b/c\" → \"$.\\\"a\\\".\\\"b\\\".\\\"c\\\"\"\n */\nfunction toSqlitePath(pointer: JsonPointer): string {\n if (!pointer || pointer === \"\" || pointer === \"/\") {\n return \"$\";\n }\n\n const segments = parseJsonPointer(pointer);\n const parts: string[] = [\"$\"];\n\n for (const segment of segments) {\n if (isArrayIndex(segment)) {\n parts.push(`[${segment}]`);\n } else {\n // Quote the key to handle special characters\n parts.push(`.${JSON.stringify(segment)}`);\n }\n }\n\n return parts.join(\"\");\n}\n\n/**\n * Checks if a JSON pointer segment is an array index.\n */\nfunction isArrayIndex(segment: string): boolean {\n return /^\\d+$/.test(segment);\n}\n\n/**\n * SQLite dialect adapter implementation.\n */\nexport const sqliteDialect: DialectAdapter = {\n name: \"sqlite\",\n capabilities: {\n standardQueryStrategy: \"cte_project\",\n recursiveQueryStrategy: \"recursive_cte\",\n materializeIntermediateTraversalCtes: true,\n emitNotMaterializedHint: false,\n forceRecursiveWorktableOuterJoinOrder: true,\n vectorPredicateStrategy: \"native\",\n vectorMetrics: [\"cosine\", \"l2\"] as const,\n supportsFulltext: true,\n },\n\n // ============================================================\n // JSON Path Operations\n // ============================================================\n\n compilePath(pointer) {\n // Use raw SQL to ensure the path is a literal, which allows expression\n // indexes on json_extract(...) to be used by the query planner.\n return sql.raw(escapeSqliteLiteral(toSqlitePath(pointer)));\n },\n\n jsonExtract(column, pointer) {\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractText(column, pointer) {\n // SQLite's json_extract returns the native JSON type, which works\n // for text comparisons. For explicit text, we use the same function.\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractNumber(column, pointer) {\n // SQLite json_extract returns numbers natively when the value is numeric\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractBoolean(column, pointer) {\n // SQLite json_extract returns 0/1 for boolean values\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractDate(column, pointer) {\n // SQLite stores dates as ISO strings, json_extract returns them as text\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n // ============================================================\n // JSON Array Operations\n // ============================================================\n\n jsonArrayLength(column) {\n return sql`json_array_length(${column})`;\n },\n\n jsonArrayContains(column, value) {\n return sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE json_each.value = ${value})`;\n },\n\n jsonArrayContainsAll(column, values) {\n if (values.length === 0) {\n return sql.raw(\"1=1\");\n }\n\n const conditions = values.map(\n (value) =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE json_each.value = ${value})`,\n );\n return sql`(${sql.join(conditions, sql` AND `)})`;\n },\n\n jsonArrayContainsAny(column, values) {\n if (values.length === 0) {\n return sql.raw(\"1=0\");\n }\n\n const conditions = values.map(\n (value) =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE json_each.value = ${value})`,\n );\n return sql`(${sql.join(conditions, sql` OR `)})`;\n },\n\n // ============================================================\n // JSON Object Operations\n // ============================================================\n\n jsonHasPath(column, pointer) {\n const path = toSqlitePath(pointer);\n return sql`json_type(${column}, ${sql.raw(escapeSqliteLiteral(path))}) IS NOT NULL`;\n },\n\n jsonPathIsNull(column, pointer) {\n const path = toSqlitePath(pointer);\n const pathSql = sql.raw(escapeSqliteLiteral(path));\n return sql`(json_extract(${column}, ${pathSql}) IS NULL OR json_type(${column}, ${pathSql}) = 'null')`;\n },\n\n jsonPathIsNotNull(column, pointer) {\n const path = toSqlitePath(pointer);\n const pathSql = sql.raw(escapeSqliteLiteral(path));\n return sql`(json_extract(${column}, ${pathSql}) IS NOT NULL AND json_type(${column}, ${pathSql}) != 'null')`;\n },\n\n // ============================================================\n // Comparison Operations\n // ============================================================\n\n nullSafeEquals(left, right) {\n // SQLite's IS operator is null-safe equality (equivalent to = for\n // non-null operands, TRUE when both sides are NULL).\n return sql`${left} IS ${right}`;\n },\n\n // ============================================================\n // String Operations\n // ============================================================\n\n ilike(column, pattern) {\n // SQLite LIKE is case-insensitive for ASCII by default, but we use\n // LOWER() for consistency with non-ASCII characters. SQLite has no default\n // LIKE escape character, so declare backslash explicitly to honor the\n // escaping the compiler applies to the pattern (parity with Postgres).\n return sql`LOWER(${column}) LIKE LOWER(${pattern}) ${likeEscapeClause}`;\n },\n\n // ============================================================\n // Set Operations\n // ============================================================\n\n wrapSetOperationOperand(inner) {\n // SQLite forbids parenthesized compound operands, but a FROM-subquery may\n // carry its own WITH clause, so wrap each operand as a subquery.\n return sql`SELECT * FROM (${inner})`;\n },\n\n // ============================================================\n // Recursive CTE Path Operations\n // ============================================================\n\n initializePath(nodeId) {\n // SQLite uses string-based paths with delimiters: '|id|'\n return sql`'|' || ${nodeId} || '|'`;\n },\n\n extendPath(currentPath, nodeId) {\n // Append: path || id || '|'\n return sql`${currentPath} || ${nodeId} || '|'`;\n },\n\n cycleCheck(nodeId, path) {\n // Check that id is NOT in path using INSTR\n // Returns TRUE if no cycle (id not found in path)\n return sql`INSTR(${path}, '|' || ${nodeId} || '|') = 0`;\n },\n\n // ============================================================\n // Value Binding & Literals\n // ============================================================\n\n bindValue(value) {\n // SQLite doesn't support native booleans, convert to 0/1\n if (typeof value === \"boolean\") {\n return value ? 1 : 0;\n }\n return value;\n },\n\n booleanLiteral(value) {\n return sql.raw(this.booleanLiteralString(value));\n },\n\n booleanLiteralString(value) {\n return value ? \"1\" : \"0\";\n },\n\n quoteIdentifier(name) {\n // SQLite uses double quotes (or backticks), escape embedded quotes by doubling\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n },\n\n // ============================================================\n // Vector Operations\n // ============================================================\n\n // Compile-time gate for `field.similarTo(...)`; the active\n // `VectorStrategy` (sqlite-vec / libSQL-native) owns the distance SQL.\n supportsVectors: true,\n\n // ============================================================\n // Fulltext Operations\n // ============================================================\n\n fulltext: fts5Strategy,\n};\n","/**\n * SQL Dialect Module\n *\n * Provides dialect adapters for different SQL databases.\n * Use `getDialect()` to get the appropriate adapter for a dialect name.\n */\n\nexport type { FulltextStrategy } from \"./fulltext-strategy\";\nexport {\n ALL_FULLTEXT_MODES,\n buildFulltextCapabilities,\n fts5Strategy,\n tsvectorStrategy,\n} from \"./fulltext-strategy\";\nexport { postgresDialect } from \"./postgres\";\nexport { sqliteDialect } from \"./sqlite\";\nexport type {\n DialectAdapter,\n DialectCapabilities,\n DialectRecursiveQueryStrategy,\n DialectStandardQueryStrategy,\n DialectVectorPredicateStrategy,\n SqlDialect,\n} from \"./types\";\nexport {\n buildVectorCapabilities,\n type VectorSlot,\n type VectorStrategy,\n} from \"./vector-strategy\";\n\nimport { postgresDialect } from \"./postgres\";\nimport { sqliteDialect } from \"./sqlite\";\nimport { type DialectAdapter, type SqlDialect } from \"./types\";\n\n/**\n * Map of dialect names to their adapters.\n */\nconst DIALECT_ADAPTERS: Record<SqlDialect, DialectAdapter> = {\n sqlite: sqliteDialect,\n postgres: postgresDialect,\n};\n\n/**\n * Gets the dialect adapter for a given dialect name.\n *\n * @param dialect - The dialect name (\"sqlite\" or \"postgres\")\n * @returns The dialect adapter\n *\n * @example\n * ```typescript\n * const adapter = getDialect(\"postgres\");\n * const sql = adapter.jsonExtract(column, \"/name\");\n * ```\n */\nexport function getDialect(dialect: SqlDialect): DialectAdapter {\n return DIALECT_ADAPTERS[dialect];\n}\n\n/**\n * Default dialect used when none is specified.\n */\nexport const DEFAULT_DIALECT: SqlDialect = \"sqlite\";\n","import { type SQL, sql } from \"drizzle-orm\";\n\nimport { type ValueType } from \"../query/ast\";\nimport { getDialect } from \"../query/dialect\";\nimport { type SqlDialect } from \"../query/dialect/types\";\nimport { type JsonPointer, jsonPointer } from \"../query/json-pointer\";\nimport {\n type EdgeIndexDeclaration,\n type IndexWhereExpression,\n type IndexWhereLiteral,\n type IndexWhereOp,\n type IndexWhereOperand,\n type NodeIndexDeclaration,\n type SystemColumnName,\n} from \"./types\";\n\n// ============================================================\n// Public Types\n// ============================================================\n\nexport type IndexCompilationContext = Readonly<{\n dialect: SqlDialect;\n propsColumn: SQL;\n systemColumn: (column: SystemColumnName) => SQL;\n}>;\n\ntype CompiledIndexKeys = Readonly<{\n /** SQL expressions in index key order */\n keys: readonly SQL[];\n}>;\n\n// ============================================================\n// Index Key Compilation\n// ============================================================\n\nexport function compileNodeIndexKeys(\n index: NodeIndexDeclaration,\n dialect: SqlDialect,\n propsColumn: SQL,\n systemColumn: (column: SystemColumnName) => SQL,\n): CompiledIndexKeys {\n const adapter = getDialect(dialect);\n const keys: SQL[] = [];\n\n const systemColumns = [\n ...getNodeScopeColumns(index.scope),\n ...(index.keySystemColumns ?? []),\n ];\n for (const column of systemColumns) {\n keys.push(systemColumn(column));\n }\n\n const allPointers = [...index.fields, ...index.coveringFields];\n const allValueTypes = [\n ...index.fieldValueTypes,\n ...index.coveringFieldValueTypes,\n ];\n\n for (const [pointerIndex, pointer] of allPointers.entries()) {\n const valueType = allValueTypes[pointerIndex];\n const extracted = compileIndexKeyValue(\n adapter,\n propsColumn,\n pointer,\n valueType,\n );\n keys.push(sql`(${extracted})`);\n }\n\n return { keys };\n}\n\nexport function compileEdgeIndexKeys(\n index: EdgeIndexDeclaration,\n dialect: SqlDialect,\n propsColumn: SQL,\n systemColumn: (column: SystemColumnName) => SQL,\n): CompiledIndexKeys {\n const adapter = getDialect(dialect);\n const keys: SQL[] = [];\n\n for (const column of getEdgeScopeColumns(index.scope, index.direction)) {\n keys.push(systemColumn(column));\n }\n\n const allPointers = [...index.fields, ...index.coveringFields];\n const allValueTypes = [\n ...index.fieldValueTypes,\n ...index.coveringFieldValueTypes,\n ];\n\n for (const [pointerIndex, pointer] of allPointers.entries()) {\n const valueType = allValueTypes[pointerIndex];\n const extracted = compileIndexKeyValue(\n adapter,\n propsColumn,\n pointer,\n valueType,\n );\n keys.push(sql`(${extracted})`);\n }\n\n return { keys };\n}\n\n/**\n * Compiles the per-field key-extraction expressions for a node index's\n * **lookup keys** — `index.fields` only, excluding scope columns and\n * `coveringFields` (which are index payload, not part of the lookup key).\n *\n * Each expression is the exact extraction the index DDL builds for that\n * field (via the shared {@link compileIndexKeyValue}), so a runtime lookup\n * predicate stays byte-identical to the materialized index expression —\n * the single source of truth that lets the planner use the physical index.\n */\nexport function compileNodeIndexFieldKeys(\n index: NodeIndexDeclaration,\n ctx: IndexCompilationContext,\n): readonly SQL[] {\n const adapter = getDialect(ctx.dialect);\n const keys: SQL[] = [];\n for (const [position, pointer] of index.fields.entries()) {\n const extracted = compileIndexKeyValue(\n adapter,\n ctx.propsColumn,\n pointer,\n index.fieldValueTypes[position],\n );\n keys.push(sql`(${extracted})`);\n }\n return keys;\n}\n\nfunction compileIndexKeyValue(\n dialect: ReturnType<typeof getDialect>,\n propsColumn: SQL,\n pointer: JsonPointer,\n valueType: ValueType | undefined,\n): SQL {\n switch (valueType) {\n case \"number\": {\n return dialect.jsonExtractNumber(propsColumn, pointer);\n }\n case \"boolean\": {\n return dialect.jsonExtractBoolean(propsColumn, pointer);\n }\n case \"date\": {\n return dialect.jsonExtractDate(propsColumn, pointer);\n }\n case \"string\":\n case \"unknown\":\n case undefined: {\n return dialect.jsonExtractText(propsColumn, pointer);\n }\n case \"array\":\n case \"object\":\n case \"embedding\": {\n // For advanced index types (GIN/json), callers should use dialect.jsonExtract\n // or index the props column directly. We keep this as a conservative fallback.\n return dialect.jsonExtract(propsColumn, pointer);\n }\n }\n}\n\nexport function getNodeScopeColumns(\n scope: NodeIndexDeclaration[\"scope\"],\n): readonly SystemColumnName[] {\n switch (scope) {\n case \"graphAndKind\": {\n return [\"graph_id\", \"kind\"];\n }\n case \"graph\": {\n return [\"graph_id\"];\n }\n case \"none\": {\n return [];\n }\n }\n}\n\nfunction getEdgeScopeColumns(\n scope: EdgeIndexDeclaration[\"scope\"],\n direction: EdgeIndexDeclaration[\"direction\"],\n): readonly SystemColumnName[] {\n const base =\n scope === \"graphAndKind\" ? ([\"graph_id\", \"kind\"] as const)\n : scope === \"graph\" ? ([\"graph_id\"] as const)\n : ([] as const);\n\n if (direction === \"out\") {\n return [...base, \"from_id\"];\n }\n if (direction === \"in\") {\n return [...base, \"to_id\"];\n }\n return [...base];\n}\n\n// ============================================================\n// WHERE Clause Compilation\n// ============================================================\n\nfunction isIndexWhereLiteralList(\n value: IndexWhereLiteral | readonly IndexWhereLiteral[],\n): value is readonly IndexWhereLiteral[] {\n return Array.isArray(value);\n}\n\nexport function compileIndexWhere(\n ctx: IndexCompilationContext,\n expression: IndexWhereExpression,\n): SQL {\n switch (expression.__type) {\n case \"index_where_and\": {\n return sql`(${sql.join(\n expression.predicates.map((p) => compileIndexWhere(ctx, p)),\n sql` AND `,\n )})`;\n }\n case \"index_where_or\": {\n return sql`(${sql.join(\n expression.predicates.map((p) => compileIndexWhere(ctx, p)),\n sql` OR `,\n )})`;\n }\n case \"index_where_not\": {\n return sql`(NOT ${compileIndexWhere(ctx, expression.predicate)})`;\n }\n case \"index_where_null_check\": {\n const operand = compileIndexWhereOperand(ctx, expression.operand);\n return expression.op === \"isNull\" ?\n sql`${operand} IS NULL`\n : sql`${operand} IS NOT NULL`;\n }\n case \"index_where_comparison\": {\n const left = compileIndexWhereOperand(ctx, expression.left);\n\n const right = expression.right;\n if (isIndexWhereLiteralList(right)) {\n if (expression.op !== \"in\" && expression.op !== \"notIn\") {\n throw new Error(\n `Operator \"${expression.op}\" does not support list comparison in index WHERE clause`,\n );\n }\n const values = right.map((literal) =>\n compileIndexWhereLiteral(ctx.dialect, literal),\n );\n const operator = expression.op === \"in\" ? sql`IN` : sql`NOT IN`;\n return sql`${left} ${operator} (${sql.join(values, sql`, `)})`;\n }\n\n if (expression.op === \"in\" || expression.op === \"notIn\") {\n throw new Error(\n `Operator \"${expression.op}\" requires a list of values in index WHERE clause`,\n );\n }\n\n const rightLiteral = compileIndexWhereLiteral(ctx.dialect, right);\n const opSql = compileComparisonOperator(expression.op);\n return sql`${left} ${opSql} ${rightLiteral}`;\n }\n }\n}\n\nfunction compileIndexWhereOperand(\n ctx: IndexCompilationContext,\n operand: IndexWhereOperand,\n): SQL {\n if (operand.__type === \"index_operand_system\") {\n return ctx.systemColumn(operand.column);\n }\n\n const adapter = getDialect(ctx.dialect);\n const pointer = jsonPointer([operand.field]);\n\n switch (operand.valueType) {\n case \"number\": {\n return adapter.jsonExtractNumber(ctx.propsColumn, pointer);\n }\n case \"boolean\": {\n return adapter.jsonExtractBoolean(ctx.propsColumn, pointer);\n }\n case \"date\": {\n return adapter.jsonExtractDate(ctx.propsColumn, pointer);\n }\n case \"array\":\n case \"object\":\n case \"embedding\": {\n return adapter.jsonExtract(ctx.propsColumn, pointer);\n }\n case \"string\":\n case \"unknown\":\n case undefined: {\n return adapter.jsonExtractText(ctx.propsColumn, pointer);\n }\n }\n}\n\nfunction compileIndexWhereLiteral(\n dialect: SqlDialect,\n literal: IndexWhereLiteral,\n): SQL {\n switch (literal.valueType) {\n case \"string\":\n case \"date\": {\n return sql.raw(escapeStringLiteral(literal.value.toString()));\n }\n case \"number\": {\n return sql.raw(literal.value.toString());\n }\n case \"boolean\": {\n return getDialect(dialect).booleanLiteral(literal.value as boolean);\n }\n case \"array\":\n case \"object\":\n case \"embedding\":\n case \"unknown\": {\n return sql.raw(escapeStringLiteral(literal.value.toString()));\n }\n }\n}\n\ntype ComparisonIndexWhereOp = Exclude<IndexWhereOp, \"in\" | \"notIn\">;\n\nfunction compileComparisonOperator(op: ComparisonIndexWhereOp): SQL {\n switch (op) {\n case \"eq\": {\n return sql`=`;\n }\n case \"neq\": {\n return sql`<>`;\n }\n case \"gt\": {\n return sql`>`;\n }\n case \"gte\": {\n return sql`>=`;\n }\n case \"lt\": {\n return sql`<`;\n }\n case \"lte\": {\n return sql`<=`;\n }\n }\n}\n\nfunction escapeStringLiteral(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n"]}
@@ -0,0 +1,10 @@
1
+ import { sql } from 'drizzle-orm';
2
+
3
+ // src/query/dialect/vector/pagination.ts
4
+ function vectorPageClause(limit, offset) {
5
+ return offset === void 0 || offset === 0 ? sql`LIMIT ${limit}` : sql`LIMIT ${limit} OFFSET ${offset}`;
6
+ }
7
+
8
+ export { vectorPageClause };
9
+ //# sourceMappingURL=chunk-DFVLCOP6.js.map
10
+ //# sourceMappingURL=chunk-DFVLCOP6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/query/dialect/vector/pagination.ts"],"names":[],"mappings":";;;AAcO,SAAS,gBAAA,CAAiB,OAAe,MAAA,EAAsB;AACpE,EAAA,OAAO,MAAA,KAAW,MAAA,IAAa,MAAA,KAAW,CAAA,GACtC,GAAA,CAAA,MAAA,EAAY,KAAK,CAAA,CAAA,GACjB,GAAA,CAAA,MAAA,EAAY,KAAK,CAAA,QAAA,EAAW,MAAM,CAAA,CAAA;AACxC","file":"chunk-DFVLCOP6.js","sourcesContent":["/**\n * Shared vector-search pagination clause.\n *\n * Every vector strategy pages its ordered relevance scan the same way: emit a\n * bare `LIMIT` for the first page (`offset` unset or `0`), and `LIMIT … OFFSET`\n * only when a non-zero offset must discard the leading rows. The three engines'\n * `buildSearch` methods each repeated this ternary verbatim; it lives here once\n * so the emitted clause can never drift between dialects.\n *\n * `limit` and `offset` ride as bound parameters (never interpolated), so the\n * clause — string and bound values alike — is identical across engines.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nexport function vectorPageClause(limit: number, offset?: number): SQL {\n return offset === undefined || offset === 0 ?\n sql`LIMIT ${limit}`\n : sql`LIMIT ${limit} OFFSET ${offset}`;\n}\n"]}
@@ -372,6 +372,20 @@ var ConfigurationError = class extends TypeGraphError {
372
372
  this.name = "ConfigurationError";
373
373
  }
374
374
  };
375
+ var RECORDED_CAPTURE_GUARD_CODES = [
376
+ "RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION",
377
+ "RECORDED_CAPTURE_RAW_SQL_DISABLED",
378
+ "REVISION_TRACKING_RAW_SQL_DISABLED"
379
+ ];
380
+ function isRecordedCaptureGuardCode(value) {
381
+ return RECORDED_CAPTURE_GUARD_CODES.includes(value);
382
+ }
383
+ function isRecordedCaptureGuardError(error, code) {
384
+ if (!(error instanceof ConfigurationError)) return false;
385
+ const actual = error.details.code;
386
+ if (!isRecordedCaptureGuardCode(actual)) return false;
387
+ return code === void 0 || actual === code;
388
+ }
375
389
  var STORE_NOT_INITIALIZED_REASON_PHRASE = {
376
390
  missing: "is not initialized",
377
391
  stale: "is stale (recorded materialization signature no longer matches)",
@@ -380,13 +394,15 @@ var STORE_NOT_INITIALIZED_REASON_PHRASE = {
380
394
  var StoreNotInitializedError = class extends TypeGraphError {
381
395
  // `graphId`/`reason` are positional and required: both are
382
396
  // load-bearing for the message and for programmatic handling via
383
- // `details.reason`. Caller `details` merge on top.
397
+ // `details.reason`. Caller `details` merge underneath — spread first
398
+ // so `graphId`/`reason` win and can't be clobbered by an
399
+ // accidentally-colliding extra key.
384
400
  constructor(graphId, reason, options) {
385
401
  super(
386
402
  `fulltext storage for graph "${graphId}" ${STORE_NOT_INITIALIZED_REASON_PHRASE[reason]}. Run createStoreWithSchema(graph, backend) during application boot, outside request handlers and adopted transactions, before using createStore().`,
387
403
  "STORE_NOT_INITIALIZED",
388
404
  {
389
- details: { graphId, reason, ...options?.details },
405
+ details: { ...options?.details, graphId, reason },
390
406
  category: "user",
391
407
  suggestion: "Call createStoreWithSchema(graph, backend) once at application startup. createStore() attaches to an already-initialized database and does not materialize storage itself.",
392
408
  cause: options?.cause
@@ -453,6 +469,20 @@ var BackendDisposedError = class extends TypeGraphError {
453
469
  this.name = "BackendDisposedError";
454
470
  }
455
471
  };
472
+ var TransactionClosedError = class extends TypeGraphError {
473
+ constructor(options) {
474
+ super(
475
+ "Statement issued on a transaction-scoped backend after its transaction boundary returned. The connection has been released; the statement was not run.",
476
+ "TRANSACTION_CLOSED",
477
+ {
478
+ category: "user",
479
+ suggestion: "Await every write started inside store.transaction(...) before the callback returns. Prefer awaiting a Promise.allSettled(...) over a Promise.all(...) whose rejection would orphan its siblings.",
480
+ cause: options?.cause
481
+ }
482
+ );
483
+ this.name = "TransactionClosedError";
484
+ }
485
+ };
456
486
  function isTypeGraphError(error) {
457
487
  return error instanceof TypeGraphError;
458
488
  }
@@ -486,11 +516,13 @@ exports.MigrationError = MigrationError;
486
516
  exports.NodeConstraintNotFoundError = NodeConstraintNotFoundError;
487
517
  exports.NodeIndexNotFoundError = NodeIndexNotFoundError;
488
518
  exports.NodeNotFoundError = NodeNotFoundError;
519
+ exports.RECORDED_CAPTURE_GUARD_CODES = RECORDED_CAPTURE_GUARD_CODES;
489
520
  exports.RestrictedDeleteError = RestrictedDeleteError;
490
521
  exports.SchemaContentConflictError = SchemaContentConflictError;
491
522
  exports.SchemaMismatchError = SchemaMismatchError;
492
523
  exports.StaleVersionError = StaleVersionError;
493
524
  exports.StoreNotInitializedError = StoreNotInitializedError;
525
+ exports.TransactionClosedError = TransactionClosedError;
494
526
  exports.TypeGraphError = TypeGraphError;
495
527
  exports.UniquenessError = UniquenessError;
496
528
  exports.UnsupportedPredicateError = UnsupportedPredicateError;
@@ -498,8 +530,9 @@ exports.ValidationError = ValidationError;
498
530
  exports.VersionConflictError = VersionConflictError;
499
531
  exports.getErrorSuggestion = getErrorSuggestion;
500
532
  exports.isConstraintError = isConstraintError;
533
+ exports.isRecordedCaptureGuardError = isRecordedCaptureGuardError;
501
534
  exports.isSystemError = isSystemError;
502
535
  exports.isTypeGraphError = isTypeGraphError;
503
536
  exports.isUserRecoverable = isUserRecoverable;
504
- //# sourceMappingURL=chunk-JIEJCTDS.cjs.map
505
- //# sourceMappingURL=chunk-JIEJCTDS.cjs.map
537
+ //# sourceMappingURL=chunk-DIK74MXX.cjs.map
538
+ //# sourceMappingURL=chunk-DIK74MXX.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors/index.ts"],"names":[],"mappings":";;;AAyDA,SAAS,YAAY,KAAA,EAAwB;AAC3C,EAAA,IAAI,iBAAiB,KAAA,EAAO;AAC1B,IAAA,OAAO,KAAA,CAAM,SAAS,KAAA,CAAM,OAAA;AAAA,EAC9B;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,IACE,OAAO,UAAU,QAAA,IACjB,OAAO,UAAU,SAAA,IACjB,OAAO,UAAU,QAAA,EACjB;AACA,IAAA,OAAO,OAAO,KAAK,CAAA;AAAA,EACrB;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,MAAM,WAAA,IAAe,QAAA;AAAA,EAC9B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A,EAAyB;AACrD,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,IAAK,KAAA,CAAM,QAAA,KAAa,QAAA;AACvD;AAKO,SAAS,kBAAkB,KAAA,EAAyB;AACzD,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,IAAK,KAAA,CAAM,QAAA,KAAa,YAAA;AACvD;AAKO,SAAS,mBAAmB,KAAA,EAAoC;AACrE,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,GAAI,KAAA,CAAM,UAAA,GAAa,MAAA;AACtD","file":"chunk-DIK74MXX.cjs","sourcesContent":["/**\n * TypeGraph Error Hierarchy\n *\n * All errors extend TypeGraphError with:\n * - `code`: Machine-readable error code for programmatic handling\n * - `category`: Classification for error handling strategies\n * - `suggestion`: Optional recovery guidance for users\n * - `details`: Structured context about the error\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ name: \"\" });\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.error(error.toUserMessage());\n * if (isUserRecoverable(error)) {\n * // Show to user for correction\n * }\n * }\n * }\n * ```\n */\n\nimport type { KindEntity } from \"../core/types\";\n// Type-only import: `materialize-indexes.ts` value-imports\n// `ConfigurationError` from this file, but type-only imports are erased\n// at runtime so this back-edge does not create a value cycle.\nimport type { MaterializeIndexesResult } from \"../store/materialize-indexes\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Error category for programmatic handling.\n *\n * - `user`: Caused by invalid input or incorrect usage. Recoverable by fixing input.\n * - `constraint`: Business rule or schema constraint violation. Recoverable by changing data.\n * - `system`: Internal error or infrastructure issue. May require investigation or retry.\n */\nexport type ErrorCategory = \"user\" | \"constraint\" | \"system\";\n\n/**\n * Options for TypeGraphError constructor.\n */\nexport type TypeGraphErrorOptions = Readonly<{\n /** Structured context about the error */\n details?: Record<string, unknown>;\n /** Error category for handling strategies */\n category: ErrorCategory;\n /** Recovery guidance for users */\n suggestion?: string;\n /** Underlying cause of the error */\n cause?: unknown;\n}>;\n\nfunction formatCause(cause: unknown): string {\n if (cause instanceof Error) {\n return cause.stack ?? cause.message;\n }\n if (typeof cause === \"string\") {\n return cause;\n }\n if (\n typeof cause === \"number\" ||\n typeof cause === \"boolean\" ||\n typeof cause === \"bigint\"\n ) {\n return String(cause);\n }\n if (typeof cause === \"symbol\") {\n return cause.description ?? \"Symbol\";\n }\n if (cause === undefined) {\n return \"Unknown cause\";\n }\n\n try {\n return JSON.stringify(cause);\n } catch (error) {\n return `Unserializable cause: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`;\n }\n}\n\n// ============================================================\n// Base Error\n// ============================================================\n\n/**\n * Base error class for all TypeGraph errors.\n *\n * Provides structured error information for both programmatic handling\n * and user-friendly messages.\n */\nexport class TypeGraphError extends Error {\n /** Machine-readable error code (e.g., \"VALIDATION_ERROR\") */\n readonly code: string;\n\n /** Error category for handling strategies */\n readonly category: ErrorCategory;\n\n /** Structured context about the error */\n readonly details: Readonly<Record<string, unknown>>;\n\n /** Recovery guidance for users */\n readonly suggestion?: string;\n\n constructor(message: string, code: string, options: TypeGraphErrorOptions) {\n super(message, options.cause ? { cause: options.cause } : undefined);\n this.name = \"TypeGraphError\";\n this.code = code;\n this.category = options.category;\n this.details = Object.freeze(options.details ?? {});\n if (options.suggestion !== undefined) {\n this.suggestion = options.suggestion;\n }\n }\n\n /**\n * Returns a user-friendly error message with suggestion if available.\n */\n toUserMessage(): string {\n if (this.suggestion) {\n return `${this.message}\\n\\nSuggestion: ${this.suggestion}`;\n }\n return this.message;\n }\n\n /**\n * Returns a detailed string representation for logging.\n */\n toLogString(): string {\n const lines = [\n `[${this.code}] ${this.message}`,\n ` Category: ${this.category}`,\n ];\n\n if (this.suggestion) {\n lines.push(` Suggestion: ${this.suggestion}`);\n }\n\n const detailKeys = Object.keys(this.details);\n if (detailKeys.length > 0) {\n lines.push(` Details: ${JSON.stringify(this.details)}`);\n }\n\n if (this.cause) {\n lines.push(` Cause: ${formatCause(this.cause)}`);\n }\n\n return lines.join(\"\\n\");\n }\n}\n\n// ============================================================\n// Validation Errors (category: \"user\")\n// ============================================================\n\n/**\n * Validation issue from Zod or custom validation.\n */\nexport type ValidationIssue = Readonly<{\n /** Path to the invalid field (e.g., \"address.city\") */\n path: string;\n /** Human-readable error message */\n message: string;\n /** Zod error code if from Zod validation */\n code?: string;\n}>;\n\n/**\n * Details for ValidationError.\n */\nexport type ValidationErrorDetails = Readonly<{\n /** Type of entity being validated */\n entityType?: KindEntity;\n /** Kind/type name of the entity */\n kind?: string;\n /** Operation being performed */\n operation?: \"create\" | \"update\";\n /** Entity ID if updating */\n id?: string;\n /** Individual validation issues */\n issues: readonly ValidationIssue[];\n}>;\n\n/**\n * Thrown when schema validation fails during node or edge operations.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ email: \"invalid\" });\n * } catch (error) {\n * if (error instanceof ValidationError) {\n * console.log(error.details.issues);\n * // [{ path: \"email\", message: \"Invalid email\" }]\n * }\n * }\n * ```\n */\nexport class ValidationError extends TypeGraphError {\n declare readonly details: ValidationErrorDetails;\n\n constructor(\n message: string,\n details: ValidationErrorDetails,\n options?: { cause?: unknown; suggestion?: string },\n ) {\n const fieldList =\n details.issues.length > 0 ?\n details.issues.map((index) => index.path || \"(root)\").join(\", \")\n : \"unknown\";\n\n super(message, \"VALIDATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ??\n `Check the following fields: ${fieldList}. See error.details.issues for specific validation failures.`,\n cause: options?.cause,\n });\n this.name = \"ValidationError\";\n }\n}\n\n// ============================================================\n// Not Found Errors (category: \"user\")\n// ============================================================\n\n/**\n * Details for NodeNotFoundError.\n */\nexport type NodeNotFoundErrorDetails = Readonly<{\n kind: string;\n id: string;\n}>;\n\n/**\n * Thrown when a node is not found.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.get(\"nonexistent-id\");\n * } catch (error) {\n * if (error instanceof NodeNotFoundError) {\n * console.log(error.details.kind, error.details.id);\n * }\n * }\n * ```\n */\nexport class NodeNotFoundError extends TypeGraphError {\n declare readonly details: NodeNotFoundErrorDetails;\n\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Node not found: ${kind}/${id}`, \"NODE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the node ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"NodeNotFoundError\";\n }\n}\n\n/**\n * Details for EdgeNotFoundError.\n */\nexport type EdgeNotFoundErrorDetails = Readonly<{\n kind: string;\n id: string;\n}>;\n\n/**\n * Thrown when an edge is not found.\n */\nexport class EdgeNotFoundError extends TypeGraphError {\n declare readonly details: EdgeNotFoundErrorDetails;\n\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Edge not found: ${kind}/${id}`, \"EDGE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the edge ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"EdgeNotFoundError\";\n }\n}\n\n/**\n * Details for KindNotFoundError.\n */\nexport type KindNotFoundErrorDetails = Readonly<{\n kindName: string;\n entity: KindEntity;\n graphId?: string;\n}>;\n\n/**\n * Thrown when an operation references a kind that isn't registered on\n * the graph — `getNodeCollectionOrThrow` against an unknown kind, a\n * `materializeIndexes({ kinds })` filter naming a missing kind, an\n * extension referencing an unresolved endpoint, search facade typos,\n * etc. Carries the offending `kindName` and `entity` plus the host\n * `graphId` so logs are unambiguous when multiple stores share a\n * process.\n */\nexport class KindNotFoundError extends TypeGraphError {\n declare readonly details: KindNotFoundErrorDetails;\n readonly kindName: string;\n readonly entity: KindEntity;\n\n constructor(\n kindName: string,\n entity: KindEntity,\n options?: Readonly<{\n graphId?: string;\n suggestion?: string;\n cause?: unknown;\n }>,\n ) {\n const where =\n options?.graphId === undefined ? \"\" : ` on graph \"${options.graphId}\"`;\n super(\n `${entity === \"node\" ? \"Node\" : \"Edge\"} kind \"${kindName}\" is not registered${where}.`,\n \"KIND_NOT_FOUND\",\n {\n details: {\n kindName,\n entity,\n ...(options?.graphId === undefined ?\n {}\n : { graphId: options.graphId }),\n },\n category: \"user\",\n suggestion:\n options?.suggestion ??\n \"Compile-time kinds come from defineGraph; extension kinds appear after store.evolve() returns. Check store.introspect() for the registered set.\",\n cause: options?.cause,\n },\n );\n this.name = \"KindNotFoundError\";\n this.kindName = kindName;\n this.entity = entity;\n }\n}\n\n/**\n * Details for NodeConstraintNotFoundError.\n */\nexport type NodeConstraintNotFoundErrorDetails = Readonly<{\n constraintName: string;\n kind: string;\n}>;\n\n/**\n * Thrown when a uniqueness constraint name is not found on a node kind.\n */\nexport class NodeConstraintNotFoundError extends TypeGraphError {\n declare readonly details: NodeConstraintNotFoundErrorDetails;\n\n constructor(\n constraintName: string,\n kind: string,\n options?: { cause?: unknown },\n ) {\n super(\n `Constraint not found: \"${constraintName}\" on node kind \"${kind}\"`,\n \"CONSTRAINT_NOT_FOUND\",\n {\n details: { constraintName, kind },\n category: \"user\",\n suggestion: `Verify the constraint name \"${constraintName}\" is defined in the unique constraints for \"${kind}\".`,\n cause: options?.cause,\n },\n );\n this.name = \"NodeConstraintNotFoundError\";\n }\n}\n\n/**\n * Details for NodeIndexNotFoundError.\n */\nexport type NodeIndexNotFoundErrorDetails = Readonly<{\n indexName: string;\n kind: string;\n}>;\n\n/**\n * Thrown when a declared node index name is not found on a node kind.\n */\nexport class NodeIndexNotFoundError extends TypeGraphError {\n declare readonly details: NodeIndexNotFoundErrorDetails;\n\n constructor(indexName: string, kind: string, options?: { cause?: unknown }) {\n super(\n `Index not found: \"${indexName}\" on node kind \"${kind}\"`,\n \"INDEX_NOT_FOUND\",\n {\n details: { indexName, kind },\n category: \"user\",\n suggestion: `Verify the index name \"${indexName}\" is declared via defineNodeIndex for \"${kind}\" and passed to defineGraph({ indexes }).`,\n cause: options?.cause,\n },\n );\n this.name = \"NodeIndexNotFoundError\";\n }\n}\n\n// ============================================================\n// Constraint Errors (category: \"constraint\")\n// ============================================================\n\n/**\n * Details for EndpointNotFoundError.\n */\nexport type EndpointNotFoundErrorDetails = Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * Thrown when edge endpoint node does not exist or is deleted.\n */\nexport class EndpointNotFoundError extends TypeGraphError {\n declare readonly details: EndpointNotFoundErrorDetails;\n\n constructor(\n details: EndpointNotFoundErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Endpoint node not found for edge \"${details.edgeKind}\": ${details.nodeKind}/${details.nodeId} (${details.endpoint})`,\n \"ENDPOINT_NOT_FOUND\",\n {\n details,\n category: \"constraint\",\n suggestion: `Ensure the ${details.endpoint} node exists before creating the edge.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointNotFoundError\";\n }\n}\n\n/**\n * Details for EndpointError.\n */\nexport type EndpointErrorDetails = Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n actualKind: string;\n expectedKinds: readonly string[];\n}>;\n\n/**\n * Thrown when edge endpoint has wrong node type.\n */\nexport class EndpointError extends TypeGraphError {\n declare readonly details: EndpointErrorDetails;\n\n constructor(details: EndpointErrorDetails, options?: { cause?: unknown }) {\n const expected = details.expectedKinds.join(\" | \");\n super(\n `Invalid ${details.endpoint} endpoint for edge \"${details.edgeKind}\": got \"${details.actualKind}\", expected ${expected}`,\n \"ENDPOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a node of type ${expected} as the ${details.endpoint} endpoint.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointError\";\n }\n}\n\n/**\n * Details for UniquenessError.\n */\nexport type UniquenessErrorDetails = Readonly<{\n constraintName: string;\n kind: string;\n existingId: string;\n newId: string;\n fields: readonly string[];\n}>;\n\n/**\n * Thrown when uniqueness constraint is violated.\n */\nexport class UniquenessError extends TypeGraphError {\n declare readonly details: UniquenessErrorDetails;\n\n constructor(details: UniquenessErrorDetails, options?: { cause?: unknown }) {\n const fieldList = details.fields.join(\", \");\n super(\n `Uniqueness violation on \"${details.kind}\": constraint \"${details.constraintName}\" (fields: ${fieldList}) conflicts with existing node ${details.existingId}`,\n \"UNIQUENESS_VIOLATION\",\n {\n details,\n category: \"constraint\",\n suggestion: `Change the values for fields [${fieldList}] to be unique, or update the existing node ${details.existingId} instead.`,\n cause: options?.cause,\n },\n );\n this.name = \"UniquenessError\";\n }\n}\n\n/**\n * Details for CardinalityError.\n */\nexport type CardinalityErrorDetails = Readonly<{\n edgeKind: string;\n fromKind: string;\n fromId: string;\n cardinality: string;\n existingCount: number;\n}>;\n\n/**\n * Thrown when cardinality constraint is violated.\n */\nexport class CardinalityError extends TypeGraphError {\n declare readonly details: CardinalityErrorDetails;\n\n constructor(details: CardinalityErrorDetails, options?: { cause?: unknown }) {\n super(\n `Cardinality violation: \"${details.edgeKind}\" from ${details.fromKind}/${details.fromId} allows \"${details.cardinality}\" but ${details.existingCount} edge(s) already exist`,\n \"CARDINALITY_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion:\n details.cardinality === \"one\" || details.cardinality === \"unique\" ?\n `Delete the existing edge before creating a new one, or use cardinality \"many\".`\n : `Check if the cardinality constraint \"${details.cardinality}\" is correct for your use case.`,\n cause: options?.cause,\n },\n );\n this.name = \"CardinalityError\";\n }\n}\n\n/**\n * Details for DisjointError.\n */\nexport type DisjointErrorDetails = Readonly<{\n nodeId: string;\n attemptedKind: string;\n conflictingKind: string;\n}>;\n\n/**\n * Thrown when disjointness constraint is violated.\n *\n * Disjoint types cannot share the same ID - a node cannot be both\n * a Person and an Organization if they are declared disjoint.\n */\nexport class DisjointError extends TypeGraphError {\n declare readonly details: DisjointErrorDetails;\n\n constructor(details: DisjointErrorDetails, options?: { cause?: unknown }) {\n super(\n `Disjoint constraint violation: cannot create ${details.attemptedKind} with ID \"${details.nodeId}\" - conflicts with existing ${details.conflictingKind}`,\n \"DISJOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a different ID for the new ${details.attemptedKind} node, or delete the existing ${details.conflictingKind}/${details.nodeId} first.`,\n cause: options?.cause,\n },\n );\n this.name = \"DisjointError\";\n }\n}\n\n/**\n * Details for RestrictedDeleteError.\n */\nexport type RestrictedDeleteErrorDetails = Readonly<{\n nodeKind: string;\n nodeId: string;\n edgeCount: number;\n edgeKinds: readonly string[];\n}>;\n\n/**\n * Thrown when deletion is blocked due to existing edges (restrict behavior).\n */\nexport class RestrictedDeleteError extends TypeGraphError {\n declare readonly details: RestrictedDeleteErrorDetails;\n\n constructor(\n details: RestrictedDeleteErrorDetails,\n options?: { cause?: unknown },\n ) {\n const edgeList = details.edgeKinds.join(\", \");\n super(\n `Cannot delete ${details.nodeKind}/${details.nodeId}: ${details.edgeCount} connected edge(s) exist (${edgeList})`,\n \"RESTRICTED_DELETE\",\n {\n details,\n category: \"constraint\",\n suggestion: `Delete the connected edges first, or change onDelete behavior to \"cascade\" (auto-delete edges) or \"disconnect\" (soft-delete edges).`,\n cause: options?.cause,\n },\n );\n this.name = \"RestrictedDeleteError\";\n }\n}\n\n// ============================================================\n// Concurrency Errors (category: \"system\")\n// ============================================================\n\n/**\n * Details for VersionConflictError.\n */\nexport type VersionConflictErrorDetails = Readonly<{\n kind: string;\n id: string;\n expectedVersion: number;\n actualVersion: number;\n}>;\n\n/**\n * Thrown when optimistic locking detects a concurrent modification.\n *\n * This occurs when two operations try to update the same entity simultaneously.\n * The operation with the stale version fails.\n */\nexport class VersionConflictError extends TypeGraphError {\n declare readonly details: VersionConflictErrorDetails;\n\n constructor(\n details: VersionConflictErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Version conflict on ${details.kind}/${details.id}: expected version ${details.expectedVersion}, found ${details.actualVersion}`,\n \"VERSION_CONFLICT\",\n {\n details,\n category: \"system\",\n suggestion: `Fetch the latest version of the entity and retry the operation. This error indicates concurrent modification.`,\n cause: options?.cause,\n },\n );\n this.name = \"VersionConflictError\";\n }\n}\n\n// ============================================================\n// Schema Errors (category: \"system\")\n// ============================================================\n\n/**\n * Details for SchemaMismatchError.\n */\nexport type SchemaMismatchErrorDetails = Readonly<{\n graphId: string;\n expectedHash: string;\n actualHash: string;\n}>;\n\n/**\n * Thrown when the schema in code doesn't match the schema in the database.\n */\nexport class SchemaMismatchError extends TypeGraphError {\n declare readonly details: SchemaMismatchErrorDetails;\n\n constructor(\n details: SchemaMismatchErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema mismatch for graph \"${details.graphId}\": code schema differs from database schema`,\n \"SCHEMA_MISMATCH\",\n {\n details,\n category: \"system\",\n suggestion: `Run schema migration to update the database, or use createStoreWithSchema() for automatic migration.`,\n cause: options?.cause,\n },\n );\n this.name = \"SchemaMismatchError\";\n }\n}\n\n/**\n * Details for MigrationError.\n */\nexport type MigrationErrorDetails = Readonly<{\n graphId: string;\n fromVersion: number;\n toVersion: number;\n reason?: string;\n}>;\n\n/**\n * Thrown when schema migration fails.\n */\nexport class MigrationError extends TypeGraphError {\n declare readonly details: MigrationErrorDetails;\n\n constructor(\n message: string,\n details: MigrationErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(message, \"MIGRATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `Review the schema changes and ensure they are backwards compatible, or implement a data migration.`,\n cause: options?.cause,\n });\n this.name = \"MigrationError\";\n }\n}\n\n/**\n * Details for EagerMaterializationError.\n */\nexport type EagerMaterializationErrorDetails = Readonly<{\n graphId: string;\n failedIndexNames: readonly string[];\n}>;\n\n/**\n * Thrown by `Store.evolve(extension, { eager })` when the schema\n * commit succeeded but the follow-on `materializeIndexes()` produced\n * one or more failed entries.\n *\n * Recovery: the schema commit is NOT rolled back. The new `Store` is\n * fully constructed and (when `options.ref` was supplied) `ref.current`\n * already points to it — the caller can read the new store via the ref\n * and decide how to handle the failed indexes (retry, skip, alert).\n * The full `MaterializeIndexesResult` is attached as `.materialization`.\n *\n * @example\n * ```ts\n * const ref = { current: store };\n * try {\n * await store.evolve(extension, { ref, eager: {} });\n * } catch (error) {\n * if (error instanceof EagerMaterializationError) {\n * // schema is committed; ref.current is the new store\n * log.warn(\n * { failed: error.failedIndexNames },\n * \"indexes did not materialize; will retry\",\n * );\n * await ref.current.materializeIndexes();\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport class EagerMaterializationError extends TypeGraphError {\n declare readonly details: EagerMaterializationErrorDetails;\n\n /**\n * The full materialization result, including successful and failed\n * entries. Same shape as `Store.materializeIndexes()` returns.\n */\n readonly materialization: MaterializeIndexesResult;\n\n constructor(materialization: MaterializeIndexesResult, graphId: string) {\n const names = collectFailedIndexNames(materialization);\n super(\n `Eager materialization failed for ${names.length} index(es) on graph \"${graphId}\": ${names.join(\", \")}. The schema commit succeeded; the new Store is available via the ref handle (when supplied) and the failed indexes can be retried via store.materializeIndexes().`,\n \"EAGER_MATERIALIZATION_FAILED\",\n {\n details: { graphId, failedIndexNames: names },\n category: \"system\",\n suggestion: `Inspect error.materialization for per-index errors. Each failure preserves any prior successful materialization timestamp; the schema is committed regardless.`,\n },\n );\n this.name = \"EagerMaterializationError\";\n this.materialization = materialization;\n }\n\n /**\n * Names of just the indexes that failed — derived from\n * `materialization.results` so the two views can never disagree.\n */\n get failedIndexNames(): readonly string[] {\n return collectFailedIndexNames(this.materialization);\n }\n}\n\nfunction collectFailedIndexNames(\n materialization: MaterializeIndexesResult,\n): readonly string[] {\n const names: string[] = [];\n for (const entry of materialization.results) {\n if (entry.status === \"failed\") names.push(entry.indexName);\n }\n return names;\n}\n\n/**\n * Details for StaleVersionError. `actual` is `0` when no active version\n * exists yet (initial-commit race where another writer initialized first).\n */\nexport type StaleVersionErrorDetails = Readonly<{\n graphId: string;\n expected: number;\n actual: number;\n}>;\n\n/**\n * Thrown by `commitSchemaVersion` and `setActiveVersion` when the\n * caller's view of the active schema version is out of date — another\n * writer has already advanced it.\n *\n * Recovery: re-read the active version with `getActiveSchema(graphId)`,\n * recompute against the new baseline, and retry. This is a routine\n * concurrency signal, not a bug.\n */\nexport class StaleVersionError extends TypeGraphError {\n declare readonly details: StaleVersionErrorDetails;\n\n constructor(\n details: StaleVersionErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema version was advanced by another writer for graph \"${details.graphId}\": expected active version ${details.expected}, actual is ${details.actual}`,\n \"STALE_SCHEMA_VERSION\",\n {\n details,\n category: \"system\",\n suggestion: `Re-read the active schema version, recompute the new version against that baseline, and retry the commit.`,\n cause: options?.cause,\n },\n );\n this.name = \"StaleVersionError\";\n }\n}\n\n/**\n * Details for SchemaContentConflictError.\n */\nexport type SchemaContentConflictErrorDetails = Readonly<{\n graphId: string;\n version: number;\n existingHash: string;\n incomingHash: string;\n}>;\n\n/**\n * Thrown by `commitSchemaVersion` when a row already exists at the\n * target version with a *different* schema hash — i.e. two writers\n * committed materially different schemas at the same version number.\n *\n * Distinct from `StaleVersionError`: this is not a refetch-and-retry\n * situation, it's a content disagreement that needs operator\n * intervention. Typically caused by inconsistent application\n * deployments writing schemas that hash differently.\n */\nexport class SchemaContentConflictError extends TypeGraphError {\n declare readonly details: SchemaContentConflictErrorDetails;\n\n constructor(\n details: SchemaContentConflictErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema content conflict for graph \"${details.graphId}\" at version ${details.version}: existing hash ${details.existingHash} differs from incoming hash ${details.incomingHash}`,\n \"SCHEMA_CONTENT_CONFLICT\",\n {\n details,\n category: \"system\",\n suggestion: `Two writers committed different schemas at the same version. Reconcile the application deployments so they produce the same canonical schema, then retry.`,\n cause: options?.cause,\n },\n );\n this.name = \"SchemaContentConflictError\";\n }\n}\n\n// ============================================================\n// Configuration Errors (category: \"user\")\n// ============================================================\n\n/**\n * Thrown when graph configuration is invalid.\n *\n * This includes invalid schema definitions, ontology conflicts,\n * and other configuration issues detected at graph creation time.\n */\nexport class ConfigurationError extends TypeGraphError {\n constructor(\n message: string,\n details: Record<string, unknown> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"CONFIGURATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ?? `Review your graph definition for errors.`,\n cause: options?.cause,\n });\n this.name = \"ConfigurationError\";\n }\n}\n\n/**\n * The stable `details.code` values raised by the recorded-capture guards on a\n * history- or revision-tracked store. These are the sanctioned branch points\n * for a portable caller that must pick a transaction strategy without\n * substring-matching {@link ConfigurationError} messages.\n *\n * - `RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION`: `store.withTransaction`\n * was called on a history-enabled store, which has no flush point before the\n * caller commits — use `store.withRecordedTransaction` instead.\n * - `RECORDED_CAPTURE_RAW_SQL_DISABLED`: a raw SQL escape (`tx.sql`,\n * `backend.executeStatement`/`executeDdl`) was reached on a history-enabled\n * store, where it would bypass recorded-time capture.\n * - `REVISION_TRACKING_RAW_SQL_DISABLED`: the same raw SQL escape on a\n * revision-tracked store, where it would bypass the revision anchor.\n *\n * @see isRecordedCaptureGuardError\n */\nexport const RECORDED_CAPTURE_GUARD_CODES = [\n \"RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION\",\n \"RECORDED_CAPTURE_RAW_SQL_DISABLED\",\n \"REVISION_TRACKING_RAW_SQL_DISABLED\",\n] as const;\n\n/** A stable, branchable code raised by a recorded-capture guard. */\nexport type RecordedCaptureGuardCode =\n (typeof RECORDED_CAPTURE_GUARD_CODES)[number];\n\n/**\n * A {@link ConfigurationError} narrowed to carry a {@link RecordedCaptureGuardCode}\n * in `details.code` — the shape {@link isRecordedCaptureGuardError} guarantees.\n * `C` narrows `details.code` to a single code when the guard was called with a\n * specific one; it defaults to the full union.\n */\nexport type RecordedCaptureGuardError<\n C extends RecordedCaptureGuardCode = RecordedCaptureGuardCode,\n> = ConfigurationError & Readonly<{ details: Readonly<{ code: C }> }>;\n\nfunction isRecordedCaptureGuardCode(\n value: unknown,\n): value is RecordedCaptureGuardCode {\n // Widen the readonly tuple so `includes` accepts an `unknown` needle.\n return (RECORDED_CAPTURE_GUARD_CODES as readonly unknown[]).includes(value);\n}\n\n/**\n * Type guard for the recorded-capture guard errors, so a portable caller can\n * branch on the invariant a store enforced instead of substring-matching the\n * message. Pass `code` to narrow to a single guard; omit it to match any.\n *\n * Distinguishes \"history capture forbids raw SQL here\" from \"this backend has\n * no transactions\" (the latter carries no guard code — see\n * `TransactionContext.sqlAvailability` for the capability discriminant).\n *\n * Passing `code` also narrows `details.code` to that literal on the guarded\n * branch, so a caller can read the payload without re-checking.\n *\n * @example\n * ```typescript\n * // `withTransaction` is a compile error on a history-enabled store, so widen\n * // to the base Store surface to reach the runtime guard this branches on.\n * const store: Store<typeof graph> = historyStore;\n * try {\n * store.withTransaction(externalTx);\n * } catch (error) {\n * if (\n * isRecordedCaptureGuardError(\n * error,\n * \"RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION\",\n * )\n * ) {\n * // error.details.code is now the literal, not the union.\n * await historyStore.withRecordedTransaction(externalTx, run);\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport function isRecordedCaptureGuardError<C extends RecordedCaptureGuardCode>(\n error: unknown,\n code: C,\n): error is RecordedCaptureGuardError<C>;\nexport function isRecordedCaptureGuardError(\n error: unknown,\n): error is RecordedCaptureGuardError;\nexport function isRecordedCaptureGuardError(\n error: unknown,\n code?: RecordedCaptureGuardCode,\n): error is RecordedCaptureGuardError {\n if (!(error instanceof ConfigurationError)) return false;\n const actual = error.details.code;\n if (!isRecordedCaptureGuardCode(actual)) return false;\n return code === undefined || actual === code;\n}\n\n/**\n * Why a store's strategy-owned storage is not usable on the current\n * connection. Drives the {@link StoreNotInitializedError} message and\n * is surfaced in `details.reason` for programmatic handling.\n *\n * - `missing`: no durable materialization marker exists — the database\n * was never initialized for this graph's runtime contributions.\n * - `stale`: a marker exists but its recorded signature no longer\n * matches the resolved contribution DDL (strategy swap or DDL drift).\n * The hot path refuses rather than silently re-materializing.\n * - `failed`: the most recent boot-time materialization attempt\n * recorded an error. Boot may retry; the hot path refuses.\n */\nexport type StoreNotInitializedReason = \"missing\" | \"stale\" | \"failed\";\n\nconst STORE_NOT_INITIALIZED_REASON_PHRASE: Readonly<\n Record<StoreNotInitializedReason, string>\n> = {\n missing: \"is not initialized\",\n stale: \"is stale (recorded materialization signature no longer matches)\",\n failed: \"failed its last initialization attempt\",\n};\n\n/**\n * Details for StoreNotInitializedError. `graphId`/`reason` are always\n * present; callers may merge additional context (e.g. `logicalName`) via\n * `options.details`.\n */\nexport type StoreNotInitializedErrorDetails = Readonly<{\n graphId: string;\n reason: StoreNotInitializedReason;\n}> &\n Readonly<Record<string, unknown>>;\n\n/**\n * Thrown when a fulltext-dependent operation runs against a connection\n * whose strategy-owned storage has not been durably materialized.\n *\n * `createStore()` is a synchronous, zero-I/O attach: it never creates\n * tables, repairs DDL, or writes materialization markers. The durable\n * marker is written exclusively by the async boot path\n * (`createStoreWithSchema`). When a fulltext read/write — or an\n * adopted/business transaction — observes no valid marker, it refuses\n * loudly here instead of lazily emitting DDL on the hot path.\n */\nexport class StoreNotInitializedError extends TypeGraphError {\n declare readonly details: StoreNotInitializedErrorDetails;\n\n // `graphId`/`reason` are positional and required: both are\n // load-bearing for the message and for programmatic handling via\n // `details.reason`. Caller `details` merge underneath — spread first\n // so `graphId`/`reason` win and can't be clobbered by an\n // accidentally-colliding extra key.\n constructor(\n graphId: string,\n reason: StoreNotInitializedReason,\n options?: {\n cause?: unknown;\n details?: Readonly<Record<string, unknown>> &\n Readonly<{ graphId?: never; reason?: never }>;\n },\n ) {\n super(\n `fulltext storage for graph \"${graphId}\" ${STORE_NOT_INITIALIZED_REASON_PHRASE[reason]}. ` +\n `Run createStoreWithSchema(graph, backend) during application boot, ` +\n `outside request handlers and adopted transactions, before using createStore().`,\n \"STORE_NOT_INITIALIZED\",\n {\n details: { ...options?.details, graphId, reason },\n category: \"user\",\n suggestion:\n \"Call createStoreWithSchema(graph, backend) once at application \" +\n \"startup. createStore() attaches to an already-initialized \" +\n \"database and does not materialize storage itself.\",\n cause: options?.cause,\n },\n );\n this.name = \"StoreNotInitializedError\";\n }\n}\n\n// ============================================================\n// Database Errors (category: \"system\")\n// ============================================================\n\n/**\n * Details for DatabaseOperationError.\n */\nexport type DatabaseOperationErrorDetails = Readonly<{\n operation: string;\n entity: string;\n}>;\n\n/**\n * Thrown when a database operation fails unexpectedly.\n *\n * This indicates a system-level failure in the database backend,\n * not a user-recoverable error.\n */\nexport class DatabaseOperationError extends TypeGraphError {\n declare readonly details: DatabaseOperationErrorDetails;\n\n constructor(\n message: string,\n details: DatabaseOperationErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(message, \"DATABASE_OPERATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `This is a system-level database error. Check the database connection and retry the operation. If the problem persists, investigate the underlying cause.`,\n cause: options?.cause,\n });\n this.name = \"DatabaseOperationError\";\n }\n}\n\n// ============================================================\n// Vector / Embedding Errors (category: \"user\")\n// ============================================================\n\n/**\n * Details for EmbeddingDimensionChangedError.\n */\nexport type EmbeddingDimensionChangedErrorDetails = Readonly<{\n kind: string;\n fieldPath: string;\n declaredDimensions?: number;\n storedDimensions?: number;\n}>;\n\n/**\n * Thrown when an embedding field's declared dimension no longer matches the\n * dimension of its materialized per-field storage — i.e. a field's\n * `embedding(N)` was changed to `embedding(M)`. The stored vectors are invalid\n * under the new dimension and cannot be converted, only recomputed, so this is\n * a deliberate app-driven migration: call\n * `store.reembedVectorField(kind, fieldPath, ...)` to recreate the storage at\n * the new dimension and re-embed existing rows.\n */\nexport class EmbeddingDimensionChangedError extends TypeGraphError {\n declare readonly details: EmbeddingDimensionChangedErrorDetails;\n\n constructor(\n message: string,\n details: EmbeddingDimensionChangedErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(message, \"EMBEDDING_DIMENSION_CHANGED\", {\n details,\n category: \"user\",\n suggestion: `Run store.reembedVectorField(\"${details.kind}\", \"${details.fieldPath}\", { embed }) to recreate the field's storage at the new dimension and re-embed existing rows.`,\n cause: options?.cause,\n });\n this.name = \"EmbeddingDimensionChangedError\";\n }\n}\n\n// ============================================================\n// Query Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a query predicate cannot be compiled for the target database.\n */\nexport class UnsupportedPredicateError extends TypeGraphError {\n constructor(\n message: string,\n details: Readonly<Record<string, unknown>> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"UNSUPPORTED_PREDICATE\", {\n details,\n category: \"system\",\n suggestion:\n options?.suggestion ??\n `This predicate may not be supported by your database backend. Check the documentation for supported predicates.`,\n cause: options?.cause,\n });\n this.name = \"UnsupportedPredicateError\";\n }\n}\n\n// ============================================================\n// Compiler Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a compiler invariant is violated.\n *\n * This indicates a bug in the query compiler — the compiler reached\n * a state that should be unreachable. These errors are not user-recoverable.\n */\nexport class CompilerInvariantError extends TypeGraphError {\n constructor(\n message: string,\n details?: Readonly<Record<string, unknown>>,\n options?: { cause?: unknown },\n ) {\n super(message, \"COMPILER_INVARIANT_ERROR\", {\n details: details ?? {},\n category: \"system\",\n suggestion: `This is an internal compiler error. Please report it as a bug with the query that triggered it.`,\n cause: options?.cause,\n });\n this.name = \"CompilerInvariantError\";\n }\n}\n\n// ============================================================\n// Lifecycle Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when an operation is attempted on a backend that has been disposed.\n *\n * This typically occurs during runtime teardown — for example, when a\n * Cloudflare Workers test runner resets Durable Object storage while\n * the TypeGraph backend still has queued operations.\n */\nexport class BackendDisposedError extends TypeGraphError {\n constructor(options?: { cause?: unknown }) {\n super(\n \"Backend has been disposed — the underlying database connection is no longer available\",\n \"BACKEND_DISPOSED\",\n {\n category: \"system\",\n suggestion:\n \"Ensure all store operations complete before calling backend.close(). \" +\n \"In test environments, await store teardown before resetting the database.\",\n cause: options?.cause,\n },\n );\n this.name = \"BackendDisposedError\";\n }\n}\n\n/**\n * Thrown when a statement is issued on a transaction-scoped backend after\n * its transaction boundary has already returned.\n *\n * The usual source is a callback that lets work escape it. `Promise.all`\n * rejects on its first rejection while its siblings keep running, so\n *\n * ```typescript\n * await store.transaction(async (tx) => {\n * await Promise.all([tx.nodes.Doc.create(a), tx.nodes.Doc.create(b)]);\n * });\n * ```\n *\n * leaves `b`'s remaining statements in flight when `a` fails. Those\n * statements have nowhere safe to go: the driver is about to emit `ROLLBACK`\n * on the same pinned connection and then hand it back to the pool, where a\n * late arrival would execute inside somebody else's transaction. TypeGraph\n * refuses them here instead.\n *\n * The error is normally invisible — `Promise.all` has already rejected with\n * the original failure, and discards this one.\n */\nexport class TransactionClosedError extends TypeGraphError {\n constructor(options?: { cause?: unknown }) {\n super(\n \"Statement issued on a transaction-scoped backend after its transaction \" +\n \"boundary returned. The connection has been released; the statement was not run.\",\n \"TRANSACTION_CLOSED\",\n {\n category: \"user\",\n suggestion:\n \"Await every write started inside store.transaction(...) before the \" +\n \"callback returns. Prefer awaiting a Promise.allSettled(...) over a \" +\n \"Promise.all(...) whose rejection would orphan its siblings.\",\n cause: options?.cause,\n },\n );\n this.name = \"TransactionClosedError\";\n }\n}\n\n// ============================================================\n// Utility Functions\n// ============================================================\n\n/**\n * Type guard for TypeGraphError.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({});\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.log(error.code, error.category);\n * }\n * }\n * ```\n */\nexport function isTypeGraphError(error: unknown): error is TypeGraphError {\n return error instanceof TypeGraphError;\n}\n\n/**\n * Check if error is recoverable by user action (user or constraint error).\n *\n * User-recoverable errors can typically be resolved by:\n * - Fixing invalid input data\n * - Using different IDs or values\n * - Deleting conflicting data first\n *\n * @example\n * ```typescript\n * if (isUserRecoverable(error)) {\n * showErrorToUser(error.toUserMessage());\n * } else {\n * logAndAlertOps(error);\n * }\n * ```\n */\nexport function isUserRecoverable(error: unknown): boolean {\n if (!isTypeGraphError(error)) return false;\n return error.category === \"user\" || error.category === \"constraint\";\n}\n\n/**\n * Check if error indicates a system/infrastructure issue.\n *\n * System errors typically require:\n * - Retry logic (for transient failures)\n * - Investigation (for persistent failures)\n * - Ops team notification\n */\nexport function isSystemError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"system\";\n}\n\n/**\n * Check if error is a constraint violation.\n */\nexport function isConstraintError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"constraint\";\n}\n\n/**\n * Extract suggestion from error if available.\n */\nexport function getErrorSuggestion(error: unknown): string | undefined {\n return isTypeGraphError(error) ? error.suggestion : undefined;\n}\n"]}