viborm 1.5.0 → 1.6.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 (277) hide show
  1. package/README.md +4 -2
  2. package/dist/{adapter-internals-Cy2QEBnH.mjs → adapter-internals-DULbfdmQ.mjs} +1 -1
  3. package/dist/{adapter-internals-Cy2QEBnH.mjs.map → adapter-internals-DULbfdmQ.mjs.map} +1 -1
  4. package/dist/{adapter-namespace-NnXlXR8c.mjs → adapter-namespace-CFtC8LbT.mjs} +2 -2
  5. package/dist/{adapter-namespace-NnXlXR8c.mjs.map → adapter-namespace-CFtC8LbT.mjs.map} +1 -1
  6. package/dist/{adapter-result-parser-D6lluSMi.mjs → adapter-result-parser-C0vW9am8.mjs} +1 -1
  7. package/dist/{adapter-result-parser-D6lluSMi.mjs.map → adapter-result-parser-C0vW9am8.mjs.map} +1 -1
  8. package/dist/adapters.d.mts +1 -1
  9. package/dist/adapters.mjs +1 -1
  10. package/dist/{array-literal-BsbbSLw3.mjs → array-literal-Dohoq5rT.mjs} +1 -1
  11. package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-Dohoq5rT.mjs.map} +1 -1
  12. package/dist/base-wlv81COV.mjs +2 -0
  13. package/dist/base-wlv81COV.mjs.map +1 -0
  14. package/dist/{batch-refs-BYCu1JnQ.mjs → batch-refs-cBYAKzaE.mjs} +2 -2
  15. package/dist/{batch-refs-BYCu1JnQ.mjs.map → batch-refs-cBYAKzaE.mjs.map} +1 -1
  16. package/dist/bind-parameter-capacity-4OU6feZG.mjs +2 -0
  17. package/dist/{bind-parameter-capacity-D6p9HrbB.mjs.map → bind-parameter-capacity-4OU6feZG.mjs.map} +1 -1
  18. package/dist/{builder-BxCr9ANq.mjs → builder-D0GQK-fA.mjs} +2 -2
  19. package/dist/{builder-BxCr9ANq.mjs.map → builder-D0GQK-fA.mjs.map} +1 -1
  20. package/dist/bun-sql.d.mts +1 -1
  21. package/dist/bun-sql.mjs +1 -1
  22. package/dist/bun-sqlite.d.mts +1 -1
  23. package/dist/bun-sqlite.mjs +1 -1
  24. package/dist/bun-sqlite.mjs.map +1 -1
  25. package/dist/cache/cloudflare-kv.d.mts +1 -1
  26. package/dist/cache/cloudflare-kv.mjs +1 -1
  27. package/dist/cache/memory.d.mts +1 -1
  28. package/dist/cache/memory.mjs +1 -1
  29. package/dist/cache/memory.mjs.map +1 -1
  30. package/dist/cache.d.mts +1 -1
  31. package/dist/cache.mjs +1 -1
  32. package/dist/cache.mjs.map +1 -1
  33. package/dist/{canonical-json-acY4dQNQ.mjs → canonical-json-D_FgOt4S.mjs} +2 -2
  34. package/dist/{canonical-json-acY4dQNQ.mjs.map → canonical-json-D_FgOt4S.mjs.map} +1 -1
  35. package/dist/chain-BQoDfo80.mjs +2 -0
  36. package/dist/{chain-C4EUyLzF.mjs.map → chain-BQoDfo80.mjs.map} +1 -1
  37. package/dist/cli.mjs +1 -1
  38. package/dist/client-BCcIdDl8.mjs +49 -0
  39. package/dist/client-BCcIdDl8.mjs.map +1 -0
  40. package/dist/client-BqgVSbk0.mjs +2 -0
  41. package/dist/client-BqgVSbk0.mjs.map +1 -0
  42. package/dist/{client-D-XiaClb.d.mts → client-C5BGyg5n.d.mts} +3 -3
  43. package/dist/client.d.mts +1 -1
  44. package/dist/client.mjs +1 -1
  45. package/dist/{clock-CJotKAxc.mjs → clock-QtW83Dcm.mjs} +1 -1
  46. package/dist/{clock-CJotKAxc.mjs.map → clock-QtW83Dcm.mjs.map} +1 -1
  47. package/dist/config.d.mts +2 -2
  48. package/dist/config.mjs +1 -1
  49. package/dist/{current-C2fZL9Ln.mjs → current-CEWlNJcP.mjs} +1 -1
  50. package/dist/{current-C2fZL9Ln.mjs.map → current-CEWlNJcP.mjs.map} +1 -1
  51. package/dist/d1.d.mts +1 -1
  52. package/dist/d1.mjs +1 -1
  53. package/dist/d1.mjs.map +1 -1
  54. package/dist/{datetime-physical-codec-CFoeuitT.mjs → datetime-physical-codec-Bl6M6vF5.mjs} +2 -2
  55. package/dist/{datetime-physical-codec-CFoeuitT.mjs.map → datetime-physical-codec-Bl6M6vF5.mjs.map} +1 -1
  56. package/dist/driver-Dv2GJyGs.mjs +2 -0
  57. package/dist/{driver-BqD-3_jO.mjs.map → driver-Dv2GJyGs.mjs.map} +1 -1
  58. package/dist/driver-szWYBmjD.mjs +2 -0
  59. package/dist/{driver-DseQwbsu.mjs.map → driver-szWYBmjD.mjs.map} +1 -1
  60. package/dist/driver.d.mts +1 -1
  61. package/dist/driver.mjs +1 -1
  62. package/dist/error-mapping-DRY49A3C.mjs +2 -0
  63. package/dist/error-mapping-DRY49A3C.mjs.map +1 -0
  64. package/dist/every-DIG9CPly.mjs +2 -0
  65. package/dist/{every-CqR4_Xsx.mjs.map → every-DIG9CPly.mjs.map} +1 -1
  66. package/dist/execution-context-_oajgBi4.mjs +2 -0
  67. package/dist/execution-context-_oajgBi4.mjs.map +1 -0
  68. package/dist/{fs-estate-N_F2YqYa.mjs → fs-estate-DNCM7hYC.mjs} +2 -2
  69. package/dist/{fs-estate-N_F2YqYa.mjs.map → fs-estate-DNCM7hYC.mjs.map} +1 -1
  70. package/dist/{geo-area-codec-4W5b7whM.mjs → geo-area-codec-H50rrGiF.mjs} +2 -2
  71. package/dist/{geo-area-codec-4W5b7whM.mjs.map → geo-area-codec-H50rrGiF.mjs.map} +1 -1
  72. package/dist/geo-point-codec-mjROsQX-.mjs +2 -0
  73. package/dist/{geo-point-codec-pAWYj5ZZ.mjs.map → geo-point-codec-mjROsQX-.mjs.map} +1 -1
  74. package/dist/{hydration-Az2rjp5a.mjs → hydration-BQ7tYLtA.mjs} +2 -2
  75. package/dist/{hydration-Az2rjp5a.mjs.map → hydration-BQ7tYLtA.mjs.map} +1 -1
  76. package/dist/{identifier-conversion-ufaCNi9E.mjs → identifier-conversion-DV63mwKG.mjs} +2 -2
  77. package/dist/{identifier-conversion-ufaCNi9E.mjs.map → identifier-conversion-DV63mwKG.mjs.map} +1 -1
  78. package/dist/{identity-CmRos0Yf.mjs → identity-B75EaVTM.mjs} +2 -2
  79. package/dist/{identity-CmRos0Yf.mjs.map → identity-B75EaVTM.mjs.map} +1 -1
  80. package/dist/{index-Ci8b13Lm.d.mts → index-DRX_LLQM.d.mts} +47 -8
  81. package/dist/index.d.mts +2 -2
  82. package/dist/index.mjs +1 -1
  83. package/dist/index.mjs.map +1 -1
  84. package/dist/instrumentation.d.mts +1 -1
  85. package/dist/instrumentation.mjs +1 -1
  86. package/dist/{invariant-D_fIjY_z.mjs → invariant-B5znICP_.mjs} +1 -1
  87. package/dist/{invariant-D_fIjY_z.mjs.map → invariant-B5znICP_.mjs.map} +1 -1
  88. package/dist/{json-number-CGXpPu4D.mjs → json-number-DoseUwuo.mjs} +1 -1
  89. package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DoseUwuo.mjs.map} +1 -1
  90. package/dist/key-rszcmZdB.mjs +2 -0
  91. package/dist/{key-CyLRw0ne.mjs.map → key-rszcmZdB.mjs.map} +1 -1
  92. package/dist/{libsql-DnbEwMY5.mjs → libsql-CAZVcr9G.mjs} +2 -2
  93. package/dist/{libsql-DnbEwMY5.mjs.map → libsql-CAZVcr9G.mjs.map} +1 -1
  94. package/dist/libsql.d.mts +1 -1
  95. package/dist/libsql.mjs +1 -1
  96. package/dist/{memory-CJ7m33Gi.mjs → memory-CqWRO6-3.mjs} +2 -2
  97. package/dist/{memory-CJ7m33Gi.mjs.map → memory-CqWRO6-3.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-OE5D32qo.mjs +2 -0
  113. package/dist/migrations-OE5D32qo.mjs.map +1 -0
  114. package/dist/migrations.d.mts +5 -5
  115. package/dist/migrations.mjs +1 -1
  116. package/dist/{mysql-9C0lSVzX.mjs → mysql-BPPBSJzl.mjs} +2 -2
  117. package/dist/{mysql-9C0lSVzX.mjs.map → mysql-BPPBSJzl.mjs.map} +1 -1
  118. package/dist/mysql-adapter-Dbo7l0lI.mjs +2 -0
  119. package/dist/mysql-adapter-Dbo7l0lI.mjs.map +1 -0
  120. package/dist/mysql2.d.mts +1 -1
  121. package/dist/mysql2.mjs +1 -1
  122. package/dist/{native-types-asNCr26n.mjs → native-types-6wCGP1a1.mjs} +1 -1
  123. package/dist/{native-types-asNCr26n.mjs.map → native-types-6wCGP1a1.mjs.map} +1 -1
  124. package/dist/neon-http.d.mts +1 -1
  125. package/dist/neon-http.mjs +1 -1
  126. package/dist/neon-http.mjs.map +1 -1
  127. package/dist/normalized-result-23DWxZVY.mjs +2 -0
  128. package/dist/{normalized-result-BF7gr4_b.mjs.map → normalized-result-23DWxZVY.mjs.map} +1 -1
  129. package/dist/{object-store-H7fJwgPR.d.mts → object-store-Cs3AueG5.d.mts} +4 -4
  130. package/dist/{object-store-WjVilDvN.mjs → object-store-DmnlQy7V.mjs} +2 -2
  131. package/dist/{object-store-WjVilDvN.mjs.map → object-store-DmnlQy7V.mjs.map} +1 -1
  132. package/dist/observation-BcT8Cs3d.mjs +2 -0
  133. package/dist/observation-BcT8Cs3d.mjs.map +1 -0
  134. package/dist/on.d.mts +80 -0
  135. package/dist/on.mjs +2 -0
  136. package/dist/on.mjs.map +1 -0
  137. package/dist/permissions.d.mts +1 -1
  138. package/dist/permissions.mjs +1 -1
  139. package/dist/pg.d.mts +1 -1
  140. package/dist/pg.mjs +1 -1
  141. package/dist/pg.mjs.map +1 -1
  142. package/dist/pglite.d.mts +1 -1
  143. package/dist/pglite.mjs +1 -1
  144. package/dist/{physical-C4D-979R.mjs → physical-DT6C54w7.mjs} +2 -2
  145. package/dist/{physical-C4D-979R.mjs.map → physical-DT6C54w7.mjs.map} +1 -1
  146. package/dist/pinned-session-BdON2d0V.mjs +2 -0
  147. package/dist/{pinned-session-FYOFV_gB.mjs.map → pinned-session-BdON2d0V.mjs.map} +1 -1
  148. package/dist/planetscale.d.mts +1 -1
  149. package/dist/planetscale.mjs +1 -1
  150. package/dist/planetscale.mjs.map +1 -1
  151. package/dist/{planner-CUcPdJwD.d.mts → planner-BxCcoO8s.d.mts} +32 -2
  152. package/dist/{postgres-BPeNXAZR.mjs → postgres-BK_aOx_C.mjs} +44 -37
  153. package/dist/postgres-BK_aOx_C.mjs.map +1 -0
  154. package/dist/postgres-adapter-CVazEDVI.mjs +2 -0
  155. package/dist/postgres-adapter-CVazEDVI.mjs.map +1 -0
  156. package/dist/postgres-adapter-DxhZu7Qw.mjs +2 -0
  157. package/dist/{postgres-adapter-B7hzWhky.mjs.map → postgres-adapter-DxhZu7Qw.mjs.map} +1 -1
  158. package/dist/postgres-result-DYeVeHuT.mjs +2 -0
  159. package/dist/{postgres-result-BCUQf8b_.mjs.map → postgres-result-DYeVeHuT.mjs.map} +1 -1
  160. package/dist/postgres.d.mts +1 -1
  161. package/dist/postgres.mjs +1 -1
  162. package/dist/postgres.mjs.map +1 -1
  163. package/dist/{provider-limits-D0ECF7_Q.mjs → provider-limits-zLe7S_0W.mjs} +2 -2
  164. package/dist/{provider-limits-D0ECF7_Q.mjs.map → provider-limits-zLe7S_0W.mjs.map} +1 -1
  165. package/dist/{validation-gwZYm3Yn.mjs → query-CTna5P9o.mjs} +2 -2
  166. package/dist/query-CTna5P9o.mjs.map +1 -0
  167. package/dist/{relation-bound-BrZLsSke.mjs → relation-bound-Bj7X-EUE.mjs} +1 -1
  168. package/dist/{relation-bound-BrZLsSke.mjs.map → relation-bound-Bj7X-EUE.mjs.map} +1 -1
  169. package/dist/{result-parsing-CQf_eCl8.mjs → result-parsing-C2044903.mjs} +1 -1
  170. package/dist/{result-parsing-CQf_eCl8.mjs.map → result-parsing-C2044903.mjs.map} +1 -1
  171. package/dist/result-shape-C8QFUuIt.mjs +2 -0
  172. package/dist/{result-shape-ic2j3Tze.mjs.map → result-shape-C8QFUuIt.mjs.map} +1 -1
  173. package/dist/rows-D7ns2l0U.mjs +2 -0
  174. package/dist/{rows-YyvK9MDz.mjs.map → rows-D7ns2l0U.mjs.map} +1 -1
  175. package/dist/{scalar-Dyns7kc7.mjs → scalar-D6QmJ22_.mjs} +2 -2
  176. package/dist/{scalar-Dyns7kc7.mjs.map → scalar-D6QmJ22_.mjs.map} +1 -1
  177. package/dist/schema/json.d.mts +1 -1
  178. package/dist/schema/json.mjs +1 -1
  179. package/dist/{schema-CUm_yh6L.mjs → schema-CY9kOwJ-.mjs} +2 -2
  180. package/dist/{schema-CUm_yh6L.mjs.map → schema-CY9kOwJ-.mjs.map} +1 -1
  181. package/dist/{schema-introspection-LpRNeSG2.mjs → schema-introspection-CfqmM3Cz.mjs} +2 -2
  182. package/dist/{schema-introspection-LpRNeSG2.mjs.map → schema-introspection-CfqmM3Cz.mjs.map} +1 -1
  183. package/dist/schema.d.mts +1 -1
  184. package/dist/schema.mjs +1 -1
  185. package/dist/{select-assembly-BjT_fDbu.mjs → select-assembly-D7FEenz2.mjs} +2 -2
  186. package/dist/select-assembly-D7FEenz2.mjs.map +1 -0
  187. package/dist/{settle-C4w1GfTU.mjs → settle-CObilv26.mjs} +2 -2
  188. package/dist/{settle-C4w1GfTU.mjs.map → settle-CObilv26.mjs.map} +1 -1
  189. package/dist/{sha256-_Nu4s32f.mjs → sha256-Da07rzvR.mjs} +1 -1
  190. package/dist/{sha256-_Nu4s32f.mjs.map → sha256-Da07rzvR.mjs.map} +1 -1
  191. package/dist/soft-delete.d.mts +1 -1
  192. package/dist/{sql-BvHwL73I.mjs → sql-DGtEeP8z.mjs} +1 -1
  193. package/dist/{sql-BvHwL73I.mjs.map → sql-DGtEeP8z.mjs.map} +1 -1
  194. package/dist/{sql-statement-tokens-4J5l5Lyt.mjs → sql-statement-tokens-DL3ooNs7.mjs} +1 -1
  195. package/dist/{sql-statement-tokens-4J5l5Lyt.mjs.map → sql-statement-tokens-DL3ooNs7.mjs.map} +1 -1
  196. package/dist/sql.d.mts +1 -1
  197. package/dist/sql.mjs +1 -1
  198. package/dist/sqlite-adapter-DqT6HeDs.mjs +2 -0
  199. package/dist/sqlite-adapter-DqT6HeDs.mjs.map +1 -0
  200. package/dist/{sqlite-utils-C5_KQPZn.mjs → sqlite-utils-DeDlMJKj.mjs} +2 -2
  201. package/dist/{sqlite-utils-C5_KQPZn.mjs.map → sqlite-utils-DeDlMJKj.mjs.map} +1 -1
  202. package/dist/sqlite3.d.mts +1 -1
  203. package/dist/sqlite3.mjs +1 -1
  204. package/dist/sqlite3.mjs.map +1 -1
  205. package/dist/{standard-sql-DmKF8msN.mjs → standard-sql-BErrm6AV.mjs} +2 -2
  206. package/dist/{standard-sql-DmKF8msN.mjs.map → standard-sql-BErrm6AV.mjs.map} +1 -1
  207. package/dist/{suppressed-failure-Bdo2aK81.mjs → suppressed-failure-3C4sFXvH.mjs} +1 -1
  208. package/dist/{suppressed-failure-Bdo2aK81.mjs.map → suppressed-failure-3C4sFXvH.mjs.map} +1 -1
  209. package/dist/{to-many-DxQuOBuq.mjs → to-many-DqYv9-vp.mjs} +2 -2
  210. package/dist/{to-many-DxQuOBuq.mjs.map → to-many-DqYv9-vp.mjs.map} +1 -1
  211. package/dist/{transaction-4dfqals6.mjs → transaction-D5LHYn-r.mjs} +2 -2
  212. package/dist/{transaction-4dfqals6.mjs.map → transaction-D5LHYn-r.mjs.map} +1 -1
  213. package/dist/{transaction-operation-CU1zlxiG.mjs → transaction-operation-Co3hw8yz.mjs} +2 -2
  214. package/dist/{transaction-operation-CU1zlxiG.mjs.map → transaction-operation-Co3hw8yz.mjs.map} +1 -1
  215. package/dist/{types-C5Oxz9yp.mjs → types-CJgtjXtu.mjs} +1 -1
  216. package/dist/{types-C5Oxz9yp.mjs.map → types-CJgtjXtu.mjs.map} +1 -1
  217. package/dist/{utils-CQ2nQwwO.mjs → utils-DooFtO1V.mjs} +3 -3
  218. package/dist/utils-DooFtO1V.mjs.map +1 -0
  219. package/dist/{v-BcroBusN.mjs → v-yKivkoka.mjs} +2 -2
  220. package/dist/{v-BcroBusN.mjs.map → v-yKivkoka.mjs.map} +1 -1
  221. package/dist/validation-pfpKPPZ_.mjs +2 -0
  222. package/dist/validation-pfpKPPZ_.mjs.map +1 -0
  223. package/dist/{validation-CjWRiLWU.mjs → validation-u-sZDdfD.mjs} +2 -2
  224. package/dist/{validation-CjWRiLWU.mjs.map → validation-u-sZDdfD.mjs.map} +1 -1
  225. package/dist/validation.d.mts +1 -1
  226. package/dist/validation.mjs +1 -1
  227. package/dist/{validator-yrGnrsAo.mjs → validator-XVm02V0K.mjs} +2 -2
  228. package/dist/{validator-yrGnrsAo.mjs.map → validator-XVm02V0K.mjs.map} +1 -1
  229. package/dist/version-WvqPqZJ4.mjs +2 -0
  230. package/dist/{version-Dt62tqkV.mjs.map → version-WvqPqZJ4.mjs.map} +1 -1
  231. package/dist/write-sinks-CoB5PPw9.mjs +2 -0
  232. package/dist/write-sinks-CoB5PPw9.mjs.map +1 -0
  233. package/dist/writes-CD0mNS5-.mjs +2 -0
  234. package/dist/writes-CD0mNS5-.mjs.map +1 -0
  235. package/package.json +36 -15
  236. package/dist/base-D3m1S7Uc.mjs +0 -2
  237. package/dist/base-D3m1S7Uc.mjs.map +0 -1
  238. package/dist/bind-parameter-capacity-D6p9HrbB.mjs +0 -2
  239. package/dist/cache-CIPRF-pz.mjs +0 -2
  240. package/dist/cache-CIPRF-pz.mjs.map +0 -1
  241. package/dist/chain-C4EUyLzF.mjs +0 -2
  242. package/dist/client-CnXO0M-E.mjs +0 -49
  243. package/dist/client-CnXO0M-E.mjs.map +0 -1
  244. package/dist/client-DACEO6tS.mjs +0 -2
  245. package/dist/client-DACEO6tS.mjs.map +0 -1
  246. package/dist/driver-BqD-3_jO.mjs +0 -2
  247. package/dist/driver-DseQwbsu.mjs +0 -2
  248. package/dist/error-mapping-6op318w6.mjs +0 -2
  249. package/dist/error-mapping-6op318w6.mjs.map +0 -1
  250. package/dist/every-CqR4_Xsx.mjs +0 -2
  251. package/dist/execution-context-asSCmyas.mjs +0 -2
  252. package/dist/execution-context-asSCmyas.mjs.map +0 -1
  253. package/dist/geo-point-codec-pAWYj5ZZ.mjs +0 -2
  254. package/dist/key-CyLRw0ne.mjs +0 -2
  255. package/dist/migrations-Bn1SatyB.mjs +0 -2
  256. package/dist/migrations-Bn1SatyB.mjs.map +0 -1
  257. package/dist/mysql-adapter-B1U35CJn.mjs +0 -2
  258. package/dist/mysql-adapter-B1U35CJn.mjs.map +0 -1
  259. package/dist/normalized-result-BF7gr4_b.mjs +0 -2
  260. package/dist/observation-Co72iCd1.mjs +0 -2
  261. package/dist/observation-Co72iCd1.mjs.map +0 -1
  262. package/dist/pinned-session-FYOFV_gB.mjs +0 -2
  263. package/dist/postgres-BPeNXAZR.mjs.map +0 -1
  264. package/dist/postgres-adapter-B7hzWhky.mjs +0 -2
  265. package/dist/postgres-adapter-CJmoxTW7.mjs +0 -2
  266. package/dist/postgres-adapter-CJmoxTW7.mjs.map +0 -1
  267. package/dist/postgres-result-BCUQf8b_.mjs +0 -2
  268. package/dist/result-shape-ic2j3Tze.mjs +0 -2
  269. package/dist/rows-YyvK9MDz.mjs +0 -2
  270. package/dist/select-assembly-BjT_fDbu.mjs.map +0 -1
  271. package/dist/sqlite-adapter-CLWY4B8w.mjs +0 -2
  272. package/dist/sqlite-adapter-CLWY4B8w.mjs.map +0 -1
  273. package/dist/utils-CQ2nQwwO.mjs.map +0 -1
  274. package/dist/validation-gwZYm3Yn.mjs.map +0 -1
  275. package/dist/version-Dt62tqkV.mjs +0 -2
  276. /package/dist/{contract-Dw0FR78e.d.mts → contract-H_WiAUaR.d.mts} +0 -0
  277. /package/dist/{sql-Q_twK-wW.d.mts → sql-CF5Xi6z-.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-adapter-B7hzWhky.mjs","names":[],"sources":["../src/drivers/shared/postgres-adapter.ts"],"sourcesContent":["import { PostgresAdapter } from \"@adapters/databases/postgres/postgres-adapter\";\nimport { ClientInitializationError, unsupportedVector } from \"@errors\";\nimport { defineImmutableDriverFact } from \"./driver-options\";\n\n/**\n * Install a PostgreSQL driver's adapter: `pgvector` alone decides the vector\n * capability, `postgis` the spatial one, `sharedRelationBodies` whether a\n * statement states each relation body it repeats once (the default: the\n * answers are the same and the statement smaller; `false` keeps every body\n * inline, as 1.2.4 spelled it), `relationsPerStatement` the relations a\n * statement may reference before it trades plans for fewer (absent:\n * unbounded until the server says otherwise, `relation-bound.ts`; PlanetScale\n * Neki needs 256).\n */\nexport function installPostgresAdapter(\n driver: object,\n namespace: string | undefined,\n options: {\n readonly pgvector?: boolean;\n readonly postgis?: boolean;\n readonly sharedRelationBodies?: boolean;\n readonly relationsPerStatement?: number;\n }\n): void {\n const adapter = new PostgresAdapter(namespace, options.postgis === true);\n adapter.capabilities.supportsVector = options.pgvector === true;\n const bound = options.relationsPerStatement;\n // A bound of 0, a fraction or NaN would escalate every statement or none.\n if (bound !== undefined && !(Number.isSafeInteger(bound) && bound > 0))\n throw new ClientInitializationError(\n `The \"relationsPerStatement\" option must be a positive integer (256 for PlanetScale Neki); received ${typeof bound === \"number\" ? bound : `type \"${typeof bound}\"`}.`\n );\n if (options.sharedRelationBodies !== false) {\n adapter.capabilities.sharesRelationBodies = true;\n adapter.capabilities.relationsPerStatement = bound;\n }\n if (!options.pgvector) adapter.vector = unsupportedVector;\n defineImmutableDriverFact(driver, \"adapter\", adapter);\n}\n"],"mappings":"4LAcA,SAAgB,uBACd,EACA,EACA,EAMM,CACN,IAAM,EAAU,IAAI,EAAgB,EAAW,EAAQ,UAAY,GAAK,CACxE,EAAQ,aAAa,eAAiB,EAAQ,WAAa,GAC3D,IAAM,EAAQ,EAAQ,sBAEtB,GAAI,IAAU,IAAA,IAAa,EAAE,OAAO,cAAc,EAAM,EAAI,EAAQ,GAClE,MAAM,IAAI,EACR,sGAAsG,OAAO,GAAU,SAAW,EAAQ,SAAS,OAAO,EAAM,GAAG,GACpK,CACC,EAAQ,uBAAyB,KACnC,EAAQ,aAAa,qBAAuB,GAC5C,EAAQ,aAAa,sBAAwB,GAE1C,EAAQ,WAAU,EAAQ,OAAS,GACxC,EAA0B,EAAQ,UAAW,EAAQ"}
