viborm 1.2.4 → 1.3.1

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 (275) hide show
  1. package/README.md +6 -1
  2. package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
  3. package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
  4. package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
  5. package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
  6. package/dist/adapters.d.mts +1 -1
  7. package/dist/adapters.mjs +1 -1
  8. package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
  9. package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
  10. package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
  11. package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
  12. package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
  13. package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
  14. package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
  15. package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
  16. package/dist/builder-s1ySUuMb.mjs +2 -0
  17. package/dist/builder-s1ySUuMb.mjs.map +1 -0
  18. package/dist/bun-sql.d.mts +3 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sql.mjs.map +1 -1
  21. package/dist/bun-sqlite.d.mts +1 -1
  22. package/dist/bun-sqlite.mjs +1 -1
  23. package/dist/cache/cloudflare-kv.d.mts +1 -1
  24. package/dist/cache/cloudflare-kv.mjs +1 -1
  25. package/dist/cache/memory.d.mts +1 -1
  26. package/dist/cache/memory.mjs +1 -1
  27. package/dist/{cache-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
  28. package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
  29. package/dist/cache.d.mts +1 -1
  30. package/dist/cache.mjs +1 -1
  31. package/dist/cache.mjs.map +1 -1
  32. package/dist/{canonical-json-rfC2Dg0X.mjs → canonical-json-BReb5nFO.mjs} +2 -2
  33. package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
  34. package/dist/chain-7qiFSE8J.mjs +2 -0
  35. package/dist/chain-7qiFSE8J.mjs.map +1 -0
  36. package/dist/cli.mjs +2 -2
  37. package/dist/cli.mjs.map +1 -1
  38. package/dist/client-6YgGlXzN.mjs +2 -0
  39. package/dist/client-6YgGlXzN.mjs.map +1 -0
  40. package/dist/{client-CUnPXifK.d.mts → client-70MrTq1E.d.mts} +3 -3
  41. package/dist/client-BgJ7Faln.mjs +49 -0
  42. package/dist/{client-B3VWFhv_.mjs.map → client-BgJ7Faln.mjs.map} +1 -1
  43. package/dist/client.d.mts +2 -2
  44. package/dist/client.mjs +1 -1
  45. package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
  46. package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
  47. package/dist/config.d.mts +2 -2
  48. package/dist/config.mjs +1 -1
  49. package/dist/controls-KQ85SWfT.mjs +2 -0
  50. package/dist/controls-KQ85SWfT.mjs.map +1 -0
  51. package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
  52. package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
  53. package/dist/d1.d.mts +1 -1
  54. package/dist/d1.mjs +1 -1
  55. package/dist/d1.mjs.map +1 -1
  56. package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
  57. package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
  58. package/dist/driver-B9fIori_.mjs +2 -0
  59. package/dist/driver-B9fIori_.mjs.map +1 -0
  60. package/dist/{driver-B19QlFqn.mjs → driver-vn-9CN0y.mjs} +2 -2
  61. package/dist/{driver-B19QlFqn.mjs.map → driver-vn-9CN0y.mjs.map} +1 -1
  62. package/dist/driver.d.mts +1 -1
  63. package/dist/driver.mjs +1 -1
  64. package/dist/error-mapping-C9WgitPi.mjs +2 -0
  65. package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
  66. package/dist/every-CcpKWCVo.mjs +2 -0
  67. package/dist/{every-o-Nu9Em8.mjs.map → every-CcpKWCVo.mjs.map} +1 -1
  68. package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
  69. package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
  70. package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
  71. package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
  72. package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
  73. package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
  74. package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
  75. package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
  76. package/dist/hydration-BsPZI4jE.mjs +2 -0
  77. package/dist/{hydration-CAxOL4aI.mjs.map → hydration-BsPZI4jE.mjs.map} +1 -1
  78. package/dist/identifier-conversion-BneQiLxQ.mjs +2 -0
  79. package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-BneQiLxQ.mjs.map} +1 -1
  80. package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
  81. package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
  82. package/dist/{index-B0b7asA4.d.mts → index-VsM29vYN.d.mts} +5257 -4915
  83. package/dist/index.d.mts +3 -3
  84. package/dist/index.mjs +1 -1
  85. package/dist/index.mjs.map +1 -1
  86. package/dist/instrumentation.d.mts +1 -1
  87. package/dist/instrumentation.mjs +1 -1
  88. package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
  89. package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
  90. package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
  91. package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
  92. package/dist/key-D9LtHxVK.mjs +2 -0
  93. package/dist/{key-BeoOwGr3.mjs.map → key-D9LtHxVK.mjs.map} +1 -1
  94. package/dist/{libsql-Drp-zaxq.mjs → libsql-BlSBYwd_.mjs} +3 -3
  95. package/dist/{libsql-Drp-zaxq.mjs.map → libsql-BlSBYwd_.mjs.map} +1 -1
  96. package/dist/libsql.d.mts +1 -1
  97. package/dist/libsql.mjs +1 -1
  98. package/dist/{memory-CDTUZQWL.mjs → memory-C0k-_S_n.mjs} +2 -2
  99. package/dist/{memory-CDTUZQWL.mjs.map → memory-C0k-_S_n.mjs.map} +1 -1
  100. package/dist/migrations/mysql.d.mts +5 -5
  101. package/dist/migrations/mysql.mjs +1 -1
  102. package/dist/migrations/postgres.d.mts +5 -5
  103. package/dist/migrations/postgres.mjs +1 -1
  104. package/dist/migrations/sqlite.d.mts +5 -5
  105. package/dist/migrations/sqlite.mjs +1 -1
  106. package/dist/migrations/storage/durable-object.d.mts +1 -1
  107. package/dist/migrations/storage/durable-object.mjs +1 -1
  108. package/dist/migrations/storage/fs.d.mts +1 -1
  109. package/dist/migrations/storage/fs.mjs +1 -1
  110. package/dist/migrations/storage/r2.d.mts +1 -1
  111. package/dist/migrations/storage/r2.mjs +1 -1
  112. package/dist/migrations/tenant.d.mts +3 -3
  113. package/dist/migrations/tenant.mjs +1 -1
  114. package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
  115. package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
  116. package/dist/migrations.d.mts +5 -5
  117. package/dist/migrations.mjs +1 -1
  118. package/dist/{mysql-D7zC03yD.mjs → mysql-DOLHwIM_.mjs} +6 -6
  119. package/dist/{mysql-D7zC03yD.mjs.map → mysql-DOLHwIM_.mjs.map} +1 -1
  120. package/dist/mysql-adapter-C6c5govr.mjs +2 -0
  121. package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
  122. package/dist/mysql2.d.mts +1 -1
  123. package/dist/mysql2.mjs +1 -1
  124. package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
  125. package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
  126. package/dist/neon-http.d.mts +3 -1
  127. package/dist/neon-http.mjs +1 -1
  128. package/dist/neon-http.mjs.map +1 -1
  129. package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
  130. package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
  131. package/dist/{object-store-DMFXXQEC.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
  132. package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
  133. package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
  134. package/dist/permissions.d.mts +424 -0
  135. package/dist/permissions.mjs +2 -0
  136. package/dist/permissions.mjs.map +1 -0
  137. package/dist/pg.d.mts +9 -1
  138. package/dist/pg.mjs +1 -1
  139. package/dist/pg.mjs.map +1 -1
  140. package/dist/pglite.d.mts +3 -1
  141. package/dist/pglite.mjs +1 -1
  142. package/dist/pglite.mjs.map +1 -1
  143. package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
  144. package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
  145. package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
  146. package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
  147. package/dist/planetscale.d.mts +1 -1
  148. package/dist/planetscale.mjs +1 -1
  149. package/dist/{planner-C0Q7ks-V.d.mts → planner-C1NzLBge.d.mts} +1 -1
  150. package/dist/{postgres-Dv-QnnbD.mjs → postgres-DQVSTqVm.mjs} +4 -4
  151. package/dist/{postgres-Dv-QnnbD.mjs.map → postgres-DQVSTqVm.mjs.map} +1 -1
  152. package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
  153. package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
  154. package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
  155. package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
  156. package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
  157. package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
  158. package/dist/postgres.d.mts +3 -1
  159. package/dist/postgres.mjs +1 -1
  160. package/dist/postgres.mjs.map +1 -1
  161. package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
  162. package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
  163. package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
  164. package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
  165. package/dist/result-shape-B6yWtnx_.mjs +2 -0
  166. package/dist/result-shape-B6yWtnx_.mjs.map +1 -0
  167. package/dist/scalar-CpEwuJvn.mjs +4 -0
  168. package/dist/scalar-CpEwuJvn.mjs.map +1 -0
  169. package/dist/schema/json.d.mts +1 -1
  170. package/dist/schema/json.mjs +1 -1
  171. package/dist/schema/json.mjs.map +1 -1
  172. package/dist/schema-BnzGHn7k.mjs +2 -0
  173. package/dist/{schema-Cjem1-0f.mjs.map → schema-BnzGHn7k.mjs.map} +1 -1
  174. package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-DZsdP6bi.mjs} +4 -4
  175. package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-DZsdP6bi.mjs.map} +1 -1
  176. package/dist/schema.d.mts +1 -1
  177. package/dist/schema.mjs +1 -1
  178. package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
  179. package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
  180. package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
  181. package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
  182. package/dist/soft-delete.d.mts +27 -96
  183. package/dist/soft-delete.mjs +1 -1
  184. package/dist/soft-delete.mjs.map +1 -1
  185. package/dist/sql-Bhxq9arK.mjs +2 -0
  186. package/dist/sql-Bhxq9arK.mjs.map +1 -0
  187. package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
  188. package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
  189. package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
  190. package/dist/sql.d.mts +1 -1
  191. package/dist/sql.mjs +1 -1
  192. package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
  193. package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
  194. package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
  195. package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
  196. package/dist/sqlite3.d.mts +3 -1
  197. package/dist/sqlite3.mjs +1 -1
  198. package/dist/sqlite3.mjs.map +1 -1
  199. package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
  200. package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
  201. package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
  202. package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
  203. package/dist/to-many-C5RMZl05.mjs +2 -0
  204. package/dist/to-many-C5RMZl05.mjs.map +1 -0
  205. package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
  206. package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
  207. package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
  208. package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
  209. package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
  210. package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
  211. package/dist/{utils-CZNaOZR7.mjs → utils-C3r4gO3Y.mjs} +4 -4
  212. package/dist/{utils-CZNaOZR7.mjs.map → utils-C3r4gO3Y.mjs.map} +1 -1
  213. package/dist/v-DtLdBQYg.mjs +2 -0
  214. package/dist/v-DtLdBQYg.mjs.map +1 -0
  215. package/dist/validation-BQtO6srU.mjs +2 -0
  216. package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
  217. package/dist/validation-BamBwne9.mjs +2 -0
  218. package/dist/validation-BamBwne9.mjs.map +1 -0
  219. package/dist/validation.d.mts +1 -1
  220. package/dist/validation.mjs +1 -1
  221. package/dist/validator-CVSrhn0u.mjs +2 -0
  222. package/dist/validator-CVSrhn0u.mjs.map +1 -0
  223. package/dist/version-C8QLCt1n.mjs +2 -0
  224. package/dist/{version-nt0parEY.mjs.map → version-C8QLCt1n.mjs.map} +1 -1
  225. package/package.json +36 -9
  226. package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
  227. package/dist/builder-Ycvq3ETg.mjs +0 -2
  228. package/dist/builder-Ycvq3ETg.mjs.map +0 -1
  229. package/dist/chain-Dh0FV72b.mjs +0 -2
  230. package/dist/chain-Dh0FV72b.mjs.map +0 -1
  231. package/dist/client-B3VWFhv_.mjs +0 -49
  232. package/dist/client-BLiBmykn.mjs +0 -2
  233. package/dist/client-BLiBmykn.mjs.map +0 -1
  234. package/dist/controls-DXgIn4zh.mjs +0 -2
  235. package/dist/controls-DXgIn4zh.mjs.map +0 -1
  236. package/dist/driver-BlnKXPFF.mjs +0 -2
  237. package/dist/driver-BlnKXPFF.mjs.map +0 -1
  238. package/dist/error-mapping-CnPCv1dm.mjs +0 -2
  239. package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
  240. package/dist/every-o-Nu9Em8.mjs +0 -2
  241. package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
  242. package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
  243. package/dist/hydration-CAxOL4aI.mjs +0 -2
  244. package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
  245. package/dist/identifier-hQCs8M1n.mjs +0 -2
  246. package/dist/identifier-hQCs8M1n.mjs.map +0 -1
  247. package/dist/key-BeoOwGr3.mjs +0 -2
  248. package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
  249. package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
  250. package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
  251. package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
  252. package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
  253. package/dist/registration-preflight-DEjv050M.mjs +0 -4
  254. package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
  255. package/dist/result-shape-CTNdNSW3.mjs +0 -2
  256. package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
  257. package/dist/scalar-U0wD5bKy.mjs +0 -2
  258. package/dist/scalar-U0wD5bKy.mjs.map +0 -1
  259. package/dist/schema-Cjem1-0f.mjs +0 -2
  260. package/dist/sql-Bp7jicEX.mjs +0 -2
  261. package/dist/sql-Bp7jicEX.mjs.map +0 -1
  262. package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
  263. package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
  264. package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
  265. package/dist/terminal-C8cq1WWX.mjs +0 -2
  266. package/dist/terminal-C8cq1WWX.mjs.map +0 -1
  267. package/dist/v-D5Z06FKN.mjs +0 -2
  268. package/dist/v-D5Z06FKN.mjs.map +0 -1
  269. package/dist/validation-Dk9Q_-C7.mjs +0 -2
  270. package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
  271. package/dist/validation-PF9-_nKd.mjs +0 -2
  272. package/dist/validator-X9-bwtRo.mjs +0 -2
  273. package/dist/validator-X9-bwtRo.mjs.map +0 -1
  274. package/dist/version-nt0parEY.mjs +0 -2
  275. /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{b as r,c as i,d as a,l as o,m as s,n as c,p as l,r as u,s as d}from"./controls-KQ85SWfT.mjs";import{_ as f,a as p,g as m,m as h,n as g,r as _,u as v}from"./bind-parameter-capacity-qfEejeOX.mjs";import{c as y,f as b,i as x,l as S,n as ee,p as C,r as te,s as w,u as T}from"./chain-7qiFSE8J.mjs";import{S as ne,b as E,i as D,n as O,t as re}from"./base-D3m1S7Uc.mjs";import{_ as ie,i as ae,t as oe,x as k,y as se}from"./error-mapping-C9WgitPi.mjs";import{a as ce,c as A,d as le,f as j,l as M,m as N,o as ue,p as de,r as P,s as fe,t as pe,u as F,y as I}from"./validation-BamBwne9.mjs";import{n as L,t as R}from"./transaction-4dfqals6.mjs";import{A as me,M as he,N as ge,P as z,_ as B,d as _e,f as ve,u as ye}from"./v-DtLdBQYg.mjs";import{$ as be,A as xe,At as Se,D as Ce,M as we,Mt as Te,N as Ee,O as De,Q as Oe,S as ke,Z as Ae,at as je,b as Me,d as Ne,f as Pe,it as Fe,k as Ie,m as Le,ot as Re,r as ze,ut as Be,x as Ve,z as He}from"./geo-point-codec-DyEHMdJg.mjs";import{o as V,r as Ue,t as H}from"./sql-Bhxq9arK.mjs";import{t as We}from"./hydration-BsPZI4jE.mjs";import{c as Ge,m as U,n as Ke,p as qe,s as Je,t as Ye,u as Xe}from"./validator-CVSrhn0u.mjs";import{a as Ze,i as Qe,o as $e,r as et,s as tt,t as nt}from"./builder-s1ySUuMb.mjs";import{r as rt}from"./geo-area-codec-CbkmFArQ.mjs";import{d as it,i as at,o as ot}from"./observation-Co72iCd1.mjs";import{C as st,S as ct,T as lt,_ as ut,b as dt,f as ft,g as pt,h as mt,i as ht,l as gt,o as _t,p as vt,r as yt,s as bt,t as xt,v as W,w as St,x as Ct,y as wt}from"./result-shape-B6yWtnx_.mjs";import{i as Tt,n as Et}from"./execution-context-rJXTRVrJ.mjs";import{n as Dt,r as G,t as Ot}from"./transaction-operation-CU1zlxiG.mjs";import{n as K,t as q}from"./adapter-internals-AGgQRu5t.mjs";import{n as kt,t as At}from"./datetime-physical-codec-BEqQbIP_.mjs";import{n as jt}from"./invariant-D57gi_yW.mjs";import{t as Mt}from"./validation-BQtO6srU.mjs";import{n as Nt,t as Pt}from"./provider-limits-Da00ilvv.mjs";const Ft=Object.freeze({$executeRaw:!0,$executeRawUnsafe:!0,$queryRaw:!0,$queryRawUnsafe:!0});function isRawWrite(e){return e===`$executeRaw`||e===`$executeRawUnsafe`}function isTemplateStringsArray(e){return Array.isArray(e)&&Array.isArray(Reflect.get(e,`raw`))}function rawInputError(e,t,n){return new de(`${e} ${t}`,{code:O.INVALID_INPUT,meta:n===void 0?{method:e}:{method:e,parameterIndex:n}})}function copyIndexedValues(e){let t=Array(e.length);for(let n=0;n<e.length;n+=1)Object.hasOwn(e,n)&&(t[n]=e[n]);return t}function copySqlStrings(e){let t=Array(e.length);for(let n=0;n<e.length;n+=1){let r=Object.getOwnPropertyDescriptor(e,n);if(r===void 0||!(`value`in r)||typeof r.value!=`string`)throw TypeError(`Sql fragment strings must be plain string values`);t[n]=r.value}return t}function createOperationSql(e){return new H(copySqlStrings(e.strings),copyIndexedValues(e.values))}function validateRawParametersBeforeInterception(e,t){v(t,{invalidDate:t=>rawInputError(e,`received an invalid Date as bound parameter ${t}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,t),unsupportedArray:t=>rawInputError(e,`received raw array parameter ${t} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,t)})}function captureValues(e){return Object.freeze(copyIndexedValues(e))}const It=Object.freeze({});let createDeferredRawOperation,Lt;(class DeferredRawOperation{[Symbol.toStringTag]=`Promise`;#e;#t;#n;#r;#i;#a;#o;#s;#c;static{createDeferredRawOperation=(e,t,n,r)=>new DeferredRawOperation(It,e,t,n,r),Lt=Object.freeze({clientId:e=>e.#e.clientId,scopeId:e=>e.#e.scopeId,model:()=>`$raw`,operation:e=>e.#r,context:e=>e.#n,requiresInterception:e=>e.#o!==void 0&&e.#o.length>0,prepareAdmission:e=>{e.#l()},stagePackageWriteOutcomes:()=>void 0,startInterception:(e,t,n,r)=>{let i=e.#o;if(i===void 0||i.length===0)return t();let a=e.#l();return lt(e.#d(`array`,a),i,t,isRawWrite(e.#r),n,r)},executeCore:(e,t,n)=>e.#t.executeReserved(()=>e.#m(t,e.#l(),n)),isWrite:e=>isRawWrite(e.#r),hasObservation:e=>(e.#e.extensionChain?.observe.length??0)>0,observe:(e,t,n)=>{let r=e.#e.extensionChain?.observe;return r===void 0||r.length===0?t():at(r,e.#r,void 0,t,n,e.#g())},reserveWith:(e,t)=>{e.#t.reserveWith(t)},executeWith:(e,t)=>{let execute=()=>e.#m(t,e.#l()),n=e.#e.extensionChain?.observe;return n===void 0||n.length===0?e.#t.executeWith(t,execute):e.#t.executeWith(t,()=>at(n,e.#r,void 0,execute,()=>e.#c===void 0?void 0:{commitCertainty:e.#c},e.#g()))},prepare:(e,t=e.#e.driver)=>{let n=e.#l();if(n.kind===`verbatim`)return m({sql:n.sql,params:[...n.params],context:e.#n});let r=t._prepare(n.query,e.#n);return h(r,{sql:r.sql,params:r.params?[...r.params]:[],context:e.#n})},prepareBatch:async()=>void 0,parseResult:(e,t)=>e.#a(t),observeBatchPhase:(e,t,n)=>dt(e.#n,t,n)}),Dt(DeferredRawOperation.prototype,e=>#e in e,Lt),Object.freeze(DeferredRawOperation.prototype)}constructor(e,t,n,r,i){if(e!==It)throw new R;this.#e=t,this.#r=n,this.#i=r,this.#a=i,this.#o=x(t.extensionChain,`query`,void 0,n),this.#t=new ut(`$raw`,n),this.#n=W(`$raw`,n,t.extensionChain),Object.freeze(this)}#l(){if(this.#s)return this.#s;let e=this.#u();return validateRawParametersBeforeInterception(this.#r,e.kind===`fragment`?e.query.values:e.params),this.#s=e,e}#u(){let e=this.#r,{query:t,values:n}=this.#i;if(this.#i.family===`unsafe`){if(typeof t==`string`)return{kind:`verbatim`,sql:t,params:[...n]}}else if(isTemplateStringsArray(t))return{kind:`fragment`,query:new H(t,n)};else if(Ue(t)){if(n.length>0)throw rawInputError(e,`received an Sql fragment together with extra values. The fragment already carries its parameters — interpolate them into it instead.`);return{kind:`fragment`,query:createOperationSql(t)}}throw rawInputError(e,`expects a tagged template (${e}\`SELECT ...\`) or an Sql fragment built with sql\`...\`. Received a value that is neither.`)}#d(e,t){return Object.freeze({mode:e,kind:this.#r.slice(1),model:void 0,operation:this.#r,input:pt(t.kind===`fragment`?{query:t.query}:{sql:t.sql,params:[...t.params]})})}#f(e){return Ct(this.#n,()=>this.#p(e))}#p(e){let t=this.#o;if(t===void 0||t.length===0)return this.#m(e,this.#l(),this.#_());let n;try{n=this.#l()}catch(e){return Promise.reject(e)}return lt(this.#d(this.#e.transactionWriteOutcomes?`transaction`:`direct`,n),t,t=>this.#m(e,n,this.#_(t)),isRawWrite(this.#r),this.#e.transactionWriteOutcomes)}async#m(e,t,n){let r=isRawWrite(this.#r)?n:void 0,i;try{i=t.kind===`fragment`?await e._execute(t.query,this.#n):await e._executeRaw(t.sql,[...t.params],this.#n)}catch(e){try{await r?.mayHaveCommitted()}catch(t){throw I(e,t)}throw e}let a;try{a={status:`success`,value:this.#a(i)}}catch(e){a={status:`failure`,error:e}}try{await r?.committed()}catch(e){throw a.status===`failure`?I(a.error,e):e}if(a.status===`failure`)throw a.error;return a.value}#h(){return this.#t.executeDefault(()=>{let e=this.#e.extensionChain?.observe;return e===void 0||e.length===0?this.#f(this.#e.driver):at(e,this.#r,void 0,()=>this.#f(this.#e.driver),()=>this.#c===void 0?void 0:{commitCertainty:this.#c},this.#g())})}#g(){return wt(this.#e.driver,this.#n,this.#r)}#_(e){if(this.#e.transactionWriteOutcomes!==void 0||(this.#e.extensionChain?.observe.length??0)===0)return e;let publish=async(e,t)=>{let n=!1,r;try{await t?.()}catch(e){n=!0,r=e}if((e===`committed`||this.#c===void 0)&&(this.#c=e),n)throw r};return Object.freeze({committed:()=>publish(`committed`,e?.committed),mayHaveCommitted:()=>publish(`may-have-committed`,e?.mayHaveCommitted)})}then(e,t){return this.#h().then(e,t)}catch(e){return this.#h().catch(e)}finally(e){return this.#h().finally(e)}});function createRawSurface(e){let{engine:t}=e,method=e=>({[e]:(n,...r)=>createDeferredRawOperation(t,e,{family:e.endsWith(`Unsafe`)?`unsafe`:`safe`,query:n,values:captureValues(r)},isRawWrite(e)?e=>e.rowCount:e=>e.rows)})[e];return{$executeRaw:method(`$executeRaw`),$executeRawUnsafe:method(`$executeRawUnsafe`),$queryRaw:method(`$queryRaw`),$queryRawUnsafe:method(`$queryRawUnsafe`)}}const Rt=Object.freeze(Object.create(null)),zt=Object.freeze({client:()=>Rt,model:()=>Rt}),Bt=new Set([`$driver`,`$schema`,`$transaction`,`$connect`,`$disconnect`,`$withCache`,`$invalidate`,`$extends`]);function readMethodRecord(e,r,i){n(e)||w(`Extension "${i}" ${r} factory must return an object.`,i);let a=Object.create(null),o;try{o=Reflect.ownKeys(e)}catch(e){throw new P(`Extension "${i}" ${r} methods could not be inspected.`,{cause:E(e),meta:{extension:i}})}for(let n of o){typeof n!=`string`&&w(`Extension "${i}" ${r} returned a non-string method key.`,i);let o;try{o=e[n]}catch(e){throw new P(`Extension "${i}" ${r} method "${n}" could not be read.`,{cause:E(e),meta:{extension:i}})}t(o)||w(`Extension "${i}" ${r} method "${n}" must be a function.`,i),a[n]=bindExtensionMethod(o)}return a}function invokeFactory(e,t,n,r){try{return Reflect.apply(e,void 0,[t])}catch(e){throw new P(`Extension "${r}" ${n} factory failed.`,{cause:E(e),meta:{extension:r}})}}function bindExtensionMethod(e){return(...t)=>Reflect.apply(e,void 0,t)}function addMethods(e,t,n){let r=Object.create(null);Object.assign(r,e);for(let[e,i]of Object.entries(t))n(e,Object.hasOwn(r,e)),r[e]=i;return Object.freeze(r)}function bindExtensionMethods(e,t){let n=[zt];for(let{name:r,client:a,model:o}of e.extensions){let e=n.at(-1),s,scopeOf=()=>s??=t(e,r),c,l=new Map;n.push({client:()=>c??=a===void 0?e.client():addMethods(e.client(),readMethodRecord(invokeFactory(a,scopeOf(),`client`,r),`client`,r),(e,t)=>{e.startsWith(`$`)||w(`Extension "${r}" client method "${e}" must be dollar-prefixed.`,r),(t||Bt.has(e)||Object.hasOwn(Ft,e))&&w(`Extension "${r}" client method "${e}" collides with the existing client surface.`,r)}),model:t=>{let n=l.get(t);if(n===void 0){let a=o?.[t],s=`model.${t}`;n=a===void 0?e.model(t):addMethods(e.model(t),readMethodRecord(invokeFactory(a,Reflect.get(scopeOf(),t),s,r),s,r),(e,n)=>{(n||e===`then`||i.has(e))&&w(`Extension "${r}" model method "${t}.${e}" collides with the existing model surface.`,r)}),l.set(t,n)}return n}})}let r=n.at(-1);return{client:r.client,model:r.model,force:()=>{for(let[t,{model:r}]of e.extensions.entries()){let e=n[t+1];e.client();for(let t of Object.keys(r??{}))e.model(t)}}}}const resultShapeKeys=(...e)=>Object.freeze(e),Vt=Object.freeze({findFirst:resultShapeKeys(`select`,`include`,`omit`),findMany:resultShapeKeys(`select`,`include`,`omit`),findUnique:resultShapeKeys(`select`,`include`,`omit`),findUniqueOrThrow:resultShapeKeys(`select`,`include`,`omit`),findFirstOrThrow:resultShapeKeys(`select`,`include`,`omit`),create:resultShapeKeys(`select`,`include`,`omit`),update:resultShapeKeys(`select`,`include`,`omit`),delete:resultShapeKeys(`select`,`include`,`omit`),upsert:resultShapeKeys(`select`,`include`,`omit`),createMany:resultShapeKeys(`select`,`omit`),updateMany:resultShapeKeys(`select`,`omit`),deleteMany:resultShapeKeys(`select`,`omit`),count:resultShapeKeys(`select`),aggregate:resultShapeKeys(`_count`,`_avg`,`_sum`,`_min`,`_max`),groupBy:resultShapeKeys(`by`,`_count`,`_avg`,`_sum`,`_min`,`_max`),exist:resultShapeKeys()}),Ht=Object.freeze({});function hasRequestTransforms(e){return e!==void 0&&e.length>0}function applyRequestTransforms(e,t,n,r,i){if(!hasRequestTransforms(r))return n;let a=r[0],o=readOwnDescriptors(n??Ht,a,e,t),s=materializeHandlerInput(o,t);for(let[n,a]of r.entries())mergePatch(o,invokeTransform(a,Object.freeze(a.controls===void 0?{model:e,operation:t,input:s}:{model:e,operation:t,input:s,controls:u(i?.admitted,a.controls)}),e,t),a.extension,e,t,i?.names)&&n+1<r.length&&(s=materializeHandlerInput(o,t));return materializeResult(o)}function invokeTransform(e,t,n,r){try{return Reflect.apply(e.handler,void 0,[t])}catch(t){throw transformFailure(e.extension,n,r,`threw`,normalizeThrown(t))}}function mergePatch(e,t,r,i,a,o){let s;try{s=isPromiseLike(t)}catch(e){throw transformFailure(r,i,a,`returned an unreadable patch`,normalizeThrown(e))}if(s)throw transformFailure(r,i,a,`returned a promise`,TypeError(`Request transforms must return synchronously`));if(!n(t))throw transformFailure(r,i,a,`returned a non-record patch`,TypeError(`Request transforms must return an object`));let c;try{c=Reflect.ownKeys(t)}catch(e){throw transformFailure(r,i,a,`returned an unreadable patch`,normalizeThrown(e))}for(let e of c)if(typeof e==`string`&&o?.has(e))throw transformFailure(r,i,a,`named control "${e}"`,TypeError(`Request patches cannot set extension controls`));try{let n=!1;for(let r of c){if(isResultShapeKey(a,r))continue;let i=Object.getOwnPropertyDescriptor(t,r);if(!i)continue;let o=e.findIndex(e=>e.key===r);o===-1?e.push({key:r,descriptor:i}):e[o]={key:r,descriptor:i},n=!0}return n}catch(e){throw transformFailure(r,i,a,`returned an unreadable patch`,normalizeThrown(e))}}function readOwnDescriptors(e,t,n,r){try{let t=[];for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);r!==void 0&&t.push({key:n,descriptor:r})}return t}catch(e){throw transformFailure(t.extension,n,r,`could not inspect request input`,normalizeThrown(e))}}function materializeHandlerInput(e,t){let n=materializeDescriptors(e,t);return n===void 0?Ht:Object.freeze(n)}function materializeResult(e){return materializeDescriptors(e)??{}}function materializeDescriptors(e,t){let n;for(let{key:r,descriptor:i}of e)t!==void 0&&isResultShapeKey(t,r)||(n??={},Object.defineProperty(n,r,i));return n}function isResultShapeKey(e,t){return typeof t==`string`?Vt[e].includes(t):!1}function isPromiseLike(e){return n(e)&&`then`in e&&t(e.then)}function normalizeThrown(e){return ne(e)?e:Error(`Request transform threw a non-Error value`)}function transformFailure(e,t,n,r,i){return new de(`Extension "${e}" request handler for ${t}.${n} ${r}.`,{cause:i,meta:{model:t,operation:n}})}var Ut=class QueryEngine{driver;extensionChain;transactionWriteOutcomes;bound;clientId;scopeId;route;constructor(e,t,n=Symbol(`viborm.client`),r=Symbol(`viborm.scope`),i,a,o){this.driver=e,this.route=t,this.extensionChain=i,this.transactionWriteOutcomes=a,this.clientId=n,this.scopeId=r,this.bound=o}withBound(e){return new QueryEngine(this.driver,this.route,this.clientId,this.scopeId,this.extensionChain,this.transactionWriteOutcomes,e)}bind(e,t=this.extensionChain,n=this.transactionWriteOutcomes){return new QueryEngine(e,this.route,this.clientId,Symbol(`viborm.scope`),t,n,this.bound)}prepare(e,t,n,r,i,a){return vt(this,e,t,n,r,i,a)}};const Wt=new WeakMap;function registerPositionalResultDriver(e,t,n){Wt.set(e,{execute:t,isEligible:n})}function resolvePositionalResultDriver(e){let t=Wt.get(e);return t?.isEligible(e)?t.execute:void 0}function assertPositionalRows(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];if(!(Object.hasOwn(e,r)&&Array.isArray(i))||i.length!==t.length)throw new de(`Driver "${n.provider}" returned malformed positional rows for operation "${n.operation}".`,{meta:p(n)})}}function borrowPositionalResult(e){let t=e.rows.map(t=>Object.fromEntries(e.columns.map((e,n)=>[e,t[n]])));return{rows:t,rowCount:t.length}}function createFailureError(e,t,n){if(e.kind===`foreignKey`)return new se(e.message,{meta:{model:t,operation:n}});if(e.kind===`nestedWrite`){let t=new M(e.message,e.relation??``);return e.raceable&&(t.meta.raceable=!0),t}if(e.kind===`notFound`)return new F(t,n);if(e.kind===`forbidden`)return new ue(t,n);let r=new L(e.message,{meta:{model:t,operation:n}});return e.raceable&&(r.meta.raceable=!0),r}async function attributeOperationBatchError(e,t,n,r=[]){if(!(e instanceof A))return e;let i=e.meta.statementIndex;if(typeof i==`number`){let n=t.find(e=>e.queryIndex===i);return n?createFailureError(n.failure,n.model,n.operation):e}if(t.length>0&&oe(r,n.dialect,new Set(t.map(e=>e.queryIndex))))return e;for(let e of t){let t=(await n._execute(e.probe,r[e.queryIndex]?.context)).rows.length>0;if(e.premise===`exists`?!t:t)return createFailureError(e.failure,e.model,e.operation)}let[a]=t;return a?t.every(e=>sameAttribution(e,a))?createFailureError(a.failure,a.model,a.operation):e:new M(fe,``,{code:O.NESTED_WRITE_ASSERTION_FAILED,cause:e})}function sameAttribution(e,t){return e.model===t.model&&e.operation===t.operation&&e.failure.kind===t.failure.kind&&e.failure.message===t.failure.message&&e.failure.relation===t.failure.relation&&e.failure.raceable===t.failure.raceable}function compileBindBudgetChunks(e,t,n){if(e===0)return[];let r=n(0,e);if(t===void 0||r.values.length<=t||e===1)return[{start:0,end:e,statement:r}];let i=[],a=0;for(;a<e;){let r=a+1,o=Math.min(e,a+1),s;for(;;){let i=n(a,o);if(i.values.length>t||(s={start:a,end:o,statement:i},o===e))break;r=o+1,o=Math.min(e,a+(o-a)*2)}if(s?.end!==e)for(--o;r<=o;){let e=r+Math.floor((o-r)/2),i=n(a,e);i.values.length<=t?(s={start:a,end:e,statement:i},r=e+1):o=e-1}let c=s??{start:a,end:a+1,statement:n(a,a+1)};i.push(c),a=c.end}return i}var Gt=class SqlSlot extends H{constructor(e){super([``,``],[e])}settle(e){SqlSlot.fill(this,e)}};function exactDecimalDomain(e){return e.type===`decimal`&&e.array!==!0?e.decimal:void 0}function requireDecimal(e,t){if(!e.decimal)throw new j(`Decimal field '${t}' has no declared precision and scale, so it has no exact value to bind.`);return e.decimal}function canonicalDecimal(e,t){let n=Le(e);if(n===void 0)throw new j(`Decimal field '${t}' received a value that is not an exact decimal.`);return n}function decimalMembers(e,t,n,r){let i=Ce(t,requireDecimal(e,n),r.decimalListRepresentation??`text`);if(i===void 0)throw new j(`Decimal list '${n}' received a member that is not an exact decimal.`);return i}function dividesByZero(e){return Le(e)===`0`}function sameDecimalDomain(e,t){return we(e,t)}function decimalSumOperand(e,t){let n=Le(e);if(n!==void 0)return{canonical:n,coefficient:De(n,t.scale)}}function decodeDecimalScalar(e,t,n,r,i){let a=i.decimalRepresentation??`text`;return n?r?ke(e,t,a):xe(e,t,a):r?Me(e,t,a):Ie(e,t,a)}function decodeDecimalList(e,t,n,r){let i=Ve(e,t,r.decimalListRepresentation??`text`);if(i!==void 0)return n?i:i.map(e=>Ee(e))}function identifierColumn(e,t,n,r,i){let a=n[`~`].state.scalars[r]===void 0?i.reference:{model:n,field:r};if(a===void 0)return;let o=Xe(a.model,a.field,t);if(o!==void 0)return{domain:o,representation:e.result.idRepresentation?.(o,a.model[`~`].state.scalars[a.field]?.[`~`].nativeType)??`text`}}function isCompact(e){return e!==void 0&&e.representation!==`text`}function encodeIdentifier(e,t){return Re(t,e.domain,e.representation)}function decodeIdentifier(e,t){return Fe(t,e.domain,e.representation)}function transportedIdentifier(e,t,n,r){if(t?.representation!==`bytes`)return n;let i=e.expressions.blobToHex(n);return r?e.expressions.caseWhen([{when:e.operators.isNull(n),then:e.literals.null()}],i):i}function aggregatedIdentifier(e,t,n){return t?.representation===`uuid`?e.expressions.cast(n,`text`):transportedIdentifier(e,t,n,!0)}function describeStorage(e){if(e===void 0)return`plain string text`;let t=e.representation===`text`?`as its own text`:e.representation===`uuid`?`as a uuid payload`:`as payload bytes`;return`${je(e.domain)}, stored ${t}`}function incomparableIdentifiers(e,t,n,r){let i=e?.representation??`text`;if(!(i===(t?.representation??`text`)&&(i===`text`||Be(e?.domain,t?.domain))))return`'${n}' is ${describeStorage(e)} and '${r}' is ${describeStorage(t)}. Two columns compare only when one value has the same physical spelling in both.`}function anyValue(){return Ae(`anyValue`,e=>be(e))}function rawRecord(){return Ae(`rawRecord`,e=>n(e)?be(e):Oe(`Expected object, received ${Array.isArray(e)?`array`:typeof e}`))}function parseValidated(e,t,n,r,i){let a=Mt(e,t);if(a.issues){let e=r?[r]:[];throw new pe(n,a.issues.map(t=>({path:[...e,...t.path?.map(String)??[]].join(`.`)||`root`,message:t.message})),{cause:Te(a),meta:{model:i[`~`].names.ts}})}return a.value}const Kt=He({where:rawRecord(),create:rawRecord(),update:rawRecord(),select:anyValue(),include:anyValue(),omit:anyValue(),targetWhere:anyValue(),setWhere:anyValue()},{atLeast:[`where`,`create`,`update`]});function linkJudgement(t){if(t.kind===`reference`&&t.owner===`source`)return;let n=t.scope.edge,r=t.kind===`reference`&&n.kind===`foreignKey`?t.pairs.map(e=>e.target):[],i=e(e=>e.source===t.source&&e.field===t.name,`own`),a=n.kind===`foreignKey`||n.kind===`junction`?n.endpoints.find(e=>!i(e)):i(n.carrier)?t.scope.member?.inverse:n.carrier;return a&&r.push(a.field),{verb:`update`,writes:r}}function bindMembership(e,t,n,r){return e.membership(t,n,r)}function variantMember(e,t){return e??t}function buildMembershipView(e,t,n,r){let i=e.index.get(t).get(n),a=i.edge,o=e.clearability(i),s=t[`~`].state.relations[n][`~`].state.cardinality===`many`;if(a.kind===`variantRowCarrier`){let e=variantMember(i.member,a.members.find(e=>e.variant===r)),c=i.member===void 0;return{scope:Object.freeze({edge:a,member:e}),clearability:o,name:c?`${n}.${e.variant}`:n,source:t,many:s,target:c?e.targetModel:a.carrier.source,kind:`reference`,owner:c?`source`:`target`,pairs:[{source:c?a.storage.idColumn.name:e.referencedField,target:c?e.referencedField:a.storage.idColumn.name}],discriminator:{side:c?`source`:`target`,field:a.storage.typeColumn.name,value:e.entry.storedValue}}}if(a.kind===`variantJunctionCarrier`){let e=variantMember(i.member,a.members.find(e=>e.variant===r)),c=i.member===void 0;return{scope:Object.freeze({edge:a,member:e}),clearability:o,name:c?`${n}.${e.variant}`:n,source:t,many:s,target:c?e.topology.target.model:e.topology.source.model,kind:`junction`,table:e.topology.table,sourceSide:c?e.topology.source:e.topology.target,targetSide:c?e.topology.target:e.topology.source,uniqueSide:e.uniqueTarget?c?`target`:`source`:void 0}}let c=a.endpoints[0],l=c.source===t&&c.field===n?a.endpoints[1]:c,u={scope:i,clearability:o,name:n,source:t,target:l.source,many:s};if(a.kind===`foreignKey`){let e=a.owner.source===t&&a.owner.field===n;return{...u,kind:`reference`,owner:e?`source`:`target`,reference:a.reference,pairs:a.reference.members.map(t=>({source:e?t.foreignField:t.referencedField,target:e?t.referencedField:t.foreignField}))}}let d=a.topology,f=l===a.endpoints[1];return{...u,kind:`junction`,table:d.table,sourceSide:f?d.source:d.target,targetSide:f?d.target:d.source}}function freezeMembershipView(e){if(e.kind===`reference`){for(let t of e.pairs)Object.freeze(t);Object.freeze(e.pairs),e.discriminator&&Object.freeze(e.discriminator)}return Object.freeze(e)}function physicalField(e,t,n){return e.physicalField(t,n)}function carrierColumns(e,t){let n=[];for(let{edge:r,member:i}of e.index.get(t).values())r.kind===`variantRowCarrier`&&!i&&n.push(r.storage.typeColumn,r.storage.idColumn);return n}function buildPhysicalFieldView(e,t,n){let r=t[`~`].state.scalars[n];return r?{name:t[`~`].getFieldName(n).sql,scalar:r,nullable:r[`~`].state.nullable===!0}:carrierColumns(e,t).find(e=>e.name===n)}function storedFields(e,t){return e.storedFields(t)}function buildStoredFieldsView(e,t){return[...t[`~`].scalarFieldNames,...carrierColumns(e,t).map(e=>e.name)]}const qt=new Set([`findMany`,`findUnique`,`findFirst`,`count`,`exist`,`aggregate`,`groupBy`]);function isReadOperation(e){return qt.has(e)}const Jt=[`multiply`,`divide`],Yt=[`set`,`increment`,`decrement`,`multiply`,`divide`];function record(e){return e}function entries(e){return Array.isArray(e)?e:[record(e)]}function memo(e,t,n){let r=e.get(t);return r===void 0&&(r=n(),e.set(t,r)),r}const createQueryViews=()=>({leaves:new WeakMap,defaultProjections:new WeakMap});var EngineSchema=class{index;registry;#e=new WeakMap;#t=new WeakMap;#n=new WeakMap;#r=new WeakMap;#i=new WeakMap;schema;constructor(e,t){if(this.schema=e,t){this.index=t.index,this.registry=t.registry;return}We(e),this.index=Ke(e),this.registry=nt(e,this.index)}admit(e,t,n){let r=t===`upsert`?this.#o(e,n):this.#a(e,t,n);if(t===`update`||t===`updateMany`){let t=this.keyPortabilityRefusal(e,r.data);if(t)throw t}return r}#a(e,t,r){let i=this.registry.getModelSchemas(e).args[t];return parseValidated(i,t===`update`&&n(r)&&n(r.data)?{...r,data:Object.fromEntries(Object.entries(r.data).sort(([t],[n])=>{let isVariant=t=>e[`~`].state.relations[t]?.[`~`].state.target.kind===`variants`;return Number(isVariant(t))-Number(isVariant(n))}))}:r,t,``,e)}namesRelation(e,t){return e[`~`].relationNames.some(e=>t[e]!==void 0)}keyPortabilityRefusal(e,t){if(n(t))for(let r of this.keys(e)){let i=t[r];if(!n(i))continue;let a=Yt.filter(e=>i[e]!==void 0);if(a.length!==1)return new N(`Primary key field '${r}' accepts exactly one update operation; received ${a.join(`, `)||`none`}.`);let o=a[0];if(o===`set`)continue;let s=e[`~`].state.scalars[r]?.[`~`].state.type;if(s===`number`||s===`decimal`&&Jt.includes(o))return new N(`Arithmetic updates are not portable for ${s} primary key field '${r}'. Use an explicit set value.`);if(i.divide===0||i.divide===0n)return new N(`Cannot divide primary key field '${r}' by zero.`)}}keyTransitionRefusal(e,t,r,i){if(n(t))for(let a of this.keys(e)){if(!r.has(a))continue;let o=t[a];if(n(o)&&i.some(e=>e.pairs.length===1&&e.pairs[0].source===a)){if(Yt.filter(e=>o[e]!==void 0).length!==1)return new N(`Cannot determine the updated primary key for model '${e[`~`].names.ts}' because field '${a}' uses an unsupported operation.`);if(o.divide===0||o.divide===0n)return new N(`Cannot divide a primary key by zero.`)}}}#o(e,t){let r=parseValidated(Kt,t,`upsert`,``,e),i=this.registry.getModelSchemas(e),a=this.namesRelation(e,r.create),o=Object.fromEntries(Object.entries(r.update).filter(([t])=>!e[`~`].relationNames.includes(t))),s=parseValidated(i.core.whereUniqueExtended,r.where,`upsert`,`where`,e),c=a?void 0:parseValidated(i.core.scalarCreate,r.create,`upsert`,`create`,e),l=parseValidated(i.core.scalarUpdate,o,`upsert`,`update`,e),u=parseValidated(i.core.upsertProjection,{select:r.select,include:r.include,omit:r.omit},`upsert`,``,e),d={targetWhere:void 0,setWhere:void 0};for(let t of[`targetWhere`,`setWhere`]){let a=r[t];if(a===void 0)continue;let o=parseValidated(i.core.where,a,`upsert`,t,e);n(o)&&Object.keys(o).length&&(d[t]=record(o))}let f=a?parseValidated(i.core.create,r.create,`create`,`data`,e):c,p=this.update(e,r.update,!1,record(l));return record({...r,...record(u),...d,where:s,create:f,update:p})}createValues(e,t){let n=this.registry.getModelSchemas(e).scalars,r={};for(let[i,a]of Object.entries(t))r[i]=parseValidated(n[i].create,a,`create`,i,e);return r}update(e,t,n,r){let i=this.registry.getModelSchemas(e);if(n)return record(parseValidated(i.core.update,t,`updateMany`,`data`,e));let a={...r??t},o=Object.keys(t).filter(t=>e[`~`].relationNames.includes(t)),isVariant=t=>e[`~`].state.relations[t][`~`].state.target.kind===`variants`;for(let n of o.sort((e,t)=>Number(isVariant(e))-Number(isVariant(t))))t[n]!==void 0&&(a[n]=parseValidated((isVariant(n)?i.polymorphic[n]:i.relations[n]).update,t[n],`update`,`data.${n}`,e));return a}member(e,t,n){let r=this.registry.getModelSchemas(e).relations[t].update;return record(entries(record(parseValidated(r,{updateMany:{data:n}},`update`,`data.${t}`,e)).updateMany)[0].data)}keys(e){return U(e).rowKey.fields}identity(e,t){return Object.fromEntries(this.keys(e).map(e=>[e,t[e]]))}membership(e,t,n){return memo(memo(memo(this.#e,e,()=>new Map),t,()=>new Map),n,()=>freezeMembershipView(buildMembershipView(this,e,t,n)))}restrictingSlots(e){return memo(this.#i,e,()=>{let t=[];for(let[n,r]of this.index.get(e)??[]){let i=r.edge;if(i.kind!==`foreignKey`&&i.kind!==`junction`)continue;let a=this.membership(e,n),o=a.kind===`junction`?Ge(a.sourceSide):i.kind===`foreignKey`&&a.owner===`target`?Je(i):void 0;(o===`restrict`||o===`noAction`)&&t.push(n)}return Object.freeze(t)})}clearability(e){return memo(this.#r,e,()=>{let t=Ze(e);return t.kind===`columns`&&Object.freeze(t.fields),Object.freeze(t)})}physicalField(e,t){let n=this.#t.get(e);n||(n=new Map,this.#t.set(e,n));let r=n.get(t);return r||(r=Object.freeze(buildPhysicalFieldView(this,e,t)),n.set(t,r)),r}#s=new WeakMap;queryViews(e){return memo(this.#s,e,createQueryViews)}storedFields(e){return memo(this.#n,e,()=>Object.freeze(buildStoredFieldsView(this,e)))}scalars(e,t){let n={};for(let r of e[`~`].scalarFieldNames){let e=t[r];e!==void 0&&(n[r]=e)}return n}};const J=Object.freeze;function returningSafeProjection(e){return e.fields.every(e=>e.kind===`scalar`||e.kind===`sentinel`)}function rowValue(e){return e.length===1?e[0]:V`(${V.join(e,`, `)})`}function newSelectorFacts(e=!0){return{fields:new Set,equals:new Map,keys:new Map,exact:e,reads:[]}}function states(e){return e.kind===`layer`?states(e.predicate):e.kind!==`and`||e.predicates.some(states)}const Y=J({kind:`always`,value:!0});function foldConditions(e,t){switch(e.kind){case`condition`:return t(e.condition)?Y:X;case`and`:case`or`:{let n=e.kind===`and`,r=[];for(let i of e.predicates){let e=foldConditions(i,t);if(e.kind!==`always`)r.push(e);else if(e.value!==n)return e}return r.length===0?n?Y:X:r.length===e.predicates.length&&r.every((t,n)=>t===e.predicates[n])?e:J({kind:e.kind,predicates:J(r)})}case`not`:{let n=foldConditions(e.predicate,t);return n.kind===`always`?n.value?X:Y:n===e.predicate?e:J({kind:`not`,predicate:n})}case`relation`:{if(!e.predicate)return e;let n=foldConditions(e.predicate,t);return n===e.predicate?e:J({...e,predicate:n})}default:return e}}function foldKnownNulls(e,t){switch(e.kind){case`operation`:{let{target:n,operand:r}=e;if(e.operator!==`equals`||n.kind!==`column`||n.path!==void 0||r?.kind!==`value`||r.value!==null||n.scalar.physical.scalar[`~`].state.type===`json`)return e;let i=t.get(n.scalar.field);return i===void 0?e:i?Y:X}case`and`:case`or`:{let n=e.kind===`and`,r=[];for(let i of e.predicates){let e=foldKnownNulls(i,t);if(e.kind!==`always`)r.push(e);else if(e.value!==n)return e}return r.length===0?n?Y:X:r.length===e.predicates.length&&r.every((t,n)=>t===e.predicates[n])?e:J({kind:e.kind,predicates:J(r)})}case`not`:{let n=foldKnownNulls(e.predicate,t);return n.kind===`always`?n.value?X:Y:n===e.predicate?e:J({kind:`not`,predicate:n})}default:return e}}function readsAny(e,t,n){switch(e.kind){case`and`:case`or`:return e.predicates.some(e=>readsAny(e,t,n));case`not`:case`layer`:return readsAny(e.predicate,t,n);case`always`:case`condition`:return!1;case`operation`:{if(e.target.kind!==`column`)return!0;let n=[e.operand,...e.operands??[]];return t.has(e.target.scalar.field)||n.some(e=>e?.kind===`field`&&t.has(e.scalar.field)||e?.kind===`sql`&&e.operands.some(e=>e.kind===`field`&&t.has(e.scalar.field)))}case`relation`:{let{edge:r}=e;return(r.kind===`reference`?[...r.pairs.map(e=>e.source),...r.discriminator?.side===`source`?[r.discriminator.field]:[]]:n).some(e=>t.has(e))}default:return!0}}function callReads(e,t,n){switch(e.kind){case`condition`:n.add(e.condition);return;case`and`:case`or`:for(let r of e.predicates)callReads(r,t,n);return;case`not`:callReads(e.predicate,t,n);return;case`relation`:e.predicate&&callReads(e.predicate,t,n);return;case`operation`:for(let n of[e.operand,...e.operands??[]])n?.kind===`parameter`&&t.set(n.parameter,n.spread===!0);e.value instanceof S&&!t.has(e.value)&&t.set(e.value,!1);return;default:return}}function sameColumnIn(e){let t=[],n;for(let r of e){for(;r.kind===`and`&&r.predicates.length===1;)r=r.predicates[0];let e=r.kind===`operation`?r.operand:void 0;if(r.kind!==`operation`||r.operator!==`equals`||r.insensitive||r.target.kind!==`column`||r.target.path||e?.kind!==`value`||e.value===null||e.value instanceof H||n&&(r.target.scalar.model!==n.scalar.model||r.target.scalar.field!==n.scalar.field||r.target.key!==n.key))return;n??=r.target,t.push(e)}let r=n?.scalar.physical.scalar[`~`].state;if(!(!n||r?.array===!0||r?.type===`json`||r?.type===`point`||r?.type===`vector`))return J({kind:`operation`,operator:`in`,target:n,operands:J(t),insensitive:!1})}function readsRelation(e){switch(e.kind){case`relation`:return!0;case`and`:case`or`:return e.predicates.some(readsRelation);case`not`:case`layer`:return readsRelation(e.predicate);default:return!1}}function distanceUpperBound(e){if(typeof e!=`object`||!e)return;let{lt:t,lte:n}=e,r=[t,n].filter(e=>typeof e==`number`&&e>0);return r.length===0?void 0:Math.min(...r)}function orphanedArm(e,t){if(t.kind!==`object`||e==null)return!1;let n=providerJson(e);return typeof n!=`object`||!n?!1:Object.keys(n).length===0&&Object.keys(t.fields).length>0}function providerJson(e){return typeof e==`string`?JSON.parse(e):e}function providerDocument(e){return e===null?null:typeof e==`object`&&!Array.isArray(e)?record(e):void 0}function own(e,t){return Object.hasOwn(e,t)?e[t]:void 0}const Xt=`Cursor pagination supports direct scalar sort directions only; relation and vector-distance orderBy are not supported.`,X=J({kind:`always`,value:!1});var InvalidScalarResult=class extends TypeError{scalarType;reason;constructor(e,t){super(`Invalid provider ${e===`int`?`integer`:e}`),this.scalarType=e,this.reason=t}},RecursiveOutputOverBudget=class extends RangeError{relation;limit;constructor(e,t){super(`Recursive relation '${e}' exceeds ${t} occurrences`),this.relation=e,this.limit=t}refusal(e,t){return new N(`'${e}' would return more than ${this.limit} occurrences of recursive relation '${this.relation}' under one row, its output budget; raise recurse.maxOccurrences, lower recurse.depth or filter the relation.`,{meta:{model:t,operation:e,relation:this.relation,feature:`recursive output budget`}})}},GatedFieldRefusal=class extends Error{path;constructor(e){super(`The selected field at '${e}' is not readable on a returned row`),this.path=e}refusal(e,t){return new pe(e,[{path:this.path,message:`is not readable on a returned row`}],{meta:{model:t}})}};const Zt=`_distance`,Z=J({root:`__rq_root`,nodes:`__rq_nodes`,edges:`__rq_edges`,key:`__rq_key`,row:`__rq_row`,parent:`__rq_parent`,child:`__rq_child`,depth:`__rq_depth`}),Qt=[`_count`,`_avg`,`_sum`,`_min`,`_max`],$t=new Set(Qt);function isAggregate(e){return $t.has(e)}const Q=J({kind:`scalar`,type:`boolean`,nullable:!1}),$=J({kind:`scalar`,type:`int`,nullable:!1}),en=new Set([`is`,`isNot`,`some`,`every`,`none`]),tn=new Set([`equals`,`not`,`in`,`notIn`,`lt`,`lte`,`gt`,`gte`,`contains`,`startsWith`,`endsWith`,`mode`,`has`,`hasEvery`,`hasSome`,`isEmpty`,`path`,`string_contains`,`string_starts_with`,`string_ends_with`,`array_contains`,`array_starts_with`,`array_ends_with`,`within`,`distance`]);function addressesOperators(e,t){return isOperatorRecord(t)?e?.type!==`json`&&e?.type!==`point`?!0:Object.keys(t).some(e=>tn.has(e)):!1}const nn=[`increment`,`decrement`,`multiply`,`divide`],rn=[`push`,`unshift`];function isOperatorRecord(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function wholeValue(e){return e instanceof H||typeof e!=`object`||!e||!isOperatorRecord(e)?{value:e}:Object.hasOwn(e,`set`)?{value:record(e).set}:void 0}function readUpdate(e){let t=wholeValue(e);if(t)return{kind:`value`,value:t.value};let n=record(e);for(let e of nn)if(Object.hasOwn(n,e))return{kind:`arithmetic`,operator:e,by:n[e]};for(let e of rn)if(Object.hasOwn(n,e)){let t=n[e];return{kind:`list`,operator:e,members:Array.isArray(t)?t:[t]}}throw new j(`Unknown update operation: ${Object.keys(n).join(`, `)}`)}function admittedTemporal(e,t){if(!(e instanceof Date))return e;let n=t(e);return`value`in n?n.value:e}function defaultSelection(e){let t={};for(let n of tt(e))t[n]=!0;return t}function rowSet(e){return{kind:`collection`,row:e.shape}}function firstRow(e){return e[0]??null}function aggregateRow(e){return e[0]??{}}function rowIdentity(e){return e}function reversedRows(e){return e.reverse()}const an=Object.freeze({purpose:`root`}),on=/(?<=["_])q(\d+)(?=["_])/g;var CallerText=class extends H{};const isCallerText=e=>e instanceof CallerText,callerText=e=>new CallerText([`(`,`)`],[e]),sn=new WeakMap;let cn=0;function valueKey(e){return e instanceof Date?`d${e.getTime()}`:Array.isArray(e)?`a${JSON.stringify(e.map(valueKey))}`:e===null||typeof e!=`object`&&typeof e!=`function`?`${typeof e}:${String(e)}`:`o${memo(sn,e,()=>cn++)}`}function sharedKey(e){let{runs:t,values:n}=H.peekRuns(e,isCallerText),r=new Map,i=t.map(({text:e,opaque:t})=>t?[e]:e.replace(on,(e,t)=>{let n=r.get(t);return n===void 0&&(n=r.size,r.set(t,n)),`q${n}`}));return JSON.stringify([i,n.map(valueKey)])}const ln=new WeakMap,un=/(?:^|_)q\d+(?:_|$)/,resemblesAlias=e=>un.test(e);function hasAliasLikeNames(e){return memo(ln,e,()=>{for(let[t,n]of e.index){if(resemblesAlias(t[`~`].names.sql))return!0;for(let n of e.storedFields(t))if(resemblesAlias(physicalField(e,t,n).name))return!0;for(let{edge:e}of n.values()){let t=e.kind===`junction`?[e.topology]:e.kind===`variantJunctionCarrier`?e.members.map(e=>e.topology):[];for(let e of t){if(resemblesAlias(e.table))return!0;for(let t of[e.source,e.target])if(t.members.some(e=>resemblesAlias(e.junctionField)))return!0}}}return!1})}const dn=Object.freeze([]),fn=Object.freeze([]),isParameterOperand=e=>e.kind===`parameter`,pn=new WeakMap;function sharedGate(e,t){return t.find(t=>t.length===e.length&&t.every(([t,,n],r)=>t===e[r][0]&&n===e[r][2]))||(t.push(e),e)}var PreparedDomain=class{rows;defaults;#e;#t={root:new Map,related:new Map};#n=new Map;#r=new Map;#i=new Map;projects;defaultProjections=new WeakMap;#a;constructor(e,t,n){this.rows=e,this.#e=t,this.defaults=n??this,this.projects=[...e.verbs?.values()??[]].some(e=>e.some(e=>e?.evidence||e?.reads.size))}layered(e,t,n){let r=e[`~`].names.ts;return memo(memo(this.#r,`${r} ${t}`,()=>new Map),n,()=>{let i=this.#e.prepareSelector(e,n);return i.predicate===void 0?i:J({...i,predicate:layerOf(t,r,i.predicate)})})}projected(e){return this.projects?this.#o(e):void 0}#o(e){let t=e[`~`].names.ts;return memo(this.#i,t,()=>{let e=new Map,n=new Map;for(let[r,i]of(this.rows.verbs?.get(t)??[]).entries()){if(i===void 0)continue;let{evidence:t,read:a}=i;t&&e.set(t.as,J({layer:r,read:a,names:t.names,ordered:t.ordered}));for(let[e,t]of i.reads)n.set(e,[...n.get(e)??[],J([r,a,t])])}let r=[];for(let[e,t]of n)n.set(e,sharedGate(J(t),r));return e.size===0&&n.size===0?null:J({keys:e,gates:n})})??void 0}reads(e){return e.rows.values===void 0?this.#a??=this.#e.under(this):this.#e.under(this,e)}selector(e,t,n=dn,r){let i=e[`~`].names.ts,a=this.rows.verbs?.get(i)&&r,o=a?`${i} ${n} ${a.verb}${a.marks?`+`:``} ${[...a.writes].sort()}`:n.length===0?i:`${i} ${n}`,s=this.#t[t].get(o);return s===void 0&&(s=this.#s(e,t,n,a,o)),s??void 0}#s(e,t,n,r,i){let a=e[`~`].names.ts,o=this.rows[t].get(a),s=this.rows.verbs?.get(a),c=this.#e;return memo(this.#t[t],i,()=>{if(o===void 0&&s===void 0)return null;let t=[],i=Math.max(o?.length??0,s?.length??0);for(let l=0;l<i;l++){if(n.includes(l))continue;let i=s?.[l],u=[...i?[i.read]:[],...o?.[l]===void 0?[]:[o[l]],...i&&r?verbInputs(i,r):[]].map(t=>memo(this.#n,t,()=>c.prepareSelector(e,t)));if(u.length===0)continue;let d=u.length===1?u[0]:c.andSelectors(e,u);t.push(d.predicate===void 0?d:J({...d,predicate:layerOf(l,a,d.predicate)}))}return t.length===0?null:t.length===1?t[0]:c.andSelectors(e,t)})}#c=new Map;produced(e,t,n){if(t?.verb===`delete`)return;let r=e[`~`].names.ts,i=this.rows.verbs?.get(r);if(i===void 0)return;let a=this.#e,o=n&&new Set(n),s=a.schema.keys(e),prepare=t=>memo(this.#n,t,()=>a.prepareSelector(e,t));return memo(this.#c,t?`update ${r} ${[...t.writes].sort()} ${n?[...n].sort():`*`}`:`create ${r}`,()=>{let n=[];for(let[c,l]of i.entries()){if(l===void 0)continue;let i=t?[l.read,...verbInputs(l,t)]:[],u=o!==void 0&&i.every(e=>prepare(e).predicate===void 0||!readsAny(prepare(e).predicate,o,s)),d=t?[...u?[]:i,...t.writes.flatMap(e=>{let t=l.moves.get(e);return t===void 0?[]:[t]})]:l.place===void 0?[]:[l.place];if(d.length===0)continue;let f=[...new Set(d)].map(prepare),p=f.length===1?f[0]:a.andSelectors(e,f);p.predicate!==void 0&&n.push(J({...p,predicate:layerOf(c,r,p.predicate)}))}return n.length===0?null:n.length===1?n[0]:a.andSelectors(e,n)})??void 0}cycles(e,t){if(t.verb===`delete`)return mn;let n=this.rows.verbs?.get(e[`~`].names.ts);if(n===void 0)return mn;let r=new Set;for(let i of n)for(let n of i?.acyclic??[]){let i=this.#e.schema.membership(e,n);(t.writes.includes(n)||i.kind===`reference`&&i.pairs.some(e=>t.writes.includes(e.source)))&&r.add(n)}return r.size===0?mn:[...r]}};const mn=Object.freeze([]);function verbInputs(e,t){return t.verb===`delete`?[e.delete]:t.writes.length===0?[e.update]:[...new Set([...t.writes.map(t=>e.writes.get(t)??e.update),...t.marks?[e.delete]:[]])]}function foldedLayer(e,t){let n=e.conditions.length===0?e.predicate:foldConditions(e.predicate,n=>t[e.conditions.indexOf(n)]===`1`),r=new Map;callReads(n,r,new Set);let i={predicate:n,parameters:[...r]};return e.folded.set(t,i),i}function layerOf(e,t,n){let r=new Set;return callReads(n,new Map,r),J({kind:`layer`,layer:e,model:t,predicate:n,conditions:J([...r]),folded:new Map})}function balancedOr(e,t){let build=(n,r)=>{if(r-n<2)return r===n?t([]):e[n];let i=n+Math.floor((r-n)/2);return t([build(n,i),build(i,r)])};return build(0,e.length)}var hn=class Queries{schema;adapter;#e=0;#t;#n;domain;#r;#i;#a;#o=!1;#s;#c;constructor(e,t,n,r,i){this.schema=e,this.adapter=t,this.#t=e.queryViews(t),this.#n=n,this.domain=r,this.#r=i,this.#c=t.capabilities.sharesRelationBodies===!0&&!resemblesAlias(t.namespace??``)&&!hasAliasLikeNames(e)}#l(e){if(this.#s!==void 0)return e();let t={byKey:new Map,order:[]};this.#s=t;let n;try{n=e()}finally{this.#s=void 0}let r=[];for(let e of t.order){let t=e.slots.length>1;for(let n of e.slots)n.slot.settle(t?n.use:n.inline);t&&r.push({name:e.name,query:e.query})}return r.length===0?n:V`${this.adapter.cte.with(r)} ${n}`}#u(e){if(!this.#c)return e();let t=!0,n=this.#l(()=>{let n=e();return t=n!==void 0,n??V.empty});return t?n:void 0}under(e,t){return new Queries(this.schema,this.adapter,this.#n,e,t)}#d(e,t,n){let r=this.#i;return r===void 0||r.length===0?this.domain?.selector(e,t,dn,n):this.domain?.defaults.selector(e,t,r)}domainOf(e,t,n){let r=this.#d(e,t,n);return r&&!this.#F(r.predicate)?r:void 0}get#f(){return(this.#i?.length??0)>0}get#p(){return this.#r?.rows.values}#m;get#h(){return this.#m??=()=>this.#r.instant()}#g(e){let t=this.#p,{conditions:n}=e,r=``;for(let e=0;e<n.length;e++)r+=n[e].holds(t,this.#h)?`1`:`0`;let i=e.folded.get(r)??foldedLayer(e,r),a=!1,{parameters:o}=i;for(let n=0;n<o.length;n++){let[r,i]=o[n],s=r.read(t,this.#h);if(!(s!==void 0&&(!i||Array.isArray(s)))){if(t?.required(r.control,e.model))return X;a=!0}}return a?void 0:i.predicate}fieldReader(e){let t=this.adapter.result,adapterLeg=n=>t.parseField(n,e,e=>e===void 0?n:e),n=this.#n?.parseField;return t=>{try{return n?n(t,e,adapterLeg):adapterLeg(t)}catch(t){throw t instanceof InvalidScalarResult||t instanceof re?t:new InvalidScalarResult(e,`provider scalar decoding failed`)}}}decodeResult(e,t,n){let adapterDecode=e=>this.adapter.result.parseResult(e,t,t=>n(t===void 0?e:t)),r=this.#n?.parseResult;return r?r(e,t,e=>adapterDecode(e)):adapterDecode(e)}alias(){return`q${this.#e++}`}#_(){return this.#e=0,this.alias()}table(e,t){return this.adapter.identifiers.table(e[`~`].names.sql,t)}column(e,t,n){let r=this.columnName(e,t);return n?this.adapter.identifiers.column(n,r):this.adapter.identifiers.escape(r)}columnName(e,t){return physicalField(this.schema,e,t).name}value(e){return e instanceof H?callerText(e):this.adapter.literals.value(e)}fieldValue(e,t,n){return this.#v(physicalField(this.schema,e,t).scalar,n,t,this.scalarShape(e,t).id)}#v(e,t,n,r){let i=this.adapter,a=e[`~`].state;if(t instanceof H){let e=callerText(t);return a.type===`decimal`&&a.array!==!0?i.expressions.decimalCast(e,a.decimal):e}let o=me(t);if(o)return o===`DbNull`?i.literals.null():i.json.value(null);if(t==null)return i.literals.null();if(a.array===!0&&Array.isArray(t))return this.#b(a,t,n);if(isCompact(r))return i.literals.id(encodeIdentifier(r,t),r.representation);switch(a.type){case`bigint`:return i.literals.value(a.array===!0?String(t):t);case`decimal`:case`json`:case`point`:case`vector`:case`datetime`:case`date`:case`time`:return this.#y(e,t,n);default:return i.literals.value(t)}}#y(e,t,n){let r=this.adapter,i=e[`~`].state,a=i.array===!0;switch(i.type){case`decimal`:return a?r.literals.value(decimalMembers(i,[t],n,this.adapter.result)[0]):r.literals.decimal(canonicalDecimal(t,n),requireDecimal(i,n));case`json`:return r.literals.json(t);case`point`:return this.#S(`value`).value(this.value(t.longitude),this.value(t.latitude));case`vector`:return r.capabilities.supportsVector?r.vector.literal(t):r.literals.json(t);case`datetime`:{let n=admittedTemporal(t,ve);return typeof n==`string`?r.literals.dateTime(n,a?void 0:this.#x(e),a):r.literals.value(n)}case`time`:{let e=_e(t);return r.literals.value(`value`in e?e.value:t)}case`date`:{let e=admittedTemporal(t,ye);return typeof e==`string`?r.literals.dateTime(e,void 0,a):r.literals.value(e)}default:return r.literals.value(t)}}#b(e,t,n){return e.type===`decimal`?this.adapter.arrays.value(decimalMembers(e,t,n,this.adapter.result)):e.type===`enum`?this.adapter.arrays.enumValue([...t]):this.adapter.arrays.value([...t],e.type===`datetime`||e.type===`date`?e.type:void 0)}#x(e){return e[`~`].state.array===!0?void 0:e[`~`].nativeType}#S(e){let t=this.adapter.geoPoint;if(!t)throw new ce(`point`,e,`GeoPoint requires a provider with its physical point tier enabled.`);return t}projectedColumn(e,t,n){let r=this.column(e,t,n),i=this.scalarShape(e,t),a=physicalField(this.schema,e,t).scalar[`~`].state;return a.type===`bigint`&&a.array!==!0?this.adapter.expressions.cast(r,`text`):a.array===!0&&(a.type===`bigint`||a.type===`number`)?this.adapter.arrays.exactNumericProjection(r):a.type===`decimal`||a.type===`point`&&a.array!==!0?this.#C(a,r):transportedIdentifier(this.adapter,i.id,r,i.nullable)}#C(e,t){if(e.type===`decimal`)return e.array===!0?this.adapter.arrays.exactNumericProjection(t):this.adapter.expressions.cast(t,`text`);let n=this.#S(`projection`),r=this.adapter.json.objectFromColumns([[`longitude`,this.adapter.json.document(this.adapter.json.number(n.longitude(t)))],[`latitude`,this.adapter.json.document(this.adapter.json.number(n.latitude(t)))]]);return e.nullable?this.adapter.expressions.caseWhen([{when:this.adapter.operators.isNull(t),then:this.adapter.literals.null()}],r):r}#w(e,t){return e.kind===`scalar`?e.type===`decimal`||(e.type===`bigint`||e.type===`number`)&&e.list?e.list?this.adapter.arrays.exactNumericProjection(t):this.adapter.expressions.cast(t,`text`):e.list||e.type===`json`||e.type===`point`||e.type===`vector`?this.adapter.json.document(t):e.type===`bigint`?this.adapter.expressions.cast(t,`text`):e.type===`number`?this.adapter.json.number(t):e.type===`blob`?this.adapter.expressions.caseWhen([{when:this.adapter.operators.isNull(t),then:this.adapter.literals.null()}],this.adapter.expressions.blobToHex(t)):t:this.adapter.json.document(t)}scalarShape(e,t){let n=this.#t.leaves.get(e);n===void 0&&(n=new Map,this.#t.leaves.set(e,n));let r=n.get(t);if(r===void 0){let i=physicalField(this.schema,e,t);r=this.#T(i.scalar,i.nullable,identifierColumn(this.adapter,this.schema.index,e,t,i)),n.set(t,r)}return r}#T(e,t,n){let r=e[`~`].state;return J({kind:`scalar`,type:r.type,nullable:t,scalar:e,list:r.array===!0?!0:void 0,decimal:r.type===`decimal`?r.decimal:void 0,dateTime:r.type===`datetime`?this.adapter.result.dateTimeRepresentation?.(this.#x(e))??`text`:void 0,enumValues:r.type===`enum`&&`enumValues`in e?new Set(e.enumValues):void 0,dimension:r.dimension,id:n})}junctionWhere(e,t,n){return this.adapter.operators.and(...[e.sourceSide,e.targetSide].flatMap(e=>e.members.filter(e=>Object.hasOwn(t,e.junctionField)).map(r=>this.adapter.operators.eq(n?this.adapter.identifiers.column(n,r.junctionField):this.adapter.identifiers.escape(r.junctionField),this.fieldValue(e.model,r.referencedField,t[r.junctionField])))))}junctionSideConditions(e,t,n){let r=this.adapter;return e.members.map(i=>r.operators.eq(t?r.identifiers.column(t,i.junctionField):r.identifiers.escape(i.junctionField),typeof n==`string`?this.column(e.model,i.referencedField,n):this.fieldValue(e.model,i.referencedField,n[i.referencedField])))}junction(e,t,n=!1){let r=this.adapter,i=this.#_(),a=e.uniqueSide===`target`?e.sourceSide:e.targetSide,o={},s=a.members.map(e=>{let t=this.scalarShape(a.model,e.referencedField);o[e.junctionField]=t;let n=r.identifiers.column(i,e.junctionField);return r.identifiers.aliased(t.type===`decimal`||t.type===`bigint`?r.expressions.cast(n,`text`):transportedIdentifier(r,t.id,n,t.nullable),e.junctionField)});return{sql:q(r,{columns:V.join(s,`, `),from:r.identifiers.table(e.table,i),where:this.junctionWhere(e,t,i),forUpdate:n}),shape:{kind:`object`,fields:o}}}#E(e,t,n){let r=readUpdate(n);if(r.kind===`arithmetic`&&r.operator===`divide`&&exactDecimalDomain(physicalField(this.schema,e,t).scalar[`~`].state)&&dividesByZero(r.by))throw new j(`Cannot divide decimal field '${t}' by zero.`);return r}namesUpdate(e,t,n){return this.#D(e,t,readUpdate(n))}#D(e,t,n){return n.kind===`arithmetic`?!((n.operator===`multiply`||n.operator===`divide`)&&exactDecimalDomain(physicalField(this.schema,e,t).scalar[`~`].state)!==void 0):n.kind===`value`}#O(e,t){let n=physicalField(this.schema,e,t).scalar[`~`].state;return{integer:n.type===`int`||n.type===`bigint`,decimal:exactDecimalDomain(n)}}updateAssignment(e,t,n){let r=this.adapter,i=this.column(e,t),a=this.#E(e,t,n);return a.kind===`value`?r.set.assign(i,this.fieldValue(e,t,a.value)):a.kind===`list`?r.set[a.operator](i,this.fieldValue(e,t,a.members)):r.set[a.operator](i,this.fieldValue(e,t,a.by),this.#O(e,t))}updateValue(e,t,n,r){let i=this.adapter,a=this.#E(e,t,n);if(!this.#D(e,t,a))throw new j(`Cannot determine the updated value of '${e[`~`].names.ts??`unknown`}.${t}' before '${a.operator}' executes: the database determines the stored result.`);if(a.kind===`value`)return this.fieldValue(e,t,a.value);let o=physicalField(this.schema,e,t).scalar[`~`].state,s=o.type===`int`?i.expressions.cast(r,`integer`):r,c=this.fieldValue(e,t,a.by);return a.operator===`increment`?i.expressions.add(s,c):a.operator===`decrement`?i.expressions.subtract(s,c):a.operator===`multiply`?i.expressions.multiply(s,c):o.type===`int`||o.type===`bigint`?i.expressions.integerDivide(s,c):i.expressions.divide(s,c)}prepareSelector(e,t,n=!1,r=!0){if(!r)return J({model:e,predicate:t?this.#R(e,t,void 0,[],n):void 0});let i=newSelectorFacts(),a=Object.keys(t??{}),o=a.length===1?qe(e,a[0]):void 0,s=o?o.name?record(t[o.name]):t:void 0;return J({model:e,facts:i,uniqueKey:o,uniqueValues:s?new Map(o.fields.map(e=>[e,s[e]])):void 0,predicate:t?this.#R(e,t,i,[],n):void 0})}selectorFacts(e){return e.facts}identitySelector(e,t){let n=newSelectorFacts();return J({model:e,facts:n,predicate:this.identityPredicate(e,t,n)})}identityPredicate(e,t,n){return J({kind:`and`,predicates:J(Object.entries(t).map(([t,r])=>this.#B(e,t,r,n)))})}excludeIdentities(e,t){let n=newSelectorFacts(),r=this.#k(e,t,n);return J({model:e,facts:n,predicate:t.length===0?void 0:this.combine(`NOT`,[r])})}includeIdentities(e,t){let n=newSelectorFacts();return J({model:e,facts:n,predicate:this.#k(e,t,n)})}referenced(e,t,n,r){let i=t.map(t=>{let i=bindMembership(this.schema,e,t),a=[],o=n?.selector(i.target,`related`)?.predicate;return o&&a.push(o),r?.slot===t&&a.push(this.combine(`NOT`,[this.identityPredicate(i.target,r.identity,newSelectorFacts(!1))])),Object.freeze({kind:`relation`,edge:i,quantifier:`some`,predicate:a.length===0?void 0:this.combine(`AND`,a),unscoped:!0})});return Object.freeze({model:e,facts:newSelectorFacts(!1),predicate:this.combine(`OR`,i)})}#k(e,t,n){let r=U(e).rowKey?.fields,i=r?.length===1?r[0]:void 0;if(i&&t.length>0&&t.every(e=>Object.keys(e).length===1&&Object.hasOwn(e,i)))return this.#B(e,i,{in:t.map(e=>e[i])},n);let a=t.map(t=>this.identityPredicate(e,t,n));return a.length>0&&(n.exact=!1),balancedOr(a,e=>this.combine(`OR`,e))}andSelectors(e,t){let n=newSelectorFacts(),r=[];for(let e of t){for(let t of e.facts.fields)n.fields.add(t);for(let[t,r]of e.facts.equals)n.equals.set(t,r);for(let[t,r]of e.facts.keys)n.keys.set(t,r);n.exact&&=e.facts.exact,n.reads.push(...e.facts.reads),e.predicate&&r.push(e.predicate)}return J({model:e,facts:n,predicate:r.length===0?void 0:J({kind:`and`,predicates:J(r)})})}candidates(e,t,n=this.domain,r){let i=n?.selector(e.model,t,dn,r);return i===void 0?e:Object.freeze({...this.andSelectors(e.model,[e,i]),uniqueKey:e.uniqueKey,uniqueValues:e.uniqueValues,scoped:!0,...r&&{judgement:r}})}#A(e,t,n){let r=this.adapter,i=this.schema.storedFields(e),a=this.alias(),o=this.table(e,a),s=q(r,{columns:V.join(i.map(t=>this.column(e,t,a)),`, `),from:o,where:r.literals.false()});return r.setOperations.typedRows({head:s,from:o,table:this.table(e),alias:a,columns:i.map(t=>this.columnName(e,t))},t.map(e=>i.map(t=>e(t)??r.literals.null())),n)}#j(e,t,n,r,i,a=mn){let o=this.adapter,s=this.#a;this.#a={alias:n,nulls:r};let c;try{c=t&&this.lowerSelector(t,n)}finally{this.#a=s}let l=[...c===void 0?[]:[c],...a.map(t=>this.#M(e,t,n))];if(l.length!==0)return o.subqueries.scalar(o.assertions.holds(o.operators.and(...l),i))}#M(e,t,n){let r=this.adapter,i=this.schema.membership(e,t),{cte:a,cteName:o,walk:s,childColumns:c}=this.#at(i,n,{depth:!1,self:!1},!1);return r.filters.none(V`${a} ${q(r,{columns:V.raw(`1`),from:r.identifiers.aliased(r.identifiers.escape(o),s),where:this.#tt(e,n,c.map(e=>r.identifiers.column(s,e)))})}`)}producedSource(e,t,n,r){let i=this.adapter,a=this.alias(),o=new Set(t),s=this.#A(e,n.map(t=>n=>o.has(n)?this.fieldValue(e,n,t[n]):void 0),a),c=new Map;for(let t of this.schema.storedFields(e)){let e=new Set(n.map(e=>{let n=o.has(t)?e[t]:null;return n instanceof H?void 0:n==null})),[r]=e;e.size===1&&r!==void 0&&c.set(t,r)}return this.#u(()=>{let n=this.#j(e,r,a,c);if(n!==void 0)return q(i,{columns:V.join(t.map(t=>this.column(e,t,a)),`, `),from:s,where:V`${n} = 1`})})}producedWhere(e,t,n,r,i=mn,a){if(r===void 0&&i.length===0)return;let o=this.adapter,s=this.alias(),c=this.alias(),current=t=>this.column(e,t,s),l=this.schema.keys(e),unread=t=>!(this.namesUpdate(e,t,n[t])||r?.predicate&&readsAny(r.predicate,new Set([t]),l)||i.some(n=>{let r=this.schema.membership(e,n);return r.kind===`reference`&&r.pairs.some(e=>e.source===t)})),u=this.#A(e,[t=>n[t]===void 0||unread(t)?current(t):this.updateValue(e,t,n[t],current(t))],c),d=new Map;for(let[e,t]of Object.entries(n)){if(t===void 0)continue;let n=wholeValue(t);n&&!(n.value instanceof H)&&d.set(e,n.value===null)}let judgedSet=()=>{let n=this.#j(e,r,c,d,u,i);if(n===void 0)return;let l=this.keyOrder(e).map(current);return q(o,{columns:V.join(l,`, `),from:this.table(e,s),where:t(s),groupBy:V.join(l,`, `),having:V`${o.aggregates.min(n)} = 1`,...a!==void 0&&{orderBy:this.#L(e,s),limit:this.value(a)}})},f=this.#u(judgedSet);if(f===void 0)return;let p=e[`~`].names.sql;return o.operators.in(rowValue(this.keyOrder(e).map(t=>this.column(e,t,p))),o.subqueries.scalar(o.capabilities.supportsMutationTargetInSubquery?f:V`SELECT * FROM ${o.subqueries.correlate(f,this.alias())}`))}#N(e,t,n){let r=this.#d(e,n);return r?.predicate===void 0?t:t?.predicate===void 0?r:J({model:e,predicate:J({kind:`and`,predicates:J([t.predicate,r.predicate])})})}lowerSelector(e,t){return e.predicate?this.#P(e.predicate,t):void 0}#P(e,t){if(e.kind===`layer`){let n=this.#g(e);if(n===void 0)return;let r=this.#a;r!==void 0&&t===r.alias&&(n=foldKnownNulls(n,r.nulls));let i=this.#i??=[];i.push(e.layer);try{return this.#J(n,t)}finally{i.pop()}}if(e.kind!==`and`)return this.#J(e,t);let{predicates:n}=e;if(n.length===1){let e=this.#P(n[0],t);return e&&this.adapter.operators.and(e)}let r=[];for(let e=0;e<n.length;e++){let i=this.#P(n[e],t);i!==void 0&&r.push(i)}return r.length===0&&n.length>0?void 0:this.adapter.operators.and(...r)}#F(e){return e?.kind===`layer`?this.#g(e)===void 0:e?.kind===`and`&&e.predicates.length>0&&e.predicates.every(e=>this.#F(e))}lowerWhere(e,t,n){let r=this.#N(e,t===void 0?void 0:this.prepareSelector(e,t,!1,!1),`root`);return r&&this.lowerSelector(r,n)}locatedValue(e,t,n,r){let i=this.alias(),a=q(this.adapter,{columns:this.column(e,t,i),from:this.table(e,i),where:this.lowerSelector(n,i),limit:this.value(1)});return this.adapter.subqueries.scalar(this.hideMutationTarget(a,e,r?.[`~`].names.sql))}lowerMutationLimit(e,t,n){let r=this.adapter,i=e[`~`].names.sql,a=!r.capabilities.supportsMutationTargetInSubquery&&t.predicate!==void 0&&readsRelation(t.predicate)?this.#I(t):this.lowerSelector(t,i);return n===void 0?{where:a}:r.capabilities.supportsMutationRowLimit?{where:a,suffix:V`${r.clauses.orderBy(this.#L(e))} ${r.clauses.limit(this.value(n))}`}:{where:r.operators.and(...[a,this.#I(t,n)].filter(e=>e!==void 0))}}window(e,t){return Object.freeze({model:e.model,facts:e.facts,predicate:Object.freeze({kind:`window`,selector:e,limit:t})})}lockAll(e){let t=this.adapter,n=this.#_(),r=q(t,{columns:t.literals.true(),from:this.table(e.model,n),where:this.lowerSelector(e,n),forUpdate:!0});return{sql:q(t,{columns:t.identifiers.aliased(t.aggregates.count(),`_count`),from:t.subqueries.correlate(r,this.alias())}),shape:{kind:`object`,fields:{_count:$}}}}through(e,t){let n=newSelectorFacts(!1);for(let t of this.keyOrder(e))n.fields.add(t);return Object.freeze({model:e,facts:n,predicate:Object.freeze({kind:`through`,model:e,last:t})})}#I(e,t,n){let r=this.adapter,i=e.model,a=this.alias(),o=this.keyOrder(i),s=q(r,{columns:V.join(o.map(e=>this.column(i,e,a)),`, `),from:this.table(i,a),where:this.lowerSelector(e,a),...t===void 0?{}:{orderBy:this.#L(i,a),limit:this.value(t)}});return r.operators.in(rowValue(o.map(e=>this.column(i,e,n))),r.subqueries.scalar(r.capabilities.supportsMutationTargetInSubquery?s:V`SELECT * FROM ${r.subqueries.correlate(s,this.alias())}`))}#L(e,t){return V.join(this.keyOrder(e).map(n=>this.adapter.orderBy.asc(this.column(e,n,t))),`, `)}lowerIdentity(e,t,n){return this.adapter.operators.and(...Object.entries(t).map(([t,r])=>this.adapter.operators.eq(this.column(e,t,n),this.fieldValue(e,t,r))))}combinator(e,t){return(t===`AND`||t===`OR`||t===`NOT`)&&!e[`~`].state.scalars[t]&&!e[`~`].state.relations[t]}combine(e,t){let n=t.filter(states);return e===`OR`?n.length===0?X:sameColumnIn(n)??J({kind:`or`,predicates:J(n)}):J({kind:`and`,predicates:J(e===`AND`?n:n.map(e=>J({kind:`not`,predicate:e})))})}#R(e,t,n,r,i=!1,a=!0){return t instanceof y?(n&&(n.exact=!1),J({kind:`condition`,condition:t})):J({kind:`and`,predicates:J(Object.entries(t).map(([t,o])=>{if(this.combinator(e,t))return n&&t!==`AND`&&(n.exact=!1),this.combine(t,entries(o).map(i=>this.#R(e,i,n,r,!1,t===`NOT`?!a:a)));if(e[`~`].state.relations[t])return this.#G(e,t,o,n,r,a);let s=i||e[`~`].state.scalars[t]===void 0?qe(e,t):void 0;return s?.name?J({kind:`and`,predicates:J(s.fields.map(t=>this.#B(e,t,record(o)[t],n,i,a)))}):this.#B(e,t,o,n,i&&s!==void 0,a)}))})}#z(e,t){return J({model:e,field:t,physical:physicalField(this.schema,e,t)})}#B(e,t,n,r,i=!1,a=!0){let o=this.#z(e,t);if(r){r.fields.add(t);let e=typeof n==`object`&&n&&!(n instanceof H)&&!(n instanceof S)&&!z(n)?record(n):void 0,a=e===void 0||Object.keys(e).length===1&&`equals`in e,o=e&&a?e.equals:n;a&&(o===null||typeof o!=`object`&&!(o instanceof H))?(r.equals.set(t,o),i&&r.keys.set(t,o)):a&&o instanceof S||(r.exact=!1)}return this.#V(J(i?{kind:`column`,scalar:o,key:!0}:{kind:`column`,scalar:o}),n,!1,a)}#V(e,t,n=!1,r=!0){let i=e.scalar?.physical.scalar[`~`].state;return t===null||t instanceof H||z(t)||typeof t!=`object`||me(t)!==void 0||i?.array===!0&&Array.isArray(t)||!addressesOperators(i,record(t))?this.prepareOperation(e,`equals`,t,n,r):this.#H(e,t,n,r)}#H(e,t,n,r){let i=e.scalar?.physical.scalar[`~`].state,a=record(t),o=a.mode,s=i?.type===`json`&&o!==void 0?o===`insensitive`:n||o===`insensitive`,c=i?.type===`json`&&Array.isArray(a.path)?J({...e,path:J([...a.path])}):e,l=[];for(let e of Object.keys(a)){if(e===`mode`||e===`path`)continue;let t=a[e];e===`equals`?l.push(this.#V(c,t,s,r)):e===`not`?l.push(J({kind:`not`,predicate:this.#V(c,t,s,!r)})):l.push(this.prepareOperation(c,e,t,s,r))}return J({kind:`and`,predicates:J(l)})}prepareOperation(e,t,n,r,i=!0){let a=e.scalar;switch(t){case`in`:case`notIn`:return J({kind:`operation`,operator:t,target:e,operands:J(n instanceof S?[{kind:`parameter`,parameter:n,spread:!0}]:n.map(e=>a?this.#U(a,e):{kind:`value`,value:e})),insensitive:r});case`equals`:case`lt`:case`lte`:case`gt`:case`gte`:case`contains`:case`startsWith`:case`endsWith`:return J({kind:`operation`,operator:t,target:e,operand:a?this.#U(a,n):{kind:`value`,value:n},value:n,insensitive:r});default:return J({kind:`operation`,operator:t,target:e,value:n,insensitive:r,...t===`distance`&&i&&a?.physical.scalar[`~`].state.type===`point`&&distanceUpperBound(n)!==void 0?{probe:!0}:{}})}}#U(e,t){if(t instanceof S)return{kind:`parameter`,parameter:t};if(z(t)){if(e.physical.scalar[`~`].state.type===`json`)throw new N(`Field reference '${ge(t)}' is not supported in a JSON filter operand.`);return this.#W(e,t)}if(!(t instanceof H))return{kind:`value`,value:t};let n=t.values.map(t=>{if(z(t))return this.#W(e,t);let n=[t],r=new WeakSet;for(let e of n){if(z(e))throw new N(`An SQL filter field reference must be a direct interpolation, not nested inside a parameter object.`);if(!(typeof e!=`object`||!e||r.has(e))){r.add(e);for(let t of Object.values(Object.getOwnPropertyDescriptors(e)))`value`in t&&n.push(t.value)}}return{kind:`value`,value:t}});return n.some(e=>e.kind===`field`)?{kind:`sql`,strings:[...t.strings],operands:J(n)}:{kind:`value`,value:t}}#W(e,t){let{model:n}=e,r=he(t),i=n[`~`].names.ts??`unknown`;if(r.model!==i)throw new N(`Field reference '${ge(t)}' cannot be used while filtering '${i}': a field reference may only compare columns of the same model.`);if(r.list)throw new N(`Field reference '${ge(t)}' is a list field and cannot be used as a scalar SQL operand.`);let a=n[`~`].state.scalars[r.field];if(!a)throw new N(`Field reference '${ge(t)}' does not name a scalar field of '${i}'.`);let o=exactDecimalDomain(e.physical.scalar[`~`].state),s=exactDecimalDomain(a[`~`].state);if(o&&s&&!sameDecimalDomain(o,s))throw new N(`Field reference '${r.field}' cannot be compared with '${e.field}' on '${i}': '${e.field}' is decimal(${o.precision},${o.scale}) and '${r.field}' is decimal(${s.precision},${s.scale}). Two decimals compare exactly only when they declare the same precision and scale.`);let c=incomparableIdentifiers(this.scalarShape(n,e.field).id,this.scalarShape(n,r.field).id,e.field,r.field);if(c!==void 0)throw new N(`Field reference '${r.field}' cannot be compared with '${e.field}' on '${i}': ${c}`);return{kind:`field`,scalar:this.#z(n,r.field)}}#G(e,t,n,r,i,a=!0){let o=this.schema.index.get(e).get(t),s=record(n);if(o.member||o.edge.kind!==`variantRowCarrier`&&o.edge.kind!==`variantJunctionCarrier`){let n=bindMembership(this.schema,e,t),o=s.recurse===void 0?void 0:J({depth:s.recurse.depth,self:s.self===!0});return J({kind:`and`,predicates:J((o?Object.entries(s).filter(([e,t])=>en.has(e)&&t!==void 0):Object.keys(s).every(e=>en.has(e))?Object.entries(s):[[`is`,s]]).map(([e,t])=>this.#K(n,e,t,r,i,a,o)))})}let c=o.edge.members,l=o.edge.kind===`variantJunctionCarrier`,variantEdge=n=>bindMembership(this.schema,e,t,n);if(o.edge.kind===`variantRowCarrier`&&s.type===void 0){let t=`is`in s,n=[o.edge.storage.typeColumn.name,o.edge.storage.idColumn.name];return Object.freeze({kind:`and`,predicates:Object.freeze(n.map(n=>this.#B(e,n,t?null:{not:null},r)))})}return J({kind:`and`,predicates:J((l?Object.entries(s).map(([e,t])=>[e,record(t)]):[[void 0,s]]).map(([e,t])=>{let n=variantEdge(t.type),o=t.isNot!==void 0,s=o||e===`none`||e===`every`,l=this.#q(n,o?record(t.isNot):t.is,r,i,s,a);if(e!==void 0){let s=J({kind:`relation`,edge:n,quantifier:e,predicate:o&&l?J({kind:`not`,predicate:l}):l});return e===`every`?J({kind:`and`,predicates:Object.freeze([...l?[s]:[],...c.filter(e=>e.variant!==t.type).map(e=>this.#K(variantEdge(e.variant),`none`,void 0,r,i,a))])}):s}return J({kind:`relation`,edge:n,quantifier:`some`,predicate:o&&l?Object.freeze({kind:`not`,predicate:l}):l})}))})}#K(e,t,n,r,i,a=!0,o){return J({kind:`relation`,edge:e,quantifier:t,predicate:this.#q(e,n==null?void 0:record(n),r,i,t===`none`||t===`every`||t===`isNot`,a,o),...o?{closure:o}:{}})}#q(e,t,n,r,i,a=!0,o){if(!n)return t?this.#R(e.target,t,void 0,r,!1,a&&!i):void 0;let s=[...r,e],c=newSelectorFacts(!i&&o===void 0);if(o&&e.kind===`reference`)for(let t of e.pairs)c.fields.add(t.source).add(t.target);let l=t?this.#R(e.target,t,c,s,!1,a&&!i):void 0,u=this.domain?.selector(e.target,`related`);if(u)for(let e of u.facts.fields)c.fields.add(e);return n.reads.push({model:e.target,path:s,fields:c.fields,equals:c.equals,exact:c.exact}),n.reads.push(...c.reads),l}#J(e,t){let n=this.adapter;switch(e.kind){case`and`:case`layer`:return this.#P(e,t)??n.literals.true();case`or`:return balancedOr(e.predicates.map(e=>this.#J(e,t)),e=>n.operators.or(...e));case`not`:return n.operators.not(this.#J(e.predicate,t));case`always`:return e.value?n.literals.true():n.literals.false();case`condition`:return e.condition.holds(this.#p,this.#h)?n.literals.true():n.literals.false();case`operation`:return this.lowerOperation(this.#Y(e),t);case`relation`:return this.#le(e,t);case`window`:return this.#I(e.selector,e.limit,t);case`through`:{let{model:r,last:i}=e,a=this.keyOrder(r);return n.operators.lte(rowValue(a.map(e=>this.column(r,e,t))),rowValue(a.map(e=>this.fieldValue(r,e,i[e]))))}}}#Y(e){return e.operand?.kind!==`parameter`&&!(e.value instanceof S)&&!e.operands?.some(isParameterOperand)?e:this.#X(e)}#X(e){let{operand:t,operands:n,value:r,...i}=e,read=e=>e.read(this.#p,this.#h),bound=e=>{if(e.kind!==`parameter`)return[e];let t=read(e.parameter);return e.spread?t.map(e=>({kind:`value`,value:e})):[{kind:`value`,value:t}]};return{...i,...t&&{operand:bound(t)[0]},...n&&{operands:n.flatMap(bound)},value:r instanceof S?read(r):r}}#Z(e,t){return this.#Q(e.model,e.field,t?this.adapter.identifiers.column(t,e.physical.name):this.adapter.identifiers.escape(e.physical.name),t)}#Q(e,t,n,r){if(this.#f||this.#o)return n;let i=this.domain?.projected(e)?.gates.get(t),a=i&&this.#Ge(e,i,r,!0);return a===void 0?n:this.adapter.expressions.caseWhen([{when:a,then:n}],this.adapter.literals.null())}#$(e,t,n){return this.#Q(e,t,this.column(e,t,n),n)}#ee(e,t){return!this.#f&&this.domain?.projected(e)?.gates.has(t)===!0}#te(e){return!(this.#f||this.#o)&&(this.domain?.projected(e)?.gates.size??0)>0}#ne(e){this.#o=!0;try{return e()}finally{this.#o=!1}}#re(e,t){return e.kind===`column`?this.#Z(e.scalar,t):this.#Me(e.aggregate,e.scalar,t)}lowerOperation(e,t){let n=this.adapter,{operator:r,target:i,operand:a}=e,o=i.scalar,s=i.kind===`aggregate`&&i.aggregate===`_count`,c=s?void 0:o?.physical.scalar[`~`].state,l=this.#re(i,t);if(c?.type===`json`&&c.array!==!0)return this.#se(e,l);let u=e.insensitive===!0,d=i.kind===`column`&&o?this.scalarShape(o.model,o.field).id:void 0,f=!(i.kind===`column`&&i.key===!0&&!u)&&c!==void 0&&c.array!==!0&&(c.type===`string`||c.type===`enum`)&&!isCompact(d),p=r===`contains`||r===`startsWith`||r===`endsWith`,exact=(e,t=o)=>f?n.expressions.caseSensitiveText(e,t?.physical.scalar[`~`].nativeType,p||u):e,m=f&&u?n.expressions.caseSensitiveText(n.expressions.asciiCaseFold(exact(l))):l,spelledAsText=e=>c?.type===`enum`&&e.kind===`field`,comparableColumn=e=>exact(spelledAsText(e)?n.expressions.cast(l,`text`):l),bind=(e,r=!1)=>{if(e.kind===`field`){let i=this.#Z(e.scalar,t),a=spelledAsText(e)?n.expressions.cast(i,`text`):i;return r?n.expressions.caseSensitiveText(n.expressions.asciiCaseFold(exact(a,e.scalar))):exact(a,e.scalar)}if(e.kind===`sql`){let i=this.value(new H(e.strings,e.operands.map(e=>e.kind===`field`?this.#Z(e.scalar,t):e.value)));return r?n.expressions.asciiCaseFold(i):i}let a=o&&!s?this.#ae(i,o,e.value,d):this.value(e.value);return r?n.expressions.asciiCaseFold(a):a};switch(r){case`equals`:{let e=a,t=e.kind===`value`?e.value:void 0;return e.kind===`value`&&t===null?n.operators.isNull(l):c?.type===`point`&&c.array!==!0?this.#S(`equals`).equals(l,t):c?.array===!0&&Array.isArray(t)?n.operators.eq(l,bind(e)):u&&(e.kind!==`value`||typeof t==`string`||t instanceof H)?n.operators.eq(m,bind(e,!0)):f&&e.kind===`value`&&!(t instanceof H)?n.operators.exactTextEq(l,bind(e),o?.physical.scalar[`~`].nativeType):n.operators.eq(comparableColumn(e),bind(e))}case`lt`:case`lte`:case`gt`:case`gte`:return n.operators[r](f&&u?m:exact(l),bind(a,f&&u));default:return this.#ie(e,{column:p&&!(r===`startsWith`&&a?.kind===`value`&&typeof a.value==`string`)?exact(l):l,folded:m,insensitive:u,text:f,exact,bind,state:c})}}#ie(e,{column:t,folded:n,insensitive:r,text:i,exact:a,bind:o,state:s}){let c=this.adapter,{operator:l,operand:u}=e,d=e.target.scalar,members=()=>e.operands??[];switch(l){case`in`:case`notIn`:{let e=l===`notIn`,s=members();if(s.length===0)return e?c.literals.true():c.literals.false();if(r)return balancedOr(s.map(t=>e?c.operators.neq(n,o(t,!0)):c.operators.eq(n,o(t,!0))),t=>e?c.operators.and(...t):c.operators.or(...t));let u=c.literals.list(s.map(e=>o(e)));return e?c.operators.notIn(a(t),u):i?c.operators.exactTextIn(t,u,d?.physical.scalar[`~`].nativeType):c.operators.in(t,u)}case`contains`:return r?c.operators.containsText(n,o(u,!0)):c.operators.containsText(t,o(u));case`startsWith`:return r?c.operators.startsWithText(n,o(u,!0)):u.kind===`value`&&typeof u.value==`string`?c.operators.startsWithPrefix(t,u.value,d?.physical.scalar[`~`].nativeType):c.operators.startsWithText(t,o(u));case`endsWith`:return r?c.operators.endsWithText(n,o(u,!0)):c.operators.endsWithText(t,o(u));case`has`:return e.value===null?c.literals.false():c.arrays.has(t,this.#v(d.physical.scalar,e.value,d.field));case`hasEvery`:{let n=e.value;return n.length===0?c.operators.isNotNull(t):c.arrays.hasEvery(t,this.#v(d.physical.scalar,n,d.field))}case`hasSome`:{let n=e.value;return n.length===0?c.literals.false():c.arrays.hasSome(t,this.#v(d.physical.scalar,n,d.field))}case`isEmpty`:return e.value?c.arrays.isEmpty(t):c.operators.not(c.arrays.isEmpty(t));case`within`:{let n=e.value,r=this.#S(`within`);if(`bounds`in n)return r.withinBounds(t,n.bounds);if(r.withinPolygon)return r.withinPolygon(t,n.polygon);throw new ce(`point`,`within polygon`,`GeoPoint polygon filtering is not supported by this provider.`)}default:{let n=record(e.value),r=this.#ce(t,s,d.field,n,`filter`),i=e.probe?distanceUpperBound(n):void 0,a=i===void 0?[]:[this.#S(`distance filter`).withinBounds(t,rt(n.to,i))];return c.operators.and(...a,...[`lt`,`lte`,`gt`,`gte`].filter(e=>n[e]!==void 0).map(e=>c.operators[e](r,this.value(n[e]))))}}}#ae(e,t,n,r){if(e.kind===`aggregate`&&(e.aggregate===`_min`||e.aggregate===`_max`)){let e=this.scalarShape(t.model,t.field).id;if(isCompact(e))return aggregatedIdentifier(this.adapter,e,this.#v(t.physical.scalar,n,t.field,e))}return e.kind===`aggregate`&&e.aggregate===`_sum`?this.#oe(t,n,r):this.#v(t.physical.scalar,n,t.field,r)}#oe(e,t,n){let r=e.physical.scalar[`~`].state,i=exactDecimalDomain(r),a=i?decimalSumOperand(t,i):void 0;if(!i||a===void 0)return this.#v(e.physical.scalar,t,e.field,n);let{canonical:o,coefficient:s}=a,c=this.adapter.aggregates.decimalSumOperandPrecision(s);if(c===void 0){let t=s.startsWith(`-`)?s.length-1:s.length;throw new j(`The 'having' _sum operand for decimal field '${e.field}' needs ${t} coefficient digits, but its value is outside this provider's exact HAVING operand cast domain. The provider may compute a wider sum, but VibORM cannot express this operand through its exact decimal cast without changing or refusing the value written.`)}return this.adapter.literals.decimal(o,{precision:Math.max(i.precision,c),scale:i.scale})}#se(e,t){let n=this.adapter,r=[...e.target.kind===`column`?e.target.path??[]:[]],i=e.value,a=n.json.extract(t,r),fold=t=>e.insensitive?n.expressions.asciiCaseFold(t):t,textTarget=()=>fold(n.json.stringAtPath(t,r)),textValue=e=>fold(n.literals.value(e));switch(e.operator){case`equals`:{let e=me(i);if(e){let r=n.operators.isNull(t),i=n.json.equals(a,n.json.value(null));return e===`DbNull`?r:e===`JsonNull`?i:n.operators.or(r,i)}return i===null&&r.length===0?n.operators.isNull(t):n.json.equals(a,n.json.value(i))}case`lt`:case`lte`:case`gt`:case`gte`:{let a=n.operators[e.operator];if(typeof i==`number`)return a(n.json.numberAtPath(t,r),this.value(i));if(typeof i==`string`)return a(n.json.stringAtPath(t,r),this.value(i));throw new j(`JSON filter '${e.operator}' requires a number or string operand.`)}case`string_contains`:return n.operators.containsText(textTarget(),textValue(i));case`string_starts_with`:return n.operators.startsWithText(textTarget(),textValue(i));case`string_ends_with`:return n.operators.endsWithText(textTarget(),textValue(i));case`array_contains`:return n.json.contains(a,n.json.value(Array.isArray(i)?i:[i]));case`array_starts_with`:return n.json.equals(n.json.extract(t,[...r,`0`]),n.json.value(i));default:return n.json.equals(n.json.lastElement(a),n.json.value(i))}}#ce(e,t,n,r,i){if(t.type===`vector`){if(!this.adapter.capabilities.supportsVector)throw new ce(`vector`,i,i===`orderBy`?`vector ordering requires a pgvector-enabled PostgreSQL driver`:`vector distance select requires a pgvector-enabled PostgreSQL driver`);let a=r.to,{dimension:o}=t;if(o!==void 0&&a.length!==o)throw new N(`Vector distance ${i} dimension mismatch for '${n}': expected ${o} values, received ${a.length}.`);let s=r.metric===`cosine`?`cosine`:`l2`;return this.adapter.vector[s](e,this.adapter.vector.literal(a))}let a=this.#S(`distance ${i}`);if(!a.distance)throw new ce(`point`,`distance ${i}`,`GeoPoint distance is not supported by this provider.`);let o=r.to;return a.distance(e,a.value(this.value(o.longitude),this.value(o.latitude)))}#le(e,t){let n=this.adapter;if(e.quantifier===`every`&&!(e.predicate&&states(e.predicate)))return n.literals.true();let{edge:r,closure:i}=e,a=this.alias(),o=e.predicate?this.#J(e.predicate,a):void 0,s=o?[e.quantifier===`every`?n.operators.not(o):o]:[],c;if(i){let{cte:e,cteName:o,walk:l,childColumns:u}=this.#at(r,t??``,i);c=V`${e} ${n.subqueries.existsCheck(V`${n.identifiers.aliased(n.identifiers.escape(o),l)} ${n.joins.inner(this.table(r.target,a),this.#tt(r.target,a,u.map(e=>n.identifiers.column(l,e))))}`,n.operators.and(...s))}`}else c=this.#ue(r,t??``,a,e.unscoped===void 0,s,e.predicate!==void 0&&readsRelation(e.predicate));switch(e.quantifier){case`some`:return n.filters.some(c);case`none`:return n.filters.none(c);case`every`:return n.filters.every(c);case`is`:return e.predicate?n.filters.is(c):n.filters.isNot(c);default:return e.predicate?n.filters.isNot(c):n.filters.is(c)}}#ue(e,t,n,r,i,a=!1){let o=this.adapter,s=this.#pe(e,n,t),c=r?this.domainOf(e.target,`related`):void 0,l=c&&this.lowerSelector(c,n),u=l&&a?o.subqueries.isolated(l):l,d=o.subqueries.existsCheck(this.table(e.target,n),o.operators.and(u?o.operators.and(s,u):s,...i)),f=this.#s,p=u?[u,...i]:i;if(f===void 0||e.kind!==`reference`||e.discriminator!==void 0||p.length===0)return d;let m=q(o,{columns:V.join(e.pairs.map((t,r)=>o.identifiers.aliased(this.column(e.target,t.target,n),`k${r}`)),`, `),from:this.table(e.target,n),where:o.operators.and(...p)}),h=sharedKey(m),g=f.byKey.get(h);g===void 0&&(g={name:`__shared_${f.order.length}`,query:m,slots:[]},f.byKey.set(h,g),f.order.push(g));let{name:_}=g,v=o.subqueries.existsCheck(o.identifiers.escape(_),o.operators.and(...e.pairs.map((n,r)=>o.operators.eq(this.column(e.source,n.source,t),o.identifiers.column(_,`k${r}`))))),y=new Gt(v);return g.slots.push({slot:y,inline:d,use:v}),y}hideMutationTarget(e,t,n){return n===void 0||this.adapter.capabilities.supportsMutationTargetInSubquery||t[`~`].names.sql!==n?e:V`SELECT * FROM ${this.adapter.subqueries.correlate(e,this.alias())}`}#de(e,t){if(e.kind!==`reference`||e.owner!==`source`||e.discriminator?.side!==`source`)return;let n=this.adapter;return n.operators.and(n.operators.eq(this.column(e.source,e.discriminator.field,t),this.value(e.discriminator.value)),...e.pairs.map(r=>n.operators.isNotNull(this.column(e.source,r.source,t))))}correlation(e,t,n,r=!0){let i=this.#pe(e,n,t);return r?this.#fe(e,n,i):i}#fe(e,t,n){let r=this.domainOf(e.target,`related`);return r===void 0?n:this.adapter.operators.and(n,this.lowerSelector(r,t))}memberWhere(e,t,n){return this.#pe(e,n,t)}outsideWhere(e,t,n){let r=this.adapter,i=this.#pe(e,n,t);if(e.kind!==`reference`)return r.operators.not(i);if(e.pairs.some(e=>t[e.source]===null||t[e.source]===void 0))return V`1 = 1`;let a=[...e.discriminator?.side===`target`?[e.discriminator.field]:[],...e.pairs.map(e=>e.target)];return r.operators.or(r.operators.not(i),...a.map(t=>r.operators.isNull(this.column(e.target,t,n))))}#pe(e,t,n){let r=this.adapter;if(e.kind===`reference`)return r.operators.and(...e.discriminator?[r.operators.eq(e.discriminator.side===`source`?typeof n==`string`?this.column(e.source,e.discriminator.field,n):this.value(n[e.discriminator.field]):this.column(e.target,e.discriminator.field,t),this.value(e.discriminator.value))]:[],...e.pairs.map(i=>r.operators.eq(typeof n==`string`?this.column(e.source,i.source,n):this.column(e.target,i.target,t),typeof n==`string`?this.column(e.target,i.target,t):this.fieldValue(e.target,i.target,n[i.source]))));let i=this.alias();return r.operators.in(rowValue(e.targetSide.members.map(n=>this.column(e.target,n.referencedField,t))),r.subqueries.scalar(q(r,{columns:V.join(e.targetSide.members.map(e=>r.identifiers.column(i,e.junctionField)),`, `),from:r.identifiers.table(e.table,i),where:r.operators.and(...this.junctionSideConditions(e.sourceSide,i,n))})))}order(e,t,n){if(t)return this.#me(this.#he(e,t,n))}#me(e){if(e.length===0)return;let t=this.adapter;return V.join(e.map(e=>{let n=e.descending?`desc`:`asc`;return!e.nullable||e.nulls===void 0?t.orderBy[n](e.expression):e.nulls===`first`?t.orderBy.nullsFirst(e.expression,n):t.orderBy.nullsLast(e.expression,n)}),`, `)}#he(e,t,n,r=!1){if(!t)return[];let i=[];for(let a of entries(t))for(let t of Object.keys(a)){let o=a[t];o!==void 0&&i.push(this.#ge(e,t,o,n,r))}return i}#ge(e,t,n,r,i=!1){if(e[`~`].state.relations[t])return this.#_e(e,t,record(n),r);let a=physicalField(this.schema,e,t),o=a.scalar[`~`].state,s=this.#$(e,t,r),c=a.nullable||this.#ee(e,t);if(n!==`asc`&&n!==`desc`){let e=record(n);if(e._distance!==void 0){if(i)throw new N(Xt);let n=record(e._distance),r=o.type===`point`;return this.#ve(this.#ce(s,o,t,n,`orderBy`),n.sort===`desc`,r?`last`:void 0,r,void 0,r?!0:void 0)}return this.#ve(s,e.sort===`desc`,e.nulls,c,t)}return this.#ve(s,n===`desc`,void 0,c,t)}#_e(e,t,n,r){let i=this.adapter,{edges:a}=this.countedMemberships(e,t);if(a.length>1||a[0].many||n._count!==void 0)return this.#ve(this.#Ze(a,void 0,r),n._count===`desc`,void 0,!1);let o=a[0],s=this.alias(),c=this.correlation(o,r,s),[l]=Object.entries(n),u=this.#ge(o.target,l[0],l[1],s),d=q(i,{columns:u.expression,from:this.table(o.target,s),where:c,limit:this.value(1)});return this.#ve(i.subqueries.scalar(d),u.descending,u.nulls,!0)}#ve(e,t,n,r,i,a){return J({expression:e,descending:t,nulls:n??(t?`first`:`last`),expressionNulls:a,nullable:r,field:i})}#ye(e){return e.map(e=>J({...e,descending:!e.descending,nulls:e.nulls===void 0||e.expressionNulls?e.nulls:e.nulls===`first`?`last`:`first`}))}#be(e,t,n,r){let i=t.take!==void 0&&t.take<0,a=t.cursor!==void 0,o=this.#he(e,t.orderBy,n,a),s=this.#xe(e,o,t.cursor,n);if(a&&o.some(e=>e.field===void 0))throw new N(Xt);let c=s??o;return{orderBy:this.#me(i?this.#ye(c):c),distinctOrderBy:i&&t.distinct?.length?this.#me(c):void 0,limit:t.take===void 0?void 0:this.value(Math.abs(t.take)),offset:t.skip===void 0?void 0:this.value(t.skip),cursor:t.cursor===void 0?void 0:this.#we(e,i?this.#ye(s):s,t.cursor,r),distinct:t.distinct?.length?V.join(t.distinct.map(t=>this.#$(e,t,n)),`, `):void 0}}#xe(e,t,n,r){if(U(e).rowKey===void 0&&n===void 0)return[...t];let i=this.#Se(e,t,r,n?Object.keys(this.#Ce(e,n)):[]);for(let e=0;e<i.length;e++){let t=i[e];t.nulls===void 0&&(t.nullable||n!==void 0)&&(i[e]=J({...t,nulls:t.descending?`first`:`last`}))}return i}#Se(e,t,n,r=[]){let i=[...t],a=new Set;for(let e of i)e.field!==void 0&&a.add(e.field);let o=this.keyOrder(e),s=r.length===0?o:[...o,...r];for(let t of s){if(a.has(t))continue;a.add(t);let r=physicalField(this.schema,e,t);i.push(this.#ve(this.#$(e,t,n),!1,`last`,r.nullable||this.#ee(e,t),t))}return i}keyOrder(e){let t=U(e),n=t.addressableKeys.find(e=>e.kind===`primary`&&e.name===void 0);if(n)return n.fields;let r=t.rowKey;if(!r)throw new j(`Paginated scalar ordering requires a primary model identifier.`);let i=new Set(r.fields);return Object.keys(e[`~`].state.scalars).filter(e=>i.has(e))}#Ce(e,t){let n={};for(let[r,i]of Object.entries(t)){let t=qe(e,r);if(t?.name)for(let e of t.fields)n[e]=record(i)[e];else n[r]=i}return n}#we(e,t,n,r){let i=this.adapter,a=this.#Ce(e,n),o=this.alias(),s=r&&this.domainOf(e,r),c=i.operators.and(...s?[this.lowerSelector(s,o)]:[],...Object.entries(a).map(([t,n])=>{if(n===null)throw new j(`Cursor field '${t}' cannot be null. Cursor must point to a specific record.`);return i.operators.eq(this.#$(e,t,o),this.fieldValue(e,t,n))})),l=t[0].descending,u=t.every(e=>!e.nullable&&e.descending===l),cursorRow=t=>q(i,{columns:V.join(t,`, `),from:this.table(e,o),where:c,limit:this.value(1)}),d=t.map(t=>this.#$(e,t.field,o));if(u)return(l?i.operators.lte:i.operators.gte)(rowValue(t.map(e=>e.expression)),i.subqueries.scalar(cursorRow(d)));let f=this.alias(),carrier=e=>`${ht}${e}`,p=cursorRow(d.map((e,t)=>i.identifiers.aliased(e,carrier(t)))),m=t.map((e,t)=>({row:e.expression,cursor:i.identifiers.column(f,carrier(t)),term:e})),h=[],g=[];for(let{row:e,cursor:t,term:n}of m){let r=n.descending?i.operators.lt:i.operators.gt,a=i.operators.and(i.operators.isNotNull(e),r(e,t));g.push(i.operators.and(...h,n.nulls===`first`?i.operators.or(i.operators.and(i.operators.isNull(t),i.operators.isNotNull(e)),i.operators.and(i.operators.isNotNull(t),a)):i.operators.and(i.operators.isNotNull(t),i.operators.or(i.operators.isNull(e),a)))),h.push(i.operators.or(i.operators.and(i.operators.isNull(e),i.operators.isNull(t)),i.operators.and(i.operators.isNotNull(e),i.operators.isNotNull(t),i.operators.eq(e,t))))}return g.push(i.operators.and(...h)),i.operators.exists(q(i,{columns:i.literals.true(),from:i.subqueries.correlate(p,f),where:i.operators.or(...g)}))}select(e,t,n,r={}){let i=this.#_(),a=this.#be(e,t,i,r.purpose),o=r.projection??this.prepareProjection(e,t),s=this.lowerProjection(o,i,r.purpose!==void 0),c=r.selector??(t.where===void 0?void 0:this.prepareSelector(e,t.where,!1,!1)),l=r.purpose===void 0?c:this.#N(e,c,r.purpose),u=l?this.lowerSelector(l,i):void 0,d=this.adapter,f=r.unless&&d.operators.not(d.expressions.coalesce(this.lowerSelector(r.unless,i)??d.literals.true(),d.literals.false()));return{sql:q(this.adapter,{columns:V.join(s,`, `),from:this.table(e,i),where:this.#Te(e,i,n,u,f,a.cursor,r),orderBy:a.orderBy,limit:a.limit,offset:a.offset,forUpdate:r.forUpdate,...a.distinct?{distinct:a.distinct,distinctOrderBy:a.distinctOrderBy,distinctColumnAliases:o.fields.map(e=>e.name)}:{}}),shape:o.shape}}#Te(e,t,n,r,i,a,o){let s=[];return n&&s.push(n.outside?this.outsideWhere(n.edge,n.parent,t):this.memberWhere(n.edge,n.parent,t)),r&&s.push(r),i&&s.push(i),a&&s.push(a),o.identity&&s.push(this.lowerIdentity(e,o.identity,t)),o.condition&&s.push(o.condition),s.length===0?void 0:this.adapter.operators.and(...s)}read(e,t,n){if(!this.#c)return this.#Ee(e,t,n);let r,i=this.#l(()=>(r=this.#Ee(e,t,n),r.query.sql));return{...r,query:{...r.query,sql:i}}}#Ee(e,t,n){switch(t){case`findUnique`:{let t=this.select(e,n,void 0,{selector:n.where===void 0?void 0:this.prepareSelector(e,n.where,!0,!1),purpose:`root`});return{query:t,single:!0,value:t.shape,result:firstRow}}case`findFirst`:{let t=n.take===void 0?1:Math.sign(n.take),r=this.select(e,{...n,take:t},void 0,an);return{query:r,single:!0,value:r.shape,result:firstRow}}case`findMany`:{let t=n.take!==void 0&&n.take<0,r=this.select(e,n,void 0,an);return{query:r,single:!1,value:rowSet(r),result:t?reversedRows:rowIdentity}}default:return this.#De(e,t,n)}}#De(e,t,n){switch(t){case`exist`:{let t=this.adapter,r=this.#_(),i=q(t,{columns:t.literals.true(),from:this.table(e,r),where:this.lowerWhere(e,n.where,r)});return{query:{sql:t.clauses.select(t.identifiers.aliased(t.operators.exists(i),`_count`)),shape:{kind:`object`,fields:{_count:Q}},expectedRows:{count:1,missing:new j(`Provider omitted the required existence result row.`)}},single:!1,value:Q,result:e=>e[0]?._count??!1}}case`count`:{let t=n.select?record(n.select):void 0,r=t?[...t._all?[{name:`_all`}]:[],...Object.keys(t).filter(e=>e!==`_all`&&t[e]).map(e=>({name:e,field:e}))]:[{name:`_count`}],i=r.flatMap(({field:e})=>e===void 0?[]:[e]),a=this.aggregated(e,n,i,t=>r.map(({name:n,field:r})=>[n,this.adapter.aggregates.count(r===void 0?void 0:this.#$(e,r,t))]),()=>({kind:`object`,fields:Object.fromEntries(r.map(({name:e})=>[e,$]))}));return a.expectedRows={count:1,missing:new j(`Provider omitted the required aggregate result row.`)},{query:a,single:t!==void 0,value:t?a.shape:$,result:e=>t?e[0]??{}:e[0]?._count??0}}case`aggregate`:{let t=this.#Oe(e,n),r=this.aggregated(e,n,t.fields,e=>t.columns(e),()=>({kind:`object`,fields:t.fields_}));return{query:r,single:!0,value:r.shape,result:aggregateRow}}case`groupBy`:{let t=this.grouped(e,n);return{query:t,single:!1,value:rowSet(t),result:rowIdentity}}default:return jt(t,`read operation`)}}aggregated(e,t,n,r,i){let a=this.adapter,o=this.#_(),s=this.#be(e,t,o,`root`),c=this.lowerWhere(e,t.where,o),aggregate=(e,t,n)=>({sql:q(a,{columns:V.join(r(e).map(([e,t])=>a.identifiers.aliased(t,e)),`, `),from:t,where:n}),shape:i(e)});if(!((s.limit??s.offset??s.cursor)||this.#te(e)))return aggregate(o,this.table(e,o),c);let l=q(a,{columns:n.length?V.join([...new Set(n)].map(t=>a.identifiers.aliased(this.#$(e,t,o),this.columnName(e,t))),`, `):a.identifiers.aliased(this.value(1),`0viborm_row`),from:this.table(e,o),where:a.operators.and(...c?[c]:[],...s.cursor?[s.cursor]:[]),orderBy:s.orderBy,limit:s.limit,offset:s.offset}),u=this.alias();return this.#ne(()=>aggregate(u,a.subqueries.correlate(l,u)))}#Oe(e,t){let n=this.adapter,r=[],i={},a=[];for(let o of Qt){let s=t[o];if(!s)continue;if(o===`_count`&&s===!0){i._count=$,a.push(()=>[`_count`,n.aggregates.count()]);continue}let c=Object.entries(record(s)).filter(([,e])=>e);if(c.length===0)continue;let l={};for(let[t]of c)t!==`_all`&&r.push(t),l[t]=this.#ke(e,o,t);i[o]={kind:`object`,fields:l},a.push(t=>[o,n.json.objectFromColumns(c.map(([r])=>{let i=l[r],a=r===`_all`?void 0:this.#z(e,r),s=this.#Ae(i);return s?[r,n.json.array(s.sql(this.#Z(a,t)).parts.map(e=>this.#w(i,e)))]:[r,this.#w(i,this.#Me(o,a,t))]}))])}return{fields:r,fields_:i,columns:e=>a.map(t=>t(e))}}#ke(e,t,n){if(t===`_count`)return $;let r=this.scalarShape(e,n);return t===`_avg`&&r.type!==`decimal`?J({kind:`scalar`,type:`number`,nullable:!0}):J({...r,nullable:!0,widened:t===`_sum`?!0:void 0})}#Ae(e){if(!e.widened)return;let{numberSum:t,integerSum:n}=this.adapter.aggregates;return e.type===`number`?{sql:t,join:joinNumberSum}:n&&{sql:n,join:t=>joinIntegerSum(t,e.type)}}#je(e,t){return this.#Ae(this.#ke(e.model,`_sum`,e.field))?.sql(t)}#Me(e,t,n){let r=this.adapter,i=t?this.#Z(t,n):void 0,a=t?.physical.scalar[`~`].state;switch(e){case`_count`:return r.aggregates.count(i);case`_sum`:return this.#je(t,i)?.value??r.aggregates.sum(i);case`_min`:case`_max`:{let n=aggregatedIdentifier(r,this.scalarShape(t.model,t.field).id,i);return e===`_min`?r.aggregates.min(n,a?.type===`boolean`):r.aggregates.max(n,a?.type===`boolean`)}case`_avg`:return a?.type===`decimal`&&a.decimal?r.aggregates.decimalAvg(i,a.decimal):r.aggregates.avg(i)}}selectSeries(e,t,n=`createMany`){let r=e.model,i=this.#_(),a=this.lowerProjection(e,i),o=t.map(e=>this.lowerIdentity(r,e,i));return{sql:q(this.adapter,{columns:V.join(a,`, `),from:this.table(r,i),where:balancedOr(o,e=>this.adapter.operators.or(...e)),orderBy:this.adapter.expressions.caseWhen(o.map((e,t)=>({when:e,then:this.value(t)})),this.value(t.length))}),shape:e.shape,expectedRows:{count:t.length,missing:n===`createMany`?new j(`createMany with 'select' could not read back one of the created rows at the primary key it reported. A later row in the same call moved that row's primary key; use the '{ count }' form, or write those rows in separate calls.`):new L(`updateMany with 'select' could not read back one of the updated rows at its final primary key.`,{meta:{model:r[`~`].names.ts??`unknown`,operation:`updateMany`}})}}}#Ne(e,t,n,r,i){let a=this.#Ve(e,n);a.length!==0&&(r[t]=J({kind:`object`,nullable:!1,fields:J(Object.fromEntries(a.map(e=>[e.relation,$])))}),i.push(J({kind:`counts`,name:t,counts:a})))}#Pe(e,t,n,r,i,a){if(r)throw new j(xt);a.push(J({kind:`distance`,name:Zt,field:t,specification:record(n)})),i[Zt]=this.#ze(e,t,record(n))}#Fe(e,t,n,r,i,a,o){let s=n.edge,c=s.kind===`variantJunctionCarrier`,l={},u={},d=[],f=c?s.members.map(n=>({variant:n.variant,edge:bindMembership(this.schema,e,t,n.variant)})):[];for(let n of s.members){let i=yt(r,c,n.variant);if(i===void 0)continue;let a=this.#Be(bindMembership(this.schema,e,t,n.variant),i,`${o}${c?`variants.`:``}${n.variant}.`);c?l[n.variant]=this.#Re(a):u[n.variant]=this.#Le(a),d.push(J({variant:n.variant,...a}))}i[t]=J(c?{kind:`variants`,relation:t,many:c,arms:J(l)}:{kind:`variants`,relation:t,many:c,arms:J(u)}),a.push(J({kind:`variants`,name:t,many:c,arms:J(d),memberships:J(f)}))}prepareProjection(e,t,n=!1,r=``){let i=n?void 0:this.domain?.projected(e),a=t.select===void 0&&t.include===void 0,o=i===void 0?this.#t.defaultProjections:this.domain.defaultProjections;if(a){let t=o.get(e);if(t!==void 0)return t}let s=i&&t.select!==void 0?pn.get(t.select):void 0,c=i&&{},l=i&&new Map,u=t.select??defaultSelection(e);t.include!==void 0&&(u={...u,...t.include});let d=[],f={},p=!1;for(let n of Object.keys(u)){let a=u[n];if(!a)continue;if(n===`_count`){this.#Ne(e,n,a,f,d);continue}if(!e[`~`].state.relations[n]){let t=a===!0?void 0:record(a)._distance;if(t!==void 0){this.#Pe(e,n,t,p,f,d),p=!0;continue}}let o=i?.keys.get(n);if(o!==void 0){this.#Ie(o,n,a,f,d);continue}if(!e[`~`].state.relations[n]){d.push(J({kind:`scalar`,name:n})),f[n]=this.scalarShape(e,n);let t=i?.gates.get(n);if(t===void 0)continue;let a=l.get(t);a===void 0&&(a=gt(l.size),l.set(t,a),d.push(J({kind:`gate`,name:a,gate:t}))),c[n]=s?.has(n)?J({gate:a,refused:`${r}select.${n}`}):J({gate:a});continue}let m=this.schema.index.get(e).get(n);if(!m.member&&(m.edge.kind===`variantRowCarrier`||m.edge.kind===`variantJunctionCarrier`)){this.#Fe(e,n,m,a,f,d,`${r}${t.include?.[n]===void 0?`select`:`include`}.${n}.`);continue}let h=this.#Be(bindMembership(this.schema,e,n),a,`${r}${t.include?.[n]===void 0?`select`:`include`}.${n}.`);f[n]=this.#Le(h),d.push(J({kind:`relation`,name:n,...h}))}d.length===0&&d.push(J({kind:`sentinel`,name:_t}));let m=J({model:e,fields:J(d),shape:J(l?.size?{kind:`object`,fields:J(f),gated:J(c),gates:J([...l.values()])}:{kind:`object`,fields:J(f)})});return a&&o.set(e,m),m}#Ie(e,t,n,r,i){let a=n===!0?e.names:e.names.filter(([e])=>n.includes(e));r[t]=e.ordered?J({kind:`scalar`,type:`enum`,nullable:!0,enumValues:new Set(a.map(([e])=>e))}):J({kind:`object`,nullable:!1,fields:J(Object.fromEntries(a.map(([e])=>[e,Q])))}),i.push(J({kind:`evidence`,name:t,evidence:e,names:a}))}#Le(e){if(e.recurrence){let t=this.schema.index.get(e.edge.source).get(e.edge.name);return J({kind:`recursive`,relation:e.edge.name,many:e.edge.many,optional:$e(t),recurrence:e.recurrence,row:e.projection.shape,identity:J(this.schema.keys(e.edge.target).map(t=>this.scalarShape(e.edge.target,t)))})}return e.edge.many?this.#Re(e):e.projection.shape}#Re(e){let t=e.arguments.take;return J({kind:`collection`,reversed:t!==void 0&&t<0?!0:void 0,row:e.projection.shape})}#ze(e,t,n){let r=physicalField(this.schema,e,t);return J({kind:`scalar`,type:`number`,nullable:r.nullable||r.scalar[`~`].state.type===`vector`&&n.metric===`cosine`})}#Be(e,t,n=``){let r=t===!0?{}:record(t);return J({edge:e,arguments:J({selector:r.where?this.prepareSelector(e.target,r.where,!1,!1):void 0,orderBy:r.orderBy,take:r.take,skip:r.skip,cursor:r.cursor,distinct:r.distinct}),projection:this.prepareProjection(e.target,r,!1,n),recurrence:r.recurse})}#Ve(e,t){let n=record(record(t).select),r=[];for(let[t,i]of Object.entries(n)){if(!i)continue;let{edges:n,variants:a}=this.countedMemberships(e,t),o=i===!0?void 0:record(i).where;if(o===void 0){r.push(J({relation:t,edges:n}));continue}let s=record(o);if(!a){r.push(J({relation:t,edges:n,selector:this.prepareSelector(n[0].target,s,!1,!1)}));continue}let c=s.type,l=n.find(e=>e.scope.member?.variant===c);if(!l)throw new j(`Unknown polymorphic target '${String(c)}' for relation '${t}'.`);let u=s.isNot!==void 0,d=u?s.isNot:s.is;r.push(J({relation:t,edges:J([l]),selector:d===void 0?void 0:this.prepareSelector(l.target,record(d),!1,!1),...u?{negated:!0}:{}}))}return J(r)}countedMemberships(e,t){let n=this.schema.index.get(e).get(t),r=n.member===void 0&&(n.edge.kind===`variantRowCarrier`||n.edge.kind===`variantJunctionCarrier`)?n.edge:void 0;return J({edges:J(r?r.members.map(n=>bindMembership(this.schema,e,t,n.variant)):[bindMembership(this.schema,e,t)]),variants:r!==void 0})}lowerProjection(e,t,n=!1){let r=[];for(let i of e.fields)r.push(this.adapter.identifiers.aliased(this.#Ue(e,i,t,n),i.name));return r}#He(e,t,n){let r=this.adapter,i;if(t.kind===`counts`)i=r.json.objectFromColumns(t.counts.map(e=>[e.relation,this.#Ze(e.edges,e.selector,n??``,e.negated)]));else if(t.kind===`distance`)i=this.#ce(this.column(e.model,t.field,n),physicalField(this.schema,e.model,t.field).scalar[`~`].state,t.field,t.specification,`select`);else{let a=t.memberships.length===0?[]:[[bt,r.json.document(r.json.objectFromColumns(t.memberships.map(e=>[e.variant,this.#Xe(e.edge,n??``)])))]],o=this.schema.index.get(e.model).get(t.name);if(o.edge.kind===`variantRowCarrier`){let t=o.edge,i=this.column(e.model,t.storage.typeColumn.name,n),s=this.column(e.model,t.storage.idColumn.name,n),c=$e(o)?r.operators.and(r.operators.isNull(i),r.operators.isNull(s)):r.literals.false(),l=r.operators.and(r.operators.isNotNull(s),r.operators.or(...t.members.map(e=>r.operators.eq(i,this.value(e.entry.storedValue))))),u=r.expressions.caseWhen([{when:r.operators.or(c,l),then:this.value(0)}],this.value(1));a.push([bt,r.json.document(r.json.objectFromColumns([[`$storage`,u]]))])}i=r.json.object([...t.arms.map(e=>{let i=this.#Qe(e,n??``),a=t.many?void 0:this.#de(e.edge,n??``);return[e.variant,r.json.document(a?r.expressions.caseWhen([{when:a,then:r.expressions.coalesce(i,this.#Je(e.edge,n??``))}],r.literals.null()):i)]}),...a])}return i}#Ue(e,t,n,r=!1){let i=this.adapter,a;return a=t.kind===`scalar`?this.projectedColumn(e.model,t.name,n):t.kind===`sentinel`?i.expressions.cast(i.literals.value(1),`integer`):t.kind===`evidence`?this.#qe(e.model,t,n,r):t.kind===`gate`?this.#Ke(this.#Ge(e.model,t.gate,n,r)):t.kind===`relation`?this.#Ye(t.edge,n??``,t.recurrence?this.#st(t,t.recurrence,n??``):this.#Qe(t,n??``)):this.#He(e,t,n),a}#We(e,t,n,r){return this.lowerSelector(this.domain.layered(e,t,n),r)}#Ge(e,t,n,r){let i=[];for(let[a,o,s]of t){let t=s===o?[o]:[o,s];for(let o of r?t.slice(1):t){let t=this.#We(e,a,o,n);t!==void 0&&i.push(t)}}return i.length===0?void 0:this.adapter.operators.and(...i)}#Ke(e){let t=this.adapter;return e===void 0?t.literals.true():t.expressions.caseWhen([{when:e,then:t.literals.true()}],t.literals.false())}#qe(e,t,n,r){let i=this.adapter,{layer:a,read:o,ordered:s}=t.evidence,c=r?void 0:this.#We(e,a,o,n),test=t=>t===o?void 0:this.#We(e,a,t,n);if(s){let e=i.expressions.caseWhen([...t.names].reverse().map(([e,t])=>({when:test(t)??i.literals.true(),then:i.expressions.cast(this.value(e),`text`)})),i.literals.null());return c===void 0?e:i.expressions.caseWhen([{when:c,then:e}],i.literals.null())}let l=i.json.objectFromColumns(t.names.map(([e,t])=>[e,this.#Ke(test(t))]));return c===void 0?l:i.expressions.caseWhen([{when:c,then:l}],i.json.objectFromColumns(t.names.map(([e])=>[e,i.literals.false()])))}#Je(e,t){let n=this.adapter;if(this.domainOf(e.target,`related`)===void 0)return n.json.object([]);let r=this.alias();return n.expressions.caseWhen([{when:n.operators.exists(n.subqueries.existsCheck(this.table(e.target,r),this.correlation(e,t,r,!1))),then:n.literals.null()}],n.json.object([]))}#Ye(e,t,n){if(e.kind!==`junction`||e.many||e.scope.edge.kind!==`variantJunctionCarrier`)return n;let r=this.adapter,i=this.alias(),a=r.subqueries.scalar(q(r,{columns:r.aggregates.count(),from:r.identifiers.table(e.table,i),where:r.operators.and(...this.junctionSideConditions(e.sourceSide,i,t))}));return r.expressions.caseWhen([{when:r.operators.gt(a,this.value(1)),then:r.json.emptyArray()}],n)}#Xe(e,t){let n=this.adapter,r=this.alias(),i=this.alias();return n.subqueries.scalar(q(n,{columns:n.aggregates.count(),from:n.identifiers.table(e.table,r),where:n.operators.and(...this.junctionSideConditions(e.sourceSide,r,t),n.filters.none(n.subqueries.existsCheck(this.table(e.target,i),n.operators.and(...this.junctionSideConditions(e.targetSide,r,i)))))}))}#Ze(e,t,n,r=!1){let i=this.adapter;return e.map(e=>{let a=this.alias(),o=t?this.lowerSelector(t,a):void 0;return i.expressions.coalesce(i.subqueries.scalar(q(i,{columns:i.aggregates.count(),from:this.table(e.target,a),where:i.operators.and(this.correlation(e,n,a),...o?[r?i.operators.not(o):o]:[])})),this.value(0))}).reduce((e,t)=>i.expressions.add(e,t))}scalarQuery(e,t,n){return{shape:{kind:`object`,fields:{[t]:this.scalarShape(e,t)}},sql:this.adapter.clauses.select(this.adapter.identifiers.aliased(this.fieldValue(e,t,n),t))}}#Qe(e,t){let n=this.adapter,{edge:r,arguments:i,projection:a}=e,o=this.alias(),s=this.lowerProjection(a,o,!0),c=Object.keys(a.shape.fields),l=this.#be(r.target,i,o,`related`),u=this.#rt(r,t,o),d=q(n,{columns:V.join(s,`, `),from:u.from,joins:u.joins,where:n.operators.and(u.where,...i.selector?[this.lowerSelector(i.selector,o)]:[],...l.cursor?[l.cursor]:[]),orderBy:l.orderBy,limit:r.many?l.limit??(l.orderBy?n.noLimitValue:void 0):this.value(1),offset:l.offset,...l.distinct?{distinct:l.distinct,distinctOrderBy:l.distinctOrderBy,distinctColumnAliases:a.fields.map(e=>e.name)}:{}}),f=this.alias(),p=c.map(e=>[e,this.#w(a.shape.fields[e],n.identifiers.column(f,e))]);for(let e of a.shape.gates??fn)p.push([e,n.identifiers.column(f,e)]);let m=n.json.object(p);return n.subqueries.scalar(q(n,{columns:r.many?n.expressions.coalesce(n.json.agg(m),n.json.emptyArray()):m,from:n.subqueries.correlate(d,f)}))}#$e(e,t){return this.adapter.json.array(this.schema.keys(e).map((n,r)=>{let i=this.scalarShape(e,n);return this.#w(i,transportedIdentifier(this.adapter,i.id,t[r],i.nullable))}))}#et(e,t){return this.schema.keys(e).map(n=>this.column(e,n,t))}#tt(e,t,n){let r=this.adapter;return r.operators.and(...this.#et(e,t).map((e,t)=>r.operators.eq(e,n[t])))}#nt(e,t,n,r=!0){let i=this.adapter;if(e.kind!==`junction`)return i.joins.inner(this.table(e.target,n),this.correlation(e,t,n,r));let a=this.alias();return V`${i.joins.inner(i.identifiers.table(e.table,a),i.operators.and(...this.junctionSideConditions(e.sourceSide,a,t)))} ${this.#it(e,a,n)}`}#rt(e,t,n){if(e.kind!==`junction`)return{from:this.table(e.target,n),where:this.correlation(e,t,n)};let r=this.alias();return{from:this.adapter.identifiers.table(e.table,r),joins:[this.#it(e,r,n)],where:this.adapter.operators.and(...this.junctionSideConditions(e.sourceSide,r,t))}}#it(e,t,n){let r=this.adapter;return r.joins.inner(this.table(e.target,n),this.#fe(e,n,r.operators.and(...this.junctionSideConditions(e.targetSide,t,n))))}#at(e,t,n,r=!0){let i=this.adapter,a=e.target,o=this.schema.keys(a),s=this.alias(),c=`__${s}_recursive`,{depth:l}=n,u=`edges`in n,d=u?o.map((e,t)=>`__${s}_parent_${t}`):[],f=o.map((e,t)=>`__${s}_child_${t}`),p=`__${s}_depth`,m=u?n.selector:void 0,hop=e=>l===!1?[]:[i.identifiers.aliased(e,p)],reached=e=>m?[this.lowerSelector(m,e)]:[],h=this.alias(),g=q(i,{columns:V.join([...this.#ot(d,this.#et(a,t)),...this.#ot(f,this.#et(a,h)),...hop(i.expressions.cast(this.value(1),`integer`))],`, `),from:this.table(a,h),where:i.operators.and(this.correlation(e,t,h,r),...reached(h))}),_=!u&&n.self?this.alias():void 0,v=_?q(i,{columns:V.join([...f,...l===!1?[]:[p]].map(e=>i.identifiers.column(_,e)),`, `),from:i.subqueries.correlate(i.setOperations.union(i.clauses.select(V.join([...this.#ot(f,this.#et(a,t)),...hop(i.expressions.cast(this.value(0),`integer`))],`, `)),g),_)}):g,y=this.alias(),b=this.alias(),x=this.alias(),carried=e=>i.identifiers.column(y,e),S=q(i,{columns:V.join([...this.#ot(d,f.map(carried)),...this.#ot(f,this.#et(a,x)),...hop(i.expressions.add(carried(p),this.value(1)))],`, `),from:V`${i.identifiers.aliased(i.identifiers.escape(c),y)} ${i.joins.inner(this.table(a,b),this.#tt(a,b,f.map(carried)))} ${this.#nt(e,b,x,r)}`,where:i.operators.and(...l===!1?[]:[i.operators.lt(carried(p),this.value(l))],...reached(x))});return{cte:i.cte.recursive(c,v,S,`distinct`),cteName:c,scope:s,walk:y,parentColumns:d,childColumns:f,depthColumn:p}}#ot(e,t){return e.map((e,n)=>this.adapter.identifiers.aliased(t[n],e))}#st(e,t,n){let r=this.adapter,i=e.edge.target,{cte:a,cteName:o,scope:s,walk:c,parentColumns:l,childColumns:u,depthColumn:d}=this.#at(e.edge,n,{depth:t.depth,edges:!0,selector:e.arguments.selector}),walkColumn=e=>r.identifiers.column(c,e),f=this.alias(),p=u.map((e,t)=>`__${s}_id_${t}`),m=q(r,{distinct:V.join(u.map(walkColumn),`, `),distinctColumnAliases:p,columns:V.join(this.#ot(p,u.map(walkColumn)),`, `),from:r.identifiers.aliased(r.identifiers.escape(o),c)}),h=this.alias(),g=r.json.object(e.projection.fields.map(t=>[t.name,this.#w(e.projection.shape.fields[t.name]??Q,this.#Ue(e.projection,t,h,!0))])),_=r.json.object([[Z.key,this.#$e(i,this.#et(i,h))],[Z.row,g]]),v=r.subqueries.scalar(q(r,{columns:r.json.agg(_),from:V`${r.subqueries.correlate(m,f)} ${r.joins.inner(this.table(i,h),this.#tt(i,h,p.map(e=>r.identifiers.column(f,e))))}`})),y=this.alias(),b=this.alias(),edgeColumn=e=>r.identifiers.column(y,e),x=`__${s}_edge`,S=[[Z.parent,this.#$e(i,l.map(edgeColumn))],[Z.child,this.#$e(i,u.map(edgeColumn))]];t.depth!==!1&&S.push([Z.depth,edgeColumn(d)]);let ee=r.json.object(S),C=this.#me(this.#Se(i,this.#he(i,e.arguments.orderBy,b),b)),te=q(r,{columns:r.identifiers.aliased(ee,x),from:V`${r.identifiers.aliased(r.identifiers.escape(o),y)} ${r.joins.inner(this.table(i,b),this.#tt(i,b,u.map(edgeColumn)))}`,orderBy:V.join([...l.map(e=>r.orderBy.asc(edgeColumn(e))),...C?[C]:[]],`, `),limit:r.noLimitValue}),w=this.alias(),T=r.subqueries.scalar(q(r,{columns:r.json.agg(r.json.document(r.identifiers.column(w,x))),from:r.subqueries.correlate(te,w)})),carrier=(e,t)=>r.json.object([[Z.root,this.#$e(i,this.#et(i,n))],[Z.nodes,r.json.document(e)],[Z.edges,r.json.document(t)]]);if(!r.capabilities.supportsLateralJoins)return r.subqueries.scalar(V`${a} ${r.clauses.select(carrier(v,T))}`);let ne=this.alias(),E=this.alias(),D=`__${s}_nodes`,O=`__${s}_edges`;return r.subqueries.scalar(q(r,{columns:carrier(r.identifiers.column(E,D),r.identifiers.column(E,O)),from:r.subqueries.correlate(r.clauses.select(V`1`),ne),joins:[r.joins.lateral(V`${a} ${r.clauses.select(V.join([r.identifiers.aliased(v,D),r.identifiers.aliased(T,O)],`, `))}`,E)]}))}grouped(e,t){let n=this.adapter,r=this.#_(),i=t.by,a=new Set(i);if(this.#te(e)){let o=this.alias(),s=q(n,{columns:V.join(this.schema.storedFields(e).map(t=>n.identifiers.aliased(this.#$(e,t,o),this.columnName(e,t))),`, `),from:this.table(e,o),where:this.lowerWhere(e,t.where,o)});return this.#ne(()=>this.#ct(e,t,r,i,a,{from:n.subqueries.correlate(s,r)}))}return this.#ct(e,t,r,i,a,{from:this.table(e,r),where:this.lowerWhere(e,t.where,r)})}#ct(e,t,n,r,i,a){let o=this.adapter,s=this.#Oe(e,t),c={},l=this.#o?this.domain?.projected(e)?.gates:void 0,u=r.map(t=>{let r=this.scalarShape(e,t);return c[t]=l?.has(t)?J({...r,nullable:!0}):r,o.identifiers.aliased(this.projectedColumn(e,t,n),t)});for(let[e,t]of s.columns(n))c[e]=s.fields_[e],u.push(o.identifiers.aliased(t,e));return{sql:q(o,{columns:V.join(u,`, `),from:a.from,where:a.where,groupBy:V.join(r.map(t=>this.column(e,t,n)),`, `),having:t.having?this.#J(this.#lt(e,record(t.having)),n):void 0,orderBy:this.#me(this.#ut(e,t.orderBy,n,i)),limit:t.take===void 0?void 0:this.value(t.take),offset:t.skip===void 0?void 0:this.value(t.skip)}),shape:{kind:`object`,fields:c}}}#lt(e,t){return J({kind:`and`,predicates:J(Object.entries(t).flatMap(([t,n])=>{if(n===void 0)return[];if(this.combinator(e,t))return[this.combine(t,entries(n).map(t=>this.#lt(e,record(t))))];let r=this.#z(e,t),i=record(n),a=Qt.filter(e=>i[e]!==void 0);return a.length===0?[this.#V(J({kind:`column`,scalar:r}),n)]:a.map(e=>this.#V(J({kind:`aggregate`,aggregate:e,scalar:r}),i[e]))}))})}#ut(e,t,n,r){let i=entries(t??{}).flatMap(t=>Object.entries(t).flatMap(([t,r])=>r===void 0?[]:isAggregate(t)?Object.entries(record(r)).flatMap(([r,i])=>{let a=r===`_all`?void 0:this.#z(e,r),o=t===`_sum`&&this.#je(a,this.#Z(a,n));return(o?o.order:[this.#Me(t,a,n)]).map(e=>this.#ve(e,i===`desc`,void 0,!1))}):[this.#ge(e,t,r,n)])),a=new Set(i.map(e=>e.field));for(let t of r)a.has(t)||i.push(this.#ge(e,t,`asc`,n));return i}assertExpectedRows(e,t){if(e.expectedRows&&t<e.expectedRows.count)throw e.expectedRows.missing;if(e.expectedRows&&t>e.expectedRows.count)throw new j(`createMany returned a different number of rows than expected.`)}decodeQuery(e,t,n=!1){return this.assertExpectedRows(e,t.length),this.decodeProjection(e.shape,t,n)}decodeProjection(e,t,n=!1,r){if(t.length===0)return[];let i=this.compileReader(e,n,!1,r);return t.map(e=>record(i(e)))}decodeRecursiveCarrier(e,t,n,r){let i=providerDocument(providerJson(t));if(!i)throw new InvalidScalarResult(`recursive carrier`,`the carrier is not an object`);let a=own(i,Z.root),o=own(i,Z.nodes),s=own(i,Z.edges);if(!(Array.isArray(a)&&Array.isArray(o)&&Array.isArray(s)))throw new InvalidScalarResult(`recursive carrier`,`the carrier's root, nodes or edges member is not an array`);let identity=t=>{if(!Array.isArray(t)||t.length!==e.identity.length)throw new InvalidScalarResult(`recursive identity`,`an identity is not a tuple of the key's width`);let n=0;for(let e of r)e(t[n]),n+=1;return JSON.stringify(t)},c=identity(a),l=new Map;for(let e of o){let t=providerDocument(e);if(!t)throw new InvalidScalarResult(`recursive node`,`a node entry is not an object`);let n=identity(own(t,Z.key));if(l.has(n))throw new InvalidScalarResult(`duplicate recursive node`,`two nodes carry the same identity`);l.set(n,own(t,Z.row))}let u=new Map,d=new Set;for(let t of s){let n=providerDocument(t);if(!n)throw new InvalidScalarResult(`recursive edge`,`an edge entry is not an object`);let r=identity(own(n,Z.parent)),i=identity(own(n,Z.child));if(!l.has(i))throw new InvalidScalarResult(`recursive edge endpoint`,`an edge's child is not a carried node`);let a=own(n,Z.depth),o;if(e.recurrence.depth===!1){if(a!==void 0)throw new InvalidScalarResult(`exhaustive recursive depth`,`an exhaustive carrier states an edge depth`)}else{if(typeof a!=`number`||!Number.isSafeInteger(a)||a<1||a>e.recurrence.depth)throw new InvalidScalarResult(`recursive depth`,`an edge depth is not an integer from 1 to the cutoff`);o=a}let s=JSON.stringify([r,i,o??null]);if(d.has(s))throw new InvalidScalarResult(`duplicate recursive edge`,`an edge fact is carried twice`);d.add(s);let c=u.get(r),f=J({child:i,...o===void 0?{}:{depth:o}});c?c.push(f):u.set(r,[f])}let f=new Map;for(let[t,n]of u){if(t!==c&&!l.has(t))throw new InvalidScalarResult(`recursive edge endpoint`,`an edge's parent is neither the root nor a carried node`);let r=[...new Set(n.map(e=>e.child))];if(!e.many&&r.length>1)throw new InvalidScalarResult(`recursive singular relation`,`a singular parent has several successors`);f.set(t,r)}let p=new Set,m=new Set,h=new Set,g=[[c,0]];for(let[t,n]of g){let r=new Set;for(let e of u.get(t)??[]){if(e.depth!==void 0&&e.depth!==n+1)continue;p.add(e),m.add(e.child),r.add(e.child);let t=e.depth===void 0?e.child:`${e.depth} ${e.child}`;h.has(t)||(h.add(t),g.push([e.child,n+1]))}if(e.recurrence.depth!==!1&&Qe(e.recurrence.depth,n)&&r.size!==(f.get(t)?.length??0))throw new InvalidScalarResult(`recursive depth`,`a hop below the cutoff omits some of its parent's children`)}if(e.recurrence.depth!==!1&&p.size!==d.size)throw new InvalidScalarResult(`recursive depth`,`an edge is not reachable at its recorded depth`);if(m.size!==l.size)throw new InvalidScalarResult(`unreachable recursive node`,`a carried node is not reachable from the root`);let cutoff=t=>!Qe(e.recurrence.depth,t),collapse=t=>t.length>0?e.many?t:t[0]:e.many?[]:null,_=new Set([c]),v=[],y=0,b=e.recurrence.maxOccurrences??et,follow=(t,r)=>{if(_.has(r)){if(e.recurrence.cycles===`reject`)throw new N(`Recursive relation '${e.relation}' contains a cycle.`,{meta:{relation:e.relation,feature:`cyclic recursive traversal`}});if(e.recurrence.cycles===`prevent`)return}if(++y>b)throw new RecursiveOutputOverBudget(e.relation,b);_.add(r);let i=n(l.get(r));if(i===null)throw new InvalidScalarResult(`recursive row`,`a node's row is null`);let a=t+1;v.push({key:r,depth:a,row:record(i),childKeys:cutoff(a)?[]:f.get(r)??[],childRows:[],next:0})},x=[];for(let t of f.get(c)??[]){follow(0,t);for(let t=v.at(-1);t!==void 0;t=v.at(-1)){if(t.next<t.childKeys.length){follow(t.depth,t.childKeys[t.next++]);continue}_.delete(t.key),v.pop(),cutoff(t.depth)||(t.row[e.relation]=collapse(t.childRows));let n=v.at(-1);n?n.childRows.push(t.row):x.push(t.row)}}return collapse(x)}compileReader(e,t,n,r){if(e.kind===`scalar`){let r=n?void 0:this.fieldReader(e.type),i=e.list?this.compileList(e,t):void 0;return this.compileScalar(e,t,r,i)}if(e.kind===`recursive`){let n=this.compileReader(e.row,t,!0),r=e.identity.map(e=>this.compileReader(e,!0,!0));return t=>this.decodeRecursiveCarrier(e,t,n,r)}if(e.kind===`variants`){let slot=t=>{let n=providerDocument(providerJson(t));if(!n)throw new InvalidScalarResult(`polymorphic slot`,`the slot is not an object`);let r=own(n,bt);if(r===void 0)return n;let i=providerDocument(r);if(!i)throw new InvalidScalarResult(`polymorphic slot`,`the integrity entry is not an object`);for(let[t,n]of Object.entries(i))if(Number(n)>0)throw t===`$storage`?new j(`Polymorphic relation '${e.relation}' has an unknown discriminator or incomplete stored pair.`):new j(`Polymorphic relation '${e.relation}' references a missing '${t}' record.`);return n};if(e.many){let n=Object.keys(e.arms).map(n=>({type:n,read:this.#ft(e.arms[n],t)}));return e=>{let t=slot(e),r=[];for(let{type:e,read:i}of n)for(let n of i(own(t,e)))r.push({type:e,data:n});return r}}let n=Object.keys(e.arms).map(n=>{let r=e.arms[n];return{type:n,arm:r,read:this.compileReader(r,t,!0)}});return t=>{let r=slot(t);for(let{type:t,arm:i,read:a}of n){let n=own(r,t);if(orphanedArm(n,i))throw new j(`Polymorphic relation '${e.relation}' references a missing '${t}' record.`);let o=a(n);if(o!==null)return{type:t,data:o}}return null}}if(e.kind===`collection`)return this.#ft(e,t);let i=Object.keys(e.fields),a=i.map(r=>{let i=e.fields[r];return this.compileReader(i,t,n||i.kind!==`scalar`)});if(e.gates!==void 0&&!t)return this.#dt(e,i,a,n,r);if(r){let e=i.map(e=>r.lastIndexOf(e));return t=>{if(!Array.isArray(t))throw new InvalidScalarResult(`row`,`a positional row is not an array`);let n={};for(let r=0;r<i.length;r++){let o=e[r];n[i[r]]=a[r](o<0?void 0:t[o])}return n}}return t=>{let n=providerDocument(providerJson(t));if(n===null){if(e.nullable===!1)throw new InvalidScalarResult(`row`,`a document the statement always builds is null`);return null}if(n===void 0)throw new InvalidScalarResult(`row`,`a requested document is not a provider row`);let r={};for(let e=0;e<i.length;e++){let t=i[e],o=a[e](own(n,t));t===`__proto__`?Object.defineProperty(r,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):r[t]=o}return r}}#dt(e,t,n,r,i){let a=e.gates,o=this.compileReader(Q,!1,r),s=t.map(t=>e.gated[t]),c=s.map(e=>e===void 0?-1:a.indexOf(e.gate)),l=i&&[...t.map(e=>i.lastIndexOf(e)),...a.map(e=>i.lastIndexOf(e))],cell=(e,t,n)=>{if(l===void 0)return own(e,n);let r=l[t];return r<0?void 0:e[r]};return r=>{let i=r;if(l){if(!Array.isArray(r))throw new InvalidScalarResult(`row`,`a positional row is not an array`)}else{if(i=providerDocument(providerJson(r)),i===null){if(e.nullable===!1)throw new InvalidScalarResult(`row`,`a document the statement always builds is null`);return null}if(i===void 0)throw new InvalidScalarResult(`row`,`a requested document is not a provider row`)}let u=a.map((e,n)=>o(cell(i,t.length+n,e))),d={};for(let e=0;e<t.length;e++){let r=t[e],a=c[e];if(a>=0&&u[a]!==!0){let t=s[e].refused;if(t!==void 0)throw new GatedFieldRefusal(t);continue}d[r]=n[e](cell(i,e,r))}return d}}#ft(e,t){let n=this.compileReader(e.row,t,!0);return t=>{let r=providerJson(t);if(!Array.isArray(r))throw new InvalidScalarResult(`collection`,`a requested relation is not a provider array`);let i=r.map(n);return e.reversed?i.reverse():i}}compileScalar(e,t,n,r){let i=r??this.#pt(e,t),a=e.nullable,o=e.type===`json`&&e.list!==!0,read=t=>{if(t===null){if(a)return null;if(!o)throw new InvalidScalarResult(e.type,e.list?`a required list is null`:`a required scalar is null`)}if(t===void 0)throw new InvalidScalarResult(e.type,`the value is absent`);return i(n===void 0?t:n(t))},s=this.#Ae(e)?.join;return s?e=>read(s(e)):read}#pt(e,t){let n=e.id;if(n!==void 0)return r=>{let i=decodeIdentifier(n,r);if(i===void 0)throw new InvalidScalarResult(e.type,`the value is not in this column's declared identifier domain`);return t&&n.representation===`text`?r:i};switch(e.type){case`string`:return decodeString;case`boolean`:return decodeBoolean;case`int`:return e.widened?e=>decodeInt(e,!0):decodeInt;case`bigint`:return decodeBigint;case`number`:return e.widened?e=>e:decodeNumber;case`decimal`:return n=>{let r=decodeDecimalScalar(n,e.decimal,e.widened===!0,t,this.adapter.result);if(r===void 0)throw new InvalidScalarResult(e.type,e.widened?`the sum is not an exact decimal at this column's scale`:`the value is not an exact decimal in this column's declared domain`);return r};case`datetime`:return n=>{if(e.dateTime!==void 0&&e.dateTime!==`text`){let t=At(n,e.dateTime);if(t===void 0)throw new InvalidScalarResult(e.type,`the value is not this column's declared physical timestamp`);return t}if(n instanceof Date){if(Pe(n.getTime()))return new Date(n.getTime());throw new InvalidScalarResult(e.type,`the Date is outside the public DateTime domain`)}let r=typeof n==`string`?kt(n):void 0;if(!r)throw new InvalidScalarResult(e.type,`the value is not a valid provider timestamp in the public DateTime domain`);return t?n:r};case`date`:return t=>{if(t instanceof Date){let n=t.getTime();if(Pe(n)&&t.getUTCHours()===0&&t.getUTCMinutes()===0&&t.getUTCSeconds()===0&&t.getUTCMilliseconds()===0)return new Date(n);throw new InvalidScalarResult(e.type,`the Date is invalid or not UTC midnight`)}let n=typeof t==`string`?_n.exec(t):null,r=n?kt(`${n[1]}-${n[2]}-${n[3]}T00:00:00.000Z${n[4]?` BC`:``}`):void 0;if(!r)throw new InvalidScalarResult(e.type,`the value is not a valid ISO calendar date`);return r};case`time`:return decodeTime;case`enum`:return t=>{if(typeof t==`string`&&e.enumValues?.has(t)===!0)return t;throw new InvalidScalarResult(e.type,`the value is not a declared enum member`)};case`json`:return e=>this.jsonValue(e);case`blob`:return decodeBlob;case`vector`:return t=>{let n=providerJson(t);if(!Array.isArray(n)||n.some(e=>typeof e!=`number`||!Number.isFinite(e)))throw new InvalidScalarResult(e.type,`the value is not an array of finite numbers`);if(e.dimension!==void 0&&n.length!==e.dimension)throw new InvalidScalarResult(e.type,`the value does not have the configured dimension ${e.dimension}`);return[...n]};case`point`:return t=>{let n=ze(providerJson(t));if(n.issues)throw new InvalidScalarResult(e.type,n.issues[0]?.message??`the value is not a canonical GeoPoint`);return n.value};default:return()=>{throw new InvalidScalarResult(e.type,`the scalar type is unsupported`)}}}compileList(e,t){if(e.type===`decimal`)return n=>{let r=decodeDecimalList(n,e.decimal,t,this.adapter.result);if(r===void 0)throw new InvalidScalarResult(e.type,`the value is not an exact decimal list in this column's declared domain`);return r};let n=J({...e,list:void 0,nullable:!1}),r=this.compileScalar(n,t),i=this.adapter.result.enumListRepresentation===`arrayText`;return t=>{let n=typeof t==`string`?i&&t.startsWith(`{`)?providerArrayMembers(t):JSON.parse(t):t;if(!Array.isArray(n))throw new InvalidScalarResult(e.type,`a list scalar did not return an array`);return n.map((t,i)=>{if(!Object.hasOwn(n,i))throw new InvalidScalarResult(e.type,`a list scalar returned a sparse array`);return r(t)})}}jsonValue(e,t){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`){if(Number.isFinite(e))return e;throw new InvalidScalarResult(`json`,`a JSON number is not finite`)}if(typeof e==`bigint`){let t=Number(e);if(Number.isFinite(t))return t;throw new InvalidScalarResult(`json`,`a JSON integer is outside the finite Number domain`)}if(Array.isArray(e)){let n=this.#mt(e,t),r=Array(e.length);for(let t=0;t<e.length;t+=1){if(!Object.hasOwn(e,t))throw new InvalidScalarResult(`json`,`a JSON array is sparse`);r[t]=this.jsonValue(e[t],n)}return n.delete(e),r}if(isPlainJsonRecord(e)){let n=this.#mt(e,t),r={};for(let[t,i]of Object.entries(e))Object.defineProperty(r,t,{configurable:!0,enumerable:!0,value:this.jsonValue(i,n),writable:!0});return n.delete(e),r}throw new InvalidScalarResult(`json`,`the value is outside the JSON value domain`)}#mt(e,t){let n=t??new Set;if(n.has(e))throw new InvalidScalarResult(`json`,`a JSON value contains itself`);return n.add(e),n}};function isPlainJsonRecord(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}const gn=/^(?:0|-?[1-9]\d*)$/,_n=/^(\d{4})-(\d{2})-(\d{2})(?: (BC))?$/,vn=/^(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,6})?(?:Z|[+-](\d{2})(?::?(\d{2}))?)?$/,yn=/(?:Z|[+-]\d{2}(?::?\d{2})?)$/,bn=/\.?0+$/;function decodeString(e){if(typeof e==`string`)return e;throw new InvalidScalarResult(`string`,`the value is not a string`)}function decodeBoolean(e){if(typeof e==`boolean`)return e;if(e===0||e===0n)return!1;if(e===1||e===1n)return!0;throw new InvalidScalarResult(`boolean`,`the value is not true, false, zero, or one`)}function decodeInt(e,t=!1){let n=typeof e==`bigint`||typeof e==`string`&&gn.test(e)?Number(e):e;if(typeof n!=`number`)throw new InvalidScalarResult(`int`,`the value is not a canonical integer`);if(!(t?Number.isInteger(n):Number.isSafeInteger(n)))throw new InvalidScalarResult(`int`,`the integer is outside the safe range`);return n}function decodeBigint(e){if(typeof e==`bigint`)return e;if(typeof e==`number`&&Number.isSafeInteger(e)||typeof e==`string`&&gn.test(e))return BigInt(e);throw new InvalidScalarResult(`bigint`,`the value is not a canonical integer`)}function decodeNumber(e){let t=typeof e==`string`&&e.trim()!==``?Number(e):e;if(typeof t!=`number`||!Number.isFinite(t))throw new InvalidScalarResult(`number`,`the value is not a canonical finite number`);return t}const xn=2**64;function joinNumberSum(e){let[t,n]=sumParts(e,`number`),r=t===null?null:decodeNumber(t),i=n===null?null:decodeNumber(n);return r===null?i:r*xn+(i??0)}const Sn=2n**32n;function joinIntegerSum(e,t){let[n,r]=sumParts(e,t);return n===null?null:String(decodeBigint(n)*Sn+decodeBigint(r))}function sumParts(e,t){if(!Array.isArray(e)||e.length!==2)throw new InvalidScalarResult(t,`the sum is not its two parts`);return[e[0],e[1]]}function decodeTime(e){if(typeof e!=`string`)throw new InvalidScalarResult(`time`,`the value is not a valid provider time`);let t=vn.exec(e);if(!(t&&Ne(Number(t[1]),Number(t[2]),Number(t[3]))))throw new InvalidScalarResult(`time`,`the value is not a valid provider time`);if(Number(t[4]??0)>23||Number(t[5]??0)>59)throw new InvalidScalarResult(`time`,`the timezone suffix is invalid`);let n=e.replace(yn,``);n.includes(`.`)&&(n=n.replace(bn,``));let r=n.split(`.`)[1];if(r&&r.length>3)throw new InvalidScalarResult(`time`,`the normalized precision exceeds milliseconds`);return n}function decodeBlob(e){let{bytes:t}=Se(e);if(t)return t;throw new InvalidScalarResult(`blob`,`the value is not a binary value`)}function providerArrayMembers(e){if(!(e.startsWith(`{`)&&e.endsWith(`}`)))throw new InvalidScalarResult(`enum`,`a list scalar did not return an array`);let t=e.slice(1,-1);if(t.length===0)return[];let n=[],r=0;for(;r<=t.length;){if(t[r]===`"`){let e=``;for(r+=1;r<t.length&&t[r]!==`"`;)e+=t[r]===`\\`?t[++r]:t[r],r+=1;n.push(e),r+=2;continue}let e=t.indexOf(`,`,r),i=e===-1?t.length:e,a=t.slice(r,i);if(n.push(a===`NULL`?null:a),r=i+1,e===-1)break}return n}const Cn=Object.freeze([]);var TransportAttempt=class{pending=[];rejectedInsert;scratchId;nextField=0;#e;#t;#n;#r;#i;#a;publishScratchValue(e){(this.#e??=[]).push(e)}drainScratchPublications(){let e=this.#e??Cn;return this.#e=void 0,e}carryScratchValue(e,t){(this.#t??=new Map).set(e,t)}carried(e){if(!(e instanceof H))return e;let t=this.#t;return t?.has(e)?t.get(e):e}recordInsertProducer(e,t){(this.#n??=new Map).set(e,t)}assertPremise(e,t){(this.#r??=new Map).set(e,t)}judgeWrite(e,t){(this.#i??=new Map).set(e,t)}drainJudgedWrites(){let e=this.#i??new Map;return this.#i=void 0,e}recordMember(e){(this.#a??=new Set).add(e)}get hasAssertedPremises(){return this.#r!==void 0&&this.#r.size>0}get holdsWrite(){return this.pending.some(e=>!this.#r?.has(e))}holdsOtherMemberWrite(e){if(!this.#a)return!1;for(let t of this.#a)if(t!==e)return!0;return!1}drainInsertProducers(){let e=this.#n??new Map;return this.#n=void 0,e}withholdPremises(){let e=this.#r;if(!e)return;let t=this.pending.length;for(;t>0&&e.has(this.pending[t-1]);)t--;this.#o.push(...this.pending.splice(t))}restorePremises(){this.#o.length>0&&this.pending.unshift(...this.#o.splice(0))}#o=[];drainAssertedPremises(){let e=this.#r??new Map,t=new Map;for(let n of this.#o){let r=e.get(n);r&&(t.set(n,r),e.delete(n))}return this.#r=t.size>0?t:void 0,e}drainMembers(){let e=this.#a?[...this.#a]:[];return this.#a=void 0,e}};const wn=new Set([`update`,`delete`,`upsert`]),Tn=Object.freeze([]),En=Object.freeze([]),Dn=Object.freeze([]);function nestedRefusal(e,t){return{kind:`nestedWrite`,relation:t,message:`Cannot ${e} relation '${t}': the record it writes is not permitted.`,raceable:!1}}var OperationContext=class{queries;driver;usesBatch;#e;get preparesBatch(){return this.#e===`batch-preparation`}#t;#n;#r;#i=!1;#a;#o;get#s(){return this.#o??=new TransportAttempt}get queued(){return this.#o?.pending??Tn}#c;#l;#u;#d;get#f(){return this.#u?.length??0}#p=0;#m;#h=0;get#g(){return this.#p>0||this.#m===!0}#_=!1;#v;heldOutcomeFailure;#y;#b;get incompletePreparation(){return this.#b??=Error(`This operation requires dynamic execution`)}#x;#S;#C;#w;get#T(){return this.#w??=crypto.randomUUID()}#E=`open`;#D=0;#O;get requiresEnvelope(){return this.#O??=Error(`This operation must execute through its driver context`)}schema;scope;modelName;operation;#k;constructor(e,t,n,r,i,a=!1,o,s){this.scope=s,this.schema=e,this.modelName=n,this.operation=r,this.#k=o,this.#e=a?`batch-preparation`:i?.kind??`standalone`,this.driver=i?.kind===`borrowed-transaction`?i.driver:t,this.#r=i?.writeOutcome,this.#t=i?.kind===`borrowed-transaction`?i.memberRollback:void 0,this.#n=i?.kind===`borrowed-transaction`?i.operationRegion:void 0,this.#a=this.driver,this.usesBatch=this.#e===`batch-preparation`||this.#e===`standalone`&&!this.driver.supportsTransactions,this.queries=new hn(e,this.driver.adapter,this.driver.result,s?.domain,s)}get attribution(){return this.#k??{model:this.modelName,operation:this.operation,correlationId:this.#T}}get#A(){return{model:this.modelName,operation:this.operation,correlationId:this.#T}}statementContext(e,t){let n=e[`~`].names.ts,r=this.#k;return r?r.model===n?r:Tt(r,n):{model:n,operation:t,correlationId:this.#T}}#j(e,t=this.attribution,n){let r=this.#a._prepare(e,t),i=h(r,{...r,context:t});return this.#s.pending.push(i),n&&this.#s.recordMember(n),i}prepareMembers(e,t){this.#_=!0;try{let n=e(),r=t?this.#l?.get(t)?.path??[]:[],i=this.#l??=new WeakMap;for(let[e,t]of n.entries())i.set(t,{path:[...r,e],totalMembers:n.length});return n}catch(e){throw this.failure(e,`planning`,t)}}#M;async executeMember(e,t){let n=this.#o?.holdsWrite===!0,r=this.#M;t&&(this.#M=t);try{let r=await e();return this.#e!==`batch-preparation`&&(n||await this.flush(void 0,t),this.#h++),r}catch(e){throw this.failure(e,`member`,t)}finally{this.#M=r}}async executeSkippableMember(e,t,n){return this.admitsSuppression(`rows involving nested writes`),this.executeMember(async()=>{try{return await this.#N(async()=>e()),!0}catch(e){if(e instanceof k&&this.rejectedProducer(e)===t)return!1;throw e}},n)}async#N(e){let t=this.#a,withinRollback=async n=>{this.#a=n;try{return await e(n)}finally{this.#a=t}};return this.#t&&!this.#i?this.#t(withinRollback,this.attribution):t.withTransaction(withinRollback,void 0,this.attribution)}admitsSuppression(e){if(this.#e===`borrowed-transaction`&&!this.#t||this.usesBatch)throw new N(`skipDuplicates cannot skip ${e} on driver '${this.driver.driverName}' in this scope; a member savepoint is required.`,{meta:{model:this.modelName,operation:this.operation}});return!0}failure(e,t,n){if(typeof e==`object`&&e&&this.#C?.has(e))return e;let r=e;if(e instanceof InvalidScalarResult){let t=this.driver.driverName,n=this.modelName,i=this.operation,{scalarType:a,reason:o}=e;r=new de(`The "${i}" result is incompatible with the ${a} scalar domain: ${o}.`,{code:O.QUERY_RESULT_INVALID,meta:{driver:t,model:n,operation:i,scalarType:a,reason:o}})}(e instanceof RecursiveOutputOverBudget||e instanceof GatedFieldRefusal)&&(r=e.refusal(this.operation,this.modelName));let i=n?this.#l?.get(n):void 0,a=n!==void 0&&n===this.#v;return this.usesBatch&&(t===`prefix`||this.#p>0||this.#m&&!a)?ie(r,{atomicity:`segment`,phase:t,committedSegments:this.#p,committedWriteMembers:this.#c?.size??0,completedMembers:this.#h,...i?.path.length?{memberPath:i.path}:{},...i?{totalMembers:i.totalMembers}:{},...this.#m?{mayHaveCommittedSegment:this.#m}:{}}):r}#P(){if(this.usesBatch)return;if(this.#e===`borrowed-transaction`){let e=this.#n;return e?t=>e(t,this.attribution):void 0}if(this.#e!==`standalone`)return;let e=this.#r?Et(this.attribution,{readyToCommit:()=>{this.#F=`ready`},committed:()=>{this.#F=`committed`}}):this.attribution;return t=>this.driver.withTransaction(t,void 0,e)}#F=`pending`;#I(){this.#F=`pending`}async#L(e,t){this.#I();let n;try{n=await e(async e=>{this.#a=e,this.#i=!0;try{return await t()}finally{this.#a=this.driver,this.#i=!1}})}catch(e){let t=this.#F===`committed`?`committed`:this.#F===`ready`?`may-have-committed`:void 0;if(!t)throw e;let n=D(e)?ae(e,t):e;throw await this.#ee(this.#F===`committed`?this.#r?.committedSegment:this.#r?.mayBeVisible,n),n}return await this.#ee(this.#r?.committedSegment),n}async run(e,t=!1){if(!(this.#e===`batch-preparation`||isReadOperation(this.operation)))return await this.#R(e,t);try{return await e()}catch(e){throw this.#z(e)}}async#R(e,t){try{t||this.#B();let n=this.#P();if(!n)return await this.#K(e);if(!t)return await this.#G(n,e);this.#E=`deferred`;try{return await e()}catch(e){if(e!==this.requiresEnvelope)throw e}return this.#V(),await this.#G(n,e)}catch(e){throw this.#z(e)}}#z(e){let t=e instanceof InvalidScalarResult||e instanceof RecursiveOutputOverBudget||e instanceof GatedFieldRefusal;return t||this.usesBatch&&this.#p>0?this.failure(e,t?`result`:`member`):e}#B(){if(this.#e!==`standalone`)return;let e=this.driver,t={driver:e.driverName,operation:this.operation};if(!(e.supportsTransactions||e.supportsBatch))throw new L(`Driver "${e.driverName}" supports neither transactions nor atomic batch execution.`,{meta:t});if(e.supportsBatch&&!e.supportsTransactions&&!e.adapter.capabilities.supportsReturning&&wn.has(this.operation))throw new L(this.operation===`upsert`?`cannot execute non-returning upsert writes atomically because public result parsing cannot be rolled back after an atomic batch commits`:`Driver '${e.driverName}' cannot execute '${this.operation}' because public result parsing cannot be rolled back.`,{meta:t})}dispatch(e,t,n){try{if(this.#E===`deferred`){if(!(t&&e===1&&this.#D===0))throw this.requiresEnvelope;this.#E=`statement`}return this.#D+=e,n()}catch(e){return Promise.reject(e)}}#V(e=new TransportAttempt){this.#o=e,this.#u=void 0,this.#d=void 0,this.#_=!1,this.#E=`open`}attachRecovery(e,t){this.#H=e,this.#U=t}#H;#U;#W=!1;spendRecovery(){if(this.#W)return;let e=this.#H?.();if(e)return this.#W=!0,e}get replaysInPlace(){return this.#e===`standalone`&&!this.#i}async#G(e,t){try{return await this.#L(e,t)}catch(n){if(this.recoveryRejection(n)?.kind!==`insert`||!this.#U?.(n))throw n;let r=this.spendRecovery();if(!r)throw n;return this.#V(r),await this.#L(e,t)}}async#K(e){try{return await e()}catch(t){if(this.recoveryRejection(t)?.kind!==`assertion`)throw t;let n=this.spendRecovery();if(!n)throw t;return this.#V(n),await e()}}async planningLocate(e,t){let n=await this.answer(e,!1,t);return this.queries.decodeQuery(e,n.rows,!0)}async read(e,t=!1,n=!1,r){if(this.#e===`batch-preparation`)throw this.incompletePreparation;let i=await this.answer(e,n,r);return this.queries.decodeQuery(e,i.rows,t)}async answer(e,t,n){let r=this.#M;r&&this.#o?.holdsOtherMemberWrite(r)&&await this.flush();let i=n?this.statementContext(n,this.operation):this.attribution;return this.dispatch(1,t,()=>this.#a._execute(e.sql,i))}publishedProjection(e,t){return this.queries.decodeResult(t,this.operation,t=>this.queries.decodeProjection(e,t))}publishedTerminal(e,t){let n=e[0];if(!n)return[];for(let[n,r]of e.entries())this.queries.assertExpectedRows(r,t[n].length);return this.publishedProjection(n.shape,t.length===1?t[0]:t.flat())}async publish(e,t){if(this.#e===`batch-preparation`)return this.publishPrepared(e,t);let n=this.#e===`standalone`&&e.value.kind===`collection`?resolvePositionalResultDriver(this.#a):void 0;if(n)return this.#q(e,t,n);let r=await this.answer(e.query,!0);return this.#J(e,t,this.publishedTerminal([e.query],[r.rows]))}async#q(e,t,n){let r=await this.dispatch(1,!0,()=>n(e.query.sql,this.attribution));if(r.kind===`positional`&&resolvePositionalResultDriver(this.#a)===n)return this.queries.assertExpectedRows(e.query,r.rows.length),this.#J(e,t,this.queries.decodeProjection(e.query.shape,r.rows,!1,r.columns));let i=r.kind===`borrowed`?r.result:borrowPositionalResult(r);return this.#J(e,t,this.publishedTerminal([e.query],[i.rows.map(record)]))}publishPrepared(e,t){let n=this.queued.length;this.#j(e.query.sql),this.#x=r=>{let i=r[n];if(!i)throw new L(`Driver '${this.driver.driverName}' omitted the prepared result for operation '${this.operation}'.`,{meta:this.#A});return this.#J(e,t,this.publishedTerminal([e.query],[i.rows.map(record)]))}}#J(e,t,n){let r=e.result(n);if(r===null&&t)throw t();return r}async flush(e,t,n){let r=Array.isArray(e)?e:e?[e]:[];this.#o?.withholdPremises();try{if(!this.usesBatch||this.queued.length===0){if(n&&!n.present&&(await this.read(n.query,!0)).length>0)throw n.failure();let t=[];for(let e of r)t.push(await this.read(e,!0));return Array.isArray(e)?t:t[0]??[]}return await this.#Y(r,e,t,n)}finally{this.#o?.restorePremises()}}async#Y(e,t,n,r){r?.present?this.requirePresent(r.query,r.failure()):r&&await this.requireAbsent(r.query,r.failure());let i=this.queued.length;for(let t of e)this.#j(t.sql);let a=await this.submit(!1,n);return this.settleSubmitted(()=>{try{let n=e.map((e,t)=>this.queries.decodeQuery(e,a[i+t].rows,!0));return Array.isArray(t)?n:n[0]??[]}catch(e){throw this.failure(e,`result`,n)}})}async requireAbsent(e,t){if(this.usesBatch){this.statePremise(e,!1,t);return}if((await this.read(e,!0)).length)throw t}requirePresent(e,t){this.statePremise(e,!0,t)}#X(e){let t=this.#o?.scratchId;return t!==void 0&&e.sql.values.includes(t)}statePremise(e,t,n){let r=this.driver.adapter.assertions;this.#s.assertPremise(this.#j(t?r.exists(e.sql):r.notExists(e.sql)),{query:e,present:t,failure:n,readsBatchReference:this.#X(e)})}async submit(e=!1,t){if(this.#e===`batch-preparation`)throw this.incompletePreparation;let n=this.#s;this.#y=void 0,n.rejectedInsert=void 0;let r=this.#p,i=this.#u,a=i?i.filter(e=>!e.declaring):En;if(i)for(let e of i)e.declaring=!1;let o=a.map(e=>{let t=e.query??=e.state(),n=this.statementContext(e.model,this.operation);return{statement:{...this.#a._prepare(this.driver.adapter.assertions.exists(t.sql),n),context:n},premise:{query:t,present:!0,failure:e.failure(),readsBatchReference:this.#X(t)}}}),s=o.length+n.pending.length,c=this.#oe();this.closeScratch();let l=[...o.map(e=>e.statement),...n.pending.splice(0)],u=n.drainInsertProducers(),d=n.drainAssertedPremises(),f=n.drainJudgedWrites();for(let{statement:e,premise:t}of o)d.set(e,t);let p=n.drainMembers(),acknowledged=async()=>{if(p.length===0)return;this.#p++;let e=this.#c??=new Set;for(let t of p)e.add(t);try{await this.#r?.committedSegment?.()}catch(e){this.heldOutcomeFailure={failure:e}}},m;try{m=await this.dispatch(l.length,!1,()=>this.#a._executeBatch(l,void 0,this.attribution,this.driver.supportsOrderedCommittedSegments?acknowledged:void 0)),this.driver.supportsOrderedCommittedSegments||await acknowledged()}catch(i){let o=this.heldOutcomeFailure;if(this.heldOutcomeFailure=void 0,o)throw this.#te(I(i,o.failure));if(this.driver.supportsBatch&&!this.#g&&!this.#_&&i instanceof k&&i.meta.commitCertainty===void 0&&i.originalCause&&i.originalCause.cause===void 0&&typeof i.meta.statementIndex==`number`){let e=u.get(l[i.meta.statementIndex]);e&&(n.rejectedInsert={error:i,producer:e})}let s,c;if(i instanceof A){let e=i.meta.statementIndex;if(typeof e==`number`){let t=l[e];s=d.get(t)?.failure??f.get(t)?.refusal,c=e}else{let e=oe(l,this.driver.dialect),t=d.size+f.size===1&&!e;for(let[e,n]of l.entries()){let r=d.get(n);if(!(s||!r||r.readsBatchReference)&&((await this.read(r.query,!0)).length>0!==r.present||t)){s=r.failure,c=e;break}}if(s===void 0&&!e){let e=l.findIndex(e=>!d.has(e)),t=[...l.entries()].filter(([t,n])=>e>=0&&t>e&&d.has(n));if(t.length===1){let[e,n]=t[0];s=d.get(n).failure,c=e}}if(s===void 0&&!e)if(f.size===1)for(let[e,t]of f)s=t.refusal,c=l.indexOf(e);else for(let[e,t]of l.entries()){let n=f.get(t)?.probe;if(n!==void 0)try{await this.#a._execute(n,this.attribution)}catch(n){if(!(n instanceof A))throw n;s=f.get(t).refusal,c=e;break}}}}let m=D(i)&&typeof i.meta.statementIndex==`number`?i.meta.statementIndex:void 0,h=m??c,g=h;if(m===void 0&&typeof c==`number`){let e=-1;for(let[t,n]of l.entries())(d.has(n)||f.has(n))&&(e=t);g=e}let _=typeof h==`number`&&typeof g==`number`&&this.#p===0&&l.every((e,t)=>t>g||d.has(e)||t===h&&f.has(e));p.length>0&&!_&&!this.driver.supportsOrderedCommittedSegments&&this.#p===r&&!(i instanceof k)&&(this.#m=!0,await this.#ee(this.#r?.mayBeVisible,i));let v=i;throw s&&i instanceof A?(v=s,this.driver.supportsBatch&&!this.#g&&i.meta.commitCertainty===void 0&&D(s)&&s.meta.raceable===!0&&(this.#y=s)):i instanceof A&&(v=new M(fe,``,{code:O.NESTED_WRITE_ASSERTION_FAILED,cause:i})),e||a.length>0?this.failure(v,this.#p>r?`result`:`member`,t):v}try{for(let[e,n]of c.entries())this.#se(n,m[s+e],t)}catch(e){let t=this.heldOutcomeFailure;throw this.heldOutcomeFailure=void 0,t?this.#te(I(e,t.failure)):e}return m.slice(o.length)}async settleSubmitted(e){let t=this.heldOutcomeFailure;this.heldOutcomeFailure=void 0;let n;try{n=await e()}catch(e){throw t?this.#te(I(e,t.failure)):e}if(t)throw this.#te(t.failure);return n}rejectedProducer(e){let t=this.#o?.rejectedInsert;return t&&t.error===e?t.producer:void 0}recoveryRejection(e){if(this.#e!==`standalone`&&!(this.#e===`borrowed-transaction`&&this.#n)||this.#g)return;if(this.#y===e)return{kind:`assertion`};let t=this.rejectedProducer(e);return t?{kind:`insert`,producer:t}:void 0}get transportAttempt(){return this.#s}restartRejectedInsert(e){this.#o=e,this.#y=void 0}published(e,t){if(!t)return e;let n=e[0];if(!n)throw this.#te(t());return n}#Z(e,t,n){if(!n||this.#e!==`batch-preparation`)return;let r=this.queries.select(e,{select:Object.fromEntries(this.schema.keys(e).map(e=>[e,!0]))},void 0,{selector:t});this.packageGuard(e,r.sql,`exists`,{kind:`notFound`,message:`${this.operation} found no '${e[`~`].names.ts}' row matching its unique selector.`,raceable:!1})}packageGuard(e,t,n,r){(this.#S??=[]).push({queryIndex:this.queued.length,premise:n,probe:t,failure:r,model:e[`~`].names.ts,operation:this.operation});let i=this.driver.adapter.assertions;this.#j(n===`exists`?i.exists(t):i.notExists(t),this.statementContext(e,this.operation))}emptyBulkResult(e){let result=()=>e?[]:{count:0};if(this.#e===`batch-preparation`){this.#x=result;return}return result()}seriesQueries(e,t,n=`createMany`){if(t.length===0)return[];let r=g(this.driver.maxBindParametersPerStatement),i=new WeakMap;return compileBindBudgetChunks(t.length,r,(r,a)=>{let o=this.queries.selectSeries(e,t.slice(r,a),n);return i.set(o.sql,o),o.sql}).map(({statement:e})=>i.get(e))}finish(){return this.finishValue(void 0)}finishValue(e){return this.finishTerminals([],()=>e)}finishOne(e){return this.finishTerminals([e],e=>e[0])}finishMany(e){return this.finishTerminals(e,e=>e)}#Q(e,t,n){let r=[];for(let i of e.keys()){let e=t[n+i];if(!e)throw new L(`Driver '${this.driver.driverName}' omitted the ${this.#e===`batch-preparation`?`prepared`:`terminal`} result for operation '${this.operation}'.`,{meta:this.#A});r.push(e.rows.map(record))}return this.publishedTerminal(e,r)}async finishTerminals(e,t){if(!this.usesBatch){let n=[];for(let t of e)n.push((await this.answer(t,e.length===1)).rows.map(record));return t(this.publishedTerminal(e,n))}let n=this.queued.length;for(let t of e)this.#j(t.sql);if(this.closeScratch(),this.#e===`batch-preparation`)return this.#x=r=>t(this.#Q(e,r,n)),t([]);if(this.queued.length===0)return t([]);let r=await this.submit();return this.settleSubmitted(()=>{try{return t(this.#Q(e,r,n))}catch(t){throw e.length?this.failure(t,`result`):t}})}isIncompletePreparation(e){return e===this.incompletePreparation}preparedBatch(){let e=this.#x;if(e!==void 0&&!this.#o?.hasAssertedPremises)return{queries:this.queued.map(e=>h(e,{sql:e.sql,params:e.params??[],context:e.context??this.attribution})),...this.#S?.length?{guards:this.#S}:{},parseResult:t=>{try{return e(t)}catch(e){throw this.failure(e,`result`)}}}}async#$(e,t,n,r){return this.setMutations([{sql:e,context:t}],e=>{let t=e[0];if(!t)throw new L(`Driver '${this.driver.driverName}' omitted the result for operation '${this.operation}'.`,{meta:this.#A});return n(t)},r)}async setMutations(e,t,n){if(this.#e===`batch-preparation`){let r=this.queued.length;for(let t of e)this.#ge(t.sql,t.context,void 0,n);this.#x=n=>{let i=n.slice(r,r+e.length);if(i.length!==e.length)throw new L(`Driver '${this.driver.driverName}' omitted the prepared result for operation '${this.operation}'.`,{meta:this.#A});return t(i)};return}let r=e.length===1&&this.queued.length===0&&this.#f===0;if(this.usesBatch&&!r){let r={};this.#v=r;let i=this.queued.length;for(let t of e)this.#ge(t.sql,t.context,r,n,t.probe);let a=await this.submit(!0,r);return this.settleSubmitted(()=>{try{return t(a.slice(i,i+e.length))}catch(e){throw this.failure(e,`result`,r)}})}return this.dispatchSetMutations(e,t,n)}dispatchSetMutations(e,t,n){return this.dispatch(e.length,!0,async()=>{let r=this.#e===`standalone`&&!this.#i,i=[];try{for(let t of e)i.push(await this.#me(n,()=>this.#a._execute(t.sql,t.context)))}catch(e){throw r&&!(e instanceof k)&&await this.#ee(this.#r?.mayBeVisible,e),e}let a;try{a={value:t(i)}}catch(e){a={failure:this.failure(e,`result`)}}if(r&&await this.#ee(this.#r?.committedSegment,`failure`in a?a.failure:void 0),`failure`in a)throw a.failure;return a.value})}async#ee(e,t){if(e)try{await e()}catch(e){throw t===void 0?e:this.#te(I(t,e))}}#te(e){return typeof e==`object`&&e&&(this.#C??=new WeakSet).add(e),e}#ne(e,t,n,r=!1,i){let a=this.queries,o=this.driver.adapter.mutations;if(t.length===0){if(i)throw new N(`Cannot create a '${e[`~`].names.ts}' row that writes no field: its placement is judged on the values it writes.`);return o.insertDefault(a.table(e))}let s=r?o.skipDuplicates(a.columnName(e,t[0])):void 0,c=i&&a.producedSource(e,t,n,i),l=o.insert(a.table(e),t.map(t=>a.columnName(e,t)),c?{select:c}:n.map(n=>t.map(t=>a.fieldValue(e,t,n[t]))),s?.prefix);return s?.suffix?V`${l} ${s.suffix}`:l}#re(e,t,n,r,i){let a=this.queries,o=n?V`${t} ${this.driver.adapter.mutations.returning(V.join(a.lowerProjection(n),`, `))}`:t;return this.#$(o,this.statementContext(e,this.operation),e=>n?this.published(this.publishedProjection(n.shape,e.rows.map(record)),r):{count:e.rowCount},i)}async insertMany(e,t,n){if(!(!this.#i||this.usesBatch))return(await this.createMany(e,t(),void 0,!1,void 0,n)).count}async createMany(e,t,n,r=!1,i,a){if(t.length===0){if(this.#e===`batch-preparation`)throw new j(`No data to insert for createMany.`);return this.emptyBulkResult(n)}let o=this.queries,s=this.driver.adapter,c=this.#de(e),l=c&&{model:e,refusal:a??this.#pe},u=r&&s.mutations.skipDuplicatesStrategy===`recoverableUniqueError`;if(u||n&&!s.capabilities.supportsReturning){if(this.#e===`batch-preparation`)throw this.incompletePreparation;let r=u&&this.admitsSuppression(`duplicate rows`),a=n?t.map(t=>{let n=this.schema.keys(e).filter(e=>t[e]===void 0),r=this.#ce(e,n);if(n.length>0&&r===void 0)throw new L(`Driver '${this.driver.driverName}' cannot locate one selected createMany row after insertion.`,{meta:this.#A});return r}):void 0,o=this.prepareMembers(()=>t),s=[],d=0;for(let[t,n]of o.entries()){let i=Object.keys(n),o=this.#ne(e,i,[n],!1,c),u=this.statementContext(e,this.operation),f;if(f=r?await this.executeMember(async()=>{try{return await this.dispatch(1,!1,()=>this.#N(e=>this.#me(l,()=>e._execute(o,u))))}catch(e){if(e instanceof k)return;throw e}},n):await this.executeMember(()=>this.dispatch(1,!1,()=>this.#me(l,()=>this.#a._execute(o,u))),n),!f||(d+=f.rowCount,!a))continue;let p=a[t];if(p&&f.insertId===void 0)throw TypeError(`INSERT did not produce the required record identity`);s.push({...this.schema.identity(e,n),...p?{[p]:f.insertId}:{}})}return n?s.length?this.finishTerminals(this.seriesQueries(n,s),e=>this.published(e,i)):this.published([],i):{count:d}}let d=n?s.mutations.returning(V.join(o.lowerProjection(n),`, `)):void 0,f=[];for(let e of t){let t=Object.keys(e),n=f.at(-1);t.length===0||!n||n.columns.length!==t.length||t.some((e,t)=>n.columns[t]!==e)?f.push({columns:t,rows:[e]}):n.rows.push(e)}let p=g(this.driver.maxBindParametersPerStatement),m=[];for(let t of f){if(t.columns.length===0){for(let n of t.rows){let t=this.#ne(e,[],[n],!1,c);d&&(t=V`${t} ${d}`),m.push({sql:t,context:this.statementContext(e,this.operation)})}continue}let n=compileBindBudgetChunks(t.rows.length,p,(n,i)=>{let a=this.#ne(e,t.columns,t.rows.slice(n,i),r,c);return d?V`${a} ${d}`:a});for(let r of n)m.push({sql:r.statement,context:this.statementContext(e,this.operation),probe:c&&this.usesBatch?o.producedSource(e,t.columns,t.rows.slice(r.start,r.end),c):void 0})}return this.setMutations(m,e=>{let t=e.reduce((e,t)=>e+t.rowCount,0);if(!n)return{count:t};let r=[];for(let t of e)r.push(...t.rows.map(record));return this.published(this.publishedProjection(n.shape,r),i)},l)}async upsertOne(e,t,n,r,i,a){let o=this.queries,s=this.driver.adapter,c=Object.keys(t),l=this.#de(e),u=this.#ne(e,c,[t],!1,l),d=e[`~`].names.sql,f=s.mutations.onConflict(V.join(r.map(t=>s.identifiers.escape(o.columnName(e,t))),`, `),s.mutations.onConflictUpdate(V.join(Object.entries(n).map(([t,n])=>s.set.assign(o.column(e,t),o.updateValue(e,t,n,o.column(e,t,d)))),`, `)));return this.#re(e,V`${u} ${f}`,i,a,l&&{model:e,refusal:this.#pe})}async updateMany(e,t,n,r,i,a){let o=this.queries,s=this.driver.adapter,c=this.#ue(e,n),produced=(r,i)=>this.#fe(e,n,t.judgement,e=>o.lowerSelector(r,e),i),l={model:e,refusal:this.#pe};if(i&&!(s.capabilities.supportsReturning&&returningSafeProjection(i))){let u=await this.captureMutationIdentities(e,t,r);if(u.length===0)return this.published([],a);let d=produced(o.andSelectors(e,[t,o.includeIdentities(e,u)]));return await this.#ie(e,t,u,r,t=>s.mutations.update(o.table(e),V.join(c,`, `),d??t),this.operation===`delete`||this.operation===`deleteMany`?`deleteMany`:`updateMany`,d&&l),this.finishTerminals(this.seriesQueries(i,u.map(t=>this.#ae(e,t,n)),`updateMany`),e=>this.published(e,a))}this.#Z(e,t,a);let u=produced(t,r),d=u?{where:u}:o.lowerMutationLimit(e,t,r),f=s.mutations.update(o.table(e),V.join(c,`, `),d.where),p=d.suffix?V`${f} ${d.suffix}`:f;return this.#re(e,p,i,a,u&&l)}async deleteMany(e,t,n,r,i){let a=this.queries,o=this.driver.adapter;if(r&&!(o.capabilities.supportsReturning&&returningSafeProjection(r))){let s=await this.captureMutationIdentities(e,t,n);if(s.length===0)return this.published([],i);let c=[];for(let t of this.seriesQueries(r,s))c.push(...await this.read(t,!1,!1,e));return await this.#ie(e,t,s,n,t=>o.mutations.delete(a.table(e),t),`deleteMany`),this.published(c,i)}this.#Z(e,t,i);let s=a.lowerMutationLimit(e,t,n),c=o.mutations.delete(a.table(e),s.where),l=s.suffix?V`${c} ${s.suffix}`:c;return this.#re(e,l,r,i)}async captureMutationIdentities(e,t,n){if(this.#e===`batch-preparation`)throw this.incompletePreparation;let r=this.schema.keys(e),i=this.queries.select(e,{select:Object.fromEntries(r.map(e=>[e,!0])),take:n},void 0,{selector:t,forUpdate:!this.usesBatch});return(this.usesBatch?await this.flush(i):await this.read(i,!0,!1,e)).map(t=>this.schema.identity(e,t))}async requireCapturedSet(e,t,n,r,i){if(!this.usesBatch)return;let a=this.queries;for(let r of n)this.requirePresent(a.select(e,{take:1},void 0,{selector:t,identity:r}),i());r===void 0&&await this.requireAbsent(a.select(e,{take:1},void 0,{selector:a.andSelectors(e,[t,a.excludeIdentities(e,n)])}),i())}async#ie(e,t,n,r,i,a,o){let changed=()=>new L(`${a} selected-row cardinality changed during its locked mutation.`,{meta:this.#A});await this.requireCapturedSet(e,t,n,r,changed);let s=i(this.capturedTarget(e,t,n)),c=this.statementContext(e,this.operation),answered=e=>{if(e.rowCount!==n.length)throw this.failure(changed(),`result`)};if(!this.usesBatch){answered(await this.dispatch(1,!1,()=>this.#me(o,()=>this.#a._execute(s,c))));return}let l=this.queued.length,u={};this.#v=u,this.#ge(s,c,u,o);let d=await this.submit(!0,u);await this.settleSubmitted(()=>{let e=d[l];if(!e)throw new L(`Driver '${this.driver.driverName}' omitted the prepared result for operation '${this.operation}'.`,{meta:this.#A});answered(e)})}capturedTarget(e,t,n){let r=this.queries;return r.lowerMutationLimit(e,r.andSelectors(e,[t,r.includeIdentities(e,n)]),void 0).where}#ae(e,t,n){let r=this.queries;return Object.fromEntries(this.schema.keys(e).map(i=>[i,Object.hasOwn(n,i)?r.updateValue(e,i,n[i],r.fieldValue(e,i,t[i])):t[i]]))}ensureScratch(){let e=this.#s;if(e.scratchId)return e.scratchId;let t=K(this.driver.adapter).batchRefs;e.scratchId=crypto.randomUUID();for(let n of t.setup(e.scratchId))this.#j(n);return e.scratchId}#oe(){let e=this.#o;if(e?.scratchId===void 0)return Dn;let t=[];for(let n of e.drainScratchPublications()){let e=this.queries.scalarQuery(n.model,n.field,n.expression);this.#j(e.sql),t.push({query:e,publication:n})}return t}#se(e,t,n){let r;try{r=this.queries.decodeQuery(e.query,t.rows,!0)[0]}catch(e){throw this.failure(e,`result`,n)}this.#s.carryScratchValue(e.publication.expression,r[e.publication.field])}closeScratch(){let e=this.#o;e?.scratchId!==void 0&&(this.#j(K(this.driver.adapter).batchRefs.cleanup(e.scratchId)),e.scratchId=void 0)}#ce(e,t){if(t.length!==1)return;let n=t[0];return e[`~`].state.scalars[n][`~`].state.autoGenerate?.kind===`increment`?n:void 0}async insert(e,t,n,r,i=`create`,a,o,s){let c=this.queries,l=this.driver.adapter,u=Object.keys(t),d=this.#de(e),f=d&&{model:e,refusal:s??this.#pe},p=this.#ne(e,u,[t],!1,d),m=d&&this.usesBatch&&u.length>0?c.producedSource(e,u,[t],d):void 0,h=[...n].filter(e=>t[e]===void 0),g=this.statementContext(e,i);if(!this.usesBatch){let n=h.length?c.prepareProjection(e,{select:Object.fromEntries(h.map(e=>[e,!0]))},!0):void 0,r=l.capabilities.supportsReturning?void 0:this.#ce(e,h);if(h.length&&!l.capabilities.supportsReturning&&r===void 0)throw Error(`Returning generated values requires RETURNING support or one generated increment field`);n&&l.capabilities.supportsReturning&&(p=V`${p} ${l.mutations.returning(V.join(c.lowerProjection(n),`, `))}`),this.#s.rejectedInsert=void 0;let i;try{i=await this.dispatch(1,!1,()=>this.#me(f,()=>this.#a._execute(p,g)))}catch(e){throw a&&e instanceof k&&(this.#s.rejectedInsert={error:e,producer:a}),e}let o=r===void 0?i.rows:i.insertId===void 0?[]:[{[r]:i.insertId}],s=n?c.decodeProjection(n.shape,o,!0)[0]:void 0;if(h.length&&s===void 0)throw TypeError(`INSERT did not produce the required record`);return{...t,...s}}o&&(this.#u??=[]).push({declaring:!0,model:o.model,state:()=>c.select(o.model,{where:o.where(),select:Object.fromEntries(this.schema.keys(o.model).map(e=>[e,!0]))}),failure:()=>new M(`Cannot ${o.verb} relation '${o.relation}': parent record changed across a committed segment.`,o.relation)});let _={...t};if(h.length){let i=K(l).batchRefs,o=this.#ce(e,h),s=i.storeInsertedKey;if(!(o!==void 0&&s!==void 0)){if(!l.capabilities.supportsReturning||l.capabilities.supportsCteWithMutations)throw Error(`The driver cannot return generated values for this atomic batch without an exact row identity`);let i=[...new Set([...this.schema.keys(e),...n])],o=Object.fromEntries(i.map(e=>[e,!0])),s=c.prepareProjection(e,{select:o},!0),u=this.queued.length,d=this.#ge(V`${p} ${l.mutations.returning(V.join(c.lowerProjection(s),`, `))}`,g,r,f,m);a&&this.#s.recordInsertProducer(d,a);let h=await this.submit(!0,r),_=await this.settleSubmitted(()=>{try{let e=c.decodeProjection(s.shape,h[u].rows,!0);if(!e[0])throw TypeError(`INSERT RETURNING did not produce the required record`);return e[0]}catch(e){throw this.failure(e,`result`,r)}});return(this.#u??=[]).push({model:e,state:()=>c.select(e,{},void 0,{projection:s,identity:_}),failure:()=>new L(`Created record '${e[`~`].names.ts}' changed across a generated-output segment boundary.`,{meta:{model:this.modelName,operation:this.operation}})}),{...t,..._}}let u=this.ensureScratch(),d=String(this.#s.nextField++),[v,...y]=s(u,d,p,l.identifiers.escape(c.columnName(e,o))),b=this.#ge(v,g,r,f,m);a&&this.#s.recordInsertProducer(b,a);for(let e of y)this.#j(e);let x=l.expressions.cast(i.read(u,d),physicalField(this.schema,e,o).scalar[`~`].state.type===`bigint`?`bigint`:`integer`);this.#s.publishScratchValue({model:e,field:o,expression:x}),_[o]=x}else{let e=this.#ge(p,g,r,f,m);a&&this.#s.recordInsertProducer(e,a)}return _}async update(e,t,n,r,i=`update`,a=new Set,o,s,c){if(Object.keys(n).length===0)return{};let l=this.queries,u=this.driver.adapter,d=this.schema.identity(e,t),f={...n},p={},m=[];if(this.usesBatch)for(let r of a){let i=n[r];if(wholeValue(i))continue;if(physicalField(this.schema,e,r).scalar[`~`].state.type!==`int`){m.push(r);continue}let a=K(u).batchRefs,o=this.ensureScratch(),s=String(this.#s.nextField++);this.#j(a.store(o,s,l.updateValue(e,r,i,l.fieldValue(e,r,t[r]))));let c=u.expressions.cast(a.read(o,s),`integer`);this.#s.publishScratchValue({model:e,field:r,expression:c}),f[r]=p[r]=c}let h=this.#fe(e,f,s,t=>l.lowerIdentity(e,d,t),void 0,!1),g=h?{model:e,refusal:c??this.#pe}:void 0,_=u.mutations.update(l.table(e),V.join(this.#ue(e,f),`, `),h??l.lowerIdentity(e,d)),v=this.statementContext(e,i);if(!this.usesBatch&&a.size){let t=[...a],r=Object.fromEntries(t.map(e=>[e,!0])),i=l.prepareProjection(e,{select:r},!0);if(!u.capabilities.supportsReturning){await this.dispatch(1,!1,()=>this.#me(g,()=>this.#a._execute(_,v)));let t=await this.read(l.select(e,{},void 0,{forUpdate:!0,projection:i,identity:this.#ae(e,d,n)}),!0);if(!t[0])throw o?.()??TypeError(`UPDATE did not produce the required record`);return{...p,...t[0]}}let s=await this.dispatch(1,!1,()=>this.#me(g,()=>this.#a._execute(V`${_} ${u.mutations.returning(V.join(l.lowerProjection(i),`, `))}`,v))),c=l.decodeProjection(i.shape,s.rows,!0);if(!c[0])throw o?.()??TypeError(`UPDATE RETURNING did not produce the required record`);return{...p,...c[0]}}if(await this.#_e(_,v,r,g),m.length===0)return p;let y=l.prepareProjection(e,{select:Object.fromEntries(m.map(e=>[e,!0]))},!0),b=await this.flush(l.select(e,{},void 0,{projection:y,identity:this.#ae(e,d,n)}),r);if(!b[0])throw TypeError(`UPDATE did not produce the required record`);return{...p,...b[0]}}#le(e,t){let n=this.#d??=new Map,r=[e,...t],i=!0;for(let[e,t]of r.entries()){let a=e===r.length-1,o=n.get(t);o===void 0&&(i=!1,o=a?!0:new Map,n.set(t,o)),a||(n=o)}return i}async link(e,t,n,r){let i=this.driver.adapter,a=this.queries,o=[...e.sourceSide.members,...e.targetSide.members].map(e=>e.junctionField);if(r){if(o.every(e=>Object.is(r[e],t[e])))return;let s=o.map(e=>r[e]);if(!this.#le(e.table,s)){let t=i.mutations.delete(i.identifiers.table(e.table),a.junctionWhere(e,r)),o=this.statementContext(e.source,`update`);if(this.usesBatch)this.#j(t,o,n);else if((await this.dispatch(1,!1,()=>this.#a._execute(t,o))).rowCount!==1){let t=new L(`Concurrent membership change on the singular polymorphic member of relation '${e.name}': the captured owner's membership was already removed; retry to converge.`);throw t.meta.raceable=!0,t}}}let s=[e.sourceSide,e.targetSide].flatMap(e=>e.members.map(n=>a.fieldValue(e.model,n.referencedField,t[n.junctionField])));if(!i.capabilities.supportsTargetedUpsert){let r=a.alias(),c=a.alias(),l=q(i,{columns:V.join(s,`, `),from:a.table(e.target,r),joins:[i.joins.left(i.identifiers.table(e.table,c),a.junctionWhere(e,t,c))],where:i.operators.and(...e.targetSide.members.map(n=>i.operators.eq(a.column(e.target,n.referencedField,r),a.fieldValue(e.target,n.referencedField,t[n.junctionField]))),i.operators.isNull(i.identifiers.column(c,o[0])))});await this.#_e(i.mutations.insert(i.identifiers.table(e.table),o,{select:l}),this.statementContext(e.source,`update`),n);return}let c=i.mutations.insert(i.identifiers.table(e.table),o,[s]);await this.#_e(V`${c} ${i.mutations.onConflict(V.join(o.map(e=>i.identifiers.escape(e)),`, `),V`NOTHING`)}`,this.statementContext(e.source,`update`),n)}async captureMembership(e,t){let n=this.queries.junction(e,t,!this.usesBatch),r=await this.read(n,!0),i=r[0]?{...t,...r[0]}:void 0;if(this.usesBatch){let t=new M(`Concurrent membership change on the singular polymorphic member of relation '${e.name}': ${i?`the captured membership is gone`:`another owner holds the target`}; retry to converge.`,e.name);t.meta.raceable=!0,i?this.requirePresent(this.queries.junction(e,i),t):await this.requireAbsent(n,t)}return i}async remove(e,t,n,r,i){let a=this.driver.adapter,o=this.queries,s=o.domainOf(e.target,`related`,linkJudgement(e)),c=o.domainOf(e.target,`related`),keeping=t=>r.length?a.operators.not(a.operators.or(...r.map(n=>o.lowerIdentity(e.target,this.schema.identity(e.target,n),t)))):void 0,l=keeping();if(n===void 0&&s!==c&&await this.requireAbsent(o.select(e.target,{take:1,select:Object.fromEntries(this.schema.keys(e.target).map(e=>[e,!0]))},{edge:e,parent:t},{selector:c,unless:s,condition:l}),new M(`Cannot clear relation '${e.name}': a connected record may not be disconnected by this call.`,e.name)),e.kind===`junction`){let c=[];for(let[r,i]of[[e.sourceSide,t],[e.targetSide,n]])i&&c.push(...o.junctionSideConditions(r,void 0,i));if(s){let t=o.alias();c.push(a.operators.exists(a.subqueries.existsCheck(o.table(e.target,t),a.operators.and(...e.targetSide.members.map(n=>a.operators.eq(a.identifiers.column(e.table,n.junctionField),o.column(e.target,n.referencedField,t))),o.lowerSelector(s,t)))))}r.length&&c.push(a.operators.not(a.operators.or(...r.map(t=>a.operators.and(...o.junctionSideConditions(e.targetSide,void 0,t)))))),await this.#_e(a.mutations.delete(a.identifiers.table(e.table),a.operators.and(...c)),this.statementContext(e.source,`update`),i);return}let unlinked=r=>{let i=keeping(r);return a.operators.and(...e.pairs.map(n=>a.operators.eq(o.column(e.target,n.target,r),o.fieldValue(e.target,n.target,t[n.source]))),...e.discriminator?[a.operators.eq(o.column(e.target,e.discriminator.field,r),o.value(e.discriminator.value))]:[],...n?[o.lowerIdentity(e.target,this.schema.identity(e.target,n),r)]:[],...i?[i]:[],...s?[o.lowerSelector(s,r)]:[])},u=e.clearability,d=Object.fromEntries(u.fields.map(e=>[e,null])),f=this.#fe(e.target,d,linkJudgement(e),unlinked);await this.#_e(a.mutations.update(o.table(e.target),V.join(this.#ue(e.target,d),`, `),f??unlinked()),this.statementContext(e.target,`update`),i,f?{model:e.target,refusal:nestedRefusal(`disconnect`,e.name)}:void 0)}#ue(e,t){return Object.entries(t).map(([t,n])=>this.queries.updateAssignment(e,t,n))}#de(e,t){return this.queries.domain?.produced(e,t)}#fe(e,t,n,r,i,a=!0){let o=this.queries.domain;if(!(n===void 0||o===void 0))return this.queries.producedWhere(e,r,t,o.produced(e,n,a?Object.keys(t):void 0),o.cycles(e,n),i)}get#pe(){return{kind:`forbidden`,message:`${this.operation} produced a row that is not permitted.`,raceable:!1}}async#me(e,t){if(e===void 0)return t();try{return await t()}catch(t){throw t instanceof A?this.#he(e):t}}#he({model:e,refusal:t}){return createFailureError(t,e[`~`].names.ts,this.operation)}#ge(e,t,n,r,i){if(r===void 0)return this.#j(e,t,n);this.#e===`batch-preparation`&&(this.#S??=[]).push({queryIndex:this.queued.length,premise:`exists`,probe:V`SELECT 1`,failure:r.refusal,model:r.model[`~`].names.ts,operation:this.operation});let a=this.#j(e,t,n),o=this.#o?.scratchId;return this.#s.judgeWrite(a,{refusal:this.#he(r),...i&&!(o!==void 0&&i.values.includes(o))&&{probe:i}}),a}async mutateMembers(e,t,n,r,i){let a=this.queries,o=this.driver.adapter,s=e.target,c=a.lowerMutationLimit(s,n,void 0).where,l=r&&this.#fe(s,r,n.judgement,r=>o.operators.and(a.memberWhere(e,t,r),...n.predicate?[a.lowerSelector(n,r)]:[])),u=o.operators.and(a.memberWhere(e,t,s[`~`].names.sql),...c?[c]:[]);await this.#_e(r?o.mutations.update(a.table(s),V.join(this.#ue(s,r),`, `),l??u):o.mutations.delete(a.table(s),u),this.statementContext(s,r?`updateMany`:`deleteMany`),i,l?{model:s,refusal:nestedRefusal(`updateMany`,e.name)}:void 0)}async delete(e,t,n){await this.#_e(this.driver.adapter.mutations.delete(this.queries.table(e),this.queries.lowerIdentity(e,this.schema.identity(e,t))),this.statementContext(e,`delete`),n)}async#_e(e,t,n,r){this.usesBatch?this.#ge(e,t,n,r):await this.dispatch(1,!1,()=>this.#me(r,()=>this.#a._execute(e,t)))}};const On=new Set([`findMany`,`findFirst`,`findUnique`,`create`,`update`,`upsert`,`delete`,`createMany`,`updateMany`,`deleteMany`]);function strip(e,t,n,r){if(!B(r))return;let i=e.projected(n),a={select:r.select,include:r.include},o=B(r.omit)?r.omit:void 0,s={},c=[],l;for(let r of[`select`,`include`]){let o=a[r];if(!B(o))continue;let u;for(let a of Object.keys(o)){let s=o[a];if(i?.keys.has(a)){l={name:a,container:r,value:s},u??={...o},delete u[a];continue}let d=n[`~`].state.relations[a]?t.index.get(n)?.get(a):void 0;if(d===void 0)continue;if(!d.member&&(d.edge.kind===`variantRowCarrier`||d.edge.kind===`variantJunctionCarrier`)){if(!B(s))continue;let i=d.edge.kind===`variantJunctionCarrier`,l=i?s.variants:s;if(!B(l))continue;let f;for(let o of d.edge.members){let s=t.membership(n,a,o.variant).target,u=strip(e,t,s,l[o.variant]);u!==void 0&&((f??={...l})[o.variant]=u[0],c.push({path:[r,a,...i?[`variants`]:[],o.variant],model:s,plan:u[1]}))}f&&((u??={...o})[a]=i?{...s,variants:f}:f);continue}let f=t.membership(n,a).target,p=strip(e,t,f,s);p!==void 0&&((u??={...o})[a]=p[0],c.push({path:[r,a],model:f,plan:p[1]}))}u&&(s[r]=u)}let u=B(a.select)?a.select:void 0,d=new Set;for(let e of i?.gates.keys()??[])(u?u[e]===!0&&o?.[e]!==!0:o?.[e]===!1)&&d.add(e);if(l===void 0&&c.length===0&&d.size===0)return;let f=s.include!==void 0&&Object.keys(s.include).length===0,{include:p,...m}=r,h=f?m:{...r},g=!1;return s.select&&(g=Object.keys(s.select).length===0,h.select=g?{[t.keys(n)[0]]:!0}:s.select),s.include&&!f&&(h.include=s.include),[h,{key:l,bare:g,named:d,children:c}]}function admitKey(e,t,n,r,i){let{value:a}=n;if(typeof a==`boolean`)return a;let o=e.projected(t).keys.get(n.name).names;if(Array.isArray(a)&&a.length>0&&a.every(e=>typeof e==`string`&&o.some(([t])=>t===e)))return Object.freeze([...a]);throw new pe(i,[{path:`${r}${n.container}.${n.name}`,message:`expected true, false or a list of ${o.map(([e])=>e).join(`, `)}`}],{meta:{model:t[`~`].names.ts}})}function attach(e,t,n,r,i,a,o){let s={...r};for(let n of i.children){let r=s;for(let[i,s]of n.path.entries()){let c=r[s];if(!B(c))break;let l=i===n.path.length-1?attach(e,t,n.model,c,n.plan,`${a}${n.path.join(`.`)}.`,o):{...c};r[s]=l,r=l}}if(i.key){let t=admitKey(e,n,i.key,a,o),{container:r}=i.key;if(i.bare&&(s.select={}),t!==!1){let e=s[r];s[r]={...B(e)?e:{},[i.key.name]:t}}}return i.named.size>0&&B(s.select)&&pn.set(s.select,i.named),s}function admitProjected(e,t,n,r,i,a){let o=On.has(r)?strip(e,t,n,i):void 0;if(o===void 0)return a(i);let[s,c]=o;return attach(e,t,n,a(s),c,``,r)}function literal(e){return{kind:`literal`,value:e}}var Assignments=class{demands=new Set;#e=new Map;#t=new Set;#n=new Map;#r;model;operation;captured;forwarded;deferred;constructor(e,t,n={},r=n,i,a=[],o=!1){this.model=e,this.operation=t,this.captured=i,this.forwarded=a,this.deferred=o;for(let[e,t]of Object.entries(n))this.#e.set(e,literal(t)),r[e]!==void 0&&this.#t.add(e)}#i(e){if(e.kind!==`literal`||this.operation!==`update`)return e;let t=wholeValue(e.value);return t?{...e,value:t.value}:void 0}isRequested(e){return this.#t.has(e)}stated(e){let t=this.#e.get(e);if(t!==void 0)return this.#i(t)??t}field(e){this.demands.add(e);for(let t of this.forwarded)t.field(e);return{kind:`field`,producer:this,field:e}}restate(e,t){this.#e.set(e,t)}forward(e){this.forwarded.push(e);for(let t of this.demands)e.field(t)}known(e){let t=this.#e.get(e);return t?.kind===`field`?t.producer.known(t.field):t&&this.#i(t)}writesField(e){return this.#e.has(e)}hold(e,t,n){this.#n.set(e,{value:t,holder:n})}moved(e){let t={};for(let[n,{value:r,holder:i}]of this.#n)e(i)&&(t[n]=r);return Object.keys(t).length===0?void 0:t}movesField(e){return this.#n.has(e)}consumes(e){for(let t of this.#e.values())if(t.kind===`field`&&t.producer===e)return!0;return!1}contribute(e,t,n){let r=this.#e.get(e);r&&this.#t.has(e)&&!this.#a(r,t)&&this.reject(new N(n)),this.#e.set(e,t),this.#t.add(e)}requireLiteral(e,t){let n=this.#e.get(e);if(!n||n.kind===`field`)return;let r=this.#i(n);r?.kind===`literal`&&(r.value===null||typeof r.value!=`object`)||this.reject(new M(`Cannot update relation key field '${e}' with a non-literal operation while mutating relation '${t}'. Use a literal value or '{ set: ... }'.`,t,{meta:{operation:`update`,field:e,relation:t}}))}reject(e){if(!this.deferred)throw e;this.#r??=e}activate(){if(this.#r)throw this.#r}absorb(e,t,n,r){let i=this.#e.get(e);if(!i)return;let a=t.known(n);(!a||a.kind!==`literal`||a.value===null||!this.#a(a,i))&&this.reject(new N(r)),this.#e.delete(e),this.#t.delete(e)}writtenFields(){return[...this.#e.keys()]}contributions(){return this.#e}#a(e,t){if(e.kind===`field`&&t.kind===`field`&&e.producer===t.producer&&e.field===t.field)return!0;let n=e.kind===`literal`?this.#i(e):e.producer.known(e.field),r=t.kind===`literal`?this.#i(t):t.producer.known(t.field);return n?.kind===`literal`&&r?.kind===`literal`&&Object.is(n.value,r.value)}select(e){return Object.fromEntries(e.map(e=>[e,this.field(e)]))}},CommandAttempt=class{constructor(e=new TransportAttempt){this.transport=e}rows=new Map;retained=new Set;junctions=new Map;missingChoices=new Map;conditionalSkips=new Map;series=new Map;#e=new Map;bind(e,t){this.#e.set(e,t)}read(e,t){let n=this.#e.get(e);if(n&&Object.hasOwn(n,t))return this.transport.carried(n[t]);let r=e.stated(t);return r?this.#t(r):e.captured&&this.read(e.captured,t)}#t(e){return e.kind===`literal`?e.value:this.read(e.producer,e.field)}resolve(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,this.#t(t)]))}values(e){return Object.fromEntries([...e.contributions()].map(([e,t])=>[e,this.#t(t)]))}select(e,t){return Object.fromEntries([...t].map(t=>[t,this.read(e,t)]))}materialize(e,t){this.bind(e,{...this.#e.get(e),...t})}};function nestedTargetAddressesConstraint(e,t){return e.kind===`junction`||t!==`disconnect`&&t!==`delete`&&t!==`update`}function membershipFields(e){return e.kind===`reference`?[...e.pairs.map(e=>e.source),...e.discriminator?.side===`source`?[e.discriminator.field]:[]]:e.sourceSide.members.map(e=>e.referencedField)}function junctionPairs(e,t,n,r){let i=[];for(let[a,o]of[[e.sourceSide,n],[e.targetSide,r]])if(o)for(let e of a.members)i.push([e.junctionField,t(o,e.referencedField)]);return Object.fromEntries(i)}var Selection=class{kind=`lookup`;fields;facts;selector;#e;#t;origin;retained;membershipOnly;dependent;insertsWhenAbsent;unjudged;execution;model;source;judgement;required;constructor(e,t,n,r,i){this.execution=e,this.model=t,this.source=n,this.required=r;let a=e.context.queries;this.fields=new Assignments(t,`select`);let o=n.selector??a.prepareSelector(t,n.where,n.unique===!0);this.selector=n.purpose===void 0?o:a.candidates(o,n.purpose,void 0,n.judgement),this.judgement=n.judgement??this.selector.judgement,this.facts=i??a.selectorFacts(this.selector),this.#e=a.prepareProjection(t,{select:Object.fromEntries(storedFields(e.context.schema,t).map(e=>[e,!0]))},!0),this.#t=a.prepareProjection(t,{select:Object.fromEntries(e.context.schema.keys(t).map(e=>[e,!0]))},!0)}membership(){return this.source.kind===`query`?this.source.membership:void 0}identityOnly(){let e=this.selector.uniqueKey;return this.selector.scoped===void 0&&e!==void 0&&e===U(this.model).rowKey&&this.facts.keys.size===e.fields.length}#n(e){return e&&{edge:e.edge,parent:this.execution.attempt.select(e.parent,membershipFields(e.edge))}}#r(e,t,n,r=!1){let i=this.execution.context;return i.queries.select(this.model,{take:1},this.#n(t),{forUpdate:!(i.usesBatch||r),identity:n,projection:this.#e,selector:e})}confirm(e,t=this.selector){return this.#r(t,e,this.execution.identity(this.fields))}unrepresentable(e){let t=this.execution.context;return t.queries.select(this.model,{take:1},void 0,{condition:t.driver.adapter.operators.isNull(t.queries.column(this.model,e)),identity:this.execution.identity(this.fields),projection:this.#t})}outsideMembership(e){let t=this.#n(e);return this.execution.context.queries.select(this.model,{take:1},t&&{...t,outside:!0},{projection:this.#t,selector:this.selector})}outsideVerb(){return this.execution.context.queries.select(this.model,{take:1},this.#n(this.membership()),{projection:this.#t,selector:this.unjudged.addressed,unless:this.selector})}query(){let e=this.source.kind===`producer`?this.execution.identity(this.source.producer):void 0;return this.#r(this.selector,this.membership(),e,this.insertsWhenAbsent)}captured(e=this,t=e.membership(),n,r=!1){return this.execution.context.queries.select(this.model,{take:n},this.#n(t),{forUpdate:r,identity:this.execution.identity(this.fields),projection:this.#t,selector:e.selector})}},CommandExecution=class{commands;context;#e;#t=new Set;constructor(e){this.commands=e,this.context=e.context,this.#e=new CommandAttempt(this.context.transportAttempt),this.context.attachRecovery(()=>this.#n(),e=>{let t=this.context.rejectedProducer(e),n=t?this.attempt.missingChoices.get(t):void 0;return!!(n&&e instanceof k&&this.#u(n,e))})}#n(){let e=new CommandAttempt;return this.#e=e,e.transport}get attempt(){return this.#e}identity(e){return this.attempt.select(e,this.context.schema.keys(e.model))}#r(e,t){return this.attempt.select(t,membershipFields(e))}#i(e,t,n){return junctionPairs(e,(e,t)=>this.attempt.read(e,t),t,n)}async#a(e){let t=this.context,n=t.queries,r=t.driver.adapter;for(let i of e.transitions){let a=this.#r(i,e.located.fields),o=this.#r(i,e.fields);for(let e of i.pairs)if(o[e.source]===null)throw new M(`Cannot update relation key field '${e.source}' to null while mutating relation '${i.name}'. A null reference names no row for that relation to point at.`,i.name,{meta:{operation:`update`,field:e.source,relation:i.name}});if(!i.reference||i.reference.onUpdate===`cascade`||i.pairs.some(e=>a[e.source]===null))continue;let s=r.operators.or(...i.pairs.map(t=>r.operators.not(r.operators.eq(n.fieldValue(e.model,t.source,a[t.source]),n.updateValue(e.model,t.source,o[t.source],n.fieldValue(e.model,t.source,a[t.source])))))),c=new M(`Cannot update relation '${i.name}' with onUpdate('${i.reference.onUpdate??`restrict`}') while the current relation is occupied.`,i.name,{meta:t.usesBatch?{relation:i.name}:{operation:`update`,relation:i.name}});t.usesBatch&&(c.meta.raceable=!0),await t.requireAbsent(n.select(i.target,{take:1},{edge:i,parent:a},{condition:s}),c)}}requireRepresentable(e,t,n){if(n===null)throw this.#o(e,t)}#o(e,t){return new M(`Cannot connect relation '${e}': the located target's referenced field '${t}' is null.`,e)}stored(e){let t=this.attempt.values(e);for(let[n,r]of e.contributions())r.kind===`field`&&r.relation!==void 0&&this.requireRepresentable(r.relation,r.field,t[n]);return t}async folded(e,t,n){let r=e.lookup.origin;if(!r)return n;let i=r.operation===`connect`&&e.lookup.membershipOnly===!1?e.lookup.selector:await this.locatedAt(e,t,r.relation);if(!i)return n;let a={...n};for(let o of e.fields.demands)this.requireRepresentable(r.relation,o,n[o]),a[o]=this.context.queries.locatedValue(e.model,o,i,t?.kind===`record`?t.model:void 0);return a}async locatedAt(e,t,n){let r=this.context,i=e.lookup;if(!(r.usesBatch&&i.insertsWhenAbsent))return;let a=this.#s(e,t);if(a.length!==0){for(let e of a)physicalField(r.schema,i.model,e).nullable&&await r.requireAbsent(i.unrepresentable(e),this.#o(n,e));return r.queries.includeIdentities(i.model,[this.identity(i.fields)])}}#s(e,t){if(t?.kind!==`record`)return[];let n=[];for(let r of t.fields.contributions().values())r.kind===`field`&&r.producer===e.fields&&r.relation!==void 0&&n.push(r.field);return n}#c(e,t){let n=e.origin;if(!n||t?.kind!==`record`)return;let r=[];for(let n of e.fields.contributions().values())n.kind===`field`&&n.producer===t.fields&&r.push(n.field);if(r.length===0)return;let i=t.fields;return{model:i.model,where:()=>({...this.identity(i),...this.attempt.select(i,r)}),relation:n.relation,verb:n.operation}}#l(e){for(let t of this.attempt.missingChoices.values())if(t.found?.command.fields===e)return!1;return!0}#u(e,t){let n=e.lookup.selector.uniqueKey,r=e.lookup.selector.uniqueValues;if(!(n&&r)||!n.fields.every(t=>{let n=e.missing?.command.fields.known(t);return n?.kind===`literal`&&Object.is(n.value,r.get(t))}))return!1;let i=e.model[`~`].names.sql,a=n.fields.map(t=>this.context.queries.columnName(e.model,t)),o=K(this.context.driver.adapter).constraints,s=(n.kind===`primary`?o.primaryKey(i,a):o.unique(i,n.name??a[0],a)).normalizedError,c=t.meta;if(c.table!==s.table||c.constraint!==s.constraint)return!1;let l=s.columns;return c.columns===void 0||l===void 0?c.columns===l:c.columns.length===l.length&&c.columns.every((e,t)=>e===l[t])}async#d(e){if(!this.context.replaysInPlace)return!1;let t=this.context.recoveryRejection(e),n=t?.kind===`insert`?this.attempt.missingChoices.get(t.producer):void 0;if(this.attempt.conditionalSkips.get(e)&&t?.kind===`assertion`){let e=this.context.spendRecovery();return e?(this.context.restartRejectedInsert(e),!0):!1}if(!(n&&e instanceof k&&this.#u(n,e)))return!1;let r=this.context.spendRecovery();return r?(this.context.restartRejectedInsert(r),await this.runSelection(n.lookup),this.attempt.rows.has(n.lookup)):!1}async complete(e,t){for(;;)try{return await this.run(e),await this.context.finishOne(this.context.queries.select(e.command.model,{select:t.select,include:t.include,omit:t.omit},void 0,{identity:this.identity(e.command.fields)}))}catch(e){if(!await this.#d(e))throw e}}async runSelection(e,t,n){let r=this.attempt;if(r.rows.has(e))return;let i=e.source;if(i.kind===`producer`&&!this.context.usesBatch&&e.facts.fields.size===0){let t=r.select(i.producer,e.fields.demands);r.rows.set(e,t),r.bind(e.fields,t);return}let a=e.required,o=(e.dependent&&this.context.usesBatch?await this.context.flush(e.query(),t,n??(a&&{query:e.query(),present:!0,failure:a})):await this.context.read(e.query(),!0,!1,e.model))[0];if(!o){if(e.required)throw e.required();let t=e.unjudged;t&&await this.context.requireAbsent(e.outsideVerb(),t.failure());return}r.rows.set(e,o),r.bind(e.fields,o),this.context.usesBatch&&e.retained&&this.context.requirePresent(e.captured(e,e.membership(),void 0,e.insertsWhenAbsent===!0),e.retained())}#f(e,t){let n=e.conditions;return n?()=>n.matched:t?.failure??e.lookup.retained??e.lookup.required??(()=>new F(e.model[`~`].names.ts,`update`))}#p(e,t,n){let r=n?.command,i=e.lookup;if(!(this.context.usesBatch||!this.context.driver.adapter.capabilities.supportsReturning||t||e.conditions||i.membership()||!i.identityOnly()||!r||r.located!==i||r.transitions.length>0||n.children.length>0||r.fields.writtenFields().length===0||r.fields.demands.size===0||r.fields.consumes(i.fields)||[...i.fields.demands].some(e=>!r.fields.demands.has(e))||[...e.fields.demands].some(e=>!r.fields.demands.has(e))))return this.#f(e,t)}async confirmFound(e,t,n){let r=this.context,i=e.lookup;if(r.usesBatch||!(t||i.insertsWhenAbsent))return n;let a=t?.membership??i.membership(),o=e.conditions?.probes??[],s=o[0],c=this.#f(e,t),l=s?o.length===1?s.lookup.selector:r.queries.andSelectors(i.model,o.map(e=>e.lookup.selector)):i.selector,u=(await r.read(i.confirm(a,l),!0,!1,i.model))[0];if(!u)throw c();return this.attempt.materialize(i.fields,u),u}started(e){return this.#t.has(e)}async run(e,t=e.command,n){let r=this.context,i=this.attempt,a=e.command;switch(this.#t.add(e),a.kind){case`record`:{if(a.fields.activate(),e.refusal)throw e.refusal;if(a.located&&!i.rows.has(a.located)&&await this.runSelection(a.located,t),r.usesBatch&&a.located&&!a.located.retained&&!i.retained.has(a.located)){let e=a.requirement?.failure??a.located.required;r.requirePresent(a.located.captured(void 0,a.requirement?.membership??a.located.membership(),1),e?e():new F(a.model[`~`].names.ts,`update`))}await this.#a(a);for(let n of e.children)n.placement===`before`&&await this.run(n,t);let o=a.located&&a.fields.moved(e=>this.#l(e));o&&i.materialize(a.located.fields,i.resolve(o));let s=this.stored(a.fields);i.bind(a.fields,a.located?await r.update(a.model,i.select(a.located.fields,[...r.schema.keys(a.model),...a.fields.demands]),s,t,a.operation,a.fields.demands,n,a.located.judgement,this.#g(a)):await r.insert(a.model,s,a.fields.demands,t,a.operation,a.fields,this.#c(a,e.parent?.command),this.#g(a)));for(let n of e.children)n.placement===`capture`&&await this.run(n,t);let c=e.children;for(let e=0;e<c.length;e++){let n=c[e];if(n.placement!==`after`)continue;let r=[],i=c[e];if(isRecordOccurrence(n))for(;i?.placement===`after`&&this.#m(n.command,i);)r.push(i),i=c[e+r.length];if(r.length<2)await this.run(n,t);else if(e+=r.length-1,await this.#h(r)===void 0)for(let e of r)await this.run(e,t)}return}case`lookup`:await this.runSelection(a,t);return;case`junction`:{if(i.junctions.has(a)||a.address&&!i.rows.has(a.address))return;let e=await r.captureMembership(a.edge,i.resolve(a.values));e&&i.junctions.set(a,e);return}case`absent`:{let e=a.excluding.map(e=>r.queries.lowerIdentity(a.model,this.identity(e))),t=a.restrict,locked=(t,n)=>r.queries.select(a.model,{take:n,select:Object.fromEntries(storedFields(r.schema,a.model).map(e=>[e,!0]))},{edge:a.membership.edge,parent:this.#r(a.membership.edge,a.membership.parent)},{forUpdate:!r.usesBatch,condition:e.length?r.driver.adapter.operators.not(r.driver.adapter.operators.or(...e)):void 0,selector:t});t?.lock&&!r.usesBatch&&await r.read(locked(t.candidates),!0),await r.requireAbsent(locked(t&&this.commands.blocked(t.candidates,t.except===void 0?void 0:{slot:t.except,identity:this.identity(a.membership.parent)}),1),a.failure());return}case`choose`:{let n=a.lookup.source.kind===`producer`;if(r.usesBatch&&n)try{await r.flush(void 0,t)}catch(e){throw r.failure(e,`prefix`,t)}let o=a.foundRequirement,s=o!==void 0&&r.usesBatch&&a.lookup.dependent===!0;try{await this.runSelection(a.lookup,t,s?{query:o.selection.outsideMembership(o.membership),present:!1,failure:o.failure}:void 0);for(let e of a.conditions?.probes??[])await this.runSelection(e.lookup,t)}catch(e){throw n?r.failure(e,`capture`,t):e}let c=i.rows.get(a.lookup),l=this.commands.choiceArm(e,`found`),u=this.commands.choiceArm(e,`missing`);if(c){if(a.conditions?.probes.length&&l){if(l.command.fields.activate(),l.refusal)throw l.refusal;let e=a.conditions.probes.find(e=>!i.rows.has(e.lookup));if(e){r.usesBatch&&(i.conditionalSkips.set(e.skip,a),r.requirePresent(a.lookup.captured(void 0,void 0,1),a.conditions.missingRow),await r.requireAbsent(a.lookup.captured(e.lookup,void 0,1),e.skip)),i.bind(a.fields,c);return}if(r.usesBatch){for(let e of a.conditions.probes)r.requirePresent(a.lookup.captured(e.lookup,void 0,1),e.match);i.retained.add(a.lookup)}}let s=this.#p(a,o,l),u=s?c:await this.confirmFound(a,o,c);l?(r.usesBatch&&n?(r.prepareMembers(()=>[l.command],t),await r.executeMember(()=>this.run(l),l.command)):await this.run(l,t,s),s&&i.materialize(a.lookup.fields,i.select(l.command.fields,a.lookup.fields.demands)),i.bind(a.fields,{...u,...i.select(l.command.fields,a.fields.demands)})):i.bind(a.fields,await this.folded(a,e.parent?.command,u))}else u&&(i.missingChoices.set(u.command.fields,a),await this.run(u,t),i.bind(a.fields,i.select(u.command.fields,a.fields.demands)));return}case`link`:{let e=a.captured&&i.junctions.get(a.captured),n=a.captured,o=n?.edge.uniqueSide===`source`?n.edge.sourceSide:n?.edge.targetSide,s=e&&n&&o?{...e,...Object.fromEntries(o.members.map(e=>[e.junctionField,i.read(n.final,e.referencedField)]))}:e,matches=e=>Object.entries(e).every(([e,t])=>s&&Object.is(s[e],t)),c=s&&a.removals?.some(e=>matches(this.#i(e.edge,e.source,e.target))&&!e.keep.some(t=>matches(this.#i(e.edge,void 0,t))));await r.link(a.edge,i.resolve(a.values),t,c?void 0:s);return}case`remove`:await r.remove(a.edge,a.source?this.#r(a.edge,a.source):void 0,a.target?this.identity(a.target):void 0,a.keep.map(e=>this.identity(e)),t);return;case`delete`:{await this.runSelection(a.located,t);let e=i.rows.get(a.located);if(!e)return;let n=a.located.model;a.values?await r.update(n,e,a.values,t,`delete`):await r.delete(n,e,t);return}case`set`:await r.mutateMembers(a.edge,this.#r(a.edge,a.parent),a.selector,a.values,t);return;case`captureSeries`:await this.captureSeries(this.commands.seriesCaptureTarget(e),t);return;case`series`:await this.#_(e.children.filter(isRecordOccurrence),t);return;case`selectedSeries`:isSeriesOccurrence(e)&&await this.#w(e);return;case`membership`:return}}async records(e,t,n){let{count:r,identities:i}=await this.#_(e,n,t!==void 0);return t?i.length===0?this.context.finishMany([]):this.context.finishMany(this.context.seriesQueries(this.context.queries.prepareProjection(e[0].command.model,{select:t}),i)):this.context.finishValue({count:r})}#m(e,t){if(!isRecordOccurrence(t))return!1;let{command:n,children:r,refusal:i}=t,a=e.fields.writtenFields(),o=n.fields.writtenFields();return n.model===e.model&&n.fields.operation===`create`&&n.fields.demands.size===0&&o.length===a.length&&o.every((e,t)=>e===a[t])&&!n.suppression&&!n.located&&r.length===0&&i===void 0}#h(e){let[t]=e;return this.context.insertMany(t.command.model,()=>{for(let{command:t}of e)t.fields.activate();return e.map(({command:e})=>this.stored(e.fields))},this.#g(t.command))}#g(e){let t=e.origin??e.located?.origin;return t&&nestedRefusal(t.operation,t.relation)}async#_(e,t,n=!1){let r=this.context,i=r.prepareMembers(()=>e,t),a=[],o=i[0];if(!n&&i.length>1&&o&&i.every(e=>this.#m(o.command,e))){let e=await this.#h(i);if(e!==void 0)return{count:e,identities:a}}let s=0;for(let e of i){let t=e.command,i=!0;if(t.suppression?i=await r.executeSkippableMember(()=>this.run(e),t.fields,t):await r.executeMember(()=>this.run(e),t),!i){await r.executeMember(()=>this.#v(e),t);continue}s++,n&&a.push(this.identity(t.fields))}return{count:s,identities:a}}async#v(e){let t=e.command;if(e.children.some(({command:e})=>e.kind===`link`&&e.edge.scope.edge.kind===`variantJunctionCarrier`&&e.edge.uniqueSide!==void 0))return;for(let t of e.children)if(t.command.kind!==`link`&&t.command.kind!==`remove`&&t.command.kind!==`junction`)return;let n=await this.#y(t);if(n){this.attempt.bind(t.fields,n);for(let n of e.children)n.placement!==`before`&&await this.run(n,t)}}async#y(e){let t=this.context,spelled=t=>{let n={};for(let r of t){let t=e.fields.known(r);if(!e.fields.isRequested(r)||t?.kind!==`literal`||t.value===null)return;n[r]=t.value}return n},n=spelled(t.schema.keys(e.model));if(!n){let t=U(e.model).addressableKeys.filter(e=>e.kind!==`primary`).map(e=>spelled(e.fields)).filter(e=>e!==void 0);if(t.length!==1)return;n=t[0]}let r=this.commands.lookup(e.model,{kind:`query`,selector:t.queries.identitySelector(e.model,n)});return await this.runSelection(r,e),this.attempt.rows.get(r)}async series(e,t=e.command.series.selection,n){let r=(await this.captureSeries(e,t)).members,i=n?r.map(({command:e})=>e.fields):[],a=await this.#w(e),o=i.map(e=>this.identity(e));return n?o.length===0?this.context.finishMany([]):this.context.finishMany(this.context.seriesQueries(n,o,`updateMany`)):(await this.context.finish(),a)}async#b(e,t,n){let r=this.context,i=e.selection,a=r.queries.andSelectors(i.model,[...i.selector?[i.selector]:[],r.queries.excludeIdentities(i.model,n.map(e=>r.schema.identity(i.model,e)))]),o=membershipRaceFailure(e.mutation.kind,t.edge.name,`added`);await r.requireAbsent(r.queries.select(i.model,{take:1},{edge:t.edge,parent:this.#r(t.edge,t.parent)},{selector:a}),o)}async captureSeries(e,t){let n=this.context,r=this.attempt,i=r.series.get(e);if(i)return i;let a=e.command.series,o=a.selection,s=o.membership(),c;if(s){let{edge:e,parent:i}=s,o=new M(`Cannot ${a.mutation.kind} relation '${e.name}': parent record changed across a committed segment.`,e.name),parentWhere=()=>({...this.identity(i),...this.#r(e,i)}),l=await n.flush(n.queries.select(i.model,{where:parentWhere(),select:Object.fromEntries([...i.demands].map(e=>[e,!0]))}),t);if(!l[0])throw n.failure(o,`result`,t);r.bind(i,l[0]),c={failure:o,query:n.queries.select(i.model,{where:parentWhere(),select:Object.fromEntries(n.schema.keys(i.model).map(e=>[e,!0]))})}}let l=n.queries.keyOrder(o.model),u=await n.read(n.queries.select(o.model,{orderBy:Object.fromEntries(l.map(e=>[e,`asc`])),take:a.limit},s&&{edge:s.edge,parent:this.#r(s.edge,s.parent)},{forUpdate:!n.usesBatch,selector:o.selector}),!0,!1,o.model);if(a.mutation.kind===`update`){let e=this.#C(o.model,a.mutation.raw,u.length);if(e)throw n.failure(e,`planning`,t)}s&&c&&n.usesBatch&&(n.requirePresent(c.query,c.failure),await this.#b(a,s,u));let d=n.prepareMembers(()=>u.map(e=>{let t=this.commands.capture(o,e);if(r.rows.set(t,e),r.bind(t.fields,e),a.mutation.kind===`delete`){n.usesBatch&&s&&(n.requirePresent(t.captured(void 0,s,1),membershipRaceFailure(a.mutation.kind,s.edge.name,`removed`)),r.retained.add(t));let e=a.mutation.raw;return{kind:`delete`,located:t,origin:a.mutation.origin,...e&&{values:this.commands.stamp(o.model,`update`,this.#x(o,s,e))}}}let i=this.commands.update(t,this.#x(o,s,a.mutation.raw),a.mutation.raw);return s&&(i.requirement={selection:t,membership:s,failure:o.required}),i}),t),f=this.commands.expandSeries(e,d);if(f)throw n.failure(f.error,`planning`,f.member);let p={members:this.commands.seriesMembers(e),parentRequirement:c};return r.series.set(e,p),p}#x(e,t,n){let r=this.context.scope?.rows.stamps;return r===void 0?this.#S(e,t,n):T(r,()=>this.#S(e,t,n))}#S(e,t,n){let r=this.context.schema;return t&&t.edge.scope.edge.kind!==`variantRowCarrier`&&t.edge.scope.edge.kind!==`variantJunctionCarrier`?r.member(t.edge.source,t.edge.name,n):r.update(e.model,n,!0)}#C(e,t,n){if(!(n<2))for(let r of e[`~`].relationNames){let i=t[r];if(i===void 0)continue;let a=e[`~`].state.relations[r][`~`].state.target.kind===`variants`;for(let t of[`connect`,`connectOrCreate`,`set`]){let o=record(i)[t];if(o!==void 0)for(let i of entries(o)){let o=this.context.schema.membership(e,r,a?i.type:void 0),s=o.kind===`junction`?o.uniqueSide===`target`&&`that target's member-junction slot can belong to only one of them`:o.owner===`target`&&`that membership is stored on the target row, which can belong to only one of them`;if(s)return new N(`updateMany matched ${n} rows, so it cannot apply '${t}' to relation '${r}': ${s} — the last row updated would take it from the others. Narrow the filter (or add 'limit: 1') so exactly one row matches, or write this relation in a separate call.`)}}}}async holdMember(e,t,n){if(!n)return;let r=this.context,i=n.edge,a=e.kind===`delete`?()=>membershipRaceFailure(`delete`,i.name,`removed`):e.requirement?.failure??t.required;if(r.usesBatch&&(r.requirePresent(t.captured(void 0,n,1,!0),a()),this.attempt.retained.add(t)),i.kind!==`junction`)return;let o=r.queries.junction(i,this.#i(i,n.parent,t.fields),!0);if(r.usesBatch){r.requirePresent(o,a());return}if(!(await r.read(o,!0))[0])throw a()}async#w(e){let t=this.context,{members:n,parentRequirement:r}=this.attempt.series.get(e),i=e.command.series.selection.membership();for(let e of n){let n=e.command,a=n.located;if(t.usesBatch){this.attempt.rows.delete(a);try{await this.runSelection(a)}catch(e){throw t.failure(e,`planning`,n)}}await t.executeMember(async()=>{t.usesBatch&&r&&t.requirePresent(r.query,r.failure),await this.holdMember(n,a,i),await this.run(e)},n)}return n.length}};const kn=[`disconnect`,`delete`,`create`,`connect`,`connectOrCreate`,`upsert`,`update`,`set`,`updateMany`],An=[`disconnect`,`delete`,`set`,`updateMany`,`deleteMany`,`update`,`upsert`,`connectOrCreate`,`connect`,`create`,`createMany`];function missingTarget(e,t,n=!0){return new M(`Cannot ${e} relation '${t}': target record was not found${n?` for this parent`:``}.`,t)}function sameTarget(e,t){return e.size===t.size&&[...e].every(([e,n])=>t.has(e)&&Object.is(t.get(e),n))}var RelationBody=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e,t,n,r,i){this.#r=e,this.#i=t,this.#a=n,this.#o=r,this.#s=i,this.#t=!n.member&&(n.edge.kind===`variantRowCarrier`||n.edge.kind===`variantJunctionCarrier`),this.#n=[`create`,`connect`,`connectOrCreate`,`upsert`].some(e=>r[e]!==void 0)}#c(e){this.#t||(this.#e=e.kind===`choose`&&!e.missing?{kind:`query`,selector:e.lookup.selector}:{kind:`producer`,producer:e.fields})}#l(e,t,n){let r=this.#i;return this.#r.create(e.target,t,n,e.kind===`reference`&&e.owner===`target`?{edge:e,source:r.fields}:void 0,r.operation??r.fields.operation,r.fields.deferred)}expand(){let e=this.#i,t=this.#a,n=t.slot.field,r=this.#o,i=this.#s,a=this.#t,o=this.#r.context.schema,s=e.model[`~`].state.relations[n][`~`].state.cardinality===`many`?An:kn,c=new Map,membership=t=>{let r=c.get(t);if(r)return r;if(r=bindMembership(o,e.model,n,t),c.set(t,r),e.fields.operation===`update`&&r.kind===`reference`){let t=o.keys(e.model);for(let n of r.pairs)(r.owner===`source`||!t.includes(n.source))&&e.fields.requireLiteral(n.source,r.name)}return r},l=Object.entries(r).sort(([e],[t])=>s.indexOf(e)-s.indexOf(t));for(let[r,s]of l){if(s===void 0)continue;let c=this.#r.createOrigin(n,r),entryOrigin=()=>this.#r.createOrigin(n,r);if(!a){this.#u(membership(),r,s,i[r],c);continue}if(t.edge.kind===`variantRowCarrier`&&r===`disconnect`&&typeof s==`boolean`){let r=o.clearability(t);if(s&&!this.#n&&r.kind===`columns`){let i=this.#r.place(e,{kind:`membership`},`before`),a={origin:c,scope:t,identity:e.located?.facts};for(let t of r.fields)e.fields.contribute(t,{kind:`literal`,value:null},`Cannot disconnect relation '${n}'.`);this.#r.publishMembership(i,e.fields,a)}continue}if(r===`set`){let e=t.edge,n=entries(s).map(e=>{let t=membership(e.type);return{edge:t,target:this.#h(t,[record(e.where)],c)[0]}});for(let t of e.members)this.#g(membership(t.variant),[],c);for(let{edge:e,target:t}of n)this.association(e,t);continue}for(let[e,t]of entries(s).entries()){let n=entryOrigin(),a=entries(i[r])[e],o=membership(t.type),untag=e=>r===`create`?e.data:r===`connect`||r===`delete`||r===`disconnect`?e.where:e;this.#u(o,r,untag(t),untag(a),{...n,relation:o.name})}}}#u(e,t,n,r,i){let a=this.#i,o=this.#n,entryOrigin=()=>this.#r.createOrigin(i.relation,i.operation,i.slot);switch(a.fields.operation===`update`&&e.kind===`reference`&&e.owner===`target`&&e.pairs.some(e=>a.fields.writesField(e.source))&&!a.transitions.includes(e)&&a.transitions.push(e),t){case`disconnect`:case`delete`:{if(n===!1)break;let r=n===!0;for(let i of r?[void 0]:entries(n)){let n=entryOrigin(),s=nestedTargetAddressesConstraint(e,t),c=t===`delete`?this.#r.tombstone(e.target):void 0,l=this.#r.context.queries,u=l.prepareSelector(e.target,i,s),d=this.#r.lookup(e.target,{kind:`query`,where:i,unique:s,selector:this.#r.candidates(u,`related`,c!==void 0,t===`delete`?jn:linkJudgement(e)),membership:{edge:e,parent:a.located.fields}},r?void 0:()=>missingTarget(t,e.name));d.origin=n,r&&t===`delete`&&l.domainOf(e.target,`related`,jn)!==l.domainOf(e.target,`related`)&&(d.unjudged={addressed:e.kind===`reference`&&e.owner===`source`?u:this.#r.candidates(u,`related`,c!==void 0),failure:()=>missingTarget(t,e.name)}),this.#v(e,a.located.fields),r&&(d.retained=()=>membershipRaceFailure(t,e.name,`removed`));let f=this.#f(d),p={kind:`delete`,located:d,origin:n,...c&&{values:c.admitted}};if(c&&this.#d(e,a.located.fields,d.selector,n),e.kind===`reference`&&e.owner===`source`){if(!(o||c)&&e.clearability.kind===`columns`){let t={origin:n,scope:e.scope,identity:a.located?.facts};for(let t of e.clearability.fields)a.fields.contribute(t,{kind:`literal`,value:null},`Cannot disconnect relation '${e.name}'.`);this.#r.publishMembership(f,a.fields,t)}t===`delete`&&this.#r.place(a,p,`after`,n)}else{let i={kind:`remove`,edge:e,source:a.fields,target:r?void 0:d.fields,keep:[],origin:n};t===`delete`&&e.kind===`junction`&&!c&&this.#r.place(a,i,`after`,n),this.#r.place(a,t===`delete`?p:i,`after`,n)}}break}case`create`:for(let[t,i]of entries(n).entries()){let n=entryOrigin(),a=this.#l(e,i,entries(r)[t]);a.origin=n,this.association(e,a),this.#c(a)}break;case`createMany`:{let t=record(n);t.skipDuplicates&&this.#r.context.admitsSuppression(`nested createMany rows`);let o=entries(record(r).data),s=entries(t.data).map((n,r)=>{let a=this.#l(e,n,o[r]);return a.origin=i,t.skipDuplicates&&(a.suppression={kind:`skipDuplicate`}),this.association(e,a,!1,a)});this.#r.place(a,{kind:`series`,records:s},`after`,i);break}case`connect`:case`connectOrCreate`:case`upsert`:case`update`:{let i=[],o=[];for(let[s,c]of entries(n).entries()){let n=entryOrigin(),l=entries(r)[s],u=t===`connect`?{where:c}:c,d=t===`upsert`?u.update:u.data,f=this.#r.context.schema.keyPortabilityRefusal(e.target,d);if(f&&t!==`upsert`)throw f;let p=u.create===void 0?void 0:this.#l(e,record(u.create),record(l.create));p&&(p.origin=n);let m=(t===`update`||t===`upsert`)&&a.fields.operation===`update`,h=t===`update`&&!e.many?this.#e:void 0,g=h?.kind===`query`?h:void 0,_=this.#r.context.queries,v=_.prepareSelector(e.target,u.where,nestedTargetAddressesConstraint(e,t)),y=v.uniqueValues;if(t===`connect`){let e=_.selectorFacts(v);if(e.exact&&Object.keys(record(u.where)).every(t=>e.fields.has(t)||v.uniqueKey?.name===t)){if(o.some(t=>sameTarget(t,e.equals)))continue;o.push(e.equals)}}if(t===`connectOrCreate`&&y){if(i.some(e=>sameTarget(e,y)))continue;p&&[...y].every(([e,t])=>{let n=p.fields.known(e);return n?.kind===`literal`&&Object.is(n.value,t)})&&i.push(y)}let b=record(t===`upsert`?l.update:l.data??l),x=t===`update`||t===`upsert`?this.#r.judge(e.target,record(d),b,t):linkJudgement(e),S={kind:`query`,where:u.where,selector:v,purpose:`related`,judgement:x},ee;if(g){let t=g.selector,n=_.selectorFacts(v),r=_.selectorFacts(t);ee=n.fields.size===0?r:n;let i=_.andSelectors(e.target,[t,v]);S={kind:`query`,selector:x?_.candidates(i,`related`,void 0,x):i}}h?.kind===`producer`&&(S={kind:`producer`,where:S.where,selector:S.selector,producer:h.producer,purpose:S.purpose,judgement:S.judgement},h.producer.select(storedFields(this.#r.context.schema,e.target)));let C,te;if(m&&!h){let n=e.kind===`reference`?e.pairs.map(e=>({...e,value:a.fields.known(e.source)??a.located.fields.field(e.source)})):[];te=Object.fromEntries(n.map(({target:e,value:t})=>[e,t]));let r={edge:e,parent:this.#_(e,t,Object.fromEntries(n.map(({source:e,value:t})=>[e,t])))};this.#v(e,r.parent),t===`upsert`&&u.where!==void 0?C=r:S={kind:`query`,where:S.where,selector:S.selector,membership:r,purpose:S.purpose,judgement:S.judgement}}let w=this.#r.lookup(e.target,S,t===`connect`||t===`update`?()=>missingTarget(t,e.name,t===`update`):void 0,ee);w.origin=n,p&&(w.insertsWhenAbsent=!0),t===`connectOrCreate`&&(w.retained=()=>new M(`Record was replaced by another transaction during nested connectOrCreate`,e.name)),w.membershipOnly=t===`connect`&&!(e.kind===`reference`&&e.owner===`source`),t===`connect`&&!w.membershipOnly&&(w.retained=w.required),this.#t&&t===`connect`&&this.#f(w),m&&!h&&t===`update`&&e.kind===`junction`&&this.#f(w);let T=C&&{selection:w,membership:C,failure:()=>missingTarget(`upsert`,e.name)},ne=new Assignments(e.target,`select`,{},{},void 0,p?[p.fields]:[]);for(let[e,t]of Object.entries(te??{}))ne.restate(e,t);let E={kind:`choose`,model:e.target,lookup:w,foundRequirement:T,missing:p?this.#r.occurrence(p,`after`):void 0,fields:ne,found:t===`upsert`||t===`update`?this.#r.occurrence(this.#r.update(w,record(d),b,!0,t===`upsert`?`upsert`:`update`),`after`):void 0};E.found&&(E.found.command.origin=n,E.found.command.requirement=T,f&&E.found.command.fields.reject(f)),this.association(e,E,m),this.#c(E)}break}case`set`:this.#m(e,entries(n),i);break;case`updateMany`:case`deleteMany`:{let i=entries(r);a.fields.select(this.#r.context.schema.keys(a.model)),this.#v(e,a.fields);for(let[r,o]of entries(n).entries()){let n=entryOrigin(),s=record(o),c=this.#r.context.schema.keyPortabilityRefusal(e.target,s.data);if(c)throw c;let l=t===`updateMany`?s.where===void 0?void 0:record(s.where):record(s.where??s),u=this.#r.context,d=t===`deleteMany`?this.#r.tombstone(e.target):void 0,f=this.#r.candidates(u.queries.prepareSelector(e.target,l),`related`,d!==void 0,t===`deleteMany`?jn:this.#r.judge(e.target,record(s.data),record(i[r].data))),p=d?d.admitted:record(s.data);if(e.kind===`reference`&&(t===`deleteMany`||!u.schema.namesRelation(e.target,p))){let o={kind:`set`,edge:e,parent:a.fields,model:e.target,selector:f,...t===`updateMany`||d?{values:d?p:this.#r.stamp(e.target,`update`,p,record(i[r].data))}:{},operation:t,origin:n};d&&this.#d(e,a.fields,f,n,!0),this.#r.place(a,o,`after`,n);continue}let m=this.#r.lookup(e.target,{kind:`query`,where:l,selector:f,membership:{edge:e,parent:a.fields}},()=>missingTarget(t===`updateMany`?`update`:`delete`,e.name));m.origin=n;let h=t===`updateMany`?{kind:`update`,raw:record(i[r].data)}:{kind:`delete`,origin:n,...d&&{raw:d.raw}},g=h.kind===`update`?this.#r.update(m,p,h.raw,!0):{kind:`delete`,located:m,origin:n,...d&&{values:d.admitted}};g.kind===`record`&&(g.origin=n);let _={selection:m,analysis:g,mutation:h};d&&this.#d(e,a.fields,f,n);let v=this.#r.place(a,this.#r.selectedSeries(_),`after`,n);this.#p(v)}break}default:jt(t,`relation verb`)}}#d(e,t,n,r,i){let a=this.#r,o=a.context.schema,s=o.restrictingSlots(e.target);if(s.length===0)return;let c=s.find(t=>o.index.get(e.target)?.get(t)?.edge===e.scope.edge&&!(e.target===e.source&&t===e.name)),l={kind:`absent`,model:e.target,membership:{edge:e,parent:t},excluding:[],failure:a.restrictFailure(e.target),restrict:{candidates:n,except:c,lock:i}};a.place(this.#i,l,`after`,r)}#f(e){let t=this.#i;return e.kind===`lookup`&&(e.retained??=e.required),this.#r.place(t,e,`before`)}#p(e){let t={kind:`captureSeries`,target:e};this.#r.place(this.#i,t,`capture`)}#m(e,t,n){let r=this.#h(e,t,n);this.#g(e,r,n);for(let t of r)this.association(e,t)}#h(e,t,n){return t.map(t=>{let r=this.#r.lookup(e.target,{kind:`query`,where:t,unique:nestedTargetAddressesConstraint(e,`set`),purpose:`related`,judgement:linkJudgement(e)},()=>missingTarget(`set`,e.name,!1));r.origin=n,this.#f(r);let i={kind:`choose`,model:e.target,lookup:r,fields:new Assignments(e.target,`select`)};return i.lookup.fields.select(this.#r.context.schema.keys(e.target)),i})}#g(e,t,n){let r=this.#i;if(e.kind===`reference`)if(e.clearability.kind===`none`){let i=[...e.discriminator?.side===`target`?[e.discriminator.field]:[],...e.pairs.map(e=>e.target)];this.#v(e,r.located.fields);let a={kind:`absent`,model:e.target,membership:{edge:e,parent:r.located.fields},excluding:t.map(e=>e.lookup.fields),failure:()=>new M(`Cannot set relation '${e.name}' because foreign key field(s) ${i.join(`, `)} are required: rows removed from the set cannot be disconnected. Delete them instead.`,e.name)};this.#r.place(r,a,`before`,t.at(-1)?.lookup.origin??n)}else this.#r.place(r,{kind:`remove`,edge:e,source:r.fields,keep:t.map(e=>e.lookup.fields),origin:n},`after`,n);else this.#r.place(r,{kind:`remove`,edge:e,source:r.fields,keep:[],origin:n},`after`,n)}association(e,t,n=!1,r){let i=this.#i,a=e.kind===`reference`&&e.owner!==`source`&&t.kind===`choose`&&!n?{edge:e,target:t}:void 0;if(a&&!a.target.found){let{lookup:e}=a.target;a.target.found=this.#r.occurrence(this.#r.update(e,Mn,{},!0),`after`)}t.kind===`choose`&&t.found&&t.lookup.insertsWhenAbsent&&t.foundRequirement===void 0&&t.found.command.fields.select(this.#r.context.schema.keys(t.model)),t.kind===`choose`&&t.found&&t.fields.forward(t.found.command.fields);let o=t.kind===`choose`?t.lookup.origin:t.origin,s=a?.target.found;if(a&&s){let{edge:e,target:t}=a;s.command.origin??=t.lookup.origin;for(let t of e.pairs)s.command.fields.absorb(t.target,i.fields,t.source,`Relation '${e.name}' owns '${e.pairs.map(e=>e.target).join(`, `)}'; omit it from nested create and update data.`)}let c=e.kind===`reference`&&e.owner===`source`?`before`:`after`,l=r?this.#r.occurrence(t,`root`):this.#r.place(i,t,c,o);if(e.kind===`reference`&&e.owner===`source`){let r=o?{origin:o,scope:e.scope,identity:i.located?.facts}:void 0;return this.#r.assignMembership(e,i.fields,t.fields,{carried:n&&t.kind===`choose`?t.found?.command.fields:void 0,requested:!n||t.kind===`choose`&&t.missing!==void 0}),r&&this.#r.publishMembership(l,i.fields,r),l}if(a&&s){let{edge:e}=a,t=o?{origin:o,scope:e.scope,identity:s.command.located?.facts}:void 0;this.#r.assignMembership(e,s.command.fields,i.fields),t&&this.#r.publishMembership(l,s.command.fields,t);for(let t of e.pairs)i.fields.field(t.source)}if(e.kind===`junction`&&!n){let n,a=e.uniqueSide===`source`?i.located:e.uniqueSide===`target`&&t.kind===`choose`?t.lookup:void 0;if(a){let r=e.uniqueSide===`source`?e.sourceSide:e.targetSide;n={kind:`junction`,edge:e,address:a,final:e.uniqueSide===`source`?i.fields:t.fields,values:Object.fromEntries(r.members.map(e=>[e.junctionField,a.fields.field(e.referencedField)]))},a!==i.located&&this.#f(a),this.#f(n)}else r&&e.uniqueSide===`target`&&t.kind===`record`&&e.targetSide.members.every(e=>t.fields.known(e.referencedField)?.kind===`literal`)&&(n={kind:`junction`,edge:e,final:t.fields,values:Object.fromEntries(e.targetSide.members.map(e=>[e.junctionField,t.fields.field(e.referencedField)]))},this.#r.place(r,n,`before`));let s=i.body.map(e=>e.command).filter(t=>t.kind===`remove`&&t.edge.kind===`junction`&&t.edge.table===e.table);for(let e of s){this.#y(e.edge,e.source,e.target);for(let t of e.keep)this.#y(e.edge,void 0,t)}this.#r.place(r??i,{kind:`link`,edge:e,values:this.#y(e,i.fields,t.fields),captured:n,removals:s,origin:o},`after`,o)}else e.kind===`junction`&&t.kind===`choose`&&t.missing&&this.#r.place(t.missing.command,{kind:`link`,edge:e,values:this.#y(e,i.fields,t.missing.command.fields),origin:o},`after`,o);return l}#_(e,t,n){let r=this.#i,i=r.located.fields;if(e.kind===`junction`)return i;if(e.owner!==`source`||t===`update`)return r.fields;let a=new Assignments(r.model,`select`,{},{},i,[i]);for(let[e,t]of Object.entries(n))a.restate(e,t);return a}#v(e,t){return t.select(membershipFields(e))}#y(e,t,n){return junctionPairs(e,(e,t)=>e.field(t),t,n)}};function bulkProjection(e,t,n){return n.select?e.queries.prepareProjection(t,{select:n.select}):void 0}function membershipRaceFailure(e,t,n){let r=new M(`Cannot ${e} relation '${t}': a member was ${n} after the plan-time read; retry to converge.`,t);return r.meta.raceable=!0,r}function dependsOn(e,t,n,r){return new M(`Nested operation '${e}' on relation '${t}' depends on an earlier ${n} in the same nested write. Split these operations into separate queries.`,t,{meta:{operation:e,...r}})}const jn=Object.freeze({verb:`delete`,writes:Object.freeze([])});function isRecordOccurrence(e){return e.command.kind===`record`}function isSeriesOccurrence(e){return e.command.kind===`selectedSeries`}const Mn=Object.freeze({});var Commands=class{#e=0;execution;context;constructor(e){this.context=e,this.execution=new CommandExecution(this)}create(e,t,n=t,r,i=`create`,a=!1){let o={kind:`record`,model:e,operation:i,body:[],transitions:[],fields:new Assignments(e,`create`,this.stamp(e,`create`,t,n),n,void 0,[],a)};return r&&this.assignMembership(r.edge,o.fields,r.source),this.#t(o,t,n),o}update(e,t,n,r=!1,i=`update`){let a=e.model,o={kind:`record`,model:a,located:e,body:[],transitions:[],fields:new Assignments(a,`update`,t===Mn?this.context.schema.scalars(a,this.context.schema.update(a,{},!0)):i===`upsert`&&Object.keys(n).length===0?{}:this.stamp(a,`update`,t,n),n,e.fields,void 0,r)};for(let t of this.context.schema.keys(a))e.fields.field(t);return this.#t(o,t,n),o}#t(e,t,n){for(let r of e.model[`~`].relationNames)t[r]!==void 0&&new RelationBody(this,e,this.context.schema.index.get(e.model).get(r),record(t[r]),record(n[r])).expand()}tombstone(e){let t=this.context.scope,n=t?.rows.tombstones?.get(e[`~`].names.ts);if(!(t&&n))return;let r=n.at===void 0?n.assign:{...n.assign,[n.at]:t.instant()};return{raw:r,admitted:this.stamp(e,`update`,this.context.schema.update(e,r,!0))}}stamp(e,t,n,r={}){let i=e[`~`].names.ts,a=this.context.scope?.rows.stamps?.get(i)?.[t];if(a===void 0)return this.context.schema.scalars(e,n);let o=new Set;for(let[t,{edge:n}]of this.context.schema.index.get(e))if(!(r[t]===void 0||n.kind!==`foreignKey`)&&!(n.owner.source!==e||n.owner.field!==t))for(let{foreignField:e}of n.reference.members)o.add(e);let s={};for(let[e,t]of Object.entries(a))r[e]===void 0&&!o.has(e)&&(s[e]=t instanceof S?this.context.scope.instant():t);let c=t===`create`?this.context.schema.createValues(e,s):this.context.schema.update(e,s,!0);return this.context.schema.scalars(e,{...n,...c})}judge(e,t,n,r=`update`){let i=e[`~`].names.ts,a=this.context.scope?.rows;if(!a?.domain.verbs?.has(i))return;let o=[],s=this.context.schema.index.get(e);for(let[t,r]of Object.entries(n)){if(r===void 0)continue;let n=s.get(t)?.edge;if(n===void 0){o.push(t);continue}let i=Object.keys(record(r));if(n.kind===`junction`||n.kind===`variantJunctionCarrier`)i.some(e=>e!==`update`&&e!==`updateMany`)&&o.push(t);else if(i.some(e=>e!==`update`)){let r=n.kind===`foreignKey`?n.owner:n.carrier;if(r.source!==e||r.field!==t)continue;if(o.push(t),n.kind===`foreignKey`)for(let{foreignField:e}of n.reference.members)o.push(e)}}if(o.length>0){let e=a.tombstones?.get(i);return e!==void 0&&o.some(t=>t===e.at||Object.hasOwn(e.assign,t))?{verb:`update`,writes:o,marks:!0}:{verb:`update`,writes:o}}return(Object.keys(a.stamps?.get(i)?.update??{}).length>0||e[`~`].scalarFieldNames.some(e=>t[e]!==void 0))&&(r===`update`||Object.keys(n).length>0)?{verb:`update`,writes:o}:void 0}candidates(e,t,n,r){let i=this.context.scope,a=this.context.queries,o=a.candidates(e,t,void 0,r);return n&&i&&i.defaults!==i.domain?a.candidates(o,t,i.defaults):o}blocked(e,t){let n=e.model,r=this.context.schema.restrictingSlots(n);if(r.length===0)return;let i=this.context.queries;return i.andSelectors(n,[e,i.referenced(n,r,this.context.scope?.defaults,t)])}restriction(e){return{kind:`foreignKey`,message:`Cannot delete '${e[`~`].names.ts}' record: a related record still references it through one of its relations whose foreign key restricts deletes: ${this.context.schema.restrictingSlots(e).map(e=>`'${e}'`).join(`, `)}.`,raceable:!1}}restrictFailure(e){let t=this.restriction(e);return()=>createFailureError(t,e[`~`].names.ts,this.context.operation)}createOrigin(e,t,n=e){return{relation:e,operation:t,slot:n,order:this.#e++}}occurrence(e,t=`root`){return{kind:`occurrence`,command:e,placement:t,children:[]}}place(e,t,n,r=this.#i(t)){let i=this.occurrence(t,n),a=r?.order??-1,placementOrder=e=>e===`before`?0:e===`capture`?1:2,o=e.body.findIndex(e=>{let t=this.#i(e.command)?.order??-1;return t>a||t===a&&placementOrder(e.placement)>placementOrder(n)});return e.body.splice(o<0?e.body.length:o,0,i),i}#n(e){return e.kind===`record`?e.body:e.kind===`choose`?[e.found,e.missing].filter(e=>e!==void 0):e.kind===`series`?e.records:e.kind===`selectedSeries`?[e.template]:[]}#r(e){let role=(e,t)=>{if(e.kind===`choose`)return t===e.found?`found`:`missing`;if(e.kind===`selectedSeries`)return`template`},t=this.#n(e.command),n=new Map;e.children=t.map(t=>{let r=this.occurrence(t.command,t.placement);return r.role=role(e.command,t),n.set(t,r),r});for(let[e,t]of n)e.command.kind===`captureSeries`&&(t.captureTarget=n.get(e.command.target));for(let t of e.children)this.#r(t)}#i(e){if(e.kind===`choose`)return e.lookup.origin;if(e.kind===`captureSeries`)return e.target.command.series.selection.origin;if(e.kind===`selectedSeries`)return e.series.selection.origin;if(e.kind===`junction`)return e.address?.origin;if(e.kind===`record`||e.kind===`delete`||e.kind===`set`||e.kind===`lookup`||e.kind===`link`||e.kind===`remove`)return e.origin}assignMembership(e,t,n,r={}){for(let i of e.pairs){let a=e.owner===`source`?i.source:i.target,o=e.owner===`source`?i.target:i.source,s=n.known(o);n.operation===`create`&&(!n.writesField(o)||s?.kind===`literal`&&s.value===null)&&(physicalField(this.context.schema,n.model,o).scalar[`~`].state.autoGenerate||t.reject(new N(`Cannot create relation '${e.name}': referenced field '${o}' must be supplied by the parent record or generated by the database.`)));let c={...n.field(o),relation:e.name};r.carried?.writesField(o)&&!t.writesField(a)&&t.hold(a,c,r.carried),r.requested!==!1&&t.contribute(a,c,`${t.operation} assigns conflicting values to column '${this.context.queries.columnName(t.model,a)}' through relation '${e.name}'.`)}e.discriminator&&r.requested!==!1&&t.contribute(e.discriminator.field,{kind:`literal`,value:e.discriminator.value},`Conflicting stored discriminator for relation '${e.name}'.`)}publishMembership(e,t,n){(e.command.membershipPublications??=[]).push({carrier:t,identity:n.identity,contribution:n})}analyze(e){let t=this.occurrence(e);return this.#r(t),this.#d(t),this.#w(t),t}analyzeSeries(e){return this.analyze(this.selectedSeries(e))}selectedSeries(e){return{kind:`selectedSeries`,series:e,template:this.occurrence(e.analysis)}}membershipPublications(e){return e.command.membershipPublications??[]}choiceArm(e,t){if(e.command.kind!==`choose`)return;let n=e.children.find(e=>e.role===t);return n&&isRecordOccurrence(n)?n:void 0}seriesMembers(e){return e.children.filter(e=>e.role===`member`&&(e.command.kind===`record`||e.command.kind===`delete`))}seriesCaptureTarget(e){return e.captureTarget}#a(t,n){let{lookup:r,owner:i}=n,a=n.membership??r.membership();if(!(r.origin&&a))return;let o=t.command;if(o?.kind===`record`&&(o.fields.operation===`create`||o.fields.writtenFields().length>0)){let s=a.edge,parentKey=e=>{let t=a.parent.known(e);return t?.kind===`literal`?t.value:a.parent===i.command.fields?i.command.located?.facts.equals.get(e):void 0},c=e(e=>this.#c(o,e,t.occurrence),`literal`),l=!1,u=!1;if(s.kind===`reference`&&s.owner===`target`){for(let e of s.pairs){if(!o.fields.writesField(e.target)||(l=!0,o.fields.operation!==`create`))continue;let t=c(e.target),n=parentKey(e.source);t!==void 0&&(t.value===null||n!==void 0&&!Object.is(t.value,n))&&(u=!0)}let e=s.discriminator;if(e?.side===`target`&&o.fields.writesField(e.field)&&(l=!0,o.fields.operation===`create`)){let t=c(e.field);t!==void 0&&t.value!==e.value&&(u=!0)}}if(o.model===s.target&&l&&!u||o.fields===a.parent&&membershipFields(s).some(e=>o.fields.writesField(e))){let e=r.origin,i=o.origin?.operation??o.fields.operation;this.#s(t,n,()=>dependsOn(e.operation,e.relation,`'${i}' membership write`,{conflictsWith:i,dependency:`membership`,overlap:`unknown`}));return}}if(a.edge.kind===`junction`){let e=t.command,i=a.edge.table;if(!((e?.kind===`link`||e?.kind===`remove`||e?.kind===`set`)&&e.edge.kind===`junction`&&e.edge.table===i))return;let o=r.origin;this.#s(t,n,()=>dependsOn(o.operation,o.relation,`membership write`,{dependency:`membership`,overlap:`unknown`}));return}let s=a.edge,c=s.owner===`source`?s.source:s.target,l=s.owner===`source`?i.command.located?.facts:r.facts,u=t.membership;if(!u)return;let d=r.origin.slot??r.origin.relation,f=r.origin.operation,dependency=e=>dependsOn(f,d,`'${e}' membership write`,{conflictsWith:e,relation:d});if(u.carrier===a.parent&&membershipFields(s).some(e=>u.carrier.movesField(e))){this.#s(t,n,()=>dependency(u.contribution.origin.operation));return}if(u.carrier.model!==c)return;let p=u.contribution;if(t.occurrence.command===r||p.scope.edge!==s.scope.edge||!(p.scope.member===void 0||p.scope.member===s.scope.member))return;let m=u.identity,h=!1;if(l&&m){for(let[e,t]of l.equals)if(!u.carrier.writesField(e)&&m.equals.has(e)&&!Object.is(m.equals.get(e),t)){h=!0;break}}h||this.#s(t,n,()=>dependency(p.origin.operation))}#o(e,t){let{lookup:n}=t;if(!n.origin||n.membershipOnly||n.source.kind===`producer`)return;let r=[{model:n.model,path:[],fields:n.facts.fields,equals:n.facts.equals,exact:n.facts.exact},...n.facts.reads],i=e.command;if(i)for(let a of r){if(i.kind===`link`||i.kind===`remove`){let r=a.path.at(-1);if(!(r!==void 0&&r.scope.edge===i.edge.scope.edge))continue;let o=n.origin;this.#s(e,t,()=>dependsOn(o.operation,o.relation,`membership write`,{conflictsWith:i.kind===`link`?`connect`:`disconnect`,dependency:`membership`,overlap:`unknown`}));return}if((i.kind===`delete`?i.located.model:i.model)!==a.model)continue;let r=i.kind===`set`?void 0:i.located;if(i.kind===`record`&&i.fields.operation!==`create`&&!i.located?.membership()?.edge.many){let e=!1;for(let t of i.fields.writtenFields())if(e=a.fields.has(t),e)break;if(!e)continue}let o=0,s=!1;for(let[e,t]of a.equals){let n=i.kind===`record`&&i.fields.operation===`create`?i.fields.known(e):void 0,c=r?.facts.exact&&!(i.kind===`record`&&i.fields.writesField(e))?r:void 0,l=n?.kind===`literal`?n.value:c?.facts.equals.get(e);if((n?.kind===`literal`||c?.facts.equals.has(e))&&a.exact){if(!Object.is(l,t)){s=!0;break}o++}}if(s)continue;let c=n.origin,l=i.kind===`set`?i.operation:i.origin?.operation??(i.kind===`delete`?`delete`:i.fields.operation);this.#s(e,t,()=>dependsOn(c.operation,c.relation,`'${l}' target write`,{conflictsWith:l,dependency:`targetExistence`,overlap:a.exact&&o>0&&o===a.fields.size?`equal`:`unknown`}));return}}#s(e,t,n){let r=t.owner,i=e.command?this.#i(e.command):e.membership?.contribution.origin;if(i!==void 0&&i.order===t.lookup.origin?.order)return;let a=new Map;for(let e=this.#l(t),n;e;n=e,e=e.parent)a.set(e,n);let o=e.occurrence;if(e.membership){for(let t=e.occurrence;t;t=t.parent)if(isRecordOccurrence(t)&&t.command.fields===e.membership.carrier){o=t;break}}let s=o,c;for(;!a.has(s);)c=s,s=s.parent;let l=a.get(s);if(!(c?this.#u(c,l,s):l.placement!==`before`)){if(isRecordOccurrence(s)&&(s.command.fields.consumes(t.lookup.fields)||l.command.kind===`choose`&&s.command.fields.consumes(l.command.fields))||this.execution.started(s)){r.refusal??=n();return}let e=s.children;e.splice(e.indexOf(l),1),l.placement=`after`;let i=this.#i(l.command)?.order,a=c?e.indexOf(c):-1,o=e.findIndex((e,t)=>{if(t<=a||e.placement!==`after`)return!1;let n=this.#i(e.command)?.order;return i!==void 0&&n!==void 0&&n>=i});e.splice(o<0?c?a+1:e.length:o,0,l)}t.lookup.dependent=!0}#c(e,t,n){let r=e.fields.known(t);if(r?.kind===`literal`)return{value:r.value};let i=e.fields.stated(t);if(i?.kind===`field`)for(let e=n;e;e=e.parent){if(!isRecordOccurrence(e)||e.command.fields!==i.producer)continue;let t=e.command.fields.known(i.field);if(t?.kind===`literal`)return{value:t.value};let n=e.command.located?.facts;return n?.exact&&n.equals.has(i.field)?{value:n.equals.get(i.field)}:void 0}}#l(e){return e.owner.children.find(t=>t.command===e.lookup||t.captureTarget===e.occurrence)??e.occurrence}#u(e,t,n){let phase=e=>e.placement===`before`?0:e.placement===`capture`?1:2;return phase(e)<phase(t)||phase(e)===phase(t)&&n.children.indexOf(e)<n.children.indexOf(t)}#d(e,t){e.parent=t,e.dependencyRead??=this.#f(e);for(let t of e.children)this.#d(t,e)}#f(e){let t=e.command,n=isSeriesOccurrence(e)?this.#m(e):this.#p(e);if(n){if(t.kind===`choose`)return{occurrence:e,lookup:t.lookup,owner:n,membership:t.foundRequirement?.membership,target:!0};if(t.kind===`delete`)return{occurrence:e,lookup:t.located,owner:n,target:!0};if(t.kind===`selectedSeries`)return{occurrence:e,lookup:t.series.selection,owner:n,target:!0}}}#p(e){let t=e.parent;for(;t;){if(isRecordOccurrence(t))return t;t=t.parent}}#m(e){let t=this.#p(e);if(t)return t;let n=e.children.find(e=>e.role===`template`);return n&&isRecordOccurrence(n)?n:void 0}#h(e,t){for(let n=e;n;n=n.parent)for(let e=t;e;e=e.parent)if(n.choice===e.choice&&n.arm!==e.arm)return!1;return!0}#g(e,t,n){let r=e.command;(r.kind===`record`&&(r.fields.operation===`create`||r.fields.writtenFields().length)||r.kind===`delete`||r.kind===`set`||r.kind===`link`||r.kind===`remove`)&&t({write:{occurrence:e,command:r},branch:n});for(let r of this.membershipPublications(e))t({write:{occurrence:e,membership:r},branch:n})}#_(e,t,n){return e.command.kind===`choose`?{parent:n,choice:e,arm:t.role===`found`?`found`:`missing`}:n}#v(e,t,n){this.#g(e,t,n);for(let r of e.children)this.#v(r,t,this.#_(e,r,n))}#y(e,t,n){let r=e.dependencyRead;if(r&&t({read:r,branch:n})===`stop`)return!0;for(let r of e.children)if(this.#y(r,t,this.#_(e,r,n)))return!0;return!1}#b(e,t,n){let r=e.parent;if(!r)return;let i=r.command.kind===`choose`?n?.parent:n;if(this.#b(r,t,i),this.#g(r,t,i),r.command.kind!==`choose`&&!this.#D(r,e))for(let n of r.children){if(n===e)return;this.#v(n,t,i)}}#x(e){let t=e.dependencyRead;if(!t)return;let n=this.#E(e),r={read:t,branch:n},i;for(let t=e;t?.parent;t=t.parent){let e=t.parent;if(!(!isSeriesOccurrence(e)||t.role!==`member`)){e.command.series.selection.membership()&&(i=this.#m(e));break}}this.#b(e,e=>{e.write.occurrence!==i&&this.#S(e,r)},n)}#S(e,t){this.#h(e.branch,t.branch)&&(this.#a(e.write,t.read),t.read.target&&this.#o(e.write,t.read))}#C(e){for(let t=e.branch;t;t=t.parent){if(t.arm===`missing`)return;let e=t.choice.command;if(e.kind!==`choose`||!this.execution.attempt.rows.has(e.lookup))return}return e.read.owner.refusal}#w(e){this.#x(e);let t=e.command;if(t.kind===`record`){this.#T(e);for(let t of e.children){let n=t.command;if(n.kind===`record`)e.refusal??=t.refusal;else if(n.kind===`choose`){let n=this.choiceArm(t,`found`),r=this.choiceArm(t,`missing`);n&&!r&&(e.refusal??=n.refusal)}else if(n.kind===`series`)for(let n of t.children)e.refusal??=n.refusal;else if(n.kind===`selectedSeries`){let n=t.children.find(e=>e.role===`template`);n&&isRecordOccurrence(n)&&(e.refusal??=n.refusal)}}return}if(t.kind===`choose`||t.kind===`series`){this.#T(e);return}if(t.kind===`selectedSeries`){let t=e.children.find(e=>e.role===`template`);t&&this.#w(t)}}#T(e){for(let t of[...e.children])this.#w(t)}#E(e){let t=e.parent;if(t)return this.#_(t,e,this.#E(t))}#D(e,t){return e.command.kind===`series`||isSeriesOccurrence(e)&&t.role===`member`}#O(e,t,n){let r=e,i=n;for(;r.parent;){let e=r.parent,n=e.command.kind===`choose`?i?.parent:i,a=!1;if(!this.#D(e,r))for(let i of e.children)if(a){if(this.#y(i,t,this.#_(e,i,n)))return!0}else i===r&&(a=!0);r=e,i=n}return!1}expandSeries(e,t){e.children=t.map(e=>{let t=this.occurrence(e);return t.role=`member`,this.#r(t),t});let n=this.seriesMembers(e),r=this.#E(e);for(let t of n)this.#d(t,e);for(let e of n)this.#w(e);for(let[i,a]of n.entries()){let n=t[i];if(!n)continue;if(a.command.kind===`record`){let e=a.refusal;if(e)return{error:e,member:n}}let o;if(this.#v(a,t=>{this.#O(e,e=>(this.#S(t,e),o??=this.#C(e),o?`stop`:void 0),r)},r),o)return{error:o,member:n}}}lookup(e,t,n,r){return new Selection(this.execution,e,t,n,r)}capture(e,t){return this.lookup(e.model,{kind:`query`,selector:this.context.queries.identitySelector(e.model,this.context.schema.identity(e.model,t)),...e.judgement&&{judgement:e.judgement}},e.required)}rootUpdate(e,t,n){let r=this.context;if(r.schema.namesRelation(e,t.data)||!r.driver.adapter.capabilities.supportsReturning)return;let i=r.queries.prepareProjection(e,t);if(!returningSafeProjection(i))return;let a=this.stamp(e,`update`,t.data,n.data);if(Object.keys(a).length===0)return;let o=r.queries.candidates(r.queries.prepareSelector(e,t.where,!0),`root`,void 0,this.judge(e,t.data,n.data));return()=>r.updateMany(e,o,a,void 0,i,()=>new F(e[`~`].names.ts,`update`))}#k(e,t,n,r,i){if(!this.blocked(e))return{single:n,run:()=>i(e,t)};let a=this.context,o=a.queries,s=e.model,c=this.restriction(s);return{single:!1,run:async()=>{let locked=(e,t)=>o.select(s,{take:t,select:Object.fromEntries(a.schema.keys(s).map(e=>[e,!0]))},void 0,{selector:e,forUpdate:!a.usesBatch}),n=e,l;if(t!==void 0&&a.usesBatch)n=o.andSelectors(s,[e,o.window(e,t)]);else if(t!==void 0){let i=await a.read(locked(e,t),!0),c=a.driver.maxBindParametersPerStatement,u=c===void 0||i.length*a.schema.keys(s).length<=c/2?o.andSelectors(s,[e,o.includeIdentities(s,i.map(e=>a.schema.identity(s,e)))]):void 0,d=u!==void 0&&(c===void 0||locked(this.blocked(u),1).sql.values.length<=c&&(o.lowerSelector(u)?.values.length??0)+r(i.length)<=c);u&&(d||i.length===0)?n=u:(n=o.andSelectors(s,[e,o.through(s,a.schema.identity(s,i.at(-1)))]),l=t)}else !a.usesBatch&&a.driver.adapter.capabilities.supportsRowLocks&&await a.read(o.lockAll(e),!0);let u=locked(this.blocked(n),1);return a.preparesBatch?a.packageGuard(s,u.sql,`notExists`,c):await a.requireAbsent(u,this.restrictFailure(s)()),i(n,l)}}}#A(e,t,n){let r=this.context,i=r.driver.adapter.capabilities;if(!r.preparesBatch&&r.scope?.rows.stamps!==void 0||t.targetWhere||t.setWhere||!i.supportsReturning||r.schema.namesRelation(e,t.create)||r.schema.namesRelation(e,t.update))return;let a=Object.keys(record(n.update)).length===0?{}:this.stamp(e,`update`,t.update,n.update),o=Object.keys(a);if(o.length===0||r.schema.keys(e).some(e=>a[e]!==void 0))return;let s=r.queries.prepareProjection(e,t);if(!returningSafeProjection(s))return;let c=this.stamp(e,`create`,t.create,n.create),missing=()=>r.createMany(e,[c],s,!1,()=>{throw new InvalidScalarResult(`record`,`INSERT did not produce the required record`)}),l=this.judge(e,t.update,record(n.update),`upsert`),u=this.lookup(e,{kind:`query`,where:t.where,unique:!0,purpose:`root`,judgement:l});u.insertsWhenAbsent=!0;let d=u.selector.uniqueKey;if(i.supportsTargetedUpsert&&u.selector.scoped===void 0&&d!==void 0&&u.selector.uniqueValues!==void 0&&d.fields.every(e=>{let t=c[e];return(t===null||typeof t!=`object`&&typeof t!=`function`)&&Object.is(t,u.selector.uniqueValues.get(e))})&&o.every(t=>r.queries.namesUpdate(e,t,a[t])))return{single:!0,run:()=>r.upsertOne(e,c,a,d.fields,s,()=>{throw TypeError(`INSERT … ON CONFLICT did not produce the required record`)})};if(r.preparesBatch)return{single:!1,run:async()=>{let t=(await r.planningLocate(u.query(),e))[0];if(!t)return missing();let n=r.queries.candidates(r.queries.prepareSelector(e,r.schema.identity(e,t),!0),`root`,void 0,l);return r.updateMany(e,n,a,void 0,s,()=>new F(e[`~`].names.ts,`upsert`))}}}rootCreate(e,t,n){let r=this.context;if(r.schema.namesRelation(e,t.data)||!r.driver.adapter.capabilities.supportsReturning)return;let i=r.queries.prepareProjection(e,t);if(!returningSafeProjection(i))return;let a=this.stamp(e,`create`,t.data,n.data);return()=>r.createMany(e,[a],i,!1,()=>{throw new InvalidScalarResult(`record`,`INSERT did not produce the required record`)})}plan(e,t,n){let r=this.context,i=r.driver.adapter,a=i.capabilities.supportsReturning;if(r.operation===`createMany`){let o=entries(t.data),s=entries(n.data);if(o.some(t=>e[`~`].relationNames.some(e=>t[e]!==void 0))){t.skipDuplicates&&r.admitsSuppression(`rows involving nested writes`);let n=o.map((n,r)=>{let i=this.create(e,n,s[r]);return t.skipDuplicates&&(i.suppression={kind:`skipDuplicate`}),i}).map(t=>{for(let n of r.schema.keys(e))t.fields.field(n);return this.analyze(t)}),i={kind:`series`,records:n};return{single:!1,run:()=>this.execution.records(n,t.select,i)}}let c=bulkProjection(r,e,t),l=o.map((t,n)=>this.stamp(e,`create`,t,s[n])),u=t.skipDuplicates===!0&&i.mutations.skipDuplicatesStrategy===`recoverableUniqueError`;return u&&r.admitsSuppression(`duplicate rows`),{single:l.length===0||!u&&(!c||a),run:()=>r.createMany(e,l,c,t.skipDuplicates)}}if(r.operation===`delete`||r.operation===`deleteMany`){let n=r.operation===`delete`,i=n?r.queries.prepareProjection(e,t):bulkProjection(r,e,t);if(t.limit===0)return{single:!0,run:async()=>r.emptyBulkResult(i)};let o=this.tombstone(e),s=this.candidates(r.queries.prepareSelector(e,t.where,n),`root`,o!==void 0,jn),c=n?()=>new F(e[`~`].names.ts,`delete`):void 0,l=!i||a&&returningSafeProjection(i);if(!o)return{single:l,run:()=>r.deleteMany(e,s,t.limit,i,c)};let u=o.admitted;return this.#k(s,t.limit,l,t=>{let n=i&&!(a&&returningSafeProjection(i))?t*r.schema.keys(e).length:0;for(let[t,i]of Object.entries(u))n+=r.queries.updateAssignment(e,t,i).values.length;return n},(t,n)=>r.updateMany(e,t,u,n,i,c))}if(r.operation===`upsert`){let i=this.#A(e,t,n);if(i)return i;let a=this.create(e,t.create,n.create);a.operation=`upsert`;let o=this.lookup(e,{kind:`query`,where:t.where,unique:!0,purpose:`root`,judgement:this.judge(e,t.update,n.update,`upsert`)});o.insertsWhenAbsent=!0;let s=this.context.queries,c=[],l=[],premiseChanged=t=>new L(`The upsert ${t} changed before the atomic batch.`,{meta:{model:e[`~`].names.ts,operation:`upsert`}});for(let n of[`targetWhere`,`setWhere`]){let r=t[n];if(!r)continue;let i=s.prepareSelector(e,r),a=premiseChanged(`${n} skip premise`);a.meta.raceable=!0;let u=this.lookup(e,{kind:`query`,selector:s.andSelectors(e,[o.selector,i])});u.insertsWhenAbsent=!0,l.push(n),c.push({lookup:u,match:premiseChanged(`${n} match premise`),skip:a})}let[u]=c,d=this.occurrence(this.update(o,t.update,n.update,!0,`upsert`)),f=r.schema.keyTransitionRefusal(e,t.update,o.selector.facts.keys,d.command.transitions);if(f)throw f;let p={kind:`choose`,model:e,lookup:o,operation:`upsert`,missing:this.occurrence(a),conditions:u&&{probes:c,missingRow:new F(e[`~`].names.ts,`upsert`),matched:c.length===1?u.match:premiseChanged(`matched premise (${l.join(`, `)})`)},fields:new Assignments(e,`select`,{},{},void 0,[a.fields]),found:d};d.command.operation=`upsert`,p.fields.forward(d.command.fields);for(let t of r.schema.keys(e))p.fields.field(t);let m=this.analyze(p),h=this.choiceArm(m,`found`);return h&&r.schema.namesRelation(e,t.update)&&(h.refusal=r.schema.keyPortabilityRefusal(e,t.update)??h.refusal),{single:!1,run:()=>this.execution.complete(m,t)}}if(r.operation===`create`||r.operation===`update`){let i=r.operation===`update`?this.rootUpdate(e,t,n):this.rootCreate(e,t,n);if(i)return{single:!0,run:i};let a=r.operation===`create`?this.create(e,t.data,n.data):this.update(this.lookup(e,{kind:`query`,where:t.where,unique:!0,purpose:`root`,judgement:this.judge(e,t.data,n.data)},()=>new F(e[`~`].names.ts,`update`)),t.data,n.data);for(let t of r.schema.keys(e))a.fields.field(t);let o=this.analyze(a);return{single:!1,run:()=>this.execution.complete(o,t)}}let o=t.data,s=r.schema.namesRelation(e,o),c=bulkProjection(r,e,t);if(t.limit===0)return{single:!0,run:async()=>r.emptyBulkResult(c)};let l=this.judge(e,o,n.data),u=s?void 0:this.stamp(e,`update`,o,n.data);if(u!==void 0&&Object.keys(u).length>0){let n=r.queries.candidates(r.queries.prepareSelector(e,t.where),`root`,void 0,l);return{single:!c||a,run:()=>r.updateMany(e,n,u,t.limit,c)}}let d=this.lookup(e,{kind:`query`,where:t.where,purpose:`root`,judgement:l},()=>new F(e[`~`].names.ts,`update`)),f={selection:d,analysis:this.update(d,o,n.data,!0),limit:t.limit,mutation:{kind:`update`,raw:n.data}},p=this.analyzeSeries(f);return{single:!1,run:async()=>c?this.execution.series(p,f.selection,c):{count:await this.execution.series(p)}}}};function publishedFacts(e){return{shape:e.query.shape,value:e.value,single:e.single,empty:e.result([]),statement:e.query.sql}}var PreparedCommand=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t,n,r,i,a,s){let c,l=s&&preparedDomain(n,s.defaults);this.#c=s&&{rows:s,domain:preparedDomain(n,s.domain,l),defaults:l,instant:()=>c??=new Date},this.#e=e,this.#t=t,this.#n=n,this.#r=o(i),this.#i=e.schema[r],this.#a=r,this.#o=a,this.#s=i===this.#r?void 0:()=>new F(this.#i[`~`].names.ts??`unknown`,i)}get args(){return this.#l??=this.#f()}#f(){let e=this.#c?.rows.stamps,t=this.#c?.domain,n=t?.projects?()=>admitProjected(t,this.#t,this.#i,this.#r,this.#o,e=>this.#t.admit(this.#i,this.#r,e)):()=>this.#t.admit(this.#i,this.#r,this.#o);return e===void 0?n():T(e,n)}#p(){if(isReadOperation(this.#r))return this.#u??=(this.#c?.domain.reads(this.#c)??this.#n).read(this.#i,this.#r,this.args)}get read(){let e=this.#p();if(e)return this.#d??=publishedFacts(e)}#m(e,t,n){return new OperationContext(this.#t,this.#e.driver,this.#a,this.#r,n,e,t,this.#c)}#h(e){return new Commands(e).plan(this.#i,this.args,this.#o)}#g(e){let t=this.#p();if(t)return e.run(()=>e.publish(t,this.#s));let n=this.#h(e),r=n.single;return e.run(()=>{let t=n??this.#h(e);return n=void 0,t.run()},r)}execute(e,t){try{return this.#g(this.#m(!1,t,e))}catch(e){return Promise.reject(e)}}prepareSingle(e){this.args;let t=this.#m(!0,e),n=this.#p();if(n)return t.publishPrepared(n,this.#s),t.preparedBatch();let r=this.#h(t);if(r.single)return r.run().catch(()=>void 0),t.preparedBatch()}async prepareBatch(e){let t=this.#m(!0,e);try{await this.#g(t)}catch(e){if(t.isIncompletePreparation(e))return;throw e}return t.preparedBatch()}};const Nn=new WeakMap,Pn=new WeakMap;function preparedDomain(e,t,n){return memo(memo(Pn,e,()=>new WeakMap),t,()=>new PreparedDomain(t,e,n))}function sharedQueries(e){let{adapter:t,result:n}=e.driver,r=e.resolved?.registry,i=r&&Nn.get(r);i||(i={schema:new EngineSchema(e.schema,e.resolved),queries:new WeakMap},r&&Nn.set(r,i));let a=i.queries.get(t);if(a||i.queries.set(t,a={parsers:new WeakMap}),!n)return a.none??=new hn(i.schema,t,n);let o=a.parsers.get(n);return o||(o=new hn(i.schema,t,n),a.parsers.set(n,o)),o}function createCommandEngine(e){let t=sharedQueries(e),{schema:n}=t,prepare=(r,i,a,o)=>new PreparedCommand(e,n,t,r,i,a,o);return{prepare}}function routeWriteOutcome(e){let{committedWriteSegment:t,writeMayBeVisible:n}=e;if(!(t||n))return;let r={published:!1,seam:{committedSegment:async()=>{r.published=!0,t&&await t()},mayBeVisible:async()=>{r.published=!0,n&&await n()}}};return r}var RoutedOperation=class{#e;#t;#n;#r;#i;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r}get preparedArgs(){return this.#r.args}buildStatement(){return this.#r.read?.statement}cacheResultCodec(){let e=this.#r.read;if(!e)throw new N(`Cannot cache '${this.#n}' on model '${this.#t}': the operation has no readable result.`,{meta:{model:this.#t,operation:this.#n}});return this.#i??=r().cacheCodec(e,this.#n)}prepareSingle(e){return this.#r.prepareSingle(e)}prepareBatch(e){return this.#r.prepareBatch(e)}execute(e){try{let t=e.isWrite?routeWriteOutcome(e):void 0;return t?runWriteCandidate(this.#r,e,this.#e,t):runCandidate(this.#r,e,this.#e,void 0)}catch(e){return Promise.reject(e)}}};function createCandidateRoute(e,t,n){let r=createCommandEngine({schema:e,driver:t,resolved:n});return{operation(e,n,i,a){let o=e[`~`].names.ts??`unknown`,s=n;return new RoutedOperation(t,o,n,r.prepare(o,s,i,a))}}}async function runWriteCandidate(e,t,n,r){let i=await runCandidate(e,t,n,r.seam);return!r.published&&t.committedWriteSegment&&await t.committedWriteSegment(),i}function runCandidate(e,t,n,r){let{context:i,driverOverride:a,engineDriver:o}=t;return a?e.execute({driver:a,kind:`borrowed-transaction`,writeOutcome:r},i):o===n?e.execute(r?{kind:`standalone`,writeOutcome:r}:void 0,i):e.execute({driver:o,kind:`borrowed-transaction`,memberRollback:(e,t)=>o.withTransaction(e,void 0,t),operationRegion:(e,t)=>o.withTransaction(e,void 0,t),writeOutcome:r},i)}function createArrayDeferred(){let e=!1,t,n,r=new Promise((e,r)=>{n=e,t=r});return r.catch(()=>void 0),{promise:r,reject(n){e||(e=!0,t(n))},resolve(t){e||(e=!0,n(t))}}}async function admitArrayQueries(e,t,n){let r,i=!1,a=e.length,o=createArrayDeferred();a===0&&o.resolve();for(let t of e){let reportAdmissionFailure=e=>{let n=t.admissionFailures;n===void 0?t.admissionFailures=[e]:n.includes(e)||n.push(e),!i&&(i=!0,r=e,o.reject(e))},e;try{e=n(t,e=>(t.notifications=e,t.admitted||(t.admitted=!0,--a,a===0&&o.resolve()),t.child.promise),{reportAdmissionFailure,readCommitCertainty:()=>t.certainty})}catch(t){reportAdmissionFailure(t),e=Promise.reject(t)}t.query=e,t.observation!==void 0&&e.then(t.observation.resolve,t.observation.reject).catch(()=>void 0),e.catch(reportAdmissionFailure)}try{if(await o.promise,await Promise.resolve(),i)throw r;return}catch(n){t.discardAll();for(let t of e)t.child.reject(n);await Promise.allSettled(e.map(readArrayQuery));let r=[];for(let t of e)for(let e of t.admissionFailures??[])r.includes(e)||r.push(e);return r}}function readArrayQuery(e){return e.query??e.child.promise}function markArrayCommitCertainty(e,t){if(D(e))return ae(e,t);if(!(e instanceof AggregateError))return e;let n=e.errors.map(e=>markArrayCommitCertainty(e,t)),r=e.cause===e.errors[0]?n[0]:markArrayCommitCertainty(e.cause,t);return AggregateError(n,e.message,{cause:r})}function combineArrayFailures(e,t){let n=t.filter(t=>t!==e);return n.length===0?e:AggregateError([e,...n],`Array transaction and operation post-work both failed.`,{cause:e})}async function prepareNativeBatch(e,t){let n=[],r=[],i=[];for(let{operation:a,owner:o}of e){let e=await o.observeBatchPhase(a,t,async()=>{let e=o.prepare(a,t);return e?{kind:`single`,prepared:e}:{kind:`batch`,preparedBatch:await o.prepareBatch(a)}}),s=n.length;if(e.kind===`single`){n.push(e.prepared),i.push(e=>o.observeBatchPhase(a,t,()=>{let n=e[s];if(!n)throw missingOperationResult(t,a,o);return o.parseResult(a,n)}));continue}let{preparedBatch:c}=e;if(!c)throw unbatchableArrayError(t);let l=c.queries.length;for(let e of c.queries)n.push(e);for(let e of c.guards??[])r.push({...e,queryIndex:s+e.queryIndex});i.push(e=>o.observeBatchPhase(a,t,()=>c.parseResult(e.slice(s,s+l))))}return{queries:n,guards:r,parsers:i}}async function executeNativeBatch(e,t,n,r,i,a){if(t.length===0)return[];try{return await e._executeBatch(t,r,i,a)}catch(r){throw await attributeOperationBatchError(r,n,e,t)}}function assertNativeBatchResults(e,t,n){_(t,n,{provider:e.driverName,operation:`$transaction([...])`})}function assertAtomicArraySupport(e){if(!(e.supportsTransactions||e.supportsBatch))throw new L(`Driver "${e.driverName}" supports neither transactions nor atomic batch execution.`,{meta:{driver:e.driverName,method:`$transaction([...])`}})}function unbatchableArrayError(e){return new L(`Driver "${e.driverName}" does not support callback transactions and this transaction contains operations that cannot be batched atomically.`,{meta:{driver:e.driverName,method:`$transaction([...])`}})}function missingOperationResult(e,t,n){let r=n.operation(t);return new L(`Driver "${e.driverName}" omitted the result for operation "${r}".`,{meta:{driver:e.driverName,operation:r}})}async function executeLegacyArrayTransaction(e,t,n,r,i=!1,a){let o=t.driver,s=e;if(!o.supportsTransactions&&o.supportsBatch){if(i){let i=ot(t.extensionChain?.observe);return i!==void 0&&await i,executeObservedNativeArray(e,o,n,r,a)}for(let t of e)G(t).reserveWith(t,o);let{queries:c,guards:l,parsers:u}=await prepareNativeBatch(batchMembers(e),o),d=await executeNativeBatch(o,c,l,n,r);assertNativeBatchResults(o,d,c.length);for(let e=0;e<u.length;e+=1)s[e]=await u[e](d);return s}return assertAtomicArraySupport(o),i?executeObservedFallbackArray(e,t,n,r,a):o.withTransaction(runInOrder(e,s),n,r)}function batchMembers(e){return e.map(e=>({operation:e,owner:G(e)}))}function runInOrder(e,t){return async n=>{for(let r=0;r<e.length;r+=1){let i=e[r];t[r]=await G(i).executeWith(i,n)}return t}}async function executeObservedNativeArray(e,t,n,r,i){let a=e,o=[];try{for(let t of e)o.push(startNativeObservation(t))}catch(e){throw rejectObservedMembers(o,e),e}let s;try{for(let n of e)G(n).reserveWith(n,t);s=await prepareNativeBatch(batchMembers(e),t)}catch(e){throw rejectObservedMembers(o,e),e}let{queries:c,guards:l,parsers:u}=s,d;try{d=await executeNativeBatch(t,c,l,n,r)}catch(e){throw setObservedCertainty(o,`may-have-committed`),i?.(`may-have-committed`),rejectObservedMembers(o,e),e}setObservedCertainty(o,`committed`),i?.(`committed`);try{assertNativeBatchResults(t,d,c.length);for(let e=0;e<u.length;e+=1){let t=await u[e](d),n=o[e];resolveObservedMember(n,t),a[e]=await n.application}return a}catch(e){throw rejectObservedMembers(o,e),e}}async function executeObservedFallbackArray(e,t,n,r,i){let a=e,o={phase:`pending`},s=t.transactionWriteOutcomes!==void 0,c=s?r:Et(r,{readyToCommit:()=>{o.phase=`ready`},committed:()=>{o.phase=`committed`}});try{let r=await t.driver.withTransaction(runInOrder(e,a),n,c);return s||i?.(`committed`),r}catch(e){throw!s&&o.phase===`committed`?i?.(`committed`):!s&&o.phase===`ready`&&i?.(`may-have-committed`),e}}function startNativeObservation(e){let t=G(e);if(!t.hasObservation(e))throw new R;let rejectChild=()=>void 0,resolveChild=()=>void 0,n=new Promise((e,t)=>{resolveChild=e,rejectChild=t}),r;return r={application:t.observe(e,()=>n,()=>r.certainty===void 0?void 0:{commitCertainty:r.certainty}),rejectChild,resolveChild,settled:!1},r.application.catch(()=>void 0),r}function rejectObservedMember(e,t){e.settled||(e.settled=!0,e.rejectChild(t))}function resolveObservedMember(e,t){e.settled||(e.settled=!0,e.resolveChild(t))}function rejectObservedMembers(e,t){for(let n of e)rejectObservedMember(n,t)}function setObservedCertainty(e,t){for(let n of e)n.certainty=t}async function executeInterceptedNativeArray(e,t,n,r,i,a){let o;try{o=await prepareNativeBatch(e,n)}catch(n){throw t.discardAll(),await rejectAndCombine(e,n)}let{queries:s,guards:c,parsers:l}=o,u=!1,d=[],confirmCommit=async()=>{if(!u){u=!0,a?.(`committed`);for(let t of e)t.certainty=`committed`;d.push(...await publishNativeOutcome(e,t,`committed`))}},f;try{f=await executeNativeBatch(n,s,c,r,i,n.supportsOrderedCommittedSegments?confirmCommit:void 0)}catch(n){throw u?await closeCommittedFailure(e,n,d):(a?.(`may-have-committed`),await closeDispatchedFailure(e,t,n))}await confirmCommit();try{assertNativeBatchResults(n,f,s.length)}catch(t){throw await closeCommittedFailure(e,t,d)}let p=Array(e.length);for(let t=0;t<e.length;t+=1){let n=e[t];try{n.child.resolve(await l[t](f))}catch(e){n.child.reject(markArrayCommitCertainty(e,`committed`))}}let m=await Promise.allSettled(e.map(readArrayQuery)),h=[];for(let e=0;e<m.length;e+=1){let t=m[e];if(t.status===`fulfilled`)p[e]=t.value;else for(let e of queryFailureParts(t.reason))h.push(e)}let g=[...h,...d.map(e=>markArrayCommitCertainty(e,`committed`))];if(g.length>0)throw combineArrayFailures(g[0],g.slice(1));return p}async function closeDispatchedFailure(e,t,n){let r=markArrayCommitCertainty(n,`may-have-committed`);for(let t of e)t.certainty=`may-have-committed`;return rejectAndCombine(e,r,await publishNativeOutcome(e,t,`may-have-committed`))}async function closeCommittedFailure(e,t,n){for(let t of e)t.certainty=`committed`;return rejectAndCombine(e,markArrayCommitCertainty(t,`committed`),n)}async function rejectAndCombine(e,t,n=[]){for(let n of e)n.child.reject(t);let r=[];for(let t of await Promise.allSettled(e.map(readArrayQuery)))t.status===`rejected`&&r.push(...queryFailureParts(t.reason));return combineArrayFailures(t,[...r,...n])}async function publishNativeOutcome(e,t,n){let r=[];for(let t of e)if(t.owner.isWrite(t.operation))try{n===`committed`?await t.notifications?.committed():await t.notifications?.mayHaveCommitted()}catch(e){r.push(e)}try{await t.publish(n)}catch(e){for(let t of St(e))r.push(t)}return r}function queryFailureParts(e){let t=st(e);return t===void 0?[e]:[t.child,...t.postWork]}function executeArrayTransaction(e,t,n,r){let i,a;try{let t=e.length;if(typeof t!=`number`||!Number.isInteger(t)||t<0||t>4294967295)throw new R;i=Array(t);for(let n=0;n<t;n+=1)i[n]=e[n]}catch(e){i=void 0,a=e}let o=t.extensionChain?.observe;if(i===void 0){if(o===void 0||o.length===0)throw a;return it({kind:`batch`,operation:`$transaction([...])`},o,()=>{throw a})}if(o===void 0||o.length===0)return assertOwnedOperations(i,t),i.length===0?Promise.resolve(i):(prepareRequestAdmissions(i,t),canRequireInterceptedArray(t)&&requiresInterceptedArray(i)?executeInterceptedArray(i,t,n,r):executeLegacyArrayTransaction(i,t,n,r));let s={};return it({kind:`batch`,operation:`$transaction([...])`},o,()=>(assertOwnedOperations(i,t),i.length===0?Promise.resolve(i):canRequireInterceptedArray(t)&&requiresInterceptedArray(i)?executeInterceptedArray(i,t,n,r,s):executeLegacyArrayTransaction(i,t,n,r,!0,e=>{s.certainty=e})),()=>s.certainty===void 0?void 0:{commitCertainty:s.certainty})}function prepareRequestAdmissions(e,t){for(let t of e)G(t).prepareAdmission(t);for(let t of e)G(t).prepareAdmission(t,`plan`)}function requiresInterceptedArray(e){for(let t of e)if(G(t).requiresInterception(t))return!0;return!1}function canRequireInterceptedArray(e){let t=e.extensionChain;return t!==void 0&&(t.hasRequestHandlers||t.hasQueryHandlers||t.hasCache)}function assertOwnedOperations(e,t){for(let n of e){if(typeof n!=`object`||!n)throw new R;let e=Ot(n);if(e===void 0)throw new R;if(e.clientId(n)!==t.clientId)throw le.clientMismatch(e.model(n),e.operation(n));if(e.scopeId(n)!==t.scopeId)throw le.scopeMismatch(e.model(n),e.operation(n))}}async function executeInterceptedArray(e,t,n,r,i){let a=t.driver;assertAtomicArraySupport(a);let o=ot(t.extensionChain?.observe);o!==void 0&&await o;let s=new ct,c=e.map(createArraySlot);startArrayOperationObservers(c,t);try{for(let e of c)e.owner.reserveWith(e.operation,a);for(let e of c)await e.owner.observeBatchPhase(e.operation,a,()=>e.owner.prepareAdmission(e.operation));for(let e of c)await e.owner.observeBatchPhase(e.operation,a,()=>e.owner.prepareAdmission(e.operation,`plan`))}catch(e){throw closeArrayOperationObservers(c,e),e}for(let e of c)e.owner.stagePackageWriteOutcomes(e.operation,s);let l=await admitArrayQueries(c,s,(e,t,n)=>e.owner.startInterception(e.operation,t,s,n));if(l!==void 0)throw combineArrayFailures(l[0],l.slice(1));return!a.supportsTransactions&&a.supportsBatch?executeInterceptedNativeArray(c,s,a,n,r,e=>{i&&(i.certainty=e)}):executeInterceptedFallback(c,s,t,n,r,i)}function createArraySlot(e){return{operation:e,owner:G(e),admitted:!1,child:createArrayDeferred()}}function startArrayOperationObservers(e,t){let n=t.extensionChain?.observe;if(!(n===void 0||n.length===0))for(let t of e){let e=createArrayDeferred();if(t.observation=e,!t.owner.hasObservation(t.operation))throw new R;t.owner.observe(t.operation,()=>e.promise,()=>t.certainty===void 0?void 0:{commitCertainty:t.certainty}).catch(()=>void 0)}}function closeArrayOperationObservers(e,t){for(let n of e)n.observation?.reject(t)}async function runOutcomeTransaction(e,t,n,r,i,a,o,s=e=>e){let c,l;try{l=await e.withTransaction(a,r,n?i:Et(i,{readyToCommit:()=>{c=`ready`},committed:()=>{c=`committed`}}))}catch(e){let n=s(e);if(c===void 0)throw t.discardAll(),n;let r=c===`ready`?`may-have-committed`:c;o?.(r);let i=D(n)?ae(n,r):n;try{await t.publish(r)}catch(e){throw I(i,e)}throw i}return n?t.promoteTo(n):(o?.(`committed`),await t.publishCommitted()),l}function executeInterceptedFallback(e,t,n,r,i,a){let o=[];return runOutcomeTransaction(n.driver,t,n.transactionWriteOutcomes,r,i,async t=>{let n=[];for(let r=0;r<e.length;r+=1){let i=e[r];startFallbackCore(i,t);try{n.push(await readArrayQuery(i))}catch(t){let n=st(t),i=n===void 0?t:n.child;if(n)for(let e of n.postWork)o.push(e);for(let t=r+1;t<e.length;t+=1)e[t].child.reject(i);let a=await Promise.allSettled(e.slice(r+1).map(readArrayQuery));for(let e of a){if(e.status!==`rejected`)continue;let t=st(e.reason);if(t){t.child!==i&&o.push(t.child);for(let e of t.postWork)o.push(e)}else e.reason!==i&&o.push(e.reason)}throw i}}return n},a&&(e=>{a.certainty=e}),e=>combineArrayFailures(e,o))}function startFallbackCore(e,t){let n;try{n=e.owner.executeCore(e.operation,t,e.notifications)}catch(t){e.child.reject(t);return}n.then(e.child.resolve,e.child.reject)}const hasEntries=e=>Object.keys(e).length>0,createClientOmitResolver=(e,t,r)=>{let i=new Map;for(let r of Object.keys(t)){let a=Object.hasOwn(e,r)?e[r]:void 0,o=t[r];if(!a)throw new re(`Client 'omit' names model '${r}', which is not in the schema.`,O.INVALID_INPUT,{meta:{model:r}});if(!n(o))continue;let s=new Set(tt(a)),c={};for(let e of Object.keys(o)){if(!s.has(e))throw new re(`Client 'omit' names field '${e}' on model '${r}', which is not a readable scalar of that model.`,O.INVALID_INPUT,{meta:{model:r,field:e}});o[e]===!0&&(c[e]=!0)}hasEntries(c)&&i.set(a,c)}if(i.size!==0)return{omit:e=>i.get(e),relations:r}},Fn=new Set([`findFirst`,`findFirstOrThrow`,`findMany`,`findUnique`,`findUniqueOrThrow`,`create`,`update`,`upsert`,`delete`]),bulkWriteProjects=(e,t)=>(e===`createMany`||e===`updateMany`||e===`deleteMany`)&&t.omit!==void 0,applyClientOmit=(e,t,n,r)=>Fn.has(t)||bulkWriteProjects(t,n)?rewriteNode(e,n,r):n,rewriteNode=(e,t,r)=>{let i=t.select,a=t.include,o=n(i),s=o?rewriteRelationMap(e,i,r):i,c=n(a)?rewriteRelationMap(e,a,r):a,l=o?void 0:r.omit(e),u=l?mergeOmit(l,t.omit):t.omit;if(s===i&&c===a&&u===t.omit)return t;let d={...t};return s!==i&&(d.select=s),c!==a&&(d.include=c),u!==t.omit&&(d.omit=u),d},mergeOmit=(e,t)=>{if(!n(t))return{...e};let r={...e};for(let e of Object.keys(t))r[e]=t[e];return r},rewriteRelationMap=(e,t,r)=>{let i=r.relations.get(e),a=!1,o={...t};for(let s of Object.keys(t)){let c=i?.get(s);if(!c)continue;let l=t[s],u=directVariantCarrier(c);if(u){let e=rewriteVariantCarrier(u,l,r);e!==l&&(o[s]=e,a=!0);continue}let d=slotTarget(c,e);if(!d)continue;if(l===!0){let e=r.omit(d);if(!e)continue;o[s]={omit:{...e}},a=!0;continue}if(!n(l))continue;let f=rewriteNode(d,l,r);f!==l&&(o[s]=f,a=!0)}return a?o:t},directVariantCarrier=e=>{if(e.member)return;let t=e.edge;return t.kind===`variantRowCarrier`||t.kind===`variantJunctionCarrier`?t:void 0},slotTarget=(e,t)=>{let n=e.edge;if(n.kind===`foreignKey`||n.kind===`junction`){let[r,i]=n.endpoints;return r.source===t&&r.field===e.slot.field?i.source:r.source}return n.carrier.source},rewriteVariantCarrier=(e,t,n)=>e.kind===`variantJunctionCarrier`?rewritePolymorphicCollection(e,t,n):rewritePolymorphicSlot(e,t,n),defaultedArm=(e,t,r)=>{if(n(t)){let n=rewriteNode(e,t,r);return n===t?void 0:n}if(t!==!0&&t!==void 0)return;let i=r.omit(e);return i?{omit:{...i}}:void 0},rewritePolymorphicSlot=(e,t,r)=>{if(t!==!0&&!n(t))return t;let i=t===!0?{}:{...t},a=!1;for(let n of e.members){let e=t===!0?void 0:t[n.variant],o=defaultedArm(n.targetModel,e,r);o!==void 0&&(i[n.variant]=o,a=!0)}return a?i:t},rewritePolymorphicCollection=(e,t,r)=>{if(t!==!0&&!n(t))return t;let i=t===!0?void 0:t,a=i?.only,o=i?.variants;if(a!==void 0&&!Array.isArray(a)||o!==void 0&&!n(o))return t;let s=Array.isArray(a)?new Set(a):void 0,c={...o},l=!1;for(let t of e.members){if(s&&!s.has(t.variant))continue;let e=defaultedArm(t.topology.target.model,o?.[t.variant],r);e!==void 0&&(c[t.variant]=e,l=!0)}return l?{...i,variants:c}:t},In=new Set([`findUnique`,`update`,`delete`,`upsert`]);function assertNonEmptyUniqueWhere(e,t,r){let i=o(t);if(!In.has(i)||!n(r))return;let a=r.where;if(n(a)&&!Object.keys(a).some(e=>a[e]!==void 0))throw new pe(i,[{path:`where`,message:`whereUnique requires at least one unique discriminator.`}],{meta:{model:e}})}function refuseGeoPointFields(e){for(let[t,n]of Object.entries(e)){let e=n[`~`].state.scalars;for(let[n,r]of Object.entries(e))if(r[`~`].state.type===`point`)throw new P(`GeoPoint field '${t}.${n}' cannot be stored by this driver because its adapter has no GeoPoint protocol.`)}}function createModelProxy(e,t,n,r=[]){let a=r.length===1?n?.(r[0]):void 0,o=new Set(r.length===0?Object.keys(e):r.length===1?[...i,...Object.keys(a??{})]:[]),s=new Map,readMember=i=>{if(typeof i!=`string`||i===`then`||!o.has(i))return;if(a!==void 0&&Object.hasOwn(a,i))return a[i];let c=s.get(i);return c===void 0&&(c=createModelProxy(e,t,n,[...r,i]),s.set(i,c)),c};return new Proxy(r.length===2?()=>void 0:{},{get:(e,t)=>Object.hasOwn(e,t)?Reflect.get(e,t):readMember(t),has:(e,t)=>Object.hasOwn(e,t)||typeof t==`string`&&o.has(t),ownKeys:e=>[...new Set([...Reflect.ownKeys(e),...o])],getOwnPropertyDescriptor:(e,t)=>Reflect.getOwnPropertyDescriptor(e,t)??(typeof t==`string`&&o.has(t)?{configurable:!0,enumerable:!0,writable:!0,value:readMember(t)}:void 0),apply(e,n,[i]){let a=r[0],o=r[1];return t({modelName:a,operation:o,args:i})}})}function isRawMethodName(e){return typeof e==`string`&&Object.hasOwn(Ft,e)}var Ln=class VibORM{#e;#t;#n;#r;#i;constructor(e,{relations:t,schemaRegistry:n}){this.#e=e.schema,this.#n=t,this.#r=n,this.#t=new Ut(e.driver,createCandidateRoute(this.#e,e.driver,{index:t,registry:n}))}#a(e,t,n){return createModelProxy(this.#e,({modelName:t,operation:r,args:i})=>this.#o(e,t,r,i,n),t)}#o(e,t,n,i,o,c){let l=s(e.extensionChain),u=String(t),d=this.#e[t];if(!d)throw new P(`Model "${u}" not found in schema`,{meta:{model:u,operation:String(n)}});let f=i??{},p=a(n),m=e.extensionChain,h=x(m,`request`,u,n),g=(m?.observe.length??0)>0,_=te(m,u,n).length>0,v=f,prepareInput,finish=e=>{let t=o?applyClientOmit(d,n,e,o):e;return assertNonEmptyUniqueWhere(u,n,t),t};h===void 0&&!_&&!g?v=finish(f):prepareInput=(e,t)=>finish((h===void 0?e:applyRequestTransforms(u,n,e,h,m?.controls===void 0?void 0:{names:m.controls.names,admitted:t}))??{});let y=l===void 0||!p?void 0:(e,t)=>r().prepareMutationCacheWriteOutcome(l.driver,u,n,r().readMutationCacheOptions(t),e,l.scope),b=e.prepare(d,n,v,c?{skipSpan:!0}:void 0,prepareInput,y);return c===void 0?b:this.#l(e,u,n,b,c)}#s(e,t,n,i){let a=r(),o=a.createCacheExecutionOptions(i,t.waitUntil,C(e.driver)),s=Object.freeze({capability:t,options:o});return createModelProxy(this.#e,({modelName:t,operation:r,args:i})=>{try{return a.validateCacheableOperation(r),this.#o(e,t,r,i,n,s)}catch(e){return Promise.reject(e)}})}#c(e){let t=b(e);if(t===void 0)return;let n=this.#i??=new WeakMap,r=n.get(t);if(r!==void 0)return r.resolver;let i=createClientOmitResolver(this.#e,t.config,this.#n);return n.set(t,Object.freeze({resolver:i})),i}#l(e,t,n,i,a){return ft(i,async(s,c)=>{let l=mt(i),u=d(e.extensionChain?.controls?.all??[],l.controls,t,o(n));if(u)throw u;if(c!==void 0||e.transactionWriteOutcomes!==void 0||(e.extensionChain?.statement.length??0)>0)return s();let f=r(),p=f.cacheKeyOf(l.args,l.controls,e.extensionChain?.rows);return p===void 0?s():f.executeCachedResultOperation(a.capability.driver,t,n,p,()=>s(),{...a.options,executionContext:l.executionContext},l.codec,a.capability.scope)})}#u(e,t,n,r,i){let a;return new Proxy(this.#a(e,r?.model,t),{get:(t,o)=>{if(typeof o==`string`&&!o.startsWith(`$`))return Reflect.get(t,o);if(o===`$schema`)return this.#e;if(o===`$transaction`)return n;if(isRawMethodName(o))return a??=createRawSurface({engine:e}),a[o];let s=i?.(o);if(s!==void 0||typeof o!=`string`)return s;let c=r?.client();return c!==void 0&&Object.hasOwn(c,o)?c[o]:Object.hasOwn(this.#e,o)?Reflect.get(t,o):void 0}})}#d(e,t,n,r,i){let transaction=(n,r)=>this.#f(e,t,n,r),a=e.extensionChain,o=a&&bindExtensionMethods(a,(r,i)=>this.#u(e,t,transaction,r,t=>t===`$bind`?t=>n(e.withBound(c(a.controls?.all??[],i,t,e.bound))):void 0));return r&&o?.force(),this.#u(e,t,transaction,o,i)}#f(e,t,n,r){try{let i=Array.isArray(n);e.driver.assertTransactionOptionsSupported(r,i?`batch`:`callback`);let a=e.extensionChain,o=W(`$transaction`,i?`$transaction([...])`:`$transaction(callback)`,a);if(i)return executeArrayTransaction(n,e,r,o);let s=a?.hasQueryHandlers||a?.hasCache||(a?.observe.length??0)>0?new ct:void 0,view=e=>this.#d(e,t,view,!1),body=async t=>n(view(e.bind(t,a,s)));return s?runOutcomeTransaction(e.driver,s,e.transactionWriteOutcomes,r,o,body):e.driver.withTransaction(body,r,o)}catch(e){return Promise.reject(e)}}#p(e,t=!0){let n=e.extensionChain,i=n===void 0?void 0:this.#c(n),disconnect=()=>e.driver._disconnect(W(`$connection`,`$disconnect`,n)),a=n&&(e=>this.#p(e,!1)),o=this.#d(e,i,a,t,t=>{if(t===`$driver`)return e.driver;if(t===`$extends`)return t=>{if(typeof t==`function`)return t(o);let r=ee(n,t,this.#e,this.#r);return r.hasCache&&l(r,e.driver),this.#p(e.bind(e.driver,r))};if(t===`$connect`)return()=>e.driver._connect(W(`$connection`,`$connect`,n));if(t===`$disconnect`||t===f)return disconnect;if(t!==`$withCache`&&t!==`$invalidate`)return;let a=s(n);if(a!==void 0)return t===`$withCache`?t=>this.#s(e,a,i,t):async(...e)=>{await r().invalidateManualCache(a.driver,e,W(`$cache`,`$invalidate`,n),a.scope)}});return o}static create(e){if(!e.driver)throw new P(`Driver is required to create a client. Pass a driver in createClient options.`);if(e.driver.dialect===`postgresql`&&e.driver.adapter.namespace===void 0)throw new P("A PostgreSQL driver must supply an adapter with a namespace. Construct PostgresAdapter, or set `namespace` on a custom adapter.");let t=assertConstructed(()=>{let t=e.skipSchemaValidation===!0,n=reusablePreparation(e.schema,t);n||We(e.schema,t);let r=n?.fittingDialects.has(e.driver.dialect)?void 0:Nt(e.schema,e.driver.dialect);if(r!==void 0)throw new P(Pt(r));e.driver.adapter.geoPoint===void 0&&refuseGeoPointFields(e.schema);let i=n??prepareSchema(e.schema,t);return i.fittingDialects.add(e.driver.dialect),new VibORM(e,i)});return t.#p(t.#t)}};const Rn=new WeakMap;function reusablePreparation(e,t){let n=Rn.get(e);if(!(n&&(n.validated||t)))return;let r=Object.keys(e);if(r.length===n.entries.length){for(let[t,[i,a]]of n.entries.entries())if(r[t]!==i||e[i]!==a)return;return n}}function prepareSchema(e,t){let n=t?Ye(e):Ke(e),r=nt(e,n),i={entries:Object.entries(e),relations:n,schemaRegistry:r,fittingDialects:new Set,validated:!t};return Rn.set(e,i),i}function assertConstructed(e){try{return e()}catch(e){if(D(e))throw e;let t=e instanceof Error?e:void 0;throw new P(t?.message??`Failed to create the VibORM client`,t?{cause:t}:void 0)}}const createClient=e=>Ln.create(e),createClientFromDriverConfig=(e,t)=>{let{schema:n,skipSchemaValidation:r}=e,i={schema:n,driver:t,...r===void 0?{}:{skipSchemaValidation:r}};return Ln.create(i)};export{registerPositionalResultDriver as a,borrowPositionalResult as i,createClientFromDriverConfig as n,assertPositionalRows as r,createClient as t};
2
+ //# sourceMappingURL=client-6YgGlXzN.mjs.map