viborm 1.14.2 → 1.15.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 (272) hide show
  1. package/dist/{adapter-namespace-DaRiTIIf.mjs → adapter-namespace-DD-BQ2Wk.mjs} +2 -2
  2. package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DD-BQ2Wk.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +15 -3
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{args-764KdWMr.mjs → args-BvA37zBZ.mjs} +2 -2
  6. package/dist/{args-764KdWMr.mjs.map → args-BvA37zBZ.mjs.map} +1 -1
  7. package/dist/{batch-refs-C-gx7A4-.mjs → batch-refs-BmEpMmjI.mjs} +2 -2
  8. package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-BmEpMmjI.mjs.map} +1 -1
  9. package/dist/bun-sql.d.mts +1 -1
  10. package/dist/bun-sql.mjs +1 -1
  11. package/dist/bun-sqlite.d.mts +1 -1
  12. package/dist/bun-sqlite.mjs +1 -1
  13. package/dist/cache/cloudflare-kv.d.mts +1 -1
  14. package/dist/cache/cloudflare-kv.mjs +1 -1
  15. package/dist/cache/memory.d.mts +1 -1
  16. package/dist/cache/memory.mjs +1 -1
  17. package/dist/cache.d.mts +2 -2
  18. package/dist/cache.mjs +1 -1
  19. package/dist/{call-Cz8XUmrl.mjs → call-BWFI7-vU.mjs} +2 -2
  20. package/dist/{call-Cz8XUmrl.mjs.map → call-BWFI7-vU.mjs.map} +1 -1
  21. package/dist/cli.mjs +2 -2
  22. package/dist/cli.mjs.map +1 -1
  23. package/dist/client-CVCC-D1j.mjs +2 -0
  24. package/dist/client-CVCC-D1j.mjs.map +1 -0
  25. package/dist/{client-CRxfhw2y.d.mts → client-DZ39sYy2.d.mts} +2 -2
  26. package/dist/{client-y7TV0PRZ.mjs → client-DtPTegtA.mjs} +2 -2
  27. package/dist/{client-y7TV0PRZ.mjs.map → client-DtPTegtA.mjs.map} +1 -1
  28. package/dist/client.d.mts +3 -3
  29. package/dist/client.mjs +1 -1
  30. package/dist/config.d.mts +1 -1
  31. package/dist/config.mjs +1 -1
  32. package/dist/{confine-DqFBTUw6.mjs → confine-BGGv2du0.mjs} +2 -2
  33. package/dist/{confine-DqFBTUw6.mjs.map → confine-BGGv2du0.mjs.map} +1 -1
  34. package/dist/{coordination-6qZHx_kl.mjs → coordination-BY6Np3xV.mjs} +2 -2
  35. package/dist/{coordination-6qZHx_kl.mjs.map → coordination-BY6Np3xV.mjs.map} +1 -1
  36. package/dist/d1.d.mts +1 -1
  37. package/dist/d1.mjs +1 -1
  38. package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-D62c-uC6.d.mts} +604 -473
  39. package/dist/{datetime-physical-codec-Dj-APo9f.mjs → datetime-physical-codec-BS2T81sD.mjs} +2 -2
  40. package/dist/{datetime-physical-codec-Dj-APo9f.mjs.map → datetime-physical-codec-BS2T81sD.mjs.map} +1 -1
  41. package/dist/{defaults-DwOHWI_M.mjs → defaults-CrtGVdEC.mjs} +2 -2
  42. package/dist/{defaults-DwOHWI_M.mjs.map → defaults-CrtGVdEC.mjs.map} +1 -1
  43. package/dist/{document-BVTQ-cF-.d.mts → document-o5Bd5ZoJ.d.mts} +1 -1
  44. package/dist/{driver-BBEmaJZy.d.mts → driver-0cdCF_KD.d.mts} +1 -1
  45. package/dist/{driver-BGVcgnIX.mjs → driver-D1grnHEr.mjs} +2 -2
  46. package/dist/{driver-BGVcgnIX.mjs.map → driver-D1grnHEr.mjs.map} +1 -1
  47. package/dist/{driver-BIXhOH2_.mjs → driver-Df88hu4U.mjs} +2 -2
  48. package/dist/{driver-BIXhOH2_.mjs.map → driver-Df88hu4U.mjs.map} +1 -1
  49. package/dist/driver.d.mts +1 -1
  50. package/dist/driver.mjs +1 -1
  51. package/dist/durable-object.d.mts +1 -1
  52. package/dist/durable-object.mjs +1 -1
  53. package/dist/error-mapping-DIRlrmDK.mjs +2 -0
  54. package/dist/error-mapping-DIRlrmDK.mjs.map +1 -0
  55. package/dist/every-BHEmfLOW.mjs +2 -0
  56. package/dist/{every-tOgQmaIE.mjs.map → every-BHEmfLOW.mjs.map} +1 -1
  57. package/dist/execution-context-VMQm-9CH.mjs +2 -0
  58. package/dist/execution-context-VMQm-9CH.mjs.map +1 -0
  59. package/dist/{exports-COCJ8f2f.d.mts → exports-Bzvtum3F.d.mts} +1 -1
  60. package/dist/geo-area-codec-BDvW7IH-.mjs +2 -0
  61. package/dist/{geo-area-codec-mHrM3b9A.mjs.map → geo-area-codec-BDvW7IH-.mjs.map} +1 -1
  62. package/dist/{hydration-A3zffFWP.mjs → hydration-D7U8HACL.mjs} +2 -2
  63. package/dist/{hydration-A3zffFWP.mjs.map → hydration-D7U8HACL.mjs.map} +1 -1
  64. package/dist/{identifier-conversion-DHYPTgzr.mjs → identifier-conversion-Ci_iaJ0b.mjs} +2 -2
  65. package/dist/{identifier-conversion-DHYPTgzr.mjs.map → identifier-conversion-Ci_iaJ0b.mjs.map} +1 -1
  66. package/dist/identifiers-BTCfD5ic.mjs +2 -0
  67. package/dist/identifiers-BTCfD5ic.mjs.map +1 -0
  68. package/dist/index.d.mts +2 -2
  69. package/dist/index.mjs +1 -1
  70. package/dist/instrumentation.d.mts +1 -1
  71. package/dist/instrumentation.mjs +1 -1
  72. package/dist/{introspect-Bm6xnXcG.mjs → introspect-C4T5gt9O.mjs} +2 -2
  73. package/dist/{introspect-Bm6xnXcG.mjs.map → introspect-C4T5gt9O.mjs.map} +1 -1
  74. package/dist/{json-DgMc8-GU.mjs → json-CHdgejCt.mjs} +2 -2
  75. package/dist/{json-DgMc8-GU.mjs.map → json-CHdgejCt.mjs.map} +1 -1
  76. package/dist/judge-words-DpwxOfre.mjs +2 -0
  77. package/dist/judge-words-DpwxOfre.mjs.map +1 -0
  78. package/dist/{key-hxFFCKed.mjs → key-B3xgpu0M.mjs} +2 -2
  79. package/dist/{key-hxFFCKed.mjs.map → key-B3xgpu0M.mjs.map} +1 -1
  80. package/dist/{keys-BQxM4c_a.mjs → keys-1Z6WKrnE.mjs} +1 -1
  81. package/dist/{keys-BQxM4c_a.mjs.map → keys-1Z6WKrnE.mjs.map} +1 -1
  82. package/dist/{libsql-DuGR904j.mjs → libsql-DJRsCDT_.mjs} +2 -2
  83. package/dist/{libsql-DuGR904j.mjs.map → libsql-DJRsCDT_.mjs.map} +1 -1
  84. package/dist/libsql.d.mts +1 -1
  85. package/dist/libsql.mjs +1 -1
  86. package/dist/{memory-G4cSuc6A.mjs → memory-gjKMy3Ql.mjs} +2 -2
  87. package/dist/{memory-G4cSuc6A.mjs.map → memory-gjKMy3Ql.mjs.map} +1 -1
  88. package/dist/methods-part-DoTrY6b9.mjs +2 -0
  89. package/dist/methods-part-DoTrY6b9.mjs.map +1 -0
  90. package/dist/migrations/mysql.d.mts +4 -4
  91. package/dist/migrations/mysql.mjs +1 -1
  92. package/dist/migrations/postgres.d.mts +4 -4
  93. package/dist/migrations/postgres.mjs +1 -1
  94. package/dist/migrations/snowflake.d.mts +4 -4
  95. package/dist/migrations/snowflake.mjs +1 -1
  96. package/dist/migrations/sqlite.d.mts +4 -4
  97. package/dist/migrations/sqlite.mjs +1 -1
  98. package/dist/migrations/storage/durable-object.mjs +1 -1
  99. package/dist/migrations/storage/r2.mjs +1 -1
  100. package/dist/migrations/surrealdb.d.mts +4 -4
  101. package/dist/migrations/surrealdb.mjs +1 -1
  102. package/dist/migrations/tenant.d.mts +2 -2
  103. package/dist/migrations/tenant.mjs +1 -1
  104. package/dist/migrations.d.mts +4 -4
  105. package/dist/migrations.mjs +1 -1
  106. package/dist/{mysql-BNXWfTOo.mjs → mysql-BH0Z3PlH.mjs} +2 -2
  107. package/dist/{mysql-BNXWfTOo.mjs.map → mysql-BH0Z3PlH.mjs.map} +1 -1
  108. package/dist/mysql-adapter-B06Ve3ds.mjs +2 -0
  109. package/dist/mysql-adapter-B06Ve3ds.mjs.map +1 -0
  110. package/dist/mysql2.d.mts +1 -1
  111. package/dist/mysql2.mjs +1 -1
  112. package/dist/named-statements-Bdz2GD5R.d.mts +13 -0
  113. package/dist/named-statements-CMj1QEyw.mjs +2 -0
  114. package/dist/named-statements-CMj1QEyw.mjs.map +1 -0
  115. package/dist/{native-types-DgjMUikz.mjs → native-types-DspZ0Z5E.mjs} +2 -2
  116. package/dist/{native-types-DgjMUikz.mjs.map → native-types-DspZ0Z5E.mjs.map} +1 -1
  117. package/dist/neon-http.d.mts +1 -1
  118. package/dist/neon-http.mjs +1 -1
  119. package/dist/{object-store-B_YMoW8u.d.mts → object-store-D5x-Yf7w.d.mts} +3 -3
  120. package/dist/{object-store-DS0F0yZX.mjs → object-store-WIE0DGGG.mjs} +1 -1
  121. package/dist/{object-store-DS0F0yZX.mjs.map → object-store-WIE0DGGG.mjs.map} +1 -1
  122. package/dist/{on-ylYaKuRu.mjs → on-DvrfHGje.mjs} +2 -2
  123. package/dist/{on-ylYaKuRu.mjs.map → on-DvrfHGje.mjs.map} +1 -1
  124. package/dist/on.d.mts +1 -1
  125. package/dist/on.mjs +1 -1
  126. package/dist/ordering/keys.mjs +1 -1
  127. package/dist/ordering.d.mts +1 -1
  128. package/dist/ordering.mjs +1 -1
  129. package/dist/pending-operation-Dq4rv-Ml.mjs +2 -0
  130. package/dist/pending-operation-Dq4rv-Ml.mjs.map +1 -0
  131. package/dist/permissions.d.mts +1 -1
  132. package/dist/permissions.mjs +1 -1
  133. package/dist/pg.d.mts +27 -1
  134. package/dist/pg.mjs +1 -1
  135. package/dist/pg.mjs.map +1 -1
  136. package/dist/pglite.d.mts +1 -1
  137. package/dist/pglite.mjs +1 -1
  138. package/dist/{physical-CeE2nYmI.mjs → physical-wboFLAg9.mjs} +2 -2
  139. package/dist/{physical-CeE2nYmI.mjs.map → physical-wboFLAg9.mjs.map} +1 -1
  140. package/dist/planetscale.d.mts +1 -1
  141. package/dist/planetscale.mjs +1 -1
  142. package/dist/{planner-DHjdvjwk.d.mts → planner-Ckoxeruk.d.mts} +1 -1
  143. package/dist/{postgres-CDdh5dSP.mjs → postgres-DQ_pO0hi.mjs} +2 -2
  144. package/dist/{postgres-CDdh5dSP.mjs.map → postgres-DQ_pO0hi.mjs.map} +1 -1
  145. package/dist/{postgres-adapter-axapXX8d.mjs → postgres-adapter-Byp7Zpop.mjs} +2 -2
  146. package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-Byp7Zpop.mjs.map} +1 -1
  147. package/dist/postgres-adapter-Ia4u0-Ht.mjs +2 -0
  148. package/dist/postgres-adapter-Ia4u0-Ht.mjs.map +1 -0
  149. package/dist/postgres-result-CiS5OWp1.mjs +2 -0
  150. package/dist/postgres-result-CiS5OWp1.mjs.map +1 -0
  151. package/dist/postgres.d.mts +17 -1
  152. package/dist/postgres.mjs +1 -1
  153. package/dist/postgres.mjs.map +1 -1
  154. package/dist/{provider-limits-Ccsb8PTb.mjs → provider-limits-CCOa4d1E.mjs} +2 -2
  155. package/dist/{provider-limits-Ccsb8PTb.mjs.map → provider-limits-CCOa4d1E.mjs.map} +1 -1
  156. package/dist/{provider-parameter-snapshot-BikrgKqI.mjs → provider-parameter-snapshot-C0ehKSAA.mjs} +2 -2
  157. package/dist/{provider-parameter-snapshot-BikrgKqI.mjs.map → provider-parameter-snapshot-C0ehKSAA.mjs.map} +1 -1
  158. package/dist/query-Cdy8E2jM.mjs +2 -0
  159. package/dist/query-Cdy8E2jM.mjs.map +1 -0
  160. package/dist/{query-inspection-BoG-yAln.mjs → query-inspection-C-T2ttRx.mjs} +2 -2
  161. package/dist/{query-inspection-BoG-yAln.mjs.map → query-inspection-C-T2ttRx.mjs.map} +1 -1
  162. package/dist/{raw-Dyq6Y6UX.mjs → raw-uaVIxHcE.mjs} +2 -2
  163. package/dist/{raw-Dyq6Y6UX.mjs.map → raw-uaVIxHcE.mjs.map} +1 -1
  164. package/dist/{relation-bound-ku_cMdye.mjs → relation-bound-BaU-LuuI.mjs} +1 -1
  165. package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-BaU-LuuI.mjs.map} +1 -1
  166. package/dist/{rule-words-ZIGm7cDm.mjs → rule-words-C4lXzgW2.mjs} +2 -2
  167. package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-C4lXzgW2.mjs.map} +1 -1
  168. package/dist/scalar-B9WizsvR.mjs +4 -0
  169. package/dist/scalar-B9WizsvR.mjs.map +1 -0
  170. package/dist/schema/introspect.d.mts +2 -2
  171. package/dist/schema/introspect.mjs +1 -1
  172. package/dist/schema/json.d.mts +2 -2
  173. package/dist/schema/json.mjs +1 -1
  174. package/dist/{schema-BYA-_bpk.mjs → schema-MB-pPNTO.mjs} +2 -2
  175. package/dist/schema-MB-pPNTO.mjs.map +1 -0
  176. package/dist/{schema-CFIaebgi.mjs → schema-TthAXPVP.mjs} +2 -2
  177. package/dist/{schema-CFIaebgi.mjs.map → schema-TthAXPVP.mjs.map} +1 -1
  178. package/dist/schema-introspection-wMVZowIF.mjs +6 -0
  179. package/dist/schema-introspection-wMVZowIF.mjs.map +1 -0
  180. package/dist/schema.d.mts +1 -1
  181. package/dist/schema.mjs +1 -1
  182. package/dist/select-assembly-SuVxJjps.mjs +2 -0
  183. package/dist/select-assembly-SuVxJjps.mjs.map +1 -0
  184. package/dist/{serializer-rBq3v1xr.mjs → serializer-B2kk7NAR.mjs} +5 -5
  185. package/dist/{serializer-rBq3v1xr.mjs.map → serializer-B2kk7NAR.mjs.map} +1 -1
  186. package/dist/{settled-BjyuA76m.mjs → settled-Dkk5w1vE.mjs} +2 -2
  187. package/dist/{settled-BjyuA76m.mjs.map → settled-Dkk5w1vE.mjs.map} +1 -1
  188. package/dist/{snowflake-UOCC820W.mjs → snowflake-6sBLJi34.mjs} +2 -2
  189. package/dist/{snowflake-UOCC820W.mjs.map → snowflake-6sBLJi34.mjs.map} +1 -1
  190. package/dist/snowflake.d.mts +2 -2
  191. package/dist/snowflake.mjs +1 -1
  192. package/dist/snowflake.mjs.map +1 -1
  193. package/dist/soft-delete.d.mts +1 -1
  194. package/dist/soft-delete.mjs +1 -1
  195. package/dist/{spans-XDUFeTzC.mjs → spans-BE-EjlZK.mjs} +1 -1
  196. package/dist/{spans-XDUFeTzC.mjs.map → spans-BE-EjlZK.mjs.map} +1 -1
  197. package/dist/sql-BGjAsoBE.mjs +2 -0
  198. package/dist/sql-BGjAsoBE.mjs.map +1 -0
  199. package/dist/{sql-Dl6nykFV.mjs → sql-CFxGrk3K.mjs} +2 -2
  200. package/dist/{sql-Dl6nykFV.mjs.map → sql-CFxGrk3K.mjs.map} +1 -1
  201. package/dist/{sql-BVZ8QefY.d.mts → sql-CXtSIPzy.d.mts} +11 -5
  202. package/dist/sql.d.mts +1 -1
  203. package/dist/sql.mjs +1 -1
  204. package/dist/{sqlite-adapter-Ad0d-m2t.mjs → sqlite-adapter-fIbNDvwO.mjs} +2 -2
  205. package/dist/{sqlite-adapter-Ad0d-m2t.mjs.map → sqlite-adapter-fIbNDvwO.mjs.map} +1 -1
  206. package/dist/{sqlite-utils-BRvbmlQ1.mjs → sqlite-utils-DcQct689.mjs} +2 -2
  207. package/dist/{sqlite-utils-BRvbmlQ1.mjs.map → sqlite-utils-DcQct689.mjs.map} +1 -1
  208. package/dist/sqlite3.d.mts +1 -1
  209. package/dist/sqlite3.mjs +1 -1
  210. package/dist/{standard-sql-qLcQyCtK.mjs → standard-sql-Bsf5nrla.mjs} +3 -3
  211. package/dist/standard-sql-Bsf5nrla.mjs.map +1 -0
  212. package/dist/surrealdb.d.mts +2 -2
  213. package/dist/surrealdb.mjs +1 -1
  214. package/dist/surrealdb.mjs.map +1 -1
  215. package/dist/{surrealql-C1dp1sWw.mjs → surrealql-DY7sgVnJ.mjs} +2 -2
  216. package/dist/{surrealql-C1dp1sWw.mjs.map → surrealql-DY7sgVnJ.mjs.map} +1 -1
  217. package/dist/{to-many-BybuKQM1.mjs → to-many-DiP6cOSQ.mjs} +2 -2
  218. package/dist/{to-many-BybuKQM1.mjs.map → to-many-DiP6cOSQ.mjs.map} +1 -1
  219. package/dist/{unit-BhHbZyuJ.mjs → unit-CSaAB0su.mjs} +2 -2
  220. package/dist/{unit-BhHbZyuJ.mjs.map → unit-CSaAB0su.mjs.map} +1 -1
  221. package/dist/{unit-words-CT0yeqfZ.mjs → unit-words-BGMVZ1MX.mjs} +2 -2
  222. package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BGMVZ1MX.mjs.map} +1 -1
  223. package/dist/{utils-CpAojrCj.mjs → utils-BLlgSQIo.mjs} +2 -2
  224. package/dist/{utils-CpAojrCj.mjs.map → utils-BLlgSQIo.mjs.map} +1 -1
  225. package/dist/validation-D0LG854o.mjs +2 -0
  226. package/dist/validation-D0LG854o.mjs.map +1 -0
  227. package/dist/validation.d.mts +1 -1
  228. package/dist/validation.mjs +1 -1
  229. package/dist/{validator-CZLW7aR3.mjs → validator-CDYlO9HV.mjs} +2 -2
  230. package/dist/{validator-CZLW7aR3.mjs.map → validator-CDYlO9HV.mjs.map} +1 -1
  231. package/dist/{values-B4aj1i1f.mjs → values-Byqn5wAh.mjs} +2 -2
  232. package/dist/{values-B4aj1i1f.mjs.map → values-Byqn5wAh.mjs.map} +1 -1
  233. package/dist/version-B_ZLWzLW.mjs +2 -0
  234. package/dist/{version-CXGIA82S.mjs.map → version-B_ZLWzLW.mjs.map} +1 -1
  235. package/package.json +35 -35
  236. package/dist/client-DRpX3-vw.mjs +0 -2
  237. package/dist/client-DRpX3-vw.mjs.map +0 -1
  238. package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
  239. package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
  240. package/dist/every-tOgQmaIE.mjs +0 -2
  241. package/dist/execution-context-BXpcbyPe.mjs +0 -2
  242. package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
  243. package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
  244. package/dist/identifiers-s00pGES8.mjs +0 -2
  245. package/dist/identifiers-s00pGES8.mjs.map +0 -1
  246. package/dist/judge-words-CzUyXtJ6.mjs +0 -2
  247. package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
  248. package/dist/methods-part-ZY0f2AV_.mjs +0 -2
  249. package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
  250. package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
  251. package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
  252. package/dist/pending-operation-C_eOFOBE.mjs +0 -2
  253. package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
  254. package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
  255. package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
  256. package/dist/postgres-result-DF6DmW3r.mjs +0 -2
  257. package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
  258. package/dist/query-BZVHfA0s.mjs +0 -2
  259. package/dist/query-BZVHfA0s.mjs.map +0 -1
  260. package/dist/scalar-BHCh7aUz.mjs +0 -4
  261. package/dist/scalar-BHCh7aUz.mjs.map +0 -1
  262. package/dist/schema-BYA-_bpk.mjs.map +0 -1
  263. package/dist/schema-introspection-D0f8cti4.mjs +0 -6
  264. package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
  265. package/dist/select-assembly-DVI7d3tf.mjs +0 -2
  266. package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
  267. package/dist/sql-3o4DOKm9.mjs +0 -2
  268. package/dist/sql-3o4DOKm9.mjs.map +0 -1
  269. package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
  270. package/dist/validation-CYaJ8ndO.mjs +0 -2
  271. package/dist/validation-CYaJ8ndO.mjs.map +0 -1
  272. package/dist/version-CXGIA82S.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"unit-words-CT0yeqfZ.mjs","names":["#source","origin","failure","statement","run","members","statements","settle","origin","driver"],"sources":["../src/extensions/unit-source.ts","../src/extensions/observation.ts","../src/drivers/driver-identity.ts","../src/extensions/unit-words.ts"],"sourcesContent":["/**\n * A unit of real work, as a handler receives it, and what its producer\n * already holds about it. The runner keeps the producer's record beside the\n * unit; each unit word (`text`, `parameters`, `driver`, …) reads that record\n * when it is called. A fact nobody reads is never computed, and a program\n * that imports no word carries none of their code.\n */\nimport type { DriverIdentitySource } from \"@drivers/driver-identity\";\nimport type { BatchQuery, QueryExecutionContext } from \"@drivers/types\";\nimport type { Sql } from \"@sql\";\nimport type { UnitContext, UnitKind, UnitOutcome } from \"./contract\";\nimport { callOf } from \"./origin\";\n\nexport type { UnitKind } from \"./contract\";\nexport type Unit = UnitContext;\nexport type UnitEnd = UnitOutcome;\ntype CommitCertainty = \"committed\" | \"may-have-committed\";\n\n/**\n * One handler around a unit. `next()` lets the unit run; the child starts\n * only then, at most once, and must be called. What the handler throws, or a\n * promise it returns that rejects, fails the call; the child's own failure\n * fails it first.\n */\nexport type UnitHandler = (\n unit: Unit,\n next: (sql?: Sql) => Promise<UnitEnd>\n) => unknown;\n\n/** Runs one statement in the transaction a unit opened, and gives its rows. */\nexport type TransactionStatementRunner = (\n statement: Sql\n) => Promise<readonly Record<string, unknown>[]>;\n\n/**\n * The producer's record of one unit: references it already held, never a\n * fact computed for a reader that may not come.\n */\nexport interface UnitSource {\n readonly kind: UnitKind;\n readonly operation?: string | undefined;\n readonly model?: string | undefined;\n /**\n * The trusted execution context: the chain, correlation, a recovered read.\n * An operation unit's is its call's own (`CallOrigin.of`), how a `run`\n * finds it.\n */\n readonly context?: QueryExecutionContext | undefined;\n /** The driver doing the work, read only by `driver(unit)`. */\n readonly driver?: DriverIdentitySource | undefined;\n /** operation: the SQL name of the model. */\n readonly table?: string | undefined;\n /** statement: the rendered text sent, a native batch's texts joined. */\n readonly sql?: string | undefined;\n /** statement: the parameters sent, as the driver detached them. */\n readonly params?: readonly unknown[] | undefined;\n /**\n * statement: the diagnostic snapshot of `params` the driver took (its\n * empty constant when it took none): what `parameters(u)` reads.\n */\n readonly shown?: readonly unknown[] | undefined;\n /** statement: a native batch's members, in order. */\n readonly batch?: readonly BatchQuery[] | undefined;\n /**\n * A logical statement under rewriting units: the statement as the earlier\n * ones left it (what `next(sql)` hands on replaces it).\n */\n statement?: Sql | undefined;\n /** How sure the child's commit is, read once it settled. */\n readonly certainty?: (() => CommitCertainty | undefined) | undefined;\n /** What extensions noted on the unit (`note`), in order. */\n notes?: unknown[];\n /**\n * transaction: called by the producer once the transaction is open, with\n * what runs a statement in it; the body waits for what it returns.\n */\n opened?: (run: TransactionStatementRunner) => Promise<void> | undefined;\n /** transaction: `run(unit, sql)`, set by the runner. */\n run?: TransactionStatementRunner;\n /** Set by the runner once the child settled. */\n failed?: boolean;\n failure?: unknown;\n /**\n * The instant the child settled, read by the innermost layer's end: an\n * outer layer's end comes after the inner handlers continued, and still\n * reports the child's instant.\n */\n settledAt?: number;\n}\n\n/** The unit a handler receives: its producer's record is its own field. */\nclass ProducedUnit implements Unit {\n readonly kind: UnitKind;\n readonly model: string | undefined;\n readonly operation: string | undefined;\n readonly #source: UnitSource;\n constructor(source: UnitSource) {\n this.kind = source.kind;\n this.model = source.model;\n // A driver's unit names its operation through its context alone.\n this.operation = Object.hasOwn(source, \"operation\")\n ? source.operation\n : source.context?.operation;\n this.#source = source;\n }\n static sourceOf(unit: object): UnitSource | undefined {\n return #source in unit ? unit.#source : undefined;\n }\n}\n\n/**\n * A running operation unit, by its execution context: one per operation,\n * the same its call carries, so a call's `run` and the cache, which holds\n * the context, find the same unit.\n */\nconst operations = new WeakMap<object, UnitSource>();\n\n/** The producer's record of `unit`, or `undefined` for a unit it did not make. */\nexport const sourceOf = (unit: object): UnitSource | undefined =>\n ProducedUnit.sourceOf(unit);\n\n/** The unit a handler receives for `source`. */\nexport function unitOf(source: UnitSource): Unit {\n const unit = new ProducedUnit(source);\n source.notes ??= [];\n if (source.kind === \"operation\" && source.context !== undefined)\n operations.set(source.context, source);\n return unit;\n}\n\n/**\n * The unit `origin` stands for: a unit a handler received or `work` made, the\n * operation unit of a call's `run`, or that of an execution context.\n */\nexport function originOf(origin: object): UnitSource | undefined {\n const context = callOf(origin)?.of?.context;\n return (\n sourceOf(origin) ??\n (context === undefined ? operations.get(origin) : operations.get(context))\n );\n}\n","/**\n * The one generation of unit handlers: what runs a unit under a chain's\n * `unit` parts, and `work`, by which an extension emits a unit of its own.\n */\nimport {\n getExecutionExtensionChain,\n isRecoverableExecution,\n trustedExecutionContext,\n} from \"@drivers/execution-context\";\nimport { QueryError } from \"@errors\";\nimport { createOperationExecutionContext } from \"@query-engine/execution-context\";\nimport { Sql } from \"@sql\";\nimport type { ExtensionPart } from \"./chain\";\nimport { coordinate, UNITS } from \"./coordination\";\nimport { scopeOf } from \"./origin\";\nimport { collect } from \"./query\";\nimport {\n originOf,\n type TransactionStatementRunner,\n type Unit,\n type UnitEnd,\n type UnitHandler,\n type UnitKind,\n type UnitSource,\n unitOf,\n} from \"./unit-source\";\n\n/**\n * What a unit runs at its core, once every handler called `next()`: given\n * the statement a logical statement's rewriting units handed on.\n */\nexport type Child<Result> = (statement?: Sql) => Promise<Result>;\n\n/** One `unit` part of a chain: its extension, its handler, its kinds. */\ninterface UnitLayer {\n readonly extension: string;\n readonly handler: UnitHandler;\n /** The kinds it runs around; every kind when absent. */\n readonly kinds?: readonly UnitKind[] | undefined;\n}\n\nconst nothing = (): undefined => undefined;\n\n/**\n * Runs one unit under `handlers`, the first one outermost. Each handler is a\n * plain wrapper: the next one, and at the end the child, starts only when it\n * calls `next()`, and the host waits for the promise it returns. The child's\n * failure fails the unit; once the child succeeded, what a handler throws\n * does. `next()` is called once: never calling it, or calling it again,\n * fails the unit. The host contains nothing a handler does.\n */\nexport function runUnit<Result>(\n handlers: readonly UnitLayer[],\n source: UnitSource,\n child: Child<Result>,\n reached?: () => void\n): Promise<Result> {\n const unit = unitOf(source);\n let core: Promise<Result> | undefined;\n const startCore = (): Promise<Result> => {\n core ??= attempt(() => child(source.statement));\n return core;\n };\n const transaction =\n source.kind === \"transaction\"\n ? openTransaction(source, startCore)\n : undefined;\n const enter = (index: number): Promise<Result> => {\n const resolved = handlers[index];\n // A layer that names other kinds is not around this unit at all.\n if (resolved?.kinds?.includes(source.kind) === false)\n return enter(index + 1);\n if (resolved === undefined) {\n reached?.();\n transaction?.enter();\n return startCore();\n }\n return around(resolved, unit, source, () => enter(index + 1));\n };\n const result = enter(0);\n return transaction === undefined ? result : result.catch(transaction.fail);\n}\n\nfunction attempt<Result>(child: () => Promise<Result>): Promise<Result> {\n try {\n return child();\n } catch (failure) {\n return Promise.reject(failure);\n }\n}\n\n/** One handler around the rest of the unit. */\nasync function around<Result>(\n resolved: UnitLayer,\n unit: Unit,\n source: UnitSource,\n rest: () => Promise<Result>\n): Promise<Result> {\n let started: Promise<Result> | undefined;\n let misuse: QueryError | undefined;\n // `next(sql)` hands on another statement to a logical statement's rest.\n const next = (statement?: Sql): Promise<UnitEnd> => {\n if (started !== undefined) {\n misuse ??= unitError(resolved, unit, \"called next() more than once\");\n return Promise.reject(misuse);\n }\n const at = Date.now();\n const handed = statement !== undefined && source.statement !== undefined;\n // The statement is rendered after every rewrite: refused here, it is\n // refused in the extension's name, not as the renderer's TypeError.\n if (handed && !(statement instanceof Sql))\n started = Promise.reject(\n unitError(resolved, unit, \"handed next() something not a statement\")\n );\n else {\n if (handed) source.statement = statement;\n started = rest();\n }\n return started.then(\n () => settle(source, at, false, undefined),\n (failure: unknown) => settle(source, at, true, failure)\n );\n };\n let handlerFailure: { readonly failure: unknown } | undefined;\n try {\n await resolved.handler(unit, next);\n } catch (failure) {\n handlerFailure = { failure };\n }\n if (started === undefined)\n throw (\n handlerFailure?.failure ??\n unitError(resolved, unit, \"settled without calling next()\")\n );\n const value = await started;\n if (handlerFailure !== undefined) throw handlerFailure.failure;\n if (misuse !== undefined) throw misuse;\n return value;\n}\n\nfunction settle(\n source: UnitSource,\n at: number,\n failed: boolean,\n failure: unknown\n): UnitEnd {\n source.failed = failed;\n source.failure = failure;\n source.settledAt ??= Date.now();\n const certainty = source.certainty?.();\n return {\n status: failed ? \"failure\" : \"success\",\n duration: Math.max(0, source.settledAt - at),\n ...(certainty === undefined ? {} : { certainty }),\n ...(failed && isRecoverableExecution(source.context)\n ? { recovered: true as const }\n : {}),\n };\n}\n\nfunction unitError(\n resolved: UnitLayer,\n unit: Unit,\n failure: string\n): QueryError {\n return new QueryError(\n `Extension \"${resolved.extension}\" unit() for ${unit.kind} ${failure}.`,\n { meta: { method: \"unit\", operation: unit.operation, model: unit.model } }\n );\n}\n\n/**\n * A transaction unit's `run(unit, sql)`: it opens the transaction if no\n * `next()` has yet, and runs the statement there before the body. The body\n * then waits for the innermost `next()`; a unit that fails before it rolls\n * back the transaction `run` opened (`fail`).\n */\nfunction openTransaction<Result>(\n source: UnitSource,\n startCore: () => Promise<Result>\n) {\n let runner: TransactionStatementRunner | undefined;\n let ready: (() => void) | undefined;\n let refuse: ((failure: unknown) => void) | undefined;\n let aborted: { readonly failure: unknown } | undefined;\n let bodyEntered = false;\n // The transaction `run` opened before the body was let run.\n let opening: Promise<Result> | undefined;\n let announce: ((run: TransactionStatementRunner) => void) | undefined;\n const opened = new Promise<TransactionStatementRunner>((resolve) => {\n announce = resolve;\n });\n const openedWith = (run: TransactionStatementRunner) => {\n runner = run;\n announce?.(run);\n if (aborted !== undefined) return Promise.reject(aborted.failure);\n if (bodyEntered) return undefined;\n return new Promise<void>((resolve, reject) => {\n ready = resolve;\n refuse = reject;\n });\n };\n // Named first, then stored: a function literal assigned to a property is\n // allocated outside the young generation and keeps the unit alive.\n source.opened = openedWith;\n const runIn = (statement: Sql) => {\n if (runner !== undefined) return runner(statement);\n opening ??= startCore();\n return Promise.race([\n opened,\n opening.then(() => {\n throw new QueryError(\"run() was called on a transaction that ended.\");\n }),\n ]).then((run) => run(statement));\n };\n source.run = runIn;\n return {\n enter: () => {\n bodyEntered = true;\n ready?.();\n },\n fail: (failure: unknown): Promise<never> => {\n // Thrown, not returned rejected: workerd reports a rejection that the\n // promise taking it holds only a microtask later.\n if (opening === undefined || bodyEntered) throw failure;\n aborted = { failure };\n refuse?.(failure);\n return opening.catch(nothing).then(() => {\n throw failure;\n });\n },\n };\n}\n\n/** What runs a unit under a chain's handlers. */\nexport interface Observation {\n readonly handlers: readonly UnitLayer[];\n readonly run: <Result>(\n source: UnitSource,\n child: Child<Result>\n ) => Promise<Result>;\n /**\n * The members of `$transaction([...])`, or of a batch of logical\n * statements: every member's unit is entered (a member without one is\n * skipped), and this resolves once each reached its child, with the units\n * and what settles once every unit did (and fails as the first that\n * failed). The array waits for it before it prepares any member: a handler\n * that waits (for a tracer to load) does so before the array's work, and\n * each member's work runs inside its unit.\n */\n readonly members: (\n members: readonly (readonly [UnitSource, Child<unknown>] | undefined)[]\n ) => Promise<{\n readonly done: Promise<unknown>;\n readonly units: readonly (\n | { readonly done: Promise<unknown> }\n | undefined\n )[];\n }>;\n /**\n * For a chain's rewriting units (`unit(fn, kinds, { rewrites: true })`):\n * the members of one batch, each its own logical statement: every member\n * is rewritten before `send` sends any (it receives each member's final\n * statement, `undefined` for a member with no unit), and each member's\n * unit then ends as the batch does. A member whose unit fails before its\n * `next()` refuses the batch: `refuse(index, failure)` is thrown.\n */\n readonly together: <Result>(\n sources: readonly (UnitSource | undefined)[],\n send: (statements: readonly (Sql | undefined)[]) => Promise<Result>,\n refuse: (index: number, failure: unknown) => unknown\n ) => Promise<Result>;\n}\n\nexport function observationOf(handlers: readonly UnitLayer[]): Observation {\n const enter = <Result>(source: UnitSource, child: Child<Result>) => {\n let reach: (() => void) | undefined;\n const reached = new Promise<void>((resolve) => {\n reach = resolve;\n });\n const done = runUnit(handlers, source, child, reach);\n done.then(reach, reach);\n return { done, reached };\n };\n const members: Observation[\"members\"] = async (members) => {\n const units = members.map((member) =>\n member === undefined ? undefined : enter(member[0], member[1])\n );\n await Promise.all(units.map((unit) => unit?.reached));\n const done = Promise.all(units.map((unit) => unit?.done));\n done.catch(() => undefined);\n return { done, units };\n };\n return {\n handlers,\n run: (source, child) => runUnit(handlers, source, child),\n members,\n together: async (sources, send, refuse) => {\n const statements: (Sql | undefined)[] = [];\n let settle!: (outcome: Promise<unknown>) => void;\n const outcome = new Promise<unknown>((resolve) => {\n settle = resolve;\n });\n const { done, units } = await members(\n sources.map((source, index) =>\n source === undefined\n ? undefined\n : [\n source,\n (statement) => {\n statements[index] = statement;\n return outcome;\n },\n ]\n )\n );\n // A member's unit reached its child where the child kept its\n // statement.\n const refused = units.findIndex(\n (unit, index) => unit !== undefined && !(index in statements)\n );\n if (refused >= 0) {\n // An unreached unit's end is its failure.\n const failure = await units[refused]?.done.catch(\n (error: unknown) => error\n );\n settle(Promise.reject(failure));\n await done.catch(() => undefined);\n throw refuse(refused, failure);\n }\n const sent = send(statements);\n settle(sent);\n // The send's failure is the call's, through `sent`; the units that\n // wait on `outcome` see it too, and where none started, nothing\n // else does.\n outcome.catch(() => undefined);\n try {\n const value = await sent;\n await done;\n return value;\n } finally {\n await done.catch(() => undefined);\n }\n },\n };\n}\n\n/**\n * The part one `unit(handler, kinds)` builds: it adds a layer to the\n * chain's units, the first extension outermost. It brings nothing of the\n * array barrier of `$transaction([...])`: the array starts every member's\n * unit, and waits until each reached its child, before it prepares any\n * member.\n */\nexport function unitLayerPart(\n handler: UnitHandler,\n kinds: readonly UnitKind[] | undefined\n): ExtensionPart {\n return {\n join({ next, owner }) {\n next.observation = observationOf([\n ...(next.observation?.handlers ?? []),\n { extension: owner.name, handler, kinds },\n ]);\n coordinate(next, UNITS, collect);\n },\n };\n}\n\n/**\n * Run `fn` as a unit of the extension's own (`kind` is any string), under\n * every `unit` part of the chain `origin` belongs to: `origin` is a call's\n * context or `run`, a unit a handler received, one `work` made, or a\n * method's scope. Without a chain that observes units, `fn` runs alone.\n * `fn` receives the unit, to `note` on it.\n */\nexport function work<Result>(\n origin: object,\n unit: {\n readonly kind: UnitKind;\n readonly operation: string;\n readonly model?: string;\n /** A first fact, noted before any handler sees the unit. */\n readonly note?: unknown;\n },\n fn: (unit: Unit) => Promise<Result>\n): Promise<Result> {\n const scope = scopeOf(origin);\n const context =\n originOf(origin)?.context ??\n trustedExecutionContext(origin) ??\n // A method works outside any call: its unit is an execution of its own,\n // with its own correlation.\n (scope &&\n createOperationExecutionContext(\n unit.model ?? scope.extension,\n unit.operation,\n scope.engine.extensionChain\n ));\n const observation = getExecutionExtensionChain(context)?.observation;\n const source: UnitSource = {\n kind: unit.kind,\n operation: unit.operation,\n model: unit.model,\n context,\n notes: unit.note === undefined ? [] : [unit.note],\n };\n // `fn` gets a unit of the same record: what it notes, handlers read.\n return observation === undefined\n ? fn(unitOf(source))\n : observation.run(source, () => fn(unitOf(source)));\n}\n","import type { Dialect } from \"./types\";\n\n/**\n * The configuration facts that name one driver in presented telemetry. No\n * package entry exports this module.\n *\n * `namespace` is the adapter's one normalized SQL qualifier and is absent when\n * the adapter is unqualified. `adapter.namespace` is installed non-writable,\n * so a snapshot taken once (the cached read's, at `$withCache`) cannot go\n * stale. This is the one reader of that property for presentation.\n */\nexport interface DriverIdentity {\n readonly dialect: Dialect;\n readonly driverName: string;\n readonly namespace?: string;\n}\n\n/** The public readonly driver fields an identity is read from. */\nexport interface DriverIdentitySource {\n readonly dialect: Dialect;\n readonly driverName: string;\n readonly adapter: { readonly namespace?: string };\n}\n\n/**\n * Read one driver's identity from its public readonly configuration, or\n * `undefined` when that read throws (a custom adapter's `namespace` getter):\n * every presenter then omits the driver attributes and presents the rest.\n */\nexport function readDriverIdentity(\n driver: DriverIdentitySource\n): DriverIdentity | undefined {\n try {\n const namespace = driver.adapter.namespace;\n return Object.freeze({\n dialect: driver.dialect,\n driverName: driver.driverName,\n ...(namespace === undefined ? {} : { namespace }),\n });\n } catch {\n // The operation's facts, its spans and a cached read's revalidation\n // identity survive a driver that cannot name itself.\n return undefined;\n }\n}\n","/**\n * The words a `unit` handler reads of its unit, each a top-level function\n * that reads what the unit's producer already holds, when it is called: a\n * fact nobody reads is never computed, and a word a program does not import\n * is not in its bundle.\n */\nimport {\n BATCH_DIAGNOSTIC_PARAMS,\n EMPTY_DIAGNOSTIC_PARAMS,\n snapshotDiagnosticParameters,\n} from \"@drivers/driver-diagnostics\";\nimport {\n type DriverIdentity,\n readDriverIdentity,\n} from \"@drivers/driver-identity\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport { errorOrigin } from \"../errors/logged-errors\";\nimport type { StatementUnit, UnitContext } from \"./contract\";\nimport { originOf, sourceOf } from \"./unit-source\";\n\n/**\n * The text a `statement` unit sends, as rendered for its driver; a native\n * batch's texts joined by `\"; \"`. The text of a verbatim unsafe raw query\n * too: it is never rewritten, but it is observed.\n */\nexport const text = (u: UnitContext): string | undefined => sourceOf(u)?.sql;\n\n/**\n * The snapshot the driver took for its diagnostics, or the one taken here at\n * the first read and kept where the driver keeps its own (`key` of `of`): a\n * caller's parameter is read once however many read it.\n */\nfunction shownOf(\n of: object,\n key: PropertyKey,\n params: readonly unknown[] | undefined\n): readonly unknown[] {\n const taken: unknown = Reflect.get(of, key);\n if (Array.isArray(taken) && taken !== EMPTY_DIAGNOSTIC_PARAMS) return taken;\n // Every statement the package sends states its parameters, a raw one `[]`.\n const shown = snapshotDiagnosticParameters(params!);\n Reflect.set(of, key, shown);\n return shown;\n}\n\n/**\n * A bounded snapshot of the parameters a `statement` unit sends; for a\n * native batch, one list per member. Read it before `next()`: a provider may\n * change what it was handed.\n */\nexport function parameters(u: UnitContext): readonly unknown[] | undefined {\n const source = sourceOf(u);\n if (source?.batch !== undefined)\n return source.batch.map((member) =>\n shownOf(member, BATCH_DIAGNOSTIC_PARAMS, member.params)\n );\n return source?.params === undefined\n ? undefined\n : shownOf(source, \"shown\", source.params);\n}\n\n/**\n * The dialect, name and SQL namespace of the driver doing a unit's work;\n * `undefined` for a unit with no driver, or when a custom adapter's\n * `namespace` getter throws.\n */\nexport function driver(u: UnitContext): DriverIdentity | undefined {\n const source = sourceOf(u)?.driver;\n return source === undefined ? undefined : readDriverIdentity(source);\n}\n\n/** What a unit's child failed with, once `next()` settled; else `undefined`. */\nexport const failure = (u: UnitContext): unknown => sourceOf(u)?.failure;\n\n/** The identity of the logical call a unit belongs to. */\nexport const correlation = (u: UnitContext): string | undefined =>\n sourceOf(u)?.context?.correlationId;\n\n/** The SQL name of the model an `operation` unit addresses. */\nexport const table = (u: UnitContext): string | undefined => sourceOf(u)?.table;\n\n/** One member of a native batch, as `statements(u)` gives it. */\nexport interface BatchMember {\n readonly sql: string;\n readonly parameters: readonly unknown[];\n readonly model?: string;\n readonly operation?: string;\n readonly correlation?: string;\n}\n\n/**\n * The members of a `statement` unit that sends a native batch, in order;\n * `undefined` for a unit that sends one statement. A failure that names a\n * member carries its index (`meta.statementIndex`).\n */\nexport function statements(u: UnitContext): readonly BatchMember[] | undefined {\n return sourceOf(u)?.batch?.map((member) => ({\n sql: member.sql,\n // A snapshot only when read, as `parameters(u)` takes one.\n get parameters() {\n return shownOf(member, BATCH_DIAGNOSTIC_PARAMS, member.params);\n },\n // Every member the package sends carries the context of its call.\n model: member.context?.model,\n operation: member.context?.operation,\n correlation: member.context?.correlationId,\n }));\n}\n\n/**\n * The first error of a line of successors the package made from it (a clone\n * that adds execution context or commit certainty); the error itself when it\n * has none. Two units that fail with errors of one origin failed once.\n */\nexport function origin(error: Error): Error;\nexport function origin(error: unknown): unknown;\nexport function origin(error: unknown): unknown {\n return errorOrigin(error);\n}\n\n/**\n * For a unit that rewrites statements: the statement before its rewrite, to\n * hand on, changed or not, to `next(sql)`. Always there in a part that\n * rewrites.\n */\nexport function statement(u: StatementUnit): Sql;\nexport function statement(u: UnitContext): Sql | undefined;\nexport function statement(u: UnitContext): Sql | undefined {\n return sourceOf(u)?.statement;\n}\n\n/**\n * For a `transaction` unit: runs `sql` in the transaction and gives its\n * rows. Called before `next()`, it opens the transaction and runs before\n * anything else does; the transaction's body waits for the innermost\n * `next()`. A savepoint is no transaction.\n */\nexport function run(\n u: UnitContext,\n sql: Sql\n): Promise<readonly Record<string, unknown>[]> {\n const send = sourceOf(u)?.run;\n return send === undefined\n ? Promise.reject(\n new QueryError(\"run() needs the transaction unit a unit() received.\")\n )\n : send(sql);\n}\n\n/**\n * Attach a fact to a unit that is still running: `target` is a unit (one a\n * handler received, or `work` made), or a call's `run`, which notes on the\n * call's `operation` unit. `false` when there is no such unit, or it has\n * settled (where no handler runs around a unit, nothing would read it).\n */\nexport function note(target: object, fact: unknown): boolean {\n const source = originOf(target);\n if (source === undefined || source.failed !== undefined) return false;\n source.notes?.push(fact);\n return true;\n}\n\n/** The facts noted on a unit, in order. */\nexport const notes = (u: UnitContext): readonly unknown[] =>\n sourceOf(u)?.notes ?? [];\n"],"mappings":"yYA2FA,IAAM,aAAN,KAAmC,CACjC,KACA,MACA,UACA,GACA,YAAY,EAAoB,CAC9B,KAAK,KAAO,EAAO,KACnB,KAAK,MAAQ,EAAO,MAEpB,KAAK,UAAY,OAAO,OAAO,EAAQ,YAAY,CAC/C,EAAO,UACP,EAAO,SAAS,UACpB,MAAA,EAAe,EAEjB,OAAO,SAAS,EAAsC,CACpD,MAAO,MAAW,EAAO,GAAA,EAAe,IAAA,KAS5C,MAAM,EAAa,IAAI,QAGV,SAAY,GACvB,aAAa,SAAS,EAAK,CAG7B,SAAgB,OAAO,EAA0B,CAC/C,IAAM,EAAO,IAAI,aAAa,EAAO,CAIrC,MAHA,GAAO,QAAU,EAAE,CACf,EAAO,OAAS,aAAe,EAAO,UAAY,IAAA,IACpD,EAAW,IAAI,EAAO,QAAS,EAAO,CACjC,EAOT,SAAgB,SAAS,EAAwC,CAC/D,IAAM,EAAU,EAAOC,EAAO,EAAE,IAAI,QACpC,OACE,SAASA,EAAO,GACf,IAAY,IAAA,GAAY,EAAW,IAAIA,EAAO,CAAG,EAAW,IAAI,EAAQ,ECjG7E,MAAM,YAA2B,IAAA,GAUjC,SAAgB,QACd,EACA,EACA,EACA,EACiB,CACjB,IAAM,EAAO,OAAO,EAAO,CACvB,EACE,eACJ,IAAS,YAAc,EAAM,EAAO,UAAU,CAAC,CACxC,GAEH,EACJ,EAAO,OAAS,cACZ,gBAAgB,EAAQ,UAAU,C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,KAAK,EAAK,CACjB,IAIT,MAAa,MAAS,GACpB,SAAS,EAAE,EAAE,OAAS,EAAE"}
