@nicia-ai/typegraph 0.32.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (264) hide show
  1. package/README.md +51 -0
  2. package/dist/backend/postgres/index.cjs +36 -19
  3. package/dist/backend/postgres/index.d.cts +6 -6
  4. package/dist/backend/postgres/index.d.ts +6 -6
  5. package/dist/backend/postgres/index.js +14 -9
  6. package/dist/backend/postgres/pglite.cjs +18 -13
  7. package/dist/backend/postgres/pglite.cjs.map +1 -1
  8. package/dist/backend/postgres/pglite.d.cts +3 -3
  9. package/dist/backend/postgres/pglite.d.ts +3 -3
  10. package/dist/backend/postgres/pglite.js +14 -9
  11. package/dist/backend/postgres/pglite.js.map +1 -1
  12. package/dist/backend/sqlite/index.cjs +34 -17
  13. package/dist/backend/sqlite/index.d.cts +7 -7
  14. package/dist/backend/sqlite/index.d.ts +7 -7
  15. package/dist/backend/sqlite/index.js +13 -8
  16. package/dist/backend/sqlite/libsql.cjs +19 -14
  17. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  18. package/dist/backend/sqlite/libsql.d.cts +12 -5
  19. package/dist/backend/sqlite/libsql.d.ts +12 -5
  20. package/dist/backend/sqlite/libsql.js +15 -10
  21. package/dist/backend/sqlite/libsql.js.map +1 -1
  22. package/dist/backend/sqlite/local.cjs +19 -14
  23. package/dist/backend/sqlite/local.cjs.map +1 -1
  24. package/dist/backend/sqlite/local.d.cts +3 -3
  25. package/dist/backend/sqlite/local.d.ts +3 -3
  26. package/dist/backend/sqlite/local.js +14 -9
  27. package/dist/backend/sqlite/local.js.map +1 -1
  28. package/dist/chunk-2EBMPJBO.js +16 -0
  29. package/dist/chunk-2EBMPJBO.js.map +1 -0
  30. package/dist/{chunk-CFNT3ITG.cjs → chunk-2JXB3NYJ.cjs} +15 -35
  31. package/dist/chunk-2JXB3NYJ.cjs.map +1 -0
  32. package/dist/chunk-2MRAX3UE.js +105 -0
  33. package/dist/chunk-2MRAX3UE.js.map +1 -0
  34. package/dist/{chunk-2LAT5BIK.cjs → chunk-3BRVBQQD.cjs} +2328 -3131
  35. package/dist/chunk-3BRVBQQD.cjs.map +1 -0
  36. package/dist/chunk-3E7SNSIA.cjs +55 -0
  37. package/dist/chunk-3E7SNSIA.cjs.map +1 -0
  38. package/dist/{chunk-FDN43KXV.cjs → chunk-3Z6TW3CT.cjs} +20 -19
  39. package/dist/chunk-3Z6TW3CT.cjs.map +1 -0
  40. package/dist/{chunk-IJORSAC3.js → chunk-4DIBPQNJ.js} +6 -4
  41. package/dist/chunk-4DIBPQNJ.js.map +1 -0
  42. package/dist/chunk-4S2FXGBJ.js +9 -0
  43. package/dist/chunk-4S2FXGBJ.js.map +1 -0
  44. package/dist/chunk-5IQIX7LU.cjs +2070 -0
  45. package/dist/chunk-5IQIX7LU.cjs.map +1 -0
  46. package/dist/{chunk-CWFPJ3RC.js → chunk-6GNSY7AV.js} +3 -3
  47. package/dist/{chunk-CWFPJ3RC.js.map → chunk-6GNSY7AV.js.map} +1 -1
  48. package/dist/{chunk-LAZGHOZW.cjs → chunk-6HVOHZHS.cjs} +184 -117
  49. package/dist/chunk-6HVOHZHS.cjs.map +1 -0
  50. package/dist/chunk-6SCVW4AS.js +20 -0
  51. package/dist/chunk-6SCVW4AS.js.map +1 -0
  52. package/dist/chunk-A7SZZFAG.js +2010 -0
  53. package/dist/chunk-A7SZZFAG.js.map +1 -0
  54. package/dist/chunk-ACSVZPK7.cjs +21 -0
  55. package/dist/chunk-ACSVZPK7.cjs.map +1 -0
  56. package/dist/{chunk-MXE2U3EX.js → chunk-BVTWD66D.js} +4 -115
  57. package/dist/chunk-BVTWD66D.js.map +1 -0
  58. package/dist/{chunk-W4ZX2GCP.js → chunk-CHXTTSC6.js} +5 -39
  59. package/dist/chunk-CHXTTSC6.js.map +1 -0
  60. package/dist/{chunk-XQFAJVYW.js → chunk-CYX2JTDG.js} +124 -5
  61. package/dist/chunk-CYX2JTDG.js.map +1 -0
  62. package/dist/{chunk-PRMKPFN5.js → chunk-DEQFL35G.js} +4 -3
  63. package/dist/chunk-DEQFL35G.js.map +1 -0
  64. package/dist/chunk-DI74SMXS.cjs +29 -0
  65. package/dist/chunk-DI74SMXS.cjs.map +1 -0
  66. package/dist/{chunk-WWVV44DY.cjs → chunk-G6SOJEDI.cjs} +11 -11
  67. package/dist/{chunk-WWVV44DY.cjs.map → chunk-G6SOJEDI.cjs.map} +1 -1
  68. package/dist/{chunk-LM2IC4ZJ.cjs → chunk-GQANNXXT.cjs} +15 -14
  69. package/dist/chunk-GQANNXXT.cjs.map +1 -0
  70. package/dist/chunk-GZCNZ7QW.js +24 -0
  71. package/dist/chunk-GZCNZ7QW.js.map +1 -0
  72. package/dist/{chunk-KTIEB7VH.cjs → chunk-HK5SATYM.cjs} +35 -58
  73. package/dist/chunk-HK5SATYM.cjs.map +1 -0
  74. package/dist/chunk-HMFK4BXR.cjs +12 -0
  75. package/dist/{chunk-6ZR4QC3O.cjs.map → chunk-HMFK4BXR.cjs.map} +1 -1
  76. package/dist/chunk-ITE4IXAK.js +25 -0
  77. package/dist/chunk-ITE4IXAK.js.map +1 -0
  78. package/dist/chunk-JJRCLAUN.cjs +155 -0
  79. package/dist/chunk-JJRCLAUN.cjs.map +1 -0
  80. package/dist/{chunk-ZFWNO3GE.cjs → chunk-JQGIPGVL.cjs} +66 -2
  81. package/dist/chunk-JQGIPGVL.cjs.map +1 -0
  82. package/dist/{chunk-2BVHPOIG.js → chunk-K2TGS3EN.js} +105 -38
  83. package/dist/chunk-K2TGS3EN.js.map +1 -0
  84. package/dist/chunk-K34OPSJK.js +29 -0
  85. package/dist/chunk-K34OPSJK.js.map +1 -0
  86. package/dist/{chunk-YW7GHMF4.cjs → chunk-KGC4LY5T.cjs} +18 -17
  87. package/dist/chunk-KGC4LY5T.cjs.map +1 -0
  88. package/dist/{chunk-SB65GJNY.cjs → chunk-KNHYNQQ3.cjs} +111 -72
  89. package/dist/chunk-KNHYNQQ3.cjs.map +1 -0
  90. package/dist/{chunk-C4C4Q7A6.js → chunk-KUTNI6SI.js} +6 -21
  91. package/dist/chunk-KUTNI6SI.js.map +1 -0
  92. package/dist/{chunk-NDM5PXEH.js → chunk-LANHCOXB.js} +44 -11
  93. package/dist/chunk-LANHCOXB.js.map +1 -0
  94. package/dist/chunk-N6WTUSBV.cjs +23 -0
  95. package/dist/chunk-N6WTUSBV.cjs.map +1 -0
  96. package/dist/{chunk-73KASJGO.cjs → chunk-NAUA4PW5.cjs} +4 -28
  97. package/dist/chunk-NAUA4PW5.cjs.map +1 -0
  98. package/dist/chunk-QV245VMN.js +145 -0
  99. package/dist/chunk-QV245VMN.js.map +1 -0
  100. package/dist/{chunk-CEF2QOTO.js → chunk-RBV7YCQD.js} +4 -3
  101. package/dist/chunk-RBV7YCQD.js.map +1 -0
  102. package/dist/chunk-RHZWOJVA.cjs +109 -0
  103. package/dist/chunk-RHZWOJVA.cjs.map +1 -0
  104. package/dist/{chunk-6RMLO5O4.cjs → chunk-RRKQAKD6.cjs} +13 -11
  105. package/dist/chunk-RRKQAKD6.cjs.map +1 -0
  106. package/dist/{chunk-TUA3MEJJ.js → chunk-RY2VIWAM.js} +612 -564
  107. package/dist/chunk-RY2VIWAM.js.map +1 -0
  108. package/dist/{chunk-PIHXFF73.js → chunk-SHLY4MCM.js} +3 -3
  109. package/dist/{chunk-PIHXFF73.js.map → chunk-SHLY4MCM.js.map} +1 -1
  110. package/dist/{chunk-HFBRAOF7.js → chunk-T2DWPQNE.js} +103 -64
  111. package/dist/chunk-T2DWPQNE.js.map +1 -0
  112. package/dist/{chunk-WYTUF3QO.js → chunk-T46GR2VY.js} +3 -3
  113. package/dist/{chunk-WYTUF3QO.js.map → chunk-T46GR2VY.js.map} +1 -1
  114. package/dist/{chunk-EEYV6UOE.cjs → chunk-T6SPUYLX.cjs} +5 -43
  115. package/dist/chunk-T6SPUYLX.cjs.map +1 -0
  116. package/dist/{chunk-3QRBXYT5.cjs → chunk-TGJE22RM.cjs} +6 -6
  117. package/dist/{chunk-3QRBXYT5.cjs.map → chunk-TGJE22RM.cjs.map} +1 -1
  118. package/dist/{chunk-YL4F3CMD.cjs → chunk-TOTPVGOG.cjs} +105 -72
  119. package/dist/chunk-TOTPVGOG.cjs.map +1 -0
  120. package/dist/{chunk-3HQDMOBK.cjs → chunk-UJLOZYKT.cjs} +680 -636
  121. package/dist/chunk-UJLOZYKT.cjs.map +1 -0
  122. package/dist/chunk-UNNPKQUG.cjs +1390 -0
  123. package/dist/chunk-UNNPKQUG.cjs.map +1 -0
  124. package/dist/chunk-UR7W5YQK.js +18 -0
  125. package/dist/chunk-UR7W5YQK.js.map +1 -0
  126. package/dist/chunk-V3QNTB7Z.js +1351 -0
  127. package/dist/chunk-V3QNTB7Z.js.map +1 -0
  128. package/dist/{chunk-XKNAK27R.js → chunk-VCGO4V26.js} +4 -3
  129. package/dist/chunk-VCGO4V26.js.map +1 -0
  130. package/dist/{chunk-YQGLVWB2.cjs → chunk-WL2SG7ZV.cjs} +6 -122
  131. package/dist/chunk-WL2SG7ZV.cjs.map +1 -0
  132. package/dist/{chunk-WNORITK6.js → chunk-WLRIWYHQ.js} +2041 -2834
  133. package/dist/chunk-WLRIWYHQ.js.map +1 -0
  134. package/dist/{chunk-JKRKIEVA.cjs → chunk-WVC2Q2FD.cjs} +128 -6
  135. package/dist/chunk-WVC2Q2FD.cjs.map +1 -0
  136. package/dist/chunk-XLUNB2TZ.js +53 -0
  137. package/dist/chunk-XLUNB2TZ.js.map +1 -0
  138. package/dist/chunk-XXVEULWX.js +39 -0
  139. package/dist/chunk-XXVEULWX.js.map +1 -0
  140. package/dist/chunk-YAZE7QZR.cjs +32 -0
  141. package/dist/chunk-YAZE7QZR.cjs.map +1 -0
  142. package/dist/chunk-YC6PWTHY.cjs +44 -0
  143. package/dist/chunk-YC6PWTHY.cjs.map +1 -0
  144. package/dist/chunk-Z5HBYM7U.cjs +11 -0
  145. package/dist/chunk-Z5HBYM7U.cjs.map +1 -0
  146. package/dist/{chunk-454I6GDF.js → chunk-Z5XBMDXU.js} +63 -3
  147. package/dist/chunk-Z5XBMDXU.js.map +1 -0
  148. package/dist/{chunk-CAMMC3E4.cjs → chunk-ZP5WHI4C.cjs} +109 -81
  149. package/dist/chunk-ZP5WHI4C.cjs.map +1 -0
  150. package/dist/{chunk-YCV72E6L.js → chunk-ZURTTSCM.js} +4 -25
  151. package/dist/chunk-ZURTTSCM.js.map +1 -0
  152. package/dist/{chunk-7WW3WL6E.js → chunk-ZV5N4DBG.js} +49 -21
  153. package/dist/chunk-ZV5N4DBG.js.map +1 -0
  154. package/dist/chunk-ZY4GXIVN.cjs +32 -0
  155. package/dist/chunk-ZY4GXIVN.cjs.map +1 -0
  156. package/dist/{ddl-C8e8zDAE.d.ts → ddl-BrmPg61z.d.ts} +3 -3
  157. package/dist/{ddl-CwyG4HoQ.d.cts → ddl-j1-sH6lE.d.cts} +3 -3
  158. package/dist/{extension-types-D1k0inWU.d.cts → extension-types-YGFJPrzK.d.cts} +1 -1
  159. package/dist/{extension-types-D1k0inWU.d.ts → extension-types-YGFJPrzK.d.ts} +1 -1
  160. package/dist/graph-extension/index.cjs +18 -17
  161. package/dist/graph-extension/index.d.cts +4 -4
  162. package/dist/graph-extension/index.d.ts +4 -4
  163. package/dist/graph-extension/index.js +3 -2
  164. package/dist/graph-merge/index.cjs +295 -146
  165. package/dist/graph-merge/index.cjs.map +1 -1
  166. package/dist/graph-merge/index.d.cts +6 -6
  167. package/dist/graph-merge/index.d.ts +6 -6
  168. package/dist/graph-merge/index.js +173 -24
  169. package/dist/graph-merge/index.js.map +1 -1
  170. package/dist/{index-BEK0VtNB.d.ts → index-DGX6D9j1.d.ts} +2 -2
  171. package/dist/{index-C8sSTErx.d.cts → index-SEvUHDA6.d.cts} +2 -2
  172. package/dist/index.cjs +206 -172
  173. package/dist/index.cjs.map +1 -1
  174. package/dist/index.d.cts +25 -55
  175. package/dist/index.d.ts +25 -55
  176. package/dist/index.js +32 -22
  177. package/dist/index.js.map +1 -1
  178. package/dist/indexes/index.cjs +28 -25
  179. package/dist/indexes/index.d.cts +5 -5
  180. package/dist/indexes/index.d.ts +5 -5
  181. package/dist/indexes/index.js +10 -7
  182. package/dist/interchange/index.cjs +25 -16
  183. package/dist/interchange/index.d.cts +5 -5
  184. package/dist/interchange/index.d.ts +5 -5
  185. package/dist/interchange/index.js +12 -3
  186. package/dist/{manager-8htmuGr-.d.ts → manager-BZUeN_BU.d.ts} +2 -2
  187. package/dist/{manager-aVgxbGt-.d.cts → manager-ms9cKdc6.d.cts} +2 -2
  188. package/dist/{materialize-indexes-CAGhqPHQ.d.ts → materialize-indexes-CAkIYFV-.d.ts} +1 -1
  189. package/dist/{materialize-indexes-DEYkU-wr.d.cts → materialize-indexes-D20xNluI.d.cts} +1 -1
  190. package/dist/{postgres-Dhom7iiX.d.ts → postgres-BhpxGMC5.d.cts} +2651 -596
  191. package/dist/{postgres-jgXmD45C.d.cts → postgres-CWHLwNl1.d.ts} +2651 -596
  192. package/dist/profiler/index.cjs +5 -4
  193. package/dist/profiler/index.cjs.map +1 -1
  194. package/dist/profiler/index.d.cts +7 -7
  195. package/dist/profiler/index.d.ts +7 -7
  196. package/dist/profiler/index.js +3 -2
  197. package/dist/profiler/index.js.map +1 -1
  198. package/dist/provenance/index.cjs +591 -0
  199. package/dist/provenance/index.cjs.map +1 -0
  200. package/dist/provenance/index.d.cts +73 -0
  201. package/dist/provenance/index.d.ts +73 -0
  202. package/dist/provenance/index.js +589 -0
  203. package/dist/provenance/index.js.map +1 -0
  204. package/dist/schema/index.cjs +37 -32
  205. package/dist/schema/index.cjs.map +1 -1
  206. package/dist/schema/index.d.cts +7 -7
  207. package/dist/schema/index.d.ts +7 -7
  208. package/dist/schema/index.js +14 -9
  209. package/dist/schema/index.js.map +1 -1
  210. package/dist/{sqlite-DcQ_BCUW.d.cts → sqlite-CGu5SLsw.d.ts} +2726 -455
  211. package/dist/{sqlite-BfLsCEqO.d.ts → sqlite-XrDxNaa7.d.cts} +2726 -455
  212. package/dist/{store-view-pBOUrQte.d.ts → store-view-BlgnhEYf.d.ts} +467 -131
  213. package/dist/{store-view-lTcb_cnp.d.cts → store-view-D09po4H6.d.cts} +467 -131
  214. package/dist/{types-DGDiXAYc.d.ts → types-B1TbZJYS.d.ts} +2 -2
  215. package/dist/{types-Dk8r09KY.d.ts → types-D1Sqeyxy.d.ts} +161 -26
  216. package/dist/{types-5RQwzWXx.d.cts → types-DiE1AO7p.d.cts} +2 -2
  217. package/dist/{types-Dvmn-eal.d.cts → types-DkNnF-7K.d.cts} +161 -26
  218. package/dist/{where-Cx_glEEB.d.cts → where-DKjuofPr.d.cts} +2 -2
  219. package/dist/{where-CHZFELX0.d.ts → where-DrUIIWHb.d.ts} +2 -2
  220. package/package.json +8 -2
  221. package/dist/chunk-2BVHPOIG.js.map +0 -1
  222. package/dist/chunk-2LAT5BIK.cjs.map +0 -1
  223. package/dist/chunk-2YMGNYXY.js +0 -40
  224. package/dist/chunk-2YMGNYXY.js.map +0 -1
  225. package/dist/chunk-3HQDMOBK.cjs.map +0 -1
  226. package/dist/chunk-454I6GDF.js.map +0 -1
  227. package/dist/chunk-6G35I3VW.cjs +0 -40
  228. package/dist/chunk-6G35I3VW.cjs.map +0 -1
  229. package/dist/chunk-6RMLO5O4.cjs.map +0 -1
  230. package/dist/chunk-6ZR4QC3O.cjs +0 -12
  231. package/dist/chunk-73KASJGO.cjs.map +0 -1
  232. package/dist/chunk-7WW3WL6E.js.map +0 -1
  233. package/dist/chunk-C4C4Q7A6.js.map +0 -1
  234. package/dist/chunk-CAMMC3E4.cjs.map +0 -1
  235. package/dist/chunk-CEF2QOTO.js.map +0 -1
  236. package/dist/chunk-CFNT3ITG.cjs.map +0 -1
  237. package/dist/chunk-EEYV6UOE.cjs.map +0 -1
  238. package/dist/chunk-FDN43KXV.cjs.map +0 -1
  239. package/dist/chunk-HFBRAOF7.js.map +0 -1
  240. package/dist/chunk-IJORSAC3.js.map +0 -1
  241. package/dist/chunk-JKRKIEVA.cjs.map +0 -1
  242. package/dist/chunk-KTIEB7VH.cjs.map +0 -1
  243. package/dist/chunk-LAZGHOZW.cjs.map +0 -1
  244. package/dist/chunk-LM2IC4ZJ.cjs.map +0 -1
  245. package/dist/chunk-M6OC455F.js +0 -65
  246. package/dist/chunk-M6OC455F.js.map +0 -1
  247. package/dist/chunk-MXE2U3EX.js.map +0 -1
  248. package/dist/chunk-NDM5PXEH.js.map +0 -1
  249. package/dist/chunk-PRMKPFN5.js.map +0 -1
  250. package/dist/chunk-RP7YITHX.cjs +0 -70
  251. package/dist/chunk-RP7YITHX.cjs.map +0 -1
  252. package/dist/chunk-SAJSMR2B.js +0 -35
  253. package/dist/chunk-SAJSMR2B.js.map +0 -1
  254. package/dist/chunk-SB65GJNY.cjs.map +0 -1
  255. package/dist/chunk-TUA3MEJJ.js.map +0 -1
  256. package/dist/chunk-W4ZX2GCP.js.map +0 -1
  257. package/dist/chunk-WNORITK6.js.map +0 -1
  258. package/dist/chunk-XKNAK27R.js.map +0 -1
  259. package/dist/chunk-XQFAJVYW.js.map +0 -1
  260. package/dist/chunk-YCV72E6L.js.map +0 -1
  261. package/dist/chunk-YL4F3CMD.cjs.map +0 -1
  262. package/dist/chunk-YQGLVWB2.cjs.map +0 -1
  263. package/dist/chunk-YW7GHMF4.cjs.map +0 -1
  264. package/dist/chunk-ZFWNO3GE.cjs.map +0 -1
