@nicia-ai/typegraph 0.44.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (265) hide show
  1. package/dist/backend/drizzle/indexes.cjs +7 -7
  2. package/dist/backend/drizzle/indexes.d.cts +1 -1
  3. package/dist/backend/drizzle/indexes.d.ts +1 -1
  4. package/dist/backend/drizzle/indexes.js +3 -3
  5. package/dist/backend/index.cjs +37 -37
  6. package/dist/backend/index.d.cts +3 -3
  7. package/dist/backend/index.d.ts +3 -3
  8. package/dist/backend/index.js +6 -6
  9. package/dist/backend/postgres/index.cjs +23 -23
  10. package/dist/backend/postgres/index.d.cts +6 -6
  11. package/dist/backend/postgres/index.d.ts +6 -6
  12. package/dist/backend/postgres/index.js +10 -10
  13. package/dist/backend/postgres/pglite-store.cjs +24 -25
  14. package/dist/backend/postgres/pglite-store.cjs.map +1 -1
  15. package/dist/backend/postgres/pglite-store.d.cts +7 -7
  16. package/dist/backend/postgres/pglite-store.d.ts +7 -7
  17. package/dist/backend/postgres/pglite-store.js +20 -21
  18. package/dist/backend/postgres/pglite-store.js.map +1 -1
  19. package/dist/backend/postgres/pglite.cjs +12 -12
  20. package/dist/backend/postgres/pglite.d.cts +3 -3
  21. package/dist/backend/postgres/pglite.d.ts +3 -3
  22. package/dist/backend/postgres/pglite.js +11 -11
  23. package/dist/backend/sqlite/index.cjs +21 -21
  24. package/dist/backend/sqlite/index.d.cts +6 -6
  25. package/dist/backend/sqlite/index.d.ts +6 -6
  26. package/dist/backend/sqlite/index.js +9 -9
  27. package/dist/backend/sqlite/libsql.cjs +14 -14
  28. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  29. package/dist/backend/sqlite/libsql.d.cts +3 -3
  30. package/dist/backend/sqlite/libsql.d.ts +3 -3
  31. package/dist/backend/sqlite/libsql.js +10 -10
  32. package/dist/backend/sqlite/libsql.js.map +1 -1
  33. package/dist/backend/sqlite/local-store.cjs +25 -26
  34. package/dist/backend/sqlite/local-store.cjs.map +1 -1
  35. package/dist/backend/sqlite/local-store.d.cts +8 -8
  36. package/dist/backend/sqlite/local-store.d.ts +8 -8
  37. package/dist/backend/sqlite/local-store.js +21 -22
  38. package/dist/backend/sqlite/local-store.js.map +1 -1
  39. package/dist/backend/sqlite/local.cjs +13 -13
  40. package/dist/backend/sqlite/local.d.cts +3 -3
  41. package/dist/backend/sqlite/local.d.ts +3 -3
  42. package/dist/backend/sqlite/local.js +11 -11
  43. package/dist/{chunk-TVLKA4AY.js → chunk-42PYUGLS.js} +57 -3
  44. package/dist/chunk-42PYUGLS.js.map +1 -0
  45. package/dist/{chunk-IJTLXNGJ.js → chunk-4GUBTVPV.js} +3 -4
  46. package/dist/chunk-4GUBTVPV.js.map +1 -0
  47. package/dist/{chunk-63KCKSSH.js → chunk-4GUTQPVO.js} +33 -9
  48. package/dist/chunk-4GUTQPVO.js.map +1 -0
  49. package/dist/{chunk-FGO5JFVJ.cjs → chunk-4MEWSUVM.cjs} +10 -10
  50. package/dist/chunk-4MEWSUVM.cjs.map +1 -0
  51. package/dist/{chunk-FMGEZBAQ.js → chunk-4QIKLIGG.js} +15 -3
  52. package/dist/chunk-4QIKLIGG.js.map +1 -0
  53. package/dist/{chunk-FMMIX6N4.js → chunk-55ITBQJI.js} +2 -2
  54. package/dist/chunk-55ITBQJI.js.map +1 -0
  55. package/dist/{chunk-TCRIQMBU.js → chunk-5EKPX6QU.js} +4 -4
  56. package/dist/{chunk-TCRIQMBU.js.map → chunk-5EKPX6QU.js.map} +1 -1
  57. package/dist/{chunk-GFRGG2US.cjs → chunk-5GAONX5G.cjs} +7 -7
  58. package/dist/{chunk-GFRGG2US.cjs.map → chunk-5GAONX5G.cjs.map} +1 -1
  59. package/dist/{chunk-ALFUGRYB.cjs → chunk-6RYPD3NJ.cjs} +29 -29
  60. package/dist/{chunk-ALFUGRYB.cjs.map → chunk-6RYPD3NJ.cjs.map} +1 -1
  61. package/dist/{chunk-QGKILWGZ.cjs → chunk-7PF2L3H6.cjs} +4 -4
  62. package/dist/{chunk-QGKILWGZ.cjs.map → chunk-7PF2L3H6.cjs.map} +1 -1
  63. package/dist/chunk-B3F2D3SP.cjs +12 -0
  64. package/dist/{chunk-EPTSMFH7.cjs.map → chunk-B3F2D3SP.cjs.map} +1 -1
  65. package/dist/{chunk-7G32LIQM.js → chunk-BGYJW37L.js} +5 -5
  66. package/dist/{chunk-7G32LIQM.js.map → chunk-BGYJW37L.js.map} +1 -1
  67. package/dist/{chunk-EE7N5XXQ.cjs → chunk-BNS75YNF.cjs} +9 -10
  68. package/dist/chunk-BNS75YNF.cjs.map +1 -0
  69. package/dist/{chunk-VITTKBWF.js → chunk-CBKG6HEP.js} +5 -5
  70. package/dist/{chunk-VITTKBWF.js.map → chunk-CBKG6HEP.js.map} +1 -1
  71. package/dist/{chunk-A4PBRX4C.cjs → chunk-D54WH24V.cjs} +57 -2
  72. package/dist/chunk-D54WH24V.cjs.map +1 -0
  73. package/dist/{chunk-MCHP7RHZ.cjs → chunk-D56XG4EI.cjs} +26 -14
  74. package/dist/chunk-D56XG4EI.cjs.map +1 -0
  75. package/dist/{chunk-SQRD2CYF.js → chunk-DXEEHSGN.js} +293 -45
  76. package/dist/chunk-DXEEHSGN.js.map +1 -0
  77. package/dist/{chunk-GWEDD3DH.js → chunk-EFEOOCJ3.js} +4 -4
  78. package/dist/{chunk-GWEDD3DH.js.map → chunk-EFEOOCJ3.js.map} +1 -1
  79. package/dist/{chunk-3PRKZW6D.cjs → chunk-EKFUG4G7.cjs} +2 -2
  80. package/dist/chunk-EKFUG4G7.cjs.map +1 -0
  81. package/dist/{chunk-HJH3RMXG.cjs → chunk-F4NHQHEZ.cjs} +4 -4
  82. package/dist/{chunk-HJH3RMXG.cjs.map → chunk-F4NHQHEZ.cjs.map} +1 -1
  83. package/dist/{chunk-46GDII45.js → chunk-FL5UQRES.js} +3 -3
  84. package/dist/{chunk-46GDII45.js.map → chunk-FL5UQRES.js.map} +1 -1
  85. package/dist/{chunk-TFMVL4QH.js → chunk-FLEQ2HBK.js} +3 -3
  86. package/dist/{chunk-TFMVL4QH.js.map → chunk-FLEQ2HBK.js.map} +1 -1
  87. package/dist/{chunk-BEFM74L2.js → chunk-FQ7ZPOTZ.js} +6 -6
  88. package/dist/{chunk-BEFM74L2.js.map → chunk-FQ7ZPOTZ.js.map} +1 -1
  89. package/dist/{chunk-ST3LPB2V.cjs → chunk-H7VE3FL4.cjs} +318 -70
  90. package/dist/chunk-H7VE3FL4.cjs.map +1 -0
  91. package/dist/{chunk-BCP7LLOY.js → chunk-ID4WXTKL.js} +367 -41
  92. package/dist/{chunk-BCP7LLOY.js.map → chunk-ID4WXTKL.js.map} +1 -1
  93. package/dist/{chunk-EFELJVLA.js → chunk-ISLPNELU.js} +15 -3
  94. package/dist/chunk-ISLPNELU.js.map +1 -0
  95. package/dist/{chunk-A2I2XO52.cjs → chunk-IX64T5OL.cjs} +4 -4
  96. package/dist/{chunk-A2I2XO52.cjs.map → chunk-IX64T5OL.cjs.map} +1 -1
  97. package/dist/{chunk-QYWINYEA.cjs → chunk-J2ICGNHO.cjs} +5 -6
  98. package/dist/chunk-J2ICGNHO.cjs.map +1 -0
  99. package/dist/{chunk-7V2FGGI2.cjs → chunk-J7LXTUTP.cjs} +54 -12
  100. package/dist/chunk-J7LXTUTP.cjs.map +1 -0
  101. package/dist/{chunk-WBUFJ7BS.cjs → chunk-JQXSZHF2.cjs} +12 -2
  102. package/dist/chunk-JQXSZHF2.cjs.map +1 -0
  103. package/dist/{chunk-OVUUTCPJ.cjs → chunk-JXUTCSXX.cjs} +28 -2
  104. package/dist/chunk-JXUTCSXX.cjs.map +1 -0
  105. package/dist/{chunk-66UVLHQA.cjs → chunk-KMXWZLQX.cjs} +14 -14
  106. package/dist/{chunk-66UVLHQA.cjs.map → chunk-KMXWZLQX.cjs.map} +1 -1
  107. package/dist/{chunk-STQ3BSED.cjs → chunk-NAAMUYMS.cjs} +23 -11
  108. package/dist/chunk-NAAMUYMS.cjs.map +1 -0
  109. package/dist/{chunk-NN3QSOVS.cjs → chunk-OOA273IJ.cjs} +14 -14
  110. package/dist/{chunk-NN3QSOVS.cjs.map → chunk-OOA273IJ.cjs.map} +1 -1
  111. package/dist/{chunk-OSZPLZIV.cjs → chunk-P7GTYOLB.cjs} +130 -106
  112. package/dist/chunk-P7GTYOLB.cjs.map +1 -0
  113. package/dist/{chunk-K3BUWSFR.js → chunk-PVUI6KGR.js} +28 -2
  114. package/dist/chunk-PVUI6KGR.js.map +1 -0
  115. package/dist/{chunk-SBPC5IP3.js → chunk-Q6EDCUXV.js} +242 -10
  116. package/dist/chunk-Q6EDCUXV.js.map +1 -0
  117. package/dist/{chunk-2BIG7U6E.cjs → chunk-QC4MCOFV.cjs} +5 -5
  118. package/dist/{chunk-2BIG7U6E.cjs.map → chunk-QC4MCOFV.cjs.map} +1 -1
  119. package/dist/{chunk-JRP3VGHS.js → chunk-QLUXRWKL.js} +3 -3
  120. package/dist/{chunk-JRP3VGHS.js.map → chunk-QLUXRWKL.js.map} +1 -1
  121. package/dist/{chunk-IIT5K7SK.cjs → chunk-QR24DJDF.cjs} +6 -6
  122. package/dist/{chunk-IIT5K7SK.cjs.map → chunk-QR24DJDF.cjs.map} +1 -1
  123. package/dist/{chunk-HOIFFY4M.js → chunk-QRNYDV5Z.js} +48 -21
  124. package/dist/chunk-QRNYDV5Z.js.map +1 -0
  125. package/dist/{chunk-FRHHDHKH.js → chunk-RFRM3Q5K.js} +15 -3
  126. package/dist/chunk-RFRM3Q5K.js.map +1 -0
  127. package/dist/{chunk-ATLN63JA.js → chunk-RUQS6M7G.js} +5 -5
  128. package/dist/chunk-RUQS6M7G.js.map +1 -0
  129. package/dist/{chunk-XMYJY7NI.js → chunk-S3ZRKJHY.js} +3 -3
  130. package/dist/{chunk-XMYJY7NI.js.map → chunk-S3ZRKJHY.js.map} +1 -1
  131. package/dist/{chunk-FSXTPBRN.js → chunk-TKORQCG4.js} +49 -7
  132. package/dist/chunk-TKORQCG4.js.map +1 -0
  133. package/dist/{chunk-2Y4IFKW7.js → chunk-TKP5T34P.js} +3 -4
  134. package/dist/chunk-TKP5T34P.js.map +1 -0
  135. package/dist/{chunk-NCX65HBY.cjs → chunk-UCQ3BFSY.cjs} +301 -68
  136. package/dist/chunk-UCQ3BFSY.cjs.map +1 -0
  137. package/dist/{chunk-B75XRV3O.js → chunk-V34A6R5V.js} +12 -3
  138. package/dist/chunk-V34A6R5V.js.map +1 -0
  139. package/dist/{chunk-BNUFUFAU.js → chunk-VTN3C3CH.js} +6 -6
  140. package/dist/chunk-VTN3C3CH.js.map +1 -0
  141. package/dist/{chunk-5MUSU4ZP.cjs → chunk-VVQM4CZD.cjs} +12 -12
  142. package/dist/chunk-VVQM4CZD.cjs.map +1 -0
  143. package/dist/{chunk-IIMQJYAM.js → chunk-WDAVPX46.js} +3 -3
  144. package/dist/{chunk-IIMQJYAM.js.map → chunk-WDAVPX46.js.map} +1 -1
  145. package/dist/{chunk-YNULOIR5.cjs → chunk-WDBXJOU5.cjs} +28 -16
  146. package/dist/chunk-WDBXJOU5.cjs.map +1 -0
  147. package/dist/{chunk-PAW2XUZN.js → chunk-WUFASQUO.js} +3 -3
  148. package/dist/{chunk-PAW2XUZN.js.map → chunk-WUFASQUO.js.map} +1 -1
  149. package/dist/{chunk-PDGEXGS6.cjs → chunk-YDWLUT5V.cjs} +136 -109
  150. package/dist/chunk-YDWLUT5V.cjs.map +1 -0
  151. package/dist/{chunk-PHXITZE4.js → chunk-YMTXMPV6.js} +3 -3
  152. package/dist/{chunk-PHXITZE4.js.map → chunk-YMTXMPV6.js.map} +1 -1
  153. package/dist/{chunk-XR4YZFKW.cjs → chunk-YOALGKRE.cjs} +690 -364
  154. package/dist/chunk-YOALGKRE.cjs.map +1 -0
  155. package/dist/{chunk-6JZUSDY2.cjs → chunk-Z3WO6MND.cjs} +27 -27
  156. package/dist/{chunk-6JZUSDY2.cjs.map → chunk-Z3WO6MND.cjs.map} +1 -1
  157. package/dist/{chunk-2VLBGQBY.cjs → chunk-ZI6VQSZA.cjs} +37 -37
  158. package/dist/{chunk-2VLBGQBY.cjs.map → chunk-ZI6VQSZA.cjs.map} +1 -1
  159. package/dist/core/index.cjs +10 -11
  160. package/dist/core/index.d.cts +5 -5
  161. package/dist/core/index.d.ts +5 -5
  162. package/dist/core/index.js +3 -4
  163. package/dist/{ddl-eWg7hx6R.d.cts → ddl-BG4J805L.d.cts} +3 -3
  164. package/dist/{ddl-D5369kOY.d.ts → ddl-CgiS9QLj.d.ts} +3 -3
  165. package/dist/{define-graph-SvYXOl78.d.ts → define-graph-BGrJahvp.d.ts} +1 -1
  166. package/dist/{define-graph-DVF-oN1i.d.cts → define-graph-alREY2wj.d.cts} +1 -1
  167. package/dist/graph-extension/index.cjs +18 -19
  168. package/dist/graph-extension/index.d.cts +4 -4
  169. package/dist/graph-extension/index.d.ts +4 -4
  170. package/dist/graph-extension/index.js +3 -4
  171. package/dist/graph-merge/index.cjs +89 -90
  172. package/dist/graph-merge/index.cjs.map +1 -1
  173. package/dist/graph-merge/index.d.cts +9 -9
  174. package/dist/graph-merge/index.d.ts +9 -9
  175. package/dist/graph-merge/index.js +16 -17
  176. package/dist/graph-merge/index.js.map +1 -1
  177. package/dist/{index-By89Sezh.d.ts → index-BBxZCUdu.d.ts} +2 -2
  178. package/dist/{index-DcQ3Sxs-.d.cts → index-C3y_98iN.d.cts} +2 -2
  179. package/dist/index.cjs +124 -125
  180. package/dist/index.cjs.map +1 -1
  181. package/dist/index.d.cts +13 -13
  182. package/dist/index.d.ts +13 -13
  183. package/dist/index.js +23 -24
  184. package/dist/index.js.map +1 -1
  185. package/dist/indexes/index.cjs +11 -11
  186. package/dist/indexes/index.d.cts +4 -4
  187. package/dist/indexes/index.d.ts +4 -4
  188. package/dist/indexes/index.js +4 -4
  189. package/dist/interchange/index.cjs +27 -26
  190. package/dist/interchange/index.cjs.map +1 -1
  191. package/dist/interchange/index.d.cts +7 -7
  192. package/dist/interchange/index.d.ts +7 -7
  193. package/dist/interchange/index.js +8 -7
  194. package/dist/interchange/index.js.map +1 -1
  195. package/dist/{manager-Cn0NFIhN.d.cts → manager-KS7CGQQT.d.cts} +3 -3
  196. package/dist/{manager-B0KjKE93.d.ts → manager-YoLEfcc1.d.ts} +3 -3
  197. package/dist/{materialize-indexes-BD4V3svD.d.ts → materialize-indexes-Bhhyb1B3.d.ts} +1 -1
  198. package/dist/{materialize-indexes-DVRhd5h4.d.cts → materialize-indexes-OHRWypW6.d.cts} +1 -1
  199. package/dist/{postgres-DaEWvN4x.d.cts → postgres-DpkW3R5Y.d.cts} +1 -1
  200. package/dist/{postgres-u0a0HN2D.d.ts → postgres-DwqyIniy.d.ts} +1 -1
  201. package/dist/profiler/index.d.cts +10 -10
  202. package/dist/profiler/index.d.ts +10 -10
  203. package/dist/provenance/index.cjs +15 -15
  204. package/dist/provenance/index.cjs.map +1 -1
  205. package/dist/provenance/index.d.cts +7 -7
  206. package/dist/provenance/index.d.ts +7 -7
  207. package/dist/provenance/index.js +3 -3
  208. package/dist/provenance/index.js.map +1 -1
  209. package/dist/schema/index.cjs +30 -31
  210. package/dist/schema/index.d.cts +7 -7
  211. package/dist/schema/index.d.ts +7 -7
  212. package/dist/schema/index.js +8 -9
  213. package/dist/{searchable-BT7j9_IK.d.cts → searchable-CIZL8Hyw.d.cts} +2 -2
  214. package/dist/{searchable-CnYEancP.d.ts → searchable-DLWEfC4a.d.ts} +2 -2
  215. package/dist/{sqlite-BrMoSsI7.d.cts → sqlite-DY0WODUK.d.cts} +1 -1
  216. package/dist/{sqlite-CHhZUyO5.d.ts → sqlite-L-VIRzqA.d.ts} +1 -1
  217. package/dist/{store-view-Bvdku0Ht.d.ts → store-view-66p92IPi.d.ts} +1887 -1811
  218. package/dist/{store-view-w-md0nQ4.d.cts → store-view-A85FFRnk.d.cts} +1887 -1811
  219. package/dist/{temporal-BCORwUau.d.cts → temporal-BNbjXqer.d.cts} +1 -1
  220. package/dist/{temporal--x9T8K4S.d.ts → temporal-Bob6Nfbp.d.ts} +1 -1
  221. package/dist/{types-Cjvkj0jA.d.ts → types-Ch9a0Dx6.d.cts} +141 -17
  222. package/dist/{types-Cjvkj0jA.d.cts → types-Ch9a0Dx6.d.ts} +141 -17
  223. package/dist/{types-COODtTJU.d.ts → types-ClCzT-dT.d.ts} +1 -1
  224. package/dist/{types-6-WJmSD4.d.cts → types-DeORZhxn.d.cts} +1 -1
  225. package/dist/{where-CUQmCR6d.d.cts → where-DPw52ksb.d.cts} +1 -1
  226. package/dist/{where-5xVawAwL.d.ts → where-kWUZPvEA.d.ts} +1 -1
  227. package/package.json +1 -1
  228. package/dist/chunk-2WDD2NO3.js +0 -59
  229. package/dist/chunk-2WDD2NO3.js.map +0 -1
  230. package/dist/chunk-2Y4IFKW7.js.map +0 -1
  231. package/dist/chunk-3PRKZW6D.cjs.map +0 -1
  232. package/dist/chunk-5MUSU4ZP.cjs.map +0 -1
  233. package/dist/chunk-63KCKSSH.js.map +0 -1
  234. package/dist/chunk-7V2FGGI2.cjs.map +0 -1
  235. package/dist/chunk-A4PBRX4C.cjs.map +0 -1
  236. package/dist/chunk-ATLN63JA.js.map +0 -1
  237. package/dist/chunk-B75XRV3O.js.map +0 -1
  238. package/dist/chunk-BNUFUFAU.js.map +0 -1
  239. package/dist/chunk-EE7N5XXQ.cjs.map +0 -1
  240. package/dist/chunk-EFELJVLA.js.map +0 -1
  241. package/dist/chunk-EPTSMFH7.cjs +0 -12
  242. package/dist/chunk-FGO5JFVJ.cjs.map +0 -1
  243. package/dist/chunk-FMGEZBAQ.js.map +0 -1
  244. package/dist/chunk-FMMIX6N4.js.map +0 -1
  245. package/dist/chunk-FRHHDHKH.js.map +0 -1
  246. package/dist/chunk-FSXTPBRN.js.map +0 -1
  247. package/dist/chunk-HOHAJ2NR.cjs +0 -61
  248. package/dist/chunk-HOHAJ2NR.cjs.map +0 -1
  249. package/dist/chunk-HOIFFY4M.js.map +0 -1
  250. package/dist/chunk-IJTLXNGJ.js.map +0 -1
  251. package/dist/chunk-K3BUWSFR.js.map +0 -1
  252. package/dist/chunk-MCHP7RHZ.cjs.map +0 -1
  253. package/dist/chunk-NCX65HBY.cjs.map +0 -1
  254. package/dist/chunk-OSZPLZIV.cjs.map +0 -1
  255. package/dist/chunk-OVUUTCPJ.cjs.map +0 -1
  256. package/dist/chunk-PDGEXGS6.cjs.map +0 -1
  257. package/dist/chunk-QYWINYEA.cjs.map +0 -1
  258. package/dist/chunk-SBPC5IP3.js.map +0 -1
  259. package/dist/chunk-SQRD2CYF.js.map +0 -1
  260. package/dist/chunk-ST3LPB2V.cjs.map +0 -1
  261. package/dist/chunk-STQ3BSED.cjs.map +0 -1
  262. package/dist/chunk-TVLKA4AY.js.map +0 -1
  263. package/dist/chunk-WBUFJ7BS.cjs.map +0 -1
  264. package/dist/chunk-XR4YZFKW.cjs.map +0 -1
  265. package/dist/chunk-YNULOIR5.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/store/row-mappers.ts","../src/store/operations/write-transaction.ts","../src/store/constraints.ts","../src/store/operations/node-operations.ts"],"names":["row"],"mappings":";;;;;;;;;;;;;;;AAiCA,SAAS,gBAAmB,KAAA,EAA4C;AACtE,EAAA,OAAO,KAAA,KAAU,OAAO,MAAA,GAAY,KAAA;AACtC;AASO,SAAS,UAAU,GAAA,EAAoB;AAC5C,EAAA,MAAM,QAAA,GAAW,gBAAA,CAAiB,GAAA,CAAI,KAAK,CAAA;AAC3C,EAAA,MAAM,KAAA,GAAQ,kBAAA,CAAmB,QAAA,EAAU,kBAAkB,CAAA;AAC7D,EAAA,OAAO;AAAA,IACL,MAAM,GAAA,CAAI,IAAA;AAAA,IACV,IAAI,GAAA,CAAI,EAAA;AAAA,IACR,IAAA,EAAM,cAAc,GAAG,CAAA;AAAA,IACvB,GAAG;AAAA,GACL;AACF;AAEO,SAAS,cACd,GAAA,EASU;AACV,EAAA,OAAO;AAAA,IACL,SAAS,GAAA,CAAI,O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AAAA,UACE,IAAA,EAAM,YAAA;AAAA,UACN,IAAI,WAAA,CAAY,EAAA;AAAA,UAChB,KAAA,EAAO;AAAA,SACT;AAAA,QACA,OAAA;AAAA,QACA,EAAE,cAAc,aAAA;AAAc,OAChC;AACA,MAAA,OAAA,CAAQ,KAAK,CAAA,GAAI;AAAA,QACf,IAAA;AAAA,QACA,MAAA,EAAQ,gBAAgB,aAAA,GAAgB;AAAA,OAC1C;AAAA,IACF,CAAA,MAAO;AACL,MAAA,OAAA,CAAQ,KAAK,IAAI,EAAE,IAAA,EAAM,UAAU,WAAW,CAAA,EAAG,QAAQ,OAAA,EAAQ;AAAA,IACnE;AAAA,EACF;AAGA,EAAA,KAAA,MAAW,EAAE,KAAA,EAAO,WAAA,EAAY,IAAK,WAAA,EAAa;AAChD,IAAA,MAAM,YAAA,GAAe,cAAA,CAAe,OAAA,CAAQ,WAAW,CAAC,CAAA;AACxD,IAAA,OAAA,CAAQ,KAAK,CAAA,GAAI,EAAE,MAAM,YAAA,CAAa,IAAA,EAAM,QAAQ,OAAA,EAAQ;AAAA,EAC9D;AAEA,EAAA,OAAO,OAAA;AACT","file":"chunk-Q6EDCUXV.js","sourcesContent":["/**\n * Row Mappers for Store\n *\n * Transforms database rows into typed Node and Edge objects.\n */\nimport {\n type EdgeRow as BackendEdgeRow,\n type NodeRow as BackendNodeRow,\n rowPropsToObject,\n} from \"../backend/types\";\nimport {\n filterReservedKeys,\n RESERVED_EDGE_KEYS,\n RESERVED_NODE_KEYS,\n} from \"./reserved-keys\";\nimport { type Edge, type EdgeMeta, type Node, type NodeMeta } from \"./types\";\n\n/**\n * Raw node row from database (without graph_id).\n * Derived from BackendNodeRow so BackendNodeRow is assignable without casts.\n */\nexport type NodeRow = Omit<BackendNodeRow, \"graph_id\">;\n\n/**\n * Raw edge row from database (without graph_id).\n * Derived from BackendEdgeRow so BackendEdgeRow is assignable without casts.\n */\nexport type EdgeRow = Omit<BackendEdgeRow, \"graph_id\">;\n\n/**\n * Converts null to undefined for consistent typing.\n * Database backends return null for missing values, but our types use undefined.\n */\nfunction nullToUndefined<T>(value: T | null | undefined): T | undefined {\n return value === null ? undefined : value;\n}\n\n/**\n * Transforms a database row into a typed Node object.\n *\n * Props are spread at top level, metadata goes under `meta`.\n * Reserved keys (id, kind, meta) in props are filtered out to prevent collisions.\n * Null values from database are normalized to undefined.\n */\nexport function rowToNode(row: NodeRow): Node {\n const rawProps = rowPropsToObject(row.props);\n const props = filterReservedKeys(rawProps, RESERVED_NODE_KEYS);\n return {\n kind: row.kind,\n id: row.id as Node[\"id\"],\n meta: rowToNodeMeta(row),\n ...props,\n };\n}\n\nexport function rowToNodeMeta(\n row: Pick<\n NodeRow,\n | \"version\"\n | \"valid_from\"\n | \"valid_to\"\n | \"created_at\"\n | \"updated_at\"\n | \"deleted_at\"\n >,\n): NodeMeta {\n return {\n version: row.version,\n validFrom: nullToUndefined(row.valid_from),\n validTo: nullToUndefined(row.valid_to),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n deletedAt: nullToUndefined(row.deleted_at),\n };\n}\n\n/**\n * Transforms a database row into a typed Edge object.\n *\n * Props are spread at top level, metadata goes under `meta`.\n * Reserved keys in props are filtered out to prevent collisions.\n * Null values from database are normalized to undefined.\n */\nexport function rowToEdge(row: EdgeRow): Edge {\n const rawProps = rowPropsToObject(row.props);\n const props = filterReservedKeys(rawProps, RESERVED_EDGE_KEYS);\n return {\n id: row.id,\n kind: row.kind,\n fromKind: row.from_kind,\n fromId: row.from_id,\n toKind: row.to_kind,\n toId: row.to_id,\n meta: rowToEdgeMeta(row),\n ...props,\n } as Edge;\n}\n\nexport function rowToEdgeMeta(\n row: Pick<\n EdgeRow,\n \"valid_from\" | \"valid_to\" | \"created_at\" | \"updated_at\" | \"deleted_at\"\n >,\n): EdgeMeta {\n return {\n validFrom: nullToUndefined(row.valid_from),\n validTo: nullToUndefined(row.valid_to),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n deletedAt: nullToUndefined(row.deleted_at),\n };\n}\n","/**\n * Shared transaction boundary for graph-entity mutations.\n *\n * A node/edge mutation is a cascade of steps — the core row write plus its\n * integrity side effects (uniqueness, embeddings, fulltext) or its delete\n * behavior (restrict / cascade / disconnect). Those steps are individually\n * atomic but not collectively atomic, so the cascade runs inside one top-level\n * transaction whether or not recorded-time capture is enabled: a mid-cascade\n * failure then rolls back the whole operation instead of leaving a half-applied\n * write (e.g. an inserted node whose uniqueness/embedding/fulltext rows were\n * never written, or a uniqueness conflict that leaves an orphaned node row).\n * Under history capture the per-graph write lock is additionally taken inside\n * that transaction so recorded capture serializes.\n *\n * Both {@link NodeOperationContext} and {@link EdgeOperationContext} route their\n * mutations through this one helper, replacing the byte-identical per-file\n * copies that previously drifted independently.\n */\nimport {\n type GraphBackend,\n runOptionallyInTransaction,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport { ConfigurationError } from \"../../errors\";\nimport { type SqlSchema } from \"../../query/compiler/schema\";\nimport {\n advanceRevisionClock,\n lockRecordedGraphWrite,\n} from \"../recorded-capture\";\nimport {\n type GraphWriteLock,\n uncapturedGraphWriteLock,\n} from \"../recorded-capture/clock\";\nimport { type OperationHookContext } from \"../types\";\n\n/**\n * The slice of an operation context {@link runInWriteTransaction} needs: the\n * graph id (for the capture lock) and whether recorded-time capture is on.\n * Both {@link NodeOperationContext} and {@link EdgeOperationContext} satisfy it.\n */\nexport type WriteTransactionContext = Readonly<{\n graphId: string;\n schemaVersion: number | undefined;\n historyEnabled: boolean;\n revisionTrackingEnabled: boolean;\n revisionSchema: SqlSchema;\n}>;\n\n/**\n * Acquires and validates the transaction-scoped schema fence for one managed\n * Store write. This intentionally runs for every write: PostgreSQL releases\n * row locks acquired after a savepoint when the caller rolls back to that\n * savepoint, so caching an earlier acquisition could let a later write proceed\n * without a live fence.\n */\nexport async function lockSchemaVersionForStoreWrite(\n ctx: Pick<WriteTransactionContext, \"graphId\" | \"schemaVersion\">,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n const expectedVersion = ctx.schemaVersion;\n if (expectedVersion === undefined) return;\n\n if (\"transaction\" in backend && !backend.capabilities.transactions) {\n throw new ConfigurationError(\n \"Schema-managed Store writes require a transactional backend so schema \" +\n \"changes and entity writes can share one fence.\",\n {\n code: \"SCHEMA_WRITE_FENCE_UNSUPPORTED\",\n graphId: ctx.graphId,\n },\n );\n }\n\n const lockSchemaVersionForWrite = backend.lockSchemaVersionForWrite;\n if (lockSchemaVersionForWrite === undefined) {\n throw new ConfigurationError(\n \"This backend cannot fence schema-managed Store writes against a \" +\n \"concurrent schema change.\",\n {\n code: \"SCHEMA_WRITE_FENCE_UNSUPPORTED\",\n graphId: ctx.graphId,\n },\n );\n }\n\n await lockSchemaVersionForWrite({\n graphId: ctx.graphId,\n expectedVersion,\n });\n}\n\n/**\n * Runs a graph-entity mutation cascade inside a single top-level transaction.\n *\n * On a transactional backend the cascade shares one transaction so it commits\n * or rolls back atomically. A nested {@link TransactionBackend} (already inside\n * `store.transaction(...)`) omits `.transaction`, so\n * {@link runOptionallyInTransaction} runs `fn` directly against it rather than\n * opening a nested transaction. A raw Store on a non-transactional backend\n * (Cloudflare D1, `drizzle-orm/neon-http`) also runs `fn` directly and cannot\n * offer atomicity. A schema-managed Store fails closed before `fn` because the\n * backend cannot hold the schema-version fence.\n *\n * Under history capture the per-graph write lock is taken inside the\n * transaction before any row work, matching the acquire order the recorded\n * clock lock depends on to avoid a circular wait.\n */\nexport function runInWriteTransaction<T>(\n ctx: WriteTransactionContext,\n backend: GraphBackend | TransactionBackend,\n fn: (\n target: GraphBackend | TransactionBackend,\n lock: GraphWriteLock,\n ) => Promise<T>,\n options?: Readonly<{ didWrite?: (result: T) => boolean }>,\n): Promise<T> {\n const ownsWriteLock =\n \"transaction\" in backend && backend.capabilities.transactions;\n return runOptionallyInTransaction(backend, async (target) => {\n await lockSchemaVersionForStoreWrite(ctx, target);\n const lock =\n ctx.historyEnabled || ctx.revisionTrackingEnabled ?\n await lockRecordedGraphWrite(target, ctx.graphId)\n : uncapturedGraphWriteLock();\n const result = await fn(target, lock);\n // History capture advances the same clock when it flushes its recorded\n // after-images. Live stores opt into revisions independently, so advance\n // only there and only after every row/sidecar write succeeded.\n if (\n ctx.revisionTrackingEnabled &&\n !ctx.historyEnabled &&\n (options?.didWrite?.(result) ?? true)\n ) {\n await advanceRevisionClock(\n target,\n ctx.revisionSchema,\n ctx.graphId,\n ownsWriteLock,\n );\n }\n return result;\n });\n}\n\n/**\n * The slice of an operation context {@link runHookedWriteOperation} needs:\n * the {@link WriteTransactionContext} plus the hook wrapper. Both\n * `NodeOperationContext` and `EdgeOperationContext` satisfy it.\n */\nexport type HookedWriteOperationContext = WriteTransactionContext &\n Readonly<{\n withOperationHooks: <T>(\n ctx: OperationHookContext,\n fn: () => Promise<T>,\n ) => Promise<T>;\n }>;\n\n/**\n * The one sanctioned composition for a hooked, non-batch write operation:\n * operation hooks WRAP the write transaction, so `onOperationEnd` observes a\n * durably committed result and a failed COMMIT surfaces through `onError` —\n * a hook that fired inside the transaction would report success for a write\n * the rollback then discards. Every hooked node/edge mutation routes through\n * this helper; composing `withOperationHooks` and `runInWriteTransaction` by\n * hand invites exactly the inverted nesting this exists to prevent.\n * (Batch operations skip hooks deliberately and call\n * {@link runInWriteTransaction} directly.)\n */\nexport function runHookedWriteOperation<T>(\n ctx: HookedWriteOperationContext,\n opContext: OperationHookContext,\n backend: GraphBackend | TransactionBackend,\n body: (\n target: GraphBackend | TransactionBackend,\n lock: GraphWriteLock,\n ) => Promise<T>,\n): Promise<T> {\n return ctx.withOperationHooks(opContext, () =>\n runInWriteTransaction(ctx, backend, body),\n );\n}\n","/**\n * Constraint Checking for Store Operations\n *\n * Handles checking disjointness and cardinality constraints.\n */\nimport { type GraphBackend, type TransactionBackend } from \"../backend/types\";\nimport {\n checkCardinality,\n checkDisjointness,\n checkUniqueEdge,\n} from \"../constraints\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\n\n/**\n * Context for constraint operations.\n */\nexport type ConstraintContext = Readonly<{\n graphId: string;\n registry: KindRegistry;\n backend: GraphBackend | TransactionBackend;\n}>;\n\n/**\n * Checks disjointness constraints for a node.\n *\n * Ensures that a node with a given ID doesn't exist in any disjoint kinds.\n *\n * @throws ValidationError if disjointness constraint is violated\n */\nexport async function checkDisjointnessConstraint(\n ctx: ConstraintContext,\n kind: string,\n id: string,\n): Promise<void> {\n // Get all kinds that are disjoint with this kind\n const disjointKinds = ctx.registry.getDisjointKinds(kind);\n\n // For each disjoint kind, check if a node with this ID exists\n for (const disjointKind of disjointKinds) {\n const existing = await ctx.backend.getNode(ctx.graphId, disjointKind, id);\n if (existing && !existing.deleted_at) {\n const error = checkDisjointness(id, kind, [disjointKind], ctx.registry);\n if (error) throw error;\n }\n }\n}\n\n/**\n * Checks cardinality constraints for an edge.\n *\n * @throws CardinalityError if cardinality constraint is violated\n */\nexport async function checkCardinalityConstraint(\n ctx: ConstraintContext,\n edgeKind: string,\n cardinality: \"many\" | \"one\" | \"unique\" | \"oneActive\",\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n validTo: string | undefined,\n): Promise<void> {\n switch (cardinality) {\n case \"many\": {\n // No constraint - allow any number of edges\n return;\n }\n\n case \"one\": {\n // At most one edge of this kind from this source\n const count = await ctx.backend.countEdgesFrom({\n graphId: ctx.graphId,\n edgeKind,\n fromKind,\n fromId,\n });\n const error = checkCardinality(\n edgeKind,\n fromKind,\n fromId,\n \"one\",\n count,\n false,\n );\n if (error) throw error;\n return;\n }\n\n case \"unique\": {\n // At most one edge between this specific source-target pair\n const exists = await ctx.backend.edgeExistsBetween({\n graphId: ctx.graphId,\n edgeKind,\n fromKind,\n fromId,\n toKind,\n toId,\n });\n const error = checkUniqueEdge(\n edgeKind,\n fromKind,\n fromId,\n toKind,\n toId,\n exists ? 1 : 0,\n );\n if (error) throw error;\n return;\n }\n\n case \"oneActive\": {\n // At most one active edge (valid_to IS NULL) from this source\n // Only check if the new edge will be active (validTo is not set)\n if (validTo !== undefined) {\n // New edge is already ended, no active constraint to check\n return;\n }\n const count = await ctx.backend.countEdgesFrom({\n graphId: ctx.graphId,\n edgeKind,\n fromKind,\n fromId,\n activeOnly: true,\n });\n const error = checkCardinality(\n edgeKind,\n fromKind,\n fromId,\n \"oneActive\",\n count,\n count > 0,\n );\n if (error) throw error;\n return;\n }\n }\n}\n","/**\n * Node Operations for Store\n *\n * Handles node CRUD operations: create, update, delete.\n */\nimport {\n createBackendOverlay,\n type GraphBackend,\n type InsertNodeParams,\n isLiveNodeRow,\n type NodeRow as BackendNodeRow,\n rowPropsToObject,\n type TransactionBackend,\n type UniqueRow,\n} from \"../../backend/types\";\nimport {\n checkWherePredicate,\n computeUniqueKey,\n getKindsForUniquenessCheck,\n} from \"../../constraints\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { assertJsonValue } from \"../../core/json-value\";\nimport {\n type JsonValue,\n type KindEntity,\n type NodeType,\n type UniqueConstraint,\n} from \"../../core/types\";\nimport {\n ConfigurationError,\n DatabaseOperationError,\n KindNotFoundError,\n NodeConstraintNotFoundError,\n NodeIndexNotFoundError,\n NodeNotFoundError,\n UniquenessError,\n ValidationError,\n} from \"../../errors\";\nimport { validateNodeProps } from \"../../errors/validation\";\nimport {\n compileIndexWhere,\n compileNodeIndexFieldKeys,\n type IndexCompilationContext,\n} from \"../../indexes/compiler\";\nimport { type NodeIndexDeclaration } from \"../../indexes/types\";\nimport { type ValueType } from \"../../query/ast\";\nimport {\n createSqlSchema,\n DEFAULT_SQL_SCHEMA,\n type SqlSchema,\n} from \"../../query/compiler/schema\";\nimport { getDialect } from \"../../query/dialect\";\nimport { type DialectAdapter } from \"../../query/dialect/types\";\nimport { type JsonPointer, resolveJsonPointer } from \"../../query/json-pointer\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport type { CompiledSelectSql } from \"../../query/sql-intent\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport { canonicalEqual } from \"../../schema/canonical\";\nimport { validateOptionalCanonicalIsoDate } from \"../../utils/date\";\nimport { generateId } from \"../../utils/id\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { type UpsertDirtyCheck } from \"../collections/coalesce\";\nimport {\n checkDisjointnessConstraint,\n type ConstraintContext,\n} from \"../constraints\";\nimport { getEmbeddingFields } from \"../embedding-sync\";\nimport { getSearchableFields } from \"../fulltext-sync\";\nimport {\n nodeInsertDispatch,\n runInsertBatch,\n runInsertBatchReturning,\n runInsertNoReturn,\n} from \"../insert-dispatch\";\nimport { getNodeRowsByIds } from \"../node-fetch\";\nimport { type GraphWriteLock } from \"../recorded-capture/clock\";\nimport { type NodeRow, rowToNode } from \"../row-mappers\";\nimport {\n type BulkOperationHookContext,\n type CreateNodeInput,\n type GetOrCreateAction,\n type Node,\n type NodeBulkFindByIndexOptions,\n type NodeGetOrCreateByConstraintOptions,\n type OperationHookContext,\n type UpdateNodeInput,\n} from \"../types\";\nimport {\n checkUniquenessConstraints,\n createUniquenessContext,\n} from \"../uniqueness\";\nimport {\n applyNodeHardDelete,\n applyNodeInsertSideEffects,\n applyNodeInsertSideEffectsBatch,\n applyNodeSoftDelete,\n applyNodeUpdate,\n createNodeWriteContext,\n} from \"./node-write-pipeline\";\nimport {\n runHookedWriteOperation,\n runInWriteTransaction,\n} from \"./write-transaction\";\n\n// ============================================================\n// Types\n// ============================================================\n\nexport type NodeOperationContext<G extends GraphDef> = Readonly<{\n graph: G;\n graphId: string;\n schemaVersion: number | undefined;\n historyEnabled: boolean;\n revisionTrackingEnabled: boolean;\n revisionSchema: SqlSchema;\n registry: KindRegistry;\n createOperationContext: (\n operation: \"create\" | \"update\" | \"delete\",\n entity: KindEntity,\n kind: string,\n id: string,\n ) => OperationHookContext;\n withOperationHooks: <T>(\n ctx: OperationHookContext,\n fn: () => Promise<T>,\n ) => Promise<T>;\n createBulkOperationContext: (\n operation: \"updateWhere\",\n kind: string,\n ) => BulkOperationHookContext;\n withBulkOperationHooks: <T extends Readonly<{ affectedCount: number }>>(\n ctx: BulkOperationHookContext,\n fn: () => Promise<T>,\n ) => Promise<T>;\n}>;\n\ntype NodeCreatePrepared = Readonly<{\n kind: string;\n id: string;\n nodeKind: NodeType;\n validatedProps: Record<string, unknown>;\n uniqueConstraints: readonly UniqueConstraint[];\n insertParams: InsertNodeParams;\n}>;\n\ntype CachedNodeRow = Awaited<ReturnType<GraphBackend[\"getNode\"]>>;\ntype CachedUniqueRow = Awaited<ReturnType<GraphBackend[\"checkUnique\"]>>;\n\n// ============================================================\n// Helper Functions\n// ============================================================\n\nfunction getNodeRegistration<G extends GraphDef>(graph: G, kind: string) {\n const registration = graph.nodes[kind];\n if (registration === undefined) throw new KindNotFoundError(kind, \"node\");\n return registration;\n}\n\nconst CACHE_KEY_SEPARATOR = \"\\u0000\";\n\nfunction buildNodeCacheKey(graphId: string, kind: string, id: string): string {\n return `${graphId}${CACHE_KEY_SEPARATOR}${kind}${CACHE_KEY_SEPARATOR}${id}`;\n}\n\nfunction buildUniqueCacheKey(\n graphId: string,\n nodeKind: string,\n constraintName: string,\n key: string,\n): string {\n return `${graphId}${CACHE_KEY_SEPARATOR}${nodeKind}${CACHE_KEY_SEPARATOR}${constraintName}${CACHE_KEY_SEPARATOR}${key}`;\n}\n\nfunction createNodeAlreadyExistsError(\n kind: string,\n id: string,\n): ValidationError {\n return new ValidationError(\n `Node already exists: ${kind}/${id}`,\n {\n entityType: \"node\",\n kind,\n operation: \"create\",\n id,\n issues: [{ path: \"id\", message: \"A node with this ID already exists\" }],\n },\n { suggestion: `Use a different ID or update the existing node.` },\n );\n}\n\nfunction buildInsertNodeParams(\n graphId: string,\n kind: string,\n id: string,\n props: Record<string, unknown>,\n validFrom: string | undefined,\n validTo: string | undefined,\n): InsertNodeParams {\n const insertParams: {\n graphId: string;\n kind: string;\n id: string;\n props: Record<string, unknown>;\n validFrom?: string;\n validTo?: string;\n } = {\n graphId,\n kind,\n id,\n props,\n };\n if (validFrom !== undefined) insertParams.validFrom = validFrom;\n if (validTo !== undefined) insertParams.validTo = validTo;\n return insertParams;\n}\n\nfunction createPendingUniqueRow(\n graphId: string,\n nodeKind: string,\n constraintName: string,\n key: string,\n nodeId: string,\n): UniqueRow {\n return {\n graph_id: graphId,\n node_kind: nodeKind,\n constraint_name: constraintName,\n key,\n node_id: nodeId,\n concrete_kind: nodeKind,\n deleted_at: undefined,\n };\n}\n\nfunction resolveConstraint<G extends GraphDef>(\n graph: G,\n kind: string,\n constraintName: string,\n): UniqueConstraint {\n const registration = getNodeRegistration(graph, kind);\n const constraints = registration.unique ?? [];\n const constraint = constraints.find(\n (candidate) => candidate.name === constraintName,\n );\n if (constraint === undefined) {\n throw new NodeConstraintNotFoundError(constraintName, kind);\n }\n return constraint;\n}\n\n// ============================================================\n// Batch Validation Cache\n//\n// During batch operations, multiple items may reference the same\n// nodes/unique keys. This cache avoids redundant backend lookups\n// and tracks pending (not-yet-flushed) inserts so that later items\n// in the batch can see earlier ones during validation.\n// ============================================================\n\nexport function createNodeBatchValidationBackend(\n graphId: string,\n registry: KindRegistry,\n backend: GraphBackend | TransactionBackend,\n): Readonly<{\n backend: GraphBackend | TransactionBackend;\n registerPendingNode: (params: InsertNodeParams) => void;\n registerPendingUniqueEntries: (\n kind: string,\n id: string,\n props: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n ) => void;\n registerAppliedNodeUpdate: (\n kind: string,\n id: string,\n oldProps: Record<string, unknown>,\n newProps: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n ) => void;\n seedNodeRow: (kind: string, id: string, row: CachedNodeRow) => void;\n seedUniqueRow: (\n kind: string,\n constraintName: string,\n key: string,\n row: CachedUniqueRow,\n ) => void;\n}> {\n const nodeCache = new Map<string, CachedNodeRow>();\n const pendingNodes = new Map<string, NonNullable<CachedNodeRow>>();\n const uniqueCache = new Map<string, CachedUniqueRow>();\n const pendingUniqueOwners = new Map<string, string>();\n\n async function getNodeCached(\n lookupGraphId: string,\n kind: string,\n id: string,\n ): Promise<CachedNodeRow> {\n const cacheKey = buildNodeCacheKey(lookupGraphId, kind, id);\n const pendingNode = pendingNodes.get(cacheKey);\n if (pendingNode !== undefined) return pendingNode;\n if (nodeCache.has(cacheKey)) return nodeCache.get(cacheKey);\n const existing = await backend.getNode(lookupGraphId, kind, id);\n nodeCache.set(cacheKey, existing);\n return existing;\n }\n\n async function checkUniqueCached(\n params: Parameters<GraphBackend[\"checkUnique\"]>[0],\n ): Promise<CachedUniqueRow> {\n const cacheKey = buildUniqueCacheKey(\n params.graphId,\n params.nodeKind,\n params.constraintName,\n params.key,\n );\n const pendingOwner = pendingUniqueOwners.get(cacheKey);\n if (pendingOwner !== undefined) {\n return createPendingUniqueRow(\n params.graphId,\n params.nodeKind,\n params.constraintName,\n params.key,\n pendingOwner,\n );\n }\n if (uniqueCache.has(cacheKey)) return uniqueCache.get(cacheKey);\n const existing = await backend.checkUnique(params);\n uniqueCache.set(cacheKey, existing);\n return existing;\n }\n\n function registerPendingNode(params: InsertNodeParams): void {\n const cacheKey = buildNodeCacheKey(params.graphId, params.kind, params.id);\n pendingNodes.set(cacheKey, {\n graph_id: params.graphId,\n kind: params.kind,\n id: params.id,\n props: JSON.stringify(params.props),\n version: 1,\n // The simulated cached row only needs a NodeRow-shaped valid_from\n // (string | undefined, never null) for existence/uniqueness checks,\n // which don't inspect its value — normalize import's explicit-NULL\n // sentinel away rather than widen this cache's row shape.\n valid_from: params.validFrom ?? undefined,\n valid_to: params.validTo,\n created_at: \"\",\n updated_at: \"\",\n deleted_at: undefined,\n });\n }\n\n function registerPendingUniqueEntries(\n kind: string,\n id: string,\n props: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n ): void {\n for (const constraint of constraints) {\n if (!checkWherePredicate(constraint, props)) continue;\n\n const key = computeUniqueKey(\n props,\n constraint.fields,\n constraint.collation,\n );\n const concreteEntryKey = buildUniqueCacheKey(\n graphId,\n kind,\n constraint.name,\n key,\n );\n pendingUniqueOwners.set(concreteEntryKey, id);\n\n if (constraint.scope !== \"kind\") {\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n registry,\n );\n for (const kindToCheck of kindsToCheck) {\n const inheritedEntryKey = buildUniqueCacheKey(\n graphId,\n kindToCheck,\n constraint.name,\n key,\n );\n pendingUniqueOwners.set(inheritedEntryKey, id);\n }\n }\n }\n }\n\n // Reflects a completed in-slice node update in the uniqueness caches so a\n // later row's pre-check sees the post-update reservation state — the state\n // the sequential path's per-row backend read would observe. The batch path\n // primes the caches ONCE before routing, but an in-slice update mutates the\n // real backend's uniqueness rows directly; without reconciling here a later\n // create either (a) claims a value this update just freed yet gets rejected\n // against the stale reservation, or (b) passes the stale \"free\" cache for a\n // value this update just took and then violates the real constraint at\n // flush, aborting the whole import. Mirrors updateUniquenessEntries' key\n // diff: for each constraint whose key changed, the released old key becomes\n // free and the reserved new key becomes owned by this node, across every\n // kind the constraint's scope checks.\n function registerAppliedNodeUpdate(\n kind: string,\n id: string,\n oldProps: Record<string, unknown>,\n newProps: Record<string, unknown>,\n constraints: readonly UniqueConstraint[],\n ): void {\n for (const constraint of constraints) {\n const oldApplies = checkWherePredicate(constraint, oldProps);\n const newApplies = checkWherePredicate(constraint, newProps);\n const oldKey =\n oldApplies ?\n computeUniqueKey(oldProps, constraint.fields, constraint.collation)\n : undefined;\n const newKey =\n newApplies ?\n computeUniqueKey(newProps, constraint.fields, constraint.collation)\n : undefined;\n if (oldKey === newKey) continue;\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n registry,\n );\n\n if (oldKey !== undefined) {\n for (const kindToCheck of kindsToCheck) {\n const cacheKey = buildUniqueCacheKey(\n graphId,\n kindToCheck,\n constraint.name,\n oldKey,\n );\n // This node released the key on the real backend, so it is now\n // free. Clear any pending reservation and record the known-free\n // state (overwriting a stale seeded owner) so a later create's\n // pre-check sees a vacancy instead of a redundant backend read.\n pendingUniqueOwners.delete(cacheKey);\n uniqueCache.set(cacheKey, undefined);\n }\n }\n if (newKey !== undefined) {\n for (const kindToCheck of kindsToCheck) {\n const cacheKey = buildUniqueCacheKey(\n graphId,\n kindToCheck,\n constraint.name,\n newKey,\n );\n // This node now holds the key on the real backend. A pending owner\n // shadows the seeded uniqueCache entry (checkUniqueCached consults\n // it first), matching registerPendingUniqueEntries' reservation.\n pendingUniqueOwners.set(cacheKey, id);\n }\n }\n }\n }\n\n // Seed functions let batch preparation prime the caches from one\n // getNodes / checkUniqueBatch round trip instead of a per-row probe.\n // Seeding an absent result (`undefined`) is meaningful — it marks the\n // key as known-missing so the per-row check skips the backend read.\n // Existing entries are never overwritten: a pending registration or an\n // earlier lookup always wins.\n function seedNodeRow(kind: string, id: string, row: CachedNodeRow): void {\n const cacheKey = buildNodeCacheKey(graphId, kind, id);\n if (nodeCache.has(cacheKey)) return;\n nodeCache.set(cacheKey, row);\n }\n\n function seedUniqueRow(\n kind: string,\n constraintName: string,\n key: string,\n row: CachedUniqueRow,\n ): void {\n const cacheKey = buildUniqueCacheKey(graphId, kind, constraintName, key);\n if (uniqueCache.has(cacheKey)) return;\n uniqueCache.set(cacheKey, row);\n }\n\n const validationBackend = createBackendOverlay(backend, {\n getNode: getNodeCached,\n checkUnique: checkUniqueCached,\n } satisfies Partial<GraphBackend | TransactionBackend>);\n\n return {\n backend: validationBackend,\n registerPendingNode,\n registerPendingUniqueEntries,\n registerAppliedNodeUpdate,\n seedNodeRow,\n seedUniqueRow,\n };\n}\n\n// ============================================================\n// Shared Create Pipeline\n// ============================================================\n\n/**\n * The synchronous half of create preparation: kind resolution, Zod\n * validation, and date validation. Produces everything the async\n * constraint checks need, so batch preparation can validate every input\n * first and then prime the validation caches with batched reads before\n * running {@link finishNodeCreatePreparation} per row.\n */\n/**\n * Internal create options threaded from operations that validated props\n * BEFORE calling into the create path. Never exposed on the public store\n * surface.\n */\ntype NodeCreateInternalOptions = Readonly<{\n /** `input.props` is already the output of `validateNodeProps`. */\n propsPreValidated?: boolean;\n}>;\n\nexport type NodeCreateDraft = Readonly<{\n kind: string;\n id: string;\n nodeKind: NodeType;\n uniqueConstraints: readonly UniqueConstraint[];\n validatedProps: Record<string, unknown>;\n validFrom: string | undefined;\n validTo: string | undefined;\n}>;\n\nfunction draftNodeCreate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n id: string,\n options?: NodeCreateInternalOptions,\n): NodeCreateDraft {\n const kind = input.kind;\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n\n // getOrCreate / findByConstraint variants validate props up front (the\n // key computation needs the PARSED shape), then hand the validated\n // object here — re-running the full Zod parse on it would double the\n // validation cost of every create leg for no additional safety (hooks\n // wrap the transaction and cannot transform inputs in between).\n const validatedProps =\n options?.propsPreValidated === true ?\n input.props\n : validateNodeProps(nodeKind.schema, input.props, {\n kind,\n operation: \"create\",\n });\n\n return {\n kind,\n id,\n nodeKind,\n uniqueConstraints: registration.unique ?? [],\n validatedProps,\n validFrom: validateOptionalCanonicalIsoDate(input.validFrom, \"validFrom\"),\n validTo: validateOptionalCanonicalIsoDate(input.validTo, \"validTo\"),\n };\n}\n\n/** The async half: existence, disjointness, and uniqueness checks. */\nasync function finishNodeCreatePreparation<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n draft: NodeCreateDraft,\n backend: GraphBackend | TransactionBackend,\n): Promise<NodeCreatePrepared> {\n const { kind, id, validatedProps, uniqueConstraints } = draft;\n\n const existingNode = await backend.getNode(ctx.graphId, kind, id);\n if (existingNode && !existingNode.deleted_at) {\n throw createNodeAlreadyExistsError(kind, id);\n }\n\n const constraintContext: ConstraintContext = {\n graphId: ctx.graphId,\n registry: ctx.registry,\n backend,\n };\n await checkDisjointnessConstraint(constraintContext, kind, id);\n\n await checkUniquenessConstraints(\n createUniquenessContext(ctx.graphId, ctx.registry, backend),\n kind,\n id,\n validatedProps,\n uniqueConstraints,\n );\n\n return {\n kind,\n id,\n nodeKind: draft.nodeKind,\n validatedProps,\n uniqueConstraints,\n insertParams: buildInsertNodeParams(\n ctx.graphId,\n kind,\n id,\n validatedProps,\n draft.validFrom,\n draft.validTo,\n ),\n };\n}\n\nasync function validateAndPrepareNodeCreate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n id: string,\n backend: GraphBackend | TransactionBackend,\n options?: NodeCreateInternalOptions,\n): Promise<NodeCreatePrepared> {\n return finishNodeCreatePreparation(\n ctx,\n draftNodeCreate(ctx, input, id, options),\n backend,\n );\n}\n\n/**\n * Batched {@link finalizeNodeCreate}: applies every prepared create's\n * side effects through the batch pipeline (one uniqueness batch, one\n * fulltext/embedding batch per kind) instead of a per-row statement fan.\n */\nasync function finalizeNodeCreateBatch<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n preparedCreates: readonly NodeCreatePrepared[],\n backend: GraphBackend | TransactionBackend,\n lock: GraphWriteLock,\n): Promise<void> {\n await applyNodeInsertSideEffectsBatch(\n createNodeWriteContext(ctx.graphId, ctx.registry, lock),\n preparedCreates.map((prepared) => ({\n kind: prepared.kind,\n id: prepared.id,\n schema: prepared.nodeKind.schema,\n props: prepared.validatedProps,\n uniqueConstraints: prepared.uniqueConstraints,\n })),\n backend,\n );\n}\n\nasync function finalizeNodeCreate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n prepared: NodeCreatePrepared,\n backend: GraphBackend | TransactionBackend,\n lock: GraphWriteLock,\n): Promise<void> {\n await applyNodeInsertSideEffects(\n createNodeWriteContext(ctx.graphId, ctx.registry, lock),\n {\n kind: prepared.kind,\n id: prepared.id,\n schema: prepared.nodeKind.schema,\n props: prepared.validatedProps,\n uniqueConstraints: prepared.uniqueConstraints,\n },\n backend,\n );\n}\n\n// ============================================================\n// Shared Update Pipeline\n//\n// executeNodeUpdate wraps this in operation hooks.\n// executeNodeUpsertUpdate calls it directly (no hooks) for\n// getOrCreate resurrections.\n// ============================================================\n\n/**\n * The exact props an update would persist: the caller's partial input merged\n * over the current props and run through the kind's Zod schema (defaults\n * applied, values normalized). Also returns the resolved registration so\n * callers need not look it up again. Operates on PARSED props so both the write\n * path (which parses the row) and the coalesce dirty-check (which may compare\n * against a batch-local running value, never a row) share one validation.\n */\nfunction computeNodeUpdate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n id: string,\n existingProps: Record<string, unknown>,\n inputProps: Partial<Record<string, unknown>>,\n) {\n const registration = getNodeRegistration(ctx.graph, kind);\n const validatedProps = validateNodeProps(\n registration.type.schema,\n { ...existingProps, ...inputProps },\n { kind, operation: \"update\", id },\n );\n return { registration, validatedProps };\n}\n\n/**\n * Row-based wrapper over {@link computeNodeUpdate} for the write path. Reads the\n * kind/id off the row (a `getNode(kind, id)` result always carries the\n * requested kind), matching {@link resolveEdgeUpdateProps}.\n */\nfunction resolveNodeUpdateProps<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n existing: Pick<NodeRow, \"kind\" | \"id\" | \"props\">,\n inputProps: Partial<Record<string, unknown>>,\n) {\n const existingProps = rowPropsToObject(existing.props);\n const { registration, validatedProps } = computeNodeUpdate(\n ctx,\n existing.kind,\n existing.id,\n existingProps,\n inputProps,\n );\n return { registration, existingProps, validatedProps };\n}\n\n/**\n * The coalesce dirty-check: returns the props an `upsertById` would persist and\n * whether they equal `existingProps` (so the write can be skipped). Compares on\n * the storage-normalized representation (validated, key-order-independent), so\n * it answers exactly \"would the persisted JSON differ?\". `existingProps` is the\n * PARSED current props — the row's, or the batch-local running value for a\n * repeated id in `bulkUpsertById`.\n */\nexport function nodeUpsertDirtyCheck<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n id: string,\n existingProps: Record<string, unknown>,\n inputProps: Record<string, unknown>,\n): UpsertDirtyCheck {\n const { validatedProps } = computeNodeUpdate(\n ctx,\n kind,\n id,\n existingProps,\n inputProps,\n );\n return {\n validatedProps,\n unchanged: canonicalEqual(validatedProps, existingProps),\n };\n}\n\nasync function performNodeUpdate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n lock: GraphWriteLock,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Node> {\n const { kind, id } = input;\n\n const existing = await backend.getNode(ctx.graphId, kind, id);\n if (!existing) throw new NodeNotFoundError(kind, id);\n\n const { registration, validatedProps } = resolveNodeUpdateProps(\n ctx,\n existing,\n input.props,\n );\n const nodeKind = registration.type;\n\n const validTo = validateOptionalCanonicalIsoDate(input.validTo, \"validTo\");\n\n const writeContext = createNodeWriteContext(ctx.graphId, ctx.registry, lock);\n const shared = {\n schema: nodeKind.schema,\n validatedProps,\n uniqueConstraints: registration.unique ?? [],\n ...(validTo !== undefined && { validTo }),\n };\n\n // A resurrecting upsert (clearDeleted) may target a tombstoned row; a plain\n // update must prove the row live — see NodeUpdateTarget.\n if (options?.clearDeleted) {\n const row = await applyNodeUpdate(\n writeContext,\n { ...shared, existing, clearDeleted: true },\n backend,\n );\n return rowToNode(row);\n }\n\n if (!isLiveNodeRow(existing)) throw new NodeNotFoundError(kind, id);\n const row = await applyNodeUpdate(\n writeContext,\n { ...shared, existing },\n backend,\n );\n return rowToNode(row);\n}\n\n// ============================================================\n// Shared Batch Preparation\n//\n// Both returning and non-returning batch creates share the same\n// validate-and-register loop. This extracts it.\n// ============================================================\n\n/**\n * Primes the batch validation caches with batched reads: one `getNodes`\n * per kind for existence probes and one `checkUniqueBatch` per\n * (constraint, kind) for uniqueness pre-checks. The per-row checks in\n * {@link finishNodeCreatePreparation} then hit memory instead of issuing\n * one probe per row. Backends without the batch primitives skip priming\n * and keep the per-row fallback.\n */\nexport async function primeBatchValidationCaches(\n ctx: Readonly<{ graphId: string; registry: KindRegistry }>,\n drafts: readonly NodeCreateDraft[],\n backend: GraphBackend | TransactionBackend,\n seams: Readonly<{\n seedNodeRow: (kind: string, id: string, row: CachedNodeRow) => void;\n seedUniqueRow: (\n kind: string,\n constraintName: string,\n key: string,\n row: CachedUniqueRow,\n ) => void;\n }>,\n): Promise<void> {\n if (backend.getNodes !== undefined) {\n const idsByKind = new Map<string, Set<string>>();\n for (const draft of drafts) {\n const ids = idsByKind.get(draft.kind) ?? new Set<string>();\n ids.add(draft.id);\n idsByKind.set(draft.kind, ids);\n }\n for (const [kind, ids] of idsByKind) {\n const orderedIds = [...ids];\n const rows = await backend.getNodes(ctx.graphId, kind, orderedIds);\n const rowsById = new Map(rows.map((row) => [row.id, row]));\n for (const id of orderedIds) {\n seams.seedNodeRow(kind, id, rowsById.get(id));\n }\n }\n }\n\n if (backend.checkUniqueBatch !== undefined) {\n interface ProbeGroup {\n nodeKind: string;\n constraintName: string;\n keys: Set<string>;\n }\n const groups = new Map<string, ProbeGroup>();\n for (const draft of drafts) {\n for (const constraint of draft.uniqueConstraints) {\n if (!checkWherePredicate(constraint, draft.validatedProps)) continue;\n const key = computeUniqueKey(\n draft.validatedProps,\n constraint.fields,\n constraint.collation,\n );\n const kindsToCheck = getKindsForUniquenessCheck(\n draft.kind,\n constraint.scope,\n ctx.registry,\n );\n for (const kindToCheck of kindsToCheck) {\n const groupKey = kindToCheck + CACHE_KEY_SEPARATOR + constraint.name;\n const group = groups.get(groupKey) ?? {\n nodeKind: kindToCheck,\n constraintName: constraint.name,\n keys: new Set<string>(),\n };\n group.keys.add(key);\n groups.set(groupKey, group);\n }\n }\n }\n for (const group of groups.values()) {\n const orderedKeys = [...group.keys];\n const rows = await backend.checkUniqueBatch({\n graphId: ctx.graphId,\n nodeKind: group.nodeKind,\n constraintName: group.constraintName,\n keys: orderedKeys,\n });\n const rowsByKey = new Map(rows.map((row) => [row.key, row]));\n for (const key of orderedKeys) {\n seams.seedUniqueRow(\n group.nodeKind,\n group.constraintName,\n key,\n rowsByKey.get(key),\n );\n }\n }\n }\n}\n\nasync function prepareBatchCreates<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n options?: NodeCreateInternalOptions,\n): Promise<{\n preparedCreates: NodeCreatePrepared[];\n batchInsertParams: InsertNodeParams[];\n}> {\n const {\n backend: validationBackend,\n registerPendingNode,\n registerPendingUniqueEntries,\n seedNodeRow,\n seedUniqueRow,\n } = createNodeBatchValidationBackend(ctx.graphId, ctx.registry, backend);\n\n // Pass 1 (synchronous): validate every input and assign ids. This\n // surfaces a later row's validation error before an earlier row's\n // constraint error — both fail the whole batch, so ordering across\n // error categories is not part of the contract.\n const drafts = inputs.map((input) =>\n draftNodeCreate(ctx, input, input.id ?? generateId(), options),\n );\n\n await primeBatchValidationCaches(ctx, drafts, backend, {\n seedNodeRow,\n seedUniqueRow,\n });\n\n // Pass 2: per-row constraint checks against the primed caches, in input\n // order, registering pendings so later rows see earlier ones.\n const preparedCreates: NodeCreatePrepared[] = [];\n for (const draft of drafts) {\n const prepared = await finishNodeCreatePreparation(\n ctx,\n draft,\n validationBackend,\n );\n preparedCreates.push(prepared);\n registerPendingNode(prepared.insertParams);\n registerPendingUniqueEntries(\n prepared.kind,\n prepared.id,\n prepared.validatedProps,\n prepared.uniqueConstraints,\n );\n }\n\n const batchInsertParams = preparedCreates.map(\n (prepared) => prepared.insertParams,\n );\n\n return { preparedCreates, batchInsertParams };\n}\n\n// ============================================================\n// Shared Constraint Lookup\n//\n// Both single and bulk find/getOrCreate operations need to look up\n// unique constraint entries across all applicable kinds.\n// ============================================================\n\nasync function findUniqueRowAcrossKinds(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n constraintName: string,\n key: string,\n kindsToCheck: readonly string[],\n includeDeleted: boolean,\n): Promise<\n | { node_id: string; concrete_kind: string; deleted_at: string | undefined }\n | undefined\n> {\n for (const kindToCheck of kindsToCheck) {\n const row = await backend.checkUnique({\n graphId,\n nodeKind: kindToCheck,\n constraintName,\n key,\n includeDeleted,\n });\n if (row !== undefined) return row;\n }\n return undefined;\n}\n\ninterface UniqueMatchRow {\n node_id: string;\n concrete_kind: string;\n deleted_at: string | undefined;\n}\n\nasync function batchCheckUniqueAcrossKinds(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n constraintName: string,\n uniqueKeys: readonly string[],\n kindsToCheck: readonly string[],\n includeDeleted: boolean,\n): Promise<Map<string, UniqueMatchRow>> {\n const existingByKey = new Map<string, UniqueMatchRow>();\n\n for (const kindToCheck of kindsToCheck) {\n if (backend.checkUniqueBatch === undefined) {\n for (const key of uniqueKeys) {\n if (existingByKey.has(key)) continue;\n const row = await backend.checkUnique({\n graphId,\n nodeKind: kindToCheck,\n constraintName,\n key,\n includeDeleted,\n });\n if (row !== undefined) {\n existingByKey.set(row.key, row);\n }\n }\n } else {\n const rows = await backend.checkUniqueBatch({\n graphId,\n nodeKind: kindToCheck,\n constraintName,\n keys: uniqueKeys,\n includeDeleted,\n });\n for (const row of rows) {\n if (!existingByKey.has(row.key)) {\n existingByKey.set(row.key, row);\n }\n }\n }\n }\n\n return existingByKey;\n}\n\n// ============================================================\n// Node Create Operations\n// ============================================================\n\nasync function executeNodeCreateInternal<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ returnRow?: boolean }> & NodeCreateInternalOptions,\n): Promise<Node | undefined> {\n const kind = input.kind;\n const id = input.id ?? generateId();\n const opContext = ctx.createOperationContext(\"create\", \"node\", kind, id);\n const shouldReturnRow = options?.returnRow ?? true;\n\n return runHookedWriteOperation(\n ctx,\n opContext,\n backend,\n async (target, lock) => {\n const prepared = await validateAndPrepareNodeCreate(\n ctx,\n input,\n id,\n target,\n options,\n );\n\n let row: BackendNodeRow | undefined;\n if (shouldReturnRow) {\n row = await target.insertNode(prepared.insertParams);\n } else {\n await runInsertNoReturn(\n nodeInsertDispatch(target),\n prepared.insertParams,\n );\n }\n\n await finalizeNodeCreate(ctx, prepared, target, lock);\n\n if (row === undefined) return;\n return rowToNode(row);\n },\n );\n}\n\nexport async function executeNodeCreate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: NodeCreateInternalOptions,\n): Promise<Node> {\n const result = await executeNodeCreateInternal(ctx, input, backend, {\n returnRow: true,\n ...options,\n });\n if (!result) {\n throw new DatabaseOperationError(\n \"Node create failed: expected created node row\",\n { operation: \"insert\", entity: \"node\" },\n );\n }\n return result;\n}\n\nexport async function executeNodeCreateNoReturn<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: CreateNodeInput,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n await executeNodeCreateInternal(ctx, input, backend, { returnRow: false });\n}\n\n/**\n * Executes batched node creates without returning inserted node payloads.\n *\n * Note: `withOperationHooks` is intentionally skipped for batch throughput.\n * Per-item hooks would negate the performance benefit of batching.\n */\nexport async function executeNodeCreateNoReturnBatch<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n if (inputs.length === 0) return;\n\n await runInWriteTransaction(ctx, backend, async (target, lock) => {\n const { preparedCreates, batchInsertParams } = await prepareBatchCreates(\n ctx,\n inputs,\n target,\n );\n\n await runInsertBatch(nodeInsertDispatch(target), batchInsertParams);\n\n await finalizeNodeCreateBatch(ctx, preparedCreates, target, lock);\n });\n}\n\n/**\n * Executes batched node creates and returns the inserted node payloads.\n *\n * Uses batch validation caching and a single multi-row INSERT with RETURNING\n * when the backend supports it. Falls back to sequential inserts otherwise.\n *\n * Note: `withOperationHooks` is intentionally skipped for batch throughput.\n * Per-item hooks would negate the performance benefit of batching.\n */\nexport async function executeNodeCreateBatch<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n options?: NodeCreateInternalOptions,\n): Promise<readonly Node[]> {\n if (inputs.length === 0) return [];\n\n return runInWriteTransaction(ctx, backend, async (target, lock) => {\n const { preparedCreates, batchInsertParams } = await prepareBatchCreates(\n ctx,\n inputs,\n target,\n options,\n );\n\n const rows = await runInsertBatchReturning(\n nodeInsertDispatch(target),\n batchInsertParams,\n );\n\n await finalizeNodeCreateBatch(ctx, preparedCreates, target, lock);\n\n return rows.map((row) => rowToNode(row));\n });\n}\n\n// ============================================================\n// Node Update Operations\n// ============================================================\n\nexport async function executeNodeUpdate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Node> {\n const opContext = ctx.createOperationContext(\n \"update\",\n \"node\",\n input.kind,\n input.id,\n );\n return runHookedWriteOperation(ctx, opContext, backend, (target, lock) =>\n performNodeUpdate(ctx, input, target, lock, options),\n );\n}\n\n/**\n * Executes an atomic, set-based update of current nodes. The backend returns\n * every after-image so the Store can validate the complete rows before\n * rebuilding all derived sidecars inside the same transaction.\n */\nexport async function executeNodeUpdateWhere<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n inputPatch: Record<string, unknown>,\n candidateIds: CompiledSelectSql,\n candidateIdColumn: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<Readonly<{ affectedCount: number }>> {\n const registration = getNodeRegistration(ctx.graph, kind);\n const schema = registration.type.schema;\n const uniqueConstraints = registration.unique ?? [];\n\n if (!backend.capabilities.transactions) {\n throw new ConfigurationError(\n \"updateWhere() requires a transactional backend so validation and sidecars are atomic\",\n { code: \"SET_UPDATE_TRANSACTIONS_REQUIRED\", kind },\n );\n }\n if (backend.updateNodeSet === undefined) {\n throw new ConfigurationError(\n \"This backend does not support set-based node updates\",\n { code: \"SET_UPDATE_UNSUPPORTED\", kind },\n );\n }\n if (Object.keys(inputPatch).length === 0) {\n throw new ValidationError(\"updateWhere() patch must not be empty\", {\n entityType: \"node\",\n kind,\n operation: \"update\",\n issues: [{ path: \"patch\", message: \"Provide at least one property\" }],\n });\n }\n const unknownProperty = Object.keys(inputPatch).find(\n (property) => !Object.hasOwn(schema.shape, property),\n );\n if (unknownProperty !== undefined) {\n throw new ValidationError(\n `Unknown ${kind} property in updateWhere() patch: ${unknownProperty}`,\n {\n entityType: \"node\",\n kind,\n operation: \"update\",\n issues: [\n {\n path: unknownProperty,\n message: \"Property is not declared by the node schema\",\n },\n ],\n },\n );\n }\n\n const parsedPatch = validateNodeProps(schema.partial(), inputPatch, {\n kind,\n operation: \"update\",\n });\n const patch: Record<string, JsonValue> = {};\n const unsetProperties: string[] = [];\n for (const [property, value] of Object.entries(parsedPatch)) {\n if (value === undefined) {\n unsetProperties.push(property);\n continue;\n }\n assertJsonValue(value, property, `Node \"${kind}\" updateWhere patch`);\n patch[property] = value as JsonValue;\n }\n if (Object.keys(patch).length === 0 && unsetProperties.length === 0) {\n throw new ValidationError(\n \"updateWhere() patch has no recognized properties\",\n {\n entityType: \"node\",\n kind,\n operation: \"update\",\n issues: [\n { path: \"patch\", message: \"Provide a declared node property\" },\n ],\n },\n );\n }\n\n if (\n uniqueConstraints.length > 0 &&\n (backend.hardDeleteUniquesByNodeIds === undefined ||\n backend.insertUniqueBatch === undefined ||\n backend.checkUniqueBatch === undefined)\n ) {\n throw new ConfigurationError(\n \"updateWhere() requires batched uniqueness sidecar operations for constrained nodes\",\n { code: \"SET_UPDATE_UNIQUENESS_UNSUPPORTED\", kind },\n );\n }\n if (\n getSearchableFields(schema).length > 0 &&\n (backend.upsertFulltext === undefined ||\n backend.deleteFulltext === undefined ||\n backend.upsertFulltextBatch === undefined ||\n backend.deleteFulltextBatch === undefined)\n ) {\n throw new ConfigurationError(\n \"updateWhere() requires batched fulltext sidecar operations for searchable nodes\",\n { code: \"SET_UPDATE_FULLTEXT_UNSUPPORTED\", kind },\n );\n }\n if (\n getEmbeddingFields(schema).length > 0 &&\n (backend.upsertEmbedding === undefined ||\n backend.deleteEmbedding === undefined ||\n backend.upsertEmbeddingBatch === undefined ||\n backend.deleteEmbeddingBatch === undefined)\n ) {\n throw new ConfigurationError(\n \"updateWhere() requires batched vector sidecar operations for embedded nodes\",\n { code: \"SET_UPDATE_VECTOR_UNSUPPORTED\", kind },\n );\n }\n\n const hookContext = ctx.createBulkOperationContext(\"updateWhere\", kind);\n return ctx.withBulkOperationHooks(hookContext, () =>\n runInWriteTransaction(\n ctx,\n backend,\n async (target, lock) => {\n const updateNodeSet = target.updateNodeSet;\n if (updateNodeSet === undefined) {\n throw new ConfigurationError(\n \"The transaction backend does not support set-based node updates\",\n { code: \"SET_UPDATE_UNSUPPORTED\", kind },\n );\n }\n const hardDeleteUniquesByNodeIds = target.hardDeleteUniquesByNodeIds;\n if (\n uniqueConstraints.length > 0 &&\n (hardDeleteUniquesByNodeIds === undefined ||\n target.insertUniqueBatch === undefined ||\n target.checkUniqueBatch === undefined)\n ) {\n throw new ConfigurationError(\n \"The transaction backend lacks batched uniqueness operations\",\n { code: \"SET_UPDATE_UNIQUENESS_UNSUPPORTED\", kind },\n );\n }\n if (\n getSearchableFields(schema).length > 0 &&\n (target.upsertFulltext === undefined ||\n target.deleteFulltext === undefined ||\n target.upsertFulltextBatch === undefined ||\n target.deleteFulltextBatch === undefined)\n ) {\n throw new ConfigurationError(\n \"The transaction backend lacks batched fulltext operations\",\n { code: \"SET_UPDATE_FULLTEXT_UNSUPPORTED\", kind },\n );\n }\n if (\n getEmbeddingFields(schema).length > 0 &&\n (target.upsertEmbedding === undefined ||\n target.deleteEmbedding === undefined ||\n target.upsertEmbeddingBatch === undefined ||\n target.deleteEmbeddingBatch === undefined)\n ) {\n throw new ConfigurationError(\n \"The transaction backend lacks batched vector operations\",\n { code: \"SET_UPDATE_VECTOR_UNSUPPORTED\", kind },\n );\n }\n const result = await updateNodeSet({\n graphId: ctx.graphId,\n kind,\n patch,\n unsetProperties,\n candidateIds,\n candidateIdColumn,\n });\n if (result.affectedCount === 0) return { affectedCount: 0 };\n\n const sidecarItems = result.rows.map((row) => {\n const props = rowPropsToObject(row.props);\n const validatedProps = validateNodeProps(schema, props, {\n kind,\n operation: \"update\",\n id: row.id,\n });\n if (!canonicalEqual(validatedProps, props)) {\n throw new ValidationError(\n `Set update would persist a non-canonical ${kind} row`,\n {\n entityType: \"node\",\n kind,\n operation: \"update\",\n id: row.id,\n issues: [\n {\n path: \"props\",\n message: \"The complete row requires schema normalization\",\n },\n ],\n },\n );\n }\n return {\n kind,\n id: row.id,\n schema,\n props: validatedProps,\n uniqueConstraints,\n };\n });\n\n if (uniqueConstraints.length > 0) {\n const affectedIds = new Set(result.rows.map((row) => row.id));\n for (const constraint of uniqueConstraints) {\n const keyToId = new Map<string, string>();\n for (const item of sidecarItems) {\n if (!checkWherePredicate(constraint, item.props)) continue;\n const key = computeUniqueKey(\n item.props,\n constraint.fields,\n constraint.collation,\n );\n const priorId = keyToId.get(key);\n if (priorId !== undefined && priorId !== item.id) {\n throw new UniquenessError({\n constraintName: constraint.name,\n kind,\n existingId: priorId,\n newId: item.id,\n fields: constraint.fields,\n });\n }\n keyToId.set(key, item.id);\n }\n const keys = [...keyToId.keys()];\n if (keys.length === 0) continue;\n for (const kindToCheck of getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n )) {\n const existingRows = await requireDefined(\n target.checkUniqueBatch,\n )({\n graphId: ctx.graphId,\n nodeKind: kindToCheck,\n constraintName: constraint.name,\n keys,\n });\n for (const existing of existingRows) {\n if (\n existing.concrete_kind === kind &&\n affectedIds.has(existing.node_id)\n ) {\n continue;\n }\n throw new UniquenessError({\n constraintName: constraint.name,\n kind: kindToCheck,\n existingId: existing.node_id,\n newId: requireDefined(keyToId.get(existing.key)),\n fields: constraint.fields,\n });\n }\n }\n }\n await requireDefined(hardDeleteUniquesByNodeIds)({\n graphId: ctx.graphId,\n concreteKind: kind,\n nodeIds: result.rows.map((row) => row.id),\n });\n }\n await applyNodeInsertSideEffectsBatch(\n createNodeWriteContext(ctx.graphId, ctx.registry, lock),\n sidecarItems,\n target,\n );\n return { affectedCount: result.affectedCount };\n },\n { didWrite: (result) => result.affectedCount > 0 },\n ),\n );\n}\n\n/**\n * Executes a node update for upsert — bypasses operation hooks\n * and allows updating soft-deleted nodes when clearDeleted is set.\n */\nexport async function executeNodeUpsertUpdate<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Node> {\n return runInWriteTransaction(ctx, backend, (target, lock) =>\n performNodeUpdate(ctx, input, target, lock, options),\n );\n}\n\n// ============================================================\n// Node Delete Operations\n// ============================================================\n\nexport async function executeNodeDelete<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n id: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n // Gate outside hooks and transaction (matching edge deletes): an absent or\n // already-tombstoned node is a no-op, so it neither fires hooks nor opens a\n // write transaction (empty transactions are costly on libsql). The cascade\n // re-reads inside the transaction, so a node concurrently deleted between\n // this gate and the write lock is still handled correctly.\n const gate = await backend.getNode(ctx.graphId, kind, id);\n if (!gate || gate.deleted_at) return;\n\n const opContext = ctx.createOperationContext(\"delete\", \"node\", kind, id);\n\n return runHookedWriteOperation(\n ctx,\n opContext,\n backend,\n async (target, lock) => {\n const registration = getNodeRegistration(ctx.graph, kind);\n // This preflight is NOT removable round-trip fat: the soft-delete\n // pipeline consumes the pre-image (uniqueness entries are keyed by\n // props-derived constraint keys), and this in-transaction read is\n // the concurrency-correct source for it.\n const preflight = await target.getNode(ctx.graphId, kind, id);\n if (!preflight || !isLiveNodeRow(preflight)) return;\n\n // The cascade (connected edges, uniques, embeddings, fulltext, node) is\n // not individually atomic, so it runs in one write transaction. Under\n // recorded-time capture this also collapses the cascade into a single\n // recorded commit instant instead of one instant per sub-write.\n await applyNodeSoftDelete(\n createNodeWriteContext(ctx.graphId, ctx.registry, lock),\n {\n existing: preflight,\n schema: registration.type.schema,\n uniqueConstraints: registration.unique ?? [],\n onDelete: registration.onDelete,\n },\n target,\n );\n },\n );\n}\n\n/**\n * Executes a node hard delete operation (permanent removal).\n *\n * Unlike soft delete, this permanently removes the node and all\n * associated data (uniqueness entries, embeddings) from the database.\n */\nexport async function executeNodeHardDelete<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n id: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n // Gate outside hooks and transaction so an absent node neither fires hooks\n // nor opens an empty transaction (see executeNodeDelete). The cascade\n // re-reads inside the transaction.\n const gate = await backend.getNode(ctx.graphId, kind, id);\n if (!gate) return;\n\n const opContext = ctx.createOperationContext(\"delete\", \"node\", kind, id);\n\n return runHookedWriteOperation(\n ctx,\n opContext,\n backend,\n async (target, lock) => {\n const registration = getNodeRegistration(ctx.graph, kind);\n // No in-transaction preflight (unlike soft delete, whose pipeline\n // consumes the pre-image for uniqueness-key cleanup): every hard\n // cascade member is id-keyed and idempotent — the delete-behavior\n // check re-reads edges itself, `hardDeleteNode` deletes by primary\n // key, and embeddings clean up by id — so a node concurrently\n // removed between the gate and the write lock makes each statement\n // a 0-row no-op.\n\n // The cascade (edges, node, embeddings) is not individually atomic, so\n // it runs in one write transaction. Embeddings live in strategy-owned\n // per-`(kind, field)` tables, so they are cleaned up here rather than\n // in the backend's graph-agnostic `hardDeleteNode` cascade.\n await applyNodeHardDelete(\n createNodeWriteContext(ctx.graphId, ctx.registry, lock),\n {\n kind,\n id,\n schema: registration.type.schema,\n onDelete: registration.onDelete,\n },\n target,\n );\n },\n );\n}\n\n// ============================================================\n// Get-Or-Create Operations\n// ============================================================\n\nexport async function executeNodeGetOrCreateByConstraint<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n constraintName: string,\n props: Record<string, unknown>,\n backend: GraphBackend | TransactionBackend,\n options?: NodeGetOrCreateByConstraintOptions,\n): Promise<Readonly<{ node: Node; action: GetOrCreateAction }>> {\n const ifExists = options?.ifExists ?? \"return\";\n\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n const validatedProps = validateNodeProps(nodeKind.schema, props, {\n kind,\n operation: \"create\",\n });\n\n const constraint = resolveConstraint(ctx.graph, kind, constraintName);\n\n if (!checkWherePredicate(constraint, validatedProps)) {\n const node = await executeNodeCreate(\n ctx,\n { kind, props: validatedProps },\n backend,\n { propsPreValidated: true },\n );\n return { node, action: \"created\" };\n }\n\n const key = computeUniqueKey(\n validatedProps,\n constraint.fields,\n constraint.collation,\n );\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n // The probe runs outside any transaction (the found path is a pure read),\n // and each write leg opens its own hooked transaction. A concurrent create\n // can therefore reserve the key between the probe and the create — that\n // surfaces as UniquenessError, and the caller retries the probe once to\n // converge on the row the winner created.\n async function attempt(): Promise<\n Readonly<{ node: Node; action: GetOrCreateAction }>\n > {\n const existingUniqueRow = await findUniqueRowAcrossKinds(\n backend,\n ctx.graphId,\n constraint.name,\n key,\n kindsToCheck,\n true,\n );\n\n if (existingUniqueRow === undefined) {\n const node = await executeNodeCreate(\n ctx,\n { kind, props: validatedProps },\n backend,\n { propsPreValidated: true },\n );\n return { node, action: \"created\" };\n }\n\n // Fetch using concrete_kind (may differ from requested kind\n // when scope is \"kindWithSubClasses\" and the match is on a sibling/parent kind)\n const existingRow = await backend.getNode(\n ctx.graphId,\n existingUniqueRow.concrete_kind,\n existingUniqueRow.node_id,\n );\n\n if (existingRow === undefined) {\n const node = await executeNodeCreate(\n ctx,\n { kind, props: validatedProps },\n backend,\n { propsPreValidated: true },\n );\n return { node, action: \"created\" };\n }\n\n const isSoftDeleted = existingRow.deleted_at !== undefined;\n\n if (isSoftDeleted || ifExists === \"update\") {\n const concreteKind = existingUniqueRow.concrete_kind;\n const node = await executeNodeUpsertUpdate(\n ctx,\n {\n kind: concreteKind,\n id: existingRow.id as UpdateNodeInput[\"id\"],\n props: validatedProps,\n },\n backend,\n { clearDeleted: isSoftDeleted },\n );\n return { node, action: isSoftDeleted ? \"resurrected\" : \"updated\" };\n }\n\n return { node: rowToNode(existingRow), action: \"found\" };\n }\n\n try {\n return await attempt();\n } catch (error) {\n if (!(error instanceof UniquenessError)) throw error;\n return attempt();\n }\n}\n\n// ============================================================\n// Find-By-Constraint Operations\n// ============================================================\n\nexport async function executeNodeFindByConstraint<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n constraintName: string,\n props: Record<string, unknown>,\n backend: GraphBackend | TransactionBackend,\n): Promise<Node | undefined> {\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n const validatedProps = validateNodeProps(nodeKind.schema, props, {\n kind,\n operation: \"create\",\n });\n\n const constraint = resolveConstraint(ctx.graph, kind, constraintName);\n if (!checkWherePredicate(constraint, validatedProps)) return undefined;\n\n const key = computeUniqueKey(\n validatedProps,\n constraint.fields,\n constraint.collation,\n );\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n const existingUniqueRow = await findUniqueRowAcrossKinds(\n backend,\n ctx.graphId,\n constraint.name,\n key,\n kindsToCheck,\n false,\n );\n\n if (existingUniqueRow === undefined) return undefined;\n\n const existingRow = await backend.getNode(\n ctx.graphId,\n existingUniqueRow.concrete_kind,\n existingUniqueRow.node_id,\n );\n\n if (existingRow === undefined || existingRow.deleted_at !== undefined)\n return undefined;\n\n return rowToNode(existingRow);\n}\n\n// ============================================================\n// Bulk Find-By-Constraint\n// ============================================================\n\n/**\n * Validates all items and computes unique constraint keys.\n * Shared by both bulk find and bulk getOrCreate.\n */\nfunction validateAndComputeKeys(\n nodeKind: NodeType,\n kind: string,\n constraint: UniqueConstraint,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n): { validatedProps: Record<string, unknown>; key: string | undefined }[] {\n const validated: {\n validatedProps: Record<string, unknown>;\n key: string | undefined;\n }[] = [];\n\n for (const item of items) {\n const validatedProps = validateNodeProps(nodeKind.schema, item.props, {\n kind,\n operation: \"create\",\n });\n const applies = checkWherePredicate(constraint, validatedProps);\n const key =\n applies ?\n computeUniqueKey(\n validatedProps,\n constraint.fields,\n constraint.collation,\n )\n : undefined;\n validated.push({ validatedProps, key });\n }\n\n return validated;\n}\n\nfunction collectUniqueKeys(\n validated: readonly { key: string | undefined }[],\n): string[] {\n return [\n ...new Set(\n validated\n .map((entry) => entry.key)\n .filter((key): key is string => key !== undefined),\n ),\n ];\n}\n\nexport async function executeNodeBulkFindByConstraint<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n constraintName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n): Promise<(Node | undefined)[]> {\n if (items.length === 0) return [];\n\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n const constraint = resolveConstraint(ctx.graph, kind, constraintName);\n\n const validated = validateAndComputeKeys(nodeKind, kind, constraint, items);\n const uniqueKeys = collectUniqueKeys(validated);\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n const existingByKey =\n uniqueKeys.length > 0 ?\n await batchCheckUniqueAcrossKinds(\n backend,\n ctx.graphId,\n constraint.name,\n uniqueKeys,\n kindsToCheck,\n false,\n )\n : new Map<string, { node_id: string; concrete_kind: string }>();\n\n // Assemble results, deduplicating keys seen within the batch\n const results: (Node | undefined)[] = Array.from({ length: items.length });\n const seenKeys = new Map<string, number>();\n\n for (const [index, { key }] of validated.entries()) {\n if (key === undefined) {\n results[index] = undefined;\n continue;\n }\n\n const previousIndex = seenKeys.get(key);\n if (previousIndex !== undefined) {\n results[index] = results[previousIndex];\n continue;\n }\n seenKeys.set(key, index);\n\n const existing = existingByKey.get(key);\n if (existing === undefined) {\n results[index] = undefined;\n continue;\n }\n\n const existingRow = await backend.getNode(\n ctx.graphId,\n existing.concrete_kind,\n existing.node_id,\n );\n\n if (existingRow === undefined || existingRow.deleted_at !== undefined) {\n results[index] = undefined;\n continue;\n }\n\n results[index] = rowToNode(existingRow);\n }\n\n return results;\n}\n\n// ============================================================\n// Bulk Find-By-Index\n// ============================================================\n\n/**\n * Resolves a declared node index by name, validating the kind first.\n *\n * @throws {KindNotFoundError} when the node kind is not registered\n * @throws {NodeIndexNotFoundError} when no node index of that name exists\n */\nfunction resolveNodeIndex<G extends GraphDef>(\n graph: G,\n kind: string,\n indexName: string,\n): NodeIndexDeclaration {\n getNodeRegistration(graph, kind);\n\n const declaration = graph.indexes?.find(\n (candidate) =>\n candidate.entity === \"node\" &&\n candidate.kind === kind &&\n candidate.name === indexName,\n );\n\n if (declaration?.entity !== \"node\") {\n throw new NodeIndexNotFoundError(indexName, kind);\n }\n\n // GIN-family indexes serve containment / substring predicates, not the\n // equality probes bulkFindByIndex compiles — targeting one here would\n // silently probe with the wrong extraction semantics.\n if (declaration.method !== undefined) {\n throw new ConfigurationError(\n `bulkFindByIndex cannot probe index \"${indexName}\" (method ` +\n `\"${declaration.method}\"): only btree indexes serve equality probes.`,\n { indexName, kind, method: declaration.method },\n );\n }\n\n return declaration;\n}\n\nconst INDEX_PROBE_EXPECTED_TYPEOF: Partial<Record<ValueType, string>> = {\n string: \"string\",\n number: \"number\",\n boolean: \"boolean\",\n};\n\n/**\n * Validates a single probe value against its declared index-field type.\n * Missing/null values are valid (null probes); only a present, scalar\n * value of the wrong type is rejected.\n */\nfunction validateIndexProbeValue(\n value: unknown,\n valueType: ValueType | undefined,\n pointer: JsonPointer,\n kind: string,\n): void {\n if (value === undefined || value === null) return;\n\n // Index keys are scalar; a non-scalar probe can't be bound and must fail\n // with a typed error rather than a cryptic driver bind error downstream.\n if (\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\" &&\n !(value instanceof Date)\n ) {\n throw indexProbeTypeError(\n pointer,\n kind,\n \"a scalar (string, number, boolean, or Date)\",\n value,\n );\n }\n\n if (valueType === \"date\") {\n if (value instanceof Date || typeof value === \"string\") return;\n throw indexProbeTypeError(\n pointer,\n kind,\n \"date (Date or ISO string)\",\n value,\n );\n }\n\n const expected = INDEX_PROBE_EXPECTED_TYPEOF[valueType ?? \"unknown\"];\n if (expected === undefined) return;\n if (typeof value !== expected) {\n throw indexProbeTypeError(pointer, kind, expected, value);\n }\n}\n\nfunction indexProbeTypeError(\n pointer: JsonPointer,\n kind: string,\n expected: string,\n value: unknown,\n): ValidationError {\n return new ValidationError(\n `Index probe value for \"${pointer}\" on node kind \"${kind}\" has an incompatible type`,\n {\n entityType: \"node\",\n kind,\n issues: [\n {\n path: pointer,\n message: `Expected ${expected}, received ${typeof value}`,\n code: \"invalid_type\",\n },\n ],\n },\n );\n}\n\n/** Coerces a non-null probe value into a driver-bindable scalar. */\nfunction coerceIndexProbeBind(\n value: unknown,\n adapter: DialectAdapter,\n): unknown {\n return adapter.bindValue(normalizeProbeScalar(value as ProbeScalar));\n}\n\ntype ProbeScalar = string | number | boolean | Date;\n\n/**\n * Canonical scalar form of a validated probe value, shared by the dedup key\n * and the bound SQL value so the two can never drift (a Date and its ISO\n * string normalize identically — and produce identical predicates).\n */\nfunction normalizeProbeScalar(value: ProbeScalar): string | number | boolean {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nconst PROBE_NULL_TAG = 0;\nconst PROBE_VALUE_TAG = 1;\n\n/**\n * Stable dedup key for a probe tuple. Each slot is tagged so a null/undefined\n * value can never collide with a string that happens to equal a sentinel -\n * null maps to [0], a present scalar to [1, normalized].\n */\nfunction canonicalIndexProbeKey(probe: readonly unknown[]): string {\n return JSON.stringify(\n probe.map((value) =>\n value === undefined || value === null ?\n [PROBE_NULL_TAG]\n : [PROBE_VALUE_TAG, normalizeProbeScalar(value as ProbeScalar)],\n ),\n );\n}\n\n/**\n * Batched candidate retrieval against a declared node index.\n *\n * Emits a single query against the nodes table: each input's indexed-field\n * values become a probe predicate (null-safe equality, reusing the index's\n * own extraction expressions so the planner can use the physical index), and\n * a `CASE` selector tags each matched row with the deduped probe group it\n * satisfies. Rows are grouped back to input positions in order; each input's\n * candidate set is ordered by node id.\n */\nexport async function executeNodeBulkFindByIndex<G extends GraphDef>(\n ctx: NodeOperationContext<G>,\n kind: string,\n indexName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n options?: NodeBulkFindByIndexOptions,\n): Promise<Node[][]> {\n if (items.length === 0) return [];\n\n const index = resolveNodeIndex(ctx.graph, kind, indexName);\n\n if (index.fields.length === 0) {\n throw new ConfigurationError(\n `bulkFindByIndex requires an index with at least one prop-based field on index \"${indexName}\" (node kind \"${kind}\")`,\n { indexName, kind },\n {\n suggestion:\n \"bulkFindByIndex probes by prop values from each item; an index declared with only keySystemColumns/coveringFields (no fields) has nothing to probe by.\",\n },\n );\n }\n\n // Date-typed lookup keys can't satisfy the cross-backend parity guarantee:\n // SQLite compares stored ISO text byte-wise while Postgres compares\n // timestamptz instants, so equal instants in different ISO forms diverge.\n // Declare the gap rather than return backend-dependent results.\n if (index.fieldValueTypes.includes(\"date\")) {\n throw new ConfigurationError(\n `bulkFindByIndex does not support date-typed key fields on index \"${indexName}\" (node kind \"${kind}\")`,\n { indexName, kind },\n {\n suggestion:\n \"Date index keys compare differently across SQLite and PostgreSQL. Use a string-encoded key field, or query date predicates via store.query(...).where(...).\",\n },\n );\n }\n\n const limitPerInput = options?.limitPerInput;\n if (\n limitPerInput !== undefined &&\n (!Number.isInteger(limitPerInput) || limitPerInput <= 0)\n ) {\n throw new ValidationError(\n \"bulkFindByIndex limitPerInput must be a positive integer\",\n {\n entityType: \"node\",\n kind,\n issues: [\n {\n path: \"limitPerInput\",\n message: `Expected a positive integer, received ${String(limitPerInput)}`,\n code: \"invalid_value\",\n },\n ],\n },\n );\n }\n\n const adapter = getDialect(backend.dialect);\n\n // 1. Extract + validate each input's indexed-field probe tuple.\n const probes: unknown[][] = items.map((item) =>\n index.fields.map((pointer, position) => {\n const value = resolveJsonPointer(item.props, pointer);\n validateIndexProbeValue(\n value,\n index.fieldValueTypes[position],\n pointer,\n kind,\n );\n return value;\n }),\n );\n\n // 2. Dedupe probe tuples; map each distinct tuple to its input positions.\n const groupByKey = new Map<string, number>();\n const groupProbes: unknown[][] = [];\n const groupToInputs: number[][] = [];\n for (const [inputIndex, probe] of probes.entries()) {\n const key = canonicalIndexProbeKey(probe);\n const existing = groupByKey.get(key);\n if (existing === undefined) {\n groupByKey.set(key, groupProbes.length);\n groupProbes.push(probe);\n groupToInputs.push([inputIndex]);\n continue;\n }\n groupToInputs[existing]?.push(inputIndex);\n }\n\n // 3. Build probe predicates shared by the CASE selector and WHERE filter.\n const schema =\n backend.tableNames ?\n createSqlSchema(backend.tableNames)\n : DEFAULT_SQL_SCHEMA;\n const compileContext: IndexCompilationContext = {\n dialect: backend.dialect,\n propsColumn: sql.raw(`\"props\"`),\n systemColumn: (column) => sql.raw(`\"${column}\"`),\n };\n const fieldKeys = compileNodeIndexFieldKeys(index, compileContext);\n\n const groupPredicates = groupProbes.map(\n (probe) =>\n sql`(${sql.join(\n fieldKeys.map((fieldKey, position) => {\n const value = probe[position];\n if (value === undefined || value === null) {\n return sql`${fieldKey} IS NULL`;\n }\n return adapter.nullSafeEquals(\n fieldKey,\n sql`${coerceIndexProbeBind(value, adapter)}`,\n );\n }),\n sql` AND `,\n )})`,\n );\n\n const caseBranches = groupPredicates.map(\n (predicate, group) => sql`WHEN ${predicate} THEN ${sql.raw(String(group))}`,\n );\n const probeIndexExpr = sql`CASE ${sql.join(caseBranches, sql` `)} ELSE NULL END`;\n\n const conditions: SqlFragment[] = [\n sql`\"graph_id\" = ${ctx.graphId}`,\n sql`\"kind\" = ${kind}`,\n sql`\"deleted_at\" IS NULL`,\n ];\n if (index.where !== undefined) {\n conditions.push(compileIndexWhere(compileContext, index.where));\n }\n conditions.push(sql`(${sql.join(groupPredicates, sql` OR `)})`);\n const whereClause = sql.join(conditions, sql` AND `);\n\n // The probe matching runs against the nodes table; rows are hydrated\n // separately via the backend's normalized node reads so the returned\n // shape is identical to every other node API (props/timestamp\n // normalization is backend-owned, not re-derived from raw driver rows).\n const probedSelect = sql`SELECT \"id\", ${probeIndexExpr} AS probe_idx FROM ${schema.nodesTable} WHERE ${whereClause}`;\n\n // limitPerInput caps each input's candidates per probe group. When the\n // backend supports window functions we cap in SQL (`ROW_NUMBER()`), which\n // also avoids transferring excess ids on low-selectivity keys. Otherwise we\n // degrade gracefully: fetch all matching ids and cap per group in JS before\n // hydration — the cap stays correct, only the id transfer is unbounded.\n const capInSql =\n limitPerInput !== undefined && backend.capabilities.windowFunctions;\n\n const query =\n capInSql ?\n sql`SELECT \"id\", probe_idx FROM (SELECT \"id\", probe_idx, ROW_NUMBER() OVER (PARTITION BY probe_idx ORDER BY \"id\") AS probe_rank FROM (${probedSelect}) AS probed) AS ranked WHERE probe_rank <= ${limitPerInput} ORDER BY probe_idx, \"id\"`\n : sql`${probedSelect} ORDER BY probe_idx, \"id\"`;\n\n // 4. Execute, hydrate matched nodes, and group back to input positions.\n const rawMatches = await backend.execute<ProbeMatch>(\n asCompiledRowsSql(query),\n );\n const matches =\n limitPerInput !== undefined && !capInSql ?\n capMatchesPerGroup(rawMatches, limitPerInput)\n : rawMatches;\n\n const nodesById = await hydrateNodesById(\n backend,\n ctx.graphId,\n kind,\n matches.map((match) => match.id),\n );\n\n const results: Node[][] = Array.from({ length: items.length }, () => []);\n for (const match of matches) {\n const node = nodesById.get(match.id);\n if (node === undefined) continue;\n const inputs = groupToInputs[match.probe_idx];\n if (inputs === undefined) continue;\n for (const inputIndex of inputs) {\n results[inputIndex]?.push(node);\n }\n }\n\n return results;\n}\n\ntype ProbeMatch = Readonly<{ id: string; probe_idx: number }>;\n\n/**\n * Caps matches to the first `limitPerInput` per probe group (the JS-side\n * equivalent of the `ROW_NUMBER()` window). Relies on `matches` already being\n * ordered by `(probe_idx, id)`, so the kept rows are the lowest ids per group.\n */\nfunction capMatchesPerGroup(\n matches: readonly ProbeMatch[],\n limitPerInput: number,\n): ProbeMatch[] {\n const perGroupCount = new Map<number, number>();\n const capped: ProbeMatch[] = [];\n for (const match of matches) {\n const count = perGroupCount.get(match.probe_idx) ?? 0;\n if (count >= limitPerInput) continue;\n perGroupCount.set(match.probe_idx, count + 1);\n capped.push(match);\n }\n return capped;\n}\n\n/** Hydrates live nodes by id via the backend's normalized node reads. */\nasync function hydrateNodesById(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kind: string,\n ids: readonly string[],\n): Promise<Map<string, Node>> {\n const rowsById = await getNodeRowsByIds(backend, graphId, kind, ids);\n const nodesById = new Map<string, Node>();\n for (const [id, row] of rowsById) {\n if (row.deleted_at !== undefined) continue;\n nodesById.set(id, rowToNode(row));\n }\n return nodesById;\n}\n\n// ============================================================\n// Bulk Get-Or-Create-By-Constraint\n// ============================================================\n\nexport async function executeNodeBulkGetOrCreateByConstraint<\n G extends GraphDef,\n>(\n ctx: NodeOperationContext<G>,\n kind: string,\n constraintName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n options?: NodeGetOrCreateByConstraintOptions,\n): Promise<Readonly<{ node: Node; action: GetOrCreateAction }>[]> {\n if (items.length === 0) return [];\n\n const ifExists = options?.ifExists ?? \"return\";\n const registration = getNodeRegistration(ctx.graph, kind);\n const nodeKind = registration.type;\n const constraint = resolveConstraint(ctx.graph, kind, constraintName);\n\n // Step 1: Validate all props and compute keys\n const validated = validateAndComputeKeys(nodeKind, kind, constraint, items);\n const uniqueKeys = collectUniqueKeys(validated);\n\n const kindsToCheck = getKindsForUniquenessCheck(\n kind,\n constraint.scope,\n ctx.registry,\n );\n\n // Step 2: Batch-check existing keys\n const existingByKey =\n uniqueKeys.length > 0 ?\n await batchCheckUniqueAcrossKinds(\n backend,\n ctx.graphId,\n constraint.name,\n uniqueKeys,\n kindsToCheck,\n true,\n )\n : new Map<\n string,\n {\n node_id: string;\n concrete_kind: string;\n deleted_at: string | undefined;\n }\n >();\n\n // Step 3: Partition into toCreate, toFetch, and duplicates\n const toCreate: { index: number; input: CreateNodeInput }[] = [];\n const toFetch: {\n index: number;\n nodeId: string;\n concreteKind: string;\n validatedProps: Record<string, unknown>;\n isSoftDeleted: boolean;\n }[] = [];\n const duplicateOf: { index: number; sourceIndex: number }[] = [];\n const seenKeys = new Map<string, number>();\n\n for (const [index, { validatedProps, key }] of validated.entries()) {\n if (key === undefined) {\n toCreate.push({ index, input: { kind, props: validatedProps } });\n continue;\n }\n\n const previousIndex = seenKeys.get(key);\n if (previousIndex !== undefined) {\n duplicateOf.push({ index, sourceIndex: previousIndex });\n continue;\n }\n\n seenKeys.set(key, index);\n\n const existing = existingByKey.get(key);\n if (existing === undefined) {\n toCreate.push({ index, input: { kind, props: validatedProps } });\n } else {\n toFetch.push({\n index,\n nodeId: existing.node_id,\n concreteKind: existing.concrete_kind,\n validatedProps,\n isSoftDeleted: existing.deleted_at !== undefined,\n });\n }\n }\n\n type Result = Readonly<{ node: Node; action: GetOrCreateAction }>;\n const results: Result[] = Array.from({ length: items.length });\n\n // Step 4: Execute creates\n if (toCreate.length > 0) {\n const createInputs = toCreate.map((entry) => entry.input);\n const createdNodes = await executeNodeCreateBatch(\n ctx,\n createInputs,\n backend,\n { propsPreValidated: true },\n );\n for (const [batchIndex, entry] of toCreate.entries()) {\n results[entry.index] = {\n node: requireDefined(createdNodes[batchIndex]),\n action: \"created\",\n };\n }\n }\n\n // Step 5: Handle existing nodes (fetch/update/resurrect)\n for (const entry of toFetch) {\n const { index, concreteKind, validatedProps, isSoftDeleted, nodeId } =\n entry;\n\n const existingRow = await backend.getNode(\n ctx.graphId,\n concreteKind,\n nodeId,\n );\n\n if (existingRow === undefined) {\n const node = await executeNodeCreate(\n ctx,\n { kind, props: validatedProps },\n backend,\n { propsPreValidated: true },\n );\n results[index] = { node, action: \"created\" };\n continue;\n }\n\n if (isSoftDeleted || ifExists === \"update\") {\n const node = await executeNodeUpsertUpdate(\n ctx,\n {\n kind: concreteKind,\n id: existingRow.id as UpdateNodeInput[\"id\"],\n props: validatedProps,\n },\n backend,\n { clearDeleted: isSoftDeleted },\n );\n results[index] = {\n node,\n action: isSoftDeleted ? \"resurrected\" : \"updated\",\n };\n } else {\n results[index] = { node: rowToNode(existingRow), action: \"found\" };\n }\n }\n\n // Step 6: Resolve within-batch duplicates by copying the first occurrence's result\n for (const { index, sourceIndex } of duplicateOf) {\n const sourceResult = requireDefined(results[sourceIndex]);\n results[index] = { node: sourceResult.node, action: \"found\" };\n }\n\n return results;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunk2VLBGQBY_cjs = require('./chunk-2VLBGQBY.cjs');