1
+ {"version":3,"file":"unit-words-BGMVZ1MX.mjs","names":["#source","origin","failure","statement","run","members","statements","settle","origin","driver"],"sources":["../src/extensions/unit-source.ts","../src/extensions/observation.ts","../src/drivers/driver-identity.ts","../src/extensions/unit-words.ts"],"sourcesContent":["/**\n * A unit of real work, as a handler receives it, and what its producer\n * already holds about it. The runner keeps the producer's record beside the\n * unit; each unit word (`text`, `parameters`, `driver`, …) reads that record\n * when it is called. A fact nobody reads is never computed, and a program\n * that imports no word carries none of their code.\n */\nimport type { DriverIdentitySource } from \"@drivers/driver-identity\";\nimport type { BatchQuery, QueryExecutionContext } from \"@drivers/types\";\nimport type { Sql } from \"@sql\";\nimport type { UnitContext, UnitKind, UnitOutcome } from \"./contract\";\nimport { callOf } from \"./origin\";\n\nexport type { UnitKind } from \"./contract\";\nexport type Unit = UnitContext;\nexport type UnitEnd = UnitOutcome;\ntype CommitCertainty = \"committed\" | \"may-have-committed\";\n\n/**\n * One handler around a unit. `next()` lets the unit run; the child starts\n * only then, at most once, and must be called. What the handler throws, or a\n * promise it returns that rejects, fails the call; the child's own failure\n * fails it first.\n */\nexport type UnitHandler = (\n unit: Unit,\n next: (sql?: Sql) => Promise<UnitEnd>\n) => unknown;\n\n/** Runs one statement in the transaction a unit opened, and gives its rows. */\nexport type TransactionStatementRunner = (\n statement: Sql\n) => Promise<readonly Record<string, unknown>[]>;\n\n/**\n * The producer's record of one unit: references it already held, never a\n * fact computed for a reader that may not come.\n */\nexport interface UnitSource {\n readonly kind: UnitKind;\n readonly operation?: string | undefined;\n readonly model?: string | undefined;\n /**\n * The trusted execution context: the chain, correlation, a recovered read.\n * An operation unit's is its call's own (`CallOrigin.of`), how a `run`\n * finds it.\n */\n readonly context?: QueryExecutionContext | undefined;\n /** The driver doing the work, read only by `driver(unit)`. */\n readonly driver?: DriverIdentitySource | undefined;\n /** operation: the SQL name of the model. */\n readonly table?: string | undefined;\n /** statement: the rendered text sent, a native batch's texts joined. */\n readonly sql?: string | undefined;\n /** statement: the parameters sent, as the driver detached them. */\n readonly params?: readonly unknown[] | undefined;\n /**\n * statement: the diagnostic snapshot of `params` the driver took (its\n * empty constant when it took none): what `parameters(u)` reads.\n */\n readonly shown?: readonly unknown[] | undefined;\n /** statement: a native batch's members, in order. */\n readonly batch?: readonly BatchQuery[] | undefined;\n /**\n * A logical statement under rewriting units: the statement as the earlier\n * ones left it (what `next(sql)` hands on replaces it).\n */\n statement?: Sql | undefined;\n /** How sure the child's commit is, read once it settled. */\n readonly certainty?: (() => CommitCertainty | undefined) | undefined;\n /** What extensions noted on the unit (`note`), in order. */\n notes?: unknown[];\n /**\n * transaction: called by the producer once the transaction is open, with\n * what runs a statement in it; the body waits for what it returns.\n */\n opened?: (run: TransactionStatementRunner) => Promise<void> | undefined;\n /** transaction: `run(unit, sql)`, set by the runner. */\n run?: TransactionStatementRunner;\n /** Set by the runner once the child settled. */\n failed?: boolean;\n failure?: unknown;\n /**\n * The instant the child settled, read by the innermost layer's end: an\n * outer layer's end comes after the inner handlers continued, and still\n * reports the child's instant.\n */\n settledAt?: number;\n}\n\n/** The unit a handler receives: its producer's record is its own field. */\nclass ProducedUnit implements Unit {\n readonly kind: UnitKind;\n readonly model: string | undefined;\n readonly operation: string | undefined;\n readonly #source: UnitSource;\n constructor(source: UnitSource) {\n this.kind = source.kind;\n this.model = source.model;\n // A driver's unit names its operation through its context alone.\n this.operation = Object.hasOwn(source, \"operation\")\n ? source.operation\n : source.context?.operation;\n this.#source = source;\n }\n static sourceOf(unit: object): UnitSource | undefined {\n return #source in unit ? unit.#source : undefined;\n }\n}\n\n/**\n * A running operation unit, by its execution context: one per operation,\n * the same its call carries, so a call's `run` and the cache, which holds\n * the context, find the same unit.\n */\nconst operations = new WeakMap<object, UnitSource>();\n\n/** The producer's record of `unit`, or `undefined` for a unit it did not make. */\nexport const sourceOf = (unit: object): UnitSource | undefined =>\n ProducedUnit.sourceOf(unit);\n\n/** The unit a handler receives for `source`. */\nexport function unitOf(source: UnitSource): Unit {\n const unit = new ProducedUnit(source);\n source.notes ??= [];\n if (source.kind === \"operation\" && source.context !== undefined)\n operations.set(source.context, source);\n return unit;\n}\n\n/**\n * The unit `origin` stands for: a unit a handler received or `work` made, the\n * operation unit of a call's `run`, or that of an execution context.\n */\nexport function originOf(origin: object): UnitSource | undefined {\n const context = callOf(origin)?.of?.context;\n return (\n sourceOf(origin) ??\n (context === undefined ? operations.get(origin) : operations.get(context))\n );\n}\n","/**\n * The one generation of unit handlers: what runs a unit under a chain's\n * `unit` parts, and `work`, by which an extension emits a unit of its own.\n */\nimport {\n getExecutionExtensionChain,\n isRecoverableExecution,\n trustedExecutionContext,\n} from \"@drivers/execution-context\";\nimport { QueryError } from \"@errors\";\nimport { createOperationExecutionContext } from \"@query-engine/execution-context\";\nimport { Sql } from \"@sql\";\nimport type { ExtensionPart } from \"./chain\";\nimport { coordinate, UNITS } from \"./coordination\";\nimport { scopeOf } from \"./origin\";\nimport { collect } from \"./query\";\nimport {\n originOf,\n type TransactionStatementRunner,\n type Unit,\n type UnitEnd,\n type UnitHandler,\n type UnitKind,\n type UnitSource,\n unitOf,\n} from \"./unit-source\";\n\n/**\n * What a unit runs at its core, once every handler called `next()`: given\n * the statement a logical statement's rewriting units handed on.\n */\nexport type Child<Result> = (statement?: Sql) => Promise<Result>;\n\n/** One `unit` part of a chain: its extension, its handler, its kinds. */\ninterface UnitLayer {\n readonly extension: string;\n readonly handler: UnitHandler;\n /** The kinds it runs around; every kind when absent. */\n readonly kinds?: readonly UnitKind[] | undefined;\n}\n\nconst nothing = (): undefined => undefined;\n\n/**\n * Runs one unit under `handlers`, the first one outermost. Each handler is a\n * plain wrapper: the next one, and at the end the child, starts only when it\n * calls `next()`, and the host waits for the promise it returns. The child's\n * failure fails the unit; once the child succeeded, what a handler throws\n * does. `next()` is called once: never calling it, or calling it again,\n * fails the unit. The host contains nothing a handler does.\n */\nexport function runUnit<Result>(\n handlers: readonly UnitLayer[],\n source: UnitSource,\n child: Child<Result>,\n reached?: () => void\n): Promise<Result> {\n const unit = unitOf(source);\n let core: Promise<Result> | undefined;\n const startCore = (): Promise<Result> => {\n core ??= attempt(() => child(source.statement));\n return core;\n };\n const transaction =\n source.kind === \"transaction\"\n ? openTransaction(source, startCore)\n : undefined;\n const enter = (index: number): Promise<Result> => {\n const resolved = handlers[index];\n // A layer that names other kinds is not around this unit at all.\n if (resolved?.kinds?.includes(source.kind) === false)\n return enter(index + 1);\n if (resolved === undefined) {\n reached?.();\n transaction?.enter();\n return startCore();\n }\n return around(resolved, unit, source, () => enter(index + 1));\n };\n const result = enter(0);\n return transaction === undefined ? result : result.catch(transaction.fail);\n}\n\nfunction attempt<Result>(child: () => Promise<Result>): Promise<Result> {\n try {\n return child();\n } catch (failure) {\n return Promise.reject(failure);\n }\n}\n\n/** One handler around the rest of the unit. */\nasync function around<Result>(\n resolved: UnitLayer,\n unit: Unit,\n source: UnitSource,\n rest: () => Promise<Result>\n): Promise<Result> {\n let started: Promise<Result> | undefined;\n let misuse: QueryError | undefined;\n // `next(sql)` hands on another statement to a logical statement's rest.\n const next = (statement?: Sql): Promise<UnitEnd> => {\n if (started !== undefined) {\n misuse ??= unitError(resolved, unit, \"called next() more than once\");\n return Promise.reject(misuse);\n }\n const at = Date.now();\n const handed = statement !== undefined && source.statement !== undefined;\n // The statement is rendered after every rewrite: refused here, it is\n // refused in the extension's name, not as the renderer's TypeError.\n if (handed && !(statement instanceof Sql))\n started = Promise.reject(\n unitError(resolved, unit, \"handed next() something not a statement\")\n );\n else {\n if (handed) source.statement = statement;\n started = rest();\n }\n return started.then(\n () => settle(source, at, false, undefined),\n (failure: unknown) => settle(source, at, true, failure)\n );\n };\n let handlerFailure: { readonly failure: unknown } | undefined;\n try {\n await resolved.handler(unit, next);\n } catch (failure) {\n handlerFailure = { failure };\n }\n if (started === undefined)\n throw (\n handlerFailure?.failure ??\n unitError(resolved, unit, \"settled without calling next()\")\n );\n const value = await started;\n if (handlerFailure !== undefined) throw handlerFailure.failure;\n if (misuse !== undefined) throw misuse;\n return value;\n}\n\nfunction settle(\n source: UnitSource,\n at: number,\n failed: boolean,\n failure: unknown\n): UnitEnd {\n source.failed = failed;\n source.failure = failure;\n source.settledAt ??= Date.now();\n const certainty = source.certainty?.();\n return {\n status: failed ? \"failure\" : \"success\",\n duration: Math.max(0, source.settledAt - at),\n ...(certainty === undefined ? {} : { certainty }),\n ...(failed && isRecoverableExecution(source.context)\n ? { recovered: true as const }\n : {}),\n };\n}\n\nfunction unitError(\n resolved: UnitLayer,\n unit: Unit,\n failure: string\n): QueryError {\n return new QueryError(\n `Extension \"${resolved.extension}\" unit() for ${unit.kind} ${failure}.`,\n { meta: { method: \"unit\", operation: unit.operation, model: unit.model } }\n );\n}\n\n/**\n * A transaction unit's `run(unit, sql)`: it opens the transaction if no\n * `next()` has yet, and runs the statement there before the body. The body\n * then waits for the innermost `next()`; a unit that fails before it rolls\n * back the transaction `run` opened (`fail`).\n */\nfunction openTransaction<Result>(\n source: UnitSource,\n startCore: () => Promise<Result>\n) {\n let runner: TransactionStatementRunner | undefined;\n let ready: (() => void) | undefined;\n let refuse: ((failure: unknown) => void) | undefined;\n let aborted: { readonly failure: unknown } | undefined;\n let bodyEntered = false;\n // The transaction `run` opened before the body was let run.\n let opening: Promise<Result> | undefined;\n let announce: ((run: TransactionStatementRunner) => void) | undefined;\n const opened = new Promise<TransactionStatementRunner>((resolve) => {\n announce = resolve;\n });\n const openedWith = (run: TransactionStatementRunner) => {\n runner = run;\n announce?.(run);\n if (aborted !== undefined) return Promise.reject(aborted.failure);\n if (bodyEntered) return undefined;\n return new Promise<void>((resolve, reject) => {\n ready = resolve;\n refuse = reject;\n });\n };\n // Named first, then stored: a function literal assigned to a property is\n // allocated outside the young generation and keeps the unit alive.\n source.opened = openedWith;\n const runIn = (statement: Sql) => {\n if (runner !== undefined) return runner(statement);\n opening ??= startCore();\n return Promise.race([\n opened,\n opening.then(() => {\n throw new QueryError(\"run() was called on a transaction that ended.\");\n }),\n ]).then((run) => run(statement));\n };\n source.run = runIn;\n return {\n enter: () => {\n bodyEntered = true;\n ready?.();\n },\n fail: (failure: unknown): Promise<never> => {\n // Thrown, not returned rejected: workerd reports a rejection that the\n // promise taking it holds only a microtask later.\n if (opening === undefined || bodyEntered) throw failure;\n aborted = { failure };\n refuse?.(failure);\n return opening.catch(nothing).then(() => {\n throw failure;\n });\n },\n };\n}\n\n/** What runs a unit under a chain's handlers. */\nexport interface Observation {\n readonly handlers: readonly UnitLayer[];\n readonly run: <Result>(\n source: UnitSource,\n child: Child<Result>\n ) => Promise<Result>;\n /**\n * The members of `$transaction([...])`, or of a batch of logical\n * statements: every member's unit is entered (a member without one is\n * skipped), and this resolves once each reached its child, with the units\n * and what settles once every unit did (and fails as the first that\n * failed). The array waits for it before it prepares any member: a handler\n * that waits (for a tracer to load) does so before the array's work, and\n * each member's work runs inside its unit.\n */\n readonly members: (\n members: readonly (readonly [UnitSource, Child<unknown>] | undefined)[]\n ) => Promise<{\n readonly done: Promise<unknown>;\n readonly units: readonly (\n | { readonly done: Promise<unknown> }\n | undefined\n )[];\n }>;\n /**\n * For a chain's rewriting units (`unit(fn, kinds, { rewrites: true })`):\n * the members of one batch, each its own logical statement: every member\n * is rewritten before `send` sends any (it receives each member's final\n * statement, `undefined` for a member with no unit), and each member's\n * unit then ends as the batch does. A member whose unit fails before its\n * `next()` refuses the batch: `refuse(index, failure)` is thrown.\n */\n readonly together: <Result>(\n sources: readonly (UnitSource | undefined)[],\n send: (statements: readonly (Sql | undefined)[]) => Promise<Result>,\n refuse: (index: number, failure: unknown) => unknown\n ) => Promise<Result>;\n}\n\nexport function observationOf(handlers: readonly UnitLayer[]): Observation {\n const enter = <Result>(source: UnitSource, child: Child<Result>) => {\n let reach: (() => void) | undefined;\n const reached = new Promise<void>((resolve) => {\n reach = resolve;\n });\n const done = runUnit(handlers, source, child, reach);\n done.then(reach, reach);\n return { done, reached };\n };\n const members: Observation[\"members\"] = async (members) => {\n const units = members.map((member) =>\n member === undefined ? undefined : enter(member[0], member[1])\n );\n await Promise.all(units.map((unit) => unit?.reached));\n const done = Promise.all(units.map((unit) => unit?.done));\n done.catch(() => undefined);\n return { done, units };\n };\n return {\n handlers,\n run: (source, child) => runUnit(handlers, source, child),\n members,\n together: async (sources, send, refuse) => {\n const statements: (Sql | undefined)[] = [];\n let settle!: (outcome: Promise<unknown>) => void;\n const outcome = new Promise<unknown>((resolve) => {\n settle = resolve;\n });\n const { done, units } = await members(\n sources.map((source, index) =>\n source === undefined\n ? undefined\n : [\n source,\n (statement) => {\n statements[index] = statement;\n return outcome;\n },\n ]\n )\n );\n // A member's unit reached its child where the child kept its\n // statement.\n const refused = units.findIndex(\n (unit, index) => unit !== undefined && !(index in statements)\n );\n if (refused >= 0) {\n // An unreached unit's end is its failure.\n const failure = await units[refused]?.done.catch(\n (error: unknown) => error\n );\n settle(Promise.reject(failure));\n await done.catch(() => undefined);\n throw refuse(refused, failure);\n }\n const sent = send(statements);\n settle(sent);\n // The send's failure is the call's, through `sent`; the units that\n // wait on `outcome` see it too, and where none started, nothing\n // else does.\n outcome.catch(() => undefined);\n try {\n const value = await sent;\n await done;\n return value;\n } finally {\n await done.catch(() => undefined);\n }\n },\n };\n}\n\n/**\n * The part one `unit(handler, kinds)` builds: it adds a layer to the\n * chain's units, the first extension outermost. It brings nothing of the\n * array barrier of `$transaction([...])`: the array starts every member's\n * unit, and waits until each reached its child, before it prepares any\n * member.\n */\nexport function unitLayerPart(\n handler: UnitHandler,\n kinds: readonly UnitKind[] | undefined\n): ExtensionPart {\n return {\n join({ next, owner }) {\n next.observation = observationOf([\n ...(next.observation?.handlers ?? []),\n { extension: owner.name, handler, kinds },\n ]);\n coordinate(next, UNITS, collect);\n },\n };\n}\n\n/**\n * Run `fn` as a unit of the extension's own (`kind` is any string), under\n * every `unit` part of the chain `origin` belongs to: `origin` is a call's\n * context or `run`, a unit a handler received, one `work` made, or a\n * method's scope. Without a chain that observes units, `fn` runs alone.\n * `fn` receives the unit, to `note` on it.\n */\nexport function work<Result>(\n origin: object,\n unit: {\n readonly kind: UnitKind;\n readonly operation: string;\n readonly model?: string;\n /** A first fact, noted before any handler sees the unit. */\n readonly note?: unknown;\n },\n fn: (unit: Unit) => Promise<Result>\n): Promise<Result> {\n const scope = scopeOf(origin);\n const context =\n originOf(origin)?.context ??\n trustedExecutionContext(origin) ??\n // A method works outside any call: its unit is an execution of its own,\n // with its own correlation.\n (scope &&\n createOperationExecutionContext(\n unit.model ?? scope.extension,\n unit.operation,\n scope.engine.extensionChain\n ));\n const observation = getExecutionExtensionChain(context)?.observation;\n const source: UnitSource = {\n kind: unit.kind,\n operation: unit.operation,\n model: unit.model,\n context,\n notes: unit.note === undefined ? [] : [unit.note],\n };\n // `fn` gets a unit of the same record: what it notes, handlers read.\n return observation === undefined\n ? fn(unitOf(source))\n : observation.run(source, () => fn(unitOf(source)));\n}\n","import type { Dialect } from \"./types\";\n\n/**\n * The configuration facts that name one driver in presented telemetry. No\n * package entry exports this module.\n *\n * `namespace` is the adapter's one normalized SQL qualifier and is absent when\n * the adapter is unqualified. `adapter.namespace` is installed non-writable,\n * so a snapshot taken once (the cached read's, at `$withCache`) cannot go\n * stale. This is the one reader of that property for presentation.\n */\nexport interface DriverIdentity {\n readonly dialect: Dialect;\n readonly driverName: string;\n readonly namespace?: string;\n}\n\n/** The public readonly driver fields an identity is read from. */\nexport interface DriverIdentitySource {\n readonly dialect: Dialect;\n readonly driverName: string;\n readonly adapter: { readonly namespace?: string };\n}\n\n/**\n * Read one driver's identity from its public readonly configuration, or\n * `undefined` when that read throws (a custom adapter's `namespace` getter):\n * every presenter then omits the driver attributes and presents the rest.\n */\nexport function readDriverIdentity(\n driver: DriverIdentitySource\n): DriverIdentity | undefined {\n try {\n const namespace = driver.adapter.namespace;\n return Object.freeze({\n dialect: driver.dialect,\n driverName: driver.driverName,\n ...(namespace === undefined ? {} : { namespace }),\n });\n } catch {\n // The operation's facts, its spans and a cached read's revalidation\n // identity survive a driver that cannot name itself.\n return undefined;\n }\n}\n","/**\n * The words a `unit` handler reads of its unit, each a top-level function\n * that reads what the unit's producer already holds, when it is called: a\n * fact nobody reads is never computed, and a word a program does not import\n * is not in its bundle.\n */\nimport {\n BATCH_DIAGNOSTIC_PARAMS,\n EMPTY_DIAGNOSTIC_PARAMS,\n snapshotDiagnosticParameters,\n} from \"@drivers/driver-diagnostics\";\nimport {\n type DriverIdentity,\n readDriverIdentity,\n} from \"@drivers/driver-identity\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport { errorOrigin } from \"../errors/logged-errors\";\nimport type { StatementUnit, UnitContext } from \"./contract\";\nimport { originOf, sourceOf } from \"./unit-source\";\n\n/**\n * The text a `statement` unit sends, as rendered for its driver; a native\n * batch's texts joined by `\"; \"`. The text of a verbatim unsafe raw query\n * too: it is never rewritten, but it is observed.\n */\nexport const text = (u: UnitContext): string | undefined => sourceOf(u)?.sql;\n\n/**\n * The snapshot the driver took for its diagnostics, or the one taken here at\n * the first read and kept where the driver keeps its own (`key` of `of`): a\n * caller's parameter is read once however many read it.\n */\nfunction shownOf(\n of: object,\n key: PropertyKey,\n params: readonly unknown[] | undefined\n): readonly unknown[] {\n const taken: unknown = Reflect.get(of, key);\n if (Array.isArray(taken) && taken !== EMPTY_DIAGNOSTIC_PARAMS) return taken;\n // Every statement the package sends states its parameters, a raw one `[]`.\n const shown = snapshotDiagnosticParameters(params!);\n Reflect.set(of, key, shown);\n return shown;\n}\n\n/**\n * A bounded snapshot of the parameters a `statement` unit sends; for a\n * native batch, one list per member. Read it before `next()`: a provider may\n * change what it was handed.\n */\nexport function parameters(u: UnitContext): readonly unknown[] | undefined {\n const source = sourceOf(u);\n if (source?.batch !== undefined)\n return source.batch.map((member) =>\n shownOf(member, BATCH_DIAGNOSTIC_PARAMS, member.params)\n );\n return source?.params === undefined\n ? undefined\n : shownOf(source, \"shown\", source.params);\n}\n\n/**\n * The dialect, name and SQL namespace of the driver doing a unit's work;\n * `undefined` for a unit with no driver, or when a custom adapter's\n * `namespace` getter throws.\n */\nexport function driver(u: UnitContext): DriverIdentity | undefined {\n const source = sourceOf(u)?.driver;\n return source === undefined ? undefined : readDriverIdentity(source);\n}\n\n/** What a unit's child failed with, once `next()` settled; else `undefined`. */\nexport const failure = (u: UnitContext): unknown => sourceOf(u)?.failure;\n\n/** The identity of the logical call a unit belongs to. */\nexport const correlation = (u: UnitContext): string | undefined =>\n sourceOf(u)?.context?.correlationId;\n\n/** The SQL name of the model an `operation` unit addresses. */\nexport const table = (u: UnitContext): string | undefined => sourceOf(u)?.table;\n\n/** One member of a native batch, as `statements(u)` gives it. */\nexport interface BatchMember {\n readonly sql: string;\n readonly parameters: readonly unknown[];\n readonly model?: string;\n readonly operation?: string;\n readonly correlation?: string;\n}\n\n/**\n * The members of a `statement` unit that sends a native batch, in order;\n * `undefined` for a unit that sends one statement. A failure that names a\n * member carries its index (`meta.statementIndex`).\n */\nexport function statements(u: UnitContext): readonly BatchMember[] | undefined {\n return sourceOf(u)?.batch?.map((member) => ({\n sql: member.sql,\n // A snapshot only when read, as `parameters(u)` takes one.\n get parameters() {\n return shownOf(member, BATCH_DIAGNOSTIC_PARAMS, member.params);\n },\n // Every member the package sends carries the context of its call.\n model: member.context?.model,\n operation: member.context?.operation,\n correlation: member.context?.correlationId,\n }));\n}\n\n/**\n * The first error of a line of successors the package made from it (a clone\n * that adds execution context or commit certainty); the error itself when it\n * has none. Two units that fail with errors of one origin failed once.\n */\nexport function origin(error: Error): Error;\nexport function origin(error: unknown): unknown;\nexport function origin(error: unknown): unknown {\n return errorOrigin(error);\n}\n\n/**\n * For a unit that rewrites statements: the statement before its rewrite, to\n * hand on, changed or not, to `next(sql)`. Always there in a part that\n * rewrites.\n */\nexport function statement(u: StatementUnit): Sql;\nexport function statement(u: UnitContext): Sql | undefined;\nexport function statement(u: UnitContext): Sql | undefined {\n return sourceOf(u)?.statement;\n}\n\n/**\n * For a `transaction` unit: runs `sql` in the transaction and gives its\n * rows. Called before `next()`, it opens the transaction and runs before\n * anything else does; the transaction's body waits for the innermost\n * `next()`. A savepoint is no transaction.\n */\nexport function run(\n u: UnitContext,\n sql: Sql\n): Promise<readonly Record<string, unknown>[]> {\n const send = sourceOf(u)?.run;\n return send === undefined\n ? Promise.reject(\n new QueryError(\"run() needs the transaction unit a unit() received.\")\n )\n : send(sql);\n}\n\n/**\n * Attach a fact to a unit that is still running: `target` is a unit (one a\n * handler received, or `work` made), or a call's `run`, which notes on the\n * call's `operation` unit. `false` when there is no such unit, or it has\n * settled (where no handler runs around a unit, nothing would read it).\n */\nexport function note(target: object, fact: unknown): boolean {\n const source = originOf(target);\n if (source === undefined || source.failed !== undefined) return false;\n source.notes?.push(fact);\n return true;\n}\n\n/** The facts noted on a unit, in order. */\nexport const notes = (u: UnitContext): readonly unknown[] =>\n sourceOf(u)?.notes ?? [];\n"],"mappings":"yYA2FA,IAAM,aAAN,KAAmC,CACjC,KACA,MACA,UACA,GACA,YAAY,EAAoB,CAC9B,KAAK,KAAO,EAAO,KACnB,KAAK,MAAQ,EAAO,MAEpB,KAAK,UAAY,OAAO,OAAO,EAAQ,YAAY,CAC/C,EAAO,UACP,EAAO,SAAS,UACpB,MAAA,EAAe,EAEjB,OAAO,SAAS,EAAsC,CACpD,MAAO,MAAW,EAAO,GAAA,EAAe,IAAA,KAS5C,MAAM,EAAa,IAAI,QAGV,SAAY,GACvB,aAAa,SAAS,EAAK,CAG7B,SAAgB,OAAO,EAA0B,CAC/C,IAAM,EAAO,IAAI,aAAa,EAAO,CAIrC,MAHA,GAAO,QAAU,EAAE,CACf,EAAO,OAAS,aAAe,EAAO,UAAY,IAAA,IACpD,EAAW,IAAI,EAAO,QAAS,EAAO,CACjC,EAOT,SAAgB,SAAS,EAAwC,CAC/D,IAAM,EAAU,EAAOC,EAAO,EAAE,IAAI,QACpC,OACE,SAASA,EAAO,GACf,IAA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EAC6C,CAC7C,IAAM,EAAO,SAAS,EAAE,EAAE,IAC1B,OAAO,IAAS,IAAA,GACZ,QAAQ,OACN,IAAI,EAAW,sDAAsD,CACtE,CACD,EAAK,EAAI,CASf,SAAgB,KAAK,EAAgB,EAAwB,CAC3D,IAAM,EAAS,SAAS,EAAO,CAG/B,OAFI,IAAW,IAAA,IAAa,EAAO,SAAW,IAAA,GAAkB,IAChE,EAAO,OAAO,KAAK,EAAK,CACjB,IAIT,MAAa,MAAS,GACpB,SAAS,EAAE,EAAE,OAAS,EAAE"}
@@ -1,4 +1,4 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t}from"./base-z-cH5ZBI.mjs";import{n}from"./suppressed-failure-CQkQsMVS.mjs";import{a as r}from"./validator-CZLW7aR3.mjs";import{existsSync as i}from"node:fs";import{resolve as a}from"node:path";import{loadEnvFile as o}from"node:process";import{createJiti as s}from"jiti";const c=[`viborm.config.ts`,`viborm.config.mts`,`viborm.config.js`,`viborm.config.mjs`];function findFile(e,t){for(let n of t){let t=a(e,n);if(i(t))return t}return null}function failCli(e,n=!1){let r=t(e),i=e instanceof Error?e.message:typeof e==`string`?e:`CLI operation failed`,a=r?e.code:void 0,o=a?.startsWith(`V11`)?Number(a.slice(1))-11e3+10:r?2:1;process.stderr.write(n?`${JSON.stringify({error:r?e.toJSON():{name:e instanceof Error?e.name:`Error`,message:i},exitCode:o})}\n`:`${a?`[${a}] `:``}${i}\n`),process.exit(o)}async function finishCli(e,t,r=!1){let i=t;try{await e?.$disconnect()}catch(e){i={value:t?n(t.value,e):e}}i&&(r?failCli(i.value,!0):failCli(i.value))}async function runCli(e,t,n){let r,i;try{let t=await loadConfig(e);r=t.client,await n(t)}catch(e){i={value:e}}finally{await finishCli(r,i,t)}}function printJson(e,t){if(t){process.stdout.write(`${JSON.stringify(e,null,2)}\n`);return}let n=[],render=(e,t=``)=>{if(Array.isArray(e)){for(let r of e)n.push(`${t}-`),render(r,`${t} `);e.length===0&&n.push(`${t}(none)`)}else if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))typeof i==`object`&&i?(n.push(`${t}${r}:`),render(i,`${t} `)):n.push(`${t}${r}: ${String(i)}`);else n.push(`${t}${String(e)}`)};render(e),process.stdout.write(`${n.join(`
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t}from"./base-z-cH5ZBI.mjs";import{n}from"./suppressed-failure-CQkQsMVS.mjs";import{a as r}from"./validator-CDYlO9HV.mjs";import{existsSync as i}from"node:fs";import{resolve as a}from"node:path";import{loadEnvFile as o}from"node:process";import{createJiti as s}from"jiti";const c=[`viborm.config.ts`,`viborm.config.mts`,`viborm.config.js`,`viborm.config.mjs`];function findFile(e,t){for(let n of t){let t=a(e,n);if(i(t))return t}return null}function failCli(e,n=!1){let r=t(e),i=e instanceof Error?e.message:typeof e==`string`?e:`CLI operation failed`,a=r?e.code:void 0,o=a?.startsWith(`V11`)?Number(a.slice(1))-11e3+10:r?2:1;process.stderr.write(n?`${JSON.stringify({error:r?e.toJSON():{name:e instanceof Error?e.name:`Error`,message:i},exitCode:o})}\n`:`${a?`[${a}] `:``}${i}\n`),process.exit(o)}async function finishCli(e,t,r=!1){let i=t;try{await e?.$disconnect()}catch(e){i={value:t?n(t.value,e):e}}i&&(r?failCli(i.value,!0):failCli(i.value))}async function runCli(e,t,n){let r,i;try{let t=await loadConfig(e);r=t.client,await n(t)}catch(e){i={value:e}}finally{await finishCli(r,i,t)}}function printJson(e,t){if(t){process.stdout.write(`${JSON.stringify(e,null,2)}\n`);return}let n=[],render=(e,t=``)=>{if(Array.isArray(e)){for(let r of e)n.push(`${t}-`),render(r,`${t} `);e.length===0&&n.push(`${t}(none)`)}else if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))typeof i==`object`&&i?(n.push(`${t}${r}:`),render(i,`${t} `)):n.push(`${t}${r}: ${String(i)}`);else n.push(`${t}${String(e)}`)};render(e),process.stdout.write(`${n.join(`
2
2
  `)}\n`)}async function loadConfig(e={}){let t=process.cwd(),n=a(t,`.env`);i(n)&&o(n);let s=e.config?a(t,e.config):findFile(t,c);if(!(s&&i(s))){let t=e.config?[e.config]:c;throw Error(`Could not find VibORM configuration file.
3
3
 
4
4
  Searched for:\n${t.map(e=>` - ${e}`).join(`
@@ -23,4 +23,4 @@ Searched for:\n${t.map(e=>` - ${e}`).join(`
23
23
  name: s.string(),
24
24
  });
25
25
  `);return e.skipValidation||r(p),{client:u.client,driver:d,models:p,migrations:u.migrations}}function loadCliModule(e){return s(e,{tsconfigPaths:!0,interopDefault:!0}).import(e)}function extractModels(e){let t={};for(let[n,r]of Object.entries(e))isModel(r)&&(t[n]=r);return t}function isModel(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`~`);if(typeof t!=`object`||!t)return!1;let n=Reflect.get(t,`state`);return typeof n==`object`&&!!n&&`scalars`in n}function isValidClient(e){return e===null||typeof e!=`object`&&typeof e!=`function`?!1:Reflect.get(e,`$driver`)!==void 0&&Reflect.get(e,`$schema`)!==void 0}function defineConfig(e){return e}export{runCli as a,printJson as i,failCli as n,loadCliModule as r,defineConfig as t};
26
- //# sourceMappingURL=utils-CpAojrCj.mjs.map
26
+ //# sourceMappingURL=utils-BLlgSQIo.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils-CpAojrCj.mjs","names":[],"sources":["../src/cli/utils.ts"],"sourcesContent":["/**\n * CLI Utilities\n *\n * Configuration loading and other CLI utilities.\n *\n * Config file pattern similar to:\n * - drizzle.config.ts\n * - prisma (uses schema.prisma but we use TS)\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { loadEnvFile } from \"node:process\";\nimport { createJiti } from \"jiti\";\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { withSuppressedFailure } from \"../drivers/shared/suppressed-failure\";\nimport { isVibORMError } from \"../errors\";\nimport type { MigrationClient } from \"../migrations/push/planner\";\nimport type { MigrationStorageWriter } from \"../migrations/storage/contract\";\nimport type { ResolveCallback } from \"../migrations/types\";\nimport type { AnyModel } from \"../schema/model\";\nimport { validateSchemaOrThrow } from \"../schema/validation\";\n\n// =============================================================================\n// CONFIG TYPES\n// =============================================================================\n\n/**\n * Migration configuration options.\n */\nexport interface MigrationConfig {\n /** Estate directory (default: \"./migrations\") */\n dir?: string;\n /** Immutable exact physical table scope; include junctions and rename destinations. */\n tables?: readonly string[];\n /** Explicit rename, destructive-change and enum-value decisions for CLI planning. */\n resolve?: ResolveCallback;\n /**\n * Estate storage writer. Defaults to filesystem storage at `dir`.\n *\n * @example\n * ```ts\n * import { createFsStorageWriter } from \"viborm/migrations/storage/fs\";\n *\n * migrations: {\n * storage: createFsStorageWriter(\"./migrations\"),\n * }\n * ```\n */\n storage?: MigrationStorageWriter;\n}\n\n/**\n * VibORM configuration file format.\n *\n * Example viborm.config.ts:\n * ```ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport interface VibORMConfig {\n /** VibORM client instance */\n client: MigrationClient & { $disconnect(): Promise<void> };\n /** Optional: Migration configuration */\n migrations?: MigrationConfig;\n}\n\nexport interface LoadConfigOptions {\n /** Path to config file (default: ./viborm.config.ts) */\n config?: string;\n /** Leave validation to the caller (`viborm check` reports every issue). */\n skipValidation?: boolean;\n /** How the config module is imported; jiti unless a runtime imports TypeScript itself. */\n importer?: (path: string) => Promise<unknown>;\n}\n\nexport interface LoadedConfig {\n client: VibORMConfig[\"client\"];\n driver: AnyDriver;\n models: Record<string, AnyModel>;\n migrations?: MigrationConfig;\n}\n\n// =============================================================================\n// CONFIG FILE DISCOVERY\n// =============================================================================\n\nconst CONFIG_FILES = [\n \"viborm.config.ts\",\n \"viborm.config.mts\",\n \"viborm.config.js\",\n \"viborm.config.mjs\",\n];\n\n/**\n * Finds the first existing file from a list of candidates.\n */\nfunction findFile(cwd: string, candidates: string[]): string | null {\n for (const candidate of candidates) {\n const fullPath = resolve(cwd, candidate);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n// =============================================================================\n// CONFIG LOADING\n// =============================================================================\n\n/**\n * Loads VibORM configuration from viborm.config.ts file.\n *\n * The config file should export a default configuration object with:\n * - client: VibORM client instance created with createClient()\n */\nexport function failCli(error: unknown, json = false): never {\n const trusted = isVibORMError(error);\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"CLI operation failed\";\n const code = trusted ? error.code : undefined;\n const exitCode = code?.startsWith(\"V11\")\n ? Number(code.slice(1)) - 11_000 + 10\n : trusted\n ? 2\n : 1;\n process.stderr.write(\n json\n ? `${JSON.stringify({ error: trusted ? error.toJSON() : { name: error instanceof Error ? error.name : \"Error\", message }, exitCode })}\\n`\n : `${code ? `[${code}] ` : \"\"}${message}\\n`\n );\n process.exit(exitCode);\n}\n\n/** Await owned CLI cleanup before reporting either the primary or cleanup failure. */\nexport async function finishCli(\n client: { $disconnect(): Promise<void> } | undefined,\n failure: { value: unknown } | undefined,\n json = false\n): Promise<void> {\n let outcome = failure;\n try {\n await client?.$disconnect();\n } catch (cleanup) {\n outcome = {\n value: failure ? withSuppressedFailure(failure.value, cleanup) : cleanup,\n };\n }\n if (outcome) {\n if (json) failCli(outcome.value, true);\n else failCli(outcome.value);\n }\n}\n\n/** Every command's frame: load the config, own its client, report through {@link finishCli}. */\nexport async function runCli(\n load: LoadConfigOptions,\n json: boolean | undefined,\n body: (config: LoadedConfig) => Promise<void>\n): Promise<void> {\n let client: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig(load);\n client = config.client;\n await body(config);\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, json);\n }\n}\n\n/** JSON for `--json`, else an indented outline of the same value. */\nexport function printJson(value: unknown, json: boolean): void {\n if (json) {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n return;\n }\n const lines: string[] = [];\n const render = (item: unknown, indent = \"\") => {\n if (Array.isArray(item)) {\n for (const entry of item) {\n lines.push(`${indent}-`);\n render(entry, `${indent} `);\n }\n if (item.length === 0) lines.push(`${indent}(none)`);\n } else if (item !== null && typeof item === \"object\") {\n for (const [key, entry] of Object.entries(item)) {\n if (entry !== null && typeof entry === \"object\") {\n lines.push(`${indent}${key}:`);\n render(entry, `${indent} `);\n } else lines.push(`${indent}${key}: ${String(entry)}`);\n }\n } else lines.push(`${indent}${String(item)}`);\n };\n render(value);\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport async function loadConfig(\n options: LoadConfigOptions = {}\n): Promise<LoadedConfig> {\n const cwd = process.cwd();\n const envPath = resolve(cwd, \".env\");\n if (existsSync(envPath)) loadEnvFile(envPath);\n\n // Find config file\n const configPath = options.config\n ? resolve(cwd, options.config)\n : findFile(cwd, CONFIG_FILES);\n\n if (!(configPath && existsSync(configPath))) {\n const searchedPaths = options.config ? [options.config] : CONFIG_FILES;\n\n throw new Error(\n \"Could not find VibORM configuration file.\\n\\n\" +\n `Searched for:\\n${searchedPaths.map((f) => ` - ${f}`).join(\"\\n\")}\\n\\n` +\n \"Create a viborm.config.ts file:\\n\\n\" +\n ` import { defineConfig } from \"viborm/config\";\\n` +\n ` import { client } from \"./src/db\";\\n\\n` +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n // Load the config file\n const configModule = (await (options.importer ?? loadCliModule)(\n configPath\n )) as VibORMConfig & { default?: VibORMConfig; config?: VibORMConfig };\n\n // Extract config (handle both default export and named export)\n const config: VibORMConfig =\n (Object.hasOwn(configModule, \"default\") && configModule.default) ||\n configModule.config ||\n configModule;\n\n // Validate client\n if (!config.client) {\n throw new Error(\n `Missing \"client\" in ${configPath}.\\n\\n` +\n \"Your config should include a VibORM client:\\n\\n\" +\n ` import { createClient } from \"viborm\";\\n` +\n \" const client = createClient({ driver, schema });\\n\\n\" +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n if (!isValidClient(config.client)) {\n throw new Error(\n `Invalid \"client\" in ${configPath}.\\n\\n` +\n \"The client must be created with createClient().\\n\"\n );\n }\n\n // Extract driver and schema from client\n const driver = config.client.$driver;\n const schemaInput = config.client.$schema;\n\n // Extract models from schema (filter out non-model exports)\n const models = extractModels(schemaInput);\n\n if (Object.keys(models).length === 0) {\n throw new Error(\n `No models found in client schema from ${configPath}.\\n\\n` +\n \"Make sure your client was created with schema models:\\n\\n\" +\n \" // src/schema.ts\\n\" +\n ` import { s } from \"viborm\";\\n\\n` +\n \" export const user = s.model({\\n\" +\n \" id: s.string().id(),\\n\" +\n \" name: s.string(),\\n\" +\n \" });\\n\"\n );\n }\n\n // Validate schema before proceeding\n if (!options.skipValidation) validateSchemaOrThrow(models);\n\n return {\n client: config.client,\n driver,\n models,\n migrations: config.migrations,\n };\n}\n\n/**\n * Dynamically imports a TypeScript/JavaScript module.\n */\nexport function loadCliModule<T>(filePath: string): Promise<T> {\n // Dependency imports need CJS interop; consumers select only authored defaults.\n return createJiti(filePath, {\n tsconfigPaths: true,\n interopDefault: true,\n }).import<T>(filePath);\n}\n\n/**\n * Extracts model objects from a module by checking for Model instances.\n */\nfunction extractModels(\n schema: Record<string, unknown>\n): Record<string, AnyModel> {\n const models: Record<string, AnyModel> = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (isModel(value)) {\n models[key] = value;\n }\n }\n\n return models;\n}\n\n/**\n * Checks if a value is a VibORM Model instance.\n */\nfunction isModel(value: unknown): value is AnyModel {\n if (value === null || typeof value !== \"object\") return false;\n const metadata = Reflect.get(value, \"~\");\n if (metadata === null || typeof metadata !== \"object\") return false;\n const state = Reflect.get(metadata, \"state\");\n // Model state exposes `scalars`/`relations` (never `fields`); the rest of\n // the codebase discriminates models the same way (see serializer).\n return state !== null && typeof state === \"object\" && \"scalars\" in state;\n}\n\n/**\n * Checks if a value is a valid VibORM client instance.\n */\nfunction isValidClient(value: unknown): boolean {\n // The client is a Proxy whose only trap is `get`, so `\"$driver\" in value`\n // (which triggers the `has` trap / falls back to the bare target) is always\n // false. Probe via property access instead.\n // `typeof null === \"object\"`, so null has to be refused here: Reflect.get\n // throws on it rather than answering undefined.\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return false;\n }\n return (\n Reflect.get(value, \"$driver\") !== undefined &&\n Reflect.get(value, \"$schema\") !== undefined\n );\n}\n\n// =============================================================================\n// DEFINE CONFIG HELPER\n// =============================================================================\n\n/**\n * Helper function for defining VibORM configuration with type safety.\n *\n * @example\n * ```ts\n * // viborm.config.ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport function defineConfig<const C extends VibORMConfig>(\n config: C &\n Record<Exclude<keyof C, keyof VibORMConfig>, never> &\n (C extends { migrations: infer M }\n ? {\n migrations: M &\n Record<Exclude<keyof M, keyof MigrationConfig>, never>;\n }\n : unknown)\n): C {\n return config;\n}\n"],"mappings":"qUA4FA,MAAM,EAAe,CACnB,mBACA,oBACA,mBACA,oBACD,CAKD,SAAS,SAAS,EAAa,EAAqC,CAClE,IAAK,IAAM,KAAa,EAAY,CAClC,IAAM,EAAW,EAAQ,EAAK,EAAU,CACxC,GAAI,EAAW,EAAS,CACtB,OAAO,EAGX,OAAO,KAaT,SAAgB,QAAQ,EAAgB,EAAO,GAAc,CAC3D,IAAM,EAAU,EAAc,EAAM,CAC9B,EACJ,aAAiB,MACb,EAAM,QACN,OAAO,GAAU,SACf,EACA,uBACF,EAAO,EAAU,EAAM,KAAO,IAAA,GAC9B,EAAW,GAAM,WAAW,MAAM,CACpC,OAAO,EAAK,MAAM,EAAE,CAAC,CAAG,KAAS,GACjC,EACE,EACA,EACN,QAAQ,OAAO,MACb,EACI,GAAG,KAAK,UAAU,CAAE,MAAO,EAAU,EAAM,QAAQ,CAAG,CAAE,KAAM,aAAiB,MAAQ,EAAM,KAAO,QAAS,UAAS,CAAE,WAAU,CAAC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AO,CAC3C,QAAQ,EAAM,GAChB,EAAO,GAAO,GAIlB,OAAO,EAMT,SAAS,QAAQ,EAAmC,CAClD,GAAsB,OAAO,GAAU,WAAnC,EAA6C,MAAO,GACxD,IAAM,EAAW,QAAQ,IAAI,EAAO,IAAI,CACxC,GAAyB,OAAO,GAAa,WAAzC,EAAmD,MAAO,GAC9D,IAAM,EAAQ,QAAQ,IAAI,EAAU,QAAQ,CAG5C,OAAyB,OAAO,GAAU,YAAnC,GAA+C,YAAa,EAMrE,SAAS,cAAc,EAAyB,CAY9C,OALE,IAAU,MACT,OAAO,GAAU,UAAY,OAAO,GAAU,WAExC,GAGP,QAAQ,IAAI,EAAO,UAAU,GAAK,IAAA,IAClC,QAAQ,IAAI,EAAO,UAAU,GAAK,IAAA,GAsBtC,SAAgB,aACd,EAQG,CACH,OAAO"}
1
+ {"version":3,"file":"utils-BLlgSQIo.mjs","names":[],"sources":["../src/cli/utils.ts"],"sourcesContent":["/**\n * CLI Utilities\n *\n * Configuration loading and other CLI utilities.\n *\n * Config file pattern similar to:\n * - drizzle.config.ts\n * - prisma (uses schema.prisma but we use TS)\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { loadEnvFile } from \"node:process\";\nimport { createJiti } from \"jiti\";\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { withSuppressedFailure } from \"../drivers/shared/suppressed-failure\";\nimport { isVibORMError } from \"../errors\";\nimport type { MigrationClient } from \"../migrations/push/planner\";\nimport type { MigrationStorageWriter } from \"../migrations/storage/contract\";\nimport type { ResolveCallback } from \"../migrations/types\";\nimport type { AnyModel } from \"../schema/model\";\nimport { validateSchemaOrThrow } from \"../schema/validation\";\n\n// =============================================================================\n// CONFIG TYPES\n// =============================================================================\n\n/**\n * Migration configuration options.\n */\nexport interface MigrationConfig {\n /** Estate directory (default: \"./migrations\") */\n dir?: string;\n /** Immutable exact physical table scope; include junctions and rename destinations. */\n tables?: readonly string[];\n /** Explicit rename, destructive-change and enum-value decisions for CLI planning. */\n resolve?: ResolveCallback;\n /**\n * Estate storage writer. Defaults to filesystem storage at `dir`.\n *\n * @example\n * ```ts\n * import { createFsStorageWriter } from \"viborm/migrations/storage/fs\";\n *\n * migrations: {\n * storage: createFsStorageWriter(\"./migrations\"),\n * }\n * ```\n */\n storage?: MigrationStorageWriter;\n}\n\n/**\n * VibORM configuration file format.\n *\n * Example viborm.config.ts:\n * ```ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport interface VibORMConfig {\n /** VibORM client instance */\n client: MigrationClient & { $disconnect(): Promise<void> };\n /** Optional: Migration configuration */\n migrations?: MigrationConfig;\n}\n\nexport interface LoadConfigOptions {\n /** Path to config file (default: ./viborm.config.ts) */\n config?: string;\n /** Leave validation to the caller (`viborm check` reports every issue). */\n skipValidation?: boolean;\n /** How the config module is imported; jiti unless a runtime imports TypeScript itself. */\n importer?: (path: string) => Promise<unknown>;\n}\n\nexport interface LoadedConfig {\n client: VibORMConfig[\"client\"];\n driver: AnyDriver;\n models: Record<string, AnyModel>;\n migrations?: MigrationConfig;\n}\n\n// =============================================================================\n// CONFIG FILE DISCOVERY\n// =============================================================================\n\nconst CONFIG_FILES = [\n \"viborm.config.ts\",\n \"viborm.config.mts\",\n \"viborm.config.js\",\n \"viborm.config.mjs\",\n];\n\n/**\n * Finds the first existing file from a list of candidates.\n */\nfunction findFile(cwd: string, candidates: string[]): string | null {\n for (const candidate of candidates) {\n const fullPath = resolve(cwd, candidate);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n// =============================================================================\n// CONFIG LOADING\n// =============================================================================\n\n/**\n * Loads VibORM configuration from viborm.config.ts file.\n *\n * The config file should export a default configuration object with:\n * - client: VibORM client instance created with createClient()\n */\nexport function failCli(error: unknown, json = false): never {\n const trusted = isVibORMError(error);\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"CLI operation failed\";\n const code = trusted ? error.code : undefined;\n const exitCode = code?.startsWith(\"V11\")\n ? Number(code.slice(1)) - 11_000 + 10\n : trusted\n ? 2\n : 1;\n process.stderr.write(\n json\n ? `${JSON.stringify({ error: trusted ? error.toJSON() : { name: error instanceof Error ? error.name : \"Error\", message }, exitCode })}\\n`\n : `${code ? `[${code}] ` : \"\"}${message}\\n`\n );\n process.exit(exitCode);\n}\n\n/** Await owned CLI cleanup before reporting either the primary or cleanup failure. */\nexport async function finishCli(\n client: { $disconnect(): Promise<void> } | undefined,\n failure: { value: unknown } | undefined,\n json = false\n): Promise<void> {\n let outcome = failure;\n try {\n await client?.$disconnect();\n } catch (cleanup) {\n outcome = {\n value: failure ? withSuppressedFailure(failure.value, cleanup) : cleanup,\n };\n }\n if (outcome) {\n if (json) failCli(outcome.value, true);\n else failCli(outcome.value);\n }\n}\n\n/** Every command's frame: load the config, own its client, report through {@link finishCli}. */\nexport async function runCli(\n load: LoadConfigOptions,\n json: boolean | undefined,\n body: (config: LoadedConfig) => Promise<void>\n): Promise<void> {\n let client: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig(load);\n client = config.client;\n await body(config);\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, json);\n }\n}\n\n/** JSON for `--json`, else an indented outline of the same value. */\nexport function printJson(value: unknown, json: boolean): void {\n if (json) {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n return;\n }\n const lines: string[] = [];\n const render = (item: unknown, indent = \"\") => {\n if (Array.isArray(item)) {\n for (const entry of item) {\n lines.push(`${indent}-`);\n render(entry, `${indent} `);\n }\n if (item.length === 0) lines.push(`${indent}(none)`);\n } else if (item !== null && typeof item === \"object\") {\n for (const [key, entry] of Object.entries(item)) {\n if (entry !== null && typeof entry === \"object\") {\n lines.push(`${indent}${key}:`);\n render(entry, `${indent} `);\n } else lines.push(`${indent}${key}: ${String(entry)}`);\n }\n } else lines.push(`${indent}${String(item)}`);\n };\n render(value);\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport async function loadConfig(\n options: LoadConfigOptions = {}\n): Promise<LoadedConfig> {\n const cwd = process.cwd();\n const envPath = resolve(cwd, \".env\");\n if (existsSync(envPath)) loadEnvFile(envPath);\n\n // Find config file\n const configPath = options.config\n ? resolve(cwd, options.config)\n : findFile(cwd, CONFIG_FILES);\n\n if (!(configPath && existsSync(configPath))) {\n const searchedPaths = options.config ? [options.config] : CONFIG_FILES;\n\n throw new Error(\n \"Could not find VibORM configuration file.\\n\\n\" +\n `Searched for:\\n${searchedPaths.map((f) => ` - ${f}`).join(\"\\n\")}\\n\\n` +\n \"Create a viborm.config.ts file:\\n\\n\" +\n ` import { defineConfig } from \"viborm/config\";\\n` +\n ` import { client } from \"./src/db\";\\n\\n` +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n // Load the config file\n const configModule = (await (options.importer ?? loadCliModule)(\n configPath\n )) as VibORMConfig & { default?: VibORMConfig; config?: VibORMConfig };\n\n // Extract config (handle both default export and named export)\n const config: VibORMConfig =\n (Object.hasOwn(configModule, \"default\") && configModule.default) ||\n configModule.config ||\n configModule;\n\n // Validate client\n if (!config.client) {\n throw new Error(\n `Missing \"client\" in ${configPath}.\\n\\n` +\n \"Your config should include a VibORM client:\\n\\n\" +\n ` import { createClient } from \"viborm\";\\n` +\n \" const client = createClient({ driver, schema });\\n\\n\" +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n if (!isValidClient(config.client)) {\n throw new Error(\n `Invalid \"client\" in ${configPath}.\\n\\n` +\n \"The client must be created with createClient().\\n\"\n );\n }\n\n // Extract driver and schema from client\n const driver = config.client.$driver;\n const schemaInput = config.client.$schema;\n\n // Extract models from schema (filter out non-model exports)\n const models = extractModels(schemaInput);\n\n if (Object.keys(models).length === 0) {\n throw new Error(\n `No models found in client schema from ${configPath}.\\n\\n` +\n \"Make sure your client was created with schema models:\\n\\n\" +\n \" // src/schema.ts\\n\" +\n ` import { s } from \"viborm\";\\n\\n` +\n \" export const user = s.model({\\n\" +\n \" id: s.string().id(),\\n\" +\n \" name: s.string(),\\n\" +\n \" });\\n\"\n );\n }\n\n // Validate schema before proceeding\n if (!options.skipValidation) validateSchemaOrThrow(models);\n\n return {\n client: config.client,\n driver,\n models,\n migrations: config.migrations,\n };\n}\n\n/**\n * Dynamically imports a TypeScript/JavaScript module.\n */\nexport function loadCliModule<T>(filePath: string): Promise<T> {\n // Dependency imports need CJS interop; consumers select only authored defaults.\n return createJiti(filePath, {\n tsconfigPaths: true,\n interopDefault: true,\n }).import<T>(filePath);\n}\n\n/**\n * Extracts model objects from a module by checking for Model instances.\n */\nfunction extractModels(\n schema: Record<string, unknown>\n): Record<string, AnyModel> {\n const models: Record<string, AnyModel> = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (isModel(value)) {\n models[key] = value;\n }\n }\n\n return models;\n}\n\n/**\n * Checks if a value is a VibORM Model instance.\n */\nfunction isModel(value: unknown): value is AnyModel {\n if (value === null || typeof value !== \"object\") return false;\n const metadata = Reflect.get(value, \"~\");\n if (metadata === null || typeof metadata !== \"object\") return false;\n const state = Reflect.get(metadata, \"state\");\n // Model state exposes `scalars`/`relations` (never `fields`); the rest of\n // the codebase discriminates models the same way (see serializer).\n return state !== null && typeof state === \"object\" && \"scalars\" in state;\n}\n\n/**\n * Checks if a value is a valid VibORM client instance.\n */\nfunction isValidClient(value: unknown): boolean {\n // The client is a Proxy whose only trap is `get`, so `\"$driver\" in value`\n // (which triggers the `has` trap / falls back to the bare target) is always\n // false. Probe via property access instead.\n // `typeof null === \"object\"`, so null has to be refused here: Reflect.get\n // throws on it rather than answering undefined.\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return false;\n }\n return (\n Reflect.get(value, \"$driver\") !== undefined &&\n Reflect.get(value, \"$schema\") !== undefined\n );\n}\n\n// =============================================================================\n// DEFINE CONFIG HELPER\n// =============================================================================\n\n/**\n * Helper function for defining VibORM configuration with type safety.\n *\n * @example\n * ```ts\n * // viborm.config.ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport function defineConfig<const C extends VibORMConfig>(\n config: C &\n Record<Exclude<keyof C, keyof VibORMConfig>, never> &\n (C extends { migrations: infer M }\n ? {\n migrations: M &\n Record<Exclude<keyof M, keyof MigrationConfig>, never>;\n }\n : unknown)\n): C {\n return config;\n}\n"],"mappings":"qUA4FA,MAAM,EAAe,CACnB,mBACA,oBACA,mBACA,oBACD,CAKD,SAAS,SAAS,EAAa,EAAqC,CAClE,IAAK,IAAM,KAAa,EAAY,CAClC,IAAM,EAAW,EAAQ,EAAK,EAAU,CACxC,GAAI,EAAW,EAAS,CACtB,OAAO,EAGX,OAAO,KAaT,SAAgB,QAAQ,EAAgB,EAAO,GAAc,CAC3D,IAAM,EAAU,EAAc,EAAM,CAC9B,EACJ,aAAiB,MACb,EAAM,QACN,OAAO,GAAU,SACf,EACA,uBACF,EAAO,EAAU,EAAM,KAAO,IAAA,GAC9B,EAAW,GAAM,WAAW,MAAM,CACpC,OAAO,EAAK,MAAM,EAAE,CAAC,CAAG,KAAS,GACjC,EACE,EACA,EACN,QAAQ,OAAO,MACb,EACI,GAAG,KAAK,UAAU,CAAE,MAAO,EAAU,EAAM,QAAQ,CAAG,CAAE,KAAM,aAAiB,MAAQ,EAAM,KAAO,QAAS,UAAS,CAAE,WAAU,CAAC,CAAC,IACpI,GAAG,EAAO,IAAI,EAAK,IAAM,KAAK,EAAQ,IAC3C,CACD,QAAQ,KAAK,EAAS,CAIxB,eAAsB,UACpB,EACA,EACA,EAAO,GACQ,CACf,IAAI,EAAU,EACd,GAAI,CACF,MAAM,GAAQ,aAAa,OACpB,EAAS,CAChB,EAAU,CACR,MAAO,EAAU,EAAsB,EAAQ,MAAO,EAAQ,CAAG,E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AAQ,CAG5C,OAAyB,OAAO,GAAU,YAAnC,GAA+C,YAAa,EAMrE,SAAS,cAAc,EAAyB,CAY9C,OALE,IAAU,MACT,OAAO,GAAU,UAAY,OAAO,GAAU,WAExC,GAGP,QAAQ,IAAI,EAAO,UAAU,GAAK,IAAA,IAClC,QAAQ,IAAI,EAAO,UAAU,GAAK,IAAA,GAsBtC,SAAgB,aACd,EAQG,CACH,OAAO"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,t as n}from"./validation--qS7OPmg.mjs";import{r}from"./sql-BGjAsoBE.mjs";import{i,o as a,s as o}from"./value-guards-CBuxSC66.mjs";import{$ as s,J as c,X as l,Y as u,Z as d,et as f,h as p,lt as m,m as h,nt as ee,q as g}from"./native-types-DspZ0Z5E.mjs";import{$ as _,B as v,G as y,H as b,K as te,V as x,W as ne,X as re,q as ie,st as S,z as C}from"./scalar-B9WizsvR.mjs";import{f as ae,h as oe,n as se}from"./validator-CDYlO9HV.mjs";import{t as ce}from"./hydration-D7U8HACL.mjs";import{i as le,r as ue}from"./physical-wboFLAg9.mjs";import{t as de}from"./current-DBTlPsQg.mjs";import{t as w}from"./types-DtDnXhwa.mjs";import{n as fe}from"./geo-area-codec-BDvW7IH-.mjs";const slotMayBeEmpty=e=>{let t=e.edge;return t.kind===`junction`||t.kind===`variantJunctionCarrier`?!0:t.kind===`variantRowCarrier`?isSlot(t.carrier,e.slot)?t.storage.typeColumn.nullable:!0:isSlot(t.owner,e.slot)?nullableForeignFields(t).length>0:!0},clearableMembership=e=>{let t=e.edge;if(t.kind===`junction`||t.kind===`variantJunctionCarrier`)return{kind:`junctionRow`};if(t.kind===`variantRowCarrier`)return t.storage.typeColumn.nullable?{kind:`columns`,fields:[t.storage.typeColumn.name,t.storage.idColumn.name]}:{kind:`none`};let[n,...r]=nullableForeignFields(t);return n?{kind:`columns`,fields:[n,...r]}:{kind:`none`}},membershipCanBeCleared=e=>clearableMembership(e).kind!==`none`;function isSlot(e,t){return e.source===t.source&&e.field===t.field}function nullableForeignFields(e){let t=e.owner.source[`~`].state.scalars;return e.reference.members.map(e=>e.foreignField).filter(e=>t[e]?.[`~`].state.nullable===!0)}function lazyRecord(e){let t={};for(let n of Object.keys(e)){let r=e[n],i;Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get(){return r&&=(i=r(),void 0),i}})}return t}var pe=class LazyScalarSchemas{base;#e;#t;#n;constructor(e){this.base=e.base,this.#e={build:e.create},this.#t={build:e.update},this.#n={build:e.filter},Object.defineProperties(this,{create:{enumerable:!0,configurable:!0,get:LazyScalarSchemas.#r},update:{enumerable:!0,configurable:!0,get:LazyScalarSchemas.#i},filter:{enumerable:!0,configurable:!0,get:LazyScalarSchemas.#a}})}static#r(){if(`value`in this.#e)return this.#e.value;let e=this.#e.build();return this.#e={value:e},e}static#i(){if(`value`in this.#t)return this.#t.value;let e=this.#t.build();return this.#t={value:e},e}static#a(){if(`value`in this.#n)return this.#n.value;let e=this.#n.build();return this.#n={value:e},e}};function lazyScalarSchemas(e){return new pe(e)}const T=v.enum([`asc`,`desc`]),me=v.enum([`l2`,`cosine`]),forbiddenOrderByKeySchema=e=>v.refused(`OrderBy key '${e}' is not valid here.`),E=v.union([T,v.object({sort:T,nulls:v.enum([`first`,`last`]),_distance:forbiddenOrderByKeySchema(`_distance`)},{atLeast:[`sort`]})]),he=v.object({_distance:v.object({to:v.array(v.number()),metric:me,sort:T,approximate:v.boolean()},{atLeast:[`to`,`metric`]}),sort:forbiddenOrderByKeySchema(`sort`),nulls:forbiddenOrderByKeySchema(`nulls`)},{atLeast:[`_distance`]}),ge=v.object({_distance:v.object({to:v.point(),sort:T},{partial:!1}),sort:forbiddenOrderByKeySchema(`sort`),nulls:forbiddenOrderByKeySchema(`nulls`)},{atLeast:[`_distance`]}),D=v.union([E,he]),isOrderableScalarState=e=>e.type!==`point`&&(e.type!==`decimal`||e.array!==!0),O=v.refused(`A decimal list cannot be used for numeric ordering.`);function isDecimalListScalarKey(e,t){let n=e[`~`].state.scalars[t][`~`].state;return n.type===`decimal`&&n.array===!0}const getOrderBySchema=(e,t)=>{let n=[],r=[],i=[],a=[],o=Object.keys(e[`~`].state.scalars);for(let t of o){if(isDecimalListScalarKey(e,t)){a.push(t);continue}let o=e[`~`].state.scalars[t][`~`].state;if(o.type===`vector`){n.push(t);continue}if(o.type===`point`){r.push(t);continue}i.push(t)}let s=x(i,E),c=x(n,D),l=x(r,ge),u=x(a,O),d=S(t.relations,`orderBy`),f=S(t.polymorphic,`orderBy`),p=v.object({...s,...c,...l,...u,...d,...f}),m=v.noOperandExpression(p,`'orderBy'`);return Reflect.set(p[`~standard`],`validate`,m[`~standard`].validate),p},paginationTake=()=>v.integer();function nonNegativeInteger(e){return g(`integer`,t=>{let n=h(t);return n.issues?n:n.value<0?c(e):n})}const paginationSkip=()=>nonNegativeInteger(`skip must be greater than or equal to 0`),bulkWriteLimit=()=>nonNegativeInteger(`limit must be greater than or equal to 0`),_e=[`day`,`week`,`month`,`quarter`,`year`],groupedColumn=e=>{if(typeof e==`string`)return{field:e};let[t,n]=Object.entries(e)[0];return{field:t,step:n}},ve=/^[A-Z][A-Za-z_]*(?:\/[A-Za-z0-9_+-]+)+$/,ye=/^Etc\/GMT[+-]/,k=new Set([`UTC`]),isTimeZoneName=e=>{if(k.has(e))return!0;if(!ve.test(e)||ye.test(e))return!1;try{Intl.DateTimeFormat(`en-US`,{timeZone:e})}catch{return!1}return k.add(e),!0},timeStepUnsupported=()=>new t(`groupBy`,`timeStep`,`Grouping by a time step is supported on PostgreSQL only.`),be=[`int`,`number`,`decimal`,`bigint`],isSummableScalar=e=>e.array!==!0&&be.includes(e.type),getAggregateScalarSchemas=t=>{let n=t[`~`].state,r=[`_all`],i=[],a=[],o=[],s=[];for(let e of Object.keys(n.scalars)){let t=n.scalars[e];r.push(e),isSummableScalar(t[`~`].state)&&i.push(e),t[`~`].state.array!==!0&&t[`~`].state.type!==`point`&&a.push(e),t[`~`].state.array===!0&&o.push(e),t[`~`].state.type===`point`&&s.push(e)}let c=v.boolean({optional:!0}),l=e(e=>v.fromKeys(o,v.refused(`A list cannot be projected by '${e}'; only '_count' is supported.`)),`projection`),pointProjection=e=>v.fromKeys(s,v.refused(`A GeoPoint cannot be projected by '${e}'; use a distance projection or '_count'.`));return{count:v.fromKeys(r,c),avg:v.object({...v.fromKeys(i,c).entries,...l(`_avg`).entries,...pointProjection(`_avg`).entries}),sum:v.object({...v.fromKeys(i,c).entries,...l(`_sum`).entries,...pointProjection(`_sum`).entries}),min:v.object({...v.fromKeys(a,c).entries,...l(`_min`).entries,...pointProjection(`_min`).entries}),max:v.object({...v.fromKeys(a,c).entries,...l(`_max`).entries,...pointProjection(`_max`).entries})}},getCountArgs=(e,t)=>{let n=getAggregateScalarSchemas(e);return v.object({where:v.lazyRef(()=>t.where),orderBy:v.lazyRef(()=>v.union([t.orderBy,v.array(t.orderBy)])),cursor:v.lazyRef(()=>t.whereUnique),take:paginationTake(),skip:paginationSkip(),select:n.count},{optional:!0})},getExistArgs=e=>v.object({where:v.lazyRef(()=>e.where)},{optional:!0}),getAggregateArgs=(e,t)=>{let n=getAggregateScalarSchemas(e);return v.object({where:v.lazyRef(()=>t.where),orderBy:v.lazyRef(()=>v.union([t.orderBy,v.array(t.orderBy)])),cursor:v.lazyRef(()=>t.whereUnique),take:paginationTake(),skip:paginationSkip(),_count:v.union([v.literal(!0),n.count]),_avg:n.avg,_sum:n.sum,_min:n.min,_max:n.max})},buildAggregateFilterOps=(e,t)=>v.object({equals:t(),in:v.array(e()),notIn:v.array(e()),gt:e(),gte:e(),lt:e(),lte:e(),not:t()},{optional:!0}),A=buildAggregateFilterOps(()=>v.number(),()=>v.number({nullable:!0})),j=v.object({equals:v.literal(null),not:v.literal(null)},{optional:!0}),isRuntimeListFilterSchema=e=>{if(e.type!==`union`)return!1;let t=Reflect.get(e,`options`);if(!Array.isArray(t)||t.length!==2)return!1;let n=t[1];return typeof n==`object`&&!!n&&Reflect.get(n,`type`)===`object`},listHavingSchema=e=>{let refusal=e=>v.refused(`A list cannot use '${e}' in having; only '_count' is supported.`),t={_count:A,_avg:refusal(`_avg`),_sum:refusal(`_sum`),_min:refusal(`_min`),_max:refusal(`_max`)};return isRuntimeListFilterSchema(e)?v.noOperandExpression(v.union([e.options[0],e.options[1].extend(t)]),`'having'`):v.refused(`The list filter schema cannot be used in having because its trusted shape is unavailable.`)},sumOperandDomain=e=>({precision:2**53-1,scale:e.scale}),havingAggregateSchema=(e,t)=>{let n=e?.type===`decimal`?e.decimal:void 0;if(!n)return v.object({_count:A,_avg:e&&isSummableScalar(e)?A:v.refused(`Only numeric scalars support '_avg' in having.`),_sum:e&&isSummableScalar(e)?A:v.refused(`Only numeric scalars support '_sum' in having.`),_min:v.union([t,j]),_max:v.union([t,j])},{optional:!0});let r=buildAggregateFilterOps(()=>v.decimal({decimal:n}),()=>v.decimal({decimal:n,nullable:!0})),i=sumOperandDomain(n);return v.object({_count:A,_avg:r,_sum:buildAggregateFilterOps(()=>v.decimal({decimal:i}),()=>v.decimal({decimal:i,nullable:!0})),_min:r,_max:r},{optional:!0})};function getHavingSchema(e,t){let n={};for(let[r,i]of Object.entries(t.scalars)){let t=e[`~`].state.scalars[r]?.[`~`].state;if(t?.type===`point`){n[r]=v.refused(`A GeoPoint cannot be used in 'having'.`);continue}n[r]=t?.array===!0?listHavingSchema(i.filter):v.noOperandExpression(v.union([havingAggregateSchema(t,i.filter),i.filter]),`'having'`)}let r=v.object({AND:()=>v.optional(v.union([r,v.array(r)])),OR:()=>v.optional(v.array(r)),NOT:()=>v.optional(v.union([r,v.array(r)]))},{optional:!0}).extend(n);return b(r,e)}const M=v.enum([`asc`,`desc`]),getGroupByOrderBySchema=e=>{let t=e[`~`].state,n=[],r=[],i=[],a=[],o=[],s=[],c=[];for(let e of Object.keys(t.scalars)){let l=t.scalars[e];n.push(e),l[`~`].state.array===!0&&a.push(e),l[`~`].state.type===`point`?c.push(e):isOrderableScalarState(l[`~`].state)?r.push(e):i.push(e),isSummableScalar(l[`~`].state)&&o.push(e),l[`~`].state.array!==!0&&l[`~`].state.type!==`point`&&s.push(e)}let aggregateOrder=(e,t)=>v.object({...v.fromKeys(t,M).entries,...v.fromKeys(a,v.refused(`A list cannot be ordered by '${e}'; only '_count' is supported.`)).entries,...v.fromKeys(c,v.refused(`A GeoPoint cannot be ordered by '${e}'; use '_distance' or '_count'.`)).entries});return v.object({...v.fromKeys(r,E).entries,...v.fromKeys(i,O).entries,_count:v.fromKeys([`_all`,...n],M),_avg:aggregateOrder(`_avg`,o),_sum:aggregateOrder(`_sum`,o),_min:aggregateOrder(`_min`,s),_max:aggregateOrder(`_max`,s)})},N=[`_avg`,`_sum`,`_min`,`_max`],groupByCollisions=e=>{let t=e.by.map(e=>groupedColumn(e).field);if(new Set(t).size!==t.length)return`GroupBy operation does not allow duplicate fields in 'by'`;for(let n of N)if(e[n]!==void 0&&t.includes(n))return`Aggregate '${n}' cannot be selected together with a model field named '${n}'.`},P=new Set([`_count`,...N]),xe=new Set([`AND`,`OR`,`NOT`]),uncomparedHavingPath=(e,t,n)=>{for(let[r,i]of Object.entries(e??{}))if(i!==void 0){if(xe.has(r)&&!Object.hasOwn(n,r)){let e=Array.isArray(i)?i:[i];for(let[a,o]of e.entries()){let e=uncomparedHavingPath(o,t,n);if(e)return Array.isArray(i)?[r,a,...e]:[r,...e]}continue}if(!t(r)&&!(a(i)&&Object.entries(i).some(([e,t])=>t!==void 0&&P.has(e))))return[r]}},groupedMembershipIssue=({by:e,having:t,orderBy:n},r)=>{if(e.length===0)return{message:`groupBy needs at least one field in 'by'.`,path:[`by`]};let i=e.map(groupedColumn),a=i.map(e=>e.field),o=uncomparedHavingPath(t,e=>a.includes(e),r);if(o)return{message:`Scalar '${String(o.at(-1))}' used in 'having' must be included in 'by'.`,path:[`having`,...o]};let s=uncomparedHavingPath(t,e=>!i.some(t=>t.field===e&&t.step),r);if(s)return{message:`'having' cannot compare '${String(s.at(-1))}', grouped by a time step; filter it in 'where'.`,path:[`having`,...s]};let c=Array.isArray(n)?n:[n];for(let[e,t]of c.entries())for(let[r,i]of Object.entries(t??{}))if(!(i===void 0||a.includes(r))&&!P.has(r))return{message:`GroupBy orderBy field '${r}' must be included in 'by' or be an aggregate (_count, _avg, _sum, _min, _max).`,path:Array.isArray(n)?[`orderBy`,e,r]:[`orderBy`,r]}},Se=g(`string`,e=>typeof e==`string`&&isTimeZoneName(e)?u(e):c(`'timeZone' takes an IANA name such as 'America/Montreal', not an offset or an abbreviation.`)),getGroupByArgs=(e,t,n)=>{let r=e[`~`].state,i=Object.keys(r.scalars).filter(e=>r.scalars[e][`~`].state.type!==`point`),a=v.enum(i),o=v.enum(_e),s=v.object(Object.fromEntries(i.map(e=>{let{type:t,array:n}=r.scalars[e][`~`].state;return[e,(t===`date`||t===`datetime`)&&n!==!0?o:v.refused(`'${e}' is not a date or dateTime column.`)]})),{refuse:e=>{let[t,n]=Object.keys(e);if(!(t!==void 0&&n===void 0))return{message:`A time step names one column: { date: "month" }.`,path:n===void 0?[]:[n]}}}),c=v.union([a,s]),l=getAggregateScalarSchemas(e),u=getHavingSchema(e,t),d=getGroupByOrderBySchema(e);return v.object({by:v.union([v.array(c),v.shorthandArray(c)]),timeZone:Se,where:v.lazyRef(()=>n.where),having:u,orderBy:v.union([d,v.array(d)]),take:paginationTake(),skip:paginationSkip(),_count:v.union([v.literal(!0),l.count]),_avg:l.avg,_sum:l.sum,_min:l.min,_max:l.max},{atLeast:[`by`],refuse:e=>groupByCollisions(e)??groupedMembershipIssue(e,r.scalars)})},projectableScalarNames=e=>{let t=e[`~`].state,n=F.get(t);if(n===void 0){let e=t.omit,r=Object.keys(t.scalars);n=Object.freeze(e?r.filter(t=>!Object.hasOwn(e,t)||e[t]!==!0):r),F.set(t,n)}return n},F=new WeakMap,Ce=v.boolean({optional:!0}),getOmitSchema=e=>v.object(v.fromKeys(projectableScalarNames(e),Ce).entries,{optional:!0}),I=e(e=>({issues:[{message:e}]}),`issue`),modelLabel=e=>e[`~`].names.ts??e[`~`].state.tableName??`model`,buildOmitSelection=(e,t)=>{let n={};for(let r of projectableScalarNames(e))t[r]!==!0&&(n[r]=!0);return Object.keys(n).length>0?n:void 0},emptyOmitProjectionMessage=(e,t)=>`'omit' on '${t}' excluded every readable field of model '${modelLabel(e)}'. At least one field must remain in the result: drop a field from 'omit', or use 'select' to name what you want.`,emptySelectedOmitProjectionMessage=(e,t)=>`'omit' on '${t}' excluded every selected field of model '${modelLabel(e)}'. At least one field must remain in the result: remove a field from 'omit' or add another field to 'select'.`,hasProjectedValue=e=>{for(let t in e){let n=e[t];if(n!==!1&&n!==void 0)return!0}return!1},subtractOmitFromSelection=(e,t)=>{let n={};for(let r of Object.keys(e))t[r]!==!0&&(n[r]=e[r]);return n},withOmitProjection=(e,t,n)=>{let r=e[`~standard`],validate=e=>{let i=a(e)&&e.omit!==void 0,o=r.validate(e);return!i||o.issues?o:projectOmit(o,t,n)};return{...e,parse:validate,"~standard":{version:r.version,vendor:r.vendor,validate,get types(){return r.types},get jsonSchema(){return r.jsonSchema}}}};function projectOmit(e,t,n){let r=e.value,i=r.omit,o=a(r.select)?r.select:void 0,s=o?subtractOmitFromSelection(o,i):buildOmitSelection(t,i);if(!s)return I(emptyOmitProjectionMessage(t,n));if(o&&hasProjectedValue(o)&&!hasProjectedValue(s))return I(emptySelectedOmitProjectionMessage(t,n));let{omit:c,...l}=r;return{value:{...l,select:s}}}const getUpsertProjectionSchema=(e,t)=>withOmitProjection(v.object({select:v.lazyRef(()=>t.select),include:v.lazyRef(()=>t.include),omit:v.lazyRef(()=>t.omit)}),e,`upsert`),we={issues:[{message:`Mutually exclusive fields cannot be used together: select, include`}]},hasSelectAndInclude=e=>a(e)&&e.select!==void 0&&e.include!==void 0,rejectSelectInclude=e=>{let t=e[`~standard`],validate=e=>hasSelectAndInclude(e)?we:t.validate(e);return{...e,parse:validate,"~standard":{version:t.version,vendor:t.vendor,validate,get types(){return t.types},get jsonSchema(){return t.jsonSchema}}}},getDistinctSchema=e=>{let t=Object.keys(e[`~`].state.scalars).filter(t=>e[`~`].state.scalars[t][`~`].state.type!==`point`);return v.singleOrArray(v.enum(t))},getFindUniqueArgs=(e,t)=>withOmitProjection(rejectSelectInclude(v.object({where:v.lazyRef(()=>t.whereUniqueExtended),select:v.lazyRef(()=>t.select),include:v.lazyRef(()=>t.include),omit:v.lazyRef(()=>t.omit)},{atLeast:[`where`]})),e,`findUnique`),getFindArgs=e=>(t,n)=>withOmitProjection(rejectSelectInclude(v.object({where:v.lazyRef(()=>n.where),orderBy:v.lazyRef(()=>v.union([n.orderBy,v.array(n.orderBy)])),take:paginationTake(),skip:paginationSkip(),cursor:v.lazyRef(()=>n.whereUnique),select:v.lazyRef(()=>n.select),include:v.lazyRef(()=>n.include),omit:v.lazyRef(()=>n.omit),distinct:v.lazyRef(()=>getDistinctSchema(t))},{optional:!0})),t,e),Te=getFindArgs(`findFirst`),Ee=getFindArgs(`findMany`),restrictToScalarProjection=(e,t,n)=>{let r=new Set(Object.keys(t[`~`].state.relations)),i=e[`~standard`],validate=e=>{if(hasOwnKey(e,`include`))return issue(`'include' is not supported on '${n}': a bulk write returns the rows its write statement produced, and viborm does not project relations into them. Select the scalar fields you need and read relations in a separate query.`);let t=findProjectedRelation(e,r);return t===void 0?i.validate(e):issue(`'select.${t}' is not supported on '${n}': a bulk write projects scalar fields only. Read the relation in a separate query.`)};return{...e,parse:validate,"~standard":{version:i.version,vendor:i.vendor,validate,get types(){return i.types},get jsonSchema(){return i.jsonSchema}}}},issue=e=>({issues:[{message:e}]}),hasOwnKey=(e,t)=>a(e)&&Object.hasOwn(e,t),findProjectedRelation=(e,t)=>{if(!a(e))return;let n=e.select;if(a(n)){for(let e of Object.keys(n))if(n[e]!==void 0&&(e===`_count`||t.has(e)))return e}},matchesEveryRow=e=>e===0||e===1,and=(e,t)=>e===2||t===2?2:e===3||t===3?3:e===1||t===1?1:0,conjunction=e=>e.reduce(and,0),negation=e=>e===1?2:e===2?1:e,disjunction=e=>{let t=2;for(let n of e){if(n===1)return 1;n===3&&(t=3)}return t};function truthOf(e,t,n){if(!a(e))return 3;let r=0;for(let i in e){let a=e[i],o=t===``?i:`${t}.${i}`;if(a===void 0){if(!n)return 3;n.push(o);continue}if(r=and(r,memberTruth(i,a,o,n)),t===``&&!matchesEveryRow(r))return r}return r}function memberTruth(e,t,n,r){if(e===`AND`||e===`OR`||e===`NOT`){let i=(Array.isArray(t)?t:[t]).map((e,i)=>truthOf(e,Array.isArray(t)?`${n}[${i}]`:n,r));return e===`AND`?conjunction(i):e===`OR`?disjunction(i.filter(e=>e!==0)):conjunction(i.map(negation))}if(a(t)&&t.every!==void 0){for(let e of Object.keys(t))if(e!==`every`){if(t[e]!==void 0||!r)return 3;r.push(`${n}.${e}`)}return matchesEveryRow(truthOf(t.every,`${n}.every`,r))?1:3}return 3}function undefinedOnlyWhere(e){let t=[];if(matchesEveryRow(truthOf(e,``,t))&&t.length!==0)return matchesEveryRow(truthOf(e,``,void 0))?void 0:t}function refusingUndefinedOnlyWhere(e,t,n,r){let i=e[`~standard`],o=i.validate,s=n?`every related row`:`every row`,c=`${n?`This nested `:``}${t} would ${t===`deleteMany`?`delete`:`update`} ${s}`;return i.validate=e=>{let t=o(e);if(t.issues)return t;let n=Array.isArray(e)?e:[e];for(let t=0;t<n.length;t++){let i=n[t],o=undefinedOnlyWhere(r?a(i)?i[r]:void 0:i);if(!o)continue;let l=Array.isArray(e)?[t]:[];return r&&l.push(r),{issues:[{message:`${c}: its where names only undefined values (${o.join(`, `)}), and an undefined value is no condition. Remove them, or pass where: {} to mean ${s}.`,path:l}]}}return t},e}const getCreateArgs=(e,t)=>withOmitProjection(rejectSelectInclude(v.object({data:v.lazyRef(()=>t.create),select:v.lazyRef(()=>t.select),include:v.lazyRef(()=>t.include),omit:v.lazyRef(()=>t.omit)},{atLeast:[`data`]})),e,`create`),refuseDefaultOnlySkipDuplicates=e=>{if(e.skipDuplicates===!0)return e.data.some(e=>a(e)&&Object.values(e).every(e=>e===void 0))?`createMany with skipDuplicates cannot include a row with no explicit scalar values; no portable duplicate-only DEFAULT VALUES primitive exists.`:void 0},getCreateManyArgs=(e,t)=>withOmitProjection(restrictToScalarProjection(v.object({data:v.lazyRef(()=>v.array(t.bulkCreate)),skipDuplicates:v.boolean({optional:!0}),select:v.lazyRef(()=>t.scalarSelect),omit:v.lazyRef(()=>t.omit)},{atLeast:[`data`],refuse:refuseDefaultOnlySkipDuplicates}),e,`createMany`),e,`createMany`),getUpdateArgs=(e,t)=>withOmitProjection(rejectSelectInclude(v.object({where:v.lazyRef(()=>t.whereUniqueExtended),data:v.lazyRef(()=>t.update),select:v.lazyRef(()=>t.select),include:v.lazyRef(()=>t.include),omit:v.lazyRef(()=>t.omit)},{atLeast:[`where`,`data`]})),e,`update`),getUpdateManyArgs=(e,t)=>withOmitProjection(restrictToScalarProjection(refusingUndefinedOnlyWhere(v.object({where:v.lazyRef(()=>t.where),data:v.lazyRef(()=>t.update),select:v.lazyRef(()=>t.scalarSelect),omit:v.lazyRef(()=>t.omit),limit:bulkWriteLimit()},{atLeast:[`data`]}),`updateMany`,!1,`where`),e,`updateMany`),e,`updateMany`),getDeleteArgs=(e,t)=>withOmitProjection(rejectSelectInclude(v.object({where:v.lazyRef(()=>t.whereUniqueExtended),select:v.lazyRef(()=>t.select),include:v.lazyRef(()=>t.include),omit:v.lazyRef(()=>t.omit)},{atLeast:[`where`]})),e,`delete`),getDeleteManyArgs=(e,t)=>withOmitProjection(restrictToScalarProjection(refusingUndefinedOnlyWhere(v.object({where:v.lazyRef(()=>t.where),select:v.lazyRef(()=>t.scalarSelect),omit:v.lazyRef(()=>t.omit),limit:bulkWriteLimit()},{optional:!0}),`deleteMany`,!1,`where`),e,`deleteMany`),e,`deleteMany`),getUpsertArgs=(e,t)=>withOmitProjection(rejectSelectInclude(v.object({where:v.lazyRef(()=>t.whereUniqueExtended),create:v.lazyRef(()=>t.create),update:v.lazyRef(()=>t.update),select:v.lazyRef(()=>t.select),include:v.lazyRef(()=>t.include),omit:v.lazyRef(()=>t.omit),targetWhere:v.lazyRef(()=>t.where),setWhere:v.lazyRef(()=>t.where)},{atLeast:[`where`,`create`,`update`]})),e,`upsert`),getArgsSchemas=(e,t,n)=>lazyRecord({findUnique:()=>getFindUniqueArgs(e,n),findFirst:()=>Te(e,n),findMany:()=>Ee(e,n),create:()=>getCreateArgs(e,n),createMany:()=>getCreateManyArgs(e,n),update:()=>getUpdateArgs(e,n),updateMany:()=>getUpdateManyArgs(e,n),delete:()=>getDeleteArgs(e,n),deleteMany:()=>getDeleteManyArgs(e,n),upsert:()=>getUpsertArgs(e,n),count:()=>getCountArgs(e,n),exist:()=>getExistArgs(n),aggregate:()=>getAggregateArgs(e,n),groupBy:()=>getGroupByArgs(e,t,n)}),getScalarCreate=(e,t)=>{let n=e[`~`].state,r={atLeast:Object.keys(n.scalars).filter(e=>!n.shape[e][`~`].state.optional),provides:e[`~`].names.ts};return v.fromObject(t.scalars,`create`,r)};function getBulkCreate(e,t,n){let r=e[`~`].state,i=getFkFields(r),a=getFkRequirementKeySets(r,n),o=getRequiredCreateScalars(r,i),s=v.fromObject(t.scalars,`create`),c=v.fromObject(t.relations,`create`),l=v.fromObject(t.polymorphic,`createMany`);return v.object({...s.entries,...c.entries,...l.entries},{atLeast:o,requiresOneOfKeySets:a,provides:e[`~`].names.ts})}const getRelationCreate=e=>v.fromObject(e.relations,`create`);function getFkFields(e){let t=new Set;for(let n of Object.values(e.relations)){let e=n[`~`].state.foreignKey;if(e)for(let n of e.fields)t.add(n)}return t}function getRequiredCreateScalars(e,t){return Object.keys(e.scalars).filter(n=>!t.has(n)&&mustBeSuppliedOnCreate(e,n))}function mustBeSuppliedOnCreate(e,t){let n=e.scalars[t][`~`].state;return!(n.hasDefault||n.optional)}function getFkRequirementKeySets(e,t){let n=[];for(let[r,i]of Object.entries(e.relations)){let a=i[`~`].state;if(a.cardinality!==`one`)continue;let o=a.foreignKey;if(o){let i=o.fields.filter(t=>mustBeSuppliedOnCreate(e,t));if(i.length>0){let e=t.get(r),a=e&&!slotMayBeEmpty(e)?o.fields:i;n.push([a,[r]])}continue}let s=t.get(r);s&&!slotMayBeEmpty(s)&&n.push([[r]])}return n}const getCreateSchema=(e,t,n)=>{let r=e[`~`].state,i=getFkFields(r),a=getFkRequirementKeySets(r,n),o=getRequiredCreateScalars(r,i),s=v.fromObject(t.scalars,`create`),c=v.fromObject(t.relations,`create`),l=v.fromObject(t.polymorphic,`create`);return v.object({...s.entries,...c.entries,...l.entries},{atLeast:o,requiresOneOfKeySets:a,provides:e[`~`].names.ts})};function nonNullable(e,t){let n=e[`~standard`].validate,r=g(`nonNullable`,e=>e===null?c(t):n(e));return r.wrapped=e,r}const getUniqueScalarSchemas=(e,t)=>{let n={};for(let r of Object.keys(e[`~`].state.uniques)){let e=t.scalars[r];e&&(n[r]=e)}return n},getScalarFilter=e=>v.fromObject(e.scalars,`filter`),uniqueMember=e=>nonNullable(e,`A unique selector cannot be null: a unique index holds any number of nulls, so null names no single row.`),getUniqueFilter=(e,t)=>{let n={};for(let[r,i]of Object.entries(getUniqueScalarSchemas(e,t)))n[r]=uniqueMember(i.base);return v.object(n)},getRelationFilter=e=>v.fromObject(e.relations,`filter`),compoundSelector=(e,t)=>{let n={};for(let r of Object.keys(e.entries))n[r]=uniqueMember(t[r].base);return v.object(n,{partial:!1})},compoundSelectors=(e,t)=>{let n={};for(let[r,i]of Object.entries(e??{}))n[r]=compoundSelector(i,t);return n},getCompoundConstraintFilter=(e,t)=>{let n=e[`~`].state;if(!(n.compoundUniques||n.compoundId))return v.object({});let r=t.scalars;return v.object({...compoundSelectors(n.compoundUniques,r),...compoundSelectors(n.compoundId,r)})},getCompoundIdFilter=(e,t)=>{let n=e[`~`].state;return n.compoundId?v.object(compoundSelectors(n.compoundId,t.scalars)):v.object({})},L=v.boolean({optional:!0}),De=v.enum([`l2`,`cosine`]),toManyRelationNames=e=>{let t=e[`~`].state.relations,n=[];for(let e of Object.keys(t))t[e][`~`].state.cardinality===`many`&&n.push(e);return n},getCountSchema=(e,t)=>{let n=toManyRelationNames(e),r=v.fromObject(t.relations,`countFilter`,{optional:!0}),i=v.fromObject(t.polymorphic,`countFilter`,{optional:!0});return v.union([v.coerce(v.literal(!0),()=>{let e={};for(let t of n)e[t]=!0;return{select:e}}),v.object({select:v.object({...r.entries,...i.entries},{optional:!0})},{optional:!0})])},Oe=v.object({_distance:v.object({to:v.array(v.number()),metric:De},{partial:!1})},{partial:!1}),ke=v.object({_distance:v.object({to:v.point()},{partial:!1})},{partial:!1}),Ae=v.union([L,Oe]),je=v.union([L,ke]),selects=e=>e!==void 0&&e!==!1,requireSelectedField=e=>Object.entries(e).some(([e,t])=>e===`_count`?a(t)&&Object.values(new Object(t.select)).some(selects):selects(t))?void 0:`select needs at least one truthy value; leave it out to return the default row.`,getScalarSelectEntries=e=>{let t=[],n=[],r=[],i=projectableScalarNames(e);for(let a of i){let i=e[`~`].state.scalars[a];if(i[`~`].state.type===`vector`){t.push(a);continue}if(i[`~`].state.type===`point`){n.push(a);continue}r.push(a)}let a=v.fromKeys(r,L),o=v.fromKeys(t,Ae),s=v.fromKeys(n,je);return{...a.entries,...o.entries,...s.entries}},getThroughSelectSchema=e=>{let t=projectableScalarNames(e);return v.union([v.coerce(v.boolean(),e=>e?{select:Object.fromEntries(t.map(e=>[e,!0]))}:!1),v.object({select:v.object(v.fromKeys(t,L).entries,{refuse:requireSelectedField})},{partial:!1})])},projection=e=>`$${e[`~`].names.ts}`,selectOptions=e=>({refuse:requireSelectedField,provides:projection(e)}),getScalarSelectSchema=e=>v.object(getScalarSelectEntries(e),selectOptions(e)),getSelectSchema=(e,t)=>{let n=getScalarSelectEntries(e),r=v.fromObject(t.relations,`select`),i=v.fromObject(t.polymorphic,`select`);return v.object({...n,...r.entries,...i.entries,_count:getCountSchema(e,t)},selectOptions(e))},getIncludeSchema=(e,t)=>{let n=v.fromObject(t.relations,`include`,{optional:!0}),r=v.fromObject(t.polymorphic,`include`,{optional:!0}),i={provides:projection(e)};return v.object({...n.entries,...r.entries,_count:getCountSchema(e,t)},i)},getScalarUpdate=e=>v.fromObject(e.scalars,`update`),getRelationUpdate=e=>v.fromObject(e.relations,`update`),getUpdateSchema=e=>{let t=v.fromObject(e.relations,`update`),n=v.fromObject(e.polymorphic,`update`);return getScalarUpdate(e).extend(t.entries).extend(n.entries)},getWhereSchema=(e,t)=>{let n=S(t.scalars,`filter`),r=S(t.relations,`filter`),i=S(t.polymorphic,`filter`),a=v.object({AND:()=>v.optional(v.union([a,v.array(a)])),OR:()=>v.optional(v.array(a)),NOT:()=>v.optional(v.union([a,v.array(a)])),...n,...r,...i});return b(ne(a),e)};function getDecimalListWhereUniqueEntries(e){let t=[];for(let n of Object.keys(e[`~`].state.scalars)){let r=e[`~`].state.scalars[n][`~`].state;r.type===`decimal`&&r.array===!0&&t.push(n)}return v.fromKeys(t,v.refused(`A decimal list cannot be used as a unique selector or cursor.`))}const getWhereUniqueSchema=(e,t)=>{let n=getUniqueFilter(e,t),r=getCompoundConstraintFilter(e,t),i={...n.entries,...r.entries},a=Object.keys(i),o=getDecimalListWhereUniqueEntries(e),s={...i,...o.entries};return v.object(s,{nonEmpty:!0,requiresOneOf:[a]})},getWhereUniqueExtendedSchema=(e,t)=>{let n=getUniqueFilter(e,t),r=getCompoundConstraintFilter(e,t),i=getWhereSchema(e,t),a={...n.entries,...r.entries},o=Object.keys(a),s={...i.entries,...a};return b(v.object(s,{nonEmpty:!0,requiresOneOf:[o]}),e)},getCoreSchemas=(e,t,n)=>{let r=lazyRecord({scalarFilter:()=>getScalarFilter(t),uniqueFilter:()=>getUniqueFilter(e,t),relationFilter:()=>getRelationFilter(t),compoundIdFilter:()=>getCompoundIdFilter(e,t),compoundConstraintFilter:()=>getCompoundConstraintFilter(e,t),scalarCreate:()=>getScalarCreate(e,t),bulkCreate:()=>getBulkCreate(e,t,n),relationCreate:()=>getRelationCreate(t),scalarUpdate:()=>getScalarUpdate(t),relationUpdate:()=>getRelationUpdate(t),where:()=>getWhereSchema(e,t),whereUnique:()=>getWhereUniqueSchema(e,t),whereUniqueExtended:()=>getWhereUniqueExtendedSchema(e,t),create:()=>getCreateSchema(e,t,n),update:()=>getUpdateSchema(t),select:()=>getSelectSchema(e,t),omit:()=>getOmitSchema(e),upsertProjection:()=>getUpsertProjectionSchema(e,r),scalarSelect:()=>getScalarSelectSchema(e),include:()=>getIncludeSchema(e,t),orderBy:()=>getOrderBySchema(e,t)});return r},getModelSchemas=(e,t,n)=>{let r=getCoreSchemas(e,t,n);return{core:r,args:getArgsSchemas(e,t,r),scalars:t.scalars,relations:t.relations,polymorphic:t.polymorphic}},countFilterFactory=(e,t)=>v.union([v.literal(!0),v.object({where:()=>t().core.where})]),junctionModelOf=e=>e.edge.kind===`junction`?e.edge.topology.declared?.model:void 0,whereWithLinkFilter=(e,t,n=()=>v.object(v.fromObject(t().scalars,`filter`).entries))=>{if(!t)return e;let r;return()=>(r??=e().extend({$through:n()}),r)},withLinkWrite=(e,t)=>{let{edge:n}=e;if(!(t&&n.kind===`junction`))return e=>e;let{source:r,target:i,declared:o}=n.topology,l=new Set([...r.members,...i.members].map(e=>e.junctionField)),d=o.model[`~`].state.scalars,f=g(`object`,e=>{if(!a(e))return c(`$through must be an object`);let n=t().scalars,r={};for(let[t,i]of Object.entries(e)){if(i===void 0)continue;if(!Object.hasOwn(n,t))return c(`$through.${t} is not a column of the junction model`);if(l.has(d[t][`~`].state.columnName??t))return c(`$through.${t} is filled from the two rows the link joins, and cannot be written`);let e=s(n[t].create,i);if(e.issues)return{issues:e.issues.map(e=>({...e,path:[`$through`,t,...e.path??[]]}))};r[t]=e.value}return u(r)});return e=>g(`object`,t=>{if(!(a(t)&&Object.hasOwn(t,`$through`)))return s(e,t);let{$through:n,...r}=t,i=s(e,r);if(i.issues||n===void 0)return i;let o=s(f,n);return o.issues?o:u({...i.value,$through:o.value})})},R={kind:`none`,keys:[]},isAskingSlot=(e,t)=>t.source===e.slot.source&&t.field===e.slot.field,ownedByEnclosingStep=e=>{let t=e.edge;return t.kind===`foreignKey`?isAskingSlot(e,t.owner)?R:{kind:`columns`,keys:t.reference.members.map(e=>e.foreignField)}:t.kind===`variantRowCarrier`||t.kind===`variantJunctionCarrier`?isAskingSlot(e,t.carrier)?R:{kind:`carrier`,keys:[t.carrier.field]}:R},nestedRelationDataProjection=(t,n)=>{let r=ownedByEnclosingStep(t),bareUpdate=()=>n().core.update,i=e(()=>C.omit(n().core.create,r.keys),`getCreateSchema`),a=e(()=>C.omit(bareUpdate(),r.keys),`getUpdateSchema`);return{getCreateSchema:i,getUpdateSchema:a,getSelectedUpsertUpdateSchema:r.kind===`carrier`?bareUpdate:a,getCreateUpsertUpdateSchema:r.kind===`columns`?bareUpdate:a}},Me=new Set([`disconnect`,`delete`]),Ne=new Set([`create`,`connect`,`connectOrCreate`]);function isAcceptedComposition(e,t){if(e.length<=1)return!0;let n,r,i=!1;for(let t of e)if(Me.has(t)){if(n!==void 0)return!1;n=t}else if(Ne.has(t)){if(r!==void 0)return!1;r=t}else if(t===`update`)i=!0;else return!1;return r===void 0||n===`delete`&&r===`connectOrCreate`?!1:i?t||n===void 0&&r===`connect`:!0}const unsupportedCombination=e=>({issues:[{message:`Unsupported to-one operation combination: ${e.join(`, `)}`}]});function enforceCompositionLattice(e,t,n,r){if(e.issues)return e;let i=e.value;if(!a(i))return e;let o=[];for(let e of t){let t=i[e];t!==void 0&&t!==!1&&o.push(e)}return r?o.length===1?e:o.length===0?{issues:[{message:`Missing to-one operation: expected exactly one of ${t.join(`, `)}`}]}:unsupportedCombination(o):isAcceptedComposition(o,n)?e:unsupportedCombination(o)}function toOneMutationSchema(e,t,n,r){let i=v.object(e,t),a=Object.keys(e),o=i[`~standard`].validate,s=n===!0,c=r===`exactlyOne`,validate=(e,t)=>enforceCompositionLattice(o(e,t),a,s,c),l={...i,"~standard":{version:1,vendor:`viborm`,validate,get jsonSchema(){return i[`~standard`].jsonSchema}}};return Object.defineProperty(l,` vibInferred`,{value:void 0,enumerable:!1}),l}const toOneCreateFactory=(e,t)=>{let n=nestedRelationDataProjection(e,t).getCreateSchema;return toOneMutationSchema({create:n,connect:()=>t().core.whereUnique,connectOrCreate:C.object({where:()=>t().core.whereUnique,create:n},{partial:!1})},{optional:!0})},toManyCreateFactory=(e,t,n=void 0)=>{let r=nestedRelationDataProjection(e,t),i=r.getCreateSchema,a=withLinkWrite(e,n),o=C.object({data:()=>C.array(i()),skipDuplicates:C.boolean({optional:!0})},{atLeast:[`data`],refuse:refuseDefaultOnlySkipDuplicates});return C.object({create:()=>C.singleOrArray(a(i())),createMany:o,connect:()=>C.singleOrArray(a(t().core.whereUnique)),connectOrCreate:()=>C.singleOrArray(a(C.object({where:()=>t().core.whereUnique,create:i},{partial:!1}))),upsert:()=>C.singleOrArray(C.object({where:()=>t().core.whereUnique,create:i,update:r.getCreateUpsertUpdateSchema},{partial:!1}))},{optional:!0})},Pe=1e4;function carriesRepeatedKey(e,t){return e===!1||t<e}const z=Object.freeze({minimum:1,maximum:1e3}),B=Object.assign(g(`integer`,e=>{let t=h(e);return t.issues?t:t.value>=z.minimum&&t.value<=z.maximum?u(t.value):c(`recurse.depth must be a positive safe integer between 1 and 1000`)}),z),V=v.object({depth:v.optional(v.union([B,v.literal(!1)])),preventCycles:v.optional(v.refused(`preventCycles applies only to a junction graph; a foreign-key recursion rejects every cycle it reaches`))}),H=v.object({depth:v.optional(B),preventCycles:v.optional(v.boolean())}),U=v.object({depth:v.literal(!1),preventCycles:v.optional(v.literal(!0))},{atLeast:[`depth`]}),W={maxOccurrences:v.optional(g(`integer`,e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=1?u(e):c(`recurse.maxOccurrences must be a positive safe integer`))),fewRows:v.optional(v.boolean())},G={selective:v.optional(v.boolean())},withOptions=(e,t)=>({...e,...t.maxOccurrences!==void 0&&{maxOccurrences:t.maxOccurrences},...t.selective===!0&&{selective:!0},...t.fewRows===!0&&{fewRows:!0}}),normalizeForeignKey=e=>withOptions({depth:e.depth??100,cycles:`reject`},e),normalizeGraph=e=>withOptions({depth:e.depth??100,cycles:e.preventCycles===!1?`allow`:`prevent`},e),Fe=v.coerce(v.literal(!0),()=>normalizeForeignKey({})),Ie=v.coerce(v.literal(!0),()=>normalizeGraph({})),Le={projection:{foreignKey:v.union([Fe,v.coerce(V.extend(W),normalizeForeignKey)]),junction:v.union([Ie,v.coerce(v.union([H.extend(W),U.extend(W)]),normalizeGraph)])},filter:{foreignKey:v.union([Fe,v.coerce(V.extend(G),normalizeForeignKey)]),junction:v.union([Ie,v.coerce(v.union([H.extend(G),U.extend(G)]),normalizeGraph)])}};function recurrenceSchema(e,t=`projection`){let{edge:n,slot:r}=e;if(n.kind!==`foreignKey`&&n.kind!==`junction`)return;let[i,a]=n.endpoints;if(i.source===a.source&&oe(r.source).rowKey)return Le[t][n.kind]}const Re=`recurse is available only on an ordinary self relation (a foreign key or a junction, never variant storage) whose model has a complete primary key`,unavailableRecurrence=()=>v.optional(v.refused(Re)),unavailableRecursiveClause=e=>v.optional(v.refused(`${e} cannot be combined with recurse`)),withoutUnspelledClosure=e=>{if(!(a(e)&&(`recurse`in e||`self`in e&&e.self===void 0)))return e;let{recurse:t,self:n,...r}=e;return n===void 0?r:{...r,self:n}},withRecursiveNode=(e,t)=>{let n=e[`~standard`].validate,r=t?.[`~standard`].validate,i=g(`union`,e=>!a(e)||e.recurse===void 0?n(withoutUnspelledClosure(e)):r?r(e):c(Re,[`recurse`])),o=Array.isArray(e.options)?e.options:[e];return Object.assign(i,{options:[...o,...t?[t]:[]]})},ze=g(`object`,()=>u({is:null})),Be=[`some`,`every`,`none`],Ve=[`is`,`isNot`],requireRelationQuantifier=(e,t)=>{let n=`Relation filter '${e.slot.field}' requires one of: ${t.join(`, `)}.`;return e=>t.some(t=>e[t]!==void 0)?void 0:n},quantifierEntries=e=>({some:e,every:e,none:e}),He=C.optional(C.refused(`$through cannot filter a recurse walk: a row has one link row per path`)),recursiveFilter=(e,t,n=void 0)=>{let r=recurrenceSchema(e,`filter`),i=whereWithLinkFilter(()=>t().core.where,n,()=>He);return r&&C.object({recurse:te(r),self:C.boolean(),...quantifierEntries(i),is:unavailableRecursiveClause(`is`),isNot:unavailableRecursiveClause(`isNot`)},{atLeast:[`recurse`],refuse:requireRelationQuantifier(e,Be)})},Ue=new Set([`is`,`isNot`]),isExplicitToOneFilter=e=>{for(let t in e)if(!Ue.has(t))return!1;return!0},toOneFilterFactory=(e,t)=>{let n=slotMayBeEmpty(e),r=C.object({is:()=>C.maybeNullable(t().core.where,n),isNot:()=>C.maybeNullable(t().core.where,n)},{refuse:requireRelationQuantifier(e,Ve)}),i=C.lazy(()=>C.coerce(t().core.where,e=>({is:e}))),o=n?[ze,r,i]:[r,i],l=g(`union`,e=>e===null?n?s(ze,e):c(`Expected object`):a(e)?isExplicitToOneFilter(e)?s(r,e):s(i,e):c(`Expected object`));return withRecursiveNode(Object.assign(l,{options:o}),recursiveFilter(e,t))},toManyFilterFactory=(e,t,n=void 0)=>{let own=()=>t().core.where;return withRecursiveNode(C.object(quantifierEntries(whereWithLinkFilter(own,n)),{refuse:requireRelationQuantifier(e,Be)}),recursiveFilter(e,t,n))},isOrderableToOneRelation=e=>e.cardinality===`one`&&!w(e),createToManyRelationOrderByFailureSchema=e=>v.refused(`Relation orderBy '${e}' cannot order through a to-many relation; use '_count'.`),getModelScalarOrderByEntries=e=>{let t=[],n=[],r=[],i=Object.keys(e[`~`].state.scalars);for(let a of i){if(isDecimalListScalarKey(e,a)){r.push(a);continue}if(e[`~`].state.scalars[a][`~`].state.type===`vector`){t.push(a);continue}n.push(a)}let a=x(n,E),o=x(t,D),s=x(r,O);return{...a,...o,...s}},getToOneRelationOrderByEntries=(e,t)=>{if(t<=0)return{};let n={},r=e[`~`].state.relations;for(let[e,i]of Object.entries(r)){let r=i[`~`].state;if(isOrderableToOneRelation(r)){n[e]=()=>v.lazyRef(()=>buildToOneOrderBySchema(i[`~`].settleTarget(),t-1));continue}n[e]=createToManyRelationOrderByFailureSchema(e)}return n},buildToOneOrderBySchema=(e,t)=>{let n=getModelScalarOrderByEntries(e),r=getToOneRelationOrderByEntries(e,t);return v.object({...n,...r})},toOneOrderByFactory=(e,t)=>()=>v.lazyRef(()=>buildToOneOrderBySchema(e[`~`].settleTarget(),7)),toManyOrderByFactory=e=>v.object({_count:v.enum([`asc`,`desc`])}),getTargetState=e=>getTargetModel(e)[`~`].state,getTargetModel=e=>e[`~`].settleTarget(),We=new WeakMap,buildSelectionForModel=e=>{let t=We.get(e);if(t===void 0){t={};for(let n of projectableScalarNames(e))t[n]=!0;We.set(e,t)}return{...t}},nestedOmitLabel=e=>{let t=e[`~`].state.name;return t?`include.${t}`:`a nested include`},withOmitForModel=(e,t,n)=>withOmitProjection(n,e,t),withNestedOmit=(e,t)=>withOmitForModel(getTargetModel(e),nestedOmitLabel(e),t),askingKeyRefusal=e=>v.optional(v.refused(`${e} is produced by recurse and cannot be selected again inside its own recursive node`)),projectionWithoutAsking=(e,t,n)=>e.extend({[t]:askingKeyRefusal(t),...n&&{$through:Ge}}),Ge=v.optional(v.refused(`$through is not available on a recurse walk: a row has one link row per path. Read the links through the junction model's delegate`)),coreWithThrough=(e,t,n)=>{if(!t)return e;let r={$through:getThroughSelectSchema(t)},i,a,o=whereWithLinkFilter(()=>e().where,n);return()=>{let t=e();return{get where(){return o()},get orderBy(){return t.orderBy},get whereUnique(){return t.whereUnique},get omit(){return t.omit},get select(){return i??=t.select.extend(r),i},get include(){return a??=t.include.extend(r),a}}}},termOrList=e=>v.union([e,v.array(e)]),buildRecursiveNode=(e,t,n,r,i={},a)=>v.coerce(withNestedOmit(e,rejectSelectInclude(v.object({...i,select:()=>projectionWithoutAsking(r().core.select,t,a),include:()=>projectionWithoutAsking(r().core.include,t,a),omit:()=>r().core.omit,recurse:n}))),includeToField(e)),withRecurrence=(e,t,n,r,i)=>{let a=recurrenceSchema(n);return a?withRecursiveNode(e,buildRecursiveNode(t,n.slot.field,a,r,i?.(),junctionModelOf(n))):e},nestedDistinctNames=e=>Object.keys(getTargetState(e).scalars),includeToFieldForModel=e=>t=>Object.hasOwn(t,`select`)&&t.select!==!1||projectableScalarNames(e).length===0?t:{...t,select:buildSelectionForModel(e)},includeToField=e=>includeToFieldForModel(getTargetModel(e)),defaultSelectionNode=e=>projectableScalarNames(e).length>0?{select:buildSelectionForModel(e)}:{},booleanToSelect=e=>v.coerce(v.boolean(),t=>t?defaultSelectionNode(getTargetModel(e)):!1),toOneIncludeFactory=(e,t,n)=>withRecurrence(v.union([booleanToSelect(e),v.coerce(withNestedOmit(e,rejectSelectInclude(v.object({select:()=>n().core.select,include:()=>n().core.include,omit:()=>n().core.omit,recurse:unavailableRecurrence()}))),includeToField(e))]),e,t,n),buildToManyNestedNode=e=>{let{targetModel:t,label:n,scalarNames:r}=e,at=t=>e.core()[t];return v.coerce(withOmitForModel(t,n,rejectSelectInclude(v.object({where:()=>at(`where`),orderBy:()=>termOrList(at(`orderBy`)),take:paginationTake(),skip:paginationSkip(),cursor:()=>at(`whereUnique`),distinct:v.enum(r,{array:!0}),select:()=>at(`select`),include:()=>at(`include`),omit:()=>at(`omit`),recurse:unavailableRecurrence()}))),includeToFieldForModel(t))},toManyIncludeFactory=(e,t,n,r=void 0)=>withRecurrence(v.union([booleanToSelect(e),buildToManyNestedNode({targetModel:getTargetModel(e),label:nestedOmitLabel(e),core:coreWithThrough(()=>n().core,junctionModelOf(t),r),scalarNames:nestedDistinctNames(e)})]),e,t,n,()=>({where:()=>n().core.where,orderBy:()=>termOrList(n().core.orderBy),take:unavailableRecursiveClause(`take`),skip:unavailableRecursiveClause(`skip`),cursor:unavailableRecursiveClause(`cursor`),distinct:unavailableRecursiveClause(`distinct`)})),Ke=toOneIncludeFactory,qe=toManyIncludeFactory;function readToOneUpdateForm(e,t){return hasEnvelopeShape(e)?!t||e.where!==void 0?`envelope`:`ambiguous`:`bare`}function toOneUpdateEnvelope(e,t){return t?{where:{},data:e}:{data:e}}function hasEnvelopeShape(e){return isPlainObject(e)&&Object.hasOwn(e,`data`)&&isPlainObject(e.data)}function isPlainObject(e){if(!a(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function toOneUpdateTargetFactory(e,t){let n=t,r=v.object({where:()=>e().core.where,data:n},{atLeast:[`data`]}),i=v.lazy(n),a=[r,i],o,targetOwnsDataField=()=>(o===void 0&&(o=Object.hasOwn(n().entries,`data`)),o),l=g(`union`,e=>{let t=targetOwnsDataField(),n=readToOneUpdateForm(e,t);if(n===`ambiguous`)return c("Ambiguous to-one nested `update`: `{ data: … }` reads both as the `{ where?, data }` envelope and as bare update data for this target's own `data` field. Spell the envelope out — `update: { where: {}, data: { … } }` updates the target's fields (put a filter in `where` to make it conditional), and `update: { where: {}, data: { data: … } }` writes its `data` field.");if(n===`envelope`)return s(r,e);let a=s(i,e);return a.issues?a:u(toOneUpdateEnvelope(a.value,t))});return l.options=a,l}const toOneUpdateFactory=(e,t,n)=>{let r=nestedRelationDataProjection(t,n),i=r.getCreateSchema,a=r.getUpdateSchema,o={create:i,connect:()=>n().core.whereUnique,connectOrCreate:v.object({where:()=>n().core.whereUnique,create:i},{partial:!1}),update:()=>toOneUpdateTargetFactory(n,a),upsert:v.object({create:i,update:a},{partial:!1})},s=e.foreignKey===void 0;return slotMayBeEmpty(t)?membershipCanBeCleared(t)?toOneMutationSchema({...o,disconnect:v.boolean(),delete:v.boolean()},void 0,s):toOneMutationSchema({...o,delete:v.boolean()},void 0,s):toOneMutationSchema(o,void 0,s)},toManyUpdateFactory=(e,t,n=void 0)=>{let r=nestedRelationDataProjection(e,t),i=r.getCreateSchema,a=r.getUpdateSchema,o=r.getSelectedUpsertUpdateSchema,s=v.object({data:()=>v.array(i()),skipDuplicates:v.boolean({optional:!0})},{atLeast:[`data`],refuse:refuseDefaultOnlySkipDuplicates}),c=v.object({where:()=>t().core.whereUnique,create:i},{partial:!1}),l=v.object({where:()=>t().core.whereUniqueExtended,data:a},{atLeast:[`where`,`data`]}),u=refusingUndefinedOnlyWhere(v.object({where:()=>t().core.where,data:a},{atLeast:[`data`]}),`updateMany`,!0,`where`),d=v.object({where:()=>t().core.whereUniqueExtended,create:i,update:o},{partial:!1}),f=membershipCanBeCleared(e)?{disconnect:()=>v.singleOrArray(t().core.whereUnique)}:{},p=withLinkWrite(e,n);return v.object({create:()=>v.singleOrArray(p(i())),createMany:s,connect:()=>v.singleOrArray(p(t().core.whereUnique)),...f,delete:()=>v.singleOrArray(t().core.whereUniqueExtended),connectOrCreate:v.singleOrArray(p(c)),set:()=>v.singleOrArray(p(t().core.whereUnique)),update:v.singleOrArray(l),updateMany:v.singleOrArray(u),upsert:v.singleOrArray(d),deleteMany:()=>refusingUndefinedOnlyWhere(v.singleOrArray(t().core.where),`deleteMany`,!0)})},toOneSchemas=(e,t,n)=>{let r=e[`~`].state;return{filter:v.lazy(()=>toOneFilterFactory(t,n)),create:v.lazy(()=>toOneCreateFactory(t,n)),update:v.lazy(()=>toOneUpdateFactory(r,t,n)),select:v.lazy(()=>Ke(e,t,n)),include:v.lazy(()=>toOneIncludeFactory(e,t,n)),orderBy:toOneOrderByFactory(e,n),countFilter:v.lazy(()=>countFilterFactory(r,n))}},toManySchemas=(e,t,n,r)=>{let i=e[`~`].state;return{filter:v.lazy(()=>toManyFilterFactory(t,n,r)),create:v.lazy(()=>toManyCreateFactory(t,n,r)),update:v.lazy(()=>toManyUpdateFactory(t,n,r)),select:v.lazy(()=>qe(e,t,n,r)),include:v.lazy(()=>toManyIncludeFactory(e,t,n,r)),orderBy:v.lazy(()=>toManyOrderByFactory(i)),countFilter:v.lazy(()=>countFilterFactory(i,n))}},getRelationSchemas=(e,t,n,r)=>e[`~`].state.cardinality===`many`?toManySchemas(e,t,n,r):toOneSchemas(e,t,n),getRelationsSchemas=(e,t,n)=>{let r={},i=e[`~`].state.relations;for(let a in i){let o=i[a];if(w(o[`~`].state))continue;let s=resolvedSlotOrThrow(e,a,n);r[a]=()=>{let e=t(o),n=junctionModelOf(s);return getRelationSchemas(o,s,e,n&&t({"~":{settleTarget:()=>n}}))}}return lazyRecord(r)},resolvedSlotOrThrow=(e,t,r)=>{let i=r.get(t);if(i)return i;let a=e[`~`].names.ts??`model`;throw new n({kind:`registry`,property:t},[{path:`${a}.${t}`,message:`The resolved relation index does not describe '${a}.${t}'`}])},taggedVerbs=(e,t)=>{let n=polymorphicPublicTypes(e),custom=(e,t={partial:!1})=>v.union(n.map(n=>v.object({type:v.literal(n),...e(n)},t))),core=(e,n)=>custom(n=>Object.fromEntries(Object.entries(e).map(([e,r])=>[e,()=>t[n]().core[r]])),n?{atLeast:[`type`,...n]}:{partial:!1});return{core,custom}},polymorphicPublicTypes=e=>Object.keys(e.target.entries);function collectionVerbs(e,t){let n=t,r=taggedVerbs(e,t),many=(e,t)=>v.singleOrArray(r.core(e,t));return{create:many({data:`create`}),createMany:v.singleOrArray(r.custom(e=>({data:()=>v.array(n[e]().core.create),skipDuplicates:v.boolean({optional:!0})}),{atLeast:[`type`,`data`],refuse:refuseDefaultOnlySkipDuplicates})),connect:many({where:`whereUnique`}),connectOrCreate:many({where:`whereUnique`,create:`create`}),set:many({where:`whereUnique`}),disconnect:many({where:`whereUnique`}),delete:many({where:`whereUniqueExtended`}),deleteMany:refusingUndefinedOnlyWhere(many({where:`where`}),`deleteMany`,!0,`where`),update:many({where:`whereUniqueExtended`,data:`update`},[`where`,`data`]),updateMany:refusingUndefinedOnlyWhere(many({where:`where`,data:`update`},[`data`]),`updateMany`,!0,`where`),upsert:many({where:`whereUniqueExtended`,create:`create`,update:`update`})}}function polymorphicCollectionCreateFactory(e,t){let n=collectionVerbs(e,t);return v.object({create:n.create,createMany:n.createMany,connect:n.connect,connectOrCreate:n.connectOrCreate},{optional:!0})}function polymorphicCollectionUpdateFactory(e,t){let n=collectionVerbs(e,t);return v.object({create:n.create,createMany:n.createMany,connect:n.connect,connectOrCreate:n.connectOrCreate,set:n.set,disconnect:n.disconnect,delete:n.delete,deleteMany:n.deleteMany,update:n.update,updateMany:n.updateMany,upsert:n.upsert})}function taggedTargetPredicate(e,t){let n=polymorphicPublicTypes(e).flatMap(e=>{let n=t[e];return[v.object({type:v.literal(e)},{partial:!1}),v.object({type:v.literal(e),is:()=>n().core.where},{partial:!1}),v.object({type:v.literal(e),isNot:()=>n().core.where},{partial:!1})]});return v.union(n)}function polymorphicCollectionCountFilterFactory(e,t){let n=t;return v.union([v.literal(!0),v.object({where:taggedTargetPredicate(e,n)})])}const polymorphicToOneCountFilterRefusal=()=>v.refused(`A polymorphic to-one slot has no collection to count.`),polymorphicSupplyEntries=e=>({connect:e.core({where:`whereUnique`}),create:e.core({data:`create`}),connectOrCreate:e.core({where:`whereUnique`,create:`create`})});function polymorphicCreateFactory(e,t){return toOneMutationSchema(polymorphicSupplyEntries(taggedVerbs(e,t)),void 0,!1,`exactlyOne`)}function polymorphicCreateManyFactory(e,t){let n=t;return v.union(polymorphicPublicTypes(e).map(e=>v.object({connect:v.object({type:v.literal(e),where:()=>n[e]().core.whereUnique},{partial:!1})},{partial:!1})))}function polymorphicFilterFactory(e,t){let n=taggedTargetPredicate(e,t),r=[v.object({is:v.literal(null)},{partial:!1}),v.object({isNot:v.literal(null)},{partial:!1})],i=v.union(r),o=v.literal(null,{transform:()=>({is:null})}),l=e.optional===!0,u=l?[o,i,n]:[n],d=g(`union`,e=>e===null?l?s(o,e):c(`Expected polymorphic filter with a type`):a(e)?Object.hasOwn(e,`type`)?s(n,e):l?s(i,e):c(`Expected polymorphic filter with a type`):c(`Expected object`));return d.options=u,d}function polymorphicCollectionFilterFactory(e,t,n){let r=taggedTargetPredicate(t,n),i=`Polymorphic collection filter '${e}' requires one of: some, every, none.`;return v.object({some:r,every:r,none:r},{refuse:e=>e.some!==void 0||e.every!==void 0||e.none!==void 0?void 0:i})}const polymorphicCollectionOrderByFactory=()=>v.object({_count:v.enum([`asc`,`desc`])}),polymorphicToOneOrderByRefusal=()=>v.refused(`A polymorphic to-one slot cannot be ordered on: the target model is chosen per row, so there is no single column to sort by.`);function polymorphicSelectFactory(e,t){let n=e[`~`].state,r=t,i={};for(let t of polymorphicPublicTypes(n)){let n=r[t],a=e[`~`].settleTarget(t);i[t]=()=>v.union([v.literal(!0),v.lazy(()=>{let e=n(),r=a,i=withOmitProjection(rejectSelectInclude(v.object({select:()=>e.core.select,include:()=>e.core.include,omit:()=>e.core.omit})),r,`polymorphic.${t}`);return v.coerce(i,e=>{if(e.select!==void 0)return e;let t={};for(let e of projectableScalarNames(r))t[e]=!0;return Object.keys(t).length===0?e:{...e,select:t}})})])}return v.union([v.boolean(),v.object(i)])}const Je=polymorphicSelectFactory,onlyAllowList=e=>{let t=v.enum(e,{array:!0});return Object.assign(g(`polymorphic_only`,n=>{let r=s(t,n);if(r.issues)return r;let i=new Set;for(let e of r.value){if(i.has(e))return c(`Duplicate value in 'only': '${e}'`);i.add(e)}return u(e.filter(e=>i.has(e)))}),{wrapped:t})},rejectVariantsOutsideOnly=e=>{let t=e[`~standard`],validate=e=>{if(!a(e))return t.validate(e);let n=e.only,r=e.variants;if(!(Array.isArray(n)&&a(r)))return t.validate(e);let i=t.validate(e);if(i.issues)return i;let o=new Set(n),s=Object.keys(r).find(e=>!o.has(e));return s===void 0?i:{issues:[{message:`Variant '${s}' is not in 'only'`,path:[`variants`,s]}]}};return{...e,parse:validate,"~standard":{version:t.version,vendor:t.vendor,validate,get types(){return t.types},get jsonSchema(){return t.jsonSchema}}}};function polymorphicCollectionSelectFactory(e,t){let n=e[`~`].state,r=polymorphicPublicTypes(n),i={};for(let n of r){let r=t[n],a=e[`~`].settleTarget(n);i[n]=()=>v.union([v.coerce(v.literal(!0),()=>defaultSelectionNode(a)),v.lazy(()=>buildToManyNestedNode({targetModel:a,label:`polymorphic.${n}`,core:()=>r().core,scalarNames:Object.keys(a[`~`].state.scalars)}))])}let a=rejectVariantsOutsideOnly(v.object({only:onlyAllowList(r),variants:v.object(i)}));return v.union([v.boolean(),a])}const Ye=polymorphicCollectionSelectFactory;function polymorphicUpdateFactory(e,t){let n=taggedVerbs(e,t),r={...polymorphicSupplyEntries(n),update:n.core({where:`where`,data:`update`},[`data`]),upsert:n.core({create:`create`,update:`update`})};return e.optional===!0?toOneMutationSchema({...r,delete:n.core({}),disconnect:v.literal(!0)},void 0,!1,`exactlyOne`):toOneMutationSchema(r,void 0,!1,`exactlyOne`)}function getTargetSchemas(e,t,n){let r={};for(let i of Object.keys(t.target.entries))r[i]=()=>n(e[`~`].settleTarget(i));return r}function getPolymorphicRelationsSchemas(e,t){let n={},r=e[`~`].state.relations;for(let e of Object.keys(r)){let i=r[e],a=i[`~`].state;w(a)&&(n[e]=()=>{let n=getTargetSchemas(i,a,t);return a.cardinality===`many`?lazyRecord({filter:()=>polymorphicCollectionFilterFactory(e,a,n),create:()=>polymorphicCollectionCreateFactory(a,n),createMany:()=>polymorphicCollectionCreateFactory(a,n),update:()=>polymorphicCollectionUpdateFactory(a,n),select:()=>polymorphicCollectionSelectFactory(i,n),include:()=>Ye(i,n),orderBy:()=>polymorphicCollectionOrderByFactory(),countFilter:()=>polymorphicCollectionCountFilterFactory(a,n)}):lazyRecord({filter:()=>polymorphicFilterFactory(a,n),create:()=>polymorphicCreateFactory(a,n),createMany:()=>polymorphicCreateManyFactory(a,n),update:()=>polymorphicUpdateFactory(a,n),select:()=>polymorphicSelectFactory(i,n),include:()=>Je(i,n),orderBy:()=>polymorphicToOneOrderByRefusal(),countFilter:()=>polymorphicToOneCountFilterRefusal()})})}return lazyRecord(n)}const scalarInternKey=(e,t)=>{if(e.schema!==void 0)return null;let n=t===void 0?``:`:${t.format}:${t.prefix??``}:${t.length??``}`;return`${e.nullable?1:0}${e.array?1:0}${e.withTimezone?1:0}${n}`},createScalarInterner=()=>{let e=new Map;return(t,n)=>{if(t===null)return n();let r=e.get(t);return r===void 0&&(r=n(),e.set(t,r)),r}},Xe=new Set([`path`,`mode`]),requireFilterOperation=e=>{for(let t in e)if(Object.hasOwn(e,t)&&!Xe.has(t)&&e[t]!==void 0)return;return`Filter must contain at least one operation.`},buildNegatableFilterSchema=(e,t)=>{let n=v.object({...e.entries,not:v.union([v.shorthandFilter(t),v.lazyRef(()=>n)])},{refuse:requireFilterOperation});return v.union([v.shorthandFilter(t),ie(n)])},comparisonFilterFamily=(e,t,n)=>{let createBase=()=>v.object({in:y(n()),notIn:y(n()),lt:v.comparisonOperand(e,t()),lte:v.comparisonOperand(e,t()),gt:v.comparisonOperand(e,t()),gte:v.comparisonOperand(e,t())}),r;return t=>{r??=createBase();let n=v.comparisonOperand(e,t);return buildNegatableFilterSchema(r.extend({equals:n}),n)}},listFilterFamily=(e,t)=>{let createBase=()=>v.object({has:y(e()),hasEvery:y(t()),hasSome:y(t()),isEmpty:v.boolean()}),n;return e=>(n??=createBase(),buildNegatableFilterSchema(n.extend({equals:y(e)}),e))},Ze=g(`nonzero_divisor`,e=>e===0||e===0n?c(`Division by zero is not allowed`):u(e)),arithmeticUpdateFamily=e=>(t,n=!1)=>v.union([v.shorthandUpdate(t),v.object({set:t,increment:n?v.refused(K):e(),decrement:n?v.refused(K):e(),multiply:n?v.refused(K):e(),divide:n?v.refused(K):withScalarOutputDomain(e(),Ze)})]),K=`Arithmetic on a field with .schema() cannot validate the resulting stored value; use set with a validated value.`;function withScalarOutputDomain(e,t){let n=e[`~standard`].validate,r={...e};Object.defineProperties(r,Object.getOwnPropertyDescriptors(e));let i=Object.getOwnPropertyDescriptors(e[`~standard`]);Reflect.deleteProperty(i,`validate`);let a=Object.defineProperties({},i);return Object.defineProperty(a,`validate`,{value:e=>{let r=n(e);return r.issues?r:s(t,r.value)}}),Object.defineProperty(r,`~standard`,{value:a}),r}const buildSetUpdate=e=>v.union([v.shorthandUpdate(e),v.object({set:e},{partial:!1})]),listUpdateFamily=(e,t)=>n=>v.union([v.shorthandUpdate(n),v.object({set:n,push:v.union([v.shorthandArray(e()),t()]),unshift:v.union([v.shorthandArray(e()),t()])})]),once=e=>{let t;return()=>(t??=e(),t)},createScalarInterners=()=>({update:createScalarInterner(),filter:createScalarInterner()}),internedVariant=(e,t,n)=>()=>e(t,n),internedScalarSchemas=(e,t,n)=>lazyScalarSchemas({base:n.base,create:n.create,update:internedVariant(e.update,t,n.update),filter:internedVariant(e.filter,t,n.filter)}),comparableScalar=(e,t,n)=>{let r=once(()=>t()),i=once(()=>t({array:!0})),a=comparisonFilterFamily(e,r,i),o=listFilterFamily(r,i),s=n?arithmeticUpdateFamily(r):buildSetUpdate,c=listUpdateFamily(r,i),l=createScalarInterners();return e=>{let storedDomain=(n=!1)=>t({nullable:e.nullable,array:e.array,disallowZero:n}),n=e.schema===void 0?e.base:withScalarOutputDomain(e.base,storedDomain()),refinedListUpdate=()=>listUpdateFamily(()=>withScalarOutputDomain(t({...e,array:!1,nullable:!1,optional:!1,default:void 0}),r()),()=>withScalarOutputDomain(t({...e,array:!0,nullable:!1,optional:!1,default:void 0}),i()))(n);return internedScalarSchemas(l,scalarInternKey(e),{base:n,create:()=>e.schema===void 0?t(e):withScalarOutputDomain(t(e),storedDomain(e.disallowZero)),update:()=>e.array?e.schema===void 0?c(e.base):refinedListUpdate():s(n,e.schema!==void 0),filter:()=>e.array?o(storedDomain()):a(storedDomain())})}},Qe=comparableScalar(`bigint`,v.bigint,!0),$e=v.blob({array:!0}),buildBlobFilterSchema=e=>buildNegatableFilterSchema(v.object({equals:e,in:$e,notIn:$e}),e),buildBlobSchema=e=>lazyScalarSchemas({base:e.base,create:()=>v.blob(e),update:()=>buildSetUpdate(e.base),filter:()=>buildBlobFilterSchema(e.base)}),et=once(()=>v.boolean()),tt=once(()=>v.boolean({array:!0})),buildBooleanFilterSchema=e=>{let t=v.comparisonOperand(`boolean`,e);return buildNegatableFilterSchema(v.object({equals:t}),t)},nt=listFilterFamily(et,tt),rt=listUpdateFamily(et,tt),it=createScalarInterners(),buildBooleanSchema=e=>internedScalarSchemas(it,scalarInternKey(e),{base:e.base,create:()=>v.boolean(e),update:()=>e.array?rt(e.base):buildSetUpdate(e.base),filter:()=>e.array?nt(e.base):buildBooleanFilterSchema(e.base)}),ot=comparableScalar(`date`,v.isoDate,!1),st=comparableScalar(`datetime`,v.isoTimestamp,!1),domainOf=e=>({decimal:e.decimal}),decimalComparisonOperand=e=>{let t=v.comparisonOperand(`decimal`,e),n=t[`~standard`].validate,i=g(`comparison_operand`,e=>{let t=n(e);return t.issues?d(t.issues):r(t.value)?c(`An SQL fragment is not a decimal operand: it carries no precision or scale, so the comparison would mean something different on each provider. Use a field reference or raw SQL.`):u(t.value)}),a={type:`comparison_operand`,fieldType:`decimal`,wrapped:e,acceptsUndefined:t.acceptsUndefined};return Object.assign(i,a)},OPERATION_REFUSAL=e=>`A decimal update takes exactly one operation: ${e.join(`, `)}`,ct=new Set([`__defineGetter__`,`__defineSetter__`,`__lookupGetter__`,`__lookupSetter__`,`__proto__`,`constructor`,`hasOwnProperty`,`isPrototypeOf`,`propertyIsEnumerable`,`toLocaleString`,`toString`,`valueOf`]),exactlyOneOperation=e=>{let t=Object.keys(e),n=new Set(t),isOperation=e=>n.has(e),r=g(`exact_one`,n=>{let r;try{if(!a(n))return c(`Expected object`);let e=Reflect.ownKeys(n);if(e.length!==1)return c(OPERATION_REFUSAL(t));let[i]=e;if(typeof i!=`string`||!isOperation(i))return c(OPERATION_REFUSAL(t));let o=new Set,s=Reflect.getPrototypeOf(n);for(;s!==null;){if(o.has(s))return c(OPERATION_REFUSAL(t));o.add(s);let e=s===Object.prototype;for(let n of Reflect.ownKeys(s))if(!e||typeof n!=`string`||!ct.has(n))return c(OPERATION_REFUSAL(t));s=Reflect.getPrototypeOf(s)}let l=Reflect.get(n,i);if(l===void 0)return c(OPERATION_REFUSAL(t));r={operation:i,operand:l}}catch{return c(OPERATION_REFUSAL(t))}let{operation:i,operand:o}=r,l=e[i],d=s(l,o);if(d.issues){if(l.type===`refused`)return d;let[e]=d.issues;return c(e.message,[i,...e.path??[]])}let f=Object.create(null);return f[i]=d.value,u(f)}),i={type:`exact_one`,entries:e};return Object.assign(r,i)},buildDecimalCreateSchema=e=>{if(!e.hasDefault||typeof e.default==`function`)return v.decimal(e);if(e.array&&Array.isArray(e.default)){let t=e.default;return v.optional(e.base,()=>t.slice())}return v.optional(e.base,e.default)};function buildDecimalSchema(e){let t=domainOf(e),member=()=>v.decimal(t),list=()=>v.decimal({...t,array:!0}),writeMember=()=>v.decimal({...t,schema:e.schema}),writeList=()=>v.decimal({...t,array:!0,schema:e.schema}),arithmeticMember=()=>e.schema===void 0?member():v.refused(K),filterBase=()=>v.decimal({...t,nullable:e.nullable,array:e.array});return lazyScalarSchemas({base:e.base,create:()=>buildDecimalCreateSchema(e),update:()=>e.array?v.union([v.shorthandUpdate(e.base),exactlyOneOperation({set:e.base,push:v.union([v.shorthandArray(writeMember()),writeList()]),unshift:v.union([v.shorthandArray(writeMember()),writeList()]),increment:v.refused(`A decimal list update does not support 'increment'.`),decrement:v.refused(`A decimal list update does not support 'decrement'.`),multiply:v.refused(`A decimal list update does not support 'multiply'.`),divide:v.refused(`A decimal list update does not support 'divide'.`)})]):v.union([v.shorthandUpdate(e.base),exactlyOneOperation({set:e.base,increment:arithmeticMember(),decrement:arithmeticMember(),multiply:arithmeticMember(),divide:arithmeticMember()})]),filter:()=>e.array?buildNegatableFilterSchema(v.object({equals:filterBase(),has:member(),hasEvery:list(),hasSome:list(),isEmpty:v.boolean(),in:v.refused(`A decimal list filter does not support 'in'.`),notIn:v.refused(`A decimal list filter does not support 'notIn'.`),lt:v.refused(`A decimal list filter does not support 'lt'.`),lte:v.refused(`A decimal list filter does not support 'lte'.`),gt:v.refused(`A decimal list filter does not support 'gt'.`),gte:v.refused(`A decimal list filter does not support 'gte'.`)}),filterBase()):buildDecimalFilterSchema(filterBase(),member,list)})}const buildDecimalFilterSchema=(e,t,n)=>{let r=decimalComparisonOperand(e);return buildNegatableFilterSchema(v.object({equals:r,in:y(n()),notIn:y(n()),lt:decimalComparisonOperand(t()),lte:decimalComparisonOperand(t()),gt:decimalComparisonOperand(t()),gte:decimalComparisonOperand(t())}),r)},orderedEnumRefusal=e=>v.refused(`Filter operation '${e}' is not supported on an enum field: PostgreSQL orders enum values by their declaration order while MySQL and SQLite compare them as text, so the same query would answer differently per provider. Use 'equals'/'in', or model the field as a string or int if you need ordering.`),enumBase=e=>v.enum(e),enumList=e=>v.enum(e,{array:!0}),buildEnumFilterSchema=(e,t)=>{let n=enumList(t),r=v.comparisonOperand(`enum`,e);return buildNegatableFilterSchema(v.object({equals:r,in:y(n),notIn:y(n),lt:orderedEnumRefusal(`lt`),lte:orderedEnumRefusal(`lte`),gt:orderedEnumRefusal(`gt`),gte:orderedEnumRefusal(`gte`)}),r)},buildEnumListFilterSchema=(e,t)=>listFilterFamily(()=>enumBase(t),()=>enumList(t))(e),buildEnumListUpdateSchema=(e,t)=>listUpdateFamily(()=>enumBase(t),()=>enumList(t))(e),buildEnumSchema=e=>{let t=e.base.values;return lazyScalarSchemas({base:e.base,create:()=>v.enum(t,e),update:()=>e.array?buildEnumListUpdateSchema(e.base,t):buildSetUpdate(e.base),filter:()=>e.array?buildEnumListFilterSchema(e.base,t):buildEnumFilterSchema(e.base,t)})},lt=comparableScalar(`int`,v.integer,!0),q=`a JSON filter operand`,J=`JSON write data`,Y=[`DbNull`,`JsonNull`,`AnyNull`],ut=[`DbNull`,`JsonNull`],dt=[`JsonNull`],ft=/^\d+$/,unsupportedPathString=(e,t)=>`JSON filter has an unsupported path string '${e}': ${t}. The supported grammar is '\$', '\$.key', '\$.key[0]' and nothing else; use the array form (path: ['a', 'b']) for keys containing '.', '[' or ']'.`,parseJsonStringPath=e=>{if(!e.startsWith(`$`))return unsupportedPathString(e,`a path string must start with '$'`);let t=[],n=1;for(;n<e.length;){let r=e[n];if(r===`.`){n+=1;let r=n;for(;n<e.length&&e[n]!==`.`&&e[n]!==`[`;)n+=1;let i=e.slice(r,n);if(i.length===0)return unsupportedPathString(e,`an object key may not be empty`);if(i.includes(`*`))return unsupportedPathString(e,`wildcards are not supported`);t.push(i);continue}if(r===`[`){let r=e.indexOf(`]`,n);if(r===-1)return unsupportedPathString(e,`an unclosed '['`);let i=e.slice(n+1,r);if(!ft.test(i))return unsupportedPathString(e,`'[${i}]' is not a non-negative integer array index`);t.push(i),n=r+1;continue}return unsupportedPathString(e,`unexpected '${r}'`)}return t},portablePathRefusal=e=>e.some(e=>e.includes(`"`)||e.includes(`\\`))?`JSON filter requires a portable JSON path; segments containing '"' or '\\' are not supported.`:void 0,pt=v.array(v.string()),mt=v.string(),buildJsonPathSchema=()=>{let e=g(`union`,e=>{if(Array.isArray(e)){let t=e.map(String),n=portablePathRefusal(t);return n?c(n):u(t)}if(typeof e!=`string`)return c(`Expected string or array of strings`);let t=parseJsonStringPath(e);if(typeof t==`string`)return c(t);let n=portablePathRefusal(t);return n?c(n):u(t)});return e.options=[pt,mt],e},ht=[`string_contains`,`string_starts_with`,`string_ends_with`],inertModeRefusal=e=>{if(e.mode===`insensitive`&&!(e.not!==void 0&&_(e.not)===void 0))return ht.some(t=>e[t]!==void 0)?void 0:`JSON filter sets mode: 'insensitive' but has no string_contains/string_starts_with/string_ends_with operation for it to apply to.`},pathSentinelRefusal=e=>{if(e.path===void 0)return;let{equals:t,not:n}=e,r=_(t)??_(n)??(a(n)?_(n.equals):void 0);return r&&`JSON filter cannot combine 'path' with the ${r} sentinel: the sentinels distinguish the database NULL from the JSON null value of the WHOLE column. Use 'path' with 'equals: null' to test for a JSON null at that path.`},buildJsonFilterSchema=e=>{let t=v.union([v.number(),v.string()]),n=v.noFieldRef(e,q),r={equals:y(v.jsonNullOr(Y,n,q)),path:buildJsonPathSchema(),mode:v.enum([`default`,`insensitive`]),lt:t,lte:t,gt:t,gte:t,string_contains:v.string(),string_starts_with:v.string(),string_ends_with:v.string(),array_contains:n,array_starts_with:n,array_ends_with:n},refuse=e=>requireFilterOperation(e)??inertModeRefusal(e)??pathSentinelRefusal(e),i=v.object(r,{refuse}),a=v.object({...r,not:v.jsonNullOr(Y,i,q)},{refuse}),o=a[`~standard`].validate;return Object.defineProperty(a[`~standard`],`validate`,{value:e=>{let t=_(e);return t?c(`${t} is an operand, not a JSON filter; compare with { equals: ${t} }.`):o(e)}}),a},nullWriteRefusal=e=>e?`null is ambiguous in JSON write data: it could mean the database NULL or the JSON value null. Use DbNull for the database NULL, or JsonNull for the JSON value null.`:`null is ambiguous in JSON write data: it could mean the database NULL or the JSON value null. This field is not nullable, so use JsonNull to write the JSON value null.`,buildJsonWriteOperand=(e,t)=>v.jsonWrite(e.nullable?ut:dt,v.noFieldRef(t,J),J,nullWriteRefusal(e.nullable)),isSetEnvelope=e=>a(e)&&Object.hasOwn(e,`set`)&&Object.keys(e).length===1,buildJsonUpdateSchema=(e,t)=>{let n=buildJsonWriteOperand(e,t),r=v.object({set:n},{partial:!1}),i=v.shorthandUpdate(n),a=v.union([r,i]);return Object.defineProperty(a[`~standard`],`validate`,{value:e=>isSetEnvelope(e)?s(r,e):s(i,e)}),a},buildJsonSchema=e=>lazyScalarSchemas({base:e.base,create:()=>{let t=buildJsonWriteOperand(e,v.json(e)),n=t[`~standard`].validate,admit=t=>{if(t!==void 0||!e.hasDefault)return n(t);let r;try{r=typeof e.default==`function`?e.default():e.default}catch{return c(`JSON default failed`)}return r===void 0?c(`JSON default must resolve to a value`):r===null?e.nullable?u(null):n(re):n(r)};return Object.defineProperty(t[`~standard`],`validate`,{value:e=>{if(!isSetEnvelope(e))return admit(e);let t=admit(e.set);return t.issues?{issues:t.issues.map(({message:e,path:t})=>({message:e,path:[`set`,...t??[]]}))}:t}}),t},update:()=>buildJsonUpdateSchema(e,e.base),filter:()=>buildJsonFilterSchema(v.json())}),gt=comparableScalar(`number`,v.number,!0),X=g(`number`,e=>{let t=p(e);return t.issues?t:t.value<0?c(`Distance comparisons must use non-negative meters`):u(t.value)}),pointDistanceSchema=()=>v.object({to:v.point(),lt:X,lte:X,gt:X,gte:X},{atLeast:[`to`],requiresOneOf:[[`lt`,`lte`,`gt`,`gte`]]}),buildPointFilterSchema=e=>buildNegatableFilterSchema(v.object({equals:e,distance:pointDistanceSchema(),within:fe()}),e),buildPointSchema=e=>lazyScalarSchemas({base:e.base,create:()=>v.point(e),update:()=>buildSetUpdate(e.base),filter:()=>buildPointFilterSchema(e.base)}),Z=once(()=>v.string()),Q=once(()=>v.string({array:!0})),_t=once(()=>v.object({in:Q(),notIn:Q(),contains:v.fieldRefOr(`string`,Z()),startsWith:v.fieldRefOr(`string`,Z()),endsWith:v.fieldRefOr(`string`,Z()),mode:v.enum([`default`,`insensitive`])})),vt=once(()=>v.object({in:Q(),notIn:Q()})),buildStringFilterSchema=(e,t)=>{let n=v.comparisonOperand(`string`,e);return buildNegatableFilterSchema(_t().extend({equals:n,lt:n,lte:n,gt:n,gte:n,in:y(t),notIn:y(t)}),n)},buildCompactIdFilterSchema=(e,t)=>{let n=v.comparisonOperand(`string`,e);return buildNegatableFilterSchema(vt().extend({equals:n,lt:n,lte:n,gt:n,gte:n,in:y(t),notIn:y(t)}),n)},yt=listFilterFamily(Z,Q),bt=listUpdateFamily(Z,Q),xt=createScalarInterners(),domainBaseOf=(e,t)=>{if(t===void 0)return e.base;let n={nullable:e.nullable,array:e.array,schema:e.schema,idDomain:t};return v.string(n)},domainMembersOf=e=>e===void 0?Q():v.string({array:!0,idDomain:e}),domainStateOf=(e,t)=>t===void 0?e:{...e,idDomain:t},buildStringSchema=(e,t)=>{let n=e.array===!0?le(e):ue(e)??t,filterBase=()=>v.string({nullable:e.nullable,array:e.array,idDomain:n}),r=domainBaseOf(e,n),i=e.schema===void 0||n!==void 0?r:withScalarOutputDomain(r,filterBase()),refinedListUpdate=()=>listUpdateFamily(()=>n===void 0?withScalarOutputDomain(v.string({schema:e.schema}),Z()):v.string({schema:e.schema,idDomain:n}),()=>n===void 0?withScalarOutputDomain(v.string({array:!0,schema:e.schema}),Q()):v.string({array:!0,schema:e.schema,idDomain:n}))(i);return internedScalarSchemas(xt,scalarInternKey(e,n),{base:i,create:()=>e.schema===void 0||n!==void 0?v.string(domainStateOf(e,n)):withScalarOutputDomain(v.string(domainStateOf(e,n)),filterBase()),update:()=>e.array?e.schema===void 0&&n===void 0?bt(i):refinedListUpdate():buildSetUpdate(i),filter:()=>e.array?n===void 0?yt(filterBase()):listFilterFamily(()=>v.string({idDomain:n}),()=>domainMembersOf(n))(filterBase()):n!==void 0&&m(n.format)?buildCompactIdFilterSchema(filterBase(),domainMembersOf(n)):buildStringFilterSchema(filterBase(),domainMembersOf(n))})},St=comparableScalar(`time`,v.isoTime,!1),buildVectorFilterSchema=e=>buildNegatableFilterSchema(v.object({equals:e}),e),buildVectorSchema=e=>lazyScalarSchemas({base:e.base,create:()=>v.vector(e.dimension,e),update:()=>buildSetUpdate(e.base),filter:()=>buildVectorFilterSchema(e.base)}),getScalarSchemas=(e,t)=>Ct[e.type](e,t),Ct={bigint:Qe,blob:buildBlobSchema,boolean:buildBooleanSchema,datetime:st,decimal:buildDecimalSchema,enum:buildEnumSchema,int:lt,json:buildJsonSchema,number:gt,point:buildPointSchema,string:buildStringSchema,vector:buildVectorSchema,date:ot,time:St},getScalarsSchemas=(e,t)=>{let n={},r=e[`~`].state.scalars;for(let e in r){let i=r[e][`~`].state;n[e]=()=>{let n=getScalarSchemas(i,t?.get(e));return i.autoGenerate?.kind===`now`?insertOnly(n):i.autoGenerate?.kind===`updatedAt`&&!i.array?updatesAt(n,i.type):n}}return lazyRecord(n)},insertOnly=e=>Object.defineProperty(e,`update`,{value:void 0,enumerable:!0}),updatedAtUpdate=(e,t)=>{let n={acceptsUndefined:!0,wrapped:e};return Object.assign(g(`optional`,n=>s(e,n===void 0?de(t):n)),n)},updatesAt=(e,t)=>lazyScalarSchemas({base:e.base,create:()=>e.create,update:()=>updatedAtUpdate(e.update,t),filter:()=>e.filter});var SchemaRegistry=class{#e=new Map;#t;#n;proxy;constructor(e,t){this.#t=e,this.#n=t,this.proxy=new Proxy({},{get:(t,r)=>{if(!(o(r)&&Object.hasOwn(e,r)&&e[r])){let e=String(r);throw new n({kind:`registry`,property:e},[{path:e,message:`${e} does not exist`}])}return this.getModelSchemas(e[r])}})}#r=e=>()=>{let t=e[`~`].settleTarget();return this.getModelSchemas(t)};#i=e=>{let t=getScalarsSchemas(e,ae(this.#n).get(e)),n=this.#n.get(e),r=getRelationsSchemas(e,this.#r,n),i=getPolymorphicRelationsSchemas(e,this.getModelSchemas),{args:a,core:o}=getModelSchemas(e,{scalars:t,relations:r,polymorphic:i},n);return{scalars:t,relations:r,polymorphic:i,args:a,core:o}};getModelSchemas=e=>{let t=this.#e.get(e);return t||(t=this.#i(e),this.#e.set(e,t)),t};validate=(e,t,r)=>{let i=Object.hasOwn(this.#t,e)?this.#t[e]:void 0;if(!i){let r=String(e);throw new n({kind:`operation`,operation:t,model:r},[{path:r,message:`${r} does not exist`}],{meta:{model:r}})}let a=this.getModelSchemas(i);if(!Object.hasOwn(a.args,t))throw new n({kind:`registry`,model:e,property:String(t)},[{path:`operation`,message:`${String(t)} does not exist`}]);try{let i=s(a.args[t],r);if(i.issues)throw new n(t,i.issues.map(e=>({path:e.path?.map(e=>e).join(`.`)??``,message:e.message})),{meta:{model:e}});return i.value??{}}catch(r){throw r instanceof n?r:new n({kind:`operation`,operation:t,model:e},[{path:``,message:`The external schema validator threw unexpectedly`}],{...r instanceof Error?{cause:r}:{},meta:{model:e}})}}};const createResolvedSchemaRegistry=(e,t)=>new SchemaRegistry(e,t),createSchemaRegistry=e=>(ce(e),createResolvedSchemaRegistry(e,se(e))),wt=` vibInferred`,isPromiseLike=e=>a(e)&&`then`in e&&i(e.then),Tt={issues:[{message:`Async validation is not supported`}]},$={issues:[{message:`Schema returned a malformed validation result`}]};function parse(e,t,n){try{let r=l(n?.allIssues===!0,()=>e[`~standard`].validate(t));if(isPromiseLike(r))return f(r),Tt;if(!a(r))return $;let i=Reflect.get(r,`issues`);return i===void 0?`value`in r?{value:Reflect.get(r,`value`)}:$:Array.isArray(i)?{issues:i}:$}catch(e){return ee(e)}}export{Pe as a,projectableScalarNames as c,clearableMembership as d,slotMayBeEmpty as f,createSchemaRegistry as i,groupedColumn as l,wt as n,carriesRepeatedKey as o,createResolvedSchemaRegistry as r,junctionModelOf as s,parse as t,timeStepUnsupported as u};
2
+ //# sourceMappingURL=validation-D0LG854o.mjs.map