@nicia-ai/typegraph 0.33.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 (244) hide show
  1. package/README.md +20 -0
  2. package/dist/backend/postgres/index.cjs +26 -22
  3. package/dist/backend/postgres/index.d.cts +5 -5
  4. package/dist/backend/postgres/index.d.ts +5 -5
  5. package/dist/backend/postgres/index.js +13 -9
  6. package/dist/backend/postgres/pglite.cjs +17 -13
  7. package/dist/backend/postgres/pglite.cjs.map +1 -1
  8. package/dist/backend/postgres/pglite.d.cts +2 -2
  9. package/dist/backend/postgres/pglite.d.ts +2 -2
  10. package/dist/backend/postgres/pglite.js +13 -9
  11. package/dist/backend/postgres/pglite.js.map +1 -1
  12. package/dist/backend/sqlite/index.cjs +24 -20
  13. package/dist/backend/sqlite/index.d.cts +6 -6
  14. package/dist/backend/sqlite/index.d.ts +6 -6
  15. package/dist/backend/sqlite/index.js +12 -8
  16. package/dist/backend/sqlite/libsql.cjs +18 -14
  17. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  18. package/dist/backend/sqlite/libsql.d.cts +11 -4
  19. package/dist/backend/sqlite/libsql.d.ts +11 -4
  20. package/dist/backend/sqlite/libsql.js +14 -10
  21. package/dist/backend/sqlite/libsql.js.map +1 -1
  22. package/dist/backend/sqlite/local.cjs +18 -14
  23. package/dist/backend/sqlite/local.cjs.map +1 -1
  24. package/dist/backend/sqlite/local.d.cts +2 -2
  25. package/dist/backend/sqlite/local.d.ts +2 -2
  26. package/dist/backend/sqlite/local.js +13 -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-GYVBEZAO.js → chunk-2MRAX3UE.js} +3 -18
  33. package/dist/chunk-2MRAX3UE.js.map +1 -0
  34. package/dist/{chunk-D3EWZ67S.cjs → chunk-3BRVBQQD.cjs} +999 -2675
  35. package/dist/chunk-3BRVBQQD.cjs.map +1 -0
  36. package/dist/{chunk-FDN43KXV.cjs → chunk-3Z6TW3CT.cjs} +20 -19
  37. package/dist/chunk-3Z6TW3CT.cjs.map +1 -0
  38. package/dist/{chunk-6NRFUHMS.js → chunk-4DIBPQNJ.js} +5 -4
  39. package/dist/chunk-4DIBPQNJ.js.map +1 -0
  40. package/dist/chunk-4S2FXGBJ.js +9 -0
  41. package/dist/chunk-4S2FXGBJ.js.map +1 -0
  42. package/dist/chunk-5IQIX7LU.cjs +2070 -0
  43. package/dist/chunk-5IQIX7LU.cjs.map +1 -0
  44. package/dist/{chunk-CWFPJ3RC.js → chunk-6GNSY7AV.js} +3 -3
  45. package/dist/{chunk-CWFPJ3RC.js.map → chunk-6GNSY7AV.js.map} +1 -1
  46. package/dist/{chunk-NG5N7R45.cjs → chunk-6HVOHZHS.cjs} +184 -117
  47. package/dist/chunk-6HVOHZHS.cjs.map +1 -0
  48. package/dist/chunk-6SCVW4AS.js +20 -0
  49. package/dist/chunk-6SCVW4AS.js.map +1 -0
  50. package/dist/chunk-A7SZZFAG.js +2010 -0
  51. package/dist/chunk-A7SZZFAG.js.map +1 -0
  52. package/dist/chunk-ACSVZPK7.cjs +21 -0
  53. package/dist/chunk-ACSVZPK7.cjs.map +1 -0
  54. package/dist/{chunk-IZ4PCL47.js → chunk-BVTWD66D.js} +4 -66
  55. package/dist/chunk-BVTWD66D.js.map +1 -0
  56. package/dist/{chunk-QBYTJSAY.js → chunk-CHXTTSC6.js} +5 -39
  57. package/dist/chunk-CHXTTSC6.js.map +1 -0
  58. package/dist/{chunk-DJYRRDHA.js → chunk-CYX2JTDG.js} +3 -3
  59. package/dist/{chunk-DJYRRDHA.js.map → chunk-CYX2JTDG.js.map} +1 -1
  60. package/dist/{chunk-PRMKPFN5.js → chunk-DEQFL35G.js} +4 -3
  61. package/dist/chunk-DEQFL35G.js.map +1 -0
  62. package/dist/chunk-DI74SMXS.cjs +29 -0
  63. package/dist/chunk-DI74SMXS.cjs.map +1 -0
  64. package/dist/{chunk-WWVV44DY.cjs → chunk-G6SOJEDI.cjs} +11 -11
  65. package/dist/{chunk-WWVV44DY.cjs.map → chunk-G6SOJEDI.cjs.map} +1 -1
  66. package/dist/{chunk-LM2IC4ZJ.cjs → chunk-GQANNXXT.cjs} +15 -14
  67. package/dist/chunk-GQANNXXT.cjs.map +1 -0
  68. package/dist/chunk-GZCNZ7QW.js +24 -0
  69. package/dist/chunk-GZCNZ7QW.js.map +1 -0
  70. package/dist/{chunk-KTIEB7VH.cjs → chunk-HK5SATYM.cjs} +35 -58
  71. package/dist/chunk-HK5SATYM.cjs.map +1 -0
  72. package/dist/chunk-HMFK4BXR.cjs +12 -0
  73. package/dist/{chunk-6ZR4QC3O.cjs.map → chunk-HMFK4BXR.cjs.map} +1 -1
  74. package/dist/chunk-ITE4IXAK.js +25 -0
  75. package/dist/chunk-ITE4IXAK.js.map +1 -0
  76. package/dist/chunk-JJRCLAUN.cjs +155 -0
  77. package/dist/chunk-JJRCLAUN.cjs.map +1 -0
  78. package/dist/{chunk-ZFWNO3GE.cjs → chunk-JQGIPGVL.cjs} +66 -2
  79. package/dist/chunk-JQGIPGVL.cjs.map +1 -0
  80. package/dist/{chunk-XVUJY72M.js → chunk-K2TGS3EN.js} +105 -38
  81. package/dist/chunk-K2TGS3EN.js.map +1 -0
  82. package/dist/chunk-K34OPSJK.js +29 -0
  83. package/dist/chunk-K34OPSJK.js.map +1 -0
  84. package/dist/{chunk-YW7GHMF4.cjs → chunk-KGC4LY5T.cjs} +18 -17
  85. package/dist/chunk-KGC4LY5T.cjs.map +1 -0
  86. package/dist/{chunk-SST7XDY6.cjs → chunk-KNHYNQQ3.cjs} +111 -72
  87. package/dist/chunk-KNHYNQQ3.cjs.map +1 -0
  88. package/dist/{chunk-C4C4Q7A6.js → chunk-KUTNI6SI.js} +6 -21
  89. package/dist/chunk-KUTNI6SI.js.map +1 -0
  90. package/dist/{chunk-OS6KS3HV.js → chunk-LANHCOXB.js} +8 -7
  91. package/dist/chunk-LANHCOXB.js.map +1 -0
  92. package/dist/chunk-N6WTUSBV.cjs +23 -0
  93. package/dist/chunk-N6WTUSBV.cjs.map +1 -0
  94. package/dist/{chunk-73KASJGO.cjs → chunk-NAUA4PW5.cjs} +4 -28
  95. package/dist/chunk-NAUA4PW5.cjs.map +1 -0
  96. package/dist/chunk-QV245VMN.js +145 -0
  97. package/dist/chunk-QV245VMN.js.map +1 -0
  98. package/dist/{chunk-CEF2QOTO.js → chunk-RBV7YCQD.js} +4 -3
  99. package/dist/chunk-RBV7YCQD.js.map +1 -0
  100. package/dist/{chunk-OIE2UPVG.cjs → chunk-RHZWOJVA.cjs} +2 -19
  101. package/dist/chunk-RHZWOJVA.cjs.map +1 -0
  102. package/dist/{chunk-3IR2GEMJ.cjs → chunk-RRKQAKD6.cjs} +10 -9
  103. package/dist/chunk-RRKQAKD6.cjs.map +1 -0
  104. package/dist/{chunk-UPDMJEW6.js → chunk-RY2VIWAM.js} +11 -8
  105. package/dist/chunk-RY2VIWAM.js.map +1 -0
  106. package/dist/{chunk-PIHXFF73.js → chunk-SHLY4MCM.js} +3 -3
  107. package/dist/{chunk-PIHXFF73.js.map → chunk-SHLY4MCM.js.map} +1 -1
  108. package/dist/{chunk-SPT5JMME.js → chunk-T2DWPQNE.js} +103 -64
  109. package/dist/chunk-T2DWPQNE.js.map +1 -0
  110. package/dist/{chunk-WYTUF3QO.js → chunk-T46GR2VY.js} +3 -3
  111. package/dist/{chunk-WYTUF3QO.js.map → chunk-T46GR2VY.js.map} +1 -1
  112. package/dist/{chunk-MBLXCV2Y.cjs → chunk-T6SPUYLX.cjs} +5 -43
  113. package/dist/chunk-T6SPUYLX.cjs.map +1 -0
  114. package/dist/{chunk-3QRBXYT5.cjs → chunk-TGJE22RM.cjs} +6 -6
  115. package/dist/{chunk-3QRBXYT5.cjs.map → chunk-TGJE22RM.cjs.map} +1 -1
  116. package/dist/{chunk-BF3ZDEUE.cjs → chunk-TOTPVGOG.cjs} +70 -69
  117. package/dist/chunk-TOTPVGOG.cjs.map +1 -0
  118. package/dist/{chunk-KY5SDVA7.cjs → chunk-UJLOZYKT.cjs} +90 -87
  119. package/dist/chunk-UJLOZYKT.cjs.map +1 -0
  120. package/dist/{chunk-I4W7MKVG.cjs → chunk-UNNPKQUG.cjs} +19 -155
  121. package/dist/chunk-UNNPKQUG.cjs.map +1 -0
  122. package/dist/chunk-UR7W5YQK.js +18 -0
  123. package/dist/chunk-UR7W5YQK.js.map +1 -0
  124. package/dist/{chunk-PYD3UCDU.js → chunk-V3QNTB7Z.js} +19 -148
  125. package/dist/chunk-V3QNTB7Z.js.map +1 -0
  126. package/dist/{chunk-XKNAK27R.js → chunk-VCGO4V26.js} +4 -3
  127. package/dist/chunk-VCGO4V26.js.map +1 -0
  128. package/dist/{chunk-EF3Z645U.cjs → chunk-WL2SG7ZV.cjs} +6 -72
  129. package/dist/chunk-WL2SG7ZV.cjs.map +1 -0
  130. package/dist/{chunk-WLP6TKFB.js → chunk-WLRIWYHQ.js} +640 -2307
  131. package/dist/chunk-WLRIWYHQ.js.map +1 -0
  132. package/dist/{chunk-4RBAJVEC.cjs → chunk-WVC2Q2FD.cjs} +5 -5
  133. package/dist/{chunk-4RBAJVEC.cjs.map → chunk-WVC2Q2FD.cjs.map} +1 -1
  134. package/dist/chunk-XXVEULWX.js +39 -0
  135. package/dist/chunk-XXVEULWX.js.map +1 -0
  136. package/dist/chunk-YAZE7QZR.cjs +32 -0
  137. package/dist/chunk-YAZE7QZR.cjs.map +1 -0
  138. package/dist/chunk-YC6PWTHY.cjs +44 -0
  139. package/dist/chunk-YC6PWTHY.cjs.map +1 -0
  140. package/dist/chunk-Z5HBYM7U.cjs +11 -0
  141. package/dist/chunk-Z5HBYM7U.cjs.map +1 -0
  142. package/dist/{chunk-454I6GDF.js → chunk-Z5XBMDXU.js} +63 -3
  143. package/dist/chunk-Z5XBMDXU.js.map +1 -0
  144. package/dist/{chunk-3642VBVC.cjs → chunk-ZP5WHI4C.cjs} +106 -80
  145. package/dist/chunk-ZP5WHI4C.cjs.map +1 -0
  146. package/dist/{chunk-YCV72E6L.js → chunk-ZURTTSCM.js} +4 -25
  147. package/dist/chunk-ZURTTSCM.js.map +1 -0
  148. package/dist/{chunk-JHOBXD7O.js → chunk-ZV5N4DBG.js} +46 -20
  149. package/dist/chunk-ZV5N4DBG.js.map +1 -0
  150. package/dist/chunk-ZY4GXIVN.cjs +32 -0
  151. package/dist/chunk-ZY4GXIVN.cjs.map +1 -0
  152. package/dist/{ddl-CVnHJcar.d.ts → ddl-BrmPg61z.d.ts} +3 -3
  153. package/dist/{ddl-Dxt_fBHr.d.cts → ddl-j1-sH6lE.d.cts} +3 -3
  154. package/dist/graph-extension/index.cjs +18 -17
  155. package/dist/graph-extension/index.js +3 -2
  156. package/dist/graph-merge/index.cjs +294 -146
  157. package/dist/graph-merge/index.cjs.map +1 -1
  158. package/dist/graph-merge/index.d.cts +3 -3
  159. package/dist/graph-merge/index.d.ts +3 -3
  160. package/dist/graph-merge/index.js +172 -24
  161. package/dist/graph-merge/index.js.map +1 -1
  162. package/dist/index.cjs +181 -172
  163. package/dist/index.cjs.map +1 -1
  164. package/dist/index.d.cts +7 -7
  165. package/dist/index.d.ts +7 -7
  166. package/dist/index.js +30 -22
  167. package/dist/index.js.map +1 -1
  168. package/dist/indexes/index.cjs +27 -25
  169. package/dist/indexes/index.d.cts +4 -4
  170. package/dist/indexes/index.d.ts +4 -4
  171. package/dist/indexes/index.js +9 -7
  172. package/dist/interchange/index.cjs +25 -16
  173. package/dist/interchange/index.d.cts +3 -3
  174. package/dist/interchange/index.d.ts +3 -3
  175. package/dist/interchange/index.js +12 -3
  176. package/dist/{manager-C0_r0ALf.d.ts → manager-BZUeN_BU.d.ts} +1 -1
  177. package/dist/{manager-BYl_zyZR.d.cts → manager-ms9cKdc6.d.cts} +1 -1
  178. package/dist/{postgres-MzBPkYzq.d.ts → postgres-BhpxGMC5.d.cts} +1 -1
  179. package/dist/{postgres-_9psmVGm.d.cts → postgres-CWHLwNl1.d.ts} +1 -1
  180. package/dist/profiler/index.cjs +3 -3
  181. package/dist/profiler/index.d.cts +5 -5
  182. package/dist/profiler/index.d.ts +5 -5
  183. package/dist/profiler/index.js +2 -2
  184. package/dist/provenance/index.cjs +591 -0
  185. package/dist/provenance/index.cjs.map +1 -0
  186. package/dist/provenance/index.d.cts +73 -0
  187. package/dist/provenance/index.d.ts +73 -0
  188. package/dist/provenance/index.js +589 -0
  189. package/dist/provenance/index.js.map +1 -0
  190. package/dist/schema/index.cjs +36 -32
  191. package/dist/schema/index.cjs.map +1 -1
  192. package/dist/schema/index.d.cts +4 -4
  193. package/dist/schema/index.d.ts +4 -4
  194. package/dist/schema/index.js +13 -9
  195. package/dist/schema/index.js.map +1 -1
  196. package/dist/{sqlite-gm44dShb.d.ts → sqlite-CGu5SLsw.d.ts} +1 -1
  197. package/dist/{sqlite-BfksSb45.d.cts → sqlite-XrDxNaa7.d.cts} +1 -1
  198. package/dist/{store-view-FfE5_7eo.d.ts → store-view-BlgnhEYf.d.ts} +33 -5
  199. package/dist/{store-view-9jQ2rPum.d.cts → store-view-D09po4H6.d.cts} +33 -5
  200. package/dist/{types-CdWxK-nD.d.ts → types-B1TbZJYS.d.ts} +1 -1
  201. package/dist/{types-DGylBhWo.d.ts → types-D1Sqeyxy.d.ts} +7 -3
  202. package/dist/{types-B6mhrcLv.d.cts → types-DiE1AO7p.d.cts} +1 -1
  203. package/dist/{types-C_UnQOQp.d.cts → types-DkNnF-7K.d.cts} +7 -3
  204. package/dist/{where-Bpp2ul_z.d.cts → where-DKjuofPr.d.cts} +1 -1
  205. package/dist/{where-BsEXraKW.d.ts → where-DrUIIWHb.d.ts} +1 -1
  206. package/package.json +8 -2
  207. package/dist/chunk-2YMGNYXY.js +0 -40
  208. package/dist/chunk-2YMGNYXY.js.map +0 -1
  209. package/dist/chunk-3642VBVC.cjs.map +0 -1
  210. package/dist/chunk-3IR2GEMJ.cjs.map +0 -1
  211. package/dist/chunk-454I6GDF.js.map +0 -1
  212. package/dist/chunk-6NRFUHMS.js.map +0 -1
  213. package/dist/chunk-6ZR4QC3O.cjs +0 -12
  214. package/dist/chunk-73KASJGO.cjs.map +0 -1
  215. package/dist/chunk-BF3ZDEUE.cjs.map +0 -1
  216. package/dist/chunk-C4C4Q7A6.js.map +0 -1
  217. package/dist/chunk-CEF2QOTO.js.map +0 -1
  218. package/dist/chunk-CFNT3ITG.cjs.map +0 -1
  219. package/dist/chunk-D3EWZ67S.cjs.map +0 -1
  220. package/dist/chunk-EF3Z645U.cjs.map +0 -1
  221. package/dist/chunk-FDN43KXV.cjs.map +0 -1
  222. package/dist/chunk-GYVBEZAO.js.map +0 -1
  223. package/dist/chunk-I4W7MKVG.cjs.map +0 -1
  224. package/dist/chunk-IZ4PCL47.js.map +0 -1
  225. package/dist/chunk-JHOBXD7O.js.map +0 -1
  226. package/dist/chunk-KTIEB7VH.cjs.map +0 -1
  227. package/dist/chunk-KY5SDVA7.cjs.map +0 -1
  228. package/dist/chunk-LM2IC4ZJ.cjs.map +0 -1
  229. package/dist/chunk-MBLXCV2Y.cjs.map +0 -1
  230. package/dist/chunk-NG5N7R45.cjs.map +0 -1
  231. package/dist/chunk-OIE2UPVG.cjs.map +0 -1
  232. package/dist/chunk-OS6KS3HV.js.map +0 -1
  233. package/dist/chunk-PRMKPFN5.js.map +0 -1
  234. package/dist/chunk-PYD3UCDU.js.map +0 -1
  235. package/dist/chunk-QBYTJSAY.js.map +0 -1
  236. package/dist/chunk-SPT5JMME.js.map +0 -1
  237. package/dist/chunk-SST7XDY6.cjs.map +0 -1
  238. package/dist/chunk-UPDMJEW6.js.map +0 -1
  239. package/dist/chunk-WLP6TKFB.js.map +0 -1
  240. package/dist/chunk-XKNAK27R.js.map +0 -1
  241. package/dist/chunk-XVUJY72M.js.map +0 -1
  242. package/dist/chunk-YCV72E6L.js.map +0 -1
  243. package/dist/chunk-YW7GHMF4.cjs.map +0 -1
  244. package/dist/chunk-ZFWNO3GE.cjs.map +0 -1
