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