@inixiative/json-rules 3.19.0 → 3.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import vt from'dayjs';import jR from'dayjs/plugin/isoWeek.js';import VR from'dayjs/plugin/quarterOfYear.js';import IR from'dayjs/plugin/timezone.js';import qR from'dayjs/plugin/utc.js';import tO from'dayjs/plugin/isSameOrAfter.js';import rO from'dayjs/plugin/isSameOrBefore.js';import {distance}from'fastest-levenshtein';import {RE2JS}from're2js';var wa=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var lg=typeof global=="object"&&global&&global.Object===Object&&global,fi=lg;var pg=typeof self=="object"&&self&&self.Object===Object&&self,dg=fi||pg||Function("return this")(),ae=dg;var fg=ae.Symbol,ve=fg;var Gl=Object.prototype,ug=Gl.hasOwnProperty,cg=Gl.toString,ho=ve?ve.toStringTag:void 0;function mg(e){var t=ug.call(e,ho),r=e[ho];try{e[ho]=void 0;var n=!0;}catch{}var o=cg.call(e);return n&&(t?e[ho]=r:delete e[ho]),o}var zl=mg;var gg=Object.prototype,yg=gg.toString;function hg(e){return yg.call(e)}var Hl=hg;var wg="[object Null]",Sg="[object Undefined]",Jl=ve?ve.toStringTag:void 0;function bg(e){return e==null?e===void 0?Sg:wg:Jl&&Jl in Object(e)?zl(e):Hl(e)}var Fe=bg;function Rg(e){return e!=null&&typeof e=="object"}var pe=Rg;var Og="[object Symbol]";function xg(e){return typeof e=="symbol"||pe(e)&&Fe(e)==Og}var sn=xg;function Eg(e,t){for(var r=-1,n=e==null?0:e.length,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}var Ql=Eg;var $g=Array.isArray,G=$g;var Zl=ve?ve.prototype:void 0,Yl=Zl?Zl.toString:void 0;function Xl(e){if(typeof e=="string")return e;if(G(e))return Ql(e,Xl)+"";if(sn(e))return Yl?Yl.call(e):"";var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var ep=Xl;function Ng(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Q=Ng;function Ag(e){return e}var an=Ag;var Pg="[object AsyncFunction]",Tg="[object Function]",kg="[object GeneratorFunction]",Cg="[object Proxy]";function Lg(e){if(!Q(e))return false;var t=Fe(e);return t==Tg||t==kg||t==Pg||t==Cg}var ln=Lg;var Mg=ae["__core-js_shared__"],ui=Mg;var tp=(function(){var e=/[^.]+$/.exec(ui&&ui.keys&&ui.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function _g(e){return !!tp&&tp in e}var rp=_g;var Dg=Function.prototype,Fg=Dg.toString;function jg(e){if(e!=null){try{return Fg.call(e)}catch{}try{return e+""}catch{}}return ""}var Dt=jg;var Vg=/[\\^$.*+?()[\]{}|]/g,Ig=/^\[object .+?Constructor\]$/,qg=Function.prototype,Bg=Object.prototype,Wg=qg.toString,Ug=Bg.hasOwnProperty,Kg=RegExp("^"+Wg.call(Ug).replace(Vg,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Gg(e){if(!Q(e)||rp(e))return false;var t=ln(e)?Kg:Ig;return t.test(Dt(e))}var np=Gg;function zg(e,t){return e?.[t]}var op=zg;function Hg(e,t){var r=op(e,t);return np(r)?r:void 0}var Ce=Hg;var Jg=Ce(ae,"WeakMap"),ci=Jg;var ip=Object.create,Qg=(function(){function e(){}return function(t){if(!Q(t))return {};if(ip)return ip(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})(),sp=Qg;function Zg(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var ap=Zg;function Yg(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}var mi=Yg;var Xg=800,ey=16,ty=Date.now;function ry(e){var t=0,r=0;return function(){var n=ty(),o=ey-(n-r);if(r=n,o>0){if(++t>=Xg)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var lp=ry;function ny(e){return function(){return e}}var pp=ny;var oy=(function(){try{var e=Ce(Object,"defineProperty");return e({},"",{}),e}catch{}})(),pn=oy;var iy=pn?function(e,t){return pn(e,"toString",{configurable:true,enumerable:false,value:pp(t),writable:true})}:an,dp=iy;var sy=lp(dp),fp=sy;function ay(e,t){for(var r=-1,n=e==null?0:e.length;++r<n&&t(e[r],r,e)!==false;);return e}var up=ay;var ly=9007199254740991,py=/^(?:0|[1-9]\d*)$/;function dy(e,t){var r=typeof e;return t=t??ly,!!t&&(r=="number"||r!="symbol"&&py.test(e))&&e>-1&&e%1==0&&e<t}var tr=dy;function fy(e,t,r){t=="__proto__"&&pn?pn(e,t,{configurable:true,enumerable:true,value:r,writable:true}):e[t]=r;}var dn=fy;function uy(e,t){return e===t||e!==e&&t!==t}var ct=uy;var cy=Object.prototype,my=cy.hasOwnProperty;function gy(e,t,r){var n=e[t];(!(my.call(e,t)&&ct(n,r))||r===void 0&&!(t in e))&&dn(e,t,r);}var fn=gy;function yy(e,t,r,n){var o=!r;r||(r={});for(var i=-1,s=t.length;++i<s;){var a=t[i],l=n?n(r[a],e[a],a,r,e):void 0;l===void 0&&(l=e[a]),o?dn(r,a,l):fn(r,a,l);}return r}var mt=yy;var cp=Math.max;function hy(e,t,r){return t=cp(t===void 0?e.length-1:t,0),function(){for(var n=arguments,o=-1,i=cp(n.length-t,0),s=Array(i);++o<i;)s[o]=n[t+o];o=-1;for(var a=Array(t+1);++o<t;)a[o]=n[o];return a[t]=r(s),ap(e,this,a)}}var mp=hy;function wy(e,t){return fp(mp(e,t,an),e+"")}var gp=wy;var Sy=9007199254740991;function by(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Sy}var un=by;function Ry(e){return e!=null&&un(e.length)&&!ln(e)}var gt=Ry;function Oy(e,t,r){if(!Q(r))return false;var n=typeof t;return (n=="number"?gt(r)&&tr(t,r.length):n=="string"&&t in r)?ct(r[t],e):false}var gi=Oy;function xy(e){return gp(function(t,r){var n=-1,o=r.length,i=o>1?r[o-1]:void 0,s=o>2?r[2]:void 0;for(i=e.length>3&&typeof i=="function"?(o--,i):void 0,s&&gi(r[0],r[1],s)&&(i=o<3?void 0:i,o=1),t=Object(t);++n<o;){var a=r[n];a&&e(t,a,n,i);}return t})}var yp=xy;var Ey=Object.prototype;function $y(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||Ey;return e===r}var cn=$y;function vy(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var hp=vy;var Ny="[object Arguments]";function Ay(e){return pe(e)&&Fe(e)==Ny}var Sa=Ay;var wp=Object.prototype,Py=wp.hasOwnProperty,Ty=wp.propertyIsEnumerable,ky=Sa((function(){return arguments})())?Sa:function(e){return pe(e)&&Py.call(e,"callee")&&!Ty.call(e,"callee")},Cr=ky;function Cy(){return false}var Sp=Cy;var Op=typeof exports=="object"&&exports&&!exports.nodeType&&exports,bp=Op&&typeof module=="object"&&module&&!module.nodeType&&module,Ly=bp&&bp.exports===Op,Rp=Ly?ae.Buffer:void 0,My=Rp?Rp.isBuffer:void 0,_y=My||Sp,Ft=_y;var Dy="[object Arguments]",Fy="[object Array]",jy="[object Boolean]",Vy="[object Date]",Iy="[object Error]",qy="[object Function]",By="[object Map]",Wy="[object Number]",Uy="[object Object]",Ky="[object RegExp]",Gy="[object Set]",zy="[object String]",Hy="[object WeakMap]",Jy="[object ArrayBuffer]",Qy="[object DataView]",Zy="[object Float32Array]",Yy="[object Float64Array]",Xy="[object Int8Array]",eh="[object Int16Array]",th="[object Int32Array]",rh="[object Uint8Array]",nh="[object Uint8ClampedArray]",oh="[object Uint16Array]",ih="[object Uint32Array]",J={};J[Zy]=J[Yy]=J[Xy]=J[eh]=J[th]=J[rh]=J[nh]=J[oh]=J[ih]=true;J[Dy]=J[Fy]=J[Jy]=J[jy]=J[Qy]=J[Vy]=J[Iy]=J[qy]=J[By]=J[Wy]=J[Uy]=J[Ky]=J[Gy]=J[zy]=J[Hy]=false;function sh(e){return pe(e)&&un(e.length)&&!!J[Fe(e)]}var xp=sh;function ah(e){return function(t){return e(t)}}var mn=ah;var Ep=typeof exports=="object"&&exports&&!exports.nodeType&&exports,wo=Ep&&typeof module=="object"&&module&&!module.nodeType&&module,lh=wo&&wo.exports===Ep,ba=lh&&fi.process,ph=(function(){try{var e=wo&&wo.require&&wo.require("util").types;return e||ba&&ba.binding&&ba.binding("util")}catch{}})(),jt=ph;var $p=jt&&jt.isTypedArray,dh=$p?mn($p):xp,gn=dh;var fh=Object.prototype,uh=fh.hasOwnProperty;function ch(e,t){var r=G(e),n=!r&&Cr(e),o=!r&&!n&&Ft(e),i=!r&&!n&&!o&&gn(e),s=r||n||o||i,a=s?hp(e.length,String):[],l=a.length;for(var d in e)(t||uh.call(e,d))&&!(s&&(d=="length"||o&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||tr(d,l)))&&a.push(d);return a}var yi=ch;function mh(e,t){return function(r){return e(t(r))}}var hi=mh;var gh=hi(Object.keys,Object),vp=gh;var yh=Object.prototype,hh=yh.hasOwnProperty;function wh(e){if(!cn(e))return vp(e);var t=[];for(var r in Object(e))hh.call(e,r)&&r!="constructor"&&t.push(r);return t}var Np=wh;function Sh(e){return gt(e)?yi(e):Np(e)}var yt=Sh;function bh(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}var Ap=bh;var Rh=Object.prototype,Oh=Rh.hasOwnProperty;function xh(e){if(!Q(e))return Ap(e);var t=cn(e),r=[];for(var n in e)n=="constructor"&&(t||!Oh.call(e,n))||r.push(n);return r}var Pp=xh;function Eh(e){return gt(e)?yi(e,true):Pp(e)}var ht=Eh;var $h=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,vh=/^\w*$/;function Nh(e,t){if(G(e))return false;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||sn(e)?true:vh.test(e)||!$h.test(e)||t!=null&&e in Object(t)}var yn=Nh;var Ah=Ce(Object,"create"),Vt=Ah;function Ph(){this.__data__=Vt?Vt(null):{},this.size=0;}var Tp=Ph;function Th(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var kp=Th;var kh="__lodash_hash_undefined__",Ch=Object.prototype,Lh=Ch.hasOwnProperty;function Mh(e){var t=this.__data__;if(Vt){var r=t[e];return r===kh?void 0:r}return Lh.call(t,e)?t[e]:void 0}var Cp=Mh;var _h=Object.prototype,Dh=_h.hasOwnProperty;function Fh(e){var t=this.__data__;return Vt?t[e]!==void 0:Dh.call(t,e)}var Lp=Fh;var jh="__lodash_hash_undefined__";function Vh(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Vt&&t===void 0?jh:t,this}var Mp=Vh;function hn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}hn.prototype.clear=Tp;hn.prototype.delete=kp;hn.prototype.get=Cp;hn.prototype.has=Lp;hn.prototype.set=Mp;var Ra=hn;function Ih(){this.__data__=[],this.size=0;}var _p=Ih;function qh(e,t){for(var r=e.length;r--;)if(ct(e[r][0],t))return r;return -1}var rr=qh;var Bh=Array.prototype,Wh=Bh.splice;function Uh(e){var t=this.__data__,r=rr(t,e);if(r<0)return false;var n=t.length-1;return r==n?t.pop():Wh.call(t,r,1),--this.size,true}var Dp=Uh;function Kh(e){var t=this.__data__,r=rr(t,e);return r<0?void 0:t[r][1]}var Fp=Kh;function Gh(e){return rr(this.__data__,e)>-1}var jp=Gh;function zh(e,t){var r=this.__data__,n=rr(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var Vp=zh;function wn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}wn.prototype.clear=_p;wn.prototype.delete=Dp;wn.prototype.get=Fp;wn.prototype.has=jp;wn.prototype.set=Vp;var nr=wn;var Hh=Ce(ae,"Map"),or=Hh;function Jh(){this.size=0,this.__data__={hash:new Ra,map:new(or||nr),string:new Ra};}var Ip=Jh;function Qh(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var qp=Qh;function Zh(e,t){var r=e.__data__;return qp(t)?r[typeof t=="string"?"string":"hash"]:r.map}var ir=Zh;function Yh(e){var t=ir(this,e).delete(e);return this.size-=t?1:0,t}var Bp=Yh;function Xh(e){return ir(this,e).get(e)}var Wp=Xh;function ew(e){return ir(this,e).has(e)}var Up=ew;function tw(e,t){var r=ir(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var Kp=tw;function Sn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}Sn.prototype.clear=Ip;Sn.prototype.delete=Bp;Sn.prototype.get=Wp;Sn.prototype.has=Up;Sn.prototype.set=Kp;var Lr=Sn;var rw="Expected a function";function Oa(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(rw);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],i=r.cache;if(i.has(o))return i.get(o);var s=e.apply(this,n);return r.cache=i.set(o,s)||i,s};return r.cache=new(Oa.Cache||Lr),r}Oa.Cache=Lr;var Gp=Oa;var nw=500;function ow(e){var t=Gp(e,function(n){return r.size===nw&&r.clear(),n}),r=t.cache;return t}var zp=ow;var iw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,sw=/\\(\\)?/g,aw=zp(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(iw,function(r,n,o,i){t.push(o?i.replace(sw,"$1"):n||r);}),t}),Hp=aw;function lw(e){return e==null?"":ep(e)}var Jp=lw;function pw(e,t){return G(e)?e:yn(e,t)?[e]:Hp(Jp(e))}var bn=pw;function fw(e){if(typeof e=="string"||sn(e))return e;var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var wt=fw;function uw(e,t){t=bn(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[wt(t[r++])];return r&&r==n?e:void 0}var wi=uw;function cw(e,t,r){var n=e==null?void 0:wi(e,t);return n===void 0?r:n}var Qp=cw;function mw(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}var Si=mw;var gw=hi(Object.getPrototypeOf,Object),Rn=gw;var yw="[object Object]",hw=Function.prototype,ww=Object.prototype,Zp=hw.toString,Sw=ww.hasOwnProperty,bw=Zp.call(Object);function Rw(e){if(!pe(e)||Fe(e)!=yw)return false;var t=Rn(e);if(t===null)return true;var r=Sw.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Zp.call(r)==bw}var re=Rw;function Ow(){if(!arguments.length)return [];var e=arguments[0];return G(e)?e:[e]}var bi=Ow;function xw(){this.__data__=new nr,this.size=0;}var Yp=xw;function Ew(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var Xp=Ew;function $w(e){return this.__data__.get(e)}var ed=$w;function vw(e){return this.__data__.has(e)}var td=vw;var Nw=200;function Aw(e,t){var r=this.__data__;if(r instanceof nr){var n=r.__data__;if(!or||n.length<Nw-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Lr(n);}return r.set(e,t),this.size=r.size,this}var rd=Aw;function On(e){var t=this.__data__=new nr(e);this.size=t.size;}On.prototype.clear=Yp;On.prototype.delete=Xp;On.prototype.get=ed;On.prototype.has=td;On.prototype.set=rd;var St=On;function Pw(e,t){return e&&mt(t,yt(t),e)}var nd=Pw;function Tw(e,t){return e&&mt(t,ht(t),e)}var od=Tw;var ld=typeof exports=="object"&&exports&&!exports.nodeType&&exports,id=ld&&typeof module=="object"&&module&&!module.nodeType&&module,kw=id&&id.exports===ld,sd=kw?ae.Buffer:void 0,ad=sd?sd.allocUnsafe:void 0;function Cw(e,t){if(t)return e.slice();var r=e.length,n=ad?ad(r):new e.constructor(r);return e.copy(n),n}var Ri=Cw;function Lw(e,t){for(var r=-1,n=e==null?0:e.length,o=0,i=[];++r<n;){var s=e[r];t(s,r,e)&&(i[o++]=s);}return i}var pd=Lw;function Mw(){return []}var Oi=Mw;var _w=Object.prototype,Dw=_w.propertyIsEnumerable,dd=Object.getOwnPropertySymbols,Fw=dd?function(e){return e==null?[]:(e=Object(e),pd(dd(e),function(t){return Dw.call(e,t)}))}:Oi,xn=Fw;function jw(e,t){return mt(e,xn(e),t)}var fd=jw;var Vw=Object.getOwnPropertySymbols,Iw=Vw?function(e){for(var t=[];e;)Si(t,xn(e)),e=Rn(e);return t}:Oi,xi=Iw;function qw(e,t){return mt(e,xi(e),t)}var ud=qw;function Bw(e,t,r){var n=t(e);return G(e)?n:Si(n,r(e))}var Ei=Bw;function Ww(e){return Ei(e,yt,xn)}var So=Ww;function Uw(e){return Ei(e,ht,xi)}var cd=Uw;var Kw=Ce(ae,"DataView"),$i=Kw;var Gw=Ce(ae,"Promise"),vi=Gw;var zw=Ce(ae,"Set"),Ni=zw;var md="[object Map]",Hw="[object Object]",gd="[object Promise]",yd="[object Set]",hd="[object WeakMap]",wd="[object DataView]",Jw=Dt($i),Qw=Dt(or),Zw=Dt(vi),Yw=Dt(Ni),Xw=Dt(ci),Mr=Fe;($i&&Mr(new $i(new ArrayBuffer(1)))!=wd||or&&Mr(new or)!=md||vi&&Mr(vi.resolve())!=gd||Ni&&Mr(new Ni)!=yd||ci&&Mr(new ci)!=hd)&&(Mr=function(e){var t=Fe(e),r=t==Hw?e.constructor:void 0,n=r?Dt(r):"";if(n)switch(n){case Jw:return wd;case Qw:return md;case Zw:return gd;case Yw:return yd;case Xw:return hd}return t});var It=Mr;var eS=Object.prototype,tS=eS.hasOwnProperty;function rS(e){var t=e.length,r=new e.constructor(t);return t&&typeof e[0]=="string"&&tS.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var Sd=rS;var nS=ae.Uint8Array,En=nS;function oS(e){var t=new e.constructor(e.byteLength);return new En(t).set(new En(e)),t}var $n=oS;function iS(e,t){var r=t?$n(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var bd=iS;var sS=/\w*$/;function aS(e){var t=new e.constructor(e.source,sS.exec(e));return t.lastIndex=e.lastIndex,t}var Rd=aS;var Od=ve?ve.prototype:void 0,xd=Od?Od.valueOf:void 0;function lS(e){return xd?Object(xd.call(e)):{}}var Ed=lS;function pS(e,t){var r=t?$n(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var Ai=pS;var dS="[object Boolean]",fS="[object Date]",uS="[object Map]",cS="[object Number]",mS="[object RegExp]",gS="[object Set]",yS="[object String]",hS="[object Symbol]",wS="[object ArrayBuffer]",SS="[object DataView]",bS="[object Float32Array]",RS="[object Float64Array]",OS="[object Int8Array]",xS="[object Int16Array]",ES="[object Int32Array]",$S="[object Uint8Array]",vS="[object Uint8ClampedArray]",NS="[object Uint16Array]",AS="[object Uint32Array]";function PS(e,t,r){var n=e.constructor;switch(t){case wS:return $n(e);case dS:case fS:return new n(+e);case SS:return bd(e,r);case bS:case RS:case OS:case xS:case ES:case $S:case vS:case NS:case AS:return Ai(e,r);case uS:return new n;case cS:case yS:return new n(e);case mS:return Rd(e);case gS:return new n;case hS:return Ed(e)}}var $d=PS;function TS(e){return typeof e.constructor=="function"&&!cn(e)?sp(Rn(e)):{}}var Pi=TS;var kS="[object Map]";function CS(e){return pe(e)&&It(e)==kS}var vd=CS;var Nd=jt&&jt.isMap,LS=Nd?mn(Nd):vd,Ad=LS;var MS="[object Set]";function _S(e){return pe(e)&&It(e)==MS}var Pd=_S;var Td=jt&&jt.isSet,DS=Td?mn(Td):Pd,kd=DS;var FS=1,jS=2,VS=4,Cd="[object Arguments]",IS="[object Array]",qS="[object Boolean]",BS="[object Date]",WS="[object Error]",Ld="[object Function]",US="[object GeneratorFunction]",KS="[object Map]",GS="[object Number]",Md="[object Object]",zS="[object RegExp]",HS="[object Set]",JS="[object String]",QS="[object Symbol]",ZS="[object WeakMap]",YS="[object ArrayBuffer]",XS="[object DataView]",eb="[object Float32Array]",tb="[object Float64Array]",rb="[object Int8Array]",nb="[object Int16Array]",ob="[object Int32Array]",ib="[object Uint8Array]",sb="[object Uint8ClampedArray]",ab="[object Uint16Array]",lb="[object Uint32Array]",z={};z[Cd]=z[IS]=z[YS]=z[XS]=z[qS]=z[BS]=z[eb]=z[tb]=z[rb]=z[nb]=z[ob]=z[KS]=z[GS]=z[Md]=z[zS]=z[HS]=z[JS]=z[QS]=z[ib]=z[sb]=z[ab]=z[lb]=true;z[WS]=z[Ld]=z[ZS]=false;function Ti(e,t,r,n,o,i){var s,a=t&FS,l=t&jS,d=t&VS;if(r&&(s=o?r(e,n,o,i):r(e)),s!==void 0)return s;if(!Q(e))return e;var p=G(e);if(p){if(s=Sd(e),!a)return mi(e,s)}else {var f=It(e),u=f==Ld||f==US;if(Ft(e))return Ri(e,a);if(f==Md||f==Cd||u&&!o){if(s=l||u?{}:Pi(e),!a)return l?ud(e,od(s,e)):fd(e,nd(s,e))}else {if(!z[f])return o?e:{};s=$d(e,f,a);}}i||(i=new St);var m=i.get(e);if(m)return m;i.set(e,s),kd(e)?e.forEach(function(g){s.add(Ti(g,t,r,g,e,i));}):Ad(e)&&e.forEach(function(g,w){s.set(w,Ti(g,t,r,w,e,i));});var y=d?l?cd:So:l?ht:yt,c=p?void 0:y(e);return up(c||e,function(g,w){c&&(w=g,g=e[w]),fn(s,w,Ti(g,t,r,w,e,i));}),s}var ki=Ti;var pb=1,db=4;function fb(e){return ki(e,pb|db)}var Ci=fb;var ub=1,cb=4;function mb(e,t){return t=typeof t=="function"?t:void 0,ki(e,ub|cb,t)}var xa=mb;var gb="__lodash_hash_undefined__";function yb(e){return this.__data__.set(e,gb),this}var _d=yb;function hb(e){return this.__data__.has(e)}var Dd=hb;function Li(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Lr;++t<r;)this.add(e[t]);}Li.prototype.add=Li.prototype.push=_d;Li.prototype.has=Dd;var Fd=Li;function wb(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return true;return false}var Mi=wb;function Sb(e,t){return e.has(t)}var jd=Sb;var bb=1,Rb=2;function Ob(e,t,r,n,o,i){var s=r&bb,a=e.length,l=t.length;if(a!=l&&!(s&&l>a))return false;var d=i.get(e),p=i.get(t);if(d&&p)return d==t&&p==e;var f=-1,u=true,m=r&Rb?new Fd:void 0;for(i.set(e,t),i.set(t,e);++f<a;){var y=e[f],c=t[f];if(n)var g=s?n(c,y,f,t,e,i):n(y,c,f,e,t,i);if(g!==void 0){if(g)continue;u=false;break}if(m){if(!Mi(t,function(w,R){if(!jd(m,R)&&(y===w||o(y,w,r,n,i)))return m.push(R)})){u=false;break}}else if(!(y===c||o(y,c,r,n,i))){u=false;break}}return i.delete(e),i.delete(t),u}var _i=Ob;function xb(e){var t=-1,r=Array(e.size);return e.forEach(function(n,o){r[++t]=[o,n];}),r}var Vd=xb;function Eb(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n;}),r}var Id=Eb;var $b=1,vb=2,Nb="[object Boolean]",Ab="[object Date]",Pb="[object Error]",Tb="[object Map]",kb="[object Number]",Cb="[object RegExp]",Lb="[object Set]",Mb="[object String]",_b="[object Symbol]",Db="[object ArrayBuffer]",Fb="[object DataView]",qd=ve?ve.prototype:void 0,Ea=qd?qd.valueOf:void 0;function jb(e,t,r,n,o,i,s){switch(r){case Fb:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return false;e=e.buffer,t=t.buffer;case Db:return !(e.byteLength!=t.byteLength||!i(new En(e),new En(t)));case Nb:case Ab:case kb:return ct(+e,+t);case Pb:return e.name==t.name&&e.message==t.message;case Cb:case Mb:return e==t+"";case Tb:var a=Vd;case Lb:var l=n&$b;if(a||(a=Id),e.size!=t.size&&!l)return false;var d=s.get(e);if(d)return d==t;n|=vb,s.set(e,t);var p=_i(a(e),a(t),n,o,i,s);return s.delete(e),p;case _b:if(Ea)return Ea.call(e)==Ea.call(t)}return false}var Bd=jb;var Vb=1,Ib=Object.prototype,qb=Ib.hasOwnProperty;function Bb(e,t,r,n,o,i){var s=r&Vb,a=So(e),l=a.length,d=So(t),p=d.length;if(l!=p&&!s)return false;for(var f=l;f--;){var u=a[f];if(!(s?u in t:qb.call(t,u)))return false}var m=i.get(e),y=i.get(t);if(m&&y)return m==t&&y==e;var c=true;i.set(e,t),i.set(t,e);for(var g=s;++f<l;){u=a[f];var w=e[u],R=t[u];if(n)var S=s?n(R,w,u,t,e,i):n(w,R,u,e,t,i);if(!(S===void 0?w===R||o(w,R,r,n,i):S)){c=false;break}g||(g=u=="constructor");}if(c&&!g){var b=e.constructor,v=t.constructor;b!=v&&"constructor"in e&&"constructor"in t&&!(typeof b=="function"&&b instanceof b&&typeof v=="function"&&v instanceof v)&&(c=false);}return i.delete(e),i.delete(t),c}var Wd=Bb;var Wb=1,Ud="[object Arguments]",Kd="[object Array]",Di="[object Object]",Ub=Object.prototype,Gd=Ub.hasOwnProperty;function Kb(e,t,r,n,o,i){var s=G(e),a=G(t),l=s?Kd:It(e),d=a?Kd:It(t);l=l==Ud?Di:l,d=d==Ud?Di:d;var p=l==Di,f=d==Di,u=l==d;if(u&&Ft(e)){if(!Ft(t))return false;s=true,p=false;}if(u&&!p)return i||(i=new St),s||gn(e)?_i(e,t,r,n,o,i):Bd(e,t,l,r,n,o,i);if(!(r&Wb)){var m=p&&Gd.call(e,"__wrapped__"),y=f&&Gd.call(t,"__wrapped__");if(m||y){var c=m?e.value():e,g=y?t.value():t;return i||(i=new St),o(c,g,r,n,i)}}return u?(i||(i=new St),Wd(e,t,r,n,o,i)):false}var zd=Kb;function Hd(e,t,r,n,o){return e===t?true:e==null||t==null||!pe(e)&&!pe(t)?e!==e&&t!==t:zd(e,t,r,n,Hd,o)}var vn=Hd;var Gb=1,zb=2;function Hb(e,t,r,n){var o=r.length,i=o,s=!n;if(e==null)return !i;for(e=Object(e);o--;){var a=r[o];if(s&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return false}for(;++o<i;){a=r[o];var l=a[0],d=e[l],p=a[1];if(s&&a[2]){if(d===void 0&&!(l in e))return false}else {var f=new St;if(n)var u=n(d,p,l,e,t,f);if(!(u===void 0?vn(p,d,Gb|zb,n,f):u))return false}}return true}var Jd=Hb;function Jb(e){return e===e&&!Q(e)}var Fi=Jb;function Qb(e){for(var t=yt(e),r=t.length;r--;){var n=t[r],o=e[n];t[r]=[n,o,Fi(o)];}return t}var Qd=Qb;function Zb(e,t){return function(r){return r==null?false:r[e]===t&&(t!==void 0||e in Object(r))}}var ji=Zb;function Yb(e){var t=Qd(e);return t.length==1&&t[0][2]?ji(t[0][0],t[0][1]):function(r){return r===e||Jd(r,e,t)}}var Zd=Yb;function Xb(e,t){return e!=null&&t in Object(e)}var Yd=Xb;function eR(e,t,r){t=bn(t,e);for(var n=-1,o=t.length,i=false;++n<o;){var s=wt(t[n]);if(!(i=e!=null&&r(e,s)))break;e=e[s];}return i||++n!=o?i:(o=e==null?0:e.length,!!o&&un(o)&&tr(s,o)&&(G(e)||Cr(e)))}var Xd=eR;function tR(e,t){return e!=null&&Xd(e,t,Yd)}var ef=tR;var rR=1,nR=2;function oR(e,t){return yn(e)&&Fi(t)?ji(wt(e),t):function(r){var n=Qp(r,e);return n===void 0&&n===t?ef(r,e):vn(t,n,rR|nR)}}var tf=oR;function iR(e){return function(t){return t?.[e]}}var rf=iR;function sR(e){return function(t){return wi(t,e)}}var nf=sR;function aR(e){return yn(e)?rf(wt(e)):nf(e)}var of=aR;function lR(e){return typeof e=="function"?e:e==null?an:typeof e=="object"?G(e)?tf(e[0],e[1]):Zd(e):of(e)}var sf=lR;function pR(e){return function(t,r,n){for(var o=-1,i=Object(t),s=n(t),a=s.length;a--;){var l=s[e?a:++o];if(r(i[l],l,i)===false)break}return t}}var af=pR;var dR=af(),Vi=dR;function fR(e,t){return e&&Vi(e,t,yt)}var lf=fR;function uR(e,t){return function(r,n){if(r==null)return r;if(!gt(r))return e(r,n);for(var o=r.length,i=t?o:-1,s=Object(r);(t?i--:++i<o)&&n(s[i],i,s)!==false;);return r}}var pf=uR;var cR=pf(lf),df=cR;function mR(e,t,r){(r!==void 0&&!ct(e[t],r)||r===void 0&&!(t in e))&&dn(e,t,r);}var bo=mR;function gR(e){return pe(e)&&gt(e)}var ff=gR;function yR(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}var Ro=yR;function hR(e){return mt(e,ht(e))}var uf=hR;function wR(e,t,r,n,o,i,s){var a=Ro(e,r),l=Ro(t,r),d=s.get(l);if(d){bo(e,r,d);return}var p=i?i(a,l,r+"",e,t,s):void 0,f=p===void 0;if(f){var u=G(l),m=!u&&Ft(l),y=!u&&!m&&gn(l);p=l,u||m||y?G(a)?p=a:ff(a)?p=mi(a):m?(f=false,p=Ri(l,true)):y?(f=false,p=Ai(l,true)):p=[]:re(l)||Cr(l)?(p=a,Cr(a)?p=uf(a):(!Q(a)||ln(a))&&(p=Pi(l))):f=false;}f&&(s.set(l,p),o(p,l,n,i,s),s.delete(l)),bo(e,r,p);}var cf=wR;function mf(e,t,r,n,o){e!==t&&Vi(t,function(i,s){if(o||(o=new St),Q(i))cf(e,t,s,r,mf,n,o);else {var a=n?n(Ro(e,s),i,s+"",e,t,o):void 0;a===void 0&&(a=i),bo(e,s,a);}},ht);}var gf=mf;function SR(e,t){return vn(e,t)}var qt=SR;var bR=yp(function(e,t,r){gf(e,t,r);}),Ii=bR;function RR(e,t,r,n){if(!Q(e))return e;t=bn(t,e);for(var o=-1,i=t.length,s=i-1,a=e;a!=null&&++o<i;){var l=wt(t[o]),d=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(o!=s){var p=a[l];d=n?n(p,l,a):void 0,d===void 0&&(d=Q(p)?p:tr(t[o+1])?[]:{});}fn(a,l,d),a=a[l];}return e}var yf=RR;function OR(e,t,r){return e==null?e:yf(e,t,r)}var Oo=OR;function xR(e,t){var r;return df(e,function(n,o,i){return r=t(n,o,i),!r}),!!r}var hf=xR;function ER(e,t,r){var n=G(e)?Mi:hf;return r&&gi(e,t,r)&&(t=void 0),n(e,sf(t))}var $a=ER;var $R=/^(\$+)\.(.*)$/,M=e=>{let t=$R.exec(e);return t?{depth:t[1].length,path:t[2]}:null},va=(e,t,r)=>`Scope ref '${e}' needs depth ${t} but only ${r} ${r===1?"scope is":"scopes are"} in reach`,Ge=(e,t)=>{let r=M(e);return r?r.depth>t.length?{outOfBounds:va(e,r.depth,t.length)}:{scope:t[t.length-r.depth],path:r.path}:{scope:t[t.length-1],path:e}},vR=/\[(\d+)\]|\[(["'])(.*?)\2\]|([^.[\]]+)/g,NR=e=>e===""?[""]:[...e.matchAll(vR)].map(t=>t[1]??t[3]??t[4]),AR=(e,t)=>{if(e==null)return;let r=Object(e);return Object.hasOwn(r,t)?r[t]:void 0},me=(e,t)=>NR(t).reduce(AR,e),sr=(e,t)=>{let r=Ge(e,t);if("outOfBounds"in r)throw new Error(r.outOfBounds);return me(r.scope,r.path)},qi=(e,t)=>M(e)?sr(e,t):me(t[0],e),xo=(e,t)=>`Scope ref '${e}' is not supported by ${t}(); evaluate with check()`,Bi=(e,t)=>{if(!(!("field"in e)||typeof e.field!="string")&&M(e.field))throw new Error(xo(e.field,t))};var An={postgres:"postgres",mysql:"mysql"},Sf=e=>Object.values(An).includes(e),Na={string:{caseInsensitive:false,fuzzy:false},prismaOptions:{datasource:{provider:"postgresql"}},sql:{dialect:An.postgres},clock:{finestUnit:"second"}},PR=new Set(Object.keys(Na)),Nn=e=>xa(e,t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!re(t)?t:void 0),wf=Symbol.for("@inixiative/json-rules/engineGlobals@3"),Eo=()=>{let e=globalThis;return e[wf]??={store:Ci(Na),registry:new Map},e[wf]},TR=e=>{let t={};for(let[r,n]of Object.entries(e))r.includes(".")?Oo(t,r,Nn(n)):t[r]=Ii(t[r]??{},Nn(n));return t},bf=(e,t,r)=>{for(let[n,o]of Object.entries(r)){let i=`${t}.${n}`;me(e,i)===void 0&&Oo(e,i,Nn(o));}},kR=e=>e!=null&&typeof e.then=="function",CR=(e,t)=>{if(!e||e.includes("."))throw new Error(`engine globals namespace "${e}" must be one non-empty segment`);if(PR.has(e))throw new Error(`engine globals namespace "${e}" belongs to json-rules`);let{store:r,registry:n}=Eo(),o=n.get(e);if(o){if(qt(o,t))return;throw new Error(`engine globals namespace "${e}" is registered with other defaults`)}n.set(e,Nn(t)),bf(r,e,t);},Xe={set:(e,t)=>{Oo(Eo().store,e,Nn(t));},get:e=>me(Eo().store,e),reset:()=>{let e=Eo();e.store=Ci(Na);for(let[t,r]of e.registry)bf(e.store,t,r);},with:(e,t)=>{let r=Eo(),n=r.store;r.store=Ii(Nn(n),TR(e));try{let o=t();if(kR(o))throw new Error("engineGlobals.with() callback must be synchronous (it returned a Promise).");return o}finally{r.store=n;}}},LR=new Set(["postgresql","cockroachdb","mongodb"]),Rf=e=>LR.has(e),oe=e=>e??Xe.get("string.caseInsensitive")??false,Wi=e=>{let t=e??Xe.get("string.fuzzy")??false;return t?t===true?{}:t:false};var h={equals:"equals",notEquals:"notEquals",lessThan:"lessThan",lessThanEquals:"lessThanEquals",greaterThan:"greaterThan",greaterThanEquals:"greaterThanEquals",contains:"contains",notContains:"notContains",in:"in",notIn:"notIn",matches:"matches",notMatches:"notMatches",between:"between",notBetween:"notBetween",isEmpty:"isEmpty",notEmpty:"notEmpty",exists:"exists",notExists:"notExists",startsWith:"startsWith",notStartsWith:"notStartsWith",endsWith:"endsWith",notEndsWith:"notEndsWith"},x={all:"all",any:"any",none:"none",atLeast:"atLeast",atMost:"atMost",exactly:"exactly",empty:"empty",notEmpty:"notEmpty"},N={before:"before",after:"after",onOrBefore:"onOrBefore",onOrAfter:"onOrAfter",notBefore:"notBefore",notAfter:"notAfter",within:"within",notWithin:"notWithin",between:"between",notBetween:"notBetween",dayIn:"dayIn",dayNotIn:"dayNotIn"};var P={String:"String",Boolean:"Boolean",Int:"Int",BigInt:"BigInt",Float:"Float",Decimal:"Decimal",DateTime:"DateTime",Json:"Json",Bytes:"Bytes",Enum:"Enum"},X=["Int","Float","Decimal","BigInt"],Pn=["String",...X,"DateTime"],ar=["String"],Ui=["String","Boolean","Int","BigInt","Float","Decimal","DateTime","Enum"],Ki=Object.values(P),Of=Ki,MR={check:"check",toPrisma:"toPrisma",toSql:"toSql"},vo=e=>typeof e=="string"&&Object.hasOwn(P,e),_=["check","toPrisma","toSql"],Tn=["check","toPrisma"],Gi=["check","toSql"],Wt={none:"none",scalar:"scalar",ordered:"ordered",array:"array",string:"string",pattern:"pattern",range:"range",dateValue:"dateValue",dateRange:"dateRange",dateWindow:"dateWindow",dayList:"dayList",count:"count",predicate:"predicate"},kn={[h.equals]:{kinds:Ui,targets:_,valueShape:"scalar"},[h.notEquals]:{negates:h.equals,kinds:Ui,targets:_,valueShape:"scalar"},[h.lessThan]:{kinds:Pn,targets:_,valueShape:"ordered",comparator:"lt"},[h.lessThanEquals]:{kinds:Pn,targets:_,valueShape:"ordered",comparator:"lte"},[h.greaterThan]:{kinds:Pn,targets:_,valueShape:"ordered",comparator:"gt"},[h.greaterThanEquals]:{kinds:Pn,targets:_,valueShape:"ordered",comparator:"gte"},[h.in]:{kinds:Ui,targets:_,valueShape:"array"},[h.notIn]:{negates:h.in,kinds:Ui,targets:_,valueShape:"array"},[h.contains]:{kinds:ar,targets:_,valueShape:"string"},[h.notContains]:{negates:h.contains,kinds:ar,targets:_,valueShape:"string"},[h.startsWith]:{kinds:ar,targets:_,valueShape:"string"},[h.notStartsWith]:{negates:h.startsWith,kinds:ar,targets:_,valueShape:"string"},[h.endsWith]:{kinds:ar,targets:_,valueShape:"string"},[h.notEndsWith]:{negates:h.endsWith,kinds:ar,targets:_,valueShape:"string"},[h.matches]:{kinds:ar,targets:Gi,valueShape:"pattern"},[h.notMatches]:{negates:h.matches,kinds:ar,targets:Gi,valueShape:"pattern"},[h.between]:{kinds:Pn,targets:_,valueShape:"range"},[h.notBetween]:{negates:h.between,kinds:Pn,targets:_,valueShape:"range"},[h.isEmpty]:{kinds:Of,targets:_,valueShape:"none"},[h.notEmpty]:{kinds:Of,targets:_,valueShape:"none"},[h.exists]:{kinds:Ki,targets:_,valueShape:"none"},[h.notExists]:{kinds:Ki,targets:_,valueShape:"none"}},Cn={[N.before]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"lt"},[N.after]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"gt"},[N.onOrBefore]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[N.onOrAfter]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[N.notBefore]:{negates:N.before,kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[N.notAfter]:{negates:N.after,kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[N.within]:{kinds:["DateTime"],targets:_,valueShape:"dateWindow",acceptsExpr:true},[N.notWithin]:{negates:N.within,kinds:["DateTime"],targets:_,valueShape:"dateWindow",acceptsExpr:true},[N.between]:{kinds:["DateTime"],targets:_,valueShape:"dateRange",acceptsExpr:true},[N.notBetween]:{negates:N.between,kinds:["DateTime"],targets:_,valueShape:"dateRange",acceptsExpr:true},[N.dayIn]:{kinds:["DateTime"],targets:Gi,valueShape:"dayList",acceptsExpr:false},[N.dayNotIn]:{negates:N.dayIn,kinds:["DateTime"],targets:Gi,valueShape:"dayList",acceptsExpr:false}},$o={[x.all]:{targets:Tn,valueShape:"predicate",holdsOnNoRows:true},[x.any]:{targets:Tn,valueShape:"predicate",holdsOnNoRows:false},[x.none]:{targets:Tn,valueShape:"predicate",holdsOnNoRows:true},[x.atLeast]:{targets:Tn,valueShape:"count",comparator:"gte",holdsOnNoRows:true},[x.atMost]:{targets:Tn,valueShape:"count",comparator:"lte",holdsOnNoRows:true},[x.exactly]:{targets:Tn,valueShape:"count",comparator:"equals",holdsOnNoRows:true},[x.empty]:{targets:_,valueShape:"none",holdsOnNoRows:true},[x.notEmpty]:{targets:_,valueShape:"none",holdsOnNoRows:false}},xf={field:kn,date:Cn,array:$o},Bt=(e,t)=>Object.hasOwn(xf[t],e)?xf[t][e]:void 0,Mn=e=>typeof e.operator=="string"?Bt(e.operator,"field"):typeof e.dateOperator=="string"?Bt(e.dateOperator,"date"):void 0,lr=(e,t)=>Bt(e,t)?.comparator,Ut=(e,t)=>{let r=Bt(e,t);if(!r)throw fe(e,t);return r.valueShape},zi=(e,t,r)=>Bt(e,t)?.targets.includes(r)??false,_R=(e,t)=>{let r=Object.keys(kn).filter(o=>{let i=kn[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))}),n=Object.keys(Cn).filter(o=>{let i=Cn[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))});return {field:r,date:n}},DR=e=>Object.keys($o).filter(t=>e?$o[t].targets.includes(e):true),Ef=[...Object.entries(kn),...Object.entries(Cn)],je=(...e)=>Ef.flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),pr=je("none"),_n=je("ordered"),No=je("dateWindow"),ze=je("range","dateRange","dateWindow"),$f=je("ordered","string","pattern","array"),bt=[h.contains,h.notContains],Aa=[h.equals,h.notEquals,h.in,h.notIn,h.exists,h.notExists],Hi=je("scalar","ordered","range"),Ln={sum:{result:"number",comparable:true},avg:{result:"number",comparable:true},count:{result:"count",comparable:false},min:{result:"element",comparable:false},max:{result:"element",comparable:false},distinct:{result:"list",comparable:false}},Rt=Object.keys(Ln).filter(e=>Ln[e].comparable),Pa=Object.keys(Ln),Ji=e=>typeof e=="string"&&Object.hasOwn(Ln,e),vf=[...X,"DateTime"],Nf=["String","Enum","DateTime","Boolean",...X],FR=()=>Hi,Ot=je("scalar"),dr=je("array"),Af=je("scalar","array"),Pf=je("dayList"),Tf=je("dateRange"),kf=je("scalar","ordered","range","dateValue","dateRange"),Cf=(...e)=>Object.entries($o).flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),Ao=Cf("count"),Ta=e=>typeof e.condition!="object"||e.condition===null?null:e.arrayOperator===x.atLeast&&e.count===1?x.any:(e.arrayOperator===x.atMost||e.arrayOperator===x.exactly)&&e.count===0?x.none:null,Po=e=>Ao.includes(e.arrayOperator)&&Ta(e)===null,Qi=Cf("predicate","count"),ka=[x.any,x.all,x.none,x.empty,x.notEmpty],Lf=[x.any,x.atLeast],W=[...Object.entries(kn),...Object.entries(Cn)].flatMap(([e,t])=>t.negates?[e]:[]),Zi=[...W,h.isEmpty,h.notExists],Mf=Object.entries($o).flatMap(([e,t])=>t.holdsOnNoRows?[e]:[]),_f=W.filter(e=>je("string").includes(e)),Dn=W.filter(e=>ze.includes(e)),Df=(...e)=>Ef.flatMap(([t,r])=>r.comparator&&e.includes(r.comparator)&&!W.includes(t)?[t]:[]),Yi=Df("lt","lte"),Ff=Df("gt","gte"),jf=["Int","BigInt"],Vf=[...X,"DateTime","Boolean","String"],If=["Int","BigInt","Float","Boolean","String"],qf=["scalar","ordered","string"],To=["second","minute","hour","day","week","month","quarter","year"],et={years:{interval:"months",factor:12,calendar:true,clock:"year"},quarters:{interval:"months",factor:3,calendar:true,clock:"quarter"},months:{interval:"months",factor:1,calendar:true,clock:"month"},weeks:{interval:"days",factor:7,calendar:true,clock:"week"},days:{interval:"days",factor:1,calendar:true,clock:"day"},hours:{interval:"secs",factor:3600,calendar:false,clock:"hour"},minutes:{interval:"secs",factor:60,calendar:false,clock:"minute"},seconds:{interval:"secs",factor:1,calendar:false,clock:"second"}},Bf=["months","days","secs"],Fn=e=>Object.hasOwn(et,e),_r=e=>Fn(e)&&et[e].calendar,Xi={year:"year",quarter:"quarter",month:"month",week:"week",isoWeek:"week",day:"day",hour:"hour",minute:"minute",second:"second"},es=Object.keys(Xi),Wf=e=>typeof e=="string"&&Object.hasOwn(Xi,e),jn=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],Uf=e=>jn.includes(e.toLowerCase()),Kf=(e,t=[])=>Object.fromEntries([...Object.entries(e).flatMap(([r,n])=>n.negates?[[n.negates,r]]:[]),...t].flatMap(([r,n])=>[[r,n],[n,r]])),ko=Kf(kn,[[h.isEmpty,h.notEmpty],[h.exists,h.notExists]]),Gf=Kf(Cn),ts={[h.lessThan]:h.greaterThanEquals,[h.lessThanEquals]:h.greaterThan,[h.greaterThan]:h.lessThanEquals,[h.greaterThanEquals]:h.lessThan,[N.onOrBefore]:N.after,[N.onOrAfter]:N.before};var rs=e=>new Error(`${e}: ArrayRule.field is required (fieldless arrayOps are check-only)`),fe=(e,t)=>new Error(`Unknown ${t} operator: ${String(e)}`),zf=(e,t)=>new Error(`'${e}' is finer than the engine's clock.finestUnit '${t}'`),Vn=e=>new Error(`${e} requires a count`),tt=e=>new Error(`${e} requires a range date expression (a period or rolling window), not a single point`),Ve=e=>new Error(`${e} requires a condition to check against array elements`),fr=e=>new Error(`'${e}' is a relation: it exists or not; compare its fields with '${e}.<field>'.`),ns=e=>new Error(`'${e}' is a list of rows: compare it with an arrayOperator (any / all / none / empty / atLeast \u2026).`),os=e=>bt.includes(e.operator)&&Wi(e.fuzzy)?new Error("Fuzzy matching has no compiled form \u2014 evaluate it in memory with check()."):null,is=(e,t)=>!_n.includes(e)&&!ze.includes(e)?null:(ze.includes(e)&&Array.isArray(t)?t:[t]).some(n=>typeof n=="boolean"||typeof n=="object"&&n!==null&&!(n instanceof Date))?new Error(`'${e}' orders numbers, strings and dates; it can't compare ${JSON.stringify(t)}`):null,ur=e=>new Error(`aggregate.mode must be one of ${Rt.join(" / ")}, not '${String(e)}'`),ss=e=>new Error(`aggregate.mode must be one of ${Pa.join(" / ")}, not '${String(e)}'`),In=e=>new Error(`${e}: a value expression is exactly one of: { value }, { path }, { bind }, an aggregate ({ field, aggregate }), if / then [/ else], or a list`),qn=e=>new Error(`${e}: an aggregate value is the aggregate itself and takes no operator or value; compare it in a rule`),xt=()=>new Error("A condition is exactly one of: a field, date, array or aggregate rule, all, any, or if/then[/else]"),V=(e,t,r)=>new Error(`${t} has no ${e==="toSql"?"SQL":"Prisma"} form${r?` (${r})`:""}; use ${e==="toSql"?"check()":"toSql() or check()"}.`),Et=e=>new Error(`Windowing (filter/orderBy/take/skip) is not supported by ${e}() for this rule; evaluate with check()${e==="toPrisma"?" \u2014 toPrisma compiles a filter alone and an extremal take: 1":""}.`),Bn=(e,t)=>new Error(`'${e}' reads through the to-many relation '${t.prefix}'; compare its rows with an arrayOperator rule on '${t.prefix}'.`),Wn=(e,t)=>new Error(`'${e}' continues past '${t}', which is not a Json column`),C=class extends Error{name="UsageError"};vt.extend(qR);vt.extend(IR);vt.extend(VR);vt.extend(jR);var ee=e=>{if(!re(e))return false;let t=e;return "ago"in t||"ahead"in t||"this"in t||"last"in t||"next"in t||"start"in t||"end"in t},Ie="UTC",Co=e=>{if(e.now===void 0)throw new C("date expressions require `now` to be supplied to the evaluator");let t=vt(e.now).tz(e.timeZone);if(!t.isValid())throw new C(`invalid \`now\`: ${String(e.now)}`);return t},Ca=(e,t)=>Object.entries(e).reduce((r,[n,o])=>et[n].interval===t?r+o*et[n].factor:r,0),Hf="YYYY-MM-DDTHH:mm:ss.SSS",cr=(e,t,r,n)=>{let o=Ca(t,"months"),i=Ca(t,"days"),s=Ca(t,"secs"),a=vt.utc(e.tz(n).format(Hf));return o&&(a=a.add(r*o,"month")),i&&(a=a.add(r*i,"day")),s&&(a=a.add(r*s*1e3,"millisecond")),vt.tz(a.format(Hf),n)},BR=e=>"ago"in e||"ahead"in e,as=(e,t)=>t===-1?{ago:e}:{ahead:e},be=e=>BR(e)?"ago"in e?[e.ago,-1]:[e.ahead,1]:null,Lo=e=>"this"in e||"last"in e||"next"in e,Mo=e=>"start"in e||"end"in e,Un=e=>"this"in e?e.this:"last"in e?e.last:e.next,WR=e=>{let t=Un(e);if(typeof t!="string"||!es.includes(t))throw new Error(`Unknown period unit '${String(t)}'`);return t},UR=(e,t)=>e==="week"?t.weekStart==="sunday"?"week":"isoWeek":e,La=(e,t)=>{let r=Co(t),n=WR(e),o=n==="isoWeek"?"week":n,i=r;"last"in e?i=r.subtract(1,o):"next"in e&&(i=r.add(1,o));let s=UR(n,t);return [i.startOf(s),i.endOf(s)]},Ma=(e,t)=>{let r=be(e);if(r)return cr(Co(t),...r,t.timeZone);if(Mo(e)){let n="start"in e?e.start:e.end,[o,i]=La(n,t);return "start"in e?o:i}throw new Error("a point operator requires a rolling or start/end edge expression, not a bare period")},Kn=(e,t,r)=>{if(Lo(e)){let[n,o]=La(e,r),i=Mn({dateOperator:t})?.negates??t;return Yi.includes(i)?n:o}return Ma(e,r)},Gn=(e,t)=>{if(Lo(e))return La(e,t);let r=be(e);if(r){let n=Co(t),o=cr(n,...r,t.timeZone);return r[1]===-1?[o,n]:[n,o]}throw tt("within")};var Jf=["value","bind","path"],Re=e=>typeof e.path=="string"&&e.path!=="",Fr=e=>Re(e)?M(e.path)??{depth:0,path:e.path}:null,_o=(e,t)=>{if(e.value!==void 0)return t.value(e.value);if(e.bind!==void 0)return t.bind(e.bind,e.bindOptional);if(Re(e))return t.path(e.path);throw new Error("No value, path or bind specified")},ls=e=>re(e)&&(e.value!==void 0||Re(e)||typeof e.bind=="string"),_a=(e,t,r)=>{if(!r||!Object.hasOwn(r,e)){if(t===true)return null;throw new C(`Missing binding for "${e}"`)}let n=r[e];return n===void 0?null:n},ps=(e,t,r)=>{if(t===true)return null;throw new C(`Unresolved binding '${e}' \u2014 resolve bindings (bindRule / bindLens) before compiling with ${r}().`)},qe=(e,t,r)=>_o(e,{value:n=>n,bind:(n,o)=>_a(n,o,r),path:n=>qi(n,t)??null});var Zf=e=>typeof e=="object"&&e!==null,ds=e=>"if"in e||"then"in e||"else"in e,Oe=e=>"arrayOperator"in e||"aggregate"in e,Yf=e=>[...["all","any"].flatMap(t=>Array.isArray(e[t])?e[t].map((r,n)=>({key:t,index:n,child:r,nested:false})):[]),...ds(e)?["if","then","else"].flatMap(t=>e[t]!==void 0?[{key:t,child:e[t],nested:false}]:[]):[],...["condition","filter"].flatMap(t=>e[t]!==void 0?[{key:t,child:e[t],nested:true}]:[])],Be=e=>"all"in e||"any"in e||ds(e),H=(e,t,r)=>{if(!Zf(e))return;let n=e,o=t(n,r),i=o===void 0?r:o;for(let{child:s,nested:a}of Yf(n))a?i!==false&&H(s,t,i):H(s,t,r);},Xf=(e,t,r,n)=>{let o=false;return H(e,(i,s)=>(!o&&t(i,s)&&(o=true),o?false:r?.(i,s)),n),o},mr=(e,t,r)=>{if(!Zf(e))return e;let n=r,o={...e},i=t.rewrite?t.rewrite(o,n):o,s=Yf(i),a=s.some(d=>d.nested)&&t.below?t.below(i,n):n;for(let d of ["all","any"])Array.isArray(i[d])&&(i[d]=[...i[d]]);for(let{key:d,index:p,child:f,nested:u}of s){if(u&&a===false)continue;let m=mr(f,t,u?a:n);p===void 0?i[d]=m:i[d][p]=m;}let l=t.after?t.after(i,n):i;return l===i&&KR(i,e)?e:l},KR=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?false:r.every(n=>{let[o,i]=[e[n],t[n]];return o===i?true:Array.isArray(o)&&Array.isArray(i)&&o.length===i.length&&o.every((s,a)=>s===i[a])})},GR=(e,t)=>re(e)?Object.fromEntries(Object.entries(e).map(([r,n])=>[r,ls(n)?t(n,_r(r)?"whole":"number"):n])):e,Da=(e,t)=>{let r=ee(e)?be(e):null;return r?as(GR(r[0],t),r[1]):e},zn=(e,t)=>{let r="dateOperator"in e;if(!r&&!("operator"in e))return e;let n=e;if(r&&e.value!==void 0){let o=Array.isArray(e.value)?e.value.map(i=>Da(i,t)):Da(e.value,t);n={...n,value:o};}if(ls(e.offset)){let o=r?{...e.offset,...e.offset.value!==void 0&&{value:Da(e.offset.value,t)}}:e.offset;n={...n,offset:t(o,r?"shift":"number")};}return ls(n)&&(n=t(n,"value")),n},Do=e=>{let t=[];return zn(e,(r,n)=>(t.push({source:r,role:n}),r)),t},Fo=e=>Do(e).flatMap(({source:t,role:r})=>Re(t)?[{ref:t.path,role:r}]:[]),gr=e=>Fo(e).map(t=>t.ref),Hn=e=>[...Array.isArray(e.orderBy)?e.orderBy.flatMap(t=>typeof t?.field=="string"?[t.field]:[]):[],...typeof e.aggregate?.field=="string"?[e.aggregate.field]:[]],zR={all:"all",any:"any",if:"if",field:"field",aggregate:"aggregate",array:"array",date:"date"},jr=()=>(e,t)=>({required:[...e],optional:[...t]}),Qf={all:jr()(["all"],["error"]),any:jr()(["any"],["error"]),if:jr()(["if","then"],["else","error"]),field:jr()(["field","operator"],["value","path","bind","bindOptional","offset","caseInsensitive","fuzzy","coerceType","error"]),aggregate:jr()(["field","aggregate","operator"],["value","path","bind","bindOptional","condition","filter","orderBy","take","skip","error"]),array:jr()(["arrayOperator"],["field","condition","count","filter","orderBy","take","skip","error"]),date:jr()(["field","dateOperator"],["value","path","bind","bindOptional","offset","error"])},HR=e=>({required:[...Qf[e].required],optional:[...Qf[e].optional]}),le=e=>{let t=new Set;return "all"in e&&t.add("all"),"any"in e&&t.add("any"),ds(e)&&t.add("if"),"arrayOperator"in e&&t.add("array"),"dateOperator"in e&&t.add("date"),"aggregate"in e?t.add("aggregate"):"operator"in e&&t.add("field"),t.size===1?[...t][0]:null},U=e=>e.length===0?true:e.length===1?e[0]:{all:[...e]},Fa=e=>typeof e=="object"&&"all"in e&&Array.isArray(e.all)?e.all.flatMap(Fa):[e],Kt=e=>e.length===0?false:e.length===1?e[0]:{any:[...e]};var JR=e=>e===null||e instanceof Date||["string","number","boolean","bigint"].includes(typeof e),Ir=e=>{if(Array.isArray(e))return e;let t=e.list;return Array.isArray(t)?t:[]},yr=e=>{if(Array.isArray(e))return "list";if(JR(e))return "literal";if(!re(e))return null;let t=e,r=[];return "list"in t&&r.push("list"),ds(t)&&r.push("if"),"aggregate"in t&&r.push("aggregate"),("value"in t||"path"in t||"bind"in t)&&r.push("source"),r.length===1?r[0]:null},Vr=e=>{let t=e;switch(yr(e)){case "list":return U(Ir(e).map(Vr));case "if":return U([t.if,Vr(t.then),...t.else===void 0?[]:[Vr(t.else)]]);case "aggregate":return t;case "source":return Re(t)?{field:t.path,operator:"exists"}:true;default:return true}};var QR=e=>Do(e).flatMap(({source:t})=>typeof t.bind=="string"?[t]:[]),jo=(e,{required:t=false}={})=>{let r=new Set;return H(e,n=>{for(let o of QR(n))(!t||o.bindOptional!==true)&&r.add(o.bind);}),[...r].sort()},ZR=e=>{let t=new Set;return H(e,r=>{typeof r.field=="string"&&t.add(r.field);for(let{ref:n}of Fo(r))t.add(n);return Oe(r)?false:void 0}),[...t].sort()},ja=(e,t)=>{let r=n=>{if(typeof n.bind!="string"||!Object.hasOwn(t,n.bind))return n;let{bind:o,bindOptional:i,...s}=n;return {...s,value:_a(o,true,t)}};return mr(e,{rewrite:n=>zn(zn(n,r),r)})};var eu=BigInt(Number.MAX_SAFE_INTEGER),qr=e=>{if(e>eu||e<-eu)throw new RangeError(`BigInt ${e} is outside the safe integer range (\xB12^53); json-rules compares BigInt as Int.`);return Number(e)},Va=e=>typeof e=="bigint"?qr(e):typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e))?Number(e):e,fs=(e,t)=>{if(e==null)return null;let r=Va(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} reads a number (got ${String(e)})`);return r},He=([e,t])=>t<e?[t,e]:[e,t],rt=(e,t)=>{if(!Array.isArray(e)||e.length!==2)throw new Error(`${t} operator requires an array of two values`);return [e[0],e[1]]},Jn=(e,t)=>{let r=rt(e,t);if(!r.every(ge))throw new Error(`${t} requires two ends that order \u2014 numbers, strings or dates (got ${JSON.stringify(e)})`);return r},us=e=>{if(!Array.isArray(e))throw new Error(`in / notIn requires a list (got ${JSON.stringify(e)})`);return e},Je=e=>{let t=us(e),r=t.filter(n=>n!==null);return {values:r,hasNull:r.length!==t.length}},ge=e=>typeof e=="string"||typeof e=="number"||e instanceof Date;var Ia=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&(!_r(t)||Number.isInteger(e))?null:`${t} must be a non-negative${_r(t)?" whole":""} number (got ${String(e)})`,qa=(e,t,r)=>{let n=typeof e=="number"?e:fs(t(e),e.path?`'${e.path}' (${r})`:r),o=n===null?null:Ia(n,r);if(o===null)return n;if(typeof e!="number"&&Re(e))return null;throw new Error(o)},Br=(e,t)=>{let r={};for(let[n,o]of Object.entries(e)){if(o===void 0)continue;let i=qa(o,t,n);if(i===null)return null;r[n]=i;}return r},$t=(e,t)=>{let r=be(e);if(!r)return e;let n=Br(r[0],t);return n?as(n,r[1]):null};var YR=e=>{let t=be(e);if(t)return re(t[0])?Object.keys(t[0]).flatMap(o=>Fn(o)?[et[o].clock]:[]):[];let r=Mo(e)?"start"in e?e.start:e.end:e;if(!re(r))return [];let n=Un(r);return Wf(n)?[Xi[n]]:[]},tu=(e,t)=>[...bi(e),t].filter(ee).flatMap(YR),XR=e=>bi(e).some(ee),cs=e=>To.indexOf(e),eO=()=>{let e=Xe.get("clock.finestUnit");if(To.includes(e))return e;if(typeof e=="string"&&Fn(e))return et[e].clock;throw new C(`clock.finestUnit reads a clock unit, singular or plural (got ${String(e)})`)},Gt=(e,t)=>{let r=tu(e,t);if(r.length===0)return null;let n=eO(),o=r.find(i=>cs(i)<cs(n));return o?zf(o,n):null},Ba=e=>re(e)?e.value:void 0,Vo=e=>{let t=null;return H(e,r=>{if(!("dateOperator"in r))return;let n=Ba(r.offset),o=Gt(r.value,n);if(o)throw o;if(XR(r.value))for(let i of tu(r.value,n))(t===null||cs(i)<t)&&(t=cs(i));}),t===null?null:To[t]};var Wr=(e,t)=>{if(e==null)return null;if(Array.isArray(e)){let n=e.map(o=>Wr(o,t));return n.some(o=>o===null)?null:n}let r=Va(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`offset needs a numeric comparison value (got ${String(e)})`);return r+t},Ur=e=>fs(e,"an offset"),Qn=e=>{if(e==null)return null;let t=ee(e)?be(e):null;if(!t)throw new Error(`a date offset reads { ago } or { ahead } (got ${JSON.stringify(e)})`);return t};vt.extend(qR);vt.extend(IR);vt.extend(rO);vt.extend(tO);var ou=(e,t,r={},n)=>{let o=sr(e.field,t),i=zt(r,u=>qe(u,t,n)),s=i.timeZone;if(o==null)return W.includes(e.dateOperator)?true:e.error||`${e.field} has no value`;let a=ge(o)?hr(o,s):null;if(!a?.isValid())throw new Error(`${e.field} is not a valid date: ${String(o)}`);let l=u=>e.error||`${e.field} ${u}`;if(Pf.includes(e.dateOperator)){let u=Wa(qe(e,t,n));if(u===null)return e.error||`${e.field} has no comparison value`;let m=u.includes(a.tz(s).day()),y=u.map(c=>jn[c]).join(" or ");return e.dateOperator===N.dayIn?m||l(`must be on ${y}`):!m||l(`must not be on ${y}`)}let d=iO(e,t,i,s,n);if(d===null)return e.error||`${e.field} has no comparison value`;let[p,f=p]=d;switch(e.dateOperator){case N.before:return a.isBefore(p)||l(`must be before ${p.format()}`);case N.after:return a.isAfter(p)||l(`must be after ${p.format()}`);case N.onOrBefore:return a.isSameOrBefore(p)||l(`must be on or before ${p.format()}`);case N.onOrAfter:return a.isSameOrAfter(p)||l(`must be on or after ${p.format()}`);case N.within:return a.isSameOrAfter(p)&&a.isSameOrBefore(f)||l(`must be within ${p.format()} and ${f.format()}`);case N.notBefore:return a.isSameOrAfter(p)||l(`must not be before ${p.format()}`);case N.notAfter:return a.isSameOrBefore(p)||l(`must not be after ${p.format()}`);case N.notWithin:return a.isBefore(p)||a.isAfter(f)||l(`must not be within ${p.format()} and ${f.format()}`);case N.between:return a.isSameOrAfter(p)&&a.isSameOrBefore(f)||l(`must be between ${p.format()} and ${f.format()}`);case N.notBetween:return a.isBefore(p)||a.isAfter(f)||l(`must not be between ${p.format()} and ${f.format()}`);default:throw fe(e.dateOperator,"date")}},iO=(e,t,r,n,o)=>{let i=e.dateOperator,s=g=>qe(g,t,o),a=qe(e,t,o);if(a==null)return null;let l=e.offset===void 0?void 0:s(e.offset),d=Gt(a,l);if(d)throw d;let p=l===void 0?void 0:Qn(l);if(p===null)return null;let f=g=>{if(p===void 0)return g;let w=Br(p[0],s);return w&&cr(g,w,p[1],n)};if(No.includes(i)){if(!ee(a))throw tt(i);let g=$t(a,s);return g&&Gn(g,r)}let u=(g,w)=>{if(g==null)return null;if(ee(g)){let S=$t(g,s);return S&&Ma(S,r)}let R=hr(g,n);if(!R.isValid())throw new Error(`Invalid ${w}: ${String(g)}`);return R};if(Tf.includes(i)){let[g,w]=rt(a,i),R=u(g,"start date"),S=u(w,"end date");if(!R||!S)return null;let[b,v]=He([R,S]),E=f(b),q=f(v);return E&&q?[E,q]:null}if(Array.isArray(a))throw new Error(`${i} operator requires a single date value`);let m=g=>{let w=$t(g,s);return w&&Kn(w,i,r)},y=ee(a)?m(a):u(a,"comparison date");if(!y)return null;let c=f(y);return c&&[c]},zt=(e,t)=>{let r=e.timeZone;if(r===void 0||typeof r=="string")return {...e,timeZone:nu(r??Ie)};if(Fr(r))throw new C(`timeZone is one per evaluation; give it as a string or a { bind }, not the row path '${r.path}'`);let n=t(r);if(n!=null&&typeof n!="string")throw new C(`timeZone reads a zone name (got ${String(n)})`);return {...e,timeZone:nu(n??Ie)}},ru=new Set,nu=e=>{if(ru.has(e))return e;try{new Intl.DateTimeFormat("en-US",{timeZone:e});}catch{throw new C(`invalid time zone: ${e}`)}return ru.add(e),e},sO=/\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:[zZ]|[+-]\d{2}(?::?\d{2})?)$/,aO=e=>sO.test(e.trim())||/\b(?:GMT|UTC)\b/.test(e),hr=(e,t)=>{if(typeof e=="string"&&/^-?\d+$/.test(e.trim()))return vt(Number(e));if(typeof e=="string"&&!aO(e)){let r=vt(e);return r.isValid()?vt.tz(e,t):r}return typeof e=="string"?vt(new Date(e.trim())):vt(e)},ms=(e,t)=>{let r=ge(e)?hr(e,t):vt(Number.NaN);if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},Wa=e=>{if(e==null)return null;if(!Array.isArray(e))throw new Error("a weekday operator requires an array of day names");return e.map(t=>{let r=jn.indexOf(String(t).toLowerCase());if(r===-1)throw new Error(`Unknown day name: ${String(t)}`);return r})};var pO=e=>e<=3?0:e<=6?1:2,dO=(e,t)=>{let{maxDistance:r,maxRatio:n}=e,o=[];return typeof r=="number"&&o.push(r),typeof n=="number"&&o.push(Math.floor(t*n)),o.length>0?Math.min(...o):pO(t)},iu=e=>e.split(/[^a-z0-9\p{L}]+/u).filter(Boolean),fO=e=>/^\d+$/.test(e),uO=(e,t,r)=>e===t?true:Math.abs(e.length-t.length)>r?false:distance(e,t)<=r,su=(e,t,r={})=>{let n=t.trim().toLowerCase();if(!n)return true;let o=e.toLowerCase();if(o.includes(n))return true;let i=iu(n);if(i.length===0)return false;let s=iu(o);return s.length===0?false:i.every(a=>{let l=dO(r,a.length);return l===0||fO(a)?s.includes(a):s.some(d=>uO(a,d,l))})};var wr=e=>{let t=e instanceof RegExp?e.source:e,r=e instanceof RegExp?e.flags:"";if(/[^i]/.test(r))throw new Error(`Refused pattern /${t}/${r}: only the 'i' flag is supported`);let n=r==="i";try{return {source:t,caseInsensitive:n,re:RE2JS.compile(t,n?RE2JS.CASE_INSENSITIVE:0)}}catch(o){throw new Error(`Refused pattern /${t}/: ${o.message}`)}},Zn={d:"0-9",w:"0-9A-Za-z_",s:"\\t\\n\\f\\r "},lu={alnum:"0-9A-Za-z",alpha:"A-Za-z",ascii:"\\u0000-\\u007f",blank:"\\t ",cntrl:"\\u0000-\\u001f\\u007f",digit:"0-9",graph:"!-~",lower:"a-z",print:" -~",punct:"!-/:-@\\[-`{-~",space:"\\t\\n\\v\\f\\r ",upper:"A-Z",word:"0-9A-Za-z_",xdigit:"0-9A-Fa-f"},cO=/[\\^$.|?*+()[\]{}]/,Ua=255,pu=e=>e<=65535?`\\u${e.toString(16).padStart(4,"0")}`:`\\U${e.toString(16).padStart(8,"0")}`,mO=e=>cO.test(e)?`\\${e}`:e,Io=e=>{let t=s=>{throw new Error(`Refused pattern /${e}/: ${s} has no Postgres form`)},r="",n=0,o=()=>{/^([*+?]|\{\d)/.test(e.slice(n))&&t("a quantified anchor");},i=s=>{let a=e[n+1];if(n+=2,Object.hasOwn(Zn,a))return s?Zn[a]:`[${Zn[a]}]`;let l=a.toLowerCase();if(a!==l&&Object.hasOwn(Zn,l))return s&&t(`a negated class \\${a} inside brackets`),`[^${Zn[l]}]`;if(a==="p"||a==="P")return t("a Unicode class");if(a==="C")return t("\\C");if(a==="x"){let d=e[n]==="{",p=d?e.indexOf("}",n):n+2,f=e.slice(d?n+1:n,p);return n=d?p+1:p,pu(Number.parseInt(f,16))}if(a>="0"&&a<="7"){let d=a;for(;d.length<3&&e[n]>="0"&&e[n]<="7";)d+=e[n++];return pu(Number.parseInt(d,8))}if(!s&&(a==="b"||a==="B")){let d=`[${Zn.w}]`;return a==="b"?`(?:(?<=${d})(?!${d})|(?<!${d})(?=${d}))`:`(?:(?<=${d})(?=${d})|(?<!${d})(?!${d}))`}if(!s&&(a==="z"||a==="A"))return o(),a==="z"?"\\Z":"\\A";if(a==="Q"){let d=e.indexOf("\\E",n),p=e.slice(n,d===-1?void 0:d);return n=d===-1?e.length:d+2,[...p].map(s?f=>/[\\\]^-]/.test(f)?`\\${f}`:f:mO).join("")}return `\\${a}`};for(;n<e.length;){let s=e[n];if(s==="\\")r+=i(false);else if(s===".")r+="[^\\n]",n++;else if(s==="("&&e[n+1]==="?"){let a=/^\(\?P?<[^>]+>/.exec(e.slice(n));a?(r+="(",n+=a[0].length):e[n+2]===":"?(r+="(?:",n+=3):t("a flag group");}else if(s==="{"){let a=/^\{(0|[1-9]\d*)(?:,(0|[1-9]\d*)?)?\}/.exec(e.slice(n));if(!a){r+="\\{",n++;continue}(Number(a[1])>Ua||Number(a[2]??0)>Ua)&&t(`a repeat count past ${Ua}`),r+=a[0],n+=a[0].length;}else if(s==="["){r+="[",n++,e[n]==="^"&&(r+="^",n++),e[n]==="]"&&(r+="\\]",n++);let a=false,l=false,d=0;for(;n<e.length&&e[n]!=="]";){let p=l?null:/^\[:(\^?)([a-z]+):\]/.exec(e.slice(n)),f=!!p||/^\\[dswDSW]/.test(e.slice(n)),u=e[n]==="-"&&d>0&&e[n+1]!=="]"&&!l;p?(p[1]&&t(`a negated class [:^${p[2]}:]`),Object.hasOwn(lu,p[2])||t(`the class [:${p[2]}:]`),r+=lu[p[2]],n+=p[0].length):e[n]==="\\"?r+=i(true):u&&a?(r+="\\-",n++):(r+=e[n]==="["?"\\[":e[n],n++);let m=l;l=u&&!a,a=f||m,d++;}r+="]",n++;}else r+=s,n++,(s==="^"||s==="$")&&o();}return r},du=(e,t)=>{try{let{source:r}=wr(e);return t==="toSql"&&Io(r),null}catch(r){return r.message}};var fu=e=>e==null||e===""||Array.isArray(e)&&e.length===0,xe=(e,t)=>{let r=t==null;return r&&(e.offset!==void 0||$f.includes(e.operator))?true:ze.includes(e.operator)?r||Array.isArray(t)&&t.some(n=>n==null):false},Jt=e=>pr.includes(e.operator)||Ot.includes(e.operator)&&e.value===null&&e.path===void 0&&e.bind===void 0,ys=(e,t)=>{let r=t.filter(o=>Array.isArray(o)||o===null),n=o=>r.map(i=>({...e,operator:o,value:i}));return e.operator===h.in?Kt(n(h.equals)):U(n(h.notEquals))},Kr=e=>typeof e=="string"?e.toLowerCase():Array.isArray(e)?e.map(Kr):e,uu=e=>typeof e=="bigint"?qr(e):Array.isArray(e)&&e.some(t=>typeof t=="bigint")?e.map(t=>typeof t=="bigint"?qr(t):t):e,cu=(e,t,r)=>{if(e==null)return e;if(X.includes(t)){if(typeof e!="string"||e.trim()==="")return e;if(t==="BigInt"&&/^-?\d+$/.test(e.trim()))return qr(BigInt(e.trim()));let n=Number(e);return Number.isFinite(n)?n:e}switch(t){case "DateTime":{if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e!="string")return e;let n=hr(e,r);return n.isValid()?n.valueOf():e}case "Boolean":return e==="true"?true:e==="false"?false:e;case "String":return typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):e;default:return e}},Ht=(e,t,r=Ie)=>t===void 0?e:Array.isArray(e)?e.map(n=>cu(n,t,r)):cu(e,t,r),qo=(e,t,r,n={},o)=>{let i=o?o.value:sr(e.field,t);if(n.absent==="unknown"&&!Zi.includes(e.operator)&&(i===void 0||Re(e)&&qi(e.path,t)===void 0))return e.error||`${e.field} is unknown`;let s=i??null,a=e.coerceType??(s instanceof Date?"DateTime":void 0),l=a==="DateTime"?zt(n,S=>qe(S,t,r)).timeZone:Ie,d=Ht(uu(s),a,l),p=!pr.includes(e.operator),f=p?gO(Ht(uu(qe(e,t,r)??null),a,l),e,t,r):void 0;if(p&&xe(e,f))return W.includes(e.operator)&&d==null?true:e.error||`${e.field} has no comparison value`;let u=S=>e.error||`${e.field} ${S}${p?` ${f instanceof RegExp?String(f):JSON.stringify(f)}`:""}`,m=oe(e.caseInsensitive),y=S=>m?Kr(S):S,c=y(d),g=y(f),w=Wi(e.fuzzy),R=()=>w&&typeof d=="string"&&typeof f=="string"?su(d,f,w):Array.isArray(d)?c.some(S=>qt(S,g)):yO(c,g);switch(e.operator){case h.equals:return qt(c,g)||u("must equal");case h.notEquals:return !qt(c,g)||u("must not equal");case h.lessThan:return gs(d,f,"lt")||u("must be less than");case h.lessThanEquals:return gs(d,f,"lte")||u("must be less than or equal to");case h.greaterThan:return gs(d,f,"gt")||u("must be greater than");case h.greaterThanEquals:return gs(d,f,"gte")||u("must be greater than or equal to");case h.in:return us(g).some(S=>qt(S,c))||u("must be one of");case h.notIn:return !us(g).some(S=>qt(S,c))||u("must not be one of");case h.contains:return R()||u("must contain");case h.notContains:return !R()||u("must not contain");case h.matches:return mu(d)&&gu(f)&&wr(f).re.test(d)||u("must match pattern");case h.notMatches:return !mu(d)||!gu(f)||!wr(f).re.test(d)||u("must not match pattern");case h.between:{let S=yu(f,e.operator);if(!wu(d,S))return u("must be between");let b=Yn(d),[v,E]=S;return b>=v&&b<=E||u("must be between")}case h.notBetween:{let S=yu(f,e.operator);if(!wu(d,S))return true;let b=Yn(d),[v,E]=S;return b<v||b>E||u("must not be between")}case h.isEmpty:return fu(d)||u("must be empty");case h.notEmpty:return !fu(d)||u("must not be empty");case h.exists:return d!=null||u("must exist");case h.notExists:return d==null||u("must not exist");case h.startsWith:return typeof c=="string"&&typeof g=="string"&&c.startsWith(g)||u("must start with");case h.endsWith:return typeof c=="string"&&typeof g=="string"&&c.endsWith(g)||u("must end with");case h.notStartsWith:return !(typeof c=="string"&&typeof g=="string"&&c.startsWith(g))||u("must not start with");case h.notEndsWith:return !(typeof c=="string"&&typeof g=="string"&&c.endsWith(g))||u("must not end with");default:throw new Error("Unknown operator")}},gO=(e,t,r,n)=>{if(t.offset===void 0)return e;let o=Ur(qe(t.offset,r,n));return o===null?null:Wr(e,o)},Yn=e=>e instanceof Date?e.getTime():e,gs=(e,t,r)=>{if(!hO(e,t)||!ge(t))return false;let n=Yn(e),o=Yn(t);switch(r){case "lt":return n<o;case "lte":return n<=o;case "gt":return n>o;case "gte":return n>=o}},mu=e=>typeof e=="string",gu=e=>typeof e=="string"||e instanceof RegExp,yu=(e,t)=>He(Jn(e,t).map(r=>Yn(r))),yO=(e,t)=>typeof e=="string"&&typeof t=="string"&&e.includes(t),hO=(e,t)=>ge(e)&&ge(t)&&hu(e)===hu(t),hu=e=>e instanceof Date?"date":typeof e,wu=(e,t)=>ge(e)&&typeof Yn(e)==typeof t[0];var Ne=e=>e.filter!==void 0||!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0,wO=e=>{if(typeof e!="object"||e===null)return null;let t=e,r=le(t);return r!=="field"&&r!=="date"||typeof t.field!="string"?null:{op:String(r==="date"?t.dateOperator:t.operator),field:t.field}},SO=e=>{if(e.filter!==void 0||e.skip!==void 0&&e.skip!==0||e.take!==1||e.orderBy?.length!==1)return null;let{field:t,dir:r}=e.orderBy[0];if(r!=="asc"&&r!=="desc")return null;let n=null;if(e.arrayOperator===x.all?n="all":(e.arrayOperator===x.any||e.arrayOperator===x.atLeast&&e.count===1)&&(n="any"),!n)return null;let o=wO(e.condition);if(!o||o.field!==t)return null;let i=Yi.includes(o.op),s=Ff.includes(o.op);if(!i&&!s)return null;let a=r==="desc";if(!(n==="all"?a&&i||!a&&s:a&&s||!a&&i))return null;let{orderBy:d,take:p,skip:f,count:u,...m}=e;if(n==="any")return {...m,arrayOperator:x.any};let y={field:t,operator:h.exists};return {any:[{field:e.field,arrayOperator:x.empty},{all:[{field:e.field,arrayOperator:x.any,condition:y},{...m,arrayOperator:x.all,condition:{if:y,then:e.condition}}]}]}},Ka=(e,t,r)=>{let n=e;return t.filter!==void 0&&r&&(n=n.filter(r)),t.orderBy?.length&&(n=Su(n,t.orderBy)),t.skip!==void 0&&(n=n.slice(t.skip)),t.take!==void 0&&(n=n.slice(0,t.take)),n},Su=(e,t)=>[...e].sort((r,n)=>{for(let{field:o,dir:i}of t){let s=bO(me(r,o),me(n,o),i);if(s!==0)return s}return 0}),bO=(e,t,r)=>{let n=e==null,o=t==null;if(n||o)return n===o?0:n?1:-1;let i=e instanceof Date?e.getTime():e,s=t instanceof Date?t.getTime():t,a=i<s?-1:i>s?1:0;return r==="asc"?a:-a},Xn=e=>{if(!Ne(e))return e;let t=!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0;if(e.filter!==void 0&&!t){let{filter:r,...n}=e;if("aggregate"in e)return {...n,condition:e.condition===void 0?r:U([r,e.condition])};switch(e.arrayOperator){case "all":return {...n,condition:{if:r,then:e.condition??true}};case "empty":return {...n,arrayOperator:"none",condition:r};case "notEmpty":return {...n,arrayOperator:"any",condition:r};default:return {...n,condition:e.condition===void 0?r:U([r,e.condition])}}}return "aggregate"in e||e.filter!==void 0?null:SO(e)};var RO=e=>H(e,t=>{let r=le(t);if(!(r==="all"||r==="any")){if(r==="array"&&!("field"in t))return false;throw new Error("check: when data is an array, every leaf must be a fieldless arrayOperator (composable with all/any)")}}),ye=(e,t,r)=>(Array.isArray(t)&&RO(e),nt(e,t,{...r,scopes:[t]})),nt=(e,t,r)=>{if(typeof e=="boolean")return e;let n=e;switch(le(e)){case "all":return OO(n.all,t,r,n.error);case "any":return xO(n.any,t,r,n.error);case "if":return EO(n,t,r);case "array":return NO(n,r);case "aggregate":return vO(n,r);case "date":return ou(n,r.scopes,r,r.bindings);case "field":return qo(n,r.scopes,r.bindings,r);default:throw xt()}},hs=(e,t)=>({...e,scopes:[...e.scopes,t]}),OO=(e,t,r,n)=>{let o=[];for(let i of e){let s=nt(i,t,r);s!==true&&(typeof s=="string"?o.push(s):o.push("false"));}return o.length?n||(o.length===1?o[0]:`All conditions must pass: ${o.join(" AND ")}`):true},xO=(e,t,r,n)=>{let o=[];for(let i of e){let s=nt(i,t,r);if(s===true)return true;typeof s=="string"&&o.push(s);}return n||(o.length===1?o[0]:`At least one condition must pass: ${o.join(" OR ")}`)},EO=(e,t,r)=>nt(e.if,t,r)===true?nt(e.then,t,r):e.else!==void 0?nt(e.else,t,r):true,bu=(e,t)=>{if(e==null)return [];if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e},Ru=(e,t)=>nt(e,t.scopes[t.scopes.length-1],t)===true,Ga=(e,t)=>{let r=bu(sr(e.field,t.scopes),e.field),n=e.filter,o=Ka(r,e,n?s=>nt(n,s,hs(t,s))===true:void 0),i=e.condition;return i?o.filter(s=>nt(i,s,hs(t,s))===true):o},eo=(e,t,r,n)=>e.flatMap((o,i)=>{let s=r?me(o,r):o;return s==null?[]:[n(s,`${t}[${i}]${r?`.${r}`:""}`)]}),$O=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} must be a finite number`);return e},ws=(e,t,r,n)=>{let o=eo(t,r,n,$O),i=o.reduce((s,a)=>s+a,0);return e==="sum"||o.length===0?i:i/o.length},vO=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!Rt.includes(r))throw ur(r);let o=Ga(e,t),i=ws(r,o,e.field,n),s={...e,field:`${e.field} ${r}`};return qo(s,t.scopes,t.bindings,t,{value:i})},NO=(e,t)=>{let r=bu(e.field?sr(e.field,t.scopes):t.scopes[t.scopes.length-1],e.field||"(root)"),n=e.filter,o=Ka(r,e,n?f=>nt(n,f,hs(t,f))===true:void 0),i=f=>e.error||`${e.field} ${f}`,s=e.condition,a=Qi.includes(e.arrayOperator);if(a&&s===void 0)throw Ve(e.arrayOperator);let l=e.count??0;if(Ao.includes(e.arrayOperator)&&e.count===void 0)throw Vn(e.arrayOperator);let d=0,p=0;if(a&&s!==void 0){if(o.length>0&&!$a(o,Q))return i("contains only primitive values; use 'in' or 'contains' instead of array operators on primitive arrays");let f=o.map(u=>nt(s,u,hs(t,u)));d=f.filter(u=>u===true).length,p=f.filter(u=>typeof u=="string").length;}switch(e.arrayOperator){case x.empty:return !o.length||i("must be empty");case x.notEmpty:return !!o.length||i("must not be empty");case x.all:return d===o.length||i(`all elements must match (${p} failed)`);case x.any:return !!d||i("at least one element must match");case x.none:return !d||i(`no elements should match (${d} matched)`);case x.atLeast:return d>=l||i(`at least ${l} elements must match (${d} matched)`);case x.atMost:return d<=l||i(`at most ${l} elements must match (${d} matched)`);case x.exactly:return d===l||i(`exactly ${l} elements must match (${d} matched)`);default:throw fe(e.arrayOperator,"array")}};var O=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,Qt=(e,t,r)=>(Object.hasOwn(e,t)||(e[t]=r()),e[t]),k=(e,t)=>O(e?.models,t),Ae=(e,t,r)=>O(k(e,t)?.fields,r);var Le=({fieldMap:e,model:t})=>`${e}:${t}`,Ou=(e,t)=>{let r=e.indexOf(":");return r===-1?{mapName:t,modelName:e}:{mapName:e.slice(0,r),modelName:e.slice(r+1)}};var xu=(e,t,r,n)=>{let o={};for(let i of e){let s=O(i,t);if(s==null)continue;let a=String(s);if(Object.hasOwn(o,a)){let l=n==="one"?`endpoint[0] must be the "one" side of a oneToMany bridge \u2014 swap endpoints if '${r}' is the "many" side`:`oneToOne bridges require unique '${t}' on both endpoints`;throw new Error(`indexBridges: duplicate '${t}' value '${a}' on '${r}' \u2014 ${l}.`)}o[a]=i;}return o},AO=(e,t)=>{let r={};for(let n of e){let o=O(n,t);o!=null&&Qt(r,String(o),()=>[]).push(n);}return r},Eu=(e,t)=>{let r={};for(let n of e.bridges??[]){let[o,i]=n.endpoints,s=Le(o),a=Le(i),l=n.cardinality==="oneToMany"?"one":"oneToOne",d=(u,m)=>Qt(Qt(r,u,()=>({})),m,()=>({})),p=O(t,s);p&&(d(o.fieldMap,o.model)[o.on]=xu(p,o.on,s,l));let f=O(t,a);f&&(n.cardinality==="oneToMany"?d(i.fieldMap,i.model)[i.on]=AO(f,i.on):d(i.fieldMap,i.model)[i.on]=xu(f,i.on,a,"oneToOne"));}return r};var Ss=e=>{let t={maps:structuredClone(e.maps),bridges:e.bridges?structuredClone(e.bridges):void 0};for(let r of e.bridges??[]){let[n,o]=r.endpoints,i=Le(n),s=Le(o),a=k(O(t.maps,n.fieldMap),n.model),l=k(O(t.maps,o.fieldMap),o.model);if(!a)throw new Error(`stitchFieldMaps: endpoint '${i}' not found`);if(!l)throw new Error(`stitchFieldMaps: endpoint '${s}' not found`);if(n.fieldMap===o.fieldMap&&n.model===o.model)throw new Error(`stitchFieldMaps: self-bridge '${i}' to itself is not supported`);if(!O(a.fields,n.on))throw new Error(`stitchFieldMaps: endpoint '${i}' has no field '${n.on}' for join`);if(!O(l.fields,o.on))throw new Error(`stitchFieldMaps: endpoint '${s}' has no field '${o.on}' for join`);if(O(a.fields,s))throw new Error(`stitchFieldMaps: bridge '${s}' already injected on '${i}'`);if(O(l.fields,i))throw new Error(`stitchFieldMaps: bridge '${i}' already injected on '${s}'`);let d=r.cardinality==="oneToMany";a.fields[s]={kind:"bridge",type:s,isList:d},l.fields[i]={kind:"bridge",type:i,isList:false};}return t};var to=(e,t,r)=>{if(e?.isList||t?.isList){if(!(e?.isList&&!t?.isList&&bt.includes(r)))return "a list column compares with no column but by membership";if(e?.kind!=="enum"&&t?.kind!=="enum")return null}let n=[e,t].filter(o=>o?.kind==="enum");return n.length===0?null:n.length===1||e?.type!==t?.type?"an enum compares only with an enum column of its own type":Ot.includes(r)?null:`an enum column orders by declaration on the database, not as check() compares its text ('${r}')`};var We=e=>e.kind==="scalar"&&e.type==="Json",L=e=>e.kind==="object"||e.kind==="bridge",Gr=(e,t)=>e.values??O(t,e.type);var Pe=(e,t,r)=>{if(!e||!("maps"in e))return e;if(!t)throw new Error(`${r}: 'map' is a FieldMapSet \u2014 'mapName' is required to resolve which map to use.`);let n=O(e.maps,t);if(!n)throw new Error(`${r}: fieldMap set has no entry for '${t}'`);return n};var ot=(e,t)=>e.kind==="object"?{mapName:t,modelName:e.type}:e.kind==="bridge"?Ou(e.type,t):null;function*Sr(e,t,r){let n=r.split("."),o=t;for(let i=0;i<n.length;i++){let s=n[i],a=Ae(O(e,o.mapName),o.modelName,s),l=a?ot(a,o.mapName):null;if(yield {index:i,field:s,at:o,entry:a,next:l},!l)return;o={...l,relPath:[...o.relPath,s]};}}var ie=(e,t,r)=>{let n=e.split("."),o=[],i={mapName:"",modelName:r,relPath:[]};for(let{index:s,field:a,at:l,entry:d}of Sr({"":t},i,e)){let p=l.modelName;if(!d)return {kind:"fallback",hops:o};if(d.kind==="bridge")return {kind:"bridge",hops:o};let f=s===n.length-1;if(d.kind==="object"){if(!k(t,d.type))return {kind:"fallback",hops:o};if(f)return {kind:"direct",hops:o,entry:d,model:p,column:a};o.push({field:a,prefix:n.slice(0,s+1).join("."),entry:d,from:p});continue}return f?{kind:"direct",hops:o,entry:d,model:p,column:a}:We(d)?{kind:"json-path",hops:o,entry:d,model:p,column:a,stopIndex:s+1,jsonPath:n.slice(s+1)}:{kind:"past-scalar",hops:o,column:a}}return {kind:"fallback",hops:o}},br=(e,t,r)=>t&&r?ie(e,t,r):void 0,te=(e,t,r)=>{let n=br(e,t,r);return n?.kind==="direct"?n.entry:void 0},$u=(e,t,r)=>ie(e,t,r).hops.filter(n=>!n.entry.isList&&n.entry.isRequired===false).map(n=>n.prefix),Bo=(e,t,r)=>{let n=ie(e,t,r);return n.kind==="direct"&&n.entry.kind==="object"?n.entry.type:null},Rr=(e,t,r)=>ie(e,t,r).kind==="bridge",Nt=(e,t,r)=>!!t&&!!r&&Xf(e,(n,o)=>typeof n.field=="string"&&n.field!==""&&Rr(n.field,t,o),(n,o)=>(typeof n.field=="string"?Bo(n.field,t,o):o)??false,r);var zr=e=>e?.kind==="json-path"?"json-path":e?.kind!=="direct"?"unknown":e.entry.kind==="object"?e.entry.isList?"relations":"relation":e.entry.isList?"list":e.entry.kind==="enum"?"enum":vu(e.entry.type),vu=e=>e===P.Json?"json":e===P.Enum?"enum":e===P.DateTime?"instant":e===P.String?"text":"scalar",bs=(e,t,r)=>{let n=te(e.field,t,r);return n?n.kind==="scalar"&&(n.type==="String"||n.type==="Json"):e.coerceType===void 0||e.coerceType==="String"||e.coerceType==="Json"},Rs=(e,t,r)=>{if(zr(br(e,t,r))==="relations")throw ns(e)},Hr=e=>e!=="scalar"&&e!=="instant"&&e!=="list"&&e!=="enum"&&e!=="relation"&&e!=="relations",Or=(e,t)=>Hr(e)&&Nu(t),Nu=e=>typeof e=="string"||Array.isArray(e)&&e.some(Nu),Ue=(e,t,r)=>{let n=zr(br(e.field,t,r));return n==="unknown"&&e.coerceType!==void 0?vu(e.coerceType):n},Ke=e=>{if(!e.isList){if(e.kind==="enum")return P.Enum;if(!(e.kind!=="scalar"||e.type===P.Json))return vo(e.type)?e.type:void 0}};var Au=new WeakSet,xs=e=>(Au.add(e),e),Pu=e=>{if(e===null||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Tu=e=>{let t=[],r=(n,o)=>{if(n!==null&&typeof n=="object"&&Au.has(n)){t.push({path:o});return}if(Array.isArray(n))for(let[i,s]of n.entries())r(s,[...o,i]);else if(Pu(n))for(let[i,s]of Object.entries(n))r(s,[...o,i]);};return r(e,[]),t},PO=["__step","__field"],Os=e=>Array.isArray(e)?e.some(Os):Pu(e)?Object.entries(e).some(([t,r])=>PO.includes(t)||Os(r)):false;var TO={[h.equals]:"equals",[h.notEquals]:"equals",[h.lessThan]:"lt",[h.lessThanEquals]:"lte",[h.greaterThan]:"gt",[h.greaterThanEquals]:"gte"},ku=(e,t,r)=>{let n=ie(e,t,r);if(n.kind!=="direct"||n.hops.length>0)return `'${e}' is not a column of ${r} (a relation hop or an undeclared path)`;let{entry:o}=n;return L(o)?`'${e}' is a relation`:We(o)?`'${e}' is a Json column`:o.isList?`'${e}' is a list column`:o},Es=(e,t,r,n,o=false)=>{let i=e.path;if(o)return {problem:"inside a counting step (a count or relation aggregate) a groupBy carries no column reference"};let s=M(i);if(s&&s.depth>1)return {problem:`'${i}' reads an enclosing scope, which a Prisma filter can't reach`};if(!s&&n)return {problem:`'${i}' reads the root row, which a Prisma relation filter can't reach`};if(!t||!r)return {problem:"comparing two columns needs the map and model"};let a=TO[e.operator];if(!a)return {problem:`'${e.operator}' takes no column reference in Prisma`};if(e.offset!==void 0)return {problem:"an offset is arithmetic, which Prisma lacks"};let l=ku(e.field,t,r);if(typeof l=="string")return {problem:l};let d=s?s.path:i,p=ku(d,t,r);if(typeof p=="string")return {problem:p};if(l.kind!==p.kind||l.type!==p.type)return {problem:`'${e.field}' (${l.type}) and '${d}' (${p.type}) are not the same type`};let f=to(l,p,e.operator);return f?{problem:f}:l.type==="String"&&oe(e.caseInsensitive)?{problem:"a case-insensitive column comparison compiles to ILIKE"}:{key:a,ref:xs({__field:{model:r,field:d}}),field:l,column:p,columnPath:d}},$s=(e,t)=>new Error(`Path '${e}' compares to a column, which the Prisma rail supports only between columns of the same model and type: ${t}. Use toSql() or check().`),Cu=new WeakSet,za=new WeakSet,Jr=(e,t,r=false)=>(Cu.add(e),(r||t!==void 0&&za.has(t))&&za.add(e),e),Lu=e=>e!==void 0&&Cu.has(e),Mu=e=>e!==void 0&&za.has(e);var Ha=e=>({field:e,operator:"notExists"}),kO=(e,t)=>{let r=t(e);if(r===null){let i=e.operator??e.dateOperator;return W.includes(i)?{field:e.field,operator:"exists"}:true}if("aggregate"in r){let i=O(ko,r.operator);return i?{...r,operator:i}:{...r,operator:O(ts,r.operator)}}if(typeof r.dateOperator=="string"){let i=O(Gf,r.dateOperator);return i?{...r,dateOperator:i}:Kt([{...r,dateOperator:O(ts,r.dateOperator)},Ha(r.field)])}if(typeof r.arrayOperator=="string"){let i=r.count;switch(r.arrayOperator){case x.any:return {...r,arrayOperator:x.none};case x.none:return {...r,arrayOperator:x.any};case x.all:return {...r,arrayOperator:x.any,condition:Qe(r.condition,t)};case x.empty:return {...r,arrayOperator:x.notEmpty};case x.notEmpty:return {...r,arrayOperator:x.empty};case x.atLeast:return i<=0?false:{...r,arrayOperator:x.atMost,count:i-1};case x.atMost:return {...r,arrayOperator:x.atLeast,count:i+1};case x.exactly:return Kt([...i>0?[{...r,arrayOperator:x.atMost,count:i-1}]:[],{...r,arrayOperator:x.atLeast,count:i+1}])}}let n=O(ko,r.operator);if(n)return {...r,operator:n};let o=typeof r.path=="string"&&r.path!==""?M(r.path)??{depth:1,path:r.path}:null;return Kt([{...r,operator:O(ts,r.operator)},Ha(r.field),...o&&o.depth===1?[Ha(o.path)]:[]])},Qe=(e,t=r=>r)=>{if(typeof e=="boolean")return !e;let r=e;if(Array.isArray(r.all))return Kt(r.all.map(n=>Qe(n,t)));if(Array.isArray(r.any))return U(r.any.map(n=>Qe(n,t)));if("if"in r){let n=U([r.if,Qe(r.then,t)]);return r.else===void 0?n:{any:[n,U([Qe(r.if,t),Qe(r.else,t)])]}}return kO(r,t)},_u=e=>le(e)==="field"&&e.value!==void 0&&xe(e,e.value)?null:e;var Du,Fu=e=>{Du=e;},de=(e,t,r)=>Du(e,t,r);var CO=e=>{let t=M(e);throw t&&t.depth>1?new Error(xo(e,"toPrisma")):new Error(`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check().`)},it=e=>_o(e,{value:t=>{if(Os(t))throw new Error("toPrisma: a value holding a '__step' or '__field' key is reserved for the plan's own references");return t},path:t=>CO(t),bind:(t,r)=>ps(t,r,"toPrisma")}),Wo=e=>it(e),ro=e=>zt({now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},Wo),no=e=>t=>{let r=typeof t.operator=="string"||typeof t.dateOperator=="string",n=t.value!==void 0||typeof t.path=="string"&&t.path!==""||typeof t.bind=="string";if(!r||"aggregate"in t||!n||typeof t.operator=="string"&&typeof t.path=="string"&&t.path!=="")return t;let o=Ue({field:String(t.field)},e?.map,e?.model);if((o==="json"||o==="json-path")&&typeof t.operator=="string"&&_n.includes(t.operator))throw V("toPrisma",`The complement of '${t.operator}' on the Json value '${t.field}'`,"it keeps values of other types");let i=it(t),s=t.offset===void 0?void 0:it(t.offset);if(t.offset!==void 0&&s==null)return null;let{path:a,bind:l,bindOptional:d,...p}=t,f={...p,value:i,...t.offset!==void 0&&{offset:{value:s}}};return typeof t.dateOperator=="string"?i==null||xe({operator:t.dateOperator},i)?null:f:_u(f)};var st=()=>({}),Qr=st,At=()=>({OR:[]}),Ja=e=>Object.keys(e).length===0,ju=e=>{let t=Object.keys(e);return t.length===1&&t[0]==="OR"&&Array.isArray(e.OR)&&e.OR.length===0},Ze=e=>{if(e.some(ju))return At();let t=e.filter(r=>!Ja(r));return t.length===0?st():t.length===1?t[0]:{AND:t}},K=e=>{if(e.some(Ja))return st();let t=e.filter(r=>!ju(r));return t.length===0?At():t.length===1?t[0]:{OR:t}},Me=e=>Ja(e)?e:{NOT:e},Vu=(e,t,r)=>Ze(e.all.map(n=>de(n,t,r))),Iu=(e,t,r)=>K(e.any.map(n=>de(n,t,r))),qu=(e,t,r)=>{if(Nt(e,t?.map,t?.model))return Qr();let n=de(Qe(e.if,no(t)),t,r),o=de(e.then,t,r),i=K([n,o]);if(e.else!==void 0){let s=de(e.if,t,r),a=de(e.else,t,r);return Ze([i,K([s,a])])}return i};var LO=(e,t,r,n)=>{let o=k(e,t);if(!o)return null;for(let i of Object.values(o.fields))if(i.kind==="object"&&i.type===r&&(i.fromFields?.length??0)>0&&(i.toFields?.length??0)>0&&(n===void 0||i.relationName===n))return i;return null},xr=(e,t,r)=>{if(r.fromFields?.length)return r.fromFields.map((o,i)=>({here:o,there:r.toFields?.[i]??"id"}));let n=LO(e,r.type,t,r.relationName);return n?.fromFields?.length?n.fromFields.map((o,i)=>({here:n.toFields?.[i]??"id",there:o})):null},vs=(e,t,r,n)=>{if(n.relationName===void 0)return null;let o=Object.entries(k(e,n.type)?.fields??{}).filter(([i,s])=>s.kind==="object"&&s.type===t&&s.relationName===n.relationName&&!(n.type===t&&i===r));return o.length===1?{field:o[0][0],entry:o[0][1]}:null};var Zr=(e,t)=>{let r=e.split("."),n=t;for(let o=r.length-1;o>=0;o--)n={[r[o]]:n};return n};var oo=(e,t,r,n)=>{let o=e.split("."),i=ie(e,t,r);if(i.kind==="bridge")throw new Error(`'${e}' crosses a bridge: ${n.toLowerCase()} aren't supported across a bridge \u2014 no one database holds both sides.`);if(i.kind!=="direct"||i.entry.kind!=="object"){let l=i.hops.at(-1)?.entry.type??r;throw new Error(`Field '${o[i.hops.length]}' is not a relation in model '${l}'. ${n} require a relation field.`)}let s=i.hops.find(l=>l.entry.isList);if(s)throw new Error(`Intermediate field '${s.field}' in path '${e}' is a list relation. Only the final segment can be a list relation for ${n.toLowerCase()}.`);if(!i.entry.isList)throw new Error(`Field '${i.column}' is not a list relation in model '${i.model}'. ${n} only apply to one-to-many or many-to-many relations.`);let a=xr(t,i.model,i.entry);if(!a){let l=Object.values(k(t,i.entry.type)?.fields??{}).some(d=>d.kind==="object"&&d.type===i.model&&d.isList&&!d.fromFields?.length);throw new Error(l?`'${i.model}.${i.column}' is an implicit many-to-many relation. ${n} require an explicit join model with a FK \u2014 convert to an explicit @relation or use prisma.$queryRaw.`:`Cannot determine FK relationship between '${i.model}' and '${i.entry.type}'. Ensure the FieldMap contains both sides of the relation.`)}if(a.length>1)throw new Error(`${n} do not support composite FK relations ('${i.model}.${i.column}'). Use prisma.$queryRaw.`);return {through:i.hops.map(l=>l.field).join("."),target:i.entry.type,parentKey:a[0].here,targetKey:a[0].there}},Ns=(e,t,r,n,o)=>{let i={operation:"groupBy",model:t.target,args:{by:[t.targetKey],where:r,having:n},extract:t.targetKey},s=xs({__step:e.steps.length});e.steps.push(i);let a={[t.parentKey]:{in:s}},l=o?Me(a):a;return t.through?Zr(t.through,l):l};var Ye=e=>({ok:e.length===0,errors:e}),Xr=(e,t)=>{if(!e.ok)throw new Error(`${t}:
1
+ import Nt from'dayjs';import HR from'dayjs/plugin/isoWeek.js';import JR from'dayjs/plugin/quarterOfYear.js';import QR from'dayjs/plugin/timezone.js';import ZR from'dayjs/plugin/utc.js';import dO from'dayjs/plugin/isSameOrAfter.js';import uO from'dayjs/plugin/isSameOrBefore.js';import {distance}from'fastest-levenshtein';import {RE2JS}from're2js';var Oa=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var wg=typeof global=="object"&&global&&global.Object===Object&&global,mi=wg;var bg=typeof self=="object"&&self&&self.Object===Object&&self,Sg=mi||bg||Function("return this")(),ae=Sg;var Rg=ae.Symbol,Ne=Rg;var Yl=Object.prototype,Og=Yl.hasOwnProperty,xg=Yl.toString,bo=Ne?Ne.toStringTag:void 0;function Eg(e){var t=Og.call(e,bo),r=e[bo];try{e[bo]=void 0;var n=!0;}catch{}var o=xg.call(e);return n&&(t?e[bo]=r:delete e[bo]),o}var Xl=Eg;var $g=Object.prototype,vg=$g.toString;function Ng(e){return vg.call(e)}var ep=Ng;var Ag="[object Null]",Pg="[object Undefined]",tp=Ne?Ne.toStringTag:void 0;function kg(e){return e==null?e===void 0?Pg:Ag:tp&&tp in Object(e)?Xl(e):ep(e)}var je=kg;function Tg(e){return e!=null&&typeof e=="object"}var pe=Tg;var Cg="[object Symbol]";function Lg(e){return typeof e=="symbol"||pe(e)&&je(e)==Cg}var ln=Lg;function Mg(e,t){for(var r=-1,n=e==null?0:e.length,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}var rp=Mg;var _g=Array.isArray,G=_g;var np=Ne?Ne.prototype:void 0,op=np?np.toString:void 0;function ip(e){if(typeof e=="string")return e;if(G(e))return rp(e,ip)+"";if(ln(e))return op?op.call(e):"";var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var sp=ip;function Fg(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Q=Fg;function jg(e){return e}var pn=jg;var Vg="[object AsyncFunction]",Ig="[object Function]",qg="[object GeneratorFunction]",Bg="[object Proxy]";function Wg(e){if(!Q(e))return false;var t=je(e);return t==Ig||t==qg||t==Vg||t==Bg}var fn=Wg;var Ug=ae["__core-js_shared__"],gi=Ug;var ap=(function(){var e=/[^.]+$/.exec(gi&&gi.keys&&gi.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function Kg(e){return !!ap&&ap in e}var lp=Kg;var Gg=Function.prototype,zg=Gg.toString;function Hg(e){if(e!=null){try{return zg.call(e)}catch{}try{return e+""}catch{}}return ""}var Ft=Hg;var Jg=/[\\^$.*+?()[\]{}|]/g,Qg=/^\[object .+?Constructor\]$/,Zg=Function.prototype,Yg=Object.prototype,Xg=Zg.toString,ey=Yg.hasOwnProperty,ty=RegExp("^"+Xg.call(ey).replace(Jg,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ry(e){if(!Q(e)||lp(e))return false;var t=fn(e)?ty:Qg;return t.test(Ft(e))}var pp=ry;function ny(e,t){return e?.[t]}var fp=ny;function oy(e,t){var r=fp(e,t);return pp(r)?r:void 0}var Le=oy;var iy=Le(ae,"WeakMap"),yi=iy;var dp=Object.create,sy=(function(){function e(){}return function(t){if(!Q(t))return {};if(dp)return dp(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})(),up=sy;function ay(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var cp=ay;function ly(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}var hi=ly;var py=800,fy=16,dy=Date.now;function uy(e){var t=0,r=0;return function(){var n=dy(),o=fy-(n-r);if(r=n,o>0){if(++t>=py)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var mp=uy;function cy(e){return function(){return e}}var gp=cy;var my=(function(){try{var e=Le(Object,"defineProperty");return e({},"",{}),e}catch{}})(),dn=my;var gy=dn?function(e,t){return dn(e,"toString",{configurable:true,enumerable:false,value:gp(t),writable:true})}:pn,yp=gy;var yy=mp(yp),hp=yy;function hy(e,t){for(var r=-1,n=e==null?0:e.length;++r<n&&t(e[r],r,e)!==false;);return e}var wp=hy;var wy=9007199254740991,by=/^(?:0|[1-9]\d*)$/;function Sy(e,t){var r=typeof e;return t=t??wy,!!t&&(r=="number"||r!="symbol"&&by.test(e))&&e>-1&&e%1==0&&e<t}var rr=Sy;function Ry(e,t,r){t=="__proto__"&&dn?dn(e,t,{configurable:true,enumerable:true,value:r,writable:true}):e[t]=r;}var un=Ry;function Oy(e,t){return e===t||e!==e&&t!==t}var mt=Oy;var xy=Object.prototype,Ey=xy.hasOwnProperty;function $y(e,t,r){var n=e[t];(!(Ey.call(e,t)&&mt(n,r))||r===void 0&&!(t in e))&&un(e,t,r);}var cn=$y;function vy(e,t,r,n){var o=!r;r||(r={});for(var i=-1,s=t.length;++i<s;){var a=t[i],l=n?n(r[a],e[a],a,r,e):void 0;l===void 0&&(l=e[a]),o?un(r,a,l):cn(r,a,l);}return r}var gt=vy;var bp=Math.max;function Ny(e,t,r){return t=bp(t===void 0?e.length-1:t,0),function(){for(var n=arguments,o=-1,i=bp(n.length-t,0),s=Array(i);++o<i;)s[o]=n[t+o];o=-1;for(var a=Array(t+1);++o<t;)a[o]=n[o];return a[t]=r(s),cp(e,this,a)}}var Sp=Ny;function Ay(e,t){return hp(Sp(e,t,pn),e+"")}var Rp=Ay;var Py=9007199254740991;function ky(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Py}var mn=ky;function Ty(e){return e!=null&&mn(e.length)&&!fn(e)}var yt=Ty;function Cy(e,t,r){if(!Q(r))return false;var n=typeof t;return (n=="number"?yt(r)&&rr(t,r.length):n=="string"&&t in r)?mt(r[t],e):false}var wi=Cy;function Ly(e){return Rp(function(t,r){var n=-1,o=r.length,i=o>1?r[o-1]:void 0,s=o>2?r[2]:void 0;for(i=e.length>3&&typeof i=="function"?(o--,i):void 0,s&&wi(r[0],r[1],s)&&(i=o<3?void 0:i,o=1),t=Object(t);++n<o;){var a=r[n];a&&e(t,a,n,i);}return t})}var Op=Ly;var My=Object.prototype;function _y(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||My;return e===r}var gn=_y;function Dy(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var xp=Dy;var Fy="[object Arguments]";function jy(e){return pe(e)&&je(e)==Fy}var xa=jy;var Ep=Object.prototype,Vy=Ep.hasOwnProperty,Iy=Ep.propertyIsEnumerable,qy=xa((function(){return arguments})())?xa:function(e){return pe(e)&&Vy.call(e,"callee")&&!Iy.call(e,"callee")},Lr=qy;function By(){return false}var $p=By;var Ap=typeof exports=="object"&&exports&&!exports.nodeType&&exports,vp=Ap&&typeof module=="object"&&module&&!module.nodeType&&module,Wy=vp&&vp.exports===Ap,Np=Wy?ae.Buffer:void 0,Uy=Np?Np.isBuffer:void 0,Ky=Uy||$p,jt=Ky;var Gy="[object Arguments]",zy="[object Array]",Hy="[object Boolean]",Jy="[object Date]",Qy="[object Error]",Zy="[object Function]",Yy="[object Map]",Xy="[object Number]",eh="[object Object]",th="[object RegExp]",rh="[object Set]",nh="[object String]",oh="[object WeakMap]",ih="[object ArrayBuffer]",sh="[object DataView]",ah="[object Float32Array]",lh="[object Float64Array]",ph="[object Int8Array]",fh="[object Int16Array]",dh="[object Int32Array]",uh="[object Uint8Array]",ch="[object Uint8ClampedArray]",mh="[object Uint16Array]",gh="[object Uint32Array]",J={};J[ah]=J[lh]=J[ph]=J[fh]=J[dh]=J[uh]=J[ch]=J[mh]=J[gh]=true;J[Gy]=J[zy]=J[ih]=J[Hy]=J[sh]=J[Jy]=J[Qy]=J[Zy]=J[Yy]=J[Xy]=J[eh]=J[th]=J[rh]=J[nh]=J[oh]=false;function yh(e){return pe(e)&&mn(e.length)&&!!J[je(e)]}var Pp=yh;function hh(e){return function(t){return e(t)}}var yn=hh;var kp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,So=kp&&typeof module=="object"&&module&&!module.nodeType&&module,wh=So&&So.exports===kp,Ea=wh&&mi.process,bh=(function(){try{var e=So&&So.require&&So.require("util").types;return e||Ea&&Ea.binding&&Ea.binding("util")}catch{}})(),Vt=bh;var Tp=Vt&&Vt.isTypedArray,Sh=Tp?yn(Tp):Pp,hn=Sh;var Rh=Object.prototype,Oh=Rh.hasOwnProperty;function xh(e,t){var r=G(e),n=!r&&Lr(e),o=!r&&!n&&jt(e),i=!r&&!n&&!o&&hn(e),s=r||n||o||i,a=s?xp(e.length,String):[],l=a.length;for(var f in e)(t||Oh.call(e,f))&&!(s&&(f=="length"||o&&(f=="offset"||f=="parent")||i&&(f=="buffer"||f=="byteLength"||f=="byteOffset")||rr(f,l)))&&a.push(f);return a}var bi=xh;function Eh(e,t){return function(r){return e(t(r))}}var Si=Eh;var $h=Si(Object.keys,Object),Cp=$h;var vh=Object.prototype,Nh=vh.hasOwnProperty;function Ah(e){if(!gn(e))return Cp(e);var t=[];for(var r in Object(e))Nh.call(e,r)&&r!="constructor"&&t.push(r);return t}var Lp=Ah;function Ph(e){return yt(e)?bi(e):Lp(e)}var ht=Ph;function kh(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}var Mp=kh;var Th=Object.prototype,Ch=Th.hasOwnProperty;function Lh(e){if(!Q(e))return Mp(e);var t=gn(e),r=[];for(var n in e)n=="constructor"&&(t||!Ch.call(e,n))||r.push(n);return r}var _p=Lh;function Mh(e){return yt(e)?bi(e,true):_p(e)}var wt=Mh;var _h=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Dh=/^\w*$/;function Fh(e,t){if(G(e))return false;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||ln(e)?true:Dh.test(e)||!_h.test(e)||t!=null&&e in Object(t)}var wn=Fh;var jh=Le(Object,"create"),It=jh;function Vh(){this.__data__=It?It(null):{},this.size=0;}var Dp=Vh;function Ih(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Fp=Ih;var qh="__lodash_hash_undefined__",Bh=Object.prototype,Wh=Bh.hasOwnProperty;function Uh(e){var t=this.__data__;if(It){var r=t[e];return r===qh?void 0:r}return Wh.call(t,e)?t[e]:void 0}var jp=Uh;var Kh=Object.prototype,Gh=Kh.hasOwnProperty;function zh(e){var t=this.__data__;return It?t[e]!==void 0:Gh.call(t,e)}var Vp=zh;var Hh="__lodash_hash_undefined__";function Jh(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=It&&t===void 0?Hh:t,this}var Ip=Jh;function bn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}bn.prototype.clear=Dp;bn.prototype.delete=Fp;bn.prototype.get=jp;bn.prototype.has=Vp;bn.prototype.set=Ip;var $a=bn;function Qh(){this.__data__=[],this.size=0;}var qp=Qh;function Zh(e,t){for(var r=e.length;r--;)if(mt(e[r][0],t))return r;return -1}var nr=Zh;var Yh=Array.prototype,Xh=Yh.splice;function ew(e){var t=this.__data__,r=nr(t,e);if(r<0)return false;var n=t.length-1;return r==n?t.pop():Xh.call(t,r,1),--this.size,true}var Bp=ew;function tw(e){var t=this.__data__,r=nr(t,e);return r<0?void 0:t[r][1]}var Wp=tw;function rw(e){return nr(this.__data__,e)>-1}var Up=rw;function nw(e,t){var r=this.__data__,n=nr(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var Kp=nw;function Sn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}Sn.prototype.clear=qp;Sn.prototype.delete=Bp;Sn.prototype.get=Wp;Sn.prototype.has=Up;Sn.prototype.set=Kp;var or=Sn;var ow=Le(ae,"Map"),ir=ow;function iw(){this.size=0,this.__data__={hash:new $a,map:new(ir||or),string:new $a};}var Gp=iw;function sw(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var zp=sw;function aw(e,t){var r=e.__data__;return zp(t)?r[typeof t=="string"?"string":"hash"]:r.map}var sr=aw;function lw(e){var t=sr(this,e).delete(e);return this.size-=t?1:0,t}var Hp=lw;function pw(e){return sr(this,e).get(e)}var Jp=pw;function fw(e){return sr(this,e).has(e)}var Qp=fw;function dw(e,t){var r=sr(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var Zp=dw;function Rn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}Rn.prototype.clear=Gp;Rn.prototype.delete=Hp;Rn.prototype.get=Jp;Rn.prototype.has=Qp;Rn.prototype.set=Zp;var Mr=Rn;var uw="Expected a function";function va(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(uw);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],i=r.cache;if(i.has(o))return i.get(o);var s=e.apply(this,n);return r.cache=i.set(o,s)||i,s};return r.cache=new(va.Cache||Mr),r}va.Cache=Mr;var Yp=va;var cw=500;function mw(e){var t=Yp(e,function(n){return r.size===cw&&r.clear(),n}),r=t.cache;return t}var Xp=mw;var gw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,yw=/\\(\\)?/g,hw=Xp(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(gw,function(r,n,o,i){t.push(o?i.replace(yw,"$1"):n||r);}),t}),ef=hw;function ww(e){return e==null?"":sp(e)}var tf=ww;function bw(e,t){return G(e)?e:wn(e,t)?[e]:ef(tf(e))}var On=bw;function Rw(e){if(typeof e=="string"||ln(e))return e;var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var bt=Rw;function Ow(e,t){t=On(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[bt(t[r++])];return r&&r==n?e:void 0}var Ri=Ow;function xw(e,t,r){var n=e==null?void 0:Ri(e,t);return n===void 0?r:n}var rf=xw;function Ew(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}var Oi=Ew;var $w=Si(Object.getPrototypeOf,Object),xn=$w;var vw="[object Object]",Nw=Function.prototype,Aw=Object.prototype,nf=Nw.toString,Pw=Aw.hasOwnProperty,kw=nf.call(Object);function Tw(e){if(!pe(e)||je(e)!=vw)return false;var t=xn(e);if(t===null)return true;var r=Pw.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&nf.call(r)==kw}var re=Tw;function Cw(){if(!arguments.length)return [];var e=arguments[0];return G(e)?e:[e]}var xi=Cw;function Lw(){this.__data__=new or,this.size=0;}var of=Lw;function Mw(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var sf=Mw;function _w(e){return this.__data__.get(e)}var af=_w;function Dw(e){return this.__data__.has(e)}var lf=Dw;var Fw=200;function jw(e,t){var r=this.__data__;if(r instanceof or){var n=r.__data__;if(!ir||n.length<Fw-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Mr(n);}return r.set(e,t),this.size=r.size,this}var pf=jw;function En(e){var t=this.__data__=new or(e);this.size=t.size;}En.prototype.clear=of;En.prototype.delete=sf;En.prototype.get=af;En.prototype.has=lf;En.prototype.set=pf;var St=En;function Vw(e,t){return e&&gt(t,ht(t),e)}var ff=Vw;function Iw(e,t){return e&&gt(t,wt(t),e)}var df=Iw;var gf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,uf=gf&&typeof module=="object"&&module&&!module.nodeType&&module,qw=uf&&uf.exports===gf,cf=qw?ae.Buffer:void 0,mf=cf?cf.allocUnsafe:void 0;function Bw(e,t){if(t)return e.slice();var r=e.length,n=mf?mf(r):new e.constructor(r);return e.copy(n),n}var Ei=Bw;function Ww(e,t){for(var r=-1,n=e==null?0:e.length,o=0,i=[];++r<n;){var s=e[r];t(s,r,e)&&(i[o++]=s);}return i}var yf=Ww;function Uw(){return []}var $i=Uw;var Kw=Object.prototype,Gw=Kw.propertyIsEnumerable,hf=Object.getOwnPropertySymbols,zw=hf?function(e){return e==null?[]:(e=Object(e),yf(hf(e),function(t){return Gw.call(e,t)}))}:$i,$n=zw;function Hw(e,t){return gt(e,$n(e),t)}var wf=Hw;var Jw=Object.getOwnPropertySymbols,Qw=Jw?function(e){for(var t=[];e;)Oi(t,$n(e)),e=xn(e);return t}:$i,vi=Qw;function Zw(e,t){return gt(e,vi(e),t)}var bf=Zw;function Yw(e,t,r){var n=t(e);return G(e)?n:Oi(n,r(e))}var Ni=Yw;function Xw(e){return Ni(e,ht,$n)}var Ro=Xw;function eb(e){return Ni(e,wt,vi)}var Sf=eb;var tb=Le(ae,"DataView"),Ai=tb;var rb=Le(ae,"Promise"),Pi=rb;var nb=Le(ae,"Set"),ki=nb;var Rf="[object Map]",ob="[object Object]",Of="[object Promise]",xf="[object Set]",Ef="[object WeakMap]",$f="[object DataView]",ib=Ft(Ai),sb=Ft(ir),ab=Ft(Pi),lb=Ft(ki),pb=Ft(yi),_r=je;(Ai&&_r(new Ai(new ArrayBuffer(1)))!=$f||ir&&_r(new ir)!=Rf||Pi&&_r(Pi.resolve())!=Of||ki&&_r(new ki)!=xf||yi&&_r(new yi)!=Ef)&&(_r=function(e){var t=je(e),r=t==ob?e.constructor:void 0,n=r?Ft(r):"";if(n)switch(n){case ib:return $f;case sb:return Rf;case ab:return Of;case lb:return xf;case pb:return Ef}return t});var qt=_r;var fb=Object.prototype,db=fb.hasOwnProperty;function ub(e){var t=e.length,r=new e.constructor(t);return t&&typeof e[0]=="string"&&db.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var vf=ub;var cb=ae.Uint8Array,vn=cb;function mb(e){var t=new e.constructor(e.byteLength);return new vn(t).set(new vn(e)),t}var Nn=mb;function gb(e,t){var r=t?Nn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var Nf=gb;var yb=/\w*$/;function hb(e){var t=new e.constructor(e.source,yb.exec(e));return t.lastIndex=e.lastIndex,t}var Af=hb;var Pf=Ne?Ne.prototype:void 0,kf=Pf?Pf.valueOf:void 0;function wb(e){return kf?Object(kf.call(e)):{}}var Tf=wb;function bb(e,t){var r=t?Nn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var Ti=bb;var Sb="[object Boolean]",Rb="[object Date]",Ob="[object Map]",xb="[object Number]",Eb="[object RegExp]",$b="[object Set]",vb="[object String]",Nb="[object Symbol]",Ab="[object ArrayBuffer]",Pb="[object DataView]",kb="[object Float32Array]",Tb="[object Float64Array]",Cb="[object Int8Array]",Lb="[object Int16Array]",Mb="[object Int32Array]",_b="[object Uint8Array]",Db="[object Uint8ClampedArray]",Fb="[object Uint16Array]",jb="[object Uint32Array]";function Vb(e,t,r){var n=e.constructor;switch(t){case Ab:return Nn(e);case Sb:case Rb:return new n(+e);case Pb:return Nf(e,r);case kb:case Tb:case Cb:case Lb:case Mb:case _b:case Db:case Fb:case jb:return Ti(e,r);case Ob:return new n;case xb:case vb:return new n(e);case Eb:return Af(e);case $b:return new n;case Nb:return Tf(e)}}var Cf=Vb;function Ib(e){return typeof e.constructor=="function"&&!gn(e)?up(xn(e)):{}}var Ci=Ib;var qb="[object Map]";function Bb(e){return pe(e)&&qt(e)==qb}var Lf=Bb;var Mf=Vt&&Vt.isMap,Wb=Mf?yn(Mf):Lf,_f=Wb;var Ub="[object Set]";function Kb(e){return pe(e)&&qt(e)==Ub}var Df=Kb;var Ff=Vt&&Vt.isSet,Gb=Ff?yn(Ff):Df,jf=Gb;var zb=1,Hb=2,Jb=4,Vf="[object Arguments]",Qb="[object Array]",Zb="[object Boolean]",Yb="[object Date]",Xb="[object Error]",If="[object Function]",eS="[object GeneratorFunction]",tS="[object Map]",rS="[object Number]",qf="[object Object]",nS="[object RegExp]",oS="[object Set]",iS="[object String]",sS="[object Symbol]",aS="[object WeakMap]",lS="[object ArrayBuffer]",pS="[object DataView]",fS="[object Float32Array]",dS="[object Float64Array]",uS="[object Int8Array]",cS="[object Int16Array]",mS="[object Int32Array]",gS="[object Uint8Array]",yS="[object Uint8ClampedArray]",hS="[object Uint16Array]",wS="[object Uint32Array]",z={};z[Vf]=z[Qb]=z[lS]=z[pS]=z[Zb]=z[Yb]=z[fS]=z[dS]=z[uS]=z[cS]=z[mS]=z[tS]=z[rS]=z[qf]=z[nS]=z[oS]=z[iS]=z[sS]=z[gS]=z[yS]=z[hS]=z[wS]=true;z[Xb]=z[If]=z[aS]=false;function Li(e,t,r,n,o,i){var s,a=t&zb,l=t&Hb,f=t&Jb;if(r&&(s=o?r(e,n,o,i):r(e)),s!==void 0)return s;if(!Q(e))return e;var p=G(e);if(p){if(s=vf(e),!a)return hi(e,s)}else {var d=qt(e),u=d==If||d==eS;if(jt(e))return Ei(e,a);if(d==qf||d==Vf||u&&!o){if(s=l||u?{}:Ci(e),!a)return l?bf(e,df(s,e)):wf(e,ff(s,e))}else {if(!z[d])return o?e:{};s=Cf(e,d,a);}}i||(i=new St);var m=i.get(e);if(m)return m;i.set(e,s),jf(e)?e.forEach(function(g){s.add(Li(g,t,r,g,e,i));}):_f(e)&&e.forEach(function(g,w){s.set(w,Li(g,t,r,w,e,i));});var y=f?l?Sf:Ro:l?wt:ht,c=p?void 0:y(e);return wp(c||e,function(g,w){c&&(w=g,g=e[w]),cn(s,w,Li(g,t,r,w,e,i));}),s}var Mi=Li;var bS=1,SS=4;function RS(e){return Mi(e,bS|SS)}var _i=RS;var OS=1,xS=4;function ES(e,t){return t=typeof t=="function"?t:void 0,Mi(e,OS|xS,t)}var Na=ES;var $S="__lodash_hash_undefined__";function vS(e){return this.__data__.set(e,$S),this}var Bf=vS;function NS(e){return this.__data__.has(e)}var Wf=NS;function Di(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Mr;++t<r;)this.add(e[t]);}Di.prototype.add=Di.prototype.push=Bf;Di.prototype.has=Wf;var Uf=Di;function AS(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return true;return false}var Fi=AS;function PS(e,t){return e.has(t)}var Kf=PS;var kS=1,TS=2;function CS(e,t,r,n,o,i){var s=r&kS,a=e.length,l=t.length;if(a!=l&&!(s&&l>a))return false;var f=i.get(e),p=i.get(t);if(f&&p)return f==t&&p==e;var d=-1,u=true,m=r&TS?new Uf:void 0;for(i.set(e,t),i.set(t,e);++d<a;){var y=e[d],c=t[d];if(n)var g=s?n(c,y,d,t,e,i):n(y,c,d,e,t,i);if(g!==void 0){if(g)continue;u=false;break}if(m){if(!Fi(t,function(w,R){if(!Kf(m,R)&&(y===w||o(y,w,r,n,i)))return m.push(R)})){u=false;break}}else if(!(y===c||o(y,c,r,n,i))){u=false;break}}return i.delete(e),i.delete(t),u}var ji=CS;function LS(e){var t=-1,r=Array(e.size);return e.forEach(function(n,o){r[++t]=[o,n];}),r}var Gf=LS;function MS(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n;}),r}var zf=MS;var _S=1,DS=2,FS="[object Boolean]",jS="[object Date]",VS="[object Error]",IS="[object Map]",qS="[object Number]",BS="[object RegExp]",WS="[object Set]",US="[object String]",KS="[object Symbol]",GS="[object ArrayBuffer]",zS="[object DataView]",Hf=Ne?Ne.prototype:void 0,Aa=Hf?Hf.valueOf:void 0;function HS(e,t,r,n,o,i,s){switch(r){case zS:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return false;e=e.buffer,t=t.buffer;case GS:return !(e.byteLength!=t.byteLength||!i(new vn(e),new vn(t)));case FS:case jS:case qS:return mt(+e,+t);case VS:return e.name==t.name&&e.message==t.message;case BS:case US:return e==t+"";case IS:var a=Gf;case WS:var l=n&_S;if(a||(a=zf),e.size!=t.size&&!l)return false;var f=s.get(e);if(f)return f==t;n|=DS,s.set(e,t);var p=ji(a(e),a(t),n,o,i,s);return s.delete(e),p;case KS:if(Aa)return Aa.call(e)==Aa.call(t)}return false}var Jf=HS;var JS=1,QS=Object.prototype,ZS=QS.hasOwnProperty;function YS(e,t,r,n,o,i){var s=r&JS,a=Ro(e),l=a.length,f=Ro(t),p=f.length;if(l!=p&&!s)return false;for(var d=l;d--;){var u=a[d];if(!(s?u in t:ZS.call(t,u)))return false}var m=i.get(e),y=i.get(t);if(m&&y)return m==t&&y==e;var c=true;i.set(e,t),i.set(t,e);for(var g=s;++d<l;){u=a[d];var w=e[u],R=t[u];if(n)var b=s?n(R,w,u,t,e,i):n(w,R,u,e,t,i);if(!(b===void 0?w===R||o(w,R,r,n,i):b)){c=false;break}g||(g=u=="constructor");}if(c&&!g){var S=e.constructor,v=t.constructor;S!=v&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof v=="function"&&v instanceof v)&&(c=false);}return i.delete(e),i.delete(t),c}var Qf=YS;var XS=1,Zf="[object Arguments]",Yf="[object Array]",Vi="[object Object]",eR=Object.prototype,Xf=eR.hasOwnProperty;function tR(e,t,r,n,o,i){var s=G(e),a=G(t),l=s?Yf:qt(e),f=a?Yf:qt(t);l=l==Zf?Vi:l,f=f==Zf?Vi:f;var p=l==Vi,d=f==Vi,u=l==f;if(u&&jt(e)){if(!jt(t))return false;s=true,p=false;}if(u&&!p)return i||(i=new St),s||hn(e)?ji(e,t,r,n,o,i):Jf(e,t,l,r,n,o,i);if(!(r&XS)){var m=p&&Xf.call(e,"__wrapped__"),y=d&&Xf.call(t,"__wrapped__");if(m||y){var c=m?e.value():e,g=y?t.value():t;return i||(i=new St),o(c,g,r,n,i)}}return u?(i||(i=new St),Qf(e,t,r,n,o,i)):false}var ed=tR;function td(e,t,r,n,o){return e===t?true:e==null||t==null||!pe(e)&&!pe(t)?e!==e&&t!==t:ed(e,t,r,n,td,o)}var An=td;var rR=1,nR=2;function oR(e,t,r,n){var o=r.length,i=o,s=!n;if(e==null)return !i;for(e=Object(e);o--;){var a=r[o];if(s&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return false}for(;++o<i;){a=r[o];var l=a[0],f=e[l],p=a[1];if(s&&a[2]){if(f===void 0&&!(l in e))return false}else {var d=new St;if(n)var u=n(f,p,l,e,t,d);if(!(u===void 0?An(p,f,rR|nR,n,d):u))return false}}return true}var rd=oR;function iR(e){return e===e&&!Q(e)}var Ii=iR;function sR(e){for(var t=ht(e),r=t.length;r--;){var n=t[r],o=e[n];t[r]=[n,o,Ii(o)];}return t}var nd=sR;function aR(e,t){return function(r){return r==null?false:r[e]===t&&(t!==void 0||e in Object(r))}}var qi=aR;function lR(e){var t=nd(e);return t.length==1&&t[0][2]?qi(t[0][0],t[0][1]):function(r){return r===e||rd(r,e,t)}}var od=lR;function pR(e,t){return e!=null&&t in Object(e)}var id=pR;function fR(e,t,r){t=On(t,e);for(var n=-1,o=t.length,i=false;++n<o;){var s=bt(t[n]);if(!(i=e!=null&&r(e,s)))break;e=e[s];}return i||++n!=o?i:(o=e==null?0:e.length,!!o&&mn(o)&&rr(s,o)&&(G(e)||Lr(e)))}var sd=fR;function dR(e,t){return e!=null&&sd(e,t,id)}var ad=dR;var uR=1,cR=2;function mR(e,t){return wn(e)&&Ii(t)?qi(bt(e),t):function(r){var n=rf(r,e);return n===void 0&&n===t?ad(r,e):An(t,n,uR|cR)}}var ld=mR;function gR(e){return function(t){return t?.[e]}}var pd=gR;function yR(e){return function(t){return Ri(t,e)}}var fd=yR;function hR(e){return wn(e)?pd(bt(e)):fd(e)}var dd=hR;function wR(e){return typeof e=="function"?e:e==null?pn:typeof e=="object"?G(e)?ld(e[0],e[1]):od(e):dd(e)}var ud=wR;function bR(e){return function(t,r,n){for(var o=-1,i=Object(t),s=n(t),a=s.length;a--;){var l=s[e?a:++o];if(r(i[l],l,i)===false)break}return t}}var cd=bR;var SR=cd(),Bi=SR;function RR(e,t){return e&&Bi(e,t,ht)}var md=RR;function OR(e,t){return function(r,n){if(r==null)return r;if(!yt(r))return e(r,n);for(var o=r.length,i=t?o:-1,s=Object(r);(t?i--:++i<o)&&n(s[i],i,s)!==false;);return r}}var gd=OR;var xR=gd(md),yd=xR;function ER(e,t,r){(r!==void 0&&!mt(e[t],r)||r===void 0&&!(t in e))&&un(e,t,r);}var Oo=ER;function $R(e){return pe(e)&&yt(e)}var hd=$R;function vR(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}var xo=vR;function NR(e){return gt(e,wt(e))}var wd=NR;function AR(e,t,r,n,o,i,s){var a=xo(e,r),l=xo(t,r),f=s.get(l);if(f){Oo(e,r,f);return}var p=i?i(a,l,r+"",e,t,s):void 0,d=p===void 0;if(d){var u=G(l),m=!u&&jt(l),y=!u&&!m&&hn(l);p=l,u||m||y?G(a)?p=a:hd(a)?p=hi(a):m?(d=false,p=Ei(l,true)):y?(d=false,p=Ti(l,true)):p=[]:re(l)||Lr(l)?(p=a,Lr(a)?p=wd(a):(!Q(a)||fn(a))&&(p=Ci(l))):d=false;}d&&(s.set(l,p),o(p,l,n,i,s),s.delete(l)),Oo(e,r,p);}var bd=AR;function Sd(e,t,r,n,o){e!==t&&Bi(t,function(i,s){if(o||(o=new St),Q(i))bd(e,t,s,r,Sd,n,o);else {var a=n?n(xo(e,s),i,s+"",e,t,o):void 0;a===void 0&&(a=i),Oo(e,s,a);}},wt);}var Rd=Sd;function PR(e,t){return An(e,t)}var Bt=PR;var kR=Op(function(e,t,r){Rd(e,t,r);}),Wi=kR;function TR(e,t,r,n){if(!Q(e))return e;t=On(t,e);for(var o=-1,i=t.length,s=i-1,a=e;a!=null&&++o<i;){var l=bt(t[o]),f=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(o!=s){var p=a[l];f=n?n(p,l,a):void 0,f===void 0&&(f=Q(p)?p:rr(t[o+1])?[]:{});}cn(a,l,f),a=a[l];}return e}var Od=TR;function CR(e,t,r){return e==null?e:Od(e,t,r)}var Eo=CR;function LR(e,t){var r;return yd(e,function(n,o,i){return r=t(n,o,i),!r}),!!r}var xd=LR;function MR(e,t,r){var n=G(e)?Fi:xd;return r&&wi(e,t,r)&&(t=void 0),n(e,ud(t))}var Pa=MR;var _R=/^(\$+)\.(.*)$/,M=e=>{let t=_R.exec(e);return t?{depth:t[1].length,path:t[2]}:null},ka=(e,t,r)=>`Scope ref '${e}' needs depth ${t} but only ${r} ${r===1?"scope is":"scopes are"} in reach`,ze=(e,t)=>{let r=M(e);return r?r.depth>t.length?{outOfBounds:ka(e,r.depth,t.length)}:{scope:t[t.length-r.depth],path:r.path}:{scope:t[t.length-1],path:e}},DR=/\[(\d+)\]|\[(["'])(.*?)\2\]|([^.[\]]+)/g,FR=e=>e===""?[""]:[...e.matchAll(DR)].map(t=>t[1]??t[3]??t[4]),jR=(e,t)=>{if(e==null)return;let r=Object(e);return Object.hasOwn(r,t)?r[t]:void 0},ge=(e,t)=>FR(t).reduce(jR,e),ar=(e,t)=>{let r=ze(e,t);if("outOfBounds"in r)throw new Error(r.outOfBounds);return ge(r.scope,r.path)},Ui=(e,t)=>M(e)?ar(e,t):ge(t[0],e),$o=(e,t)=>`Scope ref '${e}' is not supported by ${t}(); evaluate with check()`,Ki=(e,t)=>{if(!(!("field"in e)||typeof e.field!="string")&&M(e.field))throw new Error($o(e.field,t))};var kn={postgres:"postgres",mysql:"mysql"},$d=e=>Object.values(kn).includes(e),Ta={string:{caseInsensitive:false,fuzzy:false},prismaOptions:{datasource:{provider:"postgresql"}},sql:{dialect:kn.postgres},clock:{finestUnit:"second"}},VR=new Set(Object.keys(Ta)),Pn=e=>Na(e,t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!re(t)?t:void 0),Ed=Symbol.for("@inixiative/json-rules/engineGlobals@3"),vo=()=>{let e=globalThis;return e[Ed]??={store:_i(Ta),registry:new Map},e[Ed]},IR=e=>{let t={};for(let[r,n]of Object.entries(e))r.includes(".")?Eo(t,r,Pn(n)):t[r]=Wi(t[r]??{},Pn(n));return t},vd=(e,t,r)=>{for(let[n,o]of Object.entries(r)){let i=`${t}.${n}`;ge(e,i)===void 0&&Eo(e,i,Pn(o));}},qR=e=>e!=null&&typeof e.then=="function",BR=(e,t)=>{if(!e||e.includes("."))throw new Error(`engine globals namespace "${e}" must be one non-empty segment`);if(VR.has(e))throw new Error(`engine globals namespace "${e}" belongs to json-rules`);let{store:r,registry:n}=vo(),o=n.get(e);if(o){if(Bt(o,t))return;throw new Error(`engine globals namespace "${e}" is registered with other defaults`)}n.set(e,Pn(t)),vd(r,e,t);},Xe={set:(e,t)=>{Eo(vo().store,e,Pn(t));},get:e=>ge(vo().store,e),reset:()=>{let e=vo();e.store=_i(Ta);for(let[t,r]of e.registry)vd(e.store,t,r);},with:(e,t)=>{let r=vo(),n=r.store;r.store=Wi(Pn(n),IR(e));try{let o=t();if(qR(o))throw new Error("engineGlobals.with() callback must be synchronous (it returned a Promise).");return o}finally{r.store=n;}}},WR=new Set(["postgresql","cockroachdb","mongodb"]),Nd=e=>WR.has(e),oe=e=>e??Xe.get("string.caseInsensitive")??false,Gi=e=>{let t=e??Xe.get("string.fuzzy")??false;return t?t===true?{}:t:false};var h={equals:"equals",notEquals:"notEquals",lessThan:"lessThan",lessThanEquals:"lessThanEquals",greaterThan:"greaterThan",greaterThanEquals:"greaterThanEquals",contains:"contains",notContains:"notContains",in:"in",notIn:"notIn",matches:"matches",notMatches:"notMatches",between:"between",notBetween:"notBetween",isEmpty:"isEmpty",notEmpty:"notEmpty",exists:"exists",notExists:"notExists",startsWith:"startsWith",notStartsWith:"notStartsWith",endsWith:"endsWith",notEndsWith:"notEndsWith"},x={all:"all",any:"any",none:"none",atLeast:"atLeast",atMost:"atMost",exactly:"exactly",empty:"empty",notEmpty:"notEmpty"},N={before:"before",after:"after",onOrBefore:"onOrBefore",onOrAfter:"onOrAfter",notBefore:"notBefore",notAfter:"notAfter",within:"within",notWithin:"notWithin",between:"between",notBetween:"notBetween",dayIn:"dayIn",dayNotIn:"dayNotIn"};var P={String:"String",Boolean:"Boolean",Int:"Int",BigInt:"BigInt",Float:"Float",Decimal:"Decimal",DateTime:"DateTime",Json:"Json",Bytes:"Bytes",Enum:"Enum"},X=["Int","Float","Decimal","BigInt"],Tn=["String",...X,"DateTime"],lr=["String"],zi=["String","Boolean","Int","BigInt","Float","Decimal","DateTime","Enum"],Hi=Object.values(P),Ad=Hi,UR={check:"check",toPrisma:"toPrisma",toSql:"toSql"},Ao=e=>typeof e=="string"&&Object.hasOwn(P,e),_=["check","toPrisma","toSql"],Cn=["check","toPrisma"],Ji=["check","toSql"],Ut={none:"none",scalar:"scalar",ordered:"ordered",array:"array",string:"string",pattern:"pattern",range:"range",dateValue:"dateValue",dateRange:"dateRange",dateWindow:"dateWindow",dayList:"dayList",count:"count",predicate:"predicate"},Ln={[h.equals]:{kinds:zi,targets:_,valueShape:"scalar"},[h.notEquals]:{negates:h.equals,kinds:zi,targets:_,valueShape:"scalar"},[h.lessThan]:{kinds:Tn,targets:_,valueShape:"ordered",comparator:"lt"},[h.lessThanEquals]:{kinds:Tn,targets:_,valueShape:"ordered",comparator:"lte"},[h.greaterThan]:{kinds:Tn,targets:_,valueShape:"ordered",comparator:"gt"},[h.greaterThanEquals]:{kinds:Tn,targets:_,valueShape:"ordered",comparator:"gte"},[h.in]:{kinds:zi,targets:_,valueShape:"array"},[h.notIn]:{negates:h.in,kinds:zi,targets:_,valueShape:"array"},[h.contains]:{kinds:lr,targets:_,valueShape:"string"},[h.notContains]:{negates:h.contains,kinds:lr,targets:_,valueShape:"string"},[h.startsWith]:{kinds:lr,targets:_,valueShape:"string"},[h.notStartsWith]:{negates:h.startsWith,kinds:lr,targets:_,valueShape:"string"},[h.endsWith]:{kinds:lr,targets:_,valueShape:"string"},[h.notEndsWith]:{negates:h.endsWith,kinds:lr,targets:_,valueShape:"string"},[h.matches]:{kinds:lr,targets:Ji,valueShape:"pattern"},[h.notMatches]:{negates:h.matches,kinds:lr,targets:Ji,valueShape:"pattern"},[h.between]:{kinds:Tn,targets:_,valueShape:"range"},[h.notBetween]:{negates:h.between,kinds:Tn,targets:_,valueShape:"range"},[h.isEmpty]:{kinds:Ad,targets:_,valueShape:"none"},[h.notEmpty]:{kinds:Ad,targets:_,valueShape:"none"},[h.exists]:{kinds:Hi,targets:_,valueShape:"none"},[h.notExists]:{kinds:Hi,targets:_,valueShape:"none"}},Mn={[N.before]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"lt"},[N.after]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"gt"},[N.onOrBefore]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[N.onOrAfter]:{kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[N.notBefore]:{negates:N.before,kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[N.notAfter]:{negates:N.after,kinds:["DateTime"],targets:_,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[N.within]:{kinds:["DateTime"],targets:_,valueShape:"dateWindow",acceptsExpr:true},[N.notWithin]:{negates:N.within,kinds:["DateTime"],targets:_,valueShape:"dateWindow",acceptsExpr:true},[N.between]:{kinds:["DateTime"],targets:_,valueShape:"dateRange",acceptsExpr:true},[N.notBetween]:{negates:N.between,kinds:["DateTime"],targets:_,valueShape:"dateRange",acceptsExpr:true},[N.dayIn]:{kinds:["DateTime"],targets:Ji,valueShape:"dayList",acceptsExpr:false},[N.dayNotIn]:{negates:N.dayIn,kinds:["DateTime"],targets:Ji,valueShape:"dayList",acceptsExpr:false}},No={[x.all]:{targets:Cn,valueShape:"predicate",holdsOnNoRows:true},[x.any]:{targets:Cn,valueShape:"predicate",holdsOnNoRows:false},[x.none]:{targets:Cn,valueShape:"predicate",holdsOnNoRows:true},[x.atLeast]:{targets:Cn,valueShape:"count",comparator:"gte",holdsOnNoRows:true},[x.atMost]:{targets:Cn,valueShape:"count",comparator:"lte",holdsOnNoRows:true},[x.exactly]:{targets:Cn,valueShape:"count",comparator:"equals",holdsOnNoRows:true},[x.empty]:{targets:_,valueShape:"none",holdsOnNoRows:true},[x.notEmpty]:{targets:_,valueShape:"none",holdsOnNoRows:false}},Pd={field:Ln,date:Mn,array:No},Wt=(e,t)=>Object.hasOwn(Pd[t],e)?Pd[t][e]:void 0,Dn=e=>typeof e.operator=="string"?Wt(e.operator,"field"):typeof e.dateOperator=="string"?Wt(e.dateOperator,"date"):void 0,pr=(e,t)=>Wt(e,t)?.comparator,Kt=(e,t)=>{let r=Wt(e,t);if(!r)throw de(e,t);return r.valueShape},Qi=(e,t,r)=>Wt(e,t)?.targets.includes(r)??false,KR=(e,t)=>{let r=Object.keys(Ln).filter(o=>{let i=Ln[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))}),n=Object.keys(Mn).filter(o=>{let i=Mn[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))});return {field:r,date:n}},GR=e=>Object.keys(No).filter(t=>e?No[t].targets.includes(e):true),kd=[...Object.entries(Ln),...Object.entries(Mn)],Ve=(...e)=>kd.flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),fr=Ve("none"),Fn=Ve("ordered"),Po=Ve("dateWindow"),He=Ve("range","dateRange","dateWindow"),Td=Ve("ordered","string","pattern","array"),Rt=[h.contains,h.notContains],Ca=[h.equals,h.notEquals,h.in,h.notIn,h.exists,h.notExists],Zi=Ve("scalar","ordered","range"),_n={sum:{result:"number",comparable:true},avg:{result:"number",comparable:true},count:{result:"count",comparable:false},min:{result:"element",comparable:false},max:{result:"element",comparable:false},distinct:{result:"list",comparable:false}},Ot=Object.keys(_n).filter(e=>_n[e].comparable),La=Object.keys(_n),Yi=e=>typeof e=="string"&&Object.hasOwn(_n,e),Cd=[...X,"DateTime"],Ld=["String","Enum","DateTime","Boolean",...X],zR=()=>Zi,xt=Ve("scalar"),dr=Ve("array"),Md=Ve("scalar","array"),_d=Ve("dayList"),Dd=Ve("dateRange"),Fd=Ve("scalar","ordered","range","dateValue","dateRange"),jd=(...e)=>Object.entries(No).flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),ko=jd("count"),Ma=e=>typeof e.condition!="object"||e.condition===null?null:e.arrayOperator===x.atLeast&&e.count===1?x.any:(e.arrayOperator===x.atMost||e.arrayOperator===x.exactly)&&e.count===0?x.none:null,To=e=>ko.includes(e.arrayOperator)&&Ma(e)===null,Xi=jd("predicate","count"),_a=[x.any,x.all,x.none,x.empty,x.notEmpty],Vd=[x.any,x.atLeast],W=[...Object.entries(Ln),...Object.entries(Mn)].flatMap(([e,t])=>t.negates?[e]:[]),es=[...W,h.isEmpty,h.notExists],Id=Object.entries(No).flatMap(([e,t])=>t.holdsOnNoRows?[e]:[]),qd=W.filter(e=>Ve("string").includes(e)),jn=W.filter(e=>He.includes(e)),Bd=(...e)=>kd.flatMap(([t,r])=>r.comparator&&e.includes(r.comparator)&&!W.includes(t)?[t]:[]),ts=Bd("lt","lte"),Wd=Bd("gt","gte"),Ud=["Int","BigInt"],Kd=[...X,"DateTime","Boolean","String"],Gd=["Int","BigInt","Float","Boolean","String"],zd=["scalar","ordered","string"],Co=["second","minute","hour","day","week","month","quarter","year"],et={years:{interval:"months",factor:12,calendar:true,clock:"year"},quarters:{interval:"months",factor:3,calendar:true,clock:"quarter"},months:{interval:"months",factor:1,calendar:true,clock:"month"},weeks:{interval:"days",factor:7,calendar:true,clock:"week"},days:{interval:"days",factor:1,calendar:true,clock:"day"},hours:{interval:"secs",factor:3600,calendar:false,clock:"hour"},minutes:{interval:"secs",factor:60,calendar:false,clock:"minute"},seconds:{interval:"secs",factor:1,calendar:false,clock:"second"}},Hd=["months","days","secs"],Vn=e=>Object.hasOwn(et,e),Dr=e=>Vn(e)&&et[e].calendar,rs={year:"year",quarter:"quarter",month:"month",week:"week",isoWeek:"week",day:"day",hour:"hour",minute:"minute",second:"second"},ns=Object.keys(rs),Jd=e=>typeof e=="string"&&Object.hasOwn(rs,e),In=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],Qd=e=>In.includes(e.toLowerCase()),Zd=(e,t=[])=>Object.fromEntries([...Object.entries(e).flatMap(([r,n])=>n.negates?[[n.negates,r]]:[]),...t].flatMap(([r,n])=>[[r,n],[n,r]])),Lo=Zd(Ln,[[h.isEmpty,h.notEmpty],[h.exists,h.notExists]]),Yd=Zd(Mn),os={[h.lessThan]:h.greaterThanEquals,[h.lessThanEquals]:h.greaterThan,[h.greaterThan]:h.lessThanEquals,[h.greaterThanEquals]:h.lessThan,[N.onOrBefore]:N.after,[N.onOrAfter]:N.before};var is=e=>new Error(`${e}: ArrayRule.field is required (fieldless arrayOps are check-only)`),de=(e,t)=>new Error(`Unknown ${t} operator: ${String(e)}`),Xd=(e,t)=>new Error(`'${e}' is finer than the engine's clock.finestUnit '${t}'`),qn=e=>new Error(`${e} requires a count`),tt=e=>new Error(`${e} requires a range date expression (a period or rolling window), not a single point`),Ie=e=>new Error(`${e} requires a condition to check against array elements`),ur=e=>new Error(`'${e}' is a relation: it exists or not; compare its fields with '${e}.<field>'.`),ss=e=>new Error(`'${e}' is a list of rows: compare it with an arrayOperator (any / all / none / empty / atLeast \u2026).`),as=e=>Rt.includes(e.operator)&&Gi(e.fuzzy)?new Error("Fuzzy matching has no compiled form \u2014 evaluate it in memory with check()."):null,ls=(e,t)=>!Fn.includes(e)&&!He.includes(e)?null:(He.includes(e)&&Array.isArray(t)?t:[t]).some(n=>typeof n=="boolean"||typeof n=="object"&&n!==null&&!(n instanceof Date))?new Error(`'${e}' orders numbers, strings and dates; it can't compare ${JSON.stringify(t)}`):null,cr=e=>new Error(`aggregate.mode must be one of ${Ot.join(" / ")}, not '${String(e)}'`),ps=e=>new Error(`aggregate.mode must be one of ${La.join(" / ")}, not '${String(e)}'`),Bn=e=>new Error(`${e}: a value expression is exactly one of: { value }, { path }, { bind }, an aggregate ({ field, aggregate }), if / then [/ else], or a list`),Wn=e=>new Error(`${e}: an aggregate value is the aggregate itself and takes no operator or value; compare it in a rule`),Et=()=>new Error("A condition is exactly one of: a field, date, array or aggregate rule, all, any, or if/then[/else]"),V=(e,t,r)=>new Error(`${t} has no ${e==="toSql"?"SQL":"Prisma"} form${r?` (${r})`:""}; use ${e==="toSql"?"check()":"toSql() or check()"}.`),$t=e=>new Error(`Windowing (filter/orderBy/take/skip) is not supported by ${e}() for this rule; evaluate with check()${e==="toPrisma"?" \u2014 toPrisma compiles a filter alone and an extremal take: 1":""}.`),Un=(e,t)=>new Error(`'${e}' reads through the to-many relation '${t.prefix}'; compare its rows with an arrayOperator rule on '${t.prefix}'.`),Kn=(e,t)=>new Error(`'${e}' continues past '${t}', which is not a Json column`),C=class extends Error{name="UsageError"};Nt.extend(ZR);Nt.extend(QR);Nt.extend(JR);Nt.extend(HR);var ee=e=>{if(!re(e))return false;let t=e;return "ago"in t||"ahead"in t||"this"in t||"last"in t||"next"in t||"start"in t||"end"in t},qe="UTC",Mo=e=>{if(e.now===void 0)throw new C("date expressions require `now` to be supplied to the evaluator");let t=Nt(e.now).tz(e.timeZone);if(!t.isValid())throw new C(`invalid \`now\`: ${String(e.now)}`);return t},Da=(e,t)=>Object.entries(e).reduce((r,[n,o])=>et[n].interval===t?r+o*et[n].factor:r,0),eu="YYYY-MM-DDTHH:mm:ss.SSS",mr=(e,t,r,n)=>{let o=Da(t,"months"),i=Da(t,"days"),s=Da(t,"secs"),a=Nt.utc(e.tz(n).format(eu));return o&&(a=a.add(r*o,"month")),i&&(a=a.add(r*i,"day")),s&&(a=a.add(r*s*1e3,"millisecond")),Nt.tz(a.format(eu),n)},YR=e=>"ago"in e||"ahead"in e,fs=(e,t)=>t===-1?{ago:e}:{ahead:e},Re=e=>YR(e)?"ago"in e?[e.ago,-1]:[e.ahead,1]:null,_o=e=>"this"in e||"last"in e||"next"in e,Do=e=>"start"in e||"end"in e,Gn=e=>"this"in e?e.this:"last"in e?e.last:e.next,XR=e=>{let t=Gn(e);if(typeof t!="string"||!ns.includes(t))throw new Error(`Unknown period unit '${String(t)}'`);return t},eO=(e,t)=>e==="week"?t.weekStart==="sunday"?"week":"isoWeek":e,Fa=(e,t)=>{let r=Mo(t),n=XR(e),o=n==="isoWeek"?"week":n,i=r;"last"in e?i=r.subtract(1,o):"next"in e&&(i=r.add(1,o));let s=eO(n,t);return [i.startOf(s),i.endOf(s)]},ja=(e,t)=>{let r=Re(e);if(r)return mr(Mo(t),...r,t.timeZone);if(Do(e)){let n="start"in e?e.start:e.end,[o,i]=Fa(n,t);return "start"in e?o:i}throw new Error("a point operator requires a rolling or start/end edge expression, not a bare period")},zn=(e,t,r)=>{if(_o(e)){let[n,o]=Fa(e,r),i=Dn({dateOperator:t})?.negates??t;return ts.includes(i)?n:o}return ja(e,r)},Hn=(e,t)=>{if(_o(e))return Fa(e,t);let r=Re(e);if(r){let n=Mo(t),o=mr(n,...r,t.timeZone);return r[1]===-1?[o,n]:[n,o]}throw tt("within")};var tu=["value","bind","path"],Oe=e=>typeof e.path=="string"&&e.path!=="",jr=e=>Oe(e)?M(e.path)??{depth:0,path:e.path}:null,Fo=(e,t)=>{if(e.value!==void 0)return t.value(e.value);if(e.bind!==void 0)return t.bind(e.bind,e.bindOptional);if(Oe(e))return t.path(e.path);throw new Error("No value, path or bind specified")},ds=e=>re(e)&&(e.value!==void 0||Oe(e)||typeof e.bind=="string"),Va=(e,t,r)=>{if(!r||!Object.hasOwn(r,e)){if(t===true)return null;throw new C(`Missing binding for "${e}"`)}let n=r[e];return n===void 0?null:n},us=(e,t,r)=>{if(t===true)return null;throw new C(`Unresolved binding '${e}' \u2014 resolve bindings (bindRule / bindLens) before compiling with ${r}().`)},Be=(e,t,r)=>Fo(e,{value:n=>n,bind:(n,o)=>Va(n,o,r),path:n=>Ui(n,t)??null});var nu=e=>typeof e=="object"&&e!==null,cs=e=>"if"in e||"then"in e||"else"in e,xe=e=>"arrayOperator"in e||"aggregate"in e,ou=e=>[...["all","any"].flatMap(t=>Array.isArray(e[t])?e[t].map((r,n)=>({key:t,index:n,child:r,nested:false})):[]),...cs(e)?["if","then","else"].flatMap(t=>e[t]!==void 0?[{key:t,child:e[t],nested:false}]:[]):[],...["condition","filter"].flatMap(t=>e[t]!==void 0?[{key:t,child:e[t],nested:true}]:[])],We=e=>"all"in e||"any"in e||cs(e),H=(e,t,r)=>{if(!nu(e))return;let n=e,o=t(n,r),i=o===void 0?r:o;for(let{child:s,nested:a}of ou(n))a?i!==false&&H(s,t,i):H(s,t,r);},iu=(e,t,r,n)=>{let o=false;return H(e,(i,s)=>(!o&&t(i,s)&&(o=true),o?false:r?.(i,s)),n),o},gr=(e,t,r)=>{if(!nu(e))return e;let n=r,o={...e},i=t.rewrite?t.rewrite(o,n):o,s=ou(i),a=s.some(f=>f.nested)&&t.below?t.below(i,n):n;for(let f of ["all","any"])Array.isArray(i[f])&&(i[f]=[...i[f]]);for(let{key:f,index:p,child:d,nested:u}of s){if(u&&a===false)continue;let m=gr(d,t,u?a:n);p===void 0?i[f]=m:i[f][p]=m;}let l=t.after?t.after(i,n):i;return l===i&&tO(i,e)?e:l},tO=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?false:r.every(n=>{let[o,i]=[e[n],t[n]];return o===i?true:Array.isArray(o)&&Array.isArray(i)&&o.length===i.length&&o.every((s,a)=>s===i[a])})},rO=(e,t)=>re(e)?Object.fromEntries(Object.entries(e).map(([r,n])=>[r,ds(n)?t(n,Dr(r)?"whole":"number"):n])):e,Ia=(e,t)=>{let r=ee(e)?Re(e):null;return r?fs(rO(r[0],t),r[1]):e},Jn=(e,t)=>{let r="dateOperator"in e;if(!r&&!("operator"in e))return e;let n=e;if(r&&e.value!==void 0){let o=Array.isArray(e.value)?e.value.map(i=>Ia(i,t)):Ia(e.value,t);n={...n,value:o};}if(ds(e.offset)){let o=r?{...e.offset,...e.offset.value!==void 0&&{value:Ia(e.offset.value,t)}}:e.offset;n={...n,offset:t(o,r?"shift":"number")};}return ds(n)&&(n=t(n,"value")),n},jo=e=>{let t=[];return Jn(e,(r,n)=>(t.push({source:r,role:n}),r)),t},Vo=e=>jo(e).flatMap(({source:t,role:r})=>Oe(t)?[{ref:t.path,role:r}]:[]),yr=e=>Vo(e).map(t=>t.ref),Qn=e=>[...Array.isArray(e.orderBy)?e.orderBy.flatMap(t=>typeof t?.field=="string"?[t.field]:[]):[],...typeof e.aggregate?.field=="string"?[e.aggregate.field]:[]],nO={all:"all",any:"any",if:"if",field:"field",aggregate:"aggregate",array:"array",date:"date"},Vr=()=>(e,t)=>({required:[...e],optional:[...t]}),ru={all:Vr()(["all"],["error"]),any:Vr()(["any"],["error"]),if:Vr()(["if","then"],["else","error"]),field:Vr()(["field","operator"],["value","path","bind","bindOptional","offset","caseInsensitive","fuzzy","coerceType","error"]),aggregate:Vr()(["field","aggregate","operator"],["value","path","bind","bindOptional","condition","filter","orderBy","take","skip","error"]),array:Vr()(["arrayOperator"],["field","condition","count","filter","orderBy","take","skip","error"]),date:Vr()(["field","dateOperator"],["value","path","bind","bindOptional","offset","error"])},oO=e=>({required:[...ru[e].required],optional:[...ru[e].optional]}),le=e=>{let t=new Set;return "all"in e&&t.add("all"),"any"in e&&t.add("any"),cs(e)&&t.add("if"),"arrayOperator"in e&&t.add("array"),"dateOperator"in e&&t.add("date"),"aggregate"in e?t.add("aggregate"):"operator"in e&&t.add("field"),t.size===1?[...t][0]:null},U=e=>e.length===0?true:e.length===1?e[0]:{all:[...e]},qa=e=>typeof e=="object"&&"all"in e&&Array.isArray(e.all)?e.all.flatMap(qa):[e],Gt=e=>e.length===0?false:e.length===1?e[0]:{any:[...e]};var iO=e=>e===null||e instanceof Date||["string","number","boolean","bigint"].includes(typeof e),qr=e=>{if(Array.isArray(e))return e;let t=e.list;return Array.isArray(t)?t:[]},hr=e=>{if(Array.isArray(e))return "list";if(iO(e))return "literal";if(!re(e))return null;let t=e,r=[];return "list"in t&&r.push("list"),cs(t)&&r.push("if"),"aggregate"in t&&r.push("aggregate"),("value"in t||"path"in t||"bind"in t)&&r.push("source"),r.length===1?r[0]:null},Ir=e=>{let t=e;switch(hr(e)){case "list":return U(qr(e).map(Ir));case "if":return U([t.if,Ir(t.then),...t.else===void 0?[]:[Ir(t.else)]]);case "aggregate":return t;case "source":return Oe(t)?{field:t.path,operator:"exists"}:true;default:return true}};var sO=e=>jo(e).flatMap(({source:t})=>typeof t.bind=="string"?[t]:[]),Io=(e,{required:t=false}={})=>{let r=new Set;return H(e,n=>{for(let o of sO(n))(!t||o.bindOptional!==true)&&r.add(o.bind);}),[...r].sort()},aO=e=>{let t=new Set;return H(e,r=>{typeof r.field=="string"&&t.add(r.field);for(let{ref:n}of Vo(r))t.add(n);return xe(r)?false:void 0}),[...t].sort()},Ba=(e,t)=>{let r=n=>{if(typeof n.bind!="string"||!Object.hasOwn(t,n.bind))return n;let{bind:o,bindOptional:i,...s}=n;return {...s,value:Va(o,true,t)}};return gr(e,{rewrite:n=>Jn(Jn(n,r),r)})};var su=BigInt(Number.MAX_SAFE_INTEGER),Br=e=>{if(e>su||e<-su)throw new RangeError(`BigInt ${e} is outside the safe integer range (\xB12^53); json-rules compares BigInt as Int.`);return Number(e)},Wa=e=>typeof e=="bigint"?Br(e):typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e))?Number(e):e,ms=(e,t)=>{if(e==null)return null;let r=Wa(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} reads a number (got ${String(e)})`);return r},Je=([e,t])=>t<e?[t,e]:[e,t],rt=(e,t)=>{if(!Array.isArray(e)||e.length!==2)throw new Error(`${t} operator requires an array of two values`);return [e[0],e[1]]},Zn=(e,t)=>{let r=rt(e,t);if(!r.every(ye))throw new Error(`${t} requires two ends that order \u2014 numbers, strings or dates (got ${JSON.stringify(e)})`);return r},gs=e=>{if(!Array.isArray(e))throw new Error(`in / notIn requires a list (got ${JSON.stringify(e)})`);return e},Qe=e=>{let t=gs(e),r=t.filter(n=>n!==null);return {values:r,hasNull:r.length!==t.length}},ye=e=>typeof e=="string"||typeof e=="number"||e instanceof Date;var Ua=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&(!Dr(t)||Number.isInteger(e))?null:`${t} must be a non-negative${Dr(t)?" whole":""} number (got ${String(e)})`,Ka=(e,t,r)=>{let n=typeof e=="number"?e:ms(t(e),e.path?`'${e.path}' (${r})`:r),o=n===null?null:Ua(n,r);if(o===null)return n;if(typeof e!="number"&&Oe(e))return null;throw new Error(o)},Wr=(e,t)=>{let r={};for(let[n,o]of Object.entries(e)){if(o===void 0)continue;let i=Ka(o,t,n);if(i===null)return null;r[n]=i;}return r},vt=(e,t)=>{let r=Re(e);if(!r)return e;let n=Wr(r[0],t);return n?fs(n,r[1]):null};var lO=e=>{let t=Re(e);if(t)return re(t[0])?Object.keys(t[0]).flatMap(o=>Vn(o)?[et[o].clock]:[]):[];let r=Do(e)?"start"in e?e.start:e.end:e;if(!re(r))return [];let n=Gn(r);return Jd(n)?[rs[n]]:[]},au=(e,t)=>[...xi(e),t].filter(ee).flatMap(lO),pO=e=>xi(e).some(ee),ys=e=>Co.indexOf(e),fO=()=>{let e=Xe.get("clock.finestUnit");if(Co.includes(e))return e;if(typeof e=="string"&&Vn(e))return et[e].clock;throw new C(`clock.finestUnit reads a clock unit, singular or plural (got ${String(e)})`)},zt=(e,t)=>{let r=au(e,t);if(r.length===0)return null;let n=fO(),o=r.find(i=>ys(i)<ys(n));return o?Xd(o,n):null},Ga=e=>re(e)?e.value:void 0,qo=e=>{let t=null;return H(e,r=>{if(!("dateOperator"in r))return;let n=Ga(r.offset),o=zt(r.value,n);if(o)throw o;if(pO(r.value))for(let i of au(r.value,n))(t===null||ys(i)<t)&&(t=ys(i));}),t===null?null:Co[t]};var Ur=(e,t)=>{if(e==null)return null;if(Array.isArray(e)){let n=e.map(o=>Ur(o,t));return n.some(o=>o===null)?null:n}let r=Wa(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`offset needs a numeric comparison value (got ${String(e)})`);return r+t},Kr=e=>ms(e,"an offset"),Yn=e=>{if(e==null)return null;let t=ee(e)?Re(e):null;if(!t)throw new Error(`a date offset reads { ago } or { ahead } (got ${JSON.stringify(e)})`);return t};Nt.extend(ZR);Nt.extend(QR);Nt.extend(uO);Nt.extend(dO);var fu=(e,t,r={},n)=>{let o=ar(e.field,t),i=Ht(r,u=>Be(u,t,n)),s=i.timeZone;if(o==null)return W.includes(e.dateOperator)?true:e.error||`${e.field} has no value`;let a=ye(o)?wr(o,s):null;if(!a?.isValid())throw new Error(`${e.field} is not a valid date: ${String(o)}`);let l=u=>e.error||`${e.field} ${u}`;if(_d.includes(e.dateOperator)){let u=za(Be(e,t,n));if(u===null)return e.error||`${e.field} has no comparison value`;let m=u.includes(a.tz(s).day()),y=u.map(c=>In[c]).join(" or ");return e.dateOperator===N.dayIn?m||l(`must be on ${y}`):!m||l(`must not be on ${y}`)}let f=gO(e,t,i,s,n);if(f===null)return e.error||`${e.field} has no comparison value`;let[p,d=p]=f;switch(e.dateOperator){case N.before:return a.isBefore(p)||l(`must be before ${p.format()}`);case N.after:return a.isAfter(p)||l(`must be after ${p.format()}`);case N.onOrBefore:return a.isSameOrBefore(p)||l(`must be on or before ${p.format()}`);case N.onOrAfter:return a.isSameOrAfter(p)||l(`must be on or after ${p.format()}`);case N.within:return a.isSameOrAfter(p)&&a.isSameOrBefore(d)||l(`must be within ${p.format()} and ${d.format()}`);case N.notBefore:return a.isSameOrAfter(p)||l(`must not be before ${p.format()}`);case N.notAfter:return a.isSameOrBefore(p)||l(`must not be after ${p.format()}`);case N.notWithin:return a.isBefore(p)||a.isAfter(d)||l(`must not be within ${p.format()} and ${d.format()}`);case N.between:return a.isSameOrAfter(p)&&a.isSameOrBefore(d)||l(`must be between ${p.format()} and ${d.format()}`);case N.notBetween:return a.isBefore(p)||a.isAfter(d)||l(`must not be between ${p.format()} and ${d.format()}`);default:throw de(e.dateOperator,"date")}},gO=(e,t,r,n,o)=>{let i=e.dateOperator,s=g=>Be(g,t,o),a=Be(e,t,o);if(a==null)return null;let l=e.offset===void 0?void 0:s(e.offset),f=zt(a,l);if(f)throw f;let p=l===void 0?void 0:Yn(l);if(p===null)return null;let d=g=>{if(p===void 0)return g;let w=Wr(p[0],s);return w&&mr(g,w,p[1],n)};if(Po.includes(i)){if(!ee(a))throw tt(i);let g=vt(a,s);return g&&Hn(g,r)}let u=(g,w)=>{if(g==null)return null;if(ee(g)){let b=vt(g,s);return b&&ja(b,r)}let R=wr(g,n);if(!R.isValid())throw new Error(`Invalid ${w}: ${String(g)}`);return R};if(Dd.includes(i)){let[g,w]=rt(a,i),R=u(g,"start date"),b=u(w,"end date");if(!R||!b)return null;let[S,v]=Je([R,b]),E=d(S),q=d(v);return E&&q?[E,q]:null}if(Array.isArray(a))throw new Error(`${i} operator requires a single date value`);let m=g=>{let w=vt(g,s);return w&&zn(w,i,r)},y=ee(a)?m(a):u(a,"comparison date");if(!y)return null;let c=d(y);return c&&[c]},Ht=(e,t)=>{let r=e.timeZone;if(r===void 0||typeof r=="string")return {...e,timeZone:pu(r??qe)};if(jr(r))throw new C(`timeZone is one per evaluation; give it as a string or a { bind }, not the row path '${r.path}'`);let n=t(r);if(n!=null&&typeof n!="string")throw new C(`timeZone reads a zone name (got ${String(n)})`);return {...e,timeZone:pu(n??qe)}},lu=new Set,pu=e=>{if(lu.has(e))return e;try{new Intl.DateTimeFormat("en-US",{timeZone:e});}catch{throw new C(`invalid time zone: ${e}`)}return lu.add(e),e},yO=/\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:[zZ]|[+-]\d{2}(?::?\d{2})?)$/,hO=e=>yO.test(e.trim())||/\b(?:GMT|UTC)\b/.test(e),wr=(e,t)=>{if(typeof e=="string"&&/^-?\d+$/.test(e.trim()))return Nt(Number(e));if(typeof e=="string"&&!hO(e)){let r=Nt(e);return r.isValid()?Nt.tz(e,t):r}return typeof e=="string"?Nt(new Date(e.trim())):Nt(e)},hs=(e,t)=>{let r=ye(e)?wr(e,t):Nt(Number.NaN);if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},za=e=>{if(e==null)return null;if(!Array.isArray(e))throw new Error("a weekday operator requires an array of day names");return e.map(t=>{let r=In.indexOf(String(t).toLowerCase());if(r===-1)throw new Error(`Unknown day name: ${String(t)}`);return r})};var bO=e=>e<=3?0:e<=6?1:2,SO=(e,t)=>{let{maxDistance:r,maxRatio:n}=e,o=[];return typeof r=="number"&&o.push(r),typeof n=="number"&&o.push(Math.floor(t*n)),o.length>0?Math.min(...o):bO(t)},du=e=>e.split(/[^a-z0-9\p{L}]+/u).filter(Boolean),RO=e=>/^\d+$/.test(e),OO=(e,t,r)=>e===t?true:Math.abs(e.length-t.length)>r?false:distance(e,t)<=r,uu=(e,t,r={})=>{let n=t.trim().toLowerCase();if(!n)return true;let o=e.toLowerCase();if(o.includes(n))return true;let i=du(n);if(i.length===0)return false;let s=du(o);return s.length===0?false:i.every(a=>{let l=SO(r,a.length);return l===0||RO(a)?s.includes(a):s.some(f=>OO(a,f,l))})};var br=e=>{let t=e instanceof RegExp?e.source:e,r=e instanceof RegExp?e.flags:"";if(/[^i]/.test(r))throw new Error(`Refused pattern /${t}/${r}: only the 'i' flag is supported`);let n=r==="i";try{return {source:t,caseInsensitive:n,re:RE2JS.compile(t,n?RE2JS.CASE_INSENSITIVE:0)}}catch(o){throw new Error(`Refused pattern /${t}/: ${o.message}`)}},Xn={d:"0-9",w:"0-9A-Za-z_",s:"\\t\\n\\f\\r "},mu={alnum:"0-9A-Za-z",alpha:"A-Za-z",ascii:"\\u0000-\\u007f",blank:"\\t ",cntrl:"\\u0000-\\u001f\\u007f",digit:"0-9",graph:"!-~",lower:"a-z",print:" -~",punct:"!-/:-@\\[-`{-~",space:"\\t\\n\\v\\f\\r ",upper:"A-Z",word:"0-9A-Za-z_",xdigit:"0-9A-Fa-f"},xO=/[\\^$.|?*+()[\]{}]/,Ha=255,gu=e=>e<=65535?`\\u${e.toString(16).padStart(4,"0")}`:`\\U${e.toString(16).padStart(8,"0")}`,EO=e=>xO.test(e)?`\\${e}`:e,Bo=e=>{let t=s=>{throw new Error(`Refused pattern /${e}/: ${s} has no Postgres form`)},r="",n=0,o=()=>{/^([*+?]|\{\d)/.test(e.slice(n))&&t("a quantified anchor");},i=s=>{let a=e[n+1];if(n+=2,Object.hasOwn(Xn,a))return s?Xn[a]:`[${Xn[a]}]`;let l=a.toLowerCase();if(a!==l&&Object.hasOwn(Xn,l))return s&&t(`a negated class \\${a} inside brackets`),`[^${Xn[l]}]`;if(a==="p"||a==="P")return t("a Unicode class");if(a==="C")return t("\\C");if(a==="x"){let f=e[n]==="{",p=f?e.indexOf("}",n):n+2,d=e.slice(f?n+1:n,p);return n=f?p+1:p,gu(Number.parseInt(d,16))}if(a>="0"&&a<="7"){let f=a;for(;f.length<3&&e[n]>="0"&&e[n]<="7";)f+=e[n++];return gu(Number.parseInt(f,8))}if(!s&&(a==="b"||a==="B")){let f=`[${Xn.w}]`;return a==="b"?`(?:(?<=${f})(?!${f})|(?<!${f})(?=${f}))`:`(?:(?<=${f})(?=${f})|(?<!${f})(?!${f}))`}if(!s&&(a==="z"||a==="A"))return o(),a==="z"?"\\Z":"\\A";if(a==="Q"){let f=e.indexOf("\\E",n),p=e.slice(n,f===-1?void 0:f);return n=f===-1?e.length:f+2,[...p].map(s?d=>/[\\\]^-]/.test(d)?`\\${d}`:d:EO).join("")}return `\\${a}`};for(;n<e.length;){let s=e[n];if(s==="\\")r+=i(false);else if(s===".")r+="[^\\n]",n++;else if(s==="("&&e[n+1]==="?"){let a=/^\(\?P?<[^>]+>/.exec(e.slice(n));a?(r+="(",n+=a[0].length):e[n+2]===":"?(r+="(?:",n+=3):t("a flag group");}else if(s==="{"){let a=/^\{(0|[1-9]\d*)(?:,(0|[1-9]\d*)?)?\}/.exec(e.slice(n));if(!a){r+="\\{",n++;continue}(Number(a[1])>Ha||Number(a[2]??0)>Ha)&&t(`a repeat count past ${Ha}`),r+=a[0],n+=a[0].length;}else if(s==="["){r+="[",n++,e[n]==="^"&&(r+="^",n++),e[n]==="]"&&(r+="\\]",n++);let a=false,l=false,f=0;for(;n<e.length&&e[n]!=="]";){let p=l?null:/^\[:(\^?)([a-z]+):\]/.exec(e.slice(n)),d=!!p||/^\\[dswDSW]/.test(e.slice(n)),u=e[n]==="-"&&f>0&&e[n+1]!=="]"&&!l;p?(p[1]&&t(`a negated class [:^${p[2]}:]`),Object.hasOwn(mu,p[2])||t(`the class [:${p[2]}:]`),r+=mu[p[2]],n+=p[0].length):e[n]==="\\"?r+=i(true):u&&a?(r+="\\-",n++):(r+=e[n]==="["?"\\[":e[n],n++);let m=l;l=u&&!a,a=d||m,f++;}r+="]",n++;}else r+=s,n++,(s==="^"||s==="$")&&o();}return r},yu=(e,t)=>{try{let{source:r}=br(e);return t==="toSql"&&Bo(r),null}catch(r){return r.message}};var hu=e=>e==null||e===""||Array.isArray(e)&&e.length===0,Ee=(e,t)=>{let r=t==null;return r&&(e.offset!==void 0||Td.includes(e.operator))?true:He.includes(e.operator)?r||Array.isArray(t)&&t.some(n=>n==null):false},Qt=e=>fr.includes(e.operator)||xt.includes(e.operator)&&e.value===null&&e.path===void 0&&e.bind===void 0,bs=(e,t)=>{let r=t.filter(o=>Array.isArray(o)||o===null),n=o=>r.map(i=>({...e,operator:o,value:i}));return e.operator===h.in?Gt(n(h.equals)):U(n(h.notEquals))},Gr=e=>typeof e=="string"?e.toLowerCase():Array.isArray(e)?e.map(Gr):e,wu=e=>typeof e=="bigint"?Br(e):Array.isArray(e)&&e.some(t=>typeof t=="bigint")?e.map(t=>typeof t=="bigint"?Br(t):t):e,bu=(e,t,r)=>{if(e==null)return e;if(X.includes(t)){if(typeof e!="string"||e.trim()==="")return e;if(t==="BigInt"&&/^-?\d+$/.test(e.trim()))return Br(BigInt(e.trim()));let n=Number(e);return Number.isFinite(n)?n:e}switch(t){case "DateTime":{if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e!="string")return e;let n=wr(e,r);return n.isValid()?n.valueOf():e}case "Boolean":return e==="true"?true:e==="false"?false:e;case "String":return typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):e;default:return e}},Jt=(e,t,r=qe)=>t===void 0?e:Array.isArray(e)?e.map(n=>bu(n,t,r)):bu(e,t,r),Wo=(e,t,r,n={},o)=>{let i=o?o.value:ar(e.field,t);if(n.absent==="unknown"&&!es.includes(e.operator)&&(i===void 0||Oe(e)&&Ui(e.path,t)===void 0))return e.error||`${e.field} is unknown`;let s=i??null,a=e.coerceType??(s instanceof Date?"DateTime":void 0),l=a==="DateTime"?Ht(n,b=>Be(b,t,r)).timeZone:qe,f=Jt(wu(s),a,l),p=!fr.includes(e.operator),d=p?$O(Jt(wu(Be(e,t,r)??null),a,l),e,t,r):void 0;if(p&&Ee(e,d))return W.includes(e.operator)&&f==null?true:e.error||`${e.field} has no comparison value`;let u=b=>e.error||`${e.field} ${b}${p?` ${d instanceof RegExp?String(d):JSON.stringify(d)}`:""}`,m=oe(e.caseInsensitive),y=b=>m?Gr(b):b,c=y(f),g=y(d),w=Gi(e.fuzzy),R=()=>w&&typeof f=="string"&&typeof d=="string"?uu(f,d,w):Array.isArray(f)?c.some(b=>Bt(b,g)):vO(c,g);switch(e.operator){case h.equals:return Bt(c,g)||u("must equal");case h.notEquals:return !Bt(c,g)||u("must not equal");case h.lessThan:return ws(f,d,"lt")||u("must be less than");case h.lessThanEquals:return ws(f,d,"lte")||u("must be less than or equal to");case h.greaterThan:return ws(f,d,"gt")||u("must be greater than");case h.greaterThanEquals:return ws(f,d,"gte")||u("must be greater than or equal to");case h.in:return gs(g).some(b=>Bt(b,c))||u("must be one of");case h.notIn:return !gs(g).some(b=>Bt(b,c))||u("must not be one of");case h.contains:return R()||u("must contain");case h.notContains:return !R()||u("must not contain");case h.matches:return Su(f)&&Ru(d)&&br(d).re.test(f)||u("must match pattern");case h.notMatches:return !Su(f)||!Ru(d)||!br(d).re.test(f)||u("must not match pattern");case h.between:{let b=Ou(d,e.operator);if(!Eu(f,b))return u("must be between");let S=eo(f),[v,E]=b;return S>=v&&S<=E||u("must be between")}case h.notBetween:{let b=Ou(d,e.operator);if(!Eu(f,b))return true;let S=eo(f),[v,E]=b;return S<v||S>E||u("must not be between")}case h.isEmpty:return hu(f)||u("must be empty");case h.notEmpty:return !hu(f)||u("must not be empty");case h.exists:return f!=null||u("must exist");case h.notExists:return f==null||u("must not exist");case h.startsWith:return typeof c=="string"&&typeof g=="string"&&c.startsWith(g)||u("must start with");case h.endsWith:return typeof c=="string"&&typeof g=="string"&&c.endsWith(g)||u("must end with");case h.notStartsWith:return !(typeof c=="string"&&typeof g=="string"&&c.startsWith(g))||u("must not start with");case h.notEndsWith:return !(typeof c=="string"&&typeof g=="string"&&c.endsWith(g))||u("must not end with");default:throw new Error("Unknown operator")}},$O=(e,t,r,n)=>{if(t.offset===void 0)return e;let o=Kr(Be(t.offset,r,n));return o===null?null:Ur(e,o)},eo=e=>e instanceof Date?e.getTime():e,ws=(e,t,r)=>{if(!NO(e,t)||!ye(t))return false;let n=eo(e),o=eo(t);switch(r){case "lt":return n<o;case "lte":return n<=o;case "gt":return n>o;case "gte":return n>=o}},Su=e=>typeof e=="string",Ru=e=>typeof e=="string"||e instanceof RegExp,Ou=(e,t)=>Je(Zn(e,t).map(r=>eo(r))),vO=(e,t)=>typeof e=="string"&&typeof t=="string"&&e.includes(t),NO=(e,t)=>ye(e)&&ye(t)&&xu(e)===xu(t),xu=e=>e instanceof Date?"date":typeof e,Eu=(e,t)=>ye(e)&&typeof eo(e)==typeof t[0];var Ae=e=>e.filter!==void 0||!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0,AO=e=>{if(typeof e!="object"||e===null)return null;let t=e,r=le(t);return r!=="field"&&r!=="date"||typeof t.field!="string"?null:{op:String(r==="date"?t.dateOperator:t.operator),field:t.field}},PO=e=>{if(e.filter!==void 0||e.skip!==void 0&&e.skip!==0||e.take!==1||e.orderBy?.length!==1)return null;let{field:t,dir:r}=e.orderBy[0];if(r!=="asc"&&r!=="desc")return null;let n=null;if(e.arrayOperator===x.all?n="all":(e.arrayOperator===x.any||e.arrayOperator===x.atLeast&&e.count===1)&&(n="any"),!n)return null;let o=AO(e.condition);if(!o||o.field!==t)return null;let i=ts.includes(o.op),s=Wd.includes(o.op);if(!i&&!s)return null;let a=r==="desc";if(!(n==="all"?a&&i||!a&&s:a&&s||!a&&i))return null;let{orderBy:f,take:p,skip:d,count:u,...m}=e;if(n==="any")return {...m,arrayOperator:x.any};let y={field:t,operator:h.exists};return {any:[{field:e.field,arrayOperator:x.empty},{all:[{field:e.field,arrayOperator:x.any,condition:y},{...m,arrayOperator:x.all,condition:{if:y,then:e.condition}}]}]}},Ja=(e,t,r)=>{let n=e;return t.filter!==void 0&&r&&(n=n.filter(r)),t.orderBy?.length&&(n=$u(n,t.orderBy)),t.skip!==void 0&&(n=n.slice(t.skip)),t.take!==void 0&&(n=n.slice(0,t.take)),n},$u=(e,t)=>[...e].sort((r,n)=>{for(let{field:o,dir:i}of t){let s=kO(ge(r,o),ge(n,o),i);if(s!==0)return s}return 0}),kO=(e,t,r)=>{let n=e==null,o=t==null;if(n||o)return n===o?0:n?1:-1;let i=e instanceof Date?e.getTime():e,s=t instanceof Date?t.getTime():t,a=i<s?-1:i>s?1:0;return r==="asc"?a:-a},to=e=>{if(!Ae(e))return e;let t=!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0;if(e.filter!==void 0&&!t){let{filter:r,...n}=e;if("aggregate"in e)return {...n,condition:e.condition===void 0?r:U([r,e.condition])};switch(e.arrayOperator){case "all":return {...n,condition:{if:r,then:e.condition??true}};case "empty":return {...n,arrayOperator:"none",condition:r};case "notEmpty":return {...n,arrayOperator:"any",condition:r};default:return {...n,condition:e.condition===void 0?r:U([r,e.condition])}}}return "aggregate"in e||e.filter!==void 0?null:PO(e)};var TO=e=>H(e,t=>{let r=le(t);if(!(r==="all"||r==="any")){if(r==="array"&&!("field"in t))return false;throw new Error("check: when data is an array, every leaf must be a fieldless arrayOperator (composable with all/any)")}}),he=(e,t,r)=>(Array.isArray(t)&&TO(e),nt(e,t,{...r,scopes:[t]})),nt=(e,t,r)=>{if(typeof e=="boolean")return e;let n=e;switch(le(e)){case "all":return CO(n.all,t,r,n.error);case "any":return LO(n.any,t,r,n.error);case "if":return MO(n,t,r);case "array":return FO(n,r);case "aggregate":return DO(n,r);case "date":return fu(n,r.scopes,r,r.bindings);case "field":return Wo(n,r.scopes,r.bindings,r);default:throw Et()}},Ss=(e,t)=>({...e,scopes:[...e.scopes,t]}),CO=(e,t,r,n)=>{let o=[];for(let i of e){let s=nt(i,t,r);s!==true&&(typeof s=="string"?o.push(s):o.push("false"));}return o.length?n||(o.length===1?o[0]:`All conditions must pass: ${o.join(" AND ")}`):true},LO=(e,t,r,n)=>{let o=[];for(let i of e){let s=nt(i,t,r);if(s===true)return true;typeof s=="string"&&o.push(s);}return n||(o.length===1?o[0]:`At least one condition must pass: ${o.join(" OR ")}`)},MO=(e,t,r)=>nt(e.if,t,r)===true?nt(e.then,t,r):e.else!==void 0?nt(e.else,t,r):true,vu=(e,t)=>{if(e==null)return [];if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e},Nu=(e,t)=>nt(e,t.scopes[t.scopes.length-1],t)===true,Qa=(e,t)=>{let r=vu(ar(e.field,t.scopes),e.field),n=e.filter,o=Ja(r,e,n?s=>nt(n,s,Ss(t,s))===true:void 0),i=e.condition;return i?o.filter(s=>nt(i,s,Ss(t,s))===true):o},ro=(e,t,r,n)=>e.flatMap((o,i)=>{let s=r?ge(o,r):o;return s==null?[]:[n(s,`${t}[${i}]${r?`.${r}`:""}`)]}),_O=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} must be a finite number`);return e},Rs=(e,t,r,n)=>{let o=ro(t,r,n,_O),i=o.reduce((s,a)=>s+a,0);return e==="sum"||o.length===0?i:i/o.length},DO=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!Ot.includes(r))throw cr(r);let o=Qa(e,t),i=Rs(r,o,e.field,n),s={...e,field:`${e.field} ${r}`};return Wo(s,t.scopes,t.bindings,t,{value:i})},FO=(e,t)=>{let r=vu(e.field?ar(e.field,t.scopes):t.scopes[t.scopes.length-1],e.field||"(root)"),n=e.filter,o=Ja(r,e,n?d=>nt(n,d,Ss(t,d))===true:void 0),i=d=>e.error||`${e.field} ${d}`,s=e.condition,a=Xi.includes(e.arrayOperator);if(a&&s===void 0)throw Ie(e.arrayOperator);let l=e.count??0;if(ko.includes(e.arrayOperator)&&e.count===void 0)throw qn(e.arrayOperator);let f=0,p=0;if(a&&s!==void 0){if(o.length>0&&!Pa(o,Q))return i("contains only primitive values; use 'in' or 'contains' instead of array operators on primitive arrays");let d=o.map(u=>nt(s,u,Ss(t,u)));f=d.filter(u=>u===true).length,p=d.filter(u=>typeof u=="string").length;}switch(e.arrayOperator){case x.empty:return !o.length||i("must be empty");case x.notEmpty:return !!o.length||i("must not be empty");case x.all:return f===o.length||i(`all elements must match (${p} failed)`);case x.any:return !!f||i("at least one element must match");case x.none:return !f||i(`no elements should match (${f} matched)`);case x.atLeast:return f>=l||i(`at least ${l} elements must match (${f} matched)`);case x.atMost:return f<=l||i(`at most ${l} elements must match (${f} matched)`);case x.exactly:return f===l||i(`exactly ${l} elements must match (${f} matched)`);default:throw de(e.arrayOperator,"array")}};var O=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,Zt=(e,t,r)=>(Object.hasOwn(e,t)||(e[t]=r()),e[t]),T=(e,t)=>O(e?.models,t),ue=(e,t,r)=>O(T(e,t)?.fields,r);var Me=({fieldMap:e,model:t})=>`${e}:${t}`,Au=(e,t)=>{let r=e.indexOf(":");return r===-1?{mapName:t,modelName:e}:{mapName:e.slice(0,r),modelName:e.slice(r+1)}};var Pu=(e,t,r,n)=>{let o={};for(let i of e){let s=O(i,t);if(s==null)continue;let a=String(s);if(Object.hasOwn(o,a)){let l=n==="one"?`endpoint[0] must be the "one" side of a oneToMany bridge \u2014 swap endpoints if '${r}' is the "many" side`:`oneToOne bridges require unique '${t}' on both endpoints`;throw new Error(`indexBridges: duplicate '${t}' value '${a}' on '${r}' \u2014 ${l}.`)}o[a]=i;}return o},jO=(e,t)=>{let r={};for(let n of e){let o=O(n,t);o!=null&&Zt(r,String(o),()=>[]).push(n);}return r},ku=(e,t)=>{let r={};for(let n of e.bridges??[]){let[o,i]=n.endpoints,s=Me(o),a=Me(i),l=n.cardinality==="oneToMany"?"one":"oneToOne",f=(u,m)=>Zt(Zt(r,u,()=>({})),m,()=>({})),p=O(t,s);p&&(f(o.fieldMap,o.model)[o.on]=Pu(p,o.on,s,l));let d=O(t,a);d&&(n.cardinality==="oneToMany"?f(i.fieldMap,i.model)[i.on]=jO(d,i.on):f(i.fieldMap,i.model)[i.on]=Pu(d,i.on,a,"oneToOne"));}return r};var Os=e=>{let t={maps:structuredClone(e.maps),bridges:e.bridges?structuredClone(e.bridges):void 0};for(let r of e.bridges??[]){let[n,o]=r.endpoints,i=Me(n),s=Me(o),a=T(O(t.maps,n.fieldMap),n.model),l=T(O(t.maps,o.fieldMap),o.model);if(!a)throw new Error(`stitchFieldMaps: endpoint '${i}' not found`);if(!l)throw new Error(`stitchFieldMaps: endpoint '${s}' not found`);if(n.fieldMap===o.fieldMap&&n.model===o.model)throw new Error(`stitchFieldMaps: self-bridge '${i}' to itself is not supported`);if(!O(a.fields,n.on))throw new Error(`stitchFieldMaps: endpoint '${i}' has no field '${n.on}' for join`);if(!O(l.fields,o.on))throw new Error(`stitchFieldMaps: endpoint '${s}' has no field '${o.on}' for join`);if(O(a.fields,s))throw new Error(`stitchFieldMaps: bridge '${s}' already injected on '${i}'`);if(O(l.fields,i))throw new Error(`stitchFieldMaps: bridge '${i}' already injected on '${s}'`);let f=r.cardinality==="oneToMany";a.fields[s]={kind:"bridge",type:s,isList:f},l.fields[i]={kind:"bridge",type:i,isList:false};}return t};var no=(e,t,r)=>{if(e?.isList||t?.isList){if(!(e?.isList&&!t?.isList&&Rt.includes(r)))return "a list column compares with no column but by membership";if(e?.kind!=="enum"&&t?.kind!=="enum")return null}let n=[e,t].filter(o=>o?.kind==="enum");return n.length===0?null:n.length===1||e?.type!==t?.type?"an enum compares only with an enum column of its own type":xt.includes(r)?null:`an enum column orders by declaration on the database, not as check() compares its text ('${r}')`};var Ue=e=>e.kind==="scalar"&&e.type==="Json",L=e=>e.kind==="object"||e.kind==="bridge",zr=(e,t)=>e.values??O(t,e.type);var Pe=(e,t,r)=>{if(!e||!("maps"in e))return e;if(!t)throw new Error(`${r}: 'map' is a FieldMapSet \u2014 'mapName' is required to resolve which map to use.`);let n=O(e.maps,t);if(!n)throw new Error(`${r}: fieldMap set has no entry for '${t}'`);return n};var ot=(e,t)=>e.kind==="object"?{mapName:t,modelName:e.type}:e.kind==="bridge"?Au(e.type,t):null;function*Sr(e,t,r){let n=r.split("."),o=t;for(let i=0;i<n.length;i++){let s=n[i],a=ue(O(e,o.mapName),o.modelName,s),l=a?ot(a,o.mapName):null;if(yield {index:i,field:s,at:o,entry:a,next:l},!l)return;o={...l,relPath:[...o.relPath,s]};}}var ie=(e,t,r)=>{let n=e.split("."),o=[],i={mapName:"",modelName:r,relPath:[]};for(let{index:s,field:a,at:l,entry:f}of Sr({"":t},i,e)){let p=l.modelName;if(!f)return {kind:"fallback",hops:o};if(f.kind==="bridge")return {kind:"bridge",hops:o};let d=s===n.length-1;if(f.kind==="object"){if(!T(t,f.type))return {kind:"fallback",hops:o};if(d)return {kind:"direct",hops:o,entry:f,model:p,column:a};o.push({field:a,prefix:n.slice(0,s+1).join("."),entry:f,from:p});continue}return d?{kind:"direct",hops:o,entry:f,model:p,column:a}:Ue(f)?{kind:"json-path",hops:o,entry:f,model:p,column:a,stopIndex:s+1,jsonPath:n.slice(s+1)}:{kind:"past-scalar",hops:o,column:a}}return {kind:"fallback",hops:o}},Rr=(e,t,r)=>t&&r?ie(e,t,r):void 0,te=(e,t,r)=>{let n=Rr(e,t,r);return n?.kind==="direct"?n.entry:void 0},Tu=(e,t,r)=>ie(e,t,r).hops.filter(n=>!n.entry.isList&&n.entry.isRequired===false).map(n=>n.prefix),Uo=(e,t,r)=>{let n=ie(e,t,r);return n.kind==="direct"&&n.entry.kind==="object"?n.entry.type:null},Or=(e,t,r)=>ie(e,t,r).kind==="bridge",At=(e,t,r)=>!!t&&!!r&&iu(e,(n,o)=>typeof n.field=="string"&&n.field!==""&&Or(n.field,t,o),(n,o)=>(typeof n.field=="string"?Uo(n.field,t,o):o)??false,r);var Hr=e=>e?.kind==="json-path"?"json-path":e?.kind!=="direct"?"unknown":e.entry.kind==="object"?e.entry.isList?"relations":"relation":e.entry.isList?"list":e.entry.kind==="enum"?"enum":Cu(e.entry.type),Cu=e=>e===P.Json?"json":e===P.Enum?"enum":e===P.DateTime?"instant":e===P.String?"text":"scalar",xs=(e,t,r)=>{let n=te(e.field,t,r);return n?n.kind==="scalar"&&(n.type==="String"||n.type==="Json"):e.coerceType===void 0||e.coerceType==="String"||e.coerceType==="Json"},Es=(e,t,r)=>{if(Hr(Rr(e,t,r))==="relations")throw ss(e)},Jr=e=>e!=="scalar"&&e!=="instant"&&e!=="list"&&e!=="enum"&&e!=="relation"&&e!=="relations",xr=(e,t)=>Jr(e)&&Lu(t),Lu=e=>typeof e=="string"||Array.isArray(e)&&e.some(Lu),Ke=(e,t,r)=>{let n=Hr(Rr(e.field,t,r));return n==="unknown"&&e.coerceType!==void 0?Cu(e.coerceType):n},Ge=e=>{if(!e.isList){if(e.kind==="enum")return P.Enum;if(!(e.kind!=="scalar"||e.type===P.Json))return Ao(e.type)?e.type:void 0}};var Mu=new WeakSet,vs=e=>(Mu.add(e),e),_u=e=>{if(e===null||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Du=e=>{let t=[],r=(n,o)=>{if(n!==null&&typeof n=="object"&&Mu.has(n)){t.push({path:o});return}if(Array.isArray(n))for(let[i,s]of n.entries())r(s,[...o,i]);else if(_u(n))for(let[i,s]of Object.entries(n))r(s,[...o,i]);};return r(e,[]),t},VO=["__step","__field"],$s=e=>Array.isArray(e)?e.some($s):_u(e)?Object.entries(e).some(([t,r])=>VO.includes(t)||$s(r)):false;var IO={[h.equals]:"equals",[h.notEquals]:"equals",[h.lessThan]:"lt",[h.lessThanEquals]:"lte",[h.greaterThan]:"gt",[h.greaterThanEquals]:"gte"},Fu=(e,t,r)=>{let n=ie(e,t,r);if(n.kind!=="direct"||n.hops.length>0)return `'${e}' is not a column of ${r} (a relation hop or an undeclared path)`;let{entry:o}=n;return L(o)?`'${e}' is a relation`:Ue(o)?`'${e}' is a Json column`:o.isList?`'${e}' is a list column`:o},Ns=(e,t,r,n,o=false)=>{let i=e.path;if(o)return {problem:"inside a counting step (a count or relation aggregate) a groupBy carries no column reference"};let s=M(i);if(s&&s.depth>1)return {problem:`'${i}' reads an enclosing scope, which a Prisma filter can't reach`};if(!s&&n)return {problem:`'${i}' reads the root row, which a Prisma relation filter can't reach`};if(!t||!r)return {problem:"comparing two columns needs the map and model"};let a=IO[e.operator];if(!a)return {problem:`'${e.operator}' takes no column reference in Prisma`};if(e.offset!==void 0)return {problem:"an offset is arithmetic, which Prisma lacks"};let l=Fu(e.field,t,r);if(typeof l=="string")return {problem:l};let f=s?s.path:i,p=Fu(f,t,r);if(typeof p=="string")return {problem:p};if(l.kind!==p.kind||l.type!==p.type)return {problem:`'${e.field}' (${l.type}) and '${f}' (${p.type}) are not the same type`};let d=no(l,p,e.operator);return d?{problem:d}:l.type==="String"&&oe(e.caseInsensitive)?{problem:"a case-insensitive column comparison compiles to ILIKE"}:{key:a,ref:vs({__field:{model:r,field:f}}),field:l,column:p,columnPath:f}},As=(e,t)=>new Error(`Path '${e}' compares to a column, which the Prisma rail supports only between columns of the same model and type: ${t}. Use toSql() or check().`),ju=new WeakSet,Za=new WeakSet,Qr=(e,t,r=false)=>(ju.add(e),(r||t!==void 0&&Za.has(t))&&Za.add(e),e),Vu=e=>e!==void 0&&ju.has(e),Iu=e=>e!==void 0&&Za.has(e);var Ya=e=>({field:e,operator:"notExists"}),qO=(e,t)=>{let r=t(e);if(r===null){let i=e.operator??e.dateOperator;return W.includes(i)?{field:e.field,operator:"exists"}:true}if("aggregate"in r){let i=O(Lo,r.operator);return i?{...r,operator:i}:{...r,operator:O(os,r.operator)}}if(typeof r.dateOperator=="string"){let i=O(Yd,r.dateOperator);return i?{...r,dateOperator:i}:Gt([{...r,dateOperator:O(os,r.dateOperator)},Ya(r.field)])}if(typeof r.arrayOperator=="string"){let i=r.count;switch(r.arrayOperator){case x.any:return {...r,arrayOperator:x.none};case x.none:return {...r,arrayOperator:x.any};case x.all:return {...r,arrayOperator:x.any,condition:Ze(r.condition,t)};case x.empty:return {...r,arrayOperator:x.notEmpty};case x.notEmpty:return {...r,arrayOperator:x.empty};case x.atLeast:return i<=0?false:{...r,arrayOperator:x.atMost,count:i-1};case x.atMost:return {...r,arrayOperator:x.atLeast,count:i+1};case x.exactly:return Gt([...i>0?[{...r,arrayOperator:x.atMost,count:i-1}]:[],{...r,arrayOperator:x.atLeast,count:i+1}])}}let n=O(Lo,r.operator);if(n)return {...r,operator:n};let o=typeof r.path=="string"&&r.path!==""?M(r.path)??{depth:1,path:r.path}:null;return Gt([{...r,operator:O(os,r.operator)},Ya(r.field),...o&&o.depth===1?[Ya(o.path)]:[]])},Ze=(e,t=r=>r)=>{if(typeof e=="boolean")return !e;let r=e;if(Array.isArray(r.all))return Gt(r.all.map(n=>Ze(n,t)));if(Array.isArray(r.any))return U(r.any.map(n=>Ze(n,t)));if("if"in r){let n=U([r.if,Ze(r.then,t)]);return r.else===void 0?n:{any:[n,U([Ze(r.if,t),Ze(r.else,t)])]}}return qO(r,t)},qu=e=>le(e)==="field"&&e.value!==void 0&&Ee(e,e.value)?null:e;var Bu,Wu=e=>{Bu=e;},fe=(e,t,r)=>Bu(e,t,r);var BO=e=>{let t=M(e);throw t&&t.depth>1?new Error($o(e,"toPrisma")):new Error(`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check().`)},it=e=>Fo(e,{value:t=>{if($s(t))throw new Error("toPrisma: a value holding a '__step' or '__field' key is reserved for the plan's own references");return t},path:t=>BO(t),bind:(t,r)=>us(t,r,"toPrisma")}),Ko=e=>it(e),oo=e=>Ht({now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},Ko),io=e=>t=>{let r=typeof t.operator=="string"||typeof t.dateOperator=="string",n=t.value!==void 0||typeof t.path=="string"&&t.path!==""||typeof t.bind=="string";if(!r||"aggregate"in t||!n||typeof t.operator=="string"&&typeof t.path=="string"&&t.path!=="")return t;let o=Ke({field:String(t.field)},e?.map,e?.model);if((o==="json"||o==="json-path")&&typeof t.operator=="string"&&Fn.includes(t.operator))throw V("toPrisma",`The complement of '${t.operator}' on the Json value '${t.field}'`,"it keeps values of other types");let i=it(t),s=t.offset===void 0?void 0:it(t.offset);if(t.offset!==void 0&&s==null)return null;let{path:a,bind:l,bindOptional:f,...p}=t,d={...p,value:i,...t.offset!==void 0&&{offset:{value:s}}};return typeof t.dateOperator=="string"?i==null||Ee({operator:t.dateOperator},i)?null:d:qu(d)};var st=()=>({}),Zr=st,Pt=()=>({OR:[]}),Xa=e=>Object.keys(e).length===0,Uu=e=>{let t=Object.keys(e);return t.length===1&&t[0]==="OR"&&Array.isArray(e.OR)&&e.OR.length===0},ke=e=>{if(e.some(Uu))return Pt();let t=e.filter(r=>!Xa(r));return t.length===0?st():t.length===1?t[0]:{AND:t}},K=e=>{if(e.some(Xa))return st();let t=e.filter(r=>!Uu(r));return t.length===0?Pt():t.length===1?t[0]:{OR:t}},_e=e=>Xa(e)?e:{NOT:e},Ku=(e,t,r)=>ke(e.all.map(n=>fe(n,t,r))),Gu=(e,t,r)=>K(e.any.map(n=>fe(n,t,r))),zu=(e,t,r)=>{if(At(e,t?.map,t?.model))return Zr();let n=fe(Ze(e.if,io(t)),t,r),o=fe(e.then,t,r),i=K([n,o]);if(e.else!==void 0){let s=fe(e.if,t,r),a=fe(e.else,t,r);return ke([i,K([s,a])])}return i};var WO=(e,t,r,n)=>{let o=T(e,t);if(!o)return null;for(let i of Object.values(o.fields))if(i.kind==="object"&&i.type===r&&(i.fromFields?.length??0)>0&&(i.toFields?.length??0)>0&&(n===void 0||i.relationName===n))return i;return null},Er=(e,t,r)=>{if(r.fromFields?.length)return r.fromFields.map((o,i)=>({here:o,there:r.toFields?.[i]??"id"}));let n=WO(e,r.type,t,r.relationName);return n?.fromFields?.length?n.fromFields.map((o,i)=>({here:n.toFields?.[i]??"id",there:o})):null},Ps=(e,t,r,n)=>{if(n.relationName===void 0)return null;let o=Object.entries(T(e,n.type)?.fields??{}).filter(([i,s])=>s.kind==="object"&&s.type===t&&s.relationName===n.relationName&&!(n.type===t&&i===r));return o.length===1?{field:o[0][0],entry:o[0][1]}:null};var Yr=(e,t)=>{let r=e.split("."),n=t;for(let o=r.length-1;o>=0;o--)n={[r[o]]:n};return n};var so=(e,t,r,n)=>{let o=e.split("."),i=ie(e,t,r);if(i.kind==="bridge")throw new Error(`'${e}' crosses a bridge: ${n.toLowerCase()} aren't supported across a bridge \u2014 no one database holds both sides.`);if(i.kind!=="direct"||i.entry.kind!=="object"){let l=i.hops.at(-1)?.entry.type??r;throw new Error(`Field '${o[i.hops.length]}' is not a relation in model '${l}'. ${n} require a relation field.`)}let s=i.hops.find(l=>l.entry.isList);if(s)throw new Error(`Intermediate field '${s.field}' in path '${e}' is a list relation. Only the final segment can be a list relation for ${n.toLowerCase()}.`);if(!i.entry.isList)throw new Error(`Field '${i.column}' is not a list relation in model '${i.model}'. ${n} only apply to one-to-many or many-to-many relations.`);let a=Er(t,i.model,i.entry);if(!a){let l=Object.values(T(t,i.entry.type)?.fields??{}).some(f=>f.kind==="object"&&f.type===i.model&&f.isList&&!f.fromFields?.length);throw new Error(l?`'${i.model}.${i.column}' is an implicit many-to-many relation. ${n} require an explicit join model with a FK \u2014 convert to an explicit @relation or use prisma.$queryRaw.`:`Cannot determine FK relationship between '${i.model}' and '${i.entry.type}'. Ensure the FieldMap contains both sides of the relation.`)}if(a.length>1)throw new Error(`${n} do not support composite FK relations ('${i.model}.${i.column}'). Use prisma.$queryRaw.`);return {through:i.hops.map(l=>l.field).join("."),target:i.entry.type,parentKey:a[0].here,targetKey:a[0].there}},ks=(e,t,r,n,o)=>{let i={operation:"groupBy",model:t.target,args:{by:[t.targetKey],where:r,having:n},extract:t.targetKey},s=vs({__step:e.steps.length});e.steps.push(i);let a={[t.parentKey]:{in:s}},l=o?_e(a):a;return t.through?Yr(t.through,l):l};var Ye=e=>({ok:e.length===0,errors:e}),en=(e,t)=>{if(!e.ok)throw new Error(`${t}:
2
2
  ${e.errors.map(r=>`${r.path}: ${r.message}`).join(`
3
- `)}`)},Er=(e,t={})=>{let r=Qa(t);return Zt(e,"$",r,1),t.positive&&_O(e,r),Ye(r.errors)},Qa=(e={})=>({target:e.target??"check",errors:[],map:Pe(e.map,e.mapName,"toPrisma"),scopeModels:[e.model],stepScopes:[false]}),Ku=e=>{let t=Qa(),r=at(e)?Zu(e,"$",t,1):null;r&&!Ji(r.mode)&&$(t,"$.aggregate.mode","invalid_aggregate_mode",ss(r.mode).message);let n=at(e)?e:{},o=r?.mode;return n.coerceType!==void 0&&(vo(n.coerceType)?["distinct","min","max"].includes(o)||$(t,"$.coerceType","unexpected_coerce_type","coerceType reads the values distinct, min and max return"):$(t,"$.coerceType","invalid_coerce_type",`coerceType must be one of: ${Object.keys(P).join(", ")}`)),n.caseInsensitive!==void 0&&(typeof n.caseInsensitive!="boolean"?$(t,"$.caseInsensitive","invalid_case_insensitive","caseInsensitive must be a boolean"):o!=="distinct"&&$(t,"$.caseInsensitive","unexpected_case_insensitive","caseInsensitive folds the strings distinct returns")),Ye(t.errors)},Gu=e=>{let t=Qa();return at(e)&&Yr(e,"$",t,1),Ye(t.errors)},MO=["if","array","aggregate"],_O=(e,t)=>H(e,r=>{let n=le(r),o=r.operator??r.dateOperator;return (n&&MO.includes(n)||typeof o=="string"&&Zi.includes(o))&&$(t,"$","notPositive",`${n==="field"||n==="date"?o:n} can hold on a missing value`),false}),DO=(e,t={})=>{Xr(Er(e,t),"validateRule");},Zt=(e,t,r,n)=>{if(typeof e=="boolean")return;if(!at(e)){$(r,t,"invalid_condition","Condition must be a boolean or object");return}let o=le(e);if(!o){$(r,t,"ambiguous_condition",xt().message);return}switch(o){case "all":Bu(e.all,`${t}.all`,r,n);break;case "any":Bu(e.any,`${t}.any`,r,n);break;case "if":Zt(e.if,`${t}.if`,r,n),Zt(e.then,`${t}.then`,r,n),"else"in e&&e.else!==void 0&&Zt(e.else,`${t}.else`,r,n);break;case "field":FO(e,t,r,n);break;case "aggregate":IO(e,t,r,n);break;case "array":qO(e,t,r,n);break;case "date":BO(e,t,r,n);break}},Bu=(e,t,r,n)=>{if(!Array.isArray(e)){$(r,t,"logical_array_required","Logical operator requires an array of conditions");return}e.forEach((o,i)=>{Zt(o,`${t}[${i}]`,r,n);});},Ps=(e,t,r,n)=>{typeof e.field=="string"&&zu(e.field,"field",`${t}.field`,r,n);},zu=(e,t,r,n,o,i=false)=>{let s=M(e)??(t==="path"?{depth:o}:null);if(!s)return;let a=t==="field"?"Field":"Path";s.depth>o&&$(n,r,"scope_out_of_bounds",va(e,s.depth,o)),n.target==="toPrisma"&&!i?$(n,r,`unsupported_prisma_${t}`,t==="path"?`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check()`:`${a} '${e}' is not supported by toPrisma()`):n.target==="toSql"&&(t==="field"||s.depth>1)&&$(n,r,`unsupported_sql_${t}`,`${a} '${e}' is not supported by toSql()`);},As=(e,t,r,n=false)=>{e.stepScopes[t]=n||e.stepScopes[t-1]===true;let o=e.scopeModels[t-1];e.scopeModels[t]=e.map&&o&&typeof r=="string"?Bo(r,e.map,o)??void 0:void 0;},Yr=(e,t,r,n,o=false)=>{let i=Jf.filter(a=>e[a]!==void 0);if(i.length>1)return $(r,t,"ambiguous_value_source","Takes one of value, path or bind"),null;if(i.length===0)return $(r,t,"missing_value_source","Requires value, path or bind"),null;let[s]=i;return s!=="value"&&(typeof e[s]!="string"||e[s]==="")?($(r,`${t}.${s}`,"invalid_value_source",`${s} is a non-empty string`),null):(e.bindOptional!==void 0&&(s!=="bind"||typeof e.bindOptional!="boolean")&&$(r,`${t}.bindOptional`,"invalid_value_source","bindOptional is a boolean beside bind"),s==="path"&&zu(e.path,"path",`${t}.path`,r,n,o),s)},Hu=(e,t,r,n,o,i)=>{let{offset:s}=e;if(s===void 0)return;let a=`${n}.offset`;if(!kf.includes(r)){$(o,a,"unsupported_offset_operator",`Operator '${r}' has no comparison point to offset`);return}if(!at(s)){$(o,a,"invalid_offset","An offset is one of { value }, { path } or { bind }");return}let l=Yr(s,a,o,i);if(l==="path"){let f=s.path,u=Fr(s);t==="date"&&u&&u.depth<=1&&o.target==="toSql"&&$(o,`${a}.path`,"unsupported_sql_path",`A row path on a date offset ('${f}') is not supported by toSql()`);return}if(l!=="value")return;let d=s.value;if(t==="field"){(typeof d!="number"||!Number.isFinite(d))&&$(o,`${a}.value`,"invalid_offset","A field offset value is a number");return}let p=at(d)&&Object.keys(d).length===1&&ee(d)?be(d):null;if(!p){$(o,`${a}.value`,"invalid_offset","A date offset value is { ago } or { ahead }");return}Yu(p[0],`${a}.value.${Object.keys(d)[0]}`,o,i);},Ju=(e,t,r,n)=>{n.target!=="toSql"||!ze.includes(t)||Fr(e)&&$(n,`${r}.path`,"unsupported_sql_path",`A range read from the row ('${e.path}') is not supported by toSql()`);},FO=(e,t,r,n)=>{if(typeof e.field!="string"&&$(r,`${t}.field`,"field_required","Field rule requires a string field"),Ps(e,t,r,n),typeof e.operator!="string"||!Bt(e.operator,"field")){$(r,`${t}.operator`,"invalid_operator",fe(e.operator,"field").message);return}let o=e.operator;Hu(e,"field",o,t,r,n),zi(o,"field",r.target)||$(r,`${t}.operator`,`unsupported_${Ts(r.target)}_operator`,`Operator '${o}' is not supported by ${r.target}()`),e.coerceType!==void 0&&!vo(e.coerceType)&&$(r,`${t}.coerceType`,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(P).join(", ")}`);let i=Ut(o,"field");if(i==="none"){WO(e,t,r);return}if(Yr(e,t,r,n,true)!==null){if(Ju(e,o,t,r),r.target==="toPrisma"&&typeof e.path=="string"){let s=Es(e,r.map,r.scopeModels[n-1],n>1,r.stepScopes[n-1]===true);"problem"in s&&$(r,`${t}.path`,"unsupported_prisma_path",$s(e.path,s.problem).message);}if(r.target==="toSql"&&typeof e.path=="string"&&r.map){let s=r.scopeModels[n-1],a=(M(e.path)??{path:e.path}).path,l=to(te(e.field,r.map,s),te(a,r.map,s),o);l&&$(r,`${t}.path`,"unsupported_sql_path",`'${e.path}': ${l}`);}r.target==="toSql"&&typeof e.path=="string"&&["array","pattern","string"].includes(i)&&((r.map?te(e.field,r.map,r.scopeModels[n-1]):void 0)?.isList&&bt.includes(o)||$(r,`${t}.path`,"unsupported_sql_path",`'${o}' against the column '${e.path}' has no SQL form`)),!(typeof e.path=="string"||typeof e.bind=="string")&&(jO(e,o,t,r,n),VO(i,e.value,o,`${t}.value`,r));}},jO=(e,t,r,n,o)=>{if(n.target!=="toPrisma"||!n.map||typeof e.field!="string")return;let i=te(e.field,n.map,n.scopeModels[o-1]);if(!i)return;let s=e.value,a=oe(e.caseInsensitive),l=dr.includes(t)&&Array.isArray(s),d=p=>$(n,`${r}.value`,"unsupported_prisma_operator",V("toPrisma",p).message);i.isList&&!l&&Array.isArray(s)&&s.includes(null)?d(`A list holding null in '${e.field}'`):i.isList&&!l&&a&&Or("text",s)?d(`A case-insensitive comparison on the list '${e.field}'`):We(i)&&a&&d(`A case-insensitive comparison on the Json column '${e.field}'`);},VO=(e,t,r,n,o)=>{switch(e){case "scalar":case "string":e==="string"&&typeof t!="string"&&$(o,n,"invalid_string_value",`Operator '${r}' requires a string value`);return;case "ordered":ge(t)||$(o,n,"invalid_ordered_value",`Operator '${r}' requires a string, number, or Date value`);return;case "array":Array.isArray(t)||$(o,n,"invalid_membership_value",`Operator '${r}' requires an array value`);return;case "pattern":{if(!(typeof t=="string"||t instanceof RegExp)){$(o,n,"invalid_pattern_value",`Operator '${r}' requires a string or RegExp value`);return}let i=du(t,o.target);i&&$(o,n,"unsupported_pattern",i);return}case "range":try{Jn(t,r);}catch(i){$(o,n,"invalid_range_value",i.message);}return}},Qu=(e,t,r,n,o)=>{let i=r.scopeModels[n-1];if(!(r.target!=="toPrisma"||!r.map||!i||typeof e.field!="string"))try{oo(e.field,r.map,i,o);}catch(s){$(r,`${t}.field`,"unsupported_prisma_relation",s.message);}},Zu=(e,t,r,n)=>{if(Qu(e,t,r,n,"Aggregate rules"),e.offset!==void 0&&$(r,`${t}.offset`,"unexpected_offset","Aggregate rules take no offset"),Xu(e,t,r,n),typeof e.field!="string"&&$(r,`${t}.field`,"field_required","Aggregate rule requires a string field"),Ps(e,t,r,n),!at(e.aggregate))return $(r,`${t}.aggregate`,"invalid_aggregate","aggregate must be an object"),null;let o=e.aggregate;return "field"in o&&o.field!==void 0&&typeof o.field!="string"&&$(r,`${t}.aggregate.field`,"invalid_aggregate_field","aggregate.field must be a string"),"condition"in e&&e.condition!==void 0&&(r.target==="toSql"&&$(r,`${t}.condition`,"unsupported_sql_aggregate_condition","Aggregate condition filtering is not supported by toSql(); use check() or toPrisma()"),As(r,n,e.field,true),Zt(e.condition,`${t}.condition`,r,n+1)),o},IO=(e,t,r,n)=>{let o=Zu(e,t,r,n);if(!o)return;if(Rt.includes(o.mode)||$(r,`${t}.aggregate.mode`,"invalid_aggregate_mode",ur(o.mode).message),!Hi.includes(e.operator)){$(r,`${t}.operator`,"invalid_aggregate_operator",`Aggregate rules only support: ${Hi.join(", ")}`);return}if(r.target==="toPrisma"&&typeof e.path=="string"&&$(r,`${t}.path`,"unsupported_prisma_aggregate_path","path is not supported by toPrisma() for aggregate rules; use value instead"),Yr(e,t,r,n)===null||typeof e.path=="string"||typeof e.bind=="string")return;let i=e.value;ze.includes(e.operator)?UO(i)||$(r,`${t}.value`,"invalid_range_value",`Operator '${e.operator}' requires a two-item numeric range`):typeof i!="number"&&$(r,`${t}.value`,"invalid_aggregate_value","Aggregate rule value must be a number");},qO=(e,t,r,n)=>{if(typeof e.field!="string"&&r.target!=="check"&&$(r,`${t}.field`,"field_required","Array rule requires a string field for this target"),Ps(e,t,r,n),Xu(e,t,r,n),typeof e.arrayOperator!="string"||!Bt(e.arrayOperator,"array")){$(r,`${t}.arrayOperator`,"invalid_array_operator",fe(e.arrayOperator,"array").message);return}let o=e.arrayOperator;Po(e)&&Qu(e,t,r,n,"Count operators");let i=r.target==="toPrisma"&&r.map&&typeof e.field=="string"?te(e.field,r.map,r.scopeModels[n-1]):void 0;i&&!L(i)&&o!=="empty"&&o!=="notEmpty"&&$(r,`${t}.arrayOperator`,"unsupported_prisma_array_operator",V("toPrisma",`'${o}' over the array column '${e.field}'`).message),zi(o,"array",r.target)||$(r,`${t}.arrayOperator`,`unsupported_${Ts(r.target)}_array_operator`,`Array operator '${o}' is not supported by ${r.target}()`);let s=Ut(o,"array"),a=e.condition!==void 0,l=()=>{e.count!==void 0&&$(r,`${t}.count`,"unexpected_count",`Array operator '${o}' does not accept count`);};s==="none"?(a&&$(r,`${t}.condition`,"unexpected_condition",`Array operator '${o}' does not accept condition`),l()):s==="predicate"?(a?(As(r,n,e.field),Zt(e.condition,`${t}.condition`,r,n+1)):$(r,`${t}.condition`,"missing_condition",Ve(o).message),l()):s==="count"&&(typeof e.count!="number"?$(r,`${t}.count`,"missing_count",Vn(o).message):e.count!==void 0&&!(typeof e.count=="number"&&Number.isInteger(e.count)&&e.count>=0)&&$(r,`${t}.count`,"invalid_count","count must be a non-negative whole number"),a?(As(r,n,e.field,Po(e)),Zt(e.condition,`${t}.condition`,r,n+1)):$(r,`${t}.condition`,"missing_condition",Ve(o).message));},BO=(e,t,r,n)=>{if(typeof e.field!="string"&&$(r,`${t}.field`,"field_required","Date rule requires a string field"),Ps(e,t,r,n),typeof e.dateOperator!="string"||!Bt(e.dateOperator,"date")){$(r,`${t}.dateOperator`,"invalid_date_operator",fe(e.dateOperator,"date").message);return}let o=e.dateOperator;Hu(e,"date",o,t,r,n);let i=Gt(e.value,Ba(e.offset));i&&$(r,t,"clock_unit_below_floor",i.message),zi(o,"date",r.target)||$(r,`${t}.dateOperator`,`unsupported_${Ts(r.target)}_date_operator`,`Date operator '${o}' is not supported by ${r.target}()`);let s=Ut(o,"date");if(s==="dayList"){if(Yr(e,t,r,n)!=="value")return;let a=e.value;(!Array.isArray(a)||!a.every(l=>typeof l=="string"&&Uf(l)))&&$(r,`${t}.value`,"invalid_day_list",`Date operator '${o}' requires an array of day names (${jn.join(", ")})`);return}if(Yr(e,t,r,n)!==null&&(Ju(e,o,t,r),!(typeof e.path=="string"||typeof e.bind=="string"))){if(ee(e.value)){Uu(e.value,o,`${t}.value`,r,n);return}if(No.includes(o)){$(r,`${t}.value`,"invalid_date_range",tt(o).message);return}if(s==="dateRange"){if(!KO(e.value)){$(r,`${t}.value`,"invalid_date_range",`Date operator '${o}' requires a two-item date range`);return}e.value.forEach((a,l)=>{ee(a)?Uu(a,o,`${t}.value[${l}]`,r,n):ge(a)&&!hr(a,Ie).isValid()&&$(r,`${t}.value[${l}]`,"invalid_date_value",`Date operator '${o}' value '${String(a)}' does not parse as a date`);});return}if(!ge(e.value)){$(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' requires a date-like value`);return}hr(e.value,Ie).isValid()||$(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' value '${String(e.value)}' does not parse as a date`);}},Yu=(e,t,r,n)=>{if(!at(e)||Object.keys(e).length===0){$(r,t,"invalid_relative_units","Relative offset requires at least one unit");return}for(let[o,i]of Object.entries(e)){if(!Fn(o)){$(r,`${t}.${o}`,"invalid_relative_unit",`Unknown relative unit '${o}'`);continue}let s=at(i)?Yr(i,`${t}.${o}`,r,n):"literal";if(s===null||s==="path"||s==="bind")continue;let a=s==="value"?i.value:i,l=Ia(a,o);l&&$(r,`${t}.${o}`,"invalid_relative_magnitude",l);}},Wu=(e,t,r)=>{(typeof e!="string"||!es.includes(e))&&$(r,t,"invalid_period_unit",`Unknown period unit '${String(e)}'`);},Uu=(e,t,r,n,o)=>{let i=No.includes(t),s=be(e);if(s){Yu(s[0],r,n,o);return}if(Lo(e)){Wu(Un(e),r,n);return}if(Mo(e)){if(i){$(n,r,"invalid_date_range",tt(t).message);return}let a="start"in e?e.start:e.end;if(!at(a)||!Lo(a)){$(n,r,"invalid_period_unit","start/end requires a this/last/next period");return}Wu(Un(a),r,n);return}$(n,r,"invalid_date_expression","Unrecognized date expression");},WO=(e,t,r)=>{"value"in e&&e.value!==void 0&&$(r,`${t}.value`,"unexpected_value","Rule does not accept value"),"path"in e&&e.path!==void 0&&$(r,`${t}.path`,"unexpected_path","Rule does not accept path"),"bind"in e&&e.bind!==void 0&&$(r,`${t}.bind`,"unexpected_bind","Rule does not accept bind");},Ts=e=>e==="toPrisma"?"prisma":e==="toSql"?"sql":"check",at=e=>re(e),UO=e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="number"&&typeof e[1]=="number",KO=e=>Array.isArray(e)&&e.length===2&&(ge(e[0])||ee(e[0]))&&(ge(e[1])||ee(e[1])),Xu=(e,t,r,n)=>{if(Ne(e)&&r.target!=="check"&&(r.target==="toPrisma"&&Xn(e)!==null||$(r,t,`unsupported_${Ts(r.target)}_window`,Et(r.target).message)),"filter"in e&&e.filter!==void 0&&(As(r,n,e.field),Zt(e.filter,`${t}.filter`,r,n+1)),"orderBy"in e&&e.orderBy!==void 0){let i=e.orderBy;Array.isArray(i)?i.forEach((s,a)=>{(!at(s)||typeof s.field!="string"||s.dir!=="asc"&&s.dir!=="desc")&&$(r,`${t}.orderBy[${a}]`,"invalid_order_by",'orderBy entries must be { field: string, dir: "asc" | "desc" }');}):$(r,`${t}.orderBy`,"invalid_order_by","orderBy must be an array of { field, dir }");}for(let i of ["take","skip"])if(i in e&&e[i]!==void 0){let s=e[i];(typeof s!="number"||!Number.isInteger(s)||s<0)&&$(r,`${t}.${i}`,`invalid_window_${i}`,`${i} must be a non-negative integer`);}},$=(e,t,r,n)=>{e.errors.push({path:t,code:r,message:n});};var GO=/[.:]/,Za=e=>{let t=[];for(let[r,n]of Object.entries(e.maps))for(let[o,i]of Object.entries(n.models))for(let[s,a]of Object.entries(i.fields))a.kind!=="bridge"&&GO.test(s)&&t.push({path:`${Le({fieldMap:r,model:o})}.${s}`,message:"contains forbidden character . or :",code:"invalid_field_name"});return Ye(t)},ec=e=>Xr(Za(e),"validateFieldMaps");var lt=e=>!Object.hasOwn(e,"parent"),Pt=e=>{let t=[],r=new Set,n=e;for(;!lt(n);){if(r.has(n))throw new Error("cycle detected in narrowing parent chain");if(Object.hasOwn(n,"model")||Object.hasOwn(n,"maps"))throw new Error("a narrowing carries a base lens key (model / maps); it has a parent instead");r.add(n),t.unshift(n),n=n.parent;}return t},pt=e=>lt(e)?e:Pt(e)[0].parent;var Ya=(e,t)=>t.length?U([...t,e]):e,zO=e=>{if(gr(e).length)return false;let t=e.field,r=typeof t=="string"?M(t):null;try{return ye(r?{...e,field:r.path}:e,{})===!0}catch{return false}},Xa=(e,t)=>{if(!t.length)return e;if(!zO(e))return U([...t.flatMap(o=>o.clamps),e]);let[r,...n]=t;return Kt([U([...r.clamps,Xa(e,n)]),U([{field:r.prefix,operator:"notExists"},e])])},so=(e,t,{paths:r=false}={})=>mr(e,{rewrite:n=>{if(Be(n))return n;if(typeof n.field!="string"||n.field==="")throw new T(`narrowRule: cannot re-root a relation clamp of unknown shape under '${t}'`,"unsupported_clamp");let o=gr(n),i=o.find(a=>M(a));if(r&&i)throw new T(`prefixConditionFields: cannot re-root a scope ref ('${i}') under '${t}'`,"unsupported_clamp");if(o.length&&!r)throw new T(`narrowRule: cannot re-root a relation clamp with a path reference ('${o[0]}') under '${t}'. Author the clamp without 'path', or anchor it at the relation itself.`,"unsupported_clamp");if(M(n.field))throw new T(`narrowRule: cannot re-root a relation clamp with a scope ref field ('${n.field}') under '${t}'. Author the clamp against the model's own columns.`,"unsupported_clamp");if(Oe(n)){for(let a of [n.condition,n.filter])if(a!==void 0&&io(a).escaping!==null)throw new T(`narrowRule: cannot re-root a relation clamp on '${n.field}' under '${t}': '${io(a).escaping}' inside it reads the row being re-rooted. Anchor such clamps at the relation's own model.`,"unsupported_clamp")}return {...r?zn(n,a=>Re(a)?{...a,path:`${t}.${a.path}`}:a):n,field:`${t}.${n.field}`}},below:()=>false}),el=(e,t)=>t.flatMap(r=>{let n=j(e,r.map,r.model,r.relPath);if(n.whereClauses.length===0)return [];if(r.isList)throw new T(`narrowRule: cannot enforce a to-many relation clamp on '${r.prefix}' without an arrayOperator condition to anchor it (row-scoped). Traverse '${r.prefix}' via an array operator (any/all/none/...) so the clamp can be injected safely.`,"unsupported_clamp");return [{prefix:r.prefix,clamps:n.whereClauses.map(o=>so(o,r.prefix))}]}),tc=(e,t)=>el(e,t).flatMap(r=>r.clamps),nc=(e,t,r)=>{let n=Ge(e,r);if("outOfBounds"in n)throw new T(`narrowRule: ${n.outOfBounds}`,"scope_out_of_bounds");if(!n.scope)return {hops:[],end:null};let o=e.slice(0,e.length-n.path.length);return Te(t.lens.maps,n.scope,n.path,o==="$."?"":o)},HO=(e,t,r)=>{if(M(e))return nc(e,t,r).hops;let n=r.length===1?"":`${"$".repeat(r.length)}.`;return r[0]?Te(t.lens.maps,r[0],e,n).hops:[]},rc=(e,t,r)=>{if(Be(e)||typeof e.field!="string"||e.field==="")return null;let{hops:n,end:o}=nc(e.field,t,r);return {hops:n,below:o}},en=(e,t,r)=>mr(e,{below:(n,o)=>{let i=rc(n,t,o);return i?i.below?[...o,i.below]:Oe(n)?[...o,null]:false:false},after:(n,o)=>{let i=rc(n,t,o);if(!i)return n;let s=tc(t,gr(n).flatMap(f=>HO(f,t,o))),a=i.below;if(!a||!Oe(n))return Ya(Xa(n,el(t,i.hops)),s);let l=[...j(t,a.mapName,a.modelName,a.relPath).whereClauses,...tc(t,Hn(n).flatMap(f=>Te(t.lens.maps,a,f).hops))],d=n.condition===void 0||n.arrayOperator===x.all||Ne(n),p={...n};return l.length&&d?p.filter=U([...n.filter!==void 0?[n.filter]:[],...l]):l.length&&(p.condition=U([...l,n.condition])),Ya(Xa(p,el(t,i.hops.slice(0,-1))),s)}},[r]),ao=(e,t)=>{let r=D(t),n=j(r,r.lens.mapName,r.lens.model,[]),o=en(e,r,{mapName:r.lens.mapName,modelName:r.lens.model,relPath:[]});return Ya(o,n.whereClauses)};var tl=(e,t)=>{let r=Ht(e,P.DateTime,t);return typeof r=="number"&&!Number.isNaN(new Date(r).getTime())?r:void 0},JO=(e,t,r)=>n=>{if(n==null)return n;let o=tl(n,r);if(o===void 0)throw new Error(`Invalid date value for DateTime field '${e}': ${String(n)}`);return t==="toPrisma"?new Date(o):new Date(o).toISOString()},lo=(e,t,r,n,o)=>{if(t==null||r?.kind==="json-path")return t;let i=r?.kind==="direct"?r.entry:void 0;if(i?.isList)return t;let s=i?Ke(i):void 0;if(e.coerceType!==void 0&&s!==void 0&&e.coerceType!==s)throw new Error(`coerceType '${e.coerceType}' overrides ${s} field '${e.field}', but ${n} compares the column as stored \u2014 evaluate it in memory with check(), or drop the override.`);if((s??e.coerceType)===P.DateTime){let l=JO(e.field,n,o());return Array.isArray(t)?t.map(l):l(t)}if(e.coerceType===void 0&&s===P.String&&(Array.isArray(t)?t:[t]).some(l=>typeof l=="number"||typeof l=="boolean"))throw new Error(`'${e.field}' is String but the literal is not a string; pass a string, or stamp coerceType: 'String'.`);if(e.coerceType===void 0&&s!==void 0&&(X.includes(s)||s===P.Boolean)&&(Array.isArray(t)?t:[t]).some(l=>typeof l=="string"))throw new Error(`'${e.field}' is ${s} but the literal is a string; pass a ${s===P.Boolean?"boolean":"number"}, or stamp coerceType: '${s}'.`);return e.coerceType!==void 0&&If.includes(e.coerceType)?Ht(t,e.coerceType,e.coerceType===P.DateTime?o():void 0):t};var oc=e=>Array.isArray(e)?e.flatMap(oc):[e],Uo=e=>e.value===void 0?null:oc(e.value),QO=e=>tl(e)!==void 0,ZO=/^-?\d+(\.\d+)?$/,YO={String:{expected:"a string",fits:e=>typeof e=="string"},Enum:{expected:"a string",fits:e=>typeof e=="string"},Int:{expected:"an integer",fits:Number.isSafeInteger},BigInt:{expected:"an integer",fits:Number.isSafeInteger},Float:{expected:"a number",fits:Number.isFinite},Decimal:{expected:"a number or a numeric string",fits:e=>Number.isFinite(e)||typeof e=="string"&&ZO.test(e)},Boolean:{expected:"a boolean",fits:e=>typeof e=="boolean"},DateTime:{expected:"a date",fits:QO},Json:{expected:"a value",fits:()=>true},Bytes:{expected:"a value",fits:()=>true}},XO=e=>typeof e=="string"?`'${e}'`:typeof e=="object"&&e!==null?JSON.stringify(e):String(e),ks=(e,t)=>{let r="coerceType"in e?e.coerceType:void 0,n=r??t;if(n===void 0||n===P.Json)return [];let o="operator"in e?e.operator:e.dateOperator,i=Mn(e);if(!i)return [];let a=r!==void 0&&r!==t?`field '${e.field}' coerced to ${n}`:`${n} field '${e.field}'`;if(!i.kinds.includes(n))return [{path:e.field,code:"operator_kind_mismatch",message:`operator '${o}' does not apply to ${a} (applies to: ${i.kinds.join(", ")})`}];if(e.offset!==void 0&&!("dateOperator"in e?n===P.DateTime:X.includes(n)))return [{path:e.field,code:"invalid_offset",message:`an offset does not apply to ${a}`}];if("dateOperator"in e||i.valueShape==="none"||i.valueShape==="pattern")return [];if(qf.includes(i.valueShape)&&Array.isArray(e.value))return [{path:e.field,code:"invalid_value_shape",message:`operator '${o}' compares one value, but ${a} was given a list`}];let{expected:l,fits:d}=YO[n],p=u=>{try{return d(Ht(u,n))}catch{return false}},f=u=>d(u)||r!==void 0&&p(u);return (Uo(e)??[]).filter(u=>u!==null&&!f(u)).map(u=>({path:e.field,code:"invalid_value",message:`value ${XO(u)} does not fit ${a} (expected ${l})`}))},ic=(e,t,r)=>{if(r.isList===true||We(r))return null;let n=L(r)?`arrayOperator '${t}' needs a list, but '${e}' is a to-one relation \u2014 a single related record; address its fields directly (e.g. '${e}.<field>')`:`arrayOperator '${t}' needs a list, but '${e}' is a single ${Ke(r)??r.type} value`;return {path:e,code:"invalid_array_operator",message:n}};var ex=(e,t,r,n)=>H(e,(o,i)=>{let s=le(o);if(s===null)return n.push({path:typeof o.field=="string"?o.field:"",code:"ambiguous_condition",message:xt().message}),false;if(Be(o))return;let a=o,l=w=>{let R=Ge(w,i);return "outOfBounds"in R?(n.push({path:w,code:"scope_out_of_bounds",message:R.outOfBounds}),null):{scope:R.scope,field:R.path}},d=i[i.length-1],p=true,f=null;if("field"in a&&typeof a.field=="string"&&a.field!==""){let w=fo(t,i,a.field);"issue"in w?(n.push({path:a.field,...w.issue}),p=false):{next:d,walked:f}=w;}let u=f?.entry??null,m=f?.terminalFieldName??null,y=f?.entry.kind==="enum",c=f?.entry.type??null,g=f&&f.jsonSubPath.length===0?Ls(f.terminalEffect,f.terminalFieldName):null;for(let{ref:w,role:R}of Fo(a)){let S=M(w)?l(w):{scope:Tt(t),field:w};if(!S||S.scope.open)continue;let b=po(t,S.scope,S.field);if(!b){n.push({path:w,...Cs(t,S.scope,S.field,R==="value"?"path (comparison ref) does not resolve through the narrowed lens":"offset or magnitude ref does not resolve through the narrowed lens")});continue}if(L(b.entry)){n.push({path:w,code:"not_in_lens",message:"a value ref reads a column, not a relation"});continue}let v=Ke(b.entry);if(R==="value"||R==="shift"||v===void 0)continue;(R==="whole"?jf.includes(v):X.includes(v))||n.push({path:w,code:"not_in_lens",message:`${R==="whole"?"a calendar unit reads a whole number":"an offset or magnitude reads a number"}, not ${v}`});}if(!p)return false;if("arrayOperator"in a&&typeof a.field=="string"&&u){let w=ic(a.field,a.arrayOperator,u);if(w)return n.push(w),false}if(u&&L(u)&&(s==="field"||s==="date")&&(u.isList||!Jt(a))){let w=a.field;return n.push({path:w,code:"operator_kind_mismatch",message:(u.isList?ns(w):fr(w)).message}),false}if(!u?.isList&&(s==="field"||s==="date")&&n.push(...ks(a,u?Ke(u):void 0)),!d.open)for(let w of Hn(a))w!==""&&!po(t,d,w)&&n.push({path:w,...Cs(t,d,w,"an orderBy or aggregate field does not resolve through the narrowed lens")});if(g&&"operator"in a&&m){let w=Uo(a);if(w){let R=new Set(g),S=y?`enum '${c}'`:`field '${m}'`;for(let b of w)typeof b=="string"&&!R.has(b)&&n.push({path:m,code:"value_not_allowed",message:`value '${b}' is not in the allowed set for ${S} (allowed: ${[...R].join(", ")})`});}}return [...i,d]},[r]),Ko=(e,t,r,n,o)=>{let i=[];return ex(e,t,{mapName:r,modelName:n,relPath:o,open:false},i),i},$r=(e,t)=>{let r=D(t);try{let n=Ko(e,r,r.lens.mapName,r.lens.model,[]);return n.length===0&&ao(e,t),Ye(n)}catch(n){if(!(n instanceof T))throw n;return Ye([{path:"",code:n.code,message:n.message}])}};var Ho=e=>e===void 0?void 0:Array.isArray(e)?e:[e],Jo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&("where"in e||"label"in e||"groupBy"in e||"from"in e),vr=e=>{if(Jo(e))return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===0)throw tx();return {where:e}},tx=()=>new T("sources: {} is not a Condition \u2014 use `true` for an unconstrained source","invalid_source"),ol=["__offpath__"],sc=new WeakMap,rx=(e,t)=>{if(!t)return new Map;let r=JSON.stringify([Go(t.parent),Go(e.maps),e.mapName,e.model,t.mapDefaults??null]),n=sc.get(t);if(n?.fingerprint===r)return n.trees;let o=new Map;return sc.set(t,{fingerprint:r,trees:o}),o},ac=new WeakMap,nx=0,Go=e=>{let t=ac.get(e);return t===void 0&&(t=nx++,ac.set(e,t)),t},he="\0",ox=e=>{let t=Object.entries(e.fields);return {relations:new Set(t.filter(([,r])=>L(r)).map(([r])=>r)),gated:t.filter(([,r])=>r.options!==void 0||r.kind==="enum"||r.values!==void 0)}},Ms=e=>e?String(Go(e)):"",D=e=>{let t=pt(e),r=lt(e)?[]:Pt(e);return {lens:t,chain:r,origin:r[0],memo:{trees:rx(t,r[0]),vetted:new Set,effects:new Map,places:new Map,models:new Map,refs:new Map,compiles:new Map}}},_s=(e,t)=>e===null?new Set(t):new Set(t.filter(r=>e.has(r))),ix=(e,t)=>{if(t.picks&&(e.picks=_s(e.picks,t.picks)),t.omits)for(let r of t.omits)e.omits.add(r);},dc=(e,t,r)=>{e.set(t,_s(e.get(t)??null,r));},fc=(e,t,r)=>{let n=e.get(t)??new Set;for(let o of r)n.add(o);e.set(t,n);},sx=(e,t,r)=>{if(r.enumPicks)for(let[n,o]of Object.entries(r.enumPicks))dc(e,n,o);if(r.enumOmits)for(let[n,o]of Object.entries(r.enumOmits))fc(t,n,o);},rl=(e,t,r)=>JSON.stringify([e,t,r]),ax=(e,t,r,n,o,i,s,a)=>{if(s&&ix(e,t),t.where!==void 0&&i&&(o(t.where),e.whereClauses.push(r(t.where)),(a?e.modelWheres:e.pathWheres).push({where:t.where,layer:n})),t.sources)for(let[l,d]of Object.entries(t.sources)){let p=vr(d),f=e.sources.get(l)??[],u=e.sourceWheres.get(l)??[];p.where!==void 0&&i&&(o(p.where,true),f.push(r(p.where)),u.push(p.where)),e.sources.set(l,f),e.sourceWheres.set(l,u);let m=Ho(p.groupBy);for(let[y,c,g]of [["label",p.label,e.sourceLabels.get(l)],["groupBy",m,e.sourceGroupBys.get(l)]]){if(c===void 0)continue;let w=rl(l,y,c);g!==void 0&&rl(l,y,g)===w||e.sourceDeclaredAt.set(w,n);}p.label!==void 0&&e.sourceLabels.set(l,p.label),m!==void 0&&e.sourceGroupBys.set(l,m),p.from==="mapDefaults"&&!e.sourcesFromMapDefaults.has(l)&&e.sourcesFromMapDefaults.set(l,n);}},T=class extends Error{constructor(r,n){super(r);this.code=n;}code;name="LensRefusal"},il=e=>new T(`a bare path ('${e}') reads the root row, which a clamp at a relation visit or a model default doesn't stand on: use a literal, a bind, or a \`$\` scope ref`,"invalid_value_source"),lx=(e,t,r)=>Ko(e,t,r.mapName,r.modelName,r.relPath),px=e=>new T(`a later layer's clamp reads what its parent does not show: '${e.path}' ${e.message}`,e.code),sl=e=>new T(`the scope ref '${e}' climbs out of the clamp: a clamp reads its own row ('$.'), literals and binds`,"scope_out_of_bounds"),io=e=>{let t=null,r=null;return H(e,(n,o)=>{if(Be(n))return;let i=gr(n);for(let s of [...typeof n.field=="string"?[n.field]:[],...i]){let a=M(s);r===null&&a&&a.depth>o&&(r=s);}for(let s of i)t===null&&!M(s)&&(t=s);return Oe(n)?o+1:void 0},1),{bare:t,escaping:r}},nl=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},n=[r];if(t.relPath.length>0)for(let i of Te(e.lens.maps,r,t.relPath.join(".")).hops)n.push({mapName:i.map,modelName:i.model,relPath:i.relPath});let o=n[n.length-1];return n.length===t.relPath.length+1&&o.mapName===t.mapName&&o.modelName===t.modelName?n:null},zo=(e,t)=>{let r=e;for(let n of t)r=O(r?.relations,n);return r},al=(e,t,r)=>{let n=i=>O(O(e.mapDefaults,i.mapName)?.models,i.modelName);if(!r){let i=n(t);return {defaults:i?[i]:[],path:void 0}}let o=[];for(let[i,s]of r.entries()){let a=zo(n(s),t.relPath.slice(i));a&&o.push(a);}return {defaults:o,path:zo(e.root,t.relPath)}},dx=(e,t,r,n)=>{let o=zo(t.root,r.relPath),i=[r.relPath.join(he),Object.keys(o?.relations??{}).join(he),(o?.omits??[]).join(he)].join(`${he}${he}`),s=n.get(i);if(s)return s;let a=new Map,l={lens:e},d=nl(l,r)??[r],p=new Set(d.map(u=>`${u.mapName}:${u.modelName}`)),f=[{at:r,below:[]}];for(;f.length>0;){let{at:u,below:m}=f.shift(),y=k(O(e.maps,u.mapName),u.modelName)?.fields??{},{defaults:c,path:g}=al(t,u,nl(l,u)),w=new Set(c.flatMap(b=>Object.keys(b.relations??{}))),R=new Set([...c,...g?[g]:[]].flatMap(b=>b.omits??[])),S=[];for(let[b,v]of Object.entries(y)){if(!w.has(b)||R.has(b)||g?.relations!==void 0&&Object.hasOwn(g.relations,b))continue;let E=ot(v,u.mapName);if(!E||!k(O(e.maps,E.mapName),E.modelName))continue;let q=`${E.mapName}:${E.modelName}`;p.has(q)||(p.add(q),S.push(b),f.push({at:{...E,relPath:[...u.relPath,b]},below:[...m,b]}));}a.set(m.join("."),S);}return n.set(i,a),a},fx=(e,t,r,n)=>{if(!n)return al(t,r,null).defaults.flatMap(d=>Object.keys(d.relations??{}));let o=r.relPath.length;for(;o>0&&zo(t.root,r.relPath.slice(0,o))===void 0;)o--;let i={...n[o],relPath:r.relPath.slice(0,o)},a=dx(e.lens,t,i,e.memo?.trees??new Map).get(r.relPath.slice(o).join("."))??[];return [...o===r.relPath.length?Object.keys(zo(t.root,r.relPath)?.relations??{}):[],...a]},Qo=(e,t,r)=>{let n=t;for(let o of Te(e.lens.maps,t,r).hops){let i=o.relPath[o.relPath.length-1];if(!j(e,n.mapName,n.modelName,n.relPath).relations.has(i))return o.prefix;n={mapName:o.map,modelName:o.model,relPath:o.relPath};}return null},j=(e,t,r,n)=>{let o=e.memo?lc(e,t,r,n):null,i=o===null?void 0:e.memo?.effects.get(o);if(i){if(!e.unvetted&&i.unchecked){for(let I of i.unchecked)I();i.unchecked=null;}return i.effect}let s=[],a={picks:null,omits:new Set,enumValuesByField:new Map,whereClauses:[],pathWheres:[],modelWheres:[],sources:new Map,sourceWheres:new Map,sourceLabels:new Map,sourceGroupBys:new Map,sourceDeclaredAt:new Map,sourcesFromMapDefaults:new Map,relations:new Set,relationFields:new Set},l=O(e.lens.maps,t),d=k(l,r);if(!d)return a;let p=e.memo?.models.get(d);p||(p=ox(d),e.memo?.models.set(d,p)),a.relationFields=p.relations;let f={mapName:t,modelName:r,relPath:n},u=e.origin??e.chain[0],m=`${Ms(u)}${he}${t}${he}${r}${he}${n.join(he)}`,y=e.memo?.places.get(m);if(!y){let I=nl(e,f);y={trail:I,turnedOn:u?fx(e,u,f,I):[]},e.memo?.places.set(m,y);}let{trail:c}=y,g=new Map,w=new Map,R=new Map,S=new Map,b=I=>I,v=0,E=()=>{},q=true,ue=true,A=(I,B=false)=>{ax(a,I,b,v,E,q,ue,B),sx(g,w,I);};for(let[I,B]of e.chain.entries()){v=I;let Tr={...e,clamp:false,skipClampsOf:void 0,skipHidingOf:void 0,chain:e.chain.slice(0,I)};q=B!==e.skipClampsOf,ue=B!==e.skipHidingOf,b=ne=>I===0?ne:en(ne,Tr,{mapName:t,modelName:r,relPath:n});for(let[ne,we]of Object.entries(O(B.mapDefaults,t)?.enums??{}))we.picks&&dc(R,ne,we.picks),we.omits&&fc(S,ne,we.omits);let{defaults:yo,path:kr}=al(B,f,c),ce=I===0?null:Tr,ut=ne=>(we,Se=false)=>{let ke=e.memo?.refs.get(we);if(ke||(ke=io(we),e.memo?.refs.set(we,ke)),ke.bare!==null&&!(ne&&!Se))throw il(ke.bare);if(ke.escaping!==null)throw sl(ke.escaping);if(!ce)return;let Ul=()=>{let di=typeof we=="object"&&we!==null?`${Go(we)}${he}${lc(ce,t,r,n)}`:null;if(di!==null&&ce.memo?.vetted.has(di))return;let[Kl]=lx(we,ce,f);if(Kl)throw px(Kl);di!==null&&ce.memo?.vetted.add(di);};e.unvetted?s.push(Ul):Ul();};E=ut(false);let on=O(O(B.mapDefaults,t)?.models,r);for(let ne of yo)A(ne,ne===on);kr&&(E=ut(n.length===0&&c!==null),A(kr));}if(u&&e.chain.includes(u))for(let I of y.turnedOn)a.relationFields.has(I)&&!a.omits.has(I)&&a.relations.add(I);for(let[I,B]of p.gated){let Tr=B.kind==="enum",kr=B.options?.map(ne=>ne.value)??(Tr?Gr(B,l?.enums):B.values);if(!kr)continue;let ce=kr;if(Tr){let ne=R.get(B.type),we=S.get(B.type);ne&&(ce=ce.filter(Se=>ne.has(Se))),we&&(ce=ce.filter(Se=>!we.has(Se)));}let ut=g.get(I),on=w.get(I);ut&&(ce=ce.filter(ne=>ut.has(ne))),on&&(ce=ce.filter(ne=>!on.has(ne))),a.enumValuesByField.set(I,ce);}return o!==null&&e.memo?.effects.set(o,{effect:a,unchecked:s.length?s:null}),a},lc=(e,t,r,n)=>{let o=pc.get(e);if(o===void 0){o=`${Ms(e.origin)}${he}${Ms(e.skipClampsOf)}${he}${Ms(e.skipHidingOf)}${he}`;for(let i of e.chain)o+=`${Go(i)},`;pc.set(e,o);}return `${o}${he}${t}${he}${r}${he}${n.join(he)}`},pc=new WeakMap,Yt=e=>{let t=[],r=(n,o)=>{let i=O(e.lens.maps,n.mapName);if(!k(i,n.modelName))return;let s=j(e,n.mapName,n.modelName,n.relPath);t.push({path:o,at:n,effect:s});for(let a of s.relations){let l=Ae(i,n.modelName,a),d=l&&ot(l,n.mapName);d&&r({...d,relPath:[...n.relPath,a]},`${o}.${a}`);}};return r({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},e.lens.model),t},Ds=(e,t,r,n)=>j(e,t,r,ol).sources.has(n),Fs=(e,t,r,n)=>new T(`source '${n}' at '${e}' offers mapDefaults.${t}.models.${r}.sources.${n}, which no layer declares`,"invalid_source"),kt=(e,t)=>e.omits.has(t)?false:e.relationFields.has(t)?e.relations.has(t):!(e.picks!==null&&!e.picks.has(t)),Ls=(e,t)=>e.enumValuesByField.get(t)??null,tn=(e,t,r)=>{let n=r.split("."),o=[],i=[];for(let{index:s,field:a,at:l,entry:d,next:p}of Sr(e.lens.maps,t,r)){if(!d)return {resolution:{outcome:"missing",index:s,hops:o},effects:i};let f=j(e,l.mapName,l.modelName,l.relPath);if(!(e.clamp&&L(d)?!f.omits.has(a):kt(f,a)))return {resolution:{outcome:"hidden",index:s,hops:o},effects:i};let m={field:a,entry:d,mapName:l.mapName,model:l.modelName,relPath:[...l.relPath]};o.push(m),i.push(f);let y=s===n.length-1;if(y||We(d))return {resolution:{outcome:"resolved",hops:o,terminal:m,jsonSubPath:y?[]:n.slice(s+1)},effects:i};if(!p)return {resolution:{outcome:"pastScalar",index:s,hops:o},effects:i}}return {resolution:{outcome:"missing",index:n.length,hops:o},effects:i}},uo=(e,t,r,n,o)=>{let i=o==="label"?t.sourceLabels.get(n):t.sourceGroupBys.get(n);if(i===void 0)return true;let s=t.sourceDeclaredAt.get(rl(n,o,i)),a=(p,f)=>tn(p,r,f).resolution.outcome!=="hidden",l={...e,clamp:true},d={...l,skipHidingOf:s===void 0?void 0:e.chain[s]};return (typeof i=="string"?[i]:i).every(p=>Qo(e,r,p)===null&&(a(l,p)||a(d,p)))},po=(e,t,r)=>{let{resolution:n,effects:o}=tn(e,t,r);if(n.outcome!=="resolved")return null;let{terminal:i,jsonSubPath:s}=n;return {mapName:i.mapName,modelName:i.model,relPath:i.relPath,entry:i.entry,terminalEffect:o[o.length-1],terminalFieldName:i.field,jsonSubPath:s}},Cs=(e,t,r,n)=>{let{resolution:o}=tn(e,t,r);if(o.outcome!=="hidden")return {code:"not_in_lens",message:n};let i=r.split("."),s=o.hops.at(-1),a=s?{mapName:s.mapName,modelName:s.model,relPath:[...s.relPath,s.field]}:t,l=s&&ot(s.entry,s.mapName),d=l?{...l,relPath:a.relPath}:t,p=j(e,d.mapName,d.modelName,d.relPath),f=i[o.index];return !p.relationFields.has(f)||p.omits.has(f)?{code:"not_in_lens",message:n}:{code:"not_in_lens",message:`'${i.slice(0,o.index+1).join(".")}' is a relation the lens does not turn on (turn it on with \`relations\`)`}},Tt=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[],open:false}),fo=(e,t,r)=>{let n=Ge(r,t);if("outOfBounds"in n)return {issue:{code:"scope_out_of_bounds",message:n.outOfBounds}};if(n.scope.open)return {from:n.scope,next:n.scope,walked:null};let o=po(e,n.scope,n.path);if(!o)return {issue:Cs(e,n.scope,n.path,"path does not resolve through the narrowed lens")};let i=We(o.entry),s=ot(o.entry,o.mapName),a=s?{...s,relPath:[...o.relPath,o.terminalFieldName],open:i}:{...n.scope,open:i};return {from:n.scope,next:a,walked:o}},Te=(e,t,r,n="")=>{let o=r.split("."),i=[],s=null;for(let{index:a,field:l,at:d,entry:p,next:f}of Sr(e,t,r)){if(!p||!f)break;let u=[...d.relPath,l];i.push({map:f.mapName,model:f.modelName,relPath:u,prefix:`${n}${o.slice(0,a+1).join(".")}`,isList:p.isList===true}),a===o.length-1&&(s={...f,relPath:[...u]});}return {hops:i,end:s}};var pl="parent:",dl=e=>e.startsWith(pl),cc=e=>dl(e)?e.slice(pl.length):e,ll=(e,t)=>{let r={...e};if(e.where!==void 0&&(r.where=t(e.where)),e.sources){let n={};for(let[o,i]of Object.entries(e.sources))n[o]=Jo(i)?i.where!==void 0?{...i,where:t(i.where)}:i:t(i);r.sources=n;}if("relations"in e&&e.relations){let n={};for(let[o,i]of Object.entries(e.relations))n[o]=ll(i,t);r.relations=n;}return r},mc=(e,t)=>{let r={};for(let[n,o]of Object.entries(e.mapDefaults??{})){let i={};for(let[s,a]of Object.entries(o.models??{}))i[s]=ll(a,t);r[n]=o.models?{...o,models:i}:o;}return {...e,root:e.root?ll(e.root,t):void 0,mapDefaults:e.mapDefaults?r:void 0}},fl=e=>{let t=[];return mc(e,r=>(t.push(r),r)),t},uc=e=>{let t=new Set;for(let r of fl(e))for(let n of jo(r))dl(n)||t.add(n);return t},gc=e=>{let t=new Set;for(let r of Pt(e))for(let n of fl(r))for(let o of jo(n,{required:true}))t.add(cc(o));return [...t].sort()},yc=(e,t)=>{if(lt(e))return e;let r={...t};for(let[n,o]of Object.entries(t))r[`${pl}${n}`]=o;return {...mc(e,n=>ja(n,r)),parent:yc(e.parent,t)}},hc=(e,t)=>yc(e,t),wc=e=>{let t=[],r=new Set;for(let o of Pt(e.parent))for(let i of uc(o))r.add(i);for(let o of uc(e))r.has(o)&&t.push(`bind name '${o}' already declared by an ancestor narrowing \u2014 rename it, or reference the inherited one as 'parent:${o}'`);let n=new Set;for(let o of fl(e))for(let i of jo(o))dl(i)&&n.add(cc(i));for(let o of n)r.has(o)||t.push(`bind 'parent:${o}' references an inherited binding no ancestor declares`);return t};var bc=(e,t)=>e===void 0?t:t===void 0?e:{all:[e,t]},ux=(e,t)=>{if(!e||!t)return e??t;let r={...e};for(let[n,o]of Object.entries(t)){let i=r[n];if(i===void 0){r[n]=o;continue}let s=vr(i),a=vr(o),l=bc(s.where,a.where);r[n]={...s,...a,...l===void 0?{}:{where:l}};}return r},Rc=(e,t)=>{let r=bc(e?.where,t.where),n=ux(e?.sources,t.sources);return {...e,...r===void 0?{}:{where:r},...n?{sources:n}:{}}},cx=(e,t)=>{let r={...e?.models};for(let[n,o]of Object.entries(t))r[n]=Rc(r[n],o);return {...e,models:r}},Sc=(e,t)=>{let r={...e.mapDefaults};for(let[n,{models:o}]of Object.entries(t.mapDefaults??{}))r[n]=cx(r[n],o);return {...e,...t.root?{root:Rc(e.root,t.root)}:{},...t.mapDefaults?{mapDefaults:r}:{}}},ul=(e,t)=>lt(e)?Sc({parent:e},t):lt(e.parent)?Sc(e,t):{...e,parent:ul(e.parent,t)};var Oc=(e,t)=>{let r=D(t),n=(o,i)=>typeof o=="string"&&o!==""?fo(r,i,o):null;return mr(e,{rewrite:(o,i)=>{if(le(o)!=="field"||o.coerceType)return o;let s=n(o.field,i);if(!s||"issue"in s||!s.walked||s.walked.jsonSubPath.length)return o;let{entry:a}=s.walked;return a.kind==="scalar"&&Vf.includes(a.type)?{...o,coerceType:a.type}:o},below:(o,i)=>{if(!Oe(o))return false;let s=n(o.field,i),a=s&&!("issue"in s)?s.walked?.entry:void 0;return s&&!("issue"in s)&&a&&L(a)?[...i,s.next]:false}},[Tt(r)])};var xc=({maps:e,bridges:t,mapName:r,model:n})=>({...Ss({maps:e,bridges:t}),mapName:r,model:n});var mx=(e,t)=>H(e,(r,n)=>{if(t.sources.add(n[n.length-1].mapName),Be(r)||typeof r.field!="string"||r.field==="")return;let o=fo(t.policy,n,r.field);return "issue"in o?false:(o.walked&&(t.sources.add(o.walked.mapName),(o.walked.entry.kind==="bridge"||o.walked.mapName!==o.from.mapName)&&(t.bridgesCrossed=true)),[...n,o.next])},[Tt(t.policy)]),Ec=(e,t)=>{let n={policy:D(t),sources:new Set,bridgesCrossed:false};return mx(e,n),{sources:[...n.sources].sort(),bridgesCrossed:n.bridgesCrossed,supportedTargets:_.filter(o=>(o==="check"||!n.bridgesCrossed)&&Er(e,{target:o,map:n.policy.lens,mapName:n.policy.lens.mapName,model:n.policy.lens.model}).ok),errors:$r(e,t).errors}};var gx=new Set([Wt.scalar,Wt.ordered,Wt.array,Wt.dayList,Wt.dateValue]),yx=new Set([Wt.none,Wt.count]),hx=e=>{if(e.offset!==void 0||Do(e).some(({source:r})=>r.value===void 0))return {values:[],dynamic:true};let t=Mn(e);return t?yx.has(t.valueShape)?{values:[],dynamic:false}:gx.has(t.valueShape)?"value"in e?{values:Uo(e)??[],dynamic:false}:{values:[],dynamic:false}:{values:[],dynamic:true}:{values:[],dynamic:true}},wx=e=>e instanceof Date?`d:${+e}`:e instanceof RegExp?`r:${e}`:typeof e=="object"&&e!==null?`j:${JSON.stringify(e)}`:`p:${typeof e}:${String(e)}`,$c=(e,t)=>{let r=D(t),n=r.lens.model,o=new Map,i=new Map,s=(l,d)=>{if(l.length===0)return;let p=po(r,{mapName:r.lens.mapName,modelName:n,relPath:[]},l.join("."));if(!p||p.jsonSubPath.length>0)return;let{mapName:f,modelName:u,relPath:m,terminalEffect:y,terminalFieldName:c}=p;if(!y.sources.has(c))return;let g=[n,...m].join("."),w=`${g}|${c}`,R=o.get(w);R||(R={path:g,mapName:f,model:u,field:c,values:[],dynamic:false},o.set(w,R));let S=hx(d);S.dynamic&&(R.dynamic=true);let b=i.get(w)??new Set;i.set(w,b);for(let v of S.values){let E=wx(v);b.has(E)||(b.add(E),R.values.push(v));}},a=(l,d)=>{let p=Ge(l,d);if(!("outOfBounds"in p))return [...p.scope,...p.path.split(".")]};return H(e,(l,d)=>{if(Be(l))return;let p=typeof l.field=="string"?a(l.field,d):d.at(-1);return p?(!Oe(l)&&typeof l.field=="string"&&s(p,l),[...d,p]):false},[[]]),[...o.values()]};var js=(e,t,r,n)=>{let o=Sx(e,t,r);if(o.options===t)return n(o.condition,o.options);try{return n(o.condition,o.options)}catch(i){if(i instanceof T||i instanceof C)throw i;try{n(e,o.options);}catch{throw i}throw new T(`${r}: the lens's clamps on this rule have no ${r} form \u2014 ${i.message}`,"unsupported_target")}},Sx=(e,t,r)=>{if(t?.lens===void 0)return {condition:e,options:t};let{lens:n}=t;if(t.map!==void 0||t.mapName!==void 0||t.model!==void 0)throw new C(`${r}: pass \`lens\` or \`map\` / \`mapName\` / \`model\`, not both \u2014 the lens names its own`);let o=$r(e,n);if(!o.ok)throw new Error(`${r}: the rule leaves the lens \u2014 ${o.errors.map(s=>`${s.path}: ${s.message}`).join("; ")}`);let i=pt(n);return {condition:ao(e,n),options:{...t,lens:void 0,map:i,mapName:i.mapName,model:i.model}}};var Vs=(e,t,r,n)=>{if(!Af.includes(e.operator))throw new Error(`'${e.operator}' does not apply to the enum '${e.field}'; compare its values with equals / in.`);let o=oe(e.caseInsensitive),i=Gr(r,n?.enums),{values:s,hasNull:a}=Je(Ot.includes(e.operator)?[t]:t);if(!o&&(!i||s.every(f=>typeof f=="string"&&i.includes(f))))return null;if(!i)throw new Error(`'${e.field}' is an enum: a case-insensitive comparison reads its declared values, which the map doesn't list.`);let l=f=>o?f.toLowerCase():f,d=new Set(s.filter(f=>typeof f=="string").map(f=>l(f))),p=i.filter(f=>d.has(l(f)));return W.includes(e.operator)?{values:i.filter(f=>!p.includes(f)),matchesNull:!a}:{values:p,matchesNull:a}};var se=e=>`"${e.replace(/"/g,'""')}"`;var Ee=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),cl=(e,t,r=false)=>{let[n,...o]=e.split("."),i=t?`${se(t)}.${se(n)}`:se(n);if(o.length===0)return i;let s=o.map(ml),a=s.pop();return [i,...s].join("->")+(r?"->":"->>")+a},ml=e=>`'${e.replace(/'/g,"''")}'`;var bx=["@prisma/client/runtime/client","@prisma/client/runtime/library"],Is,Rx=()=>{if(Is!==void 0)return Is;for(let e of Ox())for(let t of bx)try{let r=e(t);if(r.AnyNull!==void 0)return Is=r.AnyNull,Is}catch{}},Ox=()=>{let e=[];try{let t=globalThis.process?.getBuiltinModule?.("module")?.createRequire;t&&e.push(t(import.meta.url));}catch{}return typeof wa=="function"&&e.push(wa),e},vc=()=>{let e=Xe.get("prismaOptions.anyNull")??Rx();if(e===void 0)throw new Error("A null check on a Json field needs Prisma's AnyNull, and @prisma/client isn't installed: engineGlobals.set('prismaOptions.anyNull', Prisma.AnyNull).");return e};var Nc=(e,t)=>{let r=Ur(it(t));return r===null?null:Wr(e,r)},Ac=(e,t,r)=>{if(e===null)return null;let n=Qn(it(t)),o=n&&Br(n[0],Wo);return !n||!o?null:cr(vt(e),o,n[1],ro(r).timeZone).toDate()};var yl=(e,t)=>Ue(e,t?.map,t?.model),Ct=e=>e==="json"||e==="json-path",Nr=e=>Ct(e)?vc():null,rn=(e,t)=>t?.map&&t?.model?$u(e,t.map,t.model).map(r=>Zr(r,{is:null})):[],hl=(e,t)=>{let r=yl(e,t);return [...Ct(r)||r==="list"||te(e.field,t?.map,t?.model)?.isRequired===false?[dt(e.field,{equals:Nr(r)},t)]:[],...rn(e.field,t)]},qs=(e,t,r,n)=>{if(r.mode&&Ct(n)&&Array.isArray(t))throw V("toPrisma",`A case-insensitive comparison of a Json value with the list ${JSON.stringify(t)}`);if(!r.mode||typeof t!="string")return {[e]:t,...r};if(!Ct(n))return {[e]:Ee(t),...r};if(/[%_\\"\u0000-\u001f]/.test(t))throw V("toPrisma",`A case-insensitive equality on Json against '${t}'`,"Prisma matches the JSON text, where %, _, a backslash, a quote or a control character doesn't read as itself");return {[e]:t,...r}},wl=(e,t,r,n)=>{let o=t?.datasource?.provider??Xe.get("prismaOptions.datasource.provider");return oe(e.caseInsensitive)&&Rf(o)&&Or(r,n)?{mode:"insensitive"}:{}},Pc=(e,t)=>{if(e==="list")return [{isEmpty:true}];let r=t?[{equals:""}]:[];return Ct(e)?[...r,{equals:[]}]:r},Tc=e=>"isEmpty"in e?{isEmpty:false}:{not:e.equals},Sl=(e,t,r,n,o)=>{let i=a=>dt(e,a,o),s=Pc(t,n);return r?K([i({equals:Nr(t)}),...rn(e,o),...s.map(a=>i(a))]):Ze([...t==="list"?[]:[i({not:Nr(t)})],...s.map(a=>i(Tc(a)))])},Ex=(e,t)=>{if(!Jt(e))throw fr(e.field);let n=(o=>dt(e.field,o,t))({is:{}});return ye({...e,field:"relation"},{relation:null})===true?Me(n):n},$x=(e,t)=>te(e.field,t?.map,t?.model),gl=st(),vx=(e,t,r)=>{if(t==="list"||Ct(t)||$x(e,r)?.isRequired!==true)return null;let n=e.field.split(".").slice(0,-1).join(".");return n?dt(n,{is:{}},r):gl},kc=(e,t)=>{let r=c=>dt(e.field,c,t),n=yl(e,t),o=()=>hl(e,t),i=bs(e,t?.map,t?.model);if(n==="relation")return Ex(e,t);let s=vx(e,n,t),a=s&&(s===gl?At():Me(s)),l=c=>s&&a?ye({field:"f",operator:c,value:null},{f:null})===true?a:s:null;if(s&&a&&Jt(e)){let c=Pc(n,i);return e.operator===h.isEmpty?K([a,...c.map(r)]):e.operator===h.notEmpty?Ze([s,...c.map(g=>r(Tc(g)))]):l(e.operator)}switch(e.operator){case h.exists:case h.notExists:{if(e.operator===h.exists)return n==="list"?Me(r({equals:null})):r({not:Nr(n)});let c=o();return c.length?K(c):r({equals:Nr(n)})}case h.isEmpty:case h.notEmpty:return Sl(e.field,n,e.operator===h.isEmpty,i,t)}if(Re(e)){let c=Es(e,t?.map,t?.model,Lu(t),Mu(t));if("problem"in c)throw $s(e.path,c.problem);let g=r({[c.key]:c.ref}),w=(v,E)=>E.isRequired===false?dt(v,{equals:null},t):null,R=(v,E)=>E.isRequired===false?dt(v,{not:null},t):gl,S=w(e.field,c.field),b=w(c.columnPath,c.column);return e.operator===h.equals?S&&b?K([g,Ze([S,b])]):g:e.operator===h.notEquals?K([Me(g),...S?[Ze([S,R(c.columnPath,c.column)])]:[],...b?[Ze([R(e.field,c.field),b])]:[]]):g}let d=Cc(e,t);if(xe(e,d))return K(W.includes(e.operator)?o():[]);if(d===null&&Ot.includes(e.operator)){let c=l(e.operator);if(c)return c}if(n==="list"&&dr.includes(e.operator)&&Array.isArray(d))return de(ys(e,d),t);if(n==="list"&&Array.isArray(d)&&d.includes(null))throw V("toPrisma",`A list holding null in '${e.field}'`);if(n==="list"&&oe(e.caseInsensitive)&&Or("text",d))throw V("toPrisma",`A case-insensitive comparison on the list '${e.field}'`);let p=n==="enum"?te(e.field,t?.map,t?.model):void 0,f=p?Vs(e,d,p,t?.map):null;if(f){let c=r({in:f.values});return f.matchesNull?K([c,...o()]):c}if(dr.includes(e.operator)){let{values:c,hasNull:g}=Je(d),w=wl(e,t,n,c),R=Ct(n)?e.operator===h.in?K(c.map(S=>r(qs("equals",S,w,n)))):Ze(c.map(S=>r(qs("not",S,w,n)))):r({[e.operator]:c,...w});return e.operator===h.in?g?K([R,...o()]):R:g?Ze([R,s??r({not:Nr(n)})]):K([R,...o()])}let u=c=>{if(!Ct(n)||c!==h.contains)return r(Zo({...e,operator:c},t));let g=r({array_contains:[Nx(e,d,t,n)]});return typeof d=="string"?K([r(Zo({...e,operator:c},t)),g]):g};if(e.operator===h.contains)return u(h.contains);let m=_f.includes(e.operator)?ko[e.operator]:Dn.includes(e.operator)?h.between:void 0;if(m){if(Ct(n))throw V("toPrisma",`'${e.operator}' on the Json value '${e.field}'`,"it keeps values of other types");return K([Me(u(m)),...o()])}let y=r(Zo(e,t));return e.operator===h.equals&&d===null?K([y,...rn(e.field,t)]):e.operator===h.notEquals&&n==="list"?d===null?Me(r({equals:null})):K([Me(r({equals:d})),...o()]):e.operator===h.notEquals&&d!==null?K([y,...o()]):y},Cc=(e,t)=>{let r=lo(e,it(e),br(e.field,t?.map,t?.model),"toPrisma",()=>ro(t).timeZone);return e.offset===void 0?r:Nc(r,e.offset)},Zo=(e,t)=>{let r=os(e);if(r)throw r;let n=yl(e,t),o=()=>Cc(e,t),i=d=>wl(e,t,n,d),s=d=>{let p=o();if(n==="list"){if(d!=="contains")throw new Error(`Operator '${d}' does not apply to the list '${e.field}'.`);return {has:p}}let f=Ct(n)?Ax[d]:d,u=typeof p=="string"?Ee(p):p;return {[f]:u,...i(p)}},a=is(e.operator,o());if(a)throw a;let l=lr(e.operator,"field");if(l&&_n.includes(e.operator))return {[l]:o()};switch(e.operator){case h.equals:{let d=o()??Nr(n);return qs("equals",d,i(d),n)}case h.notEquals:{let d=o()??Nr(n);return qs("not",d,i(d),n)}case h.in:case h.notIn:return {[e.operator]:o()};case h.contains:return s("contains");case h.startsWith:return s("startsWith");case h.endsWith:return s("endsWith");case h.matches:case h.notMatches:throw V("toPrisma",`'${e.operator}'`,"Prisma has no pattern filter");case h.between:case h.notBetween:{let[d,p]=He(rt(o(),e.operator));return {gte:d,lte:p}}default:throw new Error(`Operator '${e.operator}' is built by buildFieldRule`)}},Nx=(e,t,r,n)=>{if(typeof t=="object"&&t!==null)throw new Error(`Membership of an object or a list in the Json array '${e.field}' has no exact Prisma form; use toSql() or check().`);if(wl(e,r,n,t).mode)throw V("toPrisma",`A case-insensitive member of the Json array '${e.field}'`);return t},Ax={contains:"string_contains",startsWith:"string_starts_with",endsWith:"string_ends_with"},dt=(e,t,r)=>{if(!r?.map||!r?.model)return Zr(e,t);let n=ie(e,r.map,r.model),o=n.hops.find(s=>s.entry.isList);if(o)throw Bn(e,o);let i=e.split(".");switch(n.kind){case "fallback":case "direct":return Zr(e,t);case "bridge":return Qr();case "past-scalar":throw Wn(e,n.column);case "json-path":{let s={path:n.jsonPath,...t},a=i.slice(0,n.stopIndex).join(".");return Zr(a,s)}}};var Lc=(e,t,r)=>{if(Ne(e)){let n=Xn(e);if(!n)throw Et("toPrisma");return de(n,t,r)}if(!t?.map||!t?.model||!r)throw new Error("Aggregate rules require a FieldMap and model to generate a Prisma plan. Pass { map, model } options to toPrisma().");if(!Rt.includes(e.aggregate.mode))throw ur(e.aggregate.mode);if(!e.aggregate.field)throw new Error("Prisma aggregate rules require aggregate.field to specify the numeric field on the related model.");return Px(e,t,r)},Px=(e,t,r)=>{let n=oo(e.field,t.map,t.model,"Aggregate rules");if(e.condition&&Nt(e.condition,t.map,n.target))return Qr();let o=e.aggregate.field??"",i=Ae(t.map,n.target,o);if(!i)throw new Error(`aggregate.field '${o}' does not exist on model '${n.target}'.`);if(i.kind!=="scalar"||We(i))throw new Error(`aggregate.field '${o}' on model '${n.target}' must be a numeric scalar, got ${i.kind==="scalar"?"Json":`'${i.kind}'`}.`);let s=no(t)(e);if(s===null||xe(s,s.value))return At();let a=qo(s,[{}],void 0,{},{value:0})===true,l=a?Qe(s):s,d=Zo(l,t),p={[e.aggregate.mode==="sum"?"_sum":"_avg"]:d},f=Dn.includes(l.operator)?Me({[o]:p}):{[o]:p},u=e.condition?de(e.condition,Jr({...t,model:n.target},t,true),r):st(),m=Ns(r,n,u,f,a);return a?K([m,...rn(e.field,t)]):m};var _c=(e,t,r)=>{if(!e.field)throw new Error("toPrisma: count-based ArrayRule requires a field path");let n=oo(e.field,t.map,t.model,"Count operators");if(e.condition===void 0)throw Ve(e.arrayOperator);if(e.count===void 0)throw Vn(e.arrayOperator);let o=e.count;if(e.arrayOperator===x.atLeast&&o===0)return st();let i=de(e.condition,Jr({...t,model:n.target},t,true),r),s=bl(e),a=s?Mc(x.atLeast,e.arrayOperator===x.atMost?o+1:1,n.targetKey):Mc(e.arrayOperator,o,n.targetKey);return Ns(r,n,i,a,s)},Mc=(e,t,r)=>{let n=lr(e,"array");if(!n)throw new Error(`'${e}' does not count`);return {[r]:{_count:{[n]:t}}}};var Dc=(e,t,r)=>{let n=Fc(e,t,r);return e.field&&bl(e)&&!jc(e.field,t)?K([n,...rn(e.field,t)]):n},bl=e=>ye({...e,field:"items"},{items:[]})===true,Tx=e=>{let t=Ta(e);if(!t)return null;let{count:r,...n}=e;return {...n,arrayOperator:t}},Fc=(e,t,r)=>{if(Ne(e)){let s=Xn(e);if(!s)throw Et("toPrisma");return de(s,t,r)}if(e.condition!==void 0&&!Lf.includes(e.arrayOperator)&&Nt(e.condition,t?.map,Vc(e,t)?.model))return Qr();let n=Tx(e);if(n)return Fc(n,t,r);if(Ao.includes(e.arrayOperator)){if(t?.map&&t?.model&&r)return _c(e,t,r);throw new Error(`ArrayOperator '${e.arrayOperator}' requires a FieldMap and model to generate a multi-step plan. Pass { map, model } options to toPrisma(). Without them, use prisma.$queryRaw for count-based relation filtering.`)}if(!e.field)throw rs("toPrisma");let{field:o}=e;if(jc(o,t))return kx(e,o,Ue({field:o},t?.map,t?.model),t);let i=Cx(e,t,r);return dt(e.field,i,t)},jc=(e,t)=>{let r=Ue({field:e},t?.map,t?.model);return r==="list"||r==="json"||r==="json-path"},kx=(e,t,r,n)=>{switch(e.arrayOperator){case x.empty:case x.notEmpty:return Sl(t,r,e.arrayOperator===x.empty,false,n);default:throw V("toPrisma",`'${e.arrayOperator}' over the ${r==="list"?"list":"Json array"} '${t}'`,r==="list"?"test a list's membership with 'contains'":void 0)}},Vc=(e,t)=>{if(!t?.map||!t?.model||!e.field)return t&&Jr({...t});let r=Bo(e.field,t.map,t.model);return Jr(r?{...t,model:r}:{...t})},Cx=(e,t,r)=>{let n=Vc(e,t);switch(e.arrayOperator){case x.all:if(!e.condition)throw Ve(e.arrayOperator);return {none:de(Qe(e.condition,no(n)),n,r)};case x.any:if(!e.condition)throw Ve(e.arrayOperator);return {some:de(e.condition,n,r)};case x.none:if(!e.condition)throw Ve(e.arrayOperator);return {none:de(e.condition,n,r)};case x.empty:return {none:{}};case x.notEmpty:return {some:{}};default:throw fe(e.arrayOperator,"array")}};var Ic=(e,t)=>{let r=t?.map,n=Ue({field:e.field},r,t?.model);if(n==="json"||n==="json-path")throw V("toPrisma",`A date rule on the Json value '${e.field}'`,"Prisma compares Json text");let o=te(e.field,r,t?.model);if(o&&!L(o)&&Ke(o)!==P.DateTime)throw V("toPrisma",`A date rule on the ${o.type} field '${e.field}'`,`Prisma compares it as ${o.type}, not as an instant`);let i=W.includes(e.dateOperator)?hl(e,t):[],s=Lx(e,t);if(s===null)return K(i);let a=dt(e.field,s,t),l=Dn.includes(e.dateOperator)?Me(a):a;return K([l,...i])},Lx=(e,t)=>{let r=ro(t),n=Wo,o=m=>e.offset===void 0?m:Ac(m,e.offset,t),i=m=>{if(m==null)return null;if(!ee(m))return ms(m,r.timeZone);let y=$t(m,n);return y&&Kn(y,e.dateOperator,r).toDate()},s=()=>{let m=it(e);if(m==null)return m;let y=e.offset===void 0?void 0:it(e.offset),c=Gt(m,y);if(c)throw c;return m},a=()=>o(i(s())),l=()=>{let m=s();if(m==null)return null;let y=rt(m,e.dateOperator).map(i);if(y[0]===null||y[1]===null)return null;let[c,g]=He(y).map(o);return c&&g?[c,g]:null},d=()=>{let m=s();if(m==null)return null;if(!ee(m))throw tt(e.dateOperator);let y=$t(m,n);if(!y)return null;let[c,g]=Gn(y,r);return [c.toDate(),g.toDate()]},p=m=>{let y=a();return y===null?null:{[m]:y}},f=m=>m?{gte:m[0],lte:m[1]}:null,u=lr(e.dateOperator,"date");if(u)return p(u);switch(e.dateOperator){case N.within:case N.notWithin:return f(d());case N.between:case N.notBetween:return f(l());case N.dayIn:case N.dayNotIn:throw V("toPrisma",`'${e.dateOperator}'`);default:throw fe(e.dateOperator,"date")}};var Rl=(e,t,r)=>{if(typeof e=="boolean")return e?{}:At();Bi(e,"toPrisma");let n=le(e);(n==="field"||n==="date")&&Rs(e.field,t?.map,t?.model);let o=e;switch(n){case "all":return Vu(o,t,r);case "any":return Iu(o,t,r);case "if":return qu(o,t,r);case "array":return Dc(o,t,r);case "aggregate":return Lc(o,t,r);case "date":return Ic(o,t);case "field":return kc(o,t);default:throw xt()}};Fu(Rl);var Bc=async(e,t)=>{let r=e.steps.filter(i=>i.operation==="groupBy"),n=e.steps.find(i=>i.operation==="where");if(!n)throw new Error("executePrismaPlan: result has no where step");let o=[];for(let i of r){let s=Wc(t,i.model),a=qc(i.args,i.refs,o,t),l=await s[i.operation](a);o.push(l.map(d=>d[i.extract]).filter(d=>d!=null));}return qc(n.where,n.refs,o,t)},Wc=(e,t)=>{let r=t.charAt(0).toLowerCase()+t.slice(1),n=e[r];if(!n)throw new Error(`executePrismaPlan: no delegate for model '${t}'. Ensure prismaDelegate has a key '${r}'.`);return n},Mx=(e,t)=>{let r=Wc(e,t.model).fields,n=r&&Object.hasOwn(r,t.field)?r[t.field]:void 0;if(n===void 0)throw new Error(`executePrismaPlan: the '${t.model}' delegate has no field reference '${t.field}' (fields.${t.field}).`);return n},_x=(e,t)=>t.reduce((r,n)=>r!==null&&typeof r=="object"&&Object.hasOwn(r,n)?r[n]:void 0,e),Ol=(e,t,r)=>{if(t.length===0)return r;let[n,...o]=t,i=e,s=Array.isArray(e)?[...e]:{...i};return s[n]=Ol(i[n],o,r),s},qc=(e,t,r,n)=>{let o=e;for(let{path:i}of t??[]){let s=_x(e,i);if(s&&typeof s.__step=="number"){let a=s.__step;if(a>=r.length)throw new Error(`Step ref __step: ${a} out of range (${r.length} steps executed)`);o=Ol(o,i,r[a]);}else if(s&&typeof s.__field=="object"&&s.__field!==null)o=Ol(o,i,Mx(n,s.__field));else throw new Error(`executePrismaPlan: no reference at the recorded location ${i.join(".")}`)}return o};var Dx=e=>e?.map?{...e,map:Pe(e.map,e.mapName,"toPrisma")}:e,Yo=(e,t)=>js(e,t,"toPrisma",Fx),Fx=(e,t)=>{let r={steps:[]},n=Rl(e,Dx(t),r),o=(i,s)=>{let a=Tu(s);return a.length?{...i,refs:a}:i};return {steps:[...r.steps.map(i=>o(i,i.args)),o({operation:"where",where:n},n)]}};var jx=/^-?\d+(\.\d+)?$/,Uc=e=>typeof e=="string"?jx.test(e)?Number(e):e:typeof e=="object"&&e!==null&&typeof e.toNumber=="function"?e.toNumber():e,xl=(e,t)=>e?.kind!=="scalar"||e.type!=="Decimal"?t:Array.isArray(t)?t.map(Uc):Uc(t);var Bs=(e,t,r,n,o)=>{let i=`${r.mapName}\0${r.modelName}`;for(let a of t){if(typeof a=="boolean")continue;let l=e.memo?.compiles.get(a)??new Map;e.memo?.compiles.set(a,l);let d=l.get(i);if(d===void 0){let[p]=Er(a,{target:"toPrisma",map:e.lens,mapName:r.mapName,model:r.modelName}).errors;d=p?p.message:null,l.set(i,d);}if(d!==null)return new T(`${n}: ${d}`,"unsupported_clamp")}if(o)return null;let s=false;for(let a of t)H(a,l=>{("aggregate"in l||Po(l))&&(s=true);});return s?new T(`${n} needs a counting step (executePrismaPlan), which a relation's where in a select can't run`,"unsupported_clamp"):null},Ws=(e,t)=>{try{return t()}catch(r){throw r instanceof T||r instanceof C?r:new T(`${e}: ${r.message}`,"unsupported_clamp")}};var Kc=(e,t)=>e===""?t:t===""?e:`${e}.${t}`,_e=e=>{let t=new Set,r=o=>{o&&t.add(o);},n=(o,i)=>{let s=Ge(o,i);return "outOfBounds"in s?null:Kc(s.scope,s.path)};return H(e,(o,i)=>{if(Be(o))return;for(let l of gr(o))r(M(l)?n(l,i):l);let s=typeof o.field=="string"&&o.field!==""?n(o.field,i):null;if(r(s),!Oe(o))return;let a=s??i[i.length-1];for(let l of Hn(o))r(Kc(a,l));return [...i,a]},[""]),[...t]};var El=(e,t,r,n,o)=>{let i={};for(let[s,a]of Object.entries(n.fields)){if(!kt(t,s))continue;let l=t.enumValuesByField.get(s),d=o(s)?.filter(f=>l===void 0||l.includes(f.value)),p=uo(e,t,r,s,"groupBy")?t.sourceGroupBys.get(s):void 0;i[s]={...a,...l!==void 0&&{values:l},...d!==void 0&&{options:d},...p!==void 0&&{groupBy:p}};}return i},Gc=(e,t,r,n,o)=>{let{mapName:i,modelName:s}=t,a=k(O(e.lens.maps,i),s),l=El(e,r,t,a,m=>{let y=o.get(`${n}|${m}`),c=r.enumValuesByField.get(m);return y??O(a.fields,m)?.options??c?.map(g=>({value:g,label:g}))}),d={};for(let[m,y]of r.sources)kt(r,m)&&(d[m]=y);let p={};for(let[m,y]of r.sourceLabels)kt(r,m)&&uo(e,r,t,m,"label")&&(p[m]=y);let f={};for(let[m,y]of r.sourceGroupBys)kt(r,m)&&uo(e,r,t,m,"groupBy")&&(f[m]=y);let u={};for(let m of r.sourcesFromMapDefaults.keys()){if(!Ds(e,i,s,m))throw Fs(n,i,s,m);Object.hasOwn(d,m)&&(u[m]="mapDefaults");}return {mapName:i,model:s,fields:l,whereClauses:r.whereClauses,sources:d,sourceLabels:p,sourceGroupBys:f,sourceFrom:u}},zc=e=>{let t=new Map;for(let r of e.sourceValues??[])t.set(`${r.path}|${r.field}`,r.options);return t},Hc=(e,t={})=>Xo(D(e),t),Xo=(e,t={})=>{let r=zc(t),n={};for(let{path:o,at:i,effect:s}of Yt(e))n[o]=Gc(e,i,s,o,r);return n},Jc=(e,t,r={})=>$l(D(e),t,r),$l=(e,t,r={})=>{let n={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};if(t!=="")for(let s of Sr(e.lens.maps,n,t)){let a=j(e,s.at.mapName,s.at.modelName,s.at.relPath);if(!s.next||!a.relations.has(s.field))return null;n={...s.next,relPath:[...s.at.relPath,s.field]};}if(!k(O(e.lens.maps,n.mapName),n.modelName))return null;let o=j(e,n.mapName,n.modelName,n.relPath),i=[e.lens.model,...n.relPath].join(".");return Gc(e,n,o,i,zc(r))};var Us=(e,t,r,n,o)=>{let i=e.split("."),{hops:s}=Te(t,{mapName:r,modelName:n,relPath:[]},e),a=s.find((f,u)=>f.isList&&u<i.length-1);if(a)return `${o} cannot traverse to-many relation '${i[s.indexOf(a)]}'`;if(s.length===i.length)return `${o} must end on a scalar column, '${i.at(-1)}' is a relation`;let l=s.at(-1)??{map:r,model:n},d=i[s.length],p=Ae(O(t,l.map),l.model,d);return p?L(p)?`${o} relation '${d}' has no resolvable target`:s.length===i.length-1?null:`${o} segment '${d}' is not a relation`:`${o} segment '${d}' not on model '${l.model}'`},Qc=(e,t,r,n,o,i,s,a)=>{let l=Us(o,e.lens.maps,t,r,i);if(l)throw new T(`${i} '${o}': ${l}`,"invalid_source");let{hops:d}=Te(e.lens.maps,{mapName:t,modelName:r,relPath:n},o),p=d.slice(0,o.split(".").length-1);for(let f of p){let u=f.relPath.join(".");if(s.has(u))continue;s.add(u);let m=j(e,f.map,f.model,f.relPath);for(let y of m.whereClauses)a.push(so(y,f.prefix));}},Vx=(e,t,r,n,o,i)=>{let s=[],a=new Set;for(let l of o)Qc(e,t,r,n,l,"groupBy",a,s);return i?.includes(".")&&Qc(e,t,r,n,i,"label",a,s),s},ei=(e,t)=>{let r=me(e,t);return r==null||typeof r=="object"?void 0:String(r)},Ks=(e,t)=>{let r=[];for(let n of t){let o=ei(e,n);if(o===void 0)return;r.push(o);}return r},vl=(e,t)=>JSON.stringify([e??null,t]),Ix=(e,t,r,n)=>{let o=vl(n,t),i=e.get(o);i===void 0?e.set(o,{value:t,...r!==void 0?{label:r}:{},...n!==void 0?{groups:n}:{}}):r!==void 0&&(i.label===void 0||r<i.label)&&e.set(o,{...i,label:r});},Gs=(e,t,r,n,o)=>{let i=me(t,r),s=n==null?void 0:String(n);for(let a of Array.isArray(i)?i:[i])a==null||typeof a=="object"||Ix(e,String(a),s,o);},zs=e=>[...e.values()].sort((t,r)=>{let n=(t.groups===void 0?0:1)-(r.groups===void 0?0:1);if(n!==0)return n;let o=t.groups??[],i=r.groups??[];for(let s=0;s<Math.max(o.length,i.length);s++){let a=(o[s]??"").localeCompare(i[s]??"","en",{numeric:true});if(a!==0)return a}return (t.label??t.value).localeCompare(r.label??r.value,"en",{numeric:true})||t.value.localeCompare(r.value,"en",{numeric:true})}),qx=(e,t,r,n,o)=>{let{hops:i}=ie(o,t,n),s=o.split("."),a=i.at(-1)?.entry.type??n,l=s[i.length];for(let{endpoints:d}of e.bridges??[]){let[p,f]=d;for(let[u,m]of [[p,f],[f,p]])if(u.fieldMap===r&&u.model===a&&Le(m)===l)return [...s.slice(0,i.length),u.on].join(".")}throw new T(`'${o}' crosses no bridge the lens declares on ${a}`,"not_in_lens")},Hs=(e,t,r,n)=>{let o=Pe(e,t,"toPrisma");return [...new Set(n.map(i=>Rr(i,o,r)?qx(e,o,t,r,i):i))]},Bx=(e,t,r,n)=>{if(t.length===0)return [];let o={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},{hops:i,end:s}=Te(e.lens.maps,o,t.join("."));if(!s)throw new T(`source at '${t.join(".")}': its path doesn't resolve on the field maps`,"not_in_lens");let a=[o,...i.map(p=>({mapName:p.map,modelName:p.model}))],l=t.length;for(;l>0&&!r.has(t.slice(0,l).join("."));)l--;let d=l>0?r.get(t.slice(0,l).join("."))??null:null;for(let p=l;p<t.length;p++){let f=E=>{d=E,r.set(t.slice(0,p+1).join("."),E);},u=a[p],m=j(e,u.mapName,u.modelName,t.slice(0,p)).whereClauses,y=d===null?m:[...m,d];if(y.length===0&&!n){f(null);continue}let c=O(e.lens.maps,u.mapName),g=c&&Ae(c,u.modelName,t[p]);if(!g)throw new T(`source at '${t.join(".")}': '${t[p]}' isn't declared on ${u.modelName}`,"not_in_lens");let w=a[p+1],R=Le({fieldMap:u.mapName,model:u.modelName}),S=g.kind==="bridge"?Ae(O(e.lens.maps,w.mapName),w.modelName,R):void 0,b=g.kind==="bridge"?S&&{field:R,entry:S}:c?vs(c,u.modelName,t[p],g):null;if(!b&&y.length===0){f(null);continue}if(!b)throw new T(`source at '${t.join(".")}': '${t[p]}' on ${u.modelName} declares no inverse, so the clamps above can't be carried down to it`,"unsupported_clamp");let v=U(y);try{let E={field:b.field,operator:"exists"};f(b.entry.isList?{field:b.field,arrayOperator:"any",condition:v}:y.length?U([E,so(v,b.field)]):E);}catch(E){throw E instanceof T?new T(`source at '${t.join(".")}': the clamps above can't be carried down to it \u2014 ${E.message}`,E.code):E}}return d===null?[]:[d]},Zc=e=>Ar(D(e)),Ar=(e,t=Xo(e))=>{let r=new Map,n=o=>{let i=r.get(o)??new Map;return r.set(o,i),i};return Object.entries(t).flatMap(([o,i])=>Object.keys(i.sources).map(s=>{let a=O(i.sourceLabels,s),l=O(i.sourceGroupBys,s),d=Object.hasOwn(i.sourceFrom,s),p={mapName:i.mapName,modelName:i.model,relPath:o.split(".").slice(1)},f=j(e,p.mapName,p.modelName,p.relPath),u=(f.sourceWheres.get(s)??[]).map(A=>en(A,e,p)),m=Vx(e,p.mapName,p.modelName,p.relPath,l??[],a),y=O(i.fields,s)?.values,c=d?f.sourcesFromMapDefaults.get(s):void 0,g=c===void 0?void 0:e.chain[c],R=[...Bx(g===void 0?e:{...e,skipClampsOf:g},p.relPath,n(g),g===void 0&&!d),...u,...m,...y?[{field:s,operator:"in",value:[...y]}]:[]],S=U([...i.whereClauses,...R]),b=U([...i.whereClauses,...u,...m,...y?[{field:s,operator:"in",value:[...y]}]:[]]),v=e.lens.bridges?.length?Pe(e.lens,p.mapName,"toPrisma"):void 0,E=v?[..._e(S),...a===void 0?[]:[a],...l??[]].find(A=>Rr(A,v,p.modelName)):void 0,q=E!==void 0&&v?U(Fa(S).filter(A=>Nt(A,v,p.modelName))):void 0,ue=Bs(e,[...i.whereClauses,...R],p,`source '${s}' at '${o}'`,true);if(ue)throw ue;return {path:o,visit:i,field:s,...d&&{from:"mapDefaults"},...a!==void 0&&{label:a},...l!==void 0&&{groupBy:l},where:S,rowWhere:b,...E!==void 0&&{bridged:E},...q!==void 0&&{recheck:q}}}))};var Pl=(e,t)=>{for(let r of t){let n=e;for(let o of r.split("."))n=Qt(n,o,()=>({}));}return e},Js=(e,t)=>{for(let[r,n]of Object.entries(t))Js(Qt(e,r,()=>({})),n);return e},Tl=e=>e.whereClauses.flatMap(_e),Yc=(e,t)=>{let r=new Map;for(let n of t){if(n.from)continue;let o=n.path.split(".").slice(1).join("."),i=[n.field,...n.label===void 0?[]:[n.label],...n.groupBy??[],..._e(n.rowWhere)];r.set(o,[...r.get(o)??[],...n.bridged===void 0?i:Hs(e.lens,n.visit.mapName,n.visit.model,i)]);}return r},Xc=(e,t)=>e.get(t.relPath.join("."))??[],Wx=(e,t,r)=>Pl(Js({},r??{}),Tl(j(e,t.mapName,t.modelName,t.relPath))),em=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]}),kl=(e,t,r)=>({...r,relPath:[...e.relPath,t]}),Ux=(e,t,r,n)=>{if(!r.whereClauses.length)return;let o=U(r.whereClauses),i=Bs(e,r.whereClauses,t,`toLensSelect: the clamp on '${t.relPath.join(".")}'`,false);if(i)throw i;if(e.inspect)return;let s=Ws(`toLensSelect: the clamp on '${t.relPath.join(".")}'`,()=>Yo(o,{...n,map:e.lens,mapName:t.mapName,model:t.modelName})),{where:a}=s.steps[0];return Object.keys(a).length?a:void 0},Kx=(e,t,r,n)=>{let o=k(e,n.type)?.fields??{},i=a=>{let l=a===void 0?void 0:O(o,a);return l&&!L(l)?a:void 0},s=e?vs(e,t,r,n):null;return i(n.toFields?.[0])??i(s?.entry.fromFields?.[0])??i("id")},tm=(e,t,r,n,o,i)=>{let s=k(O(e.lens.maps,t.mapName),t.modelName)?.fields??{},a=j(e,t.mapName,t.modelName,t.relPath),l=r==="paths"?n:Pl(Js({},n),[...Tl(a),...Xc(i,t)]),d={};for(let[p,f]of Object.entries(s)){let u=r!=="paths"&&kt(a,p),m=O(l,p);if(!u&&m===void 0||f.kind==="bridge")continue;if(f.kind!=="object"){d[p]=true;continue}let y=u?"declared":"paths";if(y==="paths"&&m===void 0)continue;let c=kl(t,p,{mapName:t.mapName,modelName:f.type}),g=tm(e,c,y,m??{},o,i),w=f.isList&&y!=="paths"&&m===void 0?Ux(e,c,j(e,c.mapName,c.modelName,c.relPath),o):void 0,R=Object.keys(g).length?void 0:Kx(O(e.lens.maps,t.mapName),t.modelName,p,f),S=R===void 0?g:{[R]:true};Object.keys(S).length&&(d[p]={select:S,...w&&{where:w}});}return d},rm=(e,t={})=>Cl(D(e),t),Cl=(e,t={},r=Ar(e))=>{let n=tm(e,em(e),"declared",{},t,Yc(e,r));if(!Object.values(n).some(o=>o===true)){let o=O(k(O(e.lens.maps,e.lens.mapName),e.lens.model)?.fields,"id");o&&!L(o)&&(n.id=true);}return {select:n}},Nl=(e,t)=>e==null?e:Array.isArray(e)?e.flatMap(r=>{let n=typeof r=="object"&&r!==null?t(r):null;return n===null?[]:[n]}):typeof e=="object"?t(e):null,Al=(e,t,r,n)=>{let o={},i=k(O(e.lens.maps,t.mapName),t.modelName);for(let[s,a]of Object.entries(n)){if(!Object.hasOwn(r,s))continue;let l=O(i?.fields,s),d=l?ot(l,t.mapName):null;o[s]=d?Nl(r[s],p=>Al(e,kl(t,s,d),p,a)):xl(l,r[s]);}return o},nm=(e,t,r,n,o,i,s)=>{let a=j(e,t.mapName,t.modelName,t.relPath);if(!a.whereClauses.every(f=>ye(f,r,i)===true))return null;let l=k(O(e.lens.maps,t.mapName),t.modelName)?.fields??{},d=o?Pl(Js({},n),[...Tl(a),...Xc(s,t)]):{},p={};for(let[f,u]of Object.entries(l)){if(!Object.hasOwn(r,f))continue;let m=O(d,f),y=ot(u,t.mapName);if(!y){(kt(a,f)||m!==void 0)&&(p[f]=xl(u,r[f]));continue}let c=kl(t,f,y);if(kt(a,f)){let g=!Array.isArray(r[f])||m!==void 0;p[f]=Nl(r[f],w=>nm(e,c,w,m??{},o,i,s)??(o&&g?Al(e,c,w,Wx(e,c,m)):null));}else m!==void 0&&(p[f]=Nl(r[f],g=>Al(e,c,g,m)));}return p},om=(e,t,{keepClampColumns:r=false,...n}={})=>{let o=D(e),i=em(o),s=r?Yc(o,Ar(o)):new Map;return t.flatMap(a=>{let l=nm(o,i,a,{},r,n,s);return l===null?[]:[l]})};var Gx="materializeSources needs fetched or keepClampColumns rows, not viewer rows",Ll=(e,t,r)=>new C(`${e}: a row at '${t}' ${r}${r.includes(":")?" \u2014 rows across a bridge hold the far side inline under its bridge field":""}`),ti=(e,t,r,n,o,i=Gx)=>{for(let s of o){let a=[r];for(let{index:l,field:d,entry:p,next:f}of Sr(e.lens.maps,t,s)){if(!p)break;let u=s.split(".").slice(0,l+1).join("."),m=[];for(let y of a){if(y===null||typeof y!="object")continue;if(!Object.hasOwn(y,d))throw Ll(i,n,`lacks '${u}', which a read needs`);let c=y[d];if(f&&c==null&&p.fromFields?.some(g=>{let w=y[g];return w!=null}))throw Ll(i,n,`'${u}' is null while its key is set \u2014 a projection hid the row`);if(!(!f||c===null||c===void 0)){if(Array.isArray(c)!==(p.isList===true))throw Ll(i,n,`'${u}' holds ${Array.isArray(c)?"a list where it names one row":"one row where it names a list"}`);m.push(...Array.isArray(c)?c:[c]);}}if(!f)break;a=m;}}},Ml=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};return [r,...Te(e.lens.maps,r,t.split(".").slice(1).join(".")).hops.map(n=>({mapName:n.map,modelName:n.model,relPath:n.relPath}))]},zx=(e,t,r,n)=>{let o=r.split(".").slice(1),i=Ml(e,r),s=(l,d)=>{let p=i[l],f=j(e,p.mapName,p.modelName,p.relPath).whereClauses,u=U(f),m=f.flatMap(_e),y=[e.lens.model,...o.slice(0,l)].join(".");return d.filter(c=>(ti(e,p,c,y,m),ye(u,c,n)===true))},a=s(0,t);for(let[l,d]of o.entries()){let p=[],f=[e.lens.model,...o.slice(0,l)].join(".");for(let u of a){ti(e,i[l],u,f,[d]);let m=me(u,d);Array.isArray(m)?p.push(...m):m!=null&&p.push(m);}a=s(l+1,p);}return {rows:a,visit:i[i.length-1]}},im=(e,t,r)=>{let n=D(e);return Ar(n).map(({path:o,visit:i,field:s,from:a,label:l,groupBy:d,rowWhere:p})=>{if(a)throw new C(`materializeSources: '${o}.${s}' offers its model's own source, which a fetched collection can't hold \u2014 query it with toSourceQueries and materializeSourceQuery.`);let f=[s,..._e(p),...l===void 0?[]:[l],...d??[]],u=new Map,m=zx(n,t,o,r);for(let y of m.rows)ti(n,m.visit,y,o,f),ye(p,y,r)===true&&Gs(u,y,s,l===void 0?void 0:ei(y,l),d===void 0?void 0:Ks(y,d));return {path:o,mapName:i.mapName,model:i.model,field:s,options:zs(u)}})};var Qs={value:"value",query:"query"},sm=(e,t,r={})=>{let{rowShape:n="prisma",lens:o,order:i=Qs.value,...s}=r,a=n==="sql",{recheck:l}=e,d=y=>false,p=y=>true;if(l!==void 0){if(o===void 0)throw new C(`materializeSourceQuery: '${e.path}.${e.field}' reads across a bridge \u2014 its rows are candidates; pass { lens } with rows holding the far side`);let y=D(o),c=Ml(y,e.path).at(-1);if(!c||c.mapName!==e.mapName||c.modelName!==e.model)throw new C(`materializeSourceQuery: the lens doesn't reach ${e.mapName}:${e.model} at '${e.path}' \u2014 pass the lens the query was compiled from`);let g=Pe(y.lens,e.mapName,"toPrisma");d=S=>g!==void 0&&Rr(S,g,e.model);let w=[..._e(l),...e.label!==void 0&&d(e.label)?[e.label]:[],...(e.groupBy??[]).filter(d)],R="materializeSourceQuery needs candidate rows holding the far side of each bridge the source reads";p=S=>(ti(y,c,S,e.path,w,R),ye(l,S,s)===true);}let f=y=>e.label===void 0?void 0:a&&e.label.includes(".")&&!d(e.label)?y.__label:ei(y,e.label),u=e.groupBy?.map((y,c)=>a&&!d(y)?`__group_${c}`:y),m=new Map;for(let y of t)p(y)&&Gs(m,y,e.field,f(y),u===void 0?void 0:Ks(y,u));return {path:e.path,mapName:e.mapName,model:e.model,field:e.field,options:i===Qs.query?[...m.values()]:zs(m)}};var Hx=(e,t)=>`${e}::${t}`,Jx=(e,t,r)=>{let n=e.get(t);if(!n){e.set(t,r.values?{...r,values:[...r.values]}:r);return}let o=n;if(r.values&&n.values){let i=new Set([...n.values,...r.values]);o={...o,values:[...i]};}else !r.values&&n.values&&(o={...o,values:void 0});r.groupBy!==void 0&&o.groupBy===void 0&&(o={...o,groupBy:r.groupBy}),o!==n&&e.set(t,o);},am=(e,t={})=>_l(D(e),t),_l=(e,t={})=>{let{lens:r}=e,n=new Map;for(let l of t.sourceValues??[]){let d=`${l.mapName}::${l.model}::${l.field}`,p=n.get(d)??new Map;for(let f of l.options)p.set(vl(f.groups,f.value),f);n.set(d,p);}let o=new Map;for(let{at:l,effect:d}of Yt(e)){let{mapName:p,modelName:f}=l,u=k(O(r.maps,p),f);if(!u)continue;let m=Hx(p,f),y=o.get(m);y||(y={mapName:p,modelName:f,fields:new Map},o.set(m,y));let c=El(e,d,l,u,g=>{let w=n.get(`${p}::${f}::${g}`);return w&&[...w.values()]});for(let[g,w]of Object.entries(c)){let R=w.groupBy,S=y.fields.get(g)?.groupBy;if(R!==void 0&&S!==void 0&&JSON.stringify(S)!==JSON.stringify(R))throw new T(`projectLens: '${f}.${g}' is grouped by different axes on different paths ([${S}] vs [${R}]) \u2014 one surface field cannot carry two partition namespaces`,"invalid_source");Jx(y.fields,g,w);}}let i={};for(let{mapName:l,modelName:d,fields:p}of o.values()){let f=O(i,l);f||(f={models:{}},i[l]=f);let u={},m=new Map;for(let[y,c]of p)if(u[y]=c.options===void 0&&c.values?{...c,options:c.values.map(g=>({value:g,label:g}))}:c,c.kind==="enum"&&c.values){let g=m.get(c.type)??new Set;for(let w of c.values)g.add(w);m.set(c.type,g);}f.models[d]={...k(O(r.maps,l),d),fields:u};for(let[y,c]of m)f.enums??={},f.enums[y]=[...c];}let s=r.bridges?.filter(l=>{let[d,p]=l.endpoints,f=Ae(O(i,d.fieldMap),d.model,Le(p)),u=Ae(O(i,p.fieldMap),p.model,Le(d));return f!==void 0||u!==void 0}),a={maps:i};return s&&s.length>0&&(a.bridges=s),{...a,mapName:r.mapName,model:r.model}};var lm=(e,t,r,n,o)=>{if(e===void 0)return;let i=io(e),s=n==="root.where"?null:i.bare;if(s!==null){o.push({path:n,code:"invalid_value_source",message:il(s).message});return}let{escaping:a}=i;if(a!==null){o.push({path:n,code:"scope_out_of_bounds",message:sl(a).message});return}let l=new Set,d={...t,clamp:t.chain.length===0};for(let{mapName:p,modelName:f,relPath:u}of r)for(let m of Ko(e,d,p,f,u)){let y=`'${m.path}' ${m.message}`;l.has(y)||(l.add(y),o.push({path:n,code:m.code,message:y}));}},Qx=(e,t,r,n,o,i)=>{let s={...r,chain:[...r.chain,t]},a=new Set;for(let l of n){let d=j(s,l.mapName,l.modelName,l.relPath);for(let[p,f]of Object.entries(e.sources??{})){let u=vr(f);for(let m of ["label","groupBy"]){if(u[m]===void 0||a.has(`${p}|${m}`))continue;let y=m==="label"?u.label:Ho(u.groupBy),c=m==="label"?d.sourceLabels.get(p):d.sourceGroupBys.get(p);if(JSON.stringify(y)!==JSON.stringify(c))continue;let w=(typeof c=="string"?[c]:c??[]).map(R=>Qo(s,l,R)).find(R=>R!==null);if(w){a.add(`${p}|${m}`),i.push({path:`${o}.sources.${p}`,code:"invalid_source",message:`${m} '${String(u[m])}' crosses '${w}', a relation the lens does not show there (not turned on, or omitted)`});continue}uo(s,d,l,p,m)||(a.add(`${p}|${m}`),i.push({path:`${o}.sources.${p}`,code:"invalid_source",message:`${m} '${String(u[m])}' reads a column hidden by another layer`}));}}}},Zx=(e,t,r,n)=>{for(let o of r){if(!t&&o.picks&&!o.picks.includes(e))return "not in ancestor's picks";if(o.omits?.includes(e))return "was omitted by ancestor"}return !t&&n?.picks&&!n.picks.includes(e)?"not visible from defaults.picks":n?.omits?.includes(e)?"already excluded by defaults":null},Yx=(e,t,r,n,o,i,s,a,l,d,p,f,u=false)=>{let m=e.omits?.some(c=>{let g=O(i,c);return g===void 0||!L(g)});e.picks&&m&&d.push({path:`${l}`,code:"conflicting_selection",message:"cannot specify both picks and omits of a column"});for(let c of ["picks","omits"])for(let g of e[c]??[]){let w=O(i,g);if(!w){d.push({path:`${l}.${c}`,code:"not_in_lens",message:`field '${g}' not on model`});continue}let R=L(w);if(R&&c==="picks"){d.push({path:`${l}.picks`,code:"wrong_kind",message:`'${g}' is a relation: picks names columns; turn a relation on with \`relations\``});continue}let S=Zx(g,R,t,r);S&&d.push({path:`${l}.${c}`,code:"not_visible",message:`'${g}' ${S}`});}let y=(c,g,w)=>{let R=O(i,g);if(!R){d.push({path:`${l}.${c}`,code:"not_in_lens",message:`field '${g}' not on model`});return}if(R.kind!=="enum"){d.push({path:`${l}.${c}`,code:"wrong_kind",message:`field '${g}' is not an enum field`});return}let S=Gr(R,a);for(let b of w)S&&!S.includes(b)&&d.push({path:`${l}.${c}.${g}`,code:"value_not_allowed",message:`'${b}' is not a known value of enum '${R.type}'`});};for(let[c,g]of Object.entries(e.enumPicks??{}))y("enumPicks",c,g);for(let[c,g]of Object.entries(e.enumOmits??{}))y("enumOmits",c,g);lm(e.where,p,f,`${l}.where`,d);for(let[c,g]of Object.entries(e.sources??{})){let w=O(i,c);if(!w){d.push({path:`${l}.sources`,code:"not_in_lens",message:`field '${c}' not on model`});continue}if(L(w)){d.push({path:`${l}.sources.${c}`,code:"wrong_kind",message:`'${c}' is a relation: a source offers a column's values`});continue}let R;try{R=vr(g);}catch(E){if(!(E instanceof T))throw E;d.push({path:`${l}.sources.${c}`,code:E.code,message:E.message});continue}let S=R.from;if(S!==void 0){let E=S!=="mapDefaults"?`from takes 'mapDefaults', not '${String(S)}'`:u?"a mapDefaults source is what a path source's from: 'mapDefaults' points at; it can't point itself":R.label!==void 0||R.groupBy!==void 0?"a from: 'mapDefaults' source takes the model source's label and groupBy":null;E&&d.push({path:`${l}.sources.${c}`,code:"invalid_source",message:E});}let b=R.label?.includes(".")?R.label:void 0;if(R.label!==void 0)if(b){let E=Us(b,n,o,s,"label");E&&d.push({path:`${l}.sources.${c}`,code:"invalid_source",message:`${E}`});}else {let E=O(i,R.label);E?L(E)&&d.push({path:`${l}.sources.${c}`,code:"wrong_kind",message:`label '${R.label}' is a relation, not a column`}):d.push({path:`${l}.sources.${c}`,code:"not_in_lens",message:`label column '${R.label}' not on model`});}let v=Ho(R.groupBy);if(v!==void 0||b!==void 0){let E=/^__(group(_\d+)?|label)$/;(E.test(c)||R.label!==void 0&&E.test(R.label))&&d.push({path:`${l}.sources.${c}`,code:"invalid_source",message:"'__group*' / '__label' names are reserved on grouped or path-labeled sources (sql column aliases)"});}if(v!==void 0){for(let q of v){let ue=Us(q,n,o,s,"groupBy");ue&&d.push({path:`${l}.sources.${c}`,code:"invalid_source",message:`${ue}`});}let E=JSON.stringify(v);for(let q of t){let ue=O(q.sources,c);if(ue===void 0)continue;let A=Ho(vr(ue).groupBy);A!==void 0&&JSON.stringify(A)!==E&&d.push({path:`${l}.sources.${c}`,code:"not_visible",message:`groupBy [${v}] conflicts with an ancestor layer's groupBy [${A}]`});}}lm(R.where,p,f,`${l}.sources.${c}`,d);}},Xx=(e,t,r,n,o)=>{for(let[i,s]of Object.entries(t)){let a=O(r,i);if(!a){o.push({path:`mapDefaults.${e}.enums.${i}`,code:"not_in_lens",message:"enum not in registry"});continue}let l=null,d=new Set;for(let f of n){let u=f[i];if(u&&(u.picks&&(l=_s(l,u.picks)),u.omits))for(let m of u.omits)d.add(m);}let p=f=>!(d.has(f)||l&&!l.has(f));for(let f of s.picks??[])a.includes(f)?p(f)||o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"not_visible",message:`'${f}' not visible from ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"value_not_allowed",message:`'${f}' not a known value`});for(let f of s.omits??[])a.includes(f)?p(f)||o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"not_visible",message:`'${f}' already excluded by ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"value_not_allowed",message:`'${f}' not a known value`});}},eE=(e,t,r,n,o,i,s)=>{let a=j(t,r.mapName,r.modelName,r.relPath);for(let l of ["enumPicks","enumOmits"])for(let[d,p]of Object.entries(e[l]??{})){let f=O(n,d);if(f?.kind!=="enum")continue;let u=Gr(f,o)??[],m=Ls(a,d)??u;for(let y of p)u.includes(y)&&!m.includes(y)&&s.push({path:`${i}.${l}.${d}`,code:"not_visible",message:`'${y}' is not visible (not allowed by the inherited enum narrowing)`});}},pm=(e,t,r,n)=>e.map(o=>({mapName:n,modelName:r,relPath:[...o.relPath,t]})),Dl=(e,t,r,n,o,i,s,a,l,d,p)=>{let f=O(o,i),u=k(f,s);if(!u)return;let m=n.length===0,y={...d,chain:[...d.chain,r],unvetted:true},c=p.isDefault?void 0:O(O(r.mapDefaults,i)?.models,s),w=[...n.map(b=>O(O(b.mapDefaults,i)?.models,s)).filter(b=>b!==void 0),...t],R={mapName:i,modelName:s,relPath:ol};Yx(e,w,c,o,i,u.fields,s,f?.enums,a,l,d,m?p.isDefault?[R,...p.parent]:p.parent:p.composed,p.isDefault),eE(e,p.isDefault?d:{...d,chain:[...d.chain,{parent:r.parent,mapDefaults:r.mapDefaults}],unvetted:true},p.isDefault?R:p.parent[0]??R,u.fields,f?.enums,a,l),Qx(e,r,d,p.composed,a,l);let S={...d,chain:[...d.chain,r]};if(!p.isDefault)for(let[b,v]of Object.entries(e.sources??{}))!Jo(v)||v.from!=="mapDefaults"||Ds(S,i,s,b)||l.push({path:`${a}.sources.${b}`,code:"invalid_source",message:Fs([pt(r).model,...p.parent[0]?.relPath??[]].join("."),i,s,b).message});for(let[b,v]of Object.entries(e.relations??{})){let E=O(u.fields,b);if(!E){l.push({path:`${a}.relations`,code:"not_in_lens",message:`'${b}' not on model`});continue}if(!L(E)){l.push({path:`${a}.relations`,code:"wrong_kind",message:`'${b}' is not a relation (kind=${E.kind})`});continue}let q=B=>j(d,B.mapName,B.modelName,B.relPath).relations.has(b),ue=B=>j(y,B.mapName,B.modelName,B.relPath).relations.has(b);if(!m&&!(p.isDefault?p.parent.some(q):p.parent.every(q))){l.push({path:`${a}.relations`,code:"not_visible",message:`'${b}' is not shown by the parent${p.isDefault?` wherever ${s} is visited`:""}: only the first narrowing over the base lens turns a relation on`});continue}let A=ot(E,i);if(!A)continue;if(!k(O(o,A.mapName),A.modelName)){l.push({path:`${a}.relations.${b}`,code:"not_in_lens",message:"target model not found in lens"});continue}let I=t.map(B=>O(B.relations,b)).filter(B=>B!==void 0);Dl(v,I,r,n,o,A.mapName,A.modelName,`${a}.relations.${b}`,l,d,{parent:pm(p.isDefault?p.parent.filter(q):p.parent,b,A.modelName,A.mapName),composed:pm(p.composed.filter(ue),b,A.modelName,A.mapName),isDefault:p.isDefault});}},Fl=e=>{let t=[];try{tE(e,t);}catch(r){if(!(r instanceof T))throw r;t.some(n=>n.code===r.code)||t.push({path:"",code:r.code,message:r.message});}return Ye(t)},tE=(e,t)=>{let r=pt(e),n=Pt(e.parent),o=D(e.parent),i=Yt(o),s=[],a=u=>{try{u();}catch(m){if(!(m instanceof T))throw m;s.push(m);}},l=null,d=()=>(l??=Yt({...o,chain:[...o.chain,e],unvetted:true}),l);for(let[u,m]of Object.entries(e.mapDefaults??{})){let y=O(r.maps,u);if(!y){t.push({path:`mapDefaults.${u}`,code:"not_in_lens",message:"not in lens"});continue}let c=n.map(g=>O(g.mapDefaults,u)?.enums).filter(g=>g!==void 0);for(let[g,w]of Object.entries(m.models??{})){if(!k(y,g)){t.push({path:`mapDefaults.${u}.models.${g}`,code:"not_in_lens",message:"not in fieldMap"});continue}let S=n.map(E=>O(O(E.mapDefaults,u)?.models,g)).filter(E=>E!==void 0),b=E=>E.map(({at:q})=>q).filter(q=>q.mapName===u&&q.modelName===g),v=[];a(()=>{v=b(d());}),a(()=>Dl(w,S,e,n,r.maps,u,g,`mapDefaults.${u}.models.${g}`,t,o,{parent:b(i),composed:v,isDefault:!0}));}m.enums&&Xx(u,m.enums,y.enums,c,t);}if(e.root){let u=r.mapName,m=r.model,y=O(r.maps,u);if(!y)t.push({path:"root",code:"not_in_lens",message:`lens map '${u}' not in lens`});else if(!k(y,m))t.push({path:"root",code:"not_in_lens",message:`lens model '${m}' not in fieldMap`});else {let c=n.map(w=>w.root).filter(w=>w!==void 0),g={mapName:u,modelName:m,relPath:[]};a(()=>Dl(e.root,c,e,n,r.maps,u,m,"root",t,o,{parent:[g],composed:[g],isDefault:!1}));}}for(let u of wc(e))t.push({path:"bindings",code:"invalid_binding",message:u});let p={...o,chain:[...o.chain,e],inspect:true},f;a(()=>{f=Ar(p,Xo(p));}),a(()=>_l(p)),a(()=>Cl(p,{},f)),a(()=>{let u=new Map;for(let{at:m}of d()){u.set(m.relPath.join("."),m),a(()=>$l(p,m.relPath.join(".")));let y=m.relPath.at(-1),c=u.get(m.relPath.slice(0,-1).join("."));if(y===void 0||!c)continue;let w=Ae(O(r.maps,c.mapName),c.modelName,y)?.isList?{field:y,arrayOperator:"any",condition:!0}:{field:y,operator:"exists"};a(()=>en(w,p,c));}});for(let u of s)t.some(m=>u.message.includes(m.message))||t.push({path:"",code:u.code,message:u.message});},Zs=e=>Xr(Fl(e),"validateNarrowing");function dm(e,{by:t="path",...r}={}){return t==="model"?am(e,r):Hc(e,r)}var fm=(e,t,r,n={})=>{let o=D(e),{resolution:i}=tn(o,Tt(o),r);if(i.outcome!=="resolved")return {ok:false,reason:i.outcome};let{hops:s,terminal:a,jsonSubPath:l}=i;if(L(a.entry))return {ok:false,reason:"relation"};if(s.some(f=>f!==a&&f.entry.isList))return {ok:false,reason:"list"};let d=(f,u)=>u!==null&&typeof u=="object"&&j(o,f.mapName,f.model,f.relPath).whereClauses.every(m=>ye(m,u,n)===true),p=d(s[0],t)?t:null;for(let[f,u]of s.entries()){if(p===null||typeof p!="object")return {ok:true,value:null};let m=O(p,u.field);if(u===a)return {ok:true,value:l.length?me(m,l.join(".")):m};p=d(s[f+1],m)?m:null;}return {ok:true,value:null}};var rE=e=>"maps"in e,um=(e,t)=>{let r=i=>{let s=O(t,i);if(!s)throw new Error(`composeLens: no stored lens '${i}'`);return s},n=[...r(e).parents,e];if(new Set(n).size!==n.length)throw new Error(`composeLens: '${e}' lists a layer twice in its parents`);let o=null;for(let[i,s]of n.entries()){let a=r(s);if(Object.hasOwn(a,"parent"))throw new Error(`composeLens: '${s}' carries a parent; a layer composes only through \`parents\``);let{id:l,parents:d,...p}=a;if(d.join("\0")!==n.slice(0,i).join("\0"))throw new Error(`composeLens: '${s}' composes with [${d.join(", ")}], not [${n.slice(0,i).join(", ")}] as '${e}' lists`);if(rE(a)!==(i===0))throw new Error(i===0?`composeLens: '${s}' is not a base lens, so it can't head '${e}''s parents`:`composeLens: '${s}' is a base lens, so it can only head a chain`);if(o===null){o=p;continue}let u={parent:o,...p};Zs(u),o=u;}return o},cm=(e,t)=>{let r=lt(e)?[]:Pt(e);if(t.length!==r.length+1)throw new Error(`storeLens: the lens has ${r.length+1} layers, base included, but ${t.length} ids`);return [{...pt(e),id:t[0],parents:[]},...r.map(({parent:n,...o},i)=>({...o,id:t[i+1],parents:t.slice(0,i+1)}))]};var mm=e=>e instanceof Date?e.toISOString():Array.isArray(e)&&e.some(t=>t instanceof Date)?e.map(mm):e,F=(e,t)=>(e.params.push(mm(t)),`$${++e.paramIndex}`);var Xt=(e,t,{jsonb:r=false}={})=>{let n=()=>({sql:cl(e,void 0,r),shape:e.includes(".")?"json-path":"unknown"});if(!t.map||!t.currentModel||!t.currentAlias)return n();let o=ie(e,t.map,t.currentModel);if(o.kind==="past-scalar")throw Wn(e,o.column);if(o.kind==="bridge")throw new Error(`'${e}' crosses a bridge to another source; toSql() has no column for it`);if(o.kind==="fallback"||o.entry.kind==="object"&&o.entry.isList)return n();let i=o.hops.find(p=>p.entry.isList);if(i)throw Bn(e,i);let s=t.currentAlias;for(let p of o.hops){let f=gm(t,s,p);if(!f)return n();s=f;}let a=zr(o);if(o.kind==="direct"&&o.entry.kind==="object"){let p={field:o.column,entry:o.entry,from:o.model},f=xr(t.map,o.model,o.entry),u=gm(t,s,p);return !f||!u?n():{sql:`${se(u)}.${se(f[0].there)}`,shape:a}}let l=o.kind==="json-path"?[o.column,...o.jsonPath]:[o.column],d=cl(l.join("."),s,r);return {sql:a==="json"&&!r?`NULLIF(${d}, 'null'::jsonb)`:d,shape:a}},Lt=(e,t,r)=>Xt(e,t,r).sql,gm=(e,t,r)=>{let n=`${t}.${r.field}`,o=e.joinRegistry?.get(n);if(o)return o;if(!e.joinCounter||!e.map)return null;let i=`t${e.joinCounter.n+1}`,s=nE(e.map,r.from,t,r.entry,i);return s?(e.joinCounter.n+=1,e.joins?.push(s),e.joinRegistry?.set(n,i),i):null},nE=(e,t,r,n,o)=>{let i=n.type,s=k(e,i)?.dbName??i,a=xr(e,t,n);if(!a)return null;let l=a.map(({here:d,there:p})=>`${se(o)}.${se(p)} = ${se(r)}.${se(d)}`).join(" AND ");return `LEFT JOIN ${se(s)} AS ${se(o)} ON ${l}`};var er={type:"value",value:null},Mt=e=>e.type==="value"&&(e.value===null||e.value===void 0),oE=(e,t)=>{let r=M(e)??{depth:1,path:e};if(r.depth>1)throw new Error(xo(e,"toSql"));let n=Xt(r.path,t);if(n.shape==="relation")throw new Error(`'${e}' is a relation; a value ref reads a column`);return {type:"column",...n}},$e=(e,t)=>_o(e,{value:r=>({type:"value",value:r}),path:r=>oE(r,t),bind:(r,n)=>({type:"value",value:ps(r,n,"toSql")})}),nn=e=>t=>{let r=$e(t,e);if(r.type==="column")throw new Error(`'${t.path}' is a row ref`);return r.value},ft=e=>zt(e.dateConfig??{},nn(e));var iE={lt:"<",lte:"<=",gt:">",gte:">=",equals:"="},co=(e,t)=>{let r=lr(e,t);return r?{symbol:iE[r],negated:W.includes(e)}:void 0},ym=(e,t)=>e.type==="column"?e.sql:F(t,e.value),De=(e,t)=>`(${t} OR ${e} IS NULL)`,_t=(e,t,r=true)=>t&&r?`${e} IS NULL`:"FALSE",Ys=(e,t,r,n,o)=>{if(Mt(r))return _t(e,n);let i=`${e} ${t} ${ym(r,o)}`;return n?De(e,i):i},ri=(e,t,r,n,o=true)=>{if(!t||t.some(Mt))return _t(e,r,o);let[i,s]=t.map(f=>ym(f,n)),a=t.some(f=>f.type==="column"),l=a?"SYMMETRIC ":"";if(!r)return `${e} BETWEEN ${l}${i} AND ${s}`;let d=`${e} NOT BETWEEN ${l}${i} AND ${s}`,p=a?`(${d} AND ${i} IS NOT NULL AND ${s} IS NOT NULL)`:d;return o?De(e,p):p};var Sm=()=>{let e=Xe.get("sql.dialect");if(!Sf(e))throw new C(`toWhereSql: sql.dialect '${String(e)}' is not a SQL dialect \u2014 ${Object.values(An).join(", ")} are`);return e},Z=e=>new Error(`toWhereSql: ${e} has no SQL form here \u2014 it writes ${Aa.join(", ")}, all and any, and ${ka.join(", ")} over a to-many relation.`),bm=(e,t)=>jl(e,t,""),hm=(e,t,r,n)=>{let o=Object.hasOwn(e,n)?e[n]:void 0;if(typeof o!="string"||o==="")throw new C(`toWhereSql: no ${r} for '${n}' in \`${t}\``);return o},jl=(e,t,r,n={clamps:()=>[]})=>{Sm();let{columns:o,tables:i={},map:s,mapName:a,model:l}=t??{};if(typeof o!="object"||o===null)throw new C("toWhereSql: `columns` maps each field path to its SQL");if(typeof i!="object"||i===null)throw new C("toWhereSql: `tables` maps each to-many relation path to its table");if(!s||!l)throw new C("toWhereSql: `map` and `model` are required \u2014 a literal is typed by its column, and a date, Json or list value is refused by it");let d=Pe(s,a,"toWhereSql");if(!k(d,l))throw new C(`toWhereSql: the map has no model '${l}'`);return mo(e,{map:d,model:l,column:p=>hm(o,"columns","column",`${r}${p}`),table:p=>hm(i,"tables","table",`${r}${p}`),clamps:"clamps"in n?n.clamps:()=>[],joined:"joined"in n?n.joined:null,joinedRow:null})},mo=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";let r=e;switch(le(r)){case "all":{let n=r.all;return n.length?`(${n.map(o=>mo(o,t)).join(" AND ")})`:"TRUE"}case "any":{let n=r.any;return n.length?`(${n.map(o=>mo(o,t)).join(" OR ")})`:"FALSE"}case "field":return aE(e,t);case "if":throw Z("if / then / else");case "array":return sE(e,t);case "aggregate":throw Z("aggregate");case "date":throw Z(`dateOperator '${String(r.dateOperator)}'`);default:throw Z("a condition that is not exactly one node kind")}},sE=(e,t)=>{let{arrayOperator:r,field:n}=e;if(!ka.includes(r))throw Z(`arrayOperator '${r}'`);if(Ne(e))throw Z(`a window (filter / orderBy / take / skip) on '${n}'`);if(!n)throw Z(`the fieldless arrayOperator '${r}'`);let o=ie(n,t.map,t.model);if(o.kind==="fallback")throw new Error(`toWhereSql: '${n}' is not a field the map declares on ${t.model}`);if(o.kind==="bridge")throw Z(`'${n}', which crosses a bridge`);if(o.hops.length)throw Z(`arrayOperator '${r}' on '${n}', behind the relation '${o.hops[0].prefix}'`);if(o.kind!=="direct"||zr(o)!=="relations")throw Z(`arrayOperator '${r}' on '${n}', which is not a to-many relation`);let i=xr(t.map,o.model,o.entry);if(!i)throw Z(`'${n}', whose relation keys the map does not declare`);if(Qi.includes(r)&&e.condition===void 0)throw Ve(r);if(t.joinedRow!==null)throw new Error(`toWhereSql: arrayOperator '${r}' on '${n}' inside an any over the joined '${t.joinedRow}' \u2014 a joined row's own to-many relations have no join here; compile with toMany: 'subquery'`);let s={map:t.map,model:o.entry.type,column:p=>t.column(`${n}.${p}`),table:p=>t.table(`${n}.${p}`),clamps:p=>t.clamps(`${n}.${p}`),joined:t.joined,joinedRow:null};if(t.joined){if(Mf.includes(r))throw new Error(`toWhereSql: arrayOperator '${r}' on '${n}', a relation the caller joins, holds when it has no rows \u2014 that takes an anti-join, not the topic's join. Only notEmpty and any(condition) read a joined relation; compile with toMany: 'subquery' for the rest`);t.joined(n,r);let p=`${s.column(i[0].there)} IS NOT NULL`;return r!==x.any?p:`(${p} AND ${mo(e.condition,{...s,joinedRow:n})})`}let a=[...i.map(({here:p,there:f})=>`${s.column(f)} = ${t.column(p)}`),...t.clamps(n).map(({where:p,clamps:f})=>`(${mo(p,{...s,clamps:f})})`)],l=p=>`(SELECT 1 FROM ${t.table(n)} WHERE ${[...a,...p?[p]:[]].join(" AND ")})`,d=()=>`(${mo(e.condition,s)})`;switch(r){case x.any:return `EXISTS ${l(d())}`;case x.none:return `NOT EXISTS ${l(d())}`;case x.all:return `NOT EXISTS ${l(`${d()} IS NOT TRUE`)}`;case x.empty:return `NOT EXISTS ${l()}`;default:return `EXISTS ${l()}`}},aE=(e,t)=>{if(!Aa.includes(e.operator))throw Z(`operator '${e.operator}'`);if(e.bind!==void 0)throw Z(`bind '${e.bind}' on '${e.field}'`);if(e.path!==void 0)throw Z(`comparing '${e.field}' with the column '${e.path}'`);if(e.offset!==void 0)throw Z(`an offset on '${e.field}'`);if(e.coerceType!==void 0)throw Z(`coerceType on '${e.field}'`);if(oe(e.caseInsensitive))throw Z(`a case-insensitive comparison on '${e.field}'`);if(M(e.field))throw Z(`the scoped field '${e.field}'`);let r=ie(e.field,t.map,t.model),n=lE(e,r,t),[o]=r.kind==="direct"?ks(e,Ke(r.entry)):[];if(o)throw new Error(`toWhereSql: ${o.message}`);if(e.operator===h.exists)return `${n} IS NOT NULL`;if(e.operator===h.notExists)return `${n} IS NULL`;if(e.value===void 0)throw new Error("No value, path or bind specified");let i=lo(e,e.value,r,"toWhereSql",()=>Ie);if(xe(e,i))return _t(n,W.includes(e.operator));let s=a=>pE(a,e.field);switch(e.operator){case h.equals:return i===null?`${n} IS NULL`:`${n} = ${s(i)}`;case h.notEquals:return i===null?`${n} IS NOT NULL`:De(n,`${n} <> ${s(i)}`);case h.in:{let{values:a,hasNull:l}=Je(wm(e,i));if(!a.length)return l?`${n} IS NULL`:"FALSE";let d=`${n} IN (${a.map(s).join(", ")})`;return l?De(n,d):d}default:{let{values:a,hasNull:l}=Je(wm(e,i));if(!a.length)return l?`${n} IS NOT NULL`:"TRUE";let d=`${n} NOT IN (${a.map(s).join(", ")})`;return l?`(${d} AND ${n} IS NOT NULL)`:De(n,d)}}},lE=(e,t,r)=>{if(t.kind==="fallback")throw new Error(`toWhereSql: '${e.field}' is not a field the map declares on ${r.model}`);if(t.kind==="past-scalar")throw Wn(e.field,t.column);if(t.kind==="bridge")throw Z(`'${e.field}', which crosses a bridge`);let n=t.hops.find(s=>s.entry.isList);if(n)throw Bn(e.field,n);let o=zr(t),i=Jt(e);if(r.joinedRow!==null&&(t.hops.length||o==="relation"))throw new Error(`toWhereSql: '${e.field}' inside an any over the joined '${r.joinedRow}' reads the relation '${t.hops[0]?.prefix??e.field}' \u2014 a joined row's own relations have no join here; compile with toMany: 'subquery'`);if(o==="relation"&&t.kind==="direct"){if(!i)throw fr(e.field);let s=xr(r.map,t.model,t.entry);if(!s)throw Z(`'${e.field}', whose relation keys the map does not declare`);return r.column(`${e.field}.${s[0].there}`)}if(o==="relations")throw new Error(`toWhereSql: '${e.field}' is a to-many relation \u2014 its rows take an arrayOperator rule: { field: '${e.field}', arrayOperator: 'notEmpty' } for a row${r.joined?"; for no rows, compile with toMany: 'subquery'":", 'empty' for none"}`);if(o==="json"||o==="json-path")throw Z(`the Json value '${e.field}'`);if(i)return r.column(e.field);if(o==="instant")throw Z(`the date '${e.field}'`);if(o==="list")throw Z(`the list '${e.field}'`);return r.column(e.field)},wm=(e,t)=>{if(!Array.isArray(t))throw new Error(`toWhereSql: '${e.operator}' on '${e.field}' takes a list of values`);return t},pE=(e,t)=>{if(typeof e=="string"){let r=e.replace(/'/g,"''");return `'${Sm()===An.mysql?r.replace(/\\/g,"\\\\"):r}'`}if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return String(e);if(typeof e=="boolean")return e?"TRUE":"FALSE";throw Z(`the value ${e instanceof Date?"a Date":JSON.stringify(e)} for '${t}'`)};var dE=(e,t,r)=>{H(r,(n,o)=>{if(typeof n.field!="string")return;let i=Qo(e,o,n.field);if(i!==null)throw new Error(`toLensWhereSql: '${n.field}' at ${o.relPath.length?`'${o.relPath.join(".")}'`:"the root"} crosses '${i}', a relation the lens hides \u2014 a hop's clamps are reported at its own path, so a where may only cross hops the lens shows`);return Oe(n)?Te(e.lens.maps,o,n.field).end??false:void 0},t);},xm=(e,t,r)=>{let{end:n}=Te(e.lens.maps,t,r);if(!n)return null;let{pathWheres:o,modelWheres:i}=j(e,n.mapName,n.modelName,n.relPath);return {end:n,clamps:[...o.map(s=>({...s,isDefault:false})),...i.map(s=>({...s,isDefault:true}))]}},Em=(e,t,r)=>n=>{let o=xm(e,t,n);return o?o.clamps.filter(i=>i.layer<r).map(i=>({where:i.where,clamps:Em(e,o.end,i.layer)})):[]},Rm=(e,t,r,n)=>{let o=e.map(({where:i,layer:s})=>jl(i,t,r,n(s)));return o.length===1?o[0]:`(${o.join(" AND ")})`},fE=(e,t)=>{let r=new Set,n=new Map;return o=>({joined:(i,s)=>{let a=xm(e,t,i);if(!a)throw new Error(`toLensWhereSql: '${i}' reaches no relation`);let{end:l,clamps:d}=a,p=d.find(f=>f.layer>=o);if(p)throw new Error(`toLensWhereSql: the root where of layer ${o+1} reads '${i}' on the caller's join, whose ON carries a clamp of layer ${p.layer+1} (${p.isDefault?`${l.modelName}'s default where`:"its where"}) \u2014 check() reads a where through the clamps of the layers above its own only. Move that clamp into a narrowing above layer ${o+1}, or compile with toMany: 'subquery'`);if(d.some(f=>f.isDefault)){let f=`${l.mapName}.${l.modelName}`,u=n.get(f),m=l.mapName===t.mapName&&l.modelName===t.modelName?`the root is a ${l.modelName} too`:u!==void 0&&u!==i?`the root where also reads '${u}', which reaches ${l.modelName} too`:null;if(m!==null)throw new Error(`toLensWhereSql: the root where reads '${i}' on the caller's join, and ${l.modelName} has a default where, but ${m} \u2014 mapDefaults holds one predicate per model, which reads one table alias, and two aliases need it. Compile with toMany: 'subquery'`);n.set(f,i);}if(s===x.any){if(r.has(i))throw new Error(`toLensWhereSql: the root reads '${i}' with two any rules \u2014 on the caller's join one joined row stands for the relation, so both conditions would have to hold on the same row, where check() lets each find its own. Write one any whose condition says which row, or compile with toMany: 'subquery'`);r.add(i);}}})},Om=(e,t)=>()=>({joined:r=>{throw new Error(`toLensWhereSql: ${e} reads the to-many relation '${r}' \u2014 with toMany: 'join' ${t}; only the root's where reads a joined relation`)}}),$m=(e,{columns:t,tables:r,toMany:n="subquery"})=>{if(n!=="subquery"&&n!=="join")throw new C(`toLensWhereSql: toMany '${String(n)}' is neither 'subquery' nor 'join'`);let o=D(e),i={root:null,relations:{},mapDefaults:{}};for(let{at:s,effect:a}of Yt(o)){let l={columns:t,tables:r,map:o.lens,mapName:s.mapName,model:s.modelName},d=p=>({clamps:Em(o,s,p)});for(let{where:p}of [...a.pathWheres,...a.modelWheres])dE(o,s,p);if(a.pathWheres.length){let p=s.relPath.join("."),f=n==="subquery"?d:p?Om(`the where at '${p}'`,"it sits in that relation's join ON, ahead of the joins below it"):fE(o,s),u=Rm(a.pathWheres,l,p?`${p}.`:"",f);p?i.relations[p]=u:i.root=u;}if(a.modelWheres.length){let p=Qt(i.mapDefaults,s.mapName,()=>({models:{}})),f=n==="subquery"?d:Om(`the default where of ${s.modelName}`,`it compiles once for every path that reaches ${s.modelName}, and the join exists only where the lens shows the relation`),u=Rm(a.modelWheres,l,`${s.modelName}.`,f),m=O(p.models,s.modelName);if(m!==void 0&&m!==u)throw new Error(`toLensWhereSql: the default where of ${s.modelName} reads a to-many relation whose clamps differ between the paths that reach ${s.modelName} \u2014 a model default compiles to one predicate for every path`);p.models[s.modelName]=u;}}return i};var vm=e=>Array.isArray(e)?e.some(vm):typeof e=="object"&&e!==null,Nm=(e,t,r,n)=>{let o=`NULLIF(${t}, 'null'::jsonb)`,i=`jsonb_typeof(${o})`,s=`(${o} #>> '{}')`,a=S=>`${F(n,JSON.stringify(S))}::jsonb`,l=oe(e.caseInsensitive),d=S=>l?`LOWER(${S})`:S,p=W.includes(e.operator),f=S=>De(o,`NOT (${S})`);if(xe(e,r))return _t(o,p);let u=is(e.operator,r);if(u)throw u;let m=S=>{if(vm(S))throw V("toSql",`A case-insensitive comparison of '${e.field}' with a list holding objects`);return a(Kr(S))},y=S=>l&&typeof S=="string"?`(${i} = 'string' AND LOWER(${s}) = LOWER(${F(n,S)}))`:l&&Array.isArray(S)?`(${i} = 'array' AND LOWER(${o}::text)::jsonb = ${m(S)})`:`${o} = ${a(S)}`,c=S=>`(${i} = 'string' AND ${d(s)} LIKE ${d(F(n,S))})`,g=S=>{let b=v=>`(CASE WHEN ${i} = 'array' THEN EXISTS (SELECT 1 FROM jsonb_array_elements(${o}) AS e WHERE ${v}) ELSE FALSE END)`;return l&&typeof S=="string"?b(`jsonb_typeof(e) = 'string' AND LOWER(e #>> '{}') = LOWER(${F(n,S)})`):l&&Array.isArray(S)?b(`LOWER(e::text)::jsonb = ${m(S)}`):typeof S=="object"&&S!==null?b(`e = ${a(S)}`):`(${i} = 'array' AND ${o} @> ${a([S])})`},w=S=>typeof S=="string"?`(${c(`%${Ee(S)}%`)} OR ${g(S)})`:g(S);switch(e.operator){case h.equals:return r===null?`${o} IS NULL`:y(r);case h.notEquals:return r===null?`${o} IS NOT NULL`:f(y(r));case h.in:case h.notIn:{let{values:S,hasNull:b}=Je(r),v=S.length?`(${S.map(y).join(" OR ")})`:"FALSE";return e.operator===h.in?b?`(${v} OR ${o} IS NULL)`:v:b?`(NOT ${v} AND ${o} IS NOT NULL)`:f(v)}case h.between:case h.notBetween:{let[S,b]=r,v=`(${i} = jsonb_typeof(${a(S)}) AND ${o} BETWEEN ${a(S)} AND ${a(b)})`;return e.operator===h.between?v:f(v)}case h.contains:return w(r);case h.notContains:return f(w(r));case h.startsWith:return c(`${Ee(String(r))}%`);case h.endsWith:return c(`%${Ee(String(r))}`);case h.notStartsWith:return f(c(`${Ee(String(r))}%`));case h.notEndsWith:return f(c(`%${Ee(String(r))}`));case h.matches:case h.notMatches:{let{source:S,caseInsensitive:b}=wr(r),v=`(${i} = 'string' AND ${s} ~${b?"*":""} ${F(n,Io(S))})`;return e.operator===h.matches?v:f(v)}}let R=co(e.operator,"field")?.symbol;if(R)return `(${i} = jsonb_typeof(${a(r)}) AND ${o} ${R} ${a(r)})`;throw new Error(`Operator '${e.operator}' is not supported on a Json value in SQL`)};var Am=e=>typeof e=="object"&&Fr(e)!==null,ni=({sql:e,shape:t},r)=>{if(t!=="json-path"&&t!=="text")return `to_timestamp(EXTRACT(EPOCH FROM ${e}))`;let n=F(r,ft(r).timeZone);return `(CASE WHEN btrim(${e}) ~ '^-?[0-9]+(\\.[0-9]+)?$' THEN to_timestamp(btrim(${e})::numeric / 1000) WHEN ${e} ~* '[0-9]{2}:[0-9]{2}(:[0-9]{2}(\\.[0-9]+)?)?\\s*(z|[+-][0-9]{2}(:?[0-9]{2})?)\\s*$' OR ${e} ~* '\\m(gmt|utc)\\M' THEN (${e})::timestamptz ELSE (${e})::timestamp AT TIME ZONE ${n} END)`},Xs=e=>Object.values(e).some(Am),cE=(e,t,r)=>{let n=_r(r),o=n?"int":"double precision";if(typeof e=="number"||!Am(e)){let a=qa(e,nn(t),r);return `${F(t,a)}::${o}`}let i=$e(e,t).sql;return `(CASE WHEN ${n?`${i} >= 0 AND ${i} = trunc(${i})`:`${i} >= 0`} THEN ${i} END)::${o}`},mE=(e,t)=>`make_interval(${Bf.flatMap(n=>{let o=Object.keys(e).filter(i=>e[i]!==void 0&&et[i].interval===n).map(i=>{let s=cE(e[i],t,i),{factor:a}=et[i];return a===1?s:`${a} * ${s}`});return o.length?[`${n} => ${o.join(" + ")}`]:[]}).join(", ")})`,oi=(e,t,r,n)=>{let o=ft(n).timeZone;if(e.type==="value"&&!Xs(t)){let l=Br(t,nn(n));return e.value===null||e.value===void 0||l===null?er:{type:"value",value:cr(vt(e.value),l,r,o).toDate()}}let i=e.type==="column"?e.computed?e.sql:ni(e,n):`${F(n,e.value??null)}::timestamptz`,s=F(n,o);return {type:"column",computed:true,sql:`(((${i} AT TIME ZONE ${s}) ${r===1?"+":"-"} ${mE(t,n)}) AT TIME ZONE ${s})`}};var Vl=(e,t,r)=>{let n=$e(t,r);if(e.type==="value"&&n.type==="value"){let i=Ur(n.value);return i===null?er:{type:"value",value:Wr(e.value,i)}}let o=(i,s)=>i.type==="column"?`(${i.sql})::double precision`:`${F(r,s(i.value)??null)}::double precision`;return {type:"column",computed:true,sql:`(${o(e,i=>i)} + ${o(n,Ur)})`}},Pm=(e,t,r)=>{if(Mt(e))return er;let n=$e(t,r);if(n.type==="column")throw new Error(`A row path on a date offset ('${t.path}') is check-only; evaluate with check()`);let o=Qn(n.value);return o===null?er:oi(e,...o,r)};var Tm,km=e=>{Tm=e;},Pr=(e,t)=>Tm(e,t);var ta=(e,t,r)=>{let n=os(e);if(n)throw n;let o=r===void 0?Xt(e.field,t):{sql:r,shape:"scalar"};if(o.shape==="relation"&&!Jt(e))throw fr(e.field);let i=r===void 0,s=Re(e)&&t.map&&t.currentModel?(M(e.path)??{path:e.path}).path:null;if(s!==null){let b=to(te(e.field,t.map,t.currentModel),te(s,t.map,t.currentModel),e.operator);if(b)throw V("toSql",`Comparing '${e.field}' with the column '${e.path}'`,b)}if(o.shape==="enum"&&!pr.includes(e.operator)){let b=Lm(e,t),v=te(e.field,t.map,t.currentModel),E=b!==ea&&v&&!xe(e,b)?Vs(e,b,v,t.map):null;if(E){let q=`${o.sql}::text = ANY(${F(t,E.values)})`;return E.matchesNull?De(o.sql,q):q}}let a=o.shape==="enum"&&!pr.includes(e.operator)&&s===null?{...o,sql:`${o.sql}::text`}:o;if((o.shape==="json"||o.shape==="json-path")&&!pr.includes(e.operator)){let b=Lm(e,t);if(b===ea)throw new Error(`The Json value '${e.field}' compares against an operand known when compiling, not one read per row.`);return Nm(e,Lt(e.field,t,{jsonb:true}),b,t)}let d=b=>{if(b.type==="column"&&!b.computed&&(b.shape==="json"||b.shape==="json-path"))throw V("toSql",`'${e.field}' compared with a Json value read per row`,"SQL would compare its text")};if(ze.includes(e.operator)){let b=Dm(e,t);return b?.forEach(d),ri(a.sql,b,W.includes(e.operator),t,i)}let p=Mm(e,t);if(d(p),p.type==="column"&&Ut(e.operator,"field")==="string"&&!Hr(o.shape)&&o.shape!=="list")throw V("toSql",`'${e.operator}' on '${e.field}'`,"it is not text");if(p.type==="column"&&p.computed&&o.shape==="text"&&r===void 0)throw V("toSql",`'${e.field}' against a value moved by an offset`,"an offset moves a number or a date");let f=a.sql,u=co(e.operator,"field");if(u)return Ys(f,u.symbol,p,false,t);if(p.type==="value"&&xe(e,p.value))return _t(f,W.includes(e.operator),i);let m=p.type==="column"&&p.computed===true,y=oe(e.caseInsensitive)&&(p.type==="column"?!m&&Hr(o.shape)&&Hr(p.shape):Or(o.shape,p.value)),c=b=>y?`LOWER(${b})`:b,g=b=>y?Kr(b):b;if(o.shape==="list"&&p.type==="column"&&bt.includes(e.operator)){if(te(e.field,t.map,t.currentModel)?.type!=="String"||!Hr(p.shape))throw V("toSql",`'${e.operator}' on the list '${e.field}' with a member read per row ('${e.path}')`,"Postgres matches a member of the list's own type only");let b=oe(e.caseInsensitive)&&Hr(p.shape)?`EXISTS (SELECT 1 FROM unnest(${f}) AS e WHERE LOWER(e) = LOWER(${p.sql}))`:`array_position(${f}, ${p.sql}) IS NOT NULL`;return e.operator===h.contains?`(${p.sql} IS NOT NULL AND ${b})`:`(${f} IS NULL OR (${p.sql} IS NOT NULL AND NOT ${b}))`}if(o.shape==="list"&&p.type==="value"){let b=oe(e.caseInsensitive)&&Or("text",p.value);if(bt.includes(e.operator)){let v=F(t,p.value),E=b?`EXISTS (SELECT 1 FROM unnest(${f}) AS e WHERE LOWER(e) = LOWER(${v}))`:`array_position(${f}, ${v}) IS NOT NULL`;return e.operator===h.contains?E:`NOT ${E}`}if(dr.includes(e.operator)&&Array.isArray(p.value))return Pr(ys(e,p.value),t);if(gE(e.operator))throw new Error(`'${e.operator}' does not apply to the list '${e.field}'; test its members with contains.`);if(b&&Ot.includes(e.operator)&&Array.isArray(p.value)){let v=F(t,Kr(p.value)),E=`(${f} IS NOT NULL AND ARRAY(SELECT LOWER(e) FROM unnest(${f}) AS e) = ${v})`;return e.operator===h.equals?E:De(f,`NOT ${E}`)}}let w=p.type==="value"?p.value:void 0,R=p.type==="column"?p.sql:void 0;if(R!==void 0&&(dr.includes(e.operator)||["pattern","string"].includes(Ut(e.operator,"field"))))throw V("toSql",`'${e.operator}' against an operand read per row ('${e.path}')`);let S=b=>i?De(f,b):b;switch(e.operator){case h.equals:return m?`${f} = ${R}`:R!==void 0?`${c(f)} IS NOT DISTINCT FROM ${c(R)}`:w===null?`${f} IS NULL`:`${c(f)} = ${c(F(t,w))}`;case h.notEquals:return m?S(`${f} <> ${R}`):R!==void 0?`${c(f)} IS DISTINCT FROM ${c(R)}`:w===null?`${f} IS NOT NULL`:S(`${c(f)} <> ${c(F(t,w))}`);case h.in:{let{values:b,hasNull:v}=Je(w);if(!b.length)return v?`${f} IS NULL`:"FALSE";let E=`${c(f)} = ANY(${F(t,g(b))})`;return v?S(E):E}case h.notIn:{let{values:b,hasNull:v}=Je(w);if(!b.length)return v?`${f} IS NOT NULL`:"TRUE";let E=`${c(f)} <> ALL(${F(t,g(b))})`;return v?`(${E} AND ${f} IS NOT NULL)`:S(E)}case h.contains:return `${c(f)} LIKE ${c(F(t,`%${Ee(String(w))}%`))}`;case h.notContains:return S(`${c(f)} NOT LIKE ${c(F(t,`%${Ee(String(w))}%`))}`);case h.startsWith:return `${c(f)} LIKE ${c(F(t,`${Ee(String(w))}%`))}`;case h.endsWith:return `${c(f)} LIKE ${c(F(t,`%${Ee(String(w))}`))}`;case h.notStartsWith:return S(`${c(f)} NOT LIKE ${c(F(t,`${Ee(String(w))}%`))}`);case h.notEndsWith:return S(`${c(f)} NOT LIKE ${c(F(t,`%${Ee(String(w))}`))}`);case h.matches:return Cm(f,w,false,t);case h.notMatches:return S(Cm(f,w,true,t));case h.isEmpty:case h.notEmpty:return Il(e.field,o,e.operator===h.isEmpty,t,bs(e,t.map,t.currentModel));case h.exists:return `${f} IS NOT NULL`;case h.notExists:return `${f} IS NULL`;default:throw new Error(`Unknown operator: ${e.operator}`)}},Mm=(e,t)=>{if(pr.includes(e.operator))return {type:"value",value:void 0};let r=_m(e,$e(e,t),t);return e.offset===void 0?r:Vl(r,e.offset,t)},_m=(e,t,r)=>t.type==="column"?t:{type:"value",value:lo(e,t.value,br(e.field,r.map,r.currentModel),"toSql",()=>ft(r).timeZone)},Dm=(e,t)=>{let r=_m(e,$e(e,t),t),n=r.type==="value"?r.value:void 0;if(n==null)return null;let o=rt(n,e.operator);return o.some(i=>i!=null&&!ge(i))&&Jn(n,e.operator),He(o).map(i=>{let s={type:"value",value:i};return e.offset===void 0?s:Vl(s,e.offset,t)})},Cm=(e,t,r,n)=>{if(typeof t!="string"&&!(t instanceof RegExp))throw new Error("matches requires a string or RegExp pattern");let{source:o,caseInsensitive:i}=wr(t);return `${e} ${r?"!":""}~${i?"*":""} ${F(n,Io(o))}`},ea=Symbol("not known"),Lm=(e,t)=>{if(ze.includes(e.operator)){let n=Dm(e,t);return n?n.every(o=>o.type==="value")?n.map(o=>o.value):ea:null}let r=Mm(e,t);return r.type==="value"?r.value:ea},Il=(e,t,r,n,o)=>{let{sql:i,shape:s}=t;if(s==="list")return r?`(${i} IS NULL OR cardinality(${i}) = 0)`:`cardinality(${i}) > 0`;if(s==="json"||s==="json-path"){let a=Lt(e,n,{jsonb:true}),l=["'null'::jsonb",...o?[`'""'::jsonb`]:[],"'[]'::jsonb"].join(", ");return r?`(${a} IS NULL OR ${a} IN (${l}))`:`${a} NOT IN (${l})`}return o?r?`(${i} IS NULL OR ${i} = '')`:`(${i} IS NOT NULL AND ${i} <> '')`:r?`${i} IS NULL`:`${i} IS NOT NULL`},gE=e=>Ut(e,"field")==="string"&&!bt.includes(e);var Fm=(e,t)=>{if(Ne(e))throw Et("toSql");if(e.condition)throw new Error("Aggregate condition filtering is not yet supported by toSql(). Use check() for in-memory evaluation or toPrisma() for database queries.");let r=yE(e,t);return ta(e,t,r)},yE=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!Rt.includes(r))throw ur(r);let o=r==="sum"?"SUM":"AVG",i=Ue({field:e.field},t.map,t.currentModel);if(i==="relation"||te(e.field,t.map,t.currentModel)?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 toSql() cannot aggregate relation lists. Use toPrisma() instead.`);if(n?.includes("."))throw new Error(`aggregate.field '${n}' contains a nested path \u2014 toSql() only supports flat field names. Use check() for nested paths.`);let s=i==="list",a=Lt(e.field,t,{jsonb:!s}),l=s?a:`(CASE WHEN jsonb_typeof(${a}) = 'array' THEN ${a} END)`;if(s){if(n)throw new Error("aggregate.field is not supported for native array types. Use a JSONB column for object arrays.");return `(SELECT ${`COALESCE(${o}(elem), 0)`} FROM unnest(${l}) AS elem)`}if(n){let f=`(elem->>${ml(n)})::numeric`;return `(SELECT ${`COALESCE(${o}(${f}), 0)`} FROM jsonb_array_elements(${l}) AS elem)`}return `(SELECT ${`COALESCE(${o}(elem::numeric), 0)`} FROM jsonb_array_elements_text(${l}) AS elem)`};var jm=(e,t)=>{if(Ne(e))throw Et("toSql");if(!e.field)throw rs("toSql");if(Ue({field:e.field},t.map,t.currentModel)==="relation"||te(e.field,t.map,t.currentModel)?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 relation arrays are not supported in SQL; use toPrisma().`);switch(e.arrayOperator){case x.empty:case x.notEmpty:{let n=Xt(e.field,t),o=e.arrayOperator===x.empty;if(n.shape==="list")return Il(e.field,n,o,t,false);let i=Lt(e.field,t,{jsonb:true});return `(CASE WHEN jsonb_typeof(${i}) = 'array' THEN jsonb_array_length(${i}) ${o?"=":">"} 0 ELSE ${o?"TRUE":"FALSE"} END)`}case x.all:case x.any:case x.none:case x.atLeast:case x.atMost:case x.exactly:throw new Error(`Array operator '${e.arrayOperator}' with conditions is not supported in SQL. Use application-level filtering for complex array operations.`);default:throw fe(e.arrayOperator,"array")}};var hE=(e,t)=>e.type==="column"&&!e.computed?{type:"column",sql:ni(e,t),computed:true}:e,Vm=e=>e===void 0||e==="instant"||e==="text"||e==="json-path"||e==="unknown",Im=e=>V("toSql",`A date rule on '${e}'`,"it is not a date column"),qm=(e,t,r)=>{let n=t.some(i=>i.type==="column"),o=e.shape==="json-path"||e.shape==="text";return n||o?{lhs:ni(e,r),ends:t.map(i=>hE(i,r))}:{lhs:e.sql,ends:t}},Bm=(e,t)=>{let r=Xt(e.field,t);if(!Vm(r.shape))throw Im(e.field);let n=$e(e,t);if(n.type==="column"&&!Vm(n.shape))throw Im(String(e.path??e.field));if(!Mt(n)){let s=e.offset===void 0?void 0:$e(e.offset,t),a=Gt(n.type==="value"?n.value:void 0,s?.type==="value"?s.value:void 0);if(a)throw a}let o=co(e.dateOperator,"date");if(o){let{lhs:s,ends:a}=qm(r,[SE(e,t)],t);return Ys(s,o.symbol,a[0],o.negated,t)}let i=(s,a)=>{if(!s)return ri(r.sql,null,a,t);let{lhs:l,ends:d}=qm(r,s,t);return ri(l,d,a,t)};switch(e.dateOperator){case N.within:case N.notWithin:return i(bE(e,t),W.includes(e.dateOperator));case N.between:case N.notBetween:return i(RE(e,t),W.includes(e.dateOperator));case N.dayIn:case N.dayNotIn:{let s=e.dateOperator===N.dayNotIn,a=$e(e,t);if(a.type==="column")throw V("toSql",`A weekday list read from the row ('${e.path}')`);let l=Wa(a.value);if(l===null)return _t(r.sql,s);let d=F(t,ft(t).timeZone),p=F(t,l),f=`EXTRACT(DOW FROM (${ni(r,t)} AT TIME ZONE ${d}))`;return e.dateOperator===N.dayIn?`${f} = ANY(${p})`:De(r.sql,`${f} <> ALL(${p})`)}default:throw fe(e.dateOperator,"date")}},Wm=e=>({type:"value",value:Co(ft(e)).toDate()}),wE=(e,t,r)=>{let n=be(e);if(n&&Xs(n[0]))return oi(Wm(r),...n,r);let o=$t(e,nn(r));return o===null?er:{type:"value",value:Kn(o,t,ft(r)).toDate()}},Um=(e,t,r)=>e==null?er:ee(e)?wE(e,t,r):{type:"value",value:ms(e,ft(r).timeZone)},Km=(e,t,r)=>t.offset===void 0?e:Pm(e,t.offset,r),SE=(e,t)=>{let r=$e(e,t),n=r.type==="column"?r:Um(r.value,e.dateOperator,t);return Km(n,e,t)},bE=(e,t)=>{let r=$e(e,t);if(Mt(r))return null;if(r.type==="column"||!ee(r.value))throw tt(e.dateOperator);let n=be(r.value);if(n&&Xs(n[0])){let s=Wm(t),a=oi(s,...n,t);return n[1]===-1?[a,s]:[s,a]}let o=$t(r.value,nn(t));if(o===null)return null;let i=Gn(o,ft(t));return [{type:"value",value:i[0].toDate()},{type:"value",value:i[1].toDate()}]},RE=(e,t)=>{let r=$e(e,t);if(Mt(r))return null;let n=r.type==="value"?r.value:void 0,o=rt(n,e.dateOperator).map(l=>Um(l,e.dateOperator,t));if(o.some(Mt))return null;let[i,s]=o;return (i.type==="value"&&s.type==="value"?He([i.value,s.value]).map(l=>({type:"value",value:l})):o).map(l=>Km(l,e,t))};var Gm=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(n=>Pr(n,t)).join(" AND ")})`,zm=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(n=>Pr(n,t)).join(" OR ")})`,Hm=(e,t)=>{if(Nt(e,t.map,t.currentModel))return "TRUE";let r=Pr(e.if,t),n=Pr(e.then,t);if(e.else!==void 0){let o=Pr(e.else,t);return `(((${r}) IS NOT TRUE OR ${n}) AND ((${r}) IS TRUE OR ${o}))`}return `((${r}) IS NOT TRUE OR ${n})`};var ii=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if(Bi(e,"toSql"),"field"in e&&typeof e.field=="string"&&t.map&&t.currentModel&&Rr(e.field,t.map,t.currentModel))return "TRUE";let r=le(e);(r==="field"||r==="date")&&Rs(e.field,t.map,t.currentModel);let n=e;switch(r){case "all":return Gm(n,t);case "any":return zm(n,t);case "if":return Hm(n,t);case "array":return jm(n,t);case "aggregate":return Fm(n,t);case "date":return Bm(n,t);case "field":return ta(n,t);default:throw xt()}};km(ii);var ql=e=>{let t=Pe(e?.map,e?.mapName,"toSql"),r=!!(t&&e?.model),n=e?.alias??(r?"t0":void 0);return {params:[],paramIndex:0,dateConfig:{now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},map:t,currentModel:e?.model,currentAlias:n,joinCounter:r?{n:0}:void 0,joins:r?[]:void 0,joinRegistry:r?new Map:void 0}},OE=(e,t)=>js(e,t,"toSql",xE),xE=(e,t)=>{let r=ql(t);return {sql:ii(e,r),params:r.params,joins:r.joins??[]}};var Jm=(e,t)=>{let[r,...n]=t,o=e[r];if(n.length===0){o===void 0&&(e[r]=true);return}let i=o!==void 0&&o!==true?o.select:{};Jm(i,n),e[r]={select:i};},EE=(e,t,r,n,o,i,s,a,l,d)=>{let p=Ws(`source '${o}' at '${t}'`,()=>Yo(a,{...l,map:e,mapName:r,model:n})),f=p.steps.at(-1),u=f.where,m=p.steps.length>1||(f.refs?.length??0)>0,y=Pe(e,r,"toPrisma"),c=A=>d!==void 0&&ie(A,y,n).kind==="bridge",g=i!==void 0&&!c(i)?i:void 0,w=(s??[]).map(A=>c(A)?void 0:A),R=A=>{let I=ie(A,y,n);return I.kind==="json-path"?A.split(".").slice(0,I.stopIndex).join("."):A},S=d===void 0?[]:Hs(e,r,n,[..._e(d),...i!==void 0&&g===void 0?[i]:[],...(s??[]).filter(c)].map(R)).filter(A=>A!==o),b=g?.includes(".")?g:void 0,v=[...w.filter(A=>A!==void 0),...b?[b]:[],...S],E={[o]:true,...g&&!b?{[g]:true}:{}};for(let A of v)Jm(E,A.split("."));let q={model:n,...s||b||d!==void 0?{}:{distinct:g?[o,g]:[o]},select:E,where:u,...m?{steps:p.steps}:{}},ue;try{for(let Se of S){let ke=ie(Se,y,n);if(!(ke.kind==="direct"&&!ke.hops.length&&ke.entry.kind!=="object"))throw new Error(ke.kind==="direct"?`the re-check reads '${Se}' through a relation, which flat SQL rows can't hold \u2014 run the Prisma query`:`the re-check reads '${Se}', which is not a column of ${n} \u2014 run the Prisma query`)}let A=ql({...l,map:e,mapName:r,model:n,alias:"t0"}),I=ii(a,A),B=b?Lt(b,A):void 0,Tr=w.map((Se,ke)=>Se===void 0?void 0:`${Lt(Se,A)} AS ${se(`__group_${ke}`)}`),yo=A.joins??[],kr=yo.length?` ${yo.join(" ")}`:"",ce=I?.trim()?` WHERE ${I}`:"",ut=se("t0"),on=[`${ut}.${se(o)}`,...B?[`${B} AS ${se("__label")}`]:g?[`${ut}.${se(g)}`]:[],...Tr.filter(Se=>Se!==void 0),...S.map(Se=>`${ut}.${se(Se)}`)].join(", "),ne=k(O(e.maps,r),n)?.dbName??n;ue={sql:`SELECT DISTINCT ${on} FROM ${se(ne)} AS ${ut}${kr}${ce}`,params:A.params};}catch(A){ue={sql:null,params:[],error:A instanceof Error?A.message:String(A)};}return {prisma:q,sql:ue}},Qm=(e,t={})=>{let{lens:r}=D(e);return Zc(e).map(({path:n,visit:o,field:i,label:s,groupBy:a,where:l,recheck:d})=>{let p=l,{prisma:f,sql:u}=EE(r,n,o.mapName,o.model,i,s,a,p,t,d);return {path:n,mapName:o.mapName,model:o.model,field:i,...s!==void 0?{label:s}:{},...a!==void 0?{groupBy:a}:{},composedWhere:p,prisma:f,sql:u,...d!==void 0?{recheck:d}:{}}})};var ra=(e,t)=>{let r=D(e);return tn(r,Tt(r),t).resolution};var si=class extends Error{constructor(r){super(`inferValueType: ${r.path}: ${r.message}`);this.issue=r;}issue},Y=(e,t,r)=>{throw new si({path:e,code:t,message:r})};var na=(e,t)=>{let r=M(e);return r?(r.depth>1&&Y(t,"scope_out_of_bounds",`'${e}' reaches past the row a value expression reads`),r.path):e},oa=(e,t)=>{if(!e)throw new C(`inferValueType needs a lens to type ${t}`);return e},ai=(e,t,r)=>{let n=ra(e,t);if(n.outcome!=="resolved")return Y(r,"unresolved_path",`'${t}' does not resolve through the lens (${n.outcome})`);let o=n.hops.slice(0,-1).find(i=>L(i.entry)&&i.entry.isList);return {entry:n.terminal.entry,viaList:o?o.field:null,json:n.jsonSubPath.length>0||n.terminal.entry.type===P.Json}},li=e=>e.json?P.Json:Ke({...e.entry,isList:false})??null;var sa={kind:null,isList:false,nullable:true},$E={kind:null,isList:false,nullable:false},ia=e=>e!==null&&X.includes(e),Zm=e=>`${e.kind??"null"}${e.isList?"[]":""}`,aa=(e,t,r)=>{let n=e.nullable||t.nullable;if(e.kind===null&&e.isList===t.isList)return {...t,nullable:n};if(t.kind===null&&e.isList===t.isList)return {...e,nullable:n};if(e.kind===null&&!e.isList)return {...t,nullable:true};if(t.kind===null&&!t.isList)return {...e,nullable:true};if(e.isList===t.isList){if(e.kind===t.kind)return {...e,nullable:n};if(ia(e.kind)&&ia(t.kind))return {kind:e.kind===P.Decimal||t.kind===P.Decimal?P.Decimal:P.Float,isList:e.isList,nullable:n}}return Y(r,"value_type_mismatch",`the values here are ${Zm(e)} and ${Zm(t)}`)},la=(e,t)=>({...e.reduce((r,n)=>aa(r,n,t),$E),isList:true});var vE={String:["String","Boolean","DateTime",...X],DateTime:["DateTime","String",...X],Boolean:["Boolean","String"],Enum:["String"],...Object.fromEntries(X.map(e=>[e,["String","DateTime",...X]]))},NE=(e,t,r)=>{e===null||e===t||vE[e]?.includes(t)||Y(r,"coerce_kind_mismatch",`${e} values can't be read as ${t}`);},Ym=(e,t,r)=>{let n=na(t.field,`${r}.field`),o=ai(e,n,`${r}.field`);return (o.viaList||o.entry.isList!==true)&&Y(`${r}.field`,"aggregate_needs_list",`'${t.field}' is not a list; an aggregate reads a list`),{field:n,list:o}},AE=(e,t,r)=>{let{field:n,list:o}=Ym(e,t,r),i=t.aggregate.field;if(!L(o.entry))return i!==void 0&&Y(`${r}.aggregate.field`,"invalid_aggregate_field",`'${t.field}' holds values, not rows`),li(o);if(i===void 0)return Y(`${r}.aggregate.field`,"aggregate_field_required",`${t.aggregate.mode} over rows names the field it reads`);let s=ai(e,`${n}.${i}`,`${r}.aggregate.field`);return (L(s.entry)||s.entry.isList)&&Y(`${r}.aggregate.field`,"invalid_aggregate_field",`'${i}' is not one value per row`),li(s)},Xm=(e,t,r)=>{let n=t.aggregate.mode;if(Ln[n].result==="count")return e&&Ym(e,t,r),{kind:P.Int,isList:false,nullable:false};let o=AE(oa(e,`${n} over '${t.field}'`),t,r);t.coerceType!==void 0&&NE(o,t.coerceType,`${r}.coerceType`);let i=t.coerceType??o,s=`${r}.aggregate.field`;return n==="sum"||n==="avg"?(ia(i)||Y(s,"aggregate_kind_mismatch",`${n} adds numbers, not ${i??"untyped"} values`),{kind:n==="sum"||i===P.Decimal?i:P.Float,isList:false,nullable:n==="avg"}):n==="distinct"?((i===null||!Nf.includes(i))&&Y(s,"aggregate_kind_mismatch",`distinct lists strings, enums, dates, booleans and numbers, not ${i??"untyped"} values`),{kind:i,isList:true,nullable:false}):((i===null||!vf.includes(i))&&Y(s,"aggregate_kind_mismatch",`${n} orders numbers and dates, not ${i??"untyped"} values; read strings with coerceType`),{kind:i,isList:false,nullable:true})};var pa=e=>!Array.isArray(e)&&e.distinct===true,da=(e,t=false)=>{let r=new Set,n=new Set,o=new Set;return e.filter(i=>{let[s,a]=i instanceof Date?[n,i.getTime()]:typeof i=="object"&&i!==null?[o,JSON.stringify(i)]:[r,t&&typeof i=="string"?i.toLowerCase():i];return s.has(a)?false:(s.add(a),true)})};var fa=(e,t)=>e===null?sa:typeof e=="number"?{kind:Number.isInteger(e)?P.Int:P.Float,isList:false,nullable:false}:typeof e=="bigint"?{kind:P.BigInt,isList:false,nullable:false}:typeof e=="string"?{kind:P.String,isList:false,nullable:false}:typeof e=="boolean"?{kind:P.Boolean,isList:false,nullable:false}:e instanceof Date?{kind:P.DateTime,isList:false,nullable:false}:Array.isArray(e)?la(e.map((r,n)=>{let o=`${t}[${n}]`;return Array.isArray(r)&&Y(o,"nested_list","a list's items are single values"),fa(r,o)}),t):{kind:P.Json,isList:false,nullable:false};var eg=(e,t,r)=>{let n=ai(e,na(t,r),r);return n.viaList&&Y(r,"to_many_path",`'${t}' reads through the to-many relation '${n.viaList}'; aggregate its rows`),L(n.entry)&&Y(r,"relation_not_value",`'${t}' names a relation's rows, not a value; aggregate them`),{kind:li(n),isList:n.entry.isList===true,nullable:n.json||n.entry.isRequired!==true}};var go=e=>re(e)&&"aggregate"in e&&["operator","value","path","bind"].some(t=>t in e);var tg={source:["value","path","bind","bindOptional"],if:["if","then","else"],aggregate:["field","aggregate","condition","filter","orderBy","take","skip","coerceType","caseInsensitive"],list:["list","distinct"]},Bl=(e,t)=>e.map(r=>({...r,path:r.path.startsWith("$")?`${t}${r.path.slice(1)}`:`${t}.${r.path}`})),ca=(e,t,r)=>Object.keys(e).filter(n=>!tg[t].includes(n)).map(n=>({path:`${r}.${n}`,code:"unknown_key",message:`a ${t==="source"?"value source":`${t} value`} takes ${tg[t].join(", ")}, not '${n}'`})),PE=(e,t,r)=>{if(r)return [{path:t,code:"nested_list",message:"a list's items are single values"}];let n=Ir(e).flatMap((s,a)=>ua(s,`${t}[${a}]`,true));if(Array.isArray(e))return n;let o=e,i=ca(o,"list",t);return Array.isArray(o.list)||i.push({path:`${t}.list`,code:"invalid_list",message:"list must be an array"}),o.distinct!==void 0&&typeof o.distinct!="boolean"&&i.push({path:`${t}.distinct`,code:"invalid_distinct",message:"distinct must be a boolean"}),[...i,...n]},TE=(e,t,r)=>{let n=ca(e,"if",t);return e.if===void 0?n.push({path:`${t}.if`,code:"condition_required",message:"if / then takes an if"}):n.push(...Bl(Er(e.if).errors,`${t}.if`)),e.then===void 0?n.push({path:`${t}.then`,code:"value_required",message:"if / then takes a then"}):n.push(...ua(e.then,`${t}.then`,r)),e.else!==void 0&&n.push(...ua(e.else,`${t}.else`,r)),n},kE=(e,t)=>[...ca(e,"aggregate",t),...e.field===""?[{path:`${t}.field`,code:"field_required",message:"an aggregate value reads a list field"}]:[],...Bl(Ku(e).errors,t)],ua=(e,t,r)=>{let n=e;switch(yr(e)){case "literal":return [];case "list":return PE(e,t,r);case "if":return TE(n,t,r);case "aggregate":return kE(n,t);case "source":return [...ca(n,"source",t),...Bl(Gu(n).errors,t)];default:{let o=go(n),i=o?qn(t):In(t);return [{path:t,code:o?"unexpected_comparison":"invalid_value_expression",message:i.message.slice(t.length+2)}]}}},pi=e=>Ye(ua(e,"$",false)),ma=e=>Xr(pi(e),"Invalid value expression");var CE=(e,t,r)=>e.value!==void 0?fa(e.value,`${r}.value`):typeof e.bind=="string"?Y(r,"untyped_binding",`{ bind: '${e.bind}' } has no type until it is bound`):eg(oa(t,`the path '${String(e.path)}'`),e.path,r),LE=(e,t,r,n)=>{let o=ga(e.then,t,`${r}.then`,n);return e.else===void 0?n?o:aa(o,sa,r):aa(o,ga(e.else,t,`${r}.else`,n),r)},ME=(e,t,r)=>{let n=la(Ir(e).map((o,i)=>{let s=`${r}[${i}]`,a=ga(o,t,s,true);return a.isList&&Y(s,"nested_list","a list's items are single values"),a}),r);return pa(e)&&n.kind===P.Json&&Y(`${r}.distinct`,"distinct_over_json","distinct drops repeated values, not Json"),n},ga=(e,t,r,n)=>{switch(yr(e)){case "literal":return fa(e,r);case "source":return CE(e,t,r);case "aggregate":return Xm(t,e,r);case "if":return LE(e,t,r,n);case "list":return ME(e,t,r);default:return Y(r,"invalid_value_expression",In(r).message)}},ya=(e,t)=>(ma(e),ga(e,t,"$",false));var rg=(e,t)=>{let r=pi(e).errors;if(r.length>0)return {type:null,paths:[],clockUnit:null,errors:r};let n=Vr(e),o=[...$r(n,t).errors],i=null;try{i=ya(e,t);}catch(a){if(!(a instanceof si))throw a;o.push(a.issue);}let s=null;try{s=Vo(n);}catch(a){o.push({path:"$",code:"clock_unit_below_floor",message:a.message});}return {type:i,paths:_e(n).sort(),clockUnit:s,errors:o}};var _E=15,DE=e=>e.replace(/^[-+]/,"").replace(/e.*$/i,"").replace(".","").replace(/^0+/,"").replace(/0+$/,"").length,Wl=e=>{let t=String(e),r=Number(t);if(!Number.isFinite(r))return e;if(DE(t)>_E)throw new RangeError(`${t} has more digits than a number holds exactly; json-rules reads a coerced Decimal as a number.`);return r},ng=(e,t)=>r=>{if(e===void 0)return r;if(e==="String"){if(r instanceof Date)return r.toISOString();if(typeof r=="object"&&r!==null)return String(r)}let o=(X.includes(e)||e==="DateTime")&&typeof r=="bigint"?qr(r):X.includes(e)&&typeof r=="object"&&r!==null&&!(r instanceof Date)?Wl(r):r,i=Ht(o,e,t);return e==="DateTime"&&typeof i=="number"?new Date(i):i};var FE=(e,t)=>{if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return {value:e,key:e,kind:"number"};if(e instanceof Date&&!Number.isNaN(e.getTime()))return {value:e,key:e.getTime(),kind:"date"};if(typeof e=="object"&&e!==null){let r=Wl(e);if(typeof r=="number")return {value:e,key:r,kind:"number"}}throw new Error(`${t} must be a finite number or a valid date for min / max`)},jE=(e,t,r)=>{if(e.length===0)return null;let n=new Set(e.map(o=>o.kind));if(n.size>1)throw new Error(`${r} ${t} orders one kind of value, not ${[...n].join(" and ")}`);return e.reduce((o,i)=>(t==="max"?i.key>o.key:i.key<o.key)?i:o).value},og=(e,t,r)=>{if(go(e))throw qn(r);if(!re(e.aggregate))throw new Error(`${r}.aggregate must be an object`);let{mode:n,field:o}=e.aggregate;if(!Ji(n))throw ss(n);if(typeof e.field!="string"||e.field==="")throw new Error(`${r}.field: an aggregate value reads a list field`);let i=Ga(e,t),s=e.coerceType==="DateTime"?zt(t,l=>qe(l,t.scopes,t.bindings)).timeZone:Ie,a=ng(e.coerceType,s);switch(n){case "count":return o===void 0?i.length:eo(i,e.field,o,()=>true).length;case "sum":return ws(n,i,e.field,o);case "avg":return eo(i,e.field,o,()=>true).length===0?null:ws(n,i,e.field,o);case "distinct":return da(eo(i,e.field,o,a),oe(e.caseInsensitive));default:return jE(eo(i,e.field,o,(l,d)=>FE(a(l),d)),n,e.field)}};var ig=(e,t,r)=>{if(e.if===void 0||e.then===void 0)throw new Error(`${r}: if / then takes both an if and a then`);return Ru(e.if,t)?{expr:e.then,path:`${r}.then`}:e.else===void 0?void 0:{expr:e.else,path:`${r}.else`}},VE=(e,t,r)=>{let n=ig(e,t,r);return n===void 0?null:ha(n.expr,t,n.path)},IE=(e,t,r)=>{if(!Array.isArray(e)&&!Array.isArray(e.list))throw new Error(`${r}.list must be an array`);let n=Ir(e).flatMap((o,i)=>{let s=`${r}[${i}]`,a=yr(o);if(a==="list")throw new Error(`${s}: a list's items are single values`);if(a!=="if")return [ha(o,t,s)];let l=ig(o,t,s);return l===void 0?[]:[ha(l.expr,t,l.path)]});return pa(e)?da(n):n},ha=(e,t,r)=>{switch(yr(e)){case "literal":return e;case "source":return qe(e,t.scopes,t.bindings);case "aggregate":return og(e,t,r);case "if":return VE(e,t,r);case "list":return IE(e,t,r);default:throw go(e)?qn(r):In(r)}},sg=(e,t,r={})=>ha(e,{...r,scopes:[t]},"$");var ag=e=>Vo(Vr(e));/*! Bundled license information:
3
+ `)}`)},$r=(e,t={})=>{let r=el(t);return Yt(e,"$",r,1),t.positive&&KO(e,r),Ye(r.errors)},el=(e={})=>({target:e.target??"check",errors:[],map:Pe(e.map,e.mapName,"toPrisma"),scopeModels:[e.model],stepScopes:[false]}),Zu=e=>{let t=el(),r=at(e)?nc(e,"$",t,1):null;r&&!Yi(r.mode)&&$(t,"$.aggregate.mode","invalid_aggregate_mode",ps(r.mode).message);let n=at(e)?e:{},o=r?.mode;return n.coerceType!==void 0&&(Ao(n.coerceType)?["distinct","min","max"].includes(o)||$(t,"$.coerceType","unexpected_coerce_type","coerceType reads the values distinct, min and max return"):$(t,"$.coerceType","invalid_coerce_type",`coerceType must be one of: ${Object.keys(P).join(", ")}`)),n.caseInsensitive!==void 0&&(typeof n.caseInsensitive!="boolean"?$(t,"$.caseInsensitive","invalid_case_insensitive","caseInsensitive must be a boolean"):o!=="distinct"&&$(t,"$.caseInsensitive","unexpected_case_insensitive","caseInsensitive folds the strings distinct returns")),Ye(t.errors)},Yu=e=>{let t=el();return at(e)&&Xr(e,"$",t,1),Ye(t.errors)},UO=["if","array","aggregate"],KO=(e,t)=>H(e,r=>{let n=le(r),o=r.operator??r.dateOperator;return (n&&UO.includes(n)||typeof o=="string"&&es.includes(o))&&$(t,"$","notPositive",`${n==="field"||n==="date"?o:n} can hold on a missing value`),false}),GO=(e,t={})=>{en($r(e,t),"validateRule");},Yt=(e,t,r,n)=>{if(typeof e=="boolean")return;if(!at(e)){$(r,t,"invalid_condition","Condition must be a boolean or object");return}let o=le(e);if(!o){$(r,t,"ambiguous_condition",Et().message);return}switch(o){case "all":Hu(e.all,`${t}.all`,r,n);break;case "any":Hu(e.any,`${t}.any`,r,n);break;case "if":Yt(e.if,`${t}.if`,r,n),Yt(e.then,`${t}.then`,r,n),"else"in e&&e.else!==void 0&&Yt(e.else,`${t}.else`,r,n);break;case "field":zO(e,t,r,n);break;case "aggregate":QO(e,t,r,n);break;case "array":ZO(e,t,r,n);break;case "date":YO(e,t,r,n);break}},Hu=(e,t,r,n)=>{if(!Array.isArray(e)){$(r,t,"logical_array_required","Logical operator requires an array of conditions");return}e.forEach((o,i)=>{Yt(o,`${t}[${i}]`,r,n);});},Cs=(e,t,r,n)=>{typeof e.field=="string"&&Xu(e.field,"field",`${t}.field`,r,n);},Xu=(e,t,r,n,o,i=false)=>{let s=M(e)??(t==="path"?{depth:o}:null);if(!s)return;let a=t==="field"?"Field":"Path";s.depth>o&&$(n,r,"scope_out_of_bounds",ka(e,s.depth,o)),n.target==="toPrisma"&&!i?$(n,r,`unsupported_prisma_${t}`,t==="path"?`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check()`:`${a} '${e}' is not supported by toPrisma()`):n.target==="toSql"&&(t==="field"||s.depth>1)&&$(n,r,`unsupported_sql_${t}`,`${a} '${e}' is not supported by toSql()`);},Ts=(e,t,r,n=false)=>{e.stepScopes[t]=n||e.stepScopes[t-1]===true;let o=e.scopeModels[t-1];e.scopeModels[t]=e.map&&o&&typeof r=="string"?Uo(r,e.map,o)??void 0:void 0;},Xr=(e,t,r,n,o=false)=>{let i=tu.filter(a=>e[a]!==void 0);if(i.length>1)return $(r,t,"ambiguous_value_source","Takes one of value, path or bind"),null;if(i.length===0)return $(r,t,"missing_value_source","Requires value, path or bind"),null;let[s]=i;return s!=="value"&&(typeof e[s]!="string"||e[s]==="")?($(r,`${t}.${s}`,"invalid_value_source",`${s} is a non-empty string`),null):(e.bindOptional!==void 0&&(s!=="bind"||typeof e.bindOptional!="boolean")&&$(r,`${t}.bindOptional`,"invalid_value_source","bindOptional is a boolean beside bind"),s==="path"&&Xu(e.path,"path",`${t}.path`,r,n,o),s)},ec=(e,t,r,n,o,i)=>{let{offset:s}=e;if(s===void 0)return;let a=`${n}.offset`;if(!Fd.includes(r)){$(o,a,"unsupported_offset_operator",`Operator '${r}' has no comparison point to offset`);return}if(!at(s)){$(o,a,"invalid_offset","An offset is one of { value }, { path } or { bind }");return}let l=Xr(s,a,o,i);if(l==="path"){let d=s.path,u=jr(s);t==="date"&&u&&u.depth<=1&&o.target==="toSql"&&$(o,`${a}.path`,"unsupported_sql_path",`A row path on a date offset ('${d}') is not supported by toSql()`);return}if(l!=="value")return;let f=s.value;if(t==="field"){(typeof f!="number"||!Number.isFinite(f))&&$(o,`${a}.value`,"invalid_offset","A field offset value is a number");return}let p=at(f)&&Object.keys(f).length===1&&ee(f)?Re(f):null;if(!p){$(o,`${a}.value`,"invalid_offset","A date offset value is { ago } or { ahead }");return}oc(p[0],`${a}.value.${Object.keys(f)[0]}`,o,i);},tc=(e,t,r,n)=>{n.target!=="toSql"||!He.includes(t)||jr(e)&&$(n,`${r}.path`,"unsupported_sql_path",`A range read from the row ('${e.path}') is not supported by toSql()`);},zO=(e,t,r,n)=>{if(typeof e.field!="string"&&$(r,`${t}.field`,"field_required","Field rule requires a string field"),Cs(e,t,r,n),typeof e.operator!="string"||!Wt(e.operator,"field")){$(r,`${t}.operator`,"invalid_operator",de(e.operator,"field").message);return}let o=e.operator;ec(e,"field",o,t,r,n),Qi(o,"field",r.target)||$(r,`${t}.operator`,`unsupported_${Ls(r.target)}_operator`,`Operator '${o}' is not supported by ${r.target}()`),e.coerceType!==void 0&&!Ao(e.coerceType)&&$(r,`${t}.coerceType`,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(P).join(", ")}`);let i=Kt(o,"field");if(i==="none"){XO(e,t,r);return}if(Xr(e,t,r,n,true)!==null){if(tc(e,o,t,r),r.target==="toPrisma"&&typeof e.path=="string"){let s=Ns(e,r.map,r.scopeModels[n-1],n>1,r.stepScopes[n-1]===true);"problem"in s&&$(r,`${t}.path`,"unsupported_prisma_path",As(e.path,s.problem).message);}if(r.target==="toSql"&&typeof e.path=="string"&&r.map){let s=r.scopeModels[n-1],a=(M(e.path)??{path:e.path}).path,l=no(te(e.field,r.map,s),te(a,r.map,s),o);l&&$(r,`${t}.path`,"unsupported_sql_path",`'${e.path}': ${l}`);}r.target==="toSql"&&typeof e.path=="string"&&["array","pattern","string"].includes(i)&&((r.map?te(e.field,r.map,r.scopeModels[n-1]):void 0)?.isList&&Rt.includes(o)||$(r,`${t}.path`,"unsupported_sql_path",`'${o}' against the column '${e.path}' has no SQL form`)),!(typeof e.path=="string"||typeof e.bind=="string")&&(HO(e,o,t,r,n),JO(i,e.value,o,`${t}.value`,r));}},HO=(e,t,r,n,o)=>{if(n.target!=="toPrisma"||!n.map||typeof e.field!="string")return;let i=te(e.field,n.map,n.scopeModels[o-1]);if(!i)return;let s=e.value,a=oe(e.caseInsensitive),l=dr.includes(t)&&Array.isArray(s),f=p=>$(n,`${r}.value`,"unsupported_prisma_operator",V("toPrisma",p).message);i.isList&&!l&&Array.isArray(s)&&s.includes(null)?f(`A list holding null in '${e.field}'`):i.isList&&!l&&a&&xr("text",s)?f(`A case-insensitive comparison on the list '${e.field}'`):Ue(i)&&a&&f(`A case-insensitive comparison on the Json column '${e.field}'`);},JO=(e,t,r,n,o)=>{switch(e){case "scalar":case "string":e==="string"&&typeof t!="string"&&$(o,n,"invalid_string_value",`Operator '${r}' requires a string value`);return;case "ordered":ye(t)||$(o,n,"invalid_ordered_value",`Operator '${r}' requires a string, number, or Date value`);return;case "array":Array.isArray(t)||$(o,n,"invalid_membership_value",`Operator '${r}' requires an array value`);return;case "pattern":{if(!(typeof t=="string"||t instanceof RegExp)){$(o,n,"invalid_pattern_value",`Operator '${r}' requires a string or RegExp value`);return}let i=yu(t,o.target);i&&$(o,n,"unsupported_pattern",i);return}case "range":try{Zn(t,r);}catch(i){$(o,n,"invalid_range_value",i.message);}return}},rc=(e,t,r,n,o)=>{let i=r.scopeModels[n-1];if(!(r.target!=="toPrisma"||!r.map||!i||typeof e.field!="string"))try{so(e.field,r.map,i,o);}catch(s){$(r,`${t}.field`,"unsupported_prisma_relation",s.message);}},nc=(e,t,r,n)=>{if(rc(e,t,r,n,"Aggregate rules"),e.offset!==void 0&&$(r,`${t}.offset`,"unexpected_offset","Aggregate rules take no offset"),ic(e,t,r,n),typeof e.field!="string"&&$(r,`${t}.field`,"field_required","Aggregate rule requires a string field"),Cs(e,t,r,n),!at(e.aggregate))return $(r,`${t}.aggregate`,"invalid_aggregate","aggregate must be an object"),null;let o=e.aggregate;return "field"in o&&o.field!==void 0&&typeof o.field!="string"&&$(r,`${t}.aggregate.field`,"invalid_aggregate_field","aggregate.field must be a string"),"condition"in e&&e.condition!==void 0&&(r.target==="toSql"&&$(r,`${t}.condition`,"unsupported_sql_aggregate_condition","Aggregate condition filtering is not supported by toSql(); use check() or toPrisma()"),Ts(r,n,e.field,true),Yt(e.condition,`${t}.condition`,r,n+1)),o},QO=(e,t,r,n)=>{let o=nc(e,t,r,n);if(!o)return;if(Ot.includes(o.mode)||$(r,`${t}.aggregate.mode`,"invalid_aggregate_mode",cr(o.mode).message),!Zi.includes(e.operator)){$(r,`${t}.operator`,"invalid_aggregate_operator",`Aggregate rules only support: ${Zi.join(", ")}`);return}if(r.target==="toPrisma"&&typeof e.path=="string"&&$(r,`${t}.path`,"unsupported_prisma_aggregate_path","path is not supported by toPrisma() for aggregate rules; use value instead"),Xr(e,t,r,n)===null||typeof e.path=="string"||typeof e.bind=="string")return;let i=e.value;He.includes(e.operator)?ex(i)||$(r,`${t}.value`,"invalid_range_value",`Operator '${e.operator}' requires a two-item numeric range`):typeof i!="number"&&$(r,`${t}.value`,"invalid_aggregate_value","Aggregate rule value must be a number");},ZO=(e,t,r,n)=>{if(typeof e.field!="string"&&r.target!=="check"&&$(r,`${t}.field`,"field_required","Array rule requires a string field for this target"),Cs(e,t,r,n),ic(e,t,r,n),typeof e.arrayOperator!="string"||!Wt(e.arrayOperator,"array")){$(r,`${t}.arrayOperator`,"invalid_array_operator",de(e.arrayOperator,"array").message);return}let o=e.arrayOperator;To(e)&&rc(e,t,r,n,"Count operators");let i=r.target==="toPrisma"&&r.map&&typeof e.field=="string"?te(e.field,r.map,r.scopeModels[n-1]):void 0;i&&!L(i)&&o!=="empty"&&o!=="notEmpty"&&$(r,`${t}.arrayOperator`,"unsupported_prisma_array_operator",V("toPrisma",`'${o}' over the array column '${e.field}'`).message),Qi(o,"array",r.target)||$(r,`${t}.arrayOperator`,`unsupported_${Ls(r.target)}_array_operator`,`Array operator '${o}' is not supported by ${r.target}()`);let s=Kt(o,"array"),a=e.condition!==void 0,l=()=>{e.count!==void 0&&$(r,`${t}.count`,"unexpected_count",`Array operator '${o}' does not accept count`);};s==="none"?(a&&$(r,`${t}.condition`,"unexpected_condition",`Array operator '${o}' does not accept condition`),l()):s==="predicate"?(a?(Ts(r,n,e.field),Yt(e.condition,`${t}.condition`,r,n+1)):$(r,`${t}.condition`,"missing_condition",Ie(o).message),l()):s==="count"&&(typeof e.count!="number"?$(r,`${t}.count`,"missing_count",qn(o).message):e.count!==void 0&&!(typeof e.count=="number"&&Number.isInteger(e.count)&&e.count>=0)&&$(r,`${t}.count`,"invalid_count","count must be a non-negative whole number"),a?(Ts(r,n,e.field,To(e)),Yt(e.condition,`${t}.condition`,r,n+1)):$(r,`${t}.condition`,"missing_condition",Ie(o).message));},YO=(e,t,r,n)=>{if(typeof e.field!="string"&&$(r,`${t}.field`,"field_required","Date rule requires a string field"),Cs(e,t,r,n),typeof e.dateOperator!="string"||!Wt(e.dateOperator,"date")){$(r,`${t}.dateOperator`,"invalid_date_operator",de(e.dateOperator,"date").message);return}let o=e.dateOperator;ec(e,"date",o,t,r,n);let i=zt(e.value,Ga(e.offset));i&&$(r,t,"clock_unit_below_floor",i.message),Qi(o,"date",r.target)||$(r,`${t}.dateOperator`,`unsupported_${Ls(r.target)}_date_operator`,`Date operator '${o}' is not supported by ${r.target}()`);let s=Kt(o,"date");if(s==="dayList"){if(Xr(e,t,r,n)!=="value")return;let a=e.value;(!Array.isArray(a)||!a.every(l=>typeof l=="string"&&Qd(l)))&&$(r,`${t}.value`,"invalid_day_list",`Date operator '${o}' requires an array of day names (${In.join(", ")})`);return}if(Xr(e,t,r,n)!==null&&(tc(e,o,t,r),!(typeof e.path=="string"||typeof e.bind=="string"))){if(ee(e.value)){Qu(e.value,o,`${t}.value`,r,n);return}if(Po.includes(o)){$(r,`${t}.value`,"invalid_date_range",tt(o).message);return}if(s==="dateRange"){if(!tx(e.value)){$(r,`${t}.value`,"invalid_date_range",`Date operator '${o}' requires a two-item date range`);return}e.value.forEach((a,l)=>{ee(a)?Qu(a,o,`${t}.value[${l}]`,r,n):ye(a)&&!wr(a,qe).isValid()&&$(r,`${t}.value[${l}]`,"invalid_date_value",`Date operator '${o}' value '${String(a)}' does not parse as a date`);});return}if(!ye(e.value)){$(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' requires a date-like value`);return}wr(e.value,qe).isValid()||$(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' value '${String(e.value)}' does not parse as a date`);}},oc=(e,t,r,n)=>{if(!at(e)||Object.keys(e).length===0){$(r,t,"invalid_relative_units","Relative offset requires at least one unit");return}for(let[o,i]of Object.entries(e)){if(!Vn(o)){$(r,`${t}.${o}`,"invalid_relative_unit",`Unknown relative unit '${o}'`);continue}let s=at(i)?Xr(i,`${t}.${o}`,r,n):"literal";if(s===null||s==="path"||s==="bind")continue;let a=s==="value"?i.value:i,l=Ua(a,o);l&&$(r,`${t}.${o}`,"invalid_relative_magnitude",l);}},Ju=(e,t,r)=>{(typeof e!="string"||!ns.includes(e))&&$(r,t,"invalid_period_unit",`Unknown period unit '${String(e)}'`);},Qu=(e,t,r,n,o)=>{let i=Po.includes(t),s=Re(e);if(s){oc(s[0],r,n,o);return}if(_o(e)){Ju(Gn(e),r,n);return}if(Do(e)){if(i){$(n,r,"invalid_date_range",tt(t).message);return}let a="start"in e?e.start:e.end;if(!at(a)||!_o(a)){$(n,r,"invalid_period_unit","start/end requires a this/last/next period");return}Ju(Gn(a),r,n);return}$(n,r,"invalid_date_expression","Unrecognized date expression");},XO=(e,t,r)=>{"value"in e&&e.value!==void 0&&$(r,`${t}.value`,"unexpected_value","Rule does not accept value"),"path"in e&&e.path!==void 0&&$(r,`${t}.path`,"unexpected_path","Rule does not accept path"),"bind"in e&&e.bind!==void 0&&$(r,`${t}.bind`,"unexpected_bind","Rule does not accept bind");},Ls=e=>e==="toPrisma"?"prisma":e==="toSql"?"sql":"check",at=e=>re(e),ex=e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="number"&&typeof e[1]=="number",tx=e=>Array.isArray(e)&&e.length===2&&(ye(e[0])||ee(e[0]))&&(ye(e[1])||ee(e[1])),ic=(e,t,r,n)=>{if(Ae(e)&&r.target!=="check"&&(r.target==="toPrisma"&&to(e)!==null||$(r,t,`unsupported_${Ls(r.target)}_window`,$t(r.target).message)),"filter"in e&&e.filter!==void 0&&(Ts(r,n,e.field),Yt(e.filter,`${t}.filter`,r,n+1)),"orderBy"in e&&e.orderBy!==void 0){let i=e.orderBy;Array.isArray(i)?i.forEach((s,a)=>{(!at(s)||typeof s.field!="string"||s.dir!=="asc"&&s.dir!=="desc")&&$(r,`${t}.orderBy[${a}]`,"invalid_order_by",'orderBy entries must be { field: string, dir: "asc" | "desc" }');}):$(r,`${t}.orderBy`,"invalid_order_by","orderBy must be an array of { field, dir }");}for(let i of ["take","skip"])if(i in e&&e[i]!==void 0){let s=e[i];(typeof s!="number"||!Number.isInteger(s)||s<0)&&$(r,`${t}.${i}`,`invalid_window_${i}`,`${i} must be a non-negative integer`);}},$=(e,t,r,n)=>{e.errors.push({path:t,code:r,message:n});};var rx=/[.:]/,tl=e=>{let t=[];for(let[r,n]of Object.entries(e.maps))for(let[o,i]of Object.entries(n.models))for(let[s,a]of Object.entries(i.fields))a.kind!=="bridge"&&rx.test(s)&&t.push({path:`${Me({fieldMap:r,model:o})}.${s}`,message:"contains forbidden character . or :",code:"invalid_field_name"});return Ye(t)},sc=e=>en(tl(e),"validateFieldMaps");var lt=e=>!Object.hasOwn(e,"parent"),kt=e=>{let t=[],r=new Set,n=e;for(;!lt(n);){if(r.has(n))throw new Error("cycle detected in narrowing parent chain");if(Object.hasOwn(n,"model")||Object.hasOwn(n,"maps"))throw new Error("a narrowing carries a base lens key (model / maps); it has a parent instead");r.add(n),t.unshift(n),n=n.parent;}return t},pt=e=>lt(e)?e:kt(e)[0].parent;var rl=(e,t)=>t.length?U([...t,e]):e,nx=e=>{if(yr(e).length)return false;let t=e.field,r=typeof t=="string"?M(t):null;try{return he(r?{...e,field:r.path}:e,{})===!0}catch{return false}},nl=(e,t)=>{if(!t.length)return e;if(!nx(e))return U([...t.flatMap(o=>o.clamps),e]);let[r,...n]=t;return Gt([U([...r.clamps,nl(e,n)]),U([{field:r.prefix,operator:"notExists"},e])])},lo=(e,t,{paths:r=false}={})=>gr(e,{rewrite:n=>{if(We(n))return n;if(typeof n.field!="string"||n.field==="")throw new k(`narrowRule: cannot re-root a relation clamp of unknown shape under '${t}'`,"unsupported_clamp");let o=yr(n),i=o.find(a=>M(a));if(r&&i)throw new k(`prefixConditionFields: cannot re-root a scope ref ('${i}') under '${t}'`,"unsupported_clamp");if(o.length&&!r)throw new k(`narrowRule: cannot re-root a relation clamp with a path reference ('${o[0]}') under '${t}'. Author the clamp without 'path', or anchor it at the relation itself.`,"unsupported_clamp");if(M(n.field))throw new k(`narrowRule: cannot re-root a relation clamp with a scope ref field ('${n.field}') under '${t}'. Author the clamp against the model's own columns.`,"unsupported_clamp");if(xe(n)){for(let a of [n.condition,n.filter])if(a!==void 0&&ao(a).escaping!==null)throw new k(`narrowRule: cannot re-root a relation clamp on '${n.field}' under '${t}': '${ao(a).escaping}' inside it reads the row being re-rooted. Anchor such clamps at the relation's own model.`,"unsupported_clamp")}return {...r?Jn(n,a=>Oe(a)?{...a,path:`${t}.${a.path}`}:a):n,field:`${t}.${n.field}`}},below:()=>false}),ol=(e,t)=>t.flatMap(r=>{let n=j(e,r.map,r.model,r.relPath);if(n.whereClauses.length===0)return [];if(r.isList)throw new k(`narrowRule: cannot enforce a to-many relation clamp on '${r.prefix}' without an arrayOperator condition to anchor it (row-scoped). Traverse '${r.prefix}' via an array operator (any/all/none/...) so the clamp can be injected safely.`,"unsupported_clamp");return [{prefix:r.prefix,clamps:n.whereClauses.map(o=>lo(o,r.prefix))}]}),ac=(e,t)=>ol(e,t).flatMap(r=>r.clamps),pc=(e,t,r)=>{let n=ze(e,r);if("outOfBounds"in n)throw new k(`narrowRule: ${n.outOfBounds}`,"scope_out_of_bounds");if(!n.scope)return {hops:[],end:null};let o=e.slice(0,e.length-n.path.length);return Te(t.lens.maps,n.scope,n.path,o==="$."?"":o)},ox=(e,t,r)=>{if(M(e))return pc(e,t,r).hops;let n=r.length===1?"":`${"$".repeat(r.length)}.`;return r[0]?Te(t.lens.maps,r[0],e,n).hops:[]},lc=(e,t,r)=>{if(We(e)||typeof e.field!="string"||e.field==="")return null;let{hops:n,end:o}=pc(e.field,t,r);return {hops:n,below:o}},tn=(e,t,r)=>gr(e,{below:(n,o)=>{let i=lc(n,t,o);return i?i.below?[...o,i.below]:xe(n)?[...o,null]:false:false},after:(n,o)=>{let i=lc(n,t,o);if(!i)return n;let s=ac(t,yr(n).flatMap(d=>ox(d,t,o))),a=i.below;if(!a||!xe(n))return rl(nl(n,ol(t,i.hops)),s);let l=[...j(t,a.mapName,a.modelName,a.relPath).whereClauses,...ac(t,Qn(n).flatMap(d=>Te(t.lens.maps,a,d).hops))],f=n.condition===void 0||n.arrayOperator===x.all||Ae(n),p={...n};return l.length&&f?p.filter=U([...n.filter!==void 0?[n.filter]:[],...l]):l.length&&(p.condition=U([...l,n.condition])),rl(nl(p,ol(t,i.hops.slice(0,-1))),s)}},[r]),po=(e,t)=>{let r=D(t),n=j(r,r.lens.mapName,r.lens.model,[]),o=tn(e,r,{mapName:r.lens.mapName,modelName:r.lens.model,relPath:[]});return rl(o,n.whereClauses)};var il=(e,t)=>{let r=Jt(e,P.DateTime,t);return typeof r=="number"&&!Number.isNaN(new Date(r).getTime())?r:void 0},ix=(e,t,r)=>n=>{if(n==null)return n;let o=il(n,r);if(o===void 0)throw new Error(`Invalid date value for DateTime field '${e}': ${String(n)}`);return t==="toPrisma"?new Date(o):new Date(o).toISOString()},fo=(e,t,r,n,o)=>{if(t==null||r?.kind==="json-path")return t;let i=r?.kind==="direct"?r.entry:void 0;if(i?.isList)return t;let s=i?Ge(i):void 0;if(e.coerceType!==void 0&&s!==void 0&&e.coerceType!==s)throw new Error(`coerceType '${e.coerceType}' overrides ${s} field '${e.field}', but ${n} compares the column as stored \u2014 evaluate it in memory with check(), or drop the override.`);if((s??e.coerceType)===P.DateTime){let l=ix(e.field,n,o());return Array.isArray(t)?t.map(l):l(t)}if(e.coerceType===void 0&&s===P.String&&(Array.isArray(t)?t:[t]).some(l=>typeof l=="number"||typeof l=="boolean"))throw new Error(`'${e.field}' is String but the literal is not a string; pass a string, or stamp coerceType: 'String'.`);if(e.coerceType===void 0&&s!==void 0&&(X.includes(s)||s===P.Boolean)&&(Array.isArray(t)?t:[t]).some(l=>typeof l=="string"))throw new Error(`'${e.field}' is ${s} but the literal is a string; pass a ${s===P.Boolean?"boolean":"number"}, or stamp coerceType: '${s}'.`);return e.coerceType!==void 0&&Gd.includes(e.coerceType)?Jt(t,e.coerceType,e.coerceType===P.DateTime?o():void 0):t};var fc=e=>Array.isArray(e)?e.flatMap(fc):[e],Go=e=>e.value===void 0?null:fc(e.value),sx=e=>il(e)!==void 0,ax=/^-?\d+(\.\d+)?$/,lx={String:{expected:"a string",fits:e=>typeof e=="string"},Enum:{expected:"a string",fits:e=>typeof e=="string"},Int:{expected:"an integer",fits:Number.isSafeInteger},BigInt:{expected:"an integer",fits:Number.isSafeInteger},Float:{expected:"a number",fits:Number.isFinite},Decimal:{expected:"a number or a numeric string",fits:e=>Number.isFinite(e)||typeof e=="string"&&ax.test(e)},Boolean:{expected:"a boolean",fits:e=>typeof e=="boolean"},DateTime:{expected:"a date",fits:sx},Json:{expected:"a value",fits:()=>true},Bytes:{expected:"a value",fits:()=>true}},px=e=>typeof e=="string"?`'${e}'`:typeof e=="object"&&e!==null?JSON.stringify(e):String(e),Ms=(e,t)=>{let r="coerceType"in e?e.coerceType:void 0,n=r??t;if(n===void 0||n===P.Json)return [];let o="operator"in e?e.operator:e.dateOperator,i=Dn(e);if(!i)return [];let a=r!==void 0&&r!==t?`field '${e.field}' coerced to ${n}`:`${n} field '${e.field}'`;if(!i.kinds.includes(n))return [{path:e.field,code:"operator_kind_mismatch",message:`operator '${o}' does not apply to ${a} (applies to: ${i.kinds.join(", ")})`}];if(e.offset!==void 0&&!("dateOperator"in e?n===P.DateTime:X.includes(n)))return [{path:e.field,code:"invalid_offset",message:`an offset does not apply to ${a}`}];if("dateOperator"in e||i.valueShape==="none"||i.valueShape==="pattern")return [];if(zd.includes(i.valueShape)&&Array.isArray(e.value))return [{path:e.field,code:"invalid_value_shape",message:`operator '${o}' compares one value, but ${a} was given a list`}];let{expected:l,fits:f}=lx[n],p=u=>{try{return f(Jt(u,n))}catch{return false}},d=u=>f(u)||r!==void 0&&p(u);return (Go(e)??[]).filter(u=>u!==null&&!d(u)).map(u=>({path:e.field,code:"invalid_value",message:`value ${px(u)} does not fit ${a} (expected ${l})`}))},dc=(e,t,r)=>{if(r.isList===true||Ue(r))return null;let n=L(r)?`arrayOperator '${t}' needs a list, but '${e}' is a to-one relation \u2014 a single related record; address its fields directly (e.g. '${e}.<field>')`:`arrayOperator '${t}' needs a list, but '${e}' is a single ${Ge(r)??r.type} value`;return {path:e,code:"invalid_array_operator",message:n}};var fx=(e,t,r,n)=>H(e,(o,i)=>{let s=le(o);if(s===null)return n.push({path:typeof o.field=="string"?o.field:"",code:"ambiguous_condition",message:Et().message}),false;if(We(o))return;let a=o,l=w=>{let R=ze(w,i);return "outOfBounds"in R?(n.push({path:w,code:"scope_out_of_bounds",message:R.outOfBounds}),null):{scope:R.scope,field:R.path}},f=i[i.length-1],p=true,d=null;if("field"in a&&typeof a.field=="string"&&a.field!==""){let w=co(t,i,a.field);"issue"in w?(n.push({path:a.field,...w.issue}),p=false):{next:f,walked:d}=w;}let u=d?.entry??null,m=d?.terminalFieldName??null,y=d?.entry.kind==="enum",c=d?.entry.type??null,g=d&&d.jsonSubPath.length===0?Ds(d.terminalEffect,d.terminalFieldName):null;for(let{ref:w,role:R}of Vo(a)){let b=M(w)?l(w):{scope:Tt(t),field:w};if(!b||b.scope.open)continue;let S=uo(t,b.scope,b.field);if(!S){n.push({path:w,..._s(t,b.scope,b.field,R==="value"?"path (comparison ref) does not resolve through the narrowed lens":"offset or magnitude ref does not resolve through the narrowed lens")});continue}if(L(S.entry)){n.push({path:w,code:"not_in_lens",message:"a value ref reads a column, not a relation"});continue}let v=Ge(S.entry);if(R==="value"||R==="shift"||v===void 0)continue;(R==="whole"?Ud.includes(v):X.includes(v))||n.push({path:w,code:"not_in_lens",message:`${R==="whole"?"a calendar unit reads a whole number":"an offset or magnitude reads a number"}, not ${v}`});}if(!p)return false;if("arrayOperator"in a&&typeof a.field=="string"&&u){let w=dc(a.field,a.arrayOperator,u);if(w)return n.push(w),false}if(u&&L(u)&&(s==="field"||s==="date")&&(u.isList||!Qt(a))){let w=a.field;return n.push({path:w,code:"operator_kind_mismatch",message:(u.isList?ss(w):ur(w)).message}),false}if(!u?.isList&&(s==="field"||s==="date")&&n.push(...Ms(a,u?Ge(u):void 0)),!f.open)for(let w of Qn(a))w!==""&&!uo(t,f,w)&&n.push({path:w,..._s(t,f,w,"an orderBy or aggregate field does not resolve through the narrowed lens")});if(g&&"operator"in a&&m){let w=Go(a);if(w){let R=new Set(g),b=y?`enum '${c}'`:`field '${m}'`;for(let S of w)typeof S=="string"&&!R.has(S)&&n.push({path:m,code:"value_not_allowed",message:`value '${S}' is not in the allowed set for ${b} (allowed: ${[...R].join(", ")})`});}}return [...i,f]},[r]),zo=(e,t,r,n,o)=>{let i=[];return fx(e,t,{mapName:r,modelName:n,relPath:o,open:false},i),i},vr=(e,t)=>{let r=D(t);try{let n=zo(e,r,r.lens.mapName,r.lens.model,[]);return n.length===0&&po(e,t),Ye(n)}catch(n){if(!(n instanceof k))throw n;return Ye([{path:"",code:n.code,message:n.message}])}};var Qo=e=>e===void 0?void 0:Array.isArray(e)?e:[e],Zo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&("where"in e||"label"in e||"groupBy"in e||"from"in e),Nr=e=>{if(Zo(e))return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===0)throw dx();return {where:e}},dx=()=>new k("sources: {} is not a Condition \u2014 use `true` for an unconstrained source","invalid_source"),ll=["__offpath__"],uc=new WeakMap,ux=(e,t)=>{if(!t)return new Map;let r=JSON.stringify([Ho(t.parent),Ho(e.maps),e.mapName,e.model,t.mapDefaults??null]),n=uc.get(t);if(n?.fingerprint===r)return n.trees;let o=new Map;return uc.set(t,{fingerprint:r,trees:o}),o},cc=new WeakMap,cx=0,Ho=e=>{let t=cc.get(e);return t===void 0&&(t=cx++,cc.set(e,t)),t},we="\0",mx=e=>{let t=Object.entries(e.fields);return {relations:new Set(t.filter(([,r])=>L(r)).map(([r])=>r)),gated:t.filter(([,r])=>r.options!==void 0||r.kind==="enum"||r.values!==void 0)}},Fs=e=>e?String(Ho(e)):"",D=e=>{let t=pt(e),r=lt(e)?[]:kt(e);return {lens:t,chain:r,origin:r[0],memo:{trees:ux(t,r[0]),vetted:new Set,effects:new Map,places:new Map,models:new Map,refs:new Map,compiles:new Map}}},js=(e,t)=>e===null?new Set(t):new Set(t.filter(r=>e.has(r))),gx=(e,t)=>{if(t.picks&&(e.picks=js(e.picks,t.picks)),t.omits)for(let r of t.omits)e.omits.add(r);},yc=(e,t,r)=>{e.set(t,js(e.get(t)??null,r));},hc=(e,t,r)=>{let n=e.get(t)??new Set;for(let o of r)n.add(o);e.set(t,n);},yx=(e,t,r)=>{if(r.enumPicks)for(let[n,o]of Object.entries(r.enumPicks))yc(e,n,o);if(r.enumOmits)for(let[n,o]of Object.entries(r.enumOmits))hc(t,n,o);},sl=(e,t,r)=>JSON.stringify([e,t,r]),hx=(e,t,r,n,o,i,s,a)=>{if(s&&gx(e,t),t.where!==void 0&&i&&(o(t.where),e.whereClauses.push(r(t.where)),(a?e.modelWheres:e.pathWheres).push({where:t.where,layer:n})),t.sources)for(let[l,f]of Object.entries(t.sources)){let p=Nr(f),d=e.sources.get(l)??[],u=e.sourceWheres.get(l)??[];p.where!==void 0&&i&&(o(p.where,true),d.push(r(p.where)),u.push(p.where)),e.sources.set(l,d),e.sourceWheres.set(l,u);let m=Qo(p.groupBy);for(let[y,c,g]of [["label",p.label,e.sourceLabels.get(l)],["groupBy",m,e.sourceGroupBys.get(l)]]){if(c===void 0)continue;let w=sl(l,y,c);g!==void 0&&sl(l,y,g)===w||e.sourceDeclaredAt.set(w,n);}p.label!==void 0&&e.sourceLabels.set(l,p.label),m!==void 0&&e.sourceGroupBys.set(l,m),p.from==="mapDefaults"&&!e.sourcesFromMapDefaults.has(l)&&e.sourcesFromMapDefaults.set(l,n);}},k=class extends Error{constructor(r,n){super(r);this.code=n;}code;name="LensRefusal"},pl=e=>new k(`a bare path ('${e}') reads the root row, which a clamp at a relation visit or a model default doesn't stand on: use a literal, a bind, or a \`$\` scope ref`,"invalid_value_source"),wx=(e,t,r)=>zo(e,t,r.mapName,r.modelName,r.relPath),bx=e=>new k(`a later layer's clamp reads what its parent does not show: '${e.path}' ${e.message}`,e.code),fl=e=>new k(`the scope ref '${e}' climbs out of the clamp: a clamp reads its own row ('$.'), literals and binds`,"scope_out_of_bounds"),ao=e=>{let t=null,r=null;return H(e,(n,o)=>{if(We(n))return;let i=yr(n);for(let s of [...typeof n.field=="string"?[n.field]:[],...i]){let a=M(s);r===null&&a&&a.depth>o&&(r=s);}for(let s of i)t===null&&!M(s)&&(t=s);return xe(n)?o+1:void 0},1),{bare:t,escaping:r}},al=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},n=[r];if(t.relPath.length>0)for(let i of Te(e.lens.maps,r,t.relPath.join(".")).hops)n.push({mapName:i.map,modelName:i.model,relPath:i.relPath});let o=n[n.length-1];return n.length===t.relPath.length+1&&o.mapName===t.mapName&&o.modelName===t.modelName?n:null},Jo=(e,t)=>{let r=e;for(let n of t)r=O(r?.relations,n);return r},dl=(e,t,r)=>{let n=i=>O(O(e.mapDefaults,i.mapName)?.models,i.modelName);if(!r){let i=n(t);return {defaults:i?[i]:[],path:void 0}}let o=[];for(let[i,s]of r.entries()){let a=Jo(n(s),t.relPath.slice(i));a&&o.push(a);}return {defaults:o,path:Jo(e.root,t.relPath)}},Sx=(e,t,r,n)=>{let o=Jo(t.root,r.relPath),i=[r.relPath.join(we),Object.keys(o?.relations??{}).join(we),(o?.omits??[]).join(we)].join(`${we}${we}`),s=n.get(i);if(s)return s;let a=new Map,l={lens:e},f=al(l,r)??[r],p=new Set(f.map(u=>`${u.mapName}:${u.modelName}`)),d=[{at:r,below:[]}];for(;d.length>0;){let{at:u,below:m}=d.shift(),y=T(O(e.maps,u.mapName),u.modelName)?.fields??{},{defaults:c,path:g}=dl(t,u,al(l,u)),w=new Set(c.flatMap(S=>Object.keys(S.relations??{}))),R=new Set([...c,...g?[g]:[]].flatMap(S=>S.omits??[])),b=[];for(let[S,v]of Object.entries(y)){if(!w.has(S)||R.has(S)||g?.relations!==void 0&&Object.hasOwn(g.relations,S))continue;let E=ot(v,u.mapName);if(!E||!T(O(e.maps,E.mapName),E.modelName))continue;let q=`${E.mapName}:${E.modelName}`;p.has(q)||(p.add(q),b.push(S),d.push({at:{...E,relPath:[...u.relPath,S]},below:[...m,S]}));}a.set(m.join("."),b);}return n.set(i,a),a},Rx=(e,t,r,n)=>{if(!n)return dl(t,r,null).defaults.flatMap(f=>Object.keys(f.relations??{}));let o=r.relPath.length;for(;o>0&&Jo(t.root,r.relPath.slice(0,o))===void 0;)o--;let i={...n[o],relPath:r.relPath.slice(0,o)},a=Sx(e.lens,t,i,e.memo?.trees??new Map).get(r.relPath.slice(o).join("."))??[];return [...o===r.relPath.length?Object.keys(Jo(t.root,r.relPath)?.relations??{}):[],...a]},Yo=(e,t,r)=>{let n=t;for(let o of Te(e.lens.maps,t,r).hops){let i=o.relPath[o.relPath.length-1];if(!j(e,n.mapName,n.modelName,n.relPath).relations.has(i))return o.prefix;n={mapName:o.map,modelName:o.model,relPath:o.relPath};}return null},j=(e,t,r,n)=>{let o=e.memo?mc(e,t,r,n):null,i=o===null?void 0:e.memo?.effects.get(o);if(i){if(!e.unvetted&&i.unchecked){for(let I of i.unchecked)I();i.unchecked=null;}return i.effect}let s=[],a={picks:null,omits:new Set,enumValuesByField:new Map,whereClauses:[],pathWheres:[],modelWheres:[],sources:new Map,sourceWheres:new Map,sourceLabels:new Map,sourceGroupBys:new Map,sourceDeclaredAt:new Map,sourcesFromMapDefaults:new Map,relations:new Set,relationFields:new Set},l=O(e.lens.maps,t),f=T(l,r);if(!f)return a;let p=e.memo?.models.get(f);p||(p=mx(f),e.memo?.models.set(f,p)),a.relationFields=p.relations;let d={mapName:t,modelName:r,relPath:n},u=e.origin??e.chain[0],m=`${Fs(u)}${we}${t}${we}${r}${we}${n.join(we)}`,y=e.memo?.places.get(m);if(!y){let I=al(e,d);y={trail:I,turnedOn:u?Rx(e,u,d,I):[]},e.memo?.places.set(m,y);}let{trail:c}=y,g=new Map,w=new Map,R=new Map,b=new Map,S=I=>I,v=0,E=()=>{},q=true,ce=true,A=(I,B=false)=>{hx(a,I,S,v,E,q,ce,B),yx(g,w,I);};for(let[I,B]of e.chain.entries()){v=I;let Tr={...e,clamp:false,skipClampsOf:void 0,skipHidingOf:void 0,chain:e.chain.slice(0,I)};q=B!==e.skipClampsOf,ce=B!==e.skipHidingOf,S=ne=>I===0?ne:tn(ne,Tr,{mapName:t,modelName:r,relPath:n});for(let[ne,be]of Object.entries(O(B.mapDefaults,t)?.enums??{}))be.picks&&yc(R,ne,be.picks),be.omits&&hc(b,ne,be.omits);let{defaults:wo,path:Cr}=dl(B,d,c),me=I===0?null:Tr,ct=ne=>(be,Se=false)=>{let Ce=e.memo?.refs.get(be);if(Ce||(Ce=ao(be),e.memo?.refs.set(be,Ce)),Ce.bare!==null&&!(ne&&!Se))throw pl(Ce.bare);if(Ce.escaping!==null)throw fl(Ce.escaping);if(!me)return;let Ql=()=>{let ci=typeof be=="object"&&be!==null?`${Ho(be)}${we}${mc(me,t,r,n)}`:null;if(ci!==null&&me.memo?.vetted.has(ci))return;let[Zl]=wx(be,me,d);if(Zl)throw bx(Zl);ci!==null&&me.memo?.vetted.add(ci);};e.unvetted?s.push(Ql):Ql();};E=ct(false);let an=O(O(B.mapDefaults,t)?.models,r);for(let ne of wo)A(ne,ne===an);Cr&&(E=ct(n.length===0&&c!==null),A(Cr));}if(u&&e.chain.includes(u))for(let I of y.turnedOn)a.relationFields.has(I)&&!a.omits.has(I)&&a.relations.add(I);for(let[I,B]of p.gated){let Tr=B.kind==="enum",Cr=B.options?.map(ne=>ne.value)??(Tr?zr(B,l?.enums):B.values);if(!Cr)continue;let me=Cr;if(Tr){let ne=R.get(B.type),be=b.get(B.type);ne&&(me=me.filter(Se=>ne.has(Se))),be&&(me=me.filter(Se=>!be.has(Se)));}let ct=g.get(I),an=w.get(I);ct&&(me=me.filter(ne=>ct.has(ne))),an&&(me=me.filter(ne=>!an.has(ne))),a.enumValuesByField.set(I,me);}return o!==null&&e.memo?.effects.set(o,{effect:a,unchecked:s.length?s:null}),a},mc=(e,t,r,n)=>{let o=gc.get(e);if(o===void 0){o=`${Fs(e.origin)}${we}${Fs(e.skipClampsOf)}${we}${Fs(e.skipHidingOf)}${we}`;for(let i of e.chain)o+=`${Ho(i)},`;gc.set(e,o);}return `${o}${we}${t}${we}${r}${we}${n.join(we)}`},gc=new WeakMap,Xt=e=>{let t=[],r=(n,o)=>{let i=O(e.lens.maps,n.mapName);if(!T(i,n.modelName))return;let s=j(e,n.mapName,n.modelName,n.relPath);t.push({path:o,at:n,effect:s});for(let a of s.relations){let l=ue(i,n.modelName,a),f=l&&ot(l,n.mapName);f&&r({...f,relPath:[...n.relPath,a]},`${o}.${a}`);}};return r({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},e.lens.model),t},Vs=(e,t,r,n)=>j(e,t,r,ll).sources.has(n),Is=(e,t,r,n)=>new k(`source '${n}' at '${e}' offers mapDefaults.${t}.models.${r}.sources.${n}, which no layer declares`,"invalid_source"),Ct=(e,t)=>e.omits.has(t)?false:e.relationFields.has(t)?e.relations.has(t):!(e.picks!==null&&!e.picks.has(t)),Ds=(e,t)=>e.enumValuesByField.get(t)??null,rn=(e,t,r)=>{let n=r.split("."),o=[],i=[];for(let{index:s,field:a,at:l,entry:f,next:p}of Sr(e.lens.maps,t,r)){if(!f)return {resolution:{outcome:"missing",index:s,hops:o},effects:i};let d=j(e,l.mapName,l.modelName,l.relPath);if(!(e.clamp&&L(f)?!d.omits.has(a):Ct(d,a)))return {resolution:{outcome:"hidden",index:s,hops:o},effects:i};let m={field:a,entry:f,mapName:l.mapName,model:l.modelName,relPath:[...l.relPath]};o.push(m),i.push(d);let y=s===n.length-1;if(y||Ue(f))return {resolution:{outcome:"resolved",hops:o,terminal:m,jsonSubPath:y?[]:n.slice(s+1)},effects:i};if(!p)return {resolution:{outcome:"pastScalar",index:s,hops:o},effects:i}}return {resolution:{outcome:"missing",index:n.length,hops:o},effects:i}},mo=(e,t,r,n,o)=>{let i=o==="label"?t.sourceLabels.get(n):t.sourceGroupBys.get(n);if(i===void 0)return true;let s=t.sourceDeclaredAt.get(sl(n,o,i)),a=(p,d)=>rn(p,r,d).resolution.outcome!=="hidden",l={...e,clamp:true},f={...l,skipHidingOf:s===void 0?void 0:e.chain[s]};return (typeof i=="string"?[i]:i).every(p=>Yo(e,r,p)===null&&(a(l,p)||a(f,p)))},uo=(e,t,r)=>{let{resolution:n,effects:o}=rn(e,t,r);if(n.outcome!=="resolved")return null;let{terminal:i,jsonSubPath:s}=n;return {mapName:i.mapName,modelName:i.model,relPath:i.relPath,entry:i.entry,terminalEffect:o[o.length-1],terminalFieldName:i.field,jsonSubPath:s}},_s=(e,t,r,n)=>{let{resolution:o}=rn(e,t,r);if(o.outcome!=="hidden")return {code:"not_in_lens",message:n};let i=r.split("."),s=o.hops.at(-1),a=s?{mapName:s.mapName,modelName:s.model,relPath:[...s.relPath,s.field]}:t,l=s&&ot(s.entry,s.mapName),f=l?{...l,relPath:a.relPath}:t,p=j(e,f.mapName,f.modelName,f.relPath),d=i[o.index];return !p.relationFields.has(d)||p.omits.has(d)?{code:"not_in_lens",message:n}:{code:"not_in_lens",message:`'${i.slice(0,o.index+1).join(".")}' is a relation the lens does not turn on (turn it on with \`relations\`)`}},Tt=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[],open:false}),co=(e,t,r)=>{let n=ze(r,t);if("outOfBounds"in n)return {issue:{code:"scope_out_of_bounds",message:n.outOfBounds}};if(n.scope.open)return {from:n.scope,next:n.scope,walked:null};let o=uo(e,n.scope,n.path);if(!o)return {issue:_s(e,n.scope,n.path,"path does not resolve through the narrowed lens")};let i=Ue(o.entry),s=ot(o.entry,o.mapName),a=s?{...s,relPath:[...o.relPath,o.terminalFieldName],open:i}:{...n.scope,open:i};return {from:n.scope,next:a,walked:o}},Te=(e,t,r,n="")=>{let o=r.split("."),i=[],s=null;for(let{index:a,field:l,at:f,entry:p,next:d}of Sr(e,t,r)){if(!p||!d)break;let u=[...f.relPath,l];i.push({map:d.mapName,model:d.modelName,relPath:u,prefix:`${n}${o.slice(0,a+1).join(".")}`,isList:p.isList===true}),a===o.length-1&&(s={...d,relPath:[...u]});}return {hops:i,end:s}};var cl="parent:",ml=e=>e.startsWith(cl),bc=e=>ml(e)?e.slice(cl.length):e,ul=(e,t)=>{let r={...e};if(e.where!==void 0&&(r.where=t(e.where)),e.sources){let n={};for(let[o,i]of Object.entries(e.sources))n[o]=Zo(i)?i.where!==void 0?{...i,where:t(i.where)}:i:t(i);r.sources=n;}if("relations"in e&&e.relations){let n={};for(let[o,i]of Object.entries(e.relations))n[o]=ul(i,t);r.relations=n;}return r},Sc=(e,t)=>{let r={};for(let[n,o]of Object.entries(e.mapDefaults??{})){let i={};for(let[s,a]of Object.entries(o.models??{}))i[s]=ul(a,t);r[n]=o.models?{...o,models:i}:o;}return {...e,root:e.root?ul(e.root,t):void 0,mapDefaults:e.mapDefaults?r:void 0}},gl=e=>{let t=[];return Sc(e,r=>(t.push(r),r)),t},wc=e=>{let t=new Set;for(let r of gl(e))for(let n of Io(r))ml(n)||t.add(n);return t},Rc=e=>{let t=new Set;for(let r of kt(e))for(let n of gl(r))for(let o of Io(n,{required:true}))t.add(bc(o));return [...t].sort()},Oc=(e,t)=>{if(lt(e))return e;let r={...t};for(let[n,o]of Object.entries(t))r[`${cl}${n}`]=o;return {...Sc(e,n=>Ba(n,r)),parent:Oc(e.parent,t)}},xc=(e,t)=>Oc(e,t),Ec=e=>{let t=[],r=new Set;for(let o of kt(e.parent))for(let i of wc(o))r.add(i);for(let o of wc(e))r.has(o)&&t.push(`bind name '${o}' already declared by an ancestor narrowing \u2014 rename it, or reference the inherited one as 'parent:${o}'`);let n=new Set;for(let o of gl(e))for(let i of Io(o))ml(i)&&n.add(bc(i));for(let o of n)r.has(o)||t.push(`bind 'parent:${o}' references an inherited binding no ancestor declares`);return t};var vc=(e,t)=>e===void 0?t:t===void 0?e:{all:[e,t]},Ox=(e,t)=>{if(!e||!t)return e??t;let r={...e};for(let[n,o]of Object.entries(t)){let i=r[n];if(i===void 0){r[n]=o;continue}let s=Nr(i),a=Nr(o),l=vc(s.where,a.where);r[n]={...s,...a,...l===void 0?{}:{where:l}};}return r},Nc=(e,t)=>{let r=vc(e?.where,t.where),n=Ox(e?.sources,t.sources);return {...e,...r===void 0?{}:{where:r},...n?{sources:n}:{}}},xx=(e,t)=>{let r={...e?.models};for(let[n,o]of Object.entries(t))r[n]=Nc(r[n],o);return {...e,models:r}},$c=(e,t)=>{let r={...e.mapDefaults};for(let[n,{models:o}]of Object.entries(t.mapDefaults??{}))r[n]=xx(r[n],o);return {...e,...t.root?{root:Nc(e.root,t.root)}:{},...t.mapDefaults?{mapDefaults:r}:{}}},yl=(e,t)=>lt(e)?$c({parent:e},t):lt(e.parent)?$c(e,t):{...e,parent:yl(e.parent,t)};var Ac=(e,t)=>{let r=D(t),n=(o,i)=>typeof o=="string"&&o!==""?co(r,i,o):null;return gr(e,{rewrite:(o,i)=>{if(le(o)!=="field"||o.coerceType)return o;let s=n(o.field,i);if(!s||"issue"in s||!s.walked||s.walked.jsonSubPath.length)return o;let{entry:a}=s.walked;return a.kind==="scalar"&&Kd.includes(a.type)?{...o,coerceType:a.type}:o},below:(o,i)=>{if(!xe(o))return false;let s=n(o.field,i),a=s&&!("issue"in s)?s.walked?.entry:void 0;return s&&!("issue"in s)&&a&&L(a)?[...i,s.next]:false}},[Tt(r)])};var Pc=({maps:e,bridges:t,mapName:r,model:n})=>({...Os({maps:e,bridges:t}),mapName:r,model:n});var Ex=(e,t)=>H(e,(r,n)=>{if(t.sources.add(n[n.length-1].mapName),We(r)||typeof r.field!="string"||r.field==="")return;let o=co(t.policy,n,r.field);return "issue"in o?false:(o.walked&&(t.sources.add(o.walked.mapName),(o.walked.entry.kind==="bridge"||o.walked.mapName!==o.from.mapName)&&(t.bridgesCrossed=true)),[...n,o.next])},[Tt(t.policy)]),kc=(e,t)=>{let n={policy:D(t),sources:new Set,bridgesCrossed:false};return Ex(e,n),{sources:[...n.sources].sort(),bridgesCrossed:n.bridgesCrossed,supportedTargets:_.filter(o=>(o==="check"||!n.bridgesCrossed)&&$r(e,{target:o,map:n.policy.lens,mapName:n.policy.lens.mapName,model:n.policy.lens.model}).ok),errors:vr(e,t).errors}};var $x=new Set([Ut.scalar,Ut.ordered,Ut.array,Ut.dayList,Ut.dateValue]),vx=new Set([Ut.none,Ut.count]),Nx=e=>{if(e.offset!==void 0||jo(e).some(({source:r})=>r.value===void 0))return {values:[],dynamic:true};let t=Dn(e);return t?vx.has(t.valueShape)?{values:[],dynamic:false}:$x.has(t.valueShape)?"value"in e?{values:Go(e)??[],dynamic:false}:{values:[],dynamic:false}:{values:[],dynamic:true}:{values:[],dynamic:true}},Ax=e=>e instanceof Date?`d:${+e}`:e instanceof RegExp?`r:${e}`:typeof e=="object"&&e!==null?`j:${JSON.stringify(e)}`:`p:${typeof e}:${String(e)}`,Tc=(e,t)=>{let r=D(t),n=r.lens.model,o=new Map,i=new Map,s=(l,f)=>{if(l.length===0)return;let p=uo(r,{mapName:r.lens.mapName,modelName:n,relPath:[]},l.join("."));if(!p||p.jsonSubPath.length>0)return;let{mapName:d,modelName:u,relPath:m,terminalEffect:y,terminalFieldName:c}=p;if(!y.sources.has(c))return;let g=[n,...m].join("."),w=`${g}|${c}`,R=o.get(w);R||(R={path:g,mapName:d,model:u,field:c,values:[],dynamic:false},o.set(w,R));let b=Nx(f);b.dynamic&&(R.dynamic=true);let S=i.get(w)??new Set;i.set(w,S);for(let v of b.values){let E=Ax(v);S.has(E)||(S.add(E),R.values.push(v));}},a=(l,f)=>{let p=ze(l,f);if(!("outOfBounds"in p))return [...p.scope,...p.path.split(".")]};return H(e,(l,f)=>{if(We(l))return;let p=typeof l.field=="string"?a(l.field,f):f.at(-1);return p?(!xe(l)&&typeof l.field=="string"&&s(p,l),[...f,p]):false},[[]]),[...o.values()]};var qs=(e,t,r,n)=>{let o=Px(e,t,r);if(o.options===t)return n(o.condition,o.options);try{return n(o.condition,o.options)}catch(i){if(i instanceof k||i instanceof C)throw i;try{n(e,o.options);}catch{throw i}throw new k(`${r}: the lens's clamps on this rule have no ${r} form \u2014 ${i.message}`,"unsupported_target")}},Px=(e,t,r)=>{if(t?.lens===void 0)return {condition:e,options:t};let{lens:n}=t;if(t.map!==void 0||t.mapName!==void 0||t.model!==void 0)throw new C(`${r}: pass \`lens\` or \`map\` / \`mapName\` / \`model\`, not both \u2014 the lens names its own`);let o=vr(e,n);if(!o.ok)throw new Error(`${r}: the rule leaves the lens \u2014 ${o.errors.map(s=>`${s.path}: ${s.message}`).join("; ")}`);let i=pt(n);return {condition:po(e,n),options:{...t,lens:void 0,map:i,mapName:i.mapName,model:i.model}}};var Bs=(e,t,r,n)=>{if(!Md.includes(e.operator))throw new Error(`'${e.operator}' does not apply to the enum '${e.field}'; compare its values with equals / in.`);let o=oe(e.caseInsensitive),i=zr(r,n?.enums),{values:s,hasNull:a}=Qe(xt.includes(e.operator)?[t]:t);if(!o&&(!i||s.every(d=>typeof d=="string"&&i.includes(d))))return null;if(!i)throw new Error(`'${e.field}' is an enum: a case-insensitive comparison reads its declared values, which the map doesn't list.`);let l=d=>o?d.toLowerCase():d,f=new Set(s.filter(d=>typeof d=="string").map(d=>l(d))),p=i.filter(d=>f.has(l(d)));return W.includes(e.operator)?{values:i.filter(d=>!p.includes(d)),matchesNull:!a}:{values:p,matchesNull:a}};var se=e=>`"${e.replace(/"/g,'""')}"`;var $e=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),hl=(e,t,r=false)=>{let[n,...o]=e.split("."),i=t?`${se(t)}.${se(n)}`:se(n);if(o.length===0)return i;let s=o.map(wl),a=s.pop();return [i,...s].join("->")+(r?"->":"->>")+a},wl=e=>`'${e.replace(/'/g,"''")}'`;var kx=["@prisma/client/runtime/client","@prisma/client/runtime/library"],Ws,Tx=()=>{if(Ws!==void 0)return Ws;for(let e of Cx())for(let t of kx)try{let r=e(t);if(r.AnyNull!==void 0)return Ws=r.AnyNull,Ws}catch{}},Cx=()=>{let e=[];try{let t=globalThis.process?.getBuiltinModule?.("module")?.createRequire;t&&e.push(t(import.meta.url));}catch{}return typeof Oa=="function"&&e.push(Oa),e},Cc=()=>{let e=Xe.get("prismaOptions.anyNull")??Tx();if(e===void 0)throw new Error("A null check on a Json field needs Prisma's AnyNull, and @prisma/client isn't installed: engineGlobals.set('prismaOptions.anyNull', Prisma.AnyNull).");return e};var Lc=(e,t)=>{let r=Kr(it(t));return r===null?null:Ur(e,r)},Mc=(e,t,r)=>{if(e===null)return null;let n=Yn(it(t)),o=n&&Wr(n[0],Ko);return !n||!o?null:mr(Nt(e),o,n[1],oo(r).timeZone).toDate()};var Sl=(e,t)=>Ke(e,t?.map,t?.model),Lt=e=>e==="json"||e==="json-path",Ar=e=>Lt(e)?Cc():null,nn=(e,t)=>t?.map&&t?.model?Tu(e,t.map,t.model).map(r=>Yr(r,{is:null})):[],Rl=(e,t)=>{let r=Sl(e,t);return [...Lt(r)||r==="list"||te(e.field,t?.map,t?.model)?.isRequired===false?[ft(e.field,{equals:Ar(r)},t)]:[],...nn(e.field,t)]},Us=(e,t,r,n)=>{if(r.mode&&Lt(n)&&Array.isArray(t))throw V("toPrisma",`A case-insensitive comparison of a Json value with the list ${JSON.stringify(t)}`);if(!r.mode||typeof t!="string")return {[e]:t,...r};if(!Lt(n))return {[e]:$e(t),...r};if(/[%_\\"\u0000-\u001f]/.test(t))throw V("toPrisma",`A case-insensitive equality on Json against '${t}'`,"Prisma matches the JSON text, where %, _, a backslash, a quote or a control character doesn't read as itself");return {[e]:t,...r}},Ol=(e,t,r,n)=>{let o=t?.datasource?.provider??Xe.get("prismaOptions.datasource.provider");return oe(e.caseInsensitive)&&Nd(o)&&xr(r,n)?{mode:"insensitive"}:{}},_c=(e,t)=>{if(e==="list")return [{isEmpty:true}];let r=t?[{equals:""}]:[];return Lt(e)?[...r,{equals:[]}]:r},Dc=e=>"isEmpty"in e?{isEmpty:false}:{not:e.equals},xl=(e,t,r,n,o)=>{let i=a=>ft(e,a,o),s=_c(t,n);return r?K([i({equals:Ar(t)}),...nn(e,o),...s.map(a=>i(a))]):ke([...t==="list"?[]:[i({not:Ar(t)})],...s.map(a=>i(Dc(a)))])},Mx=(e,t)=>{if(!Qt(e))throw ur(e.field);let n=(o=>ft(e.field,o,t))({is:{}});return he({...e,field:"relation"},{relation:null})===true?_e(n):n},_x=(e,t)=>te(e.field,t?.map,t?.model),bl=st(),Dx=(e,t,r)=>{if(t==="list"||Lt(t)||_x(e,r)?.isRequired!==true)return null;let n=e.field.split(".").slice(0,-1).join(".");return n?ft(n,{is:{}},r):bl},Fc=(e,t)=>{let r=c=>ft(e.field,c,t),n=Sl(e,t),o=()=>Rl(e,t),i=xs(e,t?.map,t?.model);if(n==="relation")return Mx(e,t);let s=Dx(e,n,t),a=s&&(s===bl?Pt():_e(s)),l=c=>s&&a?he({field:"f",operator:c,value:null},{f:null})===true?a:s:null;if(s&&a&&Qt(e)){let c=_c(n,i);return e.operator===h.isEmpty?K([a,...c.map(r)]):e.operator===h.notEmpty?ke([s,...c.map(g=>r(Dc(g)))]):l(e.operator)}switch(e.operator){case h.exists:case h.notExists:{if(e.operator===h.exists)return n==="list"?_e(r({equals:null})):r({not:Ar(n)});let c=o();return c.length?K(c):r({equals:Ar(n)})}case h.isEmpty:case h.notEmpty:return xl(e.field,n,e.operator===h.isEmpty,i,t)}if(Oe(e)){let c=Ns(e,t?.map,t?.model,Vu(t),Iu(t));if("problem"in c)throw As(e.path,c.problem);let g=r({[c.key]:c.ref}),w=(v,E)=>E.isRequired===false?ft(v,{equals:null},t):null,R=(v,E)=>E.isRequired===false?ft(v,{not:null},t):bl,b=w(e.field,c.field),S=w(c.columnPath,c.column);return e.operator===h.equals?b&&S?K([g,ke([b,S])]):g:e.operator===h.notEquals?K([_e(g),...b?[ke([b,R(c.columnPath,c.column)])]:[],...S?[ke([R(e.field,c.field),S])]:[]]):g}let f=jc(e,t);if(Ee(e,f))return K(W.includes(e.operator)?o():[]);if(f===null&&xt.includes(e.operator)){let c=l(e.operator);if(c)return c}if(n==="list"&&dr.includes(e.operator)&&Array.isArray(f))return fe(bs(e,f),t);if(n==="list"&&Array.isArray(f)&&f.includes(null))throw V("toPrisma",`A list holding null in '${e.field}'`);if(n==="list"&&oe(e.caseInsensitive)&&xr("text",f))throw V("toPrisma",`A case-insensitive comparison on the list '${e.field}'`);let p=n==="enum"?te(e.field,t?.map,t?.model):void 0,d=p?Bs(e,f,p,t?.map):null;if(d){let c=r({in:d.values});return d.matchesNull?K([c,...o()]):c}if(dr.includes(e.operator)){let{values:c,hasNull:g}=Qe(f),w=Ol(e,t,n,c),R=Lt(n)?e.operator===h.in?K(c.map(b=>r(Us("equals",b,w,n)))):ke(c.map(b=>r(Us("not",b,w,n)))):r({[e.operator]:c,...w});return e.operator===h.in?g?K([R,...o()]):R:g?ke([R,s??r({not:Ar(n)})]):K([R,...o()])}let u=c=>{if(!Lt(n)||c!==h.contains)return r(Xo({...e,operator:c},t));let g=r({array_contains:[Fx(e,f,t,n)]});return typeof f=="string"?K([r(Xo({...e,operator:c},t)),g]):g};if(e.operator===h.contains)return u(h.contains);let m=qd.includes(e.operator)?Lo[e.operator]:jn.includes(e.operator)?h.between:void 0;if(m){if(Lt(n))throw V("toPrisma",`'${e.operator}' on the Json value '${e.field}'`,"it keeps values of other types");return K([_e(u(m)),...o()])}let y=r(Xo(e,t));return e.operator===h.equals&&f===null?K([y,...nn(e.field,t)]):e.operator===h.notEquals&&n==="list"?f===null?_e(r({equals:null})):K([_e(r({equals:f})),...o()]):e.operator===h.notEquals&&f!==null?K([y,...o()]):y},jc=(e,t)=>{let r=fo(e,it(e),Rr(e.field,t?.map,t?.model),"toPrisma",()=>oo(t).timeZone);return e.offset===void 0?r:Lc(r,e.offset)},Xo=(e,t)=>{let r=as(e);if(r)throw r;let n=Sl(e,t),o=()=>jc(e,t),i=f=>Ol(e,t,n,f),s=f=>{let p=o();if(n==="list"){if(f!=="contains")throw new Error(`Operator '${f}' does not apply to the list '${e.field}'.`);return {has:p}}let d=Lt(n)?jx[f]:f,u=typeof p=="string"?$e(p):p;return {[d]:u,...i(p)}},a=ls(e.operator,o());if(a)throw a;let l=pr(e.operator,"field");if(l&&Fn.includes(e.operator))return {[l]:o()};switch(e.operator){case h.equals:{let f=o()??Ar(n);return Us("equals",f,i(f),n)}case h.notEquals:{let f=o()??Ar(n);return Us("not",f,i(f),n)}case h.in:case h.notIn:return {[e.operator]:o()};case h.contains:return s("contains");case h.startsWith:return s("startsWith");case h.endsWith:return s("endsWith");case h.matches:case h.notMatches:throw V("toPrisma",`'${e.operator}'`,"Prisma has no pattern filter");case h.between:case h.notBetween:{let[f,p]=Je(rt(o(),e.operator));return {gte:f,lte:p}}default:throw new Error(`Operator '${e.operator}' is built by buildFieldRule`)}},Fx=(e,t,r,n)=>{if(typeof t=="object"&&t!==null)throw new Error(`Membership of an object or a list in the Json array '${e.field}' has no exact Prisma form; use toSql() or check().`);if(Ol(e,r,n,t).mode)throw V("toPrisma",`A case-insensitive member of the Json array '${e.field}'`);return t},jx={contains:"string_contains",startsWith:"string_starts_with",endsWith:"string_ends_with"},ft=(e,t,r)=>{if(!r?.map||!r?.model)return Yr(e,t);let n=ie(e,r.map,r.model),o=n.hops.find(s=>s.entry.isList);if(o)throw Un(e,o);let i=e.split(".");switch(n.kind){case "fallback":case "direct":return Yr(e,t);case "bridge":return Zr();case "past-scalar":throw Kn(e,n.column);case "json-path":{let s={path:n.jsonPath,...t},a=i.slice(0,n.stopIndex).join(".");return Yr(a,s)}}};var Vc=(e,t,r)=>{if(Ae(e)){let n=to(e);if(!n)throw $t("toPrisma");return fe(n,t,r)}if(!t?.map||!t?.model||!r)throw new Error("Aggregate rules require a FieldMap and model to generate a Prisma plan. Pass { map, model } options to toPrisma().");if(!Ot.includes(e.aggregate.mode))throw cr(e.aggregate.mode);if(!e.aggregate.field)throw new Error("Prisma aggregate rules require aggregate.field to specify the numeric field on the related model.");return Vx(e,t,r)},Vx=(e,t,r)=>{let n=so(e.field,t.map,t.model,"Aggregate rules");if(e.condition&&At(e.condition,t.map,n.target))return Zr();let o=e.aggregate.field??"",i=ue(t.map,n.target,o);if(!i)throw new Error(`aggregate.field '${o}' does not exist on model '${n.target}'.`);if(i.kind!=="scalar"||Ue(i))throw new Error(`aggregate.field '${o}' on model '${n.target}' must be a numeric scalar, got ${i.kind==="scalar"?"Json":`'${i.kind}'`}.`);let s=io(t)(e);if(s===null||Ee(s,s.value))return Pt();let a=Wo(s,[{}],void 0,{},{value:0})===true,l=a?Ze(s):s,f=Xo(l,t),p={[e.aggregate.mode==="sum"?"_sum":"_avg"]:f},d=jn.includes(l.operator)?_e({[o]:p}):{[o]:p},u=e.condition?fe(e.condition,Qr({...t,model:n.target},t,true),r):st(),m=ks(r,n,u,d,a);return a?K([m,...nn(e.field,t)]):m};var qc=(e,t,r)=>{if(!e.field)throw new Error("toPrisma: count-based ArrayRule requires a field path");let n=so(e.field,t.map,t.model,"Count operators");if(e.condition===void 0)throw Ie(e.arrayOperator);if(e.count===void 0)throw qn(e.arrayOperator);let o=e.count;if(e.arrayOperator===x.atLeast&&o===0)return st();let i=fe(e.condition,Qr({...t,model:n.target},t,true),r),s=El(e),a=s?Ic(x.atLeast,e.arrayOperator===x.atMost?o+1:1,n.targetKey):Ic(e.arrayOperator,o,n.targetKey);return ks(r,n,i,a,s)},Ic=(e,t,r)=>{let n=pr(e,"array");if(!n)throw new Error(`'${e}' does not count`);return {[r]:{_count:{[n]:t}}}};var Bc=(e,t,r)=>{let n=Wc(e,t,r);return e.field&&El(e)&&!Uc(e.field,t)?K([n,...nn(e.field,t)]):n},El=e=>he({...e,field:"items"},{items:[]})===true,Ix=e=>{let t=Ma(e);if(!t)return null;let{count:r,...n}=e;return {...n,arrayOperator:t}},Wc=(e,t,r)=>{if(Ae(e)){let s=to(e);if(!s)throw $t("toPrisma");return fe(s,t,r)}if(e.condition!==void 0&&!Vd.includes(e.arrayOperator)&&At(e.condition,t?.map,Kc(e,t)?.model))return Zr();let n=Ix(e);if(n)return Wc(n,t,r);if(ko.includes(e.arrayOperator)){if(t?.map&&t?.model&&r)return qc(e,t,r);throw new Error(`ArrayOperator '${e.arrayOperator}' requires a FieldMap and model to generate a multi-step plan. Pass { map, model } options to toPrisma(). Without them, use prisma.$queryRaw for count-based relation filtering.`)}if(!e.field)throw is("toPrisma");let{field:o}=e;if(Uc(o,t))return qx(e,o,Ke({field:o},t?.map,t?.model),t);let i=Bx(e,t,r);return ft(e.field,i,t)},Uc=(e,t)=>{let r=Ke({field:e},t?.map,t?.model);return r==="list"||r==="json"||r==="json-path"},qx=(e,t,r,n)=>{switch(e.arrayOperator){case x.empty:case x.notEmpty:return xl(t,r,e.arrayOperator===x.empty,false,n);default:throw V("toPrisma",`'${e.arrayOperator}' over the ${r==="list"?"list":"Json array"} '${t}'`,r==="list"?"test a list's membership with 'contains'":void 0)}},Kc=(e,t)=>{if(!t?.map||!t?.model||!e.field)return t&&Qr({...t});let r=Uo(e.field,t.map,t.model);return Qr(r?{...t,model:r}:{...t})},Bx=(e,t,r)=>{let n=Kc(e,t);switch(e.arrayOperator){case x.all:if(!e.condition)throw Ie(e.arrayOperator);return {none:fe(Ze(e.condition,io(n)),n,r)};case x.any:if(!e.condition)throw Ie(e.arrayOperator);return {some:fe(e.condition,n,r)};case x.none:if(!e.condition)throw Ie(e.arrayOperator);return {none:fe(e.condition,n,r)};case x.empty:return {none:{}};case x.notEmpty:return {some:{}};default:throw de(e.arrayOperator,"array")}};var Gc=(e,t)=>{let r=t?.map,n=Ke({field:e.field},r,t?.model);if(n==="json"||n==="json-path")throw V("toPrisma",`A date rule on the Json value '${e.field}'`,"Prisma compares Json text");let o=te(e.field,r,t?.model);if(o&&!L(o)&&Ge(o)!==P.DateTime)throw V("toPrisma",`A date rule on the ${o.type} field '${e.field}'`,`Prisma compares it as ${o.type}, not as an instant`);let i=W.includes(e.dateOperator)?Rl(e,t):[],s=Wx(e,t);if(s===null)return K(i);let a=ft(e.field,s,t),l=jn.includes(e.dateOperator)?_e(a):a;return K([l,...i])},Wx=(e,t)=>{let r=oo(t),n=Ko,o=m=>e.offset===void 0?m:Mc(m,e.offset,t),i=m=>{if(m==null)return null;if(!ee(m))return hs(m,r.timeZone);let y=vt(m,n);return y&&zn(y,e.dateOperator,r).toDate()},s=()=>{let m=it(e);if(m==null)return m;let y=e.offset===void 0?void 0:it(e.offset),c=zt(m,y);if(c)throw c;return m},a=()=>o(i(s())),l=()=>{let m=s();if(m==null)return null;let y=rt(m,e.dateOperator).map(i);if(y[0]===null||y[1]===null)return null;let[c,g]=Je(y).map(o);return c&&g?[c,g]:null},f=()=>{let m=s();if(m==null)return null;if(!ee(m))throw tt(e.dateOperator);let y=vt(m,n);if(!y)return null;let[c,g]=Hn(y,r);return [c.toDate(),g.toDate()]},p=m=>{let y=a();return y===null?null:{[m]:y}},d=m=>m?{gte:m[0],lte:m[1]}:null,u=pr(e.dateOperator,"date");if(u)return p(u);switch(e.dateOperator){case N.within:case N.notWithin:return d(f());case N.between:case N.notBetween:return d(l());case N.dayIn:case N.dayNotIn:throw V("toPrisma",`'${e.dateOperator}'`);default:throw de(e.dateOperator,"date")}};var $l=(e,t,r)=>{if(typeof e=="boolean")return e?{}:Pt();Ki(e,"toPrisma");let n=le(e);(n==="field"||n==="date")&&Es(e.field,t?.map,t?.model);let o=e;switch(n){case "all":return Ku(o,t,r);case "any":return Gu(o,t,r);case "if":return zu(o,t,r);case "array":return Bc(o,t,r);case "aggregate":return Vc(o,t,r);case "date":return Gc(o,t);case "field":return Fc(o,t);default:throw Et()}};Wu($l);var Hc=(e,t,r)=>t&&r?on(e,t,r):e,dt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ks=(e,t,r)=>{let n=ue(e,t,r);return n?.kind==="object"&&!n.isList?n.type:null},Ux=["some","every","none"],ei=e=>Object.entries(e).flatMap(([t,r])=>t!=="AND"?[{[t]:r}]:(Array.isArray(r)?r:[r]).flatMap(o=>dt(o)?ei(o):[{AND:o}])),vl=(e,t,r)=>{let n=Object.keys(e);if(n.length!==1||!Ks(t,r,n[0]))return null;let o=e[n[0]];if(!dt(o))return null;let i=Object.keys(o);return i.includes("isNot")?null:i.includes("is")?i.length===1&&dt(o.is)?{key:n[0],isForm:true,inner:o.is}:null:ei(o).length?{key:n[0],isForm:false,inner:o}:null},Jc=(e,t,r)=>{let n=vl(e,t,r);if(!n)return [];let o=Ks(t,r,n.key);return [n.key,...ei(n.inner).flatMap(i=>Jc(i,t,o).map(s=>`${n.key}.${s}`))]},Qc=(e,t,r)=>{if(!dt(e))return null;let n=Object.keys(e);if(n.length!==1)return null;let o=Ks(t,r,n[0]),i=e[n[0]];if(!o||!dt(i))return null;let s=Object.keys(i);if(s.length===1&&s[0]==="is"&&i.is===null)return n[0];let a=Qc(i,t,o);return a?`${n[0]}.${a}`:null},Kx=(e,t,r)=>{let n=e.map(o=>dt(o)?on(o,t,r):o);return n.some((o,i)=>o!==e[i])?n:e},Nl=(e,t)=>{let r=false,n={};for(let[o,i]of Object.entries(e))n[o]=t(o,i),n[o]!==i&&(r=true);return r?n:e},Gx=(e,t,r,n)=>{if(e==="AND"||e==="OR"||e==="NOT")return Array.isArray(t)?Kx(t,r,n):dt(t)?on(t,r,n):t;let o=ue(r,n,e);if(o?.kind!=="object"||!dt(t))return t;if(o.isList)return Nl(t,(s,a)=>Ux.includes(s)&&dt(a)?on(a,r,o.type):a);let i=Object.keys(t);return i.length===1&&(i[0]==="is"||i[0]==="isNot")?Nl(t,(s,a)=>dt(a)?on(a,r,o.type):a):on(t,r,o.type)},zc=(e,t,r)=>Nl(e,(n,o)=>Gx(n,o,t,r)),zx=(e,t,r,n)=>{let o=Object.keys(e);if(o.length!==1||o[0]!=="OR"||!Array.isArray(e.OR))return null;let i=e.OR,s=i.filter(a=>{let l=Qc(a,r,n);return l===null||!t.has(l)});return s.length===i.length||s.length===0?null:s.length===1&&dt(s[0])?ei(s[0]):[{OR:s}]},on=(e,t,r)=>{let n=ei(e),o=false;for(let l=true;l;){l=false;let f=new Set(n.flatMap(p=>Jc(p,t,r)));n=n.flatMap(p=>{let d=zx(p,f,t,r);return d?(l=o=true,d):[p]});}let i=new Map;for(let l of n){let f=vl(l,t,r);f&&i.set(f.key,[...i.get(f.key)??[],f]);}if(!o&&![...i.values()].some(l=>l.length>1))return zc(e,t,r);let s=new Set,a=[];for(let l of n){let f=vl(l,t,r),p=f?i.get(f.key)??[]:[];if(!f||p.length<2){a.push(zc(l,t,r));continue}if(s.has(f.key))continue;s.add(f.key);let d=Ks(t,r,f.key),u=on(ke(p.map(m=>m.inner)),t,d);a.push({[f.key]:p.some(m=>m.isForm)?{is:u}:u});}return ke(a)};var Yc=async(e,t)=>{let r=e.steps.filter(i=>i.operation==="groupBy"),n=e.steps.find(i=>i.operation==="where");if(!n)throw new Error("executePrismaPlan: result has no where step");let o=[];for(let i of r){let s=Xc(t,i.model),a=Zc(i.args,i.refs,o,t),l=await s[i.operation](a);o.push(l.map(f=>f[i.extract]).filter(f=>f!=null));}return Zc(n.where,n.refs,o,t)},Xc=(e,t)=>{let r=t.charAt(0).toLowerCase()+t.slice(1),n=e[r];if(!n)throw new Error(`executePrismaPlan: no delegate for model '${t}'. Ensure prismaDelegate has a key '${r}'.`);return n},Hx=(e,t)=>{let r=Xc(e,t.model).fields,n=r&&Object.hasOwn(r,t.field)?r[t.field]:void 0;if(n===void 0)throw new Error(`executePrismaPlan: the '${t.model}' delegate has no field reference '${t.field}' (fields.${t.field}).`);return n},Jx=(e,t)=>t.reduce((r,n)=>r!==null&&typeof r=="object"&&Object.hasOwn(r,n)?r[n]:void 0,e),Al=(e,t,r)=>{if(t.length===0)return r;let[n,...o]=t,i=e,s=Array.isArray(e)?[...e]:{...i};return s[n]=Al(i[n],o,r),s},Zc=(e,t,r,n)=>{let o=e;for(let{path:i}of t??[]){let s=Jx(e,i);if(s&&typeof s.__step=="number"){let a=s.__step;if(a>=r.length)throw new Error(`Step ref __step: ${a} out of range (${r.length} steps executed)`);o=Al(o,i,r[a]);}else if(s&&typeof s.__field=="object"&&s.__field!==null)o=Al(o,i,Hx(n,s.__field));else throw new Error(`executePrismaPlan: no reference at the recorded location ${i.join(".")}`)}return o};var Qx=e=>e?.map?{...e,map:Pe(e.map,e.mapName,"toPrisma")}:e,ti=(e,t)=>qs(e,t,"toPrisma",Zx),Zx=(e,t)=>{let r={steps:[]},n=Qx(t),o=Hc($l(e,n,r),n?.map,n?.model),i=(s,a)=>{let l=Du(a);return l.length?{...s,refs:l}:s};return {steps:[...r.steps.map(s=>i(s,s.args)),i({operation:"where",where:o},o)]}};var Yx=/^-?\d+(\.\d+)?$/,em=e=>typeof e=="string"?Yx.test(e)?Number(e):e:typeof e=="object"&&e!==null&&typeof e.toNumber=="function"?e.toNumber():e,Pl=(e,t)=>e?.kind!=="scalar"||e.type!=="Decimal"?t:Array.isArray(t)?t.map(em):em(t);var Gs=(e,t,r,n,o)=>{let i=`${r.mapName}\0${r.modelName}`;for(let a of t){if(typeof a=="boolean")continue;let l=e.memo?.compiles.get(a)??new Map;e.memo?.compiles.set(a,l);let f=l.get(i);if(f===void 0){let[p]=$r(a,{target:"toPrisma",map:e.lens,mapName:r.mapName,model:r.modelName}).errors;f=p?p.message:null,l.set(i,f);}if(f!==null)return new k(`${n}: ${f}`,"unsupported_clamp")}if(o)return null;let s=false;for(let a of t)H(a,l=>{("aggregate"in l||To(l))&&(s=true);});return s?new k(`${n} needs a counting step (executePrismaPlan), which a relation's where in a select can't run`,"unsupported_clamp"):null},zs=(e,t)=>{try{return t()}catch(r){throw r instanceof k||r instanceof C?r:new k(`${e}: ${r.message}`,"unsupported_clamp")}};var tm=(e,t)=>e===""?t:t===""?e:`${e}.${t}`,De=e=>{let t=new Set,r=o=>{o&&t.add(o);},n=(o,i)=>{let s=ze(o,i);return "outOfBounds"in s?null:tm(s.scope,s.path)};return H(e,(o,i)=>{if(We(o))return;for(let l of yr(o))r(M(l)?n(l,i):l);let s=typeof o.field=="string"&&o.field!==""?n(o.field,i):null;if(r(s),!xe(o))return;let a=s??i[i.length-1];for(let l of Qn(o))r(tm(a,l));return [...i,a]},[""]),[...t]};var kl=(e,t,r,n,o)=>{let i={};for(let[s,a]of Object.entries(n.fields)){if(!Ct(t,s))continue;let l=t.enumValuesByField.get(s),f=o(s)?.filter(d=>l===void 0||l.includes(d.value)),p=mo(e,t,r,s,"groupBy")?t.sourceGroupBys.get(s):void 0;i[s]={...a,...l!==void 0&&{values:l},...f!==void 0&&{options:f},...p!==void 0&&{groupBy:p}};}return i},rm=(e,t,r,n,o)=>{let{mapName:i,modelName:s}=t,a=T(O(e.lens.maps,i),s),l=kl(e,r,t,a,m=>{let y=o.get(`${n}|${m}`),c=r.enumValuesByField.get(m);return y??O(a.fields,m)?.options??c?.map(g=>({value:g,label:g}))}),f={};for(let[m,y]of r.sources)Ct(r,m)&&(f[m]=y);let p={};for(let[m,y]of r.sourceLabels)Ct(r,m)&&mo(e,r,t,m,"label")&&(p[m]=y);let d={};for(let[m,y]of r.sourceGroupBys)Ct(r,m)&&mo(e,r,t,m,"groupBy")&&(d[m]=y);let u={};for(let m of r.sourcesFromMapDefaults.keys()){if(!Vs(e,i,s,m))throw Is(n,i,s,m);Object.hasOwn(f,m)&&(u[m]="mapDefaults");}return {mapName:i,model:s,fields:l,whereClauses:r.whereClauses,sources:f,sourceLabels:p,sourceGroupBys:d,sourceFrom:u}},nm=e=>{let t=new Map;for(let r of e.sourceValues??[])t.set(`${r.path}|${r.field}`,r.options);return t},om=(e,t={})=>ri(D(e),t),ri=(e,t={})=>{let r=nm(t),n={};for(let{path:o,at:i,effect:s}of Xt(e))n[o]=rm(e,i,s,o,r);return n},im=(e,t,r={})=>Tl(D(e),t,r),Tl=(e,t,r={})=>{let n={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};if(t!=="")for(let s of Sr(e.lens.maps,n,t)){let a=j(e,s.at.mapName,s.at.modelName,s.at.relPath);if(!s.next||!a.relations.has(s.field))return null;n={...s.next,relPath:[...s.at.relPath,s.field]};}if(!T(O(e.lens.maps,n.mapName),n.modelName))return null;let o=j(e,n.mapName,n.modelName,n.relPath),i=[e.lens.model,...n.relPath].join(".");return rm(e,n,o,i,nm(r))};var Hs=(e,t,r,n,o)=>{let i=e.split("."),{hops:s}=Te(t,{mapName:r,modelName:n,relPath:[]},e),a=s.find((d,u)=>d.isList&&u<i.length-1);if(a)return `${o} cannot traverse to-many relation '${i[s.indexOf(a)]}'`;if(s.length===i.length)return `${o} must end on a scalar column, '${i.at(-1)}' is a relation`;let l=s.at(-1)??{map:r,model:n},f=i[s.length],p=ue(O(t,l.map),l.model,f);return p?L(p)?`${o} relation '${f}' has no resolvable target`:s.length===i.length-1?null:`${o} segment '${f}' is not a relation`:`${o} segment '${f}' not on model '${l.model}'`},sm=(e,t,r,n,o,i,s,a)=>{let l=Hs(o,e.lens.maps,t,r,i);if(l)throw new k(`${i} '${o}': ${l}`,"invalid_source");let{hops:f}=Te(e.lens.maps,{mapName:t,modelName:r,relPath:n},o),p=f.slice(0,o.split(".").length-1);for(let d of p){let u=d.relPath.join(".");if(s.has(u))continue;s.add(u);let m=j(e,d.map,d.model,d.relPath);for(let y of m.whereClauses)a.push(lo(y,d.prefix));}},Xx=(e,t,r,n,o,i)=>{let s=[],a=new Set;for(let l of o)sm(e,t,r,n,l,"groupBy",a,s);return i?.includes(".")&&sm(e,t,r,n,i,"label",a,s),s},ni=(e,t)=>{let r=ge(e,t);return r==null||typeof r=="object"?void 0:String(r)},Js=(e,t)=>{let r=[];for(let n of t){let o=ni(e,n);if(o===void 0)return;r.push(o);}return r},Cl=(e,t)=>JSON.stringify([e??null,t]),eE=(e,t,r,n)=>{let o=Cl(n,t),i=e.get(o);i===void 0?e.set(o,{value:t,...r!==void 0?{label:r}:{},...n!==void 0?{groups:n}:{}}):r!==void 0&&(i.label===void 0||r<i.label)&&e.set(o,{...i,label:r});},Qs=(e,t,r,n,o)=>{let i=ge(t,r),s=n==null?void 0:String(n);for(let a of Array.isArray(i)?i:[i])a==null||typeof a=="object"||eE(e,String(a),s,o);},Zs=e=>[...e.values()].sort((t,r)=>{let n=(t.groups===void 0?0:1)-(r.groups===void 0?0:1);if(n!==0)return n;let o=t.groups??[],i=r.groups??[];for(let s=0;s<Math.max(o.length,i.length);s++){let a=(o[s]??"").localeCompare(i[s]??"","en",{numeric:true});if(a!==0)return a}return (t.label??t.value).localeCompare(r.label??r.value,"en",{numeric:true})||t.value.localeCompare(r.value,"en",{numeric:true})}),tE=(e,t,r,n,o)=>{let{hops:i}=ie(o,t,n),s=o.split("."),a=i.at(-1)?.entry.type??n,l=s[i.length];for(let{endpoints:f}of e.bridges??[]){let[p,d]=f;for(let[u,m]of [[p,d],[d,p]])if(u.fieldMap===r&&u.model===a&&Me(m)===l)return [...s.slice(0,i.length),u.on].join(".")}throw new k(`'${o}' crosses no bridge the lens declares on ${a}`,"not_in_lens")},Ys=(e,t,r,n)=>{let o=Pe(e,t,"toPrisma");return [...new Set(n.map(i=>Or(i,o,r)?tE(e,o,t,r,i):i))]},rE=(e,t,r,n)=>{if(t.length===0)return [];let o={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},{hops:i,end:s}=Te(e.lens.maps,o,t.join("."));if(!s)throw new k(`source at '${t.join(".")}': its path doesn't resolve on the field maps`,"not_in_lens");let a=[o,...i.map(p=>({mapName:p.map,modelName:p.model}))],l=t.length;for(;l>0&&!r.has(t.slice(0,l).join("."));)l--;let f=l>0?r.get(t.slice(0,l).join("."))??null:null;for(let p=l;p<t.length;p++){let d=E=>{f=E,r.set(t.slice(0,p+1).join("."),E);},u=a[p],m=j(e,u.mapName,u.modelName,t.slice(0,p)).whereClauses,y=f===null?m:[...m,f];if(y.length===0&&!n){d(null);continue}let c=O(e.lens.maps,u.mapName),g=c&&ue(c,u.modelName,t[p]);if(!g)throw new k(`source at '${t.join(".")}': '${t[p]}' isn't declared on ${u.modelName}`,"not_in_lens");let w=a[p+1],R=Me({fieldMap:u.mapName,model:u.modelName}),b=g.kind==="bridge"?ue(O(e.lens.maps,w.mapName),w.modelName,R):void 0,S=g.kind==="bridge"?b&&{field:R,entry:b}:c?Ps(c,u.modelName,t[p],g):null;if(!S&&y.length===0){d(null);continue}if(!S)throw new k(`source at '${t.join(".")}': '${t[p]}' on ${u.modelName} declares no inverse, so the clamps above can't be carried down to it`,"unsupported_clamp");let v=U(y);try{let E={field:S.field,operator:"exists"};d(S.entry.isList?{field:S.field,arrayOperator:"any",condition:v}:y.length?U([E,lo(v,S.field)]):E);}catch(E){throw E instanceof k?new k(`source at '${t.join(".")}': the clamps above can't be carried down to it \u2014 ${E.message}`,E.code):E}}return f===null?[]:[f]},am=e=>Pr(D(e)),Pr=(e,t=ri(e))=>{let r=new Map,n=o=>{let i=r.get(o)??new Map;return r.set(o,i),i};return Object.entries(t).flatMap(([o,i])=>Object.keys(i.sources).map(s=>{let a=O(i.sourceLabels,s),l=O(i.sourceGroupBys,s),f=Object.hasOwn(i.sourceFrom,s),p={mapName:i.mapName,modelName:i.model,relPath:o.split(".").slice(1)},d=j(e,p.mapName,p.modelName,p.relPath),u=(d.sourceWheres.get(s)??[]).map(A=>tn(A,e,p)),m=Xx(e,p.mapName,p.modelName,p.relPath,l??[],a),y=O(i.fields,s)?.values,c=f?d.sourcesFromMapDefaults.get(s):void 0,g=c===void 0?void 0:e.chain[c],R=[...rE(g===void 0?e:{...e,skipClampsOf:g},p.relPath,n(g),g===void 0&&!f),...u,...m,...y?[{field:s,operator:"in",value:[...y]}]:[]],b=U([...i.whereClauses,...R]),S=U([...i.whereClauses,...u,...m,...y?[{field:s,operator:"in",value:[...y]}]:[]]),v=e.lens.bridges?.length?Pe(e.lens,p.mapName,"toPrisma"):void 0,E=v?[...De(b),...a===void 0?[]:[a],...l??[]].find(A=>Or(A,v,p.modelName)):void 0,q=E!==void 0&&v?U(qa(b).filter(A=>At(A,v,p.modelName))):void 0,ce=Gs(e,[...i.whereClauses,...R],p,`source '${s}' at '${o}'`,true);if(ce)throw ce;return {path:o,visit:i,field:s,...f&&{from:"mapDefaults"},...a!==void 0&&{label:a},...l!==void 0&&{groupBy:l},where:b,rowWhere:S,...E!==void 0&&{bridged:E},...q!==void 0&&{recheck:q}}}))};var _l=(e,t)=>{for(let r of t){let n=e;for(let o of r.split("."))n=Zt(n,o,()=>({}));}return e},Xs=(e,t)=>{for(let[r,n]of Object.entries(t))Xs(Zt(e,r,()=>({})),n);return e},Dl=e=>e.whereClauses.flatMap(De),lm=(e,t)=>{let r=new Map;for(let n of t){if(n.from)continue;let o=n.path.split(".").slice(1).join("."),i=[n.field,...n.label===void 0?[]:[n.label],...n.groupBy??[],...De(n.rowWhere)];r.set(o,[...r.get(o)??[],...n.bridged===void 0?i:Ys(e.lens,n.visit.mapName,n.visit.model,i)]);}return r},pm=(e,t)=>e.get(t.relPath.join("."))??[],nE=(e,t,r)=>_l(Xs({},r??{}),Dl(j(e,t.mapName,t.modelName,t.relPath))),fm=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]}),Fl=(e,t,r)=>({...r,relPath:[...e.relPath,t]}),oE=(e,t,r,n)=>{if(!r.whereClauses.length)return;let o=U(r.whereClauses),i=Gs(e,r.whereClauses,t,`toLensSelect: the clamp on '${t.relPath.join(".")}'`,false);if(i)throw i;if(e.inspect)return;let s=zs(`toLensSelect: the clamp on '${t.relPath.join(".")}'`,()=>ti(o,{...n,map:e.lens,mapName:t.mapName,model:t.modelName})),{where:a}=s.steps[0];return Object.keys(a).length?a:void 0},iE=(e,t,r,n)=>{let o=T(e,n.type)?.fields??{},i=a=>{let l=a===void 0?void 0:O(o,a);return l&&!L(l)?a:void 0},s=e?Ps(e,t,r,n):null;return i(n.toFields?.[0])??i(s?.entry.fromFields?.[0])??i("id")},dm=(e,t,r,n,o,i)=>{let s=T(O(e.lens.maps,t.mapName),t.modelName)?.fields??{},a=j(e,t.mapName,t.modelName,t.relPath),l=r==="paths"?n:_l(Xs({},n),[...Dl(a),...pm(i,t)]),f={};for(let[p,d]of Object.entries(s)){let u=r!=="paths"&&Ct(a,p),m=O(l,p);if(!u&&m===void 0||d.kind==="bridge")continue;if(d.kind!=="object"){f[p]=true;continue}let y=u?"declared":"paths";if(y==="paths"&&m===void 0)continue;let c=Fl(t,p,{mapName:t.mapName,modelName:d.type}),g=dm(e,c,y,m??{},o,i),w=d.isList&&y!=="paths"&&m===void 0?oE(e,c,j(e,c.mapName,c.modelName,c.relPath),o):void 0,R=Object.keys(g).length?void 0:iE(O(e.lens.maps,t.mapName),t.modelName,p,d),b=R===void 0?g:{[R]:true};Object.keys(b).length&&(f[p]={select:b,...w&&{where:w}});}return f},um=(e,t={})=>jl(D(e),t),jl=(e,t={},r=Pr(e))=>{let n=dm(e,fm(e),"declared",{},t,lm(e,r));if(!Object.values(n).some(o=>o===true)){let o=O(T(O(e.lens.maps,e.lens.mapName),e.lens.model)?.fields,"id");o&&!L(o)&&(n.id=true);}return {select:n}},Ll=(e,t)=>e==null?e:Array.isArray(e)?e.flatMap(r=>{let n=typeof r=="object"&&r!==null?t(r):null;return n===null?[]:[n]}):typeof e=="object"?t(e):null,Ml=(e,t,r,n)=>{let o={},i=T(O(e.lens.maps,t.mapName),t.modelName);for(let[s,a]of Object.entries(n)){if(!Object.hasOwn(r,s))continue;let l=O(i?.fields,s),f=l?ot(l,t.mapName):null;o[s]=f?Ll(r[s],p=>Ml(e,Fl(t,s,f),p,a)):Pl(l,r[s]);}return o},cm=(e,t,r,n,o,i,s)=>{let a=j(e,t.mapName,t.modelName,t.relPath);if(!a.whereClauses.every(d=>he(d,r,i)===true))return null;let l=T(O(e.lens.maps,t.mapName),t.modelName)?.fields??{},f=o?_l(Xs({},n),[...Dl(a),...pm(s,t)]):{},p={};for(let[d,u]of Object.entries(l)){if(!Object.hasOwn(r,d))continue;let m=O(f,d),y=ot(u,t.mapName);if(!y){(Ct(a,d)||m!==void 0)&&(p[d]=Pl(u,r[d]));continue}let c=Fl(t,d,y);if(Ct(a,d)){let g=!Array.isArray(r[d])||m!==void 0;p[d]=Ll(r[d],w=>cm(e,c,w,m??{},o,i,s)??(o&&g?Ml(e,c,w,nE(e,c,m)):null));}else m!==void 0&&(p[d]=Ll(r[d],g=>Ml(e,c,g,m)));}return p},mm=(e,t,{keepClampColumns:r=false,...n}={})=>{let o=D(e),i=fm(o),s=r?lm(o,Pr(o)):new Map;return t.flatMap(a=>{let l=cm(o,i,a,{},r,n,s);return l===null?[]:[l]})};var sE="materializeSources needs fetched or keepClampColumns rows, not viewer rows",Vl=(e,t,r)=>new C(`${e}: a row at '${t}' ${r}${r.includes(":")?" \u2014 rows across a bridge hold the far side inline under its bridge field":""}`),oi=(e,t,r,n,o,i=sE)=>{for(let s of o){let a=[r];for(let{index:l,field:f,entry:p,next:d}of Sr(e.lens.maps,t,s)){if(!p)break;let u=s.split(".").slice(0,l+1).join("."),m=[];for(let y of a){if(y===null||typeof y!="object")continue;if(!Object.hasOwn(y,f))throw Vl(i,n,`lacks '${u}', which a read needs`);let c=y[f];if(d&&c==null&&p.fromFields?.some(g=>{let w=y[g];return w!=null}))throw Vl(i,n,`'${u}' is null while its key is set \u2014 a projection hid the row`);if(!(!d||c===null||c===void 0)){if(Array.isArray(c)!==(p.isList===true))throw Vl(i,n,`'${u}' holds ${Array.isArray(c)?"a list where it names one row":"one row where it names a list"}`);m.push(...Array.isArray(c)?c:[c]);}}if(!d)break;a=m;}}},Il=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};return [r,...Te(e.lens.maps,r,t.split(".").slice(1).join(".")).hops.map(n=>({mapName:n.map,modelName:n.model,relPath:n.relPath}))]},aE=(e,t,r,n)=>{let o=r.split(".").slice(1),i=Il(e,r),s=(l,f)=>{let p=i[l],d=j(e,p.mapName,p.modelName,p.relPath).whereClauses,u=U(d),m=d.flatMap(De),y=[e.lens.model,...o.slice(0,l)].join(".");return f.filter(c=>(oi(e,p,c,y,m),he(u,c,n)===true))},a=s(0,t);for(let[l,f]of o.entries()){let p=[],d=[e.lens.model,...o.slice(0,l)].join(".");for(let u of a){oi(e,i[l],u,d,[f]);let m=ge(u,f);Array.isArray(m)?p.push(...m):m!=null&&p.push(m);}a=s(l+1,p);}return {rows:a,visit:i[i.length-1]}},gm=(e,t,r)=>{let n=D(e);return Pr(n).map(({path:o,visit:i,field:s,from:a,label:l,groupBy:f,rowWhere:p})=>{if(a)throw new C(`materializeSources: '${o}.${s}' offers its model's own source, which a fetched collection can't hold \u2014 query it with toSourceQueries and materializeSourceQuery.`);let d=[s,...De(p),...l===void 0?[]:[l],...f??[]],u=new Map,m=aE(n,t,o,r);for(let y of m.rows)oi(n,m.visit,y,o,d),he(p,y,r)===true&&Qs(u,y,s,l===void 0?void 0:ni(y,l),f===void 0?void 0:Js(y,f));return {path:o,mapName:i.mapName,model:i.model,field:s,options:Zs(u)}})};var ea={value:"value",query:"query"},ym=(e,t,r={})=>{let{rowShape:n="prisma",lens:o,order:i=ea.value,...s}=r,a=n==="sql",{recheck:l}=e,f=y=>false,p=y=>true;if(l!==void 0){if(o===void 0)throw new C(`materializeSourceQuery: '${e.path}.${e.field}' reads across a bridge \u2014 its rows are candidates; pass { lens } with rows holding the far side`);let y=D(o),c=Il(y,e.path).at(-1);if(!c||c.mapName!==e.mapName||c.modelName!==e.model)throw new C(`materializeSourceQuery: the lens doesn't reach ${e.mapName}:${e.model} at '${e.path}' \u2014 pass the lens the query was compiled from`);let g=Pe(y.lens,e.mapName,"toPrisma");f=b=>g!==void 0&&Or(b,g,e.model);let w=[...De(l),...e.label!==void 0&&f(e.label)?[e.label]:[],...(e.groupBy??[]).filter(f)],R="materializeSourceQuery needs candidate rows holding the far side of each bridge the source reads";p=b=>(oi(y,c,b,e.path,w,R),he(l,b,s)===true);}let d=y=>e.label===void 0?void 0:a&&e.label.includes(".")&&!f(e.label)?y.__label:ni(y,e.label),u=e.groupBy?.map((y,c)=>a&&!f(y)?`__group_${c}`:y),m=new Map;for(let y of t)p(y)&&Qs(m,y,e.field,d(y),u===void 0?void 0:Js(y,u));return {path:e.path,mapName:e.mapName,model:e.model,field:e.field,options:i===ea.query?[...m.values()]:Zs(m)}};var lE=(e,t)=>`${e}::${t}`,pE=(e,t,r)=>{let n=e.get(t);if(!n){e.set(t,r.values?{...r,values:[...r.values]}:r);return}let o=n;if(r.values&&n.values){let i=new Set([...n.values,...r.values]);o={...o,values:[...i]};}else !r.values&&n.values&&(o={...o,values:void 0});r.groupBy!==void 0&&o.groupBy===void 0&&(o={...o,groupBy:r.groupBy}),o!==n&&e.set(t,o);},hm=(e,t={})=>ql(D(e),t),ql=(e,t={})=>{let{lens:r}=e,n=new Map;for(let l of t.sourceValues??[]){let f=`${l.mapName}::${l.model}::${l.field}`,p=n.get(f)??new Map;for(let d of l.options)p.set(Cl(d.groups,d.value),d);n.set(f,p);}let o=new Map;for(let{at:l,effect:f}of Xt(e)){let{mapName:p,modelName:d}=l,u=T(O(r.maps,p),d);if(!u)continue;let m=lE(p,d),y=o.get(m);y||(y={mapName:p,modelName:d,fields:new Map},o.set(m,y));let c=kl(e,f,l,u,g=>{let w=n.get(`${p}::${d}::${g}`);return w&&[...w.values()]});for(let[g,w]of Object.entries(c)){let R=w.groupBy,b=y.fields.get(g)?.groupBy;if(R!==void 0&&b!==void 0&&JSON.stringify(b)!==JSON.stringify(R))throw new k(`projectLens: '${d}.${g}' is grouped by different axes on different paths ([${b}] vs [${R}]) \u2014 one surface field cannot carry two partition namespaces`,"invalid_source");pE(y.fields,g,w);}}let i={};for(let{mapName:l,modelName:f,fields:p}of o.values()){let d=O(i,l);d||(d={models:{}},i[l]=d);let u={},m=new Map;for(let[y,c]of p)if(u[y]=c.options===void 0&&c.values?{...c,options:c.values.map(g=>({value:g,label:g}))}:c,c.kind==="enum"&&c.values){let g=m.get(c.type)??new Set;for(let w of c.values)g.add(w);m.set(c.type,g);}d.models[f]={...T(O(r.maps,l),f),fields:u};for(let[y,c]of m)d.enums??={},d.enums[y]=[...c];}let s=r.bridges?.filter(l=>{let[f,p]=l.endpoints,d=ue(O(i,f.fieldMap),f.model,Me(p)),u=ue(O(i,p.fieldMap),p.model,Me(f));return d!==void 0||u!==void 0}),a={maps:i};return s&&s.length>0&&(a.bridges=s),{...a,mapName:r.mapName,model:r.model}};var wm=(e,t,r,n,o)=>{if(e===void 0)return;let i=ao(e),s=n==="root.where"?null:i.bare;if(s!==null){o.push({path:n,code:"invalid_value_source",message:pl(s).message});return}let{escaping:a}=i;if(a!==null){o.push({path:n,code:"scope_out_of_bounds",message:fl(a).message});return}let l=new Set,f={...t,clamp:t.chain.length===0};for(let{mapName:p,modelName:d,relPath:u}of r)for(let m of zo(e,f,p,d,u)){let y=`'${m.path}' ${m.message}`;l.has(y)||(l.add(y),o.push({path:n,code:m.code,message:y}));}},fE=(e,t,r,n,o,i)=>{let s={...r,chain:[...r.chain,t]},a=new Set;for(let l of n){let f=j(s,l.mapName,l.modelName,l.relPath);for(let[p,d]of Object.entries(e.sources??{})){let u=Nr(d);for(let m of ["label","groupBy"]){if(u[m]===void 0||a.has(`${p}|${m}`))continue;let y=m==="label"?u.label:Qo(u.groupBy),c=m==="label"?f.sourceLabels.get(p):f.sourceGroupBys.get(p);if(JSON.stringify(y)!==JSON.stringify(c))continue;let w=(typeof c=="string"?[c]:c??[]).map(R=>Yo(s,l,R)).find(R=>R!==null);if(w){a.add(`${p}|${m}`),i.push({path:`${o}.sources.${p}`,code:"invalid_source",message:`${m} '${String(u[m])}' crosses '${w}', a relation the lens does not show there (not turned on, or omitted)`});continue}mo(s,f,l,p,m)||(a.add(`${p}|${m}`),i.push({path:`${o}.sources.${p}`,code:"invalid_source",message:`${m} '${String(u[m])}' reads a column hidden by another layer`}));}}}},dE=(e,t,r,n)=>{for(let o of r){if(!t&&o.picks&&!o.picks.includes(e))return "not in ancestor's picks";if(o.omits?.includes(e))return "was omitted by ancestor"}return !t&&n?.picks&&!n.picks.includes(e)?"not visible from defaults.picks":n?.omits?.includes(e)?"already excluded by defaults":null},uE=(e,t,r,n,o,i,s,a,l,f,p,d,u=false)=>{let m=e.omits?.some(c=>{let g=O(i,c);return g===void 0||!L(g)});e.picks&&m&&f.push({path:`${l}`,code:"conflicting_selection",message:"cannot specify both picks and omits of a column"});for(let c of ["picks","omits"])for(let g of e[c]??[]){let w=O(i,g);if(!w){f.push({path:`${l}.${c}`,code:"not_in_lens",message:`field '${g}' not on model`});continue}let R=L(w);if(R&&c==="picks"){f.push({path:`${l}.picks`,code:"wrong_kind",message:`'${g}' is a relation: picks names columns; turn a relation on with \`relations\``});continue}let b=dE(g,R,t,r);b&&f.push({path:`${l}.${c}`,code:"not_visible",message:`'${g}' ${b}`});}let y=(c,g,w)=>{let R=O(i,g);if(!R){f.push({path:`${l}.${c}`,code:"not_in_lens",message:`field '${g}' not on model`});return}if(R.kind!=="enum"){f.push({path:`${l}.${c}`,code:"wrong_kind",message:`field '${g}' is not an enum field`});return}let b=zr(R,a);for(let S of w)b&&!b.includes(S)&&f.push({path:`${l}.${c}.${g}`,code:"value_not_allowed",message:`'${S}' is not a known value of enum '${R.type}'`});};for(let[c,g]of Object.entries(e.enumPicks??{}))y("enumPicks",c,g);for(let[c,g]of Object.entries(e.enumOmits??{}))y("enumOmits",c,g);wm(e.where,p,d,`${l}.where`,f);for(let[c,g]of Object.entries(e.sources??{})){let w=O(i,c);if(!w){f.push({path:`${l}.sources`,code:"not_in_lens",message:`field '${c}' not on model`});continue}if(L(w)){f.push({path:`${l}.sources.${c}`,code:"wrong_kind",message:`'${c}' is a relation: a source offers a column's values`});continue}let R;try{R=Nr(g);}catch(E){if(!(E instanceof k))throw E;f.push({path:`${l}.sources.${c}`,code:E.code,message:E.message});continue}let b=R.from;if(b!==void 0){let E=b!=="mapDefaults"?`from takes 'mapDefaults', not '${String(b)}'`:u?"a mapDefaults source is what a path source's from: 'mapDefaults' points at; it can't point itself":R.label!==void 0||R.groupBy!==void 0?"a from: 'mapDefaults' source takes the model source's label and groupBy":null;E&&f.push({path:`${l}.sources.${c}`,code:"invalid_source",message:E});}let S=R.label?.includes(".")?R.label:void 0;if(R.label!==void 0)if(S){let E=Hs(S,n,o,s,"label");E&&f.push({path:`${l}.sources.${c}`,code:"invalid_source",message:`${E}`});}else {let E=O(i,R.label);E?L(E)&&f.push({path:`${l}.sources.${c}`,code:"wrong_kind",message:`label '${R.label}' is a relation, not a column`}):f.push({path:`${l}.sources.${c}`,code:"not_in_lens",message:`label column '${R.label}' not on model`});}let v=Qo(R.groupBy);if(v!==void 0||S!==void 0){let E=/^__(group(_\d+)?|label)$/;(E.test(c)||R.label!==void 0&&E.test(R.label))&&f.push({path:`${l}.sources.${c}`,code:"invalid_source",message:"'__group*' / '__label' names are reserved on grouped or path-labeled sources (sql column aliases)"});}if(v!==void 0){for(let q of v){let ce=Hs(q,n,o,s,"groupBy");ce&&f.push({path:`${l}.sources.${c}`,code:"invalid_source",message:`${ce}`});}let E=JSON.stringify(v);for(let q of t){let ce=O(q.sources,c);if(ce===void 0)continue;let A=Qo(Nr(ce).groupBy);A!==void 0&&JSON.stringify(A)!==E&&f.push({path:`${l}.sources.${c}`,code:"not_visible",message:`groupBy [${v}] conflicts with an ancestor layer's groupBy [${A}]`});}}wm(R.where,p,d,`${l}.sources.${c}`,f);}},cE=(e,t,r,n,o)=>{for(let[i,s]of Object.entries(t)){let a=O(r,i);if(!a){o.push({path:`mapDefaults.${e}.enums.${i}`,code:"not_in_lens",message:"enum not in registry"});continue}let l=null,f=new Set;for(let d of n){let u=d[i];if(u&&(u.picks&&(l=js(l,u.picks)),u.omits))for(let m of u.omits)f.add(m);}let p=d=>!(f.has(d)||l&&!l.has(d));for(let d of s.picks??[])a.includes(d)?p(d)||o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"not_visible",message:`'${d}' not visible from ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"value_not_allowed",message:`'${d}' not a known value`});for(let d of s.omits??[])a.includes(d)?p(d)||o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"not_visible",message:`'${d}' already excluded by ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"value_not_allowed",message:`'${d}' not a known value`});}},mE=(e,t,r,n,o,i,s)=>{let a=j(t,r.mapName,r.modelName,r.relPath);for(let l of ["enumPicks","enumOmits"])for(let[f,p]of Object.entries(e[l]??{})){let d=O(n,f);if(d?.kind!=="enum")continue;let u=zr(d,o)??[],m=Ds(a,f)??u;for(let y of p)u.includes(y)&&!m.includes(y)&&s.push({path:`${i}.${l}.${f}`,code:"not_visible",message:`'${y}' is not visible (not allowed by the inherited enum narrowing)`});}},bm=(e,t,r,n)=>e.map(o=>({mapName:n,modelName:r,relPath:[...o.relPath,t]})),Bl=(e,t,r,n,o,i,s,a,l,f,p)=>{let d=O(o,i),u=T(d,s);if(!u)return;let m=n.length===0,y={...f,chain:[...f.chain,r],unvetted:true},c=p.isDefault?void 0:O(O(r.mapDefaults,i)?.models,s),w=[...n.map(S=>O(O(S.mapDefaults,i)?.models,s)).filter(S=>S!==void 0),...t],R={mapName:i,modelName:s,relPath:ll};uE(e,w,c,o,i,u.fields,s,d?.enums,a,l,f,m?p.isDefault?[R,...p.parent]:p.parent:p.composed,p.isDefault),mE(e,p.isDefault?f:{...f,chain:[...f.chain,{parent:r.parent,mapDefaults:r.mapDefaults}],unvetted:true},p.isDefault?R:p.parent[0]??R,u.fields,d?.enums,a,l),fE(e,r,f,p.composed,a,l);let b={...f,chain:[...f.chain,r]};if(!p.isDefault)for(let[S,v]of Object.entries(e.sources??{}))!Zo(v)||v.from!=="mapDefaults"||Vs(b,i,s,S)||l.push({path:`${a}.sources.${S}`,code:"invalid_source",message:Is([pt(r).model,...p.parent[0]?.relPath??[]].join("."),i,s,S).message});for(let[S,v]of Object.entries(e.relations??{})){let E=O(u.fields,S);if(!E){l.push({path:`${a}.relations`,code:"not_in_lens",message:`'${S}' not on model`});continue}if(!L(E)){l.push({path:`${a}.relations`,code:"wrong_kind",message:`'${S}' is not a relation (kind=${E.kind})`});continue}let q=B=>j(f,B.mapName,B.modelName,B.relPath).relations.has(S),ce=B=>j(y,B.mapName,B.modelName,B.relPath).relations.has(S);if(!m&&!(p.isDefault?p.parent.some(q):p.parent.every(q))){l.push({path:`${a}.relations`,code:"not_visible",message:`'${S}' is not shown by the parent${p.isDefault?` wherever ${s} is visited`:""}: only the first narrowing over the base lens turns a relation on`});continue}let A=ot(E,i);if(!A)continue;if(!T(O(o,A.mapName),A.modelName)){l.push({path:`${a}.relations.${S}`,code:"not_in_lens",message:"target model not found in lens"});continue}let I=t.map(B=>O(B.relations,S)).filter(B=>B!==void 0);Bl(v,I,r,n,o,A.mapName,A.modelName,`${a}.relations.${S}`,l,f,{parent:bm(p.isDefault?p.parent.filter(q):p.parent,S,A.modelName,A.mapName),composed:bm(p.composed.filter(ce),S,A.modelName,A.mapName),isDefault:p.isDefault});}},Wl=e=>{let t=[];try{gE(e,t);}catch(r){if(!(r instanceof k))throw r;t.some(n=>n.code===r.code)||t.push({path:"",code:r.code,message:r.message});}return Ye(t)},gE=(e,t)=>{let r=pt(e),n=kt(e.parent),o=D(e.parent),i=Xt(o),s=[],a=u=>{try{u();}catch(m){if(!(m instanceof k))throw m;s.push(m);}},l=null,f=()=>(l??=Xt({...o,chain:[...o.chain,e],unvetted:true}),l);for(let[u,m]of Object.entries(e.mapDefaults??{})){let y=O(r.maps,u);if(!y){t.push({path:`mapDefaults.${u}`,code:"not_in_lens",message:"not in lens"});continue}let c=n.map(g=>O(g.mapDefaults,u)?.enums).filter(g=>g!==void 0);for(let[g,w]of Object.entries(m.models??{})){if(!T(y,g)){t.push({path:`mapDefaults.${u}.models.${g}`,code:"not_in_lens",message:"not in fieldMap"});continue}let b=n.map(E=>O(O(E.mapDefaults,u)?.models,g)).filter(E=>E!==void 0),S=E=>E.map(({at:q})=>q).filter(q=>q.mapName===u&&q.modelName===g),v=[];a(()=>{v=S(f());}),a(()=>Bl(w,b,e,n,r.maps,u,g,`mapDefaults.${u}.models.${g}`,t,o,{parent:S(i),composed:v,isDefault:!0}));}m.enums&&cE(u,m.enums,y.enums,c,t);}if(e.root){let u=r.mapName,m=r.model,y=O(r.maps,u);if(!y)t.push({path:"root",code:"not_in_lens",message:`lens map '${u}' not in lens`});else if(!T(y,m))t.push({path:"root",code:"not_in_lens",message:`lens model '${m}' not in fieldMap`});else {let c=n.map(w=>w.root).filter(w=>w!==void 0),g={mapName:u,modelName:m,relPath:[]};a(()=>Bl(e.root,c,e,n,r.maps,u,m,"root",t,o,{parent:[g],composed:[g],isDefault:!1}));}}for(let u of Ec(e))t.push({path:"bindings",code:"invalid_binding",message:u});let p={...o,chain:[...o.chain,e],inspect:true},d;a(()=>{d=Pr(p,ri(p));}),a(()=>ql(p)),a(()=>jl(p,{},d)),a(()=>{let u=new Map;for(let{at:m}of f()){u.set(m.relPath.join("."),m),a(()=>Tl(p,m.relPath.join(".")));let y=m.relPath.at(-1),c=u.get(m.relPath.slice(0,-1).join("."));if(y===void 0||!c)continue;let w=ue(O(r.maps,c.mapName),c.modelName,y)?.isList?{field:y,arrayOperator:"any",condition:!0}:{field:y,operator:"exists"};a(()=>tn(w,p,c));}});for(let u of s)t.some(m=>u.message.includes(m.message))||t.push({path:"",code:u.code,message:u.message});},ta=e=>en(Wl(e),"validateNarrowing");function Sm(e,{by:t="path",...r}={}){return t==="model"?hm(e,r):om(e,r)}var Rm=(e,t,r,n={})=>{let o=D(e),{resolution:i}=rn(o,Tt(o),r);if(i.outcome!=="resolved")return {ok:false,reason:i.outcome};let{hops:s,terminal:a,jsonSubPath:l}=i;if(L(a.entry))return {ok:false,reason:"relation"};if(s.some(d=>d!==a&&d.entry.isList))return {ok:false,reason:"list"};let f=(d,u)=>u!==null&&typeof u=="object"&&j(o,d.mapName,d.model,d.relPath).whereClauses.every(m=>he(m,u,n)===true),p=f(s[0],t)?t:null;for(let[d,u]of s.entries()){if(p===null||typeof p!="object")return {ok:true,value:null};let m=O(p,u.field);if(u===a)return {ok:true,value:l.length?ge(m,l.join(".")):m};p=f(s[d+1],m)?m:null;}return {ok:true,value:null}};var yE=e=>"maps"in e,Om=(e,t)=>{let r=i=>{let s=O(t,i);if(!s)throw new Error(`composeLens: no stored lens '${i}'`);return s},n=[...r(e).parents,e];if(new Set(n).size!==n.length)throw new Error(`composeLens: '${e}' lists a layer twice in its parents`);let o=null;for(let[i,s]of n.entries()){let a=r(s);if(Object.hasOwn(a,"parent"))throw new Error(`composeLens: '${s}' carries a parent; a layer composes only through \`parents\``);let{id:l,parents:f,...p}=a;if(f.join("\0")!==n.slice(0,i).join("\0"))throw new Error(`composeLens: '${s}' composes with [${f.join(", ")}], not [${n.slice(0,i).join(", ")}] as '${e}' lists`);if(yE(a)!==(i===0))throw new Error(i===0?`composeLens: '${s}' is not a base lens, so it can't head '${e}''s parents`:`composeLens: '${s}' is a base lens, so it can only head a chain`);if(o===null){o=p;continue}let u={parent:o,...p};ta(u),o=u;}return o},xm=(e,t)=>{let r=lt(e)?[]:kt(e);if(t.length!==r.length+1)throw new Error(`storeLens: the lens has ${r.length+1} layers, base included, but ${t.length} ids`);return [{...pt(e),id:t[0],parents:[]},...r.map(({parent:n,...o},i)=>({...o,id:t[i+1],parents:t.slice(0,i+1)}))]};var Em=e=>e instanceof Date?e.toISOString():Array.isArray(e)&&e.some(t=>t instanceof Date)?e.map(Em):e,F=(e,t)=>(e.params.push(Em(t)),`$${++e.paramIndex}`);var er=(e,t,{jsonb:r=false}={})=>{let n=()=>({sql:hl(e,void 0,r),shape:e.includes(".")?"json-path":"unknown"});if(!t.map||!t.currentModel||!t.currentAlias)return n();let o=ie(e,t.map,t.currentModel);if(o.kind==="past-scalar")throw Kn(e,o.column);if(o.kind==="bridge")throw new Error(`'${e}' crosses a bridge to another source; toSql() has no column for it`);if(o.kind==="fallback"||o.entry.kind==="object"&&o.entry.isList)return n();let i=o.hops.find(p=>p.entry.isList);if(i)throw Un(e,i);let s=t.currentAlias;for(let p of o.hops){let d=$m(t,s,p);if(!d)return n();s=d;}let a=Hr(o);if(o.kind==="direct"&&o.entry.kind==="object"){let p={field:o.column,entry:o.entry,from:o.model},d=Er(t.map,o.model,o.entry),u=$m(t,s,p);return !d||!u?n():{sql:`${se(u)}.${se(d[0].there)}`,shape:a}}let l=o.kind==="json-path"?[o.column,...o.jsonPath]:[o.column],f=hl(l.join("."),s,r);return {sql:a==="json"&&!r?`NULLIF(${f}, 'null'::jsonb)`:f,shape:a}},Mt=(e,t,r)=>er(e,t,r).sql,$m=(e,t,r)=>{let n=`${t}.${r.field}`,o=e.joinRegistry?.get(n);if(o)return o;if(!e.joinCounter||!e.map)return null;let i=`t${e.joinCounter.n+1}`,s=hE(e.map,r.from,t,r.entry,i);return s?(e.joinCounter.n+=1,e.joins?.push(s),e.joinRegistry?.set(n,i),i):null},hE=(e,t,r,n,o)=>{let i=n.type,s=T(e,i)?.dbName??i,a=Er(e,t,n);if(!a)return null;let l=a.map(({here:f,there:p})=>`${se(o)}.${se(p)} = ${se(r)}.${se(f)}`).join(" AND ");return `LEFT JOIN ${se(s)} AS ${se(o)} ON ${l}`};var tr={type:"value",value:null},_t=e=>e.type==="value"&&(e.value===null||e.value===void 0),wE=(e,t)=>{let r=M(e)??{depth:1,path:e};if(r.depth>1)throw new Error($o(e,"toSql"));let n=er(r.path,t);if(n.shape==="relation")throw new Error(`'${e}' is a relation; a value ref reads a column`);return {type:"column",...n}},ve=(e,t)=>Fo(e,{value:r=>({type:"value",value:r}),path:r=>wE(r,t),bind:(r,n)=>({type:"value",value:us(r,n,"toSql")})}),sn=e=>t=>{let r=ve(t,e);if(r.type==="column")throw new Error(`'${t.path}' is a row ref`);return r.value},ut=e=>Ht(e.dateConfig??{},sn(e));var bE={lt:"<",lte:"<=",gt:">",gte:">=",equals:"="},go=(e,t)=>{let r=pr(e,t);return r?{symbol:bE[r],negated:W.includes(e)}:void 0},vm=(e,t)=>e.type==="column"?e.sql:F(t,e.value),Fe=(e,t)=>`(${t} OR ${e} IS NULL)`,Dt=(e,t,r=true)=>t&&r?`${e} IS NULL`:"FALSE",ra=(e,t,r,n,o)=>{if(_t(r))return Dt(e,n);let i=`${e} ${t} ${vm(r,o)}`;return n?Fe(e,i):i},ii=(e,t,r,n,o=true)=>{if(!t||t.some(_t))return Dt(e,r,o);let[i,s]=t.map(d=>vm(d,n)),a=t.some(d=>d.type==="column"),l=a?"SYMMETRIC ":"";if(!r)return `${e} BETWEEN ${l}${i} AND ${s}`;let f=`${e} NOT BETWEEN ${l}${i} AND ${s}`,p=a?`(${f} AND ${i} IS NOT NULL AND ${s} IS NOT NULL)`:f;return o?Fe(e,p):p};var Pm=()=>{let e=Xe.get("sql.dialect");if(!$d(e))throw new C(`toWhereSql: sql.dialect '${String(e)}' is not a SQL dialect \u2014 ${Object.values(kn).join(", ")} are`);return e},Z=e=>new Error(`toWhereSql: ${e} has no SQL form here \u2014 it writes ${Ca.join(", ")}, all and any, and ${_a.join(", ")} over a to-many relation.`),km=(e,t)=>Ul(e,t,""),Nm=(e,t,r,n)=>{let o=Object.hasOwn(e,n)?e[n]:void 0;if(typeof o!="string"||o==="")throw new C(`toWhereSql: no ${r} for '${n}' in \`${t}\``);return o},Ul=(e,t,r,n={clamps:()=>[]})=>{Pm();let{columns:o,tables:i={},map:s,mapName:a,model:l}=t??{};if(typeof o!="object"||o===null)throw new C("toWhereSql: `columns` maps each field path to its SQL");if(typeof i!="object"||i===null)throw new C("toWhereSql: `tables` maps each to-many relation path to its table");if(!s||!l)throw new C("toWhereSql: `map` and `model` are required \u2014 a literal is typed by its column, and a date, Json or list value is refused by it");let f=Pe(s,a,"toWhereSql");if(!T(f,l))throw new C(`toWhereSql: the map has no model '${l}'`);return yo(e,{map:f,model:l,column:p=>Nm(o,"columns","column",`${r}${p}`),table:p=>Nm(i,"tables","table",`${r}${p}`),clamps:"clamps"in n?n.clamps:()=>[],joined:"joined"in n?n.joined:null,joinedRow:null})},yo=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";let r=e;switch(le(r)){case "all":{let n=r.all;return n.length?`(${n.map(o=>yo(o,t)).join(" AND ")})`:"TRUE"}case "any":{let n=r.any;return n.length?`(${n.map(o=>yo(o,t)).join(" OR ")})`:"FALSE"}case "field":return RE(e,t);case "if":throw Z("if / then / else");case "array":return SE(e,t);case "aggregate":throw Z("aggregate");case "date":throw Z(`dateOperator '${String(r.dateOperator)}'`);default:throw Z("a condition that is not exactly one node kind")}},SE=(e,t)=>{let{arrayOperator:r,field:n}=e;if(!_a.includes(r))throw Z(`arrayOperator '${r}'`);if(Ae(e))throw Z(`a window (filter / orderBy / take / skip) on '${n}'`);if(!n)throw Z(`the fieldless arrayOperator '${r}'`);let o=ie(n,t.map,t.model);if(o.kind==="fallback")throw new Error(`toWhereSql: '${n}' is not a field the map declares on ${t.model}`);if(o.kind==="bridge")throw Z(`'${n}', which crosses a bridge`);if(o.hops.length)throw Z(`arrayOperator '${r}' on '${n}', behind the relation '${o.hops[0].prefix}'`);if(o.kind!=="direct"||Hr(o)!=="relations")throw Z(`arrayOperator '${r}' on '${n}', which is not a to-many relation`);let i=Er(t.map,o.model,o.entry);if(!i)throw Z(`'${n}', whose relation keys the map does not declare`);if(Xi.includes(r)&&e.condition===void 0)throw Ie(r);if(t.joinedRow!==null)throw new Error(`toWhereSql: arrayOperator '${r}' on '${n}' inside an any over the joined '${t.joinedRow}' \u2014 a joined row's own to-many relations have no join here; compile with toMany: 'subquery'`);let s={map:t.map,model:o.entry.type,column:p=>t.column(`${n}.${p}`),table:p=>t.table(`${n}.${p}`),clamps:p=>t.clamps(`${n}.${p}`),joined:t.joined,joinedRow:null};if(t.joined){if(Id.includes(r))throw new Error(`toWhereSql: arrayOperator '${r}' on '${n}', a relation the caller joins, holds when it has no rows \u2014 that takes an anti-join, not the topic's join. Only notEmpty and any(condition) read a joined relation; compile with toMany: 'subquery' for the rest`);t.joined(n,r);let p=`${s.column(i[0].there)} IS NOT NULL`;return r!==x.any?p:`(${p} AND ${yo(e.condition,{...s,joinedRow:n})})`}let a=[...i.map(({here:p,there:d})=>`${s.column(d)} = ${t.column(p)}`),...t.clamps(n).map(({where:p,clamps:d})=>`(${yo(p,{...s,clamps:d})})`)],l=p=>`(SELECT 1 FROM ${t.table(n)} WHERE ${[...a,...p?[p]:[]].join(" AND ")})`,f=()=>`(${yo(e.condition,s)})`;switch(r){case x.any:return `EXISTS ${l(f())}`;case x.none:return `NOT EXISTS ${l(f())}`;case x.all:return `NOT EXISTS ${l(`${f()} IS NOT TRUE`)}`;case x.empty:return `NOT EXISTS ${l()}`;default:return `EXISTS ${l()}`}},RE=(e,t)=>{if(!Ca.includes(e.operator))throw Z(`operator '${e.operator}'`);if(e.bind!==void 0)throw Z(`bind '${e.bind}' on '${e.field}'`);if(e.path!==void 0)throw Z(`comparing '${e.field}' with the column '${e.path}'`);if(e.offset!==void 0)throw Z(`an offset on '${e.field}'`);if(e.coerceType!==void 0)throw Z(`coerceType on '${e.field}'`);if(oe(e.caseInsensitive))throw Z(`a case-insensitive comparison on '${e.field}'`);if(M(e.field))throw Z(`the scoped field '${e.field}'`);let r=ie(e.field,t.map,t.model),n=OE(e,r,t),[o]=r.kind==="direct"?Ms(e,Ge(r.entry)):[];if(o)throw new Error(`toWhereSql: ${o.message}`);if(e.operator===h.exists)return `${n} IS NOT NULL`;if(e.operator===h.notExists)return `${n} IS NULL`;if(e.value===void 0)throw new Error("No value, path or bind specified");let i=fo(e,e.value,r,"toWhereSql",()=>qe);if(Ee(e,i))return Dt(n,W.includes(e.operator));let s=a=>xE(a,e.field);switch(e.operator){case h.equals:return i===null?`${n} IS NULL`:`${n} = ${s(i)}`;case h.notEquals:return i===null?`${n} IS NOT NULL`:Fe(n,`${n} <> ${s(i)}`);case h.in:{let{values:a,hasNull:l}=Qe(Am(e,i));if(!a.length)return l?`${n} IS NULL`:"FALSE";let f=`${n} IN (${a.map(s).join(", ")})`;return l?Fe(n,f):f}default:{let{values:a,hasNull:l}=Qe(Am(e,i));if(!a.length)return l?`${n} IS NOT NULL`:"TRUE";let f=`${n} NOT IN (${a.map(s).join(", ")})`;return l?`(${f} AND ${n} IS NOT NULL)`:Fe(n,f)}}},OE=(e,t,r)=>{if(t.kind==="fallback")throw new Error(`toWhereSql: '${e.field}' is not a field the map declares on ${r.model}`);if(t.kind==="past-scalar")throw Kn(e.field,t.column);if(t.kind==="bridge")throw Z(`'${e.field}', which crosses a bridge`);let n=t.hops.find(s=>s.entry.isList);if(n)throw Un(e.field,n);let o=Hr(t),i=Qt(e);if(r.joinedRow!==null&&(t.hops.length||o==="relation"))throw new Error(`toWhereSql: '${e.field}' inside an any over the joined '${r.joinedRow}' reads the relation '${t.hops[0]?.prefix??e.field}' \u2014 a joined row's own relations have no join here; compile with toMany: 'subquery'`);if(o==="relation"&&t.kind==="direct"){if(!i)throw ur(e.field);let s=Er(r.map,t.model,t.entry);if(!s)throw Z(`'${e.field}', whose relation keys the map does not declare`);return r.column(`${e.field}.${s[0].there}`)}if(o==="relations")throw new Error(`toWhereSql: '${e.field}' is a to-many relation \u2014 its rows take an arrayOperator rule: { field: '${e.field}', arrayOperator: 'notEmpty' } for a row${r.joined?"; for no rows, compile with toMany: 'subquery'":", 'empty' for none"}`);if(o==="json"||o==="json-path")throw Z(`the Json value '${e.field}'`);if(i)return r.column(e.field);if(o==="instant")throw Z(`the date '${e.field}'`);if(o==="list")throw Z(`the list '${e.field}'`);return r.column(e.field)},Am=(e,t)=>{if(!Array.isArray(t))throw new Error(`toWhereSql: '${e.operator}' on '${e.field}' takes a list of values`);return t},xE=(e,t)=>{if(typeof e=="string"){let r=e.replace(/'/g,"''");return `'${Pm()===kn.mysql?r.replace(/\\/g,"\\\\"):r}'`}if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return String(e);if(typeof e=="boolean")return e?"TRUE":"FALSE";throw Z(`the value ${e instanceof Date?"a Date":JSON.stringify(e)} for '${t}'`)};var EE=(e,t,r)=>{H(r,(n,o)=>{if(typeof n.field!="string")return;let i=Yo(e,o,n.field);if(i!==null)throw new Error(`toLensWhereSql: '${n.field}' at ${o.relPath.length?`'${o.relPath.join(".")}'`:"the root"} crosses '${i}', a relation the lens hides \u2014 a hop's clamps are reported at its own path, so a where may only cross hops the lens shows`);return xe(n)?Te(e.lens.maps,o,n.field).end??false:void 0},t);},Lm=(e,t,r)=>{let{end:n}=Te(e.lens.maps,t,r);if(!n)return null;let{pathWheres:o,modelWheres:i}=j(e,n.mapName,n.modelName,n.relPath);return {end:n,clamps:[...o.map(s=>({...s,isDefault:false})),...i.map(s=>({...s,isDefault:true}))]}},Mm=(e,t,r)=>n=>{let o=Lm(e,t,n);return o?o.clamps.filter(i=>i.layer<r).map(i=>({where:i.where,clamps:Mm(e,o.end,i.layer)})):[]},Tm=(e,t,r,n)=>{let o=e.map(({where:i,layer:s})=>Ul(i,t,r,n(s)));return o.length===1?o[0]:`(${o.join(" AND ")})`},$E=(e,t)=>{let r=new Set,n=new Map;return o=>({joined:(i,s)=>{let a=Lm(e,t,i);if(!a)throw new Error(`toLensWhereSql: '${i}' reaches no relation`);let{end:l,clamps:f}=a,p=f.find(d=>d.layer>=o);if(p)throw new Error(`toLensWhereSql: the root where of layer ${o+1} reads '${i}' on the caller's join, whose ON carries a clamp of layer ${p.layer+1} (${p.isDefault?`${l.modelName}'s default where`:"its where"}) \u2014 check() reads a where through the clamps of the layers above its own only. Move that clamp into a narrowing above layer ${o+1}, or compile with toMany: 'subquery'`);if(f.some(d=>d.isDefault)){let d=`${l.mapName}.${l.modelName}`,u=n.get(d),m=l.mapName===t.mapName&&l.modelName===t.modelName?`the root is a ${l.modelName} too`:u!==void 0&&u!==i?`the root where also reads '${u}', which reaches ${l.modelName} too`:null;if(m!==null)throw new Error(`toLensWhereSql: the root where reads '${i}' on the caller's join, and ${l.modelName} has a default where, but ${m} \u2014 mapDefaults holds one predicate per model, which reads one table alias, and two aliases need it. Compile with toMany: 'subquery'`);n.set(d,i);}if(s===x.any){if(r.has(i))throw new Error(`toLensWhereSql: the root reads '${i}' with two any rules \u2014 on the caller's join one joined row stands for the relation, so both conditions would have to hold on the same row, where check() lets each find its own. Write one any whose condition says which row, or compile with toMany: 'subquery'`);r.add(i);}}})},Cm=(e,t)=>()=>({joined:r=>{throw new Error(`toLensWhereSql: ${e} reads the to-many relation '${r}' \u2014 with toMany: 'join' ${t}; only the root's where reads a joined relation`)}}),_m=(e,{columns:t,tables:r,toMany:n="subquery"})=>{if(n!=="subquery"&&n!=="join")throw new C(`toLensWhereSql: toMany '${String(n)}' is neither 'subquery' nor 'join'`);let o=D(e),i={root:null,relations:{},mapDefaults:{}};for(let{at:s,effect:a}of Xt(o)){let l={columns:t,tables:r,map:o.lens,mapName:s.mapName,model:s.modelName},f=p=>({clamps:Mm(o,s,p)});for(let{where:p}of [...a.pathWheres,...a.modelWheres])EE(o,s,p);if(a.pathWheres.length){let p=s.relPath.join("."),d=n==="subquery"?f:p?Cm(`the where at '${p}'`,"it sits in that relation's join ON, ahead of the joins below it"):$E(o,s),u=Tm(a.pathWheres,l,p?`${p}.`:"",d);p?i.relations[p]=u:i.root=u;}if(a.modelWheres.length){let p=Zt(i.mapDefaults,s.mapName,()=>({models:{}})),d=n==="subquery"?f:Cm(`the default where of ${s.modelName}`,`it compiles once for every path that reaches ${s.modelName}, and the join exists only where the lens shows the relation`),u=Tm(a.modelWheres,l,`${s.modelName}.`,d),m=O(p.models,s.modelName);if(m!==void 0&&m!==u)throw new Error(`toLensWhereSql: the default where of ${s.modelName} reads a to-many relation whose clamps differ between the paths that reach ${s.modelName} \u2014 a model default compiles to one predicate for every path`);p.models[s.modelName]=u;}}return i};var Dm=e=>Array.isArray(e)?e.some(Dm):typeof e=="object"&&e!==null,Fm=(e,t,r,n)=>{let o=`NULLIF(${t}, 'null'::jsonb)`,i=`jsonb_typeof(${o})`,s=`(${o} #>> '{}')`,a=b=>`${F(n,JSON.stringify(b))}::jsonb`,l=oe(e.caseInsensitive),f=b=>l?`LOWER(${b})`:b,p=W.includes(e.operator),d=b=>Fe(o,`NOT (${b})`);if(Ee(e,r))return Dt(o,p);let u=ls(e.operator,r);if(u)throw u;let m=b=>{if(Dm(b))throw V("toSql",`A case-insensitive comparison of '${e.field}' with a list holding objects`);return a(Gr(b))},y=b=>l&&typeof b=="string"?`(${i} = 'string' AND LOWER(${s}) = LOWER(${F(n,b)}))`:l&&Array.isArray(b)?`(${i} = 'array' AND LOWER(${o}::text)::jsonb = ${m(b)})`:`${o} = ${a(b)}`,c=b=>`(${i} = 'string' AND ${f(s)} LIKE ${f(F(n,b))})`,g=b=>{let S=v=>`(CASE WHEN ${i} = 'array' THEN EXISTS (SELECT 1 FROM jsonb_array_elements(${o}) AS e WHERE ${v}) ELSE FALSE END)`;return l&&typeof b=="string"?S(`jsonb_typeof(e) = 'string' AND LOWER(e #>> '{}') = LOWER(${F(n,b)})`):l&&Array.isArray(b)?S(`LOWER(e::text)::jsonb = ${m(b)}`):typeof b=="object"&&b!==null?S(`e = ${a(b)}`):`(${i} = 'array' AND ${o} @> ${a([b])})`},w=b=>typeof b=="string"?`(${c(`%${$e(b)}%`)} OR ${g(b)})`:g(b);switch(e.operator){case h.equals:return r===null?`${o} IS NULL`:y(r);case h.notEquals:return r===null?`${o} IS NOT NULL`:d(y(r));case h.in:case h.notIn:{let{values:b,hasNull:S}=Qe(r),v=b.length?`(${b.map(y).join(" OR ")})`:"FALSE";return e.operator===h.in?S?`(${v} OR ${o} IS NULL)`:v:S?`(NOT ${v} AND ${o} IS NOT NULL)`:d(v)}case h.between:case h.notBetween:{let[b,S]=r,v=`(${i} = jsonb_typeof(${a(b)}) AND ${o} BETWEEN ${a(b)} AND ${a(S)})`;return e.operator===h.between?v:d(v)}case h.contains:return w(r);case h.notContains:return d(w(r));case h.startsWith:return c(`${$e(String(r))}%`);case h.endsWith:return c(`%${$e(String(r))}`);case h.notStartsWith:return d(c(`${$e(String(r))}%`));case h.notEndsWith:return d(c(`%${$e(String(r))}`));case h.matches:case h.notMatches:{let{source:b,caseInsensitive:S}=br(r),v=`(${i} = 'string' AND ${s} ~${S?"*":""} ${F(n,Bo(b))})`;return e.operator===h.matches?v:d(v)}}let R=go(e.operator,"field")?.symbol;if(R)return `(${i} = jsonb_typeof(${a(r)}) AND ${o} ${R} ${a(r)})`;throw new Error(`Operator '${e.operator}' is not supported on a Json value in SQL`)};var jm=e=>typeof e=="object"&&jr(e)!==null,si=({sql:e,shape:t},r)=>{if(t!=="json-path"&&t!=="text")return `to_timestamp(EXTRACT(EPOCH FROM ${e}))`;let n=F(r,ut(r).timeZone);return `(CASE WHEN btrim(${e}) ~ '^-?[0-9]+(\\.[0-9]+)?$' THEN to_timestamp(btrim(${e})::numeric / 1000) WHEN ${e} ~* '[0-9]{2}:[0-9]{2}(:[0-9]{2}(\\.[0-9]+)?)?\\s*(z|[+-][0-9]{2}(:?[0-9]{2})?)\\s*$' OR ${e} ~* '\\m(gmt|utc)\\M' THEN (${e})::timestamptz ELSE (${e})::timestamp AT TIME ZONE ${n} END)`},na=e=>Object.values(e).some(jm),NE=(e,t,r)=>{let n=Dr(r),o=n?"int":"double precision";if(typeof e=="number"||!jm(e)){let a=Ka(e,sn(t),r);return `${F(t,a)}::${o}`}let i=ve(e,t).sql;return `(CASE WHEN ${n?`${i} >= 0 AND ${i} = trunc(${i})`:`${i} >= 0`} THEN ${i} END)::${o}`},AE=(e,t)=>`make_interval(${Hd.flatMap(n=>{let o=Object.keys(e).filter(i=>e[i]!==void 0&&et[i].interval===n).map(i=>{let s=NE(e[i],t,i),{factor:a}=et[i];return a===1?s:`${a} * ${s}`});return o.length?[`${n} => ${o.join(" + ")}`]:[]}).join(", ")})`,ai=(e,t,r,n)=>{let o=ut(n).timeZone;if(e.type==="value"&&!na(t)){let l=Wr(t,sn(n));return e.value===null||e.value===void 0||l===null?tr:{type:"value",value:mr(Nt(e.value),l,r,o).toDate()}}let i=e.type==="column"?e.computed?e.sql:si(e,n):`${F(n,e.value??null)}::timestamptz`,s=F(n,o);return {type:"column",computed:true,sql:`(((${i} AT TIME ZONE ${s}) ${r===1?"+":"-"} ${AE(t,n)}) AT TIME ZONE ${s})`}};var Kl=(e,t,r)=>{let n=ve(t,r);if(e.type==="value"&&n.type==="value"){let i=Kr(n.value);return i===null?tr:{type:"value",value:Ur(e.value,i)}}let o=(i,s)=>i.type==="column"?`(${i.sql})::double precision`:`${F(r,s(i.value)??null)}::double precision`;return {type:"column",computed:true,sql:`(${o(e,i=>i)} + ${o(n,Kr)})`}},Vm=(e,t,r)=>{if(_t(e))return tr;let n=ve(t,r);if(n.type==="column")throw new Error(`A row path on a date offset ('${t.path}') is check-only; evaluate with check()`);let o=Yn(n.value);return o===null?tr:ai(e,...o,r)};var Im,qm=e=>{Im=e;},kr=(e,t)=>Im(e,t);var ia=(e,t,r)=>{let n=as(e);if(n)throw n;let o=r===void 0?er(e.field,t):{sql:r,shape:"scalar"};if(o.shape==="relation"&&!Qt(e))throw ur(e.field);let i=r===void 0,s=Oe(e)&&t.map&&t.currentModel?(M(e.path)??{path:e.path}).path:null;if(s!==null){let S=no(te(e.field,t.map,t.currentModel),te(s,t.map,t.currentModel),e.operator);if(S)throw V("toSql",`Comparing '${e.field}' with the column '${e.path}'`,S)}if(o.shape==="enum"&&!fr.includes(e.operator)){let S=Wm(e,t),v=te(e.field,t.map,t.currentModel),E=S!==oa&&v&&!Ee(e,S)?Bs(e,S,v,t.map):null;if(E){let q=`${o.sql}::text = ANY(${F(t,E.values)})`;return E.matchesNull?Fe(o.sql,q):q}}let a=o.shape==="enum"&&!fr.includes(e.operator)&&s===null?{...o,sql:`${o.sql}::text`}:o;if((o.shape==="json"||o.shape==="json-path")&&!fr.includes(e.operator)){let S=Wm(e,t);if(S===oa)throw new Error(`The Json value '${e.field}' compares against an operand known when compiling, not one read per row.`);return Fm(e,Mt(e.field,t,{jsonb:true}),S,t)}let f=S=>{if(S.type==="column"&&!S.computed&&(S.shape==="json"||S.shape==="json-path"))throw V("toSql",`'${e.field}' compared with a Json value read per row`,"SQL would compare its text")};if(He.includes(e.operator)){let S=Gm(e,t);return S?.forEach(f),ii(a.sql,S,W.includes(e.operator),t,i)}let p=Um(e,t);if(f(p),p.type==="column"&&Kt(e.operator,"field")==="string"&&!Jr(o.shape)&&o.shape!=="list")throw V("toSql",`'${e.operator}' on '${e.field}'`,"it is not text");if(p.type==="column"&&p.computed&&o.shape==="text"&&r===void 0)throw V("toSql",`'${e.field}' against a value moved by an offset`,"an offset moves a number or a date");let d=a.sql,u=go(e.operator,"field");if(u)return ra(d,u.symbol,p,false,t);if(p.type==="value"&&Ee(e,p.value))return Dt(d,W.includes(e.operator),i);let m=p.type==="column"&&p.computed===true,y=oe(e.caseInsensitive)&&(p.type==="column"?!m&&Jr(o.shape)&&Jr(p.shape):xr(o.shape,p.value)),c=S=>y?`LOWER(${S})`:S,g=S=>y?Gr(S):S;if(o.shape==="list"&&p.type==="column"&&Rt.includes(e.operator)){if(te(e.field,t.map,t.currentModel)?.type!=="String"||!Jr(p.shape))throw V("toSql",`'${e.operator}' on the list '${e.field}' with a member read per row ('${e.path}')`,"Postgres matches a member of the list's own type only");let S=oe(e.caseInsensitive)&&Jr(p.shape)?`EXISTS (SELECT 1 FROM unnest(${d}) AS e WHERE LOWER(e) = LOWER(${p.sql}))`:`array_position(${d}, ${p.sql}) IS NOT NULL`;return e.operator===h.contains?`(${p.sql} IS NOT NULL AND ${S})`:`(${d} IS NULL OR (${p.sql} IS NOT NULL AND NOT ${S}))`}if(o.shape==="list"&&p.type==="value"){let S=oe(e.caseInsensitive)&&xr("text",p.value);if(Rt.includes(e.operator)){let v=F(t,p.value),E=S?`EXISTS (SELECT 1 FROM unnest(${d}) AS e WHERE LOWER(e) = LOWER(${v}))`:`array_position(${d}, ${v}) IS NOT NULL`;return e.operator===h.contains?E:`NOT ${E}`}if(dr.includes(e.operator)&&Array.isArray(p.value))return kr(bs(e,p.value),t);if(PE(e.operator))throw new Error(`'${e.operator}' does not apply to the list '${e.field}'; test its members with contains.`);if(S&&xt.includes(e.operator)&&Array.isArray(p.value)){let v=F(t,Gr(p.value)),E=`(${d} IS NOT NULL AND ARRAY(SELECT LOWER(e) FROM unnest(${d}) AS e) = ${v})`;return e.operator===h.equals?E:Fe(d,`NOT ${E}`)}}let w=p.type==="value"?p.value:void 0,R=p.type==="column"?p.sql:void 0;if(R!==void 0&&(dr.includes(e.operator)||["pattern","string"].includes(Kt(e.operator,"field"))))throw V("toSql",`'${e.operator}' against an operand read per row ('${e.path}')`);let b=S=>i?Fe(d,S):S;switch(e.operator){case h.equals:return m?`${d} = ${R}`:R!==void 0?`${c(d)} IS NOT DISTINCT FROM ${c(R)}`:w===null?`${d} IS NULL`:`${c(d)} = ${c(F(t,w))}`;case h.notEquals:return m?b(`${d} <> ${R}`):R!==void 0?`${c(d)} IS DISTINCT FROM ${c(R)}`:w===null?`${d} IS NOT NULL`:b(`${c(d)} <> ${c(F(t,w))}`);case h.in:{let{values:S,hasNull:v}=Qe(w);if(!S.length)return v?`${d} IS NULL`:"FALSE";let E=`${c(d)} = ANY(${F(t,g(S))})`;return v?b(E):E}case h.notIn:{let{values:S,hasNull:v}=Qe(w);if(!S.length)return v?`${d} IS NOT NULL`:"TRUE";let E=`${c(d)} <> ALL(${F(t,g(S))})`;return v?`(${E} AND ${d} IS NOT NULL)`:b(E)}case h.contains:return `${c(d)} LIKE ${c(F(t,`%${$e(String(w))}%`))}`;case h.notContains:return b(`${c(d)} NOT LIKE ${c(F(t,`%${$e(String(w))}%`))}`);case h.startsWith:return `${c(d)} LIKE ${c(F(t,`${$e(String(w))}%`))}`;case h.endsWith:return `${c(d)} LIKE ${c(F(t,`%${$e(String(w))}`))}`;case h.notStartsWith:return b(`${c(d)} NOT LIKE ${c(F(t,`${$e(String(w))}%`))}`);case h.notEndsWith:return b(`${c(d)} NOT LIKE ${c(F(t,`%${$e(String(w))}`))}`);case h.matches:return Bm(d,w,false,t);case h.notMatches:return b(Bm(d,w,true,t));case h.isEmpty:case h.notEmpty:return Gl(e.field,o,e.operator===h.isEmpty,t,xs(e,t.map,t.currentModel));case h.exists:return `${d} IS NOT NULL`;case h.notExists:return `${d} IS NULL`;default:throw new Error(`Unknown operator: ${e.operator}`)}},Um=(e,t)=>{if(fr.includes(e.operator))return {type:"value",value:void 0};let r=Km(e,ve(e,t),t);return e.offset===void 0?r:Kl(r,e.offset,t)},Km=(e,t,r)=>t.type==="column"?t:{type:"value",value:fo(e,t.value,Rr(e.field,r.map,r.currentModel),"toSql",()=>ut(r).timeZone)},Gm=(e,t)=>{let r=Km(e,ve(e,t),t),n=r.type==="value"?r.value:void 0;if(n==null)return null;let o=rt(n,e.operator);return o.some(i=>i!=null&&!ye(i))&&Zn(n,e.operator),Je(o).map(i=>{let s={type:"value",value:i};return e.offset===void 0?s:Kl(s,e.offset,t)})},Bm=(e,t,r,n)=>{if(typeof t!="string"&&!(t instanceof RegExp))throw new Error("matches requires a string or RegExp pattern");let{source:o,caseInsensitive:i}=br(t);return `${e} ${r?"!":""}~${i?"*":""} ${F(n,Bo(o))}`},oa=Symbol("not known"),Wm=(e,t)=>{if(He.includes(e.operator)){let n=Gm(e,t);return n?n.every(o=>o.type==="value")?n.map(o=>o.value):oa:null}let r=Um(e,t);return r.type==="value"?r.value:oa},Gl=(e,t,r,n,o)=>{let{sql:i,shape:s}=t;if(s==="list")return r?`(${i} IS NULL OR cardinality(${i}) = 0)`:`cardinality(${i}) > 0`;if(s==="json"||s==="json-path"){let a=Mt(e,n,{jsonb:true}),l=["'null'::jsonb",...o?[`'""'::jsonb`]:[],"'[]'::jsonb"].join(", ");return r?`(${a} IS NULL OR ${a} IN (${l}))`:`${a} NOT IN (${l})`}return o?r?`(${i} IS NULL OR ${i} = '')`:`(${i} IS NOT NULL AND ${i} <> '')`:r?`${i} IS NULL`:`${i} IS NOT NULL`},PE=e=>Kt(e,"field")==="string"&&!Rt.includes(e);var zm=(e,t)=>{if(Ae(e))throw $t("toSql");if(e.condition)throw new Error("Aggregate condition filtering is not yet supported by toSql(). Use check() for in-memory evaluation or toPrisma() for database queries.");let r=kE(e,t);return ia(e,t,r)},kE=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!Ot.includes(r))throw cr(r);let o=r==="sum"?"SUM":"AVG",i=Ke({field:e.field},t.map,t.currentModel);if(i==="relation"||te(e.field,t.map,t.currentModel)?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 toSql() cannot aggregate relation lists. Use toPrisma() instead.`);if(n?.includes("."))throw new Error(`aggregate.field '${n}' contains a nested path \u2014 toSql() only supports flat field names. Use check() for nested paths.`);let s=i==="list",a=Mt(e.field,t,{jsonb:!s}),l=s?a:`(CASE WHEN jsonb_typeof(${a}) = 'array' THEN ${a} END)`;if(s){if(n)throw new Error("aggregate.field is not supported for native array types. Use a JSONB column for object arrays.");return `(SELECT ${`COALESCE(${o}(elem), 0)`} FROM unnest(${l}) AS elem)`}if(n){let d=`(elem->>${wl(n)})::numeric`;return `(SELECT ${`COALESCE(${o}(${d}), 0)`} FROM jsonb_array_elements(${l}) AS elem)`}return `(SELECT ${`COALESCE(${o}(elem::numeric), 0)`} FROM jsonb_array_elements_text(${l}) AS elem)`};var Hm=(e,t)=>{if(Ae(e))throw $t("toSql");if(!e.field)throw is("toSql");if(Ke({field:e.field},t.map,t.currentModel)==="relation"||te(e.field,t.map,t.currentModel)?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 relation arrays are not supported in SQL; use toPrisma().`);switch(e.arrayOperator){case x.empty:case x.notEmpty:{let n=er(e.field,t),o=e.arrayOperator===x.empty;if(n.shape==="list")return Gl(e.field,n,o,t,false);let i=Mt(e.field,t,{jsonb:true});return `(CASE WHEN jsonb_typeof(${i}) = 'array' THEN jsonb_array_length(${i}) ${o?"=":">"} 0 ELSE ${o?"TRUE":"FALSE"} END)`}case x.all:case x.any:case x.none:case x.atLeast:case x.atMost:case x.exactly:throw new Error(`Array operator '${e.arrayOperator}' with conditions is not supported in SQL. Use application-level filtering for complex array operations.`);default:throw de(e.arrayOperator,"array")}};var TE=(e,t)=>e.type==="column"&&!e.computed?{type:"column",sql:si(e,t),computed:true}:e,Jm=e=>e===void 0||e==="instant"||e==="text"||e==="json-path"||e==="unknown",Qm=e=>V("toSql",`A date rule on '${e}'`,"it is not a date column"),Zm=(e,t,r)=>{let n=t.some(i=>i.type==="column"),o=e.shape==="json-path"||e.shape==="text";return n||o?{lhs:si(e,r),ends:t.map(i=>TE(i,r))}:{lhs:e.sql,ends:t}},Ym=(e,t)=>{let r=er(e.field,t);if(!Jm(r.shape))throw Qm(e.field);let n=ve(e,t);if(n.type==="column"&&!Jm(n.shape))throw Qm(String(e.path??e.field));if(!_t(n)){let s=e.offset===void 0?void 0:ve(e.offset,t),a=zt(n.type==="value"?n.value:void 0,s?.type==="value"?s.value:void 0);if(a)throw a}let o=go(e.dateOperator,"date");if(o){let{lhs:s,ends:a}=Zm(r,[LE(e,t)],t);return ra(s,o.symbol,a[0],o.negated,t)}let i=(s,a)=>{if(!s)return ii(r.sql,null,a,t);let{lhs:l,ends:f}=Zm(r,s,t);return ii(l,f,a,t)};switch(e.dateOperator){case N.within:case N.notWithin:return i(ME(e,t),W.includes(e.dateOperator));case N.between:case N.notBetween:return i(_E(e,t),W.includes(e.dateOperator));case N.dayIn:case N.dayNotIn:{let s=e.dateOperator===N.dayNotIn,a=ve(e,t);if(a.type==="column")throw V("toSql",`A weekday list read from the row ('${e.path}')`);let l=za(a.value);if(l===null)return Dt(r.sql,s);let f=F(t,ut(t).timeZone),p=F(t,l),d=`EXTRACT(DOW FROM (${si(r,t)} AT TIME ZONE ${f}))`;return e.dateOperator===N.dayIn?`${d} = ANY(${p})`:Fe(r.sql,`${d} <> ALL(${p})`)}default:throw de(e.dateOperator,"date")}},Xm=e=>({type:"value",value:Mo(ut(e)).toDate()}),CE=(e,t,r)=>{let n=Re(e);if(n&&na(n[0]))return ai(Xm(r),...n,r);let o=vt(e,sn(r));return o===null?tr:{type:"value",value:zn(o,t,ut(r)).toDate()}},eg=(e,t,r)=>e==null?tr:ee(e)?CE(e,t,r):{type:"value",value:hs(e,ut(r).timeZone)},tg=(e,t,r)=>t.offset===void 0?e:Vm(e,t.offset,r),LE=(e,t)=>{let r=ve(e,t),n=r.type==="column"?r:eg(r.value,e.dateOperator,t);return tg(n,e,t)},ME=(e,t)=>{let r=ve(e,t);if(_t(r))return null;if(r.type==="column"||!ee(r.value))throw tt(e.dateOperator);let n=Re(r.value);if(n&&na(n[0])){let s=Xm(t),a=ai(s,...n,t);return n[1]===-1?[a,s]:[s,a]}let o=vt(r.value,sn(t));if(o===null)return null;let i=Hn(o,ut(t));return [{type:"value",value:i[0].toDate()},{type:"value",value:i[1].toDate()}]},_E=(e,t)=>{let r=ve(e,t);if(_t(r))return null;let n=r.type==="value"?r.value:void 0,o=rt(n,e.dateOperator).map(l=>eg(l,e.dateOperator,t));if(o.some(_t))return null;let[i,s]=o;return (i.type==="value"&&s.type==="value"?Je([i.value,s.value]).map(l=>({type:"value",value:l})):o).map(l=>tg(l,e,t))};var rg=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(n=>kr(n,t)).join(" AND ")})`,ng=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(n=>kr(n,t)).join(" OR ")})`,og=(e,t)=>{if(At(e,t.map,t.currentModel))return "TRUE";let r=kr(e.if,t),n=kr(e.then,t);if(e.else!==void 0){let o=kr(e.else,t);return `(((${r}) IS NOT TRUE OR ${n}) AND ((${r}) IS TRUE OR ${o}))`}return `((${r}) IS NOT TRUE OR ${n})`};var li=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if(Ki(e,"toSql"),"field"in e&&typeof e.field=="string"&&t.map&&t.currentModel&&Or(e.field,t.map,t.currentModel))return "TRUE";let r=le(e);(r==="field"||r==="date")&&Es(e.field,t.map,t.currentModel);let n=e;switch(r){case "all":return rg(n,t);case "any":return ng(n,t);case "if":return og(n,t);case "array":return Hm(n,t);case "aggregate":return zm(n,t);case "date":return Ym(n,t);case "field":return ia(n,t);default:throw Et()}};qm(li);var zl=e=>{let t=Pe(e?.map,e?.mapName,"toSql"),r=!!(t&&e?.model),n=e?.alias??(r?"t0":void 0);return {params:[],paramIndex:0,dateConfig:{now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},map:t,currentModel:e?.model,currentAlias:n,joinCounter:r?{n:0}:void 0,joins:r?[]:void 0,joinRegistry:r?new Map:void 0}},DE=(e,t)=>qs(e,t,"toSql",FE),FE=(e,t)=>{let r=zl(t);return {sql:li(e,r),params:r.params,joins:r.joins??[]}};var ig=(e,t)=>{let[r,...n]=t,o=e[r];if(n.length===0){o===void 0&&(e[r]=true);return}let i=o!==void 0&&o!==true?o.select:{};ig(i,n),e[r]={select:i};},jE=(e,t,r,n,o,i,s,a,l,f)=>{let p=zs(`source '${o}' at '${t}'`,()=>ti(a,{...l,map:e,mapName:r,model:n})),d=p.steps.at(-1),u=d.where,m=p.steps.length>1||(d.refs?.length??0)>0,y=Pe(e,r,"toPrisma"),c=A=>f!==void 0&&ie(A,y,n).kind==="bridge",g=i!==void 0&&!c(i)?i:void 0,w=(s??[]).map(A=>c(A)?void 0:A),R=A=>{let I=ie(A,y,n);return I.kind==="json-path"?A.split(".").slice(0,I.stopIndex).join("."):A},b=f===void 0?[]:Ys(e,r,n,[...De(f),...i!==void 0&&g===void 0?[i]:[],...(s??[]).filter(c)].map(R)).filter(A=>A!==o),S=g?.includes(".")?g:void 0,v=[...w.filter(A=>A!==void 0),...S?[S]:[],...b],E={[o]:true,...g&&!S?{[g]:true}:{}};for(let A of v)ig(E,A.split("."));let q={model:n,...s||S||f!==void 0?{}:{distinct:g?[o,g]:[o]},select:E,where:u,...m?{steps:p.steps}:{}},ce;try{for(let Se of b){let Ce=ie(Se,y,n);if(!(Ce.kind==="direct"&&!Ce.hops.length&&Ce.entry.kind!=="object"))throw new Error(Ce.kind==="direct"?`the re-check reads '${Se}' through a relation, which flat SQL rows can't hold \u2014 run the Prisma query`:`the re-check reads '${Se}', which is not a column of ${n} \u2014 run the Prisma query`)}let A=zl({...l,map:e,mapName:r,model:n,alias:"t0"}),I=li(a,A),B=S?Mt(S,A):void 0,Tr=w.map((Se,Ce)=>Se===void 0?void 0:`${Mt(Se,A)} AS ${se(`__group_${Ce}`)}`),wo=A.joins??[],Cr=wo.length?` ${wo.join(" ")}`:"",me=I?.trim()?` WHERE ${I}`:"",ct=se("t0"),an=[`${ct}.${se(o)}`,...B?[`${B} AS ${se("__label")}`]:g?[`${ct}.${se(g)}`]:[],...Tr.filter(Se=>Se!==void 0),...b.map(Se=>`${ct}.${se(Se)}`)].join(", "),ne=T(O(e.maps,r),n)?.dbName??n;ce={sql:`SELECT DISTINCT ${an} FROM ${se(ne)} AS ${ct}${Cr}${me}`,params:A.params};}catch(A){ce={sql:null,params:[],error:A instanceof Error?A.message:String(A)};}return {prisma:q,sql:ce}},sg=(e,t={})=>{let{lens:r}=D(e);return am(e).map(({path:n,visit:o,field:i,label:s,groupBy:a,where:l,recheck:f})=>{let p=l,{prisma:d,sql:u}=jE(r,n,o.mapName,o.model,i,s,a,p,t,f);return {path:n,mapName:o.mapName,model:o.model,field:i,...s!==void 0?{label:s}:{},...a!==void 0?{groupBy:a}:{},composedWhere:p,prisma:d,sql:u,...f!==void 0?{recheck:f}:{}}})};var sa=(e,t)=>{let r=D(e);return rn(r,Tt(r),t).resolution};var pi=class extends Error{constructor(r){super(`inferValueType: ${r.path}: ${r.message}`);this.issue=r;}issue},Y=(e,t,r)=>{throw new pi({path:e,code:t,message:r})};var aa=(e,t)=>{let r=M(e);return r?(r.depth>1&&Y(t,"scope_out_of_bounds",`'${e}' reaches past the row a value expression reads`),r.path):e},la=(e,t)=>{if(!e)throw new C(`inferValueType needs a lens to type ${t}`);return e},fi=(e,t,r)=>{let n=sa(e,t);if(n.outcome!=="resolved")return Y(r,"unresolved_path",`'${t}' does not resolve through the lens (${n.outcome})`);let o=n.hops.slice(0,-1).find(i=>L(i.entry)&&i.entry.isList);return {entry:n.terminal.entry,viaList:o?o.field:null,json:n.jsonSubPath.length>0||n.terminal.entry.type===P.Json}},di=e=>e.json?P.Json:Ge({...e.entry,isList:false})??null;var fa={kind:null,isList:false,nullable:true},VE={kind:null,isList:false,nullable:false},pa=e=>e!==null&&X.includes(e),ag=e=>`${e.kind??"null"}${e.isList?"[]":""}`,da=(e,t,r)=>{let n=e.nullable||t.nullable;if(e.kind===null&&e.isList===t.isList)return {...t,nullable:n};if(t.kind===null&&e.isList===t.isList)return {...e,nullable:n};if(e.kind===null&&!e.isList)return {...t,nullable:true};if(t.kind===null&&!t.isList)return {...e,nullable:true};if(e.isList===t.isList){if(e.kind===t.kind)return {...e,nullable:n};if(pa(e.kind)&&pa(t.kind))return {kind:e.kind===P.Decimal||t.kind===P.Decimal?P.Decimal:P.Float,isList:e.isList,nullable:n}}return Y(r,"value_type_mismatch",`the values here are ${ag(e)} and ${ag(t)}`)},ua=(e,t)=>({...e.reduce((r,n)=>da(r,n,t),VE),isList:true});var IE={String:["String","Boolean","DateTime",...X],DateTime:["DateTime","String",...X],Boolean:["Boolean","String"],Enum:["String"],...Object.fromEntries(X.map(e=>[e,["String","DateTime",...X]]))},qE=(e,t,r)=>{e===null||e===t||IE[e]?.includes(t)||Y(r,"coerce_kind_mismatch",`${e} values can't be read as ${t}`);},lg=(e,t,r)=>{let n=aa(t.field,`${r}.field`),o=fi(e,n,`${r}.field`);return (o.viaList||o.entry.isList!==true)&&Y(`${r}.field`,"aggregate_needs_list",`'${t.field}' is not a list; an aggregate reads a list`),{field:n,list:o}},BE=(e,t,r)=>{let{field:n,list:o}=lg(e,t,r),i=t.aggregate.field;if(!L(o.entry))return i!==void 0&&Y(`${r}.aggregate.field`,"invalid_aggregate_field",`'${t.field}' holds values, not rows`),di(o);if(i===void 0)return Y(`${r}.aggregate.field`,"aggregate_field_required",`${t.aggregate.mode} over rows names the field it reads`);let s=fi(e,`${n}.${i}`,`${r}.aggregate.field`);return (L(s.entry)||s.entry.isList)&&Y(`${r}.aggregate.field`,"invalid_aggregate_field",`'${i}' is not one value per row`),di(s)},pg=(e,t,r)=>{let n=t.aggregate.mode;if(_n[n].result==="count")return e&&lg(e,t,r),{kind:P.Int,isList:false,nullable:false};let o=BE(la(e,`${n} over '${t.field}'`),t,r);t.coerceType!==void 0&&qE(o,t.coerceType,`${r}.coerceType`);let i=t.coerceType??o,s=`${r}.aggregate.field`;return n==="sum"||n==="avg"?(pa(i)||Y(s,"aggregate_kind_mismatch",`${n} adds numbers, not ${i??"untyped"} values`),{kind:n==="sum"||i===P.Decimal?i:P.Float,isList:false,nullable:n==="avg"}):n==="distinct"?((i===null||!Ld.includes(i))&&Y(s,"aggregate_kind_mismatch",`distinct lists strings, enums, dates, booleans and numbers, not ${i??"untyped"} values`),{kind:i,isList:true,nullable:false}):((i===null||!Cd.includes(i))&&Y(s,"aggregate_kind_mismatch",`${n} orders numbers and dates, not ${i??"untyped"} values; read strings with coerceType`),{kind:i,isList:false,nullable:true})};var ca=e=>!Array.isArray(e)&&e.distinct===true,ma=(e,t=false)=>{let r=new Set,n=new Set,o=new Set;return e.filter(i=>{let[s,a]=i instanceof Date?[n,i.getTime()]:typeof i=="object"&&i!==null?[o,JSON.stringify(i)]:[r,t&&typeof i=="string"?i.toLowerCase():i];return s.has(a)?false:(s.add(a),true)})};var ga=(e,t)=>e===null?fa:typeof e=="number"?{kind:Number.isInteger(e)?P.Int:P.Float,isList:false,nullable:false}:typeof e=="bigint"?{kind:P.BigInt,isList:false,nullable:false}:typeof e=="string"?{kind:P.String,isList:false,nullable:false}:typeof e=="boolean"?{kind:P.Boolean,isList:false,nullable:false}:e instanceof Date?{kind:P.DateTime,isList:false,nullable:false}:Array.isArray(e)?ua(e.map((r,n)=>{let o=`${t}[${n}]`;return Array.isArray(r)&&Y(o,"nested_list","a list's items are single values"),ga(r,o)}),t):{kind:P.Json,isList:false,nullable:false};var fg=(e,t,r)=>{let n=fi(e,aa(t,r),r);return n.viaList&&Y(r,"to_many_path",`'${t}' reads through the to-many relation '${n.viaList}'; aggregate its rows`),L(n.entry)&&Y(r,"relation_not_value",`'${t}' names a relation's rows, not a value; aggregate them`),{kind:di(n),isList:n.entry.isList===true,nullable:n.json||n.entry.isRequired!==true}};var ho=e=>re(e)&&"aggregate"in e&&["operator","value","path","bind"].some(t=>t in e);var dg={source:["value","path","bind","bindOptional"],if:["if","then","else"],aggregate:["field","aggregate","condition","filter","orderBy","take","skip","coerceType","caseInsensitive"],list:["list","distinct"]},Hl=(e,t)=>e.map(r=>({...r,path:r.path.startsWith("$")?`${t}${r.path.slice(1)}`:`${t}.${r.path}`})),ha=(e,t,r)=>Object.keys(e).filter(n=>!dg[t].includes(n)).map(n=>({path:`${r}.${n}`,code:"unknown_key",message:`a ${t==="source"?"value source":`${t} value`} takes ${dg[t].join(", ")}, not '${n}'`})),WE=(e,t,r)=>{if(r)return [{path:t,code:"nested_list",message:"a list's items are single values"}];let n=qr(e).flatMap((s,a)=>ya(s,`${t}[${a}]`,true));if(Array.isArray(e))return n;let o=e,i=ha(o,"list",t);return Array.isArray(o.list)||i.push({path:`${t}.list`,code:"invalid_list",message:"list must be an array"}),o.distinct!==void 0&&typeof o.distinct!="boolean"&&i.push({path:`${t}.distinct`,code:"invalid_distinct",message:"distinct must be a boolean"}),[...i,...n]},UE=(e,t,r)=>{let n=ha(e,"if",t);return e.if===void 0?n.push({path:`${t}.if`,code:"condition_required",message:"if / then takes an if"}):n.push(...Hl($r(e.if).errors,`${t}.if`)),e.then===void 0?n.push({path:`${t}.then`,code:"value_required",message:"if / then takes a then"}):n.push(...ya(e.then,`${t}.then`,r)),e.else!==void 0&&n.push(...ya(e.else,`${t}.else`,r)),n},KE=(e,t)=>[...ha(e,"aggregate",t),...e.field===""?[{path:`${t}.field`,code:"field_required",message:"an aggregate value reads a list field"}]:[],...Hl(Zu(e).errors,t)],ya=(e,t,r)=>{let n=e;switch(hr(e)){case "literal":return [];case "list":return WE(e,t,r);case "if":return UE(n,t,r);case "aggregate":return KE(n,t);case "source":return [...ha(n,"source",t),...Hl(Yu(n).errors,t)];default:{let o=ho(n),i=o?Wn(t):Bn(t);return [{path:t,code:o?"unexpected_comparison":"invalid_value_expression",message:i.message.slice(t.length+2)}]}}},ui=e=>Ye(ya(e,"$",false)),wa=e=>en(ui(e),"Invalid value expression");var GE=(e,t,r)=>e.value!==void 0?ga(e.value,`${r}.value`):typeof e.bind=="string"?Y(r,"untyped_binding",`{ bind: '${e.bind}' } has no type until it is bound`):fg(la(t,`the path '${String(e.path)}'`),e.path,r),zE=(e,t,r,n)=>{let o=ba(e.then,t,`${r}.then`,n);return e.else===void 0?n?o:da(o,fa,r):da(o,ba(e.else,t,`${r}.else`,n),r)},HE=(e,t,r)=>{let n=ua(qr(e).map((o,i)=>{let s=`${r}[${i}]`,a=ba(o,t,s,true);return a.isList&&Y(s,"nested_list","a list's items are single values"),a}),r);return ca(e)&&n.kind===P.Json&&Y(`${r}.distinct`,"distinct_over_json","distinct drops repeated values, not Json"),n},ba=(e,t,r,n)=>{switch(hr(e)){case "literal":return ga(e,r);case "source":return GE(e,t,r);case "aggregate":return pg(t,e,r);case "if":return zE(e,t,r,n);case "list":return HE(e,t,r);default:return Y(r,"invalid_value_expression",Bn(r).message)}},Sa=(e,t)=>(wa(e),ba(e,t,"$",false));var ug=(e,t)=>{let r=ui(e).errors;if(r.length>0)return {type:null,paths:[],clockUnit:null,errors:r};let n=Ir(e),o=[...vr(n,t).errors],i=null;try{i=Sa(e,t);}catch(a){if(!(a instanceof pi))throw a;o.push(a.issue);}let s=null;try{s=qo(n);}catch(a){o.push({path:"$",code:"clock_unit_below_floor",message:a.message});}return {type:i,paths:De(n).sort(),clockUnit:s,errors:o}};var JE=15,QE=e=>e.replace(/^[-+]/,"").replace(/e.*$/i,"").replace(".","").replace(/^0+/,"").replace(/0+$/,"").length,Jl=e=>{let t=String(e),r=Number(t);if(!Number.isFinite(r))return e;if(QE(t)>JE)throw new RangeError(`${t} has more digits than a number holds exactly; json-rules reads a coerced Decimal as a number.`);return r},cg=(e,t)=>r=>{if(e===void 0)return r;if(e==="String"){if(r instanceof Date)return r.toISOString();if(typeof r=="object"&&r!==null)return String(r)}let o=(X.includes(e)||e==="DateTime")&&typeof r=="bigint"?Br(r):X.includes(e)&&typeof r=="object"&&r!==null&&!(r instanceof Date)?Jl(r):r,i=Jt(o,e,t);return e==="DateTime"&&typeof i=="number"?new Date(i):i};var ZE=(e,t)=>{if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return {value:e,key:e,kind:"number"};if(e instanceof Date&&!Number.isNaN(e.getTime()))return {value:e,key:e.getTime(),kind:"date"};if(typeof e=="object"&&e!==null){let r=Jl(e);if(typeof r=="number")return {value:e,key:r,kind:"number"}}throw new Error(`${t} must be a finite number or a valid date for min / max`)},YE=(e,t,r)=>{if(e.length===0)return null;let n=new Set(e.map(o=>o.kind));if(n.size>1)throw new Error(`${r} ${t} orders one kind of value, not ${[...n].join(" and ")}`);return e.reduce((o,i)=>(t==="max"?i.key>o.key:i.key<o.key)?i:o).value},mg=(e,t,r)=>{if(ho(e))throw Wn(r);if(!re(e.aggregate))throw new Error(`${r}.aggregate must be an object`);let{mode:n,field:o}=e.aggregate;if(!Yi(n))throw ps(n);if(typeof e.field!="string"||e.field==="")throw new Error(`${r}.field: an aggregate value reads a list field`);let i=Qa(e,t),s=e.coerceType==="DateTime"?Ht(t,l=>Be(l,t.scopes,t.bindings)).timeZone:qe,a=cg(e.coerceType,s);switch(n){case "count":return o===void 0?i.length:ro(i,e.field,o,()=>true).length;case "sum":return Rs(n,i,e.field,o);case "avg":return ro(i,e.field,o,()=>true).length===0?null:Rs(n,i,e.field,o);case "distinct":return ma(ro(i,e.field,o,a),oe(e.caseInsensitive));default:return YE(ro(i,e.field,o,(l,f)=>ZE(a(l),f)),n,e.field)}};var gg=(e,t,r)=>{if(e.if===void 0||e.then===void 0)throw new Error(`${r}: if / then takes both an if and a then`);return Nu(e.if,t)?{expr:e.then,path:`${r}.then`}:e.else===void 0?void 0:{expr:e.else,path:`${r}.else`}},XE=(e,t,r)=>{let n=gg(e,t,r);return n===void 0?null:Ra(n.expr,t,n.path)},e$=(e,t,r)=>{if(!Array.isArray(e)&&!Array.isArray(e.list))throw new Error(`${r}.list must be an array`);let n=qr(e).flatMap((o,i)=>{let s=`${r}[${i}]`,a=hr(o);if(a==="list")throw new Error(`${s}: a list's items are single values`);if(a!=="if")return [Ra(o,t,s)];let l=gg(o,t,s);return l===void 0?[]:[Ra(l.expr,t,l.path)]});return ca(e)?ma(n):n},Ra=(e,t,r)=>{switch(hr(e)){case "literal":return e;case "source":return Be(e,t.scopes,t.bindings);case "aggregate":return mg(e,t,r);case "if":return XE(e,t,r);case "list":return e$(e,t,r);default:throw ho(e)?Wn(r):Bn(r)}},yg=(e,t,r={})=>Ra(e,{...r,scopes:[t]},"$");var hg=e=>qo(Ir(e));/*! Bundled license information:
4
4
 
5
5
  lodash-es/lodash.js:
6
6
  (**
@@ -12,5 +12,5 @@ lodash-es/lodash.js:
12
12
  * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
13
13
  * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
14
14
  *)
15
- */export{Ki as ALL_KINDS,x as ArrayOperator,To as CLOCK_UNITS,zR as ConditionShape,N as DateOperator,P as FieldKind,T as LensRefusal,X as NUMERIC_KINDS,h as Operator,MR as RuleTarget,Qs as SourceOptionOrder,An as SqlDialect,C as UsageError,Pa as VALUE_AGGREGATE_MODES,Wt as ValueShape,Ze as andWhere,ec as assertValidFieldMaps,Zs as assertValidNarrowing,DO as assertValidRule,ma as assertValidValue,hc as bindLens,ja as bindRule,ye as check,ul as clampLens,Vo as clockUnit,Oc as coerceRule,um as composeLens,xc as createLens,Ec as describeRule,$c as describeRuleSources,rg as describeValue,Xe as engineGlobals,sg as evaluateValue,Bc as executePrismaPlan,FR as getAggregateOperators,DR as getArrayOperators,HR as getConditionShapeKeys,pt as getLensRoot,_R as getOperatorsForKind,Ut as getValueShape,Eu as indexBridges,ya as inferValueType,Jc as lensVisit,jo as listBindings,ZR as listFields,gc as listLensBindings,st as matchAll,At as matchNothing,sm as materializeSourceQuery,im as materializeSources,ao as narrowRule,K as orWhere,Su as orderRecords,M as parseScopeRef,so as prefixConditionFields,dm as projectLens,om as projectRows,fm as readLensValue,Ge as readScopeRef,CR as registerEngineGlobals,Ss as stitchFieldMaps,cm as storeLens,rm as toLensSelect,$m as toLensWhereSql,Yo as toPrisma,Qm as toSourceQueries,OE as toSql,bm as toWhereSql,Za as validateFieldMaps,Fl as validateNarrowing,Er as validateRule,$r as validateRuleInLens,pi as validateValue,ag as valueClockUnit,ra as walkLensPath};//# sourceMappingURL=index.js.map
15
+ */export{Hi as ALL_KINDS,x as ArrayOperator,Co as CLOCK_UNITS,nO as ConditionShape,N as DateOperator,P as FieldKind,k as LensRefusal,X as NUMERIC_KINDS,h as Operator,UR as RuleTarget,ea as SourceOptionOrder,kn as SqlDialect,C as UsageError,La as VALUE_AGGREGATE_MODES,Ut as ValueShape,ke as andWhere,sc as assertValidFieldMaps,ta as assertValidNarrowing,GO as assertValidRule,wa as assertValidValue,xc as bindLens,Ba as bindRule,he as check,yl as clampLens,qo as clockUnit,Ac as coerceRule,Om as composeLens,Pc as createLens,kc as describeRule,Tc as describeRuleSources,ug as describeValue,Xe as engineGlobals,yg as evaluateValue,Yc as executePrismaPlan,zR as getAggregateOperators,GR as getArrayOperators,oO as getConditionShapeKeys,pt as getLensRoot,KR as getOperatorsForKind,Kt as getValueShape,ku as indexBridges,Sa as inferValueType,im as lensVisit,Io as listBindings,aO as listFields,Rc as listLensBindings,st as matchAll,Pt as matchNothing,ym as materializeSourceQuery,gm as materializeSources,po as narrowRule,K as orWhere,$u as orderRecords,M as parseScopeRef,lo as prefixConditionFields,Sm as projectLens,mm as projectRows,Rm as readLensValue,ze as readScopeRef,BR as registerEngineGlobals,Os as stitchFieldMaps,xm as storeLens,um as toLensSelect,_m as toLensWhereSql,ti as toPrisma,sg as toSourceQueries,DE as toSql,km as toWhereSql,tl as validateFieldMaps,Wl as validateNarrowing,$r as validateRule,vr as validateRuleInLens,ui as validateValue,hg as valueClockUnit,sa as walkLensPath};//# sourceMappingURL=index.js.map
16
16
  //# sourceMappingURL=index.js.map