@@ -0,0 +1,2070 @@
1
+ 'use strict';
2
+
3
+ var chunkUNNPKQUG_cjs = require('./chunk-UNNPKQUG.cjs');
4
+ var chunkYC6PWTHY_cjs = require('./chunk-YC6PWTHY.cjs');
5
+ var chunkRHZWOJVA_cjs = require('./chunk-RHZWOJVA.cjs');
6
+ var chunkYAZE7QZR_cjs = require('./chunk-YAZE7QZR.cjs');
7
+ var chunkNAUA4PW5_cjs = require('./chunk-NAUA4PW5.cjs');
8
+ var chunkJQGIPGVL_cjs = require('./chunk-JQGIPGVL.cjs');
9
+ var chunkJIEJCTDS_cjs = require('./chunk-JIEJCTDS.cjs');
10
+ var drizzleOrm = require('drizzle-orm');
11
+ var nanoid = require('nanoid');
12
+
13
+ // src/core/temporal.ts
14
+ var RECORDED_MAX = "9999-12-31T23:59:59.999Z";
15
+ function assertValidRecordedInstant(value, path) {
16
+ chunkYC6PWTHY_cjs.validateCanonicalIsoDate(value, path);
17
+ if (value >= RECORDED_MAX) {
18
+ throw new chunkJIEJCTDS_cjs.ValidationError(
19
+ `${path} must be before the recorded-time open sentinel ${RECORDED_MAX}.`,
20
+ {
21
+ issues: [
22
+ {
23
+ path,
24
+ message: `Expected a timestamp before ${RECORDED_MAX}, got "${value}"`
25
+ }
26
+ ]
27
+ },
28
+ {
29
+ suggestion: "Use a real recorded-time commit instant, not the open-interval sentinel."
30
+ }
31
+ );
32
+ }
33
+ }
34
+ function asRecordedInstant(value) {
35
+ assertValidRecordedInstant(value, "asRecordedInstant");
36
+ return value;
37
+ }
38
+ function resolveReadCoordinate(mode, asOf, suggestion) {
39
+ if (mode !== "asOf" && asOf !== void 0) {
40
+ throw new chunkJIEJCTDS_cjs.ValidationError(
41
+ `Temporal mode "${mode}" does not take an asOf timestamp.`,
42
+ {
43
+ issues: [
44
+ {
45
+ path: "asOf",
46
+ message: `asOf is only valid with mode "asOf", not "${mode}"`
47
+ }
48
+ ]
49
+ },
50
+ {
51
+ suggestion: 'Pin an instant with store.asOf(timestamp) or store.view({ mode: "asOf", asOf }); drop asOf for other modes.'
52
+ }
53
+ );
54
+ }
55
+ assertValidAsOf(
56
+ mode,
57
+ asOf,
58
+ suggestion === void 0 ? void 0 : { suggestion }
59
+ );
60
+ return { valid: asOf === void 0 ? { mode } : { mode, asOf } };
61
+ }
62
+ function withRecordedCoordinate(coordinate, recordedAsOf) {
63
+ assertValidRecordedInstant(recordedAsOf, "asOfRecorded");
64
+ return {
65
+ ...coordinate,
66
+ recorded: { asOf: recordedAsOf }
67
+ };
68
+ }
69
+ function assertValidAsOf(mode, asOf, options) {
70
+ if (mode === "asOf" && asOf === void 0) {
71
+ throw new chunkJIEJCTDS_cjs.ValidationError(
72
+ 'Temporal mode "asOf" requires a timestamp',
73
+ {
74
+ issues: [
75
+ { path: "asOf", message: "Timestamp is required for asOf mode" }
76
+ ]
77
+ },
78
+ {
79
+ suggestion: options?.suggestion ?? 'Provide an ISO-8601 timestamp for asOf mode, e.g. "2026-01-01T00:00:00.000Z".'
80
+ }
81
+ );
82
+ }
83
+ if (asOf !== void 0) {
84
+ chunkYC6PWTHY_cjs.validateCanonicalIsoDate(asOf, "asOf");
85
+ }
86
+ }
87
+ function describeCoordinate(coordinate) {
88
+ const { mode, asOf } = coordinate.valid;
89
+ const valid = asOf === void 0 ? `mode "${mode}"` : `mode "${mode}" asOf ${asOf}`;
90
+ return coordinate.recorded === void 0 ? valid : `${valid}, recorded asOf ${coordinate.recorded.asOf}`;
91
+ }
92
+ function coordinateContext(coordinate) {
93
+ const { mode, asOf } = coordinate.valid;
94
+ return {
95
+ temporalMode: mode,
96
+ ...asOf !== void 0 && { asOf },
97
+ ...coordinate.recorded === void 0 ? {} : { recordedAsOf: coordinate.recorded.asOf }
98
+ };
99
+ }
100
+
101
+ // src/query/sql-intent.ts
102
+ function asCompiledRowsSql(query) {
103
+ return query;
104
+ }
105
+ function asCompiledSelectSql(query) {
106
+ return asCompiledRowsSql(query);
107
+ }
108
+ function asCompiledStatementSql(query) {
109
+ return query;
110
+ }
111
+ var SqlSchemaDescriptor = class {
112
+ // Private field gives SqlSchema nominal identity; runtime checks use instanceof.
113
+ #brand = true;
114
+ tables;
115
+ nodesTable;
116
+ edgesTable;
117
+ recordedNodesTable;
118
+ recordedEdgesTable;
119
+ recordedClockTable;
120
+ fulltextTable;
121
+ constructor(fields) {
122
+ this.tables = fields.tables;
123
+ this.nodesTable = fields.nodesTable;
124
+ this.edgesTable = fields.edgesTable;
125
+ this.recordedNodesTable = fields.recordedNodesTable;
126
+ this.recordedEdgesTable = fields.recordedEdgesTable;
127
+ this.recordedClockTable = fields.recordedClockTable;
128
+ this.fulltextTable = fields.fulltextTable;
129
+ void this.#brand;
130
+ Object.freeze(this);
131
+ }
132
+ };
133
+ var DEFAULT_TABLE_NAMES = {
134
+ nodes: "typegraph_nodes",
135
+ edges: "typegraph_edges",
136
+ recordedNodes: "typegraph_recorded_nodes",
137
+ recordedEdges: "typegraph_recorded_edges",
138
+ recordedClock: "typegraph_recorded_clock",
139
+ fulltext: "typegraph_node_fulltext",
140
+ uniques: "typegraph_node_uniques"
141
+ };
142
+ function resolveTableNames(names) {
143
+ return {
144
+ nodes: names.nodes ?? DEFAULT_TABLE_NAMES.nodes,
145
+ edges: names.edges ?? DEFAULT_TABLE_NAMES.edges,
146
+ recordedNodes: names.recordedNodes ?? DEFAULT_TABLE_NAMES.recordedNodes,
147
+ recordedEdges: names.recordedEdges ?? DEFAULT_TABLE_NAMES.recordedEdges,
148
+ recordedClock: names.recordedClock ?? DEFAULT_TABLE_NAMES.recordedClock,
149
+ fulltext: names.fulltext ?? DEFAULT_TABLE_NAMES.fulltext,
150
+ uniques: names.uniques ?? DEFAULT_TABLE_NAMES.uniques
151
+ };
152
+ }
153
+ var VALID_IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_$]*$/i;
154
+ function validateTableName(name, label) {
155
+ if (!name || name.length === 0) {
156
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(`${label} table name cannot be empty`);
157
+ }
158
+ if (name.length > chunkNAUA4PW5_cjs.MAX_PG_IDENTIFIER_LENGTH) {
159
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
160
+ `${label} table name exceeds maximum length of ${chunkNAUA4PW5_cjs.MAX_PG_IDENTIFIER_LENGTH} characters`
161
+ );
162
+ }
163
+ if (!VALID_IDENTIFIER_PATTERN.test(name)) {
164
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
165
+ `${label} table name "${name}" is not a valid SQL identifier. Table names must start with a letter or underscore and contain only letters, digits, underscores, or dollar signs.`
166
+ );
167
+ }
168
+ }
169
+ function quoteIdentifier(name) {
170
+ return `"${name.replaceAll('"', '""')}"`;
171
+ }
172
+ function freezeSqlSchema(fields) {
173
+ return new SqlSchemaDescriptor(fields);
174
+ }
175
+ function isSqlSchema(schema) {
176
+ return schema instanceof SqlSchemaDescriptor && Object.isFrozen(schema);
177
+ }
178
+ function requireSqlSchema(schema, surface = "SqlSchema") {
179
+ if (isSqlSchema(schema)) return schema;
180
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
181
+ `${surface} must be created with createSqlSchema(...).`,
182
+ { code: "INVALID_SQL_SCHEMA", surface },
183
+ {
184
+ suggestion: "Pass the result of createSqlSchema(...) instead of a plain schema-shaped object."
185
+ }
186
+ );
187
+ }
188
+ function createSqlSchema(names = {}) {
189
+ const tables = resolveTableNames(names);
190
+ validateTableName(tables.nodes, "nodes");
191
+ validateTableName(tables.edges, "edges");
192
+ validateTableName(tables.recordedNodes, "recordedNodes");
193
+ validateTableName(tables.recordedEdges, "recordedEdges");
194
+ validateTableName(tables.recordedClock, "recordedClock");
195
+ validateTableName(tables.fulltext, "fulltext");
196
+ validateTableName(tables.uniques, "uniques");
197
+ return freezeSqlSchema({
198
+ tables: Object.freeze(tables),
199
+ nodesTable: drizzleOrm.sql.raw(quoteIdentifier(tables.nodes)),
200
+ edgesTable: drizzleOrm.sql.raw(quoteIdentifier(tables.edges)),
201
+ recordedNodesTable: drizzleOrm.sql.raw(quoteIdentifier(tables.recordedNodes)),
202
+ recordedEdgesTable: drizzleOrm.sql.raw(quoteIdentifier(tables.recordedEdges)),
203
+ recordedClockTable: drizzleOrm.sql.raw(quoteIdentifier(tables.recordedClock)),
204
+ fulltextTable: drizzleOrm.sql.raw(quoteIdentifier(tables.fulltext))
205
+ });
206
+ }
207
+ var EXTERNAL_RECORDED_READ_SOURCE = /* @__PURE__ */ Symbol(
208
+ "ExternalRecordedReadSource"
209
+ );
210
+ var TYPEGRAPH_RECORDED_READ_SOURCE = /* @__PURE__ */ Symbol(
211
+ "TypeGraphRecordedReadSource"
212
+ );
213
+ function recordedRelation(options) {
214
+ const schema = requireSqlSchema(options.schema, "recordedRelation schema");
215
+ return Object.freeze({
216
+ source: "external",
217
+ schema,
218
+ [EXTERNAL_RECORDED_READ_SOURCE]: true
219
+ });
220
+ }
221
+ function requireExternalRecordedReadSource(source) {
222
+ if (source === void 0) return void 0;
223
+ if (isExternalRecordedReadSource(source)) return source;
224
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
225
+ "recordedRead must be created with recordedRelation({ schema }).",
226
+ { code: "INVALID_RECORDED_READ_SOURCE" },
227
+ {
228
+ suggestion: "Pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation. Use { history: true } when TypeGraph should capture writes."
229
+ }
230
+ );
231
+ }
232
+ function isExternalRecordedReadSource(source) {
233
+ if (typeof source !== "object" || source === null) return false;
234
+ const candidate = source;
235
+ return candidate.source === "external" && candidate[EXTERNAL_RECORDED_READ_SOURCE] === true && isSqlSchema(candidate.schema) && Object.isFrozen(candidate);
236
+ }
237
+ function createRecordedReadBinding(schema) {
238
+ const readSchema = requireSqlSchema(schema, "recorded read binding schema");
239
+ return Object.freeze({
240
+ source: "typegraph-capture",
241
+ schema: readSchema,
242
+ [TYPEGRAPH_RECORDED_READ_SOURCE]: true
243
+ });
244
+ }
245
+ function requireRecordedReadBinding(binding, surface) {
246
+ if (isRecordedReadBinding(binding)) return binding;
247
+ if (binding !== void 0) {
248
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
249
+ "Recorded-time reads require a recorded read relation created by TypeGraph.",
250
+ { code: "INVALID_RECORDED_READ_BINDING", surface },
251
+ {
252
+ suggestion: "Use createStore(graph, backend, { history: true }) or { recordedRead: recordedRelation({ schema }) } instead of passing a plain object."
253
+ }
254
+ );
255
+ }
256
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
257
+ "Recorded-time reads require a recorded read relation.",
258
+ { code: "RECORDED_READ_REQUIRES_BINDING", surface },
259
+ {
260
+ suggestion: "Create the store with createStore(graph, backend, { history: true }) to bind TypeGraph's built-in captured relation, or pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation."
261
+ }
262
+ );
263
+ }
264
+ function isTypeGraphRecordedReadSource(source) {
265
+ if (typeof source !== "object" || source === null) return false;
266
+ const candidate = source;
267
+ return candidate.source === "typegraph-capture" && candidate[TYPEGRAPH_RECORDED_READ_SOURCE] === true && isSqlSchema(candidate.schema) && Object.isFrozen(candidate);
268
+ }
269
+ function isRecordedReadBinding(binding) {
270
+ return isExternalRecordedReadSource(binding) || isTypeGraphRecordedReadSource(binding);
271
+ }
272
+ function recordedReadSqlSchema(binding) {
273
+ const { schema } = requireRecordedReadBinding(
274
+ binding,
275
+ "recorded-read-schema"
276
+ );
277
+ return freezeSqlSchema({
278
+ tables: schema.tables,
279
+ nodesTable: schema.recordedNodesTable,
280
+ edgesTable: schema.recordedEdgesTable,
281
+ recordedNodesTable: schema.recordedNodesTable,
282
+ recordedEdgesTable: schema.recordedEdgesTable,
283
+ recordedClockTable: schema.recordedClockTable,
284
+ fulltextTable: schema.fulltextTable
285
+ });
286
+ }
287
+ function recordedReadSchemaFor(schema, recordedAsOf, binding, surface) {
288
+ const baseSchema = requireSqlSchema(schema, `${surface} schema`);
289
+ if (recordedAsOf === void 0) return baseSchema;
290
+ return recordedReadSqlSchema(requireRecordedReadBinding(binding, surface));
291
+ }
292
+ var DEFAULT_SQL_SCHEMA = createSqlSchema();
293
+ function vectorSlotKey(nodeKind, fieldPath) {
294
+ return `${nodeKind}\0${fieldPath}`;
295
+ }
296
+ var ALIAS_CTE_PREFIX = "cte_";
297
+ var EMBEDDINGS_CTE_ALIAS = "cte_embeddings";
298
+ var FULLTEXT_CTE_ALIAS = "cte_fulltext";
299
+ var HYBRID_CANDIDATES_CTE_ALIAS = "cte_relevance_candidates";
300
+ function generateId() {
301
+ return nanoid.nanoid();
302
+ }
303
+ function requireRecordedSchema(target) {
304
+ if (target.tableNames === void 0) {
305
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
306
+ "Recorded-time capture requires the backend to expose tableNames.",
307
+ { dialect: target.dialect },
308
+ {
309
+ suggestion: "Use a built-in SQLite/PostgreSQL backend, or set tableNames on the custom backend so recorded-time capture targets the configured relations."
310
+ }
311
+ );
312
+ }
313
+ return createSqlSchema(target.tableNames);
314
+ }
315
+ function requireCaptureStatements(target) {
316
+ if (target.executeStatement === void 0) {
317
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
318
+ "Recorded-time capture requires backend.executeStatement support on the transaction backend.",
319
+ { dialect: target.dialect },
320
+ {
321
+ suggestion: "Use the built-in SQLite/PostgreSQL backends or provide executeStatement on the custom backend's transaction target."
322
+ }
323
+ );
324
+ }
325
+ }
326
+ async function executeStatement(target, query) {
327
+ requireCaptureStatements(target);
328
+ await target.executeStatement(asCompiledStatementSql(query));
329
+ }
330
+ function unsupportedPostgresIsolationError(isolationLevel) {
331
+ return new chunkJIEJCTDS_cjs.ConfigurationError(
332
+ "Recorded-time capture on PostgreSQL requires read_committed isolation.",
333
+ { isolationLevel: isolationLevel ?? "unknown" },
334
+ {
335
+ suggestion: "Omit the transaction isolation option or use read_committed. PostgreSQL repeatable_read/serializable snapshots cannot safely allocate the per-graph recorded clock inside the captured transaction."
336
+ }
337
+ );
338
+ }
339
+ function isSupportedRecordedIsolationLevel(isolationLevel) {
340
+ return isolationLevel === void 0 || isolationLevel === "read_committed" || isolationLevel === "read_uncommitted";
341
+ }
342
+ function assertRequestedRecordedIsolation(backend, options) {
343
+ if (backend.dialect !== "postgres") return;
344
+ const isolationLevel = options?.isolationLevel;
345
+ if (isSupportedRecordedIsolationLevel(isolationLevel)) return;
346
+ throw unsupportedPostgresIsolationError(isolationLevel);
347
+ }
348
+ function normalizeIsolationLevel(value) {
349
+ if (typeof value !== "string") return void 0;
350
+ return value.replaceAll(" ", "_").toLowerCase();
351
+ }
352
+ async function assertRecordedCaptureTransactionIsolation(target) {
353
+ if (target.dialect !== "postgres") return;
354
+ const rows = await target.execute(
355
+ asCompiledRowsSql(drizzleOrm.sql`
356
+ SELECT current_setting('transaction_isolation') AS transaction_isolation
357
+ `)
358
+ );
359
+ const isolationLevel = normalizeIsolationLevel(
360
+ rows[0]?.transaction_isolation
361
+ );
362
+ if (isSupportedRecordedIsolationLevel(isolationLevel)) return;
363
+ throw unsupportedPostgresIsolationError(isolationLevel);
364
+ }
365
+ function recordedCaptureRequiresCallbackTransactionError(details) {
366
+ return new chunkJIEJCTDS_cjs.ConfigurationError(
367
+ "withTransaction() has no recorded-time capture flush point when history is enabled.",
368
+ details,
369
+ {
370
+ suggestion: "Use store.withRecordedTransaction(externalTx, async (tx) => ...) so TypeGraph can flush capture before the caller commits."
371
+ }
372
+ );
373
+ }
374
+ function historyUnsafeRawWriteError(surface) {
375
+ return new chunkJIEJCTDS_cjs.ConfigurationError(
376
+ `${surface} is not available when history capture is enabled because raw SQL writes bypass recorded-time capture.`,
377
+ { code: "RECORDED_CAPTURE_RAW_SQL_DISABLED" },
378
+ {
379
+ suggestion: "Run graph writes through store.nodes/store.edges (or tx.nodes/tx.edges inside a transaction), or perform raw relational writes outside a history-enabled TypeGraph store."
380
+ }
381
+ );
382
+ }
383
+ function failHistoryUnsafeSqlRef() {
384
+ throw historyUnsafeRawWriteError("tx.sql");
385
+ }
386
+ function createHistoryUnsafeSqlRef() {
387
+ return new Proxy(
388
+ function historyUnsafeSqlRef() {
389
+ return failHistoryUnsafeSqlRef();
390
+ },
391
+ {
392
+ get() {
393
+ return failHistoryUnsafeSqlRef();
394
+ },
395
+ apply() {
396
+ return failHistoryUnsafeSqlRef();
397
+ },
398
+ set() {
399
+ return failHistoryUnsafeSqlRef();
400
+ },
401
+ defineProperty() {
402
+ return failHistoryUnsafeSqlRef();
403
+ },
404
+ deleteProperty() {
405
+ return failHistoryUnsafeSqlRef();
406
+ },
407
+ // Enumeration / inspection traps too, so spreading (`{...tx.sql}`),
408
+ // `Object.keys`, `in`, and prototype reads also fail loudly rather than
409
+ // silently yielding an empty object that reads as "no raw handle".
410
+ has() {
411
+ return failHistoryUnsafeSqlRef();
412
+ },
413
+ ownKeys() {
414
+ return failHistoryUnsafeSqlRef();
415
+ },
416
+ getOwnPropertyDescriptor() {
417
+ return failHistoryUnsafeSqlRef();
418
+ },
419
+ getPrototypeOf() {
420
+ return failHistoryUnsafeSqlRef();
421
+ }
422
+ }
423
+ );
424
+ }
425
+ function rawWriteGuards(target, prefix) {
426
+ return {
427
+ ...target.executeStatement === void 0 ? {} : {
428
+ executeStatement(_query) {
429
+ return Promise.reject(
430
+ historyUnsafeRawWriteError(`${prefix}.executeStatement`)
431
+ );
432
+ }
433
+ },
434
+ ...target.executeDdl === void 0 ? {} : {
435
+ executeDdl(_ddl) {
436
+ return Promise.reject(
437
+ historyUnsafeRawWriteError(`${prefix}.executeDdl`)
438
+ );
439
+ }
440
+ }
441
+ };
442
+ }
443
+ function assertCapturableBackend(backend) {
444
+ if (!backend.capabilities.transactions) {
445
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
446
+ "history: true requires a backend with transaction support.",
447
+ { dialect: backend.dialect },
448
+ {
449
+ suggestion: "Use a transactional SQLite/PostgreSQL backend or disable recorded-time capture for this store."
450
+ }
451
+ );
452
+ }
453
+ if (backend.executeStatement === void 0) {
454
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
455
+ "history: true requires a backend that supports executeStatement.",
456
+ { dialect: backend.dialect },
457
+ {
458
+ suggestion: "Use a built-in SQLite/PostgreSQL backend, or implement executeStatement on the custom backend so recorded-time capture can write history rows."
459
+ }
460
+ );
461
+ }
462
+ if (backend.capabilities.returning === false) {
463
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
464
+ "history: true requires a backend that supports UPDATE \u2026 RETURNING.",
465
+ { dialect: backend.dialect },
466
+ {
467
+ suggestion: "Use a built-in SQLite/PostgreSQL backend, or run recorded-time capture on a backend whose engine supports UPDATE \u2026 RETURNING \u2014 capture closes recorded intervals with a RETURNING statement on its hot path."
468
+ }
469
+ );
470
+ }
471
+ if (backend.tableNames === void 0) {
472
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
473
+ "history: true requires a backend that exposes tableNames.",
474
+ { dialect: backend.dialect },
475
+ {
476
+ suggestion: "Use a built-in SQLite/PostgreSQL backend, or set tableNames on the custom backend so recorded-time capture can resolve the recorded relations instead of silently falling back to defaults."
477
+ }
478
+ );
479
+ }
480
+ }
481
+
482
+ // src/store/recorded-capture/clock.ts
483
+ var RECORDED_MIN = "1970-01-01T00:00:00.000Z";
484
+ var RECORDED_MAX_TIME = new Date(RECORDED_MAX).getTime();
485
+ var RECORDED_CLOCK_ADVISORY_LOCK_NAMESPACE = "typegraph:recorded-clock";
486
+ var RECORDED_GRAPH_WRITE_ADVISORY_LOCK_NAMESPACE = "typegraph:recorded-graph-write";
487
+ function graphAdvisoryLockSql(namespace, graphId) {
488
+ return drizzleOrm.sql`
489
+ SELECT pg_advisory_xact_lock(
490
+ hashtext(${namespace}),
491
+ hashtext(${graphId})
492
+ )
493
+ `;
494
+ }
495
+ function recordedClockAdvisoryLockSql(graphId) {
496
+ return graphAdvisoryLockSql(RECORDED_CLOCK_ADVISORY_LOCK_NAMESPACE, graphId);
497
+ }
498
+ function recordedGraphWriteAdvisoryLockSql(graphId) {
499
+ return graphAdvisoryLockSql(
500
+ RECORDED_GRAPH_WRITE_ADVISORY_LOCK_NAMESPACE,
501
+ graphId
502
+ );
503
+ }
504
+ var GRAPH_WRITE_LOCK_EVIDENCE = Object.freeze({});
505
+ function graphWriteLockEvidence() {
506
+ return GRAPH_WRITE_LOCK_EVIDENCE;
507
+ }
508
+ function uncapturedGraphWriteLock() {
509
+ return graphWriteLockEvidence();
510
+ }
511
+ async function lockRecordedGraphWrite(target, graphId) {
512
+ if (target.dialect !== "postgres") return graphWriteLockEvidence();
513
+ await target.execute(
514
+ asCompiledRowsSql(recordedGraphWriteAdvisoryLockSql(graphId))
515
+ );
516
+ return graphWriteLockEvidence();
517
+ }
518
+ async function lockRecordedGraphWrites(target, graphIds) {
519
+ if (target.dialect !== "postgres") return;
520
+ const uniqueGraphIds = [...new Set(graphIds)].toSorted();
521
+ for (const graphId of uniqueGraphIds) {
522
+ await lockRecordedGraphWrite(target, graphId);
523
+ }
524
+ }
525
+ function failInvalidClockTimestamp(value) {
526
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
527
+ "Recorded clock row contained an invalid timestamp",
528
+ { value }
529
+ );
530
+ }
531
+ var ZONELESS_DATETIME_PATTERN = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
532
+ var OFFSET_DATETIME_PATTERN = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)(Z|[+-]\d{2}(?::?\d{2})?)$/i;
533
+ function normalizeOffsetDesignator(offset) {
534
+ if (offset.toUpperCase() === "Z") return "Z";
535
+ if (/^[+-]\d{2}$/.test(offset)) return `${offset}:00`;
536
+ if (/^[+-]\d{4}$/.test(offset)) {
537
+ return `${offset.slice(0, 3)}:${offset.slice(3)}`;
538
+ }
539
+ return offset;
540
+ }
541
+ function clockTimestampMs(value) {
542
+ if (ZONELESS_DATETIME_PATTERN.test(value)) {
543
+ return Date.parse(`${value.replace(" ", "T")}Z`);
544
+ }
545
+ const offsetMatch = OFFSET_DATETIME_PATTERN.exec(value);
546
+ if (offsetMatch) {
547
+ const [, date, time, offset] = offsetMatch;
548
+ return Date.parse(`${date}T${time}${normalizeOffsetDesignator(offset)}`);
549
+ }
550
+ return Date.parse(value);
551
+ }
552
+ function toCanonicalIso(value) {
553
+ if (value instanceof Date) {
554
+ if (Number.isNaN(value.getTime())) return failInvalidClockTimestamp(value);
555
+ return value.toISOString();
556
+ }
557
+ if (typeof value === "string") {
558
+ const timestamp = clockTimestampMs(value);
559
+ if (Number.isNaN(timestamp)) return failInvalidClockTimestamp(value);
560
+ return new Date(timestamp).toISOString();
561
+ }
562
+ return failInvalidClockTimestamp(value);
563
+ }
564
+ function nextRecordedCommitTime(previous) {
565
+ const wallTime = Date.parse(chunkYC6PWTHY_cjs.nowIso());
566
+ return previous === void 0 ? wallTime : Math.max(wallTime, Date.parse(previous) + 1);
567
+ }
568
+ async function readRecordedClock(target, schema, graphId) {
569
+ const rows = await target.execute(
570
+ asCompiledRowsSql(drizzleOrm.sql`
571
+ SELECT recorded_at
572
+ FROM ${schema.recordedClockTable}
573
+ WHERE graph_id = ${graphId}
574
+ `)
575
+ );
576
+ const first = rows[0];
577
+ return first === void 0 ? void 0 : toCanonicalIso(first.recorded_at);
578
+ }
579
+ async function writeRecordedClock(target, schema, graphId, recordedAt) {
580
+ await executeStatement(
581
+ target,
582
+ drizzleOrm.sql`
583
+ INSERT INTO ${schema.recordedClockTable} (graph_id, recorded_at)
584
+ VALUES (${graphId}, ${recordedAt})
585
+ ON CONFLICT (graph_id) DO UPDATE SET recorded_at = ${recordedAt}
586
+ `
587
+ );
588
+ }
589
+ async function lockRecordedClock(target, schema, graphId, ownsWriteLock) {
590
+ if (target.dialect === "postgres") {
591
+ await target.execute(
592
+ asCompiledRowsSql(recordedClockAdvisoryLockSql(graphId))
593
+ );
594
+ return;
595
+ }
596
+ if (ownsWriteLock) return;
597
+ await executeStatement(
598
+ target,
599
+ drizzleOrm.sql`
600
+ INSERT INTO ${schema.recordedClockTable} (graph_id, recorded_at)
601
+ VALUES (${graphId}, ${RECORDED_MIN})
602
+ ON CONFLICT (graph_id) DO UPDATE SET recorded_at = recorded_at
603
+ `
604
+ );
605
+ }
606
+ async function allocateRecordedCommit(target, schema, graphId, ownsWriteLock) {
607
+ await lockRecordedClock(target, schema, graphId, ownsWriteLock);
608
+ const previous = await readRecordedClock(target, schema, graphId);
609
+ const recordedCommitTime = nextRecordedCommitTime(previous);
610
+ if (!Number.isFinite(recordedCommitTime) || recordedCommitTime >= RECORDED_MAX_TIME) {
611
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
612
+ `Recorded commit clock reached the open sentinel ${RECORDED_MAX}`,
613
+ { graphId, recordedCommitTime },
614
+ {
615
+ suggestion: "Use a graph with a normal recorded-time clock; the open sentinel is reserved for relation intervals."
616
+ }
617
+ );
618
+ }
619
+ const recordedCommit = new Date(recordedCommitTime).toISOString();
620
+ await writeRecordedClock(target, schema, graphId, recordedCommit);
621
+ return recordedCommit;
622
+ }
623
+
624
+ // src/store/insert-dispatch.ts
625
+ function nodeInsertDispatch(backend) {
626
+ return {
627
+ one: (params) => backend.insertNode(params),
628
+ oneNoReturn: backend.insertNodeNoReturn === void 0 ? void 0 : (params) => backend.insertNodeNoReturn(params),
629
+ batch: backend.insertNodesBatch === void 0 ? void 0 : (params) => backend.insertNodesBatch(params),
630
+ batchReturning: backend.insertNodesBatchReturning === void 0 ? void 0 : (params) => backend.insertNodesBatchReturning(params)
631
+ };
632
+ }
633
+ function edgeInsertDispatch(backend) {
634
+ return {
635
+ one: (params) => backend.insertEdge(params),
636
+ oneNoReturn: backend.insertEdgeNoReturn === void 0 ? void 0 : (params) => backend.insertEdgeNoReturn(params),
637
+ batch: backend.insertEdgesBatch === void 0 ? void 0 : (params) => backend.insertEdgesBatch(params),
638
+ batchReturning: backend.insertEdgesBatchReturning === void 0 ? void 0 : (params) => backend.insertEdgesBatchReturning(params)
639
+ };
640
+ }
641
+ async function runInsertNoReturn(dispatch, params) {
642
+ if (dispatch.oneNoReturn !== void 0) {
643
+ await dispatch.oneNoReturn(params);
644
+ return;
645
+ }
646
+ await dispatch.one(params);
647
+ }
648
+ async function runInsertBatch(dispatch, params) {
649
+ if (params.length === 0) return;
650
+ if (dispatch.batch !== void 0) {
651
+ await dispatch.batch(params);
652
+ return;
653
+ }
654
+ for (const insertParams of params) {
655
+ await runInsertNoReturn(dispatch, insertParams);
656
+ }
657
+ }
658
+ async function runInsertBatchReturning(dispatch, params) {
659
+ if (dispatch.batchReturning !== void 0) {
660
+ return dispatch.batchReturning(params);
661
+ }
662
+ const rows = [];
663
+ for (const insertParams of params) {
664
+ rows.push(await dispatch.one(insertParams));
665
+ }
666
+ return rows;
667
+ }
668
+
669
+ // src/store/row-fetch.ts
670
+ async function getRowsByIds(ids, policy) {
671
+ const rowsById = /* @__PURE__ */ new Map();
672
+ if (ids.length === 0) return rowsById;
673
+ if (policy.batch !== void 0) {
674
+ const rows2 = await policy.batch(ids);
675
+ for (const row of rows2) {
676
+ rowsById.set(row.id, row);
677
+ }
678
+ return rowsById;
679
+ }
680
+ const uniqueIds = [...new Set(ids)];
681
+ const rows = await Promise.all(uniqueIds.map((id) => policy.one(id)));
682
+ for (const row of rows) {
683
+ if (row !== void 0) rowsById.set(row.id, row);
684
+ }
685
+ return rowsById;
686
+ }
687
+
688
+ // src/store/edge-fetch.ts
689
+ async function getEdgeRowsByIds(backend, graphId, ids) {
690
+ return getRowsByIds(ids, {
691
+ batch: backend.getEdges === void 0 ? void 0 : (batchIds) => backend.getEdges(graphId, batchIds),
692
+ one: (id) => backend.getEdge(graphId, id)
693
+ });
694
+ }
695
+
696
+ // src/store/node-fetch.ts
697
+ async function getNodeRowsByIds(backend, graphId, kind, ids) {
698
+ return getRowsByIds(ids, {
699
+ batch: backend.getNodes === void 0 ? void 0 : (batchIds) => backend.getNodes(graphId, kind, batchIds),
700
+ one: (id) => backend.getNode(graphId, kind, id)
701
+ });
702
+ }
703
+ var RECORDED_HISTORY_META = "{}";
704
+ var RECORDED_NODE_COLUMNS = [
705
+ "history_id",
706
+ "graph_id",
707
+ "kind",
708
+ "id",
709
+ "props",
710
+ "version",
711
+ "valid_from",
712
+ "valid_to",
713
+ "created_at",
714
+ "updated_at",
715
+ "deleted_at",
716
+ "recorded_from",
717
+ "recorded_to",
718
+ "op",
719
+ "schema_version",
720
+ "tx_id",
721
+ "meta"
722
+ ];
723
+ var RECORDED_EDGE_COLUMNS = [
724
+ "history_id",
725
+ "graph_id",
726
+ "id",
727
+ "kind",
728
+ "from_kind",
729
+ "from_id",
730
+ "to_kind",
731
+ "to_id",
732
+ "props",
733
+ "valid_from",
734
+ "valid_to",
735
+ "created_at",
736
+ "updated_at",
737
+ "deleted_at",
738
+ "recorded_from",
739
+ "recorded_to",
740
+ "op",
741
+ "schema_version",
742
+ "tx_id",
743
+ "meta"
744
+ ];
745
+ var RECORDED_NODE_COLUMN_LIST = drizzleOrm.sql.raw(RECORDED_NODE_COLUMNS.join(", "));
746
+ var RECORDED_EDGE_COLUMN_LIST = drizzleOrm.sql.raw(RECORDED_EDGE_COLUMNS.join(", "));
747
+ var RECORDED_BIND_PARAM_BUDGET = 900;
748
+ function recordedBindParamBudget(target) {
749
+ const budget = target.capabilities.maxBindParameters ?? RECORDED_BIND_PARAM_BUDGET;
750
+ if (!Number.isSafeInteger(budget) || budget < 1) {
751
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
752
+ `backend capabilities.maxBindParameters must be a positive integer, got: ${String(budget)}`,
753
+ {
754
+ code: "INVALID_BACKEND_CAPABILITY",
755
+ capability: "maxBindParameters",
756
+ value: budget
757
+ }
758
+ );
759
+ }
760
+ return budget;
761
+ }
762
+ function recordedChunkSize(target, columnCount) {
763
+ const budget = recordedBindParamBudget(target);
764
+ return Math.max(1, Math.floor(budget / columnCount));
765
+ }
766
+ function recordedCommonCells() {
767
+ return {
768
+ history_id: () => drizzleOrm.sql`${generateId()}`,
769
+ graph_id: (row) => drizzleOrm.sql`${row.graph_id}`,
770
+ id: (row) => drizzleOrm.sql`${row.id}`,
771
+ kind: (row) => drizzleOrm.sql`${row.kind}`,
772
+ props: (row) => drizzleOrm.sql`${row.props}`,
773
+ valid_from: (row) => drizzleOrm.sql`${chunkYAZE7QZR_cjs.sqlNull(row.valid_from)}`,
774
+ valid_to: (row) => drizzleOrm.sql`${chunkYAZE7QZR_cjs.sqlNull(row.valid_to)}`,
775
+ created_at: (row) => drizzleOrm.sql`${row.created_at}`,
776
+ updated_at: (row) => drizzleOrm.sql`${row.updated_at}`,
777
+ deleted_at: (row) => drizzleOrm.sql`${chunkYAZE7QZR_cjs.sqlNull(row.deleted_at)}`,
778
+ recorded_from: (_row, recordedCommit) => drizzleOrm.sql`${recordedCommit}`,
779
+ recorded_to: () => drizzleOrm.sql`${RECORDED_MAX}`,
780
+ op: (_row, _recordedCommit, operation) => drizzleOrm.sql`${operation}`,
781
+ schema_version: () => drizzleOrm.sql`NULL`,
782
+ tx_id: () => drizzleOrm.sql`NULL`,
783
+ meta: () => drizzleOrm.sql`${RECORDED_HISTORY_META}`
784
+ };
785
+ }
786
+ var recordedNodeCells = {
787
+ ...recordedCommonCells(),
788
+ version: (row) => drizzleOrm.sql`${row.version}`
789
+ };
790
+ var recordedEdgeCells = {
791
+ ...recordedCommonCells(),
792
+ from_kind: (row) => drizzleOrm.sql`${row.from_kind}`,
793
+ from_id: (row) => drizzleOrm.sql`${row.from_id}`,
794
+ to_kind: (row) => drizzleOrm.sql`${row.to_kind}`,
795
+ to_id: (row) => drizzleOrm.sql`${row.to_id}`
796
+ };
797
+ function recordedValuesTuple(columns, cells, row, recordedCommit, operation) {
798
+ const tuple = columns.map(
799
+ (column) => cells[column](row, recordedCommit, operation)
800
+ );
801
+ return drizzleOrm.sql`(${drizzleOrm.sql.join(tuple, drizzleOrm.sql`, `)})`;
802
+ }
803
+ async function insertRecordedRows(target, table, columnList, columns, cells, inserts, recordedCommit) {
804
+ if (inserts.length === 0) return;
805
+ const values = inserts.map(
806
+ (insert) => recordedValuesTuple(
807
+ columns,
808
+ cells,
809
+ insert.row,
810
+ recordedCommit,
811
+ insert.operation
812
+ )
813
+ );
814
+ await executeStatement(
815
+ target,
816
+ drizzleOrm.sql`
817
+ INSERT INTO ${table} (${columnList})
818
+ VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
819
+ `
820
+ );
821
+ }
822
+ function recordedNodeChunkSize(target) {
823
+ return recordedChunkSize(target, RECORDED_NODE_COLUMNS.length);
824
+ }
825
+ function recordedEdgeChunkSize(target) {
826
+ return recordedChunkSize(target, RECORDED_EDGE_COLUMNS.length);
827
+ }
828
+ function insertRecordedNodeRows(target, table, inserts, recordedCommit) {
829
+ return insertRecordedRows(
830
+ target,
831
+ table,
832
+ RECORDED_NODE_COLUMN_LIST,
833
+ RECORDED_NODE_COLUMNS,
834
+ recordedNodeCells,
835
+ inserts,
836
+ recordedCommit
837
+ );
838
+ }
839
+ function insertRecordedEdgeRows(target, table, inserts, recordedCommit) {
840
+ return insertRecordedRows(
841
+ target,
842
+ table,
843
+ RECORDED_EDGE_COLUMN_LIST,
844
+ RECORDED_EDGE_COLUMNS,
845
+ recordedEdgeCells,
846
+ inserts,
847
+ recordedCommit
848
+ );
849
+ }
850
+
851
+ // src/store/recorded-capture/flush.ts
852
+ function entityKey(entity) {
853
+ switch (entity.entity) {
854
+ case "node": {
855
+ return `node\0${entity.graphId}\0${entity.kind}\0${entity.id}`;
856
+ }
857
+ case "edge": {
858
+ return `edge\0${entity.graphId}\0${entity.id}`;
859
+ }
860
+ }
861
+ }
862
+ async function closeOpenReturning(target, table, graphId, ids, recordedCommit, kind) {
863
+ const kindFilter = kind === void 0 ? drizzleOrm.sql`` : drizzleOrm.sql`AND kind = ${kind}`;
864
+ const rows = await target.execute(
865
+ asCompiledRowsSql(drizzleOrm.sql`
866
+ UPDATE ${table}
867
+ SET recorded_to = ${recordedCommit}
868
+ WHERE graph_id = ${graphId}
869
+ ${kindFilter}
870
+ AND recorded_to = ${RECORDED_MAX}
871
+ AND id IN (${chunkUNNPKQUG_cjs.sqlValueList(ids)})
872
+ RETURNING id, deleted_at
873
+ `)
874
+ );
875
+ return new Map(rows.map((row) => [row.id, chunkUNNPKQUG_cjs.isPresent(row.deleted_at)]));
876
+ }
877
+ function recordedOp(hadOpenRow, priorRowWasTombstone, after) {
878
+ if (chunkUNNPKQUG_cjs.isPresent(after.deleted_at)) return "delete";
879
+ if (!hadOpenRow || priorRowWasTombstone) return "create";
880
+ return "update";
881
+ }
882
+ function groupNodesByKind(entities) {
883
+ const byKind = /* @__PURE__ */ new Map();
884
+ for (const entity of entities) {
885
+ const group = byKind.get(entity.kind) ?? [];
886
+ group.push(entity);
887
+ byKind.set(entity.kind, group);
888
+ }
889
+ return byKind;
890
+ }
891
+ async function resolveAfterImages(entities, readMissing) {
892
+ const afterById = /* @__PURE__ */ new Map();
893
+ const needRead = [];
894
+ for (const entity of entities) {
895
+ if (entity.afterImage === void 0) {
896
+ needRead.push(entity.id);
897
+ } else {
898
+ afterById.set(entity.id, entity.afterImage);
899
+ }
900
+ }
901
+ if (needRead.length > 0) {
902
+ for (const [id, row] of await readMissing(needRead)) afterById.set(id, row);
903
+ }
904
+ return afterById;
905
+ }
906
+ function recordedInsertsFor(afterById, closed) {
907
+ return [...afterById.values()].map((row) => ({
908
+ row,
909
+ operation: recordedOp(closed.has(row.id), closed.get(row.id) ?? false, row)
910
+ }));
911
+ }
912
+ async function flushNodes(target, schema, graphId, entities, recordedCommit) {
913
+ const chunkSize = recordedNodeChunkSize(target);
914
+ for (const [kind, group] of groupNodesByKind(entities)) {
915
+ for (const entityChunk of chunkUNNPKQUG_cjs.chunk(group, chunkSize)) {
916
+ const ids = entityChunk.map((entity) => entity.id);
917
+ const closed = await closeOpenReturning(
918
+ target,
919
+ schema.recordedNodesTable,
920
+ graphId,
921
+ ids,
922
+ recordedCommit,
923
+ kind
924
+ );
925
+ const afterById = await resolveAfterImages(
926
+ entityChunk,
927
+ (missing) => getNodeRowsByIds(target, graphId, kind, missing)
928
+ );
929
+ await insertRecordedNodeRows(
930
+ target,
931
+ schema.recordedNodesTable,
932
+ recordedInsertsFor(afterById, closed),
933
+ recordedCommit
934
+ );
935
+ }
936
+ }
937
+ }
938
+ async function flushEdges(target, schema, graphId, entities, recordedCommit) {
939
+ const chunkSize = recordedEdgeChunkSize(target);
940
+ for (const entityChunk of chunkUNNPKQUG_cjs.chunk(entities, chunkSize)) {
941
+ const ids = entityChunk.map((entity) => entity.id);
942
+ const closed = await closeOpenReturning(
943
+ target,
944
+ schema.recordedEdgesTable,
945
+ graphId,
946
+ ids,
947
+ recordedCommit
948
+ );
949
+ const afterById = await resolveAfterImages(
950
+ entityChunk,
951
+ (missing) => getEdgeRowsByIds(target, graphId, missing)
952
+ );
953
+ await insertRecordedEdgeRows(
954
+ target,
955
+ schema.recordedEdgesTable,
956
+ recordedInsertsFor(afterById, closed),
957
+ recordedCommit
958
+ );
959
+ }
960
+ }
961
+ async function closeOpenByKind(target, table, graphId, kind, recordedCommit) {
962
+ await executeStatement(
963
+ target,
964
+ drizzleOrm.sql`
965
+ UPDATE ${table}
966
+ SET recorded_to = ${recordedCommit}
967
+ WHERE graph_id = ${graphId}
968
+ AND kind = ${kind}
969
+ AND recorded_to = ${RECORDED_MAX}
970
+ `
971
+ );
972
+ }
973
+ async function closeOpenEdgesByNodeKind(target, schema, graphId, nodeKind, recordedCommit) {
974
+ await executeStatement(
975
+ target,
976
+ drizzleOrm.sql`
977
+ UPDATE ${schema.recordedEdgesTable}
978
+ SET recorded_to = ${recordedCommit}
979
+ WHERE graph_id = ${graphId}
980
+ AND (from_kind = ${nodeKind} OR to_kind = ${nodeKind})
981
+ AND recorded_to = ${RECORDED_MAX}
982
+ `
983
+ );
984
+ }
985
+ async function closeRecordedHardDeletedKind(target, schema, graphId, removal, ownsWriteLock) {
986
+ const recordedCommit = await allocateRecordedCommit(
987
+ target,
988
+ schema,
989
+ graphId,
990
+ ownsWriteLock
991
+ );
992
+ if (removal.entity === "node") {
993
+ await closeOpenByKind(
994
+ target,
995
+ schema.recordedNodesTable,
996
+ graphId,
997
+ removal.kind,
998
+ recordedCommit
999
+ );
1000
+ await closeOpenEdgesByNodeKind(
1001
+ target,
1002
+ schema,
1003
+ graphId,
1004
+ removal.kind,
1005
+ recordedCommit
1006
+ );
1007
+ return;
1008
+ }
1009
+ await closeOpenByKind(
1010
+ target,
1011
+ schema.recordedEdgesTable,
1012
+ graphId,
1013
+ removal.kind,
1014
+ recordedCommit
1015
+ );
1016
+ }
1017
+ async function queryConnectedEdgeIds(target, schema, params) {
1018
+ const rows = await target.execute(
1019
+ asCompiledRowsSql(drizzleOrm.sql`
1020
+ SELECT id
1021
+ FROM ${schema.edgesTable}
1022
+ WHERE graph_id = ${params.graphId}
1023
+ AND (
1024
+ (from_kind = ${params.kind} AND from_id = ${params.id})
1025
+ OR (to_kind = ${params.kind} AND to_id = ${params.id})
1026
+ )
1027
+ `)
1028
+ );
1029
+ return rows.map((row) => row.id);
1030
+ }
1031
+
1032
+ // src/store/recorded-capture.ts
1033
+ function nodeIdentityKey(graphId, kind, id) {
1034
+ return `${graphId}\0${kind}\0${id}`;
1035
+ }
1036
+ function nodeParamsIdentityKey(params) {
1037
+ return nodeIdentityKey(params.graphId, params.kind, params.id);
1038
+ }
1039
+ function nodeRowIdentityKey(row) {
1040
+ return nodeIdentityKey(row.graph_id, row.kind, row.id);
1041
+ }
1042
+ function edgeIdentityKey(graphId, id) {
1043
+ return `${graphId}\0${id}`;
1044
+ }
1045
+ function edgeParamsIdentityKey(params) {
1046
+ return edgeIdentityKey(params.graphId, params.id);
1047
+ }
1048
+ function edgeRowIdentityKey(row) {
1049
+ return edgeIdentityKey(row.graph_id, row.id);
1050
+ }
1051
+ function createRecordedCaptureSession() {
1052
+ const touched = /* @__PURE__ */ new Map();
1053
+ let sealed = false;
1054
+ function touch(entity) {
1055
+ if (sealed) {
1056
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
1057
+ "Recorded-time capture session is sealed: a graph write happened after the transaction's capture was flushed.",
1058
+ { entity: entity.entity, graphId: entity.graphId, id: entity.id },
1059
+ {
1060
+ suggestion: "Perform all writes inside the withRecordedTransaction callback; do not reuse the transaction context after it returns."
1061
+ }
1062
+ );
1063
+ }
1064
+ touched.set(entityKey(entity), entity);
1065
+ }
1066
+ return {
1067
+ touchNode(graphId, kind, id, afterImage) {
1068
+ touch({ entity: "node", graphId, kind, id, afterImage });
1069
+ },
1070
+ touchEdge(graphId, id, afterImage) {
1071
+ touch({ entity: "edge", graphId, id, afterImage });
1072
+ },
1073
+ async flush(target, schema, ownsWriteLock) {
1074
+ if (sealed) {
1075
+ throw new chunkJIEJCTDS_cjs.ConfigurationError(
1076
+ "Recorded-time capture session was already flushed.",
1077
+ {},
1078
+ {
1079
+ suggestion: "A capture scope flushes once at its terminal point; do not flush it twice."
1080
+ }
1081
+ );
1082
+ }
1083
+ sealed = true;
1084
+ if (touched.size === 0) return;
1085
+ const byGraph = chunkUNNPKQUG_cjs.groupBy(touched.values(), (entity) => entity.graphId);
1086
+ for (const [graphId, entities] of byGraph) {
1087
+ const recordedCommit = await allocateRecordedCommit(
1088
+ target,
1089
+ schema,
1090
+ graphId,
1091
+ ownsWriteLock
1092
+ );
1093
+ const nodes = entities.filter(
1094
+ (entity) => entity.entity === "node"
1095
+ );
1096
+ const edges = entities.filter(
1097
+ (entity) => entity.entity === "edge"
1098
+ );
1099
+ await flushNodes(target, schema, graphId, nodes, recordedCommit);
1100
+ await flushEdges(target, schema, graphId, edges, recordedCommit);
1101
+ }
1102
+ touched.clear();
1103
+ }
1104
+ };
1105
+ }
1106
+ function createRecordedTransactionBackend(target, session, schema) {
1107
+ const nodeDispatch = nodeInsertDispatch(target);
1108
+ const edgeDispatch = edgeInsertDispatch(target);
1109
+ async function lockGraph(graphId) {
1110
+ await lockRecordedGraphWrite(target, graphId);
1111
+ }
1112
+ async function lockGraphs(params) {
1113
+ await lockRecordedGraphWrites(
1114
+ target,
1115
+ params.map((parameter) => parameter.graphId)
1116
+ );
1117
+ }
1118
+ return chunkUNNPKQUG_cjs.createBackendOverlay(target, {
1119
+ ...rawWriteGuards(target, "tx.backend"),
1120
+ async insertNode(params) {
1121
+ await lockGraph(params.graphId);
1122
+ const row = await target.insertNode(params);
1123
+ session.touchNode(params.graphId, params.kind, params.id, row);
1124
+ return row;
1125
+ },
1126
+ ...target.insertNodeNoReturn === void 0 ? {} : {
1127
+ async insertNodeNoReturn(params) {
1128
+ await lockGraph(params.graphId);
1129
+ await runInsertNoReturn(nodeDispatch, params);
1130
+ session.touchNode(params.graphId, params.kind, params.id);
1131
+ }
1132
+ },
1133
+ ...target.insertNodesBatch === void 0 ? {} : {
1134
+ async insertNodesBatch(params) {
1135
+ await lockGraphs(params);
1136
+ await runInsertBatch(nodeDispatch, params);
1137
+ for (const node of params) {
1138
+ session.touchNode(node.graphId, node.kind, node.id);
1139
+ }
1140
+ }
1141
+ },
1142
+ ...target.insertNodesBatchReturning === void 0 ? {} : {
1143
+ async insertNodesBatchReturning(params) {
1144
+ await lockGraphs(params);
1145
+ const rows = await runInsertBatchReturning(nodeDispatch, params);
1146
+ const rowsByIdentity = new Map(
1147
+ rows.map((row) => [nodeRowIdentityKey(row), row])
1148
+ );
1149
+ for (const node of params) {
1150
+ session.touchNode(
1151
+ node.graphId,
1152
+ node.kind,
1153
+ node.id,
1154
+ rowsByIdentity.get(nodeParamsIdentityKey(node))
1155
+ );
1156
+ }
1157
+ return rows;
1158
+ }
1159
+ },
1160
+ async updateNode(params) {
1161
+ await lockGraph(params.graphId);
1162
+ const row = await target.updateNode(params);
1163
+ session.touchNode(params.graphId, params.kind, params.id, row);
1164
+ return row;
1165
+ },
1166
+ async deleteNode(params) {
1167
+ await lockGraph(params.graphId);
1168
+ await target.deleteNode(params);
1169
+ session.touchNode(params.graphId, params.kind, params.id);
1170
+ },
1171
+ async hardDeleteNode(params) {
1172
+ await lockGraph(params.graphId);
1173
+ const connectedEdgeIds = await queryConnectedEdgeIds(
1174
+ target,
1175
+ schema,
1176
+ params
1177
+ );
1178
+ await target.hardDeleteNode(params);
1179
+ session.touchNode(params.graphId, params.kind, params.id);
1180
+ for (const edgeId of connectedEdgeIds) {
1181
+ session.touchEdge(params.graphId, edgeId);
1182
+ }
1183
+ },
1184
+ async insertEdge(params) {
1185
+ await lockGraph(params.graphId);
1186
+ const row = await target.insertEdge(params);
1187
+ session.touchEdge(params.graphId, params.id, row);
1188
+ return row;
1189
+ },
1190
+ ...target.insertEdgeNoReturn === void 0 ? {} : {
1191
+ async insertEdgeNoReturn(params) {
1192
+ await lockGraph(params.graphId);
1193
+ await runInsertNoReturn(edgeDispatch, params);
1194
+ session.touchEdge(params.graphId, params.id);
1195
+ }
1196
+ },
1197
+ ...target.insertEdgesBatch === void 0 ? {} : {
1198
+ async insertEdgesBatch(params) {
1199
+ await lockGraphs(params);
1200
+ await runInsertBatch(edgeDispatch, params);
1201
+ for (const edge of params) {
1202
+ session.touchEdge(edge.graphId, edge.id);
1203
+ }
1204
+ }
1205
+ },
1206
+ ...target.insertEdgesBatchReturning === void 0 ? {} : {
1207
+ async insertEdgesBatchReturning(params) {
1208
+ await lockGraphs(params);
1209
+ const rows = await runInsertBatchReturning(edgeDispatch, params);
1210
+ const rowsByIdentity = new Map(
1211
+ rows.map((row) => [edgeRowIdentityKey(row), row])
1212
+ );
1213
+ for (const edge of params) {
1214
+ session.touchEdge(
1215
+ edge.graphId,
1216
+ edge.id,
1217
+ rowsByIdentity.get(edgeParamsIdentityKey(edge))
1218
+ );
1219
+ }
1220
+ return rows;
1221
+ }
1222
+ },
1223
+ async updateEdge(params) {
1224
+ await lockGraph(params.graphId);
1225
+ const row = await target.updateEdge(params);
1226
+ session.touchEdge(params.graphId, params.id, row);
1227
+ return row;
1228
+ },
1229
+ async deleteEdge(params) {
1230
+ await lockGraph(params.graphId);
1231
+ await target.deleteEdge(params);
1232
+ session.touchEdge(params.graphId, params.id);
1233
+ },
1234
+ async hardDeleteEdge(params) {
1235
+ await lockGraph(params.graphId);
1236
+ await target.hardDeleteEdge(params);
1237
+ session.touchEdge(params.graphId, params.id);
1238
+ }
1239
+ });
1240
+ }
1241
+ function createRecordedTransactionScope(target, schema, ownsWriteLock = false) {
1242
+ requireCaptureStatements(target);
1243
+ const session = createRecordedCaptureSession();
1244
+ const resolvedSchema = schema ?? requireRecordedSchema(target);
1245
+ return {
1246
+ backend: createRecordedTransactionBackend(target, session, resolvedSchema),
1247
+ async flush() {
1248
+ await chunkRHZWOJVA_cjs.withRecordedRelationsPrecondition(
1249
+ session.flush(target, resolvedSchema, ownsWriteLock),
1250
+ { dialect: target.dialect, surface: "capture-flush" }
1251
+ );
1252
+ }
1253
+ };
1254
+ }
1255
+ async function runCapturedAutocommit(backend, schema, fn, options) {
1256
+ assertRequestedRecordedIsolation(backend, options);
1257
+ return backend.transaction(async (target) => {
1258
+ await assertRecordedCaptureTransactionIsolation(target);
1259
+ const scope = createRecordedTransactionScope(target, schema, true);
1260
+ const result = await fn(scope.backend);
1261
+ await scope.flush();
1262
+ return result;
1263
+ }, options);
1264
+ }
1265
+ function createRecordedBackend(backend, schema) {
1266
+ assertCapturableBackend(backend);
1267
+ const capture = (fn) => runCapturedAutocommit(backend, schema, fn);
1268
+ return chunkUNNPKQUG_cjs.createBackendOverlay(backend, {
1269
+ ...rawWriteGuards(backend, "backend"),
1270
+ async insertNode(params) {
1271
+ return capture((target) => target.insertNode(params));
1272
+ },
1273
+ ...backend.insertNodeNoReturn === void 0 ? {} : {
1274
+ async insertNodeNoReturn(params) {
1275
+ await capture(
1276
+ (target) => runInsertNoReturn(nodeInsertDispatch(target), params)
1277
+ );
1278
+ }
1279
+ },
1280
+ ...backend.insertNodesBatch === void 0 ? {} : {
1281
+ async insertNodesBatch(params) {
1282
+ await capture(
1283
+ (target) => runInsertBatch(nodeInsertDispatch(target), params)
1284
+ );
1285
+ }
1286
+ },
1287
+ ...backend.insertNodesBatchReturning === void 0 ? {} : {
1288
+ async insertNodesBatchReturning(params) {
1289
+ return capture(
1290
+ (target) => runInsertBatchReturning(nodeInsertDispatch(target), params)
1291
+ );
1292
+ }
1293
+ },
1294
+ async updateNode(params) {
1295
+ return capture((target) => target.updateNode(params));
1296
+ },
1297
+ async deleteNode(params) {
1298
+ await capture((target) => target.deleteNode(params));
1299
+ },
1300
+ async hardDeleteNode(params) {
1301
+ await capture((target) => target.hardDeleteNode(params));
1302
+ },
1303
+ async insertEdge(params) {
1304
+ return capture((target) => target.insertEdge(params));
1305
+ },
1306
+ ...backend.insertEdgeNoReturn === void 0 ? {} : {
1307
+ async insertEdgeNoReturn(params) {
1308
+ await capture(
1309
+ (target) => runInsertNoReturn(edgeInsertDispatch(target), params)
1310
+ );
1311
+ }
1312
+ },
1313
+ ...backend.insertEdgesBatch === void 0 ? {} : {
1314
+ async insertEdgesBatch(params) {
1315
+ await capture(
1316
+ (target) => runInsertBatch(edgeInsertDispatch(target), params)
1317
+ );
1318
+ }
1319
+ },
1320
+ ...backend.insertEdgesBatchReturning === void 0 ? {} : {
1321
+ async insertEdgesBatchReturning(params) {
1322
+ return capture(
1323
+ (target) => runInsertBatchReturning(edgeInsertDispatch(target), params)
1324
+ );
1325
+ }
1326
+ },
1327
+ async updateEdge(params) {
1328
+ return capture((target) => target.updateEdge(params));
1329
+ },
1330
+ async deleteEdge(params) {
1331
+ await capture((target) => target.deleteEdge(params));
1332
+ },
1333
+ async hardDeleteEdge(params) {
1334
+ await capture((target) => target.hardDeleteEdge(params));
1335
+ },
1336
+ async transaction(fn, options) {
1337
+ assertRequestedRecordedIsolation(backend, options);
1338
+ return backend.transaction(async (target) => {
1339
+ await assertRecordedCaptureTransactionIsolation(target);
1340
+ const scope = createRecordedTransactionScope(target, schema, true);
1341
+ const result = await fn(scope.backend, createHistoryUnsafeSqlRef());
1342
+ await scope.flush();
1343
+ return result;
1344
+ }, options);
1345
+ },
1346
+ ...backend.adoptTransaction === void 0 ? {} : {
1347
+ adoptTransaction(externalTx) {
1348
+ throw recordedCaptureRequiresCallbackTransactionError({
1349
+ externalTxType: typeof externalTx
1350
+ });
1351
+ }
1352
+ }
1353
+ });
1354
+ }
1355
+
1356
+ // src/store/embedding-sync.ts
1357
+ var embeddingFieldsCache = /* @__PURE__ */ new WeakMap();
1358
+ function getEmbeddingFields(schema) {
1359
+ const cached = embeddingFieldsCache.get(schema);
1360
+ if (cached) return cached;
1361
+ const fields = chunkJQGIPGVL_cjs.resolveEmbeddingFields(schema);
1362
+ embeddingFieldsCache.set(schema, fields);
1363
+ return fields;
1364
+ }
1365
+ async function syncEmbeddings(ctx, schema, props) {
1366
+ const { backend } = ctx;
1367
+ if (!backend.upsertEmbedding || !backend.deleteEmbedding) {
1368
+ return;
1369
+ }
1370
+ const embeddingFields = getEmbeddingFields(schema);
1371
+ if (embeddingFields.length === 0) {
1372
+ return;
1373
+ }
1374
+ for (const field of embeddingFields) {
1375
+ const value = props[field.fieldPath];
1376
+ if (isValidEmbeddingValue(value)) {
1377
+ await backend.upsertEmbedding({
1378
+ graphId: ctx.graphId,
1379
+ nodeKind: ctx.nodeKind,
1380
+ nodeId: ctx.nodeId,
1381
+ fieldPath: field.fieldPath,
1382
+ embedding: value,
1383
+ dimensions: field.dimensions,
1384
+ metric: field.metric,
1385
+ indexType: field.indexType
1386
+ });
1387
+ } else if (value === void 0) {
1388
+ await backend.deleteEmbedding({
1389
+ graphId: ctx.graphId,
1390
+ nodeKind: ctx.nodeKind,
1391
+ nodeId: ctx.nodeId,
1392
+ fieldPath: field.fieldPath,
1393
+ dimensions: field.dimensions,
1394
+ metric: field.metric,
1395
+ indexType: field.indexType
1396
+ });
1397
+ }
1398
+ }
1399
+ }
1400
+ async function deleteNodeEmbeddings(ctx, schema) {
1401
+ const { backend } = ctx;
1402
+ if (!backend.deleteEmbedding) {
1403
+ return;
1404
+ }
1405
+ const embeddingFields = getEmbeddingFields(schema);
1406
+ if (embeddingFields.length === 0) {
1407
+ return;
1408
+ }
1409
+ for (const field of embeddingFields) {
1410
+ await backend.deleteEmbedding({
1411
+ graphId: ctx.graphId,
1412
+ nodeKind: ctx.nodeKind,
1413
+ nodeId: ctx.nodeId,
1414
+ fieldPath: field.fieldPath,
1415
+ dimensions: field.dimensions,
1416
+ metric: field.metric,
1417
+ indexType: field.indexType
1418
+ });
1419
+ }
1420
+ }
1421
+ function isValidEmbeddingValue(value) {
1422
+ if (!Array.isArray(value)) {
1423
+ return false;
1424
+ }
1425
+ return value.every((n) => typeof n === "number" && Number.isFinite(n));
1426
+ }
1427
+
1428
+ // src/store/fulltext-sync.ts
1429
+ var searchableFieldsCache = /* @__PURE__ */ new WeakMap();
1430
+ function getSearchableFields(schema) {
1431
+ const cached = searchableFieldsCache.get(schema);
1432
+ if (cached) return cached;
1433
+ const fields = computeSearchableFields(schema);
1434
+ searchableFieldsCache.set(schema, fields);
1435
+ return fields;
1436
+ }
1437
+ function computeSearchableFields(schema) {
1438
+ if (schema.type !== "object") return [];
1439
+ const def = schema.def;
1440
+ const shape = def.shape;
1441
+ if (!shape) return [];
1442
+ const fields = [];
1443
+ for (const [fieldPath, fieldSchema] of Object.entries(shape)) {
1444
+ const metadata = chunkJQGIPGVL_cjs.getSearchableMetadata(fieldSchema);
1445
+ if (metadata !== void 0) {
1446
+ fields.push({ fieldPath, metadata });
1447
+ }
1448
+ }
1449
+ warnIfConflictingLanguages(fields);
1450
+ return fields;
1451
+ }
1452
+ function warnIfConflictingLanguages(fields) {
1453
+ if (fields.length < 2) return;
1454
+ const languages = new Set(fields.map((field) => field.metadata.language));
1455
+ if (languages.size < 2) return;
1456
+ if (typeof console === "undefined" || typeof console.warn !== "function") {
1457
+ return;
1458
+ }
1459
+ const fieldSummary = fields.map((field) => `${field.fieldPath}=${field.metadata.language}`).join(", ");
1460
+ const winning = fields[0]?.metadata.language ?? chunkJQGIPGVL_cjs.DEFAULT_SEARCHABLE_LANGUAGE;
1461
+ console.warn(
1462
+ `[typegraph] searchable() fields declare conflicting languages (${fieldSummary}). The first field's language ("${winning}") is recorded on the fulltext row; true multilingual indexing requires a dedicated node kind per language.`
1463
+ );
1464
+ }
1465
+ var FIELD_SEPARATOR = "\n";
1466
+ function resolveCombinedLanguage(fields) {
1467
+ return fields[0]?.metadata.language ?? chunkJQGIPGVL_cjs.DEFAULT_SEARCHABLE_LANGUAGE;
1468
+ }
1469
+ function computeFulltextContent(schema, props) {
1470
+ const searchableFields = getSearchableFields(schema);
1471
+ if (searchableFields.length === 0) return void 0;
1472
+ const parts = [];
1473
+ for (const field of searchableFields) {
1474
+ const value = props[field.fieldPath];
1475
+ if (typeof value === "string" && value.length > 0) {
1476
+ parts.push(value);
1477
+ }
1478
+ }
1479
+ if (parts.length === 0) return void 0;
1480
+ return {
1481
+ content: parts.join(FIELD_SEPARATOR),
1482
+ language: resolveCombinedLanguage(searchableFields)
1483
+ };
1484
+ }
1485
+ async function syncFulltext(ctx, schema, props) {
1486
+ const { backend } = ctx;
1487
+ if (!backend.upsertFulltext || !backend.deleteFulltext) {
1488
+ return;
1489
+ }
1490
+ const computed = computeFulltextContent(schema, props);
1491
+ if (computed !== void 0) {
1492
+ await backend.upsertFulltext({
1493
+ graphId: ctx.graphId,
1494
+ nodeKind: ctx.nodeKind,
1495
+ nodeId: ctx.nodeId,
1496
+ content: computed.content,
1497
+ language: computed.language
1498
+ });
1499
+ return;
1500
+ }
1501
+ if (getSearchableFields(schema).length === 0) return;
1502
+ await backend.deleteFulltext({
1503
+ graphId: ctx.graphId,
1504
+ nodeKind: ctx.nodeKind,
1505
+ nodeId: ctx.nodeId
1506
+ });
1507
+ }
1508
+ async function deleteNodeFulltext(ctx, schema) {
1509
+ const { backend } = ctx;
1510
+ if (!backend.deleteFulltext) {
1511
+ return;
1512
+ }
1513
+ if (getSearchableFields(schema).length === 0) {
1514
+ return;
1515
+ }
1516
+ await backend.deleteFulltext({
1517
+ graphId: ctx.graphId,
1518
+ nodeKind: ctx.nodeKind,
1519
+ nodeId: ctx.nodeId
1520
+ });
1521
+ }
1522
+
1523
+ // src/constraints/index.ts
1524
+ var UNIQUE_KEY_SEPARATOR = "";
1525
+ var UNIQUE_KEY_NULL_MARKER = "";
1526
+ function computeUniqueKey(props, fields, collation) {
1527
+ const values = fields.map((field) => {
1528
+ const value = props[field];
1529
+ if (value === void 0 || value === null) {
1530
+ return UNIQUE_KEY_NULL_MARKER;
1531
+ }
1532
+ const stringValue = typeof value === "string" ? value : typeof value === "number" || typeof value === "boolean" ? value.toString() : JSON.stringify(value);
1533
+ return collation === "caseInsensitive" ? stringValue.toLowerCase() : stringValue;
1534
+ });
1535
+ return values.join(UNIQUE_KEY_SEPARATOR);
1536
+ }
1537
+ function checkWherePredicate(constraint, props) {
1538
+ if (!constraint.where) {
1539
+ return true;
1540
+ }
1541
+ const predicateBuilder = buildPredicateContext(props);
1542
+ const predicate = constraint.where(predicateBuilder);
1543
+ return evaluatePredicate(predicate, props);
1544
+ }
1545
+ function buildPredicateContext(props) {
1546
+ const context = {};
1547
+ for (const key of Object.keys(props)) {
1548
+ context[key] = {
1549
+ isNull: () => ({
1550
+ __type: "unique_predicate",
1551
+ field: key,
1552
+ op: "isNull"
1553
+ }),
1554
+ isNotNull: () => ({
1555
+ __type: "unique_predicate",
1556
+ field: key,
1557
+ op: "isNotNull"
1558
+ })
1559
+ };
1560
+ }
1561
+ return context;
1562
+ }
1563
+ function evaluatePredicate(predicate, props) {
1564
+ if (typeof predicate !== "object" || predicate === null || !("__type" in predicate)) {
1565
+ return true;
1566
+ }
1567
+ const pred = predicate;
1568
+ if (pred.__type !== "unique_predicate") {
1569
+ return true;
1570
+ }
1571
+ const value = props[pred.field];
1572
+ if (pred.op === "isNull") {
1573
+ return value === null || value === void 0;
1574
+ }
1575
+ return chunkUNNPKQUG_cjs.isPresent(value);
1576
+ }
1577
+ function getKindsForUniquenessCheck(baseKind, scope, registry) {
1578
+ if (scope === "kind") {
1579
+ return [baseKind];
1580
+ }
1581
+ const root = findRootAncestor(baseKind, registry);
1582
+ return registry.expandSubClasses(root);
1583
+ }
1584
+ function findRootAncestor(kind, registry) {
1585
+ const ancestors = registry.getAncestors(kind);
1586
+ if (ancestors.size === 0) {
1587
+ return kind;
1588
+ }
1589
+ for (const ancestor of ancestors) {
1590
+ if (registry.getAncestors(ancestor).size === 0) {
1591
+ return ancestor;
1592
+ }
1593
+ }
1594
+ const firstAncestor = [...ancestors][0];
1595
+ return firstAncestor ? findRootAncestor(firstAncestor, registry) : kind;
1596
+ }
1597
+ function checkCardinality(edgeKind, fromKind, fromId, cardinality, existingEdgeCount, hasActiveEdge) {
1598
+ switch (cardinality) {
1599
+ case "many": {
1600
+ return void 0;
1601
+ }
1602
+ case "one": {
1603
+ if (existingEdgeCount > 0) {
1604
+ return new chunkJIEJCTDS_cjs.CardinalityError({
1605
+ edgeKind,
1606
+ fromKind,
1607
+ fromId,
1608
+ cardinality: "one",
1609
+ existingCount: existingEdgeCount
1610
+ });
1611
+ }
1612
+ return void 0;
1613
+ }
1614
+ case "unique": {
1615
+ return void 0;
1616
+ }
1617
+ case "oneActive": {
1618
+ if (hasActiveEdge) {
1619
+ return new chunkJIEJCTDS_cjs.CardinalityError({
1620
+ edgeKind,
1621
+ fromKind,
1622
+ fromId,
1623
+ cardinality: "oneActive",
1624
+ existingCount: 1
1625
+ });
1626
+ }
1627
+ return void 0;
1628
+ }
1629
+ }
1630
+ }
1631
+ function checkUniqueEdge(edgeKind, fromKind, fromId, _toKind, _toId, existingCount) {
1632
+ if (existingCount > 0) {
1633
+ return new chunkJIEJCTDS_cjs.CardinalityError({
1634
+ edgeKind,
1635
+ fromKind,
1636
+ fromId,
1637
+ cardinality: "unique",
1638
+ existingCount
1639
+ });
1640
+ }
1641
+ return void 0;
1642
+ }
1643
+ function validateEdgeEndpoints(edgeKind, fromKind, toKind, registration, registry) {
1644
+ const validFromKinds = registration.from.map((node) => node.kind);
1645
+ const fromValid = validFromKinds.some(
1646
+ (validKind) => registry.isAssignableTo(fromKind, validKind)
1647
+ );
1648
+ if (!fromValid) {
1649
+ return new chunkJIEJCTDS_cjs.EndpointError({
1650
+ edgeKind,
1651
+ endpoint: "from",
1652
+ actualKind: fromKind,
1653
+ expectedKinds: validFromKinds
1654
+ });
1655
+ }
1656
+ const validToKinds = registration.to.map((node) => node.kind);
1657
+ const toValid = validToKinds.some(
1658
+ (validKind) => registry.isAssignableTo(toKind, validKind)
1659
+ );
1660
+ if (!toValid) {
1661
+ return new chunkJIEJCTDS_cjs.EndpointError({
1662
+ edgeKind,
1663
+ endpoint: "to",
1664
+ actualKind: toKind,
1665
+ expectedKinds: validToKinds
1666
+ });
1667
+ }
1668
+ return void 0;
1669
+ }
1670
+ function checkDisjointness(nodeId, nodeKind, existingKinds, registry) {
1671
+ for (const existingKind of existingKinds) {
1672
+ if (registry.areDisjoint(nodeKind, existingKind)) {
1673
+ return new chunkJIEJCTDS_cjs.DisjointError({
1674
+ nodeId,
1675
+ attemptedKind: nodeKind,
1676
+ conflictingKind: existingKind
1677
+ });
1678
+ }
1679
+ }
1680
+ return void 0;
1681
+ }
1682
+
1683
+ // src/store/uniqueness.ts
1684
+ function createUniquenessContext(graphId, registry, backend) {
1685
+ return { graphId, registry, backend };
1686
+ }
1687
+ async function checkUniquenessConstraints(ctx, kind, id, props, constraints) {
1688
+ for (const constraint of constraints) {
1689
+ if (!checkWherePredicate(constraint, props)) {
1690
+ continue;
1691
+ }
1692
+ const key = computeUniqueKey(
1693
+ props,
1694
+ constraint.fields,
1695
+ constraint.collation
1696
+ );
1697
+ const kindsToCheck = getKindsForUniquenessCheck(
1698
+ kind,
1699
+ constraint.scope,
1700
+ ctx.registry
1701
+ );
1702
+ for (const kindToCheck of kindsToCheck) {
1703
+ const existing = await ctx.backend.checkUnique({
1704
+ graphId: ctx.graphId,
1705
+ nodeKind: kindToCheck,
1706
+ constraintName: constraint.name,
1707
+ key
1708
+ });
1709
+ if (existing && existing.node_id !== id) {
1710
+ throw new chunkJIEJCTDS_cjs.UniquenessError({
1711
+ constraintName: constraint.name,
1712
+ kind: kindToCheck,
1713
+ existingId: existing.node_id,
1714
+ newId: id,
1715
+ fields: constraint.fields
1716
+ });
1717
+ }
1718
+ }
1719
+ }
1720
+ }
1721
+ async function insertUniquenessEntries(ctx, kind, id, props, constraints) {
1722
+ for (const constraint of constraints) {
1723
+ if (!checkWherePredicate(constraint, props)) {
1724
+ continue;
1725
+ }
1726
+ const key = computeUniqueKey(
1727
+ props,
1728
+ constraint.fields,
1729
+ constraint.collation
1730
+ );
1731
+ await ctx.backend.insertUnique({
1732
+ graphId: ctx.graphId,
1733
+ nodeKind: kind,
1734
+ constraintName: constraint.name,
1735
+ key,
1736
+ nodeId: id,
1737
+ concreteKind: kind
1738
+ });
1739
+ }
1740
+ }
1741
+ async function deleteUniquenessEntries(ctx, kind, props, constraints) {
1742
+ for (const constraint of constraints) {
1743
+ if (!checkWherePredicate(constraint, props)) {
1744
+ continue;
1745
+ }
1746
+ const key = computeUniqueKey(
1747
+ props,
1748
+ constraint.fields,
1749
+ constraint.collation
1750
+ );
1751
+ await ctx.backend.deleteUnique({
1752
+ graphId: ctx.graphId,
1753
+ nodeKind: kind,
1754
+ constraintName: constraint.name,
1755
+ key
1756
+ });
1757
+ }
1758
+ }
1759
+ async function updateUniquenessEntries(ctx, kind, id, oldProps, newProps, constraints) {
1760
+ const pending = [];
1761
+ for (const constraint of constraints) {
1762
+ const oldApplies = checkWherePredicate(constraint, oldProps);
1763
+ const newApplies = checkWherePredicate(constraint, newProps);
1764
+ const oldKey = oldApplies ? computeUniqueKey(oldProps, constraint.fields, constraint.collation) : void 0;
1765
+ const newKey = newApplies ? computeUniqueKey(newProps, constraint.fields, constraint.collation) : void 0;
1766
+ if (!oldApplies && !newApplies) {
1767
+ continue;
1768
+ }
1769
+ if (oldApplies && newApplies && oldKey === newKey) {
1770
+ continue;
1771
+ }
1772
+ if (newApplies && newKey !== void 0) {
1773
+ const kindsToCheck = getKindsForUniquenessCheck(
1774
+ kind,
1775
+ constraint.scope,
1776
+ ctx.registry
1777
+ );
1778
+ for (const kindToCheck of kindsToCheck) {
1779
+ const existing = await ctx.backend.checkUnique({
1780
+ graphId: ctx.graphId,
1781
+ nodeKind: kindToCheck,
1782
+ constraintName: constraint.name,
1783
+ key: newKey
1784
+ });
1785
+ if (existing && existing.node_id !== id) {
1786
+ throw new chunkJIEJCTDS_cjs.UniquenessError({
1787
+ constraintName: constraint.name,
1788
+ kind: kindToCheck,
1789
+ existingId: existing.node_id,
1790
+ newId: id,
1791
+ fields: constraint.fields
1792
+ });
1793
+ }
1794
+ }
1795
+ }
1796
+ pending.push({ constraintName: constraint.name, oldKey, newKey });
1797
+ }
1798
+ for (const mutation of pending) {
1799
+ if (mutation.oldKey !== void 0) {
1800
+ await ctx.backend.deleteUnique({
1801
+ graphId: ctx.graphId,
1802
+ nodeKind: kind,
1803
+ constraintName: mutation.constraintName,
1804
+ key: mutation.oldKey
1805
+ });
1806
+ }
1807
+ }
1808
+ for (const mutation of pending) {
1809
+ if (mutation.newKey !== void 0) {
1810
+ await ctx.backend.insertUnique({
1811
+ graphId: ctx.graphId,
1812
+ nodeKind: kind,
1813
+ constraintName: mutation.constraintName,
1814
+ key: mutation.newKey,
1815
+ nodeId: id,
1816
+ concreteKind: kind
1817
+ });
1818
+ }
1819
+ }
1820
+ }
1821
+
1822
+ // src/store/operations/node-write-pipeline.ts
1823
+ function createNodeWriteContext(graphId, registry, lock) {
1824
+ return { graphId, registry, lock };
1825
+ }
1826
+ function uniquenessContext(ctx, backend) {
1827
+ return createUniquenessContext(ctx.graphId, ctx.registry, backend);
1828
+ }
1829
+ function nodeSyncContext(ctx, kind, id, backend) {
1830
+ return { graphId: ctx.graphId, nodeKind: kind, nodeId: id, backend };
1831
+ }
1832
+ async function enforceNodeDeleteBehavior(ctx, args, backend, policy) {
1833
+ if (policy?.enforceDeleteBehavior === false) return;
1834
+ const behavior = args.onDelete ?? "restrict";
1835
+ const connectedEdges = await backend.findEdgesConnectedTo({
1836
+ graphId: ctx.graphId,
1837
+ nodeKind: args.kind,
1838
+ nodeId: args.id
1839
+ });
1840
+ if (connectedEdges.length === 0) return;
1841
+ switch (behavior) {
1842
+ case "restrict": {
1843
+ throw new chunkJIEJCTDS_cjs.RestrictedDeleteError({
1844
+ nodeKind: args.kind,
1845
+ nodeId: args.id,
1846
+ edgeCount: connectedEdges.length,
1847
+ edgeKinds: [...new Set(connectedEdges.map((edge) => edge.kind))]
1848
+ });
1849
+ }
1850
+ case "cascade":
1851
+ case "disconnect": {
1852
+ for (const edge of connectedEdges) {
1853
+ await (args.mode === "hard" ? backend.hardDeleteEdge({ graphId: ctx.graphId, id: edge.id }) : backend.deleteEdge({ graphId: ctx.graphId, id: edge.id }));
1854
+ }
1855
+ break;
1856
+ }
1857
+ }
1858
+ }
1859
+ async function applyNodeInsertSideEffects(ctx, args, backend) {
1860
+ await insertUniquenessEntries(
1861
+ uniquenessContext(ctx, backend),
1862
+ args.kind,
1863
+ args.id,
1864
+ args.props,
1865
+ args.uniqueConstraints
1866
+ );
1867
+ await Promise.all([
1868
+ syncEmbeddings(
1869
+ nodeSyncContext(ctx, args.kind, args.id, backend),
1870
+ args.schema,
1871
+ args.props
1872
+ ),
1873
+ syncFulltext(
1874
+ nodeSyncContext(ctx, args.kind, args.id, backend),
1875
+ args.schema,
1876
+ args.props
1877
+ )
1878
+ ]);
1879
+ }
1880
+ function parseRowProps(row) {
1881
+ return JSON.parse(row.props);
1882
+ }
1883
+ async function applyNodeUpdate(ctx, args, backend) {
1884
+ const { kind, id } = args.existing;
1885
+ if (args.existing.deleted_at === void 0) {
1886
+ await updateUniquenessEntries(
1887
+ uniquenessContext(ctx, backend),
1888
+ kind,
1889
+ id,
1890
+ parseRowProps(args.existing),
1891
+ args.validatedProps,
1892
+ args.uniqueConstraints
1893
+ );
1894
+ } else {
1895
+ await checkUniquenessConstraints(
1896
+ uniquenessContext(ctx, backend),
1897
+ kind,
1898
+ id,
1899
+ args.validatedProps,
1900
+ args.uniqueConstraints
1901
+ );
1902
+ await insertUniquenessEntries(
1903
+ uniquenessContext(ctx, backend),
1904
+ kind,
1905
+ id,
1906
+ args.validatedProps,
1907
+ args.uniqueConstraints
1908
+ );
1909
+ }
1910
+ const updateParams = {
1911
+ graphId: ctx.graphId,
1912
+ kind,
1913
+ id,
1914
+ props: args.validatedProps,
1915
+ incrementVersion: true
1916
+ };
1917
+ if (args.validTo !== void 0) updateParams.validTo = args.validTo;
1918
+ if (args.clearDeleted) updateParams.clearDeleted = true;
1919
+ const row = await backend.updateNode(updateParams);
1920
+ await Promise.all([
1921
+ syncEmbeddings(
1922
+ nodeSyncContext(ctx, kind, id, backend),
1923
+ args.schema,
1924
+ args.validatedProps
1925
+ ),
1926
+ syncFulltext(
1927
+ nodeSyncContext(ctx, kind, id, backend),
1928
+ args.schema,
1929
+ args.validatedProps
1930
+ )
1931
+ ]);
1932
+ return row;
1933
+ }
1934
+ async function applyNodeSoftDelete(ctx, args, backend, policy) {
1935
+ const { kind, id } = args.existing;
1936
+ await enforceNodeDeleteBehavior(
1937
+ ctx,
1938
+ { kind, id, mode: "soft", onDelete: args.onDelete },
1939
+ backend,
1940
+ policy
1941
+ );
1942
+ await backend.deleteNode({
1943
+ graphId: ctx.graphId,
1944
+ kind,
1945
+ id
1946
+ });
1947
+ await deleteUniquenessEntries(
1948
+ uniquenessContext(ctx, backend),
1949
+ kind,
1950
+ parseRowProps(args.existing),
1951
+ args.uniqueConstraints
1952
+ );
1953
+ await deleteNodeEmbeddings(
1954
+ nodeSyncContext(ctx, kind, id, backend),
1955
+ args.schema
1956
+ );
1957
+ await deleteNodeFulltext(
1958
+ nodeSyncContext(ctx, kind, id, backend),
1959
+ args.schema
1960
+ );
1961
+ }
1962
+ async function applyNodeHardDelete(ctx, args, backend) {
1963
+ await enforceNodeDeleteBehavior(
1964
+ ctx,
1965
+ { kind: args.kind, id: args.id, mode: "hard", onDelete: args.onDelete },
1966
+ backend
1967
+ );
1968
+ await backend.hardDeleteNode({
1969
+ graphId: ctx.graphId,
1970
+ kind: args.kind,
1971
+ id: args.id
1972
+ });
1973
+ await deleteNodeEmbeddings(
1974
+ nodeSyncContext(ctx, args.kind, args.id, backend),
1975
+ args.schema
1976
+ );
1977
+ }
1978
+ async function applyNodeResurrect(ctx, args, backend) {
1979
+ const { kind, id } = args.existing;
1980
+ const props = parseRowProps(args.existing);
1981
+ await checkUniquenessConstraints(
1982
+ uniquenessContext(ctx, backend),
1983
+ kind,
1984
+ id,
1985
+ props,
1986
+ args.uniqueConstraints
1987
+ );
1988
+ await insertUniquenessEntries(
1989
+ uniquenessContext(ctx, backend),
1990
+ kind,
1991
+ id,
1992
+ props,
1993
+ args.uniqueConstraints
1994
+ );
1995
+ const row = await backend.updateNode({
1996
+ graphId: ctx.graphId,
1997
+ kind,
1998
+ id,
1999
+ props,
2000
+ incrementVersion: true,
2001
+ clearDeleted: true
2002
+ });
2003
+ await Promise.all([
2004
+ syncEmbeddings(nodeSyncContext(ctx, kind, id, backend), args.schema, props),
2005
+ syncFulltext(nodeSyncContext(ctx, kind, id, backend), args.schema, props)
2006
+ ]);
2007
+ return row;
2008
+ }
2009
+
2010
+ exports.ALIAS_CTE_PREFIX = ALIAS_CTE_PREFIX;
2011
+ exports.DEFAULT_SQL_SCHEMA = DEFAULT_SQL_SCHEMA;
2012
+ exports.EMBEDDINGS_CTE_ALIAS = EMBEDDINGS_CTE_ALIAS;
2013
+ exports.FULLTEXT_CTE_ALIAS = FULLTEXT_CTE_ALIAS;
2014
+ exports.HYBRID_CANDIDATES_CTE_ALIAS = HYBRID_CANDIDATES_CTE_ALIAS;
2015
+ exports.applyNodeHardDelete = applyNodeHardDelete;
2016
+ exports.applyNodeInsertSideEffects = applyNodeInsertSideEffects;
2017
+ exports.applyNodeResurrect = applyNodeResurrect;
2018
+ exports.applyNodeSoftDelete = applyNodeSoftDelete;
2019
+ exports.applyNodeUpdate = applyNodeUpdate;
2020
+ exports.asCompiledRowsSql = asCompiledRowsSql;
2021
+ exports.asCompiledSelectSql = asCompiledSelectSql;
2022
+ exports.asCompiledStatementSql = asCompiledStatementSql;
2023
+ exports.asRecordedInstant = asRecordedInstant;
2024
+ exports.assertRecordedCaptureTransactionIsolation = assertRecordedCaptureTransactionIsolation;
2025
+ exports.assertValidRecordedInstant = assertValidRecordedInstant;
2026
+ exports.checkCardinality = checkCardinality;
2027
+ exports.checkDisjointness = checkDisjointness;
2028
+ exports.checkUniqueEdge = checkUniqueEdge;
2029
+ exports.checkUniquenessConstraints = checkUniquenessConstraints;
2030
+ exports.checkWherePredicate = checkWherePredicate;
2031
+ exports.closeRecordedHardDeletedKind = closeRecordedHardDeletedKind;
2032
+ exports.computeFulltextContent = computeFulltextContent;
2033
+ exports.computeUniqueKey = computeUniqueKey;
2034
+ exports.coordinateContext = coordinateContext;
2035
+ exports.createHistoryUnsafeSqlRef = createHistoryUnsafeSqlRef;
2036
+ exports.createNodeWriteContext = createNodeWriteContext;
2037
+ exports.createRecordedBackend = createRecordedBackend;
2038
+ exports.createRecordedReadBinding = createRecordedReadBinding;
2039
+ exports.createRecordedTransactionScope = createRecordedTransactionScope;
2040
+ exports.createSqlSchema = createSqlSchema;
2041
+ exports.createUniquenessContext = createUniquenessContext;
2042
+ exports.describeCoordinate = describeCoordinate;
2043
+ exports.edgeInsertDispatch = edgeInsertDispatch;
2044
+ exports.generateId = generateId;
2045
+ exports.getEdgeRowsByIds = getEdgeRowsByIds;
2046
+ exports.getEmbeddingFields = getEmbeddingFields;
2047
+ exports.getKindsForUniquenessCheck = getKindsForUniquenessCheck;
2048
+ exports.getNodeRowsByIds = getNodeRowsByIds;
2049
+ exports.getSearchableFields = getSearchableFields;
2050
+ exports.lockRecordedGraphWrite = lockRecordedGraphWrite;
2051
+ exports.nodeInsertDispatch = nodeInsertDispatch;
2052
+ exports.readRecordedClock = readRecordedClock;
2053
+ exports.recordedBindParamBudget = recordedBindParamBudget;
2054
+ exports.recordedCaptureRequiresCallbackTransactionError = recordedCaptureRequiresCallbackTransactionError;
2055
+ exports.recordedReadSchemaFor = recordedReadSchemaFor;
2056
+ exports.recordedReadSqlSchema = recordedReadSqlSchema;
2057
+ exports.recordedRelation = recordedRelation;
2058
+ exports.requireExternalRecordedReadSource = requireExternalRecordedReadSource;
2059
+ exports.requireRecordedReadBinding = requireRecordedReadBinding;
2060
+ exports.requireSqlSchema = requireSqlSchema;
2061
+ exports.resolveReadCoordinate = resolveReadCoordinate;
2062
+ exports.runInsertBatch = runInsertBatch;
2063
+ exports.runInsertBatchReturning = runInsertBatchReturning;
2064
+ exports.runInsertNoReturn = runInsertNoReturn;
2065
+ exports.uncapturedGraphWriteLock = uncapturedGraphWriteLock;
2066
+ exports.validateEdgeEndpoints = validateEdgeEndpoints;
2067
+ exports.vectorSlotKey = vectorSlotKey;
2068
+ exports.withRecordedCoordinate = withRecordedCoordinate;
2069
+ //# sourceMappingURL=chunk-5IQIX7LU.cjs.map
2070
+ //# sourceMappingURL=chunk-5IQIX7LU.cjs.map