viborm 1.5.1 → 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 (254) hide show
  1. package/README.md +4 -2
  2. package/dist/{adapter-internals-Dagucesf.mjs → adapter-internals-DULbfdmQ.mjs} +1 -1
  3. package/dist/{adapter-internals-Dagucesf.mjs.map → adapter-internals-DULbfdmQ.mjs.map} +1 -1
  4. package/dist/{adapter-namespace-DuugUuQa.mjs → adapter-namespace-CFtC8LbT.mjs} +2 -2
  5. package/dist/{adapter-namespace-DuugUuQa.mjs.map → adapter-namespace-CFtC8LbT.mjs.map} +1 -1
  6. package/dist/{adapter-result-parser-B63ouFIz.mjs → adapter-result-parser-C0vW9am8.mjs} +1 -1
  7. package/dist/{adapter-result-parser-B63ouFIz.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-BU1R9byi.mjs → array-literal-Dohoq5rT.mjs} +1 -1
  11. package/dist/{array-literal-BU1R9byi.mjs.map → array-literal-Dohoq5rT.mjs.map} +1 -1
  12. package/dist/{batch-refs-C3MTcVre.mjs → batch-refs-cBYAKzaE.mjs} +2 -2
  13. package/dist/{batch-refs-C3MTcVre.mjs.map → batch-refs-cBYAKzaE.mjs.map} +1 -1
  14. package/dist/bind-parameter-capacity-4OU6feZG.mjs +2 -0
  15. package/dist/{bind-parameter-capacity-faPOSaLz.mjs.map → bind-parameter-capacity-4OU6feZG.mjs.map} +1 -1
  16. package/dist/{builder-ClblW6Lj.mjs → builder-D0GQK-fA.mjs} +2 -2
  17. package/dist/{builder-ClblW6Lj.mjs.map → builder-D0GQK-fA.mjs.map} +1 -1
  18. package/dist/bun-sql.d.mts +1 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sqlite.d.mts +1 -1
  21. package/dist/bun-sqlite.mjs +1 -1
  22. package/dist/bun-sqlite.mjs.map +1 -1
  23. package/dist/cache/cloudflare-kv.d.mts +1 -1
  24. package/dist/cache/cloudflare-kv.mjs +1 -1
  25. package/dist/cache/memory.d.mts +1 -1
  26. package/dist/cache/memory.mjs +1 -1
  27. package/dist/cache.d.mts +1 -1
  28. package/dist/cache.mjs +1 -1
  29. package/dist/{canonical-json-JLUMrnoq.mjs → canonical-json-D_FgOt4S.mjs} +1 -1
  30. package/dist/{canonical-json-JLUMrnoq.mjs.map → canonical-json-D_FgOt4S.mjs.map} +1 -1
  31. package/dist/chain-BQoDfo80.mjs +2 -0
  32. package/dist/{chain-C1VPkUpC.mjs.map → chain-BQoDfo80.mjs.map} +1 -1
  33. package/dist/cli.mjs +1 -1
  34. package/dist/{client-C1MxqFtt.mjs → client-BCcIdDl8.mjs} +4 -4
  35. package/dist/client-BCcIdDl8.mjs.map +1 -0
  36. package/dist/client-BqgVSbk0.mjs +2 -0
  37. package/dist/client-BqgVSbk0.mjs.map +1 -0
  38. package/dist/{client-DyIsSin0.d.mts → client-C5BGyg5n.d.mts} +3 -3
  39. package/dist/client.d.mts +1 -1
  40. package/dist/client.mjs +1 -1
  41. package/dist/{clock-CK41KO7t.mjs → clock-QtW83Dcm.mjs} +1 -1
  42. package/dist/{clock-CK41KO7t.mjs.map → clock-QtW83Dcm.mjs.map} +1 -1
  43. package/dist/config.d.mts +2 -2
  44. package/dist/config.mjs +1 -1
  45. package/dist/{current-CKQ4EgeM.mjs → current-CEWlNJcP.mjs} +1 -1
  46. package/dist/{current-CKQ4EgeM.mjs.map → current-CEWlNJcP.mjs.map} +1 -1
  47. package/dist/d1.d.mts +1 -1
  48. package/dist/d1.mjs +1 -1
  49. package/dist/d1.mjs.map +1 -1
  50. package/dist/{datetime-physical-codec-DfVmz14E.mjs → datetime-physical-codec-Bl6M6vF5.mjs} +2 -2
  51. package/dist/{datetime-physical-codec-DfVmz14E.mjs.map → datetime-physical-codec-Bl6M6vF5.mjs.map} +1 -1
  52. package/dist/{driver-DpQbSOUD.mjs → driver-Dv2GJyGs.mjs} +2 -2
  53. package/dist/{driver-DpQbSOUD.mjs.map → driver-Dv2GJyGs.mjs.map} +1 -1
  54. package/dist/driver-szWYBmjD.mjs +2 -0
  55. package/dist/{driver-aqfbJdZC.mjs.map → driver-szWYBmjD.mjs.map} +1 -1
  56. package/dist/driver.d.mts +1 -1
  57. package/dist/driver.mjs +1 -1
  58. package/dist/error-mapping-DRY49A3C.mjs +2 -0
  59. package/dist/error-mapping-DRY49A3C.mjs.map +1 -0
  60. package/dist/every-DIG9CPly.mjs +2 -0
  61. package/dist/{every-BUf842ai.mjs.map → every-DIG9CPly.mjs.map} +1 -1
  62. package/dist/{fs-estate-BXNX7l62.mjs → fs-estate-DNCM7hYC.mjs} +2 -2
  63. package/dist/{fs-estate-BXNX7l62.mjs.map → fs-estate-DNCM7hYC.mjs.map} +1 -1
  64. package/dist/{geo-area-codec-DQpSEgSD.mjs → geo-area-codec-H50rrGiF.mjs} +2 -2
  65. package/dist/{geo-area-codec-DQpSEgSD.mjs.map → geo-area-codec-H50rrGiF.mjs.map} +1 -1
  66. package/dist/geo-point-codec-mjROsQX-.mjs +2 -0
  67. package/dist/{geo-point-codec-DcUTvoEg.mjs.map → geo-point-codec-mjROsQX-.mjs.map} +1 -1
  68. package/dist/{hydration-BK6vRndL.mjs → hydration-BQ7tYLtA.mjs} +2 -2
  69. package/dist/{hydration-BK6vRndL.mjs.map → hydration-BQ7tYLtA.mjs.map} +1 -1
  70. package/dist/{identifier-conversion-8ldidfgu.mjs → identifier-conversion-DV63mwKG.mjs} +2 -2
  71. package/dist/{identifier-conversion-8ldidfgu.mjs.map → identifier-conversion-DV63mwKG.mjs.map} +1 -1
  72. package/dist/{identity-Bu6jbgym.mjs → identity-B75EaVTM.mjs} +2 -2
  73. package/dist/{identity-Bu6jbgym.mjs.map → identity-B75EaVTM.mjs.map} +1 -1
  74. package/dist/{index-Ci8b13Lm.d.mts → index-DRX_LLQM.d.mts} +47 -8
  75. package/dist/index.d.mts +2 -2
  76. package/dist/index.mjs +1 -1
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/instrumentation.d.mts +1 -1
  79. package/dist/instrumentation.mjs +1 -1
  80. package/dist/{invariant-BnLYqsHO.mjs → invariant-B5znICP_.mjs} +1 -1
  81. package/dist/{invariant-BnLYqsHO.mjs.map → invariant-B5znICP_.mjs.map} +1 -1
  82. package/dist/{json-number-CAfNAqDB.mjs → json-number-DoseUwuo.mjs} +1 -1
  83. package/dist/{json-number-CAfNAqDB.mjs.map → json-number-DoseUwuo.mjs.map} +1 -1
  84. package/dist/{key-DJXcPZR_.mjs → key-rszcmZdB.mjs} +2 -2
  85. package/dist/{key-DJXcPZR_.mjs.map → key-rszcmZdB.mjs.map} +1 -1
  86. package/dist/{libsql-Dmtj0O4E.mjs → libsql-CAZVcr9G.mjs} +2 -2
  87. package/dist/{libsql-Dmtj0O4E.mjs.map → libsql-CAZVcr9G.mjs.map} +1 -1
  88. package/dist/libsql.d.mts +1 -1
  89. package/dist/libsql.mjs +1 -1
  90. package/dist/libsql.mjs.map +1 -1
  91. package/dist/{memory-b-dafk9S.mjs → memory-CqWRO6-3.mjs} +2 -2
  92. package/dist/{memory-b-dafk9S.mjs.map → memory-CqWRO6-3.mjs.map} +1 -1
  93. package/dist/migrations/mysql.d.mts +5 -5
  94. package/dist/migrations/mysql.mjs +1 -1
  95. package/dist/migrations/postgres.d.mts +5 -5
  96. package/dist/migrations/postgres.mjs +1 -1
  97. package/dist/migrations/sqlite.d.mts +5 -5
  98. package/dist/migrations/sqlite.mjs +1 -1
  99. package/dist/migrations/storage/durable-object.d.mts +1 -1
  100. package/dist/migrations/storage/durable-object.mjs +1 -1
  101. package/dist/migrations/storage/fs.d.mts +1 -1
  102. package/dist/migrations/storage/fs.mjs +1 -1
  103. package/dist/migrations/storage/r2.d.mts +1 -1
  104. package/dist/migrations/storage/r2.mjs +1 -1
  105. package/dist/migrations/tenant.d.mts +3 -3
  106. package/dist/migrations/tenant.mjs +1 -1
  107. package/dist/migrations.d.mts +5 -5
  108. package/dist/migrations.mjs +1 -1
  109. package/dist/{mysql-DAaUSeBw.mjs → mysql-BPPBSJzl.mjs} +2 -2
  110. package/dist/{mysql-DAaUSeBw.mjs.map → mysql-BPPBSJzl.mjs.map} +1 -1
  111. package/dist/mysql-adapter-Dbo7l0lI.mjs +2 -0
  112. package/dist/mysql-adapter-Dbo7l0lI.mjs.map +1 -0
  113. package/dist/mysql2.d.mts +1 -1
  114. package/dist/mysql2.mjs +1 -1
  115. package/dist/mysql2.mjs.map +1 -1
  116. package/dist/{native-types-BbKWN3JV.mjs → native-types-6wCGP1a1.mjs} +1 -1
  117. package/dist/{native-types-BbKWN3JV.mjs.map → native-types-6wCGP1a1.mjs.map} +1 -1
  118. package/dist/neon-http.d.mts +1 -1
  119. package/dist/neon-http.mjs +1 -1
  120. package/dist/neon-http.mjs.map +1 -1
  121. package/dist/normalized-result-23DWxZVY.mjs +2 -0
  122. package/dist/{normalized-result-VunNi4ID.mjs.map → normalized-result-23DWxZVY.mjs.map} +1 -1
  123. package/dist/{object-store-BHyP-LEI.d.mts → object-store-Cs3AueG5.d.mts} +4 -4
  124. package/dist/{object-store-I1MyfM72.mjs → object-store-DmnlQy7V.mjs} +2 -2
  125. package/dist/{object-store-I1MyfM72.mjs.map → object-store-DmnlQy7V.mjs.map} +1 -1
  126. package/dist/on.d.mts +80 -0
  127. package/dist/on.mjs +2 -0
  128. package/dist/on.mjs.map +1 -0
  129. package/dist/permissions.d.mts +1 -1
  130. package/dist/permissions.mjs +1 -1
  131. package/dist/pg.d.mts +1 -1
  132. package/dist/pg.mjs +1 -1
  133. package/dist/pg.mjs.map +1 -1
  134. package/dist/pglite.d.mts +1 -1
  135. package/dist/pglite.mjs +1 -1
  136. package/dist/{physical-CAZ_LauY.mjs → physical-DT6C54w7.mjs} +2 -2
  137. package/dist/{physical-CAZ_LauY.mjs.map → physical-DT6C54w7.mjs.map} +1 -1
  138. package/dist/pinned-session-BdON2d0V.mjs +2 -0
  139. package/dist/{pinned-session-D8bM5obl.mjs.map → pinned-session-BdON2d0V.mjs.map} +1 -1
  140. package/dist/planetscale.d.mts +1 -1
  141. package/dist/planetscale.mjs +1 -1
  142. package/dist/planetscale.mjs.map +1 -1
  143. package/dist/{planner-BDLdDieE.d.mts → planner-BxCcoO8s.d.mts} +22 -1
  144. package/dist/{postgres-HaFcFACt.mjs → postgres-BK_aOx_C.mjs} +44 -37
  145. package/dist/postgres-BK_aOx_C.mjs.map +1 -0
  146. package/dist/postgres-adapter-CVazEDVI.mjs +2 -0
  147. package/dist/postgres-adapter-CVazEDVI.mjs.map +1 -0
  148. package/dist/postgres-adapter-DxhZu7Qw.mjs +2 -0
  149. package/dist/{postgres-adapter-CnZjhvG1.mjs.map → postgres-adapter-DxhZu7Qw.mjs.map} +1 -1
  150. package/dist/postgres-result-DYeVeHuT.mjs +2 -0
  151. package/dist/{postgres-result-D4_yZqO8.mjs.map → postgres-result-DYeVeHuT.mjs.map} +1 -1
  152. package/dist/postgres.d.mts +1 -1
  153. package/dist/postgres.mjs +1 -1
  154. package/dist/postgres.mjs.map +1 -1
  155. package/dist/{provider-limits-CpitUqW6.mjs → provider-limits-zLe7S_0W.mjs} +2 -2
  156. package/dist/{provider-limits-CpitUqW6.mjs.map → provider-limits-zLe7S_0W.mjs.map} +1 -1
  157. package/dist/{validation-DN1N2OdK.mjs → query-CTna5P9o.mjs} +2 -2
  158. package/dist/query-CTna5P9o.mjs.map +1 -0
  159. package/dist/{relation-bound-5ChGF3n5.mjs → relation-bound-Bj7X-EUE.mjs} +1 -1
  160. package/dist/{relation-bound-5ChGF3n5.mjs.map → relation-bound-Bj7X-EUE.mjs.map} +1 -1
  161. package/dist/{result-parsing-BX3_3Q15.mjs → result-parsing-C2044903.mjs} +1 -1
  162. package/dist/{result-parsing-BX3_3Q15.mjs.map → result-parsing-C2044903.mjs.map} +1 -1
  163. package/dist/result-shape-C8QFUuIt.mjs +2 -0
  164. package/dist/{result-shape-BuGfArOr.mjs.map → result-shape-C8QFUuIt.mjs.map} +1 -1
  165. package/dist/rows-D7ns2l0U.mjs +2 -0
  166. package/dist/{rows-BlONp14o.mjs.map → rows-D7ns2l0U.mjs.map} +1 -1
  167. package/dist/{scalar-B3WLZzJj.mjs → scalar-D6QmJ22_.mjs} +2 -2
  168. package/dist/{scalar-B3WLZzJj.mjs.map → scalar-D6QmJ22_.mjs.map} +1 -1
  169. package/dist/schema/json.d.mts +1 -1
  170. package/dist/schema/json.mjs +1 -1
  171. package/dist/{schema-B_Bc7TQ2.mjs → schema-CY9kOwJ-.mjs} +2 -2
  172. package/dist/{schema-B_Bc7TQ2.mjs.map → schema-CY9kOwJ-.mjs.map} +1 -1
  173. package/dist/{schema-introspection-BqN7d_sA.mjs → schema-introspection-CfqmM3Cz.mjs} +2 -2
  174. package/dist/{schema-introspection-BqN7d_sA.mjs.map → schema-introspection-CfqmM3Cz.mjs.map} +1 -1
  175. package/dist/schema.d.mts +1 -1
  176. package/dist/schema.mjs +1 -1
  177. package/dist/{select-assembly-BP8c4O-0.mjs → select-assembly-D7FEenz2.mjs} +2 -2
  178. package/dist/select-assembly-D7FEenz2.mjs.map +1 -0
  179. package/dist/{settle-B9Vg1FnP.mjs → settle-CObilv26.mjs} +2 -2
  180. package/dist/{settle-B9Vg1FnP.mjs.map → settle-CObilv26.mjs.map} +1 -1
  181. package/dist/{sha256-DDEbgnTU.mjs → sha256-Da07rzvR.mjs} +1 -1
  182. package/dist/{sha256-DDEbgnTU.mjs.map → sha256-Da07rzvR.mjs.map} +1 -1
  183. package/dist/soft-delete.d.mts +1 -1
  184. package/dist/{sql-BR8ZzKn8.mjs → sql-DGtEeP8z.mjs} +1 -1
  185. package/dist/{sql-BR8ZzKn8.mjs.map → sql-DGtEeP8z.mjs.map} +1 -1
  186. package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-DL3ooNs7.mjs} +1 -1
  187. package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-DL3ooNs7.mjs.map} +1 -1
  188. package/dist/sql.d.mts +1 -1
  189. package/dist/sql.mjs +1 -1
  190. package/dist/sqlite-adapter-DqT6HeDs.mjs +2 -0
  191. package/dist/sqlite-adapter-DqT6HeDs.mjs.map +1 -0
  192. package/dist/{sqlite-utils-CFInz2yY.mjs → sqlite-utils-DeDlMJKj.mjs} +2 -2
  193. package/dist/{sqlite-utils-CFInz2yY.mjs.map → sqlite-utils-DeDlMJKj.mjs.map} +1 -1
  194. package/dist/sqlite3.d.mts +1 -1
  195. package/dist/sqlite3.mjs +1 -1
  196. package/dist/sqlite3.mjs.map +1 -1
  197. package/dist/{standard-sql-wRMNi-Yg.mjs → standard-sql-BErrm6AV.mjs} +2 -2
  198. package/dist/{standard-sql-wRMNi-Yg.mjs.map → standard-sql-BErrm6AV.mjs.map} +1 -1
  199. package/dist/{suppressed-failure-Bdo2aK81.mjs → suppressed-failure-3C4sFXvH.mjs} +1 -1
  200. package/dist/{suppressed-failure-Bdo2aK81.mjs.map → suppressed-failure-3C4sFXvH.mjs.map} +1 -1
  201. package/dist/{to-many-CUBK3CTd.mjs → to-many-DqYv9-vp.mjs} +2 -2
  202. package/dist/{to-many-CUBK3CTd.mjs.map → to-many-DqYv9-vp.mjs.map} +1 -1
  203. package/dist/{transaction-operation-C3Jbblbl.mjs → transaction-operation-Co3hw8yz.mjs} +1 -1
  204. package/dist/{transaction-operation-C3Jbblbl.mjs.map → transaction-operation-Co3hw8yz.mjs.map} +1 -1
  205. package/dist/{types-BNR3u6hH.mjs → types-CJgtjXtu.mjs} +1 -1
  206. package/dist/{types-BNR3u6hH.mjs.map → types-CJgtjXtu.mjs.map} +1 -1
  207. package/dist/{utils-Be91XL14.mjs → utils-DooFtO1V.mjs} +3 -3
  208. package/dist/utils-DooFtO1V.mjs.map +1 -0
  209. package/dist/{v-lthABIXD.mjs → v-yKivkoka.mjs} +2 -2
  210. package/dist/{v-lthABIXD.mjs.map → v-yKivkoka.mjs.map} +1 -1
  211. package/dist/validation-pfpKPPZ_.mjs +2 -0
  212. package/dist/validation-pfpKPPZ_.mjs.map +1 -0
  213. package/dist/{validation-BfJaNYMf.mjs → validation-u-sZDdfD.mjs} +2 -2
  214. package/dist/{validation-BfJaNYMf.mjs.map → validation-u-sZDdfD.mjs.map} +1 -1
  215. package/dist/validation.d.mts +1 -1
  216. package/dist/validation.mjs +1 -1
  217. package/dist/{validator-BJhI364k.mjs → validator-XVm02V0K.mjs} +2 -2
  218. package/dist/{validator-BJhI364k.mjs.map → validator-XVm02V0K.mjs.map} +1 -1
  219. package/dist/version-WvqPqZJ4.mjs +2 -0
  220. package/dist/{version-DAFcmokN.mjs.map → version-WvqPqZJ4.mjs.map} +1 -1
  221. package/dist/write-sinks-CoB5PPw9.mjs +2 -0
  222. package/dist/write-sinks-CoB5PPw9.mjs.map +1 -0
  223. package/dist/writes-CD0mNS5-.mjs +2 -0
  224. package/dist/writes-CD0mNS5-.mjs.map +1 -0
  225. package/package.json +36 -15
  226. package/dist/bind-parameter-capacity-faPOSaLz.mjs +0 -2
  227. package/dist/chain-C1VPkUpC.mjs +0 -2
  228. package/dist/client-C1MxqFtt.mjs.map +0 -1
  229. package/dist/client-DHf2ZfRe.mjs +0 -2
  230. package/dist/client-DHf2ZfRe.mjs.map +0 -1
  231. package/dist/driver-aqfbJdZC.mjs +0 -2
  232. package/dist/error-mapping-Zett_Pnt.mjs +0 -2
  233. package/dist/error-mapping-Zett_Pnt.mjs.map +0 -1
  234. package/dist/every-BUf842ai.mjs +0 -2
  235. package/dist/geo-point-codec-DcUTvoEg.mjs +0 -2
  236. package/dist/mysql-adapter-BrkDrfin.mjs +0 -2
  237. package/dist/mysql-adapter-BrkDrfin.mjs.map +0 -1
  238. package/dist/normalized-result-VunNi4ID.mjs +0 -2
  239. package/dist/pinned-session-D8bM5obl.mjs +0 -2
  240. package/dist/postgres-HaFcFACt.mjs.map +0 -1
  241. package/dist/postgres-adapter-BhNE_3b-.mjs +0 -2
  242. package/dist/postgres-adapter-BhNE_3b-.mjs.map +0 -1
  243. package/dist/postgres-adapter-CnZjhvG1.mjs +0 -2
  244. package/dist/postgres-result-D4_yZqO8.mjs +0 -2
  245. package/dist/result-shape-BuGfArOr.mjs +0 -2
  246. package/dist/rows-BlONp14o.mjs +0 -2
  247. package/dist/select-assembly-BP8c4O-0.mjs.map +0 -1
  248. package/dist/sqlite-adapter-CF-m7LIP.mjs +0 -2
  249. package/dist/sqlite-adapter-CF-m7LIP.mjs.map +0 -1
  250. package/dist/utils-Be91XL14.mjs.map +0 -1
  251. package/dist/validation-DN1N2OdK.mjs.map +0 -1
  252. package/dist/version-DAFcmokN.mjs +0 -2
  253. /package/dist/{contract-Dw0FR78e.d.mts → contract-H_WiAUaR.d.mts} +0 -0
  254. /package/dist/{sql-Q_twK-wW.d.mts → sql-CF5Xi6z-.d.mts} +0 -0
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{Pt as t}from"./geo-point-codec-DcUTvoEg.mjs";import{S as n,T as r}from"./scalar-B3WLZzJj.mjs";function hydrateSchemaNames(e,t=!1){let i=Object.entries(e);if(t){for(let[e,t]of i)bindModelNames(e,t);return}let a=r(i);if(a)throw new n([a]);for(let[e,t]of i)preflightModelIdentifiers(e,t);for(let[e,t]of i)bindModelNames(e,t)}function preflightModelIdentifiers(e,t){let n=t[`~`].state;assertValidIdentifier(`Model`,e),n.tableName!==void 0&&assertValidIdentifier(`Mapped table`,n.tableName,e);for(let t of Object.keys(n.shape))assertValidIdentifier(`Field`,t,e);for(let t of Object.values(n.scalars))t[`~`].state.columnName!==void 0&&assertValidIdentifier(`Mapped column`,t[`~`].state.columnName,e)}function bindModelNames(e,t){let n=t[`~`].names,r=t[`~`].state,i=t[`~`].nameRegistry;n.ts=e,n.sql=r.tableName??e;for(let[e,t]of Object.entries(r.scalars)){let n={ts:e,sql:t[`~`].state.columnName??e};i.fields.set(e,n)}}function assertValidIdentifier(e,n,r){if(t(n))return;let i=r?` in '${r}'`:``,a=String(n);throw Error(`${e} '${a}'${i} is invalid identifier; identifiers must be ASCII, at most 63 bytes, and must not collide with Object.prototype properties`)}export{hydrateSchemaNames as t};
2
- //# sourceMappingURL=hydration-BK6vRndL.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{Pt as t}from"./geo-point-codec-mjROsQX-.mjs";import{S as n,T as r}from"./scalar-D6QmJ22_.mjs";function hydrateSchemaNames(e,t=!1){let i=Object.entries(e);if(t){for(let[e,t]of i)bindModelNames(e,t);return}let a=r(i);if(a)throw new n([a]);for(let[e,t]of i)preflightModelIdentifiers(e,t);for(let[e,t]of i)bindModelNames(e,t)}function preflightModelIdentifiers(e,t){let n=t[`~`].state;assertValidIdentifier(`Model`,e),n.tableName!==void 0&&assertValidIdentifier(`Mapped table`,n.tableName,e);for(let t of Object.keys(n.shape))assertValidIdentifier(`Field`,t,e);for(let t of Object.values(n.scalars))t[`~`].state.columnName!==void 0&&assertValidIdentifier(`Mapped column`,t[`~`].state.columnName,e)}function bindModelNames(e,t){let n=t[`~`].names,r=t[`~`].state,i=t[`~`].nameRegistry;n.ts=e,n.sql=r.tableName??e;for(let[e,t]of Object.entries(r.scalars)){let n={ts:e,sql:t[`~`].state.columnName??e};i.fields.set(e,n)}}function assertValidIdentifier(e,n,r){if(t(n))return;let i=r?` in '${r}'`:``,a=String(n);throw Error(`${e} '${a}'${i} is invalid identifier; identifiers must be ASCII, at most 63 bytes, and must not collide with Object.prototype properties`)}export{hydrateSchemaNames as t};
2
+ //# sourceMappingURL=hydration-BQ7tYLtA.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"hydration-BK6vRndL.mjs","names":[],"sources":["../src/schema/hydration.ts"],"sourcesContent":["/**\n * Schema Hydration\n *\n * Hydrates schema name slots (tsName, sqlName) for models and scalars.\n * This is called once at client initialization when the full schema context is available.\n *\n * - tsName: The TypeScript key name in the schema (e.g., \"email\", \"User\")\n * - sqlName: The resolved database name (e.g., \"email_column\", \"users\")\n *\n * Names are stored in the model's nameRegistry, not on the scalar instances.\n * This allows the same scalar to be reused across multiple models with different keys.\n */\n\nimport { isValidSchemaIdentifier } from \"./identifier\";\nimport type { Model, NameRegistry } from \"./model\";\nimport { preflightModelRegistrationIdentity } from \"./registration-preflight\";\nimport type { Scalar } from \"./scalars/base\";\nimport type { SchemaNames } from \"./scalars/common\";\nimport { SchemaValidationError } from \"./validation/error\";\n\n/**\n * Schema type - record of model names to Model instances\n */\nexport type Schema = Record<string, Model<any>>;\n\n/**\n * Hydrate name slots for all models and scalars in a schema.\n *\n * This function populates the model's nameRegistry:\n * - model[\"~\"].names.ts = schema key (e.g., \"User\")\n * - model[\"~\"].names.sql = tableName ?? schema key (e.g., \"users\")\n * - model[\"~\"].nameRegistry.fields.get(fieldKey) = {ts, sql}\n *\n * Operation schemas are registry-owned; hydration only binds reusable schema\n * definitions to model-local names and relation sources.\n *\n * @param schema - The schema object mapping model names to Model instances\n */\nexport function hydrateSchemaNames(schema: Schema, checked = false): void {\n const registrations = Object.entries(schema);\n // A schema `viborm check` validated binds its names without re-proving them.\n if (checked) {\n for (const [modelKey, model] of registrations)\n bindModelNames(modelKey, model);\n return;\n }\n // TWO ordered phases. The preflight proves every model's identity and name\n // stability BEFORE a single registry write, so a schema that fails validation\n // never leaves models 0..N-1 bound while model N is refused.\n const identityIssue = preflightModelRegistrationIdentity(registrations);\n if (identityIssue) throw new SchemaValidationError([identityIssue]);\n for (const [modelKey, model] of registrations) {\n preflightModelIdentifiers(modelKey, model);\n }\n for (const [modelKey, model] of registrations) {\n bindModelNames(modelKey, model);\n }\n}\n\n/**\n * Prove one model's identity: its identifiers are legal, and its schema key is\n * the one this model object is already bound to.\n *\n * A model object binds ONE schema key for its lifetime. Re-registering the same\n * object under the same key is idempotent — the same schema composed twice, or\n * a second client over the same models, is a normal thing to do — while a second\n * key is refused, because every derived name, junction table, index and\n * constraint in the estate is generated from the schema key and two keys would\n * make one model object mean two different tables.\n */\nfunction preflightModelIdentifiers(modelKey: string, model: Model<any>): void {\n const state = model[\"~\"].state;\n\n assertValidIdentifier(\"Model\", modelKey);\n if (state.tableName !== undefined) {\n assertValidIdentifier(\"Mapped table\", state.tableName, modelKey);\n }\n for (const fieldKey of Object.keys(state.shape)) {\n assertValidIdentifier(\"Field\", fieldKey, modelKey);\n }\n for (const scalar of Object.values(state.scalars as Record<string, Scalar>)) {\n if (scalar[\"~\"].state.columnName !== undefined) {\n assertValidIdentifier(\n \"Mapped column\",\n scalar[\"~\"].state.columnName,\n modelKey\n );\n }\n }\n}\n\n/**\n * Bind one model's names and its scalar name registry.\n *\n * A relation has no name entry — its key is its only name, with no column to\n * map — and no relation is given a source model: `.extends()` may reuse one\n * relation object under more than one model or key, so a contextual operation\n * carries its own slot identity instead.\n */\nfunction bindModelNames(modelKey: string, model: Model<any>): void {\n const names = model[\"~\"].names as SchemaNames;\n const state = model[\"~\"].state;\n const registry = model[\"~\"].nameRegistry as NameRegistry;\n\n names.ts = modelKey;\n names.sql = state.tableName ?? modelKey;\n\n for (const [fieldKey, scalar] of Object.entries(\n state.scalars as Record<string, Scalar>\n )) {\n const fieldNames: SchemaNames = {\n ts: fieldKey,\n sql: scalar[\"~\"].state.columnName ?? fieldKey,\n };\n registry.fields.set(fieldKey, fieldNames);\n }\n\n // Operation schemas are built by SchemaRegistry, not during name hydration.\n}\n\nfunction assertValidIdentifier(\n kind: \"Field\" | \"Mapped column\" | \"Mapped table\" | \"Model\",\n identifier: unknown,\n modelName?: string\n): void {\n if (isValidSchemaIdentifier(identifier)) return;\n const location = modelName ? ` in '${modelName}'` : \"\";\n const renderedIdentifier = String(identifier);\n throw new Error(\n `${kind} '${renderedIdentifier}'${location} is invalid identifier; identifiers must be ASCII, at most 63 bytes, and must not collide with Object.prototype properties`\n );\n}\n\n/**\n * Check if a schema has been hydrated\n */\nexport function isSchemaHydrated(schema: Schema): boolean {\n const firstModel = Object.values(schema)[0];\n if (!firstModel) {\n return true;\n } // Empty schema is considered hydrated\n return firstModel[\"~\"].names.ts !== undefined;\n}\n\n/**\n * Get the SQL name for a model (throws if not hydrated)\n */\nexport function getModelSqlName(model: Model<any>): string {\n const sqlName = model[\"~\"].names.sql;\n if (!sqlName) {\n throw new Error(\n \"Schema not hydrated. Call hydrateSchemaNames() or create a client first.\"\n );\n }\n return sqlName;\n}\n\n/**\n * Get the SQL name for a scalar field key.\n * Delegates to model[\"~\"].getFieldName().\n */\nexport function getFieldSqlName(model: Model<any>, fieldKey: string): string {\n return model[\"~\"].getFieldName(fieldKey).sql;\n}\n"],"mappings":"8IAsCA,SAAgB,mBAAmB,EAAgB,EAAU,GAAa,CACxE,IAAM,EAAgB,OAAO,QAAQ,EAAO,CAE5C,GAAI,EAAS,CACX,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,eAAe,EAAU,EAAM,CACjC,OAKF,IAAM,EAAgB,EAAmC,EAAc,CACvE,GAAI,EAAe,MAAM,IAAI,EAAsB,CAAC,EAAc,CAAC,CACnE,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,0BAA0B,EAAU,EAAM,CAE5C,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,eAAe,EAAU,EAAM,CAenC,SAAS,0BAA0B,EAAkB,EAAyB,CAC5E,IAAM,EAAQ,EAAM,KAAK,MAEzB,sBAAsB,QAAS,EAAS,CACpC,EAAM,YAAc,IAAA,IACtB,sBAAsB,eAAgB,EAAM,UAAW,EAAS,CAElE,IAAK,IAAM,KAAY,OAAO,KAAK,EAAM,MAAM,CAC7C,sBAAsB,QAAS,EAAU,EAAS,CAEpD,IAAK,IAAM,KAAU,OAAO,OAAO,EAAM,QAAkC,CACrE,EAAO,KAAK,MAAM,aAAe,IAAA,IACnC,sBACE,gBACA,EAAO,KAAK,MAAM,WAClB,EACD,CAaP,SAAS,eAAe,EAAkB,EAAyB,CACjE,IAAM,EAAQ,EAAM,KAAK,MACnB,EAAQ,EAAM,KAAK,MACnB,EAAW,EAAM,KAAK,aAE5B,EAAM,GAAK,EACX,EAAM,IAAM,EAAM,WAAa,EAE/B,IAAK,GAAM,CAAC,EAAU,KAAW,OAAO,QACtC,EAAM,QACP,CAAE,CACD,IAAM,EAA0B,CAC9B,GAAI,EACJ,IAAK,EAAO,KAAK,MAAM,YAAc,EACtC,CACD,EAAS,OAAO,IAAI,EAAU,EAAW,EAM7C,SAAS,sBACP,EACA,EACA,EACM,CACN,GAAI,EAAwB,EAAW,CAAE,OACzC,IAAM,EAAW,EAAY,QAAQ,EAAU,GAAK,GAC9C,EAAqB,OAAO,EAAW,CAC7C,MAAU,MACR,GAAG,EAAK,IAAI,EAAmB,GAAG,EAAS,4HAC5C"}
1
+ {"version":3,"file":"hydration-BQ7tYLtA.mjs","names":[],"sources":["../src/schema/hydration.ts"],"sourcesContent":["/**\n * Schema Hydration\n *\n * Hydrates schema name slots (tsName, sqlName) for models and scalars.\n * This is called once at client initialization when the full schema context is available.\n *\n * - tsName: The TypeScript key name in the schema (e.g., \"email\", \"User\")\n * - sqlName: The resolved database name (e.g., \"email_column\", \"users\")\n *\n * Names are stored in the model's nameRegistry, not on the scalar instances.\n * This allows the same scalar to be reused across multiple models with different keys.\n */\n\nimport { isValidSchemaIdentifier } from \"./identifier\";\nimport type { Model, NameRegistry } from \"./model\";\nimport { preflightModelRegistrationIdentity } from \"./registration-preflight\";\nimport type { Scalar } from \"./scalars/base\";\nimport type { SchemaNames } from \"./scalars/common\";\nimport { SchemaValidationError } from \"./validation/error\";\n\n/**\n * Schema type - record of model names to Model instances\n */\nexport type Schema = Record<string, Model<any>>;\n\n/**\n * Hydrate name slots for all models and scalars in a schema.\n *\n * This function populates the model's nameRegistry:\n * - model[\"~\"].names.ts = schema key (e.g., \"User\")\n * - model[\"~\"].names.sql = tableName ?? schema key (e.g., \"users\")\n * - model[\"~\"].nameRegistry.fields.get(fieldKey) = {ts, sql}\n *\n * Operation schemas are registry-owned; hydration only binds reusable schema\n * definitions to model-local names and relation sources.\n *\n * @param schema - The schema object mapping model names to Model instances\n */\nexport function hydrateSchemaNames(schema: Schema, checked = false): void {\n const registrations = Object.entries(schema);\n // A schema `viborm check` validated binds its names without re-proving them.\n if (checked) {\n for (const [modelKey, model] of registrations)\n bindModelNames(modelKey, model);\n return;\n }\n // TWO ordered phases. The preflight proves every model's identity and name\n // stability BEFORE a single registry write, so a schema that fails validation\n // never leaves models 0..N-1 bound while model N is refused.\n const identityIssue = preflightModelRegistrationIdentity(registrations);\n if (identityIssue) throw new SchemaValidationError([identityIssue]);\n for (const [modelKey, model] of registrations) {\n preflightModelIdentifiers(modelKey, model);\n }\n for (const [modelKey, model] of registrations) {\n bindModelNames(modelKey, model);\n }\n}\n\n/**\n * Prove one model's identity: its identifiers are legal, and its schema key is\n * the one this model object is already bound to.\n *\n * A model object binds ONE schema key for its lifetime. Re-registering the same\n * object under the same key is idempotent — the same schema composed twice, or\n * a second client over the same models, is a normal thing to do — while a second\n * key is refused, because every derived name, junction table, index and\n * constraint in the estate is generated from the schema key and two keys would\n * make one model object mean two different tables.\n */\nfunction preflightModelIdentifiers(modelKey: string, model: Model<any>): void {\n const state = model[\"~\"].state;\n\n assertValidIdentifier(\"Model\", modelKey);\n if (state.tableName !== undefined) {\n assertValidIdentifier(\"Mapped table\", state.tableName, modelKey);\n }\n for (const fieldKey of Object.keys(state.shape)) {\n assertValidIdentifier(\"Field\", fieldKey, modelKey);\n }\n for (const scalar of Object.values(state.scalars as Record<string, Scalar>)) {\n if (scalar[\"~\"].state.columnName !== undefined) {\n assertValidIdentifier(\n \"Mapped column\",\n scalar[\"~\"].state.columnName,\n modelKey\n );\n }\n }\n}\n\n/**\n * Bind one model's names and its scalar name registry.\n *\n * A relation has no name entry — its key is its only name, with no column to\n * map — and no relation is given a source model: `.extends()` may reuse one\n * relation object under more than one model or key, so a contextual operation\n * carries its own slot identity instead.\n */\nfunction bindModelNames(modelKey: string, model: Model<any>): void {\n const names = model[\"~\"].names as SchemaNames;\n const state = model[\"~\"].state;\n const registry = model[\"~\"].nameRegistry as NameRegistry;\n\n names.ts = modelKey;\n names.sql = state.tableName ?? modelKey;\n\n for (const [fieldKey, scalar] of Object.entries(\n state.scalars as Record<string, Scalar>\n )) {\n const fieldNames: SchemaNames = {\n ts: fieldKey,\n sql: scalar[\"~\"].state.columnName ?? fieldKey,\n };\n registry.fields.set(fieldKey, fieldNames);\n }\n\n // Operation schemas are built by SchemaRegistry, not during name hydration.\n}\n\nfunction assertValidIdentifier(\n kind: \"Field\" | \"Mapped column\" | \"Mapped table\" | \"Model\",\n identifier: unknown,\n modelName?: string\n): void {\n if (isValidSchemaIdentifier(identifier)) return;\n const location = modelName ? ` in '${modelName}'` : \"\";\n const renderedIdentifier = String(identifier);\n throw new Error(\n `${kind} '${renderedIdentifier}'${location} is invalid identifier; identifiers must be ASCII, at most 63 bytes, and must not collide with Object.prototype properties`\n );\n}\n\n/**\n * Check if a schema has been hydrated\n */\nexport function isSchemaHydrated(schema: Schema): boolean {\n const firstModel = Object.values(schema)[0];\n if (!firstModel) {\n return true;\n } // Empty schema is considered hydrated\n return firstModel[\"~\"].names.ts !== undefined;\n}\n\n/**\n * Get the SQL name for a model (throws if not hydrated)\n */\nexport function getModelSqlName(model: Model<any>): string {\n const sqlName = model[\"~\"].names.sql;\n if (!sqlName) {\n throw new Error(\n \"Schema not hydrated. Call hydrateSchemaNames() or create a client first.\"\n );\n }\n return sqlName;\n}\n\n/**\n * Get the SQL name for a scalar field key.\n * Delegates to model[\"~\"].getFieldName().\n */\nexport function getFieldSqlName(model: Model<any>, fieldKey: string): string {\n return model[\"~\"].getFieldName(fieldKey).sql;\n}\n"],"mappings":"8IAsCA,SAAgB,mBAAmB,EAAgB,EAAU,GAAa,CACxE,IAAM,EAAgB,OAAO,QAAQ,EAAO,CAE5C,GAAI,EAAS,CACX,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,eAAe,EAAU,EAAM,CACjC,OAKF,IAAM,EAAgB,EAAmC,EAAc,CACvE,GAAI,EAAe,MAAM,IAAI,EAAsB,CAAC,EAAc,CAAC,CACnE,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,0BAA0B,EAAU,EAAM,CAE5C,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,eAAe,EAAU,EAAM,CAenC,SAAS,0BAA0B,EAAkB,EAAyB,CAC5E,IAAM,EAAQ,EAAM,KAAK,MAEzB,sBAAsB,QAAS,EAAS,CACpC,EAAM,YAAc,IAAA,IACtB,sBAAsB,eAAgB,EAAM,UAAW,EAAS,CAElE,IAAK,IAAM,KAAY,OAAO,KAAK,EAAM,MAAM,CAC7C,sBAAsB,QAAS,EAAU,EAAS,CAEpD,IAAK,IAAM,KAAU,OAAO,OAAO,EAAM,QAAkC,CACrE,EAAO,KAAK,MAAM,aAAe,IAAA,IACnC,sBACE,gBACA,EAAO,KAAK,MAAM,WAClB,EACD,CAaP,SAAS,eAAe,EAAkB,EAAyB,CACjE,IAAM,EAAQ,EAAM,KAAK,MACnB,EAAQ,EAAM,KAAK,MACnB,EAAW,EAAM,KAAK,aAE5B,EAAM,GAAK,EACX,EAAM,IAAM,EAAM,WAAa,EAE/B,IAAK,GAAM,CAAC,EAAU,KAAW,OAAO,QACtC,EAAM,QACP,CAAE,CACD,IAAM,EAA0B,CAC9B,GAAI,EACJ,IAAK,EAAO,KAAK,MAAM,YAAc,EACtC,CACD,EAAS,OAAO,IAAI,EAAU,EAAW,EAM7C,SAAS,sBACP,EACA,EACA,EACM,CACN,GAAI,EAAwB,EAAW,CAAE,OACzC,IAAM,EAAW,EAAY,QAAQ,EAAU,GAAK,GAC9C,EAAqB,OAAO,EAAW,CAC7C,MAAU,MACR,GAAG,EAAK,IAAI,EAAmB,GAAG,EAAS,4HAC5C"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{ct as r,dt as i}from"./geo-point-codec-DcUTvoEg.mjs";import{o as a}from"./sql-BR8ZzKn8.mjs";import{f as o,p as s}from"./scalar-B3WLZzJj.mjs";import{t as c}from"./hydration-BK6vRndL.mjs";import{l,m as u,n as d,u as f}from"./validator-BJhI364k.mjs";import{N as p}from"./standard-sql-wRMNi-Yg.mjs";function mapReferentialAction(e){switch(e.toUpperCase()){case`CASCADE`:return`cascade`;case`SET NULL`:return`setNull`;case`RESTRICT`:return`restrict`;case`SET DEFAULT`:return`setDefault`;default:return`noAction`}}function groupBy(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}function groupByNested(e,t,n){let r=new Map;for(let i of e){let e=t(i),a=n(i),o=r.get(e);o||(o=new Map,r.set(e,o));let s=o.get(a);s?s.push(i):o.set(a,[i])}return r}const m=`[0-9a-fA-F]`,h=`[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]`,g=`[0-9A-Za-z]`,_={uuid:{length:36,regex:`^${m}{8}-${m}{4}-${m}{4}-${m}{4}-${m}{12}$`,glob:`${m.repeat(8)}-${m.repeat(4)}-${m.repeat(4)}-${m.repeat(4)}-${m.repeat(12)}`,fold:`lower`,max:void 0},ulid:{length:26,regex:`^[0-7]${h}{25}$`,glob:`[0-7]${h.repeat(25)}`,fold:`upper`,max:void 0},ksuid:{length:27,regex:`^${g}{27}$`,glob:g.repeat(27),fold:void 0,max:i}};function patternOf(e){return e.format===`ulid`?_.ulid:e.format===`ksuid`?_.ksuid:_.uuid}const int=e=>a.raw(String(e));function fromSql(e,t,n,r){let i=p(t===`mysql`?"`":`"`),o=t===`postgresql`&&n?`${i(n)}.`:``;return a.raw(`${o+i(s(e))} AS ${r}`)}function columnSql(e,t,n,r){let i=p(n===`mysql`?"`":`"`);return a.raw(`${r}.${i(o(e,t))}`)}function payloadSql(e,t){let n=t.prefix;return n?a`substr(${e}, ${int(n.length+2)})`:e}function bytesSql(e,t){return t===`mysql`?a`CAST(${e} AS BINARY)`:e}function orderedSql(e,t){return t===`postgresql`?a`CAST(${e} AS text) COLLATE "C"`:bytesSql(e,t)}function admitsSql(e,t,n){let r=patternOf(t),i=payloadSql(e,t),o=n===`postgresql`?a`${i} ~ ${r.regex}`:n===`mysql`?a`${i} REGEXP ${r.regex}`:a`${i} GLOB ${r.glob}`,s=a`${a.raw(n===`mysql`?`CHAR_LENGTH`:`length`)}(${i}) = ${int(r.length)} AND ${o}`,c=r.max===void 0?s:a`${s} AND ${orderedSql(i,n)} <= ${r.max}`,l=t.prefix;return l?a`${bytesSql(a`substr(${e}, 1, ${int(l.length+1)})`,n)} = ${`${l}-`} AND ${c}`:c}function foldSql(e,t,n){let r=patternOf(t).fold,i=payloadSql(e,t);return bytesSql(r===void 0?i:a`${a.raw(r)}(${i})`,n)}function foldCollisionCheck(e,t,n,r){return{kind:`trusted-read`,query:a`SELECT COUNT(${t}) = COUNT(DISTINCT ${foldSql(t,n,r)}) AS ok FROM ${e}`,equals:!0}}function isSingleColumnKey(e,t){return u(e).referenceableKeys.some(e=>e.length===1&&e[0]===t)}const noRowWhere=(e,t)=>({kind:`trusted-read`,query:a`SELECT NOT EXISTS (SELECT 1 FROM ${e} WHERE ${t}) AS ok`,equals:!0});function referencingColumns(e,t){let n=[];for(let r of l(t))if(r.kind===`foreignKey`&&(r.endpoints[0]===r.owner?r.endpoints[1]:r.endpoints[0]).source===e.model)for(let t of r.reference.members)t.referencedField===e.field&&n.push({model:r.owner.source,field:t.foreignField});return n}function identifierConversionChecks(e){let{model:i,field:l,dialect:u,namespace:p}=e;c(e.schema);let m=d(e.schema),h=f(i,l,m);if(h===void 0||!r(h.format))throw new n(`'${s(i)}.${o(i,l)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,t.INVALID_INPUT);let g=fromSql(i,u,p,`p`),_=columnSql(i,l,u,`p`),v=[noRowWhere(g,a`${_} IS NOT NULL AND NOT (${admitsSql(_,h,u)})`)],y=patternOf(h).fold!==void 0;y&&v.push(foldCollisionCheck(g,_,h,u));for(let t of referencingColumns(e,m)){let e=fromSql(t.model,u,p,`c`),n=columnSql(t.model,t.field,u,`c`);v.push(noRowWhere(e,a`${n} IS NOT NULL AND NOT (${admitsSql(n,h,u)})`)),y&&isSingleColumnKey(t.model,t.field)&&v.push(foldCollisionCheck(e,n,h,u)),v.push(noRowWhere(e,a`${n} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${g} WHERE ${foldSql(_,h,u)} = ${foldSql(n,h,u)})`))}return v}const v=/^(?:text|citext|varchar\(\d+\)|character varying.*)$/i,literal=e=>`'${e.replaceAll(`'`,`''`)}'`;function postgresTextToUuidGuard(e,t){let n=`${e}.${t}`;return`DO \$viborm\$ DECLARE invalid bigint; BEGIN SELECT count(*) INTO invalid FROM ${e} WHERE ${t} IS NOT NULL AND ${t} !~ ${literal(_.uuid.regex)}; IF invalid > 0 THEN RAISE EXCEPTION ${literal(`VibORM: % row(s) of ${n} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; END IF; END \$viborm\$`}function isPostgresTextToUuid(e,t){return t.toLowerCase()===`uuid`&&v.test(e.trim())}export{groupByNested as a,groupBy as i,isPostgresTextToUuid as n,mapReferentialAction as o,postgresTextToUuidGuard as r,identifierConversionChecks as t};
2
- //# sourceMappingURL=identifier-conversion-8ldidfgu.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{ct as r,dt as i}from"./geo-point-codec-mjROsQX-.mjs";import{o as a}from"./sql-DGtEeP8z.mjs";import{f as o,p as s}from"./scalar-D6QmJ22_.mjs";import{t as c}from"./hydration-BQ7tYLtA.mjs";import{l,m as u,n as d,u as f}from"./validator-XVm02V0K.mjs";import{N as p}from"./standard-sql-BErrm6AV.mjs";function mapReferentialAction(e){switch(e.toUpperCase()){case`CASCADE`:return`cascade`;case`SET NULL`:return`setNull`;case`RESTRICT`:return`restrict`;case`SET DEFAULT`:return`setDefault`;default:return`noAction`}}function groupBy(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}function groupByNested(e,t,n){let r=new Map;for(let i of e){let e=t(i),a=n(i),o=r.get(e);o||(o=new Map,r.set(e,o));let s=o.get(a);s?s.push(i):o.set(a,[i])}return r}const m=`[0-9a-fA-F]`,h=`[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]`,g=`[0-9A-Za-z]`,_={uuid:{length:36,regex:`^${m}{8}-${m}{4}-${m}{4}-${m}{4}-${m}{12}$`,glob:`${m.repeat(8)}-${m.repeat(4)}-${m.repeat(4)}-${m.repeat(4)}-${m.repeat(12)}`,fold:`lower`,max:void 0},ulid:{length:26,regex:`^[0-7]${h}{25}$`,glob:`[0-7]${h.repeat(25)}`,fold:`upper`,max:void 0},ksuid:{length:27,regex:`^${g}{27}$`,glob:g.repeat(27),fold:void 0,max:i}};function patternOf(e){return e.format===`ulid`?_.ulid:e.format===`ksuid`?_.ksuid:_.uuid}const int=e=>a.raw(String(e));function fromSql(e,t,n,r){let i=p(t===`mysql`?"`":`"`),o=t===`postgresql`&&n?`${i(n)}.`:``;return a.raw(`${o+i(s(e))} AS ${r}`)}function columnSql(e,t,n,r){let i=p(n===`mysql`?"`":`"`);return a.raw(`${r}.${i(o(e,t))}`)}function payloadSql(e,t){let n=t.prefix;return n?a`substr(${e}, ${int(n.length+2)})`:e}function bytesSql(e,t){return t===`mysql`?a`CAST(${e} AS BINARY)`:e}function orderedSql(e,t){return t===`postgresql`?a`CAST(${e} AS text) COLLATE "C"`:bytesSql(e,t)}function admitsSql(e,t,n){let r=patternOf(t),i=payloadSql(e,t),o=n===`postgresql`?a`${i} ~ ${r.regex}`:n===`mysql`?a`${i} REGEXP ${r.regex}`:a`${i} GLOB ${r.glob}`,s=a`${a.raw(n===`mysql`?`CHAR_LENGTH`:`length`)}(${i}) = ${int(r.length)} AND ${o}`,c=r.max===void 0?s:a`${s} AND ${orderedSql(i,n)} <= ${r.max}`,l=t.prefix;return l?a`${bytesSql(a`substr(${e}, 1, ${int(l.length+1)})`,n)} = ${`${l}-`} AND ${c}`:c}function foldSql(e,t,n){let r=patternOf(t).fold,i=payloadSql(e,t);return bytesSql(r===void 0?i:a`${a.raw(r)}(${i})`,n)}function foldCollisionCheck(e,t,n,r){return{kind:`trusted-read`,query:a`SELECT COUNT(${t}) = COUNT(DISTINCT ${foldSql(t,n,r)}) AS ok FROM ${e}`,equals:!0}}function isSingleColumnKey(e,t){return u(e).referenceableKeys.some(e=>e.length===1&&e[0]===t)}const noRowWhere=(e,t)=>({kind:`trusted-read`,query:a`SELECT NOT EXISTS (SELECT 1 FROM ${e} WHERE ${t}) AS ok`,equals:!0});function referencingColumns(e,t){let n=[];for(let r of l(t))if(r.kind===`foreignKey`&&(r.endpoints[0]===r.owner?r.endpoints[1]:r.endpoints[0]).source===e.model)for(let t of r.reference.members)t.referencedField===e.field&&n.push({model:r.owner.source,field:t.foreignField});return n}function identifierConversionChecks(e){let{model:i,field:l,dialect:u,namespace:p}=e;c(e.schema);let m=d(e.schema),h=f(i,l,m);if(h===void 0||!r(h.format))throw new n(`'${s(i)}.${o(i,l)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,t.INVALID_INPUT);let g=fromSql(i,u,p,`p`),_=columnSql(i,l,u,`p`),v=[noRowWhere(g,a`${_} IS NOT NULL AND NOT (${admitsSql(_,h,u)})`)],y=patternOf(h).fold!==void 0;y&&v.push(foldCollisionCheck(g,_,h,u));for(let t of referencingColumns(e,m)){let e=fromSql(t.model,u,p,`c`),n=columnSql(t.model,t.field,u,`c`);v.push(noRowWhere(e,a`${n} IS NOT NULL AND NOT (${admitsSql(n,h,u)})`)),y&&isSingleColumnKey(t.model,t.field)&&v.push(foldCollisionCheck(e,n,h,u)),v.push(noRowWhere(e,a`${n} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${g} WHERE ${foldSql(_,h,u)} = ${foldSql(n,h,u)})`))}return v}const v=/^(?:text|citext|varchar\(\d+\)|character varying.*)$/i,literal=e=>`'${e.replaceAll(`'`,`''`)}'`;function postgresTextToUuidGuard(e,t){let n=`${e}.${t}`;return`DO \$viborm\$ DECLARE invalid bigint; BEGIN SELECT count(*) INTO invalid FROM ${e} WHERE ${t} IS NOT NULL AND ${t} !~ ${literal(_.uuid.regex)}; IF invalid > 0 THEN RAISE EXCEPTION ${literal(`VibORM: % row(s) of ${n} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; END IF; END \$viborm\$`}function isPostgresTextToUuid(e,t){return t.toLowerCase()===`uuid`&&v.test(e.trim())}export{groupByNested as a,groupBy as i,isPostgresTextToUuid as n,mapReferentialAction as o,postgresTextToUuidGuard as r,identifierConversionChecks as t};
2
+ //# sourceMappingURL=identifier-conversion-DV63mwKG.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"identifier-conversion-8ldidfgu.mjs","names":["sql"],"sources":["../src/migrations/drivers/utils.ts","../src/migrations/identifier-conversion.ts"],"sourcesContent":["/**\n * Migration Driver Utilities\n *\n * Shared helper functions used across multiple migration drivers.\n */\n\nimport type { ReferentialAction } from \"../types\";\n\n/** A catalog's `ON DELETE` / `ON UPDATE` spelling, as a ReferentialAction. */\nexport function mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\n/**\n * Groups items by a key function.\n *\n * @param items - Array of items to group\n * @param keyFn - Function to extract the grouping key\n * @returns Map from key to array of items\n */\nexport function groupBy<T>(\n items: T[],\n keyFn: (item: T) => string\n): Map<string, T[]> {\n const map = new Map<string, T[]>();\n for (const item of items) {\n const key = keyFn(item);\n const existing = map.get(key);\n if (existing) {\n existing.push(item);\n } else {\n map.set(key, [item]);\n }\n }\n return map;\n}\n\n/**\n * Groups items by two levels of keys (nested grouping).\n *\n * @param items - Array of items to group\n * @param primaryKeyFn - Function to extract the primary grouping key\n * @param secondaryKeyFn - Function to extract the secondary grouping key\n * @returns Nested Map structure\n */\nexport function groupByNested<T>(\n items: T[],\n primaryKeyFn: (item: T) => string,\n secondaryKeyFn: (item: T) => string\n): Map<string, Map<string, T[]>> {\n const map = new Map<string, Map<string, T[]>>();\n for (const item of items) {\n const pk = primaryKeyFn(item);\n const sk = secondaryKeyFn(item);\n\n let secondary = map.get(pk);\n if (!secondary) {\n secondary = new Map();\n map.set(pk, secondary);\n }\n\n const existing = secondary.get(sk);\n if (existing) {\n existing.push(item);\n } else {\n secondary.set(sk, [item]);\n }\n }\n return map;\n}\n","/**\n * The three questions an EXISTING text column has to answer before it can\n * become an identifier column — asked as SQL, against the live database, by\n * the person doing the conversion.\n *\n * VibORM does not convert a populated text column on its own: the generated\n * `alterColumn` into a binary column is refused outright\n * ({@link file://./binary-conversion.ts}), and PostgreSQL's one automated leg,\n * `text` → `uuid`, is a per-value cast that either succeeds for the whole table\n * or aborts it. Both routes leave the same work to the author, and this module\n * is the part of that work a machine can state exactly:\n *\n * 1. **Every row is a value of the domain.** Prefix matched whole, payload in\n * the format's own grammar and width — and, for a KSUID, at most the text\n * of the largest value its 20 bytes hold. A row that is not is a row no\n * route can carry.\n * 2. **No two rows fold together.** `uuid` admits uppercase and `ulid`\n * lowercase as ALIASES, so a text column may hold two spellings of one\n * identifier. Compact storage holds the canonical one, so those two rows\n * become one value — violating a unique key, or silently merging two rows\n * where there is none. `ksuid` has no aliases and gets no such check. Asked\n * of the key AND of every referencing column that is a complete key of its\n * own model, because that column carries its own unique constraint through\n * the same fold; a non-unique foreign key holds repeats by design and is\n * never asked.\n * 3. **Every foreign key still finds its parent after the fold.** The FK\n * column converts with its own normalization, so agreement has to be proven\n * against the NORMALIZED sets rather than the stored text.\n *\n * Each check is one row and one boolean column, so each is exactly a\n * {@link MigrationCheckInput} — the `trusted-read` shape `generate()` already\n * accepts as `originChecks` on a manual transition. Run them by hand, or put\n * them in front of your own conversion migration; they are the same SQL either\n * way.\n *\n * Every IDENTITY comparison these checks make is asked of BYTES, because the\n * column they are about answers in bytes. MySQL 8's default collation is\n * `utf8mb4_0900_ai_ci`, where `=` folds case and accents: a bare\n * `p.id = c.userId` there answers TRUE for a KSUID pair that a `BINARY(20)`\n * column will hold as two different values, so an estate certified ready came\n * out of the conversion with a foreign key naming no parent. `CAST(… AS BINARY)`\n * pins it, and it pins across character sets where `COLLATE utf8mb4_bin` raises\n * on a `latin1` column. The grammar match is deliberately NOT cast: MySQL's\n * `REGEXP` refuses a binary operand outright, and every pattern here already\n * spells both cases, so nothing is lost.\n *\n * Pure and connection-free, like every other module in this layer: it renders\n * SQL, it never executes it.\n *\n * What it does NOT cover, deliberately: a junction table's own columns and a\n * polymorphic row carrier's id column. Those hold a key's values too and\n * convert by the same recipe, but they are private storage with no (model,\n * field) to name them by, so the migration guide lists them rather than this\n * module guessing at them.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport {\n type AnyModel,\n getColumnName,\n getModelKeyCatalog,\n getTableName,\n} from \"../schema/model\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n type ResolvedRelationIndex,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\nimport {\n type IdDomain,\n isCompactIdFormat,\n} from \"../validation/primitives/id-codec\";\nimport { KSUID_MAX_TEXT } from \"../validation/primitives/id-formats\";\nimport type { Dialect } from \"./drivers/types\";\nimport type { MigrationCheckInput } from \"./v1-types\";\n\n/** The key whose text column is being converted, and the schema it lives in. */\nexport interface IdentifierConversionRequest {\n /**\n * The WHOLE schema, not just the model: a foreign key's domain is derived\n * from the resolved topology, and so is the list of columns that reference\n * this key. Resolved here, exactly as `serializeModels` resolves it.\n */\n readonly schema: Record<string, AnyModel>;\n readonly model: AnyModel;\n readonly field: string;\n readonly dialect: Dialect;\n /** PostgreSQL's target namespace, when the estate is bound to one. */\n readonly namespace?: string | undefined;\n}\n\n/** One character class, spelled once for both pattern languages. */\nconst HEX = \"[0-9a-fA-F]\";\nconst CROCKFORD = \"[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]\";\nconst BASE62 = \"[0-9A-Za-z]\";\n\n/**\n * The payload grammar of each compact format, as a regex and as a GLOB, and\n * the largest payload text when the grammar alone admits more than the bytes\n * hold.\n *\n * A ULID's grammar carries its own bound — the leading `[0-7]` — but 27 base62\n * characters express more than 2^160 values, and no character class can say\n * where 2^160 falls. So a KSUID is bounded by comparison against the codec's\n * own maximum text, read from `id-formats.ts` rather than spelled here.\n */\nconst PATTERNS = {\n uuid: {\n length: 36,\n regex: `^${HEX}{8}-${HEX}{4}-${HEX}{4}-${HEX}{4}-${HEX}{12}$`,\n glob: `${HEX.repeat(8)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(12)}`,\n fold: \"lower\",\n max: undefined,\n },\n ulid: {\n length: 26,\n regex: `^[0-7]${CROCKFORD}{25}$`,\n glob: `[0-7]${CROCKFORD.repeat(25)}`,\n fold: \"upper\",\n max: undefined,\n },\n ksuid: {\n length: 27,\n regex: `^${BASE62}{27}$`,\n glob: BASE62.repeat(27),\n fold: undefined,\n max: KSUID_MAX_TEXT,\n },\n} as const;\n\n/** `uuidv7` shares a uuid's grammar: the version nibble is not a storage fact. */\nfunction patternOf(domain: IdDomain) {\n if (domain.format === \"ulid\") return PATTERNS.ulid;\n if (domain.format === \"ksuid\") return PATTERNS.ksuid;\n return PATTERNS.uuid;\n}\n\n/** A literal integer: a width, never caller text, so it is text and not a bind. */\nconst int = (value: number): Sql => sql.raw(String(value));\n\n/** One quoted, optionally qualified table name, bound to a one-letter alias. */\nfunction fromSql(\n model: AnyModel,\n dialect: Dialect,\n namespace: string | undefined,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n const qualifier =\n dialect === \"postgresql\" && namespace ? `${quote(namespace)}.` : \"\";\n return sql.raw(`${qualifier + quote(getTableName(model))} AS ${alias}`);\n}\n\n/**\n * One column, always written through its table's alias.\n *\n * The FK checks correlate two tables, and a one-to-one child whose primary key\n * IS its foreign key names both columns `id` — an unqualified reference there\n * binds to the inner table and compares a value with itself.\n */\nfunction columnSql(\n model: AnyModel,\n field: string,\n dialect: Dialect,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n return sql.raw(`${alias}.${quote(getColumnName(model, field))}`);\n}\n\n/** The payload of a stored value: the whole column, or what follows the prefix. */\nfunction payloadSql(column: Sql, domain: IdDomain): Sql {\n const prefix = domain.prefix;\n if (!prefix) return column;\n return sql`substr(${column}, ${int(prefix.length + 2)})`;\n}\n\n/**\n * One comparison operand, asked as the bytes the compact column will hold.\n *\n * Only MySQL needs it, and only because its default collation answers a\n * different question than the column will: see the module note above. Not\n * applied to `REGEXP`, which refuses a binary operand.\n */\nfunction bytesSql(expression: Sql, dialect: Dialect): Sql {\n return dialect === \"mysql\" ? sql`CAST(${expression} AS BINARY)` : expression;\n}\n\n/**\n * One ORDERING operand, compared byte by byte on every dialect.\n *\n * Fixed-width base62 text sorts as its number only under byte order: every\n * database default here that is not bytes folds case, and there `a` sorts\n * before `V`. MySQL takes the byte pin `bytesSql` already applies; PostgreSQL\n * takes `COLLATE \"C\"`, after a cast to `text` because `citext` — a text-family\n * type a KSUID column may hold — lowercases before any collation is consulted;\n * SQLite's default collation is already `BINARY`, as every identity\n * comparison in this module already relies on.\n */\nfunction orderedSql(expression: Sql, dialect: Dialect): Sql {\n if (dialect === \"postgresql\") {\n return sql`CAST(${expression} AS text) COLLATE \"C\"`;\n }\n return bytesSql(expression, dialect);\n}\n\n/** Whether one stored value is a value of the domain. */\nfunction admitsSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const pattern = patternOf(domain);\n const payload = payloadSql(column, domain);\n const matches =\n dialect === \"postgresql\"\n ? sql`${payload} ~ ${pattern.regex}`\n : dialect === \"mysql\"\n ? sql`${payload} REGEXP ${pattern.regex}`\n : sql`${payload} GLOB ${pattern.glob}`;\n const width = sql.raw(dialect === \"mysql\" ? \"CHAR_LENGTH\" : \"length\");\n const grammar = sql`${width}(${payload}) = ${int(pattern.length)} AND ${matches}`;\n const sized =\n pattern.max === undefined\n ? grammar\n : sql`${grammar} AND ${orderedSql(payload, dialect)} <= ${pattern.max}`;\n const prefix = domain.prefix;\n if (!prefix) return sized;\n const spelled = bytesSql(\n sql`substr(${column}, 1, ${int(prefix.length + 1)})`,\n dialect\n );\n return sql`${spelled} = ${`${prefix}-`} AND ${sized}`;\n}\n\n/**\n * The canonical spelling of one stored value, as the bytes it will become:\n * the alias fold for a format that has one, then the dialect's byte pin.\n */\nfunction foldSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const fold = patternOf(domain).fold;\n const payload = payloadSql(column, domain);\n return bytesSql(\n fold === undefined ? payload : sql`${sql.raw(fold)}(${payload})`,\n dialect\n );\n}\n\n/**\n * `COUNT(col) = COUNT(DISTINCT fold(col))`: the question a UNIQUE column has to\n * answer before its aliases collapse into one another.\n */\nfunction foldCollisionCheck(\n from: Sql,\n column: Sql,\n domain: IdDomain,\n dialect: Dialect\n): MigrationCheckInput {\n return {\n kind: \"trusted-read\",\n query: sql`SELECT COUNT(${column}) = COUNT(DISTINCT ${foldSql(column, domain, dialect)}) AS ok FROM ${from}`,\n equals: true,\n };\n}\n\n/**\n * Whether this column is, BY ITSELF, a complete key of its own model.\n *\n * The fold question belongs to every column that carries a uniqueness\n * constraint through it, and a referencing column often does: the one-to-one\n * child whose primary key IS its foreign key is the ordinary shape, and a\n * `.unique()` foreign key is the other. Asking it of a plain many-side foreign\n * key would refuse every healthy estate on earth — repeats there are the\n * relation — so the catalog decides, not the fact of being a reference.\n *\n * `referenceableKeys` is the right catalog rather than the addressable one: a\n * total unique INDEX no selector can name still refuses a duplicate.\n */\nfunction isSingleColumnKey(model: AnyModel, field: string): boolean {\n return getModelKeyCatalog(model).referenceableKeys.some(\n (key) => key.length === 1 && key[0] === field\n );\n}\n\n/** `SELECT NOT EXISTS (…)`, the shape every row check takes. */\nconst noRowWhere = (from: Sql, predicate: Sql): MigrationCheckInput => ({\n kind: \"trusted-read\",\n query: sql`SELECT NOT EXISTS (SELECT 1 FROM ${from} WHERE ${predicate}) AS ok`,\n equals: true,\n});\n\n/** Every foreign-key column that holds this key's values. */\nfunction referencingColumns(\n request: IdentifierConversionRequest,\n index: ResolvedRelationIndex\n): { model: AnyModel; field: string }[] {\n const columns: { model: AnyModel; field: string }[] = [];\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"foreignKey\") continue;\n const other =\n edge.endpoints[0] === edge.owner ? edge.endpoints[1] : edge.endpoints[0];\n if (other.source !== request.model) continue;\n for (const member of edge.reference.members) {\n if (member.referencedField !== request.field) continue;\n columns.push({ model: edge.owner.source, field: member.foreignField });\n }\n }\n return columns;\n}\n\n/**\n * The pre-checks for converting one key's text column into its identifier\n * column, in the order a conversion needs them.\n *\n * Refuses a field with no compactly stored identifier domain rather than\n * answering with an empty list: an empty list reads as \"this estate is ready\",\n * and that is the one answer a caller who named the wrong field must not get.\n */\nexport function identifierConversionChecks(\n request: IdentifierConversionRequest\n): readonly MigrationCheckInput[] {\n const { model, field, dialect, namespace } = request;\n hydrateSchemaNames(request.schema);\n const index = resolveSchemaOrThrow(request.schema);\n const domain = idDomainOf(model, field, index);\n if (domain === undefined || !isCompactIdFormat(domain.format)) {\n throw new MigrationError(\n `'${getTableName(model)}.${getColumnName(model, field)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n const parent = fromSql(model, dialect, namespace, \"p\");\n const key = columnSql(model, field, dialect, \"p\");\n const checks: MigrationCheckInput[] = [\n noRowWhere(\n parent,\n sql`${key} IS NOT NULL AND NOT (${admitsSql(key, domain, dialect)})`\n ),\n ];\n const folds = patternOf(domain).fold !== undefined;\n if (folds) {\n checks.push(foldCollisionCheck(parent, key, domain, dialect));\n }\n for (const reference of referencingColumns(request, index)) {\n const child = fromSql(reference.model, dialect, namespace, \"c\");\n const fk = columnSql(reference.model, reference.field, dialect, \"c\");\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT (${admitsSql(fk, domain, dialect)})`\n )\n );\n if (folds && isSingleColumnKey(reference.model, reference.field)) {\n checks.push(foldCollisionCheck(child, fk, domain, dialect));\n }\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${parent} WHERE ${foldSql(key, domain, dialect)} = ${foldSql(fk, domain, dialect)})`\n )\n );\n }\n return checks;\n}\n\n// =============================================================================\n// THE ONE AUTOMATED LEG\n// =============================================================================\n\n/** The text column spellings PostgreSQL can hold an identifier in. */\nconst PG_TEXT_COLUMN = /^(?:text|citext|varchar\\(\\d+\\)|character varying.*)$/i;\n\n/** A SQL string literal: the only escape a quoted name needs inside one. */\nconst literal = (text: string): string => `'${text.replaceAll(\"'\", \"''\")}'`;\n\n/**\n * The message PostgreSQL's own `col::uuid` does not give.\n *\n * `ALTER COLUMN … TYPE uuid USING col::uuid` converts value by value: it\n * succeeds for an estate of canonical uuids and raises\n * `invalid input syntax for type uuid: \"…\"` on the first row that is not one,\n * aborting the transaction and leaving the column as it was. The outcome is\n * right; the message names one offending row and nothing about the choice the\n * author actually has. This runs FIRST, inside the same transaction, and says\n * how many rows are in the way and what the two routes are.\n *\n * A PREFIXED domain fails here too, and deliberately: `usr-a0ee…` is not uuid\n * text, and no `USING substring(col from 5)::uuid` is emitted for it, because\n * the snapshot carries the column TYPE and not the domain — the prefix is a\n * fact of the declaration that no migration artifact has ever held. Converting\n * a prefixed column is a manual route, and this says so before anything runs.\n *\n * It is not a second refusal: without it the conversion fails anyway. Its whole\n * and only coverage is the message.\n */\nexport function postgresTextToUuidGuard(\n qualifiedTable: string,\n quotedColumn: string\n): string {\n const marker = `${qualifiedTable}.${quotedColumn}`;\n return (\n \"DO $viborm$ DECLARE invalid bigint; BEGIN \" +\n `SELECT count(*) INTO invalid FROM ${qualifiedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} !~ ${literal(PATTERNS.uuid.regex)}; ` +\n \"IF invalid > 0 THEN RAISE EXCEPTION \" +\n `${literal(`VibORM: % row(s) of ${marker} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; ` +\n \"END IF; END $viborm$\"\n );\n}\n\n/** Whether this alteration is the one text→identifier conversion pg performs. */\nexport function isPostgresTextToUuid(\n fromType: string,\n toType: string\n): boolean {\n return (\n toType.toLowerCase() === \"uuid\" && PG_TEXT_COLUMN.test(fromType.trim())\n );\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"identifier-conversion-DV63mwKG.mjs","names":["sql"],"sources":["../src/migrations/drivers/utils.ts","../src/migrations/identifier-conversion.ts"],"sourcesContent":["/**\n * Migration Driver Utilities\n *\n * Shared helper functions used across multiple migration drivers.\n */\n\nimport type { ReferentialAction } from \"../types\";\n\n/** A catalog's `ON DELETE` / `ON UPDATE` spelling, as a ReferentialAction. */\nexport function mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\n/**\n * Groups items by a key function.\n *\n * @param items - Array of items to group\n * @param keyFn - Function to extract the grouping key\n * @returns Map from key to array of items\n */\nexport function groupBy<T>(\n items: T[],\n keyFn: (item: T) => string\n): Map<string, T[]> {\n const map = new Map<string, T[]>();\n for (const item of items) {\n const key = keyFn(item);\n const existing = map.get(key);\n if (existing) {\n existing.push(item);\n } else {\n map.set(key, [item]);\n }\n }\n return map;\n}\n\n/**\n * Groups items by two levels of keys (nested grouping).\n *\n * @param items - Array of items to group\n * @param primaryKeyFn - Function to extract the primary grouping key\n * @param secondaryKeyFn - Function to extract the secondary grouping key\n * @returns Nested Map structure\n */\nexport function groupByNested<T>(\n items: T[],\n primaryKeyFn: (item: T) => string,\n secondaryKeyFn: (item: T) => string\n): Map<string, Map<string, T[]>> {\n const map = new Map<string, Map<string, T[]>>();\n for (const item of items) {\n const pk = primaryKeyFn(item);\n const sk = secondaryKeyFn(item);\n\n let secondary = map.get(pk);\n if (!secondary) {\n secondary = new Map();\n map.set(pk, secondary);\n }\n\n const existing = secondary.get(sk);\n if (existing) {\n existing.push(item);\n } else {\n secondary.set(sk, [item]);\n }\n }\n return map;\n}\n","/**\n * The three questions an EXISTING text column has to answer before it can\n * become an identifier column — asked as SQL, against the live database, by\n * the person doing the conversion.\n *\n * VibORM does not convert a populated text column on its own: the generated\n * `alterColumn` into a binary column is refused outright\n * ({@link file://./binary-conversion.ts}), and PostgreSQL's one automated leg,\n * `text` → `uuid`, is a per-value cast that either succeeds for the whole table\n * or aborts it. Both routes leave the same work to the author, and this module\n * is the part of that work a machine can state exactly:\n *\n * 1. **Every row is a value of the domain.** Prefix matched whole, payload in\n * the format's own grammar and width — and, for a KSUID, at most the text\n * of the largest value its 20 bytes hold. A row that is not is a row no\n * route can carry.\n * 2. **No two rows fold together.** `uuid` admits uppercase and `ulid`\n * lowercase as ALIASES, so a text column may hold two spellings of one\n * identifier. Compact storage holds the canonical one, so those two rows\n * become one value — violating a unique key, or silently merging two rows\n * where there is none. `ksuid` has no aliases and gets no such check. Asked\n * of the key AND of every referencing column that is a complete key of its\n * own model, because that column carries its own unique constraint through\n * the same fold; a non-unique foreign key holds repeats by design and is\n * never asked.\n * 3. **Every foreign key still finds its parent after the fold.** The FK\n * column converts with its own normalization, so agreement has to be proven\n * against the NORMALIZED sets rather than the stored text.\n *\n * Each check is one row and one boolean column, so each is exactly a\n * {@link MigrationCheckInput} — the `trusted-read` shape `generate()` already\n * accepts as `originChecks` on a manual transition. Run them by hand, or put\n * them in front of your own conversion migration; they are the same SQL either\n * way.\n *\n * Every IDENTITY comparison these checks make is asked of BYTES, because the\n * column they are about answers in bytes. MySQL 8's default collation is\n * `utf8mb4_0900_ai_ci`, where `=` folds case and accents: a bare\n * `p.id = c.userId` there answers TRUE for a KSUID pair that a `BINARY(20)`\n * column will hold as two different values, so an estate certified ready came\n * out of the conversion with a foreign key naming no parent. `CAST(… AS BINARY)`\n * pins it, and it pins across character sets where `COLLATE utf8mb4_bin` raises\n * on a `latin1` column. The grammar match is deliberately NOT cast: MySQL's\n * `REGEXP` refuses a binary operand outright, and every pattern here already\n * spells both cases, so nothing is lost.\n *\n * Pure and connection-free, like every other module in this layer: it renders\n * SQL, it never executes it.\n *\n * What it does NOT cover, deliberately: a junction table's own columns and a\n * polymorphic row carrier's id column. Those hold a key's values too and\n * convert by the same recipe, but they are private storage with no (model,\n * field) to name them by, so the migration guide lists them rather than this\n * module guessing at them.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport {\n type AnyModel,\n getColumnName,\n getModelKeyCatalog,\n getTableName,\n} from \"../schema/model\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n type ResolvedRelationIndex,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\nimport {\n type IdDomain,\n isCompactIdFormat,\n} from \"../validation/primitives/id-codec\";\nimport { KSUID_MAX_TEXT } from \"../validation/primitives/id-formats\";\nimport type { Dialect } from \"./drivers/types\";\nimport type { MigrationCheckInput } from \"./v1-types\";\n\n/** The key whose text column is being converted, and the schema it lives in. */\nexport interface IdentifierConversionRequest {\n /**\n * The WHOLE schema, not just the model: a foreign key's domain is derived\n * from the resolved topology, and so is the list of columns that reference\n * this key. Resolved here, exactly as `serializeModels` resolves it.\n */\n readonly schema: Record<string, AnyModel>;\n readonly model: AnyModel;\n readonly field: string;\n readonly dialect: Dialect;\n /** PostgreSQL's target namespace, when the estate is bound to one. */\n readonly namespace?: string | undefined;\n}\n\n/** One character class, spelled once for both pattern languages. */\nconst HEX = \"[0-9a-fA-F]\";\nconst CROCKFORD = \"[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]\";\nconst BASE62 = \"[0-9A-Za-z]\";\n\n/**\n * The payload grammar of each compact format, as a regex and as a GLOB, and\n * the largest payload text when the grammar alone admits more than the bytes\n * hold.\n *\n * A ULID's grammar carries its own bound — the leading `[0-7]` — but 27 base62\n * characters express more than 2^160 values, and no character class can say\n * where 2^160 falls. So a KSUID is bounded by comparison against the codec's\n * own maximum text, read from `id-formats.ts` rather than spelled here.\n */\nconst PATTERNS = {\n uuid: {\n length: 36,\n regex: `^${HEX}{8}-${HEX}{4}-${HEX}{4}-${HEX}{4}-${HEX}{12}$`,\n glob: `${HEX.repeat(8)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(12)}`,\n fold: \"lower\",\n max: undefined,\n },\n ulid: {\n length: 26,\n regex: `^[0-7]${CROCKFORD}{25}$`,\n glob: `[0-7]${CROCKFORD.repeat(25)}`,\n fold: \"upper\",\n max: undefined,\n },\n ksuid: {\n length: 27,\n regex: `^${BASE62}{27}$`,\n glob: BASE62.repeat(27),\n fold: undefined,\n max: KSUID_MAX_TEXT,\n },\n} as const;\n\n/** `uuidv7` shares a uuid's grammar: the version nibble is not a storage fact. */\nfunction patternOf(domain: IdDomain) {\n if (domain.format === \"ulid\") return PATTERNS.ulid;\n if (domain.format === \"ksuid\") return PATTERNS.ksuid;\n return PATTERNS.uuid;\n}\n\n/** A literal integer: a width, never caller text, so it is text and not a bind. */\nconst int = (value: number): Sql => sql.raw(String(value));\n\n/** One quoted, optionally qualified table name, bound to a one-letter alias. */\nfunction fromSql(\n model: AnyModel,\n dialect: Dialect,\n namespace: string | undefined,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n const qualifier =\n dialect === \"postgresql\" && namespace ? `${quote(namespace)}.` : \"\";\n return sql.raw(`${qualifier + quote(getTableName(model))} AS ${alias}`);\n}\n\n/**\n * One column, always written through its table's alias.\n *\n * The FK checks correlate two tables, and a one-to-one child whose primary key\n * IS its foreign key names both columns `id` — an unqualified reference there\n * binds to the inner table and compares a value with itself.\n */\nfunction columnSql(\n model: AnyModel,\n field: string,\n dialect: Dialect,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n return sql.raw(`${alias}.${quote(getColumnName(model, field))}`);\n}\n\n/** The payload of a stored value: the whole column, or what follows the prefix. */\nfunction payloadSql(column: Sql, domain: IdDomain): Sql {\n const prefix = domain.prefix;\n if (!prefix) return column;\n return sql`substr(${column}, ${int(prefix.length + 2)})`;\n}\n\n/**\n * One comparison operand, asked as the bytes the compact column will hold.\n *\n * Only MySQL needs it, and only because its default collation answers a\n * different question than the column will: see the module note above. Not\n * applied to `REGEXP`, which refuses a binary operand.\n */\nfunction bytesSql(expression: Sql, dialect: Dialect): Sql {\n return dialect === \"mysql\" ? sql`CAST(${expression} AS BINARY)` : expression;\n}\n\n/**\n * One ORDERING operand, compared byte by byte on every dialect.\n *\n * Fixed-width base62 text sorts as its number only under byte order: every\n * database default here that is not bytes folds case, and there `a` sorts\n * before `V`. MySQL takes the byte pin `bytesSql` already applies; PostgreSQL\n * takes `COLLATE \"C\"`, after a cast to `text` because `citext` — a text-family\n * type a KSUID column may hold — lowercases before any collation is consulted;\n * SQLite's default collation is already `BINARY`, as every identity\n * comparison in this module already relies on.\n */\nfunction orderedSql(expression: Sql, dialect: Dialect): Sql {\n if (dialect === \"postgresql\") {\n return sql`CAST(${expression} AS text) COLLATE \"C\"`;\n }\n return bytesSql(expression, dialect);\n}\n\n/** Whether one stored value is a value of the domain. */\nfunction admitsSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const pattern = patternOf(domain);\n const payload = payloadSql(column, domain);\n const matches =\n dialect === \"postgresql\"\n ? sql`${payload} ~ ${pattern.regex}`\n : dialect === \"mysql\"\n ? sql`${payload} REGEXP ${pattern.regex}`\n : sql`${payload} GLOB ${pattern.glob}`;\n const width = sql.raw(dialect === \"mysql\" ? \"CHAR_LENGTH\" : \"length\");\n const grammar = sql`${width}(${payload}) = ${int(pattern.length)} AND ${matches}`;\n const sized =\n pattern.max === undefined\n ? grammar\n : sql`${grammar} AND ${orderedSql(payload, dialect)} <= ${pattern.max}`;\n const prefix = domain.prefix;\n if (!prefix) return sized;\n const spelled = bytesSql(\n sql`substr(${column}, 1, ${int(prefix.length + 1)})`,\n dialect\n );\n return sql`${spelled} = ${`${prefix}-`} AND ${sized}`;\n}\n\n/**\n * The canonical spelling of one stored value, as the bytes it will become:\n * the alias fold for a format that has one, then the dialect's byte pin.\n */\nfunction foldSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const fold = patternOf(domain).fold;\n const payload = payloadSql(column, domain);\n return bytesSql(\n fold === undefined ? payload : sql`${sql.raw(fold)}(${payload})`,\n dialect\n );\n}\n\n/**\n * `COUNT(col) = COUNT(DISTINCT fold(col))`: the question a UNIQUE column has to\n * answer before its aliases collapse into one another.\n */\nfunction foldCollisionCheck(\n from: Sql,\n column: Sql,\n domain: IdDomain,\n dialect: Dialect\n): MigrationCheckInput {\n return {\n kind: \"trusted-read\",\n query: sql`SELECT COUNT(${column}) = COUNT(DISTINCT ${foldSql(column, domain, dialect)}) AS ok FROM ${from}`,\n equals: true,\n };\n}\n\n/**\n * Whether this column is, BY ITSELF, a complete key of its own model.\n *\n * The fold question belongs to every column that carries a uniqueness\n * constraint through it, and a referencing column often does: the one-to-one\n * child whose primary key IS its foreign key is the ordinary shape, and a\n * `.unique()` foreign key is the other. Asking it of a plain many-side foreign\n * key would refuse every healthy estate on earth — repeats there are the\n * relation — so the catalog decides, not the fact of being a reference.\n *\n * `referenceableKeys` is the right catalog rather than the addressable one: a\n * total unique INDEX no selector can name still refuses a duplicate.\n */\nfunction isSingleColumnKey(model: AnyModel, field: string): boolean {\n return getModelKeyCatalog(model).referenceableKeys.some(\n (key) => key.length === 1 && key[0] === field\n );\n}\n\n/** `SELECT NOT EXISTS (…)`, the shape every row check takes. */\nconst noRowWhere = (from: Sql, predicate: Sql): MigrationCheckInput => ({\n kind: \"trusted-read\",\n query: sql`SELECT NOT EXISTS (SELECT 1 FROM ${from} WHERE ${predicate}) AS ok`,\n equals: true,\n});\n\n/** Every foreign-key column that holds this key's values. */\nfunction referencingColumns(\n request: IdentifierConversionRequest,\n index: ResolvedRelationIndex\n): { model: AnyModel; field: string }[] {\n const columns: { model: AnyModel; field: string }[] = [];\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"foreignKey\") continue;\n const other =\n edge.endpoints[0] === edge.owner ? edge.endpoints[1] : edge.endpoints[0];\n if (other.source !== request.model) continue;\n for (const member of edge.reference.members) {\n if (member.referencedField !== request.field) continue;\n columns.push({ model: edge.owner.source, field: member.foreignField });\n }\n }\n return columns;\n}\n\n/**\n * The pre-checks for converting one key's text column into its identifier\n * column, in the order a conversion needs them.\n *\n * Refuses a field with no compactly stored identifier domain rather than\n * answering with an empty list: an empty list reads as \"this estate is ready\",\n * and that is the one answer a caller who named the wrong field must not get.\n */\nexport function identifierConversionChecks(\n request: IdentifierConversionRequest\n): readonly MigrationCheckInput[] {\n const { model, field, dialect, namespace } = request;\n hydrateSchemaNames(request.schema);\n const index = resolveSchemaOrThrow(request.schema);\n const domain = idDomainOf(model, field, index);\n if (domain === undefined || !isCompactIdFormat(domain.format)) {\n throw new MigrationError(\n `'${getTableName(model)}.${getColumnName(model, field)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n const parent = fromSql(model, dialect, namespace, \"p\");\n const key = columnSql(model, field, dialect, \"p\");\n const checks: MigrationCheckInput[] = [\n noRowWhere(\n parent,\n sql`${key} IS NOT NULL AND NOT (${admitsSql(key, domain, dialect)})`\n ),\n ];\n const folds = patternOf(domain).fold !== undefined;\n if (folds) {\n checks.push(foldCollisionCheck(parent, key, domain, dialect));\n }\n for (const reference of referencingColumns(request, index)) {\n const child = fromSql(reference.model, dialect, namespace, \"c\");\n const fk = columnSql(reference.model, reference.field, dialect, \"c\");\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT (${admitsSql(fk, domain, dialect)})`\n )\n );\n if (folds && isSingleColumnKey(reference.model, reference.field)) {\n checks.push(foldCollisionCheck(child, fk, domain, dialect));\n }\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${parent} WHERE ${foldSql(key, domain, dialect)} = ${foldSql(fk, domain, dialect)})`\n )\n );\n }\n return checks;\n}\n\n// =============================================================================\n// THE ONE AUTOMATED LEG\n// =============================================================================\n\n/** The text column spellings PostgreSQL can hold an identifier in. */\nconst PG_TEXT_COLUMN = /^(?:text|citext|varchar\\(\\d+\\)|character varying.*)$/i;\n\n/** A SQL string literal: the only escape a quoted name needs inside one. */\nconst literal = (text: string): string => `'${text.replaceAll(\"'\", \"''\")}'`;\n\n/**\n * The message PostgreSQL's own `col::uuid` does not give.\n *\n * `ALTER COLUMN … TYPE uuid USING col::uuid` converts value by value: it\n * succeeds for an estate of canonical uuids and raises\n * `invalid input syntax for type uuid: \"…\"` on the first row that is not one,\n * aborting the transaction and leaving the column as it was. The outcome is\n * right; the message names one offending row and nothing about the choice the\n * author actually has. This runs FIRST, inside the same transaction, and says\n * how many rows are in the way and what the two routes are.\n *\n * A PREFIXED domain fails here too, and deliberately: `usr-a0ee…` is not uuid\n * text, and no `USING substring(col from 5)::uuid` is emitted for it, because\n * the snapshot carries the column TYPE and not the domain — the prefix is a\n * fact of the declaration that no migration artifact has ever held. Converting\n * a prefixed column is a manual route, and this says so before anything runs.\n *\n * It is not a second refusal: without it the conversion fails anyway. Its whole\n * and only coverage is the message.\n */\nexport function postgresTextToUuidGuard(\n qualifiedTable: string,\n quotedColumn: string\n): string {\n const marker = `${qualifiedTable}.${quotedColumn}`;\n return (\n \"DO $viborm$ DECLARE invalid bigint; BEGIN \" +\n `SELECT count(*) INTO invalid FROM ${qualifiedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} !~ ${literal(PATTERNS.uuid.regex)}; ` +\n \"IF invalid > 0 THEN RAISE EXCEPTION \" +\n `${literal(`VibORM: % row(s) of ${marker} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; ` +\n \"END IF; END $viborm$\"\n );\n}\n\n/** Whether this alteration is the one text→identifier conversion pg performs. */\nexport function isPostgresTextToUuid(\n fromType: string,\n toType: string\n): boolean {\n return (\n toType.toLowerCase() === \"uuid\" && PG_TEXT_COLUMN.test(fromType.trim())\n );\n}\n"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{t as r}from"./sha256-DDEbgnTU.mjs";const i=`sha256`,a={estate:`viborm.migration.estate.v1`,snapshot:`viborm.migration.snapshot.v1`,snapshotDelta:`viborm.migration.snapshot-delta.v1`,sql:`viborm.migration.sql.v1`,dispatch:`viborm.migration.dispatch.v1`,transition:`viborm.migration.transition.v1`,state:`viborm.migration.state.v1`,path:`viborm.migration.path.v1`,plan:`viborm.migration.plan.v1`,resetPlan:`viborm.migration.reset-plan.v1`,event:`viborm.migration.event.v1`},o=/^[0-9a-f]{64}$/,s=new TextEncoder;function isSha256(e){return typeof e==`string`&&o.test(e)}function parseSha256(e,r){if(!isSha256(e))throw new n(`${r} is not a lowercase 64-hex SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return e}function sha256Hex(e){let t=``;for(let n of r(e))t+=n.toString(16).padStart(2,`0`);return t}function domainHash(e,t){let n=s.encode(e),r=new Uint8Array(n.length+1+t.length);return r.set(n,0),r[n.length]=0,r.set(t,n.length+1),sha256Hex(r)}function utf8Bytes(e){return s.encode(e)}function decodeUtf8(e){return new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(e)}export{isSha256 as a,utf8Bytes as c,domainHash as i,a as n,parseSha256 as o,decodeUtf8 as r,sha256Hex as s,i as t};
2
- //# sourceMappingURL=identity-Bu6jbgym.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{t as r}from"./sha256-Da07rzvR.mjs";const i=`sha256`,a={estate:`viborm.migration.estate.v1`,snapshot:`viborm.migration.snapshot.v1`,snapshotDelta:`viborm.migration.snapshot-delta.v1`,sql:`viborm.migration.sql.v1`,dispatch:`viborm.migration.dispatch.v1`,transition:`viborm.migration.transition.v1`,state:`viborm.migration.state.v1`,path:`viborm.migration.path.v1`,plan:`viborm.migration.plan.v1`,resetPlan:`viborm.migration.reset-plan.v1`,event:`viborm.migration.event.v1`},o=/^[0-9a-f]{64}$/,s=new TextEncoder;function isSha256(e){return typeof e==`string`&&o.test(e)}function parseSha256(e,r){if(!isSha256(e))throw new n(`${r} is not a lowercase 64-hex SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return e}function sha256Hex(e){let t=``;for(let n of r(e))t+=n.toString(16).padStart(2,`0`);return t}function domainHash(e,t){let n=s.encode(e),r=new Uint8Array(n.length+1+t.length);return r.set(n,0),r[n.length]=0,r.set(t,n.length+1),sha256Hex(r)}function utf8Bytes(e){return s.encode(e)}function decodeUtf8(e){return new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(e)}export{isSha256 as a,utf8Bytes as c,domainHash as i,a as n,parseSha256 as o,decodeUtf8 as r,sha256Hex as s,i as t};
2
+ //# sourceMappingURL=identity-B75EaVTM.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"identity-Bu6jbgym.mjs","names":[],"sources":["../src/migrations/identity.ts"],"sourcesContent":["/**\n * Content-addressed identity for Migration V1.\n *\n * One hash owner: SHA-256 over a frozen ASCII domain label, 0x00, then the\n * exact bytes being authenticated. Filenames and stored hex digests are the\n * lowercase 64-hex form of that digest. There is no self-referential checksum\n * header and no second hasher.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { sha256 } from \"../validation/primitives/sha256\";\n\nexport type Sha256 = string;\n\nexport const HASH_ALGORITHM = \"sha256\";\n\nexport const HASH_DOMAIN = {\n estate: \"viborm.migration.estate.v1\",\n snapshot: \"viborm.migration.snapshot.v1\",\n snapshotDelta: \"viborm.migration.snapshot-delta.v1\",\n sql: \"viborm.migration.sql.v1\",\n dispatch: \"viborm.migration.dispatch.v1\",\n transition: \"viborm.migration.transition.v1\",\n state: \"viborm.migration.state.v1\",\n path: \"viborm.migration.path.v1\",\n plan: \"viborm.migration.plan.v1\",\n resetPlan: \"viborm.migration.reset-plan.v1\",\n event: \"viborm.migration.event.v1\",\n} as const;\n\nexport type HashDomain = (typeof HASH_DOMAIN)[keyof typeof HASH_DOMAIN];\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst UTF8 = new TextEncoder();\n\nexport function isSha256(value: unknown): value is Sha256 {\n return typeof value === \"string\" && HEX64.test(value);\n}\n\nexport function parseSha256(value: unknown, label: string): Sha256 {\n if (!isSha256(value)) {\n throw new MigrationError(\n `${label} is not a lowercase 64-hex SHA-256 digest`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return value;\n}\n\nexport function sha256Hex(bytes: Uint8Array): Sha256 {\n let hex = \"\";\n for (const byte of sha256(bytes)) hex += byte.toString(16).padStart(2, \"0\");\n return hex;\n}\n\nexport function domainHash(domain: HashDomain, bytes: Uint8Array): Sha256 {\n const prefix = UTF8.encode(domain);\n const input = new Uint8Array(prefix.length + 1 + bytes.length);\n input.set(prefix, 0);\n input[prefix.length] = 0;\n input.set(bytes, prefix.length + 1);\n return sha256Hex(input);\n}\n\nexport function utf8Bytes(text: string): Uint8Array {\n return UTF8.encode(text);\n}\n\n/**\n * Exactly the characters the bytes encode — a leading U+FEFF among them.\n *\n * These bytes are a VALUE (a catalog default, a blob's text), not a document\n * with a byte-order mark: the decoder's default of swallowing a leading U+FEFF\n * would report a value its source does not hold. A caller that refuses a BOM\n * refuses it as a byte, before this (`validateSqlRanges`).\n */\nexport function decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n bytes\n );\n}\n"],"mappings":"yKAcA,MAAa,EAAiB,SAEjB,EAAc,CACzB,OAAQ,6BACR,SAAU,+BACV,cAAe,qCACf,IAAK,0BACL,SAAU,+BACV,WAAY,iCACZ,MAAO,4BACP,KAAM,2BACN,KAAM,2BACN,UAAW,iCACX,MAAO,4BACR,CAIK,EAAQ,iBACR,EAAO,IAAI,YAEjB,SAAgB,SAAS,EAAiC,CACxD,OAAO,OAAO,GAAU,UAAY,EAAM,KAAK,EAAM,CAGvD,SAAgB,YAAY,EAAgB,EAAuB,CACjE,GAAI,CAAC,SAAS,EAAM,CAClB,MAAM,IAAI,EACR,GAAG,EAAM,2CACT,EAAgB,yBACjB,CAEH,OAAO,EAGT,SAAgB,UAAU,EAA2B,CACnD,IAAI,EAAM,GACV,IAAK,IAAM,KAAQ,EAAO,EAAM,CAAE,GAAO,EAAK,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAC3E,OAAO,EAGT,SAAgB,WAAW,EAAoB,EAA2B,CACxE,IAAM,EAAS,EAAK,OAAO,EAAO,CAC5B,EAAQ,IAAI,WAAW,EAAO,OAAS,EAAI,EAAM,OAAO,CAI9D,OAHA,EAAM,IAAI,EAAQ,EAAE,CACpB,EAAM,EAAO,QAAU,EACvB,EAAM,IAAI,EAAO,EAAO,OAAS,EAAE,CAC5B,UAAU,EAAM,CAGzB,SAAgB,UAAU,EAA0B,CAClD,OAAO,EAAK,OAAO,EAAK,CAW1B,SAAgB,WAAW,EAA2B,CACpD,OAAO,IAAI,YAAY,QAAS,CAAE,MAAO,GAAM,UAAW,GAAM,CAAC,CAAC,OAChE,EACD"}
1
+ {"version":3,"file":"identity-B75EaVTM.mjs","names":[],"sources":["../src/migrations/identity.ts"],"sourcesContent":["/**\n * Content-addressed identity for Migration V1.\n *\n * One hash owner: SHA-256 over a frozen ASCII domain label, 0x00, then the\n * exact bytes being authenticated. Filenames and stored hex digests are the\n * lowercase 64-hex form of that digest. There is no self-referential checksum\n * header and no second hasher.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { sha256 } from \"../validation/primitives/sha256\";\n\nexport type Sha256 = string;\n\nexport const HASH_ALGORITHM = \"sha256\";\n\nexport const HASH_DOMAIN = {\n estate: \"viborm.migration.estate.v1\",\n snapshot: \"viborm.migration.snapshot.v1\",\n snapshotDelta: \"viborm.migration.snapshot-delta.v1\",\n sql: \"viborm.migration.sql.v1\",\n dispatch: \"viborm.migration.dispatch.v1\",\n transition: \"viborm.migration.transition.v1\",\n state: \"viborm.migration.state.v1\",\n path: \"viborm.migration.path.v1\",\n plan: \"viborm.migration.plan.v1\",\n resetPlan: \"viborm.migration.reset-plan.v1\",\n event: \"viborm.migration.event.v1\",\n} as const;\n\nexport type HashDomain = (typeof HASH_DOMAIN)[keyof typeof HASH_DOMAIN];\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst UTF8 = new TextEncoder();\n\nexport function isSha256(value: unknown): value is Sha256 {\n return typeof value === \"string\" && HEX64.test(value);\n}\n\nexport function parseSha256(value: unknown, label: string): Sha256 {\n if (!isSha256(value)) {\n throw new MigrationError(\n `${label} is not a lowercase 64-hex SHA-256 digest`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return value;\n}\n\nexport function sha256Hex(bytes: Uint8Array): Sha256 {\n let hex = \"\";\n for (const byte of sha256(bytes)) hex += byte.toString(16).padStart(2, \"0\");\n return hex;\n}\n\nexport function domainHash(domain: HashDomain, bytes: Uint8Array): Sha256 {\n const prefix = UTF8.encode(domain);\n const input = new Uint8Array(prefix.length + 1 + bytes.length);\n input.set(prefix, 0);\n input[prefix.length] = 0;\n input.set(bytes, prefix.length + 1);\n return sha256Hex(input);\n}\n\nexport function utf8Bytes(text: string): Uint8Array {\n return UTF8.encode(text);\n}\n\n/**\n * Exactly the characters the bytes encode — a leading U+FEFF among them.\n *\n * These bytes are a VALUE (a catalog default, a blob's text), not a document\n * with a byte-order mark: the decoder's default of swallowing a leading U+FEFF\n * would report a value its source does not hold. A caller that refuses a BOM\n * refuses it as a byte, before this (`validateSqlRanges`).\n */\nexport function decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n bytes\n );\n}\n"],"mappings":"yKAcA,MAAa,EAAiB,SAEjB,EAAc,CACzB,OAAQ,6BACR,SAAU,+BACV,cAAe,qCACf,IAAK,0BACL,SAAU,+BACV,WAAY,iCACZ,MAAO,4BACP,KAAM,2BACN,KAAM,2BACN,UAAW,iCACX,MAAO,4BACR,CAIK,EAAQ,iBACR,EAAO,IAAI,YAEjB,SAAgB,SAAS,EAAiC,CACxD,OAAO,OAAO,GAAU,UAAY,EAAM,KAAK,EAAM,CAGvD,SAAgB,YAAY,EAAgB,EAAuB,CACjE,GAAI,CAAC,SAAS,EAAM,CAClB,MAAM,IAAI,EACR,GAAG,EAAM,2CACT,EAAgB,yBACjB,CAEH,OAAO,EAGT,SAAgB,UAAU,EAA2B,CACnD,IAAI,EAAM,GACV,IAAK,IAAM,KAAQ,EAAO,EAAM,CAAE,GAAO,EAAK,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAC3E,OAAO,EAGT,SAAgB,WAAW,EAAoB,EAA2B,CACxE,IAAM,EAAS,EAAK,OAAO,EAAO,CAC5B,EAAQ,IAAI,WAAW,EAAO,OAAS,EAAI,EAAM,OAAO,CAI9D,OAHA,EAAM,IAAI,EAAQ,EAAE,CACpB,EAAM,EAAO,QAAU,EACvB,EAAM,IAAI,EAAO,EAAO,OAAS,EAAE,CAC5B,UAAU,EAAM,CAGzB,SAAgB,UAAU,EAA0B,CAClD,OAAO,EAAK,OAAO,EAAK,CAW1B,SAAgB,WAAW,EAA2B,CACpD,OAAO,IAAI,YAAY,QAAS,CAAE,MAAO,GAAM,UAAW,GAAM,CAAC,CAAC,OAChE,EACD"}
@@ -1,4 +1,4 @@
1
- import { c as sqlTag, n as Sql } from "./sql-Q_twK-wW.mjs";
1
+ import { c as sqlTag, n as Sql } from "./sql-CF5Xi6z-.mjs";
2
2
  import { StandardSchemaV1 } from "@standard-schema/spec";
3
3
 
4
4
  //#region src/schema/scalars/native-types.d.ts
@@ -12689,6 +12689,8 @@ interface GeoPointSql {
12689
12689
  * then composes them into complete queries. The adapter never
12690
12690
  * needs to understand query semantics - just SQL syntax.
12691
12691
  */
12692
+ /** The three substring filters, as `insensitiveText` names them. */
12693
+ type TextMatch = "contains" | "startsWith" | "endsWith";
12692
12694
  interface DatabaseAdapter {
12693
12695
  /**
12694
12696
  * NAMESPACE
@@ -12819,6 +12821,17 @@ interface DatabaseAdapter {
12819
12821
  containsText: (column: Sql, value: Sql) => Sql;
12820
12822
  startsWithText: (column: Sql, value: Sql) => Sql;
12821
12823
  endsWithText: (column: Sql, value: Sql) => Sql;
12824
+ /**
12825
+ * The same three predicates under `mode: "insensitive"`: letter case is
12826
+ * ignored the way THIS database folds it (its own `LOWER`/`ILIKE`), so the
12827
+ * answer for a non-ASCII letter follows the database and its locale.
12828
+ * Accents and every other difference still count.
12829
+ *
12830
+ * Both operands arrive raw: neither folded nor wrapped in
12831
+ * `caseSensitiveText`. A plain string `value` is a bare bound parameter,
12832
+ * which an adapter matching with `LIKE` escapes client-side.
12833
+ */
12834
+ insensitiveText: (kind: TextMatch, column: Sql, value: Sql, nativeType?: NativeTypeDeclaration) => Sql;
12822
12835
  /**
12823
12836
  * `startsWithText` for a plain string operand, spelled so the dialect's
12824
12837
  * planner can turn it into an index range.
@@ -12904,8 +12917,14 @@ interface DatabaseAdapter {
12904
12917
  concat: (...parts: Sql[]) => Sql;
12905
12918
  upper: (expr: Sql) => Sql;
12906
12919
  lower: (expr: Sql) => Sql;
12907
- /** Fold ASCII A-Z to a-z without provider-native Unicode case folding. */
12908
- asciiCaseFold: (expr: Sql) => Sql;
12920
+ /**
12921
+ * Fold letter case the way this database does natively (its own `LOWER`),
12922
+ * for `mode: "insensitive"` equality, membership and ranges. The caller
12923
+ * compares the result under `caseSensitiveText`, so case is the only
12924
+ * difference it ignores. `expr` arrives raw, never wrapped in
12925
+ * `caseSensitiveText`, with the native type of the column it reads.
12926
+ */
12927
+ caseFold: (expr: Sql, nativeType?: NativeTypeDeclaration) => Sql;
12909
12928
  /** Force exact text comparison semantics independent of column/database collation. */
12910
12929
  caseSensitiveText: (expr: Sql, nativeType?: NativeTypeDeclaration, textOperation?: boolean) => Sql;
12911
12930
  /** Cast a deferred value into one fixed-decimal field's exact domain. */
@@ -13077,6 +13096,13 @@ interface DatabaseAdapter {
13077
13096
  * JSON lt/lte/gt/gte with string operands.
13078
13097
  */
13079
13098
  stringAtPath: (column: Sql, path: string[]) => Sql;
13099
+ /**
13100
+ * `stringAtPath` in the database's own text type and collation, for
13101
+ * `mode: "insensitive"`: the byte-ordered pin stops a database folding
13102
+ * case (`LOWER`/`ILIKE` under PG `COLLATE "C"` fold `A`-`Z` only, and
13103
+ * MySQL's `LOWER` leaves a binary string as it is).
13104
+ */
13105
+ foldableStringAtPath: (column: Sql, path: string[]) => Sql;
13080
13106
  /**
13081
13107
  * JSON array containment: target is an array containing every element
13082
13108
  * of the candidate JSON array value (PG @>, MySQL JSON_CONTAINS,
@@ -13329,6 +13355,13 @@ interface DatabaseAdapter {
13329
13355
  delete: (table: Sql, where?: Sql) => Sql;
13330
13356
  /** RETURNING clause (PG/SQLite) or empty (MySQL) */
13331
13357
  returning: (columns: Sql) => Sql;
13358
+ /**
13359
+ * A `RETURNING` expression true where an `INSERT … ON CONFLICT DO UPDATE`
13360
+ * inserted its row rather than updated it (PostgreSQL: `xmax = 0`).
13361
+ * Absent where the statement cannot say: an upsert that must report its
13362
+ * arm then reads the row first.
13363
+ */
13364
+ upserted?: Sql;
13332
13365
  /**
13333
13366
  * ON CONFLICT / ON DUPLICATE KEY
13334
13367
  * @param target - Conflict target columns (e.g., "id")
@@ -13529,6 +13562,7 @@ declare class MySQLAdapter implements DatabaseAdapter {
13529
13562
  containsText: (column: Sql, value: Sql) => Sql;
13530
13563
  startsWithText: (column: Sql, value: Sql) => Sql;
13531
13564
  endsWithText: (column: Sql, value: Sql) => Sql;
13565
+ insensitiveText: (kind: TextMatch, column: Sql, value: Sql) => Sql;
13532
13566
  startsWithPrefix: (column: Sql, value: string) => Sql;
13533
13567
  exactTextEq: (column: Sql, value: Sql) => Sql;
13534
13568
  exactTextIn: (column: Sql, values: Sql) => Sql;
@@ -13540,7 +13574,7 @@ declare class MySQLAdapter implements DatabaseAdapter {
13540
13574
  gte: (left: Sql, right: Sql) => Sql;
13541
13575
  };
13542
13576
  expressions: {
13543
- asciiCaseFold: (expr: Sql) => Sql;
13577
+ caseFold: (expr: Sql) => Sql;
13544
13578
  caseSensitiveText: (expr: Sql) => Sql;
13545
13579
  concat: (...parts: Sql[]) => Sql;
13546
13580
  greatest: (...exprs: Sql[]) => Sql;
@@ -13592,6 +13626,7 @@ declare class MySQLAdapter implements DatabaseAdapter {
13592
13626
  extractText: (column: Sql, path: string[]) => Sql;
13593
13627
  numberAtPath: (column: Sql, path: string[]) => Sql;
13594
13628
  stringAtPath: (column: Sql, path: string[]) => Sql;
13629
+ foldableStringAtPath: (column: Sql, path: string[]) => Sql;
13595
13630
  contains: (target: Sql, value: Sql) => Sql;
13596
13631
  lastElement: (target: Sql) => Sql;
13597
13632
  value: (v: unknown) => Sql;
@@ -13727,7 +13762,6 @@ declare class MySQLAdapter implements DatabaseAdapter {
13727
13762
  }
13728
13763
  //#endregion
13729
13764
  //#region src/adapters/databases/postgres/postgres-adapter.d.ts
13730
- declare function postgresAsciiCaseFold(expr: Sql): Sql;
13731
13765
  declare function postgresJsonObject(pairs: [string, Sql][]): Sql;
13732
13766
  declare class PostgresAdapter implements DatabaseAdapter {
13733
13767
  #private;
@@ -13769,6 +13803,7 @@ declare class PostgresAdapter implements DatabaseAdapter {
13769
13803
  containsText: (column: Sql, value: Sql) => Sql;
13770
13804
  startsWithText: (column: Sql, value: Sql) => Sql;
13771
13805
  endsWithText: (column: Sql, value: Sql) => Sql;
13806
+ insensitiveText: (kind: TextMatch, column: Sql, value: Sql, nativeType?: NativeTypeDeclaration) => Sql;
13772
13807
  startsWithPrefix: (column: Sql, value: string, nativeType?: NativeTypeDeclaration) => Sql;
13773
13808
  exactTextEq: (column: Sql, value: Sql, nativeType?: NativeTypeDeclaration) => Sql;
13774
13809
  exactTextIn: (column: Sql, values: Sql, nativeType?: NativeTypeDeclaration) => Sql;
@@ -13783,7 +13818,7 @@ declare class PostgresAdapter implements DatabaseAdapter {
13783
13818
  };
13784
13819
  expressions: {
13785
13820
  caseSensitiveText: (expr: Sql, nativeType?: NativeTypeDeclaration, textOperation?: boolean) => Sql;
13786
- asciiCaseFold: typeof postgresAsciiCaseFold;
13821
+ caseFold: (expr: Sql, nativeType?: NativeTypeDeclaration) => Sql;
13787
13822
  concat: (...parts: Sql[]) => Sql;
13788
13823
  greatest: (...exprs: Sql[]) => Sql;
13789
13824
  least: (...exprs: Sql[]) => Sql;
@@ -13834,6 +13869,7 @@ declare class PostgresAdapter implements DatabaseAdapter {
13834
13869
  extractText: (column: Sql, path: string[]) => Sql;
13835
13870
  numberAtPath: (column: Sql, path: string[]) => Sql;
13836
13871
  stringAtPath: (column: Sql, path: string[]) => Sql;
13872
+ foldableStringAtPath: (column: Sql, path: string[]) => Sql;
13837
13873
  contains: (target: Sql, value: Sql) => Sql;
13838
13874
  lastElement: (target: Sql) => Sql;
13839
13875
  value: (v: unknown) => Sql;
@@ -13909,6 +13945,7 @@ declare class PostgresAdapter implements DatabaseAdapter {
13909
13945
  onConflict: (target: Sql | null, action: Sql, targetWhere?: Sql) => Sql;
13910
13946
  onConflictUpdate: (sets: Sql, setWhere?: Sql) => Sql;
13911
13947
  returning: (columns: Sql) => Sql;
13948
+ upserted: Sql;
13912
13949
  update: (table: Sql, sets: Sql, where?: Sql) => Sql;
13913
13950
  delete: (table: Sql, where?: Sql) => Sql;
13914
13951
  skipDuplicatesStrategy: "sql";
@@ -14080,6 +14117,7 @@ declare class SQLiteAdapter implements DatabaseAdapter {
14080
14117
  containsText: (column: Sql, value: Sql) => Sql;
14081
14118
  startsWithText: (column: Sql, value: Sql) => Sql;
14082
14119
  endsWithText: (column: Sql, value: Sql) => Sql;
14120
+ insensitiveText(kind: TextMatch, column: Sql, value: Sql): Sql;
14083
14121
  startsWithPrefix: (column: Sql, value: string) => Sql;
14084
14122
  exactTextEq: (column: Sql, value: Sql) => Sql;
14085
14123
  exactTextIn: (column: Sql, values: Sql) => Sql;
@@ -14091,7 +14129,7 @@ declare class SQLiteAdapter implements DatabaseAdapter {
14091
14129
  gte: (left: Sql, right: Sql) => Sql;
14092
14130
  };
14093
14131
  expressions: {
14094
- asciiCaseFold: (expr: Sql) => Sql;
14132
+ caseFold: (expr: Sql) => Sql;
14095
14133
  caseSensitiveText: (expr: Sql) => Sql;
14096
14134
  concat: (...parts: Sql[]) => Sql;
14097
14135
  greatest: (...exprs: Sql[]) => Sql;
@@ -14147,6 +14185,7 @@ declare class SQLiteAdapter implements DatabaseAdapter {
14147
14185
  extractText: (column: Sql, path: string[]) => Sql;
14148
14186
  numberAtPath: (column: Sql, path: string[]) => Sql;
14149
14187
  stringAtPath: (column: Sql, path: string[]) => Sql;
14188
+ foldableStringAtPath(column: Sql, path: string[]): Sql;
14150
14189
  contains: (target: Sql, value: Sql) => Sql;
14151
14190
  lastElement: (target: Sql) => Sql;
14152
14191
  value: (v: unknown) => Sql;
@@ -14273,4 +14312,4 @@ declare const mysqlAdapter: MySQLAdapter;
14273
14312
  declare const postgresAdapter: PostgresAdapter;
14274
14313
  declare const sqliteAdapter: SQLiteAdapter;
14275
14314
  //#endregion
14276
- export { ModelOperationInput as $, AutoGenerate as $n, ValidationErrorSource as $r, ExtensionResultConsumerState as $t, Schema$1 as A, CacheConfigurationError as Ai, BatchQuery as An, BaseBlobSchema as Ar, DriverConfig as At, VariantToOneRelation as B, wrapError as Bi, ModelFieldRefs as Bn, JsonNull as Br, DefinitionControls as Bt, Client as C, UniqueConstraintError as Ci, WaitUntilFn as Cn, IsoDateSchema as Cr, s as Ct, OperationPayloadSchema as D, isNotNullConstraintError as Di, BatchTransactionOptions as Dn, EnumSchema as Dr, renderSchemaType as Dt, OperationPayload as E, isForeignKeyError as Ei, sqliteResultParser as En, BaseEnumSchema as Er, renderOperationResultType as Et, LinkedClientConfig as F, VibORMError as Fi, V$1 as Fn, toJsonSchema as Fr, VibORMClient as Ft, ParseResult as G, GeoPolygon as Gi, IndexOptions as Gn, inferred as Gr, defineExtension as Gt, BigIntScalar as H, GeoArea as Hi, isFieldRef as Hn, JsonNullSentinel as Hr, PlacedControl as Ht, Links$1 as I, VibORMErrorCode as Ii, v as In, createSchemaRegistry as Ir, VibORMConfig as It, SchemaRegistryOperation as J, MYSQL as Ji, Model$1 as Jn, JunctionReferentialAction as Jr, AccumulatedExtensionState as Jt, Prettify as K, DecimalDescriptor as Ki, IndexType as Kn, AnyRelation as Kr, StatementContext as Kt, RelationLinks as L, isRetryableError as Li, StringSchema as Ln, AnyJsonNullSentinel as Lr, createClient as Lt, ClientSchema as M, CacheInvalidTTLError as Mi, Dialect as Mn, BaseBigIntSchema as Mr, ExtendedOperationResult as Mt, FlatSchema as N, CacheOperationNotCacheableError as Ni, QueryExecutionContext as Nn, BigIntSchema as Nr, ExtensionState as Nt, OperationResult as O, isUniqueConstraintError as Oi, DriverTransactionOptions as On, BaseBooleanSchema as Or, validateOperationPayload as Ot, Linked as P, PrismaErrorCode as Pi, QueryResult as Pn, createJsonSchemaConverter as Pr, NoExtraDriverConfigKeys as Pt, ModelCoreSchemas as Q, SQLITE as Qi, DecimalSchema as Qn, ValidationError as Qr, ExtensionContributionState as Qt, ModelShape as R, isVibORMError as Ri, AnyFieldRef as Rn, AnyNull as Rr, defaultOmit as Rt, CachedClient as S, NotNullConstraintError as Si, CacheSetOptions as Sn, BaseIsoTimestampSchema as Sr, ModelToManyRelation as St, MutationOperations as T, isCheckConstraintError as Ti, WithCacheOptions as Tn, IsoTimestampSchema as Tr, getOperationPayloadSchema as Tt, InferInput as U, GeoBounds as Ui, AnyModel as Un, isJsonNullSentinel as Ur, RowsVerbs as Ut, type Scalar as V, DiagnosticDisclosure as Vi, createModelFieldRefs as Vn, JsonNullKind as Vr, NoControls as Vt, InferOutput as W, GeoPoint as Wi, IndexDefinition as Wn, JsonSchema$1 as Wr, ClientExtension as Wt, ModelArgsSchemas as X, NativeTypeMap as Xi, ModelState as Xn, RelationCardinality as Xr, EmptyClientExtensionState as Xt, VibSchema as Y, NativeType as Yi, ModelInternal as Yn, ReferentialAction as Yr, ClientExtensionState as Yt, ModelCoreInput as Z, PG as Zi, UpdateState as Zn, RelationSlot as Zr, ExtensionCacheState as Zt, ObservationCompletion as _, isUnsupportedOperationError as _i, UnwrapPendingOperation as _n, InputJsonValue as _r, DateScalar as _t, PostgresAdapter as a, FeatureNotSupportedError as ai, InferSelectInclude as an, UpdateState$1 as ar, CoreSchemas as at, OFFICIAL_INSTRUMENTATION_NAME as b, CheckConstraintError as bi, CacheDriver as bn, BaseIsoDateSchema as br, ModelToOneRelation as bt, Operation as c, NestedWriteError as ci, validateSchemaOrThrow as cn, VectorSchema as cr, StringScalar as ct, MigrationSessionAttestation as d, QueryEngineError as di, SchemaValidationIssue as dn, ObjectSchema as dr, JsonScalar as dt, isValidationError as ei, MergeExtensionState as en, AutoGenerateType as er, ModelRelationNestedInput as et, SQLITE_MIGRATION_CAPABILITY as f, QueryError as fi, Severity as fn, BaseIntegerSchema as fr, IntScalar as ft, MigrationNamespaceAttestation as g, isPendingOperationError as gi, PendingOperation as gn, BaseJsonSchema as gr, DateTimeScalar as gt, DriverResultParser as h, isNotFoundError as hi, Schema$3 as hn, NumberSchema as hr, TimeScalar as ht, SQLiteAdapter as i, ConnectionError as ii, GroupByResultType as in, ScalarType as ir, ArgsSchemas as it, ValidatedOperationPayload as j, CacheInvalidKeyError as ji, CommittedBatchNotification as jn, BlobSchema as jr, ExtendedClient as jt, Operations as k, isValueTooLongError as ki, TransactionOptionSupport as kn, BooleanSchema as kr, ClientTypeState as kt, AnyDriver as l, NotFoundError as li, SchemaValidationError as ln, BasePointSchema as lr, PointScalar as lt, PinnedSessionReservation as m, isClientInitializationError as mi, DateTimePhysicalForm as mn, IntegerSchema as mr, DecimalScalar as mt, postgresAdapter as n, TransactionError as ni, BatchPayload as nn, InitialScalarState as nr, ModelStateSchemas as nt, MySQLAdapter as o, ForbiddenError as oi, RawOperation as on, parse as or, NumericScalar as ot, SqliteMigrationCapability as p, UnsupportedOperationError as pi, ValidationResult$1 as pn, BaseNumberSchema as pr, EnumScalar as pt, SchemaRegistryLookup as q, Decimal as qi, InitialModelState as qn, Getter as qr, StatementHandler as qt, sqliteAdapter as r, ClientInitializationError as ri, CountResultType as rn, ScalarState as rr, ScalarSchemas as rt, DatabaseAdapter as s, NestedWriteAssertionError as si, validateSchema as sn, BaseVectorSchema as sr, VectorScalar as st, mysqlAdapter as t, InvalidTransactionInputError as ti, AggregateResultType as tn, GeneratorDefaultBrand as tr, ModelSchemas as tt, Driver as u, PendingOperationError as ui, isSchemaValidationError as un, PointSchema as ur, NumberScalar as ut, ObservationUnit as v, MigrationError as vi, UnwrapPendingOperations as vn, JsonSchema as vr, BooleanScalar as vt, InferDatabase as w, ValueTooLongError as wi, CacheInvalidationOptions as wn, IsoTimeSchema as wr, getSchemas as wt, CacheableOperations as x, ForeignKeyError as xi, CacheEntry as xn, BaseIsoTimeSchema as xr, ReferencesStage as xt, ObserveHandler as y, isMigrationError as yi, isPendingOperation as yn, JsonValue as yr, BlobScalar as yt, VariantToManyRelation as z, toPrismaErrorCode as zi, FieldRef as zn, DbNull as zr, OfficialCacheExtension as zt };
14315
+ export { ModelOperationInput as $, SQLITE as $i, DecimalSchema as $n, ValidationError as $r, ExtensionContributionState as $t, Schema$1 as A, isValueTooLongError as Ai, TransactionOptionSupport as An, BooleanSchema as Ar, DriverConfig as At, VariantToOneRelation as B, toPrismaErrorCode as Bi, FieldRef as Bn, DbNull as Br, WriteOutcome as Bt, Client as C, NotNullConstraintError as Ci, CacheSetOptions as Cn, BaseIsoTimestampSchema as Cr, s as Ct, OperationPayloadSchema as D, isForeignKeyError as Di, sqliteResultParser as Dn, BaseEnumSchema as Dr, renderSchemaType as Dt, OperationPayload as E, isCheckConstraintError as Ei, WithCacheOptions as En, IsoTimestampSchema as Er, renderOperationResultType as Et, LinkedClientConfig as F, PrismaErrorCode as Fi, QueryResult as Fn, createJsonSchemaConverter as Fr, VibORMClient as Ft, ParseResult as G, GeoPoint as Gi, IndexDefinition as Gn, JsonSchema$1 as Gr, ClientExtension as Gt, BigIntScalar as H, DiagnosticDisclosure as Hi, createModelFieldRefs as Hn, JsonNullKind as Hr, NoControls as Ht, Links$1 as I, VibORMError as Ii, V$1 as In, toJsonSchema as Ir, VibORMConfig as It, SchemaRegistryOperation as J, Decimal as Ji, InitialModelState as Jn, Getter as Jr, StatementHandler as Jt, Prettify as K, GeoPolygon as Ki, IndexOptions as Kn, inferred as Kr, defineExtension as Kt, RelationLinks as L, VibORMErrorCode as Li, v as Ln, createSchemaRegistry as Lr, createClient as Lt, ClientSchema as M, CacheInvalidKeyError as Mi, CommittedBatchNotification as Mn, BlobSchema as Mr, ExtendedOperationResult as Mt, FlatSchema as N, CacheInvalidTTLError as Ni, Dialect as Nn, BaseBigIntSchema as Nr, ExtensionState as Nt, OperationResult as O, isNotNullConstraintError as Oi, BatchTransactionOptions as On, EnumSchema as Or, validateOperationPayload as Ot, Linked as P, CacheOperationNotCacheableError as Pi, QueryExecutionContext as Pn, BigIntSchema as Pr, NoExtraDriverConfigKeys as Pt, ModelCoreSchemas as Q, PG as Qi, UpdateState as Qn, RelationSlot as Qr, ExtensionCacheState as Qt, ModelShape as R, isRetryableError as Ri, StringSchema as Rn, AnyJsonNullSentinel as Rr, defaultOmit as Rt, CachedClient as S, ForeignKeyError as Si, CacheEntry as Sn, BaseIsoTimeSchema as Sr, ModelToManyRelation as St, MutationOperations as T, ValueTooLongError as Ti, CacheInvalidationOptions as Tn, IsoTimeSchema as Tr, getOperationPayloadSchema as Tt, InferInput as U, GeoArea as Ui, isFieldRef as Un, JsonNullSentinel as Ur, PlacedControl as Ut, type Scalar as V, wrapError as Vi, ModelFieldRefs as Vn, JsonNull as Vr, DefinitionControls as Vt, InferOutput as W, GeoBounds as Wi, AnyModel as Wn, isJsonNullSentinel as Wr, RowsVerbs as Wt, ModelArgsSchemas as X, NativeType as Xi, ModelInternal as Xn, ReferentialAction as Xr, ClientExtensionState as Xt, VibSchema as Y, MYSQL as Yi, Model$1 as Yn, JunctionReferentialAction as Yr, AccumulatedExtensionState as Yt, ModelCoreInput as Z, NativeTypeMap as Zi, ModelState as Zn, RelationCardinality as Zr, EmptyClientExtensionState as Zt, ObservationCompletion as _, isPendingOperationError as _i, PendingOperation as _n, BaseJsonSchema as _r, DateScalar as _t, PostgresAdapter as a, ConnectionError as ai, GroupByResultType as an, ScalarType as ar, CoreSchemas as at, OFFICIAL_INSTRUMENTATION_NAME as b, isMigrationError as bi, isPendingOperation as bn, JsonValue as br, ModelToOneRelation as bt, Operation as c, NestedWriteAssertionError as ci, validateSchema as cn, BaseVectorSchema as cr, StringScalar as ct, MigrationSessionAttestation as d, PendingOperationError as di, isSchemaValidationError as dn, PointSchema as dr, JsonScalar as dt, ValidationErrorSource as ei, ExtensionResultConsumerState as en, AutoGenerate as er, ModelRelationNestedInput as et, SQLITE_MIGRATION_CAPABILITY as f, QueryEngineError as fi, SchemaValidationIssue as fn, ObjectSchema as fr, IntScalar as ft, MigrationNamespaceAttestation as g, isNotFoundError as gi, Schema$3 as gn, NumberSchema as gr, DateTimeScalar as gt, DriverResultParser as h, isClientInitializationError as hi, DateTimePhysicalForm as hn, IntegerSchema as hr, TimeScalar as ht, SQLiteAdapter as i, ClientInitializationError as ii, CountResultType as in, ScalarState as ir, ArgsSchemas as it, ValidatedOperationPayload as j, CacheConfigurationError as ji, BatchQuery as jn, BaseBlobSchema as jr, ExtendedClient as jt, Operations as k, isUniqueConstraintError as ki, DriverTransactionOptions as kn, BaseBooleanSchema as kr, ClientTypeState as kt, AnyDriver as l, NestedWriteError as li, validateSchemaOrThrow as ln, VectorSchema as lr, PointScalar as lt, PinnedSessionReservation as m, UnsupportedOperationError as mi, ValidationResult$1 as mn, BaseNumberSchema as mr, DecimalScalar as mt, postgresAdapter as n, InvalidTransactionInputError as ni, AggregateResultType as nn, GeneratorDefaultBrand as nr, ModelStateSchemas as nt, MySQLAdapter as o, FeatureNotSupportedError as oi, InferSelectInclude as on, UpdateState$1 as or, NumericScalar as ot, SqliteMigrationCapability as p, QueryError as pi, Severity as pn, BaseIntegerSchema as pr, EnumScalar as pt, SchemaRegistryLookup as q, DecimalDescriptor as qi, IndexType as qn, AnyRelation as qr, StatementContext as qt, sqliteAdapter as r, TransactionError as ri, BatchPayload as rn, InitialScalarState as rr, ScalarSchemas as rt, DatabaseAdapter as s, ForbiddenError as si, RawOperation as sn, parse as sr, VectorScalar as st, mysqlAdapter as t, isValidationError as ti, MergeExtensionState as tn, AutoGenerateType as tr, ModelSchemas as tt, Driver as u, NotFoundError as ui, SchemaValidationError as un, BasePointSchema as ur, NumberScalar as ut, ObservationUnit as v, isUnsupportedOperationError as vi, UnwrapPendingOperation as vn, InputJsonValue as vr, BooleanScalar as vt, InferDatabase as w, UniqueConstraintError as wi, WaitUntilFn as wn, IsoDateSchema as wr, getSchemas as wt, CacheableOperations as x, CheckConstraintError as xi, CacheDriver as xn, BaseIsoDateSchema as xr, ReferencesStage as xt, ObserveHandler as y, MigrationError as yi, UnwrapPendingOperations as yn, JsonSchema as yr, BlobScalar as yt, VariantToManyRelation as z, isVibORMError as zi, AnyFieldRef as zn, AnyNull as zr, OfficialCacheExtension as zt };
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { $n as AutoGenerate, $r as ValidationErrorSource, $t as ExtensionResultConsumerState, Ai as CacheConfigurationError, B as VariantToOneRelation, Bi as wrapError, Bn as ModelFieldRefs, Br as JsonNull, Ci as UniqueConstraintError, Cr as IsoDateSchema, Ct as s, Di as isNotNullConstraintError, Dr as EnumSchema, Dt as renderSchemaType, Ei as isForeignKeyError, Et as renderOperationResultType, F as LinkedClientConfig, Fi as VibORMError, Ft as VibORMClient, Gi as GeoPolygon, Gn as IndexOptions, Gt as defineExtension, H as BigIntScalar, Hi as GeoArea, Hn as isFieldRef, Hr as JsonNullSentinel, Ht as PlacedControl, I as Links, Ii as VibORMErrorCode, It as VibORMConfig, Jn as Model, Jt as AccumulatedExtensionState, Ki as DecimalDescriptor, Kr as AnyRelation, Kt as StatementContext, L as RelationLinks, Li as isRetryableError, Ln as StringSchema, Lr as AnyJsonNullSentinel, Lt as createClient, M as ClientSchema, Mi as CacheInvalidTTLError, Mt as ExtendedOperationResult, N as FlatSchema, Ni as CacheOperationNotCacheableError, Nr as BigIntSchema, Nt as ExtensionState, Oi as isUniqueConstraintError, Ot as validateOperationPayload, P as Linked, Pi as PrismaErrorCode, Qn as DecimalSchema, Qr as ValidationError, Qt as ExtensionContributionState, R as ModelShape, Ri as isVibORMError, Rn as AnyFieldRef, Rr as AnyNull, Si as NotNullConstraintError, St as ModelToManyRelation, Ti as isCheckConstraintError, Tr as IsoTimestampSchema, Tt as getOperationPayloadSchema, Ui as GeoBounds, Un as AnyModel, Ur as isJsonNullSentinel, V as Scalar, Vi as DiagnosticDisclosure, Vn as createModelFieldRefs, Vr as JsonNullKind, Vt as NoControls, Wi as GeoPoint, Wn as IndexDefinition, Wt as ClientExtension, Xn as ModelState, Xr as RelationCardinality, Xt as EmptyClientExtensionState, Y as VibSchema, Yn as ModelInternal, Yr as ReferentialAction, Yt as ClientExtensionState, Zn as UpdateState, Zr as RelationSlot, Zt as ExtensionCacheState, _ as ObservationCompletion, _i as isUnsupportedOperationError, _n as UnwrapPendingOperation, _r as InputJsonValue, _t as DateScalar, ai as FeatureNotSupportedError, ar as UpdateState$1, bi as CheckConstraintError, bt as ModelToOneRelation, ci as NestedWriteError, cn as validateSchemaOrThrow, cr as VectorSchema, ct as StringScalar, di as QueryEngineError, dn as SchemaValidationIssue, dr as ObjectSchema, dt as JsonScalar, ei as isValidationError, en as MergeExtensionState, fi as QueryError, fn as Severity, ft as IntScalar, gi as isPendingOperationError, gn as PendingOperation, gt as DateTimeScalar, hi as isNotFoundError, hr as NumberSchema, ht as TimeScalar, ii as ConnectionError, ji as CacheInvalidKeyError, jr as BlobSchema, jt as ExtendedClient, ki as isValueTooLongError, kr as BooleanSchema, kt as ClientTypeState, li as NotFoundError, ln as SchemaValidationError, lt as PointScalar, mi as isClientInitializationError, mr as IntegerSchema, mt as DecimalScalar, ni as TransactionError, nr as InitialScalarState, oi as ForbiddenError, on as RawOperation, ot as NumericScalar, pi as UnsupportedOperationError, pn as ValidationResult, pt as EnumScalar, qi as Decimal, qn as InitialModelState, qr as Getter, qt as StatementHandler, ri as ClientInitializationError, rr as ScalarState, si as NestedWriteAssertionError, sn as validateSchema, st as VectorScalar, ti as InvalidTransactionInputError, tr as GeneratorDefaultBrand, ui as PendingOperationError, un as isSchemaValidationError, ur as PointSchema, ut as NumberScalar, v as ObservationUnit, vi as MigrationError, vn as UnwrapPendingOperations, vr as JsonSchema, vt as BooleanScalar, wi as ValueTooLongError, wr as IsoTimeSchema, wt as getSchemas, xi as ForeignKeyError, xt as ReferencesStage, y as ObserveHandler, yi as isMigrationError, yn as isPendingOperation, yr as JsonValue, yt as BlobScalar, z as VariantToManyRelation, zi as toPrismaErrorCode, zn as FieldRef, zr as DbNull } from "./index-Ci8b13Lm.mjs";
2
- import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-Q_twK-wW.mjs";
1
+ import { $n as DecimalSchema, $r as ValidationError, $t as ExtensionContributionState, Ai as isValueTooLongError, Ar as BooleanSchema, B as VariantToOneRelation, Bi as toPrismaErrorCode, Bn as FieldRef, Br as DbNull, Ci as NotNullConstraintError, Ct as s, Di as isForeignKeyError, Dt as renderSchemaType, Ei as isCheckConstraintError, Er as IsoTimestampSchema, Et as renderOperationResultType, F as LinkedClientConfig, Fi as PrismaErrorCode, Ft as VibORMClient, Gi as GeoPoint, Gn as IndexDefinition, Gt as ClientExtension, H as BigIntScalar, Hi as DiagnosticDisclosure, Hn as createModelFieldRefs, Hr as JsonNullKind, Ht as NoControls, I as Links, Ii as VibORMError, It as VibORMConfig, Ji as Decimal, Jn as InitialModelState, Jr as Getter, Jt as StatementHandler, Ki as GeoPolygon, Kn as IndexOptions, Kt as defineExtension, L as RelationLinks, Li as VibORMErrorCode, Lt as createClient, M as ClientSchema, Mi as CacheInvalidKeyError, Mr as BlobSchema, Mt as ExtendedOperationResult, N as FlatSchema, Ni as CacheInvalidTTLError, Nt as ExtensionState, Oi as isNotNullConstraintError, Or as EnumSchema, Ot as validateOperationPayload, P as Linked, Pi as CacheOperationNotCacheableError, Pr as BigIntSchema, Qn as UpdateState, Qr as RelationSlot, Qt as ExtensionCacheState, R as ModelShape, Ri as isRetryableError, Rn as StringSchema, Rr as AnyJsonNullSentinel, Si as ForeignKeyError, St as ModelToManyRelation, Ti as ValueTooLongError, Tr as IsoTimeSchema, Tt as getOperationPayloadSchema, Ui as GeoArea, Un as isFieldRef, Ur as JsonNullSentinel, Ut as PlacedControl, V as Scalar, Vi as wrapError, Vn as ModelFieldRefs, Vr as JsonNull, Wi as GeoBounds, Wn as AnyModel, Wr as isJsonNullSentinel, Xn as ModelInternal, Xr as ReferentialAction, Xt as ClientExtensionState, Y as VibSchema, Yn as Model, Yt as AccumulatedExtensionState, Zn as ModelState, Zr as RelationCardinality, Zt as EmptyClientExtensionState, _ as ObservationCompletion, _i as isPendingOperationError, _n as PendingOperation, _t as DateScalar, ai as ConnectionError, bi as isMigrationError, bn as isPendingOperation, br as JsonValue, bt as ModelToOneRelation, ci as NestedWriteAssertionError, cn as validateSchema, ct as StringScalar, di as PendingOperationError, dn as isSchemaValidationError, dr as PointSchema, dt as JsonScalar, ei as ValidationErrorSource, en as ExtensionResultConsumerState, er as AutoGenerate, fi as QueryEngineError, fn as SchemaValidationIssue, fr as ObjectSchema, ft as IntScalar, gi as isNotFoundError, gr as NumberSchema, gt as DateTimeScalar, hi as isClientInitializationError, hr as IntegerSchema, ht as TimeScalar, ii as ClientInitializationError, ir as ScalarState, ji as CacheConfigurationError, jt as ExtendedClient, ki as isUniqueConstraintError, kt as ClientTypeState, li as NestedWriteError, ln as validateSchemaOrThrow, lr as VectorSchema, lt as PointScalar, mi as UnsupportedOperationError, mn as ValidationResult, mt as DecimalScalar, ni as InvalidTransactionInputError, nr as GeneratorDefaultBrand, oi as FeatureNotSupportedError, or as UpdateState$1, ot as NumericScalar, pi as QueryError, pn as Severity, pt as EnumScalar, qi as DecimalDescriptor, qr as AnyRelation, qt as StatementContext, ri as TransactionError, rr as InitialScalarState, si as ForbiddenError, sn as RawOperation, st as VectorScalar, ti as isValidationError, tn as MergeExtensionState, ui as NotFoundError, un as SchemaValidationError, ut as NumberScalar, v as ObservationUnit, vi as isUnsupportedOperationError, vn as UnwrapPendingOperation, vr as InputJsonValue, vt as BooleanScalar, wi as UniqueConstraintError, wr as IsoDateSchema, wt as getSchemas, xi as CheckConstraintError, xt as ReferencesStage, y as ObserveHandler, yi as MigrationError, yn as UnwrapPendingOperations, yr as JsonSchema, yt as BlobScalar, z as VariantToManyRelation, zi as isVibORMError, zn as AnyFieldRef, zr as AnyNull } from "./index-DRX_LLQM.mjs";
2
+ import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-CF5Xi6z-.mjs";
3
3
  export { type AccumulatedExtensionState, type AnyFieldRef, type AnyJsonNullSentinel, type AnyModel, AnyNull, type AnyRelation, type AutoGenerate, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, CacheConfigurationError, CacheInvalidKeyError, CacheInvalidTTLError, CacheOperationNotCacheableError, CheckConstraintError, type ClientExtension, type ClientExtensionState, ClientInitializationError, type ClientSchema, type ClientTypeState, ConnectionError, type DateScalar, type DateTimeScalar, DbNull, Decimal, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type DiagnosticDisclosure, type EmptyClientExtensionState, type EnumScalar, type EnumSchema, type ExtendedClient, type ExtendedOperationResult, type ExtensionCacheState, type ExtensionContributionState, type ExtensionResultConsumerState, type ExtensionState, FeatureNotSupportedError, type FieldRef, type FlatSchema, ForbiddenError, ForeignKeyError, type GeneratorDefaultBrand, type GeoArea, type GeoBounds, type GeoPoint, type GeoPolygon, type Getter, type IndexDefinition, type IndexOptions, type InitialModelState, type InitialScalarState, type InputJsonValue, type IntScalar, type IntegerSchema, InvalidTransactionInputError, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, JsonNull, type JsonNullKind, JsonNullSentinel, type JsonScalar, type JsonValue, type JsonSchema as JsonValueSchema, type Linked, type LinkedClientConfig, type Links, type MergeExtensionState, MigrationError, type Model, type ModelFieldRefs, type ModelInternal, type ModelShape, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, NestedWriteAssertionError, NestedWriteError, type NoControls, NotFoundError, NotNullConstraintError, type NumberScalar, type NumberSchema, type NumericScalar, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, PendingOperation, PendingOperationError, type PlacedControl, type PointScalar, type PointSchema, type PrismaErrorCode, QueryEngineError, QueryError, type RawOperation, type RawValue, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationLinks, type RelationSlot, type Scalar, type ScalarState, type UpdateState$1 as ScalarUpdateState, SchemaValidationError, type SchemaValidationIssue, type Severity, Sql, type StatementContext, type StatementHandler, type StringScalar, type StringSchema, type TimeScalar, TransactionError, UniqueConstraintError, UnsupportedOperationError, type UnwrapPendingOperation, type UnwrapPendingOperations, ValidationError, type ValidationErrorSource, type ValidationResult, type Value, ValueTooLongError, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, type VibORMClient, type VibORMConfig, VibORMError, VibORMErrorCode, type VibSchema, createClient, createModelFieldRefs, defineExtension, empty, getOperationPayloadSchema, getSchemas, isCheckConstraintError, isClientInitializationError, isFieldRef, isForeignKeyError, isJsonNullSentinel, isMigrationError, isNotFoundError, isNotNullConstraintError, isPendingOperation, isPendingOperationError, isRetryableError, isSchemaValidationError, isSql, isUniqueConstraintError, isUnsupportedOperationError, isValidationError, isValueTooLongError, isVibORMError, join, raw, renderOperationResultType, renderSchemaType, s, sqlTag as sql, toPrismaErrorCode, validateOperationPayload, validateSchema, validateSchemaOrThrow, wrapError };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t}from"./chain-C1VPkUpC.mjs";import{a as n,i as r,n as i,o as a,r as o,t as s}from"./base-wlv81COV.mjs";import{g as c,h as l,m as u,p as d}from"./observation-BcT8Cs3d.mjs";import{C as f,D as p,E as m,O as h,S as g,T as _,b as v,w as y,x as b,y as x}from"./error-mapping-Zett_Pnt.mjs";import{n as S,t as C}from"./migrations-OE5D32qo.mjs";import{_ as w,a as T,c as E,d as D,f as O,g as k,h as A,i as j,l as M,m as N,n as P,o as F,p as I,r as L,t as R,u as z,v as B}from"./validation-DN1N2OdK.mjs";import{n as V,t as H}from"./transaction-D5LHYn-r.mjs";import{D as U,E as W,O as G,P as K,T as q,j as J,k as Y}from"./v-lthABIXD.mjs";import{F as X}from"./geo-point-codec-DcUTvoEg.mjs";import{a as Z,i as Q,n as $,o as ee,r as te,t as ne}from"./sql-BR8ZzKn8.mjs";import{C as re,S as ie}from"./scalar-B3WLZzJj.mjs";import{a as ae,i as oe}from"./validator-BJhI364k.mjs";import{n as se}from"./builder-ClblW6Lj.mjs";import{d as ce,m as le}from"./result-shape-BuGfArOr.mjs";import{t as ue}from"./client-DHf2ZfRe.mjs";import{i as de,n as fe,r as pe,t as me}from"./schema-introspection-BqN7d_sA.mjs";import{t as he}from"./schema-B_Bc7TQ2.mjs";const getSchemas=e=>se(e).proxy;export{q as AnyNull,d as CacheConfigurationError,u as CacheInvalidKeyError,l as CacheInvalidTTLError,c as CacheOperationNotCacheableError,x as CheckConstraintError,L as ClientInitializationError,j as ConnectionError,W as DbNull,X as Decimal,T as FeatureNotSupportedError,F as ForbiddenError,v as ForeignKeyError,H as InvalidTransactionInputError,U as JsonNull,G as JsonNullSentinel,C as MigrationError,E as NestedWriteAssertionError,M as NestedWriteError,z as NotFoundError,b as NotNullConstraintError,ce as PendingOperation,D as PendingOperationError,O as QueryEngineError,I as QueryError,ie as SchemaValidationError,ne as Sql,V as TransactionError,g as UniqueConstraintError,N as UnsupportedOperationError,R as ValidationError,f as ValueTooLongError,s as VibORMError,i as VibORMErrorCode,ue as createClient,J as createModelFieldRefs,t as defineExtension,$ as empty,me as getOperationPayloadSchema,getSchemas,y as isCheckConstraintError,A as isClientInitializationError,K as isFieldRef,_ as isForeignKeyError,Y as isJsonNullSentinel,S as isMigrationError,k as isNotFoundError,m as isNotNullConstraintError,le as isPendingOperation,w as isPendingOperationError,o as isRetryableError,re as isSchemaValidationError,te as isSql,p as isUniqueConstraintError,B as isUnsupportedOperationError,P as isValidationError,h as isValueTooLongError,r as isVibORMError,Q as join,Z as raw,fe as renderOperationResultType,pe as renderSchemaType,he as s,ee as sql,n as toPrismaErrorCode,de as validateOperationPayload,oe as validateSchema,ae as validateSchemaOrThrow,a as wrapError};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t}from"./chain-BQoDfo80.mjs";import{a as n,i as r,n as i,o as a,r as o,t as s}from"./base-wlv81COV.mjs";import{g as c,h as l,m as u,p as d}from"./observation-BcT8Cs3d.mjs";import{C as f,D as p,E as m,O as h,S as g,T as _,b as v,w as y,x as b,y as x}from"./error-mapping-DRY49A3C.mjs";import{n as S,t as C}from"./migrations-OE5D32qo.mjs";import{c as w,d as T,f as E,g as D,h as O,i as k,l as A,m as j,n as M,o as N,p as P,r as F,s as I,t as L,u as R}from"./query-CTna5P9o.mjs";import{n as z,t as B}from"./transaction-D5LHYn-r.mjs";import{n as V,t as H}from"./validation-pfpKPPZ_.mjs";import{D as U,E as W,O as G,P as K,T as q,j as J,k as Y}from"./v-yKivkoka.mjs";import{F as X}from"./geo-point-codec-mjROsQX-.mjs";import{a as Z,i as Q,n as $,o as ee,r as te,t as ne}from"./sql-DGtEeP8z.mjs";import{C as re,S as ie}from"./scalar-D6QmJ22_.mjs";import{a as ae,i as oe}from"./validator-XVm02V0K.mjs";import{n as se}from"./builder-D0GQK-fA.mjs";import{d as ce,m as le}from"./result-shape-C8QFUuIt.mjs";import{t as ue}from"./client-BqgVSbk0.mjs";import{i as de,n as fe,r as pe,t as me}from"./schema-introspection-CfqmM3Cz.mjs";import{t as he}from"./schema-CY9kOwJ-.mjs";const getSchemas=e=>se(e).proxy;export{q as AnyNull,d as CacheConfigurationError,u as CacheInvalidKeyError,l as CacheInvalidTTLError,c as CacheOperationNotCacheableError,x as CheckConstraintError,L as ClientInitializationError,M as ConnectionError,W as DbNull,X as Decimal,F as FeatureNotSupportedError,k as ForbiddenError,v as ForeignKeyError,B as InvalidTransactionInputError,U as JsonNull,G as JsonNullSentinel,C as MigrationError,N as NestedWriteAssertionError,I as NestedWriteError,w as NotFoundError,b as NotNullConstraintError,ce as PendingOperation,A as PendingOperationError,R as QueryEngineError,T as QueryError,ie as SchemaValidationError,ne as Sql,z as TransactionError,g as UniqueConstraintError,E as UnsupportedOperationError,H as ValidationError,f as ValueTooLongError,s as VibORMError,i as VibORMErrorCode,ue as createClient,J as createModelFieldRefs,t as defineExtension,$ as empty,me as getOperationPayloadSchema,getSchemas,y as isCheckConstraintError,P as isClientInitializationError,K as isFieldRef,_ as isForeignKeyError,Y as isJsonNullSentinel,S as isMigrationError,j as isNotFoundError,m as isNotNullConstraintError,le as isPendingOperation,O as isPendingOperationError,o as isRetryableError,re as isSchemaValidationError,te as isSql,p as isUniqueConstraintError,D as isUnsupportedOperationError,V as isValidationError,h as isValueTooLongError,r as isVibORMError,Q as join,Z as raw,fe as renderOperationResultType,pe as renderSchemaType,he as s,ee as sql,n as toPrismaErrorCode,de as validateOperationPayload,oe as validateSchema,ae as validateSchemaOrThrow,a as wrapError};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/schema/schemas.ts"],"sourcesContent":["import { createSchemaRegistry, type ModelSchemas } from \"@validation\";\nimport type { AnyModel } from \"./model\";\n\ntype Schema = Record<string, AnyModel>;\n\ntype SchemaProxy<S extends Schema> = {\n [K in keyof S]: ModelSchemas<S[K]>;\n};\n\n/**\n * Creates a registry-backed proxy to access model validation schemas.\n * Usage: `getSchemas(mySchema).user.core.where` → returns the where schema for the user model\n *\n * This is REGISTRY-ONLY construction — a schema surface without a client — and\n * plan §7.3 makes it one of the three effect-capable boundaries: the operation\n * schemas it returns decide which mutation verbs a caller may spell, which is a\n * topology answer. So it hydrates and runs the structural relation-definition\n * gate once, for its own lifecycle, exactly as client construction does.\n */\nexport const getSchemas = <S extends Schema>(schema: S): SchemaProxy<S> => {\n return createSchemaRegistry(schema).proxy;\n};\n"],"mappings":"8pCAmBA,MAAa,WAAgC,GACpC,GAAqB,EAAO,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/schema/schemas.ts"],"sourcesContent":["import { createSchemaRegistry, type ModelSchemas } from \"@validation\";\nimport type { AnyModel } from \"./model\";\n\ntype Schema = Record<string, AnyModel>;\n\ntype SchemaProxy<S extends Schema> = {\n [K in keyof S]: ModelSchemas<S[K]>;\n};\n\n/**\n * Creates a registry-backed proxy to access model validation schemas.\n * Usage: `getSchemas(mySchema).user.core.where` → returns the where schema for the user model\n *\n * This is REGISTRY-ONLY construction — a schema surface without a client — and\n * plan §7.3 makes it one of the three effect-capable boundaries: the operation\n * schemas it returns decide which mutation verbs a caller may spell, which is a\n * topology answer. So it hydrates and runs the structural relation-definition\n * gate once, for its own lifecycle, exactly as client construction does.\n */\nexport const getSchemas = <S extends Schema>(schema: S): SchemaProxy<S> => {\n return createSchemaRegistry(schema).proxy;\n};\n"],"mappings":"gsCAmBA,MAAa,WAAgC,GACpC,GAAqB,EAAO,CAAC"}
@@ -1,4 +1,4 @@
1
- import { Fi as VibORMError, Vi as DiagnosticDisclosure, b as OFFICIAL_INSTRUMENTATION_NAME, c as Operation, y as ObserveHandler } from "./index-Ci8b13Lm.mjs";
1
+ import { Hi as DiagnosticDisclosure, Ii as VibORMError, b as OFFICIAL_INSTRUMENTATION_NAME, c as Operation, y as ObserveHandler } from "./index-DRX_LLQM.mjs";
2
2
 
3
3
  //#region src/instrumentation/types.d.ts
4
4
 
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,s as n}from"./value-guards-CK9guf2Z.mjs";import{f as r,t as i}from"./chain-C1VPkUpC.mjs";import{C as a,D as o,E as s,S as c,T as l,g as u,m as d,p as f,s as p,x as m,y as h}from"./base-wlv81COV.mjs";import{c as g,s as _,u as ee}from"./observation-BcT8Cs3d.mjs";import{t as te}from"./version-DAFcmokN.mjs";const v=new Set([`deprecation`,`event`,`notice`,`status`]);function sanitizeLogMetadata(e,t){return f(e,v,t,!0)}function prettyLog(e){let t=e.timestamp.toISOString(),r=e.duration===void 0?``:`${e.duration}ms`,i=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,i||`query`,r].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,n(e.meta?.event)?e.meta.event:`unknown`,n(e.meta?.status)?`(${e.meta.status})`:``);break;case`warning`:console.warn(`[WARN]`,t,i,formatDiagnostic(e.meta));break;case`error`:console.error(`[ERROR]`,t,i,r),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function formatDiagnostic(e){return e===void 0?``:String(JSON.stringify(e))}function getHandler(e,t){let n=e[t];return n===void 0?e.all:n}function createLogger(e){let t=Object.freeze({includeParams:e.includeParams===!0,includeSql:e.includeSql===!0}),n=Object.freeze({cache:getHandler(e,`cache`),error:getHandler(e,`error`),query:getHandler(e,`query`),warning:getHandler(e,`warning`)});function sanitizeEvent(e,n){let r=t.includeParams&&e.params?d(e.params,t):void 0;return{level:n,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:t.includeSql?e.sql:void 0,params:r,error:e.error?u(e.error,t):void 0,meta:e.meta?sanitizeLogMetadata(e.meta,t):void 0}}function emit(e,t){try{let r=n[t];if(!r)return;let i=sanitizeEvent(e,t),defaultLog=()=>{try{prettyLog(i)}catch{}};r===!0?defaultLog():Promise.resolve(r(i,defaultLog)).catch(()=>void 0)}catch{}}return Object.freeze({log(e){emit(e,e.level)},query(e){emit(e,`query`)},cache(e){emit(e,`cache`)},warn(e){emit(e,`warning`)},error(e){emit(e,`error`)},isLevelEnabled(e){return n[e]!==void 0}})}const y=`viborm.operation`,b=`viborm.execute`,x=`viborm.transaction`,S=`viborm.connect`,C=`viborm.disconnect`,w=`db.system.name`,T=`db.namespace`,E=`db.collection.name`,D=`db.operation.name`,O=`db.query.text`,k=`db.query.summary`,A=`db.operation.batch.size`,j=`server.address`,M=`server.port`,N=`db.response.returned_rows`,P=`error.type`,F=`db.system.driver`,I=`viborm.correlation.id`,L=`db.query.parameter`,R=`viborm.cache.get`,z=`viborm.cache.set`,B=`viborm.cache.delete`,V=`viborm.cache.clear`,H=`viborm.cache.invalidate`,U=`cache.driver`,W=`cache.result`,G=`cache.ttl`,K={SpanStatusCode:{OK:1,ERROR:2}},q=te,J=Symbol(`viborm.shouldTraceSpan`),Y=new WeakMap,X=new WeakSet,Z={async startActiveSpan(e,t){return t()},isEnabled(){return!1}};Object.defineProperty(Z,J,{value:()=>!1}),Object.freeze(Z);function createTracerWrapper(e){let t=Object.freeze((e?.ignoreSpanTypes??[]).map(e=>n(e)?e:new RegExp(e.source,e.flags))),r=e?.includeSql===!0,i=e?.includeParams===!0;function shouldIgnoreSpan(e){return t.some(t=>n(t)?t===e:new RegExp(t.source,t.flags).test(e))}function buildAttributes(e){let t={...e.attributes};if(e.sql&&(r&&e.sql.query!==void 0&&(t[O]=e.sql.query),i&&e.sql.params)){let n=d(e.sql.params,{includeParams:!0,includeSql:r});for(let e=0;e<n.length;e++){let r=n[e];t[`${L}.${e}`]=formatSanitizedSpanParameter(r)}}return t}function presentThrough(e){return{async startActiveSpan(t,n){if(shouldIgnoreSpan(t.name))return n();let r=createExecution(n,K);try{let n=buildAttributes(t);Promise.resolve(e.startActiveSpan(t.name,e=>(setSpanAttributes(e,n),r(e)))).catch(()=>void 0)}catch{}return r()},isEnabled(){return!0}}}function autoDetect(){let e=null,t=null,n=!1;async function tryLoadOtel(){try{return e=await import(`@opentelemetry/api`),e}catch{return null}}function getTracer(e){return t||=e.trace.getTracer(`viborm`,q),t}let r=tryLoadOtel().then(e=>(n=!0,e)),i={async startActiveSpan(t,i){if(n||await r,!e||shouldIgnoreSpan(t.name))return i();let a,o;try{let n=buildAttributes(t),r=t.kind??e.SpanKind.INTERNAL,i=t.root?e.ROOT_CONTEXT:e.context.active();a=getTracer(e).startSpan(t.name,{kind:r,attributes:n},i),o=e.trace.setSpan(i,a)}catch{return i()}let s=createExecution(i,e);try{Promise.resolve(e.context.with(o,()=>s(a))).catch(()=>void 0)}catch{}return s(a)},isEnabled(){return e!==null}},a=r.then(()=>void 0);return Y.set(i,a),a.then(()=>Y.delete(i)),i}let a=e?.tracer,o=a===void 0?autoDetect():presentThrough(a);return Object.defineProperty(o,J,{value:e=>!shouldIgnoreSpan(e)}),Object.freeze(o)}function createExecution(e,t){let n=new Set,r,i,settle=(e,a)=>{r=e,i=a;for(let r of n)endSpan(r,e,t,a)},a,o=!1;return s=>{if(s!==void 0&&(n.add(s),r!==void 0&&endSpan(s,r,t,i)),a)return a;if(o)return Promise.reject(createTraceError());o=!0;try{return a=new Promise((t,n)=>{try{Promise.resolve(e(s)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),n(e)})}catch(e){settle(!0,e),n(e)}}),a}finally{o=!1}}}function endSpan(e,t,n,r){if(!X.has(e)){if(X.add(e),t){let t=c(r)?h(r):void 0,i=typeof t?.name==`string`?t.name:`Error`;safely(()=>e.setAttribute(`error.type`,i));let a=t?.code;typeof a==`string`&&safely(()=>e.setAttribute(`viborm.error.code`,a));let o=t?.meta;if(typeof o==`object`&&o&&`providerSqlState`in o&&typeof o.providerSqlState==`string`){let t=o.providerSqlState;safely(()=>e.setAttribute(`db.response.sqlstate`,t))}safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let s=createTraceError();s.name=i,safely(()=>e.recordException?.(s))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function prewarmTracer(e){return Y.get(e)}function shouldTraceSpan(e,t){try{let n=Reflect.get(e,J);return typeof n!=`function`||n(t)!==!1}catch{return!0}}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function formatSanitizedSpanParameter(e){return n(e)?e:String(JSON.stringify(e))}function getNoopTracer(){return Z}function createInstrumentationContext(e){let t=snapshotInstrumentationConfig(e),n;if(t.tracing){let e=t.tracing===!0?{}:t.tracing;n=createTracerWrapper({includeSql:e.includeSql,includeParams:e.includeParams,ignoreSpanTypes:e.ignoreSpanTypes,tracer:e.tracer})}else n=getNoopTracer();let r={config:t,tracer:n};return t.logging&&(r.logger=createLogger(t.logging===!0?{all:!0}:t.logging)),Object.freeze(r)}function snapshotInstrumentationConfig(e){let t=snapshotDisclosure(o(e,`diagnostics`)),n=o(e,`tracing`),r=o(e,`logging`),i=n===!0?!0:a(n)?snapshotTracingConfig(n):void 0,s=r===!0?!0:a(r)?snapshotLoggingConfig(r):void 0;return Object.freeze({diagnostics:t,tracing:i,logging:s})}function snapshotDisclosure(e){return Object.freeze({includeParams:a(e)&&o(e,`includeParams`)===!0,includeSql:a(e)&&o(e,`includeSql`)===!0,includeProviderDetails:a(e)&&o(e,`includeProviderDetails`)===!0,includeCallsite:a(e)&&o(e,`includeCallsite`)===!0})}function snapshotTracingConfig(e){let t=snapshotIgnorePatterns(o(e,`ignoreSpanTypes`)),n=o(e,`tracer`);return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,...t.length>0?{ignoreSpanTypes:t}:{},...isPlatformTracer(n)?{tracer:n}:{}})}function isPlatformTracer(e){return a(e)&&t(o(e,`startActiveSpan`))}function snapshotIgnorePatterns(e){if(!m(e))return Object.freeze([]);let t=[],r=Math.min(l(e),128);for(let i=0;i<r;i+=1){let r=s(e,String(i));if(!(r&&`value`in r))continue;let a=r.value;if(n(a)){t.push(a);continue}try{a instanceof RegExp&&t.push(Object.freeze(new RegExp(a.source,a.flags)))}catch{}}return Object.freeze(t)}function snapshotLoggingConfig(e){let t=readLogHandler(e,`all`),n=readLogHandler(e,`cache`),r=readLogHandler(e,`error`),i=readLogHandler(e,`query`),a=readLogHandler(e,`warning`);if(![t,n,r,i,a].every(e=>!e))return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,all:t,cache:n,error:r,query:i,warning:a})}function readLogHandler(e,n){let r=o(e,n);return r===!0||t(r)?r:void 0}const ne={connect:S,disconnect:C,savepoint:x,transaction:x},Q={clear:V,delete:B,get:R,invalidate:H,revalidate:y,set:z};function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[w]:t,[F]:n,...r===void 0?{}:{[T]:r}}}function createCorrelationAttributes(e){let t=e?.correlationId;return t===void 0?{}:{[I]:t}}function createCacheSpanOptions(e,t){if(t.kind===`cache-backend`)return{name:Q[t.boundary],attributes:{[U]:t.driverName}};let{driverName:n,read:r,ttl:i}=t;return{name:Q[e],attributes:{...n===void 0?{}:{[U]:n},...i===void 0?{}:{[G]:String(i)},...r===void 0?{}:{...createDriverAttributes(r.identity),[E]:r.model,[D]:r.operation},...createCorrelationAttributes(t.context)},...r===void 0?{}:{root:!0}}}function presentCacheOutcome(e,t){let{error:n}=t;return Object.freeze({timestamp:new Date(t.at),model:e?.model,operation:e?.operation,correlationId:e?.correlationId,error:n instanceof Error?u(n):void 0,meta:Object.freeze({event:t.event,status:t.status})})}function createOperationSpanOptions(e){let{collection:t}=e;return{name:y,attributes:{...createDriverAttributes(e.identity),...t===void 0?{}:{[E]:t},[D]:e.requestedOperation,...createCorrelationAttributes(e.context)}}}function createOperationErrorLogEvent(e,t,n,r,i){return Object.freeze({timestamp:new Date(r),error:u(n),model:e.model,operation:e.operation,correlationId:t,duration:i})}function readChannelDisclosure(e){return e&&e!==!0?e:p}function createContextAttributes(e,t){let{model:n,operation:i,correlationId:a}=t;return{...createDriverAttributes(r(e)),...n?{[E]:n}:{},...i?{[D]:i}:{},...a?{[I]:a}:{}}}function createStatementSpanOptions(e,t){let{includeParams:n,includeSql:r}=readChannelDisclosure(e);return{name:b,attributes:createContextAttributes(t.driver,t.context),...r||n?{sql:{...r?{query:t.sql}:{},...n?{params:t.params}:{}}}:{}}}function createLifecycleSpanOptions(e){return{name:ne[e.boundary],attributes:createContextAttributes(e.driver,e.context)}}function createStatementLogEvent(e,t,n){let{context:r,endedAt:i,failure:a}=e,o=readChannelDisclosure(n);return Object.freeze({timestamp:new Date(i),duration:i-t,model:r.model,operation:r.operation,correlationId:r.correlationId,sql:o.includeSql?e.sql:void 0,params:o.includeParams?e.params:void 0,error:a===void 0?void 0:u(a,o)})}const $=new WeakMap;function instrumentation(e){let t=createInstrumentationContext(e),n=Object.freeze({observesLifecycle:t.config.tracing!==void 0||t.config.logging!==void 0,...t.config.tracing===void 0?{}:{prewarm:()=>prewarmTracer(t.tracer)},diagnostics:t.config.diagnostics,wants:e=>wants(t,e),warn:e=>warn(t,e)}),r=function officialInstrumentationObserver(){};return $.set(n,t),ee(r,n,(e,n)=>observeOfficialInstrumentation(t,e,n)),Object.freeze({name:i,observe:r})}function wants(e,t){switch(t){case`operation`:return traces(e,y);case`statement`:return traces(e,b);case`transaction`:case`savepoint`:return traces(e,x);case`connect`:return traces(e,S);case`disconnect`:return traces(e,C);case`cache`:return e.config.tracing!==void 0;case`cache-outcomes`:return logs(e,`cache`);case`query-log`:return logs(e,`query`);case`error-log`:return logs(e,`error`);default:return disclosesParameters(e)}}function traces(e,t){return e.config.tracing!==void 0&&shouldTraceSpan(e.tracer,t)}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function disclosesParameters(e){let{logging:t,tracing:n}=e.config;return t!==void 0&&t!==!0&&t.includeParams===!0&&(logs(e,`query`)||logs(e,`error`))?!0:n!==void 0&&n!==!0&&n.includeParams===!0&&shouldTraceSpan(e.tracer,b)}function warn(e,t){let n=e.logger;return n?.isLevelEnabled(`warning`)===!0?(n.warn({timestamp:new Date,model:t.model,operation:t.operation,correlationId:t.correlationId,meta:{notice:t.message}}),!0):!1}function observeOfficialInstrumentation(e,t,n){let r=g(t);if(t.kind===`cache`&&(r?.kind===`cache`||r?.kind===`cache-backend`))return observeCacheInstrumentation(e,t.operation,t,r,n);if(r?.kind===`statement`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,wants(e,`statement`)?createStatementSpanOptions(e.config.tracing,n):void 0,()=>observeStatementCompletion(t,i,n.startedAt)))}if(r?.kind===`driver-lifecycle`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,createLifecycleSpanOptions(n),()=>observeLifecycleCompletion(i,t)))}if(r?.kind!==`operation`)return n();let i=r.context.correlationId,observeCompletion=()=>n().then(n=>{let a=_(t);if(a?.kind===`operation`){let{failure:t,readCacheOutcomes:o}=a;if(o!==void 0)for(let t of o())e.logger?.cache(presentCacheOutcome(r.context,t));t!==void 0&&a.skipLog!==!0&&e.logger?.error(createOperationErrorLogEvent(r,i,t,a.endedAt,n.durationMs))}if(n.status===`failure`)throw createObservedFailure(a?.kind===`operation`?a.failure:void 0)});return e.config.tracing===void 0?observeCompletion():e.tracer.startActiveSpan(createOperationSpanOptions(r),observeCompletion)}function observeCacheInstrumentation(e,t,n,r,i){let{logger:a,tracer:o}=e,s=wants(e,`cache`),c=r.kind===`cache`?r.context:void 0,l=r.kind===`cache`&&wants(e,`cache-outcomes`),u=Date.now(),observeCompletion=async e=>{l&&t===`revalidate`&&a?.cache(presentCacheOutcome(c,{event:`revalidate`,status:`start`,at:u}));let r=await i(),o=_(n);if(o?.kind===`cache`&&(s&&o.result!==void 0&&setSpanAttributes(e,{[W]:o.result}),l&&o.outcomes!==void 0))for(let e of o.outcomes)a?.cache(presentCacheOutcome(c,e));if(r.status===`failure`)throw createObservedFailure()};return s?o.startActiveSpan(createCacheSpanOptions(t,r),observeCompletion):observeCompletion()}async function presentDispatch(e,t,n,r){if(n===void 0)return t(),r();try{return await e.tracer.startActiveSpan(n,()=>(t(),r()))}finally{t()}}async function observeStatementCompletion(e,t,n){let r=await t,i=_(e);if(i?.kind===`statement`&&i.skipLog!==!0){let e=$.get(i.capability),t=createStatementLogEvent(i,n,e?.config.logging);i.failure===void 0?e?.logger?.query(t):e?.logger?.error(t)}if(r.status===`failure`&&!(i?.kind===`statement`&&i.recovered))throw createObservedFailure(i?.kind===`statement`?i.failure:void 0)}async function observeLifecycleCompletion(e,t){let n=await e,r=t&&_(t);if(n.status===`failure`)throw createObservedFailure(r?.kind===`driver-lifecycle`?r.failure:void 0)}function createObservedFailure(e){if(e)return u(e);let t=Error(`Operation failed`);return t.stack=void 0,t}export{U as ATTR_CACHE_DRIVER,W as ATTR_CACHE_RESULT,G as ATTR_CACHE_TTL,A as ATTR_DB_BATCH_SIZE,E as ATTR_DB_COLLECTION,F as ATTR_DB_DRIVER,T as ATTR_DB_NAMESPACE,D as ATTR_DB_OPERATION_NAME,L as ATTR_DB_QUERY_PARAMETER_PREFIX,k as ATTR_DB_QUERY_SUMMARY,O as ATTR_DB_QUERY_TEXT,N as ATTR_DB_ROWS_RETURNED,w as ATTR_DB_SYSTEM,P as ATTR_ERROR_TYPE,j as ATTR_SERVER_ADDRESS,M as ATTR_SERVER_PORT,I as ATTR_VIBORM_CORRELATION_ID,V as SPAN_CACHE_CLEAR,B as SPAN_CACHE_DELETE,R as SPAN_CACHE_GET,H as SPAN_CACHE_INVALIDATE,z as SPAN_CACHE_SET,S as SPAN_CONNECT,C as SPAN_DISCONNECT,b as SPAN_EXECUTE,y as SPAN_OPERATION,x as SPAN_TRANSACTION,instrumentation};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,s as n}from"./value-guards-CK9guf2Z.mjs";import{f as r,t as i}from"./chain-BQoDfo80.mjs";import{C as a,D as o,E as s,S as c,T as l,g as u,m as d,p as f,s as p,x as m,y as h}from"./base-wlv81COV.mjs";import{c as g,s as _,u as ee}from"./observation-BcT8Cs3d.mjs";import{t as te}from"./version-WvqPqZJ4.mjs";const v=new Set([`deprecation`,`event`,`notice`,`status`]);function sanitizeLogMetadata(e,t){return f(e,v,t,!0)}function prettyLog(e){let t=e.timestamp.toISOString(),r=e.duration===void 0?``:`${e.duration}ms`,i=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,i||`query`,r].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,n(e.meta?.event)?e.meta.event:`unknown`,n(e.meta?.status)?`(${e.meta.status})`:``);break;case`warning`:console.warn(`[WARN]`,t,i,formatDiagnostic(e.meta));break;case`error`:console.error(`[ERROR]`,t,i,r),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function formatDiagnostic(e){return e===void 0?``:String(JSON.stringify(e))}function getHandler(e,t){let n=e[t];return n===void 0?e.all:n}function createLogger(e){let t=Object.freeze({includeParams:e.includeParams===!0,includeSql:e.includeSql===!0}),n=Object.freeze({cache:getHandler(e,`cache`),error:getHandler(e,`error`),query:getHandler(e,`query`),warning:getHandler(e,`warning`)});function sanitizeEvent(e,n){let r=t.includeParams&&e.params?d(e.params,t):void 0;return{level:n,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:t.includeSql?e.sql:void 0,params:r,error:e.error?u(e.error,t):void 0,meta:e.meta?sanitizeLogMetadata(e.meta,t):void 0}}function emit(e,t){try{let r=n[t];if(!r)return;let i=sanitizeEvent(e,t),defaultLog=()=>{try{prettyLog(i)}catch{}};r===!0?defaultLog():Promise.resolve(r(i,defaultLog)).catch(()=>void 0)}catch{}}return Object.freeze({log(e){emit(e,e.level)},query(e){emit(e,`query`)},cache(e){emit(e,`cache`)},warn(e){emit(e,`warning`)},error(e){emit(e,`error`)},isLevelEnabled(e){return n[e]!==void 0}})}const y=`viborm.operation`,b=`viborm.execute`,x=`viborm.transaction`,S=`viborm.connect`,C=`viborm.disconnect`,w=`db.system.name`,T=`db.namespace`,E=`db.collection.name`,D=`db.operation.name`,O=`db.query.text`,k=`db.query.summary`,A=`db.operation.batch.size`,j=`server.address`,M=`server.port`,N=`db.response.returned_rows`,P=`error.type`,F=`db.system.driver`,I=`viborm.correlation.id`,L=`db.query.parameter`,R=`viborm.cache.get`,z=`viborm.cache.set`,B=`viborm.cache.delete`,V=`viborm.cache.clear`,H=`viborm.cache.invalidate`,U=`cache.driver`,W=`cache.result`,G=`cache.ttl`,K={SpanStatusCode:{OK:1,ERROR:2}},q=te,J=Symbol(`viborm.shouldTraceSpan`),Y=new WeakMap,X=new WeakSet,Z={async startActiveSpan(e,t){return t()},isEnabled(){return!1}};Object.defineProperty(Z,J,{value:()=>!1}),Object.freeze(Z);function createTracerWrapper(e){let t=Object.freeze((e?.ignoreSpanTypes??[]).map(e=>n(e)?e:new RegExp(e.source,e.flags))),r=e?.includeSql===!0,i=e?.includeParams===!0;function shouldIgnoreSpan(e){return t.some(t=>n(t)?t===e:new RegExp(t.source,t.flags).test(e))}function buildAttributes(e){let t={...e.attributes};if(e.sql&&(r&&e.sql.query!==void 0&&(t[O]=e.sql.query),i&&e.sql.params)){let n=d(e.sql.params,{includeParams:!0,includeSql:r});for(let e=0;e<n.length;e++){let r=n[e];t[`${L}.${e}`]=formatSanitizedSpanParameter(r)}}return t}function presentThrough(e){return{async startActiveSpan(t,n){if(shouldIgnoreSpan(t.name))return n();let r=createExecution(n,K);try{let n=buildAttributes(t);Promise.resolve(e.startActiveSpan(t.name,e=>(setSpanAttributes(e,n),r(e)))).catch(()=>void 0)}catch{}return r()},isEnabled(){return!0}}}function autoDetect(){let e=null,t=null,n=!1;async function tryLoadOtel(){try{return e=await import(`@opentelemetry/api`),e}catch{return null}}function getTracer(e){return t||=e.trace.getTracer(`viborm`,q),t}let r=tryLoadOtel().then(e=>(n=!0,e)),i={async startActiveSpan(t,i){if(n||await r,!e||shouldIgnoreSpan(t.name))return i();let a,o;try{let n=buildAttributes(t),r=t.kind??e.SpanKind.INTERNAL,i=t.root?e.ROOT_CONTEXT:e.context.active();a=getTracer(e).startSpan(t.name,{kind:r,attributes:n},i),o=e.trace.setSpan(i,a)}catch{return i()}let s=createExecution(i,e);try{Promise.resolve(e.context.with(o,()=>s(a))).catch(()=>void 0)}catch{}return s(a)},isEnabled(){return e!==null}},a=r.then(()=>void 0);return Y.set(i,a),a.then(()=>Y.delete(i)),i}let a=e?.tracer,o=a===void 0?autoDetect():presentThrough(a);return Object.defineProperty(o,J,{value:e=>!shouldIgnoreSpan(e)}),Object.freeze(o)}function createExecution(e,t){let n=new Set,r,i,settle=(e,a)=>{r=e,i=a;for(let r of n)endSpan(r,e,t,a)},a,o=!1;return s=>{if(s!==void 0&&(n.add(s),r!==void 0&&endSpan(s,r,t,i)),a)return a;if(o)return Promise.reject(createTraceError());o=!0;try{return a=new Promise((t,n)=>{try{Promise.resolve(e(s)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),n(e)})}catch(e){settle(!0,e),n(e)}}),a}finally{o=!1}}}function endSpan(e,t,n,r){if(!X.has(e)){if(X.add(e),t){let t=c(r)?h(r):void 0,i=typeof t?.name==`string`?t.name:`Error`;safely(()=>e.setAttribute(`error.type`,i));let a=t?.code;typeof a==`string`&&safely(()=>e.setAttribute(`viborm.error.code`,a));let o=t?.meta;if(typeof o==`object`&&o&&`providerSqlState`in o&&typeof o.providerSqlState==`string`){let t=o.providerSqlState;safely(()=>e.setAttribute(`db.response.sqlstate`,t))}safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let s=createTraceError();s.name=i,safely(()=>e.recordException?.(s))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function prewarmTracer(e){return Y.get(e)}function shouldTraceSpan(e,t){try{let n=Reflect.get(e,J);return typeof n!=`function`||n(t)!==!1}catch{return!0}}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function formatSanitizedSpanParameter(e){return n(e)?e:String(JSON.stringify(e))}function getNoopTracer(){return Z}function createInstrumentationContext(e){let t=snapshotInstrumentationConfig(e),n;if(t.tracing){let e=t.tracing===!0?{}:t.tracing;n=createTracerWrapper({includeSql:e.includeSql,includeParams:e.includeParams,ignoreSpanTypes:e.ignoreSpanTypes,tracer:e.tracer})}else n=getNoopTracer();let r={config:t,tracer:n};return t.logging&&(r.logger=createLogger(t.logging===!0?{all:!0}:t.logging)),Object.freeze(r)}function snapshotInstrumentationConfig(e){let t=snapshotDisclosure(o(e,`diagnostics`)),n=o(e,`tracing`),r=o(e,`logging`),i=n===!0?!0:a(n)?snapshotTracingConfig(n):void 0,s=r===!0?!0:a(r)?snapshotLoggingConfig(r):void 0;return Object.freeze({diagnostics:t,tracing:i,logging:s})}function snapshotDisclosure(e){return Object.freeze({includeParams:a(e)&&o(e,`includeParams`)===!0,includeSql:a(e)&&o(e,`includeSql`)===!0,includeProviderDetails:a(e)&&o(e,`includeProviderDetails`)===!0,includeCallsite:a(e)&&o(e,`includeCallsite`)===!0})}function snapshotTracingConfig(e){let t=snapshotIgnorePatterns(o(e,`ignoreSpanTypes`)),n=o(e,`tracer`);return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,...t.length>0?{ignoreSpanTypes:t}:{},...isPlatformTracer(n)?{tracer:n}:{}})}function isPlatformTracer(e){return a(e)&&t(o(e,`startActiveSpan`))}function snapshotIgnorePatterns(e){if(!m(e))return Object.freeze([]);let t=[],r=Math.min(l(e),128);for(let i=0;i<r;i+=1){let r=s(e,String(i));if(!(r&&`value`in r))continue;let a=r.value;if(n(a)){t.push(a);continue}try{a instanceof RegExp&&t.push(Object.freeze(new RegExp(a.source,a.flags)))}catch{}}return Object.freeze(t)}function snapshotLoggingConfig(e){let t=readLogHandler(e,`all`),n=readLogHandler(e,`cache`),r=readLogHandler(e,`error`),i=readLogHandler(e,`query`),a=readLogHandler(e,`warning`);if(![t,n,r,i,a].every(e=>!e))return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,all:t,cache:n,error:r,query:i,warning:a})}function readLogHandler(e,n){let r=o(e,n);return r===!0||t(r)?r:void 0}const ne={connect:S,disconnect:C,savepoint:x,transaction:x},Q={clear:V,delete:B,get:R,invalidate:H,revalidate:y,set:z};function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[w]:t,[F]:n,...r===void 0?{}:{[T]:r}}}function createCorrelationAttributes(e){let t=e?.correlationId;return t===void 0?{}:{[I]:t}}function createCacheSpanOptions(e,t){if(t.kind===`cache-backend`)return{name:Q[t.boundary],attributes:{[U]:t.driverName}};let{driverName:n,read:r,ttl:i}=t;return{name:Q[e],attributes:{...n===void 0?{}:{[U]:n},...i===void 0?{}:{[G]:String(i)},...r===void 0?{}:{...createDriverAttributes(r.identity),[E]:r.model,[D]:r.operation},...createCorrelationAttributes(t.context)},...r===void 0?{}:{root:!0}}}function presentCacheOutcome(e,t){let{error:n}=t;return Object.freeze({timestamp:new Date(t.at),model:e?.model,operation:e?.operation,correlationId:e?.correlationId,error:n instanceof Error?u(n):void 0,meta:Object.freeze({event:t.event,status:t.status})})}function createOperationSpanOptions(e){let{collection:t}=e;return{name:y,attributes:{...createDriverAttributes(e.identity),...t===void 0?{}:{[E]:t},[D]:e.requestedOperation,...createCorrelationAttributes(e.context)}}}function createOperationErrorLogEvent(e,t,n,r,i){return Object.freeze({timestamp:new Date(r),error:u(n),model:e.model,operation:e.operation,correlationId:t,duration:i})}function readChannelDisclosure(e){return e&&e!==!0?e:p}function createContextAttributes(e,t){let{model:n,operation:i,correlationId:a}=t;return{...createDriverAttributes(r(e)),...n?{[E]:n}:{},...i?{[D]:i}:{},...a?{[I]:a}:{}}}function createStatementSpanOptions(e,t){let{includeParams:n,includeSql:r}=readChannelDisclosure(e);return{name:b,attributes:createContextAttributes(t.driver,t.context),...r||n?{sql:{...r?{query:t.sql}:{},...n?{params:t.params}:{}}}:{}}}function createLifecycleSpanOptions(e){return{name:ne[e.boundary],attributes:createContextAttributes(e.driver,e.context)}}function createStatementLogEvent(e,t,n){let{context:r,endedAt:i,failure:a}=e,o=readChannelDisclosure(n);return Object.freeze({timestamp:new Date(i),duration:i-t,model:r.model,operation:r.operation,correlationId:r.correlationId,sql:o.includeSql?e.sql:void 0,params:o.includeParams?e.params:void 0,error:a===void 0?void 0:u(a,o)})}const $=new WeakMap;function instrumentation(e){let t=createInstrumentationContext(e),n=Object.freeze({observesLifecycle:t.config.tracing!==void 0||t.config.logging!==void 0,...t.config.tracing===void 0?{}:{prewarm:()=>prewarmTracer(t.tracer)},diagnostics:t.config.diagnostics,wants:e=>wants(t,e),warn:e=>warn(t,e)}),r=function officialInstrumentationObserver(){};return $.set(n,t),ee(r,n,(e,n)=>observeOfficialInstrumentation(t,e,n)),Object.freeze({name:i,observe:r})}function wants(e,t){switch(t){case`operation`:return traces(e,y);case`statement`:return traces(e,b);case`transaction`:case`savepoint`:return traces(e,x);case`connect`:return traces(e,S);case`disconnect`:return traces(e,C);case`cache`:return e.config.tracing!==void 0;case`cache-outcomes`:return logs(e,`cache`);case`query-log`:return logs(e,`query`);case`error-log`:return logs(e,`error`);default:return disclosesParameters(e)}}function traces(e,t){return e.config.tracing!==void 0&&shouldTraceSpan(e.tracer,t)}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function disclosesParameters(e){let{logging:t,tracing:n}=e.config;return t!==void 0&&t!==!0&&t.includeParams===!0&&(logs(e,`query`)||logs(e,`error`))?!0:n!==void 0&&n!==!0&&n.includeParams===!0&&shouldTraceSpan(e.tracer,b)}function warn(e,t){let n=e.logger;return n?.isLevelEnabled(`warning`)===!0?(n.warn({timestamp:new Date,model:t.model,operation:t.operation,correlationId:t.correlationId,meta:{notice:t.message}}),!0):!1}function observeOfficialInstrumentation(e,t,n){let r=g(t);if(t.kind===`cache`&&(r?.kind===`cache`||r?.kind===`cache-backend`))return observeCacheInstrumentation(e,t.operation,t,r,n);if(r?.kind===`statement`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,wants(e,`statement`)?createStatementSpanOptions(e.config.tracing,n):void 0,()=>observeStatementCompletion(t,i,n.startedAt)))}if(r?.kind===`driver-lifecycle`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,createLifecycleSpanOptions(n),()=>observeLifecycleCompletion(i,t)))}if(r?.kind!==`operation`)return n();let i=r.context.correlationId,observeCompletion=()=>n().then(n=>{let a=_(t);if(a?.kind===`operation`){let{failure:t,readCacheOutcomes:o}=a;if(o!==void 0)for(let t of o())e.logger?.cache(presentCacheOutcome(r.context,t));t!==void 0&&a.skipLog!==!0&&e.logger?.error(createOperationErrorLogEvent(r,i,t,a.endedAt,n.durationMs))}if(n.status===`failure`)throw createObservedFailure(a?.kind===`operation`?a.failure:void 0)});return e.config.tracing===void 0?observeCompletion():e.tracer.startActiveSpan(createOperationSpanOptions(r),observeCompletion)}function observeCacheInstrumentation(e,t,n,r,i){let{logger:a,tracer:o}=e,s=wants(e,`cache`),c=r.kind===`cache`?r.context:void 0,l=r.kind===`cache`&&wants(e,`cache-outcomes`),u=Date.now(),observeCompletion=async e=>{l&&t===`revalidate`&&a?.cache(presentCacheOutcome(c,{event:`revalidate`,status:`start`,at:u}));let r=await i(),o=_(n);if(o?.kind===`cache`&&(s&&o.result!==void 0&&setSpanAttributes(e,{[W]:o.result}),l&&o.outcomes!==void 0))for(let e of o.outcomes)a?.cache(presentCacheOutcome(c,e));if(r.status===`failure`)throw createObservedFailure()};return s?o.startActiveSpan(createCacheSpanOptions(t,r),observeCompletion):observeCompletion()}async function presentDispatch(e,t,n,r){if(n===void 0)return t(),r();try{return await e.tracer.startActiveSpan(n,()=>(t(),r()))}finally{t()}}async function observeStatementCompletion(e,t,n){let r=await t,i=_(e);if(i?.kind===`statement`&&i.skipLog!==!0){let e=$.get(i.capability),t=createStatementLogEvent(i,n,e?.config.logging);i.failure===void 0?e?.logger?.query(t):e?.logger?.error(t)}if(r.status===`failure`&&!(i?.kind===`statement`&&i.recovered))throw createObservedFailure(i?.kind===`statement`?i.failure:void 0)}async function observeLifecycleCompletion(e,t){let n=await e,r=t&&_(t);if(n.status===`failure`)throw createObservedFailure(r?.kind===`driver-lifecycle`?r.failure:void 0)}function createObservedFailure(e){if(e)return u(e);let t=Error(`Operation failed`);return t.stack=void 0,t}export{U as ATTR_CACHE_DRIVER,W as ATTR_CACHE_RESULT,G as ATTR_CACHE_TTL,A as ATTR_DB_BATCH_SIZE,E as ATTR_DB_COLLECTION,F as ATTR_DB_DRIVER,T as ATTR_DB_NAMESPACE,D as ATTR_DB_OPERATION_NAME,L as ATTR_DB_QUERY_PARAMETER_PREFIX,k as ATTR_DB_QUERY_SUMMARY,O as ATTR_DB_QUERY_TEXT,N as ATTR_DB_ROWS_RETURNED,w as ATTR_DB_SYSTEM,P as ATTR_ERROR_TYPE,j as ATTR_SERVER_ADDRESS,M as ATTR_SERVER_PORT,I as ATTR_VIBORM_CORRELATION_ID,V as SPAN_CACHE_CLEAR,B as SPAN_CACHE_DELETE,R as SPAN_CACHE_GET,H as SPAN_CACHE_INVALIDATE,z as SPAN_CACHE_SET,S as SPAN_CONNECT,C as SPAN_DISCONNECT,b as SPAN_EXECUTE,y as SPAN_OPERATION,x as SPAN_TRANSACTION,instrumentation};
2
2
  //# sourceMappingURL=instrumentation.mjs.map