viborm 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/{adapter-namespace-DMhEF6my.mjs → adapter-namespace-DqkJQdrD.mjs} +2 -2
- package/dist/{adapter-namespace-DMhEF6my.mjs.map → adapter-namespace-DqkJQdrD.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-D9FexFqy.mjs → array-literal-BsbbSLw3.mjs} +1 -1
- package/dist/{array-literal-D9FexFqy.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
- package/dist/base-AdXAoy6l.mjs +2 -0
- package/dist/base-AdXAoy6l.mjs.map +1 -0
- package/dist/batch-refs-4L8ECdPU.mjs +2 -0
- package/dist/batch-refs-4L8ECdPU.mjs.map +1 -0
- package/dist/bind-parameter-capacity-CjPgqnmx.mjs +2 -0
- package/dist/{bind-parameter-capacity-DzMcIB95.mjs.map → bind-parameter-capacity-CjPgqnmx.mjs.map} +1 -1
- package/dist/builder-Ycvq3ETg.mjs +2 -0
- package/dist/builder-Ycvq3ETg.mjs.map +1 -0
- package/dist/bun-sql.d.mts +19 -2
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +9 -8
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache/memory.mjs.map +1 -1
- package/dist/cache-BO57X0TT.mjs +2 -0
- package/dist/cache-BO57X0TT.mjs.map +1 -0
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/canonical-json-rfC2Dg0X.mjs +2 -0
- package/dist/canonical-json-rfC2Dg0X.mjs.map +1 -0
- package/dist/chain-Dh0FV72b.mjs +2 -0
- package/dist/chain-Dh0FV72b.mjs.map +1 -0
- package/dist/cli.mjs +5 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-BLiBmykn.mjs +2 -0
- package/dist/client-BLiBmykn.mjs.map +1 -0
- package/dist/client-CCgfcp5A.mjs +52 -0
- package/dist/client-CCgfcp5A.mjs.map +1 -0
- package/dist/client-CRBo95D0.d.mts +610 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-W8H2Khng.mjs → clock-CK41KO7t.mjs} +1 -1
- package/dist/{clock-W8H2Khng.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
- package/dist/config.d.mts +3 -3
- package/dist/config.mjs +1 -1
- package/dist/controls-DXgIn4zh.mjs +2 -0
- package/dist/controls-DXgIn4zh.mjs.map +1 -0
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/datetime-physical-codec-oIhiYZEP.mjs +2 -0
- package/dist/datetime-physical-codec-oIhiYZEP.mjs.map +1 -0
- package/dist/driver-B19QlFqn.mjs +2 -0
- package/dist/{driver-CRaDT4B7.mjs.map → driver-B19QlFqn.mjs.map} +1 -1
- package/dist/driver-BlnKXPFF.mjs +2 -0
- package/dist/driver-BlnKXPFF.mjs.map +1 -0
- package/dist/driver.d.mts +2 -2
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-CnPCv1dm.mjs +2 -0
- package/dist/error-mapping-CnPCv1dm.mjs.map +1 -0
- package/dist/every-4KE0p2Gw.mjs +2 -0
- package/dist/every-4KE0p2Gw.mjs.map +1 -0
- package/dist/execution-context-BKR3bgES.mjs +2 -0
- package/dist/execution-context-BKR3bgES.mjs.map +1 -0
- package/dist/fs-estate-CAhDg7nY.mjs +2 -0
- package/dist/fs-estate-CAhDg7nY.mjs.map +1 -0
- package/dist/{geo-area-codec-B4DRInvA.mjs → geo-area-codec-1SY9im7O.mjs} +2 -2
- package/dist/{geo-area-codec-B4DRInvA.mjs.map → geo-area-codec-1SY9im7O.mjs.map} +1 -1
- package/dist/geo-point-codec-lhxH42SK.mjs +2 -0
- package/dist/geo-point-codec-lhxH42SK.mjs.map +1 -0
- package/dist/{hydration-D6JICBQG.mjs → hydration-CAxOL4aI.mjs} +2 -2
- package/dist/{hydration-D6JICBQG.mjs.map → hydration-CAxOL4aI.mjs.map} +1 -1
- package/dist/identifier-conversion-GgbwHc2G.mjs +2 -0
- package/dist/identifier-conversion-GgbwHc2G.mjs.map +1 -0
- package/dist/{identifier-EsWKVHXi.mjs → identifier-hQCs8M1n.mjs} +2 -2
- package/dist/{identifier-EsWKVHXi.mjs.map → identifier-hQCs8M1n.mjs.map} +1 -1
- package/dist/identity-CLFhCTZx.mjs +2 -0
- package/dist/identity-CLFhCTZx.mjs.map +1 -0
- package/dist/{index-T0YKKw66.d.mts → index-C_XLSTy2.d.mts} +723 -400
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/instrumentation.mjs.map +1 -1
- package/dist/{invariant-DCsftyml.mjs → invariant-BnLYqsHO.mjs} +1 -1
- package/dist/{invariant-DCsftyml.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
- package/dist/{json-number-C10HFiy6.mjs → json-number-CGXpPu4D.mjs} +1 -1
- package/dist/{json-number-C10HFiy6.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
- package/dist/key-BeoOwGr3.mjs +2 -0
- package/dist/key-BeoOwGr3.mjs.map +1 -0
- package/dist/libsql-Bu_IdFU1.mjs +11 -0
- package/dist/libsql-Bu_IdFU1.mjs.map +1 -0
- package/dist/libsql.d.mts +8 -3
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/memory-D4yxtCPK.mjs +2 -0
- package/dist/memory-D4yxtCPK.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +6 -0
- package/dist/migrations/mysql.mjs +2 -0
- package/dist/migrations/mysql.mjs.map +1 -0
- package/dist/migrations/postgres.d.mts +6 -0
- package/dist/migrations/postgres.mjs +2 -0
- package/dist/migrations/postgres.mjs.map +1 -0
- package/dist/migrations/sqlite.d.mts +6 -0
- package/dist/migrations/sqlite.mjs +2 -0
- package/dist/migrations/sqlite.mjs.map +1 -0
- package/dist/migrations/storage/durable-object.d.mts +17 -0
- package/dist/migrations/storage/durable-object.mjs +2 -0
- package/dist/migrations/storage/durable-object.mjs.map +1 -0
- package/dist/migrations/storage/fs.d.mts +6 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +14 -0
- package/dist/migrations/storage/r2.mjs +2 -0
- package/dist/migrations/storage/r2.mjs.map +1 -0
- package/dist/migrations/tenant.d.mts +92 -0
- package/dist/migrations/tenant.mjs +2 -0
- package/dist/migrations/tenant.mjs.map +1 -0
- package/dist/{migrations-BWZSBMZh.mjs → migrations-DTObIjAm.mjs} +2 -2
- package/dist/migrations-DTObIjAm.mjs.map +1 -0
- package/dist/migrations.d.mts +6 -559
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/mysql-CibPaHSp.mjs +99 -0
- package/dist/mysql-CibPaHSp.mjs.map +1 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs +2 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -3
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/object-store-DQR6bTBY.mjs +2 -0
- package/dist/object-store-DQR6bTBY.mjs.map +1 -0
- package/dist/object-store-DyYOCtmX.d.mts +156 -0
- package/dist/observation-DUSm7oXK.mjs +2 -0
- package/dist/observation-DUSm7oXK.mjs.map +1 -0
- package/dist/pg.d.mts +37 -12
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +2 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/physical-6V_LNU3L.mjs +2 -0
- package/dist/{physical-BkelResN.mjs.map → physical-6V_LNU3L.mjs.map} +1 -1
- package/dist/pinned-session-CLxj5M5e.mjs +2 -0
- package/dist/pinned-session-CLxj5M5e.mjs.map +1 -0
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-B11VjIin.d.mts → planner-C6Lfsasx.d.mts} +57 -3
- package/dist/postgres-adapter-B3SQvcV1.mjs +2 -0
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +1 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs +2 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +1 -0
- package/dist/postgres-oqNW9xqo.mjs +415 -0
- package/dist/postgres-oqNW9xqo.mjs.map +1 -0
- package/dist/{postgres-result-Dc_iW3Hb.mjs → postgres-result-7F0DllQe.mjs} +2 -2
- package/dist/{postgres-result-Dc_iW3Hb.mjs.map → postgres-result-7F0DllQe.mjs.map} +1 -1
- package/dist/postgres.d.mts +11 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/provider-limits-BHATED_m.mjs +2 -0
- package/dist/provider-limits-BHATED_m.mjs.map +1 -0
- package/dist/registration-preflight-DEjv050M.mjs +4 -0
- package/dist/registration-preflight-DEjv050M.mjs.map +1 -0
- package/dist/result-shape-CTNdNSW3.mjs +2 -0
- package/dist/result-shape-CTNdNSW3.mjs.map +1 -0
- package/dist/scalar-U0wD5bKy.mjs +2 -0
- package/dist/{scalar-BTktMqvO.mjs.map → scalar-U0wD5bKy.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-Cjem1-0f.mjs +2 -0
- package/dist/{schema-BFNcMdO6.mjs.map → schema-Cjem1-0f.mjs.map} +1 -1
- package/dist/schema-introspection-DEYGC2qg.mjs +6 -0
- package/dist/schema-introspection-DEYGC2qg.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BgqlrePH.mjs → select-assembly-f1UGoblh.mjs} +2 -2
- package/dist/select-assembly-f1UGoblh.mjs.map +1 -0
- package/dist/settle-B9Vg1FnP.mjs +2 -0
- package/dist/settle-B9Vg1FnP.mjs.map +1 -0
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sql--69HUgel.mjs → sql-Bp7jicEX.mjs} +1 -1
- package/dist/{sql--69HUgel.mjs.map → sql-Bp7jicEX.mjs.map} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +2 -0
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +1 -0
- package/dist/sqlite-utils-DlgokMJN.mjs +2 -0
- package/dist/sqlite-utils-DlgokMJN.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -8
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs +6 -0
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +1 -0
- package/dist/{suppressed-failure-BPxfHTMc.mjs → suppressed-failure-BwULh-8h.mjs} +1 -1
- package/dist/{suppressed-failure-BPxfHTMc.mjs.map → suppressed-failure-BwULh-8h.mjs.map} +1 -1
- package/dist/{terminal-BbRi0CNZ.mjs → terminal-C8cq1WWX.mjs} +2 -2
- package/dist/{terminal-BbRi0CNZ.mjs.map → terminal-C8cq1WWX.mjs.map} +1 -1
- package/dist/{transaction-oskVwmsf.mjs → transaction-Bnl6ULTw.mjs} +2 -2
- package/dist/transaction-Bnl6ULTw.mjs.map +1 -0
- package/dist/{transaction-operation-BC7aua5V.mjs → transaction-operation-CKK3l_9x.mjs} +2 -2
- package/dist/transaction-operation-CKK3l_9x.mjs.map +1 -0
- package/dist/{utils-DfztpPvR.mjs → utils-CZNaOZR7.mjs} +4 -3
- package/dist/utils-CZNaOZR7.mjs.map +1 -0
- package/dist/v-D5Z06FKN.mjs +2 -0
- package/dist/v-D5Z06FKN.mjs.map +1 -0
- package/dist/validation-Dk9Q_-C7.mjs +2 -0
- package/dist/validation-Dk9Q_-C7.mjs.map +1 -0
- package/dist/validation-PF9-_nKd.mjs +2 -0
- package/dist/{validation-tgjL_9n8.mjs.map → validation-PF9-_nKd.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-X9-bwtRo.mjs +2 -0
- package/dist/{validator-DMlEScV3.mjs.map → validator-X9-bwtRo.mjs.map} +1 -1
- package/dist/value-guards-CK9guf2Z.mjs +2 -0
- package/dist/value-guards-CK9guf2Z.mjs.map +1 -0
- package/dist/version-JDaZht4U.mjs +2 -0
- package/dist/{version-Cr80LFvx.mjs.map → version-JDaZht4U.mjs.map} +1 -1
- package/package.json +75 -34
- package/dist/base-vfur-DaU.mjs +0 -2
- package/dist/base-vfur-DaU.mjs.map +0 -1
- package/dist/batch-refs-BY51FIXm.mjs +0 -6
- package/dist/batch-refs-BY51FIXm.mjs.map +0 -1
- package/dist/bind-parameter-capacity-DzMcIB95.mjs +0 -2
- package/dist/builder-bPfagDQV.mjs +0 -2
- package/dist/builder-bPfagDQV.mjs.map +0 -1
- package/dist/chain-uIFlkkXS.mjs +0 -2
- package/dist/chain-uIFlkkXS.mjs.map +0 -1
- package/dist/client-NleI4Nm-.mjs +0 -434
- package/dist/client-NleI4Nm-.mjs.map +0 -1
- package/dist/client-tjSMPjeZ.mjs +0 -2
- package/dist/client-tjSMPjeZ.mjs.map +0 -1
- package/dist/controls-BhxRnPYS.mjs +0 -2
- package/dist/controls-BhxRnPYS.mjs.map +0 -1
- package/dist/decimal-12NERGYZ.mjs +0 -3
- package/dist/decimal-12NERGYZ.mjs.map +0 -1
- package/dist/driver-CRaDT4B7.mjs +0 -2
- package/dist/driver-options-DxlB1tms.mjs +0 -2
- package/dist/driver-options-DxlB1tms.mjs.map +0 -1
- package/dist/driver-yCYqzIQg.mjs +0 -2
- package/dist/driver-yCYqzIQg.mjs.map +0 -1
- package/dist/error-mapping-BWzb-l02.mjs +0 -2
- package/dist/error-mapping-BWzb-l02.mjs.map +0 -1
- package/dist/execution-context-BPk0YLhd.mjs +0 -2
- package/dist/execution-context-BPk0YLhd.mjs.map +0 -1
- package/dist/fs-estate-3Bu_K9mk.d.mts +0 -7
- package/dist/fs-estate-BcjgY4iY.mjs +0 -2
- package/dist/fs-estate-BcjgY4iY.mjs.map +0 -1
- package/dist/geo-point-codec-DUTTtlav.mjs +0 -2
- package/dist/geo-point-codec-DUTTtlav.mjs.map +0 -1
- package/dist/identifiers-By-JRCb5.mjs +0 -2
- package/dist/identifiers-By-JRCb5.mjs.map +0 -1
- package/dist/key-DKaqPb8w.mjs +0 -2
- package/dist/key-DKaqPb8w.mjs.map +0 -1
- package/dist/migrations-BWZSBMZh.mjs.map +0 -1
- package/dist/mysql-adapter-D9FoHlWE.mjs +0 -2
- package/dist/mysql-adapter-D9FoHlWE.mjs.map +0 -1
- package/dist/observation-CLp8ylmL.mjs +0 -2
- package/dist/observation-CLp8ylmL.mjs.map +0 -1
- package/dist/physical-BkelResN.mjs +0 -2
- package/dist/pinned-session-Ca7C9yxY.mjs +0 -2
- package/dist/pinned-session-Ca7C9yxY.mjs.map +0 -1
- package/dist/postgres-adapter-T2Iko-vt.mjs +0 -2
- package/dist/postgres-adapter-T2Iko-vt.mjs.map +0 -1
- package/dist/registration-preflight-BrA3EWvq.mjs +0 -4
- package/dist/registration-preflight-BrA3EWvq.mjs.map +0 -1
- package/dist/result-shape-DKTu8yre.mjs +0 -2
- package/dist/result-shape-DKTu8yre.mjs.map +0 -1
- package/dist/scalar-BTktMqvO.mjs +0 -2
- package/dist/schema-BFNcMdO6.mjs +0 -2
- package/dist/schema-introspection-DsXPfCst.mjs +0 -6
- package/dist/schema-introspection-DsXPfCst.mjs.map +0 -1
- package/dist/select-assembly-BgqlrePH.mjs.map +0 -1
- package/dist/sqlite-adapter-HqO3GpAK.mjs +0 -2
- package/dist/sqlite-adapter-HqO3GpAK.mjs.map +0 -1
- package/dist/sqlite-utils-D26BFuJJ.mjs +0 -2
- package/dist/sqlite-utils-D26BFuJJ.mjs.map +0 -1
- package/dist/transaction-operation-BC7aua5V.mjs.map +0 -1
- package/dist/transaction-oskVwmsf.mjs.map +0 -1
- package/dist/transactions-gjmrWN5W.mjs +0 -2
- package/dist/transactions-gjmrWN5W.mjs.map +0 -1
- package/dist/utils-DfztpPvR.mjs.map +0 -1
- package/dist/v-B2WwtcRz.mjs +0 -2
- package/dist/v-B2WwtcRz.mjs.map +0 -1
- package/dist/validation-Du6j0Q38.mjs +0 -2
- package/dist/validation-Du6j0Q38.mjs.map +0 -1
- package/dist/validation-tgjL_9n8.mjs +0 -2
- package/dist/validator-DMlEScV3.mjs +0 -2
- package/dist/version-Cr80LFvx.mjs +0 -2
- /package/dist/{contract-BHUOUAZ-.d.mts → contract-CIIqgFyb.d.mts} +0 -0
- /package/dist/{sql--yhoVvRM.d.mts → sql-BvfwUKIh.d.mts} +0 -0
package/dist/client-tjSMPjeZ.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{C as t,T as n,a as r,c as i,d as a,f as o,l as s,o as c,p as l,r as u,s as d,t as f,u as p,v as m}from"./validation-Du6j0Q38.mjs";import{_ as h,c as g,d as _,n as v,o as y,u as b}from"./controls-BhxRnPYS.mjs";import{_ as x,a as S,g as C,m as w,n as T,r as E,u as D}from"./bind-parameter-capacity-DzMcIB95.mjs";import{c as O,d as k,i as ee,l as A,n as te,o as ne,r as re}from"./chain-uIFlkkXS.mjs";import{b as j,i as M,n as N,t as P}from"./base-vfur-DaU.mjs";import{d as F,i as ie,o as ae}from"./observation-CLp8ylmL.mjs";import{f as oe,i as se,m as I,o as ce,t as le,u as ue}from"./error-mapping-BWzb-l02.mjs";import{n as L,t as R}from"./transaction-oskVwmsf.mjs";import{_ as z,b as B,x as V,y as de}from"./terminal-BbRi0CNZ.mjs";import{o as H,r as fe,t as U}from"./sql--69HUgel.mjs";import{C as W,S as pe,T as me,_ as he,a as ge,b as _e,c as G,f as ve,g as ye,h as be,i as xe,p as Se,r as Ce,s as we,t as Te,v as K,w as Ee,x as De,y as Oe}from"./result-shape-DKTu8yre.mjs";import{i as ke,n as Ae}from"./execution-context-BPk0YLhd.mjs";import{n as je,r as q,t as Me}from"./transaction-operation-BC7aua5V.mjs";import{n as Ne}from"./invariant-DCsftyml.mjs";import{n as J,t as Y}from"./adapter-internals-n3Mf3css.mjs";import{a as Pe,i as Fe,o as Ie,r as Le,t as Re}from"./builder-bPfagDQV.mjs";import{f as ze,l as Be,n as Ve,p as X,s as He,t as Ue,u as We}from"./validator-DMlEScV3.mjs";import{A as Ge,C as Ke,F as qe,H as Je,J as Ye,M as Xe,P as Ze,S as Qe,St as $e,U as et,W as tt,X as nt,Y as rt,bt as it,d as at,et as ot,f as st,g as ct,h as lt,j as ut,k as dt,m as ft,r as pt,w as mt}from"./geo-point-codec-DUTTtlav.mjs";import{c as ht,o as gt,s as _t}from"./v-B2WwtcRz.mjs";import{a as vt,i as yt,r as bt,t as xt}from"./identifiers-By-JRCb5.mjs";import{r as St}from"./geo-area-codec-B4DRInvA.mjs";import{t as Ct}from"./hydration-D6JICBQG.mjs";import{t as wt}from"./validation-tgjL_9n8.mjs";import{f as Tt,g as Et,h as Dt,t as Ot,u as kt}from"./decimal-12NERGYZ.mjs";const At=Object.freeze({$executeRaw:!0,$executeRawUnsafe:!0,$queryRaw:!0,$queryRawUnsafe:!0});function rawQueryKind(e){return e===`$queryRaw`?`queryRaw`:e===`$executeRaw`?`executeRaw`:e===`$queryRawUnsafe`?`queryRawUnsafe`:`executeRawUnsafe`}function isRawWrite(e){return e===`$executeRaw`||e===`$executeRawUnsafe`}function isTemplateStringsArray(e){return Array.isArray(e)&&Array.isArray(Reflect.get(e,`raw`))}function invalidRawQueryError(e){return new o(`${e} expects a tagged template (${e}\`SELECT ...\`) or an Sql fragment built with sql\`...\`. Received a value that is neither.`,{code:N.INVALID_INPUT,meta:{method:e}})}function fragmentWithValuesError(e){return new o(`${e} received an Sql fragment together with extra values. The fragment already carries its parameters — interpolate them into it instead.`,{code:N.INVALID_INPUT,meta:{method:e}})}function invalidRawDateError(e,t){return new o(`${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.`,{code:N.INVALID_INPUT,meta:{method:e,parameterIndex:t}})}function unsupportedRawArrayError(e,t){return new o(`${e} received raw array parameter ${t} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,{code:N.INVALID_INPUT,meta:{method:e,parameterIndex:t}})}function hasOwnIndex(e,t){return Object.hasOwn(e,t)}function copyIndexedValues(e){let t=Array(e.length);for(let n=0;n<e.length;n+=1)hasOwnIndex(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 U(copySqlStrings(e.strings),copyIndexedValues(e.values))}function validateRawParametersBeforeInterception(e,t){D(t,{invalidDate:t=>invalidRawDateError(e,t),unsupportedArray:t=>unsupportedRawArrayError(e,t)})}function captureValues(e){return Object.freeze(copyIndexedValues(e))}const jt=Object.freeze({});let createDeferredRawOperation,Mt;(class DeferredRawOperation{[Symbol.toStringTag]=`Promise`;#e;#t;#n;#r;#i;#a;#o;#s;#c;static{createDeferredRawOperation=(e,t,n,r)=>new DeferredRawOperation(jt,e,t,n,r),Mt=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(),o=a.kind===`fragment`?{query:a.query}:{sql:a.sql,params:[...a.params]};return me(Object.freeze({mode:`array`,kind:rawQueryKind(e.#r),model:void 0,operation:e.#r,input:ye(o)}),i,t,isRawWrite(e.#r),n,r)},executeCore:(e,t,n)=>e.#t.executeReserved(()=>e.#p(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():ie(r,e.#r,void 0,t,n,e.#h())},reserveWith:(e,t)=>{e.#t.reserveWith(t)},executeWith:(e,t)=>{let execute=()=>e.#p(t,e.#l()),n=e.#e.extensionChain?.observe;return n===void 0||n.length===0?e.#t.executeWith(t,execute):e.#t.executeWith(t,()=>ie(n,e.#r,void 0,execute,()=>e.#c===void 0?void 0:{commitCertainty:e.#c},e.#h()))},prepare:(e,t=e.#e.driver)=>{let n=e.#l();if(n.kind===`verbatim`)return C({sql:n.sql,params:[...n.params],context:e.#n});let r=t._prepare(n.query,e.#n);return w(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)=>_e(e.#n,t,n)}),je(DeferredRawOperation.prototype,e=>#e in e,Mt),Object.freeze(DeferredRawOperation.prototype)}constructor(e,t,n,r,i){if(e!==jt)throw new R;this.#e=t,this.#r=n,this.#i=r,this.#a=i,this.#o=ee(t.extensionChain,`query`,void 0,n),this.#t=new he(`$raw`,n),this.#n=K(`$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{query:e,values:t}=this.#i;if(this.#i.family===`unsafe`){if(typeof e!=`string`)throw invalidRawQueryError(this.#r);return{kind:`verbatim`,sql:e,params:[...t]}}if(isTemplateStringsArray(e))return{kind:`fragment`,query:new U(e,t)};if(fe(e)){if(t.length>0)throw fragmentWithValuesError(this.#r);return{kind:`fragment`,query:createOperationSql(e)}}throw invalidRawQueryError(this.#r)}#d(e){return De(this.#n,()=>this.#f(e))}#f(e){let t=this.#o;if(t===void 0||t.length===0)return this.#p(e,this.#l(),this.#g());let n;try{n=this.#l()}catch(e){return Promise.reject(e)}let r=n.kind===`fragment`?{query:n.query}:{sql:n.sql,params:[...n.params]};return me(Object.freeze({mode:this.#e.transactionWriteOutcomes?`transaction`:`direct`,kind:rawQueryKind(this.#r),model:void 0,operation:this.#r,input:ye(r)}),t,t=>this.#p(e,n,this.#g(t)),isRawWrite(this.#r),this.#e.transactionWriteOutcomes)}async#p(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 m(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`?m(a.error,e):e}if(a.status===`failure`)throw a.error;return a.value}#m(){return this.#t.executeDefault(()=>{let e=this.#e.extensionChain?.observe;return e===void 0||e.length===0?this.#d(this.#e.driver):ie(e,this.#r,void 0,()=>this.#d(this.#e.driver),()=>this.#c===void 0?void 0:{commitCertainty:this.#c},this.#h())})}#h(){return Oe(this.#e.driver,this.#n,this.#r)}#g(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.#m().then(e,t)}catch(e){return this.#m().catch(e)}finally(e){return this.#m().finally(e)}});function createRawSurface(e){let{engine:t}=e;function $queryRaw(e,...n){return createDeferredRawOperation(t,`$queryRaw`,{family:`safe`,query:e,values:captureValues(n)},e=>e.rows)}function $queryRawUnsafe(e,...n){return createDeferredRawOperation(t,`$queryRawUnsafe`,{family:`unsafe`,query:e,values:captureValues(n)},e=>e.rows)}function $executeRaw(e,...n){return createDeferredRawOperation(t,`$executeRaw`,{family:`safe`,query:e,values:captureValues(n)},e=>e.rowCount)}function $executeRawUnsafe(e,...n){return createDeferredRawOperation(t,`$executeRawUnsafe`,{family:`unsafe`,query:e,values:captureValues(n)},e=>e.rowCount)}return{$executeRaw,$executeRawUnsafe,$queryRaw,$queryRawUnsafe}}const Nt=new Set([`$driver`,`$schema`,`$transaction`,`$connect`,`$disconnect`,`$withCache`,`$invalidate`,`$extends`]);function readMethodRecord(e,r,i){n(e)||A(`Extension "${i}" ${r} factory must return an object.`,i);let a=Object.create(null),o;try{o=Reflect.ownKeys(e)}catch(e){throw new u(`Extension "${i}" ${r} methods could not be inspected.`,{cause:O(e),meta:{extension:i}})}for(let n of o){typeof n!=`string`&&A(`Extension "${i}" ${r} returned a non-string method key.`,i);let o;try{o=e[n]}catch(e){throw new u(`Extension "${i}" ${r} method "${n}" could not be read.`,{cause:O(e),meta:{extension:i}})}t(o)||A(`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 u(`Extension "${r}" ${n} factory failed.`,{cause:O(e),meta:{extension:r}})}}function bindExtensionMethod(e){return(...t)=>Reflect.apply(e,void 0,t)}function snapshotMethods(e,t){let n=Object.create(null);for(let[t,r]of Object.entries(e))n[t]=r;let r=Object.create(null);for(let[e,n]of Object.entries(t)){let t=Object.create(null);for(let[e,r]of Object.entries(n))t[e]=r;r[e]=Object.freeze(t)}return Object.freeze({client:Object.freeze(n),models:Object.freeze(r)})}function bindExtensionMethods(e,t){let n=Object.create(null),r=Object.create(null);for(let i of e.extensions){let e=snapshotMethods(n,r),a=t(e.client,e.models),o=i.client?readMethodRecord(invokeFactory(i.client,a,`client`,i.name),`client`,i.name):void 0,s=Object.create(null);if(i.model)for(let[e,t]of Object.entries(i.model))s[e]=readMethodRecord(invokeFactory(t,Reflect.get(a,e),`model.${e}`,i.name),`model.${e}`,i.name);if(o)for(let[e,t]of Object.entries(o))e.startsWith(`$`)||A(`Extension "${i.name}" client method "${e}" must be dollar-prefixed.`,i.name),(Nt.has(e)||Object.hasOwn(At,e)||Object.hasOwn(n,e))&&A(`Extension "${i.name}" client method "${e}" collides with the existing client surface.`,i.name),n[e]=t;for(let[e,t]of Object.entries(s)){let n=r[e]??=Object.create(null);for(let[r,a]of Object.entries(t))(r===`then`||y.has(r)||Object.hasOwn(n,r))&&A(`Extension "${i.name}" model method "${e}.${r}" collides with the existing model surface.`,i.name),n[r]=a}}return snapshotMethods(n,r)}const resultShapeKeys=(...e)=>Object.freeze(e),Pt=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()}),Ft=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??Ft,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:v(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?Ft: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`?Pt[e].includes(t):!1}function isPromiseLike(e){return n(e)&&`then`in e&&t(e.then)}function normalizeThrown(e){return j(e)?e:Error(`Request transform threw a non-Error value`)}function transformFailure(e,t,n,r,i){return new o(`Extension "${e}" request handler for ${t}.${n} ${r}.`,{cause:i,meta:{model:t,operation:n}})}var It=class QueryEngine{driver;extensionChain;transactionWriteOutcomes;clientId;scopeId;route;constructor(e,t,n=Symbol(`viborm.client`),r=Symbol(`viborm.scope`),i,a){this.driver=e,this.route=t,this.extensionChain=i,this.transactionWriteOutcomes=a,this.clientId=n,this.scopeId=r}bind(e,t=this.extensionChain,n=this.transactionWriteOutcomes){return new QueryEngine(e,this.route,this.clientId,Symbol(`viborm.scope`),t,n)}prepare(e,t,n,r,i,a){return Se(this,e,t,n,r,i,a)}};const Lt=new WeakMap;function registerPositionalResultDriver(e,t,n){Lt.set(e,{execute:t,isEligible:n})}function resolvePositionalResultDriver(e){let t=Lt.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 o(`Driver "${n.provider}" returned malformed positional rows for operation "${n.operation}".`,{meta:S(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===`unsupported`)return new l(e.message,{meta:{model:t,operation:n}});if(e.kind===`foreignKey`)return new oe(e.message,{meta:{model:t,operation:n}});if(e.kind===`nestedWrite`){let t=new i(e.message,e.relation??``);return e.raceable&&(t.meta.raceable=!0),t}if(e.kind===`notFound`)return new s(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 d))return e;let a=e.meta.statementIndex;if(typeof a==`number`){let n=t.find(e=>e.queryIndex===a);return n?createFailureError(n.failure,n.model,n.operation):e}if(t.length>0&&le(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[o]=t;return o?t.every(e=>sameAttribution(e,o))?createFailureError(o.failure,o.model,o.operation):e:new i(c,``,{code:N.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}function exactDecimalDomain(e){return e.type===`decimal`&&e.array!==!0?e.decimal:void 0}function requireDecimal(e,t){if(!e.decimal)throw new a(`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=ct(e);if(n===void 0)throw new a(`Decimal field '${t}' received a value that is not an exact decimal.`);return n}function decimalMembers(e,t,n,r){let i=dt(t,requireDecimal(e,n),r.decimalListRepresentation??`text`);if(i===void 0)throw new a(`Decimal list '${n}' received a member that is not an exact decimal.`);return i}function dividesByZero(e){return ct(e)===`0`}function sameDecimalDomain(e,t){return Ze(e,t)}function decimalSumOperand(e,t){let n=ct(e);if(n!==void 0)return{canonical:n,coefficient:Ge(n,t.scale)}}function decodeDecimalScalar(e,t,n,r,i){let a=i.decimalRepresentation??`text`;return n?r?mt(e,t,a):Xe(e,t,a):r?Qe(e,t,a):ut(e,t,a)}function decodeDecimalList(e,t,n,r){let i=Ke(e,t,r.decimalListRepresentation??`text`);if(i!==void 0)return n?i:i.map(e=>qe(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=He(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 nt(t,e.domain,e.representation)}function decodeIdentifier(e,t){return Ye(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`${rt(e.domain)}, stored ${t}`}function incomparableIdentifiers(e,t,n,r){let i=e?.representation??`text`;if(!(i===(t?.representation??`text`)&&(i===`text`||ot(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 Je(`anyValue`,e=>tt(e))}function rawRecord(){return Je(`rawRecord`,e=>n(e)?tt(e):et(`Expected object, received ${Array.isArray(e)?`array`:typeof e}`))}function parseValidated(e,t,n,r){let i=wt(e,t);if(i.issues){let e=r?[r]:[];throw new f(n,i.issues.map(t=>({path:[...e,...t.path?.map(String)??[]].join(`.`)||`root`,message:t.message})),{cause:$e(i)})}return i.value}const Rt=ft({where:rawRecord(),create:rawRecord(),update:rawRecord(),select:anyValue(),include:anyValue(),omit:anyValue(),targetWhere:anyValue(),setWhere:anyValue()},{atLeast:[`where`,`create`,`update`]});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 zt=new Set([`findMany`,`findUnique`,`findFirst`,`count`,`exist`,`aggregate`,`groupBy`]);function isReadOperation(e){return zt.has(e)}const Bt=[`multiply`,`divide`],Vt=[`set`,`increment`,`decrement`,`multiply`,`divide`];function record(e){return e}function entries(e){return Array.isArray(e)?e:[record(e)]}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}Ct(e),this.index=Ve(e),this.registry=Re(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,``)}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=Vt.filter(e=>i[e]!==void 0);if(a.length!==1)return new l(`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`&&Bt.includes(o))return new l(`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 l(`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(Vt.filter(e=>o[e]!==void 0).length!==1)return new l(`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 l(`Cannot divide a primary key by zero.`)}}}#o(e,t){let r=parseValidated(Rt,t,`upsert`,``),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`),c=a?void 0:parseValidated(i.core.scalarCreate,r.create,`upsert`,`create`),l=parseValidated(i.core.scalarUpdate,o,`upsert`,`update`),u=parseValidated(i.core.upsertProjection,{select:r.select,include:r.include,omit:r.omit},`upsert`,``),d={targetWhere:void 0,setWhere:void 0};for(let e of[`targetWhere`,`setWhere`]){let t=r[e];if(t===void 0)continue;let a=parseValidated(i.core.where,t,`upsert`,e);n(a)&&Object.keys(a).length&&(d[e]=record(a))}let f=a?parseValidated(i.core.create,r.create,`create`,`data`):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[e,i]of Object.entries(t))r[e]=parseValidated(n[e].create,i,`create`,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`));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 e of o.sort((e,t)=>Number(isVariant(e))-Number(isVariant(t))))t[e]!==void 0&&(a[e]=parseValidated((isVariant(e)?i.polymorphic[e]:i.relations[e]).update,t[e],`update`,`data.${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}`)).updateMany)[0].data)}keys(e){return X(e).rowKey.fields}identity(e,t){return Object.fromEntries(this.keys(e).map(e=>[e,t[e]]))}membership(e,t,n){let r=this.#e.get(e);r||(r=new Map,this.#e.set(e,r));let i=r.get(t);i||(i=new Map,r.set(t,i));let a=i.get(n);return a||(a=freezeMembershipView(buildMembershipView(this,e,t,n)),i.set(n,a)),a}restrictingSlots(e){let t=this.#i.get(e);if(t)return t;let n=[];for(let[t,r]of this.index.get(e)??[]){let i=r.edge;if(i.kind!==`foreignKey`&&i.kind!==`junction`)continue;let a=this.membership(e,t),o=a.kind===`junction`?We(a.sourceSide):i.kind===`foreignKey`&&a.owner===`target`?Be(i):void 0;(o===`restrict`||o===`noAction`)&&n.push(t)}return t=Object.freeze(n),this.#i.set(e,t),t}clearability(e){let t=this.#r.get(e);return t||(t=Pe(e),t.kind===`columns`&&Object.freeze(t.fields),Object.freeze(t),this.#r.set(e,t)),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){let t=this.#s.get(e);return t===void 0&&(t=createQueryViews(),this.#s.set(e,t)),t}storedFields(e){let t=this.#n.get(e);return t||(t=Object.freeze(buildStoredFieldsView(this,e)),this.#n.set(e,t)),t}scalars(e,t){let n={};for(let r of e[`~`].scalarFieldNames){let e=t[r];e!==void 0&&(n[r]=e)}return n}};const Z=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]:H`(${H.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!==`and`||e.predicates.some(states)}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 Ht=`Cursor pagination supports direct scalar sort directions only; relation and vector-distance orderBy are not supported.`,Ut=Z({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}};const Wt=`_distance`,Q=Z({root:`__rq_root`,nodes:`__rq_nodes`,edges:`__rq_edges`,key:`__rq_key`,row:`__rq_row`,parent:`__rq_parent`,child:`__rq_child`,depth:`__rq_depth`}),Gt=[`_count`,`_avg`,`_sum`,`_min`,`_max`],Kt=new Set(Gt);function isAggregate(e){return Kt.has(e)}const qt=Z({kind:`scalar`,type:`boolean`,nullable:!1}),$=Z({kind:`scalar`,type:`int`,nullable:!1}),Jt=new Set([`is`,`isNot`,`some`,`every`,`none`]),Yt=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=>Yt.has(e)):!1}const Xt=[`increment`,`decrement`,`multiply`,`divide`],Zt=[`push`,`unshift`];function isOperatorRecord(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function wholeValue(e){return e instanceof U||typeof e!=`object`||!e||!isOperatorRecord(e)?{value:e}:Object.hasOwn(e,`set`)?{value:record(e).set}:void 0}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 Fe(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 Qt=Object.freeze({purpose:`root`});var PreparedDomain=class{rows;#e;#t={root:new Map,related:new Map};#n;constructor(e,t){this.rows=e,this.#e=t}get reads(){return this.#n??=this.#e.under(this)}selector(e,t){let n=e[`~`].names.ts,r=this.rows[t].get(n);if(r===void 0)return;let i=this.#t[t],a=i.get(n);if(a===void 0){let t=this.#e;a=r.length===1?t.prepareSelector(e,r[0]):t.andSelectors(e,r.map(n=>t.prepareSelector(e,n))),i.set(n,a)}return a}};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 $t=class Queries{schema;adapter;#e=0;#t;#n;#r;domain;constructor(e,t,n,r,i){this.schema=e,this.adapter=t,this.#n=e.queryViews(t),this.#r=n,this.domain=r,this.#t=i}captureModels(e){let t=this.#t,n=new Set;this.#t=n;try{return{value:e(),models:n}}finally{this.#t=t}}under(e){return new Queries(this.schema,this.adapter,this.#r,e)}fieldReader(e){let t=this.adapter.result,adapterLeg=n=>t.parseField(n,e,e=>e===void 0?n:e),n=this.#r?.parseField;return t=>{try{return n?n(t,e,adapterLeg):adapterLeg(t)}catch(t){throw t instanceof InvalidScalarResult||t instanceof P?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.#r?.parseResult;return r?r(e,t,e=>adapterDecode(e)):adapterDecode(e)}alias(){return`q${this.#e++}`}#i(){return this.#e=0,this.alias()}table(e,t){return this.#t?.add(e),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 U?H`(${e})`:this.adapter.literals.value(e)}fieldValue(e,t,n){return this.#a(physicalField(this.schema,e,t).scalar,n,t,this.scalarShape(e,t).id)}#a(e,t,n,r){let i=this.adapter,a=e[`~`].state;if(t instanceof U){let e=H`(${t})`;return a.type===`decimal`&&a.array!==!0?i.expressions.decimalCast(e,a.decimal):e}let o=z(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.#s(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.#o(e,t,n);default:return i.literals.value(t)}}#o(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.#l(`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,ht);return typeof n==`string`?r.literals.dateTime(n,a?void 0:this.#c(e),a):r.literals.value(n)}case`time`:{let e=_t(t);return r.literals.value(`value`in e?e.value:t)}case`date`:{let e=admittedTemporal(t,gt);return typeof e==`string`?r.literals.dateTime(e,void 0,a):r.literals.value(e)}default:return r.literals.value(t)}}#s(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)}#c(e){return e[`~`].state.array===!0?void 0:e[`~`].nativeType}#l(e){let t=this.adapter.geoPoint;if(!t)throw new r(`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.#u(a,r):transportedIdentifier(this.adapter,i.id,r,i.nullable)}#u(e,t){if(e.type===`decimal`)return e.array===!0?this.adapter.arrays.exactNumericProjection(t):this.adapter.expressions.cast(t,`text`);let n=this.#l(`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}#d(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.#n.leaves.get(e);n===void 0&&(n=new Map,this.#n.leaves.set(e,n));let r=n.get(t);if(r===void 0){let i=physicalField(this.schema,e,t);r=this.#f(i.scalar,i.nullable,identifierColumn(this.adapter,this.schema.index,e,t,i)),n.set(t,r)}return r}#f(e,t,n){let r=e[`~`].state;return Z({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.#c(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.#i(),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`?r.expressions.cast(n,`text`):transportedIdentifier(r,t.id,n,t.nullable),e.junctionField)});return{sql:Y(r,{columns:H.join(s,`, `),from:r.identifiers.table(e.table,i),where:this.junctionWhere(e,t,i),forUpdate:n}),shape:{kind:`object`,fields:o}}}#p(e,t,n){let r=wholeValue(n);if(r)return{kind:`value`,value:r.value};let i=record(n);for(let n of Xt)if(Object.hasOwn(i,n)){let r=i[n];if(n===`divide`&&exactDecimalDomain(physicalField(this.schema,e,t).scalar[`~`].state)&÷sByZero(r))throw new a(`Cannot divide decimal field '${t}' by zero.`);return{kind:`arithmetic`,operator:n,by:r}}for(let e of Zt)if(Object.hasOwn(i,e)){let t=i[e];return{kind:`list`,operator:e,members:Array.isArray(t)?t:[t]}}throw new a(`Unknown update operation: ${Object.keys(i).join(`, `)}`)}#m(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.#p(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.#m(e,t))}updateValue(e,t,n,r){let i=this.adapter,o=this.#p(e,t,n);if(o.kind===`value`)return this.fieldValue(e,t,o.value);let s=physicalField(this.schema,e,t).scalar[`~`].state,c=exactDecimalDomain(s)!==void 0&&(o.operator===`multiply`||o.operator===`divide`);if(o.kind===`list`||c)throw new a(`Cannot determine the updated value of '${e[`~`].names.ts??`unknown`}.${t}' before '${o.operator}' executes: the database determines the stored result.`);let l=s.type===`int`?i.expressions.cast(r,`integer`):r,u=this.fieldValue(e,t,o.by);return o.operator===`increment`?i.expressions.add(l,u):o.operator===`decrement`?i.expressions.subtract(l,u):o.operator===`multiply`?i.expressions.multiply(l,u):s.type===`int`||s.type===`bigint`?i.expressions.integerDivide(l,u):i.expressions.divide(l,u)}prepareSelector(e,t,n=!1,r=!0){if(!r)return Z({model:e,predicate:t?this.#y(e,t,void 0,[],n):void 0});let i=newSelectorFacts(),a=Object.keys(t??{}),o=a.length===1?ze(e,a[0]):void 0,s=o?o.name?record(t[o.name]):t:void 0;return Z({model:e,facts:i,uniqueKey:o,uniqueValues:s?new Map(o.fields.map(e=>[e,s[e]])):void 0,predicate:t?this.#y(e,t,i,[],n):void 0})}selectorFacts(e){return e.facts}identitySelector(e,t){let n=newSelectorFacts();return Z({model:e,facts:n,predicate:this.identityPredicate(e,t,n)})}identityPredicate(e,t,n){return Z({kind:`and`,predicates:Z(Object.entries(t).map(([t,r])=>this.#b(e,t,r,n)))})}excludeIdentities(e,t){let n=newSelectorFacts(),r=this.#h(e,t,n);return Z({model:e,facts:n,predicate:t.length===0?void 0:this.combine(`NOT`,[r])})}includeIdentities(e,t){let n=newSelectorFacts();return Z({model:e,facts:n,predicate:this.#h(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)})}#h(e,t,n){let r=X(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 Z({model:e,facts:n,predicate:r.length===0?void 0:Z({kind:`and`,predicates:Z(r)})})}candidates(e,t,n=this.domain){let r=n?.selector(e.model,t);return r===void 0?e:Object.freeze({...this.andSelectors(e.model,[e,r]),uniqueKey:e.uniqueKey,uniqueValues:e.uniqueValues,scoped:!0})}#g(e,t,n){let r=this.domain?.selector(e,n);return r?.predicate===void 0?t:t?.predicate===void 0?r:Z({model:e,predicate:Z({kind:`and`,predicates:Z([t.predicate,r.predicate])})})}lowerSelector(e,t,n){return e.predicate?this.#O(e.predicate,t,n):void 0}lowerWhere(e,t,n){let r=this.#g(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=Y(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;return n===void 0?{where:this.lowerSelector(t,i,i)}:r.capabilities.supportsMutationRowLimit?{where:this.lowerSelector(t,i,i),suffix:H`${r.clauses.orderBy(this.#v(e))} ${r.clauses.limit(this.value(n))}`}:{where:r.operators.and(...[this.lowerSelector(t,i,i),this.#_(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.#i(),r=Y(t,{columns:t.literals.true(),from:this.table(e.model,n),where:this.lowerSelector(e,n),forUpdate:!0});return{sql:Y(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})})}#_(e,t,n){let r=this.adapter,i=e.model,a=this.alias(),o=this.keyOrder(i),s=Y(r,{columns:H.join(o.map(e=>this.column(i,e,a)),`, `),from:this.table(i,a),where:this.lowerSelector(e,a),orderBy:this.#v(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:H`SELECT * FROM ${r.subqueries.correlate(s,this.alias())}`))}#v(e,t){return H.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?Ut:Z({kind:`or`,predicates:Z(n)}):Z({kind:`and`,predicates:Z(e===`AND`?n:n.map(e=>Z({kind:`not`,predicate:e})))})}#y(e,t,n,r,i=!1,a=!0){return Z({kind:`and`,predicates:Z(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.#y(e,i,n,r,!1,t===`NOT`?!a:a)));if(e[`~`].state.relations[t])return this.#T(e,t,o,n,r,a);let s=i||e[`~`].state.scalars[t]===void 0?ze(e,t):void 0;return s?.name?Z({kind:`and`,predicates:Z(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)}))})}#b(e,t,n,r,i=!1,a=!0){let o=Z({model:e,field:t,physical:physicalField(this.schema,e,t)});if(r){r.fields.add(t);let e=typeof n==`object`&&n&&!(n instanceof U)&&!V(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 U))?(r.equals.set(t,o),i&&r.keys.set(t,o)):r.exact=!1}return this.#x(Z(i?{kind:`column`,scalar:o,key:!0}:{kind:`column`,scalar:o}),n,!1,a)}#x(e,t,n=!1,r=!0){let i=e.scalar?.physical.scalar[`~`].state;return t===null||t instanceof U||V(t)||typeof t!=`object`||z(t)!==void 0||i?.array===!0&&Array.isArray(t)||!addressesOperators(i,record(t))?this.prepareOperation(e,`equals`,t,n,r):this.#S(e,t,n,r)}#S(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)?Z({...e,path:Z([...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.#x(c,t,s,r)):e===`not`?l.push(Z({kind:`not`,predicate:this.#x(c,t,s,!r)})):l.push(this.prepareOperation(c,e,t,s,r))}return Z({kind:`and`,predicates:Z(l)})}prepareOperation(e,t,n,r,i=!0){let a=e.scalar;switch(t){case`in`:case`notIn`:return Z({kind:`operation`,operator:t,target:e,operands:Z(n.map(e=>a?this.#C(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 Z({kind:`operation`,operator:t,target:e,operand:a?this.#C(a,n):{kind:`value`,value:n},value:n,insensitive:r});default:return Z({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}:{}})}}#C(e,t){if(V(t)){if(e.physical.scalar[`~`].state.type===`json`)throw new l(`Field reference '${B(t)}' is not supported in a JSON filter operand.`);return this.#w(e,t)}if(!(t instanceof U))return{kind:`value`,value:t};let n=t.values.map(t=>{if(V(t))return this.#w(e,t);let n=[t],r=new WeakSet;for(let e of n){if(V(e))throw new l(`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:Z(n)}:{kind:`value`,value:t}}#w(e,t){let{model:n}=e,r=de(t),i=n[`~`].names.ts??`unknown`;if(r.model!==i)throw new l(`Field reference '${B(t)}' cannot be used while filtering '${i}': a field reference may only compare columns of the same model.`);if(r.list)throw new l(`Field reference '${B(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 l(`Field reference '${B(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 l(`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 l(`Field reference '${r.field}' cannot be compared with '${e.field}' on '${i}': ${c}`);return{kind:`field`,scalar:Z({model:n,field:r.field,physical:physicalField(this.schema,n,r.field)})}}#T(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);return Z({kind:`and`,predicates:Z((Object.keys(s).every(e=>Jt.has(e))?Object.entries(s):[[`is`,s]]).map(([e,t])=>this.#E(n,e,t,r,i,a)))})}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 Z({kind:`and`,predicates:Z((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.#D(n,o?record(t.isNot):t.is,r,i,s,a);if(e!==void 0){let s=Z({kind:`relation`,edge:n,quantifier:e,predicate:o&&l?Z({kind:`not`,predicate:l}):l});return e===`every`?Z({kind:`and`,predicates:Object.freeze([...l?[s]:[],...c.filter(e=>e.variant!==t.type).map(e=>this.#E(variantEdge(e.variant),`none`,void 0,r,i,a))])}):s}return Z({kind:`relation`,edge:n,quantifier:`some`,predicate:o&&l?Object.freeze({kind:`not`,predicate:l}):l})}))})}#E(e,t,n,r,i,a=!0){return Z({kind:`relation`,edge:e,quantifier:t,predicate:this.#D(e,n==null?void 0:record(n),r,i,t===`none`||t===`every`||t===`isNot`,a)})}#D(e,t,n,r,i,a=!0){if(!n)return t?this.#y(e.target,t,void 0,r,!1,a&&!i):void 0;let o=[...r,e],s=newSelectorFacts(!i),c=t?this.#y(e.target,t,s,o,!1,a&&!i):void 0,l=this.domain?.selector(e.target,`related`);if(l)for(let e of l.facts.fields)s.fields.add(e);return n.reads.push({model:e.target,path:o,fields:s.fields,equals:s.equals,exact:s.exact}),n.reads.push(...s.reads),c}#O(e,t,n){let r=this.adapter;switch(e.kind){case`and`:return e.predicates.length===1?r.operators.and(this.#O(e.predicates[0],t,n)):r.operators.and(...e.predicates.map(e=>this.#O(e,t,n)));case`or`:return e.predicates.length===1?r.operators.or(this.#O(e.predicates[0],t,n)):r.operators.or(...e.predicates.map(e=>this.#O(e,t,n)));case`not`:return r.operators.not(this.#O(e.predicate,t,n));case`always`:return e.value?r.literals.true():r.literals.false();case`operation`:return this.lowerOperation(e,t);case`relation`:return this.#I(e,t,n);case`window`:return this.#_(e.selector,e.limit,t);case`through`:{let{model:n,last:i}=e,a=this.keyOrder(n);return r.operators.lte(rowValue(a.map(e=>this.column(n,e,t))),rowValue(a.map(e=>this.fieldValue(n,e,i[e]))))}}}#k(e,t){return t?this.adapter.identifiers.column(t,e.physical.name):this.adapter.identifiers.escape(e.physical.name)}#A(e,t){return e.kind===`column`?this.#k(e.scalar,t):this.#$(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.#A(i,t);if(c?.type===`json`&&c.array!==!0)return this.#P(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.#k(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 U(e.strings,e.operands.map(e=>e.kind===`field`?this.#k(e.scalar,t):e.value)));return r?n.expressions.asciiCaseFold(i):i}let a=o&&!s?this.#M(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.#l(`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 U)?n.operators.eq(m,bind(e,!0)):f&&e.kind===`value`&&!(t instanceof U)?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.#j(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})}}#j(e,{column:t,folded:n,insensitive:i,text:a,exact:o,bind:s,state:c}){let l=this.adapter,{operator:u,operand:d}=e,f=e.target.scalar,members=()=>e.operands??[];switch(u){case`in`:case`notIn`:{let e=u===`notIn`,r=members();if(r.length===0)return e?l.literals.true():l.literals.false();if(i){let t=r.map(t=>e?l.operators.neq(n,s(t,!0)):l.operators.eq(n,s(t,!0)));return e?l.operators.and(...t):l.operators.or(...t)}let c=l.literals.list(r.map(e=>s(e)));return e?l.operators.notIn(o(t),c):a?l.operators.exactTextIn(t,c,f?.physical.scalar[`~`].nativeType):l.operators.in(t,c)}case`contains`:return i?l.operators.containsText(n,s(d,!0)):l.operators.containsText(t,s(d));case`startsWith`:return i?l.operators.startsWithText(n,s(d,!0)):d.kind===`value`&&typeof d.value==`string`?l.operators.startsWithPrefix(t,d.value,f?.physical.scalar[`~`].nativeType):l.operators.startsWithText(t,s(d));case`endsWith`:return i?l.operators.endsWithText(n,s(d,!0)):l.operators.endsWithText(t,s(d));case`has`:return e.value===null?l.literals.false():l.arrays.has(t,this.#a(f.physical.scalar,e.value,f.field));case`hasEvery`:{let n=e.value;return n.length===0?l.operators.isNotNull(t):l.arrays.hasEvery(t,this.#a(f.physical.scalar,n,f.field))}case`hasSome`:{let n=e.value;return n.length===0?l.literals.false():l.arrays.hasSome(t,this.#a(f.physical.scalar,n,f.field))}case`isEmpty`:return e.value?l.arrays.isEmpty(t):l.operators.not(l.arrays.isEmpty(t));case`within`:{let n=e.value,i=this.#l(`within`);if(`bounds`in n)return i.withinBounds(t,n.bounds);if(i.withinPolygon)return i.withinPolygon(t,n.polygon);throw new r(`point`,`within polygon`,`GeoPoint polygon filtering is not supported by this provider.`)}default:{let n=record(e.value),r=this.#F(t,c,f.field,n,`filter`),i=e.probe?distanceUpperBound(n):void 0,a=i===void 0?[]:[this.#l(`distance filter`).withinBounds(t,St(n.to,i))];return l.operators.and(...a,...[`lt`,`lte`,`gt`,`gte`].filter(e=>n[e]!==void 0).map(e=>l.operators[e](r,this.value(n[e]))))}}}#M(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.#a(t.physical.scalar,n,t.field,e))}return e.kind===`aggregate`&&e.aggregate===`_sum`?this.#N(t,n,r):this.#a(t.physical.scalar,n,t.field,r)}#N(e,t,n){let r=e.physical.scalar[`~`].state,i=exactDecimalDomain(r),o=i?decimalSumOperand(t,i):void 0;if(!i||o===void 0)return this.#a(e.physical.scalar,t,e.field,n);let{canonical:s,coefficient:c}=o,l=this.adapter.aggregates.decimalSumOperandPrecision(c);if(l===void 0){let t=c.startsWith(`-`)?c.length-1:c.length;throw new a(`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(s,{precision:Math.max(i.precision,l),scale:i.scale})}#P(e,t){let n=this.adapter,r=[...e.target.kind===`column`?e.target.path??[]:[]],i=e.value,o=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 s=z(i);if(s){if(r.length)throw new a(`JSON filter for field '${e.target.scalar.field}' cannot combine 'path' with the ${s} sentinel: the sentinels distinguish the database NULL from the JSON null value of the WHOLE column. Use 'path' with 'equals: null' to test for a JSON null at that path.`);let i=n.operators.isNull(t),c=n.json.equals(o,n.json.value(null));return s===`DbNull`?i:s===`JsonNull`?c:n.operators.or(i,c)}return i===null&&r.length===0?n.operators.isNull(t):n.json.equals(o,n.json.value(i))}case`lt`:case`lte`:case`gt`:case`gte`:{let o=n.operators[e.operator];if(typeof i==`number`)return o(n.json.numberAtPath(t,r),this.value(i));if(typeof i==`string`)return o(n.json.stringAtPath(t,r),this.value(i));throw new a(`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(o,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(o),n.json.value(i))}}#F(e,t,n,i,a){if(t.type===`vector`){if(!this.adapter.capabilities.supportsVector)throw new r(`vector`,a,a===`orderBy`?`vector ordering requires a pgvector-enabled PostgreSQL driver`:`vector distance select requires a pgvector-enabled PostgreSQL driver`);let o=i.to,{dimension:s}=t;if(s!==void 0&&o.length!==s)throw new l(`Vector distance ${a} dimension mismatch for '${n}': expected ${s} values, received ${o.length}.`);let c=i.metric===`cosine`?`cosine`:`l2`;return this.adapter.vector[c](e,this.adapter.vector.literal(o))}let o=this.#l(`distance ${a}`);if(!o.distance)throw new r(`point`,`distance ${a}`,`GeoPoint distance is not supported by this provider.`);let s=i.to;return o.distance(e,o.value(this.value(s.longitude),this.value(s.latitude)))}#I(e,t,n){let r=this.adapter;if(e.quantifier===`every`&&!(e.predicate&&states(e.predicate)))return r.literals.true();let i=this.alias(),a=e.predicate?this.#O(e.predicate,i,n):void 0,o=r.operators.and(this.correlation(e.edge,t??``,i,e.unscoped===void 0),...a?[e.quantifier===`every`?r.operators.not(a):a]:[]),s=this.hideMutationTarget(r.subqueries.existsCheck(this.table(e.edge.target,i),o),e.edge.target,n);switch(e.quantifier){case`some`:return r.filters.some(s);case`none`:return r.filters.none(s);case`every`:return r.filters.every(s);case`is`:return e.predicate?r.filters.is(s):r.filters.isNot(s);default:return e.predicate?r.filters.isNot(s):r.filters.is(s)}}hideMutationTarget(e,t,n){return n===void 0||this.adapter.capabilities.supportsMutationTargetInSubquery||t[`~`].names.sql!==n?e:H`SELECT * FROM ${this.adapter.subqueries.correlate(e,this.alias())}`}#L(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.#R(e,n,t),a=r?this.domain?.selector(e.target,`related`):void 0;return a===void 0?i:this.adapter.operators.and(i,this.lowerSelector(a,n))}memberWhere(e,t,n){return this.#R(e,n,t)}outsideWhere(e,t,n){let r=this.adapter,i=this.#R(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 H`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))))}#R(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(Y(r,{columns:H.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.#z(this.#B(e,t,n))}#z(e){if(e.length===0)return;let t=this.adapter;return H.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)}),`, `)}#B(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.#V(e,t,o,n,r))}return i}#V(e,t,n,r,i=!1){if(e[`~`].state.relations[t])return this.#H(e,t,record(n),r);let a=physicalField(this.schema,e,t),o=a.scalar[`~`].state,s=this.column(e,t,r);if(n!==`asc`&&n!==`desc`){let e=record(n);if(e._distance!==void 0){if(i)throw new l(Ht);let n=record(e._distance),r=o.type===`point`;return this.#U(this.#F(s,o,t,n,`orderBy`),n.sort===`desc`,r?`last`:void 0,r,void 0,r?!0:void 0)}return this.#U(s,e.sort===`desc`,e.nulls,a.nullable,t)}return this.#U(s,n===`desc`,void 0,a.nullable,t)}#H(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.#U(this.#pe(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.#V(o.target,l[0],l[1],s),d=Y(i,{columns:u.expression,from:this.table(o.target,s),where:c,limit:this.value(1)});return this.#U(i.subqueries.scalar(d),u.descending,u.nulls,!0)}#U(e,t,n,r,i,a){return Z({expression:e,descending:t,nulls:n??(t?`first`:`last`),expressionNulls:a,nullable:r,field:i})}#W(e){return e.map(e=>Z({...e,descending:!e.descending,nulls:e.nulls===void 0||e.expressionNulls?e.nulls:e.nulls===`first`?`last`:`first`}))}#G(e,t,n,r){let i=t.take!==void 0&&t.take<0,a=t.cursor!==void 0,o=this.#B(e,t.orderBy,n,a),s=this.#K(e,o,t.cursor,n);if(a&&o.some(e=>e.field===void 0))throw new l(Ht);let c=s??o;return{orderBy:this.#z(i?this.#W(c):c),distinctOrderBy:i&&t.distinct?.length?this.#z(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.#Y(e,i?this.#W(s):s,t.cursor,r),distinct:t.distinct?.length?H.join(t.distinct.map(t=>this.column(e,t,n)),`, `):void 0}}#K(e,t,n,r){if(X(e).rowKey===void 0&&n===void 0)return[...t];let i=this.#q(e,t,r,n?Object.keys(this.#J(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]=Z({...t,nulls:t.descending?`first`:`last`}))}return i}#q(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.#U(this.column(e,t,n),!1,`last`,r.nullable,t))}return i}keyOrder(e){let t=X(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 a(`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))}#J(e,t){let n={};for(let[r,i]of Object.entries(t)){let t=ze(e,r);if(t?.name)for(let e of t.fields)n[e]=record(i)[e];else n[r]=i}return n}#Y(e,t,n,r){let i=this.adapter,o=this.#J(e,n),s=this.alias(),c=r&&this.domain?.selector(e,r),l=i.operators.and(...c?[this.lowerSelector(c,s)]:[],...Object.entries(o).map(([t,n])=>{if(n===null)throw new a(`Cursor field '${t}' cannot be null. Cursor must point to a specific record.`);return i.operators.eq(this.column(e,t,s),this.fieldValue(e,t,n))})),u=t[0].descending,d=t.every(e=>!e.nullable&&e.descending===u),cursorRow=t=>Y(i,{columns:H.join(t,`, `),from:this.table(e,s),where:l,limit:this.value(1)}),f=t.map(t=>this.column(e,t.field,s));if(d)return(u?i.operators.lte:i.operators.gte)(rowValue(t.map(e=>e.expression)),i.subqueries.scalar(cursorRow(f)));let p=this.alias(),carrier=e=>`${ge}${e}`,m=cursorRow(f.map((e,t)=>i.identifiers.aliased(e,carrier(t)))),h=t.map((e,t)=>({row:e.expression,cursor:i.identifiers.column(p,carrier(t)),term:e})),g=[],_=[];for(let{row:e,cursor:t,term:n}of h){let r=n.descending?i.operators.lt:i.operators.gt,a=i.operators.and(i.operators.isNotNull(e),r(e,t));_.push(i.operators.and(...g,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)))),g.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 _.push(i.operators.and(...g)),i.operators.exists(Y(i,{columns:i.literals.true(),from:i.subqueries.correlate(m,p),where:i.operators.or(..._)}))}select(e,t,n,r={}){let i=this.#i(),a=this.#G(e,t,i,r.purpose),o=r.projection??this.prepareProjection(e,t),s=this.lowerProjection(o,i),c=r.selector??(t.where===void 0?void 0:this.prepareSelector(e,t.where,!1,!1)),l=r.purpose===void 0?c:this.#g(e,c,r.purpose),u=l?this.lowerSelector(l,i):void 0;return{sql:Y(this.adapter,{columns:H.join(s,`, `),from:this.table(e,i),where:n||u||a.cursor||r.identity||r.condition?this.adapter.operators.and(...n?[n.outside?this.outsideWhere(n.edge,n.parent,i):this.memberWhere(n.edge,n.parent,i)]:[],...u?[u]:[],...a.cursor?[a.cursor]:[],...r.identity?[this.lowerIdentity(e,r.identity,i)]:[],...r.condition?[r.condition]:[]):void 0,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}}read(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,Qt);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,Qt);return{query:r,single:!1,value:rowSet(r),result:t?reversedRows:rowIdentity}}default:return this.#X(e,t,n)}}#X(e,t,n){switch(t){case`exist`:{let t=this.select(e,{...n,take:n.take??1},void 0,{...Qt,projection:{model:e,fields:[{kind:`sentinel`,name:we}],shape:{kind:`object`,fields:{}}}});return{query:{sql:this.adapter.clauses.select(this.adapter.identifiers.aliased(this.adapter.operators.exists(t.sql),`_count`)),shape:{kind:`object`,fields:{_count:qt}},expectedRows:{count:1,missing:new a(`Provider omitted the required existence result row.`)}},single:!1,value:qt,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]),o=this.aggregated(e,n,i,t=>r.map(({name:n,field:r})=>[n,this.adapter.aggregates.count(r===void 0?void 0:this.column(e,r,t))]),()=>({kind:`object`,fields:Object.fromEntries(r.map(({name:e})=>[e,$]))}));return o.expectedRows={count:1,missing:new a(`Provider omitted the required aggregate result row.`)},{query:o,single:t!==void 0,value:t?o.shape:$,result:e=>t?e[0]??{}:e[0]?._count??0}}case`aggregate`:{let t=this.#Z(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 Ne(t,`read operation`)}}aggregated(e,t,n,r,i){let a=this.adapter,o=this.#i(),s=this.#G(e,t,o,`root`),c=this.lowerWhere(e,t.where,o),l=Y(a,{columns:n.length?H.join([...new Set(n)].map(t=>a.identifiers.aliased(this.column(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{sql:Y(a,{columns:H.join(r(u).map(([e,t])=>a.identifiers.aliased(t,e)),`, `),from:a.subqueries.correlate(l,u)}),shape:i(u)}}#Z(e,t){let n=this.adapter,r=[],i={},a=[];for(let o of Gt){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.#Q(e,o,t);i[o]={kind:`object`,fields:l},a.push(t=>[o,n.json.objectFromColumns(c.map(([n])=>[n,this.#d(l[n],this.#$(o,n===`_all`?void 0:Z({model:e,field:n,physical:physicalField(this.schema,e,n)}),t))]))])}return{fields:r,fields_:i,columns:e=>a.map(t=>t(e))}}#Q(e,t,n){if(t===`_count`)return $;let r=this.scalarShape(e,n),i=r.type===`decimal`;return Z(t===`_avg`&&!i?{kind:`scalar`,type:`number`,nullable:!0}:{...r,nullable:!0,widened:t===`_sum`&&i?!0:void 0})}#$(e,t,n){let r=this.adapter,i=t?this.#k(t,n):void 0,a=t?.physical.scalar[`~`].state;switch(e){case`_count`:return r.aggregates.count(i);case`_sum`:return 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.#i(),o=this.lowerProjection(e,i),s=t.map(e=>this.lowerIdentity(r,e,i));return{sql:Y(this.adapter,{columns:H.join(o,`, `),from:this.table(r,i),where:balancedOr(s,e=>this.adapter.operators.or(...e)),orderBy:this.adapter.expressions.caseWhen(s.map((e,t)=>({when:e,then:this.value(t)})),this.value(t.length))}),shape:e.shape,expectedRows:{count:t.length,missing:n===`createMany`?new a(`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`}})}}}#ee(e,t,n,r,i){let a=this.#se(e,n);a.length!==0&&(r[t]=Z({kind:`object`,nullable:!1,fields:Z(Object.fromEntries(a.map(e=>[e.relation,$])))}),i.push(Z({kind:`counts`,name:t,counts:a})))}#te(e,t,n,r,i,o){if(r)throw new a(Te);o.push(Z({kind:`distance`,name:Wt,field:t,specification:record(n)})),i[Wt]=this.#ae(e,t,record(n))}#ne(e,t,n,r,i,a){let o=n.edge,s=o.kind===`variantJunctionCarrier`,c={},l={},u=[],d=s?o.members.map(n=>({variant:n.variant,edge:bindMembership(this.schema,e,t,n.variant)})):[];for(let n of o.members){let i=xe(r,s,n.variant);if(i===void 0)continue;let a=this.#oe(bindMembership(this.schema,e,t,n.variant),i);s?c[n.variant]=this.#ie(a):l[n.variant]=this.#re(a),u.push(Z({variant:n.variant,...a}))}i[t]=Z(s?{kind:`variants`,relation:t,many:s,arms:Z(c)}:{kind:`variants`,relation:t,many:s,arms:Z(l)}),a.push(Z({kind:`variants`,name:t,many:s,arms:Z(u),memberships:Z(d)}))}prepareProjection(e,t){let n=t.select===void 0&&t.include===void 0;if(n){let t=this.#n.defaultProjections.get(e);if(t!==void 0)return t}let r=t.select??defaultSelection(e);t.include!==void 0&&(r={...r,...t.include});let i=[],o={},s=!1;for(let t of Object.keys(r)){let n=r[t];if(!n)continue;if(t===`_count`){this.#ee(e,t,n,o,i);continue}if(!e[`~`].state.relations[t]){let r=n===!0?void 0:record(n)._distance;if(r!==void 0){this.#te(e,t,r,s,o,i),s=!0;continue}}if(!e[`~`].state.relations[t]){i.push(Z({kind:`scalar`,name:t})),o[t]=this.scalarShape(e,t);continue}let a=this.schema.index.get(e).get(t);if(!a.member&&(a.edge.kind===`variantRowCarrier`||a.edge.kind===`variantJunctionCarrier`)){this.#ne(e,t,a,n,o,i);continue}let c=this.#oe(bindMembership(this.schema,e,t),n);o[t]=this.#re(c),i.push(Z({kind:`relation`,name:t,...c}))}if(i.length===0){if(t.select!==void 0)throw new a(Ce(e));i.push(Z({kind:`sentinel`,name:we}))}let c=Z({model:e,fields:Z(i),shape:Z({kind:`object`,fields:Z(o)})});return n&&this.#n.defaultProjections.set(e,c),c}#re(e){if(e.recurrence){let t=this.schema.index.get(e.edge.source).get(e.edge.name);return Z({kind:`recursive`,relation:e.edge.name,many:e.edge.many,optional:Ie(t),recurrence:e.recurrence,row:e.projection.shape,identity:Z(this.schema.keys(e.edge.target).map(t=>this.scalarShape(e.edge.target,t)))})}return e.edge.many?this.#ie(e):e.projection.shape}#ie(e){let t=e.arguments.take;return Z({kind:`collection`,reversed:t!==void 0&&t<0?!0:void 0,row:e.projection.shape})}#ae(e,t,n){let r=physicalField(this.schema,e,t);return Z({kind:`scalar`,type:`number`,nullable:r.nullable||r.scalar[`~`].state.type===`vector`&&n.metric===`cosine`})}#oe(e,t){let n=t===!0?{}:record(t);return Z({edge:e,arguments:Z({selector:n.where?this.prepareSelector(e.target,n.where,!1,!1):void 0,orderBy:n.orderBy,take:n.take,skip:n.skip,cursor:n.cursor,distinct:n.distinct}),projection:this.prepareProjection(e.target,n),recurrence:n.recurse})}#se(e,t){let n=record(record(t).select),r=[];for(let[t,i]of Object.entries(n)){if(!i)continue;let{edges:n,variants:o}=this.countedMemberships(e,t),s=i===!0?void 0:record(i).where;if(s===void 0){r.push(Z({relation:t,edges:n}));continue}let c=record(s);if(!o){r.push(Z({relation:t,edges:n,selector:this.prepareSelector(n[0].target,c,!1,!1)}));continue}let l=c.type,u=n.find(e=>e.scope.member?.variant===l);if(!u)throw new a(`Unknown polymorphic target '${String(l)}' for relation '${t}'.`);let d=c.isNot!==void 0,f=d?c.isNot:c.is;r.push(Z({relation:t,edges:Z([u]),selector:f===void 0?void 0:this.prepareSelector(u.target,record(f),!1,!1),...d?{negated:!0}:{}}))}return Z(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 Z({edges:Z(r?r.members.map(n=>bindMembership(this.schema,e,t,n.variant)):[bindMembership(this.schema,e,t)]),variants:r!==void 0})}lowerProjection(e,t){let n=[];for(let r of e.fields)n.push(this.adapter.identifiers.aliased(this.#le(e,r,t),r.name));return n}#ce(e,t,n){let r=this.adapter,i;if(t.kind===`counts`)i=r.json.objectFromColumns(t.counts.map(e=>[e.relation,this.#pe(e.edges,e.selector,n??``,e.negated)]));else if(t.kind===`distance`)i=this.#F(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?[]:[[G,r.json.document(r.json.objectFromColumns(t.memberships.map(e=>[e.variant,this.#fe(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=Ie(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([G,r.json.document(r.json.objectFromColumns([[`$storage`,u]]))])}i=r.json.object([...t.arms.map(e=>{let i=this.#me(e,n??``),a=t.many?void 0:this.#L(e.edge,n??``);return[e.variant,r.json.document(a?r.expressions.caseWhen([{when:a,then:r.expressions.coalesce(i,this.#ue(e.edge,n??``))}],r.literals.null()):i)]}),...a])}return i}#le(e,t,n){let r=this.adapter,i;return i=t.kind===`scalar`?this.projectedColumn(e.model,t.name,n):t.kind===`sentinel`?r.expressions.cast(r.literals.value(1),`integer`):t.kind===`relation`?this.#de(t.edge,n??``,t.recurrence?this.#ge(t,t.recurrence,n??``):this.#me(t,n??``)):this.#ce(e,t,n),i}#ue(e,t){let n=this.adapter;if(this.domain?.selector(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([]))}#de(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(Y(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)}#fe(e,t){let n=this.adapter,r=this.alias(),i=this.alias();return n.subqueries.scalar(Y(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)))))}))}#pe(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(Y(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))}}#me(e,t){let n=this.adapter,{edge:r,arguments:i,projection:a}=e,o=this.alias(),s=this.lowerProjection(a,o),c=Object.keys(a.shape.fields),l=this.#G(r.target,i,o,`related`),u=Y(n,{columns:H.join(s,`, `),from:this.table(r.target,o),where:n.operators.and(this.correlation(r,t,o),...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)}:{}}),d=this.alias(),f=n.json.object(c.map(e=>[e,this.#d(a.shape.fields[e],n.identifiers.column(d,e))]));return n.subqueries.scalar(Y(n,{columns:r.many?n.expressions.coalesce(n.json.agg(f),n.json.emptyArray()):f,from:n.subqueries.correlate(u,d)}))}#he(e,t){return this.adapter.json.array(this.schema.keys(e).map((n,r)=>{let i=this.scalarShape(e,n);return this.#d(i,transportedIdentifier(this.adapter,i.id,t[r],i.nullable))}))}#ge(e,t,n){let r=this.adapter,i=e.edge.target,a=this.schema.keys(i),o=this.alias(),s=`__${o}_recursive`,c=a.map((e,t)=>`__${o}_parent_${t}`),l=a.map((e,t)=>`__${o}_child_${t}`),u=`__${o}_depth`,columns=(e,t)=>e.map((e,n)=>r.identifiers.aliased(t[n],e)),rawIdentity=e=>a.map(t=>this.column(i,t,e)),sameRow=(e,t)=>r.operators.and(...rawIdentity(e).map((e,n)=>r.operators.eq(e,t[n]))),d=this.alias(),f=[...columns(c,rawIdentity(n)),...columns(l,rawIdentity(d)),...t.depth===!1?[]:[r.identifiers.aliased(r.expressions.cast(this.value(1),`integer`),u)]],p=Y(r,{columns:H.join(f,`, `),from:this.table(i,d),where:r.operators.and(this.correlation(e.edge,n,d),...e.arguments.selector?[this.lowerSelector(e.arguments.selector,d)]:[])}),m=this.alias(),h=this.alias(),g=this.alias(),walkColumn=e=>r.identifiers.column(m,e),_=[...columns(c,l.map(walkColumn)),...columns(l,rawIdentity(g)),...t.depth===!1?[]:[r.identifiers.aliased(r.expressions.add(walkColumn(u),this.value(1)),u)]],v=Y(r,{columns:H.join(_,`, `),from:H`${r.identifiers.aliased(r.identifiers.escape(s),m)} ${r.joins.inner(this.table(i,h),sameRow(h,l.map(walkColumn)))} ${r.joins.inner(this.table(i,g),this.correlation(e.edge,h,g))}`,where:r.operators.and(...t.depth===!1?[]:[r.operators.lt(walkColumn(u),this.value(t.depth))],...e.arguments.selector?[this.lowerSelector(e.arguments.selector,g)]:[])}),y=this.alias(),b=l.map((e,t)=>`__${o}_id_${t}`),x=Y(r,{distinct:H.join(l.map(walkColumn),`, `),distinctColumnAliases:b,columns:H.join(columns(b,l.map(walkColumn)),`, `),from:r.identifiers.aliased(r.identifiers.escape(s),m)}),S=this.alias(),C=r.json.object(e.projection.fields.map(t=>[t.name,this.#d(e.projection.shape.fields[t.name],this.#le(e.projection,t,S))])),w=r.json.object([[Q.key,this.#he(i,rawIdentity(S))],[Q.row,C]]),T=r.subqueries.scalar(Y(r,{columns:r.json.agg(w),from:H`${r.subqueries.correlate(x,y)} ${r.joins.inner(this.table(i,S),sameRow(S,b.map(e=>r.identifiers.column(y,e))))}`})),E=this.alias(),D=this.alias(),edgeColumn=e=>r.identifiers.column(E,e),O=`__${o}_edge`,k=[[Q.parent,this.#he(i,c.map(edgeColumn))],[Q.child,this.#he(i,l.map(edgeColumn))]];t.depth!==!1&&k.push([Q.depth,edgeColumn(u)]);let ee=r.json.object(k),A=this.#z(this.#q(i,this.#B(i,e.arguments.orderBy,D),D)),te=Y(r,{columns:r.identifiers.aliased(ee,O),from:H`${r.identifiers.aliased(r.identifiers.escape(s),E)} ${r.joins.inner(this.table(i,D),sameRow(D,l.map(edgeColumn)))}`,orderBy:H.join([...c.map(e=>r.orderBy.asc(edgeColumn(e))),...A?[A]:[]],`, `),limit:r.noLimitValue}),ne=this.alias(),re=r.subqueries.scalar(Y(r,{columns:r.json.agg(r.json.document(r.identifiers.column(ne,O))),from:r.subqueries.correlate(te,ne)})),carrier=(e,t)=>r.json.object([[Q.root,this.#he(i,rawIdentity(n))],[Q.nodes,r.json.document(e)],[Q.edges,r.json.document(t)]]),j=r.cte.recursive(s,p,v,`distinct`);if(!r.capabilities.supportsLateralJoins)return r.subqueries.scalar(H`${j} ${r.clauses.select(carrier(T,re))}`);let M=this.alias(),N=this.alias(),P=`__${o}_nodes`,F=`__${o}_edges`;return r.subqueries.scalar(Y(r,{columns:carrier(r.identifiers.column(N,P),r.identifiers.column(N,F)),from:r.subqueries.correlate(r.clauses.select(H`1`),M),joins:[r.joins.lateral(H`${j} ${r.clauses.select(H.join([r.identifiers.aliased(T,P),r.identifiers.aliased(re,F)],`, `))}`,N)]}))}grouped(e,t){let n=this.adapter,r=this.#i(),i=t.by,a=new Set(i),o=this.#Z(e,t),s={},c=i.map(t=>(s[t]=this.scalarShape(e,t),n.identifiers.aliased(this.projectedColumn(e,t,r),t)));for(let[e,t]of o.columns(r))s[e]=o.fields_[e],c.push(n.identifiers.aliased(t,e));return{sql:Y(n,{columns:H.join(c,`, `),from:this.table(e,r),where:this.lowerWhere(e,t.where,r),groupBy:H.join(i.map(t=>this.column(e,t,r)),`, `),having:t.having?this.#O(this.#_e(e,record(t.having),a),r):void 0,orderBy:this.#z(this.#ve(e,t.orderBy,r,a)),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:s}}}#_e(e,t,n){return Z({kind:`and`,predicates:Z(Object.entries(t).flatMap(([t,r])=>{if(r===void 0)return[];if(this.combinator(e,t))return[this.combine(t,entries(r).map(t=>this.#_e(e,record(t),n)))];let i=Z({model:e,field:t,physical:physicalField(this.schema,e,t)}),o=record(r),s=Gt.filter(e=>o[e]!==void 0);if(s.length===0){if(!n.has(t))throw new a(`Scalar '${t}' used in 'having' must be included in 'by'.`);return[this.#x(Z({kind:`column`,scalar:i}),r)]}return s.map(e=>this.#x(Z({kind:`aggregate`,aggregate:e,scalar:i}),o[e]))}))})}#ve(e,t,n,r){let i=entries(t??{}).flatMap(t=>Object.entries(t).flatMap(([t,i])=>{if(i===void 0)return[];if(!isAggregate(t)){if(!r.has(t))throw new a(`GroupBy orderBy field '${t}' must be included in 'by' or be an aggregate (_count, _avg, _sum, _min, _max).`);return[this.#V(e,t,i,n)]}return Object.entries(record(i)).map(([r,i])=>this.#U(this.#$(t,r===`_all`?void 0:Z({model:e,field:r,physical:physicalField(this.schema,e,r)}),n),i===`desc`,void 0,!1))})),o=new Set(i.map(e=>e.field));for(let t of r)o.has(t)||i.push(this.#V(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 a(`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,Q.root),o=own(i,Q.nodes),s=own(i,Q.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),u=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,Q.key));if(u.has(n))throw new InvalidScalarResult(`duplicate recursive node`,`two nodes carry the same identity`);u.set(n,own(t,Q.row))}let d=new Map,p=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,Q.parent)),i=identity(own(n,Q.child));if(!u.has(i))throw new InvalidScalarResult(`recursive edge endpoint`,`an edge's child is not a carried node`);let a=own(n,Q.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(p.has(s))throw new InvalidScalarResult(`duplicate recursive edge`,`an edge fact is carried twice`);p.add(s);let c=d.get(r),l=Z({child:i,...o===void 0?{}:{depth:o}});c?c.push(l):d.set(r,[l])}let m=new Map;for(let[t,n]of d){if(t!==c&&!u.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`);m.set(t,r)}let h=new Set,g=new Set,_=new Set,v=[[c,0]];for(let[t,n]of v){let r=new Set;for(let e of d.get(t)??[]){if(e.depth!==void 0&&e.depth!==n+1)continue;h.add(e),g.add(e.child),r.add(e.child);let t=e.depth===void 0?e.child:`${e.depth} ${e.child}`;_.has(t)||(_.add(t),v.push([e.child,n+1]))}if(e.recurrence.depth!==!1&&Le(e.recurrence.depth,n)&&r.size!==(m.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&&h.size!==p.size)throw new InvalidScalarResult(`recursive depth`,`an edge is not reachable at its recorded depth`);if(g.size!==u.size)throw new InvalidScalarResult(`unreachable recursive node`,`a carried node is not reachable from the root`);let cutoff=t=>!Le(e.recurrence.depth,t),collapse=t=>t.length>0?e.many?t:t[0]:e.many?[]:null,y=new Set([c]),b=[],x=0,follow=(t,r)=>{if(y.has(r)){if(e.recurrence.cycles===`reject`)throw new l(`Recursive relation '${e.relation}' contains a cycle.`,{meta:{relation:e.relation,feature:`cyclic recursive traversal`}});if(e.recurrence.cycles===`prevent`)return}if(++x>1e4)throw new f(`findMany`,[{path:`recurse.${e.relation}`,message:`Recursive output exceeds the 10000 occurrence budget; reduce recurse.depth or filter the relation.`}]);y.add(r);let i=n(u.get(r));if(i===null)throw new InvalidScalarResult(`recursive row`,`a node's row is null`);let a=t+1;b.push({key:r,depth:a,row:record(i),childKeys:cutoff(a)?[]:m.get(r)??[],childRows:[],next:0})},S=[];for(let t of m.get(c)??[]){follow(0,t);for(let t=b.at(-1);t!==void 0;t=b.at(-1)){if(t.next<t.childKeys.length){follow(t.depth,t.childKeys[t.next++]);continue}y.delete(t.key),b.pop(),cutoff(t.depth)||(t.row[e.relation]=collapse(t.childRows));let n=b.at(-1);n?n.childRows.push(t.row):S.push(t.row)}}return collapse(S)}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,G);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 a(`Polymorphic relation '${e.relation}' has an unknown discriminator or incomplete stored pair.`):new a(`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.#ye(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:o}of n){let n=own(r,t);if(orphanedArm(n,i))throw new a(`Polymorphic relation '${e.relation}' references a missing '${t}' record.`);let s=o(n);if(s!==null)return{type:t,data:s}}return null}}if(e.kind===`collection`)return this.#ye(e,t);let i=Object.keys(e.fields),o=i.map(r=>{let i=e.fields[r];return this.compileReader(i,t,n||i.kind!==`scalar`)});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 a=e[r];n[i[r]]=o[r](a<0?void 0:t[a])}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];r[t]=o[e](own(n,t))}return r}}#ye(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.#be(e,t),a=e.nullable,o=e.type===`json`&&e.list!==!0;return 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))}}#be(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 decodeInt;case`bigint`:return decodeBigint;case`number`:return 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=yt(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(st(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`?vt(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(st(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`?tn.exec(t):null,r=n?vt(`${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=pt(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=Z({...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.#xe(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.#xe(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`)}#xe(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 en=/^(?:0|-?[1-9]\d*)$/,tn=/^(\d{4})-(\d{2})-(\d{2})(?: (BC))?$/,nn=/^(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,6})?(?:Z|[+-](\d{2})(?::?(\d{2}))?)?$/,rn=/(?:Z|[+-]\d{2}(?::?\d{2})?)$/,an=/\.?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){let t=typeof e==`bigint`||typeof e==`string`&&en.test(e)?Number(e):e;if(typeof t!=`number`)throw new InvalidScalarResult(`int`,`the value is not a canonical integer`);if(!Number.isSafeInteger(t))throw new InvalidScalarResult(`int`,`the integer is outside the safe range`);return t}function decodeBigint(e){if(typeof e==`bigint`)return e;if(typeof e==`number`&&Number.isSafeInteger(e)||typeof e==`string`&&en.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}function decodeTime(e){if(typeof e!=`string`)throw new InvalidScalarResult(`time`,`the value is not a valid provider time`);let t=nn.exec(e);if(!(t&&at(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(rn,``);n.includes(`.`)&&(n=n.replace(an,``));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}=it(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 on=Object.freeze([]);var TransportAttempt=class{pending=[];rejectedInsert;scratchId;nextField=0;#e;#t;#n;#r;#i;publishScratchValue(e){(this.#e??=[]).push(e)}drainScratchPublications(){let e=this.#e??on;return this.#e=void 0,e}carryScratchValue(e,t){(this.#t??=new Map).set(e,t)}carried(e){if(!(e instanceof U))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)}recordMember(e){(this.#i??=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.#i)return!1;for(let t of this.#i)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.#a.push(...this.pending.splice(t))}restorePremises(){this.#a.length>0&&this.pending.unshift(...this.#a.splice(0))}#a=[];drainAssertedPremises(){let e=this.#r??new Map,t=new Map;for(let n of this.#a){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.#i?[...this.#i]:[];return this.#i=void 0,e}};const sn=new Set([`update`,`delete`,`upsert`]),cn=Object.freeze([]),ln=Object.freeze([]),un=Object.freeze([]);var OperationContext=class{queries;modelDependencies=new Set;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??cn}#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;checkStorage;constructor(e,t,n,r,i,a=!1,o,s,c=t,l){this.checkStorage=l,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 $t(e,this.driver.adapter,this.driver.result,s?.domain,this.modelDependencies)}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:ke(r,n):{model:n,operation:t,correlationId:this.#T}}#j(e,t=this.attribution,n){let r=this.#a._prepare(e,t),i=w(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 I&&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 l(`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:s}=e;r=new o(`The "${i}" result is incompatible with the ${a} scalar domain: ${s}.`,{code:N.QUERY_RESULT_INVALID,meta:{driver:t,model:n,operation:i,scalarType:a,reason:s}})}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)?ue(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?Ae(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=M(e)?se(e,t):e;throw await this.#ne(this.#F===`committed`?this.#r?.committedSegment:this.#r?.mayBeVisible,n),n}return await this.#ne(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.#J(e);if(!t)return await this.#q(n,e);this.#E=`deferred`;try{return await e()}catch(e){if(e!==this.requiresEnvelope)throw e}return this.#U(),await this.#q(n,e)}catch(e){throw this.#z(e)}}#z(e){return e instanceof InvalidScalarResult||this.usesBatch&&this.#p>0?this.failure(e,e instanceof InvalidScalarResult?`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&&sn.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)}}async storageGuards(){let e=await this.checkStorage?.(this.#a,this.attribution,this.modelDependencies),t=ke(this.attribution,`$schema`,`verifyStorage`),n=[];return{statements:(e??[]).map(({query:e,failure:r},i)=>{n.push({queryIndex:i,probe:e,premise:`exists`,failure:{kind:`unsupported`,message:r.message,raceable:!1},model:typeof r.meta.model==`string`?r.meta.model:this.modelName,operation:this.operation});let a=this.#a._prepare(this.driver.adapter.assertions.exists(e),t);return w(a,{...a,context:t})}),guards:n}}async#V(e,t,n){if(!this.checkStorage)return this.#a._execute(e,t);let r=n??await this.storageGuards();if(r.statements.length===0)return this.#a._execute(e,t);let i=this.#a._prepare(e,t),a=(await this.#H([w(i,{...i,context:t})],void 0,t,void 0,r))[0];if(!a)throw new L(`Driver '${this.driver.driverName}' omitted the result for operation '${this.operation}'.`,{meta:this.#A});return a}async#H(e,t,n,r,i){if(!this.checkStorage)return this.#a._executeBatch([...e],t,n,r);let a=i??await this.storageGuards(),o=[...a.statements,...e];try{return(await this.#a._executeBatch(o,t,n,r)).slice(a.statements.length)}catch(e){let t=await attributeOperationBatchError(e,a.guards,this.#a,o);throw t===e&&M(e)&&typeof e.meta.statementIndex==`number`?ce(e,e.meta.statementIndex-a.statements.length):t}}async prepareStorageBatch(){let e=this.preparedBatch();if(!(e&&this.checkStorage))return e;let t=await this.storageGuards();if(t.statements.length===0)return e;let n=t.statements.length;return{queries:[...t.statements.map(e=>w(e,{sql:e.sql,params:e.params??[],context:e.context??this.attribution})),...e.queries],guards:[...t.guards,...(e.guards??[]).map(e=>({...e,queryIndex:e.queryIndex+n}))],parseResult:t=>e.parseResult(t.slice(n))}}#U(e=new TransportAttempt){this.#o=e,this.#u=void 0,this.#d=void 0,this.#_=!1,this.#E=`open`}attachRecovery(e,t){this.#W=e,this.#G=t}#W;#G;#K=!1;spendRecovery(){if(this.#K)return;let e=this.#W?.();if(e)return this.#K=!0,e}get replaysInPlace(){return this.#e===`standalone`&&!this.#i}async#q(e,t){try{return await this.#L(e,t)}catch(n){if(this.recoveryRejection(n)?.kind!==`insert`||!this.#G?.(n))throw n;let r=this.spendRecovery();if(!r)throw n;return this.#U(r),await this.#L(e,t)}}async#J(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.#U(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,r){let i=this.#M;i&&this.#o?.holdsOtherMemberWrite(i)&&await this.flush();let a=n?this.statementContext(n,this.operation):this.attribution;return this.dispatch(1,t,()=>this.#V(e.sql,a,r))}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.checkStorage?await this.storageGuards():void 0,r=(!n||n.statements.length===0)&&this.#e===`standalone`&&e.value.kind===`collection`?resolvePositionalResultDriver(this.#a):void 0;if(r)return this.#Y(e,t,r);let i=await this.answer(e.query,!0,void 0,n);return this.#X(e,t,this.publishedTerminal([e.query],[i.rows]))}async#Y(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.#X(e,t,this.queries.decodeProjection(e.query.shape,r.rows,!1,r.columns));let i=r.kind===`borrowed`?r.result:borrowPositionalResult(r);return this.#X(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.#X(e,t,this.publishedTerminal([e.query],[i.rows.map(record)]))}}#X(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.#Z(r,e,t,n)}finally{this.#o?.restorePremises()}}async#Z(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)}#Q(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.#Q(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,a=this.#u,o=a?a.filter(e=>!e.declaring):ln;if(a)for(let e of a)e.declaring=!1;let s=o.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.#Q(t)}}}),l=s.length+n.pending.length,u=this.#ce();this.closeScratch();let f=[...s.map(e=>e.statement),...n.pending.splice(0)],p=n.drainInsertProducers(),h=n.drainAssertedPremises();for(let{statement:e,premise:t}of s)h.set(e,t);let g=n.drainMembers(),acknowledged=async()=>{if(g.length===0)return;this.#p++;let e=this.#c??=new Set;for(let t of g)e.add(t);try{await this.#r?.committedSegment?.()}catch(e){this.heldOutcomeFailure={failure:e}}},_;try{_=await this.dispatch(f.length,!1,()=>this.#H(f,void 0,this.attribution,this.driver.supportsOrderedCommittedSegments?acknowledged:void 0)),this.driver.supportsOrderedCommittedSegments||await acknowledged()}catch(a){let s=this.heldOutcomeFailure;if(this.heldOutcomeFailure=void 0,s)throw this.#re(m(a,s.failure));if(this.driver.supportsBatch&&!this.#g&&!this.#_&&a instanceof I&&a.meta.commitCertainty===void 0&&a.originalCause&&a.originalCause.cause===void 0&&typeof a.meta.statementIndex==`number`){let e=p.get(f[a.meta.statementIndex]);e&&(n.rejectedInsert={error:a,producer:e})}let l,u;if(a instanceof d){let e=a.meta.statementIndex;if(typeof e==`number`)l=h.get(f[e])?.failure,u=e;else{let e=le(f,this.driver.dialect),t=h.size===1&&!e;for(let[e,n]of f.entries()){let r=h.get(n);if(!(!r||r.readsBatchReference)&&((await this.read(r.query,!0)).length>0!==r.present||t)){l=r.failure,u=e;break}}if(l===void 0&&!e){let e=f.findIndex(e=>!h.has(e)),t=[...f.entries()].filter(([t,n])=>e>=0&&t>e&&h.has(n));if(t.length===1){let[e,n]=t[0];l=h.get(n).failure,u=e}}}}let _=M(a)&&typeof a.meta.statementIndex==`number`?a.meta.statementIndex:void 0,v=_??u,y=v;if(_===void 0&&typeof u==`number`){let e=-1;for(let[t,n]of f.entries())h.has(n)&&(e=t);y=e}let b=typeof v==`number`&&typeof y==`number`&&this.#p===0&&f.every((e,t)=>t>y||h.has(e));g.length>0&&!b&&!this.driver.supportsOrderedCommittedSegments&&this.#p===r&&!(a instanceof I)&&(this.#m=!0,await this.#ne(this.#r?.mayBeVisible,a));let x=a;throw l&&a instanceof d?(x=l,this.driver.supportsBatch&&!this.#g&&a.meta.commitCertainty===void 0&&M(l)&&l.meta.raceable===!0&&(this.#y=l)):a instanceof d&&(x=new i(c,``,{code:N.NESTED_WRITE_ASSERTION_FAILED,cause:a})),e||o.length>0?this.failure(x,this.#p>r?`result`:`member`,t):x}try{for(let[e,n]of u.entries())this.#le(n,_[l+e],t)}catch(e){let t=this.heldOutcomeFailure;throw this.heldOutcomeFailure=void 0,t?this.#re(m(e,t.failure)):e}return _.slice(s.length)}async settleSubmitted(e){let t=this.heldOutcomeFailure;this.heldOutcomeFailure=void 0;let n;try{n=await e()}catch(e){throw t?this.#re(m(e,t.failure)):e}if(t)throw this.#re(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.#re(t());return n}#$(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=T(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)}#ee(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.#ee(e,r,n)),t([]);if(this.queued.length===0)return t([]);let r=await this.submit();return this.settleSubmitted(()=>{try{return t(this.#ee(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=>w(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#te(e,t,n){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)})}async setMutations(e,t){if(this.#e===`batch-preparation`){let n=this.queued.length;for(let t of e)this.#j(t.sql,t.context);this.#x=r=>{let i=r.slice(n,n+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 n=e.length===1&&this.queued.length===0&&this.#f===0;if(this.usesBatch&&!n){let n={};this.#v=n;let r=this.queued.length;for(let t of e)this.#j(t.sql,t.context,n);let i=await this.submit(!0,n);return this.settleSubmitted(()=>{try{return t(i.slice(r,r+e.length))}catch(e){throw this.failure(e,`result`,n)}})}return this.dispatchSetMutations(e,t)}dispatchSetMutations(e,t){return this.dispatch(e.length,!0,async()=>{let n=this.#e===`standalone`&&!this.#i,r=[];try{for(let t of e)r.push(await this.#V(t.sql,t.context))}catch(e){throw n&&!(e instanceof I)&&await this.#ne(this.#r?.mayBeVisible,e),e}let i;try{i={value:t(r)}}catch(e){i={failure:this.failure(e,`result`)}}if(n&&await this.#ne(this.#r?.committedSegment,`failure`in i?i.failure:void 0),`failure`in i)throw i.failure;return i.value})}async#ne(e,t){if(e)try{await e()}catch(e){throw t===void 0?e:this.#re(m(t,e))}}#re(e){return typeof e==`object`&&e&&(this.#C??=new WeakSet).add(e),e}#ie(e,t,n,r=!1){let i=this.queries,a=this.driver.adapter.mutations;if(t.length===0)return a.insertDefault(i.table(e));let o=r?a.skipDuplicates(i.columnName(e,t[0])):void 0,s=a.insert(i.table(e),t.map(t=>i.columnName(e,t)),n.map(n=>t.map(t=>i.fieldValue(e,t,n[t]))),o?.prefix);return o?.suffix?H`${s} ${o.suffix}`:s}#ae(e,t,n,r){let i=this.queries,a=n?H`${t} ${this.driver.adapter.mutations.returning(H.join(i.lowerProjection(n),`, `))}`:t;return this.#te(a,this.statementContext(e,this.operation),e=>n?this.published(this.publishedProjection(n.shape,e.rows.map(record)),r):{count:e.rowCount})}async insertMany(e,t){if(!(!this.#i||this.usesBatch))return(await this.createMany(e,t())).count}async createMany(e,t,n,r=!1,i){if(t.length===0){if(this.#e===`batch-preparation`)throw new a(`No data to insert for createMany.`);return this.emptyBulkResult(n)}let o=this.queries,s=this.driver.adapter,c=r&&s.mutations.skipDuplicatesStrategy===`recoverableUniqueError`;if(c||n&&!s.capabilities.supportsReturning){if(this.#e===`batch-preparation`)throw this.incompletePreparation;let r=c&&this.admitsSuppression(`duplicate rows`),a=n?t.map(t=>{let n=this.schema.keys(e).filter(e=>t[e]===void 0),r=this.#ue(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=[],l=0;for(let[t,n]of o.entries()){let i=Object.keys(n),o=this.#ie(e,i,[n]),c=this.statementContext(e,this.operation),u;if(u=r?await this.executeMember(async()=>{try{return await this.dispatch(1,!1,()=>this.#N(()=>this.#V(o,c)))}catch(e){if(e instanceof I)return;throw e}},n):await this.executeMember(()=>this.dispatch(1,!1,()=>this.#V(o,c)),n),!u||(l+=u.rowCount,!a))continue;let d=a[t];if(d&&u.insertId===void 0)throw TypeError(`INSERT did not produce the required record identity`);s.push({...this.schema.identity(e,n),...d?{[d]:u.insertId}:{}})}return n?s.length?this.finishTerminals(this.seriesQueries(n,s),e=>this.published(e,i)):this.published([],i):{count:l}}let l=n?s.mutations.returning(H.join(o.lowerProjection(n),`, `)):void 0,u=[];for(let e of t){let t=Object.keys(e),n=u.at(-1);t.length===0||!n||n.columns.length!==t.length||t.some((e,t)=>n.columns[t]!==e)?u.push({columns:t,rows:[e]}):n.rows.push(e)}let d=T(this.driver.maxBindParametersPerStatement),f=[];for(let t of u){if(t.columns.length===0){for(let n of t.rows){let t=this.#ie(e,[],[n]);l&&(t=H`${t} ${l}`),f.push({sql:t,context:this.statementContext(e,this.operation)})}continue}let n=compileBindBudgetChunks(t.rows.length,d,(n,i)=>{let a=this.#ie(e,t.columns,t.rows.slice(n,i),r);return l?H`${a} ${l}`:a});for(let t of n)f.push({sql:t.statement,context:this.statementContext(e,this.operation)})}return this.setMutations(f,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)})}async upsertOne(e,t,n,r,i,a){let o=this.queries,s=this.driver.adapter,c=Object.keys(t),l=this.#ie(e,c,[t]),u=s.mutations.onConflict(H.join(r.map(t=>s.identifiers.escape(o.columnName(e,t))),`, `),s.mutations.onConflictUpdate(H.join(this.#fe(e,n),`, `)));return this.#ae(e,H`${l} ${u}`,i,a)}async updateMany(e,t,n,r,i,a){let o=this.queries,s=this.driver.adapter,c=this.#fe(e,n);if(i&&!(s.capabilities.supportsReturning&&returningSafeProjection(i))){let l=await this.captureMutationIdentities(e,t,r);return l.length===0?this.published([],a):(await this.#oe(e,t,l,r,t=>s.mutations.update(o.table(e),H.join(c,`, `),t),this.operation===`delete`||this.operation===`deleteMany`?`deleteMany`:`updateMany`),this.finishTerminals(this.seriesQueries(i,l.map(t=>this.#se(e,t,n)),`updateMany`),e=>this.published(e,a)))}this.#$(e,t,a);let l=o.lowerMutationLimit(e,t,r),u=s.mutations.update(o.table(e),H.join(c,`, `),l.where),d=l.suffix?H`${u} ${l.suffix}`:u;return this.#ae(e,d,i,a)}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.#oe(e,t,s,n,t=>o.mutations.delete(a.table(e),t),`deleteMany`),this.published(c,i)}this.#$(e,t,i);let s=a.lowerMutationLimit(e,t,n),c=o.mutations.delete(a.table(e),s.where),l=s.suffix?H`${c} ${s.suffix}`:c;return this.#ae(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#oe(e,t,n,r,i,a){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 o=i(this.capturedTarget(e,t,n)),s=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.#V(o,s)));return}let c=this.queued.length,l={};this.#v=l,this.#j(o,s,l);let u=await this.submit(!0,l);await this.settleSubmitted(()=>{let e=u[c];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}#se(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=J(this.driver.adapter).batchRefs;e.scratchId=crypto.randomUUID();for(let n of t.setup(e.scratchId))this.#j(n);return this.#j(t.clear(e.scratchId)),e.scratchId}#ce(){let e=this.#o;if(e?.scratchId===void 0)return un;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}#le(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(J(this.driver.adapter).batchRefs.cleanup(e.scratchId)),e.scratchId=void 0)}#ue(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,a=`create`,o,s){let c=this.queries,l=this.driver.adapter,u=Object.keys(t),d=this.#ie(e,u,[t]),f=[...n].filter(e=>t[e]===void 0),p=this.statementContext(e,a);if(!this.usesBatch){let n=f.length?c.prepareProjection(e,{select:Object.fromEntries(f.map(e=>[e,!0]))}):void 0,r=l.capabilities.supportsReturning?void 0:this.#ue(e,f);if(f.length&&!l.capabilities.supportsReturning&&r===void 0)throw Error(`Returning generated values requires RETURNING support or one generated increment field`);n&&l.capabilities.supportsReturning&&(d=H`${d} ${l.mutations.returning(H.join(c.lowerProjection(n),`, `))}`),this.#s.rejectedInsert=void 0;let i;try{i=await this.dispatch(1,!1,()=>this.#V(d,p))}catch(e){throw o&&e instanceof I&&(this.#s.rejectedInsert={error:e,producer:o}),e}let a=r===void 0?i.rows:i.insertId===void 0?[]:[{[r]:i.insertId}],s=n?c.decodeProjection(n.shape,a,!0)[0]:void 0;if(f.length&&s===void 0)throw TypeError(`INSERT did not produce the required record`);return{...t,...s}}s&&(this.#u??=[]).push({declaring:!0,model:s.model,state:()=>c.select(s.model,{where:s.where(),select:Object.fromEntries(this.schema.keys(s.model).map(e=>[e,!0]))}),failure:()=>new i(`Cannot ${s.verb} relation '${s.relation}': parent record changed across a committed segment.`,s.relation)});let m={...t};if(f.length){let i=J(l).batchRefs,a=this.#ue(e,f),s=i.storeInsertedKey;if(!(a!==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])],a=Object.fromEntries(i.map(e=>[e,!0])),s=c.prepareProjection(e,{select:a}),u=this.queued.length,f=this.#j(H`${d} ${l.mutations.returning(H.join(c.lowerProjection(s),`, `))}`,p,r);o&&this.#s.recordInsertProducer(f,o);let m=await this.submit(!0,r),h=await this.settleSubmitted(()=>{try{let e=c.decodeProjection(s.shape,m[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:h}),failure:()=>new L(`Created record '${e[`~`].names.ts}' changed across a generated-output segment boundary.`,{meta:{model:this.modelName,operation:this.operation}})}),{...t,...h}}let u=this.ensureScratch(),h=String(this.#s.nextField++),[g,..._]=s(u,h,d,l.identifiers.escape(c.columnName(e,a))),v=this.#j(g,p,r);o&&this.#s.recordInsertProducer(v,o);for(let e of _)this.#j(e);let y=l.expressions.cast(i.read(u,h),physicalField(this.schema,e,a).scalar[`~`].state.type===`bigint`?`bigint`:`integer`);this.#s.publishScratchValue({model:e,field:a,expression:y}),m[a]=y}else{let e=this.#j(d,p,r);o&&this.#s.recordInsertProducer(e,o)}return m}async update(e,t,n,r,i=`update`,a=new Set,o){if(Object.keys(n).length===0)return{};let s=this.queries,c=this.driver.adapter,l=this.schema.identity(e,t),u={...n},d={},f=[];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`){f.push(r);continue}let a=J(c).batchRefs,o=this.ensureScratch(),l=String(this.#s.nextField++);this.#j(a.store(o,l,s.updateValue(e,r,i,s.fieldValue(e,r,t[r]))));let p=c.expressions.cast(a.read(o,l),`integer`);this.#s.publishScratchValue({model:e,field:r,expression:p}),u[r]=d[r]=p}let p=Object.entries(u).map(([t,n])=>s.updateAssignment(e,t,n)),m=c.mutations.update(s.table(e),H.join(p,`, `),s.lowerIdentity(e,l)),h=this.statementContext(e,i);if(!this.usesBatch&&a.size){let t=[...a],r=Object.fromEntries(t.map(e=>[e,!0])),i=s.prepareProjection(e,{select:r});if(!c.capabilities.supportsReturning){await this.dispatch(1,!1,()=>this.#V(m,h));let t=await this.read(s.select(e,{},void 0,{forUpdate:!0,projection:i,identity:this.#se(e,l,n)}),!0);if(!t[0])throw o?.()??TypeError(`UPDATE did not produce the required record`);return{...d,...t[0]}}let u=await this.dispatch(1,!1,()=>this.#V(H`${m} ${c.mutations.returning(H.join(s.lowerProjection(i),`, `))}`,h)),f=s.decodeProjection(i.shape,u.rows,!0);if(!f[0])throw o?.()??TypeError(`UPDATE RETURNING did not produce the required record`);return{...d,...f[0]}}if(await this.#pe(m,h,r),f.length===0)return d;let g=s.prepareProjection(e,{select:Object.fromEntries(f.map(e=>[e,!0]))}),_=await this.flush(s.select(e,{},void 0,{projection:g,identity:this.#se(e,l,n)}),r);if(!_[0])throw TypeError(`UPDATE did not produce the required record`);return{...d,..._[0]}}#de(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.#de(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.#V(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=Y(i,{columns:H.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.#pe(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.#pe(H`${c} ${i.mutations.onConflict(H.join(o.map(e=>i.identifiers.escape(e)),`, `),H`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),a=r[0]?{...t,...r[0]}:void 0;if(this.usesBatch){let t=new i(`Concurrent membership change on the singular polymorphic member of relation '${e.name}': ${a?`the captured membership is gone`:`another owner holds the target`}; retry to converge.`,e.name);t.meta.raceable=!0,a?this.requirePresent(this.queries.junction(e,a),t):await this.requireAbsent(n,t)}return a}async remove(e,t,n,r,i){let a=this.driver.adapter,o=this.queries,s=o.domain?.selector(e.target,`related`);if(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.#pe(a.mutations.delete(a.identifiers.table(e.table),a.operators.and(...c)),this.statementContext(e.source,`update`),i);return}let c=a.operators.and(...e.pairs.map(n=>a.operators.eq(o.column(e.target,n.target),o.fieldValue(e.target,n.target,t[n.source]))),...e.discriminator?[a.operators.eq(o.column(e.target,e.discriminator.field),o.value(e.discriminator.value))]:[],...n?[o.lowerIdentity(e.target,this.schema.identity(e.target,n))]:[],...r.length?[a.operators.not(a.operators.or(...r.map(t=>o.lowerIdentity(e.target,this.schema.identity(e.target,t)))))]:[],...s?[o.lowerSelector(s)]:[]),l=e.clearability.fields.map(t=>a.set.assign(o.column(e.target,t),a.literals.null()));await this.#pe(a.mutations.update(o.table(e.target),H.join(l,`, `),c),this.statementContext(e.target,`update`),i)}#fe(e,t){return Object.entries(t).map(([t,n])=>this.queries.updateAssignment(e,t,n))}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=o.operators.and(a.memberWhere(e,t,s[`~`].names.sql),...c?[c]:[]);await this.#pe(r?o.mutations.update(a.table(s),H.join(this.#fe(s,r),`, `),l):o.mutations.delete(a.table(s),l),this.statementContext(s,r?`updateMany`:`deleteMany`),i)}async delete(e,t,n){await this.#pe(this.driver.adapter.mutations.delete(this.queries.table(e),this.queries.lowerIdentity(e,this.schema.identity(e,t))),this.statementContext(e,`delete`),n)}async#pe(e,t,n){this.usesBatch?this.#j(e,t,n):await this.dispatch(1,!1,()=>this.#V(e,t))}};const parseStamped=(e,t)=>lt((t,n)=>e.get(t)?.create?.[n]!==void 0,t);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 l(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 i(`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 l(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;execution;model;source;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),this.facts=i??a.selectorFacts(this.selector),this.#e=a.prepareProjection(t,{select:Object.fromEntries(storedFields(e.context.schema,t).map(e=>[e,!0]))}),this.#t=a.prepareProjection(t,{select:Object.fromEntries(e.context.schema.keys(t).map(e=>[e,!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===X(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})}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 I&&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 a of e.transitions){let o=this.#r(a,e.located.fields),s=this.#r(a,e.fields);for(let e of a.pairs)if(s[e.source]===null)throw new i(`Cannot update relation key field '${e.source}' to null while mutating relation '${a.name}'. A null reference names no row for that relation to point at.`,a.name,{meta:{operation:`update`,field:e.source,relation:a.name}});if(!a.reference||a.reference.onUpdate===`cascade`||a.pairs.some(e=>o[e.source]===null))continue;let c=r.operators.or(...a.pairs.map(t=>r.operators.not(r.operators.eq(n.fieldValue(e.model,t.source,o[t.source]),n.updateValue(e.model,t.source,s[t.source],n.fieldValue(e.model,t.source,o[t.source])))))),l=new i(`Cannot update relation '${a.name}' with onUpdate('${a.reference.onUpdate??`restrict`}') while the current relation is occupied.`,a.name,{meta:t.usesBatch?{relation:a.name}:{operation:`update`,relation:a.name}});t.usesBatch&&(l.meta.raceable=!0),await t.requireAbsent(n.select(a.target,{take:1},{edge:a,parent:o},{condition:c}),l)}}requireRepresentable(e,t,n){if(n===null)throw this.#o(e,t)}#o(e,t){return new i(`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=J(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 I&&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();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 s(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 s(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 c=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]),c,t,a.operation,a.fields.demands,n):await r.insert(a.model,c,a.fields.demands,t,a.operation,a.fields,this.#c(a,e.parent?.command)));for(let n of e.children)n.placement===`capture`&&await this.run(n,t);for(let n of e.children)n.placement===`after`&&await this.run(n,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.#m(e.children.filter(isRecordOccurrence),t);return;case`selectedSeries`:isSeriesOccurrence(e)&&await this.#x(e);return;case`membership`:return}}async records(e,t,n){let{count:r,identities:i}=await this.#m(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})}async#m(e,t,n=!1){let r=this.context,i=r.prepareMembers(()=>e,t),a=[],o=i[0],s=o?.command.fields.writtenFields()??[];if(!n&&i.length>1&&o&&i.every(({command:e,children:t,refusal:n})=>e.model===o.command.model&&e.fields.operation===`create`&&e.fields.demands.size===0&&e.fields.writtenFields().length===s.length&&e.fields.writtenFields().every((e,t)=>e===s[t])&&!e.suppression&&!e.located&&t.length===0&&n===void 0)){let e=await r.insertMany(o.command.model,()=>{for(let{command:e}of i)e.fields.activate();return i.map(({command:e})=>this.stored(e.fields))});if(e!==void 0)return{count:e,identities:a}}let c=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.#h(e),t);continue}c++,n&&a.push(this.identity(t.fields))}return{count:c,identities:a}}async#h(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.#g(t);if(n){this.attempt.bind(t.fields,n);for(let n of e.children)n.placement!==`before`&&await this.run(n,t)}}async#g(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=X(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.#x(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#_(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,a=r.series.get(e);if(a)return a;let o=e.command.series,s=o.selection,c=s.membership(),l;if(c){let{edge:e,parent:a}=c,s=new i(`Cannot ${o.mutation.kind} relation '${e.name}': parent record changed across a committed segment.`,e.name),parentWhere=()=>({...this.identity(a),...this.#r(e,a)}),u=await n.flush(n.queries.select(a.model,{where:parentWhere(),select:Object.fromEntries([...a.demands].map(e=>[e,!0]))}),t);if(!u[0])throw n.failure(s,`result`,t);r.bind(a,u[0]),l={failure:s,query:n.queries.select(a.model,{where:parentWhere(),select:Object.fromEntries(n.schema.keys(a.model).map(e=>[e,!0]))})}}let u=n.queries.keyOrder(s.model),d=await n.read(n.queries.select(s.model,{orderBy:Object.fromEntries(u.map(e=>[e,`asc`])),take:o.limit},c&&{edge:c.edge,parent:this.#r(c.edge,c.parent)},{forUpdate:!n.usesBatch,selector:s.selector}),!0,!1,s.model);if(o.mutation.kind===`update`){let e=this.#b(s.model,o.mutation.raw,d.length);if(e)throw n.failure(e,`planning`,t)}c&&l&&n.usesBatch&&(n.requirePresent(l.query,l.failure),await this.#_(o,c,d));let f=n.prepareMembers(()=>d.map(e=>{let t=this.commands.capture(s,e);if(r.rows.set(t,e),r.bind(t.fields,e),o.mutation.kind===`delete`){n.usesBatch&&c&&(n.requirePresent(t.captured(void 0,c,1),membershipRaceFailure(o.mutation.kind,c.edge.name,`removed`)),r.retained.add(t));let e=o.mutation.raw;return{kind:`delete`,located:t,origin:o.mutation.origin,...e&&{values:this.commands.stamp(s.model,`update`,this.#v(s,c,e))}}}let i=this.commands.update(t,this.#v(s,c,o.mutation.raw),o.mutation.raw);return c&&(i.requirement={selection:t,membership:c,failure:s.required}),i}),t),p=this.commands.expandSeries(e,f);if(p)throw n.failure(p.error,`planning`,p.member);let m={members:this.commands.seriesMembers(e),parentRequirement:l};return r.series.set(e,m),m}#v(e,t,n){let r=this.context.scope?.rows.stamps;return r===void 0?this.#y(e,t,n):parseStamped(r,()=>this.#y(e,t,n))}#y(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)}#b(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 l(`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#x(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 dn=[`disconnect`,`delete`,`create`,`connect`,`connectOrCreate`,`upsert`,`update`,`set`,`updateMany`],fn=[`disconnect`,`delete`,`set`,`updateMany`,`deleteMany`,`update`,`upsert`,`connectOrCreate`,`connect`,`create`,`createMany`];function missingTarget(e,t,n=!0){return new i(`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`?fn:dn,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,a){let o=this.#i,s=this.#n,entryOrigin=()=>this.#r.createOrigin(a.relation,a.operation,a.slot);switch(o.fields.operation===`update`&&e.kind===`reference`&&e.owner===`target`&&e.pairs.some(e=>o.fields.writesField(e.source))&&!o.transitions.includes(e)&&o.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(),a=nestedTargetAddressesConstraint(e,t),c=t===`delete`?this.#r.tombstone(e.target):void 0,l=this.#r.lookup(e.target,{kind:`query`,where:i,unique:a,...t===`delete`||t===`disconnect`?{selector:this.#r.candidates(this.#r.context.queries.prepareSelector(e.target,i,a),`related`,c!==void 0)}:{},membership:{edge:e,parent:o.located.fields}},r?void 0:()=>missingTarget(t,e.name));l.origin=n,this.#v(e,o.located.fields),r&&(l.retained=()=>membershipRaceFailure(t,e.name,`removed`));let u=this.#f(l),d={kind:`delete`,located:l,origin:n,...c&&{values:c.admitted}};if(c&&this.#d(e,o.located.fields,l.selector,n),e.kind===`reference`&&e.owner===`source`){if(!(s||c)&&e.clearability.kind===`columns`){let t={origin:n,scope:e.scope,identity:o.located?.facts};for(let t of e.clearability.fields)o.fields.contribute(t,{kind:`literal`,value:null},`Cannot disconnect relation '${e.name}'.`);this.#r.publishMembership(u,o.fields,t)}t===`delete`&&this.#r.place(o,d,`after`,n)}else{let i={kind:`remove`,edge:e,source:o.fields,target:r?void 0:l.fields,keep:[],origin:n};t===`delete`&&e.kind===`junction`&&!c&&this.#r.place(o,i,`after`,n),this.#r.place(o,t===`delete`?d: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 i=entries(record(r).data),s=entries(t.data).map((n,r)=>{let o=this.#l(e,n,i[r]);return o.origin=a,t.skipDuplicates&&(o.suppression={kind:`skipDuplicate`}),this.association(e,o,!1,o)});this.#r.place(o,{kind:`series`,records:s},`after`,a);break}case`connect`:case`connectOrCreate`:case`upsert`:case`update`:{let a=[],s=[];for(let[c,l]of entries(n).entries()){let n=entryOrigin(),u=entries(r)[c],d=t===`connect`?{where:l}:l,f=t===`upsert`?d.update:d.data,p=this.#r.context.schema.keyPortabilityRefusal(e.target,f);if(p&&t!==`upsert`)throw p;let m=d.create===void 0?void 0:this.#l(e,record(d.create),record(u.create));m&&(m.origin=n);let h=(t===`update`||t===`upsert`)&&o.fields.operation===`update`,g=t===`update`&&!e.many?this.#e:void 0,_=g?.kind===`query`?g:void 0,v=this.#r.context.queries,y=v.prepareSelector(e.target,d.where,nestedTargetAddressesConstraint(e,t)),b=y.uniqueValues;if(t===`connect`){let e=v.selectorFacts(y);if(e.exact&&Object.keys(record(d.where)).every(t=>e.fields.has(t)||y.uniqueKey?.name===t)){if(s.some(t=>sameTarget(t,e.equals)))continue;s.push(e.equals)}}if(t===`connectOrCreate`&&b){if(a.some(e=>sameTarget(e,b)))continue;m&&[...b].every(([e,t])=>{let n=m.fields.known(e);return n?.kind===`literal`&&Object.is(n.value,t)})&&a.push(b)}let x={kind:`query`,where:d.where,selector:y,purpose:`related`},S;if(_){let t=_.selector,n=v.selectorFacts(y),r=v.selectorFacts(t);S=n.fields.size===0?r:n,x={kind:`query`,selector:v.andSelectors(e.target,[t,y])}}g?.kind===`producer`&&(x={kind:`producer`,where:x.where,selector:x.selector,producer:g.producer,purpose:x.purpose},g.producer.select(storedFields(this.#r.context.schema,e.target)));let C,w;if(h&&!g){let n=e.kind===`reference`?e.pairs.map(e=>({...e,value:o.fields.known(e.source)??o.located.fields.field(e.source)})):[];w=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`&&d.where!==void 0?C=r:x={kind:`query`,where:x.where,selector:x.selector,membership:r,purpose:x.purpose}}let T=this.#r.lookup(e.target,x,t===`connect`||t===`update`?()=>missingTarget(t,e.name,t===`update`):void 0,S);T.origin=n,m&&(T.insertsWhenAbsent=!0),t===`connectOrCreate`&&(T.retained=()=>new i(`Record was replaced by another transaction during nested connectOrCreate`,e.name)),T.membershipOnly=t===`connect`&&!(e.kind===`reference`&&e.owner===`source`),t===`connect`&&!T.membershipOnly&&(T.retained=T.required),this.#t&&t===`connect`&&this.#f(T),h&&!g&&t===`update`&&e.kind===`junction`&&this.#f(T);let E=C&&{selection:T,membership:C,failure:()=>missingTarget(`upsert`,e.name)},D=new Assignments(e.target,`select`,{},{},void 0,m?[m.fields]:[]);for(let[e,t]of Object.entries(w??{}))D.restate(e,t);let O={kind:`choose`,model:e.target,lookup:T,foundRequirement:E,missing:m?this.#r.occurrence(m,`after`):void 0,fields:D,found:t===`upsert`||t===`update`?this.#r.occurrence(this.#r.update(T,record(f),record(t===`upsert`?u.update:u.data??u),!0,t===`upsert`?`upsert`:`update`),`after`):void 0};O.found&&(O.found.command.origin=n,O.found.command.requirement=E,p&&O.found.command.fields.reject(p)),this.association(e,O,h),this.#c(O)}break}case`set`:this.#m(e,entries(n),a);break;case`updateMany`:case`deleteMany`:{let i=entries(r);o.fields.select(this.#r.context.schema.keys(o.model)),this.#v(e,o.fields);for(let[r,a]of entries(n).entries()){let n=entryOrigin(),s=record(a),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),p=d?d.admitted:record(s.data);if(e.kind===`reference`&&(t===`deleteMany`||!u.schema.namesRelation(e.target,p))){let a={kind:`set`,edge:e,parent:o.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,o.fields,f,n,!0),this.#r.place(o,a,`after`,n);continue}let m=this.#r.lookup(e.target,{kind:`query`,where:l,selector:f,membership:{edge:e,parent:o.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,o.fields,f,n);let v=this.#r.place(o,this.#r.selectedSeries(_),`after`,n);this.#p(v)}break}default:Ne(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`},()=>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 a=[...e.discriminator?.side===`target`?[e.discriminator.field]:[],...e.pairs.map(e=>e.target)];this.#v(e,r.located.fields);let o={kind:`absent`,model:e.target,membership:{edge:e,parent:r.located.fields},excluding:t.map(e=>e.lookup.fields),failure:()=>new i(`Cannot set relation '${e.name}' because foreign key field(s) ${a.join(`, `)} are required: rows removed from the set cannot be disconnected. Delete them instead.`,e.name)};this.#r.place(r,o,`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,pn,{},!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 i(`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 i(`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}})}function isRecordOccurrence(e){return e.command.kind===`record`}function isSeriesOccurrence(e){return e.command.kind===`selectedSeries`}const pn=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===pn?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 of Object.keys(a))r[e]===void 0&&!o.has(e)&&(s[e]=a[e]);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})}candidates(e,t,n){let r=this.context.scope,i=this.context.queries,a=i.candidates(e,t);return n&&r&&r.defaults!==r.domain?i.candidates(a,t,r.defaults):a}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 l(`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.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),o=r.queries.candidates(r.queries.prepareSelector(e,t.where,!0),`root`);return()=>r.updateMany(e,o,a,void 0,i,()=>new s(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 c=r.queries.prepareProjection(e,t);if(!returningSafeProjection(c))return;let l=this.stamp(e,`create`,t.create,n.create),missing=()=>r.createMany(e,[l],c,!1,()=>{throw new InvalidScalarResult(`record`,`INSERT did not produce the required record`)}),u=this.lookup(e,{kind:`query`,where:t.where,unique:!0,purpose:`root`});u.insertsWhenAbsent=!0;let d=u.selector.uniqueKey;if(i.supportsTargetedUpsert&&u.selector.scoped===void 0&&d!==void 0&&u.selector.uniqueValues!==void 0&&o.every(e=>wholeValue(a[e]))&&d.fields.every(e=>{let t=l[e];return(t===null||typeof t!=`object`&&typeof t!=`function`)&&Object.is(t,u.selector.uniqueValues.get(e))}))return{single:!0,run:()=>r.upsertOne(e,l,a,d.fields,c,()=>{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`);return r.updateMany(e,n,a,void 0,c,()=>new s(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),c=this.candidates(r.queries.prepareSelector(e,t.where,n),`root`,o!==void 0),l=n?()=>new s(e[`~`].names.ts,`delete`):void 0,u=!i||a&&returningSafeProjection(i);if(!o)return{single:u,run:()=>r.deleteMany(e,c,t.limit,i,l)};let d=o.admitted;return this.#k(c,t.limit,u,t=>{let n=i&&!(a&&returningSafeProjection(i))?t*r.schema.keys(e).length:0;for(let[t,i]of Object.entries(d))n+=r.queries.updateAssignment(e,t,i).values.length;return n},(t,n)=>r.updateMany(e,t,d,n,i,l))}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`});o.insertsWhenAbsent=!0;let c=this.context.queries,l=[],u=[],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=c.prepareSelector(e,r),a=premiseChanged(`${n} skip premise`);a.meta.raceable=!0;let s=this.lookup(e,{kind:`query`,selector:c.andSelectors(e,[o.selector,i])});s.insertsWhenAbsent=!0,u.push(n),l.push({lookup:s,match:premiseChanged(`${n} match premise`),skip:a})}let[d]=l,f=this.occurrence(this.update(o,t.update,n.update,!0,`upsert`)),p=r.schema.keyTransitionRefusal(e,t.update,o.selector.facts.keys,f.command.transitions);if(p)throw p;let m={kind:`choose`,model:e,lookup:o,operation:`upsert`,missing:this.occurrence(a),conditions:d&&{probes:l,missingRow:new s(e[`~`].names.ts,`upsert`),matched:l.length===1?d.match:premiseChanged(`matched premise (${u.join(`, `)})`)},fields:new Assignments(e,`select`,{},{},void 0,[a.fields]),found:f};f.command.operation=`upsert`,m.fields.forward(f.command.fields);for(let t of r.schema.keys(e))m.fields.field(t);let h=this.analyze(m),g=this.choiceArm(h,`found`);return g&&r.schema.namesRelation(e,t.update)&&(g.refusal=r.schema.keyPortabilityRefusal(e,t.update)??g.refusal),{single:!1,run:()=>this.execution.complete(h,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`},()=>new s(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,c=r.schema.namesRelation(e,o),l=bulkProjection(r,e,t);if(t.limit===0)return{single:!0,run:async()=>r.emptyBulkResult(l)};if(!c){let i=r.queries.candidates(r.queries.prepareSelector(e,t.where),`root`),s=this.stamp(e,`update`,o,n.data);return{single:!l||a,run:()=>r.updateMany(e,i,s,t.limit,l)}}let u=this.lookup(e,{kind:`query`,where:t.where,purpose:`root`},()=>new s(e[`~`].names.ts,`update`)),d={selection:u,analysis:this.update(u,o,n.data,!0),limit:t.limit,mutation:{kind:`update`,raw:n.data}},f=this.analyzeSeries(d);return{single:!1,run:async()=>l?this.execution.series(f,d.selection,l):{count:await this.execution.series(f)}}}};function admittedOperation(e){switch(e){case`findUniqueOrThrow`:return`findUnique`;case`findFirstOrThrow`:return`findFirst`;case`create`:case`createMany`:case`update`:case`upsert`:case`updateMany`:case`delete`:case`deleteMany`:case`findMany`:case`findUnique`:case`findFirst`:case`count`:case`exist`:case`aggregate`:case`groupBy`:return e;default:return Ne(e,`client operation`)}}function publishedFacts(e,t){return{models:t,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;#f=new Set;constructor(e,t,n,r,i,a,o){let c;this.#c=o&&{rows:o,domain:preparedDomain(n,o.domain),defaults:preparedDomain(n,o.defaults),instant:()=>c??=new Date},this.#e=e,this.#t=t,this.#n=n,this.#r=admittedOperation(i),this.#i=e.schema[r],this.#a=r,this.#o=a,this.#s=i===this.#r?void 0:()=>new s(this.#i[`~`].names.ts??`unknown`,i)}get args(){return this.#l??=this.#p()}#p(){let e=this.#c?.rows.stamps,admit=()=>this.#t.admit(this.#i,this.#r,this.#o);return e===void 0?admit():parseStamped(e,admit)}#m(){let e=this.#r;if(isReadOperation(e)){if(!this.#u){let t=this.#c?.domain.reads??this.#n,n=t.captureModels(()=>t.read(this.#i,e,this.args));this.#u=n.value,this.#f=n.models}return this.#u}}get read(){let e=this.#m();if(e)return this.#d??=publishedFacts(e,this.#f)}#h(e){let t=this.#m();if(t){for(let t of this.#f)e.modelDependencies.add(t);return e.run(()=>e.publish(t,this.#s))}let n=new Commands(e).plan(this.#i,this.args,this.#o),r=n.single;return e.run(()=>{let t=n??new Commands(e).plan(this.#i,this.args,this.#o);return n=void 0,t.run()},r)}execute(e,t,n){try{return this.#h(new OperationContext(this.#t,this.#e.driver,this.#a,this.#r,e,!1,t,this.#c,this.#e,n))}catch(e){return Promise.reject(e)}}prepareSingle(e){let t=this.args,n=new OperationContext(this.#t,this.#e.driver,this.#a,this.#r,void 0,!0,e,this.#c,this.#e),r=this.#m();if(r)return n.publishPrepared(r,this.#s),n.preparedBatch();let i=new Commands(n).plan(this.#i,t,this.#o);if(i.single)return i.run().catch(()=>void 0),n.preparedBatch()}async prepareBatch(e,t,n){let r=new OperationContext(this.#t,n??this.#e.driver,this.#a,this.#r,void 0,!0,e,this.#c,this.#e,t);try{await this.#h(r)}catch(e){if(r.isIncompletePreparation(e))return;throw e}return r.prepareStorageBatch()}};const mn=new WeakMap,hn=new WeakMap;function preparedDomain(e,t){let n=hn.get(e);n||hn.set(e,n=new WeakMap);let r=n.get(t);return r||n.set(t,r=new PreparedDomain(t,e)),r}function sharedQueries(e){let{adapter:t,result:n}=e.driver,r=e.resolved?.registry,i=r&&mn.get(r);i||(i={schema:new EngineSchema(e.schema,e.resolved),queries:new WeakMap},r&&mn.set(r,i));let a=i.queries.get(t);if(a||i.queries.set(t,a={parsers:new WeakMap}),!n)return a.none??=new $t(i.schema,t,n);let o=a.parsers.get(n);return o||(o=new $t(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;#a;constructor(e,t,n,r,i){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}get preparedArgs(){return this.#r.args}buildStatement(){return this.#r.read?.statement}cacheResultCodec(){let e=this.#r.read;if(!e)throw new l(`Cannot cache '${this.#n}' on model '${this.#t}': the operation has no readable result.`,{meta:{model:this.#t,operation:this.#n}});return this.#a??=h().cacheCodec(e,this.#n)}async checkStorage(e,t){let n=this.#r.read;n&&await this.#i?.(e,t,n.models)}prepareSingle(e){let t=this.#r.prepareSingle(e);return this.#i?void 0:t}async prepareBatch(e,t=this.#e){return this.#r.prepareBatch(e,this.#i,t)}async execute(e){try{let t=e.isWrite?routeWriteOutcome(e):void 0;return t?runWriteCandidate(this.#r,e,this.#e,t,this.#i):runCandidate(this.#r,e,this.#e,void 0,this.#i)}catch(e){return Promise.reject(e)}}};function createCandidateRoute(e,t,n,r){let i=createCommandEngine({schema:e,driver:t,resolved:n});return{operation(e,n,a,o){let s=e[`~`].names.ts??`unknown`,c=n;return new RoutedOperation(t,s,n,i.prepare(s,c,a,o),r)}}}async function runWriteCandidate(e,t,n,r,i){let a=await runCandidate(e,t,n,r.seam,i);return!r.published&&t.committedWriteSegment&&await t.committedWriteSegment(),a}function runCandidate(e,t,n,r,i){let{context:a,driverOverride:o,engineDriver:s}=t;return o?e.execute({driver:o,kind:`borrowed-transaction`,writeOutcome:r},a,i):s===n?e.execute(r?{kind:`standalone`,writeOutcome:r}:void 0,a,i):e.execute({driver:s,kind:`borrowed-transaction`,memberRollback:(e,t)=>s.withTransaction(e,void 0,t),operationRegion:(e,t)=>s.withTransaction(e,void 0,t),writeOutcome:r},a,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(M(e))return se(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 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){E(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=ae(t.extensionChain?.observe);return i!==void 0&&await i,executeObservedNativeArray(e,o,n,r,a)}for(let t of e)q(t).reserveWith(t,o);let c=[],l=[],u=[];for(let t of e){let e=q(t),n=await e.observeBatchPhase(t,o,async()=>{let n=e.prepare(t,o);return n?{kind:`single`,prepared:n}:{kind:`batch`,preparedBatch:await e.prepareBatch(t,o)}});if(n.kind===`single`){let r=c.length;c.push(n.prepared),u.push({parse:n=>e.observeBatchPhase(t,o,()=>{let i=n[r];if(!i)throw missingOperationResult(o,t,e);return e.parseResult(t,i)})});continue}let{preparedBatch:r}=n;if(!r)break;let i=c.length,a=r.queries.length;for(let e of r.queries)c.push(e);for(let e of r.guards??[])l.push({...e,queryIndex:i+e.queryIndex});u.push({parse:n=>e.observeBatchPhase(t,o,()=>r.parseResult(n.slice(i,i+a)))})}if(u.length!==e.length)throw unbatchableArrayError(o);let d=await executeNativeBatch(o,c,l,n,r);E(d,c.length,{provider:o.driverName,operation:`$transaction([...])`});for(let e=0;e<u.length;e+=1)s[e]=await u[e].parse(d);return s}return assertAtomicArraySupport(o),i?executeObservedFallbackArray(e,t,n,r,a):o.withTransaction(async t=>{for(let n=0;n<e.length;n+=1){let r=e[n];s[n]=await q(r).executeWith(r,t)}return s},n,r)}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=[],c=[],l=[];try{for(let n of e)q(n).reserveWith(n,t);for(let n of e){let e=q(n),r=await e.observeBatchPhase(n,t,async()=>{let r=e.prepare(n,t);return r?{kind:`single`,prepared:r}:{kind:`batch`,preparedBatch:await e.prepareBatch(n,t)}});if(r.kind===`single`){let i=s.length;s.push(r.prepared),l.push(r=>e.observeBatchPhase(n,t,()=>{let a=r[i];if(!a)throw missingOperationResult(t,n,e);return e.parseResult(n,a)}));continue}let{preparedBatch:i}=r;if(!i)throw unbatchableArrayError(t);let a=s.length,o=i.queries.length;for(let e of i.queries)s.push(e);for(let e of i.guards??[])c.push({...e,queryIndex:a+e.queryIndex});l.push(r=>e.observeBatchPhase(n,t,()=>i.parseResult(r.slice(a,a+o))))}}catch(e){throw rejectObservedMembers(o,e),e}let u;try{u=await executeNativeBatch(t,s,c,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,u,s.length);for(let e=0;e<l.length;e+=1){let t=await l[e](u),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:Ae(r,{readyToCommit:()=>{o.phase=`ready`},committed:()=>{o.phase=`committed`}});try{let r=await t.driver.withTransaction(async t=>{for(let n=0;n<e.length;n+=1){let r=e[n];a[n]=await q(r).executeWith(r,t)}return 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=q(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=[],s=[],c=[];try{for(let t of e){let e=await t.owner.observeBatchPhase(t.operation,n,async()=>{let e=t.owner.prepare(t.operation,n);return e?{kind:`single`,prepared:e}:{kind:`batch`,preparedBatch:await t.owner.prepareBatch(t.operation,n)}});if(e.kind===`single`){let r=o.length;o.push(e.prepared),c.push({parse:e=>t.owner.observeBatchPhase(t.operation,n,()=>{let i=e[r];if(!i)throw missingOperationResult(n,t.operation,t.owner);return t.owner.parseResult(t.operation,i)})});continue}let{preparedBatch:r}=e;if(!r)throw unbatchableArrayError(n);let i=o.length,a=r.queries.length;for(let e of r.queries)o.push(e);for(let e of r.guards??[])s.push({...e,queryIndex:i+e.queryIndex});c.push({parse:e=>t.owner.observeBatchPhase(t.operation,n,()=>r.parseResult(e.slice(i,i+a)))})}}catch(n){throw await closePreDispatchFailure(e,t,n)}let l=!1,u=[],confirmCommit=async()=>{if(!l){l=!0,a?.(`committed`);for(let t of e)t.certainty=`committed`;u.push(...await publishNativeOutcome(e,t,`committed`))}},d;try{d=await executeNativeBatch(n,o,s,r,i,n.supportsOrderedCommittedSegments?confirmCommit:void 0)}catch(n){throw l?await closeCommittedFailure(e,n,u):(a?.(`may-have-committed`),await closeDispatchedFailure(e,t,n))}await confirmCommit();try{assertNativeBatchResults(n,d,o.length)}catch(t){throw await closeCommittedFailure(e,t,u)}let f=Array(e.length);for(let t=0;t<e.length;t+=1){let n=e[t];try{n.child.resolve(await c[t].parse(d))}catch(e){n.child.reject(markArrayCommitCertainty(e,`committed`))}}let p=await Promise.allSettled(e.map(readArrayQuery)),m=[];for(let e=0;e<p.length;e+=1){let t=p[e];if(t.status===`fulfilled`)f[e]=t.value;else for(let e of queryFailureParts(t.reason))m.push(e)}let h=[...m,...u.map(e=>markArrayCommitCertainty(e,`committed`))];if(h.length>0)throw combineArrayFailures(h[0],h.slice(1));return f}async function closePreDispatchFailure(e,t,n){t.discardAll();for(let t of e)t.child.reject(n);let r=await Promise.allSettled(e.map(readArrayQuery)),i=[];for(let e of r)if(e.status===`rejected`)for(let t of queryFailureParts(e.reason))t!==n&&i.push(t);return combineArrayFailures(n,i)}async function closeDispatchedFailure(e,t,n){let r=markArrayCommitCertainty(n,`may-have-committed`);for(let t of e)t.certainty=`may-have-committed`;let i=await publishNativeOutcome(e,t,`may-have-committed`);for(let t of e)t.child.reject(r);let a=await Promise.allSettled(e.map(readArrayQuery)),o=[];for(let e of a)if(e.status===`rejected`)for(let t of queryFailureParts(e.reason))t!==r&&o.push(t);for(let e of i)o.push(e);return combineArrayFailures(r,o)}async function closeCommittedFailure(e,t,n){let r=markArrayCommitCertainty(t,`committed`);for(let t of e)t.certainty=`committed`,t.child.reject(r);let i=[],a=await Promise.allSettled(e.map(readArrayQuery));for(let e of a)if(e.status===`rejected`)for(let t of queryFailureParts(e.reason))t!==r&&i.push(t);for(let e of n)i.push(e);return combineArrayFailures(r,i)}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 Ee(e))r.push(t)}return r}function queryFailureParts(e){let t=W(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 F({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 F({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)q(t).prepareAdmission(t);for(let t of e)q(t).prepareAdmission(t,`plan`)}function requiresInterceptedArray(e){for(let t of e)if(q(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=Me(n);if(e===void 0)throw new R;if(e.clientId(n)!==t.clientId)throw p.clientMismatch(e.model(n),e.operation(n));if(e.scopeId(n)!==t.scopeId)throw p.scopeMismatch(e.model(n),e.operation(n))}}async function executeInterceptedArray(e,t,n,r,i){let a=t.driver;assertAtomicArraySupport(a);let o=ae(t.extensionChain?.observe);o!==void 0&&await o;let s=new pe,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:q(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:Ae(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=M(n)?se(n,r):n;try{await t.publish(r)}catch(e){throw m(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=W(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=W(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)}function assertDecimalDomainsFitProvider(e,t){let n=Et(e,t);if(n!==void 0)throw new u(Dt(n))}function assertGeoPointFieldsFitAdapter(e,t){t.geoPoint===void 0&&refuseGeoPointFields(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 u(`GeoPoint field '${t}.${n}' cannot be stored by this driver because its adapter has no GeoPoint protocol.`)}}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 P(`Client 'omit' names model '${r}', which is not in the schema.`,N.INVALID_INPUT,{meta:{model:r}});if(!n(o))continue;let s=new Set(Fe(a)),c={};for(let e of Object.keys(o)){if(!s.has(e))throw new P(`Client 'omit' names field '${e}' on model '${r}', which is not a readable scalar of that model.`,N.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}},gn=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)=>gn.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},_n=xt(`"`);function sqliteStorageCheck(e,t){let n=t.filter(e=>e.kind!==`decimal`).map(e=>{let t=e.kind===`time`?Tt:kt;if(!e.list)return H`NOT ${H.raw(t(e.name))}`;let n=_n(e.name);return H.raw(`CASE WHEN ${n} IS NULL THEN 0 WHEN json_valid(${n}) AND json_type(${n}) = 'array' THEN EXISTS (SELECT 1 FROM json_each(${n}) WHERE type <> 'text' OR NOT ${t(`value`)}) ELSE 1 END`)}),r=n.length===0?H.raw(`NULL`):H`(SELECT 1 FROM ${H.raw(bt(_n,void 0,e))} WHERE ${H.join(n,` OR `)} LIMIT 1)`;return{statement:H`SELECT s.sql AS definition, p.name, p.type, p."notnull", p.pk, ${r} AS foreign_time FROM sqlite_schema AS s JOIN pragma_table_info(s.name) AS p WHERE s.type = 'table' AND s.name = ${e}`,validate(n){let i=n[0]?.definition;typeof i!=`string`&&refuse(e,t[0]?.name??``,`its physical table is missing or cannot be inspected`);for(let r of t){let t=n.find(e=>e.name===r.name);if((!t||typeof t.type!=`string`||typeof t.definition!=`string`)&&refuse(e,r.name,`its physical column is missing or cannot be inspected`),t.foreign_time!==null&&t.foreign_time!==void 0&&refuse(e,r.name,`stored time values are not canonical UTC text; repair them with VibORM's SQLite DateTime conversion before using typed queries`),r.kind!==`decimal`)continue;let i=Ot(t.definition,{name:r.name,type:t.type,nullable:Number(t.notnull)===0&&Number(t.pk)===0},_n);(t.type.toUpperCase()!==(r.list?`TEXT`:`INTEGER`)||!Ze(i,r.descriptor))&&refuse(e,r.name,`its declared storage is not the checked scaled-integer decimal domain; foreign REAL/NUMERIC/TEXT decimals require an explicit conversion`)}return H`SELECT 1 FROM sqlite_schema AS s WHERE s.type = 'table' AND s.name = ${e} AND s.sql = ${i} AND ${r} IS NULL`}}}function refuse(e,t,n){throw new l(`Cannot use SQLite column "${e}"."${t}": ${n}.`,{meta:{table:e,column:t,dialect:`sqlite`}})}function createPhysicalSchemaCheck(e,t){if(t.dialect!==`sqlite`)return;let n=new Map;for(let[r,i]of Object.entries(e)){let e=i[`~`].state,a=[];for(let[n,r]of Object.entries(e.scalars)){let e=r[`~`].state,o=i[`~`].getFieldName(n).sql;e.type===`decimal`?a.push({name:o,kind:`decimal`,descriptor:e.decimal,list:e.array===!0}):(e.type===`time`||e.type===`datetime`&&(e.array||(t.adapter.result.dateTimeRepresentation?.(r[`~`].nativeType)??`text`)===`text`))&&a.push({name:o,kind:e.type===`time`?`time`:`timestamp`,list:e.array===!0})}a.length&&n.set(i,sqliteStorageCheck(i[`~`].names.sql??e.tableName??r,a))}if(n.size!==0)return async(e,t,r)=>{let i=[];for(let a of new Set(r)){let r=n.get(a);if(!r)continue;let o=await e._executeRaw(r.statement.toStatement(),r.statement.values,ke(t,`$schema`,`verifyStorage`)),s=r.validate(o.rows);i.push({query:s,failure:new l(`SQLite storage for model '${a[`~`].names.ts}' changed after inspection or contains noncanonical time values; repair its physical schema/data before using typed queries.`,{meta:{model:a[`~`].names.ts,dialect:`sqlite`}})})}return i}}const vn=new Map([[`findUnique`,`findUnique`],[`findUniqueOrThrow`,`findUnique`],[`update`,`update`],[`delete`,`delete`],[`upsert`,`upsert`]]);function assertNonEmptyUniqueWhere(e,t){let r=vn.get(e);if(r===void 0||!n(t))return;let i=t.where;if(n(i)&&!Object.keys(i).some(e=>i[e]!==void 0))throw new f(r,[{path:`where`,message:`whereUnique requires at least one unique discriminator.`}])}function createModelProxy(e,t,n,r=[]){let i=new Set(r.length===0?Object.keys(e):r.length===1?[...y,...Object.keys(n?.[r[0]]??{})]:[]),a=new Map,readMember=o=>{if(typeof o!=`string`||o===`then`||!i.has(o))return;if(r.length===1){let e=n?.[r[0]]?.[o];if(e)return e}let s=a.get(o);return s===void 0&&(s=createModelProxy(e,t,n,[...r,o]),a.set(o,s)),s};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`&&i.has(t),ownKeys:e=>[...new Set([...Reflect.ownKeys(e),...i])],getOwnPropertyDescriptor:(e,t)=>Reflect.getOwnPropertyDescriptor(e,t)??(typeof t==`string`&&i.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(At,e)}var yn=class VibORM{#e;#t;#n;#r;constructor(e,{relations:t,schemaRegistry:n}){this.#e=e.schema,this.#n=t,this.#t=new It(e.driver,createCandidateRoute(this.#e,e.driver,{index:t,registry:n},createPhysicalSchemaCheck(this.#e,e.driver)))}#i(e,t,n){return createModelProxy(this.#e,({modelName:t,operation:r,args:i})=>this.#a(e,t,r,i,n),t)}#a(e,t,n,r,i,a){let o=_(e.extensionChain),s=String(t),c=this.#e[t];if(!c)throw new u(`Model "${s}" not found in schema`,{meta:{model:s,operation:String(n)}});let l=r??{},d=g(n),f=e.extensionChain,p=ee(f,`request`,s,n),m=(f?.observe.length??0)>0,v=re(f,s,n).length>0,y=l,prepareInput;if(p===void 0&&!v&&!m){let e=l;y=i?applyClientOmit(c,n,e,i):e,assertNonEmptyUniqueWhere(n,y)}else prepareInput=(e,t)=>{let r=(p===void 0?e:applyRequestTransforms(s,n,e,p,f?.controls===void 0?void 0:{names:f.controls.names,admitted:t}))??{},a=i?applyClientOmit(c,n,r,i):r;return assertNonEmptyUniqueWhere(n,a),a};let b=o===void 0||!d?void 0:(e,t)=>h().prepareMutationCacheWriteOutcome(o.driver,s,n,h().readMutationCacheOptions(t),e,o.scope),x=a?e.prepare(c,n,y,{skipSpan:!0},prepareInput):e.prepare(c,n,y,void 0,prepareInput,b);return a===void 0?x:this.#c(e,s,n,x,a)}#o(e,t,n,r){let i=h(),a=i.createCacheExecutionOptions(r,t.waitUntil,k(e.driver)),o=Object.freeze({capability:t,options:a});return createModelProxy(this.#e,({modelName:t,operation:r,args:a})=>{try{return i.validateCacheableOperation(r),this.#a(e,t,r,a,n,o)}catch(e){return Promise.reject(e)}})}#s(e){let t=ne(e);if(t===void 0)return;let n=this.#r??=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}#c(e,t,n,r,i){return ve(r,async(a,o)=>{if(o!==void 0||e.transactionWriteOutcomes!==void 0||(e.extensionChain?.statement.length??0)>0)return a();let s=be(r);await s.checkStorage(e.driver);let c=h(),l=c.cacheKeyOf(s.args,s.controls,e.extensionChain?.rows);return l===void 0?a():c.executeCachedResultOperation(i.capability.driver,t,n,l,()=>a(),{...i.options,executionContext:s.executionContext},s.codec,i.capability.scope)})}#l(e,t,n,r,i,a){let o;return new Proxy(this.#i(e,i,t),{get:(t,i)=>{if(typeof i==`string`){if(!i.startsWith(`$`))return Reflect.get(t,i);if(r&&Object.hasOwn(r,i))return r[i]}if(i===`$schema`)return this.#e;if(i===`$transaction`)return n;if(isRawMethodName(i))return o??=createRawSurface({engine:e}),o[i];let s=a?.(i);return s===void 0&&typeof i==`string`&&Object.hasOwn(this.#e,i)?Reflect.get(t,i):s}})}#u(e,t,n){let transaction=(n,r)=>this.#d(e,t,n,r),r=e.extensionChain,i=r&&bindExtensionMethods(r,(n,r)=>this.#l(e,t,transaction,n,r));return this.#l(e,t,transaction,i?.client,i?.models,n)}#d(e,t,n,r){try{let i=Array.isArray(n);e.driver.assertTransactionOptionsSupported(r,i?`batch`:`callback`);let a=e.extensionChain,o=K(`$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 pe:void 0,body=async r=>n(this.#u(e.bind(r,a,s),t));return s?runOutcomeTransaction(e.driver,s,e.transactionWriteOutcomes,r,o,body):e.driver.withTransaction(body,r,o)}catch(e){return Promise.reject(e)}}#f(e){let t=e.extensionChain,n=t===void 0?void 0:this.#s(t),disconnect=()=>e.driver._disconnect(K(`$connection`,`$disconnect`,t));return this.#u(e,n,r=>{if(r===`$driver`)return e.driver;if(r===`$extends`)return n=>{let r=te(t,n,this.#e);return r.hasCache&&b(r,e.driver),this.#f(e.bind(e.driver,r))};if(r===`$connect`)return()=>e.driver._connect(K(`$connection`,`$connect`,t));if(r===`$disconnect`||r===x)return disconnect;if(r!==`$withCache`&&r!==`$invalidate`)return;let i=_(t);if(i!==void 0)return r===`$withCache`?t=>this.#o(e,i,n,t):async(...e)=>{await h().invalidateManualCache(i.driver,e,K(`$cache`,`$invalidate`,t),i.scope)}})}static create(e){if(!e.driver)throw new u(`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 u("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||Ct(e.schema,t),n?.fittingDialects.has(e.driver.dialect)||assertDecimalDomainsFitProvider(e.schema,e.driver.dialect),assertGeoPointFieldsFitAdapter(e.schema,e.driver.adapter);let r=n??prepareSchema(e.schema,t);return r.fittingDialects.add(e.driver.dialect),new VibORM(e,r)});return t.#f(t.#t)}};const bn=new WeakMap;function reusablePreparation(e,t){let n=bn.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?Ue(e):Ve(e),r=Re(e,n),i={entries:Object.entries(e),relations:n,schemaRegistry:r,fittingDialects:new Set,validated:!t};return bn.set(e,i),i}function assertConstructed(e){try{return e()}catch(e){if(M(e))throw e;let t=e instanceof Error?e:void 0;throw new u(t?.message??`Failed to create the VibORM client`,t?{cause:t}:void 0)}}const createClient=e=>yn.create(e),createClientFromDriverConfig=(e,t)=>{let{schema:n,skipSchemaValidation:r}=e,i={schema:n,driver:t,...r===void 0?{}:{skipSchemaValidation:r}};return yn.create(i)};export{registerPositionalResultDriver as a,borrowPositionalResult as i,createClientFromDriverConfig as n,assertPositionalRows as r,createClient as t};
|
|
2
|
-
//# sourceMappingURL=client-tjSMPjeZ.mjs.map
|