viborm 1.5.1 → 1.7.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 (278) hide show
  1. package/README.md +4 -2
  2. package/dist/{adapter-internals-Dagucesf.mjs → adapter-internals-DNY4JWFC.mjs} +1 -1
  3. package/dist/{adapter-internals-Dagucesf.mjs.map → adapter-internals-DNY4JWFC.mjs.map} +1 -1
  4. package/dist/{adapter-namespace-DuugUuQa.mjs → adapter-namespace-BMss0hKo.mjs} +2 -2
  5. package/dist/{adapter-namespace-DuugUuQa.mjs.map → adapter-namespace-BMss0hKo.mjs.map} +1 -1
  6. package/dist/{adapter-result-parser-B63ouFIz.mjs → adapter-result-parser-Bz3WtMBa.mjs} +1 -1
  7. package/dist/{adapter-result-parser-B63ouFIz.mjs.map → adapter-result-parser-Bz3WtMBa.mjs.map} +1 -1
  8. package/dist/adapters.d.mts +1 -1
  9. package/dist/adapters.mjs +1 -1
  10. package/dist/{array-literal-BU1R9byi.mjs → array-literal-DfgmVxKI.mjs} +1 -1
  11. package/dist/{array-literal-BU1R9byi.mjs.map → array-literal-DfgmVxKI.mjs.map} +1 -1
  12. package/dist/{batch-refs-C3MTcVre.mjs → batch-refs-DWMYN0fw.mjs} +2 -2
  13. package/dist/{batch-refs-C3MTcVre.mjs.map → batch-refs-DWMYN0fw.mjs.map} +1 -1
  14. package/dist/bind-parameter-capacity-Bjgx1lMC.mjs +2 -0
  15. package/dist/{bind-parameter-capacity-faPOSaLz.mjs.map → bind-parameter-capacity-Bjgx1lMC.mjs.map} +1 -1
  16. package/dist/builder-B4n-7I7Q.mjs +2 -0
  17. package/dist/{builder-ClblW6Lj.mjs.map → builder-B4n-7I7Q.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-sqlite.d.mts +1 -1
  21. package/dist/bun-sqlite.mjs +1 -1
  22. package/dist/bun-sqlite.mjs.map +1 -1
  23. package/dist/cache/cloudflare-kv.d.mts +1 -1
  24. package/dist/cache/cloudflare-kv.mjs +1 -1
  25. package/dist/cache/memory.d.mts +1 -1
  26. package/dist/cache/memory.mjs +1 -1
  27. package/dist/cache.d.mts +1 -1
  28. package/dist/cache.mjs +1 -1
  29. package/dist/cache.mjs.map +1 -1
  30. package/dist/{canonical-json-JLUMrnoq.mjs → canonical-json-B6J5VbLv.mjs} +1 -1
  31. package/dist/{canonical-json-JLUMrnoq.mjs.map → canonical-json-B6J5VbLv.mjs.map} +1 -1
  32. package/dist/chain-DVuRxjPO.mjs +2 -0
  33. package/dist/chain-DVuRxjPO.mjs.map +1 -0
  34. package/dist/cli.mjs +1 -1
  35. package/dist/{client-DyIsSin0.d.mts → client-7ApJka0M.d.mts} +3 -3
  36. package/dist/client-Yqn0LqmI.mjs +2 -0
  37. package/dist/client-Yqn0LqmI.mjs.map +1 -0
  38. package/dist/{client-C1MxqFtt.mjs → client-l7dSOul5.mjs} +13 -13
  39. package/dist/client-l7dSOul5.mjs.map +1 -0
  40. package/dist/client.d.mts +1 -1
  41. package/dist/client.mjs +1 -1
  42. package/dist/{clock-CK41KO7t.mjs → clock-DXbsDHLj.mjs} +1 -1
  43. package/dist/{clock-CK41KO7t.mjs.map → clock-DXbsDHLj.mjs.map} +1 -1
  44. package/dist/config.d.mts +2 -2
  45. package/dist/config.mjs +1 -1
  46. package/dist/{current-CKQ4EgeM.mjs → current-nScH-oH5.mjs} +1 -1
  47. package/dist/{current-CKQ4EgeM.mjs.map → current-nScH-oH5.mjs.map} +1 -1
  48. package/dist/d1.d.mts +1 -1
  49. package/dist/d1.mjs +1 -1
  50. package/dist/d1.mjs.map +1 -1
  51. package/dist/{datetime-physical-codec-DfVmz14E.mjs → datetime-physical-codec-DTdvABny.mjs} +2 -2
  52. package/dist/{datetime-physical-codec-DfVmz14E.mjs.map → datetime-physical-codec-DTdvABny.mjs.map} +1 -1
  53. package/dist/driver-CK_IKqDa.mjs +2 -0
  54. package/dist/{driver-aqfbJdZC.mjs.map → driver-CK_IKqDa.mjs.map} +1 -1
  55. package/dist/{driver-DpQbSOUD.mjs → driver-DaBNytbz.mjs} +2 -2
  56. package/dist/{driver-DpQbSOUD.mjs.map → driver-DaBNytbz.mjs.map} +1 -1
  57. package/dist/driver.d.mts +1 -1
  58. package/dist/driver.mjs +1 -1
  59. package/dist/error-mapping-D--MVRCY.mjs +2 -0
  60. package/dist/error-mapping-D--MVRCY.mjs.map +1 -0
  61. package/dist/every-6VrIclsx.mjs +2 -0
  62. package/dist/{every-BUf842ai.mjs.map → every-6VrIclsx.mjs.map} +1 -1
  63. package/dist/{fs-estate-BXNX7l62.mjs → fs-estate-CfvH8Fxa.mjs} +2 -2
  64. package/dist/{fs-estate-BXNX7l62.mjs.map → fs-estate-CfvH8Fxa.mjs.map} +1 -1
  65. package/dist/{geo-area-codec-DQpSEgSD.mjs → geo-area-codec-DvHcWF3g.mjs} +2 -2
  66. package/dist/{geo-area-codec-DQpSEgSD.mjs.map → geo-area-codec-DvHcWF3g.mjs.map} +1 -1
  67. package/dist/geo-point-codec-CIZxuIvE.mjs +2 -0
  68. package/dist/geo-point-codec-CIZxuIvE.mjs.map +1 -0
  69. package/dist/{hydration-BK6vRndL.mjs → hydration-BUBkHlCK.mjs} +2 -2
  70. package/dist/{hydration-BK6vRndL.mjs.map → hydration-BUBkHlCK.mjs.map} +1 -1
  71. package/dist/identifier-conversion-BXrBYgAq.mjs +2 -0
  72. package/dist/{identifier-conversion-8ldidfgu.mjs.map → identifier-conversion-BXrBYgAq.mjs.map} +1 -1
  73. package/dist/{identity-Bu6jbgym.mjs → identity-BtuwgqhS.mjs} +2 -2
  74. package/dist/{identity-Bu6jbgym.mjs.map → identity-BtuwgqhS.mjs.map} +1 -1
  75. package/dist/{index-Ci8b13Lm.d.mts → index-CsO6vG2h.d.mts} +71 -14
  76. package/dist/index.d.mts +2 -2
  77. package/dist/index.mjs +1 -1
  78. package/dist/index.mjs.map +1 -1
  79. package/dist/insert-value-Cbp_bNxj.mjs +2 -0
  80. package/dist/insert-value-Cbp_bNxj.mjs.map +1 -0
  81. package/dist/instrumentation.d.mts +1 -1
  82. package/dist/instrumentation.mjs +1 -1
  83. package/dist/{invariant-BnLYqsHO.mjs → invariant-Dw9UB49x.mjs} +1 -1
  84. package/dist/{invariant-BnLYqsHO.mjs.map → invariant-Dw9UB49x.mjs.map} +1 -1
  85. package/dist/{json-number-CAfNAqDB.mjs → json-number-ChtP7ZeY.mjs} +1 -1
  86. package/dist/{json-number-CAfNAqDB.mjs.map → json-number-ChtP7ZeY.mjs.map} +1 -1
  87. package/dist/{key-DJXcPZR_.mjs → key-Cz83fdLO.mjs} +2 -2
  88. package/dist/{key-DJXcPZR_.mjs.map → key-Cz83fdLO.mjs.map} +1 -1
  89. package/dist/keys-EP1Eq2eD.mjs +2 -0
  90. package/dist/keys-EP1Eq2eD.mjs.map +1 -0
  91. package/dist/{libsql-Dmtj0O4E.mjs → libsql-ClGi2zY2.mjs} +3 -3
  92. package/dist/{libsql-Dmtj0O4E.mjs.map → libsql-ClGi2zY2.mjs.map} +1 -1
  93. package/dist/libsql.d.mts +1 -1
  94. package/dist/libsql.mjs +1 -1
  95. package/dist/libsql.mjs.map +1 -1
  96. package/dist/{memory-b-dafk9S.mjs → memory-B1GnzgZr.mjs} +2 -2
  97. package/dist/{memory-b-dafk9S.mjs.map → memory-B1GnzgZr.mjs.map} +1 -1
  98. package/dist/migrations/mysql.d.mts +5 -5
  99. package/dist/migrations/mysql.mjs +1 -1
  100. package/dist/migrations/postgres.d.mts +5 -5
  101. package/dist/migrations/postgres.mjs +1 -1
  102. package/dist/migrations/sqlite.d.mts +5 -5
  103. package/dist/migrations/sqlite.mjs +1 -1
  104. package/dist/migrations/storage/durable-object.d.mts +1 -1
  105. package/dist/migrations/storage/durable-object.mjs +1 -1
  106. package/dist/migrations/storage/fs.d.mts +1 -1
  107. package/dist/migrations/storage/fs.mjs +1 -1
  108. package/dist/migrations/storage/r2.d.mts +1 -1
  109. package/dist/migrations/storage/r2.mjs +1 -1
  110. package/dist/migrations/tenant.d.mts +3 -3
  111. package/dist/migrations/tenant.mjs +1 -1
  112. package/dist/migrations.d.mts +5 -5
  113. package/dist/migrations.mjs +1 -1
  114. package/dist/model-DsXZ_pHE.mjs +2 -0
  115. package/dist/model-DsXZ_pHE.mjs.map +1 -0
  116. package/dist/mysql-adapter-D-Dq2FN9.mjs +2 -0
  117. package/dist/mysql-adapter-D-Dq2FN9.mjs.map +1 -0
  118. package/dist/{mysql-DAaUSeBw.mjs → mysql-hoo290Dd.mjs} +6 -6
  119. package/dist/{mysql-DAaUSeBw.mjs.map → mysql-hoo290Dd.mjs.map} +1 -1
  120. package/dist/mysql2.d.mts +1 -1
  121. package/dist/mysql2.mjs +1 -1
  122. package/dist/mysql2.mjs.map +1 -1
  123. package/dist/{native-types-BbKWN3JV.mjs → native-types-CQH05hcr.mjs} +1 -1
  124. package/dist/{native-types-BbKWN3JV.mjs.map → native-types-CQH05hcr.mjs.map} +1 -1
  125. package/dist/neon-http.d.mts +1 -1
  126. package/dist/neon-http.mjs +1 -1
  127. package/dist/neon-http.mjs.map +1 -1
  128. package/dist/normalized-result-23DWxZVY.mjs +2 -0
  129. package/dist/{normalized-result-VunNi4ID.mjs.map → normalized-result-23DWxZVY.mjs.map} +1 -1
  130. package/dist/{object-store-BHyP-LEI.d.mts → object-store-9VfS-3sY.d.mts} +4 -4
  131. package/dist/{object-store-I1MyfM72.mjs → object-store-DdgcT8d9.mjs} +2 -2
  132. package/dist/{object-store-I1MyfM72.mjs.map → object-store-DdgcT8d9.mjs.map} +1 -1
  133. package/dist/on.d.mts +80 -0
  134. package/dist/on.mjs +2 -0
  135. package/dist/on.mjs.map +1 -0
  136. package/dist/ordering.d.mts +101 -0
  137. package/dist/ordering.mjs +11 -0
  138. package/dist/ordering.mjs.map +1 -0
  139. package/dist/permissions.d.mts +1 -1
  140. package/dist/permissions.mjs +1 -1
  141. package/dist/pg.d.mts +1 -1
  142. package/dist/pg.mjs +1 -1
  143. package/dist/pg.mjs.map +1 -1
  144. package/dist/pglite.d.mts +1 -1
  145. package/dist/pglite.mjs +1 -1
  146. package/dist/{physical-CAZ_LauY.mjs → physical-t_gDjUCD.mjs} +2 -2
  147. package/dist/{physical-CAZ_LauY.mjs.map → physical-t_gDjUCD.mjs.map} +1 -1
  148. package/dist/pinned-session-De2rDjdO.mjs +2 -0
  149. package/dist/{pinned-session-D8bM5obl.mjs.map → pinned-session-De2rDjdO.mjs.map} +1 -1
  150. package/dist/planetscale.d.mts +1 -1
  151. package/dist/planetscale.mjs +1 -1
  152. package/dist/planetscale.mjs.map +1 -1
  153. package/dist/{planner-BDLdDieE.d.mts → planner-Cc3ABIUU.d.mts} +22 -1
  154. package/dist/{postgres-HaFcFACt.mjs → postgres-CqcP_qv-.mjs} +44 -37
  155. package/dist/postgres-CqcP_qv-.mjs.map +1 -0
  156. package/dist/postgres-adapter-CYZAL2uo.mjs +2 -0
  157. package/dist/{postgres-adapter-CnZjhvG1.mjs.map → postgres-adapter-CYZAL2uo.mjs.map} +1 -1
  158. package/dist/postgres-adapter-_o6EWuxW.mjs +2 -0
  159. package/dist/postgres-adapter-_o6EWuxW.mjs.map +1 -0
  160. package/dist/postgres-result-D94PyZ78.mjs +2 -0
  161. package/dist/{postgres-result-D4_yZqO8.mjs.map → postgres-result-D94PyZ78.mjs.map} +1 -1
  162. package/dist/postgres.d.mts +1 -1
  163. package/dist/postgres.mjs +1 -1
  164. package/dist/postgres.mjs.map +1 -1
  165. package/dist/{provider-limits-CpitUqW6.mjs → provider-limits-kO9B3KCF.mjs} +2 -2
  166. package/dist/{provider-limits-CpitUqW6.mjs.map → provider-limits-kO9B3KCF.mjs.map} +1 -1
  167. package/dist/{validation-DN1N2OdK.mjs → query-CTna5P9o.mjs} +2 -2
  168. package/dist/query-CTna5P9o.mjs.map +1 -0
  169. package/dist/{relation-bound-5ChGF3n5.mjs → relation-bound-5hindjxU.mjs} +1 -1
  170. package/dist/{relation-bound-5ChGF3n5.mjs.map → relation-bound-5hindjxU.mjs.map} +1 -1
  171. package/dist/{result-parsing-BX3_3Q15.mjs → result-parsing-Dkgy-xcy.mjs} +1 -1
  172. package/dist/{result-parsing-BX3_3Q15.mjs.map → result-parsing-Dkgy-xcy.mjs.map} +1 -1
  173. package/dist/result-shape-uaCsF_SZ.mjs +2 -0
  174. package/dist/{result-shape-BuGfArOr.mjs.map → result-shape-uaCsF_SZ.mjs.map} +1 -1
  175. package/dist/rows-AtX0guAb.mjs +2 -0
  176. package/dist/rows-AtX0guAb.mjs.map +1 -0
  177. package/dist/scalar-CZ_q89Hc.mjs +4 -0
  178. package/dist/scalar-CZ_q89Hc.mjs.map +1 -0
  179. package/dist/schema/json.d.mts +1 -1
  180. package/dist/schema/json.mjs +1 -1
  181. package/dist/schema/json.mjs.map +1 -1
  182. package/dist/schema-CZTCxG2p.mjs +2 -0
  183. package/dist/{schema-B_Bc7TQ2.mjs.map → schema-CZTCxG2p.mjs.map} +1 -1
  184. package/dist/{schema-introspection-BqN7d_sA.mjs → schema-introspection-DoZHc1o7.mjs} +2 -2
  185. package/dist/{schema-introspection-BqN7d_sA.mjs.map → schema-introspection-DoZHc1o7.mjs.map} +1 -1
  186. package/dist/schema.d.mts +1 -1
  187. package/dist/schema.mjs +1 -1
  188. package/dist/{select-assembly-BP8c4O-0.mjs → select-assembly-BtNtBsUh.mjs} +2 -2
  189. package/dist/select-assembly-BtNtBsUh.mjs.map +1 -0
  190. package/dist/{settle-B9Vg1FnP.mjs → settle-v6QhvFkm.mjs} +2 -2
  191. package/dist/{settle-B9Vg1FnP.mjs.map → settle-v6QhvFkm.mjs.map} +1 -1
  192. package/dist/{sha256-DDEbgnTU.mjs → sha256-D_fCV62w.mjs} +1 -1
  193. package/dist/{sha256-DDEbgnTU.mjs.map → sha256-D_fCV62w.mjs.map} +1 -1
  194. package/dist/soft-delete.d.mts +1 -1
  195. package/dist/{sql-BR8ZzKn8.mjs → sql-DGtEeP8z.mjs} +1 -1
  196. package/dist/{sql-BR8ZzKn8.mjs.map → sql-DGtEeP8z.mjs.map} +1 -1
  197. package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CV2qkIKN.mjs} +1 -1
  198. package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CV2qkIKN.mjs.map} +1 -1
  199. package/dist/sql.d.mts +1 -1
  200. package/dist/sql.mjs +1 -1
  201. package/dist/sqlite-adapter-CnAwmszh.mjs +2 -0
  202. package/dist/sqlite-adapter-CnAwmszh.mjs.map +1 -0
  203. package/dist/{sqlite-utils-CFInz2yY.mjs → sqlite-utils-DztTzv08.mjs} +2 -2
  204. package/dist/{sqlite-utils-CFInz2yY.mjs.map → sqlite-utils-DztTzv08.mjs.map} +1 -1
  205. package/dist/sqlite3.d.mts +1 -1
  206. package/dist/sqlite3.mjs +1 -1
  207. package/dist/sqlite3.mjs.map +1 -1
  208. package/dist/{standard-sql-wRMNi-Yg.mjs → standard-sql-Ci8ROrql.mjs} +2 -2
  209. package/dist/{standard-sql-wRMNi-Yg.mjs.map → standard-sql-Ci8ROrql.mjs.map} +1 -1
  210. package/dist/{suppressed-failure-Bdo2aK81.mjs → suppressed-failure-DO0ej03b.mjs} +1 -1
  211. package/dist/{suppressed-failure-Bdo2aK81.mjs.map → suppressed-failure-DO0ej03b.mjs.map} +1 -1
  212. package/dist/to-many-BtLpp5cW.mjs +2 -0
  213. package/dist/{to-many-CUBK3CTd.mjs.map → to-many-BtLpp5cW.mjs.map} +1 -1
  214. package/dist/{transaction-operation-C3Jbblbl.mjs → transaction-operation-Km-Gr-a3.mjs} +1 -1
  215. package/dist/{transaction-operation-C3Jbblbl.mjs.map → transaction-operation-Km-Gr-a3.mjs.map} +1 -1
  216. package/dist/{types-BNR3u6hH.mjs → types-C4v6iAmY.mjs} +1 -1
  217. package/dist/{types-BNR3u6hH.mjs.map → types-C4v6iAmY.mjs.map} +1 -1
  218. package/dist/{utils-Be91XL14.mjs → utils-CAACs9Jw.mjs} +3 -3
  219. package/dist/utils-CAACs9Jw.mjs.map +1 -0
  220. package/dist/v-Pb_jJOjC.mjs +2 -0
  221. package/dist/{v-lthABIXD.mjs.map → v-Pb_jJOjC.mjs.map} +1 -1
  222. package/dist/validation-BSpO4DjI.mjs +2 -0
  223. package/dist/{validation-BfJaNYMf.mjs.map → validation-BSpO4DjI.mjs.map} +1 -1
  224. package/dist/validation-pfpKPPZ_.mjs +2 -0
  225. package/dist/validation-pfpKPPZ_.mjs.map +1 -0
  226. package/dist/validation.d.mts +1 -1
  227. package/dist/validation.mjs +1 -1
  228. package/dist/validator-Dthaj1Hz.mjs +2 -0
  229. package/dist/validator-Dthaj1Hz.mjs.map +1 -0
  230. package/dist/version-DvynkoaW.mjs +2 -0
  231. package/dist/{version-DAFcmokN.mjs.map → version-DvynkoaW.mjs.map} +1 -1
  232. package/dist/write-sinks-3IKCDF-S.mjs +2 -0
  233. package/dist/write-sinks-3IKCDF-S.mjs.map +1 -0
  234. package/dist/writes-BX5fLiw5.mjs +2 -0
  235. package/dist/writes-BX5fLiw5.mjs.map +1 -0
  236. package/package.json +55 -15
  237. package/dist/bind-parameter-capacity-faPOSaLz.mjs +0 -2
  238. package/dist/builder-ClblW6Lj.mjs +0 -2
  239. package/dist/chain-C1VPkUpC.mjs +0 -2
  240. package/dist/chain-C1VPkUpC.mjs.map +0 -1
  241. package/dist/client-C1MxqFtt.mjs.map +0 -1
  242. package/dist/client-DHf2ZfRe.mjs +0 -2
  243. package/dist/client-DHf2ZfRe.mjs.map +0 -1
  244. package/dist/driver-aqfbJdZC.mjs +0 -2
  245. package/dist/error-mapping-Zett_Pnt.mjs +0 -2
  246. package/dist/error-mapping-Zett_Pnt.mjs.map +0 -1
  247. package/dist/every-BUf842ai.mjs +0 -2
  248. package/dist/geo-point-codec-DcUTvoEg.mjs +0 -2
  249. package/dist/geo-point-codec-DcUTvoEg.mjs.map +0 -1
  250. package/dist/identifier-conversion-8ldidfgu.mjs +0 -2
  251. package/dist/mysql-adapter-BrkDrfin.mjs +0 -2
  252. package/dist/mysql-adapter-BrkDrfin.mjs.map +0 -1
  253. package/dist/normalized-result-VunNi4ID.mjs +0 -2
  254. package/dist/pinned-session-D8bM5obl.mjs +0 -2
  255. package/dist/postgres-HaFcFACt.mjs.map +0 -1
  256. package/dist/postgres-adapter-BhNE_3b-.mjs +0 -2
  257. package/dist/postgres-adapter-BhNE_3b-.mjs.map +0 -1
  258. package/dist/postgres-adapter-CnZjhvG1.mjs +0 -2
  259. package/dist/postgres-result-D4_yZqO8.mjs +0 -2
  260. package/dist/result-shape-BuGfArOr.mjs +0 -2
  261. package/dist/rows-BlONp14o.mjs +0 -2
  262. package/dist/rows-BlONp14o.mjs.map +0 -1
  263. package/dist/scalar-B3WLZzJj.mjs +0 -4
  264. package/dist/scalar-B3WLZzJj.mjs.map +0 -1
  265. package/dist/schema-B_Bc7TQ2.mjs +0 -2
  266. package/dist/select-assembly-BP8c4O-0.mjs.map +0 -1
  267. package/dist/sqlite-adapter-CF-m7LIP.mjs +0 -2
  268. package/dist/sqlite-adapter-CF-m7LIP.mjs.map +0 -1
  269. package/dist/to-many-CUBK3CTd.mjs +0 -2
  270. package/dist/utils-Be91XL14.mjs.map +0 -1
  271. package/dist/v-lthABIXD.mjs +0 -2
  272. package/dist/validation-BfJaNYMf.mjs +0 -2
  273. package/dist/validation-DN1N2OdK.mjs.map +0 -1
  274. package/dist/validator-BJhI364k.mjs +0 -2
  275. package/dist/validator-BJhI364k.mjs.map +0 -1
  276. package/dist/version-DAFcmokN.mjs +0 -2
  277. /package/dist/{contract-Dw0FR78e.d.mts → contract-CYl0OzhZ.d.mts} +0 -0
  278. /package/dist/{sql-Q_twK-wW.d.mts → sql-BnXk8adi.d.mts} +0 -0
