viborm 1.14.2 → 1.16.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 (483) hide show
  1. package/dist/adapter-namespace-DwFnfpED.mjs +2 -0
  2. package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +26 -10
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/args-7WgBFd_f.mjs +2 -0
  6. package/dist/{args-764KdWMr.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
  7. package/dist/array-literal-BOzj0E2u.mjs +2 -0
  8. package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
  9. package/dist/base-17NSFtrA.mjs +2 -0
  10. package/dist/base-17NSFtrA.mjs.map +1 -0
  11. package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
  12. package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
  13. package/dist/better-auth.d.mts +116 -0
  14. package/dist/better-auth.mjs +6 -0
  15. package/dist/better-auth.mjs.map +1 -0
  16. package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
  17. package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
  18. package/dist/bun-sql.d.mts +1 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sql.mjs.map +1 -1
  21. package/dist/bun-sqlite.d.mts +1 -1
  22. package/dist/bun-sqlite.mjs +1 -1
  23. package/dist/bun-sqlite.mjs.map +1 -1
  24. package/dist/cache/cloudflare-kv.d.mts +1 -1
  25. package/dist/cache/cloudflare-kv.mjs +1 -1
  26. package/dist/cache/cloudflare-kv.mjs.map +1 -1
  27. package/dist/cache/memory.d.mts +1 -1
  28. package/dist/cache/memory.mjs +1 -1
  29. package/dist/cache/memory.mjs.map +1 -1
  30. package/dist/cache.d.mts +2 -2
  31. package/dist/cache.mjs +1 -1
  32. package/dist/cache.mjs.map +1 -1
  33. package/dist/call-0bd_B9Vp.mjs +2 -0
  34. package/dist/{call-Cz8XUmrl.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
  35. package/dist/cli.mjs +6 -6
  36. package/dist/cli.mjs.map +1 -1
  37. package/dist/client-D7sWgUt2.mjs +2 -0
  38. package/dist/client-D7sWgUt2.mjs.map +1 -0
  39. package/dist/client-DEfFqv4S.mjs +9 -0
  40. package/dist/client-DEfFqv4S.mjs.map +1 -0
  41. package/dist/{client-CRxfhw2y.d.mts → client-Dlz3-2JC.d.mts} +3 -3
  42. package/dist/client.d.mts +3 -3
  43. package/dist/client.mjs +1 -1
  44. package/dist/client.mjs.map +1 -1
  45. package/dist/config.d.mts +2 -2
  46. package/dist/config.mjs +1 -1
  47. package/dist/confine-CyI9IwjC.mjs +2 -0
  48. package/dist/{confine-DqFBTUw6.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
  49. package/dist/coordination-BxMskOgi.mjs +2 -0
  50. package/dist/coordination-BxMskOgi.mjs.map +1 -0
  51. package/dist/d1.d.mts +2 -30
  52. package/dist/d1.mjs +1 -1
  53. package/dist/d1.mjs.map +1 -1
  54. package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-BMjJiBFm.d.mts} +8476 -8386
  55. package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
  56. package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
  57. package/dist/defaults-DAPb-tJ4.mjs +2 -0
  58. package/dist/{defaults-DwOHWI_M.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
  59. package/dist/{document-BVTQ-cF-.d.mts → document-CHaVF7Vn.d.mts} +36 -2
  60. package/dist/{driver-BBEmaJZy.d.mts → driver-BvTixv-m.d.mts} +1 -1
  61. package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
  62. package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
  63. package/dist/driver-kiIQS_Fd.mjs +2 -0
  64. package/dist/driver-kiIQS_Fd.mjs.map +1 -0
  65. package/dist/driver-lShUkDmf.mjs +2 -0
  66. package/dist/driver-lShUkDmf.mjs.map +1 -0
  67. package/dist/driver.d.mts +1 -1
  68. package/dist/driver.mjs +1 -1
  69. package/dist/durable-object.d.mts +1 -1
  70. package/dist/durable-object.mjs +2 -2
  71. package/dist/durable-object.mjs.map +1 -1
  72. package/dist/error-mapping-B9rSvgG9.mjs +2 -0
  73. package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
  74. package/dist/every-JpbiHdMb.mjs +2 -0
  75. package/dist/{every-tOgQmaIE.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
  76. package/dist/execution-context-couU2tgh.mjs +2 -0
  77. package/dist/execution-context-couU2tgh.mjs.map +1 -0
  78. package/dist/{exports-COCJ8f2f.d.mts → exports-DYnTfvQo.d.mts} +1 -1
  79. package/dist/extension-Dh1ddrlA.mjs +2 -0
  80. package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
  81. package/dist/fs-estate-n-QpsFqb.mjs +2 -0
  82. package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
  83. package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
  84. package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
  85. package/dist/id-domain-Cg65TLZ-.mjs +2 -0
  86. package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
  87. package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
  88. package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
  89. package/dist/identifiers-BxOf57qy.mjs +2 -0
  90. package/dist/identifiers-BxOf57qy.mjs.map +1 -0
  91. package/dist/identity-CJlRQA-m.mjs +2 -0
  92. package/dist/identity-CJlRQA-m.mjs.map +1 -0
  93. package/dist/index.d.mts +3 -3
  94. package/dist/index.mjs +1 -1
  95. package/dist/index.mjs.map +1 -1
  96. package/dist/instrumentation.d.mts +1 -1
  97. package/dist/instrumentation.mjs +1 -1
  98. package/dist/instrumentation.mjs.map +1 -1
  99. package/dist/introspect-q3Rf_Xv8.mjs +2 -0
  100. package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
  101. package/dist/json-CsAdz9pg.mjs +2 -0
  102. package/dist/json-CsAdz9pg.mjs.map +1 -0
  103. package/dist/json-number-C09rsm1g.mjs +2 -0
  104. package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
  105. package/dist/json-parameter-D7hDrVKw.mjs +2 -0
  106. package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
  107. package/dist/judge-words-k5GCc4cV.mjs +2 -0
  108. package/dist/judge-words-k5GCc4cV.mjs.map +1 -0
  109. package/dist/key-BDH6oTyC.mjs +2 -0
  110. package/dist/key-BDH6oTyC.mjs.map +1 -0
  111. package/dist/keys-CIal55WQ.mjs +2 -0
  112. package/dist/{keys-BQxM4c_a.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
  113. package/dist/keys-DZdKAd4n.mjs +2 -0
  114. package/dist/keys-DZdKAd4n.mjs.map +1 -0
  115. package/dist/libsql-DEZ0uhK2.mjs +3 -0
  116. package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
  117. package/dist/libsql.d.mts +2 -20
  118. package/dist/libsql.mjs +1 -1
  119. package/dist/libsql.mjs.map +1 -1
  120. package/dist/light-D2wNSbzY.mjs +2 -0
  121. package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
  122. package/dist/memory-BaGWNdvk.mjs +2 -0
  123. package/dist/{memory-G4cSuc6A.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
  124. package/dist/methods-part-BaNx3o7b.mjs +2 -0
  125. package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
  126. package/dist/migrations/mysql.d.mts +5 -5
  127. package/dist/migrations/mysql.mjs +1 -1
  128. package/dist/migrations/postgres.d.mts +5 -5
  129. package/dist/migrations/postgres.mjs +1 -1
  130. package/dist/migrations/snowflake.d.mts +5 -5
  131. package/dist/migrations/snowflake.mjs +1 -1
  132. package/dist/migrations/sqlite.d.mts +5 -5
  133. package/dist/migrations/sqlite.mjs +1 -1
  134. package/dist/migrations/storage/durable-object.d.mts +1 -1
  135. package/dist/migrations/storage/durable-object.mjs +1 -1
  136. package/dist/migrations/storage/durable-object.mjs.map +1 -1
  137. package/dist/migrations/storage/fs.d.mts +1 -1
  138. package/dist/migrations/storage/fs.mjs +1 -1
  139. package/dist/migrations/storage/r2.d.mts +1 -1
  140. package/dist/migrations/storage/r2.mjs +1 -1
  141. package/dist/migrations/storage/r2.mjs.map +1 -1
  142. package/dist/migrations/surrealdb.d.mts +5 -5
  143. package/dist/migrations/surrealdb.mjs +1 -1
  144. package/dist/migrations/tenant.d.mts +3 -3
  145. package/dist/migrations/tenant.mjs +1 -1
  146. package/dist/migrations/tenant.mjs.map +1 -1
  147. package/dist/migrations-DIUltjr3.mjs +2 -0
  148. package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
  149. package/dist/migrations.d.mts +5 -5
  150. package/dist/migrations.mjs +1 -1
  151. package/dist/model-Dtd37Sky.mjs +2 -0
  152. package/dist/model-Dtd37Sky.mjs.map +1 -0
  153. package/dist/mysql-BFPF8xyv.mjs +9 -0
  154. package/dist/mysql-BFPF8xyv.mjs.map +1 -0
  155. package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
  156. package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
  157. package/dist/mysql2.d.mts +2 -27
  158. package/dist/mysql2.mjs +1 -1
  159. package/dist/mysql2.mjs.map +1 -1
  160. package/dist/named-statements-CkOOD__I.mjs +2 -0
  161. package/dist/named-statements-CkOOD__I.mjs.map +1 -0
  162. package/dist/named-statements-NF7Iycjk.d.mts +13 -0
  163. package/dist/native-types-1ewJXVks.mjs +2 -0
  164. package/dist/native-types-1ewJXVks.mjs.map +1 -0
  165. package/dist/neon-http.d.mts +1 -1
  166. package/dist/neon-http.mjs +1 -1
  167. package/dist/neon-http.mjs.map +1 -1
  168. package/dist/normalized-result-D7nVkF36.mjs +2 -0
  169. package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
  170. package/dist/{object-store-B_YMoW8u.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
  171. package/dist/object-store-Chq1PMYz.mjs +2 -0
  172. package/dist/object-store-Chq1PMYz.mjs.map +1 -0
  173. package/dist/on-ZkOVmE4-.mjs +2 -0
  174. package/dist/{on-ylYaKuRu.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
  175. package/dist/on.d.mts +1 -1
  176. package/dist/on.mjs +1 -1
  177. package/dist/on.mjs.map +1 -1
  178. package/dist/ordering/keys.mjs +1 -1
  179. package/dist/ordering.d.mts +9 -3
  180. package/dist/ordering.mjs +10 -10
  181. package/dist/ordering.mjs.map +1 -1
  182. package/dist/pending-operation-D4gUKMxD.mjs +2 -0
  183. package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
  184. package/dist/permissions.d.mts +1 -1
  185. package/dist/permissions.mjs +1 -1
  186. package/dist/permissions.mjs.map +1 -1
  187. package/dist/pg.d.mts +16 -99
  188. package/dist/pg.mjs +1 -1
  189. package/dist/pg.mjs.map +1 -1
  190. package/dist/pglite.d.mts +3 -1
  191. package/dist/pglite.mjs +1 -1
  192. package/dist/pglite.mjs.map +1 -1
  193. package/dist/physical-DO4PEYcc.mjs +2 -0
  194. package/dist/physical-DO4PEYcc.mjs.map +1 -0
  195. package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
  196. package/dist/pinned-session-Y7-2pRBJ.mjs.map +1 -0
  197. package/dist/planetscale.d.mts +1 -1
  198. package/dist/planetscale.mjs +1 -1
  199. package/dist/planetscale.mjs.map +1 -1
  200. package/dist/{planner-DHjdvjwk.d.mts → planner-C-zjj19U.d.mts} +123 -1
  201. package/dist/postgres-DQQE2ys_.mjs +34 -0
  202. package/dist/postgres-DQQE2ys_.mjs.map +1 -0
  203. package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
  204. package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
  205. package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
  206. package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
  207. package/dist/postgres-result-133boRW-.mjs +2 -0
  208. package/dist/postgres-result-133boRW-.mjs.map +1 -0
  209. package/dist/postgres.d.mts +27 -59
  210. package/dist/postgres.mjs +1 -1
  211. package/dist/postgres.mjs.map +1 -1
  212. package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
  213. package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
  214. package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
  215. package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
  216. package/dist/quantized-BKBs0joq.mjs +2 -0
  217. package/dist/quantized-BKBs0joq.mjs.map +1 -0
  218. package/dist/query-BTb6iakn.mjs +2 -0
  219. package/dist/query-BTb6iakn.mjs.map +1 -0
  220. package/dist/query-backend-TisPjCPF.mjs +2 -0
  221. package/dist/query-backend-TisPjCPF.mjs.map +1 -0
  222. package/dist/query-inspection-DwYBKSDG.mjs +2 -0
  223. package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
  224. package/dist/raw-DqEb71JZ.mjs +2 -0
  225. package/dist/raw-DqEb71JZ.mjs.map +1 -0
  226. package/dist/relation-bound-CSNKLyDy.mjs +2 -0
  227. package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
  228. package/dist/result-parsing-BbffueEX.mjs +2 -0
  229. package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
  230. package/dist/routed-operations-CcKOdn51.mjs +2 -0
  231. package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
  232. package/dist/rows-of-Bgl9GVtK.mjs +2 -0
  233. package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
  234. package/dist/rule-words-DMbQuvD2.mjs +2 -0
  235. package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
  236. package/dist/scalar-Dm9brvAU.mjs +4 -0
  237. package/dist/scalar-Dm9brvAU.mjs.map +1 -0
  238. package/dist/schema/introspect.d.mts +2 -2
  239. package/dist/schema/introspect.mjs +1 -1
  240. package/dist/schema/json.d.mts +6 -4
  241. package/dist/schema/json.mjs +1 -1
  242. package/dist/schema-DDkAUfOb.mjs +2 -0
  243. package/dist/schema-DDkAUfOb.mjs.map +1 -0
  244. package/dist/schema-DqR_Kcje.mjs +2 -0
  245. package/dist/schema-DqR_Kcje.mjs.map +1 -0
  246. package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
  247. package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
  248. package/dist/schema.d.mts +2 -2
  249. package/dist/schema.mjs +1 -1
  250. package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
  251. package/dist/select-assembly-CEpNu-Gw.mjs.map +1 -0
  252. package/dist/serializer-ettLu5xG.mjs +33 -0
  253. package/dist/serializer-ettLu5xG.mjs.map +1 -0
  254. package/dist/settle-Pui-1tfJ.mjs +2 -0
  255. package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
  256. package/dist/settled-DYYPcaBX.mjs +2 -0
  257. package/dist/{settled-BjyuA76m.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
  258. package/dist/snowflake-BfF8xwfP.mjs +2 -0
  259. package/dist/{snowflake-UOCC820W.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
  260. package/dist/snowflake.d.mts +3 -3
  261. package/dist/snowflake.mjs +2 -2
  262. package/dist/snowflake.mjs.map +1 -1
  263. package/dist/soft-delete.d.mts +9 -3
  264. package/dist/soft-delete.mjs +1 -1
  265. package/dist/soft-delete.mjs.map +1 -1
  266. package/dist/{spans-XDUFeTzC.mjs → spans-DwDXMvyd.mjs} +1 -1
  267. package/dist/{spans-XDUFeTzC.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
  268. package/dist/sql-Bu63iAfT.mjs +2 -0
  269. package/dist/sql-Bu63iAfT.mjs.map +1 -0
  270. package/dist/{sql-BVZ8QefY.d.mts → sql-C4_sFNDm.d.mts} +18 -5
  271. package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
  272. package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
  273. package/dist/sql-tegqTqGq.mjs +2 -0
  274. package/dist/sql-tegqTqGq.mjs.map +1 -0
  275. package/dist/sql.d.mts +1 -1
  276. package/dist/sql.mjs +1 -1
  277. package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
  278. package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
  279. package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
  280. package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
  281. package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
  282. package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
  283. package/dist/sqlite3.d.mts +2 -46
  284. package/dist/sqlite3.mjs +1 -1
  285. package/dist/sqlite3.mjs.map +1 -1
  286. package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
  287. package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
  288. package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
  289. package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
  290. package/dist/surrealdb.d.mts +2 -2
  291. package/dist/surrealdb.mjs +1 -1
  292. package/dist/surrealdb.mjs.map +1 -1
  293. package/dist/surrealql-DY74AUeD.mjs +2 -0
  294. package/dist/surrealql-DY74AUeD.mjs.map +1 -0
  295. package/dist/time-step-DJaIhpAz.mjs +2 -0
  296. package/dist/time-step-DJaIhpAz.mjs.map +1 -0
  297. package/dist/transaction-Bv5nyp-U.mjs +2 -0
  298. package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
  299. package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
  300. package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
  301. package/dist/types-Dy33vBdd.mjs +2 -0
  302. package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
  303. package/dist/unit-DUPX5Sdd.mjs +2 -0
  304. package/dist/{unit-BhHbZyuJ.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
  305. package/dist/unit-words-BXpLpyr2.mjs +2 -0
  306. package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
  307. package/dist/utils-BHkJsduV.mjs +26 -0
  308. package/dist/{utils-CpAojrCj.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
  309. package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
  310. package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
  311. package/dist/validation-ATmgN5RE.mjs +2 -0
  312. package/dist/validation-ATmgN5RE.mjs.map +1 -0
  313. package/dist/validation-BHjx13zG.mjs +2 -0
  314. package/dist/validation-BHjx13zG.mjs.map +1 -0
  315. package/dist/validation.d.mts +1 -1
  316. package/dist/validation.mjs +1 -1
  317. package/dist/validator-DMzH5Tz0.mjs +2 -0
  318. package/dist/validator-DMzH5Tz0.mjs.map +1 -0
  319. package/dist/value-guards-CBVIJXlI.mjs +2 -0
  320. package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
  321. package/dist/values-Ch2cTlss.mjs +2 -0
  322. package/dist/{values-B4aj1i1f.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
  323. package/dist/version-0BDwfy7C.mjs +2 -0
  324. package/dist/{version-CXGIA82S.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
  325. package/dist/view-CHgjF2BO.mjs +2 -0
  326. package/dist/view-CHgjF2BO.mjs.map +1 -0
  327. package/dist/write-sinks-Bei5vFHP.mjs +2 -0
  328. package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
  329. package/package.json +50 -37
  330. package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
  331. package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
  332. package/dist/adapter-namespace-DaRiTIIf.mjs +0 -2
  333. package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
  334. package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
  335. package/dist/args-764KdWMr.mjs +0 -2
  336. package/dist/array-literal-DHinAnVs.mjs +0 -2
  337. package/dist/base-z-cH5ZBI.mjs +0 -2
  338. package/dist/base-z-cH5ZBI.mjs.map +0 -1
  339. package/dist/batch-refs-C-gx7A4-.mjs +0 -2
  340. package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
  341. package/dist/call-Cz8XUmrl.mjs +0 -2
  342. package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
  343. package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
  344. package/dist/chunk-BuuaeEvq.mjs +0 -1
  345. package/dist/client-DRpX3-vw.mjs +0 -2
  346. package/dist/client-DRpX3-vw.mjs.map +0 -1
  347. package/dist/client-y7TV0PRZ.mjs +0 -9
  348. package/dist/client-y7TV0PRZ.mjs.map +0 -1
  349. package/dist/confine-DqFBTUw6.mjs +0 -2
  350. package/dist/coordination-6qZHx_kl.mjs +0 -2
  351. package/dist/coordination-6qZHx_kl.mjs.map +0 -1
  352. package/dist/current-DBTlPsQg.mjs +0 -2
  353. package/dist/current-DBTlPsQg.mjs.map +0 -1
  354. package/dist/datetime-physical-codec-Dj-APo9f.mjs +0 -2
  355. package/dist/datetime-physical-codec-Dj-APo9f.mjs.map +0 -1
  356. package/dist/defaults-DwOHWI_M.mjs +0 -2
  357. package/dist/driver-BGVcgnIX.mjs +0 -2
  358. package/dist/driver-BGVcgnIX.mjs.map +0 -1
  359. package/dist/driver-BIXhOH2_.mjs +0 -2
  360. package/dist/driver-BIXhOH2_.mjs.map +0 -1
  361. package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
  362. package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
  363. package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
  364. package/dist/every-tOgQmaIE.mjs +0 -2
  365. package/dist/execution-context-BXpcbyPe.mjs +0 -2
  366. package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
  367. package/dist/extension-CGepsF-p.mjs +0 -2
  368. package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
  369. package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
  370. package/dist/geo-area-codec-mHrM3b9A.mjs.map +0 -1
  371. package/dist/hydration-A3zffFWP.mjs +0 -2
  372. package/dist/hydration-A3zffFWP.mjs.map +0 -1
  373. package/dist/identifier-conversion-DHYPTgzr.mjs +0 -2
  374. package/dist/identifier-conversion-DHYPTgzr.mjs.map +0 -1
  375. package/dist/identifiers-s00pGES8.mjs +0 -2
  376. package/dist/identifiers-s00pGES8.mjs.map +0 -1
  377. package/dist/identity-CtW15WlB.mjs +0 -2
  378. package/dist/identity-CtW15WlB.mjs.map +0 -1
  379. package/dist/introspect-Bm6xnXcG.mjs +0 -2
  380. package/dist/introspect-Bm6xnXcG.mjs.map +0 -1
  381. package/dist/json-DgMc8-GU.mjs +0 -2
  382. package/dist/json-DgMc8-GU.mjs.map +0 -1
  383. package/dist/json-number-AI-SdUUn.mjs +0 -2
  384. package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
  385. package/dist/judge-words-CzUyXtJ6.mjs +0 -2
  386. package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
  387. package/dist/key-hxFFCKed.mjs +0 -2
  388. package/dist/key-hxFFCKed.mjs.map +0 -1
  389. package/dist/keys-BQxM4c_a.mjs +0 -2
  390. package/dist/libsql-DuGR904j.mjs +0 -3
  391. package/dist/libsql-DuGR904j.mjs.map +0 -1
  392. package/dist/light-BkJe3-yW.mjs +0 -2
  393. package/dist/memory-G4cSuc6A.mjs +0 -2
  394. package/dist/methods-part-ZY0f2AV_.mjs +0 -2
  395. package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
  396. package/dist/migrations-BMiRjR-N.mjs +0 -2
  397. package/dist/mysql-BNXWfTOo.mjs +0 -100
  398. package/dist/mysql-BNXWfTOo.mjs.map +0 -1
  399. package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
  400. package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
  401. package/dist/native-types-DgjMUikz.mjs +0 -2
  402. package/dist/native-types-DgjMUikz.mjs.map +0 -1
  403. package/dist/normalized-result-B8pifWS0.mjs +0 -2
  404. package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
  405. package/dist/object-store-DS0F0yZX.mjs +0 -2
  406. package/dist/object-store-DS0F0yZX.mjs.map +0 -1
  407. package/dist/on-ylYaKuRu.mjs +0 -2
  408. package/dist/pending-operation-C_eOFOBE.mjs +0 -2
  409. package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
  410. package/dist/physical-CeE2nYmI.mjs +0 -2
  411. package/dist/physical-CeE2nYmI.mjs.map +0 -1
  412. package/dist/pinned-session-DCoAZDOz.mjs +0 -2
  413. package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
  414. package/dist/postgres-CDdh5dSP.mjs +0 -437
  415. package/dist/postgres-CDdh5dSP.mjs.map +0 -1
  416. package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
  417. package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
  418. package/dist/postgres-adapter-axapXX8d.mjs +0 -2
  419. package/dist/postgres-result-DF6DmW3r.mjs +0 -2
  420. package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
  421. package/dist/provider-limits-Ccsb8PTb.mjs +0 -2
  422. package/dist/provider-limits-Ccsb8PTb.mjs.map +0 -1
  423. package/dist/provider-parameter-snapshot-BikrgKqI.mjs +0 -2
  424. package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +0 -1
  425. package/dist/query-BZVHfA0s.mjs +0 -2
  426. package/dist/query-BZVHfA0s.mjs.map +0 -1
  427. package/dist/query-inspection-BoG-yAln.mjs +0 -2
  428. package/dist/query-inspection-BoG-yAln.mjs.map +0 -1
  429. package/dist/raw-Dyq6Y6UX.mjs +0 -2
  430. package/dist/raw-Dyq6Y6UX.mjs.map +0 -1
  431. package/dist/relation-bound-ku_cMdye.mjs +0 -2
  432. package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
  433. package/dist/routed-operations-wytpbYKv.mjs +0 -2
  434. package/dist/rule-words-ZIGm7cDm.mjs +0 -2
  435. package/dist/scalar-BHCh7aUz.mjs +0 -4
  436. package/dist/scalar-BHCh7aUz.mjs.map +0 -1
  437. package/dist/schema-BYA-_bpk.mjs +0 -2
  438. package/dist/schema-BYA-_bpk.mjs.map +0 -1
  439. package/dist/schema-CFIaebgi.mjs +0 -2
  440. package/dist/schema-CFIaebgi.mjs.map +0 -1
  441. package/dist/schema-introspection-D0f8cti4.mjs +0 -6
  442. package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
  443. package/dist/select-assembly-DVI7d3tf.mjs +0 -2
  444. package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
  445. package/dist/serializer-rBq3v1xr.mjs +0 -51
  446. package/dist/serializer-rBq3v1xr.mjs.map +0 -1
  447. package/dist/settle-1cy5x_52.mjs +0 -2
  448. package/dist/settled-BjyuA76m.mjs +0 -2
  449. package/dist/snowflake-UOCC820W.mjs +0 -2
  450. package/dist/sql-3o4DOKm9.mjs +0 -2
  451. package/dist/sql-3o4DOKm9.mjs.map +0 -1
  452. package/dist/sql-Dl6nykFV.mjs +0 -2
  453. package/dist/sql-Dl6nykFV.mjs.map +0 -1
  454. package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
  455. package/dist/sqlite-adapter-Ad0d-m2t.mjs +0 -2
  456. package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +0 -1
  457. package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
  458. package/dist/sqlite-utils-BRvbmlQ1.mjs +0 -2
  459. package/dist/sqlite-utils-BRvbmlQ1.mjs.map +0 -1
  460. package/dist/standard-sql-qLcQyCtK.mjs +0 -6
  461. package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
  462. package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
  463. package/dist/surrealql-C1dp1sWw.mjs +0 -2
  464. package/dist/surrealql-C1dp1sWw.mjs.map +0 -1
  465. package/dist/to-many-BybuKQM1.mjs +0 -2
  466. package/dist/to-many-BybuKQM1.mjs.map +0 -1
  467. package/dist/transaction-BNomMtme.mjs +0 -2
  468. package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
  469. package/dist/types-DtDnXhwa.mjs +0 -2
  470. package/dist/unit-BhHbZyuJ.mjs +0 -2
  471. package/dist/unit-words-CT0yeqfZ.mjs +0 -2
  472. package/dist/utils-CpAojrCj.mjs +0 -26
  473. package/dist/validation--qS7OPmg.mjs +0 -2
  474. package/dist/validation--qS7OPmg.mjs.map +0 -1
  475. package/dist/validation-CYaJ8ndO.mjs +0 -2
  476. package/dist/validation-CYaJ8ndO.mjs.map +0 -1
  477. package/dist/validator-CZLW7aR3.mjs +0 -2
  478. package/dist/validator-CZLW7aR3.mjs.map +0 -1
  479. package/dist/value-guards-CBuxSC66.mjs +0 -2
  480. package/dist/values-B4aj1i1f.mjs +0 -2
  481. package/dist/version-CXGIA82S.mjs +0 -2
  482. package/dist/write-sinks-3IKCDF-S.mjs +0 -2
  483. /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"better-auth.mjs","names":[],"sources":["../src/better-auth/named.ts","../src/better-auth/schema.ts","../src/better-auth/where.ts","../src/better-auth/index.ts"],"sourcesContent":["import { ClientInitializationError } from \"@errors\";\nimport type { CleanedWhere } from \"better-auth/adapters\";\n\nexport type VibormAdapterOperation =\n | \"create\"\n | \"findOne\"\n | \"findMany\"\n | \"count\"\n | \"update\"\n | \"updateMany\"\n | \"delete\"\n | \"deleteMany\"\n | \"consumeOne\"\n | \"incrementOne\";\n\n/**\n * Controls how the adapter sets VibORM's per-call `named` option for\n * server-side prepared statements (see driver `namedStatements`).\n *\n * - `undefined`: omits `named`, deferring entirely to the driver's default.\n * - `false`: passes `named: false` on every call so Better Auth never consumes\n * slots in an automatic driver statement cache.\n * - `true`: passes `named: true` on bounded recurrent hot-path operations\n * (`findOne`, `findMany`, `consumeOne`, `incrementOne`, `delete`) and\n * `named: false` on dynamic-arity (`in`/`not_in`), custom-select, paginated\n * (`offset`), `OR`, or high-cardinality calls so `namedStatements.max` is\n * never exhausted.\n * - `{ models?, operations? }`: applies the same bounded-shape guard scoped to\n * the chosen models (canonical keys or physical model names) and operations.\n */\nexport type VibormNamedStatementsOption =\n | boolean\n | {\n readonly models?: readonly string[];\n readonly operations?: readonly VibormAdapterOperation[];\n };\n\nconst ALL_OPERATIONS = new Set<string>([\n \"create\",\n \"findOne\",\n \"findMany\",\n \"count\",\n \"update\",\n \"updateMany\",\n \"delete\",\n \"deleteMany\",\n \"consumeOne\",\n \"incrementOne\",\n]);\n\n/** Default hot-path operations eligible when `namedStatements: true`. */\nconst DEFAULT_HOT_PATH_OPERATIONS: readonly VibormAdapterOperation[] = [\n \"findOne\",\n \"findMany\",\n \"consumeOne\",\n \"incrementOne\",\n \"delete\",\n];\n\n/** Upper bound on AND predicates in a named hot-path query. */\nconst MAX_NAMED_CONDITIONS = 4;\n/** Upper bound on updated columns in a named update query. */\nconst MAX_NAMED_UPDATE_COLUMNS = 4;\n\nexport interface ResolvedNamedPolicy {\n readonly mode: \"off\" | \"never\" | \"bounded\";\n readonly models: ReadonlySet<string> | undefined;\n readonly operations: ReadonlySet<VibormAdapterOperation>;\n}\n\nconst OFF_POLICY: ResolvedNamedPolicy = {\n mode: \"off\",\n models: undefined,\n operations: new Set(),\n};\n\nconst NEVER_POLICY: ResolvedNamedPolicy = {\n mode: \"never\",\n models: undefined,\n operations: new Set(),\n};\n\nexport function resolveNamedPolicy(\n option: VibormNamedStatementsOption | undefined\n): ResolvedNamedPolicy {\n if (option === undefined) return OFF_POLICY;\n if (option === false) return NEVER_POLICY;\n if (option === true) {\n return {\n mode: \"bounded\",\n models: undefined,\n operations: new Set(DEFAULT_HOT_PATH_OPERATIONS),\n };\n }\n if (typeof option !== \"object\" || option === null || Array.isArray(option)) {\n throw new ClientInitializationError(\n \"vibormAdapter: namedStatements must be a boolean or { models?, operations? }.\",\n { meta: { operation: \"configuration\" } }\n );\n }\n let models: ReadonlySet<string> | undefined;\n if (option.models !== undefined) {\n if (\n !Array.isArray(option.models) ||\n option.models.some(\n (name) => typeof name !== \"string\" || name.length === 0\n )\n ) {\n throw new ClientInitializationError(\n \"vibormAdapter: namedStatements.models must be an array of non-empty model names.\",\n { meta: { operation: \"configuration\" } }\n );\n }\n models = new Set(option.models);\n }\n let operations: ReadonlySet<VibormAdapterOperation>;\n if (option.operations !== undefined) {\n if (\n !Array.isArray(option.operations) ||\n option.operations.some(\n (op) => typeof op !== \"string\" || !ALL_OPERATIONS.has(op)\n )\n ) {\n throw new ClientInitializationError(\n \"vibormAdapter: namedStatements.operations contains an unknown adapter operation.\",\n { meta: { operation: \"configuration\" } }\n );\n }\n operations = new Set(option.operations);\n } else {\n operations = new Set(DEFAULT_HOT_PATH_OPERATIONS);\n }\n return { mode: \"bounded\", models, operations };\n}\n\nexport interface NamedCallShape {\n readonly operation: VibormAdapterOperation;\n readonly model: string;\n readonly modelKey: string;\n readonly where?: readonly CleanedWhere[] | undefined;\n readonly hasCustomSelect?: boolean;\n readonly hasJoin?: boolean;\n readonly hasOffset?: boolean;\n readonly updateFieldCount?: number;\n}\n\n/**\n * Whether `where` has a fixed, low-cardinality SQL template:\n * AND-only, scalar (no `in`/`not_in` variable bind lists), defined values, and\n * within `MAX_NAMED_CONDITIONS`.\n */\nfunction hasBoundedWhere(\n conditions: readonly CleanedWhere[] | undefined,\n allowEmpty: boolean\n): boolean {\n const list = conditions ?? [];\n if (list.length === 0) return allowEmpty;\n if (list.length > MAX_NAMED_CONDITIONS) return false;\n for (const clause of list) {\n if (clause.connector === \"OR\") return false;\n if (clause.operator === \"in\" || clause.operator === \"not_in\") return false;\n if (clause.value === undefined) return false;\n }\n return true;\n}\n\n/**\n * Decide the per-call `named` argument to hand to VibORM.\n * Returns `undefined` when `namedStatements` is unconfigured, `true` when the\n * call is an eligible bounded hot path, and `false` otherwise.\n */\nexport function resolveNamedOption(\n policy: ResolvedNamedPolicy,\n call: NamedCallShape\n): boolean | undefined {\n if (policy.mode === \"off\") return undefined;\n if (policy.mode === \"never\") return false;\n if (!policy.operations.has(call.operation)) return false;\n if (\n policy.models !== undefined &&\n !policy.models.has(call.modelKey) &&\n !policy.models.has(call.model)\n ) {\n return false;\n }\n if (call.hasCustomSelect) return false;\n\n switch (call.operation) {\n case \"create\":\n return true;\n case \"count\":\n return hasBoundedWhere(call.where, true);\n case \"findOne\":\n return hasBoundedWhere(call.where, false);\n case \"findMany\":\n if (call.hasOffset || call.hasJoin) return false;\n return hasBoundedWhere(call.where, false);\n case \"update\":\n case \"updateMany\":\n if (\n call.updateFieldCount !== undefined &&\n (call.updateFieldCount === 0 ||\n call.updateFieldCount > MAX_NAMED_UPDATE_COLUMNS)\n ) {\n return false;\n }\n return hasBoundedWhere(call.where, false);\n default:\n return hasBoundedWhere(call.where, false);\n }\n}\n","import type { BetterAuthDBSchema, DBFieldAttribute } from \"better-auth/db\";\n\ntype Table = BetterAuthDBSchema[string];\n\n/** Whether a Better Auth column may hold null (`required` defaults to `true`). */\nexport const isNullable = (\n attribute: Pick<DBFieldAttribute, \"required\">\n): boolean => attribute.required === false;\n\n/**\n * An inverse relation added to a generated Better Auth model for an application\n * model that holds a foreign key to it. VibORM declares relations on both ends,\n * so listing application inverses here preserves them across `createSchema`\n * regenerations.\n */\nexport interface VibormSchemaInverse {\n /** Auth model receiving the inverse (canonical key or physical model name, e.g. `\"user\"`). */\n readonly model: string;\n /** Relation property name on that auth model (e.g. `\"posts\"`). */\n readonly key: string;\n /** Exported identifier of the application model (e.g. `\"post\"`). */\n readonly target: string;\n /** Import specifier for `target`, relative to the generated schema file (e.g. `\"./post\"`). */\n readonly from: string;\n /** Optional explicit relation name when multiple relations connect the same two models. */\n readonly name?: string;\n /** Set `true` for a one-to-one inverse (`s.toOne`); defaults to `s.toMany`. */\n readonly one?: boolean;\n}\n\nexport interface VibormSchemaOptions {\n /** Output file path used by `createSchema` when Better Auth does not pass one. Defaults to `\"./auth-schema.ts\"`. */\n readonly path?: string;\n /** Name of the exported schema object holding all generated models. Defaults to `\"authSchema\"`. */\n readonly exportName?: string;\n /** Use plural model names (matching Better Auth's `usePlural` adapter option). */\n readonly usePlural?: boolean;\n /** Render auto-incrementing integer primary keys (`s.int().id().increment()`) and integer foreign keys for `generateId: \"serial\"`. */\n readonly numericIds?: boolean;\n /** Inverse relations from application models targeting generated Better Auth models. */\n readonly inverses?: readonly VibormSchemaInverse[];\n /** Optional comment header prepended to the generated file. */\n readonly header?: string;\n}\n\nconst DEFAULT_HEADER =\n \"// Generated by viborm/better-auth. Do not edit manually.\";\n\nconst SCALARS: Record<string, string> = {\n string: \"s.string()\",\n number: \"s.int()\",\n boolean: \"s.boolean()\",\n date: \"s.dateTime()\",\n json: \"s.json()\",\n \"string[]\": \"s.string().array()\",\n \"number[]\": \"s.int().array()\",\n};\n\nconst REFERENTIAL_ACTIONS: Record<string, string> = {\n cascade: \"cascade\",\n \"set null\": \"setNull\",\n restrict: \"restrict\",\n \"no action\": \"noAction\",\n};\n\n/** Valid bare JS identifier for generated bindings and object keys. */\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/;\n\n/** Reserved words a strict ESM module cannot bind with `const`, plus `s`. */\nconst RESERVED_BINDINGS = new Set(\n \"await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield arguments eval s\".split(\n \" \"\n )\n);\n\n/** Characters escaped in emitted JS/TS string literals beyond `JSON.stringify`. */\nconst UNSAFE_CODE_CHARS = /[<>&\\u2028\\u2029]/g;\n\nfunction literal(value: unknown): string {\n if (typeof value === \"string\") {\n return JSON.stringify(value).replace(\n UNSAFE_CODE_CHARS,\n (ch) => `\\\\u${ch.charCodeAt(0).toString(16).padStart(4, \"0\")}`\n );\n }\n if (Array.isArray(value)) return `[${value.map(literal).join(\", \")}]`;\n if (typeof value === \"object\" && value !== null) {\n const entries = Object.entries(value).map(\n ([key, member]) => `${literal(key)}: ${literal(member)}`\n );\n return entries.length > 0 ? `{ ${entries.join(\", \")} }` : \"{}\";\n }\n return String(value);\n}\n\n/** Whether a default value is a database-storable literal (functions/Dates run in JS on create). */\nconst isLiteralDefault = (value: unknown): boolean =>\n value !== undefined &&\n value !== null &&\n typeof value !== \"function\" &&\n !(value instanceof Date);\n\nconst capitalize = (text: string): string =>\n text[0]!.toUpperCase() + text.slice(1);\n\n/** Relation key beside an owning FK column: `userId` -> `user`, `owner_id` -> `owner_idRelation`. */\nconst relationKey = (column: string): string =>\n column.endsWith(\"Id\") && column.length > 2\n ? column.slice(0, -2)\n : `${column}Relation`;\n\nconst physicalModelName = (table: Table, usePlural: boolean): string =>\n usePlural ? `${table.modelName}s` : table.modelName;\n\n/** Resolve a Better Auth table by canonical key, raw modelName, or pluralized modelName. */\nconst tableIn = (\n tables: BetterAuthDBSchema,\n reference: string,\n usePlural: boolean\n): Table | undefined => {\n const direct = tables[reference];\n if (direct) return direct;\n return Object.values(tables).find(\n (table) =>\n table.modelName === reference ||\n (usePlural && `${table.modelName}s` === reference)\n );\n};\n\nconst columnIn = (table: Table, field: string): string =>\n table.fields[field]?.fieldName ?? field;\n\nfunction renderScalar(\n model: string,\n field: string,\n attribute: DBFieldAttribute,\n numericIds: boolean\n): string {\n const { type } = attribute;\n let base: string | undefined;\n if (Array.isArray(type)) {\n base = `s.enum(${literal(type)})`;\n } else if (\n numericIds &&\n type === \"string\" &&\n attribute.references?.field === \"id\"\n ) {\n base = \"s.int()\";\n } else if (type === \"number\" && attribute.bigint) {\n // Better Auth marks millisecond timestamps / >int4 JS numbers with `bigint: true`,\n // while passing JS `number` values (not JS `bigint`). `s.number()` (float8/REAL)\n // stores every JS safe integer exactly across PostgreSQL, MySQL, and SQLite.\n base = \"s.number()\";\n } else {\n base = SCALARS[type];\n }\n if (base === undefined) {\n throw new Error(\n `renderVibormSchema: '${model}.${field}' has type '${String(type)}', which has no VibORM scalar.`\n );\n }\n return (\n base +\n (isNullable(attribute) ? \".nullable()\" : \"\") +\n (attribute.unique ? \".unique()\" : \"\") +\n (isLiteralDefault(attribute.defaultValue)\n ? `.default(${literal(attribute.defaultValue)})`\n : \"\")\n );\n}\n\ninterface PendingRelation {\n readonly sourceModel: string;\n readonly sourceBaseName: string;\n readonly targetModel: string;\n readonly column: string;\n readonly references: string;\n readonly action: string;\n readonly unique: boolean;\n readonly key: string;\n}\n\nconst undirectedPairKey = (a: string, b: string): string =>\n a <= b ? `${a}\\0${b}` : `${b}\\0${a}`;\n\n/**\n * Render a Better Auth `BetterAuthDBSchema` as a standalone VibORM TypeScript\n * schema module.\n */\nexport function renderVibormSchema(\n tables: BetterAuthDBSchema,\n options: VibormSchemaOptions = {}\n): string {\n const usePlural = options.usePlural === true;\n const numericIds = options.numericIds === true;\n const exportName = options.exportName ?? \"authSchema\";\n const inverses = options.inverses ?? [];\n const header = options.header ?? DEFAULT_HEADER;\n\n if (!IDENTIFIER.test(exportName) || RESERVED_BINDINGS.has(exportName)) {\n throw new Error(\n `renderVibormSchema: exportName '${exportName}' is not a valid module binding name.`\n );\n }\n\n const takenBindings = new Set(RESERVED_BINDINGS);\n takenBindings.add(exportName);\n\n const idScalar = numericIds ? \"s.int().id().increment()\" : \"s.string().id()\";\n const models = new Map<\n string,\n { members: Map<string, string>; indexes: string[] }\n >();\n\n for (const table of Object.values(tables)) {\n const modelName = physicalModelName(table, usePlural);\n if (!IDENTIFIER.test(modelName) || takenBindings.has(modelName)) {\n throw new Error(\n `renderVibormSchema: the table '${modelName}' cannot name a model the module declares. Name it a JavaScript identifier other than a reserved word, 's', or '${exportName}'.`\n );\n }\n const idColumn = table.fields.id?.fieldName ?? \"id\";\n if (!IDENTIFIER.test(idColumn)) {\n throw new Error(\n `renderVibormSchema: '${modelName}.${idColumn}' cannot name a key of its model. Name the column a JavaScript identifier.`\n );\n }\n models.set(modelName, {\n members: new Map([[idColumn, idScalar]]),\n indexes: [],\n });\n }\n\n const declare = (model: string, key: string, source: string) => {\n const entry = models.get(model)!;\n if (!IDENTIFIER.test(key)) {\n throw new Error(\n `renderVibormSchema: '${model}.${key}' cannot name a key of its model. Name the column a JavaScript identifier.`\n );\n }\n if (entry.members.has(key)) {\n throw new Error(\n `renderVibormSchema: '${model}.${key}' is declared twice. A field and a relation, or two relations to one table, cannot share a name.`\n );\n }\n entry.members.set(key, source);\n };\n\n // Pass 1: declare all scalar columns and collect foreign-key relations so we\n // know when multiple foreign keys connect the same pair of models.\n const pendingRelations: PendingRelation[] = [];\n const pairCounts = new Map<string, number>();\n\n for (const table of Object.values(tables)) {\n const model = physicalModelName(table, usePlural);\n for (const [field, attribute] of Object.entries(table.fields)) {\n // Better Auth mutates `schema[m].fields.id` at runtime; the primary key\n // was already declared above.\n if (field === \"id\") continue;\n\n const column = attribute.fieldName ?? field;\n declare(\n model,\n column,\n renderScalar(model, column, attribute, numericIds)\n );\n if (attribute.index && !attribute.unique) {\n models.get(model)!.indexes.push(`.index([${literal(column)}])`);\n }\n\n const target =\n attribute.references &&\n tableIn(tables, attribute.references.model, usePlural);\n if (!target) continue;\n\n const onDelete = attribute.references!.onDelete ?? \"cascade\";\n const action = REFERENTIAL_ACTIONS[onDelete];\n if (!action) {\n throw new Error(\n `renderVibormSchema: '${model}.${column}' deletes with '${onDelete}', which VibORM cannot declare.`\n );\n }\n const targetModel = physicalModelName(target, usePlural);\n const pairKey = undirectedPairKey(model, targetModel);\n pairCounts.set(pairKey, (pairCounts.get(pairKey) ?? 0) + 1);\n pendingRelations.push({\n sourceModel: model,\n sourceBaseName: table.modelName,\n targetModel,\n column,\n references: columnIn(target, attribute.references!.field),\n action,\n unique: attribute.unique === true,\n key: relationKey(column),\n });\n }\n\n for (const index of table.indexes ?? []) {\n const optionsParts = [\n ...(index.name === undefined ? [] : [`name: ${literal(index.name)}`]),\n ...(index.unique ? [\"unique: true\"] : []),\n ];\n const columns = literal(\n index.fields.map((field) => columnIn(table, field))\n );\n models\n .get(model)!\n .indexes.push(\n `.index(${columns}${optionsParts.length > 0 ? `, { ${optionsParts.join(\", \")} }` : \"\"})`\n );\n }\n }\n\n // Pass 2: declare owning relations and their inverses, naming multi-edge\n // pairs so VibORM resolves every relation unambiguously.\n const inverseDeclarations: [model: string, key: string, source: string][] =\n [];\n for (const rel of pendingRelations) {\n const pairKey = undirectedPairKey(rel.sourceModel, rel.targetModel);\n const multiEdge = pairCounts.get(pairKey)! > 1;\n const relationName = multiEdge\n ? `${rel.sourceBaseName}_${rel.column}_${rel.targetModel}`\n : undefined;\n const nameSuffix =\n relationName === undefined ? \"\" : `.name(${literal(relationName)})`;\n\n declare(\n rel.sourceModel,\n rel.key,\n `s.toOne(() => ${rel.targetModel}).fields(${literal(rel.column)}).references(${literal(rel.references)}).onDelete(${literal(rel.action)})${nameSuffix}`\n );\n\n const baseInverseKey = rel.unique\n ? rel.sourceBaseName\n : `${rel.sourceBaseName}s`;\n const inverseKey = multiEdge\n ? `${baseInverseKey}By${capitalize(rel.key)}`\n : baseInverseKey;\n const inverseFactory = rel.unique ? \"s.toOne\" : \"s.toMany\";\n inverseDeclarations.push([\n rel.targetModel,\n inverseKey,\n `${inverseFactory}(() => ${rel.sourceModel})${nameSuffix}`,\n ]);\n }\n for (const [model, key, source] of inverseDeclarations) {\n declare(model, key, source);\n }\n\n // Pass 3: attach caller-supplied inverse relations for application models.\n // Inverses targeting auth models omitted by the current Better Auth options\n // (for example `organization` when the plugin is off) are skipped cleanly.\n const activeInverses: Array<VibormSchemaInverse & { resolvedModel: string }> =\n [];\n for (const inverse of inverses) {\n const resolvedTable = tableIn(tables, inverse.model, usePlural);\n const resolvedModel = resolvedTable\n ? physicalModelName(resolvedTable, usePlural)\n : inverse.model;\n if (!models.has(resolvedModel)) continue;\n if (\n !IDENTIFIER.test(inverse.target) ||\n takenBindings.has(inverse.target) ||\n models.has(inverse.target)\n ) {\n throw new Error(\n `renderVibormSchema: the inverse target model '${inverse.target}' cannot be imported beside the auth models.`\n );\n }\n if (typeof inverse.from !== \"string\" || inverse.from.length === 0) {\n throw new Error(\n `renderVibormSchema: inverse '${resolvedModel}.${inverse.key}' must declare a non-empty 'from' module specifier.`\n );\n }\n declare(\n resolvedModel,\n inverse.key,\n `${inverse.one ? \"s.toOne\" : \"s.toMany\"}(() => ${inverse.target})${inverse.name === undefined ? \"\" : `.name(${literal(inverse.name)})`}`\n );\n activeInverses.push({ ...inverse, resolvedModel });\n }\n\n const importSpecifiers = [...new Set(activeInverses.map(({ from }) => from))];\n const imports = importSpecifiers\n .map((from) => {\n const targets = [\n ...new Set(\n activeInverses\n .filter((entry) => entry.from === from)\n .map((entry) => entry.target)\n ),\n ].sort();\n return `import { ${targets.join(\", \")} } from ${literal(from)};\\n`;\n })\n .join(\"\");\n\n const renderedModels = [...models].map(([name, { members, indexes }]) => {\n const lines = [...members].map(([key, source]) => ` ${key}: ${source},`);\n const indexSuffix = indexes.map((index) => `\\n ${index}`).join(\"\");\n return `export const ${name} = s.model({\\n${lines.join(\"\\n\")}\\n})${indexSuffix};`;\n });\n\n const exportedModels = [...models.keys()]\n .map((name) => ` ${name},`)\n .join(\"\\n\");\n\n const head = header.length > 0 ? `${header}\\n\\n` : \"\";\n return `${head}import { s } from \"viborm\";\\n${imports}\\n${renderedModels.join(\"\\n\\n\")}\\n\\nexport const ${exportName} = {\\n${exportedModels}\\n};\\n`;\n}\n","import { DbNull } from \"@schema/json-null\";\nimport type { CleanedWhere } from \"better-auth/adapters\";\n\nexport type VibormWhere = Record<string, unknown>;\n\n/** An empty disjunction: VibORM lowers it to FALSE. */\nconst NO_ROW: VibormWhere = { OR: [] };\n/** FALSE, negated. Not `{}`, which VibORM drops from a disjunction. */\nconst EVERY_ROW: VibormWhere = { NOT: NO_ROW };\n\nconst COMPARISON_OPERATORS = {\n lt: \"lt\",\n lte: \"lte\",\n gt: \"gt\",\n gte: \"gte\",\n contains: \"contains\",\n starts_with: \"startsWith\",\n ends_with: \"endsWith\",\n} as const;\n\nexport interface WhereColumnFacts {\n /** Whether the column may hold SQL NULL. */\n readonly nullable: (column: string) => boolean;\n /** Whether the column accepts VibORM `mode: \"insensitive\"` text folding. */\n readonly supportsInsensitive?: (column: string) => boolean;\n}\n\nconst isTextOperand = (operand: unknown): boolean =>\n typeof operand === \"string\" ||\n (Array.isArray(operand) && operand.every((item) => typeof item === \"string\"));\n\nconst isNullValue = (value: unknown): boolean =>\n value === null || value === DbNull;\n\nfunction convertCondition(\n { field, value, operator, mode }: CleanedWhere,\n facts: WhereColumnFacts\n): VibormWhere {\n // Undefined compares to nothing in SQL, matching no row.\n if (value === undefined) return NO_ROW;\n\n const canFold =\n mode === \"insensitive\" &&\n isTextOperand(value) &&\n (facts.supportsInsensitive ? facts.supportsInsensitive(field) : true);\n const fold = canFold ? { mode: \"insensitive\" as const } : {};\n\n switch (operator) {\n case \"eq\":\n if (isNullValue(value)) {\n return facts.nullable(field) ? { [field]: { equals: value } } : NO_ROW;\n }\n return { [field]: { equals: value, ...fold } };\n\n case \"ne\":\n if (isNullValue(value)) {\n return facts.nullable(field) ? { [field]: { not: value } } : EVERY_ROW;\n }\n return { [field]: { not: { equals: value, ...fold } } };\n\n case \"in\":\n case \"not_in\": {\n const members: unknown[] = Array.isArray(value) ? value : [value];\n const values = members.filter(\n (item) => item !== null && item !== undefined && item !== DbNull\n );\n if (operator === \"not_in\" && values.length < members.length) {\n return NO_ROW;\n }\n if (values.length === 0) {\n return operator === \"in\" ? NO_ROW : EVERY_ROW;\n }\n const listFold =\n mode === \"insensitive\" &&\n isTextOperand(values) &&\n (facts.supportsInsensitive ? facts.supportsInsensitive(field) : true)\n ? { mode: \"insensitive\" as const }\n : {};\n return {\n [field]: {\n [operator === \"in\" ? \"in\" : \"notIn\"]: values,\n ...listFold,\n },\n };\n }\n\n default: {\n // Null comparisons (<, <=, >, >=, LIKE) evaluate to SQL UNKNOWN -> no row.\n if (isNullValue(value)) return NO_ROW;\n return { [field]: { [COMPARISON_OPERATORS[operator]]: value, ...fold } };\n }\n }\n}\n\n/**\n * Translate Better Auth's cleaned `where` conditions to a VibORM `where` object.\n *\n * Every AND condition holds, and at least one OR condition holds when present —\n * matching Better Auth's first-party SQL adapter grouping.\n */\nexport function convertWhere(\n where: CleanedWhere[] | undefined,\n factsOrNullable: WhereColumnFacts | ((column: string) => boolean)\n): VibormWhere {\n if (!where || where.length === 0) return {};\n const facts: WhereColumnFacts =\n typeof factsOrNullable === \"function\"\n ? { nullable: factsOrNullable }\n : factsOrNullable;\n if (where.length === 1) {\n return convertCondition(where[0]!, facts);\n }\n const and: VibormWhere[] = [];\n const or: VibormWhere[] = [];\n for (const clause of where) {\n const converted = convertCondition(clause, facts);\n if (clause.connector === \"OR\") {\n or.push(converted);\n } else {\n and.push(converted);\n }\n }\n return {\n ...(and.length > 0 ? { AND: and } : {}),\n ...(or.length > 0 ? { OR: or } : {}),\n };\n}\n","import type { Schema } from \"@client/types\";\nimport { DbNull, JsonNull } from \"@schema/json-null\";\nimport type { AnyModel } from \"@schema/model\";\nimport { getModelKeyCatalog } from \"@schema/model/keys\";\nimport type { AnyRelation } from \"@schema/relation\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport { idDomainOfState } from \"@schema/scalars/string/id-domain\";\nimport type { BetterAuthOptions } from \"better-auth\";\nimport {\n type AdapterFactoryConfig,\n type AdapterFactoryCustomizeAdapterCreator,\n type CleanedWhere,\n type CustomAdapter,\n createAdapterFactory,\n type DBAdapterDebugLogOption,\n} from \"better-auth/adapters\";\nimport {\n type ResolvedNamedPolicy,\n resolveNamedOption,\n resolveNamedPolicy,\n type VibormAdapterOperation,\n type VibormNamedStatementsOption,\n} from \"./named\";\nimport {\n isNullable,\n renderVibormSchema,\n type VibormSchemaOptions,\n} from \"./schema\";\nimport { convertWhere, type VibormWhere, type WhereColumnFacts } from \"./where\";\n\nexport type {\n VibormAdapterOperation,\n VibormNamedStatementsOption,\n} from \"./named\";\nexport {\n renderVibormSchema,\n type VibormSchemaInverse,\n type VibormSchemaOptions,\n} from \"./schema\";\n\ntype Row = Record<string, unknown>;\n\ntype RelationInclude = true | { readonly take: number };\ntype Selection = { [key: string]: true | RelationInclude };\ntype Inclusion = { [key: string]: RelationInclude };\n\ntype AdapterArgs<\n Method extends\n | \"create\"\n | \"findOne\"\n | \"findMany\"\n | \"update\"\n | \"consumeOne\"\n | \"incrementOne\",\n> = Parameters<NonNullable<CustomAdapter[Method]>>[0];\n\ntype JoinInput = NonNullable<AdapterArgs<\"findOne\">[\"join\"]>;\n\n/**\n * The subset of a VibORM client surface consumed by the adapter.\n * Satisfied by any `VibORMClient`, extended client, or `TransactionClient`.\n */\nexport interface VibormAdapterClient {\n readonly $schema: Schema;\n readonly $driver?: {\n readonly dialect?: string;\n readonly supportsTransactions?: boolean;\n };\n $transaction<R>(run: (tx: VibormAdapterClient) => Promise<R>): Promise<R>;\n}\n\nexport interface VibormAdapterConfig {\n /** Better Auth adapter debug logging configuration. */\n readonly debugLogs?: DBAdapterDebugLogOption;\n /** Use plural model names (all Better Auth model keys end in `s`). Defaults to `false`. */\n readonly usePlural?: boolean;\n /**\n * Enable or disable interactive `$transaction` wrapping for Better Auth.\n * Defaults to `client.$driver?.supportsTransactions ?? true`.\n */\n readonly transaction?: boolean;\n /**\n * Opt into VibORM's `named: true` server-side prepared statements for\n * recurrent bounded Better Auth hot paths.\n */\n readonly namedStatements?: VibormNamedStatementsOption;\n /** Default options forwarded to `createSchema` (`@better-auth/cli`). */\n readonly schema?: VibormSchemaOptions;\n}\n\ninterface ModelDelegate {\n create(args: { data: Row; named?: boolean }): Promise<Row>;\n findUnique(args: {\n where: VibormWhere;\n select?: Selection;\n include?: Inclusion;\n named?: boolean;\n }): Promise<Row | null>;\n findFirst(args: {\n where: VibormWhere;\n select?: Selection;\n include?: Inclusion;\n named?: boolean;\n }): Promise<Row | null>;\n findMany(args: {\n where: VibormWhere;\n take: number;\n skip?: number;\n orderBy?: Record<string, \"asc\" | \"desc\">;\n select?: Selection;\n include?: Inclusion;\n named?: boolean;\n }): Promise<Row[]>;\n count(args: { where: VibormWhere; named?: boolean }): Promise<number>;\n updateMany(args: {\n where: VibormWhere;\n data: Row;\n limit?: number;\n named?: boolean;\n }): Promise<{ count: number }>;\n updateMany(args: {\n where: VibormWhere;\n data: Row;\n select: Selection;\n limit?: number;\n named?: boolean;\n }): Promise<Row[]>;\n deleteMany(args: {\n where: VibormWhere;\n limit?: number;\n named?: boolean;\n }): Promise<{ count: number }>;\n deleteMany(args: {\n where: VibormWhere;\n select: Selection;\n limit?: number;\n named?: boolean;\n }): Promise<Row[]>;\n}\n\nconst DEFAULT_SCHEMA_PATH = \"./auth-schema.ts\";\nconst identityRow = (found: Row): Row => found;\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * A one-key `{ set }` object is VibORM's write envelope for JSON columns; wrap\n * a literal Better Auth JSON object of that shape so it is stored verbatim.\n */\nconst isJsonSetEnvelope = (value: unknown): boolean =>\n isPlainRecord(value) &&\n Object.hasOwn(value, \"set\") &&\n Object.keys(value).length === 1;\n\n/** Compact identifier formats that VibORM stores without text-folding filters. */\nconst COMPACT_ID_FORMATS = new Set([\"uuid\", \"uuidv7\", \"ulid\", \"ksuid\"]);\n\nfunction isTextFoldableScalar(scalar: Scalar): boolean {\n const state = scalar[\"~\"].state;\n if (state.type !== \"string\" || state.array) return false;\n const domain = idDomainOfState(state);\n return domain === undefined || !COMPACT_ID_FORMATS.has(domain.format);\n}\n\nfunction collectModelKeySets(model: AnyModel): {\n readonly uniqueColumns: ReadonlySet<string>;\n readonly addressableUnique: ReadonlySet<string>;\n readonly textFoldable: ReadonlySet<string>;\n} {\n const catalog = getModelKeyCatalog(model);\n const uniqueColumns = new Set<string>();\n const addressableUnique = new Set<string>();\n const textFoldable = new Set<string>();\n // Unconditional single-column unique keys: addressable keys plus total unique\n // indexes only (partial unique indexes are excluded by the key catalog).\n for (const fields of catalog.referenceableKeys) {\n if (fields.length === 1) {\n uniqueColumns.add(fields[0]!);\n }\n }\n // Bare single-scalar selectors safe for `findUnique({ where: { [field]: v } })`.\n // In the key catalog, `name === undefined` holds exclusively for bare scalar keys.\n for (const key of catalog.addressableKeys) {\n if (key.name === undefined) {\n addressableUnique.add(key.fields[0]!);\n }\n }\n for (const [field, scalar] of Object.entries(\n model[\"~\"].state.scalars as Record<string, Scalar>\n )) {\n if (isTextFoldableScalar(scalar)) {\n textFoldable.add(field);\n }\n }\n return { uniqueColumns, addressableUnique, textFoldable };\n}\n\nfunction singleTargetModel(relation: AnyRelation): AnyModel | undefined {\n return relation[\"~\"].state.target.kind === \"model\"\n ? (relation[\"~\"].settleTarget() as AnyModel)\n : undefined;\n}\n\ninterface ResolvedJoin {\n readonly key: string;\n readonly many: boolean;\n}\n\n/**\n * Resolve the exact relation key declared on `baseModel` in `client.$schema`\n * matching a Better Auth join `{ from, to }` to `joinedModel`.\n *\n * Inspects the actual VibORM models so generated schemas, `usePlural`, custom\n * names, multi-FK pairs, and hand-authored schemas all work without guessing.\n * Returns `undefined` when no exact relation exists (Better Auth then runs its\n * fallback join query cleanly).\n */\nfunction resolveSchemaJoin(\n schema: Schema,\n baseModelName: string,\n joinedModelName: string,\n on: { readonly from: string; readonly to: string }\n): ResolvedJoin | undefined {\n const baseModel = schema[baseModelName]!;\n const joinedModel = schema[joinedModelName];\n if (!joinedModel) return undefined;\n\n const baseRelations = baseModel[\"~\"].state.relations as Record<\n string,\n AnyRelation\n >;\n const joinedRelations = joinedModel[\"~\"].state.relations as Record<\n string,\n AnyRelation\n >;\n\n // Case 1: base model owns the foreign key (`from` -> `joined.to`).\n for (const [key, relation] of Object.entries(baseRelations)) {\n const state = relation[\"~\"].state;\n const fk = state.foreignKey;\n if (\n fk &&\n fk.fields.length === 1 &&\n fk.references.length === 1 &&\n fk.fields[0] === on.from &&\n fk.references[0] === on.to &&\n singleTargetModel(relation) === joinedModel\n ) {\n return { key, many: false };\n }\n }\n\n // Case 2: joined model owns the foreign key (`to` -> `base.from`).\n // Every owning FK in a constructed VibORM schema has exactly one paired\n // inverse on its target model (enforced by R002/R009 at client creation).\n for (const relation of Object.values(joinedRelations)) {\n const state = relation[\"~\"].state;\n const fk = state.foreignKey;\n if (\n fk &&\n fk.fields.length === 1 &&\n fk.references.length === 1 &&\n fk.fields[0] === on.to &&\n fk.references[0] === on.from &&\n singleTargetModel(relation) === baseModel\n ) {\n const [key, inverse] = Object.entries(baseRelations).find(([, inv]) => {\n const invState = inv[\"~\"].state;\n return (\n !invState.foreignKey &&\n singleTargetModel(inv) === joinedModel &&\n invState.name === state.name\n );\n })!;\n return { key, many: inverse[\"~\"].state.cardinality === \"many\" };\n }\n }\n\n return undefined;\n}\n\ninterface ModelMeta {\n readonly model: string;\n readonly modelKey: string;\n readonly delegate: ModelDelegate;\n readonly whereFacts: WhereColumnFacts;\n readonly uniqueColumns: ReadonlySet<string>;\n readonly addressableUnique: ReadonlySet<string>;\n readonly fullRow: Selection;\n readonly joins: Map<string, ResolvedJoin | null>;\n}\n\ninterface ReadPlan {\n readonly select?: Selection;\n readonly include?: Inclusion;\n readonly rename: (found: Row) => Row;\n}\n\nconst PLAIN_READ: ReadPlan = { rename: identityRow };\n\nconst isUniqueScalarEquality = (\n clause: CleanedWhere,\n columns: ReadonlySet<string>\n): boolean =>\n clause.operator === \"eq\" &&\n clause.mode !== \"insensitive\" &&\n clause.value !== null &&\n clause.value !== undefined &&\n (clause.value as unknown) !== DbNull &&\n columns.has(clause.field);\n\nconst createOperations =\n (\n client: VibormAdapterClient,\n config: {\n readonly usePlural: boolean;\n readonly namedPolicy: ResolvedNamedPolicy;\n readonly schemaOptions: VibormSchemaOptions | undefined;\n }\n ): AdapterFactoryCustomizeAdapterCreator =>\n ({ options, schema, getDefaultModelName, getFieldName, getModelName }) => {\n const columns = (modelKey: string, fields: string[]): Selection =>\n Object.fromEntries(\n fields.map((field) => [getFieldName({ model: modelKey, field }), true])\n );\n\n // Precompute per-model metadata once per adapter instance so hot calls\n // avoid rebuilding column maps, closures, and key sets.\n const metaCache = new Map<string, ModelMeta>();\n const metaOf = (model: string): ModelMeta => {\n let cached = metaCache.get(model);\n if (cached) return cached;\n if (!Object.hasOwn(client.$schema, model)) {\n throw new Error(\n `vibormAdapter: the VibORM client has no model '${model}'. Regenerate its schema with createSchema.`\n );\n }\n const modelKey = getDefaultModelName(model);\n const baFields = schema[modelKey]!.fields;\n const nullableSet = new Set(\n Object.entries(baFields)\n .filter(\n ([field, attribute]) => field !== \"id\" && isNullable(attribute)\n )\n .map(([field, attribute]) => attribute.fieldName ?? field)\n );\n const { uniqueColumns, addressableUnique, textFoldable } =\n collectModelKeySets(client.$schema[model]!);\n cached = {\n model,\n modelKey,\n delegate: (client as unknown as Record<string, ModelDelegate>)[model]!,\n whereFacts: {\n nullable: (column) => nullableSet.has(column),\n supportsInsensitive: (column) => textFoldable.has(column),\n },\n uniqueColumns,\n addressableUnique,\n fullRow: columns(modelKey, [\"id\", ...Object.keys(baFields)]),\n joins: new Map(),\n };\n metaCache.set(model, cached);\n return cached;\n };\n\n const resolvedJoin = (\n meta: ModelMeta,\n joinedModel: string,\n on: { readonly from: string; readonly to: string }\n ): ResolvedJoin | undefined => {\n const cacheKey = `${joinedModel}\\0${on.from}\\0${on.to}`;\n let cached = meta.joins.get(cacheKey);\n if (cached === undefined) {\n cached =\n resolveSchemaJoin(client.$schema, meta.model, joinedModel, on) ??\n null;\n meta.joins.set(cacheKey, cached);\n }\n return cached ?? undefined;\n };\n\n /**\n * Whether `conditions` pin at most one row via a case-sensitive AND-only\n * equality on a single-column unique key.\n */\n const isUniqueWhere = (\n meta: ModelMeta,\n conditions: readonly CleanedWhere[]\n ): boolean => {\n if (conditions.length === 0) return false;\n if (conditions.some((clause) => clause.connector === \"OR\")) return false;\n return conditions.some((clause) =>\n isUniqueScalarEquality(clause, meta.uniqueColumns)\n );\n };\n\n /**\n * Build `include` (when no explicit `select` is given, hitting VibORM's\n * cached default projections) or `select` (when explicit fields are given).\n */\n const buildReadPlan = (\n meta: ModelMeta,\n select: string[] | undefined,\n join: JoinInput | undefined\n ): ReadPlan => {\n const own =\n select && select.length > 0\n ? columns(meta.modelKey, select)\n : undefined;\n if (!join) {\n return own ? { select: own, rename: identityRow } : PLAIN_READ;\n }\n const relations: Inclusion = {};\n const renames: [expectedKey: string, relationKey: string][] = [];\n let matched = 0;\n for (const [name, { on, relation, limit }] of Object.entries(join)) {\n const targetKey = getDefaultModelName(name);\n const targetModel = getModelName(targetKey);\n const match = resolvedJoin(meta, targetModel, on);\n if (!match) continue;\n matched += 1;\n relations[match.key] =\n match.many && relation !== \"one-to-one\" && limit !== undefined\n ? { take: limit }\n : true;\n if (name !== match.key) {\n renames.push([name, match.key]);\n }\n }\n if (matched === 0) {\n return own ? { select: own, rename: identityRow } : PLAIN_READ;\n }\n const rename =\n renames.length === 0\n ? identityRow\n : (found: Row) => {\n for (const [expectedKey, relKey] of renames) {\n found[expectedKey] = found[relKey];\n delete found[relKey];\n }\n return found;\n };\n if (own) {\n return { select: { ...own, ...relations }, rename };\n }\n return { include: relations, rename };\n };\n\n const namedArg = (\n operation: VibormAdapterOperation,\n meta: ModelMeta,\n shape: {\n readonly where?: readonly CleanedWhere[];\n readonly hasCustomSelect?: boolean;\n readonly hasJoin?: boolean;\n readonly hasOffset?: boolean;\n readonly updateFieldCount?: number;\n } = {}\n ): { named: boolean } | Record<never, never> => {\n const decision = resolveNamedOption(config.namedPolicy, {\n operation,\n model: meta.model,\n modelKey: meta.modelKey,\n ...shape,\n });\n return decision === undefined ? {} : { named: decision };\n };\n\n return {\n create: async <T>({ model, data }: AdapterArgs<\"create\">) => {\n const meta = metaOf(model);\n return (await meta.delegate.create({\n data,\n ...namedArg(\"create\", meta),\n })) as T;\n },\n\n findOne: async <T>({\n model,\n where: conditions,\n select,\n join,\n }: AdapterArgs<\"findOne\">) => {\n const meta = metaOf(model);\n const read = buildReadPlan(meta, select, join);\n const named = namedArg(\"findOne\", meta, {\n where: conditions,\n hasCustomSelect: Boolean(select && select.length > 0),\n hasJoin: Boolean(join && Object.keys(join).length > 0),\n });\n const uniqueClause =\n conditions.length === 1 &&\n isUniqueScalarEquality(conditions[0]!, meta.addressableUnique)\n ? conditions[0]!\n : undefined;\n const found = uniqueClause\n ? await meta.delegate.findUnique({\n where: { [uniqueClause.field]: uniqueClause.value },\n ...(read.select ? { select: read.select } : {}),\n ...(read.include ? { include: read.include } : {}),\n ...named,\n })\n : await meta.delegate.findFirst({\n where: convertWhere(conditions, meta.whereFacts),\n ...(read.select ? { select: read.select } : {}),\n ...(read.include ? { include: read.include } : {}),\n ...named,\n });\n return (found ? read.rename(found) : null) as T | null;\n },\n\n findMany: async <T>({\n model,\n where: conditions,\n limit,\n offset,\n sortBy,\n select,\n join,\n }: AdapterArgs<\"findMany\">) => {\n // VibORM reads a negative `take` from the end, as Prisma does.\n if (limit < 0) {\n throw new Error(\n `vibormAdapter: a limit of ${limit} rows is negative. Better Auth counts rows from the first, and SQL refuses it.`\n );\n }\n const meta = metaOf(model);\n const read = buildReadPlan(meta, select, join);\n const found = await meta.delegate.findMany({\n where: convertWhere(conditions, meta.whereFacts),\n take: limit,\n ...(offset ? { skip: offset } : {}),\n ...(sortBy\n ? {\n orderBy: {\n [getFieldName({ model: meta.modelKey, field: sortBy.field })]:\n sortBy.direction,\n },\n }\n : {}),\n ...(read.select ? { select: read.select } : {}),\n ...(read.include ? { include: read.include } : {}),\n ...namedArg(\"findMany\", meta, {\n where: conditions,\n hasCustomSelect: Boolean(select && select.length > 0),\n hasJoin: Boolean(join && Object.keys(join).length > 0),\n hasOffset: Boolean(offset),\n }),\n });\n return read.rename === identityRow\n ? (found as T[])\n : (found.map(read.rename) as T[]);\n },\n\n count: ({ model, where: conditions }) => {\n const meta = metaOf(model);\n return meta.delegate.count({\n where: convertWhere(conditions, meta.whereFacts),\n ...namedArg(\"count\", meta, { where: conditions }),\n });\n },\n\n update: async <T>({\n model,\n where: conditions,\n update,\n }: AdapterArgs<\"update\">) => {\n const meta = metaOf(model);\n const data = update as Row;\n const [updated] = await meta.delegate.updateMany({\n where: convertWhere(conditions, meta.whereFacts),\n data,\n select: meta.fullRow,\n ...(isUniqueWhere(meta, conditions) ? {} : { limit: 1 }),\n ...namedArg(\"update\", meta, {\n where: conditions,\n updateFieldCount: Object.keys(data).length,\n }),\n });\n return (updated ?? null) as T | null;\n },\n\n updateMany: async ({ model, where: conditions, update }) => {\n const meta = metaOf(model);\n return (\n await meta.delegate.updateMany({\n where: convertWhere(conditions, meta.whereFacts),\n data: update,\n ...namedArg(\"updateMany\", meta, {\n where: conditions,\n updateFieldCount: Object.keys(update).length,\n }),\n })\n ).count;\n },\n\n delete: async ({ model, where: conditions }) => {\n const meta = metaOf(model);\n await meta.delegate.deleteMany({\n where: convertWhere(conditions, meta.whereFacts),\n ...namedArg(\"delete\", meta, { where: conditions }),\n });\n },\n\n deleteMany: async ({ model, where: conditions }) => {\n const meta = metaOf(model);\n return (\n await meta.delegate.deleteMany({\n where: convertWhere(conditions, meta.whereFacts),\n ...namedArg(\"deleteMany\", meta, { where: conditions }),\n })\n ).count;\n },\n\n consumeOne: async <T>({\n model,\n where: conditions,\n }: AdapterArgs<\"consumeOne\">) => {\n const meta = metaOf(model);\n const [consumed] = await meta.delegate.deleteMany({\n where: convertWhere(conditions, meta.whereFacts),\n select: meta.fullRow,\n ...(isUniqueWhere(meta, conditions) ? {} : { limit: 1 }),\n ...namedArg(\"consumeOne\", meta, { where: conditions }),\n });\n return (consumed ?? null) as T | null;\n },\n\n incrementOne: async <T>({\n model,\n where: conditions,\n increment,\n set,\n }: AdapterArgs<\"incrementOne\">) => {\n const meta = metaOf(model);\n const deltas = Object.entries(increment).map(([field, delta]) => [\n field,\n { increment: delta },\n ]);\n const data: Row = { ...set, ...Object.fromEntries(deltas) };\n const [updated] = await meta.delegate.updateMany({\n where: convertWhere(conditions, meta.whereFacts),\n data,\n select: meta.fullRow,\n ...(isUniqueWhere(meta, conditions) ? {} : { limit: 1 }),\n ...namedArg(\"incrementOne\", meta, {\n where: conditions,\n updateFieldCount: Object.keys(data).length,\n }),\n });\n return (updated ?? null) as T | null;\n },\n\n createSchema: async ({ file, tables }) => {\n const numericIds =\n config.schemaOptions?.numericIds ??\n options.advanced?.database?.generateId === \"serial\";\n const usePlural = config.schemaOptions?.usePlural ?? config.usePlural;\n return {\n code: renderVibormSchema(tables, {\n ...config.schemaOptions,\n usePlural,\n numericIds,\n }),\n path: file ?? config.schemaOptions?.path ?? DEFAULT_SCHEMA_PATH,\n overwrite: true,\n };\n },\n };\n };\n\nconst BASE_FACTORY_CONFIG = {\n adapterId: \"viborm\",\n adapterName: \"VibORM Adapter\",\n // VibORM owns each dialect's spelling of JSON, arrays, dates, booleans,\n // and auto-increment integer primary keys.\n supportsJSON: true,\n supportsArrays: true,\n supportsDates: true,\n supportsBooleans: true,\n supportsNumericIds: true,\n supportsUUIDs: false,\n customTransformInput: ({ data, fieldAttributes, action }) => {\n if (fieldAttributes.type !== \"json\") return data;\n if (data === null) {\n if (isNullable(fieldAttributes)) return DbNull;\n return action === \"create\" || action === \"update\" ? JsonNull : DbNull;\n }\n if (\n (action === \"create\" || action === \"update\") &&\n isJsonSetEnvelope(data)\n ) {\n return { set: data };\n }\n return data;\n },\n} satisfies AdapterFactoryConfig;\n\n/**\n * Official Better Auth database adapter backed by a VibORM client.\n *\n * @example\n * ```ts\n * import { betterAuth } from \"better-auth\";\n * import { vibormAdapter } from \"viborm/better-auth\";\n *\n * export const auth = betterAuth({\n * database: vibormAdapter(db, { namedStatements: true }),\n * });\n * ```\n */\nexport function vibormAdapter(\n client: VibormAdapterClient,\n config: VibormAdapterConfig = {}\n) {\n const {\n debugLogs = false,\n usePlural = false,\n transaction,\n namedStatements,\n schema: schemaOptions,\n } = config;\n const namedPolicy = resolveNamedPolicy(namedStatements);\n const useTransactions =\n transaction ?? client.$driver?.supportsTransactions ?? true;\n\n return (options: BetterAuthOptions) => {\n const createFor = (\n targetClient: VibormAdapterClient,\n tx: AdapterFactoryConfig[\"transaction\"]\n ) =>\n createAdapterFactory({\n config: {\n ...BASE_FACTORY_CONFIG,\n debugLogs,\n usePlural,\n transaction: tx,\n },\n adapter: createOperations(targetClient, {\n usePlural,\n namedPolicy,\n schemaOptions,\n }),\n })(options);\n\n return createFor(\n client,\n useTransactions\n ? (run) => client.$transaction((tx) => run(createFor(tx, false)))\n : false\n );\n };\n}\n"],"mappings":"iPAqCA,MAAM,EAAiB,IAAI,IAAY,CACrC,SACA,UACA,WACA,QACA,SACA,aACA,SACA,aACA,aACA,eACD,CAAC,CAGI,EAAiE,CACrE,UACA,WACA,aACA,eACA,SACD,CAaK,EAAkC,CACtC,KAAM,MACN,OAAQ,IAAA,GACR,WAAY,IAAI,IACjB,CAEK,EAAoC,CACxC,KAAM,QACN,OAAQ,IAAA,GACR,WAAY,IAAI,IACjB,CAED,SAAgB,EACd,EACqB,CACrB,G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B,CACrC,IAAM,GACJ,EACA,IAEA,EAAqB,CACnB,OAAQ,CACN,GAAG,EACH,YACA,YACA,YAAa,EACd,CACD,QAAS,EAAiB,EAAc,CACtC,YACA,cACA,gBACD,CAAC,CACH,CAAC,CAAC,EAAQ,CAEb,OAAO,EACL,EACA,EACK,GAAQ,EAAO,aAAc,GAAO,EAAI,EAAU,EAAI,GAAM,CAAC,CAAC,CAC/D,GACL"}
@@ -0,0 +1,2 @@
1
+ import{m as e}from"./validation-ATmgN5RE.mjs";function t(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}function n(t,n,r,i){if(!(r===void 0||t.values.length<=r))throw new e(`Driver '${n}' cannot run ${i}: statement needs ${t.values.length} bind params (limit ${r}).`)}export{t as n,n as t};
2
+ //# sourceMappingURL=bind-parameter-capacity-BAFQM9Jt.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"bind-parameter-capacity-BMD-bxMO.mjs","names":[],"sources":["../src/drivers/bind-parameter-capacity.ts"],"sourcesContent":["import { UnsupportedOperationError } from \"@errors\";\nimport type { Sql } from \"@sql\";\n\n/** Normalize one driver's optional bind declaration into verified capacity. */\nexport function normalizedBindParameterLimit(\n limit: unknown\n): number | undefined {\n return typeof limit === \"number\" && Number.isInteger(limit) && limit > 0\n ? limit\n : undefined;\n}\n\n/** Refuse one materialized statement before it reaches provider I/O. */\nexport function assertStatementBindParameterCapacity(\n statement: Pick<Sql, \"values\">,\n driverName: string,\n limit: number | undefined,\n subject: string\n): void {\n if (limit === undefined || statement.values.length <= limit) return;\n throw new UnsupportedOperationError(\n `Driver '${driverName}' cannot execute this ${subject} because one indivisible statement needs ${statement.values.length} bound values, above the verified limit of ${limit}.`\n );\n}\n"],"mappings":"uFAIA,SAAgB,6BACd,EACoB,CACpB,OAAO,OAAO,GAAU,UAAY,OAAO,UAAU,EAAM,EAAI,EAAQ,EACnE,EACA,IAAA,GAIN,SAAgB,qCACd,EACA,EACA,EACA,EACM,CACF,SAAU,IAAA,IAAa,EAAU,OAAO,QAAU,GACtD,MAAM,IAAI,EACR,WAAW,EAAW,wBAAwB,EAAQ,2CAA2C,EAAU,OAAO,OAAO,6CAA6C,EAAM,GAC7K"}
1
+ {"version":3,"file":"bind-parameter-capacity-BAFQM9Jt.mjs","names":[],"sources":["../src/drivers/bind-parameter-capacity.ts"],"sourcesContent":["import { UnsupportedOperationError } from \"@errors\";\nimport type { Sql } from \"@sql\";\n\n/** Normalize one driver's optional bind declaration into verified capacity. */\nexport function normalizedBindParameterLimit(\n limit: unknown\n): number | undefined {\n return typeof limit === \"number\" && Number.isInteger(limit) && limit > 0\n ? limit\n : undefined;\n}\n\n/** Refuse one materialized statement before it reaches provider I/O. */\nexport function assertStatementBindParameterCapacity(\n statement: Pick<Sql, \"values\">,\n driverName: string,\n limit: number | undefined,\n subject: string\n): void {\n if (limit === undefined || statement.values.length <= limit) return;\n throw new UnsupportedOperationError(\n `Driver '${driverName}' cannot run ${subject}: statement needs ${statement.values.length} bind params (limit ${limit}).`\n );\n}\n"],"mappings":"8CAIA,SAAgB,EACd,EACoB,CACpB,OAAO,OAAO,GAAU,UAAY,OAAO,UAAU,EAAM,EAAI,EAAQ,EACnE,EACA,IAAA,GAIN,SAAgB,EACd,EACA,EACA,EACA,EACM,CACF,SAAU,IAAA,IAAa,EAAU,OAAO,QAAU,GACtD,MAAM,IAAI,EACR,WAAW,EAAW,eAAe,EAAQ,oBAAoB,EAAU,OAAO,OAAO,sBAAsB,EAAM,IACtH"}
@@ -1,4 +1,4 @@
1
- import { Na as TransactionOptionSupport, Ra as QueryExecutionContext, _ as DriverResultParser, f as MigrationSessionAttestation, g as PinnedSessionReservation, it as NoExtraDriverConfigKeys, l as Driver, ni as Schema, pi as LinkedClientConfig, st as VibORMClient, t as DatabaseAdapter, tt as DriverConfig, za as QueryResult } from "./database-adapter-BGqvjeEy.mjs";
1
+ import { $a as QueryExecutionContext, C as DriverResultParser, Di as LinkedClientConfig, Gr as Schema, Ja as TransactionOptionSupport, S as PinnedSessionReservation, eo as QueryResult, h as Driver, pt as VibORMClient, st as DriverConfig, t as DatabaseAdapter, ut as NoExtraDriverConfigKeys, v as MigrationSessionAttestation } from "./database-adapter-BMjJiBFm.mjs";
2
2
 
3
3
  //#region src/drivers/bun-sql/index.d.ts
4
4
 
package/dist/bun-sql.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{B as t,f as n,u as r}from"./error-mapping-B1-IWkCQ.mjs";import{o as i}from"./normalized-result-B8pifWS0.mjs";import{n as a}from"./client-DRpX3-vw.mjs";import{i as o,t as s}from"./pinned-session-DCoAZDOz.mjs";import{c,d as l,o as u,r as d,u as f}from"./driver-BIXhOH2_.mjs";import{t as p}from"./postgres-adapter-axapXX8d.mjs";import{n as m}from"./relation-bound-ku_cMdye.mjs";function normalizeBunSQLParams(e,t){let n;for(let r=0;r<t.length;r+=1){let i=t[r];Array.isArray(i)&&(n??=[...t],n[r]=e.array(i,`TEXT`).serializedValues)}return n??t}const h={parseField:(e,t,n)=>t===`int`&&e instanceof Int32Array?n(Array.from(e),t):n(e,t)},g={client:!0,databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0,migrationSessionAttestation:!0};var BunSQLDriver=class extends d{result=h;maxBindParametersPerStatement=65535;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`bun-sql`);let t=l(e);this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient&&(this.client=this.suppliedClient),p(this,t,e),u(this,`migrationSessionAttestation`,f(e))}migrationSessionEndpoints(){let{databaseUrl:e,options:t}=this.driverOptions,n=this.suppliedClient?.options;return[e,t?.hostname,n?.hostname,n?.url]}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let{SQL:e}=await import(`bun`);return this.driverOptions.databaseUrl?new e({...this.driverOptions.options,url:this.driverOptions.databaseUrl}):new e(this.driverOptions.options??{})}async closeClient(e){e!==this.suppliedClient&&await e.close()}async execute(e,t,n,r){let a=r?.operation??`execute`,o=await e.unsafe(t,normalizeBunSQLParams(e,n)).catch(e=>{throw m(this.adapter,e),e});return{rows:o,rowCount:i(o.count,{provider:`bun-sql`,operation:a})}}async executeRaw(e,t,n,r){let a=r?.operation??`executeRaw`,o=await e.unsafe(t,n);return{rows:o,rowCount:i(o.count,{provider:`bun-sql`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`Bun SQL acquires the connection inside sql.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said`}}async transaction(e,i,a){if(`savepoint`in e)throw r(this.driverName);return n({run:t=>e.begin(t),callback:i,phases:t(a),close:async()=>void 0})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`savepoint`in e)throw r(this.driverName);let t=await e.reserve();return{session:t,release:(n,r)=>o({driverName:this.driverName,discard:n,lost:r,reset:()=>t.unsafe(`SELECT pg_advisory_unlock_all()`),release:()=>t.release(),closeOwnedTransport:e===this.suppliedClient?void 0:async()=>{this.client=null,this.initPromise=null,await e.close({timeout:s/1e3})}})}}};function createClient(e){c(e,`bun-sql`,g);let{client:t,databaseUrl:n,options:r,pgvector:i,postgis:o}=e,s=l(e),u=f(e);return a(e,new BunSQLDriver({client:t,databaseUrl:n,options:r,pgvector:i,postgis:o,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:s,migrationSessionAttestation:u}))}export{BunSQLDriver,createClient};
1
+ import{B as e,f as t,u as n}from"./error-mapping-B9rSvgG9.mjs";import{o as r}from"./normalized-result-D7nVkF36.mjs";import{n as i}from"./client-D7sWgUt2.mjs";import{i as a,t as o}from"./pinned-session-Y7-2pRBJ.mjs";import{_ as s,h as c,p as l,r as u,v as d}from"./driver-lShUkDmf.mjs";import{t as f}from"./postgres-adapter-BpLizOaK.mjs";import{n as p}from"./relation-bound-CSNKLyDy.mjs";function m(e,t){let n;for(let r=0;r<t.length;r+=1){let i=t[r];Array.isArray(i)&&(n??=[...t],n[r]=e.array(i,`TEXT`).serializedValues)}return n??t}const h={parseField:(e,t,n)=>t===`int`&&e instanceof Int32Array?n(Array.from(e),t):n(e,t)},g={client:!0,databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0,migrationSessionAttestation:!0};var _=class extends u{static get name(){return`BunSQLDriver`}result=h;maxBindParametersPerStatement=65535;eg;eb;constructor(e={}){super(`postgresql`,`bun-sql`);let t=d(e);this.eg=e,this.eb=e.client,this.eb&&(this.client=this.eb),f(this,t,e),l(this,`migrationSessionAttestation`,s(e))}migrationSessionEndpoints(){let{databaseUrl:e,options:t}=this.eg,n=this.eb?.options;return[e,t?.hostname,n?.hostname,n?.url]}async initClient(){if(this.eb!==void 0)return this.eb;let{SQL:e}=await import(`bun`);return this.eg.databaseUrl?new e({...this.eg.options,url:this.eg.databaseUrl}):new e(this.eg.options??{})}async closeClient(e){e!==this.eb&&await e.close()}async execute(e,t,n,i){let a=i?.operation??`execute`,o=await e.unsafe(t,m(e,n)).catch(e=>{throw p(this.adapter,e),e});return{rows:o,rowCount:r(o.count,{provider:`bun-sql`,operation:a})}}async executeRaw(e,t,n,i){let a=i?.operation??`executeRaw`,o=await e.unsafe(t,n);return{rows:o,rowCount:r(o.count,{provider:`bun-sql`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`Bun SQL acquires the connection inside sql.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said`}}async transaction(r,i,a){if(`savepoint`in r)throw n(this.driverName);return t({run:e=>r.begin(e),callback:i,he:e(a),close:async()=>void 0})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`savepoint`in e)throw n(this.driverName);let t=await e.reserve();return{session:t,release:(n,r)=>a({driverName:this.driverName,discard:n,lost:r,reset:()=>t.unsafe(`SELECT pg_advisory_unlock_all()`),release:()=>t.release(),uu:e===this.eb?void 0:async()=>{this.client=null,this.initPromise=null,await e.close({timeout:o/1e3})}})}}};function v(e){c(e,`bun-sql`,g);let{client:t,databaseUrl:n,options:r,pgvector:a,postgis:o}=e,l=d(e),u=s(e);return i(e,new _({client:t,databaseUrl:n,options:r,pgvector:a,postgis:o,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:l,migrationSessionAttestation:u}))}export{_ as BunSQLDriver,v as createClient};
2
2
  //# sourceMappingURL=bun-sql.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"bun-sql.mjs","names":[],"sources":["../src/drivers/bun-sql/index.ts"],"sourcesContent":["/**\n * Bun SQL Driver\n *\n * Driver implementation for Bun's built-in PostgreSQL client.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n Driver,\n type DriverResultParser,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n type PinnedSessionReservation,\n releaseReservedPostgresSession,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { CLEANUP_BOUND_MS } from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN SQL\n// ============================================================\n\n// Bun's SQL type - we define inline to avoid requiring bun types at compile time\n// Every result is an array carrying its required provider row count.\ntype BunSQLResult<T> = T[] & { count: number };\n\ninterface BunSQL {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;\n unsafe<T = unknown>(\n sql: string,\n params?: unknown[]\n ): Promise<BunSQLResult<T>>;\n array(\n values: unknown[],\n typeNameOrTypeID?: string\n ): { readonly serializedValues: string };\n begin<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;\n /** `timeout` in seconds: past it, open connections are closed anyway. */\n close(options?: { readonly timeout?: number }): Promise<void>;\n reserve(): Promise<BunSQLReservedConnection>;\n /** Bun's resolved client options; migration admission reads its host. */\n readonly options?: { readonly hostname?: unknown; readonly url?: unknown };\n}\n\ninterface BunSQLTransaction {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;\n unsafe<T = unknown>(\n sql: string,\n params?: unknown[]\n ): Promise<BunSQLResult<T>>;\n array(\n values: unknown[],\n typeNameOrTypeID?: string\n ): { readonly serializedValues: string };\n savepoint<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;\n}\n\n/**\n * Bun's `unsafe()` path does not invoke its array helper: a plain JavaScript\n * array is bound as `Array#toString()`, which is not PostgreSQL array input\n * syntax. The adapter has already validated ORM list members, so let Bun's own\n * PostgreSQL encoder escape their flat scalar text and leave the statement's\n * column context to infer the concrete array type.\n *\n * Verbatim raw execution deliberately bypasses this conversion. A verbatim\n * caller owns the provider representation and receives Bun's ordinary\n * `unsafe()` semantics; a tagged safe-raw fragment stays on typed execution.\n */\nfunction normalizeBunSQLParams(\n client: BunSQL | BunSQLTransaction,\n params: unknown[]\n): unknown[] {\n let normalized: unknown[] | undefined;\n for (let index = 0; index < params.length; index += 1) {\n const param = params[index];\n if (!Array.isArray(param)) continue;\n normalized ??= [...params];\n normalized[index] = client.array(param, \"TEXT\").serializedValues;\n }\n return normalized ?? params;\n}\n\n/** Bun decodes PostgreSQL `integer[]` as `Int32Array`, not `Array`. */\nconst bunSQLResultParser: DriverResultParser = {\n parseField: (value, scalarType, next) => {\n if (scalarType === \"int\" && value instanceof Int32Array) {\n return next(Array.from(value), scalarType);\n }\n return next(value, scalarType);\n },\n};\n\n/**\n * Bun's `ReservedSQL` is an `SQL` bound to one connection, plus `release()` —\n * not a reduced surface. Declaring it that way is both faithful and load-\n * bearing: a reserved connection is what {@link BunSQLDriver.pinnedSession}\n * hands to the pinned view as its client, and the view's transaction control\n * runs `BEGIN`/`COMMIT` on it through the same `unsafe` path every statement\n * uses.\n */\ninterface BunSQLReservedConnection extends BunSQL {\n release(): void;\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLOptions {\n hostname?: string;\n port?: number;\n username?: string;\n password?: string;\n database?: string;\n tls?: boolean | object;\n max?: number;\n idleTimeout?: number;\n maxLifetime?: number;\n}\n\nexport interface BunSQLDriverOptions {\n client?: BunSQL;\n databaseUrl?: string;\n options?: BunSQLOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. PlanetScale Neki refuses more than 256: Bun SQL keeps no startup message, so set 256 there; absent, Neki's first refusal teaches it 256 (that statement fails). A stated bound always wins. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Your claim, at your risk, that every connection this client opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport type BunSQLClientConfig<C extends DriverConfig> = BunSQLDriverOptions &\n C;\n\nconst BUN_SQL_CONFIG_KEYS: Record<keyof BunSQLDriverOptions, true> = {\n client: true,\n databaseUrl: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n namespace: true,\n migrationSessionAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLDriver extends Driver<BunSQL, BunSQLTransaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly result: DriverResultParser = bunSQLResultParser;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n private readonly driverOptions: BunSQLDriverOptions;\n /**\n * The EXACT transport the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's transport while believing it had made its own.\n */\n private readonly suppliedClient: BunSQL | undefined;\n\n constructor(options: BunSQLDriverOptions = {}) {\n super(\"postgresql\", \"bun-sql\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n }\n\n installPostgresAdapter(this, namespace, options);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's client connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const { databaseUrl, options } = this.driverOptions;\n const supplied = this.suppliedClient?.options;\n return [databaseUrl, options?.hostname, supplied?.hostname, supplied?.url];\n }\n\n /**\n * The transport this driver connects through.\n *\n * A caller's transport is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second one behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<BunSQL> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const { SQL } = await import(\"bun\");\n\n if (this.driverOptions.databaseUrl) {\n return new SQL({\n ...this.driverOptions.options,\n url: this.driverOptions.databaseUrl,\n }) as unknown as BunSQL;\n }\n\n return new SQL(this.driverOptions.options ?? {}) as unknown as BunSQL;\n }\n\n /**\n * A supplied transport belongs to the caller, who may be sharing it with\n * other clients — two schema-scoped estates over one transport is the\n * documented shape — and §5.3's rule is that VibORM never changes a caller's\n * connection state. `$disconnect()` used to close it regardless, so\n * disconnecting one client tore down every other consumer of that transport.\n *\n * The test is on the transport's IDENTITY against what construction\n * captured, so it answers for the transport actually being closed rather than\n * for whatever the caller's record says now.\n */\n protected async closeClient(sql: BunSQL): Promise<void> {\n if (sql === this.suppliedClient) {\n return;\n }\n await sql.close();\n }\n\n protected async execute<T>(\n client: BunSQL | BunSQLTransaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n // Bun SQL keeps no parameter status: Neki's bound is learned from its\n // refusal, and the statements built after it fit.\n const result = await client\n .unsafe<T>(sql, normalizeBunSQLParams(client, params))\n .catch((error: unknown) => {\n learnRelationLimit(this.adapter, error);\n throw error;\n });\n return {\n rows: result,\n rowCount: normalizeProviderRowCount(result.count, {\n provider: \"bun-sql\",\n operation,\n }),\n };\n }\n\n protected async executeRaw<T>(\n client: BunSQL | BunSQLTransaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const result = await client.unsafe<T>(sql, params);\n return {\n rows: result,\n rowCount: normalizeProviderRowCount(result.count, {\n provider: \"bun-sql\",\n operation,\n }),\n };\n }\n\n /**\n * Bun's `sql.begin()` owns BEGIN and connection acquisition, so the isolation\n * level goes in as the transaction's first statement and there is no\n * acquisition step VibORM can bound.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Bun SQL acquires the connection inside sql.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said\",\n };\n }\n\n protected async transaction<T>(\n client: BunSQL | BunSQLTransaction,\n fn: (tx: BunSQLTransaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (\"savepoint\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n return runProviderManagedTransaction({\n run: (callback) => client.begin(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * One `reserve()` result — plan §3.5's pinned producer for Bun SQL, and the\n * producer its transaction control uses too, because the pinned view opens\n * `BEGIN`/`COMMIT` on this exact connection.\n *\n * Bun exposes only `release()` for a reserved connection — the same shape\n * postgres.js has — so a condemned session takes the same rule: reset with\n * `pg_advisory_unlock_all()`, and when that reset fails, abandoned rather\n * than returned to a pool with a lock state nobody can account for.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<BunSQL | BunSQLTransaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"savepoint\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const reserved = await client.reserve();\n return {\n session: reserved,\n release: (discard, lost) =>\n releaseReservedPostgresSession({\n driverName: this.driverName,\n discard,\n lost,\n reset: () => reserved.unsafe(\"SELECT pg_advisory_unlock_all()\"),\n release: () => reserved.release(),\n // Settled at construction, never re-read: see `suppliedClient`.\n closeOwnedTransport:\n client === this.suppliedClient\n ? undefined\n : async () => {\n // Withdrawn BEFORE the close, never after it: see the\n // postgres.js driver, which has the same shape and the same\n // reason — a rejecting `close()` used to leave this condemned\n // transport installed for the next ordinary query.\n this.client = null;\n this.initPromise = null;\n await client.close({ timeout: CLEANUP_BOUND_MS / 1000 });\n },\n }),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: BunSQLClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, BunSQLDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: BunSQLDriver }\n >]: LinkedClientConfig<C & { driver: BunSQLDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"bun-sql\", BUN_SQL_CONFIG_KEYS);\n const { client, databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n const migrationSessionAttestation =\n resolveMigrationSessionAttestationOption(config);\n\n const driver = new BunSQLDriver({\n client,\n databaseUrl,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n migrationSessionAttestation,\n });\n\n return createClientFromDriverConfig<S, C, BunSQLDriver>(config, driver);\n}\n"],"mappings":"uaAyFA,SAAS,sBACP,EACA,EACW,CACX,IAAI,EACJ,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAO,OAAQ,GAAS,EAAG,CACrD,IAAM,EAAQ,EAAO,GAChB,MAAM,QAAQ,EAAM,GACzB,IAAe,CAAC,GAAG,EAAO,CAC1B,EAAW,GAAS,EAAO,MAAM,EAAO,OAAO,CAAC,kBAElD,OAAO,GAAc,EAIvB,MAAM,EAAyC,CAC7C,YAAa,EAAO,EAAY,IAC1B,IAAe,OAAS,aAAiB,WACpC,EAAK,MAAM,KAAK,EAAM,CAAE,EAAW,CAErC,EAAK,EAAO,EAAW,CAEjC,CAsDK,EAA+D,CACnE,OAAQ,GACR,YAAa,GACb,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,GACtB,sBAAuB,GACvB,UAAW,GACX,4BAA6B,GAC9B,CAMD,IAAa,aAAb,cAAkC,CAAkC,CAElE,OAAsC,EACtC,8BAA6D,MAE7D,cAQA,eAEA,YAAY,EAA+B,EAAE,CAAE,CAC7C,MAAM,aAAc,UAAU,CAC9B,IAAM,EAAY,EAAuB,EAAQ,CACjD,KAAK,cAAgB,EACrB,KAAK,eAAiB,EAAQ,OAE1B,KAAK,iBACP,KAAK,OAAS,KAAK,gBAGrB,EAAuB,KAAM,EAAW,EAAQ,CAChD,EACE,KACA,8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,CAG9C,MAAO,SAAY,IAAA,GACpB,CAAC,CAaJ,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,cAAe,EACjB,MAAM,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAW,MAAM,EAAO,SAAS,CACvC,MAAO,CACL,QAAS,EACT,SAAU,EAAS,IACjB,EAA+B,CAC7B,WAAY,KAAK,WACjB,UACA,OACA,UAAa,EAAS,OAAO,kCAAkC,CAC/D,YAAe,EAAS,SAAS,CAEjC,oBACE,IAAW,KAAK,eACZ,IAAA,GACA,SAAY,CAKV,KAAK,OAAS,KACd,KAAK,YAAc,KACnB,MAAM,EAAO,MAAM,CAAE,QAAS,EAAmB,IAAM,CAAC,EAEjE,CAAC,CACL,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,UAAW,EAAoB,CACrE,GAAM,CAAE,SAAQ,cAAa,UAAS,WAAU,WAAY,EACtD,EAAY,EAAuB,EAAO,CAC1C,EACJ,EAAyC,EAAO,CAclD,OAAO,EAAiD,EAZzC,IAAI,aAAa,CAC9B,SACA,cACA,UACA,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC9B,YACA,8BACD,CAAC,CAEqE"}
1
+ {"version":3,"file":"bun-sql.mjs","names":[],"sources":["../src/drivers/bun-sql/index.ts"],"sourcesContent":["/**\n * Bun SQL Driver\n *\n * Driver implementation for Bun's built-in PostgreSQL client.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n Driver,\n type DriverResultParser,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n type PinnedSessionReservation,\n releaseReservedPostgresSession,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { CLEANUP_BOUND_MS } from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN SQL\n// ============================================================\n\n// Bun's SQL type - we define inline to avoid requiring bun types at compile time\n// Every result is an array carrying its required provider row count.\ntype BunSQLResult<T> = T[] & { count: number };\n\ninterface BunSQL {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;\n unsafe<T = unknown>(\n sql: string,\n params?: unknown[]\n ): Promise<BunSQLResult<T>>;\n array(\n values: unknown[],\n typeNameOrTypeID?: string\n ): { readonly serializedValues: string };\n begin<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;\n /** `timeout` in seconds: past it, open connections are closed anyway. */\n close(options?: { readonly timeout?: number }): Promise<void>;\n reserve(): Promise<BunSQLReservedConnection>;\n /** Bun's resolved client options; migration admission reads its host. */\n readonly options?: { readonly hostname?: unknown; readonly url?: unknown };\n}\n\ninterface BunSQLTransaction {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;\n unsafe<T = unknown>(\n sql: string,\n params?: unknown[]\n ): Promise<BunSQLResult<T>>;\n array(\n values: unknown[],\n typeNameOrTypeID?: string\n ): { readonly serializedValues: string };\n savepoint<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;\n}\n\n/**\n * Bun's `unsafe()` path does not invoke its array helper: a plain JavaScript\n * array is bound as `Array#toString()`, which is not PostgreSQL array input\n * syntax. The adapter has already validated ORM list members, so let Bun's own\n * PostgreSQL encoder escape their flat scalar text and leave the statement's\n * column context to infer the concrete array type.\n *\n * Verbatim raw execution deliberately bypasses this conversion. A verbatim\n * caller owns the provider representation and receives Bun's ordinary\n * `unsafe()` semantics; a tagged safe-raw fragment stays on typed execution.\n */\nfunction normalizeBunSQLParams(\n client: BunSQL | BunSQLTransaction,\n params: unknown[]\n): unknown[] {\n let normalized: unknown[] | undefined;\n for (let index = 0; index < params.length; index += 1) {\n const param = params[index];\n if (!Array.isArray(param)) continue;\n normalized ??= [...params];\n normalized[index] = client.array(param, \"TEXT\").serializedValues;\n }\n return normalized ?? params;\n}\n\n/** Bun decodes PostgreSQL `integer[]` as `Int32Array`, not `Array`. */\nconst bunSQLResultParser: DriverResultParser = {\n parseField: (value, scalarType, next) => {\n if (scalarType === \"int\" && value instanceof Int32Array) {\n return next(Array.from(value), scalarType);\n }\n return next(value, scalarType);\n },\n};\n\n/**\n * Bun's `ReservedSQL` is an `SQL` bound to one connection, plus `release()` —\n * not a reduced surface. Declaring it that way is both faithful and load-\n * bearing: a reserved connection is what {@link BunSQLDriver.pinnedSession}\n * hands to the pinned view as its client, and the view's transaction control\n * runs `BEGIN`/`COMMIT` on it through the same `unsafe` path every statement\n * uses.\n */\ninterface BunSQLReservedConnection extends BunSQL {\n release(): void;\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLOptions {\n hostname?: string;\n port?: number;\n username?: string;\n password?: string;\n database?: string;\n tls?: boolean | object;\n max?: number;\n idleTimeout?: number;\n maxLifetime?: number;\n}\n\nexport interface BunSQLDriverOptions {\n client?: BunSQL;\n databaseUrl?: string;\n options?: BunSQLOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. PlanetScale Neki refuses more than 256: Bun SQL keeps no startup message, so set 256 there; absent, Neki's first refusal teaches it 256 (that statement fails). A stated bound always wins. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Your claim, at your risk, that every connection this client opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport type BunSQLClientConfig<C extends DriverConfig> = BunSQLDriverOptions &\n C;\n\nconst BUN_SQL_CONFIG_KEYS: Record<keyof BunSQLDriverOptions, true> = {\n client: true,\n databaseUrl: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n namespace: true,\n migrationSessionAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLDriver extends Driver<BunSQL, BunSQLTransaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly result: DriverResultParser = bunSQLResultParser;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n private readonly driverOptions: BunSQLDriverOptions;\n /**\n * The EXACT transport the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's transport while believing it had made its own.\n */\n private readonly suppliedClient: BunSQL | undefined;\n\n constructor(options: BunSQLDriverOptions = {}) {\n super(\"postgresql\", \"bun-sql\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n }\n\n installPostgresAdapter(this, namespace, options);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's client connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const { databaseUrl, options } = this.driverOptions;\n const supplied = this.suppliedClient?.options;\n return [databaseUrl, options?.hostname, supplied?.hostname, supplied?.url];\n }\n\n /**\n * The transport this driver connects through.\n *\n * A caller's transport is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second one behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<BunSQL> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const { SQL } = await import(\"bun\");\n\n if (this.driverOptions.databaseUrl) {\n return new SQL({\n ...this.driverOptions.options,\n url: this.driverOptions.databaseUrl,\n }) as unknown as BunSQL;\n }\n\n return new SQL(this.driverOptions.options ?? {}) as unknown as BunSQL;\n }\n\n /**\n * A supplied transport belongs to the caller, who may be sharing it with\n * other clients — two schema-scoped estates over one transport is the\n * documented shape — and §5.3's rule is that VibORM never changes a caller's\n * connection state. `$disconnect()` used to close it regardless, so\n * disconnecting one client tore down every other consumer of that transport.\n *\n * The test is on the transport's IDENTITY against what construction\n * captured, so it answers for the transport actually being closed rather than\n * for whatever the caller's record says now.\n */\n protected async closeClient(sql: BunSQL): Promise<void> {\n if (sql === this.suppliedClient) {\n return;\n }\n await sql.close();\n }\n\n protected async execute<T>(\n client: BunSQL | BunSQLTransaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n // Bun SQL keeps no parameter status: Neki's bound is learned from its\n // refusal, and the statements built after it fit.\n const result = await client\n .unsafe<T>(sql, normalizeBunSQLParams(client, params))\n .catch((error: unknown) => {\n learnRelationLimit(this.adapter, error);\n throw error;\n });\n return {\n rows: result,\n rowCount: normalizeProviderRowCount(result.count, {\n provider: \"bun-sql\",\n operation,\n }),\n };\n }\n\n protected async executeRaw<T>(\n client: BunSQL | BunSQLTransaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const result = await client.unsafe<T>(sql, params);\n return {\n rows: result,\n rowCount: normalizeProviderRowCount(result.count, {\n provider: \"bun-sql\",\n operation,\n }),\n };\n }\n\n /**\n * Bun's `sql.begin()` owns BEGIN and connection acquisition, so the isolation\n * level goes in as the transaction's first statement and there is no\n * acquisition step VibORM can bound.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Bun SQL acquires the connection inside sql.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said\",\n };\n }\n\n protected async transaction<T>(\n client: BunSQL | BunSQLTransaction,\n fn: (tx: BunSQLTransaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (\"savepoint\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n return runProviderManagedTransaction({\n run: (callback) => client.begin(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * One `reserve()` result — plan §3.5's pinned producer for Bun SQL, and the\n * producer its transaction control uses too, because the pinned view opens\n * `BEGIN`/`COMMIT` on this exact connection.\n *\n * Bun exposes only `release()` for a reserved connection — the same shape\n * postgres.js has — so a condemned session takes the same rule: reset with\n * `pg_advisory_unlock_all()`, and when that reset fails, abandoned rather\n * than returned to a pool with a lock state nobody can account for.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<BunSQL | BunSQLTransaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"savepoint\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const reserved = await client.reserve();\n return {\n session: reserved,\n release: (discard, lost) =>\n releaseReservedPostgresSession({\n driverName: this.driverName,\n discard,\n lost,\n reset: () => reserved.unsafe(\"SELECT pg_advisory_unlock_all()\"),\n release: () => reserved.release(),\n // Settled at construction, never re-read: see `suppliedClient`.\n closeOwnedTransport:\n client === this.suppliedClient\n ? undefined\n : async () => {\n // Withdrawn BEFORE the close, never after it: see the\n // postgres.js driver, which has the same shape and the same\n // reason — a rejecting `close()` used to leave this condemned\n // transport installed for the next ordinary query.\n this.client = null;\n this.initPromise = null;\n await client.close({ timeout: CLEANUP_BOUND_MS / 1000 });\n },\n }),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: BunSQLClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, BunSQLDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: BunSQLDriver }\n >]: LinkedClientConfig<C & { driver: BunSQLDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"bun-sql\", BUN_SQL_CONFIG_KEYS);\n const { client, databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n const migrationSessionAttestation =\n resolveMigrationSessionAttestationOption(config);\n\n const driver = new BunSQLDriver({\n client,\n databaseUrl,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n migrationSessionAttestation,\n });\n\n return createClientFromDriverConfig<S, C, BunSQLDriver>(config, driver);\n}\n"],"mappings":"mYAyFA,SAAS,EACP,EACA,EACW,CACX,IAAI,EACJ,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAO,OAAQ,GAAS,EAAG,CACrD,IAAM,EAAQ,EAAO,GAChB,MAAM,QAAQ,EAAM,GACzB,IAAe,CAAC,GAAG,EAAO,CAC1B,EAAW,GAAS,EAAO,MAAM,EAAO,OAAO,CAAC,kBAElD,OAAO,GAAc,EAIvB,MAAM,EAAyC,CAC7C,YAAa,EAAO,EAAY,IAC1B,IAAe,OAAS,aAAiB,WACpC,EAAK,MAAM,KAAK,EAAM,CAAE,EAAW,CAErC,EAAK,EAA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uB,EAAO,sBAC9B,YACA,8BACD,CAAC,CAEqE"}
@@ -1,4 +1,4 @@
1
- import { Na as TransactionOptionSupport, Ra as QueryExecutionContext, _ as DriverResultParser, it as NoExtraDriverConfigKeys, l as Driver, m as SqliteMigrationCapability, ni as Schema, pi as LinkedClientConfig, st as VibORMClient, t as DatabaseAdapter, tt as DriverConfig, za as QueryResult } from "./database-adapter-BGqvjeEy.mjs";
1
+ import { $a as QueryExecutionContext, C as DriverResultParser, Di as LinkedClientConfig, Gr as Schema, Ja as TransactionOptionSupport, b as SqliteMigrationCapability, eo as QueryResult, h as Driver, pt as VibORMClient, st as DriverConfig, t as DatabaseAdapter, ut as NoExtraDriverConfigKeys } from "./database-adapter-BMjJiBFm.mjs";
2
2
 
3
3
  //#region src/drivers/bun-sqlite/index.d.ts
4
4
 
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,r as n}from"./validation--qS7OPmg.mjs";import{n as r}from"./client-DRpX3-vw.mjs";import{c as i,i as a,p as o,r as s}from"./driver-BIXhOH2_.mjs";import{a as c,c as l,i as u,l as d,n as f,s as p,t as m}from"./sqlite-utils-BRvbmlQ1.mjs";import{t as h}from"./sqlite-adapter-Ad0d-m2t.mjs";function requireSafeIntegers(e){if(typeof e.safeIntegers!=`function`)throw new t(`bun:sqlite`,`Statement.safeIntegers`,`This Bun build cannot read INTEGER columns as BigInt, so any value past 2^53 would come back silently rounded. Upgrade to Bun 1.1.14 or newer.`);return e}function reusesStatements(e){let t;for(let n=Object.getPrototypeOf(e);n;n=Object.getPrototypeOf(n))Object.hasOwn(n,`prepare`)&&(t=n.prepare);return e.prepare===t}const g=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function convertValuesForBunSQLite(e){return e.map(e=>{let t=f(e);if(typeof t==`string`&&g.test(t))throw TypeError(`bun:sqlite cannot preserve unpaired UTF-16 surrogates; the parameter was refused before dispatch.`);return t instanceof Uint8Array||!u(t)?t:l(t)})}const _={client:!0,dataDir:!0,options:!0};var BunSQLiteDriver=class extends s{adapter=new h;maxBindParametersPerStatement=32766;result=d;sqliteMigrationCapability=a;serializeTransactions=!0;driverOptions;suppliedClient;busyTimeout;constructor(e={}){if(super(`sqlite`,`bun-sqlite`),this.driverOptions=e,this.busyTimeout=e.options?.timeout??5e3,!Number.isSafeInteger(this.busyTimeout)||this.busyTimeout<0)throw new n(`The bun-sqlite "timeout" option must be a non-negative integer number of milliseconds.`,{meta:{driver:`bun-sqlite`,operation:`configuration`}});if(this.suppliedClient=e.client,this.suppliedClient){let e=this.suppliedClient.query(`PRAGMA foreign_keys`).get();if(!e||typeof e!=`object`||Reflect.get(e,`foreign_keys`)!==1)throw new n(`A supplied bun:sqlite Database must enable PRAGMA foreign_keys = ON before wrapping.`,{meta:{driver:`bun-sqlite`}});this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:o(this.suppliedClient)})}}async initClient(){if(this.suppliedClient)return this.suppliedClient;let{Database:e}=await import(`bun:sqlite`),t=this.driverOptions.dataDir??`:memory:`,{timeout:n,...r}=this.driverOptions.options??{},i=Object.keys(r).length===0?new e(t):new e(t,r);return i.exec(`PRAGMA foreign_keys = ON`),i.exec(`PRAGMA busy_timeout = ${this.busyTimeout}`),i}async closeClient(e){e!==this.suppliedClient&&e.close()}async execute(e,t,n,r){let i=convertValuesForBunSQLite(n);return this.runStatement(e,t,i,r?.model!==`$raw`)}async executeRaw(e,t,n){let r=n?convertValuesForBunSQLite(n):void 0;return this.runStatement(e,t,r,!1)}runStatement(e,t,n,r){let i=r&&reusesStatements(e)?e.query(t):e.prepare(t);if(i.columnNames.length>0){requireSafeIntegers(i).safeIntegers(!0);let e=n?i.all(...n):i.all();return{rows:r?e:c(e),rowCount:e.length}}return{rows:[],rowCount:(n?i.run(...n):i.run()).changes}}transactionOptionSupport(){return m}async transaction(e,t,n){return p(e,t,n)}};function createClient(e){i(e,`bun-sqlite`,_,{databaseUrl:`pass the database file as dataDir`});let{client:t,dataDir:n,options:a}=e;return r(e,new BunSQLiteDriver({client:t,dataDir:n,options:a}))}export{BunSQLiteDriver,createClient};
1
+ import{a as e,r as t}from"./validation-ATmgN5RE.mjs";import{n}from"./client-D7sWgUt2.mjs";import{t as r}from"./sqlite-adapter-Cb-SJw2f.mjs";import{h as i,i as a,o,r as s}from"./driver-lShUkDmf.mjs";import{a as c,c as l,i as u,l as d,n as f,s as p,t as m}from"./sqlite-utils-Bfmtkt1b.mjs";function h(t){if(typeof t.safeIntegers!=`function`)throw new e(`bun:sqlite`,`Statement.safeIntegers`,`This Bun build cannot read INTEGER columns as BigInt, so any value past 2^53 would come back silently rounded. Upgrade to Bun 1.1.14 or newer.`);return t}function g(e){let t;for(let n=Object.getPrototypeOf(e);n;n=Object.getPrototypeOf(n))Object.hasOwn(n,`prepare`)&&(t=n.prepare);return e.prepare===t}const _=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function v(e){return e.map(e=>{let t=f(e);if(typeof t==`string`&&_.test(t))throw TypeError(`bun:sqlite cannot preserve unpaired UTF-16 surrogates; the parameter was refused before dispatch.`);return t instanceof Uint8Array||!u(t)?t:l(t)})}const y={client:!0,dataDir:!0,options:!0};var b=class extends s{static get name(){return`BunSQLiteDriver`}adapter=new r;maxBindParametersPerStatement=32766;result=d;sqliteMigrationCapability=a;serializeTransactions=!0;eg;eb;gg;constructor(e={}){if(super(`sqlite`,`bun-sqlite`),this.eg=e,this.gg=e.options?.timeout??5e3,!Number.isSafeInteger(this.gg)||this.gg<0)throw new t(`The bun-sqlite "timeout" option must be a non-negative integer number of milliseconds.`,{meta:{driver:`bun-sqlite`,operation:`configuration`}});if(this.eb=e.client,this.eb){let e=this.eb.query(`PRAGMA foreign_keys`).get();if(!e||typeof e!=`object`||Reflect.get(e,`foreign_keys`)!==1)throw new t(`A supplied bun:sqlite Database must enable PRAGMA foreign_keys = ON before wrapping.`,{meta:{driver:`bun-sqlite`}});this.client=this.eb,Object.defineProperty(this,`connectionQueue`,{value:o(this.eb)})}}async initClient(){if(this.eb)return this.eb;let{Database:e}=await import(`bun:sqlite`),t=this.eg.dataDir??`:memory:`,{timeout:n,...r}=this.eg.options??{},i=Object.keys(r).length===0?new e(t):new e(t,r);return i.exec(`PRAGMA foreign_keys = ON`),i.exec(`PRAGMA busy_timeout = ${this.gg}`),i}async closeClient(e){e!==this.eb&&e.close()}async execute(e,t,n,r){let i=v(n);return this.xp(e,t,i,r?.model!==`$raw`)}async executeRaw(e,t,n){let r=n?v(n):void 0;return this.xp(e,t,r,!1)}xp(e,t,n,r){let i=r&&g(e)?e.query(t):e.prepare(t);if(i.columnNames.length>0){h(i).safeIntegers(!0);let e=n?i.all(...n):i.all();return{rows:r?e:c(e),rowCount:e.length}}return{rows:[],rowCount:(n?i.run(...n):i.run()).changes}}transactionOptionSupport(){return m}async transaction(e,t,n){return p(e,t,n)}};function x(e){i(e,`bun-sqlite`,y,{databaseUrl:`pass the database file as dataDir`});let{client:t,dataDir:r,options:a}=e;return n(e,new b({client:t,dataDir:r,options:a}))}export{b as BunSQLiteDriver,x as createClient};
2
2
  //# sourceMappingURL=bun-sqlite.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"bun-sqlite.mjs","names":[],"sources":["../src/drivers/bun-sqlite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n LOCAL_SQLITE_TRANSACTION_SUPPORT,\n normalizeSQLiteRawRows,\n runLocalSQLiteTransaction,\n} from \"../shared/sqlite-utils\";\n/**\n * Bun SQLite Driver\n *\n * Driver implementation for Bun's built-in SQLite (bun:sqlite).\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, FeatureNotSupportedError } from \"@errors\";\nimport {\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n SQLITE_MIGRATION_CAPABILITY,\n} from \"../driver\";\nimport {\n convertValueForSQLite,\n isSQLiteBinaryValue,\n sqliteBinaryToUint8Array,\n sqliteResultParser,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN:SQLITE\n// ============================================================\n\n// Bun's Database type - we define inline to avoid requiring bun types at compile time\ninterface BunSQLiteDatabase {\n query<T = unknown>(sql: string): BunSQLiteStatement<T>;\n prepare<T = unknown>(sql: string): BunSQLiteStatement<T>;\n run(sql: string, ...params: unknown[]): void;\n exec(sql: string): void;\n readonly inTransaction: boolean;\n close(): void;\n transaction<T>(fn: () => T): () => T;\n}\n\ninterface BunSQLiteStatement<T = unknown> {\n readonly columnNames: string[];\n all(...params: unknown[]): T[];\n get(...params: unknown[]): T | null;\n run(...params: unknown[]): {\n changes: number;\n lastInsertRowid: number | bigint;\n };\n /**\n * Reads INTEGER columns as BigInt instead of lossy JS numbers. Present on\n * `bun:sqlite` statements since Bun 1.1.14; the driver refuses to read\n * rather than return corrupted values when it is missing.\n */\n safeIntegers(safe: boolean): BunSQLiteStatement<T>;\n values(...params: unknown[]): unknown[][];\n}\n\n/**\n * `safeIntegers()` is what keeps an INTEGER past 2^53 from being rounded on\n * the way out of SQLite. A `bun:sqlite` old enough to lack it cannot answer\n * the query truthfully, so the read is refused instead of silently returning\n * a corrupted number — the one outcome that must never ship.\n */\nfunction requireSafeIntegers<T>(\n stmt: BunSQLiteStatement<T>\n): BunSQLiteStatement<T> {\n if (typeof stmt.safeIntegers !== \"function\") {\n throw new FeatureNotSupportedError(\n \"bun:sqlite\",\n \"Statement.safeIntegers\",\n \"This Bun build cannot read INTEGER columns as BigInt, so any value past 2^53 would come back silently rounded. Upgrade to Bun 1.1.14 or newer.\"\n );\n }\n return stmt;\n}\n\n/**\n * Typed statements come from `bun:sqlite`'s own bounded statement cache\n * (`query`), which dies with the database: `close()` finalizes it, and a closed\n * database refuses instead of answering. The cache is reused only while\n * `prepare` is the one `bun:sqlite` defines at the base of the class chain; a\n * database whose `prepare` was replaced or overridden sees every call.\n */\nfunction reusesStatements(db: BunSQLiteDatabase): boolean {\n let stock: unknown;\n for (\n let proto = Object.getPrototypeOf(db);\n proto;\n proto = Object.getPrototypeOf(proto)\n )\n if (Object.hasOwn(proto, \"prepare\")) stock = proto.prepare;\n return db.prepare === stock;\n}\n\nconst UNPAIRED_SURROGATE_PATTERN =\n /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u;\n\nfunction convertValuesForBunSQLite(values: unknown[]): unknown[] {\n return values.map((parameter) => {\n const value = convertValueForSQLite(parameter);\n if (typeof value === \"string\" && UNPAIRED_SURROGATE_PATTERN.test(value)) {\n throw new TypeError(\n \"bun:sqlite cannot preserve unpaired UTF-16 surrogates; the parameter was refused before dispatch.\"\n );\n }\n if (value instanceof Uint8Array || !isSQLiteBinaryValue(value)) {\n return value;\n }\n return sqliteBinaryToUint8Array(value);\n });\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLiteOptions {\n readonly?: boolean;\n create?: boolean;\n readwrite?: boolean;\n strict?: boolean;\n /**\n * Busy timeout in milliseconds, applied as `PRAGMA busy_timeout`. A VibORM\n * option: `bun:sqlite` has none of its own. Defaults to 5000.\n */\n timeout?: number;\n}\n\nexport interface BunSQLiteDriverOptions {\n client?: BunSQLiteDatabase;\n dataDir?: string;\n options?: BunSQLiteOptions;\n}\n\nexport type BunSQLiteClientConfig<C extends DriverConfig> =\n BunSQLiteDriverOptions & C;\n\nconst BUN_SQLITE_CONFIG_KEYS: Record<keyof BunSQLiteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLiteDriver extends Driver<\n BunSQLiteDatabase,\n BunSQLiteDatabase\n> {\n readonly adapter: DatabaseAdapter = new SQLiteAdapter();\n readonly maxBindParametersPerStatement: number | undefined = 32_766;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly sqliteMigrationCapability = SQLITE_MIGRATION_CAPABILITY;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: BunSQLiteDriverOptions;\n private readonly suppliedClient: BunSQLiteDatabase | undefined;\n /** Interpolated into a PRAGMA, so it is admitted here as an integer. */\n private readonly busyTimeout: number;\n\n constructor(options: BunSQLiteDriverOptions = {}) {\n super(\"sqlite\", \"bun-sqlite\");\n this.driverOptions = options;\n this.busyTimeout = options.options?.timeout ?? 5000;\n if (!Number.isSafeInteger(this.busyTimeout) || this.busyTimeout < 0) {\n throw new ClientInitializationError(\n 'The bun-sqlite \"timeout\" option must be a non-negative integer number of milliseconds.',\n { meta: { driver: \"bun-sqlite\", operation: \"configuration\" } }\n );\n }\n\n this.suppliedClient = options.client;\n if (this.suppliedClient) {\n const enabled = this.suppliedClient.query(\"PRAGMA foreign_keys\").get();\n if (\n !enabled ||\n typeof enabled !== \"object\" ||\n Reflect.get(enabled, \"foreign_keys\") !== 1\n ) {\n throw new ClientInitializationError(\n \"A supplied bun:sqlite Database must enable PRAGMA foreign_keys = ON before wrapping.\",\n { meta: { driver: \"bun-sqlite\" } }\n );\n }\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n }\n\n protected async initClient(): Promise<BunSQLiteDatabase> {\n if (this.suppliedClient) return this.suppliedClient;\n // Dynamic import for bun:sqlite\n const { Database } = await import(\"bun:sqlite\");\n\n const dataDir = this.driverOptions.dataDir ?? \":memory:\";\n // `timeout` is VibORM's own key, not one of bun:sqlite's open flags.\n const { timeout: _timeout, ...openFlags } =\n this.driverOptions.options ?? {};\n\n // bun:sqlite derives its open flags from this object and rejects one that\n // names no access mode: `new Database(path, {})` throws SQLITE_MISUSE\n // (\"flags must include SQLITE_OPEN_READONLY or SQLITE_OPEN_READWRITE\").\n // An options bag that says nothing must mean nothing, so the argument is\n // omitted entirely and Bun applies its own default (readwrite + create).\n const db = (Object.keys(openFlags).length === 0\n ? new Database(dataDir)\n : new Database(dataDir, openFlags)) as unknown as BunSQLiteDatabase;\n\n // bun:sqlite leaves SQLite's foreign_keys default (OFF), which would let a\n // dangling FK write report success while sqlite3 and libsql refuse it.\n // Enforcement is a viborm guarantee, not an inherited library default.\n db.exec(\"PRAGMA foreign_keys = ON\");\n db.exec(`PRAGMA busy_timeout = ${this.busyTimeout}`);\n\n return db;\n }\n\n protected async closeClient(db: BunSQLiteDatabase): Promise<void> {\n if (db !== this.suppliedClient) db.close();\n }\n\n protected async execute<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertValuesForBunSQLite(params);\n return this.runStatement<T>(client, sql, values, context?.model !== \"$raw\");\n }\n\n protected async executeRaw<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params?: unknown[]\n ): Promise<QueryResult<T>> {\n const values = params ? convertValuesForBunSQLite(params) : undefined;\n return this.runStatement<T>(client, sql, values, false);\n }\n\n private runStatement<T>(\n db: BunSQLiteDatabase,\n sql: string,\n values: unknown[] | undefined,\n typed: boolean\n ): QueryResult<T> {\n const stmt =\n typed && reusesStatements(db) ? db.query(sql) : db.prepare(sql);\n\n if (stmt.columnNames.length > 0) {\n // Read once without precision loss, including unsafe raw queries.\n requireSafeIntegers(stmt).safeIntegers(true);\n const rows = (values ? stmt.all(...values) : stmt.all()) as T[];\n return {\n rows: typed ? rows : normalizeSQLiteRawRows(rows),\n rowCount: rows.length,\n };\n }\n\n const result = values ? stmt.run(...values) : stmt.run();\n return { rows: [] as T[], rowCount: result.changes };\n }\n\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return LOCAL_SQLITE_TRANSACTION_SUPPORT;\n }\n\n protected async transaction<T>(\n client: BunSQLiteDatabase,\n fn: (tx: BunSQLiteDatabase) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n return runLocalSQLiteTransaction(client, fn, context);\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: BunSQLiteClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, BunSQLiteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: BunSQLiteDriver }\n >]: LinkedClientConfig<C & { driver: BunSQLiteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"bun-sqlite\", BUN_SQLITE_CONFIG_KEYS, {\n databaseUrl: \"pass the database file as dataDir\",\n });\n const { client, dataDir, options } = config;\n\n const driver = new BunSQLiteDriver({ client, dataDir, options });\n\n return createClientFromDriverConfig<S, C, BunSQLiteDriver>(config, driver);\n}\n"],"mappings":"mVA6EA,SAAS,oBACP,EACuB,CACvB,GAAI,OAAO,EAAK,cAAiB,WAC/B,MAAM,IAAI,EACR,aACA,yBACA,iJACD,CAEH,OAAO,EAUT,SAAS,iBAAiB,EAAgC,CACxD,IAAI,EACJ,IACE,IAAI,EAAQ,OAAO,eAAe,EAAG,CACrC,EACA,EAAQ,OAAO,eAAe,EAAM,CAEhC,OAAO,OAAO,EAAO,UAAU,GAAE,EAAQ,EAAM,SACrD,OAAO,EAAG,UAAY,EAGxB,MAAM,EACJ,0EAEF,SAAS,0BAA0B,EAA8B,CAC/D,OAAO,EAAO,IAAK,GAAc,CAC/B,IAAM,EAAQ,EAAsB,EAAU,CAC9C,GAAI,OAAO,GAAU,UAAY,EAA2B,KAAK,EAAM,CACrE,MAAU,UACR,oGACD,CAKH,OAHI,aAAi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AGT,MAAgB,YAAY,EAAsC,CAC5D,IAAO,KAAK,gBAAgB,EAAG,OAAO,CAG5C,MAAgB,QACd,EACA,EACA,EACA,EACyB,CACzB,IAAM,EAAS,0BAA0B,EAAO,CAChD,OAAO,KAAK,aAAgB,EAAQ,EAAK,EAAQ,GAAS,QAAU,OAAO,CAG7E,MAAgB,WACd,EACA,EACA,EACyB,CACzB,IAAM,EAAS,EAAS,0BAA0B,EAAO,CAAG,IAAA,GAC5D,OAAO,KAAK,aAAgB,EAAQ,EAAK,EAAQ,GAAM,CAGzD,aACE,EACA,EACA,EACA,EACgB,CAChB,IAAM,EACJ,GAAS,iBAAiB,EAAG,CAAG,EAAG,MAAM,EAAI,CAAG,EAAG,QAAQ,EAAI,CAEjE,GAAI,EAAK,YAAY,OAAS,EAAG,CAE/B,oBAAoB,EAAK,CAAC,aAAa,GAAK,CAC5C,IAAM,EAAQ,EAAS,EAAK,IAAI,GAAG,EAAO,CAAG,EAAK,KAAK,CACvD,MAAO,CACL,KAAM,EAAQ,EAAO,EAAuB,EAAK,CACjD,SAAU,EAAK,OAChB,CAIH,MAAO,CAAE,KAAM,EAAE,CAAS,UADX,EAAS,EAAK,IAAI,GAAG,EAAO,CAAG,EAAK,KAAK,EACb,QAAS,CAGtD,0BAAwE,CACtE,OAAO,EAGT,MAAgB,YACd,EACA,EACA,EACY,CACZ,OAAO,EAA0B,EAAQ,EAAI,EAAQ,GAQzD,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,aAAc,EAAwB,CAC1E,YAAa,oCACd,CAAC,CACF,GAAM,CAAE,SAAQ,UAAS,WAAY,EAIrC,OAAO,EAAoD,EAF5C,IAAI,gBAAgB,CAAE,SAAQ,UAAS,UAAS,CAAC,CAEU"}
1
+ {"version":3,"file":"bun-sqlite.mjs","names":[],"sources":["../src/drivers/bun-sqlite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n LOCAL_SQLITE_TRANSACTION_SUPPORT,\n normalizeSQLiteRawRows,\n runLocalSQLiteTransaction,\n} from \"../shared/sqlite-utils\";\n/**\n * Bun SQLite Driver\n *\n * Driver implementation for Bun's built-in SQLite (bun:sqlite).\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, FeatureNotSupportedError } from \"@errors\";\nimport {\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n SQLITE_MIGRATION_CAPABILITY,\n} from \"../driver\";\nimport {\n convertValueForSQLite,\n isSQLiteBinaryValue,\n sqliteBinaryToUint8Array,\n sqliteResultParser,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN:SQLITE\n// ============================================================\n\n// Bun's Database type - we define inline to avoid requiring bun types at compile time\ninterface BunSQLiteDatabase {\n query<T = unknown>(sql: string): BunSQLiteStatement<T>;\n prepare<T = unknown>(sql: string): BunSQLiteStatement<T>;\n run(sql: string, ...params: unknown[]): void;\n exec(sql: string): void;\n readonly inTransaction: boolean;\n close(): void;\n transaction<T>(fn: () => T): () => T;\n}\n\ninterface BunSQLiteStatement<T = unknown> {\n readonly columnNames: string[];\n all(...params: unknown[]): T[];\n get(...params: unknown[]): T | null;\n run(...params: unknown[]): {\n changes: number;\n lastInsertRowid: number | bigint;\n };\n /**\n * Reads INTEGER columns as BigInt instead of lossy JS numbers. Present on\n * `bun:sqlite` statements since Bun 1.1.14; the driver refuses to read\n * rather than return corrupted values when it is missing.\n */\n safeIntegers(safe: boolean): BunSQLiteStatement<T>;\n values(...params: unknown[]): unknown[][];\n}\n\n/**\n * `safeIntegers()` is what keeps an INTEGER past 2^53 from being rounded on\n * the way out of SQLite. A `bun:sqlite` old enough to lack it cannot answer\n * the query truthfully, so the read is refused instead of silently returning\n * a corrupted number — the one outcome that must never ship.\n */\nfunction requireSafeIntegers<T>(\n stmt: BunSQLiteStatement<T>\n): BunSQLiteStatement<T> {\n if (typeof stmt.safeIntegers !== \"function\") {\n throw new FeatureNotSupportedError(\n \"bun:sqlite\",\n \"Statement.safeIntegers\",\n \"This Bun build cannot read INTEGER columns as BigInt, so any value past 2^53 would come back silently rounded. Upgrade to Bun 1.1.14 or newer.\"\n );\n }\n return stmt;\n}\n\n/**\n * Typed statements come from `bun:sqlite`'s own bounded statement cache\n * (`query`), which dies with the database: `close()` finalizes it, and a closed\n * database refuses instead of answering. The cache is reused only while\n * `prepare` is the one `bun:sqlite` defines at the base of the class chain; a\n * database whose `prepare` was replaced or overridden sees every call.\n */\nfunction reusesStatements(db: BunSQLiteDatabase): boolean {\n let stock: unknown;\n for (\n let proto = Object.getPrototypeOf(db);\n proto;\n proto = Object.getPrototypeOf(proto)\n )\n if (Object.hasOwn(proto, \"prepare\")) stock = proto.prepare;\n return db.prepare === stock;\n}\n\nconst UNPAIRED_SURROGATE_PATTERN =\n /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u;\n\nfunction convertValuesForBunSQLite(values: unknown[]): unknown[] {\n return values.map((parameter) => {\n const value = convertValueForSQLite(parameter);\n if (typeof value === \"string\" && UNPAIRED_SURROGATE_PATTERN.test(value)) {\n throw new TypeError(\n \"bun:sqlite cannot preserve unpaired UTF-16 surrogates; the parameter was refused before dispatch.\"\n );\n }\n if (value instanceof Uint8Array || !isSQLiteBinaryValue(value)) {\n return value;\n }\n return sqliteBinaryToUint8Array(value);\n });\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLiteOptions {\n readonly?: boolean;\n create?: boolean;\n readwrite?: boolean;\n strict?: boolean;\n /**\n * Busy timeout in milliseconds, applied as `PRAGMA busy_timeout`. A VibORM\n * option: `bun:sqlite` has none of its own. Defaults to 5000.\n */\n timeout?: number;\n}\n\nexport interface BunSQLiteDriverOptions {\n client?: BunSQLiteDatabase;\n dataDir?: string;\n options?: BunSQLiteOptions;\n}\n\nexport type BunSQLiteClientConfig<C extends DriverConfig> =\n BunSQLiteDriverOptions & C;\n\nconst BUN_SQLITE_CONFIG_KEYS: Record<keyof BunSQLiteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLiteDriver extends Driver<\n BunSQLiteDatabase,\n BunSQLiteDatabase\n> {\n readonly adapter: DatabaseAdapter = new SQLiteAdapter();\n readonly maxBindParametersPerStatement: number | undefined = 32_766;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly sqliteMigrationCapability = SQLITE_MIGRATION_CAPABILITY;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: BunSQLiteDriverOptions;\n private readonly suppliedClient: BunSQLiteDatabase | undefined;\n /** Interpolated into a PRAGMA, so it is admitted here as an integer. */\n private readonly busyTimeout: number;\n\n constructor(options: BunSQLiteDriverOptions = {}) {\n super(\"sqlite\", \"bun-sqlite\");\n this.driverOptions = options;\n this.busyTimeout = options.options?.timeout ?? 5000;\n if (!Number.isSafeInteger(this.busyTimeout) || this.busyTimeout < 0) {\n throw new ClientInitializationError(\n 'The bun-sqlite \"timeout\" option must be a non-negative integer number of milliseconds.',\n { meta: { driver: \"bun-sqlite\", operation: \"configuration\" } }\n );\n }\n\n this.suppliedClient = options.client;\n if (this.suppliedClient) {\n const enabled = this.suppliedClient.query(\"PRAGMA foreign_keys\").get();\n if (\n !enabled ||\n typeof enabled !== \"object\" ||\n Reflect.get(enabled, \"foreign_keys\") !== 1\n ) {\n throw new ClientInitializationError(\n \"A supplied bun:sqlite Database must enable PRAGMA foreign_keys = ON before wrapping.\",\n { meta: { driver: \"bun-sqlite\" } }\n );\n }\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n }\n\n protected async initClient(): Promise<BunSQLiteDatabase> {\n if (this.suppliedClient) return this.suppliedClient;\n // Dynamic import for bun:sqlite\n const { Database } = await import(\"bun:sqlite\");\n\n const dataDir = this.driverOptions.dataDir ?? \":memory:\";\n // `timeout` is VibORM's own key, not one of bun:sqlite's open flags.\n const { timeout: _timeout, ...openFlags } =\n this.driverOptions.options ?? {};\n\n // bun:sqlite derives its open flags from this object and rejects one that\n // names no access mode: `new Database(path, {})` throws SQLITE_MISUSE\n // (\"flags must include SQLITE_OPEN_READONLY or SQLITE_OPEN_READWRITE\").\n // An options bag that says nothing must mean nothing, so the argument is\n // omitted entirely and Bun applies its own default (readwrite + create).\n const db = (Object.keys(openFlags).length === 0\n ? new Database(dataDir)\n : new Database(dataDir, openFlags)) as unknown as BunSQLiteDatabase;\n\n // bun:sqlite leaves SQLite's foreign_keys default (OFF), which would let a\n // dangling FK write report success while sqlite3 and libsql refuse it.\n // Enforcement is a viborm guarantee, not an inherited library default.\n db.exec(\"PRAGMA foreign_keys = ON\");\n db.exec(`PRAGMA busy_timeout = ${this.busyTimeout}`);\n\n return db;\n }\n\n protected async closeClient(db: BunSQLiteDatabase): Promise<void> {\n if (db !== this.suppliedClient) db.close();\n }\n\n protected async execute<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertValuesForBunSQLite(params);\n return this.runStatement<T>(client, sql, values, context?.model !== \"$raw\");\n }\n\n protected async executeRaw<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params?: unknown[]\n ): Promise<QueryResult<T>> {\n const values = params ? convertValuesForBunSQLite(params) : undefined;\n return this.runStatement<T>(client, sql, values, false);\n }\n\n private runStatement<T>(\n db: BunSQLiteDatabase,\n sql: string,\n values: unknown[] | undefined,\n typed: boolean\n ): QueryResult<T> {\n const stmt =\n typed && reusesStatements(db) ? db.query(sql) : db.prepare(sql);\n\n if (stmt.columnNames.length > 0) {\n // Read once without precision loss, including unsafe raw queries.\n requireSafeIntegers(stmt).safeIntegers(true);\n const rows = (values ? stmt.all(...values) : stmt.all()) as T[];\n return {\n rows: typed ? rows : normalizeSQLiteRawRows(rows),\n rowCount: rows.length,\n };\n }\n\n const result = values ? stmt.run(...values) : stmt.run();\n return { rows: [] as T[], rowCount: result.changes };\n }\n\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return LOCAL_SQLITE_TRANSACTION_SUPPORT;\n }\n\n protected async transaction<T>(\n client: BunSQLiteDatabase,\n fn: (tx: BunSQLiteDatabase) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n return runLocalSQLiteTransaction(client, fn, context);\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: BunSQLiteClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, BunSQLiteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: BunSQLiteDriver }\n >]: LinkedClientConfig<C & { driver: BunSQLiteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"bun-sqlite\", BUN_SQLITE_CONFIG_KEYS, {\n databaseUrl: \"pass the database file as dataDir\",\n });\n const { client, dataDir, options } = config;\n\n const driver = new BunSQLiteDriver({ client, dataDir, options });\n\n return createClientFromDriverConfig<S, C, BunSQLiteDriver>(config, driver);\n}\n"],"mappings":"gSA6EA,SAAS,EACP,EACuB,CACvB,GAAI,OAAO,EAAK,cAAiB,WAC/B,MAAM,IAAI,EACR,aACA,yBACA,iJACD,CAEH,OAAO,EAUT,SAAS,EAAiB,EAAgC,CACxD,IAAI,EACJ,IACE,IAAI,EAAQ,OAAO,eAAe,EAAG,CACrC,EACA,EAAQ,OAAO,eAA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aAAc,EAAwB,CAC1E,YAAa,oCACd,CAAC,CACF,GAAM,CAAE,SAAQ,UAAS,WAAY,EAIrC,OAAO,EAAoD,EAF5C,IAAI,EAAgB,CAAE,SAAQ,UAAS,UAAS,CAAC,CAEU"}
@@ -1,4 +1,4 @@
1
- import { n as CacheEntry, t as CacheDriver } from "../driver-BBEmaJZy.mjs";
1
+ import { n as CacheEntry, t as CacheDriver } from "../driver-BvTixv-m.mjs";
2
2
  import { KVNamespace } from "@cloudflare/workers-types";
3
3
 
4
4
  //#region src/cache/drivers/cloudflare-kv.d.ts
@@ -1,2 +1,2 @@
1
- import{n as e}from"../chunk-BuuaeEvq.mjs";import{n as t}from"../driver-BGVcgnIX.mjs";var CloudflareKVCache=class extends t{#e;constructor(e){super(`cloudflare-kv`),this.#e=e}async get(e){return await this.#e.get(e,`json`)||null}async set(e,t,n){let r=Math.max(60,Math.ceil(t/1e3));await this.#e.put(e,JSON.stringify(n),{expirationTtl:r})}async delete(e){await Promise.all(e.map(e=>this.#e.delete(e)))}async clear(e){let t;do{let n=await this.#e.list({prefix:e,cursor:t});await Promise.all(n.keys.map(e=>this.#e.delete(e.name))),t=n.list_complete?void 0:n.cursor}while(t)}};export{CloudflareKVCache};
1
+ import{n as e}from"../driver-kiIQS_Fd.mjs";var t=class extends e{static get name(){return`CloudflareKVCache`}#e;constructor(e){super(`cloudflare-kv`),this.#e=e}async get(e){return await this.#e.get(e,`json`)||null}async set(e,t,n){let r=Math.max(60,Math.ceil(t/1e3));await this.#e.put(e,JSON.stringify(n),{expirationTtl:r})}async delete(e){await Promise.all(e.map(e=>this.#e.delete(e)))}async clear(e){let t;do{let n=await this.#e.list({prefix:e,cursor:t});await Promise.all(n.keys.map(e=>this.#e.delete(e.name))),t=n.list_complete?void 0:n.cursor}while(t)}};export{t as CloudflareKVCache};
2
2
  //# sourceMappingURL=cloudflare-kv.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare-kv.mjs","names":["#kv"],"sources":["../../src/cache/drivers/cloudflare-kv.ts"],"sourcesContent":["/**\n * Cloudflare KV Cache\n *\n * Cache implementation using Cloudflare Workers KV.\n */\n\nimport type { KVNamespace } from \"@cloudflare/workers-types\";\nimport { CacheDriver, type CacheEntry } from \"../driver\";\n\n/**\n * Cloudflare KV cache implementation\n */\nexport class CloudflareKVCache extends CacheDriver {\n readonly #kv: KVNamespace;\n\n constructor(kv: KVNamespace) {\n super(\"cloudflare-kv\");\n this.#kv = kv;\n }\n\n protected async get<T>(key: string): Promise<CacheEntry<T> | null> {\n const data = await this.#kv.get<CacheEntry<T>>(key, \"json\");\n if (!data) return null;\n return data;\n }\n\n protected async set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void> {\n // KV TTL is in seconds\n const kvTtlSeconds = Math.max(60, Math.ceil(storageTtl / 1000));\n\n await this.#kv.put(key, JSON.stringify(entry), {\n expirationTtl: kvTtlSeconds,\n });\n }\n\n protected async delete(keys: string[]): Promise<void> {\n await Promise.all(keys.map((key) => this.#kv.delete(key)));\n }\n\n protected async clear(prefix: string): Promise<void> {\n let cursor: string | undefined;\n do {\n const result = await this.#kv.list({ prefix, cursor });\n await Promise.all(result.keys.map((k) => this.#kv.delete(k.name)));\n cursor = result.list_complete ? undefined : result.cursor;\n } while (cursor);\n }\n}\n"],"mappings":"qFAYA,IAAa,kBAAb,cAAuC,CAAY,CACjD,GAEA,YAAY,EAAiB,CAC3B,MAAM,gBAAgB,CACtB,MAAA,EAAW,EAGb,MAAgB,IAAO,EAA4C,CAGjE,OAFa,MAAM,MAAA,EAAS,IAAmB,EAAK,OAAO,EACzC,KAIpB,MAAgB,IACd,EACA,EACA,EACe,CAEf,IAAM,EAAe,KAAK,IAAI,GAAI,KAAK,KAAK,EAAa,IAAK,CAAC,CAE/D,MAAM,MAAA,EAAS,IAAI,EAAK,KAAK,UAAU,EAAM,CAAE,CAC7C,cAAe,EAChB,CAAC,CAGJ,MAAgB,OAAO,EAA+B,CACpD,MAAM,QAAQ,IAAI,EAAK,IAAK,GAAQ,MAAA,EAAS,OAAO,EAAI,CAAC,CAAC,CAG5D,MAAgB,MAAM,EAA+B,CACnD,IAAI,EACJ,EAAG,CACD,IAAM,EAAS,MAAM,MAAA,EAAS,KAAK,CAAE,SAAQ,SAAQ,CAAC,CACtD,MAAM,QAAQ,IAAI,EAAO,KAAK,IAAK,GAAM,MAAA,EAAS,OAAO,EAAE,KAAK,CAAC,CAAC,CAClE,EAAS,EAAO,cAAgB,IAAA,GAAY,EAAO,aAC5C"}
1
+ {"version":3,"file":"cloudflare-kv.mjs","names":[],"sources":["../../src/cache/drivers/cloudflare-kv.ts"],"sourcesContent":["/**\n * Cloudflare KV Cache\n *\n * Cache implementation using Cloudflare Workers KV.\n */\n\nimport type { KVNamespace } from \"@cloudflare/workers-types\";\nimport { CacheDriver, type CacheEntry } from \"../driver\";\n\n/**\n * Cloudflare KV cache implementation\n */\nexport class CloudflareKVCache extends CacheDriver {\n readonly #kv: KVNamespace;\n\n constructor(kv: KVNamespace) {\n super(\"cloudflare-kv\");\n this.#kv = kv;\n }\n\n protected async get<T>(key: string): Promise<CacheEntry<T> | null> {\n const data = await this.#kv.get<CacheEntry<T>>(key, \"json\");\n if (!data) return null;\n return data;\n }\n\n protected async set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void> {\n // KV TTL is in seconds\n const kvTtlSeconds = Math.max(60, Math.ceil(storageTtl / 1000));\n\n await this.#kv.put(key, JSON.stringify(entry), {\n expirationTtl: kvTtlSeconds,\n });\n }\n\n protected async delete(keys: string[]): Promise<void> {\n await Promise.all(keys.map((key) => this.#kv.delete(key)));\n }\n\n protected async clear(prefix: string): Promise<void> {\n let cursor: string | undefined;\n do {\n const result = await this.#kv.list({ prefix, cursor });\n await Promise.all(result.keys.map((k) => this.#kv.delete(k.name)));\n cursor = result.list_complete ? undefined : result.cursor;\n } while (cursor);\n }\n}\n"],"mappings":"2CAYA,IAAa,EAAb,cAAuC,CAAY,CAAA,WAAA,MAAA,CAAA,MAAA,oBACjD,GAEA,YAAY,EAAiB,CAC3B,MAAM,gBAAgB,CACtB,MAAA,EAAW,EAGb,MAAgB,IAAO,EAA4C,CAGjE,OAFa,MAAM,MAAA,EAAS,IAAmB,EAAK,OAAO,EACzC,KAIpB,MAAgB,IACd,EACA,EACA,EACe,CAEf,IAAM,EAAe,KAAK,IAAI,GAAI,KAAK,KAAK,EAAa,IAAK,CAAC,CAE/D,MAAM,MAAA,EAAS,IAAI,EAAK,KAAK,UAAU,EAAM,CAAE,CAC7C,cAAe,EAChB,CAAC,CAGJ,MAAgB,OAAO,EAA+B,CACpD,MAAM,QAAQ,IAAI,EAAK,IAAK,GAAQ,MAAA,EAAS,OAAO,EAAI,CAAC,CAAC,CAG5D,MAAgB,MAAM,EAA+B,CACnD,IAAI,EACJ,EAAG,CACD,IAAM,EAAS,MAAM,MAAA,EAAS,KAAK,CAAE,SAAQ,SAAQ,CAAC,CACtD,MAAM,QAAQ,IAAI,EAAO,KAAK,IAAK,GAAM,MAAA,EAAS,OAAO,EAAE,KAAK,CAAC,CAAC,CAClE,EAAS,EAAO,cAAgB,IAAA,GAAY,EAAO,aAC5C"}
@@ -1,4 +1,4 @@
1
- import { n as CacheEntry, t as CacheDriver } from "../driver-BBEmaJZy.mjs";
1
+ import { n as CacheEntry, t as CacheDriver } from "../driver-BvTixv-m.mjs";
2
2
 
3
3
  //#region src/cache/drivers/memory.d.ts
4
4
  interface MemoryCacheOptions {
@@ -1,2 +1,2 @@
1
- import{n as e}from"../chunk-BuuaeEvq.mjs";import{O as t}from"../error-mapping-B1-IWkCQ.mjs";import{n}from"../driver-BGVcgnIX.mjs";var MemoryCache=class extends n{#e=new Map;#t;#n;constructor(e){super(`memory`);let n=e?.maxEntries??1024;if(!Number.isSafeInteger(n)||n<1||Object.keys(e??{}).some(e=>e!==`maxEntries`))throw new t(`MemoryCache options must contain a positive safe-integer maxEntries only.`);this.#t=n}async get(e){let t=this.#e.get(e);return t?(this.#e.delete(e),this.clock.now()>=t.expiresAt?(this.#r(),null):(this.#e.set(e,t),t.entry)):null}async set(e,t,n){for(this.#e.delete(e),this.#e.set(e,{entry:n,expiresAt:this.clock.now()+t});this.#e.size>this.#t;)this.#e.delete(this.#e.keys().next().value);this.#i(t)}async delete(e){for(let t of e)this.#e.delete(t);this.#r()}async clear(e){for(let t of this.#e.keys())t.startsWith(e)&&this.#e.delete(t);this.#r()}#r(){this.#e.size||(this.#n?.cancel(),this.#n=void 0)}#i(e=6e4){this.#n||!this.#e.size||(this.#n=this.clock.setTimeout(()=>{this.#n=void 0;let e=this.clock.now();for(let[t,n]of this.#e)e>=n.expiresAt&&this.#e.delete(t);this.#i()},Math.min(e,6e4)),this.#n.unref?.())}async disconnect(){this.#e.clear(),this.#r()}};export{MemoryCache};
1
+ import{O as e}from"../error-mapping-B9rSvgG9.mjs";import{n as t}from"../driver-kiIQS_Fd.mjs";var n=class extends t{static get name(){return`MemoryCache`}#e=new Map;#t;#n;constructor(t){super(`memory`);let n=t?.maxEntries??1024;if(!Number.isSafeInteger(n)||n<1||Object.keys(t??{}).some(e=>e!==`maxEntries`))throw new e(`MemoryCache options must contain a positive safe-integer maxEntries only.`);this.#t=n}async get(e){let t=this.#e.get(e);return t?(this.#e.delete(e),this.clock.now()>=t.expiresAt?(this.#r(),null):(this.#e.set(e,t),t.entry)):null}async set(e,t,n){for(this.#e.delete(e),this.#e.set(e,{entry:n,expiresAt:this.clock.now()+t});this.#e.size>this.#t;)this.#e.delete(this.#e.keys().next().value);this.#i(t)}async delete(e){for(let t of e)this.#e.delete(t);this.#r()}async clear(e){for(let t of this.#e.keys())t.startsWith(e)&&this.#e.delete(t);this.#r()}#r(){this.#e.size||(this.#n?.cancel(),this.#n=void 0)}#i(e=6e4){this.#n||!this.#e.size||(this.#n=this.clock.setTimeout(()=>{this.#n=void 0;let e=this.clock.now();for(let[t,n]of this.#e)e>=n.expiresAt&&this.#e.delete(t);this.#i()},Math.min(e,6e4)),this.#n.unref?.())}async disconnect(){this.#e.clear(),this.#r()}};export{n as MemoryCache};
2
2
  //# sourceMappingURL=memory.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"memory.mjs","names":["#store","#maxEntries","#idle","#schedule","#timer"],"sources":["../../src/cache/drivers/memory.ts"],"sourcesContent":["/** In-memory LRU cache with a bounded entry count and one expiry sweep. */\nimport { CacheConfigurationError } from \"../../errors\";\nimport { CacheDriver, type CacheEntry, type CacheTimer } from \"../driver\";\n\nexport interface MemoryCacheOptions {\n readonly maxEntries: number;\n}\n\nexport class MemoryCache<\n const Options extends MemoryCacheOptions = MemoryCacheOptions,\n> extends CacheDriver {\n readonly #store = new Map<string, { entry: CacheEntry; expiresAt: number }>();\n readonly #maxEntries: number;\n #timer?: CacheTimer;\n\n constructor(\n options?: Options &\n Record<Exclude<keyof Options, keyof MemoryCacheOptions>, never>\n ) {\n super(\"memory\");\n const maxEntries = options?.maxEntries ?? 1024;\n // A misspelled or retired option is refused, not ignored.\n if (\n !Number.isSafeInteger(maxEntries) ||\n maxEntries < 1 ||\n Object.keys(options ?? {}).some((key) => key !== \"maxEntries\")\n )\n throw new CacheConfigurationError(\n \"MemoryCache options must contain a positive safe-integer maxEntries only.\"\n );\n this.#maxEntries = maxEntries;\n }\n\n protected async get<T>(key: string): Promise<CacheEntry<T> | null> {\n const stored = this.#store.get(key);\n if (!stored) return null;\n this.#store.delete(key);\n if (this.clock.now() >= stored.expiresAt) {\n this.#idle();\n return null;\n }\n this.#store.set(key, stored);\n // The entry `set` stored under this key, for the type the caller reads it as.\n return stored.entry as CacheEntry<T>;\n }\n\n protected async set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void> {\n this.#store.delete(key);\n this.#store.set(key, { entry, expiresAt: this.clock.now() + storageTtl });\n // Past the bound the store holds an entry: the oldest is the first key.\n while (this.#store.size > this.#maxEntries)\n this.#store.delete(this.#store.keys().next().value!);\n this.#schedule(storageTtl);\n }\n\n protected async delete(keys: string[]): Promise<void> {\n for (const key of keys) this.#store.delete(key);\n this.#idle();\n }\n\n protected async clear(prefix: string): Promise<void> {\n for (const key of this.#store.keys())\n if (key.startsWith(prefix)) this.#store.delete(key);\n this.#idle();\n }\n\n #idle(): void {\n if (this.#store.size) return;\n this.#timer?.cancel();\n this.#timer = undefined;\n }\n\n #schedule(delay = 60_000): void {\n if (this.#timer || !this.#store.size) return;\n this.#timer = this.clock.setTimeout(\n () => {\n this.#timer = undefined;\n const now = this.clock.now();\n for (const [key, stored] of this.#store)\n if (now >= stored.expiresAt) this.#store.delete(key);\n this.#schedule();\n },\n Math.min(delay, 60_000)\n );\n this.#timer.unref?.();\n }\n\n override async disconnect(): Promise<void> {\n this.#store.clear();\n this.#idle();\n }\n}\n"],"mappings":"kIAQA,IAAa,YAAb,cAEU,CAAY,CACpB,GAAkB,IAAI,IACtB,GACA,GAEA,YACE,EAEA,CACA,MAAM,SAAS,CACf,IAAM,EAAa,GAAS,YAAc,KAE1C,GACE,CAAC,OAAO,cAAc,EAAW,EACjC,EAAa,GACb,OAAO,KAAK,GAAW,EAAE,CAAC,CAAC,KAAM,GAAQ,IAAQ,aAAa,CAE9D,MAAM,IAAI,EACR,4EACD,CACH,MAAA,EAAmB,EAGrB,MAAgB,IAAO,EAA4C,CACjE,IAAM,EAAS,MAAA,EAAY,IAAI,EAAI,CASnC,OARK,GACL,MAAA,EAAY,OAAO,EAAI,CACnB,KAAK,MAAM,KAAK,EAAI,EAAO,WAC7B,MAAA,GAAY,CACL,OAET,MAAA,EAAY,IAAI,EAAK,EAAO,CAErB,EAAO,QARM,KAWtB,MAAgB,IACd,EACA,EACA,EACe,CAIf,IAHA,MAAA,EAAY,OAAO,EAAI,CACvB,MAAA,EAAY,IAAI,EAAK,CAAE,QAAO,UAAW,KAAK,MAAM,KAAK,CAAG,EAAY,CAAC,CAElE,MAAA,EAAY,KAAO,MAAA,GACxB,MAAA,EAAY,OAAO,MAAA,EAAY,MAAM,CAAC,MAAM,CAAC,MAAO,CACtD,MAAA,EAAe,EAAW,CAG5B,MAAgB,OAAO,EAA+B,CACpD,IAAK,IAAM,KAAO,EAAM,MAAA,EAAY,OAAO,EAAI,CAC/C,MAAA,GAAY,CAGd,MAAgB,MAAM,EAA+B,CACnD,IAAK,IAAM,KAAO,MAAA,EAAY,MAAM,CAC9B,EAAI,WAAW,EAAO,EAAE,MAAA,EAAY,OAAO,EAAI,CACrD,MAAA,GAAY,CAGd,IAAc,CACR,MAAA,EAAY,OAChB,MAAA,GAAa,QAAQ,CACrB,MAAA,EAAc,IAAA,IAGhB,GAAU,EAAQ,IAAc,CAC1B,MAAA,GAAe,CAAC,MAAA,EAAY,OAChC,MAAA,EAAc,KAAK,MAAM,eACjB,CACJ,MAAA,EAAc,IAAA,GACd,IAAM,EAAM,KAAK,MAAM,KAAK,CAC5B,IAAK,GAAM,CAAC,EAAK,KAAW,MAAA,EACtB,GAAO,EAAO,WAAW,MAAA,EAAY,OAAO,EAAI,CACtD,MAAA,GAAgB,EAElB,KAAK,IAAI,EAAO,IAAO,CACxB,CACD,MAAA,EAAY,SAAS,EAGvB,MAAe,YAA4B,CACzC,MAAA,EAAY,OAAO,CACnB,MAAA,GAAY"}
1
+ {"version":3,"file":"memory.mjs","names":[],"sources":["../../src/cache/drivers/memory.ts"],"sourcesContent":["/** In-memory LRU cache with a bounded entry count and one expiry sweep. */\nimport { CacheConfigurationError } from \"../../errors\";\nimport { CacheDriver, type CacheEntry, type CacheTimer } from \"../driver\";\n\nexport interface MemoryCacheOptions {\n readonly maxEntries: number;\n}\n\nexport class MemoryCache<\n const Options extends MemoryCacheOptions = MemoryCacheOptions,\n> extends CacheDriver {\n readonly #store = new Map<string, { entry: CacheEntry; expiresAt: number }>();\n readonly #maxEntries: number;\n #timer?: CacheTimer;\n\n constructor(\n options?: Options &\n Record<Exclude<keyof Options, keyof MemoryCacheOptions>, never>\n ) {\n super(\"memory\");\n const maxEntries = options?.maxEntries ?? 1024;\n // A misspelled or retired option is refused, not ignored.\n if (\n !Number.isSafeInteger(maxEntries) ||\n maxEntries < 1 ||\n Object.keys(options ?? {}).some((key) => key !== \"maxEntries\")\n )\n throw new CacheConfigurationError(\n \"MemoryCache options must contain a positive safe-integer maxEntries only.\"\n );\n this.#maxEntries = maxEntries;\n }\n\n protected async get<T>(key: string): Promise<CacheEntry<T> | null> {\n const stored = this.#store.get(key);\n if (!stored) return null;\n this.#store.delete(key);\n if (this.clock.now() >= stored.expiresAt) {\n this.#idle();\n return null;\n }\n this.#store.set(key, stored);\n // The entry `set` stored under this key, for the type the caller reads it as.\n return stored.entry as CacheEntry<T>;\n }\n\n protected async set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void> {\n this.#store.delete(key);\n this.#store.set(key, { entry, expiresAt: this.clock.now() + storageTtl });\n // Past the bound the store holds an entry: the oldest is the first key.\n while (this.#store.size > this.#maxEntries)\n this.#store.delete(this.#store.keys().next().value!);\n this.#schedule(storageTtl);\n }\n\n protected async delete(keys: string[]): Promise<void> {\n for (const key of keys) this.#store.delete(key);\n this.#idle();\n }\n\n protected async clear(prefix: string): Promise<void> {\n for (const key of this.#store.keys())\n if (key.startsWith(prefix)) this.#store.delete(key);\n this.#idle();\n }\n\n #idle(): void {\n if (this.#store.size) return;\n this.#timer?.cancel();\n this.#timer = undefined;\n }\n\n #schedule(delay = 60_000): void {\n if (this.#timer || !this.#store.size) return;\n this.#timer = this.clock.setTimeout(\n () => {\n this.#timer = undefined;\n const now = this.clock.now();\n for (const [key, stored] of this.#store)\n if (now >= stored.expiresAt) this.#store.delete(key);\n this.#schedule();\n },\n Math.min(delay, 60_000)\n );\n this.#timer.unref?.();\n }\n\n override async disconnect(): Promise<void> {\n this.#store.clear();\n this.#idle();\n }\n}\n"],"mappings":"6FAQA,IAAa,EAAb,cAEU,CAAY,CAAA,WAAA,MAAA,CAAA,MAAA,cACpB,GAAkB,IAAI,IACtB,GACA,GAEA,YACE,EAEA,CACA,MAAM,SAAS,C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W,MAAA,EAAY,OAAO,EAAI,CACtD,MAAA,GAAgB,EAElB,KAAK,IAAI,EAAO,IAAM,CACvB,CACD,MAAA,EAAY,SAAS,EAGvB,MAAe,YAA4B,CACzC,MAAA,EAAY,OAAO,CACnB,MAAA,GAAY"}
package/dist/cache.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as Extension, L as PlacedArgument, S as AnyTarget, Xr as MutationOperations, Y as CachedClientOf, j as Facts } from "./database-adapter-BGqvjeEy.mjs";
2
- import { a as WaitUntilFn, i as Revalidate, n as CacheEntry, o as CacheInvalidationOptions, r as CacheSetOptions, s as WithCacheOptions, t as CacheDriver } from "./driver-BBEmaJZy.mjs";
1
+ import { I as Extension, L as Facts, O as AnyTarget, U as PlacedArgument, tt as CachedClientOf, zr as MutationOperations } from "./database-adapter-BMjJiBFm.mjs";
2
+ import { a as WaitUntilFn, i as Revalidate, n as CacheEntry, o as CacheInvalidationOptions, r as CacheSetOptions, s as WithCacheOptions, t as CacheDriver } from "./driver-BvTixv-m.mjs";
3
3
 
4
4
  //#region src/cache/extension.d.ts
5
5
  interface CacheExtensionConfig {
package/dist/cache.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{O as t,j as n,k as r}from"./error-mapping-B1-IWkCQ.mjs";import{t as i}from"./base-z-cH5ZBI.mjs";import{t as a}from"./extension-CGepsF-p.mjs";import{t as o}from"./methods-part-ZY0f2AV_.mjs";import{a as s,c,l}from"./on-ylYaKuRu.mjs";import{n as u,r as d,t as f}from"./args-764KdWMr.mjs";import{n as p,t as m}from"./call-Cz8XUmrl.mjs";import{t as h}from"./settled-BjyuA76m.mjs";import{n as g,r as _,t as v}from"./key-hxFFCKed.mjs";import{h as y,i as b}from"./unit-words-CT0yeqfZ.mjs";import{_ as x,a as S,c as C,d as w,f as T,g as E,h as D,i as O,l as k,m as A,n as j,o as M,p as N,r as P,s as F,t as I,u as L,v as R,y as z}from"./driver-BGVcgnIX.mjs";function step(e,n,r,i){try{return i()}catch(i){throw new t(r,{cause:i instanceof Error?i:void 0,meta:{method:e,operation:n}})}}function cacheCodec(e,t){return{run:()=>e.run(),snapshot:()=>step(`snapshot`,t,`The operation result cannot be represented by the cache result codec.`,()=>e.snapshot()),materialize:n=>step(`materialize`,t,`The cached result snapshot is malformed.`,()=>e.materialize(n))}}const validator=e=>({"~standard":{version:1,vendor:`viborm.cache`,validate:t=>({value:e(t)})}});function configurationError(e){throw new t(e)}function cache(e){let{driver:r,version:y,waitUntil:b,swr:E}=e;r instanceof j||configurationError(`Cache extension configuration requires a CacheDriver instance.`),y!==void 0&&!(typeof y==`string`||Number.isFinite(y))&&configurationError(`Cache extension configuration "version" must be a string or finite number.`),b!==void 0&&typeof b!=`function`&&configurationError(`Cache extension configuration "waitUntil" must be a function.`);let namespaceOf=({dialect:e,namespace:t})=>x({version:y,dialect:e,namespace:t}),invalidate=async(e,n,a)=>{try{let t=namespaceOf(g(e));await r[S](``,n,e,e=>C(t,e))}catch(e){throw a===void 0&&e instanceof i?e:new t(a?`Cache invalidation failed after mutation '${a.operation}' on model '${a.model}'.`:`Cache invalidation failed.`,{cause:e instanceof Error?e:void 0,meta:{method:`invalidate`,...a}})}};return a(`viborm.cache`,u({cache:f(validator(T)).on(l),cacheRead:d(validator(e=>{let t=N(e);return t.swr!==!1&&E===void 0&&configurationError(`A view's "swr" option needs the cache configured with it: cache({ driver, swr: staleWhileRevalidate }).`),t}))}),p(e=>{let t=e.values;if(t.cacheRead!==void 0)throw new n(e.operation,[...w]);let r=t.cache;A(r)&&h(e,({certainty:t})=>invalidate(e,r,{model:e.model,operation:e.operation,commitCertainty:t}))},c(l)),m(e=>{let t=e.values.cacheRead;if(t===void 0)return;let n=e.model;return i=>{if(i.mode!==`direct`)return i();let a=v(i);if(a===void 0)return i();let o=g(i);return r[M]({id:a,codec:cacheCodec(_(i),e.operation),read:t,namespace:namespaceOf(o),waitUntil:b,model:n,operation:e.operation,origin:i,database:o,revalidate:E})}},c(s),{inner:!0}),o(e=>({$withCache:t=>e.$bind({cacheRead:t}),$invalidate:(...t)=>h(e,()=>invalidate(e,{invalidate:t}))})))}const staleWhileRevalidate=e=>{let{request:t,entry:n,now:r}=e,i=t.read.swr;return i===!1||r-n.createdAt>=i||r>=n.expiresAt?!1:(z(refreshed(e),t.waitUntil),b(t.origin,k(`hit`,`stale`)),!0)};async function refreshed({request:e,key:t,backend:n,store:r}){try{if(!await R(n,t,!0))return}catch{return}let{codec:i}=e;await y(e.origin,{kind:`cache`,operation:`revalidate`,note:L(e,e.database)},async a=>{let o=!1,s,c;try{await i.run(),await r(i.snapshot()),c=k(`revalidate`,`success`,void 0,e)}catch(t){o=!0,s=t,c=k(`revalidate`,`error`,t,e)}try{await R(n,t,!1)}catch(e){s=o?AggregateError([s,e],`Cache revalidation work and cleanup both failed.`,{cause:s}):e,o=!0}if(b(a,c),o)throw s})}function unscoped(e){let t=e.startsWith(`${D}:`)?e:e?`${D}:${e}`:D;if(t===E||t.startsWith(`${E}:`))throw new r(`The official cache namespace is the cache extension's own: the public storage functions cannot address a key under it.`);return t}async function getEntry(e,t,n){return e[O](unscoped(t),n)}async function setEntry(e,t,n,r,i){return e[F](unscoped(t),n,r,i)}async function deleteEntry(e,t,n){return e[P](`delete`,unscoped(t),n)}async function clearEntries(e,t,n){return e[P](`clear`,unscoped(t??``),n)}async function invalidateEntries(e,t,n,r){return e[S](`${t}:`,n,r,unscoped)}async function markRevalidating(e,t){return R(e[I](),unscoped(t),!0)}async function clearRevalidating(e,t){await R(e[I](),unscoped(t),!1)}export{j as CacheDriver,cache,clearEntries,clearRevalidating,deleteEntry,getEntry,invalidateEntries,markRevalidating,setEntry,staleWhileRevalidate};
1
+ import{O as e,j as t,k as n}from"./error-mapping-B9rSvgG9.mjs";import{t as r}from"./base-17NSFtrA.mjs";import{t as i}from"./extension-Dh1ddrlA.mjs";import{t as a}from"./methods-part-BaNx3o7b.mjs";import{a as o,c as s,l as c}from"./on-ZkOVmE4-.mjs";import{n as l,r as u,t as d}from"./args-7WgBFd_f.mjs";import{n as f,t as p}from"./call-0bd_B9Vp.mjs";import{t as m}from"./settled-DYYPcaBX.mjs";import{n as h,r as g,t as _}from"./key-BDH6oTyC.mjs";import{h as v,i as y}from"./unit-words-BXpLpyr2.mjs";import{_ as b,a as x,c as S,d as C,f as w,g as T,h as E,i as D,l as O,m as k,n as A,o as j,p as M,r as N,s as P,t as F,u as I,v as L,y as R}from"./driver-kiIQS_Fd.mjs";function z(t,n,r,i){try{return i()}catch(i){throw new e(r,{cause:i instanceof Error?i:void 0,meta:{method:t,operation:n}})}}function B(e,t){return{run:()=>e.run(),snapshot:()=>z(`snapshot`,t,`The operation result cannot be represented by the cache result codec.`,()=>e.snapshot()),materialize:n=>z(`materialize`,t,`The cached result snapshot is malformed.`,()=>e.materialize(n))}}const V=e=>({"~standard":{version:1,vendor:`viborm.cache`,validate:t=>({value:e(t)})}});function H(t){throw new e(t)}function U(n){let{driver:v,version:y,waitUntil:T,swr:E}=n;v instanceof A||H(`Cache extension configuration requires a CacheDriver instance.`),y!==void 0&&!(typeof y==`string`||Number.isFinite(y))&&H(`Cache extension configuration "version" must be a string or finite number.`),T!==void 0&&typeof T!=`function`&&H(`Cache extension configuration "waitUntil" must be a function.`);let D=({dialect:e,namespace:t})=>b({version:y,dialect:e,namespace:t}),O=async(t,n,i)=>{try{let e=D(h(t));await v[x](``,n,t,t=>S(e,t))}catch(t){throw i===void 0&&t instanceof r?t:new e(i?`Cache invalidation failed after mutation '${i.operation}' on model '${i.model}'.`:`Cache invalidation failed.`,{cause:t instanceof Error?t:void 0,meta:{method:`invalidate`,...i}})}};return i(`viborm.cache`,l({cache:d(V(w)).on(c),xy:u(V(e=>{let t=M(e);return t.swr!==!1&&E===void 0&&H(`A view's "swr" option needs the cache configured with it: cache({ driver, swr: staleWhileRevalidate }).`),t}))}),f(e=>{let n=e.values;if(n.xy!==void 0)throw new t(e.operation,[...C]);let r=n.cache;k(r)&&m(e,({certainty:t})=>O(e,r,{model:e.model,operation:e.operation,commitCertainty:t}))},s(c)),p(e=>{let t=e.values.xy;if(t===void 0)return;let n=e.model;return r=>{if(r.mode!==`direct`)return r();let i=_(r);if(i===void 0)return r();let a=h(r);return v[j]({id:i,codec:B(g(r),e.operation),read:t,namespace:D(a),waitUntil:T,model:n,operation:e.operation,origin:r,database:a,revalidate:E})}},s(o),{inner:!0}),a(e=>({$withCache:t=>e.$bind({xy:t}),$invalidate:(...t)=>m(e,()=>O(e,{invalidate:t}))})))}const W=e=>{let{request:t,entry:n,now:r}=e,i=t.read.swr;return i===!1||r-n.createdAt>=i||r>=n.expiresAt?!1:(R(G(e),t.waitUntil),y(t.origin,O(`hit`,`stale`)),!0)};async function G({request:e,key:t,backend:n,store:r}){try{if(!await L(n,t,!0))return}catch{return}let{codec:i}=e;await v(e.origin,{kind:`cache`,operation:`revalidate`,note:I(e,e.database)},async a=>{let o=!1,s,c;try{await i.run(),await r(i.snapshot()),c=O(`revalidate`,`success`,void 0,e)}catch(t){o=!0,s=t,c=O(`revalidate`,`error`,t,e)}try{await L(n,t,!1)}catch(e){s=o?AggregateError([s,e],`Cache revalidation work and cleanup both failed.`,{cause:s}):e,o=!0}if(y(a,c),o)throw s})}function K(e){let t=e.startsWith(`${E}:`)?e:e?`${E}:${e}`:E;if(t===T||t.startsWith(`${T}:`))throw new n(`The official cache namespace is the cache extension's own: the public storage functions cannot address a key under it.`);return t}async function q(e,t,n){return e[D](K(t),n)}async function J(e,t,n,r,i){return e[P](K(t),n,r,i)}async function Y(e,t,n){return e[N](`delete`,K(t),n)}async function X(e,t,n){return e[N](`clear`,K(t??``),n)}async function Z(e,t,n,r){return e[x](`${t}:`,n,r,K)}async function Q(e,t){return L(e[F](),K(t),!0)}async function $(e,t){await L(e[F](),K(t),!1)}export{A as CacheDriver,U as cache,X as clearEntries,$ as clearRevalidating,Y as deleteEntry,q as getEntry,Z as invalidateEntries,Q as markRevalidating,J as setEntry,W as staleWhileRevalidate};
2
2
  //# sourceMappingURL=cache.mjs.map