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
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./schema-BYA-_bpk.mjs";import{l as n,t as r}from"./judge-words-CzUyXtJ6.mjs";function bound(e){let r=new Map;return(i,a)=>{let o=i[`~`].names.ts,s=e.rows.confine?.get(o);if(s!==void 0)return t(r,`${o} ${a}`,()=>e.conjunction(i,a.map(e=>[e,[s[e]].filter(n)])))??void 0}}const i={admit:({admit:e},t,n)=>Object.fromEntries(Object.entries(t).map(([t,r])=>[t,e(t,`${t}.confine`,r,n)])),bind(e){let n=new Map;for(let[r,i]of e.entries())for(let[e,a]of Object.entries(i.confine??{}))t(n,e,()=>[])[r]=a;return{confine:n,bound}}};var Within=class extends r{join({key:e,model:t,schema:n,lazy:r,layer:a,refuse:o}){(e!==`confine`||r)&&o(`${r?`a lazy entry`:e} does not take within()`);let{scalars:s}=n[t][`~`].state;for(let e of Object.keys(this.held))Object.hasOwn(s,e)||o(`confine names "${e}", which is not a scalar field`);(a.confine??={})[t]=this.held,(a.brings??={}).confines=i}};function within(e){return new Within(e)}export{within as t};
2
- //# sourceMappingURL=confine-DqFBTUw6.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{N as t,i as n,t as r,y as i}from"./error-mapping-B1-IWkCQ.mjs";import{a,n as o,t as s,x as c,y as l}from"./base-z-cH5ZBI.mjs";import{c as u,d,l as f,o as p,p as m,s as h,u as g,y as _}from"./validation--qS7OPmg.mjs";import{n as v,t as y}from"./transaction-BNomMtme.mjs";import{s as b,t as x}from"./normalized-result-B8pifWS0.mjs";import{r as S,t as C}from"./transaction-operation-CVVJxQ19.mjs";import{r as w}from"./routed-operations-wytpbYKv.mjs";function createFailureError(e,t,n){if(e.kind===`foreignKey`)return new i(e.message,{meta:{model:t,operation:n}});if(e.kind===`nestedWrite`){let t=new f(e.message,e.relation??``);return e.raceable&&(t.meta.raceable=!0),t}if(e.kind===`notFound`)return new g(t,n);if(e.kind===`forbidden`)return new p(t,n,e.reason===void 0?void 0:{reason:e.reason});let r=new v(e.message,{meta:{model:t,operation:n}});return e.raceable&&(r.meta.raceable=!0),r}async function attributeOperationBatchError(e,t,n,i=[]){if(!(e instanceof u))return e;let a=e.meta.statementIndex;if(typeof a==`number`){let n=t.find(e=>e.queryIndex===a);return n?createFailureError(n.failure,n.model,n.operation):e}if(t.length>0&&r(i,n.dialect,new Set(t.map(e=>e.queryIndex))))return e;for(let e of t){let t=(await n._execute(e.probe,i[e.queryIndex]?.context)).rows.length>0;if(e.premise===`exists`?!t:t)return createFailureError(e.failure,e.model,e.operation)}let[s]=t;return s?t.every(e=>sameAttribution(e,s))?createFailureError(s.failure,s.model,s.operation):e:new f(h,``,{code:o.NESTED_WRITE_ASSERTION_FAILED,cause:e})}function sameAttribution(e,t){return e.model===t.model&&e.operation===t.operation&&e.failure.kind===t.failure.kind&&e.failure.message===t.failure.message&&e.failure.relation===t.failure.relation&&e.failure.reason===t.failure.reason&&e.failure.raceable===t.failure.raceable}function executeArrayTransaction(e,t,n,r){let i,a;try{let t=e.length;if(typeof t!=`number`||!Number.isInteger(t)||t<0||t>4294967295)throw new y;let n=Array(t);for(let r=0;r<t;r+=1)n[r]=e[r];i=n}catch(e){a=e}let run=e=>{if(i===void 0)throw a;if(assertOwnedOperations(i,t),i.length===0)return Promise.resolve(i);if(e===void 0)for(let e of[`input`,`plan`])for(let t of i)S(t).prepareAdmission(t,e);return executeMembers(i,t,n,r,e)},o=t.extensionChain?.observation;if(o===void 0)return finishArrayResults(i,t,run);let s={};return finishArrayResults(i,t,()=>o.run({kind:`batch`,operation:`$transaction([...])`,context:r,certainty:()=>s.certainty},()=>run(s)))}function finishArrayResults(e,t,n){let r=t.extensionChain;if(r?.fields===void 0&&r?.watch===void 0)return n();let i=[...e??[]];return n().then(async e=>{let t=[];for(let[n,r]of i.entries()){let i=S(r);try{i.finishResult&&(e[n]=await i.finishResult(r,e[n]))}catch(e){t.push(e)}}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Several array members failed after commit.`,{cause:t[0]});return e})}function executeMembers(e,t,n,r,i){let{driver:a}=t,o=!a.supportsTransactions&&a.supportsBatch;o||assertAtomicArraySupport(a);let s=t.extensionChain,c=s?.coordination;return c&&(s?.observation?o||c.admit:c.intercepts?.(e))?executeSlots(e,t,n,r,i,c,o):o?sendNativeBatch(e,a,n,r):sendTransaction(e,t,n,r,i)}async function executeSlots(e,t,n,r,i,a,o){let{driver:s}=t,c=scopeOf(t,i??{}),l=e.map(e=>({operation:e,owner:S(e),child:createArrayDeferred()})),u=await t.extensionChain?.observation?.members(l.map(e=>[{...e.owner.unit(e.operation),certainty:()=>e.certainty},()=>e.child.promise.then(nothing,nothing).then(()=>memberValue(e))]));try{for(let e of l)e.owner.reserveWith(e.operation,s);for(let e of[`input`,`plan`])for(let t of l)await t.owner.observeBatchPhase(t.operation,s,()=>t.owner.prepareAdmission(t.operation,e))}catch(e){for(let t of l)t.child.reject(e);throw e}let d=await a.admit?.(l,c);if(d!==void 0)throw combineArrayFailures(d[0],d.slice(1));let f;try{f=await(o?sendNativeBatch(e,s,n,r,l,c,i):sendTransaction(e,t,n,r,i,l,c))}catch(e){for(let t of l)t.child.reject(e);throw e}return await u?.done,f}function sendTransaction(e,t,n,r,i,a,o){let s=e,body=async t=>{for(let n=0;n<e.length;n+=1){let r=e[n],i=a?.[n];if(i===void 0){s[n]=await S(r).executeWith(r,t);continue}i.owner.executeCore(r,t,i.notifications).then(i.child.resolve,i.child.reject);try{s[n]=await memberValue(i)}catch(e){await settleSlots(a.slice(n+1),[e])}}return s};return transact(t,n,r,body,o,i)}async function sendNativeBatch(e,t,n,r,i,a,o){if(i===void 0)for(let n of e)S(n).reserveWith(n,t);let s,c=[],publish=async e=>{if(!s){s=e,o&&(o.certainty=e);for(let t of i){t.certainty=e;try{await t.notifications?.[e===`committed`?`committed`:`mayHaveCommitted`]()}catch(e){c.push(e)}}try{await a?.outcomes?.publish(e)}catch(e){c.push(e)}}},close=async(e,t)=>{if(i===void 0)return e;t&&await publish(`may-have-committed`),await settleSlots(i,[s?markCommitCertainty(e,s):e],c)},l,u,d;try{({queries:l,guards:u,parsers:d}=await prepareNativeBatch(e,t))}catch(e){throw await close(e)}let f;try{f=await executeNativeBatch(t,l,u,n,r,i&&t.supportsOrderedCommittedSegments?()=>publish(`committed`):void 0),i&&await publish(`committed`),assertNativeBatchResults(t,f,l.length)}catch(e){throw await close(e,!0)}let p=e;for(let e=0;e<d.length;e+=1){let t=i?.[e];if(t===void 0)p[e]=await d[e](f);else try{t.child.resolve(await d[e](f))}catch(e){t.child.reject(markCommitCertainty(e,`committed`))}}return i&&await settleSlots(i,[],c.map(e=>markCommitCertainty(e,`committed`)),p),p}const nothing=()=>void 0;function memberValue(e){return e.query??e.child.promise}async function settleSlots(e,t,n=[],r=[]){for(let n of e)n.child.reject(t[0]);for(let[n,i]of(await Promise.allSettled(e.map(memberValue))).entries())i.status===`fulfilled`?r[n]=i.value:t.push(i.reason);if(t.push(...n),t.length>0)throw combineArrayFailures(t[0],t.slice(1))}function combineArrayFailures(e,t){let n=t.filter(t=>t!==e);return n.length===0?e:AggregateError([e,...n],`Array transaction and operation post-work both failed.`,{cause:e})}function markCommitCertainty(e,t){return a(e)?n(e,t):e}function createArrayDeferred(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.catch(nothing),{promise:n,resolve:e,reject:t}}async function prepareNativeBatch(e,t){let n=[],r=[],i=[];for(let a of e){let e=S(a),o=await e.observeBatchPhase(a,t,async()=>{let n=e.prepare(a,t);return n?{prepared:n}:{preparedBatch:await e.prepareBatch(a)}}),s=n.length;if(o.prepared){n.push(o.prepared),i.push(n=>e.observeBatchPhase(a,t,()=>{let r=n[s];if(!r)throw arrayError(t,`omitted the result for operation "${e.operation(a)}"`,{operation:e.operation(a)});return e.parseResult(a,r)}));continue}let{preparedBatch:c}=o;if(!c)throw unbatchableArrayError(t);let l=c.queries.length;for(let e of c.queries)n.push(e);for(let e of c.guards??[])r.push({...e,queryIndex:s+e.queryIndex});i.push(n=>e.observeBatchPhase(a,t,()=>c.parseResult(n.slice(s,s+l))))}return{queries:n,guards:r,parsers:i}}async function executeNativeBatch(e,t,n,r,i,a){try{return await e._executeBatch(t,r,i,a)}catch(r){throw await attributeOperationBatchError(r,n,e,t)}}function assertNativeBatchResults(e,t,n){x(t,n,{provider:e.driverName,operation:`$transaction([...])`})}function assertAtomicArraySupport(e){if(!(e.supportsTransactions||e.supportsBatch))throw arrayError(e,`supports neither transactions nor atomic batch execution`)}function unbatchableArrayError(e){return arrayError(e,`does not support callback transactions and this transaction contains operations that cannot be batched atomically`)}function arrayError(e,t,n={method:`$transaction([...])`}){return new v(`Driver "${e.driverName}" ${t}.`,{meta:{driver:e.driverName,...n}})}function assertOwnedOperations(e,t){for(let n of e){if(typeof n!=`object`||!n)throw new y;let e=C(n);if(e===void 0)throw new y;if(e.clientId(n)!==t.clientId)throw d.clientMismatch(e.model(n),e.operation(n));if(e.scopeId(n)!==t.scopeId)throw d.scopeMismatch(e.model(n),e.operation(n))}}const T=Symbol(`viborm.call`),E=Symbol(`viborm.scope`),D=Symbol(`viborm.attempt`),isCall=e=>typeof e==`object`&&!!e,isScope=e=>typeof e==`object`&&!!e&&`engine`in e;function callOf(e){let t=Reflect.get(e,T);return isCall(t)?t:void 0}function attemptOf(e){return Reflect.get(e,D)}function scopeOf$1(e){let t=Reflect.get(e,E);return isScope(t)?t:void 0}e(scopeOf$1,`scopeOf`);function engineOf(e){return callOf(e)?.of?.engine??scopeOf$1(e)?.engine}const O=`called run() after its second moment returned`;function executePreparedQuery(e,t,n,r,i,a,o){return e!==void 0||o?r||o?executeRegisteredQuery(e,t,n,r,i,a,o,runArounds):runArounds(e,t,e=>n(void 0,e),a?.readCommitCertainty,a?.reportAdmissionFailure):n()}function executeRegisteredQuery(e,t,n,r,i,a,o,s){let c=o?[o]:e?.call?.told,l=c?.[0]?.tell?.(c,i),u=!1,d,notified=e=>async()=>{u=!0,i||(d=e),await l?.(e)},f={committed:notified(`committed`),mayHaveCommitted:notified(`may-have-committed`)},executeChild=async e=>{let t=await n(f,e);return r&&!u&&await f.committed(),t};return s&&e&&t?.length?s(e,t,executeChild,()=>d??a?.readCommitCertainty?.(),a?.reportAdmissionFailure):executeChild()}function runArounds(e,t,n,r,i){let at=(a,o)=>{let s=t?.[a];return s===void 0?n(o):runAround(e,s,e=>at(a+1,e??o),r,i,()=>n(o))};return at(0)}async function runAround(e,t,n,r,i,a){let{extension:o}=t,s=e.mode===`direct`,c=s&&e.kind===`model`&&w(e.operation),l=c,u,d,refuse=t=>(d===void 0&&(d=aroundError(o,e,t),i?.(d)),d),f={open:!0,failed:!1,done:!1,direct:s,routable:c,certainty:r,start(e){if(!f.open)throw refuse(`called run() more than once`);if(f.done)throw refuse(O);return f.open=!1,f.failed=!1,u=(async()=>n(e))(),u.then(void 0,()=>{f.failed=!0}),u}},p=Object.defineProperties(()=>{if(!f.done)return f.start();if(!l)throw refuse(O);return l=!1,(async()=>a())()},{input:{get:()=>e.input},mode:{value:e.mode},[T]:{value:e.kind===`model`?e.call:void 0},[D]:{value:f}}),m;try{m={value:await t.handler(e,p)}}catch(e){m={reason:e}}f.done=!0;let h=`reason`in m&&(d===void 0||m.reason!==d)?aroundFailure(o,e,m.reason,r?.()):void 0;if(u===void 0){if(h!==void 0)throw h;if(e.mode===`array`||e.kind!==`model`||!w(e.operation))throw aroundError(o,e,`returned without run()`)}else h!==void 0&&!f.failed&&i?.(h),await u;if(`value`in m&&d===void 0)return m.value;throw d??h}function aroundFailure(e,t,n,r){return c(n)?n:aroundError(e,t,`failed`,l(n),r)}function aroundError(e,t,n,r,i){return new m(`Extension "${e}" around() for ${t.kind===`model`?`${t.model}.${t.operation}`:t.operation} ${n}.`,{...r&&{cause:r},meta:{method:`around`,model:t.model,operation:t.operation,...i===void 0?{}:{commitCertainty:i}}})}var TransactionWriteOutcomes=class{staged=[];publish(e){return publishWriteOutcomes(this.staged.filter(e=>e.ok),{certainty:e})}async end({parent:e,root:t},r,i){if(!i)return e?collect(e).staged.push(...this.staged.filter(e=>e.ok)):await this.publish(`committed`),r;let{certainty:o}=t;if(e||o===void 0)throw r;let s=a(r)?n(r,o):r;try{await this.publish(o)}catch(e){throw _(s,e)}throw s}};function collect(e){return e.outcomes??=new TransactionWriteOutcomes,e.outcomes}function tell(e,t){if(t===void 0)return t=>publishWriteOutcomes(e,{certainty:t});for(let n of e)(n.collect?.(t)??t.outcomes)?.staged.push(n);return async()=>{for(let t of e)t.ok=!0}}async function publishWriteOutcomes(e,t){let n;for(let{extension:r,listener:i}of e)try{await i(t)}catch(e){n??=e instanceof s?e:new m(`Extension "${r}" settled() failed (${t.certainty}).`,{cause:l(e),meta:{method:`settled`,commitCertainty:t.certainty}})}if(n)throw n}function interceptsArray(e){return e.some(e=>{let{handlers:t,registration:n}=S(e).around(e);return t?.length||n})}async function stageArray(e,t){for(let n of e){let{write:e,registration:r}=n.owner.around(n.operation);if(r===void 0)continue;let child=e=>(n.notifications=e,n.child.promise),i=executeRegisteredQuery(void 0,void 0,child,e,t,void 0,r);n.query=i,i.catch(ignore)}}const ignore=()=>void 0;function admitArray(e,t,n){let r=e.map(e=>e.owner.around(e.operation));return admitArrayQueries(e,(i,a,o)=>{let{context:s,handlers:c,write:l,registration:u}=r[e.indexOf(i)];return c?.length||u?n(s,c,a,l,t,o,u):a()})}async function admitArrayQueries(e,t){let n,r=e.length,i=createArrayDeferred();r===0&&i.resolve();for(let a of e){let reportAdmissionFailure=e=>{let t=a.admissionFailures??=[];t.includes(e)||t.push(e),n??={failure:e},i.reject(e)},e;try{e=t(a,e=>(a.notifications=e,--r,r===0&&i.resolve(),a.child.promise),{reportAdmissionFailure,readCommitCertainty:()=>a.certainty})}catch(t){reportAdmissionFailure(t),e=Promise.reject(t)}a.query=e,e.catch(reportAdmissionFailure)}try{if(await i.promise,await Promise.resolve(),n)throw n.failure;return}catch(t){for(let n of e)n.child.reject(t);await Promise.allSettled(e.map(memberValue));let n=[];for(let t of e)for(let e of t.admissionFailures??[])n.includes(e)||n.push(e);return n}}const k={rank:-1},A={rank:1,executePreparedQuery:executeRegisteredQuery,intercepts:interceptsArray,admit:stageArray},j={rank:2,executePreparedQuery,intercepts:interceptsArray,admit:(e,t)=>admitArray(e,t,executePreparedQuery)};function coordinate(e,t,n){n&&(e.collect=n),(e.coordination===void 0||t.rank>e.coordination.rank)&&(e.coordination=t)}function transact(e,n,r,i,a,o=a?.root??{}){let s=e.extensionChain,c=e.transaction,l,end=e=>t=>{if(e||c||(o.certainty=`committed`),!l?.outcomes){if(e)throw t;return t}let n=l.outcomes.end(l,t,e);return n.catch(()=>void 0),n},u=e.driver.withTransaction(t=>(l=a??scopeOf(e,o),i(t,l)),n,c||!(s?.coordination||s?.methods)?r:t(r,{readyToCommit:()=>{o.certainty=`may-have-committed`},committed:()=>{o.certainty=`committed`}}));return c?b(u,end()):u.then(end(),end(!0))}function scopeOf(e,t){let n={parent:e.transaction,root:t};return e.extensionChain?.collect?.(n),n}export{transact as a,tell as c,attemptOf as d,callOf as f,createFailureError as g,executeArrayTransaction as h,coordinate as i,T as l,scopeOf$1 as m,j as n,collect as o,engineOf as p,k as r,publishWriteOutcomes as s,A as t,E as u};
2
- //# sourceMappingURL=coordination-6qZHx_kl.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"coordination-6qZHx_kl.mjs","names":["error","candidate","batch","scopeOf","failure","failure"],"sources":["../src/query-engine/batch-error-attribution.ts","../src/client/array-transaction.ts","../src/extensions/origin.ts","../src/extensions/query.ts","../src/extensions/array-admission.ts","../src/extensions/coordination.ts"],"sourcesContent":["import { batchMayContainAssertionCollision } from \"@drivers/error-mapping\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport {\n ForbiddenError,\n ForeignKeyError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n NestedWriteAssertionError,\n NestedWriteError,\n NotFoundError,\n TransactionError,\n VibORMErrorCode,\n} from \"@errors\";\nimport type { PreparedBatchGuard, PreparedGuardFailure } from \"./types\";\n\n/**\n * Materialize a guard's declared {@link PreparedGuardFailure} as its typed\n * error — the ONE failure-to-error construction, which the engine's own\n * referential refusal reuses when it runs outside a package\n * (`Commands.restrictFailure`). A `notFound` failure rebuilds\n * its sentence from the model and verb, so the declared message is never\n * user-facing for that kind; the `raceable` mark is what lets the routed retry\n * re-plan and converge, so it survives every arm.\n */\nexport function createFailureError(\n failure: PreparedGuardFailure,\n model: string,\n operation: string\n): Error {\n if (failure.kind === \"foreignKey\") {\n return new ForeignKeyError(failure.message, { meta: { model, operation } });\n }\n if (failure.kind === \"nestedWrite\") {\n const error = new NestedWriteError(failure.message, failure.relation ?? \"\");\n if (failure.raceable) {\n error.meta.raceable = true;\n }\n return error;\n }\n if (failure.kind === \"notFound\") {\n return new NotFoundError(model, operation);\n }\n if (failure.kind === \"forbidden\") {\n return new ForbiddenError(\n model,\n operation,\n failure.reason === undefined ? undefined : { reason: failure.reason }\n );\n }\n const error = new TransactionError(failure.message, {\n meta: { model, operation },\n });\n if (failure.raceable) {\n error.meta.raceable = true;\n }\n return error;\n}\n\n/**\n * Attribute a native-batch assertion failure to the guard that raised it (P6\n * pure-leaf extraction, consumed by the client's shared-batch path): a\n * `NestedWriteAssertionError` carries the index of the offending statement when\n * the driver surfaces it, else each guard's probe is re-run to locate the\n * violated precondition. The attributed error reconstructs the guard's typed\n * failure with the correct model/operation.\n *\n * The re-probe runs AFTER the atomic batch rolled back, which makes it blind to\n * one whole class: a premise broken by a SIBLING statement inside the same batch\n * is restored by that rollback and probes clean, so no guard is blamed. When\n * every guard in the batch would raise the same failure for the same\n * model/operation, that blindness costs nothing — whichever fired, the error is\n * the same one — but only once it is established that a guard fired AT ALL.\n *\n * That last part is not free. A native batch is normalized against the JOINED\n * SQL, so one assertion statement anywhere arms the detector\n * (`src/drivers/error-mapping.ts`) for every statement in the batch: an ordinary\n * statement that raises the same provider signature — `n / 0` from a literal\n * `divide: 0` on Postgres, a malformed-JSON argument on MySQL/SQLite — arrives\n * as a `NestedWriteAssertionError` no guard caused. Blaming a guard for it\n * asserts something false about the database (a `NotFoundError`/P2025 for a row\n * that is still there, which Prisma callers branch on). So the reconstruction\n * runs only when NO ordinary statement in the batch could have produced the\n * signature — viborm built every statement, so it can tell — and the raw\n * driver-mapped error stands whenever the failure cannot be tied to a guard.\n * A batch carrying guards that DISAGREE about what went wrong likewise stays\n * un-attributable.\n */\nexport async function attributeOperationBatchError(\n error: unknown,\n guards: readonly PreparedBatchGuard[],\n driver: AnyDriver,\n statements: readonly {\n readonly sql: string;\n readonly context?: QueryExecutionContext;\n }[] = []\n): Promise<unknown> {\n if (!(error instanceof NestedWriteAssertionError)) return error;\n const statementIndex = error.meta.statementIndex;\n if (typeof statementIndex === \"number\") {\n const guard = guards.find(\n (candidate) => candidate.queryIndex === statementIndex\n );\n if (guard) {\n return createFailureError(guard.failure, guard.model, guard.operation);\n }\n return error;\n }\n if (\n guards.length > 0 &&\n batchMayContainAssertionCollision(\n statements,\n driver.dialect,\n new Set(guards.map((guard) => guard.queryIndex))\n )\n ) {\n // A failed premise after rollback does not identify which statement failed.\n return error;\n }\n for (const guard of guards) {\n const result = await driver._execute(\n guard.probe,\n statements[guard.queryIndex]?.context\n );\n const exists = result.rows.length > 0;\n if (guard.premise === \"exists\" ? !exists : exists) {\n return createFailureError(guard.failure, guard.model, guard.operation);\n }\n }\n const [candidate] = guards;\n if (candidate) {\n const attributable = guards.every((guard) =>\n sameAttribution(guard, candidate)\n );\n return attributable\n ? createFailureError(\n candidate.failure,\n candidate.model,\n candidate.operation\n )\n : error;\n }\n return new NestedWriteError(NESTED_WRITE_ASSERTION_FLOOR_MESSAGE, \"\", {\n code: VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED,\n cause: error,\n });\n}\n\n/**\n * Two guards that would produce the SAME error: same model, same operation, and\n * a failure identical in every field the reconstruction below reads.\n */\nfunction sameAttribution(\n guard: PreparedBatchGuard,\n other: PreparedBatchGuard\n): boolean {\n return (\n guard.model === other.model &&\n guard.operation === other.operation &&\n guard.failure.kind === other.failure.kind &&\n guard.failure.message === other.failure.message &&\n guard.failure.relation === other.failure.relation &&\n guard.failure.reason === other.failure.reason &&\n guard.failure.raceable === other.failure.raceable\n );\n}\n","/**\n * The one executor of `$transaction([...])`. Every application runs it: one\n * transaction on a transaction driver, one native batch on a batch driver.\n * A chain whose parts intercept calls admits the members through its\n * coordination's `admit` hook (`@extensions/array-admission`), read from\n * the chain's state, so an application without one carries none of it.\n */\n\nimport { attachCommitCertainty } from \"@drivers/driver-error-context\";\nimport type {\n AnyDriver,\n BatchQuery,\n QueryExecutionContext,\n QueryResult,\n} from \"@drivers/exports\";\nimport { assertNormalizedBatchResults } from \"@drivers/normalized-result\";\nimport type {\n BatchTransactionOptions,\n TransactionOptions,\n} from \"@drivers/shared/transaction-options\";\nimport {\n InvalidTransactionInputError,\n isVibORMError,\n PendingOperationError,\n TransactionError,\n} from \"@errors\";\nimport {\n type ArrayCertainty,\n type Coordination,\n scopeOf,\n transact,\n} from \"@extensions/coordination\";\nimport type {\n TransactionScope,\n WriteOutcome,\n WriteOutcomeNotifications,\n} from \"@extensions/query\";\nimport { attributeOperationBatchError } from \"@query-engine/batch-error-attribution\";\nimport type { QueryEngine } from \"@query-engine/query-engine\";\nimport {\n readTransactionOperation,\n type TransactionOperationCapability,\n type TransactionOperationOwner,\n transactionOperationOwner,\n} from \"@query-engine/transaction-operation\";\nimport type { PreparedBatchGuard } from \"@query-engine/types\";\n\ntype ArrayOptions = TransactionOptions | BatchTransactionOptions | undefined;\n\n/** Each member's parser over the batch's results. */\ntype BatchParser = (batchResults: QueryResult<unknown>[]) => Promise<unknown>;\n\n/**\n * Execute one root or nested array transaction. Without an observer, every\n * member's request work (argument admission included) settles before any\n * provider effect; an observer runs it inside each member's unit instead.\n */\nexport function executeArrayTransaction(\n candidates: readonly unknown[],\n engine: QueryEngine,\n options: ArrayOptions,\n context: QueryExecutionContext\n): Promise<unknown[]> {\n let operations: unknown[] | undefined;\n let snapshotFailure: unknown;\n try {\n const length = candidates.length;\n if (\n typeof length !== \"number\" ||\n !Number.isInteger(length) ||\n length < 0 ||\n length > 0xff_ff_ff_ff\n ) {\n throw new InvalidTransactionInputError();\n }\n const snapshot = new Array<unknown>(length);\n for (let index = 0; index < length; index += 1) {\n snapshot[index] = candidates[index];\n }\n operations = snapshot;\n } catch (error) {\n snapshotFailure = error;\n }\n const run = (batch?: ArrayCertainty): Promise<unknown[]> => {\n if (operations === undefined) throw snapshotFailure;\n assertOwnedOperations(operations, engine);\n if (operations.length === 0) return Promise.resolve(operations);\n if (batch === undefined)\n for (const phase of [\"input\", \"plan\"] as const)\n for (const operation of operations)\n transactionOperationOwner(operation).prepareAdmission(\n operation,\n phase\n );\n return executeMembers(operations, engine, options, context, batch);\n };\n const observation = engine.extensionChain?.observation;\n if (observation === undefined)\n return finishArrayResults(operations, engine, run);\n const batch: ArrayCertainty = {};\n return finishArrayResults(operations, engine, () =>\n observation.run(\n {\n kind: \"batch\",\n operation: \"$transaction([...])\",\n context,\n certainty: () => batch.certainty,\n },\n () => run(batch)\n )\n );\n}\n\n/**\n * Each member's value as its caller receives it: a chain that computes\n * result fields or watches writes finishes every member once the array has\n * settled.\n * The members are read before the run, which writes its values over them.\n */\nfunction finishArrayResults(\n operations: readonly unknown[] | undefined,\n engine: QueryEngine,\n run: () => Promise<unknown[]>\n): Promise<unknown[]> {\n const chain = engine.extensionChain;\n if (chain?.fields === undefined && chain?.watch === undefined) return run();\n const members = [...(operations ?? [])] as object[];\n return run().then(async (values) => {\n // One member at a time: a member's write hooks run in member order, and\n // one failing does not keep the next from running.\n const failures: unknown[] = [];\n for (const [index, operation] of members.entries()) {\n const owner = transactionOperationOwner(operation);\n try {\n if (owner.finishResult)\n values[index] = await owner.finishResult(operation, values[index]);\n } catch (failure) {\n failures.push(failure);\n }\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1)\n throw new AggregateError(\n failures,\n \"Several array members failed after commit.\",\n {\n cause: failures[0],\n }\n );\n return values;\n });\n}\n\n/**\n * The members sent as one transaction, or one native batch. On a chain that\n * may intercept them (its `admit` hook), or whose units observe a native\n * batch's members, each member gets a slot first: its unit entered, its\n * arguments admitted and its handlers started, all before anything is sent.\n */\nfunction executeMembers(\n operations: TransactionOperationCapability[],\n engine: QueryEngine,\n options: ArrayOptions,\n context: QueryExecutionContext,\n batch: ArrayCertainty | undefined\n): Promise<unknown[]> {\n const { driver } = engine;\n const native = !driver.supportsTransactions && driver.supportsBatch;\n if (!native) assertAtomicArraySupport(driver);\n const chain = engine.extensionChain;\n const coordination = chain?.coordination;\n // Observed members go through slots, but on a transaction driver only\n // where a part may intercept them; else each member's unit runs around\n // its own work, in order. Unobserved members, prepared already, only\n // where one is intercepted.\n return coordination &&\n (chain?.observation\n ? native || coordination.admit\n : coordination.intercepts?.(operations))\n ? executeSlots(\n operations,\n engine,\n options,\n context,\n batch,\n coordination,\n native\n )\n : native\n ? sendNativeBatch(operations, driver, options, context)\n : sendTransaction(operations, engine, options, context, batch);\n}\n\n/** One member of an observed or intercepted array. */\nexport interface ArraySlot {\n readonly operation: TransactionOperationCapability;\n readonly owner: TransactionOperationOwner<TransactionOperationCapability>;\n /** The core's result, which the member's handlers resume with. */\n readonly child: ArrayDeferred<unknown>;\n /** The member's handlers: its value as its caller receives it. */\n query?: Promise<unknown>;\n notifications?: WriteOutcomeNotifications;\n certainty?: WriteOutcome[\"certainty\"];\n admissionFailures?: unknown[];\n}\n\nasync function executeSlots(\n operations: TransactionOperationCapability[],\n engine: QueryEngine,\n options: ArrayOptions,\n context: QueryExecutionContext,\n batch: ArrayCertainty | undefined,\n coordination: Coordination,\n native: boolean\n): Promise<unknown[]> {\n const { driver } = engine;\n // The array's scope, made before its members are admitted, which stage in it.\n const scope = scopeOf(engine, batch ?? {});\n const slots = operations.map(\n (operation): ArraySlot => ({\n operation,\n owner: transactionOperationOwner(operation),\n child: createArrayDeferred(),\n })\n );\n // Each member's unit starts before any member is prepared, and the array\n // waits until every unit reached its child: a handler that waits first\n // (for a tracer to load) does so before the array's work, which then runs\n // inside each member's unit, until its handlers settled.\n const units = await engine.extensionChain?.observation?.members(\n slots.map((slot) => [\n { ...slot.owner.unit(slot.operation), certainty: () => slot.certainty },\n () =>\n slot.child.promise.then(nothing, nothing).then(() => memberValue(slot)),\n ])\n );\n try {\n for (const slot of slots) slot.owner.reserveWith(slot.operation, driver);\n for (const phase of [\"input\", \"plan\"] as const)\n for (const slot of slots)\n await slot.owner.observeBatchPhase(slot.operation, driver, () =>\n slot.owner.prepareAdmission(slot.operation, phase)\n );\n } catch (error) {\n for (const slot of slots) slot.child.reject(error);\n throw error;\n }\n const failures = await coordination.admit?.(slots, scope);\n if (failures !== undefined)\n throw combineArrayFailures(failures[0], failures.slice(1));\n let values: unknown[];\n try {\n values = await (native\n ? sendNativeBatch(\n operations,\n driver,\n options,\n context,\n slots,\n scope,\n batch\n )\n : sendTransaction(\n operations,\n engine,\n options,\n context,\n batch,\n slots,\n scope\n ));\n } catch (failure) {\n // A transaction that failed before a member ran still lets that\n // member's handlers and unit end.\n for (const slot of slots) slot.child.reject(failure);\n throw failure;\n }\n // What a member's unit handler threw, once its child succeeded, fails the\n // array: the host contains nothing a handler does.\n await units?.done;\n return values;\n}\n\n/** The members in order inside one transaction, or a savepoint. */\nfunction sendTransaction(\n operations: TransactionOperationCapability[],\n engine: QueryEngine,\n options: ArrayOptions,\n context: QueryExecutionContext,\n batch: ArrayCertainty | undefined,\n slots?: ArraySlot[],\n scope?: TransactionScope\n): Promise<unknown[]> {\n const results: unknown[] = operations;\n const body = async (transactionDriver: AnyDriver): Promise<unknown[]> => {\n for (let index = 0; index < operations.length; index += 1) {\n const operation = operations[index]!;\n const slot = slots?.[index];\n if (slot === undefined) {\n results[index] = await transactionOperationOwner(operation).executeWith(\n operation,\n transactionDriver\n );\n continue;\n }\n // The reserved execution turns what its core throws into a rejection.\n slot.owner\n .executeCore(operation, transactionDriver, slot.notifications)\n .then(slot.child.resolve, slot.child.reject);\n try {\n results[index] = await memberValue(slot);\n } catch (failure) {\n // The members after a failed one never run: their handlers resume\n // with its failure before the rollback, which fails with it.\n await settleSlots(slots!.slice(index + 1), [failure]);\n }\n }\n return results;\n };\n return transact(engine, options, context, body, scope, batch);\n}\n\n/** The members prepared in order and sent as one native batch. */\nasync function sendNativeBatch(\n operations: TransactionOperationCapability[],\n driver: AnyDriver,\n options: ArrayOptions,\n context: QueryExecutionContext,\n slots?: ArraySlot[],\n scope?: TransactionScope,\n batch?: ArrayCertainty\n): Promise<unknown[]> {\n // Slots were reserved before they were admitted.\n if (slots === undefined)\n for (const operation of operations)\n transactionOperationOwner(operation).reserveWith(operation, driver);\n // What the sent batch reached, reported to every unit and published once,\n // and what publishing it failed with.\n let reached: WriteOutcome[\"certainty\"] | undefined;\n const late: unknown[] = [];\n const publish = async (certainty: WriteOutcome[\"certainty\"]) => {\n if (reached) return;\n reached = certainty;\n if (batch) batch.certainty = certainty;\n for (const slot of slots!) {\n slot.certainty = certainty;\n try {\n // Only a write's handlers are handed notifications.\n await slot.notifications?.[\n certainty === \"committed\" ? \"committed\" : \"mayHaveCommitted\"\n ]();\n } catch (error) {\n late.push(error);\n }\n }\n try {\n await scope?.outcomes?.publish(certainty);\n } catch (error) {\n late.push(error);\n }\n };\n // The failure to throw: every slot settled, it rejects with the folded one.\n const close = async (failure: unknown, sent?: true): Promise<unknown> => {\n if (slots === undefined) return failure;\n if (sent) await publish(\"may-have-committed\");\n await settleSlots(\n slots,\n [reached ? markCommitCertainty(failure, reached) : failure],\n late\n );\n };\n let queries: BatchQuery[];\n let guards: PreparedBatchGuard[];\n let parsers: BatchParser[];\n try {\n ({ queries, guards, parsers } = await prepareNativeBatch(\n operations,\n driver\n ));\n } catch (error) {\n throw await close(error);\n }\n let batchResults: QueryResult<unknown>[];\n try {\n batchResults = await executeNativeBatch(\n driver,\n queries,\n guards,\n options,\n context,\n slots && driver.supportsOrderedCommittedSegments\n ? () => publish(\"committed\")\n : undefined\n );\n if (slots) await publish(\"committed\");\n assertNativeBatchResults(driver, batchResults, queries.length);\n } catch (error) {\n throw await close(error, true);\n }\n const results: unknown[] = operations;\n for (let index = 0; index < parsers.length; index += 1) {\n const slot = slots?.[index];\n if (slot === undefined)\n results[index] = await parsers[index]!(batchResults);\n else\n try {\n slot.child.resolve(await parsers[index]!(batchResults));\n } catch (error) {\n slot.child.reject(markCommitCertainty(error, \"committed\"));\n }\n }\n if (slots)\n await settleSlots(\n slots,\n [],\n late.map((error) => markCommitCertainty(error, \"committed\")),\n results\n );\n return results;\n}\n\nconst nothing = (): undefined => undefined;\n\n/** The member's value as its handlers return it, or its core's before they start. */\nexport function memberValue(\n slot: Pick<ArraySlot, \"query\" | \"child\">\n): Promise<unknown> {\n return slot.query ?? slot.child.promise;\n}\n\n/**\n * Wait for every member's handlers, each child still unsettled rejected\n * with the first of `failures`, their values written into `values`; then\n * fail with the first failure, the distinct others and `extra` folded in.\n */\nexport async function settleSlots(\n slots: readonly ArraySlot[],\n failures: unknown[],\n extra: readonly unknown[] = [],\n values: unknown[] = []\n): Promise<void> {\n for (const slot of slots) slot.child.reject(failures[0]);\n for (const [index, settled] of (\n await Promise.allSettled(slots.map(memberValue))\n ).entries())\n if (settled.status === \"fulfilled\") values[index] = settled.value;\n else failures.push(settled.reason);\n failures.push(...extra);\n if (failures.length > 0)\n throw combineArrayFailures(failures[0], failures.slice(1));\n}\n\n/** The primary failure, with the distinct ones that settled beside it. */\nexport function combineArrayFailures(\n primary: unknown,\n suppressed: readonly unknown[]\n): unknown {\n const distinct = suppressed.filter((failure) => failure !== primary);\n if (distinct.length === 0) return primary;\n return new AggregateError(\n [primary, ...distinct],\n \"Array transaction and operation post-work both failed.\",\n { cause: primary }\n );\n}\n\n/** An error of viborm's own marked with the array's commit certainty. */\nfunction markCommitCertainty(\n error: unknown,\n certainty: WriteOutcome[\"certainty\"]\n): unknown {\n return isVibORMError(error) ? attachCommitCertainty(error, certainty) : error;\n}\n\nexport interface ArrayDeferred<Value> {\n readonly promise: Promise<Value>;\n readonly resolve: (value: Value) => void;\n readonly reject: (reason: unknown) => void;\n}\n\n/** A promise settled from outside; the first settlement holds. */\nexport function createArrayDeferred<Value>(): ArrayDeferred<Value> {\n // Promise executors run synchronously; TypeScript does not model that guarantee.\n let resolve!: (value: Value) => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<Value>((ok, fail) => {\n resolve = ok;\n reject = fail;\n });\n promise.catch(nothing);\n return { promise, resolve, reject };\n}\n\n/** Prepare members in order into one native batch with per-member parsers. */\nexport async function prepareNativeBatch(\n operations: readonly TransactionOperationCapability[],\n driver: AnyDriver\n): Promise<{\n readonly queries: BatchQuery[];\n readonly guards: PreparedBatchGuard[];\n readonly parsers: BatchParser[];\n}> {\n const queries: BatchQuery[] = [];\n const guards: PreparedBatchGuard[] = [];\n const parsers: BatchParser[] = [];\n for (const operation of operations) {\n const owner = transactionOperationOwner(operation);\n const preparation = await owner.observeBatchPhase(\n operation,\n driver,\n async () => {\n const prepared = owner.prepare(operation, driver);\n if (prepared) return { prepared };\n return { preparedBatch: await owner.prepareBatch(operation) };\n }\n );\n const start = queries.length;\n if (preparation.prepared) {\n queries.push(preparation.prepared);\n parsers.push((batchResults) =>\n owner.observeBatchPhase(operation, driver, () => {\n const result = batchResults[start];\n if (!result)\n throw arrayError(\n driver,\n `omitted the result for operation \"${owner.operation(operation)}\"`,\n { operation: owner.operation(operation) }\n );\n return owner.parseResult(operation, result);\n })\n );\n continue;\n }\n const { preparedBatch } = preparation;\n if (!preparedBatch) throw unbatchableArrayError(driver);\n const length = preparedBatch.queries.length;\n for (const query of preparedBatch.queries) queries.push(query);\n for (const guard of preparedBatch.guards ?? []) {\n guards.push({ ...guard, queryIndex: start + guard.queryIndex });\n }\n parsers.push((batchResults) =>\n owner.observeBatchPhase(operation, driver, () =>\n preparedBatch.parseResult(batchResults.slice(start, start + length))\n )\n );\n }\n return { queries, guards, parsers };\n}\n\nexport async function executeNativeBatch(\n driver: AnyDriver,\n queries: BatchQuery[],\n guards: PreparedBatchGuard[],\n options: ArrayOptions,\n context: QueryExecutionContext,\n committed?: () => Promise<void>\n): Promise<QueryResult<unknown>[]> {\n // The driver answers an empty batch itself, without sending it.\n try {\n return await driver._executeBatch(\n queries,\n options as BatchTransactionOptions | undefined,\n context,\n committed\n );\n } catch (error) {\n throw await attributeOperationBatchError(error, guards, driver, queries);\n }\n}\n\nexport function assertNativeBatchResults(\n driver: AnyDriver,\n results: QueryResult<unknown>[],\n queryCount: number\n): void {\n assertNormalizedBatchResults(results, queryCount, {\n provider: driver.driverName,\n operation: \"$transaction([...])\",\n });\n}\n\nexport function assertAtomicArraySupport(driver: AnyDriver): void {\n if (driver.supportsTransactions || driver.supportsBatch) return;\n throw arrayError(\n driver,\n \"supports neither transactions nor atomic batch execution\"\n );\n}\n\nexport function unbatchableArrayError(driver: AnyDriver): TransactionError {\n return arrayError(\n driver,\n \"does not support callback transactions and this transaction contains operations that cannot be batched atomically\"\n );\n}\n\nfunction arrayError(\n driver: AnyDriver,\n problem: string,\n meta: Record<string, unknown> = { method: \"$transaction([...])\" }\n): TransactionError {\n return new TransactionError(`Driver \"${driver.driverName}\" ${problem}.`, {\n meta: { driver: driver.driverName, ...meta },\n });\n}\n\nfunction assertOwnedOperations(\n candidates: unknown[],\n engine: QueryEngine\n): asserts candidates is TransactionOperationCapability[] {\n for (const candidate of candidates) {\n if (candidate === null || typeof candidate !== \"object\") {\n throw new InvalidTransactionInputError();\n }\n const owner = readTransactionOperation(candidate);\n if (owner === undefined) throw new InvalidTransactionInputError();\n if (owner.clientId(candidate) !== engine.clientId) {\n throw PendingOperationError.clientMismatch(\n owner.model(candidate),\n owner.operation(candidate)\n );\n }\n if (owner.scopeId(candidate) !== engine.scopeId) {\n throw PendingOperationError.scopeMismatch(\n owner.model(candidate),\n owner.operation(candidate)\n );\n }\n }\n}\n","/**\n * Where a call's words find what they read: a first moment's context and a\n * second moment's `run` carry the call (`CALL`), a method's scope carries its\n * view (`SCOPE`). Symbols, so a call, a run or a scope shows them to the words\n * that import this module and to nothing else.\n */\nimport type { QueryExecutionContext } from \"@drivers/types\";\nimport type { QueryEngine } from \"@query-engine/query-engine\";\nimport type { PreparedOperation } from \"@query-engine/raptor3/commands\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { Seconds } from \"./call\";\nimport type { Attempt, WriteOutcomeRegistration } from \"./query\";\nimport type { Watched } from \"./watch-part\";\n\n/** The key of the call a first moment's context and a `run` belong to. */\nexport const CALL = Symbol(\"viborm.call\");\n/** The key of the view a method's scope serves. */\nexport const SCOPE = Symbol(\"viborm.scope\");\n/** The key of what a second moment's `run` started, which `again` and `via` read. */\nexport const ATTEMPT = Symbol(\"viborm.attempt\");\n\n/**\n * One call, as its words and its parts read it: a model call's own object, a\n * raw statement's resolved query. Each part that keeps something for the\n * call writes its own field, and only it reads that field: what it keeps\n * lives as long as the call, never on a chain or a part, which outlive it.\n */\nexport interface CallOrigin {\n /** The arguments of the extensions the call admitted. */\n readonly values?: AdmittedArgs;\n /** Set once the call is an operation of an engine: absent on a raw statement. */\n of?: {\n readonly engine: QueryEngine;\n readonly context: QueryExecutionContext;\n /** The call prepared once: what runs is this preparation. */\n readonly prepared: () => PreparedOperation;\n };\n /** `around` (`call.ts`): what each part's first moment left its second. */\n seconds?: Seconds;\n /** `watch` and `settled` on a model call (`watch-part.ts`): per extension. */\n watched?: Watched;\n /** `settled` on a raw statement, in an `around`'s first moment (`call.ts`). */\n told?: WriteOutcomeRegistration[];\n}\n\n/** The view one extension's method scope serves. */\ninterface ScopeOrigin {\n readonly engine: QueryEngine;\n readonly extension: string;\n}\n\n// Only this module and the core write these keys: what they hold is what\n// the core put there.\nconst isCall = <T = CallOrigin>(value: unknown): value is T =>\n typeof value === \"object\" && value !== null;\nconst isScope = (value: unknown): value is ScopeOrigin =>\n typeof value === \"object\" && value !== null && \"engine\" in value;\n\n/** The call a first moment's context or a `run` belongs to, if it has one. */\nexport function callOf(x: object): CallOrigin | undefined {\n const call: unknown = Reflect.get(x, CALL);\n return isCall(call) ? call : undefined;\n}\n\n/**\n * What a second moment's `run` started: every `run` the host hands carries\n * it, and a forged one is not guarded against (D6).\n */\nexport function attemptOf(run: object): Attempt {\n return Reflect.get(run, ATTEMPT);\n}\n\n/** The view a method's scope serves, if `x` is one. */\nexport function scopeOf(x: object): ScopeOrigin | undefined {\n const scope: unknown = Reflect.get(x, SCOPE);\n return isScope(scope) ? scope : undefined;\n}\n\n/** The engine a call, a run or a scope works on. */\nexport function engineOf(x: object): QueryEngine | undefined {\n return callOf(x)?.of?.engine ?? scopeOf(x)?.engine;\n}\n","import { attachCommitCertainty } from \"@drivers/driver-error-context\";\nimport type { AnyDriver } from \"@drivers/exports\";\nimport {\n isVibORMError,\n QueryError,\n retainWriteOutcomeFailure,\n VibORMError,\n} from \"@errors\";\nimport { isReadOperation } from \"@query-engine/routed-operations\";\nimport { errorCause, isError } from \"../errors/diagnostic-safety\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { CallHandler } from \"./chain\";\nimport { ATTEMPT, CALL, type CallOrigin } from \"./origin\";\n\nexport type CallMode = \"direct\" | \"transaction\" | \"array\";\n\nexport type RawQueryKind =\n | \"queryRaw\"\n | \"executeRaw\"\n | \"queryRawUnsafe\"\n | \"executeRawUnsafe\";\n\ntype RawQueryOperation = `$${RawQueryKind}`;\n\ninterface PreparedQueryContextBase<Input extends object> {\n readonly mode: CallMode;\n readonly input: Readonly<Input>;\n /**\n * One object per call, the same one its first moments were handed: what\n * links an `around` part's two moments.\n */\n readonly call?: CallOrigin;\n}\n\nexport interface PreparedModelQueryContext<Input extends object>\n extends PreparedQueryContextBase<Input> {\n readonly kind: \"model\";\n readonly model: string;\n readonly operation: string;\n /**\n * The call's admitted arguments. A handler sees only its own extension's,\n * and only when that extension declares any.\n */\n readonly values?: AdmittedArgs;\n}\n\nexport interface PreparedRawQueryContext<Input extends object>\n extends PreparedQueryContextBase<Input> {\n readonly kind: RawQueryKind;\n readonly model: undefined;\n readonly operation: RawQueryOperation;\n}\n\n/** The prepared logical-operation facts safe for `around` parts to inspect. */\nexport type PreparedQueryContext<\n Input extends object = Record<string, unknown>,\n> = PreparedModelQueryContext<Input> | PreparedRawQueryContext<Input>;\n\nexport type WriteOutcome = Readonly<{\n certainty: \"committed\" | \"may-have-committed\";\n}>;\n\nexport type WriteOutcomeListener = (\n outcome: WriteOutcome\n) => unknown | Promise<unknown>;\n\nexport interface WriteOutcomeRegistration {\n readonly extension: string;\n readonly listener: WriteOutcomeListener;\n /**\n * What installs a transaction scope's collector, brought by the word that\n * registered (`settled`); absent, the scope's own, installed at its start\n * by a chain whose parts hear writes.\n */\n readonly collect?: typeof collect;\n /**\n * What tells a call's registrations of its outcome, brought by what\n * registered (`settled`, the part that watches writes): a chain where\n * nothing registers carries none of it.\n */\n readonly tell?: typeof tell;\n /** In a transaction: the call reached its outcome, so it is told at the scope's end. */\n ok?: true;\n}\n\nexport interface WriteOutcomeNotifications {\n readonly committed: () => Promise<void>;\n readonly mayHaveCommitted: () => Promise<void>;\n}\n\n/** A `run()` no second moment may make once it returned. */\nconst AFTER_RETURN = \"called run() after its second moment returned\";\n\n/** The child a handler chain runs: on the driver a handler chose, if any. */\ntype Child<Result> = (driver?: AnyDriver) => Promise<Result>;\n\n/** What one `around` part runs for a call: its second moment, handed `run` by the runner. */\nexport type AroundRunner = (\n prepared: PreparedQueryContext<object>,\n run: () => Promise<unknown>\n) => unknown;\n\n/** The `around` parts one call runs, the first applied outermost. */\nexport type AroundHandlers = readonly CallHandler<AroundRunner>[];\n\ntype Certainty = WriteOutcome[\"certainty\"];\n\n/** Private coordination hooks used only while array members await admission. */\nexport interface AdmissionHooks {\n readonly reportAdmissionFailure?: (failure: unknown) => void;\n readonly readCommitCertainty?: () => Certainty | undefined;\n}\n\n/** The child of a prepared call, told of the commits it reaches. */\ntype PreparedChild<Result> = (\n notifications?: WriteOutcomeNotifications,\n driver?: AnyDriver\n) => Promise<Result>;\n\n/**\n * Execute one prepared operation through its `around` parts and under what\n * its write registered.\n */\nexport function executePreparedQuery<Result, Input extends object>(\n context: PreparedQueryContext<Input> | undefined,\n arounds: AroundHandlers | undefined,\n child: PreparedChild<Result>,\n isWrite: boolean,\n scope?: TransactionScope,\n hooks?: AdmissionHooks,\n registration?: WriteOutcomeRegistration\n): Promise<Result> {\n // A context is prepared only for a call some `around` part wraps.\n const intercepted = context !== undefined;\n if (!(intercepted || registration)) return child();\n return isWrite || registration\n ? executeRegisteredQuery(\n context,\n arounds,\n child,\n isWrite,\n scope,\n hooks,\n registration,\n runArounds\n )\n : runArounds(\n context!,\n arounds,\n (driver) => child(undefined, driver),\n hooks?.readCommitCertainty,\n hooks?.reportAdmissionFailure\n );\n}\n\n/**\n * One write under what it registered (the registration a model write's\n * watches made, or the `settled` functions a raw statement's first moments\n * kept on it), around its `around` parts when `intercept` runs them, which\n * {@link executePreparedQuery} passes: a chain without `around` parts does\n * not carry their runner. Each commit the child reports is told (outside a\n * transaction, the certainty it reached is what `again` reads), and a write\n * that succeeded without reporting one is told it committed.\n */\nexport function executeRegisteredQuery<Result, Input extends object>(\n context: PreparedQueryContext<Input> | undefined,\n arounds: AroundHandlers | undefined,\n child: PreparedChild<Result>,\n isWrite: boolean,\n scope?: TransactionScope,\n hooks?: AdmissionHooks,\n registration?: WriteOutcomeRegistration,\n intercept?: typeof runArounds\n): Promise<Result> {\n const registrations = registration ? [registration] : context?.call?.told;\n const told = registrations?.[0]?.tell?.(registrations, scope);\n let reported = false;\n let certainty: Certainty | undefined;\n const notified = (reached: Certainty) => async (): Promise<void> => {\n reported = true;\n if (!scope) certainty = reached;\n await told?.(reached);\n };\n const notifications: WriteOutcomeNotifications = {\n committed: notified(\"committed\"),\n mayHaveCommitted: notified(\"may-have-committed\"),\n };\n // What fails before its outcome is reached is never marked, so never told.\n const executeChild = async (driver?: AnyDriver): Promise<Result> => {\n const value = await child(notifications, driver);\n if (isWrite && !reported) await notifications.committed();\n return value;\n };\n return intercept && context && arounds?.length\n ? intercept(\n context,\n arounds,\n executeChild,\n () => certainty ?? hooks?.readCommitCertainty?.(),\n hooks?.reportAdmissionFailure\n )\n : executeChild();\n}\n\n/**\n * Run one already-compiled part chain around one prepared child, the\n * first handler outermost.\n *\n * The undefined/empty branch deliberately returns the child's promise directly:\n * unextended operations allocate no runner promise, context, closure, or list.\n */\nexport function runArounds<Result, Input extends object>(\n context: PreparedQueryContext<Input>,\n arounds: AroundHandlers | undefined,\n child: Child<Result>,\n readCommitCertainty?: () => Certainty | undefined,\n reportAdmissionFailure?: (failure: unknown) => void\n): Promise<Result> {\n const at = (index: number, driver?: AnyDriver): Promise<Result> => {\n const part = arounds?.[index];\n return part === undefined\n ? child(driver)\n : runAround(\n context,\n part,\n (chosen) => at(index + 1, chosen ?? driver),\n readCommitCertainty,\n reportAdmissionFailure,\n () => child(driver)\n );\n };\n return at(0);\n}\n\n/**\n * One `run` of one `around` part, as the words that read it find it\n * (`again`, `via`): what may start the child, and what happened to it.\n */\nexport interface Attempt {\n /** `run()` may start the child. */\n open: boolean;\n /** The child's last start failed. */\n failed: boolean;\n /** The second moment returned. */\n done: boolean;\n /** A direct call outside a transaction and an array. */\n readonly direct: boolean;\n /** A direct read: what `via` may run on another driver. */\n readonly routable: boolean;\n readonly certainty: (() => Certainty | undefined) | undefined;\n readonly start: (driver?: AnyDriver) => Promise<unknown>;\n}\n\n/**\n * One handler around its child. Once the child ran, its failure is the\n * call's, whatever the handler returns or throws after it; a handler that\n * breaks the protocol fails the call with that refusal once the child\n * succeeded.\n */\nasync function runAround<Result, Input extends object>(\n prepared: PreparedQueryContext<Input>,\n part: CallHandler<AroundRunner>,\n child: Child<Result>,\n readCommitCertainty: (() => Certainty | undefined) | undefined,\n reportAdmissionFailure: ((failure: unknown) => void) | undefined,\n core: () => Promise<Result>\n): Promise<Result> {\n const { extension } = part;\n const direct = prepared.mode === \"direct\";\n const routable =\n direct && prepared.kind === \"model\" && isReadOperation(prepared.operation);\n // A direct read may run once more after its handler returned (a value\n // served now and refreshed later): that run is the core's alone.\n let replayable = routable;\n let running: Promise<Result> | undefined;\n let protocolFailure: QueryError | undefined;\n const refuse = (failure: string): QueryError => {\n if (protocolFailure === undefined) {\n protocolFailure = aroundError(extension, prepared, failure);\n reportAdmissionFailure?.(protocolFailure);\n }\n return protocolFailure;\n };\n const attempt: Attempt = {\n open: true,\n failed: false,\n done: false,\n direct,\n routable,\n certainty: readCommitCertainty,\n start(driver) {\n if (!attempt.open) throw refuse(\"called run() more than once\");\n if (attempt.done) throw refuse(AFTER_RETURN);\n attempt.open = false;\n attempt.failed = false;\n // What the child throws, even at once, is its promise's rejection.\n running = (async () => child(driver))();\n // Attached first, so a handler's own `catch` already reads it.\n running.then(undefined, () => {\n attempt.failed = true;\n });\n return running;\n },\n };\n const run = Object.defineProperties(\n (): Promise<unknown> => {\n if (!attempt.done) return attempt.start();\n if (!replayable) throw refuse(AFTER_RETURN);\n replayable = false;\n return (async () => core())();\n },\n {\n // Read when asked: the context snapshots the input the first time.\n input: { get: () => prepared.input },\n mode: { value: prepared.mode },\n [CALL]: { value: prepared.kind === \"model\" ? prepared.call : undefined },\n [ATTEMPT]: { value: attempt },\n }\n );\n let outcome: { readonly value: Result } | { readonly reason: unknown };\n try {\n outcome = {\n // A second moment answers the call: `around`'s types hold its value\n // to the call's result.\n value: (await part.handler(prepared, run)) as Result,\n };\n } catch (reason) {\n outcome = { reason };\n }\n attempt.done = true;\n const failure =\n \"reason\" in outcome &&\n (protocolFailure === undefined || outcome.reason !== protocolFailure)\n ? aroundFailure(\n extension,\n prepared,\n outcome.reason,\n readCommitCertainty?.()\n )\n : undefined;\n if (running === undefined) {\n if (failure !== undefined) throw failure;\n if (\n prepared.mode === \"array\" ||\n prepared.kind !== \"model\" ||\n !isReadOperation(prepared.operation)\n )\n throw aroundError(extension, prepared, \"returned without run()\");\n } else {\n if (failure !== undefined && !attempt.failed)\n reportAdmissionFailure?.(failure);\n await running;\n }\n if (\"value\" in outcome && protocolFailure === undefined) return outcome.value;\n throw protocolFailure ?? failure;\n}\n\nfunction aroundFailure<Input extends object>(\n extension: string,\n context: PreparedQueryContext<Input>,\n reason: unknown,\n commitCertainty?: WriteOutcome[\"certainty\"]\n): Error {\n if (isError(reason)) return reason;\n return aroundError(\n extension,\n context,\n \"failed\",\n errorCause(reason),\n commitCertainty\n );\n}\n\nfunction aroundError<Input extends object>(\n extension: string,\n context: PreparedQueryContext<Input>,\n failure: string,\n cause?: Error,\n commitCertainty?: WriteOutcome[\"certainty\"]\n): QueryError {\n return new QueryError(\n `Extension \"${extension}\" around() for ${context.kind === \"model\" ? `${context.model}.${context.operation}` : context.operation} ${failure}.`,\n {\n ...(cause && { cause }),\n meta: {\n method: \"around\",\n model: context.model,\n operation: context.operation,\n ...(commitCertainty === undefined ? {} : { commitCertainty }),\n },\n }\n );\n}\n\n/**\n * The collector of one transaction scope: the registrations its calls\n * staged, each told at the scope's end if its call reached its outcome.\n */\nexport class TransactionWriteOutcomes {\n readonly staged: WriteOutcomeRegistration[] = [];\n\n /** Tell what reached its outcome; a native batch's scope ends so. */\n publish(certainty: Certainty): Promise<void> {\n return publishWriteOutcomes(\n this.staged.filter((registration) => registration.ok),\n { certainty }\n );\n }\n\n /**\n * End the scope this collects for, with what its transaction settled\n * with. A savepoint that commits hands what it collected to its parent's\n * collector, which owns the decision; the outermost publishes it after\n * its commit, or, when its commit failed after COMMIT was sent, with the\n * certainty reached, which the failure then carries.\n */\n async end<T>(\n { parent, root }: TransactionScope,\n settled: T,\n failed?: true\n ): Promise<T> {\n if (!failed) {\n if (parent)\n collect(parent).staged.push(\n ...this.staged.filter((registration) => registration.ok)\n );\n else await this.publish(\"committed\");\n return settled;\n }\n const { certainty } = root;\n if (parent || certainty === undefined) throw settled;\n const primary = isVibORMError(settled)\n ? attachCommitCertainty(settled, certainty)\n : settled;\n try {\n await this.publish(certainty);\n } catch (outcomeFailure) {\n throw retainWriteOutcomeFailure(primary, outcomeFailure);\n }\n throw primary;\n }\n}\n\n/**\n * One transaction scope, as `transact` (`coordination.ts`) runs it: what its\n * calls register waits in it until it ends. The scope holds no code: the\n * first registration installs the collector (`collect`), which brings the\n * code that ends the scope, so a transaction where nothing registers runs\n * none of it.\n */\nexport interface TransactionScope {\n /** The scope this one is a savepoint of. */\n readonly parent: TransactionScope | undefined;\n /** The outermost scope's commit phase, as its driver reports it. */\n readonly root: CommitPhase;\n outcomes?: TransactionWriteOutcomes;\n}\n\n/** How far a transaction's commit went; nothing before COMMIT was sent. */\nexport interface CommitPhase {\n certainty?: Certainty;\n}\n\n/** The collector of a transaction scope, installed by its first registration. */\nexport function collect(scope: TransactionScope): TransactionWriteOutcomes {\n scope.outcomes ??= new TransactionWriteOutcomes();\n return scope.outcomes;\n}\n\n/**\n * What tells one call's registrations of the commits it reaches: inside a\n * transaction, each is staged in the scope and marked once the call reached\n * its outcome, told when the scope ends; outside one, each commit is told.\n */\nexport function tell(\n registrations: readonly WriteOutcomeRegistration[],\n scope: TransactionScope | undefined\n): (certainty: Certainty) => Promise<void> {\n if (scope === undefined)\n return (certainty) => publishWriteOutcomes(registrations, { certainty });\n for (const registration of registrations)\n (registration.collect?.(scope) ?? scope.outcomes)?.staged.push(\n registration\n );\n return async () => {\n for (const registration of registrations) registration.ok = true;\n };\n}\n\n/**\n * Deliver every registered listener in registration order, all of them. The\n * first fault rejects: an error of viborm's own as it is, any other value as\n * the cause of a `QueryError`; later faults are lost.\n */\nexport async function publishWriteOutcomes(\n registrations: readonly WriteOutcomeRegistration[],\n outcome: WriteOutcome\n): Promise<void> {\n let first: unknown;\n for (const { extension, listener } of registrations) {\n try {\n await listener(outcome);\n } catch (reason) {\n first ??=\n reason instanceof VibORMError\n ? reason\n : new QueryError(\n `Extension \"${extension}\" settled() failed (${outcome.certainty}).`,\n {\n cause: errorCause(reason),\n meta: {\n method: \"settled\",\n commitCertainty: outcome.certainty,\n },\n }\n );\n }\n }\n if (first) throw first;\n}\n","/**\n * The `admit` hooks of a chain whose parts concern a member of\n * `$transaction([...])`. Where `around` parts may wrap a member, before the\n * one executor (`@client/array-transaction`) sends anything, every member's\n * handlers start and the array waits until each reached `run()` or failed: a\n * refusal, a second `run()`, a late detached one or a handler that throws\n * aborts the array, and nothing is sent. Where parts only hear a member's\n * writes, nothing waits: each member's registration is staged and its child\n * handed what tells it of the commit (`stageArray`).\n */\nimport {\n type ArraySlot,\n createArrayDeferred,\n memberValue,\n} from \"@client/array-transaction\";\nimport {\n type TransactionOperationCapability,\n transactionOperationOwner,\n} from \"@query-engine/transaction-operation\";\nimport {\n type AdmissionHooks,\n type executePreparedQuery,\n executeRegisteredQuery,\n type TransactionScope,\n type WriteOutcomeNotifications,\n} from \"./query\";\n\n/** What admission reads and writes of a slot. */\nexport type AdmissionSlot = Omit<ArraySlot, \"operation\" | \"owner\">;\n\n/** Whether a part intercepts one of the members, once they are prepared. */\nexport function interceptsArray(\n operations: readonly TransactionOperationCapability[]\n): boolean {\n return operations.some((operation) => {\n const { handlers, registration } =\n transactionOperationOwner(operation).around(operation);\n return handlers?.length || registration;\n });\n}\n\n/**\n * The hook of a chain whose parts hear writes and wrap no call: a member with\n * a registration runs under it, its child reached at once, so the array has\n * nothing to wait for. Its value is then the registration's run, whose\n * rejection the array reads in member order.\n */\nexport async function stageArray(\n slots: readonly ArraySlot[],\n scope: TransactionScope\n): Promise<undefined> {\n for (const slot of slots) {\n const { write, registration } = slot.owner.around(slot.operation);\n if (registration === undefined) continue;\n const child = (notifications?: WriteOutcomeNotifications) => {\n slot.notifications = notifications;\n return slot.child.promise;\n };\n const query = executeRegisteredQuery(\n undefined,\n undefined,\n child,\n write,\n scope,\n undefined,\n registration\n );\n slot.query = query;\n // Read by the array in member order; one the array never reaches (it\n // failed before) is settled here.\n query.catch(ignore);\n }\n return undefined;\n}\n\nconst ignore = (): undefined => undefined;\n\n/**\n * The hook: each member's handlers started, in member order, by `execute`\n * (the chain's runner of a prepared call), which stages what it registered;\n * a member with nothing to intercept is admitted at once.\n */\nexport function admitArray(\n slots: readonly ArraySlot[],\n scope: TransactionScope,\n execute: typeof executePreparedQuery\n): Promise<readonly unknown[] | undefined> {\n const facts = slots.map((slot) => slot.owner.around(slot.operation));\n return admitArrayQueries(slots, (slot, child, hooks) => {\n const { context, handlers, write, registration } =\n facts[slots.indexOf(slot)]!;\n return handlers?.length || registration\n ? execute(context, handlers, child, write, scope, hooks, registration)\n : child();\n });\n}\n\n/**\n * Start every member's handlers and release the array only after each has\n * reached its child. On a failure, every child rejects with the first one,\n * and the distinct failures each member reported return in member order.\n */\nexport async function admitArrayQueries<Slot extends AdmissionSlot>(\n slots: readonly Slot[],\n start: (\n slot: Slot,\n child: (notifications?: WriteOutcomeNotifications) => Promise<unknown>,\n hooks: AdmissionHooks\n ) => Promise<unknown>\n): Promise<readonly unknown[] | undefined> {\n let failed: { readonly failure: unknown } | undefined;\n let remaining = slots.length;\n const signal = createArrayDeferred<void>();\n if (remaining === 0) signal.resolve();\n\n for (const slot of slots) {\n const reportAdmissionFailure = (failure: unknown): void => {\n const failures = (slot.admissionFailures ??= []);\n if (!failures.includes(failure)) failures.push(failure);\n failed ??= { failure };\n signal.reject(failure);\n };\n let query: Promise<unknown>;\n try {\n query = start(\n slot,\n (notifications) => {\n slot.notifications = notifications;\n // Reached once: a second `run()` is refused before its child.\n remaining -= 1;\n if (remaining === 0) signal.resolve();\n return slot.child.promise;\n },\n {\n reportAdmissionFailure,\n readCommitCertainty: () => slot.certainty,\n }\n );\n } catch (error) {\n reportAdmissionFailure(error);\n query = Promise.reject(error);\n }\n slot.query = query;\n query.catch(reportAdmissionFailure);\n }\n\n try {\n await signal.promise;\n // A handler that fails in the turn its member was admitted still aborts.\n await Promise.resolve();\n if (failed) throw failed.failure;\n return undefined;\n } catch (failure) {\n for (const slot of slots) slot.child.reject(failure);\n await Promise.allSettled(slots.map(memberValue));\n const reported: unknown[] = [];\n for (const slot of slots)\n for (const failure of slot.admissionFailures ?? [])\n if (!reported.includes(failure)) reported.push(failure);\n return reported;\n }\n}\n","/**\n * What a part that wraps a call's execution brings beside its own state: how\n * a prepared call runs (under write-outcome registrations, under `around`\n * parts), and, for the parts an array member can be intercepted by, how the\n * one executor of `$transaction([...])` (`@client/array-transaction`)\n * admits its members. A chain of none of those parts carries none of it.\n *\n * And how every transaction scope runs (`transact`): what a call registers\n * there waits in its scope, and the first registration installs the\n * collector by value (`collect`, imported by what registers: `settled`, the\n * part that watches writes, `unit` parts), so an extension behaves the same\n * whatever else its chain holds, and a transaction where nothing registers\n * runs none of that code.\n */\nimport type { ArraySlot } from \"@client/array-transaction\";\nimport { appendExecutionTransactionPhases } from \"@drivers/execution-context\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport { afterFulfilled } from \"@drivers/rejection-observed-promise\";\nimport type { TransactionOptions } from \"@drivers/shared/transaction-options\";\nimport type { QueryEngine } from \"@query-engine/query-engine\";\nimport { admitArray, interceptsArray, stageArray } from \"./array-admission\";\nimport {\n type CommitPhase,\n type collect,\n executePreparedQuery,\n executeRegisteredQuery,\n type TransactionScope,\n} from \"./query\";\n\n/** The commit certainty one array reports to its `batch` unit. */\nexport type ArrayCertainty = CommitPhase;\n\nexport interface Coordination {\n /** What it adds to the one before it: a chain keeps the highest it needs. */\n readonly rank: number;\n /**\n * Where its parts hear writes: the collector installed in each transaction\n * scope from its start, so the scope's failure carries its commit\n * certainty even when nothing registered.\n */\n readonly collect?: typeof collect;\n /**\n * What runs a prepared call under the chain's `around` parts and what it\n * registered: absent where neither exists (`unit` parts alone), since\n * core asks it only of a call that has handlers or a registration.\n */\n readonly executePreparedQuery?: typeof executePreparedQuery;\n /** Present with `admit`: whether a part intercepts one of the members. */\n readonly intercepts?: typeof interceptsArray;\n /**\n * Present where a member of `$transaction([...])` may be intercepted:\n * starts every member's handlers and waits until each reached `run()`,\n * before anything is sent. Resolves to the failures that abort the array.\n */\n readonly admit?: (\n slots: readonly ArraySlot[],\n scope: TransactionScope\n ) => ReturnType<typeof admitArray>;\n}\n\n/**\n * For `unit` parts: nothing of the chain wraps a call, the prepared call\n * runs as it is.\n */\nexport const UNITS: Coordination = { rank: -1 };\n\n/**\n * For the part that watches writes: an array member it hears runs under its\n * registration, and nothing waits, since no handler wraps it.\n */\nexport const ARRAYS: Coordination = {\n rank: 1,\n executePreparedQuery: executeRegisteredQuery,\n intercepts: interceptsArray,\n admit: stageArray,\n};\n\n/** For `around` parts: what runs their second moments around a call, too. */\nexport const QUERIES: Coordination = {\n rank: 2,\n executePreparedQuery,\n intercepts: interceptsArray,\n admit: (slots, scope) => admitArray(slots, scope, executePreparedQuery),\n};\n\n/**\n * The chain being built coordinated as `needed` asks, never less than it\n * was; `collect` is kept whatever the rank.\n */\nexport function coordinate(\n next: { coordination?: Coordination; collect?: typeof collect },\n needed: Coordination,\n collects?: typeof collect\n): void {\n if (collects) next.collect = collects;\n if (next.coordination === undefined || needed.rank > next.coordination.rank)\n next.coordination = needed;\n}\n\n/**\n * Run one transaction scope. A savepoint's scope is a child of its parent's;\n * the outermost one hears its commit phases where a part may register, for\n * the certainty of what was registered in it. What its calls register installs\n * the collector that ends it (`TransactionWriteOutcomes.end`). A body run\n * again (a driver that reruns a callback on a conflict) gets a scope of its\n * own: nothing the failed run registered is told. An array's scope is made\n * before its members are admitted, and passed.\n */\nexport function transact<T>(\n engine: QueryEngine,\n options: TransactionOptions | undefined,\n context: QueryExecutionContext,\n body: (driver: AnyDriver, scope: TransactionScope) => Promise<T>,\n made?: TransactionScope,\n root: CommitPhase = made?.root ?? {}\n): Promise<T> {\n const chain = engine.extensionChain;\n const parent = engine.transaction;\n let scope: TransactionScope | undefined;\n const end =\n (failed?: true) =>\n (settled: T): T | Promise<T> => {\n // A driver that reports no phase still committed what resolved.\n if (!(failed || parent)) root.certainty = \"committed\";\n if (!scope?.outcomes) {\n if (failed) throw settled;\n return settled;\n }\n // The promise this handler returns is taken a microtask later, and\n // workerd reports a rejection no handler holds by then.\n const ended = scope.outcomes.end(scope, settled, failed);\n ended.catch(() => undefined);\n return ended;\n };\n const ran = engine.driver.withTransaction(\n (driver) => {\n scope = made ?? scopeOf(engine, root);\n return body(driver, scope);\n },\n options,\n // Only where a part may register: a chain of `call` parts, rules or\n // defaults alone runs its transactions as an unextended client does.\n parent || !(chain?.coordination || chain?.methods)\n ? context\n : appendExecutionTransactionPhases(context, {\n readyToCommit: () => {\n root.certainty = \"may-have-committed\";\n },\n committed: () => {\n root.certainty = \"committed\";\n },\n })\n );\n // A savepoint that fails drops what it collected: no handler of its\n // rejection, which only the caller's own observes (an unobserved one fails\n // the outer transaction, and is reported there alone).\n return parent ? afterFulfilled(ran, end()) : ran.then(end(), end(true));\n}\n\n/**\n * A transaction scope inside `engine`'s, with the collector of a chain whose\n * parts hear writes installed from its start.\n */\nexport function scopeOf(\n engine: QueryEngine,\n root: CommitPhase\n): TransactionScope {\n const scope = { parent: engine.transaction, root };\n engine.extensionChain?.collect?.(scope);\n return scope;\n}\n"],"mappings":"+eAuBA,SAAgB,mBACd,EACA,EACA,EACO,CACP,GAAI,EAAQ,OAAS,aACnB,OAAO,IAAI,EAAgB,EAAQ,QAAS,CAAE,KAAM,CAAE,QAAO,YAAW,CAAE,CAAC,CAE7E,GAAI,EAAQ,OAAS,cAAe,CAClC,IAAMA,EAAQ,IAAI,EAAiB,EAAQ,QAAS,EAAQ,UAAY,GAAG,CAI3E,OAHI,EAAQ,WACV,EAAM,KAAK,SAAW,IAEjBA,EAET,GAAI,EAAQ,OAAS,WACnB,OAAO,IAAI,EAAc,EAAO,EAAU,CAE5C,GAAI,EAAQ,OAAS,YACnB,OAAO,IAAI,EACT,EACA,EACA,EAAQ,SAAW,IAAA,GAAY,IAAA,GAAY,CAAE,OAAQ,EAAQ,OAAQ,CACtE,C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WAAY,gBACZ,MAAO,WACR,CAGY,EAAwB,CACnC,KAAM,EACN,qBACA,WAAY,gBACZ,OAAQ,EAAO,IAAU,WAAW,EAAO,EAAO,qBAAqB,CACxE,CAMD,SAAgB,WACd,EACA,EACA,EACM,CACF,IAAU,EAAK,QAAU,IACzB,EAAK,eAAiB,IAAA,IAAa,EAAO,KAAO,EAAK,aAAa,QACrE,EAAK,aAAe,GAYxB,SAAgB,SACd,EACA,EACA,EACA,EACA,EACA,EAAoB,GAAM,MAAQ,EAAE,CACxB,CACZ,IAAM,EAAQ,EAAO,eACf,EAAS,EAAO,YAClB,EACE,IACH,GACA,GAA+B,CAG9B,GADM,GAAU,IAAS,EAAK,UAAY,aACtC,CAAC,GAAO,SAAU,CACpB,GAAI,EAAQ,MAAM,EAClB,OAAO,EAIT,IAAM,EAAQ,EAAM,SAAS,IAAI,EAAO,EAAS,EAAO,CAExD,OADA,EAAM,UAAY,IAAA,GAAU,CACrB,GAEL,EAAM,EAAO,OAAO,gBACvB,IACC,EAAQ,GAAQ,QAAQ,EAAQ,EAAK,CAC9B,EAAK,EAAQ,EAAM,EAE5B,EAGA,GAAU,EAAE,GAAO,cAAgB,GAAO,SACtC,EACA,EAAiC,EAAS,CACxC,kBAAqB,CACnB,EAAK,UAAY,sBAEnB,cAAiB,CACf,EAAK,UAAY,aAEpB,CAAC,CACP,CAID,OAAO,EAAS,EAAe,EAAK,KAAK,CAAC,CAAG,EAAI,KAAK,KAAK,CAAE,IAAI,GAAK,CAAC,CAOzE,SAAgB,QACd,EACA,EACkB,CAClB,IAAM,EAAQ,CAAE,OAAQ,EAAO,YAAa,OAAM,CAElD,OADA,EAAO,gBAAgB,UAAU,EAAM,CAChC"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";let t;function currentInstant(){return t===void 0&&(t=new Date().toISOString(),queueMicrotask(()=>{t=void 0})),t}function currentTemporalValue(e){let t=currentInstant();return e===`date`?t.slice(0,10):e===`time`?t.slice(11,19):t}export{currentTemporalValue as t};
2
- //# sourceMappingURL=current-DBTlPsQg.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"current-DBTlPsQg.mjs","names":[],"sources":["../src/schema/scalars/datetime/current.ts"],"sourcesContent":["/** The wall-clock value shared by temporal `now` and `updatedAt` generators. */\nexport type TemporalKind = \"datetime\" | \"date\" | \"time\";\n\n/**\n * The instant every generator of the current synchronous run reads.\n *\n * A call's input is admitted in one synchronous run, and each `now` and\n * `updatedAt` field generates its value there, one after another: read\n * separately, a create's `createdAt` and `updatedAt` could straddle a\n * millisecond and differ. The first read of a run takes the clock and the\n * rest reuse it, until the run's microtasks run.\n */\nlet runInstant: string | undefined;\n\nfunction currentInstant(): string {\n if (runInstant === undefined) {\n runInstant = new Date().toISOString();\n queueMicrotask(() => {\n runInstant = undefined;\n });\n }\n return runInstant;\n}\n\n/**\n * Read the host wall clock (once per synchronous run) and spell it in one\n * temporal scalar's logical input language.\n */\nexport function currentTemporalValue(kind: TemporalKind): string {\n const timestamp = currentInstant();\n if (kind === \"date\") return timestamp.slice(0, 10);\n if (kind === \"time\") return timestamp.slice(11, 19);\n return timestamp;\n}\n"],"mappings":"yCAYA,IAAI,EAEJ,SAAS,gBAAyB,CAOhC,OANI,IAAe,IAAA,KACjB,EAAa,IAAI,MAAM,CAAC,aAAa,CACrC,mBAAqB,CACnB,EAAa,IAAA,IACb,EAEG,EAOT,SAAgB,qBAAqB,EAA4B,CAC/D,IAAM,EAAY,gBAAgB,CAGlC,OAFI,IAAS,OAAe,EAAU,MAAM,EAAG,GAAG,CAC9C,IAAS,OAAe,EAAU,MAAM,GAAI,GAAG,CAC5C"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,t as n}from"./value-guards-CBuxSC66.mjs";import{b as r,x as i,y as a}from"./native-types-DgjMUikz.mjs";const o=864e5,s=2440587.5;function encodePostgresTemporal(e){return e.startsWith(`0000-`)?`0001${e.slice(4)} BC`:e}function physicalNumber(e){if(t(e))return Number.isFinite(e)?e:void 0;if(n(e)){let t=Number(e);return Number.isSafeInteger(t)?t:void 0}}function encodePhysicalDateTime(e,t){if(t===`text`)return e;let n=Date.parse(e);return t===`epochMillis`?n:n/o+s}function decodePhysicalDateTime(e,t){let n=physicalNumber(e);if(n===void 0)return;let i=t===`epochMillis`?n:Math.round((n-s)*o);if(r(i))return new Date(i)}const c=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?)?(?: (BC))?$/;function digitsAt(e,t,n){let r=0;for(let i=t;i<t+n;i+=1){let t=e.charCodeAt(i)-48;if(t<0||t>9)return-1;r=r*10+t}return r}function decodeCanonicalTimestamp(e){if(e.length!==24||e.charCodeAt(4)!==45||e.charCodeAt(7)!==45||e.charCodeAt(10)!==84||e.charCodeAt(13)!==58||e.charCodeAt(16)!==58||e.charCodeAt(19)!==46||e.charCodeAt(23)!==90)return!1;let t=digitsAt(e,0,4),n=digitsAt(e,5,2),o=digitsAt(e,8,2),s=digitsAt(e,11,2),c=digitsAt(e,14,2),l=digitsAt(e,17,2),u=digitsAt(e,20,3);if(t<100||n<0||o<0||s<0||c<0||l<0||u<0)return!1;if(!(i(t,n,o)&&a(s,c,l)))return;let d=Date.UTC(t,n-1,o,s,c,l,u);return r(d)?new Date(d):void 0}function decodeProviderTimestamp(e){let t=decodeCanonicalTimestamp(e);if(t!==!1)return t;let n=c.exec(e);if(!n)return;let o=n[13]?1-Number(n[1]):Number(n[1]),s=Number(n[2]),l=Number(n[3]),u=Number(n[4]),d=Number(n[5]),f=Number(n[6]),p=Number(n[10]??0),m=Number(n[11]??0),h=Number(n[12]??0);if(!(i(o,s,l)&&a(u,d,f))||p>23||m>59||h>59)return;let g=new Date(0);g.setUTCFullYear(o,s-1,l),g.setUTCHours(u,d,f,Number((n[7]??``).padEnd(3,`0`).slice(0,3)));let _=(p*3600+m*60+h)*1e3,v=g.getTime()-(n[9]===`-`?-_:_);return r(v)?new Date(v):void 0}const encodeMySqlDateTime=e=>new Date(e).toISOString().slice(0,23).replace(`T`,` `);export{encodePostgresTemporal as a,encodePhysicalDateTime as i,decodeProviderTimestamp as n,encodeMySqlDateTime as r,decodePhysicalDateTime as t};
2
- //# sourceMappingURL=datetime-physical-codec-Dj-APo9f.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"datetime-physical-codec-Dj-APo9f.mjs","names":[],"sources":["../src/validation/primitives/datetime-physical-codec.ts"],"sourcesContent":["/**\n * The ONE physical datetime codec.\n *\n * A datetime's LOGICAL value is an instant, and every layer above this one\n * spells it as a validated ISO-8601 string or a `Date`. Its PHYSICAL value is\n * whatever the column it lands in actually holds, and SQLite makes that a\n * DECLARED choice with three answers: timestamp TEXT, an INTEGER count of epoch\n * milliseconds, or a REAL Julian day. This module owns the conversion between\n * the two, so value lowering and result decoding cannot disagree about what a\n * column holds.\n *\n * The form is declared and never inferred, because a physical value cannot name\n * its own vocabulary: `2460324.9375` is 2024-01-15T10:30:00Z as a Julian day and\n * an instant in 1970 as milliseconds, and `1705314600000` is that same instant\n * as milliseconds and a date no calendar reaches as a Julian day.\n */\n\nimport { isBigInt, isNumber } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\n\n/**\n * The three physical spellings a datetime column can hold.\n *\n * `text` is the timestamp text every dialect stores by default, and its\n * conversion is the identity — the ISO string IS the physical value. The other\n * two are numbers, and each has an exact arithmetic.\n */\nexport type DateTimePhysicalForm = \"text\" | \"epochMillis\" | \"julianDay\";\n\n/**\n * The two forms whose physical value is a NUMBER rather than timestamp text.\n *\n * Named separately because the decode entry accepts only these: the textual\n * grammar a provider timestamp is held to belongs to the result boundary that\n * already owns it for every dialect, and duplicating it here would give one\n * spelling two readers.\n */\nexport type DateTimeNumericForm = Exclude<DateTimePhysicalForm, \"text\">;\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\n\n/** The Julian day of 1970-01-01T00:00:00Z, where the Unix epoch begins. */\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n\n/** PostgreSQL uses historical years: the admitted ISO year 0000 is 1 BC. */\nexport function encodePostgresTemporal(iso: string): string {\n return iso.startsWith(\"0000-\") ? `0001${iso.slice(4)} BC` : iso;\n}\n\n/**\n * The number a provider returned for a numeric datetime column, or `undefined`\n * when it returned something else.\n *\n * `bigint` is admitted because the SQLite family reads INTEGER columns in a\n * BigInt mode so values past 2^53 survive — an epoch-millisecond column is read\n * through that same mode. Every public DateTime instant is a safe integer, so a\n * bigint that does not survive the round trip is already outside the domain and\n * is refused here rather than rounded into it.\n */\nfunction physicalNumber(value: unknown): number | undefined {\n if (isNumber(value)) return Number.isFinite(value) ? value : undefined;\n if (isBigInt(value)) {\n // `Number(bigint)` is exact for every magnitude below 2^53, so the safe\n // test alone decides survival — an unsafe result is already outside the\n // public DateTime domain and there is no second case to check.\n const asNumber = Number(value);\n return Number.isSafeInteger(asNumber) ? asNumber : undefined;\n }\n return undefined;\n}\n\n/**\n * The physical value one VALIDATED ISO-8601 timestamp lands in a column as.\n *\n * The ISO boundary (`validateIsoTimestamp`) already owns \"this string names an\n * instant\", and every value lowered here has crossed it. REAL/Julian storage\n * needs no second admission branch: every millisecond in the four-digit public\n * DateTime domain survives its Julian-day double round trip. Behavior on any\n * other string is unspecified rather than re-guarded — one guard per invariant.\n */\nexport function encodePhysicalDateTime(\n iso: string,\n form: DateTimePhysicalForm\n): string | number {\n if (form === \"text\") return iso;\n const epochMilliseconds = Date.parse(iso);\n return form === \"epochMillis\"\n ? epochMilliseconds\n : epochMilliseconds / MILLISECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY;\n}\n\n/**\n * The instant one physical number holds, or `undefined` when the provider\n * returned a value this column's declared form cannot hold.\n *\n * A Julian day is a COUNT OF DAYS in a double, so its resolution near the\n * present is about fifty microseconds and a millisecond is not exactly\n * representable in it. The instant is therefore rounded to the nearest\n * millisecond — the same precision the logical value has — and then held to the\n * public four-digit instant range, so a day number outside the DateTime domain\n * is a malformed row rather than an extended-year `Date`.\n */\nexport function decodePhysicalDateTime(\n value: unknown,\n form: DateTimeNumericForm\n): Date | undefined {\n const physical = physicalNumber(value);\n if (physical === undefined) return undefined;\n const epochMilliseconds =\n form === \"epochMillis\"\n ? physical\n : Math.round((physical - UNIX_EPOCH_JULIAN_DAY) * MILLISECONDS_PER_DAY);\n if (!isDateTimeInstant(epochMilliseconds)) return undefined;\n return new Date(epochMilliseconds);\n}\n\nconst TIMESTAMP_TEXT =\n /^(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:(Z)|([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?(?: (BC))?$/;\n\n/** The digits `value` holds at `[at, at + count)`, or -1 where one is not a digit. */\nfunction digitsAt(value: string, at: number, count: number): number {\n let parsed = 0;\n for (let index = at; index < at + count; index += 1) {\n const digit = value.charCodeAt(index) - 48;\n if (digit < 0 || digit > 9) return -1;\n parsed = parsed * 10 + digit;\n }\n return parsed;\n}\n\n/**\n * The canonical stored spelling `YYYY-MM-DDTHH:MM:SS.sssZ` (what the\n * DateTime boundary writes), read by character: `false` for any other\n * spelling, and for a year below 100, which `Date.UTC` would read as 19xx.\n * The general grammar reads both; the domain rules are the same.\n */\nfunction decodeCanonicalTimestamp(value: string): Date | undefined | false {\n if (\n value.length !== 24 ||\n value.charCodeAt(4) !== 45 || // -\n value.charCodeAt(7) !== 45 || // -\n value.charCodeAt(10) !== 84 || // T\n value.charCodeAt(13) !== 58 || // :\n value.charCodeAt(16) !== 58 || // :\n value.charCodeAt(19) !== 46 || // .\n value.charCodeAt(23) !== 90 // Z\n )\n return false;\n const year = digitsAt(value, 0, 4);\n const month = digitsAt(value, 5, 2);\n const day = digitsAt(value, 8, 2);\n const hour = digitsAt(value, 11, 2);\n const minute = digitsAt(value, 14, 2);\n const second = digitsAt(value, 17, 2);\n const millisecond = digitsAt(value, 20, 3);\n if (\n year < 100 ||\n month < 0 ||\n day < 0 ||\n hour < 0 ||\n minute < 0 ||\n second < 0 ||\n millisecond < 0\n )\n return false;\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n )\n )\n return undefined;\n const epoch = Date.UTC(\n year,\n month - 1,\n day,\n hour,\n minute,\n second,\n millisecond\n );\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** The provider timestamp grammar; the domain rules are the codec's. */\nexport function decodeProviderTimestamp(value: string): Date | undefined {\n const canonical = decodeCanonicalTimestamp(value);\n if (canonical !== false) return canonical;\n const match = TIMESTAMP_TEXT.exec(value);\n if (!match) return undefined;\n const year = match[13] ? 1 - Number(match[1]) : Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const offsetHour = Number(match[10] ?? 0);\n const offsetMinute = Number(match[11] ?? 0);\n const offsetSecond = Number(match[12] ?? 0);\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n ) ||\n offsetHour > 23 ||\n offsetMinute > 59 ||\n offsetSecond > 59\n )\n return undefined;\n const parsed = new Date(0);\n // setUTCFullYear keeps years 0..99 literal; Date.UTC reinterprets them as 1900..1999.\n parsed.setUTCFullYear(year, month - 1, day);\n parsed.setUTCHours(\n hour,\n minute,\n second,\n Number((match[7] ?? \"\").padEnd(3, \"0\").slice(0, 3))\n );\n const offset = (offsetHour * 3600 + offsetMinute * 60 + offsetSecond) * 1000;\n const epoch = parsed.getTime() - (match[9] === \"-\" ? -offset : offset);\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** MySQL DATETIME stores the admitted instant as a naive UTC wall clock. */\nexport const encodeMySqlDateTime = (iso: string): string =>\n new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,GAEf,OACF,IAAM,EAAS,IAAI,KAAK,EAAE,CAE1B,EAAO,eAAe,EAAM,EAAQ,EAAG,EAAI,CAC3C,EAAO,YACL,EACA,EACA,EACA,QAAQ,EAAM,IAAM,IAAI,OAAO,EAAG,IAAI,CAAC,MAAM,EAAG,EAAE,CAAC,CACpD,CACD,IAAM,GAAU,EAAa,KAAO,EAAe,GAAK,GAAgB,IAClE,EAAQ,EAAO,SAAS,EAAI,EAAM,KAAO,IAAM,CAAC,EAAS,GAC/D,OAAO,EAAkB,EAAM,CAAG,IAAI,KAAK,EAAM,CAAG,IAAA,GAItD,MAAa,oBAAuB,GAClC,IAAI,KAAK,EAAI,CAAC,aAAa,CAAC,MAAM,EAAG,GAAG,CAAC,QAAQ,IAAK,IAAI"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,r as n}from"./extension-CGepsF-p.mjs";import{j as r}from"./scalar-BHCh7aUz.mjs";import{h as i}from"./validator-CZLW7aR3.mjs";import{i as a}from"./schema-BYA-_bpk.mjs";import{ut as o}from"./query-BZVHfA0s.mjs";import{h as s,m as c,n as l,p as u,t as d}from"./rule-words-ZIGm7cDm.mjs";function omitPart(e,t){return{seal({next:n}){let r={...n.omit?.config};r[e]=Object.freeze({...r[e],[t]:!0}),n.omit=Object.freeze({config:Object.freeze(r)})}}}const f=new Set([`json`,`vector`,`point`,`blob`]);function orderOf(e,t){let n=Array.isArray(t)?t:[t],{scalars:a}=e[`~`].state;return i(e).rowKey!==void 0&&n.length>0&&n.every(e=>{let[t,...n]=r(e)?Object.keys(e):[],i=t!==void 0&&Object.hasOwn(a,t)?a[t][`~`].state:void 0,o=i&&e[t];return n.length===0&&(o===`asc`||o===`desc`)&&!i.array&&!f.has(i.type)})?n.map(e=>({...e})):void 0}var PlainDomain=class{rows;queries;defaults=this;judge=void 0;project=void 0;#e;constructor(e,t){this.rows=e,this.queries=t}prepare(e,t){return this.queries.prepareSelector(e,t)}conjunction(){return null}reads(){return this.#e??=this.queries.under(this)}selector(){}bound(){}restrictsLinkWrite(){return!1}refuseHiddenLinkRow(){}};const p=new WeakMap;function preparePlain(e,t){let n=a(a(p,e,()=>new WeakMap),this.domain,()=>new PlainDomain(this.domain,e));return{rows:this,domain:n,defaults:n,instant:t}}const m=new Map;var PlainBinding=class{#e;#t;constructor({defaultOrder:e,stamps:t}){let n={root:m,related:m,...e&&{order:new Map(Object.entries(e))}};this.#t=t,this.#e={domain:n,...t&&{stamps:t.all},prepare:preparePlain}}call(e,t){let n=this.#t;return n?.named?{...this.#e,stamps:n.of(t)}:this.#e}};const bindPlain=e=>new PlainBinding(e),h=new Set([`orderBy`,`create`,`update`,`fields`]);var Omitted=class extends d{join({key:e,field:t,model:n,bring:r,refuse:i}){e!==`fields.${t}`&&i(`${e} does not take omitted`),r(omitPart(n,t))}};const g=omittedValue();function omittedValue(){return new Omitted}function stampOf(e,t,n){if(e===void 0)return;if(!r(e))return n(`data is an object of fields`);let i={};for(let[r,a]of Object.entries(e))Object.hasOwn(t,r)||n(`names unknown field "${r}"`),i[r]=a instanceof l&&a.stamp?a.stamp():a;return i}const merged=(e,t)=>t===void 0?e:{...e,...t};function writeDefaults(e,t,i){let a={order:{},data:{},brought:[]},{order:o,data:s,brought:c}=a;for(let[a,l]of Object.entries(t)){let refuse=t=>n(`Extension "${e}" defaults.${a}: ${t}.`,e);Object.hasOwn(i,a)||n(`Extension "${e}" defaults names unknown model "${a}".`,e),r(l)||refuse(`an entry is an object`);for(let e of Object.keys(l))h.has(e)||refuse(`"${e}" is not a defaults key`);let t=i[a],{scalars:u}=t[`~`].state;l.orderBy!==void 0&&(o[a]=orderOf(t,l.orderBy)??refuse(`orderBy maps a model with a key to { field: "asc" | "desc" } terms over its ordered scalars`));for(let e of[`create`,`update`]){let t=stampOf(l[e],u,refuse);t!==void 0&&(s[a]={...s[a],[e]:merged(s[a]?.[e],t)})}if(l.fields!==void 0){r(l.fields)||refuse(`fields is an object`);for(let[e,t]of Object.entries(l.fields)){let n=`fields.${e}`;t instanceof d||refuse(`${n} is written omitted`),t.join({model:a,key:n,field:e,schema:i,bring:e=>c.push(e),lazy:!1,entry:()=>refuse(`${n} is written omitted`),refuse})}}}return a}function defaultsPart(e){let n={join(r){let{name:i,next:a,schema:c}=r,{order:l,data:d,brought:f}=t(r,n,()=>writeDefaults(i,e(c),c));for(let e of f)r.bring(e);if(Object.keys(l).length>0&&(a.defaultOrder={...a.defaultOrder,...l}),Object.keys(d).length===0)return;let p=[],m={...a.defaultData};for(let[e,t]of Object.entries(d)){let n=m[e];m[e]={create:merged(n?.create,t.create),update:merged(n?.update,t.update)};for(let e of[...Object.values(t.create??{}),...Object.values(t.update??{})])e instanceof o&&e.arg!==void 0&&p.push(e.arg)}s(r,p),a.defaultData=m,a.stamps=new u(a.defaultData)},seal(e){c(e,bindPlain)}};return n}function defaults(e){return defaultsPart(t=>typeof e==`function`?e(t):e)}export{g as n,defaults as t};
2
- //# sourceMappingURL=defaults-DwOHWI_M.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{A as t,O as n,k as r}from"./error-mapping-B1-IWkCQ.mjs";import{B as i}from"./scalar-BHCh7aUz.mjs";import{t as a}from"./validation-CYaJ8ndO.mjs";import{h as o,i as s}from"./unit-words-CT0yeqfZ.mjs";import{E as c,_ as l,a as u,c as d,n as f,r as p,t as m}from"./spans-XDUFeTzC.mjs";const h=`:reval`,g=3e4;function scheduleBackground(e,t){let n=e.catch(()=>void 0);if(t)try{t(n)}catch{}}async function marker(e,t,n){let r=`${t}${h}`;if(!n)return await e.delete([r]),!1;let i=await e.get(r);return i&&e.now()-i.createdAt<i.ttl?!1:(await e.set(r,g,{value:!0,createdAt:e.now(),ttl:g}),!0)}const _=`viborm`,v=`${_}:cache`;function encodeText(e){return e.split(``).map(e=>e.charCodeAt(0).toString(16).padStart(4,`0`)).join(``)}function encodeVersion(e){if(e===void 0)return`u`;if(typeof e==`number`){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!1),`n:${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}return`s:${encodeText(e)}`}function createOfficialCacheNamespace(e){return[v,`r6`,`d:${encodeText(e.dialect)}`,e.namespace===void 0?`x`:`k:${encodeText(e.namespace)}`,encodeVersion(e.version)].join(`:`)}function fastHash(e){let t=3735928559,n=1103547991;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),(n>>>0).toString(16).padStart(8,`0`)+(t>>>0).toString(16).padStart(8,`0`)}const y=/^(\d+(?:\.\d+)?)\s*(?:(ms|milliseconds?)|(s|sec|seconds?)|(m|min|minutes?)|(h|hr|hours?)|(d|days?)|(w|weeks?)|(months?))$/,b=[1,1e3,6e4,36e5,864e5,6048e5,2592e6];function parseTTL(e){if(typeof e==`number`){if(!Number.isFinite(e)||e<=0||e>2**53-1)throw new t(`TTL must be positive, got: ${e}`);return e}let n=y.exec(e.trim().toLowerCase());if(!n)throw new t(`Invalid TTL format: "${e}". Expected format: "<number> <unit>" (e.g., "1 hour", "20 seconds"), the unit one of ms, s, sec, m, min, h, hr, d, w, month, or a word for it.`);let r=Math.floor(Number.parseFloat(n[1])*b[n.slice(2).findIndex(e=>e!==void 0)]);if(!Number.isSafeInteger(r)||r<=0)throw new t(`TTL must be positive, got: ${r}ms from "${e}"`);return r}const x=i.object({invalidate:i.string({array:!0,optional:!0}),autoInvalidate:i.boolean({optional:!0,default:!0})},{optional:!0,default:{autoInvalidate:!0}});function hasCacheInvalidationWork(e){return e===void 0||e.autoInvalidate===!0||e.invalidate!==void 0&&e.invalidate.length>0}const S=300*1e3,C=i.object({ttl:i.coerce(i.optional(i.union([i.string(),i.number()]),S),parseTTL),swr:i.coerce(i.optional(i.union([i.boolean(),i.string(),i.number()])),e=>e===void 0||typeof e==`boolean`?e:parseTTL(e)),key:i.string({optional:!0}),bypass:i.boolean({optional:!0})},{optional:!0,default:{ttl:S,swr:!1,bypass:!1}}),w=Object.freeze([`findFirst`,`findMany`,`findUnique`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]);function refused(e,t){throw new n(`Invalid ${e}: ${t.map(e=>e.message).join(`, `)}`)}function admitMutationOptions(e){let t=a(x,e);t.issues&&refused(`mutation cache options`,t.issues);let{autoInvalidate:n,invalidate:r}=t.value;if(r===void 0)return Object.freeze({autoInvalidate:n});let i=[...r];return Object.freeze(i),Object.freeze({autoInvalidate:n,invalidate:i})}function admitReadOptions(e){let t=a(C,e);t.issues&&refused(`cache options`,t.issues);let{bypass:n,key:r,ttl:i,swr:o}=t.value;return Object.freeze({ttlMs:i,swr:o===void 0||o===!1?!1:i+(o===!0?i:o),bypass:n,...r===void 0?{}:{key:r}})}const cacheOutcome=(e,t,n,r)=>({log:`cache`,at:Date.now(),meta:{event:e,status:t},error:n,...r});function placeSetFailure(e,t,n,r){s(e,cacheOutcome(`miss`,`cache-set-failed`,t))||s(n,cacheOutcome(`miss`,`cache-set-failed`,t,r))}function cacheStep(e,t,n,r,i){if(t===void 0)return r();let a={[m]:n,...i===void 0?{}:{[p]:String(i)},...e===`delete`||e===`clear`?{[l]:void 0}:{}};return o(t,{kind:`cache`,operation:e,note:{span:`viborm.cache.${e}`,attributes:a}},r)}const revalidationStart=(e,t)=>({...cacheOutcome(`revalidate`,`start`,void 0,e),span:c,root:!0,database:t,attributes:{[u]:e.model,[d]:e.operation}}),T={now:()=>Date.now(),setTimeout:(e,t)=>{let n=setTimeout(e,t);return{cancel:()=>clearTimeout(n),unref:()=>n.unref?.()}}},E=Symbol(`serve`),D=Symbol(`invalidate`),O=Symbol(`get`),k=Symbol(`set`),A=Symbol(`drop`),j=Symbol(`backend`);function scopedKey(e,t){if(t.startsWith(`${_}:`))throw new r(`Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.`);return`${e}:${t}`}var CacheDriver=class{#e=0;driverName;clock;constructor(e,t=T){this.driverName=e,this.clock=t}async[E](e){let{id:t,read:n,namespace:r,codec:i,model:a,operation:o,origin:c}=e,l=scopedKey(r,`${a}:${o}:${fastHash(t)}${n.key===void 0?``:`:${n.key}`}`),u=JSON.stringify([t,n.key]),d=this.#e,store=(e,t)=>this[k](l,e,{ttl:n.ttlMs,swrTtl:n.swr||void 0},c,t,u,d),f=`bypass`;if(!n.bypass){let t=await this[O](l,c);if(t?.identity===u){let{createdAt:n,ttl:r,expiresAt:a}=t;if([n,r,a].every(Number.isFinite)&&r>0&&a>=n){let a=i.materialize(t.value),o=this.clock.now();if(o-n<r)return s(c,cacheOutcome(`hit`)),a;if(e.revalidate?.({request:e,entry:t,now:o,key:l,backend:this[j](),store}))return a}}f=`miss`}let p=await i.run();if(d===this.#e)try{scheduleBackground(store(i.snapshot(),e),e.waitUntil)}catch(e){s(c,cacheOutcome(`miss`,`cache-set-failed`,e))}return s(c,cacheOutcome(f)),p}async[O](e,t){return cacheStep(`get`,t,this.driverName,async t=>{let n=await this.get(e);return t!==void 0&&s(t,{attributes:{[f]:n?this.clock.now()-n.createdAt>n.ttl?`stale`:`hit`:`miss`}}),n})}async[k](e,t,n,r,i,a,o){if(o!==void 0&&o!==this.#e)return;let s=n.swrTtl??n.ttl,c=this.clock.now(),l={value:t,createdAt:c,ttl:n.ttl,...a===void 0?{}:{identity:a,expiresAt:c+s}};return cacheStep(`set`,r,this.driverName,async t=>{try{await this.set(e,s,l),o!==void 0&&o!==this.#e&&await this.delete([e])}catch(e){throw i!==void 0&&t!==void 0&&placeSetFailure(i.origin,e,t,i),e}},n.ttl)}[j](){return{get:e=>this.get(e),set:(e,t,n)=>this.set(e,t,n),delete:e=>this.delete(e),now:()=>this.clock.now()}}async[D](e,t,n,r){if(!hasCacheInvalidationWork(t))return;this.#e+=1;let i=t===void 0||t.autoInvalidate===!0?[[`clear`,r(e)]]:[];for(let e of t?.invalidate??[])i.push(e.endsWith(`*`)?[`clear`,r(e.slice(0,-1))]:[`delete`,r(e)]);return cacheStep(`invalidate`,n,this.driverName,async e=>{await Promise.all(i.map(([t,n])=>this[A](t,n,e)))})}[A](e,t,n){return this.#e+=1,cacheStep(e,n,this.driverName,()=>e===`clear`?this.clear(t):this.delete([t,`${t}${h}`]))}};export{createOfficialCacheNamespace as _,D as a,scopedKey as c,w as d,admitMutationOptions as f,v as g,_ as h,O as i,cacheOutcome as l,hasCacheInvalidationWork as m,CacheDriver as n,E as o,admitReadOptions as p,A as r,k as s,j as t,revalidationStart as u,marker as v,scheduleBackground as y};
2
- //# sourceMappingURL=driver-BGVcgnIX.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"driver-BGVcgnIX.mjs","names":["v","#fillRevision"],"sources":["../src/cache/cache-background.ts","../src/cache/key.ts","../src/cache/ttl.ts","../src/cache/schema.ts","../src/cache/units.ts","../src/cache/driver.ts"],"sourcesContent":["import type { CacheEntry, WaitUntilFn } from \"./driver\";\n\nexport const REVALIDATING_SUFFIX = \":reval\";\nconst REVALIDATING_TTL_MS = 30_000;\n\nexport function scheduleBackground(\n promise: Promise<unknown>,\n waitUntil: WaitUntilFn | undefined\n): void {\n const observed = promise.catch(() => undefined);\n if (!waitUntil) return;\n try {\n waitUntil(observed);\n } catch {\n // Background scheduling cannot alter the authoritative query outcome.\n }\n}\n\n/** A driver's own storage primitives, unobserved, and its clock. */\nexport interface Backend {\n get(key: string): Promise<CacheEntry | null>;\n set(key: string, ttl: number, entry: CacheEntry): Promise<void>;\n delete(keys: string[]): Promise<void>;\n now(): number;\n}\n\n/**\n * Claim the refresh of the entry at `key` (whether this caller performs\n * it), or release the claim: a marker beside the entry, with a short TTL.\n */\nexport async function marker(\n backend: Backend,\n key: string,\n claim: boolean\n): Promise<boolean> {\n const marked = `${key}${REVALIDATING_SUFFIX}`;\n if (!claim) {\n await backend.delete([marked]);\n return false;\n }\n const existing = await backend.get(marked);\n if (existing && backend.now() - existing.createdAt < existing.ttl)\n return false;\n await backend.set(marked, REVALIDATING_TTL_MS, {\n value: true,\n createdAt: backend.now(),\n ttl: REVALIDATING_TTL_MS,\n });\n return true;\n}\n","/**\n * Cache key spaces: the official namespace one cache scope partitions on,\n * and the hash that names an entry inside it. What a read is keyed on is the\n * prepared call itself (`key(run)`).\n */\n\n/**\n * Prefix for all VibORM cache keys\n */\nexport const CACHE_PREFIX = \"viborm\";\n\n/** Namespace root reserved for the official cache extension's scopes. */\nexport const OFFICIAL_CACHE_NAMESPACE_ROOT = `${CACHE_PREFIX}:cache`;\n\n/**\n * Private storage-format revision. It moved r1 → r2 when the SQL namespace and\n * dialect entered the derivation below: every r1 entry keyed a scope that made\n * no claim about which schema or database produced the rows, so no r1 entry may\n * ever be served to an r2 reader. The bump is the invalidation.\n *\n * It moved r2 → r3 when a decimal became a value object. An r2 entry stored a\n * decimal's canonical text and MATERIALIZED it as that same string, which is\n * what an r2 reader's caller was handed; an r3 reader rebuilds a `Decimal` from\n * the identical bytes. The stored bytes did not change — their MEANING did, and\n * a reader that served the old bytes under the new contract would hand one\n * client a string where every other read gives it a value object. Same rule as\n * before: the bump is the invalidation.\n */\n// r4 entries carry their full canonical identity, checked before materialization.\n// r5 entries are keyed by the prepared call (`key(run)`): the statement the\n// engine sends, so a rule's filter, order and projection key an entry by\n// what they do to that statement.\n// r6 entries hold the rows the driver returned, not the decoded answer: an r5\n// answer read as rows would be refused at best.\nconst OFFICIAL_CACHE_SNAPSHOT_REVISION = \"r6\";\n\n/**\n * The facts one official cache scope partitions on.\n *\n * `dialect` is load-bearing on its own: a PostgreSQL schema `billing` and a\n * MySQL database `billing` are different stores that spell their qualifier the\n * same way. `namespace` is `undefined` for exactly the families the feature\n * leaves unqualified — SQLite and unbound MySQL/PlanetScale — and that absence\n * is encoded as its own token, never as text that a real namespace could spell.\n */\nexport interface OfficialCacheScopeFacts {\n readonly version: string | number | undefined;\n readonly dialect: string;\n readonly namespace: string | undefined;\n}\n\n/**\n * Encode text as fixed-width hex per UTF-16 code unit.\n *\n * Fixed width is what makes the joined namespace INJECTIVE: every component\n * below is either a bare discriminator letter or `<letter>:<hex>`, hex never\n * contains the `:` separator, and no variable-length body can absorb the\n * component after it. Two different fact tuples therefore cannot produce one\n * namespace, which is the whole isolation guarantee.\n */\nfunction encodeText(value: string): string {\n // `split(\"\")` gives the code units, never a pair as one code point.\n return value\n .split(\"\")\n .map((unit) => unit.charCodeAt(0).toString(16).padStart(4, \"0\"))\n .join(\"\");\n}\n\n/** `u` unversioned, `n:<f64 hex>` numeric, `s:<hex>` string. */\nfunction encodeVersion(version: string | number | undefined): string {\n if (version === undefined) return \"u\";\n if (typeof version === \"number\") {\n const bytes = new Uint8Array(8);\n new DataView(bytes.buffer).setFloat64(0, version, false);\n return `n:${Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n }\n return `s:${encodeText(version)}`;\n}\n\n/**\n * Build the private namespace for one client-bound official cache extension.\n *\n * Pure: the same facts always give the same string, which is why re-binding the\n * chain after another extension is appended retains the scope by value instead\n * of needing a registry to hand the old one back.\n */\nexport function createOfficialCacheNamespace(\n facts: OfficialCacheScopeFacts\n): string {\n return [\n OFFICIAL_CACHE_NAMESPACE_ROOT,\n OFFICIAL_CACHE_SNAPSHOT_REVISION,\n `d:${encodeText(facts.dialect)}`,\n // `x` unknown, `k:<hex>` known. An unknown namespace is a bare `x` with\n // no body, so it cannot be reached by encoding any string whatsoever — a\n // database literally named `undefined` encodes as `k:0075...`. Absence is\n // a distinct value here, not a spelling.\n facts.namespace === undefined ? \"x\" : `k:${encodeText(facts.namespace)}`,\n encodeVersion(facts.version),\n ].join(\":\");\n}\n\n/**\n * Fast non-cryptographic hash (djb2 variant)\n * Produces a 16-character hex string\n */\nexport function fastHash(str: string): string {\n let h1 = 0xde_ad_be_ef;\n let h2 = 0x41_c6_ce_57;\n\n for (let i = 0; i < str.length; i++) {\n const ch = str.charCodeAt(i);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h1 = Math.imul(h1 ^ ch, 2_654_435_761);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h2 = Math.imul(h2 ^ ch, 1_597_334_677);\n }\n\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3_266_489_909);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3_266_489_909);\n\n return (\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h2 >>> 0).toString(16).padStart(8, \"0\") +\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h1 >>> 0)\n .toString(16)\n .padStart(8, \"0\")\n );\n}\n","/**\n * TTL Parser\n *\n * Converts human-readable TTL strings to milliseconds.\n */\n\nimport { CacheInvalidTTLError } from \"@errors\";\n\n/** `<number> <unit>`, each unit's spellings one group, in the order of `UNIT_MS`. */\nconst TTL_PATTERN =\n /^(\\d+(?:\\.\\d+)?)\\s*(?:(ms|milliseconds?)|(s|sec|seconds?)|(m|min|minutes?)|(h|hr|hours?)|(d|days?)|(w|weeks?)|(months?))$/;\n\n/** Milliseconds per unit, a month being thirty days. */\nconst UNIT_MS = [1, 1e3, 6e4, 36e5, 864e5, 6048e5, 2592e6];\n\nexport function parseTTL(ttl: string | number): number {\n if (typeof ttl === \"number\") {\n if (!Number.isFinite(ttl) || ttl <= 0 || ttl > Number.MAX_SAFE_INTEGER) {\n throw new CacheInvalidTTLError(`TTL must be positive, got: ${ttl}`);\n }\n return ttl;\n }\n\n const match = TTL_PATTERN.exec(ttl.trim().toLowerCase());\n\n if (!match) {\n throw new CacheInvalidTTLError(\n `Invalid TTL format: \"${ttl}\". Expected format: \"<number> <unit>\" (e.g., \"1 hour\", \"20 seconds\"), the unit one of ms, s, sec, m, min, h, hr, d, w, month, or a word for it.`\n );\n }\n\n const result = Math.floor(\n Number.parseFloat(match[1]!) *\n UNIT_MS[match.slice(2).findIndex((unit) => unit !== undefined)]!\n );\n\n if (!Number.isSafeInteger(result) || result <= 0) {\n throw new CacheInvalidTTLError(\n `TTL must be positive, got: ${result}ms from \"${ttl}\"`\n );\n }\n\n return result;\n}\n","import { CacheConfigurationError } from \"@errors\";\nimport { parse } from \"@validation\";\nimport v, { type V } from \"@validation/primitives/v\";\nimport { parseTTL } from \"./ttl\";\n\n// =============================================================================\n// CACHE INVALIDATION SCHEMA (for mutations)\n// =============================================================================\n\ntype CacheInvalidationSchemaEntries = {\n invalidate: V.String<{ array: true; optional: true }>;\n autoInvalidate: V.Boolean<{ optional: true }>;\n};\n\nexport type CacheInvalidationSchema = V.Object<\n CacheInvalidationSchemaEntries,\n { optional: true }\n>;\n\nconst cacheInvalidationSchema = v.object(\n {\n /**\n * Specific keys to clear from cache\n * Can end with a * to invalidate all keys starting with the given prefix\n */\n invalidate: v.string({ array: true, optional: true }),\n /**\n * Automatically invalidate all entries in the bound cache scope after a durable mutation\n * @default true\n */\n autoInvalidate: v.boolean({ optional: true, default: true }),\n },\n { optional: true, default: { autoInvalidate: true } }\n);\n\n/**\n * Input type for cache invalidation options (inferred from schema)\n */\nexport type CacheInvalidationOptions =\n CacheInvalidationSchema[\" vibInferred\"][\"0\"];\n\n/** Whether normalized mutation options request any invalidation work. */\nexport function hasCacheInvalidationWork(\n options: CacheInvalidationOptions | undefined\n): boolean {\n return (\n options === undefined ||\n options.autoInvalidate === true ||\n (options.invalidate !== undefined && options.invalidate.length > 0)\n );\n}\n\n// =============================================================================\n// WITH CACHE OPTIONS SCHEMA (for $withCache method)\n// =============================================================================\n\n/**\n * Default TTL: 5 minutes (in milliseconds)\n */\nconst DEFAULT_CACHE_TTL = 5 * 60 * 1000;\n\ntype WithCacheSchemaEntries = {\n ttl: V.Optional<V.Union<[V.String, V.Number]>>;\n swr: V.Optional<V.Union<[V.Boolean, V.String, V.Number]>>;\n key: V.String<{ optional: true }>;\n bypass: V.Boolean<{ optional: true }>;\n};\n\nexport type WithCacheSchema = V.Object<\n WithCacheSchemaEntries,\n { optional: true }\n>;\n\nconst withCacheSchema = v.object(\n {\n /**\n * Time to live for cache entries\n * Can be a number (milliseconds) or a string like \"1 hour\", \"20 seconds\"\n * @default 300000 (5 minutes)\n */\n ttl: v.coerce(\n v.optional(v.union([v.string(), v.number()]), DEFAULT_CACHE_TTL),\n parseTTL\n ),\n /**\n * Enable stale-while-revalidate pattern\n * When true, returns stale data immediately and revalidates in background\n *\n * The value represents the \"stale window\" - how long data can be served stale.\n * Storage TTL is automatically calculated as `ttl + staleWindow`.\n *\n * Can be a boolean or a duration value (number in ms or string like \"1 hour\")\n * - true: stale window = ttl (storage TTL = 2x ttl)\n * - false/undefined: SWR disabled\n * - number/string: custom stale window duration (storage TTL = ttl + swr)\n * @default false\n */\n swr: v.coerce(\n v.optional(v.union([v.boolean(), v.string(), v.number()])),\n (value: boolean | string | number | undefined) =>\n value === undefined || typeof value === \"boolean\"\n ? value\n : parseTTL(value)\n ),\n /**\n * The official cache extension retains the canonical model/operation/args\n * key and appends this value as a suffix contribution.\n */\n key: v.string({ optional: true }),\n /**\n * Bypass cache read and force fresh data\n * Still writes result to cache for subsequent requests\n * @default false\n */\n bypass: v.boolean({ optional: true }),\n },\n {\n optional: true,\n default: {\n ttl: DEFAULT_CACHE_TTL,\n swr: false,\n bypass: false,\n },\n }\n);\n\n/**\n * Input type for $withCache options (inferred from schema)\n */\nexport type WithCacheOptions = WithCacheSchema[\" vibInferred\"][\"0\"];\n\n// =============================================================================\n// THE CACHE'S TWO ARGUMENTS, AND THE READS IT SERVES\n// =============================================================================\n\n/**\n * The reads a cached view serves, as its refusal of anything else lists\n * them.\n */\nexport const CACHEABLE: readonly string[] = Object.freeze([\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"findUniqueOrThrow\",\n \"findFirstOrThrow\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n]);\n\n/** One read's options, as the cache applies them. */\nexport interface CacheReadOptions {\n readonly ttlMs: number;\n readonly swr: number | false;\n readonly bypass: boolean;\n readonly key?: string;\n}\n\nfunction refused(what: string, issues: readonly { message: string }[]): never {\n throw new CacheConfigurationError(\n `Invalid ${what}: ${issues.map((issue) => issue.message).join(\", \")}`\n );\n}\n\n/**\n * A write's `cache` argument: what it invalidates once durable. Frozen, as\n * the argument a call admitted and nothing else holds.\n */\nexport function admitMutationOptions(value: unknown): CacheInvalidationOptions {\n const parsed = parse(cacheInvalidationSchema, value);\n if (parsed.issues) refused(\"mutation cache options\", parsed.issues);\n const { autoInvalidate, invalidate } = parsed.value;\n if (invalidate === undefined) return Object.freeze({ autoInvalidate });\n const keys = [...invalidate];\n Object.freeze(keys);\n return Object.freeze({ autoInvalidate, invalidate: keys });\n}\n\n/** `$withCache(options)`: the options of every read through the view. */\nexport function admitReadOptions(value: unknown): CacheReadOptions {\n const parsed = parse(withCacheSchema, value);\n if (parsed.issues) refused(\"cache options\", parsed.issues);\n const { bypass, key, ttl, swr } = parsed.value;\n return Object.freeze({\n ttlMs: ttl,\n // The SWR window: the stale window added to the TTL, `true` the TTL again.\n swr:\n swr === undefined || swr === false\n ? false\n : ttl + (swr === true ? ttl : swr),\n bypass,\n ...(key === undefined ? {} : { key }),\n });\n}\n","/**\n * The cache's units (`get`, `set`, `invalidate`, `revalidate`, and the\n * `delete` and `clear` an invalidation runs) and the outcomes of a read\n * (`hit`, a stale `hit`, `miss`, `bypass`, `cache-set-failed`), written with\n * the words any extension has: each step is a `cache` unit it emits with\n * `work` (on the call's context or `run`, a method's scope, or the unit of\n * the step it is part of), and what a presenter shows of it is noted on it\n * with `note`, in the shape the official instrumentation presents any\n * extension's units with (`InstrumentationNote`): the span as the unit\n * starts, then its attributes and its logs. A read's outcomes are noted on\n * the call's own `operation` unit.\n */\nimport type { UnitContext } from \"@extensions/contract\";\nimport type { Database } from \"@extensions/database\";\nimport { work } from \"@extensions/observation\";\nimport { note } from \"@extensions/unit-words\";\nimport {\n ATTR_CACHE_DRIVER,\n ATTR_CACHE_TTL,\n ATTR_DB_COLLECTION,\n ATTR_DB_OPERATION_NAME,\n ATTR_VIBORM_CORRELATION_ID,\n SPAN_OPERATION,\n type VibORMSpanName,\n} from \"../instrumentation/spans\";\nimport type { InstrumentationNote } from \"../instrumentation/types\";\n\n/** The call a step's logs name: its model and the operation it asked. */\ninterface CacheCall {\n readonly model: string;\n readonly operation: string;\n}\n\n/**\n * One decision of a read, as a cache log presents it: the call is named\n * where the note is not on the call's own unit. Never a key or a suffix.\n */\nexport const cacheOutcome = (\n event: string,\n status?: string,\n error?: unknown,\n call?: CacheCall\n): InstrumentationNote => ({\n log: \"cache\",\n at: Date.now(),\n meta: { event, status },\n error,\n ...call,\n});\n\n/**\n * A background set failure joins its read's outcomes while that read's\n * operation still runs, so it presents after the logical miss; otherwise the\n * set unit presents it itself.\n */\nexport function placeSetFailure(\n background: object,\n failure: unknown,\n unit: UnitContext,\n call: CacheCall | undefined\n): void {\n if (!note(background, cacheOutcome(\"miss\", \"cache-set-failed\", failure)))\n note(unit, cacheOutcome(\"miss\", \"cache-set-failed\", failure, call));\n}\n\n/**\n * Run one cache step as a `cache` unit of the chain `origin` belongs to;\n * `execute` is handed the unit, to note what the step learns. A step asked\n * with no origin (a backend method called directly) belongs to no chain.\n */\nexport function cacheStep<T>(\n step: \"get\" | \"set\" | \"invalidate\" | \"delete\" | \"clear\",\n origin: object | undefined,\n driverName: string,\n execute: (unit?: UnitContext) => Promise<T>,\n ttl?: number\n): Promise<T> {\n if (origin === undefined) return execute();\n const attributes: InstrumentationNote[\"attributes\"] = {\n [ATTR_CACHE_DRIVER]: driverName,\n ...(ttl === undefined ? {} : { [ATTR_CACHE_TTL]: String(ttl) }),\n // A backend step of an invalidation names its driver alone.\n ...(step === \"delete\" || step === \"clear\"\n ? { [ATTR_VIBORM_CORRELATION_ID]: undefined }\n : {}),\n };\n return work(\n origin,\n // Its span is the public `SPAN_CACHE_<STEP>`: spelled from the step,\n // which costs no bytes, and checked against those constants.\n {\n kind: \"cache\",\n operation: step,\n note: {\n span: `viborm.cache.${step}` satisfies VibORMSpanName,\n attributes,\n },\n },\n execute\n );\n}\n\n/**\n * What a revalidation's own `cache` unit starts with: it is presented as the\n * root operation it replays.\n */\nexport const revalidationStart = (\n call: CacheCall,\n database: Database\n): InstrumentationNote => ({\n ...cacheOutcome(\"revalidate\", \"start\", undefined, call),\n span: SPAN_OPERATION,\n root: true,\n database,\n attributes: {\n [ATTR_DB_COLLECTION]: call.model,\n [ATTR_DB_OPERATION_NAME]: call.operation,\n },\n});\n","/**\n * Cache Driver\n *\n * Abstract base class for cache implementations.\n * Follows the same pattern as the database Driver class.\n * Handles both storage operations and cache orchestration (hit/miss/stale/SWR).\n */\n\nimport { CacheInvalidKeyError } from \"@errors\";\nimport type { Database } from \"@extensions/database\";\nimport { note } from \"@extensions/unit-words\";\nimport { ATTR_CACHE_RESULT } from \"../instrumentation/spans\";\nimport {\n type Backend,\n REVALIDATING_SUFFIX,\n scheduleBackground,\n} from \"./cache-background\";\nimport { CACHE_PREFIX, fastHash } from \"./key\";\nimport {\n type CacheInvalidationOptions,\n type CacheReadOptions,\n hasCacheInvalidationWork,\n} from \"./schema\";\nimport { cacheOutcome, cacheStep, placeSetFailure } from \"./units\";\n\n/** A timer a `CacheClock` armed, cancelled through its handle. */\nexport interface CacheTimer {\n cancel(): void;\n /** Release the host's hold on the event loop, where it has one. */\n unref?(): void;\n}\n\n/**\n * Where a cache reads time and arms its timers: the host's own, unless a\n * test hands a clock it advances instead of sleeping through a TTL.\n */\nexport interface CacheClock {\n now(): number;\n setTimeout(callback: () => void, ms: number): CacheTimer;\n}\n\nconst hostClock: CacheClock = {\n // Read when called: a test's fake timers replace `Date.now`.\n now: () => Date.now(),\n setTimeout: (callback, ms) => {\n const timer = setTimeout(callback, ms);\n // A host that is not Node hands back a number, with no `unref`.\n return { cancel: () => clearTimeout(timer), unref: () => timer.unref?.() };\n },\n};\n\n/** Extend a request lifetime until background cache work settles. */\nexport type WaitUntilFn = (promise: Promise<unknown>) => void;\n\n/** Cache entry with freshness metadata for stale-while-revalidate. */\nexport interface CacheEntry<T = unknown> {\n value: T;\n createdAt: number;\n ttl: number;\n /** Exact operation identity on official detached entries. */\n identity?: string;\n /** Logical expiry, independent of a backend minimum physical TTL. */\n expiresAt?: number;\n}\n\n/** Storage options for a cache write. */\nexport interface CacheSetOptions {\n /** Time to live in milliseconds. */\n ttl: number;\n /** Storage TTL including the stale window, when SWR is enabled. */\n swrTtl?: number;\n}\n\n/**\n * One read's codec: `run` runs the prepared read (during the serve, or once\n * after it as a refresh), `snapshot` stores what that run returned.\n */\nexport interface DetachedCacheResultCodec<T> {\n run(): Promise<T>;\n snapshot(): unknown;\n materialize(snapshot: unknown): T;\n}\n\n/** One read the official cache serves, as its extension hands it over. */\ninterface CacheServe<T> {\n /** The prepared call's key: equal for two reads that send one statement. */\n readonly id: string;\n readonly codec: DetachedCacheResultCodec<T>;\n readonly read: CacheReadOptions;\n readonly namespace: string;\n readonly waitUntil: WaitUntilFn | undefined;\n readonly model: string;\n readonly operation: string;\n /** The call's `run`: what the read's units and outcomes belong to. */\n readonly origin: object;\n /** The database the read works against, which a revalidation presents. */\n readonly database: Database;\n /** What refreshes a stale entry: `staleWhileRevalidate`, when the cache was given it. */\n readonly revalidate?: Revalidate | undefined;\n}\n\n/**\n * One stale entry, as the driver hands it over: its read, its entry and\n * age, its prefixed key and the driver's backend (what the marker that\n * claims a refresh uses), and the store of the new rows.\n */\nexport interface Refresh {\n readonly request: CacheServe<unknown>;\n readonly entry: CacheEntry<unknown>;\n readonly now: number;\n readonly key: string;\n readonly backend: Backend;\n store(stored: unknown): Promise<void>;\n}\n\n/**\n * Whether a stale entry is served while it is refreshed in the background:\n * what `swr` brings, so a cache without it carries none of it.\n */\nexport type Revalidate = (refresh: Refresh) => boolean;\n\n/**\n * The keys of the two methods a driver serves its extension with: one read\n * through the store, and a namespace's invalidation. No package entry\n * exports them, so only the cache's own extension calls them.\n */\nexport const SERVE = Symbol(\"serve\");\nexport const INVALIDATE = Symbol(\"invalidate\");\n\n/**\n * The keys of the steps on a prefixed key the driver owns, observed as\n * `cache` units: what its extension and the unscoped storage functions\n * (`storage.ts`, which an application that never calls them does not carry)\n * reach. No package entry exports them either.\n */\nexport const GET = Symbol(\"get\");\nexport const SET = Symbol(\"set\");\nexport const DROP = Symbol(\"drop\");\nexport const BACKEND = Symbol(\"backend\");\n\n/** How a key is dropped: the entries under it, or the one entry it names. */\ntype Drop = \"clear\" | \"delete\";\n\n/**\n * A relative key rebased into an official scope. An EMPTY relative key is\n * the whole scope — `$invalidate(\"*\")` — and it rebases to `<scope>:`, WITH\n * the separator, because the storage backends clear by `startsWith`. A bare\n * `<scope>` would also match every sibling scope whose namespace string\n * merely extends this one, and one axis of the scope grammar can do that:\n * the cache `version` is the last component and its `s:` body is\n * variable-length, so `version: \"a\"` is a strict prefix of `version: \"ab\"`\n * at the same dialect and namespace. That axis is exactly what §7.1 leaves\n * users to partition SQLite and unbound MySQL databases with, so a\n * clear-all crossing it would empty a physically different database's\n * entries. Adding the separator loses nothing: every key this scope can hold\n * is `<model>:<operation>:<hash>`, so no stored key is ever equal to the\n * bare scope.\n */\nexport function scopedKey(namespace: string, key: string): string {\n if (key.startsWith(`${CACHE_PREFIX}:`)) {\n throw new CacheInvalidKeyError(\n \"Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.\"\n );\n }\n return `${namespace}:${key}`;\n}\n\n/**\n * Abstract base class for cache drivers.\n *\n * Follows the same pattern as the database Driver class:\n * - Protected abstract methods for concrete implementations (non-underscored)\n * - Symbol-keyed steps handle prefixed keys, instrumentation, and delegation\n * - Cache orchestration (hit/miss/stale/SWR logic)\n */\nexport abstract class CacheDriver {\n #fillRevision = 0;\n readonly driverName: string;\n /**\n * Every freshness decision this class makes reads from here. Internal seam,\n * not public API: it exists so tests can advance time rather than sleep\n * through a TTL. Defaults to the host clock.\n */\n protected readonly clock: CacheClock;\n\n constructor(driverName: string, clock: CacheClock = hostClock) {\n this.driverName = driverName;\n this.clock = clock;\n }\n\n // ============================================================\n // ABSTRACT METHODS - Concrete drivers implement these\n // ============================================================\n\n /**\n * Get a value from cache\n */\n protected abstract get<T>(key: string): Promise<CacheEntry<T> | null>;\n\n /**\n * Set a value in cache\n * @param key - The cache key\n * @param storageTtl - TTL for the backing store (already SWR-compliant)\n * @param entry - Cache entry with user's original TTL for staleness checks\n */\n protected abstract set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void>;\n\n /**\n * Delete keys from cache\n * @param keys - Array of keys to delete\n */\n protected abstract delete(keys: string[]): Promise<void>;\n\n /**\n * Clear cache by prefix\n * @param prefix - Always provided (at minimum CACHE_PREFIX to avoid clearing unrelated data)\n */\n protected abstract clear(prefix: string): Promise<void>;\n\n // ============================================================\n // CACHE ORCHESTRATION - Hit/Miss/Stale/SWR logic\n // ============================================================\n\n async [SERVE]<T>(request: CacheServe<T>): Promise<T> {\n const { id, read, namespace, codec, model, operation, origin } = request;\n const cacheKey = scopedKey(\n namespace,\n `${model}:${operation}:${fastHash(id)}${read.key === undefined ? \"\" : `:${read.key}`}`\n );\n const identity = JSON.stringify([id, read.key]);\n const revision = this.#fillRevision;\n const store = (stored: unknown, background?: CacheServe<unknown>) =>\n this[SET](\n cacheKey,\n stored,\n { ttl: read.ttlMs, swrTtl: read.swr || undefined },\n origin,\n background,\n identity,\n revision\n );\n let outcome = \"bypass\";\n if (!read.bypass) {\n const cached = await this[GET]<unknown>(cacheKey, origin);\n // Read as the backend gives it: an entry of another identity, or whose\n // times are not a finite span, is a miss.\n if (cached?.identity === identity) {\n const { createdAt, ttl, expiresAt } = cached;\n if (\n [createdAt, ttl, expiresAt].every(Number.isFinite) &&\n ttl > 0 &&\n expiresAt! >= createdAt\n ) {\n const value = codec.materialize(cached.value);\n const now = this.clock.now();\n if (now - createdAt < ttl) {\n note(origin, cacheOutcome(\"hit\"));\n return value;\n }\n if (\n request.revalidate?.({\n request,\n entry: cached,\n now,\n key: cacheKey,\n backend: this[BACKEND](),\n store,\n })\n )\n return value;\n }\n }\n outcome = \"miss\";\n }\n const result = await codec.run();\n if (revision === this.#fillRevision) {\n try {\n // The observed set unit presents a failure, which the background\n // promise then holds.\n scheduleBackground(store(codec.snapshot(), request), request.waitUntil);\n } catch (error) {\n note(origin, cacheOutcome(\"miss\", \"cache-set-failed\", error));\n }\n }\n note(origin, cacheOutcome(outcome));\n return result;\n }\n\n // ============================================================\n // STEPS - on prefixed keys, observed as `cache` units\n // ============================================================\n\n async [GET]<T>(\n prefixedKey: string,\n origin?: object\n ): Promise<CacheEntry<T> | null> {\n return cacheStep(\"get\", origin, this.driverName, async (unit) => {\n const entry = await this.get<T>(prefixedKey);\n if (unit !== undefined)\n note(unit, {\n attributes: {\n [ATTR_CACHE_RESULT]: entry\n ? this.clock.now() - entry.createdAt > entry.ttl\n ? \"stale\"\n : \"hit\"\n : \"miss\",\n },\n });\n return entry;\n });\n }\n\n async [SET]<T>(\n prefixedKey: string,\n value: T,\n options: CacheSetOptions,\n origin?: object,\n /** The read a background set belongs to, whose outcomes a failure joins. */\n background?: CacheServe<unknown>,\n identity?: string,\n revision?: number\n ): Promise<void> {\n if (revision !== undefined && revision !== this.#fillRevision) return;\n // Use SWR TTL if provided, otherwise just use regular TTL\n const storageTtl = options.swrTtl ?? options.ttl;\n const createdAt = this.clock.now();\n const entry: CacheEntry<T> = {\n value,\n createdAt,\n ttl: options.ttl,\n ...(identity === undefined\n ? {}\n : { identity, expiresAt: createdAt + storageTtl }),\n };\n\n return cacheStep(\n \"set\",\n origin,\n this.driverName,\n async (unit) => {\n try {\n await this.set(prefixedKey, storageTtl, entry);\n // A durable invalidation may finish while a backend set is pending.\n // Suppress this obsolete fill locally; generic KV remains eventual.\n if (revision !== undefined && revision !== this.#fillRevision)\n await this.delete([prefixedKey]);\n } catch (failure) {\n if (background !== undefined && unit !== undefined)\n placeSetFailure(background.origin, failure, unit, background);\n throw failure;\n }\n },\n options.ttl\n );\n }\n\n /** The backend's own primitives, unobserved, and the clock. */\n [BACKEND](): Backend {\n return {\n get: (key) => this.get(key),\n set: (key, ttl, entry) => this.set(key, ttl, entry),\n delete: (keys) => this.delete(keys),\n now: () => this.clock.now(),\n };\n }\n\n /**\n * Invalidate after a mutation: the entries under `prefix` (relative keys\n * rebased by `prefixed`), and the targets `options` names.\n */\n async [INVALIDATE](\n prefix: string,\n options: CacheInvalidationOptions | undefined,\n origin: object | undefined,\n prefixed: (key: string) => string\n ): Promise<void> {\n if (!hasCacheInvalidationWork(options)) return;\n this.#fillRevision += 1;\n // Every target is rebased, and so validated, before any is dropped.\n const targets: [Drop, string][] =\n options === undefined || options.autoInvalidate === true\n ? [[\"clear\", prefixed(prefix)]]\n : [];\n for (const entry of options?.invalidate ?? [])\n targets.push(\n entry.endsWith(\"*\")\n ? [\"clear\", prefixed(entry.slice(0, -1))]\n : [\"delete\", prefixed(entry)]\n );\n return cacheStep(\"invalidate\", origin, this.driverName, async (unit) => {\n await Promise.all(\n targets.map(([drop, key]) => this[DROP](drop, key, unit))\n );\n });\n }\n\n /**\n * Optional: connect to cache backend\n */\n connect?(): Promise<void>;\n\n /**\n * Optional: disconnect from cache backend\n */\n disconnect?(): Promise<void>;\n\n /**\n * Drop the entries under `prefixedKey` (`clear`), or that entry and its\n * revalidation marker (`delete`). Not `async`: a step that fails is\n * rejected by the promise the caller holds, with no promise between them\n * left a tick without a handler (workerd reports one).\n */\n [DROP](drop: Drop, prefixedKey: string, origin?: object): Promise<void> {\n this.#fillRevision += 1;\n return cacheStep(drop, origin, this.driverName, () =>\n drop === \"clear\"\n ? this.clear(prefixedKey)\n : this.delete([prefixedKey, `${prefixedKey}${REVALIDATING_SUFFIX}`])\n );\n }\n}\n"],"mappings":"wUAEA,MAAa,EAAsB,SAC7B,EAAsB,IAE5B,SAAgB,mBACd,EACA,EACM,CACN,IAAM,EAAW,EAAQ,UAAY,IAAA,GAAU,CAC1C,KACL,GAAI,CACF,EAAU,EAAS,MACb,GAiBV,eAAsB,OACpB,EACA,EACA,EACkB,CAClB,IAAM,EAAS,GAAG,IAAM,IACxB,GAAI,CAAC,EAEH,OADA,MAAM,EAAQ,OAAO,CAAC,EAAO,CAAC,CACvB,GAET,IAAM,EAAW,MAAM,EAAQ,IAAI,EAAO,CAQ1C,OAPI,GAAY,EAAQ,KAAK,CAAG,EAAS,UAAY,EAAS,IACrD,IACT,MAAM,EAAQ,IAAI,EAAQ,EAAqB,CAC7C,MAAO,GACP,UAAW,EAAQ,KAAK,CACxB,IAAK,EACN,CAAC,CACK,ICvCT,MAAa,EAAe,SAGf,EAAgC,GAAG,EAAa,QAgD7D,SAAS,WAAW,EAAuB,CAEzC,OAAO,EACJ,MAAM,GAAG,CACT,IAAK,GAAS,EAAK,WAAW,EAAE,CAAC,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAAC,CAC/D,KAAK,GAAG,CAIb,SAAS,cAAc,EAA8C,CACnE,GAAI,IAAY,IAAA,GAAW,MAAO,IAClC,GAAI,OAAO,GAAY,SAAU,CAC/B,IAAM,EAAQ,IAAI,WAAW,EAAE,CAE/B,OADA,IAAI,SAAS,EAAM,OAAO,CAAC,WAAW,EAAG,EAAS,GAAM,CACjD,KAAK,MAAM,KAAK,EAAQ,GAAS,EAAK,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAAC,CAAC,KAAK,GAAG,GAEtF,MAAO,KAAK,WAAW,EAAQ,GAUjC,SAAg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,OAAA,GAAsB,EACf,UAAU,EAAM,EAAQ,KAAK,eAClC,IAAS,QACL,KAAK,MAAM,EAAY,CACvB,KAAK,OAAO,CAAC,EAAa,GAAG,IAAc,IAAsB,CAAC,CACvE"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{t}from"./async-dispose-d96wFNu6.mjs";import{H as n,N as r,R as i,c as a,d as o,h as s,l as c,n as l,p as u,r as d,s as f,z as p}from"./error-mapping-B1-IWkCQ.mjs";import{c as m,n as h,y as g}from"./base-z-cH5ZBI.mjs";import{i as _,m as v,r as y}from"./validation--qS7OPmg.mjs";import{n as b}from"./transaction-BNomMtme.mjs";import{c as x,n as S,t as C}from"./normalized-result-B8pifWS0.mjs";import{t as w}from"./sql-3o4DOKm9.mjs";import{n as T}from"./suppressed-failure-CQkQsMVS.mjs";import{o as E}from"./value-guards-CBuxSC66.mjs";import{n as D,t as O}from"./bind-parameter-capacity-BMD-bxMO.mjs";import{a as k,i as A,o as j,r as M,s as N,t as P}from"./provider-parameter-snapshot-BikrgKqI.mjs";import{i as F,n as I,r as L,t as R}from"./driver-diagnostics-DW9NdckJ.mjs";import{n as z,t as B}from"./settle-1cy5x_52.mjs";var SavepointQueue=class{queue=[];head=0;processing=!1;get busy(){return this.processing}enqueue(e,t){return new Promise((n,r)=>{let i=!1,a;t&&(a=setTimeout(()=>{i=!0,r(t.onMaxWaitExceeded())},t.maxWaitMs));let o,s=new Promise(e=>{o=e}).then(async()=>{if(a&&clearTimeout(a),!i)try{n(await e())}catch(e){r(e)}});this.queue.push(()=>(o(),s)),this.scheduleFlush()})}run(e,t){if(this.processing)return this.enqueue(e,t);this.processing=!0;let n=e(),release=()=>this.flush();return n.then(release,release),n}scheduleFlush(){this.processing||(this.processing=!0,queueMicrotask(()=>this.flush()))}async flush(){for(;this.head<this.queue.length;){let e=this.queue[this.head++];e&&await e()}this.queue=[],this.head=0,this.processing=!1}};const V=[`ReadUncommitted`,`ReadCommitted`,`RepeatableRead`,`Serializable`],methodForForm=e=>e===`batch`?`$transaction([...])`:`$transaction(callback)`;function invalidTransactionOptions(e,t){return new b(e,{code:h.INVALID_TRANSACTION_INPUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}function refuseTransactionOption(e,t,n){return new v(`Driver "${n.driverName}" cannot honor the "${e}" transaction option on ${methodForForm(n.form)}: ${t}`,{meta:{driver:n.driverName,method:methodForForm(n.form)}})}function transactionTimeoutError(e,t){return new b(`Transaction on driver "${t.driverName}" exceeded its timeout of ${e}ms and was rolled back.`,{code:h.TRANSACTION_TIMEOUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}function transactionMaxWaitError(e,t){return new b(`Transaction on driver "${t.driverName}" waited longer than maxWait (${e}ms) for a transaction slot and never started.`,{code:h.TRANSACTION_TIMEOUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}const isIsolationLevel=e=>V.includes(e);function readDurationOption(e,t,n){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw invalidTransactionOptions(`Transaction option "${t}" must be a positive finite number of milliseconds.`,n);return e}function parseTransactionOptions(e,t){if(e===void 0)return;if(!E(e))throw invalidTransactionOptions(`Transaction options must be an object.`,t);let n=t.form===`batch`?[`isolationLevel`]:[`isolationLevel`,`timeout`,`maxWait`];for(let r of Reflect.ownKeys(e))if(!(typeof r==`string`&&n.includes(r)))throw t.form===`batch`&&(r===`timeout`||r===`maxWait`)?invalidTransactionOptions(`Transaction option "${r}" is not available on $transaction([...]): an array of operations has no interactive window to bound. Use the callback form.`,t):invalidTransactionOptions(`Unknown transaction option "${String(r)}". Supported options are ${n.map(e=>`"${e}"`).join(`, `)}.`,t);let r={};if(e.isolationLevel!==void 0){if(!isIsolationLevel(e.isolationLevel))throw invalidTransactionOptions(`Unknown isolation level ${JSON.stringify(e.isolationLevel)}. Supported levels are ${V.map(e=>`"${e}"`).join(`, `)}.`,t);r.isolationLevel=e.isolationLevel}return e.timeout!==void 0&&(r.timeout=readDurationOption(e.timeout,`timeout`,t)),e.maxWait!==void 0&&(r.maxWait=readDurationOption(e.maxWait,`maxWait`,t)),r}const H={ReadUncommitted:`READ UNCOMMITTED`,ReadCommitted:`READ COMMITTED`,RepeatableRead:`REPEATABLE READ`,Serializable:`SERIALIZABLE`};function isolationLevelStatement(e){return`SET TRANSACTION ISOLATION LEVEL ${H[e]}`}function resolveIsolationLevel(e,t,n){switch(t.isolationLevel){case`provider`:return{placement:`provider`};case`post-begin`:case`pre-begin`:return{placement:t.isolationLevel,statement:isolationLevelStatement(e)};case`snapshot-only`:case`serializable-only`:if(e===`Serializable`==(t.isolationLevel===`serializable-only`))return{placement:t.isolationLevel};throw refuseTransactionOption(`isolationLevel`,`${e} is not available — ${t.isolationLevelReason??`this driver offers Serializable only`}.`,n);default:throw refuseTransactionOption(`isolationLevel`,t.isolationLevelReason??`this driver does not open a transaction that can be configured`,n)}}function resolveTransactionPlan(e,t,n){if(!e||e.isolationLevel===void 0&&e.timeout===void 0&&e.maxWait===void 0)return;let r=`unsupported`,i;if(e.isolationLevel!==void 0){let a=resolveIsolationLevel(e.isolationLevel,t,n);r=a.placement,i=a.statement}if(e.timeout!==void 0&&!t.timeout)throw refuseTransactionOption(`timeout`,t.timeoutReason??`this driver does not run an interactive callback that could be interrupted`,n);if(e.maxWait!==void 0&&t.maxWait===`unsupported`)throw refuseTransactionOption(`maxWait`,t.maxWaitReason??`this driver has no transaction-slot wait that VibORM can bound`,n);let a={};return r===`pre-begin`&&e.isolationLevel!==void 0&&(a.isolationLevel=e.isolationLevel),t.maxWait===`acquisition`&&e.maxWait!==void 0&&(a.maxWaitMs=e.maxWait),{...e.isolationLevel===void 0?{}:{isolationLevel:e.isolationLevel},...i===void 0?{}:{isolationStatement:i},isolationPlacement:r,...e.timeout===void 0?{}:{timeoutMs:e.timeout},...e.maxWait===void 0?{}:{maxWaitMs:e.maxWait},maxWaitMode:t.maxWait,...Object.keys(a).length===0?{}:{driverOptions:a}}}async function runWithTransactionTimeout(e,t,n,r=z){return B(e(),t,()=>transactionTimeoutError(t,n),void 0,r)}async function acquireWithMaxWait(e,t,n,r,i=z){let a=e();return n===void 0?a:B(a,n,()=>transactionMaxWaitError(n,r),e=>{try{t(e)}catch{}},i)}const U=new WeakMap;let W,G;function physicalConnectionQueue(e){let t=U.get(e);return t||(t=new SavepointQueue,U.set(e,t)),t}function connectionScopeUntracked(){return W===null}function isConnectionScope(e){let t=W?.getStore();return t!==void 0&&t.queue===e&&t.active}function connectionQueueWait(e,t){let n=e??(W===null?5e3:void 0);return n===void 0?void 0:{maxWaitMs:n,onMaxWaitExceeded:()=>transactionMaxWaitError(n,t)}}async function withConnectionScope(e,t){if(G??=import(`node:async_hooks`).then(({AsyncLocalStorage:e})=>{W=new e}).catch(()=>{W=null}),await G,W===null)return t();if(!W)throw Error(`Connection scope failed to initialize`);let n={queue:e,active:!0};return W.run(n,async()=>{try{return await t()}finally{n.active=!1}})}function prepareAtomicBatch(e,t,r,i){let a=[],o=e.map(e=>{let i=e.params,o=n(e.context,t,`executeBatch`),s=i?P(i,o):void 0;s&&Object.freeze(s);let c={sql:e.sql,...s?{params:s}:{},context:o};M(e)&&(c=A(c)),N(e,c,s??[]);let l=r(s??[],o);return a.push(l),Object.defineProperty(c,R,{configurable:!1,enumerable:!1,value:l,writable:!1}),Object.freeze(c)}),s=i?a:I;return i&&Object.freeze(s),{queries:o,diagnosticParams:s}}var NumberedSql=class extends w{#e;#t;constructor(e,t){super([``],[]);let n=e.strings,r=[],i=new Map,a=n[0];for(let[o,s]of e.values.entries()){let e=s instanceof Date?`date:${s.getTime()}`:s===null||typeof s!=`object`&&typeof s!=`function`?`${typeof s}:${String(s)}`:s,c=i.get(e);c===void 0&&(c=r.push(s),i.set(e,c)),a+=`${t}${c}${n[o+1]}`}this.#e=a,this.#t=r}get values(){return this.#t}toStatement(){return this.#e}};function readOptionOnce(e,t){try{return Object.hasOwn(e,t)?Reflect.get(e,t):void 0}catch(e){throw new y(`The "${t}" option could not be read.`,{cause:g(e)})}}function resolveNamespaceOption(e){let t=readOptionOnce(e,`namespace`);if(t===void 0||typeof t==`string`)return t;throw new y(`The "namespace" option must be a string; received type "${typeof t}".`)}function resolveAttestationOption(e,t,n){let r=readOptionOnce(e,t);if(r!==void 0){if(r===n)return n;throw new y(`The "${t}" option admits only "${n}".`)}}function resolveMigrationNamespaceAttestationOption(e){return resolveAttestationOption(e,`migrationNamespaceAttestation`,`non-redirecting`)}function resolveMigrationSessionAttestationOption(e){return resolveAttestationOption(e,`migrationSessionAttestation`,`dedicated-session`)}function refuseEmptyDatabaseUrl(e,t,n){if(!(n||t.databaseUrl||!Object.hasOwn(t,`databaseUrl`)))throw new y(`Driver "${e}" was given an empty databaseUrl and no host; set the URL or name the host in options.`,{meta:{driver:e,operation:`configuration`}})}function systemRootAsVerifyFull(e){let t;try{t=new URL(e)}catch{return e}return t.searchParams.get(`sslrootcert`)===`system`?(t.searchParams.delete(`sslrootcert`),t.searchParams.set(`sslmode`,`verify-full`),t.href):e}function defineImmutableDriverFact(e,t,n){Object.defineProperty(e,t,{value:n,writable:!1,enumerable:!0,configurable:!1})}const K={schema:!0,skipSchemaValidation:!0,findUniqueBatching:!0};function refuseUnknownDriverConfigKeys(e,t,n,r={}){for(let i of Object.keys(e)){if(Object.hasOwn(K,i)||Object.hasOwn(n,i))continue;let e=Object.hasOwn(r,i)?r[i]:void 0,a=[...Object.keys(K),...Object.keys(n)];throw new y(`viborm/${t} does not accept "${i}"; ${e??`it accepts ${a.join(`, `)}`}.`,{meta:{driver:t,operation:`configuration`}})}}var q=class DriverInstrumentationBase{supportsTransactions=!0;supportsBatch=!1;supportsOrderedCommittedSegments=!1;maxBindParametersPerStatement=void 0;driverName;result;client=null;inTransaction=!1;serializeTransactions=!1;connectionQueue=new SavepointQueue;initPromise=null;closeRetryClient=null;isDisconnecting=!1;transactionPoisonError;boundContext;transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`this driver has not declared an isolation-level contract`,timeout:!1,timeoutReason:`this driver has not declared a timeout contract`,maxWait:`unsupported`,maxWaitReason:`this driver has not declared a maxWait contract`}}constructor(e,t,r={},i){defineImmutableDriverFact(this,`dialect`,e),this.driverName=t,this.boundContext=n(r),defineImmutableDriverFact(this,`migrationNamespaceAttestation`,i)}get numbersPlaceholders(){return!0}boundStatement(e){let t=D(this.maxBindParametersPerStatement),n=t!==void 0&&e.values.length>t&&this.dialect!==`mysql`&&this.numbersPlaceholders?new NumberedSql(e,this.dialect===`postgresql`?`$`:`?`):e;return O(n,this.driverName,t,`operation`),n}materializeTrustedBatchQuery(e,t,n=k(e)){if(n===void 0)return e;let r=this.boundStatement(n);return{sql:this.buildStatement(r),params:P(r.values,t),...e.context===void 0?{}:{context:e.context}}}rewriteBatch(e,t,n,r){let i=e.map(k),a=p(t)?.rewrites;return a===void 0?n(i):a.together(i.map((n,r)=>{if(n===void 0)return;let i=this.resolveExecutionContext(e[r]?.context??t,`executeBatch`);return{kind:`statement`,operation:i.operation,model:i.model,context:i,driver:this,statement:n}}),n,r)}buildStatement(e){switch(this.dialect){case`postgresql`:return e.toStatement(`$n`);case`sqlite`:case`mysql`:return e.toStatement(`?`);default:return e.toStatement()}}getBatchDiagnosticParameters(e){try{let t=Reflect.get(e,R);return Array.isArray(t)?t:this.getDiagnosticParameters(e.params??[],e.context)}catch{return this.getDiagnosticParameters(e.params??[],e.context)}}getDiagnosticParameters(e,t,n){return this.canDiscloseParameters(t)||n!==void 0&&n!==t&&this.canDiscloseParameters(n)?F(e):I}connectedClient(){if(!(this.getClient!==DriverInstrumentationBase.prototype.getClient||this.transactionPoisonError||this.isDisconnecting||this.closeRetryClient!==null))return this.client??void 0}async getClient(e={}){if(this.transactionPoisonError||this.isDisconnecting||this.closeRetryClient!==null)throw this.unavailableClientError(e);return this.client?this.client:await this.initializeClient(e)}unavailableClientError(e){return this.transactionPoisonError?new b(`Driver "${this.driverName}" is unavailable after transaction cleanup failed.`,{cause:this.transactionPoisonError,meta:{driver:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId}}):this.connectionClosedError(this.isDisconnecting?`Database connection is closing`:`Database connection cleanup is incomplete`,e)}connectionClosedError(e,t){return new _(e,{code:h.CONNECTION_CLOSED,diagnostics:this.getErrorDisclosure(t),meta:{driver:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId}})}async initializeClient(e){this.initPromise||=Promise.resolve().then(()=>this.initClient()).then(e=>(this.client=e,e));try{return await this.initPromise}catch(t){throw l(t,{driverName:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:i(e),diagnostics:this.getErrorDisclosure(e)})}}normalizeStatementFailure(e,t,n,r,a){return d(e,{driverName:this.driverName,dialect:this.dialect,model:r.model,operation:r.operation,correlationId:r.correlationId,callsite:i(r),query:t,params:n,diagnostics:this.getErrorDisclosure(r),forceContext:a})}async executeNormalizedStatement(e,t,n,r,i){try{return await r()}catch(r){throw this.normalizeStatementFailure(r,e,t,n,i)}}inUnit(e,t,n,r,i,a,o){let s=p(t)?.observation;return s===void 0?n():s.run({kind:e,model:t.model,context:t,driver:this,sql:r,params:i,batch:o,shown:a},n)}resolveExecutionContext(e,t){return n(e,this.boundContext,t)}canDiscloseParameters(e){return this.getErrorDisclosure(e).includeParams===!0}getErrorDisclosure(e){return p(e)?.disclosure??m}};function toTransactionOperationError(e){return e instanceof Error?e:new b(`Transaction operation failed`,{cause:Error(`A transaction operation rejected without an Error`)})}function normalizeTransactionLifecycleError(e,t){try{if(!(e instanceof AggregateError))return t(e);let n=e.cause;return e.errors[0]===n?c(t(n),e.errors.slice(1).map(e=>t(e))):t(e)}catch{return t(e)}}function withoutTimeout(e){if(!e)return e;let{timeout:t,...n}=e;return n}var DriverTransactionBase=class extends q{runTransactionBody(e){return e()}assertBaseOperationAllowedDuringTransaction(e){if(isConnectionScope(this.connectionQueue))throw this.transactionBoundError(e)}holdsConnectionScope(){return!this.serializeTransactions||this.inTransaction?!1:connectionScopeUntracked()?this.connectionQueue.busy:isConnectionScope(this.connectionQueue)}transactionBoundError(e){return new b(`Driver "${this.driverName}" cannot use the originating client while its single connection is transaction-bound. Use the transaction client supplied to the callback.`,{meta:{driver:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,method:`$transaction(callback)`}})}async runConnectionTransactionLease(e){return withConnectionScope(this.connectionQueue,e)}resolveTransactionOptions(e,t){let n={driverName:this.driverName,form:t};return resolveTransactionPlan(parseTransactionOptions(e,n),this.transactionOptionSupport(),n)}assertTransactionOptionsSupported(e,t){this.resolveTransactionOptions(e,t)}readPostBeginIsolationStatement(e){if(e?.isolationPlacement===`post-begin`)return e.isolationStatement}_execute(e,t){return this.executeTypedStatement(e,t,this.executeNormalizedProvider)}async executeNormalizedProvider(e,t,n,r,i=!1){let a=i?await this.executeRaw(e,t,n,r):await this.execute(e,t,n,r);return S(a,{provider:this.driverName,operation:r.operation??(i?`executeRaw`:`execute`)}),a}async executeTypedStatement(e,t,n){let r=this.resolveExecutionContext(t,`execute`),send=(t=e)=>this.dispatchStatement(r,async()=>{let e=this.boundStatement(t);return this.sendStatement(this.buildStatement(e),e.values,r,n)}),i=p(r)?.rewrites;return i===void 0?send():i.run({kind:`statement`,operation:r.operation,model:r.model,context:r,driver:this,statement:e},send)}dispatchStatement(e,t){return this.serializeTransactions&&!this.inTransaction?(this.assertBaseOperationAllowedDuringTransaction(e),this.connectionQueue.run(t,connectionQueueWait(void 0,{driverName:this.driverName,form:`callback`}))):t()}async sendStatement(e,t,n,r){let i=P(t,n),a=this.getDiagnosticParameters(i,n),o=this.connectedClient()??await this.getClient(n);return this.inUnit(`statement`,n,()=>this.executeNormalizedStatement(e,a,n,()=>r.call(this,o,e,i,n),!0),e,i,a)}_prepare(e,t){let n=new w([...e.strings],[...e.values]),r={sql:this.buildStatement(n),params:[...n.values]};return j(r,n),r}async _executeRaw(e,t,n){let r=this.resolveExecutionContext(n,`executeRaw`);return this.dispatchStatement(r,()=>this.sendStatement(e,t??[],r,(e,t,n)=>this.executeNormalizedProvider(e,t,n,r,!0)))}runProviderTransactionCore(e,t,n,i){let a=p(n)?.observation;if(a===void 0)return this.runProviderTransaction(e,t,n);let o=`pending`,s=i===`transaction`?r(n,{readyToCommit:()=>{o=`ready`},committed:()=>{o=`committed`}}):n,c={kind:i,operation:n.operation,model:n.model,context:n,driver:this,...i===`transaction`?{certainty:()=>o===`pending`?void 0:o===`committed`?`committed`:`may-have-committed`}:{}};return a.run(c,async()=>{let n=await this.runProviderTransaction(e,t,s,c);return o=`committed`,n})}runProviderTransaction(e,t,n,r){let i=Symbol(`noCallbackFailure`),s=i,l=t?.timeoutMs===void 0?e:n=>runWithTransactionTimeout(()=>e(n),t.timeoutMs,{driverName:this.driverName,form:`callback`}),trackedCallback=async e=>{try{return await l(e)}catch(e){throw s=e,e}},u=this.readPostBeginIsolationStatement(t),providerCallback=async e=>(u&&await this.executeRaw(e,u,void 0,{...n,operation:`transaction`}),await r?.opened?.(async t=>(await this.executeRaw(e,this.buildStatement(t),[...t.values],n)).rows),trackedCallback(e)),runTransaction=async()=>{let e=await this.getClient(n);try{return await this.transaction(e,providerCallback,n,t?.driverOptions)}catch(e){let normalizeTransactionFailure=e=>d(e,{driverName:this.driverName,dialect:this.dialect,model:n.model,operation:n.operation,correlationId:n.correlationId,diagnostics:this.getErrorDisclosure(n)});if(s!==i){if(e===s)throw e;let t=o(e,s).map(normalizeTransactionFailure),n=c(s,t);throw this.transactionCleanupFailed(n),n}let t=normalizeTransactionLifecycleError(e,normalizeTransactionFailure);throw(this.inTransaction||e instanceof a||e instanceof AggregateError&&e.errors[0]===e.cause&&e.errors.length>1)&&this.transactionCleanupFailed(t),t}};return runTransaction()}async _transaction(e,t,n){let r=this.resolveTransactionOptions(t,`callback`);if(!this.supportsTransactions)throw s(this.driverName);let i=this.resolveExecutionContext(n,`transaction`),a=this.serializeTransactions&&!this.inTransaction;a&&this.assertBaseOperationAllowedDuringTransaction(i);let o=connectionQueueWait(r?.maxWaitMode===`queue`?r.maxWaitMs:void 0,{driverName:this.driverName,form:`callback`}),run=()=>this.runProviderTransactionCore(e,r,i,`transaction`);return a?this.connectionQueue.enqueue(()=>this.runConnectionTransactionLease(run),o):run()}async withTransaction(e,t,n){let r=this.resolveTransactionOptions(t,`callback`),i=this.resolveExecutionContext(n,`transaction`),a=r?.timeoutMs,o=a===void 0?t:withoutTimeout(t),s;return await this._transaction(async t=>{s=this.createTransactionBoundDriver(t,i);let n=s,scopedBody=()=>this.runTransactionBody(()=>e(n)),runBody=()=>a===void 0?scopedBody():runWithTransactionTimeout(scopedBody,a,{driverName:this.driverName,form:`callback`});try{let e=await runBody();return s.closeTransactionScope(),await s.waitForActiveOperations(),s.assertTransactionCommittable(),e}catch(e){s.closeTransactionScope(e),await s.waitForActiveOperations();let t=s.getTransactionFailure();throw t&&t!==e?T(e,t):e}},o,i)}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},contextOf=e=>e.context?this.resolveExecutionContext(e.context,e.context.operation??`executeBatch`):a,normalizeAt=(e,t,n,r)=>{let i=contextOf(n);return d(t,{driverName:this.driverName,dialect:this.dialect,model:i.model,operation:i.operation,correlationId:i.correlationId,statementIndex:e,query:n.sql,params:r,diagnostics:this.getErrorDisclosure(i),forceContext:!0})};return this.rewriteBatch(t,a,async n=>{let r=[];for(let[e,i]of t.entries()){if(!i)continue;let t=contextOf(i),a;try{a=this.materializeTrustedBatchQuery(i,t,n[e])}catch(t){throw normalizeAt(e,t,i,this.getBatchDiagnosticParameters(i))}r.push({statementIndex:e,statementContext:t,executionQuery:a,diagnosticParams:this.getBatchDiagnosticParameters(a)})}let i=[];for(let{statementIndex:t,statementContext:n,executionQuery:a,diagnosticParams:o}of r){let{sql:r,params:s}=a,c=M(a);i.push(await this.inUnit(`statement`,n,()=>this.executeNormalizedStatement(r,o,n,()=>c?this.executeRaw(e,r,s,n):this.execute(e,r,s??[],n),!0).catch(e=>{throw normalizeAt(t,e,a,o)}),r,s??[],o))}return i},(e,n)=>{let r=t[e];return r===void 0?n:normalizeAt(e,n,r,this.getBatchDiagnosticParameters(r))})}async _executeBatch(e,t,n,r){if(this.resolveTransactionOptions(t,`batch`),e.length===0)return[];if(!(this.supportsBatch||this.supportsTransactions))throw new b(`Driver "${this.driverName}" supports neither transactions nor atomic batch execution.`,{meta:{driver:this.driverName,method:`$transaction([...])`}});let i=this.resolveExecutionContext(n,`executeBatch`),a={provider:this.driverName,operation:i.operation??`executeBatch`};if(this.supportsBatch){if(r&&!this.supportsOrderedCommittedSegments)throw new b(`Driver '${this.driverName}' cannot acknowledge ordered committed segments.`);let submitNativeBatch=()=>this.rewriteBatch(e,i,e=>sendNativeBatch(e),(e,t)=>t),sendNativeBatch=async n=>{let{queries:o,diagnosticParams:s}=prepareAtomicBatch(e.map((e,t)=>this.materializeTrustedBatchQuery(e,e.context??i,n[t])),i,(e,t)=>this.getDiagnosticParameters(e,t,i),this.canDiscloseParameters(i)),c=o.map(e=>e.sql).join(`; `),l=await this.getClient(i),executeProvider=async()=>{try{let e=await this.executeBatch(l,o,i,r,t);return C(e,o.length,a),e}catch(e){let t=L(e,o),n=t===void 0?void 0:o[t],r=n?.context??i;throw d(e,{driverName:this.driverName,dialect:this.dialect,model:r.model,operation:r.operation,correlationId:r.correlationId,statementIndex:n?t:void 0,query:n?n.sql:c,params:n?this.getBatchDiagnosticParameters(n):s,diagnostics:this.getErrorDisclosure(r),forceContext:!0})}};return this.inUnit(`statement`,i,()=>this.executeNormalizedStatement(c,s,i,executeProvider,!1),c,void 0,void 0,o)};return this.serializeTransactions&&!this.inTransaction?(this.assertBaseOperationAllowedDuringTransaction(i),this.connectionQueue.enqueue(submitNativeBatch,connectionQueueWait(void 0,{driverName:this.driverName,form:`batch`}))):submitNativeBatch()}let{queries:o}=prepareAtomicBatch(e,i,(e,t)=>this.getDiagnosticParameters(e,t,i),this.canDiscloseParameters(i)),runSequentialBatch=async e=>{let t=await this.executeBatch(e,o,i);return C(t,o.length,a),t};return this.inTransaction?runSequentialBatch(await this.getClient(i)):this._transaction(runSequentialBatch,t,i)}transactionCleanupFailed(e){this.transactionPoisonError??=e}};const J=Object.freeze({foreignKeys:`pragma`,reservedTablePrefixes:`none`,exclusion:`database-write-lock`}),Y={foreignKeys:`pragma`,reservedTablePrefixes:`_cf_`,exclusion:`frame`},X={foreignKeys:`none`,reservedTablePrefixes:`_cf_`,exclusion:`none`};var Driver=class extends DriverTransactionBase{createTransactionBoundDriver(e,t){return new Z(this,e,t)}_connect(e){return this.runConnectionLifecycle(`connect`,e,e=>this.inUnit(`connection`,e,async()=>{await this.getClient(e)}))}_disconnect(e){return this.runConnectionLifecycle(`disconnect`,e,async e=>{if(this.isDisconnecting)throw this.connectionClosedError(`Database connection is closing`,e);this.isDisconnecting=!0;let doDisconnect=async()=>{if(this.initPromise)try{await this.initPromise}catch{}let t=this.closeRetryClient??this.client;if(!t){this.transactionPoisonError=void 0;return}try{await this.closeClient(t)}catch(n){throw this.closeRetryClient=t,this.client===t&&(this.client=null),this.initPromise=null,l(n,{driverName:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,diagnostics:this.getErrorDisclosure(e)},`Database disconnection failed`)}},t=this.inUnit(`connection`,e,doDisconnect);try{await t,this.client=null,this.initPromise=null,this.closeRetryClient=null,this.transactionPoisonError=void 0}finally{this.isDisconnecting=!1}})}async runConnectionLifecycle(e,t,n){let r=this.resolveExecutionContext(t,e),run=()=>n(r),i=this.serializeTransactions&&!this.inTransaction;return i&&this.assertBaseOperationAllowedDuringTransaction(r),i?this.connectionQueue.enqueue(run):run()}async disconnect(){return this._disconnect()}};function disposeDriver(){return this.disconnect()}t!==void 0&&Object.defineProperty(Driver.prototype,t,{configurable:!0,writable:!0,enumerable:!1,value:disposeDriver});var Z=class TransactionBoundDriver extends Driver{baseDriver;parentTransactionDriver;tx;scopeQueue=new SavepointQueue;activeOperations=new Set;nestedTransactionObservations=new Set;transactionClosed=!1;signalScopeClosed;scopeClosed;isSavepointActive=!1;hasAdmittedWithTransactionDispatch=!1;rollbackOnlyError;result;inTransaction=!0;supportsTransactions;supportsBatch;supportsOrderedCommittedSegments;maxBindParametersPerStatement;constructor(e,t,n){super(e.dialect,e.driverName,n,e.migrationNamespaceAttestation);let resolveClosed=()=>void 0;this.scopeClosed=new Promise(e=>{resolveClosed=e}),this.signalScopeClosed=resolveClosed,this.baseDriver=e,this.parentTransactionDriver=e instanceof TransactionBoundDriver?e:void 0,this.tx=t,defineImmutableDriverFact(this,`adapter`,e.adapter),this.result=e.result,this.supportsTransactions=e.supportsTransactions,this.supportsBatch=e.supportsBatch,this.supportsOrderedCommittedSegments=e.supportsOrderedCommittedSegments,this.maxBindParametersPerStatement=e.maxBindParametersPerStatement}async getClient(e){return this.tx}closeTransactionScope(...e){this.transactionClosed=!0,e.length>0&&this.signalScopeClosed(e[0]);for(let e of this.nestedTransactionObservations)e.failure&&!e.isRejectionObserved&&this.markCurrentScopeRollbackOnly(e.failure)}runTransactionBody(e){return Promise.race([e(),this.scopeClosed.then(e=>{throw e})])}async waitForActiveOperations(){for(;this.activeOperations.size>0;)await Promise.allSettled([...this.activeOperations])}getTransactionFailure(){return this.parentTransactionDriver?.getTransactionFailure()??this.rollbackOnlyError}assertTransactionCommittable(){if(this.parentTransactionDriver?.assertTransactionCommittable(),this.rollbackOnlyError)throw this.rollbackOnlyError}markCurrentScopeRollbackOnly(e){this.rollbackOnlyError??=e}markRootTransactionRollbackOnly(e){if(this.parentTransactionDriver){this.parentTransactionDriver.markRootTransactionRollbackOnly(e);return}this.rollbackOnlyError??=e}assertRollbackOnlyUsable(){let e=this.getTransactionFailure();if(e)throw T(f(e,new b(`Transaction for driver "${this.driverName}" is rollback-only after an earlier failure; no further statements can execute.`,{cause:e,meta:{driver:this.driverName,method:`$transaction`}})),e)}assertTransactionOpen(){if(this.parentTransactionDriver?.assertTransactionOpen(),this.assertRollbackOnlyUsable(),this.transactionClosed)throw new b(`Transaction for driver "${this.driverName}" is no longer active.`,{meta:{driver:this.driverName,method:`$transaction`}})}getActiveSavepointUseError(e){if(this.isSavepointActive)return new b(`Transaction scope for driver "${this.driverName}" cannot be used while its nested transaction is active. At every nesting level, use the transaction client supplied to that callback.`,{meta:{driver:this.driverName,method:e}})}enqueueScopeOperation(e){return this.scopeQueue.enqueue(async()=>{this.assertRollbackOnlyUsable();try{return await e()}catch(e){throw this.markCurrentScopeRollbackOnly(toTransactionOperationError(e)),e}})}trackTransactionOperation(e,t){let n=t?void 0:{isRejectionObserved:!1};n&&this.nestedTransactionObservations.add(n);let r=Promise.resolve().then(()=>(this.assertTransactionOpen(),e()));return this.activeOperations.add(r),r.then(()=>{this.activeOperations.delete(r)},e=>{this.activeOperations.delete(r);let t=toTransactionOperationError(e);if(n){n.failure=t,this.transactionClosed&&!n.isRejectionObserved&&this.markCurrentScopeRollbackOnly(t);return}this.markCurrentScopeRollbackOnly(t)}).catch(()=>void 0),n?x(r,()=>{n.isRejectionObserved=!0}):r}scoped(e,t){let n=this.getActiveSavepointUseError(e);return n?Promise.reject(n):this.trackTransactionOperation(()=>this.enqueueScopeOperation(t),!0)}_execute(e,t){return this.scoped(`execute`,()=>super._execute(e,t))}_executeRaw(e,t,n){return this.scoped(`executeRaw`,()=>super._executeRaw(e,t,n))}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`a nested transaction runs inside the outer transaction, whose isolation level is already fixed and cannot be changed mid-transaction — set it on the outermost $transaction`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`a nested transaction reuses the outer transaction's connection, so there is no transaction slot to wait for`}}resolveNestedOptions(e,t){try{return this.resolveTransactionOptions(e,t)}catch(e){return toTransactionOperationError(e)}}_executeBatch(e,t,n,r){let i=this.resolveNestedOptions(t,`batch`);return i instanceof Error?Promise.reject(i):e.length===0?Promise.resolve([]):this.scoped(`$transaction([...])`,()=>super._executeBatch(e,t,n,r))}_transaction(e,t,n){let r=this.resolveNestedOptions(t,`callback`);if(r instanceof Error)return Promise.reject(r);let i=this.hasAdmittedWithTransactionDispatch;if(!i){let e=this.getActiveSavepointUseError(`$transaction(callback)`);if(e)return Promise.reject(e);try{this.assertTransactionOpen()}catch(e){return Promise.reject(e)}}let a=this.resolveExecutionContext(n,`transaction`),executeTransaction=()=>this.scopeQueue.enqueue(async()=>{this.assertRollbackOnlyUsable(),this.isSavepointActive=!0;try{return await this.runProviderTransactionCore(e,r,a,`savepoint`)}finally{this.isSavepointActive=!1}});return i?executeTransaction():this.trackTransactionOperation(executeTransaction,!1)}withTransaction(e,t,n){let r=this.resolveNestedOptions(t,`callback`);if(r instanceof Error)return Promise.reject(r);let i=this.getActiveSavepointUseError(`$transaction(callback)`);return i?Promise.reject(i):this.trackTransactionOperation(()=>{this.hasAdmittedWithTransactionDispatch=!0;try{return super.withTransaction(e,t,n)}finally{this.hasAdmittedWithTransactionDispatch=!1}},!1)}initClient(){throw Error(`TransactionBoundDriver does not initialize clients`)}closeClient(){return Promise.resolve()}execute(e,t,n,r){return this.baseDriver.execute(e,t,n,r)}executeRaw(e,t,n,r){return this.baseDriver.executeRaw(e,t,n,r)}async transaction(e,t,n){return this.assertTransactionCommittable(),u(e=>this.baseDriver.executeRaw(this.tx,e,void 0,n??{}),()=>t(this.tx))}transactionCleanupFailed(e){this.markRootTransactionRollbackOnly(e)}async disconnect(){}};export{Z as a,refuseUnknownDriverConfigKeys as c,resolveNamespaceOption as d,systemRootAsVerifyFull as f,isolationLevelStatement as h,J as i,resolveMigrationNamespaceAttestationOption as l,acquireWithMaxWait as m,Y as n,defineImmutableDriverFact as o,physicalConnectionQueue as p,Driver as r,refuseEmptyDatabaseUrl as s,X as t,resolveMigrationSessionAttestationOption as u};
2
- //# sourceMappingURL=driver-BIXhOH2_.mjs.map