package/dist/mysql2.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, g as MigrationNamespaceAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-Ci8b13Lm.mjs";
1
+ import { A as Schema, An as DriverTransactionOptions, At as DriverConfig, F as LinkedClientConfig, Fn as QueryExecutionContext, Ft as VibORMClient, In as QueryResult, Pt as NoExtraDriverConfigKeys, g as MigrationNamespaceAttestation, jn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-CsO6vG2h.mjs";
2
2
  import { Pool, PoolConnection, PoolOptions } from "mysql2/promise";
3
3
 
4
4
  //#region src/drivers/mysql2/index.d.ts
package/dist/mysql2.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,i as n,o as r}from"./normalized-result-VunNi4ID.mjs";import{l as i}from"./execution-context-_oajgBi4.mjs";import{i as a}from"./base-wlv81COV.mjs";import{m as o,u as s}from"./error-mapping-Zett_Pnt.mjs";import{p as c,r as l}from"./validation-DN1N2OdK.mjs";import{n as u}from"./transaction-D5LHYn-r.mjs";import{n as d}from"./client-DHf2ZfRe.mjs";import{a as f,c as p,d as m,i as h,l as g,o as _,t as v}from"./driver-aqfbJdZC.mjs";import{t as y}from"./mysql-adapter-BrkDrfin.mjs";import{Buffer as b}from"node:buffer";const x=/^(?:ssl|tls)/i;function tlsRefusal(e){return new l(e,{meta:{driver:`mysql2`,operation:`configuration`}})}function parseMySQLUrl(e){let t=new URL(e),n=decodeURIComponent(t.pathname.slice(1)),r={};for(let[e,n]of t.searchParams){if(x.test(e)&&e!==`ssl`&&e!==`sslmode`)throw tlsRefusal(`Unsupported MySQL TLS URL option; configure options.ssl explicitly.`);try{r[e]=JSON.parse(n)}catch{r[e]=n}}let i=t.searchParams.get(`sslmode`);if(i&&i!==`disable`){if(![`require`,`verify-ca`,`verify-full`].includes(i))throw tlsRefusal(`Unsupported MySQL sslmode; configure options.ssl explicitly.`);if(r.ssl!==void 0&&(r.ssl===null||typeof r.ssl!=`object`&&typeof r.ssl!=`string`))throw tlsRefusal(`MySQL sslmode requires a TLS configuration`);r.ssl??={}}Reflect.deleteProperty(r,`sslmode`);let a=decodeURIComponent(t.username),o=decodeURIComponent(t.password);return{host:t.hostname,...t.port?{port:Number.parseInt(t.port,10)}:{},...n===``?{}:{database:n},...a===``?{}:{user:a},...o===``?{}:{password:o},...r}}const S={pool:!0,options:!0,databaseUrl:!0,namespace:!0,migrationNamespaceAttestation:!0};function convertValuesForMySQL(e){return e.map(e=>e instanceof Uint8Array&&!b.isBuffer(e)?b.from(e.buffer,e.byteOffset,e.byteLength):e)}function isMultiStatementFields(e){return Array.isArray(e)&&e.every(e=>e===void 0||Array.isArray(e))}function malformedMySQL2Result(e,t){return new c(`Driver "mysql2" returned a malformed result for operation "${e}": ${t}.`,{meta:{driver:`mysql2`,operation:e}})}const C=/^-[1-9]\d*$/;function normalizeMySQL2InsertId(e,n){if(!(typeof e==`number`&&Number.isSafeInteger(e)&&e<0||typeof e==`string`&&C.test(e)))return t(e,n,{allowNumber:!0})}function toQueryResult(e,t,i){if(isMultiStatementFields(t))throw new c(`Driver "mysql2" returned multiple statement results for operation "${i}"; VibORM requires exactly one statement result.`,{meta:{driver:`mysql2`,operation:i}});if(Array.isArray(e)){if(!Array.isArray(t)||t.some(e=>!n(e)))throw malformedMySQL2Result(i,`row arrays require one flat field metadata array`);return{rows:e,rowCount:e.length}}if(t!==void 0)throw malformedMySQL2Result(i,`mutation results require undefined field metadata`);if(!n(e))throw malformedMySQL2Result(i,`expected a mutation result object`);let a={provider:`mysql2`,operation:i},o=normalizeMySQL2InsertId(e.insertId,a);return{rows:[],rowCount:r(e.affectedRows,a,{allowDecimalString:!0}),...o===void 0?{}:{insertId:o}}}function deriveMySQL2Namespace(e){if(e.suppliedPool)return;let t=e.connectionOptions.database;return t===``?void 0:t}function resolveMySQL2Configuration(e){let t=m(e),n=e.databaseUrl,r={...n?parseMySQL2ConfiguredUrl(n):void 0};for(let[t,n]of Object.entries(e.options??{}))n!==void 0&&Reflect.set(r,t,n);let i={suppliedPool:e.pool,connectionOptions:r};return{namespace:t??deriveMySQL2Namespace(i),...i}}function parseMySQL2ConfiguredUrl(e){try{return parseMySQLUrl(e)}catch(e){throw a(e)?e:new l(`Driver "mysql2" could not parse its databaseUrl.`,{cause:e instanceof Error?e:void 0})}}var MySQL2Driver=class extends v{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;constructor(e={}){let t=g(e),n=resolveMySQL2Configuration(e);if(super(`mysql`,`mysql2`,{},t),n.connectionOptions.multipleStatements===!0)throw new l(`Driver "mysql2" does not support options.multipleStatements=true because VibORM operations require one result per statement.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.rowsAsArray===!0)throw new l(`Driver "mysql2" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.nestTables===!0||typeof n.connectionOptions.nestTables==`string`)throw new l(`Driver "mysql2" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.`,{meta:{driver:`mysql2`,operation:`configuration`}});this.suppliedPool=n.suppliedPool,this.connectionOptions=n.connectionOptions,_(this,`adapter`,new y(n.namespace)),this.suppliedPool&&(this.client=this.suppliedPool)}async initClient(){if(this.suppliedPool!==void 0)return this.suppliedPool;let e=await import(`mysql2/promise`),t={timezone:`Z`,supportBigNumbers:!0,dateStrings:[`DATE`],...this.connectionOptions};return this.adapter.namespace!==void 0&&(t={...t,database:this.adapter.namespace}),e.createPool(t)}async closeClient(e){e!==this.suppliedPool&&await e.end()}async execute(e,t,n,r){let i=r?.operation??`execute`,[a,o]=await e.query({sql:t,values:convertValuesForMySQL(n),typeCast:(e,t)=>[`DATE`,`DATETIME`,`TIMESTAMP`,`LONGLONG`,`NEWDECIMAL`].includes(e.type)?e.string():t()});return toQueryResult(a,o,i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,[a,o]=await e.query(t,n&&convertValuesForMySQL(n));return toQueryResult(a,o,i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,t,n,r){if(!(`getConnection`in e))throw s(this.driverName);let a=e,c=await h(()=>a.getConnection(),e=>e.release(),r?.maxWaitMs,{driverName:this.driverName,form:`callback`}),l=!1,runOrDestroy=async e=>{try{await e()}catch(e){throw l=!0,e}},d=r?.isolationLevel;return o({begin:()=>runOrDestroy(async()=>{d&&await c.query(f(d)),await c.beginTransaction()}),callback:()=>t(c),commit:()=>runOrDestroy(()=>c.commit()),rollback:()=>runOrDestroy(()=>c.rollback()),phases:i(n),close:()=>{try{if(l){c.destroy();return}c.release()}catch(e){throw super.transactionCleanupFailed(new u(`Driver "mysql2" could not release an unsafe transaction connection.`,{meta:{driver:`mysql2`,method:`$transaction`}})),e}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!(`getConnection`in e))throw s(this.driverName);let t=await e.getConnection();return{session:t,release:()=>(t.destroy(),Promise.resolve())}}};function createClient(e){p(e,`mysql2`,S);let{pool:t,options:n,databaseUrl:r}=e;return d(e,new MySQL2Driver({migrationNamespaceAttestation:g(e),namespace:m(e),pool:t,options:n,databaseUrl:r}))}export{MySQL2Driver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,i as n,o as r}from"./normalized-result-23DWxZVY.mjs";import{l as i}from"./execution-context-_oajgBi4.mjs";import{i as a}from"./base-wlv81COV.mjs";import{m as o,u as s}from"./error-mapping-D--MVRCY.mjs";import{d as c,t as l}from"./query-CTna5P9o.mjs";import{n as u}from"./transaction-D5LHYn-r.mjs";import{n as d}from"./client-Yqn0LqmI.mjs";import{a as f,c as p,d as m,i as h,l as g,o as _,t as v}from"./driver-CK_IKqDa.mjs";import{t as y}from"./mysql-adapter-D-Dq2FN9.mjs";import{Buffer as b}from"node:buffer";const x=/^(?:ssl|tls)/i;function tlsRefusal(e){return new l(e,{meta:{driver:`mysql2`,operation:`configuration`}})}function parseMySQLUrl(e){let t=new URL(e),n=decodeURIComponent(t.pathname.slice(1)),r={};for(let[e,n]of t.searchParams){if(x.test(e)&&e!==`ssl`&&e!==`sslmode`)throw tlsRefusal(`Unsupported MySQL TLS URL option; configure options.ssl explicitly.`);try{r[e]=JSON.parse(n)}catch{r[e]=n}}let i=t.searchParams.get(`sslmode`);if(i&&i!==`disable`){if(![`require`,`verify-ca`,`verify-full`].includes(i))throw tlsRefusal(`Unsupported MySQL sslmode; configure options.ssl explicitly.`);if(r.ssl!==void 0&&(r.ssl===null||typeof r.ssl!=`object`&&typeof r.ssl!=`string`))throw tlsRefusal(`MySQL sslmode requires a TLS configuration`);r.ssl??={}}Reflect.deleteProperty(r,`sslmode`);let a=decodeURIComponent(t.username),o=decodeURIComponent(t.password);return{host:t.hostname,...t.port?{port:Number.parseInt(t.port,10)}:{},...n===``?{}:{database:n},...a===``?{}:{user:a},...o===``?{}:{password:o},...r}}const S={pool:!0,options:!0,databaseUrl:!0,namespace:!0,migrationNamespaceAttestation:!0};function convertValuesForMySQL(e){return e.map(e=>e instanceof Uint8Array&&!b.isBuffer(e)?b.from(e.buffer,e.byteOffset,e.byteLength):e)}function isMultiStatementFields(e){return Array.isArray(e)&&e.every(e=>e===void 0||Array.isArray(e))}function malformedMySQL2Result(e,t){return new c(`Driver "mysql2" returned a malformed result for operation "${e}": ${t}.`,{meta:{driver:`mysql2`,operation:e}})}const C=/^-[1-9]\d*$/;function normalizeMySQL2InsertId(e,n){if(!(typeof e==`number`&&Number.isSafeInteger(e)&&e<0||typeof e==`string`&&C.test(e)))return t(e,n,{allowNumber:!0})}function toQueryResult(e,t,i){if(isMultiStatementFields(t))throw new c(`Driver "mysql2" returned multiple statement results for operation "${i}"; VibORM requires exactly one statement result.`,{meta:{driver:`mysql2`,operation:i}});if(Array.isArray(e)){if(!Array.isArray(t)||t.some(e=>!n(e)))throw malformedMySQL2Result(i,`row arrays require one flat field metadata array`);return{rows:e,rowCount:e.length}}if(t!==void 0)throw malformedMySQL2Result(i,`mutation results require undefined field metadata`);if(!n(e))throw malformedMySQL2Result(i,`expected a mutation result object`);let a={provider:`mysql2`,operation:i},o=normalizeMySQL2InsertId(e.insertId,a);return{rows:[],rowCount:r(e.affectedRows,a,{allowDecimalString:!0}),...o===void 0?{}:{insertId:o}}}function deriveMySQL2Namespace(e){if(e.suppliedPool)return;let t=e.connectionOptions.database;return t===``?void 0:t}function resolveMySQL2Configuration(e){let t=m(e),n=e.databaseUrl,r={...n?parseMySQL2ConfiguredUrl(n):void 0};for(let[t,n]of Object.entries(e.options??{}))n!==void 0&&Reflect.set(r,t,n);let i={suppliedPool:e.pool,connectionOptions:r};return{namespace:t??deriveMySQL2Namespace(i),...i}}function parseMySQL2ConfiguredUrl(e){try{return parseMySQLUrl(e)}catch(e){throw a(e)?e:new l(`Driver "mysql2" could not parse its databaseUrl.`,{cause:e instanceof Error?e:void 0})}}var MySQL2Driver=class extends v{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;constructor(e={}){let t=g(e),n=resolveMySQL2Configuration(e);if(super(`mysql`,`mysql2`,{},t),n.connectionOptions.multipleStatements===!0)throw new l(`Driver "mysql2" does not support options.multipleStatements=true because VibORM operations require one result per statement.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.rowsAsArray===!0)throw new l(`Driver "mysql2" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.nestTables===!0||typeof n.connectionOptions.nestTables==`string`)throw new l(`Driver "mysql2" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.`,{meta:{driver:`mysql2`,operation:`configuration`}});this.suppliedPool=n.suppliedPool,this.connectionOptions=n.connectionOptions,_(this,`adapter`,new y(n.namespace)),this.suppliedPool&&(this.client=this.suppliedPool)}async initClient(){if(this.suppliedPool!==void 0)return this.suppliedPool;let e=await import(`mysql2/promise`),t={timezone:`Z`,supportBigNumbers:!0,dateStrings:[`DATE`],...this.connectionOptions};return this.adapter.namespace!==void 0&&(t={...t,database:this.adapter.namespace}),e.createPool(t)}async closeClient(e){e!==this.suppliedPool&&await e.end()}async execute(e,t,n,r){let i=r?.operation??`execute`,[a,o]=await e.query({sql:t,values:convertValuesForMySQL(n),typeCast:(e,t)=>[`DATE`,`DATETIME`,`TIMESTAMP`,`LONGLONG`,`NEWDECIMAL`].includes(e.type)?e.string():t()});return toQueryResult(a,o,i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,[a,o]=await e.query(t,n&&convertValuesForMySQL(n));return toQueryResult(a,o,i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,t,n,r){if(!(`getConnection`in e))throw s(this.driverName);let a=e,c=await h(()=>a.getConnection(),e=>e.release(),r?.maxWaitMs,{driverName:this.driverName,form:`callback`}),l=!1,runOrDestroy=async e=>{try{await e()}catch(e){throw l=!0,e}},d=r?.isolationLevel;return o({begin:()=>runOrDestroy(async()=>{d&&await c.query(f(d)),await c.beginTransaction()}),callback:()=>t(c),commit:()=>runOrDestroy(()=>c.commit()),rollback:()=>runOrDestroy(()=>c.rollback()),phases:i(n),close:()=>{try{if(l){c.destroy();return}c.release()}catch(e){throw super.transactionCleanupFailed(new u(`Driver "mysql2" could not release an unsafe transaction connection.`,{meta:{driver:`mysql2`,method:`$transaction`}})),e}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!(`getConnection`in e))throw s(this.driverName);let t=await e.getConnection();return{session:t,release:()=>(t.destroy(),Promise.resolve())}}};function createClient(e){p(e,`mysql2`,S);let{pool:t,options:n,databaseUrl:r}=e;return d(e,new MySQL2Driver({migrationNamespaceAttestation:g(e),namespace:m(e),pool:t,options:n,databaseUrl:r}))}export{MySQL2Driver,createClient};
2
2
  //# sourceMappingURL=mysql2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"mysql2.mjs","names":[],"sources":["../src/drivers/shared/mysql-utils.ts","../src/drivers/mysql2/index.ts"],"sourcesContent":["/**\n * Shared MySQL Utilities\n *\n * Shared connection utilities for MySQL-based drivers.\n */\n\nimport { ClientInitializationError } from \"@errors\";\n\n/**\n * The connection options a MySQL database URL carries: only the keys it\n * spells, so merged under a caller's options it fills what they left out\n * instead of replacing it with `undefined` or a default port.\n */\nexport interface MySQLConnectionOptions {\n [option: string]: unknown;\n ssl?: object | string;\n host: string;\n port?: number;\n /** Absent when the URL carries no database path. */\n database?: string;\n user?: string;\n password?: string;\n}\n\nconst TLS_URL_OPTION_PATTERN = /^(?:ssl|tls)/i;\n\n/**\n * A TLS request VibORM cannot honour. Its own text, which carries no part of\n * the URL, so the driver surfaces it rather than redacting it.\n */\nfunction tlsRefusal(message: string): ClientInitializationError {\n return new ClientInitializationError(message, {\n meta: { driver: \"mysql2\", operation: \"configuration\" },\n });\n}\n\nexport function parseMySQLUrl(url: string): MySQLConnectionOptions {\n const parsed = new URL(url);\n const database = decodeURIComponent(parsed.pathname.slice(1));\n const queryOptions: Record<string, unknown> = {};\n for (const [key, value] of parsed.searchParams) {\n if (\n TLS_URL_OPTION_PATTERN.test(key) &&\n key !== \"ssl\" &&\n key !== \"sslmode\"\n ) {\n throw tlsRefusal(\n \"Unsupported MySQL TLS URL option; configure options.ssl explicitly.\"\n );\n }\n try {\n queryOptions[key] = JSON.parse(value);\n } catch {\n queryOptions[key] = value;\n }\n }\n // mysql2 understands ssl, but not libpq's sslmode. Refuse a TLS request\n // whose policy cannot be represented instead of silently opening plaintext.\n const sslmode = parsed.searchParams.get(\"sslmode\");\n if (sslmode && sslmode !== \"disable\") {\n if (![\"require\", \"verify-ca\", \"verify-full\"].includes(sslmode)) {\n throw tlsRefusal(\n \"Unsupported MySQL sslmode; configure options.ssl explicitly.\"\n );\n }\n if (\n queryOptions.ssl !== undefined &&\n (queryOptions.ssl === null ||\n (typeof queryOptions.ssl !== \"object\" &&\n typeof queryOptions.ssl !== \"string\"))\n )\n throw tlsRefusal(\"MySQL sslmode requires a TLS configuration\");\n queryOptions.ssl ??= {};\n }\n Reflect.deleteProperty(queryOptions, \"sslmode\");\n const user = decodeURIComponent(parsed.username);\n const password = decodeURIComponent(parsed.password);\n return {\n host: parsed.hostname,\n ...(parsed.port ? { port: Number.parseInt(parsed.port, 10) } : {}),\n ...(database === \"\" ? {} : { database }),\n ...(user === \"\" ? {} : { user }),\n ...(password === \"\" ? {} : { password }),\n ...queryOptions,\n };\n}\n","/**\n * MySQL2 Driver\n *\n * Driver implementation for mysql2/promise with connection pooling.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { MySQLAdapter } from \"@adapters/databases/mysql/mysql-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n isVibORMError,\n QueryError,\n TransactionError,\n} from \"@errors\";\nimport type { Pool, PoolConnection, PoolOptions } from \"mysql2/promise\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n isNormalizedResultRow,\n type NormalizedResultContext,\n normalizeProviderInsertId,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n isolationLevelStatement,\n type MigrationNamespaceAttestation,\n type MySQLConnectionOptions,\n nestedTransactionDispatchError,\n type PinnedSessionReservation,\n parseMySQLUrl,\n resolveMigrationNamespaceAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type MySQL2Options = PoolOptions;\n\nexport interface MySQL2DriverOptions {\n pool?: Pool;\n options?: PoolOptions;\n databaseUrl?: string;\n /**\n * The MySQL database this driver's persistent objects live in. Omitted, the\n * target is derived from a driver-created pool's own configuration, and a\n * driver that resolves none keeps the existing unqualified mode.\n */\n namespace?: string;\n /**\n * Caller-owned assertion that qualified `database.table` references and the\n * pinned migration session's `USE` cannot be redirected by VTGate\n * schema-routing rules or an equivalent proxy. It selects nothing, is never\n * inferred, and only effectful live migration work requires it.\n */\n migrationNamespaceAttestation?: MigrationNamespaceAttestation;\n}\n\nexport type MySQL2ClientConfig<C extends DriverConfig> = MySQL2DriverOptions &\n C;\n\nconst MYSQL2_CONFIG_KEYS: Record<keyof MySQL2DriverOptions, true> = {\n pool: true,\n options: true,\n databaseUrl: true,\n namespace: true,\n migrationNamespaceAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\n/** mysql2 escapes plain Uint8Array as an object — convert to Buffer for blobs. */\nfunction convertValuesForMySQL(values: unknown[]): unknown[] {\n return values.map((v) =>\n v instanceof Uint8Array && !Buffer.isBuffer(v)\n ? Buffer.from(v.buffer, v.byteOffset, v.byteLength)\n : v\n );\n}\n\nfunction isMultiStatementFields(fields: unknown): boolean {\n return (\n Array.isArray(fields) &&\n fields.every(\n (fieldSet) => fieldSet === undefined || Array.isArray(fieldSet)\n )\n );\n}\n\nfunction malformedMySQL2Result(operation: string, reason: string): QueryError {\n return new QueryError(\n `Driver \"mysql2\" returned a malformed result for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n}\n\nconst CANONICAL_NEGATIVE_DECIMAL = /^-[1-9]\\d*$/;\n\n/** mysql2 echoes an explicit negative AUTO_INCREMENT key in ResultSetHeader.insertId. */\nfunction normalizeMySQL2InsertId(\n value: unknown,\n context: NormalizedResultContext\n): number | bigint | undefined {\n if (\n (typeof value === \"number\" && Number.isSafeInteger(value) && value < 0) ||\n (typeof value === \"string\" && CANONICAL_NEGATIVE_DECIMAL.test(value))\n ) {\n return undefined;\n }\n return normalizeProviderInsertId(value, context, { allowNumber: true });\n}\n\n/** SELECT returns a row array; mutations return a ResultSetHeader. */\nfunction toQueryResult<T>(\n result: unknown,\n fields: unknown,\n operation: string\n): QueryResult<T> {\n if (isMultiStatementFields(fields)) {\n throw new QueryError(\n `Driver \"mysql2\" returned multiple statement results for operation \"${operation}\"; VibORM requires exactly one statement result.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n }\n\n if (Array.isArray(result)) {\n if (\n !Array.isArray(fields) ||\n fields.some((field) => !isNormalizedResultRow(field))\n ) {\n throw malformedMySQL2Result(\n operation,\n \"row arrays require one flat field metadata array\"\n );\n }\n return {\n rows: result as T[],\n rowCount: result.length,\n };\n }\n\n if (fields !== undefined) {\n throw malformedMySQL2Result(\n operation,\n \"mutation results require undefined field metadata\"\n );\n }\n if (!isNormalizedResultRow(result)) {\n throw malformedMySQL2Result(operation, \"expected a mutation result object\");\n }\n const context = { provider: \"mysql2\", operation };\n const insertId = normalizeMySQL2InsertId(result.insertId, context);\n return {\n rows: [] as T[],\n rowCount: normalizeProviderRowCount(result.affectedRows, context, {\n allowDecimalString: true,\n }),\n ...(insertId === undefined ? {} : { insertId }),\n };\n}\n\n/**\n * The target derived from a pool this driver will create: the `database` it\n * connects with, which is the caller's option when given and otherwise the\n * URL's path (see `resolveMySQL2Configuration`). A supplied `Pool` is opaque —\n * VibORM does not inspect mysql2 internals, so only an explicit `namespace` can\n * bind one. A pathless URL contributes nothing, and neither does an empty\n * `options.database`: §1.3's empty candidate is an absent one rather than a\n * name handed to identifier validation. A non-empty derived name is validated\n * exactly like an explicit one, by the adapter that installs it.\n */\nfunction deriveMySQL2Namespace(\n configuration: Omit<MySQL2Configuration, \"namespace\">\n): string | undefined {\n if (configuration.suppliedPool) return undefined;\n const configured = configuration.connectionOptions.database;\n return configured === \"\" ? undefined : configured;\n}\n\n/** What this driver settles from its caller's object, each source read once. */\ninterface MySQL2Configuration {\n readonly namespace: string | undefined;\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled once, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed.\n */\n readonly suppliedPool: Pool | undefined;\n /**\n * The caller's connection record, copied once, over the keys its\n * `databaseUrl` carries: the URL fills only what the record leaves out, and\n * a key the record sets to `undefined` (an unset environment variable) is\n * left out. A per-tenant URL plus a password from a secret is this shape.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database — all live here. It is also what the\n * constructor's refusals read, so the options this driver validated are the\n * exact options it later connects with.\n */\n readonly connectionOptions: PoolOptions;\n}\n\n/**\n * The one immutable ORM target for this driver, in the plan's exact order: an\n * explicit `namespace`, then the driver-created pool's own derivation.\n *\n * `databaseUrl` is read once and parsed once, here, and the parse is kept: a\n * second read at connect time would let a caller-owned accessor hand the\n * provider a different URL than the one that decided the target. A present URL\n * is parsed even when an explicit `namespace` outranks it, because an unusable\n * connection string is a construction failure either way; `\"\"`, `null`, and an\n * absent property are the same absent request. Both rules are the convenience\n * wrapper's too, so the two entry points cannot disagree.\n *\n * None of these sources is transport evidence: the attestation is read\n * separately and never derived from a resolved target.\n */\nfunction resolveMySQL2Configuration(\n options: MySQL2DriverOptions\n): MySQL2Configuration {\n const explicit = resolveNamespaceOption(options);\n const databaseUrl = options.databaseUrl;\n const urlOptions = databaseUrl\n ? parseMySQL2ConfiguredUrl(databaseUrl)\n : undefined;\n const connectionOptions: PoolOptions = { ...urlOptions };\n for (const [key, value] of Object.entries(options.options ?? {})) {\n if (value !== undefined) Reflect.set(connectionOptions, key, value);\n }\n const captured = { suppliedPool: options.pool, connectionOptions };\n return {\n namespace: explicit ?? deriveMySQL2Namespace(captured),\n ...captured,\n };\n}\n\n/**\n * The URL now decides a target, so a malformed one fails at construction. A\n * TLS refusal is VibORM's own secret-free text and passes through; the URL\n * parser's failure can carry the URL, so it is replaced and redacted.\n */\nfunction parseMySQL2ConfiguredUrl(databaseUrl: string): MySQLConnectionOptions {\n try {\n return parseMySQLUrl(databaseUrl);\n } catch (cause) {\n if (isVibORMError(cause)) throw cause;\n throw new ClientInitializationError(\n 'Driver \"mysql2\" could not parse its databaseUrl.',\n { cause: cause instanceof Error ? cause : undefined }\n );\n }\n}\n\nexport class MySQL2Driver extends Driver<Pool, PoolConnection> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /** The caller's pool and connection record, as construction captured them. */\n private readonly suppliedPool: Pool | undefined;\n private readonly connectionOptions: PoolOptions;\n\n constructor(options: MySQL2DriverOptions = {}) {\n // Both facts are read before `super(...)` so the transport assertion is\n // installed by the base constructor and no option can be read twice.\n const attestation = resolveMigrationNamespaceAttestationOption(options);\n const configuration = resolveMySQL2Configuration(options);\n super(\"mysql\", \"mysql2\", {}, attestation);\n if (configuration.connectionOptions.multipleStatements === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.multipleStatements=true because VibORM operations require one result per statement.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (configuration.connectionOptions.rowsAsArray === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (\n configuration.connectionOptions.nestTables === true ||\n typeof configuration.connectionOptions.nestTables === \"string\"\n ) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n this.suppliedPool = configuration.suppliedPool;\n this.connectionOptions = configuration.connectionOptions;\n defineImmutableDriverFact(\n this,\n \"adapter\",\n new MySQLAdapter(configuration.namespace)\n );\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<Pool> {\n if (this.suppliedPool !== undefined) {\n return this.suppliedPool;\n }\n const mysql = await import(\"mysql2/promise\");\n\n let options: PoolOptions = {\n // DATETIME is stored as naive UTC wall-clock; read it back as UTC\n // instead of shifting by the process timezone\n timezone: \"Z\",\n // BIGINT/DECIMAL values outside Number's safe range arrive as strings\n // (the result parser converts them losslessly) instead of lossy numbers\n supportBigNumbers: true,\n // DATE as plain \"YYYY-MM-DD\" — the result parser builds a UTC-midnight\n // Date, matching every other driver (mysql2 would build local midnight)\n dateStrings: [\"DATE\"],\n // Already merged with the URL, from the one parse construction made:\n // this driver never re-reads the caller's `databaseUrl`.\n ...this.connectionOptions,\n };\n\n // The pool this driver creates defaults to the same database the adapter\n // qualifies with, whichever source resolved it. A supplied pool never\n // reaches here, so VibORM never changes a caller's connection state.\n if (this.adapter.namespace !== undefined) {\n options = { ...options, database: this.adapter.namespace };\n }\n\n return mysql.createPool(options);\n }\n\n /**\n * Ends only a pool this driver created.\n *\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients or with their own code, and §5.3's rule is that VibORM never\n * changes a caller's connection state. `$disconnect()` used to end it\n * regardless, so disconnecting one client tore down every other consumer of\n * that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: Pool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n await pool.end();\n }\n\n protected async execute<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const [result, fields] = await client.query({\n sql,\n values: convertValuesForMySQL(params),\n // Per-statement decoding also covers borrowed pools without mutating\n // their connection options. Text protocol avoids a statement per IN size.\n typeCast: (field, next) =>\n [\"DATE\", \"DATETIME\", \"TIMESTAMP\", \"LONGLONG\", \"NEWDECIMAL\"].includes(\n field.type\n )\n ? field.string()\n : next(),\n });\n return toQueryResult<T>(result, fields, operation);\n }\n\n protected async executeRaw<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const [result, fields] = await client.query(\n sql,\n params && convertValuesForMySQL(params)\n );\n return toQueryResult<T>(result, fields, operation);\n }\n\n /**\n * MySQL rejects `SET TRANSACTION ISOLATION LEVEL` once a transaction is open\n * (ER_CANT_CHANGE_TX_CHARACTERISTICS), so the level must be set on the\n * transaction's own connection *before* BEGIN, where it applies to exactly\n * the next transaction on that session. mysql2 pools hand out a connection we\n * can wait for with a bound and release if we stop waiting.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"pre-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: Pool | PoolConnection,\n fn: (tx: PoolConnection) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction from pool\n const pool = client as Pool;\n const connection = await acquireWithMaxWait(\n () => pool.getConnection(),\n (acquired) => acquired.release(),\n options?.maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n let shouldDestroy = false;\n const runOrDestroy = async (operation: () => Promise<void>) => {\n try {\n await operation();\n } catch (error) {\n shouldDestroy = true;\n throw error;\n }\n };\n const isolationLevel = options?.isolationLevel;\n return runTransactionLifecycle({\n begin: () =>\n runOrDestroy(async () => {\n // Session-scoped-next-transaction: this statement must land before\n // beginTransaction() to bind to the transaction it opens.\n if (isolationLevel) {\n await connection.query(isolationLevelStatement(isolationLevel));\n }\n await connection.beginTransaction();\n }),\n callback: () => fn(connection),\n commit: () => runOrDestroy(() => connection.commit()),\n rollback: () => runOrDestroy(() => connection.rollback()),\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n if (shouldDestroy) {\n connection.destroy();\n return;\n }\n connection.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"mysql2\" could not release an unsafe transaction connection.',\n { meta: { driver: \"mysql2\", method: \"$transaction\" } }\n )\n );\n throw error;\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // A connection with failed cleanup is destroyed; the pool remains usable.\n }\n\n /**\n * One `PoolConnection` from `pool.getConnection()` — plan §3.5's pinned\n * producer for MySQL2.\n *\n * It is ALWAYS destroyed, never released, and the `discard` flag is therefore\n * ignored: this session has executed `USE` to select the migration target and\n * may have executed author-owned statements from a manual artifact, and\n * mysql2's release resets neither. Returning it to an owned or a supplied\n * pool would leak that state into unrelated queries. This is correctness, not\n * an optimization.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<Pool | PoolConnection>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const connection = await client.getConnection();\n return {\n session: connection,\n release: () => {\n connection.destroy();\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: MySQL2ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, MySQL2DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: MySQL2Driver }\n >]: LinkedClientConfig<C & { driver: MySQL2Driver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"mysql2\", MYSQL2_CONFIG_KEYS);\n const { pool, options, databaseUrl } = config;\n const driver = new MySQL2Driver({\n // Attestation first, then namespace: the order a refusal reports in.\n migrationNamespaceAttestation:\n resolveMigrationNamespaceAttestationOption(config),\n namespace: resolveNamespaceOption(config),\n pool,\n options,\n databaseUrl,\n });\n\n return createClientFromDriverConfig<S, C, MySQL2Driver>(config, driver);\n}\n"],"mappings":"yjBAwBA,MAAM,EAAyB,gBAM/B,SAAS,WAAW,EAA4C,CAC9D,OAAO,IAAI,EAA0B,EAAS,CAC5C,KAAM,CAAE,OAAQ,SAAU,UAAW,gBAAiB,CACvD,CAAC,CAGJ,SAAgB,cAAc,EAAqC,CACjE,IAAM,EAAS,IAAI,IAAI,EAAI,CACrB,EAAW,mBAAmB,EAAO,SAAS,MAAM,EAAE,CAAC,CACvD,EAAwC,EAAE,CAChD,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,aAAc,CAC9C,GACE,EAAuB,KAAK,EAAI,EAChC,IAAQ,OACR,IAAQ,UAER,MAAM,WACJ,sEACD,CAEH,GAAI,CACF,EAAa,GAAO,KAAK,MAAM,EAAM,MAC/B,CACN,EAAa,GAAO,GAKxB,IAAM,EAAU,EAAO,aAAa,IAAI,UAAU,CAClD,GAAI,GAAW,IAAY,UAAW,CACpC,GAAI,CAAC,CAAC,UAAW,YAAa,cAAc,CAAC,SAAS,EAAQ,CAC5D,MAAM,WACJ,+DACD,CAEH,GACE,EAAa,MAAQ,IAAA,KACpB,EAAa,MAAQ,MACnB,OAAO,EAAa,KAAQ,UAC3B,OAAO,EAAa,KAAQ,UAEhC,MAAM,WAAW,6CAA6C,CAChE,EAAa,MAAQ,EAAE,CAEzB,QAAQ,eAAe,EAAc,UAAU,CAC/C,IAAM,EAAO,mBAAmB,EAAO,SAAS,CAC1C,EAAW,mBAAmB,EAAO,SAAS,CACpD,MAAO,CACL,KAAM,EAAO,SACb,GAAI,EAAO,KAAO,CAAE,KAAM,OAAO,SAAS,EAAO,KAAM,GAAG,CAAE,CAAG,EAAE,C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,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAa,MAAM,EAAO,eAAe,CAC/C,MAAO,CACL,QAAS,EACT,aACE,EAAW,SAAS,CACb,QAAQ,SAAS,EAE3B,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,SAAU,EAAmB,CACnE,GAAM,CAAE,OAAM,UAAS,eAAgB,EAWvC,OAAO,EAAiD,EAVzC,IAAI,aAAa,CAE9B,8BACE,EAA2C,EAAO,CACpD,UAAW,EAAuB,EAAO,CACzC,OACA,UACA,cACD,CAAC,CAEqE"}
1
+ {"version":3,"file":"mysql2.mjs","names":[],"sources":["../src/drivers/shared/mysql-utils.ts","../src/drivers/mysql2/index.ts"],"sourcesContent":["/**\n * Shared MySQL Utilities\n *\n * Shared connection utilities for MySQL-based drivers.\n */\n\nimport { ClientInitializationError } from \"@errors\";\n\n/**\n * The connection options a MySQL database URL carries: only the keys it\n * spells, so merged under a caller's options it fills what they left out\n * instead of replacing it with `undefined` or a default port.\n */\nexport interface MySQLConnectionOptions {\n [option: string]: unknown;\n ssl?: object | string;\n host: string;\n port?: number;\n /** Absent when the URL carries no database path. */\n database?: string;\n user?: string;\n password?: string;\n}\n\nconst TLS_URL_OPTION_PATTERN = /^(?:ssl|tls)/i;\n\n/**\n * A TLS request VibORM cannot honour. Its own text, which carries no part of\n * the URL, so the driver surfaces it rather than redacting it.\n */\nfunction tlsRefusal(message: string): ClientInitializationError {\n return new ClientInitializationError(message, {\n meta: { driver: \"mysql2\", operation: \"configuration\" },\n });\n}\n\nexport function parseMySQLUrl(url: string): MySQLConnectionOptions {\n const parsed = new URL(url);\n const database = decodeURIComponent(parsed.pathname.slice(1));\n const queryOptions: Record<string, unknown> = {};\n for (const [key, value] of parsed.searchParams) {\n if (\n TLS_URL_OPTION_PATTERN.test(key) &&\n key !== \"ssl\" &&\n key !== \"sslmode\"\n ) {\n throw tlsRefusal(\n \"Unsupported MySQL TLS URL option; configure options.ssl explicitly.\"\n );\n }\n try {\n queryOptions[key] = JSON.parse(value);\n } catch {\n queryOptions[key] = value;\n }\n }\n // mysql2 understands ssl, but not libpq's sslmode. Refuse a TLS request\n // whose policy cannot be represented instead of silently opening plaintext.\n const sslmode = parsed.searchParams.get(\"sslmode\");\n if (sslmode && sslmode !== \"disable\") {\n if (![\"require\", \"verify-ca\", \"verify-full\"].includes(sslmode)) {\n throw tlsRefusal(\n \"Unsupported MySQL sslmode; configure options.ssl explicitly.\"\n );\n }\n if (\n queryOptions.ssl !== undefined &&\n (queryOptions.ssl === null ||\n (typeof queryOptions.ssl !== \"object\" &&\n typeof queryOptions.ssl !== \"string\"))\n )\n throw tlsRefusal(\"MySQL sslmode requires a TLS configuration\");\n queryOptions.ssl ??= {};\n }\n Reflect.deleteProperty(queryOptions, \"sslmode\");\n const user = decodeURIComponent(parsed.username);\n const password = decodeURIComponent(parsed.password);\n return {\n host: parsed.hostname,\n ...(parsed.port ? { port: Number.parseInt(parsed.port, 10) } : {}),\n ...(database === \"\" ? {} : { database }),\n ...(user === \"\" ? {} : { user }),\n ...(password === \"\" ? {} : { password }),\n ...queryOptions,\n };\n}\n","/**\n * MySQL2 Driver\n *\n * Driver implementation for mysql2/promise with connection pooling.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { MySQLAdapter } from \"@adapters/databases/mysql/mysql-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n isVibORMError,\n QueryError,\n TransactionError,\n} from \"@errors\";\nimport type { Pool, PoolConnection, PoolOptions } from \"mysql2/promise\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n isNormalizedResultRow,\n type NormalizedResultContext,\n normalizeProviderInsertId,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n isolationLevelStatement,\n type MigrationNamespaceAttestation,\n type MySQLConnectionOptions,\n nestedTransactionDispatchError,\n type PinnedSessionReservation,\n parseMySQLUrl,\n resolveMigrationNamespaceAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type MySQL2Options = PoolOptions;\n\nexport interface MySQL2DriverOptions {\n pool?: Pool;\n options?: PoolOptions;\n databaseUrl?: string;\n /**\n * The MySQL database this driver's persistent objects live in. Omitted, the\n * target is derived from a driver-created pool's own configuration, and a\n * driver that resolves none keeps the existing unqualified mode.\n */\n namespace?: string;\n /**\n * Caller-owned assertion that qualified `database.table` references and the\n * pinned migration session's `USE` cannot be redirected by VTGate\n * schema-routing rules or an equivalent proxy. It selects nothing, is never\n * inferred, and only effectful live migration work requires it.\n */\n migrationNamespaceAttestation?: MigrationNamespaceAttestation;\n}\n\nexport type MySQL2ClientConfig<C extends DriverConfig> = MySQL2DriverOptions &\n C;\n\nconst MYSQL2_CONFIG_KEYS: Record<keyof MySQL2DriverOptions, true> = {\n pool: true,\n options: true,\n databaseUrl: true,\n namespace: true,\n migrationNamespaceAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\n/** mysql2 escapes plain Uint8Array as an object — convert to Buffer for blobs. */\nfunction convertValuesForMySQL(values: unknown[]): unknown[] {\n return values.map((v) =>\n v instanceof Uint8Array && !Buffer.isBuffer(v)\n ? Buffer.from(v.buffer, v.byteOffset, v.byteLength)\n : v\n );\n}\n\nfunction isMultiStatementFields(fields: unknown): boolean {\n return (\n Array.isArray(fields) &&\n fields.every(\n (fieldSet) => fieldSet === undefined || Array.isArray(fieldSet)\n )\n );\n}\n\nfunction malformedMySQL2Result(operation: string, reason: string): QueryError {\n return new QueryError(\n `Driver \"mysql2\" returned a malformed result for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n}\n\nconst CANONICAL_NEGATIVE_DECIMAL = /^-[1-9]\\d*$/;\n\n/** mysql2 echoes an explicit negative AUTO_INCREMENT key in ResultSetHeader.insertId. */\nfunction normalizeMySQL2InsertId(\n value: unknown,\n context: NormalizedResultContext\n): number | bigint | undefined {\n if (\n (typeof value === \"number\" && Number.isSafeInteger(value) && value < 0) ||\n (typeof value === \"string\" && CANONICAL_NEGATIVE_DECIMAL.test(value))\n ) {\n return undefined;\n }\n return normalizeProviderInsertId(value, context, { allowNumber: true });\n}\n\n/** SELECT returns a row array; mutations return a ResultSetHeader. */\nfunction toQueryResult<T>(\n result: unknown,\n fields: unknown,\n operation: string\n): QueryResult<T> {\n if (isMultiStatementFields(fields)) {\n throw new QueryError(\n `Driver \"mysql2\" returned multiple statement results for operation \"${operation}\"; VibORM requires exactly one statement result.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n }\n\n if (Array.isArray(result)) {\n if (\n !Array.isArray(fields) ||\n fields.some((field) => !isNormalizedResultRow(field))\n ) {\n throw malformedMySQL2Result(\n operation,\n \"row arrays require one flat field metadata array\"\n );\n }\n return {\n rows: result as T[],\n rowCount: result.length,\n };\n }\n\n if (fields !== undefined) {\n throw malformedMySQL2Result(\n operation,\n \"mutation results require undefined field metadata\"\n );\n }\n if (!isNormalizedResultRow(result)) {\n throw malformedMySQL2Result(operation, \"expected a mutation result object\");\n }\n const context = { provider: \"mysql2\", operation };\n const insertId = normalizeMySQL2InsertId(result.insertId, context);\n return {\n rows: [] as T[],\n rowCount: normalizeProviderRowCount(result.affectedRows, context, {\n allowDecimalString: true,\n }),\n ...(insertId === undefined ? {} : { insertId }),\n };\n}\n\n/**\n * The target derived from a pool this driver will create: the `database` it\n * connects with, which is the caller's option when given and otherwise the\n * URL's path (see `resolveMySQL2Configuration`). A supplied `Pool` is opaque —\n * VibORM does not inspect mysql2 internals, so only an explicit `namespace` can\n * bind one. A pathless URL contributes nothing, and neither does an empty\n * `options.database`: §1.3's empty candidate is an absent one rather than a\n * name handed to identifier validation. A non-empty derived name is validated\n * exactly like an explicit one, by the adapter that installs it.\n */\nfunction deriveMySQL2Namespace(\n configuration: Omit<MySQL2Configuration, \"namespace\">\n): string | undefined {\n if (configuration.suppliedPool) return undefined;\n const configured = configuration.connectionOptions.database;\n return configured === \"\" ? undefined : configured;\n}\n\n/** What this driver settles from its caller's object, each source read once. */\ninterface MySQL2Configuration {\n readonly namespace: string | undefined;\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled once, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed.\n */\n readonly suppliedPool: Pool | undefined;\n /**\n * The caller's connection record, copied once, over the keys its\n * `databaseUrl` carries: the URL fills only what the record leaves out, and\n * a key the record sets to `undefined` (an unset environment variable) is\n * left out. A per-tenant URL plus a password from a secret is this shape.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database — all live here. It is also what the\n * constructor's refusals read, so the options this driver validated are the\n * exact options it later connects with.\n */\n readonly connectionOptions: PoolOptions;\n}\n\n/**\n * The one immutable ORM target for this driver, in the plan's exact order: an\n * explicit `namespace`, then the driver-created pool's own derivation.\n *\n * `databaseUrl` is read once and parsed once, here, and the parse is kept: a\n * second read at connect time would let a caller-owned accessor hand the\n * provider a different URL than the one that decided the target. A present URL\n * is parsed even when an explicit `namespace` outranks it, because an unusable\n * connection string is a construction failure either way; `\"\"`, `null`, and an\n * absent property are the same absent request. Both rules are the convenience\n * wrapper's too, so the two entry points cannot disagree.\n *\n * None of these sources is transport evidence: the attestation is read\n * separately and never derived from a resolved target.\n */\nfunction resolveMySQL2Configuration(\n options: MySQL2DriverOptions\n): MySQL2Configuration {\n const explicit = resolveNamespaceOption(options);\n const databaseUrl = options.databaseUrl;\n const urlOptions = databaseUrl\n ? parseMySQL2ConfiguredUrl(databaseUrl)\n : undefined;\n const connectionOptions: PoolOptions = { ...urlOptions };\n for (const [key, value] of Object.entries(options.options ?? {})) {\n if (value !== undefined) Reflect.set(connectionOptions, key, value);\n }\n const captured = { suppliedPool: options.pool, connectionOptions };\n return {\n namespace: explicit ?? deriveMySQL2Namespace(captured),\n ...captured,\n };\n}\n\n/**\n * The URL now decides a target, so a malformed one fails at construction. A\n * TLS refusal is VibORM's own secret-free text and passes through; the URL\n * parser's failure can carry the URL, so it is replaced and redacted.\n */\nfunction parseMySQL2ConfiguredUrl(databaseUrl: string): MySQLConnectionOptions {\n try {\n return parseMySQLUrl(databaseUrl);\n } catch (cause) {\n if (isVibORMError(cause)) throw cause;\n throw new ClientInitializationError(\n 'Driver \"mysql2\" could not parse its databaseUrl.',\n { cause: cause instanceof Error ? cause : undefined }\n );\n }\n}\n\nexport class MySQL2Driver extends Driver<Pool, PoolConnection> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /** The caller's pool and connection record, as construction captured them. */\n private readonly suppliedPool: Pool | undefined;\n private readonly connectionOptions: PoolOptions;\n\n constructor(options: MySQL2DriverOptions = {}) {\n // Both facts are read before `super(...)` so the transport assertion is\n // installed by the base constructor and no option can be read twice.\n const attestation = resolveMigrationNamespaceAttestationOption(options);\n const configuration = resolveMySQL2Configuration(options);\n super(\"mysql\", \"mysql2\", {}, attestation);\n if (configuration.connectionOptions.multipleStatements === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.multipleStatements=true because VibORM operations require one result per statement.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (configuration.connectionOptions.rowsAsArray === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (\n configuration.connectionOptions.nestTables === true ||\n typeof configuration.connectionOptions.nestTables === \"string\"\n ) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n this.suppliedPool = configuration.suppliedPool;\n this.connectionOptions = configuration.connectionOptions;\n defineImmutableDriverFact(\n this,\n \"adapter\",\n new MySQLAdapter(configuration.namespace)\n );\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<Pool> {\n if (this.suppliedPool !== undefined) {\n return this.suppliedPool;\n }\n const mysql = await import(\"mysql2/promise\");\n\n let options: PoolOptions = {\n // DATETIME is stored as naive UTC wall-clock; read it back as UTC\n // instead of shifting by the process timezone\n timezone: \"Z\",\n // BIGINT/DECIMAL values outside Number's safe range arrive as strings\n // (the result parser converts them losslessly) instead of lossy numbers\n supportBigNumbers: true,\n // DATE as plain \"YYYY-MM-DD\" — the result parser builds a UTC-midnight\n // Date, matching every other driver (mysql2 would build local midnight)\n dateStrings: [\"DATE\"],\n // Already merged with the URL, from the one parse construction made:\n // this driver never re-reads the caller's `databaseUrl`.\n ...this.connectionOptions,\n };\n\n // The pool this driver creates defaults to the same database the adapter\n // qualifies with, whichever source resolved it. A supplied pool never\n // reaches here, so VibORM never changes a caller's connection state.\n if (this.adapter.namespace !== undefined) {\n options = { ...options, database: this.adapter.namespace };\n }\n\n return mysql.createPool(options);\n }\n\n /**\n * Ends only a pool this driver created.\n *\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients or with their own code, and §5.3's rule is that VibORM never\n * changes a caller's connection state. `$disconnect()` used to end it\n * regardless, so disconnecting one client tore down every other consumer of\n * that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: Pool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n await pool.end();\n }\n\n protected async execute<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const [result, fields] = await client.query({\n sql,\n values: convertValuesForMySQL(params),\n // Per-statement decoding also covers borrowed pools without mutating\n // their connection options. Text protocol avoids a statement per IN size.\n typeCast: (field, next) =>\n [\"DATE\", \"DATETIME\", \"TIMESTAMP\", \"LONGLONG\", \"NEWDECIMAL\"].includes(\n field.type\n )\n ? field.string()\n : next(),\n });\n return toQueryResult<T>(result, fields, operation);\n }\n\n protected async executeRaw<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const [result, fields] = await client.query(\n sql,\n params && convertValuesForMySQL(params)\n );\n return toQueryResult<T>(result, fields, operation);\n }\n\n /**\n * MySQL rejects `SET TRANSACTION ISOLATION LEVEL` once a transaction is open\n * (ER_CANT_CHANGE_TX_CHARACTERISTICS), so the level must be set on the\n * transaction's own connection *before* BEGIN, where it applies to exactly\n * the next transaction on that session. mysql2 pools hand out a connection we\n * can wait for with a bound and release if we stop waiting.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"pre-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: Pool | PoolConnection,\n fn: (tx: PoolConnection) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction from pool\n const pool = client as Pool;\n const connection = await acquireWithMaxWait(\n () => pool.getConnection(),\n (acquired) => acquired.release(),\n options?.maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n let shouldDestroy = false;\n const runOrDestroy = async (operation: () => Promise<void>) => {\n try {\n await operation();\n } catch (error) {\n shouldDestroy = true;\n throw error;\n }\n };\n const isolationLevel = options?.isolationLevel;\n return runTransactionLifecycle({\n begin: () =>\n runOrDestroy(async () => {\n // Session-scoped-next-transaction: this statement must land before\n // beginTransaction() to bind to the transaction it opens.\n if (isolationLevel) {\n await connection.query(isolationLevelStatement(isolationLevel));\n }\n await connection.beginTransaction();\n }),\n callback: () => fn(connection),\n commit: () => runOrDestroy(() => connection.commit()),\n rollback: () => runOrDestroy(() => connection.rollback()),\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n if (shouldDestroy) {\n connection.destroy();\n return;\n }\n connection.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"mysql2\" could not release an unsafe transaction connection.',\n { meta: { driver: \"mysql2\", method: \"$transaction\" } }\n )\n );\n throw error;\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // A connection with failed cleanup is destroyed; the pool remains usable.\n }\n\n /**\n * One `PoolConnection` from `pool.getConnection()` — plan §3.5's pinned\n * producer for MySQL2.\n *\n * It is ALWAYS destroyed, never released, and the `discard` flag is therefore\n * ignored: this session has executed `USE` to select the migration target and\n * may have executed author-owned statements from a manual artifact, and\n * mysql2's release resets neither. Returning it to an owned or a supplied\n * pool would leak that state into unrelated queries. This is correctness, not\n * an optimization.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<Pool | PoolConnection>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const connection = await client.getConnection();\n return {\n session: connection,\n release: () => {\n connection.destroy();\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: MySQL2ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, MySQL2DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: MySQL2Driver }\n >]: LinkedClientConfig<C & { driver: MySQL2Driver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"mysql2\", MYSQL2_CONFIG_KEYS);\n const { pool, options, databaseUrl } = config;\n const driver = new MySQL2Driver({\n // Attestation first, then namespace: the order a refusal reports in.\n migrationNamespaceAttestation:\n resolveMigrationNamespaceAttestationOption(config),\n namespace: resolveNamespaceOption(config),\n pool,\n options,\n databaseUrl,\n });\n\n return createClientFromDriverConfig<S, C, MySQL2Driver>(config, driver);\n}\n"],"mappings":"ojBAwBA,MAAM,EAAyB,gBAM/B,SAAS,WAAW,EAA4C,CAC9D,OAAO,IAAI,EAA0B,EAAS,CAC5C,KAAM,CAAE,OAAQ,SAAU,UAAW,gBAAiB,CACvD,CAAC,CAGJ,SAAgB,cAAc,EAAqC,CACjE,IAAM,EAAS,IAAI,IAAI,EAAI,CACrB,EAAW,mBAAmB,EAAO,SAAS,MAAM,EAAE,CAAC,CACvD,EAAwC,EAAE,CAChD,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,aAAc,CAC9C,GACE,EAAuB,KAAK,EAAI,EAChC,IAAQ,OACR,IAAQ,UAER,MAAM,WACJ,sEACD,CAEH,GAAI,CACF,EAAa,GAAO,KAAK,MAAM,EAAM,MAC/B,CACN,EAAa,GAAO,GAKxB,IAAM,EAAU,EAAO,aAAa,IAAI,UAAU,CAClD,GAAI,GAAW,IAAY,UAAW,CACpC,GAAI,CAAC,CAAC,UAAW,YAAa,cAAc,CAAC,SAAS,EAAQ,CAC5D,MAAM,WACJ,+DACD,CAEH,GACE,EAAa,MAAQ,IAAA,KACpB,E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AI,CACF,GAAI,EAAe,CACjB,EAAW,SAAS,CACpB,OAEF,EAAW,SAAS,OACb,EAAO,CAOd,MANA,MAAM,yBACJ,IAAI,EACF,sEACA,CAAE,KAAM,CAAE,OAAQ,SAAU,OAAQ,eAAgB,CAAE,CACvD,CACF,CACK,IAGX,CAAC,CAGJ,yBAA4C,EAAqB,EAejE,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,EAAE,kBAAmB,GACvB,MAAM,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAa,MAAM,EAAO,eAAe,CAC/C,MAAO,CACL,QAAS,EACT,aACE,EAAW,SAAS,CACb,QAAQ,SAAS,EAE3B,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,SAAU,EAAmB,CACnE,GAAM,CAAE,OAAM,UAAS,eAAgB,EAWvC,OAAO,EAAiD,EAVzC,IAAI,aAAa,CAE9B,8BACE,EAA2C,EAAO,CACpD,UAAW,EAAuB,EAAO,CACzC,OACA,UACA,cACD,CAAC,CAEqE"}
@@ -1,2 +1,2 @@
1
1
  import{n as e}from"./chunk-BuuaeEvq.mjs";const t=[`pg`,`mysql`,`sqlite`],isTaggedNativeType=e=>`db`in e;function nativeTypeFor(e,t){if(e!==void 0)return isTaggedNativeType(e)?e.db===t?e:void 0:e[t]}const fixed=e=>t=>({db:e,type:t}),n=fixed(`pg`),r=fixed(`mysql`),i=fixed(`sqlite`),sized=(e,t)=>n=>({db:e,type:`${t}(${n})`}),opt=(e,t)=>n=>({db:e,type:n===void 0?t:`${t}(${n})`}),a={STRING:{TEXT:n(`text`),VARCHAR:sized(`pg`,`varchar`),CHAR:sized(`pg`,`char`),CITEXT:n(`citext`),UUID:n(`uuid`),BIT:sized(`pg`,`bit`),VARBIT:e=>({db:`pg`,type:e?`varbit(${e})`:`varbit`}),XML:n(`xml`),INET:n(`inet`),CIDR:n(`cidr`),MACADDR:n(`macaddr`),MACADDR8:n(`macaddr8`),TSVECTOR:n(`tsvector`),TSQUERY:n(`tsquery`)},INT:{SMALLINT:n(`smallint`),INTEGER:n(`integer`),OID:n(`oid`)},BIGINT:{BIGINT:n(`bigint`)},FLOAT:{REAL:n(`real`),DOUBLE_PRECISION:n(`double precision`)},BOOLEAN:{BOOLEAN:n(`boolean`)},DATETIME:{TIMESTAMP:opt(`pg`,`timestamp`),TIMESTAMPTZ:opt(`pg`,`timestamptz`),DATE:n(`date`),TIME:opt(`pg`,`time`),TIMETZ:opt(`pg`,`timetz`)},JSON:{JSON:n(`json`),JSONB:n(`jsonb`)},BLOB:{BYTEA:n(`bytea`)}},o={STRING:{VARCHAR:sized(`mysql`,`VARCHAR`),CHAR:sized(`mysql`,`CHAR`),TEXT:r(`TEXT`),TINYTEXT:r(`TINYTEXT`),MEDIUMTEXT:r(`MEDIUMTEXT`),LONGTEXT:r(`LONGTEXT`),BIT:sized(`mysql`,`BIT`)},INT:{TINYINT:r(`TINYINT`),TINYINT_UNSIGNED:r(`TINYINT UNSIGNED`),SMALLINT:r(`SMALLINT`),SMALLINT_UNSIGNED:r(`SMALLINT UNSIGNED`),MEDIUMINT:r(`MEDIUMINT`),MEDIUMINT_UNSIGNED:r(`MEDIUMINT UNSIGNED`),INT:r(`INT`),INT_UNSIGNED:r(`INT UNSIGNED`),YEAR:r(`YEAR`)},BIGINT:{BIGINT:r(`BIGINT`),BIGINT_UNSIGNED:r(`BIGINT UNSIGNED`)},FLOAT:{FLOAT:r(`FLOAT`),DOUBLE:r(`DOUBLE`)},BOOLEAN:{TINYINT:r(`TINYINT(1)`)},DATETIME:{DATETIME:opt(`mysql`,`DATETIME`),TIMESTAMP:opt(`mysql`,`TIMESTAMP`),DATE:r(`DATE`),TIME:opt(`mysql`,`TIME`)},JSON:{JSON:r(`JSON`)},BLOB:{BLOB:r(`BLOB`),TINYBLOB:r(`TINYBLOB`),MEDIUMBLOB:r(`MEDIUMBLOB`),LONGBLOB:r(`LONGBLOB`),BINARY:sized(`mysql`,`BINARY`),VARBINARY:sized(`mysql`,`VARBINARY`)}},s={STRING:{TEXT:i(`TEXT`)},INT:{INTEGER:i(`INTEGER`)},BIGINT:{INTEGER:i(`INTEGER`)},FLOAT:{REAL:i(`REAL`)},BOOLEAN:{INTEGER:i(`INTEGER`)},DATETIME:{TEXT:i(`TEXT`),REAL:i(`REAL`),INTEGER:i(`INTEGER`)},JSON:{TEXT:i(`TEXT`)},BLOB:{BLOB:i(`BLOB`)}};export{isTaggedNativeType as a,s as i,t as n,nativeTypeFor as o,a as r,o as t};
2
- //# sourceMappingURL=native-types-BbKWN3JV.mjs.map
2
+ //# sourceMappingURL=native-types-CQH05hcr.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"native-types-BbKWN3JV.mjs","names":[],"sources":["../src/schema/scalars/native-types.ts"],"sourcesContent":["// Native Database Type Overrides\n// Provides typed constants for database-specific column types\n\n// =============================================================================\n// NATIVE TYPE INTERFACE\n// =============================================================================\n\nexport interface NativeType {\n readonly db: \"pg\" | \"mysql\" | \"sqlite\";\n readonly type: string;\n}\n\n/** The three dialects a native type can name. */\nexport type NativeDialect = NativeType[\"db\"];\n\n/**\n * A native type of ONE dialect — what every `PG` / `MYSQL` / `SQLITE` constant\n * is, parameterized ones included, so `PG.STRING.VARCHAR(80)` can fill a `pg`\n * entry of a {@link NativeTypeMap} and cannot fill a `mysql` one.\n */\nexport interface DialectNativeType<Dialect extends NativeDialect>\n extends NativeType {\n readonly db: Dialect;\n}\n\n/**\n * One scalar's native type on each dialect it names:\n * `s.string({ pg: PG.STRING.CITEXT, mysql: MYSQL.STRING.LONGTEXT })`.\n *\n * A dialect the map leaves out keeps that scalar's automatic column, exactly\n * as a tagged {@link NativeType} leaves every OTHER dialect's column alone.\n */\nexport interface NativeTypeMap {\n readonly pg?: DialectNativeType<\"pg\">;\n readonly mysql?: DialectNativeType<\"mysql\">;\n readonly sqlite?: DialectNativeType<\"sqlite\">;\n}\n\n/**\n * What a scalar factory's native-type argument declares: the tagged shorthand\n * (one dialect) or a {@link NativeTypeMap} (several). Scalars store the\n * declaration in the form it was written, so a schema document restates it\n * faithfully; every PHYSICAL reader asks {@link nativeTypeFor} instead of\n * inspecting the form.\n */\nexport type NativeTypeDeclaration = NativeType | NativeTypeMap;\n\n/** Every dialect, in the order a per-dialect question visits them. */\nexport const NATIVE_DIALECTS: readonly NativeDialect[] = [\n \"pg\",\n \"mysql\",\n \"sqlite\",\n];\n\n/** Whether a declaration is the tagged shorthand rather than a map. */\nexport const isTaggedNativeType = (\n declaration: NativeTypeDeclaration\n): declaration is NativeType => \"db\" in declaration;\n\n/**\n * The native type a declaration selects on one dialect, or `undefined` for the\n * dialect's automatic column.\n *\n * The ONE bound-dialect resolver. A migration driver, an adapter and the\n * identifier storage owner each know which dialect they speak and ask this;\n * none of them reads the declaration's form. A tagged shorthand for another\n * dialect is that dialect's automatic column, as it always was.\n */\nexport function nativeTypeFor(\n declaration: NativeTypeDeclaration | undefined,\n dialect: NativeDialect\n): NativeType | undefined {\n if (declaration === undefined) return undefined;\n if (isTaggedNativeType(declaration)) {\n return declaration.db === dialect ? declaration : undefined;\n }\n return declaration[dialect];\n}\n\n/**\n * A scalar factory's native-type argument: the tagged shorthand of dialect\n * `Db`, or the map `Given`, which the factory bounds by\n * {@link ExactNativeTypeMap}.\n *\n * The tagged shorthand keeps its historical shape: a `NativeType`, a union of\n * them, a generic `T extends NativeType`, a custom `type`, or one with unrelated\n * extra keys held in a variable all still compile, a fresh literal with an extra\n * key is still an excess-property error, and a value missing `db` or `type` is\n * still refused — except that a dialect key BESIDE its `db` is refused, since\n * that object would be two declarations at once.\n *\n * `Db` is inferred from a tagged value's `db` only so that TypeScript counts the\n * value as matched by this first member and keeps it out of `Given`: an\n * argument reaches `Given` only when it is not tagged, and `Given` is naked so\n * a union-typed argument (`NativeType | NativeTypeMap`) reaches it whole.\n */\nexport type NativeTypeArgument<Db extends NativeDialect, Given> =\n | (DialectNativeType<Db> & Partial<Record<NativeDialect, never>>)\n | Given;\n\n/**\n * The bound of a factory's `Given`: every key a dialect, each entry a native\n * type of its own key's dialect, and at least one dialect key. `{ type: \"text\" }`,\n * `{ postgres: … }`, `{}` and a `Date` are refused; an unknown key is refused\n * beside a real one, fresh and held in a variable. An argument that fails the\n * bound is refused against the bound itself, which is TypeScript's fallback.\n *\n * The exactness is a homomorphic mapped type, so it judges each member of a\n * union-typed map on its own. Measured traps (TS 7.0.2) that shaped it: a\n * generic CONSTRAINED to the weak `NativeTypeMap` falls back to that weak type\n * and admitted `{ foo: 1 }` and a `Date`; a parameter spelled `Given & NoInfer<…>`\n * makes TypeScript infer one member of a union argument; and a bound that is a\n * conditional type distributing over `Given` is a circular constraint (TS2313).\n * The at-least-one test is therefore not distributive: a union of maps with no\n * dialect key in COMMON is refused — annotate such a variable `NativeTypeMap`.\n */\nexport type ExactNativeTypeMap<Given> = {\n [Key in keyof Given]: Key extends NativeDialect\n ? DialectNativeType<Key>\n : never;\n} & ([keyof Given & NativeDialect] extends [never] ? never : unknown);\n\n// =============================================================================\n// CONSTANT BUILDERS\n// =============================================================================\n\n/** A fixed native type: its `db` and `type` keep their literal types. */\nconst fixed =\n <const Db extends NativeDialect>(db: Db) =>\n <const Type extends string>(type: Type) =>\n ({ db, type }) as const;\n\nconst pg = fixed(\"pg\");\nconst mysql = fixed(\"mysql\");\nconst sqlite = fixed(\"sqlite\");\n\n/** A type that takes one required size: `varchar(80)`. */\nconst sized =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (n: number): DialectNativeType<Db> => ({ db, type: `${name}(${n})` });\n\n/** A type whose precision is optional: `timestamp` or `timestamp(3)`. */\nconst opt =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (precision?: number): DialectNativeType<Db> => ({\n db,\n type: precision !== undefined ? `${name}(${precision})` : name,\n });\n\n// =============================================================================\n// POSTGRESQL NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#postgresql\n// =============================================================================\n\nexport const PG = {\n // String types\n STRING: {\n TEXT: pg(\"text\"),\n VARCHAR: sized(\"pg\", \"varchar\"),\n CHAR: sized(\"pg\", \"char\"),\n CITEXT: pg(\"citext\"),\n UUID: pg(\"uuid\"),\n BIT: sized(\"pg\", \"bit\"),\n // By hand: a zero size is the bare type here, not `varbit(0)`.\n VARBIT: (n?: number): DialectNativeType<\"pg\"> => ({\n db: \"pg\",\n type: n ? `varbit(${n})` : \"varbit\",\n }),\n XML: pg(\"xml\"),\n INET: pg(\"inet\"),\n CIDR: pg(\"cidr\"),\n MACADDR: pg(\"macaddr\"),\n MACADDR8: pg(\"macaddr8\"),\n TSVECTOR: pg(\"tsvector\"),\n TSQUERY: pg(\"tsquery\"),\n },\n\n // Integer types\n INT: {\n SMALLINT: pg(\"smallint\"),\n INTEGER: pg(\"integer\"),\n OID: pg(\"oid\"),\n },\n\n // BigInt types\n BIGINT: {\n BIGINT: pg(\"bigint\"),\n },\n\n // Float types\n FLOAT: {\n REAL: pg(\"real\"),\n DOUBLE_PRECISION: pg(\"double precision\"),\n },\n\n // Boolean types\n BOOLEAN: {\n BOOLEAN: pg(\"boolean\"),\n },\n\n // DateTime types\n DATETIME: {\n TIMESTAMP: opt(\"pg\", \"timestamp\"),\n TIMESTAMPTZ: opt(\"pg\", \"timestamptz\"),\n DATE: pg(\"date\"),\n TIME: opt(\"pg\", \"time\"),\n TIMETZ: opt(\"pg\", \"timetz\"),\n },\n\n // JSON types\n JSON: {\n JSON: pg(\"json\"),\n JSONB: pg(\"jsonb\"),\n },\n\n // Binary types\n BLOB: {\n BYTEA: pg(\"bytea\"),\n },\n} as const;\n\n// =============================================================================\n// MYSQL NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#mysql\n// =============================================================================\n\nexport const MYSQL = {\n // String types\n STRING: {\n VARCHAR: sized(\"mysql\", \"VARCHAR\"),\n CHAR: sized(\"mysql\", \"CHAR\"),\n TEXT: mysql(\"TEXT\"),\n TINYTEXT: mysql(\"TINYTEXT\"),\n MEDIUMTEXT: mysql(\"MEDIUMTEXT\"),\n LONGTEXT: mysql(\"LONGTEXT\"),\n BIT: sized(\"mysql\", \"BIT\"),\n },\n\n // Integer types\n INT: {\n TINYINT: mysql(\"TINYINT\"),\n TINYINT_UNSIGNED: mysql(\"TINYINT UNSIGNED\"),\n SMALLINT: mysql(\"SMALLINT\"),\n SMALLINT_UNSIGNED: mysql(\"SMALLINT UNSIGNED\"),\n MEDIUMINT: mysql(\"MEDIUMINT\"),\n MEDIUMINT_UNSIGNED: mysql(\"MEDIUMINT UNSIGNED\"),\n INT: mysql(\"INT\"),\n INT_UNSIGNED: mysql(\"INT UNSIGNED\"),\n YEAR: mysql(\"YEAR\"),\n },\n\n // BigInt types\n BIGINT: {\n BIGINT: mysql(\"BIGINT\"),\n BIGINT_UNSIGNED: mysql(\"BIGINT UNSIGNED\"),\n },\n\n // Float types\n FLOAT: {\n FLOAT: mysql(\"FLOAT\"),\n DOUBLE: mysql(\"DOUBLE\"),\n },\n\n // Boolean types (MySQL uses TINYINT(1))\n BOOLEAN: {\n TINYINT: mysql(\"TINYINT(1)\"),\n },\n\n // DateTime types\n DATETIME: {\n DATETIME: opt(\"mysql\", \"DATETIME\"),\n TIMESTAMP: opt(\"mysql\", \"TIMESTAMP\"),\n DATE: mysql(\"DATE\"),\n TIME: opt(\"mysql\", \"TIME\"),\n },\n\n // JSON types\n JSON: {\n JSON: mysql(\"JSON\"),\n },\n\n // Binary types\n BLOB: {\n BLOB: mysql(\"BLOB\"),\n TINYBLOB: mysql(\"TINYBLOB\"),\n MEDIUMBLOB: mysql(\"MEDIUMBLOB\"),\n LONGBLOB: mysql(\"LONGBLOB\"),\n BINARY: sized(\"mysql\", \"BINARY\"),\n VARBINARY: sized(\"mysql\", \"VARBINARY\"),\n },\n} as const;\n\n// =============================================================================\n// SQLITE NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#sqlite\n// SQLite has limited type affinity, but we expose common mappings\n// =============================================================================\n\nexport const SQLITE = {\n // String types (all map to TEXT)\n STRING: {\n TEXT: sqlite(\"TEXT\"),\n },\n\n // Integer types\n INT: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // BigInt types (same as INTEGER in SQLite)\n BIGINT: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // Float types\n FLOAT: {\n REAL: sqlite(\"REAL\"),\n },\n\n // Boolean types (stored as INTEGER 0/1)\n BOOLEAN: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // DateTime types (stored as TEXT, REAL, or INTEGER)\n DATETIME: {\n TEXT: sqlite(\"TEXT\"),\n REAL: sqlite(\"REAL\"),\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // JSON types (stored as TEXT)\n JSON: {\n TEXT: sqlite(\"TEXT\"),\n },\n\n // Binary types\n BLOB: {\n BLOB: sqlite(\"BLOB\"),\n },\n} as const;\n"],"mappings":"yCAgDA,MAAa,EAA4C,CACvD,KACA,QACA,SACD,CAGY,mBACX,GAC8B,OAAQ,EAWxC,SAAgB,cACd,EACA,EACwB,CACpB,OAAgB,IAAA,GAIpB,OAHI,mBAAmB,EAAY,CAC1B,EAAY,KAAO,EAAU,EAAc,IAAA,GAE7C,EAAY,GAmDrB,MAAM,MAC6B,GACL,IACzB,CAAE,KAAI,OAAM,EAEX,EAAK,MAAM,KAAK,CAChB,EAAQ,MAAM,QAAQ,CACtB,EAAS,MAAM,SAAS,CAGxB,OACuB,EAAQ,IAClC,IAAsC,CAAE,KAAI,KAAM,GAAG,EAAK,GAAG,EAAE,GAAI,EAGhE,KACuB,EAAQ,IAClC,IAA+C,CAC9C,KACA,KAAM,IAAc,IAAA,GAAsC,EAA1B,GAAG,EAAK,GAAG,EAAU,GACtD,EAOU,EAAK,CAEhB,OAAQ,CACN,KAAM,EAAG,OAAO,CAChB,QAAS,MAAM,KAAM,UAAU,CAC/B,KAAM,MAAM,KAAM,OAAO,CACzB,OAAQ,EAAG,SAAS,CACpB,KAAM,EAAG,OA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,aAAc,EAAM,eAAe,CACnC,KAAM,EAAM,OAAO,CACpB,CAGD,OAAQ,CACN,OAAQ,EAAM,SAAS,CACvB,gBAAiB,EAAM,kBAAkB,CAC1C,CAGD,MAAO,CACL,MAAO,EAAM,QAAQ,CACrB,OAAQ,EAAM,SAAS,CACxB,CAGD,QAAS,CACP,QAAS,EAAM,aAAa,CAC7B,CAGD,SAAU,CACR,SAAU,IAAI,QAAS,WAAW,CAClC,UAAW,IAAI,QAAS,YAAY,CACpC,KAAM,EAAM,OAAO,CACnB,KAAM,IAAI,QAAS,OAAO,CAC3B,CAGD,KAAM,CACJ,KAAM,EAAM,OAAO,CACpB,CAGD,KAAM,CACJ,KAAM,EAAM,OAAO,CACnB,SAAU,EAAM,WAAW,CAC3B,WAAY,EAAM,aAAa,CAC/B,SAAU,EAAM,WAAW,CAC3B,OAAQ,MAAM,QAAS,SAAS,CAChC,UAAW,MAAM,QAAS,YAAY,CACvC,CACF,CAQY,EAAS,CAEpB,OAAQ,CACN,KAAM,EAAO,OAAO,CACrB,CAGD,IAAK,CACH,QAAS,EAAO,UAAU,CAC3B,CAGD,OAAQ,CACN,QAAS,EAAO,UAAU,CAC3B,CAGD,MAAO,CACL,KAAM,EAAO,OAAO,CACrB,CAGD,QAAS,CACP,QAAS,EAAO,UAAU,CAC3B,CAGD,SAAU,CACR,KAAM,EAAO,OAAO,CACpB,KAAM,EAAO,OAAO,CACpB,QAAS,EAAO,UAAU,CAC3B,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CACF"}
1
+ {"version":3,"file":"native-types-CQH05hcr.mjs","names":[],"sources":["../src/schema/scalars/native-types.ts"],"sourcesContent":["// Native Database Type Overrides\n// Provides typed constants for database-specific column types\n\n// =============================================================================\n// NATIVE TYPE INTERFACE\n// =============================================================================\n\nexport interface NativeType {\n readonly db: \"pg\" | \"mysql\" | \"sqlite\";\n readonly type: string;\n}\n\n/** The three dialects a native type can name. */\nexport type NativeDialect = NativeType[\"db\"];\n\n/**\n * A native type of ONE dialect — what every `PG` / `MYSQL` / `SQLITE` constant\n * is, parameterized ones included, so `PG.STRING.VARCHAR(80)` can fill a `pg`\n * entry of a {@link NativeTypeMap} and cannot fill a `mysql` one.\n */\nexport interface DialectNativeType<Dialect extends NativeDialect>\n extends NativeType {\n readonly db: Dialect;\n}\n\n/**\n * One scalar's native type on each dialect it names:\n * `s.string({ pg: PG.STRING.CITEXT, mysql: MYSQL.STRING.LONGTEXT })`.\n *\n * A dialect the map leaves out keeps that scalar's automatic column, exactly\n * as a tagged {@link NativeType} leaves every OTHER dialect's column alone.\n */\nexport interface NativeTypeMap {\n readonly pg?: DialectNativeType<\"pg\">;\n readonly mysql?: DialectNativeType<\"mysql\">;\n readonly sqlite?: DialectNativeType<\"sqlite\">;\n}\n\n/**\n * What a scalar factory's native-type argument declares: the tagged shorthand\n * (one dialect) or a {@link NativeTypeMap} (several). Scalars store the\n * declaration in the form it was written, so a schema document restates it\n * faithfully; every PHYSICAL reader asks {@link nativeTypeFor} instead of\n * inspecting the form.\n */\nexport type NativeTypeDeclaration = NativeType | NativeTypeMap;\n\n/** Every dialect, in the order a per-dialect question visits them. */\nexport const NATIVE_DIALECTS: readonly NativeDialect[] = [\n \"pg\",\n \"mysql\",\n \"sqlite\",\n];\n\n/** Whether a declaration is the tagged shorthand rather than a map. */\nexport const isTaggedNativeType = (\n declaration: NativeTypeDeclaration\n): declaration is NativeType => \"db\" in declaration;\n\n/**\n * The native type a declaration selects on one dialect, or `undefined` for the\n * dialect's automatic column.\n *\n * The ONE bound-dialect resolver. A migration driver, an adapter and the\n * identifier storage owner each know which dialect they speak and ask this;\n * none of them reads the declaration's form. A tagged shorthand for another\n * dialect is that dialect's automatic column, as it always was.\n */\nexport function nativeTypeFor(\n declaration: NativeTypeDeclaration | undefined,\n dialect: NativeDialect\n): NativeType | undefined {\n if (declaration === undefined) return undefined;\n if (isTaggedNativeType(declaration)) {\n return declaration.db === dialect ? declaration : undefined;\n }\n return declaration[dialect];\n}\n\n/**\n * A scalar factory's native-type argument: the tagged shorthand of dialect\n * `Db`, or the map `Given`, which the factory bounds by\n * {@link ExactNativeTypeMap}.\n *\n * The tagged shorthand keeps its historical shape: a `NativeType`, a union of\n * them, a generic `T extends NativeType`, a custom `type`, or one with unrelated\n * extra keys held in a variable all still compile, a fresh literal with an extra\n * key is still an excess-property error, and a value missing `db` or `type` is\n * still refused — except that a dialect key BESIDE its `db` is refused, since\n * that object would be two declarations at once.\n *\n * `Db` is inferred from a tagged value's `db` only so that TypeScript counts the\n * value as matched by this first member and keeps it out of `Given`: an\n * argument reaches `Given` only when it is not tagged, and `Given` is naked so\n * a union-typed argument (`NativeType | NativeTypeMap`) reaches it whole.\n */\nexport type NativeTypeArgument<Db extends NativeDialect, Given> =\n | (DialectNativeType<Db> & Partial<Record<NativeDialect, never>>)\n | Given;\n\n/**\n * The bound of a factory's `Given`: every key a dialect, each entry a native\n * type of its own key's dialect, and at least one dialect key. `{ type: \"text\" }`,\n * `{ postgres: … }`, `{}` and a `Date` are refused; an unknown key is refused\n * beside a real one, fresh and held in a variable. An argument that fails the\n * bound is refused against the bound itself, which is TypeScript's fallback.\n *\n * The exactness is a homomorphic mapped type, so it judges each member of a\n * union-typed map on its own. Measured traps (TS 7.0.2) that shaped it: a\n * generic CONSTRAINED to the weak `NativeTypeMap` falls back to that weak type\n * and admitted `{ foo: 1 }` and a `Date`; a parameter spelled `Given & NoInfer<…>`\n * makes TypeScript infer one member of a union argument; and a bound that is a\n * conditional type distributing over `Given` is a circular constraint (TS2313).\n * The at-least-one test is therefore not distributive: a union of maps with no\n * dialect key in COMMON is refused — annotate such a variable `NativeTypeMap`.\n */\nexport type ExactNativeTypeMap<Given> = {\n [Key in keyof Given]: Key extends NativeDialect\n ? DialectNativeType<Key>\n : never;\n} & ([keyof Given & NativeDialect] extends [never] ? never : unknown);\n\n// =============================================================================\n// CONSTANT BUILDERS\n// =============================================================================\n\n/** A fixed native type: its `db` and `type` keep their literal types. */\nconst fixed =\n <const Db extends NativeDialect>(db: Db) =>\n <const Type extends string>(type: Type) =>\n ({ db, type }) as const;\n\nconst pg = fixed(\"pg\");\nconst mysql = fixed(\"mysql\");\nconst sqlite = fixed(\"sqlite\");\n\n/** A type that takes one required size: `varchar(80)`. */\nconst sized =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (n: number): DialectNativeType<Db> => ({ db, type: `${name}(${n})` });\n\n/** A type whose precision is optional: `timestamp` or `timestamp(3)`. */\nconst opt =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (precision?: number): DialectNativeType<Db> => ({\n db,\n type: precision !== undefined ? `${name}(${precision})` : name,\n });\n\n// =============================================================================\n// POSTGRESQL NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#postgresql\n// =============================================================================\n\nexport const PG = {\n // String types\n STRING: {\n TEXT: pg(\"text\"),\n VARCHAR: sized(\"pg\", \"varchar\"),\n CHAR: sized(\"pg\", \"char\"),\n CITEXT: pg(\"citext\"),\n UUID: pg(\"uuid\"),\n BIT: sized(\"pg\", \"bit\"),\n // By hand: a zero size is the bare type here, not `varbit(0)`.\n VARBIT: (n?: number): DialectNativeType<\"pg\"> => ({\n db: \"pg\",\n type: n ? `varbit(${n})` : \"varbit\",\n }),\n XML: pg(\"xml\"),\n INET: pg(\"inet\"),\n CIDR: pg(\"cidr\"),\n MACADDR: pg(\"macaddr\"),\n MACADDR8: pg(\"macaddr8\"),\n TSVECTOR: pg(\"tsvector\"),\n TSQUERY: pg(\"tsquery\"),\n },\n\n // Integer types\n INT: {\n SMALLINT: pg(\"smallint\"),\n INTEGER: pg(\"integer\"),\n OID: pg(\"oid\"),\n },\n\n // BigInt types\n BIGINT: {\n BIGINT: pg(\"bigint\"),\n },\n\n // Float types\n FLOAT: {\n REAL: pg(\"real\"),\n DOUBLE_PRECISION: pg(\"double precision\"),\n },\n\n // Boolean types\n BOOLEAN: {\n BOOLEAN: pg(\"boolean\"),\n },\n\n // DateTime types\n DATETIME: {\n TIMESTAMP: opt(\"pg\", \"timestamp\"),\n TIMESTAMPTZ: opt(\"pg\", \"timestamptz\"),\n DATE: pg(\"date\"),\n TIME: opt(\"pg\", \"time\"),\n TIMETZ: opt(\"pg\", \"timetz\"),\n },\n\n // JSON types\n JSON: {\n JSON: pg(\"json\"),\n JSONB: pg(\"jsonb\"),\n },\n\n // Binary types\n BLOB: {\n BYTEA: pg(\"bytea\"),\n },\n} as const;\n\n// =============================================================================\n// MYSQL NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#mysql\n// =============================================================================\n\nexport const MYSQL = {\n // String types\n STRING: {\n VARCHAR: sized(\"mysql\", \"VARCHAR\"),\n CHAR: sized(\"mysql\", \"CHAR\"),\n TEXT: mysql(\"TEXT\"),\n TINYTEXT: mysql(\"TINYTEXT\"),\n MEDIUMTEXT: mysql(\"MEDIUMTEXT\"),\n LONGTEXT: mysql(\"LONGTEXT\"),\n BIT: sized(\"mysql\", \"BIT\"),\n },\n\n // Integer types\n INT: {\n TINYINT: mysql(\"TINYINT\"),\n TINYINT_UNSIGNED: mysql(\"TINYINT UNSIGNED\"),\n SMALLINT: mysql(\"SMALLINT\"),\n SMALLINT_UNSIGNED: mysql(\"SMALLINT UNSIGNED\"),\n MEDIUMINT: mysql(\"MEDIUMINT\"),\n MEDIUMINT_UNSIGNED: mysql(\"MEDIUMINT UNSIGNED\"),\n INT: mysql(\"INT\"),\n INT_UNSIGNED: mysql(\"INT UNSIGNED\"),\n YEAR: mysql(\"YEAR\"),\n },\n\n // BigInt types\n BIGINT: {\n BIGINT: mysql(\"BIGINT\"),\n BIGINT_UNSIGNED: mysql(\"BIGINT UNSIGNED\"),\n },\n\n // Float types\n FLOAT: {\n FLOAT: mysql(\"FLOAT\"),\n DOUBLE: mysql(\"DOUBLE\"),\n },\n\n // Boolean types (MySQL uses TINYINT(1))\n BOOLEAN: {\n TINYINT: mysql(\"TINYINT(1)\"),\n },\n\n // DateTime types\n DATETIME: {\n DATETIME: opt(\"mysql\", \"DATETIME\"),\n TIMESTAMP: opt(\"mysql\", \"TIMESTAMP\"),\n DATE: mysql(\"DATE\"),\n TIME: opt(\"mysql\", \"TIME\"),\n },\n\n // JSON types\n JSON: {\n JSON: mysql(\"JSON\"),\n },\n\n // Binary types\n BLOB: {\n BLOB: mysql(\"BLOB\"),\n TINYBLOB: mysql(\"TINYBLOB\"),\n MEDIUMBLOB: mysql(\"MEDIUMBLOB\"),\n LONGBLOB: mysql(\"LONGBLOB\"),\n BINARY: sized(\"mysql\", \"BINARY\"),\n VARBINARY: sized(\"mysql\", \"VARBINARY\"),\n },\n} as const;\n\n// =============================================================================\n// SQLITE NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#sqlite\n// SQLite has limited type affinity, but we expose common mappings\n// =============================================================================\n\nexport const SQLITE = {\n // String types (all map to TEXT)\n STRING: {\n TEXT: sqlite(\"TEXT\"),\n },\n\n // Integer types\n INT: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // BigInt types (same as INTEGER in SQLite)\n BIGINT: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // Float types\n FLOAT: {\n REAL: sqlite(\"REAL\"),\n },\n\n // Boolean types (stored as INTEGER 0/1)\n BOOLEAN: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // DateTime types (stored as TEXT, REAL, or INTEGER)\n DATETIME: {\n TEXT: sqlite(\"TEXT\"),\n REAL: sqlite(\"REAL\"),\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // JSON types (stored as TEXT)\n JSON: {\n TEXT: sqlite(\"TEXT\"),\n },\n\n // Binary types\n BLOB: {\n BLOB: sqlite(\"BLOB\"),\n },\n} as const;\n"],"mappings":"yCAgDA,MAAa,EAA4C,CACvD,KACA,QACA,SACD,CAGY,mBACX,GAC8B,OAAQ,EAWxC,SAAgB,cACd,EACA,EACwB,CACpB,OAAgB,IAAA,GA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3B,CAGD,OAAQ,CACN,QAAS,EAAO,UAAU,CAC3B,CAGD,MAAO,CACL,KAAM,EAAO,OAAO,CACrB,CAGD,QAAS,CACP,QAAS,EAAO,UAAU,CAC3B,CAGD,SAAU,CACR,KAAM,EAAO,OAAO,CACpB,KAAM,EAAO,OAAO,CACpB,QAAS,EAAO,UAAU,CAC3B,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CACF"}
@@ -1,4 +1,4 @@
1
- import { A as Schema, An as BatchQuery, At as DriverConfig, Dn as BatchTransactionOptions, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-Ci8b13Lm.mjs";
1
+ import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Fn as QueryExecutionContext, Ft as VibORMClient, In as QueryResult, Mn as BatchQuery, Nn as CommittedBatchNotification, Pt as NoExtraDriverConfigKeys, jn as TransactionOptionSupport, kn as BatchTransactionOptions, s as DatabaseAdapter, u as Driver } from "./index-CsO6vG2h.mjs";
2
2
  import { NeonQueryFunction } from "@neondatabase/serverless";
3
3
 
4
4
  //#region src/drivers/neon-http/index.d.ts
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./normalized-result-VunNi4ID.mjs";import{h as n}from"./error-mapping-Zett_Pnt.mjs";import{p as r,r as i}from"./validation-DN1N2OdK.mjs";import{n as a}from"./client-DHf2ZfRe.mjs";import{c as o,d as s,t as c}from"./driver-aqfbJdZC.mjs";import{t as l}from"./postgres-result-D4_yZqO8.mjs";import{t as u}from"./postgres-adapter-CnZjhvG1.mjs";const d={databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0};function malformedNeonResult(e,t){let n=e.operation??`execute`;return new r(`Driver "neon-http" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`neon-http`,...e,operation:n}})}function assertNeonFullResult(e,n){if(!(t(e)&&Array.isArray(e.fields))||typeof e.command!=`string`||!Object.hasOwn(e,`rowCount`)||e.rowCount!==null&&(typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0)||!Array.isArray(e.rows)||!e.rows.every(t)||e.rowAsArray!==!1)throw malformedNeonResult(n,`expected fullResults object with object rows and explicit rowCount`)}var NeonHTTPDriver=class extends c{maxBindParametersPerStatement=65535;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;queryTypes;constructor(e={}){super(`postgresql`,`neon-http`);let t=s(e);this.driverOptions=e,u(this,t,e)}async initClient(){let{neon:e,types:t}=await import(`@neondatabase/serverless`);if(!this.driverOptions.databaseUrl)throw new i(`Neon HTTP driver requires a databaseUrl`,{meta:{driver:this.driverName}});let identityParser=e=>e,getTypeParser=((e,n)=>[1082,1114,1184,1115,1182,1185].includes(e)&&n!==`binary`?identityParser:t.getTypeParser(e,n));return this.queryTypes={getTypeParser},e(this.driverOptions.databaseUrl,{fetchOptions:this.driverOptions.options?.fetchOptions,authToken:this.driverOptions.options?.authToken,fullResults:!0,arrayMode:!1})}async closeClient(e){}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeQuery(e,t,n,r,i){let a=r??{operation:i},o=await e.query(t,n,{arrayMode:!1,fullResults:!0,types:this.queryTypes});return this.parseResult(o,a)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n??[],r,`executeRaw`)}transactionOptionSupport(){return{isolationLevel:`provider`,timeout:!1,timeoutReason:`Neon HTTP runs a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`Neon HTTP submits the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(n(this.driverName))}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=await e.transaction(t.map(t=>{let n=t.context??a;try{return e.query(t.sql,t.params??[],{types:this.queryTypes})}catch(e){throw this.normalizeStatementFailure(e,t.sql,this.getBatchDiagnosticParameters(t),n,!0)}}),{isolationLevel:i?.isolationLevel,arrayMode:!1,fullResults:!0});if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedNeonResult(a,`expected ${t.length} statement results but received ${e}`)}return o.map((e,n)=>this.parseResult(e,t[n]?.context??a))}parseResult(e,t){let n=t.operation??`execute`;return assertNeonFullResult(e,t),{rows:e.rows,rowCount:l(e.rowCount,e.command,e.rows,{provider:`neon-http`,operation:n,model:t.model,correlationId:t.correlationId})}}};function createClient(e){o(e,`neon-http`,d);let{databaseUrl:t,options:n,pgvector:r,postgis:i}=e,c=s(e);return a(e,new NeonHTTPDriver({databaseUrl:t,options:n,pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:c}))}export{NeonHTTPDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./normalized-result-23DWxZVY.mjs";import{h as n}from"./error-mapping-D--MVRCY.mjs";import{d as r,t as i}from"./query-CTna5P9o.mjs";import{n as a}from"./client-Yqn0LqmI.mjs";import{c as o,d as s,t as c}from"./driver-CK_IKqDa.mjs";import{t as l}from"./postgres-result-D94PyZ78.mjs";import{t as u}from"./postgres-adapter-CYZAL2uo.mjs";const d={databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0};function malformedNeonResult(e,t){let n=e.operation??`execute`;return new r(`Driver "neon-http" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`neon-http`,...e,operation:n}})}function assertNeonFullResult(e,n){if(!(t(e)&&Array.isArray(e.fields))||typeof e.command!=`string`||!Object.hasOwn(e,`rowCount`)||e.rowCount!==null&&(typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0)||!Array.isArray(e.rows)||!e.rows.every(t)||e.rowAsArray!==!1)throw malformedNeonResult(n,`expected fullResults object with object rows and explicit rowCount`)}var NeonHTTPDriver=class extends c{maxBindParametersPerStatement=65535;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;queryTypes;constructor(e={}){super(`postgresql`,`neon-http`);let t=s(e);this.driverOptions=e,u(this,t,e)}async initClient(){let{neon:e,types:t}=await import(`@neondatabase/serverless`);if(!this.driverOptions.databaseUrl)throw new i(`Neon HTTP driver requires a databaseUrl`,{meta:{driver:this.driverName}});let identityParser=e=>e,getTypeParser=((e,n)=>[1082,1114,1184,1115,1182,1185].includes(e)&&n!==`binary`?identityParser:t.getTypeParser(e,n));return this.queryTypes={getTypeParser},e(this.driverOptions.databaseUrl,{fetchOptions:this.driverOptions.options?.fetchOptions,authToken:this.driverOptions.options?.authToken,fullResults:!0,arrayMode:!1})}async closeClient(e){}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeQuery(e,t,n,r,i){let a=r??{operation:i},o=await e.query(t,n,{arrayMode:!1,fullResults:!0,types:this.queryTypes});return this.parseResult(o,a)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n??[],r,`executeRaw`)}transactionOptionSupport(){return{isolationLevel:`provider`,timeout:!1,timeoutReason:`Neon HTTP runs a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`Neon HTTP submits the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(n(this.driverName))}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=await e.transaction(t.map(t=>{let n=t.context??a;try{return e.query(t.sql,t.params??[],{types:this.queryTypes})}catch(e){throw this.normalizeStatementFailure(e,t.sql,this.getBatchDiagnosticParameters(t),n,!0)}}),{isolationLevel:i?.isolationLevel,arrayMode:!1,fullResults:!0});if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedNeonResult(a,`expected ${t.length} statement results but received ${e}`)}return o.map((e,n)=>this.parseResult(e,t[n]?.context??a))}parseResult(e,t){let n=t.operation??`execute`;return assertNeonFullResult(e,t),{rows:e.rows,rowCount:l(e.rowCount,e.command,e.rows,{provider:`neon-http`,operation:n,model:t.model,correlationId:t.correlationId})}}};function createClient(e){o(e,`neon-http`,d);let{databaseUrl:t,options:n,pgvector:r,postgis:i}=e,c=s(e);return a(e,new NeonHTTPDriver({databaseUrl:t,options:n,pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:c}))}export{NeonHTTPDriver,createClient};
2
2
  //# sourceMappingURL=neon-http.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"neon-http.mjs","names":[],"sources":["../src/drivers/neon-http/index.ts"],"sourcesContent":["/**\n * Neon HTTP Driver\n *\n * Driver implementation for @neondatabase/serverless - Neon's HTTP-based PostgreSQL driver.\n *\n * Note: Neon's HTTP API uses non-interactive transactions. This means:\n * - Batch transactions ($transaction([...])) work via executeBatch\n * - Callback transactions ($transaction(async (tx) => {...})) are NOT supported\n * because Neon HTTP requires all queries to be submitted at once\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, QueryError } from \"@errors\";\nimport type {\n CustomTypesConfig,\n NeonQueryFunction,\n} from \"@neondatabase/serverless\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { isNormalizedResultRow } from \"../normalized-result\";\nimport {\n type BatchTransactionOptions,\n normalizePostgresRowCount,\n resolveNamespaceOption,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface NeonHTTPDriverOptions {\n databaseUrl?: string;\n options?: {\n fetchOptions?: RequestInit;\n authToken?: string | (() => Promise<string> | string);\n };\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. Set 256 for PlanetScale Neki, which refuses more. Absent: unbounded. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type NeonHTTPClientConfig<C extends DriverConfig> =\n NeonHTTPDriverOptions & C;\n\nconst NEON_HTTP_CONFIG_KEYS: Record<keyof NeonHTTPDriverOptions, true> = {\n databaseUrl: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n namespace: true,\n};\n\n// ============================================================\n// TYPE DECLARATIONS\n// ============================================================\n\n/**\n * NeonQuery is the main query function returned by neon().\n * Configured with arrayMode=false (object rows) and fullResults=true (includes rowCount).\n */\ntype NeonQuery = NeonQueryFunction<false, true>;\n\ninterface NeonFullResult<T> {\n fields: unknown[];\n command: string;\n rowCount: number | null;\n rows: T[];\n rowAsArray: false;\n}\n\nfunction malformedNeonResult(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"neon-http\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"neon-http\", ...context, operation } }\n );\n}\n\nfunction assertNeonFullResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is NeonFullResult<T> {\n if (\n !(isNormalizedResultRow(result) && Array.isArray(result.fields)) ||\n typeof result.command !== \"string\" ||\n !Object.hasOwn(result, \"rowCount\") ||\n (result.rowCount !== null &&\n (typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0)) ||\n !Array.isArray(result.rows) ||\n !result.rows.every(isNormalizedResultRow) ||\n result.rowAsArray !== false\n ) {\n throw malformedNeonResult(\n context,\n \"expected fullResults object with object rows and explicit rowCount\"\n );\n }\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class NeonHTTPDriver extends Driver<NeonQuery, NeonQuery> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n // Neon HTTP only supports non-interactive (batch) transactions\n // Callback-style transactions are not supported\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n\n // Hosted rollback, durable visibility and malformed post-commit metadata\n // witnesses qualify this notification before driver result validation.\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: NeonHTTPDriverOptions;\n private queryTypes: CustomTypesConfig | undefined;\n\n constructor(options: NeonHTTPDriverOptions = {}) {\n super(\"postgresql\", \"neon-http\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n\n installPostgresAdapter(this, namespace, options);\n }\n\n protected async initClient(): Promise<NeonQuery> {\n const { neon, types } = await import(\"@neondatabase/serverless\");\n\n if (!this.driverOptions.databaseUrl) {\n throw new ClientInitializationError(\n \"Neon HTTP driver requires a databaseUrl\",\n { meta: { driver: this.driverName } }\n );\n }\n\n // DATE (1082) / TIMESTAMP WITHOUT TIME ZONE (1114): the default parsers\n // build process-local Dates, shifting the stored value by the process\n // timezone. Return raw strings — the shared result parser builds UTC\n // Dates from them, matching every other driver.\n const identityParser = (value: string) => value;\n // pg-types declares getTypeParser with per-format overloads that a single\n // wrapper function can't express — the cast is unavoidable here\n const getTypeParser = ((oid: number, format?: string) => {\n if (\n [1082, 1114, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return types.getTypeParser(oid as never, format as never);\n }) as typeof types.getTypeParser;\n this.queryTypes = { getTypeParser };\n\n // Always use arrayMode=false (object rows) and fullResults=true (includes rowCount)\n const client = neon(this.driverOptions.databaseUrl, {\n fetchOptions: this.driverOptions.options?.fetchOptions,\n authToken: this.driverOptions.options?.authToken,\n fullResults: true,\n arrayMode: false,\n });\n\n return client;\n }\n\n protected async closeClient(_client: NeonQuery): Promise<void> {\n // HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(client, sql, params, context, \"execute\");\n }\n\n private async executeQuery<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext | undefined,\n fallbackOperation: string\n ): Promise<QueryResult<T>> {\n const executionContext = context ?? { operation: fallbackOperation };\n const result = await client.query(sql, params, {\n arrayMode: false,\n fullResults: true,\n types: this.queryTypes,\n });\n\n return this.parseResult<T>(result, executionContext);\n }\n\n protected async executeRaw<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(\n client,\n sql,\n params ?? [],\n context,\n \"executeRaw\"\n );\n }\n\n /**\n * Neon HTTP sends the whole batch as one request through `client.transaction`\n * and offers no callback transaction. The provider opens and closes that\n * transaction server-side in a single round trip. The SDK receives the\n * requested isolation level; timeout/maxWait need an interactive body or\n * acquired connection, which this HTTP transport does not have.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"provider\",\n timeout: false,\n timeoutReason:\n \"Neon HTTP runs a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Neon HTTP submits the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: NeonQuery,\n _fn: (tx: NeonQuery) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using Neon's transaction() function.\n * This provides atomic batch execution with full PostgreSQL transaction semantics.\n */\n protected async executeBatch<T>(\n client: NeonQuery,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification,\n options?: BatchTransactionOptions\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n // Query promises retain their own parser options in the public SDK API.\n const results: unknown = await client.transaction(\n queries.map((query) => {\n const statementContext = query.context ?? batchContext;\n try {\n return client.query(query.sql, query.params ?? [], {\n types: this.queryTypes,\n });\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }),\n {\n isolationLevel: options?.isolationLevel,\n arrayMode: false,\n fullResults: true,\n }\n );\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedNeonResult(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n return results.map((result, index) =>\n this.parseResult<T>(result, queries[index]?.context ?? batchContext)\n );\n }\n\n /**\n * Parse Neon result into QueryResult format.\n */\n private parseResult<T>(\n result: unknown,\n context: QueryExecutionContext\n ): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertNeonFullResult<T>(result, context);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n {\n provider: \"neon-http\",\n operation,\n model: context.model,\n correlationId: context.correlationId,\n }\n ),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: NeonHTTPClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, NeonHTTPDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: NeonHTTPDriver }\n >]: LinkedClientConfig<C & { driver: NeonHTTPDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"neon-http\", NEON_HTTP_CONFIG_KEYS);\n const { databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new NeonHTTPDriver({\n databaseUrl,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, NeonHTTPDriver>(config, driver);\n}\n"],"mappings":"6YAiEA,MAAM,EAAmE,CACvE,YAAa,GACb,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,GACtB,sBAAuB,GACvB,UAAW,GACZ,CAoBD,SAAS,oBACP,EACA,EACY,CACZ,IAAM,EAAY,EAAQ,WAAa,UACvC,OAAO,IAAI,EACT,yEAAyE,EAAU,KAAK,EAAO,GAC/F,CAAE,KAAM,CAAE,OAAQ,YAAa,GAAG,EAAS,YAAW,CAAE,CACzD,CAGH,SAAS,qBACP,EACA,EACqC,CACrC,GACE,EAAE,EAAsB,EAAO,EAAI,MAAM,QAAQ,EAAO,OAAO,GAC/D,OAAO,EAAO,SAAY,UAC1B,CAAC,OAAO,OAAO,EAAQ,WAAW,EACjC,EAAO,WAAa,OAClB,OAAO,EAAO,UAAa,UAC1B,CAAC,OAAO,SAAS,EAAO,SAAS,EACjC,CAAC,OAAO,cAAc,EAAO,SAAS,EACtC,EAAO,SAAW,IACtB,CAAC,MAAM,QAAQ,EAAO,KAAK,EAC3B,CAAC,EAAO,KAAK,MAAM,EAAsB,EACzC,EAAO,aAAe,GAEtB,MAAM,oBACJ,EACA,qEACD,CAQL,IAAa,eAAb,cAAoC,CAA6B,CAE/D,8BAA6D,MAI7D,qBAAgC,GAChC,cAAyB,GAIzB,iCAA4C,GAE5C,cACA,WAEA,YAAY,EAAiC,EAAE,CAAE,CAC/C,MAAM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http/index.ts"],"sourcesContent":["/**\n * Neon HTTP Driver\n *\n * Driver implementation for @neondatabase/serverless - Neon's HTTP-based PostgreSQL driver.\n *\n * Note: Neon's HTTP API uses non-interactive transactions. This means:\n * - Batch transactions ($transaction([...])) work via executeBatch\n * - Callback transactions ($transaction(async (tx) => {...})) are NOT supported\n * because Neon HTTP requires all queries to be submitted at once\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, QueryError } from \"@errors\";\nimport type {\n CustomTypesConfig,\n NeonQueryFunction,\n} from \"@neondatabase/serverless\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { isNormalizedResultRow } from \"../normalized-result\";\nimport {\n type BatchTransactionOptions,\n normalizePostgresRowCount,\n resolveNamespaceOption,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface NeonHTTPDriverOptions {\n databaseUrl?: string;\n options?: {\n fetchOptions?: RequestInit;\n authToken?: string | (() => Promise<string> | string);\n };\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. Set 256 for PlanetScale Neki, which refuses more. Absent: unbounded. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type NeonHTTPClientConfig<C extends DriverConfig> =\n NeonHTTPDriverOptions & C;\n\nconst NEON_HTTP_CONFIG_KEYS: Record<keyof NeonHTTPDriverOptions, true> = {\n databaseUrl: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n namespace: true,\n};\n\n// ============================================================\n// TYPE DECLARATIONS\n// ============================================================\n\n/**\n * NeonQuery is the main query function returned by neon().\n * Configured with arrayMode=false (object rows) and fullResults=true (includes rowCount).\n */\ntype NeonQuery = NeonQueryFunction<false, true>;\n\ninterface NeonFullResult<T> {\n fields: unknown[];\n command: string;\n rowCount: number | null;\n rows: T[];\n rowAsArray: false;\n}\n\nfunction malformedNeonResult(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"neon-http\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"neon-http\", ...context, operation } }\n );\n}\n\nfunction assertNeonFullResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is NeonFullResult<T> {\n if (\n !(isNormalizedResultRow(result) && Array.isArray(result.fields)) ||\n typeof result.command !== \"string\" ||\n !Object.hasOwn(result, \"rowCount\") ||\n (result.rowCount !== null &&\n (typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0)) ||\n !Array.isArray(result.rows) ||\n !result.rows.every(isNormalizedResultRow) ||\n result.rowAsArray !== false\n ) {\n throw malformedNeonResult(\n context,\n \"expected fullResults object with object rows and explicit rowCount\"\n );\n }\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class NeonHTTPDriver extends Driver<NeonQuery, NeonQuery> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n // Neon HTTP only supports non-interactive (batch) transactions\n // Callback-style transactions are not supported\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n\n // Hosted rollback, durable visibility and malformed post-commit metadata\n // witnesses qualify this notification before driver result validation.\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: NeonHTTPDriverOptions;\n private queryTypes: CustomTypesConfig | undefined;\n\n constructor(options: NeonHTTPDriverOptions = {}) {\n super(\"postgresql\", \"neon-http\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n\n installPostgresAdapter(this, namespace, options);\n }\n\n protected async initClient(): Promise<NeonQuery> {\n const { neon, types } = await import(\"@neondatabase/serverless\");\n\n if (!this.driverOptions.databaseUrl) {\n throw new ClientInitializationError(\n \"Neon HTTP driver requires a databaseUrl\",\n { meta: { driver: this.driverName } }\n );\n }\n\n // DATE (1082) / TIMESTAMP WITHOUT TIME ZONE (1114): the default parsers\n // build process-local Dates, shifting the stored value by the process\n // timezone. Return raw strings — the shared result parser builds UTC\n // Dates from them, matching every other driver.\n const identityParser = (value: string) => value;\n // pg-types declares getTypeParser with per-format overloads that a single\n // wrapper function can't express — the cast is unavoidable here\n const getTypeParser = ((oid: number, format?: string) => {\n if (\n [1082, 1114, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return types.getTypeParser(oid as never, format as never);\n }) as typeof types.getTypeParser;\n this.queryTypes = { getTypeParser };\n\n // Always use arrayMode=false (object rows) and fullResults=true (includes rowCount)\n const client = neon(this.driverOptions.databaseUrl, {\n fetchOptions: this.driverOptions.options?.fetchOptions,\n authToken: this.driverOptions.options?.authToken,\n fullResults: true,\n arrayMode: false,\n });\n\n return client;\n }\n\n protected async closeClient(_client: NeonQuery): Promise<void> {\n // HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(client, sql, params, context, \"execute\");\n }\n\n private async executeQuery<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext | undefined,\n fallbackOperation: string\n ): Promise<QueryResult<T>> {\n const executionContext = context ?? { operation: fallbackOperation };\n const result = await client.query(sql, params, {\n arrayMode: false,\n fullResults: true,\n types: this.queryTypes,\n });\n\n return this.parseResult<T>(result, executionContext);\n }\n\n protected async executeRaw<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(\n client,\n sql,\n params ?? [],\n context,\n \"executeRaw\"\n );\n }\n\n /**\n * Neon HTTP sends the whole batch as one request through `client.transaction`\n * and offers no callback transaction. The provider opens and closes that\n * transaction server-side in a single round trip. The SDK receives the\n * requested isolation level; timeout/maxWait need an interactive body or\n * acquired connection, which this HTTP transport does not have.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"provider\",\n timeout: false,\n timeoutReason:\n \"Neon HTTP runs a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Neon HTTP submits the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: NeonQuery,\n _fn: (tx: NeonQuery) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using Neon's transaction() function.\n * This provides atomic batch execution with full PostgreSQL transaction semantics.\n */\n protected async executeBatch<T>(\n client: NeonQuery,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification,\n options?: BatchTransactionOptions\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n // Query promises retain their own parser options in the public SDK API.\n const results: unknown = await client.transaction(\n queries.map((query) => {\n const statementContext = query.context ?? batchContext;\n try {\n return client.query(query.sql, query.params ?? [], {\n types: this.queryTypes,\n });\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }),\n {\n isolationLevel: options?.isolationLevel,\n arrayMode: false,\n fullResults: true,\n }\n );\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedNeonResult(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n return results.map((result, index) =>\n this.parseResult<T>(result, queries[index]?.context ?? batchContext)\n );\n }\n\n /**\n * Parse Neon result into QueryResult format.\n */\n private parseResult<T>(\n result: unknown,\n context: QueryExecutionContext\n ): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertNeonFullResult<T>(result, context);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n {\n provider: \"neon-http\",\n operation,\n model: context.model,\n correlationId: context.correlationId,\n }\n ),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: NeonHTTPClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, NeonHTTPDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: NeonHTTPDriver }\n >]: LinkedClientConfig<C & { driver: NeonHTTPDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"neon-http\", NEON_HTTP_CONFIG_KEYS);\n const { databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new NeonHTTPDriver({\n databaseUrl,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, NeonHTTPDriver>(config, driver);\n}\n"],"mappings":"wYAiEA,MAAM,EAAmE,CACvE,YAAa,GACb,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,GACtB,sBAAuB,GACvB,UAAW,GACZ,CAoBD,SAAS,oBACP,EACA,EACY,CACZ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Q,CAAG,EAAQ,OAAS,EACpE,MAAM,oBACJ,EACA,YAAY,EAAQ,OAAO,kCAAkC,IAC9D,CAGH,OAAO,EAAQ,KAAK,EAAQ,IAC1B,KAAK,YAAe,EAAQ,EAAQ,IAAQ,SAAW,EAAa,CACrE,CAMH,YACE,EACA,EACgB,CAChB,IAAM,EAAY,EAAQ,WAAa,UAEvC,OADA,qBAAwB,EAAQ,EAAQ,CACjC,CACL,KAAM,EAAO,KACb,SAAU,EACR,EAAO,SACP,EAAO,QACP,EAAO,KACP,CACE,SAAU,YACV,YACA,MAAO,EAAQ,MACf,cAAe,EAAQ,cACxB,CACF,CACF,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,YAAa,EAAsB,CACzE,GAAM,CAAE,cAAa,UAAS,WAAU,WAAY,EAC9C,EAAY,EAAuB,EAAO,CAYhD,OAAO,EAAmD,EAV3C,IAAI,eAAe,CAChC,cACA,UACA,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC9B,YACD,CAAC,CAEuE"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{r as t}from"./value-guards-CK9guf2Z.mjs";import{n}from"./base-wlv81COV.mjs";import{d as r}from"./query-CTna5P9o.mjs";import{t as i}from"./sql-DGtEeP8z.mjs";const a=typeof Symbol.asyncDispose==`symbol`?Symbol.asyncDispose:void 0,o=Symbol(`viborm.verbatimBatchQuery`);function markVerbatimBatchQuery(e){return Object.defineProperty(e,o,{configurable:!1,enumerable:!1,value:!0,writable:!1}),e}function isVerbatimBatchQuery(e){return Reflect.get(e,o)===!0}const s=new WeakMap;function registerPreparedStatement(e,t){s.set(e,t)}function transferPreparedStatement(e,t){let n=s.get(e);return n!==void 0&&s.set(t,n),t}function snapshotPreparedStatement(e,t,n){let r=s.get(e);return r!==void 0&&s.set(t,new i([...r.strings],[...n])),t}function readPreparedStatement(e){return s.get(e)}const c=/^(?:0|[1-9]\d*)$/;function captureBuiltinPrototype(e){let t=[];for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&t.push({descriptor:r,key:n})}return Object.freeze(t)}const l=captureBuiltinPrototype(Object.prototype),u=captureBuiltinPrototype(Array.prototype);function isArrayIndex(e){if(typeof e!=`string`||!c.test(e))return!1;let t=Number(e);return t<=4294967294&&String(t)===e}function functionSource(e){if(typeof e==`function`)try{return Function.prototype.toString.call(e)}catch{return}}function sameInertRecord(e,t){if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return Object.is(e,t);try{if(Object.getPrototypeOf(e)!==null||Object.getPrototypeOf(t)!==null)return!1;let n=Reflect.ownKeys(e),r=Reflect.ownKeys(t);if(n.length!==r.length)return!1;for(let i=0;i<r.length;i+=1){let a=n[i],o=r[i];if(a!==o||o===void 0)return!1;let s=Object.getOwnPropertyDescriptor(e,o),c=Object.getOwnPropertyDescriptor(t,o);if(s===void 0||c===void 0||!(`value`in s)||!(`value`in c)||s.configurable!==c.configurable||s.enumerable!==c.enumerable||s.writable!==c.writable||!Object.is(s.value,c.value))return!1}return!0}catch{return!1}}function sameBuiltinDescriptor(e,t){if(e.configurable!==t.configurable||e.enumerable!==t.enumerable||`value`in e!=`value`in t)return!1;if(`value`in e&&`value`in t){if(e.writable!==t.writable)return!1;let n=functionSource(t.value);return n===void 0?sameInertRecord(e.value,t.value):functionSource(e.value)===n}return functionSource(e.get)===functionSource(t.get)&&functionSource(e.set)===functionSource(t.set)}function hasBuiltinPrototypeShape(e,t){try{let n=Reflect.ownKeys(e);if(n.length!==t.length)return!1;for(let r=0;r<t.length;r+=1){let i=t[r];if(i===void 0||n[r]!==i.key)return!1;let a=Object.getOwnPropertyDescriptor(e,i.key);if(a===void 0||!sameBuiltinDescriptor(a,i.descriptor))return!1}return!0}catch{return!1}}function isObjectPrototype(e){try{return Object.getPrototypeOf(e)===null&&hasBuiltinPrototypeShape(e,l)}catch{return!1}}function isArrayPrototype(e){try{let t=Object.getPrototypeOf(e);return t!==null&&isObjectPrototype(t)&&hasBuiltinPrototypeShape(e,u)}catch{return!1}}function rawParameterNodeShape(e){let t=!1;try{t=Array.isArray(e);let n=Object.getPrototypeOf(e);if(t&&n!==null&&!isArrayPrototype(n)||!t&&n!==null&&!isObjectPrototype(n))return{kind:t?`unsupported-array`:`opaque`};let r=[],i=[];for(let n of Reflect.ownKeys(e)){let a=Object.getOwnPropertyDescriptor(e,n);if(a!==void 0&&(i.push({descriptor:a,key:n}),t?isArrayIndex(n):a.enumerable&&typeof n==`string`)){if(!(`value`in a))return{kind:t?`unsupported-array`:`opaque`};r.push({descriptor:a,key:n,value:a.value})}}let a=i.find(e=>e.key===`toJSON`);return a&&(!(`value`in a.descriptor)||typeof a.descriptor.value==`function`)?{kind:t?`unsupported-array`:`opaque`}:{kind:`node`,shape:{edges:r,isArray:t,properties:i,prototype:n}}}catch{return{kind:t?`unsupported-array`:`opaque`}}}function rawDateTime(e,n,r){if(!t(e))return;let i=Date.prototype.getTime.call(e);if(Number.isNaN(i))throw r(n);return i}function analyzeRawParameterGraph(e,t){let n=new WeakMap,r=new WeakMap,i=[],a=Array(e.length),discover=(e,a)=>{let o=rawDateTime(e,a,t.invalidDate);if(o!==void 0&&typeof e==`object`&&e){r.set(e,o);return}if(typeof e!=`object`||!e)return;let s=n.get(e);if(s)return s;let c=rawParameterNodeShape(e);if(c.kind===`unsupported-array`)throw t.unsupportedArray(a);if(c.kind===`opaque`)return;let l={...c.shape,source:e};return n.set(e,l),i.push(l),l};for(let n=0;n<e.length;n++){if(!Object.hasOwn(e,n))continue;let o=e[n];a[n]=o;let s=rawDateTime(o,n,t.invalidDate);if(s!==void 0&&typeof o==`object`&&o){r.set(o,s);continue}let c=discover(o,n);if(!c)continue;let l=[c],u=0;for(;u<l.length;){let e=l[u];if(u+=1,e)for(let t of e.edges){let e=i.length,r=discover(t.value,n);r&&i.length>e&&l.push(r)}}}return{dateTimes:r,nodes:i,roots:a}}function validateRawParameters(e,t){analyzeRawParameterGraph(e,t)}function snapshotRawParameterGraph(e,t){let n=analyzeRawParameterGraph(e,t),r=new WeakMap,i=new WeakMap;for(let e of n.nodes){let t=e.isArray?[]:{};e.prototype===null&&Object.setPrototypeOf(t,null),r.set(e.source,t)}let copiedValue=e=>{if(typeof e!=`object`||!e)return e;let t=n.dateTimes.get(e);if(t!==void 0){let n=i.get(e);if(n)return n;let r=new Date(t);return i.set(e,r),r}return r.get(e)??e};for(let e of n.nodes){let t=r.get(e.source);if(t){for(let n of e.properties){if(e.isArray&&n.key===`length`)continue;let r=n.descriptor;Object.defineProperty(t,n.key,`value`in r&&(e.isArray?isArrayIndex(n.key):r.enumerable&&typeof n.key==`string`)?{...r,value:copiedValue(r.value)}:r)}if(e.isArray){let n=e.properties.find(e=>e.key===`length`);n&&Object.defineProperty(t,`length`,n.descriptor)}}}let a=Array(n.roots.length);for(let e=0;e<n.roots.length;e++)Object.hasOwn(n.roots,e)&&(a[e]=copiedValue(n.roots[e]));return a}function invalidProviderDateError(e,t){return new r(`Operation "${e.operation??`statement`}" received an invalid Date as bound parameter ${t}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,{code:n.INVALID_INPUT,meta:{parameterIndex:t,model:e.model,operation:e.operation,correlationId:e.correlationId}})}function unsupportedProviderArrayError(e,t){return new r(`Operation "${e.operation??`statement`}" received raw array parameter ${t} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,{code:n.INVALID_INPUT,meta:{parameterIndex:t,model:e.model,operation:e.operation,correlationId:e.correlationId}})}function snapshotProviderParameters(e,t){return t.model===`$raw`?snapshotRawParameterGraph(e,{invalidDate:e=>invalidProviderDateError(t,e),unsupportedArray:e=>unsupportedProviderArrayError(t,e)}):[...e]}function createNormalizedResultMeta(e){return{driver:e.provider,operation:e.operation,...e.model?{model:e.model}:{},...e.correlationId?{correlationId:e.correlationId}:{}}}const d=/^(?:0|[1-9]\d*)$/;function normalizeProviderRowCount(e,t,n){let i=e===null?n?.nullValue:e;if(n?.allowDecimalString===!0&&typeof i==`string`&&d.test(i)&&(i=Number(i)),typeof i!=`number`||!Number.isSafeInteger(i)||i<0)throw new r(`Driver "${t.provider}" returned a malformed row count for operation "${t.operation}".`,{meta:createNormalizedResultMeta(t)});return i}function normalizeProviderInsertId(e,t,n){if(typeof e==`string`){if(!d.test(e))throw malformedInsertId(t);return e===`0`?void 0:BigInt(e)}if(n?.allowNumber===!0&&typeof e==`number`){if(!Number.isSafeInteger(e)||e<0)throw malformedInsertId(t);return e===0?void 0:e}throw malformedInsertId(t)}function malformedInsertId(e){return new r(`Driver "${e.provider}" returned a malformed insert id for operation "${e.operation}".`,{meta:createNormalizedResultMeta(e)})}function malformedNormalizedResult(e,t){let n=t===void 0?``:` at batch result index ${t}`;return new r(`Driver "${e.provider}" returned a malformed normalized result for operation "${e.operation}"${n}; expected { rows: object[], rowCount: safe non-negative integer }.`,{meta:{...createNormalizedResultMeta(e),...t===void 0?{}:{resultIndex:t}}})}function isNormalizedResultRow(e){return typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Object]`}function hasNormalizedRows(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1)if(!(Object.hasOwn(e,t)&&isNormalizedResultRow(e[t])))return!1;return!0}function assertNormalizedQueryResult(e,t,n){let r=e?.insertId===void 0||typeof e.insertId==`bigint`&&e.insertId>=0n||typeof e.insertId==`number`&&Number.isFinite(e.insertId)&&Number.isSafeInteger(e.insertId)&&e.insertId>=0;if(!(isNormalizedResultRow(e)&&hasNormalizedRows(e.rows))||typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0||!r)throw malformedNormalizedResult(t,n)}function assertNormalizedBatchResults(e,t,n){if(!Array.isArray(e)||e.length!==t){let i=Array.isArray(e)?e.length:0;throw new r(`Driver "${n.provider}" returned ${i} results for operation "${n.operation}"; expected ${t}, one per statement.`,{meta:{...createNormalizedResultMeta(n),expectedStatementCount:t,actualResultCount:i}})}for(let t=0;t<e.length;t+=1)assertNormalizedQueryResult(e[t],n,t)}export{normalizeProviderInsertId as a,validateRawParameters as c,snapshotPreparedStatement as d,transferPreparedStatement as f,a as h,isNormalizedResultRow as i,readPreparedStatement as l,markVerbatimBatchQuery as m,assertNormalizedQueryResult as n,normalizeProviderRowCount as o,isVerbatimBatchQuery as p,createNormalizedResultMeta as r,snapshotProviderParameters as s,assertNormalizedBatchResults as t,registerPreparedStatement as u};
2
+ //# sourceMappingURL=normalized-result-23DWxZVY.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"normalized-result-VunNi4ID.mjs","names":[],"sources":["../src/drivers/async-dispose.ts","../src/drivers/driver-batch-query-kind.ts","../src/drivers/prepared-statement-provenance.ts","../src/drivers/provider-parameter-snapshot.ts","../src/drivers/normalized-result.ts"],"sourcesContent":["/**\n * The platform's async-disposal protocol — as much of it as the runtime and the\n * consumer's type declarations actually provide.\n *\n * `Symbol.asyncDispose` (explicit resource management, TypeScript 5.2+) can be\n * missing in two independent ways, and each one is handled here so that no\n * caller has to think about it:\n *\n * 1. **The runtime symbol** is absent on engines that predate the proposal.\n * {@link ASYNC_DISPOSE} resolves it once; every definition site guards on it\n * rather than writing a bare `[Symbol.asyncDispose]` computed key, which\n * would otherwise install a method under the string key `\"undefined\"`.\n *\n * 2. **The type declaration** is absent from a consumer's `lib` / `@types`.\n * That is why the disposal member is carried by {@link AsyncDisposeMember}\n * instead of being written literally: a consumer who never writes\n * `await using` must not be forced to widen `lib` just to compile the\n * published `.d.mts`. See `docs/architecture/typed-kernel-without-effect-plan.md`\n * (Phase T6) and the consumer-floor probe in\n * `scripts/consumer-type-floor.mjs` for the measured floor.\n */\n\n/**\n * The runtime's async-disposal key, or `undefined` on engines that predate\n * explicit resource management.\n */\nexport const ASYNC_DISPOSE: typeof Symbol.asyncDispose | undefined =\n typeof Symbol.asyncDispose === \"symbol\" ? Symbol.asyncDispose : undefined;\n\n/**\n * `Symbol.asyncDispose`'s type where the ambient declarations define it, and\n * `never` where they do not.\n *\n * `never` is the load-bearing half: it turns {@link AsyncDisposeMember} into the\n * empty object, so the member simply is not there for a consumer whose `lib`\n * and `@types` never declared the symbol in the first place.\n */\nexport type AsyncDisposeKey = SymbolConstructor extends {\n readonly asyncDispose: infer Key extends symbol;\n}\n ? Key\n : never;\n\n/**\n * `{ [Symbol.asyncDispose](): Promise<void> }` where the symbol is typed, and\n * `{}` where it is not — the graceful-degradation carrier for every viborm type\n * that participates in `await using`.\n */\nexport type AsyncDisposeMember = {\n [Key in AsyncDisposeKey]: () => Promise<void>;\n};\n","/** Internal execution-kind metadata for prepared batch queries. */\n\nconst VERBATIM_BATCH_QUERY = Symbol(\"viborm.verbatimBatchQuery\");\n\n/** Mark a prepared raw statement that must retain verbatim driver semantics. */\nexport function markVerbatimBatchQuery<T extends object>(query: T): T {\n Object.defineProperty(query, VERBATIM_BATCH_QUERY, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n });\n return query;\n}\n\n/** Whether a prepared statement came from an unsafe or legacy raw call. */\nexport function isVerbatimBatchQuery(query: object): boolean {\n return Reflect.get(query, VERBATIM_BATCH_QUERY) === true;\n}\n","import { Sql } from \"@sql\";\n\nconst preparedStatements = new WeakMap<object, Sql>();\n\n/** Retain the typed Sql behind a rendered batch query without publishing it. */\nexport function registerPreparedStatement(query: object, statement: Sql): void {\n preparedStatements.set(query, statement);\n}\n\n/** Preserve private provenance when an internal owner snapshots a batch query. */\nexport function transferPreparedStatement<Output extends object>(\n source: object,\n output: Output\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) preparedStatements.set(output, statement);\n return output;\n}\n\n/** Preserve provenance with the exact detached values a batch will execute. */\nexport function snapshotPreparedStatement<Output extends object>(\n source: object,\n output: Output,\n values: readonly unknown[]\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) {\n preparedStatements.set(\n output,\n new Sql([...statement.strings], [...values])\n );\n }\n return output;\n}\n\n/** Read provenance only at the trusted typed-statement execution boundary. */\nexport function readPreparedStatement(query: object): Sql | undefined {\n return preparedStatements.get(query);\n}\n","import { QueryError, VibORMErrorCode } from \"@errors\";\nimport { isDate } from \"@validation/value-guards\";\nimport type { QueryExecutionContext } from \"./types\";\n\ntype InvalidRawDateError = (parameterIndex: number) => Error;\ntype UnsupportedRawArrayError = (parameterIndex: number) => Error;\n\ninterface RawParameterErrors {\n readonly invalidDate: InvalidRawDateError;\n readonly unsupportedArray: UnsupportedRawArrayError;\n}\n\ninterface RawParameterEdge {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n readonly value: unknown;\n}\n\ninterface RawParameterNode {\n readonly edges: readonly RawParameterEdge[];\n readonly isArray: boolean;\n readonly properties: readonly RawParameterProperty[];\n readonly prototype: object | null;\n readonly source: object;\n}\n\ninterface RawParameterProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\ninterface RawParameterGraph {\n readonly dateTimes: WeakMap<object, number>;\n readonly nodes: readonly RawParameterNode[];\n readonly roots: readonly unknown[];\n}\n\ntype RawParameterNodeAnalysis =\n | { readonly kind: \"node\"; readonly shape: Omit<RawParameterNode, \"source\"> }\n | { readonly kind: \"opaque\" }\n | { readonly kind: \"unsupported-array\" };\n\nconst arrayIndex = /^(?:0|[1-9]\\d*)$/;\nconst maximumArrayIndex = 4_294_967_294;\n\ninterface BuiltinPrototypeProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\nfunction captureBuiltinPrototype(\n prototype: object\n): readonly BuiltinPrototypeProperty[] {\n const properties: BuiltinPrototypeProperty[] = [];\n for (const key of Reflect.ownKeys(prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, key);\n if (descriptor) properties.push({ descriptor, key });\n }\n return Object.freeze(properties);\n}\n\nconst objectPrototypeShape = captureBuiltinPrototype(Object.prototype);\nconst arrayPrototypeShape = captureBuiltinPrototype(Array.prototype);\n\nfunction isArrayIndex(key: PropertyKey): boolean {\n if (typeof key !== \"string\" || !arrayIndex.test(key)) return false;\n const index = Number(key);\n return index <= maximumArrayIndex && String(index) === key;\n}\n\nfunction functionSource(value: unknown): string | undefined {\n if (typeof value !== \"function\") return;\n try {\n return Function.prototype.toString.call(value);\n } catch {\n return;\n }\n}\n\nfunction sameInertRecord(left: unknown, right: unknown): boolean {\n if (\n left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\"\n ) {\n return Object.is(left, right);\n }\n try {\n if (\n Object.getPrototypeOf(left) !== null ||\n Object.getPrototypeOf(right) !== null\n ) {\n return false;\n }\n const leftKeys = Reflect.ownKeys(left);\n const rightKeys = Reflect.ownKeys(right);\n if (leftKeys.length !== rightKeys.length) return false;\n for (let index = 0; index < rightKeys.length; index += 1) {\n const leftKey = leftKeys[index];\n const rightKey = rightKeys[index];\n if (leftKey !== rightKey || rightKey === undefined) return false;\n const leftDescriptor = Object.getOwnPropertyDescriptor(left, rightKey);\n const rightDescriptor = Object.getOwnPropertyDescriptor(right, rightKey);\n if (\n leftDescriptor === undefined ||\n rightDescriptor === undefined ||\n !(\"value\" in leftDescriptor) ||\n !(\"value\" in rightDescriptor) ||\n leftDescriptor.configurable !== rightDescriptor.configurable ||\n leftDescriptor.enumerable !== rightDescriptor.enumerable ||\n leftDescriptor.writable !== rightDescriptor.writable ||\n !Object.is(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction sameBuiltinDescriptor(\n actual: PropertyDescriptor,\n expected: PropertyDescriptor\n): boolean {\n if (\n actual.configurable !== expected.configurable ||\n actual.enumerable !== expected.enumerable ||\n \"value\" in actual !== \"value\" in expected\n ) {\n return false;\n }\n if (\"value\" in actual && \"value\" in expected) {\n if (actual.writable !== expected.writable) return false;\n const expectedSource = functionSource(expected.value);\n if (expectedSource !== undefined) {\n return functionSource(actual.value) === expectedSource;\n }\n return sameInertRecord(actual.value, expected.value);\n }\n return (\n functionSource(actual.get) === functionSource(expected.get) &&\n functionSource(actual.set) === functionSource(expected.set)\n );\n}\n\nfunction hasBuiltinPrototypeShape(\n prototype: object,\n shape: readonly BuiltinPrototypeProperty[]\n): boolean {\n try {\n const keys = Reflect.ownKeys(prototype);\n if (keys.length !== shape.length) return false;\n for (let index = 0; index < shape.length; index += 1) {\n const expected = shape[index];\n if (expected === undefined || keys[index] !== expected.key) return false;\n const actual = Object.getOwnPropertyDescriptor(prototype, expected.key);\n if (\n actual === undefined ||\n !sameBuiltinDescriptor(actual, expected.descriptor)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isObjectPrototype(prototype: object): boolean {\n try {\n return (\n Object.getPrototypeOf(prototype) === null &&\n hasBuiltinPrototypeShape(prototype, objectPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\nfunction isArrayPrototype(prototype: object): boolean {\n try {\n const parent = Object.getPrototypeOf(prototype);\n return (\n parent !== null &&\n isObjectPrototype(parent) &&\n hasBuiltinPrototypeShape(prototype, arrayPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\n/** Only arrays and records with inert inherited behavior are interpreted. */\nfunction rawParameterNodeShape(value: object): RawParameterNodeAnalysis {\n let isArray = false;\n try {\n isArray = Array.isArray(value);\n const prototype = Object.getPrototypeOf(value);\n if (\n (isArray && prototype !== null && !isArrayPrototype(prototype)) ||\n (!isArray && prototype !== null && !isObjectPrototype(prototype))\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n\n const edges: RawParameterEdge[] = [];\n const properties: RawParameterProperty[] = [];\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) continue;\n properties.push({ descriptor, key });\n const isProviderVisible = isArray\n ? isArrayIndex(key)\n : descriptor.enumerable && typeof key === \"string\";\n if (!isProviderVisible) continue;\n if (!(\"value\" in descriptor)) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n edges.push({ descriptor, key, value: descriptor.value });\n }\n const toJSON = properties.find((property) => property.key === \"toJSON\");\n if (\n toJSON &&\n (!(\"value\" in toJSON.descriptor) ||\n typeof toJSON.descriptor.value === \"function\")\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n return {\n kind: \"node\",\n shape: { edges, isArray, properties, prototype },\n };\n } catch {\n // An exotic record owns its traversal semantics. If reflection refuses an\n // array shape, it cannot safely reach provider array semantics.\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n}\n\nfunction rawDateTime(\n value: unknown,\n parameterIndex: number,\n invalidDateError: InvalidRawDateError\n): number | undefined {\n if (!isDate(value)) return;\n const time = Date.prototype.getTime.call(value);\n if (Number.isNaN(time)) throw invalidDateError(parameterIndex);\n return time;\n}\n\nfunction analyzeRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): RawParameterGraph {\n const nodesBySource = new WeakMap<object, RawParameterNode>();\n const dateTimes = new WeakMap<object, number>();\n const nodes: RawParameterNode[] = [];\n const roots = new Array<unknown>(params.length);\n\n const discover = (\n value: unknown,\n parameterIndex: number\n ): RawParameterNode | undefined => {\n const time = rawDateTime(value, parameterIndex, errors.invalidDate);\n if (time !== undefined && typeof value === \"object\" && value !== null) {\n dateTimes.set(value, time);\n return;\n }\n if (typeof value !== \"object\" || value === null) return;\n\n const known = nodesBySource.get(value);\n if (known) return known;\n const analysis = rawParameterNodeShape(value);\n if (analysis.kind === \"unsupported-array\") {\n throw errors.unsupportedArray(parameterIndex);\n }\n if (analysis.kind === \"opaque\") return;\n const node: RawParameterNode = {\n ...analysis.shape,\n source: value,\n };\n nodesBySource.set(value, node);\n nodes.push(node);\n return node;\n };\n\n for (\n let parameterIndex = 0;\n parameterIndex < params.length;\n parameterIndex++\n ) {\n if (!Object.hasOwn(params, parameterIndex)) continue;\n const root = params[parameterIndex];\n roots[parameterIndex] = root;\n const rootTime = rawDateTime(root, parameterIndex, errors.invalidDate);\n if (rootTime !== undefined && typeof root === \"object\" && root !== null) {\n dateTimes.set(root, rootTime);\n continue;\n }\n const rootNode = discover(root, parameterIndex);\n if (!rootNode) continue;\n\n const pending = [rootNode];\n let cursor = 0;\n while (cursor < pending.length) {\n const node = pending[cursor];\n cursor += 1;\n if (!node) continue;\n for (const edge of node.edges) {\n const before = nodes.length;\n const child = discover(edge.value, parameterIndex);\n if (child && nodes.length > before) pending.push(child);\n }\n }\n }\n\n return { dateTimes, nodes, roots };\n}\n\n/** Validate every interpreted raw parameter before query interception. */\nexport function validateRawParameters(\n params: readonly unknown[],\n errors: RawParameterErrors\n): void {\n analyzeRawParameterGraph(params, errors);\n}\n\n/**\n * Snapshot every admitted data-descriptor JSON container, preserving aliases,\n * cycles, and property descriptors. Foreign built-in containers normalize to\n * local prototypes. Custom record carriers and provider-native objects remain\n * opaque; arrays with custom provider-visible behavior are refused. A Proxy\n * can run reflection traps while presenting an admitted container shape; the\n * captured descriptor view, never the later mutable Proxy, reaches dispatch.\n */\nfunction snapshotRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): unknown[] {\n const graph = analyzeRawParameterGraph(params, errors);\n const copies = new WeakMap<object, object>();\n const copiedDates = new WeakMap<object, Date>();\n\n for (const node of graph.nodes) {\n const copy: object = node.isArray ? [] : {};\n if (node.prototype === null) Object.setPrototypeOf(copy, null);\n copies.set(node.source, copy);\n }\n\n const copiedValue = (value: unknown): unknown => {\n if (typeof value !== \"object\" || value === null) return value;\n const time = graph.dateTimes.get(value);\n if (time !== undefined) {\n const known = copiedDates.get(value);\n if (known) return known;\n const copy = new Date(time);\n copiedDates.set(value, copy);\n return copy;\n }\n return copies.get(value) ?? value;\n };\n\n for (const node of graph.nodes) {\n const copy = copies.get(node.source);\n if (!copy) continue;\n for (const property of node.properties) {\n if (node.isArray && property.key === \"length\") continue;\n const descriptor = property.descriptor;\n Object.defineProperty(\n copy,\n property.key,\n \"value\" in descriptor &&\n (node.isArray\n ? isArrayIndex(property.key)\n : descriptor.enumerable && typeof property.key === \"string\")\n ? { ...descriptor, value: copiedValue(descriptor.value) }\n : descriptor\n );\n }\n if (node.isArray) {\n const length = node.properties.find(\n (property) => property.key === \"length\"\n );\n if (length) Object.defineProperty(copy, \"length\", length.descriptor);\n }\n }\n\n const snapshot = new Array<unknown>(graph.roots.length);\n for (let index = 0; index < graph.roots.length; index++) {\n if (!Object.hasOwn(graph.roots, index)) continue;\n snapshot[index] = copiedValue(graph.roots[index]);\n }\n return snapshot;\n}\n\nfunction invalidProviderDateError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received an invalid Date as bound parameter ${parameterIndex}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\nfunction unsupportedProviderArrayError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received raw array parameter ${parameterIndex} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\n/**\n * Preserve the raw Date admission invariant after the last trusted statement\n * transform. Non-raw statements keep the old shallow-copy path: their typed\n * inputs were validated upstream, and statement transforms are trusted. Raw\n * Date leaves are revalidated and every admitted data-descriptor array or\n * ordinary JSON record is detached. Reflection does not invoke accessors,\n * iterators, or `toJSON`; a Proxy may run its reflection traps, so its captured\n * descriptor view is the stable provider value. Arrays with custom inherited\n * or accessor behavior are refused. Custom record and provider-native carriers\n * remain opaque and are not traversed.\n */\nexport function snapshotProviderParameters(\n params: readonly unknown[],\n context: QueryExecutionContext\n): unknown[] {\n if (context.model !== \"$raw\") return [...params];\n return snapshotRawParameterGraph(params, {\n invalidDate: (parameterIndex) =>\n invalidProviderDateError(context, parameterIndex),\n unsupportedArray: (parameterIndex) =>\n unsupportedProviderArrayError(context, parameterIndex),\n });\n}\n","import { QueryError } from \"@errors\";\nimport type { QueryResult } from \"./types\";\n\nexport interface NormalizedResultContext {\n provider: string;\n operation: string;\n model?: string;\n correlationId?: string;\n}\n\nexport function createNormalizedResultMeta(\n context: NormalizedResultContext\n): Record<string, unknown> {\n return {\n driver: context.provider,\n operation: context.operation,\n ...(context.model ? { model: context.model } : {}),\n ...(context.correlationId ? { correlationId: context.correlationId } : {}),\n };\n}\n\nconst NON_NEGATIVE_DECIMAL_REGEX = /^(?:0|[1-9]\\d*)$/;\n\nexport function normalizeProviderRowCount(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowDecimalString?: boolean; nullValue?: number }\n): number {\n let normalized = value === null ? options?.nullValue : value;\n if (\n options?.allowDecimalString === true &&\n typeof normalized === \"string\" &&\n NON_NEGATIVE_DECIMAL_REGEX.test(normalized)\n ) {\n normalized = Number(normalized);\n }\n if (\n typeof normalized !== \"number\" ||\n !Number.isSafeInteger(normalized) ||\n normalized < 0\n ) {\n throw new QueryError(\n `Driver \"${context.provider}\" returned a malformed row count for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n }\n return normalized;\n}\n\nexport function normalizeProviderInsertId(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowNumber?: boolean }\n): number | bigint | undefined {\n if (typeof value === \"string\") {\n if (!NON_NEGATIVE_DECIMAL_REGEX.test(value)) {\n throw malformedInsertId(context);\n }\n return value === \"0\" ? undefined : BigInt(value);\n }\n if (options?.allowNumber === true && typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw malformedInsertId(context);\n }\n return value === 0 ? undefined : value;\n }\n throw malformedInsertId(context);\n}\n\nfunction malformedInsertId(context: NormalizedResultContext): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed insert id for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n}\n\nfunction malformedNormalizedResult(\n context: NormalizedResultContext,\n resultIndex?: number\n): QueryError {\n const position =\n resultIndex === undefined ? \"\" : ` at batch result index ${resultIndex}`;\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed normalized result for operation \"${context.operation}\"${position}; expected { rows: object[], rowCount: safe non-negative integer }.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n ...(resultIndex === undefined ? {} : { resultIndex }),\n },\n }\n );\n}\n\nexport function isNormalizedResultRow(\n value: unknown\n): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction hasNormalizedRows(value: unknown): value is Record<string, unknown>[] {\n if (!Array.isArray(value)) return false;\n for (let index = 0; index < value.length; index += 1) {\n if (!(Object.hasOwn(value, index) && isNormalizedResultRow(value[index]))) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Assert the single cross-driver success contract. Empty row arrays and a\n * rowCount of zero are valid; missing fields, non-record rows, and invented\n * counts are not.\n */\nexport function assertNormalizedQueryResult(\n result: QueryResult<unknown> | undefined,\n context: NormalizedResultContext,\n resultIndex?: number\n): void {\n const hasValidInsertId =\n result?.insertId === undefined ||\n (typeof result.insertId === \"bigint\" && result.insertId >= 0n) ||\n (typeof result.insertId === \"number\" &&\n Number.isFinite(result.insertId) &&\n Number.isSafeInteger(result.insertId) &&\n result.insertId >= 0);\n if (\n !(isNormalizedResultRow(result) && hasNormalizedRows(result.rows)) ||\n typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0 ||\n !hasValidInsertId\n ) {\n throw malformedNormalizedResult(context, resultIndex);\n }\n}\n\n/**\n * Native and planned batches must return one normalized result for each\n * submitted statement, in the same order.\n */\nexport function assertNormalizedBatchResults(\n results: readonly QueryResult<unknown>[],\n expectedStatementCount: number,\n context: NormalizedResultContext\n): void {\n if (!Array.isArray(results) || results.length !== expectedStatementCount) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw new QueryError(\n `Driver \"${context.provider}\" returned ${actualResultCount} results for operation \"${context.operation}\"; expected ${expectedStatementCount}, one per statement.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n expectedStatementCount,\n actualResultCount,\n },\n }\n );\n }\n\n for (let resultIndex = 0; resultIndex < results.length; resultIndex += 1) {\n assertNormalizedQueryResult(results[resultIndex], context, resultIndex);\n }\n}\n"],"mappings":"iNA0BA,MAAa,EACX,OAAO,OAAO,cAAiB,SAAW,OAAO,aAAe,IAAA,GCzB5D,EAAuB,OAAO,4BAA4B,CAGhE,SAAgB,uBAAyC,EAAa,CAOpE,OANA,OAAO,eAAe,EAAO,EAAsB,CACjD,aAAc,GACd,WAAY,GACZ,MAAO,GACP,SAAU,GACX,CAAC,CACK,EAIT,SAAgB,qBAAqB,EAAwB,CAC3D,OAAO,QAAQ,IAAI,EAAO,EAAqB,GAAK,GCftD,MAAM,EAAqB,IAAI,QAG/B,SAAgB,0BAA0B,EAAe,EAAsB,CAC7E,EAAmB,IAAI,EAAO,EAAU,CAI1C,SAAgB,0BACd,EACA,EACQ,CACR,IAAM,EAAY,EAAmB,IAAI,EAAO,CAEhD,OADI,IAAc,IAAA,IAAW,EAAmB,IAAI,EAAQ,EAAU,CAC/D,EAIT,SAAgB,0BACd,EACA,EACA,EACQ,CACR,IAAM,EAAY,EAAmB,IAAI,EAAO,CAOhD,OANI,IAAc,IAAA,IAChB,EAAmB,IACjB,EACA,IAAI,EAAI,CAAC,GAAG,EAAU,QAAQ,CAAE,CAAC,GAAG,EAAO,CAAC,CAC7C,CAEI,EAIT,SAAgB,sBAAsB,EAAgC,CACpE,OAAO,EAAmB,IAAI,EAAM,CCKtC,MAAM,EAAa,mBAQnB,SAAS,wBACP,EACqC,CACrC,IAAM,EAAyC,EAAE,CACjD,IAAK,IAAM,KAAO,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AAY,EAAO,UAAY,IAC1D,OAAO,EAAO,UAAa,UAC1B,OAAO,SAAS,EAAO,SAAS,EAChC,OAAO,cAAc,EAAO,SAAS,EACrC,EAAO,UAAY,EACvB,GACE,EAAE,sBAAsB,EAAO,EAAI,kBAAkB,EAAO,KAAK,GACjE,OAAO,EAAO,UAAa,UAC3B,CAAC,OAAO,SAAS,EAAO,SAAS,EACjC,CAAC,OAAO,cAAc,EAAO,SAAS,EACtC,EAAO,SAAW,GAClB,CAAC,EAED,MAAM,0BAA0B,EAAS,EAAY,CAQzD,SAAgB,6BACd,EACA,EACA,EACM,CACN,GAAI,CAAC,MAAM,QAAQ,EAAQ,EAAI,EAAQ,SAAW,EAAwB,CACxE,IAAM,EAAoB,MAAM,QAAQ,EAAQ,CAAG,EAAQ,OAAS,EACpE,MAAM,IAAI,EACR,WAAW,EAAQ,SAAS,aAAa,EAAkB,0BAA0B,EAAQ,UAAU,cAAc,EAAuB,sBAC5I,CACE,KAAM,CACJ,GAAG,2BAA2B,EAAQ,CACtC,yBACA,oBACD,CACF,CACF,CAGH,IAAK,IAAI,EAAc,EAAG,EAAc,EAAQ,OAAQ,GAAe,EACrE,4BAA4B,EAAQ,GAAc,EAAS,EAAY"}
1
+ {"version":3,"file":"normalized-result-23DWxZVY.mjs","names":[],"sources":["../src/drivers/async-dispose.ts","../src/drivers/driver-batch-query-kind.ts","../src/drivers/prepared-statement-provenance.ts","../src/drivers/provider-parameter-snapshot.ts","../src/drivers/normalized-result.ts"],"sourcesContent":["/**\n * The platform's async-disposal protocol — as much of it as the runtime and the\n * consumer's type declarations actually provide.\n *\n * `Symbol.asyncDispose` (explicit resource management, TypeScript 5.2+) can be\n * missing in two independent ways, and each one is handled here so that no\n * caller has to think about it:\n *\n * 1. **The runtime symbol** is absent on engines that predate the proposal.\n * {@link ASYNC_DISPOSE} resolves it once; every definition site guards on it\n * rather than writing a bare `[Symbol.asyncDispose]` computed key, which\n * would otherwise install a method under the string key `\"undefined\"`.\n *\n * 2. **The type declaration** is absent from a consumer's `lib` / `@types`.\n * That is why the disposal member is carried by {@link AsyncDisposeMember}\n * instead of being written literally: a consumer who never writes\n * `await using` must not be forced to widen `lib` just to compile the\n * published `.d.mts`. See `docs/architecture/typed-kernel-without-effect-plan.md`\n * (Phase T6) and the consumer-floor probe in\n * `scripts/consumer-type-floor.mjs` for the measured floor.\n */\n\n/**\n * The runtime's async-disposal key, or `undefined` on engines that predate\n * explicit resource management.\n */\nexport const ASYNC_DISPOSE: typeof Symbol.asyncDispose | undefined =\n typeof Symbol.asyncDispose === \"symbol\" ? Symbol.asyncDispose : undefined;\n\n/**\n * `Symbol.asyncDispose`'s type where the ambient declarations define it, and\n * `never` where they do not.\n *\n * `never` is the load-bearing half: it turns {@link AsyncDisposeMember} into the\n * empty object, so the member simply is not there for a consumer whose `lib`\n * and `@types` never declared the symbol in the first place.\n */\nexport type AsyncDisposeKey = SymbolConstructor extends {\n readonly asyncDispose: infer Key extends symbol;\n}\n ? Key\n : never;\n\n/**\n * `{ [Symbol.asyncDispose](): Promise<void> }` where the symbol is typed, and\n * `{}` where it is not — the graceful-degradation carrier for every viborm type\n * that participates in `await using`.\n */\nexport type AsyncDisposeMember = {\n [Key in AsyncDisposeKey]: () => Promise<void>;\n};\n","/** Internal execution-kind metadata for prepared batch queries. */\n\nconst VERBATIM_BATCH_QUERY = Symbol(\"viborm.verbatimBatchQuery\");\n\n/** Mark a prepared raw statement that must retain verbatim driver semantics. */\nexport function markVerbatimBatchQuery<T extends object>(query: T): T {\n Object.defineProperty(query, VERBATIM_BATCH_QUERY, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n });\n return query;\n}\n\n/** Whether a prepared statement came from an unsafe or legacy raw call. */\nexport function isVerbatimBatchQuery(query: object): boolean {\n return Reflect.get(query, VERBATIM_BATCH_QUERY) === true;\n}\n","import { Sql } from \"@sql\";\n\nconst preparedStatements = new WeakMap<object, Sql>();\n\n/** Retain the typed Sql behind a rendered batch query without publishing it. */\nexport function registerPreparedStatement(query: object, statement: Sql): void {\n preparedStatements.set(query, statement);\n}\n\n/** Preserve private provenance when an internal owner snapshots a batch query. */\nexport function transferPreparedStatement<Output extends object>(\n source: object,\n output: Output\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) preparedStatements.set(output, statement);\n return output;\n}\n\n/** Preserve provenance with the exact detached values a batch will execute. */\nexport function snapshotPreparedStatement<Output extends object>(\n source: object,\n output: Output,\n values: readonly unknown[]\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) {\n preparedStatements.set(\n output,\n new Sql([...statement.strings], [...values])\n );\n }\n return output;\n}\n\n/** Read provenance only at the trusted typed-statement execution boundary. */\nexport function readPreparedStatement(query: object): Sql | undefined {\n return preparedStatements.get(query);\n}\n","import { QueryError, VibORMErrorCode } from \"@errors\";\nimport { isDate } from \"@validation/value-guards\";\nimport type { QueryExecutionContext } from \"./types\";\n\ntype InvalidRawDateError = (parameterIndex: number) => Error;\ntype UnsupportedRawArrayError = (parameterIndex: number) => Error;\n\ninterface RawParameterErrors {\n readonly invalidDate: InvalidRawDateError;\n readonly unsupportedArray: UnsupportedRawArrayError;\n}\n\ninterface RawParameterEdge {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n readonly value: unknown;\n}\n\ninterface RawParameterNode {\n readonly edges: readonly RawParameterEdge[];\n readonly isArray: boolean;\n readonly properties: readonly RawParameterProperty[];\n readonly prototype: object | null;\n readonly source: object;\n}\n\ninterface RawParameterProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\ninterface RawParameterGraph {\n readonly dateTimes: WeakMap<object, number>;\n readonly nodes: readonly RawParameterNode[];\n readonly roots: readonly unknown[];\n}\n\ntype RawParameterNodeAnalysis =\n | { readonly kind: \"node\"; readonly shape: Omit<RawParameterNode, \"source\"> }\n | { readonly kind: \"opaque\" }\n | { readonly kind: \"unsupported-array\" };\n\nconst arrayIndex = /^(?:0|[1-9]\\d*)$/;\nconst maximumArrayIndex = 4_294_967_294;\n\ninterface BuiltinPrototypeProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\nfunction captureBuiltinPrototype(\n prototype: object\n): readonly BuiltinPrototypeProperty[] {\n const properties: BuiltinPrototypeProperty[] = [];\n for (const key of Reflect.ownKeys(prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, key);\n if (descriptor) properties.push({ descriptor, key });\n }\n return Object.freeze(properties);\n}\n\nconst objectPrototypeShape = captureBuiltinPrototype(Object.prototype);\nconst arrayPrototypeShape = captureBuiltinPrototype(Array.prototype);\n\nfunction isArrayIndex(key: PropertyKey): boolean {\n if (typeof key !== \"string\" || !arrayIndex.test(key)) return false;\n const index = Number(key);\n return index <= maximumArrayIndex && String(index) === key;\n}\n\nfunction functionSource(value: unknown): string | undefined {\n if (typeof value !== \"function\") return;\n try {\n return Function.prototype.toString.call(value);\n } catch {\n return;\n }\n}\n\nfunction sameInertRecord(left: unknown, right: unknown): boolean {\n if (\n left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\"\n ) {\n return Object.is(left, right);\n }\n try {\n if (\n Object.getPrototypeOf(left) !== null ||\n Object.getPrototypeOf(right) !== null\n ) {\n return false;\n }\n const leftKeys = Reflect.ownKeys(left);\n const rightKeys = Reflect.ownKeys(right);\n if (leftKeys.length !== rightKeys.length) return false;\n for (let index = 0; index < rightKeys.length; index += 1) {\n const leftKey = leftKeys[index];\n const rightKey = rightKeys[index];\n if (leftKey !== rightKey || rightKey === undefined) return false;\n const leftDescriptor = Object.getOwnPropertyDescriptor(left, rightKey);\n const rightDescriptor = Object.getOwnPropertyDescriptor(right, rightKey);\n if (\n leftDescriptor === undefined ||\n rightDescriptor === undefined ||\n !(\"value\" in leftDescriptor) ||\n !(\"value\" in rightDescriptor) ||\n leftDescriptor.configurable !== rightDescriptor.configurable ||\n leftDescriptor.enumerable !== rightDescriptor.enumerable ||\n leftDescriptor.writable !== rightDescriptor.writable ||\n !Object.is(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction sameBuiltinDescriptor(\n actual: PropertyDescriptor,\n expected: PropertyDescriptor\n): boolean {\n if (\n actual.configurable !== expected.configurable ||\n actual.enumerable !== expected.enumerable ||\n \"value\" in actual !== \"value\" in expected\n ) {\n return false;\n }\n if (\"value\" in actual && \"value\" in expected) {\n if (actual.writable !== expected.writable) return false;\n const expectedSource = functionSource(expected.value);\n if (expectedSource !== undefined) {\n return functionSource(actual.value) === expectedSource;\n }\n return sameInertRecord(actual.value, expected.value);\n }\n return (\n functionSource(actual.get) === functionSource(expected.get) &&\n functionSource(actual.set) === functionSource(expected.set)\n );\n}\n\nfunction hasBuiltinPrototypeShape(\n prototype: object,\n shape: readonly BuiltinPrototypeProperty[]\n): boolean {\n try {\n const keys = Reflect.ownKeys(prototype);\n if (keys.length !== shape.length) return false;\n for (let index = 0; index < shape.length; index += 1) {\n const expected = shape[index];\n if (expected === undefined || keys[index] !== expected.key) return false;\n const actual = Object.getOwnPropertyDescriptor(prototype, expected.key);\n if (\n actual === undefined ||\n !sameBuiltinDescriptor(actual, expected.descriptor)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isObjectPrototype(prototype: object): boolean {\n try {\n return (\n Object.getPrototypeOf(prototype) === null &&\n hasBuiltinPrototypeShape(prototype, objectPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\nfunction isArrayPrototype(prototype: object): boolean {\n try {\n const parent = Object.getPrototypeOf(prototype);\n return (\n parent !== null &&\n isObjectPrototype(parent) &&\n hasBuiltinPrototypeShape(prototype, arrayPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\n/** Only arrays and records with inert inherited behavior are interpreted. */\nfunction rawParameterNodeShape(value: object): RawParameterNodeAnalysis {\n let isArray = false;\n try {\n isArray = Array.isArray(value);\n const prototype = Object.getPrototypeOf(value);\n if (\n (isArray && prototype !== null && !isArrayPrototype(prototype)) ||\n (!isArray && prototype !== null && !isObjectPrototype(prototype))\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n\n const edges: RawParameterEdge[] = [];\n const properties: RawParameterProperty[] = [];\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) continue;\n properties.push({ descriptor, key });\n const isProviderVisible = isArray\n ? isArrayIndex(key)\n : descriptor.enumerable && typeof key === \"string\";\n if (!isProviderVisible) continue;\n if (!(\"value\" in descriptor)) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n edges.push({ descriptor, key, value: descriptor.value });\n }\n const toJSON = properties.find((property) => property.key === \"toJSON\");\n if (\n toJSON &&\n (!(\"value\" in toJSON.descriptor) ||\n typeof toJSON.descriptor.value === \"function\")\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n return {\n kind: \"node\",\n shape: { edges, isArray, properties, prototype },\n };\n } catch {\n // An exotic record owns its traversal semantics. If reflection refuses an\n // array shape, it cannot safely reach provider array semantics.\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n}\n\nfunction rawDateTime(\n value: unknown,\n parameterIndex: number,\n invalidDateError: InvalidRawDateError\n): number | undefined {\n if (!isDate(value)) return;\n const time = Date.prototype.getTime.call(value);\n if (Number.isNaN(time)) throw invalidDateError(parameterIndex);\n return time;\n}\n\nfunction analyzeRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): RawParameterGraph {\n const nodesBySource = new WeakMap<object, RawParameterNode>();\n const dateTimes = new WeakMap<object, number>();\n const nodes: RawParameterNode[] = [];\n const roots = new Array<unknown>(params.length);\n\n const discover = (\n value: unknown,\n parameterIndex: number\n ): RawParameterNode | undefined => {\n const time = rawDateTime(value, parameterIndex, errors.invalidDate);\n if (time !== undefined && typeof value === \"object\" && value !== null) {\n dateTimes.set(value, time);\n return;\n }\n if (typeof value !== \"object\" || value === null) return;\n\n const known = nodesBySource.get(value);\n if (known) return known;\n const analysis = rawParameterNodeShape(value);\n if (analysis.kind === \"unsupported-array\") {\n throw errors.unsupportedArray(parameterIndex);\n }\n if (analysis.kind === \"opaque\") return;\n const node: RawParameterNode = {\n ...analysis.shape,\n source: value,\n };\n nodesBySource.set(value, node);\n nodes.push(node);\n return node;\n };\n\n for (\n let parameterIndex = 0;\n parameterIndex < params.length;\n parameterIndex++\n ) {\n if (!Object.hasOwn(params, parameterIndex)) continue;\n const root = params[parameterIndex];\n roots[parameterIndex] = root;\n const rootTime = rawDateTime(root, parameterIndex, errors.invalidDate);\n if (rootTime !== undefined && typeof root === \"object\" && root !== null) {\n dateTimes.set(root, rootTime);\n continue;\n }\n const rootNode = discover(root, parameterIndex);\n if (!rootNode) continue;\n\n const pending = [rootNode];\n let cursor = 0;\n while (cursor < pending.length) {\n const node = pending[cursor];\n cursor += 1;\n if (!node) continue;\n for (const edge of node.edges) {\n const before = nodes.length;\n const child = discover(edge.value, parameterIndex);\n if (child && nodes.length > before) pending.push(child);\n }\n }\n }\n\n return { dateTimes, nodes, roots };\n}\n\n/** Validate every interpreted raw parameter before query interception. */\nexport function validateRawParameters(\n params: readonly unknown[],\n errors: RawParameterErrors\n): void {\n analyzeRawParameterGraph(params, errors);\n}\n\n/**\n * Snapshot every admitted data-descriptor JSON container, preserving aliases,\n * cycles, and property descriptors. Foreign built-in containers normalize to\n * local prototypes. Custom record carriers and provider-native objects remain\n * opaque; arrays with custom provider-visible behavior are refused. A Proxy\n * can run reflection traps while presenting an admitted container shape; the\n * captured descriptor view, never the later mutable Proxy, reaches dispatch.\n */\nfunction snapshotRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): unknown[] {\n const graph = analyzeRawParameterGraph(params, errors);\n const copies = new WeakMap<object, object>();\n const copiedDates = new WeakMap<object, Date>();\n\n for (const node of graph.nodes) {\n const copy: object = node.isArray ? [] : {};\n if (node.prototype === null) Object.setPrototypeOf(copy, null);\n copies.set(node.source, copy);\n }\n\n const copiedValue = (value: unknown): unknown => {\n if (typeof value !== \"object\" || value === null) return value;\n const time = graph.dateTimes.get(value);\n if (time !== undefined) {\n const known = copiedDates.get(value);\n if (known) return known;\n const copy = new Date(time);\n copiedDates.set(value, copy);\n return copy;\n }\n return copies.get(value) ?? value;\n };\n\n for (const node of graph.nodes) {\n const copy = copies.get(node.source);\n if (!copy) continue;\n for (const property of node.properties) {\n if (node.isArray && property.key === \"length\") continue;\n const descriptor = property.descriptor;\n Object.defineProperty(\n copy,\n property.key,\n \"value\" in descriptor &&\n (node.isArray\n ? isArrayIndex(property.key)\n : descriptor.enumerable && typeof property.key === \"string\")\n ? { ...descriptor, value: copiedValue(descriptor.value) }\n : descriptor\n );\n }\n if (node.isArray) {\n const length = node.properties.find(\n (property) => property.key === \"length\"\n );\n if (length) Object.defineProperty(copy, \"length\", length.descriptor);\n }\n }\n\n const snapshot = new Array<unknown>(graph.roots.length);\n for (let index = 0; index < graph.roots.length; index++) {\n if (!Object.hasOwn(graph.roots, index)) continue;\n snapshot[index] = copiedValue(graph.roots[index]);\n }\n return snapshot;\n}\n\nfunction invalidProviderDateError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received an invalid Date as bound parameter ${parameterIndex}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\nfunction unsupportedProviderArrayError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received raw array parameter ${parameterIndex} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\n/**\n * Preserve the raw Date admission invariant after the last trusted statement\n * transform. Non-raw statements keep the old shallow-copy path: their typed\n * inputs were validated upstream, and statement transforms are trusted. Raw\n * Date leaves are revalidated and every admitted data-descriptor array or\n * ordinary JSON record is detached. Reflection does not invoke accessors,\n * iterators, or `toJSON`; a Proxy may run its reflection traps, so its captured\n * descriptor view is the stable provider value. Arrays with custom inherited\n * or accessor behavior are refused. Custom record and provider-native carriers\n * remain opaque and are not traversed.\n */\nexport function snapshotProviderParameters(\n params: readonly unknown[],\n context: QueryExecutionContext\n): unknown[] {\n if (context.model !== \"$raw\") return [...params];\n return snapshotRawParameterGraph(params, {\n invalidDate: (parameterIndex) =>\n invalidProviderDateError(context, parameterIndex),\n unsupportedArray: (parameterIndex) =>\n unsupportedProviderArrayError(context, parameterIndex),\n });\n}\n","import { QueryError } from \"@errors\";\nimport type { QueryResult } from \"./types\";\n\nexport interface NormalizedResultContext {\n provider: string;\n operation: string;\n model?: string;\n correlationId?: string;\n}\n\nexport function createNormalizedResultMeta(\n context: NormalizedResultContext\n): Record<string, unknown> {\n return {\n driver: context.provider,\n operation: context.operation,\n ...(context.model ? { model: context.model } : {}),\n ...(context.correlationId ? { correlationId: context.correlationId } : {}),\n };\n}\n\nconst NON_NEGATIVE_DECIMAL_REGEX = /^(?:0|[1-9]\\d*)$/;\n\nexport function normalizeProviderRowCount(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowDecimalString?: boolean; nullValue?: number }\n): number {\n let normalized = value === null ? options?.nullValue : value;\n if (\n options?.allowDecimalString === true &&\n typeof normalized === \"string\" &&\n NON_NEGATIVE_DECIMAL_REGEX.test(normalized)\n ) {\n normalized = Number(normalized);\n }\n if (\n typeof normalized !== \"number\" ||\n !Number.isSafeInteger(normalized) ||\n normalized < 0\n ) {\n throw new QueryError(\n `Driver \"${context.provider}\" returned a malformed row count for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n }\n return normalized;\n}\n\nexport function normalizeProviderInsertId(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowNumber?: boolean }\n): number | bigint | undefined {\n if (typeof value === \"string\") {\n if (!NON_NEGATIVE_DECIMAL_REGEX.test(value)) {\n throw malformedInsertId(context);\n }\n return value === \"0\" ? undefined : BigInt(value);\n }\n if (options?.allowNumber === true && typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw malformedInsertId(context);\n }\n return value === 0 ? undefined : value;\n }\n throw malformedInsertId(context);\n}\n\nfunction malformedInsertId(context: NormalizedResultContext): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed insert id for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n}\n\nfunction malformedNormalizedResult(\n context: NormalizedResultContext,\n resultIndex?: number\n): QueryError {\n const position =\n resultIndex === undefined ? \"\" : ` at batch result index ${resultIndex}`;\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed normalized result for operation \"${context.operation}\"${position}; expected { rows: object[], rowCount: safe non-negative integer }.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n ...(resultIndex === undefined ? {} : { resultIndex }),\n },\n }\n );\n}\n\nexport function isNormalizedResultRow(\n value: unknown\n): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction hasNormalizedRows(value: unknown): value is Record<string, unknown>[] {\n if (!Array.isArray(value)) return false;\n for (let index = 0; index < value.length; index += 1) {\n if (!(Object.hasOwn(value, index) && isNormalizedResultRow(value[index]))) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Assert the single cross-driver success contract. Empty row arrays and a\n * rowCount of zero are valid; missing fields, non-record rows, and invented\n * counts are not.\n */\nexport function assertNormalizedQueryResult(\n result: QueryResult<unknown> | undefined,\n context: NormalizedResultContext,\n resultIndex?: number\n): void {\n const hasValidInsertId =\n result?.insertId === undefined ||\n (typeof result.insertId === \"bigint\" && result.insertId >= 0n) ||\n (typeof result.insertId === \"number\" &&\n Number.isFinite(result.insertId) &&\n Number.isSafeInteger(result.insertId) &&\n result.insertId >= 0);\n if (\n !(isNormalizedResultRow(result) && hasNormalizedRows(result.rows)) ||\n typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0 ||\n !hasValidInsertId\n ) {\n throw malformedNormalizedResult(context, resultIndex);\n }\n}\n\n/**\n * Native and planned batches must return one normalized result for each\n * submitted statement, in the same order.\n */\nexport function assertNormalizedBatchResults(\n results: readonly QueryResult<unknown>[],\n expectedStatementCount: number,\n context: NormalizedResultContext\n): void {\n if (!Array.isArray(results) || results.length !== expectedStatementCount) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw new QueryError(\n `Driver \"${context.provider}\" returned ${actualResultCount} results for operation \"${context.operation}\"; expected ${expectedStatementCount}, one per statement.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n expectedStatementCount,\n actualResultCount,\n },\n }\n );\n }\n\n for (let resultIndex = 0; resultIndex < results.length; resultIndex += 1) {\n assertNormalizedQueryResult(results[resultIndex], context, resultIndex);\n }\n}\n"],"mappings":"4MA0BA,MAAa,EACX,OAAO,OAAO,cAAiB,SAAW,OAAO,aAAe,IAAA,GCzB5D,EAAuB,OAAO,4BAA4B,CAGhE,SAAgB,uBAAyC,EAAa,CAOpE,OANA,OAAO,eAAe,EAAO,EAAsB,CACjD,aAAc,GACd,WAAY,GACZ,MAAO,GACP,SAAU,GACX,CAAC,CACK,EAIT,SAAgB,qBAAqB,EAAwB,CAC3D,OAAO,QAAQ,IAAI,EAAO,EAAqB,GAAK,GCftD,MAAM,EAAqB,IAAI,QAG/B,SAAgB,0BAA0B,EAAe,EAAsB,CAC7E,EAAmB,IAAI,EAAO,EAAU,CAI1C,SAAgB,0BACd,EACA,EACQ,CACR,IAAM,EAAY,EAAmB,IAAI,EAAO,CAEhD,O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