@nicia-ai/typegraph 0.43.0 → 0.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend/drizzle/indexes.cjs +9 -9
- package/dist/backend/drizzle/indexes.d.cts +1 -1
- package/dist/backend/drizzle/indexes.d.ts +1 -1
- package/dist/backend/drizzle/indexes.js +5 -5
- package/dist/backend/index.cjs +50 -50
- package/dist/backend/index.d.cts +3 -3
- package/dist/backend/index.d.ts +3 -3
- package/dist/backend/index.js +11 -11
- package/dist/backend/postgres/index.cjs +26 -26
- package/dist/backend/postgres/index.d.cts +6 -5
- package/dist/backend/postgres/index.d.ts +6 -5
- package/dist/backend/postgres/index.js +13 -13
- package/dist/backend/postgres/pglite-store.cjs +32 -33
- package/dist/backend/postgres/pglite-store.cjs.map +1 -1
- package/dist/backend/postgres/pglite-store.d.cts +7 -7
- package/dist/backend/postgres/pglite-store.d.ts +7 -7
- package/dist/backend/postgres/pglite-store.js +28 -29
- package/dist/backend/postgres/pglite-store.js.map +1 -1
- package/dist/backend/postgres/pglite.cjs +15 -15
- package/dist/backend/postgres/pglite.d.cts +3 -2
- package/dist/backend/postgres/pglite.d.ts +3 -2
- package/dist/backend/postgres/pglite.js +14 -14
- package/dist/backend/sqlite/index.cjs +23 -23
- package/dist/backend/sqlite/index.d.cts +7 -6
- package/dist/backend/sqlite/index.d.ts +7 -6
- package/dist/backend/sqlite/index.js +11 -11
- package/dist/backend/sqlite/libsql.cjs +17 -17
- package/dist/backend/sqlite/libsql.cjs.map +1 -1
- package/dist/backend/sqlite/libsql.d.cts +3 -2
- package/dist/backend/sqlite/libsql.d.ts +3 -2
- package/dist/backend/sqlite/libsql.js +13 -13
- package/dist/backend/sqlite/libsql.js.map +1 -1
- package/dist/backend/sqlite/local-store.cjs +33 -34
- package/dist/backend/sqlite/local-store.cjs.map +1 -1
- package/dist/backend/sqlite/local-store.d.cts +8 -7
- package/dist/backend/sqlite/local-store.d.ts +8 -7
- package/dist/backend/sqlite/local-store.js +29 -30
- package/dist/backend/sqlite/local-store.js.map +1 -1
- package/dist/backend/sqlite/local.cjs +16 -16
- package/dist/backend/sqlite/local.d.cts +3 -2
- package/dist/backend/sqlite/local.d.ts +3 -2
- package/dist/backend/sqlite/local.js +14 -14
- package/dist/{chunk-2OOY4OYT.js → chunk-2L54C2C2.js} +4 -4
- package/dist/{chunk-2OOY4OYT.js.map → chunk-2L54C2C2.js.map} +1 -1
- package/dist/{chunk-4WYFRACU.js → chunk-42PYUGLS.js} +58 -4
- package/dist/chunk-42PYUGLS.js.map +1 -0
- package/dist/{chunk-EQOQOT55.js → chunk-4GUBTVPV.js} +4 -5
- package/dist/chunk-4GUBTVPV.js.map +1 -0
- package/dist/{chunk-ZIRC2U6G.js → chunk-4GUTQPVO.js} +102 -16
- package/dist/chunk-4GUTQPVO.js.map +1 -0
- package/dist/{chunk-OYJSYDIH.js → chunk-4MB3AQAQ.js} +13 -3
- package/dist/chunk-4MB3AQAQ.js.map +1 -0
- package/dist/{chunk-5Q3P6OIC.cjs → chunk-4MEWSUVM.cjs} +12 -12
- package/dist/chunk-4MEWSUVM.cjs.map +1 -0
- package/dist/{chunk-VC26BUNP.js → chunk-4QIKLIGG.js} +17 -5
- package/dist/chunk-4QIKLIGG.js.map +1 -0
- package/dist/chunk-4SZ6XPTG.cjs +12 -0
- package/dist/{chunk-VGMNGWBR.cjs.map → chunk-4SZ6XPTG.cjs.map} +1 -1
- package/dist/{chunk-UZLEQFTV.js → chunk-55ITBQJI.js} +4 -4
- package/dist/chunk-55ITBQJI.js.map +1 -0
- package/dist/{chunk-JOYPNY33.js → chunk-5EKPX6QU.js} +9 -9
- package/dist/{chunk-JOYPNY33.js.map → chunk-5EKPX6QU.js.map} +1 -1
- package/dist/{chunk-TRC646QQ.cjs → chunk-5GAONX5G.cjs} +7 -7
- package/dist/{chunk-TRC646QQ.cjs.map → chunk-5GAONX5G.cjs.map} +1 -1
- package/dist/{chunk-M4GYQF2H.js → chunk-6DCB664D.js} +7 -4
- package/dist/chunk-6DCB664D.js.map +1 -0
- package/dist/{chunk-64LERBFM.cjs → chunk-6RYPD3NJ.cjs} +75 -65
- package/dist/chunk-6RYPD3NJ.cjs.map +1 -0
- package/dist/{chunk-5AERZSHC.cjs → chunk-7PF2L3H6.cjs} +4 -4
- package/dist/{chunk-5AERZSHC.cjs.map → chunk-7PF2L3H6.cjs.map} +1 -1
- package/dist/chunk-B3F2D3SP.cjs +12 -0
- package/dist/{chunk-U3YRCZ5L.cjs.map → chunk-B3F2D3SP.cjs.map} +1 -1
- package/dist/{chunk-Z3WIL6S3.js → chunk-BGYJW37L.js} +5 -5
- package/dist/{chunk-Z3WIL6S3.js.map → chunk-BGYJW37L.js.map} +1 -1
- package/dist/{chunk-DMZEVJGL.cjs → chunk-BNS75YNF.cjs} +12 -13
- package/dist/chunk-BNS75YNF.cjs.map +1 -0
- package/dist/{chunk-KTBTSHU6.cjs → chunk-C4F7VJ5D.cjs} +13 -3
- package/dist/chunk-C4F7VJ5D.cjs.map +1 -0
- package/dist/{chunk-L2BYRYHC.js → chunk-CBKG6HEP.js} +43 -33
- package/dist/chunk-CBKG6HEP.js.map +1 -0
- package/dist/{chunk-CVK4T34X.cjs → chunk-CPEL3YIR.cjs} +22 -22
- package/dist/{chunk-CVK4T34X.cjs.map → chunk-CPEL3YIR.cjs.map} +1 -1
- package/dist/{chunk-O2GZM7UK.cjs → chunk-D54WH24V.cjs} +62 -7
- package/dist/chunk-D54WH24V.cjs.map +1 -0
- package/dist/{chunk-33PAKPED.cjs → chunk-D56XG4EI.cjs} +53 -41
- package/dist/chunk-D56XG4EI.cjs.map +1 -0
- package/dist/{chunk-O3USVVWS.js → chunk-DK2S42XB.js} +3 -3
- package/dist/{chunk-O3USVVWS.js.map → chunk-DK2S42XB.js.map} +1 -1
- package/dist/{chunk-HHBKGPEI.js → chunk-DXEEHSGN.js} +517 -26
- package/dist/chunk-DXEEHSGN.js.map +1 -0
- package/dist/{chunk-UJRWOV5B.js → chunk-EFEOOCJ3.js} +5 -5
- package/dist/{chunk-UJRWOV5B.js.map → chunk-EFEOOCJ3.js.map} +1 -1
- package/dist/{chunk-ECU53PMN.cjs → chunk-EKFUG4G7.cjs} +5 -5
- package/dist/chunk-EKFUG4G7.cjs.map +1 -0
- package/dist/{chunk-FSCJOTHF.cjs → chunk-EQ7JKLZO.cjs} +10 -10
- package/dist/{chunk-FSCJOTHF.cjs.map → chunk-EQ7JKLZO.cjs.map} +1 -1
- package/dist/{chunk-AQR6BHB3.cjs → chunk-F4NHQHEZ.cjs} +10 -10
- package/dist/{chunk-AQR6BHB3.cjs.map → chunk-F4NHQHEZ.cjs.map} +1 -1
- package/dist/{chunk-2G6ZEGYO.js → chunk-FL5UQRES.js} +4 -4
- package/dist/{chunk-2G6ZEGYO.js.map → chunk-FL5UQRES.js.map} +1 -1
- package/dist/{chunk-ZP2KPDNN.js → chunk-FLEQ2HBK.js} +3 -3
- package/dist/{chunk-ZP2KPDNN.js.map → chunk-FLEQ2HBK.js.map} +1 -1
- package/dist/{chunk-RAWG2FEU.js → chunk-FQ7ZPOTZ.js} +264 -18
- package/dist/chunk-FQ7ZPOTZ.js.map +1 -0
- package/dist/{chunk-O7XVCLXW.cjs → chunk-H7VE3FL4.cjs} +577 -82
- package/dist/chunk-H7VE3FL4.cjs.map +1 -0
- package/dist/{chunk-JNXZQBN3.js → chunk-ID4WXTKL.js} +1039 -482
- package/dist/chunk-ID4WXTKL.js.map +1 -0
- package/dist/{chunk-ZGOUVMVS.js → chunk-ISLPNELU.js} +17 -5
- package/dist/chunk-ISLPNELU.js.map +1 -0
- package/dist/{chunk-I73ATSAH.cjs → chunk-IX64T5OL.cjs} +4 -4
- package/dist/{chunk-I73ATSAH.cjs.map → chunk-IX64T5OL.cjs.map} +1 -1
- package/dist/{chunk-XDMPDUKL.cjs → chunk-J2ICGNHO.cjs} +8 -9
- package/dist/chunk-J2ICGNHO.cjs.map +1 -0
- package/dist/{chunk-KDRF3NR2.cjs → chunk-J7LXTUTP.cjs} +295 -201
- package/dist/chunk-J7LXTUTP.cjs.map +1 -0
- package/dist/{chunk-AO2WPYFZ.cjs → chunk-JQXSZHF2.cjs} +14 -4
- package/dist/chunk-JQXSZHF2.cjs.map +1 -0
- package/dist/{chunk-UTTW2Q3M.cjs → chunk-JXUTCSXX.cjs} +197 -133
- package/dist/chunk-JXUTCSXX.cjs.map +1 -0
- package/dist/{chunk-GT7NEXSU.js → chunk-KCO5EFJU.js} +3 -3
- package/dist/{chunk-GT7NEXSU.js.map → chunk-KCO5EFJU.js.map} +1 -1
- package/dist/{chunk-ARN3ZODS.cjs → chunk-KKYELPZ2.cjs} +6 -6
- package/dist/{chunk-ARN3ZODS.cjs.map → chunk-KKYELPZ2.cjs.map} +1 -1
- package/dist/{chunk-7Y6BV3TK.cjs → chunk-KMXWZLQX.cjs} +100 -100
- package/dist/{chunk-7Y6BV3TK.cjs.map → chunk-KMXWZLQX.cjs.map} +1 -1
- package/dist/{chunk-CDYRPI5U.js → chunk-MIJKEVV7.js} +4 -4
- package/dist/{chunk-CDYRPI5U.js.map → chunk-MIJKEVV7.js.map} +1 -1
- package/dist/{chunk-FFQGI67R.cjs → chunk-NAAMUYMS.cjs} +56 -44
- package/dist/chunk-NAAMUYMS.cjs.map +1 -0
- package/dist/{chunk-6TJ6PKPS.cjs → chunk-OOA273IJ.cjs} +27 -27
- package/dist/{chunk-6TJ6PKPS.cjs.map → chunk-OOA273IJ.cjs.map} +1 -1
- package/dist/{chunk-F2KVJ6FF.cjs → chunk-P7GTYOLB.cjs} +203 -117
- package/dist/chunk-P7GTYOLB.cjs.map +1 -0
- package/dist/{chunk-42XYPKZU.js → chunk-PVUI6KGR.js} +67 -3
- package/dist/chunk-PVUI6KGR.js.map +1 -0
- package/dist/{chunk-L5AUCL5P.js → chunk-Q6EDCUXV.js} +274 -14
- package/dist/chunk-Q6EDCUXV.js.map +1 -0
- package/dist/{chunk-ZPCKPLMX.cjs → chunk-QB6VMOJ2.cjs} +8 -8
- package/dist/{chunk-ZPCKPLMX.cjs.map → chunk-QB6VMOJ2.cjs.map} +1 -1
- package/dist/{chunk-3RPQDGUE.cjs → chunk-QC4MCOFV.cjs} +5 -5
- package/dist/{chunk-3RPQDGUE.cjs.map → chunk-QC4MCOFV.cjs.map} +1 -1
- package/dist/{chunk-4XRP2N6B.js → chunk-QLUXRWKL.js} +3 -3
- package/dist/{chunk-4XRP2N6B.js.map → chunk-QLUXRWKL.js.map} +1 -1
- package/dist/{chunk-OM6RIOA5.cjs → chunk-QR24DJDF.cjs} +13 -13
- package/dist/{chunk-OM6RIOA5.cjs.map → chunk-QR24DJDF.cjs.map} +1 -1
- package/dist/{chunk-YPVQYM3L.js → chunk-QRNYDV5Z.js} +138 -31
- package/dist/chunk-QRNYDV5Z.js.map +1 -0
- package/dist/{chunk-ZOHCFYXE.js → chunk-QT6V3YRH.js} +3 -3
- package/dist/{chunk-ZOHCFYXE.js.map → chunk-QT6V3YRH.js.map} +1 -1
- package/dist/{chunk-5C75HQYQ.js → chunk-RFRM3Q5K.js} +17 -5
- package/dist/chunk-RFRM3Q5K.js.map +1 -0
- package/dist/{chunk-NXIZL7ZZ.js → chunk-RUQS6M7G.js} +6 -6
- package/dist/chunk-RUQS6M7G.js.map +1 -0
- package/dist/{chunk-CI5NPLXX.js → chunk-S3ZRKJHY.js} +3 -3
- package/dist/{chunk-CI5NPLXX.js.map → chunk-S3ZRKJHY.js.map} +1 -1
- package/dist/{chunk-3V6D5DEC.js → chunk-S4KQ5LV4.js} +3 -3
- package/dist/{chunk-3V6D5DEC.js.map → chunk-S4KQ5LV4.js.map} +1 -1
- package/dist/{chunk-CTWZPYJW.js → chunk-TKORQCG4.js} +108 -15
- package/dist/chunk-TKORQCG4.js.map +1 -0
- package/dist/{chunk-2HKIID5K.js → chunk-TKP5T34P.js} +4 -5
- package/dist/chunk-TKP5T34P.js.map +1 -0
- package/dist/{chunk-X2XOQZT3.cjs → chunk-U5W4LKZV.cjs} +13 -9
- package/dist/chunk-U5W4LKZV.cjs.map +1 -0
- package/dist/{chunk-BLBG2VZ5.cjs → chunk-UCQ3BFSY.cjs} +372 -110
- package/dist/chunk-UCQ3BFSY.cjs.map +1 -0
- package/dist/{chunk-CUPJL6TS.js → chunk-V34A6R5V.js} +13 -4
- package/dist/chunk-V34A6R5V.js.map +1 -0
- package/dist/{chunk-LQLVJWUH.js → chunk-VTN3C3CH.js} +7 -7
- package/dist/chunk-VTN3C3CH.js.map +1 -0
- package/dist/{chunk-FY4VY5EV.cjs → chunk-VVQM4CZD.cjs} +20 -20
- package/dist/chunk-VVQM4CZD.cjs.map +1 -0
- package/dist/{chunk-LDCWO5B6.js → chunk-WDAVPX46.js} +3 -3
- package/dist/{chunk-LDCWO5B6.js.map → chunk-WDAVPX46.js.map} +1 -1
- package/dist/{chunk-5GV4JQNA.cjs → chunk-WDBXJOU5.cjs} +55 -43
- package/dist/chunk-WDBXJOU5.cjs.map +1 -0
- package/dist/{chunk-FMPZPOUD.js → chunk-WUFASQUO.js} +3 -3
- package/dist/{chunk-FMPZPOUD.js.map → chunk-WUFASQUO.js.map} +1 -1
- package/dist/{chunk-5ZPRE4CV.cjs → chunk-YDWLUT5V.cjs} +237 -130
- package/dist/chunk-YDWLUT5V.cjs.map +1 -0
- package/dist/{chunk-CVNGKTHO.js → chunk-YMTXMPV6.js} +4 -4
- package/dist/{chunk-CVNGKTHO.js.map → chunk-YMTXMPV6.js.map} +1 -1
- package/dist/{chunk-NDQLPKBX.cjs → chunk-YOALGKRE.cjs} +2092 -1535
- package/dist/chunk-YOALGKRE.cjs.map +1 -0
- package/dist/{chunk-OMQ2NBOR.cjs → chunk-Z3WO6MND.cjs} +27 -27
- package/dist/{chunk-OMQ2NBOR.cjs.map → chunk-Z3WO6MND.cjs.map} +1 -1
- package/dist/{chunk-V2GZBPY2.cjs → chunk-ZI6VQSZA.cjs} +310 -61
- package/dist/chunk-ZI6VQSZA.cjs.map +1 -0
- package/dist/{chunk-ZBV4LQD2.cjs → chunk-ZTAJL4DT.cjs} +4 -4
- package/dist/{chunk-ZBV4LQD2.cjs.map → chunk-ZTAJL4DT.cjs.map} +1 -1
- package/dist/core/index.cjs +27 -28
- package/dist/core/index.d.cts +5 -5
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.js +7 -8
- package/dist/{ddl-3unqC-kg.d.cts → ddl-BG4J805L.d.cts} +3 -3
- package/dist/{ddl-Bc4Dl8fu.d.ts → ddl-CgiS9QLj.d.ts} +3 -3
- package/dist/{define-graph-DBFnc7u_.d.ts → define-graph-BGrJahvp.d.ts} +1 -1
- package/dist/{define-graph-Byslw2OO.d.cts → define-graph-alREY2wj.d.cts} +1 -1
- package/dist/graph-extension/index.cjs +19 -20
- package/dist/graph-extension/index.d.cts +4 -4
- package/dist/graph-extension/index.d.ts +4 -4
- package/dist/graph-extension/index.js +4 -5
- package/dist/graph-merge/index.cjs +103 -104
- package/dist/graph-merge/index.cjs.map +1 -1
- package/dist/graph-merge/index.d.cts +9 -8
- package/dist/graph-merge/index.d.ts +9 -8
- package/dist/graph-merge/index.js +23 -24
- package/dist/graph-merge/index.js.map +1 -1
- package/dist/{index-DHXw7QAl.d.cts → index-BBxZCUdu.d.ts} +37 -7
- package/dist/{index-DQzVJBHa.d.ts → index-C3y_98iN.d.cts} +37 -7
- package/dist/index.cjs +209 -202
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -13
- package/dist/index.d.ts +13 -13
- package/dist/index.js +33 -34
- package/dist/index.js.map +1 -1
- package/dist/indexes/index.cjs +13 -13
- package/dist/indexes/index.d.cts +4 -4
- package/dist/indexes/index.d.ts +4 -4
- package/dist/indexes/index.js +6 -6
- package/dist/interchange/index.cjs +50 -41
- package/dist/interchange/index.cjs.map +1 -1
- package/dist/interchange/index.d.cts +11 -11
- package/dist/interchange/index.d.ts +11 -11
- package/dist/interchange/index.js +24 -15
- package/dist/interchange/index.js.map +1 -1
- package/dist/{manager-U9_zopqr.d.cts → manager-KS7CGQQT.d.cts} +44 -6
- package/dist/{manager-Dl0-er1G.d.ts → manager-YoLEfcc1.d.ts} +44 -6
- package/dist/{materialize-indexes-BM3u0aXE.d.ts → materialize-indexes-Bhhyb1B3.d.ts} +1 -1
- package/dist/{materialize-indexes-DzMCetZe.d.cts → materialize-indexes-OHRWypW6.d.cts} +1 -1
- package/dist/{postgres-DpJqtbSX.d.cts → postgres-DpkW3R5Y.d.cts} +1 -1
- package/dist/{postgres-C5-WMKFA.d.ts → postgres-DwqyIniy.d.ts} +1 -1
- package/dist/profiler/index.d.cts +10 -9
- package/dist/profiler/index.d.ts +10 -9
- package/dist/provenance/index.cjs +38 -38
- package/dist/provenance/index.cjs.map +1 -1
- package/dist/provenance/index.d.cts +7 -7
- package/dist/provenance/index.d.ts +7 -7
- package/dist/provenance/index.js +8 -8
- package/dist/provenance/index.js.map +1 -1
- package/dist/schema/index.cjs +40 -41
- package/dist/schema/index.d.cts +7 -7
- package/dist/schema/index.d.ts +7 -7
- package/dist/schema/index.js +13 -14
- package/dist/{searchable-B4mUXZT6.d.cts → searchable-CIZL8Hyw.d.cts} +2 -2
- package/dist/{searchable-C7jmPNLT.d.ts → searchable-DLWEfC4a.d.ts} +2 -2
- package/dist/{sqlite-Ch5tSYQY.d.ts → sqlite-DY0WODUK.d.cts} +1 -1
- package/dist/{sqlite-Da7jiYu9.d.cts → sqlite-L-VIRzqA.d.ts} +1 -1
- package/dist/{store-view-DdwBNjZQ.d.ts → store-view-66p92IPi.d.ts} +1974 -1751
- package/dist/{store-view-D1F6KqsE.d.cts → store-view-A85FFRnk.d.cts} +1974 -1751
- package/dist/{temporal-CMpigMCW.d.cts → temporal-BNbjXqer.d.cts} +1 -1
- package/dist/{temporal-BtrTYTiB.d.ts → temporal-Bob6Nfbp.d.ts} +1 -1
- package/dist/{types-Dh-EgT-w.d.cts → types-Ch9a0Dx6.d.cts} +483 -20
- package/dist/{types-Dh-EgT-w.d.ts → types-Ch9a0Dx6.d.ts} +483 -20
- package/dist/{types-D2rU5Taq.d.ts → types-ClCzT-dT.d.ts} +1 -1
- package/dist/{types-G4sVM-76.d.cts → types-DeORZhxn.d.cts} +1 -1
- package/dist/{where-DbZ9XDOI.d.cts → where-DPw52ksb.d.cts} +1 -1
- package/dist/{where-B8Y21kig.d.ts → where-kWUZPvEA.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-2HKIID5K.js.map +0 -1
- package/dist/chunk-33PAKPED.cjs.map +0 -1
- package/dist/chunk-42XYPKZU.js.map +0 -1
- package/dist/chunk-4WYFRACU.js.map +0 -1
- package/dist/chunk-5C75HQYQ.js.map +0 -1
- package/dist/chunk-5GV4JQNA.cjs.map +0 -1
- package/dist/chunk-5Q3P6OIC.cjs.map +0 -1
- package/dist/chunk-5ZPRE4CV.cjs.map +0 -1
- package/dist/chunk-64LERBFM.cjs.map +0 -1
- package/dist/chunk-AO2WPYFZ.cjs.map +0 -1
- package/dist/chunk-BLBG2VZ5.cjs.map +0 -1
- package/dist/chunk-CTWZPYJW.js.map +0 -1
- package/dist/chunk-CUPJL6TS.js.map +0 -1
- package/dist/chunk-DMZEVJGL.cjs.map +0 -1
- package/dist/chunk-ECU53PMN.cjs.map +0 -1
- package/dist/chunk-EQOQOT55.js.map +0 -1
- package/dist/chunk-F2KVJ6FF.cjs.map +0 -1
- package/dist/chunk-F7TDKSVB.cjs +0 -61
- package/dist/chunk-F7TDKSVB.cjs.map +0 -1
- package/dist/chunk-FFQGI67R.cjs.map +0 -1
- package/dist/chunk-FY4VY5EV.cjs.map +0 -1
- package/dist/chunk-HHBKGPEI.js.map +0 -1
- package/dist/chunk-JNXZQBN3.js.map +0 -1
- package/dist/chunk-KDRF3NR2.cjs.map +0 -1
- package/dist/chunk-KTBTSHU6.cjs.map +0 -1
- package/dist/chunk-L2BYRYHC.js.map +0 -1
- package/dist/chunk-L5AUCL5P.js.map +0 -1
- package/dist/chunk-LQLVJWUH.js.map +0 -1
- package/dist/chunk-M4GYQF2H.js.map +0 -1
- package/dist/chunk-NDQLPKBX.cjs.map +0 -1
- package/dist/chunk-NXIZL7ZZ.js.map +0 -1
- package/dist/chunk-O2GZM7UK.cjs.map +0 -1
- package/dist/chunk-O7XVCLXW.cjs.map +0 -1
- package/dist/chunk-OYJSYDIH.js.map +0 -1
- package/dist/chunk-RAWG2FEU.js.map +0 -1
- package/dist/chunk-RXOAXO3R.js +0 -59
- package/dist/chunk-RXOAXO3R.js.map +0 -1
- package/dist/chunk-U3YRCZ5L.cjs +0 -12
- package/dist/chunk-UTTW2Q3M.cjs.map +0 -1
- package/dist/chunk-UZLEQFTV.js.map +0 -1
- package/dist/chunk-V2GZBPY2.cjs.map +0 -1
- package/dist/chunk-VC26BUNP.js.map +0 -1
- package/dist/chunk-VGMNGWBR.cjs +0 -12
- package/dist/chunk-X2XOQZT3.cjs.map +0 -1
- package/dist/chunk-XDMPDUKL.cjs.map +0 -1
- package/dist/chunk-YPVQYM3L.js.map +0 -1
- package/dist/chunk-ZGOUVMVS.js.map +0 -1
- package/dist/chunk-ZIRC2U6G.js.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":["rowPropsToObject","filterReservedKeys","RESERVED_NODE_KEYS","RESERVED_EDGE_KEYS","ConfigurationError","runOptionallyInTransaction","lockRecordedGraphWrite","uncapturedGraphWriteLock","advanceRevisionClock","checkDisjointness","checkCardinality","checkUniqueEdge","KindNotFoundError","ValidationError","NodeConstraintNotFoundError","checkWherePredicate","computeUniqueKey","getKindsForUniquenessCheck","createBackendOverlay","validateNodeProps","validateOptionalCanonicalIsoDate","checkUniquenessConstraints","createUniquenessContext","applyNodeInsertSideEffectsBatch","createNodeWriteContext","applyNodeInsertSideEffects","canonicalEqual","NodeNotFoundError","row","applyNodeUpdate","isLiveNodeRow","generateId","runInsertNoReturn","nodeInsertDispatch","DatabaseOperationError","runInsertBatch","runInsertBatchReturning","assertJsonValue","getSearchableFields","getEmbeddingFields","UniquenessError","requireDefined","applyNodeSoftDelete","applyNodeHardDelete","NodeIndexNotFoundError","getDialect","resolveJsonPointer","createSqlSchema","DEFAULT_SQL_SCHEMA","sql","compileNodeIndexFieldKeys","compileIndexWhere","asCompiledRowsSql","getNodeRowsByIds"],"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,GAAWA,kCAAA,CAAiB,GAAA,CAAI,KAAK,CAAA;AAC3C,EAAA,MAAM,KAAA,GAAQC,oCAAA,CAAmB,QAAA,EAAUC,oCAAkB,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,OAAA;AAAA,IACb,SAAA,EAAW,eAAA,CAAgB,GAAA,CAAI,UAAU,CAAA;AAAA,IACzC,OAAA,EAAS,eAAA,CAAgB,GAAA,CAAI,QAAQ,CAAA;AAAA,IACrC,WAAW,GAAA,CAAI,UAAA;AAAA,IACf,WAAW,GAAA,CAAI,UAAA;AAAA,IACf,SAAA,EAAW,eAAA,CAAgB,GAAA,CAAI,UAAU;AAAA,GAC3C;AACF;AASO,SAAS,UAAU,GAAA,EAAoB;AAC5C,EAAA,MAAM,QAAA,GAAWF,kCAAA,CAAiB,GAAA,CAAI,KAAK,CAAA;AAC3C,EAAA,MAAM,KAAA,GAAQC,oCAAA,CAAmB,QAAA,EAAUE,oCAAkB,CAAA;AAC7D,EAAA,OAAO;AAAA,IACL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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,GAAeA,gCAAA,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-UCQ3BFSY.cjs","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,4 +1,4 @@
|
|
|
1
|
-
import { ConfigurationError } from './chunk-
|
|
1
|
+
import { ConfigurationError } from './chunk-4MB3AQAQ.js';
|
|
2
2
|
|
|
3
3
|
// src/utils/sql-errors.ts
|
|
4
4
|
var SQLITE_MISSING_TABLE_PATTERN = "no such table";
|
|
@@ -7,6 +7,7 @@ var SQLITE_NOT_AUTHORIZED_CODE = "SQLITE_AUTH";
|
|
|
7
7
|
var DRIZZLE_QUERY_ERROR_PREFIX = "Failed query:";
|
|
8
8
|
var POSTGRES_UNDEFINED_RELATION_PATTERN = /\b(?:relation|table)\s+"[^"]+"\s+does not exist\b/i;
|
|
9
9
|
var POSTGRES_UNDEFINED_TABLE_CODE = "42P01";
|
|
10
|
+
var POSTGRES_UNIQUE_VIOLATION_CODE = "23505";
|
|
10
11
|
function* errorChain(error) {
|
|
11
12
|
const seen = /* @__PURE__ */ new Set();
|
|
12
13
|
let current = error;
|
|
@@ -74,6 +75,14 @@ function isMissingTableError(error) {
|
|
|
74
75
|
}
|
|
75
76
|
return false;
|
|
76
77
|
}
|
|
78
|
+
function isPostgresUniqueViolationError(error) {
|
|
79
|
+
for (const link of errorChain(error)) {
|
|
80
|
+
if (canReadProperty(link) && Reflect.get(link, "code") === POSTGRES_UNIQUE_VIOLATION_CODE) {
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
77
86
|
function isSqliteNotAuthorizedError(error) {
|
|
78
87
|
for (const link of errorChain(error)) {
|
|
79
88
|
if (sqliteErrorCode(link) === SQLITE_NOT_AUTHORIZED_CODE) return true;
|
|
@@ -120,6 +129,6 @@ function parseDimensionMismatch(error) {
|
|
|
120
129
|
return void 0;
|
|
121
130
|
}
|
|
122
131
|
|
|
123
|
-
export { isInsufficientResourcesError, isMissingTableError, isSqliteNotAuthorizedError, parseDimensionMismatch, withRecordedRelationsPrecondition };
|
|
124
|
-
//# sourceMappingURL=chunk-
|
|
125
|
-
//# sourceMappingURL=chunk-
|
|
132
|
+
export { isInsufficientResourcesError, isMissingTableError, isPostgresUniqueViolationError, isSqliteNotAuthorizedError, parseDimensionMismatch, withRecordedRelationsPrecondition };
|
|
133
|
+
//# sourceMappingURL=chunk-V34A6R5V.js.map
|
|
134
|
+
//# sourceMappingURL=chunk-V34A6R5V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/sql-errors.ts"],"names":[],"mappings":";;;AAuBA,IAAM,4BAAA,GAA+B,eAAA;AACrC,IAAM,yBAAA,GAA4B,cAAA;AAClC,IAAM,0BAAA,GAA6B,aAAA;AACnC,IAAM,0BAAA,GAA6B,eAAA;AACnC,IAAM,mCAAA,GACJ,oDAAA;AASF,IAAM,6BAAA,GAAgC,OAAA;AACtC,IAAM,8BAAA,GAAiC,OAAA;AAiBvC,UAAU,WAAW,KAAA,EAAgD;AACnE,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAa;AAC9B,EAAA,IAAI,OAAA,GAAmB,KAAA;AACvB,EAAA,OAAO,OAAA,KAAY,UAAa,OAAA,KAAY,IAAA,IAAQ,CAAC,IAAA,CAAK,GAAA,CAAI,OAAO,CAAA,EAAG;AACtE,IAAA,IAAA,CAAK,IAAI,OAAO,CAAA;AAChB,IAAA,MAAM,OAAA;AACN,IAAA,OAAA,GACE,gBAAgB,OAAO,CAAA,GAAI,QAAQ,GAAA,CAAI,OAAA,EAAS,OAAO,CAAA,GAAI,MAAA;AAAA,EAC/D;AACF;AAEA,SAAS,gBAAgB,KAAA,EAAiC;AACxD,EAAA,OACG,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAS,OAAO,KAAA,KAAU,UAAA;AAEtE;AAMA,SAAS,yBAAyB,IAAA,EAAwB;AACxD,EAAA,OACE,gBAAgB,IAAI,CAAA,IACpB,QAAQ,GAAA,CAAI,IAAA,EAAM,MAAM,CAAA,KAAM,6BAAA;AAElC;AAEA,SAAS,gBAAgB,IAAA,EAAmC;AAC1D,EAAA,IAAI,OAAO,IAAA,KA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,KAAA,GAAQ,0BAAA,CAA2B,IAAA,CAAK,OAAO,CAAA;AACrD,IAAA,IAAI,KAAA,EAAO;AACT,MAAA,OAAO;AAAA,QACL,QAAA,EAAU,MAAA,CAAO,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,QACzB,MAAA,EAAQ,MAAM,CAAC,CAAA,KAAM,SAAY,MAAA,GAAY,MAAA,CAAO,KAAA,CAAM,CAAC,CAAC;AAAA,OAC9D;AAAA,IACF;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-V34A6R5V.js","sourcesContent":["/**\n * Cross-dialect detection of \"this relation does not exist yet\" errors.\n *\n * Shared so the schema bootstrap (`loadActiveSchemaWithBootstrap`) and\n * the durable contribution-materialization gate (#135) agree on what a\n * missing-table failure looks like, and — critically — so neither one\n * swallows a genuine system fault (connection/permission/driver error)\n * as a benign \"not bootstrapped yet\".\n *\n * Detection walks the error's `cause` chain because Drizzle (>= the\n * `DrizzleQueryError` era, drizzle-orm ≥ 0.36) wraps every failure from a\n * query-builder call (`db.select()`, `db.insert()`, …): the wrapper's\n * `.message` becomes the failed query text and the real driver error —\n * which carries both the missing-relation text and the SQLSTATE — is\n * preserved on `.cause`. node-postgres / postgres-js nest the pg error\n * one link deep; better-sqlite3 throws it unwrapped; raw `client.query()`\n * fast paths surface it directly. Walking the chain makes the check\n * wrapper- and driver-agnostic instead of only matching the outermost\n * `.message`, which on Postgres is just the SQL string.\n */\n\nimport { ConfigurationError } from \"../errors\";\n\nconst SQLITE_MISSING_TABLE_PATTERN = \"no such table\";\nconst SQLITE_GENERIC_ERROR_CODE = \"SQLITE_ERROR\";\nconst SQLITE_NOT_AUTHORIZED_CODE = \"SQLITE_AUTH\";\nconst DRIZZLE_QUERY_ERROR_PREFIX = \"Failed query:\";\nconst POSTGRES_UNDEFINED_RELATION_PATTERN =\n /\\b(?:relation|table)\\s+\"[^\"]+\"\\s+does not exist\\b/i;\n\n/**\n * SQLSTATE for PostgreSQL `undefined_table`. Preferred over the\n * human-readable message: it is locale-independent (the \"... does not\n * exist\" text is translated under a non-English `lc_messages`) and is\n * preserved on the underlying driver error even when Drizzle overwrites\n * `.message` with the query text.\n */\nconst POSTGRES_UNDEFINED_TABLE_CODE = \"42P01\";\nconst POSTGRES_UNIQUE_VIOLATION_CODE = \"23505\";\n\n/**\n * Yields an error and each error reachable by following `.cause`,\n * outermost first. `seen` guards the pathological cyclic-cause case so a\n * self-referential chain can't spin forever.\n *\n * The walk intentionally follows `.cause` through *non-`Error`* links, not just\n * `Error` instances: postgres-js surfaces its driver error as a plain object\n * (message + SQLSTATE `code`) on a Drizzle wrapper's `.cause`, so stopping at\n * the first non-`Error` link would miss it (see the postgres-js test). A plain\n * object is classified by its locale-independent SQLSTATE alone\n * ({@link isPostgresUndefinedTable}); the looser SQLite message substring is\n * consulted only for `Error` instances and raw strings\n * ({@link missingTableMessage}), so an unrelated object in a cause chain that\n * merely mentions one of those phrases is not mistaken for a missing table.\n */\nfunction* errorChain(error: unknown): Generator<unknown, void, void> {\n const seen = new Set<unknown>();\n let current: unknown = error;\n while (current !== undefined && current !== null && !seen.has(current)) {\n seen.add(current);\n yield current;\n current =\n canReadProperty(current) ? Reflect.get(current, \"cause\") : undefined;\n }\n}\n\nfunction canReadProperty(value: unknown): value is object {\n return (\n (typeof value === \"object\" && value !== null) || typeof value === \"function\"\n );\n}\n\n/**\n * Whether a single chain link is a PostgreSQL `undefined_table` failure,\n * identified by its SQLSTATE rather than a message substring.\n */\nfunction isPostgresUndefinedTable(link: unknown): boolean {\n return (\n canReadProperty(link) &&\n Reflect.get(link, \"code\") === POSTGRES_UNDEFINED_TABLE_CODE\n );\n}\n\nfunction messageProperty(link: unknown): string | undefined {\n if (typeof link === \"string\") return link;\n if (link instanceof Error) return link.message;\n const message =\n canReadProperty(link) ?\n (Reflect.get(link, \"message\") as unknown)\n : undefined;\n return typeof message === \"string\" ? message : undefined;\n}\n\nfunction errorMessage(link: unknown): string {\n return messageProperty(link) ?? String(link);\n}\n\n/**\n * The message a SQLite missing-table substring match may be tested against — but\n * only for `Error` instances and raw `string` links, never an arbitrary plain\n * object.\n *\n * Generic \"does not exist\" is deliberately not substring-matched: PostgreSQL uses\n * that phrase for undefined columns, functions, types, and relations. PostgreSQL\n * missing tables are classified by SQLSTATE 42P01 when available, or by the\n * narrower driver-message shape `relation/table \"...\" does not exist` when a\n * bring-your-own driver omits SQLSTATE. SQLite does not expose a portable\n * SQLSTATE here, so the narrow \"no such table\" engine message is still accepted.\n */\nfunction missingTableMessage(link: unknown): string | undefined {\n return typeof link === \"string\" || link instanceof Error ?\n messageProperty(link)\n : undefined;\n}\n\nfunction sqliteErrorCode(link: unknown): unknown {\n if (!canReadProperty(link)) return undefined;\n return Reflect.get(link, \"code\");\n}\n\n/**\n * Cloudflare D1 / Durable Objects may surface a missing-table failure as the\n * generic SQLite code with no detail. Accept the bare marker, but do not\n * substring-match detailed `SQLITE_ERROR: ...` failures: those include syntax\n * errors and bind-limit faults that must stay loud.\n */\nfunction isBareSqliteErrorMarker(link: unknown): boolean {\n const message = messageProperty(link);\n if (message === SQLITE_GENERIC_ERROR_CODE) return true;\n if (sqliteErrorCode(link) !== SQLITE_GENERIC_ERROR_CODE) return false;\n return (\n message === undefined ||\n message === SQLITE_GENERIC_ERROR_CODE ||\n message.includes(SQLITE_MISSING_TABLE_PATTERN)\n );\n}\n\nfunction isPostgresUndefinedRelationMessage(link: unknown): boolean {\n const message = errorMessage(link);\n if (message.startsWith(DRIZZLE_QUERY_ERROR_PREFIX)) return false;\n return POSTGRES_UNDEFINED_RELATION_PATTERN.test(message);\n}\n\n/**\n * Whether any link in the cause chain is a PostgreSQL \"insufficient\n * resources\" failure (SQLSTATE class 53: disk_full, out_of_memory,\n * configuration_limit_exceeded, ...). Parallel index builds surface\n * shared-memory exhaustion this way (53100 from dsm_impl_posix on hosts\n * with a small /dev/shm); callers retry such work with parallelism\n * disabled. Identified by the locale-independent 5-character SQLSTATE\n * prefix only — never by message text.\n */\nexport function isInsufficientResourcesError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (!canReadProperty(link)) continue;\n const code: unknown = Reflect.get(link, \"code\");\n if (typeof code === \"string\" && code.length === 5 && code.startsWith(\"53\"))\n return true;\n }\n return false;\n}\n\nexport function isMissingTableError(error: unknown): boolean {\n // SQLSTATE 42P01 is locale-independent and structural, so it is honored on\n // *every* link — including a plain driver-error object reached only by walking\n // through a non-`Error` `.cause` (postgres-js).\n //\n // The SQLite message substring is honored only while every prior link in the\n // chain was an `Error` (or the top-level string) — the reach of the\n // pre-broadening walk, which stopped at the first non-`Error` `.cause`.\n let everyPriorLinkWasError = true;\n for (const link of errorChain(error)) {\n if (isPostgresUndefinedTable(link)) return true;\n if (isPostgresUndefinedRelationMessage(link)) return true;\n if (isBareSqliteErrorMarker(link)) return true;\n if (everyPriorLinkWasError) {\n const message = missingTableMessage(link);\n if (message?.includes(SQLITE_MISSING_TABLE_PATTERN) === true) {\n return true;\n }\n }\n if (!(link instanceof Error)) everyPriorLinkWasError = false;\n }\n return false;\n}\n\n/**\n * Whether PostgreSQL reported a uniqueness violation anywhere in a driver's\n * error-cause chain. `CREATE TABLE IF NOT EXISTS` can surface this code when\n * two sessions concurrently insert the same internal catalog rows; callers\n * handling that specific idempotent DDL race can retry once after the winner\n * commits.\n */\nexport function isPostgresUniqueViolationError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (\n canReadProperty(link) &&\n Reflect.get(link, \"code\") === POSTGRES_UNIQUE_VIOLATION_CODE\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Whether SQLite rejected a statement through its authorizer. Cloudflare D1\n * and Durable Objects surface this as `not authorized: SQLITE_AUTH`, usually on\n * a Drizzle wrapper's `.cause`; native drivers may instead expose\n * `code: \"SQLITE_AUTH\"`. Both shapes are structural enough to distinguish from\n * an unrelated permission or connection failure.\n */\nexport function isSqliteNotAuthorizedError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (sqliteErrorCode(link) === SQLITE_NOT_AUTHORIZED_CODE) return true;\n const message = messageProperty(link);\n if (\n message?.includes(SQLITE_NOT_AUTHORIZED_CODE) === true &&\n message.toLowerCase().includes(\"not authorized\")\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction historyMissingRecordedRelationsError(\n details: Record<string, unknown>,\n cause: unknown,\n): ConfigurationError {\n return new ConfigurationError(\n \"history: true requires the recorded-time relations to exist, but a recorded relation is missing.\",\n details,\n {\n cause,\n suggestion:\n \"Create the recorded-time relations (typegraph_recorded_nodes, typegraph_recorded_edges, typegraph_recorded_clock) — e.g. re-run the generated migration SQL — on this database before enabling history capture.\",\n },\n );\n}\n\n/**\n * Converts missing recorded-relation failures into the actionable precondition\n * error used by construction-time history checks. Capture paths use this after\n * the live write has already succeeded inside the same transaction; recorded\n * read paths use it when query/schema swapping reaches a recorded table that\n * has not been materialized yet.\n */\nexport async function withRecordedRelationsPrecondition<T>(\n promise: Promise<T>,\n details: Record<string, unknown>,\n): Promise<T> {\n try {\n return await promise;\n } catch (error) {\n if (!isMissingTableError(error)) throw error;\n throw historyMissingRecordedRelationsError(\n { ...details, code: \"RECORDED_RELATIONS_MISSING\" },\n error,\n );\n }\n}\n\n/**\n * Engine \"vector dimension mismatch\" message shapes. pgvector:\n * `expected 384 dimensions, not 512`; libSQL / sqlite-vec surface a similar\n * `expected N … got/not M`. The first capture is the dimension the *stored*\n * column expects; the optional second is the dimension that was *attempted*.\n */\nconst DIMENSION_MISMATCH_PATTERN =\n /expected (\\d+) dimensions(?:[,\\s]+(?:not|got|but got|but)\\s*(\\d+))?/i;\n\n/**\n * Parses an engine vector-dimension-mismatch error into `{ expected, actual }`\n * by walking the `.cause` chain (drivers wrap the real error). `expected` is\n * the stored column's dimension; `actual` (when the message includes it) is the\n * attempted vector's dimension. Returns `undefined` for unrelated errors.\n */\nexport function parseDimensionMismatch(\n error: unknown,\n): { expected: number; actual: number | undefined } | undefined {\n for (const link of errorChain(error)) {\n const message = errorMessage(link);\n const match = DIMENSION_MISMATCH_PATTERN.exec(message);\n if (match) {\n return {\n expected: Number(match[1]),\n actual: match[2] === undefined ? undefined : Number(match[2]),\n };\n }\n }\n return undefined;\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { createSqliteBackend } from './chunk-
|
|
2
|
-
import { sqliteVecStrategy } from './chunk-
|
|
3
|
-
import { tables2, generateSqliteDDL } from './chunk-
|
|
4
|
-
import { wrapWithManagedClose } from './chunk-
|
|
5
|
-
import { ConfigurationError } from './chunk-
|
|
1
|
+
import { createSqliteBackend } from './chunk-4GUTQPVO.js';
|
|
2
|
+
import { sqliteVecStrategy } from './chunk-4QIKLIGG.js';
|
|
3
|
+
import { tables2, generateSqliteDDL } from './chunk-BGYJW37L.js';
|
|
4
|
+
import { wrapWithManagedClose } from './chunk-55ITBQJI.js';
|
|
5
|
+
import { ConfigurationError } from './chunk-4MB3AQAQ.js';
|
|
6
6
|
import { createRequire } from 'module';
|
|
7
7
|
import Database from 'better-sqlite3';
|
|
8
8
|
import { drizzle } from 'drizzle-orm/better-sqlite3';
|
|
@@ -179,5 +179,5 @@ function tryLoadSqliteVec(sqlite) {
|
|
|
179
179
|
}
|
|
180
180
|
|
|
181
181
|
export { DEFAULT_LOCAL_SQLITE_PRAGMAS, createLocalSqliteBackend };
|
|
182
|
-
//# sourceMappingURL=chunk-
|
|
183
|
-
//# sourceMappingURL=chunk-
|
|
182
|
+
//# sourceMappingURL=chunk-VTN3C3CH.js.map
|
|
183
|
+
//# sourceMappingURL=chunk-VTN3C3CH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/backend/sqlite/local-options.ts","../src/backend/sqlite/local.ts"],"names":["tables"],"mappings":";;;;;;;;;;AA8BO,IAAM,4BAAA,GACX;AAAA,EACE,WAAA,EAAa,KAAA;AAAA,EACb,WAAA,EAAa,QAAA;AAAA,EACb,aAAA,EAAe,GAAA;AAAA,EACf,YAAA,EAAc,MAAA;AAAA,EACd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A,IACE,OAAO,OAAA,KAAY,QAAA,IACnB,OAAA,KAAY,IAAA,IACZ,UAAU,OAAA,IACV,OAAO,OAAA,CAAQ,IAAA,KAAS,UAAA,EACxB;AACA,MAAC,OAAA,CAAsD,KAAK,MAAM,CAAA;AAClE,MAAA,OAAO,IAAA;AAAA,IACT;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"chunk-VTN3C3CH.js","sourcesContent":["/** Journal modes accepted by local SQLite connections. */\nexport type LocalSqliteJournalMode =\n \"wal\" | \"delete\" | \"truncate\" | \"persist\" | \"memory\" | \"off\";\n\n/** Synchronous levels accepted by local SQLite connections. */\nexport type LocalSqliteSynchronousMode = \"off\" | \"normal\" | \"full\" | \"extra\";\n\n/** Connection pragmas applied when TypeGraph opens a local SQLite database. */\nexport type LocalSqlitePragmaOptions = Readonly<{\n /** `PRAGMA journal_mode`. Default: `\"wal\"` (no-op on `\":memory:\"`). */\n journalMode?: LocalSqliteJournalMode;\n /** `PRAGMA synchronous`. Default: `\"normal\"`. */\n synchronous?: LocalSqliteSynchronousMode;\n /** `PRAGMA busy_timeout`, in milliseconds. Default: `5000`. */\n busyTimeoutMs?: number;\n /**\n * `PRAGMA cache_size`, expressed as a negative KiB value. Positive values\n * mean pages in SQLite and are rejected to prevent accidental oversizing.\n */\n cacheSizeKib?: number | undefined;\n /** `PRAGMA mmap_size`, in non-negative bytes. */\n mmapSizeBytes?: number | undefined;\n /**\n * `PRAGMA wal_autocheckpoint`, in WAL pages. Use `0` to disable automatic\n * checkpoints and run them explicitly after controlled bulk loads.\n */\n walAutocheckpointPages?: number | undefined;\n}>;\n\n/** Defaults for TypeGraph-owned local SQLite connections. */\nexport const DEFAULT_LOCAL_SQLITE_PRAGMAS: Required<LocalSqlitePragmaOptions> =\n {\n journalMode: \"wal\",\n synchronous: \"normal\",\n busyTimeoutMs: 5000,\n cacheSizeKib: undefined,\n mmapSizeBytes: undefined,\n walAutocheckpointPages: undefined,\n };\n","/**\n * Local SQLite backend using better-sqlite3.\n *\n * This module depends on the `better-sqlite3` native addon and should only\n * be imported in Node.js environments. For bundler-friendly SQLite DDL\n * generation and Drizzle backend creation, import from `@nicia-ai/typegraph/adapters/drizzle/sqlite`.\n *\n * @example In-memory database (default)\n * ```typescript\n * import { createLocalSqliteBackend } from \"@nicia-ai/typegraph/adapters/drizzle/sqlite/local\";\n *\n * const { backend, db } = createLocalSqliteBackend();\n * const store = createStore(graph, backend);\n * ```\n *\n * @example File-based database for persistent local development\n * ```typescript\n * import { createLocalSqliteBackend } from \"@nicia-ai/typegraph/adapters/drizzle/sqlite/local\";\n *\n * const { backend, db } = createLocalSqliteBackend({ path: \"./dev.db\" });\n * const store = createStore(graph, backend);\n * ```\n */\nimport { createRequire } from \"node:module\";\n\nimport Database from \"better-sqlite3\";\nimport {\n type BetterSQLite3Database,\n drizzle,\n} from \"drizzle-orm/better-sqlite3\";\n\nimport { ConfigurationError } from \"../../errors\";\nimport { sqliteVecStrategy } from \"../../query/dialect/vector/sqlite-vec-strategy\";\nimport { generateSqliteDDL } from \"../drizzle/ddl\";\nimport { type AnySqliteDatabase } from \"../drizzle/execution\";\nexport type { AnySqliteDatabase } from \"../drizzle/execution\";\nimport {\n createSqliteBackend,\n type SqliteTables,\n tables as defaultTables,\n} from \"../drizzle/sqlite\";\nimport {\n DEFAULT_LOCAL_SQLITE_PRAGMAS,\n type LocalSqliteJournalMode,\n type LocalSqlitePragmaOptions,\n type LocalSqliteSynchronousMode,\n} from \"./local-options\";\n\nexport {\n DEFAULT_LOCAL_SQLITE_PRAGMAS,\n type LocalSqliteJournalMode,\n type LocalSqlitePragmaOptions,\n type LocalSqliteSynchronousMode,\n} from \"./local-options\";\nimport {\n type AdapterBackend,\n type BackendCapabilities,\n wrapWithManagedClose,\n} from \"../types\";\n\nexport type {\n ContributionDiagnostic,\n ContributionDiagnosticState,\n ContributionRepairEntry,\n ContributionRepairResult,\n} from \"../types\";\n\nconst nodeRequire = createRequire(import.meta.url);\n\n// ============================================================\n// Native Addon Helpers\n// ============================================================\n\ntype NodeModuleVersionMismatch = Readonly<{\n compiled: number;\n required: number;\n}>;\n\nfunction getUnknownErrorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\nfunction parseNodeModuleVersionMismatchMessage(\n message: string,\n): NodeModuleVersionMismatch | undefined {\n const regexp =\n /NODE_MODULE_VERSION (?<compiled>\\d+)[\\s\\S]*?NODE_MODULE_VERSION (?<required>\\d+)/;\n const match = regexp.exec(message);\n if (!match?.groups) return undefined;\n\n const compiled = Number(match.groups[\"compiled\"]);\n const required = Number(match.groups[\"required\"]);\n\n if (!Number.isFinite(compiled) || !Number.isFinite(required))\n return undefined;\n\n return { compiled, required };\n}\n\nfunction createDatabase(path: string): Database.Database {\n try {\n return new Database(path);\n } catch (error) {\n const message = getUnknownErrorMessage(error);\n const mismatch = parseNodeModuleVersionMismatchMessage(message);\n if (!mismatch) throw error;\n\n throw new ConfigurationError(\n [\n \"Failed to load better-sqlite3 native addon.\",\n `It was compiled for NODE_MODULE_VERSION ${mismatch.compiled}, but this Node.js runtime requires ${mismatch.required}.`,\n \"This usually happens after switching Node versions without rebuilding native dependencies.\",\n \"Rebuild with: pnpm rebuild better-sqlite3 (or npm rebuild better-sqlite3).\",\n ].join(\" \"),\n {\n nodeVersion: process.version,\n nodeModuleVersion: process.versions.modules,\n compiledNodeModuleVersion: mismatch.compiled,\n requiredNodeModuleVersion: mismatch.required,\n },\n { cause: error },\n );\n }\n}\n\n// ============================================================\n// Types\n// ============================================================\n\nconst LOCAL_SQLITE_JOURNAL_MODES: readonly LocalSqliteJournalMode[] = [\n \"wal\",\n \"delete\",\n \"truncate\",\n \"persist\",\n \"memory\",\n \"off\",\n];\n\nconst LOCAL_SQLITE_SYNCHRONOUS_MODES: readonly LocalSqliteSynchronousMode[] = [\n \"off\",\n \"normal\",\n \"full\",\n \"extra\",\n];\n\nconst SQLITE_MAX_WAL_AUTOCHECKPOINT_PAGES = 2_147_483_647;\n\nfunction applyConnectionPragmas(\n sqlite: Database.Database,\n pragmas: LocalSqlitePragmaOptions | false | undefined,\n): void {\n if (pragmas === false) return;\n const resolved: Required<LocalSqlitePragmaOptions> = {\n ...DEFAULT_LOCAL_SQLITE_PRAGMAS,\n ...pragmas,\n };\n\n // Runtime guards mirror the compile-time unions: pragma values are spliced\n // into pragma statements, so reject anything outside the allowlists rather\n // than forwarding it to SQLite.\n if (!LOCAL_SQLITE_JOURNAL_MODES.includes(resolved.journalMode)) {\n throw new ConfigurationError(\n `Invalid journalMode pragma: ${resolved.journalMode}. ` +\n `Expected one of: ${LOCAL_SQLITE_JOURNAL_MODES.join(\", \")}.`,\n { journalMode: resolved.journalMode },\n );\n }\n if (!LOCAL_SQLITE_SYNCHRONOUS_MODES.includes(resolved.synchronous)) {\n throw new ConfigurationError(\n `Invalid synchronous pragma: ${resolved.synchronous}. ` +\n `Expected one of: ${LOCAL_SQLITE_SYNCHRONOUS_MODES.join(\", \")}.`,\n { synchronous: resolved.synchronous },\n );\n }\n if (\n !Number.isSafeInteger(resolved.busyTimeoutMs) ||\n resolved.busyTimeoutMs < 0\n ) {\n throw new ConfigurationError(\n `Invalid busyTimeoutMs pragma: ${String(resolved.busyTimeoutMs)}. ` +\n \"Expected a non-negative integer number of milliseconds.\",\n { busyTimeoutMs: resolved.busyTimeoutMs },\n );\n }\n if (\n resolved.cacheSizeKib !== undefined &&\n (!Number.isSafeInteger(resolved.cacheSizeKib) || resolved.cacheSizeKib >= 0)\n ) {\n throw new ConfigurationError(\n `Invalid cacheSizeKib pragma: ${String(resolved.cacheSizeKib)}. ` +\n \"Expected a negative safe integer — SQLite's own cache_size pragma \" +\n \"interprets a positive value as a page count, not KiB, so a caller \" +\n 'who passes e.g. 131072 meaning \"131072 KiB\" silently gets ' +\n \"131072 pages (~512MiB at the default 4KiB page size) instead.\",\n { cacheSizeKib: resolved.cacheSizeKib },\n );\n }\n if (\n resolved.mmapSizeBytes !== undefined &&\n (!Number.isSafeInteger(resolved.mmapSizeBytes) ||\n resolved.mmapSizeBytes < 0)\n ) {\n throw new ConfigurationError(\n `Invalid mmapSizeBytes pragma: ${String(resolved.mmapSizeBytes)}. ` +\n \"Expected a non-negative safe integer number of bytes.\",\n { mmapSizeBytes: resolved.mmapSizeBytes },\n );\n }\n if (\n resolved.walAutocheckpointPages !== undefined &&\n (!Number.isSafeInteger(resolved.walAutocheckpointPages) ||\n resolved.walAutocheckpointPages < 0 ||\n resolved.walAutocheckpointPages > SQLITE_MAX_WAL_AUTOCHECKPOINT_PAGES)\n ) {\n throw new ConfigurationError(\n `Invalid walAutocheckpointPages pragma: ${String(resolved.walAutocheckpointPages)}. ` +\n `Expected an integer between 0 and ${SQLITE_MAX_WAL_AUTOCHECKPOINT_PAGES} ` +\n \"WAL pages (0 disables automatic checkpointing entirely).\",\n { walAutocheckpointPages: resolved.walAutocheckpointPages },\n );\n }\n\n // \":memory:\" databases always journal in memory; SQLite answers the WAL\n // request with \"memory\" instead of erroring, so no special-casing needed.\n sqlite.pragma(`journal_mode = ${resolved.journalMode}`);\n sqlite.pragma(`synchronous = ${resolved.synchronous}`);\n sqlite.pragma(`busy_timeout = ${resolved.busyTimeoutMs}`);\n if (resolved.cacheSizeKib !== undefined) {\n sqlite.pragma(`cache_size = ${resolved.cacheSizeKib}`);\n }\n if (resolved.mmapSizeBytes !== undefined) {\n sqlite.pragma(`mmap_size = ${resolved.mmapSizeBytes}`);\n }\n if (resolved.walAutocheckpointPages !== undefined) {\n sqlite.pragma(`wal_autocheckpoint = ${resolved.walAutocheckpointPages}`);\n }\n}\n\n/**\n * Options for creating a local SQLite backend.\n */\nexport type LocalSqliteBackendOptions = Readonly<{\n /**\n * Path to the SQLite database file.\n * Defaults to \":memory:\" for an in-memory database.\n */\n path?: string;\n\n /**\n * Connection pragmas applied at open. Defaults to\n * {@link DEFAULT_LOCAL_SQLITE_PRAGMAS} (WAL, `synchronous=NORMAL`, 5s busy\n * timeout, and SQLite's own tiny built-in page cache / disabled mmap\n * left untouched). Individual values merge over the defaults; pass\n * `false` to skip pragma configuration entirely and keep the driver\n * defaults (rollback journal, `synchronous=FULL`, and better-sqlite3's\n * own 5s busy timeout from its `timeout` constructor option). Set\n * `cacheSizeKib`/`mmapSizeBytes` explicitly once a database's working\n * set is known to exceed SQLite's 2MiB default cache — otherwise every\n * query pays a fresh disk read per page past that tiny working set. Set\n * `walAutocheckpointPages` explicitly for a bulk-insert-heavy workload —\n * SQLite's own default checkpoints every ~4MiB of WAL growth, which gets\n * more expensive as the database file grows over a large load.\n */\n pragmas?: LocalSqlitePragmaOptions | false;\n\n /**\n * Custom table definitions.\n * Defaults to standard TypeGraph table names.\n */\n tables?: SqliteTables;\n\n /**\n * Override specific backend capabilities — e.g. to simulate an engine-level\n * gap like missing SQL window functions in tests. Forwarded to\n * createSqliteBackend.\n */\n capabilities?: Partial<BackendCapabilities>;\n}>;\n\n/**\n * Result of creating a local SQLite backend.\n */\nexport type LocalSqliteBackendResult = Readonly<{\n /**\n * The GraphBackend instance for use with createStore.\n */\n backend: AdapterBackend<AnySqliteDatabase>;\n\n /**\n * The underlying Drizzle database instance.\n * Useful for direct SQL access or cleanup.\n */\n db: BetterSQLite3Database;\n}>;\n\n// ============================================================\n// Factory Function\n// ============================================================\n\n/**\n * Creates a SQLite backend with minimal configuration.\n *\n * This is a convenience function for local development and testing.\n * It handles database creation, schema migration, and backend setup.\n *\n * For production deployments or custom configurations, use createSqliteBackend\n * directly with your own Drizzle database instance.\n *\n * @param options - Configuration options\n * @returns Backend and database instances\n *\n * @example In-memory database (default)\n * ```typescript\n * const { backend } = createLocalSqliteBackend();\n * const store = createStore(graph, backend);\n * ```\n *\n * @example File-based database\n * ```typescript\n * const { backend, db } = createLocalSqliteBackend({ path: \"./data.db\" });\n * const store = createStore(graph, backend);\n * ```\n */\nexport function createLocalSqliteBackend(\n options: LocalSqliteBackendOptions = {},\n): LocalSqliteBackendResult {\n const path = options.path ?? \":memory:\";\n const tables = options.tables ?? defaultTables;\n\n const sqlite = createDatabase(path);\n try {\n applyConnectionPragmas(sqlite, options.pragmas);\n\n // Best-effort: load sqlite-vec so embedding fields are persisted to\n // per-`(kind, field)` `vec0` storage. Without it, nodes with\n // `embedding()` fields validate and insert but their vectors are silently\n // dropped. When the user has installed sqlite-vec as a peer dep we load\n // it and wire the strategy; otherwise we proceed without vector support.\n const hasSqliteVec = tryLoadSqliteVec(sqlite);\n\n const db = drizzle(sqlite);\n\n // Generate and execute DDL from schema\n const ddlStatements = generateSqliteDDL(tables);\n for (const statement of ddlStatements) {\n sqlite.exec(statement);\n }\n\n const backend = createSqliteBackend(db, {\n executionProfile: {\n isSync: true,\n },\n tables,\n ...(hasSqliteVec ? { vector: sqliteVecStrategy } : {}),\n capabilities: {\n ...options.capabilities,\n graphAnalytics: {\n supported:\n options.capabilities?.graphAnalytics?.supported ??\n options.capabilities?.transactions !== false,\n mathFunctions:\n options.capabilities?.graphAnalytics?.mathFunctions ?? true,\n },\n },\n });\n const managedBackend = wrapWithManagedClose(backend, () => {\n sqlite.close();\n });\n\n return { backend: managedBackend, db };\n } catch (error) {\n try {\n sqlite.close();\n } catch {\n // Preserve the provisioning error; a cleanup failure is secondary.\n }\n throw error;\n }\n}\n\nfunction tryLoadSqliteVec(sqlite: Database.Database): boolean {\n try {\n // `sqlite-vec` is an optional peer dep; resolved via createRequire so\n // bundlers don't mark it as a hard import. Node resolves the package\n // only when it's actually installed.\n const module_: unknown = nodeRequire(\"sqlite-vec\");\n if (\n typeof module_ === \"object\" &&\n module_ !== null &&\n \"load\" in module_ &&\n typeof module_.load === \"function\"\n ) {\n (module_ as { load: (db: Database.Database) => void }).load(sqlite);\n return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n"]}
|