@@ -1,7 +1,7 @@
1
- import { K as KindRegistry, G as GraphDef, w as EdgeKinds, t as NodeKinds, v as AllNodeTypes, c as SchemaManagerOptions, d as SchemaValidationResult } from './manager-BYl_zyZR.cjs';
1
+ import { K as KindRegistry, G as GraphDef, w as EdgeKinds, t as NodeKinds, v as AllNodeTypes, c as SchemaManagerOptions, d as SchemaValidationResult } from './manager-ms9cKdc6.cjs';
2
2
  import { T as TemporalMode, A as AnyEdgeType, N as NodeType, g as EdgeType, E as EdgeRegistration, e as EdgeId, d as NodeId, b as NodeRegistration, K as KindEntity, m as Cardinality, q as EndpointExistence, f as KindAnnotations, s as UniquenessScope, n as Collation, G as GraphExtension } from './extension-types-YGFJPrzK.cjs';
3
3
  import { z } from 'zod';
4
- import { b7 as ValueType, b8 as PredicateExpression, b9 as VectorMetricType, ae as FulltextQueryMode, Q as QueryAst, J as JsonPointer, P as FieldRef, ax as ParameterRef, G as GraphBackend, aP as TransactionBackend, ao as JsonPointerInput, aQ as TraversalExpansion, p as SqlDialect, aL as SqlSchema, ba as Traversal, bb as NodePredicate, bc as ProjectedField, aw as OrderSpec, bd as GroupBySpec, ak as HybridFusionOptions, be as RecursiveCyclePolicy, W as TraversalDirection$1, bf as EdgeRow, bg as NodeRow, aa as ExternalRecordedReadSource, X as AdoptedTransaction, L as AggregateExpr, a3 as CompiledSelectSql, F as FulltextStrategy, V as VectorStrategy, bh as VectorSlotMap, bi as RecordedReadBinding, bj as SelectiveField, bk as ComposableQuery, bl as SetOperationType, bm as SetOperation, aJ as SortDirection, bn as VectorMetric, m as JsonSchema, bo as TransactionOptions } from './types-C_UnQOQp.cjs';
4
+ import { b7 as ValueType, b8 as PredicateExpression, b9 as VectorMetricType, ae as FulltextQueryMode, Q as QueryAst, J as JsonPointer, P as FieldRef, ax as ParameterRef, G as GraphBackend, aP as TransactionBackend, ao as JsonPointerInput, aQ as TraversalExpansion, p as SqlDialect, aL as SqlSchema, ba as Traversal, bb as NodePredicate, bc as ProjectedField, aw as OrderSpec, bd as GroupBySpec, ak as HybridFusionOptions, be as RecursiveCyclePolicy, W as TraversalDirection$1, bf as EdgeRow, bg as NodeRow, aa as ExternalRecordedReadSource, X as AdoptedTransaction, L as AggregateExpr, a3 as CompiledSelectSql, F as FulltextStrategy, V as VectorStrategy, bh as VectorSlotMap, bi as RecordedReadBinding, bj as SelectiveField, bk as ComposableQuery, bl as SetOperationType, bm as SetOperation, aJ as SortDirection, bn as VectorMetric, m as JsonSchema, bo as TransactionOptions } from './types-DkNnF-7K.cjs';
5
5
  import { b as MaterializeIndexesOptions, M as MaterializeIndexesResult } from './materialize-indexes-D20xNluI.cjs';
6
6
 
7
7
  /**
@@ -1173,11 +1173,24 @@ type StoreHooks = Readonly<{
1173
1173
  }>) => void;
1174
1174
  /** Called before a CRUD operation starts */
1175
1175
  onOperationStart?: (ctx: OperationHookContext) => void;
1176
- /** Called after a CRUD operation completes */
1176
+ /**
1177
+ * Called after a CRUD operation completes AND is durably committed. For a
1178
+ * top-level operation that is when its own transaction commits; for an
1179
+ * operation inside `store.transaction`, emission is deferred until the
1180
+ * enclosing transaction commits — if that commit fails, the operation is
1181
+ * reported through `onError` instead. (Inside an adopted transaction —
1182
+ * `withTransaction` / `withRecordedTransaction` — the commit belongs to
1183
+ * the caller and cannot be observed, so this fires when the operation
1184
+ * completes within the still-open transaction.)
1185
+ */
1177
1186
  onOperationEnd?: (ctx: OperationHookContext, result: Readonly<{
1178
1187
  durationMs: number;
1179
1188
  }>) => void;
1180
- /** Called when an error occurs */
1189
+ /**
1190
+ * Called when an operation fails — including an operation that completed
1191
+ * inside a `store.transaction` whose commit then failed and rolled it
1192
+ * back.
1193
+ */
1181
1194
  onError?: (ctx: HookContext, error: Error) => void;
1182
1195
  }>;