1
+ {"version":3,"file":"postgres-adapter-DxhZu7Qw.mjs","names":[],"sources":["../src/drivers/shared/postgres-adapter.ts"],"sourcesContent":["import { PostgresAdapter } from \"@adapters/databases/postgres/postgres-adapter\";\nimport { ClientInitializationError, unsupportedVector } from \"@errors\";\nimport { defineImmutableDriverFact } from \"./driver-options\";\n\n/**\n * Install a PostgreSQL driver's adapter: `pgvector` alone decides the vector\n * capability, `postgis` the spatial one, `sharedRelationBodies` whether a\n * statement states each relation body it repeats once (the default: the\n * answers are the same and the statement smaller; `false` keeps every body\n * inline, as 1.2.4 spelled it), `relationsPerStatement` the relations a\n * statement may reference before it trades plans for fewer (absent:\n * unbounded until the server says otherwise, `relation-bound.ts`; PlanetScale\n * Neki needs 256).\n */\nexport function installPostgresAdapter(\n driver: object,\n namespace: string | undefined,\n options: {\n readonly pgvector?: boolean;\n readonly postgis?: boolean;\n readonly sharedRelationBodies?: boolean;\n readonly relationsPerStatement?: number;\n }\n): void {\n const adapter = new PostgresAdapter(namespace, options.postgis === true);\n adapter.capabilities.supportsVector = options.pgvector === true;\n const bound = options.relationsPerStatement;\n // A bound of 0, a fraction or NaN would escalate every statement or none.\n if (bound !== undefined && !(Number.isSafeInteger(bound) && bound > 0))\n throw new ClientInitializationError(\n `The \"relationsPerStatement\" option must be a positive integer (256 for PlanetScale Neki); received ${typeof bound === \"number\" ? bound : `type \"${typeof bound}\"`}.`\n );\n if (options.sharedRelationBodies !== false) {\n adapter.capabilities.sharesRelationBodies = true;\n adapter.capabilities.relationsPerStatement = bound;\n }\n if (!options.pgvector) adapter.vector = unsupportedVector;\n defineImmutableDriverFact(driver, \"adapter\", adapter);\n}\n"],"mappings":"kLAcA,SAAgB,uBACd,EACA,EACA,EAMM,CACN,IAAM,EAAU,IAAI,EAAgB,EAAW,EAAQ,UAAY,GAAK,CACxE,EAAQ,aAAa,eAAiB,EAAQ,WAAa,GAC3D,IAAM,EAAQ,EAAQ,sBAEtB,GAAI,IAAU,IAAA,IAAa,EAAE,OAAO,cAAc,EAAM,EAAI,EAAQ,GAClE,MAAM,IAAI,EACR,sGAAsG,OAAO,GAAU,SAAW,EAAQ,SAAS,OAAO,EAAM,GAAG,GACpK,CACC,EAAQ,uBAAyB,KACnC,EAAQ,aAAa,qBAAuB,GAC5C,EAAQ,aAAa,sBAAwB,GAE1C,EAAQ,WAAU,EAAQ,OAAS,GACxC,EAA0B,EAAQ,UAAW,EAAQ"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t,r as n}from"./normalized-result-23DWxZVY.mjs";import{d as r}from"./query-CTna5P9o.mjs";const i=/\s+/,a=/^[A-Za-z]+$/,o=new Set([`COPY`,`DELETE`,`FETCH`,`INSERT`,`MERGE`,`MOVE`,`SELECT`,`UPDATE`]),s=new Set(`ALTER.ANALYZE.BEGIN.CALL.CHECKPOINT.CLOSE.CLUSTER.COMMENT.COMMIT.CREATE.DEALLOCATE.DECLARE.DISCARD.DO.DROP.END.EXPLAIN.GRANT.IMPORT.LISTEN.LOAD.LOCK.NOTIFY.PREPARE.REASSIGN.REFRESH.REINDEX.RELEASE.RESET.REVOKE.ROLLBACK.SAVEPOINT.SECURITY.SET.SHOW.START.TRUNCATE.UNLISTEN.VACUUM`.split(`.`));function malformedPostgresResult(e,t){return new r(`Driver "${e.provider}" returned malformed PostgreSQL result metadata for operation "${e.operation}": ${t}.`,{meta:n(e)})}function normalizePostgresRowCount(e,n,r,c){if(!Array.isArray(r))throw malformedPostgresResult(c,`the rows payload is not an array`);if(typeof n!=`string`||n.trim()===``)throw malformedPostgresResult(c,`the command tag is invalid`);let[l]=n.trim().split(i,1);if(!(l&&a.test(l)))throw malformedPostgresResult(c,`the command tag is invalid`);let u=l.toUpperCase(),d=o.has(u),f=s.has(u);if(!(d||f))throw malformedPostgresResult(c,`the command tag is unknown`);if(e!==null)return t(e,c);if(d)throw malformedPostgresResult(c,`command ${u} requires a numeric row count`);return r.length}export{normalizePostgresRowCount as t};
2
+ //# sourceMappingURL=postgres-result-DYeVeHuT.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-result-BCUQf8b_.mjs","names":[],"sources":["../src/drivers/shared/postgres-result.ts"],"sourcesContent":["import { QueryError } from \"@errors\";\nimport {\n createNormalizedResultMeta,\n type NormalizedResultContext,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\n\nconst COMMAND_SEPARATOR_REGEX = /\\s+/;\nconst COMMAND_TOKEN_REGEX = /^[A-Za-z]+$/;\n\nconst COUNTED_COMMANDS = new Set([\n \"COPY\",\n \"DELETE\",\n \"FETCH\",\n \"INSERT\",\n \"MERGE\",\n \"MOVE\",\n \"SELECT\",\n \"UPDATE\",\n]);\n\nconst NULLABLE_COUNT_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"BEGIN\",\n \"CALL\",\n \"CHECKPOINT\",\n \"CLOSE\",\n \"CLUSTER\",\n \"COMMENT\",\n \"COMMIT\",\n \"CREATE\",\n \"DEALLOCATE\",\n \"DECLARE\",\n \"DISCARD\",\n \"DO\",\n \"DROP\",\n \"END\",\n \"EXPLAIN\",\n \"GRANT\",\n \"IMPORT\",\n \"LISTEN\",\n \"LOAD\",\n \"LOCK\",\n \"NOTIFY\",\n \"PREPARE\",\n \"REASSIGN\",\n \"REFRESH\",\n \"REINDEX\",\n \"RELEASE\",\n \"RESET\",\n \"REVOKE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"SECURITY\",\n \"SET\",\n \"SHOW\",\n \"START\",\n \"TRUNCATE\",\n \"UNLISTEN\",\n \"VACUUM\",\n]);\n\nfunction malformedPostgresResult(\n context: NormalizedResultContext,\n reason: string\n): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned malformed PostgreSQL result metadata for operation \"${context.operation}\": ${reason}.`,\n { meta: createNormalizedResultMeta(context) }\n );\n}\n\n/**\n * PostgreSQL command tags carry a numeric count only for a defined set of\n * commands. Other known tags legitimately expose null, while missing metadata\n * and null counts for counted commands are malformed provider successes.\n */\nexport function normalizePostgresRowCount(\n value: unknown,\n command: unknown,\n rows: unknown,\n context: NormalizedResultContext\n): number {\n if (!Array.isArray(rows)) {\n throw malformedPostgresResult(context, \"the rows payload is not an array\");\n }\n if (typeof command !== \"string\" || command.trim() === \"\") {\n throw malformedPostgresResult(context, \"the command tag is invalid\");\n }\n const [commandToken] = command.trim().split(COMMAND_SEPARATOR_REGEX, 1);\n if (!(commandToken && COMMAND_TOKEN_REGEX.test(commandToken))) {\n throw malformedPostgresResult(context, \"the command tag is invalid\");\n }\n const normalizedCommand = commandToken.toUpperCase();\n const isCountedCommand = COUNTED_COMMANDS.has(normalizedCommand);\n const isNullableCountCommand = NULLABLE_COUNT_COMMANDS.has(normalizedCommand);\n if (!(isCountedCommand || isNullableCountCommand)) {\n throw malformedPostgresResult(context, \"the command tag is unknown\");\n }\n if (value !== null) {\n return normalizeProviderRowCount(value, context);\n }\n if (isCountedCommand) {\n throw malformedPostgresResult(\n context,\n `command ${normalizedCommand} requires a numeric row count`\n );\n }\n return rows.length;\n}\n"],"mappings":"mJAOA,MAAM,EAA0B,MAC1B,EAAsB,cAEtB,EAAmB,IAAI,IAAI,CAC/B,OACA,SACA,QACA,SACA,QACA,OACA,SACA,SACD,CAAC,CAEI,EAA0B,IAAI,IAAI,kSAwCvC,CAAC,CAEF,SAAS,wBACP,EACA,EACY,CACZ,OAAO,IAAI,EACT,WAAW,EAAQ,SAAS,iEAAiE,EAAQ,UAAU,KAAK,EAAO,GAC3H,CAAE,KAAM,EAA2B,EAAQ,CAAE,CAC9C,CAQH,SAAgB,0BACd,EACA,EACA,EACA,EACQ,CACR,GAAI,CAAC,MAAM,QAAQ,EAAK,CACtB,MAAM,wBAAwB,EAAS,mCAAmC,CAE5E,GAAI,OAAO,GAAY,UAAY,EAAQ,MAAM,GAAK,GACpD,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,GAAM,CAAC,GAAgB,EAAQ,MAAM,CAAC,MAAM,EAAyB,EAAE,CACvE,GAAI,EAAE,GAAgB,EAAoB,KAAK,EAAa,EAC1D,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,IAAM,EAAoB,EAAa,aAAa,CAC9C,EAAmB,EAAiB,IAAI,EAAkB,CAC1D,EAAyB,EAAwB,IAAI,EAAkB,CAC7E,GAAI,EAAE,GAAoB,GACxB,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,GAAI,IAAU,KACZ,OAAO,EAA0B,EAAO,EAAQ,CAElD,GAAI,EACF,MAAM,wBACJ,EACA,WAAW,EAAkB,+BAC9B,CAEH,OAAO,EAAK"}
1
+ {"version":3,"file":"postgres-result-DYeVeHuT.mjs","names":[],"sources":["../src/drivers/shared/postgres-result.ts"],"sourcesContent":["import { QueryError } from \"@errors\";\nimport {\n createNormalizedResultMeta,\n type NormalizedResultContext,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\n\nconst COMMAND_SEPARATOR_REGEX = /\\s+/;\nconst COMMAND_TOKEN_REGEX = /^[A-Za-z]+$/;\n\nconst COUNTED_COMMANDS = new Set([\n \"COPY\",\n \"DELETE\",\n \"FETCH\",\n \"INSERT\",\n \"MERGE\",\n \"MOVE\",\n \"SELECT\",\n \"UPDATE\",\n]);\n\nconst NULLABLE_COUNT_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"BEGIN\",\n \"CALL\",\n \"CHECKPOINT\",\n \"CLOSE\",\n \"CLUSTER\",\n \"COMMENT\",\n \"COMMIT\",\n \"CREATE\",\n \"DEALLOCATE\",\n \"DECLARE\",\n \"DISCARD\",\n \"DO\",\n \"DROP\",\n \"END\",\n \"EXPLAIN\",\n \"GRANT\",\n \"IMPORT\",\n \"LISTEN\",\n \"LOAD\",\n \"LOCK\",\n \"NOTIFY\",\n \"PREPARE\",\n \"REASSIGN\",\n \"REFRESH\",\n \"REINDEX\",\n \"RELEASE\",\n \"RESET\",\n \"REVOKE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"SECURITY\",\n \"SET\",\n \"SHOW\",\n \"START\",\n \"TRUNCATE\",\n \"UNLISTEN\",\n \"VACUUM\",\n]);\n\nfunction malformedPostgresResult(\n context: NormalizedResultContext,\n reason: string\n): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned malformed PostgreSQL result metadata for operation \"${context.operation}\": ${reason}.`,\n { meta: createNormalizedResultMeta(context) }\n );\n}\n\n/**\n * PostgreSQL command tags carry a numeric count only for a defined set of\n * commands. Other known tags legitimately expose null, while missing metadata\n * and null counts for counted commands are malformed provider successes.\n */\nexport function normalizePostgresRowCount(\n value: unknown,\n command: unknown,\n rows: unknown,\n context: NormalizedResultContext\n): number {\n if (!Array.isArray(rows)) {\n throw malformedPostgresResult(context, \"the rows payload is not an array\");\n }\n if (typeof command !== \"string\" || command.trim() === \"\") {\n throw malformedPostgresResult(context, \"the command tag is invalid\");\n }\n const [commandToken] = command.trim().split(COMMAND_SEPARATOR_REGEX, 1);\n if (!(commandToken && COMMAND_TOKEN_REGEX.test(commandToken))) {\n throw malformedPostgresResult(context, \"the command tag is invalid\");\n }\n const normalizedCommand = commandToken.toUpperCase();\n const isCountedCommand = COUNTED_COMMANDS.has(normalizedCommand);\n const isNullableCountCommand = NULLABLE_COUNT_COMMANDS.has(normalizedCommand);\n if (!(isCountedCommand || isNullableCountCommand)) {\n throw malformedPostgresResult(context, \"the command tag is unknown\");\n }\n if (value !== null) {\n return normalizeProviderRowCount(value, context);\n }\n if (isCountedCommand) {\n throw malformedPostgresResult(\n context,\n `command ${normalizedCommand} requires a numeric row count`\n );\n }\n return rows.length;\n}\n"],"mappings":"8IAOA,MAAM,EAA0B,MAC1B,EAAsB,cAEtB,EAAmB,IAAI,IAAI,CAC/B,OACA,SACA,QACA,SACA,QACA,OACA,SACA,SACD,CAAC,CAEI,EAA0B,IAAI,IAAI,kSAwCvC,CAAC,CAEF,SAAS,wBACP,EACA,EACY,CACZ,OAAO,IAAI,EACT,WAAW,EAAQ,SAAS,iEAAiE,EAAQ,UAAU,KAAK,EAAO,GAC3H,CAAE,KAAM,EAA2B,EAAQ,CAAE,CAC9C,CAQH,SAAgB,0BACd,EACA,EACA,EACA,EACQ,CACR,GAAI,CAAC,MAAM,QAAQ,EAAK,CACtB,MAAM,wBAAwB,EAAS,mCAAmC,CAE5E,GAAI,OAAO,GAAY,UAAY,EAAQ,MAAM,GAAK,GACpD,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,GAAM,CAAC,GAAgB,EAAQ,MAAM,CAAC,MAAM,EAAyB,EAAE,CACvE,GAAI,EAAE,GAAgB,EAAoB,KAAK,EAAa,EAC1D,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,IAAM,EAAoB,EAAa,aAAa,CAC9C,EAAmB,EAAiB,IAAI,EAAkB,CAC1D,EAAyB,EAAwB,IAAI,EAAkB,CAC7E,GAAI,EAAE,GAAoB,GACxB,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,GAAI,IAAU,KACZ,OAAO,EAA0B,EAAO,EAAQ,CAElD,GAAI,EACF,MAAM,wBACJ,EACA,WAAW,EAAkB,+BAC9B,CAEH,OAAO,EAAK"}
@@ -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, d as MigrationSessionAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-Ci8b13Lm.mjs";
1
+ import { A as Schema, An as TransactionOptionSupport, At as DriverConfig, F as LinkedClientConfig, Fn as QueryResult, Ft as VibORMClient, Pn as QueryExecutionContext, Pt as NoExtraDriverConfigKeys, d as MigrationSessionAttestation, kn as DriverTransactionOptions, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-DRX_LLQM.mjs";
2
2
  import postgres, { Options, Sql } from "postgres";
3
3
 
4
4
  //#region src/drivers/postgres/index.d.ts
package/dist/postgres.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{d as n,l as r,r as i}from"./error-mapping-6op318w6.mjs";import{r as a}from"./validation-gwZYm3Yn.mjs";import{n as o}from"./suppressed-failure-Bdo2aK81.mjs";import{c as s}from"./execution-context-asSCmyas.mjs";import{n as c}from"./client-DACEO6tS.mjs";import{i as l,t as u}from"./pinned-session-FYOFV_gB.mjs";import{c as d,d as f,f as p,i as m,o as h,s as g,t as _,u as v}from"./driver-DseQwbsu.mjs";import{t as y}from"./postgres-result-BCUQf8b_.mjs";import{t as b}from"./postgres-adapter-B7hzWhky.mjs";import{n as x,t as S}from"./relation-bound-BrZLsSke.mjs";import C from"postgres";const w={timestamp:{to:1114,from:[1082,1114,1184],serialize:e=>e instanceof Date?e.toISOString():String(e),parse:e=>e},json:{to:114,from:[114,3802],serialize:e=>typeof e==`string`?e:JSON.stringify(e),parse:e=>JSON.parse(e)}};function encodeListParameters(e){return e.map(e=>Array.isArray(e)?`{${e.map(e=>e===null?`NULL`:`"${String(e).replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`).join(`,`)}}`:e)}const withVibormTypes=(e={})=>({...e,types:{...w,...e.types}}),T={client:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,databaseUrl:!0,namespace:!0,migrationSessionAttestation:!0},isTransaction=e=>`savepoint`in e;var PostgresDriver=class extends _{maxBindParametersPerStatement=65533;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`postgres`);let t=f(e);this.driverOptions={databaseUrl:e.databaseUrl,options:{...e.options}},this.suppliedClient=e.client;let{host:n,hostname:r}=this.driverOptions.options??{};if(g(`postgres`,e,!!(this.suppliedClient||n||r)),this.suppliedClient){for(let e of[1082,1114,1184])if(this.suppliedClient.options?.parsers[e]!==w.timestamp?.parse)throw new a(`A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).`,{meta:{driver:`postgres`,operation:`configuration`}});this.client=this.suppliedClient}b(this,t,e),S(this.adapter,()=>{let e=this.client;return e&&!isTransaction(e)?e.parameters.server_version:void 0}),h(this,`migrationSessionAttestation`,v(e))}migrationSessionEndpoints(){let{databaseUrl:e,options:t}=this.driverOptions;return[e,t?.host,t?.hostname,...this.suppliedClient?.options.host??[]]}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let{databaseUrl:e,options:t}=this.driverOptions;return e?C(p(e),withVibormTypes(t)):C(withVibormTypes(t))}async closeClient(e){e!==this.suppliedClient&&await e.end()}async execute(e,t,n,r){return this.executeQuery(e,t,encodeListParameters(n),r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=await e.unsafe(t,n,{prepare:this.driverOptions.options?.prepare===!0}).catch(e=>{throw x(this.adapter,e),e});return{rows:o,rowCount:y(o.count,o.command,o,{provider:`postgres`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said`}}async transaction(e,t,i,a){if(isTransaction(e))throw r(this.driverName);return n({run:async t=>{let n=!1;try{return await e.begin(e=>(n=!0,t(e)))}catch(t){throw!n&&this.isConnectionFailure(t)&&await this.recoverFailedBegin(e,t,a?.maxWaitMs??5e3),t}},callback:t,phases:s(i),close:async()=>void 0})}isConnectionFailure(e){let n=i(e,{driverName:this.driverName,dialect:this.dialect});return n.code===t.CONNECTION_FAILED||n.code===t.CONNECTION_TIMEOUT}async recoverFailedBegin(e,t,n){let r=Date.now()+n;for(let n=0;n<2;n++){let n=r-Date.now();if(n<=0)break;try{(await m(()=>e.reserve(),e=>e.release(),n,{driverName:this.driverName,form:`callback`})).release();return}catch(e){if(o(t,e),!this.isConnectionFailure(e))break}}}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(isTransaction(e))throw r(this.driverName);let t=await e.reserve();return{session:t,release:(n,r)=>l({driverName:this.driverName,discard:n,lost:r,reset:()=>t.unsafe(`SELECT pg_advisory_unlock_all()`),release:()=>t.release(),closeOwnedTransport:e===this.suppliedClient?void 0:async()=>{this.client=null,this.initPromise=null,await e.end({timeout:u/1e3})}})}}};function createClient(e){d(e,`postgres`,T);let{client:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e,o=f(e),s=v(e);return c(e,new PostgresDriver({client:t,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:o,migrationSessionAttestation:s}))}export{PostgresDriver,createClient,w as vibormTypes};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{l as t}from"./execution-context-_oajgBi4.mjs";import{n}from"./base-wlv81COV.mjs";import{f as r,r as i,u as a}from"./error-mapping-DRY49A3C.mjs";import{t as o}from"./query-CTna5P9o.mjs";import{n as s}from"./suppressed-failure-3C4sFXvH.mjs";import{n as c}from"./client-BqgVSbk0.mjs";import{i as l,t as u}from"./pinned-session-BdON2d0V.mjs";import{c as d,d as f,f as p,i as m,o as h,s as g,t as _,u as v}from"./driver-szWYBmjD.mjs";import{t as y}from"./postgres-result-DYeVeHuT.mjs";import{t as b}from"./postgres-adapter-DxhZu7Qw.mjs";import{n as x,t as S}from"./relation-bound-Bj7X-EUE.mjs";import C from"postgres";const w={timestamp:{to:1114,from:[1082,1114,1184],serialize:e=>e instanceof Date?e.toISOString():String(e),parse:e=>e},json:{to:114,from:[114,3802],serialize:e=>typeof e==`string`?e:JSON.stringify(e),parse:e=>JSON.parse(e)}};function encodeListParameters(e){return e.map(e=>Array.isArray(e)?`{${e.map(e=>e===null?`NULL`:`"${String(e).replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`).join(`,`)}}`:e)}const withVibormTypes=(e={})=>({...e,types:{...w,...e.types}}),T={client:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,databaseUrl:!0,namespace:!0,migrationSessionAttestation:!0},isTransaction=e=>`savepoint`in e;var PostgresDriver=class extends _{maxBindParametersPerStatement=65533;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`postgres`);let t=f(e);this.driverOptions={databaseUrl:e.databaseUrl,options:{...e.options}},this.suppliedClient=e.client;let{host:n,hostname:r}=this.driverOptions.options??{};if(g(`postgres`,e,!!(this.suppliedClient||n||r)),this.suppliedClient){for(let e of[1082,1114,1184])if(this.suppliedClient.options?.parsers[e]!==w.timestamp?.parse)throw new o(`A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).`,{meta:{driver:`postgres`,operation:`configuration`}});this.client=this.suppliedClient}b(this,t,e),S(this.adapter,()=>{let e=this.client;return e&&!isTransaction(e)?e.parameters.server_version:void 0}),h(this,`migrationSessionAttestation`,v(e))}migrationSessionEndpoints(){let{databaseUrl:e,options:t}=this.driverOptions;return[e,t?.host,t?.hostname,...this.suppliedClient?.options.host??[]]}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let{databaseUrl:e,options:t}=this.driverOptions;return e?C(p(e),withVibormTypes(t)):C(withVibormTypes(t))}async closeClient(e){e!==this.suppliedClient&&await e.end()}async execute(e,t,n,r){return this.executeQuery(e,t,encodeListParameters(n),r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=await e.unsafe(t,n,{prepare:this.driverOptions.options?.prepare===!0}).catch(e=>{throw x(this.adapter,e),e});return{rows:o,rowCount:y(o.count,o.command,o,{provider:`postgres`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said`}}async transaction(e,n,i,o){if(isTransaction(e))throw a(this.driverName);return r({run:async t=>{let n=!1;try{return await e.begin(e=>(n=!0,t(e)))}catch(t){throw!n&&this.isConnectionFailure(t)&&await this.recoverFailedBegin(e,t,o?.maxWaitMs??5e3),t}},callback:n,phases:t(i),close:async()=>void 0})}isConnectionFailure(e){let t=i(e,{driverName:this.driverName,dialect:this.dialect});return t.code===n.CONNECTION_FAILED||t.code===n.CONNECTION_TIMEOUT}async recoverFailedBegin(e,t,n){let r=Date.now()+n;for(let n=0;n<2;n++){let n=r-Date.now();if(n<=0)break;try{(await m(()=>e.reserve(),e=>e.release(),n,{driverName:this.driverName,form:`callback`})).release();return}catch(e){if(s(t,e),!this.isConnectionFailure(e))break}}}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(isTransaction(e))throw a(this.driverName);let t=await e.reserve();return{session:t,release:(n,r)=>l({driverName:this.driverName,discard:n,lost:r,reset:()=>t.unsafe(`SELECT pg_advisory_unlock_all()`),release:()=>t.release(),closeOwnedTransport:e===this.suppliedClient?void 0:async()=>{this.client=null,this.initPromise=null,await e.end({timeout:u/1e3})}})}}};function createClient(e){d(e,`postgres`,T);let{client:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e,o=f(e),s=v(e);return c(e,new PostgresDriver({client:t,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:o,migrationSessionAttestation:s}))}export{PostgresDriver,createClient,w as vibormTypes};
2
2
  //# sourceMappingURL=postgres.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.mjs","names":[],"sources":["../src/drivers/postgres/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (postgres.js)\n *\n * Driver implementation for postgres.js - a modern, fast PostgreSQL client.\n *\n * Generated statements use unsafe(query, values, queryOptions). Preparation\n * defaults to false for pooler compatibility; options.prepare: true opts into\n * the provider's prepared-statement reuse on compatible sessions.\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, VibORMErrorCode } from \"@errors\";\nimport postgres, {\n type Options as PostgresOptionsType,\n type Sql as PostgresSql,\n} from \"postgres\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { normalizeDriverError } from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n releaseReservedPostgresSession,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { CLEANUP_BOUND_MS } from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { boundByServer, learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\nexport type PostgresOptions = PostgresOptionsType<\n Record<string, postgres.PostgresType>\n>;\n\ntype PostgresTransaction = postgres.TransactionSql<Record<string, unknown>>;\n\nexport interface PostgresDriverOptions {\n client?: PostgresSql<Record<string, unknown>>;\n options?: PostgresOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. PlanetScale Neki refuses more than 256: absent, the driver reads each connection's startup, 256 on Neki and before the first connection, none elsewhere. A stated bound always wins. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Your claim, at your risk, that every connection this client opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport const vibormTypes: Record<string, postgres.PostgresType> = {\n // TIMESTAMP WITHOUT TIME ZONE (1114): postgres.js builds process-local\n // Dates, shifting the stored UTC wall clock by the process timezone. Keep\n // the raw string — the shared result parser builds a UTC Date from it,\n // matching every other driver. (DATE already arrives as a string.)\n timestamp: {\n to: 1114,\n from: [1082, 1114, 1184],\n serialize: (value: unknown) =>\n value instanceof Date ? value.toISOString() : String(value),\n parse: (value: string) => value,\n },\n // The adapter binds a `JsonParameter` carrier (src/sql/json-parameter.ts),\n // which the object arm serializes to its canonical text via `toJSON`. The\n // string arm exists for raw SQL: a caller's own JSON text bound to a\n // json/jsonb parameter must not be JSON.stringify'd a second time once the\n // server declares the param type — that double-encodes the stored value.\n json: {\n to: 114,\n from: [114, 3802],\n serialize: (value: unknown) =>\n typeof value === \"string\" ? value : JSON.stringify(value),\n parse: (value: string) => JSON.parse(value),\n },\n};\n\n/** Bind validated one-dimensional lists as PostgreSQL text, letting SQL infer\n * the column type; postgres.js otherwise guesses bigint[]/boolean[] wrongly. */\nfunction encodeListParameters(params: unknown[]): unknown[] {\n return params.map((value) =>\n Array.isArray(value)\n ? `{${value.map((member) => (member === null ? \"NULL\" : `\"${String(member).replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`)).join(\",\")}}`\n : value\n );\n}\n\nconst withVibormTypes = (options: PostgresOptions = {}): PostgresOptions => ({\n ...options,\n types: { ...vibormTypes, ...options.types },\n});\n\nexport type PostgresClientConfig<C extends DriverConfig> =\n PostgresDriverOptions & C;\n\nconst POSTGRES_CONFIG_KEYS: Record<keyof PostgresDriverOptions, true> = {\n client: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n databaseUrl: true,\n namespace: true,\n migrationSessionAttestation: true,\n};\n\ntype PostgresClient = PostgresSql<Record<string, unknown>>;\n\nconst isTransaction = (\n client: PostgresClient | PostgresTransaction\n): client is PostgresTransaction => {\n return \"savepoint\" in client;\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PostgresDriver extends Driver<\n PostgresClient,\n PostgresTransaction\n> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_533;\n\n private readonly driverOptions: PostgresDriverOptions;\n /**\n * The EXACT transport the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's transport while believing it had made its own.\n */\n private readonly suppliedClient: PostgresClient | undefined;\n\n constructor(options: PostgresDriverOptions = {}) {\n super(\"postgresql\", \"postgres\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = {\n databaseUrl: options.databaseUrl,\n options: { ...options.options },\n };\n this.suppliedClient = options.client;\n const { host, hostname } = this.driverOptions.options ?? {};\n refuseEmptyDatabaseUrl(\n \"postgres\",\n options,\n Boolean(this.suppliedClient || host || hostname)\n );\n\n if (this.suppliedClient) {\n for (const oid of [1082, 1114, 1184]) {\n if (\n this.suppliedClient.options?.parsers[oid] !==\n vibormTypes.timestamp?.parse\n ) {\n throw new ClientInitializationError(\n \"A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).\",\n { meta: { driver: \"postgres\", operation: \"configuration\" } }\n );\n }\n }\n this.client = this.suppliedClient;\n }\n\n installPostgresAdapter(this, namespace, options);\n // postgres.js keeps every parameter status its connections received.\n boundByServer(this.adapter, () => {\n const client = this.client;\n return client && !isTransaction(client)\n ? client.parameters.server_version\n : undefined;\n });\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's client connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const { databaseUrl, options } = this.driverOptions;\n return [\n databaseUrl,\n options?.host,\n options?.hostname,\n ...(this.suppliedClient?.options.host ?? []),\n ];\n }\n\n /**\n * The transport this driver connects through.\n *\n * A caller's transport is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second one behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<PostgresClient> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n // postgres.js reads the URL for the keys it carries and lets every key\n // set in options win, which is the documented precedence.\n const { databaseUrl, options } = this.driverOptions;\n return databaseUrl\n ? postgres(systemRootAsVerifyFull(databaseUrl), withVibormTypes(options))\n : postgres(withVibormTypes(options));\n }\n\n /**\n * A supplied transport belongs to the caller, who may be sharing it with\n * other clients — two schema-scoped estates over one transport is the\n * documented shape — and §5.3's rule is that VibORM never changes a caller's\n * connection state. `$disconnect()` used to end it regardless, so\n * disconnecting one client tore down every other consumer of that transport.\n *\n * The test is on the transport's IDENTITY against what construction\n * captured, so it answers for the transport actually being closed rather than\n * for whatever the caller's record says now.\n */\n protected async closeClient(sql: PostgresClient): Promise<void> {\n if (sql === this.suppliedClient) {\n return;\n }\n await sql.end();\n }\n\n protected async execute<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n // postgres.js unsafe() takes (query, parameters?, queryOptions?)\n // parameters must be cast as postgres expects specific types\n return this.executeQuery(\n client,\n sqlStr,\n encodeListParameters(params),\n context,\n \"execute\"\n );\n }\n\n protected async executeRaw<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sqlStr, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client\n .unsafe<T[]>(sqlStr, params, {\n prepare: this.driverOptions.options?.prepare === true,\n })\n .catch((error: unknown) => {\n learnRelationLimit(this.adapter, error);\n throw error;\n });\n return {\n rows: result,\n rowCount: normalizePostgresRowCount(\n result.count,\n result.command,\n result,\n {\n provider: \"postgres\",\n operation,\n }\n ),\n };\n }\n\n /**\n * postgres.js owns BEGIN inside `client.begin()`, so the isolation level goes\n * in as the transaction's first statement. It also owns connection\n * acquisition inside that same call: there is no acquisition step VibORM can\n * bound or abandon, so `maxWait` is refused rather than faked.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said\",\n };\n }\n\n protected async transaction<T>(\n client: PostgresClient | PostgresTransaction,\n fn: (tx: PostgresTransaction) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n return runProviderManagedTransaction({\n run: async (callback) => {\n let entered = false;\n try {\n return await client.begin((tx) => {\n entered = true;\n return callback(tx);\n });\n } catch (error) {\n if (!entered && this.isConnectionFailure(error))\n await this.recoverFailedBegin(\n client,\n error,\n options?.maxWaitMs ?? 5000\n );\n throw error;\n }\n },\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n private isConnectionFailure(error: unknown): boolean {\n const failure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n });\n return (\n failure.code === VibORMErrorCode.CONNECTION_FAILED ||\n failure.code === VibORMErrorCode.CONNECTION_TIMEOUT\n );\n }\n\n private async recoverFailedBegin(\n client: PostgresClient,\n primary: unknown,\n maxWaitMs: number\n ): Promise<void> {\n // postgres.js can retain a fatal response across reconnect, rejecting the\n // next acquisition before dispatch. Drain that startup error with leases,\n // never caller SQL; the callback above has provably not entered. A drain\n // that cannot connect needs no quarantine: a connection failure before the\n // callback leaves no live session, and the next lease that connects\n // clears the state.\n const deadline = Date.now() + maxWaitMs;\n for (let attempt = 0; attempt < 2; attempt++) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n try {\n const lease = await acquireWithMaxWait(\n () => client.reserve(),\n (late) => late.release(),\n remaining,\n { driverName: this.driverName, form: \"callback\" }\n );\n lease.release();\n return;\n } catch (cleanup) {\n withSuppressedFailure(primary, cleanup);\n if (!this.isConnectionFailure(cleanup)) break;\n }\n }\n }\n\n /**\n * One `reserve()` result — plan §3.5's pinned producer for postgres.js.\n *\n * postgres.js exposes no destroy for a reserved connection, so a condemned\n * session is reset with PostgreSQL's own instrument before it goes back:\n * `pg_advisory_unlock_all()` releases every advisory lock the session still\n * holds, which is the exact state that must not survive the release. When\n * that reset FAILS the session's lock state is unknown, and the shared rule\n * below is what keeps it out of the pool — the reset's failure is not\n * swallowed, because a session that may still hold VibORM's migration lock is\n * not something a caller can be left unaware of.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PostgresClient | PostgresTransaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const reserved = await client.reserve();\n return {\n session: reserved,\n release: (discard, lost) =>\n releaseReservedPostgresSession({\n driverName: this.driverName,\n discard,\n lost,\n reset: () => reserved.unsafe(\"SELECT pg_advisory_unlock_all()\"),\n release: () => reserved.release(),\n // Ownership is the identity this driver settled at construction,\n // never a later read of the caller's options object: a `client` key\n // deleted after construction would otherwise make VibORM end a\n // transport it was handed.\n closeOwnedTransport:\n client === this.suppliedClient\n ? undefined\n : async () => {\n // Withdrawn BEFORE the close, never after it. `end()` can\n // reject — a socket already gone is the ordinary way — and\n // withdrawing afterwards left this exact transport installed,\n // so the next ordinary query ran on the connection whose\n // advisory-lock state is precisely what could not be\n // accounted for. The in-flight connect goes with it, because\n // `getClient()` answers from it when `client` is null.\n this.client = null;\n this.initPromise = null;\n // Bounded: an abandoned connection whose socket stopped\n // answering never finishes on its own, and `end()` without\n // a timeout waits for it. Past the bound postgres.js\n // terminates every connection of this transport.\n await client.end({ timeout: CLEANUP_BOUND_MS / 1000 });\n },\n }),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PostgresClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PostgresDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PostgresDriver }\n >]: LinkedClientConfig<C & { driver: PostgresDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"postgres\", POSTGRES_CONFIG_KEYS);\n const { client, options = {}, pgvector, postgis, databaseUrl } = config;\n const namespace = resolveNamespaceOption(config);\n const migrationSessionAttestation =\n resolveMigrationSessionAttestationOption(config);\n\n const driver = new PostgresDriver({\n client,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n migrationSessionAttestation,\n });\n\n return createClientFromDriverConfig<S, C, PostgresDriver>(config, driver);\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"postgres.mjs","names":[],"sources":["../src/drivers/postgres/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (postgres.js)\n *\n * Driver implementation for postgres.js - a modern, fast PostgreSQL client.\n *\n * Generated statements use unsafe(query, values, queryOptions). Preparation\n * defaults to false for pooler compatibility; options.prepare: true opts into\n * the provider's prepared-statement reuse on compatible sessions.\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, VibORMErrorCode } from \"@errors\";\nimport postgres, {\n type Options as PostgresOptionsType,\n type Sql as PostgresSql,\n} from \"postgres\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { normalizeDriverError } from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n releaseReservedPostgresSession,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { CLEANUP_BOUND_MS } from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { boundByServer, learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\nexport type PostgresOptions = PostgresOptionsType<\n Record<string, postgres.PostgresType>\n>;\n\ntype PostgresTransaction = postgres.TransactionSql<Record<string, unknown>>;\n\nexport interface PostgresDriverOptions {\n client?: PostgresSql<Record<string, unknown>>;\n options?: PostgresOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. PlanetScale Neki refuses more than 256: absent, the driver reads each connection's startup, 256 on Neki and before the first connection, none elsewhere. A stated bound always wins. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Your claim, at your risk, that every connection this client opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport const vibormTypes: Record<string, postgres.PostgresType> = {\n // TIMESTAMP WITHOUT TIME ZONE (1114): postgres.js builds process-local\n // Dates, shifting the stored UTC wall clock by the process timezone. Keep\n // the raw string — the shared result parser builds a UTC Date from it,\n // matching every other driver. (DATE already arrives as a string.)\n timestamp: {\n to: 1114,\n from: [1082, 1114, 1184],\n serialize: (value: unknown) =>\n value instanceof Date ? value.toISOString() : String(value),\n parse: (value: string) => value,\n },\n // The adapter binds a `JsonParameter` carrier (src/sql/json-parameter.ts),\n // which the object arm serializes to its canonical text via `toJSON`. The\n // string arm exists for raw SQL: a caller's own JSON text bound to a\n // json/jsonb parameter must not be JSON.stringify'd a second time once the\n // server declares the param type — that double-encodes the stored value.\n json: {\n to: 114,\n from: [114, 3802],\n serialize: (value: unknown) =>\n typeof value === \"string\" ? value : JSON.stringify(value),\n parse: (value: string) => JSON.parse(value),\n },\n};\n\n/** Bind validated one-dimensional lists as PostgreSQL text, letting SQL infer\n * the column type; postgres.js otherwise guesses bigint[]/boolean[] wrongly. */\nfunction encodeListParameters(params: unknown[]): unknown[] {\n return params.map((value) =>\n Array.isArray(value)\n ? `{${value.map((member) => (member === null ? \"NULL\" : `\"${String(member).replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`)).join(\",\")}}`\n : value\n );\n}\n\nconst withVibormTypes = (options: PostgresOptions = {}): PostgresOptions => ({\n ...options,\n types: { ...vibormTypes, ...options.types },\n});\n\nexport type PostgresClientConfig<C extends DriverConfig> =\n PostgresDriverOptions & C;\n\nconst POSTGRES_CONFIG_KEYS: Record<keyof PostgresDriverOptions, true> = {\n client: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n databaseUrl: true,\n namespace: true,\n migrationSessionAttestation: true,\n};\n\ntype PostgresClient = PostgresSql<Record<string, unknown>>;\n\nconst isTransaction = (\n client: PostgresClient | PostgresTransaction\n): client is PostgresTransaction => {\n return \"savepoint\" in client;\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PostgresDriver extends Driver<\n PostgresClient,\n PostgresTransaction\n> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_533;\n\n private readonly driverOptions: PostgresDriverOptions;\n /**\n * The EXACT transport the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's transport while believing it had made its own.\n */\n private readonly suppliedClient: PostgresClient | undefined;\n\n constructor(options: PostgresDriverOptions = {}) {\n super(\"postgresql\", \"postgres\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = {\n databaseUrl: options.databaseUrl,\n options: { ...options.options },\n };\n this.suppliedClient = options.client;\n const { host, hostname } = this.driverOptions.options ?? {};\n refuseEmptyDatabaseUrl(\n \"postgres\",\n options,\n Boolean(this.suppliedClient || host || hostname)\n );\n\n if (this.suppliedClient) {\n for (const oid of [1082, 1114, 1184]) {\n if (\n this.suppliedClient.options?.parsers[oid] !==\n vibormTypes.timestamp?.parse\n ) {\n throw new ClientInitializationError(\n \"A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).\",\n { meta: { driver: \"postgres\", operation: \"configuration\" } }\n );\n }\n }\n this.client = this.suppliedClient;\n }\n\n installPostgresAdapter(this, namespace, options);\n // postgres.js keeps every parameter status its connections received.\n boundByServer(this.adapter, () => {\n const client = this.client;\n return client && !isTransaction(client)\n ? client.parameters.server_version\n : undefined;\n });\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's client connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const { databaseUrl, options } = this.driverOptions;\n return [\n databaseUrl,\n options?.host,\n options?.hostname,\n ...(this.suppliedClient?.options.host ?? []),\n ];\n }\n\n /**\n * The transport this driver connects through.\n *\n * A caller's transport is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second one behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<PostgresClient> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n // postgres.js reads the URL for the keys it carries and lets every key\n // set in options win, which is the documented precedence.\n const { databaseUrl, options } = this.driverOptions;\n return databaseUrl\n ? postgres(systemRootAsVerifyFull(databaseUrl), withVibormTypes(options))\n : postgres(withVibormTypes(options));\n }\n\n /**\n * A supplied transport belongs to the caller, who may be sharing it with\n * other clients — two schema-scoped estates over one transport is the\n * documented shape — and §5.3's rule is that VibORM never changes a caller's\n * connection state. `$disconnect()` used to end it regardless, so\n * disconnecting one client tore down every other consumer of that transport.\n *\n * The test is on the transport's IDENTITY against what construction\n * captured, so it answers for the transport actually being closed rather than\n * for whatever the caller's record says now.\n */\n protected async closeClient(sql: PostgresClient): Promise<void> {\n if (sql === this.suppliedClient) {\n return;\n }\n await sql.end();\n }\n\n protected async execute<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n // postgres.js unsafe() takes (query, parameters?, queryOptions?)\n // parameters must be cast as postgres expects specific types\n return this.executeQuery(\n client,\n sqlStr,\n encodeListParameters(params),\n context,\n \"execute\"\n );\n }\n\n protected async executeRaw<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sqlStr, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client\n .unsafe<T[]>(sqlStr, params, {\n prepare: this.driverOptions.options?.prepare === true,\n })\n .catch((error: unknown) => {\n learnRelationLimit(this.adapter, error);\n throw error;\n });\n return {\n rows: result,\n rowCount: normalizePostgresRowCount(\n result.count,\n result.command,\n result,\n {\n provider: \"postgres\",\n operation,\n }\n ),\n };\n }\n\n /**\n * postgres.js owns BEGIN inside `client.begin()`, so the isolation level goes\n * in as the transaction's first statement. It also owns connection\n * acquisition inside that same call: there is no acquisition step VibORM can\n * bound or abandon, so `maxWait` is refused rather than faked.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said\",\n };\n }\n\n protected async transaction<T>(\n client: PostgresClient | PostgresTransaction,\n fn: (tx: PostgresTransaction) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n return runProviderManagedTransaction({\n run: async (callback) => {\n let entered = false;\n try {\n return await client.begin((tx) => {\n entered = true;\n return callback(tx);\n });\n } catch (error) {\n if (!entered && this.isConnectionFailure(error))\n await this.recoverFailedBegin(\n client,\n error,\n options?.maxWaitMs ?? 5000\n );\n throw error;\n }\n },\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n private isConnectionFailure(error: unknown): boolean {\n const failure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n });\n return (\n failure.code === VibORMErrorCode.CONNECTION_FAILED ||\n failure.code === VibORMErrorCode.CONNECTION_TIMEOUT\n );\n }\n\n private async recoverFailedBegin(\n client: PostgresClient,\n primary: unknown,\n maxWaitMs: number\n ): Promise<void> {\n // postgres.js can retain a fatal response across reconnect, rejecting the\n // next acquisition before dispatch. Drain that startup error with leases,\n // never caller SQL; the callback above has provably not entered. A drain\n // that cannot connect needs no quarantine: a connection failure before the\n // callback leaves no live session, and the next lease that connects\n // clears the state.\n const deadline = Date.now() + maxWaitMs;\n for (let attempt = 0; attempt < 2; attempt++) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n try {\n const lease = await acquireWithMaxWait(\n () => client.reserve(),\n (late) => late.release(),\n remaining,\n { driverName: this.driverName, form: \"callback\" }\n );\n lease.release();\n return;\n } catch (cleanup) {\n withSuppressedFailure(primary, cleanup);\n if (!this.isConnectionFailure(cleanup)) break;\n }\n }\n }\n\n /**\n * One `reserve()` result — plan §3.5's pinned producer for postgres.js.\n *\n * postgres.js exposes no destroy for a reserved connection, so a condemned\n * session is reset with PostgreSQL's own instrument before it goes back:\n * `pg_advisory_unlock_all()` releases every advisory lock the session still\n * holds, which is the exact state that must not survive the release. When\n * that reset FAILS the session's lock state is unknown, and the shared rule\n * below is what keeps it out of the pool — the reset's failure is not\n * swallowed, because a session that may still hold VibORM's migration lock is\n * not something a caller can be left unaware of.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PostgresClient | PostgresTransaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const reserved = await client.reserve();\n return {\n session: reserved,\n release: (discard, lost) =>\n releaseReservedPostgresSession({\n driverName: this.driverName,\n discard,\n lost,\n reset: () => reserved.unsafe(\"SELECT pg_advisory_unlock_all()\"),\n release: () => reserved.release(),\n // Ownership is the identity this driver settled at construction,\n // never a later read of the caller's options object: a `client` key\n // deleted after construction would otherwise make VibORM end a\n // transport it was handed.\n closeOwnedTransport:\n client === this.suppliedClient\n ? undefined\n : async () => {\n // Withdrawn BEFORE the close, never after it. `end()` can\n // reject — a socket already gone is the ordinary way — and\n // withdrawing afterwards left this exact transport installed,\n // so the next ordinary query ran on the connection whose\n // advisory-lock state is precisely what could not be\n // accounted for. The in-flight connect goes with it, because\n // `getClient()` answers from it when `client` is null.\n this.client = null;\n this.initPromise = null;\n // Bounded: an abandoned connection whose socket stopped\n // answering never finishes on its own, and `end()` without\n // a timeout waits for it. Past the bound postgres.js\n // terminates every connection of this transport.\n await client.end({ timeout: CLEANUP_BOUND_MS / 1000 });\n },\n }),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PostgresClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PostgresDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PostgresDriver }\n >]: LinkedClientConfig<C & { driver: PostgresDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"postgres\", POSTGRES_CONFIG_KEYS);\n const { client, options = {}, pgvector, postgis, databaseUrl } = config;\n const namespace = resolveNamespaceOption(config);\n const migrationSessionAttestation =\n resolveMigrationSessionAttestationOption(config);\n\n const driver = new PostgresDriver({\n client,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n migrationSessionAttestation,\n });\n\n return createClientFromDriverConfig<S, C, PostgresDriver>(config, driver);\n}\n"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{T as t}from"./geo-point-codec-pAWYj5ZZ.mjs";function decimalDialectOf(e){return e===`postgresql`?`pg`:e===`mysql`?`mysql`:`sqlite`}function findDecimalProviderLimitRefusal(e,n){let r=decimalDialectOf(n);for(let[i,a]of Object.entries(e)){let e=a[`~`].state.scalars;for(let[a,o]of Object.entries(e)){let e=o[`~`].state;if(e.type!==`decimal`||e.decimal===void 0)continue;let s=t(r,e.decimal);if(s!==void 0)return{modelName:i,fieldName:a,dialect:n,descriptor:e.decimal,reason:s}}}}function describeDecimalProviderLimitRefusal(e){return`Decimal field '${e.modelName}.${e.fieldName}' cannot be stored by the '${e.dialect}' driver: ${e.reason}.`}export{findDecimalProviderLimitRefusal as n,describeDecimalProviderLimitRefusal as t};
2
- //# sourceMappingURL=provider-limits-D0ECF7_Q.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{T as t}from"./geo-point-codec-mjROsQX-.mjs";function decimalDialectOf(e){return e===`postgresql`?`pg`:e===`mysql`?`mysql`:`sqlite`}function findDecimalProviderLimitRefusal(e,n){let r=decimalDialectOf(n);for(let[i,a]of Object.entries(e)){let e=a[`~`].state.scalars;for(let[a,o]of Object.entries(e)){let e=o[`~`].state;if(e.type!==`decimal`||e.decimal===void 0)continue;let s=t(r,e.decimal);if(s!==void 0)return{modelName:i,fieldName:a,dialect:n,descriptor:e.decimal,reason:s}}}}function describeDecimalProviderLimitRefusal(e){return`Decimal field '${e.modelName}.${e.fieldName}' cannot be stored by the '${e.dialect}' driver: ${e.reason}.`}export{findDecimalProviderLimitRefusal as n,describeDecimalProviderLimitRefusal as t};
2
+ //# sourceMappingURL=provider-limits-zLe7S_0W.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"provider-limits-D0ECF7_Q.mjs","names":[],"sources":["../src/schema/scalars/decimal/provider-limits.ts"],"sourcesContent":["/**\n * The ONE schema-plus-provider fixed-decimal admission decision.\n *\n * A decimal descriptor is a valid schema fact independently of provider\n * limits. The first boundary that combines a complete model map with a chosen\n * provider asks this pure owner whether every declared scalar or list fits.\n * It returns one structured refusal and performs no boundary-specific throw;\n * client and migration composition roots retain their own error classes.\n */\n\nimport type { AnyModel } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport {\n type DecimalDescriptor,\n type DecimalDialect,\n describeProviderLimitRefusal,\n} from \"@validation/primitives/decimal-codec\";\n\ntype ProviderDialect = \"postgresql\" | \"mysql\" | \"sqlite\";\n\nexport interface DecimalProviderLimitRefusal {\n readonly modelName: string;\n readonly fieldName: string;\n readonly dialect: ProviderDialect;\n readonly descriptor: DecimalDescriptor;\n readonly reason: string;\n}\n\n/** The driver's dialect in the decimal codec's physical vocabulary. */\nfunction decimalDialectOf(dialect: ProviderDialect): DecimalDialect {\n if (dialect === \"postgresql\") return \"pg\";\n if (dialect === \"mysql\") return \"mysql\";\n return \"sqlite\";\n}\n\n/** Return the first declared decimal domain the selected provider cannot hold. */\nexport function findDecimalProviderLimitRefusal(\n schema: Record<string, AnyModel>,\n dialect: ProviderDialect\n): DecimalProviderLimitRefusal | undefined {\n const decimalDialect = decimalDialectOf(dialect);\n for (const [modelName, model] of Object.entries(schema)) {\n const scalars: Record<string, Scalar> = model[\"~\"].state.scalars;\n for (const [fieldName, scalar] of Object.entries(scalars)) {\n const state = scalar[\"~\"].state;\n if (state.type !== \"decimal\" || state.decimal === undefined) continue;\n const reason = describeProviderLimitRefusal(\n decimalDialect,\n state.decimal\n );\n if (reason === undefined) continue;\n return {\n modelName,\n fieldName,\n dialect,\n descriptor: state.decimal,\n reason,\n };\n }\n }\n return undefined;\n}\n\n/** The shared diagnostic body; each composition root chooses its error model. */\nexport function describeDecimalProviderLimitRefusal(\n refusal: DecimalProviderLimitRefusal\n): string {\n return `Decimal field '${refusal.modelName}.${refusal.fieldName}' cannot be stored by the '${refusal.dialect}' driver: ${refusal.reason}.`;\n}\n"],"mappings":"4FA6BA,SAAS,iBAAiB,EAA0C,CAGlE,OAFI,IAAY,aAAqB,KACjC,IAAY,QAAgB,QACzB,SAIT,SAAgB,gCACd,EACA,EACyC,CACzC,IAAM,EAAiB,iBAAiB,EAAQ,CAChD,IAAK,GAAM,CAAC,EAAW,KAAU,OAAO,QAAQ,EAAO,CAAE,CACvD,IAAM,EAAkC,EAAM,KAAK,MAAM,QACzD,IAAK,GAAM,CAAC,EAAW,KAAW,OAAO,QAAQ,EAAQ,CAAE,CACzD,IAAM,EAAQ,EAAO,KAAK,MAC1B,GAAI,EAAM,OAAS,WAAa,EAAM,UAAY,IAAA,GAAW,SAC7D,IAAM,EAAS,EACb,EACA,EAAM,QACP,CACG,OAAW,IAAA,GACf,MAAO,CACL,YACA,YACA,UACA,WAAY,EAAM,QAClB,SACD,GAOP,SAAgB,oCACd,EACQ,CACR,MAAO,kBAAkB,EAAQ,UAAU,GAAG,EAAQ,UAAU,6BAA6B,EAAQ,QAAQ,YAAY,EAAQ,OAAO"}
1
+ {"version":3,"file":"provider-limits-zLe7S_0W.mjs","names":[],"sources":["../src/schema/scalars/decimal/provider-limits.ts"],"sourcesContent":["/**\n * The ONE schema-plus-provider fixed-decimal admission decision.\n *\n * A decimal descriptor is a valid schema fact independently of provider\n * limits. The first boundary that combines a complete model map with a chosen\n * provider asks this pure owner whether every declared scalar or list fits.\n * It returns one structured refusal and performs no boundary-specific throw;\n * client and migration composition roots retain their own error classes.\n */\n\nimport type { AnyModel } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport {\n type DecimalDescriptor,\n type DecimalDialect,\n describeProviderLimitRefusal,\n} from \"@validation/primitives/decimal-codec\";\n\ntype ProviderDialect = \"postgresql\" | \"mysql\" | \"sqlite\";\n\nexport interface DecimalProviderLimitRefusal {\n readonly modelName: string;\n readonly fieldName: string;\n readonly dialect: ProviderDialect;\n readonly descriptor: DecimalDescriptor;\n readonly reason: string;\n}\n\n/** The driver's dialect in the decimal codec's physical vocabulary. */\nfunction decimalDialectOf(dialect: ProviderDialect): DecimalDialect {\n if (dialect === \"postgresql\") return \"pg\";\n if (dialect === \"mysql\") return \"mysql\";\n return \"sqlite\";\n}\n\n/** Return the first declared decimal domain the selected provider cannot hold. */\nexport function findDecimalProviderLimitRefusal(\n schema: Record<string, AnyModel>,\n dialect: ProviderDialect\n): DecimalProviderLimitRefusal | undefined {\n const decimalDialect = decimalDialectOf(dialect);\n for (const [modelName, model] of Object.entries(schema)) {\n const scalars: Record<string, Scalar> = model[\"~\"].state.scalars;\n for (const [fieldName, scalar] of Object.entries(scalars)) {\n const state = scalar[\"~\"].state;\n if (state.type !== \"decimal\" || state.decimal === undefined) continue;\n const reason = describeProviderLimitRefusal(\n decimalDialect,\n state.decimal\n );\n if (reason === undefined) continue;\n return {\n modelName,\n fieldName,\n dialect,\n descriptor: state.decimal,\n reason,\n };\n }\n }\n return undefined;\n}\n\n/** The shared diagnostic body; each composition root chooses its error model. */\nexport function describeDecimalProviderLimitRefusal(\n refusal: DecimalProviderLimitRefusal\n): string {\n return `Decimal field '${refusal.modelName}.${refusal.fieldName}' cannot be stored by the '${refusal.dialect}' driver: ${refusal.reason}.`;\n}\n"],"mappings":"4FA6BA,SAAS,iBAAiB,EAA0C,CAGlE,OAFI,IAAY,aAAqB,KACjC,IAAY,QAAgB,QACzB,SAIT,SAAgB,gCACd,EACA,EACyC,CACzC,IAAM,EAAiB,iBAAiB,EAAQ,CAChD,IAAK,GAAM,CAAC,EAAW,KAAU,OAAO,QAAQ,EAAO,CAAE,CACvD,IAAM,EAAkC,EAAM,KAAK,MAAM,QACzD,IAAK,GAAM,CAAC,EAAW,KAAW,OAAO,QAAQ,EAAQ,CAAE,CACzD,IAAM,EAAQ,EAAO,KAAK,MAC1B,GAAI,EAAM,OAAS,WAAa,EAAM,UAAY,IAAA,GAAW,SAC7D,IAAM,EAAS,EACb,EACA,EAAM,QACP,CACG,OAAW,IAAA,GACf,MAAO,CACL,YACA,YACA,UACA,WAAY,EAAM,QAClB,SACD,GAOP,SAAgB,oCACd,EACQ,CACR,MAAO,kBAAkB,EAAQ,UAAU,GAAG,EAAQ,UAAU,6BAA6B,EAAQ,QAAQ,YAAY,EAAQ,OAAO"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,t as n}from"./base-D3m1S7Uc.mjs";var ConnectionError=class extends n{static diagnosticName=`ConnectionError`;constructor(e,n){super(e,n?.code??t.CONNECTION_FAILED,n)}},ClientInitializationError=class extends n{static diagnosticName=`ClientInitializationError`;constructor(e,n){super(e,t.CLIENT_INITIALIZATION,n)}};function isClientInitializationError(e){return e instanceof ClientInitializationError}var QueryError=class extends n{static diagnosticName=`QueryError`;constructor(e,n){super(e,n?.code??t.QUERY_FAILED,n)}},NotFoundError=class extends n{static diagnosticName=`NotFoundError`;constructor(e,n,r){super(`No ${e} record found for ${n}`,t.RECORD_NOT_FOUND,{meta:{...r?.meta,model:e,operation:n}})}},ForbiddenError=class extends n{static diagnosticName=`ForbiddenError`;constructor(e,n,r){super(`The ${n} on ${e} is not permitted${r?.reason?`: ${r.reason}`:``}`,t.FORBIDDEN,{meta:{...r?.meta,model:e,operation:n},cause:r?.cause})}},NestedWriteError=class extends n{static diagnosticName=`NestedWriteError`;constructor(e,n,r){super(e,r?.code??t.NESTED_WRITE_FAILED,{cause:r?.cause,diagnostics:r?.diagnostics,meta:{...r?.meta,relation:n}})}};const r=`Nested write assertion failed: a batch precondition (e.g. a connect/disconnect target or ownership check) did not hold.`;var NestedWriteAssertionError=class extends n{static diagnosticName=`NestedWriteAssertionError`;constructor(e,n){super(e,t.NESTED_WRITE_ASSERTION_FAILED,n)}},FeatureNotSupportedError=class extends n{static diagnosticName=`FeatureNotSupportedError`;constructor(e,n,r){let i=r?`${e}.${n} is not supported. ${r}`:`${e}.${n} is not supported by this driver.`;super(i,t.FEATURE_NOT_SUPPORTED,{meta:{feature:e,method:n}})}},i=class PendingOperationError extends n{static diagnosticName=`PendingOperationError`;constructor(e,t,n){super(e,t,n)}static alreadyExecutedWithDriver(e,n){return new PendingOperationError(`Cannot await a PendingOperation that was already executed with executeWith(). The ${e}.${n}() operation was already executed in a transaction context. Create a new operation if you need to execute outside the transaction.`,t.OPERATION_ALREADY_EXECUTED,{meta:{model:e,operation:n}})}static alreadyExecutedDefault(e,n){return new PendingOperationError(`Cannot call executeWith() on a PendingOperation that was already awaited. The ${e}.${n}() operation was already executed outside a transaction. Create a new operation for transaction execution.`,t.OPERATION_EXECUTION_CONFLICT,{meta:{model:e,operation:n}})}static differentDriverConflict(e,n){return new PendingOperationError(`Cannot call executeWith() with a different driver. The ${e}.${n}() operation was already executed in another transaction context.`,t.OPERATION_EXECUTION_CONFLICT,{meta:{model:e,operation:n}})}static clientMismatch(e,n){return new PendingOperationError(`Cannot execute ${e}.${n}() in this transaction: the operation was created by a different client instance. All operations in \$transaction([...]) must come from the same client.`,t.OPERATION_CLIENT_MISMATCH,{meta:{model:e,operation:n}})}static scopeMismatch(e,n){return new PendingOperationError(`Cannot execute ${e}.${n}() in this transaction: the operation was created outside this transaction scope. Create the operation from the client provided to this transaction callback.`,t.OPERATION_SCOPE_MISMATCH,{meta:{model:e,operation:n}})}};function isPendingOperationError(e){return e instanceof i}var QueryEngineError=class extends n{static diagnosticName=`QueryEngineError`;constructor(e,n){super(e,n?.code??t.INTERNAL_ERROR,n)}},UnsupportedOperationError=class extends QueryEngineError{static diagnosticName=`UnsupportedOperationError`;constructor(e,n){super(e,{...n,code:t.UNSUPPORTED_OPERATION})}};function isUnsupportedOperationError(e){return e instanceof UnsupportedOperationError}function isNotFoundError(e){return e instanceof NotFoundError}function retainWriteOutcomeFailure(e,t,n=`Query execution and write-outcome publication both failed.`){let r=t instanceof AggregateError?[...t.errors]:[t];return AggregateError([e,...r],n,{cause:e})}const a={literal:()=>{throw new FeatureNotSupportedError(`vector`,`literal`,`Load the pgvector extension.`)},l2:()=>{throw new FeatureNotSupportedError(`vector`,`l2`,`Load the pgvector extension.`)},cosine:()=>{throw new FeatureNotSupportedError(`vector`,`cosine`,`Load the pgvector extension.`)}},o={createManyAndReturn:`createMany`,updateManyAndReturn:`updateMany`,deleteManyAndReturn:`deleteMany`};function publicOperationName(e){return o[e]??e}var ValidationError=class extends n{static diagnosticName=`ValidationError`;issues;source;operation;constructor(e,n,r){let i=n.length===1?[n[0].path,n[0].message].filter(Boolean).join(`: `):`${n.length} validation errors`,a=normalizeSource(e,r?.meta),o=a.kind===`operation`?a.operation:void 0,s=validationSubject(a);super(`Validation failed for ${s}: ${i}`,o?t.VALIDATION_FAILED:t.INVALID_INPUT,{cause:r?.cause,diagnostics:r?.diagnostics,validation:{source:a,issues:n},meta:o?{...r?.meta,operation:o}:{...r?.meta}}),this.issues=n,this.source=a,this.operation=o}};function normalizeSource(e,t){if(typeof e==`string`){let n=typeof t?.model==`string`?t.model:void 0;return Object.freeze({kind:`operation`,operation:publicOperationName(e),...n?{model:n}:{}})}return e.kind===`operation`?Object.freeze({...e,operation:publicOperationName(e.operation)}):Object.freeze({...e})}function validationSubject(e){return e.kind===`operation`?e.model?`${e.model}.${e.operation}`:e.operation:e.kind===`registry`?`schema registry`:e.kind===`schema-builder`?e.builder:`JSON Schema`}function isValidationError(e){return e instanceof ValidationError}export{isPendingOperationError as _,FeatureNotSupportedError as a,a as b,NestedWriteAssertionError as c,i as d,QueryEngineError as f,isNotFoundError as g,isClientInitializationError as h,ConnectionError as i,NestedWriteError as l,UnsupportedOperationError as m,isValidationError as n,ForbiddenError as o,QueryError as p,ClientInitializationError as r,r as s,ValidationError as t,NotFoundError as u,isUnsupportedOperationError as v,retainWriteOutcomeFailure as y};
2
- //# sourceMappingURL=validation-gwZYm3Yn.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,t as n}from"./base-wlv81COV.mjs";var ConnectionError=class extends n{static diagnosticName=`ConnectionError`;constructor(e,n){super(e,n?.code??t.CONNECTION_FAILED,n)}},ClientInitializationError=class extends n{static diagnosticName=`ClientInitializationError`;constructor(e,n){super(e,t.CLIENT_INITIALIZATION,n)}};function isClientInitializationError(e){return e instanceof ClientInitializationError}var QueryError=class extends n{static diagnosticName=`QueryError`;constructor(e,n){super(e,n?.code??t.QUERY_FAILED,n)}},NotFoundError=class extends n{static diagnosticName=`NotFoundError`;constructor(e,n,r){super(`No ${e} record found for ${n}`,t.RECORD_NOT_FOUND,{meta:{...r?.meta,model:e,operation:n}})}},ForbiddenError=class extends n{static diagnosticName=`ForbiddenError`;constructor(e,n,r){super(`The ${n} on ${e} is not permitted${r?.reason?`: ${r.reason}`:``}`,t.FORBIDDEN,{meta:{...r?.meta,model:e,operation:n},cause:r?.cause})}},NestedWriteError=class extends n{static diagnosticName=`NestedWriteError`;constructor(e,n,r){super(e,r?.code??t.NESTED_WRITE_FAILED,{cause:r?.cause,diagnostics:r?.diagnostics,meta:{...r?.meta,relation:n}})}};const r=`Nested write assertion failed: a batch precondition (e.g. a connect/disconnect target or ownership check) did not hold.`;var NestedWriteAssertionError=class extends n{static diagnosticName=`NestedWriteAssertionError`;constructor(e,n){super(e,t.NESTED_WRITE_ASSERTION_FAILED,n)}},FeatureNotSupportedError=class extends n{static diagnosticName=`FeatureNotSupportedError`;constructor(e,n,r){let i=r?`${e}.${n} is not supported. ${r}`:`${e}.${n} is not supported by this driver.`;super(i,t.FEATURE_NOT_SUPPORTED,{meta:{feature:e,method:n}})}},i=class PendingOperationError extends n{static diagnosticName=`PendingOperationError`;constructor(e,t,n){super(e,t,n)}static alreadyExecutedWithDriver(e,n){return new PendingOperationError(`Cannot await a PendingOperation that was already executed with executeWith(). The ${e}.${n}() operation was already executed in a transaction context. Create a new operation if you need to execute outside the transaction.`,t.OPERATION_ALREADY_EXECUTED,{meta:{model:e,operation:n}})}static alreadyExecutedDefault(e,n){return new PendingOperationError(`Cannot call executeWith() on a PendingOperation that was already awaited. The ${e}.${n}() operation was already executed outside a transaction. Create a new operation for transaction execution.`,t.OPERATION_EXECUTION_CONFLICT,{meta:{model:e,operation:n}})}static differentDriverConflict(e,n){return new PendingOperationError(`Cannot call executeWith() with a different driver. The ${e}.${n}() operation was already executed in another transaction context.`,t.OPERATION_EXECUTION_CONFLICT,{meta:{model:e,operation:n}})}static clientMismatch(e,n){return new PendingOperationError(`Cannot execute ${e}.${n}() in this transaction: the operation was created by a different client instance. All operations in \$transaction([...]) must come from the same client.`,t.OPERATION_CLIENT_MISMATCH,{meta:{model:e,operation:n}})}static scopeMismatch(e,n){return new PendingOperationError(`Cannot execute ${e}.${n}() in this transaction: the operation was created outside this transaction scope. Create the operation from the client provided to this transaction callback.`,t.OPERATION_SCOPE_MISMATCH,{meta:{model:e,operation:n}})}};function isPendingOperationError(e){return e instanceof i}var QueryEngineError=class extends n{static diagnosticName=`QueryEngineError`;constructor(e,n){super(e,n?.code??t.INTERNAL_ERROR,n)}},UnsupportedOperationError=class extends QueryEngineError{static diagnosticName=`UnsupportedOperationError`;constructor(e,n){super(e,{...n,code:t.UNSUPPORTED_OPERATION})}};function isUnsupportedOperationError(e){return e instanceof UnsupportedOperationError}function isNotFoundError(e){return e instanceof NotFoundError}function retainWriteOutcomeFailure(e,t,n=`Query execution and write-outcome publication both failed.`){let r=t instanceof AggregateError?[...t.errors]:[t];return AggregateError([e,...r],n,{cause:e})}const a={literal:()=>{throw new FeatureNotSupportedError(`vector`,`literal`,`Load the pgvector extension.`)},l2:()=>{throw new FeatureNotSupportedError(`vector`,`l2`,`Load the pgvector extension.`)},cosine:()=>{throw new FeatureNotSupportedError(`vector`,`cosine`,`Load the pgvector extension.`)}};export{retainWriteOutcomeFailure as _,r as a,NotFoundError as c,QueryError as d,UnsupportedOperationError as f,isUnsupportedOperationError as g,isPendingOperationError as h,ForbiddenError as i,i as l,isNotFoundError as m,ConnectionError as n,NestedWriteAssertionError as o,isClientInitializationError as p,FeatureNotSupportedError as r,NestedWriteError as s,ClientInitializationError as t,QueryEngineError as u,a as v};
2
+ //# sourceMappingURL=query-CTna5P9o.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-CTna5P9o.mjs","names":[],"sources":["../src/errors/query.ts"],"sourcesContent":["import {\n VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n type VibORMErrorOptions,\n} from \"./base\";\n\n/**\n * Every code {@link ConnectionError} can carry. `CLIENT_INITIALIZATION` is NOT here — it has\n * its own class ({@link ClientInitializationError}).\n */\nexport type ConnectionErrorCode =\n | typeof VibORMErrorCode.CONNECTION_FAILED\n | typeof VibORMErrorCode.CONNECTION_TIMEOUT\n | typeof VibORMErrorCode.CONNECTION_CLOSED\n | typeof VibORMErrorCode.CONNECTION_CAPACITY;\n\n/**\n * Connection-related errors\n */\nexport class ConnectionError extends VibORMError {\n static override readonly diagnosticName = \"ConnectionError\";\n\n /** Discriminant: one of {@link ConnectionErrorCode}, never a code outside the family. */\n declare readonly code: ConnectionErrorCode;\n\n constructor(\n message: string,\n options?: VibORMErrorOptions & { code?: ConnectionErrorCode | undefined }\n ) {\n super(message, options?.code ?? VibORMErrorCode.CONNECTION_FAILED, options);\n }\n}\n\n/**\n * Client construction failures (Prisma P1012)\n *\n * Raised while a client is being built or while its schema-shaped surface is being resolved:\n * a missing driver, a schema that fails name hydration, or an access to a model the schema\n * does not define. These are configuration faults, not query faults — nothing has reached the\n * database yet.\n *\n * Prisma raises `PrismaClientInitializationError` for the same category and exposes its code\n * on `errorCode`; P1012 is Prisma's \"Schema validation error\", the closest documented code for\n * a client that cannot be constructed from the given schema and configuration. VibORM\n * publishes it through the shared `prismaCode` getter.\n */\nexport class ClientInitializationError extends VibORMError {\n static override readonly diagnosticName = \"ClientInitializationError\";\n\n /** Literal discriminant: this class always carries `CLIENT_INITIALIZATION`. */\n declare readonly code: typeof VibORMErrorCode.CLIENT_INITIALIZATION;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.CLIENT_INITIALIZATION, options);\n }\n}\n\n/**\n * Type guard for client initialization errors\n */\nexport function isClientInitializationError(\n error: unknown\n): error is ClientInitializationError {\n return error instanceof ClientInitializationError;\n}\n\n/**\n * Every code {@link QueryError} can carry.\n *\n * The `V2xxx` query family plus `INVALID_INPUT`, which the raw-SQL helpers raise through this\n * class when a caller hands `$queryRaw` something that is neither a tagged template nor an\n * `Sql` fragment, or a raw/provider parameter boundary refuses an invalid\n * `Date` (`client/raw.ts`, `drivers/provider-parameter-snapshot.ts`) — measured\n * at the construction sites, not assumed.\n */\nexport type QueryErrorCode =\n | typeof VibORMErrorCode.QUERY_FAILED\n | typeof VibORMErrorCode.QUERY_TIMEOUT\n | typeof VibORMErrorCode.QUERY_SYNTAX\n | typeof VibORMErrorCode.QUERY_SCHEMA_MISMATCH\n | typeof VibORMErrorCode.QUERY_OUT_OF_RANGE\n | typeof VibORMErrorCode.QUERY_RESULT_INVALID\n | typeof VibORMErrorCode.INVALID_INPUT;\n\n/**\n * Query execution errors\n */\nexport class QueryError extends VibORMError {\n static override readonly diagnosticName = \"QueryError\";\n\n /** Discriminant: one of {@link QueryErrorCode}, never a code outside the family. */\n declare readonly code: QueryErrorCode;\n\n constructor(\n message: string,\n options?: VibORMErrorOptions & { code?: QueryErrorCode | undefined }\n ) {\n super(message, options?.code ?? VibORMErrorCode.QUERY_FAILED, options);\n }\n}\n\n/**\n * Record not found (for OrThrow operations)\n */\nexport class NotFoundError extends VibORMError {\n static override readonly diagnosticName = \"NotFoundError\";\n\n /** Literal discriminant: this class always carries `RECORD_NOT_FOUND`. */\n declare readonly code: typeof VibORMErrorCode.RECORD_NOT_FOUND;\n\n constructor(\n model: string,\n operation: string,\n options?: { meta?: VibORMErrorMeta }\n ) {\n super(\n `No ${model} record found for ${operation}`,\n VibORMErrorCode.RECORD_NOT_FOUND,\n {\n meta: { ...options?.meta, model, operation },\n }\n );\n }\n}\n\n/**\n * A policy refused the operation: the row a write would produce, or an explicit `assert`, is\n * not permitted to the caller. Like {@link NotFoundError}, it never says whether the row was\n * hidden or visible and not permitted, nor whether a referenced row is hidden or missing.\n */\nexport class ForbiddenError extends VibORMError {\n static override readonly diagnosticName = \"ForbiddenError\";\n\n /** Literal discriminant: this class always carries `FORBIDDEN`. */\n declare readonly code: typeof VibORMErrorCode.FORBIDDEN;\n\n /**\n * `reason` names what refused the operation where the operation alone does\n * not say it, e.g. a field an update writes through a nested write;\n * `cause`, the failure it explains (an upsert's unique violation).\n */\n constructor(\n model: string,\n operation: string,\n options?: { meta?: VibORMErrorMeta; reason?: string; cause?: Error }\n ) {\n super(\n `The ${operation} on ${model} is not permitted${options?.reason ? `: ${options.reason}` : \"\"}`,\n VibORMErrorCode.FORBIDDEN,\n {\n meta: { ...options?.meta, model, operation },\n cause: options?.cause,\n }\n );\n }\n}\n\n/**\n * Every code {@link NestedWriteError} can carry.\n *\n * `NESTED_WRITE_ASSERTION_FAILED` is in the union even though\n * {@link NestedWriteAssertionError} owns that code as a class: the un-attributable batch floor\n * (`OperationExecutor.attributeGuardFailure`, `query-engine/batch-error-attribution.ts`)\n * deliberately re-raises the V7006 floor as a `NestedWriteError` so the surfaced error carries\n * the assertion code without claiming the driver-mapped class. Measured at the construction\n * sites; the two are told apart by class, not by code.\n */\nexport type NestedWriteErrorCode =\n | typeof VibORMErrorCode.NESTED_WRITE_FAILED\n | typeof VibORMErrorCode.NESTED_CREATE_FAILED\n | typeof VibORMErrorCode.NESTED_UPDATE_FAILED\n | typeof VibORMErrorCode.NESTED_DELETE_FAILED\n | typeof VibORMErrorCode.NESTED_CONNECT_FAILED\n | typeof VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED;\n\n/**\n * Nested write operation errors\n */\nexport class NestedWriteError extends VibORMError {\n static override readonly diagnosticName = \"NestedWriteError\";\n\n /** Discriminant: one of {@link NestedWriteErrorCode}, never a code outside the family. */\n declare readonly code: NestedWriteErrorCode;\n\n constructor(\n message: string,\n relation: string,\n options?: VibORMErrorOptions & { code?: NestedWriteErrorCode | undefined }\n ) {\n super(message, options?.code ?? VibORMErrorCode.NESTED_WRITE_FAILED, {\n cause: options?.cause,\n diagnostics: options?.diagnostics,\n meta: { ...options?.meta, relation },\n });\n }\n}\n\n/**\n * The batch assertion-abort floor sentence — one home for the three layers that\n * say it: the executor's guard-free-ladder floor, merged-batch attribution's\n * un-attributable floor, and driver error mapping's assertion translation.\n * The wording matches V1's frozen runtime verbatim; edit it nowhere else.\n */\nexport const NESTED_WRITE_ASSERTION_FLOOR_MESSAGE =\n \"Nested write assertion failed: a batch precondition (e.g. a connect/disconnect target or ownership check) did not hold.\";\n\n/**\n * Batch-plan nested-write assertion failures\n *\n * Atomic batch plans encode preconditions (connect/disconnect targets must\n * exist, correlation checks) as SQL statements that error on purpose when the\n * precondition fails (adapter.assertions). Each dialect surfaces a different\n * raw error (PG: division by zero, MySQL/SQLite: invalid JSON); the driver\n * error mapping normalizes all of them to this type.\n */\nexport class NestedWriteAssertionError extends VibORMError {\n static override readonly diagnosticName = \"NestedWriteAssertionError\";\n\n /** Literal discriminant: this class always carries `NESTED_WRITE_ASSERTION_FAILED`. */\n declare readonly code: typeof VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED, options);\n }\n}\n\n/**\n * Feature not supported errors\n */\nexport class FeatureNotSupportedError extends VibORMError {\n static override readonly diagnosticName = \"FeatureNotSupportedError\";\n\n /** Literal discriminant: this class always carries `FEATURE_NOT_SUPPORTED`. */\n declare readonly code: typeof VibORMErrorCode.FEATURE_NOT_SUPPORTED;\n\n constructor(feature: string, method: string, suggestion?: string) {\n const message = suggestion\n ? `${feature}.${method} is not supported. ${suggestion}`\n : `${feature}.${method} is not supported by this driver.`;\n super(message, VibORMErrorCode.FEATURE_NOT_SUPPORTED, {\n meta: { feature, method },\n });\n }\n}\n\n/**\n * Pending operation execution errors\n *\n * Thrown when attempting to execute a PendingOperation in an invalid way,\n * such as awaiting after executeWith() or calling executeWith() after await.\n */\n/** Every code {@link PendingOperationError} can carry. */\nexport type PendingOperationErrorCode =\n | typeof VibORMErrorCode.OPERATION_ALREADY_EXECUTED\n | typeof VibORMErrorCode.OPERATION_EXECUTION_CONFLICT\n | typeof VibORMErrorCode.OPERATION_CLIENT_MISMATCH\n | typeof VibORMErrorCode.OPERATION_SCOPE_MISMATCH;\n\nexport class PendingOperationError extends VibORMError {\n static override readonly diagnosticName = \"PendingOperationError\";\n\n /** Discriminant: one of {@link PendingOperationErrorCode}, never a code outside the family. */\n declare readonly code: PendingOperationErrorCode;\n\n // biome-ignore lint/complexity/noUselessConstructor: not a forwarder — it narrows the public signature, restricting `code` to PendingOperationErrorCode and `options` to `{ meta }`; deleting it would widen the constructor back to the base's VibORMErrorCode plus `cause`/`diagnostics`.\n constructor(\n message: string,\n code: PendingOperationErrorCode,\n options?: { meta?: VibORMErrorMeta }\n ) {\n super(message, code, options);\n }\n\n /**\n * Create error for attempting to await after executeWith()\n */\n static alreadyExecutedWithDriver(\n model: string,\n operation: string\n ): PendingOperationError {\n return new PendingOperationError(\n \"Cannot await a PendingOperation that was already executed with executeWith(). \" +\n `The ${model}.${operation}() operation was already executed in a transaction context. ` +\n \"Create a new operation if you need to execute outside the transaction.\",\n VibORMErrorCode.OPERATION_ALREADY_EXECUTED,\n { meta: { model, operation } }\n );\n }\n\n /**\n * Create error for attempting executeWith() after await\n */\n static alreadyExecutedDefault(\n model: string,\n operation: string\n ): PendingOperationError {\n return new PendingOperationError(\n \"Cannot call executeWith() on a PendingOperation that was already awaited. \" +\n `The ${model}.${operation}() operation was already executed outside a transaction. ` +\n \"Create a new operation for transaction execution.\",\n VibORMErrorCode.OPERATION_EXECUTION_CONFLICT,\n { meta: { model, operation } }\n );\n }\n\n /**\n * Create error for attempting executeWith() with a different driver\n */\n static differentDriverConflict(\n model: string,\n operation: string\n ): PendingOperationError {\n return new PendingOperationError(\n \"Cannot call executeWith() with a different driver. \" +\n `The ${model}.${operation}() operation was already executed in another transaction context.`,\n VibORMErrorCode.OPERATION_EXECUTION_CONFLICT,\n { meta: { model, operation } }\n );\n }\n\n /**\n * Create error for operations from different clients in $transaction\n */\n static clientMismatch(\n model: string,\n operation: string\n ): PendingOperationError {\n return new PendingOperationError(\n `Cannot execute ${model}.${operation}() in this transaction: ` +\n \"the operation was created by a different client instance. \" +\n \"All operations in $transaction([...]) must come from the same client.\",\n VibORMErrorCode.OPERATION_CLIENT_MISMATCH,\n { meta: { model, operation } }\n );\n }\n\n /** Create error for mixing root and transaction-bound operation scopes. */\n static scopeMismatch(\n model: string,\n operation: string\n ): PendingOperationError {\n return new PendingOperationError(\n `Cannot execute ${model}.${operation}() in this transaction: ` +\n \"the operation was created outside this transaction scope. \" +\n \"Create the operation from the client provided to this transaction callback.\",\n VibORMErrorCode.OPERATION_SCOPE_MISMATCH,\n { meta: { model, operation } }\n );\n }\n}\n\n/**\n * Type guard for pending operation errors\n */\nexport function isPendingOperationError(\n error: unknown\n): error is PendingOperationError {\n return error instanceof PendingOperationError;\n}\n\n/**\n * Internal query engine error\n */\n/**\n * Every code a {@link QueryEngineError} can carry — its own `INTERNAL_ERROR`, plus the\n * `UNSUPPORTED_OPERATION` its {@link UnsupportedOperationError} subclass narrows to. A wider\n * type here would be a lie about the class; a narrower one would make the subclass's `code`\n * an illegal override.\n */\nexport type QueryEngineErrorCode =\n | typeof VibORMErrorCode.INTERNAL_ERROR\n | typeof VibORMErrorCode.UNSUPPORTED_OPERATION;\n\nexport class QueryEngineError extends VibORMError {\n // Annotated `string` (not the literal) so a subclass may narrow it — the\n // pattern VibORMError itself uses for its subclasses.\n static override readonly diagnosticName: string = \"QueryEngineError\";\n\n /**\n * Discriminant. `INTERNAL_ERROR` for a bare engine error; the\n * {@link UnsupportedOperationError} subclass narrows it to `UNSUPPORTED_OPERATION`, which is\n * why this is the family and not a single literal — a code check alone cannot separate the\n * two, so {@link classifyFailure} separates them by class.\n */\n declare readonly code: QueryEngineErrorCode;\n\n constructor(\n message: string,\n options?: {\n cause?: Error | undefined;\n meta?: VibORMErrorMeta | undefined;\n /** Subclass seam: a distinct taxonomy code (default INTERNAL_ERROR). */\n code?: QueryEngineErrorCode | undefined;\n }\n ) {\n super(message, options?.code ?? VibORMErrorCode.INTERNAL_ERROR, options);\n }\n}\n\n/**\n * A payload SHAPE the query engine deliberately does not express — a documented\n * capability boundary (a compound key or non-literal fold past a proven surface,\n * an inexpressible sub-shape, a parity refusal), NOT an engine crash. Distinct\n * from {@link FeatureNotSupportedError} (a dialect/driver capability gap): this\n * is shape-capability. It extends {@link QueryEngineError} so pre-existing\n * `instanceof QueryEngineError` handling keeps working, but carries its own\n * name and code (`V8003 UNSUPPORTED_OPERATION`) so a deliberate refusal is\n * distinguishable from `V9001 INTERNAL_ERROR` programmatically and in logs.\n * Users can `instanceof UnsupportedOperationError` (exported from the package\n * root) to branch on it.\n */\nexport class UnsupportedOperationError extends QueryEngineError {\n static override readonly diagnosticName = \"UnsupportedOperationError\";\n\n /** Literal discriminant: this class always carries `UNSUPPORTED_OPERATION`. */\n declare readonly code: typeof VibORMErrorCode.UNSUPPORTED_OPERATION;\n\n constructor(\n message: string,\n options?: {\n cause?: Error | undefined;\n meta?: VibORMErrorMeta | undefined;\n }\n ) {\n super(message, {\n ...options,\n code: VibORMErrorCode.UNSUPPORTED_OPERATION,\n });\n }\n}\n\n/**\n * Type guard for unsupported-operation (shape-capability) refusals\n */\nexport function isUnsupportedOperationError(\n error: unknown\n): error is UnsupportedOperationError {\n return error instanceof UnsupportedOperationError;\n}\n\n/**\n * Type guard for not found errors\n */\nexport function isNotFoundError(error: unknown): error is NotFoundError {\n return error instanceof NotFoundError;\n}\n\n/**\n * Keep the execution failure primary while retaining every listener failure.\n *\n * ONE composition for the whole estate, stated at the boundary all three of its\n * consumers already depend on: the client (`client.ts`, `raw.ts`,\n * `array-transaction.ts`), the query engine's deferred operation\n * (`pending-operation.ts`) and the candidate engine's operation context. It is\n * pure — a primary, the listener failures flattened out of the publication\n * owner's aggregate, and the primary again as `cause` — so it belongs beside the\n * query failures it composes rather than inside the extension publication owner\n * that raises one half of it. The candidate engine takes no `@extensions`\n * import anywhere today, and importing that owner would add\n * `src/extensions/query.ts` and `src/query-engine/routed-operations.ts` to\n * `raptor3/shared/operation-context.ts`'s runtime closure (181 → 183). A\n * directory cycle is not what this placement avoids: the engine→extensions\n * runtime edge already exists — `query-engine/pending-operation.ts` holds it\n * for the shipped path — and is pre-existing. A second restatement inside the\n * engine was the duplication FC-05 deleted.\n */\nexport function retainWriteOutcomeFailure(\n primary: unknown,\n outcomeFailure: unknown,\n message = \"Query execution and write-outcome publication both failed.\"\n): AggregateError {\n const suppressed =\n outcomeFailure instanceof AggregateError\n ? [...outcomeFailure.errors]\n : [outcomeFailure];\n return new AggregateError([primary, ...suppressed], message, {\n cause: primary,\n });\n}\n\n/**\n * Unsupported vector operations\n *\n * Use this to override adapter.vector when pgvector is not available.\n */\nexport const unsupportedVector = {\n literal: (): never => {\n throw new FeatureNotSupportedError(\n \"vector\",\n \"literal\",\n \"Load the pgvector extension.\"\n );\n },\n l2: (): never => {\n throw new FeatureNotSupportedError(\n \"vector\",\n \"l2\",\n \"Load the pgvector extension.\"\n );\n },\n cosine: (): never => {\n throw new FeatureNotSupportedError(\n \"vector\",\n \"cosine\",\n \"Load the pgvector extension.\"\n );\n },\n};\n"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
1
  import{n as e}from"./chunk-BuuaeEvq.mjs";function boundByServer(e,t){let n=e.capabilities;return n.sharesRelationBodies!==!0||n.relationsPerStatement!==void 0?!1:(Object.defineProperty(n,`relationsPerStatement`,{configurable:!0,enumerable:!0,get(){let e=t();return e===void 0||typeof e==`string`&&e.endsWith(`(Neki)`)?256:void 0}}),!0)}const t=/references more than (\d+) relations/;function learnRelationLimit(e,n){let r=e.capabilities;if(r.sharesRelationBodies!==!0||r.relationsPerStatement!==void 0||typeof n!=`object`||!n)return;let i=Reflect.get(n,`code`)===`54000`||Reflect.get(n,`errno`)===`54000`,a=t.exec(String(Reflect.get(n,`message`)));i&&a!==null&&Object.defineProperty(r,`relationsPerStatement`,{configurable:!0,enumerable:!0,writable:!0,value:Number(a[1])})}export{learnRelationLimit as n,boundByServer as t};
2
- //# sourceMappingURL=relation-bound-BrZLsSke.mjs.map
2
+ //# sourceMappingURL=relation-bound-Bj7X-EUE.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"relation-bound-BrZLsSke.mjs","names":[],"sources":["../src/drivers/shared/relation-bound.ts"],"sourcesContent":["import type { DatabaseAdapter } from \"@adapters/database-adapter\";\n\n/**\n * What a PostgreSQL server says of itself that bounds the relations one\n * statement may reference (`capabilities.relationsPerStatement`). PlanetScale's\n * Neki refuses a statement referencing more than 256; it names itself in the\n * `server_version` of every connection's startup (`18.6 (…) (Neki)`), which\n * node-postgres (through the `Client` a driver's own pool makes) and\n * postgres.js (`sql.parameters`) receive with no statement of their own, and\n * in its refusal (SQLSTATE 54000, \"the statement references more than 256\n * relations, the limit for one statement\").\n *\n * Each fills an ABSENT bound only, and only where bodies are shared: a\n * `relationsPerStatement` the caller stated always wins, and\n * `sharedRelationBodies: false` keeps every statement's form.\n */\nconst NEKI_RELATIONS = 256;\n\n/**\n * The bound of a driver that reads its server's startup, `serverVersion`\n * (undefined until a connection opened): read as each statement is built, so\n * a statement built once a connection said what server it is, a transaction's\n * included, takes Neki's bound or none, and one built before (a driver's first\n * statement, an array transaction's members) takes Neki's, which costs only\n * plans elsewhere and only past 256 relations. Whether the bound is the\n * server's to say (no bound stated, bodies shared).\n */\nexport function boundByServer(\n adapter: DatabaseAdapter,\n serverVersion: () => unknown\n): boolean {\n const capabilities = adapter.capabilities;\n if (\n capabilities.sharesRelationBodies !== true ||\n capabilities.relationsPerStatement !== undefined\n )\n return false;\n Object.defineProperty(capabilities, \"relationsPerStatement\", {\n configurable: true,\n enumerable: true,\n get() {\n const version = serverVersion();\n return version === undefined ||\n (typeof version === \"string\" && version.endsWith(\"(Neki)\"))\n ? NEKI_RELATIONS\n : undefined;\n },\n });\n return true;\n}\n\nconst RELATION_LIMIT = /references more than (\\d+) relations/;\n\n/**\n * The bound a refusal names, for a transport whose startup is unread (Bun SQL,\n * a supplied pool): the refused statement fails, the next ones fit. The code\n * is node-postgres's and postgres.js's `code`, Bun SQL's `errno`.\n */\nexport function learnRelationLimit(\n adapter: DatabaseAdapter,\n error: unknown\n): void {\n const capabilities = adapter.capabilities;\n if (\n capabilities.sharesRelationBodies !== true ||\n capabilities.relationsPerStatement !== undefined ||\n typeof error !== \"object\" ||\n error === null\n )\n return;\n const refused =\n Reflect.get(error, \"code\") === \"54000\" ||\n Reflect.get(error, \"errno\") === \"54000\";\n const limit = RELATION_LIMIT.exec(String(Reflect.get(error, \"message\")));\n // A value, replacing a startup reader whose server did not say Neki.\n if (refused && limit !== null)\n Object.defineProperty(capabilities, \"relationsPerStatement\", {\n configurable: true,\n enumerable: true,\n writable: true,\n value: Number(limit[1]),\n });\n}\n"],"mappings":"yCA2BA,SAAgB,cACd,EACA,EACS,CACT,IAAM,EAAe,EAAQ,aAiB7B,OAfE,EAAa,uBAAyB,IACtC,EAAa,wBAA0B,IAAA,GAEhC,IACT,OAAO,eAAe,EAAc,wBAAyB,CAC3D,aAAc,GACd,WAAY,GACZ,KAAM,CACJ,IAAM,EAAU,GAAe,CAC/B,OAAO,IAAY,IAAA,IAChB,OAAO,GAAY,UAAY,EAAQ,SAAS,SAAS,CACxD,IACA,IAAA,IAEP,CAAC,CACK,IAGT,MAAM,EAAiB,uCAOvB,SAAgB,mBACd,EACA,EACM,CACN,IAAM,EAAe,EAAQ,aAC7B,GACE,EAAa,uBAAyB,IACtC,EAAa,wBAA0B,IAAA,IACvC,OAAO,GAAU,WACjB,EAEA,OACF,IAAM,EACJ,QAAQ,IAAI,EAAO,OAAO,GAAK,SAC/B,QAAQ,IAAI,EAAO,QAAQ,GAAK,QAC5B,EAAQ,EAAe,KAAK,OAAO,QAAQ,IAAI,EAAO,UAAU,CAAC,CAAC,CAEpE,GAAW,IAAU,MACvB,OAAO,eAAe,EAAc,wBAAyB,CAC3D,aAAc,GACd,WAAY,GACZ,SAAU,GACV,MAAO,OAAO,EAAM,GAAG,CACxB,CAAC"}
1
+ {"version":3,"file":"relation-bound-Bj7X-EUE.mjs","names":[],"sources":["../src/drivers/shared/relation-bound.ts"],"sourcesContent":["import type { DatabaseAdapter } from \"@adapters/database-adapter\";\n\n/**\n * What a PostgreSQL server says of itself that bounds the relations one\n * statement may reference (`capabilities.relationsPerStatement`). PlanetScale's\n * Neki refuses a statement referencing more than 256; it names itself in the\n * `server_version` of every connection's startup (`18.6 (…) (Neki)`), which\n * node-postgres (through the `Client` a driver's own pool makes) and\n * postgres.js (`sql.parameters`) receive with no statement of their own, and\n * in its refusal (SQLSTATE 54000, \"the statement references more than 256\n * relations, the limit for one statement\").\n *\n * Each fills an ABSENT bound only, and only where bodies are shared: a\n * `relationsPerStatement` the caller stated always wins, and\n * `sharedRelationBodies: false` keeps every statement's form.\n */\nconst NEKI_RELATIONS = 256;\n\n/**\n * The bound of a driver that reads its server's startup, `serverVersion`\n * (undefined until a connection opened): read as each statement is built, so\n * a statement built once a connection said what server it is, a transaction's\n * included, takes Neki's bound or none, and one built before (a driver's first\n * statement, an array transaction's members) takes Neki's, which costs only\n * plans elsewhere and only past 256 relations. Whether the bound is the\n * server's to say (no bound stated, bodies shared).\n */\nexport function boundByServer(\n adapter: DatabaseAdapter,\n serverVersion: () => unknown\n): boolean {\n const capabilities = adapter.capabilities;\n if (\n capabilities.sharesRelationBodies !== true ||\n capabilities.relationsPerStatement !== undefined\n )\n return false;\n Object.defineProperty(capabilities, \"relationsPerStatement\", {\n configurable: true,\n enumerable: true,\n get() {\n const version = serverVersion();\n return version === undefined ||\n (typeof version === \"string\" && version.endsWith(\"(Neki)\"))\n ? NEKI_RELATIONS\n : undefined;\n },\n });\n return true;\n}\n\nconst RELATION_LIMIT = /references more than (\\d+) relations/;\n\n/**\n * The bound a refusal names, for a transport whose startup is unread (Bun SQL,\n * a supplied pool): the refused statement fails, the next ones fit. The code\n * is node-postgres's and postgres.js's `code`, Bun SQL's `errno`.\n */\nexport function learnRelationLimit(\n adapter: DatabaseAdapter,\n error: unknown\n): void {\n const capabilities = adapter.capabilities;\n if (\n capabilities.sharesRelationBodies !== true ||\n capabilities.relationsPerStatement !== undefined ||\n typeof error !== \"object\" ||\n error === null\n )\n return;\n const refused =\n Reflect.get(error, \"code\") === \"54000\" ||\n Reflect.get(error, \"errno\") === \"54000\";\n const limit = RELATION_LIMIT.exec(String(Reflect.get(error, \"message\")));\n // A value, replacing a startup reader whose server did not say Neki.\n if (refused && limit !== null)\n Object.defineProperty(capabilities, \"relationsPerStatement\", {\n configurable: true,\n enumerable: true,\n writable: true,\n value: Number(limit[1]),\n });\n}\n"],"mappings":"yCA2BA,SAAgB,cACd,EACA,EACS,CACT,IAAM,EAAe,EAAQ,aAiB7B,OAfE,EAAa,uBAAyB,IACtC,EAAa,wBAA0B,IAAA,GAEhC,IACT,OAAO,eAAe,EAAc,wBAAyB,CAC3D,aAAc,GACd,WAAY,GACZ,KAAM,CACJ,IAAM,EAAU,GAAe,CAC/B,OAAO,IAAY,IAAA,IAChB,OAAO,GAAY,UAAY,EAAQ,SAAS,SAAS,CACxD,IACA,IAAA,IAEP,CAAC,CACK,IAGT,MAAM,EAAiB,uCAOvB,SAAgB,mBACd,EACA,EACM,CACN,IAAM,EAAe,EAAQ,aAC7B,GACE,EAAa,uBAAyB,IACtC,EAAa,wBAA0B,IAAA,IACvC,OAAO,GAAU,WACjB,EAEA,OACF,IAAM,EACJ,QAAQ,IAAI,EAAO,OAAO,GAAK,SAC/B,QAAQ,IAAI,EAAO,QAAQ,GAAK,QAC5B,EAAQ,EAAe,KAAK,OAAO,QAAQ,IAAI,EAAO,UAAU,CAAC,CAAC,CAEpE,GAAW,IAAU,MACvB,OAAO,eAAe,EAAc,wBAAyB,CAC3D,aAAc,GACd,WAAY,GACZ,SAAU,GACV,MAAO,OAAO,EAAM,GAAG,CACxB,CAAC"}
@@ -1,2 +1,2 @@
1
1
  import{n as e}from"./chunk-BuuaeEvq.mjs";const t=`0viborm_count_result`;function parseIntegerBoolean(e){if(typeof e==`number`)return e===1?!0:e===0?!1:void 0;if(typeof e==`bigint`)return e===1n?!0:e===0n?!1:void 0;if(e==null)return null}export{parseIntegerBoolean as n,t};
2
- //# sourceMappingURL=result-parsing-CQf_eCl8.mjs.map
2
+ //# sourceMappingURL=result-parsing-C2044903.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"result-parsing-CQf_eCl8.mjs","names":[],"sources":["../src/adapters/shared/result-parsing.ts"],"sourcesContent":["/**\n * Shared Result Parsing Utilities\n *\n * Common parsing logic used by adapters for database-specific type conversions.\n * These utilities use `undefined` as a sentinel to indicate \"not handled\" -\n * allowing the caller to fall through to default parsing.\n *\n * @example\n * const parsed = tryParseJsonString(value);\n * if (parsed !== undefined) {\n * // Use parsed value\n * } else {\n * // Fall through to default\n * }\n */\n\n/**\n * The private column name a COUNT result carries in a RESULT SHAPE.\n *\n * It names a shape's single raw key, never a provider's row: its readers are\n * `query-engine/result/result-shape.ts` and `client/typescript-type-renderer.ts`,\n * both over DECODED values. A live row's\n * count arrives under the alias the engine asked for (`_count`), which the\n * engine's own decoder reads back (Arnaud's D-40).\n */\nexport const COUNT_RESULT_KEY = \"0viborm_count_result\" as const;\n\n/**\n * Parse JSON string values (MySQL/SQLite return JSON as strings).\n *\n * @param value - Raw value from database\n * @returns Parsed JSON object/array, or `undefined` if not a JSON string\n *\n * @example\n * tryParseJsonString('[1,2,3]') // [1, 2, 3]\n * tryParseJsonString('{\"a\":1}') // { a: 1 }\n * tryParseJsonString('hello') // undefined (not JSON)\n * tryParseJsonString(123) // undefined (not a string)\n * tryParseJsonString('[invalid') // undefined (invalid JSON)\n */\nexport function tryParseJsonString(value: unknown): unknown | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n }\n\n return undefined;\n}\n\n/**\n * Convert SQLite/MySQL integer to boolean.\n * These databases store booleans as 0/1 integers.\n *\n * @param value - Raw value from database\n * @returns `true` for 1, `false` for 0, `null` for null/undefined,\n * or `undefined` if value is not an integer (fall through to default)\n *\n * @example\n * parseIntegerBoolean(1) // true\n * parseIntegerBoolean(0) // false\n * parseIntegerBoolean(null) // null\n * parseIntegerBoolean('true') // undefined (not handled, fall through)\n */\nexport function parseIntegerBoolean(\n value: unknown\n): boolean | null | undefined {\n if (typeof value === \"number\") {\n if (value === 1) return true;\n if (value === 0) return false;\n return undefined;\n }\n // SQLite drivers read integers safely (BigInt), including boolean columns\n if (typeof value === \"bigint\") {\n if (value === 1n) return true;\n if (value === 0n) return false;\n return undefined;\n }\n if (value === null || value === undefined) {\n return null;\n }\n return undefined;\n}\n"],"mappings":"yCAyBA,MAAa,EAAmB,uBAiDhC,SAAgB,oBACd,EAC4B,CAC5B,GAAI,OAAO,GAAU,SAGnB,OAFI,IAAU,EAAU,GACpB,IAAU,EAAU,GACxB,OAGF,GAAI,OAAO,GAAU,SAGnB,OAFI,IAAU,GAAW,GACrB,IAAU,GAAW,GACzB,OAEF,GAAI,GAAU,KACZ,OAAO"}
1
+ {"version":3,"file":"result-parsing-C2044903.mjs","names":[],"sources":["../src/adapters/shared/result-parsing.ts"],"sourcesContent":["/**\n * Shared Result Parsing Utilities\n *\n * Common parsing logic used by adapters for database-specific type conversions.\n * These utilities use `undefined` as a sentinel to indicate \"not handled\" -\n * allowing the caller to fall through to default parsing.\n *\n * @example\n * const parsed = tryParseJsonString(value);\n * if (parsed !== undefined) {\n * // Use parsed value\n * } else {\n * // Fall through to default\n * }\n */\n\n/**\n * The private column name a COUNT result carries in a RESULT SHAPE.\n *\n * It names a shape's single raw key, never a provider's row: its readers are\n * `query-engine/result/result-shape.ts` and `client/typescript-type-renderer.ts`,\n * both over DECODED values. A live row's\n * count arrives under the alias the engine asked for (`_count`), which the\n * engine's own decoder reads back (Arnaud's D-40).\n */\nexport const COUNT_RESULT_KEY = \"0viborm_count_result\" as const;\n\n/**\n * Parse JSON string values (MySQL/SQLite return JSON as strings).\n *\n * @param value - Raw value from database\n * @returns Parsed JSON object/array, or `undefined` if not a JSON string\n *\n * @example\n * tryParseJsonString('[1,2,3]') // [1, 2, 3]\n * tryParseJsonString('{\"a\":1}') // { a: 1 }\n * tryParseJsonString('hello') // undefined (not JSON)\n * tryParseJsonString(123) // undefined (not a string)\n * tryParseJsonString('[invalid') // undefined (invalid JSON)\n */\nexport function tryParseJsonString(value: unknown): unknown | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n }\n\n return undefined;\n}\n\n/**\n * Convert SQLite/MySQL integer to boolean.\n * These databases store booleans as 0/1 integers.\n *\n * @param value - Raw value from database\n * @returns `true` for 1, `false` for 0, `null` for null/undefined,\n * or `undefined` if value is not an integer (fall through to default)\n *\n * @example\n * parseIntegerBoolean(1) // true\n * parseIntegerBoolean(0) // false\n * parseIntegerBoolean(null) // null\n * parseIntegerBoolean('true') // undefined (not handled, fall through)\n */\nexport function parseIntegerBoolean(\n value: unknown\n): boolean | null | undefined {\n if (typeof value === \"number\") {\n if (value === 1) return true;\n if (value === 0) return false;\n return undefined;\n }\n // SQLite drivers read integers safely (BigInt), including boolean columns\n if (typeof value === \"bigint\") {\n if (value === 1n) return true;\n if (value === 0n) return false;\n return undefined;\n }\n if (value === null || value === undefined) {\n return null;\n }\n return undefined;\n}\n"],"mappings":"yCAyBA,MAAa,EAAmB,uBAiDhC,SAAgB,oBACd,EAC4B,CAC5B,GAAI,OAAO,GAAU,SAGnB,OAFI,IAAU,EAAU,GACpB,IAAU,EAAU,GACxB,OAGF,GAAI,OAAO,GAAU,SAGnB,OAFI,IAAU,GAAW,GACrB,IAAU,GAAW,GACzB,OAEF,GAAI,GAAU,KACZ,OAAO"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{C as r,N as i,_ as a,h as o,j as s,r as c,x as l}from"./rows-D7ns2l0U.mjs";import{f as u,i as d,r as f}from"./chain-BQoDfo80.mjs";import{a as p,c as m,i as h,s as g}from"./execution-context-_oajgBi4.mjs";import{S as _,t as v}from"./base-wlv81COV.mjs";import{i as y,t as b}from"./observation-BcT8Cs3d.mjs";import{a as x,g as S,r as C}from"./error-mapping-DRY49A3C.mjs";import{_ as ee,d as w,l as T,u as E}from"./query-CTna5P9o.mjs";import{t as D}from"./transaction-D5LHYn-r.mjs";import{t as O}from"./sql-DGtEeP8z.mjs";import{p as k}from"./validator-XVm02V0K.mjs";import{o as A,s as j}from"./builder-D0GQK-fA.mjs";import{t as M}from"./types-CJgtjXtu.mjs";import{n as N}from"./transaction-operation-Co3hw8yz.mjs";import{t as P}from"./adapter-result-parser-C0vW9am8.mjs";import{n as F}from"./bind-parameter-capacity-4OU6feZG.mjs";import{t as I}from"./result-parsing-C2044903.mjs";const L=new WeakMap,R=new WeakMap;function executePreparedQuery(e,t,n,r,i,a,o){return(e===void 0||t===void 0||t.length===0)&&o===void 0?n():!r&&o===void 0&&e!==void 0&&t!==void 0&&t.length>0?runCompiledQueryInterceptors(e,t,n,discardReadWriteOutcomeRegistration,a?.readCommitCertainty,a?.reportAdmissionFailure):executeInterceptedQuery(e,t,n,r,i,a,o)}function discardReadWriteOutcomeRegistration(){}async function executeInterceptedQuery(e,t,n,r,i,a,o){let s=o===void 0?[]:[o];o!==void 0&&i?.stage(o);let captureWriteOutcome=e=>{s.push(e),i?.stage(e)},c=0,l,u=!1,publish=async e=>{if(i){if(s.length===0||u)return;u=!0,i.confirm(s);return}c+=1,l=e,s.length!==0&&await publishWriteOutcomes(s,{certainty:e})},d=Object.freeze({committed:()=>publish(`committed`),mayHaveCommitted:()=>publish(`may-have-committed`)}),executeChild=async()=>{try{let e=await n(d);return r&&(i!==void 0||c===0)&&await publish(`committed`),e}catch(e){throw i&&!u&&i.discard(s),e}};try{return e===void 0||t===void 0||t.length===0?await executeChild():await runCompiledQueryInterceptors(e,t,executeChild,captureWriteOutcome,()=>l??a?.readCommitCertainty?.(),a?.reportAdmissionFailure)}catch(e){throw i&&!u&&i.discard(s),e}}function runCompiledQueryInterceptors(e,t,n,r,i,a){return t===void 0||t.length===0?n():runInterceptorAt(e,t,0,n,r,i,a)}function runInterceptorAt(e,t,n,r,i,a,o){let s=t[n];return s===void 0?r():runOneInterceptor(e,s,()=>runInterceptorAt(e,t,n+1,r,i,a,o),i,a,o)}async function runOneInterceptor(e,n,r,i,a,o){let s=!0,c,l=!1,u=!0,d,recordProtocolFailure=t=>{if(d)return d;let r=interceptorError(n.extension,e,t);return d=r,o?.(r),r},proceed=()=>{if(!s)throw recordProtocolFailure(`called proceed more than once`);if(l)throw recordProtocolFailure(`called proceed after its handler settled`);u=!1,s=!1;let e=startChild(r);return c=settle(e),e},onWriteOutcome=e=>{if(!t(e))throw recordProtocolFailure(`registered a non-function write-outcome listener`);if(!u||l)throw recordProtocolFailure(`registered a write-outcome listener after proceed`);i(Object.freeze({extension:n.extension,listener:e}))},f=exposeHandlerContext(e,proceed,onWriteOutcome,n.controls),p;try{p=Promise.resolve(Reflect.apply(n.handler,void 0,[f]))}catch(e){p=Promise.reject(e)}let m=await settle(p);l=!0,u=!1;let h=m.status===`fulfilled`?m:{...m,failure:d!==void 0&&m.reason===d?d:interceptorFailure(n.extension,e,m.reason,a?.())};if(c!==void 0&&h.status===`rejected`&&h.reason!==d&&o?.(h.failure),c===void 0){if(d)throw d;if(h.status===`rejected`)throw h.failure;if(requiresProceed(e))throw interceptorError(n.extension,e,`completed without proceed`);return h.value}let g=await c;if(g.status===`rejected`){let e=selectExtensionFailures(d,h,g);throw e?retainSuppressedFailures(g.reason,e):g.reason}let _=selectExtensionFailures(d,h,g);return _&&throwExtensionFailures(_),h.value}function selectExtensionFailures(e,t,n){if(e&&n.status===`rejected`&&n.reason===e)return;if(t.status!==`rejected`||e!==void 0&&t.reason===e||n.status===`rejected`&&t.reason===n.reason)return e?[e]:void 0;let r=t.failure;return e?[e,r]:[r]}function exposeHandlerContext(e,t,n,r){return Object.freeze({mode:e.mode,kind:e.kind,model:e.model,operation:e.operation,get input(){return e.input},...e.kind===`model`&&r!==void 0?{controls:a(e.controls,r)}:{},proceed:t,onWriteOutcome:n})}function startChild(e){try{return Promise.resolve(e())}catch(e){return Promise.reject(e)}}async function settle(e){try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}function requiresProceed(e){return e.mode===`array`||e.kind!==`model`||!r(e.operation)}function interceptorFailure(e,t,n,r){return _(n)?n:interceptorError(e,t,`failed`,Error(`Query interceptor rejected with a non-Error value`),r)}function interceptorError(e,t,n,r,i){let a=`Extension "${e}" query handler for ${describeOperation(t)} ${n}.`,o={method:`query`,model:t.model,operation:String(t.operation),...i===void 0?{}:{commitCertainty:i}};return r?new w(a,{cause:r,meta:o}):new w(a,{meta:o})}function describeOperation(e){return e.kind===`model`?`${e.model}.${e.operation}`:e.operation}function throwExtensionFailures(e){let t=e[0];throw e.length===1?t:AggregateError(e,`Query interceptor protocol and handler both failed.`,{cause:t})}function retainSuppressedFailures(e,t){let n=AggregateError([e,...t],`Query execution and extension post-work both failed.`,{cause:e});return L.set(n,e),n}function decomposeQueryCoordinationFailure(e){if(!(e instanceof AggregateError)||!L.has(e))return;let t=L.get(e);if(!(e.cause!==t||e.errors[0]!==t))return Object.freeze({child:t,postWork:Object.freeze(e.errors.slice(1))})}var TransactionWriteOutcomes=class{#e=[];stage(e){for(let t of this.#e)if(t.registration===e)return;this.#e.push({registration:e,state:`pending`})}confirm(e){this.#t(e,`confirmed`)}discard(e){this.#t(e,`discarded`)}discardAll(){for(let e of this.#e)e.state=`discarded`}promoteTo(e){for(let t of this.#e)t.state===`confirmed`&&e.#e.push({...t}),t.state=`discarded`}publishCommitted(){return this.publish(`committed`)}async publish(e){let t=[];for(let e of this.#e)e.state===`confirmed`&&t.push(e.registration),e.state=`discarded`;await publishWriteOutcomes(t,{certainty:e})}#t(e,t){for(let n of this.#e)n.state===`pending`&&e.includes(n.registration)&&(n.state=t)}};async function publishWriteOutcomes(e,t){let n;for(let r of e)try{await r.listener(t)}catch(e){let i=_(e)?e:void 0,a=r.failurePolicy===`boundary-owned`&&i!==void 0?i:new w(`Extension "${r.extension}" write-outcome listener failed after ${t.certainty}.`,{cause:i??Error(`Write-outcome listener rejected with a non-Error value`),meta:{method:`onWriteOutcome`,commitCertainty:t.certainty}});(n??=[]).push(a)}if(n===void 0)return;let[r]=n;if(n.length===1)throw r;let i=AggregateError(n,`Multiple extension write-outcome listeners failed.`,{cause:r});throw R.set(i,n),i}function decomposeWriteOutcomePublicationFailure(e){return e instanceof AggregateError?R.get(e)??[e]:[e]}function createOperationExecutionContext(e,t,n){let r=b(n)?.diagnostics?.includeCallsite===!0?Error(`VibORM operation created here`).stack:void 0;return h({model:e,operation:t},createCorrelationId,n,r)}function createPendingOperationContext(e,t,n,r,i){return Object.freeze({clientId:n,scopeId:r,attribution:createOperationExecutionContext(e,t,i)})}function withOperationErrorContext(e,t){let n=g(e);if(n===void 0)return t();let r=b(m(e))?.diagnostics,annotate=t=>{throw t instanceof v?x(t,{forceContext:!1,driverName:typeof t.meta.driver==`string`?t.meta.driver:`unknown`,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:n,diagnostics:r}):t};try{return t().catch(annotate)}catch(e){return Promise.reject().catch(()=>annotate(e))}}function createPendingOperationInstrumentationFacts(e,t,n,r,i,a,o){return createOperationInstrumentationFacts(e,t,n,r,i,a,o)}function createRawOperationInstrumentationFacts(e,t,n){return createOperationInstrumentationFacts(e,t,void 0,n,n,void 0,!1)}function createOperationInstrumentationFacts(e,t,n,r,a,o,s){let c=b(m(t));if(c?.observesLifecycle===!0)return()=>Object.freeze({kind:`operation`,context:t,identity:u(e),model:n,requestedOperation:r,operation:a,collection:o,complete(e){let n=s?i().readCacheExecutionOutcomes(t):void 0,{failure:r}=e,a=e.status===`failure`&&c.wants(`error-log`)&&isUnloggedError(r)?r:void 0,o=e.status===`failure`&&r instanceof Error&&c.wants(`operation`)?r:void 0;if(!(n===void 0&&a===void 0&&o===void 0))return Object.freeze({kind:`operation`,endedAt:Date.now(),...n===void 0?{}:{readCacheOutcomes:n},...(a??o)===void 0?{}:{failure:a??o},...a===void 0?{skipLog:!0}:{}})}})}async function observeTransactionBatchPhase(e,t,n){let r=b(m(e))?.diagnostics;try{return await n()}catch(n){throw C(n,{driverName:t.driverName,dialect:t.dialect,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:g(e),diagnostics:r,forceContext:!0})}}function createCorrelationId(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function isUnloggedError(e){return e instanceof Error&&!S(e)}function captureExecution(e){try{return e()}catch(e){return Promise.reject(e)}}var PendingExecution=class{#e=null;#t=null;#n=!1;#r;#i;constructor(e,t){this.#r=e,this.#i=t}executeDefault(e){if(this.#t!==null&&this.#t!==`default`)throw T.alreadyExecutedWithDriver(this.#r,this.#i);return this.#e||=(this.#t=`default`,captureExecution(e)),this.#e}executeWith(e,t){if(this.#n)throw T.alreadyExecutedWithDriver(this.#r,this.#i);if(this.#t===`default`)throw T.alreadyExecutedDefault(this.#r,this.#i);if(this.#t!==null&&this.#t!==e)throw T.differentDriverConflict(this.#r,this.#i);return this.#e||=(this.#t=e,captureExecution(t)),this.#e}reserveWith(e){if(this.#t===`default`)throw T.alreadyExecutedDefault(this.#r,this.#i);if(this.#t!==null)throw this.#t===e?T.alreadyExecutedWithDriver(this.#r,this.#i):T.differentDriverConflict(this.#r,this.#i);this.#t=e,this.#n=!0}executeReserved(e){return this.#e||=captureExecution(e),this.#e}};const z=Object.freeze({accessor:opaqueInspectionValue(`accessor`),function:opaqueInspectionValue(`function`),unsupported:opaqueInspectionValue(`unsupported`)}),B=Object.getOwnPropertyDescriptor(O.prototype,`strings`)?.get,V=Object.getOwnPropertyDescriptor(O.prototype,`values`)?.get;function opaqueInspectionValue(e){let t=Object.create(null);return t.opaque=e,Object.freeze(t)}function snapshotQueryInput(e){return snapshotOwn(e,new Map,!1)}function snapshotOwn(e,t,n){let r=n?[]:Object.create(null);t.set(e,r);let i;try{i=Reflect.ownKeys(e)}catch{return t.set(e,z.unsupported),z.unsupported}for(let a of i){let i;try{i=Object.getOwnPropertyDescriptor(e,a)}catch{return t.set(e,z.unsupported),z.unsupported}if(i!==void 0){if(n&&a===`length`){Object.defineProperty(r,a,i);continue}i.enumerable&&Object.defineProperty(r,a,{configurable:!1,enumerable:!0,value:`value`in i?snapshotValue(i.value,t):z.accessor,writable:!1})}}return Object.freeze(r)}function snapshotValue(e,t){if(typeof e==`function`)return z.function;if(typeof e!=`object`||!e)return e;if(t.has(e))return t.get(e);try{if(Array.isArray(e))return snapshotOwn(e,t,!0);let r=Object.getPrototypeOf(e);if(r===O.prototype&&e instanceof O)return snapshotSql(e,t);if(r===Date.prototype&&e instanceof Date){let n=Object.freeze(new Date(Date.prototype.getTime.call(e)));return t.set(e,n),n}if(e instanceof Uint8Array){let n=new Uint8Array(e);return t.set(e,n),n}if(r===ArrayBuffer.prototype&&e instanceof ArrayBuffer){let n=e.slice(0);return t.set(e,n),n}if(r===Map.prototype&&e instanceof Map){let n=new Map;return t.set(e,n),Map.prototype.forEach.call(e,(e,r)=>{n.set(snapshotValue(r,t),snapshotValue(e,t))}),n}if(r===Set.prototype&&e instanceof Set){let n=new Set;return t.set(e,n),Set.prototype.forEach.call(e,e=>{n.add(snapshotValue(e,t))}),n}if(ArrayBuffer.isView(e)){let n=structuredClone(e);return t.set(e,n),n}if((r===Object.prototype||r===null)&&n(e))return snapshotOwn(e,t,!1)}catch{}return t.set(e,z.unsupported),z.unsupported}function snapshotSql(e,t){if(!(B&&V))throw TypeError(`Sql inspection getters are unavailable`);let n=Reflect.apply(B,e,[]),r=Reflect.apply(V,e,[]),i=Array(n.length);for(let e=0;e<n.length;e+=1){let t=Object.getOwnPropertyDescriptor(n,e);if(!(t&&`value`in t&&typeof t.value==`string`))throw TypeError(`Sql inspection strings are not plain data values`);i[e]=t.value}let a=Array(r.length),o=new O(i,a);t.set(e,o);for(let e=0;e<r.length;e+=1){let n=Object.getOwnPropertyDescriptor(r,e);a[e]=n&&`value`in n?snapshotValue(n.value,t):z.accessor}o.toStatement(`?`),o.toStatement(`$n`),o.toStatement(`:n`);for(let e of Reflect.ownKeys(o)){let t=Reflect.get(o,e);typeof t==`object`&&t&&Object.freeze(t)}return Object.freeze(o),o}function compileBindBudgetChunks(e,t,n){if(e===0)return[];let r=n(0,e);if(t===void 0||r.values.length<=t||e===1)return[{start:0,end:e,statement:r}];let i=[],a=0;for(;a<e;){let r=a+1,o=Math.min(e,a+1),s;for(;;){let i=n(a,o);if(i.values.length>t||(s={start:a,end:o,statement:i},o===e))break;r=o+1,o=Math.min(e,a+(o-a)*2)}if(s?.end!==e)for(--o;r<=o;){let e=r+Math.floor((o-r)/2),i=n(a,e);i.values.length<=t?(s={start:a,end:e,statement:i},r=e+1):o=e-1}let c=s??{start:a,end:a+1,statement:n(a,a+1)};i.push(c),a=c.end}return i}const H=Symbol(`run alone`),U={string:e=>typeof e==`string`,int:e=>typeof e==`number`&&Number.isSafeInteger(e),bigint:e=>typeof e==`bigint`};let W;const G=new WeakSet;function enableFindUniqueBatching(e){G.add(e)}const K=(()=>{let e=globalThis.process,t=e?.nextTick;return typeof t==`function`?n=>t.call(e,n):queueMicrotask})();function batchFindUnique(e){if(!engineBatches(e.engine)||e.engine.driver.holdsConnectionScope())return;let t;try{t=e.routed.preparedArgs}catch{return}let n=keyOf(e.model,t.where);if(n===void 0)return;let{where:r,...i}=e.args,a=signatureOf(i);if(a===void 0)return;let o,s=new Promise(e=>{o=e}),c,l=new Promise(e=>{c=e}),u={values:n.values,signature:signatureOf(n.values),orThrow:e.requested!==`findUnique`,decide:o};return(enqueue(e,`${n.selector}\u0000${a}`,n,u,c)?l.then(e=>(runBatch(e),s)):s).then(t=>t===H?e.run():t.value)}function engineBatches(e){let{driver:t}=e;return G.has(e.route)&&t===e.route.driver&&(e.extensionChain?.statement.length??0)===0&&t.result?.parseResult===void 0&&t.adapter.result.parseResult===P}function keyOf(e,t){if(!n(t))return;let r=Object.keys(t);if(r.length!==1)return;let i=r[0],a=k(e,i);if(a===void 0)return;let o=t[i],s;if(a.name===void 0)s=[o];else{if(!n(o)||Object.keys(o).length!==a.fields.length)return;s=a.fields.map(e=>o[e])}let{scalars:c,omit:l}=e[`~`].state,u=!1;for(let[e,t]of a.fields.entries()){let n=c[t]?.[`~`].state;if(!(n&&!n.array&&U[n.type])?.(s[e])||l?.[t]===!0)return;n.type===`string`&&(u=!0)}return{selector:i,fields:a.fields,values:s,textKey:u}}function enqueue(e,t,n,r,i){W===void 0&&(W=new Map,K(flush));let a=W.get(e.engine);a===void 0&&W.set(e.engine,a=new Map);let o=`${e.model[`~`].names.ts}\u0000${t}`,s=a.get(o);s===void 0&&a.set(o,s=[]);let c=s.find(t=>sameControls(t.leader.controls,e.controls)),l=!1;if(c===void 0){let t={leader:e,start:()=>i(t),fields:n.fields,textKey:n.textKey,members:[]};c=t,s.push(c),l=!0}return c.members.push(r),l}function sameControls(e,t){if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&e[n]===t[n])}function flush(){let e=W;W=void 0;for(let t of e.values())for(let e of t.values())for(let t of e)t.start()}function runBatch(e){let{members:t}=e,runAlone=e=>{for(let t of e)t.decide(H)};if(t.length===1){runAlone(t);return}try{let n=new Map;for(let e of t){let t=n.get(e.signature);t?t.push(e):n.set(e.signature,[e])}let r=planBatch(e,[...n.values()]),{engine:i}=e.leader,a=p(e.leader.context);for(let t of r.chunks){let o=t.signatures.flatMap(e=>n.get(e));t.read.execute({committedWriteSegment:void 0,context:a,driverOverride:void 0,engineDriver:i.driver,isWrite:!1,writeMayBeVisible:void 0}).then(i=>{try{dispatch(e,t,n,r.injected,i)}catch{runAlone(o)}},()=>runAlone(o))}}catch{runAlone(t)}}function planBatch(e,t){let{leader:n,fields:r}=e,i=projectionWithKey(n,r),a=n.rows(),o=new Map,read=(e,s)=>{let c=`${e}:${s}`,l=o.get(c);if(l===void 0){let u=t.slice(e,s).map(e=>e[0].values);l=n.engine.route.operation(n.model,`findMany`,{...i.args,where:mergedWhere(r,u)},a),o.set(c,l)}return l},s=t.map(e=>e[0].signature),c=F(n.engine.driver.maxBindParametersPerStatement);return{chunks:(c===void 0?[{start:0,end:t.length}]:compileBindBudgetChunks(t.length,c,(e,t)=>read(e,t).buildStatement())).map(({start:e,end:t})=>({signatures:s.slice(e,t),read:read(e,t)})),injected:i.injected}}function mergedWhere(e,t){return e.length===1?{[e[0]]:{in:t.map(e=>e[0])}}:{OR:t.map(t=>Object.fromEntries(e.map((e,n)=>[e,t[n]])))}}function projectionWithKey(e,t){let{where:r,...i}=e.args,a=e.routed.preparedArgs.select,o=[];if(!n(a))return{args:i,injected:o};for(let e of t)a[e]!==!0&&(n(i.select)&&(i.select={...i.select,[e]:!0}),n(i.omit)&&(i.omit={...i.omit,[e]:!1}),o.push(e));return{args:i,injected:o}}function dispatch(e,t,n,r,i){let a=new Map;for(let t of i){let n=signatureOf(e.fields.map(e=>t[e]));for(let e of r)delete t[e];a.has(n)||a.set(n,t)}for(let r of t.signatures){let t=a.get(r);for(let[i,a]of n.get(r).entries())t===void 0?a.orThrow||e.textKey?a.decide(H):a.decide({value:null}):a.decide({value:i===0?t:copyResult(t)})}}function signatureOf(e){switch(typeof e){case`undefined`:return`u`;case`boolean`:case`number`:return String(e);case`string`:return JSON.stringify(e);case`bigint`:return`${e}n`;case`object`:break;default:return}if(e===null)return`null`;if(Array.isArray(e)){let t=[];for(let n of e){let e=signatureOf(n);if(e===void 0)return;t.push(e)}return`[${t.join(`,`)}]`}if(e instanceof Date)return`D${e.getTime()}`;let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return;let n=[];for(let[t,r]of Object.entries(e)){let e=signatureOf(r);if(e===void 0)return;n.push(`${JSON.stringify(t)}:${e}`)}return`{${n.join(`,`)}}`}function copyResult(e,t=new Map){if(typeof e!=`object`||!e)return e;let n=t.get(e);if(n!==void 0)return n;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Uint8Array)return Uint8Array.prototype.slice.call(e);if(Array.isArray(e)){let n=[];t.set(e,n);for(let r of e)n.push(copyResult(r,t));return n}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let i=Object.create(r);t.set(e,i);for(let[n,r]of Object.entries(e))Object.defineProperty(i,n,{value:copyResult(r,t),enumerable:!0,writable:!0,configurable:!0});return i}const q=Symbol.for(`viborm.pendingOperation`);let attachPendingCacheExecutionFriend,readPendingCacheResultFriend;function combineWriteNotifications(e,t){return e===void 0?t:t===void 0||t===e?e:async()=>{let n=!1,r;try{await e()}catch(e){n=!0,r=e}try{await t()}catch(e){throw n?ee(r,e,`Write publication callbacks both failed.`):e}if(n)throw r}}const J=Object.freeze({});let createPendingOperationFriend,Y;var te=class PendingOperation{[Symbol.toStringTag]=`Promise`;[q]=!0;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=!1;#p;#m;#h;#g;#_;#v=!1;static{createPendingOperationFriend=(e,t,n,r,i,a,o)=>new PendingOperation(J,e,t,n,r,i,void 0,void 0,a===void 0?void 0:{prepare:a,status:`pending`},void 0,o),attachPendingCacheExecutionFriend=(e,t)=>e.#L(t),readPendingCacheResultFriend=e=>({get args(){return e.cacheKeyArgs()},get controls(){return e.#y(),e.#l?.controls},get codec(){return e.#E()},executionContext:e.#e.attribution}),Y=Object.freeze({clientId:e=>e.#e.clientId,scopeId:e=>e.#e.scopeId,model:e=>e.#i,operation:e=>e.#a,context:e=>e.#e.attribution,requiresInterception:e=>{let t=String(e.#o.originalOperation),n=d(e.#t.extensionChain,`request`,e.#i,t),r=n!==void 0&&n.length>0&&(e.#t.extensionChain?.observe.length??0)>0,i=d(e.#t.extensionChain,`query`,e.#i,t);return r||i!==void 0&&i.length>0||e.#u!==void 0&&(!e.#f||e.#d!==void 0)},prepareAdmission:(e,t=`input`)=>{e.#w(),t===`plan`&&e.#C()},stagePackageWriteOutcomes:(e,t)=>{let n=e.#b();n!==void 0&&t.stage(n)},startInterception:(e,t,n,i)=>{let a=String(e.#o.originalOperation),o=d(e.#t.extensionChain,`query`,e.#i,a),s=e.#w(),c=e.#b();return(o===void 0||o.length===0)&&c===void 0?t():executePreparedQuery(o===void 0||o.length===0?void 0:e.#T(`array`,s),o,t,!r(a),n,i,c)},executeCore:(e,t,n)=>e.#s.executeReserved(()=>e.#P(t,n?.committed,n?.mayHaveCommitted)),isWrite:e=>!r(String(e.#o.originalOperation)),hasObservation:e=>(e.#t.extensionChain?.observe.length??0)>0,observe:(e,t,n)=>{let r=e.#t.extensionChain?.observe;return r===void 0||r.length===0?t():y(r,String(e.#o.originalOperation),e.#i,t,n,e.#k())},reserveWith:(e,t)=>{e.#s.reserveWith(t)},executeWith:(e,t)=>{let n=e.#t.extensionChain?.observe;return n===void 0||n.length===0?e.#s.executeWith(t,()=>e.#P(t)):e.#s.executeWith(t,()=>y(n,String(e.#o.originalOperation),e.#i,()=>e.#P(t),()=>e.#m===void 0?void 0:{commitCertainty:e.#m},e.#k()))},finishResult:(e,t)=>e.#o.finishResult?e.#o.finishResult(t):t,prepare:e=>e.#C()?.queries[0],prepareBatch:async e=>{let t=await e.#x().prepareBatch(e.#e.attribution),n=e.#o.takeResult;return n&&t?{...t,parseResult:e=>n(t.parseResult(e))}:t},parseResult:(e,t)=>{let n=e.#C();if(!n)throw new E(`Operation '${e.#a}' on model '${e.#i}' publishes no single driver result to parse.`);let r=e.#o.takeResult,i=n.parseResult([t]);return r?r(i):i},observeBatchPhase:(e,t,n)=>observeTransactionBatchPhase(e.#e.attribution,t,n)}),N(PendingOperation.prototype,e=>#e in e,Y),Object.freeze(PendingOperation.prototype)}constructor(e,t,n,r,i,a,o,s,c,l,u){if(e!==J)throw new D;this.#t=t,this.#n=n,this.#r=i,this.#c=s,this.#l=c,this.#u=u,this.#p=l,this.#h=t.route;let d=r.endsWith(`OrThrow`);this.#a=d?r.slice(0,-7):r,this.#i=n[`~`].names.ts??`unknown`,this.#s=new PendingExecution(this.#i,this.#a),this.#o=Object.freeze({...a,throwIfNotFound:d||a?.throwIfNotFound,originalOperation:a?.originalOperation??r}),this.#e=o??createPendingOperationContext(this.#i,this.#a,t.clientId,t.scopeId,t.extensionChain),Object.freeze(this)}#y(){let e=this.#l;if(e===void 0)return this.#r;if(e.status===`success`&&e.args)return e.args;if(e.status===`failure`)throw e.error;try{let t=f(this.#t.extensionChain,this.#i,String(this.#o.originalOperation)),n=t.length===0?void 0:o(this.#i,this.#a,this.#r,t,this.#t.bound),r=e.prepare(n?.args??this.#r,n?.controls);return e.args=r,e.controls=n?.controls,e.status=`success`,r}catch(t){throw e.error=t,e.status=`failure`,t}}#b(){return this.#f?this.#d:(this.#d=this.#u?.(this.#e.attribution,this.#l?.controls),this.#f=!0,this.#d)}#x(){let e=this.#p?.routed;if(e)return e;if(this.#g)return this.#g;if(!l.has(this.#a))throw new E(`Unknown operation '${this.#a}' on model '${this.#i}'. Known operations: ${[...l].sort().join(`, `)}.`);let t=this.#y();this.#b();let n=this.#h.operation(this.#n,String(this.#o.originalOperation),t,this.#S());return this.#g=n,this.#p&&(this.#p.routed=n),n}#S(){let e=this.#t.extensionChain?.callRows;return e&&c(e,this.#i,this.#l?.controls)}#C(){if(this.#v)return this.#_;let e=this.#x().prepareSingle(this.#e.attribution);return this.#_=e?.queries.length===1?e:void 0,this.#v=!0,this.#_}#w(){return this.#x().preparedArgs}#T(e,t){let n=this.#l?.controls,r;return Object.freeze({mode:e,kind:`model`,model:this.#i,operation:String(this.#o.originalOperation),get input(){return r??=snapshotQueryInput(t),r},...n===void 0?{}:{controls:n}})}#E(){return this.#x().cacheResultCodec()}#D(){return this.#s.executeDefault(()=>{let e=this.#t.extensionChain?.observe;return e===void 0||e.length===0?this.#O(this.#A()):y(e,String(this.#o.originalOperation),this.#i,()=>this.#O(this.#A()),()=>this.#m===void 0?void 0:{commitCertainty:this.#m},this.#k())})}#O(e){let t=this.#o.finishResult;return t?e.then(e=>t(e)):e}#k(){return createPendingOperationInstrumentationFacts(this.#t.driver,this.#e.attribution,this.#i,String(this.#o.originalOperation),String(this.#a),this.#n[`~`].names.sql??this.#i,s(this.#o))}#A(e,t,n){return withOperationErrorContext(this.#e.attribution,()=>this.#j(e,t,n))}#j(e,t,n){let r=this.#N(`committed`),i=this.#N(`may-have-committed`),a=String(this.#o.originalOperation),o=d(this.#t.extensionChain,`query`,this.#i,a);return(o===void 0||o.length===0)&&this.#u===void 0?this.#P(e,combineWriteNotifications(t,r),combineWriteNotifications(n,i)):this.#M(o,a,r,i,e,t,n)}#M(e,t,n,i,a,o,s){let c;try{c=this.#w()}catch(e){return Promise.reject(e)}let l=this.#b();return(e===void 0||e.length===0)&&l===void 0?this.#P(a,combineWriteNotifications(o,n),combineWriteNotifications(s,i)):executePreparedQuery(e===void 0||e.length===0?void 0:this.#T(this.#t.transactionWriteOutcomes?`transaction`:`direct`,c),e,e=>this.#P(a,combineWriteNotifications(o,combineWriteNotifications(e?.committed,n)),combineWriteNotifications(s,combineWriteNotifications(e?.mayHaveCommitted,i))),!r(t),this.#t.transactionWriteOutcomes,void 0,l)}#N(e){if(!(this.#t.transactionWriteOutcomes!==void 0||(this.#t.extensionChain?.observe.length??0)===0))return async()=>{(e===`committed`||this.#m===void 0)&&(this.#m=e)}}#P(e,t,n){let r=this.#c?this.#c(e,t,n):this.#F(e,t,n),i=this.#o.takeResult;return i?r.then(e=>i(e,!0)):r}#F(e,t,n){let i;try{i=this.#x()}catch(e){return Promise.reject(e)}let run=()=>i.execute({committedWriteSegment:t,context:this.#e.attribution,driverOverride:e,engineDriver:this.#t.driver,isWrite:!r(String(this.#o.originalOperation)),writeMayBeVisible:n});if(this.#a===`findUnique`&&e===void 0){let e=batchFindUnique({engine:this.#t,model:this.#n,requested:String(this.#o.originalOperation),args:this.#y(),controls:this.#l?.controls,rows:()=>this.#S(),routed:i,context:this.#e.attribution,run});if(e!==void 0)return e}return run()}getArgs(){return this.#r}cacheKeyArgs(){let e=this.#I();if(!e)throw new E(`Operation '${this.#a}' on model '${this.#i}' exposes no validated payload to key a cache entry on.`);return e}#I(){if(r(this.#a))return this.#x().preparedArgs}buildStatement(){return this.#x().buildStatement()}#L(e){let t=this.#p??={routed:this.#g},deferredExecution=(t,n,r)=>e((e,i,a)=>this.#P(e??t,combineWriteNotifications(i,n),combineWriteNotifications(a,r)),t);return new PendingOperation(J,this.#t,this.#n,this.#a,this.#r,this.#o,this.#e,deferredExecution,this.#l,t,this.#u)}then(e,t){return this.#D().then(e,t)}catch(e){return this.#D().catch(e)}finally(e){return this.#D().finally(e)}};function createPendingOperation(e,t,n,r,i,a,o){return createPendingOperationFriend(e,t,n,r,i,a,o)}function attachPendingCacheExecution(e,t){return attachPendingCacheExecutionFriend(e,t)}function readPendingCacheResult(e){return readPendingCacheResultFriend(e)}function isPendingOperation(e){return typeof e==`object`&&!!e&&q in e&&e[q]===!0}const X=`0viborm_distance`,Z=`0viborm_relation_counts`,Q=`0viborm_empty_row`,gateResultKey=e=>`0viborm_gate:${e}`,ne=`0viborm_cursor_`,re=`0viborm_orphans`;function getAggregateResultKey(e){return`0viborm_aggregate:${e.slice(1)}`}function getAggregateResultName(e){switch(e){case`0viborm_aggregate:count`:return`_count`;case`0viborm_aggregate:avg`:return`_avg`;case`0viborm_aggregate:sum`:return`_sum`;case`0viborm_aggregate:min`:return`_min`;case`0viborm_aggregate:max`:return`_max`;default:return}}function getGroupByFields(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?[e]:[];if(new Set(t).size!==t.length)throw new E(`GroupBy operation does not allow duplicate fields in 'by'`);return t}const ie=new Set([`findFirst`,`findMany`,`findUnique`,`create`,`createManyAndReturn`,`update`,`updateManyAndReturn`,`delete`,`deleteManyAndReturn`,`upsert`]),$=`Distance select supports only one _distance field per select.`;function selectedArm(e,t,r){let i=n(e)?e:void 0;if(!t)return getOwnValue(i,r)??!0;let a=getOwnValue(i,`only`);if(Array.isArray(a)&&!a.includes(r))return;let o=getOwnValue(i,`variants`);return(n(o)?getOwnValue(o,r):void 0)??!0}const ae=[`_count`,`_avg`,`_sum`,`_min`,`_max`];function getOwnValue(e,t){return e&&Object.hasOwn(e,t)?e[t]:void 0}function createShape(e,t=new Map,n=new Map,r=new Set,i=new Map,a){if(new Set(e).size!==e.length)throw new E(`The requested result shape contains colliding output columns.`);return{carrier:`rows`,rawKeys:e,...a?{distanceScalar:a}:{},relations:t,polymorphic:i,aggregates:n,relationCounts:r}}function selectedEntries(e){return n(e)?Object.entries(e).filter(([,e])=>e!==!1&&e!==void 0):[]}function getNestedSelection(e){if(!n(e))return{};let t={},r=getOwnValue(e,`select`),i=getOwnValue(e,`include`);return n(r)&&(t.select=r),n(i)&&(t.include=i),t}function buildModelShape(e,t,r){let i=[],a=new Map,o=new Map,s=e[`~`].state.scalars,c=e[`~`].state.relations,l=getOwnValue(t,`select`),u=getOwnValue(t,`include`),d=n(l)?l:void 0,f=n(u)?u:void 0,p=!1,m;if(d)for(let[e,t]of Object.entries(d)){let r=getOwnValue(s,e);if(r){if(t===!0){i.push(e);continue}if(n(t)&&Object.hasOwn(t,`_distance`)){if(p)throw new E($);p=!0,m=r,i.push(X)}}}else for(let t of j(e))i.push(t);addSelectedRelations(e,c,d,i,a,r),addSelectedPolymorphicRelations(e,d,i,o,r),addSelectedRelations(e,c,f,i,a,r),addSelectedPolymorphicRelations(e,f,i,o,r);let h=[getOwnValue(d,`_count`),getOwnValue(f,`_count`)],g=new Set;for(let e of h){if(!n(e))continue;let t=getOwnValue(e,`select`);if(n(t))for(let[e]of selectedEntries(t)){let t=getOwnValue(c,e);if(!t)continue;let n=t[`~`].state;M(n)&&n.cardinality!==`many`||g.add(e)}}return g.size>0&&i.push(Z),i.length===0&&i.push(Q),createShape(i,a,new Map,g,o,m)}function admittedRecurrence(e){if(n(e))return getOwnValue(e,`recurse`)}function addSelectedRelations(e,t,n,r,i,a){for(let[o,s]of selectedEntries(n)){let n=getOwnValue(t,o);if(!n||M(n[`~`].state))continue;let c=n[`~`].settleTarget();r.push(o);let l=buildModelShape(c,getNestedSelection(s),a),u=a.get(e)?.get(o),d=admittedRecurrence(s);i.set(o,{model:c,shape:l,cardinality:n[`~`].state.cardinality,optional:u!==void 0&&A(u),...d?{recurrence:d}:{}})}}function addSelectedPolymorphicRelations(e,t,n,r,i){let a=e[`~`].state.relations;for(let[o,s]of selectedEntries(t)){let t=getOwnValue(a,o);if(!t)continue;let c=t[`~`].state;if(!M(c))continue;let l=c.cardinality===`many`,u=new Map;for(let e of Object.keys(c.target.entries)){let n=selectedArm(s,l,e);if(n===void 0)continue;let r=t[`~`].settleTarget(e);u.set(e,{model:r,shape:buildModelShape(r,getNestedSelection(n),i)})}n.push(o);let d=i.get(e)?.get(o);r.set(o,{cardinality:c.cardinality,optional:d!==void 0&&A(d),variants:u})}}function buildAggregateShape(e,t=[]){let n=[...t],r=new Set(t),i=new Map;for(let t of ae){let a=getOwnValue(e,t);if(a===void 0||a===!1)continue;let o;if(!(t===`_count`&&a===!0)){let e=selectedEntries(a);if(e.length===0)continue;o=new Set(e.map(([e])=>e))}if(r.has(t))throw new E(`GroupBy cannot return both grouped scalar '${t}' and aggregate '${t}' in one result.`);let s=getAggregateResultKey(t);n.push(s),r.add(t),i.set(s,{...o?{fields:o}:{}})}return createShape(n,new Map,i)}function buildCountShape(e){let t=selectedEntries(getOwnValue(e,`select`)).map(([e])=>e);return{...createShape(t.length===0?[I]:t),carrier:`count`}}function buildExpectedResultShape(e,t,n,r){if(t===`count`)return buildCountShape(n);if(t===`exist`)return{...createShape([I]),carrier:`existence`};if(t===`aggregate`)return buildAggregateShape(n);if(t===`groupBy`)return buildAggregateShape(n,getGroupByFields(getOwnValue(n,`by`)));if(ie.has(t))return buildModelShape(e,n,r)}export{withOperationErrorContext as C,executePreparedQuery as D,decomposeWriteOutcomePublicationFailure as E,observeTransactionBatchPhase as S,decomposeQueryCoordinationFailure as T,compileBindBudgetChunks as _,X as a,createOperationExecutionContext as b,Z as c,te as d,attachPendingCacheExecution as f,enableFindUniqueBatching as g,readPendingCacheResult as h,ne as i,gateResultKey as l,isPendingOperation as m,buildExpectedResultShape as n,Q as o,createPendingOperation as p,selectedArm as r,re as s,$ as t,getAggregateResultName as u,snapshotQueryInput as v,TransactionWriteOutcomes as w,createRawOperationInstrumentationFacts as x,PendingExecution as y};
2
+ //# sourceMappingURL=result-shape-C8QFUuIt.mjs.map