3
+ var chunkZI6VQSZA_cjs = require('./chunk-ZI6VQSZA.cjs');
4
4
 
5
5
  // src/schema/deserializer.ts
6
6
  function deserializeSchema(schema) {
@@ -40,7 +40,7 @@ function buildRegistryFromClosures(schema) {
40
40
  const edgeImplyingClosure = recordToMap(closures.edgeImplyingClosure);
41
41
  const nodeKinds = /* @__PURE__ */ new Map();
42
42
  const edgeKinds = /* @__PURE__ */ new Map();
43
- const registry = new chunk2VLBGQBY_cjs.KindRegistry(nodeKinds, edgeKinds, {
43
+ const registry = new chunkZI6VQSZA_cjs.KindRegistry(nodeKinds, edgeKinds, {
44
44
  subClassAncestors,
45
45
  subClassDescendants,
46
46
  broaderClosure,
@@ -54,7 +54,7 @@ function buildRegistryFromClosures(schema) {
54
54
  edgeImplicationsClosure,
55
55
  edgeImplyingClosure
56
56
  });
57
- chunk2VLBGQBY_cjs.validateImpliesEndpointCompatibility(
57
+ chunkZI6VQSZA_cjs.validateImpliesEndpointCompatibility(
58
58
  buildEdgeEndpointKinds(schema.edges),
59
59
  registry
60
60
  );
@@ -79,5 +79,5 @@ function simpleRecordToMap(record) {
79
79
  }
80
80
 
81
81
  exports.deserializeSchema = deserializeSchema;
82
- //# sourceMappingURL=chunk-2BIG7U6E.cjs.map
83
- //# sourceMappingURL=chunk-2BIG7U6E.cjs.map
82
+ //# sourceMappingURL=chunk-QC4MCOFV.cjs.map
83
+ //# sourceMappingURL=chunk-QC4MCOFV.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schema/deserializer.ts"],"names":["KindRegistry","validateImpli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P,KAAA,EACwC;AACxC,EAAA,MAAM,MAAA,uBAAa,GAAA,EAA+B;AAClD,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,GAAG,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAC/C,IAAA,MAAA,CAAO,GAAA,CAAI,MAAM,EAAE,IAAA,EAAM,IAAI,SAAA,EAAW,EAAA,EAAI,GAAA,CAAI,OAAA,EAAS,CAAA;AAAA,EAC3D;AACA,EAAA,OAAO,MAAA;AACT;AAKA,SAAS,YACP,MAAA,EAC0C;AAC1C,EAAA,MAAM,MAAA,uBAAa,GAAA,EAAyB;AAC5C,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,MAAM,KAAK,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,EAAG;AAClD,IAAA,MAAA,CAAO,GAAA,CAAI,GAAA,EAAK,IAAI,GAAA,CAAI,MAAM,CAAC,CAAA;AAAA,EACjC;AACA,EAAA,OAAO,MAAA;AACT;AAKA,SAAS,kBACP,MAAA,EAC6B;AAC7B,EAAA,OAAO,IAAI,GAAA,CAAI,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAC,CAAA;AACvC","file":"chunk-2BIG7U6E.cjs","sourcesContent":["/**\n * Schema deserializer for loading stored schemas.\n *\n * Reconstructs runtime objects from SerializedSchema.\n * Note: Zod schemas cannot be fully reconstructed from JSON Schema,\n * so this provides access to the serialized data for introspection.\n */\nimport { KindRegistry } from \"../registry/kind-registry\";\nimport {\n type EdgeEndpointKinds,\n validateImpliesEndpointCompatibility,\n} from \"../registry/validate-implies\";\nimport {\n type SerializedClosures,\n type SerializedEdgeDef,\n type SerializedMetaEdge,\n type SerializedNodeDef,\n type SerializedOntologyRelation,\n type SerializedSchema,\n} from \"./types\";\n\n// ============================================================\n// Deserialized Schema\n// ============================================================\n\n/**\n * A deserialized schema provides read-only access to schema metadata.\n *\n * Note: Unlike the original GraphDef, this does not include Zod schemas\n * since those cannot be reconstructed from JSON Schema. Use this for\n * introspection and metadata access only.\n */\nexport type DeserializedSchema = Readonly<{\n graphId: string;\n version: number;\n generatedAt: string;\n\n /** Get node definition by name */\n getNode: (name: string) => SerializedNodeDef | undefined;\n\n /** Get all node names */\n getNodeNames: () => readonly string[];\n\n /** Get edge definition by name */\n getEdge: (name: string) => SerializedEdgeDef | undefined;\n\n /** Get all edge names */\n getEdgeNames: () => readonly string[];\n\n /** Get meta-edge definition by name */\n getMetaEdge: (name: string) => SerializedMetaEdge | undefined;\n\n /** Get all meta-edge names */\n getMetaEdgeNames: () => readonly string[];\n\n /** Get all ontology relations */\n getRelations: () => readonly SerializedOntologyRelation[];\n\n /** Get precomputed closures */\n getClosures: () => SerializedClosures;\n\n /** Get graph defaults */\n getDefaults: () => SerializedSchema[\"defaults\"];\n\n /** Get the raw serialized schema */\n getRaw: () => SerializedSchema;\n\n /** Build a KindRegistry from the closures */\n buildRegistry: () => KindRegistry;\n}>;\n\n// ============================================================\n// Deserialization\n// ============================================================\n\n/**\n * Deserializes a SerializedSchema into a DeserializedSchema.\n *\n * @param schema - The serialized schema to deserialize\n * @returns A deserialized schema with accessor methods\n */\nexport function deserializeSchema(\n schema: SerializedSchema,\n): DeserializedSchema {\n const nodeNames = Object.keys(schema.nodes);\n const edgeNames = Object.keys(schema.edges);\n const metaEdgeNames = Object.keys(schema.ontology.metaEdges);\n\n return {\n graphId: schema.graphId,\n version: schema.version,\n generatedAt: schema.generatedAt,\n\n getNode: (name) => schema.nodes[name],\n getNodeNames: () => nodeNames,\n\n getEdge: (name) => schema.edges[name],\n getEdgeNames: () => edgeNames,\n\n getMetaEdge: (name) => schema.ontology.metaEdges[name],\n getMetaEdgeNames: () => metaEdgeNames,\n\n getRelations: () => schema.ontology.relations,\n getClosures: () => schema.ontology.closures,\n\n getDefaults: () => schema.defaults,\n getRaw: () => schema,\n\n buildRegistry: () => buildRegistryFromClosures(schema),\n };\n}\n\n// ============================================================\n// Registry Building\n// ============================================================\n\n/**\n * Builds a KindRegistry from serialized closures.\n *\n * This allows query execution without recomputing closures.\n */\nfunction buildRegistryFromClosures(schema: SerializedSchema): KindRegistry {\n const { closures } = schema.ontology;\n\n // Convert Record<string, string[]> back to Map<string, Set<string>>\n const subClassAncestors = recordToMap(closures.subClassAncestors);\n const subClassDescendants = recordToMap(closures.subClassDescendants);\n const broaderClosure = recordToMap(closures.broaderClosure);\n const narrowerClosure = recordToMap(closures.narrowerClosure);\n const equivalenceSets = recordToMap(closures.equivalenceSets);\n const partOfClosure = recordToMap(closures.partOfClosure);\n const hasPartClosure = recordToMap(closures.hasPartClosure);\n const iriToKind = simpleRecordToMap(closures.iriToKind);\n const disjointPairs = new Set(closures.disjointPairs);\n const edgeInverses = simpleRecordToMap(closures.edgeInverses);\n const edgeImplicationsClosure = recordToMap(closures.edgeImplicationsClosure);\n const edgeImplyingClosure = recordToMap(closures.edgeImplyingClosure);\n\n // Build empty node/edge kind maps (we don't have the actual Zod schemas)\n const nodeKinds = new Map();\n const edgeKinds = new Map();\n\n const registry = new KindRegistry(nodeKinds, edgeKinds, {\n subClassAncestors,\n subClassDescendants,\n broaderClosure,\n narrowerClosure,\n equivalenceSets,\n iriToKind,\n disjointPairs,\n partOfClosure,\n hasPartClosure,\n edgeInverses,\n edgeImplicationsClosure,\n edgeImplyingClosure,\n });\n\n validateImpliesEndpointCompatibility(\n buildEdgeEndpointKinds(schema.edges),\n registry,\n );\n\n return registry;\n}\n\n/**\n * Maps each edge kind's serialized definition to its domain/range kind\n * names, for `validateImpliesEndpointCompatibility`. A `Map` (rather than\n * the plain `schema.edges` object) so a lookup for an edge kind literally\n * named \"toString\" or another `Object.prototype` member can't resolve to\n * an inherited member instead of `undefined`.\n */\nfunction buildEdgeEndpointKinds(\n edges: Record<string, SerializedEdgeDef>,\n): ReadonlyMap<string, EdgeEndpointKinds> {\n const result = new Map<string, EdgeEndpointKinds>();\n for (const [kind, def] of Object.entries(edges)) {\n result.set(kind, { from: def.fromKinds, to: def.toKinds });\n }\n return result;\n}\n\n/**\n * Converts Record<string, string[]> to Map<string, Set<string>>.\n */\nfunction recordToMap(\n record: Record<string, readonly string[]>,\n): ReadonlyMap<string, ReadonlySet<string>> {\n const result = new Map<string, Set<string>>();\n for (const [key, values] of Object.entries(record)) {\n result.set(key, new Set(values));\n }\n return result;\n}\n\n/**\n * Converts Record<string, string> to Map<string, string>.\n */\nfunction simpleRecordToMap(\n record: Record<string, string>,\n): ReadonlyMap<string, string> {\n return new Map(Object.entries(record));\n}\n"]}
1
+ {"version":3,"sources":["../src/schema/deserializer.ts"],"names":["KindRegistry","validateImpliesEndpointCompatibility"],"mappings":";;;;;AAiFO,SAAS,kBACd,MAAA,EACoB;AACpB,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA;AAC1C,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA;AAC1C,EAAA,MAAM,aAAA,GAAgB,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,SAAS,SAAS,CAAA;AAE3D,EAAA,OAAO;AAAA,IACL,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,aAAa,MAAA,CAAO,WAAA;AAAA,IAEpB,OAAA,EAAS,CAAC,IAAA,KAAS,MAAA,CAAO,MAAM,IAAI,CAAA;AAAA,IACpC,cAAc,MAAM,SAAA;AAAA,IAEpB,OAAA,EAAS,CAAC,IAAA,KAAS,MAAA,CAAO,MAAM,IAAI,CAAA;AAAA,IACpC,cAAc,MAAM,SAAA;AAAA,IAEpB,aAAa,CAAC,IAAA,KAAS,MAAA,CAAO,QAAA,CAAS,UAAU,IAAI,CAAA;AAAA,IACrD,kBAAkB,MAAM,aAAA;AAAA,IAExB,YAAA,EAAc,MAAM,MAAA,CAAO,QAAA,CAAS,SAAA;AAAA,IACpC,WAAA,EAAa,MAAM,MAAA,CAAO,QAAA,CAAS,QAAA;AAA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W,SAAA,EAAW;AAAA,IACtD,iBAAA;AAAA,IACA,mBAAA;AAAA,IACA,cAAA;AAAA,IACA,eAAA;AAAA,IACA,eAAA;AAAA,IACA,SAAA;AAAA,IACA,aAAA;AAAA,IACA,aAAA;AAAA,IACA,cAAA;AAAA,IACA,YAAA;AAAA,IACA,uBAAA;AAAA,IACA;AAAA,GACD,CAAA;AAED,EAAAC,sDAAA;AAAA,IACE,sBAAA,CAAuB,OAAO,KAAK,CAAA;AAAA,IACnC;AAAA,GACF;AAEA,EAAA,OAAO,QAAA;AACT;AASA,SAAS,uBACP,KAAA,EACwC;AACxC,EAAA,MAAM,MAAA,uBAAa,GAAA,EAA+B;AAClD,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,GAAG,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAC/C,IAAA,MAAA,CAAO,GAAA,CAAI,MAAM,EAAE,IAAA,EAAM,IAAI,SAAA,EAAW,EAAA,EAAI,GAAA,CAAI,OAAA,EAAS,CAAA;AAAA,EAC3D;AACA,EAAA,OAAO,MAAA;AACT;AAKA,SAAS,YACP,MAAA,EAC0C;AAC1C,EAAA,MAAM,MAAA,uBAAa,GAAA,EAAyB;AAC5C,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,MAAM,KAAK,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,EAAG;AAClD,IAAA,MAAA,CAAO,GAAA,CAAI,GAAA,EAAK,IAAI,GAAA,CAAI,MAAM,CAAC,CAAA;AAAA,EACjC;AACA,EAAA,OAAO,MAAA;AACT;AAKA,SAAS,kBACP,MAAA,EAC6B;AAC7B,EAAA,OAAO,IAAI,GAAA,CAAI,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAC,CAAA;AACvC","file":"chunk-QC4MCOFV.cjs","sourcesContent":["/**\n * Schema deserializer for loading stored schemas.\n *\n * Reconstructs runtime objects from SerializedSchema.\n * Note: Zod schemas cannot be fully reconstructed from JSON Schema,\n * so this provides access to the serialized data for introspection.\n */\nimport { KindRegistry } from \"../registry/kind-registry\";\nimport {\n type EdgeEndpointKinds,\n validateImpliesEndpointCompatibility,\n} from \"../registry/validate-implies\";\nimport {\n type SerializedClosures,\n type SerializedEdgeDef,\n type SerializedMetaEdge,\n type SerializedNodeDef,\n type SerializedOntologyRelation,\n type SerializedSchema,\n} from \"./types\";\n\n// ============================================================\n// Deserialized Schema\n// ============================================================\n\n/**\n * A deserialized schema provides read-only access to schema metadata.\n *\n * Note: Unlike the original GraphDef, this does not include Zod schemas\n * since those cannot be reconstructed from JSON Schema. Use this for\n * introspection and metadata access only.\n */\nexport type DeserializedSchema = Readonly<{\n graphId: string;\n version: number;\n generatedAt: string;\n\n /** Get node definition by name */\n getNode: (name: string) => SerializedNodeDef | undefined;\n\n /** Get all node names */\n getNodeNames: () => readonly string[];\n\n /** Get edge definition by name */\n getEdge: (name: string) => SerializedEdgeDef | undefined;\n\n /** Get all edge names */\n getEdgeNames: () => readonly string[];\n\n /** Get meta-edge definition by name */\n getMetaEdge: (name: string) => SerializedMetaEdge | undefined;\n\n /** Get all meta-edge names */\n getMetaEdgeNames: () => readonly string[];\n\n /** Get all ontology relations */\n getRelations: () => readonly SerializedOntologyRelation[];\n\n /** Get precomputed closures */\n getClosures: () => SerializedClosures;\n\n /** Get graph defaults */\n getDefaults: () => SerializedSchema[\"defaults\"];\n\n /** Get the raw serialized schema */\n getRaw: () => SerializedSchema;\n\n /** Build a KindRegistry from the closures */\n buildRegistry: () => KindRegistry;\n}>;\n\n// ============================================================\n// Deserialization\n// ============================================================\n\n/**\n * Deserializes a SerializedSchema into a DeserializedSchema.\n *\n * @param schema - The serialized schema to deserialize\n * @returns A deserialized schema with accessor methods\n */\nexport function deserializeSchema(\n schema: SerializedSchema,\n): DeserializedSchema {\n const nodeNames = Object.keys(schema.nodes);\n const edgeNames = Object.keys(schema.edges);\n const metaEdgeNames = Object.keys(schema.ontology.metaEdges);\n\n return {\n graphId: schema.graphId,\n version: schema.version,\n generatedAt: schema.generatedAt,\n\n getNode: (name) => schema.nodes[name],\n getNodeNames: () => nodeNames,\n\n getEdge: (name) => schema.edges[name],\n getEdgeNames: () => edgeNames,\n\n getMetaEdge: (name) => schema.ontology.metaEdges[name],\n getMetaEdgeNames: () => metaEdgeNames,\n\n getRelations: () => schema.ontology.relations,\n getClosures: () => schema.ontology.closures,\n\n getDefaults: () => schema.defaults,\n getRaw: () => schema,\n\n buildRegistry: () => buildRegistryFromClosures(schema),\n };\n}\n\n// ============================================================\n// Registry Building\n// ============================================================\n\n/**\n * Builds a KindRegistry from serialized closures.\n *\n * This allows query execution without recomputing closures.\n */\nfunction buildRegistryFromClosures(schema: SerializedSchema): KindRegistry {\n const { closures } = schema.ontology;\n\n // Convert Record<string, string[]> back to Map<string, Set<string>>\n const subClassAncestors = recordToMap(closures.subClassAncestors);\n const subClassDescendants = recordToMap(closures.subClassDescendants);\n const broaderClosure = recordToMap(closures.broaderClosure);\n const narrowerClosure = recordToMap(closures.narrowerClosure);\n const equivalenceSets = recordToMap(closures.equivalenceSets);\n const partOfClosure = recordToMap(closures.partOfClosure);\n const hasPartClosure = recordToMap(closures.hasPartClosure);\n const iriToKind = simpleRecordToMap(closures.iriToKind);\n const disjointPairs = new Set(closures.disjointPairs);\n const edgeInverses = simpleRecordToMap(closures.edgeInverses);\n const edgeImplicationsClosure = recordToMap(closures.edgeImplicationsClosure);\n const edgeImplyingClosure = recordToMap(closures.edgeImplyingClosure);\n\n // Build empty node/edge kind maps (we don't have the actual Zod schemas)\n const nodeKinds = new Map();\n const edgeKinds = new Map();\n\n const registry = new KindRegistry(nodeKinds, edgeKinds, {\n subClassAncestors,\n subClassDescendants,\n broaderClosure,\n narrowerClosure,\n equivalenceSets,\n iriToKind,\n disjointPairs,\n partOfClosure,\n hasPartClosure,\n edgeInverses,\n edgeImplicationsClosure,\n edgeImplyingClosure,\n });\n\n validateImpliesEndpointCompatibility(\n buildEdgeEndpointKinds(schema.edges),\n registry,\n );\n\n return registry;\n}\n\n/**\n * Maps each edge kind's serialized definition to its domain/range kind\n * names, for `validateImpliesEndpointCompatibility`. A `Map` (rather than\n * the plain `schema.edges` object) so a lookup for an edge kind literally\n * named \"toString\" or another `Object.prototype` member can't resolve to\n * an inherited member instead of `undefined`.\n */\nfunction buildEdgeEndpointKinds(\n edges: Record<string, SerializedEdgeDef>,\n): ReadonlyMap<string, EdgeEndpointKinds> {\n const result = new Map<string, EdgeEndpointKinds>();\n for (const [kind, def] of Object.entries(edges)) {\n result.set(kind, { from: def.fromKinds, to: def.toKinds });\n }\n return result;\n}\n\n/**\n * Converts Record<string, string[]> to Map<string, Set<string>>.\n */\nfunction recordToMap(\n record: Record<string, readonly string[]>,\n): ReadonlyMap<string, ReadonlySet<string>> {\n const result = new Map<string, Set<string>>();\n for (const [key, values] of Object.entries(record)) {\n result.set(key, new Set(values));\n }\n return result;\n}\n\n/**\n * Converts Record<string, string> to Map<string, string>.\n */\nfunction simpleRecordToMap(\n record: Record<string, string>,\n): ReadonlyMap<string, string> {\n return new Map(Object.entries(record));\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { shortHash, quoteIdentifier } from './chunk-K3BUWSFR.js';
1
+ import { shortHash, quoteIdentifier } from './chunk-PVUI6KGR.js';
2
2
 
3
3
  // src/indexes/system.ts
4
4
  var SYSTEM_INDEX_DECLARATIONS = [
@@ -208,5 +208,5 @@ function generateSystemIndexDDL(declaration, physicalTableName, options) {
208
208
  }
209
209
 
210
210
  export { SYSTEM_INDEX_DECLARATIONS, assertNoSystemIndexNameCollision, generateSystemIndexDDL, resolveSystemIndexNames, resolveSystemIndexTableName, systemIndexName };
211
- //# sourceMappingURL=chunk-JRP3VGHS.js.map
212
- //# sourceMappingURL=chunk-JRP3VGHS.js.map
211
+ //# sourceMappingURL=chunk-QLUXRWKL.js.map
212
+ //# sourceMappingURL=chunk-QLUXRWKL.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/indexes/system.ts"],"names":[],"mappings":";;;AA6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A,CAAgB,iBAAA,EAAmB,WAAA,CAAY,MAAM;AAAA,GACvD;AACA,EAAA,MAAM,KAAA,GAAQ,gBAAgB,iBAAiB,CAAA;AAC/C,EAAA,MAAM,OAAA,GAAU,WAAA,CAAY,OAAA,CACzB,GAAA,CAAI,CAAC,MAAA,KAAW,eAAA,CAAgB,MAAM,CAAC,CAAA,CACvC,IAAA,CAAK,IAAI,CAAA;AACZ,EAAA,MAAM,YAAA,GAAe,OAAA,CAAQ,UAAA,GAAa,eAAA,GAAkB,EAAA;AAC5D,EAAA,OAAO,gBAAgB,YAAY,CAAA,cAAA,EAAiB,IAAI,CAAA,IAAA,EAAO,KAAK,KAAK,OAAO,CAAA,EAAA,CAAA;AAClF","file":"chunk-JRP3VGHS.js","sourcesContent":["/**\n * System-index declarations — the single source of truth for the plain\n * btree indexes TypeGraph ships on its own relations.\n *\n * Both dialect schema factories (`createSqliteTables` /\n * `createPostgresTables`) derive their Drizzle index builders from this\n * list, so the two dialects cannot drift, and\n * `materializeSystemIndexes()` derives the same indexes as runtime DDL so\n * an index added in a new library version reaches already-initialized\n * databases (bootstrap DDL only runs on first boot — see\n * `loadActiveSchemaWithBootstrap`).\n *\n * Scope: non-unique btree column indexes on the four graph relations,\n * where performance iteration actually happens. Primary keys, unique /\n * partial-unique constraints, and status-table indexes are structural —\n * they are created with their table and never retrofitted — and stay in\n * the schema files.\n *\n * Changing a declaration's shape under the same suffix is a signature\n * drift: `materializeSystemIndexes` reports `failed` for it until the\n * operator drops the old physical index. Rename (new suffix) instead,\n * exactly like graph-declared indexes. Two acknowledged limits of that\n * contract: on databases whose indexes were bootstrap-created (no status\n * rows) an in-place reshape is undetectable at runtime — the rename rule\n * is enforced by review and the parity tests; and a renamed suffix\n * strands the old physical index (the runner only adds). When the first\n * rename actually happens, add a retired-suffixes list + drop path here.\n */\nimport { quoteIdentifier, shortHash } from \"../query/dialect/vector-strategy\";\n\n/** The TypeGraph relations that carry system indexes. */\nexport type SystemIndexTable =\n \"nodes\" | \"edges\" | \"recordedNodes\" | \"recordedEdges\";\n\ntype LiveColumn =\n | \"graph_id\"\n | \"kind\"\n | \"id\"\n | \"deleted_at\"\n | \"valid_from\"\n | \"valid_to\"\n | \"created_at\";\n\ntype LiveEdgeColumn =\n LiveColumn | \"from_kind\" | \"from_id\" | \"to_kind\" | \"to_id\";\n\ntype RecordedColumn =\n | \"graph_id\"\n | \"kind\"\n | \"id\"\n | \"valid_from\"\n | \"valid_to\"\n | \"recorded_from\"\n | \"recorded_to\";\n\ntype RecordedEdgeColumn =\n RecordedColumn | \"from_kind\" | \"from_id\" | \"to_kind\" | \"to_id\";\n\ntype SystemIndexColumnsFor<T extends SystemIndexTable> =\n T extends \"nodes\" ? LiveColumn\n : T extends \"edges\" ? LiveEdgeColumn\n : T extends \"recordedNodes\" ? RecordedColumn\n : RecordedEdgeColumn;\n\ntype SystemIndexDeclarationFor<T extends SystemIndexTable> = Readonly<{\n table: T;\n /** Physical index name is `${physicalTableName}_${suffix}`. */\n suffix: string;\n columns: readonly [SystemIndexColumnsFor<T>, ...SystemIndexColumnsFor<T>[]];\n}>;\n\nexport type SystemIndexDeclaration =\n | SystemIndexDeclarationFor<\"nodes\">\n | SystemIndexDeclarationFor<\"edges\">\n | SystemIndexDeclarationFor<\"recordedNodes\">\n | SystemIndexDeclarationFor<\"recordedEdges\">;\n\nexport const SYSTEM_INDEX_DECLARATIONS: readonly SystemIndexDeclaration[] = [\n // ---------------------------------------------------------- nodes\n { table: \"nodes\", suffix: \"kind_idx\", columns: [\"graph_id\", \"kind\"] },\n // Listing shape: kind partition ordered by creation with the\n // soft-delete column ahead of it so `deleted_at IS NULL` list queries\n // stay index-served.\n {\n table: \"nodes\",\n suffix: \"kind_created_idx\",\n columns: [\"graph_id\", \"kind\", \"deleted_at\", \"created_at\"],\n },\n {\n table: \"nodes\",\n suffix: \"deleted_idx\",\n columns: [\"graph_id\", \"deleted_at\"],\n },\n {\n table: \"nodes\",\n suffix: \"valid_idx\",\n columns: [\"graph_id\", \"valid_from\", \"valid_to\"],\n },\n // Bare-id lookup: the primary key leads with `kind` (graph_id, kind,\n // id), so a `WHERE graph_id = ? AND id = ?` probe that doesn't know the\n // kind can't seek it — SQLite falls back to a graph_id-only scan of\n // every node in the graph (~3M at LDBC SF1).\n // `store.algorithms.degree`'s node-kind subquery does exactly that\n // lookup (it resolves the seed's kind by id), so without this index\n // degree is a full nodes scan (~95ms at SF1). See typegraph#280.\n { table: \"nodes\", suffix: \"id_idx\", columns: [\"graph_id\", \"id\"] },\n\n // ---------------------------------------------------------- edges\n { table: \"edges\", suffix: \"kind_idx\", columns: [\"graph_id\", \"kind\"] },\n // Directional traversal index (outgoing): supports endpoint lookups\n // and extra filtering by edge kind / target kind. Includes every\n // system column the compiled query's soft-delete/temporal-validity\n // predicate touches (deleted_at, valid_from, valid_to), trailed by\n // to_id — the compiled traversal join reads `n.id = e.to_id` for an\n // outgoing traversal (standard-builders.ts), so without to_id here\n // the join still fetches the edge's heap row for that one column\n // even with the seek/predicate columns covered.\n {\n table: \"edges\",\n suffix: \"from_idx\",\n columns: [\n \"graph_id\",\n \"from_kind\",\n \"from_id\",\n \"kind\",\n \"to_kind\",\n \"deleted_at\",\n \"valid_from\",\n \"valid_to\",\n \"to_id\",\n ],\n },\n // Directional traversal index (incoming): mirrors from_idx for\n // reverse traversals, trailed by from_id for the same reason\n // (`n.id = e.from_id` for an incoming traversal).\n {\n table: \"edges\",\n suffix: \"to_idx\",\n columns: [\n \"graph_id\",\n \"to_kind\",\n \"to_id\",\n \"kind\",\n \"from_kind\",\n \"deleted_at\",\n \"valid_from\",\n \"valid_to\",\n \"from_id\",\n ],\n },\n {\n table: \"edges\",\n suffix: \"kind_created_idx\",\n columns: [\"graph_id\", \"kind\", \"deleted_at\", \"created_at\"],\n },\n {\n table: \"edges\",\n suffix: \"deleted_idx\",\n columns: [\"graph_id\", \"deleted_at\"],\n },\n {\n table: \"edges\",\n suffix: \"valid_idx\",\n columns: [\"graph_id\", \"valid_from\", \"valid_to\"],\n },\n // Cardinality enforcement: the one-per-endpoint check probes for a\n // currently-valid edge of a kind from a specific endpoint.\n {\n table: \"edges\",\n suffix: \"cardinality_idx\",\n columns: [\"graph_id\", \"kind\", \"from_kind\", \"from_id\", \"valid_to\"],\n },\n\n // ---------------------------------------------------------- recordedNodes\n {\n table: \"recordedNodes\",\n suffix: \"entity_idx\",\n columns: [\"graph_id\", \"kind\", \"id\", \"recorded_from\", \"recorded_to\"],\n },\n {\n table: \"recordedNodes\",\n suffix: \"open_idx\",\n columns: [\"graph_id\", \"recorded_to\"],\n },\n {\n table: \"recordedNodes\",\n suffix: \"valid_idx\",\n columns: [\"graph_id\", \"valid_from\", \"valid_to\"],\n },\n // Bare-id lookup parity with the live nodes table: recorded-pinned\n // reads swap this relation in as the node source, and `entity_idx`\n // leads with `kind`, so the same kind-by-bare-id probe (e.g.\n // `degree()` at a recorded coordinate) would otherwise scan every\n // historical version in the graph. See typegraph#280.\n { table: \"recordedNodes\", suffix: \"id_idx\", columns: [\"graph_id\", \"id\"] },\n\n // ---------------------------------------------------------- recordedEdges\n {\n table: \"recordedEdges\",\n suffix: \"entity_idx\",\n columns: [\"graph_id\", \"kind\", \"id\", \"recorded_from\", \"recorded_to\"],\n },\n {\n table: \"recordedEdges\",\n suffix: \"open_idx\",\n columns: [\"graph_id\", \"recorded_to\"],\n },\n {\n table: \"recordedEdges\",\n suffix: \"from_idx\",\n columns: [\n \"graph_id\",\n \"from_kind\",\n \"from_id\",\n \"kind\",\n \"to_kind\",\n \"recorded_from\",\n \"recorded_to\",\n ],\n },\n {\n table: \"recordedEdges\",\n suffix: \"to_idx\",\n columns: [\n \"graph_id\",\n \"to_kind\",\n \"to_id\",\n \"kind\",\n \"from_kind\",\n \"recorded_from\",\n \"recorded_to\",\n ],\n },\n {\n table: \"recordedEdges\",\n suffix: \"valid_idx\",\n columns: [\"graph_id\", \"valid_from\", \"valid_to\"],\n },\n];\n\n/** Default physical table names for the system-index relations. */\nconst DEFAULT_SYSTEM_INDEX_TABLE_NAMES: Readonly<\n Record<SystemIndexTable, string>\n> = {\n nodes: \"typegraph_nodes\",\n edges: \"typegraph_edges\",\n recordedNodes: \"typegraph_recorded_nodes\",\n recordedEdges: \"typegraph_recorded_edges\",\n};\n\n/**\n * Resolves the physical table name for a system-index relation, honoring\n * a backend's table-name overrides.\n */\nexport function resolveSystemIndexTableName(\n table: SystemIndexTable,\n overrides:\n Readonly<Partial<Record<SystemIndexTable, string | undefined>>> | undefined,\n): string {\n return overrides?.[table] ?? DEFAULT_SYSTEM_INDEX_TABLE_NAMES[table];\n}\n\n/**\n * PostgreSQL truncates identifiers to NAMEDATALEN-1 = 63 bytes SILENTLY —\n * two suffixes of one long custom table name would collide after\n * truncation, and the catalog probes (which compare by exact name) would\n * never match the stored name, re-attempting the build on every boot.\n * SQLite has no such limit but uses the same bound so the two dialects'\n * index sets stay in byte-for-byte parity. (Char-based like the vector\n * identifier bound — multibyte table names are out of scope.)\n */\nconst MAX_SQL_IDENTIFIER_LENGTH = 63;\n\n/**\n * Physical index name: `${physicalTableName}_${suffix}`, deterministically\n * truncated + hash-suffixed past the 63-char identifier bound so distinct\n * indexes stay distinct. Single choke point — the Drizzle builders, the\n * runtime DDL, the catalog probes, and the status keys all derive the\n * name here, so they can never disagree.\n */\nexport function systemIndexName(\n physicalTableName: string,\n suffix: string,\n): string {\n const full = `${physicalTableName}_${suffix}`;\n if (full.length <= MAX_SQL_IDENTIFIER_LENGTH) return full;\n const hash = shortHash(JSON.stringify([physicalTableName, suffix]));\n return `${full.slice(0, MAX_SQL_IDENTIFIER_LENGTH - 1 - hash.length)}_${hash}`;\n}\n\n/**\n * Every system index name for a deployment's (possibly overridden) table\n * names. Graph-declared index names must not collide with these: a\n * colliding `CREATE INDEX IF NOT EXISTS` would silently no-op against the\n * system index (wrong shape) while recording a false success — see the\n * guards in the schema factories and `materializeIndexes`.\n */\nexport function resolveSystemIndexNames(\n overrides:\n Readonly<Partial<Record<SystemIndexTable, string | undefined>>> | undefined,\n): ReadonlySet<string> {\n return new Set(\n SYSTEM_INDEX_DECLARATIONS.map((declaration) =>\n systemIndexName(\n resolveSystemIndexTableName(declaration.table, overrides),\n declaration.suffix,\n ),\n ),\n );\n}\n\n/**\n * Rejects graph-declared indexes whose names collide with this\n * deployment's system index names. Called by both dialect schema\n * factories so a colliding declaration fails at table-definition time\n * instead of silently no-opping against the (differently shaped) system\n * index at CREATE INDEX IF NOT EXISTS time. `materializeIndexes` applies\n * the same check per-declaration on its runtime path.\n */\nexport function assertNoSystemIndexNameCollision(\n indexes: readonly Readonly<{ name: string }>[],\n overrides:\n Readonly<Partial<Record<SystemIndexTable, string | undefined>>> | undefined,\n): void {\n if (indexes.length === 0) return;\n const reserved = resolveSystemIndexNames(overrides);\n for (const index of indexes) {\n if (reserved.has(index.name)) {\n throw new Error(\n `Index name \"${index.name}\" collides with a TypeGraph system ` +\n `index. Choose a different name — system index names are ` +\n `reserved, and a same-named CREATE INDEX IF NOT EXISTS would ` +\n `silently no-op against the system index instead of creating ` +\n `the declared one.`,\n );\n }\n }\n}\n\n/**\n * Runtime DDL for one system index — byte-compatible with the index the\n * bootstrap path creates from the Drizzle schema (same name, same\n * columns), plus `CONCURRENTLY` where the dialect supports building\n * without blocking writes.\n */\nexport function generateSystemIndexDDL(\n declaration: SystemIndexDeclaration,\n physicalTableName: string,\n options: Readonly<{ concurrent: boolean }>,\n): string {\n const name = quoteIdentifier(\n systemIndexName(physicalTableName, declaration.suffix),\n );\n const table = quoteIdentifier(physicalTableName);\n const columns = declaration.columns\n .map((column) => quoteIdentifier(column))\n .join(\", \");\n const concurrently = options.concurrent ? \"CONCURRENTLY \" : \"\";\n return `CREATE INDEX ${concurrently}IF NOT EXISTS ${name} ON ${table} (${columns});`;\n}\n"]}
1
+ {"version":3,"sources":["../src/indexes/system.ts"],"names":[],"mappings":";;;AA6EO,IAAM,yBAAA,GAA+D;AAAA;AAAA,EAE1E,EAAE,OAAO,OAAA,EAAS,M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M,KAAA,GAAQ,gBAAgB,iBAAiB,CAAA;AAC/C,EAAA,MAAM,OAAA,GAAU,WAAA,CAAY,OAAA,CACzB,GAAA,CAAI,CAAC,MAAA,KAAW,eAAA,CAAgB,MAAM,CAAC,CAAA,CACvC,IAAA,CAAK,IAAI,CAAA;AACZ,EAAA,MAAM,YAAA,GAAe,OAAA,CAAQ,UAAA,GAAa,eAAA,GAAkB,EAAA;AAC5D,EAAA,OAAO,gBAAgB,YAAY,CAAA,cAAA,EAAiB,IAAI,CAAA,IAAA,EAAO,KAAK,KAAK,OAAO,CAAA,EAAA,CAAA;AAClF","file":"chunk-QLUXRWKL.js","sourcesContent":["/**\n * System-index declarations — the single source of truth for the plain\n * btree indexes TypeGraph ships on its own relations.\n *\n * Both dialect schema factories (`createSqliteTables` /\n * `createPostgresTables`) derive their Drizzle index builders from this\n * list, so the two dialects cannot drift, and\n * `materializeSystemIndexes()` derives the same indexes as runtime DDL so\n * an index added in a new library version reaches already-initialized\n * databases (bootstrap DDL only runs on first boot — see\n * `loadActiveSchemaWithBootstrap`).\n *\n * Scope: non-unique btree column indexes on the four graph relations,\n * where performance iteration actually happens. Primary keys, unique /\n * partial-unique constraints, and status-table indexes are structural —\n * they are created with their table and never retrofitted — and stay in\n * the schema files.\n *\n * Changing a declaration's shape under the same suffix is a signature\n * drift: `materializeSystemIndexes` reports `failed` for it until the\n * operator drops the old physical index. Rename (new suffix) instead,\n * exactly like graph-declared indexes. Two acknowledged limits of that\n * contract: on databases whose indexes were bootstrap-created (no status\n * rows) an in-place reshape is undetectable at runtime — the rename rule\n * is enforced by review and the parity tests; and a renamed suffix\n * strands the old physical index (the runner only adds). When the first\n * rename actually happens, add a retired-suffixes list + drop path here.\n */\nimport { quoteIdentifier, shortHash } from \"../query/dialect/vector-strategy\";\n\n/** The TypeGraph relations that carry system indexes. */\nexport type SystemIndexTable =\n \"nodes\" | \"edges\" | \"recordedNodes\" | \"recordedEdges\";\n\ntype LiveColumn =\n | \"graph_id\"\n | \"kind\"\n | \"id\"\n | \"deleted_at\"\n | \"valid_from\"\n | \"valid_to\"\n | \"created_at\";\n\ntype LiveEdgeColumn =\n LiveColumn | \"from_kind\" | \"from_id\" | \"to_kind\" | \"to_id\";\n\ntype RecordedColumn =\n | \"graph_id\"\n | \"kind\"\n | \"id\"\n | \"valid_from\"\n | \"valid_to\"\n | \"recorded_from\"\n | \"recorded_to\";\n\ntype RecordedEdgeColumn =\n RecordedColumn | \"from_kind\" | \"from_id\" | \"to_kind\" | \"to_id\";\n\ntype SystemIndexColumnsFor<T extends SystemIndexTable> =\n T extends \"nodes\" ? LiveColumn\n : T extends \"edges\" ? LiveEdgeColumn\n : T extends \"recordedNodes\" ? RecordedColumn\n : RecordedEdgeColumn;\n\ntype SystemIndexDeclarationFor<T extends SystemIndexTable> = Readonly<{\n table: T;\n /** Physical index name is `${physicalTableName}_${suffix}`. */\n suffix: string;\n columns: readonly [SystemIndexColumnsFor<T>, ...SystemIndexColumnsFor<T>[]];\n}>;\n\nexport type SystemIndexDeclaration =\n | SystemIndexDeclarationFor<\"nodes\">\n | SystemIndexDeclarationFor<\"edges\">\n | SystemIndexDeclarationFor<\"recordedNodes\">\n | SystemIndexDeclarationFor<\"recordedEdges\">;\n\nexport const SYSTEM_INDEX_DECLARATIONS: readonly SystemIndexDeclaration[] = [\n // ---------------------------------------------------------- nodes\n { table: \"nodes\", suffix: \"kind_idx\", columns: [\"graph_id\", \"kind\"] },\n // Listing shape: kind partition ordered by creation with the\n // soft-delete column ahead of it so `deleted_at IS NULL` list queries\n // stay index-served.\n {\n table: \"nodes\",\n suffix: \"kind_created_idx\",\n columns: [\"graph_id\", \"kind\", \"deleted_at\", \"created_at\"],\n },\n {\n table: \"nodes\",\n suffix: \"deleted_idx\",\n columns: [\"graph_id\", \"deleted_at\"],\n },\n {\n table: \"nodes\",\n suffix: \"valid_idx\",\n columns: [\"graph_id\", \"valid_from\", \"valid_to\"],\n },\n // Bare-id lookup: the primary key leads with `kind` (graph_id, kind,\n // id), so a `WHERE graph_id = ? AND id = ?` probe that doesn't know the\n // kind can't seek it — SQLite falls back to a graph_id-only scan of\n // every node in the graph (~3M at LDBC SF1).\n // `store.algorithms.degree`'s node-kind subquery does exactly that\n // lookup (it resolves the seed's kind by id), so without this index\n // degree is a full nodes scan (~95ms at SF1). See typegraph#280.\n { table: \"nodes\", suffix: \"id_idx\", columns: [\"graph_id\", \"id\"] },\n\n // ---------------------------------------------------------- edges\n { table: \"edges\", suffix: \"kind_idx\", columns: [\"graph_id\", \"kind\"] },\n // Directional traversal index (outgoing): supports endpoint lookups\n // and extra filtering by edge kind / target kind. Includes every\n // system column the compiled query's soft-delete/temporal-validity\n // predicate touches (deleted_at, valid_from, valid_to), trailed by\n // to_id — the compiled traversal join reads `n.id = e.to_id` for an\n // outgoing traversal (standard-builders.ts), so without to_id here\n // the join still fetches the edge's heap row for that one column\n // even with the seek/predicate columns covered.\n {\n table: \"edges\",\n suffix: \"from_idx\",\n columns: [\n \"graph_id\",\n \"from_kind\",\n \"from_id\",\n \"kind\",\n \"to_kind\",\n \"deleted_at\",\n \"valid_from\",\n \"valid_to\",\n \"to_id\",\n ],\n },\n // Directional traversal index (incoming): mirrors from_idx for\n // reverse traversals, trailed by from_id for the same reason\n // (`n.id = e.from_id` for an incoming traversal).\n {\n table: \"edges\",\n suffix: \"to_idx\",\n columns: [\n \"graph_id\",\n \"to_kind\",\n \"to_id\",\n \"kind\",\n \"from_kind\",\n \"deleted_at\",\n \"valid_from\",\n \"valid_to\",\n \"from_id\",\n ],\n },\n {\n table: \"edges\",\n suffix: \"kind_created_idx\",\n columns: [\"graph_id\", \"kind\", \"deleted_at\", \"created_at\"],\n },\n {\n table: \"edges\",\n suffix: \"deleted_idx\",\n columns: [\"graph_id\", \"deleted_at\"],\n },\n {\n table: \"edges\",\n suffix: \"valid_idx\",\n columns: [\"graph_id\", \"valid_from\", \"valid_to\"],\n },\n // Cardinality enforcement: the one-per-endpoint check probes for a\n // currently-valid edge of a kind from a specific endpoint.\n {\n table: \"edges\",\n suffix: \"cardinality_idx\",\n columns: [\"graph_id\", \"kind\", \"from_kind\", \"from_id\", \"valid_to\"],\n },\n\n // ---------------------------------------------------------- recordedNodes\n {\n table: \"recordedNodes\",\n suffix: \"entity_idx\",\n columns: [\"graph_id\", \"kind\", \"id\", \"recorded_from\", \"recorded_to\"],\n },\n {\n table: \"recordedNodes\",\n suffix: \"open_idx\",\n columns: [\"graph_id\", \"recorded_to\"],\n },\n {\n table: \"recordedNodes\",\n suffix: \"valid_idx\",\n columns: [\"graph_id\", \"valid_from\", \"valid_to\"],\n },\n // Bare-id lookup parity with the live nodes table: recorded-pinned\n // reads swap this relation in as the node source, and `entity_idx`\n // leads with `kind`, so the same kind-by-bare-id probe (e.g.\n // `degree()` at a recorded coordinate) would otherwise scan every\n // historical version in the graph. See typegraph#280.\n { table: \"recordedNodes\", suffix: \"id_idx\", columns: [\"graph_id\", \"id\"] },\n\n // ---------------------------------------------------------- recordedEdges\n {\n table: \"recordedEdges\",\n suffix: \"entity_idx\",\n columns: [\"graph_id\", \"kind\", \"id\", \"recorded_from\", \"recorded_to\"],\n },\n {\n table: \"recordedEdges\",\n suffix: \"open_idx\",\n columns: [\"graph_id\", \"recorded_to\"],\n },\n {\n table: \"recordedEdges\",\n suffix: \"from_idx\",\n columns: [\n \"graph_id\",\n \"from_kind\",\n \"from_id\",\n \"kind\",\n \"to_kind\",\n \"recorded_from\",\n \"recorded_to\",\n ],\n },\n {\n table: \"recordedEdges\",\n suffix: \"to_idx\",\n columns: [\n \"graph_id\",\n \"to_kind\",\n \"to_id\",\n \"kind\",\n \"from_kind\",\n \"recorded_from\",\n \"recorded_to\",\n ],\n },\n {\n table: \"recordedEdges\",\n suffix: \"valid_idx\",\n columns: [\"graph_id\", \"valid_from\", \"valid_to\"],\n },\n];\n\n/** Default physical table names for the system-index relations. */\nconst DEFAULT_SYSTEM_INDEX_TABLE_NAMES: Readonly<\n Record<SystemIndexTable, string>\n> = {\n nodes: \"typegraph_nodes\",\n edges: \"typegraph_edges\",\n recordedNodes: \"typegraph_recorded_nodes\",\n recordedEdges: \"typegraph_recorded_edges\",\n};\n\n/**\n * Resolves the physical table name for a system-index relation, honoring\n * a backend's table-name overrides.\n */\nexport function resolveSystemIndexTableName(\n table: SystemIndexTable,\n overrides:\n Readonly<Partial<Record<SystemIndexTable, string | undefined>>> | undefined,\n): string {\n return overrides?.[table] ?? DEFAULT_SYSTEM_INDEX_TABLE_NAMES[table];\n}\n\n/**\n * PostgreSQL truncates identifiers to NAMEDATALEN-1 = 63 bytes SILENTLY —\n * two suffixes of one long custom table name would collide after\n * truncation, and the catalog probes (which compare by exact name) would\n * never match the stored name, re-attempting the build on every boot.\n * SQLite has no such limit but uses the same bound so the two dialects'\n * index sets stay in byte-for-byte parity. (Char-based like the vector\n * identifier bound — multibyte table names are out of scope.)\n */\nconst MAX_SQL_IDENTIFIER_LENGTH = 63;\n\n/**\n * Physical index name: `${physicalTableName}_${suffix}`, deterministically\n * truncated + hash-suffixed past the 63-char identifier bound so distinct\n * indexes stay distinct. Single choke point — the Drizzle builders, the\n * runtime DDL, the catalog probes, and the status keys all derive the\n * name here, so they can never disagree.\n */\nexport function systemIndexName(\n physicalTableName: string,\n suffix: string,\n): string {\n const full = `${physicalTableName}_${suffix}`;\n if (full.length <= MAX_SQL_IDENTIFIER_LENGTH) return full;\n const hash = shortHash(JSON.stringify([physicalTableName, suffix]));\n return `${full.slice(0, MAX_SQL_IDENTIFIER_LENGTH - 1 - hash.length)}_${hash}`;\n}\n\n/**\n * Every system index name for a deployment's (possibly overridden) table\n * names. Graph-declared index names must not collide with these: a\n * colliding `CREATE INDEX IF NOT EXISTS` would silently no-op against the\n * system index (wrong shape) while recording a false success — see the\n * guards in the schema factories and `materializeIndexes`.\n */\nexport function resolveSystemIndexNames(\n overrides:\n Readonly<Partial<Record<SystemIndexTable, string | undefined>>> | undefined,\n): ReadonlySet<string> {\n return new Set(\n SYSTEM_INDEX_DECLARATIONS.map((declaration) =>\n systemIndexName(\n resolveSystemIndexTableName(declaration.table, overrides),\n declaration.suffix,\n ),\n ),\n );\n}\n\n/**\n * Rejects graph-declared indexes whose names collide with this\n * deployment's system index names. Called by both dialect schema\n * factories so a colliding declaration fails at table-definition time\n * instead of silently no-opping against the (differently shaped) system\n * index at CREATE INDEX IF NOT EXISTS time. `materializeIndexes` applies\n * the same check per-declaration on its runtime path.\n */\nexport function assertNoSystemIndexNameCollision(\n indexes: readonly Readonly<{ name: string }>[],\n overrides:\n Readonly<Partial<Record<SystemIndexTable, string | undefined>>> | undefined,\n): void {\n if (indexes.length === 0) return;\n const reserved = resolveSystemIndexNames(overrides);\n for (const index of indexes) {\n if (reserved.has(index.name)) {\n throw new Error(\n `Index name \"${index.name}\" collides with a TypeGraph system ` +\n `index. Choose a different name — system index names are ` +\n `reserved, and a same-named CREATE INDEX IF NOT EXISTS would ` +\n `silently no-op against the system index instead of creating ` +\n `the declared one.`,\n );\n }\n }\n}\n\n/**\n * Runtime DDL for one system index — byte-compatible with the index the\n * bootstrap path creates from the Drizzle schema (same name, same\n * columns), plus `CONCURRENTLY` where the dialect supports building\n * without blocking writes.\n */\nexport function generateSystemIndexDDL(\n declaration: SystemIndexDeclaration,\n physicalTableName: string,\n options: Readonly<{ concurrent: boolean }>,\n): string {\n const name = quoteIdentifier(\n systemIndexName(physicalTableName, declaration.suffix),\n );\n const table = quoteIdentifier(physicalTableName);\n const columns = declaration.columns\n .map((column) => quoteIdentifier(column))\n .join(\", \");\n const concurrently = options.concurrent ? \"CONCURRENTLY \" : \"\";\n return `CREATE INDEX ${concurrently}IF NOT EXISTS ${name} ON ${table} (${columns});`;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkOVUUTCPJ_cjs = require('./chunk-OVUUTCPJ.cjs');
3
+ var chunkJXUTCSXX_cjs = require('./chunk-JXUTCSXX.cjs');
4
4
  var chunkU5W4LKZV_cjs = require('./chunk-U5W4LKZV.cjs');
5
5
  var chunk764JHTLT_cjs = require('./chunk-764JHTLT.cjs');
6
6
 
@@ -30,9 +30,9 @@ function generateTableIndexDDL(index, dialect, tableName, options) {
30
30
  const ifNotExists = options.ifNotExists ?? true;
31
31
  const propsColumn = chunkU5W4LKZV_cjs.sql.identifier("props");
32
32
  const systemColumn = (column) => chunkU5W4LKZV_cjs.sql.identifier(column);
33
- const keys = index.entity === "node" ? chunkOVUUTCPJ_cjs.compileNodeIndexKeys(index, dialect, propsColumn, systemColumn).keys : chunkOVUUTCPJ_cjs.compileEdgeIndexKeys(index, dialect, propsColumn, systemColumn).keys;
33
+ const keys = index.entity === "node" ? chunkJXUTCSXX_cjs.compileNodeIndexKeys(index, dialect, propsColumn, systemColumn).keys : chunkJXUTCSXX_cjs.compileEdgeIndexKeys(index, dialect, propsColumn, systemColumn).keys;
34
34
  const whereSql = index.where ? chunkU5W4LKZV_cjs.renderSqlInline(
35
- chunkOVUUTCPJ_cjs.compileIndexWhere(
35
+ chunkJXUTCSXX_cjs.compileIndexWhere(
36
36
  {
37
37
  dialect,
38
38
  propsColumn,
@@ -55,7 +55,7 @@ function generateGinFamilyIndexDDL(index, dialect, tableName, options) {
55
55
  `Index "${index.name}" declares method "${index.method}", which requires PostgreSQL. materializeIndexes() reports such declarations as skipped on SQLite instead of calling this.`
56
56
  );
57
57
  }
58
- const adapter = chunkOVUUTCPJ_cjs.getDialect(dialect);
58
+ const adapter = chunkJXUTCSXX_cjs.getDialect(dialect);
59
59
  const propsColumn = chunkU5W4LKZV_cjs.sql.identifier("props");
60
60
  const pointer = chunk764JHTLT_cjs.requireDefined(index.fields[0]);
61
61
  const expression = index.method === "gin" ? adapter.jsonExtract(propsColumn, pointer) : adapter.jsonExtractText(propsColumn, pointer);
@@ -71,5 +71,5 @@ function quoteIdentifier(identifier) {
71
71
  exports.generateEdgeIndexDDL = generateEdgeIndexDDL;
72
72
  exports.generateIndexDDL = generateIndexDDL;
73
73
  exports.generateNodeIndexDDL = generateNodeIndexDDL;
74
- //# sourceMappingURL=chunk-IIT5K7SK.cjs.map
75
- //# sourceMappingURL=chunk-IIT5K7SK.cjs.map
74
+ //# sourceMappingURL=chunk-QR24DJDF.cjs.map
75
+ //# sourceMappingURL=chunk-QR24DJDF.cjs.map