1183
1196
  type BaseStoreOptions = Readonly<{
@@ -1915,6 +1928,21 @@ type TransactionContext<G extends GraphDef> = Readonly<{
1915
1928
  * is the store's plain backend — reads work, but there is no snapshot.
1916
1929
  */
1917
1930
  backend: TransactionBackend;
1931
+ /**
1932
+ * Runtime string-keyed node collection access, mirroring
1933
+ * `Store.getNodeCollection` — for callers (e.g. provenance) that resolve a
1934
+ * kind dynamically rather than through the static `nodes.<Kind>` property.
1935
+ * Returns `undefined` when `kind` is not registered in this graph.
1936
+ */
1937
+ getNodeCollection(kind: string): DynamicNodeCollection | undefined;
1938
+ /**
1939
+ * @internal Runs a graph-owned node mutation through this transaction's
1940
+ * operation-hook lifecycle when the mutation cannot use a public collection
1941
+ * verb directly (provenance fact close/reopen). Routed through the
1942
+ * transaction's hook runner, so a successful operation's `onOperationEnd`
1943
+ * is deferred until the transaction commits.
1944
+ */
1945
+ runNodeOperationHooks<T>(operation: "create" | "update" | "delete", kind: string, id: string, fn: () => Promise<T>): Promise<T>;
1918
1946
  }>;
1919
1947
  /**
1920
1948
  * Replace branded `NodeId` / `EdgeId` with plain `string` in each
@@ -4588,4 +4616,4 @@ declare class RecordedStoreView<G extends GraphDef> extends CoordinatePinnedView
4588
4616
  get edges(): RecordedStoreViewEdgeCollections<G>;
4589
4617
  }
4590
4618
 
4591
- export { type GraphAlgorithms as $, type AliasMap as A, type BaseTraversalOptions as B, type ConstraintNames as C, DEFAULT_SEARCHABLE_LANGUAGE as D, type EmbeddingMetric as E, type EdgeFindByEndpointsOptions as F, type EdgeGetOrCreateByEndpointsOptions as G, type EdgeGetOrCreateByEndpointsResult as H, type EdgeIntrospection as I, type EdgeTemporalReads as J, type EdgeWrites as K, type EmbeddingSchema as L, type EmbeddingValue as M, type Node as N, type EmptyAliasMap as O, type EmptyEdgeAliasMap as P, type QueryCoordinateState as Q, type RecursiveAliasMap as R, Store as S, TraversalBuilder as T, type UniqueIntrospection as U, ExecutableAggregateQuery as V, ExecutableQuery as W, type FieldAccessor as X, type FulltextSearchHit as Y, type FulltextSearchOptions as Z, type GetOrCreateAction as _, type EmbeddingIndexType as a, type SelectableEdge as a$, type GraphEdgeCollections as a0, type GraphNodeCollections as a1, type HistorySafeBackend as a2, type HistorySafeTransactionBackend as a3, type HistoryStore as a4, type HistoryStoreOptions as a5, type HistoryTransactionContext as a6, type HookContext as a7, type HybridFulltextOptions as a8, type HybridSearchHit as a9, type PathNode as aA, type Predicate as aB, PreparedQuery as aC, type PropsAccessor as aD, type QueryHookContext as aE, type QueryOptions as aF, type ReachableNode as aG, type ReachableOptions as aH, type RebuildFulltextOptions as aI, type RebuildFulltextResult as aJ, type ReclaimedVectorFieldEntry as aK, type RecordedInstant as aL, type RecordedReadStore as aM, RecordedStoreView as aN, type RecordedStoreViewEdgeCollection as aO, type RecordedStoreViewEdgeCollections as aP, type RecordedStoreViewNodeCollection as aQ, type RecordedStoreViewNodeCollections as aR, type RecursiveTraversalOptions as aS, type ReembedFunction as aT, type ReembedVectorFieldOptions as aU, type ReembedVectorFieldResult as aV, type SchemaIntrospection as aW, type SearchableMetadata as aX, type SearchableOptions as aY, type SearchableSchema as aZ, type SelectContext as a_, type HybridSearchOptions as aa, type HybridVectorOptions as ab, type IfExistsMode as ac, type InitialQueryBuilder as ad, type KindIntrospection as ae, type LiveStoreOptions as af, type MaterializeRemovalsEntry as ag, type MaterializeRemovalsOptions as ah, type MaterializeRemovalsResult as ai, type NeighborsOptions as aj, type NoRecordedCoordinate as ak, type NodeAccessor as al, type NodeAlias as am, type NodeBulkFindByIndexOptions as an, type NodeCollection as ao, type NodeCurrentReads as ap, type NodeGetOrCreateByConstraintOptions as aq, type NodeGetOrCreateByConstraintResult as ar, type NodeIdentifier as as, type NodeRef as at, type NodeTemporalReads as au, type NodeWrites as av, type OntologyIntrospection as aw, type OperationHookContext as ax, type PaginateOptions as ay, type PaginatedResult as az, type EdgeAliasMap as b, type SelectableNode as b0, type ShortestPathOptions as b1, type ShortestPathResult as b2, type StoreHooks as b3, type StoreOptions as b4, type StoreProjection as b5, type StoreRef as b6, StoreSearch as b7, StoreView as b8, type StoreViewCanReachOptions as b9, type VectorSearchHit as bA, type VectorSearchOptions as bB, asRecordedInstant as bC, createQueryBuilder as bD, createStore as bE, createStoreWithSchema as bF, createVerifiedStore as bG, defineSubgraphProject as bH, embedding as bI, exists as bJ, fieldRef as bK, getEmbeddingDimensions as bL, getSearchableMetadata as bM, inSubquery as bN, isEmbeddingSchema as bO, isParameterRef as bP, isSearchableSchema as bQ, notExists as bR, notInSubquery as bS, param as bT, searchable as bU, type StoreViewCoordinate as ba, type StoreViewDegreeOptions as bb, type StoreViewEdgeCollection as bc, type StoreViewEdgeCollections as bd, type StoreViewNeighborsOptions as be, type StoreViewNodeCollection as bf, type StoreViewNodeCollections as bg, type StoreViewReachableOptions as bh, type StoreViewShortestPathOptions as bi, type StoreViewSubgraphOptions as bj, type StreamOptions as bk, type SubgraphEdgeResult as bl, type SubgraphNodeResult as bm, type SubgraphOptions as bn, type SubgraphResult as bo, type SubsetEdge as bp, type SubsetNode as bq, type TemporalAlgorithmOptions as br, type TransactionContext as bs, type TraversalDirection as bt, type TypedEdgeCollection as bu, type TypedRecordedStoreViewEdgeCollection as bv, type TypedStoreViewEdgeCollection as bw, UnionableQuery as bx, type UpdateEdgeInput as by, type UpdateNodeInput as bz, QueryBuilder as c, type EmptyRecursiveAliasMap as d, type AggregateResult as e, type AlgorithmCyclePolicy as f, type AnyEdge as g, type AnyNode as h, type BatchResults as i, type BatchableQuery as j, type CreateEdgeInput as k, type CreateNodeInput as l, type DegreeOptions as m, type DynamicEdgeAccessor as n, type DynamicEdgeCollection as o, type DynamicEdgeType as p, type DynamicFieldBuilder as q, type DynamicNodeAccessor as r, type DynamicNodeCollection as s, type DynamicNodeType as t, type DynamicSelectableEdge as u, type DynamicSelectableNode as v, type Edge as w, type EdgeAccessor as x, type EdgeBatchReads as y, type EdgeCollection as z };
4619
+ export { type GetOrCreateAction as $, type AliasMap as A, type BaseTraversalOptions as B, type ConstraintNames as C, DEFAULT_SEARCHABLE_LANGUAGE as D, type EmbeddingMetric as E, type EdgeFindByEndpointsOptions as F, type EdgeGetOrCreateByEndpointsOptions as G, type HistoryStore as H, type EdgeGetOrCreateByEndpointsResult as I, type EdgeIntrospection as J, type EdgeTemporalReads as K, type EdgeWrites as L, type EmbeddingSchema as M, type Node as N, type EmbeddingValue as O, type EmptyAliasMap as P, type QueryCoordinateState as Q, type RecursiveAliasMap as R, Store as S, TraversalBuilder as T, type UniqueIntrospection as U, type EmptyEdgeAliasMap as V, ExecutableAggregateQuery as W, ExecutableQuery as X, type FieldAccessor as Y, type FulltextSearchHit as Z, type FulltextSearchOptions as _, type EmbeddingIndexType as a, type SelectableEdge as a$, type GraphAlgorithms as a0, type GraphEdgeCollections as a1, type GraphNodeCollections as a2, type HistorySafeBackend as a3, type HistorySafeTransactionBackend as a4, type HistoryStoreOptions as a5, type HistoryTransactionContext as a6, type HookContext as a7, type HybridFulltextOptions as a8, type HybridSearchHit as a9, type PathNode as aA, type Predicate as aB, PreparedQuery as aC, type PropsAccessor as aD, type QueryHookContext as aE, type QueryOptions as aF, type ReachableNode as aG, type ReachableOptions as aH, type RebuildFulltextOptions as aI, type RebuildFulltextResult as aJ, type ReclaimedVectorFieldEntry as aK, type RecordedInstant as aL, type RecordedReadStore as aM, RecordedStoreView as aN, type RecordedStoreViewEdgeCollection as aO, type RecordedStoreViewEdgeCollections as aP, type RecordedStoreViewNodeCollection as aQ, type RecordedStoreViewNodeCollections as aR, type RecursiveTraversalOptions as aS, type ReembedFunction as aT, type ReembedVectorFieldOptions as aU, type ReembedVectorFieldResult as aV, type SchemaIntrospection as aW, type SearchableMetadata as aX, type SearchableOptions as aY, type SearchableSchema as aZ, type SelectContext as a_, type HybridSearchOptions as aa, type HybridVectorOptions as ab, type IfExistsMode as ac, type InitialQueryBuilder as ad, type KindIntrospection as ae, type LiveStoreOptions as af, type MaterializeRemovalsEntry as ag, type MaterializeRemovalsOptions as ah, type MaterializeRemovalsResult as ai, type NeighborsOptions as aj, type NoRecordedCoordinate as ak, type NodeAccessor as al, type NodeAlias as am, type NodeBulkFindByIndexOptions as an, type NodeCollection as ao, type NodeCurrentReads as ap, type NodeGetOrCreateByConstraintOptions as aq, type NodeGetOrCreateByConstraintResult as ar, type NodeIdentifier as as, type NodeRef as at, type NodeTemporalReads as au, type NodeWrites as av, type OntologyIntrospection as aw, type OperationHookContext as ax, type PaginateOptions as ay, type PaginatedResult as az, type EdgeAliasMap as b, type SelectableNode as b0, type ShortestPathOptions as b1, type ShortestPathResult as b2, type StoreHooks as b3, type StoreOptions as b4, type StoreProjection as b5, type StoreRef as b6, StoreSearch as b7, StoreView as b8, type StoreViewCanReachOptions as b9, type VectorSearchHit as bA, type VectorSearchOptions as bB, asRecordedInstant as bC, createQueryBuilder as bD, createStore as bE, createStoreWithSchema as bF, createVerifiedStore as bG, defineSubgraphProject as bH, embedding as bI, exists as bJ, fieldRef as bK, getEmbeddingDimensions as bL, getSearchableMetadata as bM, inSubquery as bN, isEmbeddingSchema as bO, isParameterRef as bP, isSearchableSchema as bQ, notExists as bR, notInSubquery as bS, param as bT, searchable as bU, type StoreViewCoordinate as ba, type StoreViewDegreeOptions as bb, type StoreViewEdgeCollection as bc, type StoreViewEdgeCollections as bd, type StoreViewNeighborsOptions as be, type StoreViewNodeCollection as bf, type StoreViewNodeCollections as bg, type StoreViewReachableOptions as bh, type StoreViewShortestPathOptions as bi, type StoreViewSubgraphOptions as bj, type StreamOptions as bk, type SubgraphEdgeResult as bl, type SubgraphNodeResult as bm, type SubgraphOptions as bn, type SubgraphResult as bo, type SubsetEdge as bp, type SubsetNode as bq, type TemporalAlgorithmOptions as br, type TransactionContext as bs, type TraversalDirection as bt, type TypedEdgeCollection as bu, type TypedRecordedStoreViewEdgeCollection as bv, type TypedStoreViewEdgeCollection as bw, UnionableQuery as bx, type UpdateEdgeInput as by, type UpdateNodeInput as bz, QueryBuilder as c, type EmptyRecursiveAliasMap as d, type AggregateResult as e, type AlgorithmCyclePolicy as f, type AnyEdge as g, type AnyNode as h, type BatchResults as i, type BatchableQuery as j, type CreateEdgeInput as k, type CreateNodeInput as l, type DegreeOptions as m, type DynamicEdgeAccessor as n, type DynamicEdgeCollection as o, type DynamicEdgeType as p, type DynamicFieldBuilder as q, type DynamicNodeAccessor as r, type DynamicNodeCollection as s, type DynamicNodeType as t, type DynamicSelectableEdge as u, type DynamicSelectableNode as v, type Edge as w, type EdgeAccessor as x, type EdgeBatchReads as y, type EdgeCollection as z };
@@ -1,5 +1,5 @@
1
1
  import { K as KindEntity } from './extension-types-YGFJPrzK.js';
2
- import { J as JsonPointer } from './types-DGylBhWo.js';
2
+ import { J as JsonPointer } from './types-D1Sqeyxy.js';
3
3
 
4
4
  /**
5
5
  * QueryProfiler types.
@@ -794,10 +794,14 @@ type AnyPgDatabase = PgDatabase<PgQueryResultHKT, Record<string, unknown>>;
794
794
  /**
795
795
  * Controls how the backend manages SQLite transactions.
796
796
  *
797
- * - `"sql"`: TypeGraph issues BEGIN / COMMIT / ROLLBACK SQL directly.
798
- * Default for sync drivers (better-sqlite3, bun:sqlite).
797
+ * - `"sql"`: TypeGraph issues BEGIN / COMMIT / ROLLBACK SQL directly on
798
+ * the connection. Default for sync drivers (better-sqlite3,
799
+ * bun:sqlite); also selected by `createLibsqlBackend` for
800
+ * local `@libsql/client` connections (`file:` / `:memory:`),
801
+ * whose `client.transaction()` permanently abandons the
802
+ * current connection — fatal for an in-memory database.
799
803
  * - `"drizzle"`: Delegates to Drizzle's `db.transaction()` method.
800
- * Default for async drivers (libsql, sql.js).
804
+ * Default for async drivers (remote libsql/Turso, sql.js).
801
805
  * - `"do-sqlite"`: Delegates to the Cloudflare Durable Objects async
802
806
  * storage transaction runner (`db.$client.transaction`,
803
807
  * i.e. `ctx.storage.transaction(async ...)`). Drizzle's
@@ -1,5 +1,5 @@
1
1
  import { K as KindEntity } from './extension-types-YGFJPrzK.cjs';
2
- import { J as JsonPointer } from './types-C_UnQOQp.cjs';
2
+ import { J as JsonPointer } from './types-DkNnF-7K.cjs';
3
3
 
4
4
  /**
5
5
  * QueryProfiler types.
@@ -794,10 +794,14 @@ type AnyPgDatabase = PgDatabase<PgQueryResultHKT, Record<string, unknown>>;
794
794
  /**
795
795
  * Controls how the backend manages SQLite transactions.
796
796
  *
797
- * - `"sql"`: TypeGraph issues BEGIN / COMMIT / ROLLBACK SQL directly.
798
- * Default for sync drivers (better-sqlite3, bun:sqlite).
797
+ * - `"sql"`: TypeGraph issues BEGIN / COMMIT / ROLLBACK SQL directly on
798
+ * the connection. Default for sync drivers (better-sqlite3,
799
+ * bun:sqlite); also selected by `createLibsqlBackend` for
800
+ * local `@libsql/client` connections (`file:` / `:memory:`),
801
+ * whose `client.transaction()` permanently abandons the
802
+ * current connection — fatal for an in-memory database.
799
803
  * - `"drizzle"`: Delegates to Drizzle's `db.transaction()` method.
800
- * Default for async drivers (libsql, sql.js).
804
+ * Default for async drivers (remote libsql/Turso, sql.js).
801
805
  * - `"do-sqlite"`: Delegates to the Cloudflare Durable Objects async
802
806
  * storage transaction runner (`db.$client.transaction`,
803
807
  * i.e. `ctx.storage.transaction(async ...)`). Drizzle's
@@ -1,5 +1,5 @@
1
1
  import { A as AnyEdgeType, N as NodeType } from './extension-types-YGFJPrzK.cjs';
2
- import { E as EdgeIndexConfig, c as EdgeIndexDeclaration, N as NodeIndexConfig, d as NodeIndexDeclaration, e as IndexWhereExpression } from './types-C_UnQOQp.cjs';
2
+ import { E as EdgeIndexConfig, c as EdgeIndexDeclaration, N as NodeIndexConfig, d as NodeIndexDeclaration, e as IndexWhereExpression } from './types-DkNnF-7K.cjs';
3
3
 
4
4
  declare function defineNodeIndex<N extends NodeType>(node: N, config: NodeIndexConfig<N>): NodeIndexDeclaration;
5
5
  declare function defineEdgeIndex<E extends AnyEdgeType>(edge: E, config: EdgeIndexConfig<E>): EdgeIndexDeclaration;
@@ -1,5 +1,5 @@
1
1
  import { A as AnyEdgeType, N as NodeType } from './extension-types-YGFJPrzK.js';
2
- import { E as EdgeIndexConfig, c as EdgeIndexDeclaration, N as NodeIndexConfig, d as NodeIndexDeclaration, e as IndexWhereExpression } from './types-DGylBhWo.js';
2
+ import { E as EdgeIndexConfig, c as EdgeIndexDeclaration, N as NodeIndexConfig, d as NodeIndexDeclaration, e as IndexWhereExpression } from './types-D1Sqeyxy.js';
3
3
 
4
4
  declare function defineNodeIndex<N extends NodeType>(node: N, config: NodeIndexConfig<N>): NodeIndexDeclaration;
5
5
  declare function defineEdgeIndex<E extends AnyEdgeType>(edge: E, config: EdgeIndexConfig<E>): EdgeIndexDeclaration;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nicia-ai/typegraph",
3
- "version": "0.33.0",
3
+ "version": "0.34.0",
4
4
  "description": "TypeScript-first embedded knowledge graph library with ontological reasoning",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -42,6 +42,11 @@
42
42
  "import": "./dist/graph-merge/index.js",
43
43
  "require": "./dist/graph-merge/index.cjs"
44
44
  },
45
+ "./provenance": {
46
+ "types": "./dist/provenance/index.d.ts",
47
+ "import": "./dist/provenance/index.js",
48
+ "require": "./dist/provenance/index.cjs"
49
+ },
45
50
  "./sqlite": {
46
51
  "types": "./dist/backend/sqlite/index.d.ts",
47
52
  "import": "./dist/backend/sqlite/index.js",
@@ -187,6 +192,7 @@
187
192
  "test:postgres": "./scripts/test-postgres.sh",
188
193
  "test:do": "vitest run --config vitest.workers.config.ts",
189
194
  "test:coverage": "vitest run --coverage",
190
- "test:mutation": "stryker run"
195
+ "test:mutation": "stryker run",
196
+ "test:mutation:critical": "stryker run stryker.critical.config.json"
191
197
  }
192
198
  }
@@ -1,40 +0,0 @@
1
- // src/constants.ts
2
- var MAX_PG_IDENTIFIER_LENGTH = 63;
3
- var TRUNCATED_IDENTIFIER_MAX_LENGTH = 54;
4
- var IDENTIFIER_COMPONENT_MAX_LENGTH = 20;
5
- var FNV1A_OFFSET_BASIS = 2166136261;
6
- var FNV1A_PRIME = 16777619;
7
- var DEFAULT_PAGINATION_LIMIT = 20;
8
- var DEFAULT_STREAM_BATCH_SIZE = 1e3;
9
- var SQLITE_PATH_DELIMITER = "|";
10
- var PG_PATH_ELEMENT_SEPARATOR = ",";
11
- var PG_ARRAY_START = "{";
12
- var PG_ARRAY_END = "}";
13
-
14
- // src/utils/hash.ts
15
- function fnv1aBase36(input) {
16
- let hash = FNV1A_OFFSET_BASIS;
17
- for (const character of input) {
18
- const codePoint = character.codePointAt(0);
19
- if (codePoint === void 0) continue;
20
- hash ^= codePoint;
21
- hash = Math.imul(hash, FNV1A_PRIME);
22
- }
23
- return (hash >>> 0).toString(36);
24
- }
25
- async function sha256Hex(input, byteLength = 8) {
26
- const encoded = new TextEncoder().encode(input);
27
- const digest = await globalThis.crypto.subtle.digest("SHA-256", encoded);
28
- const bytes = new Uint8Array(digest);
29
- let hex = "";
30
- for (let index = 0; index < byteLength; index++) {
31
- const byte = bytes[index];
32
- if (byte === void 0) break;
33
- hex += byte.toString(16).padStart(2, "0");
34
- }
35
- return hex;
36
- }
37
-
38
- export { DEFAULT_PAGINATION_LIMIT, DEFAULT_STREAM_BATCH_SIZE, IDENTIFIER_COMPONENT_MAX_LENGTH, MAX_PG_IDENTIFIER_LENGTH, PG_ARRAY_END, PG_ARRAY_START, PG_PATH_ELEMENT_SEPARATOR, SQLITE_PATH_DELIMITER, TRUNCATED_IDENTIFIER_MAX_LENGTH, fnv1aBase36, sha256Hex };
39
- //# sourceMappingURL=chunk-2YMGNYXY.js.map
40
- //# sourceMappingURL=chunk-2YMGNYXY.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/constants.ts","../src/utils/hash.ts"],"names":[],"mappings":";AAYO,IAAM,wBAAA,GAA2B;AAGjC,IAAM,+BAAA,GAAkC;AAGxC,IAAM,+BAAA,GAAkC;AAOxC,IAAM,kBAAA,GAAqB,UAAA;AAG3B,IAAM,WAAA,GAAc,QAAA;AAOpB,IAAM,w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across the TypeGraph codebase.\n */\n\n// ============================================================\n// PostgreSQL Limits\n// ============================================================\n\n/**\n * PostgreSQL truncates identifiers longer than 63 bytes.\n * Used for column aliases, index names, and other generated identifiers.\n */\nexport const MAX_PG_IDENTIFIER_LENGTH = 63;\n\n/** Maximum byte length for the truncated portion of a generated identifier. */\nexport const TRUNCATED_IDENTIFIER_MAX_LENGTH = 54;\n\n/** Maximum length for a single component (kind name, field name) in a generated identifier. */\nexport const IDENTIFIER_COMPONENT_MAX_LENGTH = 20;\n\n// ============================================================\n// FNV-1a Hash Constants\n// ============================================================\n\n/** FNV-1a 32-bit offset basis. */\nexport const FNV1A_OFFSET_BASIS = 0x81_1c_9d_c5;\n\n/** FNV-1a 32-bit prime. */\nexport const FNV1A_PRIME = 0x01_00_01_93;\n\n// ============================================================\n// Pagination\n// ============================================================\n\n/** Default page size for paginate() and cursor-based pagination. */\nexport const DEFAULT_PAGINATION_LIMIT = 20;\n\n/** Default batch size for streaming query results. */\nexport const DEFAULT_STREAM_BATCH_SIZE = 1000;\n\n// ============================================================\n// Path Delimiters\n// ============================================================\n\n/** SQLite stores array paths as pipe-delimited strings: |id1|id2|id3| */\nexport const SQLITE_PATH_DELIMITER = \"|\";\n\n/** PostgreSQL text arrays use comma-separated elements: {id1,id2,id3} */\nexport const PG_PATH_ELEMENT_SEPARATOR = \",\";\n\n/** PostgreSQL text array start delimiter. */\nexport const PG_ARRAY_START = \"{\";\n\n/** PostgreSQL text array end delimiter. */\nexport const PG_ARRAY_END = \"}\";\n","/**\n * Hash utilities — FNV-1a for fast non-cryptographic identifier\n * generation, SHA-256 (truncated) for collision-resistant signatures.\n */\nimport { FNV1A_OFFSET_BASIS, FNV1A_PRIME } from \"../constants\";\n\n/**\n * FNV-1a hash of `input`, returned as a base-36 encoded string. Used for\n * generating short, deterministic identifiers (column aliases, index\n * name suffixes, etc.).\n */\nexport function fnv1aBase36(input: string): string {\n let hash = FNV1A_OFFSET_BASIS;\n for (const character of input) {\n const codePoint = character.codePointAt(0);\n if (codePoint === undefined) continue;\n hash ^= codePoint;\n hash = Math.imul(hash, FNV1A_PRIME);\n }\n return (hash >>> 0).toString(36);\n}\n\n/**\n * Hex-truncated SHA-256 of `input` via the Web Crypto API. Works in\n * Node.js 16+, Cloudflare Workers, Deno, and browsers.\n *\n * `byteLength` controls how many bytes of the digest are emitted —\n * default 8 (16 hex chars, ~64 bits, sufficient for schema-version and\n * per-graph index signatures). Pass 16 (32 hex chars) when hashes are\n * compared against externally-stored signatures.\n */\nexport async function sha256Hex(\n input: string,\n byteLength = 8,\n): Promise<string> {\n const encoded = new TextEncoder().encode(input);\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", encoded);\n const bytes = new Uint8Array(digest);\n let hex = \"\";\n for (let index = 0; index < byteLength; index++) {\n const byte = bytes[index];\n if (byte === undefined) break;\n hex += byte.toString(16).padStart(2, \"0\");\n }\n return hex;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/drizzle/execution/sqlite-execution.ts","../src/backend/drizzle/sqlite.ts"],"names":["sql","getOrCreateLru","compileQueryWithDialect","executeCompiled","SQLITE_MAX_BIND_PARAMETERS","createNodeRowMapper","SQLITE_ROW_MAPPER_CONFIG","createEdgeRowMapper","createUniqueRowMapper","createSchemaVersionRowMapper","BackendDisposedError","ConfigurationError","SQLITE_CAPABILITIES","buildFulltextCapabilities","buildVectorCapabilities","createCommonOperationBackend","nowIso","vectorSlotFromParams","mapVectorWriteError","assertVectorSearchLimit","vectorSlotFromCreateIndexParams","vectorSlotFromDropIndexParams","isMissingTableError","coerceNumericScore","tables","fts5Strategy","createVectorSlotLatch","getTableName","createSqliteOperationStrategy","generateSqliteCreateTableSQL","and","eq","mapContributionMaterializationRow","SQLITE_CONTRIBUTION_MAT_TIMESTAMPS","buildContributionInsertValues","buildContributionOnConflictSet","createContributionMaterializer","gateFulltext","generateSqliteDDL","gateFulltextMethods","mapMaterializationRow","SQLITE_INDEX_MAT_TIMESTAMPS","inArray","buildMaterializationInsertValues","buildMaterializationOnConflictSet","isNull","mapKindRemovalRow","SQLITE_KIND_REMOVAL_TIMESTAMPS","buildKindRemovalInsertValues","buildKindRemovalOnConflictSet","assertAdoptedDialect","BaseSQLiteDatabase"],"mappings":";;;;;;;;;;;AAWA,IAAM,oCAAA,GAAuC,GAAA;AAwE7C,SAAS,eAAe,EAAA,EAA2C;AACjE,EAAA,MAAM,mBAAA,GAAsB,EAAA;AAC5B,EAAA,MAAM,kBAAA,GAAqB,mBAAA,CAAoB,OAAA,EAAS,WAAA,EAAa,IAAA;AACrE,EAAA,IAAI,uBAAuB,MAAA,EAAW;AACpC,IAAA,OAAO,kBAAA;AAAA,EACT;AAEA,EAAA,OAAO,mBAAA,CAAoB,CAAA,EAAG,OAAA,EAAS,WAAA,EAAa,IAAA;AACtD;AAEA,SAAS,0BAA0B,EAAA,EAAgC;AACjE,EAAA,OAAO,cAAA,CAAe,EAAE,CAAA,KAAM,iBAAA;AAChC;AAEA,SAAS,6BAA6B,EAAA,EAAgC;AACpE,EAAA,MAAM,WAAA,GAAc,eAAe,EAAE,CAAA;AAIrC,EAAA,OACE,WAAA,KAAgB,qBAChB,WAAA,KAAgB,4BAAA;AAEpB;AAEA,SAAS,4BAA4B,EAAA,EAAgC;AACnE,EAAA,MAAM,WAAA,GAAc,eAAe,EAAE,CAAA;AACrC,EAAA,OACE,WAAA,KAAgB,yBAAyB,WAAA,KAAgB,kBAAA;AAE7D;AAEA,SAAS,iBAAA,CACP,IACA,YAAA,EACS;AACT,EAAA,IAAI,YAAA,CAAa,WAAW,MAAA,EAAW;AACrC,IAAA,OAAO,YAAA,CAAa,MAAA;AAAA,EACtB;AAEA,EAAA,MAAM,WAAA,GAAc,eAAe,EAAE,CAAA;AACrC,EAAA,IAAI,WAAA,KAAgB,qBAAA,IAAyB,WAAA,KAAgB,kBAAA,EAAoB;AAC/E,IAAA,OAAO,IAAA;AAAA,EACT;AAGA,EAAA,IAAI,4BAAA,CAA6B,EAA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E,GAAG,EAAE;AAAA;AACnC,OACJ;AAAA,IACF,CAAA;AAAA,IAEA,iBAAiB,UAAA,EAAoD;AAKnE,MAAA,IAAI,oBAAoB,MAAA,EAAQ;AAC9B,QAAA,+BAAA;AAAA,UACE;AAAA,SAMF;AAAA,MACF;AACA,MAAAkD,sCAAA;AAAA,QACE,UAAA;AAAA,QACAC,6BAAA;AAAA,QACA;AAAA,OACF;AAKA,MAAA,OAAO,uBAAuB,UAAU,CAAA;AAAA,IAC1C,CAAA;AAAA,IAEA,KAAA,GAAuB;AACrB,MAAA,eAAA,EAAiB,OAAA,EAAQ;AACzB,MAAA,OAAO,QAAQ,OAAA,EAAQ;AAAA,IACzB;AAAA,GACF;AAEA,EAAA,OAAO,OAAA;AACT;AAEA,SAAS,yBACP,OAAA,EAC0B;AAC1B,EAAA,MAAM,kBAAA,GACJ,OAAA,CAAQ,gBAAA,IACR,4BAAA,CAA6B,QAAQ,EAAA,EAAI;AAAA,IACvC,cAAc,OAAA,CAAQ;AAAA,GACvB,CAAA;AAQH,EAAA,OAAO,4BAAA,CAA6B;AAAA,IAClC,cAAc,OAAA,CAAQ,YAAA;AAAA,IACtB,IAAI,OAAA,CAAQ,EAAA;AAAA,IACZ,gBAAA,EAAkB,kBAAA;AAAA,IAClB,mBAAmB,OAAA,CAAQ,iBAAA;AAAA,IAC3B,YAAY,OAAA,CAAQ,UAAA;AAAA,IACpB,kBAAkB,OAAA,CAAQ,gBAAA;AAAA,IAC1B,gBAAgB,OAAA,CAAQ,cAAA;AAAA,IACxB,GAAI,QAAQ,cAAA,KAAmB,MAAA,GAC3B,EAAC,GACD,EAAE,eAAA,EAAiBzB,uCAAA,EAAsB;AAAE,GAChD,CAAA;AACH","file":"chunk-3642VBVC.cjs","sourcesContent":["import { type SQL, sql } from \"drizzle-orm\";\nimport { type BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport { getOrCreateLru } from \"./lru\";\nimport {\n type CompiledSqlQuery,\n compileQueryWithDialect,\n type PreparedSqlStatement,\n type SqlExecutionAdapter,\n} from \"./types\";\n\nconst DEFAULT_PREPARED_STATEMENT_CACHE_MAX = 256;\n\ntype PreparedAllStatement = Readonly<{\n all: (...params: readonly unknown[]) => readonly unknown[];\n}>;\n\ntype SqliteClientWithPrepare = Readonly<{\n prepare: (sqlText: string) => PreparedAllStatement;\n}>;\n\ntype SqliteClientCarrier = Readonly<{\n $client?: SqliteClientWithPrepare;\n}>;\n\ntype SessionLike = Readonly<{\n constructor?: Readonly<{\n name?: string;\n }>;\n}>;\n\ntype DatabaseWithSession = Readonly<{\n _?: Readonly<{\n session?: SessionLike;\n }>;\n session?: SessionLike;\n}>;\n\n/**\n * Controls how the backend manages SQLite transactions.\n *\n * - `\"sql\"`: TypeGraph issues BEGIN / COMMIT / ROLLBACK SQL directly.\n * Default for sync drivers (better-sqlite3, bun:sqlite).\n * - `\"drizzle\"`: Delegates to Drizzle's `db.transaction()` method.\n * Default for async drivers (libsql, sql.js).\n * - `\"do-sqlite\"`: Delegates to the Cloudflare Durable Objects async\n * storage transaction runner (`db.$client.transaction`,\n * i.e. `ctx.storage.transaction(async ...)`). Drizzle's\n * own `db.transaction()` on DO is\n * `ctx.storage.transactionSync` and cannot span `await`,\n * so it is deliberately not used. Auto-detected for\n * `drizzle(ctx.storage)` (#140).\n * - `\"none\"`: Transactions disabled. Default for Cloudflare D1\n * (`D1Database.batch` is transactional but not an\n * interactive runner — tracked separately).\n */\nexport type SqliteTransactionMode = \"sql\" | \"drizzle\" | \"none\" | \"do-sqlite\";\n\nexport type SqliteExecutionProfileHints = Readonly<{\n isSync?: boolean;\n transactionMode?: SqliteTransactionMode;\n}>;\n\ntype SqliteExecutionAdapterOptions = Readonly<{\n profileHints?: SqliteExecutionProfileHints;\n statementCacheMax?: number;\n}>;\n\nexport type AnySqliteDatabase = BaseSQLiteDatabase<\"sync\" | \"async\", unknown>;\n\nexport type SqliteExecutionProfile = Readonly<{\n isSync: boolean;\n supportsCompiledExecution: boolean;\n transactionMode: SqliteTransactionMode;\n}>;\n\nexport type SqliteExecutionAdapter = Readonly<\n SqlExecutionAdapter & {\n clearStatementCache: () => void;\n profile: SqliteExecutionProfile;\n }\n>;\n\nfunction getSessionName(db: AnySqliteDatabase): string | undefined {\n const databaseWithSession = db as DatabaseWithSession;\n const primarySessionName = databaseWithSession.session?.constructor?.name;\n if (primarySessionName !== undefined) {\n return primarySessionName;\n }\n\n return databaseWithSession._?.session?.constructor?.name;\n}\n\nfunction isD1DatabaseBySessionName(db: AnySqliteDatabase): boolean {\n return getSessionName(db) === \"SQLiteD1Session\";\n}\n\nfunction isDurableObjectBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n // drizzle-orm/durable-sqlite's session class is `SQLiteDOSession`\n // (verified drizzle 0.45.x). `SQLiteDurableObjectSession` is kept as\n // a defensive alias against future drizzle renames.\n return (\n sessionName === \"SQLiteDOSession\" ||\n sessionName === \"SQLiteDurableObjectSession\"\n );\n}\n\nfunction isSyncDatabaseBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n return (\n sessionName === \"BetterSQLiteSession\" || sessionName === \"BunSQLiteSession\"\n );\n}\n\nfunction detectSyncProfile(\n db: AnySqliteDatabase,\n profileHints: SqliteExecutionProfileHints,\n): boolean {\n if (profileHints.isSync !== undefined) {\n return profileHints.isSync;\n }\n\n const sessionName = getSessionName(db);\n if (sessionName === \"BetterSQLiteSession\" || sessionName === \"BunSQLiteSession\") {\n return true;\n }\n // Durable Objects SQLite is synchronous (`ctx.storage` exec /\n // `transactionSync`); detect it by name rather than the SQL probe.\n if (isDurableObjectBySessionName(db)) {\n return true;\n }\n if (sessionName === \"SQLiteD1Session\") {\n return false;\n }\n\n try {\n const probeResult = db.get(sql`SELECT 1 AS __typegraph_sync_probe__`);\n return !(probeResult instanceof Promise);\n } catch {\n return isSyncDatabaseBySessionName(db);\n }\n}\n\nfunction detectTransactionMode(\n db: AnySqliteDatabase,\n profileHints: SqliteExecutionProfileHints,\n isSync: boolean,\n): SqliteTransactionMode {\n if (profileHints.transactionMode !== undefined) {\n return profileHints.transactionMode;\n }\n // Neither D1 nor Durable Object SQLite supports raw BEGIN/COMMIT SQL\n // through Drizzle's db.run(), and Drizzle's own db.transaction() on\n // Durable Objects is `ctx.storage.transactionSync` (cannot span an\n // await). Durable Objects expose an async storage transaction runner\n // (`ctx.storage.transaction(async ...)`, surfaced by Drizzle as\n // `db.$client.transaction`) — route those through \"do-sqlite\" (#140).\n // D1 has no equivalent interactive runner (only batch); it stays\n // \"none\" pending a separate batch-mode investigation.\n if (isDurableObjectBySessionName(db)) {\n return \"do-sqlite\";\n }\n if (isD1DatabaseBySessionName(db)) {\n return \"none\";\n }\n if (isSync) return \"sql\";\n return \"drizzle\";\n}\n\nfunction resolveSqliteClient(\n db: AnySqliteDatabase,\n): SqliteClientWithPrepare | undefined {\n const databaseWithClient = db as SqliteClientCarrier;\n const sqliteClient = databaseWithClient.$client;\n if (sqliteClient?.prepare === undefined) {\n return undefined;\n }\n return sqliteClient;\n}\n\nfunction getOrCreatePreparedStatement(\n cache: Map<string, PreparedAllStatement>,\n sqliteClient: SqliteClientWithPrepare,\n sqlText: string,\n cacheMax: number,\n): PreparedAllStatement {\n return getOrCreateLru(cache, sqlText, cacheMax, () =>\n sqliteClient.prepare(sqlText),\n );\n}\n\n// Uses unconditional `await` because Drizzle returns SQLiteRaw thenables\n// that fail `instanceof Promise` checks (drizzle-team/drizzle-orm#2275).\nasync function executeDrizzleQuery<TRow>(\n db: AnySqliteDatabase,\n query: SQL,\n): Promise<readonly TRow[]> {\n return (await db.all(query));\n}\n\nfunction createPreparedStatementExecutor(\n sqliteClient: SqliteClientWithPrepare,\n cache: Map<string, PreparedAllStatement>,\n sqlText: string,\n cacheMax: number,\n): PreparedSqlStatement {\n return {\n execute<TRow>(params: readonly unknown[]): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n cache,\n sqliteClient,\n sqlText,\n cacheMax,\n );\n const rows = preparedStatement.all(...params);\n return Promise.resolve(rows as readonly TRow[]);\n },\n };\n}\n\nexport function createSqliteExecutionAdapter(\n db: AnySqliteDatabase,\n statementCacheMaxOrOptions: number | SqliteExecutionAdapterOptions = {},\n): SqliteExecutionAdapter {\n const options: SqliteExecutionAdapterOptions =\n typeof statementCacheMaxOrOptions === \"number\"\n ? { statementCacheMax: statementCacheMaxOrOptions }\n : statementCacheMaxOrOptions;\n const statementCacheMax =\n options.statementCacheMax ?? DEFAULT_PREPARED_STATEMENT_CACHE_MAX;\n const profileHints = options.profileHints ?? {};\n\n const isSync = detectSyncProfile(db, profileHints);\n const sqliteClient = isSync ? resolveSqliteClient(db) : undefined;\n const transactionMode = detectTransactionMode(db, profileHints, isSync);\n\n const profile: SqliteExecutionProfile = {\n isSync,\n supportsCompiledExecution: sqliteClient !== undefined,\n transactionMode,\n };\n\n const compile = (query: SQL): CompiledSqlQuery =>\n compileQueryWithDialect(db, query, \"SQLite\");\n\n if (sqliteClient !== undefined) {\n const client = sqliteClient;\n const statementCache = new Map<string, PreparedAllStatement>();\n\n function executeCompiled<TRow>(\n compiledQuery: CompiledSqlQuery,\n ): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n compiledQuery.sql,\n statementCacheMax,\n );\n const rows = preparedStatement.all(...compiledQuery.params);\n return Promise.resolve(rows as readonly TRow[]);\n }\n\n return {\n clearStatementCache() {\n statementCache.clear();\n },\n compile,\n execute<TRow>(query: SQL): Promise<readonly TRow[]> {\n const compiledQuery = compile(query);\n return executeCompiled<TRow>(compiledQuery);\n },\n executeCompiled,\n prepare(sqlText: string): PreparedSqlStatement {\n return createPreparedStatementExecutor(\n client,\n statementCache,\n sqlText,\n statementCacheMax,\n );\n },\n profile,\n };\n }\n\n return {\n clearStatementCache() {\n // No-op: no statement cache in async/D1 mode\n },\n compile,\n execute<TRow>(query: SQL): Promise<readonly TRow[]> {\n return executeDrizzleQuery<TRow>(db, query);\n },\n profile,\n };\n}\n","/**\n * SQLite backend adapter for TypeGraph.\n *\n * Works with any Drizzle SQLite database instance:\n * - better-sqlite3\n * - libsql / Turso\n * - Cloudflare D1\n * - bun:sqlite\n * - sql.js\n *\n * @example\n * ```typescript\n * import { drizzle } from \"drizzle-orm/better-sqlite3\";\n * import Database from \"better-sqlite3\";\n * import { createSqliteBackend, tables } from \"@nicia-ai/typegraph/sqlite\";\n *\n * const sqlite = new Database(\"app.db\");\n * const db = drizzle(sqlite);\n * const backend = createSqliteBackend(db, { tables });\n * ```\n */\nimport {\n and,\n eq,\n getTableName,\n inArray,\n isNull,\n type SQL,\n sql,\n} from \"drizzle-orm\";\nimport { BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport { BackendDisposedError, ConfigurationError } from \"../../errors\";\nimport type { ResolvedSqlTableNames } from \"../../query/compiler/schema\";\nimport {\n buildFulltextCapabilities,\n fts5Strategy,\n type FulltextStrategy,\n} from \"../../query/dialect/fulltext-strategy\";\nimport {\n assertVectorSearchLimit,\n buildVectorCapabilities,\n type VectorSlot,\n type VectorStrategy,\n} from \"../../query/dialect/vector-strategy\";\nimport { isMissingTableError } from \"../../utils/sql-errors\";\nimport {\n type AdoptedTransaction,\n type BackendCapabilities,\n type CommitSchemaVersionParams,\n type ContributionMaterializationIdentity,\n type ContributionMaterializationRow,\n type CreateVectorIndexParams,\n type DeleteEmbeddingParams,\n type DeleteFulltextBatchParams,\n type DeleteFulltextParams,\n type DropVectorIndexParams,\n type FulltextSearchParams,\n type FulltextSearchResult,\n type GraphBackend,\n type IndexMaterializationRow,\n type KindRemovalRow,\n type RecordContributionMaterializationParams,\n type RecordIndexMaterializationParams,\n type RecordKindRemovalParams,\n type SchemaVersionRow,\n type SetActiveVersionParams,\n SQLITE_CAPABILITIES,\n SQLITE_MAX_BIND_PARAMETERS,\n type TransactionBackend,\n type TransactionOptions,\n type UpsertEmbeddingParams,\n type UpsertFulltextBatchParams,\n type UpsertFulltextParams,\n type VectorSearchParams,\n type VectorSearchResult,\n} from \"../types\";\nimport {\n type AnySqliteDatabase,\n createSqliteExecutionAdapter,\n type SqliteExecutionAdapter,\n type SqliteExecutionProfileHints,\n} from \"./execution/sqlite-execution\";\nimport {\n createVectorSlotLatch,\n mapVectorWriteError,\n vectorSlotFromCreateIndexParams,\n vectorSlotFromDropIndexParams,\n vectorSlotFromParams,\n type VectorSlotLatch,\n} from \"./vector-runtime\";\nexport type { SqliteTransactionMode } from \"./execution/sqlite-execution\";\nimport {\n buildContributionInsertValues,\n buildContributionOnConflictSet,\n createContributionMaterializer,\n gateFulltext,\n gateFulltextMethods,\n mapContributionMaterializationRow,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS,\n} from \"./contribution-materializations\";\nimport { generateSqliteCreateTableSQL, generateSqliteDDL } from \"./ddl\";\nimport {\n buildMaterializationInsertValues,\n buildMaterializationOnConflictSet,\n mapMaterializationRow,\n SQLITE_INDEX_MAT_TIMESTAMPS,\n} from \"./index-materializations\";\nimport {\n buildKindRemovalInsertValues,\n buildKindRemovalOnConflictSet,\n mapKindRemovalRow,\n SQLITE_KIND_REMOVAL_TIMESTAMPS,\n} from \"./kind-removals\";\nimport {\n assertAdoptedDialect,\n type CommonOperationBackend,\n createCommonOperationBackend,\n type InternalOperationBackend,\n} from \"./operation-backend-core\";\nimport { createSqliteOperationStrategy } from \"./operations/strategy\";\nimport {\n coerceNumericScore,\n createEdgeRowMapper,\n createNodeRowMapper,\n createSchemaVersionRowMapper,\n createUniqueRowMapper,\n nowIso,\n SQLITE_ROW_MAPPER_CONFIG,\n} from \"./row-mappers\";\nimport { type SqliteTables, tables as defaultTables } from \"./schema/sqlite\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a SQLite backend.\n */\nexport type SqliteBackendOptions = Readonly<{\n /**\n * Custom table definitions. Use createSqliteTables() to customize table names.\n * Defaults to standard TypeGraph table names.\n */\n tables?: SqliteTables;\n /**\n * Optional execution profile hints used to avoid runtime driver reflection.\n * Set `transactionMode: \"none\"` for drivers without transactions (e.g.\n * Cloudflare D1). Durable Objects (`drizzle(ctx.storage)`) auto-detect\n * `transactionMode: \"do-sqlite\"` and do not need a hint.\n */\n executionProfile?: SqliteExecutionProfileHints;\n /**\n * Fulltext strategy override. Defaults to `fts5Strategy` (SQLite's\n * built-in FTS5 virtual table). Most users should leave this alone.\n */\n fulltext?: FulltextStrategy;\n /**\n * Vector strategy override. When present, the backend owns per-`(kind,\n * field)` typed storage through this strategy (DDL, upsert, delete,\n * similarity search, ANN index lifecycle) and advertises\n * `strategy.capabilities` as `capabilities.vector`. `createLibsqlBackend`\n * passes `libsqlVectorStrategy` unconditionally; `createLocalSqliteBackend`\n * passes `sqliteVecStrategy` when the extension loads. When absent the\n * backend exposes no vector capability and embedding values pass through\n * writes without being indexed — matching existing behavior for SQLite\n * connections without a vector extension.\n */\n vector?: VectorStrategy;\n /**\n * Override specific backend capabilities. Useful for custom SQLite builds\n * or tests that need to simulate an engine-level capability gap.\n */\n capabilities?: Partial<BackendCapabilities>;\n}>;\n\nconst NODE_INSERT_PARAM_COUNT = 9;\nconst EDGE_INSERT_PARAM_COUNT = 12;\nconst SQLITE_NODE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(SQLITE_MAX_BIND_PARAMETERS / NODE_INSERT_PARAM_COUNT),\n);\nconst SQLITE_EDGE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(SQLITE_MAX_BIND_PARAMETERS / EDGE_INSERT_PARAM_COUNT),\n);\nconst SQLITE_GET_NODES_ID_CHUNK_SIZE = Math.max(\n 1,\n SQLITE_MAX_BIND_PARAMETERS - 2,\n);\nconst SQLITE_GET_EDGES_ID_CHUNK_SIZE = Math.max(\n 1,\n SQLITE_MAX_BIND_PARAMETERS - 1,\n);\nconst CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT = 3;\nconst SQLITE_CHECK_UNIQUE_BATCH_CHUNK_SIZE = Math.max(\n 1,\n SQLITE_MAX_BIND_PARAMETERS - CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT,\n);\n\ntype SerializedExecutionQueue = Readonly<{\n dispose: () => void;\n runExclusive: <T>(task: () => Promise<T>) => Promise<T>;\n}>;\n\n// ============================================================\n// Utilities\n// ============================================================\n\nconst toNodeRow = createNodeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toEdgeRow = createEdgeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toUniqueRow = createUniqueRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toSchemaVersionRow = createSchemaVersionRowMapper(\n SQLITE_ROW_MAPPER_CONFIG,\n);\n\n/** A shared promise that never settles — used to absorb post-dispose work. */\nconst PENDING_FOREVER: Promise<never> = new Promise<never>(noop);\n\nfunction pendingForever<T>(): Promise<T> {\n return PENDING_FOREVER;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noop(): void {}\n\nfunction createSerializedExecutionQueue(): SerializedExecutionQueue {\n let tail: Promise<unknown> = Promise.resolve();\n let disposed = false;\n\n function isDisposed(): boolean {\n return disposed;\n }\n\n return {\n dispose() {\n disposed = true;\n },\n\n runExclusive<T>(task: () => Promise<T>): Promise<T> {\n if (isDisposed()) return Promise.reject(new BackendDisposedError());\n\n // When disposed, runTask returns a never-settling promise so that no\n // rejection propagates through the 7+ async wrappers between this\n // queue and the store-level caller. A rejection here would become an\n // unhandled rejection if the caller abandoned the promise during\n // teardown — and JavaScript offers no way to `.catch()` a rejection\n // at the bottom of a chain without every async wrapper above it also\n // creating an independently-unhandled rejected promise.\n //\n // The tradeoff: an active caller whose operation was queued before\n // dispose() will see a permanently-pending promise rather than a\n // BackendDisposedError. Post-dispose submissions (the check above)\n // still reject immediately since the caller actively holds that\n // promise.\n const runTask = async (): Promise<T> => {\n if (isDisposed()) return pendingForever<T>();\n try {\n return await task();\n } catch (error) {\n if (isDisposed()) return pendingForever<T>();\n throw error;\n }\n };\n const result = tail.then(runTask, runTask);\n tail = result.then(\n () => 0,\n () => 0,\n );\n return result;\n },\n };\n}\n\nfunction runWithSerializedQueue<T>(\n queue: SerializedExecutionQueue | undefined,\n task: () => Promise<T>,\n): Promise<T> {\n if (queue === undefined) return task();\n return queue.runExclusive(task);\n}\n\n/**\n * The async storage transaction runner Drizzle's durable-sqlite driver\n * exposes as `db.$client` (`ctx.storage.transaction(async () => ...)`).\n * Structural because drizzle-orm does not export the DO `$client` type.\n */\ninterface DurableObjectStorageClient {\n transaction?: <R>(closure: () => Promise<R>) => Promise<R>;\n}\n\n/** Every SQLite \"atomic transactions unavailable\" refusal shares this shape. */\nfunction throwSqliteTransactionsDisabled(message: string): never {\n throw new ConfigurationError(message, {\n backend: \"sqlite\",\n capability: \"transactions\",\n supportsTransactions: false,\n });\n}\n\nfunction buildSqliteCapabilities(\n options: Readonly<{\n fulltextStrategy: FulltextStrategy;\n vectorStrategy: VectorStrategy | undefined;\n transactionMode: SqliteExecutionAdapter[\"profile\"][\"transactionMode\"];\n }>,\n): BackendCapabilities {\n const base =\n options.transactionMode === \"none\" ?\n { ...SQLITE_CAPABILITIES, transactions: false }\n : SQLITE_CAPABILITIES;\n return {\n ...base,\n fulltext: buildFulltextCapabilities(options.fulltextStrategy),\n ...(options.vectorStrategy === undefined ?\n {}\n : { vector: buildVectorCapabilities(options.vectorStrategy) }),\n };\n}\n\n// ============================================================\n// Backend Factory\n// ============================================================\n\n/**\n * Creates a TypeGraph backend for SQLite databases.\n *\n * Works with any Drizzle SQLite instance regardless of the underlying driver.\n *\n * @param db - A Drizzle SQLite database instance\n * @param options - Backend configuration\n * @returns A GraphBackend implementation\n */\ntype CreateSqliteOperationBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n serializedQueue?: SerializedExecutionQueue;\n tableNames: ResolvedSqlTableNames;\n fulltextStrategy: FulltextStrategy;\n /**\n * Active vector strategy, or `undefined` when the connection has no\n * vector extension. When present, the backend exposes upsertEmbedding /\n * deleteEmbedding / vectorSearch / createVectorIndex / dropVectorIndex,\n * all routed through this strategy's per-`(kind, field)` storage.\n */\n vectorStrategy?: VectorStrategy | undefined;\n /**\n * Per-`(kind, field)` storage-ensure latch shared across the outer\n * backend and every transaction-scoped backend (see\n * {@link createVectorSlotLatch}). Required whenever `vectorStrategy` is\n * set so writes never hit a missing per-field table.\n */\n vectorSlotLatch?: VectorSlotLatch | undefined;\n}>;\n\ntype CreateSqliteTransactionBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter?: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n profileHints: SqliteExecutionProfileHints;\n tableNames: ResolvedSqlTableNames;\n fulltextStrategy: FulltextStrategy;\n /** Active vector strategy. See {@link CreateSqliteOperationBackendOptions}. */\n vectorStrategy?: VectorStrategy | undefined;\n /** Shared storage-ensure latch. See {@link CreateSqliteOperationBackendOptions}. */\n vectorSlotLatch?: VectorSlotLatch | undefined;\n}>;\n\nfunction createSqliteOperationBackend(\n options: CreateSqliteOperationBackendOptions,\n): InternalOperationBackend {\n const {\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n serializedQueue,\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n vectorSlotLatch,\n } = options;\n\n function execGet<T>(query: SQL): Promise<T | undefined> {\n // Workaround: drizzle-team/drizzle-orm#1049 — db.get() crashes with\n // the libsql driver when no rows match (normalizeRow receives undefined).\n // Using db.all()[0] avoids the crash for all drivers.\n //\n // All three exec helpers use `await` unconditionally rather than\n // `instanceof Promise` because Drizzle returns SQLiteRaw thenables\n // that are NOT Promise instances (drizzle-team/drizzle-orm#2275).\n return runWithSerializedQueue(serializedQueue, async () => {\n const rows = await db.all(query);\n return (rows as T[])[0];\n });\n }\n\n function execAll<T>(query: SQL): Promise<T[]> {\n return runWithSerializedQueue(serializedQueue, async () => {\n return await db.all(query);\n });\n }\n\n function execRun(query: SQL): Promise<void> {\n return runWithSerializedQueue(serializedQueue, async () => {\n await db.run(query);\n });\n }\n\n const commonBackend = createCommonOperationBackend({\n batchConfig: {\n checkUniqueBatchChunkSize: SQLITE_CHECK_UNIQUE_BATCH_CHUNK_SIZE,\n edgeInsertBatchSize: SQLITE_EDGE_INSERT_BATCH_SIZE,\n getEdgesChunkSize: SQLITE_GET_EDGES_ID_CHUNK_SIZE,\n getNodesChunkSize: SQLITE_GET_NODES_ID_CHUNK_SIZE,\n nodeInsertBatchSize: SQLITE_NODE_INSERT_BATCH_SIZE,\n },\n execution: {\n execAll,\n execGet,\n execRun,\n },\n nowIso,\n operationStrategy,\n rowMappers: {\n toEdgeRow,\n toNodeRow,\n toSchemaVersionRow,\n toUniqueRow,\n },\n });\n\n const executeCompiled = executionAdapter.executeCompiled;\n const executeRawMethod: Pick<TransactionBackend, \"executeRaw\"> =\n executeCompiled === undefined ?\n {}\n : {\n executeRaw<T>(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executeCompiled<T>({ params, sql: sqlText }),\n );\n },\n };\n\n // The latch runs per-field DDL on the same connection a write/search\n // executes on, so a transaction-scoped write materializes its slot inside\n // the caller's transaction.\n async function ensureVectorSlotStorage(slot: VectorSlot): Promise<void> {\n if (vectorStrategy === undefined || vectorSlotLatch === undefined) return;\n await vectorSlotLatch.ensure(vectorStrategy, slot, async (statement) => {\n await execRun(sql.raw(statement));\n });\n }\n\n const vectorEmbeddingMethods =\n vectorStrategy === undefined ?\n {}\n : {\n async upsertEmbedding(params: UpsertEmbeddingParams): Promise<void> {\n const slot = vectorSlotFromParams(params);\n await ensureVectorSlotStorage(slot);\n const statements = vectorStrategy.buildUpsert(slot, params, nowIso());\n try {\n for (const statement of statements) {\n await execRun(statement);\n }\n } catch (error) {\n throw mapVectorWriteError(error, params);\n }\n },\n async deleteEmbedding(params: DeleteEmbeddingParams): Promise<void> {\n // Ensure the per-field table exists before deleting. A delete\n // can run before any embedding was ever written for the field\n // (e.g. a node hard-deleted having never carried one); the\n // idempotent ensure makes the DELETE a clean no-op against an\n // existing (possibly empty) table, matching the Postgres path\n // (where a DELETE on a missing relation would abort an\n // enclosing transaction).\n const slot = vectorSlotFromParams(params);\n await ensureVectorSlotStorage(slot);\n const statements = vectorStrategy.buildDelete(slot, params);\n for (const statement of statements) {\n await execRun(statement);\n }\n },\n async vectorSearch(\n params: VectorSearchParams,\n ): Promise<readonly VectorSearchResult[]> {\n assertVectorSearchLimit(params.limit);\n const slot = vectorSlotFromParams(params);\n await ensureVectorSlotStorage(slot);\n const query = vectorStrategy.buildSearch(slot, params);\n let rows: readonly { node_id: string; score: number }[];\n try {\n rows = await execAll<{ node_id: string; score: number }>(query);\n } catch (error) {\n // A query vector whose dimension no longer matches the stored\n // column surfaces the same typed error as the write path.\n throw mapVectorWriteError(error, params);\n }\n return rows.map((row) => ({\n nodeId: row.node_id,\n score: row.score,\n }));\n },\n };\n\n const operationBackend: InternalOperationBackend = {\n ...commonBackend,\n ...executeRawMethod,\n ...vectorEmbeddingMethods,\n capabilities,\n dialect: \"sqlite\",\n tableNames,\n fulltextStrategy,\n ...(vectorStrategy === undefined ? {} : { vectorStrategy }),\n\n async createVectorIndex(params: CreateVectorIndexParams): Promise<void> {\n if (vectorStrategy === undefined) return;\n const slot = vectorSlotFromCreateIndexParams(params);\n // Ensure the per-field table exists first (idempotent), then create\n // its ANN index. `ownedTables` already folds the index DDL in, so the\n // explicit `buildCreateIndex` step is belt-and-suspenders for slots\n // whose index intent changed after the table was first materialized.\n await ensureVectorSlotStorage(slot);\n const indexStatement = vectorStrategy.buildCreateIndex?.(slot);\n if (indexStatement !== undefined) {\n await execRun(indexStatement);\n }\n },\n\n async dropVectorIndex(params: DropVectorIndexParams): Promise<void> {\n if (vectorStrategy === undefined) return;\n const slot = vectorSlotFromDropIndexParams(params);\n const dropStatement = vectorStrategy.buildDropIndex?.(slot);\n if (dropStatement === undefined) return;\n try {\n await execRun(dropStatement);\n } catch (error) {\n // The per-field table (and thus its index) may never have been\n // materialized; DROP INDEX IF EXISTS against a missing table errors\n // on some drivers, so treat that as already-dropped.\n if (!isMissingTableError(error)) throw error;\n }\n },\n\n // === Fulltext Operations ===\n\n async upsertFulltext(params: UpsertFulltextParams): Promise<void> {\n const timestamp = nowIso();\n const statements = operationStrategy.buildUpsertFulltext(\n params,\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async deleteFulltext(params: DeleteFulltextParams): Promise<void> {\n const statements = operationStrategy.buildDeleteFulltext(params);\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async upsertFulltextBatch(\n params: UpsertFulltextBatchParams,\n ): Promise<void> {\n if (params.rows.length === 0) return;\n const timestamp = nowIso();\n const statements = operationStrategy.buildUpsertFulltextBatch(\n params,\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async deleteFulltextBatch(\n params: DeleteFulltextBatchParams,\n ): Promise<void> {\n if (params.nodeIds.length === 0) return;\n const statements = operationStrategy.buildDeleteFulltextBatch(params);\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async fulltextSearch(\n params: FulltextSearchParams,\n ): Promise<readonly FulltextSearchResult[]> {\n const query = operationStrategy.buildFulltextSearch(params);\n const rows = await execAll<{\n node_id: string;\n score: number | string;\n snippet: string | null;\n }>(query);\n return rows.map((row, index) => ({\n nodeId: row.node_id,\n score: coerceNumericScore(row.score),\n rank: index + 1,\n ...(row.snippet === null ? {} : { snippet: row.snippet }),\n }));\n },\n\n // === Query Execution ===\n\n async execute<T>(query: SQL): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executionAdapter.execute<T>(query),\n );\n },\n\n compileSql(\n query: SQL,\n ): Readonly<{ sql: string; params: readonly unknown[] }> {\n return executionAdapter.compile(query);\n },\n };\n\n return operationBackend;\n}\n\nexport function createSqliteBackend(\n db: AnySqliteDatabase,\n options: SqliteBackendOptions = {},\n): GraphBackend {\n const tables = options.tables ?? defaultTables;\n const fulltextStrategy = options.fulltext ?? fts5Strategy;\n const profileHints = options.executionProfile ?? {};\n const executionAdapter = createSqliteExecutionAdapter(db, { profileHints });\n const { isSync, transactionMode } = executionAdapter.profile;\n // The active vector strategy gates upsertEmbedding / deleteEmbedding /\n // vectorSearch and supplies the per-`(kind, field)` storage. Passed by\n // the caller that knows the connection's vector capability\n // (`createLibsqlBackend` always; `createLocalSqliteBackend` when the\n // extension loads); absent for plain SQLite drivers with no extension.\n const vectorStrategy = options.vector;\n // One latch per backend instance, shared with every transaction-scoped\n // backend so a slot's per-field table is created at most once per process.\n const vectorSlotLatch =\n vectorStrategy === undefined ? undefined : createVectorSlotLatch();\n const capabilities: BackendCapabilities = {\n ...buildSqliteCapabilities({\n fulltextStrategy,\n vectorStrategy,\n transactionMode,\n }),\n ...options.capabilities,\n };\n\n const tableNames: ResolvedSqlTableNames = {\n nodes: getTableName(tables.nodes),\n edges: getTableName(tables.edges),\n recordedNodes: getTableName(tables.recordedNodes),\n recordedEdges: getTableName(tables.recordedEdges),\n recordedClock: getTableName(tables.recordedClock),\n fulltext: tables.fulltextTableName,\n uniques: getTableName(tables.uniques),\n };\n const operationStrategy = createSqliteOperationStrategy(\n tables,\n fulltextStrategy,\n );\n const serializedQueue = isSync ? createSerializedExecutionQueue() : undefined;\n const operations = createSqliteOperationBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n vectorSlotLatch,\n ...(serializedQueue === undefined ? {} : { serializedQueue }),\n });\n\n /**\n * #140: the `transactionMode: \"do-sqlite\"` primitive. Cloudflare\n * Durable Objects expose an async storage transaction runner —\n * `ctx.storage.transaction(async () => ...)`, surfaced by Drizzle as\n * `db.$client.transaction` — that rolls back SQL writes across\n * `await`. There is no Drizzle tx handle on DO: the storage\n * transaction is ambient on the object, so callers bind the *outer*\n * `db` (as the \"sql\" path binds the outer connection). Drizzle's own\n * `db.transaction()` here is `ctx.storage.transactionSync` and cannot\n * span an await, so it is deliberately not used. Shared by\n * `transaction()` (business writes) and `runSchemaWriteTransaction()`\n * (schema-version commits — data only, never DDL: the #135 invariant\n * holds because `bootstrapTables` runs outside any transaction).\n */\n function runDoSqliteStorageTransaction<T>(run: () => Promise<T>): Promise<T> {\n const storage = (db as { $client?: DurableObjectStorageClient }).$client;\n const storageTransaction = storage?.transaction;\n if (typeof storageTransaction !== \"function\") {\n throwSqliteTransactionsDisabled(\n \"transactionMode 'do-sqlite' requires a Drizzle Durable Objects \" +\n \"database (drizzle(ctx.storage)) whose `$client` exposes the \" +\n \"async storage `transaction(async () => ...)` runner.\",\n );\n }\n return runWithSerializedQueue(\n serializedQueue,\n async () => storageTransaction.call(storage, run) as Promise<T>,\n );\n }\n\n /**\n * Runs `fn` inside a SQLite write transaction (BEGIN IMMEDIATE) so that\n * the read-then-write inside `commitSchemaVersion` / `setActiveVersion`\n * is serialized against concurrent writers — a deferred BEGIN would let\n * two transactions race past the CAS read and one would later fail\n * with SQLITE_BUSY instead of producing a clean StaleVersionError.\n *\n * Refuses on `transactionMode: \"none\"`. The orphan-row crash window\n * cannot be eliminated without atomicity.\n */\n function runSchemaWriteTransaction<T>(\n fn: (tx: CommonOperationBackend) => Promise<T>,\n ): Promise<T> {\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"commitSchemaVersion and setActiveVersion require atomic transactions, \" +\n \"but this SQLite backend has transactions disabled. Configure a \" +\n \"driver that supports transactions (better-sqlite3, libsql, \" +\n \"bun:sqlite) to use schema commits.\",\n );\n }\n\n if (transactionMode === \"sql\") {\n return runWithSerializedQueue(serializedQueue, async () => {\n // Write-lock is held here, so the schema-write-capable\n // InternalOperationBackend is used intentionally (see its type).\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isSync: true },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n vectorSlotLatch,\n });\n db.run(sql`BEGIN IMMEDIATE`);\n try {\n const result = await fn(txBackend);\n db.run(sql`COMMIT`);\n return result;\n } catch (error) {\n db.run(sql`ROLLBACK`);\n throw error;\n }\n });\n }\n\n if (transactionMode === \"do-sqlite\") {\n // No interactive lock-mode control on the DO storage runner; the\n // serialized queue (always present — DO is sync) provides the\n // single-writer ordering that \"immediate\" gives the other paths.\n // Raw txBackend (no `gateFulltext`, unlike the business\n // `transaction()` do-sqlite branch): schema-version commits are\n // data-only and never touch fulltext (#135), matching the \"sql\"\n // and \"drizzle\" schema-write branches.\n return runDoSqliteStorageTransaction(async () => {\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n vectorSlotLatch,\n });\n return fn(txBackend);\n });\n }\n\n // transactionMode === \"drizzle\". Drizzle's sqlite-core transaction\n // accepts a `behavior` option that maps to BEGIN / BEGIN IMMEDIATE /\n // BEGIN EXCLUSIVE; \"immediate\" is what we need to acquire a reserved\n // write lock at the start of the transaction.\n return runWithSerializedQueue(\n serializedQueue,\n async () =>\n db.transaction(\n async (tx) => {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n vectorSlotLatch,\n });\n return fn(txBackend);\n },\n { behavior: \"immediate\" },\n ) as Promise<T>,\n );\n }\n\n // Durable fulltext materialization (#135): the dialect-specific\n // marker-table primitives. Orchestration (materialize / assert /\n // per-instance cache) lives once in `createContributionMaterializer`.\n const matTable = tables.contributionMaterializations;\n\n async function ensureContributionMaterializationsTableImpl(): Promise<void> {\n await db.run(sql.raw(generateSqliteCreateTableSQL(matTable)));\n }\n\n async function getContributionMaterializationRow(\n identity: ContributionMaterializationIdentity,\n ): Promise<ContributionMaterializationRow | undefined> {\n const rows = await db\n .select()\n .from(matTable)\n .where(\n and(\n eq(matTable.graphId, identity.graphId),\n eq(matTable.logicalName, identity.logicalName),\n eq(matTable.owner, identity.owner),\n eq(matTable.tableName, identity.tableName),\n ),\n );\n const row = rows[0];\n if (row === undefined) return undefined;\n return mapContributionMaterializationRow(\n row,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS.decode,\n );\n }\n\n async function recordContributionMaterializationRow(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await db\n .insert(matTable)\n .values(\n buildContributionInsertValues(\n params,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: [\n matTable.graphId,\n matTable.logicalName,\n matTable.owner,\n matTable.tableName,\n ],\n set: buildContributionOnConflictSet(\n matTable.materializedAt,\n params.materializedAt,\n ),\n });\n }\n\n const contributionMaterializer = createContributionMaterializer({\n dialect: \"sqlite\",\n fulltextStrategy,\n fulltextTableName: tables.fulltextTableName,\n execDdl: async (statement) => {\n await db.run(sql.raw(statement));\n },\n ensureMarkerTable: ensureContributionMaterializationsTableImpl,\n getMarker: getContributionMaterializationRow,\n recordMarker: recordContributionMaterializationRow,\n });\n\n // Shared by the \"drizzle\" branch of `transaction()` (TypeGraph opens\n // the tx) and `adoptTransaction()` (#134 — the caller already opened\n // it): bind a tx-scoped backend to the *literal* `tx` client and gate\n // fulltext on the durable marker (a cached SELECT, never DDL).\n function bindTransactionBackend(tx: AnySqliteDatabase): TransactionBackend {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n vectorSlotLatch,\n });\n return gateFulltext(txBackend, contributionMaterializer.assertInitialized);\n }\n\n const backend: GraphBackend = {\n ...operations,\n\n async bootstrapTables(): Promise<void> {\n const statements = generateSqliteDDL(tables, fulltextStrategy);\n for (const statement of statements) {\n await db.run(sql.raw(statement));\n }\n },\n\n // Every fulltext-touching method asserts the durable marker instead\n // of lazily emitting DDL. Steady state performs zero ensure; an\n // uninitialized database throws `StoreNotInitializedError` rather\n // than self-healing (#135). Shared verbatim with the tx-scoped gate\n // via `gateFulltextMethods`.\n ...gateFulltextMethods(\n operations,\n contributionMaterializer.assertInitialized,\n ),\n\n async executeDdl(ddl: string): Promise<void> {\n await db.run(sql.raw(ddl));\n },\n\n async ensureIndexMaterializationsTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.indexMaterializations)),\n );\n },\n\n async getIndexMaterialization(\n indexName: string,\n ): Promise<IndexMaterializationRow | undefined> {\n const t = tables.indexMaterializations;\n const rows = await db.select().from(t).where(eq(t.indexName, indexName));\n const row = rows[0];\n if (row === undefined) return undefined;\n return mapMaterializationRow(row, SQLITE_INDEX_MAT_TIMESTAMPS.decode);\n },\n\n async getIndexMaterializations(\n statusKeys: readonly string[],\n ): Promise<readonly IndexMaterializationRow[]> {\n if (statusKeys.length === 0) return [];\n const t = tables.indexMaterializations;\n const rows = await db\n .select()\n .from(t)\n .where(inArray(t.indexName, [...statusKeys]));\n return rows.map((row) =>\n mapMaterializationRow(row, SQLITE_INDEX_MAT_TIMESTAMPS.decode),\n );\n },\n\n async recordIndexMaterialization(\n params: RecordIndexMaterializationParams,\n ): Promise<void> {\n const t = tables.indexMaterializations;\n await db\n .insert(t)\n .values(\n buildMaterializationInsertValues(\n params,\n SQLITE_INDEX_MAT_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: t.indexName,\n set: buildMaterializationOnConflictSet(\n t.materializedAt,\n params.materializedAt,\n ),\n });\n },\n\n async ensureContributionMaterializationsTable(): Promise<void> {\n await ensureContributionMaterializationsTableImpl();\n },\n\n async getContributionMaterialization(\n identity: ContributionMaterializationIdentity,\n ): Promise<ContributionMaterializationRow | undefined> {\n return getContributionMaterializationRow(identity);\n },\n\n async recordContributionMaterialization(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await recordContributionMaterializationRow(params);\n },\n\n async assertRuntimeContributionsInitialized(\n graphId: string,\n ): Promise<void> {\n await contributionMaterializer.assertInitialized(graphId);\n },\n\n async ensureKindRemovalsTable(): Promise<void> {\n await db.run(sql.raw(generateSqliteCreateTableSQL(tables.kindRemovals)));\n },\n\n async getPendingKindRemovals(\n graphId: string,\n ): Promise<readonly KindRemovalRow[]> {\n const t = tables.kindRemovals;\n const rows = await db\n .select()\n .from(t)\n .where(and(eq(t.graphId, graphId), isNull(t.removedAt)));\n return rows.map((row) =>\n mapKindRemovalRow(row, SQLITE_KIND_REMOVAL_TIMESTAMPS.decode),\n );\n },\n\n async getAllKindRemovals(\n graphId: string,\n ): Promise<readonly KindRemovalRow[]> {\n const t = tables.kindRemovals;\n const rows = await db.select().from(t).where(eq(t.graphId, graphId));\n return rows.map((row) =>\n mapKindRemovalRow(row, SQLITE_KIND_REMOVAL_TIMESTAMPS.decode),\n );\n },\n\n async recordKindRemoval(params: RecordKindRemovalParams): Promise<void> {\n const t = tables.kindRemovals;\n await db\n .insert(t)\n .values(\n buildKindRemovalInsertValues(\n params,\n SQLITE_KIND_REMOVAL_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: [t.graphId, t.kindName, t.entity, t.schemaVersion],\n set: buildKindRemovalOnConflictSet(t.removedAt, params.removedAt),\n });\n },\n\n async ensureReconciliationMarkersTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.reconciliationMarkers)),\n );\n },\n\n async ensureRuntimeContributions(graphId: string): Promise<void> {\n await contributionMaterializer.ensureRuntimeContributions(graphId);\n },\n\n /**\n * Superseded by `ensureRuntimeContributions(graphId)` (#129).\n * Retained as a thin back-compat wrapper for callers predating\n * #129; #135 routed it through the durable-marker writer.\n */\n async ensureFulltextTable(graphId: string): Promise<void> {\n await contributionMaterializer.ensureRuntimeContributions(graphId);\n },\n\n async getReconciliationMarker(\n graphId: string,\n ): Promise<number | undefined> {\n const t = tables.reconciliationMarkers;\n const rows = await db.select().from(t).where(eq(t.graphId, graphId));\n return rows[0]?.reconciledToVersion;\n },\n\n async setReconciliationMarker(\n graphId: string,\n version: number,\n ): Promise<void> {\n const t = tables.reconciliationMarkers;\n await db\n .insert(t)\n .values({ graphId, reconciledToVersion: version })\n .onConflictDoUpdate({\n target: t.graphId,\n set: { reconciledToVersion: version },\n });\n },\n\n async refreshStatistics(): Promise<void> {\n // `ANALYZE` populates `sqlite_stat1`. With no stat table, the\n // planner falls back to heuristics that, at least for FTS5\n // virtual-table queries and multi-column index selection, can be\n // an order of magnitude slower. Running it explicitly makes the\n // planner data-driven.\n await db.run(sql`ANALYZE`);\n },\n\n async commitSchemaVersion(\n params: CommitSchemaVersionParams,\n ): Promise<SchemaVersionRow> {\n return runSchemaWriteTransaction((target) =>\n target.commitSchemaVersion(params),\n );\n },\n\n async setActiveVersion(params: SetActiveVersionParams): Promise<void> {\n await runSchemaWriteTransaction((target) =>\n target.setActiveVersion(params),\n );\n },\n\n async transaction<T>(\n fn: (tx: TransactionBackend, sql: AdoptedTransaction) => Promise<T>,\n _options?: TransactionOptions,\n ): Promise<T> {\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"This SQLite backend does not support atomic transactions. \" +\n \"Operations within a transaction are not rolled back on failure. \" +\n \"Use backend.capabilities.transactions to check for transaction support, \" +\n \"or use individual operations with manual error handling.\",\n );\n }\n\n // #134/#135: NO DDL or ensure here. The tx-scoped backend\n // exposes raw fulltext methods without self-ensure wrappers; the\n // single gate is `Store.transaction()`, which asserts the durable\n // contribution marker (one cached SELECT) before this method is\n // reached. The caller's BEGIN never carries CREATE statements.\n if (transactionMode === \"sql\") {\n return runWithSerializedQueue(serializedQueue, async () => {\n // Not `bindTransactionBackend(...)`: this path frames the tx\n // with manual BEGIN/COMMIT on the *outer* `db`, so it must\n // reuse that connection's already-built `executionAdapter`\n // rather than synthesize a fresh one for a distinct handle.\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isSync: true },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n vectorSlotLatch,\n });\n db.run(sql`BEGIN`);\n\n try {\n const result = await fn(\n gateFulltext(\n txBackend,\n contributionMaterializer.assertInitialized,\n ),\n db,\n );\n db.run(sql`COMMIT`);\n return result;\n } catch (error) {\n db.run(sql`ROLLBACK`);\n throw error;\n }\n });\n }\n\n if (transactionMode === \"do-sqlite\") {\n return runDoSqliteStorageTransaction(async () =>\n fn(bindTransactionBackend(db), db),\n );\n }\n\n // transactionMode === \"drizzle\"\n return runWithSerializedQueue(\n serializedQueue,\n async () =>\n db.transaction(async (tx) =>\n fn(bindTransactionBackend(tx), tx),\n ) as Promise<T>,\n );\n },\n\n adoptTransaction(externalTx: AdoptedTransaction): TransactionBackend {\n // #134: parity with Postgres. Cross-store atomicity needs real\n // rollback; on a \"none\" driver the caller's relational write\n // would commit with no way to undo the graph write. Refuse\n // loudly rather than silently degrade.\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"Cross-store atomicity is unavailable on this SQLite backend: \" +\n \"transactions are disabled (transactionMode: 'none'). Adopting \" +\n \"an external transaction here would let the caller's relational \" +\n \"write commit with no way to roll back the graph write. \" +\n \"Configure a driver that supports transactions (better-sqlite3, \" +\n \"libsql, bun:sqlite).\",\n );\n }\n assertAdoptedDialect<AnySqliteDatabase>(\n externalTx,\n BaseSQLiteDatabase,\n \"sqlite\",\n );\n // serializedQueue is deliberately NOT applied to an adopted tx: a\n // sync better-sqlite3 driver runs the adopted statements on the\n // caller's stack, so wrapping a caller-driven tx in our queue\n // could deadlock against the caller's outer `db.transaction(...)`.\n return bindTransactionBackend(externalTx);\n },\n\n close(): Promise<void> {\n serializedQueue?.dispose();\n return Promise.resolve();\n },\n };\n\n return backend;\n}\n\nfunction createTransactionBackend(\n options: CreateSqliteTransactionBackendOptions,\n): InternalOperationBackend {\n const txExecutionAdapter =\n options.executionAdapter ??\n createSqliteExecutionAdapter(options.db, {\n profileHints: options.profileHints,\n });\n\n // A transaction-scoped backend gets its OWN per-field ensure-latch, never\n // the outer process-global one. A `CREATE TABLE/INDEX` that runs inside the\n // caller's transaction and then rolls back must not leave the shared latch\n // marking the slot \"ensured\" — that would skip the re-CREATE and make every\n // later write fail with \"no such table\". The fresh latch is discarded with\n // the transaction, so the next write re-ensures idempotently.\n return createSqliteOperationBackend({\n capabilities: options.capabilities,\n db: options.db,\n executionAdapter: txExecutionAdapter,\n operationStrategy: options.operationStrategy,\n tableNames: options.tableNames,\n fulltextStrategy: options.fulltextStrategy,\n vectorStrategy: options.vectorStrategy,\n ...(options.vectorStrategy === undefined\n ? {}\n : { vectorSlotLatch: createVectorSlotLatch() }),\n });\n}\n\n// Re-export schema utilities\nexport type { SqliteTableNames, SqliteTables } from \"./schema/sqlite\";\nexport { createSqliteTables, tables } from \"./schema/sqlite\";\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/system-fields.ts","../src/indexes/define-index.ts"],"names":["createSchemaIntrospector","jsonPointer","normalizeJsonPointer","parseJsonPointer","resolveFieldTypeInfoAtJsonPointer","fnv1aBase36","MAX_PG_IDENTIFIER_LENGTH","TRUNCATED_IDENTIFIER_MAX_LENGTH","IDENTIFIER_COMPONENT_MAX_LENGTH"],"mappings":";;;;;;;;AAAO,IAAM,cAAA,GAAiB;AAAA,EAC5B,SAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA;AACF;AAEO,IAAM,cAAA,GAAiB;AAAA,EAC5B,WAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA;AACF;;;ACmCO,SAAS,eAAA,CACd,MACA,MAAA,EACsB;AACtB,EAAA,MAAM,KAAA,GAAQ,OAAO,KAAA,IAAS,cAAA;AAC9B,EAAA,MAAM,MAAA,GAAS,OAAO,MAAA,IAAU,KAAA;AAEhC,EAAA,MAAM,kBAAA,GAAqBA,0CAAA;AAAA,oBACzB,IAAI,GAAA,CAAI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\"validTo\",\n \"createdAt\",\n \"updatedAt\",\n \"deletedAt\",\n] as const;\n\nexport const EDGE_META_KEYS = [\n \"validFrom\",\n \"validTo\",\n \"createdAt\",\n \"updatedAt\",\n \"deletedAt\",\n] as const;\n","import { type z } from \"zod\";\n\nimport {\n IDENTIFIER_COMPONENT_MAX_LENGTH,\n MAX_PG_IDENTIFIER_LENGTH,\n TRUNCATED_IDENTIFIER_MAX_LENGTH,\n} from \"../constants\";\nimport {\n type AnyEdgeType,\n type KindEntity,\n type NodeType,\n} from \"../core/types\";\nimport { type ValueType } from \"../query/ast\";\nimport { resolveFieldTypeInfoAtJsonPointer } from \"../query/field-type-info\";\nimport {\n type JsonPointer,\n jsonPointer,\n type JsonPointerInput,\n type JsonPointerSegment,\n normalizeJsonPointer,\n parseJsonPointer,\n} from \"../query/json-pointer\";\nimport {\n createSchemaIntrospector,\n type FieldTypeInfo,\n} from \"../query/schema-introspector\";\nimport { EDGE_META_KEYS, NODE_META_KEYS } from \"../system-fields\";\nimport { fnv1aBase36 } from \"../utils/hash\";\nimport {\n type EdgeIndexConfig,\n type EdgeIndexDeclaration,\n type EdgeIndexDirection,\n type EdgeIndexWhereBuilder,\n type IndexFieldInput,\n type IndexScope,\n type IndexWhereExpression,\n type IndexWhereFieldBuilder,\n type IndexWhereLiteral,\n type IndexWhereOp,\n type IndexWhereOperand,\n type NodeIndexConfig,\n type NodeIndexDeclaration,\n type NodeIndexWhereBuilder,\n type SystemColumnName,\n} from \"./types\";\n\n// ============================================================\n// Public API\n// ============================================================\n\nexport function defineNodeIndex<N extends NodeType>(\n node: N,\n config: NodeIndexConfig<N>,\n): NodeIndexDeclaration {\n const scope = config.scope ?? \"graphAndKind\";\n const unique = config.unique ?? false;\n\n const schemaIntrospector = createSchemaIntrospector(\n new Map([[node.kind, { schema: node.schema }]]),\n );\n\n const { pointers: fields, valueTypes: fieldValueTypes } =\n normalizeNodeIndexFieldsOrThrow(\n node,\n config.fields,\n schemaIntrospector,\n \"fields\",\n { allowEmpty: false },\n );\n\n const { pointers: coveringFields, valueTypes: coveringFieldValueTypes } =\n normalizeNodeIndexFieldsOrThrow(\n node,\n config.coveringFields ?? [],\n schemaIntrospector,\n \"coveringFields\",\n { allowEmpty: true },\n );\n assertNoOverlap(fields, coveringFields, \"fields\", \"coveringFields\");\n\n const where = normalizeWhereInput(config.where, () =>\n createNodeWhereBuilder(node, schemaIntrospector),\n );\n\n const name =\n config.name ??\n generateDefaultIndexName({\n kind: \"node\",\n kindName: node.kind,\n unique,\n scope,\n direction: \"none\",\n fields,\n coveringFields,\n });\n\n // `origin` is intentionally omitted: `\"compile-time\"` is the default\n // and is canonicalized by absence so the serialized form stays\n // byte-identical for legacy graphs.\n return {\n entity: \"node\",\n kind: node.kind,\n name,\n fields,\n fieldValueTypes,\n coveringFields,\n coveringFieldValueTypes,\n unique,\n scope,\n where,\n };\n}\n\nexport function defineEdgeIndex<E extends AnyEdgeType>(\n edge: E,\n config: EdgeIndexConfig<E>,\n): EdgeIndexDeclaration {\n const scope = config.scope ?? \"graphAndKind\";\n const unique = config.unique ?? false;\n const direction = config.direction ?? \"none\";\n\n const schemaIntrospector = createSchemaIntrospector(\n new Map(),\n new Map([[edge.kind, { schema: edge.schema }]]),\n );\n\n const { pointers: fields, valueTypes: fieldValueTypes } =\n normalizeEdgeIndexFieldsOrThrow(\n edge,\n config.fields,\n schemaIntrospector,\n \"fields\",\n { allowEmpty: false },\n );\n\n const { pointers: coveringFields, valueTypes: coveringFieldValueTypes } =\n normalizeEdgeIndexFieldsOrThrow(\n edge,\n config.coveringFields ?? [],\n schemaIntrospector,\n \"coveringFields\",\n { allowEmpty: true },\n );\n assertNoOverlap(fields, coveringFields, \"fields\", \"coveringFields\");\n\n const where = normalizeWhereInput(config.where, () =>\n createEdgeWhereBuilder(edge, schemaIntrospector),\n );\n\n const name =\n config.name ??\n generateDefaultIndexName({\n kind: \"edge\",\n kindName: edge.kind,\n unique,\n scope,\n direction,\n fields,\n coveringFields,\n });\n\n return {\n entity: \"edge\",\n kind: edge.kind,\n name,\n fields,\n fieldValueTypes,\n coveringFields,\n coveringFieldValueTypes,\n unique,\n scope,\n direction,\n where,\n };\n}\n\n// ============================================================\n// WHERE Builder\n// ============================================================\n\n/**\n * The WHERE builder currently only supports top-level fields.\n * Nested field access (e.g., `where.metadata.priority.gt(5)`) is not supported.\n * Use top-level field predicates like `where.status.eq(\"active\")`.\n *\n * For complex nested predicates, use `andWhere()`, `orWhere()`, and `notWhere()`\n * to compose multiple top-level conditions.\n */\n\nfunction normalizeWhereInput<Builder>(\n input:\n | ((where: Builder) => IndexWhereExpression)\n | IndexWhereExpression\n | undefined,\n createBuilder: () => Builder,\n): IndexWhereExpression | undefined {\n if (input === undefined) {\n return undefined;\n }\n\n if (typeof input === \"function\") {\n return input(createBuilder());\n }\n\n return input;\n}\n\ntype NodeShape = Readonly<Record<string, z.ZodType>>;\ntype EdgeShape = Readonly<Record<string, z.ZodType>>;\n\nfunction createNodeWhereBuilder<N extends NodeType>(\n node: N,\n schemaIntrospector: ReturnType<typeof createSchemaIntrospector>,\n): NodeIndexWhereBuilder<N> {\n const shape = getSchemaShape(node.schema);\n const system = createSystemColumnMapForNode();\n\n function getOperand(key: string): IndexWhereOperand {\n const systemColumn = system.get(key);\n if (systemColumn) {\n return {\n __type: \"index_operand_system\",\n column: systemColumn.column,\n valueType: systemColumn.valueType,\n };\n }\n\n if (!(key in shape)) {\n throw new Error(\n `Unknown field \"${key}\" in node index WHERE clause for \"${node.kind}\"`,\n );\n }\n\n const info = schemaIntrospector.getFieldTypeInfo(node.kind, key);\n const valueType = info?.valueType;\n\n return {\n __type: \"index_operand_prop\",\n field: key,\n valueType,\n };\n }\n\n return createWhereProxy<NodeIndexWhereBuilder<N>>((key) => getOperand(key));\n}\n\nfunction createEdgeWhereBuilder<E extends AnyEdgeType>(\n edge: E,\n schemaIntrospector: ReturnType<typeof createSchemaIntrospector>,\n): EdgeIndexWhereBuilder<E> {\n const shape = getSchemaShape(edge.schema);\n const system = createSystemColumnMapForEdge();\n\n function getOperand(key: string): IndexWhereOperand {\n const systemColumn = system.get(key);\n if (systemColumn) {\n return {\n __type: \"index_operand_system\",\n column: systemColumn.column,\n valueType: systemColumn.valueType,\n };\n }\n\n if (!(key in shape)) {\n throw new Error(\n `Unknown field \"${key}\" in edge index WHERE clause for \"${edge.kind}\"`,\n );\n }\n\n const info = schemaIntrospector.getEdgeFieldTypeInfo(edge.kind, key);\n const valueType = info?.valueType;\n\n return {\n __type: \"index_operand_prop\",\n field: key,\n valueType,\n };\n }\n\n return createWhereProxy<EdgeIndexWhereBuilder<E>>((key) => getOperand(key));\n}\n\nfunction createWhereProxy<TBuilder extends object>(\n getOperand: (key: string) => IndexWhereOperand,\n): TBuilder {\n return new Proxy(Object.create(null) as TBuilder, {\n get: (_target, property: string | symbol) => {\n if (typeof property !== \"string\") return;\n if (property === \"then\") return;\n if (property === \"toJSON\") return;\n\n const operand = getOperand(property);\n return createIndexWhereFieldBuilder(operand);\n },\n });\n}\n\nfunction createIndexWhereFieldBuilder<T>(\n operand: IndexWhereOperand,\n): IndexWhereFieldBuilder<T> {\n function isNull(): IndexWhereExpression {\n return { __type: \"index_where_null_check\", operand, op: \"isNull\" };\n }\n\n function isNotNull(): IndexWhereExpression {\n return { __type: \"index_where_null_check\", operand, op: \"isNotNull\" };\n }\n\n function comparison(op: IndexWhereOp, value: unknown): IndexWhereExpression {\n return {\n __type: \"index_where_comparison\",\n left: operand,\n op,\n right: toLiteralOrThrow(value, operand.valueType),\n };\n }\n\n function listComparison(\n op: IndexWhereOp,\n values: readonly unknown[],\n ): IndexWhereExpression {\n const literals = values.map((value) =>\n toLiteralOrThrow(value, operand.valueType),\n );\n return {\n __type: \"index_where_comparison\",\n left: operand,\n op,\n right: literals,\n };\n }\n\n return {\n eq: (value) => comparison(\"eq\", value),\n neq: (value) => comparison(\"neq\", value),\n gt: (value) => comparison(\"gt\", value),\n gte: (value) => comparison(\"gte\", value),\n lt: (value) => comparison(\"lt\", value),\n lte: (value) => comparison(\"lte\", value),\n in: (values) => listComparison(\"in\", values),\n notIn: (values) => listComparison(\"notIn\", values),\n isNull,\n isNotNull,\n };\n}\n\nfunction toLiteralOrThrow(\n value: unknown,\n preferredType: ValueType | undefined,\n): IndexWhereLiteral {\n if (value instanceof Date) {\n return {\n __type: \"index_where_literal\",\n value: value.toISOString(),\n valueType: \"date\",\n };\n }\n\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n const valueType = inferValueType(value, preferredType);\n return { __type: \"index_where_literal\", value, valueType };\n }\n\n throw new Error(\n `Unsupported literal value type in index WHERE clause: ${String(value)}`,\n );\n}\n\nfunction inferValueType(\n value: string | number | boolean,\n preferredType: ValueType | undefined,\n): ValueType {\n if (preferredType === \"date\" && typeof value === \"string\") {\n return \"date\";\n }\n if (preferredType === \"number\" && typeof value === \"string\") {\n return \"number\";\n }\n if (preferredType === \"boolean\" && typeof value === \"string\") {\n return \"boolean\";\n }\n\n if (typeof value === \"string\") return \"string\";\n if (typeof value === \"number\") return \"number\";\n return \"boolean\";\n}\n\nfunction toSystemColumnName(metaKey: string): SystemColumnName {\n const snake = metaKey.replaceAll(/([A-Z])/g, \"_$1\").toLowerCase();\n\n switch (snake) {\n case \"deleted_at\":\n case \"valid_from\":\n case \"valid_to\":\n case \"created_at\":\n case \"updated_at\": {\n return snake;\n }\n default: {\n throw new Error(`Unsupported system meta key: ${metaKey}`);\n }\n }\n}\n\nfunction createSystemColumnMapForNode(): Map<\n string,\n Readonly<{ column: SystemColumnName; valueType: ValueType | undefined }>\n> {\n const entries: (readonly [\n string,\n Readonly<{ column: SystemColumnName; valueType: ValueType | undefined }>,\n ])[] = [\n [\"graphId\", { column: \"graph_id\", valueType: \"string\" }],\n [\"kind\", { column: \"kind\", valueType: \"string\" }],\n [\"id\", { column: \"id\", valueType: \"string\" }],\n ];\n\n for (const key of NODE_META_KEYS) {\n if (key === \"version\") {\n entries.push([key, { column: \"version\", valueType: \"number\" }]);\n continue;\n }\n entries.push([key, { column: toSystemColumnName(key), valueType: \"date\" }]);\n }\n\n return new Map(entries);\n}\n\nfunction createSystemColumnMapForEdge(): Map<\n string,\n Readonly<{ column: SystemColumnName; valueType: ValueType | undefined }>\n> {\n const entries: (readonly [\n string,\n Readonly<{ column: SystemColumnName; valueType: ValueType | undefined }>,\n ])[] = [\n [\"graphId\", { column: \"graph_id\", valueType: \"string\" }],\n [\"kind\", { column: \"kind\", valueType: \"string\" }],\n [\"id\", { column: \"id\", valueType: \"string\" }],\n [\"fromKind\", { column: \"from_kind\", valueType: \"string\" }],\n [\"fromId\", { column: \"from_id\", valueType: \"string\" }],\n [\"toKind\", { column: \"to_kind\", valueType: \"string\" }],\n [\"toId\", { column: \"to_id\", valueType: \"string\" }],\n ];\n\n for (const key of EDGE_META_KEYS) {\n entries.push([key, { column: toSystemColumnName(key), valueType: \"date\" }]);\n }\n\n return new Map(entries);\n}\n\nfunction getSchemaShape(schema: z.ZodType): NodeShape | EdgeShape {\n if (schema.type !== \"object\") {\n throw new Error(\"Index definitions require an object schema\");\n }\n\n const def = schema.def as { shape?: Record<string, z.ZodType> };\n const shape = def.shape;\n if (!shape) {\n throw new Error(\"Index definitions require a resolvable object shape\");\n }\n\n return shape;\n}\n\n// ============================================================\n// Validation\n// ============================================================\n\nfunction assertNonEmpty(values: readonly unknown[], label: string): void {\n if (values.length === 0) {\n throw new Error(`Index ${label} must not be empty`);\n }\n}\n\nfunction assertUnique(values: readonly string[], label: string): void {\n const set = new Set<string>();\n for (const value of values) {\n if (set.has(value)) {\n throw new Error(`Index ${label} contains duplicate value: ${value}`);\n }\n set.add(value);\n }\n}\n\nfunction assertNoOverlap(\n a: readonly string[],\n b: readonly string[],\n aLabel: string,\n bLabel: string,\n): void {\n const set = new Set(a);\n for (const value of b) {\n if (set.has(value)) {\n throw new Error(`Index ${bLabel} must not overlap ${aLabel}: ${value}`);\n }\n }\n}\n\nfunction assertIndexableValueType(valueType: ValueType, context: string): void {\n if (valueType === \"embedding\") {\n throw new Error(\n `Cannot create props index for embedding field (${context}); embedding() fields are indexed automatically in the vector strategy's per-(kind, field) storage`,\n );\n }\n\n if (valueType === \"array\" || valueType === \"object\") {\n throw new Error(\n `Cannot create btree props index for ${valueType} field (${context}); use a GIN/JSON index strategy instead`,\n );\n }\n}\n\ntype NormalizedIndexFields = Readonly<{\n pointers: readonly JsonPointer[];\n valueTypes: readonly (ValueType | undefined)[];\n}>;\n\nfunction normalizeNodeIndexFieldsOrThrow<N extends NodeType>(\n node: N,\n inputs: readonly IndexFieldInput<z.infer<N[\"schema\"]>>[],\n schemaIntrospector: ReturnType<typeof createSchemaIntrospector>,\n label: string,\n options: Readonly<{ allowEmpty: boolean }>,\n): NormalizedIndexFields {\n if (inputs.length === 0 && options.allowEmpty) {\n return { pointers: [], valueTypes: [] };\n }\n assertNonEmpty(inputs, label);\n\n const pointers: JsonPointer[] = [];\n const valueTypes: (ValueType | undefined)[] = [];\n\n for (const input of inputs) {\n const pointer = normalizeIndexFieldPointer(input);\n const info = resolveNodeFieldTypeInfoOrThrow(\n node.kind,\n pointer,\n schemaIntrospector,\n );\n assertIndexableValueType(info.valueType, `node \"${node.kind}\" ${pointer}`);\n pointers.push(pointer);\n valueTypes.push(info.valueType);\n }\n\n assertUnique(pointers, label);\n\n return { pointers, valueTypes };\n}\n\nfunction normalizeEdgeIndexFieldsOrThrow<E extends AnyEdgeType>(\n edge: E,\n inputs: readonly IndexFieldInput<z.infer<E[\"schema\"]>>[],\n schemaIntrospector: ReturnType<typeof createSchemaIntrospector>,\n label: string,\n options: Readonly<{ allowEmpty: boolean }>,\n): NormalizedIndexFields {\n if (inputs.length === 0 && options.allowEmpty) {\n return { pointers: [], valueTypes: [] };\n }\n assertNonEmpty(inputs, label);\n\n const pointers: JsonPointer[] = [];\n const valueTypes: (ValueType | undefined)[] = [];\n\n for (const input of inputs) {\n const pointer = normalizeIndexFieldPointer(input);\n const info = resolveEdgeFieldTypeInfoOrThrow(\n edge.kind,\n pointer,\n schemaIntrospector,\n );\n assertIndexableValueType(info.valueType, `edge \"${edge.kind}\" ${pointer}`);\n pointers.push(pointer);\n valueTypes.push(info.valueType);\n }\n\n assertUnique(pointers, label);\n\n return { pointers, valueTypes };\n}\n\nfunction normalizeIndexFieldPointer<T>(input: IndexFieldInput<T>): JsonPointer {\n if (Array.isArray(input)) {\n if (input.length === 0) {\n throw new Error(\"Index field JSON pointer must not be empty\");\n }\n return jsonPointer(input as readonly JsonPointerSegment[]);\n }\n\n if (typeof input === \"string\") {\n if (input.startsWith(\"/\")) {\n const pointer = normalizeJsonPointer(\n input as JsonPointerInput<Record<string, unknown>>,\n );\n if (pointer === \"\") {\n throw new Error(\"Index field JSON pointer must not be empty\");\n }\n return pointer;\n }\n return jsonPointer([input]);\n }\n\n throw new Error(`Unsupported index field input: ${String(input)}`);\n}\n\nfunction resolveNodeFieldTypeInfoOrThrow(\n nodeKind: string,\n pointer: JsonPointer,\n schemaIntrospector: ReturnType<typeof createSchemaIntrospector>,\n): FieldTypeInfo {\n const segments = parseJsonPointer(pointer);\n const [first, ...rest] = segments;\n if (!first) {\n throw new Error(\"Index field JSON pointer must not be empty\");\n }\n\n const rootInfo = schemaIntrospector.getFieldTypeInfo(nodeKind, first);\n if (!rootInfo) {\n throw new Error(\n `Unknown field \"${first}\" for node \"${nodeKind}\" in index definition`,\n );\n }\n\n if (rest.length === 0) {\n return rootInfo;\n }\n\n const resolved = resolveFieldTypeInfoAtJsonPointer(\n rootInfo,\n jsonPointer(rest),\n );\n if (!resolved) {\n throw new Error(\n `Unknown JSON pointer \"${pointer}\" for node \"${nodeKind}\" in index definition`,\n );\n }\n\n return resolved;\n}\n\nfunction resolveEdgeFieldTypeInfoOrThrow(\n edgeKind: string,\n pointer: JsonPointer,\n schemaIntrospector: ReturnType<typeof createSchemaIntrospector>,\n): FieldTypeInfo {\n const segments = parseJsonPointer(pointer);\n const [first, ...rest] = segments;\n if (!first) {\n throw new Error(\"Index field JSON pointer must not be empty\");\n }\n\n const rootInfo = schemaIntrospector.getEdgeFieldTypeInfo(edgeKind, first);\n if (!rootInfo) {\n throw new Error(\n `Unknown field \"${first}\" for edge \"${edgeKind}\" in index definition`,\n );\n }\n\n if (rest.length === 0) {\n return rootInfo;\n }\n\n const resolved = resolveFieldTypeInfoAtJsonPointer(\n rootInfo,\n jsonPointer(rest),\n );\n if (!resolved) {\n throw new Error(\n `Unknown JSON pointer \"${pointer}\" for edge \"${edgeKind}\" in index definition`,\n );\n }\n\n return resolved;\n}\n\n// ============================================================\n// Default Name Generation\n// ============================================================\n\ntype DefaultNameParts = Readonly<{\n kind: KindEntity;\n kindName: string;\n unique: boolean;\n scope: IndexScope;\n direction: EdgeIndexDirection;\n fields: readonly string[];\n coveringFields: readonly string[];\n}>;\n\nfunction generateDefaultIndexName(parts: DefaultNameParts): string {\n const hash = fnv1aBase36(\n JSON.stringify({\n kind: parts.kind,\n kindName: parts.kindName,\n unique: parts.unique,\n scope: parts.scope,\n direction: parts.direction,\n fields: parts.fields,\n covering: parts.coveringFields,\n }),\n );\n\n const nameParts = [\n \"idx\",\n \"tg\",\n parts.kind,\n sanitizeIdentifierComponent(parts.kindName),\n sanitizeIdentifierComponent(parts.fields.join(\"_\")),\n parts.coveringFields.length > 0 ?\n `cov_${sanitizeIdentifierComponent(parts.coveringFields.join(\"_\"))}`\n : undefined,\n parts.direction === \"none\" ? undefined : parts.direction,\n parts.unique ? \"uniq\" : undefined,\n parts.scope === \"graphAndKind\" ?\n undefined\n : sanitizeIdentifierComponent(parts.scope),\n hash,\n ].filter((part) => part !== undefined);\n\n const joined = nameParts.join(\"_\");\n return joined.length <= MAX_PG_IDENTIFIER_LENGTH ?\n joined\n : `${joined.slice(0, TRUNCATED_IDENTIFIER_MAX_LENGTH)}_${hash}`;\n}\n\nfunction sanitizeIdentifierComponent(value: string): string {\n return value\n .toLowerCase()\n .replaceAll(/[^a-z0-9_]+/g, \"_\")\n .replaceAll(/^_+|_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GAAY,MAAA,GAC7B,sBAAA,CAAuB,SAAS,CAAA;AAEtC;AAEA,SAAS,4BACP,MAAA,EACoC;AACpC,EAAA,MAAM,MAAA,GAAS,kBAAkB,MAAM,CAAA;AACvC,EAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;AACjC,EAAA,MAAM,SAAA,GAAY,kBAAkB,MAAM,CAAA;AAC1C,EAAA,OAAO,SAAA,KAAc,MAAA,GAAY,MAAA,GAAY,iBAAA,CAAkB,SAAS,CAAA;AAC1E;AAOA,SAAS,kBAAkB,MAAA,EAA0C;AACnE,EAAA,MAAM,OAAO,MAAA,CAAO,IAAA;AACpB,EAAA,MAAM,SAAA,GAAa,OAAO,GAAA,CAAkC,SAAA;AAC5D,EAAA,IAAA,CACG,IAAA,KAAS,cACR,IAAA,KAAS,UAAA,IACT,SAAS,SAAA,IACT,IAAA,KAAS,eACX,SAAA,EACA;AACA,IAAA,IAAI,iBAAA,CAAkB,SAAS,CAAA,EAAG,OAAO,SAAA;AACzC,IAAA,OAAO,kBAAkB,SAAS,CAAA;AAAA,EACpC;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-454I6GDF.js","sourcesContent":["/**\n * Embedding type for vector search.\n *\n * Creates a Zod-compatible schema for vector embeddings with\n * dimension validation and metadata for query compilation.\n */\nimport { z } from \"zod\";\n\n// ============================================================\n// Embedding Brand Symbol\n// ============================================================\n\n/**\n * Symbol used to brand embedding values at the type level.\n * This allows TypeScript to distinguish embedding arrays from regular\n * number arrays in the query builder type system.\n */\ndeclare const EMBEDDING_BRAND: unique symbol;\n\n/**\n * Branded embedding type for type-level distinction.\n * At runtime this is just `readonly number[]`, but TypeScript can\n * distinguish it from regular arrays for query builder typing.\n */\nexport type EmbeddingValue = readonly number[] & {\n readonly [EMBEDDING_BRAND]: true;\n};\n\n// ============================================================\n// Embedding Metadata Symbol\n// ============================================================\n\n/**\n * Symbol key for storing embedding dimensions on the schema.\n * This allows the schema introspector to detect embedding types\n * and extract dimension information.\n */\nexport const EMBEDDING_DIMENSIONS_KEY = \"_embeddingDimensions\" as const;\n\n/**\n * Symbol key for storing the embedding's preferred index configuration\n * on the schema. The schema introspector reads this when auto-deriving\n * `VectorIndexDeclaration` entries at `defineGraph()` time.\n */\nexport const EMBEDDING_INDEX_KEY = \"_embeddingIndex\" as const;\n\n/**\n * Distance metric used for vector similarity. Pinned at the embedding\n * brand because changing the metric usually means generating different\n * model output (e.g. cosine-normalized vs. raw inner-product), and the\n * stored index needs the same metric to score correctly.\n *\n * - `cosine`: cosine similarity. The default — works for most\n * sentence-transformer / OpenAI-style embeddings that are already\n * length-normalized.\n * - `l2`: Euclidean distance. Use when your model outputs vectors\n * trained for L2 (e.g. some image embedding models).\n * - `inner_product`: dot-product distance. Use when your model outputs\n * pre-normalized vectors AND you want to skip the cosine\n * normalization step at query time.\n */\nexport type EmbeddingMetric = \"cosine\" | \"l2\" | \"inner_product\";\n\n/**\n * Vector index implementation. `hnsw` is the default and what pgvector\n * recommends for most workloads. `ivfflat` is the alternative for\n * larger datasets where memory is the bottleneck. `none` disables\n * automatic index creation for this embedding (the operator can still\n * call `backend.createVectorIndex` manually).\n */\nexport type EmbeddingIndexType = \"hnsw\" | \"ivfflat\" | \"none\";\n\n/**\n * Per-embedding configuration for the auto-derived\n * `VectorIndexDeclaration`. All fields are optional with sensible\n * defaults (`cosine` / `hnsw` / pgvector defaults: `m=16`,\n * `ef_construction=64`). Override only when your model or dataset has\n * a known reason to.\n */\nexport type EmbeddingIndexOptions = Readonly<{\n /** Distance metric. Default `\"cosine\"`. */\n metric?: EmbeddingMetric;\n /** Vector index implementation. Default `\"hnsw\"`. */\n indexType?: EmbeddingIndexType;\n /** HNSW `m` parameter — max connections per layer. Default `16`. */\n m?: number;\n /** HNSW `ef_construction` parameter — build-time search depth. Default `64`. */\n efConstruction?: number;\n /** IVFFlat `lists` parameter — number of inverted-list partitions. */\n lists?: number;\n}>;\n\n/**\n * Resolved embedding index configuration with all defaults applied.\n * What gets attached to the brand and read by the auto-derivation pass.\n */\nexport type ResolvedEmbeddingIndex = Readonly<{\n metric: EmbeddingMetric;\n indexType: EmbeddingIndexType;\n m: number;\n efConstruction: number;\n lists: number | undefined;\n}>;\n\nconst DEFAULT_HNSW_M = 16;\nconst DEFAULT_HNSW_EF_CONSTRUCTION = 64;\n\n// ============================================================\n// Embedding Schema Type\n// ============================================================\n\n/**\n * A Zod schema for vector embeddings with attached dimension metadata.\n * Uses the branded EmbeddingValue type for type-level distinction.\n */\nexport type EmbeddingSchema<D extends number = number> =\n z.ZodType<EmbeddingValue> &\n Readonly<{\n [EMBEDDING_DIMENSIONS_KEY]: D;\n [EMBEDDING_INDEX_KEY]: ResolvedEmbeddingIndex;\n }>;\n\n// ============================================================\n// Embedding Factory\n// ============================================================\n\n/**\n * Creates a Zod schema for vector embeddings.\n *\n * The dimension is validated at runtime and attached as metadata\n * for the schema introspector and query compiler.\n *\n * @param dimensions - The number of dimensions (e.g., 384, 512, 768, 1536, 3072)\n * @returns A Zod schema that validates embedding arrays\n *\n * @example\n * ```typescript\n * // OpenAI ada-002 embeddings\n * const Document = defineNode(\"Document\", {\n * schema: z.object({\n * title: z.string(),\n * embedding: embedding(1536),\n * }),\n * });\n *\n * // Sentence transformers\n * const Sentence = defineNode(\"Sentence\", {\n * schema: z.object({\n * text: z.string(),\n * embedding: embedding(384), // all-MiniLM-L6-v2\n * }),\n * });\n *\n * // Optional embeddings are supported\n * const Article = defineNode(\"Article\", {\n * schema: z.object({\n * content: z.string(),\n * embedding: embedding(1536).optional(),\n * }),\n * });\n * ```\n */\nexport function embedding<D extends number>(\n dimensions: D,\n options: EmbeddingIndexOptions = {},\n): EmbeddingSchema<D> {\n if (!Number.isInteger(dimensions) || dimensions <= 0) {\n throw new Error(\n `Embedding dimensions must be a positive integer, got: ${dimensions}`,\n );\n }\n\n const indexConfig = resolveEmbeddingIndex(options);\n\n // Use EmbeddingValue as the output type for proper type branding.\n // At runtime, validation accepts any number array with correct dimensions.\n const schema = z.custom<EmbeddingValue>(\n (value): value is EmbeddingValue => {\n if (!Array.isArray(value)) {\n return false;\n }\n if (value.length !== dimensions) {\n return false;\n }\n return value.every((n) => typeof n === \"number\" && Number.isFinite(n));\n },\n {\n message: `Expected an array of ${dimensions} finite numbers`,\n },\n );\n\n return Object.assign(schema, {\n [EMBEDDING_DIMENSIONS_KEY]: dimensions,\n [EMBEDDING_INDEX_KEY]: indexConfig,\n });\n}\n\nfunction resolveEmbeddingIndex(\n options: EmbeddingIndexOptions,\n): ResolvedEmbeddingIndex {\n const indexType = options.indexType ?? DEFAULT_EMBEDDING_INDEX_TYPE;\n const m = options.m ?? DEFAULT_HNSW_M;\n const efConstruction = options.efConstruction ?? DEFAULT_HNSW_EF_CONSTRUCTION;\n\n if (m <= 0 || !Number.isInteger(m)) {\n throw new Error(\n `embedding() index option 'm' must be a positive integer, got: ${m}`,\n );\n }\n if (efConstruction <= 0 || !Number.isInteger(efConstruction)) {\n throw new Error(\n `embedding() index option 'efConstruction' must be a positive integer, got: ${efConstruction}`,\n );\n }\n if (\n options.lists !== undefined &&\n (options.lists <= 0 || !Number.isInteger(options.lists))\n ) {\n throw new Error(\n `embedding() index option 'lists' must be a positive integer, got: ${options.lists}`,\n );\n }\n\n return Object.freeze({\n metric: options.metric ?? DEFAULT_EMBEDDING_METRIC,\n indexType,\n m,\n efConstruction,\n lists: options.lists,\n });\n}\n\n// ============================================================\n// Type Guards\n// ============================================================\n\n/**\n * Checks if a value is an embedding schema.\n */\nexport function isEmbeddingSchema(value: unknown): value is EmbeddingSchema {\n return (\n typeof value === \"object\" &&\n value !== null &&\n EMBEDDING_DIMENSIONS_KEY in value &&\n typeof (value as Record<string, unknown>)[EMBEDDING_DIMENSIONS_KEY] ===\n \"number\"\n );\n}\n\n/**\n * Gets the dimensions from an embedding schema.\n * Returns undefined if the schema is not an embedding schema.\n */\nexport function getEmbeddingDimensions(schema: z.ZodType): number | undefined {\n if (isEmbeddingSchema(schema)) {\n return schema[EMBEDDING_DIMENSIONS_KEY];\n }\n return undefined;\n}\n\n/**\n * Gets the resolved index configuration from an embedding schema.\n * Returns undefined if the schema is not an embedding schema. Used by\n * the auto-derivation pass at `defineGraph()` time to build vector\n * `IndexDeclaration` entries.\n */\nexport function getEmbeddingIndex(\n schema: z.ZodType,\n): ResolvedEmbeddingIndex | undefined {\n if (!isEmbeddingSchema(schema)) return undefined;\n const candidate = (schema as unknown as Record<string, unknown>)[\n EMBEDDING_INDEX_KEY\n ];\n if (candidate === undefined) return undefined;\n return candidate as ResolvedEmbeddingIndex;\n}\n\n// ============================================================\n// Embedding Field Resolution\n// ============================================================\n\n/**\n * One resolved embedding field on a node schema — its dot-path plus the\n * fixed `dimensions` and the resolved index `(metric, indexType)`.\n * Sourced from the field's `embedding()` brand, unwrapping `.optional()`\n * / `.nullable()` / `.default()` / `.readonly()` wrappers. The single\n * source of truth shared by embedding sync (write path), the query\n * compiler's `field.similarTo(...)` slot resolution, and search.\n */\nexport type ResolvedEmbeddingField = Readonly<{\n fieldPath: string;\n dimensions: number;\n metric: EmbeddingMetric;\n indexType: EmbeddingIndexType;\n}>;\n\n/**\n * The single source of truth for an embedding field's default metric / index\n * type when unspecified — used by `embedding()` declaration resolution, the\n * field-fallback below, and the legacy-migration slot defaults\n * (`migrate-vectors.ts`) so the three never drift.\n */\nexport const DEFAULT_EMBEDDING_METRIC: EmbeddingMetric = \"cosine\";\nexport const DEFAULT_EMBEDDING_INDEX_TYPE: EmbeddingIndexType = \"hnsw\";\n\n/**\n * Extracts every top-level embedding field from a node's object schema.\n * Returns `[]` for non-object schemas or schemas with no embedding\n * fields. Embeddings nested inside object properties are out of scope by\n * design (storage keys at the top-level `(kind, fieldPath)` grain).\n */\nexport function resolveEmbeddingFields(\n schema: z.ZodType,\n): readonly ResolvedEmbeddingField[] {\n if (schema.type !== \"object\") return [];\n const shape = (schema.def as { shape?: Record<string, z.ZodType> }).shape;\n if (!shape) return [];\n\n const fields: ResolvedEmbeddingField[] = [];\n for (const [fieldPath, fieldSchema] of Object.entries(shape)) {\n const dimensions = resolveEmbeddingDimensions(fieldSchema);\n if (dimensions === undefined) continue;\n const index = resolveEmbeddingIndexConfig(fieldSchema);\n fields.push({\n fieldPath,\n dimensions,\n metric: index?.metric ?? DEFAULT_EMBEDDING_METRIC,\n indexType: index?.indexType ?? DEFAULT_EMBEDDING_INDEX_TYPE,\n });\n }\n return fields;\n}\n\nfunction resolveEmbeddingDimensions(schema: z.ZodType): number | undefined {\n const direct = getEmbeddingDimensions(schema);\n if (direct !== undefined) return direct;\n const unwrapped = unwrapToEmbedding(schema);\n return unwrapped === undefined ? undefined : (\n getEmbeddingDimensions(unwrapped)\n );\n}\n\nfunction resolveEmbeddingIndexConfig(\n schema: z.ZodType,\n): ResolvedEmbeddingIndex | undefined {\n const direct = getEmbeddingIndex(schema);\n if (direct !== undefined) return direct;\n const unwrapped = unwrapToEmbedding(schema);\n return unwrapped === undefined ? undefined : getEmbeddingIndex(unwrapped);\n}\n\n/**\n * Unwraps optional / nullable / default / readonly wrappers to find the\n * inner embedding schema, recursing through chained wrappers. Returns\n * `undefined` when no embedding schema is reachable.\n */\nfunction unwrapToEmbedding(schema: z.ZodType): z.ZodType | undefined {\n const type = schema.type;\n const innerType = (schema.def as { innerType?: z.ZodType }).innerType;\n if (\n (type === \"optional\" ||\n type === \"nullable\" ||\n type === \"default\" ||\n type === \"readonly\") &&\n innerType\n ) {\n if (isEmbeddingSchema(innerType)) return innerType;\n return unwrapToEmbedding(innerType);\n }\n return undefined;\n}\n"]}